egui/widgets/text_edit/
state.rs

1use std::sync::Arc;
2
3use crate::mutex::Mutex;
4
5use crate::{
6    Context, Id, Vec2,
7    text_selection::{CCursorRange, TextCursorState},
8};
9
10pub type TextEditUndoer = crate::util::undoer::Undoer<(CCursorRange, String)>;
11
12/// The text edit state stored between frames.
13///
14/// Attention: You also need to `store` the updated state.
15/// ```
16/// # egui::__run_test_ui(|ui| {
17/// # let mut text = String::new();
18/// use egui::text::{CCursor, CCursorRange};
19///
20/// let mut output = egui::TextEdit::singleline(&mut text).show(ui);
21///
22/// // Create a new selection range
23/// let min = CCursor::new(0);
24/// let max = CCursor::new(0);
25/// let new_range = CCursorRange::two(min, max);
26///
27/// // Update the state
28/// output.state.cursor.set_char_range(Some(new_range));
29/// // Store the updated state
30/// output.state.store(ui.ctx(), output.response.id);
31/// # });
32/// ```
33#[derive(Clone, Default)]
34#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
35#[cfg_attr(feature = "serde", serde(default))]
36pub struct TextEditState {
37    /// Controls the text selection.
38    pub cursor: TextCursorState,
39
40    /// Wrapped in Arc for cheaper clones.
41    #[cfg_attr(feature = "serde", serde(skip))]
42    pub(crate) undoer: Arc<Mutex<TextEditUndoer>>,
43
44    // If IME candidate window is shown on this text edit.
45    #[cfg_attr(feature = "serde", serde(skip))]
46    pub(crate) ime_enabled: bool,
47
48    // cursor range for IME candidate.
49    #[cfg_attr(feature = "serde", serde(skip))]
50    pub(crate) ime_cursor_range: CCursorRange,
51
52    // Text offset within the widget area.
53    // Used for sensing and singleline text clipping.
54    #[cfg_attr(feature = "serde", serde(skip))]
55    pub(crate) text_offset: Vec2,
56
57    /// When did the user last press a key or click on the `TextEdit`.
58    /// Used to pause the cursor animation when typing.
59    #[cfg_attr(feature = "serde", serde(skip))]
60    pub(crate) last_interaction_time: f64,
61}
62
63impl TextEditState {
64    pub fn load(ctx: &Context, id: Id) -> Option<Self> {
65        ctx.data_mut(|d| d.get_persisted(id))
66    }
67
68    pub fn store(self, ctx: &Context, id: Id) {
69        ctx.data_mut(|d| d.insert_persisted(id, self));
70    }
71
72    pub fn undoer(&self) -> TextEditUndoer {
73        self.undoer.lock().clone()
74    }
75
76    #[expect(clippy::needless_pass_by_ref_mut)] // Intentionally hide interiority of mutability
77    pub fn set_undoer(&mut self, undoer: TextEditUndoer) {
78        *self.undoer.lock() = undoer;
79    }
80
81    pub fn clear_undoer(&mut self) {
82        self.set_undoer(TextEditUndoer::default());
83    }
84}