Skip to main content

waft_winui/controls/
text_box.rs

1//! WinUI TextBox template and behavior, using Waft’s native editing engine.
2
3use super::text_control::{TextControl, TextControlState};
4use crate::Brush;
5use std::{fmt, rc::Rc};
6use waft_embedder::{Color, Offset, Rect, TextAlign, TextSelection};
7use waft_foundation::{App, Handle};
8use waft_rendering::RenderBox;
9use waft_services::{SelectionChangedCause, TextInputFormatterRef};
10use waft_widgets::*;
11
12/// XAML `TextWrapping`: whether long lines break at the box's width.
13#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
14pub enum TextWrapping {
15    /// Lines stay whole and scroll sideways, a single line and, with `AcceptsReturn`, each line
16    /// of a multiline box.
17    #[default]
18    NoWrap,
19    /// Long lines wrap within the editor width.
20    Wrap,
21}
22
23/// XAML `ScrollBarVisibility` for `ScrollViewer.HorizontalScrollBarVisibility`, as far as the kit's scroll bar can draw it.
24#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
25pub enum ScrollBarVisibility {
26    /// The content does not scroll on this axis: it is laid out at the view's width and clipped.
27    Disabled,
28    /// A scroll bar shows when the content is wider than the view.
29    Auto,
30    /// The content scrolls, with no scroll bar; `TextBox`'s style default.
31    #[default]
32    Hidden,
33}
34
35/// Notification of a user edit after the native controller updates.
36pub type TextChangedCallback = Rc<dyn Fn(&mut App, String)>;
37
38/// Notification of a native selection change and its input cause.
39pub type TextSelectionChangedCallback =
40    Rc<dyn Fn(&mut App, TextSelection, Option<SelectionChangedCause>)>;
41
42/// The WinUI TextBox control with its default Fluent template.
43#[derive(Clone)]
44pub struct TextBox {
45    /// Owns the text, selection and composing range; the caller retains and disposes it.
46    pub controller: TextEditingControllerRef,
47
48    /// An optional caller-owned focus node; otherwise the control creates one.
49    pub focus_node: Option<FocusNodeRef>,
50
51    /// Content above the editor, with the source header margin.
52    pub header: Option<WidgetRef>,
53
54    /// Supporting content below the editor.
55    pub description: Option<WidgetRef>,
56
57    /// Text displayed while the controller is empty.
58    pub placeholder_text: String,
59
60    /// Whether the editor accepts pointer and keyboard input.
61    pub is_enabled: bool,
62
63    /// The editor font size and basis of the helper-button width threshold; the theme's `ControlContentThemeFontSize` when `None`.
64    pub font_size: Option<f64>,
65
66    /// Editor padding in left, top, right, bottom order; the theme's `TextControlThemePadding` when `None`.
67    pub padding: Option<[f64; 4]>,
68
69    /// The template border and helper-button corner radius.
70    pub corner_radius: Option<f64>,
71
72    /// Overrides the normal editor foreground; visual states use their source theme resources.
73    pub foreground: Option<Color>,
74
75    /// Overrides the normal editor background.
76    pub background: Option<Brush>,
77
78    /// Overrides the normal editor border brush.
79    pub border_brush: Option<Brush>,
80
81    /// Overrides the selection fill while the editor has focus.
82    pub selection_highlight_color: Option<Color>,
83
84    /// Limits user edits through the native length formatter; programmatic assignments remain unrestricted.
85    pub max_length: Option<i32>,
86
87    /// Native formatters applied to user edits, following Flutter composition and undo behavior.
88    pub input_formatters: Vec<TextInputFormatterRef>,
89
90    /// Requests initial keyboard focus through the native editor.
91    pub autofocus: bool,
92
93    /// Whether the caret is drawn while the box has the focus; Flutter's `TextField.showCursor`,
94    /// which XAML's `TextBox` has no property for. `None` draws it unless the box is read-only.
95    /// A box that hides it still takes what is typed.
96    pub show_cursor: Option<bool>,
97
98    /// Overrides the desktop text-command menu.
99    pub context_menu_builder: Option<EditableTextContextMenuBuilder>,
100
101    /// Allows selection and copying while preventing edits.
102    pub is_read_only: bool,
103
104    /// Accepts line breaks and enables native wrapped multiline editing.
105    ///
106    /// A multiline box fills the height its parent gives it, as WinUI's default
107    /// `VerticalAlignment="Stretch"` does, and its editor scrolls once the text passes it; in an
108    /// unbounded parent it grows with its text.
109    pub accepts_return: bool,
110
111    /// Wraps text independently of accepting Enter; with `NoWrap`, a multiline box keeps each line whole and scrolls sideways.
112    pub text_wrapping: TextWrapping,
113
114    /// `ScrollViewer.HorizontalScrollBarVisibility`: how a multiline box that does not wrap scrolls its lines sideways.
115    pub horizontal_scroll_bar_visibility: ScrollBarVisibility,
116
117    /// Limits the visible height in lines for a multiline editor, which grows with its text from
118    /// one line up to it; past it, the content scrolls vertically. Setting it leaves the editor
119    /// at that height instead of filling the box; leave it unset for a box that fills its pane.
120    pub max_lines: Option<i32>,
121
122    /// Alignment of editor and placeholder text.
123    pub text_alignment: TextAlign,
124
125    /// Overrides the placeholder foreground in every visual state.
126    pub placeholder_foreground: Option<Color>,
127
128    /// Receives user text edits and clear-button actions; listen to the controller for all assignments.
129    pub text_changed: Option<TextChangedCallback>,
130
131    /// Receives native user selection changes after the controller updates.
132    pub selection_changed: Option<TextSelectionChangedCallback>,
133
134    /// Identity retained across parent rebuilds.
135    pub key: Option<KeyRef>,
136}
137
138impl TextBox {
139    /// Creates an editor using a caller-owned native editing controller.
140    pub fn new(controller: TextEditingControllerRef) -> Self {
141        Self {
142            controller,
143            focus_node: None,
144            header: None,
145            description: None,
146            placeholder_text: String::new(),
147            is_enabled: true,
148            font_size: None,
149            padding: None,
150            corner_radius: None,
151            foreground: None,
152            background: None,
153            border_brush: None,
154            selection_highlight_color: None,
155            max_length: None,
156            input_formatters: Vec::new(),
157            autofocus: false,
158            show_cursor: None,
159            context_menu_builder: None,
160            is_read_only: false,
161            accepts_return: false,
162            text_wrapping: TextWrapping::NoWrap,
163            horizontal_scroll_bar_visibility: ScrollBarVisibility::Hidden,
164            max_lines: None,
165            text_alignment: TextAlign::Start,
166            placeholder_foreground: None,
167            text_changed: None,
168            selection_changed: None,
169            key: None,
170        }
171    }
172
173    /// Sets FocusNode.
174    pub fn focus_node(mut self, value: FocusNodeRef) -> Self {
175        self.focus_node = Some(value);
176        self
177    }
178
179    /// Sets Header.
180    #[cfg_attr(debug_assertions, track_caller)]
181    pub fn header<K>(mut self, value: impl IntoWidget<K>) -> Self {
182        self.header = Some(value.into_widget());
183        self
184    }
185
186    /// Sets Description.
187    #[cfg_attr(debug_assertions, track_caller)]
188    pub fn description<K>(mut self, value: impl IntoWidget<K>) -> Self {
189        self.description = Some(value.into_widget());
190        self
191    }
192
193    /// Sets PlaceholderText.
194    pub fn placeholder_text(mut self, value: impl Into<String>) -> Self {
195        self.placeholder_text = value.into();
196        self
197    }
198
199    /// Sets IsEnabled.
200    pub fn is_enabled(mut self, value: bool) -> Self {
201        self.is_enabled = value;
202        self
203    }
204
205    /// Sets FontSize.
206    pub fn font_size(mut self, value: f64) -> Self {
207        self.font_size = Some(value);
208        self
209    }
210
211    /// Sets Padding.
212    pub fn padding(mut self, value: [f64; 4]) -> Self {
213        self.padding = Some(value);
214        self
215    }
216
217    /// Sets CornerRadius.
218    pub fn corner_radius(mut self, value: f64) -> Self {
219        self.corner_radius = Some(value);
220        self
221    }
222
223    /// Sets Foreground.
224    pub fn foreground(mut self, value: Color) -> Self {
225        self.foreground = Some(value);
226        self
227    }
228
229    /// Sets Background.
230    pub fn background(mut self, value: Brush) -> Self {
231        self.background = Some(value);
232        self
233    }
234
235    /// Sets BorderBrush.
236    pub fn border_brush(mut self, value: Brush) -> Self {
237        self.border_brush = Some(value);
238        self
239    }
240
241    /// Sets SelectionHighlightColor.
242    pub fn selection_highlight_color(mut self, value: Color) -> Self {
243        self.selection_highlight_color = Some(value);
244        self
245    }
246
247    /// Sets MaxLength.
248    pub fn max_length(mut self, value: i32) -> Self {
249        assert!(value >= 0, "MaxLength must be non-negative");
250        self.max_length = Some(value);
251        self
252    }
253
254    /// Sets InputFormatters.
255    pub fn input_formatters(mut self, value: Vec<TextInputFormatterRef>) -> Self {
256        self.input_formatters = value;
257        self
258    }
259
260    /// Sets Autofocus.
261    pub fn autofocus(mut self, value: bool) -> Self {
262        self.autofocus = value;
263        self
264    }
265
266    /// Sets ContextMenuBuilder.
267    pub fn context_menu_builder(
268        mut self,
269        value: impl Fn(&mut App, BuildContext, Handle<EditableTextState>) -> WidgetRef + 'static,
270    ) -> Self {
271        self.context_menu_builder = Some(Rc::new(value));
272        self
273    }
274
275    /// Sets IsReadOnly.
276    pub fn is_read_only(mut self, value: bool) -> Self {
277        self.is_read_only = value;
278        self
279    }
280
281    /// Sets AcceptsReturn.
282    pub fn accepts_return(mut self, value: bool) -> Self {
283        self.accepts_return = value;
284        self
285    }
286
287    /// Sets TextWrapping.
288    pub fn text_wrapping(mut self, value: TextWrapping) -> Self {
289        self.text_wrapping = value;
290        self
291    }
292
293    /// Sets `ScrollViewer.HorizontalScrollBarVisibility`.
294    pub fn horizontal_scroll_bar_visibility(mut self, value: ScrollBarVisibility) -> Self {
295        self.horizontal_scroll_bar_visibility = value;
296        self
297    }
298
299    /// Sets MaxLines.
300    pub fn max_lines(mut self, value: i32) -> Self {
301        self.max_lines = Some(value);
302        self
303    }
304
305    /// Sets TextAlignment.
306    pub fn text_alignment(mut self, value: TextAlign) -> Self {
307        self.text_alignment = value;
308        self
309    }
310
311    /// Whether the caret is drawn while the box has the focus: Flutter's `TextField.showCursor`.
312    pub fn show_cursor(mut self, value: bool) -> Self {
313        self.show_cursor = Some(value);
314        self
315    }
316
317    /// Sets PlaceholderForeground.
318    pub fn placeholder_foreground(mut self, value: Color) -> Self {
319        self.placeholder_foreground = Some(value);
320        self
321    }
322
323    /// Sets TextChanged.
324    pub fn text_changed(mut self, value: impl Fn(&mut App, String) + 'static) -> Self {
325        self.text_changed = Some(Rc::new(value));
326        self
327    }
328
329    /// Sets SelectionChanged.
330    pub fn selection_changed(
331        mut self,
332        value: impl Fn(&mut App, TextSelection, Option<SelectionChangedCause>) + 'static,
333    ) -> Self {
334        self.selection_changed = Some(Rc::new(value));
335        self
336    }
337
338    /// Sets widget identity.
339    pub fn key(mut self, key: KeyRef) -> Self {
340        self.key = Some(key);
341        self
342    }
343}
344
345impl fmt::Debug for TextBox {
346    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
347        f.debug_struct("TextBox")
348            .field("is_enabled", &self.is_enabled)
349            .finish_non_exhaustive()
350    }
351}
352
353impl StatefulWidget for TextBox {
354    type State = TextBoxState;
355
356    fn key(&self) -> Option<&KeyRef> {
357        self.key.as_ref()
358    }
359
360    fn create_state(&self) -> TextBoxState {
361        TextBoxState {
362            state: StateData::new(),
363        }
364    }
365}
366
367/// A `TextBox` in the tree, which a `GlobalKey` on the box reaches.
368pub struct TextBoxState {
369    state: StateData<TextBox>,
370}
371
372impl TextBoxState {
373    /// `TextBox::GetRectFromCharacterIndex` (`TextBox.cpp`): the leading or, with
374    /// `trailing_edge`, the trailing edge of the character at `char_index`, a UTF-16 index into
375    /// the text, as a rectangle of no width and the line's height, in the box's own coordinates
376    /// and where the character shows now, scrolled on either axis. `None` for an index outside
377    /// the text, the end of the text and every index of an empty box among them, where WinUI
378    /// throws `E_INVALIDARG`, and before the box is laid out.
379    pub fn get_rect_from_character_index(
380        self: Handle<Self>,
381        app: &mut App,
382        char_index: i32,
383        trailing_edge: bool,
384    ) -> Option<Rect> {
385        let length = self
386            .widget(app)
387            .controller
388            .text_value(app)
389            .encode_utf16()
390            .count();
391        if char_index < 0 || char_index as usize >= length {
392            return None;
393        }
394        let editable = self.text_control(app)?.render_editable(app)?;
395        let character = TextSelection::new(char_index, char_index + 1);
396        let boxes = editable.get_boxes_for_selection(app, character);
397        let glyph = boxes.first()?;
398        // RichEdit's `TA_LEFT` and `TA_RIGHT`: the character's left and right edges.
399        let x = if trailing_edge {
400            glyph.right
401        } else {
402            glyph.left
403        };
404        let top_left = editable
405            .as_box()
406            .local_to_global(app, Offset::new(x, glyph.top), None);
407        let own = self.context(app).find_render_object(app)?.as_box()?;
408        let local = own.global_to_local(app, top_left, None);
409        Some(Rect::from_ltwh(
410            local.dx(),
411            local.dy(),
412            0.0,
413            glyph.bottom - glyph.top,
414        ))
415    }
416
417    /// The shared editor this box builds.
418    fn text_control(self: Handle<Self>, app: &App) -> Option<Handle<TextControlState>> {
419        let mut found = None;
420        self.context(app).visit_child_elements(app, &mut |child| {
421            found = child.state_handle::<TextControlState>(app);
422        });
423        found
424    }
425}
426
427impl State for TextBoxState {
428    type Widget = TextBox;
429    waft_widgets::state_accessors!();
430
431    fn build(self: Handle<Self>, app: &mut App, _context: BuildContext) -> WidgetRef {
432        TextControl::new(self.widget(app).clone(), None).into_widget()
433    }
434}