embedded-graphics-keyboard 0.2.0

no_std on-screen keyboard and text field widgets for embedded-graphics, driven by buttons or touch
Documentation
//! Interactive demo in the `embedded-graphics` simulator.
//!
//! ```sh
//! cargo run --example simulator            # 480x320
//! cargo run --example simulator -- 800 480 # any screen size
//! ```
//!
//! Arrow keys move the selection, Enter presses the selected key, the mouse
//! touches keys directly. Up from the first row (or a click on the field)
//! focuses the text field, where Left and Right move the cursor; Down or Enter
//! go back to the keys.

use embedded_graphics::{
    mono_font::{MonoTextStyle, ascii::FONT_10X20},
    pixelcolor::Rgb565,
    prelude::*,
    primitives::Rectangle,
};
use embedded_graphics_keyboard::{
    CursorStyle, FrameStyle, KeyEvent, KeyStyle, Keyboard, KeyboardConfig, KeyboardTheme,
    NavButton, TextField, TextFieldStyle,
};
use embedded_graphics_simulator::{
    OutputSettings, SimulatorDisplay, SimulatorEvent, Window,
    sdl2::{Keycode, MouseButton},
};

const MARGIN: u32 = 4;
const GAP: u32 = 6;

fn main() -> Result<(), core::convert::Infallible> {
    let mut args = std::env::args()
        .skip(1)
        .map(|a| a.parse().expect("size in pixels"));
    let size = Size::new(args.next().unwrap_or(480), args.next().unwrap_or(320));
    let mut display = SimulatorDisplay::<Rgb565>::new(size);

    let field_style = |accent| {
        TextFieldStyle::new(
            MonoTextStyle::new(&FONT_10X20, accent),
            MonoTextStyle::new(&FONT_10X20, Rgb565::CSS_SILVER),
        )
        .with_frame(
            FrameStyle::new()
                .with_fill(Rgb565::new(2, 4, 2))
                .with_border(accent, 2)
                .with_corner_radius(8),
        )
        .with_cursor(CursorStyle {
            color: accent,
            width: 2,
            gap: 2,
        })
    };
    let editing = field_style(Rgb565::YELLOW);
    let focused = field_style(Rgb565::CSS_DODGER_BLUE);
    let submitted = field_style(Rgb565::GREEN);
    let field_height = editing.height(true);

    // The keyboard fills the screen below the text field...
    let screen = display.bounding_box().offset(-(MARGIN as i32));
    let keyboard_area = Rectangle::new(
        screen.top_left + Point::new(0, (field_height + GAP) as i32),
        Size::new(screen.size.width, screen.size.height - field_height - GAP),
    );
    let black_text = MonoTextStyle::new(&FONT_10X20, Rgb565::BLACK);
    let idle = KeyStyle::new(MonoTextStyle::new(&FONT_10X20, Rgb565::WHITE))
        .with_fill(Rgb565::new(4, 10, 8))
        .with_border(Rgb565::new(12, 24, 12), 1)
        .with_corner_radius(8);
    let theme = KeyboardTheme {
        idle,
        selected: idle
            .with_fill(Rgb565::CSS_DODGER_BLUE)
            .with_font(black_text),
        pressed: idle.with_fill(Rgb565::WHITE).with_font(black_text),
    };
    let mut keyboard =
        Keyboard::new(KeyboardConfig::new(keyboard_area, theme).with_field_navigation(true))
            .expect("keyboard does not fit on this screen");

    // ...and the text field is aligned on the keys.
    let keys = keyboard.keys_bounds();
    let field_bounds = Rectangle::new(
        Point::new(keys.top_left.x, screen.top_left.y),
        Size::new(keys.size.width, field_height),
    );

    let mut text = String::new();
    // Byte index of the cursor in `text`.
    let mut cursor = 0;
    let mut done = false;
    let mut frame = 0u32;
    let mut window = Window::new("embedded-graphics-keyboard", &OutputSettings::default());

    // Cleared once: afterwards the keyboard only redraws the keys that change,
    // and the filled field frame covers its previous content.
    display.clear(Rgb565::BLACK)?;
    'running: loop {
        let style = if done {
            &submitted
        } else if keyboard.is_field_focused() {
            &focused
        } else {
            &editing
        };
        TextField::new(field_bounds, &text, style)
            .with_title("Message")
            .with_cursor_position(cursor)
            .with_cursor_visible(done || (frame / 15) % 2 == 0)
            .draw(&mut display)?;
        keyboard.redraw(&mut display, Rgb565::BLACK)?;
        // The SDL window only exists after the first `update`.
        window.update(&display);
        frame = frame.wrapping_add(1);

        for event in window.events() {
            let key_event = match event {
                SimulatorEvent::Quit => break 'running,
                SimulatorEvent::MouseButtonDown {
                    mouse_btn: MouseButton::Left,
                    point,
                } if field_bounds.contains(point) => {
                    keyboard.set_field_focused(true);
                    None
                }
                SimulatorEvent::MouseButtonDown {
                    mouse_btn: MouseButton::Left,
                    point,
                } => keyboard.handle_touch(point),
                SimulatorEvent::KeyDown { keycode, .. } => match keycode {
                    Keycode::Up => keyboard.handle_button(NavButton::Up),
                    Keycode::Down => keyboard.handle_button(NavButton::Down),
                    Keycode::Left => keyboard.handle_button(NavButton::Left),
                    Keycode::Right => keyboard.handle_button(NavButton::Right),
                    Keycode::Return | Keycode::KpEnter => {
                        keyboard.handle_button(NavButton::Validate)
                    }
                    _ => None,
                },
                SimulatorEvent::MouseButtonUp { .. } | SimulatorEvent::KeyUp { .. } => {
                    keyboard.release();
                    None
                }
                _ => None,
            };

            let Some(key_event) = key_event else { continue };
            match key_event {
                KeyEvent::Char(c) => {
                    text.insert(cursor, c);
                    cursor += c.len_utf8();
                }
                KeyEvent::Backspace => {
                    if let Some(c) = text[..cursor].chars().next_back() {
                        cursor -= c.len_utf8();
                        text.remove(cursor);
                    }
                }
                KeyEvent::Back => {
                    text.clear();
                    cursor = 0;
                }
                KeyEvent::Enter => {}
                KeyEvent::CursorLeft => {
                    cursor -= text[..cursor].chars().next_back().map_or(0, char::len_utf8);
                }
                KeyEvent::CursorRight => {
                    cursor += text[cursor..].chars().next().map_or(0, char::len_utf8);
                }
            }
            done = key_event == KeyEvent::Enter;
        }
    }
    Ok(())
}