egui/widgets/text_edit/
builder.rs

1use std::sync::Arc;
2
3use emath::{Rect, TSTransform};
4use epaint::{
5    StrokeKind,
6    text::{Galley, LayoutJob, cursor::CCursor},
7};
8
9use crate::{
10    Align, Align2, Color32, Context, CursorIcon, Event, EventFilter, FontSelection, Id, ImeEvent,
11    Key, KeyboardShortcut, Margin, Modifiers, NumExt as _, Response, Sense, Shape, TextBuffer,
12    TextStyle, TextWrapMode, Ui, Vec2, Widget, WidgetInfo, WidgetText, WidgetWithState, epaint,
13    os::OperatingSystem,
14    output::OutputEvent,
15    response, text_selection,
16    text_selection::{CCursorRange, text_cursor_state::cursor_rect, visuals::paint_text_selection},
17    vec2,
18};
19
20use super::{TextEditOutput, TextEditState};
21
22type LayouterFn<'t> = &'t mut dyn FnMut(&Ui, &dyn TextBuffer, f32) -> Arc<Galley>;
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::text_edit_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<LayouterFn<'t>>,
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::text_edit_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, buf: &dyn egui::TextBuffer, wrap_width: f32| {
267    ///     let mut layout_job: egui::text::LayoutJob = my_memoized_highlighter(buf.as_str());
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(
276        mut self,
277        layouter: &'t mut dyn FnMut(&Ui, &dyn TextBuffer, f32) -> Arc<Galley>,
278    ) -> Self {
279        self.layouter = Some(layouter);
280
281        self
282    }
283
284    /// Default is `true`. If set to `false` then you cannot interact with the text (neither edit or select it).
285    ///
286    /// Consider using [`Ui::add_enabled`] instead to also give the [`TextEdit`] a greyed out look.
287    #[inline]
288    pub fn interactive(mut self, interactive: bool) -> Self {
289        self.interactive = interactive;
290        self
291    }
292
293    /// Default is `true`. If set to `false` there will be no frame showing that this is editable text!
294    #[inline]
295    pub fn frame(mut self, frame: bool) -> Self {
296        self.frame = frame;
297        self
298    }
299
300    /// Set margin of text. Default is `Margin::symmetric(4.0, 2.0)`
301    #[inline]
302    pub fn margin(mut self, margin: impl Into<Margin>) -> Self {
303        self.margin = margin.into();
304        self
305    }
306
307    /// Set to 0.0 to keep as small as possible.
308    /// Set to [`f32::INFINITY`] to take up all available space (i.e. disable automatic word wrap).
309    #[inline]
310    pub fn desired_width(mut self, desired_width: f32) -> Self {
311        self.desired_width = Some(desired_width);
312        self
313    }
314
315    /// Set the number of rows to show by default.
316    /// The default for singleline text is `1`.
317    /// The default for multiline text is `4`.
318    #[inline]
319    pub fn desired_rows(mut self, desired_height_rows: usize) -> Self {
320        self.desired_height_rows = desired_height_rows;
321        self
322    }
323
324    /// When `false` (default), pressing TAB will move focus
325    /// to the next widget.
326    ///
327    /// When `true`, the widget will keep the focus and pressing TAB
328    /// will insert the `'\t'` character.
329    #[inline]
330    pub fn lock_focus(mut self, tab_will_indent: bool) -> Self {
331        self.event_filter.tab = tab_will_indent;
332        self
333    }
334
335    /// When `true` (default), the cursor will initially be placed at the end of the text.
336    ///
337    /// When `false`, the cursor will initially be placed at the beginning of the text.
338    #[inline]
339    pub fn cursor_at_end(mut self, b: bool) -> Self {
340        self.cursor_at_end = b;
341        self
342    }
343
344    /// When `true` (default), overflowing text will be clipped.
345    ///
346    /// When `false`, widget width will expand to make all text visible.
347    ///
348    /// This only works for singleline [`TextEdit`].
349    #[inline]
350    pub fn clip_text(mut self, b: bool) -> Self {
351        // always show everything in multiline
352        if !self.multiline {
353            self.clip_text = b;
354        }
355        self
356    }
357
358    /// Sets the limit for the amount of characters can be entered
359    ///
360    /// This only works for singleline [`TextEdit`]
361    #[inline]
362    pub fn char_limit(mut self, limit: usize) -> Self {
363        self.char_limit = limit;
364        self
365    }
366
367    /// Set the horizontal align of the inner text.
368    #[inline]
369    pub fn horizontal_align(mut self, align: Align) -> Self {
370        self.align.0[0] = align;
371        self
372    }
373
374    /// Set the vertical align of the inner text.
375    #[inline]
376    pub fn vertical_align(mut self, align: Align) -> Self {
377        self.align.0[1] = align;
378        self
379    }
380
381    /// Set the minimum size of the [`TextEdit`].
382    #[inline]
383    pub fn min_size(mut self, min_size: Vec2) -> Self {
384        self.min_size = min_size;
385        self
386    }
387
388    /// Set the return key combination.
389    ///
390    /// This combination will cause a newline on multiline,
391    /// whereas on singleline it will cause the widget to lose focus.
392    ///
393    /// This combination is optional and can be disabled by passing [`None`] into this function.
394    #[inline]
395    pub fn return_key(mut self, return_key: impl Into<Option<KeyboardShortcut>>) -> Self {
396        self.return_key = return_key.into();
397        self
398    }
399}
400
401// ----------------------------------------------------------------------------
402
403impl Widget for TextEdit<'_> {
404    fn ui(self, ui: &mut Ui) -> Response {
405        self.show(ui).response
406    }
407}
408
409impl TextEdit<'_> {
410    /// Show the [`TextEdit`], returning a rich [`TextEditOutput`].
411    ///
412    /// ```
413    /// # egui::__run_test_ui(|ui| {
414    /// # let mut my_string = String::new();
415    /// let output = egui::TextEdit::singleline(&mut my_string).show(ui);
416    /// if let Some(text_cursor_range) = output.cursor_range {
417    ///     use egui::TextBuffer as _;
418    ///     let selected_chars = text_cursor_range.as_sorted_char_range();
419    ///     let selected_text = my_string.char_range(selected_chars);
420    ///     ui.label("Selected text: ");
421    ///     ui.monospace(selected_text);
422    /// }
423    /// # });
424    /// ```
425    pub fn show(self, ui: &mut Ui) -> TextEditOutput {
426        let is_mutable = self.text.is_mutable();
427        let frame = self.frame;
428        let where_to_put_background = ui.painter().add(Shape::Noop);
429        let background_color = self
430            .background_color
431            .unwrap_or_else(|| ui.visuals().text_edit_bg_color());
432        let output = self.show_content(ui);
433
434        if frame {
435            let visuals = ui.style().interact(&output.response);
436            let frame_rect = output.response.rect.expand(visuals.expansion);
437            let shape = if is_mutable {
438                if output.response.has_focus() {
439                    epaint::RectShape::new(
440                        frame_rect,
441                        visuals.corner_radius,
442                        background_color,
443                        ui.visuals().selection.stroke,
444                        StrokeKind::Inside,
445                    )
446                } else {
447                    epaint::RectShape::new(
448                        frame_rect,
449                        visuals.corner_radius,
450                        background_color,
451                        visuals.bg_stroke, // TODO(emilk): we want to show something here, or a text-edit field doesn't "pop".
452                        StrokeKind::Inside,
453                    )
454                }
455            } else {
456                let visuals = &ui.style().visuals.widgets.inactive;
457                epaint::RectShape::stroke(
458                    frame_rect,
459                    visuals.corner_radius,
460                    visuals.bg_stroke, // TODO(emilk): we want to show something here, or a text-edit field doesn't "pop".
461                    StrokeKind::Inside,
462                )
463            };
464
465            ui.painter().set(where_to_put_background, shape);
466        }
467
468        output
469    }
470
471    fn show_content(self, ui: &mut Ui) -> TextEditOutput {
472        let TextEdit {
473            text,
474            hint_text,
475            hint_text_font,
476            id,
477            id_salt,
478            font_selection,
479            text_color,
480            layouter,
481            password,
482            frame: _,
483            margin,
484            multiline,
485            interactive,
486            desired_width,
487            desired_height_rows,
488            event_filter,
489            cursor_at_end,
490            min_size,
491            align,
492            clip_text,
493            char_limit,
494            return_key,
495            background_color: _,
496        } = self;
497
498        let text_color = text_color
499            .or(ui.visuals().override_text_color)
500            // .unwrap_or_else(|| ui.style().interact(&response).text_color()); // too bright
501            .unwrap_or_else(|| ui.visuals().widgets.inactive.text_color());
502
503        let prev_text = text.as_str().to_owned();
504        let hint_text_str = hint_text.text().to_owned();
505
506        let font_id = font_selection.resolve(ui.style());
507        let row_height = ui.fonts(|f| f.row_height(&font_id));
508        const MIN_WIDTH: f32 = 24.0; // Never make a [`TextEdit`] more narrow than this.
509        let available_width = (ui.available_width() - margin.sum().x).at_least(MIN_WIDTH);
510        let desired_width = desired_width.unwrap_or_else(|| ui.spacing().text_edit_width);
511        let wrap_width = if ui.layout().horizontal_justify() {
512            available_width
513        } else {
514            desired_width.min(available_width)
515        };
516
517        let font_id_clone = font_id.clone();
518        let mut default_layouter = move |ui: &Ui, text: &dyn TextBuffer, wrap_width: f32| {
519            let text = mask_if_password(password, text.as_str());
520            let layout_job = if multiline {
521                LayoutJob::simple(text, font_id_clone.clone(), text_color, wrap_width)
522            } else {
523                LayoutJob::simple_singleline(text, font_id_clone.clone(), text_color)
524            };
525            ui.fonts(|f| f.layout_job(layout_job))
526        };
527
528        let layouter = layouter.unwrap_or(&mut default_layouter);
529
530        let mut galley = layouter(ui, text, wrap_width);
531
532        let desired_inner_width = if clip_text {
533            wrap_width // visual clipping with scroll in singleline input.
534        } else {
535            galley.size().x.max(wrap_width)
536        };
537        let desired_height = (desired_height_rows.at_least(1) as f32) * row_height;
538        let desired_inner_size = vec2(desired_inner_width, galley.size().y.max(desired_height));
539        let desired_outer_size = (desired_inner_size + margin.sum()).at_least(min_size);
540        let (auto_id, outer_rect) = ui.allocate_space(desired_outer_size);
541        let rect = outer_rect - margin; // inner rect (excluding frame/margin).
542
543        let id = id.unwrap_or_else(|| {
544            if let Some(id_salt) = id_salt {
545                ui.make_persistent_id(id_salt)
546            } else {
547                auto_id // Since we are only storing the cursor a persistent Id is not super important
548            }
549        });
550        let mut state = TextEditState::load(ui.ctx(), id).unwrap_or_default();
551
552        // On touch screens (e.g. mobile in `eframe` web), should
553        // dragging select text, or scroll the enclosing [`ScrollArea`] (if any)?
554        // Since currently copying selected text in not supported on `eframe` web,
555        // we prioritize touch-scrolling:
556        let allow_drag_to_select =
557            ui.input(|i| !i.has_touch_screen()) || ui.memory(|mem| mem.has_focus(id));
558
559        let sense = if interactive {
560            if allow_drag_to_select {
561                Sense::click_and_drag()
562            } else {
563                Sense::click()
564            }
565        } else {
566            Sense::hover()
567        };
568        let mut response = ui.interact(outer_rect, id, sense);
569        response.intrinsic_size = Some(Vec2::new(desired_width, desired_outer_size.y));
570
571        // Don't sent `OutputEvent::Clicked` when a user presses the space bar
572        response.flags -= response::Flags::FAKE_PRIMARY_CLICKED;
573        let text_clip_rect = rect;
574        let painter = ui.painter_at(text_clip_rect.expand(1.0)); // expand to avoid clipping cursor
575
576        if interactive {
577            if let Some(pointer_pos) = response.interact_pointer_pos() {
578                if response.hovered() && text.is_mutable() {
579                    ui.output_mut(|o| o.mutable_text_under_cursor = true);
580                }
581
582                // TODO(emilk): drag selected text to either move or clone (ctrl on windows, alt on mac)
583
584                let singleline_offset = vec2(state.singleline_offset, 0.0);
585                let cursor_at_pointer =
586                    galley.cursor_from_pos(pointer_pos - rect.min + singleline_offset);
587
588                if ui.visuals().text_cursor.preview
589                    && response.hovered()
590                    && ui.input(|i| i.pointer.is_moving())
591                {
592                    // text cursor preview:
593                    let cursor_rect = TSTransform::from_translation(rect.min.to_vec2())
594                        * cursor_rect(&galley, &cursor_at_pointer, row_height);
595                    text_selection::visuals::paint_cursor_end(&painter, ui.visuals(), cursor_rect);
596                }
597
598                let is_being_dragged = ui.ctx().is_being_dragged(response.id);
599                let did_interact = state.cursor.pointer_interaction(
600                    ui,
601                    &response,
602                    cursor_at_pointer,
603                    &galley,
604                    is_being_dragged,
605                );
606
607                if did_interact || response.clicked() {
608                    ui.memory_mut(|mem| mem.request_focus(response.id));
609
610                    state.last_interaction_time = ui.ctx().input(|i| i.time);
611                }
612            }
613        }
614
615        if interactive && response.hovered() {
616            ui.ctx().set_cursor_icon(CursorIcon::Text);
617        }
618
619        let mut cursor_range = None;
620        let prev_cursor_range = state.cursor.range(&galley);
621        if interactive && ui.memory(|mem| mem.has_focus(id)) {
622            ui.memory_mut(|mem| mem.set_focus_lock_filter(id, event_filter));
623
624            let default_cursor_range = if cursor_at_end {
625                CCursorRange::one(galley.end())
626            } else {
627                CCursorRange::default()
628            };
629
630            let (changed, new_cursor_range) = events(
631                ui,
632                &mut state,
633                text,
634                &mut galley,
635                layouter,
636                id,
637                wrap_width,
638                multiline,
639                password,
640                default_cursor_range,
641                char_limit,
642                event_filter,
643                return_key,
644            );
645
646            if changed {
647                response.mark_changed();
648            }
649            cursor_range = Some(new_cursor_range);
650        }
651
652        let mut galley_pos = align
653            .align_size_within_rect(galley.size(), rect)
654            .intersect(rect) // limit pos to the response rect area
655            .min;
656        let align_offset = rect.left() - galley_pos.x;
657
658        // Visual clipping for singleline text editor with text larger than width
659        if clip_text && align_offset == 0.0 {
660            let cursor_pos = match (cursor_range, ui.memory(|mem| mem.has_focus(id))) {
661                (Some(cursor_range), true) => galley.pos_from_cursor(cursor_range.primary).min.x,
662                _ => 0.0,
663            };
664
665            let mut offset_x = state.singleline_offset;
666            let visible_range = offset_x..=offset_x + desired_inner_size.x;
667
668            if !visible_range.contains(&cursor_pos) {
669                if cursor_pos < *visible_range.start() {
670                    offset_x = cursor_pos;
671                } else {
672                    offset_x = cursor_pos - desired_inner_size.x;
673                }
674            }
675
676            offset_x = offset_x
677                .at_most(galley.size().x - desired_inner_size.x)
678                .at_least(0.0);
679
680            state.singleline_offset = offset_x;
681            galley_pos -= vec2(offset_x, 0.0);
682        } else {
683            state.singleline_offset = align_offset;
684        }
685
686        let selection_changed = if let (Some(cursor_range), Some(prev_cursor_range)) =
687            (cursor_range, prev_cursor_range)
688        {
689            prev_cursor_range != cursor_range
690        } else {
691            false
692        };
693
694        if ui.is_rect_visible(rect) {
695            if text.as_str().is_empty() && !hint_text.is_empty() {
696                let hint_text_color = ui.visuals().weak_text_color();
697                let hint_text_font_id = hint_text_font.unwrap_or(font_id.into());
698                let galley = if multiline {
699                    hint_text.into_galley(
700                        ui,
701                        Some(TextWrapMode::Wrap),
702                        desired_inner_size.x,
703                        hint_text_font_id,
704                    )
705                } else {
706                    hint_text.into_galley(
707                        ui,
708                        Some(TextWrapMode::Extend),
709                        f32::INFINITY,
710                        hint_text_font_id,
711                    )
712                };
713                let galley_pos = align
714                    .align_size_within_rect(galley.size(), rect)
715                    .intersect(rect)
716                    .min;
717                painter.galley(galley_pos, galley, hint_text_color);
718            }
719
720            let has_focus = ui.memory(|mem| mem.has_focus(id));
721
722            if has_focus {
723                if let Some(cursor_range) = state.cursor.range(&galley) {
724                    // Add text selection rectangles to the galley:
725                    paint_text_selection(&mut galley, ui.visuals(), &cursor_range, None);
726                }
727            }
728
729            if !clip_text {
730                // Allocate additional space if edits were made this frame that changed the size. This is important so that,
731                // if there's a ScrollArea, it can properly scroll to the cursor.
732                // Condition `!clip_text` is important to avoid breaking layout for `TextEdit::singleline` (PR #5640)
733                let extra_size = galley.size() - rect.size();
734                if extra_size.x > 0.0 || extra_size.y > 0.0 {
735                    ui.allocate_rect(
736                        Rect::from_min_size(outer_rect.max, extra_size),
737                        Sense::hover(),
738                    );
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                    hint_text_str.as_str(),
811                )
812            });
813        } else if selection_changed {
814            let cursor_range = cursor_range.unwrap();
815            let char_range = cursor_range.primary.index..=cursor_range.secondary.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                    hint_text_str.as_str(),
829                )
830            });
831        }
832
833        #[cfg(feature = "accesskit")]
834        {
835            let role = if password {
836                accesskit::Role::PasswordInput
837            } else if multiline {
838                accesskit::Role::MultilineTextInput
839            } else {
840                accesskit::Role::TextInput
841            };
842
843            crate::text_selection::accesskit_text::update_accesskit_for_text_widget(
844                ui.ctx(),
845                id,
846                cursor_range,
847                role,
848                TSTransform::from_translation(galley_pos.to_vec2()),
849                &galley,
850            );
851        }
852
853        TextEditOutput {
854            response,
855            galley,
856            galley_pos,
857            text_clip_rect,
858            state,
859            cursor_range,
860        }
861    }
862}
863
864fn mask_if_password(is_password: bool, text: &str) -> String {
865    fn mask_password(text: &str) -> String {
866        std::iter::repeat_n(
867            epaint::text::PASSWORD_REPLACEMENT_CHAR,
868            text.chars().count(),
869        )
870        .collect::<String>()
871    }
872
873    if is_password {
874        mask_password(text)
875    } else {
876        text.to_owned()
877    }
878}
879
880// ----------------------------------------------------------------------------
881
882/// Check for (keyboard) events to edit the cursor and/or text.
883#[expect(clippy::too_many_arguments)]
884fn events(
885    ui: &crate::Ui,
886    state: &mut TextEditState,
887    text: &mut dyn TextBuffer,
888    galley: &mut Arc<Galley>,
889    layouter: &mut dyn FnMut(&Ui, &dyn TextBuffer, f32) -> Arc<Galley>,
890    id: Id,
891    wrap_width: f32,
892    multiline: bool,
893    password: bool,
894    default_cursor_range: CCursorRange,
895    char_limit: usize,
896    event_filter: EventFilter,
897    return_key: Option<KeyboardShortcut>,
898) -> (bool, CCursorRange) {
899    let os = ui.ctx().os();
900
901    let mut cursor_range = state.cursor.range(galley).unwrap_or(default_cursor_range);
902
903    // We feed state to the undoer both before and after handling input
904    // so that the undoer creates automatic saves even when there are no events for a while.
905    state.undoer.lock().feed_state(
906        ui.input(|i| i.time),
907        &(cursor_range, text.as_str().to_owned()),
908    );
909
910    let copy_if_not_password = |ui: &Ui, text: String| {
911        if !password {
912            ui.ctx().copy_text(text);
913        }
914    };
915
916    let mut any_change = false;
917
918    let mut events = ui.input(|i| i.filtered_events(&event_filter));
919
920    if state.ime_enabled {
921        remove_ime_incompatible_events(&mut events);
922        // Process IME events first:
923        events.sort_by_key(|e| !matches!(e, Event::Ime(_)));
924    }
925
926    for event in &events {
927        let did_mutate_text = match event {
928            // First handle events that only changes the selection cursor, not the text:
929            event if cursor_range.on_event(os, event, galley, id) => None,
930
931            Event::Copy => {
932                if cursor_range.is_empty() {
933                    None
934                } else {
935                    copy_if_not_password(ui, cursor_range.slice_str(text.as_str()).to_owned());
936                    None
937                }
938            }
939            Event::Cut => {
940                if cursor_range.is_empty() {
941                    None
942                } else {
943                    copy_if_not_password(ui, cursor_range.slice_str(text.as_str()).to_owned());
944                    Some(CCursorRange::one(text.delete_selected(&cursor_range)))
945                }
946            }
947            Event::Paste(text_to_insert) => {
948                if !text_to_insert.is_empty() {
949                    let mut ccursor = text.delete_selected(&cursor_range);
950
951                    text.insert_text_at(&mut ccursor, text_to_insert, char_limit);
952
953                    Some(CCursorRange::one(ccursor))
954                } else {
955                    None
956                }
957            }
958            Event::Text(text_to_insert) => {
959                // Newlines are handled by `Key::Enter`.
960                if !text_to_insert.is_empty() && text_to_insert != "\n" && text_to_insert != "\r" {
961                    let mut ccursor = text.delete_selected(&cursor_range);
962
963                    text.insert_text_at(&mut ccursor, text_to_insert, char_limit);
964
965                    Some(CCursorRange::one(ccursor))
966                } else {
967                    None
968                }
969            }
970            Event::Key {
971                key: Key::Tab,
972                pressed: true,
973                modifiers,
974                ..
975            } if multiline => {
976                let mut ccursor = text.delete_selected(&cursor_range);
977                if modifiers.shift {
978                    // TODO(emilk): support removing indentation over a selection?
979                    text.decrease_indentation(&mut ccursor);
980                } else {
981                    text.insert_text_at(&mut ccursor, "\t", char_limit);
982                }
983                Some(CCursorRange::one(ccursor))
984            }
985            Event::Key {
986                key,
987                pressed: true,
988                modifiers,
989                ..
990            } if return_key.is_some_and(|return_key| {
991                *key == return_key.logical_key && modifiers.matches_logically(return_key.modifiers)
992            }) =>
993            {
994                if multiline {
995                    let mut ccursor = text.delete_selected(&cursor_range);
996                    text.insert_text_at(&mut ccursor, "\n", char_limit);
997                    // TODO(emilk): if code editor, auto-indent by same leading tabs, + one if the lines end on an opening bracket
998                    Some(CCursorRange::one(ccursor))
999                } else {
1000                    ui.memory_mut(|mem| mem.surrender_focus(id)); // End input with enter
1001                    break;
1002                }
1003            }
1004
1005            Event::Key {
1006                key,
1007                pressed: true,
1008                modifiers,
1009                ..
1010            } if (modifiers.matches_logically(Modifiers::COMMAND) && *key == Key::Y)
1011                || (modifiers.matches_logically(Modifiers::SHIFT | Modifiers::COMMAND)
1012                    && *key == Key::Z) =>
1013            {
1014                if let Some((redo_ccursor_range, redo_txt)) = state
1015                    .undoer
1016                    .lock()
1017                    .redo(&(cursor_range, text.as_str().to_owned()))
1018                {
1019                    text.replace_with(redo_txt);
1020                    Some(*redo_ccursor_range)
1021                } else {
1022                    None
1023                }
1024            }
1025
1026            Event::Key {
1027                key: Key::Z,
1028                pressed: true,
1029                modifiers,
1030                ..
1031            } if modifiers.matches_logically(Modifiers::COMMAND) => {
1032                if let Some((undo_ccursor_range, undo_txt)) = state
1033                    .undoer
1034                    .lock()
1035                    .undo(&(cursor_range, text.as_str().to_owned()))
1036                {
1037                    text.replace_with(undo_txt);
1038                    Some(*undo_ccursor_range)
1039                } else {
1040                    None
1041                }
1042            }
1043
1044            Event::Key {
1045                modifiers,
1046                key,
1047                pressed: true,
1048                ..
1049            } => check_for_mutating_key_press(os, &cursor_range, text, galley, modifiers, *key),
1050
1051            Event::Ime(ime_event) => match ime_event {
1052                ImeEvent::Enabled => {
1053                    state.ime_enabled = true;
1054                    state.ime_cursor_range = cursor_range;
1055                    None
1056                }
1057                ImeEvent::Preedit(text_mark) => {
1058                    if text_mark == "\n" || text_mark == "\r" {
1059                        None
1060                    } else {
1061                        // Empty prediction can be produced when user press backspace
1062                        // or escape during IME, so we clear current text.
1063                        let mut ccursor = text.delete_selected(&cursor_range);
1064                        let start_cursor = ccursor;
1065                        if !text_mark.is_empty() {
1066                            text.insert_text_at(&mut ccursor, text_mark, char_limit);
1067                        }
1068                        state.ime_cursor_range = cursor_range;
1069                        Some(CCursorRange::two(start_cursor, ccursor))
1070                    }
1071                }
1072                ImeEvent::Commit(prediction) => {
1073                    if prediction == "\n" || prediction == "\r" {
1074                        None
1075                    } else {
1076                        state.ime_enabled = false;
1077
1078                        if !prediction.is_empty()
1079                            && cursor_range.secondary.index
1080                                == state.ime_cursor_range.secondary.index
1081                        {
1082                            let mut ccursor = text.delete_selected(&cursor_range);
1083                            text.insert_text_at(&mut ccursor, prediction, char_limit);
1084                            Some(CCursorRange::one(ccursor))
1085                        } else {
1086                            let ccursor = cursor_range.primary;
1087                            Some(CCursorRange::one(ccursor))
1088                        }
1089                    }
1090                }
1091                ImeEvent::Disabled => {
1092                    state.ime_enabled = false;
1093                    None
1094                }
1095            },
1096
1097            _ => None,
1098        };
1099
1100        if let Some(new_ccursor_range) = did_mutate_text {
1101            any_change = true;
1102
1103            // Layout again to avoid frame delay, and to keep `text` and `galley` in sync.
1104            *galley = layouter(ui, text, wrap_width);
1105
1106            // Set cursor_range using new galley:
1107            cursor_range = new_ccursor_range;
1108        }
1109    }
1110
1111    state.cursor.set_char_range(Some(cursor_range));
1112
1113    state.undoer.lock().feed_state(
1114        ui.input(|i| i.time),
1115        &(cursor_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: &CCursorRange,
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)
1161                } else {
1162                    text.delete_previous_char(cursor)
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)
1177                } else {
1178                    text.delete_next_char(cursor)
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);
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)
1208            } else {
1209                text.delete_selected(cursor_range)
1210            };
1211            Some(CCursorRange::one(ccursor))
1212        }
1213
1214        _ => None,
1215    }
1216}