embedded-graphics-keyboard 0.2.1

no_std on-screen keyboard and text field widgets for embedded-graphics, driven by buttons or touch
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
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
//! Single-line text field with an optional title above its frame.

use embedded_graphics::{
    Drawable,
    draw_target::{DrawTarget, DrawTargetExt},
    geometry::{AnchorPoint, Dimensions, Point, Size},
    pixelcolor::PixelColor,
    primitives::{Primitive, PrimitiveStyle, Rectangle},
};

use crate::style::{FontStyle, FrameStyle};

/// Text cursor appearance.
///
/// ```
/// # use embedded_graphics::{pixelcolor::Rgb565, prelude::*};
/// # use embedded_graphics_keyboard::CursorStyle;
/// let cursor = CursorStyle::new(Rgb565::YELLOW).with_width(2).with_gap(2);
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct CursorStyle<C> {
    /// Bar color.
    pub color: C,
    /// Bar thickness in pixels.
    pub width: u32,
    /// Gap in pixels between the character before the cursor and the cursor.
    pub gap: u32,
}

impl<C: PixelColor> CursorStyle<C> {
    /// Creates a 1 px wide cursor of `color`, 1 px after the previous character.
    #[must_use]
    pub const fn new(color: C) -> Self {
        Self {
            color,
            width: 1,
            gap: 1,
        }
    }

    /// Sets the bar thickness.
    #[must_use]
    pub const fn with_width(mut self, width: u32) -> Self {
        self.width = width;
        self
    }

    /// Sets the gap between the character before the cursor and the cursor.
    #[must_use]
    pub const fn with_gap(mut self, gap: u32) -> Self {
        self.gap = gap;
        self
    }
}

/// Appearance of a [`TextField`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct TextFieldStyle<C, S> {
    /// Frame around the value.
    pub frame: FrameStyle<C>,
    /// Font of the value.
    pub font: S,
    /// Font of the title.
    pub title_font: S,
    /// Vertical gap in pixels between the title and the frame.
    pub title_gap: u32,
    /// Margin in pixels between the frame border and the text.
    pub padding: u32,
    /// Cursor drawn in the text, or `None` for no cursor.
    pub cursor: Option<CursorStyle<C>>,
}

impl<C: PixelColor, S> TextFieldStyle<C, S> {
    /// Creates a style with an invisible frame, `title_gap = 4`, `padding = 8` and no cursor.
    #[must_use]
    pub const fn new(font: S, title_font: S) -> Self {
        Self {
            frame: FrameStyle::new(),
            font,
            title_font,
            title_gap: 4,
            padding: 8,
            cursor: None,
        }
    }

    /// Sets the frame style.
    #[must_use]
    pub const fn with_frame(mut self, frame: FrameStyle<C>) -> Self {
        self.frame = frame;
        self
    }

    /// Sets the gap between the title and the frame.
    #[must_use]
    pub const fn with_title_gap(mut self, gap: u32) -> Self {
        self.title_gap = gap;
        self
    }

    /// Sets the margin between the frame border and the text.
    #[must_use]
    pub const fn with_padding(mut self, padding: u32) -> Self {
        self.padding = padding;
        self
    }

    /// Sets the cursor style.
    #[must_use]
    pub const fn with_cursor(mut self, cursor: CursorStyle<C>) -> Self {
        self.cursor = Some(cursor);
        self
    }
}

impl<C: PixelColor, S: FontStyle<C>> TextFieldStyle<C, S> {
    /// Height of a field fitting one line of text, with `padding` above and
    /// below it, and the title if `with_title` is `true`.
    ///
    /// Use it to size the `bounds` of a [`TextField`].
    #[must_use]
    pub fn height(&self, with_title: bool) -> u32 {
        let title = if with_title {
            (self.title_font.measure(REFERENCE_TEXT).height).saturating_add(self.title_gap)
        } else {
            0
        };
        let margins = self
            .padding
            .saturating_add(self.frame.effective_border_width())
            .saturating_mul(2);
        title
            .saturating_add(self.font.measure(REFERENCE_TEXT).height)
            .saturating_add(margins)
    }
}

/// Text with an ascender and a descender, measured to get the line height of a font.
const REFERENCE_TEXT: &str = "Ag";

/// Drawable single-line text field: an optional title, then a framed value.
///
/// Like `embedded_graphics::text::Text`, it is a short-lived view built every frame
/// from the current value.
///
/// The cursor is drawn at the end of the value, or at the position given to
/// [`TextField::with_cursor_position`]. When the value is wider than the field,
/// it is scrolled so that its end stays visible, unless that would hide the cursor.
/// The field keeps no state, so the scroll only depends on the value and the
/// cursor: moving the cursor left in a long value keeps it on the left edge.
///
/// Nothing is drawn outside `bounds`: a title or value too long is cut.
#[derive(Debug, Clone, Copy)]
pub struct TextField<'a, C, S> {
    bounds: Rectangle,
    value: &'a str,
    title: Option<&'a str>,
    show_cursor: bool,
    cursor_position: Option<usize>,
    style: &'a TextFieldStyle<C, S>,
}

impl<'a, C, S> TextField<'a, C, S>
where
    C: PixelColor,
    S: FontStyle<C>,
{
    /// Creates a field occupying `bounds` (title included) showing `value`.
    #[must_use]
    pub const fn new(bounds: Rectangle, value: &'a str, style: &'a TextFieldStyle<C, S>) -> Self {
        Self {
            bounds,
            value,
            title: None,
            show_cursor: true,
            cursor_position: None,
            style,
        }
    }

    /// Displays `title` above the frame.
    #[must_use]
    pub const fn with_title(mut self, title: &'a str) -> Self {
        self.title = Some(title);
        self
    }

    /// Shows or hides the cursor (e.g. to make it blink).
    #[must_use]
    pub const fn with_cursor_visible(mut self, visible: bool) -> Self {
        self.show_cursor = visible;
        self
    }

    /// Draws the cursor before the byte at `index` of the value, instead of at its end.
    ///
    /// `index` is clamped to the length of the value and moved back to the start
    /// of the character it falls in, so it is the index to give to
    /// `String::insert` and `String::remove`.
    #[must_use]
    pub const fn with_cursor_position(mut self, index: usize) -> Self {
        self.cursor_position = Some(index);
        self
    }

    /// Byte index of the cursor in the value, on a character boundary.
    fn cursor_index(&self) -> usize {
        let mut index = self
            .cursor_position
            .map_or(self.value.len(), |i| i.min(self.value.len()));
        while !self.value.is_char_boundary(index) {
            index -= 1;
        }
        index
    }

    /// Height taken by the title and its gap (`0` without title).
    fn title_height(&self) -> u32 {
        self.title.map_or(0, |title| {
            (self.style.title_font.measure(title).height).saturating_add(self.style.title_gap)
        })
    }

    /// Bounds of the frame, i.e. the field minus the title area.
    #[must_use]
    pub fn frame_bounds(&self) -> Rectangle {
        let title_h = self.title_height().min(self.bounds.size.height);
        Rectangle::new(
            self.bounds.top_left + Point::new(0, title_h as i32),
            Size::new(self.bounds.size.width, self.bounds.size.height - title_h),
        )
    }
}

impl<C, S> Dimensions for TextField<'_, C, S> {
    fn bounding_box(&self) -> Rectangle {
        self.bounds
    }
}

impl<C, S> Drawable for TextField<'_, C, S>
where
    C: PixelColor,
    S: FontStyle<C>,
{
    type Color = C;
    type Output = ();

    fn draw<D: DrawTarget<Color = C>>(&self, target: &mut D) -> Result<(), D::Error> {
        let style = self.style;

        if let Some(title) = self.title {
            style.title_font.draw_anchored(
                &mut target.clipped(&self.bounds),
                title,
                self.bounds.top_left,
                AnchorPoint::TopLeft,
            )?;
        }

        let frame = self.frame_bounds();
        style.frame.draw(target, frame)?;

        let content = style.frame.content_area(frame);
        let content = Rectangle::new(
            content.top_left + Point::new(style.padding as i32, 0),
            Size::new(
                content
                    .size
                    .width
                    .saturating_sub(style.padding.saturating_mul(2)),
                content.size.height,
            ),
        );

        let cursor = style.cursor.filter(|_| self.show_cursor);
        let cursor_w = cursor.map_or(0, |c| c.gap.saturating_add(c.width));
        let text_size = style.font.measure(self.value);
        let cursor_x = style.font.measure(&self.value[..self.cursor_index()]).width;

        // Scroll left when the text (plus cursor) overflows, keeping its end
        // visible, but never past the cursor.
        let overflow = (text_size.width.saturating_add(cursor_w))
            .saturating_sub(content.size.width)
            .min(cursor_x);
        let text_left = content.top_left.x - overflow as i32;
        let center_y = content.center().y;

        let mut clipped = target.clipped(&content);
        style.font.draw_anchored(
            &mut clipped,
            self.value,
            Point::new(text_left, center_y),
            AnchorPoint::CenterLeft,
        )?;

        if let Some(cursor) = cursor {
            // Measure a reference string so the cursor keeps its height on empty input.
            let height = style
                .font
                .measure(REFERENCE_TEXT)
                .height
                .min(content.size.height);
            let origin = Point::new(
                text_left + cursor_x.saturating_add(cursor.gap) as i32,
                center_y - (height / 2) as i32,
            );
            Rectangle::new(origin, Size::new(cursor.width, height))
                .into_styled(PrimitiveStyle::with_fill(cursor.color))
                .draw(&mut clipped)?;
        }

        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use embedded_graphics::{
        mock_display::MockDisplay,
        mono_font::{MonoTextStyle, ascii::FONT_6X10},
        pixelcolor::BinaryColor,
    };

    const BOUNDS: Rectangle = Rectangle::new(Point::new(2, 2), Size::new(60, 40));

    fn style() -> TextFieldStyle<BinaryColor, MonoTextStyle<'static, BinaryColor>> {
        let font = MonoTextStyle::new(&FONT_6X10, BinaryColor::On);
        TextFieldStyle::new(font, font)
            .with_frame(FrameStyle::new().with_border(BinaryColor::On, 2))
            .with_padding(3)
            .with_cursor(CursorStyle::new(BinaryColor::On))
    }

    #[test]
    fn title_sits_above_the_frame() {
        let style = style();
        let field = TextField::new(BOUNDS, "", &style);
        assert_eq!(field.frame_bounds(), BOUNDS);

        let field = field.with_title("Title");
        let frame = field.frame_bounds();
        assert_eq!(frame.top_left.y, BOUNDS.top_left.y + 10 + 4);
        assert_eq!(frame.bottom_right(), BOUNDS.bottom_right());
    }

    #[test]
    fn height_fits_title_text_padding_and_border() {
        let style = style();
        // FONT_6X10 lines are 10 px; padding 3 and border 2 on both sides.
        assert_eq!(style.height(false), 10 + 2 * (3 + 2));
        assert_eq!(style.height(true), 10 + 4 + 10 + 2 * (3 + 2));
    }

    #[test]
    fn long_text_is_clipped_to_the_frame() {
        let style = style();
        let field =
            TextField::new(BOUNDS, "a very long text that overflows", &style).with_title("T");

        let mut display = MockDisplay::new();
        display.set_allow_overdraw(true);
        field.draw(&mut display).unwrap();
        assert!(BOUNDS.contains(display.affected_area().top_left));
        assert!(BOUNDS.contains(display.affected_area().bottom_right().unwrap()));

        // The end of the text and the cursor stay visible: the last content
        // column (just inside the padding) is lit.
        let content = style.frame.content_area(field.frame_bounds());
        let last_x = content.top_left.x + content.size.width as i32 - 1 - 3;
        let lit = (content.top_left.y..content.top_left.y + content.size.height as i32)
            .any(|y| display.get_pixel(Point::new(last_x, y)) == Some(BinaryColor::On));
        assert!(lit);
    }

    #[test]
    fn long_title_is_clipped_to_the_bounds() {
        let style = style();
        let field =
            TextField::new(BOUNDS, "", &style).with_title("a title much wider than the field");

        let mut display = MockDisplay::new();
        display.set_allow_overdraw(true);
        field.draw(&mut display).unwrap();
        assert!(BOUNDS.contains(display.affected_area().bottom_right().unwrap()));
    }

    #[test]
    fn huge_padding_does_not_overflow() {
        let style = style().with_padding(u32::MAX);
        assert_eq!(style.height(true), u32::MAX);
    }

    /// Columns of the content area with at least one lit pixel.
    fn lit_columns(
        field: &TextField<'_, BinaryColor, MonoTextStyle<'static, BinaryColor>>,
    ) -> [bool; 60] {
        let mut display = MockDisplay::new();
        display.set_allow_overdraw(true);
        field.draw(&mut display).unwrap();
        let content = field.style.frame.content_area(field.frame_bounds());
        let mut lit = [false; 60];
        for (x, column) in lit.iter_mut().enumerate() {
            *column = (content.top_left.y..content.top_left.y + content.size.height as i32)
                .any(|y| display.get_pixel(Point::new(x as i32, y)) == Some(BinaryColor::On));
        }
        lit
    }

    #[test]
    fn cursor_is_drawn_at_its_position() {
        let style = style();
        // Spaces draw nothing: only the cursor is lit. The text starts at
        // x = 2 + 2 (border) + 3 (padding) = 7, one glyph is 6 px, the gap 1 px.
        let field = TextField::new(BOUNDS, "   ", &style);
        let lit = lit_columns(&field);
        assert!(lit[7 + 18 + 1] && !lit[7 + 6 + 1]);

        let lit = lit_columns(&field.with_cursor_position(1));
        assert!(lit[7 + 6 + 1] && !lit[7 + 18 + 1]);

        // Past the end: clamped to the end.
        let lit = lit_columns(&field.with_cursor_position(99));
        assert!(lit[7 + 18 + 1]);

        // Inside a multi-byte character: moved back to its start.
        let field = TextField::new(BOUNDS, " \u{e9}", &style).with_cursor_position(2);
        assert_eq!(field.cursor_index(), 1);
    }

    #[test]
    fn scrolling_keeps_the_cursor_visible() {
        let style = style();
        let field = TextField::new(BOUNDS, "a very long text that overflows", &style)
            .with_cursor_position(0);
        let lit = lit_columns(&field);
        // No scroll: the cursor is right after the left padding.
        assert!(lit[7 + 1]);
    }
}