Skip to main content

saturnus_host/
lib.rs

1#![cfg_attr(test, allow(clippy::unwrap_used, clippy::expect_used))]
2//! What every front end of Saturnus needs around the core, with no
3//! bindings, no I/O and no threads (it builds for `wasm32` like the core):
4//! the browser's wasm bindings (`saturnus-web`), the desktop app and the
5//! CLI's control API (through `saturnus-drive`'s runner) all use it.
6//!
7//! [`protocol::Engine`] is the front end's protocol (`web/protocol.md` in
8//! the repository) with its pacing, implemented once for every host: it
9//! takes commands and the host's clock, gives replies and events, and
10//! says when it wants to be called again. A host only feeds it messages
11//! and timer calls.
12//!
13//! [`Emulator`] owns one [`Machine`] and runs it in emulated milliseconds
14//! ([`Emulator::run_ms`], [`Emulator::run_slice`]); it gives the display
15//! as change-detected events ([`Emulator::frame_if_changed`],
16//! [`host::Frame`]) and reads the user memory straight from RAM (48SX,
17//! 48GX, 49G: [`Emulator::memory_tree`], [`Emulator::stack`],
18//! [`Emulator::flags`]).
19//!
20//! - [`protocol`]: commands, replies, events, pacing, sends and the
21//!   memory watch.
22//! - [`host`]: the key queue that times presses and types letters in
23//!   emulated time, and the change-detected `frame` and `keys` events of
24//!   the front end's protocol (`web/protocol.md` in the repository).
25//! - [`typing`]: typing text into the command line (`insert`, `run`,
26//!   `replace`) in emulated time.
27//! - [`transfer`]: the writes to the user memory (store, fetch, purge,
28//!   rename, change directory, flags) as a hidden transaction with the
29//!   ROM's Kermit server, in emulated time.
30//! - [`layout`] and [`skins`]: each model's keys in their places and its
31//!   drawn calculator.
32//! - [`romid`]: ROM identification by SHA-256 ([`sha256`]) and size, and
33//!   the assignment of ROM files to models.
34//!
35//! Answers are typed values (serializable where a front end needs them as
36//! JSON); failures are the one [`Error`] type, shown to the user as its
37//! message. The wasm bindings and the native runner convert both to the
38//! protocol's JSON at their own edge.
39
40pub mod clock;
41mod error;
42pub mod host;
43pub mod layout;
44pub mod menulabels;
45pub mod protocol;
46pub mod romid;
47pub mod sha256;
48pub mod skins;
49pub mod transfer;
50pub mod typing;
51pub mod wire;
52
53use saturnus_core::io::Key;
54use saturnus_core::{Annunciators, LCD_HEIGHT, LCD_WIDTH, Lcd};
55use saturnus_core::{Machine, Model};
56use saturnus_objects::{Flags, NameTable, UserMemory, Variable, menus, softkeys};
57use serde::ser::SerializeMap;
58use std::sync::Arc;
59
60pub use error::{Error, Result};
61
62/// Bytes `framebuffer()` returns on the 131x64 models: one per pixel.
63pub const FRAMEBUFFER_BYTES: usize = LCD_WIDTH * LCD_HEIGHT;
64
65/// The pixels as one byte per pixel, row-major, 1 = dark.
66pub fn pack_pixels(lcd: &Lcd) -> Vec<u8> {
67    let mut out = Vec::with_capacity(lcd.width() * lcd.height());
68    for row in &lcd.pixels {
69        out.extend(row.iter().map(|&on| u8::from(on)));
70    }
71    out
72}
73
74/// The annunciators serialized as an object of booleans,
75/// `{leftshift, rightshift, alpha, alert, busy, transmit, updown, battery,
76/// g, rad, suspended}`: all eleven on every model, in
77/// [`Annunciators::list`] order.
78#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
79pub struct AnnunciatorFlags(pub Annunciators);
80
81impl serde::Serialize for AnnunciatorFlags {
82    fn serialize<S: serde::Serializer>(&self, s: S) -> std::result::Result<S::Ok, S::Error> {
83        let list = self.0.list();
84        let mut map = s.serialize_map(Some(list.len()))?;
85        for (name, on) in list {
86            map.serialize_entry(name, &on)?;
87        }
88        map.end()
89    }
90}
91
92/// The current directory and HOME's tree ([`Emulator::memory_tree`]).
93#[derive(Clone, Debug, serde::Serialize)]
94pub struct MemoryTree {
95    /// The current directory, e.g. `["HOME", "A"]`.
96    pub path: Vec<String>,
97    /// HOME's variables, newest first, with sub-directories.
98    pub variables: Vec<Variable>,
99}
100
101/// The emulated calculator.
102#[derive(Debug)]
103pub struct Emulator {
104    machine: Machine,
105    /// Fractional cycles owed by `run_ms` calls, so many short frames add
106    /// up to exactly `clock_hz` cycles per emulated second.
107    cycle_debt: f64,
108    /// Key presses timed in emulated time (see [`host`]).
109    queue: host::KeyQueue,
110    /// What the last `frame` event showed.
111    shown: Option<host::Frame>,
112    /// The keys down in the last `keys` event.
113    shown_keys: Option<Vec<&'static str>>,
114    /// The ROM's command names with the ROM generation they were built
115    /// at: built on the first object read, rebuilt when the ROM changed
116    /// (the 49G's flash is written by storing a library in port 2).
117    names: std::cell::RefCell<Option<(u64, Arc<NameTable>)>>,
118    /// The ROM's built-in menus with the ROM generation they were read
119    /// at (`None` inside: none found), read on the first menu event.
120    menus: std::cell::RefCell<Option<(u64, Option<Arc<menus::Menus>>)>>,
121    /// What the menu keys depended on at the last look
122    /// ([`softkeys::signature`]), and the keys the last `menu` event
123    /// gave.
124    menu_seen: Option<[u32; 6]>,
125    shown_menu: Option<Option<Vec<Option<softkeys::ShownKey>>>>,
126    /// The key presses the queue had started at the last look: a press
127    /// since may have changed what the signature does not see (ORDER,
128    /// a variable rewritten in place).
129    menu_presses: u64,
130    /// Read the keys again at the next look whatever the signature says:
131    /// a send or write ran, a state was loaded, memory poked.
132    menu_dirty: bool,
133    /// Send the next `menu` event even when it says what the last one
134    /// did, `null` included ([`Emulator::reshow`]: the page and the hub
135    /// may hold the keys of the machine as it was).
136    menu_force: bool,
137    /// A send typing into the command line (see [`typing`]).
138    typing: Option<typing::Job>,
139    /// A write through the Kermit server (see [`transfer`]).
140    transfer: Option<transfer::Transfer>,
141}
142
143impl Emulator {
144    /// Build `model` from its ROM image.
145    pub fn new(model: Model, rom: &[u8]) -> Result<Self> {
146        let machine = Machine::new(model, rom)?;
147        Ok(Self {
148            queue: host::KeyQueue::new(model),
149            machine,
150            cycle_debt: 0.0,
151            shown: None,
152            shown_keys: None,
153            names: std::cell::RefCell::new(None),
154            menus: std::cell::RefCell::new(None),
155            menu_seen: None,
156            shown_menu: None,
157            menu_presses: 0,
158            menu_dirty: true,
159            menu_force: false,
160            typing: None,
161            transfer: None,
162        })
163    }
164
165    /// Wrap a machine a native host built (and perhaps already ran), with
166    /// an empty key queue; the next frame and keys are sent in full.
167    pub fn from_machine(machine: Machine) -> Self {
168        Self {
169            queue: host::KeyQueue::new(machine.model()),
170            machine,
171            cycle_debt: 0.0,
172            shown: None,
173            shown_keys: None,
174            names: std::cell::RefCell::new(None),
175            menus: std::cell::RefCell::new(None),
176            menu_seen: None,
177            shown_menu: None,
178            menu_presses: 0,
179            menu_dirty: true,
180            menu_force: false,
181            typing: None,
182            transfer: None,
183        }
184    }
185
186    /// A copy of the machine to try something on (the clock's rehearsal):
187    /// the same machine and the same fraction of a cycle owed, an empty
188    /// key queue, no send or write.
189    pub fn rehearsal(&self) -> Self {
190        let mut e = Self::from_machine(self.machine.clone());
191        e.cycle_debt = self.cycle_debt;
192        e
193    }
194
195    /// The machine, for a native host that drives it directly (a key
196    /// script) or keeps it after the emulator.
197    pub fn into_machine(self) -> Machine {
198        self.machine
199    }
200
201    /// The machine, mutably, for native hosts (the serial bridge, memory
202    /// writes).
203    pub fn machine_mut(&mut self) -> &mut Machine {
204        &mut self.machine
205    }
206
207    /// Run `ms` emulated milliseconds; returns the cycles run.
208    pub fn run_ms(&mut self, ms: f64) -> Result<f64> {
209        if !ms.is_finite() || ms <= 0.0 {
210            return Ok(0.0);
211        }
212        let want = ms * f64::from(self.machine.model().clock_hz()) / 1000.0 + self.cycle_debt;
213        let whole = want.floor();
214        if whole < 1.0 {
215            self.cycle_debt = want;
216            return Ok(0.0);
217        }
218        let start = self.machine.cycles();
219        // `whole` is positive and far below 2^53 for any sane frame.
220        let n = whole as u64;
221        let result = self.machine.run_cycles(n);
222        let ran = self.machine.cycles() - start;
223        // The machine may overshoot by up to one instruction (or a SHUTDN
224        // skip); carry that as a credit into the next call.
225        self.cycle_debt = want - ran as f64;
226        result?;
227        Ok(ran as f64)
228    }
229
230    fn key(&self, name: &str) -> Result<Key> {
231        Key::from_name(name).ok_or_else(|| format!("unknown key {name:?}").into())
232    }
233
234    /// Press the key named `name`.
235    pub fn key_down(&mut self, name: &str) -> Result<()> {
236        let k = self.key(name)?;
237        Ok(self.machine.key_down(k)?)
238    }
239
240    /// Release the key named `name`.
241    pub fn key_up(&mut self, name: &str) -> Result<()> {
242        let k = self.key(name)?;
243        Ok(self.machine.key_up(k)?)
244    }
245
246    /// Restore a state saved by `save_state` for the same model and ROM.
247    /// The keys the state holds are its own; the host's queued and held
248    /// presses (a shifted one too), and a send or a write in progress,
249    /// belonged to the machine before and are dropped, so none of them
250    /// plays into the loaded one. On error nothing changes.
251    pub fn load_state(&mut self, data: &[u8]) -> Result<()> {
252        self.machine.load_state(data)?;
253        self.menu_dirty = true;
254        self.cycle_debt = 0.0;
255        self.queue.clear();
256        self.typing = None;
257        self.transfer = None;
258        Ok(())
259    }
260
261    /// Emulated milliseconds the shut-down CPU will sleep before its next
262    /// timer or UART event, so a host can stop stepping and set a timer
263    /// instead; `None` while the CPU runs or has a wake condition pending.
264    pub fn idle_ms(&self) -> Option<f64> {
265        self.machine
266            .idle_cycles()
267            .map(|c| c as f64 * 1000.0 / f64::from(self.machine.model().clock_hz()))
268    }
269
270    /// The CPU cycles of one step of a send or a write that may take
271    /// `ms` of emulated time (at least 1 ms).
272    pub(crate) fn step_cycles(&self, ms: f64) -> u64 {
273        let per_ms = f64::from(self.machine.model().clock_hz()) / 1000.0;
274        (ms.max(1.0) * per_ms) as u64
275    }
276
277    /// The machine, for native callers and tests.
278    pub fn machine(&self) -> &Machine {
279        &self.machine
280    }
281
282    fn user_memory(&self) -> Result<UserMemory<'_>> {
283        UserMemory::of(&self.machine).map_err(Into::into)
284    }
285
286    /// The ROM's command names, built on the first call and again
287    /// whenever the ROM moved on ([`Machine::rom_generation`]).
288    fn names(&self) -> Arc<NameTable> {
289        let generation = self.machine.rom_generation();
290        let mut cached = self.names.borrow_mut();
291        match &*cached {
292            Some((g, names)) if *g == generation => names.clone(),
293            _ => {
294                let names = Arc::new(NameTable::of(&self.machine));
295                *cached = Some((generation, names.clone()));
296                names
297            }
298        }
299    }
300
301    /// The ROM's built-in menus (48SX, 48GX, 49G; `None` elsewhere),
302    /// read once per ROM generation as [`Emulator::names`] are.
303    fn menus(&self) -> Option<Arc<menus::Menus>> {
304        let generation = self.machine.rom_generation();
305        let mut cached = self.menus.borrow_mut();
306        match &*cached {
307            Some((g, m)) if *g == generation => m.clone(),
308            _ => {
309                let names = self.names();
310                let m = menus::read(self.machine.rom_nibbles(), &names).map(Arc::new);
311                *cached = Some((generation, m.clone()));
312                m
313            }
314        }
315    }
316
317    /// The six menu keys the screen shows now, read from RAM
318    /// ([`softkeys::read`] on the 48SX, 48GX and 49G, [`menulabels::read`]
319    /// on the 42S, 27S, 17BII, 17B, 19BII and 28S): `None` where they are
320    /// not known (another model, another screen has the keyboard, a menu
321    /// the ROM builds in RAM, no label boxes drawn).
322    pub fn menu_keys(&self) -> Result<Option<Vec<Option<softkeys::ShownKey>>>> {
323        if menulabels::reads(self.machine.model()) {
324            return Ok(menulabels::read(&self.machine));
325        }
326        self.user_memory()?;
327        let Some(defs) = self.menus() else {
328            return Ok(None);
329        };
330        Ok(softkeys::read(&self.machine, &defs)?)
331    }
332
333    /// The `menu` event if the menu keys changed since the last one, else
334    /// `None`; on the models [`Emulator::menu_keys`] reads, and to be
335    /// called while the ROM waits for a key (its RAM is whole then). Cheap
336    /// when nothing moved: on the 48SX, 48GX and 49G the keys are read
337    /// again only when the menu, its page, the current directory, the
338    /// variables, the stack or the screen's loop changed
339    /// ([`softkeys::signature`]); the others' are a few nibbles and the
340    /// LCD's label row, read each time.
341    pub fn menu_if_changed(&mut self) -> Option<host::MenuKeys> {
342        if menulabels::reads(self.machine.model()) {
343            let keys = menulabels::read(&self.machine);
344            return self.menu_news(keys);
345        }
346        self.user_memory().ok()?;
347        if self.typing.is_some() || self.transfer.is_some() {
348            self.menu_dirty = true;
349            return None;
350        }
351        let seen = softkeys::signature(&self.machine).ok();
352        let presses = self.queue.presses_started();
353        let same = seen.is_some()
354            && seen == self.menu_seen
355            && presses == self.menu_presses
356            && !self.menu_dirty
357            && self.shown_menu.is_some();
358        if same {
359            return None;
360        }
361        self.menu_seen = seen;
362        self.menu_presses = presses;
363        self.menu_dirty = false;
364        let keys = self.menu_keys().ok().flatten();
365        self.menu_news(keys)
366    }
367
368    /// The `menu` event for `keys` read now, if they are news.
369    fn menu_news(
370        &mut self,
371        keys: Option<Vec<Option<softkeys::ShownKey>>>,
372    ) -> Option<host::MenuKeys> {
373        let force = std::mem::take(&mut self.menu_force);
374        // A page starts with no menu keys known: none is not news, unless
375        // the machine changed under it (`menu_force`).
376        if !force && self.shown_menu.as_ref().unwrap_or(&None) == &keys {
377            self.shown_menu = Some(keys);
378            return None;
379        }
380        self.shown_menu = Some(keys.clone());
381        Some(host::MenuKeys { keys })
382    }
383
384    /// Why this model has no memory view (an aplet model, the 42S), or
385    /// `None` for a model whose user memory can be read.
386    pub fn memory_refusal(&self) -> Option<String> {
387        self.user_memory().err().map(|e| e.to_string())
388    }
389
390    /// The current directory and HOME's tree.
391    pub fn memory_tree(&self) -> Result<MemoryTree> {
392        let u = self.user_memory()?;
393        let path = u.current_path()?;
394        let variables = u.tree()?;
395        Ok(MemoryTree { path, variables })
396    }
397
398    /// The stack's typed levels, level 1 first, each object with the
399    /// calculator's own `text` (`saturnus_objects::described`).
400    pub fn stack(&self) -> Result<Vec<serde_json::Value>> {
401        let names = self.names();
402        let levels = self.user_memory()?.with_names(&names).stack_described()?;
403        Ok(levels)
404    }
405
406    /// The stack's depth and level 1 (`{depth, level1}`, `level1` null on
407    /// an empty stack), level 1 described as [`Emulator::stack`]'s are,
408    /// the other levels not decoded.
409    pub fn stack_top(&self) -> Result<serde_json::Value> {
410        let names = self.names();
411        let (depth, level1) = self.user_memory()?.with_names(&names).stack_top()?;
412        Ok(serde_json::json!({"depth": depth, "level1": level1}))
413    }
414
415    /// The flags (`{system, user, set}` in JSON).
416    pub fn flags(&self) -> Result<Flags> {
417        Ok(self.user_memory()?.flags()?)
418    }
419
420    /// The typed object at `address` (a variable's `address`), with the
421    /// calculator's own `text` on it and on every object inside.
422    pub fn object_at(&self, address: u32) -> Result<serde_json::Value> {
423        let names = self.names();
424        let obj = self
425            .user_memory()?
426            .with_names(&names)
427            .object_described(address)?;
428        Ok(obj)
429    }
430
431    /// A counter that moves whenever a variable, the current directory,
432    /// the stack or a flag changes.
433    pub fn memory_changes(&self) -> Result<u64> {
434        Ok(self.user_memory()?.change_counter()?)
435    }
436}
437
438impl Emulator {
439    /// The emulated model.
440    pub fn model(&self) -> Model {
441        self.machine.model()
442    }
443
444    /// The whole machine state (binds to this model and ROM).
445    pub fn save_state(&self) -> Vec<u8> {
446        self.machine.save_state()
447    }
448
449    /// Hardware reset; RAM is kept.
450    pub fn reset(&mut self) {
451        self.machine.reset();
452    }
453
454    /// CPU cycles since power-on (exact below 2^53).
455    pub fn cycles(&self) -> f64 {
456        self.machine.cycles() as f64
457    }
458
459    /// Emulated milliseconds since power-on.
460    pub fn emulated_ms(&self) -> f64 {
461        self.machine.cycles() as f64 * 1000.0 / f64::from(self.machine.model().clock_hz())
462    }
463
464    /// True while the CPU sleeps in SHUTDN.
465    pub fn is_shutdown(&self) -> bool {
466        self.machine.is_shutdown()
467    }
468}
469
470#[cfg(test)]
471mod tests {
472    use super::*;
473
474    fn put(n: &mut [u8], at: usize, value: usize, width: usize) {
475        for i in 0..width {
476            n[at + i] = ((value >> (4 * i)) & 0xF) as u8;
477        }
478    }
479
480    fn put_rel(n: &mut [u8], at: usize, target: usize) {
481        put(n, at, (target + 0x100000 - at) & 0xFFFFF, 5);
482    }
483
484    /// Library `id` with one command named `name` at nibble `base` of `n`
485    /// (layout: wiki protocols/rpl-libraries).
486    fn library(n: &mut [u8], base: usize, id: usize, name: &str) {
487        let (header, hash, object) = (base, base + 0x40, base + 0x200);
488        let body = hash + 10;
489        let entry = body + 85;
490        put_rel(n, body + 5 * (name.len() - 1), entry);
491        put(n, entry, name.len(), 2);
492        for (i, b) in name.bytes().enumerate() {
493            put(n, entry + 2 + 2 * i, usize::from(b), 2);
494        }
495        put(n, entry + 2 + 2 * name.len(), 0, 3);
496        let numbers = entry + 2 + 2 * name.len() + 3;
497        put_rel(n, body + 80, numbers);
498        put(n, numbers, numbers - entry, 5);
499        let end = numbers + 5;
500        put(n, hash, 0x02A4E, 5);
501        put(n, hash + 5, end - hash - 5, 5);
502        let link = end;
503        put(n, link, 0x02A4E, 5);
504        put(n, link + 5, 10, 5);
505        put_rel(n, link + 10, object);
506        put(n, object - 6, id, 3);
507        put(n, object - 3, 0, 3);
508        put(n, object, 0x02D9D, 5);
509        put(n, object + 5, 0x0312B, 5);
510        put(n, header, id, 3);
511        put_rel(n, header + 3, hash);
512        put_rel(n, header + 13, link);
513    }
514
515    /// The 49G's flash changes under a running emulator (a library stored
516    /// in port 2, here a loaded state): the name table is rebuilt and the
517    /// new library resolves.
518    #[test]
519    fn names_follow_flash_changes() {
520        let marker = b"saturnus-marker!";
521        let mut image = vec![0xFFu8; Model::Hp49g.rom_bytes()];
522        image[0x100..0x110].copy_from_slice(marker);
523        let emu = Emulator::from_machine(Machine::new(Model::Hp49g, &image).unwrap());
524        assert_eq!(emu.names().xlib(0x123, 0), None);
525        let first = emu.names();
526        assert!(Arc::ptr_eq(&first, &emu.names()), "cached while unchanged");
527
528        // The same flash with the library in bank 5, through a state.
529        let mut nibbles: Vec<u8> = image.iter().flat_map(|&b| [b & 0xF, b >> 4]).collect();
530        library(&mut nibbles, 5 * 0x40000 + 0x1000, 0x123, "FOO");
531        let packed: Vec<u8> = nibbles.chunks(2).map(|p| p[0] | (p[1] << 4)).collect();
532        let mut state = emu.machine().save_state();
533        let at = state
534            .windows(marker.len())
535            .position(|w| w == marker)
536            .unwrap()
537            - 0x100;
538        state[at..at + packed.len()].copy_from_slice(&packed);
539        let mut emu = emu;
540        emu.load_state(&state).unwrap();
541        let names = emu.names();
542        assert!(!Arc::ptr_eq(&first, &names), "rebuilt after the change");
543        assert_eq!(names.xlib(0x123, 0).and_then(|c| c.name), Some("FOO"));
544    }
545
546    #[test]
547    fn pixels_pack_one_byte_each_row_major() {
548        let mut lcd = Lcd::blank();
549        lcd.pixels[0][0] = true;
550        lcd.pixels[0][130] = true;
551        lcd.pixels[1][0] = true;
552        lcd.pixels[63][130] = true;
553        let fb = pack_pixels(&lcd);
554        assert_eq!(fb.len(), FRAMEBUFFER_BYTES);
555        assert_eq!(fb.len(), 8384);
556        let lit: Vec<usize> = (0..fb.len()).filter(|&i| fb[i] == 1).collect();
557        assert_eq!(lit, vec![0, 130, 131, 8383]);
558        assert!(fb.iter().all(|&b| b <= 1));
559    }
560
561    #[test]
562    fn annunciators_as_json() {
563        let json = |a| serde_json::to_string(&AnnunciatorFlags(a)).unwrap();
564        assert_eq!(
565            json(Annunciators::default()),
566            "{\"leftshift\":false,\"rightshift\":false,\"alpha\":false,\
567             \"alert\":false,\"busy\":false,\"transmit\":false,\"updown\":false,\
568             \"battery\":false,\"g\":false,\"rad\":false,\"suspended\":false}"
569        );
570        let j = json(Annunciators {
571            alpha: true,
572            busy: true,
573            ..Annunciators::default()
574        });
575        assert!(j.contains("\"alpha\":true") && j.contains("\"busy\":true"));
576        assert!(j.contains("\"leftshift\":false"));
577    }
578
579    #[test]
580    fn rejects_wrong_rom_size() {
581        let e = Emulator::new(Model::Hp48sx, &[0u8; 1000]).unwrap_err();
582        assert!(e.to_string().contains("1000"), "{e}");
583    }
584
585    /// A machine on a ROM of zeros runs (it loops through nonsense or
586    /// halts) and keeps exact time across many short frames.
587    #[test]
588    fn run_ms_keeps_exact_time() {
589        // A ROM of #F nibbles... any content; use zeros and tolerate a halt.
590        let mut emu = Emulator::new(Model::Hp48sx, &vec![0u8; 256 * 1024]).unwrap();
591        let mut total = 0.0;
592        for _ in 0..100 {
593            match emu.run_ms(0.3) {
594                Ok(c) => total += c,
595                Err(e) => {
596                    assert!(matches!(e, Error::Halted(_)), "{e}");
597                    return;
598                }
599            }
600        }
601        // 100 x 0.3 ms at 2 MHz = 60000 cycles, give or take one
602        // instruction of overshoot.
603        assert!((total - 60_000.0).abs() < 100.0, "{total}");
604        assert_eq!(emu.run_ms(0.0), Ok(0.0));
605        assert_eq!(emu.run_ms(f64::NAN), Ok(0.0));
606    }
607
608    #[test]
609    fn keys_by_name_per_model() {
610        let mut emu = Emulator::new(Model::Hp48sx, &vec![0u8; 256 * 1024]).unwrap();
611        assert!(emu.key_down("enter").is_ok());
612        assert!(emu.key_up("enter").is_ok());
613        assert!(emu.key_down("f1").is_ok());
614        assert!(
615            emu.key_down("bogus")
616                .unwrap_err()
617                .to_string()
618                .contains("unknown key")
619        );
620        // The 49G-only key is refused on a 48.
621        assert!(emu.key_down("apps").is_err());
622    }
623
624    /// The memory view needs memory the ROM has set up; the aplet models
625    /// have none.
626    #[test]
627    fn memory_view_errors() {
628        let emu = Emulator::new(Model::Hp48sx, &vec![0u8; 256 * 1024]).unwrap();
629        let e = emu.memory_tree().unwrap_err();
630        assert!(e.to_string().contains("no directory at HOME"), "{e}");
631        assert!(
632            matches!(&e, Error::Objects(o) if o.is_not_set_up()),
633            "{e:?}"
634        );
635        let flags = serde_json::to_string(&emu.flags().unwrap()).unwrap();
636        assert!(flags.contains("\"set\":[]"));
637        let emu = Emulator::new(Model::Hp38g, &vec![0u8; 512 * 1024]).unwrap();
638        assert!(emu.stack().unwrap_err().to_string().contains("aplets"));
639        let emu = Emulator::new(Model::Hp42s, &vec![0u8; 64 * 1024]).unwrap();
640        for e in [
641            emu.stack().unwrap_err(),
642            emu.memory_tree().unwrap_err(),
643            emu.flags().unwrap_err(),
644        ] {
645            assert!(e.to_string().contains("42S has no RPL user memory"), "{e}");
646        }
647    }
648
649    /// A fresh machine on a ROM of zeros is running, so it reports no idle
650    /// span.
651    #[test]
652    fn idle_ms_is_none_while_running() {
653        let emu = Emulator::new(Model::Hp48sx, &vec![0u8; 256 * 1024]).unwrap();
654        assert_eq!(emu.idle_ms(), None);
655    }
656
657    #[test]
658    fn state_round_trip() {
659        let mut emu = Emulator::new(Model::Hp48sx, &vec![0u8; 256 * 1024]).unwrap();
660        let _ = emu.run_ms(1.0);
661        let saved = emu.machine().save_state();
662        let cycles = emu.machine().cycles();
663        let _ = emu.run_ms(5.0);
664        emu.load_state(&saved).unwrap();
665        assert_eq!(emu.machine().cycles(), cycles);
666        assert!(emu.load_state(&[1, 2, 3]).is_err());
667    }
668
669    /// Presses queued (or held) for the machine before a state load do
670    /// not play into the loaded one; on a failed load they stay.
671    #[test]
672    fn a_state_load_drops_the_queued_presses() {
673        let mut emu = Emulator::new(Model::Hp48sx, &vec![0u8; 256 * 1024]).unwrap();
674        let _ = emu.run_ms(1.0);
675        let saved = emu.machine().save_state();
676        assert!(emu.press("1"));
677        assert!(emu.press("enter"));
678        assert!(emu.press_shifted("sqrt", "leftshift"));
679        emu.type_keys("2 3");
680        assert!(emu.keys_busy());
681        assert!(emu.load_state(&[1, 2, 3]).is_err());
682        assert!(emu.keys_busy(), "a failed load changes nothing");
683        emu.load_state(&saved).unwrap();
684        assert!(!emu.keys_busy(), "the queue is empty");
685        emu.pump();
686        assert_eq!(
687            emu.keys_if_changed().map(|k| k.down),
688            Some(vec![]),
689            "no key went down"
690        );
691        assert_eq!(
692            emu.machine().save_state(),
693            saved,
694            "the loaded machine as saved: no key pressed in it"
695        );
696    }
697
698    /// A send or a write in progress belonged to the machine before a
699    /// state load: a load drops it, a failed load keeps it.
700    #[test]
701    fn a_state_load_drops_a_send_or_a_write_in_progress() {
702        let mut emu = Emulator::new(Model::Hp48sx, &vec![0u8; 256 * 1024]).unwrap();
703        let _ = emu.run_ms(1.0);
704        let saved = emu.machine().save_state();
705        emu.start_typing("insert", "12").unwrap();
706        assert!(emu.typing());
707        assert!(emu.load_state(&[1, 2, 3]).is_err());
708        assert!(emu.typing(), "a failed load keeps the send");
709        emu.load_state(&saved).unwrap();
710        assert!(!emu.typing(), "the send is gone");
711        assert!(emu.typing_step(10.0).is_err(), "no typing in progress");
712
713        emu.transfer = Some(transfer::Transfer::empty(emu.machine()));
714        assert!(emu.transferring());
715        assert!(emu.load_state(&[1, 2, 3]).is_err());
716        assert!(emu.transferring(), "a failed load keeps the write");
717        emu.load_state(&saved).unwrap();
718        assert!(!emu.transferring(), "the write is gone");
719        assert!(emu.transfer_step(10.0).is_err(), "no write in progress");
720    }
721
722    #[test]
723    fn hp42s_has_a_16_row_display_and_its_own_keys() {
724        let mut emu = Emulator::new(Model::Hp42s, &vec![0u8; 64 * 1024]).unwrap();
725        assert_eq!(emu.machine().lcd().height(), 16);
726        assert_eq!(pack_pixels(&emu.machine().lcd()).len(), 131 * 16);
727        assert!(emu.key_down("xeq").is_ok());
728        assert!(emu.key_down("exit").is_ok());
729        assert!(
730            emu.key_down("f1").is_err(),
731            "the 42S's menu keys keep their labels"
732        );
733    }
734}
735
736// The README (the crate's page on crates.io) compiles as a doctest.
737#[cfg(doctest)]
738#[doc = include_str!("../README.md")]
739struct ReadmeDoctests;