Skip to main content

saturnus_host/
host.rs

1//! What a host needs around an [`Emulator`] to run it behind the front
2//! end's command/event protocol (`web/protocol.md`): the key queue that
3//! times presses and types letters in emulated time ([`KeyQueue`]), the
4//! slice runner that feeds it, the change-detected `frame` and `keys`
5//! events, and the choice of model for a ROM file.
6//!
7//! Every host uses this through [`crate::protocol`], which adds the
8//! wall-clock pacing; everything here is in emulated time and has no I/O.
9
10use std::collections::VecDeque;
11
12use saturnus_core::io::Key;
13use saturnus_core::{LCD_WIDTH, Machine, Model};
14
15use crate::layout;
16use crate::skins::{self, Typing};
17use crate::{AnnunciatorFlags, Emulator, Error};
18
19/// Shortest key press the ROM sees, in emulated ms (its debounce needs >10).
20pub const MIN_HOLD_MS: f64 = 60.0;
21/// Shortest pause between two queued key presses, in emulated ms.
22pub const GAP_MS: f64 = 30.0;
23/// How long a queued press waits for the ROM to go idle (SHUTDN) after
24/// the previous key, in emulated ms; while the ROM stays busy longer, as
25/// in a running program, the press goes in anyway. A press sent while
26/// the ROM still handles the last key may be lost (the 48SX ROM drops
27/// it), so the cap lies above the longest time each ROM stays awake
28/// after an ordinary key: measured over 40 timer phases for a shift, a
29/// digit, ENTER and a function key (kb: decision log, "Key waits per
30/// model"), plus a margin; 300 ms where the ROM never stays awake that
31/// long. The 48SX stays awake about 250 ms or, by its timer's phase,
32/// about 525 ms after a shift, and up to 750 ms after √x.
33pub fn busy_gap_ms(model: Model) -> f64 {
34    match model {
35        // Measured up to 753 ms (√x), 605 (ENTER), 583 (shift).
36        Model::Hp48sx => 850.0,
37        // Up to 521 ms (shift), 516 (ENTER).
38        Model::Hp48gx => 600.0,
39        // Up to 462 ms (ENTER).
40        Model::Hp49g => 550.0,
41        // Up to 968 ms (ENTER), 523 (a digit, √x, shift).
42        Model::Hp38g => 1100.0,
43        // Up to 244 ms (39G, 40G) and 78 ms (42S); the 27S, 17BII and
44        // 17B are taken as the 42S (same board, not measured).
45        Model::Hp39g
46        | Model::Hp40g
47        | Model::Hp42s
48        | Model::Hp27s
49        | Model::Hp17bii
50        | Model::Hp17b => 300.0,
51        // Not measured: the 28S shows its busy annunciator for about
52        // 210 ms after ENTER and 2 ENTER 3 + (28S ROM 2BB); the 19BII is
53        // taken as the 28S (same board).
54        Model::Hp28s | Model::Hp19bii => 300.0,
55    }
56}
57/// Shortest pause before a key is pressed again right after its own
58/// release, in emulated ms. The 39G and 40G ROM takes a key pressed again
59/// within about 95 ms of its release as the same press and drops it (in
60/// Saturnus, 1133 typed as 13, twelve 1s in a row as six; seen before and
61/// after the held-keys fix of 2026-10-13); 150 ms leaves a margin. The
62/// other models take [`GAP_MS`] (tried on the 38G, 27S, 17B, 17BII and
63/// 19BII: 1133.555 typed whole).
64pub fn repeat_gap_ms(model: Model) -> f64 {
65    match model {
66        Model::Hp39g | Model::Hp40g => 150.0,
67        _ => GAP_MS,
68    }
69}
70
71/// Quiet time before a typed letter or a shifted press reads an
72/// annunciator while the ROM stays busy, in emulated ms, at least: the
73/// 48SX ROM blinks alpha while it redraws the command line, up to about
74/// 250 ms after a key is released. Never shorter than the model's
75/// [`busy_gap_ms`], which a queued press waits for first.
76pub const LETTER_SETTLE_MS: f64 = 400.0;
77/// Runs are cut in slices of this many emulated ms, so key timing is fine.
78pub const SLICE_MS: f64 = 10.0;
79
80/// The machine as the key queue sees it.
81pub trait Keyboard {
82    /// Emulated milliseconds since power-on.
83    fn now_ms(&self) -> f64;
84    /// True while the CPU sleeps in SHUTDN.
85    fn idle(&self) -> bool;
86    /// The alpha annunciator.
87    fn alpha_on(&self) -> bool;
88    /// The annunciator of shift key `shift` (`leftshift`, `rightshift`);
89    /// a model with one `shift` key reports either.
90    fn shift_on(&self, shift: &str) -> bool;
91    /// Press the key named `name`.
92    fn down(&mut self, name: &str) -> crate::Result<()>;
93    /// Release the key named `name`.
94    fn up(&mut self, name: &str);
95}
96
97impl Keyboard for Machine {
98    fn now_ms(&self) -> f64 {
99        self.cycles() as f64 * 1000.0 / f64::from(self.model().clock_hz())
100    }
101
102    fn idle(&self) -> bool {
103        self.is_shutdown()
104    }
105
106    fn alpha_on(&self) -> bool {
107        self.framebuffer().annunciators.alpha
108    }
109
110    fn shift_on(&self, shift: &str) -> bool {
111        let a = self.framebuffer().annunciators;
112        match shift {
113            "leftshift" => a.left_shift,
114            "rightshift" => a.right_shift,
115            _ => a.left_shift || a.right_shift,
116        }
117    }
118
119    fn down(&mut self, name: &str) -> crate::Result<()> {
120        let k = Key::from_name(name).ok_or_else(|| format!("unknown key {name:?}"))?;
121        Ok(self.key_down(k)?)
122    }
123
124    fn up(&mut self, name: &str) {
125        if let Some(k) = Key::from_name(name) {
126            // Only fails for a key the model lacks, which was never pressed.
127            let _ = self.key_up(k);
128        }
129    }
130}
131
132/// One key press, queued or down.
133#[derive(Clone, Debug)]
134struct Press {
135    name: &'static str,
136    /// Released by the user (or a typed press, released once held long
137    /// enough).
138    up: bool,
139    /// Emulated ms it went down.
140    down_at: f64,
141    /// Pressed by the queue for a typed letter or key sequence.
142    typed: bool,
143}
144
145#[derive(Clone, Debug)]
146enum Item {
147    Press(Press),
148    /// A letter, expanded into presses when its turn comes.
149    Letter {
150        letter: char,
151        lower: bool,
152    },
153    /// A press of a key's shifted function (a modifier click): when its
154    /// turn comes, the shift is tapped first unless its annunciator is on.
155    Shifted {
156        shift: &'static str,
157        press: Press,
158    },
159}
160
161/// The shift keys a [`KeyQueue::press_shifted`] may name.
162const SHIFT_KEYS: [&str; 3] = ["leftshift", "rightshift", "shift"];
163
164/// Key presses in emulated time: `active` keys are down in the machine;
165/// `pending` presses (or letters, expanded when their turn comes) wait for
166/// a fast-typed predecessor to be released first.
167#[derive(Clone, Debug)]
168pub struct KeyQueue {
169    /// The model's keys (its drawn layout), the only names accepted.
170    names: Vec<&'static str>,
171    /// `None` on a model without typing data (the 42S types letters from
172    /// its ALPHA menus), which then types no letters.
173    typing: Option<Typing>,
174    letters: Vec<(char, &'static str)>,
175    active: Vec<Press>,
176    pending: VecDeque<Item>,
177    last_release_ms: f64,
178    /// The key released last.
179    last_released: Option<&'static str>,
180    /// [`repeat_gap_ms`] of the model.
181    repeat_gap_ms: f64,
182    /// Presses the machine took since the queue was made.
183    started: u64,
184    /// [`busy_gap_ms`] of the model.
185    busy_gap_ms: f64,
186    /// [`LETTER_SETTLE_MS`], or the model's busy gap if longer.
187    settle_ms: f64,
188    /// Alpha is known to be off: a typed letter pressed alpha and its key
189    /// used it up, and no alpha press came since. Letters then skip reading
190    /// the annunciator and the settling wait.
191    alpha_spent: bool,
192    /// Errors from presses the machine refused, for the host to report.
193    errors: Vec<Error>,
194}
195
196impl KeyQueue {
197    /// An empty queue for `model`'s keys and typing rules.
198    pub fn new(model: Model) -> Self {
199        Self {
200            names: layout::layout(model).iter().map(|k| k.name).collect(),
201            typing: skins::typing(model),
202            letters: skins::letters(model),
203            active: Vec::new(),
204            pending: VecDeque::new(),
205            last_release_ms: f64::NEG_INFINITY,
206            last_released: None,
207            repeat_gap_ms: repeat_gap_ms(model),
208            started: 0,
209            busy_gap_ms: busy_gap_ms(model),
210            settle_ms: busy_gap_ms(model).max(LETTER_SETTLE_MS),
211            alpha_spent: false,
212            errors: Vec::new(),
213        }
214    }
215
216    fn name(&self, name: &str) -> Option<&'static str> {
217        self.names.iter().copied().find(|&n| n == name)
218    }
219
220    /// Whether the model has a key called `name` (its drawn layout).
221    pub fn has_key(&self, name: &str) -> bool {
222        self.name(name).is_some()
223    }
224
225    /// Keys are down or presses are queued: the run must keep its slices
226    /// short and pump.
227    pub fn busy(&self) -> bool {
228        !self.active.is_empty() || !self.pending.is_empty()
229    }
230
231    /// A key the user pressed is down and not yet released: its hold
232    /// must run at 1x, or a tap at a higher speed reads as a long hold
233    /// (the 42S shows NULL after about a second).
234    pub fn held(&self) -> bool {
235        self.active.iter().any(|p| !p.up)
236    }
237
238    /// Queue a press of `name` (held until [`KeyQueue::release`]); false
239    /// if the model has no such key.
240    pub fn press(&mut self, name: &str) -> bool {
241        let Some(name) = self.name(name) else {
242            return false;
243        };
244        self.pending.push_back(Item::Press(Press {
245            name,
246            up: false,
247            down_at: 0.0,
248            typed: false,
249        }));
250        true
251    }
252
253    /// Queue a press of `name` held until [`KeyQueue::release`], after a
254    /// tap of shift key `shift` unless that shift is on when the press's
255    /// turn comes: decided then, not now, so a shift still queued or one
256    /// a queued key will use up counts. False if the model has no such key
257    /// or `shift` is not one of its shift keys.
258    pub fn press_shifted(&mut self, name: &str, shift: &str) -> bool {
259        let (Some(name), Some(shift)) = (self.name(name), self.name(shift)) else {
260            return false;
261        };
262        if !SHIFT_KEYS.contains(&shift) {
263            return false;
264        }
265        self.pending.push_back(Item::Shifted {
266            shift,
267            press: Press {
268                name,
269                up: false,
270                down_at: 0.0,
271                typed: false,
272            },
273        });
274        true
275    }
276
277    /// Queue `ch` typed through the calculator's alpha mode; false if the
278    /// model has no key for it.
279    pub fn type_letter(&mut self, ch: char) -> bool {
280        let upper = ch.to_ascii_uppercase();
281        if self.typing.is_none() || !self.letters.iter().any(|&(c, _)| c == upper) {
282            return false;
283        }
284        self.pending.push_back(Item::Letter {
285            letter: upper,
286            lower: ch != upper,
287        });
288        true
289    }
290
291    /// Queue full presses of `names`, one after the other (unknown names
292    /// are skipped).
293    pub fn type_keys(&mut self, names: &[&str]) {
294        for n in names {
295            if let Some(name) = self.name(n) {
296                self.pending.push_back(Item::Press(Press {
297                    name,
298                    up: true,
299                    down_at: 0.0,
300                    typed: true,
301                }));
302            }
303        }
304    }
305
306    /// Release the newest press of `name` that the user still holds.
307    pub fn release(&mut self, name: &str) {
308        let queued = self.pending.iter_mut().rev().filter_map(|i| match i {
309            Item::Press(p) | Item::Shifted { press: p, .. } => Some(p),
310            Item::Letter { .. } => None,
311        });
312        if let Some(p) = queued
313            .chain(self.active.iter_mut().rev())
314            .find(|p| p.name == name && !p.up)
315        {
316            p.up = true;
317        }
318    }
319
320    /// Release every held key once it has been down long enough (the
321    /// window lost the focus).
322    pub fn release_held(&mut self) {
323        for p in &mut self.active {
324            p.up = true;
325        }
326        for i in &mut self.pending {
327            if let Item::Press(p) | Item::Shifted { press: p, .. } = i {
328                p.up = true;
329            }
330        }
331    }
332
333    /// Drop the queue and forget every key; the machine's keys stay as
334    /// they are ([`Emulator::release_keys`] releases both).
335    pub fn clear(&mut self) {
336        self.active.clear();
337        self.pending.clear();
338        self.last_release_ms = f64::NEG_INFINITY;
339        self.last_released = None;
340        self.alpha_spent = false;
341    }
342
343    /// The keys down now, for the view.
344    pub fn down(&self) -> Vec<&'static str> {
345        let mut v: Vec<&'static str> = self.active.iter().map(|p| p.name).collect();
346        v.dedup();
347        v
348    }
349
350    /// Presses the machine took since the queue was made (each key of a
351    /// typed letter counts, alpha too).
352    pub fn presses_started(&self) -> u64 {
353        self.started
354    }
355
356    /// Errors collected since the last call.
357    pub fn take_errors(&mut self) -> Vec<Error> {
358        std::mem::take(&mut self.errors)
359    }
360
361    /// The presses that type a queued letter now: the letter's key after
362    /// the alpha key, unless alpha is already on (one alpha press lasts for
363    /// the next key; two lock it on the 48 and 49G, cancel it on the
364    /// others); a lowercase letter adds the model's shift, before or after
365    /// alpha as the model wants. Alpha is read from the annunciator, except
366    /// right after a letter this queue pressed alpha for: that alpha was
367    /// spent by its key.
368    fn expand_letter(&mut self, kb: &impl Keyboard, letter: char, lower: bool) -> Vec<Item> {
369        let Some(t) = self.typing else {
370            return Vec::new();
371        };
372        let Some(&(_, key)) = self.letters.iter().find(|&&(c, _)| c == letter) else {
373            return Vec::new();
374        };
375        let mut seq = Vec::new();
376        if t.direct {
377            // The 28S: the letter's own key; LC switches lowercase on
378            // before it and off after it.
379            if lower {
380                seq.extend([t.lower_shift, key, t.lower_shift]);
381            } else {
382                seq.push(key);
383            }
384            return self.presses(seq);
385        }
386        let alpha_on = !self.alpha_spent && kb.alpha_on();
387        if t.shift_first && lower {
388            seq.push(t.lower_shift);
389        }
390        if !alpha_on {
391            seq.push(t.alpha);
392        }
393        if !t.shift_first && lower {
394            seq.push(t.lower_shift);
395        }
396        seq.push(key);
397        self.alpha_spent = !alpha_on;
398        self.presses(seq)
399    }
400
401    /// Full presses of the keys `seq` names (unknown names skipped).
402    fn presses(&self, seq: Vec<&str>) -> Vec<Item> {
403        seq.into_iter()
404            .filter_map(|n| self.name(n))
405            .map(|name| {
406                Item::Press(Press {
407                    name,
408                    up: true,
409                    down_at: 0.0,
410                    typed: true,
411                })
412            })
413            .collect()
414    }
415
416    /// Release keys held long enough, then start queued presses.
417    pub fn pump(&mut self, kb: &mut impl Keyboard) {
418        let now = kb.now_ms();
419        let mut released = false;
420        let mut last = self.last_released;
421        self.active.retain(|p| {
422            if p.up && now - p.down_at >= MIN_HOLD_MS {
423                kb.up(p.name);
424                last = Some(p.name);
425                released = true;
426                false
427            } else {
428                true
429            }
430        });
431        if released {
432            self.last_release_ms = now;
433            self.last_released = last;
434        }
435        let idle = kb.idle();
436        while let Some(head) = self.pending.front() {
437            // Wait while a fast-typed key is still on its way up; a key the
438            // user keeps holding (ON for a chord) does not block.
439            if self.active.iter().any(|p| p.up) {
440                break;
441            }
442            let since = now - self.last_release_ms;
443            if since < GAP_MS || (!idle && since < self.busy_gap_ms) {
444                break;
445            }
446            if let &Item::Letter { letter, lower } = head {
447                // A letter waits for an empty keyboard, and, unless it
448                // follows a letter whose alpha this queue pressed, for the
449                // ROM to settle the alpha annunciator it reads.
450                if !self.active.is_empty() {
451                    break;
452                }
453                if !self.alpha_spent && !idle && since < self.settle_ms {
454                    break;
455                }
456                self.pending.pop_front();
457                for item in self.expand_letter(kb, letter, lower).into_iter().rev() {
458                    self.pending.push_front(item);
459                }
460                continue;
461            }
462            if let &Item::Shifted { shift, .. } = head {
463                // As a letter: the shift annunciator is read with every key
464                // before it played and settled (a shift queued before it
465                // lit it, a key before it used it up).
466                if !self.active.is_empty() || (!idle && since < self.settle_ms) {
467                    break;
468                }
469                let Some(Item::Shifted { press, .. }) = self.pending.pop_front() else {
470                    continue;
471                };
472                self.pending.push_front(Item::Press(press));
473                if !kb.shift_on(shift) {
474                    self.pending.push_front(Item::Press(Press {
475                        name: shift,
476                        up: true,
477                        down_at: 0.0,
478                        typed: true,
479                    }));
480                }
481                continue;
482            }
483            if let Item::Press(p) = head
484                && Some(p.name) == self.last_released
485                && since < self.repeat_gap_ms
486            {
487                break;
488            }
489            let Some(Item::Press(mut p)) = self.pending.pop_front() else {
490                continue;
491            };
492            if self.typing.is_some_and(|t| p.name == t.alpha) && !p.typed {
493                self.alpha_spent = false;
494            }
495            if let Some(o) = self.active.iter_mut().find(|o| o.name == p.name) {
496                // Same key still down (held): count this press as the same one.
497                if p.up {
498                    o.up = true;
499                }
500                continue;
501            }
502            if let Err(e) = kb.down(p.name) {
503                self.errors.push(e);
504                continue;
505            }
506            p.down_at = now;
507            self.started += 1;
508            self.active.push(p);
509        }
510    }
511}
512
513/// Packed LCD bytes per row of `width` pixels.
514pub fn packed_row_bytes(width: usize) -> usize {
515    width.div_ceil(8)
516}
517
518/// The pixels packed one bit each, row-major from the top-left, each row
519/// starting on a byte, the leftmost pixel in the most significant bit,
520/// 1 = dark (`web/protocol.md`, `frame`).
521pub fn pack_bits(rows: &[Vec<bool>]) -> Vec<u8> {
522    let w = rows.first().map_or(LCD_WIDTH, Vec::len);
523    let mut out = vec![0u8; packed_row_bytes(w) * rows.len()];
524    for (y, row) in rows.iter().enumerate() {
525        for (x, &on) in row.iter().enumerate() {
526            if on {
527                out[y * packed_row_bytes(w) + x / 8] |= 0x80 >> (x % 8);
528            }
529        }
530    }
531    out
532}
533
534/// Standard base64 with padding.
535pub fn base64(bytes: &[u8]) -> String {
536    const ALPHABET: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
537    let mut out = String::with_capacity(bytes.len().div_ceil(3) * 4);
538    for chunk in bytes.chunks(3) {
539        let b = [
540            chunk[0],
541            chunk.get(1).copied().unwrap_or(0),
542            chunk.get(2).copied().unwrap_or(0),
543        ];
544        let n = (u32::from(b[0]) << 16) | (u32::from(b[1]) << 8) | u32::from(b[2]);
545        for i in 0..4 {
546            if i <= chunk.len() {
547                out.push(char::from(ALPHABET[(n >> (18 - 6 * i)) as usize & 63]));
548            } else {
549                out.push('=');
550            }
551        }
552    }
553    out
554}
555
556/// Decode standard base64 (padding optional, no whitespace): the JSON form
557/// of the protocol's *bytes* fields.
558pub fn base64_decode(s: &str) -> crate::Result<Vec<u8>> {
559    fn value(c: u8) -> Option<u32> {
560        Some(u32::from(match c {
561            b'A'..=b'Z' => c - b'A',
562            b'a'..=b'z' => c - b'a' + 26,
563            b'0'..=b'9' => c - b'0' + 52,
564            b'+' => 62,
565            b'/' => 63,
566            _ => return None,
567        }))
568    }
569    let s = s.trim_end_matches('=').as_bytes();
570    if s.len() % 4 == 1 {
571        return Err("bad base64 length".into());
572    }
573    let mut out = Vec::with_capacity(s.len() * 3 / 4);
574    for chunk in s.chunks(4) {
575        let mut n = 0u32;
576        for (i, &c) in chunk.iter().enumerate() {
577            n |= value(c).ok_or("bad base64 character")? << (18 - 6 * i);
578        }
579        let bytes = n.to_be_bytes();
580        out.extend_from_slice(&bytes[1..chunk.len()]);
581    }
582    Ok(out)
583}
584
585/// Serialize bytes as base64 (`web/protocol.md`: `frame`'s `pixels`,
586/// `serial`'s `bytes`).
587pub(crate) fn as_base64<S: serde::Serializer>(bytes: &[u8], s: S) -> Result<S::Ok, S::Error> {
588    s.serialize_str(&base64(bytes))
589}
590
591/// The `frame` event (`web/protocol.md`): the display, sent when it
592/// changed. Serializes as `{"type":"frame","width","height","pixels",
593/// "annunciators","contrast","contrastRange","contrastDefault"}`.
594#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize)]
595#[serde(tag = "type", rename = "frame", rename_all = "camelCase")]
596pub struct Frame {
597    /// Pixels per row: 131.
598    pub width: usize,
599    /// Rows: 64, or 16 on the 42S.
600    pub height: usize,
601    /// The pixels packed one bit each ([`pack_bits`]); base64 in JSON.
602    #[serde(serialize_with = "as_base64")]
603    pub pixels: Vec<u8>,
604    /// The annunciators.
605    pub annunciators: AnnunciatorFlags,
606    /// Raw 5-bit contrast, 0-31, higher is darker.
607    pub contrast: u8,
608    /// The model's usable contrast range, `[low, high]`.
609    pub contrast_range: [u8; 2],
610    /// The contrast the ROM sets at power-on.
611    pub contrast_default: u8,
612}
613
614/// The `keys` event (`web/protocol.md`): the keys down, sent when they
615/// changed. Serializes as `{"type":"keys","down":[names]}`.
616#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize)]
617#[serde(tag = "type", rename = "keys")]
618pub struct KeysDown {
619    /// Script names of the keys down.
620    pub down: Vec<&'static str>,
621}
622
623/// The `menu` event (`web/protocol.md`): the six menu keys the screen
624/// shows (48SX, 48GX, 49G; the 42S, the Pioneers and the 28S), sent when
625/// they changed. Serializes as
626/// `{"type":"menu","keys":[{label, command?, submenu?, type?} | null, ...]}`,
627/// `keys` null where they are not known.
628#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize)]
629#[serde(tag = "type", rename = "menu")]
630pub struct MenuKeys {
631    /// The keys A-F (F1-F6), `None` for a blank one.
632    pub keys: Option<Vec<Option<saturnus_objects::softkeys::ShownKey>>>,
633}
634
635/// The model that runs `rom`, preferring `preferred`: a 2 MB file fits
636/// both the 49G (packed) and the 39G/40G (unpacked, every byte a nibble);
637/// the bytes tell which ([`crate::romid::fitting_models`]). `preferred`
638/// when nothing fits (the boot then reports the size).
639pub fn model_for_rom(rom: &[u8], preferred: Model) -> Model {
640    let fits = crate::romid::fitting_models(rom);
641    if fits.contains(&preferred) {
642        return preferred;
643    }
644    fits.first().copied().unwrap_or(preferred)
645}
646
647impl Emulator {
648    /// One slice of at most `left_ms` emulated ms: a sleeping CPU with no
649    /// keys to time skips to its next timer event in one step; with `keys`
650    /// the queue is fed afterwards. Returns the emulated ms run.
651    pub fn run_slice(&mut self, left_ms: f64, keys: bool) -> crate::Result<f64> {
652        if !left_ms.is_finite() || left_ms <= 0.0 {
653            return Ok(0.0);
654        }
655        let timed = keys && self.queue.busy();
656        let idle = if timed { None } else { self.idle_ms() };
657        let step = left_ms.min(idle.filter(|&i| i > SLICE_MS).unwrap_or(SLICE_MS));
658        self.run_ms(step)?;
659        if keys {
660            self.queue.pump(&mut self.machine);
661        }
662        Ok(step)
663    }
664
665    /// Feed the key queue now (after a command added to it).
666    pub fn pump(&mut self) {
667        self.queue.pump(&mut self.machine);
668    }
669
670    /// The key queue.
671    pub fn queue(&mut self) -> &mut KeyQueue {
672        &mut self.queue
673    }
674
675    /// Release every key at once: the machine's keyboard (matrix and ON)
676    /// and the key queue (held presses, presses and letters waiting, with
677    /// no minimum hold), as after a reset, a state load or before a
678    /// script. The one way to let go of everything; [`KeyQueue::release_held`]
679    /// is the gentle one (the window lost the focus).
680    pub fn release_keys(&mut self) {
681        self.machine.release_all_keys();
682        self.queue.clear();
683    }
684
685    /// The `frame` event if the display changed since the last one
686    /// (pixels, annunciators or contrast), else `None`.
687    pub fn frame_if_changed(&mut self) -> Option<Frame> {
688        let fb = self.machine.framebuffer();
689        let model = self.machine.model();
690        let range = model.contrast_range();
691        let frame = Frame {
692            width: fb.pixels.width(),
693            height: fb.pixels.pixels.len(),
694            pixels: pack_bits(&fb.pixels.pixels),
695            annunciators: AnnunciatorFlags(fb.annunciators),
696            contrast: fb.contrast,
697            contrast_range: [*range.start(), *range.end()],
698            contrast_default: model.default_contrast(),
699        };
700        if self.shown.as_ref() == Some(&frame) {
701            return None;
702        }
703        self.shown = Some(frame.clone());
704        Some(frame)
705    }
706
707    /// Forget what was shown, so the next [`Emulator::frame_if_changed`]
708    /// and [`Emulator::keys_if_changed`] send their events (a new view
709    /// subscribed, a state was loaded).
710    pub fn reshow(&mut self) {
711        self.shown = None;
712        self.shown_keys = None;
713        self.menu_seen = None;
714        self.shown_menu = None;
715        self.menu_dirty = true;
716        self.menu_force = true;
717    }
718
719    /// The `keys` event if the keys down changed since the last one, else
720    /// `None`.
721    pub fn keys_if_changed(&mut self) -> Option<KeysDown> {
722        let down = self.queue.down();
723        if self.shown_keys.as_deref() == Some(down.as_slice()) {
724            return None;
725        }
726        self.shown_keys = Some(down.clone());
727        Some(KeysDown { down })
728    }
729}
730
731impl Emulator {
732    /// Queue a press of `name`, held until `release(name)`; false if the
733    /// model has no such key. Takes effect at the next `pump`.
734    pub fn press(&mut self, name: &str) -> bool {
735        self.queue.press(name)
736    }
737
738    /// Queue a press of `name` after a tap of shift key `shift`, unless
739    /// that shift is on when it plays ([`KeyQueue::press_shifted`]); false
740    /// if the model has no such key or shift.
741    pub fn press_shifted(&mut self, name: &str, shift: &str) -> bool {
742        self.queue.press_shifted(name, shift)
743    }
744
745    /// Whether the model has a key called `name`.
746    pub fn has_key(&self, name: &str) -> bool {
747        self.queue.has_key(name)
748    }
749
750    /// Release the newest held press of `name` (at the next `pump`).
751    pub fn release(&mut self, name: &str) {
752        self.queue.release(name);
753    }
754
755    /// Release every held key once it was down long enough.
756    pub fn release_held(&mut self) {
757        self.queue.release_held();
758    }
759
760    /// Queue the first character of `ch` typed through alpha mode; false
761    /// if the model has no key for it.
762    pub fn type_letter(&mut self, ch: &str) -> bool {
763        ch.chars().next().is_some_and(|c| self.queue.type_letter(c))
764    }
765
766    /// Queue full presses of the space-separated key `names`.
767    pub fn type_keys(&mut self, names: &str) {
768        let names: Vec<&str> = names.split_whitespace().collect();
769        self.queue.type_keys(&names);
770    }
771
772    /// Keys are down or queued: run in short slices.
773    pub fn keys_busy(&self) -> bool {
774        self.queue.busy()
775    }
776
777    /// A key the user pressed is still down ([`KeyQueue::held`]).
778    pub fn keys_held(&self) -> bool {
779        self.queue.held()
780    }
781
782    /// Errors from refused key presses since the last call.
783    pub fn take_errors(&mut self) -> Vec<Error> {
784        self.queue.take_errors()
785    }
786}
787
788#[cfg(test)]
789mod tests {
790    use super::*;
791
792    /// A keyboard that records presses; time and idleness are set by hand.
793    /// Its shift annunciators follow the keys as a ROM's do: a shift key
794    /// turns its shift on (the other off), again off; any other key uses it
795    /// up.
796    #[derive(Default)]
797    struct Fake {
798        now: f64,
799        idle: bool,
800        /// The ROM stays awake this long after each key goes up.
801        busy_after_up: f64,
802        last_up: f64,
803        /// Keys pressed while the ROM was awake (it may drop them).
804        pressed_busy: Vec<String>,
805        /// When each key went down.
806        down_at: Vec<f64>,
807        alpha: bool,
808        left: bool,
809        right: bool,
810        log: Vec<String>,
811    }
812
813    impl Keyboard for Fake {
814        fn now_ms(&self) -> f64 {
815            self.now
816        }
817        fn idle(&self) -> bool {
818            self.idle && self.now >= self.last_up + self.busy_after_up
819        }
820        fn alpha_on(&self) -> bool {
821            self.alpha
822        }
823        fn shift_on(&self, shift: &str) -> bool {
824            match shift {
825                "rightshift" => self.right,
826                "leftshift" => self.left,
827                _ => self.left || self.right,
828            }
829        }
830        fn down(&mut self, name: &str) -> crate::Result<()> {
831            self.log.push(format!("+{name}"));
832            self.down_at.push(self.now);
833            if !self.idle() {
834                self.pressed_busy.push(name.to_string());
835            }
836            match name {
837                "leftshift" | "shift" => (self.left, self.right) = (!self.left, false),
838                "rightshift" => (self.left, self.right) = (false, !self.right),
839                _ => (self.left, self.right) = (false, false),
840            }
841            Ok(())
842        }
843        fn up(&mut self, name: &str) {
844            self.log.push(format!("-{name}"));
845            self.last_up = self.now;
846        }
847    }
848
849    /// Run the fake in 10 ms steps for `ms`, pumping after each.
850    fn run(q: &mut KeyQueue, kb: &mut Fake, ms: f64) {
851        let end = kb.now + ms;
852        while kb.now < end {
853            kb.now += 10.0;
854            q.pump(kb);
855        }
856    }
857
858    #[test]
859    fn a_press_is_held_at_least_min_hold() {
860        let mut q = KeyQueue::new(Model::Hp48sx);
861        let mut kb = Fake {
862            idle: true,
863            ..Fake::default()
864        };
865        assert!(q.press("enter"));
866        assert!(!q.press("apps"), "a 49G key on a 48SX");
867        q.pump(&mut kb);
868        assert_eq!(kb.log, ["+enter"]);
869        assert_eq!(q.down(), ["enter"]);
870        q.release("enter");
871        kb.now = 50.0;
872        q.pump(&mut kb);
873        assert_eq!(kb.log, ["+enter"], "released before 60 ms");
874        kb.now = 60.0;
875        q.pump(&mut kb);
876        assert_eq!(kb.log, ["+enter", "-enter"]);
877        assert!(!q.busy());
878    }
879
880    #[test]
881    fn queued_presses_wait_for_the_gap_and_a_busy_rom() {
882        let mut q = KeyQueue::new(Model::Hp48sx);
883        let mut kb = Fake::default();
884        q.type_keys(&["1", "2"]);
885        q.pump(&mut kb);
886        assert_eq!(kb.log, ["+1"]);
887        // Busy ROM: the next press waits the 48SX's busy gap after the release at 60.
888        run(&mut q, &mut kb, 50.0 + busy_gap_ms(Model::Hp48sx));
889        assert_eq!(kb.log, ["+1", "-1"]);
890        run(&mut q, &mut kb, 20.0);
891        assert_eq!(kb.log, ["+1", "-1", "+2"]);
892        // Idle ROM: only GAP_MS.
893        let mut q = KeyQueue::new(Model::Hp48sx);
894        let mut kb = Fake {
895            idle: true,
896            ..Fake::default()
897        };
898        q.type_keys(&["1", "2"]);
899        // Down at 10, up at 70, the next one 30 ms later.
900        run(&mut q, &mut kb, 100.0);
901        assert_eq!(kb.log, ["+1", "-1", "+2"]);
902    }
903
904    #[test]
905    fn a_busy_rom_takes_keys_at_its_models_rate() {
906        // A program keeps the ROM awake: each queued key is held 60 ms and
907        // the next waits the model's busy gap, so the 39G (which sleeps
908        // within 250 ms of a key) takes keys every 360 ms, about 2.8 a
909        // second, and the 48SX, which may stay awake 750 ms, every 910 ms.
910        for (model, every) in [
911            (Model::Hp39g, 360.0),
912            (Model::Hp42s, 360.0),
913            (Model::Hp48sx, 910.0),
914        ] {
915            let mut q = KeyQueue::new(model);
916            let mut kb = Fake::default();
917            q.type_keys(&["1", "2", "3", "4"]);
918            run(&mut q, &mut kb, 5000.0);
919            assert_eq!(downs(&kb), ["1", "2", "3", "4"], "{model:?}");
920            let gaps: Vec<f64> = kb.down_at.windows(2).map(|w| w[1] - w[0]).collect();
921            assert_eq!(gaps, [every; 3], "{model:?}");
922        }
923    }
924
925    /// The keys pressed, in order.
926    fn downs(kb: &Fake) -> Vec<&str> {
927        kb.log.iter().filter_map(|s| s.strip_prefix('+')).collect()
928    }
929
930    #[test]
931    fn two_quick_shifted_presses_each_get_their_shift() {
932        // Two Ctrl+clicks on √x in quick succession: both are queued before
933        // the first plays, and the first one's shift is spent by its key,
934        // so the second taps the shift again.
935        let mut q = KeyQueue::new(Model::Hp48sx);
936        let mut kb = Fake {
937            idle: true,
938            ..Fake::default()
939        };
940        assert!(q.press_shifted("sqrt", "leftshift"));
941        q.pump(&mut kb);
942        q.release("sqrt");
943        assert!(q.press_shifted("sqrt", "leftshift"));
944        q.release("sqrt");
945        run(&mut q, &mut kb, 1000.0);
946        assert_eq!(downs(&kb), ["leftshift", "sqrt", "leftshift", "sqrt"]);
947        assert!(!q.busy());
948    }
949
950    #[test]
951    fn quick_shifted_presses_wait_out_the_roms_long_key_wait() {
952        // The 48SX ROM, depending on its timer's phase, stays awake about
953        // 520 ms after a key goes up and may drop a key pressed then: two
954        // quick Ctrl+clicks lost the second shift and gave √x for x²
955        // (the page test under load). Every press waits for the ROM.
956        let mut q = KeyQueue::new(Model::Hp48sx);
957        let mut kb = Fake {
958            idle: true,
959            busy_after_up: 520.0,
960            last_up: f64::NEG_INFINITY,
961            ..Fake::default()
962        };
963        assert!(q.press_shifted("sqrt", "leftshift"));
964        q.release("sqrt");
965        assert!(q.press_shifted("sqrt", "leftshift"));
966        q.release("sqrt");
967        run(&mut q, &mut kb, 5000.0);
968        assert_eq!(downs(&kb), ["leftshift", "sqrt", "leftshift", "sqrt"]);
969        assert_eq!(
970            kb.pressed_busy,
971            Vec::<String>::new(),
972            "no key pressed while the ROM was awake"
973        );
974        assert!(!q.busy());
975    }
976
977    #[test]
978    fn a_shifted_press_after_a_queued_shift_does_not_tap_it_again() {
979        // A click on the left shift, then at once a Ctrl+click: the shift
980        // is still queued, then on when the shifted press plays.
981        let mut q = KeyQueue::new(Model::Hp48sx);
982        let mut kb = Fake {
983            idle: true,
984            ..Fake::default()
985        };
986        assert!(q.press("leftshift"));
987        q.release("leftshift");
988        assert!(q.press_shifted("sqrt", "leftshift"));
989        q.release("sqrt");
990        run(&mut q, &mut kb, 1000.0);
991        assert_eq!(downs(&kb), ["leftshift", "sqrt"]);
992        // The right shift on, a left-shifted press: the left one is tapped.
993        let mut q = KeyQueue::new(Model::Hp48sx);
994        let mut kb = Fake {
995            idle: true,
996            right: true,
997            ..Fake::default()
998        };
999        assert!(q.press_shifted("sqrt", "leftshift"));
1000        q.release("sqrt");
1001        run(&mut q, &mut kb, 1000.0);
1002        assert_eq!(downs(&kb), ["leftshift", "sqrt"]);
1003    }
1004
1005    #[test]
1006    fn a_shifted_press_is_held_until_released_and_checks_its_names() {
1007        let mut q = KeyQueue::new(Model::Hp39g);
1008        let mut kb = Fake {
1009            idle: true,
1010            ..Fake::default()
1011        };
1012        assert!(
1013            !q.press_shifted("enter", "leftshift"),
1014            "no left shift on a 39G"
1015        );
1016        assert!(!q.press_shifted("enter", "alpha"), "not a shift key");
1017        assert!(!q.press_shifted("bogus", "shift"));
1018        assert!(q.press_shifted("enter", "shift"));
1019        run(&mut q, &mut kb, 500.0);
1020        assert_eq!(downs(&kb), ["shift", "enter"]);
1021        assert_eq!(q.down(), ["enter"], "held while the button is");
1022        q.release("enter");
1023        run(&mut q, &mut kb, 100.0);
1024        assert!(!q.busy());
1025        // One shift: either annunciator counts as on.
1026        let mut q = KeyQueue::new(Model::Hp39g);
1027        let mut kb = Fake {
1028            idle: true,
1029            right: true,
1030            ..Fake::default()
1031        };
1032        assert!(q.press_shifted("enter", "shift"));
1033        q.release("enter");
1034        run(&mut q, &mut kb, 500.0);
1035        assert_eq!(downs(&kb), ["enter"]);
1036    }
1037
1038    #[test]
1039    fn letters_press_alpha_then_skip_it_while_spent() {
1040        let mut q = KeyQueue::new(Model::Hp48sx);
1041        let mut kb = Fake {
1042            idle: true,
1043            ..Fake::default()
1044        };
1045        assert!(q.type_letter('A'));
1046        assert!(q.type_letter('b'));
1047        assert!(!q.type_letter('!'));
1048        run(&mut q, &mut kb, 2000.0);
1049        let downs: Vec<&str> = kb.log.iter().filter_map(|s| s.strip_prefix('+')).collect();
1050        // A = alpha + key; b = alpha + left shift + key (shift after alpha).
1051        let a = skins::letters(Model::Hp48sx)
1052            .into_iter()
1053            .find(|&(c, _)| c == 'A')
1054            .map(|(_, k)| k)
1055            .unwrap();
1056        let b = skins::letters(Model::Hp48sx)
1057            .into_iter()
1058            .find(|&(c, _)| c == 'B')
1059            .map(|(_, k)| k)
1060            .unwrap();
1061        assert_eq!(downs, ["alpha", a, "alpha", "leftshift", b]);
1062        assert!(!q.busy());
1063    }
1064
1065    /// The 28S has a key per letter: no alpha press, even with alpha on;
1066    /// a lowercase letter is LC, the key, LC.
1067    #[test]
1068    fn hp28s_letters_are_keys_of_their_own() {
1069        let mut q = KeyQueue::new(Model::Hp28s);
1070        let mut kb = Fake {
1071            idle: true,
1072            alpha: true,
1073            ..Fake::default()
1074        };
1075        assert!(q.type_letter('A'));
1076        assert!(q.type_letter('z'));
1077        assert!(!q.type_letter('1'));
1078        run(&mut q, &mut kb, 2000.0);
1079        let downs: Vec<&str> = kb.log.iter().filter_map(|s| s.strip_prefix('+')).collect();
1080        assert_eq!(downs, ["lettera", "lc", "letterz", "lc"]);
1081        assert!(!q.busy());
1082    }
1083
1084    #[test]
1085    fn aplet_models_shift_before_alpha_and_respect_alpha_on() {
1086        let mut q = KeyQueue::new(Model::Hp38g);
1087        let mut kb = Fake {
1088            idle: true,
1089            alpha: true,
1090            ..Fake::default()
1091        };
1092        q.type_letter('c');
1093        run(&mut q, &mut kb, 1000.0);
1094        let downs: Vec<&str> = kb.log.iter().filter_map(|s| s.strip_prefix('+')).collect();
1095        // Alpha already on: shift, then the key, no alpha press.
1096        assert_eq!(downs.len(), 2);
1097        assert_eq!(downs[0], "shift");
1098    }
1099
1100    #[test]
1101    fn release_held_lets_go_of_user_presses() {
1102        let mut q = KeyQueue::new(Model::Hp48sx);
1103        let mut kb = Fake {
1104            idle: true,
1105            ..Fake::default()
1106        };
1107        q.press("on");
1108        q.pump(&mut kb);
1109        q.release_held();
1110        run(&mut q, &mut kb, 100.0);
1111        assert_eq!(kb.log, ["+on", "-on"]);
1112    }
1113
1114    #[test]
1115    fn packs_bits_msb_first_per_row() {
1116        let mut rows = vec![vec![false; LCD_WIDTH]; 2];
1117        rows[0][0] = true;
1118        rows[0][9] = true;
1119        rows[1][130] = true;
1120        let p = pack_bits(&rows);
1121        assert_eq!(p.len(), 2 * 17);
1122        assert_eq!(p[0], 0x80);
1123        assert_eq!(p[1], 0x40);
1124        assert_eq!(p[17 + 16], 0x20);
1125        assert_eq!(p.iter().map(|b| b.count_ones()).sum::<u32>(), 3);
1126    }
1127
1128    #[test]
1129    fn base64_matches_rfc4648() {
1130        assert_eq!(base64(b""), "");
1131        assert_eq!(base64(b"f"), "Zg==");
1132        assert_eq!(base64(b"fo"), "Zm8=");
1133        assert_eq!(base64(b"foo"), "Zm9v");
1134        assert_eq!(base64(b"foobar"), "Zm9vYmFy");
1135        assert_eq!(base64(&[0xff, 0xfe]), "//4=");
1136        for n in 0..40 {
1137            let bytes: Vec<u8> = (0..n).map(|i| (i * 37 + 11) as u8).collect();
1138            assert_eq!(base64_decode(&base64(&bytes)).unwrap(), bytes);
1139        }
1140        assert_eq!(base64_decode("aGk").unwrap(), b"hi");
1141        assert!(base64_decode("a").is_err());
1142        assert!(base64_decode("a*bc").is_err());
1143    }
1144
1145    #[test]
1146    fn rom_picks_the_model() {
1147        let two = 2 * 1024 * 1024;
1148        assert_eq!(
1149            model_for_rom(&vec![0u8; 256 * 1024], Model::Hp49g),
1150            Model::Hp48sx
1151        );
1152        assert_eq!(
1153            model_for_rom(&vec![0u8; 256 * 1024], Model::Hp48sx),
1154            Model::Hp48sx
1155        );
1156        // 2 MB of nibbles: an unpacked 39G/40G, not a 49G.
1157        assert_eq!(model_for_rom(&vec![0u8; two], Model::Hp49g), Model::Hp39g);
1158        assert_eq!(model_for_rom(&vec![0u8; two], Model::Hp40g), Model::Hp40g);
1159        // 2 MB with full bytes: the 49G.
1160        assert_eq!(
1161            model_for_rom(&vec![0xffu8; two], Model::Hp39g),
1162            Model::Hp49g
1163        );
1164        assert_eq!(model_for_rom(&[0u8; 1000], Model::Hp38g), Model::Hp38g);
1165    }
1166
1167    #[test]
1168    fn frames_and_keys_only_when_changed() {
1169        let mut emu = Emulator::new(Model::Hp48sx, &vec![0u8; 256 * 1024]).unwrap();
1170        let f = serde_json::to_string(&emu.frame_if_changed().unwrap()).unwrap();
1171        assert!(
1172            f.starts_with("{\"type\":\"frame\",\"width\":131,\"height\":64,\"pixels\":\"AAAA"),
1173            "{f}"
1174        );
1175        assert!(f.contains(",\"annunciators\":{\"leftshift\":false,"), "{f}");
1176        assert!(
1177            f.ends_with(",\"contrastRange\":[3,19],\"contrastDefault\":11}"),
1178            "{f}"
1179        );
1180        assert!(emu.frame_if_changed().is_none());
1181        emu.reshow();
1182        assert!(emu.frame_if_changed().is_some());
1183        let keys = |emu: &mut Emulator| {
1184            emu.keys_if_changed()
1185                .map(|k| serde_json::to_string(&k).unwrap())
1186        };
1187        assert_eq!(
1188            keys(&mut emu).as_deref(),
1189            Some("{\"type\":\"keys\",\"down\":[]}")
1190        );
1191        assert!(emu.keys_if_changed().is_none());
1192        emu.queue().press("enter");
1193        emu.pump();
1194        assert_eq!(
1195            keys(&mut emu).as_deref(),
1196            Some("{\"type\":\"keys\",\"down\":[\"enter\"]}")
1197        );
1198    }
1199}