Skip to main content

saturnus_host/protocol/
mod.rs

1//! The front end's protocol (`web/protocol.md`) and its pacing, once for
2//! every host: [`Engine`] takes commands and gives replies and events,
3//! and runs the machine against a clock the host passes in. It has no
4//! clock, timer, thread or I/O of its own; a host is a thin driver around
5//! it:
6//!
7//! - feed it the page's messages ([`Engine::command`]) with the host's
8//!   [`Clock`];
9//! - after every call, deliver [`Engine::take_output`] in order (the events
10//!   a command caused come before its reply) and arm one timer for
11//!   [`Engine::deadline`], which calls [`Engine::timer`].
12//!
13//! The Web Worker (`web/worker.js`, through `saturnus-web`) drives it with
14//! `performance.now()` and `setTimeout`; the native machine thread
15//! (`saturnus-drive`'s runner, for the desktop app and `saturnus run`)
16//! with `Instant` and its channel's `recv_timeout`. What only one host has
17//! stays with it: files and dialogs natively, IndexedDB and the ROM slots
18//! in the browser, the native commands (`screen`, `info`, `model`,
19//! `peek`, `poke`, `keyScript`), which the runner serves around the engine
20//! ([`Engine::answer`], [`Engine::exclusive`]).
21//!
22//! Sends (`insert`, `run`, `replace`, `typeText`) and the writes to the
23//! user memory (`storeFile`, `fetchFile`, `purge`, `rename`, `createDir`,
24//! `changeDir`, `setFlag`, `storeText`, `copy`, `move`, `storeScreen`: a
25//! hidden Kermit transaction,
26//! [`crate::transfer`]) run in
27//! turns between other messages; meanwhile the commands in
28//! whose [`Policy`] says `refused_while_typing` are refused, `releaseAll` stops the send or
29//! the write, and a send of more than 12 characters, or any write, holds
30//! the frames, keys and errors until it ends.
31//!
32//! The page may also hold the emulated serial port itself (`serialOpen`,
33//! `serialWrite`, the `serial` event, `serialClose`): the transfer page
34//! talks to the calculator over it as over a cable. The port carries one
35//! conversation at a time, so while the page holds it the writes are
36//! refused, and while a write runs the page cannot take it.
37//!
38//! A host that keeps states ([`Engine::set_auto_save`]) gets the machine's
39//! state as [`Output::Save`] once it changed and settled (`protocol/autosave.rs`),
40//! and boots a model with the state it kept ([`Engine::boot_restoring`]).
41
42mod autosave;
43mod command;
44mod pacing;
45mod recover;
46mod watch;
47
48#[cfg(test)]
49mod tests;
50
51pub use autosave::DELAY_MS as AUTO_SAVE_MS;
52pub use command::{CommandKind, HttpEndpoint, Policy};
53pub use pacing::{LoopState, MAX_BEHIND_MS, Pacing, Speed};
54pub use watch::{EVENT_MS as MEMORY_EVENT_MS, LOOK_MS as MEMORY_LOOK_MS};
55
56use saturnus_core::{Machine, Model};
57use serde::Serialize;
58use serde_json::{Value, json};
59
60use crate::host::{Frame, KeysDown, base64_decode, model_for_rom};
61use crate::transfer::{MAX_FILE_BYTES, Op, Target};
62use crate::{Emulator, Error, Result};
63use autosave::AutoSave;
64use pacing::Loop;
65use recover::{Recover, Step};
66use watch::Watch;
67
68/// The protocol version.
69pub const VERSION: u64 = 1;
70/// Largest state accepted (`loadState`): the largest is the 49G's, 2.6 MB
71/// (its 2 MiB flash and 512 KiB RAM); 4 MiB leaves half again as much.
72pub const MAX_STATE_BYTES: usize = 4 * 1024 * 1024;
73/// Emulated ms one step of a send runs.
74pub const TYPING_STEP_MS: f64 = 20.0;
75/// Wall time a send may take in all, in ms (also the native key scripts').
76/// A `run` that reaches it after ENTER replies `running` instead.
77pub const WALL_LIMIT_MS: f64 = 30_000.0;
78/// Steps a `run` cut short after ENTER may take to finish (reading the
79/// line, closing the 49G's error box and waiting after it).
80const WAIT_END_STEPS: usize = 64;
81/// Most bytes waiting for the calculator's UART (`serialWrite`): at 9600
82/// baud it takes about 840 a second, so this is many packets ahead.
83pub const MAX_SERIAL_PENDING: usize = 16 * 1024;
84/// Why a write is refused while the page holds the serial port.
85pub const SERIAL_IN_USE: &str = "the serial port is in use (serialClose frees it)";
86/// Least wall time between two `serial` events while the machine computes
87/// in passes (a native host runs one every millisecond): about 10 bytes at
88/// 9600 baud, so a Kermit packet is two or three events, not a hundred.
89pub const SERIAL_EVENT_MS: f64 = 10.0;
90
91/// The host's clock: milliseconds from any fixed start, never going back.
92pub trait Clock {
93    /// Now, in ms.
94    fn now_ms(&self) -> f64;
95}
96
97/// The `status` event: sent whenever one of its fields changed.
98#[derive(Clone, Debug, PartialEq, Serialize)]
99#[serde(tag = "type", rename = "status", rename_all = "camelCase")]
100pub struct Status {
101    /// The booted model's name.
102    pub model: Option<&'static str>,
103    /// The ROM file's name.
104    pub rom_name: String,
105    /// The machine runs (booted, not paused, not halted).
106    pub running: bool,
107    /// Why the CPU stopped, or `None`.
108    pub halted: Option<String>,
109    /// The speed setting.
110    pub speed: Speed,
111    /// What the loop does.
112    #[serde(rename = "loop")]
113    pub loop_state: LoopState,
114    /// A long send holds the frames.
115    pub busy: bool,
116    /// A cold boot's "Try To Recover Memory?" (and the 49G's "Memory
117    /// Clear") is still being answered: the keyboard is not the user's
118    /// yet, and a send waits for the answer.
119    pub starting: bool,
120}
121
122/// The `error` event: a command without an `id` failed, or a key the
123/// machine refused.
124#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
125#[serde(tag = "type", rename = "error")]
126pub struct ErrorEvent {
127    /// For the user.
128    pub message: String,
129}
130
131/// The `memoryChanged` event.
132#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
133#[serde(tag = "type", rename = "memoryChanged")]
134pub struct MemoryChanged {}
135
136/// The `serial` event: bytes the calculator sent on its serial port while
137/// the page holds it (`serialOpen`); base64 in JSON.
138#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
139#[serde(tag = "type", rename = "serial")]
140pub struct SerialEvent {
141    /// The bytes, in the order they left the UART.
142    #[serde(serialize_with = "crate::host::as_base64")]
143    pub bytes: Vec<u8>,
144}
145
146/// An event for the page (`web/protocol.md`, "Events"); serializes as
147/// the protocol's JSON object.
148#[derive(Clone, Debug, PartialEq, Serialize)]
149#[serde(untagged)]
150pub enum Event {
151    /// `serial`.
152    Serial(SerialEvent),
153    /// `frame`.
154    Frame(Frame),
155    /// `keys`.
156    Keys(KeysDown),
157    /// `status`.
158    Status(Status),
159    /// `error`.
160    Error(ErrorEvent),
161    /// `memoryChanged`.
162    MemoryChanged(MemoryChanged),
163    /// `menu`.
164    Menu(crate::host::MenuKeys),
165}
166
167/// The reply to a command that asked for one.
168#[derive(Clone, Debug, PartialEq)]
169pub struct Reply {
170    /// The host's tag for the command ([`Engine::command`]).
171    pub tag: u64,
172    /// The result, or the error's message.
173    pub result: std::result::Result<Value, String>,
174    /// Bytes that belong in the result's field of this name (`saveState`'s
175    /// `state`): the Worker passes them as a `Uint8Array`, JSON hosts as
176    /// base64.
177    pub bytes: Option<(&'static str, Vec<u8>)>,
178}
179
180/// The machine's state for the host's store: it changed and has settled
181/// ([`Engine::set_auto_save`]). The host keeps it in the model's auto slot,
182/// apart from the user's own saved state.
183#[derive(Clone, Debug, PartialEq, Eq)]
184pub struct Saved {
185    /// The model's name.
186    pub model: &'static str,
187    /// The ROM file's name.
188    pub rom_name: String,
189    /// CPU cycles since power-on.
190    pub cycles: u64,
191    /// The whole machine state (`saveState`'s).
192    pub state: Vec<u8>,
193}
194
195/// What the engine has for the host, in order.
196#[derive(Clone, Debug, PartialEq)]
197pub enum Output {
198    /// An event for every page.
199    Event(Event),
200    /// A reply for one caller.
201    Reply(Reply),
202    /// A state for the host's store, not for the page.
203    Save(Saved),
204}
205
206/// `boot`'s result.
207#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
208#[serde(rename_all = "camelCase")]
209pub struct Booted {
210    /// The model booted (the ROM may have chosen another).
211    pub model: &'static str,
212    /// The ROM file's name.
213    pub rom_name: String,
214    /// The host's kept state was restored ([`Engine::boot_restoring`]);
215    /// only `true` is sent.
216    #[serde(skip_serializing_if = "std::ops::Not::not")]
217    pub restored: bool,
218    /// Why the kept state did not load (another ROM, an older format):
219    /// the machine cold-booted instead.
220    #[serde(skip_serializing_if = "Option::is_none")]
221    pub restore_error: Option<String>,
222}
223
224/// `stats`'s result: counters for tests (`web/protocol.md`).
225#[derive(Clone, Debug, PartialEq, Serialize)]
226#[serde(rename_all = "camelCase")]
227pub struct Stats {
228    /// CPU cycles since power-on.
229    pub cycles: u64,
230    /// Emulated ms since power-on.
231    pub emulated_ms: f64,
232    /// Wall ms spent emulating (passes, wakes, sends, key scripts).
233    pub work_ms: f64,
234    /// Passes run.
235    pub ticks: u64,
236    /// Wakes from a sleep.
237    pub wakes: u64,
238    /// Looks at the user memory for `memoryChanged`.
239    pub memory_looks: u64,
240    /// Wall ms those looks took.
241    pub memory_ms: f64,
242    /// What the loop does.
243    #[serde(rename = "loop")]
244    pub loop_state: LoopState,
245    /// Emulated ms owed to the wall clock: unpaid, plus the current sleep.
246    pub owed_ms: f64,
247    /// The host's clock.
248    pub now_ms: f64,
249}
250
251/// Why a host's own run of the machine failed ([`Engine::exclusive`]).
252#[derive(Clone, Debug, PartialEq, Eq)]
253pub struct RunError {
254    /// For the user.
255    pub message: String,
256    /// The CPU halted (the machine stops until a reset or a state load).
257    pub halted: bool,
258}
259
260/// What the calculator sent on the page's serial port and the page has
261/// not had yet: gathered between passes, so a `serial` event goes out at
262/// most every [`SERIAL_EVENT_MS`] while the machine computes, and at once
263/// otherwise (asleep, before a reply).
264#[derive(Clone, Debug, Default)]
265struct SerialOut {
266    held: Vec<u8>,
267    /// When the last `serial` event went out.
268    last: Option<f64>,
269}
270
271impl SerialOut {
272    /// The bytes to send at `t`: all held, if there are any and `now`, or
273    /// [`SERIAL_EVENT_MS`] has passed since the last event (within the
274    /// host timer's `slack`).
275    fn take(&mut self, t: f64, slack: f64, now: bool) -> Option<Vec<u8>> {
276        if self.held.is_empty()
277            || (!now && self.last.is_some_and(|l| t + slack < l + SERIAL_EVENT_MS))
278        {
279            return None;
280        }
281        self.last = Some(t);
282        Some(std::mem::take(&mut self.held))
283    }
284
285    /// When held bytes are due to go out.
286    fn due(&self) -> Option<f64> {
287        (!self.held.is_empty()).then(|| self.last.map_or(0.0, |l| l + SERIAL_EVENT_MS))
288    }
289}
290
291/// A send in progress.
292#[derive(Clone, Debug)]
293struct Send {
294    /// Where its reply goes; `None`: errors become `error` events.
295    tag: Option<u64>,
296    /// It holds the frames (`status` `busy`).
297    freezes: bool,
298    /// A write through the Kermit server rather than typing.
299    transfer: bool,
300    /// When it started, on the host's clock.
301    started: f64,
302    /// When its next turn is due.
303    due: f64,
304    /// A write being stopped: why (its reply), while its cleanup (the
305    /// server ended, the 49G's mode set again) runs in turns.
306    stopping: Option<Error>,
307    /// A send or write that came while the boot's question was still
308    /// being answered: started once the answer is done.
309    waiting: Option<Waiting>,
310}
311
312/// What a send waiting for the boot's question starts.
313#[derive(Clone, Debug)]
314enum Waiting {
315    /// Typing: the verb and the text.
316    Typing(String, String),
317    /// A write.
318    Transfer(Op),
319}
320
321/// The protocol's state machine (see the module docs).
322#[derive(Debug)]
323pub struct Engine {
324    /// The host's name in `hello` ("worker", "tauri", "http").
325    host: &'static str,
326    emu: Option<Emulator>,
327    model: Option<Model>,
328    rom_name: String,
329    halted: Option<String>,
330    lp: Loop,
331    watch: Watch,
332    send: Option<Send>,
333    out: Vec<Output>,
334    last_status: Option<Status>,
335    /// When the last `frame` event went out.
336    last_frame: Option<f64>,
337    autosave: AutoSave,
338    /// Whether a cold boot's "Try To Recover Memory?" is answered
339    /// ([`Engine::set_answer_recover`]), and the answer pending.
340    answer_recover: bool,
341    recover: Option<Recover>,
342    /// The page holds the serial port (`serialOpen`): what the UART sends
343    /// goes out as `serial` events, and the writes are refused.
344    serial: bool,
345    serial_out: SerialOut,
346}
347
348/// What one look at a sleeping machine's screen does for the boot's
349/// question (`recover.rs`).
350enum Look {
351    /// Not on the screen yet.
352    Wait,
353    /// It did not come in time: given up.
354    GiveUp,
355    /// On the screen: press the sixth menu key (the NO, then the 49G's
356    /// OK, both there), then wait for this (none after the last).
357    Answer(Option<Recover>),
358}
359
360fn look(e: &Emulator, r: Recover) -> Look {
361    if e.emulated_ms() > r.until_ms {
362        return Look::GiveUp;
363    }
364    let rows = &e.machine().framebuffer().pixels.pixels;
365    match r.step {
366        Step::Prompt if recover::is_prompt(rows) => {
367            Look::Answer((e.model() == Model::Hp49g).then(|| Recover {
368                step: Step::Dismiss,
369                until_ms: e.emulated_ms() + recover::DISMISS_WAIT_MS,
370            }))
371        }
372        Step::Dismiss if recover::is_memory_clear(rows) => Look::Answer(None),
373        _ => Look::Wait,
374    }
375}
376
377/// One step of a send waiting for the boot's question: run the machine
378/// [`TYPING_STEP_MS`], answering the question as [`Engine::timer`] would
379/// (a look whenever the CPU sleeps). True once it is answered (or given
380/// up) and the ROM has settled after the last key, so typing can begin.
381fn answer_boot(e: &mut Emulator, recover: &mut Option<Recover>) -> Result<bool> {
382    if pacing::asleep(e) {
383        match recover.map(|r| look(e, r)) {
384            None => return Ok(true),
385            Some(Look::Wait) => {}
386            Some(Look::GiveUp) => *recover = None,
387            // Not a change to keep: a reload boots cold and is answered
388            // again.
389            Some(Look::Answer(next)) => {
390                e.type_keys("f");
391                *recover = next;
392            }
393        }
394    }
395    e.run_slice(TYPING_STEP_MS, true)?;
396    Ok(false)
397}
398
399/// The string field `name` of `msg`.
400fn str_field<'a>(msg: &'a Value, name: &str) -> Result<&'a str> {
401    msg.get(name)
402        .and_then(Value::as_str)
403        .ok_or_else(|| format!("missing string field {name:?}").into())
404}
405
406/// The `text` of a send or `storeText`. With `codes` true (the AI
407/// tools' text) the 48's translation codes (`\GS`, `\v/`, `\->`, `\\` for
408/// a backslash) are read as their characters first, as an ASCII transfer
409/// reads them (`charset::from_trigraphs`); without it the text is the
410/// calculator's own (the editor's, which may hold a backslash in a string)
411/// and stays as it is.
412fn text_field(msg: &Value) -> Result<String> {
413    let text = str_field(msg, "text")?;
414    Ok(if msg.get("codes").and_then(Value::as_bool) == Some(true) {
415        saturnus_objects::charset::from_trigraphs(text)
416    } else {
417        text.to_string()
418    })
419}
420
421/// A typed answer as the reply's JSON value.
422fn value_of<T: Serialize>(v: &T) -> Result<Value> {
423    serde_json::to_value(v).map_err(|e| e.to_string().into())
424}
425
426fn unknown_key(e: &Emulator, key: &str) -> Error {
427    format!("no key {key:?} on the {}", e.model().name()).into()
428}
429
430/// What a command handler answers: a reply now (with bytes for a field),
431/// or later (a send).
432enum Answer {
433    Now(Value, Option<(&'static str, Vec<u8>)>),
434    Later,
435}
436
437impl From<Value> for Answer {
438    fn from(v: Value) -> Self {
439        Answer::Now(v, None)
440    }
441}
442
443impl Engine {
444    /// An engine with no machine yet, for the host called `host`, paced
445    /// as `pacing` says.
446    pub fn new(host: &'static str, pacing: Pacing) -> Engine {
447        Engine {
448            host,
449            emu: None,
450            model: None,
451            rom_name: String::new(),
452            halted: None,
453            lp: Loop::new(pacing),
454            watch: Watch::default(),
455            send: None,
456            out: Vec::new(),
457            last_status: None,
458            last_frame: None,
459            autosave: AutoSave::default(),
460            answer_recover: false,
461            recover: None,
462            serial: false,
463            serial_out: SerialOut::default(),
464        }
465    }
466
467    /// Whether a cold boot's "Try To Recover Memory?" (48SX, 48GX, 49G)
468    /// is answered NO for the user, and the 49G's "Memory Clear" after it
469    /// dismissed (`recover.rs`): a host that keeps the user's calculator
470    /// (off by default; key scripts and tests answer it themselves).
471    pub fn set_answer_recover(&mut self, on: bool) {
472        self.answer_recover = on;
473        if !on {
474            self.recover = None;
475        }
476    }
477
478    /// An answer to the boot's question is still pending.
479    pub fn answering_recover(&self) -> bool {
480        self.recover.is_some()
481    }
482
483    /// Whether the host keeps states: then the machine's state comes out
484    /// as [`Output::Save`] once it changed and settled (off by default).
485    pub fn set_auto_save(&mut self, on: bool) {
486        self.autosave.on = on;
487        if !on {
488            self.autosave.clear();
489        }
490    }
491
492    /// Saves handed to the host so far.
493    pub fn auto_saves(&self) -> u64 {
494        self.autosave.saves
495    }
496
497    /// A change is waiting to be saved.
498    pub fn save_owed(&self) -> bool {
499        self.autosave.owed()
500    }
501
502    /// Hand out the owed save now, without the delay, if the machine has
503    /// settled (a computing one is not saved: its last settled state is
504    /// in the store). A host calls it before a boot, and stores what it
505    /// gives before it reads or clears the slot: a model switch keeps the
506    /// machine it leaves, a reboot of the same model restores the newest
507    /// state, and a fresh start deletes the slot after this save, so the
508    /// old machine never comes back.
509    pub fn save_now(&mut self) {
510        if self.autosave.owed() && self.settled() {
511            self.emit_save();
512        }
513    }
514
515    /// The protocol version check and the command's name, refused while a
516    /// send is typing if its [`Policy`] says so: what every command
517    /// passes first, also those a host serves itself.
518    pub fn admit<'a>(&self, msg: &'a Value) -> Result<&'a str> {
519        match msg.get("v") {
520            Some(v) if v.as_u64() == Some(VERSION) => {}
521            Some(v) => {
522                return Err(format!(
523                    "protocol version {v} not supported (this host speaks {VERSION})"
524                )
525                .into());
526            }
527            None => {
528                return Err(
529                    format!("protocol version missing (this host speaks {VERSION})").into(),
530                );
531            }
532        }
533        let cmd = str_field(msg, "cmd")?;
534        match self.refusal(cmd) {
535            Some(e) => Err(e),
536            None => Ok(cmd),
537        }
538    }
539
540    /// Why `cmd` is refused now, or `None` (an unknown name never is):
541    /// the page holds the serial port and it is a write or a question to
542    /// the server; a send is typing and it is `refused_while_typing`; a
543    /// write runs and it uses the serial port.
544    pub fn refusal(&self, cmd: &str) -> Option<Error> {
545        let policy = cmd.parse::<CommandKind>().ok()?.policy();
546        if self.serial && (policy.write || policy.server) {
547            return Some(SERIAL_IN_USE.into());
548        }
549        let send = self.send.as_ref()?;
550        let refused = policy.refused_while_typing || (send.transfer && policy.serial);
551        refused.then(|| {
552            if send.transfer {
553                "a transfer is in progress (releaseAll stops it)".into()
554            } else {
555                "typing is in progress (releaseAll stops it)".into()
556            }
557        })
558    }
559
560    /// One protocol message. `bytes` are its *bytes* field when the host
561    /// has them apart from the JSON (the Worker's `rom` and `state`);
562    /// without them a `state` field is base64. With a `reply` tag the
563    /// reply comes out as [`Output::Reply`] after the events the command
564    /// caused (a send's when it is done); without one an error comes out
565    /// as an `error` event.
566    pub fn command(
567        &mut self,
568        clock: &dyn Clock,
569        msg: &Value,
570        bytes: Option<Vec<u8>>,
571        reply: Option<u64>,
572    ) {
573        let answer = self
574            .admit(msg)
575            .and_then(|cmd| self.handle(clock, cmd, msg, bytes, reply));
576        match answer {
577            Ok(Answer::Later) => self.flush(clock, true),
578            Ok(Answer::Now(v, b)) => self.respond(clock, reply, Ok(v), b),
579            Err(e) => self.respond(clock, reply, Err(e), None),
580        }
581    }
582
583    /// Answer a command the host served itself: the events so far, then
584    /// the reply (or, without a `reply` tag, an `error` event for an
585    /// error).
586    pub fn answer(&mut self, clock: &dyn Clock, reply: Option<u64>, result: Result<Value>) {
587        self.respond(clock, reply, result, None);
588    }
589
590    fn respond(
591        &mut self,
592        clock: &dyn Clock,
593        reply: Option<u64>,
594        result: Result<Value>,
595        bytes: Option<(&'static str, Vec<u8>)>,
596    ) {
597        self.flush(clock, true);
598        self.reply_to(reply, result, bytes);
599    }
600
601    fn reply_to(
602        &mut self,
603        reply: Option<u64>,
604        result: Result<Value>,
605        bytes: Option<(&'static str, Vec<u8>)>,
606    ) {
607        match (reply, result) {
608            (Some(tag), result) => self.out.push(Output::Reply(Reply {
609                tag,
610                result: result.map_err(|e| e.to_string()),
611                bytes,
612            })),
613            (None, Err(e)) => self.event(Event::Error(ErrorEvent {
614                message: e.to_string(),
615            })),
616            (None, Ok(_)) => {}
617        }
618    }
619
620    fn event(&mut self, e: Event) {
621        self.out.push(Output::Event(e));
622    }
623
624    /// The replies and events so far, in order.
625    pub fn take_output(&mut self) -> Vec<Output> {
626        std::mem::take(&mut self.out)
627    }
628
629    /// When [`Engine::timer`] is due on the host's clock; `None` while
630    /// only a message can change anything (paused, idle with nothing to
631    /// watch).
632    pub fn deadline(&self) -> Option<f64> {
633        [
634            self.send.as_ref().map(|s| s.due),
635            self.lp.due(),
636            self.watch.due,
637            self.serial_out.due(),
638            // A busy machine's own timers bring it to the save.
639            self.settled().then(|| self.autosave.due()).flatten(),
640        ]
641        .into_iter()
642        .flatten()
643        .reduce(f64::min)
644    }
645
646    /// The host's timer fired: run what is due (a send's turn, a pass, a
647    /// wake, a look at the memory).
648    pub fn timer(&mut self, clock: &dyn Clock) {
649        let now = clock.now_ms();
650        let slack = self.lp.pacing.timer_slack_ms;
651        if self.send.as_ref().is_some_and(|s| s.due <= now + slack) {
652            self.typing_turn(clock);
653        }
654        if let Some(e) = self.emu.as_mut()
655            && let Err(err) = self.lp.fire(e, clock, now)
656        {
657            self.halt(clock, err);
658        }
659        if self.watch.due.is_some_and(|d| d <= now + slack) {
660            self.watch.due = None;
661        }
662        // Between passes a frame waits for the throttle; otherwise it
663        // goes now.
664        self.flush(clock, !self.lp.passing());
665        self.poll_recover(clock);
666    }
667
668    /// Answer the boot's question once it is on the screen and the ROM
669    /// waits for a key (`recover.rs`); give up when it does not come.
670    fn poll_recover(&mut self, clock: &dyn Clock) {
671        let Some(r) = self.recover else {
672            return;
673        };
674        if !self.settled() {
675            return;
676        }
677        let Some(e) = self.emu.as_mut() else {
678            self.recover = None;
679            return;
680        };
681        match look(e, r) {
682            Look::Wait => {}
683            Look::GiveUp => self.recover = None,
684            Look::Answer(next) => {
685                e.type_keys("f");
686                self.recover = next;
687                self.after_keys(clock);
688            }
689        }
690    }
691
692    /// Bytes arrived for the machine from outside (the serial bridge): a
693    /// sleeping CPU first runs the time that passed, then sees when the
694    /// UART wakes it.
695    pub fn input(&mut self, clock: &dyn Clock) {
696        self.autosave.touch(clock.now_ms());
697        if self.lp.sleeping() {
698            self.wake(clock);
699            self.flush(clock, !self.lp.passing());
700        }
701    }
702
703    /// The page holds the serial port (`serialOpen`).
704    pub fn serial_open(&self) -> bool {
705        self.serial
706    }
707
708    /// The page lets go of the serial port: bytes not yet on the wire to
709    /// the calculator are dropped, and so is what it sent and the page
710    /// did not get.
711    fn close_serial(&mut self) {
712        self.serial_out = SerialOut::default();
713        if std::mem::take(&mut self.serial)
714            && let Some(e) = self.emu.as_mut()
715        {
716            let m = e.machine_mut();
717            m.serial_clear_inbound();
718            m.serial_drain();
719        }
720    }
721
722    /// A write through the Kermit server runs (a `/v1/memory` write, a
723    /// server probe): it owns the calculator's UART, so a host's own serial
724    /// bridge leaves it alone until it ends.
725    pub fn transferring(&self) -> bool {
726        self.send.as_ref().is_some_and(|s| s.transfer)
727    }
728
729    /// The tag of the send in progress, if it has one.
730    pub fn sending(&self) -> Option<u64> {
731        self.send.as_ref().and_then(|s| s.tag)
732    }
733
734    /// Stop the send in progress; its reply is the error `why`.
735    pub fn cancel_send(&mut self, clock: &dyn Clock, why: &str) {
736        if self.send.is_some() {
737            self.end_typing(clock, Some(why.into()));
738        }
739    }
740
741    /// What `status` says now.
742    pub fn status(&self) -> Status {
743        Status {
744            model: self.model.map(Model::name),
745            rom_name: self.rom_name.clone(),
746            running: self.lp.running,
747            halted: self.halted.clone(),
748            speed: self.lp.speed,
749            loop_state: self.lp.state(),
750            busy: self.send.as_ref().is_some_and(|s| s.freezes),
751            // Only answered while the machine runs: paused or halted at
752            // the question, the keyboard is the user's to take.
753            starting: self.recover.is_some() && self.lp.running && self.halted.is_none(),
754        }
755    }
756
757    /// The machine, for what a host does beside the protocol (the serial
758    /// bridge); `None` before a boot.
759    pub fn emulator_mut(&mut self) -> Option<&mut Emulator> {
760        self.emu.as_mut()
761    }
762
763    /// The machine, for the commands a host serves itself.
764    pub fn emulator(&self) -> Result<&Emulator> {
765        self.emu.as_ref().ok_or_else(|| "no ROM loaded".into())
766    }
767
768    /// The machine, once the host is done with the engine.
769    pub fn into_emulator(self) -> Option<Emulator> {
770        self.emu
771    }
772
773    /// Start running `emu`, a machine the host built (and perhaps ran)
774    /// from the ROM file `rom_name`.
775    pub fn start(&mut self, clock: &dyn Clock, emu: Emulator, rom_name: &str) {
776        self.serial = false;
777        self.serial_out = SerialOut::default();
778        self.model = Some(emu.model());
779        self.emu = Some(emu);
780        self.rom_name = rom_name.to_string();
781        // A machine the host built and perhaps ran: its screen is its own.
782        self.recover = None;
783        self.halted = None;
784        self.watch.force = true;
785        self.autosave.clear();
786        self.set_running(clock, true);
787        self.flush(clock, true);
788    }
789
790    /// Write `nibbles` from `address` on as CPU writes would (`poke`):
791    /// the display may show it, the user memory may have changed, a
792    /// sleeping CPU may see it.
793    pub fn poke(&mut self, clock: &dyn Clock, address: u32, nibbles: &[u8]) -> Result<()> {
794        if let Some(e) = self.refusal("poke") {
795            return Err(e);
796        }
797        let e = self.emu.as_mut().ok_or("no ROM loaded")?;
798        self.recover = None;
799        for (a, &n) in (address..).zip(nibbles) {
800            e.machine_mut().poke(a, n);
801        }
802        e.reshow();
803        self.watch.force = true;
804        if self.send.is_none() {
805            self.lp.schedule(&*e, clock.now_ms());
806        }
807        self.autosave.touch(clock.now_ms());
808        Ok(())
809    }
810
811    /// Run `f` on the machine outside the pacing, as fast as the host can
812    /// (a native key script), with every key released first; then follow
813    /// the wall clock again from where it left the machine. `f` gets the
814    /// machine and gives it back with its result. Refused during a send,
815    /// as `keyScript`.
816    pub fn exclusive<T>(
817        &mut self,
818        clock: &dyn Clock,
819        f: impl FnOnce(Machine) -> (Machine, std::result::Result<T, RunError>),
820    ) -> Result<T> {
821        if let Some(e) = self.refusal("keyScript") {
822            return Err(e);
823        }
824        // A sleeping machine first catches up the time that passed.
825        self.wake_running(clock)?;
826        let mut emu = self.emu.take().ok_or("no ROM loaded")?;
827        emu.release_keys();
828        self.recover = None;
829        let start = clock.now_ms();
830        let (machine, result) = f(emu.into_machine());
831        self.lp.work_ms += clock.now_ms() - start;
832        self.emu = Some(Emulator::from_machine(machine));
833        self.autosave.touch(clock.now_ms());
834        match result {
835            Ok(t) => {
836                self.set_running(clock, self.lp.running);
837                Ok(t)
838            }
839            Err(e) => {
840                if e.halted {
841                    self.halted = Some(e.message.clone());
842                    self.set_running(clock, false);
843                } else {
844                    self.set_running(clock, self.lp.running);
845                }
846                Err(e.message.into())
847            }
848        }
849    }
850
851    /// Build `model` (a preference: a ROM that only fits another model
852    /// boots that one) from `rom` and run it; the machine before keeps
853    /// running if this one cannot be built.
854    pub fn boot(
855        &mut self,
856        clock: &dyn Clock,
857        model: &str,
858        rom: &[u8],
859        rom_name: &str,
860    ) -> Result<Booted> {
861        self.boot_restoring(clock, model, rom, rom_name, None)
862    }
863
864    /// [`Engine::boot`], then restore `kept`, the state the host kept for
865    /// this model, before the machine runs a cycle: the calculator is as
866    /// it was, with no "Try To Recover Memory?". A state that does not
867    /// load (another ROM, another model, an older format) leaves the cold
868    /// boot, and `restore_error` says why. The machine it replaces is not
869    /// saved here: the host calls [`Engine::save_now`] and stores that
870    /// save before it reads or clears the slot, so the slot it reads is
871    /// the newest and a fresh start's stays empty. An owed save left now
872    /// is dropped.
873    pub fn boot_restoring(
874        &mut self,
875        clock: &dyn Clock,
876        model: &str,
877        rom: &[u8],
878        rom_name: &str,
879        kept: Option<&[u8]>,
880    ) -> Result<Booted> {
881        if let Some(e) = self.refusal("boot") {
882            return Err(e);
883        }
884        let model = model_for_rom(rom, model.parse()?);
885        let mut emu = Emulator::new(model, rom)?;
886        let mut restored = false;
887        let mut restore_error = None;
888        if let Some(state) = kept {
889            if state.len() > MAX_STATE_BYTES {
890                restore_error = Some(format!("state is larger than {MAX_STATE_BYTES} bytes"));
891            } else {
892                match emu.load_state(state) {
893                    Ok(()) => restored = true,
894                    Err(e) => restore_error = Some(e.to_string()),
895                }
896            }
897        }
898        // A cold boot of a model that asks: the question is answered once it is up.
899        self.recover =
900            (self.answer_recover && !restored && recover::asks(model)).then(|| Recover {
901                step: Step::Prompt,
902                until_ms: emu.emulated_ms() + recover::PROMPT_WAIT_MS,
903            });
904        // Another calculator: the page's link to the old one is gone.
905        self.serial = false;
906        self.serial_out = SerialOut::default();
907        self.emu = Some(emu);
908        self.model = Some(model);
909        self.rom_name = rom_name.to_string();
910        self.halted = None;
911        self.watch.force = true;
912        self.autosave.clear();
913        self.set_running(clock, true);
914        self.flush(clock, true);
915        Ok(Booted {
916            model: model.name(),
917            rom_name: self.rom_name.clone(),
918            restored,
919            restore_error,
920        })
921    }
922
923    /// The whole machine state (`saveState`).
924    pub fn save_state(&self) -> Result<Vec<u8>> {
925        if let Some(e) = self.refusal("saveState") {
926            return Err(e);
927        }
928        Ok(self.emulator()?.save_state())
929    }
930
931    /// Restore a saved state of the same model and ROM (`loadState`);
932    /// the host's queued and held keys go with the old machine
933    /// ([`Emulator::load_state`]). A state that does not load changes
934    /// nothing, the keys held included.
935    pub fn load_state(&mut self, clock: &dyn Clock, state: &[u8]) -> Result<()> {
936        if let Some(e) = self.refusal("loadState") {
937            return Err(e);
938        }
939        if state.len() > MAX_STATE_BYTES {
940            return Err(format!("state is larger than {MAX_STATE_BYTES} bytes").into());
941        }
942        let e = self.emu.as_mut().ok_or("no ROM loaded")?;
943        e.load_state(state)?;
944        e.reshow();
945        // Another machine's screen: nothing of the boot's to answer.
946        self.recover = None;
947        self.halted = None;
948        self.watch.force = true;
949        self.autosave.touch(clock.now_ms());
950        self.set_running(clock, self.lp.running);
951        self.flush(clock, true);
952        Ok(())
953    }
954
955    /// Stats now.
956    pub fn stats(&self, clock: &dyn Clock) -> Stats {
957        let now = clock.now_ms();
958        Stats {
959            cycles: self.emu.as_ref().map_or(0, |e| e.machine().cycles()),
960            emulated_ms: self.emu.as_ref().map_or(0.0, Emulator::emulated_ms),
961            work_ms: self.lp.work_ms,
962            ticks: self.lp.ticks,
963            wakes: self.lp.wakes,
964            memory_looks: self.watch.looks,
965            memory_ms: self.watch.spent_ms,
966            loop_state: self.lp.state(),
967            owed_ms: self.lp.owed_ms(now),
968            now_ms: now,
969        }
970    }
971
972    fn emu(&mut self) -> Result<&mut Emulator> {
973        self.emu.as_mut().ok_or_else(|| "no ROM loaded".into())
974    }
975
976    /// One admitted command.
977    fn handle(
978        &mut self,
979        clock: &dyn Clock,
980        cmd: &str,
981        msg: &Value,
982        bytes: Option<Vec<u8>>,
983        reply: Option<u64>,
984    ) -> Result<Answer> {
985        // The user's own keys answer whatever the screen asks: the boot's
986        // question is theirs then. (A machine replaced, reset, poked or
987        // run by a key script ends it in those methods, for every host.)
988        let kind: CommandKind = cmd.parse()?;
989        use CommandKind as C;
990        if matches!(kind, C::KeyDown | C::TypeLetter | C::TypeKeys) {
991            self.recover = None;
992        }
993        Ok(match kind {
994            C::Hello => {
995                // A (re)loaded page starts from nothing: the status, the
996                // keys down and the current frame go out again, before
997                // this reply. The page fetches the model's skin itself.
998                self.last_status = None;
999                self.watch.on = false;
1000                self.close_serial();
1001                if let Some(e) = self.emu.as_mut() {
1002                    e.reshow();
1003                }
1004                let models: Vec<&str> = crate::skins::hosted_models().map(|m| m.name()).collect();
1005                // The release (the workspace's version): the page shows it in About.
1006                json!({
1007                    "protocol": VERSION,
1008                    "host": self.host,
1009                    "models": models,
1010                    "version": env!("CARGO_PKG_VERSION"),
1011                })
1012                .into()
1013            }
1014            C::Skin => {
1015                let m: Model = str_field(msg, "model")?.parse()?;
1016                let view = crate::skins::skin_view(m)
1017                    .ok_or_else(|| format!("no drawn keyboard for the {} yet", m.name()))?;
1018                value_of(&view)?.into()
1019            }
1020            C::Layout => {
1021                let m: Model = str_field(msg, "model")?.parse()?;
1022                value_of(&crate::layout::grid(m))?.into()
1023            }
1024            C::Boot => {
1025                let model = str_field(msg, "model")?;
1026                let rom = bytes.ok_or("missing bytes field \"rom\"")?;
1027                let name = msg.get("romName").and_then(Value::as_str).unwrap_or("");
1028                value_of(&self.boot(clock, model, &rom, name)?)?.into()
1029            }
1030            C::KeyDown => {
1031                let key = str_field(msg, "key")?;
1032                let shift = msg.get("shift").and_then(Value::as_str);
1033                let e = self.emu()?;
1034                let queued = match shift {
1035                    None => e.press(key),
1036                    Some(shift) => {
1037                        if !e.has_key(shift) {
1038                            return Err(unknown_key(e, shift));
1039                        }
1040                        e.press_shifted(key, shift)
1041                    }
1042                };
1043                if !queued {
1044                    if let Some(shift) = shift.filter(|_| e.has_key(key)) {
1045                        return Err(format!("{shift:?} is not a shift key").into());
1046                    }
1047                    return Err(unknown_key(e, key));
1048                }
1049                self.autosave.touch(clock.now_ms());
1050                self.after_keys(clock);
1051                Value::Null.into()
1052            }
1053            C::KeyUp => {
1054                let key = str_field(msg, "key")?;
1055                let e = self.emu()?;
1056                if !e.has_key(key) {
1057                    return Err(unknown_key(e, key));
1058                }
1059                e.release(key);
1060                e.pump();
1061                self.autosave.touch(clock.now_ms());
1062                Value::Null.into()
1063            }
1064            C::KeyUpAll => {
1065                // The window lost the focus during a send: the send holds
1066                // no queued key, and its own key comes up when its press
1067                // ends.
1068                if self.send.is_none()
1069                    && let Some(e) = self.emu.as_mut()
1070                {
1071                    e.release_held();
1072                    e.pump();
1073                }
1074                Value::Null.into()
1075            }
1076            C::TypeLetter => {
1077                let letter = str_field(msg, "letter")?;
1078                let Some(e) = self.emu.as_mut() else {
1079                    return Ok(Value::Bool(false).into());
1080                };
1081                let ok = e.type_letter(letter);
1082                self.autosave.touch(clock.now_ms());
1083                self.after_keys(clock);
1084                Value::Bool(ok).into()
1085            }
1086            C::TypeKeys => {
1087                let keys = msg
1088                    .get("keys")
1089                    .and_then(Value::as_array)
1090                    .ok_or("missing array field \"keys\"")?;
1091                // As long as the longest text a send types.
1092                if keys.len() > crate::typing::MAX_CHARS {
1093                    return Err(format!(
1094                        "\"keys\" holds more than {} keys",
1095                        crate::typing::MAX_CHARS
1096                    )
1097                    .into());
1098                }
1099                let keys: Vec<&str> = keys
1100                    .iter()
1101                    .map(Value::as_str)
1102                    .collect::<Option<_>>()
1103                    .ok_or("\"keys\" must hold key names (strings)")?;
1104                let e = self.emu()?;
1105                // All or nothing: one unknown name refuses the sequence.
1106                if let Some(k) = keys.iter().find(|k| !e.has_key(k)) {
1107                    return Err(unknown_key(e, k));
1108                }
1109                e.queue().type_keys(&keys);
1110                self.autosave.touch(clock.now_ms());
1111                self.after_keys(clock);
1112                Value::Null.into()
1113            }
1114            C::ReleaseAll => {
1115                // Also stops a send in progress (its reply is an error).
1116                self.cancel_send(clock, "cancelled");
1117                if let Some(e) = self.emu.as_mut() {
1118                    e.release_keys();
1119                }
1120                Value::Null.into()
1121            }
1122            C::SetSpeed => {
1123                // Asleep, emulated time runs at 1x at any speed: only the
1124                // passes change.
1125                self.lp.speed = Speed::parse(str_field(msg, "speed")?);
1126                Value::Null.into()
1127            }
1128            C::Pause => {
1129                // Anything but `paused: false` pauses.
1130                let paused = msg.get("paused").and_then(Value::as_bool).unwrap_or(true);
1131                self.set_running(clock, !paused);
1132                Value::Null.into()
1133            }
1134            C::Unload => {
1135                // Its ROM was removed: no machine, as before the first
1136                // boot (the page shows the empty state). A change not yet
1137                // saved is saved first, as saved states stay (the page
1138                // deletes a 49G's after, with its ROM).
1139                if self.autosave.owed() {
1140                    self.emit_save();
1141                }
1142                self.serial = false;
1143                self.serial_out = SerialOut::default();
1144                self.emu = None;
1145                self.model = None;
1146                self.rom_name.clear();
1147                self.halted = None;
1148                self.recover = None;
1149                self.watch.on = false;
1150                self.autosave.clear();
1151                self.set_running(clock, false);
1152                self.send_status();
1153                Value::Null.into()
1154            }
1155            C::Reset => {
1156                self.recover = None;
1157                let e = self.emu()?;
1158                e.release_keys();
1159                e.reset();
1160                self.halted = None;
1161                self.autosave.touch(clock.now_ms());
1162                self.set_running(clock, true);
1163                Value::Null.into()
1164            }
1165            C::SaveState => {
1166                let state = self.save_state()?;
1167                let cycles = self.emulator()?.machine().cycles();
1168                Answer::Now(json!({"cycles": cycles}), Some(("state", state)))
1169            }
1170            C::LoadState => {
1171                let state = match bytes {
1172                    Some(b) => b,
1173                    None => {
1174                        let b64 = str_field(msg, "state")?;
1175                        if b64.len() > MAX_STATE_BYTES.div_ceil(3) * 4 {
1176                            return Err(
1177                                format!("state is larger than {MAX_STATE_BYTES} bytes").into()
1178                            );
1179                        }
1180                        base64_decode(b64).map_err(|e| format!("state: {e}"))?
1181                    }
1182                };
1183                self.load_state(clock, &state)?;
1184                json!({}).into()
1185            }
1186            C::Visibility => {
1187                let hidden = msg.get("hidden").and_then(Value::as_bool).unwrap_or(false);
1188                // The last moment a phone's page may run: an unsaved
1189                // change is saved now, or once a send, a write or a
1190                // computation has settled. In the browser a computation
1191                // stops while hidden, so its save waits until the page is
1192                // shown again.
1193                if hidden {
1194                    self.autosave.hide();
1195                }
1196                let idle = self.send.is_none();
1197                self.lp
1198                    .set_hidden(hidden, self.emu.as_ref(), idle, clock.now_ms());
1199                Value::Null.into()
1200            }
1201            C::Stats => value_of(&self.stats(clock))?.into(),
1202            C::WatchMemory => {
1203                let on = msg.get("on").and_then(Value::as_bool).unwrap_or(false);
1204                self.watch.subscribe(on, self.emu.as_ref());
1205                let Some(e) = &self.emu else {
1206                    return Ok(json!({"supported": null, "reason": null}).into());
1207                };
1208                let reason = e.memory_refusal();
1209                json!({"supported": reason.is_none(), "reason": reason}).into()
1210            }
1211            C::MemoryTree => value_of(&self.emu()?.memory_tree()?)?.into(),
1212            C::Stack => Value::Array(self.emu()?.stack()?).into(),
1213            C::StackTop => self.emu()?.stack_top()?.into(),
1214            C::Flags => value_of(&self.emu()?.flags()?)?.into(),
1215            C::ObjectAt => {
1216                let address = msg
1217                    .get("address")
1218                    .and_then(Value::as_u64)
1219                    .ok_or("missing number field \"address\"")?;
1220                let address = u32::try_from(address)
1221                    .ok()
1222                    .filter(|&a| a <= 0xF_FFFF)
1223                    .ok_or("address is outside the address space")?;
1224                self.emu()?.object_at(address)?.into()
1225            }
1226            C::CommandLine => value_of(&self.emu()?.command_line()?)?.into(),
1227            C::EntryModes => value_of(&crate::typing::entry_modes(self.emu()?.machine())?)?.into(),
1228            C::UiState => value_of(&self.emu()?.ui_state()?)?.into(),
1229            C::SerialOpen => {
1230                let serial = self.serial;
1231                let e = self.emu()?;
1232                if !e.machine().has_serial() {
1233                    return Err(format!(
1234                        "the {} has no serial port",
1235                        e.model().name().to_uppercase()
1236                    )
1237                    .into());
1238                }
1239                // What the calculator sent before is not the page's; once
1240                // open, what it sent since is (a second open keeps it).
1241                if !serial {
1242                    e.machine_mut().serial_drain();
1243                    self.serial = true;
1244                }
1245                Value::Null.into()
1246            }
1247            C::SerialWrite => {
1248                // The calculator and the port first, then the bytes.
1249                self.emu()?;
1250                if !self.serial {
1251                    return Err("the serial port is not open (serialOpen first)".into());
1252                }
1253                let too_many =
1254                    || format!("more than {MAX_SERIAL_PENDING} bytes for the serial port");
1255                let data = match bytes {
1256                    Some(b) => b,
1257                    None => {
1258                        let b64 = str_field(msg, "bytes")?;
1259                        if b64.len() > MAX_SERIAL_PENDING.div_ceil(3) * 4 {
1260                            return Err(too_many().into());
1261                        }
1262                        base64_decode(b64).map_err(|e| format!("bytes: {e}"))?
1263                    }
1264                };
1265                if data.len() > MAX_SERIAL_PENDING {
1266                    return Err(too_many().into());
1267                }
1268                let m = self.emu()?.machine_mut();
1269                let waiting = m.serial_pending();
1270                if waiting + data.len() > MAX_SERIAL_PENDING {
1271                    return Err(format!(
1272                        "the serial port's input is full ({waiting} bytes still waiting)"
1273                    )
1274                    .into());
1275                }
1276                m.serial_push(&data);
1277                self.input(clock);
1278                Value::Null.into()
1279            }
1280            C::SerialClose => {
1281                self.close_serial();
1282                Value::Null.into()
1283            }
1284            C::EditText => {
1285                let (dir, target) = self.text_target(msg)?;
1286                let (text, was) = self.emu()?.edit_text(&dir, &target)?;
1287                json!({"text": text, "was": was}).into()
1288            }
1289            C::Insert | C::TypeText => self.start_typing(clock, "insert", msg, reply)?,
1290            C::Run => self.start_typing(clock, "run", msg, reply)?,
1291            C::ProbeServer | C::EndServer => {
1292                // No server possible: answered at once, the machine
1293                // untouched (a boot's check is no change to save).
1294                let m = self.emu()?.machine();
1295                if !crate::transfer::may_serve(m) && m.has_serial() {
1296                    return Ok(json!({"server": false, "emulatedMs": 0.0, "keys": false}).into());
1297                }
1298                let op = Op::Server {
1299                    end: kind == C::EndServer,
1300                };
1301                self.start_transfer(clock, op, reply)?
1302            }
1303            C::StoreFile
1304            | C::FetchFile
1305            | C::Purge
1306            | C::Rename
1307            | C::CreateDir
1308            | C::ChangeDir
1309            | C::SetFlag
1310            | C::Copy
1311            | C::Move
1312            | C::StoreScreen
1313            | C::StoreText
1314            | C::Backup => {
1315                let op = self.write_op(kind, msg, bytes)?;
1316                self.start_transfer(clock, op, reply)?
1317            }
1318            C::Replace => self.start_typing(clock, "replace", msg, reply)?,
1319            C::SetClock => self.set_clock(clock, msg, reply)?,
1320            // Served by the hosts themselves (the native commands, the ROM
1321            // slots, the hub's), or by none: unknown here.
1322            C::Screen
1323            | C::Info
1324            | C::Model
1325            | C::Peek
1326            | C::Poke
1327            | C::KeyScript
1328            | C::StateSlot
1329            | C::OpenState
1330            | C::SaveFile
1331            | C::RomSlots
1332            | C::BootModel
1333            | C::ChooseRom
1334            | C::DownloadRom
1335            | C::ForgetRom
1336            | C::RomSettings
1337            | C::Join
1338            | C::Ping
1339            | C::Attach
1340            | C::Leave => return Err(format!("unknown command {cmd:?}").into()),
1341        })
1342    }
1343
1344    /// Commands queued keys: wake a sleeping machine (its time first, then
1345    /// the keys; the wake starts passes for the queue), then feed the
1346    /// queue.
1347    fn after_keys(&mut self, clock: &dyn Clock) {
1348        self.wake(clock);
1349        if let Some(e) = self.emu.as_mut() {
1350            e.pump();
1351        }
1352    }
1353
1354    /// Leave a sleep now (a halt on the way stops the machine).
1355    fn wake(&mut self, clock: &dyn Clock) {
1356        if let Some(e) = self.emu.as_mut()
1357            && let Err(err) = self.lp.wake(e, clock)
1358        {
1359            self.halt(clock, err);
1360        }
1361    }
1362
1363    /// [`Engine::wake`] for work that needs a running CPU: refused if it
1364    /// is halted, before the wake or by it (the time it caught up ran into
1365    /// the halt).
1366    fn wake_running(&mut self, clock: &dyn Clock) -> Result<()> {
1367        if self.halted.is_none() {
1368            self.wake(clock);
1369        }
1370        match &self.halted {
1371            Some(h) => Err(format!("the CPU is halted: {h}").into()),
1372            None => Ok(()),
1373        }
1374    }
1375
1376    fn halt(&mut self, clock: &dyn Clock, err: Error) {
1377        self.halted = Some(err.to_string());
1378        self.set_running(clock, false);
1379    }
1380
1381    /// The Run/Pause switch, and the restart after anything that changed
1382    /// the machine under the loop.
1383    fn set_running(&mut self, clock: &dyn Clock, on: bool) {
1384        self.lp.running = on && self.emu.is_some() && self.halted.is_none();
1385        self.lp.stop();
1386        // A send drives the machine itself; the loop resumes when it ends.
1387        if self.send.is_some() {
1388            return;
1389        }
1390        if let Some(e) = &self.emu {
1391            self.lp.start(e, clock.now_ms());
1392        }
1393    }
1394
1395    /// Start a send of `msg`'s `text` with `verb`: the loop stops and the
1396    /// send runs in turns ([`Engine::timer`]) until it is done.
1397    fn start_typing(
1398        &mut self,
1399        clock: &dyn Clock,
1400        verb: &str,
1401        msg: &Value,
1402        reply: Option<u64>,
1403    ) -> Result<Answer> {
1404        let text = &text_field(msg)?;
1405        self.emu()?;
1406        // A sleeping machine first catches up the time that passed.
1407        self.wake_running(clock)?;
1408        // Right after a cold boot the question still has the keyboard
1409        // (and the 49G's RAM may not hold a command line yet): the send
1410        // waits, in emulated time, until it is answered, then types.
1411        let waiting = self.recover.is_some() && self.lp.running;
1412        let freezes = if waiting {
1413            self.emu()?.check_typing(verb, text)?
1414        } else {
1415            self.emu()?.start_typing(verb, text)?
1416        };
1417        self.lp.stop();
1418        let now = clock.now_ms();
1419        self.autosave.touch(now);
1420        self.send = Some(Send {
1421            tag: reply,
1422            freezes,
1423            transfer: false,
1424            started: now,
1425            due: now,
1426            stopping: None,
1427            waiting: waiting.then(|| Waiting::Typing(verb.to_string(), text.to_string())),
1428        });
1429        Ok(Answer::Later)
1430    }
1431
1432    /// The write a command asks for: `dir` (the current directory when
1433    /// absent), `name`, `to`, `flag`, `on`, and `storeFile`'s file
1434    /// (`bytes`, else the base64 field `data`).
1435    fn write_op(&mut self, cmd: CommandKind, msg: &Value, bytes: Option<Vec<u8>>) -> Result<Op> {
1436        let given = match msg.get("dir") {
1437            None | Some(Value::Null) => None,
1438            Some(v) => Some(
1439                v.as_array()
1440                    .and_then(|a| {
1441                        a.iter()
1442                            .map(|s| s.as_str().map(str::to_string))
1443                            .collect::<Option<Vec<_>>>()
1444                    })
1445                    .ok_or("\"dir\" must be an array of directory names")?,
1446            ),
1447        };
1448        let name = || str_field(msg, "name").map(str::to_string);
1449        let dir = Vec::new();
1450        if cmd == CommandKind::StoreText {
1451            let text = text_field(msg)?;
1452            let (dir, target) = self.text_target(msg)?;
1453            // What the editor opened must still be there: a save never
1454            // replaces what it did not show. Compared by the object
1455            // (`editText`'s `was`: size and checksum), not its text, which
1456            // follows the display mode.
1457            if let Some(was) = msg.get("was").and_then(Value::as_str) {
1458                self.emu()?.check_unchanged(&dir, &target, was)?;
1459            }
1460            return Ok(Op::StoreText { dir, target, text });
1461        }
1462        if cmd == CommandKind::StoreScreen {
1463            let name = match msg.get("name") {
1464                None | Some(Value::Null) => None,
1465                Some(_) => Some(name()?),
1466            };
1467            let screen = self.screen_of(msg)?;
1468            let dir = match (given, &name) {
1469                (Some(d), _) => d,
1470                (None, Some(_)) => self.emu()?.memory_tree()?.path,
1471                (None, None) => Vec::new(),
1472            };
1473            return Ok(Op::StoreScreen {
1474                dir,
1475                name,
1476                replace: msg.get("replace").and_then(Value::as_bool).unwrap_or(false),
1477                screen,
1478            });
1479        }
1480        if cmd == CommandKind::Backup {
1481            return Ok(Op::Backup);
1482        }
1483        let mut op = match cmd {
1484            CommandKind::StoreFile => {
1485                let data = match bytes {
1486                    Some(b) => b,
1487                    None => {
1488                        let b64 = str_field(msg, "data")?;
1489                        if b64.len() > MAX_FILE_BYTES.div_ceil(3) * 4 {
1490                            return Err(
1491                                format!("the file is larger than {MAX_FILE_BYTES} bytes").into()
1492                            );
1493                        }
1494                        base64_decode(b64).map_err(|e| format!("data: {e}"))?
1495                    }
1496                };
1497                Op::Store {
1498                    dir,
1499                    name: name()?,
1500                    data,
1501                    replace: msg.get("replace").and_then(Value::as_bool),
1502                }
1503            }
1504            CommandKind::FetchFile => Op::Fetch {
1505                dir,
1506                name: name()?,
1507                text: msg.get("text").and_then(Value::as_bool).unwrap_or(false),
1508            },
1509            CommandKind::Purge => Op::Purge { dir, name: name()? },
1510            CommandKind::Rename => Op::Rename {
1511                dir,
1512                name: name()?,
1513                to: str_field(msg, "to")?.to_string(),
1514            },
1515            CommandKind::CreateDir => Op::CreateDir { dir, name: name()? },
1516            CommandKind::Copy | CommandKind::Move => Op::Copy {
1517                dir,
1518                name: name()?,
1519                to: msg
1520                    .get("to")
1521                    .and_then(Value::as_array)
1522                    .and_then(|a| {
1523                        a.iter()
1524                            .map(|s| s.as_str().map(str::to_string))
1525                            .collect::<Option<Vec<_>>>()
1526                    })
1527                    .ok_or("\"to\" must be an array of directory names")?,
1528                replace: msg.get("replace").and_then(Value::as_bool).unwrap_or(false),
1529                remove: cmd == CommandKind::Move,
1530            },
1531            CommandKind::ChangeDir if given.is_none() => {
1532                return Err("missing array field \"dir\"".into());
1533            }
1534            CommandKind::ChangeDir => Op::ChangeDir { dir },
1535            _ => {
1536                let flag = msg
1537                    .get("flag")
1538                    .and_then(Value::as_i64)
1539                    .and_then(|f| i32::try_from(f).ok())
1540                    .ok_or("missing number field \"flag\"")?;
1541                let on = msg
1542                    .get("on")
1543                    .and_then(Value::as_bool)
1544                    .ok_or("missing boolean field \"on\"")?;
1545                Op::SetFlag { flag, on }
1546            }
1547        };
1548        // The fields first, then the calculator.
1549        if let Op::Store { dir, .. }
1550        | Op::Fetch { dir, .. }
1551        | Op::Purge { dir, .. }
1552        | Op::Rename { dir, .. }
1553        | Op::CreateDir { dir, .. }
1554        | Op::Copy { dir, .. }
1555        | Op::ChangeDir { dir } = &mut op
1556        {
1557            *dir = match given {
1558                Some(d) => d,
1559                None => self.emu()?.memory_tree()?.path,
1560            };
1561        }
1562        Ok(op)
1563    }
1564
1565    /// The screen `storeScreen` stores: `pixels` (base64, packed as the
1566    /// `frame` event's, the display's size: the frame the page showed),
1567    /// or else the display as it is now.
1568    fn screen_of(&mut self, msg: &Value) -> Result<saturnus_objects::Graphic> {
1569        let lcd = self.emu()?.machine().lcd();
1570        let (width, height) = (lcd.width(), lcd.height());
1571        let packed = match msg.get("pixels") {
1572            None | Some(Value::Null) => crate::host::pack_bits(&lcd.pixels),
1573            Some(_) => {
1574                let b64 = str_field(msg, "pixels")?;
1575                let given =
1576                    |k: &str, d: usize| msg.get(k).and_then(Value::as_u64).unwrap_or(d as u64);
1577                if given("width", width) != width as u64 || given("height", height) != height as u64
1578                {
1579                    return Err(format!("the screen is {width} by {height} pixels").into());
1580                }
1581                let bytes = base64_decode(b64).map_err(|e| format!("pixels: {e}"))?;
1582                if bytes.len() != crate::host::packed_row_bytes(width) * height {
1583                    return Err(format!("pixels: not {width} by {height} pixels").into());
1584                }
1585                bytes
1586            }
1587        };
1588        saturnus_objects::Graphic::from_packed(width as u32, height as u32, &packed)
1589            .map_err(Into::into)
1590    }
1591
1592    /// The directory and the target of `editText` and `storeText`: `dir`
1593    /// (the current directory when absent) and `name`, or `level`.
1594    fn text_target(&mut self, msg: &Value) -> Result<(Vec<String>, Target)> {
1595        let target = match (msg.get("name"), msg.get("level")) {
1596            (Some(_), None) => Target::Variable(str_field(msg, "name")?.to_string()),
1597            (None, Some(l)) => Target::Level(
1598                l.as_u64()
1599                    .and_then(|n| usize::try_from(n).ok())
1600                    .filter(|&n| n >= 1)
1601                    .ok_or("\"level\" must be a stack level (1 or more)")?,
1602            ),
1603            _ => return Err("give either \"name\" or \"level\"".into()),
1604        };
1605        let dir = match msg.get("dir") {
1606            None | Some(Value::Null) => self.emu()?.memory_tree()?.path,
1607            Some(v) => v
1608                .as_array()
1609                .and_then(|a| {
1610                    a.iter()
1611                        .map(|s| s.as_str().map(str::to_string))
1612                        .collect::<Option<Vec<_>>>()
1613                })
1614                .ok_or("\"dir\" must be an array of directory names")?,
1615        };
1616        Ok((dir, target))
1617    }
1618
1619    /// `setClock`: the 48 and 49 type `→TIME` and `→DATE` as a write
1620    /// (replied when done); the other models with a clock get its keys
1621    /// queued (replied at once). Either way the set is rehearsed on a
1622    /// copy of the machine first and the time keyed ahead (or behind) by
1623    /// what that showed, so the clock reads the wall clock once the set is
1624    /// done (`crate::clock`). Refused while the boot's question is being
1625    /// answered, and when the calculator is off, busy or has a command
1626    /// line open.
1627    fn set_clock(&mut self, clock: &dyn Clock, msg: &Value, reply: Option<u64>) -> Result<Answer> {
1628        let wall_ms = clock.now_ms();
1629        let time = crate::clock::ClockTime::from_json(msg)?;
1630        let ms = match msg.get("millisecond") {
1631            None | Some(Value::Null) => 0.0,
1632            Some(v) => v
1633                .as_f64()
1634                .filter(|ms| (0.0..1000.0).contains(ms))
1635                .ok_or("\"millisecond\" must be a number from 0 to 999")?,
1636        };
1637        let now = crate::clock::Now { time, ms, wall_ms };
1638        if let Some(h) = &self.halted {
1639            return Err(format!("the CPU is halted: {h}").into());
1640        }
1641        if self.recover.is_some() {
1642            return Err(crate::clock::BUSY.into());
1643        }
1644        if let Some(why) = self.emu()?.clock_refusal() {
1645            return Err(why.into());
1646        }
1647        // Time the CPU slept is run first, so the rehearsal starts from
1648        // the machine the keys will play on. A wake may halt the CPU; one
1649        // that could not catch up leaves time owed, which the first pass
1650        // would run with the keys, faster than the rehearsal: refused.
1651        self.wake_running(clock)?;
1652        if self.lp.behind_ms() > 0.0 {
1653            return Err(crate::clock::BUSY.into());
1654        }
1655        let e = self.emu()?;
1656        if crate::clock::by_command(e.model()) {
1657            // A write runs as fast as the host can, whatever the speed.
1658            let (op, _) = e.clock_write(&now, &crate::clock::Pace::UNBOUNDED, clock)?;
1659            return self.start_transfer(clock, op, reply);
1660        }
1661        let pace = self.lp.clock_pace();
1662        let e = self.emu()?;
1663        e.set_clock_by_keys(&now, &pace, clock)?;
1664        self.autosave.touch(clock.now_ms());
1665        self.after_keys(clock);
1666        Ok(Value::Null.into())
1667    }
1668
1669    /// Start the write `op`: the loop stops and it runs in turns, the
1670    /// screen held, until it is done.
1671    fn start_transfer(&mut self, clock: &dyn Clock, op: Op, reply: Option<u64>) -> Result<Answer> {
1672        self.emu()?;
1673        self.wake_running(clock)?;
1674        // As a send: right after a cold boot it waits for the question's
1675        // answer (the memory is not set up before).
1676        let waiting = if self.recover.is_some() && self.lp.running {
1677            Some(Waiting::Transfer(op))
1678        } else {
1679            self.emu()?.start_transfer(op)?;
1680            None
1681        };
1682        self.lp.stop();
1683        let now = clock.now_ms();
1684        self.autosave.touch(now);
1685        self.send = Some(Send {
1686            tag: reply,
1687            freezes: true,
1688            transfer: true,
1689            started: now,
1690            due: now,
1691            stopping: None,
1692            waiting,
1693        });
1694        Ok(Answer::Later)
1695    }
1696
1697    /// One turn of the send: steps until it is done or the turn's wall
1698    /// time is used up.
1699    fn typing_turn(&mut self, clock: &dyn Clock) {
1700        let (Some(send), Some(e)) = (self.send.as_mut(), self.emu.as_mut()) else {
1701            return;
1702        };
1703        let started = send.started;
1704        let transfer = send.transfer;
1705        let start = clock.now_ms();
1706        let mut result = Ok(false);
1707        while matches!(result, Ok(false)) && clock.now_ms() - start < self.lp.pacing.typing_tick_ms
1708        {
1709            result = if send.waiting.is_some() {
1710                match answer_boot(e, &mut self.recover) {
1711                    Ok(true) => match send.waiting.take() {
1712                        Some(Waiting::Typing(verb, text)) => {
1713                            e.start_typing(&verb, &text).map(|_| false)
1714                        }
1715                        Some(Waiting::Transfer(op)) => e.start_transfer(op).map(|_| false),
1716                        None => Ok(false),
1717                    },
1718                    other => other.map(|_| false),
1719                }
1720            } else if transfer {
1721                e.transfer_step(TYPING_STEP_MS)
1722            } else {
1723                e.typing_step(TYPING_STEP_MS)
1724            };
1725        }
1726        let now = clock.now_ms();
1727        self.lp.work_ms += now - start;
1728        // Out of wall time after ENTER: the wait ends as at its emulated
1729        // cap, and the reply says `running` (the error is for typing).
1730        if matches!(result, Ok(false))
1731            && now - started > WALL_LIMIT_MS
1732            && !transfer
1733            && send.waiting.is_none()
1734            && e.typing_end_wait()
1735        {
1736            for _ in 0..WAIT_END_STEPS {
1737                result = e.typing_step(TYPING_STEP_MS);
1738                if !matches!(result, Ok(false)) {
1739                    break;
1740                }
1741                e.typing_end_wait();
1742            }
1743        }
1744        match result {
1745            Ok(false) if now - started > WALL_LIMIT_MS => self.end_typing(
1746                clock,
1747                Some(
1748                    format!(
1749                        "{} ran out of wall-clock time ({} s)",
1750                        if transfer { "the transfer" } else { "typing" },
1751                        WALL_LIMIT_MS / 1000.0
1752                    )
1753                    .into(),
1754                ),
1755            ),
1756            Ok(false) => {
1757                if let Some(s) = self.send.as_mut() {
1758                    s.due = now;
1759                }
1760                self.flush(clock, true);
1761            }
1762            Ok(true) => self.end_typing(clock, None),
1763            Err(err) => self.end_typing(clock, Some(err)),
1764        }
1765    }
1766
1767    /// Finish the send: its result, or `error` (the send is stopped). A
1768    /// write that is stopped first runs its cleanup in turns
1769    /// ([`Send::stopping`]); its reply is then `error`, with what the
1770    /// cleanup could not do.
1771    fn end_typing(&mut self, clock: &dyn Clock, error: Option<Error>) {
1772        let Some(mut send) = self.send.take() else {
1773            return;
1774        };
1775        if let (Some(err), Some(e)) = (&error, self.emu.as_mut())
1776            && send.transfer
1777            && e.transferring()
1778        {
1779            if send.stopping.is_none() && !matches!(err, Error::Halted(_)) {
1780                e.stop_transfer();
1781                let now = clock.now_ms();
1782                send.stopping = Some(err.clone());
1783                send.started = now;
1784                send.due = now;
1785                self.send = Some(send);
1786                return;
1787            }
1788            // Its cleanup ran out of time too: given up.
1789            e.abandon_transfer();
1790        }
1791        let error = match (send.stopping.take(), error) {
1792            (Some(why), None) => Some(match self.emu.as_mut().map(Emulator::transfer_result) {
1793                Some(Err(e)) if e.to_string() != crate::transfer::STOPPED => {
1794                    format!("{why}; {e}").into()
1795                }
1796                _ => why,
1797            }),
1798            (Some(why), Some(e)) => Some(format!("{why}; {e}").into()),
1799            (None, e) => e,
1800        };
1801        // The delay counts from its end.
1802        self.autosave.touch(clock.now_ms());
1803        let mut bytes = None;
1804        let result = match (error, self.emu.as_mut()) {
1805            (_, None) => Err("no ROM loaded".into()),
1806            (None, Some(e)) if send.transfer => e.transfer_result().and_then(|(r, file)| {
1807                bytes = file.map(|f| ("data", f));
1808                value_of(&r)
1809            }),
1810            (None, Some(e)) => e.typing_result().and_then(|r| value_of(&r)),
1811            (Some(err), Some(e)) => {
1812                e.stop_typing();
1813                e.stop_transfer();
1814                Err(err)
1815            }
1816        };
1817        if send.transfer {
1818            // What the server drew is gone; the memory changed.
1819            if let Some(e) = self.emu.as_mut() {
1820                e.reshow();
1821            }
1822            self.watch.force = true;
1823        }
1824        // The status says the screen is live again before its frame.
1825        if send.freezes {
1826            self.send_status();
1827        }
1828        match &result {
1829            Err(e @ Error::Halted(_)) => {
1830                let e = e.clone();
1831                self.halt(clock, e);
1832            }
1833            _ => self.set_running(clock, self.lp.running),
1834        }
1835        self.respond(clock, send.tag, result, bytes);
1836    }
1837
1838    /// Send what the calculator sent on a serial port the page holds, the
1839    /// status if it changed, the errors, the keys and a frame if
1840    /// they changed (none of these while a long send holds them; a frame
1841    /// between passes only every [`Pacing::frame_ms`] unless `now`), and
1842    /// look at the user memory if that is due.
1843    fn flush(&mut self, clock: &dyn Clock, now: bool) {
1844        // The serial port is not the screen: a send does not hold it.
1845        // Gathered between passes, as frames are.
1846        if self.serial
1847            && let Some(e) = self.emu.as_mut()
1848        {
1849            self.serial_out.held.extend(e.machine_mut().serial_drain());
1850            let slack = self.lp.pacing.timer_slack_ms;
1851            if let Some(bytes) = self.serial_out.take(clock.now_ms(), slack, now) {
1852                self.event(Event::Serial(SerialEvent { bytes }));
1853            }
1854        }
1855        let frozen = self.send.as_ref().is_some_and(|s| s.freezes);
1856        if !frozen && let Some(e) = self.emu.as_mut() {
1857            let errors = e.take_errors();
1858            let keys = e.keys_if_changed();
1859            let t = clock.now_ms();
1860            let due = now
1861                || self
1862                    .last_frame
1863                    .is_none_or(|f| t - f >= self.lp.pacing.frame_ms);
1864            let frame = if due { e.frame_if_changed() } else { None };
1865            for err in errors {
1866                self.event(Event::Error(ErrorEvent {
1867                    message: err.to_string(),
1868                }));
1869            }
1870            if let Some(k) = keys {
1871                self.event(Event::Keys(k));
1872            }
1873            if let Some(f) = frame {
1874                self.last_frame = Some(t);
1875                self.event(Event::Frame(f));
1876            }
1877            // The menu keys while the ROM waits for a key, no send
1878            // typing or writing (its RAM is whole then).
1879            if self.send.is_none()
1880                && let Some(e) = self.emu.as_mut()
1881                && pacing::asleep(e)
1882                && let Some(m) = e.menu_if_changed()
1883            {
1884                self.event(Event::Menu(m));
1885            }
1886        }
1887        self.send_status();
1888        self.poll_memory(clock);
1889        self.poll_save(clock);
1890    }
1891
1892    /// The machine is in a state worth keeping: no send or write in
1893    /// progress, the CPU asleep with no key down or queued, not halted.
1894    fn settled(&self) -> bool {
1895        self.send.is_none()
1896            && self.halted.is_none()
1897            && self.emu.as_ref().is_some_and(pacing::asleep)
1898    }
1899
1900    /// Hand the state to the host if a save is due and the machine has
1901    /// settled (`protocol/autosave.rs`).
1902    fn poll_save(&mut self, clock: &dyn Clock) {
1903        let settled = self.settled();
1904        if self
1905            .autosave
1906            .poll(clock.now_ms(), self.lp.pacing.timer_slack_ms, settled)
1907        {
1908            self.emit_save();
1909        }
1910    }
1911
1912    fn emit_save(&mut self) {
1913        let Some(e) = self.emu.as_ref() else {
1914            return;
1915        };
1916        let saved = Saved {
1917            model: e.model().name(),
1918            rom_name: self.rom_name.clone(),
1919            cycles: e.machine().cycles(),
1920            state: e.save_state(),
1921        };
1922        self.autosave.clear();
1923        self.autosave.saves += 1;
1924        self.out.push(Output::Save(saved));
1925    }
1926
1927    fn send_status(&mut self) {
1928        let status = self.status();
1929        if self.last_status.as_ref() != Some(&status) {
1930            self.last_status = Some(status.clone());
1931            self.event(Event::Status(status));
1932        }
1933    }
1934
1935    /// Tell a watching page that the user memory changed, if a look is
1936    /// due and shows it (see [`watch`]): not while the machine computes,
1937    /// nor while a send types.
1938    fn poll_memory(&mut self, clock: &dyn Clock) {
1939        let quiet = self.send.is_none()
1940            && self
1941                .emu
1942                .as_ref()
1943                .is_none_or(|e| !self.lp.running || pacing::asleep(e));
1944        if self.watch.poll(self.emu.as_ref(), quiet, clock) {
1945            self.event(Event::MemoryChanged(MemoryChanged {}));
1946        }
1947    }
1948}