Skip to main content

egui/data/
output.rs

1//! All the data egui returns to the backend at the end of each frame.
2
3use core::ops::Range;
4
5use epaint::text::CharIndex;
6
7use crate::{OrderedViewportIdMap, RepaintCause, Role, ViewportOutput};
8
9/// What egui emits each frame from [`crate::Context::run_ui`].
10///
11/// The backend should use this.
12#[derive(Clone, Default)]
13pub struct FullOutput {
14    /// Non-rendering related output.
15    pub platform_output: PlatformOutput,
16
17    /// Texture changes since last frame (including the font texture).
18    ///
19    /// The backend needs to apply [`crate::TexturesDelta::push`] _before_ painting,
20    /// and free any texture in [`crate::TexturesDelta::free`] _after_ painting.
21    ///
22    /// It is assumed that all egui viewports share the same painter and texture namespace.
23    pub textures_delta: epaint::textures::TexturesDelta,
24
25    /// What to paint.
26    ///
27    /// You can use [`crate::Context::tessellate`] to turn this into triangles.
28    pub shapes: Vec<epaint::ClippedShape>,
29
30    /// The number of physical pixels per logical ui point, for the viewport that was updated.
31    ///
32    /// You can pass this to [`crate::Context::tessellate`] together with [`Self::shapes`].
33    pub pixels_per_point: f32,
34
35    /// All the active viewports, including the root.
36    ///
37    /// It is up to the integration to spawn a native window for each viewport,
38    /// and to close any window that no longer has a viewport in this map.
39    pub viewport_output: OrderedViewportIdMap<ViewportOutput>,
40}
41
42impl FullOutput {
43    /// Add on new output.
44    pub fn append(&mut self, newer: Self) {
45        use alloc::collections::btree_map::Entry;
46
47        let Self {
48            platform_output,
49            textures_delta,
50            shapes,
51            pixels_per_point,
52            viewport_output,
53        } = newer;
54
55        self.platform_output.append(platform_output);
56        self.textures_delta.append(textures_delta);
57        self.shapes = shapes; // Only paint the latest
58        self.pixels_per_point = pixels_per_point; // Use latest
59
60        for (id, new_viewport) in viewport_output {
61            match self.viewport_output.entry(id) {
62                Entry::Vacant(entry) => {
63                    entry.insert(new_viewport);
64                }
65                Entry::Occupied(mut entry) => {
66                    entry.get_mut().append(new_viewport);
67                }
68            }
69        }
70    }
71
72    /// [`epaint::textures::TexturesDelta`] will panic when dropped with still unapplied deltas,
73    /// this is a helper to clear the deltas.
74    pub fn drop_without_applying_deltas(mut self) {
75        self.textures_delta.clear();
76    }
77}
78
79/// What egui emits from [`crate::Context::run_logic`], i.e. from a tick where no ui was shown.
80///
81/// There is nothing to paint, but the app may still have asked the integration to do things,
82/// e.g. to show a hidden window again with [`crate::ViewportCommand::Focus`].
83#[derive(Clone, Default)]
84pub struct LogicOutput {
85    /// Non-rendering related output.
86    pub platform_output: PlatformOutput,
87
88    /// The commands sent with [`crate::Context::send_viewport_cmd`] and friends.
89    ///
90    /// Note that this contains no information about which viewports exist:
91    /// the integration should leave its viewports as they are.
92    pub viewport_commands: OrderedViewportIdMap<Vec<crate::ViewportCommand>>,
93}
94
95/// Information about text being edited.
96///
97/// Useful for IME.
98#[derive(Copy, Clone, Debug, PartialEq, Eq)]
99#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
100pub struct IMEOutput {
101    /// IME's purpose.
102    pub purpose: crate::IMEPurpose,
103
104    /// Where the [`crate::TextEdit`] is located on screen.
105    pub rect: crate::Rect,
106
107    /// Where the primary cursor is.
108    ///
109    /// This is a very thin rectangle.
110    pub cursor_rect: crate::Rect,
111
112    /// Whether any ongoing IME composition should be interrupted.
113    pub should_interrupt_composition: bool,
114}
115
116/// Commands that the egui integration should execute at the end of a frame.
117///
118/// Commands that are specific to a viewport should be put in [`crate::ViewportCommand`] instead.
119#[derive(Clone, Debug, PartialEq, Eq)]
120#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
121pub enum OutputCommand {
122    /// Put this text to the system clipboard.
123    ///
124    /// This is often a response to [`crate::Event::Copy`] or [`crate::Event::Cut`].
125    CopyText(String),
126
127    /// The user has finished changing the text selection, and this is what is now selected.
128    ///
129    /// Sent once the selection settles (e.g. when the mouse button is released after a drag),
130    /// and only if it changed, so not on every frame of a drag.
131    ///
132    /// On X11 and Wayland, `egui-winit` puts this in the PRIMARY selection,
133    /// so that it can be pasted with the middle mouse button.
134    TextSelectionSettled(String),
135
136    /// Put this image to the system clipboard.
137    CopyImage(crate::ColorImage),
138
139    /// Open this url in a browser.
140    OpenUrl(OpenUrl),
141}
142
143/// The non-rendering part of what egui emits each frame.
144///
145/// You can access (and modify) this with [`crate::Context::output`].
146///
147/// The backend should use this.
148#[derive(Default, Clone, PartialEq)]
149#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
150pub struct PlatformOutput {
151    /// Commands that the egui integration should execute at the end of a frame.
152    pub commands: Vec<OutputCommand>,
153
154    /// Set the cursor to this icon.
155    pub cursor_icon: CursorIcon,
156
157    /// If set, the integration should display this RGBA image as the OS
158    /// cursor (via e.g. `winit::window::CustomCursor`) instead of the
159    /// standard `cursor_icon`. Set per frame; integrations that don't
160    /// support custom cursors fall back to `cursor_icon`.
161    ///
162    /// Skipped from serde because the bitmap is ephemeral and shouldn't
163    /// roundtrip through persisted state.
164    #[cfg_attr(feature = "serde", serde(skip))]
165    pub cursor_image: Option<CustomCursorImage>,
166
167    /// Events that may be useful to e.g. a screen reader.
168    pub events: Vec<OutputEvent>,
169
170    /// Is there a mutable [`TextEdit`](crate::TextEdit) under the cursor?
171    /// Use by `eframe` web to show/hide mobile keyboard and IME agent.
172    pub mutable_text_under_cursor: bool,
173
174    /// This is set if, and only if, the user is currently editing text.
175    ///
176    /// Useful for IME.
177    ///
178    /// This field should only be set by the widget that currently owns IME
179    /// events (see [`crate::Memory::owns_ime_events`]).
180    pub ime: Option<IMEOutput>,
181
182    /// The difference in the widget tree since last frame.
183    ///
184    /// NOTE: this needs to be per-viewport.
185    pub accesskit_update: Option<accesskit::TreeUpdate>,
186
187    /// How many ui passes is this the sum of?
188    ///
189    /// See [`crate::Context::request_discard`] for details.
190    ///
191    /// This is incremented at the END of each frame,
192    /// so this will be `0` for the first pass.
193    pub num_completed_passes: usize,
194
195    /// Was [`crate::Context::request_discard`] called during the latest pass?
196    ///
197    /// If so, what was the reason(s) for it?
198    ///
199    /// If empty, there was never any calls.
200    #[cfg_attr(feature = "serde", serde(skip))]
201    pub request_discard_reasons: Vec<RepaintCause>,
202}
203
204impl PlatformOutput {
205    /// This can be used by a text-to-speech system to describe the events (if any).
206    pub fn events_description(&self) -> String {
207        // only describe last event:
208        if let Some(event) = self.events.iter().next_back() {
209            match event {
210                OutputEvent::Clicked(widget_info)
211                | OutputEvent::DoubleClicked(widget_info)
212                | OutputEvent::TripleClicked(widget_info)
213                | OutputEvent::FocusGained(widget_info)
214                | OutputEvent::TextSelectionChanged(widget_info)
215                | OutputEvent::ValueChanged(widget_info) => {
216                    return widget_info.description();
217                }
218            }
219        }
220        Default::default()
221    }
222
223    /// Add on new output.
224    pub fn append(&mut self, newer: Self) {
225        let Self {
226            mut commands,
227            cursor_icon,
228            cursor_image,
229            mut events,
230            mutable_text_under_cursor,
231            ime,
232            accesskit_update,
233            num_completed_passes,
234            mut request_discard_reasons,
235        } = newer;
236
237        self.commands.append(&mut commands);
238        self.cursor_icon = cursor_icon;
239        self.cursor_image = cursor_image;
240        self.events.append(&mut events);
241        self.mutable_text_under_cursor = mutable_text_under_cursor;
242        self.ime = ime.or(self.ime);
243        self.num_completed_passes += num_completed_passes;
244        self.request_discard_reasons
245            .append(&mut request_discard_reasons);
246
247        // egui produces a complete AccessKit tree for each frame, so overwrite rather than append:
248        self.accesskit_update = accesskit_update;
249    }
250
251    /// Take everything ephemeral (everything except `cursor_icon` and
252    /// `cursor_image` currently)
253    pub fn take(&mut self) -> Self {
254        let taken = core::mem::take(self);
255        self.cursor_icon = taken.cursor_icon; // sticky between frames
256        self.cursor_image = taken.cursor_image.clone(); // sticky between frames
257        taken
258    }
259
260    /// Was [`crate::Context::request_discard`] called?
261    pub fn requested_discard(&self) -> bool {
262        !self.request_discard_reasons.is_empty()
263    }
264}
265
266/// What URL to open, and how.
267///
268/// Use with [`crate::Context::open_url`].
269#[derive(Clone, Debug, PartialEq, Eq)]
270#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
271pub struct OpenUrl {
272    pub url: String,
273
274    /// If `true`, open the url in a new tab.
275    /// If `false` open it in the same tab.
276    /// Only matters when in a web browser.
277    pub new_tab: bool,
278}
279
280impl OpenUrl {
281    #[expect(clippy::needless_pass_by_value)]
282    pub fn same_tab(url: impl ToString) -> Self {
283        Self {
284            url: url.to_string(),
285            new_tab: false,
286        }
287    }
288
289    #[expect(clippy::needless_pass_by_value)]
290    pub fn new_tab(url: impl ToString) -> Self {
291        Self {
292            url: url.to_string(),
293            new_tab: true,
294        }
295    }
296}
297
298/// Types of attention to request from a user when a native window is not in focus.
299///
300/// See [winit's documentation][user_attention_type] for platform-specific meaning of the attention types.
301///
302/// [user_attention_type]: https://docs.rs/winit/latest/winit/window/enum.UserAttentionType.html
303#[derive(Clone, Copy, Debug, PartialEq, Eq)]
304#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
305pub enum UserAttentionType {
306    /// Request an elevated amount of animations and flair for the window and the task bar or dock icon.
307    Critical,
308
309    /// Request a standard amount of attention-grabbing actions.
310    Informational,
311
312    /// Reset the attention request and interrupt related animations and flashes.
313    Reset,
314}
315
316/// A bitmap cursor pushed to the integration via [`PlatformOutput::cursor_image`].
317///
318/// The integration is expected to upload this to the OS as a real cursor
319/// (so the image is not clipped by the egui window — what `egui::Painter`
320/// drawn cursors suffer from). Backends that don't support it should fall
321/// back to [`PlatformOutput::cursor_icon`].
322///
323/// `rgba` is straight (non-premultiplied) RGBA — same encoding as
324/// `winit::window::CustomCursor::from_rgba`. The buffer length must be
325/// exactly `size[0] * size[1] * 4` bytes. `size` and `hotspot` use
326/// `u16` to match winit's native types and avoid a lossy cast in the
327/// integration layer.
328///
329/// `Arc<[u8]>` is used so integrations can dedupe / cache by pointer
330/// identity (`Arc::ptr_eq`) and avoid re-uploading the same bitmap to
331/// the OS every frame.
332#[derive(Clone, PartialEq, Eq)]
333pub struct CustomCursorImage {
334    pub rgba: alloc::sync::Arc<[u8]>,
335    pub size: [u16; 2],
336    pub hotspot: [u16; 2],
337}
338
339impl core::fmt::Debug for CustomCursorImage {
340    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
341        f.debug_struct("CustomCursorImage")
342            .field("size", &self.size)
343            .field("hotspot", &self.hotspot)
344            .field("rgba_len", &self.rgba.len())
345            .finish()
346    }
347}
348
349/// A mouse cursor icon.
350///
351/// egui emits a [`CursorIcon`] in [`PlatformOutput`] each frame as a request to the integration.
352///
353/// Loosely based on <https://developer.mozilla.org/en-US/docs/Web/CSS/cursor>.
354#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
355#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
356pub enum CursorIcon {
357    /// Normal cursor icon, whatever that is.
358    #[default]
359    Default,
360
361    /// Show no cursor
362    None,
363
364    // ------------------------------------
365    // Links and status:
366    /// A context menu is available
367    ContextMenu,
368
369    /// Question mark
370    Help,
371
372    /// Pointing hand, used for e.g. web links
373    PointingHand,
374
375    /// Shows that processing is being done, but that the program is still interactive.
376    Progress,
377
378    /// Not yet ready, try later.
379    Wait,
380
381    // ------------------------------------
382    // Selection:
383    /// Hover a cell in a table
384    Cell,
385
386    /// For precision work
387    Crosshair,
388
389    /// Text caret, e.g. "Click here to edit text"
390    Text,
391
392    /// Vertical text caret, e.g. "Click here to edit vertical text"
393    VerticalText,
394
395    // ------------------------------------
396    // Drag-and-drop:
397    /// Indicated an alias, e.g. a shortcut
398    Alias,
399
400    /// Indicate that a copy will be made
401    Copy,
402
403    /// Omnidirectional move icon (e.g. arrows in all cardinal directions)
404    Move,
405
406    /// Can't drop here
407    NoDrop,
408
409    /// Forbidden
410    NotAllowed,
411
412    /// The thing you are hovering can be grabbed
413    Grab,
414
415    /// You are grabbing the thing you are hovering
416    Grabbing,
417
418    // ------------------------------------
419    /// Something can be scrolled in any direction (panned).
420    AllScroll,
421
422    // ------------------------------------
423    // Resizing in two directions:
424    /// Horizontal resize `-` to make something wider or more narrow (left to/from right)
425    ResizeHorizontal,
426
427    /// Diagonal resize `/` (right-up to/from left-down)
428    ResizeNeSw,
429
430    /// Diagonal resize `\` (left-up to/from right-down)
431    ResizeNwSe,
432
433    /// Vertical resize `|` (up-down or down-up)
434    ResizeVertical,
435
436    // ------------------------------------
437    // Resizing in one direction:
438    /// Resize something rightwards (e.g. when dragging the right-most edge of something)
439    ResizeEast,
440
441    /// Resize something down and right (e.g. when dragging the bottom-right corner of something)
442    ResizeSouthEast,
443
444    /// Resize something downwards (e.g. when dragging the bottom edge of something)
445    ResizeSouth,
446
447    /// Resize something down and left (e.g. when dragging the bottom-left corner of something)
448    ResizeSouthWest,
449
450    /// Resize something leftwards (e.g. when dragging the left edge of something)
451    ResizeWest,
452
453    /// Resize something up and left (e.g. when dragging the top-left corner of something)
454    ResizeNorthWest,
455
456    /// Resize something up (e.g. when dragging the top edge of something)
457    ResizeNorth,
458
459    /// Resize something up and right (e.g. when dragging the top-right corner of something)
460    ResizeNorthEast,
461
462    // ------------------------------------
463    /// Resize a column
464    ResizeColumn,
465
466    /// Resize a row
467    ResizeRow,
468
469    // ------------------------------------
470    // Zooming:
471    /// Enhance!
472    ZoomIn,
473
474    /// Let's get a better overview
475    ZoomOut,
476}
477
478impl CursorIcon {
479    pub const ALL: [Self; 35] = [
480        Self::Default,
481        Self::None,
482        Self::ContextMenu,
483        Self::Help,
484        Self::PointingHand,
485        Self::Progress,
486        Self::Wait,
487        Self::Cell,
488        Self::Crosshair,
489        Self::Text,
490        Self::VerticalText,
491        Self::Alias,
492        Self::Copy,
493        Self::Move,
494        Self::NoDrop,
495        Self::NotAllowed,
496        Self::Grab,
497        Self::Grabbing,
498        Self::AllScroll,
499        Self::ResizeHorizontal,
500        Self::ResizeNeSw,
501        Self::ResizeNwSe,
502        Self::ResizeVertical,
503        Self::ResizeEast,
504        Self::ResizeSouthEast,
505        Self::ResizeSouth,
506        Self::ResizeSouthWest,
507        Self::ResizeWest,
508        Self::ResizeNorthWest,
509        Self::ResizeNorth,
510        Self::ResizeNorthEast,
511        Self::ResizeColumn,
512        Self::ResizeRow,
513        Self::ZoomIn,
514        Self::ZoomOut,
515    ];
516}
517
518/// Things that happened during this frame that the integration may be interested in.
519///
520/// In particular, these events may be useful for accessibility, i.e. for screen readers.
521#[derive(Clone, PartialEq)]
522#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
523pub enum OutputEvent {
524    /// A widget was clicked.
525    Clicked(WidgetInfo),
526
527    /// A widget was double-clicked.
528    DoubleClicked(WidgetInfo),
529
530    /// A widget was triple-clicked.
531    TripleClicked(WidgetInfo),
532
533    /// A widget gained keyboard focus (by tab key).
534    FocusGained(WidgetInfo),
535
536    /// Text selection was updated.
537    TextSelectionChanged(WidgetInfo),
538
539    /// A widget's value changed.
540    ValueChanged(WidgetInfo),
541}
542
543impl OutputEvent {
544    pub fn widget_info(&self) -> &WidgetInfo {
545        match self {
546            Self::Clicked(info)
547            | Self::DoubleClicked(info)
548            | Self::TripleClicked(info)
549            | Self::FocusGained(info)
550            | Self::TextSelectionChanged(info)
551            | Self::ValueChanged(info) => info,
552        }
553    }
554}
555
556impl core::fmt::Debug for OutputEvent {
557    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
558        match self {
559            Self::Clicked(wi) => write!(f, "Clicked({wi:?})"),
560            Self::DoubleClicked(wi) => write!(f, "DoubleClicked({wi:?})"),
561            Self::TripleClicked(wi) => write!(f, "TripleClicked({wi:?})"),
562            Self::FocusGained(wi) => write!(f, "FocusGained({wi:?})"),
563            Self::TextSelectionChanged(wi) => write!(f, "TextSelectionChanged({wi:?})"),
564            Self::ValueChanged(wi) => write!(f, "ValueChanged({wi:?})"),
565        }
566    }
567}
568
569/// Describes a widget such as a [`crate::Button`] or a [`crate::TextEdit`].
570#[derive(Clone, PartialEq)]
571#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
572pub struct WidgetInfo {
573    /// The accessibility role of this widget.
574    pub role: Role,
575
576    /// Whether the widget is enabled.
577    pub enabled: bool,
578
579    /// The text on labels, buttons, checkboxes etc.
580    pub label: Option<String>,
581
582    /// The contents of some editable text (for [`TextEdit`](crate::TextEdit) fields).
583    pub current_text_value: Option<String>,
584
585    /// The previous text value.
586    pub prev_text_value: Option<String>,
587
588    /// The current value of checkboxes and radio buttons.
589    pub selected: Option<bool>,
590
591    /// The current value of sliders etc.
592    pub value: Option<f64>,
593
594    /// Selected range of characters in [`Self::current_text_value`].
595    ///
596    /// The range is `start..end` in *character* offsets (not bytes), with `end` exclusive.
597    pub text_selection: Option<Range<CharIndex>>,
598
599    /// The hint text for text edit fields.
600    pub hint_text: Option<String>,
601}
602
603impl core::fmt::Debug for WidgetInfo {
604    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
605        let Self {
606            role,
607            enabled,
608            label,
609            current_text_value: text_value,
610            prev_text_value,
611            selected,
612            value,
613            text_selection,
614            hint_text,
615        } = self;
616
617        let mut s = f.debug_struct("WidgetInfo");
618
619        s.field("role", role);
620
621        if !enabled {
622            s.field("enabled", enabled);
623        }
624
625        if let Some(label) = label {
626            s.field("label", label);
627        }
628        if let Some(text_value) = text_value {
629            s.field("text_value", text_value);
630        }
631        if let Some(prev_text_value) = prev_text_value {
632            s.field("prev_text_value", prev_text_value);
633        }
634        if let Some(selected) = selected {
635            s.field("selected", selected);
636        }
637        if let Some(value) = value {
638            s.field("value", value);
639        }
640        if let Some(text_selection) = text_selection {
641            s.field("text_selection", text_selection);
642        }
643        if let Some(hint_text) = hint_text {
644            s.field("hint_text", hint_text);
645        }
646
647        s.finish()
648    }
649}
650
651/// A human-readable, lowercase name for a widget role, e.g. for a text-to-speech system.
652///
653/// The [`Role`] is spelled out in `CamelCase`, so we split it into lowercase words.
654/// [`Role::Unknown`] has no useful name, and gives an empty string.
655///
656/// ```
657/// # use egui::{Role, role_description};
658/// assert_eq!(role_description(Role::Button), "button");
659/// assert_eq!(role_description(Role::CheckBox), "check box");
660/// assert_eq!(role_description(Role::SpinButton), "spin button");
661/// assert_eq!(role_description(Role::Unknown), "");
662/// ```
663pub fn role_description(role: Role) -> String {
664    if role == Role::Unknown {
665        return String::new();
666    }
667
668    let mut description = String::new();
669    for ch in format!("{role:?}").chars() {
670        if ch.is_ascii_uppercase() && !description.is_empty() {
671            description.push(' ');
672        }
673        description.push(ch.to_ascii_lowercase());
674    }
675    description
676}
677
678impl WidgetInfo {
679    pub fn new(role: Role) -> Self {
680        Self {
681            role,
682            enabled: true,
683            label: None,
684            current_text_value: None,
685            prev_text_value: None,
686            selected: None,
687            value: None,
688            text_selection: None,
689            hint_text: None,
690        }
691    }
692
693    #[expect(clippy::needless_pass_by_value)]
694    pub fn labeled(role: Role, enabled: bool, label: impl ToString) -> Self {
695        Self {
696            enabled,
697            label: Some(label.to_string()),
698            ..Self::new(role)
699        }
700    }
701
702    /// checkboxes, radio-buttons etc
703    #[expect(clippy::needless_pass_by_value)]
704    pub fn selected(role: Role, enabled: bool, selected: bool, label: impl ToString) -> Self {
705        Self {
706            enabled,
707            label: Some(label.to_string()),
708            selected: Some(selected),
709            ..Self::new(role)
710        }
711    }
712
713    pub fn drag_value(enabled: bool, value: f64) -> Self {
714        Self {
715            enabled,
716            value: Some(value),
717            ..Self::new(Role::SpinButton)
718        }
719    }
720
721    #[expect(clippy::needless_pass_by_value)]
722    pub fn slider(enabled: bool, value: f64, label: impl ToString) -> Self {
723        let label = label.to_string();
724        Self {
725            enabled,
726            label: if label.is_empty() { None } else { Some(label) },
727            value: Some(value),
728            ..Self::new(Role::Slider)
729        }
730    }
731
732    #[expect(clippy::needless_pass_by_value)]
733    pub fn text_edit(
734        enabled: bool,
735        prev_text_value: impl ToString,
736        text_value: impl ToString,
737        hint_text: impl ToString,
738    ) -> Self {
739        let text_value = text_value.to_string();
740        let prev_text_value = prev_text_value.to_string();
741        let hint_text = hint_text.to_string();
742        let prev_text_value = if text_value == prev_text_value {
743            None
744        } else {
745            Some(prev_text_value)
746        };
747        Self {
748            enabled,
749            current_text_value: Some(text_value),
750            prev_text_value,
751            hint_text: Some(hint_text),
752            ..Self::new(Role::TextInput)
753        }
754    }
755
756    #[expect(clippy::needless_pass_by_value)]
757    pub fn text_selection_changed(
758        enabled: bool,
759        text_selection: Range<CharIndex>,
760        current_text_value: impl ToString,
761    ) -> Self {
762        Self {
763            enabled,
764            text_selection: Some(text_selection),
765            current_text_value: Some(current_text_value.to_string()),
766            ..Self::new(Role::TextInput)
767        }
768    }
769
770    /// This can be used by a text-to-speech system to describe the widget.
771    pub fn description(&self) -> String {
772        let Self {
773            role,
774            enabled,
775            label,
776            current_text_value: text_value,
777            prev_text_value: _,
778            selected,
779            value,
780            text_selection: _,
781            hint_text: _,
782        } = self;
783
784        let mut description = role_description(*role);
785
786        if let Some(selected) = selected {
787            if *role == Role::CheckBox {
788                let state = if *selected { "checked" } else { "unchecked" };
789                description = format!("{state} {description}");
790            } else {
791                description += if *selected { "selected" } else { "" };
792            }
793        }
794
795        if let Some(label) = label {
796            description = format!("{label}: {description}");
797        }
798
799        if role == &Role::TextInput {
800            let text = if let Some(text_value) = text_value {
801                if text_value.is_empty() {
802                    "blank".into()
803                } else {
804                    text_value.clone()
805                }
806            } else {
807                "blank".into()
808            };
809            description = format!("{text}: {description}");
810        }
811
812        if let Some(value) = value {
813            description += " ";
814            description += &value.to_string();
815        }
816
817        if !enabled {
818            description += ": disabled";
819        }
820        description.trim().to_owned()
821    }
822}