From 297aca86a155956f07534c2aa1a37d83a9b524e8 Mon Sep 17 00:00:00 2001 From: Michael Aguiar Date: Wed, 25 Nov 2026 11:51:51 -0700 Subject: [PATCH 01/50] Set up the crate, CI and the benchmark harness bench/run measures Alias Calc, omacalc and GNOME Calculator the same way (exec to Hyprland openwindow, PSS/RSS/threads after 2 s, wakeups over 5 idle seconds) and prints one table of medians. The README records the baselines the app has to beat. ALI-2097 --- .github/workflows/ci.yml | 65 +++++++++++++++ .gitignore | 1 + Cargo.lock | 7 ++ Cargo.toml | 19 +++++ README.md | 28 +++++++ bench/calcbench.py | 165 +++++++++++++++++++++++++++++++++++++++ bench/run | 47 +++++++++++ src/main.rs | 3 + 8 files changed, 335 insertions(+) create mode 100644 .github/workflows/ci.yml create mode 100644 Cargo.lock create mode 100644 Cargo.toml create mode 100755 bench/calcbench.py create mode 100755 bench/run create mode 100644 src/main.rs diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..81b7f96 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,65 @@ +# Runs on the org's self-hosted home runners (shared with other +# repositories: one VM, one Docker daemon). Their host has no Rust and no +# sudo, so the job runs in a container where it is root and can +# apt-install what it needs. The runner runs as uid 1001 and cleans the +# workspace and its temp directory before the next job; it can't remove +# what root left there, so the job ends by handing both back. +# +# No test opens a window. +name: CI + +on: + push: + branches: [main] + pull_request: + +# A PR's runs share a group, so a new push cancels the one it supersedes. +# Each push to main has a group of its own, so every commit gets a result. +concurrency: + group: ci-${{ github.event_name == 'pull_request' && github.ref || github.run_id }} + cancel-in-progress: ${{ github.event_name == 'pull_request' }} + +# The job runs PR code as root on shared runners: its token reads only. +permissions: + contents: read + +env: + CARGO_TERM_COLOR: always + DEBIAN_FRONTEND: noninteractive + LANG: C.UTF-8 + +jobs: + check: + name: fmt, clippy, tests, release build + runs-on: [self-hosted, home] + container: ubuntu:24.04 + timeout-minutes: 30 + steps: + # git before checkout, or checkout falls back to a tarball; a C + # compiler for the linker; and the two libraries the app links. + - name: Install build dependencies + run: | + apt-get update -qq + apt-get install -y -qq --no-install-recommends \ + git ca-certificates curl build-essential pkg-config \ + libwayland-dev libxkbcommon-dev python3 >/dev/null + - uses: actions/checkout@v4 + # A clean Rust each time: an earlier job's half-installed rustup in + # the shared $HOME breaks the install. + - name: Start from a clean home + run: rm -rf "$HOME/.cargo" "$HOME/.rustup" + - uses: dtolnay/rust-toolchain@stable + with: + components: rustfmt, clippy + - uses: Swatinem/rust-cache@v2 + - run: cargo fmt --all --check + - run: cargo clippy --all-targets --locked -- -D warnings + - run: cargo test --locked + - run: cargo build --release --locked + - name: Benchmark scripts parse + run: | + python3 -m py_compile bench/calcbench.py + bash -n bench/run + - name: Hand the workspace back to the runner user + if: always() + run: chown -R 1001:1001 "$GITHUB_WORKSPACE" "$RUNNER_TEMP" diff --git a/.gitignore b/.gitignore index ea8c4bf..df611ec 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,2 @@ /target +__pycache__/ diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 0000000..6654869 --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,7 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "alias-calc" +version = "0.1.0" diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..9b1e478 --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,19 @@ +[package] +name = "alias-calc" +version = "0.1.0" +edition = "2024" +license = "LicenseRef-Proprietary" +description = "A tiny, instant calculator for aliasOS" +publish = false + +[dependencies] + +[profile.release] +lto = "fat" +codegen-units = 1 +opt-level = 3 +panic = "abort" +strip = true + +[profile.dev.package."*"] +opt-level = 2 diff --git a/README.md b/README.md index 04469e3..3240860 100644 --- a/README.md +++ b/README.md @@ -3,3 +3,31 @@ A tiny, instant calculator for aliasOS. It starts faster, uses less memory and wakes the CPU less than omacalc and GNOME Calculator, does exact decimal math, and follows the live aliasOS theme. Linear project: Alias Calc (P-ALI-28). + +## Build + +```sh +cargo build --release +``` + +The binary is `target/release/alias-calc`. It links only `wayland` and `libxkbcommon`. + +## Benchmark + +Alias Calc must beat omacalc and GNOME Calculator on startup, memory and idle wakeups. In a Hyprland session, run: + +```sh +OMACALC=/path/to/omacalc bench/run # 10 runs each +bench/run --runs 3 # quicker +``` + +For each app it times exec until Hyprland reports the window open, reads PSS, RSS and threads 2 s later, and counts wakeups over the next 5 idle seconds. It prints the medians as one table. The windows open on the current workspace, so leave the machine alone while it runs. omacalc builds from with `bin/build`. + +Baselines (2026-11-25, RTX 4090, 4K at scale 1, median of 10): + +| | Target | omacalc (e43fd0a) | GNOME Calculator 51.1 | +|---|---|---|---| +| Time to window mapped | < 20 ms | 148 ms | 241 ms | +| PSS | < 8 MB | 80 MB | 66 MB | +| Threads | 1 | 7 | 20 | +| Idle wakeups/s | 0 | 3 | 348 | diff --git a/bench/calcbench.py b/bench/calcbench.py new file mode 100755 index 0000000..f04f596 --- /dev/null +++ b/bench/calcbench.py @@ -0,0 +1,165 @@ +#!/usr/bin/env python3 +"""Measure one GUI calculator's launch on Hyprland. + +Each run starts the command, then times how long Hyprland takes to report the +window opened (`openwindow` on its event socket, sent once the app's first +buffer maps the toplevel). After the window settles, it reads PSS, RSS and the +thread count for the process tree, then counts context switches (wakeups) over +an idle period. It prints the medians as one JSON line. + +Usage: calcbench.py [--runs N] -- cmd args... + calcbench.py --table < results.jsonl + +The windows open on the current workspace, so leave the machine alone while it +runs. +""" +import argparse +import json +import os +import signal +import socket +import statistics +import subprocess +import sys +import time + +SETTLE = 2.0 # seconds after map before reading memory +IDLE = 5.0 # seconds of idle to count wakeups over +MAP_TIMEOUT = 10.0 + + +def event_socket(): + sig = os.environ.get("HYPRLAND_INSTANCE_SIGNATURE") + if not sig: + sys.exit("calcbench: needs a Hyprland session (HYPRLAND_INSTANCE_SIGNATURE is unset)") + return f"{os.environ['XDG_RUNTIME_DIR']}/hypr/{sig}/.socket2.sock" + + +def tree(pid): + """The process and all its descendants.""" + pids, todo = [], [pid] + while todo: + p = todo.pop() + pids.append(p) + try: + for t in os.listdir(f"/proc/{p}/task"): + with open(f"/proc/{p}/task/{t}/children") as f: + todo += [int(c) for c in f.read().split()] + except OSError: + pass + return pids + + +def memory(pids): + pss = rss = threads = 0 + for p in pids: + try: + with open(f"/proc/{p}/smaps_rollup") as f: + for line in f: + key, value = line.split(":", 1) + if key == "Pss": + pss += int(value.split()[0]) + elif key == "Rss": + rss += int(value.split()[0]) + threads += len(os.listdir(f"/proc/{p}/task")) + except OSError: + pass + return pss, rss, threads + + +def switches(pids): + total = 0 + for p in pids: + try: + for t in os.listdir(f"/proc/{p}/task"): + with open(f"/proc/{p}/task/{t}/status") as f: + for line in f: + if line.startswith(("voluntary_ctxt", "nonvoluntary_ctxt")): + total += int(line.split()[1]) + except OSError: + pass + return total + + +def wait_for_window(sock, wclass): + deadline = time.perf_counter() + MAP_TIMEOUT + buf = b"" + while True: + sock.settimeout(max(0.01, deadline - time.perf_counter())) + chunk = sock.recv(65536) + if not chunk: + raise ConnectionError("Hyprland closed the event socket") + buf += chunk + *lines, buf = buf.split(b"\n") + for line in lines: + if line.startswith(b"openwindow>>") and wclass in line.decode(errors="replace").lower(): + return time.perf_counter() + + +def run_once(cmd, wclass, path): + sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) + sock.connect(path) + start = time.perf_counter() + proc = subprocess.Popen(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, + start_new_session=True) + try: + mapped = wait_for_window(sock, wclass) + sock.close() + time.sleep(SETTLE) + pids = tree(proc.pid) + pss, rss, threads = memory(pids) + before = switches(pids) + time.sleep(IDLE) + wakeups = (switches(tree(proc.pid)) - before) / IDLE + finally: + sock.close() + try: + os.killpg(proc.pid, signal.SIGTERM) + except ProcessLookupError: + pass + proc.wait() + time.sleep(0.5) + return dict(map_ms=(mapped - start) * 1000, pss_kb=pss, rss_kb=rss, threads=threads, + wakeups_s=wakeups) + + +def table(): + """Print calcbench JSON lines from stdin as one table.""" + rows = [json.loads(line) for line in sys.stdin if line.strip()] + cols = [("map_ms", "map ms"), ("map_ms_min", "min ms"), ("pss_kb", "PSS MiB"), + ("rss_kb", "RSS MiB"), ("threads", "threads"), ("wakeups_s", "wakeups/s")] + print(" " * 18 + "".join(f"{label:>11}" for _, label in cols)) + for row in rows: + cells = [row[k] / 1024 if k.endswith("_kb") else row[k] for k, _ in cols] + print(f"{row['name']:18}" + "".join(f"{v:>11.1f}" for v in cells)) + if rows: + print(f"median of {rows[0]['runs']} runs each") + + +def main(): + argv = sys.argv[1:] + if argv == ["--table"]: + return table() + if "--" not in argv: + sys.exit(__doc__) + split = argv.index("--") + parser = argparse.ArgumentParser() + parser.add_argument("--runs", type=int, default=10) + parser.add_argument("name") + parser.add_argument("wclass") + args = parser.parse_args(argv[:split]) + cmd = argv[split + 1:] + path = event_socket() + + try: + results = [run_once(cmd, args.wclass.lower(), path) for _ in range(args.runs)] + except (TimeoutError, socket.timeout): + sys.exit(f"calcbench: {args.name}: no window within {MAP_TIMEOUT:.0f} s") + + median = {k: round(statistics.median(r[k] for r in results), 1) for k in results[0]} + median["map_ms_min"] = round(min(r["map_ms"] for r in results), 1) + print(json.dumps({"name": args.name, "runs": args.runs, **median})) + + +if __name__ == "__main__": + main() diff --git a/bench/run b/bench/run new file mode 100755 index 0000000..26c8b62 --- /dev/null +++ b/bench/run @@ -0,0 +1,47 @@ +#!/bin/bash +# Benchmark Alias Calc against omacalc and GNOME Calculator and print one +# table. Needs a Hyprland session; the windows open on the current workspace. +# +# bench/run [--runs N] +# +# omacalc comes from $OMACALC, else `omacalc` on PATH, else it's skipped. +# Build it from https://github.com/omacom/omacalc with `bin/build`. +# GNOME Calculator must not already be running (it would hand off to the +# running copy instead of starting). + +set -euo pipefail +cd "$(dirname "$0")/.." + +runs=10 +if [[ ${1:-} == --runs ]]; then runs=$2; fi + +cargo build --release --locked --quiet +results=() + +bench() { + local name=$1 class=$2 + shift 2 + local row + if row=$(python3 -I bench/calcbench.py --runs "$runs" "$name" "$class" -- "$@"); then + results+=("$row") + fi +} + +bench alias-calc com.aliasproject.calc target/release/alias-calc + +omacalc=${OMACALC:-$(command -v omacalc || true)} +if [[ -n $omacalc ]]; then + bench omacalc omacalc "$omacalc" +else + echo "Skipping omacalc: set OMACALC or put omacalc on PATH." >&2 +fi + +if command -v gnome-calculator >/dev/null; then + if pgrep -f '(^|/)gnome-calculator( |$)' >/dev/null; then + echo "Skipping GNOME Calculator: it's already running." >&2 + else + bench gnome-calculator org.gnome.calculator gnome-calculator + fi +fi + +printf '%s\n' "${results[@]}" | python3 -I bench/calcbench.py --table diff --git a/src/main.rs b/src/main.rs new file mode 100644 index 0000000..521ff7f --- /dev/null +++ b/src/main.rs @@ -0,0 +1,3 @@ +//! Alias Calc: a tiny, instant calculator for aliasOS. + +fn main() {} From dbff06dab40071bfc2740c6ba4e05791a6c1222c Mon Sep 17 00:00:00 2001 From: Michael Aguiar Date: Wed, 25 Nov 2026 12:00:23 -0700 Subject: [PATCH 02/50] Open the window: xdg toplevel drawn into a wl_shm buffer One thread blocking in poll on the Wayland socket, with no timeouts, so an idle window never wakes on its own (Hyprland's 1.5 s ping is the only wakeup). Pure-Rust Wayland, so the binary links only libc and libgcc_s. Sharp at fractional scales via fractional-scale-v1 + viewporter, falling back to integer buffer scales. Window title Calculator, app ID com.aliasproject.calc. ALIAS_CALC_TRACE=1 prints startup timings. bench/run floats all three apps first, as they are in daily use. ALI-2098 --- Cargo.lock | 345 +++++++++++++++++++++++++++++++++++++++++++ Cargo.toml | 3 + README.md | 15 +- bench/run | 5 + src/main.rs | 35 ++++- src/trace.rs | 24 +++ src/window.rs | 400 ++++++++++++++++++++++++++++++++++++++++++++++++++ 7 files changed, 825 insertions(+), 2 deletions(-) create mode 100644 src/trace.rs create mode 100644 src/window.rs diff --git a/Cargo.lock b/Cargo.lock index 6654869..3c619b0 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5,3 +5,348 @@ version = 4 [[package]] name = "alias-calc" version = "0.1.0" +dependencies = [ + "rustix", + "smithay-client-toolkit", + "wayland-protocols", +] + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + +[[package]] +name = "cc" +version = "1.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "02f0e023adb368345ce0ca6cdfc0f24a06554468d0e8503e14a0841de79bfa69" +dependencies = [ + "find-msvc-tools", + "shlex", +] + +[[package]] +name = "cursor-icon" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f27ae1dd37df86211c42e150270f82743308803d90a6f6e6651cd730d5e1732f" + +[[package]] +name = "downcast-rs" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75b325c5dbd37f80359721ad39aca5a29fb04c89279657cffdda8736d0c0b9d2" + +[[package]] +name = "errno" +version = "0.3.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e35d6e78f4cebb90e51d543db8fe41528851d6deeef6ef21ebd4bfdc1e784776" +dependencies = [ + "libc", + "windows-sys", +] + +[[package]] +name = "find-msvc-tools" +version = "0.1.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48" + +[[package]] +name = "libc" +version = "0.2.191" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" + +[[package]] +name = "linux-raw-sys" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" + +[[package]] +name = "log" +version = "0.4.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "memmap2" +version = "0.9.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b0ca1155a9ecc25aa12e8313a119f32edf0255fea2f44839c4ac0a12b2ac157" +dependencies = [ + "libc", +] + +[[package]] +name = "pkg-config" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548" + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quick-xml" +version = "0.41.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e660451e55124f798a69a5af3f49ccfbefbd41910eefd25caf2393e1f3473ec1" +dependencies = [ + "memchr", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "rustix" +version = "1.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa" +dependencies = [ + "bitflags", + "errno", + "libc", + "linux-raw-sys", + "windows-sys", +] + +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + +[[package]] +name = "smallvec" +version = "1.16.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3244542535d5de959d90ec55d1b5ff0fd2bb7b1310223907d5f11932847f7b59" + +[[package]] +name = "smithay-client-toolkit" +version = "0.21.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "74dc9ee14b0fdcb535f9556141bacac070c994a977d2240ee455d7438a617f00" +dependencies = [ + "bitflags", + "cursor-icon", + "log", + "memmap2", + "rustix", + "thiserror", + "wayland-client", + "wayland-csd-frame", + "wayland-cursor", + "wayland-protocols", + "wayland-protocols-experimental", + "wayland-protocols-misc", + "wayland-protocols-wlr", + "wayland-scanner", + "xkeysym", +] + +[[package]] +name = "syn" +version = "3.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "thiserror" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e" +dependencies = [ + "thiserror-impl", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "wayland-backend" +version = "0.3.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38a91b4eaddff87b1cd1074985e3713da4af2c49742d1b356b2c01670a67a078" +dependencies = [ + "cc", + "downcast-rs", + "rustix", + "smallvec", + "wayland-sys", +] + +[[package]] +name = "wayland-client" +version = "0.31.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3c36a0f861ad76d0901f2800b46321410d9f73f2ea88aac0650d86c32688073" +dependencies = [ + "bitflags", + "rustix", + "wayland-backend", + "wayland-scanner", +] + +[[package]] +name = "wayland-csd-frame" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "625c5029dbd43d25e6aa9615e88b829a5cad13b2819c4ae129fdbb7c31ab4c7e" +dependencies = [ + "bitflags", + "cursor-icon", + "wayland-backend", +] + +[[package]] +name = "wayland-cursor" +version = "0.31.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a52d18780be9b1314328a3de5f930b73d2200112e3849ca6cb11822793fb34d" +dependencies = [ + "rustix", + "wayland-client", + "xcursor", +] + +[[package]] +name = "wayland-protocols" +version = "0.32.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23d0c813de3daa2ed6520af85a3bd49b0e722a3078506899aa9686fea58dc4b6" +dependencies = [ + "bitflags", + "wayland-backend", + "wayland-client", + "wayland-scanner", +] + +[[package]] +name = "wayland-protocols-experimental" +version = "20251230.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "91c6c3e7178e553d093d46999032bc79aafea9dedd71dd702c8ace7bbc25cf13" +dependencies = [ + "bitflags", + "wayland-backend", + "wayland-client", + "wayland-protocols", + "wayland-scanner", +] + +[[package]] +name = "wayland-protocols-misc" +version = "0.3.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e9567599ef23e09b8dad6e429e5738d4509dfc46b3b21f32841a304d16b29c8" +dependencies = [ + "bitflags", + "wayland-backend", + "wayland-client", + "wayland-protocols", + "wayland-scanner", +] + +[[package]] +name = "wayland-protocols-wlr" +version = "0.3.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eb04e52f7836d7c7976c78ca0250d61e33873c34156a2a1fc9474828ec268234" +dependencies = [ + "bitflags", + "wayland-backend", + "wayland-client", + "wayland-protocols", + "wayland-scanner", +] + +[[package]] +name = "wayland-scanner" +version = "0.31.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "338e30461b3a2b67d70eb30a6d89f8e0c93a833e07d2ae89085cd070c4a00ac0" +dependencies = [ + "proc-macro2", + "quick-xml", + "quote", +] + +[[package]] +name = "wayland-sys" +version = "0.31.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d8eab23fefc9e41f8e841df4a9c707e8a8c4ed26e944ef69297184de2785e3be" +dependencies = [ + "pkg-config", +] + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "xcursor" +version = "0.3.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "163b33ed8786455e2fa5d72f554057ce3f3182425434f756cd39c99839d88e23" + +[[package]] +name = "xkeysym" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9cc00251562a284751c9973bace760d86c0276c471b4be569fe6b068ee97a56" diff --git a/Cargo.toml b/Cargo.toml index 9b1e478..aace7ce 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -7,6 +7,9 @@ description = "A tiny, instant calculator for aliasOS" publish = false [dependencies] +rustix = { version = "1", default-features = false, features = ["std", "event"] } +smithay-client-toolkit = { version = "0.21", default-features = false } +wayland-protocols = { version = "0.32", features = ["client", "staging"] } [profile.release] lto = "fat" diff --git a/README.md b/README.md index 3240860..434dd15 100644 --- a/README.md +++ b/README.md @@ -30,4 +30,17 @@ Baselines (2026-11-25, RTX 4090, 4K at scale 1, median of 10): | Time to window mapped | < 20 ms | 148 ms | 241 ms | | PSS | < 8 MB | 80 MB | 66 MB | | Threads | 1 | 7 | 20 | -| Idle wakeups/s | 0 | 3 | 348 | +| Idle wakeups/s | 0.67 (Hyprland's ping only) | 3 | 348 | + +Hyprland pings every window every 1.5 s to check that it still responds (`xdg_wm_base.ping`), so 0.67 wakeups/s is the floor for any window on Hyprland. Alias Calc wakes for nothing else while idle. + +## Trace + +`ALIAS_CALC_TRACE=1 alias-calc` prints startup timings and every wakeup to stderr: + +``` +[trace] 0.020 ms connected +[trace] 0.105 ms globals +[trace] 0.369 ms configured +[trace] 0.608 ms frame committed (320x480 px) +``` diff --git a/bench/run b/bench/run index 26c8b62..11369ea 100755 --- a/bench/run +++ b/bench/run @@ -16,6 +16,11 @@ runs=10 if [[ ${1:-} == --runs ]]; then runs=$2; fi cargo build --release --locked --quiet + +# Measure every app as the floating window it is in daily use (aliasOS +# floats GNOME Calculator already). The rule lasts until Hyprland reloads +# its config. +hyprctl eval 'hl.window_rule({ match = { class = [[^(com\.aliasproject\.calc|omacalc|org\.gnome\.Calculator)$]] }, float = true })' >/dev/null results=() bench() { diff --git a/src/main.rs b/src/main.rs index 521ff7f..fb9b629 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,3 +1,36 @@ //! Alias Calc: a tiny, instant calculator for aliasOS. +//! +//! One thread, no toolkit, no GPU: a plain Wayland client that draws on the +//! CPU into a shared-memory buffer and sleeps until something happens. -fn main() {} +mod trace; +mod window; + +use std::process::ExitCode; + +fn main() -> ExitCode { + trace::start(); + match std::env::args().nth(1).as_deref() { + Some("--version" | "-V") => { + println!("alias-calc {}", env!("CARGO_PKG_VERSION")); + return ExitCode::SUCCESS; + } + Some("--help" | "-h") => { + println!("Usage: alias-calc\n\nSet ALIAS_CALC_TRACE=1 to print startup timings."); + return ExitCode::SUCCESS; + } + Some(other) => { + eprintln!("alias-calc: unknown argument {other:?} (try --help)"); + return ExitCode::from(2); + } + None => {} + } + + match window::run() { + Ok(()) => ExitCode::SUCCESS, + Err(err) => { + eprintln!("alias-calc: {err}"); + ExitCode::FAILURE + } + } +} diff --git a/src/trace.rs b/src/trace.rs new file mode 100644 index 0000000..452aa7d --- /dev/null +++ b/src/trace.rs @@ -0,0 +1,24 @@ +//! Startup timings, printed to stderr when `ALIAS_CALC_TRACE` is set. +//! +//! Each mark prints the milliseconds since `main` started, so a launch shows +//! where its time goes (connect, globals, first configure, first commit). + +use std::sync::OnceLock; +use std::time::Instant; + +static START: OnceLock> = OnceLock::new(); + +/// Starts the clock. Call first thing in `main`. +pub fn start() { + START.get_or_init(|| std::env::var_os("ALIAS_CALC_TRACE").map(|_| Instant::now())); +} + +/// Prints `what` with the time since `start`, if tracing is on. +pub fn mark(what: &str) { + if let Some(Some(start)) = START.get() { + eprintln!( + "[trace] {:>7.3} ms {what}", + start.elapsed().as_secs_f64() * 1000.0 + ); + } +} diff --git a/src/window.rs b/src/window.rs new file mode 100644 index 0000000..bf2888e --- /dev/null +++ b/src/window.rs @@ -0,0 +1,400 @@ +//! The Wayland window: an xdg toplevel drawn on the CPU into a `wl_shm` +//! buffer, sharp at fractional scales through `fractional-scale-v1` and +//! `viewporter`. +//! +//! Everything runs on the one thread. The loop blocks in `poll` on the +//! Wayland socket and only wakes when the compositor sends something, so an +//! idle window costs no CPU at all. + +use std::error::Error; + +use rustix::event::{PollFd, PollFlags, poll}; +use rustix::io::Errno; +use smithay_client_toolkit::compositor::{CompositorHandler, CompositorState}; +use smithay_client_toolkit::dispatch2::Dispatch2; +use smithay_client_toolkit::output::{OutputHandler, OutputState}; +use smithay_client_toolkit::reexports::client::backend::WaylandError; +use smithay_client_toolkit::reexports::client::globals::registry_queue_init; +use smithay_client_toolkit::reexports::client::protocol::{wl_output, wl_shm, wl_surface}; +use smithay_client_toolkit::reexports::client::{Connection, QueueHandle}; +use smithay_client_toolkit::registry::{ProvidesRegistryState, RegistryState}; +use smithay_client_toolkit::shell::WaylandSurface; +use smithay_client_toolkit::shell::xdg::XdgShell; +use smithay_client_toolkit::shell::xdg::window::{ + Window, WindowConfigure, WindowDecorations, WindowHandler, +}; +use smithay_client_toolkit::shm::slot::{Buffer, SlotPool}; +use smithay_client_toolkit::shm::{Shm, ShmHandler}; +use smithay_client_toolkit::{delegate_dispatch2, delegate_registry, registry_handlers}; +use wayland_protocols::wp::fractional_scale::v1::client::{ + wp_fractional_scale_manager_v1::WpFractionalScaleManagerV1, + wp_fractional_scale_v1::{self, WpFractionalScaleV1}, +}; +use wayland_protocols::wp::viewporter::client::{ + wp_viewport::WpViewport, wp_viewporter::WpViewporter, +}; + +use crate::trace; + +/// What people see in the launcher and the title bar. "Alias Calc" is the +/// product name; the window says what it does. +const TITLE: &str = "Calculator"; +const APP_ID: &str = "com.aliasproject.calc"; + +/// Logical size when the compositor leaves it to us (a floating window). +const DEFAULT_SIZE: (u32, u32) = (320, 480); +const MIN_SIZE: (u32, u32) = (260, 380); + +/// Stand-in until the theme lands (ALI-2103). +const BACKGROUND: [u8; 4] = argb(0x1a, 0x1b, 0x26); + +/// `wl_shm` ARGB8888 is little-endian: blue, green, red, alpha in memory. +const fn argb(r: u8, g: u8, b: u8) -> [u8; 4] { + [b, g, r, 0xff] +} + +/// Fractional scales arrive as 120ths (`wp_fractional_scale_v1`). +const SCALE_DENOMINATOR: u32 = 120; + +pub fn run() -> Result<(), Box> { + let conn = Connection::connect_to_env()?; + trace::mark("connected"); + let (globals, mut queue) = registry_queue_init::(&conn)?; + let qh = queue.handle(); + trace::mark("globals"); + + let compositor = CompositorState::bind(&globals, &qh)?; + let xdg_shell = XdgShell::bind(&globals, &qh)?; + let shm = Shm::bind(&globals, &qh)?; + // Both are optional: without them the window falls back to integer + // buffer scales. + let fractional_manager: Option = + globals.bind(&qh, 1..=1, NoEvents).ok(); + let viewporter: Option = globals.bind(&qh, 1..=1, NoEvents).ok(); + + let surface = compositor.create_surface(&qh); + let scaling = match (fractional_manager, viewporter) { + (Some(manager), Some(viewporter)) => { + manager.get_fractional_scale(&surface, &qh, ScaleData); + let viewport = viewporter.get_viewport(&surface, &qh, NoEvents); + Scaling::Fractional { + viewport, + scale120: SCALE_DENOMINATOR, + } + } + _ => Scaling::Integer(1), + }; + + let window = xdg_shell.create_window(surface, WindowDecorations::RequestServer, &qh); + window.set_title(TITLE); + window.set_app_id(APP_ID); + window.set_min_size(Some(MIN_SIZE)); + // The first commit has no buffer: it asks the compositor for a + // configure, and the first draw answers it. + window.commit(); + trace::mark("window requested"); + + let (w, h) = DEFAULT_SIZE; + let pool = SlotPool::new((w * h * 4) as usize, &shm)?; + let mut app = App { + registry: RegistryState::new(&globals), + outputs: OutputState::new(&globals, &qh), + shm, + window, + pool, + buffer: None, + size: DEFAULT_SIZE, + scaling, + configured: false, + dirty: false, + exit: false, + }; + + event_loop(&mut queue, &mut app) +} + +type Queue = smithay_client_toolkit::reexports::client::EventQueue; + +/// Dispatch, draw if anything changed, then sleep until the compositor +/// writes to the socket. No timeouts: an idle window never wakes. +fn event_loop(queue: &mut Queue, app: &mut App) -> Result<(), Box> { + loop { + queue.dispatch_pending(app)?; + if app.exit { + return Ok(()); + } + if app.dirty && app.configured { + app.draw(); + } + match queue.flush() { + Ok(()) => {} + Err(WaylandError::Io(err)) if err.kind() == std::io::ErrorKind::WouldBlock => {} + Err(err) => return Err(err.into()), + } + + // Events already queued mean there's nothing to wait for. + let Some(guard) = queue.prepare_read() else { + continue; + }; + let fd = guard.connection_fd(); + let mut fds = [PollFd::new(&fd, PollFlags::IN)]; + match poll(&mut fds, None) { + Ok(_) => {} + Err(Errno::INTR) => continue, + Err(err) => return Err(err.into()), + } + match guard.read() { + Ok(n) => trace::mark(&format!("woke: {n} event(s)")), + Err(WaylandError::Io(err)) if err.kind() == std::io::ErrorKind::WouldBlock => {} + Err(err) => return Err(err.into()), + } + } +} + +enum Scaling { + /// `wp_fractional_scale_v1` + `wp_viewport`: the buffer is drawn at the + /// exact pixel size and the viewport maps it to the logical size. + Fractional { viewport: WpViewport, scale120: u32 }, + /// `wl_surface.set_buffer_scale` with the output's integer scale. + Integer(u32), +} + +struct App { + registry: RegistryState, + outputs: OutputState, + shm: Shm, + window: Window, + pool: SlotPool, + buffer: Option, + /// Logical size, in surface coordinates. + size: (u32, u32), + scaling: Scaling, + configured: bool, + /// Something changed since the last frame. + dirty: bool, + exit: bool, +} + +impl App { + /// The buffer's size in pixels for the current logical size and scale. + fn pixel_size(&self) -> (u32, u32) { + let (w, h) = self.size; + match self.scaling { + // Round to nearest, as the protocol asks. + Scaling::Fractional { scale120, .. } => ( + (w * scale120 + SCALE_DENOMINATOR / 2) / SCALE_DENOMINATOR, + (h * scale120 + SCALE_DENOMINATOR / 2) / SCALE_DENOMINATOR, + ), + Scaling::Integer(scale) => (w * scale, h * scale), + } + } + + fn draw(&mut self) { + self.dirty = false; + let (pw, ph) = self.pixel_size(); + let stride = pw as i32 * 4; + + // Reuse the one buffer when its size still fits and the compositor + // has released it; otherwise make a new one in the same pool (the + // pool reuses the freed space, so memory stays flat). + let reusable = self.buffer.as_ref().is_some_and(|b| { + b.height() == ph as i32 && b.stride() == stride && self.pool.canvas(b).is_some() + }); + if !reusable { + match self + .pool + .create_buffer(pw as i32, ph as i32, stride, wl_shm::Format::Argb8888) + { + Ok((buffer, _)) => self.buffer = Some(buffer), + Err(err) => { + eprintln!("alias-calc: can't allocate a {pw}x{ph} buffer: {err}"); + return; + } + } + } + let Some(buffer) = self.buffer.as_ref() else { + return; + }; + let Some(canvas) = self.pool.canvas(buffer) else { + return; + }; + + canvas.as_chunks_mut::<4>().0.fill(BACKGROUND); + + let surface = self.window.wl_surface(); + match &self.scaling { + Scaling::Fractional { viewport, .. } => { + viewport.set_destination(self.size.0 as i32, self.size.1 as i32); + } + Scaling::Integer(scale) => surface.set_buffer_scale(*scale as i32), + } + surface.damage_buffer(0, 0, pw as i32, ph as i32); + if let Err(err) = buffer.attach_to(surface) { + eprintln!("alias-calc: can't attach the buffer: {err}"); + return; + } + self.window.commit(); + trace::mark(&format!("frame committed ({pw}x{ph} px)")); + } +} + +impl CompositorHandler for App { + fn scale_factor_changed( + &mut self, + _: &Connection, + _: &QueueHandle, + _: &wl_surface::WlSurface, + factor: i32, + ) { + if let Scaling::Integer(scale) = &mut self.scaling { + let factor = factor.max(1) as u32; + if *scale != factor { + *scale = factor; + self.dirty = true; + } + } + } + + fn transform_changed( + &mut self, + _: &Connection, + _: &QueueHandle, + _: &wl_surface::WlSurface, + _: wl_output::Transform, + ) { + } + + fn frame(&mut self, _: &Connection, _: &QueueHandle, _: &wl_surface::WlSurface, _: u32) {} + + fn surface_enter( + &mut self, + _: &Connection, + _: &QueueHandle, + _: &wl_surface::WlSurface, + _: &wl_output::WlOutput, + ) { + } + + fn surface_leave( + &mut self, + _: &Connection, + _: &QueueHandle, + _: &wl_surface::WlSurface, + _: &wl_output::WlOutput, + ) { + } +} + +impl OutputHandler for App { + fn output_state(&mut self) -> &mut OutputState { + &mut self.outputs + } + fn new_output(&mut self, _: &Connection, _: &QueueHandle, _: wl_output::WlOutput) {} + fn update_output(&mut self, _: &Connection, _: &QueueHandle, _: wl_output::WlOutput) {} + fn output_destroyed(&mut self, _: &Connection, _: &QueueHandle, _: wl_output::WlOutput) {} +} + +impl WindowHandler for App { + fn request_close(&mut self, _: &Connection, _: &QueueHandle, _: &Window) { + self.exit = true; + } + + fn configure( + &mut self, + _: &Connection, + _: &QueueHandle, + _: &Window, + configure: WindowConfigure, + _: u32, + ) { + if !self.configured { + trace::mark("configured"); + } + let (w, h) = match configure.new_size { + (Some(w), Some(h)) => (w.get(), h.get()), + _ => self.size, + }; + self.size = (w.max(1), h.max(1)); + self.configured = true; + // Every configure needs a commit to answer it, even when the size + // is unchanged. + self.dirty = true; + } +} + +impl ShmHandler for App { + fn shm_state(&mut self) -> &mut Shm { + &mut self.shm + } +} + +impl ProvidesRegistryState for App { + fn registry(&mut self) -> &mut RegistryState { + &mut self.registry + } + registry_handlers![OutputState]; +} + +/// User data for objects that send no events we use. +struct NoEvents; + +impl Dispatch2 for NoEvents { + fn event( + &self, + _: &mut App, + _: &WpFractionalScaleManagerV1, + _: ::Event, + _: &Connection, + _: &QueueHandle, + ) { + } +} + +impl Dispatch2 for NoEvents { + fn event( + &self, + _: &mut App, + _: &WpViewporter, + _: ::Event, + _: &Connection, + _: &QueueHandle, + ) { + } +} + +impl Dispatch2 for NoEvents { + fn event( + &self, + _: &mut App, + _: &WpViewport, + _: ::Event, + _: &Connection, + _: &QueueHandle, + ) { + } +} + +/// User data for the surface's `wp_fractional_scale_v1`. +struct ScaleData; + +impl Dispatch2 for ScaleData { + fn event( + &self, + app: &mut App, + _: &WpFractionalScaleV1, + event: wp_fractional_scale_v1::Event, + _: &Connection, + _: &QueueHandle, + ) { + if let wp_fractional_scale_v1::Event::PreferredScale { scale } = event + && let Scaling::Fractional { scale120, .. } = &mut app.scaling + && *scale120 != scale + { + *scale120 = scale.max(1); + app.dirty = true; + } + } +} + +delegate_registry!(App); +delegate_dispatch2!(App); From b9889b75ad02a580fd559130cefe388bbfce0e73 Mon Sep 17 00:00:00 2001 From: Michael Aguiar Date: Wed, 25 Nov 2026 12:04:48 -0700 Subject: [PATCH 03/50] Add the calculator engine with exact decimal math Keys in, expression and display text out, with no UI. It follows omacalc's rules (precedence with ^ first and right to left, desk-calculator percent, chaining from the exact result, sign, backspace, paste, thousands separators), but numbers are exact decimals (rust_decimal), so 0.1 + 0.2 is 0.3 and 16-digit integers show exactly. Values past a decimal's range (about 7.9e28, or below 1e-28) fall back to f64, so 10 ^ 308 still works. Nothing calls it until the keypad lands (ALI-2101). ALI-2100 --- Cargo.lock | 465 +++++++++++++++++++++ Cargo.toml | 1 + src/engine.rs | 1086 +++++++++++++++++++++++++++++++++++++++++++++++++ src/main.rs | 4 + 4 files changed, 1556 insertions(+) create mode 100644 src/engine.rs diff --git a/Cargo.lock b/Cargo.lock index 6654869..3dd56a4 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5,3 +5,468 @@ version = 4 [[package]] name = "alias-calc" version = "0.1.0" +dependencies = [ + "rust_decimal", +] + +[[package]] +name = "arrayvec" +version = "0.7.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3fb67a6e08acf24fdeccbac2cb6ac4305825bd1f117462e0e6f2f193345ad56" + +[[package]] +name = "autocfg" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" + +[[package]] +name = "borsh" +version = "1.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "553c5d846a6ba5150c65e3b1b8ec073bcf1abc20f9b7220de384a4443ea4e20a" +dependencies = [ + "borsh-derive", + "bytes", + "cfg_aliases", +] + +[[package]] +name = "borsh-derive" +version = "1.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12cdfe656708a01f89b451a7d36466e6fe6c414de0aa18fc54f864f6f9ca9f56" +dependencies = [ + "once_cell", + "proc-macro-crate", + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "bumpalo" +version = "3.20.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "87a0cf66fd1eb2fb7b822cb78370d82303750809bc6ba855f3f58e517d3238db" + +[[package]] +name = "bytes" +version = "1.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "776dfebd015e2d8732c684a2c71003674ccb49457b539b9e82151ba38e96dd7c" + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "cfg_aliases" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527" + +[[package]] +name = "equivalent" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" + +[[package]] +name = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "libc", + "wasi", +] + +[[package]] +name = "getrandom" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd" +dependencies = [ + "cfg-if", + "libc", + "r-efi", + "wasip2", +] + +[[package]] +name = "hashbrown" +version = "0.17.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "735eaa21a6a5ffb2e84362faaeb90c05ba8e19797ca30428478cb6ea3a4921bc" + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown", +] + +[[package]] +name = "itoa" +version = "1.0.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" + +[[package]] +name = "libc" +version = "0.2.191" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "ppv-lite86" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9" +dependencies = [ + "zerocopy", +] + +[[package]] +name = "proc-macro-crate" +version = "3.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e67ba7e9b2b56446f1d419b1d807906278ffa1a658a8a5d8a39dcb1f5a78614f" +dependencies = [ + "toml_edit", +] + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "r-efi" +version = "5.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f" + +[[package]] +name = "rand" +version = "0.8.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e058c7de0b26af77780c769414d6257830bb240f3c38477dbc2c16e5f54d6d4c" +dependencies = [ + "libc", + "rand_chacha 0.3.1", + "rand_core 0.6.4", +] + +[[package]] +name = "rand" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9ef1d0d795eb7d84685bca4f72f3649f064e6641543d3a8c415898726a57b41" +dependencies = [ + "rand_chacha 0.9.0", + "rand_core 0.9.5", +] + +[[package]] +name = "rand_chacha" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88" +dependencies = [ + "ppv-lite86", + "rand_core 0.6.4", +] + +[[package]] +name = "rand_chacha" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb" +dependencies = [ + "ppv-lite86", + "rand_core 0.9.5", +] + +[[package]] +name = "rand_core" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" +dependencies = [ + "getrandom 0.2.17", +] + +[[package]] +name = "rand_core" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c" +dependencies = [ + "getrandom 0.3.4", +] + +[[package]] +name = "rust_decimal" +version = "1.43.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7653272e75dcac41dc199fbea6f5797633994fafd339943c06c9af16bf29cd3a" +dependencies = [ + "arrayvec", + "borsh", + "bytes", + "num-traits", + "rand 0.8.8", + "rand 0.9.5", + "serde", + "serde_json", + "wasm-bindgen", +] + +[[package]] +name = "rustversion" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "serde_json" +version = "1.0.154" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "toml_datetime" +version = "1.1.3+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "173f25c883cd2176a2d8212155638c0a60d484a9d84546d270866f40f56b6e49" +dependencies = [ + "serde_core", +] + +[[package]] +name = "toml_edit" +version = "0.25.21+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "88497dab46de5bf343ec66b05c251e48c6213f3e9170c70a70a823f7abe886a4" +dependencies = [ + "indexmap", + "toml_datetime", + "toml_parser", + "winnow", +] + +[[package]] +name = "toml_parser" +version = "1.1.7+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bb28d6e049a9766c3bd91a8326e6179f5b132dec87906bb97018ef7a2f3431a" +dependencies = [ + "winnow", +] + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + +[[package]] +name = "wasip2" +version = "1.0.4+wasi-0.2.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b67efb37e106e55ce722a510d6b5f9c17f083e5fc79afc2badeb12cc313d9487" +dependencies = [ + "wit-bindgen", +] + +[[package]] +name = "wasm-bindgen" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a0181c14ddd6c7b8b0b0132a5f1ea2f32be0d893cd3ea97b6e3b28886b8a3d1c" +dependencies = [ + "cfg-if", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e931a02a39abdbf66966fc35902b5ed58344750a70885bed4ebb3d8eaf28ed9" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ca4b54280e455bd831e33a6b8e734baf432fe63fbc35c42ac14ce67a043a53a" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn 3.0.10", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b1f9c3798725016c6ee5f2f57869ec0831e8bbc0ab0310a86e787e97f41389e" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "winnow" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8c3b93199df0ab874cdf0c6a94f0a0dc3423fe41f1cafb62b8bd7b1deb277aef" +dependencies = [ + "memchr", +] + +[[package]] +name = "wit-bindgen" +version = "0.57.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" + +[[package]] +name = "zerocopy" +version = "0.8.64" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed43f3060383c64b000f3c630550aebdfa9d3b76d48de32390483dd2cc7e0865" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.64" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a5cbd820fe3e35fb38c83b6dc7e6b1618bc46e0cd10073ae94e8d52dc468d8b9" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/Cargo.toml b/Cargo.toml index 9b1e478..e83062f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -7,6 +7,7 @@ description = "A tiny, instant calculator for aliasOS" publish = false [dependencies] +rust_decimal = { version = "1.43", default-features = false, features = ["std", "maths"] } [profile.release] lto = "fat" diff --git a/src/engine.rs b/src/engine.rs new file mode 100644 index 0000000..f623c91 --- /dev/null +++ b/src/engine.rs @@ -0,0 +1,1086 @@ +//! The calculator itself: keys in, expression and display text out. No UI. +//! +//! It behaves like omacalc (the keypad, precedence, percent and chaining +//! rules), with one big difference: numbers are exact decimals +//! (`rust_decimal`), so `0.1 + 0.2` is exactly `0.3` and money stays exact. +//! A decimal holds 28–29 significant digits up to about 7.9 × 10²⁸; past +//! that, or below 10⁻²⁸, a value falls back to `f64` so very large and very +//! small numbers still work (shown to 15 significant digits, as omacalc does). +//! +//! The display rounds exact values to 16 significant digits, so every +//! integer up to 9,999,999,999,999,999 shows exactly. Like C's `%g`, a value +//! switches to exponent form (`1.5e+20`, `1e-05`) when its exponent is below +//! −4 or at least the precision (16 for exact values, 15 for `f64`). + +use std::fmt::Write as _; +use std::str::FromStr; + +use rust_decimal::{Decimal, MathematicalOps}; + +/// Significant digits shown for an exact value, and the most that can be typed. +const EXACT_DIGITS: u32 = 16; +/// Significant digits shown for an `f64` value: what a double holds reliably. +const FLOAT_DIGITS: u32 = 15; + +/// What the display says when a calculation has no answer. +pub const ERROR_TEXT: &str = "Error"; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Op { + Add, + Sub, + Mul, + Div, + Pow, +} + +impl Op { + /// The sign shown in the expression line. + pub fn symbol(self) -> &'static str { + match self { + Op::Add => "+", + Op::Sub => "−", + Op::Mul => "×", + Op::Div => "÷", + Op::Pow => "^", + } + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Key { + /// 0–9; anything larger is ignored. + Digit(u8), + Point, + Op(Op), + Equals, + Percent, + Sign, + Backspace, + Clear, +} + +/// A number: exact when it fits a decimal, `f64` when it doesn't. +#[derive(Clone, Copy, Debug, PartialEq)] +enum Num { + Exact(Decimal), + Float(f64), +} + +/// A calculation with no answer: division by zero, overflow past `f64`, or a +/// negative number raised to a fractional power. +#[derive(Debug, PartialEq)] +struct NoAnswer; + +type Answer = Result; + +impl Num { + const ZERO: Num = Num::Exact(Decimal::ZERO); + + fn to_f64(self) -> f64 { + match self { + Num::Exact(d) => f64::from_str(&d.to_string()).unwrap_or(f64::NAN), + Num::Float(f) => f, + } + } + + fn is_zero(self) -> bool { + match self { + Num::Exact(d) => d.is_zero(), + Num::Float(f) => f == 0.0, + } + } + + /// An `f64` result, made exact again when its 15 significant digits fit + /// a decimal, so later steps stay exact (`4 ^ 0.5` is exactly 2). + fn from_f64(value: f64) -> Answer { + if !value.is_finite() { + return Err(NoAnswer); + } + if value == 0.0 { + return Ok(Num::ZERO); + } + let text = format!("{:.*e}", FLOAT_DIGITS as usize - 1, value); + match Decimal::from_scientific(&text) { + // A value below a decimal's 28 places would round away: keep it + // as a float. + Ok(d) if !d.is_zero() && d.normalize().scale() < 28 => Ok(Num::Exact(d.normalize())), + _ => Ok(Num::Float(value)), + } + } + + /// Applies an exact operation, falling back to `f64` when the decimal + /// overflows or underflows to zero. + fn combine( + self, + other: Num, + exact: impl Fn(Decimal, Decimal) -> Option, + float: impl Fn(f64, f64) -> f64, + may_underflow: bool, + ) -> Answer { + if let (Num::Exact(a), Num::Exact(b)) = (self, other) + && let Some(result) = exact(a, b) + && !(may_underflow && result.is_zero() && !a.is_zero()) + { + return Ok(Num::Exact(result.normalize())); + } + Num::from_f64(float(self.to_f64(), other.to_f64())) + } + + fn apply(self, op: Op, other: Num) -> Answer { + match op { + Op::Add => self.combine(other, Decimal::checked_add, |a, b| a + b, false), + Op::Sub => self.combine(other, Decimal::checked_sub, |a, b| a - b, false), + Op::Mul => self.combine(other, Decimal::checked_mul, |a, b| a * b, true), + Op::Div => { + if other.is_zero() { + return Err(NoAnswer); + } + self.combine(other, Decimal::checked_div, |a, b| a / b, true) + } + Op::Pow => self.pow(other), + } + } + + fn pow(self, exponent: Num) -> Answer { + let whole = match exponent { + Num::Exact(e) => e.is_integer(), + Num::Float(e) => e.fract() == 0.0, + }; + let negative = match self { + Num::Exact(d) => d.is_sign_negative() && !d.is_zero(), + Num::Float(f) => f < 0.0, + }; + if negative && !whole { + return Err(NoAnswer); + } + if self.is_zero() && exponent.to_f64() < 0.0 { + return Err(NoAnswer); + } + if let (Num::Exact(base), Num::Exact(e)) = (self, exponent) + && whole + && let Ok(e) = i64::try_from(e.mantissa() / 10i128.pow(e.scale())) + && let Some(result) = base.checked_powi(e) + && (!result.is_zero() || base.is_zero()) + { + return Ok(Num::Exact(result.normalize())); + } + Num::from_f64(self.to_f64().powf(exponent.to_f64())) + } + + /// The display text, without thousands separators. + fn format(self) -> String { + match self { + Num::Exact(d) => format_exact(d), + Num::Float(f) => format_float(f), + } + } +} + +/// Rounds to 16 significant digits and lays the digits out. +fn format_exact(value: Decimal) -> String { + if value.is_zero() { + return "0".into(); + } + let rounded = value.round_sf(EXACT_DIGITS).unwrap_or(value).normalize(); + let mantissa = rounded.mantissa(); + let digits = mantissa.unsigned_abs().to_string(); + // value = digits × 10^(−scale), so the first digit's power of ten is: + let exponent = digits.len() as i32 - 1 - rounded.scale() as i32; + layout(mantissa < 0, &digits, exponent, EXACT_DIGITS) +} + +fn format_float(value: f64) -> String { + if value == 0.0 { + return "0".into(); + } + // `{:e}` with 14 places rounds to 15 significant digits. + let text = format!("{:.*e}", FLOAT_DIGITS as usize - 1, value); + let (mantissa, exponent) = text.split_once('e').unwrap_or((&text, "0")); + let exponent: i32 = exponent.parse().unwrap_or(0); + let negative = mantissa.starts_with('-'); + let digits: String = mantissa.chars().filter(char::is_ascii_digit).collect(); + layout(negative, &digits, exponent, FLOAT_DIGITS) +} + +/// Lays out significant `digits` whose first digit is worth 10^`exponent`, +/// `%g`-style: plain unless the exponent is below −4 or at least `precision`. +fn layout(negative: bool, digits: &str, exponent: i32, precision: u32) -> String { + let digits = digits.trim_end_matches('0'); + let digits = if digits.is_empty() { "0" } else { digits }; + let mut out = String::with_capacity(digits.len() + 8); + if negative { + out.push('-'); + } + if exponent < -4 || exponent >= precision as i32 { + out.push_str(&digits[..1]); + if digits.len() > 1 { + out.push('.'); + out.push_str(&digits[1..]); + } + let sign = if exponent < 0 { '-' } else { '+' }; + let _ = write!(out, "e{sign}{:02}", exponent.unsigned_abs()); + } else if exponent >= 0 { + let whole = exponent as usize + 1; + if digits.len() <= whole { + out.push_str(digits); + out.extend(std::iter::repeat_n('0', whole - digits.len())); + } else { + out.push_str(&digits[..whole]); + out.push('.'); + out.push_str(&digits[whole..]); + } + } else { + out.push_str("0."); + out.extend(std::iter::repeat_n('0', (-exponent - 1) as usize)); + out.push_str(digits); + } + out +} + +/// Separates the whole-number digits into groups of three with commas: +/// `1234567.891` reads `1,234,567.891`. The fraction and any exponent stay +/// as they are, and text that isn't a number (like "Error") passes through. +pub fn group_digits(number: &str) -> String { + let start = usize::from(number.starts_with('-')); + let end = start + + number[start..] + .bytes() + .take_while(u8::is_ascii_digit) + .count(); + let count = end - start; + if count <= 3 { + return number.to_owned(); + } + let mut out = String::with_capacity(number.len() + count / 3); + out.push_str(&number[..start]); + for (i, digit) in number[start..end].chars().enumerate() { + if i > 0 && (count - i) % 3 == 0 { + out.push(','); + } + out.push(digit); + } + out.push_str(&number[end..]); + out +} + +/// Parses a plain number (`-12.5`, `.5`, `1e-05`, `1.5e+20`). Nothing else: +/// no separators, spaces, signs other than a leading `-`, or `inf`/`nan`. +fn parse_number(text: &str) -> Option { + let body = text.strip_prefix('-').unwrap_or(text); + let (mantissa, exponent) = match body.split_once(['e', 'E']) { + Some((m, e)) => (m, Some(e)), + None => (body, None), + }; + let (whole, fraction) = mantissa.split_once('.').unwrap_or((mantissa, "")); + let digits_ok = |s: &str| s.bytes().all(|b| b.is_ascii_digit()); + if whole.is_empty() && fraction.is_empty() + || !digits_ok(whole) + || !digits_ok(fraction) + || mantissa.matches('.').count() > 1 + { + return None; + } + if let Some(e) = exponent { + let e = e.strip_prefix(['+', '-']).unwrap_or(e); + if e.is_empty() || !digits_ok(e) { + return None; + } + } + + let exact = if exponent.is_some() { + Decimal::from_scientific(text).ok() + } else { + Decimal::from_str(text).ok() + }; + match exact { + Some(d) if !(d.is_zero() && text.bytes().any(|b| (b'1'..=b'9').contains(&b))) => { + Some(Num::Exact(d)) + } + _ => Num::from_f64(f64::from_str(text).ok()?).ok(), + } +} + +#[derive(Clone, Copy, Debug, PartialEq)] +enum Token { + Num(Num), + Op(Op), +} + +/// The calculator's state. Feed it keys with [`Calc::press`] and read +/// [`Calc::expression`] and [`Calc::display`] back. +#[derive(Debug, Default)] +pub struct Calc { + /// Numbers and operators entered so far, always starting with a number. + tokens: Vec, + /// The number being typed, as typed ("5.", "-0", "1.50"), or a whole + /// value in exponent form from a percent or paste. + entry: String, + /// After `=`: the exact result, its display text, and the expression. + result: Option<(Num, String)>, + evaluated: String, + errored: bool, +} + +impl Calc { + pub fn new() -> Self { + Self::default() + } + + pub fn press(&mut self, key: Key) { + match key { + Key::Digit(d) if d <= 9 => self.press_digit(char::from(b'0' + d)), + Key::Digit(_) => {} + Key::Point => self.press_point(), + Key::Op(op) => self.press_op(op), + Key::Equals => self.press_equals(), + Key::Percent => self.press_percent(), + Key::Sign => self.press_sign(), + Key::Backspace => self.press_backspace(), + Key::Clear => self.clear(), + } + } + + /// The line above the display: what's been entered, or after `=`, the + /// calculation that gave the result. Empty at the start. + pub fn expression(&self) -> String { + if self.errored || self.result.is_some() { + return self.evaluated.clone(); + } + pretty(&self.tokens) + } + + /// The big number, with thousands separators. + pub fn display(&self) -> String { + group_digits(&self.copy_text()) + } + + /// The display without separators: what copy puts on the clipboard, as + /// a spreadsheet or terminal reads `1234567` more reliably than `1,234,567`. + pub fn copy_text(&self) -> String { + if self.errored { + return ERROR_TEXT.into(); + } + if !self.entry.is_empty() { + return self.entry.clone(); + } + if let Some((_, text)) = &self.result { + return text.clone(); + } + self.current_value().format() + } + + /// Whether the display shows an error. + pub fn is_error(&self) -> bool { + self.errored + } + + /// Replaces the number being typed with a pasted one. Accepts spaces + /// around it, thousands separators in groups of three (`1,234,567.89`), + /// a decimal comma (`1,5`) and the `−` this calculator shows. Anything + /// else is ignored, and the return value says whether it was taken. + pub fn paste(&mut self, text: &str) -> bool { + let mut text: String = text + .trim() + .replace('−', "-") + .chars() + .filter(|c| *c != ' ') + .collect(); + if is_grouped(&text) { + text.retain(|c| c != ','); + } + let value = parse_number(&text).or_else(|| parse_number(&text.replace(',', "."))); + let Some(value) = value else { return false }; + + if self.errored || self.result.is_some() { + self.clear(); + } + self.entry = value.format(); + true + } + + fn press_digit(&mut self, digit: char) { + if self.errored || self.result.is_some() { + // A digit after `=` starts a new calculation. + self.clear(); + } + if in_exponent_form(&self.entry) { + self.entry.clear(); + } + match self.entry.as_str() { + "0" => { + self.entry.clear(); + self.entry.push(digit); + } + "-0" => { + self.entry.truncate(1); + self.entry.push(digit); + } + _ if significant_digits(&self.entry) < EXACT_DIGITS as usize => { + self.entry.push(digit); + } + // Past 16 significant digits the display would round what was typed. + _ => {} + } + } + + fn press_point(&mut self) { + if self.errored || self.result.is_some() { + self.clear(); + } + if in_exponent_form(&self.entry) { + self.entry.clear(); + } + if self.entry.is_empty() { + self.entry.push_str("0."); + } else if !self.entry.contains('.') { + self.entry.push('.'); + } + } + + fn press_op(&mut self, op: Op) { + if self.errored { + return; + } + if let Some((value, _)) = self.result.take() { + // Chain from the exact result, not its rounded display, so + // 1 ÷ 3 = × 3 comes back as exactly 1. + self.tokens.clear(); + self.tokens.push(Token::Num(value)); + self.evaluated.clear(); + } + if !self.entry.is_empty() { + let value = seal(&self.entry); + self.entry.clear(); + self.tokens.push(Token::Num(value)); + self.tokens.push(Token::Op(op)); + } else if self.tokens.is_empty() { + self.tokens.push(Token::Num(Num::ZERO)); + self.tokens.push(Token::Op(op)); + } else if let Some(Token::Op(last)) = self.tokens.last_mut() { + // A second operator in a row replaces the first: 4 + × 2 is 4 × 2. + *last = op; + } else { + self.tokens.push(Token::Op(op)); + } + } + + fn press_equals(&mut self) { + if self.errored || self.result.is_some() { + return; + } + let mut tokens = std::mem::take(&mut self.tokens); + if !self.entry.is_empty() { + tokens.push(Token::Num(seal(&self.entry))); + self.entry.clear(); + } + // A trailing operator is dropped: 9 + = is 9. + while let Some(Token::Op(_)) = tokens.last() { + tokens.pop(); + } + if tokens.is_empty() { + return; + } + self.evaluated = pretty(&tokens); + match evaluate(&tokens) { + Ok(value) => self.result = Some((value, value.format())), + Err(NoAnswer) => self.errored = true, + } + } + + /// With a pending + or −, x % is x percent of the running total, so + /// 200 + 10 % = 220. Otherwise (after ×, ÷ or ^, or on its own) it's x ÷ 100. + fn press_percent(&mut self) { + if self.errored { + return; + } + if let Some((value, _)) = self.result.take() { + self.evaluated.clear(); + match value.apply(Op::Div, Num::Exact(Decimal::ONE_HUNDRED)) { + Ok(percent) => self.entry = percent.format(), + Err(NoAnswer) => self.errored = true, + } + return; + } + + let value = self.current_value(); + let hundred = Num::Exact(Decimal::ONE_HUNDRED); + let percent = match self.tokens.last() { + Some(Token::Op(Op::Add | Op::Sub)) => { + let total = &self.tokens[..self.tokens.len() - 1]; + evaluate(total).and_then(|base| { + // Multiplying first keeps a tiny percentage exact; dividing + // first keeps 1e308 + 100 % from overflowing on the way. + base.apply(Op::Mul, value) + .and_then(|p| p.apply(Op::Div, hundred)) + .or_else(|_| base.apply(Op::Mul, value.apply(Op::Div, hundred)?)) + }) + } + _ => value.apply(Op::Div, hundred), + }; + match percent { + Ok(percent) => self.entry = percent.format(), + Err(NoAnswer) => { + let mut shown = self.tokens.clone(); + shown.push(Token::Num(value)); + self.evaluated = format!("{} %", pretty(&shown)); + self.errored = true; + self.tokens.clear(); + self.entry.clear(); + } + } + } + + fn press_sign(&mut self) { + if self.errored { + return; + } + if self.result.is_some() { + self.edit_result(); + } + // With nothing typed, start a fresh negative number: 4 + ± 2 is 4 + -2. + if self.entry.is_empty() { + self.entry.push_str("-0"); + } else if self.entry.starts_with('-') { + self.entry.remove(0); + } else { + self.entry.insert(0, '-'); + } + } + + fn press_backspace(&mut self) { + if self.errored { + self.clear(); + return; + } + if self.result.is_some() { + self.edit_result(); + } + if in_exponent_form(&self.entry) { + // Backspace on 1e+15 would leave 1e+1, which is 10: clear it. + self.entry.clear(); + self.entry.push('0'); + return; + } + self.entry.pop(); + if self.entry == "-" { + self.entry.clear(); + } + } + + fn clear(&mut self) { + self.tokens.clear(); + self.entry.clear(); + self.result = None; + self.evaluated.clear(); + self.errored = false; + } + + /// Editing after `=` starts from the result's digits, with the old + /// expression cleared. + fn edit_result(&mut self) { + if let Some((_, text)) = self.result.take() { + self.entry = text; + } + self.tokens.clear(); + self.evaluated.clear(); + } + + /// The number the calculator is at: the one being typed, else the last + /// one entered, else zero. + fn current_value(&self) -> Num { + if !self.entry.is_empty() { + return seal(&self.entry); + } + self.tokens + .iter() + .rev() + .find_map(|t| match t { + Token::Num(n) => Some(*n), + Token::Op(_) => None, + }) + .unwrap_or(Num::ZERO) + } +} + +/// Turns a half-typed entry ("5.", "-", "-0") into a number. +fn seal(entry: &str) -> Num { + let entry = entry.strip_suffix('.').unwrap_or(entry); + if entry.is_empty() || entry == "-" { + return Num::ZERO; + } + parse_number(entry).unwrap_or(Num::ZERO) +} + +fn in_exponent_form(entry: &str) -> bool { + entry.contains('e') +} + +/// Significant digits typed so far; the zero in a leading "0." doesn't count. +fn significant_digits(entry: &str) -> usize { + let digits = entry.bytes().filter(u8::is_ascii_digit).count(); + let leading_zero = entry.starts_with("0.") || entry.starts_with("-0."); + digits - usize::from(leading_zero) +} + +/// `1,234` or `-1,234,567.89`: commas exactly every three digits. +fn is_grouped(text: &str) -> bool { + let body = text.strip_prefix('-').unwrap_or(text); + let whole = body.split_once('.').map_or(body, |(w, _)| w); + let fraction_ok = body + .split_once('.') + .is_none_or(|(_, f)| f.bytes().all(|b| b.is_ascii_digit())); + let mut groups = whole.split(','); + let Some(first) = groups.next() else { + return false; + }; + let first_ok = (1..=3).contains(&first.len()) && first.bytes().all(|b| b.is_ascii_digit()); + let mut rest = groups.peekable(); + let has_rest = rest.peek().is_some(); + first_ok + && has_rest + && fraction_ok + && rest.all(|g| g.len() == 3 && g.bytes().all(|b| b.is_ascii_digit())) +} + +/// The expression line: every number at display precision, grouped. +fn pretty(tokens: &[Token]) -> String { + let mut out = String::new(); + for token in tokens { + if !out.is_empty() { + out.push(' '); + } + match token { + Token::Num(n) => out.push_str(&group_digits(&n.format())), + Token::Op(op) => out.push_str(op.symbol()), + } + } + out +} + +/// Evaluates number, operator, number, …: `^` first and right to left +/// (2 ^ 3 ^ 2 is 2 ^ 9), then × and ÷, then + and −, each left to right. +fn evaluate(tokens: &[Token]) -> Answer { + let mut values = Vec::with_capacity(tokens.len() / 2 + 1); + let mut ops = Vec::with_capacity(tokens.len() / 2); + for (i, token) in tokens.iter().enumerate() { + match (i % 2, token) { + (0, Token::Num(n)) => values.push(*n), + (1, Token::Op(op)) => ops.push(*op), + _ => return Err(NoAnswer), + } + } + if values.len() != ops.len() + 1 { + return Err(NoAnswer); + } + + for i in (0..ops.len()).rev() { + if ops[i] == Op::Pow { + values[i] = values[i].pow(values[i + 1])?; + values.remove(i + 1); + ops.remove(i); + } + } + + let mut terms = vec![values[0]]; + let mut signs = Vec::new(); + for (op, value) in ops.iter().zip(&values[1..]) { + match op { + Op::Mul | Op::Div => { + let last = terms.last_mut().ok_or(NoAnswer)?; + *last = last.apply(*op, *value)?; + } + _ => { + signs.push(*op); + terms.push(*value); + } + } + } + let mut total = terms[0]; + for (op, term) in signs.iter().zip(&terms[1..]) { + total = total.apply(*op, *term)?; + } + Ok(total) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Presses space-separated keys, the way omacalc's tests do. + fn press(calc: &mut Calc, keys: &str) { + for key in keys.split_whitespace() { + let key = match key { + "+" => Key::Op(Op::Add), + "-" | "−" => Key::Op(Op::Sub), + "×" | "*" => Key::Op(Op::Mul), + "÷" | "/" => Key::Op(Op::Div), + "^" => Key::Op(Op::Pow), + "=" => Key::Equals, + "%" => Key::Percent, + "." => Key::Point, + "sign" => Key::Sign, + "backspace" => Key::Backspace, + "clear" => Key::Clear, + d if d.len() == 1 && d.as_bytes()[0].is_ascii_digit() => { + Key::Digit(d.as_bytes()[0] - b'0') + } + other => panic!("unknown key {other}"), + }; + calc.press(key); + } + } + + fn shows(keys: &str) -> String { + let mut calc = Calc::new(); + press(&mut calc, keys); + calc.display() + } + + #[test] + fn starts_at_zero() { + let calc = Calc::new(); + assert_eq!(calc.display(), "0"); + assert_eq!(calc.expression(), ""); + } + + #[test] + fn readme_examples() { + let mut calc = Calc::new(); + press(&mut calc, "4 2 × 3 + 7 ="); + assert_eq!(calc.display(), "133"); + assert_eq!(calc.expression(), "42 × 3 + 7"); + assert_eq!(shows("2 × 3 ^ 2 ="), "18"); + assert_eq!(shows("2 0 0 + 1 0 % ="), "220"); + assert_eq!(shows("1 2 3 4 5 6 7 . 8 9"), "1,234,567.89"); + } + + #[test] + fn exact_decimals() { + assert_eq!(shows("0 . 1 + 0 . 2 ="), "0.3"); + assert_eq!(shows(". 1 × 3 ="), "0.3"); + assert_eq!(shows("1 . 1 × 1 . 1 ="), "1.21"); + assert_eq!(shows("1 ÷ 3 ="), "0.3333333333333333"); + assert_eq!(shows("2 ÷ 3 ="), "0.6666666666666667"); + // 16 digits exactly, where omacalc's doubles show 9.89999999999999e+15. + assert_eq!( + shows("9 9 9 9 9 9 9 9 9 9 9 9 9 9 × 9 9 ="), + "9,899,999,999,999,901" + ); + assert_eq!(shows("1 0 . 0 5 - 1 0 ="), "0.05"); + } + + #[test] + fn powers() { + assert_eq!(shows("2 ^ 2 ="), "4"); + assert_eq!(shows("2 × 3 ^ 2 ="), "18"); + assert_eq!(shows("2 ^ 3 × 2 ="), "16"); + assert_eq!(shows("2 ^ 3 ^ 2 ="), "512"); + assert_eq!(shows("2 ^ 0 ="), "1"); + assert_eq!(shows("2 ^ 3 = ^ 2 ="), "64"); + assert_eq!(shows("2 sign ^ 3 ="), "-8"); + assert_eq!(shows("0 ^ 0 ="), "1"); + assert_eq!(shows("0 ^ 1 sign ="), "Error"); + assert_eq!(shows("2 sign ^ 0 . 5 ="), "Error"); + assert_eq!(shows("2 ^ 1 sign ="), "0.5"); + assert_eq!(shows("4 ^ 0 . 5 ="), "2"); + assert_eq!(shows("2 ^ 0 . 1 ="), "1.07177346253629"); + // Past a decimal's range, powers fall back to f64. + assert_eq!(shows("2 ^ 1 0 0 ="), "1.26765060022823e+30"); + assert_eq!(shows("1 0 ^ 3 0 8 ="), "1e+308"); + assert_eq!(shows("1 0 ^ 3 0 9 ="), "Error"); + assert_eq!(shows(". 1 ^ 4 0 ="), "1e-40"); + } + + #[test] + fn error_then_digit_starts_fresh() { + let mut calc = Calc::new(); + press(&mut calc, "2 sign ^ 0 . 5 ="); + assert!(calc.is_error()); + press(&mut calc, "5"); + assert_eq!(calc.display(), "5"); + assert!(!calc.is_error()); + } + + #[test] + fn precedence() { + assert_eq!(shows("2 + 3 × 4 ="), "14"); + assert_eq!(shows("1 0 - 4 ÷ 2 ="), "8"); + assert_eq!(shows("1 0 - 2 - 3 ="), "5"); + assert_eq!(shows("1 2 ÷ 2 ÷ 3 ="), "2"); + } + + #[test] + fn shows_entry_while_typing() { + let mut calc = Calc::new(); + press(&mut calc, "4 2 ×"); + assert_eq!(calc.display(), "42"); + assert_eq!(calc.expression(), "42 ×"); + press(&mut calc, "3"); + assert_eq!(calc.display(), "3"); + } + + #[test] + fn decimals() { + assert_eq!(shows(". 5 + . 2 5 ="), "0.75"); + assert_eq!(shows("1 . 5 . 5"), "1.55"); + // What was typed stays as typed until it's used. + assert_eq!(shows("1 . 5 0"), "1.50"); + assert_eq!(shows("5 ."), "5."); + assert_eq!(shows("5 . + 1 ="), "6"); + } + + #[test] + fn division_by_zero() { + let mut calc = Calc::new(); + press(&mut calc, "1 ÷ 0 ="); + assert_eq!(calc.display(), "Error"); + assert_eq!(calc.copy_text(), "Error"); + assert_eq!(calc.expression(), "1 ÷ 0"); + press(&mut calc, "5"); + assert_eq!(calc.display(), "5"); + } + + #[test] + fn keys_after_error() { + let mut calc = Calc::new(); + press(&mut calc, "1 ÷ 0 = + sign %"); + assert_eq!(calc.display(), "Error"); + press(&mut calc, "backspace"); + assert_eq!(calc.display(), "0"); + press(&mut calc, "1 ÷ 0 = ."); + assert_eq!(calc.display(), "0."); + } + + #[test] + fn percent() { + assert_eq!(shows("2 0 0 + 1 0 % ="), "220"); + assert_eq!(shows("2 0 0 - 1 0 % ="), "180"); + assert_eq!(shows("2 0 0 × 1 0 % ="), "20"); + assert_eq!(shows("2 0 0 ÷ 1 0 % ="), "2,000"); + assert_eq!(shows("2 ^ 1 0 % ="), "1.07177346253629"); + assert_eq!(shows("5 0 %"), "0.5"); + assert_eq!(shows("4 0 + 1 0 = %"), "0.5"); + // The running total includes everything before the + or −. + assert_eq!(shows("1 0 0 + 1 0 0 + 1 0 % ="), "220"); + assert_eq!(shows("1 0 × 1 0 + 5 % ="), "105"); + } + + #[test] + fn percent_of_a_huge_total() { + assert_eq!(shows("1 0 ^ 3 0 8 = - 1 0 0 % ="), "0"); + let mut calc = Calc::new(); + press(&mut calc, "1 0 ^ 3 0 8 = + 1 0 0 0 %"); + assert_eq!(calc.display(), "Error"); + assert_eq!(calc.expression(), "1e+308 + 1,000 %"); + } + + #[test] + fn sign() { + let mut calc = Calc::new(); + press(&mut calc, "8 sign"); + assert_eq!(calc.display(), "-8"); + press(&mut calc, "sign"); + assert_eq!(calc.display(), "8"); + assert_eq!(shows("4 + 8 sign ="), "-4"); + } + + #[test] + fn sign_starts_a_new_operand() { + let mut calc = Calc::new(); + press(&mut calc, "4 + sign 2 ="); + assert_eq!(calc.display(), "2"); + assert_eq!(calc.expression(), "4 + -2"); + let mut calc = Calc::new(); + press(&mut calc, "sign"); + assert_eq!(calc.display(), "-0"); + press(&mut calc, "5"); + assert_eq!(calc.display(), "-5"); + } + + #[test] + fn sign_after_result_edits_it() { + let mut calc = Calc::new(); + press(&mut calc, "6 × 7 = sign"); + assert_eq!(calc.display(), "-42"); + assert_eq!(calc.expression(), ""); + press(&mut calc, "+ 2 ="); + assert_eq!(calc.display(), "-40"); + } + + #[test] + fn chains_with_full_precision() { + assert_eq!(shows("1 ÷ 3 = × 3 ="), "1"); + assert_eq!(shows("2 ÷ 3 = × 3 ="), "2"); + assert_eq!(shows("9 9 9 9 9 9 9 9 9 9 9 9 9 9 ="), "99,999,999,999,999"); + } + + #[test] + fn caps_entry_at_sixteen_digits() { + assert_eq!( + shows("1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 8"), + "1,234,567,891,234,567" + ); + assert_eq!( + shows(". 1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 8"), + "0.1234567891234567" + ); + assert_eq!( + shows("sign 1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 8"), + "-1,234,567,891,234,567" + ); + } + + #[test] + fn backspace() { + let mut calc = Calc::new(); + press(&mut calc, "1 2 3 backspace"); + assert_eq!(calc.display(), "12"); + press(&mut calc, "backspace backspace backspace"); + assert_eq!(calc.display(), "0"); + assert_eq!(shows("5 sign backspace"), "0"); + assert_eq!(shows("6 × 7 = backspace"), "4"); + } + + #[test] + fn exponent_form_is_a_whole_value() { + assert_eq!(shows(". 0 0 1 % 5"), "5"); + assert_eq!(shows(". 0 0 1 % ."), "0."); + assert_eq!(shows(". 0 0 0 0 1 %"), "1e-07"); + assert_eq!( + shows("1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 × 1 0 0 = backspace"), + "0" + ); + assert_eq!(shows(". 0 0 0 0 1 % sign × 2 ="), "-2e-07"); + assert_eq!(shows("2 + . 0 0 0 0 1 % 5 ="), "7"); + assert_eq!(shows("2 + . 0 0 0 0 1 % . 5 ="), "2.5"); + let mut calc = Calc::new(); + press(&mut calc, "2 + . 0 0 0 0 1 % backspace"); + assert_eq!(calc.display(), "0"); + assert_eq!(calc.expression(), "2 +"); + } + + #[test] + fn chains_from_result() { + let mut calc = Calc::new(); + press(&mut calc, "6 × 7 = × 2 ="); + assert_eq!(calc.display(), "84"); + assert_eq!(calc.expression(), "42 × 2"); + press(&mut calc, "9"); + assert_eq!(calc.display(), "9"); + assert_eq!(calc.expression(), ""); + } + + #[test] + fn equals_twice_does_nothing() { + assert_eq!(shows("2 + 3 = ="), "5"); + assert_eq!(shows("="), "0"); + } + + #[test] + fn replaces_dangling_operator() { + assert_eq!(shows("4 + × 2 ="), "8"); + assert_eq!(shows("9 + ="), "9"); + let mut calc = Calc::new(); + press(&mut calc, "×"); + assert_eq!(calc.expression(), "0 ×"); + } + + #[test] + fn pastes_numbers() { + let mut calc = Calc::new(); + assert!(calc.paste(" 42.5 ")); + assert_eq!(calc.display(), "42.5"); + press(&mut calc, "+ . 5 ="); + assert_eq!(calc.display(), "43"); + assert!(calc.paste("1,5")); + assert_eq!(calc.display(), "1.5"); + assert!(!calc.paste("not a number")); + assert_eq!(calc.display(), "1.5"); + assert!(calc.paste("1,234,567.89")); + assert_eq!(calc.display(), "1,234,567.89"); + assert!(calc.paste("−12,000")); + assert_eq!(calc.display(), "-12,000"); + assert!(calc.paste("1e-9")); + assert_eq!(calc.display(), "1e-09"); + for junk in [ + "", "-", ".", "1.2.3", "1,2,3", "inf", "NaN", "1e", "--1", "+1", "0x10", + ] { + assert!(!calc.paste(junk), "{junk:?} should be refused"); + } + } + + #[test] + fn paste_replaces_a_result() { + let mut calc = Calc::new(); + press(&mut calc, "1 ÷ 0 ="); + assert!(calc.paste("7")); + assert_eq!(calc.display(), "7"); + assert_eq!(calc.expression(), ""); + } + + #[test] + fn groups_thousands() { + let mut calc = Calc::new(); + press(&mut calc, "1 2 3 4"); + assert_eq!(calc.display(), "1,234"); + press(&mut calc, ". 5 6 7 8"); + assert_eq!(calc.display(), "1,234.5678"); + press(&mut calc, "× 1 0 0 0 ="); + assert_eq!(calc.display(), "1,234,567.8"); + assert_eq!(calc.expression(), "1,234.5678 × 1,000"); + press(&mut calc, "+ 1 ="); + assert_eq!(calc.display(), "1,234,568.8"); + press(&mut calc, "backspace backspace"); + assert_eq!(calc.display(), "1,234,568"); + assert_eq!(shows("1 0 0 0 0 0 0 sign"), "-1,000,000"); + } + + #[test] + fn copies_without_separators() { + let mut calc = Calc::new(); + press(&mut calc, "1 2 3 4 5 6 7 . 5"); + assert_eq!(calc.copy_text(), "1234567.5"); + } + + #[test] + fn group_digits_cases() { + assert_eq!(group_digits("0"), "0"); + assert_eq!(group_digits("999"), "999"); + assert_eq!(group_digits("1000"), "1,000"); + assert_eq!(group_digits("-100000"), "-100,000"); + assert_eq!(group_digits("0.123456"), "0.123456"); + assert_eq!(group_digits("1.5e+20"), "1.5e+20"); + assert_eq!(group_digits("Error"), "Error"); + assert_eq!(group_digits("-0"), "-0"); + } + + #[test] + fn formats_numbers() { + let exact = |s: &str| Num::Exact(Decimal::from_str(s).unwrap()).format(); + assert_eq!(exact("133"), "133"); + assert_eq!(exact("-0"), "0"); + assert_eq!(exact("0.0001"), "0.0001"); + assert_eq!(exact("0.00001"), "1e-05"); + assert_eq!(exact("1000000000000000"), "1000000000000000"); + assert_eq!(exact("10000000000000000"), "1e+16"); + assert_eq!(exact("12345678901234567"), "1.234567890123457e+16"); + assert_eq!(exact("1.50"), "1.5"); + assert_eq!(exact("-2.5"), "-2.5"); + assert_eq!(format_float(1e15), "1e+15"); + assert_eq!(format_float(123456789012345.0), "123456789012345"); + assert_eq!(format_float(-1.5e300), "-1.5e+300"); + assert_eq!(format_float(0.1 + 0.2), "0.3"); + } + + #[test] + fn evaluate_tokens() { + let n = |v: i64| Token::Num(Num::Exact(Decimal::from(v))); + let t = [n(2), Token::Op(Op::Add), n(3), Token::Op(Op::Mul), n(4)]; + assert_eq!(evaluate(&t), Ok(Num::Exact(Decimal::from(14)))); + let t = [n(2), Token::Op(Op::Pow), n(3), Token::Op(Op::Pow), n(2)]; + assert_eq!(evaluate(&t), Ok(Num::Exact(Decimal::from(512)))); + assert_eq!(evaluate(&[n(1), Token::Op(Op::Add)]), Err(NoAnswer)); + assert_eq!(evaluate(&[]), Err(NoAnswer)); + } +} diff --git a/src/main.rs b/src/main.rs index 521ff7f..a540426 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,3 +1,7 @@ //! Alias Calc: a tiny, instant calculator for aliasOS. +// Nothing calls the engine until the keypad lands (ALI-2101). +#[allow(dead_code)] +mod engine; + fn main() {} From 47a8160d6ef3a021a27f3833f1ad327c78d89269 Mon Sep 17 00:00:00 2001 From: Michael Aguiar Date: Wed, 25 Nov 2026 12:06:39 -0700 Subject: [PATCH 04/50] Draw the calculator: rounded rectangles, embedded fonts, keypad A small CPU renderer: solid fills, anti-aliased rounded rectangles (exact coverage on the edges and corners, solid spans everywhere else) and text from 9 KB subsets of JetBrains Mono Regular and Light, rasterized with fontdue and cached per face, character and size. No fontconfig lookup. ui.rs lays out the expression line, the result (shrunk to fit) and the 5x4 keypad in logical pixels, drawn at the buffer's scale. Key corners are 4 px, close to the 2 px aliasOS windows use. The palette is worked out from a background, foreground and accent; a fixed one stands in until the theme lands (ALI-2103). A full frame is 0.54 ms at 640x960 (4K at scale 2), checked by an ignored budget test: cargo test --release -- --ignored budget. ALI-2099 --- .claude/worktrees/agent-a2e016efd9728fd93 | 1 + Cargo.lock | 34 ++ Cargo.toml | 1 + fonts/JetBrainsMono-Light-subset.ttf | Bin 0 -> 9396 bytes fonts/JetBrainsMono-Regular-subset.ttf | Bin 0 -> 9448 bytes fonts/OFL.txt | 93 ++++++ fonts/README.md | 16 + src/main.rs | 2 + src/render.rs | 378 ++++++++++++++++++++++ src/ui.rs | 345 ++++++++++++++++++++ src/window.rs | 27 +- 11 files changed, 888 insertions(+), 9 deletions(-) create mode 160000 .claude/worktrees/agent-a2e016efd9728fd93 create mode 100644 fonts/JetBrainsMono-Light-subset.ttf create mode 100644 fonts/JetBrainsMono-Regular-subset.ttf create mode 100644 fonts/OFL.txt create mode 100644 fonts/README.md create mode 100644 src/render.rs create mode 100644 src/ui.rs diff --git a/.claude/worktrees/agent-a2e016efd9728fd93 b/.claude/worktrees/agent-a2e016efd9728fd93 new file mode 160000 index 0000000..b9889b7 --- /dev/null +++ b/.claude/worktrees/agent-a2e016efd9728fd93 @@ -0,0 +1 @@ +Subproject commit b9889b75ad02a580fd559130cefe388bbfce0e73 diff --git a/Cargo.lock b/Cargo.lock index 3c619b0..0c6c7e7 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6,6 +6,7 @@ version = 4 name = "alias-calc" version = "0.1.0" dependencies = [ + "fontdue", "rustix", "smithay-client-toolkit", "wayland-protocols", @@ -27,6 +28,15 @@ dependencies = [ "shlex", ] +[[package]] +name = "core_maths" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77745e017f5edba1a9c1d854f6f3a52dac8a12dd5af5d2f54aecf61e43d80d30" +dependencies = [ + "libm", +] + [[package]] name = "cursor-icon" version = "1.2.0" @@ -55,12 +65,27 @@ version = "0.1.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48" +[[package]] +name = "fontdue" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e796cb6894e6418daacea84b28dd4f98d3b32c74d5bb452ba1ecfbf5ad8e84ca" +dependencies = [ + "ttf-parser", +] + [[package]] name = "libc" version = "0.2.191" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" +[[package]] +name = "libm" +version = "0.2.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981" + [[package]] name = "linux-raw-sys" version = "0.12.1" @@ -200,6 +225,15 @@ dependencies = [ "syn", ] +[[package]] +name = "ttf-parser" +version = "0.25.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2df906b07856748fa3f6e0ad0cbaa047052d4a7dd609e231c4f72cee8c36f31" +dependencies = [ + "core_maths", +] + [[package]] name = "unicode-ident" version = "1.0.27" diff --git a/Cargo.toml b/Cargo.toml index aace7ce..6370515 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -7,6 +7,7 @@ description = "A tiny, instant calculator for aliasOS" publish = false [dependencies] +fontdue = { version = "0.9", default-features = false, features = ["std", "simd"] } rustix = { version = "1", default-features = false, features = ["std", "event"] } smithay-client-toolkit = { version = "0.21", default-features = false } wayland-protocols = { version = "0.32", features = ["client", "staging"] } diff --git a/fonts/JetBrainsMono-Light-subset.ttf b/fonts/JetBrainsMono-Light-subset.ttf new file mode 100644 index 0000000000000000000000000000000000000000..cd2befe5cd83b1da71d64661944e678aa43d10ac GIT binary patch literal 9396 zcmbVR2Yg%Axj*M>%PX=i%ZU?PwqnVShipx6?O}PycI?C%wqxAUJjnT-!_WnuZV;bo=bikGB>S5|X=;5PHwHiGlvP$feI>{xW<& zwY`7mB>6q(0Z(`33#+&r{{!>pN0XI_g1`L_r}H z6jWpd(Se4_Y|2t+0$H8Q;jR;zO*X4VuhZc}{2}_2=%ltB^F!T*o^qK;YHBI(*-nqRtE*iLPXy{6El`*A$3Erc+}k9F5J`dFsUTE=T>PW1K%={V3flLB?B|d@ ziKr8jXMvDZsxvTJDkgRRbpwf6?%#;V{Pe=V;x6 zp048`#N6$e`+j1s74xk5YPeFp{nlIQo&yJhTqqb^ctX(368lt`nHHDV9QO!lL%y`( zxp2tsZVF$boE`GDwD`EBg?|jqfZ zex^S%%m0k-Zg#qw82gcL}PO2#rj5m^?! z0d>j>*P;%bEd-fa8jZkAN-IY8v~_q~t>*IW-mqnJeSNPr9IUSPm#>)!cGw4$Q~l1S zP+f&TB`U%jrPa(#{6=eCwKq-ZlIni@8vP*PF_O|;NNhANtfekyr|zV|YB6C!_{ z#R+`P;zX6mQv|$Fi{g=A8r>RpHZ(ZHTa=T1oO`bFl9tSk)z z6)EuPGws(TtHk1rdO);wmDzQv>MAOJv+I_mG?6GR`Ie41X$F0Pe>r=#LSC3nEqpcq z0rSc_U~|A`Rn$uJQIu%DdL3=&kD=;5N;ic$Pq2OA8Po%g1mU00xC&&VKJFnFF=nd; z%Z5xR1dkey)k%fSw6et{GYcG|Wo?#6cH2Fouw?tj{?S${-(dE(-CthgR`xZUno7!N zOAB3Hk@fs_BbIuvr)F(+Sw#)whjogcfo$nmVOhKygn}uHb3zud6k{tQ7%@(P`Zi@a zOcfpVYoh~O>pY&iT8~#*YaZn0k6dc59q+xnce~H!yW8h(bRBjzGVObj4>Ca`As>(e z$N-H_zep3Sm)$ItQcM5bTz~Hj*T(s4>l+*EYyEg+3&Y{a#Bg_&BLIQ{M^*PQq~0u8 z>73LMQJ`uNihja4=cHD33`Ez~cPMB$tZZ9dzP^vHsK&|K>i1a?Do z7qiPoaNr?z*5Zm5=b*-lDI^RNS(Kl!4C>$p{s~zFMN@KzZW*C9>GUs{jo^P6}I8NDG*BOm= z*0m~W>%jVS!4huwv7o)OGE!mN+B?@XURBw*@QbxQbXB8k+|`J7r{2%Jh?P&M8<|XA z{4Ite>pR%u&>yDq)`pH~*j-)gMGbh@S~Jqk-#`c5fsmWOJr*O~5MM8na(aUP4i##c z8^N8%$1y5ohhPh=*xk=P5_>904+QywAaFNA>*E40vO>VUU%+MKj{rAi(H1IX7gN4( zx699;rd=}w$AW$b{c&*Nlimr&Z5UD%!S0JIc)T*`)WhM)|Jd}{4}0#Ng78D{@~8RV zoj#5E=n^>{=7U2%TYb<{u!?C`(_MkJPt&9#-Gl8udM3E=bYXE2^PQNV4gWw#SVpT%oIa#4FDWc6X=&g$(R+1kidUbz zpYuosiF-s{`9+T?S{#cG(GOc|m-<79@Xrw8#&fIwVuXJo=@H#i{rywZ5!U_!6w^c3 z4^0b~fZub_;}2YP{ZK z+&uD8$j*B6+`WHu`H_?Ha>6pdS*VYhqyY8mVxfOQ#k!wz%Jy1RtB$%hB@MrVdQ}5P z$ByhYRSV^++SI?G|C>PH>3PtN?5AW7$|OS%Av@1%p%comS~b_EXlYo#IeclolhY4d z>PC7iDy|43%7M8q_8DruF|qm^%vp#P=zMnh$6LJk38g!+`s-+B_aLfWjmd1OE?m98 z&K>PCh6f~VVtc8vvdZ&iZ*ZVnv9__O+_*+>6lW@$9D$BjN8XxpgHw^A==3#rF{#l4 zpa(y}x~)X4q7(@ABp$H?p4QuMZ~Ma^bh(Go0(Arr9SZUfYgY?>XuL1b|1W((N$+^r zQ&Z~=Pbw!PG{WEE427KR9+?DRY^}H)WZ{KWKZ9$2Qqf&95r+1@Etl+3p>;>gZR#;Rj%L;lu zf5~!7db(vfy?$YyUY_GhPj}_;SAttLxaEP{zv&CAPkygwR+=IfrO0M_zV~d;WwKPU zBu#c1&7n!(Rc6cO*~;(of9L=7bW)C7o|E)6sMeuFT?wkJ{@9oF1@y`GSJqu4UnUl( z$uI5XKRosZC*mK-GA>(Y)X;Tki-6mM%jdv7uPf-G)%>gUEBr~?*h=>Y!~7JyBO;xN z-4*N5(TgnEQGTIEx1&nMH=EeWln%_z4GhlC4LF*c9Sm0F<*fiH=c3dZotumD$D?!J zb~kmp+uPmzad&%c)ru84IV)DIic82XN9|LxzQwGPS?#Q(^}P7}gIn(naxJ%P+QT+6 zl(fROtmDmQ^D=D0#u;luqFq5JEz4JL_@|{jUQpAaJ0@GQNYe~H^YFuo{6nX8Fz4E}Ut zs0<=-#0wv0f}&d3%@hcm0Xw>9^rym>09$!hy5j4CG>ew`$7)uudbs;3QA*8fXT(}F z=JR%SdA(h5P!mcW>wXdO}&+4smg=@)b4LP@if?Og+W;_ffgGlfqt|oz%rG%dQ%9`?u7_4adJkHwxxz3~Ye4egj`$Ms8uT z!6NQl_N*=~T@6r{=yYXeI$a6oz8;Iv333x`M>KHW>s8Uf9n{4C48q3gVAV)sRfaC1 zBwF%JOAW=vh9y9c6cywb73CKc@f+Bcy)kO9g3}&QOJOxRL5)QnYwf_9>a=UtXw$XD z#o8eVL5~z`*?_iq;pCz`@5Vl-Gl)15qfjU^i)3**5>%)>sW-{ELaSYoos*Zp{1hi$ zIQ^^q6>MNR7FUj33;g$hFRZn8q1S}9(X7Td$Ow${3BF-+x3qe$ywW>VRk6Otx*|V+ zg=S@5{)$r%3TbNTbJlFKh(?z1pxEVX<4oK(Qc8&3V8>PsdqIPpZQI~$;kXEU5xZR@ z!yz38HL}Dm?r41|xj22fUA24pZdGL#wucgl+9bT$muD0uhw7S=@{*Erled+OsmjyE zsj@O(nN*XUZBGBnSJKVd$r>pJP~p?dRbwSvmRYm2t;?V@>-Vfe-s2?8Y=^P}m}O== zK&=x%XJ_Y*c3oHTrlEqti6TeQeMQbC&!+oy_q|d3MC}{+7r)VT;gqZ`b`v(W4MOyw z1hvt@PX6$?=%F)6SW1?BmEbEq#vksagYnOl9FKjOz9R|}c4EbBgFIDBgY}r*?fS8&qe2cQB5pv7$I5hYi+v37ugmK;5}Gy*Z8! ztZ?im`VUBoRT?>Ax7*^5x8W4SCTvus=v|mgWHKpQ95wxM=b$1}QtaHZ!?{M9sTl06 zs4&_jnbKO9vrd{Ru^B7IyIPJ~%L7L1(Uz`2dD+n_pG*<5A1x~nfZqTtqX0iFjl!;m z@j)z{Wqg(q`Xrr!~um-;dEl+?e&P!Og%FYU3`{>R)Ve-J4KLnUhZpDo25;KI& zrCD|Bop*jT9uVaQ;$GWF4fJKYo%u8ab#@maO-0Ca4Tc)3f{(-I{LfK9uIai z2k67}S;Uy0bRHx`N;*f`Y#yTa7KS>; zx{p{*m9`_cT8lAt-_^3QbvCz*X34X*2HS>Z*IX?d?J&7y{OM%PcxdgI{A%vW3V-U~ zWi<@Xr8bYCnfE|{%tF{ zp8l0fW_ZYc&o5?hhu8b@;xqETn|y~O^lflJEHFPx0NwO{9zc%- z0)K@|*-4HM-F=vKx^`<}yjm4nB{9Od`W&-LhOma^;@6CL3Dp&pi`daZlecPhrEXPTR%MgNUTD&-%*!%S z60Gv(7>aVRST8<+S{Lo)M2JRcibH7}g(lAEx*ltKv}sbFDiWtDW@sn9mfuZ98HS`J zLk7QqGj3Jvb1uNWC9GO`q>R)8A3jMes#v^4sBElzNVF2{P>FpuU$5I zWmhoJ<#(*9l5^edn}@db4doP*oGSENi$2G%5v&VaSiV6xi{ zi9@MV@~L$Ut4;8n?*CQ^riMY5MxVy1C z$U@fVQ<{(Fgl$KV$T9=c7|G0)^PBnC;PE?3tyayEL*7HT1rHtc9X#ZsrPO9C<)bC` z1BVZv9R^2!KljyGwn)lq!qV*KPvsRB<^i~`YFDl*C|I>p%VvkUy|FBjipfU}W(|L0 zdgFF(@4kHm)#g5KFCE7>85!Yl`Xp2wLdNKmWSm@wx=V$z#fvEMo{ucQoZLmePku%| zrz%92i*BM@=-25(^q2IXh?TY6joe+_aqicmbWy!%vuIlMpy=0PiP$C{7GEX)k@zj~ z`{D(OLQ){9k#tC|liVkHP0C5F(hli<>BG{OrSHmeWsR~C*_UKb%3hXzBF~lEW+gii3(L6@O8hl>N#{<>ksl$|sZ`CKV^uBsC>>H!G98dx<0M-G505-oDuo=L3*8mpjbmN%;8)q;K&;gtPhR4R( zo#D;_7)>*P@v8@{22=y;0E}j5;@*mTC;?&Iy#V&jpLqTa?ym#b{Z+ubfNKGI0OQ}5 zfaAE&02qw{z-xe80s8=q=K%l@AOL0y#)o~|3SjnRx-ppP;2q+78+DlB-iBZB%AQJzO zMdbM6O9<-^-n6=sI1kYo&_SB9@0=cM10h<(i$H?qANC3H9LgkO@>9I$;@3zKels!R z^uPLUxlqxN;t^`@is8rxQ+(kCwlz9u;N-n+NJ67b_allitAH<%< z{b=l}*uZc7Z`ME-oF1{WbhcX*{sj~F_^pfh$XXIaM)#8e?24O6GYOFOSXtY_uaS6w z*8{$ri66f+hjB{K1}QtpC}}~b(aL^R#Xkj^W}1naoxnfwOi2;m;^Q2&WW58MBf_t6 z|DAXiFPS4DopeoNTuStGPvSX+7SMYV&#A=5JrAiS$RybXu47~bvdqFlCfJC97Fvvw zA>2c_&O(!E=r)FmHiNMiV2%T{&|@0+EtoSP;Ja|9ISb4QjI)_V0^M2gnSuR`_!|Kg zHe(K!C^a~;A#I6@= zx5%RmK3ufRI?Q7Fj6vFQXtk7%7TU~`VbEuqPe3zfC1%SaatWyf$0~pYU`L-~g}<%P z{9+nhj5G7Xm|#i2z?;!si>G05*dge|d=#It4fg>^%6v2gK3YgLjysc`Ng4O&TEt^B z-ox+-o2x}kGOZY8rtvunr5L$TbEXf2czj%p@1ivQ(4IvMvwRd+Cg%>kGdZ*vV|-o6 z5B5BZ*wA8}S@K+@%s>_vo0Axw0Z(TCZMd`88bQp2L81BoiN&%@_!k?3Hxtz+J`%tF E4*>!O(EtDd literal 0 HcmV?d00001 diff --git a/fonts/JetBrainsMono-Regular-subset.ttf b/fonts/JetBrainsMono-Regular-subset.ttf new file mode 100644 index 0000000000000000000000000000000000000000..f369b8a8779a944171cf5122bb413bc6e3709e79 GIT binary patch literal 9448 zcmbVS3s_v$oj>Q^dGSmJ7%+q+^9VBphUdJ18HSkwW_SgL0Rov2$nb^`LU<%ZCG93Y z(yd91U(Fh$7OmZFv({=wZGAs>)wU-mQ+is!DLXTT1-ZxNuf}dJa_Qf9Ywz=@_oN_Z3@SwtmPJ$j4!=J zlP`L?Em=qOz@fI3q-)X?O3g+Nje)n6*lkv$!GLk8v-3y&`vPTo z-t4LVTlSY%`N|L6SXozBc_X*jzr8e^z{^Xv7Ig2S-*DS(?xokN%3TeFlCJ0{Ts-$% zvYrsR-e^->?Q9zZ5bG5hby_+@Zb?&6Yyb3gfA4hI>vUFCIi23{bo@jwt?!-K7jair zxrHa#GqMkycY$sKx)X>dMs+$6DHH}1!=+{zDk~cb^!51~8hm}+qP@3D_(fHp zJy`Ff25&v+>IW8;hy|SMG~zGXe)^#BIL#5>rVZR;=+{BvatI0|J(!(@*>P;g<=H*- zVc{%w39n%0pF+YjnAZtz72tN$|H7@!V6#BLwCEa+zjkRg%Raa8xVyUA-5+`aTvMhk z`j=&Tp)33v@VhhoemML-wBbfWg*jyXt*>oCcQ8RMqo%EJF?+kJF zP-y9Ok+1ydC*sUC61^5lAHWUzl1FC40gopTJ{Z4$u&S=Eic>9pI=CPBnFfl0KT(vw z8rH|B8hC@cD?Ii<@8i!8ogD!|uh4Q~Ubuy}2;XHAJd8EWUggpno#t?u*25}iMLKHn z6*fvz#jmNUj5({_?%)l4I<#AR^Ulc49lS!eziFRJ0p$NeUEp?m@s|!;g^6W|4e6ksi${lrdN2Os(;;!pVwDVkGrnU zExb@s&-P&vK?gdMNrouD638CtMcrPZb>~HIuf4JI&b|`|kCs+fmmcL7ZQYgiqZ;8w zY8PIow+70cex{3BNOLWy-g1>~S&b&dC>xZEIB+Epq@`zMh?~)((L>=TkGsCmytk&= z+Fjx9v4^W|Hea4;vaaQN#Dt2P+H$iuaZ}omzr3@!xTCD3va%$nEJ2&Lw{h1b_I1R# zP%<7Q+mF6R-+zre3bUUTtprvdvl1~T!Q90-B-y=ra4hVsaJj;}}x2Vl9s)de(~fR4*r)iZKN zy*DMrt6y5gZpbmBe=;qm@)k&z5$RxF8p{vLob#^^?~6-S$W!B{`d&RhG#8gDNB9#5IW>y59lBkIl1+1%qj_jivsxvJ)?oqqQz zx9AHjvLuK+iCGXV!TK`{#$~L?Tn>wZWx?6m{+<~=%==22+m`y!oq^S#>YW(uw3Su4 z|G`~dZtY~zsza313gsYD#A-2#F@IS=E0iaO`g&X4Eh@@|!&Dj6mU=v;pgw-Q`~IGB zw{32I$v9%KXcCEbR?kNEXS3rPx^dw>iK!3y;gffGk)s zbCnM7KT~MucvX|Ly|=gB*`(sO4{cYA(x|Ll2-)&W!o{|+?&O9Wp3o{_Lsj)<9-mLheLunMA&NZ{j#_k9wM&( zmb4n@+;mNV96 z7vyfOh%p1wcM`gq=-e@m7NeMmbbWCC&rPON_s0rl`v~+i+&1AFIdU` zk_o}-uMGj_zM1L%{^^-MR;rd)SF5In4~P7onR|L-e){RE;KJfSqZlux2=+w|a7_ez zfaAqY`a)tTJ0FV!3$ftUvj?GU$@r-l2g*HXJ>^Wk6JRF=oJbW~Op_XoL5#~9^+cFc zHhQ-049_^-oN>hF9_lG9oUMknV{JPm%R{orODx~ADwFxDHC74WMT&)DEJq>0q(jrY z2Ez7YbBV)ySE;+N!yFut?cgk1%mr54@!JNvRIQE1JabMUE?u>?vNqK0* zyL~H?4JC!3SH-=^=#5z_97>EQlD+m-hwi&CeDR`g{d}{JR)x--2?@_;8IXZcMT+%- zkyVjjP#@&=Oolyi@0}4u+dbc?CsTP!q0^DJiGm%j>)QDrHJ!B)JcmZ%ntT z)wXnc(@Jk?k=~e9sa98J2{(bi66}VGL9FurMtxB7@{^-`lu0r^Nx5hA$(Kg=E0g51 zHLCq|Jxw^9kf~B-CY%*M65d-#*bo=DAz=Yn?XY#mIg37yRrLY=UdtPi!>VMSPgWl6 z5iTwKl#>Y$rJ2{RHK)-wlt)bBcnDZ4#=YhGAWW^Of=}WkQ4^-uhr+@w&<>Ak_!DUM zx2RIHmMtoFszj)}rcif?&fWqt8 zyi~h*dPZJ|6)&i$l{(F~KikYT&Wb>opY0nsP*(G=w6T@SN;`91fjW2J^klDfy7o=c z8vU_qHEYFtVll&DbFflMiOQMrryJNG_PbcM+WZ&ds?}7 zM+wXnG_tY;=SG~O32@k`g=$#Fp|=Z9(D*^&{SU(P$LM#2O4IiQmhMOcq|Pe1*f~CS zQj{(Ta3IcLGG;^=V?pRe_9YOjM?nB2akc`**uGZ~Aus0-t2v}DqddTQE$Cj1BOUL~tVSlc0T z7qbf%`=sj{<~-T?`PqPYvmv{nAlqPuT+c^$(HU|FBu6r!xbu!N|2!=b-UO-SXTb9% zvHq7 zY1+J8-3W-FcjxM~d3jo0?$RsE^jwVog&u$n@C-vXZ{d{^9WgAFPaI7w&D85NH*VOZ z&%D6#OG`i3XJ+bknVIb1Lk?s8yI3z~S%+9_Li@PNiJ7WWb2Y*@OFRt?-nlvdP+3uX zX~hcWv+OY5ZrkN6+hON>R_#GiB@J;_Zj6`-ahM!9vf)fV@@iZxBP zR+-bBqsUCobfnJBr8>}2U_iN6mS$7$EbdmjGBcei;CcDPx1QZ+SsY+i1dGz*0B8&% z7#!^0(P3ycb@b{ZVVgze?%w9PdyG#zTgMHeMgSp9Wrb%xE&vD2N=WRs%kl(*Yr>GlG}EEXMVT4 zcjo68T4ihG>}FEFMrJL{AMa>>&{h~Mv_06|5zNbb&>2uFo5~-|%L{_mo~R@xq)G9F z!}ft)T-o@_Mkt=x&I&_MexXCTF0R~SDUVyHbQI?2JGbYn)~WJfjUF>P`P-f2Y@f2` zIF-MQ?PIF9#VD{gm>8FDMDL(4flJ(>u&R~a9=`GMnKKZ7@bX7NHscg#d^I*hJgHdJ zr_P-Dcs$4_1|<#NM)mX@on-n=MZ~?0dZ<1qu60H4;j*H?6E%-7F8Ztfh6bE#PSA(x z58-1*(sqgv1!)^)JAH=H9?^3Nh2K)D8dPG)EWE|4f!gRax0WA-t>&`2Mvh=@LUPJb zOSeq$RK)8H+&7yv(hZYR!{f6}p^y@@$wX7TcXMHMB_>M`6Q;-(%95+Ia(o0-2 zTZcG+2mqIdv)^MmcFc18q~+vs>#?KOW5+GWPFhbMvmS>O`iX;n#Pwpu8kV6~$6F<< z5Uz^3EPfmF^DoicUyF6=xh;DA76#vJX!u~cj|k9C&T>3`A3MMjm=@)Lb~s}Q8n`{?(@joR>_9_2GCfbXB%=VMd zxfJ>;lZr#kW*hN`4Jnu!^aVV-WboIPXP4;LZ%iv}4>)7JsNWgLG?_9Tet&tb)L}FS zX`A?018|BBYM~nGjR4nsly}2u__`~Qm~6A=uG;~>Z;X8I7RwtPXnb59y}Y)(LdD- z$-a#S!$tu0VXP4!8a#O0w820P^!7Tpm)-K>AxyBp1JSoOZ}M*1EItI&%GVmh^01ik z@=?zhq2e%IsfAX`Y}6hrH!QJ3ym+p<`l5x_v>&Ru{m|r*ZS{2>e$N(r9M>KU_wU|0 zZZPKN8UYJ|Bb~JE)-y*Yg%6u{bOxsDTeMmJ_VDzu@KFC$11%`dn=uy_nWyuLSr%Rw z{cmmvG;JnDh)fa@4pXd5S-DNl$UuV1Fqn`iO(hP8DRy^vp>r_Ym}TF!)zMnmX)|XR zZg_b||A~`*kvx5?u`I_rx3SRSj2r4K3+|F_4mbjxMeVp zd8eh!;)E?k5dpWy@)vH7qv2TY;-Wj?4=1>9;GB>S&(~3^Lvf7536i-XAp3^mVo$*pLwcE`?Z=U1SJ@-_dITN_&boJ>ous-1!_m${+ zK90qO)gCUqr863J0PZXL4a^WW;3|^}_1w+TEMCo`EHzm&glDJv$GMwtyN%r-J;2>e zr}0gRilbAEIfRVR?~`$IE8;H2$jT2Nd)JXRGDqggljPsXr!*Os<))o>b%3WP&_iZjd|Wt@5MtZ_9tI zkSj_R+Z4Ae9#))F{7$)1S*ILQ&MBW#zN!3JrB#)xBC1oWv#L+y%yGWBVBCSYyW+kd z_kMgyd?bD%{!8)q#Xl4OQ9@yYC!r;wJ7F|oCgCRho=2l5I7N&q_nT`}lK+XLtXu<;Qz*0K4lWost@Y;GZd?PmvU0x(`!pN%oP zSlbBj$DjeN2M_}IV*N$5=K((hyaBifV0>-{FxuG~20s8y#rjM>Z0;$*Z2(5&3BYFn z0${T60@ybuKPJ=Fys>YLCPrg2fXR0qAj);Z=ZJ6&P>*+Z=S29+tU%y8KP!vw;Fhkj zX;?dvah>#b_V-Bc@3Dq}TCt_wq=b4fO4w~g><2zXURZvq_la*>L!Pt;f0?3Umv#_u zM+wowUPKhk`*3EEd?<~`$m@9Dh`+h>xW6bQWyFKKk6oZ$1qSk0)e-Fn` z9AVWRl`%PC|5%^mUgnutp97a~$ND^OgWrqwWyDPNvA&$N(WY2mL2~H>v3?S(A7lMw z*yklswHNo02eIo283HZSkWdL^#6Sx!hRFchdOWAW$s~9iK}4Iv*jB6@2WY{^B-&BT z=@Zv`$qd?Ij7^F&b40w;*k=mzE5z>*u&^03kVFAi?In9K`q#UB(b)37TfSia3RNLc zGX(r&pm-A86ySe)6cH<`gnID7p4W1;j5i-TS-tkJXRhp`y=LwW za6C;0K@XG8UU1JO$>g0w_LE{zSPHNL9H?e&un8Na^F>_#ElQcTMnsAG#r+xXR`dq3 z%K=diOqbG(F|>W4mg#Z;duc({I9f(Oqg2v+E9|xr@6FI1o2!NGGR_$0#;Y)xF>)>U zj3)+?9evTh%hW_50cKfDTfKNPIuGET(V@i{+t&*}V*P2@kQU=inkyDH1#XxPPhfNk jdomr2p=CBW1lwu`hQ|NrD&~daPjmnpjYTDCM0)-YU1 Self { + Self { r, g, b } + } + + /// Parses `#rrggbb` (the `#` is optional). + #[allow(dead_code)] // The theme reader uses it (ALI-2103). + pub fn from_hex(hex: &str) -> Option { + let hex = hex.trim().trim_start_matches('#'); + if hex.len() != 6 || !hex.is_ascii() { + return None; + } + let channel = |i: usize| u8::from_str_radix(&hex[i..i + 2], 16).ok(); + Some(Self::rgb(channel(0)?, channel(2)?, channel(4)?)) + } + + /// `self` moved `t` (0..=1) of the way towards `other`. + pub fn mix(self, other: Color, t: f32) -> Color { + let lerp = |a: u8, b: u8| (a as f32 + (b as f32 - a as f32) * t).round() as u8; + Color::rgb( + lerp(self.r, other.r), + lerp(self.g, other.g), + lerp(self.b, other.b), + ) + } + + /// Relative luminance (WCAG), 0 for black to 1 for white. + pub fn luminance(self) -> f32 { + let linear = |c: u8| { + let c = c as f32 / 255.0; + if c <= 0.040_45 { + c / 12.92 + } else { + ((c + 0.055) / 1.055).powf(2.4) + } + }; + 0.2126 * linear(self.r) + 0.7152 * linear(self.g) + 0.0722 * linear(self.b) + } + + const fn pixel(self) -> [u8; 4] { + [self.b, self.g, self.r, 0xff] + } +} + +/// Blends `color` over `dst` with coverage `a` (0..=255). +#[inline] +fn blend(dst: &mut [u8; 4], color: [u8; 4], a: u32) { + if a >= 255 { + *dst = color; + } else if a > 0 { + for i in 0..3 { + let d = dst[i] as u32; + let s = color[i] as u32; + // d + (s - d) * a / 255, rounded, without going negative. + dst[i] = ((d * (255 - a) + s * a + 127) / 255) as u8; + } + } +} + +/// A pixel buffer to draw into. +pub struct Canvas<'a> { + px: &'a mut [[u8; 4]], + width: usize, + height: usize, +} + +impl<'a> Canvas<'a> { + /// Wraps a `width * height` ARGB8888 buffer. + pub fn new(bytes: &'a mut [u8], width: usize, height: usize) -> Self { + let (px, _) = bytes.as_chunks_mut::<4>(); + let px = &mut px[..width * height]; + Self { px, width, height } + } + + pub fn width(&self) -> usize { + self.width + } + + pub fn height(&self) -> usize { + self.height + } + + pub fn fill(&mut self, color: Color) { + self.px.fill(color.pixel()); + } + + /// Fills a rectangle with corners of radius `r`, anti-aliased. All + /// values are in pixels and may be fractional. + pub fn rounded_rect(&mut self, x: f32, y: f32, w: f32, h: f32, r: f32, color: Color) { + if w <= 0.0 || h <= 0.0 { + return; + } + let pixel = color.pixel(); + let hw = w / 2.0; + let hh = h / 2.0; + let r = r.clamp(0.0, hw.min(hh)); + let cx = x + hw; + let cy = y + hh; + + let x0 = (x.floor().max(0.0)) as usize; + let y0 = (y.floor().max(0.0)) as usize; + let x1 = ((x + w).ceil() as usize).min(self.width); + let y1 = ((y + h).ceil() as usize).min(self.height); + + for py in y0..y1 { + let qy = ((py as f32 + 0.5) - cy).abs(); + let row = &mut self.px[py * self.width..(py + 1) * self.width]; + // Rows clear of the corners and the top and bottom edges are + // solid except for their two end pixels. + let solid_row = qy + 0.5 <= hh - r && qy + 0.5 <= hh; + for (px, dst) in row.iter_mut().enumerate().take(x1).skip(x0) { + let qx = ((px as f32 + 0.5) - cx).abs(); + if solid_row && qx + 0.5 <= hw { + *dst = pixel; + continue; + } + // Signed distance from the pixel center to the shape. + let dx = qx - (hw - r); + let dy = qy - (hh - r); + let outside = (dx.max(0.0).powi(2) + dy.max(0.0).powi(2)).sqrt(); + let inside = dx.max(dy).min(0.0); + let distance = outside + inside - r; + let coverage = (0.5 - distance).clamp(0.0, 1.0); + blend(dst, pixel, (coverage * 255.0).round() as u32); + } + } + } + + /// Draws `text` with its left edge and baseline at `origin`. + pub fn text( + &mut self, + fonts: &mut Fonts, + face: Face, + size: f32, + text: &str, + origin: (f32, f32), + color: Color, + ) { + let (x, baseline) = origin; + let pixel = color.pixel(); + let mut pen = x; + for ch in text.chars() { + let glyph = fonts.glyph(face, ch, size); + let left = (pen + glyph.metrics.xmin as f32).round() as isize; + let top = (baseline - glyph.metrics.ymin as f32 - glyph.metrics.height as f32).round() + as isize; + for gy in 0..glyph.metrics.height { + let py = top + gy as isize; + if py < 0 || py as usize >= self.height { + continue; + } + let src = &glyph.coverage[gy * glyph.metrics.width..(gy + 1) * glyph.metrics.width]; + let row = &mut self.px[py as usize * self.width..(py as usize + 1) * self.width]; + for (gx, &a) in src.iter().enumerate() { + let px = left + gx as isize; + if px < 0 || px as usize >= self.width { + continue; + } + blend(&mut row[px as usize], pixel, a as u32); + } + } + pen += glyph.metrics.advance_width; + } + } +} + +/// The two embedded weights. Both are subsets of JetBrains Mono, the aliasOS +/// monospace font: printable ASCII plus × ÷ − ± ⌫ (see fonts/README.md). +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum Face { + Regular, + Light, +} + +static REGULAR: &[u8] = include_bytes!("../fonts/JetBrainsMono-Regular-subset.ttf"); +static LIGHT: &[u8] = include_bytes!("../fonts/JetBrainsMono-Light-subset.ttf"); + +struct Glyph { + metrics: Metrics, + coverage: Vec, +} + +/// The fonts and a cache of every glyph rasterized so far, keyed by face, +/// character and size. A calculator shows a few dozen glyphs at three or four +/// sizes, so the cache stays small and a frame almost never rasterizes. +pub struct Fonts { + regular: Font, + light: Font, + cache: HashMap<(Face, char, u32), Glyph>, +} + +impl Fonts { + pub fn load() -> Self { + let settings = || FontSettings { + collection_index: 0, + scale: 40.0, + load_substitutions: false, + }; + // The fonts are compiled in and tested below, so they always parse. + let parse = + |bytes: &'static [u8]| Font::from_bytes(bytes, settings()).expect("embedded font"); + Self { + regular: parse(REGULAR), + light: parse(LIGHT), + cache: HashMap::new(), + } + } + + fn font(&self, face: Face) -> &Font { + match face { + Face::Regular => &self.regular, + Face::Light => &self.light, + } + } + + fn glyph(&mut self, face: Face, ch: char, size: f32) -> &Glyph { + // Sizes are cached in 1/16 px steps. + let key = (face, ch, (size * 16.0).round() as u32); + let font = match face { + Face::Regular => &self.regular, + Face::Light => &self.light, + }; + self.cache.entry(key).or_insert_with(|| { + let (metrics, coverage) = font.rasterize(ch, size); + Glyph { metrics, coverage } + }) + } + + /// The advance width of `text`. The font is monospaced, so this is the + /// character count times one advance. + pub fn width(&self, face: Face, size: f32, text: &str) -> f32 { + let font = self.font(face); + text.chars() + .map(|ch| font.metrics(ch, size).advance_width) + .sum() + } + + /// The height of the digits above the baseline, for centring numbers + /// and symbols optically. + pub fn digit_height(&self, face: Face, size: f32) -> f32 { + let m = self.font(face).metrics('0', size); + m.height as f32 + m.ymin as f32 + } + + /// The largest size, up to `preferred`, at which `text` fits `max_width`. + pub fn fit(&self, face: Face, preferred: f32, text: &str, max_width: f32) -> f32 { + let width = self.width(face, preferred, text); + if width <= max_width || width <= 0.0 { + preferred + } else { + // Advance scales linearly with size. + (preferred * max_width / width).floor().max(1.0) + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + const BLACK: Color = Color::rgb(0, 0, 0); + const WHITE: Color = Color::rgb(255, 255, 255); + + fn canvas_bytes(w: usize, h: usize) -> Vec { + vec![0; w * h * 4] + } + + fn red_at(bytes: &[u8], w: usize, x: usize, y: usize) -> u8 { + bytes[(y * w + x) * 4 + 2] + } + + #[test] + fn parses_hex_colors() { + assert_eq!( + Color::from_hex("#5E92C6"), + Some(Color::rgb(0x5e, 0x92, 0xc6)) + ); + assert_eq!( + Color::from_hex("0b111a"), + Some(Color::rgb(0x0b, 0x11, 0x1a)) + ); + assert_eq!(Color::from_hex("#fff"), None); + assert_eq!(Color::from_hex("#gg0000"), None); + assert_eq!(Color::from_hex("#ééé"), None); + } + + #[test] + fn mixes_and_measures_luminance() { + assert_eq!(BLACK.mix(WHITE, 0.5), Color::rgb(128, 128, 128)); + assert!(WHITE.luminance() > 0.99); + assert!(BLACK.luminance() < 0.01); + } + + #[test] + fn writes_bgra() { + let mut bytes = canvas_bytes(1, 1); + Canvas::new(&mut bytes, 1, 1).fill(Color::rgb(1, 2, 3)); + assert_eq!(bytes, [3, 2, 1, 255]); + } + + #[test] + fn rounded_rect_is_solid_inside_and_soft_at_the_corners() { + let (w, h) = (40, 40); + let mut bytes = canvas_bytes(w, h); + let mut canvas = Canvas::new(&mut bytes, w, h); + canvas.fill(BLACK); + canvas.rounded_rect(10.0, 10.0, 20.0, 20.0, 6.0, WHITE); + assert_eq!(red_at(&bytes, w, 20, 20), 255, "center"); + assert_eq!(red_at(&bytes, w, 10, 20), 255, "left edge, mid-height"); + assert_eq!(red_at(&bytes, w, 9, 20), 0, "just outside"); + assert_eq!(red_at(&bytes, w, 10, 10), 0, "the corner pixel is cut away"); + let edge = red_at(&bytes, w, 11, 12); + assert!( + edge > 0 && edge < 255, + "corner arc is anti-aliased, got {edge}" + ); + } + + #[test] + fn rounded_rect_clips_to_the_canvas() { + let mut bytes = canvas_bytes(10, 10); + let mut canvas = Canvas::new(&mut bytes, 10, 10); + canvas.rounded_rect(-5.0, -5.0, 30.0, 30.0, 4.0, WHITE); + assert!(bytes.iter().all(|&b| b == 255)); + } + + #[test] + fn fonts_cover_every_symbol_the_app_shows() { + let fonts = Fonts::load(); + for face in [Face::Regular, Face::Light] { + for ch in "0123456789.,+−×÷^%=()±⌫CEeor-".chars() { + assert_ne!( + fonts.font(face).lookup_glyph_index(ch), + 0, + "{face:?} is missing {ch:?}" + ); + } + } + } + + #[test] + fn text_draws_and_fits() { + let mut fonts = Fonts::load(); + let (w, h) = (200, 60); + let mut bytes = canvas_bytes(w, h); + let mut canvas = Canvas::new(&mut bytes, w, h); + canvas.fill(BLACK); + canvas.text(&mut fonts, Face::Regular, 32.0, "1,234", (4.0, 40.0), WHITE); + assert!( + bytes.chunks(4).any(|p| p[2] == 255), + "some pixels are fully covered" + ); + + let wide = "123,456,789,012,345"; + let size = fonts.fit(Face::Light, 64.0, wide, 200.0); + assert!(size < 64.0); + assert!(fonts.width(Face::Light, size, wide) <= 200.0); + assert_eq!(fonts.fit(Face::Light, 64.0, "0", 200.0), 64.0); + } +} diff --git a/src/ui.rs b/src/ui.rs new file mode 100644 index 0000000..9badf21 --- /dev/null +++ b/src/ui.rs @@ -0,0 +1,345 @@ +//! The calculator screen: the expression line, the result, and the keypad. +//! +//! Layout is in logical pixels and multiplied by the scale when drawn, so +//! it's the same at every scale and sharp at all of them. + +use crate::render::{Canvas, Color, Face, Fonts}; + +/// The keypad, row by row, as its keys are labelled. +pub const KEYS: [[&str; 4]; 5] = [ + ["C", "±", "%", "÷"], + ["7", "8", "9", "×"], + ["4", "5", "6", "−"], + ["1", "2", "3", "+"], + ["0", ".", "⌫", "="], +]; + +/// How a key looks. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Role { + Digit, + /// C, ± and % and ⌫. + Function, + /// ÷ × − +. + Operator, + Equals, +} + +fn role(label: &str) -> Role { + match label { + "=" => Role::Equals, + "÷" | "×" | "−" | "+" => Role::Operator, + "C" | "±" | "%" | "⌫" => Role::Function, + _ => Role::Digit, + } +} + +/// The colors the screen is drawn with, worked out from a theme's +/// background, foreground and accent. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Palette { + pub background: Color, + pub foreground: Color, + pub accent: Color, + /// The expression line and the function keys' labels. + pub muted: Color, + pub key: Color, + pub key_pressed: Color, + /// The label on the accent-filled `=` key. + pub on_accent: Color, +} + +impl Palette { + pub fn new(background: Color, foreground: Color, accent: Color) -> Self { + let dark = background.luminance() < 0.5; + let key = background.mix(foreground, if dark { 0.08 } else { 0.06 }); + let key_pressed = background.mix(foreground, if dark { 0.18 } else { 0.14 }); + // Whichever of background and foreground reads better on the accent. + let on_accent = if contrast(accent, background) >= contrast(accent, foreground) { + background + } else { + foreground + }; + Self { + background, + foreground, + accent, + muted: background.mix(foreground, 0.55), + key, + key_pressed, + on_accent, + } + } +} + +impl Default for Palette { + /// Used until the theme is read, and when it can't be. + fn default() -> Self { + Palette::new( + Color::rgb(0x1a, 0x1b, 0x26), + Color::rgb(0xc0, 0xca, 0xf5), + Color::rgb(0x7a, 0xa2, 0xf7), + ) + } +} + +/// WCAG contrast ratio between two colors. +fn contrast(a: Color, b: Color) -> f32 { + let (la, lb) = (a.luminance(), b.luminance()); + (la.max(lb) + 0.05) / (la.min(lb) + 0.05) +} + +/// What the screen shows. +pub struct View<'a> { + pub expression: &'a str, + pub display: &'a str, + /// The key held down with the mouse, as (row, column). + pub pressed: Option<(usize, usize)>, +} + +// Logical sizes. +const PADDING: f32 = 12.0; +const GAP: f32 = 6.0; +const RADIUS: f32 = 4.0; +const EXPRESSION_SIZE: f32 = 18.0; +const DISPLAY_SIZE: f32 = 60.0; +const KEY_SIZE: f32 = 24.0; +/// The share of the height above the keypad. +const DISPLAY_SHARE: f32 = 0.3; + +/// Where things go for a given logical size. +struct Layout { + /// The keypad's top-left corner and one key's size. + grid: (f32, f32), + key: (f32, f32), + /// Baselines of the expression line and the result. + expression_baseline: f32, + display_baseline: f32, +} + +impl Layout { + fn new(fonts: &Fonts, width: f32, height: f32) -> Self { + let display_height = (height * DISPLAY_SHARE).max(EXPRESSION_SIZE + DISPLAY_SIZE); + let grid_top = PADDING + display_height; + let rows = KEYS.len() as f32; + let cols = KEYS[0].len() as f32; + let key_w = ((width - 2.0 * PADDING - (cols - 1.0) * GAP) / cols).max(1.0); + let key_h = ((height - grid_top - PADDING - (rows - 1.0) * GAP) / rows).max(1.0); + let display_baseline = grid_top - GAP - 4.0; + let expression_baseline = display_baseline + - fonts.digit_height(Face::Light, DISPLAY_SIZE) + - EXPRESSION_SIZE * 0.6; + Self { + grid: (PADDING, grid_top), + key: (key_w, key_h), + expression_baseline: expression_baseline.max(PADDING + EXPRESSION_SIZE), + display_baseline, + } + } + + /// A key's rectangle: x, y, width, height. + fn key_rect(&self, row: usize, col: usize) -> (f32, f32, f32, f32) { + let x = self.grid.0 + col as f32 * (self.key.0 + GAP); + let y = self.grid.1 + row as f32 * (self.key.1 + GAP); + (x, y, self.key.0, self.key.1) + } +} + +/// Draws the whole screen. `scale` is buffer pixels per logical pixel. +pub fn draw(canvas: &mut Canvas, fonts: &mut Fonts, palette: &Palette, view: &View, scale: f32) { + let width = canvas.width() as f32 / scale; + let height = canvas.height() as f32 / scale; + let layout = Layout::new(fonts, width, height); + let s = |v: f32| v * scale; + + canvas.fill(palette.background); + + // The expression line and the result, right-aligned. + let max_text = s(width - 2.0 * PADDING); + let right = s(width - PADDING); + if !view.expression.is_empty() { + let size = fonts.fit(Face::Regular, s(EXPRESSION_SIZE), view.expression, max_text); + let w = fonts.width(Face::Regular, size, view.expression); + let baseline = s(layout.expression_baseline); + canvas.text( + fonts, + Face::Regular, + size, + view.expression, + (right - w, baseline), + palette.muted, + ); + } + let size = fonts.fit(Face::Light, s(DISPLAY_SIZE), view.display, max_text); + let w = fonts.width(Face::Light, size, view.display); + let baseline = s(layout.display_baseline); + canvas.text( + fonts, + Face::Light, + size, + view.display, + (right - w, baseline), + palette.foreground, + ); + + // The keypad. + for (row, labels) in KEYS.iter().enumerate() { + for (col, &label) in labels.iter().enumerate() { + let (x, y, w, h) = layout.key_rect(row, col); + let pressed = view.pressed == Some((row, col)); + let (fill, ink) = match role(label) { + Role::Equals => ( + if pressed { + palette.accent.mix(palette.background, 0.25) + } else { + palette.accent + }, + palette.on_accent, + ), + other => { + let fill = if pressed { + palette.key_pressed + } else { + palette.key + }; + let ink = match other { + Role::Operator => palette.accent, + Role::Function => palette.muted, + _ => palette.foreground, + }; + (fill, ink) + } + }; + // Snap keys to whole pixels so their straight edges stay crisp. + let (px, py) = (s(x).round(), s(y).round()); + let (pw, ph) = (s(x + w).round() - px, s(y + h).round() - py); + canvas.rounded_rect(px, py, pw, ph, s(RADIUS), fill); + + // JetBrains Mono draws × ÷ − + small next to its digits. + let size = match role(label) { + Role::Operator | Role::Equals => s(KEY_SIZE) * 1.3, + _ => s(KEY_SIZE), + } + .min(ph * 0.5); + let tw = fonts.width(Face::Regular, size, label); + let th = fonts.digit_height(Face::Regular, size); + let tx = px + (pw - tw) / 2.0; + let baseline = py + (ph + th) / 2.0; + canvas.text( + fonts, + Face::Regular, + size, + label, + (tx, baseline.round()), + ink, + ); + } + } +} + +/// The key at logical position (x, y), as (row, column). +#[allow(dead_code)] // Mouse input uses it (ALI-2101). +pub fn hit_test(fonts: &Fonts, width: f32, height: f32, x: f32, y: f32) -> Option<(usize, usize)> { + let layout = Layout::new(fonts, width, height); + for (row, labels) in KEYS.iter().enumerate() { + for col in 0..labels.len() { + let (kx, ky, kw, kh) = layout.key_rect(row, col); + if x >= kx && x < kx + kw && y >= ky && y < ky + kh { + return Some((row, col)); + } + } + } + None +} + +#[cfg(test)] +mod tests { + use super::*; + use std::time::Instant; + + #[test] + fn hit_test_finds_the_corner_keys_and_misses_the_gaps() { + let fonts = Fonts::load(); + let (w, h) = (320.0, 480.0); + let layout = Layout::new(&fonts, w, h); + let (x, y, kw, kh) = layout.key_rect(0, 0); + assert_eq!(hit_test(&fonts, w, h, x + 1.0, y + 1.0), Some((0, 0))); + let (x, y, ..) = layout.key_rect(4, 3); + assert_eq!(hit_test(&fonts, w, h, x + 1.0, y + 1.0), Some((4, 3))); + // Between the first two keys of the first row. + assert_eq!( + hit_test(&fonts, w, h, PADDING + kw + GAP / 2.0, y - kh), + None + ); + // The display area. + assert_eq!(hit_test(&fonts, w, h, w / 2.0, PADDING), None); + } + + #[test] + fn keypad_fits_inside_the_window() { + let fonts = Fonts::load(); + for (w, h) in [(260.0, 380.0), (320.0, 480.0), (900.0, 1200.0)] { + let layout = Layout::new(&fonts, w, h); + let (x, y, kw, kh) = layout.key_rect(4, 3); + assert!( + x + kw <= w - PADDING + 0.01 && y + kh <= h - PADDING + 0.01, + "{w}x{h}" + ); + assert!(layout.expression_baseline < layout.display_baseline); + } + } + + #[test] + fn on_accent_picks_the_readable_label() { + let dark = Palette::new( + Color::rgb(0x0b, 0x11, 0x1a), + Color::rgb(0xc5, 0xce, 0xd6), + Color::rgb(0x5e, 0x92, 0xc6), + ); + assert_eq!(dark.on_accent, dark.background); + let light = Palette::new( + Color::rgb(0xfa, 0xfa, 0xfa), + Color::rgb(0x20, 0x20, 0x20), + Color::rgb(0x1d, 0x4e, 0xd8), + ); + assert_eq!(light.on_accent, light.background); + } + + /// The renderer's budget: a full frame in under 1 ms at 4K scale 2 + /// (640x960 px). Optimised builds only: `cargo test --release -- --ignored`. + #[test] + #[ignore] + fn budget_full_frame_under_1ms() { + let mut fonts = Fonts::load(); + let (w, h) = (640, 960); + let mut bytes = vec![0; w * h * 4]; + let palette = Palette::default(); + let view = View { + expression: "1,234 × 5,678 +", + display: "7,006,652", + pressed: Some((2, 1)), + }; + // Warm the glyph cache, as every frame after the first finds it. + draw( + &mut Canvas::new(&mut bytes, w, h), + &mut fonts, + &palette, + &view, + 2.0, + ); + let runs = 200; + let start = Instant::now(); + for _ in 0..runs { + draw( + &mut Canvas::new(&mut bytes, w, h), + &mut fonts, + &palette, + &view, + 2.0, + ); + } + let per_frame = start.elapsed() / runs; + println!("full frame at 640x960: {per_frame:?}"); + assert!(per_frame.as_micros() < 1000, "{per_frame:?}"); + } +} diff --git a/src/window.rs b/src/window.rs index bf2888e..1b57124 100644 --- a/src/window.rs +++ b/src/window.rs @@ -34,7 +34,9 @@ use wayland_protocols::wp::viewporter::client::{ wp_viewport::WpViewport, wp_viewporter::WpViewporter, }; +use crate::render::{Canvas, Fonts}; use crate::trace; +use crate::ui::{self, Palette, View}; /// What people see in the launcher and the title bar. "Alias Calc" is the /// product name; the window says what it does. @@ -45,14 +47,6 @@ const APP_ID: &str = "com.aliasproject.calc"; const DEFAULT_SIZE: (u32, u32) = (320, 480); const MIN_SIZE: (u32, u32) = (260, 380); -/// Stand-in until the theme lands (ALI-2103). -const BACKGROUND: [u8; 4] = argb(0x1a, 0x1b, 0x26); - -/// `wl_shm` ARGB8888 is little-endian: blue, green, red, alpha in memory. -const fn argb(r: u8, g: u8, b: u8) -> [u8; 4] { - [b, g, r, 0xff] -} - /// Fractional scales arrive as 120ths (`wp_fractional_scale_v1`). const SCALE_DENOMINATOR: u32 = 120; @@ -94,6 +88,10 @@ pub fn run() -> Result<(), Box> { window.commit(); trace::mark("window requested"); + // Parse the fonts while the compositor works on the configure. + let fonts = Fonts::load(); + trace::mark("fonts loaded"); + let (w, h) = DEFAULT_SIZE; let pool = SlotPool::new((w * h * 4) as usize, &shm)?; let mut app = App { @@ -103,6 +101,8 @@ pub fn run() -> Result<(), Box> { window, pool, buffer: None, + fonts, + palette: Palette::default(), size: DEFAULT_SIZE, scaling, configured: false, @@ -166,6 +166,8 @@ struct App { window: Window, pool: SlotPool, buffer: Option, + fonts: Fonts, + palette: Palette, /// Logical size, in surface coordinates. size: (u32, u32), scaling: Scaling, @@ -219,7 +221,14 @@ impl App { return; }; - canvas.as_chunks_mut::<4>().0.fill(BACKGROUND); + let scale = pw as f32 / self.size.0 as f32; + let view = View { + expression: "", + display: "0", + pressed: None, + }; + let mut canvas = Canvas::new(canvas, pw as usize, ph as usize); + ui::draw(&mut canvas, &mut self.fonts, &self.palette, &view, scale); let surface = self.window.wl_surface(); match &self.scaling { From f1c09985dd298a9ce94754d628fd5120a233da38 Mon Sep 17 00:00:00 2001 From: Michael Aguiar Date: Wed, 25 Nov 2026 12:06:52 -0700 Subject: [PATCH 05/50] Ignore .claude/ and drop the agent worktree committed by mistake ALI-2099 --- .claude/worktrees/agent-a2e016efd9728fd93 | 1 - .gitignore | 1 + 2 files changed, 1 insertion(+), 1 deletion(-) delete mode 160000 .claude/worktrees/agent-a2e016efd9728fd93 diff --git a/.claude/worktrees/agent-a2e016efd9728fd93 b/.claude/worktrees/agent-a2e016efd9728fd93 deleted file mode 160000 index b9889b7..0000000 --- a/.claude/worktrees/agent-a2e016efd9728fd93 +++ /dev/null @@ -1 +0,0 @@ -Subproject commit b9889b75ad02a580fd559130cefe388bbfce0e73 diff --git a/.gitignore b/.gitignore index df611ec..f8d6143 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,3 @@ /target __pycache__/ +/.claude/ From 4b5264d1bcdb0cf86dcf3a68e5cb51f236a5028a Mon Sep 17 00:00:00 2001 From: Michael Aguiar Date: Wed, 25 Nov 2026 12:10:08 -0700 Subject: [PATCH 06/50] Wire the keypad: keyboard, mouse and Backspace repeat Keys map by keysym, so the layout is followed and the numpad works with NumLock on or off. Ctrl, Alt and Super chords are left alone (copy and paste come in ALI-2102). A button lights while its keyboard key is held, and while the mouse holds it; a click counts only if it ends on the button it began on. Backspace repeats at the compositor's rate, timed by the poll timeout, which is set only while it's held, so idle still never wakes. The pointer gets the default cursor through cursor-shape-v1. The engine (ALI-2100) is merged in; the display shows its expression and result. ALI-2101 --- Cargo.lock | 37 ++++++ Cargo.toml | 2 +- src/engine.rs | 3 + src/input.rs | 77 +++++++++++ src/main.rs | 1 + src/trace.rs | 5 + src/ui.rs | 66 ++++++++- src/window.rs | 360 ++++++++++++++++++++++++++++++++++++++++++++++++-- 8 files changed, 540 insertions(+), 11 deletions(-) create mode 100644 src/input.rs diff --git a/Cargo.lock b/Cargo.lock index 7807f73..1ffcf47 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -61,6 +61,26 @@ version = "3.20.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "87a0cf66fd1eb2fb7b822cb78370d82303750809bc6ba855f3f58e517d3238db" +[[package]] +name = "bytemuck" +version = "1.25.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95832e849adfb21180ccb6826a99da14e5d266ae5c2e668e1602cf234f153797" +dependencies = [ + "bytemuck_derive", +] + +[[package]] +name = "bytemuck_derive" +version = "1.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6a1f896587b6f2c069c73d2f0913e2d590c3990285cd2f0b6aa02b786b4c679c" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + [[package]] name = "bytes" version = "1.12.2" @@ -453,9 +473,11 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "74dc9ee14b0fdcb535f9556141bacac070c994a977d2240ee455d7438a617f00" dependencies = [ "bitflags", + "bytemuck", "cursor-icon", "log", "memmap2", + "pkg-config", "rustix", "thiserror", "wayland-client", @@ -466,6 +488,7 @@ dependencies = [ "wayland-protocols-misc", "wayland-protocols-wlr", "wayland-scanner", + "xkbcommon", "xkeysym", ] @@ -769,11 +792,25 @@ version = "0.3.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "163b33ed8786455e2fa5d72f554057ce3f3182425434f756cd39c99839d88e23" +[[package]] +name = "xkbcommon" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8d66ca9352cbd4eecbbc40871d8a11b4ac8107cfc528a6e14d7c19c69d0e1ac9" +dependencies = [ + "libc", + "memmap2", + "xkeysym", +] + [[package]] name = "xkeysym" version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b9cc00251562a284751c9973bace760d86c0276c471b4be569fe6b068ee97a56" +dependencies = [ + "bytemuck", +] [[package]] name = "zerocopy" diff --git a/Cargo.toml b/Cargo.toml index 98ee16a..f0d626e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -10,7 +10,7 @@ publish = false fontdue = { version = "0.9", default-features = false, features = ["std", "simd"] } rust_decimal = { version = "1.43", default-features = false, features = ["std", "maths"] } rustix = { version = "1", default-features = false, features = ["std", "event"] } -smithay-client-toolkit = { version = "0.21", default-features = false } +smithay-client-toolkit = { version = "0.21", default-features = false, features = ["xkbcommon"] } wayland-protocols = { version = "0.32", features = ["client", "staging"] } [profile.release] diff --git a/src/engine.rs b/src/engine.rs index f623c91..3d49344 100644 --- a/src/engine.rs +++ b/src/engine.rs @@ -371,6 +371,7 @@ impl Calc { } /// Whether the display shows an error. + #[allow(dead_code)] // Copy and paste use it (ALI-2102). pub fn is_error(&self) -> bool { self.errored } @@ -379,6 +380,7 @@ impl Calc { /// around it, thousands separators in groups of three (`1,234,567.89`), /// a decimal comma (`1,5`) and the `−` this calculator shows. Anything /// else is ignored, and the return value says whether it was taken. + #[allow(dead_code)] // Copy and paste use it (ALI-2102). pub fn paste(&mut self, text: &str) -> bool { let mut text: String = text .trim() @@ -624,6 +626,7 @@ fn significant_digits(entry: &str) -> usize { } /// `1,234` or `-1,234,567.89`: commas exactly every three digits. +#[allow(dead_code)] // Only `paste` uses it so far. fn is_grouped(text: &str) -> bool { let body = text.strip_prefix('-').unwrap_or(text); let whole = body.split_once('.').map_or(body, |(w, _)| w); diff --git a/src/input.rs b/src/input.rs new file mode 100644 index 0000000..9a70b22 --- /dev/null +++ b/src/input.rs @@ -0,0 +1,77 @@ +//! Keyboard mapping: which calculator key a keysym presses. +//! +//! Keysyms, not text, so the mapping follows the keyboard layout and the +//! numpad works with NumLock on (KP_1) or off (KP_End). + +use smithay_client_toolkit::seat::keyboard::Keysym; + +use crate::engine::{Key, Op}; + +/// The calculator key for a keysym pressed with no Ctrl, Alt or Super. +pub fn key_for(sym: Keysym) -> Option { + let key = match sym { + Keysym::_0 | Keysym::KP_0 | Keysym::KP_Insert => Key::Digit(0), + Keysym::_1 | Keysym::KP_1 | Keysym::KP_End => Key::Digit(1), + Keysym::_2 | Keysym::KP_2 | Keysym::KP_Down => Key::Digit(2), + Keysym::_3 | Keysym::KP_3 | Keysym::KP_Next => Key::Digit(3), + Keysym::_4 | Keysym::KP_4 | Keysym::KP_Left => Key::Digit(4), + Keysym::_5 | Keysym::KP_5 | Keysym::KP_Begin => Key::Digit(5), + Keysym::_6 | Keysym::KP_6 | Keysym::KP_Right => Key::Digit(6), + Keysym::_7 | Keysym::KP_7 | Keysym::KP_Home => Key::Digit(7), + Keysym::_8 | Keysym::KP_8 | Keysym::KP_Up => Key::Digit(8), + Keysym::_9 | Keysym::KP_9 | Keysym::KP_Prior => Key::Digit(9), + Keysym::period | Keysym::KP_Decimal | Keysym::KP_Delete => Key::Point, + Keysym::plus | Keysym::KP_Add => Key::Op(Op::Add), + Keysym::minus | Keysym::KP_Subtract => Key::Op(Op::Sub), + Keysym::asterisk | Keysym::KP_Multiply | Keysym::x | Keysym::X => Key::Op(Op::Mul), + Keysym::slash | Keysym::KP_Divide => Key::Op(Op::Div), + Keysym::asciicircum => Key::Op(Op::Pow), + Keysym::percent => Key::Percent, + Keysym::Return | Keysym::KP_Enter | Keysym::equal | Keysym::KP_Equal => Key::Equals, + Keysym::BackSpace => Key::Backspace, + Keysym::c | Keysym::C | Keysym::Escape => Key::Clear, + Keysym::s | Keysym::S => Key::Sign, + _ => return None, + }; + Some(key) +} + +/// Keys that repeat while held. Only Backspace: repeating a digit or an +/// operator by holding it is never what anyone wants on a calculator. +pub fn repeats(key: Key) -> bool { + key == Key::Backspace +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn numpad_works_with_and_without_numlock() { + for (on, off, digit) in [ + (Keysym::KP_0, Keysym::KP_Insert, 0), + (Keysym::KP_1, Keysym::KP_End, 1), + (Keysym::KP_5, Keysym::KP_Begin, 5), + (Keysym::KP_9, Keysym::KP_Prior, 9), + ] { + assert_eq!(key_for(on), Some(Key::Digit(digit))); + assert_eq!(key_for(off), Some(Key::Digit(digit))); + } + assert_eq!(key_for(Keysym::KP_Delete), Some(Key::Point)); + assert_eq!(key_for(Keysym::KP_Enter), Some(Key::Equals)); + } + + #[test] + fn maps_the_documented_keys() { + assert_eq!(key_for(Keysym::x), Some(Key::Op(Op::Mul))); + assert_eq!(key_for(Keysym::asterisk), Some(Key::Op(Op::Mul))); + assert_eq!(key_for(Keysym::asciicircum), Some(Key::Op(Op::Pow))); + assert_eq!(key_for(Keysym::percent), Some(Key::Percent)); + assert_eq!(key_for(Keysym::Escape), Some(Key::Clear)); + assert_eq!(key_for(Keysym::C), Some(Key::Clear)); + assert_eq!(key_for(Keysym::s), Some(Key::Sign)); + assert_eq!(key_for(Keysym::a), None); + assert!(repeats(Key::Backspace)); + assert!(!repeats(Key::Digit(1))); + } +} diff --git a/src/main.rs b/src/main.rs index 00247fd..771e7bb 100644 --- a/src/main.rs +++ b/src/main.rs @@ -4,6 +4,7 @@ //! CPU into a shared-memory buffer and sleeps until something happens. mod engine; +mod input; mod render; mod trace; mod ui; diff --git a/src/trace.rs b/src/trace.rs index 452aa7d..3aade7a 100644 --- a/src/trace.rs +++ b/src/trace.rs @@ -13,6 +13,11 @@ pub fn start() { START.get_or_init(|| std::env::var_os("ALIAS_CALC_TRACE").map(|_| Instant::now())); } +/// Whether `ALIAS_CALC_TRACE` is set, so callers can skip formatting. +pub fn on() -> bool { + matches!(START.get(), Some(Some(_))) +} + /// Prints `what` with the time since `start`, if tracing is on. pub fn mark(what: &str) { if let Some(Some(start)) = START.get() { diff --git a/src/ui.rs b/src/ui.rs index 9badf21..656e27f 100644 --- a/src/ui.rs +++ b/src/ui.rs @@ -3,6 +3,7 @@ //! Layout is in logical pixels and multiplied by the scale when drawn, so //! it's the same at every scale and sharp at all of them. +use crate::engine::{Key, Op}; use crate::render::{Canvas, Color, Face, Fonts}; /// The keypad, row by row, as its keys are labelled. @@ -14,6 +15,45 @@ pub const KEYS: [[&str; 4]; 5] = [ ["0", ".", "⌫", "="], ]; +/// The calculator key each keypad button presses, in the same order as +/// [`KEYS`]. +const ACTIONS: [[Key; 4]; 5] = [ + [Key::Clear, Key::Sign, Key::Percent, Key::Op(Op::Div)], + [ + Key::Digit(7), + Key::Digit(8), + Key::Digit(9), + Key::Op(Op::Mul), + ], + [ + Key::Digit(4), + Key::Digit(5), + Key::Digit(6), + Key::Op(Op::Sub), + ], + [ + Key::Digit(1), + Key::Digit(2), + Key::Digit(3), + Key::Op(Op::Add), + ], + [Key::Digit(0), Key::Point, Key::Backspace, Key::Equals], +]; + +/// What the button at (row, column) presses. +pub fn action(cell: (usize, usize)) -> Key { + ACTIONS[cell.0][cell.1] +} + +/// The button for a key, to light it up while its keyboard key is held. +/// `^` has no button. +pub fn cell_of(key: Key) -> Option<(usize, usize)> { + ACTIONS + .iter() + .enumerate() + .find_map(|(row, keys)| keys.iter().position(|&k| k == key).map(|col| (row, col))) +} + /// How a key looks. #[derive(Clone, Copy, Debug, PartialEq, Eq)] enum Role { @@ -238,7 +278,6 @@ pub fn draw(canvas: &mut Canvas, fonts: &mut Fonts, palette: &Palette, view: &Vi } /// The key at logical position (x, y), as (row, column). -#[allow(dead_code)] // Mouse input uses it (ALI-2101). pub fn hit_test(fonts: &Fonts, width: f32, height: f32, x: f32, y: f32) -> Option<(usize, usize)> { let layout = Layout::new(fonts, width, height); for (row, labels) in KEYS.iter().enumerate() { @@ -275,6 +314,31 @@ mod tests { assert_eq!(hit_test(&fonts, w, h, w / 2.0, PADDING), None); } + #[test] + fn every_button_presses_the_key_its_label_says() { + for (row, labels) in KEYS.iter().enumerate() { + for (col, label) in labels.iter().enumerate() { + let key = action((row, col)); + assert_eq!(cell_of(key), Some((row, col)), "{label}"); + let expected = match *label { + "C" => Key::Clear, + "±" => Key::Sign, + "%" => Key::Percent, + "÷" => Key::Op(Op::Div), + "×" => Key::Op(Op::Mul), + "−" => Key::Op(Op::Sub), + "+" => Key::Op(Op::Add), + "." => Key::Point, + "⌫" => Key::Backspace, + "=" => Key::Equals, + digit => Key::Digit(digit.parse().unwrap()), + }; + assert_eq!(key, expected, "{label}"); + } + } + assert_eq!(cell_of(Key::Op(Op::Pow)), None); + } + #[test] fn keypad_fits_inside_the_window() { let fonts = Fonts::load(); diff --git a/src/window.rs b/src/window.rs index 1b57124..8024a8c 100644 --- a/src/window.rs +++ b/src/window.rs @@ -7,17 +7,26 @@ //! idle window costs no CPU at all. use std::error::Error; +use std::time::{Duration, Instant}; -use rustix::event::{PollFd, PollFlags, poll}; +use rustix::event::{PollFd, PollFlags, Timespec, poll}; use rustix::io::Errno; use smithay_client_toolkit::compositor::{CompositorHandler, CompositorState}; use smithay_client_toolkit::dispatch2::Dispatch2; use smithay_client_toolkit::output::{OutputHandler, OutputState}; use smithay_client_toolkit::reexports::client::backend::WaylandError; use smithay_client_toolkit::reexports::client::globals::registry_queue_init; -use smithay_client_toolkit::reexports::client::protocol::{wl_output, wl_shm, wl_surface}; +use smithay_client_toolkit::reexports::client::protocol::{ + wl_keyboard, wl_output, wl_pointer, wl_seat, wl_shm, wl_surface, +}; use smithay_client_toolkit::reexports::client::{Connection, QueueHandle}; use smithay_client_toolkit::registry::{ProvidesRegistryState, RegistryState}; +use smithay_client_toolkit::seat::keyboard::{ + KeyEvent, KeyboardHandler, Keysym, Modifiers, RawModifiers, RepeatInfo, +}; +use smithay_client_toolkit::seat::pointer::cursor_shape::CursorShapeManager; +use smithay_client_toolkit::seat::pointer::{PointerEvent, PointerEventKind, PointerHandler}; +use smithay_client_toolkit::seat::{Capability, SeatHandler, SeatState}; use smithay_client_toolkit::shell::WaylandSurface; use smithay_client_toolkit::shell::xdg::XdgShell; use smithay_client_toolkit::shell::xdg::window::{ @@ -26,6 +35,9 @@ use smithay_client_toolkit::shell::xdg::window::{ use smithay_client_toolkit::shm::slot::{Buffer, SlotPool}; use smithay_client_toolkit::shm::{Shm, ShmHandler}; use smithay_client_toolkit::{delegate_dispatch2, delegate_registry, registry_handlers}; +use wayland_protocols::wp::cursor_shape::v1::client::wp_cursor_shape_device_v1::{ + Shape, WpCursorShapeDeviceV1, +}; use wayland_protocols::wp::fractional_scale::v1::client::{ wp_fractional_scale_manager_v1::WpFractionalScaleManagerV1, wp_fractional_scale_v1::{self, WpFractionalScaleV1}, @@ -34,6 +46,8 @@ use wayland_protocols::wp::viewporter::client::{ wp_viewport::WpViewport, wp_viewporter::WpViewporter, }; +use crate::engine::{Calc, Key}; +use crate::input; use crate::render::{Canvas, Fonts}; use crate::trace; use crate::ui::{self, Palette, View}; @@ -47,6 +61,13 @@ const APP_ID: &str = "com.aliasproject.calc"; const DEFAULT_SIZE: (u32, u32) = (320, 480); const MIN_SIZE: (u32, u32) = (260, 380); +/// Key repeat when the compositor doesn't say (it always does on Hyprland). +const DEFAULT_REPEAT: (Duration, Duration) = + (Duration::from_millis(600), Duration::from_millis(40)); + +/// The left mouse button (linux/input-event-codes.h BTN_LEFT). +const BTN_LEFT: u32 = 0x110; + /// Fractional scales arrive as 120ths (`wp_fractional_scale_v1`). const SCALE_DENOMINATOR: u32 = 120; @@ -65,6 +86,7 @@ pub fn run() -> Result<(), Box> { let fractional_manager: Option = globals.bind(&qh, 1..=1, NoEvents).ok(); let viewporter: Option = globals.bind(&qh, 1..=1, NoEvents).ok(); + let cursor_shape = CursorShapeManager::bind(&globals, &qh).ok(); let surface = compositor.create_surface(&qh); let scaling = match (fractional_manager, viewporter) { @@ -97,6 +119,18 @@ pub fn run() -> Result<(), Box> { let mut app = App { registry: RegistryState::new(&globals), outputs: OutputState::new(&globals, &qh), + seats: SeatState::new(&globals, &qh), + keyboard: None, + pointer: None, + cursor_shape, + cursor: None, + modifiers: Modifiers::default(), + calc: Calc::new(), + mouse_down: None, + mouse_at: (0.0, 0.0), + key_down: None, + repeat_rate: Some(DEFAULT_REPEAT), + repeat: None, shm, window, pool, @@ -138,13 +172,31 @@ fn event_loop(queue: &mut Queue, app: &mut App) -> Result<(), Box> { }; let fd = guard.connection_fd(); let mut fds = [PollFd::new(&fd, PollFlags::IN)]; - match poll(&mut fds, None) { + // Only a held Backspace sets a timeout; otherwise sleep until the + // compositor sends something. + let timeout = app.repeat.as_ref().map(|r| { + let wait = r.next.saturating_duration_since(Instant::now()); + Timespec { + tv_sec: wait.as_secs() as _, + tv_nsec: wait.subsec_nanos() as _, + } + }); + match poll(&mut fds, timeout.as_ref()) { + Ok(0) => { + drop(guard); + app.repeat_tick(); + continue; + } Ok(_) => {} Err(Errno::INTR) => continue, Err(err) => return Err(err.into()), } match guard.read() { - Ok(n) => trace::mark(&format!("woke: {n} event(s)")), + Ok(n) => { + if trace::on() { + trace::mark(&format!("woke: {n} event(s)")); + } + } Err(WaylandError::Io(err)) if err.kind() == std::io::ErrorKind::WouldBlock => {} Err(err) => return Err(err.into()), } @@ -168,6 +220,22 @@ struct App { buffer: Option, fonts: Fonts, palette: Palette, + seats: SeatState, + keyboard: Option, + pointer: Option, + cursor_shape: Option, + cursor: Option, + modifiers: Modifiers, + calc: Calc, + /// The button the left mouse button went down on. + mouse_down: Option<(usize, usize)>, + /// The pointer's last logical position. + mouse_at: (f64, f64), + /// The keyboard key held down (its raw code) and the button it lights. + key_down: Option<(u32, Option<(usize, usize)>)>, + /// Repeat delay and interval, or None when the compositor disables repeat. + repeat_rate: Option<(Duration, Duration)>, + repeat: Option, /// Logical size, in surface coordinates. size: (u32, u32), scaling: Scaling, @@ -177,7 +245,41 @@ struct App { exit: bool, } +/// A key being repeated while held. +struct Repeat { + raw_code: u32, + key: Key, + next: Instant, +} + impl App { + fn press(&mut self, key: Key) { + self.calc.press(key); + self.dirty = true; + } + + fn repeat_tick(&mut self) { + let Some(repeat) = &mut self.repeat else { + return; + }; + let key = repeat.key; + let interval = self.repeat_rate.map_or(DEFAULT_REPEAT.1, |r| r.1); + repeat.next += interval; + // After a stall (a suspended machine), don't fire a burst. + let now = Instant::now(); + if repeat.next < now { + repeat.next = now + interval; + } + self.press(key); + } + + /// The button under the pointer, if any. + fn button_under_pointer(&self) -> Option<(usize, usize)> { + let (w, h) = self.size; + let (x, y) = self.mouse_at; + ui::hit_test(&self.fonts, w as f32, h as f32, x as f32, y as f32) + } + /// The buffer's size in pixels for the current logical size and scale. fn pixel_size(&self) -> (u32, u32) { let (w, h) = self.size; @@ -191,8 +293,20 @@ impl App { } } + /// The button drawn pressed: the mouse's, while the pointer is still on + /// it, else the one whose keyboard key is held. + fn pressed_button(&self) -> Option<(usize, usize)> { + let mouse = self + .mouse_down + .filter(|&cell| self.button_under_pointer() == Some(cell)); + mouse.or(self.key_down.and_then(|(_, cell)| cell)) + } + fn draw(&mut self) { self.dirty = false; + let expression = self.calc.expression(); + let display = self.calc.display(); + let pressed = self.pressed_button(); let (pw, ph) = self.pixel_size(); let stride = pw as i32 * 4; @@ -223,9 +337,9 @@ impl App { let scale = pw as f32 / self.size.0 as f32; let view = View { - expression: "", - display: "0", - pressed: None, + expression: &expression, + display: &display, + pressed, }; let mut canvas = Canvas::new(canvas, pw as usize, ph as usize); ui::draw(&mut canvas, &mut self.fonts, &self.palette, &view, scale); @@ -243,7 +357,9 @@ impl App { return; } self.window.commit(); - trace::mark(&format!("frame committed ({pw}x{ph} px)")); + if trace::on() { + trace::mark(&format!("frame committed ({pw}x{ph} px)")); + } } } @@ -331,6 +447,232 @@ impl WindowHandler for App { } } +impl SeatHandler for App { + fn seat_state(&mut self) -> &mut SeatState { + &mut self.seats + } + + fn new_seat(&mut self, _: &Connection, _: &QueueHandle, _: wl_seat::WlSeat) {} + + fn new_capability( + &mut self, + _: &Connection, + qh: &QueueHandle, + seat: wl_seat::WlSeat, + capability: Capability, + ) { + if capability == Capability::Keyboard && self.keyboard.is_none() { + match self.seats.get_keyboard(qh, &seat, None) { + Ok(keyboard) => self.keyboard = Some(keyboard), + Err(err) => eprintln!("alias-calc: no keyboard: {err}"), + } + } + if capability == Capability::Pointer && self.pointer.is_none() { + match self.seats.get_pointer(qh, &seat) { + Ok(pointer) => { + self.cursor = self + .cursor_shape + .as_ref() + .map(|m| m.get_shape_device(&pointer, qh)); + self.pointer = Some(pointer); + } + Err(err) => eprintln!("alias-calc: no pointer: {err}"), + } + } + } + + fn remove_capability( + &mut self, + _: &Connection, + _: &QueueHandle, + _: wl_seat::WlSeat, + capability: Capability, + ) { + if capability == Capability::Keyboard + && let Some(keyboard) = self.keyboard.take() + { + keyboard.release(); + self.key_down = None; + self.repeat = None; + } + if capability == Capability::Pointer + && let Some(pointer) = self.pointer.take() + { + if let Some(cursor) = self.cursor.take() { + cursor.destroy(); + } + pointer.release(); + self.mouse_down = None; + } + } + + fn remove_seat(&mut self, _: &Connection, _: &QueueHandle, _: wl_seat::WlSeat) {} +} + +impl KeyboardHandler for App { + fn enter( + &mut self, + _: &Connection, + _: &QueueHandle, + _: &wl_keyboard::WlKeyboard, + _: &wl_surface::WlSurface, + _: u32, + _: &[u32], + _: &[Keysym], + ) { + } + + fn leave( + &mut self, + _: &Connection, + _: &QueueHandle, + _: &wl_keyboard::WlKeyboard, + _: &wl_surface::WlSurface, + _: u32, + ) { + // Keys released elsewhere never send their release here. + if self.key_down.take().is_some_and(|(_, cell)| cell.is_some()) { + self.dirty = true; + } + self.repeat = None; + } + + fn press_key( + &mut self, + _: &Connection, + _: &QueueHandle, + _: &wl_keyboard::WlKeyboard, + _: u32, + event: KeyEvent, + ) { + // Ctrl, Alt and Super chords belong to the compositor and to copy + // and paste (ALI-2102), never to the keypad. + if self.modifiers.ctrl || self.modifiers.alt || self.modifiers.logo { + return; + } + let Some(key) = input::key_for(event.keysym) else { + return; + }; + self.key_down = Some((event.raw_code, ui::cell_of(key))); + self.repeat = match self.repeat_rate { + Some((delay, _)) if input::repeats(key) => Some(Repeat { + raw_code: event.raw_code, + key, + next: Instant::now() + delay, + }), + _ => None, + }; + self.press(key); + } + + fn repeat_key( + &mut self, + _: &Connection, + _: &QueueHandle, + _: &wl_keyboard::WlKeyboard, + _: u32, + _: KeyEvent, + ) { + // Only SCTK's calloop integration calls this; the event loop repeats. + } + + fn release_key( + &mut self, + _: &Connection, + _: &QueueHandle, + _: &wl_keyboard::WlKeyboard, + _: u32, + event: KeyEvent, + ) { + if self.key_down.is_some_and(|(raw, _)| raw == event.raw_code) { + self.key_down = None; + self.dirty = true; + } + if self + .repeat + .as_ref() + .is_some_and(|r| r.raw_code == event.raw_code) + { + self.repeat = None; + } + } + + fn update_modifiers( + &mut self, + _: &Connection, + _: &QueueHandle, + _: &wl_keyboard::WlKeyboard, + _: u32, + modifiers: Modifiers, + _: RawModifiers, + _: u32, + ) { + self.modifiers = modifiers; + } + + fn update_repeat_info( + &mut self, + _: &Connection, + _: &QueueHandle, + _: &wl_keyboard::WlKeyboard, + info: RepeatInfo, + ) { + self.repeat_rate = match info { + RepeatInfo::Repeat { rate, delay } => Some(( + Duration::from_millis(delay.into()), + Duration::from_secs(1) / rate.get(), + )), + RepeatInfo::Disable => None, + }; + } +} + +impl PointerHandler for App { + fn pointer_frame( + &mut self, + _: &Connection, + _: &QueueHandle, + _: &wl_pointer::WlPointer, + events: &[PointerEvent], + ) { + for event in events { + if &event.surface != self.window.wl_surface() { + continue; + } + let before = self.pressed_button(); + self.mouse_at = event.position; + match event.kind { + PointerEventKind::Enter { serial } => { + if let Some(cursor) = &self.cursor { + cursor.set_shape(serial, Shape::Default); + } + } + PointerEventKind::Leave { .. } => {} + PointerEventKind::Press { + button: BTN_LEFT, .. + } => { + self.mouse_down = self.button_under_pointer(); + } + PointerEventKind::Release { + button: BTN_LEFT, .. + } => { + // A click counts only if it ends on the button it began on. + if let Some(cell) = self.mouse_down.take() + && self.button_under_pointer() == Some(cell) + { + self.press(ui::action(cell)); + } + } + _ => {} + } + let after = self.pressed_button(); + if before != after { + self.dirty = true; + } + } + } +} + impl ShmHandler for App { fn shm_state(&mut self) -> &mut Shm { &mut self.shm @@ -341,7 +683,7 @@ impl ProvidesRegistryState for App { fn registry(&mut self) -> &mut RegistryState { &mut self.registry } - registry_handlers![OutputState]; + registry_handlers![OutputState, SeatState]; } /// User data for objects that send no events we use. From e7e362c436b6794ad14c66a8129e2826c2839b66 Mon Sep 17 00:00:00 2001 From: Michael Aguiar Date: Wed, 25 Nov 2026 12:12:32 -0700 Subject: [PATCH 07/50] Follow the live aliasOS theme Reads background, foreground and accent (falling back to color4, then the foreground) from current/theme/colors.toml with a small line parser, and works the key, pressed, muted and on-accent colors out from them. An inotify watch on current/ sees aliasos-theme-apply's mv of theme (the event aliasos-theme-changed waits on) and Omarchy's theme symlink swap; the window redraws once with the new colors. The watch's fd sits in the same poll as the Wayland socket, so it adds no wakeups. Order: $XDG_STATE_HOME/aliasos/current, then $XDG_CONFIG_HOME/omarchy/current, then the built-in dark palette. ALI-2103 --- Cargo.toml | 2 +- src/main.rs | 1 + src/render.rs | 1 - src/theme.rs | 226 ++++++++++++++++++++++++++++++++++++++++++++++++++ src/window.rs | 44 +++++++++- 5 files changed, 268 insertions(+), 6 deletions(-) create mode 100644 src/theme.rs diff --git a/Cargo.toml b/Cargo.toml index f0d626e..579f614 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -9,7 +9,7 @@ publish = false [dependencies] fontdue = { version = "0.9", default-features = false, features = ["std", "simd"] } rust_decimal = { version = "1.43", default-features = false, features = ["std", "maths"] } -rustix = { version = "1", default-features = false, features = ["std", "event"] } +rustix = { version = "1", default-features = false, features = ["std", "event", "fs"] } smithay-client-toolkit = { version = "0.21", default-features = false, features = ["xkbcommon"] } wayland-protocols = { version = "0.32", features = ["client", "staging"] } diff --git a/src/main.rs b/src/main.rs index 771e7bb..4c5057e 100644 --- a/src/main.rs +++ b/src/main.rs @@ -6,6 +6,7 @@ mod engine; mod input; mod render; +mod theme; mod trace; mod ui; mod window; diff --git a/src/render.rs b/src/render.rs index 71c5321..243d88f 100644 --- a/src/render.rs +++ b/src/render.rs @@ -22,7 +22,6 @@ impl Color { } /// Parses `#rrggbb` (the `#` is optional). - #[allow(dead_code)] // The theme reader uses it (ALI-2103). pub fn from_hex(hex: &str) -> Option { let hex = hex.trim().trim_start_matches('#'); if hex.len() != 6 || !hex.is_ascii() { diff --git a/src/theme.rs b/src/theme.rs new file mode 100644 index 0000000..00ddfc4 --- /dev/null +++ b/src/theme.rs @@ -0,0 +1,226 @@ +//! The live aliasOS theme: colors from `current/theme/colors.toml`, re-read +//! whenever the theme changes. +//! +//! `aliasos-theme-apply` swaps the theme directory in with `mv`, which fires +//! `IN_MOVED_TO` for `theme` on its parent (the same event +//! `aliasos-theme-changed` waits on). The theme directory itself briefly +//! stops existing during the swap, so the parent is what's watched. Omarchy +//! swaps a `theme` symlink (`IN_CREATE`) in `~/.config/omarchy/current`; the +//! same watch covers it. + +use std::ffi::OsStr; +use std::os::fd::{AsFd, OwnedFd}; +use std::os::unix::ffi::OsStrExt; +use std::path::{Path, PathBuf}; + +use rustix::fs::inotify::{self, CreateFlags, ReadFlags, WatchFlags}; +use rustix::io::Errno; + +use crate::render::Color; +use crate::ui::Palette; + +/// Where a theme lives: the `current` directory that holds `theme/`. +fn sources() -> Vec { + let Some(home) = std::env::var_os("HOME").map(PathBuf::from) else { + return Vec::new(); + }; + let state = std::env::var_os("XDG_STATE_HOME") + .map(PathBuf::from) + .filter(|p| p.is_absolute()) + .unwrap_or_else(|| home.join(".local/state")); + let config = std::env::var_os("XDG_CONFIG_HOME") + .map(PathBuf::from) + .filter(|p| p.is_absolute()) + .unwrap_or_else(|| home.join(".config")); + vec![ + state.join("aliasos/current"), + config.join("omarchy/current"), + ] +} + +/// The first theme source that exists: aliasOS, then Omarchy. +fn current_dir() -> Option { + sources().into_iter().find(|dir| dir.is_dir()) +} + +/// Reads the palette from the current theme, or the built-in one when +/// there's no theme or it can't be read. +pub fn load() -> Palette { + current_dir() + .and_then(|dir| std::fs::read_to_string(dir.join("theme/colors.toml")).ok()) + .and_then(|text| palette_from(&text)) + .unwrap_or_default() +} + +/// The palette a `colors.toml` describes. It needs `background` and +/// `foreground`; `accent` falls back to `color4` (blue), then to the +/// foreground. +fn palette_from(text: &str) -> Option { + let mut background = None; + let mut foreground = None; + let mut accent = None; + let mut blue = None; + for line in text.lines() { + let Some((key, value)) = line.split_once('=') else { + continue; + }; + let Some(color) = color_value(value) else { + continue; + }; + match key.trim() { + "background" => background = Some(color), + "foreground" => foreground = Some(color), + "accent" => accent = Some(color), + "color4" => blue = Some(color), + _ => {} + } + } + let foreground = foreground?; + Some(Palette::new( + background?, + foreground, + accent.or(blue).unwrap_or(foreground), + )) +} + +/// `"#rrggbb"`, with optional quotes and a trailing `# comment`. +fn color_value(value: &str) -> Option { + let value = value.trim(); + let value = match value.strip_prefix('"') { + // A quoted string ends at its closing quote; a comment may follow. + Some(rest) => &rest[..rest.find('"')?], + None => value.split_whitespace().next()?, + }; + Color::from_hex(value) +} + +/// Watches for theme changes. Its fd goes in the event loop's poll set. +pub struct Watch { + fd: OwnedFd, +} + +impl Watch { + /// Starts watching the theme source's `current` directory. `None` when + /// there's no theme to follow or inotify isn't available. + pub fn new() -> Option { + let dir = current_dir()?; + let fd = inotify::init(CreateFlags::CLOEXEC | CreateFlags::NONBLOCK).ok()?; + let flags = WatchFlags::MOVED_TO | WatchFlags::CREATE | WatchFlags::CLOSE_WRITE; + inotify::add_watch(&fd, &dir, flags).ok()?; + Some(Self { fd }) + } + + pub fn fd(&self) -> impl AsFd + '_ { + self.fd.as_fd() + } + + /// Drains the pending events and says whether any touched the theme. + /// Call when the fd is readable. + pub fn changed(&self) -> bool { + let mut buf = [std::mem::MaybeUninit::uninit(); 4096]; + let mut reader = inotify::Reader::new(&self.fd, &mut buf); + let mut changed = false; + loop { + match reader.next() { + Ok(event) => { + if event.events().contains(ReadFlags::QUEUE_OVERFLOW) { + changed = true; + } + if let Some(name) = event.file_name() + && is_theme_entry(OsStr::from_bytes(name.to_bytes())) + { + changed = true; + } + } + Err(Errno::AGAIN | Errno::INTR) => return changed, + Err(_) => return changed, + } + } + } +} + +/// The entries in `current/` whose change means a new theme. +fn is_theme_entry(name: &OsStr) -> bool { + Path::new(name) == Path::new("theme") +} + +#[cfg(test)] +mod tests { + use super::*; + + const TARNISHED: &str = r##" +# Tarnished: a Dark Souls theme. +accent = "#5E92C6" +cursor = "#A9C2D6" +foreground = "#C5CED6" +background = "#0B111A" +color4 = "#5482B4" +"##; + + #[test] + fn reads_an_aliasos_theme() { + let palette = palette_from(TARNISHED).unwrap(); + assert_eq!(palette.background, Color::rgb(0x0b, 0x11, 0x1a)); + assert_eq!(palette.foreground, Color::rgb(0xc5, 0xce, 0xd6)); + assert_eq!(palette.accent, Color::rgb(0x5e, 0x92, 0xc6)); + } + + #[test] + fn accent_falls_back_to_blue_then_foreground() { + let text = "background = \"#000000\"\nforeground = \"#ffffff\"\ncolor4 = \"#0000ff\"\n"; + assert_eq!(palette_from(text).unwrap().accent, Color::rgb(0, 0, 255)); + let text = "background = \"#000000\"\nforeground = \"#ffffff\"\n"; + assert_eq!( + palette_from(text).unwrap().accent, + Color::rgb(255, 255, 255) + ); + } + + #[test] + fn tolerates_comments_spacing_and_bare_values() { + let text = + "background=\"#101010\" # dark\n foreground = #eeeeee # bare\naccent = \"nope\"\n"; + let palette = palette_from(text).unwrap(); + assert_eq!(palette.background, Color::rgb(0x10, 0x10, 0x10)); + assert_eq!(palette.foreground, Color::rgb(0xee, 0xee, 0xee)); + // A bad accent is skipped, so the foreground stands in. + assert_eq!(palette.accent, palette.foreground); + } + + #[test] + fn needs_background_and_foreground() { + assert!(palette_from("background = \"#000000\"\n").is_none()); + assert!(palette_from("").is_none()); + } + + #[test] + fn only_the_theme_entry_counts() { + assert!(is_theme_entry(OsStr::new("theme"))); + assert!(!is_theme_entry(OsStr::new("next-theme"))); + assert!(!is_theme_entry(OsStr::new("theme.name"))); + assert!(!is_theme_entry(OsStr::new("background"))); + } + + #[test] + fn watch_sees_a_theme_swap() { + let dir = std::env::temp_dir().join(format!("alias-calc-theme-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(dir.join("next-theme")).unwrap(); + let fd = inotify::init(CreateFlags::CLOEXEC | CreateFlags::NONBLOCK).unwrap(); + inotify::add_watch( + &fd, + &dir, + WatchFlags::MOVED_TO | WatchFlags::CREATE | WatchFlags::CLOSE_WRITE, + ) + .unwrap(); + let watch = Watch { fd }; + assert!(!watch.changed(), "nothing yet"); + + std::fs::write(dir.join("theme.name"), "x").unwrap(); + assert!(!watch.changed(), "other entries don't count"); + + std::fs::rename(dir.join("next-theme"), dir.join("theme")).unwrap(); + assert!(watch.changed(), "the swap counts"); + std::fs::remove_dir_all(&dir).unwrap(); + } +} diff --git a/src/window.rs b/src/window.rs index 8024a8c..7f73930 100644 --- a/src/window.rs +++ b/src/window.rs @@ -49,6 +49,7 @@ use wayland_protocols::wp::viewporter::client::{ use crate::engine::{Calc, Key}; use crate::input; use crate::render::{Canvas, Fonts}; +use crate::theme; use crate::trace; use crate::ui::{self, Palette, View}; @@ -113,6 +114,9 @@ pub fn run() -> Result<(), Box> { // Parse the fonts while the compositor works on the configure. let fonts = Fonts::load(); trace::mark("fonts loaded"); + let palette = theme::load(); + let theme_watch = theme::Watch::new(); + trace::mark("theme read"); let (w, h) = DEFAULT_SIZE; let pool = SlotPool::new((w * h * 4) as usize, &shm)?; @@ -136,7 +140,7 @@ pub fn run() -> Result<(), Box> { pool, buffer: None, fonts, - palette: Palette::default(), + palette, size: DEFAULT_SIZE, scaling, configured: false, @@ -144,14 +148,19 @@ pub fn run() -> Result<(), Box> { exit: false, }; - event_loop(&mut queue, &mut app) + event_loop(&mut queue, &mut app, theme_watch.as_ref()) } type Queue = smithay_client_toolkit::reexports::client::EventQueue; /// Dispatch, draw if anything changed, then sleep until the compositor /// writes to the socket. No timeouts: an idle window never wakes. -fn event_loop(queue: &mut Queue, app: &mut App) -> Result<(), Box> { +/// `theme` is None when there's no theme to follow. +fn event_loop( + queue: &mut Queue, + app: &mut App, + theme: Option<&theme::Watch>, +) -> Result<(), Box> { loop { queue.dispatch_pending(app)?; if app.exit { @@ -171,7 +180,7 @@ fn event_loop(queue: &mut Queue, app: &mut App) -> Result<(), Box> { continue; }; let fd = guard.connection_fd(); - let mut fds = [PollFd::new(&fd, PollFlags::IN)]; + let theme_fd = theme.map(|w| w.fd()); // Only a held Backspace sets a timeout; otherwise sleep until the // compositor sends something. let timeout = app.repeat.as_ref().map(|r| { @@ -181,6 +190,14 @@ fn event_loop(queue: &mut Queue, app: &mut App) -> Result<(), Box> { tv_nsec: wait.subsec_nanos() as _, } }); + let mut fds = [ + PollFd::new(&fd, PollFlags::IN), + // Without a theme to follow, an fd poll ignores (negative). + match &theme_fd { + Some(theme_fd) => PollFd::new(theme_fd, PollFlags::IN), + None => PollFd::from_borrowed_fd(fd, PollFlags::empty()), + }, + ]; match poll(&mut fds, timeout.as_ref()) { Ok(0) => { drop(guard); @@ -191,6 +208,16 @@ fn event_loop(queue: &mut Queue, app: &mut App) -> Result<(), Box> { Err(Errno::INTR) => continue, Err(err) => return Err(err.into()), } + let wayland_ready = !fds[0].revents().is_empty(); + let theme_ready = theme_fd.is_some() && !fds[1].revents().is_empty(); + drop(theme_fd); + if theme_ready && theme.is_some_and(|w| w.changed()) { + app.reload_theme(); + } + if !wayland_ready { + drop(guard); + continue; + } match guard.read() { Ok(n) => { if trace::on() { @@ -258,6 +285,15 @@ impl App { self.dirty = true; } + fn reload_theme(&mut self) { + let palette = theme::load(); + if palette != self.palette { + self.palette = palette; + self.dirty = true; + trace::mark("theme changed"); + } + } + fn repeat_tick(&mut self) { let Some(repeat) = &mut self.repeat else { return; From 37d01b0e99d148370c64423bc2318b2feeea3bd6 Mon Sep 17 00:00:00 2001 From: Michael Aguiar Date: Wed, 25 Nov 2026 12:12:57 -0700 Subject: [PATCH 08/50] Make the keyboard after the first frame The compositor sends the keymap along with the first configure, and compiling it in libxkbcommon took ~1.5 ms ahead of the first draw. The keyboard is now bound right after the first commit: first frame at 1.1 ms instead of 3.0 ms. ALI-2101 --- src/window.rs | 30 +++++++++++++++++++++++++++--- 1 file changed, 27 insertions(+), 3 deletions(-) diff --git a/src/window.rs b/src/window.rs index 8024a8c..5995cdf 100644 --- a/src/window.rs +++ b/src/window.rs @@ -140,6 +140,8 @@ pub fn run() -> Result<(), Box> { size: DEFAULT_SIZE, scaling, configured: false, + drawn: false, + keyboard_seat: None, dirty: false, exit: false, }; @@ -159,6 +161,9 @@ fn event_loop(queue: &mut Queue, app: &mut App) -> Result<(), Box> { } if app.dirty && app.configured { app.draw(); + if let Some(seat) = app.keyboard_seat.take() { + app.bind_keyboard(&queue.handle(), &seat); + } } match queue.flush() { Ok(()) => {} @@ -240,6 +245,10 @@ struct App { size: (u32, u32), scaling: Scaling, configured: bool, + /// A frame has been committed. + drawn: bool, + /// A seat whose keyboard waits for the first frame. + keyboard_seat: Option, /// Something changed since the last frame. dirty: bool, exit: bool, @@ -253,6 +262,13 @@ struct Repeat { } impl App { + fn bind_keyboard(&mut self, qh: &QueueHandle, seat: &wl_seat::WlSeat) { + match self.seats.get_keyboard(qh, seat, None) { + Ok(keyboard) => self.keyboard = Some(keyboard), + Err(err) => eprintln!("alias-calc: no keyboard: {err}"), + } + } + fn press(&mut self, key: Key) { self.calc.press(key); self.dirty = true; @@ -357,6 +373,7 @@ impl App { return; } self.window.commit(); + self.drawn = true; if trace::on() { trace::mark(&format!("frame committed ({pw}x{ph} px)")); } @@ -462,9 +479,13 @@ impl SeatHandler for App { capability: Capability, ) { if capability == Capability::Keyboard && self.keyboard.is_none() { - match self.seats.get_keyboard(qh, &seat, None) { - Ok(keyboard) => self.keyboard = Some(keyboard), - Err(err) => eprintln!("alias-calc: no keyboard: {err}"), + // Compiling the keymap takes ~1.5 ms, and the compositor sends it + // with the first configure. Nobody types in the first frame, so + // the keyboard is made right after it (see `event_loop`). + if self.drawn { + self.bind_keyboard(qh, &seat); + } else { + self.keyboard_seat = Some(seat.clone()); } } if capability == Capability::Pointer && self.pointer.is_none() { @@ -488,6 +509,9 @@ impl SeatHandler for App { _: wl_seat::WlSeat, capability: Capability, ) { + if capability == Capability::Keyboard { + self.keyboard_seat = None; + } if capability == Capability::Keyboard && let Some(keyboard) = self.keyboard.take() { From dec008109cc5ad11b557d90eb3772e884d468d13 Mon Sep 17 00:00:00 2001 From: Michael Aguiar Date: Wed, 25 Nov 2026 12:21:56 -0700 Subject: [PATCH 09/50] Bind the pointer after the first frame too, and send that frame first Binding the keyboard in the same flush as the first commit still delayed the map: Hyprland builds the keymap it sends a new keyboard before it gets to the rest of the batch. The first frame now goes out on its own, then the keyboard and the pointer are bound. Map time (exec to openwindow, median of 10) is 2.7 ms, against 2.5 ms for a window with no input at all. ALI-2101 --- src/window.rs | 55 ++++++++++++++++++++++++++++++++++++++------------- 1 file changed, 41 insertions(+), 14 deletions(-) diff --git a/src/window.rs b/src/window.rs index 5995cdf..58dc863 100644 --- a/src/window.rs +++ b/src/window.rs @@ -142,6 +142,7 @@ pub fn run() -> Result<(), Box> { configured: false, drawn: false, keyboard_seat: None, + pointer_seat: None, dirty: false, exit: false, }; @@ -161,8 +162,12 @@ fn event_loop(queue: &mut Queue, app: &mut App) -> Result<(), Box> { } if app.dirty && app.configured { app.draw(); - if let Some(seat) = app.keyboard_seat.take() { - app.bind_keyboard(&queue.handle(), &seat); + if app.keyboard_seat.is_some() || app.pointer_seat.is_some() { + // Send the first frame on its own: a new keyboard makes the + // compositor build and send a keymap, and that shouldn't + // hold up mapping the window. + let _ = queue.flush(); + app.bind_input(&queue.handle()); } } match queue.flush() { @@ -247,8 +252,9 @@ struct App { configured: bool, /// A frame has been committed. drawn: bool, - /// A seat whose keyboard waits for the first frame. + /// Seats whose keyboard and pointer wait for the first frame. keyboard_seat: Option, + pointer_seat: Option, /// Something changed since the last frame. dirty: bool, exit: bool, @@ -269,6 +275,29 @@ impl App { } } + fn bind_pointer(&mut self, qh: &QueueHandle, seat: &wl_seat::WlSeat) { + match self.seats.get_pointer(qh, seat) { + Ok(pointer) => { + self.cursor = self + .cursor_shape + .as_ref() + .map(|m| m.get_shape_device(&pointer, qh)); + self.pointer = Some(pointer); + } + Err(err) => eprintln!("alias-calc: no pointer: {err}"), + } + } + + /// Binds the keyboard and pointer held back for the first frame. + fn bind_input(&mut self, qh: &QueueHandle) { + if let Some(seat) = self.keyboard_seat.take() { + self.bind_keyboard(qh, &seat); + } + if let Some(seat) = self.pointer_seat.take() { + self.bind_pointer(qh, &seat); + } + } + fn press(&mut self, key: Key) { self.calc.press(key); self.dirty = true; @@ -480,8 +509,8 @@ impl SeatHandler for App { ) { if capability == Capability::Keyboard && self.keyboard.is_none() { // Compiling the keymap takes ~1.5 ms, and the compositor sends it - // with the first configure. Nobody types in the first frame, so - // the keyboard is made right after it (see `event_loop`). + // with the first configure. Nobody types or clicks in the first + // frame, so input is bound right after it (see `event_loop`). if self.drawn { self.bind_keyboard(qh, &seat); } else { @@ -489,15 +518,10 @@ impl SeatHandler for App { } } if capability == Capability::Pointer && self.pointer.is_none() { - match self.seats.get_pointer(qh, &seat) { - Ok(pointer) => { - self.cursor = self - .cursor_shape - .as_ref() - .map(|m| m.get_shape_device(&pointer, qh)); - self.pointer = Some(pointer); - } - Err(err) => eprintln!("alias-calc: no pointer: {err}"), + if self.drawn { + self.bind_pointer(qh, &seat); + } else { + self.pointer_seat = Some(seat); } } } @@ -512,6 +536,9 @@ impl SeatHandler for App { if capability == Capability::Keyboard { self.keyboard_seat = None; } + if capability == Capability::Pointer { + self.pointer_seat = None; + } if capability == Capability::Keyboard && let Some(keyboard) = self.keyboard.take() { From e94dd8856f7c2cc786ffb79dc833dd338fa74ac8 Mon Sep 17 00:00:00 2001 From: Michael Aguiar Date: Wed, 25 Nov 2026 12:25:27 -0700 Subject: [PATCH 10/50] Copy and paste numbers Ctrl+C or Super+C offers the result without separators (an error isn't copied) as text/plain;charset=utf-8, text/plain, UTF8_STRING, TEXT and STRING. Ctrl+V or Super+V reads the selection in the best of those and pastes it if it's a number, with or without separators. The paste pipe is read without blocking, from the same poll as the Wayland socket: the source can be this app, which has to answer its own send_request while the paste is still being read. Pastes over 256 bytes or not UTF-8 are dropped. The data device shares the keyboard's seat and is made with it, after the first frame. ALI-2102 --- Cargo.toml | 2 +- src/clipboard.rs | 145 +++++++++++++++++++++++++++++++++ src/engine.rs | 3 - src/main.rs | 1 + src/window.rs | 204 +++++++++++++++++++++++++++++++++++++++++++---- 5 files changed, 336 insertions(+), 19 deletions(-) create mode 100644 src/clipboard.rs diff --git a/Cargo.toml b/Cargo.toml index 579f614..56d4dfc 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -9,7 +9,7 @@ publish = false [dependencies] fontdue = { version = "0.9", default-features = false, features = ["std", "simd"] } rust_decimal = { version = "1.43", default-features = false, features = ["std", "maths"] } -rustix = { version = "1", default-features = false, features = ["std", "event", "fs"] } +rustix = { version = "1", default-features = false, features = ["std", "event", "fs", "pipe"] } smithay-client-toolkit = { version = "0.21", default-features = false, features = ["xkbcommon"] } wayland-protocols = { version = "0.32", features = ["client", "staging"] } diff --git a/src/clipboard.rs b/src/clipboard.rs new file mode 100644 index 0000000..522eb7d --- /dev/null +++ b/src/clipboard.rs @@ -0,0 +1,145 @@ +//! Copy and paste: which text formats to offer and accept, and reading a +//! pasted number without blocking the event loop. +//! +//! A paste is read through a pipe the source app writes to. That app may be +//! this one (pasting what it just copied), so the pipe is never read in one +//! blocking go: it sits in the event loop's poll set and is drained as data +//! arrives, while the loop keeps answering the compositor. + +use std::io::{ErrorKind, Read}; +use std::os::fd::AsFd; + +use smithay_client_toolkit::data_device_manager::ReadPipe; + +/// Formats offered when copying, most specific first. +pub const OFFERED: [&str; 5] = [ + "text/plain;charset=utf-8", + "text/plain", + "UTF8_STRING", + "TEXT", + "STRING", +]; + +/// The best text format among those an offer has. +pub fn pick_format(available: &[String]) -> Option { + OFFERED + .iter() + .find(|want| available.iter().any(|have| have == *want)) + .map(|s| s.to_string()) +} + +/// A number is short. Anything longer than this isn't one, and reading +/// stops there. +const MAX_PASTE: usize = 256; + +/// A paste being read. +pub struct Paste { + pipe: ReadPipe, + text: Vec, +} + +/// What reading a paste came to. +pub enum Progress { + /// More may come. + Pending, + /// The source closed the pipe: here's the text. + Done(String), + /// It failed, or was too long to be a number. + Dropped, +} + +impl Paste { + /// Takes the pipe and makes it non-blocking. + pub fn new(pipe: ReadPipe) -> Option { + rustix::io::ioctl_fionbio(&pipe, true).ok()?; + Some(Self { + pipe, + text: Vec::new(), + }) + } + + pub fn fd(&self) -> impl AsFd + '_ { + self.pipe.as_fd() + } + + /// Reads what's there. Call when the pipe is readable. + pub fn read(&mut self) -> Progress { + let mut buf = [0u8; 256]; + loop { + match self.pipe.read(&mut buf) { + Ok(0) => { + return match String::from_utf8(std::mem::take(&mut self.text)) { + Ok(text) => Progress::Done(text), + Err(_) => Progress::Dropped, + }; + } + Ok(n) => { + self.text.extend_from_slice(&buf[..n]); + if self.text.len() > MAX_PASTE { + return Progress::Dropped; + } + } + Err(err) if err.kind() == ErrorKind::WouldBlock => return Progress::Pending, + Err(err) if err.kind() == ErrorKind::Interrupted => continue, + Err(_) => return Progress::Dropped, + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::io::Write; + + #[test] + fn prefers_utf8_text() { + let have = |list: &[&str]| list.iter().map(|s| s.to_string()).collect::>(); + assert_eq!( + pick_format(&have(&["STRING", "text/plain;charset=utf-8", "text/html"])).as_deref(), + Some("text/plain;charset=utf-8") + ); + assert_eq!( + pick_format(&have(&["UTF8_STRING", "TEXT"])).as_deref(), + Some("UTF8_STRING") + ); + assert_eq!(pick_format(&have(&["image/png"])), None); + } + + fn pipe() -> (ReadPipe, std::fs::File) { + let (r, w) = rustix::pipe::pipe().unwrap(); + (ReadPipe::from(r), std::fs::File::from(w)) + } + + #[test] + fn reads_in_pieces_without_blocking() { + let (r, mut w) = pipe(); + let mut paste = Paste::new(r).unwrap(); + assert!( + matches!(paste.read(), Progress::Pending), + "nothing written yet" + ); + w.write_all(b"1,234.").unwrap(); + assert!(matches!(paste.read(), Progress::Pending)); + w.write_all(b"5").unwrap(); + drop(w); + match paste.read() { + Progress::Done(text) => assert_eq!(text, "1,234.5"), + _ => panic!("expected the text"), + } + } + + #[test] + fn drops_long_or_binary_pastes() { + let (r, mut w) = pipe(); + let mut paste = Paste::new(r).unwrap(); + w.write_all(&[b'9'; MAX_PASTE + 1]).unwrap(); + assert!(matches!(paste.read(), Progress::Dropped)); + + let (r, mut w) = pipe(); + let mut paste = Paste::new(r).unwrap(); + w.write_all(&[0xff, 0xfe]).unwrap(); + drop(w); + assert!(matches!(paste.read(), Progress::Dropped)); + } +} diff --git a/src/engine.rs b/src/engine.rs index 3d49344..f623c91 100644 --- a/src/engine.rs +++ b/src/engine.rs @@ -371,7 +371,6 @@ impl Calc { } /// Whether the display shows an error. - #[allow(dead_code)] // Copy and paste use it (ALI-2102). pub fn is_error(&self) -> bool { self.errored } @@ -380,7 +379,6 @@ impl Calc { /// around it, thousands separators in groups of three (`1,234,567.89`), /// a decimal comma (`1,5`) and the `−` this calculator shows. Anything /// else is ignored, and the return value says whether it was taken. - #[allow(dead_code)] // Copy and paste use it (ALI-2102). pub fn paste(&mut self, text: &str) -> bool { let mut text: String = text .trim() @@ -626,7 +624,6 @@ fn significant_digits(entry: &str) -> usize { } /// `1,234` or `-1,234,567.89`: commas exactly every three digits. -#[allow(dead_code)] // Only `paste` uses it so far. fn is_grouped(text: &str) -> bool { let body = text.strip_prefix('-').unwrap_or(text); let whole = body.split_once('.').map_or(body, |(w, _)| w); diff --git a/src/main.rs b/src/main.rs index 4c5057e..9408b01 100644 --- a/src/main.rs +++ b/src/main.rs @@ -3,6 +3,7 @@ //! One thread, no toolkit, no GPU: a plain Wayland client that draws on the //! CPU into a shared-memory buffer and sleeps until something happens. +mod clipboard; mod engine; mod input; mod render; diff --git a/src/window.rs b/src/window.rs index fb35f77..f55d075 100644 --- a/src/window.rs +++ b/src/window.rs @@ -12,12 +12,20 @@ use std::time::{Duration, Instant}; use rustix::event::{PollFd, PollFlags, Timespec, poll}; use rustix::io::Errno; use smithay_client_toolkit::compositor::{CompositorHandler, CompositorState}; +use smithay_client_toolkit::data_device_manager::data_device::{DataDevice, DataDeviceHandler}; +use smithay_client_toolkit::data_device_manager::data_offer::{DataOfferHandler, DragOffer}; +use smithay_client_toolkit::data_device_manager::data_source::{ + CopyPasteSource, DataSourceHandler, +}; +use smithay_client_toolkit::data_device_manager::{DataDeviceManagerState, WritePipe}; use smithay_client_toolkit::dispatch2::Dispatch2; use smithay_client_toolkit::output::{OutputHandler, OutputState}; use smithay_client_toolkit::reexports::client::backend::WaylandError; use smithay_client_toolkit::reexports::client::globals::registry_queue_init; +use smithay_client_toolkit::reexports::client::protocol::wl_data_device_manager::DndAction; use smithay_client_toolkit::reexports::client::protocol::{ - wl_keyboard, wl_output, wl_pointer, wl_seat, wl_shm, wl_surface, + wl_data_device::WlDataDevice, wl_data_source::WlDataSource, wl_keyboard, wl_output, wl_pointer, + wl_seat, wl_shm, wl_surface, }; use smithay_client_toolkit::reexports::client::{Connection, QueueHandle}; use smithay_client_toolkit::registry::{ProvidesRegistryState, RegistryState}; @@ -46,6 +54,7 @@ use wayland_protocols::wp::viewporter::client::{ wp_viewport::WpViewport, wp_viewporter::WpViewporter, }; +use crate::clipboard::{self, Paste, Progress}; use crate::engine::{Calc, Key}; use crate::input; use crate::render::{Canvas, Fonts}; @@ -88,6 +97,7 @@ pub fn run() -> Result<(), Box> { globals.bind(&qh, 1..=1, NoEvents).ok(); let viewporter: Option = globals.bind(&qh, 1..=1, NoEvents).ok(); let cursor_shape = CursorShapeManager::bind(&globals, &qh).ok(); + let data_manager = DataDeviceManagerState::bind(&globals, &qh).ok(); let surface = compositor.create_surface(&qh); let scaling = match (fractional_manager, viewporter) { @@ -130,6 +140,10 @@ pub fn run() -> Result<(), Box> { cursor: None, modifiers: Modifiers::default(), calc: Calc::new(), + data_manager, + data_device: None, + copied: None, + paste: None, mouse_down: None, mouse_at: (0.0, 0.0), key_down: None, @@ -191,6 +205,9 @@ fn event_loop( }; let fd = guard.connection_fd(); let theme_fd = theme.map(|w| w.fd()); + // Out of `app` while polled, so its fd can be borrowed alongside. + let mut paste = app.paste.take(); + let paste_fd = paste.as_ref().map(|p| p.fd()); // Only a held Backspace sets a timeout; otherwise sleep until the // compositor sends something. let timeout = app.repeat.as_ref().map(|r| { @@ -200,15 +217,32 @@ fn event_loop( tv_nsec: wait.subsec_nanos() as _, } }); + // A missing theme watch or paste polls the Wayland fd again with + // no events asked for, which never wakes the loop. + let idle = || PollFd::from_borrowed_fd(fd, PollFlags::empty()); let mut fds = [ PollFd::new(&fd, PollFlags::IN), - // Without a theme to follow, an fd poll ignores (negative). - match &theme_fd { - Some(theme_fd) => PollFd::new(theme_fd, PollFlags::IN), - None => PollFd::from_borrowed_fd(fd, PollFlags::empty()), - }, + theme_fd + .as_ref() + .map_or_else(idle, |f| PollFd::new(f, PollFlags::IN)), + paste_fd + .as_ref() + .map_or_else(idle, |f| PollFd::new(f, PollFlags::IN)), ]; - match poll(&mut fds, timeout.as_ref()) { + let polled = poll(&mut fds, timeout.as_ref()); + let ready = |i: usize| !fds[i].revents().is_empty(); + let (wayland_ready, theme_ready, paste_ready) = ( + ready(0), + theme_fd.is_some() && ready(1), + paste_fd.is_some() && ready(2), + ); + drop(theme_fd); + drop(paste_fd); + if paste_ready && let Some(mut reading) = paste.take() { + paste = app.paste_progress(reading.read(), reading); + } + app.paste = paste; + match polled { Ok(0) => { drop(guard); app.repeat_tick(); @@ -218,9 +252,6 @@ fn event_loop( Err(Errno::INTR) => continue, Err(err) => return Err(err.into()), } - let wayland_ready = !fds[0].revents().is_empty(); - let theme_ready = theme_fd.is_some() && !fds[1].revents().is_empty(); - drop(theme_fd); if theme_ready && theme.is_some_and(|w| w.changed()) { app.reload_theme(); } @@ -264,6 +295,12 @@ struct App { cursor: Option, modifiers: Modifiers, calc: Calc, + /// Copy and paste; None when the compositor has no data device manager. + data_manager: Option, + data_device: Option, + /// What this app last copied, while it still owns the selection. + copied: Option<(CopyPasteSource, String)>, + paste: Option, /// The button the left mouse button went down on. mouse_down: Option<(usize, usize)>, /// The pointer's last logical position. @@ -300,6 +337,55 @@ impl App { Ok(keyboard) => self.keyboard = Some(keyboard), Err(err) => eprintln!("alias-calc: no keyboard: {err}"), } + // Copy and paste are keyboard shortcuts, so they share its seat. + if self.data_device.is_none() + && let Some(manager) = &self.data_manager + { + self.data_device = Some(manager.get_data_device(qh, seat)); + } + } + + /// Ctrl+C: offers the result, without separators. An error isn't copied. + fn copy(&mut self, qh: &QueueHandle, serial: u32) { + if self.calc.is_error() { + return; + } + let (Some(manager), Some(device)) = (&self.data_manager, &self.data_device) else { + return; + }; + let source = manager.create_copy_paste_source(qh, clipboard::OFFERED); + source.set_selection(device, serial); + // Replacing the old source destroys it. + self.copied = Some((source, self.calc.copy_text())); + } + + /// Ctrl+V: starts reading the selection; `event_loop` finishes it. + fn paste(&mut self) { + let Some(offer) = self + .data_device + .as_ref() + .and_then(|d| d.data().selection_offer()) + else { + return; + }; + let Some(format) = offer.with_mime_types(clipboard::pick_format) else { + return; + }; + self.paste = offer.receive(format).ok().and_then(Paste::new); + } + + /// Takes a paste's read result: keeps reading, or pastes the text. + fn paste_progress(&mut self, progress: Progress, reading: Paste) -> Option { + match progress { + Progress::Pending => Some(reading), + Progress::Done(text) => { + if self.calc.paste(&text) { + self.dirty = true; + } + None + } + Progress::Dropped => None, + } } fn bind_pointer(&mut self, qh: &QueueHandle, seat: &wl_seat::WlSeat) { @@ -627,14 +713,23 @@ impl KeyboardHandler for App { fn press_key( &mut self, _: &Connection, - _: &QueueHandle, + qh: &QueueHandle, _: &wl_keyboard::WlKeyboard, - _: u32, + serial: u32, event: KeyEvent, ) { - // Ctrl, Alt and Super chords belong to the compositor and to copy - // and paste (ALI-2102), never to the keypad. - if self.modifiers.ctrl || self.modifiers.alt || self.modifiers.logo { + let m = self.modifiers; + // Ctrl+C / Super+C copy and Ctrl+V / Super+V paste, as in omacalc. + if (m.ctrl || m.logo) && !m.alt && !m.shift { + match event.keysym { + Keysym::c | Keysym::C => self.copy(qh, serial), + Keysym::v | Keysym::V => self.paste(), + _ => {} + } + return; + } + // Other chords belong to the compositor, never to the keypad. + if m.ctrl || m.alt || m.logo { return; } let Some(key) = input::key_for(event.keysym) else { @@ -760,6 +855,85 @@ impl PointerHandler for App { } } +impl DataDeviceHandler for App { + fn enter( + &mut self, + _: &Connection, + _: &QueueHandle, + _: &WlDataDevice, + _: f64, + _: f64, + _: &wl_surface::WlSurface, + ) { + } + fn leave(&mut self, _: &Connection, _: &QueueHandle, _: &WlDataDevice) {} + fn motion(&mut self, _: &Connection, _: &QueueHandle, _: &WlDataDevice, _: f64, _: f64) {} + // The selection is read only when Ctrl+V asks for it. + fn selection(&mut self, _: &Connection, _: &QueueHandle, _: &WlDataDevice) {} + fn drop_performed(&mut self, _: &Connection, _: &QueueHandle, _: &WlDataDevice) {} +} + +impl DataOfferHandler for App { + fn source_actions( + &mut self, + _: &Connection, + _: &QueueHandle, + _: &mut DragOffer, + _: DndAction, + ) { + } + fn selected_action( + &mut self, + _: &Connection, + _: &QueueHandle, + _: &mut DragOffer, + _: DndAction, + ) { + } +} + +impl DataSourceHandler for App { + fn accept_mime( + &mut self, + _: &Connection, + _: &QueueHandle, + _: &WlDataSource, + _: Option, + ) { + } + + fn send_request( + &mut self, + _: &Connection, + _: &QueueHandle, + source: &WlDataSource, + _: String, + mut fd: WritePipe, + ) { + use std::io::Write; + // A number is far smaller than a pipe's buffer, so this never blocks. + if let Some((ours, text)) = &self.copied + && ours.inner() == source + { + let _ = fd.write_all(text.as_bytes()); + } + } + + fn cancelled(&mut self, _: &Connection, _: &QueueHandle, source: &WlDataSource) { + if self + .copied + .as_ref() + .is_some_and(|(ours, _)| ours.inner() == source) + { + self.copied = None; + } + } + + fn dnd_dropped(&mut self, _: &Connection, _: &QueueHandle, _: &WlDataSource) {} + fn dnd_finished(&mut self, _: &Connection, _: &QueueHandle, _: &WlDataSource) {} + fn action(&mut self, _: &Connection, _: &QueueHandle, _: &WlDataSource, _: DndAction) {} +} + impl ShmHandler for App { fn shm_state(&mut self) -> &mut Shm { &mut self.shm From 7f2340468db611aa5f4bb844d902bea0916965d7 Mon Sep 17 00:00:00 2001 From: Michael Aguiar Date: Wed, 25 Nov 2026 12:30:45 -0700 Subject: [PATCH 11/50] Make the benchmark harness fail loudly instead of measuring wrong From review: a crashed app read as 0 MB and no wakeups; the map timeout restarted on every unrelated Hyprland event; the class was matched anywhere in the openwindow line (a title containing "omacalc" counted); wakeups summed counters over whichever threads existed at each sample; an app ignoring SIGTERM hung the run. Now the class field is matched exactly, the deadline is checked on every event, the run fails if the app exits before or after mapping, wakeups are per-thread differences, and the app is SIGKILLed if SIGTERM doesn't end it. bench/run finds the binary through cargo metadata, parses --runs N and --runs=N (rejecting anything else), and exits 1 when no app was measured. The README and CI no longer say the app links libwayland: the Wayland client is pure Rust. ALI-2097 --- .github/workflows/ci.yml | 5 +- README.md | 2 +- bench/calcbench.py | 98 +++++++++++++++++++++++++++++++--------- bench/run | 15 +++++- 4 files changed, 93 insertions(+), 27 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 81b7f96..bf4e57f 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -36,13 +36,14 @@ jobs: timeout-minutes: 30 steps: # git before checkout, or checkout falls back to a tarball; a C - # compiler for the linker; and the two libraries the app links. + # compiler for the linker; libxkbcommon for keyboard layouts (the + # Wayland client is pure Rust, so libwayland isn't needed). - name: Install build dependencies run: | apt-get update -qq apt-get install -y -qq --no-install-recommends \ git ca-certificates curl build-essential pkg-config \ - libwayland-dev libxkbcommon-dev python3 >/dev/null + libxkbcommon-dev python3 >/dev/null - uses: actions/checkout@v4 # A clean Rust each time: an earlier job's half-installed rustup in # the shared $HOME breaks the install. diff --git a/README.md b/README.md index 3240860..ed65d91 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ Linear project: Alias Calc (P-ALI-28). cargo build --release ``` -The binary is `target/release/alias-calc`. It links only `wayland` and `libxkbcommon`. +The binary is `target/release/alias-calc`. The aim is to link nothing beyond libc and `libxkbcommon` (for keyboard layouts), with a pure-Rust Wayland client. ## Benchmark diff --git a/bench/calcbench.py b/bench/calcbench.py index f04f596..4d39a59 100755 --- a/bench/calcbench.py +++ b/bench/calcbench.py @@ -7,7 +7,7 @@ thread count for the process tree, then counts context switches (wakeups) over an idle period. It prints the medians as one JSON line. -Usage: calcbench.py [--runs N] -- cmd args... +Usage: calcbench.py [--runs N] -- cmd args... calcbench.py --table < results.jsonl The windows open on the current workspace, so leave the machine alone while it @@ -68,34 +68,72 @@ def memory(pids): def switches(pids): - total = 0 + """Context switches per thread, as {(pid, tid): count}. Voluntary ones + (the thread slept and was woken) plus involuntary ones (preempted while + running): both mean the thread was on a CPU.""" + counts = {} for p in pids: try: - for t in os.listdir(f"/proc/{p}/task"): - with open(f"/proc/{p}/task/{t}/status") as f: - for line in f: - if line.startswith(("voluntary_ctxt", "nonvoluntary_ctxt")): - total += int(line.split()[1]) + tids = os.listdir(f"/proc/{p}/task") except OSError: - pass - return total + continue + for t in tids: + try: + with open(f"/proc/{p}/task/{t}/status") as f: + counts[(p, t)] = sum( + int(line.split()[1]) + for line in f + if line.startswith(("voluntary_ctxt", "nonvoluntary_ctxt")) + ) + except OSError: + pass + return counts + +def wakeups(before, after): + """Switches between two samples. A thread in both counts its difference; + one that started in between counts all of its switches; one that ended + counts none it made after the first sample (they can't be read).""" + return sum(n - before.get(key, 0) for key, n in after.items()) -def wait_for_window(sock, wclass): + +def window_class(line): + """The class in `openwindow>>ADDRESS,WORKSPACE,CLASS,TITLE`, lowercased.""" + payload = line.decode(errors="replace").removeprefix("openwindow>>") + fields = payload.split(",", 3) + return fields[2].lower() if len(fields) >= 3 else None + + +def wait_for_window(sock, wclass, proc): deadline = time.perf_counter() + MAP_TIMEOUT buf = b"" while True: - sock.settimeout(max(0.01, deadline - time.perf_counter())) - chunk = sock.recv(65536) + left = deadline - time.perf_counter() + # Other windows' events keep arriving, so the deadline is checked + # here, not only through the socket timeout. + if left <= 0: + raise TimeoutError + if proc.poll() is not None: + raise RuntimeError(f"exited with status {proc.returncode} before opening a window") + sock.settimeout(min(left, 0.25)) + try: + chunk = sock.recv(65536) + except (TimeoutError, socket.timeout): + continue if not chunk: raise ConnectionError("Hyprland closed the event socket") buf += chunk *lines, buf = buf.split(b"\n") for line in lines: - if line.startswith(b"openwindow>>") and wclass in line.decode(errors="replace").lower(): + if line.startswith(b"openwindow>>") and window_class(line) == wclass: return time.perf_counter() +def still_running(proc, when): + if proc.poll() is not None: + raise RuntimeError(f"exited with status {proc.returncode} {when}") + + def run_once(cmd, wclass, path): sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) sock.connect(path) @@ -103,24 +141,38 @@ def run_once(cmd, wclass, path): proc = subprocess.Popen(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, start_new_session=True) try: - mapped = wait_for_window(sock, wclass) + mapped = wait_for_window(sock, wclass, proc) sock.close() time.sleep(SETTLE) + # A crashed app would otherwise read as zero memory and no wakeups. + still_running(proc, "while settling") pids = tree(proc.pid) pss, rss, threads = memory(pids) before = switches(pids) time.sleep(IDLE) - wakeups = (switches(tree(proc.pid)) - before) / IDLE + still_running(proc, "while idle") + idle_wakeups = wakeups(before, switches(tree(proc.pid))) / IDLE finally: sock.close() + stop(proc) + return dict(map_ms=(mapped - start) * 1000, pss_kb=pss, rss_kb=rss, threads=threads, + wakeups_s=idle_wakeups) + + +def stop(proc): + """SIGTERM the app's process group, then SIGKILL it if it lingers (a + lingering GNOME Calculator would take over the next run's launch).""" + for sig, wait in ((signal.SIGTERM, 3), (signal.SIGKILL, 3)): try: - os.killpg(proc.pid, signal.SIGTERM) + os.killpg(proc.pid, sig) except ProcessLookupError: - pass - proc.wait() - time.sleep(0.5) - return dict(map_ms=(mapped - start) * 1000, pss_kb=pss, rss_kb=rss, threads=threads, - wakeups_s=wakeups) + break + try: + proc.wait(timeout=wait) + break + except subprocess.TimeoutExpired: + continue + time.sleep(0.5) def table(): @@ -144,7 +196,7 @@ def main(): sys.exit(__doc__) split = argv.index("--") parser = argparse.ArgumentParser() - parser.add_argument("--runs", type=int, default=10) + parser.add_argument("--runs", type=int, default=10, choices=range(1, 1001), metavar="N") parser.add_argument("name") parser.add_argument("wclass") args = parser.parse_args(argv[:split]) @@ -155,6 +207,8 @@ def main(): results = [run_once(cmd, args.wclass.lower(), path) for _ in range(args.runs)] except (TimeoutError, socket.timeout): sys.exit(f"calcbench: {args.name}: no window within {MAP_TIMEOUT:.0f} s") + except (OSError, RuntimeError) as err: + sys.exit(f"calcbench: {args.name}: {err}") median = {k: round(statistics.median(r[k] for r in results), 1) for k in results[0]} median["map_ms_min"] = round(min(r["map_ms"] for r in results), 1) diff --git a/bench/run b/bench/run index 26c8b62..88b181a 100755 --- a/bench/run +++ b/bench/run @@ -13,9 +13,16 @@ set -euo pipefail cd "$(dirname "$0")/.." runs=10 -if [[ ${1:-} == --runs ]]; then runs=$2; fi +while (($#)); do + case $1 in + --runs) runs=${2:?--runs needs a number}; shift 2 ;; + --runs=*) runs=${1#--runs=}; shift ;; + *) echo "Usage: bench/run [--runs N]" >&2; exit 2 ;; + esac +done cargo build --release --locked --quiet +target=$(cargo metadata --format-version 1 --no-deps | python3 -I -c 'import json, sys; print(json.load(sys.stdin)["target_directory"])') results=() bench() { @@ -27,7 +34,7 @@ bench() { fi } -bench alias-calc com.aliasproject.calc target/release/alias-calc +bench alias-calc com.aliasproject.calc "$target/release/alias-calc" omacalc=${OMACALC:-$(command -v omacalc || true)} if [[ -n $omacalc ]]; then @@ -44,4 +51,8 @@ if command -v gnome-calculator >/dev/null; then fi fi +if ((${#results[@]} == 0)); then + echo "No app was measured." >&2 + exit 1 +fi printf '%s\n' "${results[@]}" | python3 -I bench/calcbench.py --table From 0814eb0c8660578b3944f0ae5f02bb6fb3e68a4a Mon Sep 17 00:00:00 2001 From: Michael Aguiar Date: Wed, 25 Nov 2026 12:32:09 -0700 Subject: [PATCH 12/50] Don't hang unseen, keep flushing a full socket, size each axis From review: a failed buffer allocation printed a line and left the app blocked in poll with no window; a flush that hit a full socket left requests queued with nothing to wake the loop until the compositor spoke; and a configure fixing only one axis was treated as no size at all. draw() now returns an error that ends the app; after a WouldBlock flush the loop also polls for writable and flushes again; each axis of a configure is resolved on its own. bench/run (in the merge) now says it added a float rule. ALI-2098 --- src/window.rs | 53 +++++++++++++++++++++++++++++++-------------------- 1 file changed, 32 insertions(+), 21 deletions(-) diff --git a/src/window.rs b/src/window.rs index bf2888e..ff770f5 100644 --- a/src/window.rs +++ b/src/window.rs @@ -124,25 +124,37 @@ fn event_loop(queue: &mut Queue, app: &mut App) -> Result<(), Box> { return Ok(()); } if app.dirty && app.configured { - app.draw(); + app.draw()?; } - match queue.flush() { - Ok(()) => {} - Err(WaylandError::Io(err)) if err.kind() == std::io::ErrorKind::WouldBlock => {} + // A full socket leaves requests queued; then wait until it can take + // more as well as for events. + let unsent = match queue.flush() { + Ok(()) => false, + Err(WaylandError::Io(err)) if err.kind() == std::io::ErrorKind::WouldBlock => true, Err(err) => return Err(err.into()), - } + }; // Events already queued mean there's nothing to wait for. let Some(guard) = queue.prepare_read() else { continue; }; let fd = guard.connection_fd(); - let mut fds = [PollFd::new(&fd, PollFlags::IN)]; + let flags = if unsent { + PollFlags::IN | PollFlags::OUT + } else { + PollFlags::IN + }; + let mut fds = [PollFd::new(&fd, flags)]; match poll(&mut fds, None) { Ok(_) => {} Err(Errno::INTR) => continue, Err(err) => return Err(err.into()), } + if !fds[0].revents().contains(PollFlags::IN) { + // Only writable: go round and flush. + drop(guard); + continue; + } match guard.read() { Ok(n) => trace::mark(&format!("woke: {n} event(s)")), Err(WaylandError::Io(err)) if err.kind() == std::io::ErrorKind::WouldBlock => {} @@ -189,7 +201,10 @@ impl App { } } - fn draw(&mut self) { + /// Draws and commits a frame. An error means the window can't be shown + /// (no memory for the buffer), which ends the app rather than leaving it + /// running unseen. + fn draw(&mut self) -> Result<(), Box> { self.dirty = false; let (pw, ph) = self.pixel_size(); let stride = pw as i32 * 4; @@ -206,17 +221,14 @@ impl App { .create_buffer(pw as i32, ph as i32, stride, wl_shm::Format::Argb8888) { Ok((buffer, _)) => self.buffer = Some(buffer), - Err(err) => { - eprintln!("alias-calc: can't allocate a {pw}x{ph} buffer: {err}"); - return; - } + Err(err) => return Err(format!("can't allocate a {pw}x{ph} buffer: {err}").into()), } } let Some(buffer) = self.buffer.as_ref() else { - return; + return Err("no buffer".into()); }; let Some(canvas) = self.pool.canvas(buffer) else { - return; + return Err("the new buffer is busy".into()); }; canvas.as_chunks_mut::<4>().0.fill(BACKGROUND); @@ -229,12 +241,12 @@ impl App { Scaling::Integer(scale) => surface.set_buffer_scale(*scale as i32), } surface.damage_buffer(0, 0, pw as i32, ph as i32); - if let Err(err) = buffer.attach_to(surface) { - eprintln!("alias-calc: can't attach the buffer: {err}"); - return; - } + buffer + .attach_to(surface) + .map_err(|err| format!("can't attach the buffer: {err}"))?; self.window.commit(); trace::mark(&format!("frame committed ({pw}x{ph} px)")); + Ok(()) } } @@ -310,10 +322,9 @@ impl WindowHandler for App { if !self.configured { trace::mark("configured"); } - let (w, h) = match configure.new_size { - (Some(w), Some(h)) => (w.get(), h.get()), - _ => self.size, - }; + // Each axis the compositor leaves at 0 is ours to choose. + let w = configure.new_size.0.map_or(self.size.0, |w| w.get()); + let h = configure.new_size.1.map_or(self.size.1, |h| h.get()); self.size = (w.max(1), h.max(1)); self.configured = true; // Every configure needs a commit to answer it, even when the size From e0dfd12c4307a49184b2d9aaac2853451719de9b Mon Sep 17 00:00:00 2001 From: Michael Aguiar Date: Wed, 25 Nov 2026 12:35:00 -0700 Subject: [PATCH 13/50] Whole-pixel text, bounded glyph cache, hit-test what's drawn MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit From review: glyphs were cached per 1/16 px but measured at the exact size, and pen advances were fractional, so right-aligned text could end off the padding and digit spacing wobbled at fractional scales; the cache grew without bound while resizing a small window (key labels track the key height); fit() could shrink text to 1 px; hit_test used the unsnapped key rectangles, so a key's edge pixel at a fractional scale could miss it; from_hex took "#+1+2+3" and "##ffffff"; dark/light split at luminance 0.5, so mid-tones counted as dark. Text sizes and advances are now whole pixels in both measuring and drawing; the cache empties past 512 glyphs; fit() has a floor (16 px for the result, which still fits the longest number in the narrowest window; 13 px for the expression, which is then elided from the start with …, added to the font subsets); drawing and hit_test share key_pixels(); from_hex wants exactly six hex digits; the split is at 0.18. CI runs the frame budget in release. ALI-2099 --- .github/workflows/ci.yml | 4 + fonts/JetBrainsMono-Light-subset.ttf | Bin 9396 -> 9528 bytes fonts/JetBrainsMono-Regular-subset.ttf | Bin 9448 -> 9584 bytes fonts/README.md | 4 +- src/render.rs | 133 +++++++++++++++++++++---- src/ui.rs | 124 +++++++++++++++++++---- 6 files changed, 226 insertions(+), 39 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index bf4e57f..731d9d8 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -57,6 +57,10 @@ jobs: - run: cargo clippy --all-targets --locked -- -D warnings - run: cargo test --locked - run: cargo build --release --locked + # The renderer's frame budget: only meaningful optimised, so it's + # ignored in the debug test run. + - name: Performance budgets + run: cargo test --release --locked -- --ignored budget_ - name: Benchmark scripts parse run: | python3 -m py_compile bench/calcbench.py diff --git a/fonts/JetBrainsMono-Light-subset.ttf b/fonts/JetBrainsMono-Light-subset.ttf index cd2befe5cd83b1da71d64661944e678aa43d10ac..6c8b8d2bcd4d63f9f2abf3de4beefa38aec22efa 100644 GIT binary patch delta 652 zcmZ`%Ur1A76#w0O&D#C59?a?3-0sW?Gtk(Y5H83pO>v5}~%r0e^F*9ku+ypk9?JMj6%`zz!>0PJ(gxDvDNh~xlA zKXHvoBH+h2$`25(NvdPxg(uYt#cu#ierP1BT++_Z096+$zN{+ao;2RE%|yhAkcSmD z9^_JWfGZDh!|9RHv0@TFz+E|;UotTXEyFi434MXzZpv~96xUcgrXj%w53s4a*6-id z=<{02%eR%fHXz>y#C)>Y?Uo9g?YFw_Os!kqVQsZK{;L2MAB(@3QTCO-Qg)l$9KHpV zBCK7lC@|gnM5S6HB-viNj4{`gwq~E|Su_=RH?Q({`1||25iSdwa8H;P z=7o82i)a^X#69AmI3eB?b@8dVDoN6S^icY4X3h2H1Lly~n6Xin4KC)c`M&61t6CT) zpzU<(OiKIUtYap%t#YUPIi<+7O2{@~H};|r5ey=QbI4#8FY!aJ)iScolDR8evopn9 zG4|H^rtNhT)tBj*@p`Sa4e9u6{^{csIfi!h;1psAqZ2_KL@)NC8_ks6g8ev&ew;uX hqBw#>I0^+JYTz*9=%Q8(G2t}*IHtq|=w8JmgUc+He-nzz2}VMo5|-4rZ5@I zgh87YEnb4)RwyV@c_A{mh+G6w5S6q_5ZdG-G8b*6>5O$R=id8$=X~F}oQ3L^@{9824UNeFfz|+h(>ogI!OE%zhG~Pnz~v zSW2}3zD7Wr%%ty37cHD7uP1BIwq=%Za{N3?xCP!IyOHBdQh9U%IEJY6r|N+9yT7XK zGIiWDNM_WKBI%@RpGG$1J>JSqp5b}E$k+J~(JX?ZTMUZ0NQ)fp_hMIkS3JroC8Uff zS>>^^u6$Je>Wo@Y->3&(?ydIvjvPJVPY>UXZn>7$&YYFHRhD!Ny@kPfr1vzurIs2h zXqa9Ea1IwR1OrK=FpC`4@CCn}LtS??---NkajqEK>G&EXTa9!&n0D|2cq5 zh!A%jCSr)98$Gy;8)!p6Lg++0>26{eBj~^=deMbG>Us?p!ieK4ZXNl^n4*8NGMUgO J;1+y2=`ZvzdqV&K diff --git a/fonts/JetBrainsMono-Regular-subset.ttf b/fonts/JetBrainsMono-Regular-subset.ttf index f369b8a8779a944171cf5122bb413bc6e3709e79..59264fa12a6cbde0383ac3376b3a7823816b6564 100644 GIT binary patch delta 659 zcmZ`!T}V@57=F%~DLX&AFrCT%&a4fV;K(^4T96u=HuJBgjEbGMwKcZ6Xpj{-L+T=e zE{+I+m(`>sk^>=2G6=e;iz3k|C@M&*i?9TRl1^_l0x$YLp7(j5=Y9D2-cRkz9XT)n zIE+9CsjJUjU(xVm0gy7}hQcX1Qy1*KO8PnJrC9RJ@xa%Qi_}j6=Ew1<95K~~MgeP* zyv8^g@Zvk={iL_WQ`w=FN756TUk8}U zJrB}Wz&-=$#xsMbvRWJ-z|lQDxu9oa$}qQ^iK(-kU7ypzr>(MP+=2)bT)?Ipr`Oxi z=&3hWR#ueSHz>~r#e6ZE&BiK|=~t@Q&Z0K@{wQOK29-!UbVMm=T@{t75sB6z_@a2ED;+@Ed}LaPd{PbN=R(YlpgSX<-iMs!vLDm kizZ69U@wm1Fpi)NVRU0ZdLV=EqhB3B6kQ0Zb@qbpH-pol@&Et; delta 513 zcmXYtO-NKx6vzK}MwEB&eM5l@Bb|8z4y{=!K8884G z&*6sF7xp(*o=fKe-yW&aSkkckPQwDA1oGD3X9vbyp_eB9M=^mT)FJ7h-86sL~LGFU?JzQ>QR{( zb=@IYsjq~cu6Y;!sQl(l+~5|^@Yg)Y_k~}yiI5l)V`5soqWMkih+SDBn`J;6@|m2M zpX8?6sLrUL)vxLw&vB2>Q-4Hs^?qM!y__M+BPyFn$rI7VOT zfgcyqhJHkmz!=h)#R@iYU`t)I&*&#IABr!Ev8}+*7Q#}$Xd$~yRvOp-ZU5JsxPmZg zw_qTK2)faOtGJCz2%#OF=%Bno4B#FDcz`~1AxKqkz(g;GaUJ)MI0_!qyI7e*UJh_J H^tbN6cm{k~ diff --git a/fonts/README.md b/fonts/README.md index f087b26..282c882 100644 --- a/fonts/README.md +++ b/fonts/README.md @@ -2,12 +2,12 @@ Subsets of [JetBrains Mono](https://github.com/JetBrains/JetBrainsMono) v2.304, the aliasOS monospace font, under the SIL Open Font License 1.1 (`OFL.txt`). They're compiled into the binary, so nothing is looked up through fontconfig at startup. -Each keeps printable ASCII plus × ÷ − ± ⌫, with no hinting or layout tables (the renderer doesn't use them). About 9 KB each. To rebuild them from the release's `fonts/ttf/` files: +Each keeps printable ASCII plus × ÷ − ± ⌫ …, with no hinting or layout tables (the renderer doesn't use them). About 9 KB each. To rebuild them from the release's `fonts/ttf/` files: ```sh for w in Regular Light; do uvx --from fonttools pyftsubset JetBrainsMono-$w.ttf \ - --unicodes="U+0020-007E,U+00D7,U+00F7,U+00B1,U+2212,U+232B" \ + --unicodes="U+0020-007E,U+00D7,U+00F7,U+00B1,U+2212,U+232B,U+2026" \ --layout-features='' --no-hinting --desubroutinize \ --name-IDs='0,1,2,3,4,5,6,13,14' \ --drop-tables+=GSUB,GPOS,GDEF,DSIG,STAT,gasp,prep,fpgm,cvt \ diff --git a/src/render.rs b/src/render.rs index 71c5321..dad7f0d 100644 --- a/src/render.rs +++ b/src/render.rs @@ -24,8 +24,10 @@ impl Color { /// Parses `#rrggbb` (the `#` is optional). #[allow(dead_code)] // The theme reader uses it (ALI-2103). pub fn from_hex(hex: &str) -> Option { - let hex = hex.trim().trim_start_matches('#'); - if hex.len() != 6 || !hex.is_ascii() { + let hex = hex.trim(); + let hex = hex.strip_prefix('#').unwrap_or(hex); + // from_str_radix alone would take a leading '+'. + if hex.len() != 6 || !hex.bytes().all(|b| b.is_ascii_hexdigit()) { return None; } let channel = |i: usize| u8::from_str_radix(&hex[i..i + 2], 16).ok(); @@ -155,6 +157,7 @@ impl<'a> Canvas<'a> { color: Color, ) { let (x, baseline) = origin; + let size = quantize(size); let pixel = color.pixel(); let mut pen = x; for ch in text.chars() { @@ -177,13 +180,22 @@ impl<'a> Canvas<'a> { blend(&mut row[px as usize], pixel, a as u32); } } - pen += glyph.metrics.advance_width; + pen += glyph.metrics.advance_width.round(); } } } +/// Text sizes snap to whole pixels, so the glyph cache holds one entry per +/// size actually drawn, and what's measured is what's rasterized. +pub fn quantize(size: f32) -> f32 { + size.round().max(1.0) +} + +/// More cached glyphs than this (a long run of resizes) empties the cache. +const CACHE_LIMIT: usize = 512; + /// The two embedded weights. Both are subsets of JetBrains Mono, the aliasOS -/// monospace font: printable ASCII plus × ÷ − ± ⌫ (see fonts/README.md). +/// monospace font: printable ASCII plus × ÷ − ± ⌫ … (see fonts/README.md). #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub enum Face { Regular, @@ -199,8 +211,9 @@ struct Glyph { } /// The fonts and a cache of every glyph rasterized so far, keyed by face, -/// character and size. A calculator shows a few dozen glyphs at three or four -/// sizes, so the cache stays small and a frame almost never rasterizes. +/// character and whole-pixel size. A calculator shows a few dozen glyphs at +/// three or four sizes, so a frame almost never rasterizes; resizing through +/// many sizes is bounded by `CACHE_LIMIT`. pub struct Fonts { regular: Font, light: Font, @@ -231,9 +244,12 @@ impl Fonts { } } + /// `size` must already be quantized. fn glyph(&mut self, face: Face, ch: char, size: f32) -> &Glyph { - // Sizes are cached in 1/16 px steps. - let key = (face, ch, (size * 16.0).round() as u32); + let key = (face, ch, size as u32); + if self.cache.len() >= CACHE_LIMIT && !self.cache.contains_key(&key) { + self.cache.clear(); + } let font = match face { Face::Regular => &self.regular, Face::Light => &self.light, @@ -248,27 +264,61 @@ impl Fonts { /// character count times one advance. pub fn width(&self, face: Face, size: f32, text: &str) -> f32 { let font = self.font(face); + let size = quantize(size); text.chars() - .map(|ch| font.metrics(ch, size).advance_width) + .map(|ch| font.metrics(ch, size).advance_width.round()) .sum() } /// The height of the digits above the baseline, for centring numbers /// and symbols optically. pub fn digit_height(&self, face: Face, size: f32) -> f32 { - let m = self.font(face).metrics('0', size); + let m = self.font(face).metrics('0', quantize(size)); m.height as f32 + m.ymin as f32 } - /// The largest size, up to `preferred`, at which `text` fits `max_width`. - pub fn fit(&self, face: Face, preferred: f32, text: &str, max_width: f32) -> f32 { + /// The largest whole-pixel size, from `preferred` down to `min`, at + /// which `text` fits `max_width`; `min` if it doesn't fit even then. + pub fn fit(&self, face: Face, preferred: f32, min: f32, text: &str, max_width: f32) -> f32 { + let preferred = quantize(preferred); + let min = quantize(min).min(preferred); let width = self.width(face, preferred, text); if width <= max_width || width <= 0.0 { - preferred - } else { - // Advance scales linearly with size. - (preferred * max_width / width).floor().max(1.0) + return preferred; + } + // Advance scales about linearly with size; rounding can leave it a + // pixel over, so step down until it fits. + let mut size = (preferred * max_width / width) + .floor() + .clamp(min, preferred); + while size > min && self.width(face, size, text) > max_width { + size -= 1.0; + } + size + } + + /// `text`, with characters dropped from the front and an ellipsis put + /// in their place until it fits `max_width`. The end of an expression + /// is the part being worked on, so it's the part kept. + pub fn elide_start<'t>( + &self, + face: Face, + size: f32, + text: &'t str, + max_width: f32, + ) -> std::borrow::Cow<'t, str> { + if self.width(face, size, text) <= max_width { + return text.into(); + } + let mut chars = text.chars(); + while chars.next().is_some() { + let rest = chars.as_str(); + let candidate = format!("…{rest}"); + if rest.is_empty() || self.width(face, size, &candidate) <= max_width { + return candidate.into(); + } } + "…".into() } } @@ -300,6 +350,8 @@ mod tests { assert_eq!(Color::from_hex("#fff"), None); assert_eq!(Color::from_hex("#gg0000"), None); assert_eq!(Color::from_hex("#ééé"), None); + assert_eq!(Color::from_hex("#+1+2+3"), None); + assert_eq!(Color::from_hex("##ffffff"), None); } #[test] @@ -346,7 +398,7 @@ mod tests { fn fonts_cover_every_symbol_the_app_shows() { let fonts = Fonts::load(); for face in [Face::Regular, Face::Light] { - for ch in "0123456789.,+−×÷^%=()±⌫CEeor-".chars() { + for ch in "0123456789.,+−×÷^%=()±⌫…CEeor-".chars() { assert_ne!( fonts.font(face).lookup_glyph_index(ch), 0, @@ -370,9 +422,50 @@ mod tests { ); let wide = "123,456,789,012,345"; - let size = fonts.fit(Face::Light, 64.0, wide, 200.0); - assert!(size < 64.0); + let size = fonts.fit(Face::Light, 64.0, 8.0, wide, 200.0); + assert!(size < 64.0 && size == size.round()); assert!(fonts.width(Face::Light, size, wide) <= 200.0); - assert_eq!(fonts.fit(Face::Light, 64.0, "0", 200.0), 64.0); + assert_eq!(fonts.fit(Face::Light, 64.0, 8.0, "0", 200.0), 64.0); + // Too long to fit even at the minimum: the minimum, not 1 px. + assert_eq!( + fonts.fit(Face::Light, 64.0, 20.0, &"9".repeat(200), 200.0), + 20.0 + ); + } + + #[test] + fn elides_from_the_start() { + let fonts = Fonts::load(); + let text = "1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9"; + let advance = fonts.width(Face::Regular, 20.0, "0"); + let max = advance * 10.0; + let elided = fonts.elide_start(Face::Regular, 20.0, text, max); + assert!( + elided.starts_with('…') && elided.ends_with("8 + 9"), + "{elided}" + ); + assert!(fonts.width(Face::Regular, 20.0, &elided) <= max); + assert_eq!(fonts.elide_start(Face::Regular, 20.0, "12", max), "12"); + } + + #[test] + fn sizes_and_advances_are_whole_pixels() { + let fonts = Fonts::load(); + // Measuring at 23.4 and 23.0 agree: both draw at 23. + assert_eq!( + fonts.width(Face::Regular, 23.4, "1234"), + fonts.width(Face::Regular, 23.0, "1234") + ); + let w = fonts.width(Face::Regular, 23.0, "1234"); + assert_eq!(w, w.round()); + } + + #[test] + fn glyph_cache_is_bounded() { + let mut fonts = Fonts::load(); + for size in 1..2000 { + fonts.glyph(Face::Regular, '8', size as f32); + } + assert!(fonts.cache.len() <= CACHE_LIMIT); } } diff --git a/src/ui.rs b/src/ui.rs index 9badf21..46be677 100644 --- a/src/ui.rs +++ b/src/ui.rs @@ -51,7 +51,8 @@ pub struct Palette { impl Palette { pub fn new(background: Color, foreground: Color, accent: Color) -> Self { - let dark = background.luminance() < 0.5; + // 0.18 is where a color contrasts equally with black and white. + let dark = background.luminance() < 0.18; let key = background.mix(foreground, if dark { 0.08 } else { 0.06 }); let key_pressed = background.mix(foreground, if dark { 0.18 } else { 0.14 }); // Whichever of background and foreground reads better on the accent. @@ -104,6 +105,8 @@ const RADIUS: f32 = 4.0; const EXPRESSION_SIZE: f32 = 18.0; const DISPLAY_SIZE: f32 = 60.0; const KEY_SIZE: f32 = 24.0; +const EXPRESSION_MIN_SIZE: f32 = 13.0; +const DISPLAY_MIN_SIZE: f32 = 16.0; /// The share of the height above the keypad. const DISPLAY_SHARE: f32 = 0.3; @@ -137,7 +140,19 @@ impl Layout { } } - /// A key's rectangle: x, y, width, height. + /// A key's rectangle in buffer pixels, snapped to whole pixels so its + /// straight edges stay crisp. Drawing and hit-testing both use this. + fn key_pixels(&self, row: usize, col: usize, scale: f32) -> (f32, f32, f32, f32) { + let (x, y, w, h) = self.key_rect(row, col); + let (px, py) = ((x * scale).round(), (y * scale).round()); + let (pw, ph) = ( + ((x + w) * scale).round() - px, + ((y + h) * scale).round() - py, + ); + (px, py, pw, ph) + } + + /// A key's rectangle in logical pixels: x, y, width, height. fn key_rect(&self, row: usize, col: usize) -> (f32, f32, f32, f32) { let x = self.grid.0 + col as f32 * (self.key.0 + GAP); let y = self.grid.1 + row as f32 * (self.key.1 + GAP); @@ -158,19 +173,34 @@ pub fn draw(canvas: &mut Canvas, fonts: &mut Fonts, palette: &Palette, view: &Vi let max_text = s(width - 2.0 * PADDING); let right = s(width - PADDING); if !view.expression.is_empty() { - let size = fonts.fit(Face::Regular, s(EXPRESSION_SIZE), view.expression, max_text); - let w = fonts.width(Face::Regular, size, view.expression); + let size = fonts.fit( + Face::Regular, + s(EXPRESSION_SIZE), + s(EXPRESSION_MIN_SIZE), + view.expression, + max_text, + ); + let expression = fonts.elide_start(Face::Regular, size, view.expression, max_text); + let w = fonts.width(Face::Regular, size, &expression); let baseline = s(layout.expression_baseline); canvas.text( fonts, Face::Regular, size, - view.expression, + &expression, (right - w, baseline), palette.muted, ); } - let size = fonts.fit(Face::Light, s(DISPLAY_SIZE), view.display, max_text); + // The engine keeps a number to 16 digits plus separators and sign, which + // fits at the minimum size in the narrowest window. + let size = fonts.fit( + Face::Light, + s(DISPLAY_SIZE), + s(DISPLAY_MIN_SIZE), + view.display, + max_text, + ); let w = fonts.width(Face::Light, size, view.display); let baseline = s(layout.display_baseline); canvas.text( @@ -185,7 +215,6 @@ pub fn draw(canvas: &mut Canvas, fonts: &mut Fonts, palette: &Palette, view: &Vi // The keypad. for (row, labels) in KEYS.iter().enumerate() { for (col, &label) in labels.iter().enumerate() { - let (x, y, w, h) = layout.key_rect(row, col); let pressed = view.pressed == Some((row, col)); let (fill, ink) = match role(label) { Role::Equals => ( @@ -210,9 +239,7 @@ pub fn draw(canvas: &mut Canvas, fonts: &mut Fonts, palette: &Palette, view: &Vi (fill, ink) } }; - // Snap keys to whole pixels so their straight edges stay crisp. - let (px, py) = (s(x).round(), s(y).round()); - let (pw, ph) = (s(x + w).round() - px, s(y + h).round() - py); + let (px, py, pw, ph) = layout.key_pixels(row, col, scale); canvas.rounded_rect(px, py, pw, ph, s(RADIUS), fill); // JetBrains Mono draws × ÷ − + small next to its digits. @@ -237,13 +264,22 @@ pub fn draw(canvas: &mut Canvas, fonts: &mut Fonts, palette: &Palette, view: &Vi } } -/// The key at logical position (x, y), as (row, column). +/// The key at logical position (x, y), as (row, column), in a window of +/// `width` by `height` logical pixels drawn at `scale`. It tests the same +/// pixel-snapped rectangles that are drawn, so a click on a key's edge pixel +/// presses that key. #[allow(dead_code)] // Mouse input uses it (ALI-2101). -pub fn hit_test(fonts: &Fonts, width: f32, height: f32, x: f32, y: f32) -> Option<(usize, usize)> { +pub fn hit_test( + fonts: &Fonts, + (width, height): (f32, f32), + scale: f32, + (x, y): (f32, f32), +) -> Option<(usize, usize)> { let layout = Layout::new(fonts, width, height); + let (x, y) = (x * scale, y * scale); for (row, labels) in KEYS.iter().enumerate() { for col in 0..labels.len() { - let (kx, ky, kw, kh) = layout.key_rect(row, col); + let (kx, ky, kw, kh) = layout.key_pixels(row, col, scale); if x >= kx && x < kx + kw && y >= ky && y < ky + kh { return Some((row, col)); } @@ -263,16 +299,70 @@ mod tests { let (w, h) = (320.0, 480.0); let layout = Layout::new(&fonts, w, h); let (x, y, kw, kh) = layout.key_rect(0, 0); - assert_eq!(hit_test(&fonts, w, h, x + 1.0, y + 1.0), Some((0, 0))); + assert_eq!( + hit_test(&fonts, (w, h), 1.0, (x + 1.0, y + 1.0)), + Some((0, 0)) + ); let (x, y, ..) = layout.key_rect(4, 3); - assert_eq!(hit_test(&fonts, w, h, x + 1.0, y + 1.0), Some((4, 3))); + assert_eq!( + hit_test(&fonts, (w, h), 1.0, (x + 1.0, y + 1.0)), + Some((4, 3)) + ); // Between the first two keys of the first row. assert_eq!( - hit_test(&fonts, w, h, PADDING + kw + GAP / 2.0, y - kh), + hit_test(&fonts, (w, h), 1.0, (PADDING + kw + GAP / 2.0, y - kh)), None ); // The display area. - assert_eq!(hit_test(&fonts, w, h, w / 2.0, PADDING), None); + assert_eq!(hit_test(&fonts, (w, h), 1.0, (w / 2.0, PADDING)), None); + } + + #[test] + fn every_drawn_pixel_of_a_key_hits_that_key() { + let fonts = Fonts::load(); + let (w, h) = (320.0, 480.0); + let layout = Layout::new(&fonts, w, h); + for scale in [1.0, 1.25, 1.5, 1.75] { + for (row, col) in [(0, 0), (2, 1), (4, 3)] { + let (px, py, pw, ph) = layout.key_pixels(row, col, scale); + // The four corner pixels of the drawn key, at their centres. + for (x, y) in [ + (px, py), + (px + pw - 1.0, py), + (px, py + ph - 1.0), + (px + pw - 1.0, py + ph - 1.0), + ] { + let at = ((x + 0.5) / scale, (y + 0.5) / scale); + assert_eq!( + hit_test(&fonts, (w, h), scale, at), + Some((row, col)), + "scale {scale}, pixel {x},{y}" + ); + } + } + } + } + + #[test] + fn the_longest_number_fits_the_narrowest_window() { + let fonts = Fonts::load(); + // 16 digits with separators and a sign, the most the engine shows + // (exponent forms like -1.234567890123457e+19 are as long). + let longest = "-9,999,999,999,999,999"; + for scale in [1.0, 1.5, 2.0] { + let max = (260.0 - 2.0 * PADDING) * scale; + let size = fonts.fit( + Face::Light, + DISPLAY_SIZE * scale, + DISPLAY_MIN_SIZE * scale, + longest, + max, + ); + assert!( + fonts.width(Face::Light, size, longest) <= max, + "scale {scale}" + ); + } } #[test] From ed6b28053813b36ee7c5fed9d9b0584da3fb5d28 Mon Sep 17 00:00:00 2001 From: Michael Aguiar Date: Wed, 25 Nov 2026 12:36:17 -0700 Subject: [PATCH 14/50] Fix lost digits, division residue and promoted float powers MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - A decimal keeps 28 places, not 28 significant digits, so a ×, ÷ or ^ result below 1e-13 is now redone in f64 and keeps 15 digits (1 ÷ 300000000000000 showed 14 digits; 0.7 ^ 100 showed 13). - Every exact result except a division's is rounded to 25 significant digits. The guard digits below that absorb a division's last-place error, so 1 ÷ 3 × 3 − 1 is exactly 0 instead of -1e-28. - A fractional power stays an f64 unless it's whole or its 15-digit text reads back as the same f64, so 2 ^ 0.5 × 2 ^ 0.5 is 2, not 2.000000000000014. 4 ^ 0.5 and 9 ^ 0.5 stay exact. - paste refuses a lone comma at either end (1, or ,5). - Docs: the module doc covers the f64 cases, and paste's doc says long numbers are rounded to 16 digits. ALI-2100 --- src/engine.rs | 169 ++++++++++++++++++++++++++++++++++++++++++++------ 1 file changed, 151 insertions(+), 18 deletions(-) diff --git a/src/engine.rs b/src/engine.rs index f623c91..7d7a57c 100644 --- a/src/engine.rs +++ b/src/engine.rs @@ -8,7 +8,11 @@ //! small numbers still work (shown to 15 significant digits, as omacalc does). //! //! The display rounds exact values to 16 significant digits, so every -//! integer up to 9,999,999,999,999,999 shows exactly. Like C's `%g`, a value +//! integer up to 9,999,999,999,999,999 shows exactly. A decimal keeps 28 +//! places rather than 28 significant digits, so a ×, ÷ or ^ result below +//! 10⁻¹³ is worked out in `f64` instead and shows 15 digits. A fractional +//! power is approximate, so it stays an `f64` too, unless the answer is +//! exact (`4 ^ 0.5` is 2). Like C's `%g`, a value //! switches to exponent form (`1.5e+20`, `1e-05`) when its exponent is below //! −4 or at least the precision (16 for exact values, 15 for `f64`). @@ -21,6 +25,12 @@ use rust_decimal::{Decimal, MathematicalOps}; const EXACT_DIGITS: u32 = 16; /// Significant digits shown for an `f64` value: what a double holds reliably. const FLOAT_DIGITS: u32 = 15; +/// Significant digits every exact result except a division's is rounded to, +/// leaving guard digits below a decimal's 28 (see [`Num::combine`]). +const WORKING_DIGITS: u32 = 25; +/// The smallest power of ten a decimal's 28 places still hold to 16 +/// significant digits (10⁻¹³ down to 10⁻²⁸). +const SMALLEST_FULL_EXPONENT: i32 = -13; /// What the display says when a calculation has no answer. pub const ERROR_TEXT: &str = "Error"; @@ -91,8 +101,12 @@ impl Num { } } - /// An `f64` result, made exact again when its 15 significant digits fit - /// a decimal, so later steps stay exact (`4 ^ 0.5` is exactly 2). + /// An `f64` result. It stays approximate unless it's exactly what a + /// decimal would hold: a whole number, or a value whose 15-digit text + /// reads back as the very same `f64` (so `4 ^ 0.5` is exactly 2, and + /// `0.25 ^ 0.5` is exactly 0.5). Anything else, like `2 ^ 0.5`, stays an + /// `f64`, so arithmetic on it stays in `f64` and shows 15 digits, as + /// omacalc does: `2 ^ 0.5 × 2 ^ 0.5` is 2, not 2.000000000000014. fn from_f64(value: f64) -> Answer { if !value.is_finite() { return Err(NoAnswer); @@ -100,43 +114,74 @@ impl Num { if value == 0.0 { return Ok(Num::ZERO); } + if value.fract() == 0.0 { + return Ok(match Decimal::from_f64_retain(value) { + Some(d) => Num::Exact(d.normalize()), + None => Num::Float(value), + }); + } let text = format!("{:.*e}", FLOAT_DIGITS as usize - 1, value); + let round_trips = f64::from_str(&text).is_ok_and(|back| back == value); match Decimal::from_scientific(&text) { - // A value below a decimal's 28 places would round away: keep it - // as a float. - Ok(d) if !d.is_zero() && d.normalize().scale() < 28 => Ok(Num::Exact(d.normalize())), + // Below a decimal's 28 places the value would round away. + Ok(d) if round_trips && !d.is_zero() && d.normalize().scale() <= 28 => { + Ok(Num::Exact(d.normalize())) + } _ => Ok(Num::Float(value)), } } - /// Applies an exact operation, falling back to `f64` when the decimal - /// overflows or underflows to zero. + /// Applies the exact operation when both sides are exact and the + /// decimal holds the answer well; otherwise the `f64` one. + /// + /// `rounds`: round the result to [`WORKING_DIGITS`]. Division is the one + /// exact operation that is itself inexact (1 ÷ 3 stops after 28 places), + /// so its result keeps all 28 places, and every other result is rounded + /// to 25 significant digits. The digits below that are guard digits: + /// they absorb a division's last-place error, so 1 ÷ 3 × 3 is exactly 1 + /// and 1 ÷ 3 × 3 − 1 is exactly 0, not −1e-28. Rounding the division + /// itself instead would keep its error (25 threes × 3 is 25 nines). 25 + /// digits is still far more than the 16 shown, so nothing a person can + /// type or see is rounded by it. + /// + /// `loses_digits`: the operation can make more digits than it keeps + /// (× and ÷). A decimal keeps 28 places, not 28 significant digits, so a + /// result below 10⁻¹³ would show fewer than 16 digits, and one that + /// rounds to zero would be lost. Those are redone in `f64`. fn combine( self, other: Num, exact: impl Fn(Decimal, Decimal) -> Option, float: impl Fn(f64, f64) -> f64, - may_underflow: bool, + rounds: bool, + loses_digits: bool, ) -> Answer { if let (Num::Exact(a), Num::Exact(b)) = (self, other) && let Some(result) = exact(a, b) - && !(may_underflow && result.is_zero() && !a.is_zero()) { - return Ok(Num::Exact(result.normalize())); + let result = if rounds { + round_working(result) + } else { + result + }; + let zero_ok = a.is_zero() || b.is_zero(); + if !loses_digits || keeps_full_precision(result, zero_ok) { + return Ok(Num::Exact(result.normalize())); + } } Num::from_f64(float(self.to_f64(), other.to_f64())) } fn apply(self, op: Op, other: Num) -> Answer { match op { - Op::Add => self.combine(other, Decimal::checked_add, |a, b| a + b, false), - Op::Sub => self.combine(other, Decimal::checked_sub, |a, b| a - b, false), - Op::Mul => self.combine(other, Decimal::checked_mul, |a, b| a * b, true), + Op::Add => self.combine(other, Decimal::checked_add, |a, b| a + b, true, false), + Op::Sub => self.combine(other, Decimal::checked_sub, |a, b| a - b, true, false), + Op::Mul => self.combine(other, Decimal::checked_mul, |a, b| a * b, true, true), Op::Div => { if other.is_zero() { return Err(NoAnswer); } - self.combine(other, Decimal::checked_div, |a, b| a / b, true) + self.combine(other, Decimal::checked_div, |a, b| a / b, false, true) } Op::Pow => self.pow(other), } @@ -160,8 +205,8 @@ impl Num { if let (Num::Exact(base), Num::Exact(e)) = (self, exponent) && whole && let Ok(e) = i64::try_from(e.mantissa() / 10i128.pow(e.scale())) - && let Some(result) = base.checked_powi(e) - && (!result.is_zero() || base.is_zero()) + && let Some(result) = base.checked_powi(e).map(round_working) + && keeps_full_precision(result, base.is_zero()) { return Ok(Num::Exact(result.normalize())); } @@ -177,6 +222,24 @@ impl Num { } } +/// Rounds a result to the working precision (see [`Num::combine`]). +fn round_working(value: Decimal) -> Decimal { + value.round_sf(WORKING_DIGITS).unwrap_or(value) +} + +/// Whether an exact result of ×, ÷ or ^ still has every digit the display +/// needs: it's at least 10⁻¹³, so 28 places hold 16 significant digits, or +/// it's zero and zero is the true answer. +fn keeps_full_precision(value: Decimal, zero_ok: bool) -> bool { + if value.is_zero() { + return zero_ok; + } + let normal = value.normalize(); + let digits = normal.mantissa().unsigned_abs().ilog10() as i32 + 1; + // The first digit is worth 10^(digits − 1 − scale). + digits - 1 - normal.scale() as i32 >= SMALLEST_FULL_EXPONENT +} + /// Rounds to 16 significant digits and lays the digits out. fn format_exact(value: Decimal) -> String { if value.is_zero() { @@ -378,7 +441,10 @@ impl Calc { /// Replaces the number being typed with a pasted one. Accepts spaces /// around it, thousands separators in groups of three (`1,234,567.89`), /// a decimal comma (`1,5`) and the `−` this calculator shows. Anything - /// else is ignored, and the return value says whether it was taken. + /// else, including a lone comma at either end (`1,`, `,5`), is ignored, + /// and the return value says whether it was taken. The number is shown + /// as the display shows it, so one with more than 16 significant digits + /// (a long integer, say) is rounded to 16. pub fn paste(&mut self, text: &str) -> bool { let mut text: String = text .trim() @@ -386,6 +452,10 @@ impl Calc { .chars() .filter(|c| *c != ' ') .collect(); + let body = text.strip_prefix('-').unwrap_or(&text); + if body.starts_with(',') || body.ends_with(',') { + return false; + } if is_grouped(&text) { text.retain(|c| c != ','); } @@ -792,6 +862,54 @@ mod tests { assert_eq!(shows(". 1 ^ 4 0 ="), "1e-40"); } + /// A decimal keeps 28 places, not 28 significant digits: small results + /// of ×, ÷ and ^ are worked out in f64 so they keep their digits. + #[test] + fn small_results_keep_their_digits() { + assert_eq!( + shows("1 ÷ 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 ="), + format_float(1.0 / 300000000000000.0) + ); + assert_eq!( + shows("1 ÷ 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 ="), + "3.33333333333333e-15" + ); + assert_eq!(shows(". 7 ^ 1 0 0 ="), format_float(0.7f64.powf(100.0))); + assert_eq!(shows(". 7 ^ 1 0 0 =").len(), "3.23447650962474e-16".len()); + // Exact small values that fit stay exact. + assert_eq!(shows(". 0 0 0 1 × . 0 0 0 1 ="), "1e-08"); + assert_eq!(shows("1 ÷ 8 ="), "0.125"); + } + + /// Guard digits absorb a division's last-place error. + #[test] + fn division_residue_cancels() { + assert_eq!(shows("1 ÷ 3 × 3 - 1 ="), "0"); + assert_eq!(shows("2 ÷ 3 × 3 - 2 ="), "0"); + assert_eq!(shows("1 ÷ 3 = × 3 = - 1 ="), "0"); + assert_eq!(shows("1 ÷ 7 × 7 - 1 ="), "0"); + assert_eq!(shows("1 0 ÷ 3 × 3 - 1 0 ="), "0"); + assert_eq!(shows("1 ÷ 3 = × 3 ="), "1"); + assert_eq!(shows("0 . 1 + 0 . 2 ="), "0.3"); + assert_eq!(shows("0 . 1 + 0 . 2 - 0 . 3 ="), "0"); + } + + /// A fractional power is approximate, so arithmetic on it stays in f64. + #[test] + fn fractional_powers_stay_approximate() { + assert_eq!(shows("2 ^ . 5 × 2 ^ . 5 ="), "2"); + let cubed = 10f64.powf(0.3) * 10f64.powf(0.3) * 10f64.powf(0.3); + assert_eq!( + shows("1 0 ^ . 3 × 1 0 ^ . 3 × 1 0 ^ . 3 ="), + format_float(cubed) + ); + assert_eq!(shows("4 ^ . 5 ="), "2"); + assert_eq!(shows("9 ^ . 5 ="), "3"); + assert_eq!(shows(". 2 5 ^ . 5 ="), "0.5"); + // An exact power result stays exact in later steps. + assert_eq!(shows("4 ^ . 5 + 0 . 1 ="), "2.1"); + } + #[test] fn error_then_digit_starts_fresh() { let mut calc = Calc::new(); @@ -1010,6 +1128,21 @@ mod tests { } } + #[test] + fn paste_refuses_a_lone_end_comma() { + let mut calc = Calc::new(); + for junk in ["1,", ",5", "5,", "-,5", "-5,", ",", "1,234,"] { + assert!(!calc.paste(junk), "{junk:?} should be refused"); + } + assert_eq!(calc.display(), "0"); + assert!(calc.paste("12,34")); + assert_eq!(calc.display(), "12.34"); + assert!(calc.paste("1,234")); + assert_eq!(calc.display(), "1,234"); + assert!(calc.paste("12345678901234567890")); + assert_eq!(calc.display(), "1.234567890123457e+19"); + } + #[test] fn paste_replaces_a_result() { let mut calc = Calc::new(); From 764ee8108cd191a5b67df0240c750ae1ef0a2c2e Mon Sep 17 00:00:00 2001 From: Michael Aguiar Date: Wed, 25 Nov 2026 12:37:22 -0700 Subject: [PATCH 15/50] Tear input down with its seat, stop repeat when disabled, never starve it From review: SCTK reports a removed seat only through remove_seat, which did nothing, so a Backspace held while its seat went away kept repeating and a lit key stayed lit; a compositor switching repeat off mid-hold left the repeat running at the 40 ms fallback; a socket kept busy (pointer motion while Backspace is held) kept poll from timing out, delaying the repeat; tearing down input cleared the lit key without a redraw; the numpad decimal key on decimal-comma layouts (KP_Separator) and a dead ^ did nothing. remove_seat and remove_capability now share drop_keyboard/drop_pointer, which also redraw; RepeatInfo::Disable clears a running repeat; a due repeat fires at the top of the loop as well as on a poll timeout; KP_Separator is the decimal point and dead_circumflex is ^. ALI-2101 --- src/input.rs | 11 +++++-- src/window.rs | 87 +++++++++++++++++++++++++++++++++++++-------------- 2 files changed, 72 insertions(+), 26 deletions(-) diff --git a/src/input.rs b/src/input.rs index 9a70b22..4ae4cba 100644 --- a/src/input.rs +++ b/src/input.rs @@ -20,12 +20,17 @@ pub fn key_for(sym: Keysym) -> Option { Keysym::_7 | Keysym::KP_7 | Keysym::KP_Home => Key::Digit(7), Keysym::_8 | Keysym::KP_8 | Keysym::KP_Up => Key::Digit(8), Keysym::_9 | Keysym::KP_9 | Keysym::KP_Prior => Key::Digit(9), - Keysym::period | Keysym::KP_Decimal | Keysym::KP_Delete => Key::Point, + // KP_Separator is the numpad's decimal key on layouts with a decimal + // comma (German, French). + Keysym::period | Keysym::KP_Decimal | Keysym::KP_Separator | Keysym::KP_Delete => { + Key::Point + } Keysym::plus | Keysym::KP_Add => Key::Op(Op::Add), Keysym::minus | Keysym::KP_Subtract => Key::Op(Op::Sub), Keysym::asterisk | Keysym::KP_Multiply | Keysym::x | Keysym::X => Key::Op(Op::Mul), Keysym::slash | Keysym::KP_Divide => Key::Op(Op::Div), - Keysym::asciicircum => Key::Op(Op::Pow), + // ^ is a dead key on many European layouts. + Keysym::asciicircum | Keysym::dead_circumflex => Key::Op(Op::Pow), Keysym::percent => Key::Percent, Keysym::Return | Keysym::KP_Enter | Keysym::equal | Keysym::KP_Equal => Key::Equals, Keysym::BackSpace => Key::Backspace, @@ -59,6 +64,8 @@ mod tests { } assert_eq!(key_for(Keysym::KP_Delete), Some(Key::Point)); assert_eq!(key_for(Keysym::KP_Enter), Some(Key::Equals)); + assert_eq!(key_for(Keysym::KP_Separator), Some(Key::Point)); + assert_eq!(key_for(Keysym::dead_circumflex), Some(Key::Op(Op::Pow))); } #[test] diff --git a/src/window.rs b/src/window.rs index 9d5a869..7c0d0f0 100644 --- a/src/window.rs +++ b/src/window.rs @@ -3,8 +3,8 @@ //! `viewporter`. //! //! Everything runs on the one thread. The loop blocks in `poll` on the -//! Wayland socket and only wakes when the compositor sends something, so an -//! idle window costs no CPU at all. +//! Wayland socket and only wakes when the compositor sends something (or a +//! held Backspace is due to repeat), so an idle window costs no CPU at all. use std::error::Error; use std::time::{Duration, Instant}; @@ -143,6 +143,7 @@ pub fn run() -> Result<(), Box> { drawn: false, keyboard_seat: None, pointer_seat: None, + input_seat: None, dirty: false, exit: false, }; @@ -153,13 +154,23 @@ pub fn run() -> Result<(), Box> { type Queue = smithay_client_toolkit::reexports::client::EventQueue; /// Dispatch, draw if anything changed, then sleep until the compositor -/// writes to the socket. No timeouts: an idle window never wakes. +/// writes to the socket. The only timeout is a held Backspace's next +/// repeat, so an idle window never wakes. fn event_loop(queue: &mut Queue, app: &mut App) -> Result<(), Box> { loop { queue.dispatch_pending(app)?; if app.exit { return Ok(()); } + // A busy socket (pointer motion while Backspace is held) would keep + // poll from ever timing out, so a due repeat fires here too. + if app + .repeat + .as_ref() + .is_some_and(|r| r.next <= Instant::now()) + { + app.repeat_tick(); + } if app.dirty && app.configured { app.draw()?; if app.keyboard_seat.is_some() || app.pointer_seat.is_some() { @@ -199,9 +210,9 @@ fn event_loop(queue: &mut Queue, app: &mut App) -> Result<(), Box> { } }); match poll(&mut fds, timeout.as_ref()) { + // The repeat's time came: the top of the loop fires it. Ok(0) => { drop(guard); - app.repeat_tick(); continue; } Ok(_) => {} @@ -267,6 +278,8 @@ struct App { /// Seats whose keyboard and pointer wait for the first frame. keyboard_seat: Option, pointer_seat: Option, + /// The seat the keyboard and pointer were bound from. + input_seat: Option, /// Something changed since the last frame. dirty: bool, exit: bool, @@ -280,7 +293,34 @@ struct Repeat { } impl App { + /// Forgets the keyboard and anything it held: a lit key, a repeat. + fn drop_keyboard(&mut self) { + self.keyboard_seat = None; + if let Some(keyboard) = self.keyboard.take() { + keyboard.release(); + } + if self.key_down.take().is_some() { + self.dirty = true; + } + self.repeat = None; + } + + /// Forgets the pointer and a button it held down. + fn drop_pointer(&mut self) { + self.pointer_seat = None; + if let Some(cursor) = self.cursor.take() { + cursor.destroy(); + } + if let Some(pointer) = self.pointer.take() { + pointer.release(); + } + if self.mouse_down.take().is_some() { + self.dirty = true; + } + } + fn bind_keyboard(&mut self, qh: &QueueHandle, seat: &wl_seat::WlSeat) { + self.input_seat = Some(seat.clone()); match self.seats.get_keyboard(qh, seat, None) { Ok(keyboard) => self.keyboard = Some(keyboard), Err(err) => eprintln!("alias-calc: no keyboard: {err}"), @@ -288,6 +328,7 @@ impl App { } fn bind_pointer(&mut self, qh: &QueueHandle, seat: &wl_seat::WlSeat) { + self.input_seat = Some(seat.clone()); match self.seats.get_pointer(qh, seat) { Ok(pointer) => { self.cursor = self @@ -550,31 +591,26 @@ impl SeatHandler for App { _: wl_seat::WlSeat, capability: Capability, ) { - if capability == Capability::Keyboard { - self.keyboard_seat = None; + match capability { + Capability::Keyboard => self.drop_keyboard(), + Capability::Pointer => self.drop_pointer(), + _ => {} } - if capability == Capability::Pointer { - self.pointer_seat = None; + } + + /// SCTK reports a removed seat only here, without removing its + /// capabilities first, so the same teardown happens. + fn remove_seat(&mut self, _: &Connection, _: &QueueHandle, seat: wl_seat::WlSeat) { + if self.keyboard_seat.as_ref() == Some(&seat) || self.input_seat.as_ref() == Some(&seat) { + self.drop_keyboard(); } - if capability == Capability::Keyboard - && let Some(keyboard) = self.keyboard.take() - { - keyboard.release(); - self.key_down = None; - self.repeat = None; + if self.pointer_seat.as_ref() == Some(&seat) || self.input_seat.as_ref() == Some(&seat) { + self.drop_pointer(); } - if capability == Capability::Pointer - && let Some(pointer) = self.pointer.take() - { - if let Some(cursor) = self.cursor.take() { - cursor.destroy(); - } - pointer.release(); - self.mouse_down = None; + if self.input_seat.as_ref() == Some(&seat) { + self.input_seat = None; } } - - fn remove_seat(&mut self, _: &Connection, _: &QueueHandle, _: wl_seat::WlSeat) {} } impl KeyboardHandler for App { @@ -692,6 +728,9 @@ impl KeyboardHandler for App { )), RepeatInfo::Disable => None, }; + if self.repeat_rate.is_none() { + self.repeat = None; + } } } From f0c973aac99ea642f4bf7db63cb1e9124f750406 Mon Sep 17 00:00:00 2001 From: Michael Aguiar Date: Wed, 25 Nov 2026 12:43:08 -0700 Subject: [PATCH 16/50] Paste spaces only as separators, keep a pending paste, follow aliasOS's shortcuts From review: paste dropped every space, so "2026 11 25" and "555 1234" were taken as numbers, while the no-break spaces locales group digits with were refused; a second Ctrl+V that couldn't start cancelled a paste still being read; the data device outlived a removed keyboard; aliasOS's universal Super+C/V reach some apps as Ctrl+Insert / Shift+Insert, which did nothing. Spaces (plain, no-break, thin, narrow no-break) are now taken only as thousands separators in groups of three; a paste that can't start leaves the pending one alone; dropping the keyboard drops its data device; Ctrl+Insert copies and Shift+Insert pastes. ALI-2102 --- src/engine.rs | 40 ++++++++++++++++++++++++++++++++++------ src/window.rs | 21 +++++++++++++++++++-- 2 files changed, 53 insertions(+), 8 deletions(-) diff --git a/src/engine.rs b/src/engine.rs index 7d7a57c..e3b93d1 100644 --- a/src/engine.rs +++ b/src/engine.rs @@ -446,12 +446,23 @@ impl Calc { /// as the display shows it, so one with more than 16 significant digits /// (a long integer, say) is rounded to 16. pub fn paste(&mut self, text: &str) -> bool { - let mut text: String = text - .trim() - .replace('−', "-") - .chars() - .filter(|c| *c != ' ') - .collect(); + let text = text.trim().replace('−', "-"); + // Spaces (and the no-break ones locales group digits with) are taken + // only as thousands separators: "1 234,5" is a number, "2026 11 25" + // and "555 1234" aren't. + let is_space = |c: char| matches!(c, ' ' | '\u{a0}' | '\u{2009}' | '\u{202f}'); + let mut text = if text.contains(is_space) { + let whole = text.split(['.', ',']).next().unwrap_or(""); + if text.contains(',') && text.contains(is_space) && whole.contains(',') { + return false; + } + if !is_grouped(&whole.replace(is_space, ",")) { + return false; + } + text.replace(is_space, "") + } else { + text + }; let body = text.strip_prefix('-').unwrap_or(&text); if body.starts_with(',') || body.ends_with(',') { return false; @@ -1128,6 +1139,23 @@ mod tests { } } + #[test] + fn paste_takes_spaces_only_as_thousands_separators() { + for (text, shown) in [ + ("1 234", "1,234"), + ("1\u{a0}234,5", "1,234.5"), + ("1\u{202f}234\u{202f}567.89", "1,234,567.89"), + (" 42 ", "42"), + ] { + let mut calc = Calc::new(); + assert!(calc.paste(text), "{text:?}"); + assert_eq!(calc.display(), shown, "{text:?}"); + } + for text in ["2026 11 25", "555 1234", "12 34", "1 23"] { + assert!(!Calc::new().paste(text), "{text:?} isn't a number"); + } + } + #[test] fn paste_refuses_a_lone_end_comma() { let mut calc = Calc::new(); diff --git a/src/window.rs b/src/window.rs index 279a1df..e57a8d9 100644 --- a/src/window.rs +++ b/src/window.rs @@ -371,6 +371,9 @@ impl App { self.dirty = true; } self.repeat = None; + // The data device belongs to the keyboard's seat; a keyboard bound + // later (maybe on another seat) makes a new one. + self.data_device = None; } /// Forgets the pointer and a button it held down. @@ -427,7 +430,10 @@ impl App { let Some(format) = offer.with_mime_types(clipboard::pick_format) else { return; }; - self.paste = offer.receive(format).ok().and_then(Paste::new); + // A paste that can't start leaves one still being read alone. + if let Some(paste) = offer.receive(format).ok().and_then(Paste::new) { + self.paste = Some(paste); + } } /// Takes a paste's read result: keeps reading, or pastes the text. @@ -779,14 +785,25 @@ impl KeyboardHandler for App { ) { let m = self.modifiers; // Ctrl+C / Super+C copy and Ctrl+V / Super+V paste, as in omacalc. + // aliasOS's universal Super+C/V reach apps as Ctrl+C/V, or as + // Ctrl+Insert / Shift+Insert for some, so those work too. if (m.ctrl || m.logo) && !m.alt && !m.shift { match event.keysym { - Keysym::c | Keysym::C => self.copy(qh, serial), + Keysym::c | Keysym::C | Keysym::Insert | Keysym::KP_Insert => self.copy(qh, serial), Keysym::v | Keysym::V => self.paste(), _ => {} } return; } + if m.shift + && !m.ctrl + && !m.alt + && !m.logo + && matches!(event.keysym, Keysym::Insert | Keysym::KP_Insert) + { + self.paste(); + return; + } // Other chords belong to the compositor, never to the keypad. if m.ctrl || m.alt || m.logo { return; From 017df23cf25a63aa0866acb9c778f5a11a8d8e1d Mon Sep 17 00:00:00 2001 From: Michael Aguiar Date: Wed, 25 Nov 2026 12:47:06 -0700 Subject: [PATCH 17/50] Don't wake for theme.name writes; ignore an empty HOME From review round 2: CLOSE_WRITE never matched (a theme arrives as a moved or created entry named theme) but woke the loop for the theme.name and theme.generation writes on every switch; an empty HOME made the theme paths relative to the working directory. ALI-2103 --- src/theme.rs | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/src/theme.rs b/src/theme.rs index 868925d..aa69006 100644 --- a/src/theme.rs +++ b/src/theme.rs @@ -24,7 +24,11 @@ use crate::ui::Palette; /// Omarchy's scripts hard-code them (neither follows `XDG_STATE_HOME` or /// `XDG_CONFIG_HOME`). fn sources() -> Vec { - let Some(home) = std::env::var_os("HOME").map(PathBuf::from) else { + // An empty HOME would make these relative to the working directory. + let Some(home) = std::env::var_os("HOME") + .filter(|h| !h.is_empty()) + .map(PathBuf::from) + else { return Vec::new(); }; vec![ @@ -111,7 +115,11 @@ impl Watch { fn on(sources: &[PathBuf]) -> Option { let fd = inotify::init(CreateFlags::CLOEXEC | CreateFlags::NONBLOCK).ok()?; - let flags = WatchFlags::MOVED_TO | WatchFlags::CREATE | WatchFlags::CLOSE_WRITE; + // A theme arrives as an entry named `theme` moved or created in + // `current/` (a directory or a symlink, never written in place), so + // file writes beside it (theme.name, theme.generation) aren't asked + // for and don't wake the loop. + let flags = WatchFlags::MOVED_TO | WatchFlags::CREATE; let watched = sources .iter() .filter(|dir| inotify::add_watch(&fd, dir.as_path(), flags).is_ok()) From e794eabb57016581f918809fc2f09aeda683355e Mon Sep 17 00:00:00 2001 From: Michael Aguiar Date: Wed, 25 Nov 2026 12:47:46 -0700 Subject: [PATCH 18/50] Forget modifiers with focus, stop repeat on a chord, end a press on leave From review round 2: modifiers held when the keyboard left or was removed stayed set, so keys were ignored until the next modifiers event; a held Backspace kept repeating after Ctrl, Alt or Super went down; a mouse press survived a pointer leave without a release; View::pressed's doc said mouse only. ALI-2101 --- src/ui.rs | 3 ++- src/window.rs | 13 ++++++++++++- 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/src/ui.rs b/src/ui.rs index 9ec2830..fab9f20 100644 --- a/src/ui.rs +++ b/src/ui.rs @@ -134,7 +134,8 @@ fn contrast(a: Color, b: Color) -> f32 { pub struct View<'a> { pub expression: &'a str, pub display: &'a str, - /// The key held down with the mouse, as (row, column). + /// The key drawn pressed, held with the mouse or the keyboard, as + /// (row, column). pub pressed: Option<(usize, usize)>, } diff --git a/src/window.rs b/src/window.rs index 7c0d0f0..4c2d031 100644 --- a/src/window.rs +++ b/src/window.rs @@ -303,6 +303,7 @@ impl App { self.dirty = true; } self.repeat = None; + self.modifiers = Modifiers::default(); } /// Forgets the pointer and a button it held down. @@ -639,6 +640,9 @@ impl KeyboardHandler for App { self.dirty = true; } self.repeat = None; + // Modifiers released elsewhere aren't reported either; the next + // enter sends the real state. + self.modifiers = Modifiers::default(); } fn press_key( @@ -712,6 +716,11 @@ impl KeyboardHandler for App { _: u32, ) { self.modifiers = modifiers; + // A chord starting mid-repeat (Super for a shortcut) mustn't keep + // deleting digits. + if modifiers.ctrl || modifiers.alt || modifiers.logo { + self.repeat = None; + } } fn update_repeat_info( @@ -754,7 +763,9 @@ impl PointerHandler for App { cursor.set_shape(serial, Shape::Default); } } - PointerEventKind::Leave { .. } => {} + // A press that leaves without a release (the compositor + // took the pointer) is over. + PointerEventKind::Leave { .. } => self.mouse_down = None, PointerEventKind::Press { button: BTN_LEFT, .. } => { From fb4fe78cb577ab8fb06013c7bc5958ac7e6e5114 Mon Sep 17 00:00:00 2001 From: Michael Aguiar Date: Wed, 25 Nov 2026 12:49:20 -0700 Subject: [PATCH 19/50] No spaces after the decimal mark, leave numpad 0 alone, document use From review round 2: "1 234.5 6" pasted as 1234.56, since only the whole part was checked for spaces (and a guard on it could never be true); Shift or Ctrl with numpad 0 under NumLock (KP_Insert) pasted or copied instead of typing 0. Only the main Insert key now takes part in those chords. The README gains a Use section. ALI-2102 --- README.md | 9 +++++++++ src/engine.rs | 18 ++++++++++++------ src/window.rs | 11 ++++------- 3 files changed, 25 insertions(+), 13 deletions(-) diff --git a/README.md b/README.md index 6be25a6..b80a590 100644 --- a/README.md +++ b/README.md @@ -4,6 +4,15 @@ A tiny, instant calculator for aliasOS. It starts faster, uses less memory and w Linear project: Alias Calc (P-ALI-28). +## Use + +The keypad works with the mouse or the keyboard: `0-9 . + - * x / ^ %`, Enter or `=`, Backspace (held, it repeats), `C` or Escape to clear, and `S` to change sign. The numpad works with NumLock on or off. + +- Ctrl+C (or Super+C, or Ctrl+Insert) copies the result without separators. +- Ctrl+V (or Super+V, or Shift+Insert) pastes a number, with or without separators: `1,234.5`, `1 234,5` and `12,34` all work. Anything that isn't a number is ignored. + +Colors follow the live aliasOS theme (`~/.local/state/aliasos/current/theme/colors.toml`), falling back to Omarchy's, and change as soon as the theme does. + ## Build ```sh diff --git a/src/engine.rs b/src/engine.rs index e3b93d1..2c11bce 100644 --- a/src/engine.rs +++ b/src/engine.rs @@ -452,11 +452,9 @@ impl Calc { // and "555 1234" aren't. let is_space = |c: char| matches!(c, ' ' | '\u{a0}' | '\u{2009}' | '\u{202f}'); let mut text = if text.contains(is_space) { - let whole = text.split(['.', ',']).next().unwrap_or(""); - if text.contains(',') && text.contains(is_space) && whole.contains(',') { - return false; - } - if !is_grouped(&whole.replace(is_space, ",")) { + let (whole, fraction) = text.split_once(['.', ',']).unwrap_or((&text, "")); + // Grouping is for whole numbers only: "1 234.5 6" isn't a number. + if fraction.contains(is_space) || !is_grouped(&whole.replace(is_space, ",")) { return false; } text.replace(is_space, "") @@ -1146,12 +1144,20 @@ mod tests { ("1\u{a0}234,5", "1,234.5"), ("1\u{202f}234\u{202f}567.89", "1,234,567.89"), (" 42 ", "42"), + ("12 345 678", "12,345,678"), ] { let mut calc = Calc::new(); assert!(calc.paste(text), "{text:?}"); assert_eq!(calc.display(), shown, "{text:?}"); } - for text in ["2026 11 25", "555 1234", "12 34", "1 23"] { + for text in [ + "2026 11 25", + "555 1234", + "12 34", + "1 23", + "1 234.5 6", + "12 345,6 7", + ] { assert!(!Calc::new().paste(text), "{text:?} isn't a number"); } } diff --git a/src/window.rs b/src/window.rs index e57a8d9..a87dc8d 100644 --- a/src/window.rs +++ b/src/window.rs @@ -789,18 +789,15 @@ impl KeyboardHandler for App { // Ctrl+Insert / Shift+Insert for some, so those work too. if (m.ctrl || m.logo) && !m.alt && !m.shift { match event.keysym { - Keysym::c | Keysym::C | Keysym::Insert | Keysym::KP_Insert => self.copy(qh, serial), + // Only the main Insert key: Shift or Ctrl with numpad 0 under + // NumLock is KP_Insert, and that should stay a 0. + Keysym::c | Keysym::C | Keysym::Insert => self.copy(qh, serial), Keysym::v | Keysym::V => self.paste(), _ => {} } return; } - if m.shift - && !m.ctrl - && !m.alt - && !m.logo - && matches!(event.keysym, Keysym::Insert | Keysym::KP_Insert) - { + if m.shift && !m.ctrl && !m.alt && !m.logo && event.keysym == Keysym::Insert { self.paste(); return; } From d690076e87628fa40d65f49156a4e70cda647e7d Mon Sep 17 00:00:00 2001 From: Michael Aguiar Date: Wed, 25 Nov 2026 12:51:40 -0700 Subject: [PATCH 20/50] Fail the run without Alias Calc's row, kill leftover helpers From review round 2: bench/run exited 0 when Alias Calc's own measurement failed as long as another app was measured; stop() left helper processes in the app's group once the leader exited on SIGTERM; a missing XDG_RUNTIME_DIR gave a raw KeyError. Also ignore only .claude/worktrees/ rather than all of .claude/. ALI-2097 --- .gitignore | 1 + bench/calcbench.py | 10 +++++++++- bench/run | 7 +++++++ 3 files changed, 17 insertions(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index df611ec..a379f86 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,3 @@ /target __pycache__/ +/.claude/worktrees/ diff --git a/bench/calcbench.py b/bench/calcbench.py index 4d39a59..5895e26 100755 --- a/bench/calcbench.py +++ b/bench/calcbench.py @@ -32,7 +32,10 @@ def event_socket(): sig = os.environ.get("HYPRLAND_INSTANCE_SIGNATURE") if not sig: sys.exit("calcbench: needs a Hyprland session (HYPRLAND_INSTANCE_SIGNATURE is unset)") - return f"{os.environ['XDG_RUNTIME_DIR']}/hypr/{sig}/.socket2.sock" + runtime = os.environ.get("XDG_RUNTIME_DIR") + if not runtime: + sys.exit("calcbench: XDG_RUNTIME_DIR is unset") + return f"{runtime}/hypr/{sig}/.socket2.sock" def tree(pid): @@ -172,6 +175,11 @@ def stop(proc): break except subprocess.TimeoutExpired: continue + # Helpers the app started may outlive it in its group. + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass time.sleep(0.5) diff --git a/bench/run b/bench/run index 88b181a..db2ef20 100755 --- a/bench/run +++ b/bench/run @@ -35,6 +35,9 @@ bench() { } bench alias-calc com.aliasproject.calc "$target/release/alias-calc" +# The table still prints the others, but a run without Alias Calc's own row +# is a failure. +alias_calc_measured=${#results[@]} omacalc=${OMACALC:-$(command -v omacalc || true)} if [[ -n $omacalc ]]; then @@ -56,3 +59,7 @@ if ((${#results[@]} == 0)); then exit 1 fi printf '%s\n' "${results[@]}" | python3 -I bench/calcbench.py --table +if ((alias_calc_measured == 0)); then + echo "Alias Calc wasn't measured." >&2 + exit 1 +fi From 85790c91ed5b7c98bb9a32126b338ba01f8f699c Mon Sep 17 00:00:00 2001 From: Michael Aguiar Date: Wed, 25 Nov 2026 12:51:52 -0700 Subject: [PATCH 21/50] Merge the reviewed harness (ALI-2097) and end on a broken socket From review round 2: poll reporting HUP, ERR or NVAL without IN sent the loop round again, and poll would then return at once forever. The app now ends with an error instead. ALI-2098 --- src/window.rs | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/src/window.rs b/src/window.rs index ff770f5..7500db7 100644 --- a/src/window.rs +++ b/src/window.rs @@ -150,7 +150,15 @@ fn event_loop(queue: &mut Queue, app: &mut App) -> Result<(), Box> { Err(Errno::INTR) => continue, Err(err) => return Err(err.into()), } - if !fds[0].revents().contains(PollFlags::IN) { + let revents = fds[0].revents(); + // A broken socket without data to read would make poll return at + // once forever; there's nothing to recover, so end. + if !revents.contains(PollFlags::IN) + && revents.intersects(PollFlags::ERR | PollFlags::HUP | PollFlags::NVAL) + { + return Err("lost the connection to the compositor".into()); + } + if !revents.contains(PollFlags::IN) { // Only writable: go round and flush. drop(guard); continue; From 574364abd6c20704e3957ee0be90e8da841e0b30 Mon Sep 17 00:00:00 2001 From: Michael Aguiar Date: Wed, 25 Nov 2026 12:52:16 -0700 Subject: [PATCH 22/50] Use a fixed working precision, keep % exact, fix paste edge cases MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Exact results now use one rule (settle), with the same precision at every size: sums, products and powers round to 20 significant digits, and quotients round to 22, so the next rounding absorbs their error. A quotient that ends exactly is kept as it is. Guard digits counted in places ran out for small quotients (1 ÷ 3000 × 3000 − 1 gave -1e-25). - A power with a negative exponent is worked out as a reciprocal and settled as a quotient (7 ^ -1 × 7 − 1 gave -3e-25). - A cut-off quotient below 1e-7 and a product below 1e-13 go to f64. - % keeps the exact value behind its entry, so 1 ÷ 3 = % × 300 = is 1. - paste reads 0,123 as 0.123, not 123: a first group of 0 isn't a thousands group. It refuses 1e-400 instead of showing 0. - Display rounding is done by hand, so a value near Decimal::MAX shows 16 digits instead of 29. ALI-2100 --- src/engine.rs | 355 ++++++++++++++++++++++++++++++++++++++++---------- 1 file changed, 287 insertions(+), 68 deletions(-) diff --git a/src/engine.rs b/src/engine.rs index 7d7a57c..4fb997e 100644 --- a/src/engine.rs +++ b/src/engine.rs @@ -8,11 +8,23 @@ //! small numbers still work (shown to 15 significant digits, as omacalc does). //! //! The display rounds exact values to 16 significant digits, so every -//! integer up to 9,999,999,999,999,999 shows exactly. A decimal keeps 28 -//! places rather than 28 significant digits, so a ×, ÷ or ^ result below -//! 10⁻¹³ is worked out in `f64` instead and shows 15 digits. A fractional -//! power is approximate, so it stays an `f64` too, unless the answer is -//! exact (`4 ^ 0.5` is 2). Like C's `%g`, a value +//! integer up to 9,999,999,999,999,999 shows exactly. +//! +//! Exact results are worked to a fixed precision, whatever their size: every +//! sum, difference, product and power is rounded to 20 significant digits. +//! A quotient (÷, or a power with a negative exponent, which is a +//! reciprocal) keeps 22, unless it ends exactly. The two extra digits are +//! guard digits: the next rounding to 20 absorbs the quotient's last-place +//! error, so 1 ÷ 3 × 3 − 1 and 1 ÷ 7000 × 7000 − 1 are exactly 0. Twenty +//! digits is still more than the 16 shown, so nothing a person can type or +//! see is rounded by it. +//! +//! A decimal keeps 28 places rather than 28 significant digits, so small +//! values can't carry those digits. A product or power below 10⁻¹³ (fewer +//! than 16 digits in 28 places) and a quotient that doesn't end below 10⁻⁷ +//! (fewer than 22) are worked out in `f64` instead and show 15 digits, as +//! omacalc does. A fractional power is approximate, so it stays an `f64` +//! too, unless the answer is exact (`4 ^ 0.5` is 2). Like C's `%g`, a value //! switches to exponent form (`1.5e+20`, `1e-05`) when its exponent is below //! −4 or at least the precision (16 for exact values, 15 for `f64`). @@ -25,12 +37,20 @@ use rust_decimal::{Decimal, MathematicalOps}; const EXACT_DIGITS: u32 = 16; /// Significant digits shown for an `f64` value: what a double holds reliably. const FLOAT_DIGITS: u32 = 15; -/// Significant digits every exact result except a division's is rounded to, -/// leaving guard digits below a decimal's 28 (see [`Num::combine`]). -const WORKING_DIGITS: u32 = 25; -/// The smallest power of ten a decimal's 28 places still hold to 16 -/// significant digits (10⁻¹³ down to 10⁻²⁸). -const SMALLEST_FULL_EXPONENT: i32 = -13; +/// The working precision: every exact sum, difference, product and power is +/// rounded to this many significant digits (see [`settle`]). +const WORKING_DIGITS: u32 = 20; +/// Quotients (÷, and powers with a negative exponent) keep two more digits, +/// so the next rounding to [`WORKING_DIGITS`] absorbs their last-place error. +const QUOTIENT_DIGITS: u32 = WORKING_DIGITS + 2; +/// A decimal keeps this many places after the point, whatever its size. +const DECIMAL_PLACES: i32 = 28; +/// The smallest power of ten whose value 28 places hold to 16 significant +/// digits: 10⁻¹³. +const SMALLEST_FULL_EXPONENT: i32 = EXACT_DIGITS as i32 - 1 - DECIMAL_PLACES; +/// The smallest power of ten whose value 28 places hold to 22 significant +/// digits: 10⁻⁷. +const SMALLEST_QUOTIENT_EXPONENT: i32 = QUOTIENT_DIGITS as i32 - 1 - DECIMAL_PLACES; /// What the display says when a calculation has no answer. pub const ERROR_TEXT: &str = "Error"; @@ -131,42 +151,32 @@ impl Num { } } - /// Applies the exact operation when both sides are exact and the - /// decimal holds the answer well; otherwise the `f64` one. - /// - /// `rounds`: round the result to [`WORKING_DIGITS`]. Division is the one - /// exact operation that is itself inexact (1 ÷ 3 stops after 28 places), - /// so its result keeps all 28 places, and every other result is rounded - /// to 25 significant digits. The digits below that are guard digits: - /// they absorb a division's last-place error, so 1 ÷ 3 × 3 is exactly 1 - /// and 1 ÷ 3 × 3 − 1 is exactly 0, not −1e-28. Rounding the division - /// itself instead would keep its error (25 threes × 3 is 25 nines). 25 - /// digits is still far more than the 16 shown, so nothing a person can - /// type or see is rounded by it. - /// - /// `loses_digits`: the operation can make more digits than it keeps - /// (× and ÷). A decimal keeps 28 places, not 28 significant digits, so a - /// result below 10⁻¹³ would show fewer than 16 digits, and one that - /// rounds to zero would be lost. Those are redone in `f64`. + /// Applies the exact operation when both sides are exact and [`settle`] + /// accepts its result; otherwise the `f64` one. fn combine( self, other: Num, + kind: Kind, exact: impl Fn(Decimal, Decimal) -> Option, float: impl Fn(f64, f64) -> f64, - rounds: bool, - loses_digits: bool, ) -> Answer { if let (Num::Exact(a), Num::Exact(b)) = (self, other) && let Some(result) = exact(a, b) { - let result = if rounds { - round_working(result) - } else { - result + let zero_ok = match kind { + Kind::Sum => true, + Kind::Product => a.is_zero() || b.is_zero(), + Kind::Quotient { .. } => a.is_zero(), + }; + // A quotient ends exactly when it multiplies back to the dividend. + let kind = match kind { + Kind::Quotient { .. } => Kind::Quotient { + ends: result.checked_mul(b) == Some(a), + }, + kind => kind, }; - let zero_ok = a.is_zero() || b.is_zero(); - if !loses_digits || keeps_full_precision(result, zero_ok) { - return Ok(Num::Exact(result.normalize())); + if let Some(result) = settle(kind, result, zero_ok) { + return Ok(Num::Exact(result)); } } Num::from_f64(float(self.to_f64(), other.to_f64())) @@ -174,19 +184,27 @@ impl Num { fn apply(self, op: Op, other: Num) -> Answer { match op { - Op::Add => self.combine(other, Decimal::checked_add, |a, b| a + b, true, false), - Op::Sub => self.combine(other, Decimal::checked_sub, |a, b| a - b, true, false), - Op::Mul => self.combine(other, Decimal::checked_mul, |a, b| a * b, true, true), + Op::Add => self.combine(other, Kind::Sum, Decimal::checked_add, |a, b| a + b), + Op::Sub => self.combine(other, Kind::Sum, Decimal::checked_sub, |a, b| a - b), + Op::Mul => self.combine(other, Kind::Product, Decimal::checked_mul, |a, b| a * b), Op::Div => { if other.is_zero() { return Err(NoAnswer); } - self.combine(other, Decimal::checked_div, |a, b| a / b, false, true) + let quotient = Kind::Quotient { ends: false }; + self.combine(other, quotient, Decimal::checked_div, |a, b| a / b) } Op::Pow => self.pow(other), } } + fn negate(self) -> Num { + match self { + Num::Exact(d) => Num::Exact(-d), + Num::Float(f) => Num::Float(-f), + } + } + fn pow(self, exponent: Num) -> Answer { let whole = match exponent { Num::Exact(e) => e.is_integer(), @@ -205,10 +223,9 @@ impl Num { if let (Num::Exact(base), Num::Exact(e)) = (self, exponent) && whole && let Ok(e) = i64::try_from(e.mantissa() / 10i128.pow(e.scale())) - && let Some(result) = base.checked_powi(e).map(round_working) - && keeps_full_precision(result, base.is_zero()) + && let Some(result) = exact_integer_power(base, e) { - return Ok(Num::Exact(result.normalize())); + return Ok(Num::Exact(result)); } Num::from_f64(self.to_f64().powf(exponent.to_f64())) } @@ -222,22 +239,69 @@ impl Num { } } -/// Rounds a result to the working precision (see [`Num::combine`]). -fn round_working(value: Decimal) -> Decimal { - value.round_sf(WORKING_DIGITS).unwrap_or(value) +/// What an exact operation was, for [`settle`]. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Kind { + /// + or −. + Sum, + /// × or a power with a non-negative exponent. + Product, + /// ÷ or a power with a negative exponent (a reciprocal). `ends`: the + /// quotient is exact, like 1 ÷ 8, rather than cut off, like 1 ÷ 3. + Quotient { ends: bool }, } -/// Whether an exact result of ×, ÷ or ^ still has every digit the display -/// needs: it's at least 10⁻¹³, so 28 places hold 16 significant digits, or -/// it's zero and zero is the true answer. -fn keeps_full_precision(value: Decimal, zero_ok: bool) -> bool { +/// The one rule for exact results: rounds `value`, the raw result of an +/// exact operation, to the working precision, or says it must be redone in +/// `f64` (`None`). +/// +/// * A sum, difference, product or power is rounded to 20 significant +/// digits ([`WORKING_DIGITS`]). +/// * A quotient that's cut off is rounded to 22 ([`QUOTIENT_DIGITS`]). The +/// next rounding to 20 absorbs its last-place error, so 1 ÷ 3 × 3 is +/// exactly 1 and 1 ÷ 3000 × 3000 − 1 is exactly 0. The precision is the +/// same at every size: guard digits counted in places (a decimal's 28) +/// would run out for a small quotient like 1 ÷ 3000. +/// * A quotient that ends exactly (1 ÷ 8) is kept as it is. +/// * Small values can't carry those digits in 28 places, so they go to +/// `f64`: a product or power below 10⁻¹³ (16 digits shown) and a cut-off +/// quotient below 10⁻⁷ (22 digits kept). A zero is kept only when zero is +/// the true answer (`zero_ok`), not when a tiny product rounded away. +fn settle(kind: Kind, value: Decimal, zero_ok: bool) -> Option { if value.is_zero() { - return zero_ok; + return zero_ok.then_some(Decimal::ZERO); + } + let (digits, smallest) = match kind { + Kind::Sum => (WORKING_DIGITS, i32::MIN), + Kind::Product => (WORKING_DIGITS, SMALLEST_FULL_EXPONENT), + Kind::Quotient { ends: true } => return Some(value.normalize()), + Kind::Quotient { ends: false } => (QUOTIENT_DIGITS, SMALLEST_QUOTIENT_EXPONENT), + }; + if first_digit_exponent(value) < smallest { + return None; } + Some(value.round_sf(digits).unwrap_or(value).normalize()) +} + +/// The power of ten the first significant digit of a non-zero value is worth. +fn first_digit_exponent(value: Decimal) -> i32 { let normal = value.normalize(); let digits = normal.mantissa().unsigned_abs().ilog10() as i32 + 1; - // The first digit is worth 10^(digits − 1 − scale). - digits - 1 - normal.scale() as i32 >= SMALLEST_FULL_EXPONENT + digits - 1 - normal.scale() as i32 +} + +/// `base ^ e` for a whole `e`, exactly, or `None` to work it out in `f64`. A +/// negative power is the reciprocal of the positive one, so it's settled as +/// a quotient and gets the same guard digits as 1 ÷ x. +fn exact_integer_power(base: Decimal, e: i64) -> Option { + let power = base.checked_powu(e.unsigned_abs())?; + let power = settle(Kind::Product, power, base.is_zero())?; + if e >= 0 { + return Some(power); + } + let reciprocal = Decimal::ONE.checked_div(power)?; + let ends = reciprocal.checked_mul(power) == Some(Decimal::ONE); + settle(Kind::Quotient { ends }, reciprocal, false) } /// Rounds to 16 significant digits and lays the digits out. @@ -245,12 +309,47 @@ fn format_exact(value: Decimal) -> String { if value.is_zero() { return "0".into(); } - let rounded = value.round_sf(EXACT_DIGITS).unwrap_or(value).normalize(); - let mantissa = rounded.mantissa(); - let digits = mantissa.unsigned_abs().to_string(); + let normal = value.normalize(); + let mantissa = normal.mantissa(); + let all = mantissa.unsigned_abs().to_string(); // value = digits × 10^(−scale), so the first digit's power of ten is: - let exponent = digits.len() as i32 - 1 - rounded.scale() as i32; - layout(mantissa < 0, &digits, exponent, EXACT_DIGITS) + let exponent = all.len() as i32 - 1 - normal.scale() as i32; + // Rounded by hand: `round_sf` can't round a value near Decimal::MAX. + let (digits, carried) = round_digits(&all, EXACT_DIGITS as usize); + layout( + mantissa < 0, + &digits, + exponent + i32::from(carried), + EXACT_DIGITS, + ) +} + +/// Rounds a run of significant digits to `keep` of them, half away from +/// zero. Returns the digits and whether rounding carried into a new leading +/// digit (999… → 1000…). +fn round_digits(digits: &str, keep: usize) -> (String, bool) { + if digits.len() <= keep { + return (digits.to_owned(), false); + } + let mut kept: Vec = digits.as_bytes()[..keep].to_vec(); + if digits.as_bytes()[keep] >= b'5' { + let mut i = keep; + loop { + if i == 0 { + kept.insert(0, b'1'); + kept.pop(); + return (String::from_utf8(kept).unwrap_or_default(), true); + } + i -= 1; + if kept[i] == b'9' { + kept[i] = b'0'; + } else { + kept[i] += 1; + break; + } + } + } + (String::from_utf8(kept).unwrap_or_default(), false) } fn format_float(value: f64) -> String { @@ -360,7 +459,15 @@ fn parse_number(text: &str) -> Option { Some(d) if !(d.is_zero() && text.bytes().any(|b| (b'1'..=b'9').contains(&b))) => { Some(Num::Exact(d)) } - _ => Num::from_f64(f64::from_str(text).ok()?).ok(), + _ => { + let value = f64::from_str(text).ok()?; + // 1e-400 reads as 0 in f64: refuse it rather than show 0. + let nonzero = mantissa.bytes().any(|b| (b'1'..=b'9').contains(&b)); + if value == 0.0 && nonzero { + return None; + } + Num::from_f64(value).ok() + } } } @@ -379,6 +486,10 @@ pub struct Calc { /// The number being typed, as typed ("5.", "-0", "1.50"), or a whole /// value in exponent form from a percent or paste. entry: String, + /// The exact value behind `entry` when the calculator set it (a percent, + /// a paste, or a result being edited), so using it doesn't lose what the + /// 16-digit text rounds off. Typing into the entry drops it. + entry_value: Option, /// After `=`: the exact result, its display text, and the expression. result: Option<(Num, String)>, evaluated: String, @@ -466,6 +577,7 @@ impl Calc { self.clear(); } self.entry = value.format(); + self.entry_value = Some(value); true } @@ -474,6 +586,7 @@ impl Calc { // A digit after `=` starts a new calculation. self.clear(); } + self.entry_value = None; if in_exponent_form(&self.entry) { self.entry.clear(); } @@ -498,6 +611,7 @@ impl Calc { if self.errored || self.result.is_some() { self.clear(); } + self.entry_value = None; if in_exponent_form(&self.entry) { self.entry.clear(); } @@ -520,8 +634,9 @@ impl Calc { self.evaluated.clear(); } if !self.entry.is_empty() { - let value = seal(&self.entry); + let value = self.entry_num(); self.entry.clear(); + self.entry_value = None; self.tokens.push(Token::Num(value)); self.tokens.push(Token::Op(op)); } else if self.tokens.is_empty() { @@ -541,8 +656,9 @@ impl Calc { } let mut tokens = std::mem::take(&mut self.tokens); if !self.entry.is_empty() { - tokens.push(Token::Num(seal(&self.entry))); + tokens.push(Token::Num(self.entry_num())); self.entry.clear(); + self.entry_value = None; } // A trailing operator is dropped: 9 + = is 9. while let Some(Token::Op(_)) = tokens.last() { @@ -567,7 +683,7 @@ impl Calc { if let Some((value, _)) = self.result.take() { self.evaluated.clear(); match value.apply(Op::Div, Num::Exact(Decimal::ONE_HUNDRED)) { - Ok(percent) => self.entry = percent.format(), + Ok(percent) => self.set_entry(percent), Err(NoAnswer) => self.errored = true, } return; @@ -589,7 +705,7 @@ impl Calc { _ => value.apply(Op::Div, hundred), }; match percent { - Ok(percent) => self.entry = percent.format(), + Ok(percent) => self.set_entry(percent), Err(NoAnswer) => { let mut shown = self.tokens.clone(); shown.push(Token::Num(value)); @@ -597,6 +713,7 @@ impl Calc { self.errored = true; self.tokens.clear(); self.entry.clear(); + self.entry_value = None; } } } @@ -609,6 +726,7 @@ impl Calc { self.edit_result(); } // With nothing typed, start a fresh negative number: 4 + ± 2 is 4 + -2. + self.entry_value = self.entry_value.map(Num::negate); if self.entry.is_empty() { self.entry.push_str("-0"); } else if self.entry.starts_with('-') { @@ -626,6 +744,7 @@ impl Calc { if self.result.is_some() { self.edit_result(); } + self.entry_value = None; if in_exponent_form(&self.entry) { // Backspace on 1e+15 would leave 1e+1, which is 10: clear it. self.entry.clear(); @@ -641,6 +760,7 @@ impl Calc { fn clear(&mut self) { self.tokens.clear(); self.entry.clear(); + self.entry_value = None; self.result = None; self.evaluated.clear(); self.errored = false; @@ -649,18 +769,31 @@ impl Calc { /// Editing after `=` starts from the result's digits, with the old /// expression cleared. fn edit_result(&mut self) { - if let Some((_, text)) = self.result.take() { + if let Some((value, text)) = self.result.take() { self.entry = text; + self.entry_value = Some(value); } self.tokens.clear(); self.evaluated.clear(); } + /// Shows a value the calculator worked out as the entry, keeping it exact. + fn set_entry(&mut self, value: Num) { + self.entry = value.format(); + self.entry_value = Some(value); + } + + /// The entry's number: its exact value if the calculator set it, else + /// what was typed. + fn entry_num(&self) -> Num { + self.entry_value.unwrap_or_else(|| seal(&self.entry)) + } + /// The number the calculator is at: the one being typed, else the last /// one entered, else zero. fn current_value(&self) -> Num { if !self.entry.is_empty() { - return seal(&self.entry); + return self.entry_num(); } self.tokens .iter() @@ -693,7 +826,9 @@ fn significant_digits(entry: &str) -> usize { digits - usize::from(leading_zero) } -/// `1,234` or `-1,234,567.89`: commas exactly every three digits. +/// `1,234` or `-1,234,567.89`: commas exactly every three digits. A first +/// group of just `0` isn't a thousands group, so `0,500` is a decimal comma +/// (0.5), not 500. fn is_grouped(text: &str) -> bool { let body = text.strip_prefix('-').unwrap_or(text); let whole = body.split_once('.').map_or(body, |(w, _)| w); @@ -704,7 +839,8 @@ fn is_grouped(text: &str) -> bool { let Some(first) = groups.next() else { return false; }; - let first_ok = (1..=3).contains(&first.len()) && first.bytes().all(|b| b.is_ascii_digit()); + let first_ok = + (1..=3).contains(&first.len()) && first.bytes().all(|b| b.is_ascii_digit()) && first != "0"; let mut rest = groups.peekable(); let has_rest = rest.peek().is_some(); first_ok @@ -892,6 +1028,54 @@ mod tests { assert_eq!(shows("1 ÷ 3 = × 3 ="), "1"); assert_eq!(shows("0 . 1 + 0 . 2 ="), "0.3"); assert_eq!(shows("0 . 1 + 0 . 2 - 0 . 3 ="), "0"); + // Small quotients get the same guard digits as large ones. + assert_eq!(shows("1 ÷ 3 0 0 0 × 3 0 0 0 - 1 ="), "0"); + assert_eq!(shows("1 ÷ 3 0 0 0 0 × 3 0 0 0 0 - 1 ="), "0"); + assert_eq!(shows("2 ÷ 3 0 0 0 0 0 × 3 0 0 0 0 0 - 2 ="), "0"); + assert_eq!(shows("1 ÷ 7 0 0 0 × 7 0 0 0 - 1 ="), "0"); + assert_eq!(shows("1 ÷ 3 0 0 0 = × 3 0 0 0 = - 1 ="), "0"); + assert_eq!(shows("1 ÷ 3 0 0 0 0 × sign 3 0 0 0 0 + 1 ="), "0"); + // Below 1e-7 a cut-off quotient is an f64, shown at 15 digits. + assert_eq!( + shows("1 ÷ 3 0 0 0 0 0 0 0 0 0 0 0 0 × 3 0 0 0 0 0 0 0 0 0 0 0 0 ="), + "1" + ); + assert_eq!( + shows("1 ÷ 3 0 0 0 0 0 0 0 0 0 0 0 0 = × 3 0 0 0 0 0 0 0 0 0 0 0 0 ="), + "1" + ); + // A quotient that ends stays exact at any size. + assert_eq!( + shows("1 ÷ 1 0 0 0 0 0 0 0 0 × 1 0 0 0 0 0 0 0 0 - 1 ="), + "0" + ); + assert_eq!(shows("1 9 . 9 9 × 3 ="), "59.97"); + assert_eq!(shows("1 ÷ 3 ÷ 7 × 2 1 - 1 ="), "0"); + assert_eq!( + shows("1 0 ^ 2 7 + 1 - 1 0 ^ 2 7 ="), + "0", + "20 working digits drop the 1" + ); + } + + /// A negative power is a reciprocal and gets a quotient's guard digits. + #[test] + fn negative_powers_cancel() { + assert_eq!(shows("7 ^ 1 sign × 7 - 1 ="), "0"); + assert_eq!(shows("3 ^ 1 sign × 3 - 1 ="), "0"); + assert_eq!(shows("2 ^ 1 sign ="), "0.5"); + assert_eq!(shows("2 ^ 3 sign ="), "0.125"); + assert_eq!(shows("3 ^ 2 sign × 9 ="), "1"); + } + + /// % keeps the exact value, not its 16-digit text. + #[test] + fn percent_keeps_the_exact_value() { + assert_eq!(shows("1 ÷ 3 = % × 3 0 0 ="), "1"); + assert_eq!(shows("1 ÷ 3 = % × 3 0 0 - 1 ="), "0"); + // Editing it by hand goes back to the typed digits. + assert_eq!(shows("5 0 % 5"), "0.55"); + assert_eq!(shows("1 ÷ 3 = % sign × 3 0 0 ="), "-1"); } /// A fractional power is approximate, so arithmetic on it stays in f64. @@ -1143,6 +1327,41 @@ mod tests { assert_eq!(calc.display(), "1.234567890123457e+19"); } + /// A first group of just 0 can't be a thousands group. + #[test] + fn paste_reads_a_zero_comma_as_decimal() { + let mut calc = Calc::new(); + assert!(calc.paste("0,123")); + assert_eq!(calc.display(), "0.123"); + assert!(calc.paste("0,500")); + assert_eq!(calc.display(), "0.5"); + assert!(calc.paste("-0,500")); + assert_eq!(calc.display(), "-0.5"); + assert!(calc.paste("1,234")); + assert_eq!(calc.display(), "1,234"); + assert!(calc.paste("12,34")); + assert_eq!(calc.display(), "12.34"); + assert!(calc.paste("1 234,5")); + assert_eq!(calc.display(), "1,234.5"); + assert!(!calc.paste("0,123,456")); + assert!(!calc.paste(",5")); + } + + #[test] + fn paste_extremes() { + let mut calc = Calc::new(); + assert!(calc.paste("79228162514264337593543950335")); + assert_eq!(calc.display(), "7.922816251426434e+28"); + assert!(calc.paste("99999999999999999999")); + assert_eq!(calc.display(), "1e+20"); + assert!(!calc.paste("1e-400")); + assert_eq!(calc.display(), "1e+20"); + // A pasted long number is used exactly, though it shows 16 digits. + assert!(calc.paste("1234567890123456.7")); + press(&mut calc, "- 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 ="); + assert_eq!(calc.display(), "0.7"); + } + #[test] fn paste_replaces_a_result() { let mut calc = Calc::new(); From bfaab37a71d24d7a09dcd06da4fee8fc1fd11e12 Mon Sep 17 00:00:00 2001 From: Michael Aguiar Date: Wed, 25 Nov 2026 13:00:13 -0700 Subject: [PATCH 23/50] Snap cancellation to zero, keep large whole floats approximate MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Guard digits absorb one rounding, but a chain leaves residue at the 20th digit (1 ÷ 3 ÷ 3 × 3 × 3 − 1 gave -1e-20). A sum or difference that's at most 1e-18 of its larger operand (1e-14 when either is an f64) is now 0. Typed numbers carry at most 16 digits, so a real difference between them is never that small. - from_f64 promotes a whole f64 to exact only up to 2^53; above that it carries binary noise, so 1e30 × 1e-7 shows 1e+23, not 9.999999999999999e+22. ALI-2100 --- src/engine.rs | 84 +++++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 81 insertions(+), 3 deletions(-) diff --git a/src/engine.rs b/src/engine.rs index 4fb997e..dcc9086 100644 --- a/src/engine.rs +++ b/src/engine.rs @@ -19,6 +19,15 @@ //! digits is still more than the 16 shown, so nothing a person can type or //! see is rounded by it. //! +//! Guard digits absorb one rounding, but a chain of them can still leave +//! residue at the 20th digit (1 ÷ 3 ÷ 3 × 3 × 3 − 1). So a sum or difference +//! that's at most 10⁻¹⁸ of its larger operand (10⁻¹⁴ when either is an +//! `f64`) is cancellation, and is 0. That never hides a real difference +//! between typed numbers: they carry at most 16 significant digits, so they +//! differ by at least about 10⁻¹⁶ of their size. A pasted number with more +//! than 16 digits can lose a difference that small, as it can lose digits +//! to the 20-digit rounding. +//! //! A decimal keeps 28 places rather than 28 significant digits, so small //! values can't carry those digits. A product or power below 10⁻¹³ (fewer //! than 16 digits in 28 places) and a quotient that doesn't end below 10⁻⁷ @@ -51,6 +60,12 @@ const SMALLEST_FULL_EXPONENT: i32 = EXACT_DIGITS as i32 - 1 - DECIMAL_PLACES; /// The smallest power of ten whose value 28 places hold to 22 significant /// digits: 10⁻⁷. const SMALLEST_QUOTIENT_EXPONENT: i32 = QUOTIENT_DIGITS as i32 - 1 - DECIMAL_PLACES; +/// Cancellation snapping: a sum or difference this small relative to its +/// larger operand is rounding left over from earlier steps, not a real +/// difference, so it's 0. 10⁻¹⁸ for exact operands. +const EXACT_CANCELLATION: Decimal = Decimal::from_parts(1, 0, 0, false, 18); +/// The same for an `f64` operand, whose own error is about 10⁻¹⁶. +const FLOAT_CANCELLATION: f64 = 1e-14; /// What the display says when a calculation has no answer. pub const ERROR_TEXT: &str = "Error"; @@ -122,7 +137,7 @@ impl Num { } /// An `f64` result. It stays approximate unless it's exactly what a - /// decimal would hold: a whole number, or a value whose 15-digit text + /// decimal would hold: a whole number up to 2^53, or a value whose 15-digit text /// reads back as the very same `f64` (so `4 ^ 0.5` is exactly 2, and /// `0.25 ^ 0.5` is exactly 0.5). Anything else, like `2 ^ 0.5`, stays an /// `f64`, so arithmetic on it stays in `f64` and shows 15 digits, as @@ -134,7 +149,10 @@ impl Num { if value == 0.0 { return Ok(Num::ZERO); } - if value.fract() == 0.0 { + // Every whole f64 up to 2^53 is exact; above that a whole f64 carries + // binary noise (1e30 × 1e-7 is 99999999999999991611392), so it goes + // through the 15-digit test below like any other f64. + if value.fract() == 0.0 && value.abs() <= 9_007_199_254_740_992.0 { return Ok(match Decimal::from_f64_retain(value) { Some(d) => Num::Exact(d.normalize()), None => Num::Float(value), @@ -176,10 +194,19 @@ impl Num { kind => kind, }; if let Some(result) = settle(kind, result, zero_ok) { + let largest = a.abs().max(b.abs()); + if kind == Kind::Sum && result.abs() <= largest * EXACT_CANCELLATION { + return Ok(Num::ZERO); + } return Ok(Num::Exact(result)); } } - Num::from_f64(float(self.to_f64(), other.to_f64())) + let (a, b) = (self.to_f64(), other.to_f64()); + let result = float(a, b); + if kind == Kind::Sum && result.abs() <= a.abs().max(b.abs()) * FLOAT_CANCELLATION { + return Ok(Num::ZERO); + } + Num::from_f64(result) } fn apply(self, op: Op, other: Num) -> Answer { @@ -1058,6 +1085,57 @@ mod tests { ); } + /// Chained roundings cancel to exactly 0. + #[test] + fn cancellation_snaps_to_zero() { + assert_eq!(shows("1 ÷ 3 ÷ 3 × 3 × 3 - 1 ="), "0"); + assert_eq!(shows("1 ÷ 7 ÷ 7 × 7 × 7 - 1 ="), "0"); + assert_eq!( + shows("1 0 ÷ 3 ÷ 3 ÷ 3 ÷ 3 ÷ 3 × 3 × 3 × 3 × 3 × 3 - 1 0 ="), + "0" + ); + // On the f64 side of the quotient cutoff. + assert_eq!(shows("1 ÷ 2 9 9 9 9 9 9 9 × 2 9 9 9 9 9 9 9 - 1 ="), "0"); + assert_eq!(shows("1 ÷ 1 0 0 0 0 0 0 4 × 1 0 0 0 0 0 0 4 - 1 ="), "0"); + assert_eq!(shows("3 ^ 4 0 sign × 3 ^ 4 0 - 1 ="), "0"); + } + + /// Snapping never hides a real difference between typed numbers. + #[test] + fn cancellation_keeps_real_differences() { + assert_eq!( + shows("1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 - 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 5 ="), + "1" + ); + assert_eq!( + shows("1 - . 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 ="), + "0.9999999999999999" + ); + assert_eq!( + shows(". 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 + . 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 ="), + "2e-16" + ); + assert_eq!(shows("0 . 1 + 0 . 2 - 0 . 3 ="), "0"); + let rest = shows("1 ÷ 3 - . 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 ="); + assert!( + rest.starts_with("3.333") && rest.ends_with("e-17"), + "{rest}" + ); + } + + /// A whole f64 past 2^53 isn't exact, so it isn't promoted with its noise. + #[test] + fn large_whole_floats_stay_approximate() { + let mut calc = Calc::new(); + assert!(calc.paste("1e30")); + press(&mut calc, "×"); + assert!(calc.paste("1e-7")); + press(&mut calc, "="); + assert_eq!(calc.display(), "1e+23"); + // Whole numbers up to 2^53 still become exact. + assert_eq!(shows("4 ^ . 5 + 0 . 1 ="), "2.1"); + } + /// A negative power is a reciprocal and gets a quotient's guard digits. #[test] fn negative_powers_cancel() { From 5ec3bb83cfdb9045fd3de3f72916d4b0cf0e18cb Mon Sep 17 00:00:00 2001 From: Michael Aguiar Date: Wed, 25 Nov 2026 13:01:12 -0700 Subject: [PATCH 24/50] Snap float cancellation at 10^-15, not 10^-14 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 10^-14 also zeroed real differences against a number typed to 15 digits: 2 ^ 0.5 − 1.41421356237309 gave 0, where the difference is 5.1e-15 and omacalc shows it. f64 leftovers are a few units in the last place (about 1e-16 relative), which 10^-15 still snaps; every chain in cancellation_snaps_to_zero still gives 0. ALI-2100 --- src/engine.rs | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/src/engine.rs b/src/engine.rs index dcc9086..86b1b74 100644 --- a/src/engine.rs +++ b/src/engine.rs @@ -21,7 +21,7 @@ //! //! Guard digits absorb one rounding, but a chain of them can still leave //! residue at the 20th digit (1 ÷ 3 ÷ 3 × 3 × 3 − 1). So a sum or difference -//! that's at most 10⁻¹⁸ of its larger operand (10⁻¹⁴ when either is an +//! that's at most 10⁻¹⁸ of its larger operand (10⁻¹⁵ when either is an //! `f64`) is cancellation, and is 0. That never hides a real difference //! between typed numbers: they carry at most 16 significant digits, so they //! differ by at least about 10⁻¹⁶ of their size. A pasted number with more @@ -64,8 +64,11 @@ const SMALLEST_QUOTIENT_EXPONENT: i32 = QUOTIENT_DIGITS as i32 - 1 - DECIMAL_PLA /// larger operand is rounding left over from earlier steps, not a real /// difference, so it's 0. 10⁻¹⁸ for exact operands. const EXACT_CANCELLATION: Decimal = Decimal::from_parts(1, 0, 0, false, 18); -/// The same for an `f64` operand, whose own error is about 10⁻¹⁶. -const FLOAT_CANCELLATION: f64 = 1e-14; +/// The same for an `f64` operand, whose own error is about 10⁻¹⁶: a few +/// units in the last place snap, but a real difference against a number +/// typed to 15 digits (`2 ^ 0.5 − 1.41421356237309`, 3.6 × 10⁻¹⁵ of it) +/// is kept, as omacalc shows it. +const FLOAT_CANCELLATION: f64 = 1e-15; /// What the display says when a calculation has no answer. pub const ERROR_TEXT: &str = "Error"; @@ -1116,6 +1119,12 @@ mod tests { "2e-16" ); assert_eq!(shows("0 . 1 + 0 . 2 - 0 . 3 ="), "0"); + // A float against a number typed to 15 digits keeps its difference. + let sqrt2 = shows("2 ^ . 5 - 1 . 4 1 4 2 1 3 5 6 2 3 7 3 0 9 ="); + assert!( + sqrt2.starts_with("5.") && sqrt2.ends_with("e-15"), + "{sqrt2}" + ); let rest = shows("1 ÷ 3 - . 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 ="); assert!( rest.starts_with("3.333") && rest.ends_with("e-17"), From 2aead7b18371701cc571ceca0e956388d0f100e6 Mon Sep 17 00:00:00 2001 From: Michael Aguiar Date: Wed, 25 Nov 2026 13:11:08 -0700 Subject: [PATCH 25/50] Track how exact each value is, and round and snap only inexact ones MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Every value now carries a level: Exact (typed, pasted, and lossless + − × and whole powers of exact values, including divisions that end), Guarded (cut-off quotients, negative powers, lossy decimal results, and anything from them), or Approx (anything that went through f64, even once turned back into a decimal). A result takes the highest level of its inputs and its operation. - Exact values are never rounded or snapped, so typed digits survive a chain: 1000000000 + 0.000000001 − 1000000000 is 1e-09, and 8403911115566009 + 2.4118675 − 8403911115566009 is 2.4118675. - Guarded values round as before (cut-off quotients 22 digits, the rest 20) and snap at 1e-18 of the larger operand. - Approx values snap at 1e-15, so an f64 quotient turned back into a decimal no longer leaves its error (4 ÷ 50619463 × 50619463 − 4 is 0). - Seeded property tests: a ÷ b × b − a and a ÷ b ÷ b × b × b − a are 0, and (a + c) − a is c whenever a decimal holds a + c. ALI-2100 --- src/engine.rs | 499 +++++++++++++++++++++++++++++++++++++------------- 1 file changed, 372 insertions(+), 127 deletions(-) diff --git a/src/engine.rs b/src/engine.rs index 86b1b74..04b3583 100644 --- a/src/engine.rs +++ b/src/engine.rs @@ -7,50 +7,61 @@ //! that, or below 10⁻²⁸, a value falls back to `f64` so very large and very //! small numbers still work (shown to 15 significant digits, as omacalc does). //! -//! The display rounds exact values to 16 significant digits, so every +//! The display rounds decimal values to 16 significant digits, so every //! integer up to 9,999,999,999,999,999 shows exactly. //! -//! Exact results are worked to a fixed precision, whatever their size: every -//! sum, difference, product and power is rounded to 20 significant digits. -//! A quotient (÷, or a power with a negative exponent, which is a -//! reciprocal) keeps 22, unless it ends exactly. The two extra digits are -//! guard digits: the next rounding to 20 absorbs the quotient's last-place -//! error, so 1 ÷ 3 × 3 − 1 and 1 ÷ 7000 × 7000 − 1 are exactly 0. Twenty -//! digits is still more than the 16 shown, so nothing a person can type or -//! see is rounded by it. +//! # How exact a value is //! -//! Guard digits absorb one rounding, but a chain of them can still leave -//! residue at the 20th digit (1 ÷ 3 ÷ 3 × 3 × 3 − 1). So a sum or difference -//! that's at most 10⁻¹⁸ of its larger operand (10⁻¹⁵ when either is an -//! `f64`) is cancellation, and is 0. That never hides a real difference -//! between typed numbers: they carry at most 16 significant digits, so they -//! differ by at least about 10⁻¹⁶ of their size. A pasted number with more -//! than 16 digits can lose a difference that small, as it can lose digits -//! to the 20-digit rounding. +//! Every value carries one of three levels, and a result takes the highest +//! level among its inputs and its operation: +//! +//! * **Exact**: what was typed or pasted, and any + − × or whole power ≥ 0 +//! of exact values that a decimal holds without loss, including a division +//! that ends (1 ÷ 4, 1 ÷ 100000000). Exact values are never rounded and +//! never snapped, so `1000000000 + 0.000000001 − 1000000000` is 1e-09 and +//! `8403911115566009 + 2.4118675 − 8403911115566009` is 2.4118675. +//! * **Guarded**: a division that doesn't end (1 ÷ 3), a negative power (a +//! reciprocal), a + − × or power that a decimal can't hold without loss, +//! and anything worked out from those. A cut-off quotient keeps 22 +//! significant digits and every other guarded result 20, the same at +//! every size. The two extra digits are guard digits: the next rounding +//! to 20 absorbs the quotient's last-place error, so 1 ÷ 3 × 3 − 1 and +//! 1 ÷ 7000 × 7000 − 1 are exactly 0. A chain of quotients can still leave +//! residue at the 20th digit (1 ÷ 3 ÷ 3 × 3 × 3 − 1), so a guarded sum or +//! difference that's at most 10⁻¹⁸ of its larger operand is 0. +//! * **Approx**: anything that went through `f64` (a fractional power, a +//! quotient too small to keep 22 digits, a value out of a decimal's +//! range), even when it's turned back into a decimal, and anything worked +//! out from it. It's shown to 15 digits when it's an `f64`, and a sum or +//! difference that's at most 10⁻¹⁵ of its larger operand is 0, which +//! clears an `f64`'s last-place error but keeps a real difference like +//! `2 ^ 0.5 − 1.41421356237309`. //! //! A decimal keeps 28 places rather than 28 significant digits, so small -//! values can't carry those digits. A product or power below 10⁻¹³ (fewer -//! than 16 digits in 28 places) and a quotient that doesn't end below 10⁻⁷ -//! (fewer than 22) are worked out in `f64` instead and show 15 digits, as -//! omacalc does. A fractional power is approximate, so it stays an `f64` -//! too, unless the answer is exact (`4 ^ 0.5` is 2). Like C's `%g`, a value -//! switches to exponent form (`1.5e+20`, `1e-05`) when its exponent is below -//! −4 or at least the precision (16 for exact values, 15 for `f64`). +//! values can't carry those digits. A rounded product or power below 10⁻¹³ +//! (fewer than 16 digits in 28 places) and a cut-off quotient below 10⁻⁷ +//! (fewer than 22) are worked out in `f64` instead, and so become Approx. A +//! fractional power is worked out in `f64` too; `4 ^ 0.5` is still shown as +//! 2. Like C's `%g`, a value switches to exponent form (`1.5e+20`, `1e-05`) +//! when its exponent is below −4 or at least the precision (16 for decimal +//! values, 15 for `f64`). use std::fmt::Write as _; use std::str::FromStr; use rust_decimal::{Decimal, MathematicalOps}; -/// Significant digits shown for an exact value, and the most that can be typed. +/// Significant digits shown for a decimal value, and the most that can be typed. const EXACT_DIGITS: u32 = 16; /// Significant digits shown for an `f64` value: what a double holds reliably. const FLOAT_DIGITS: u32 = 15; -/// The working precision: every exact sum, difference, product and power is -/// rounded to this many significant digits (see [`settle`]). +/// The working precision for guarded and approximate results: sums, +/// differences, products and powers are rounded to this many significant +/// digits (see [`settle`]). const WORKING_DIGITS: u32 = 20; -/// Quotients (÷, and powers with a negative exponent) keep two more digits, -/// so the next rounding to [`WORKING_DIGITS`] absorbs their last-place error. +/// Cut-off quotients (÷, and powers with a negative exponent) keep two more +/// digits, so the next rounding to [`WORKING_DIGITS`] absorbs their +/// last-place error. const QUOTIENT_DIGITS: u32 = WORKING_DIGITS + 2; /// A decimal keeps this many places after the point, whatever its size. const DECIMAL_PLACES: i32 = 28; @@ -60,15 +71,14 @@ const SMALLEST_FULL_EXPONENT: i32 = EXACT_DIGITS as i32 - 1 - DECIMAL_PLACES; /// The smallest power of ten whose value 28 places hold to 22 significant /// digits: 10⁻⁷. const SMALLEST_QUOTIENT_EXPONENT: i32 = QUOTIENT_DIGITS as i32 - 1 - DECIMAL_PLACES; -/// Cancellation snapping: a sum or difference this small relative to its -/// larger operand is rounding left over from earlier steps, not a real -/// difference, so it's 0. 10⁻¹⁸ for exact operands. -const EXACT_CANCELLATION: Decimal = Decimal::from_parts(1, 0, 0, false, 18); -/// The same for an `f64` operand, whose own error is about 10⁻¹⁶: a few -/// units in the last place snap, but a real difference against a number -/// typed to 15 digits (`2 ^ 0.5 − 1.41421356237309`, 3.6 × 10⁻¹⁵ of it) -/// is kept, as omacalc shows it. -const FLOAT_CANCELLATION: f64 = 1e-15; +/// Cancellation snapping for a guarded sum or difference: this small +/// relative to its larger operand, it's residue from rounding, so it's 0. +const GUARDED_CANCELLATION: Decimal = Decimal::from_parts(1, 0, 0, false, 18); +/// The same for an approximate one. An `f64`'s own error is about 10⁻¹⁶, so +/// a few units in the last place snap, but a real difference against a +/// number typed to 15 digits (`2 ^ 0.5 − 1.41421356237309`, 3.6 × 10⁻¹⁵ of +/// it) is kept, as omacalc shows it. +const APPROX_CANCELLATION: f64 = 1e-15; /// What the display says when a calculation has no answer. pub const ERROR_TEXT: &str = "Error"; @@ -108,10 +118,20 @@ pub enum Key { Clear, } -/// A number: exact when it fits a decimal, `f64` when it doesn't. +/// How exact a value is (see the module docs). Ordered, so a result's level +/// is the `max` of its inputs' and its operation's. +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] +enum Level { + Exact, + Guarded, + Approx, +} + +/// A number: a decimal with its [`Level`], or an `f64` (always Approx) +/// when a decimal can't hold it. #[derive(Clone, Copy, Debug, PartialEq)] enum Num { - Exact(Decimal), + Dec(Decimal, Level), Float(f64), } @@ -123,41 +143,52 @@ struct NoAnswer; type Answer = Result; impl Num { - const ZERO: Num = Num::Exact(Decimal::ZERO); + const ZERO: Num = Num::Dec(Decimal::ZERO, Level::Exact); + + fn exact(value: Decimal) -> Num { + Num::Dec(value, Level::Exact) + } + + fn level(self) -> Level { + match self { + Num::Dec(_, level) => level, + Num::Float(_) => Level::Approx, + } + } fn to_f64(self) -> f64 { match self { - Num::Exact(d) => f64::from_str(&d.to_string()).unwrap_or(f64::NAN), + Num::Dec(d, _) => f64::from_str(&d.to_string()).unwrap_or(f64::NAN), Num::Float(f) => f, } } fn is_zero(self) -> bool { match self { - Num::Exact(d) => d.is_zero(), + Num::Dec(d, _) => d.is_zero(), Num::Float(f) => f == 0.0, } } - /// An `f64` result. It stays approximate unless it's exactly what a - /// decimal would hold: a whole number up to 2^53, or a value whose 15-digit text - /// reads back as the very same `f64` (so `4 ^ 0.5` is exactly 2, and - /// `0.25 ^ 0.5` is exactly 0.5). Anything else, like `2 ^ 0.5`, stays an - /// `f64`, so arithmetic on it stays in `f64` and shows 15 digits, as - /// omacalc does: `2 ^ 0.5 × 2 ^ 0.5` is 2, not 2.000000000000014. + /// An `f64` result, which is Approx whatever it looks like. It's kept as + /// a decimal when it's what a decimal would hold: a whole number up to + /// 2^53, or a value whose 15-digit text reads back as the very same + /// `f64` (`4 ^ 0.5` is 2, `0.25 ^ 0.5` is 0.5). Anything else, like + /// `2 ^ 0.5`, stays an `f64`, so arithmetic on it stays in `f64` and + /// shows 15 digits, as omacalc does: `2 ^ 0.5 × 2 ^ 0.5` is 2. fn from_f64(value: f64) -> Answer { if !value.is_finite() { return Err(NoAnswer); } if value == 0.0 { - return Ok(Num::ZERO); + return Ok(Num::Dec(Decimal::ZERO, Level::Approx)); } // Every whole f64 up to 2^53 is exact; above that a whole f64 carries // binary noise (1e30 × 1e-7 is 99999999999999991611392), so it goes // through the 15-digit test below like any other f64. if value.fract() == 0.0 && value.abs() <= 9_007_199_254_740_992.0 { return Ok(match Decimal::from_f64_retain(value) { - Some(d) => Num::Exact(d.normalize()), + Some(d) => Num::Dec(d.normalize(), Level::Approx), None => Num::Float(value), }); } @@ -166,63 +197,81 @@ impl Num { match Decimal::from_scientific(&text) { // Below a decimal's 28 places the value would round away. Ok(d) if round_trips && !d.is_zero() && d.normalize().scale() <= 28 => { - Ok(Num::Exact(d.normalize())) + Ok(Num::Dec(d.normalize(), Level::Approx)) } _ => Ok(Num::Float(value)), } } - /// Applies the exact operation when both sides are exact and [`settle`] - /// accepts its result; otherwise the `f64` one. + /// Applies the decimal operation when both sides are decimals and + /// [`settle`] accepts its result; otherwise the `f64` one. + /// + /// `undo` checks the raw decimal result against the inputs: it's the + /// inverse operation (r − b = a for +), true when nothing was lost. fn combine( self, other: Num, kind: Kind, exact: impl Fn(Decimal, Decimal) -> Option, + undo: impl Fn(Decimal, Decimal, Decimal) -> bool, float: impl Fn(f64, f64) -> f64, ) -> Answer { - if let (Num::Exact(a), Num::Exact(b)) = (self, other) - && let Some(result) = exact(a, b) + let level = self.level().max(other.level()); + if let (Num::Dec(a, _), Num::Dec(b, _)) = (self, other) + && let Some(raw) = exact(a, b) { let zero_ok = match kind { Kind::Sum => true, Kind::Product => a.is_zero() || b.is_zero(), - Kind::Quotient { .. } => a.is_zero(), + Kind::Quotient => a.is_zero(), }; - // A quotient ends exactly when it multiplies back to the dividend. - let kind = match kind { - Kind::Quotient { .. } => Kind::Quotient { - ends: result.checked_mul(b) == Some(a), - }, - kind => kind, - }; - if let Some(result) = settle(kind, result, zero_ok) { - let largest = a.abs().max(b.abs()); - if kind == Kind::Sum && result.abs() <= largest * EXACT_CANCELLATION { - return Ok(Num::ZERO); - } - return Ok(Num::Exact(result)); + if let Some((value, level)) = settle(kind, raw, undo(a, b, raw), level, zero_ok) { + return Ok(snap(kind, Num::Dec(value, level), a.abs().max(b.abs()))); } } let (a, b) = (self.to_f64(), other.to_f64()); let result = float(a, b); - if kind == Kind::Sum && result.abs() <= a.abs().max(b.abs()) * FLOAT_CANCELLATION { - return Ok(Num::ZERO); + if kind == Kind::Sum && result.abs() <= a.abs().max(b.abs()) * APPROX_CANCELLATION { + return Ok(Num::Dec(Decimal::ZERO, Level::Approx)); } Num::from_f64(result) } fn apply(self, op: Op, other: Num) -> Answer { match op { - Op::Add => self.combine(other, Kind::Sum, Decimal::checked_add, |a, b| a + b), - Op::Sub => self.combine(other, Kind::Sum, Decimal::checked_sub, |a, b| a - b), - Op::Mul => self.combine(other, Kind::Product, Decimal::checked_mul, |a, b| a * b), + Op::Add => self.combine( + other, + Kind::Sum, + Decimal::checked_add, + |a, b, r| r.checked_sub(b) == Some(a), + |a, b| a + b, + ), + Op::Sub => self.combine( + other, + Kind::Sum, + Decimal::checked_sub, + |a, b, r| r.checked_add(b) == Some(a), + |a, b| a - b, + ), + Op::Mul => self.combine( + other, + Kind::Product, + Decimal::checked_mul, + |a, b, r| b.is_zero() || r.checked_div(b) == Some(a), + |a, b| a * b, + ), Op::Div => { if other.is_zero() { return Err(NoAnswer); } - let quotient = Kind::Quotient { ends: false }; - self.combine(other, quotient, Decimal::checked_div, |a, b| a / b) + // A quotient ends exactly when it multiplies back to the dividend. + self.combine( + other, + Kind::Quotient, + Decimal::checked_div, + |a, b, r| r.checked_mul(b) == Some(a), + |a, b| a / b, + ) } Op::Pow => self.pow(other), } @@ -230,18 +279,18 @@ impl Num { fn negate(self) -> Num { match self { - Num::Exact(d) => Num::Exact(-d), + Num::Dec(d, level) => Num::Dec(-d, level), Num::Float(f) => Num::Float(-f), } } fn pow(self, exponent: Num) -> Answer { let whole = match exponent { - Num::Exact(e) => e.is_integer(), + Num::Dec(e, _) => e.is_integer(), Num::Float(e) => e.fract() == 0.0, }; let negative = match self { - Num::Exact(d) => d.is_sign_negative() && !d.is_zero(), + Num::Dec(d, _) => d.is_sign_negative() && !d.is_zero(), Num::Float(f) => f < 0.0, }; if negative && !whole { @@ -250,12 +299,12 @@ impl Num { if self.is_zero() && exponent.to_f64() < 0.0 { return Err(NoAnswer); } - if let (Num::Exact(base), Num::Exact(e)) = (self, exponent) + if let (Num::Dec(base, _), Num::Dec(e, _)) = (self, exponent) && whole && let Ok(e) = i64::try_from(e.mantissa() / 10i128.pow(e.scale())) - && let Some(result) = exact_integer_power(base, e) + && let Some((value, level)) = integer_power(base, e, self.level().max(exponent.level())) { - return Ok(Num::Exact(result)); + return Ok(Num::Dec(value, level)); } Num::from_f64(self.to_f64().powf(exponent.to_f64())) } @@ -263,54 +312,91 @@ impl Num { /// The display text, without thousands separators. fn format(self) -> String { match self { - Num::Exact(d) => format_exact(d), + Num::Dec(d, _) => format_exact(d), Num::Float(f) => format_float(f), } } } -/// What an exact operation was, for [`settle`]. +/// What a decimal operation was, for [`settle`]. #[derive(Clone, Copy, Debug, PartialEq, Eq)] enum Kind { /// + or −. Sum, /// × or a power with a non-negative exponent. Product, - /// ÷ or a power with a negative exponent (a reciprocal). `ends`: the - /// quotient is exact, like 1 ÷ 8, rather than cut off, like 1 ÷ 3. - Quotient { ends: bool }, + /// ÷ or a power with a negative exponent (a reciprocal). + Quotient, } -/// The one rule for exact results: rounds `value`, the raw result of an -/// exact operation, to the working precision, or says it must be redone in -/// `f64` (`None`). +/// The one rule for decimal results. Takes the raw result of a decimal +/// operation, whether it lost nothing (`lossless`: a sum or product a +/// decimal holds in full, or a quotient that ends), and the inputs' level. +/// Returns the value and its level, or `None` to redo it in `f64`. /// -/// * A sum, difference, product or power is rounded to 20 significant -/// digits ([`WORKING_DIGITS`]). -/// * A quotient that's cut off is rounded to 22 ([`QUOTIENT_DIGITS`]). The -/// next rounding to 20 absorbs its last-place error, so 1 ÷ 3 × 3 is -/// exactly 1 and 1 ÷ 3000 × 3000 − 1 is exactly 0. The precision is the -/// same at every size: guard digits counted in places (a decimal's 28) -/// would run out for a small quotient like 1 ÷ 3000. -/// * A quotient that ends exactly (1 ÷ 8) is kept as it is. -/// * Small values can't carry those digits in 28 places, so they go to -/// `f64`: a product or power below 10⁻¹³ (16 digits shown) and a cut-off -/// quotient below 10⁻⁷ (22 digits kept). A zero is kept only when zero is -/// the true answer (`zero_ok`), not when a tiny product rounded away. -fn settle(kind: Kind, value: Decimal, zero_ok: bool) -> Option { - if value.is_zero() { - return zero_ok.then_some(Decimal::ZERO); +/// * A lossless result keeps its inputs' level; anything else is at least +/// Guarded. +/// * An Exact result is kept as it is: never rounded. +/// * A Guarded or Approx result is rounded: a cut-off quotient to 22 +/// significant digits ([`QUOTIENT_DIGITS`]), anything else to 20 +/// ([`WORKING_DIGITS`]). The precision is the same at every size: guard +/// digits counted in places (a decimal's 28) would run out for a small +/// quotient like 1 ÷ 3000. +/// * Small rounded values can't carry those digits in 28 places, so they go +/// to `f64`: a product or power below 10⁻¹³ and a cut-off quotient below +/// 10⁻⁷. A zero is kept only when zero is the true answer (`zero_ok`), not +/// when a tiny product rounded away. +fn settle( + kind: Kind, + raw: Decimal, + lossless: bool, + level: Level, + zero_ok: bool, +) -> Option<(Decimal, Level)> { + let level = if lossless { + level + } else { + level.max(Level::Guarded) + }; + if raw.is_zero() { + return zero_ok.then_some((Decimal::ZERO, level)); + } + if level == Level::Exact { + return Some((raw.normalize(), level)); } let (digits, smallest) = match kind { Kind::Sum => (WORKING_DIGITS, i32::MIN), Kind::Product => (WORKING_DIGITS, SMALLEST_FULL_EXPONENT), - Kind::Quotient { ends: true } => return Some(value.normalize()), - Kind::Quotient { ends: false } => (QUOTIENT_DIGITS, SMALLEST_QUOTIENT_EXPONENT), + Kind::Quotient if lossless => (QUOTIENT_DIGITS, i32::MIN), + Kind::Quotient => (QUOTIENT_DIGITS, SMALLEST_QUOTIENT_EXPONENT), }; - if first_digit_exponent(value) < smallest { + if first_digit_exponent(raw) < smallest { return None; } - Some(value.round_sf(digits).unwrap_or(value).normalize()) + Some((raw.round_sf(digits).unwrap_or(raw).normalize(), level)) +} + +/// Cancellation snapping for + and −: a non-zero sum or difference this +/// small next to its larger operand (`largest`) is residue from rounding, +/// so it's 0. Exact results never snap; Guarded ones at 10⁻¹⁸ of `largest`, +/// Approx ones at 10⁻¹⁵. +fn snap(kind: Kind, value: Num, largest: Decimal) -> Num { + let Num::Dec(result, level) = value else { + return value; + }; + if kind != Kind::Sum || result.is_zero() { + return value; + } + let threshold = match level { + Level::Exact => return value, + Level::Guarded => GUARDED_CANCELLATION, + Level::Approx => Decimal::new(1, 15), + }; + if result.abs() <= largest * threshold { + Num::Dec(Decimal::ZERO, level) + } else { + value + } } /// The power of ten the first significant digit of a non-zero value is worth. @@ -320,18 +406,23 @@ fn first_digit_exponent(value: Decimal) -> i32 { digits - 1 - normal.scale() as i32 } -/// `base ^ e` for a whole `e`, exactly, or `None` to work it out in `f64`. A -/// negative power is the reciprocal of the positive one, so it's settled as -/// a quotient and gets the same guard digits as 1 ÷ x. -fn exact_integer_power(base: Decimal, e: i64) -> Option { - let power = base.checked_powu(e.unsigned_abs())?; - let power = settle(Kind::Product, power, base.is_zero())?; +/// `base ^ e` for a whole `e` as a decimal and its level, or `None` to work +/// it out in `f64`. A negative power is the reciprocal of the positive one, +/// so it's settled as a quotient and gets the same guard digits as 1 ÷ x. +fn integer_power(base: Decimal, e: i64, level: Level) -> Option<(Decimal, Level)> { + let n = e.unsigned_abs(); + let power = base.checked_powu(n)?; + // A normalized base ends in a non-zero digit, so its power does too: the + // power lost nothing exactly when it kept every place. + let places = u64::from(base.normalize().scale()) * n; + let lossless = u64::from(power.normalize().scale()) == places; + let (power, level) = settle(Kind::Product, power, lossless, level, base.is_zero())?; if e >= 0 { - return Some(power); + return Some((power, level)); } let reciprocal = Decimal::ONE.checked_div(power)?; let ends = reciprocal.checked_mul(power) == Some(Decimal::ONE); - settle(Kind::Quotient { ends }, reciprocal, false) + settle(Kind::Quotient, reciprocal, ends, level, false) } /// Rounds to 16 significant digits and lays the digits out. @@ -487,7 +578,7 @@ fn parse_number(text: &str) -> Option { }; match exact { Some(d) if !(d.is_zero() && text.bytes().any(|b| (b'1'..=b'9').contains(&b))) => { - Some(Num::Exact(d)) + Some(Num::exact(d)) } _ => { let value = f64::from_str(text).ok()?; @@ -712,7 +803,7 @@ impl Calc { } if let Some((value, _)) = self.result.take() { self.evaluated.clear(); - match value.apply(Op::Div, Num::Exact(Decimal::ONE_HUNDRED)) { + match value.apply(Op::Div, Num::exact(Decimal::ONE_HUNDRED)) { Ok(percent) => self.set_entry(percent), Err(NoAnswer) => self.errored = true, } @@ -720,7 +811,7 @@ impl Calc { } let value = self.current_value(); - let hundred = Num::Exact(Decimal::ONE_HUNDRED); + let hundred = Num::exact(Decimal::ONE_HUNDRED); let percent = match self.tokens.last() { Some(Token::Op(Op::Add | Op::Sub)) => { let total = &self.tokens[..self.tokens.len() - 1]; @@ -1083,8 +1174,8 @@ mod tests { assert_eq!(shows("1 ÷ 3 ÷ 7 × 2 1 - 1 ="), "0"); assert_eq!( shows("1 0 ^ 2 7 + 1 - 1 0 ^ 2 7 ="), - "0", - "20 working digits drop the 1" + "1", + "exact values are never rounded" ); } @@ -1132,6 +1223,160 @@ mod tests { ); } + /// Exact values are never rounded or snapped, so typed digits survive a + /// chain however large the intermediate gets. + #[test] + fn exact_chains_keep_typed_digits() { + assert_eq!( + shows("1 0 0 0 0 0 0 0 0 0 + . 0 0 0 0 0 0 0 0 1 - 1 0 0 0 0 0 0 0 0 0 ="), + "1e-09" + ); + assert_eq!( + shows("1 0 0 0 0 0 0 0 0 0 0 0 0 0 + . 0 0 0 1 - 1 0 0 0 0 0 0 0 0 0 0 0 0 0 ="), + "0.0001" + ); + assert_eq!(shows("2 ^ 6 0 + 1 - 2 ^ 6 0 ="), "1"); + assert_eq!( + shows( + "1 0 0 0 0 0 0 0 0 0 × 1 0 0 0 0 0 0 0 0 0 0 + 1 \ + - 1 0 0 0 0 0 0 0 0 0 × 1 0 0 0 0 0 0 0 0 0 0 =" + ), + "1" + ); + assert_eq!( + shows( + "8 4 0 3 9 1 1 1 1 5 5 6 6 0 0 9 + 2 . 4 1 1 8 6 7 5 \ + - 8 4 0 3 9 1 1 1 1 5 5 6 6 0 0 9 =" + ), + "2.4118675" + ); + } + + /// A quotient that went through f64 stays Approx when it's turned back + /// into a decimal, so its f64 error snaps. + #[test] + fn approx_quotients_snap() { + assert_eq!(shows("4 ÷ 5 0 6 1 9 4 6 3 × 5 0 6 1 9 4 6 3 - 4 ="), "0"); + assert_eq!( + shows("3 1 9 ÷ 3 9 3 6 7 7 2 1 8 8 × 3 9 3 6 7 7 2 1 8 8 - 3 1 9 ="), + "0" + ); + } + + /// A small xorshift, so the property tests need no dependency and fail + /// the same way every run. + struct Rng(u64); + + impl Rng { + fn next(&mut self) -> u64 { + self.0 ^= self.0 << 13; + self.0 ^= self.0 >> 7; + self.0 ^= self.0 << 17; + self.0 + } + + fn below(&mut self, n: u64) -> u64 { + self.next() % n + } + + /// `len` random digits, the first non-zero. + fn digits(&mut self, len: usize) -> String { + (0..len) + .map(|i| { + let d = if i == 0 { + 1 + self.below(9) + } else { + self.below(10) + }; + char::from(b'0' + d as u8) + }) + .collect() + } + } + + /// The key presses that type `number` ("12.5" → "1 2 . 5"). + fn keys(number: &str) -> String { + let mut out = String::new(); + for c in number.chars() { + out.push(c); + out.push(' '); + } + out + } + + /// A typed number of 1–10 digits, sometimes with a decimal point. + fn typed_operand(rng: &mut Rng) -> String { + let len = 1 + rng.below(10) as usize; + let mut number = rng.digits(len); + if len > 1 && rng.below(3) == 0 { + number.insert(1 + rng.below(len as u64 - 1) as usize, '.'); + } + number + } + + #[test] + fn property_division_round_trips() { + let mut rng = Rng(0x9e37_79b9_7f4a_7c15); + for _ in 0..3000 { + let (a, b) = (typed_operand(&mut rng), typed_operand(&mut rng)); + let (a, b) = (keys(&a), keys(&b)); + let once = format!("{a}÷ {b}× {b}- {a}="); + assert_eq!(shows(&once), "0", "{once}"); + let twice = format!("{a}÷ {b}÷ {b}× {b}× {b}- {a}="); + assert_eq!(shows(&twice), "0", "{twice}"); + } + } + + #[test] + fn property_adding_then_subtracting_returns_the_addend() { + let mut rng = Rng(0x2545_f491_4f6c_dd1d); + let mut checked = 0; + for _ in 0..4000 { + // a: up to 16 typed digits, the point anywhere. + let len = 1 + rng.below(16) as usize; + let mut a = rng.digits(len); + if rng.below(2) == 0 { + a.insert(rng.below(len as u64) as usize, '.'); + if a.starts_with('.') { + a.insert(0, '0'); + } + } + // c: from 1e-12 to 1e15, as many digits as the 16-digit entry + // takes (the zeros after "0." count). + let exponent = rng.below(28) as i32 - 12; + let room = if exponent >= 0 { 16 } else { 17 + exponent } as u64; + let sig_len = 1 + rng.below(room) as usize; + let sig = rng.digits(sig_len); + let c = if exponent >= 0 { + let whole = (exponent + 1) as usize; + if sig.len() <= whole { + format!("{sig}{}", "0".repeat(whole - sig.len())) + } else { + format!("{}.{}", &sig[..whole], &sig[whole..]) + } + } else { + format!("0.{}{sig}", "0".repeat((-exponent - 1) as usize)) + }; + + // Only when a decimal can hold a + c in full: its 28 digits must + // cover the larger whole part and the longer fraction. + let (av, cv) = ( + Decimal::from_str(&a).unwrap(), + Decimal::from_str(&c).unwrap(), + ); + let whole_digits = |d: Decimal| d.trunc().to_string().trim_start_matches('0').len(); + let fits = whole_digits(av + cv).max(1) as u32 + av.scale().max(cv.scale()) <= 28; + if !fits { + continue; + } + checked += 1; + let keys_text = format!("{}+ {}- {}=", keys(&a), keys(&c), keys(&a)); + let expected = group_digits(&Num::exact(cv).format()); + assert_eq!(shows(&keys_text), expected, "{keys_text}"); + } + assert!(checked > 3000, "only {checked} cases fit a decimal"); + } + /// A whole f64 past 2^53 isn't exact, so it isn't promoted with its noise. #[test] fn large_whole_floats_stay_approximate() { @@ -1496,7 +1741,7 @@ mod tests { #[test] fn formats_numbers() { - let exact = |s: &str| Num::Exact(Decimal::from_str(s).unwrap()).format(); + let exact = |s: &str| Num::exact(Decimal::from_str(s).unwrap()).format(); assert_eq!(exact("133"), "133"); assert_eq!(exact("-0"), "0"); assert_eq!(exact("0.0001"), "0.0001"); @@ -1514,11 +1759,11 @@ mod tests { #[test] fn evaluate_tokens() { - let n = |v: i64| Token::Num(Num::Exact(Decimal::from(v))); + let n = |v: i64| Token::Num(Num::exact(Decimal::from(v))); let t = [n(2), Token::Op(Op::Add), n(3), Token::Op(Op::Mul), n(4)]; - assert_eq!(evaluate(&t), Ok(Num::Exact(Decimal::from(14)))); + assert_eq!(evaluate(&t), Ok(Num::exact(Decimal::from(14)))); let t = [n(2), Token::Op(Op::Pow), n(3), Token::Op(Op::Pow), n(2)]; - assert_eq!(evaluate(&t), Ok(Num::Exact(Decimal::from(512)))); + assert_eq!(evaluate(&t), Ok(Num::exact(Decimal::from(512)))); assert_eq!(evaluate(&[n(1), Token::Op(Op::Add)]), Err(NoAnswer)); assert_eq!(evaluate(&[]), Err(NoAnswer)); } From b97f730384870fb067187b4ac28c605e13db941d Mon Sep 17 00:00:00 2001 From: Michael Aguiar Date: Wed, 25 Nov 2026 13:24:51 -0700 Subject: [PATCH 26/50] Decide exactness against the true value, keep guarded digits MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit rust_decimal's checked ops and from_str round silently when a result needs more than 28 places or 96 bits, so undoing an operation with another rounding one could pass on a rounded result and mark it Exact. - Losslessness is now decided by comparing the result with the true value, worked out in 256 bits (Wide, Value): one helper per operation, integer powers by squaring with each multiplication checked, and quotients by checking q × b against a exactly. - Parsing marks a number Exact only when the decimal holds the text's exact value; otherwise it goes through f64 and is Approx. - Guarded values are no longer rounded to 20 or 22 digits: they keep every digit, and snap at 1e-24 of the larger operand. A rounded product, power or quotient below 1e-3 (fewer than 26 digits in 28 places) goes to f64, so a guarded value's error stays below the snap. - A reference property test (i128, 20,000 cases per op) checks that Exact always means exact and that every value a decimal can hold is Exact; residue-shape properties check that the remaining shapes cancel to 0. ALI-2100 --- src/engine.rs | 605 ++++++++++++++++++++++++++++++++++++++++++++------ 1 file changed, 532 insertions(+), 73 deletions(-) diff --git a/src/engine.rs b/src/engine.rs index 04b3583..90dbeae 100644 --- a/src/engine.rs +++ b/src/engine.rs @@ -12,68 +12,78 @@ //! //! # How exact a value is //! +//! rust_decimal rounds silently: `checked_add`, `checked_mul` and the rest +//! don't fail when a result needs more than 28 places or 96 bits, and +//! `from_str` rounds a long number the same way. So whether a value is exact +//! is decided by comparing it with the true value, worked out in 256 bits +//! (see [`Value`]), never by undoing an operation with another rounding one. +//! //! Every value carries one of three levels, and a result takes the highest //! level among its inputs and its operation: //! -//! * **Exact**: what was typed or pasted, and any + − × or whole power ≥ 0 -//! of exact values that a decimal holds without loss, including a division -//! that ends (1 ÷ 4, 1 ÷ 100000000). Exact values are never rounded and -//! never snapped, so `1000000000 + 0.000000001 − 1000000000` is 1e-09 and +//! * **Exact**: what was typed or pasted (when a decimal holds it in full), +//! and any + − × or whole power ≥ 0 of exact values whose true result a +//! decimal holds, including a division that ends (1 ÷ 4, 1 ÷ 100000000). +//! Exact values are never rounded and never snapped, so +//! `1000000000 + 0.000000001 − 1000000000` is 1e-09 and //! `8403911115566009 + 2.4118675 − 8403911115566009` is 2.4118675. //! * **Guarded**: a division that doesn't end (1 ÷ 3), a negative power (a -//! reciprocal), a + − × or power that a decimal can't hold without loss, -//! and anything worked out from those. A cut-off quotient keeps 22 -//! significant digits and every other guarded result 20, the same at -//! every size. The two extra digits are guard digits: the next rounding -//! to 20 absorbs the quotient's last-place error, so 1 ÷ 3 × 3 − 1 and -//! 1 ÷ 7000 × 7000 − 1 are exactly 0. A chain of quotients can still leave -//! residue at the 20th digit (1 ÷ 3 ÷ 3 × 3 × 3 − 1), so a guarded sum or -//! difference that's at most 10⁻¹⁸ of its larger operand is 0. +//! reciprocal), any operation the decimal had to round, and anything worked +//! out from those. A guarded value keeps every digit the decimal holds, at +//! least 26 significant ones (see below), so each rounding is off by at +//! most about 10⁻²⁶ of the value. A guarded sum or difference that's at +//! most 10⁻²⁴ of its larger operand is that residue, and is 0: so +//! 1 ÷ 3 × 3 − 1, 1 ÷ 3 ÷ 3 × 3 × 3 − 1 and 34 ÷ 7.67 + 9.3 ÷ 7.67 − +//! 43.3 ÷ 7.67 are exactly 0, while a real difference like +//! 1 ÷ 3 − 0.333333333333333333 (3 × 10⁻¹⁹) is kept. //! * **Approx**: anything that went through `f64` (a fractional power, a -//! quotient too small to keep 22 digits, a value out of a decimal's +//! rounded value too small to hold 26 digits, a value out of a decimal's //! range), even when it's turned back into a decimal, and anything worked //! out from it. It's shown to 15 digits when it's an `f64`, and a sum or //! difference that's at most 10⁻¹⁵ of its larger operand is 0, which //! clears an `f64`'s last-place error but keeps a real difference like //! `2 ^ 0.5 − 1.41421356237309`. //! -//! A decimal keeps 28 places rather than 28 significant digits, so small -//! values can't carry those digits. A rounded product or power below 10⁻¹³ -//! (fewer than 16 digits in 28 places) and a cut-off quotient below 10⁻⁷ -//! (fewer than 22) are worked out in `f64` instead, and so become Approx. A -//! fractional power is worked out in `f64` too; `4 ^ 0.5` is still shown as -//! 2. Like C's `%g`, a value switches to exponent form (`1.5e+20`, `1e-05`) +//! A decimal keeps 28 places rather than 28 significant digits, so a small +//! value holds few digits. A rounded product, power or quotient below 10⁻³ +//! (fewer than 26 digits in 28 places) is worked out in `f64` instead, and +//! so becomes Approx. A fractional power is worked out in `f64` too; +//! `4 ^ 0.5` is still shown as 2. +//! +//! The one remaining limit is a sum of exact values whose true result needs +//! more than 28 digits: `1000000000000000 + 0.0000000000000001` can't be +//! held, so it's rounded and becomes Guarded, and taking 1000000000000000 +//! back off gives 0, as omacalc's double does. Fixing that would take a +//! wider number type. +//! +//! Like C's `%g`, a value switches to exponent form (`1.5e+20`, `1e-05`) //! when its exponent is below −4 or at least the precision (16 for decimal //! values, 15 for `f64`). use std::fmt::Write as _; use std::str::FromStr; -use rust_decimal::{Decimal, MathematicalOps}; +use rust_decimal::Decimal; /// Significant digits shown for a decimal value, and the most that can be typed. const EXACT_DIGITS: u32 = 16; /// Significant digits shown for an `f64` value: what a double holds reliably. const FLOAT_DIGITS: u32 = 15; -/// The working precision for guarded and approximate results: sums, -/// differences, products and powers are rounded to this many significant -/// digits (see [`settle`]). -const WORKING_DIGITS: u32 = 20; -/// Cut-off quotients (÷, and powers with a negative exponent) keep two more -/// digits, so the next rounding to [`WORKING_DIGITS`] absorbs their -/// last-place error. -const QUOTIENT_DIGITS: u32 = WORKING_DIGITS + 2; +/// The fewest significant digits a rounded product or quotient may hold and +/// stay a decimal (see [`settle`]). Its rounding error is then at most +/// 5 × 10⁻²⁶ of it, far enough below the 10⁻²⁴ snap that a chain of rounded +/// steps still cancels to 0. +const GUARDED_DIGITS: u32 = 26; /// A decimal keeps this many places after the point, whatever its size. const DECIMAL_PLACES: i32 = 28; -/// The smallest power of ten whose value 28 places hold to 16 significant -/// digits: 10⁻¹³. -const SMALLEST_FULL_EXPONENT: i32 = EXACT_DIGITS as i32 - 1 - DECIMAL_PLACES; -/// The smallest power of ten whose value 28 places hold to 22 significant -/// digits: 10⁻⁷. -const SMALLEST_QUOTIENT_EXPONENT: i32 = QUOTIENT_DIGITS as i32 - 1 - DECIMAL_PLACES; +/// The smallest power of ten whose value 28 places hold to 26 significant +/// digits: 10⁻³. +const SMALLEST_GUARDED_EXPONENT: i32 = GUARDED_DIGITS as i32 - 1 - DECIMAL_PLACES; /// Cancellation snapping for a guarded sum or difference: this small /// relative to its larger operand, it's residue from rounding, so it's 0. -const GUARDED_CANCELLATION: Decimal = Decimal::from_parts(1, 0, 0, false, 18); +/// A 28-digit value leaves about 10⁻²⁷ a step, and a real difference like +/// `1 ÷ 3 − 0.333333333333333333` (3 × 10⁻¹⁹) is far above it. +const GUARDED_CANCELLATION: Decimal = Decimal::from_parts(1, 0, 0, false, 24); /// The same for an approximate one. An `f64`'s own error is about 10⁻¹⁶, so /// a few units in the last place snap, but a real difference against a /// number typed to 15 digits (`2 ^ 0.5 − 1.41421356237309`, 3.6 × 10⁻¹⁵ of @@ -243,33 +253,32 @@ impl Num { other, Kind::Sum, Decimal::checked_add, - |a, b, r| r.checked_sub(b) == Some(a), + lossless_add, |a, b| a + b, ), Op::Sub => self.combine( other, Kind::Sum, Decimal::checked_sub, - |a, b, r| r.checked_add(b) == Some(a), + lossless_sub, |a, b| a - b, ), Op::Mul => self.combine( other, Kind::Product, Decimal::checked_mul, - |a, b, r| b.is_zero() || r.checked_div(b) == Some(a), + lossless_mul, |a, b| a * b, ), Op::Div => { if other.is_zero() { return Err(NoAnswer); } - // A quotient ends exactly when it multiplies back to the dividend. self.combine( other, Kind::Quotient, Decimal::checked_div, - |a, b, r| r.checked_mul(b) == Some(a), + lossless_div, |a, b| a / b, ) } @@ -336,16 +345,15 @@ enum Kind { /// /// * A lossless result keeps its inputs' level; anything else is at least /// Guarded. -/// * An Exact result is kept as it is: never rounded. -/// * A Guarded or Approx result is rounded: a cut-off quotient to 22 -/// significant digits ([`QUOTIENT_DIGITS`]), anything else to 20 -/// ([`WORKING_DIGITS`]). The precision is the same at every size: guard -/// digits counted in places (a decimal's 28) would run out for a small -/// quotient like 1 ÷ 3000. -/// * Small rounded values can't carry those digits in 28 places, so they go -/// to `f64`: a product or power below 10⁻¹³ and a cut-off quotient below -/// 10⁻⁷. A zero is kept only when zero is the true answer (`zero_ok`), not -/// when a tiny product rounded away. +/// * No result is rounded beyond what the decimal itself did: a Guarded +/// result keeps all 28–29 digits, and cancellation snapping (see [`snap`]) +/// clears the residue a rounded step leaves. +/// * A decimal keeps 28 places rather than 28 significant digits, so a small +/// rounded result holds few digits. A rounded (Guarded or Approx) product, +/// power or cut-off quotient that holds fewer than 26 significant digits +/// ([`GUARDED_DIGITS`], so below 10⁻³) goes to `f64` instead. A zero is +/// kept only when zero is the true answer (`zero_ok`), not when a tiny +/// product rounded away. fn settle( kind: Kind, raw: Decimal, @@ -364,22 +372,21 @@ fn settle( if level == Level::Exact { return Some((raw.normalize(), level)); } - let (digits, smallest) = match kind { - Kind::Sum => (WORKING_DIGITS, i32::MIN), - Kind::Product => (WORKING_DIGITS, SMALLEST_FULL_EXPONENT), - Kind::Quotient if lossless => (QUOTIENT_DIGITS, i32::MIN), - Kind::Quotient => (QUOTIENT_DIGITS, SMALLEST_QUOTIENT_EXPONENT), + let smallest = match kind { + Kind::Sum => i32::MIN, + Kind::Quotient if lossless => i32::MIN, + Kind::Product | Kind::Quotient => SMALLEST_GUARDED_EXPONENT, }; if first_digit_exponent(raw) < smallest { return None; } - Some((raw.round_sf(digits).unwrap_or(raw).normalize(), level)) + Some((raw.normalize(), level)) } /// Cancellation snapping for + and −: a non-zero sum or difference this /// small next to its larger operand (`largest`) is residue from rounding, -/// so it's 0. Exact results never snap; Guarded ones at 10⁻¹⁸ of `largest`, -/// Approx ones at 10⁻¹⁵. +/// so it's 0. Exact results never snap; Guarded ones at 10⁻²⁴ of `largest` +/// (a 28-digit value's residue is about 10⁻²⁷ a step), Approx ones at 10⁻¹⁵. fn snap(kind: Kind, value: Num, largest: Decimal) -> Num { let Num::Dec(result, level) = value else { return value; @@ -410,21 +417,206 @@ fn first_digit_exponent(value: Decimal) -> i32 { /// it out in `f64`. A negative power is the reciprocal of the positive one, /// so it's settled as a quotient and gets the same guard digits as 1 ÷ x. fn integer_power(base: Decimal, e: i64, level: Level) -> Option<(Decimal, Level)> { - let n = e.unsigned_abs(); - let power = base.checked_powu(n)?; - // A normalized base ends in a non-zero digit, so its power does too: the - // power lost nothing exactly when it kept every place. - let places = u64::from(base.normalize().scale()) * n; - let lossless = u64::from(power.normalize().scale()) == places; - let (power, level) = settle(Kind::Product, power, lossless, level, base.is_zero())?; + let (raw, lossless) = power(base, e.unsigned_abs())?; + let (raw, level) = settle(Kind::Product, raw, lossless, level, base.is_zero())?; if e >= 0 { - return Some((power, level)); + return Some((raw, level)); } - let reciprocal = Decimal::ONE.checked_div(power)?; - let ends = reciprocal.checked_mul(power) == Some(Decimal::ONE); + let reciprocal = Decimal::ONE.checked_div(raw)?; + let ends = lossless_div(Decimal::ONE, raw, reciprocal); settle(Kind::Quotient, reciprocal, ends, level, false) } +/// A 256-bit unsigned integer: wide enough for the exact sum or product of +/// two decimal mantissas (96 bits each, aligned by up to 10²⁸), so the +/// lossless checks below can compare rust_decimal's result with the true one. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct Wide([u64; 4]); + +impl Wide { + fn from_u128(x: u128) -> Wide { + Wide([x as u64, (x >> 64) as u64, 0, 0]) + } + + fn is_zero(self) -> bool { + self.0 == [0; 4] + } + + fn mul_u64(self, m: u64) -> Option { + let mut out = [0u64; 4]; + let mut carry = 0u128; + for (o, limb) in out.iter_mut().zip(self.0) { + let t = u128::from(limb) * u128::from(m) + carry; + *o = t as u64; + carry = t >> 64; + } + (carry == 0).then_some(Wide(out)) + } + + fn mul_u128(self, m: u128) -> Option { + let low = self.mul_u64(m as u64)?; + let high = self.mul_u64((m >> 64) as u64)?; + if high.0[3] != 0 { + return None; + } + low.add(Wide([0, high.0[0], high.0[1], high.0[2]])) + } + + fn mul_pow10(mut self, mut k: u32) -> Option { + while k > 0 { + let step = k.min(19); + self = self.mul_u64(10u64.pow(step))?; + k -= step; + } + Some(self) + } + + fn add(self, other: Wide) -> Option { + let mut out = [0u64; 4]; + let mut carry = false; + for (o, (x, y)) in out.iter_mut().zip(self.0.into_iter().zip(other.0)) { + let (s, c1) = x.overflowing_add(y); + let (s, c2) = s.overflowing_add(u64::from(carry)); + *o = s; + carry = c1 || c2; + } + (!carry).then_some(Wide(out)) + } + + /// `self − other`, for `self ≥ other`. + fn sub(self, other: Wide) -> Wide { + let mut out = [0u64; 4]; + let mut borrow = false; + for (o, (x, y)) in out.iter_mut().zip(self.0.into_iter().zip(other.0)) { + let (d, b1) = x.overflowing_sub(y); + let (d, b2) = d.overflowing_sub(u64::from(borrow)); + *o = d; + borrow = b1 || b2; + } + Wide(out) + } + + fn less_than(self, other: Wide) -> bool { + self.0.iter().rev().lt(other.0.iter().rev()) + } + + fn div_rem_10(self) -> (Wide, u64) { + let mut out = [0u64; 4]; + let mut rem = 0u128; + for i in (0..4).rev() { + let cur = (rem << 64) | u128::from(self.0[i]); + out[i] = (cur / 10) as u64; + rem = cur % 10; + } + (Wide(out), rem as u64) + } +} + +/// An exact decimal value, `mag × 10^−scale`, with trailing zeros removed +/// (down to scale 0), so equal values compare equal. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct Value { + negative: bool, + mag: Wide, + scale: u32, +} + +impl Value { + fn new(negative: bool, mut mag: Wide, mut scale: u32) -> Value { + while scale > 0 { + let (q, r) = mag.div_rem_10(); + if r != 0 { + break; + } + mag = q; + scale -= 1; + } + let negative = negative && !mag.is_zero(); + let scale = if mag.is_zero() { 0 } else { scale }; + Value { + negative, + mag, + scale, + } + } + + fn of(d: Decimal) -> Value { + Value::new( + d.is_sign_negative(), + Wide::from_u128(d.mantissa().unsigned_abs()), + d.scale(), + ) + } + + /// The true `a ± b`. + fn sum(a: Decimal, b: Decimal, subtract: bool) -> Option { + let scale = a.scale().max(b.scale()); + let ma = Wide::from_u128(a.mantissa().unsigned_abs()).mul_pow10(scale - a.scale())?; + let mb = Wide::from_u128(b.mantissa().unsigned_abs()).mul_pow10(scale - b.scale())?; + let (na, nb) = (a.is_sign_negative(), b.is_sign_negative() ^ subtract); + Some(if na == nb { + Value::new(na, ma.add(mb)?, scale) + } else if mb.less_than(ma) { + Value::new(na, ma.sub(mb), scale) + } else { + Value::new(nb, mb.sub(ma), scale) + }) + } + + /// The true `a × b`. + fn product(a: Decimal, b: Decimal) -> Option { + let mag = + Wide::from_u128(a.mantissa().unsigned_abs()).mul_u128(b.mantissa().unsigned_abs())?; + let negative = a.is_sign_negative() ^ b.is_sign_negative(); + Some(Value::new(negative, mag, a.scale() + b.scale())) + } +} + +// rust_decimal's checked_add, checked_sub, checked_mul and checked_div don't +// fail when a result needs more than 28 places or 96 bits: they round it, +// silently. So whether an operation lost anything is decided here by +// comparing its result with the true value, worked out exactly in 256 bits, +// and never by undoing it with another rounding operation. + +/// Whether `r` is exactly `a + b`. +fn lossless_add(a: Decimal, b: Decimal, r: Decimal) -> bool { + Value::sum(a, b, false) == Some(Value::of(r)) +} + +/// Whether `r` is exactly `a − b`. +fn lossless_sub(a: Decimal, b: Decimal, r: Decimal) -> bool { + Value::sum(a, b, true) == Some(Value::of(r)) +} + +/// Whether `r` is exactly `a × b`. +fn lossless_mul(a: Decimal, b: Decimal, r: Decimal) -> bool { + Value::product(a, b) == Some(Value::of(r)) +} + +/// Whether the quotient `q = a ÷ b` ends: `q × b` is exactly `a`. +fn lossless_div(a: Decimal, b: Decimal, q: Decimal) -> bool { + Value::product(q, b) == Some(Value::of(a)) +} + +/// `base ^ n` by squaring, and whether every multiplication was lossless. +fn power(base: Decimal, mut n: u64) -> Option<(Decimal, bool)> { + let (mut result, mut square, mut lossless) = (Decimal::ONE, base, true); + while n > 0 { + if n & 1 == 1 { + let next = result.checked_mul(square)?; + lossless &= lossless_mul(result, square, next); + result = next; + } + n >>= 1; + if n > 0 { + let next = square.checked_mul(square)?; + lossless &= lossless_mul(square, square, next); + square = next; + } + } + Some((result, lossless)) +} + /// Rounds to 16 significant digits and lays the digits out. fn format_exact(value: Decimal) -> String { if value.is_zero() { @@ -571,15 +763,21 @@ fn parse_number(text: &str) -> Option { } } - let exact = if exponent.is_some() { + let parsed = if exponent.is_some() { Decimal::from_scientific(text).ok() } else { Decimal::from_str(text).ok() }; - match exact { - Some(d) if !(d.is_zero() && text.bytes().any(|b| (b'1'..=b'9').contains(&b))) => { - Some(Num::exact(d)) - } + // from_str rounds a number with more digits or places than a decimal + // holds, so it's exact only when it matches the text's true value. + let exponent: i64 = match exponent { + Some(e) => e.parse().ok()?, + None => 0, + }; + let scale = fraction.len() as i64 - exponent; + let truth = text_value(text.starts_with('-'), &format!("{whole}{fraction}"), scale); + match parsed { + Some(d) if truth.is_some_and(|t| t == Value::of(d)) => Some(Num::exact(d)), _ => { let value = f64::from_str(text).ok()?; // 1e-400 reads as 0 in f64: refuse it rather than show 0. @@ -592,6 +790,22 @@ fn parse_number(text: &str) -> Option { } } +/// The exact value of `digits × 10^−scale`, or `None` when it's too long +/// to work out (and so can't be a decimal anyway). +fn text_value(negative: bool, digits: &str, scale: i64) -> Option { + let digits = digits.trim_start_matches('0'); + let mut mag = Wide::from_u128(0); + for b in digits.bytes() { + mag = mag + .mul_u64(10)? + .add(Wide::from_u128(u128::from(b - b'0')))?; + } + if scale < 0 { + mag = mag.mul_pow10(u32::try_from(-scale).ok()?)?; + } + Some(Value::new(negative, mag, u32::try_from(scale.max(0)).ok()?)) +} + #[derive(Clone, Copy, Debug, PartialEq)] enum Token { Num(Num), @@ -1377,6 +1591,251 @@ mod tests { assert!(checked > 3000, "only {checked} cases fit a decimal"); } + /// rust_decimal rounds silently; a rounded result is never marked Exact. + #[test] + fn silent_rounding_is_caught() { + // 1.234567890123456e-20 needs 36 places: rounded, so not exact, and + // too small to keep 26 digits, so it's worked out in f64. + assert_eq!( + shows( + ". 0 0 0 0 0 0 0 0 0 1 × . 0 0 0 0 0 0 0 0 0 1 × 1 . 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 =" + ), + format_float(1.234567890123456e-20) + ); + assert_eq!( + shows("3 4 ÷ 7 . 6 7 + 9 . 3 ÷ 7 . 6 7 - 4 3 . 3 ÷ 7 . 6 7 ="), + "0" + ); + let sixths = "1 ÷ 1 . 2 + ".repeat(5) + "1 ÷ 1 . 2 - 5 ="; + assert_eq!(shows(&sixths), "0"); + assert_eq!( + shows("2 . 4 7 5 8 ^ 2 sign × 2 . 4 7 5 8 × 2 . 4 7 5 8 - 1 ="), + "0" + ); + let mut calc = Calc::new(); + assert!(calc.paste("0.00000000000000000000000000015")); + assert_eq!(calc.display(), "1.5e-28"); + } + + /// Guarded values keep every digit the decimal holds. + #[test] + fn guarded_values_keep_their_digits() { + assert_eq!( + shows("2 ÷ 3 + 1 0 0 0 0 0 0 0 0 0 0 - 1 0 0 0 0 0 0 0 0 0 0 ="), + "0.6666666666666667" + ); + let mut calc = Calc::new(); + press(&mut calc, "1 ÷ 3 -"); + assert!(calc.paste("0.333333333333333333")); + press(&mut calc, "="); + let rest = calc.display(); + assert!( + rest.starts_with("3.333333333") && rest.ends_with("e-19"), + "{rest}" + ); + } + + /// The remaining limit: a sum of typed numbers that needs more than 28 + /// digits is rounded (Guarded), as omacalc's double rounds it too. + #[test] + fn sums_past_28_digits_round() { + assert_eq!( + shows( + "1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 + . 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 \ + - 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 =" + ), + "0" + ); + } + + /// Backspace over a whole new operand shows the previous one, as omacalc + /// does (its display falls back to the last operand when nothing's typed). + #[test] + fn backspace_over_new_operand_shows_previous() { + let mut calc = Calc::new(); + press(&mut calc, "1 2 + 3 backspace"); + assert_eq!(calc.display(), "12"); + assert_eq!(calc.expression(), "12 +"); + press(&mut calc, "4 ="); + assert_eq!(calc.display(), "16"); + } + + /// A reference value `m × 10^−s` (`s` may be negative), worked in i128, + /// independent of rust_decimal. + #[derive(Clone, Copy, Debug, PartialEq)] + struct Ref { + m: i128, + s: i32, + } + + impl Ref { + fn of(d: Decimal) -> Ref { + Ref { + m: d.mantissa(), + s: d.scale() as i32, + } + .normal() + } + + fn normal(mut self) -> Ref { + while self.m != 0 && self.m % 10 == 0 { + self.m /= 10; + self.s -= 1; + } + if self.m == 0 { + self.s = 0; + } + self + } + + fn scaled(self, s: i32) -> Option { + self.m + .checked_mul(10i128.checked_pow(u32::try_from(s - self.s).ok()?)?) + } + + fn add(self, other: Ref, subtract: bool) -> Option { + let s = self.s.max(other.s); + let (a, b) = (self.scaled(s)?, other.scaled(s)?); + let m = if subtract { + a.checked_sub(b)? + } else { + a.checked_add(b)? + }; + Some(Ref { m, s }.normal()) + } + + fn mul(self, other: Ref) -> Option { + let m = self.m.checked_mul(other.m)?; + Some( + Ref { + m, + s: self.s + other.s, + } + .normal(), + ) + } + + /// Whether a decimal can hold this value exactly: a 96-bit mantissa + /// and at most 28 places. + fn fits(self) -> bool { + let r = self.normal(); + let m = if r.s < 0 { + match r.scaled(0) { + Some(m) => m, + None => return false, + } + } else { + r.m + }; + r.s <= 28 && m.unsigned_abs() < (1u128 << 96) + } + } + + /// A typed operand: 1–16 significant digits, scale −10 to 16, either sign. + fn reference_operand(rng: &mut Rng) -> Decimal { + let len = 1 + rng.below(16) as usize; + let mut m: i128 = rng.digits(len).parse().unwrap(); + if rng.below(2) == 0 { + m = -m; + } + let scale = rng.below(27) as i32 - 10; + if scale < 0 { + Decimal::from_i128_with_scale(m * 10i128.pow(scale.unsigned_abs()), 0) + } else { + Decimal::from_i128_with_scale(m, scale as u32) + } + } + + /// The key test for precision: every result marked Exact is the true + /// value, and every true value a decimal can hold is marked Exact. + #[test] + fn property_exact_means_exact() { + let mut rng = Rng(0x1234_5678_9abc_def1); + for op in [Op::Add, Op::Sub, Op::Mul] { + let mut checked = 0; + for _ in 0..20_000 { + let (a, b) = (reference_operand(&mut rng), reference_operand(&mut rng)); + let truth = match op { + Op::Add => Ref::of(a).add(Ref::of(b), false), + Op::Sub => Ref::of(a).add(Ref::of(b), true), + _ => Ref::of(a).mul(Ref::of(b)), + }; + let Some(truth) = truth else { continue }; + checked += 1; + let result = Num::exact(a).apply(op, Num::exact(b)); + if let Ok(Num::Dec(d, Level::Exact)) = result { + assert_eq!(Ref::of(d), truth, "{a} {op:?} {b} marked Exact as {d}"); + } + if truth.fits() { + assert!( + matches!(result, Ok(Num::Dec(_, Level::Exact))), + "{a} {op:?} {b} fits a decimal but is {result:?}" + ); + } + } + assert!(checked > 15_000, "{op:?}: only {checked} cases fit i128"); + } + + let mut checked = 0; + for _ in 0..20_000 { + let (a, b) = (reference_operand(&mut rng), reference_operand(&mut rng)); + if b.is_zero() { + continue; + } + if let Ok(Num::Dec(q, Level::Exact)) = Num::exact(a).apply(Op::Div, Num::exact(b)) + && let Some(back) = Ref::of(q).mul(Ref::of(b)) + { + checked += 1; + assert_eq!(back, Ref::of(a), "{a} ÷ {b} marked Exact as {q}"); + } + } + assert!(checked > 1000, "only {checked} exact quotients checked"); + } + + /// Typed operands of 1–10 digits as numbers, for the residue shapes. + fn residue_operand(rng: &mut Rng) -> Num { + Num::exact(Decimal::from_str(&typed_operand(rng)).unwrap()) + } + + #[test] + fn property_residue_shapes_cancel() { + let mut rng = Rng(0x0dd_ba11_cafe_f00d); + let (div, add, sub, mul) = (Op::Div, Op::Add, Op::Sub, Op::Mul); + for _ in 0..5000 { + let (a, b, c) = ( + residue_operand(&mut rng), + residue_operand(&mut rng), + residue_operand(&mut rng), + ); + let q = |x: Num| x.apply(div, b).unwrap(); + + let round_trip = q(a).apply(mul, b).unwrap().apply(sub, a).unwrap(); + assert!( + round_trip.is_zero(), + "{a:?} ÷ {b:?} × b − a = {round_trip:?}" + ); + + let split = q(a).apply(add, q(c)).unwrap(); + let whole = q(a.apply(add, c).unwrap()); + let left = split.apply(sub, whole).unwrap(); + assert!( + left.is_zero(), + "a÷b + c÷b − (a+c)÷b = {left:?} for {a:?} {b:?} {c:?}" + ); + + let mut sum = q(a); + for _ in 0..6 { + sum = sum.apply(add, q(a)).unwrap(); + } + let seven = q(a.apply(mul, Num::exact(Decimal::from(7))).unwrap()); + let left = sum.apply(sub, seven).unwrap(); + assert!( + left.is_zero(), + "7 × (a÷b) summed − 7a÷b = {left:?} for {a:?} {b:?}" + ); + } + } + /// A whole f64 past 2^53 isn't exact, so it isn't promoted with its noise. #[test] fn large_whole_floats_stay_approximate() { From 2c0b27c7c84c179567eb4d191b9e31a38991ae3e Mon Sep 17 00:00:00 2001 From: Michael Aguiar Date: Wed, 25 Nov 2026 13:36:21 -0700 Subject: [PATCH 27/50] Show f64-derived decimals at 15 digits; don't loop on a zero's exponent MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit From review round 6: a quotient small enough to go through f64 came back as a decimal and was then shown at 16 digits, so f64's rounding showed (8.88 ÷ 889507 × 889507 gave 8.880000000000002); Approx decimals now show 15 digits, as Floats do. Pasting 0e4294967295 looped through the exponent for ~0.4 s; a zero mantissa now returns at once. Drops rust_decimal's unused maths feature. ALI-2100 --- Cargo.toml | 2 +- src/engine.rs | 35 +++++++++++++++++++++++++++++++++-- 2 files changed, 34 insertions(+), 3 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index e83062f..2dc3074 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -7,7 +7,7 @@ description = "A tiny, instant calculator for aliasOS" publish = false [dependencies] -rust_decimal = { version = "1.43", default-features = false, features = ["std", "maths"] } +rust_decimal = { version = "1.43", default-features = false, features = ["std"] } [profile.release] lto = "fat" diff --git a/src/engine.rs b/src/engine.rs index 90dbeae..755d738 100644 --- a/src/engine.rs +++ b/src/engine.rs @@ -321,6 +321,9 @@ impl Num { /// The display text, without thousands separators. fn format(self) -> String { match self { + // A decimal that came back from f64 carries its error, so it's + // shown at f64's 15 digits, like a Float. + Num::Dec(d, Level::Approx) => format_decimal(d, FLOAT_DIGITS), Num::Dec(d, _) => format_exact(d), Num::Float(f) => format_float(f), } @@ -463,6 +466,10 @@ impl Wide { } fn mul_pow10(mut self, mut k: u32) -> Option { + // Zero times anything is zero; don't loop through a huge exponent. + if self.0 == [0; 4] { + return Some(self); + } while k > 0 { let step = k.min(19); self = self.mul_u64(10u64.pow(step))?; @@ -619,6 +626,11 @@ fn power(base: Decimal, mut n: u64) -> Option<(Decimal, bool)> { /// Rounds to 16 significant digits and lays the digits out. fn format_exact(value: Decimal) -> String { + format_decimal(value, EXACT_DIGITS) +} + +/// Rounds to `precision` significant digits and lays the digits out. +fn format_decimal(value: Decimal, precision: u32) -> String { if value.is_zero() { return "0".into(); } @@ -628,12 +640,12 @@ fn format_exact(value: Decimal) -> String { // value = digits × 10^(−scale), so the first digit's power of ten is: let exponent = all.len() as i32 - 1 - normal.scale() as i32; // Rounded by hand: `round_sf` can't round a value near Decimal::MAX. - let (digits, carried) = round_digits(&all, EXACT_DIGITS as usize); + let (digits, carried) = round_digits(&all, precision as usize); layout( mantissa < 0, &digits, exponent + i32::from(carried), - EXACT_DIGITS, + precision, ) } @@ -1278,6 +1290,25 @@ mod tests { calc.display() } + /// A decimal back from f64 shows f64's 15 digits, so its rounding error + /// doesn't: money divided by a large number and multiplied back. + #[test] + fn approx_decimals_hide_f64_noise() { + assert_eq!(shows("8 . 8 8 ÷ 8 8 9 5 0 7 × 8 8 9 5 0 7 ="), "8.88"); + assert_eq!(shows("1 . 4 3 ÷ 3 1 2 5 5 4 × 1 2 5 0 2 1 6 ="), "5.72"); + assert_eq!(shows("5 8 1 . 2 ÷ 5 8 1 4 3 2 × 5 8 1 4 3 2 0 ="), "5,812"); + } + + /// A pasted zero with a huge exponent is a quick, exact 0. + #[test] + fn pasted_zero_with_a_huge_exponent() { + let start = std::time::Instant::now(); + let mut calc = Calc::new(); + assert!(calc.paste("0e4294967295")); + assert_eq!(calc.display(), "0"); + assert!(start.elapsed().as_millis() < 50, "{:?}", start.elapsed()); + } + #[test] fn starts_at_zero() { let calc = Calc::new(); From b60176201d4bfda22a91102c4bdaab0486c76f80 Mon Sep 17 00:00:00 2001 From: Michael Aguiar Date: Wed, 25 Nov 2026 14:19:18 -0700 Subject: [PATCH 28/50] Show "Copied" after a copy Mike, after trying the build: a copy should show that it happened. The expression line shows Copied in the accent color for 1.2 s after Ctrl+C, Super+C or Ctrl+Insert takes the result (not on an error, or with nothing to copy into). Copying again restarts it; a key, a click or a paste ends it at once. Clearing it is one timed wakeup through the same poll timeout as Backspace repeat; startup and idle are unchanged. ALI-2107 --- src/ui.rs | 66 ++++++++++++++++++++++++++++++++++++++++++++++++++- src/window.rs | 28 ++++++++++++++++++++-- 2 files changed, 91 insertions(+), 3 deletions(-) diff --git a/src/ui.rs b/src/ui.rs index 8caec67..b9febae 100644 --- a/src/ui.rs +++ b/src/ui.rs @@ -137,6 +137,9 @@ pub struct View<'a> { /// The key drawn pressed, held with the mouse or the keyboard, as /// (row, column). pub pressed: Option<(usize, usize)>, + /// A short message ("Copied") shown in the accent color in place of + /// the expression line. + pub notice: Option<&'a str>, } // Logical sizes. @@ -220,7 +223,25 @@ pub fn draw( // The expression line and the result, right-aligned. let max_text = s(width - 2.0 * PADDING); let right = s(width - PADDING); - if !view.expression.is_empty() { + if let Some(notice) = view.notice { + let size = fonts.fit( + Face::Regular, + s(EXPRESSION_SIZE), + s(EXPRESSION_MIN_SIZE), + notice, + max_text, + ); + let w = fonts.width(Face::Regular, size, notice); + let baseline = s(layout.expression_baseline); + canvas.text( + fonts, + Face::Regular, + size, + notice, + (right - w, baseline), + palette.accent, + ); + } else if !view.expression.is_empty() { let size = fonts.fit( Face::Regular, s(EXPRESSION_SIZE), @@ -454,6 +475,7 @@ mod tests { expression: "", display, pressed: None, + notice: None, }; draw( &mut Canvas::new(&mut bytes, w, h), @@ -475,6 +497,47 @@ mod tests { } } + #[test] + fn a_notice_replaces_the_expression_in_the_accent_color() { + let mut fonts = Fonts::load(); + let palette = Palette::default(); + let (w, h) = (320usize, 480usize); + let draw_with = |fonts: &mut Fonts, notice| { + let mut bytes = vec![0; w * h * 4]; + let view = View { + expression: "12 +", + display: "12", + pressed: None, + notice, + }; + draw( + &mut Canvas::new(&mut bytes, w, h), + fonts, + &palette, + &view, + (320.0, 480.0), + 1.0, + ); + bytes + }; + let has = |bytes: &[u8], c: Color| { + bytes + .chunks(4) + .any(|p| (p[2], p[1], p[0]) == (c.r, c.g, c.b)) + }; + // The expression is drawn muted; with a notice, the accent shows in + // the expression line's rows and the muted ink doesn't. + let rows = |bytes: &[u8]| { + let top = PADDING as usize * w * 4; + let bottom = (h as f32 * DISPLAY_SHARE * 0.6) as usize * w * 4; + bytes[top..bottom].to_vec() + }; + let plain = rows(&draw_with(&mut fonts, None)); + let noted = rows(&draw_with(&mut fonts, Some("Copied"))); + assert!(has(&plain, palette.muted) && !has(&plain, palette.accent)); + assert!(has(¬ed, palette.accent) && !has(¬ed, palette.muted)); + } + #[test] fn keypad_fits_inside_the_window() { let fonts = Fonts::load(); @@ -518,6 +581,7 @@ mod tests { expression: "1,234 × 5,678 +", display: "7,006,652", pressed: Some((2, 1)), + notice: None, }; // Warm the glyph cache, as every frame after the first finds it. draw( diff --git a/src/window.rs b/src/window.rs index be35161..16c9da2 100644 --- a/src/window.rs +++ b/src/window.rs @@ -75,6 +75,9 @@ const MIN_SIZE: (u32, u32) = (260, 380); const DEFAULT_REPEAT: (Duration, Duration) = (Duration::from_millis(600), Duration::from_millis(40)); +/// How long "Copied" shows after a copy. +const NOTICE_TIME: Duration = Duration::from_millis(1200); + /// The left mouse button (linux/input-event-codes.h BTN_LEFT). const BTN_LEFT: u32 = 0x110; @@ -141,6 +144,7 @@ pub fn run() -> Result<(), Box> { cursor: None, modifiers: Modifiers::default(), calc: Calc::new(), + notice_until: None, data_manager, data_device: None, copied: None, @@ -195,6 +199,13 @@ fn event_loop( { app.repeat_tick(); } + if app + .notice_until + .is_some_and(|until| until <= Instant::now()) + { + app.notice_until = None; + app.dirty = true; + } if app.dirty && app.configured { app.draw()?; if app.keyboard_seat.is_some() || app.pointer_seat.is_some() { @@ -229,8 +240,13 @@ fn event_loop( }; // Only a held Backspace sets a timeout; otherwise sleep until the // compositor sends something. - let timeout = app.repeat.as_ref().map(|r| { - let wait = r.next.saturating_duration_since(Instant::now()); + // Only a held Backspace or a showing "Copied" sets a timeout. + let deadline = match (app.repeat.as_ref().map(|r| r.next), app.notice_until) { + (Some(a), Some(b)) => Some(a.min(b)), + (a, b) => a.or(b), + }; + let timeout = deadline.map(|next| { + let wait = next.saturating_duration_since(Instant::now()); Timespec { tv_sec: wait.as_secs() as _, tv_nsec: wait.subsec_nanos() as _, @@ -330,6 +346,8 @@ struct App { cursor: Option, modifiers: Modifiers, calc: Calc, + /// When "Copied" stops showing, while it shows. + notice_until: Option, /// Copy and paste; None when the compositor has no data device manager. data_manager: Option, data_device: Option, @@ -425,6 +443,8 @@ impl App { source.set_selection(device, serial); // Replacing the old source destroys it. self.copied = Some((source, self.calc.copy_text())); + self.notice_until = Some(Instant::now() + NOTICE_TIME); + self.dirty = true; } /// Ctrl+V: starts reading the selection; `event_loop` finishes it. @@ -451,6 +471,7 @@ impl App { Progress::Pending => Some(reading), Progress::Done(text) => { if self.calc.paste(&text) { + self.notice_until = None; self.dirty = true; } None @@ -485,6 +506,8 @@ impl App { fn press(&mut self, key: Key) { self.calc.press(key); + // Carrying on hides "Copied" at once. + self.notice_until = None; self.dirty = true; } @@ -587,6 +610,7 @@ impl App { expression: &expression, display: &display, pressed, + notice: self.notice_until.map(|_| "Copied"), }; let mut canvas = Canvas::new(canvas, pw as usize, ph as usize); let logical = (self.size.0 as f32, self.size.1 as f32); From a71676bead67fc9c9d349160ec1256d941d30710 Mon Sep 17 00:00:00 2001 From: Michael Aguiar Date: Wed, 25 Nov 2026 14:20:49 -0700 Subject: [PATCH 29/50] End "Copied" on any click and on Ctrl+V; fix stale comments From review: a click off the keys, or a Ctrl+V with nothing to paste, left Copied showing for the rest of its 1.2 s; the loop's comments still named Backspace repeat as the only timeout. ALI-2107 --- src/window.rs | 26 ++++++++++++++++++-------- 1 file changed, 18 insertions(+), 8 deletions(-) diff --git a/src/window.rs b/src/window.rs index 16c9da2..45fd73f 100644 --- a/src/window.rs +++ b/src/window.rs @@ -177,8 +177,9 @@ pub fn run() -> Result<(), Box> { type Queue = smithay_client_toolkit::reexports::client::EventQueue; /// Dispatch, draw if anything changed, then sleep until the compositor -/// writes to the socket, the theme changes or a paste arrives. The only timeout is a held -/// Backspace's next repeat, so an idle window never wakes. `theme` is None +/// writes to the socket, the theme changes or a paste arrives. The only +/// timeouts are a held Backspace's next repeat and the end of a showing +/// "Copied", so an idle window never wakes. `theme` is None /// when there's no theme to follow. fn event_loop( queue: &mut Queue, @@ -238,9 +239,8 @@ fn event_loop( } else { PollFlags::IN }; - // Only a held Backspace sets a timeout; otherwise sleep until the - // compositor sends something. - // Only a held Backspace or a showing "Copied" sets a timeout. + // Only a held Backspace or a showing "Copied" sets a timeout; + // otherwise sleep until something arrives. let deadline = match (app.repeat.as_ref().map(|r| r.next), app.notice_until) { (Some(a), Some(b)) => Some(a.min(b)), (a, b) => a.or(b), @@ -277,7 +277,8 @@ fn event_loop( } app.paste = paste; match polled { - // The repeat's time came: the top of the loop fires it. + // A repeat or the end of "Copied" came due: the top of the + // loop handles both. Ok(0) => { drop(guard); continue; @@ -449,6 +450,8 @@ impl App { /// Ctrl+V: starts reading the selection; `event_loop` finishes it. fn paste(&mut self) { + // Asking to paste ends "Copied", whether or not anything arrives. + self.end_notice(); let Some(offer) = self .data_device .as_ref() @@ -471,7 +474,6 @@ impl App { Progress::Pending => Some(reading), Progress::Done(text) => { if self.calc.paste(&text) { - self.notice_until = None; self.dirty = true; } None @@ -507,10 +509,16 @@ impl App { fn press(&mut self, key: Key) { self.calc.press(key); // Carrying on hides "Copied" at once. - self.notice_until = None; + self.end_notice(); self.dirty = true; } + fn end_notice(&mut self) { + if self.notice_until.take().is_some() { + self.dirty = true; + } + } + /// Reads the theme again. A theme that can't be read keeps the colors /// already showing rather than flashing the built-in ones. fn reload_theme(&mut self) { @@ -960,6 +968,8 @@ impl PointerHandler for App { PointerEventKind::Press { button: BTN_LEFT, .. } => { + // Any click ends "Copied", on a key or not. + self.end_notice(); self.mouse_down = self.button_under_pointer(); } PointerEventKind::Release { From fd1e680296858592998b802fb858643aa1bc242a Mon Sep 17 00:00:00 2001 From: Michael Aguiar Date: Wed, 25 Nov 2026 14:50:31 -0700 Subject: [PATCH 30/50] Meet WCAG AA contrast with any theme Mike: all of our apps should follow WCAG guidelines. The design canvas's contrast table had the expression line (18 px, muted) at 4.1:1 on the built-in palette and 4.2-4.3 on Tarnished and Papercraft; AA needs 4.5. Muted moves from 55% to 65% of the way to the foreground, which clears 4.5:1 on every aliasOS theme as it is. On top of that, Palette::new now checks each text colour against every fill it's drawn on and moves it towards white or black until it passes: 4.5:1 for the 18 px expression line and Copied, 3:1 for the result and the key labels (24 px and up). Copied and the operators get their own colours (notice, operator) so a low-contrast accent can be lifted for text without changing the = key's fill. A property test over 20,000 random themes checks every pair. ALI-2110 --- src/ui.rs | 164 +++++++++++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 156 insertions(+), 8 deletions(-) diff --git a/src/ui.rs b/src/ui.rs index b9febae..b37f924 100644 --- a/src/ui.rs +++ b/src/ui.rs @@ -79,8 +79,16 @@ fn role(label: &str) -> Role { #[derive(Clone, Copy, Debug, PartialEq)] pub struct Palette { pub background: Color, + /// The result and digit labels. pub foreground: Color, + /// The `=` key's fill. pub accent: Color, + /// The `=` key's fill while held. + pub accent_pressed: Color, + /// "Copied": the accent, made readable as small text on the background. + pub notice: Color, + /// ÷ × − +: the accent, made readable on the keys. + pub operator: Color, /// The expression line and the function keys' labels. pub muted: Color, pub key: Color, @@ -89,28 +97,85 @@ pub struct Palette { pub on_accent: Color, } +/// WCAG 2.2 AA: text needs 4.5:1; large text (24 px and up, which every key +/// label and the result are) needs 3:1. +const TEXT_CONTRAST: f32 = 4.5; +const LARGE_CONTRAST: f32 = 3.0; + +const WHITE: Color = Color::rgb(255, 255, 255); +const BLACK: Color = Color::rgb(0, 0, 0); + impl Palette { pub fn new(background: Color, foreground: Color, accent: Color) -> Self { // 0.18 is where a color contrasts equally with black and white. let dark = background.luminance() < 0.18; let key = background.mix(foreground, if dark { 0.08 } else { 0.06 }); let key_pressed = background.mix(foreground, if dark { 0.18 } else { 0.14 }); + let accent_pressed = accent.mix(background, 0.25); // Whichever of background and foreground reads better on the accent. let on_accent = if contrast(accent, background) >= contrast(accent, foreground) { background } else { foreground }; + // Every text colour is checked against every fill it's drawn on, and + // moved towards white or black until it passes, so a theme nobody + // tried still meets AA. Most themes need no change. + let keys = [key, key_pressed]; Self { background, - foreground, + foreground: readable(foreground, &[background, key, key_pressed], LARGE_CONTRAST), accent, - muted: background.mix(foreground, 0.55), + accent_pressed, + notice: readable(accent, &[background], TEXT_CONTRAST), + operator: readable(accent, &keys, LARGE_CONTRAST), + // 65% of the way to the foreground clears 4.5:1 on every aliasOS + // theme as it is; `readable` covers the rest. + muted: readable( + readable( + background.mix(foreground, 0.65), + &[background], + TEXT_CONTRAST, + ), + &[background, key, key_pressed], + LARGE_CONTRAST, + ), key, key_pressed, - on_accent, + on_accent: readable(on_accent, &[accent, accent_pressed], LARGE_CONTRAST), + } + } +} + +/// `ink`, or the nearest colour towards white or black that has at least +/// `min` contrast with every one of `grounds`. Whichever direction needs the +/// smaller step wins; if neither gets there, the better of white and black. +fn readable(ink: Color, grounds: &[Color], min: f32) -> Color { + let worst = |c: Color| { + grounds + .iter() + .map(|&g| contrast(c, g)) + .fold(f32::INFINITY, f32::min) + }; + if worst(ink) >= min { + return ink; + } + for step in 1..=20 { + let t = step as f32 / 20.0; + let candidates = [ink.mix(WHITE, t), ink.mix(BLACK, t)]; + let best = candidates + .into_iter() + .filter(|&c| worst(c) >= min) + .max_by(|&a, &b| worst(a).total_cmp(&worst(b))); + if let Some(c) = best { + return c; } } + if worst(WHITE) >= worst(BLACK) { + WHITE + } else { + BLACK + } } impl Default for Palette { @@ -239,7 +304,7 @@ pub fn draw( size, notice, (right - w, baseline), - palette.accent, + palette.notice, ); } else if !view.expression.is_empty() { let size = fonts.fit( @@ -293,7 +358,7 @@ pub fn draw( let (fill, ink) = match role(label) { Role::Equals => ( if pressed { - palette.accent.mix(palette.background, 0.25) + palette.accent_pressed } else { palette.accent }, @@ -306,7 +371,7 @@ pub fn draw( palette.key }; let ink = match other { - Role::Operator => palette.accent, + Role::Operator => palette.operator, Role::Function => palette.muted, _ => palette.foreground, }; @@ -534,8 +599,8 @@ mod tests { }; let plain = rows(&draw_with(&mut fonts, None)); let noted = rows(&draw_with(&mut fonts, Some("Copied"))); - assert!(has(&plain, palette.muted) && !has(&plain, palette.accent)); - assert!(has(¬ed, palette.accent) && !has(¬ed, palette.muted)); + assert!(has(&plain, palette.muted) && !has(&plain, palette.notice)); + assert!(has(¬ed, palette.notice) && !has(¬ed, palette.muted)); } #[test] @@ -552,6 +617,89 @@ mod tests { } } + /// Every text colour against every fill it's drawn on. + fn assert_aa(p: &Palette, theme: &str) { + let check = |what: &str, ink: Color, ground: Color, min: f32| { + let c = contrast(ink, ground); + assert!(c >= min, "{theme}: {what} is {c:.2}:1, needs {min}:1"); + }; + check("expression line", p.muted, p.background, TEXT_CONTRAST); + check("Copied", p.notice, p.background, TEXT_CONTRAST); + check("result", p.foreground, p.background, LARGE_CONTRAST); + for (fill, name) in [(p.key, "key"), (p.key_pressed, "held key")] { + check( + &format!("digit on {name}"), + p.foreground, + fill, + LARGE_CONTRAST, + ); + check( + &format!("function label on {name}"), + p.muted, + fill, + LARGE_CONTRAST, + ); + check( + &format!("operator on {name}"), + p.operator, + fill, + LARGE_CONTRAST, + ); + } + check("= label", p.on_accent, p.accent, LARGE_CONTRAST); + check( + "= label held", + p.on_accent, + p.accent_pressed, + LARGE_CONTRAST, + ); + } + + #[test] + fn aliasos_themes_meet_aa_and_keep_their_colours() { + let hex = |h: &str| Color::from_hex(h).unwrap(); + // The built-in palette and four themes from ~/.config/aliasos/themes. + for (name, bg, fg, accent) in [ + ("built-in", "#1a1b26", "#c0caf5", "#7aa2f7"), + ("tarnished", "#0b111a", "#c5ced6", "#5e92c6"), + ("ember-night", "#081822", "#dce4e8", "#f0502a"), + ("papercraft", "#1a1a1c", "#d8ccb8", "#d9692e"), + ("night-city", "#0a0c10", "#d4e2e4", "#e8cf45"), + ] { + let p = Palette::new(hex(bg), hex(fg), hex(accent)); + assert_aa(&p, name); + // These themes already pass: only muted moves. + assert_eq!(p.foreground, hex(fg), "{name}"); + assert_eq!(p.notice, hex(accent), "{name}"); + assert_eq!(p.operator, hex(accent), "{name}"); + assert_eq!(p.muted, hex(bg).mix(hex(fg), 0.65), "{name}"); + } + assert_eq!(Palette::default().muted, hex("#868dad")); + } + + #[test] + fn any_theme_meets_aa() { + // xorshift, fixed seed: random dark, light and mid-tone themes. + let mut x: u64 = 0x2545_f491_4f6c_dd1d; + let mut next = || { + x ^= x << 13; + x ^= x >> 7; + x ^= x << 17; + x + }; + let mut color = || { + let v = next(); + Color::rgb(v as u8, (v >> 8) as u8, (v >> 16) as u8) + }; + for i in 0..20_000 { + let (bg, fg, accent) = (color(), color(), color()); + assert_aa( + &Palette::new(bg, fg, accent), + &format!("theme {i} {bg:?} {fg:?} {accent:?}"), + ); + } + } + #[test] fn on_accent_picks_the_readable_label() { let dark = Palette::new( From 37ec03320e6590ebda44c197cca09370b901e49e Mon Sep 17 00:00:00 2001 From: Michael Aguiar Date: Wed, 25 Nov 2026 14:56:36 -0700 Subject: [PATCH 31/50] Give all text 4.5:1, at every size it's drawn From review: 3:1 assumed key labels and the result are large text (24 px and up), but the result shrinks to fit a long number and key labels drop to ~22 px at the minimum window, so several pairs fell under AA there (built-in function labels 4.41 on keys, 3.43 held; Papercraft and Ember Night operators 4.2). All text now gets 4.5:1. The expression line keeps #868dad; the function labels get their own colour (function) so lifting them on the keys doesn't brighten the expression line. The = label is chosen against the accent and a held = moves away from it (lighter under a dark label), since moving towards the background could land on a mid-tone no label passes. When no label colour can pass on a key fill (mid-tone backgrounds), the fills step away from the text until all do. A broken muted re-check and stale accent-colour docs are gone with the rewrite. any_theme_meets_aa now checks every pair at 4.5:1 over 20,000 random themes. ALI-2110 --- src/ui.rs | 179 +++++++++++++++++++++++++++++++++++------------------- 1 file changed, 117 insertions(+), 62 deletions(-) diff --git a/src/ui.rs b/src/ui.rs index b37f924..322975a 100644 --- a/src/ui.rs +++ b/src/ui.rs @@ -89,18 +89,21 @@ pub struct Palette { pub notice: Color, /// ÷ × − +: the accent, made readable on the keys. pub operator: Color, - /// The expression line and the function keys' labels. + /// The expression line. pub muted: Color, + /// C ± % ⌫: muted, made readable on the keys. + pub function: Color, pub key: Color, pub key_pressed: Color, /// The label on the accent-filled `=` key. pub on_accent: Color, } -/// WCAG 2.2 AA: text needs 4.5:1; large text (24 px and up, which every key -/// label and the result are) needs 3:1. +/// WCAG 2.2 AA for text: 4.5:1. Large text (24 px and up) only needs 3:1, +/// but nothing here is large at every size: the result shrinks to fit a long +/// number, and key labels drop to ~22 px at the minimum window. So all text +/// gets 4.5:1. const TEXT_CONTRAST: f32 = 4.5; -const LARGE_CONTRAST: f32 = 3.0; const WHITE: Color = Color::rgb(255, 255, 255); const BLACK: Color = Color::rgb(0, 0, 0); @@ -111,45 +114,112 @@ impl Palette { let dark = background.luminance() < 0.18; let key = background.mix(foreground, if dark { 0.08 } else { 0.06 }); let key_pressed = background.mix(foreground, if dark { 0.18 } else { 0.14 }); - let accent_pressed = accent.mix(background, 0.25); - // Whichever of background and foreground reads better on the accent. - let on_accent = if contrast(accent, background) >= contrast(accent, foreground) { - background + // Whichever of background and foreground reads better on the accent, + // made readable on it. + let on_accent = readable( + if contrast(accent, background) >= contrast(accent, foreground) { + background + } else { + foreground + }, + &[accent], + TEXT_CONTRAST, + ); + // A held = moves away from its label (lighter under a dark label, + // darker under a light one), so holding it only raises the label's + // contrast. Moving towards the background could land on a mid-tone + // where neither a dark nor a light label reaches 4.5:1. + let away = if on_accent.luminance() < accent.luminance() { + WHITE } else { - foreground + BLACK }; + let accent_pressed = accent.mix(away, 0.25); // Every text colour is checked against every fill it's drawn on, and // moved towards white or black until it passes, so a theme nobody - // tried still meets AA. Most themes need no change. - let keys = [key, key_pressed]; + // tried still meets AA. Most themes need no change. 65% of the way to + // the foreground clears 4.5:1 on the background for every aliasOS + // theme as it is. + let muted = readable( + background.mix(foreground, 0.65), + &[background], + TEXT_CONTRAST, + ); + let notice = readable(accent, &[background], TEXT_CONTRAST); + // On a mid-tone background a key fill can sit where no label reaches + // 4.5:1 however it's moved. Then the fills step away from the text + // (darker under light text, lighter under dark) until every label + // passes; on real themes the first try already does. + let text_is_light = + readable(foreground, &[background], TEXT_CONTRAST).luminance() > background.luminance(); + let away_from_text = if text_is_light { BLACK } else { WHITE }; + let (mut key, mut key_pressed) = (key, key_pressed); + let mut labels = KeyLabels::on(background, foreground, muted, accent, key, key_pressed); + for _ in 0..20 { + if labels.pass(background, key, key_pressed) { + break; + } + key = key.mix(away_from_text, 0.1); + key_pressed = key_pressed.mix(away_from_text, 0.1); + labels = KeyLabels::on(background, foreground, muted, accent, key, key_pressed); + } Self { background, - foreground: readable(foreground, &[background, key, key_pressed], LARGE_CONTRAST), + foreground: labels.foreground, accent, accent_pressed, - notice: readable(accent, &[background], TEXT_CONTRAST), - operator: readable(accent, &keys, LARGE_CONTRAST), - // 65% of the way to the foreground clears 4.5:1 on every aliasOS - // theme as it is; `readable` covers the rest. - muted: readable( - readable( - background.mix(foreground, 0.65), - &[background], - TEXT_CONTRAST, - ), - &[background, key, key_pressed], - LARGE_CONTRAST, - ), + notice, + operator: labels.operator, + muted, + function: labels.function, key, key_pressed, - on_accent: readable(on_accent, &[accent, accent_pressed], LARGE_CONTRAST), + on_accent, + } + } +} + +/// The text drawn on keys (and, for the result, on the background), each +/// made readable on every fill it sits on. +struct KeyLabels { + /// Digits and the result. + foreground: Color, + function: Color, + operator: Color, +} + +impl KeyLabels { + fn on( + background: Color, + foreground: Color, + muted: Color, + accent: Color, + key: Color, + pressed: Color, + ) -> Self { + Self { + foreground: readable(foreground, &[background, key, pressed], TEXT_CONTRAST), + function: readable(muted, &[key, pressed], TEXT_CONTRAST), + operator: readable(accent, &[key, pressed], TEXT_CONTRAST), } } + + fn pass(&self, background: Color, key: Color, pressed: Color) -> bool { + let ok = |ink: Color, grounds: &[Color]| { + grounds.iter().all(|&g| contrast(ink, g) >= TEXT_CONTRAST) + }; + ok(self.foreground, &[background, key, pressed]) + && ok(self.function, &[key, pressed]) + && ok(self.operator, &[key, pressed]) + } } /// `ink`, or the nearest colour towards white or black that has at least /// `min` contrast with every one of `grounds`. Whichever direction needs the -/// smaller step wins; if neither gets there, the better of white and black. +/// smaller step wins. If neither gets there it returns the better of white +/// and black; for 4.5:1 that can't happen with the grounds used here (white +/// or black reaches 4.58:1 on any one colour, and each set is close +/// together), which `any_theme_meets_aa` checks over 20,000 random themes. fn readable(ink: Color, grounds: &[Color], min: f32) -> Color { let worst = |c: Color| { grounds @@ -202,7 +272,8 @@ pub struct View<'a> { /// The key drawn pressed, held with the mouse or the keyboard, as /// (row, column). pub pressed: Option<(usize, usize)>, - /// A short message ("Copied") shown in the accent color in place of + /// A short message ("Copied") shown in the notice colour (the accent, + /// made readable) in place of /// the expression line. pub notice: Option<&'a str>, } @@ -372,7 +443,7 @@ pub fn draw( }; let ink = match other { Role::Operator => palette.operator, - Role::Function => palette.muted, + Role::Function => palette.function, _ => palette.foreground, }; (fill, ink) @@ -617,42 +688,25 @@ mod tests { } } - /// Every text colour against every fill it's drawn on. + /// Every text colour against every fill it's drawn on, at 4.5:1. fn assert_aa(p: &Palette, theme: &str) { - let check = |what: &str, ink: Color, ground: Color, min: f32| { + let check = |what: &str, ink: Color, ground: Color| { let c = contrast(ink, ground); - assert!(c >= min, "{theme}: {what} is {c:.2}:1, needs {min}:1"); + assert!( + c >= TEXT_CONTRAST, + "{theme}: {what} is {c:.2}:1, needs 4.5:1" + ); }; - check("expression line", p.muted, p.background, TEXT_CONTRAST); - check("Copied", p.notice, p.background, TEXT_CONTRAST); - check("result", p.foreground, p.background, LARGE_CONTRAST); + check("expression line", p.muted, p.background); + check("Copied", p.notice, p.background); + check("result", p.foreground, p.background); for (fill, name) in [(p.key, "key"), (p.key_pressed, "held key")] { - check( - &format!("digit on {name}"), - p.foreground, - fill, - LARGE_CONTRAST, - ); - check( - &format!("function label on {name}"), - p.muted, - fill, - LARGE_CONTRAST, - ); - check( - &format!("operator on {name}"), - p.operator, - fill, - LARGE_CONTRAST, - ); + check(&format!("digit on {name}"), p.foreground, fill); + check(&format!("function label on {name}"), p.function, fill); + check(&format!("operator on {name}"), p.operator, fill); } - check("= label", p.on_accent, p.accent, LARGE_CONTRAST); - check( - "= label held", - p.on_accent, - p.accent_pressed, - LARGE_CONTRAST, - ); + check("= label", p.on_accent, p.accent); + check("= label held", p.on_accent, p.accent_pressed); } #[test] @@ -668,10 +722,11 @@ mod tests { ] { let p = Palette::new(hex(bg), hex(fg), hex(accent)); assert_aa(&p, name); - // These themes already pass: only muted moves. + // On these themes the result, Copied and the expression line keep + // their colours; operators and function labels may lift on the + // keys, which are lighter than the background. assert_eq!(p.foreground, hex(fg), "{name}"); assert_eq!(p.notice, hex(accent), "{name}"); - assert_eq!(p.operator, hex(accent), "{name}"); assert_eq!(p.muted, hex(bg).mix(hex(fg), 0.65), "{name}"); } assert_eq!(Palette::default().muted, hex("#868dad")); From 809178f4bcfb2aa605cf0b55f36cc3e35e686ae2 Mon Sep 17 00:00:00 2001 From: Michael Aguiar Date: Wed, 25 Nov 2026 14:59:28 -0700 Subject: [PATCH 32/50] Assert the key-label loop passes; doc and test tidy-ups From review round 2 (no defects found; 4 million random themes and a grey sweep all pass): a debug_assert after the key-fill loop, readable()'s doc now says what its 5% steps pick, the notice test and comment no longer say accent, and the real-theme test pins a held = lightening under their dark labels. ALI-2110 --- src/ui.rs | 20 ++++++++++++++++---- 1 file changed, 16 insertions(+), 4 deletions(-) diff --git a/src/ui.rs b/src/ui.rs index 322975a..35e29fc 100644 --- a/src/ui.rs +++ b/src/ui.rs @@ -163,6 +163,12 @@ impl Palette { key_pressed = key_pressed.mix(away_from_text, 0.1); labels = KeyLabels::on(background, foreground, muted, accent, key, key_pressed); } + // Never seen to fail over 4 million random themes; if a change to the + // steps or mixes ever breaks that, debug builds and the tests say so. + debug_assert!( + labels.pass(background, key, key_pressed), + "key labels under 4.5:1" + ); Self { background, foreground: labels.foreground, @@ -215,8 +221,9 @@ impl KeyLabels { } /// `ink`, or the nearest colour towards white or black that has at least -/// `min` contrast with every one of `grounds`. Whichever direction needs the -/// smaller step wins. If neither gets there it returns the better of white +/// `min` contrast with every one of `grounds`. It moves in 5% steps and stops +/// at the first step where either direction passes, taking the direction +/// with more contrast there. If neither gets there it returns the better of white /// and black; for 4.5:1 that can't happen with the grounds used here (white /// or black reaches 4.58:1 on any one colour, and each set is close /// together), which `any_theme_meets_aa` checks over 20,000 random themes. @@ -634,7 +641,7 @@ mod tests { } #[test] - fn a_notice_replaces_the_expression_in_the_accent_color() { + fn a_notice_replaces_the_expression_in_its_own_colour() { let mut fonts = Fonts::load(); let palette = Palette::default(); let (w, h) = (320usize, 480usize); @@ -661,7 +668,7 @@ mod tests { .chunks(4) .any(|p| (p[2], p[1], p[0]) == (c.r, c.g, c.b)) }; - // The expression is drawn muted; with a notice, the accent shows in + // The expression is drawn muted; with a notice, the notice colour shows in // the expression line's rows and the muted ink doesn't. let rows = |bytes: &[u8]| { let top = PADDING as usize * w * 4; @@ -728,6 +735,11 @@ mod tests { assert_eq!(p.foreground, hex(fg), "{name}"); assert_eq!(p.notice, hex(accent), "{name}"); assert_eq!(p.muted, hex(bg).mix(hex(fg), 0.65), "{name}"); + // Under the dark = label these themes have, a held = lightens. + assert!( + p.accent_pressed.luminance() > p.accent.luminance(), + "{name}" + ); } assert_eq!(Palette::default().muted, hex("#868dad")); } From f4c9f2004e74062328741a055b4cad6b747f24bf Mon Sep 17 00:00:00 2001 From: Michael Aguiar Date: Wed, 25 Nov 2026 15:42:06 -0700 Subject: [PATCH 33/50] Meet WCAG 2.2 AA: key outlines, keyboard focus, 44 px keys, text size Mike's global rule: everything with a UI meets WCAG 2.2 AA. Misses fixed: - Control boundaries (1.4.11): key fills were 1.2:1 on the background. Every key gets a 1 px outline at 3:1 or more (readable(), like the text colours); the = key's accent is its own boundary unless it's under 3:1. Outline and fill draw in one pass (outlined_rect), so a frame costs 0.60 ms against 0.55. - Keyboard focus (2.1.1, 2.4.7): every function had a key, but nothing took focus. Tab / Shift+Tab move through the keys in reading order, the arrows around the grid; Space presses the focused key; Enter stays =. A 2 px ring in the 6 px gap shows from the first Tab or arrow and hides on a click. It's an outline, so focus isn't shown by colour alone. - Targets (house rule 44 px): keys were 43.6 px tall at the 260 x 380 minimum. The minimum is now 260 x 400 (keys 46.4 px). - Text size (1.4.4): the aliasOS text size (aliasos-display-text-size, [font] base-size in ~/.config/aliasos/shell.toml) now scales the text and, from 1.0 up, the starting and minimum window. It's followed live through the theme watch's inotify fd. ALI-2113 --- src/main.rs | 1 + src/render.rs | 42 ++++++-- src/textsize.rs | 76 ++++++++++++++ src/theme.rs | 105 ++++++++++++++++---- src/ui.rs | 257 +++++++++++++++++++++++++++++++++++++++++++----- src/window.rs | 95 ++++++++++++++++-- 6 files changed, 517 insertions(+), 59 deletions(-) create mode 100644 src/textsize.rs diff --git a/src/main.rs b/src/main.rs index 9408b01..e8b19d9 100644 --- a/src/main.rs +++ b/src/main.rs @@ -7,6 +7,7 @@ mod clipboard; mod engine; mod input; mod render; +mod textsize; mod theme; mod trace; mod ui; diff --git a/src/render.rs b/src/render.rs index 721fc47..2476993 100644 --- a/src/render.rs +++ b/src/render.rs @@ -56,7 +56,7 @@ impl Color { 0.2126 * linear(self.r) + 0.7152 * linear(self.g) + 0.0722 * linear(self.b) } - const fn pixel(self) -> [u8; 4] { + pub(crate) const fn pixel(self) -> [u8; 4] { [self.b, self.g, self.r, 0xff] } } @@ -98,10 +98,25 @@ impl<'a> Canvas<'a> { /// Fills a rectangle with corners of radius `r`, anti-aliased. All /// values are in pixels and may be fractional. pub fn rounded_rect(&mut self, x: f32, y: f32, w: f32, h: f32, r: f32, color: Color) { + self.outlined_rect((x, y, w, h), r, color, None); + } + + /// A rounded rectangle filled with `fill`, with an `edge` outline of + /// `width` pixels inside its bounds when given, in one pass: every pixel + /// is written once, so an outline costs no second fill. + pub fn outlined_rect( + &mut self, + (x, y, w, h): (f32, f32, f32, f32), + r: f32, + fill: Color, + outline: Option<(f32, Color)>, + ) { if w <= 0.0 || h <= 0.0 { return; } - let pixel = color.pixel(); + let (b, edge) = outline.unwrap_or((0.0, fill)); + let fill_px = fill.pixel(); + let edge_px = edge.pixel(); let hw = w / 2.0; let hh = h / 2.0; let r = r.clamp(0.0, hw.min(hh)); @@ -116,13 +131,13 @@ impl<'a> Canvas<'a> { for py in y0..y1 { let qy = ((py as f32 + 0.5) - cy).abs(); let row = &mut self.px[py * self.width..(py + 1) * self.width]; - // Rows clear of the corners and the top and bottom edges are - // solid except for their two end pixels. - let solid_row = qy + 0.5 <= hh - r && qy + 0.5 <= hh; + // Rows clear of the corners and of the top and bottom edge (and + // outline) are solid fill except near their two ends. + let solid_row = qy + 0.5 <= hh - r.max(b); for (px, dst) in row.iter_mut().enumerate().take(x1).skip(x0) { let qx = ((px as f32 + 0.5) - cx).abs(); - if solid_row && qx + 0.5 <= hw { - *dst = pixel; + if solid_row && qx + 0.5 <= hw - b { + *dst = fill_px; continue; } // Signed distance from the pixel center to the shape. @@ -132,6 +147,19 @@ impl<'a> Canvas<'a> { let inside = dx.max(dy).min(0.0); let distance = outside + inside - r; let coverage = (0.5 - distance).clamp(0.0, 1.0); + if coverage <= 0.0 { + continue; + } + // How far in past the outline: 1 is all fill, 0 all edge. + // Only the pixel on the outline's inner edge needs a mix. + let inner = (0.5 - (distance + b)).clamp(0.0, 1.0); + let pixel = if b <= 0.0 || inner >= 1.0 { + fill_px + } else if inner <= 0.0 { + edge_px + } else { + edge.mix(fill, inner).pixel() + }; blend(dst, pixel, (coverage * 255.0).round() as u32); } } diff --git a/src/textsize.rs b/src/textsize.rs new file mode 100644 index 0000000..a55029e --- /dev/null +++ b/src/textsize.rs @@ -0,0 +1,76 @@ +//! The aliasOS text size. `aliasos-display-text-size` writes it as +//! `base-size` (in px, 9–20, default 12) under `[font]` in +//! `~/.config/aliasos/shell.toml`, and sets GNOME's text-scaling-factor to +//! match. Alias Calc scales its text and its starting window by +//! base-size ÷ 12 (WCAG 1.4.4: text resizes to 200%). + +use std::path::PathBuf; + +/// The aliasOS default, which Alias Calc's sizes are designed at. +const DEFAULT_PX: f32 = 12.0; + +/// The smallest and largest factors followed. aliasOS's own range (9–20 px) +/// is 0.75–1.67; 2.0 leaves room for a hand-edited file. +const MIN_SCALE: f32 = 0.75; +const MAX_SCALE: f32 = 2.0; + +/// The folder holding `shell.toml`, which the theme watch also watches. +pub fn dir() -> Option { + let home = std::env::var_os("HOME").filter(|h| !h.is_empty())?; + Some(PathBuf::from(home).join(".config/aliasos")) +} + +/// The file name a change to watch for in `dir()`. +pub const FILE: &str = "shell.toml"; + +/// The current text scale: 1.0 when there's no setting or it can't be read. +pub fn load() -> f32 { + dir() + .and_then(|d| std::fs::read_to_string(d.join(FILE)).ok()) + .and_then(|text| base_size(&text)) + .map_or(1.0, |px| (px / DEFAULT_PX).clamp(MIN_SCALE, MAX_SCALE)) +} + +/// `base-size` under `[font]`, as aliasos-display-text-size writes it. +fn base_size(text: &str) -> Option { + let mut in_font = false; + for line in text.lines() { + let line = line.split('#').next().unwrap_or("").trim(); + if let Some(table) = line.strip_prefix('[') { + in_font = table.trim_end_matches(']').trim() == "font"; + continue; + } + if !in_font { + continue; + } + if let Some((key, value)) = line.split_once('=') + && key.trim() == "base-size" + { + return value + .trim() + .trim_matches('"') + .parse::() + .ok() + .filter(|v| *v > 0.0); + } + } + None +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn reads_base_size_under_font_only() { + assert_eq!(base_size("[font]\nbase-size = 18\n"), Some(18.0)); + assert_eq!( + base_size("[bar]\nbase-size = 30\n[font]\nbase-size = 14 # px\n"), + Some(14.0) + ); + assert_eq!(base_size("base-size = 18\n"), None, "not under [font]"); + assert_eq!(base_size("[font]\nfamily = \"x\"\n"), None); + assert_eq!(base_size("[font]\nbase-size = big\n"), None); + assert_eq!(base_size("[font]\nbase-size = 0\n"), None); + } +} diff --git a/src/theme.rs b/src/theme.rs index aa69006..f758457 100644 --- a/src/theme.rs +++ b/src/theme.rs @@ -103,17 +103,28 @@ fn color_value(value: &str) -> Option { /// Watches for theme changes. Its fd goes in the event loop's poll set. pub struct Watch { fd: OwnedFd, + /// The watch on the aliasOS config folder, for the text size. + text_wd: Option, +} + +/// What a batch of watch events changed. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct Changed { + pub theme: bool, + /// The aliasOS text size (crate::textsize). + pub text: bool, } impl Watch { /// Starts watching every theme source's `current` directory that exists, - /// so a fallback to Omarchy still sees an aliasOS theme arrive. `None` - /// when there's none, or inotify isn't available. + /// so a fallback to Omarchy still sees an aliasOS theme arrive, and the + /// aliasOS config folder for the text size. `None` when there's nothing + /// to watch, or inotify isn't available. pub fn new() -> Option { - Self::on(&sources()) + Self::on(&sources(), crate::textsize::dir()) } - fn on(sources: &[PathBuf]) -> Option { + fn on(sources: &[PathBuf], text_dir: Option) -> Option { let fd = inotify::init(CreateFlags::CLOEXEC | CreateFlags::NONBLOCK).ok()?; // A theme arrives as an entry named `theme` moved or created in // `current/` (a directory or a symlink, never written in place), so @@ -124,30 +135,48 @@ impl Watch { .iter() .filter(|dir| inotify::add_watch(&fd, dir.as_path(), flags).is_ok()) .count(); - (watched > 0).then_some(Self { fd }) + // shell.toml is rewritten in place or replaced with mv. + let text_wd = text_dir.and_then(|dir| { + inotify::add_watch( + &fd, + dir.as_path(), + WatchFlags::CLOSE_WRITE | WatchFlags::MOVED_TO, + ) + .ok() + }); + (watched > 0 || text_wd.is_some()).then_some(Self { fd, text_wd }) } pub fn fd(&self) -> impl AsFd + '_ { self.fd.as_fd() } - /// Drains the pending events and says whether any touched the theme. - /// Call when the fd is readable. An error means the watch is broken (its - /// fd would stay readable and spin the loop), so stop using it. - pub fn changed(&self) -> Result { + /// Drains the pending events and says what they changed. Call when the + /// fd is readable. An error means the watch is broken (its fd would stay + /// readable and spin the loop), so stop using it. + pub fn changed(&self) -> Result { let mut buf = [std::mem::MaybeUninit::uninit(); 4096]; let mut reader = inotify::Reader::new(&self.fd, &mut buf); - let mut changed = false; + let mut changed = Changed::default(); loop { match reader.next() { Ok(event) => { if event.events().contains(ReadFlags::QUEUE_OVERFLOW) { - changed = true; + changed = Changed { + theme: true, + text: true, + }; } - if let Some(name) = event.file_name() - && is_theme_entry(OsStr::from_bytes(name.to_bytes())) - { - changed = true; + let Some(name) = event.file_name() else { + continue; + }; + let name = OsStr::from_bytes(name.to_bytes()); + if Some(event.wd()) == self.text_wd { + if name == crate::textsize::FILE { + changed.text = true; + } + } else if is_theme_entry(name) { + changed.theme = true; } } Err(Errno::AGAIN) => return Ok(changed), @@ -290,22 +319,56 @@ color4 = "#5482B4" let omarchy = tmp.0.join("omarchy/current"); std::fs::create_dir_all(aliasos.join("next-theme")).unwrap(); std::fs::create_dir_all(&omarchy).unwrap(); - let watch = Watch::on(&[aliasos.clone(), omarchy.clone()]).unwrap(); - assert_eq!(watch.changed(), Ok(false), "nothing yet"); + let watch = Watch::on(&[aliasos.clone(), omarchy.clone()], None).unwrap(); + assert_eq!(watch.changed().map(|c| c.theme), Ok(false), "nothing yet"); std::fs::write(aliasos.join("theme.name"), "x").unwrap(); - assert_eq!(watch.changed(), Ok(false), "other entries don't count"); + assert_eq!( + watch.changed().map(|c| c.theme), + Ok(false), + "other entries don't count" + ); std::fs::rename(aliasos.join("next-theme"), aliasos.join("theme")).unwrap(); - assert_eq!(watch.changed(), Ok(true), "aliasOS's mv counts"); + assert_eq!( + watch.changed().map(|c| c.theme), + Ok(true), + "aliasOS's mv counts" + ); std::os::unix::fs::symlink(&aliasos, omarchy.join("theme")).unwrap(); - assert_eq!(watch.changed(), Ok(true), "Omarchy's symlink counts"); + assert_eq!( + watch.changed().map(|c| c.theme), + Ok(true), + "Omarchy's symlink counts" + ); + } + + #[test] + fn watch_sees_the_text_size_change() { + let tmp = TempDir::new("textwatch"); + let config = tmp.0.join("aliasos"); + std::fs::create_dir_all(&config).unwrap(); + let watch = Watch::on(&[], Some(config.clone())).unwrap(); + std::fs::write(config.join("other.toml"), "x").unwrap(); + assert_eq!( + watch.changed(), + Ok(Changed::default()), + "other files don't count" + ); + std::fs::write(config.join("shell.toml"), "[font]\nbase-size = 18\n").unwrap(); + assert_eq!( + watch.changed(), + Ok(Changed { + theme: false, + text: true + }) + ); } #[test] fn no_watch_without_a_source() { let tmp = TempDir::new("nowatch"); - assert!(Watch::on(&[tmp.0.join("missing")]).is_none()); + assert!(Watch::on(&[tmp.0.join("missing")], None).is_none()); } } diff --git a/src/ui.rs b/src/ui.rs index 35e29fc..40c65ff 100644 --- a/src/ui.rs +++ b/src/ui.rs @@ -97,8 +97,18 @@ pub struct Palette { pub key_pressed: Color, /// The label on the accent-filled `=` key. pub on_accent: Color, + /// The 1 px outline every key has, 3:1 against the background (WCAG + /// 1.4.11: a control's boundary). The = key's accent fill usually is its + /// own boundary; `equals_border` is set only when it isn't. + pub border: Color, + pub equals_border: Option, + /// The keyboard focus ring: 3:1 against the background it's drawn on. + pub focus: Color, } +/// WCAG 2.2 AA for non-text: control boundaries and focus indicators. +const NON_TEXT_CONTRAST: f32 = 3.0; + /// WCAG 2.2 AA for text: 4.5:1. Large text (24 px and up) only needs 3:1, /// but nothing here is large at every size: the result shrinks to fit a long /// number, and key labels drop to ~22 px at the minimum window. So all text @@ -181,6 +191,20 @@ impl Palette { key, key_pressed, on_accent, + border: readable( + background.mix(foreground, 0.35), + &[background], + NON_TEXT_CONTRAST, + ), + equals_border: (contrast(accent, background) < NON_TEXT_CONTRAST).then(|| { + readable( + background.mix(foreground, 0.35), + &[background], + NON_TEXT_CONTRAST, + ) + }), + // The digits' colour already has 4.5:1 on the background. + focus: labels.foreground, } } } @@ -283,6 +307,10 @@ pub struct View<'a> { /// made readable) in place of /// the expression line. pub notice: Option<&'a str>, + /// The key with keyboard focus, when the focus ring should show. + pub focus: Option<(usize, usize)>, + /// The aliasOS text size as a factor of the default (1.0 = 12 px). + pub text_scale: f32, } // Logical sizes. @@ -294,6 +322,10 @@ const DISPLAY_SIZE: f32 = 60.0; const KEY_SIZE: f32 = 24.0; const EXPRESSION_MIN_SIZE: f32 = 13.0; const DISPLAY_MIN_SIZE: f32 = 16.0; +/// Focus ring: its width and its gap from the key, inside the 6 px between +/// keys. +const FOCUS_WIDTH: f32 = 2.0; +const FOCUS_OFFSET: f32 = 2.0; /// The share of the height above the keypad. const DISPLAY_SHARE: f32 = 0.3; @@ -308,8 +340,9 @@ struct Layout { } impl Layout { - fn new(fonts: &Fonts, width: f32, height: f32) -> Self { - let display_height = (height * DISPLAY_SHARE).max(EXPRESSION_SIZE + DISPLAY_SIZE); + fn new(fonts: &Fonts, width: f32, height: f32, text_scale: f32) -> Self { + let display_height = + (height * DISPLAY_SHARE).max((EXPRESSION_SIZE + DISPLAY_SIZE) * text_scale); let grid_top = PADDING + display_height; let rows = KEYS.len() as f32; let cols = KEYS[0].len() as f32; @@ -317,12 +350,12 @@ impl Layout { let key_h = ((height - grid_top - PADDING - (rows - 1.0) * GAP) / rows).max(1.0); let display_baseline = grid_top - GAP - 4.0; let expression_baseline = display_baseline - - fonts.digit_height(Face::Light, DISPLAY_SIZE) - - EXPRESSION_SIZE * 0.6; + - fonts.digit_height(Face::Light, DISPLAY_SIZE * text_scale) + - EXPRESSION_SIZE * text_scale * 0.6; Self { grid: (PADDING, grid_top), key: (key_w, key_h), - expression_baseline: expression_baseline.max(PADDING + EXPRESSION_SIZE), + expression_baseline: expression_baseline.max(PADDING + EXPRESSION_SIZE * text_scale), display_baseline, } } @@ -358,8 +391,10 @@ pub fn draw( (width, height): (f32, f32), scale: f32, ) { - let layout = Layout::new(fonts, width, height); + let layout = Layout::new(fonts, width, height, view.text_scale); let s = |v: f32| v * scale; + // Text sizes follow the aliasOS text size; spacing doesn't. + let t = |v: f32| v * scale * view.text_scale; canvas.fill(palette.background); @@ -369,8 +404,8 @@ pub fn draw( if let Some(notice) = view.notice { let size = fonts.fit( Face::Regular, - s(EXPRESSION_SIZE), - s(EXPRESSION_MIN_SIZE), + t(EXPRESSION_SIZE), + t(EXPRESSION_MIN_SIZE), notice, max_text, ); @@ -387,8 +422,8 @@ pub fn draw( } else if !view.expression.is_empty() { let size = fonts.fit( Face::Regular, - s(EXPRESSION_SIZE), - s(EXPRESSION_MIN_SIZE), + t(EXPRESSION_SIZE), + t(EXPRESSION_MIN_SIZE), view.expression, max_text, ); @@ -410,8 +445,8 @@ pub fn draw( // still right, a clipped one isn't. let mut size = fonts.fit( Face::Light, - s(DISPLAY_SIZE), - s(DISPLAY_MIN_SIZE), + t(DISPLAY_SIZE), + t(DISPLAY_MIN_SIZE), view.display, max_text, ); @@ -457,12 +492,21 @@ pub fn draw( } }; let (px, py, pw, ph) = layout.key_pixels(row, col, scale); - canvas.rounded_rect(px, py, pw, ph, s(RADIUS), fill); + // The outline, then the fill inside it: at least one whole pixel. + let border = match role(label) { + Role::Equals => palette.equals_border, + _ => Some(palette.border), + }; + let outline = border.map(|edge| (s(1.0).round().max(1.0), edge)); + canvas.outlined_rect((px, py, pw, ph), s(RADIUS), fill, outline); + if view.focus == Some((row, col)) { + focus_ring(canvas, (px, py, pw, ph), scale, palette.focus); + } // JetBrains Mono draws × ÷ − + small next to its digits. let size = match role(label) { - Role::Operator | Role::Equals => s(KEY_SIZE) * 1.3, - _ => s(KEY_SIZE), + Role::Operator | Role::Equals => t(KEY_SIZE) * 1.3, + _ => t(KEY_SIZE), } .min(ph * 0.5); let tw = fonts.width(Face::Regular, size, label); @@ -481,6 +525,59 @@ pub fn draw( } } +/// A ring around a key, in the gap between keys: an outline, so focus never +/// depends on colour alone. +fn focus_ring( + canvas: &mut Canvas, + (px, py, pw, ph): (f32, f32, f32, f32), + scale: f32, + color: Color, +) { + let gap = (FOCUS_OFFSET * scale).round(); + let width = (FOCUS_WIDTH * scale).round().max(1.0); + let out = gap + width; + // Four edges, square-cornered like aliasOS windows, so the key inside + // is never painted over. + let (x0, y0, x1, y1) = (px - out, py - out, px + pw + out, py + ph + out); + canvas.rounded_rect(x0, y0, x1 - x0, width, width / 2.0, color); + canvas.rounded_rect(x0, y1 - width, x1 - x0, width, width / 2.0, color); + canvas.rounded_rect(x0, y0, width, y1 - y0, width / 2.0, color); + canvas.rounded_rect(x1 - width, y0, width, y1 - y0, width / 2.0, color); +} + +/// Where keyboard focus goes from `from`. With no focus yet, every move +/// lands on the first key. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Move { + Next, + Previous, + Up, + Down, + Left, + Right, +} + +pub fn move_focus(from: Option<(usize, usize)>, how: Move) -> (usize, usize) { + let (rows, cols) = (KEYS.len(), KEYS[0].len()); + let Some((r, c)) = from else { return (0, 0) }; + match how { + // Tab order is reading order, wrapping at the end. + Move::Next => { + let i = (r * cols + c + 1) % (rows * cols); + (i / cols, i % cols) + } + Move::Previous => { + let i = (r * cols + c + rows * cols - 1) % (rows * cols); + (i / cols, i % cols) + } + // Arrows stop at the edges. + Move::Up => (r.saturating_sub(1), c), + Move::Down => ((r + 1).min(rows - 1), c), + Move::Left => (r, c.saturating_sub(1)), + Move::Right => (r, (c + 1).min(cols - 1)), + } +} + /// The key at logical position (x, y), as (row, column), in a window of /// `width` by `height` logical pixels drawn at `scale`. It tests the same /// pixel-snapped rectangles that are drawn, so a click on a key's edge pixel @@ -489,9 +586,10 @@ pub fn hit_test( fonts: &Fonts, (width, height): (f32, f32), scale: f32, + text_scale: f32, (x, y): (f32, f32), ) -> Option<(usize, usize)> { - let layout = Layout::new(fonts, width, height); + let layout = Layout::new(fonts, width, height, text_scale); let (x, y) = (x * scale, y * scale); for (row, labels) in KEYS.iter().enumerate() { for col in 0..labels.len() { @@ -513,31 +611,31 @@ mod tests { fn hit_test_finds_the_corner_keys_and_misses_the_gaps() { let fonts = Fonts::load(); let (w, h) = (320.0, 480.0); - let layout = Layout::new(&fonts, w, h); + let layout = Layout::new(&fonts, w, h, 1.0); let (x, y, kw, kh) = layout.key_rect(0, 0); assert_eq!( - hit_test(&fonts, (w, h), 1.0, (x + 1.0, y + 1.0)), + hit_test(&fonts, (w, h), 1.0, 1.0, (x + 1.0, y + 1.0)), Some((0, 0)) ); let (x, y, ..) = layout.key_rect(4, 3); assert_eq!( - hit_test(&fonts, (w, h), 1.0, (x + 1.0, y + 1.0)), + hit_test(&fonts, (w, h), 1.0, 1.0, (x + 1.0, y + 1.0)), Some((4, 3)) ); // Between the first two keys of the first row. assert_eq!( - hit_test(&fonts, (w, h), 1.0, (PADDING + kw + GAP / 2.0, y - kh)), + hit_test(&fonts, (w, h), 1.0, 1.0, (PADDING + kw + GAP / 2.0, y - kh)), None ); // The display area. - assert_eq!(hit_test(&fonts, (w, h), 1.0, (w / 2.0, PADDING)), None); + assert_eq!(hit_test(&fonts, (w, h), 1.0, 1.0, (w / 2.0, PADDING)), None); } #[test] fn every_drawn_pixel_of_a_key_hits_that_key() { let fonts = Fonts::load(); let (w, h) = (320.0, 480.0); - let layout = Layout::new(&fonts, w, h); + let layout = Layout::new(&fonts, w, h, 1.0); for scale in [1.0, 1.25, 1.5, 1.75] { for (row, col) in [(0, 0), (2, 1), (4, 3)] { let (px, py, pw, ph) = layout.key_pixels(row, col, scale); @@ -550,7 +648,7 @@ mod tests { ] { let at = ((x + 0.5) / scale, (y + 0.5) / scale); assert_eq!( - hit_test(&fonts, (w, h), scale, at), + hit_test(&fonts, (w, h), scale, 1.0, at), Some((row, col)), "scale {scale}, pixel {x},{y}" ); @@ -619,6 +717,8 @@ mod tests { display, pressed: None, notice: None, + focus: None, + text_scale: 1.0, }; draw( &mut Canvas::new(&mut bytes, w, h), @@ -652,6 +752,8 @@ mod tests { display: "12", pressed: None, notice, + focus: None, + text_scale: 1.0, }; draw( &mut Canvas::new(&mut bytes, w, h), @@ -685,7 +787,7 @@ mod tests { fn keypad_fits_inside_the_window() { let fonts = Fonts::load(); for (w, h) in [(260.0, 380.0), (320.0, 480.0), (900.0, 1200.0)] { - let layout = Layout::new(&fonts, w, h); + let layout = Layout::new(&fonts, w, h, 1.0); let (x, y, kw, kh) = layout.key_rect(4, 3); assert!( x + kw <= w - PADDING + 0.01 && y + kh <= h - PADDING + 0.01, @@ -714,6 +816,111 @@ mod tests { } check("= label", p.on_accent, p.accent); check("= label held", p.on_accent, p.accent_pressed); + // Non-text (WCAG 1.4.11): key outlines and the focus ring, 3:1 on + // the background they meet. + let edge = |what: &str, c: Color| { + let r = contrast(c, p.background); + assert!( + r >= NON_TEXT_CONTRAST, + "{theme}: {what} is {r:.2}:1, needs 3:1" + ); + }; + edge("key outline", p.border); + edge("focus ring", p.focus); + edge("= key boundary", p.equals_border.unwrap_or(p.accent)); + } + + /// The smallest a key may be in either direction: the house rule is 44 px + /// (WCAG 2.5.8 asks 24). MIN_SIZE in src/window.rs keeps it. + const MIN_KEY: f32 = 44.0; + + #[test] + fn keys_are_at_least_44_px_at_the_minimum_window() { + let fonts = Fonts::load(); + // MIN_SIZE (260 × 400), grown by the text scale as window.rs does. + for text_scale in [0.75, 1.0, 1.5, 1.67, 2.0] { + let k = f32::max(text_scale, 1.0); + let (w, h) = ((260.0 * k).round(), (400.0 * k).round()); + let layout = Layout::new(&fonts, w, h, text_scale); + let (_, _, kw, kh) = layout.key_rect(0, 0); + assert!( + kw >= MIN_KEY && kh >= MIN_KEY, + "text {text_scale}: keys {kw}×{kh}" + ); + } + } + + #[test] + fn focus_moves_by_tab_and_arrows() { + assert_eq!(move_focus(None, Move::Next), (0, 0)); + assert_eq!( + move_focus(Some((0, 3)), Move::Next), + (1, 0), + "Tab wraps to the next row" + ); + assert_eq!( + move_focus(Some((4, 3)), Move::Next), + (0, 0), + "and back to the top" + ); + assert_eq!(move_focus(Some((0, 0)), Move::Previous), (4, 3)); + assert_eq!(move_focus(Some((2, 1)), Move::Up), (1, 1)); + assert_eq!( + move_focus(Some((0, 1)), Move::Up), + (0, 1), + "arrows stop at the edge" + ); + assert_eq!(move_focus(Some((4, 3)), Move::Right), (4, 3)); + assert_eq!(move_focus(Some((4, 3)), Move::Left), (4, 2)); + assert_eq!(move_focus(Some((3, 0)), Move::Down), (4, 0)); + } + + #[test] + fn keys_have_an_outline_and_focus_draws_a_ring() { + let mut fonts = Fonts::load(); + let palette = Palette::default(); + let (w, h) = (320usize, 480usize); + let draw_with = |fonts: &mut Fonts, focus| { + let mut bytes = vec![0; w * h * 4]; + let view = View { + expression: "", + display: "0", + pressed: None, + notice: None, + focus, + text_scale: 1.0, + }; + draw( + &mut Canvas::new(&mut bytes, w, h), + fonts, + &palette, + &view, + (320.0, 480.0), + 1.0, + ); + bytes + }; + let at = |bytes: &[u8], x: usize, y: usize| { + let p = &bytes[(y * w + x) * 4..(y * w + x) * 4 + 3]; + Color::rgb(p[2], p[1], p[0]) + }; + let layout = Layout::new(&fonts, 320.0, 480.0, 1.0); + let (kx, ky, kw, kh) = layout.key_pixels(2, 1, 1.0); + let plain = draw_with(&mut fonts, None); + // The key's left edge, half way down, is outline; one in, fill. + let mid = (ky + kh / 2.0) as usize; + assert_eq!(at(&plain, kx as usize, mid), palette.border); + assert_eq!(at(&plain, kx as usize + 2, mid), palette.key); + // Focus: the ring sits in the gap, 2 px out from the key, 2 px wide. + let focused = draw_with(&mut fonts, Some((2, 1))); + let ring_x = kx as usize - 3; + assert_eq!( + at(&plain, ring_x, mid), + palette.background, + "no ring without focus" + ); + assert_eq!(at(&focused, ring_x, mid), palette.focus); + let _ = kw; } #[test] @@ -797,6 +1004,8 @@ mod tests { display: "7,006,652", pressed: Some((2, 1)), notice: None, + focus: None, + text_scale: 1.0, }; // Warm the glyph cache, as every frame after the first finds it. draw( diff --git a/src/window.rs b/src/window.rs index 45fd73f..26662ea 100644 --- a/src/window.rs +++ b/src/window.rs @@ -58,6 +58,7 @@ use crate::clipboard::{self, Paste, Progress}; use crate::engine::{Calc, Key}; use crate::input; use crate::render::{Canvas, Fonts}; +use crate::textsize; use crate::theme; use crate::trace; use crate::ui::{self, Palette, View}; @@ -69,7 +70,8 @@ const APP_ID: &str = "com.aliasproject.calc"; /// Logical size when the compositor leaves it to us (a floating window). const DEFAULT_SIZE: (u32, u32) = (320, 480); -const MIN_SIZE: (u32, u32) = (260, 380); +/// 400 tall keeps every key at least 44 px (ui::MIN_KEY) at the smallest size. +const MIN_SIZE: (u32, u32) = (260, 400); /// Key repeat when the compositor doesn't say (it always does on Hyprland). const DEFAULT_REPEAT: (Duration, Duration) = @@ -81,6 +83,12 @@ const NOTICE_TIME: Duration = Duration::from_millis(1200); /// The left mouse button (linux/input-event-codes.h BTN_LEFT). const BTN_LEFT: u32 = 0x110; +/// `size` grown by the text scale (never shrunk below it). +fn scaled((w, h): (u32, u32), text_scale: f32) -> (u32, u32) { + let k = text_scale.max(1.0); + ((w as f32 * k).round() as u32, (h as f32 * k).round() as u32) +} + /// Fractional scales arrive as 120ths (`wp_fractional_scale_v1`). const SCALE_DENOMINATOR: u32 = 120; @@ -115,10 +123,12 @@ pub fn run() -> Result<(), Box> { _ => Scaling::Integer(1), }; + // Larger aliasOS text means a larger window, so the layout holds. + let text_scale = textsize::load(); let window = xdg_shell.create_window(surface, WindowDecorations::RequestServer, &qh); window.set_title(TITLE); window.set_app_id(APP_ID); - window.set_min_size(Some(MIN_SIZE)); + window.set_min_size(Some(scaled(MIN_SIZE, text_scale))); // The first commit has no buffer: it asks the compositor for a // configure, and the first draw answers it. window.commit(); @@ -132,7 +142,7 @@ pub fn run() -> Result<(), Box> { let palette = theme::load().unwrap_or_default(); trace::mark("theme read"); - let (w, h) = DEFAULT_SIZE; + let (w, h) = scaled(DEFAULT_SIZE, text_scale); let pool = SlotPool::new((w * h * 4) as usize, &shm)?; let mut app = App { registry: RegistryState::new(&globals), @@ -160,7 +170,10 @@ pub fn run() -> Result<(), Box> { buffer: None, fonts, palette, - size: DEFAULT_SIZE, + size: (w, h), + text_scale, + focus: None, + focus_visible: false, scaling, configured: false, drawn: false, @@ -289,8 +302,14 @@ fn event_loop( } if theme_ready && let Some(watch) = &theme { match watch.changed() { - Ok(true) => app.reload_theme(), - Ok(false) => {} + Ok(changed) => { + if changed.theme { + app.reload_theme(); + } + if changed.text { + app.reload_text_size(); + } + } // A broken watch would keep the fd readable and spin the // loop: stop following the theme instead. Err(err) => { @@ -347,6 +366,12 @@ struct App { cursor: Option, modifiers: Modifiers, calc: Calc, + /// The aliasOS text size as a factor (crate::textsize). + text_scale: f32, + /// The key with keyboard focus, and whether its ring shows (from the + /// first Tab or arrow until the next click). + focus: Option<(usize, usize)>, + focus_visible: bool, /// When "Copied" stops showing, while it shows. notice_until: Option, /// Copy and paste; None when the compositor has no data device manager. @@ -519,6 +544,19 @@ impl App { } } + /// Follows a change to the aliasOS text size: new text sizes now, and a + /// new minimum window. The window keeps its size; the compositor or the + /// person resizes it. + fn reload_text_size(&mut self) { + let text_scale = textsize::load(); + if text_scale != self.text_scale { + self.text_scale = text_scale; + self.window.set_min_size(Some(scaled(MIN_SIZE, text_scale))); + self.dirty = true; + trace::mark("text size changed"); + } + } + /// Reads the theme again. A theme that can't be read keeps the colors /// already showing rather than flashing the built-in ones. fn reload_theme(&mut self) { @@ -554,6 +592,7 @@ impl App { &self.fonts, (w as f32, h as f32), scale, + self.text_scale, (x as f32, y as f32), ) } @@ -619,6 +658,8 @@ impl App { display: &display, pressed, notice: self.notice_until.map(|_| "Copied"), + focus: self.focus.filter(|_| self.focus_visible), + text_scale: self.text_scale, }; let mut canvas = Canvas::new(canvas, pw as usize, ph as usize); let logical = (self.size.0 as f32, self.size.1 as f32); @@ -857,8 +898,39 @@ impl KeyboardHandler for App { if m.ctrl || m.alt || m.logo { return; } - let Some(key) = input::key_for(event.keysym) else { + // Keyboard focus: Tab, Shift+Tab and the arrows move it (and show + // it); Space presses the focused key. + let movement = match event.keysym { + Keysym::Tab => Some(ui::Move::Next), + Keysym::ISO_Left_Tab => Some(ui::Move::Previous), + Keysym::Up => Some(ui::Move::Up), + Keysym::Down => Some(ui::Move::Down), + Keysym::Left => Some(ui::Move::Left), + Keysym::Right => Some(ui::Move::Right), + _ => None, + }; + if let Some(how) = movement { + // The first press only shows where focus is (the last key + // clicked, else the first key); later presses move it. + self.focus = Some(match (self.focus_visible, self.focus) { + (true, from) => ui::move_focus(from, how), + (false, Some(cell)) => cell, + (false, None) => ui::move_focus(None, how), + }); + self.focus_visible = true; + self.dirty = true; return; + } + let key = if event.keysym == Keysym::space { + match self.focus.filter(|_| self.focus_visible) { + Some(cell) => ui::action(cell), + None => return, + } + } else { + let Some(key) = input::key_for(event.keysym) else { + return; + }; + key }; self.key_down = Some((event.raw_code, ui::cell_of(key))); self.repeat = match self.repeat_rate { @@ -971,6 +1043,15 @@ impl PointerHandler for App { // Any click ends "Copied", on a key or not. self.end_notice(); self.mouse_down = self.button_under_pointer(); + // A click moves focus to the key, but the ring is for + // keyboard users: it hides until the next Tab or arrow. + if let Some(cell) = self.mouse_down { + self.focus = Some(cell); + } + if self.focus_visible { + self.focus_visible = false; + self.dirty = true; + } } PointerEventKind::Release { button: BTN_LEFT, .. From f559e88dae1ebb2184ac9214fefbfa1499cccc54 Mon Sep 17 00:00:00 2001 From: Michael Aguiar Date: Wed, 25 Nov 2026 15:46:51 -0700 Subject: [PATCH 34/50] Keep keys at 44 px when text grows; = outline on both fills; tidy-ups From review: raising the text size with the window small let the display take keypad height until keys fell under 44 px (39.2 at 260 x 400 and 2.0); the display is now capped so keys keep 44 px, and its text fits what's left. Wayland apps can't resize their own window, so the window grows only through the raised minimum size. Also: the = key's outline is decided from its held fill as well as its normal one; Tab with Shift held moves back on layouts that don't send ISO_Left_Tab; the focus ring's corners are square as its comment says; minimum text sizes no longer shrink below the defaults with smaller text; the layout test uses the real minimum window. ALI-2113 --- src/ui.rs | 74 ++++++++++++++++++++++++++++++++++++--------------- src/window.rs | 3 +++ 2 files changed, 56 insertions(+), 21 deletions(-) diff --git a/src/ui.rs b/src/ui.rs index 40c65ff..b383747 100644 --- a/src/ui.rs +++ b/src/ui.rs @@ -196,13 +196,17 @@ impl Palette { &[background], NON_TEXT_CONTRAST, ), - equals_border: (contrast(accent, background) < NON_TEXT_CONTRAST).then(|| { - readable( - background.mix(foreground, 0.35), - &[background], - NON_TEXT_CONTRAST, - ) - }), + // Either of the = key's fills under 3:1 gets the outline. + equals_border: [accent, accent_pressed] + .iter() + .any(|&f| contrast(f, background) < NON_TEXT_CONTRAST) + .then(|| { + readable( + background.mix(foreground, 0.35), + &[background], + NON_TEXT_CONTRAST, + ) + }), // The digits' colour already has 4.5:1 on the background. focus: labels.foreground, } @@ -322,6 +326,11 @@ const DISPLAY_SIZE: f32 = 60.0; const KEY_SIZE: f32 = 24.0; const EXPRESSION_MIN_SIZE: f32 = 13.0; const DISPLAY_MIN_SIZE: f32 = 16.0; +/// The smallest a key may be in either direction: the house rule is 44 px +/// (WCAG 2.5.8 asks 24). MIN_SIZE in src/window.rs is chosen to keep it, and +/// larger text never takes keypad height below it. +const MIN_KEY: f32 = 44.0; + /// Focus ring: its width and its gap from the key, inside the 6 px between /// keys. const FOCUS_WIDTH: f32 = 2.0; @@ -341,8 +350,12 @@ struct Layout { impl Layout { fn new(fonts: &Fonts, width: f32, height: f32, text_scale: f32) -> Self { - let display_height = - (height * DISPLAY_SHARE).max((EXPRESSION_SIZE + DISPLAY_SIZE) * text_scale); + // Larger text wants a taller display, but never at the keys' cost: + // they keep MIN_KEY each, and the display text fits what's left. + let keypad_min = 5.0 * MIN_KEY + 4.0 * GAP; + let display_height = (height * DISPLAY_SHARE) + .max((EXPRESSION_SIZE + DISPLAY_SIZE) * text_scale) + .min((height - 2.0 * PADDING - keypad_min).max(height * DISPLAY_SHARE)); let grid_top = PADDING + display_height; let rows = KEYS.len() as f32; let cols = KEYS[0].len() as f32; @@ -395,6 +408,8 @@ pub fn draw( let s = |v: f32| v * scale; // Text sizes follow the aliasOS text size; spacing doesn't. let t = |v: f32| v * scale * view.text_scale; + // Minimums don't shrink below the defaults with smaller text. + let floor = |v: f32| v * scale * view.text_scale.max(1.0); canvas.fill(palette.background); @@ -405,7 +420,7 @@ pub fn draw( let size = fonts.fit( Face::Regular, t(EXPRESSION_SIZE), - t(EXPRESSION_MIN_SIZE), + floor(EXPRESSION_MIN_SIZE), notice, max_text, ); @@ -423,7 +438,7 @@ pub fn draw( let size = fonts.fit( Face::Regular, t(EXPRESSION_SIZE), - t(EXPRESSION_MIN_SIZE), + floor(EXPRESSION_MIN_SIZE), view.expression, max_text, ); @@ -446,7 +461,7 @@ pub fn draw( let mut size = fonts.fit( Face::Light, t(DISPLAY_SIZE), - t(DISPLAY_MIN_SIZE), + floor(DISPLAY_MIN_SIZE), view.display, max_text, ); @@ -539,10 +554,10 @@ fn focus_ring( // Four edges, square-cornered like aliasOS windows, so the key inside // is never painted over. let (x0, y0, x1, y1) = (px - out, py - out, px + pw + out, py + ph + out); - canvas.rounded_rect(x0, y0, x1 - x0, width, width / 2.0, color); - canvas.rounded_rect(x0, y1 - width, x1 - x0, width, width / 2.0, color); - canvas.rounded_rect(x0, y0, width, y1 - y0, width / 2.0, color); - canvas.rounded_rect(x1 - width, y0, width, y1 - y0, width / 2.0, color); + canvas.rounded_rect(x0, y0, x1 - x0, width, 0.0, color); + canvas.rounded_rect(x0, y1 - width, x1 - x0, width, 0.0, color); + canvas.rounded_rect(x0, y0, width, y1 - y0, 0.0, color); + canvas.rounded_rect(x1 - width, y0, width, y1 - y0, 0.0, color); } /// Where keyboard focus goes from `from`. With no focus yet, every move @@ -786,7 +801,7 @@ mod tests { #[test] fn keypad_fits_inside_the_window() { let fonts = Fonts::load(); - for (w, h) in [(260.0, 380.0), (320.0, 480.0), (900.0, 1200.0)] { + for (w, h) in [(260.0, 400.0), (320.0, 480.0), (900.0, 1200.0)] { let layout = Layout::new(&fonts, w, h, 1.0); let (x, y, kw, kh) = layout.key_rect(4, 3); assert!( @@ -828,12 +843,12 @@ mod tests { edge("key outline", p.border); edge("focus ring", p.focus); edge("= key boundary", p.equals_border.unwrap_or(p.accent)); + edge( + "= key boundary held", + p.equals_border.unwrap_or(p.accent_pressed), + ); } - /// The smallest a key may be in either direction: the house rule is 44 px - /// (WCAG 2.5.8 asks 24). MIN_SIZE in src/window.rs keeps it. - const MIN_KEY: f32 = 44.0; - #[test] fn keys_are_at_least_44_px_at_the_minimum_window() { let fonts = Fonts::load(); @@ -850,6 +865,23 @@ mod tests { } } + #[test] + fn larger_text_never_shrinks_keys_below_44_px() { + let fonts = Fonts::load(); + // The window stays small while the setting goes up (Wayland apps + // can't resize themselves). + for (w, h) in [(260.0, 400.0), (320.0, 480.0)] { + for text_scale in [1.0, 1.5, 2.0] { + let layout = Layout::new(&fonts, w, h, text_scale); + let (_, _, kw, kh) = layout.key_rect(4, 3); + assert!( + kw >= MIN_KEY && kh >= MIN_KEY, + "{w}x{h} at {text_scale}: {kw}×{kh}" + ); + } + } + } + #[test] fn focus_moves_by_tab_and_arrows() { assert_eq!(move_focus(None, Move::Next), (0, 0)); diff --git a/src/window.rs b/src/window.rs index 26662ea..fd928bb 100644 --- a/src/window.rs +++ b/src/window.rs @@ -901,6 +901,9 @@ impl KeyboardHandler for App { // Keyboard focus: Tab, Shift+Tab and the arrows move it (and show // it); Space presses the focused key. let movement = match event.keysym { + // Shift+Tab is ISO_Left_Tab on standard layouts, Tab with Shift + // held on others. + Keysym::Tab if m.shift => Some(ui::Move::Previous), Keysym::Tab => Some(ui::Move::Next), Keysym::ISO_Left_Tab => Some(ui::Move::Previous), Keysym::Up => Some(ui::Move::Up), From 0fdfae2228d5d2dcce3da8d0c34819d440b2e279 Mon Sep 17 00:00:00 2001 From: Michael Aguiar Date: Wed, 25 Nov 2026 15:50:13 -0700 Subject: [PATCH 35/50] Share the key outline colour between keys and the = key From review: equals_border repeated the outline expression and could drift from it; the ring test kept an unused binding. ALI-2113 --- src/ui.rs | 24 ++++++++++-------------- 1 file changed, 10 insertions(+), 14 deletions(-) diff --git a/src/ui.rs b/src/ui.rs index b383747..4c982b9 100644 --- a/src/ui.rs +++ b/src/ui.rs @@ -179,6 +179,13 @@ impl Palette { labels.pass(background, key, key_pressed), "key labels under 4.5:1" ); + // Key outlines: the background moved towards the text, lifted to + // 3:1 (WCAG 1.4.11). + let border = readable( + background.mix(foreground, 0.35), + &[background], + NON_TEXT_CONTRAST, + ); Self { background, foreground: labels.foreground, @@ -191,22 +198,12 @@ impl Palette { key, key_pressed, on_accent, - border: readable( - background.mix(foreground, 0.35), - &[background], - NON_TEXT_CONTRAST, - ), + border, // Either of the = key's fills under 3:1 gets the outline. equals_border: [accent, accent_pressed] .iter() .any(|&f| contrast(f, background) < NON_TEXT_CONTRAST) - .then(|| { - readable( - background.mix(foreground, 0.35), - &[background], - NON_TEXT_CONTRAST, - ) - }), + .then_some(border), // The digits' colour already has 4.5:1 on the background. focus: labels.foreground, } @@ -937,7 +934,7 @@ mod tests { Color::rgb(p[2], p[1], p[0]) }; let layout = Layout::new(&fonts, 320.0, 480.0, 1.0); - let (kx, ky, kw, kh) = layout.key_pixels(2, 1, 1.0); + let (kx, ky, _, kh) = layout.key_pixels(2, 1, 1.0); let plain = draw_with(&mut fonts, None); // The key's left edge, half way down, is outline; one in, fill. let mid = (ky + kh / 2.0) as usize; @@ -952,7 +949,6 @@ mod tests { "no ring without focus" ); assert_eq!(at(&focused, ring_x, mid), palette.focus); - let _ = kw; } #[test] From cb5b9c74e039248ed38c417af8ce297a98252e67 Mon Sep 17 00:00:00 2001 From: Michael Aguiar Date: Wed, 25 Nov 2026 16:20:51 -0700 Subject: [PATCH 36/50] Screen reader support through AccessKit, loaded only when Orca runs Alias Calc draws its own pixels, so Orca saw nothing. AccessKit's Linux adapter speaks AT-SPI to it: the window is named Calculator, each key is a button with a spoken name (Divide, Change sign, Backspace) and a press action, the expression and result are text, and the result is a polite live region, read out when it changes. Keyboard focus is accessibility focus, and a screen reader's focus request shows the ring. AccessKit costs three threads and about 2 MiB, and built in it grew the binary from 1.0 to 3.4 MB and memory from 2.4 to 2.9 MiB even with no screen reader (more code pages mapped). So it lives in its own library (a11y/, libalias_calc_a11y.so) behind a small versioned C interface, and alias-calc dlopens it only when a process named orca is running, checked once after the first frame. Without Orca: 1.06 MB, 2.4 MiB, one thread, startup unchanged. The library's thread queues requests and writes to an eventfd the event loop polls, so state stays on the main thread. Missing or mismatched, the library is skipped with a line on stderr. ALI-2114 --- .github/workflows/ci.yml | 6 +- Cargo.lock | 753 +++++++++++++++++++++++++++++++++++++++ Cargo.toml | 4 + README.md | 8 +- a11y/Cargo.toml | 17 + a11y/src/lib.rs | 415 +++++++++++++++++++++ src/a11y.rs | 387 ++++++++++++++++++++ src/main.rs | 1 + src/ui.rs | 11 + src/window.rs | 92 ++++- 10 files changed, 1688 insertions(+), 6 deletions(-) create mode 100644 a11y/Cargo.toml create mode 100644 a11y/src/lib.rs create mode 100644 src/a11y.rs diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 731d9d8..dc4251a 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -54,9 +54,9 @@ jobs: components: rustfmt, clippy - uses: Swatinem/rust-cache@v2 - run: cargo fmt --all --check - - run: cargo clippy --all-targets --locked -- -D warnings - - run: cargo test --locked - - run: cargo build --release --locked + - run: cargo clippy --workspace --all-targets --locked -- -D warnings + - run: cargo test --workspace --locked + - run: cargo build --workspace --release --locked # The renderer's frame budget: only meaningful optimised, so it's # ignored in the debug test run. - name: Performance budgets diff --git a/Cargo.lock b/Cargo.lock index 1ffcf47..db80c34 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2,6 +2,57 @@ # It is not intended for manual editing. version = 4 +[[package]] +name = "accesskit" +version = "0.25.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e883d1d28c5fd5568c79ed2d2bd48d9f2fd3945c8974ed0f53690ceddb051be" +dependencies = [ + "uuid", +] + +[[package]] +name = "accesskit_atspi_common" +version = "0.21.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24f5baf62e34a4a6c30e3d697e4782f821a7337049c44c3b40576a27dfbb580d" +dependencies = [ + "accesskit", + "accesskit_consumer", + "atspi-common", + "phf", + "serde", + "zvariant", +] + +[[package]] +name = "accesskit_consumer" +version = "0.39.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f3da8f27636015191b2264ee1df681503170a632cafd832fdc1edfdd4e3a2fd3" +dependencies = [ + "accesskit", + "hashbrown", +] + +[[package]] +name = "accesskit_unix" +version = "0.24.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "30d5192871228c54f1b0fb4a85cef000e11a3804f25d2165f14afa0daa67f3f6" +dependencies = [ + "accesskit", + "accesskit_atspi_common", + "async-channel", + "async-executor", + "async-task", + "atspi", + "futures-lite", + "futures-util", + "serde", + "zbus", +] + [[package]] name = "alias-calc" version = "0.1.0" @@ -13,12 +64,194 @@ dependencies = [ "wayland-protocols", ] +[[package]] +name = "alias-calc-a11y" +version = "0.1.0" +dependencies = [ + "accesskit", + "accesskit_unix", +] + [[package]] name = "arrayvec" version = "0.7.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d3fb67a6e08acf24fdeccbac2cb6ac4305825bd1f117462e0e6f2f193345ad56" +[[package]] +name = "async-broadcast" +version = "0.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "435a87a52755b8f27fcf321ac4f04b2802e337c8c4872923137471ec39c37532" +dependencies = [ + "event-listener", + "event-listener-strategy", + "futures-core", + "pin-project-lite", +] + +[[package]] +name = "async-channel" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "924ed96dd52d1b75e9c1a3e6275715fd320f5f9439fb5a4a11fa51f4221158d2" +dependencies = [ + "concurrent-queue", + "event-listener-strategy", + "futures-core", + "pin-project-lite", +] + +[[package]] +name = "async-executor" +version = "1.14.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f426a31126c735126297bc5ea7a521263c9faff4f63ca415267ee625651c4f37" +dependencies = [ + "async-task", + "concurrent-queue", + "fastrand", + "futures-lite", + "pin-project-lite", + "slab", +] + +[[package]] +name = "async-io" +version = "2.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "456b8a8feb6f42d237746d4b3e9a178494627745c3c56c6ea55d92ba50d026fc" +dependencies = [ + "autocfg", + "cfg-if", + "concurrent-queue", + "futures-io", + "futures-lite", + "parking", + "polling", + "rustix", + "slab", + "windows-sys", +] + +[[package]] +name = "async-lock" +version = "3.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0876700b0d007ad25d5508865a4259c3af9af6d296bf663a0d586d0bc3369f6f" +dependencies = [ + "event-listener", + "event-listener-strategy", + "pin-project-lite", +] + +[[package]] +name = "async-process" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc50921ec0055cdd8a16de48773bfeec5c972598674347252c0399676be7da75" +dependencies = [ + "async-channel", + "async-io", + "async-lock", + "async-signal", + "async-task", + "blocking", + "cfg-if", + "event-listener", + "futures-lite", + "rustix", +] + +[[package]] +name = "async-recursion" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4f8abc12baad266b1c8cec146854c195b5864b4221d4b2ca7296a7ae82d9e451" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "async-signal" +version = "0.2.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52b5aaafa020cf5053a01f2a60e8ff5dccf550f0f77ec54a4e47285ac2bab485" +dependencies = [ + "async-io", + "async-lock", + "atomic-waker", + "cfg-if", + "futures-core", + "futures-io", + "rustix", + "signal-hook-registry", + "slab", + "windows-sys", +] + +[[package]] +name = "async-task" +version = "4.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b75356056920673b02621b35afd0f7dda9306d03c79a30f5c56c44cf256e3de" + +[[package]] +name = "async-trait" +version = "0.1.92" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "82f6aeea286b8eb4dd3431a1be1b59d290ace00f5bfd8e2a159bc2a05e2c1667" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "atomic-waker" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" + +[[package]] +name = "atspi" +version = "0.29.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c77886257be21c9cd89a4ae7e64860c6f0eefca799bb79127913052bd0eefb3d" +dependencies = [ + "atspi-common", + "atspi-proxies", +] + +[[package]] +name = "atspi-common" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20c5617155740c98003016429ad13fe43ce7a77b007479350a9f8bf95a29f63d" +dependencies = [ + "enumflags2", + "serde", + "static_assertions", + "zbus", + "zbus-lockstep", + "zbus-lockstep-macros", + "zbus_names", + "zvariant", +] + +[[package]] +name = "atspi-proxies" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2230e48787ed3eb4088996eab66a32ca20c0b67bbd4fd6cdfe79f04f1f04c9fc" +dependencies = [ + "atspi-common", + "serde", + "zbus", +] + [[package]] name = "autocfg" version = "1.5.1" @@ -31,6 +264,19 @@ version = "2.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" +[[package]] +name = "blocking" +version = "1.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a70e4329df6cb94385eed412ec92375c3cdd8a6e502493d1229b6414e4036dfa" +dependencies = [ + "async-channel", + "async-task", + "futures-io", + "futures-lite", + "piper", +] + [[package]] name = "borsh" version = "1.8.1" @@ -109,6 +355,15 @@ version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527" +[[package]] +name = "concurrent-queue" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ca0197aee26d1ae37445ee532fefce43251d24cc7c166799f4d46817f1d3973" +dependencies = [ + "crossbeam-utils", +] + [[package]] name = "core_maths" version = "0.1.1" @@ -118,6 +373,12 @@ dependencies = [ "libm", ] +[[package]] +name = "crossbeam-utils" +version = "0.8.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6" + [[package]] name = "cursor-icon" version = "1.2.0" @@ -130,6 +391,33 @@ version = "1.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "75b325c5dbd37f80359721ad39aca5a29fb04c89279657cffdda8736d0c0b9d2" +[[package]] +name = "endi" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "66b7e2430c6dff6a955451e2cfc438f09cea1965a9d6f87f7e3b90decc014099" + +[[package]] +name = "enumflags2" +version = "0.7.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1027f7680c853e056ebcec683615fb6fbbc07dbaa13b4d5d9442b146ded4ecef" +dependencies = [ + "enumflags2_derive", + "serde", +] + +[[package]] +name = "enumflags2_derive" +version = "0.7.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67c78a4d8fdf9953a5c9d458f9efe940fd97a0cab0941c075a813ac594733827" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "equivalent" version = "1.0.3" @@ -146,12 +434,44 @@ dependencies = [ "windows-sys", ] +[[package]] +name = "event-listener" +version = "5.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a23add41df1562121a9393cb065eab5146a1242410f23a644851e90cfd669d2" +dependencies = [ + "parking", + "pin-project-lite", +] + +[[package]] +name = "event-listener-strategy" +version = "0.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8be9f3dfaaffdae2972880079a491a1a8bb7cbed0b8dd7a347f668b4150a3b93" +dependencies = [ + "event-listener", + "pin-project-lite", +] + +[[package]] +name = "fastrand" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" + [[package]] name = "find-msvc-tools" version = "0.1.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48" +[[package]] +name = "foldhash" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" + [[package]] name = "fontdue" version = "0.9.5" @@ -161,6 +481,61 @@ dependencies = [ "ttf-parser", ] +[[package]] +name = "futures-core" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" + +[[package]] +name = "futures-io" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53c0fa8157de1303bfffdaa1cc2a673bfffb60102f76b0ef4441659124373fed" + +[[package]] +name = "futures-lite" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f78e10609fe0e0b3f4157ffab1876319b5b0db102a2c60dc4626306dc46b44ad" +dependencies = [ + "fastrand", + "futures-core", + "futures-io", + "parking", + "pin-project-lite", +] + +[[package]] +name = "futures-macro" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9fb9654ba8355388abeb8dcb4fc62f511300867002afc858860463bdd9fe0c44" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "futures-task" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" + +[[package]] +name = "futures-util" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" +dependencies = [ + "futures-core", + "futures-macro", + "futures-task", + "pin-project-lite", + "slab", +] + [[package]] name = "getrandom" version = "0.2.17" @@ -189,6 +564,21 @@ name = "hashbrown" version = "0.17.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "735eaa21a6a5ffb2e84362faaeb90c05ba8e19797ca30428478cb6ea3a4921bc" +dependencies = [ + "foldhash", +] + +[[package]] +name = "hermit-abi" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e17592d60ebacc7d5e169f4663c5f84f9161cc90328abcfe8456f41e4dfcb284" + +[[package]] +name = "hex" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" [[package]] name = "indexmap" @@ -206,6 +596,17 @@ version = "1.0.19" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" +[[package]] +name = "js-sys" +version = "0.3.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8dc09d2154098bbf4ef54eab6b117a3c24cbbffe94046b16ee6d6d4510584d3a" +dependencies = [ + "cfg-if", + "futures-util", + "wasm-bindgen", +] + [[package]] name = "libc" version = "0.2.191" @@ -245,6 +646,15 @@ dependencies = [ "libc", ] +[[package]] +name = "memoffset" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "488016bfae457b036d996092f6cb448677611ce4449e970ceaf42695203f218a" +dependencies = [ + "autocfg", +] + [[package]] name = "num-traits" version = "0.2.19" @@ -260,12 +670,102 @@ version = "1.21.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" +[[package]] +name = "ordered-stream" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9aa2b01e1d916879f73a53d01d1d6cee68adbb31d6d9177a8cfce093cced1d50" +dependencies = [ + "futures-core", + "pin-project-lite", +] + +[[package]] +name = "parking" +version = "2.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f38d5652c16fde515bb1ecef450ab0f6a219d619a7274976324d5e377f7dceba" + +[[package]] +name = "phf" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "010378780309880b08997fae13be7834dba947d36393bd372f2b1556deb2a2f6" +dependencies = [ + "phf_macros", + "phf_shared", + "serde", +] + +[[package]] +name = "phf_generator" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aeb62e0959d5a1bebc965f4d15d9e2b7cea002b6b0f5ba8cde6cc26738467100" +dependencies = [ + "fastrand", + "phf_shared", +] + +[[package]] +name = "phf_macros" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5fa8d0ca26d424d27630da600c6624696e7dec8bf7b3b492b383c5dc49e5e085" +dependencies = [ + "phf_generator", + "phf_shared", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "phf_shared" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6fd9027e2d9319be6349febd1db4e8d02aa544921200c9b777720ac34a3aa89" +dependencies = [ + "siphasher", +] + +[[package]] +name = "pin-project-lite" +version = "0.2.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c938015719552d665fd0553b90d96cd7ff58e83e4c061ca99e6bb78865a72752" + +[[package]] +name = "piper" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c835479a4443ded371d6c535cbfd8d31ad92c5d23ae9770a61bc155e4992a3c1" +dependencies = [ + "atomic-waker", + "fastrand", + "futures-io", +] + [[package]] name = "pkg-config" version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548" +[[package]] +name = "polling" +version = "3.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d0e4f59085d47d8241c88ead0f274e8a0cb551f3625263c05eb8dd897c34218" +dependencies = [ + "cfg-if", + "concurrent-queue", + "hermit-abi", + "pin-project-lite", + "rustix", + "windows-sys", +] + [[package]] name = "ppv-lite86" version = "0.2.21" @@ -419,6 +919,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" dependencies = [ "serde_core", + "serde_derive", ] [[package]] @@ -454,12 +955,45 @@ dependencies = [ "zmij", ] +[[package]] +name = "serde_repr" +version = "0.1.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8d3b1629de253c70a0508c3899572da79ca359fdab27c7920ff00406df418906" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + [[package]] name = "shlex" version = "2.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" +[[package]] +name = "signal-hook-registry" +version = "1.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b" +dependencies = [ + "errno", + "libc", +] + +[[package]] +name = "siphasher" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33f4fe9184a62d842c9ef383018f3306d8ba224fd9d836f56d7288308847c256" + +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + [[package]] name = "smallvec" version = "1.16.6" @@ -492,6 +1026,12 @@ dependencies = [ "xkeysym", ] +[[package]] +name = "static_assertions" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" + [[package]] name = "syn" version = "2.0.119" @@ -514,6 +1054,19 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "tempfile" +version = "3.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" +dependencies = [ + "fastrand", + "getrandom 0.3.4", + "once_cell", + "rustix", + "windows-sys", +] + [[package]] name = "thiserror" version = "2.0.21" @@ -564,6 +1117,37 @@ dependencies = [ "winnow", ] +[[package]] +name = "tracing" +version = "0.1.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" +dependencies = [ + "pin-project-lite", + "tracing-attributes", + "tracing-core", +] + +[[package]] +name = "tracing-attributes" +version = "0.1.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "tracing-core" +version = "0.1.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" +dependencies = [ + "once_cell", +] + [[package]] name = "ttf-parser" version = "0.25.1" @@ -573,12 +1157,34 @@ dependencies = [ "core_maths", ] +[[package]] +name = "uds_windows" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2f6fb2847f6742cd76af783a2a2c49e9375d0a111c7bef6f71cd9e738c72d6e" +dependencies = [ + "memoffset", + "tempfile", + "windows-sys", +] + [[package]] name = "unicode-ident" version = "1.0.27" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" +[[package]] +name = "uuid" +version = "1.29.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c14b15dffa2f4bd712103e857140aa04a4f2ff6e955c77d7eb8e53ee02a3b64" +dependencies = [ + "js-sys", + "serde_core", + "wasm-bindgen", +] + [[package]] name = "wasi" version = "0.11.1+wasi-snapshot-preview1" @@ -812,6 +1418,112 @@ dependencies = [ "bytemuck", ] +[[package]] +name = "zbus" +version = "5.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5db4be7c075cb421e4b7ee645541604239bd243ba7c357511f4ff3a74b555907" +dependencies = [ + "async-broadcast", + "async-executor", + "async-io", + "async-lock", + "async-process", + "async-recursion", + "async-task", + "async-trait", + "blocking", + "enumflags2", + "event-listener", + "futures-core", + "futures-lite", + "hex", + "libc", + "ordered-stream", + "rustix", + "serde", + "serde_repr", + "tracing", + "uds_windows", + "uuid", + "windows-sys", + "winnow", + "zbus_macros", + "zbus_names", + "zvariant", +] + +[[package]] +name = "zbus-lockstep" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6998de05217a084b7578728a9443d04ea4cd80f2a0839b8d78770b76ccd45863" +dependencies = [ + "zbus_xml", + "zvariant", +] + +[[package]] +name = "zbus-lockstep-macros" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10da05367f3a7b7553c8cdf8fa91aee6b64afebe32b51c95177957efc47ca3a0" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", + "zbus-lockstep", + "zbus_xml", + "zvariant", +] + +[[package]] +name = "zbus_macros" +version = "5.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2990635d09ade6df1868f72f8cac69a876a90981e8bd3c40b1be413f8dc88f40" +dependencies = [ + "proc-macro-crate", + "proc-macro2", + "quote", + "syn 3.0.10", + "zbus_names", + "zvariant", + "zvariant_utils", +] + +[[package]] +name = "zbus_names" +version = "4.3.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "812a12be4ead7a59e18ea8f047d08add0066b73bc62fc1467066a2472ae088dd" +dependencies = [ + "serde", + "winnow", + "zvariant", +] + +[[package]] +name = "zbus_xml" +version = "5.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d1586c021a01ca0a9216dcd874e546382e156a5cbab5fab6cb5f10087e22682a" +dependencies = [ + "serde", + "winnow", + "zbus_names", + "zvariant", +] + +[[package]] +name = "zcheapstr" +version = "1.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2da34e7164b75d803c3197b86e6cf61b874106fbd472c5082575a8bc5fbd0907" +dependencies = [ + "serde", +] + [[package]] name = "zerocopy" version = "0.8.65" @@ -837,3 +1549,44 @@ name = "zmij" version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" + +[[package]] +name = "zvariant" +version = "5.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "80bf6d6cd6a4b601acb64cfb8284cdc643fcfa75ef26ae3c46ec8aa4e8a1fbb7" +dependencies = [ + "endi", + "enumflags2", + "serde", + "winnow", + "zcheapstr", + "zvariant_derive", + "zvariant_utils", +] + +[[package]] +name = "zvariant_derive" +version = "5.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef2672456ba1cb54b5eaec136e63135b3c7495fb938e53b28a62e633496d486d" +dependencies = [ + "proc-macro-crate", + "proc-macro2", + "quote", + "syn 3.0.10", + "zvariant_utils", +] + +[[package]] +name = "zvariant_utils" +version = "4.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bad0294361a320b694a328460dc73add56c306150f5cb6bfafc44446120008a3" +dependencies = [ + "proc-macro2", + "quote", + "serde", + "syn 3.0.10", + "winnow", +] diff --git a/Cargo.toml b/Cargo.toml index fa2db8f..cbda174 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -13,6 +13,10 @@ rustix = { version = "1", default-features = false, features = ["std", "event", smithay-client-toolkit = { version = "0.21", default-features = false, features = ["xkbcommon"] } wayland-protocols = { version = "0.32", features = ["client", "staging"] } +[workspace] +# The screen reader bridge, a library loaded only when one is running. +members = [".", "a11y"] + [profile.release] lto = "fat" codegen-units = 1 diff --git a/README.md b/README.md index b80a590..0b3ad93 100644 --- a/README.md +++ b/README.md @@ -11,16 +11,22 @@ The keypad works with the mouse or the keyboard: `0-9 . + - * x / ^ %`, Enter or - Ctrl+C (or Super+C, or Ctrl+Insert) copies the result without separators. - Ctrl+V (or Super+V, or Shift+Insert) pastes a number, with or without separators: `1,234.5`, `1 234,5` and `12,34` all work. Anything that isn't a number is ignored. +Tab and Shift+Tab move a focus ring through the keys, and the arrow keys move it around the grid; Space presses the focused key. Text follows the aliasOS text size (`aliasos-display-text-size`). + +With Orca running when it starts, the calculator works with the screen reader: each key is a named button, and the result is read out when it changes. Starting Orca later means reopening the calculator. + Colors follow the live aliasOS theme (`~/.local/state/aliasos/current/theme/colors.toml`), falling back to Omarchy's, and change as soon as the theme does. ## Build ```sh -cargo build --release +cargo build --workspace --release ``` The binary is `target/release/alias-calc`. The aim is to link nothing beyond libc and `libxkbcommon` (for keyboard layouts), with a pure-Rust Wayland client. +Screen reader support is a separate library, `target/release/libalias_calc_a11y.so` (the `a11y/` crate, with AccessKit). The calculator loads it only when Orca is running, from beside its binary or from `/usr/lib/alias-calc/`, so without a screen reader it costs nothing. A package installs it to `/usr/lib/alias-calc/`. + ## Benchmark Alias Calc must beat omacalc and GNOME Calculator on startup, memory and idle wakeups. In a Hyprland session, run: diff --git a/a11y/Cargo.toml b/a11y/Cargo.toml new file mode 100644 index 0000000..1ea4a2b --- /dev/null +++ b/a11y/Cargo.toml @@ -0,0 +1,17 @@ +[package] +name = "alias-calc-a11y" +version = "0.1.0" +edition = "2024" +license = "LicenseRef-Proprietary" +description = "Alias Calc's screen reader bridge, loaded only when one is running" +publish = false + +# A shared library that alias-calc loads with dlopen (src/a11y.rs there), so +# AccessKit costs nothing when no screen reader runs. +[lib] +name = "alias_calc_a11y" +crate-type = ["cdylib"] + +[dependencies] +accesskit = "0.25" +accesskit_unix = "0.24" diff --git a/a11y/src/lib.rs b/a11y/src/lib.rs new file mode 100644 index 0000000..5fbb576 --- /dev/null +++ b/a11y/src/lib.rs @@ -0,0 +1,415 @@ +//! Alias Calc's screen reader bridge: AccessKit, which speaks AT-SPI to +//! Orca, behind a small C interface. alias-calc loads this library with +//! dlopen only when a screen reader is running, so without one AccessKit +//! costs no memory, threads or binary size. +//! +//! The library knows nothing about the calculator: it's given a window +//! title, two texts (the expression and the result, read out when it +//! changes) and a grid of buttons with names and rectangles. +//! +//! AccessKit calls its handlers on its own thread. They queue requests and +//! write to the eventfd alias-calc passed in, and alias-calc takes them with +//! `alias_calc_a11y_next` on its own thread. +//! +//! The interface is versioned by [`ABI`]; alias-calc refuses a library with +//! another version. + +use std::fs::File; +use std::io::Write; +use std::os::fd::BorrowedFd; +use std::sync::mpsc::{Receiver, Sender, channel}; +use std::sync::{Arc, Mutex}; + +use accesskit::{ + Action, ActionHandler, ActionRequest, ActivationHandler, DeactivationHandler, Live, Node, + NodeId, Rect, Role, TreeId, TreeInfo, TreeUpdate, +}; + +/// Bumped on any change to the functions or structs below. +pub const ABI: u32 = 1; + +/// A borrowed UTF-8 string. +#[repr(C)] +#[derive(Clone, Copy)] +pub struct Str { + pub ptr: *const u8, + pub len: usize, +} + +impl Str { + /// # Safety + /// `ptr` must point to `len` bytes that live while the result is used. + unsafe fn get<'a>(self) -> &'a str { + if self.ptr.is_null() { + return ""; + } + // SAFETY: the caller's promise. + let bytes = unsafe { std::slice::from_raw_parts(self.ptr, self.len) }; + std::str::from_utf8(bytes).unwrap_or("") + } +} + +/// A button: its spoken name and its rectangle in logical pixels. +#[repr(C)] +#[derive(Clone, Copy)] +pub struct Button { + pub name: Str, + pub x: f32, + pub y: f32, + pub width: f32, + pub height: f32, +} + +/// What's on screen. +#[repr(C)] +pub struct State { + pub title: Str, + pub expression: Str, + pub result: Str, + pub buttons: *const Button, + pub button_count: usize, + /// The focused button's index, or -1 for the window. + pub focus: i32, + pub width: f32, + pub height: f32, +} + +/// What the screen reader asked for, as `alias_calc_a11y_next` returns it. +pub const REQUEST_NONE: u32 = 0; +/// It wants the whole tree: answer with `alias_calc_a11y_update`. +pub const REQUEST_TREE: u32 = 1; +/// Press the button. +pub const REQUEST_PRESS: u32 = 2; +/// Move keyboard focus to the button. +pub const REQUEST_FOCUS: u32 = 3; + +#[derive(Debug, PartialEq)] +enum Request { + Tree, + Press(u32), + Focus(u32), +} + +pub struct Bridge { + adapter: accesskit_unix::Adapter, + requests: Receiver, +} + +/// The interface version this library speaks. +#[unsafe(no_mangle)] +pub extern "C" fn alias_calc_a11y_abi() -> u32 { + ABI +} + +/// Starts the bridge. Requests are signalled by writing 1 to `wake` (an +/// eventfd, duplicated here). Null if `wake` can't be duplicated. +#[unsafe(no_mangle)] +pub extern "C" fn alias_calc_a11y_start(wake: i32) -> *mut Bridge { + if wake < 0 { + return std::ptr::null_mut(); + } + // SAFETY: the caller passes an open fd, which stays open for this call. + let borrowed = unsafe { BorrowedFd::borrow_raw(wake) }; + let Ok(wake) = borrowed.try_clone_to_owned() else { + return std::ptr::null_mut(); + }; + let (send, requests) = channel(); + let notify = Notify { + send: Arc::new(Mutex::new(send)), + wake: Arc::new(File::from(wake)), + }; + let adapter = accesskit_unix::Adapter::new(notify.clone(), notify, Inactive); + Box::into_raw(Box::new(Bridge { adapter, requests })) +} + +/// Takes the oldest request: its kind (REQUEST_*) and, for a press or focus, +/// the button's index in `button`. REQUEST_NONE when there's none. +/// +/// # Safety +/// `bridge` comes from `alias_calc_a11y_start`; `button` is writable. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn alias_calc_a11y_next(bridge: *mut Bridge, button: *mut u32) -> u32 { + // SAFETY: the caller's promise. + let Some(bridge) = (unsafe { bridge.as_mut() }) else { + return REQUEST_NONE; + }; + let (kind, index) = match bridge.requests.try_recv() { + Ok(Request::Tree) => (REQUEST_TREE, 0), + Ok(Request::Press(i)) => (REQUEST_PRESS, i), + Ok(Request::Focus(i)) => (REQUEST_FOCUS, i), + Err(_) => (REQUEST_NONE, 0), + }; + if !button.is_null() { + // SAFETY: the caller's promise. + unsafe { *button = index }; + } + kind +} + +/// Sends what's on screen, if a screen reader has asked for the tree. +/// +/// # Safety +/// `bridge` comes from `alias_calc_a11y_start`; `state` and everything it +/// points to are valid for this call. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn alias_calc_a11y_update(bridge: *mut Bridge, state: *const State) { + // SAFETY: the caller's promise. + let (Some(bridge), Some(state)) = (unsafe { bridge.as_mut() }, unsafe { state.as_ref() }) + else { + return; + }; + // SAFETY: the caller's promise. + bridge.adapter.update_if_active(|| unsafe { tree(state) }); +} + +/// Says whether the window has keyboard focus. +/// +/// # Safety +/// `bridge` comes from `alias_calc_a11y_start`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn alias_calc_a11y_window_focused(bridge: *mut Bridge, focused: bool) { + // SAFETY: the caller's promise. + if let Some(bridge) = unsafe { bridge.as_mut() } { + bridge.adapter.update_window_focus_state(focused); + } +} + +/// Queues requests from AccessKit's thread and wakes alias-calc. +#[derive(Clone)] +struct Notify { + send: Arc>>, + wake: Arc, +} + +impl Notify { + fn send(&self, request: Request) { + let sent = self + .send + .lock() + .is_ok_and(|send| send.send(request).is_ok()); + if sent { + // An eventfd adds the 8-byte count written to it. + let _ = (&*self.wake).write(&1u64.to_ne_bytes()); + } + } +} + +impl ActivationHandler for Notify { + fn request_initial_tree(&mut self) -> Option { + // The state lives on alias-calc's thread: it answers with + // alias_calc_a11y_update. + self.send(Request::Tree); + None + } +} + +impl ActionHandler for Notify { + fn do_action(&mut self, request: ActionRequest) { + let Some(index) = button_of(request.target_node) else { + return; + }; + match request.action { + Action::Click => self.send(Request::Press(index)), + Action::Focus => self.send(Request::Focus(index)), + _ => {} + } + } +} + +struct Inactive; + +impl DeactivationHandler for Inactive { + fn deactivate_accessibility(&mut self) {} +} + +const WINDOW: NodeId = NodeId(1); +const EXPRESSION: NodeId = NodeId(2); +const RESULT: NodeId = NodeId(3); +/// Buttons are numbered from here. +const FIRST_BUTTON: u64 = 10; +/// More than any keypad has; bounds what a request can name. +const MAX_BUTTONS: u64 = 256; + +fn button_node(index: usize) -> NodeId { + NodeId(FIRST_BUTTON + index as u64) +} + +fn button_of(node: NodeId) -> Option { + let index = node.0.checked_sub(FIRST_BUTTON)?; + (index < MAX_BUTTONS).then_some(index as u32) +} + +/// The whole tree: the window, the expression, the result and the buttons. +/// +/// # Safety +/// Everything `state` points to is valid. +unsafe fn tree(state: &State) -> TreeUpdate { + let buttons: &[Button] = if state.buttons.is_null() { + &[] + } else { + // SAFETY: the caller's promise. + unsafe { std::slice::from_raw_parts(state.buttons, state.button_count) } + }; + let buttons = &buttons[..buttons.len().min(MAX_BUTTONS as usize)]; + let rect = |x: f32, y: f32, w: f32, h: f32| Rect { + x0: x as f64, + y0: y as f64, + x1: (x + w) as f64, + y1: (y + h) as f64, + }; + let mut nodes = Vec::with_capacity(3 + buttons.len()); + let mut children = vec![EXPRESSION, RESULT]; + + // Labels speak their value. + let mut expression = Node::new(Role::Label); + // SAFETY: the caller's promise. + expression.set_value(unsafe { state.expression.get() }); + nodes.push((EXPRESSION, expression)); + + // A polite live region: the result is read out when it changes. + let mut result = Node::new(Role::Label); + // SAFETY: the caller's promise. + result.set_value(unsafe { state.result.get() }); + result.set_live(Live::Polite); + nodes.push((RESULT, result)); + + for (index, button) in buttons.iter().enumerate() { + let mut node = Node::new(Role::Button); + // SAFETY: the caller's promise. + node.set_label(unsafe { button.name.get() }); + node.add_action(Action::Click); + node.add_action(Action::Focus); + node.set_bounds(rect(button.x, button.y, button.width, button.height)); + children.push(button_node(index)); + nodes.push((button_node(index), node)); + } + + let mut window = Node::new(Role::Window); + // SAFETY: the caller's promise. + window.set_label(unsafe { state.title.get() }); + window.set_bounds(rect(0.0, 0.0, state.width, state.height)); + window.set_children(children); + nodes.push((WINDOW, window)); + + let focus = usize::try_from(state.focus) + .ok() + .filter(|&i| i < buttons.len()) + .map_or(WINDOW, button_node); + let mut tree = TreeInfo::new(WINDOW); + tree.toolkit_name = Some("Alias Calc".into()); + tree.toolkit_version = Some(env!("CARGO_PKG_VERSION").into()); + TreeUpdate { + nodes, + tree: Some(tree), + tree_id: TreeId::ROOT, + focus, + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::os::fd::OwnedFd; + + fn s(text: &str) -> Str { + Str { + ptr: text.as_ptr(), + len: text.len(), + } + } + + fn update(focus: i32) -> TreeUpdate { + let names = ["Clear", "7", "Divide"]; + let buttons: Vec