denise-ui 0.0.1

Scene graph, widgets and compositor for Denise.
Documentation
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
//! A single-line editable text field.

use alloc::string::String;

use denise::{ElementState, InputEvent, KeyCode, Point, Radius, Rect, Role};
use denise_render::Canvas;
use denise_text::{TextEngine, TextStyle};

use crate::widget::{Animation, Event, EventCtx, Handled, PaintCtx, VisualState, Widget};
use crate::widgets::style::{Align, focus_ring, interactive_pair};

/// Half-period of the caret blink, in milliseconds.
const BLINK_MS: u64 = 500;

/// A single-line text field with a caret.
///
/// # What it does not do
///
/// No selection, no clipboard, no undo, no word motion. A kiosk field takes a
/// name, a PIN or a setpoint; the machinery those omissions would need is real
/// work that belongs with proper text handling in M4, and half of it is
/// meaningless without a font that can measure a substring.
///
/// # Blinking
///
/// The caret blinks only while the field has focus, and the tree only asks the
/// focused widget to animate. An unfocused panel therefore has nothing running on
/// a timer at all, which is the difference between a device that idles and one
/// that keeps a core awake for its whole service life. Typing resets the phase so
/// the caret stays solid while it is moving.
///
/// A blink damages the whole field rather than the caret, because
/// [`Widget::animate`] reports *that* something changed, not *where*. On a Pi 3
/// that is 26 kpx twice a second — 58 µs, or 0.35% of one 60 Hz frame — against
/// the 32 px the caret actually occupies. The 800× coarseness is real and the
/// cost of removing it is a wider trait; the measurement is why it has not been
/// paid.
#[derive(Clone, Debug)]
pub struct TextInput<M> {
    text: String,
    placeholder: String,
    /// Caret position as a **character** index, not a byte offset.
    caret: usize,
    /// First character drawn, for fields wider than their box.
    first_visible: usize,
    max_chars: usize,
    style: TextStyle,
    radius: Radius,
    submit: Option<M>,
    password: bool,
    blink_epoch: u64,
    caret_on: bool,
}

impl<M> TextInput<M> {
    /// An empty field.
    pub fn new() -> Self {
        Self {
            text: String::new(),
            placeholder: String::new(),
            caret: 0,
            first_visible: 0,
            max_chars: 256,
            style: TextStyle::built_in(16),
            radius: Radius::Field,
            submit: None,
            password: false,
            blink_epoch: 0,
            caret_on: true,
        }
    }

    /// Sets the text shown when the field is empty.
    pub fn with_placeholder(mut self, placeholder: impl Into<String>) -> Self {
        self.placeholder = placeholder.into();
        self
    }

    /// Sets the message emitted when Enter is pressed.
    pub fn with_submit(mut self, message: M) -> Self {
        self.submit = Some(message);
        self
    }

    /// Caps the number of characters the field will hold.
    pub fn with_max_chars(mut self, max: usize) -> Self {
        self.max_chars = max;
        self
    }

    /// Sets the font and size.
    pub fn with_style(mut self, style: TextStyle) -> Self {
        self.style = style;
        self
    }

    /// Sets the size, keeping the font.
    pub fn with_size(mut self, size_px: u16) -> Self {
        self.style.size_px = size_px;
        self
    }

    /// The font and size this field draws in.
    #[inline]
    pub const fn style(&self) -> TextStyle {
        self.style
    }

    /// Draws every character as `*`. The text is still stored in the clear —
    /// this hides a PIN from someone standing behind the panel, and nothing more.
    pub fn with_password(mut self, password: bool) -> Self {
        self.password = password;
        self
    }

    /// The current contents.
    #[inline]
    pub fn text(&self) -> &str {
        &self.text
    }

    /// Replaces the contents, putting the caret at the end.
    pub fn set_text(&mut self, text: impl Into<String>) {
        self.text = text.into();
        self.caret = self.len_chars();
        self.first_visible = 0;
    }

    /// Empties the field.
    pub fn clear(&mut self) {
        self.set_text(String::new());
    }

    /// Caret position, as a character index.
    #[inline]
    pub const fn caret(&self) -> usize {
        self.caret
    }

    #[inline]
    fn len_chars(&self) -> usize {
        self.text.chars().count()
    }

    /// Byte offset of character `index`, or the end of the string.
    fn byte_of(&self, index: usize) -> usize {
        self.text
            .char_indices()
            .nth(index)
            .map_or(self.text.len(), |(offset, _)| offset)
    }

    /// Horizontal padding inside the field's bounds.
    #[inline]
    const fn pad(&self) -> i32 {
        self.style.size_px as i32 / 3
    }

    /// The field's inner rectangle, inside the padding.
    fn inner(&self, bounds: Rect) -> Rect {
        Rect::from_edges(
            bounds.x + self.pad(),
            bounds.y,
            bounds.right() - self.pad(),
            bounds.bottom(),
        )
    }

    /// Width of characters `from..to` as they are displayed.
    ///
    /// Measured rather than counted. With a proportional font a caret placed by
    /// multiplying an index by an advance is wrong everywhere except after the
    /// first character, and wrong in a way that looks like a rendering glitch
    /// rather than an arithmetic mistake.
    fn run_width(&self, engine: &mut TextEngine, from: usize, to: usize) -> i32 {
        if from >= to {
            return 0;
        }
        if self.password {
            return engine.measure_line(self.style, "*") * (to - from) as i32;
        }
        let (start, end) = (self.byte_of(from), self.byte_of(to));
        engine.measure_line(self.style, &self.text[start..end])
    }

    /// First character to draw, given where the caret is and how wide the box is.
    fn window_start(&self, engine: &mut TextEngine, bounds: Rect) -> usize {
        let available = self.inner(bounds).width;
        let mut first = self.first_visible.min(self.caret);
        // Walks rather than bisects: a kiosk field holds a name or a setpoint, and
        // the loop runs once per character that scrolled off since last frame,
        // which is almost always one.
        while first < self.caret && self.run_width(engine, first, self.caret) > available {
            first += 1;
        }
        first
    }

    /// Horizontal offset of the caret from the field's left edge.
    ///
    /// Measured, not counted — see [`TextInput::run_width`].
    pub fn caret_x(&self, engine: &mut TextEngine, bounds: Rect) -> i32 {
        let first = self.window_start(engine, bounds);
        self.pad() + self.run_width(engine, first, self.caret)
    }

    fn scroll_to_caret(&mut self, engine: &mut TextEngine, bounds: Rect) {
        self.first_visible = self.window_start(engine, bounds);
    }

    /// Restarts the blink so the caret is solid while it is being moved.
    fn wake_caret(&mut self, now_ms: u64) {
        self.blink_epoch = now_ms;
        self.caret_on = true;
    }

    fn insert(&mut self, ch: char) -> bool {
        if self.len_chars() >= self.max_chars {
            return false;
        }
        let at = self.byte_of(self.caret);
        self.text.insert(at, ch);
        self.caret += 1;
        true
    }

    fn delete_before(&mut self) -> bool {
        if self.caret == 0 {
            return false;
        }
        let at = self.byte_of(self.caret - 1);
        self.text.remove(at);
        self.caret -= 1;
        true
    }

    fn delete_after(&mut self) -> bool {
        if self.caret >= self.len_chars() {
            return false;
        }
        let at = self.byte_of(self.caret);
        self.text.remove(at);
        true
    }
}

impl<M> Default for TextInput<M> {
    fn default() -> Self {
        Self::new()
    }
}

impl<M: Clone + 'static> Widget<M> for TextInput<M> {
    fn paint(&self, ctx: &mut PaintCtx<'_>, canvas: &mut Canvas<'_>) {
        let radius = ctx.theme.radius(self.radius);
        let disabled = ctx.state.contains(VisualState::DISABLED);
        let focused = ctx.state.contains(VisualState::FOCUSED);
        let (background, _) = interactive_pair(ctx.theme, Role::Base100, ctx.state);
        canvas.fill_rounded_rect(ctx.bounds, radius, background);
        canvas.stroke_rounded_rect(ctx.bounds, radius, 1, ctx.theme.color(Role::Base300));
        if focused {
            focus_ring(ctx.theme, ctx.bounds, radius, canvas);
        }

        let inner = self.inner(ctx.bounds);
        let line_height = ctx.text.line_height(self.style);
        let top = inner.y + Align::Center.offset(inner.height, line_height);
        // Text is clipped to the inner box, so a value longer than the field
        // scrolls under the border rather than over it.
        let mut clipped = canvas.with_clip(inner);

        if self.text.is_empty() {
            if !self.placeholder.is_empty() {
                let hint = ctx
                    .theme
                    .color(Role::Base300)
                    .mix(ctx.theme.color(Role::BaseContent), 128);
                ctx.text.draw(
                    &mut clipped,
                    self.style,
                    Point::new(inner.x, top),
                    &self.placeholder,
                    hint,
                );
            }
        } else {
            let content = if disabled {
                ctx.theme.color(Role::Base300)
            } else {
                ctx.theme.color(Role::BaseContent)
            };
            let first = self.window_start(ctx.text, ctx.bounds);
            if self.password {
                // Drawn one at a time rather than by building a string of stars,
                // because a paint path that allocates is a paint path that can
                // fail on a device with no memory left.
                let advance = ctx.text.measure_line(self.style, "*");
                let count = self.len_chars().saturating_sub(first);
                for i in 0..count {
                    let x = inner.x + advance * i as i32;
                    if x > inner.right() {
                        break;
                    }
                    ctx.text
                        .draw(&mut clipped, self.style, Point::new(x, top), "*", content);
                }
            } else {
                let start = self.byte_of(first);
                ctx.text.draw(
                    &mut clipped,
                    self.style,
                    Point::new(inner.x, top),
                    &self.text[start..],
                    content,
                );
            }
        }

        if focused && self.caret_on && !disabled {
            let first = self.window_start(ctx.text, ctx.bounds);
            let x = inner.x + self.run_width(ctx.text, first, self.caret);
            let width = (i32::from(self.style.size_px) / 10).max(1);
            clipped.fill_rect(
                Rect::new(x, top, width, line_height),
                ctx.theme.color(Role::Accent),
            );
        }
    }

    fn on_event(&mut self, event: &Event<'_>, ctx: &mut EventCtx<'_, M>) -> Handled {
        match event {
            Event::FocusGained | Event::FocusLost => {
                self.wake_caret(ctx.now_ms);
                // Not `Handled`: nothing was consumed. The tree already repaints
                // on a focus change, so the caret appearing is covered.
                Handled::No
            }
            Event::Input(InputEvent::Text { ch }) if !ch.is_control() => {
                if self.insert(*ch) {
                    self.wake_caret(ctx.now_ms);
                    let bounds = ctx.bounds;
                    self.scroll_to_caret(ctx.text, bounds);
                    Handled::Yes
                } else {
                    Handled::No
                }
            }
            Event::Input(InputEvent::Key {
                code,
                state: ElementState::Down,
                ..
            }) => {
                let changed = match code {
                    KeyCode::Backspace => self.delete_before(),
                    KeyCode::Delete => self.delete_after(),
                    KeyCode::ArrowLeft => {
                        let moved = self.caret > 0;
                        self.caret = self.caret.saturating_sub(1);
                        moved
                    }
                    KeyCode::ArrowRight => {
                        let moved = self.caret < self.len_chars();
                        self.caret = (self.caret + 1).min(self.len_chars());
                        moved
                    }
                    KeyCode::Home => {
                        let moved = self.caret != 0;
                        self.caret = 0;
                        moved
                    }
                    KeyCode::End => {
                        let moved = self.caret != self.len_chars();
                        self.caret = self.len_chars();
                        moved
                    }
                    KeyCode::Enter | KeyCode::NumpadEnter => {
                        if let Some(message) = self.submit.clone() {
                            ctx.emit(message);
                        }
                        // Consumed either way: Enter in a field must not fall
                        // through and activate something else.
                        return Handled::Yes;
                    }
                    _ => return Handled::No,
                };
                self.wake_caret(ctx.now_ms);
                let bounds = ctx.bounds;
                self.scroll_to_caret(ctx.text, bounds);
                // Even a caret move that changed nothing must repaint, because the
                // caret itself is pixels.
                let _ = changed;
                Handled::Yes
            }
            _ => Handled::No,
        }
    }

    fn accepts_pointer(&self) -> bool {
        true
    }

    fn focusable(&self) -> bool {
        true
    }

    fn animate(&mut self, now_ms: u64) -> Animation {
        let elapsed = now_ms.saturating_sub(self.blink_epoch);
        let on = (elapsed / BLINK_MS).is_multiple_of(2);
        let repaint = on != self.caret_on;
        self.caret_on = on;
        Animation {
            repaint,
            next_ms: Some(self.blink_epoch + (elapsed / BLINK_MS + 1) * BLINK_MS),
        }
    }
}