git clone https://garage44.eu/jeroen/pinnacle.git.. /layout/src/lib.rs
//! Where everything goes on a screen of any size: pure functions from a
//! window's size to the rectangles on it. Pinnacle runs on screens of every
//! shape — a phone held upright, a tablet, a laptop — so no screen keeps a
//! fixed coordinate; each lays out from its window here.
//!
//! The apps draw by these functions and test their taps by them, and
//! `cargo xtask`, which drives the system in QEMU, taps by them too, so a
//! demo finds the same buttons on every screen size.
#![no_std]
pub use pinnacle_gfx::Rect;
/// How much room a window has, by its width: one column of content
/// (compact), a wider one (medium), or room for two panes side by side
/// (expanded).
#[derive(Clone, Copy, PartialEq, Eq, Debug, PartialOrd, Ord)]
pub enum Class {
Compact,
Medium,
Expanded,
}
impl Class {
pub fn of(width: i32) -> Class {
match width {
..800 => Class::Compact,
800..1200 => Class::Medium,
_ => Class::Expanded,
}
}
}
/// The space kept clear along a window's edges.
pub fn margin(width: i32) -> i32 {
if Class::of(width) == Class::Compact {
24
} else {
32
}
}
/// The widest a column of text and cards gets: wider reads badly.
pub const COLUMN_MAX: i32 = 760;
/// A column of content in a window `width` wide: its margins on a narrow
/// window, centred and at most `max` wide on a wide one. Returns its x and
/// width.
pub fn column(width: i32, max: i32) -> (i32, i32) {
let m = margin(width);
let w = (width - 2 * m).min(max);
((width - w) / 2, w)
}
pub fn center(r: Rect) -> (i32, i32) {
(r.x + r.width / 2, r.y + r.height / 2)
}
/// The display server's frame: a status bar on top, a home bar along the
/// bottom, and between them the area the app in front gets.
pub mod shell {
use super::Rect;
pub const STATUS: i32 = 56;
pub const HOME_BAR: i32 = 48;
pub fn app_area(width: i32, height: i32) -> Rect {
Rect::new(0, STATUS, width, height - STATUS - HOME_BAR)
}
/// Where a tap goes home.
pub fn home(width: i32, height: i32) -> (i32, i32) {
(width / 2, height - HOME_BAR / 2)
}
/// The button on the status bar that closes the app in front: at its
/// left, before the app's title.
pub fn close(width: i32) -> Rect {
let size = STATUS - 16;
Rect::new(super::margin(width) - 8, (STATUS - size) / 2, size, size)
}
/// Where a notification shows, as a banner under the status bar.
pub fn banner(width: i32) -> Rect {
let (x, w) = super::column(width, 640);
Rect::new(x, STATUS + 8, w, 108)
}
/// Room the clock takes at the status bar's right ("23:59" in the
/// body font, with a little to spare).
const CLOCK: i32 = 64;
/// The button on the status bar that opens the list of past
/// notifications: left of the clock, shown once there is one.
pub fn notices(width: i32) -> Rect {
let size = STATUS - 16;
let w = size + 24;
Rect::new(
width - super::margin(width) - CLOCK - 12 - w,
(STATUS - size) / 2,
w,
size,
)
}
/// The list of past notifications, over the app area: its heading's
/// baseline (window coordinates), the newest first below it.
pub const NOTICES_HEADING: i32 = 64;
/// One past notification in the list, a card the height of a banner.
pub const NOTICE: i32 = 108;
/// Notification `i` of the list (window coordinates), newest first.
pub fn notice(width: i32, i: usize) -> Rect {
let (x, w) = super::column(width, 640);
Rect::new(x, 96 + i as i32 * (NOTICE + 12), w, NOTICE)
}
/// How many notifications the list shows in an app area `height` tall.
pub fn notices_fit(height: i32) -> usize {
((height - 96 + 12) / (NOTICE + 12)).max(0) as usize
}
/// The list's button that forgets them all, at the heading's right.
pub fn notices_clear(width: i32) -> Rect {
let (x, w) = super::column(width, 640);
Rect::new(x + w - 120, 20, 120, 56)
}
/// The pill drawn on the home bar.
pub fn pill(width: i32, height: i32) -> Rect {
Rect::new(width / 2 - 70, height - HOME_BAR / 2 - 3, 140, 6)
}
/// The agent's confirmation, which the display server draws over
/// everything: its "Allow" and "Don't allow" buttons, side by side
/// under the question.
pub fn confirm_buttons(width: i32, height: i32) -> (Rect, Rect) {
let (x, w) = super::column(width, 640);
let half = (w - 16) / 2;
let y = height - HOME_BAR - 140;
(Rect::new(x, y, half, 72), Rect::new(x + half + 16, y, half, 72))
}
/// A point in the app area, as the screen sees it.
pub fn to_screen(width: i32, height: i32, (x, y): (i32, i32)) -> (i32, i32) {
let a = app_area(width, height);
(a.x + x, a.y + y)
}
}
/// The home screen: a grid of app tiles under a heading, as many columns
/// as fit (at least four), the grid centred.
pub mod launcher {
use super::{Rect, margin};
pub const TILE: i32 = 120;
/// From a tile's top to the next row's.
pub const ROW: i32 = TILE + 64;
pub const TOP: i32 = 180;
const GAP_MIN: i32 = 48;
pub fn columns(width: i32) -> i32 {
let room = width - 2 * margin(width);
((room + GAP_MIN) / (TILE + GAP_MIN)).max(4)
}
pub fn tile(width: i32, i: usize) -> Rect {
let room = width - 2 * margin(width);
let columns = columns(width);
// Four columns spread over a narrow window; more sit a fixed gap
// apart, centred.
let gap = if columns == 4 {
(room - 4 * TILE) / 3
} else {
GAP_MIN
};
let grid = columns * TILE + (columns - 1) * gap;
let left = (width - grid) / 2;
let (col, row) = (i as i32 % columns, i as i32 / columns);
Rect::new(left + col * (TILE + gap), TOP + row * ROW, TILE, TILE)
}
pub fn tile_center(width: i32, i: usize) -> (i32, i32) {
super::center(tile(width, i))
}
}
/// Lists of cards (the Store's offers, contacts): a column under a heading.
pub mod list {
use super::{COLUMN_MAX, Rect, column};
pub const TOP: i32 = 150;
pub const GAP: i32 = 12;
/// Card `i` of cards `height` tall, in a pane `width` wide.
pub fn card(width: i32, height: i32, i: usize) -> Rect {
let (x, w) = column(width, COLUMN_MAX);
Rect::new(x, TOP + i as i32 * (height + GAP), w, height)
}
/// The heading's left edge and the width under it.
pub fn heading(width: i32) -> (i32, i32) {
column(width, COLUMN_MAX)
}
}
/// The Store: a card per offer, its button at the right.
pub mod store {
use super::{Rect, list};
pub const CARD: i32 = 150;
pub fn card(width: i32, i: usize) -> Rect {
list::card(width, CARD, i)
}
pub fn button(width: i32, i: usize) -> Rect {
let c = card(width, i);
Rect::new(c.right() - 24 - 150, c.y + (CARD - 56) / 2, 150, 56)
}
pub fn button_center(width: i32, i: usize) -> (i32, i32) {
super::center(button(width, i))
}
}
/// Messages: the contact list and a conversation. A wide window shows both
/// side by side; a narrow one, one at a time.
pub mod messages {
use super::{Class, Rect, list};
pub const ROW: i32 = 112;
/// The conversation's header bar.
pub const HEADER: i32 = 96;
const LIST_PANE: i32 = 380;
pub fn two_panes(width: i32) -> bool {
Class::of(width) == Class::Expanded
}
/// The contact list's pane and the conversation's, in a window this
/// size; on a narrow window both are the whole window.
pub fn panes(width: i32, height: i32) -> (Rect, Rect) {
let all = Rect::new(0, 0, width, height);
if two_panes(width) {
(
Rect::new(0, 0, LIST_PANE, height),
Rect::new(LIST_PANE, 0, width - LIST_PANE, height),
)
} else {
(all, all)
}
}
/// Contact `i`'s row, in window coordinates.
pub fn contact(width: i32, height: i32, i: usize) -> Rect {
let pane = panes(width, height).0;
let r = list::card(pane.width, ROW, i);
Rect::new(pane.x + r.x, pane.y + r.y, r.width, r.height)
}
pub fn contact_center(width: i32, height: i32, i: usize) -> (i32, i32) {
super::center(contact(width, height, i))
}
/// The conversation's "back" control, shown when it has the window.
pub fn back(width: i32) -> Option<Rect> {
(!two_panes(width)).then(|| Rect::new(0, 0, 200, HEADER))
}
}
/// Notes: the list of notes and the note being written, side by side on a
/// wide window; on a narrow one, one or the other.
pub mod notes {
use super::{Class, Rect, list, margin};
pub const ROW: i32 = 96;
/// The note's header bar.
pub const HEADER: i32 = 96;
const LIST_PANE: i32 = 380;
/// The "New note" button's height, above the list.
const NEW: i32 = 64;
pub fn two_panes(width: i32) -> bool {
Class::of(width) == Class::Expanded
}
/// The list's pane and the note's, in a window this size; on a narrow
/// window both are the whole window.
pub fn panes(width: i32, height: i32) -> (Rect, Rect) {
let all = Rect::new(0, 0, width, height);
if two_panes(width) {
(
Rect::new(0, 0, LIST_PANE, height),
Rect::new(LIST_PANE, 0, width - LIST_PANE, height),
)
} else {
(all, all)
}
}
/// The button that starts a new note, where the list begins.
pub fn new_note(width: i32, height: i32) -> Rect {
let pane = panes(width, height).0;
let r = list::card(pane.width, NEW, 0);
Rect::new(pane.x + r.x, pane.y + r.y, r.width, r.height)
}
/// Note `i`'s row, under the button.
pub fn note(width: i32, height: i32, i: usize) -> Rect {
let pane = panes(width, height).0;
let r = list::card(pane.width, ROW, i);
let below = NEW + list::GAP;
Rect::new(pane.x + r.x, pane.y + r.y + below, r.width, r.height)
}
/// The note's "back" control, shown when it has the window.
pub fn back(width: i32) -> Option<Rect> {
(!two_panes(width)).then(|| Rect::new(0, 0, 200, HEADER))
}
/// The note's "Delete", at its header's right.
pub fn delete(width: i32, height: i32) -> Rect {
let pane = panes(width, height).1;
Rect::new(pane.right() - margin(pane.width) - 120, 16, 120, HEADER - 32)
}
/// The note's "Copy", left of "Delete": the whole note to the clipboard.
pub fn copy(width: i32, height: i32) -> Rect {
let delete = delete(width, height);
Rect::new(delete.x - 120, delete.y, 120, delete.height)
}
}
/// Settings: sections of rows, each a heading over a card; one column, or
/// two side by side on a wide window, the sections split between them.
/// The terminal: a slim header with Stop, then the session's records and
/// the prompt under them, edge to edge; above the on-screen keyboard, a row
/// of the keys it lacks.
pub mod terminal {
use super::Rect;
/// The bar along the top: where commands run, and Stop.
pub const HEADER: i32 = 48;
/// Between the window's edges and the text.
pub const PAD: i32 = 16;
/// The row of keys a terminal needs that the on-screen keyboard lacks,
/// above it while it shows.
pub const EXTRA: i32 = 56;
/// What that row holds, the most wanted first: as many as fit are shown.
pub const EXTRA_KEYS: [&str; 16] = [
"Tab", "↑", "↓", "←", "→", "-", "/", "=", "\"", "~", "|", ":", "@", "+", "'", "_",
];
/// The narrowest an extra key gets.
const EXTRA_MIN: i32 = 60;
/// A row of answers to a question.
const ANSWER: i32 = 52;
const GAP: i32 = 8;
/// Stop, at the header's right end, while a command runs.
pub fn stop(width: i32) -> Rect {
Rect::new(width - PAD - 104, 8, 104, HEADER - 16)
}
/// Where the terminal's own content ends: above the extra keys while
/// the on-screen `keyboard` shows (it begins at `keys_top`), else the
/// window's bottom (`keys_top` too).
pub fn bottom(keys_top: i32, keyboard: bool) -> i32 {
if keyboard { keys_top - EXTRA } else { keys_top }
}
/// How many of [`EXTRA_KEYS`] fit on a window `width` wide.
pub fn extra_keys(width: i32) -> usize {
(((width - GAP) / EXTRA_MIN).max(1) as usize).min(EXTRA_KEYS.len())
}
/// Extra key `i`, in the row just above the on-screen keyboard.
pub fn extra_key(width: i32, keys_top: i32, i: usize) -> Rect {
let n = extra_keys(width) as i32;
let w = (width - GAP) / n;
let left = (width - w * n + GAP) / 2;
Rect::new(
left + i as i32 * w,
keys_top - EXTRA + GAP / 2,
w - GAP,
EXTRA - GAP,
)
}
/// Answer `i` of `count` to a question with options, in a row along
/// `bottom` (see [`bottom`]).
pub fn option(width: i32, bottom: i32, i: usize, count: usize) -> Rect {
let row = Rect::new(PAD, bottom - GAP - ANSWER, width - 2 * PAD, ANSWER);
let count = count.max(1) as i32;
let w = (row.width - GAP * (count - 1)) / count;
Rect::new(row.x + i as i32 * (w + GAP), row.y, w, row.height)
}
/// Where the session and the prompt are drawn: under the header, down
/// to `bottom`, or to the row of answers when a question has `options`.
pub fn page(width: i32, bottom: i32, options: bool) -> Rect {
let top = HEADER + GAP;
let end = if options {
option(width, bottom, 0, 1).y
} else {
bottom
};
Rect::new(PAD, top, width - 2 * PAD, (end - GAP - top).max(0))
}
}
pub mod settings {
use super::{COLUMN_MAX, Class, Rect, column, margin};
pub const ROW: i32 = 56;
/// A section's heading, above its card.
pub const HEADING: i32 = 44;
const TOP: i32 = 120;
const GAP: i32 = 28;
/// Where each column's sections start: on a wide window, the second
/// column takes the sections from the middle on.
fn split(width: i32, sections: usize) -> usize {
if Class::of(width) == Class::Expanded {
sections.div_ceil(2)
} else {
sections
}
}
/// The card of section `i`, of sections with `rows[i]` rows each.
pub fn card(width: i32, rows: &[i32], i: usize) -> Rect {
let split = split(width, rows.len());
let (x, w) = if split < rows.len() {
let m = margin(width);
let w = ((width - 3 * m) / 2).min(COLUMN_MAX);
let left = (width - 2 * w - m) / 2;
(if i < split { left } else { left + w + m }, w)
} else {
column(width, COLUMN_MAX)
};
let first = if i < split { 0 } else { split };
let above: i32 = rows[first..i].iter().map(|r| HEADING + r * ROW + GAP).sum();
Rect::new(x, TOP + above + HEADING, w, rows[i] * ROW)
}
/// Row `row` of a card.
pub fn row(card: Rect, row: i32) -> Rect {
Rect::new(card.x, card.y + row * ROW, card.width, ROW)
}
/// The button at the right of a row.
pub fn button(row: Rect) -> Rect {
Rect::new(row.right() - 16 - 120, row.y + 8, 120, ROW - 16)
}
}
/// The on-screen keyboard: five rows of keys along the bottom of a pane,
/// at most a comfortable width, centred.
pub mod keyboard {
use super::Rect;
pub const ROWS: [&str; 4] = ["1234567890", "qwertyuiop", "asdfghjkl", "zxcvbnm"];
/// What a key types with shift on: a letter in capitals; the digits,
/// the comma and the full stop what an address, a phone number or a
/// question needs, which the keyboard has no other keys for.
pub fn shifted(c: char) -> char {
const FROM: &str = "1234567890,.";
const TO: &str = "!@#+-/&'()?:";
match FROM.chars().position(|f| f == c) {
Some(i) => TO.chars().nth(i).unwrap_or(c),
None => c.to_ascii_uppercase(),
}
}
pub const KEY_H: i32 = 64;
pub const GAP: i32 = 8;
/// Five rows of keys and their gaps.
pub const HEIGHT: i32 = 5 * (KEY_H + GAP) + GAP;
/// The widest a key gets: a keyboard across a laptop's screen is not
/// one to type on.
const UNIT_MAX: i32 = 88;
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Key {
Char(char),
Shift,
Backspace,
Space,
Enter,
/// Put what is on the clipboard here.
Paste,
/// Ctrl+C on a physical keyboard: copy what the app takes to be meant.
Copy,
Tab,
Escape,
Up,
Down,
Left,
Right,
Home,
End,
PageUp,
PageDown,
/// Forward delete.
Delete,
/// Ctrl and a letter other than C and V (lower case).
Ctrl(char),
}
/// The shortest a key gets, on a low screen.
const KEY_H_MIN: i32 = 36;
/// The keyboard's area at the bottom of `pane`: [`HEIGHT`], or less on
/// a low screen, where it takes no more than half the pane and its keys
/// are shorter, so what is typed into stays in view.
pub fn area(pane: Rect) -> Rect {
let height = HEIGHT.min(pane.height / 2).max(5 * (KEY_H_MIN + GAP) + GAP);
Rect::new(pane.x, pane.bottom() - height, pane.width, height)
}
/// How tall a key is in a keyboard `area`.
fn key_height(area: Rect) -> i32 {
((area.height - GAP) / 5 - GAP).clamp(KEY_H_MIN, KEY_H)
}
/// Every key and where it is, for a keyboard in `area`.
/// How many keys: four rows, shift and backspace, and the bottom row's five.
pub const COUNT: usize = 10 + 10 + 9 + 7 + 2 + 5;
pub fn keys(area: Rect) -> [(Rect, Key); COUNT] {
let unit = ((area.width - GAP) / 10).min(UNIT_MAX);
let left = area.x + (area.width - 10 * unit - GAP) / 2;
let key_h = key_height(area);
let row_y = |r: i32| area.y + GAP + r * (key_h + GAP);
let mut keys = [(Rect::new(0, 0, 0, 0), Key::Space); COUNT];
let mut k = 0;
let mut put = |rect, key| {
keys[k] = (rect, key);
k += 1;
};
for (r, row) in ROWS.iter().enumerate() {
let n = row.chars().count() as i32;
// Rows narrower than ten keys are centred; the last makes room
// for shift and backspace.
let x0 = left + GAP / 2 + (10 - n) * unit / 2;
for (i, c) in row.chars().enumerate() {
put(
Rect::new(x0 + i as i32 * unit + GAP / 2, row_y(r as i32), unit - GAP, key_h),
Key::Char(c),
);
}
if r == 3 {
let side = x0 - left - GAP;
put(Rect::new(left + GAP, row_y(3), side - GAP / 2, key_h), Key::Shift);
put(
Rect::new(x0 + n * unit + GAP / 2, row_y(3), side - GAP / 2, key_h),
Key::Backspace,
);
}
}
let (x, y) = (left + GAP, row_y(4));
put(Rect::new(x, y, unit * 2 - GAP, key_h), Key::Char(','));
put(Rect::new(x + unit * 2, y, unit * 3 - GAP, key_h), Key::Space);
put(Rect::new(x + unit * 5, y, unit * 2 - GAP, key_h), Key::Paste);
put(Rect::new(x + unit * 7, y, unit - GAP, key_h), Key::Char('.'));
put(Rect::new(x + unit * 8, y, unit * 2 - GAP, key_h), Key::Enter);
keys
}
/// Where to tap for `c` (lower case, digits, space, ',', '.', and
/// '\n' for enter).
pub fn key_center(area: Rect, c: char) -> Option<(i32, i32)> {
let want = match c {
' ' => Key::Space,
'\n' => Key::Enter,
c => Key::Char(c),
};
keys(area)
.iter()
.find(|(_, k)| *k == want)
.map(|(r, _)| super::center(*r))
}
/// Linux key codes of the keys that change what others type.
pub const LEFT_SHIFT: u16 = 42;
pub const RIGHT_SHIFT: u16 = 54;
pub const LEFT_CTRL: u16 = 29;
pub const RIGHT_CTRL: u16 = 97;
const KEY_C: u16 = 46;
const KEY_V: u16 = 47;
/// The rows of a US keyboard by Linux key code, from code 2 ('1'): each
/// key unshifted and shifted, `\0` where a code is no character.
const ROW_CODES: [(u16, &str, &str); 4] = [
(2, "1234567890-=", "!@#$%^&*()_+"),
(16, "qwertyuiop[]", "QWERTYUIOP{}"),
(30, "asdfghjkl;'`", "ASDFGHJKL:\"~"),
(43, "\\zxcvbnm,./", "|ZXCVBNM<>?"),
];
/// What a physical key (a Linux key code, US layout) types, with shift
/// or ctrl held or not.
pub fn from_code(code: u16, shift: bool, ctrl: bool) -> Option<Key> {
match code {
KEY_C if ctrl => return Some(Key::Copy),
KEY_V if ctrl => return Some(Key::Paste),
1 => return Some(Key::Escape),
14 => return Some(Key::Backspace),
15 => return Some(Key::Tab),
28 | 96 => return Some(Key::Enter),
57 => return Some(Key::Space),
102 => return Some(Key::Home),
103 => return Some(Key::Up),
104 => return Some(Key::PageUp),
105 => return Some(Key::Left),
106 => return Some(Key::Right),
107 => return Some(Key::End),
108 => return Some(Key::Down),
109 => return Some(Key::PageDown),
111 => return Some(Key::Delete),
_ if ctrl => {
return match from_code(code, false, false) {
Some(Key::Char(c)) if c.is_ascii_lowercase() => Some(Key::Ctrl(c)),
_ => None,
};
}
_ => {}
}
ROW_CODES.iter().find_map(|&(first, plain, shifted)| {
let i = usize::from(code.checked_sub(first)?);
let row = if shift { shifted } else { plain };
row.chars().nth(i).map(Key::Char)
})
}
/// The physical key the right Alt is, AltGr on a European keyboard: it
/// reaches a third character on many keys (`€` on Dutch's E).
pub const RIGHT_ALT: u16 = 100;
/// The key between left shift and Z on an ISO keyboard (Dutch `]`).
const KEY_ISO: u16 = 86;
/// A keyboard's layout: what its keys type, chosen in Settings →
/// Keyboard. A key code (Linux's, by the key's place) is the same on
/// every keyboard; the layout says which character that place has.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Layout {
/// US English, as printed on most laptops sold outside Europe.
Us,
/// US English with dead keys (Windows' "US-International"): `'`,
/// `"`, `` ` ``, `^` and `~` wait for the next key and put their
/// accent on it (`'` `e` is é, `"` `e` is ë, `'` `c` is ç), or are
/// themselves before a space; AltGr reaches more (AltGr `,` is ç).
/// What most people in the Netherlands type on.
UsInternational,
/// The Dutch layout (`@` left of 1, `+` beside L), its accents dead
/// keys: ¨ and ^ beside P, ´ and `` ` `` beside +, ~ and ¸ beside /.
Dutch,
}
/// What a key gives on a layout.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Typed {
Key(Key),
/// An accent that waits for the next key ([`compose`]), as itself:
/// `'` or `´`, `"` or `¨`, `` ` ``, `^`, `~`, `¸`.
Dead(char),
}
impl Layout {
pub const ALL: [Layout; 3] = [Layout::Us, Layout::UsInternational, Layout::Dutch];
/// Its name in `system:/locale/keyboard`.
pub fn name(self) -> &'static str {
match self {
Layout::Us => "us",
Layout::UsInternational => "us-intl",
Layout::Dutch => "nl",
}
}
pub fn from_name(name: &str) -> Option<Layout> {
Layout::ALL.into_iter().find(|l| l.name() == name.trim())
}
/// As Settings shows it.
pub fn title(self) -> &'static str {
match self {
Layout::Us => "English (US)",
Layout::UsInternational => "English (US, international)",
Layout::Dutch => "Dutch",
}
}
/// Its rows by key code, as [`ROW_CODES`]: each key unshifted,
/// shifted and with AltGr, `\0` where it types nothing.
fn rows(self) -> &'static [(u16, &'static str, &'static str, &'static str)] {
match self {
Layout::Us => &[
(2, "1234567890-=", "!@#$%^&*()_+", ""),
(16, "qwertyuiop[]", "QWERTYUIOP{}", ""),
(30, "asdfghjkl;'`", "ASDFGHJKL:\"~", ""),
(43, "\\zxcvbnm,./", "|ZXCVBNM<>?", ""),
],
Layout::UsInternational => &[
(2, "1234567890-=", "!@#$%^&*()_+", "¡²³¤€¼½¾‘’¥×"),
(16, "qwertyuiop[]", "QWERTYUIOP{}", "äåé®þüúíóö«»"),
(30, "asdfghjkl;'`", "ASDFGHJKL:\"~", "áßð\0\0\0\0\0ø¶´\0"),
(43, "\\zxcvbnm,./", "|ZXCVBNM<>?", "¬æ\0©\0\0ñµç\0¿"),
(KEY_ISO, "\\", "|", ""),
],
Layout::Dutch => &[
(2, "1234567890/°", "!\"#$%&_()'?~", "¹²³¼½¾£{}\0\\¸"),
(16, "qwertyuiop¨*", "QWERTYUIOP^|", "\0\0€¶\0\0\0\0\0\0\0\0"),
(30, "asdfghjkl+´@", "ASDFGHJKL±`§", "\0ß\0\0\0\0\0\0\0\0\0¬"),
(43, "<zxcvbnm,.-", ">ZXCVBNM;:=", "\0\0\0¢\0\0\0µ\0\0\0"),
(KEY_ISO, "]", "[", "¦"),
],
}
}
/// Whether `c`, typed on this layout, is a dead key.
fn dead(self, c: char) -> bool {
match self {
Layout::Us => false,
Layout::UsInternational => matches!(c, '\'' | '"' | '`' | '^' | '~'),
Layout::Dutch => matches!(c, '¨' | '^' | '´' | '`' | '~' | '¸'),
}
}
/// What a physical key types on this layout, with shift, ctrl and
/// AltGr held or not. The keys that are not characters (arrows,
/// enter, backspace) and ctrl's shortcuts by the key's letter, as
/// [`from_code`] has them.
pub fn typed(self, code: u16, shift: bool, ctrl: bool, altgr: bool) -> Option<Typed> {
let character = |shift: bool, altgr: bool| {
self.rows().iter().find_map(|&(first, plain, shifted, third)| {
let i = usize::from(code.checked_sub(first)?);
let c = if altgr {
let c = third.chars().nth(i)?;
// Shift with AltGr: the capital, where there is one.
let mut upper = c.to_uppercase();
match (shift, upper.next(), upper.next()) {
(false, ..) => c,
(true, Some(u), None) if u != c => u,
_ => return None,
}
} else {
if shift { shifted } else { plain }.chars().nth(i)?
};
(c != '\0').then_some(c)
})
};
if ctrl {
// By the letter this layout puts there: ctrl-c copies
// where C is.
return match character(false, false)? {
'c' => Some(Typed::Key(Key::Copy)),
'v' => Some(Typed::Key(Key::Paste)),
c if c.is_ascii_lowercase() => Some(Typed::Key(Key::Ctrl(c))),
_ => None,
};
}
match from_code(code, false, false) {
Some(Key::Char(_)) | None => {}
Some(other) => return Some(Typed::Key(other)),
}
let c = character(shift, altgr)?;
Some(if self.dead(c) {
Typed::Dead(c)
} else {
Typed::Key(Key::Char(c))
})
}
}
/// A dead key's accent on the next character typed: `´` or `'` and `e`
/// is é. None where the accent has no such letter: then the accent and
/// the letter are typed as they are, and a space after a dead key types
/// the accent alone. On US-International `'` `c` is ç, as Windows has it.
pub fn compose(dead: char, c: char) -> Option<char> {
let (from, to) = match dead {
'\'' | '´' => ("aeiouyAEIOUY", "áéíóúýÁÉÍÓÚÝ"),
'`' => ("aeiouAEIOU", "àèìòùÀÈÌÒÙ"),
'^' => ("aeiouAEIOU", "âêîôûÂÊÎÔÛ"),
'"' | '¨' => ("aeiouyAEIOU", "äëïöüÿÄËÏÖÜ"),
'~' => ("anoANO", "ãñõÃÑÕ"),
'¸' => ("cC", "çÇ"),
_ => return None,
};
if dead == '\'' && matches!(c, 'c' | 'C') {
return Some(if c == 'c' { 'ç' } else { 'Ç' });
}
from.chars().position(|f| f == c).and_then(|i| to.chars().nth(i))
}
}
/// The calculator: a 4×4 keypad at the bottom, as large as the window
/// allows in both directions, centred; the number above it.
pub mod calculator {
use super::{Rect, margin};
const GAP: i32 = 16;
/// Room kept above the keypad for the number.
const DISPLAY: i32 = 200;
pub fn key(width: i32, height: i32, i: usize) -> Rect {
let m = margin(width);
let by_width = (width - 2 * m - 3 * GAP) / 4;
let by_height = (height - DISPLAY - m - 3 * GAP) / 4;
let size = by_width.min(by_height).min(180);
let pad = 4 * size + 3 * GAP;
let (left, top) = ((width - pad) / 2, height - m - pad);
let (col, row) = (i as i32 % 4, i as i32 / 4);
Rect::new(left + col * (size + GAP), top + row * (size + GAP), size, size)
}
pub fn key_center(width: i32, height: i32, i: usize) -> (i32, i32) {
super::center(key(width, height, i))
}
}
/// Paint: the canvas, and a bar along the bottom with the palette and Clear.
pub mod paint {
use super::{Rect, margin};
pub const BAR: i32 = 110;
pub const COLORS: usize = 6;
/// Swatch `i` (and Clear after the colours).
pub fn swatch(width: i32, height: i32, i: usize) -> Rect {
let m = margin(width);
let step = ((width - 2 * m) / (COLORS as i32 + 1)).min(96);
Rect::new(m + i as i32 * step + 8, height - BAR + 25, 60, 60)
}
pub fn swatch_center(width: i32, height: i32, i: usize) -> (i32, i32) {
super::center(swatch(width, height, i))
}
}
/// Calls: the contact list, a ringing screen, and the call.
pub mod calls {
use super::{Rect, list};
pub const ROW: i32 = 112;
pub fn contact(width: i32, i: usize) -> Rect {
list::card(width, ROW, i)
}
pub fn contact_center(width: i32, i: usize) -> (i32, i32) {
super::center(contact(width, i))
}
/// Decline (left) and answer (right) on an incoming call.
pub fn answer_buttons(width: i32, height: i32) -> (Rect, Rect) {
let y = height - 220;
(
Rect::new(width / 2 - 200, y, 160, 160),
Rect::new(width / 2 + 40, y, 160, 160),
)
}
/// End, while calling or in a call.
pub fn end_button(width: i32, height: i32) -> Rect {
Rect::new(width / 2 - 80, height - 220, 160, 160)
}
/// How much larger than it was sent the other side's video is shown:
/// twice when it fits above the buttons, else as is.
pub fn video_scale(width: i32, height: i32, (w, h): (i32, i32)) -> i32 {
if 2 * w <= width && 2 * h + 120 + 240 <= height {
2
} else {
1
}
}
pub fn answer_center(width: i32, height: i32) -> (i32, i32) {
super::center(answer_buttons(width, height).1)
}
}
/// A screen of centred content (the clock, About): where a block of
/// content `height` tall starts so that it sits a little above the middle.
pub fn centered_top(window_height: i32, height: i32) -> i32 {
((window_height - height) * 2 / 5).max(24)
}
#[cfg(test)]
mod tests {
extern crate std;
use super::*;
const SIZES: [(i32, i32); 4] = [(720, 1440), (1280, 800), (1920, 1080), (480, 800)];
fn app(size: (i32, i32)) -> (i32, i32) {
let a = shell::app_area(size.0, size.1);
(a.width, a.height)
}
fn inside(r: Rect, w: i32, h: i32) -> bool {
r.x >= 0 && r.y >= 0 && r.right() <= w && r.bottom() <= h && !r.is_empty()
}
#[test]
fn the_phone_layout_is_what_it_was() {
// 720 wide: four columns 64 apart, as before the layout was general.
assert_eq!(launcher::tile(720, 0), Rect::new(24, 180, 120, 120));
assert_eq!(launcher::tile(720, 5), Rect::new(24 + 184, 180 + 184, 120, 120));
let (w, h) = app((720, 1440));
assert_eq!(calculator::key(w, h, 0).width, 156);
}
#[test]
fn wide_screens_get_more_columns_and_a_centred_grid() {
assert_eq!(launcher::columns(720), 4);
assert!(launcher::columns(1280) >= 6);
let last = launcher::tile(1280, launcher::columns(1280) as usize - 1);
let first = launcher::tile(1280, 0);
assert_eq!(first.x, 1280 - last.right(), "the grid is centred");
}
#[test]
fn everything_fits_on_every_screen() {
for size in SIZES {
let (w, h) = app(size);
for i in 0..16 {
assert!(inside(calculator::key(w, h, i), w, h), "{size:?} key {i}");
}
for i in 0..=paint::COLORS {
assert!(inside(paint::swatch(w, h, i), w, h), "{size:?} swatch {i}");
}
let (list, chat) = messages::panes(w, h);
for (r, _) in keyboard::keys(keyboard::area(chat)) {
assert!(inside(r, w, h) && chat.contains(r.x, r.y), "{size:?} key {r:?}");
}
assert!(inside(messages::contact(w, h, 0), w, h));
// The notifications button clears the close button, and the
// list's cards that are shown fit the app area.
let notices = shell::notices(size.0);
assert!(inside(notices, size.0, shell::STATUS) && notices.x > shell::close(size.0).right() + 120);
let fit = shell::notices_fit(h);
assert!(fit >= 3, "{size:?} shows {fit}");
assert!(inside(shell::notice(w, fit - 1), w, h), "{size:?}");
assert!(shell::notice(w, 0).y > shell::notices_clear(w).bottom());
// The terminal, with the on-screen keyboard and without.
for keyboard in [true, false] {
let keys_top = if keyboard {
keyboard::area(Rect::new(0, 0, w, h)).y
} else {
h
};
let bottom = terminal::bottom(keys_top, keyboard);
let page = terminal::page(w, bottom, false);
assert!(
page.height > 0 && page.bottom() <= bottom && inside(page, w, h),
"{size:?} terminal"
);
assert!(inside(terminal::stop(w), w, h) && terminal::stop(w).bottom() < page.y);
if keyboard {
for i in 0..terminal::extra_keys(w) {
let key = terminal::extra_key(w, keys_top, i);
assert!(
inside(key, w, h) && key.y >= bottom && key.bottom() <= keys_top,
"{size:?} {i}"
);
assert!(key.width >= 40, "{size:?} extra key {i} is {} wide", key.width);
}
}
let page = terminal::page(w, bottom, true);
for i in 0..3 {
let option = terminal::option(w, bottom, i, 3);
assert!(inside(option, w, h) && option.bottom() <= bottom && option.y > page.bottom());
}
assert!(page.height > 0);
}
assert!(list.contains(messages::contact_center(w, h, 0).0, 200));
assert!(inside(store::button(w, 0), w, h));
let (no, yes) = calls::answer_buttons(w, h);
assert!(inside(no, w, h) && inside(yes, w, h));
}
}
#[test]
fn physical_keys_type_what_their_caps_say() {
use keyboard::{Key, from_code};
assert_eq!(from_code(30, false, false), Some(Key::Char('a')));
assert_eq!(from_code(30, true, false), Some(Key::Char('A')));
assert_eq!(from_code(2, true, false), Some(Key::Char('!')));
assert_eq!(from_code(11, false, false), Some(Key::Char('0')));
assert_eq!(from_code(51, false, false), Some(Key::Char(',')));
assert_eq!(from_code(53, true, false), Some(Key::Char('?')));
assert_eq!(from_code(57, false, false), Some(Key::Space));
assert_eq!(from_code(28, false, false), Some(Key::Enter));
assert_eq!(from_code(14, false, false), Some(Key::Backspace));
assert_eq!(from_code(keyboard::LEFT_SHIFT, false, false), None);
assert_eq!(from_code(1, false, false), Some(Key::Escape));
assert_eq!(from_code(15, false, false), Some(Key::Tab));
assert_eq!(from_code(103, false, false), Some(Key::Up));
assert_eq!(from_code(105, false, false), Some(Key::Left));
assert_eq!(from_code(111, false, false), Some(Key::Delete));
assert_eq!(from_code(47, false, true), Some(Key::Paste));
assert_eq!(from_code(46, true, true), Some(Key::Copy));
assert_eq!(from_code(30, false, true), Some(Key::Ctrl('a')));
assert_eq!(from_code(2, false, true), None, "ctrl with a digit types nothing");
}
#[test]
fn keyboard_layouts() {
use keyboard::{Key, Layout, Typed, compose};
let ch = |c| Some(Typed::Key(Key::Char(c)));
// Each key by its place: Q, the key beside L, the one left of 1.
let (q, beside_l, before_1, e, comma) = (16, 39, 41, 18, 51);
assert_eq!(Layout::Us.typed(q, false, false, false), ch('q'));
assert_eq!(Layout::Us.typed(beside_l, false, false, false), ch(';'));
assert_eq!(Layout::Dutch.typed(beside_l, false, false, false), ch('+'));
assert_eq!(Layout::Dutch.typed(before_1, false, false, false), ch('@'));
assert_eq!(Layout::Dutch.typed(3, true, false, false), ch('"'), "shift 2");
assert_eq!(Layout::Dutch.typed(e, false, false, true), ch('€'), "AltGr E");
assert_eq!(Layout::Dutch.typed(86, false, false, false), ch(']'));
// The accents: dead on US-International and Dutch, not on US.
let apostrophe = 40;
assert_eq!(Layout::Us.typed(apostrophe, false, false, false), ch('\''));
assert_eq!(
Layout::UsInternational.typed(apostrophe, false, false, false),
Some(Typed::Dead('\''))
);
assert_eq!(
Layout::UsInternational.typed(apostrophe, true, false, false),
Some(Typed::Dead('"'))
);
assert_eq!(
Layout::Dutch.typed(26, false, false, false),
Some(Typed::Dead('¨'))
);
assert_eq!(
Layout::Dutch.typed(26, true, false, false),
Some(Typed::Dead('^'))
);
assert_eq!(
Layout::Dutch.typed(13, false, false, true),
Some(Typed::Dead('¸'))
);
// AltGr on US-International, and its capitals.
assert_eq!(Layout::UsInternational.typed(e, false, false, true), ch('é'));
assert_eq!(Layout::UsInternational.typed(e, true, false, true), ch('É'));
assert_eq!(Layout::UsInternational.typed(comma, false, false, true), ch('ç'));
// é, ë, ç as the person types them.
assert_eq!(compose('\'', 'e'), Some('é'));
assert_eq!(compose('´', 'e'), Some('é'));
assert_eq!(compose('"', 'e'), Some('ë'));
assert_eq!(compose('¨', 'E'), Some('Ë'));
assert_eq!(compose('\'', 'c'), Some('ç'));
assert_eq!(compose('¸', 'c'), Some('ç'));
assert_eq!(compose('^', 'o'), Some('ô'));
assert_eq!(compose('`', 'a'), Some('à'));
assert_eq!(compose('~', 'n'), Some('ñ'));
assert_eq!(compose('\'', 'x'), None);
// Keys that are no characters, and ctrl by the letter's place.
assert_eq!(
Layout::Dutch.typed(28, false, false, false),
Some(Typed::Key(Key::Enter))
);
assert_eq!(
Layout::Dutch.typed(46, false, true, false),
Some(Typed::Key(Key::Copy))
);
assert_eq!(
Layout::Dutch.typed(q, false, true, false),
Some(Typed::Key(Key::Ctrl('q')))
);
for layout in Layout::ALL {
assert_eq!(Layout::from_name(layout.name()), Some(layout));
}
}
#[test]
fn shift_reaches_the_symbols_an_address_needs() {
use keyboard::shifted;
assert_eq!(shifted('a'), 'A');
assert_eq!(shifted('2'), '@');
assert_eq!(shifted('4'), '+');
assert_eq!(shifted('5'), '-');
assert_eq!(shifted(','), '?');
let typed: std::string::String = "1234567890,.".chars().map(shifted).collect();
assert!(typed.chars().all(|c| !c.is_ascii_alphanumeric()), "{typed}");
}
#[test]
fn keys_do_not_overlap() {
let keys = keyboard::keys(keyboard::area(Rect::new(0, 0, 720, 1336)));
for (i, (a, _)) in keys.iter().enumerate() {
for (b, _) in &keys[i + 1..] {
assert!(a.intersect(b).is_empty(), "{a:?} {b:?}");
}
}
}
}
/// The Bluetooth app: devices found as rows, a device's page.
pub mod bluetooth;