rust_widgets 2.3.1

Pure Rust cross-platform native GUI library with hardware-adaptive rendering, 60+ widgets, touch/gesture support, i18n, and SVG-pipeline-accurate output
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
// SPDX-FileCopyrightText: Copyright (c) 2026 Mike Li/Mikewolfli/Wei Li(mikewolfli@163.com)
// SPDX-License-Identifier: MIT

//! Input dialog widget.
use crate::core::{Color, Font, HorizontalAlignment, Point, Rect, Size};
use crate::event::{Event, EventHandler};
use crate::impl_widget_property_hooks;
use crate::property_names_of;
use crate::render::RenderContext;
use crate::signal::{GenericSignal, Signal1};
use crate::tr;
use crate::widget::capability::coercion::expect_string;
use crate::widget::capability::properties_trait::{base_property_get, base_property_set};
use crate::widget::capability::types::{CapabilityAccessError, CapabilityValue};
use crate::widget::capability::WidgetProperties;
use crate::widget::{BaseWidget, Draw, Widget, WidgetKind};
/// Input dialog input mode.
///
/// The mode selects which of the dialog's parallel value slots the input field
/// displays and edits; the other slots keep their values but are not shown.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum InputMode {
    /// Free text, edited through [`InputDialog::text_value`].
    Text,
    /// A whole number, clamped to the `int_min`/`int_max` range set by
    /// [`InputDialog::get_int`] and stepped by `int_step`.
    Integer,
    /// A real number, clamped to the `double_min`/`double_max` range and shown
    /// rounded to `double_decimals` places.
    Double,
    /// A choice from [`InputDialog::items`], navigated by
    /// [`InputDialog::current_item`].
    Item,
}
/// Input dialog for simple user input.
pub struct InputDialog {
    base: BaseWidget,
    modal: bool,
    title: String,
    label_text: String,
    mode: InputMode,
    text_value: String,
    int_value: i64,
    double_value: f64,
    items: Vec<String>,
    current_item: usize,
    int_min: i64,
    int_max: i64,
    int_step: i64,
    double_min: f64,
    double_max: f64,
    _double_step: f64,
    double_decimals: u8,
    /// Emitted when the text value changes. Nothing in this widget emits it
    /// yet — editing happens elsewhere and calls [`InputDialog::set_text_value`]
    /// — so it is for a host that drives the field.
    pub text_value_changed: Signal1<String>,
    /// Emitted when the integer value changes. Not emitted by this widget yet;
    /// see [`InputDialog::text_value_changed`].
    pub int_value_changed: Signal1<i64>,
    /// Emitted when the floating-point value changes. Not emitted by this widget
    /// yet; see [`InputDialog::text_value_changed`].
    pub double_value_changed: Signal1<f64>,
    /// Emitted by [`InputDialog::accept`].
    pub accepted: GenericSignal,
    /// Emitted by [`InputDialog::reject`].
    pub rejected: GenericSignal,
}
impl InputDialog {
    /// Creates a modal, empty dialog in [`InputMode::Text`].
    ///
    /// The title and label are empty, the item list is empty, and the numeric
    /// ranges are left wide open (the full `i64`/`f64` ranges, step 1). Set what
    /// you need afterwards, or use one of the configured constructors.
    pub fn new(geometry: Rect) -> Self {
        Self {
            base: BaseWidget::new(WidgetKind::InputDialog, geometry, "InputDialog"),
            modal: true,
            title: String::new(),
            label_text: String::new(),
            mode: InputMode::Text,
            text_value: String::new(),
            int_value: 0,
            double_value: 0.0,
            items: Vec::new(),
            current_item: 0,
            int_min: i64::MIN,
            int_max: i64::MAX,
            int_step: 1,
            double_min: f64::MIN,
            double_max: f64::MAX,
            _double_step: 1.0,
            double_decimals: 1,
            text_value_changed: Signal1::new(),
            int_value_changed: Signal1::new(),
            double_value_changed: Signal1::new(),
            accepted: GenericSignal::new(),
            rejected: GenericSignal::new(),
        }
    }
    /// Creates a text-input dialog with its title, label and initial text
    /// preset, in [`InputMode::Text`].
    ///
    /// `default` seeds [`InputDialog::text_value`]; it is not a placeholder — an
    /// empty `default` means the field opens genuinely empty.
    pub fn get_text(
        geometry: Rect,
        title: impl Into<String>,
        label: impl Into<String>,
        default: impl Into<String>,
    ) -> Self {
        let mut d = Self::new(geometry);
        d.title = title.into();
        d.label_text = label.into();
        d.text_value = default.into();
        d.mode = InputMode::Text;
        d
    }
    /// Creates a whole-number dialog preset to `value`, bounded by `min` and
    /// `max`, in [`InputMode::Integer`].
    ///
    /// `value` is clamped into the inclusive range as the dialog is built, so a
    /// request outside it is silently brought inside; read
    /// [`InputDialog::int_value`] to see what was actually taken. `step` is stored
    /// but nothing in this widget applies increments, so it does not affect the
    /// value.
    pub fn get_int(
        geometry: Rect,
        title: impl Into<String>,
        label: impl Into<String>,
        value: i64,
        min: i64,
        max: i64,
        step: i64,
    ) -> Self {
        let mut d = Self::new(geometry);
        d.title = title.into();
        d.label_text = label.into();
        d.int_value = value.clamp(min, max);
        d.int_min = min;
        d.int_max = max;
        d.int_step = step;
        d.mode = InputMode::Integer;
        d
    }
    /// The dialog's title, drawn in its header bar.
    pub fn title(&self) -> &str {
        &self.title
    }
    /// The text drawn beside the input field to say what is being asked for.
    pub fn label_text(&self) -> &str {
        &self.label_text
    }
    /// Which value the input field currently presents.
    pub fn mode(&self) -> InputMode {
        self.mode
    }
    /// The free-text value. This is the value the caller cares about after an
    /// [`InputMode::Text`] dialog is accepted; it exists in every mode but is
    /// only displayed in `Text`.
    pub fn text_value(&self) -> &str {
        &self.text_value
    }
    /// The whole-number value, clamped to the `int_min`/`int_max` range.
    ///
    /// Read this after an [`InputMode::Integer`] dialog is accepted. It holds a
    /// meaningful value in every mode, but only the `Integer` mode displays it.
    pub fn int_value(&self) -> i64 {
        self.int_value
    }
    /// The floating-point value, clamped to the `double_min`/`double_max` range.
    ///
    /// Stays `0.0` unless set: no constructor here seeds it, and it is only
    /// displayed in [`InputMode::Double`].
    pub fn double_value(&self) -> f64 {
        self.double_value
    }
    /// The index of the selected item, or `0` when there are no items.
    ///
    /// Always an index, never an optional — check [`InputDialog::items`] to tell
    /// "nothing to choose from" from "the first item is chosen".
    pub fn current_item(&self) -> usize {
        self.current_item
    }
    /// The choices offered in [`InputMode::Item`]. Empty unless
    /// [`InputDialog::set_items`] was called.
    pub fn items(&self) -> &[String] {
        &self.items
    }

    /// The selected item's text, or `None` when the list is empty or the index
    /// no longer addresses an entry.
    pub fn current_item_text(&self) -> Option<&str> {
        self.items.get(self.current_item).map(|s| s.as_str())
    }
    /// Sets the title and repaints.
    pub fn set_title(&mut self, t: impl Into<String>) {
        self.title = t.into();
        self.base.request_redraw();
    }
    /// Sets the label drawn beside the input field and repaints.
    pub fn set_label_text(&mut self, t: impl Into<String>) {
        self.label_text = t.into();
        self.base.request_redraw();
    }
    /// Switches which value the input field presents, and repaints.
    ///
    /// The other values are unaffected: switching away from a mode does not
    /// clear what it held, so switching back shows it again.
    pub fn set_mode(&mut self, mode: InputMode) {
        self.mode = mode;
        self.base.request_redraw();
    }
    /// Sets the free-text value and repaints. Overwrites rather than appends, so
    /// it cannot be used for incremental typing.
    ///
    /// Emits [`Self::text_value_changed`] when the value actually differs. The
    /// signal is named `_changed`, so emitting on a no-op write would be a lie: a
    /// caller using it to drive an expensive downstream update would run that
    /// update for a write that changed nothing.
    pub fn set_text_value(&mut self, v: impl Into<String>) {
        let value = v.into();
        if value == self.text_value {
            return;
        }
        self.text_value = value;
        self.base.request_redraw();
        self.text_value_changed.emit(self.text_value.clone());
    }
    /// Replaces the item list and repaints.
    ///
    /// Resets the selection to index 0, so a previously chosen item is lost even
    /// if it is still present in the new list.
    pub fn set_items(&mut self, items: Vec<String>) {
        self.items = items;
        self.current_item = 0;
        self.base.request_redraw();
    }
    /// Sets the whole-number value, clamped into the current
    /// `int_min`/`int_max` range, and repaints.
    ///
    /// Emits [`Self::int_value_changed`] when the *stored* value changes, so a
    /// request that was clamped back to what was already there is not reported as
    /// a change.
    pub fn set_int_value(&mut self, v: i64) {
        let clamped = v.clamp(self.int_min, self.int_max);
        if clamped == self.int_value {
            return;
        }
        self.int_value = clamped;
        self.base.request_redraw();
        self.int_value_changed.emit(self.int_value);
    }

    /// Sets the floating-point value, clamped into the current
    /// `double_min`/`double_max` range, and repaints.
    ///
    /// A `NaN` is rejected without touching the stored value: it cannot be clamped
    /// into a range (every comparison is false), so accepting it would leave the
    /// control outside its own declared bounds. Emits
    /// [`Self::double_value_changed`] on a real change.
    pub fn set_double_value(&mut self, v: f64) {
        if v.is_nan() {
            return;
        }
        let clamped = v.clamp(self.double_min, self.double_max);
        if clamped == self.double_value {
            return;
        }
        self.double_value = clamped;
        self.base.request_redraw();
        self.double_value_changed.emit(self.double_value);
    }
    /// Whether the dialog blocks interaction with its owner while open.
    ///
    /// A stored flag, on by default: nothing here enforces modality, so the host
    /// is what must act on it.
    pub fn is_modal(&self) -> bool {
        self.modal
    }
    /// Sets the modality flag and repaints. See [`InputDialog::is_modal`].
    pub fn set_modal(&mut self, modal: bool) {
        self.modal = modal;
        self.base.request_redraw();
    }
    /// Confirms the dialog: emits `accepted`, then hides it.
    ///
    /// Unlike the file dialog this does not emit the value: the caller reads
    /// [`InputDialog::text_value`], [`InputDialog::int_value`],
    /// [`InputDialog::double_value`] or [`InputDialog::current_item`] according
    /// to [`InputDialog::mode`]. Pressing Enter (key code 13) on an enabled,
    /// visible dialog does the same.
    pub fn accept(&mut self) {
        self.accepted.emit();
        self.hide();
    }
    /// Cancels the dialog and hides it, emitting `rejected`.
    ///
    /// The values are **not** cleared, so a cancelled dialog still reports what
    /// was in its fields. Pressing Escape (key code 27) has the same effect.
    pub fn reject(&mut self) {
        self.rejected.emit();
        self.hide();
    }
}
impl Widget for InputDialog {
    fn base(&self) -> &BaseWidget {
        &self.base
    }

    fn base_mut(&mut self) -> &mut BaseWidget {
        &mut self.base
    }

    fn size_hint(&self) -> Size {
        crate::core::Size::new(350, 150)
    }

    /// Reports this widget as the object that paints it.
    ///
    /// `InputDialog` implements `Draw`, so `Some(self)` is total and cannot be
    /// wrong.
    fn as_draw_mut(&mut self) -> Option<&mut dyn crate::widget::Draw> {
        Some(self)
    }

    impl_widget_property_hooks!();
}

/// `InputDialog`'s property contract.
///
/// Read semantics are carried over unchanged from the centralised
/// `access_read_dialog.in.rs` dispatch. Both properties are read-only: the old
/// write layer had no arm for this kind.
impl WidgetProperties for InputDialog {
    fn get(&self, name: &str) -> Result<CapabilityValue, CapabilityAccessError> {
        match name {
            "title" => Ok(CapabilityValue::String(self.title().to_string())),
            "label_text" => Ok(CapabilityValue::String(self.label_text().to_string())),
            _ => base_property_get(self, name),
        }
    }

    fn set(&mut self, name: &str, value: CapabilityValue) -> Result<(), CapabilityAccessError> {
        match name {
            "title" => {
                self.set_title(expect_string(value)?);
                Ok(())
            }
            "label_text" => {
                self.set_label_text(expect_string(value)?);
                Ok(())
            }
            _ => base_property_set(self, name, value),
        }
    }

    fn property_names(&self) -> &'static [&'static str] {
        property_names_of!["title", "label_text", BASE_PROPERTY_NAMES]
    }
}
impl EventHandler for InputDialog {
    fn handle_event(&mut self, event: &Event) {
        self.base.handle_event(event);
        if !self.base.is_enabled() {
            return;
        }
        if let Event::KeyPress { key, .. } = event {
            if *key == 13 {
                self.accept();
            } else if *key == 27 {
                self.reject();
            }
        }
    }
}
impl Draw for InputDialog {
    fn draw(&mut self, context: &mut RenderContext) {
        let rect = self.geometry();
        context.fill_rect(
            Rect::new(rect.x, rect.y, rect.width, rect.height),
            Color::rgb(245, 245, 245),
        );
        context.draw_rect(
            Rect::new(rect.x, rect.y, rect.width, rect.height),
            Color::rgb(160, 160, 160),
        );
        context.fill_rect(Rect::new(rect.x, rect.y, rect.width, 28), Color::rgb(0, 120, 215));
        context.draw_text(
            Point::new(rect.x + 8, rect.y + 14),
            &self.title,
            &Font::default(),
            Color::rgb(255, 255, 255),
            HorizontalAlignment::Left,
        );
        // Label
        context.draw_text(
            Point::new(rect.x + 10, rect.y + 48),
            &self.label_text,
            &Font::default(),
            Color::rgb(0, 0, 0),
            HorizontalAlignment::Left,
        );
        // Input field
        let input_y = rect.y + 60;
        context.fill_rect(
            Rect::new(rect.x + 10, input_y, rect.width.saturating_sub(20), 26),
            Color::rgb(255, 255, 255),
        );
        context.draw_rect(
            Rect::new(rect.x + 10, input_y, rect.width.saturating_sub(20), 26),
            Color::rgb(150, 150, 150),
        );
        let display_text = match self.mode {
            InputMode::Text => self.text_value.clone(),
            InputMode::Integer => self.int_value.to_string(),
            InputMode::Double => {
                format!("{:.prec$}", self.double_value, prec = self.double_decimals as usize)
            }
            InputMode::Item => self.current_item_text().unwrap_or("").to_string(),
        };
        context.draw_text(
            Point::new(rect.x + 14, input_y + 13),
            &display_text,
            &Font::default(),
            Color::rgb(0, 0, 0),
            HorizontalAlignment::Left,
        );
        // OK/Cancel
        let btn_y = rect.y as f32 + rect.height as f32 - 40.0;
        context.fill_rect(
            Rect::new(rect.x + rect.width as i32 - 176, btn_y as i32, 80, 28),
            Color::rgb(0, 120, 215),
        );
        context.draw_text(
            Point::new(rect.x + rect.width as i32 - 136, (btn_y + 14.0) as i32),
            &tr!("common.button.ok"),
            &Font::default(),
            Color::rgb(255, 255, 255),
            HorizontalAlignment::Left,
        );
        context.fill_rect(
            Rect::new(rect.x + rect.width as i32 - 88, btn_y as i32, 80, 28),
            Color::rgb(225, 225, 225),
        );
        context.draw_rect(
            Rect::new(rect.x + rect.width as i32 - 88, btn_y as i32, 80, 28),
            Color::rgb(100, 100, 100),
        );
        context.draw_text(
            Point::new(rect.x + rect.width as i32 - 48, (btn_y + 14.0) as i32),
            &tr!("common.button.cancel"),
            &Font::default(),
            Color::rgb(0, 0, 0),
            HorizontalAlignment::Left,
        );
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::event::Event;
    use std::sync::{Arc, Mutex};

    #[test]
    fn get_int_clamps_and_sets_integer_mode() {
        let dialog = InputDialog::get_int(Rect::new(0, 0, 320, 180), "T", "L", 500, 0, 100, 5);
        assert_eq!(dialog.mode(), InputMode::Integer);
        assert_eq!(dialog.int_value(), 100);
    }

    #[test]
    fn enter_and_escape_emit_accept_reject() {
        let mut dialog = InputDialog::new(Rect::new(0, 0, 320, 180));
        let accepted = Arc::new(Mutex::new(0usize));
        let rejected = Arc::new(Mutex::new(0usize));

        let a = Arc::clone(&accepted);
        dialog.accepted.connect(move || {
            if let Ok(mut n) = a.lock() {
                *n += 1;
            }
        });

        let r = Arc::clone(&rejected);
        dialog.rejected.connect(move || {
            if let Ok(mut n) = r.lock() {
                *n += 1;
            }
        });

        dialog.show();
        dialog.handle_event(&Event::key_press(13, 0));
        assert_eq!(*accepted.lock().expect("accepted lock"), 1);
        assert!(!dialog.is_visible());

        dialog.show();
        dialog.handle_event(&Event::key_press(27, 0));
        assert_eq!(*rejected.lock().expect("rejected lock"), 1);
        assert!(!dialog.is_visible());
    }
}