git clone https://garage44.eu/jeroen/pinnacle.git.. /programs/src/bin/calculator.rs
//! A calculator, built from a view: the sum so far over the number, over a
//! keypad of four columns and five rows that fills what the window leaves.
//! It works as a pocket calculator does: each operation is done as the next
//! one is pressed, left to right (2 + 3 × 4 is 20), = finishes the sum, %
//! takes a percentage (of the number before it for + and −: 200 + 10 % is
//! 220), ± turns the sign and ⌫ takes the last digit back. Numbers are
//! shown in the language's way (1.234,5 in Dutch), and a physical keyboard
//! types too: the digits, + - * /, Enter or =, Backspace, Escape (C), % and
//! both `.` and `,` for the decimal separator.
#![no_std]
#![no_main]
extern crate alloc;
use alloc::string::String;
use alloc::vec::Vec;
use pinnacle_locale::{localise_number, t};
use pinnacle_rt::abi::InputEvent;
use pinnacle_ui::keyboard::{Key, Keyboard};
use pinnacle_ui::{App, Event};
use pinnacle_view::{IntoView, Screen, Signal, View, el, signal};
/// How many digits a number typed may have.
const MAX_DIGITS: usize = 15;
/// How many significant digits a result is shown with: enough for any sum
/// typed, few enough that 0.1 + 0.2 is 0.3.
const SIGNIFICANT: usize = 12;
/// How many characters of the sum so far are shown: its end.
const SUM_KEPT: usize = 32;
/// An operation between two numbers.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum Op {
Add,
Subtract,
Multiply,
Divide,
}
impl Op {
fn symbol(self) -> &'static str {
match self {
Op::Add => "+",
Op::Subtract => "−",
Op::Multiply => "×",
Op::Divide => "÷",
}
}
/// `a` and `b` taken together, or why they cannot be.
fn apply(self, a: f64, b: f64) -> Result<f64, &'static str> {
let r = match self {
Op::Add => a + b,
Op::Subtract => a - b,
Op::Multiply => a * b,
Op::Divide if b == 0.0 => return Err(t("Cannot divide by zero")),
Op::Divide => a / b,
};
if r.is_finite() {
Ok(r)
} else {
Err(t("Too large to show"))
}
}
}
/// What a key on the keypad, or of a physical keyboard, does.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum Press {
Digit(u8),
Point,
Op(Op),
Equals,
Percent,
Sign,
Back,
Clear,
}
/// A key of the keypad: its label, the name `cargo xtask` taps, and what it
/// does. The digits, the operations, C and = keep the names they had on the
/// keypad of four by four (their place on it, counted from 7), so a demo
/// that taps those still works; the keys added since are named by what
/// they do.
struct Pad {
label: &'static str,
name: &'static str,
press: Press,
}
const fn key(label: &'static str, name: &'static str, press: Press) -> Pad {
Pad { label, name, press }
}
/// The keypad, row by row: C ⌫ % ÷ / 7 8 9 × / 4 5 6 − / 1 2 3 + / ± 0 , =.
/// The decimal key's label is the language's separator, put in when drawn.
const KEYS: [Pad; 20] = [
key("C", "12", Press::Clear),
key("⌫", "back", Press::Back),
key("%", "percent", Press::Percent),
key("÷", "3", Press::Op(Op::Divide)),
key("7", "0", Press::Digit(7)),
key("8", "1", Press::Digit(8)),
key("9", "2", Press::Digit(9)),
key("×", "7", Press::Op(Op::Multiply)),
key("4", "4", Press::Digit(4)),
key("5", "5", Press::Digit(5)),
key("6", "6", Press::Digit(6)),
key("−", "11", Press::Op(Op::Subtract)),
key("1", "8", Press::Digit(1)),
key("2", "9", Press::Digit(2)),
key("3", "10", Press::Digit(3)),
key("+", "15", Press::Op(Op::Add)),
key("±", "sign", Press::Sign),
key("0", "13", Press::Digit(0)),
key(".", "decimal", Press::Point),
key("=", "14", Press::Equals),
];
/// A piece of the sum shown above the number.
#[derive(Clone, PartialEq, Debug)]
enum Part {
/// A number, as [`Calc::entry`] holds it.
Number(String),
Op(Op),
Equals,
}
/// The calculator's state. Numbers are kept as typed, in plain digits with
/// `.` and `-`, and put in the language's way only when shown.
struct Calc {
/// The number shown: being typed, or a result.
entry: String,
/// The number is being typed: a digit goes on its end.
typing: bool,
/// A number came since the last operation was pressed: another
/// operation pressed now goes with it, rather than replacing the last.
operand: bool,
/// The number before the operation pressed, and that operation.
held: Option<f64>,
op: Option<Op>,
/// The sum so far, shown above the number.
sum: Vec<Part>,
/// = finished the sum: the next digit starts another.
done: bool,
/// Why the last result could not be had, shown until the next key.
error: Option<&'static str>,
}
impl Default for Calc {
fn default() -> Self {
Calc {
entry: String::from("0"),
typing: false,
operand: false,
held: None,
op: None,
sum: Vec::new(),
done: false,
error: None,
}
}
}
impl Calc {
fn value(&self) -> f64 {
self.entry.parse().unwrap_or(0.0)
}
/// Starts typing a new number, when one is not being typed already.
fn begin(&mut self) {
if !self.typing {
if self.done {
self.sum.clear();
self.done = false;
}
self.entry = String::from("0");
self.typing = true;
self.operand = true;
}
}
/// A result: shown, or the reason there is none.
fn result(&mut self, r: Result<f64, &'static str>) -> Option<f64> {
match r.ok().and_then(|r| format_number(r).map(|s| (r, s))) {
Some((r, s)) => {
self.entry = s;
Some(r)
}
None => {
let why = r.err().unwrap_or(t("Too large to show"));
*self = Calc::default();
self.error = Some(why);
None
}
}
}
fn press(&mut self, press: Press) {
// After an error, any key starts afresh; a digit also counts.
if self.error.take().is_some() && !matches!(press, Press::Digit(_) | Press::Point) {
return;
}
match press {
Press::Clear => *self = Calc::default(),
Press::Digit(d) => {
self.begin();
if self.entry.chars().filter(char::is_ascii_digit).count() >= MAX_DIGITS {
return;
}
match self.entry.as_str() {
"0" => self.entry.clear(),
"-0" => {
self.entry.pop();
}
_ => {}
}
self.entry.push(char::from(b'0' + d));
}
Press::Point => {
self.begin();
if !self.entry.contains('.') {
self.entry.push('.');
}
}
Press::Back => {
if self.typing {
self.entry.pop();
if self.entry.is_empty() || self.entry == "-" {
self.entry = String::from("0");
}
}
}
Press::Sign => {
// Right after an operation, ± starts the next number negative.
if !self.operand {
self.begin();
}
if let Some(rest) = self.entry.strip_prefix('-') {
self.entry = String::from(rest);
} else {
self.entry.insert(0, '-');
}
}
Press::Percent => {
let b = self.value();
let r = match (self.held, self.op) {
(Some(a), Some(Op::Add | Op::Subtract)) => a * b / 100.0,
_ => b / 100.0,
};
if self.result(Ok(r)).is_none() {
return;
}
self.typing = false;
self.operand = true;
}
Press::Op(op) => {
if self.op.is_some() && !self.operand {
// An operation pressed again: it replaces the last.
self.sum.pop();
} else {
if self.done {
self.sum.clear();
self.done = false;
}
self.sum.push(Part::Number(self.entry.clone()));
let b = self.value();
let held = match (self.held, self.op) {
(Some(a), Some(last)) => match self.result(last.apply(a, b)) {
Some(r) => r,
None => return,
},
_ => b,
};
self.held = Some(held);
}
self.sum.push(Part::Op(op));
self.op = Some(op);
self.typing = false;
self.operand = false;
}
Press::Equals => {
let (Some(a), Some(op)) = (self.held, self.op) else {
return;
};
let b = self.value();
self.sum.push(Part::Number(self.entry.clone()));
self.sum.push(Part::Equals);
let sum = core::mem::take(&mut self.sum);
if self.result(op.apply(a, b)).is_some() {
self.sum = sum;
self.held = None;
self.op = None;
self.typing = false;
self.operand = true;
self.done = true;
}
}
}
}
/// The number as shown: in the language's way, or the error.
fn shown(&self) -> String {
match self.error {
Some(why) => String::from(why),
None => local(&self.entry),
}
}
/// The sum so far, as shown above the number.
fn sum_shown(&self) -> String {
let mut out = String::new();
for part in &self.sum {
if !out.is_empty() {
out.push(' ');
}
match part {
Part::Number(n) => out.push_str(&local(n)),
Part::Op(op) => out.push_str(op.symbol()),
Part::Equals => out.push('='),
}
}
// A long sum keeps its end, where the number goes on.
let n = out.chars().count();
if n > SUM_KEPT {
let tail: String = out.chars().skip(n - SUM_KEPT + 1).collect();
out = alloc::format!("…{tail}");
}
out
}
}
/// `v` with at most [`SIGNIFICANT`] digits, and in powers of ten when it
/// is too large or too small for that ("1.5e20"); None when it is no
/// number at all.
fn format_number(v: f64) -> Option<String> {
if !v.is_finite() {
return None;
}
let a = v.abs();
if a != 0.0 && !(1e-9..1e15).contains(&a) {
let s = alloc::format!("{:.*e}", SIGNIFICANT - 3, v);
let (mantissa, exponent) = s.split_once('e')?;
let mantissa = mantissa.trim_end_matches('0').trim_end_matches('.');
return Some(alloc::format!("{mantissa}e{exponent}"));
}
let whole = alloc::format!("{}", a as u64).len();
let places = SIGNIFICANT.saturating_sub(whole);
let s = alloc::format!("{v:.places$}");
let s = if s.contains('.') {
s.trim_end_matches('0').trim_end_matches('.')
} else {
&s
};
Some(if s == "-0" {
String::from("0")
} else {
String::from(s)
})
}
/// A number kept in plain digits, with its thousands grouped and in the
/// language's separators: "-1234.5" is "-1.234,5" in Dutch.
fn local(number: &str) -> String {
let (mantissa, exponent) = match number.split_once('e') {
Some((m, e)) => (m, Some(e)),
None => (number, None),
};
let (sign, digits) = match mantissa.strip_prefix('-') {
Some(rest) => ("-", rest),
None => ("", mantissa),
};
let (whole, fraction) = match digits.split_once('.') {
Some((w, f)) => (w, Some(f)),
None => (digits, None),
};
let mut out = String::from(sign);
for (i, c) in whole.chars().enumerate() {
if i > 0 && (whole.len() - i).is_multiple_of(3) {
out.push(',');
}
out.push(c);
}
if let Some(f) = fraction {
out.push('.');
out.push_str(f);
}
if let Some(e) = exponent {
out.push('e');
out.push_str(e);
}
localise_number(&out)
}
/// What a key of a physical keyboard presses, if anything: by the
/// character it types, or the keypad's keys by their code.
fn typed(key: Key) -> Option<Press> {
Some(match key {
Key::Char(c @ '0'..='9') => Press::Digit(c as u8 - b'0'),
Key::Char('.' | ',') => Press::Point,
Key::Char('+') => Press::Op(Op::Add),
Key::Char('-' | '−') => Press::Op(Op::Subtract),
Key::Char('*' | 'x' | '×') => Press::Op(Op::Multiply),
Key::Char('/' | '÷') => Press::Op(Op::Divide),
Key::Char('%') => Press::Percent,
Key::Char('=') | Key::Enter => Press::Equals,
Key::Backspace => Press::Back,
Key::Escape | Key::Delete | Key::Char('c' | 'C') => Press::Clear,
_ => return None,
})
}
/// The number pad's keys (Linux key codes), which the layouts do not type.
fn keypad(code: u16) -> Option<Press> {
Some(match code {
71 => Press::Digit(7),
72 => Press::Digit(8),
73 => Press::Digit(9),
74 => Press::Op(Op::Subtract),
75 => Press::Digit(4),
76 => Press::Digit(5),
77 => Press::Digit(6),
78 => Press::Op(Op::Add),
79 => Press::Digit(1),
80 => Press::Digit(2),
81 => Press::Digit(3),
82 => Press::Digit(0),
83 => Press::Point,
55 => Press::Op(Op::Multiply),
98 => Press::Op(Op::Divide),
_ => return None,
})
}
/// The font size for a text of `n` characters: large while it fits, then
/// smaller, so a long result stays whole rather than cut off.
fn size_for(n: usize, large: usize, fits: usize) -> usize {
if n <= fits {
large
} else {
(large * fits / n).max(large / 3)
}
}
/// The sum so far and the number, right-aligned, over the keypad: twenty
/// keys in a grid of four columns that share the window's width and what
/// height is left.
fn page(shown: Signal<String>, sum: Signal<String>, tapped: &Signal<Option<usize>>) -> View {
// Five rows of four, each row and each key growing to share what the
// window leaves: the keys fill the lower part of any window.
let mut keypad = el("div").attr(
"style",
"flex: 1.5; display: flex; flex-direction: column; gap: 12px",
);
let mut row = el("div").attr("style", "flex: 1; display: flex; gap: 12px");
for (i, pad) in KEYS.iter().enumerate() {
// = in the accent, the operations a shade darker than the digits,
// as the hand-drawn keypad had them; C, ⌫ and % darker too.
let (variant, plate) = match pad.press {
Press::Equals => (Some("primary"), ""),
Press::Digit(_) | Press::Point | Press::Sign => (None, ""),
_ => (None, "background: var(--m-pressed); "),
};
let label = match pad.press {
Press::Point => localise_number("."),
_ => String::from(pad.label),
};
let spoken = match pad.press {
Press::Back => Some(t("Delete last digit")),
Press::Sign => Some(t("Change sign")),
Press::Percent => Some(t("Percent")),
Press::Clear => Some(t("Clear")),
Press::Point => Some(t("Decimal separator")),
_ => None,
};
let tapped = tapped.clone();
row = row.child(
el("button")
.class("m-button")
.attr("type", "button")
.attr("data-variant", variant)
.attr("data-name", pad.name)
.attr("aria-label", spoken)
.attr(
"style",
alloc::format!(
"{plate}flex: 1; min-width: 0; min-height: 40px; height: auto; \
font-size: 26px; border-radius: 999px"
),
)
.on("click", move |_| tapped.set(Some(i)))
.child(label),
);
if i % 4 == 3 {
keypad = keypad.child(core::mem::replace(
&mut row,
el("div").attr("style", "flex: 1; display: flex; gap: 12px"),
));
}
}
let (sum_size, shown_size) = (sum.clone(), shown.clone());
el("main")
.attr(
"style",
"height: 100vh; max-width: 560px; margin: 0 auto; padding: 24px 16px; \
display: flex; flex-direction: column; gap: 16px",
)
.child(
el("div")
.attr(
"style",
"flex: 1; min-height: 0; display: flex; flex-direction: column; \
justify-content: flex-end; align-items: flex-end; gap: 4px; overflow: hidden",
)
.child(
el("div")
.attr("data-name", "sum")
.attr("style", move || {
let n = sum_size.with(|s| s.chars().count());
alloc::format!(
"font-size: {}px; min-height: 30px; color: var(--m-text-dim); \
white-space: nowrap; overflow: hidden",
size_for(n, 24, SUM_KEPT)
)
})
.child(move || sum.get()),
)
.child(
el("div")
.attr("data-name", "result")
.attr("role", "status")
.attr("style", move || {
let n = shown_size.with(|s| s.chars().count());
alloc::format!(
"font-size: {}px; white-space: nowrap; overflow: hidden",
size_for(n, 64, 9)
)
})
.child(move || shown.get()),
),
)
.child(keypad)
.into_view()
}
#[unsafe(no_mangle)]
fn main(_argument: u64) -> u64 {
let mut app = App::new("Calculator");
let mut calc = Calc::default();
let mut keys = Keyboard::new();
let mut screen = Screen::new(app.width, app.height);
let shown = signal(calc.shown());
let sum = signal(String::new());
let tapped: Signal<Option<usize>> = signal(None);
screen.mount(page(shown.clone(), sum.clone(), &tapped));
screen.draw(&mut app.canvas(), true);
app.present_all();
screen.announce("calculator: key ");
loop {
match app.next_event(None) {
Event::Input(e) => {
let mut pressed = None;
if e.kind == InputEvent::KEY {
// A physical key: the calculator's when it presses one
// of its keys, the view's otherwise (Tab, the arrows).
pressed = if e.value != 0 { keypad(e.code) } else { None };
if pressed.is_none() {
match keys.key_event(e.code, e.value).and_then(typed) {
Some(p) => pressed = Some(p),
None => screen.input(&e),
}
}
} else {
screen.input(&e);
if let Some(i) = tapped.get_untracked() {
tapped.set(None);
pressed = Some(KEYS[i].press);
}
}
if let Some(press) = pressed {
calc.press(press);
pinnacle_rt::println!("calculator: {:?}, shows {}", press, calc.entry);
shown.set(calc.shown());
sum.set(calc.sum_shown());
}
if let Some(area) = screen.draw(&mut app.canvas(), false) {
app.present(area);
}
}
Event::Shown(true) | Event::Resized => {
screen.resize(app.width, app.height);
screen.draw(&mut app.canvas(), true);
app.present_all();
screen.announce("calculator: key ");
}
Event::Preferences => {
// Another language: its separators, and its texts.
screen.restyle();
shown.set(calc.shown());
sum.set(calc.sum_shown());
screen.clear();
screen.mount(page(shown.clone(), sum.clone(), &tapped));
screen.draw(&mut app.canvas(), true);
app.present_all();
}
Event::Closed => return 0,
_ => {}
}
}
}