garage44.eu/jeroen/pinnacle

logclone: git clone https://garage44.eu/jeroen/pinnacle.git

.. /ui/src/keyboard.rs

raw

//! The on-screen keyboard an app draws along the bottom of a pane: digits,
//! letters, shift, backspace, space and enter, laid out by
//! `pinnacle_layout::keyboard` for the pane's width. The app owns the text;
//! the keyboard turns taps, and keys of a physical keyboard, into key
//! presses. Once a physical key is typed, the on-screen keyboard steps aside
//! (its area is empty) until the app calls it back: a laptop or a tablet with
//! a keyboard attached does not need it.
//!
//! A physical keyboard types by the layout chosen in Settings → Keyboard
//! (`pinnacle_rt::locale::keyboard`), read again a moment after it changes:
//! AltGr's characters, and dead keys, whose accent goes on the next letter
//! (`'` then `e` is é on US-International).

use pinnacle_gfx::{Canvas, Rect};
use pinnacle_layout::keyboard::{self as layout, Layout, Typed, compose, keys};
pub use pinnacle_layout::keyboard::{HEIGHT, Key};

use crate::theme;

/// How long a layout read is kept before the next key reads it again.
const LAYOUT_KEPT_MS: u64 = 2000;

pub struct Keyboard {
    pub shift: bool,
    pressed: Option<Key>,
    /// A physical shift key held.
    held_shift: bool,
    /// A physical ctrl key held.
    held_ctrl: bool,
    /// AltGr (the right Alt) held.
    held_altgr: bool,
    /// A dead key typed, waiting for the next.
    dead: Option<char>,
    /// A second key a key typed (an accent that went on nothing, then the
    /// key), for [`queued`](Keyboard::queued).
    next: Option<Key>,
    /// The layout, and when it was read.
    layout: Layout,
    layout_read: Option<u64>,
    /// Typing on a physical keyboard: the on-screen one is hidden.
    pub physical: bool,
}

impl Default for Keyboard {
    fn default() -> Self {
        Self::new()
    }
}

impl Keyboard {
    pub fn new() -> Keyboard {
        Keyboard {
            shift: false,
            pressed: None,
            held_shift: false,
            held_ctrl: false,
            held_altgr: false,
            dead: None,
            next: None,
            layout: Layout::Us,
            layout_read: None,
            physical: false,
        }
    }

    /// A physical shift key is held: an arrow then selects as it moves.
    pub fn shift_held(&self) -> bool {
        self.held_shift
    }

    /// A physical ctrl key is held.
    pub fn ctrl_held(&self) -> bool {
        self.held_ctrl
    }

    fn shown(&self, key: Key) -> Key {
        match key {
            Key::Char(c) if self.shift => Key::Char(layout::shifted(c)),
            k => k,
        }
    }

    /// The on-screen keyboard's area at the bottom of `pane`: empty while
    /// a physical keyboard is in use.
    pub fn area(&self, pane: Rect) -> Rect {
        if self.physical {
            Rect::new(pane.x, pane.bottom(), pane.width, 0)
        } else {
            layout::area(pane)
        }
    }

    /// A physical key pressed (`value` 1, or 2 repeated) or released (0):
    /// what it types, if anything. The first one hides the on-screen
    /// keyboard.
    pub fn key_event(&mut self, code: u16, value: i32) -> Option<Key> {
        if code == layout::LEFT_SHIFT || code == layout::RIGHT_SHIFT {
            self.held_shift = value != 0;
            return None;
        }
        if code == layout::LEFT_CTRL || code == layout::RIGHT_CTRL {
            self.held_ctrl = value != 0;
            return None;
        }
        if code == layout::RIGHT_ALT {
            self.held_altgr = value != 0;
            return None;
        }
        if value == 0 {
            return None;
        }
        let typed = self
            .layout()
            .typed(code, self.held_shift, self.held_ctrl, self.held_altgr)?;
        self.physical = true;
        let key = match (self.dead.take(), typed) {
            (None, Typed::Dead(accent)) => {
                self.dead = Some(accent);
                return None;
            }
            (None, Typed::Key(key)) => key,
            // An accent, then a space: the accent itself.
            (Some(accent), Typed::Key(Key::Space)) => Key::Char(accent),
            (Some(accent), Typed::Key(Key::Char(c))) => match compose(accent, c) {
                Some(composed) => Key::Char(composed),
                None => {
                    self.next = Some(Key::Char(c));
                    Key::Char(accent)
                }
            },
            // An accent twice: typed once.
            (Some(accent), Typed::Dead(again)) if accent == again => Key::Char(accent),
            (Some(accent), Typed::Dead(other)) => {
                self.dead = Some(other);
                Key::Char(accent)
            }
            // Before a key that is no character, the accent is dropped.
            (Some(_), Typed::Key(key)) => key,
        };
        Some(key)
    }

    /// A key the last [`key_event`](Keyboard::key_event) typed after the
    /// one it returned: an accent that went on nothing (`'` then `x` types
    /// both). Taken once.
    pub fn queued(&mut self) -> Option<Key> {
        self.next.take()
    }

    /// The layout chosen, read again when the last read is a while ago.
    fn layout(&mut self) -> Layout {
        let now = pinnacle_rt::time();
        if self.layout_read.is_none_or(|at| now >= at + LAYOUT_KEPT_MS) {
            self.layout = Layout::from_name(&pinnacle_rt::locale::keyboard()).unwrap_or(Layout::Us);
            self.layout_read = Some(now);
        }
        self.layout
    }

    /// Draws the keyboard in `area` (see [`area`]).
    pub fn draw(&self, canvas: &mut Canvas, area: Rect) {
        if area.height == 0 {
            return;
        }
        canvas.fill_rect(area, theme::SURFACE);
        let font = theme::heading();
        for (rect, key) in keys(area) {
            let pressed = self.pressed == Some(key);
            let fill = match key {
                Key::Char(_) | Key::Space => theme::SURFACE_PRESSED,
                Key::Enter => theme::ACCENT,
                Key::Shift if self.shift => theme::ACCENT,
                _ => theme::BACKGROUND,
            };
            let fill = if pressed {
                pinnacle_gfx::Color(pinnacle_gfx::blend(fill.0, 0xffffff, 70))
            } else {
                fill
            };
            canvas.fill_rounded(rect, 10, fill);
            let mut label = [0u8; 4];
            let text = match self.shown(key) {
                Key::Char(c) => &*c.encode_utf8(&mut label),
                Key::Shift => "Aa",
                Key::Backspace => "←",
                Key::Space => "",
                Key::Enter => "OK",
                Key::Paste => "Paste",
                Key::Copy => "Copy",
                // Keys of a physical keyboard only.
                _ => "",
            };
            canvas.text_centered(font, rect, text, theme::TEXT);
        }
    }

    /// A press or release at (x, y) on a keyboard in `area`: on a release
    /// over the key pressed, the key (shift handled here). Returns whether
    /// to redraw, and the key.
    pub fn touch(&mut self, x: i32, y: i32, area: Rect, down: bool) -> (bool, Option<Key>) {
        let hit = keys(area)
            .into_iter()
            .find(|(r, _)| r.contains(x, y))
            .map(|(_, k)| k);
        if down {
            let changed = self.pressed != hit;
            self.pressed = hit;
            return (changed, None);
        }
        let pressed = self.pressed.take();
        match pressed {
            Some(key) if hit == Some(key) => {
                if key == Key::Shift {
                    self.shift = !self.shift;
                    return (true, None);
                }
                let key = self.shown(key);
                if matches!(key, Key::Char(_)) && self.shift {
                    self.shift = false;
                }
                (true, Some(key))
            }
            Some(_) => (true, None),
            None => (false, None),
        }
    }
}