Skip to main content

saturnus_objects/
screen.rs

1//! What has the keyboard: the stack (the ROM's top-level outer loop), an
2//! open command line, a halted program, or an application's own loop (an
3//! input form, a choose box, a message box, the graphics screen, the 48's
4//! EquationWriter, the interactive stack, an object edited on the command
5//! line, the MatrixWriter), read from RAM without pressing a key; the
6//! display only where RAM gave no sign (wiki: hardware/ui-state).
7//!
8//! The signals, observed on the 48SX (ROM J), 48GX (ROM R) and 49G (ROM
9//! 2.10 and 1.19-6) while the ROM waits for a key:
10//!
11//! - The RPL return stack (between the saved `HeapStart` and the saved B):
12//!   its bottom entries are the system outer loop's own frame; while the
13//!   stack has the keyboard, the sixth entry from the top (under the key
14//!   wait's four entries and the calling loop's own return into it) is
15//!   that same outer-loop frame. Any other loop (a
16//!   parameterized outer loop: forms, choose and message boxes, the
17//!   graphics screen, `INPUT`, `WAIT`, the interactive stack; the 48's
18//!   equation writer) puts its own frame there. A halted program leaves
19//!   its frames on the return stack with a new outer loop above them, so
20//!   each halted program adds one more copy of the outer-loop frame.
21//! - The temporary environments (RPLMAN 13.1): input forms bind named
22//!   temporaries (`IF` on the 48GX, `IfMenu`, `CurrentField`, ... on the
23//!   49G), the 49G's choose box binds `NbElm` and others. The 48SX's and
24//!   48GX's EquationWriter binds `ploc`, `FontGauge` and others: newest
25//!   in entry mode, under one environment binding only `SavedUI` in
26//!   selection mode, under `SavedUI` and `SAVEDDEPTH EXITFCN EnvOK`
27//!   (48SX: `EXITFCN EnvOK`) in scrolling mode. The 49G's equation writer
28//!   binds only unnamed temporaries and edits on the command line: it
29//!   reads as INPUT does.
30//! - The types of the objects bound to unnamed temporaries (observed on
31//!   48SX J, 48GX R, 49G 2.10 and 1.19-6):
32//!   - The interactive stack binds a command and three system binaries
33//!     (48, under `SavedUI`), or eight objects: a system binary, any, a
34//!     command, a system binary, a command, a system binary, a string, a
35//!     program (49G).
36//!   - An object edited on the command line (▼, EDIT, VISIT, the
37//!     interactive stack's EDIT, the 49G's TOOL EDIT) binds a command, a
38//!     system binary, a command and a string, as `INPUT` does; the
39//!     environment under it (under its `SavedUI` on the 48) binds the
40//!     edited object alone. Under `INPUT` there is a named one, a system
41//!     binary (its options) or the stack's own (a command).
42//!   - The 48's MatrixWriter binds 22: a system binary, any, a command, a
43//!     system binary, then others, under `SavedUI`; the 49G's names `_IDX`
44//!     and `_TAB2`.
45//! - The display: the stack display's GROB pointer equals the PICT
46//!   pointer while the graphics screen shows.
47//! - The 48GX's choose and message boxes bind only unnamed temporaries,
48//!   so they are told apart on the display: a framed box with a two-dot
49//!   shadow, a choose box with a dark (inverted) row inside it.
50
51use saturnus_core::{Machine, Model};
52use serde::Serialize;
53
54use crate::cmdline::{self, EditorLayout};
55use crate::error::Error;
56use crate::object::{Memory, Object, decode_at};
57use crate::prolog::ObjectType;
58use crate::prolog::ObjectType::{Program, String as Str, SystemBinary as Bint};
59
60type Result<T, E = Error> = std::result::Result<T, E>;
61
62/// Most return-stack entries believed (more means the pointers are not
63/// the ROM's).
64const MAX_DEPTH: u32 = 4096;
65/// Most temporary environments walked.
66const MAX_ENVIRONMENTS: usize = 64;
67/// Most temporaries read per environment.
68const MAX_BINDINGS: u32 = 512;
69/// Entries the key wait itself puts on the return stack, above the loop
70/// that called it.
71const KEY_WAIT: u32 = 4;
72/// The entry from the top (1-based) that holds the calling loop's frame:
73/// under the key wait's entries and the loop's own return into the wait.
74const LOOP_FRAME: u32 = KEY_WAIT + 2;
75
76/// Where a model's ROM keeps what the screen state is read from (wiki:
77/// hardware/ui-state). The `*_ptr` fields hold 5-nibble pointers.
78#[derive(Clone, Copy, Debug, PartialEq, Eq)]
79pub struct ScreenLayout {
80    /// The bottom of the return stack (`HeapStart` in the 1991 address
81    /// list).
82    pub return_bottom_ptr: u32,
83    /// The saved B, the return stack's top (`FramePtr`).
84    pub return_top_ptr: u32,
85    /// The newest temporary environment (`local_vars`).
86    pub environments_ptr: u32,
87    /// The GROB the display shows below the header (`Stk_56line_GROB_ptr`).
88    pub shown_grob_ptr: u32,
89    /// PICT (`graph_GROB_ptr`).
90    pub pict_ptr: u32,
91    /// Return-stack entries at the stack with no program halted.
92    pub base_depth: u32,
93    /// Which entry from the bottom (1 = the bottom one) is the outer
94    /// loop's frame.
95    pub outer_frame: u32,
96}
97
98impl ScreenLayout {
99    /// 48SX (ROM J): the 1991 address list's locations.
100    pub const HP48SX: ScreenLayout = ScreenLayout {
101        return_bottom_ptr: 0x7056F,
102        return_top_ptr: 0x70574,
103        environments_ptr: 0x70583,
104        shown_grob_ptr: 0x7055B,
105        pict_ptr: 0x70565,
106        base_depth: 8,
107        outer_frame: 3,
108    };
109    /// 48GX (ROM R): the 48SX's plus #1017F.
110    pub const HP48GX: ScreenLayout = ScreenLayout {
111        return_bottom_ptr: 0x806EE,
112        return_top_ptr: 0x806F3,
113        environments_ptr: 0x80702,
114        shown_grob_ptr: 0x806DA,
115        pict_ptr: 0x806E4,
116        base_depth: 8,
117        outer_frame: 3,
118    };
119    /// 49G (ROM 2.10): the 48GX's addresses; one more entry at the bottom.
120    pub const HP49G: ScreenLayout = ScreenLayout {
121        base_depth: 9,
122        outer_frame: 4,
123        ..Self::HP48GX
124    };
125
126    /// The layout of `model`, or `None` where there is none (as
127    /// [`EditorLayout::of`]).
128    pub fn of(model: Model) -> Option<ScreenLayout> {
129        match model {
130            Model::Hp48sx => Some(Self::HP48SX),
131            Model::Hp48gx => Some(Self::HP48GX),
132            Model::Hp49g => Some(Self::HP49G),
133            Model::Hp38g
134            | Model::Hp39g
135            | Model::Hp40g
136            | Model::Hp42s
137            | Model::Hp27s
138            | Model::Hp17bii
139            | Model::Hp17b
140            | Model::Hp28s
141            | Model::Hp19bii => None,
142        }
143    }
144}
145
146/// What has the keyboard.
147#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
148#[serde(rename_all = "camelCase")]
149pub enum Kind {
150    /// The stack, no command line open, no program halted.
151    Stack,
152    /// The stack with a command line open.
153    CommandLine,
154    /// The stack, with one or more programs halted (HALT, PROMPT).
155    Halted,
156    /// An input form (48GX, 49G).
157    InputForm,
158    /// A choose box.
159    ChooseBox,
160    /// A message box (MSGBOX, the 49G's error box).
161    Message,
162    /// The graphics screen (PICTURE, PVIEW, a plot).
163    Graphics,
164    /// The 48SX's or 48GX's EquationWriter in entry or selection mode.
165    /// Its working objects lie on the stack above the user's levels while
166    /// it is open.
167    EquationWriter,
168    /// The 48SX's or 48GX's EquationWriter in scrolling mode (▼ on an
169    /// algebraic at the stack, or PICTURE in the writer): ENTER does
170    /// nothing there, CANCEL returns to the writer.
171    EquationView,
172    /// The interactive stack (▲ at the stack; the 49G's HIST): ▲▼ move
173    /// its pointer, the menu keys act on the level it points at, ENTER or
174    /// CANCEL leaves and keeps what was done.
175    InteractiveStack,
176    /// An object edited on the command line inside another loop (▼ on a
177    /// stack level, EDIT, VISIT, the interactive stack's EDIT, the 49G's
178    /// TOOL EDIT): ENTER puts the edited object back, CANCEL restores the
179    /// original. The object is off the stack meanwhile.
180    ObjectEdit,
181    /// The MatrixWriter (◀MATRIX, the 49G's MTRW, ▼ on a matrix), also
182    /// with a cell being typed ([`Screen::command_line`]).
183    MatrixWriter,
184    /// Another loop reads the keys with the command line open: a program
185    /// waits for input (INPUT), or an editor uses the line (the 49G's
186    /// equation writer).
187    Input,
188    /// Another loop has the keyboard (WAIT, a catalog or browser), or the
189    /// state could not be read.
190    Unknown,
191}
192
193/// Where a [`Screen::kind`] came from.
194#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
195#[serde(rename_all = "camelCase")]
196pub enum Source {
197    /// RAM.
198    Memory,
199    /// The display's dots.
200    Display,
201}
202
203/// The `uiState` protocol answer.
204#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
205#[serde(rename_all = "camelCase")]
206pub struct Screen {
207    /// What has the keyboard.
208    pub kind: Kind,
209    /// Where `kind` came from.
210    pub from: Source,
211    /// The stack's own loop reads the keys (also with a command line open
212    /// or a program halted).
213    pub stack_in_control: bool,
214    /// Programs halted (HALT, PROMPT), waiting for CONT or KILL.
215    pub halted: u32,
216    /// The editor's command line is open (at the stack, in a form's
217    /// field, or for INPUT).
218    pub command_line: bool,
219}
220
221fn field(mem: &dyn Memory, addr: u32, len: u32) -> Result<u32> {
222    let mut v = 0;
223    for i in (0..len).rev() {
224        v = (v << 4) | u32::from(mem.nibble(addr + i).ok_or(Error::Unreadable(addr + i))?);
225    }
226    Ok(v)
227}
228
229/// The return stack as the ROM left it.
230#[derive(Clone, Debug, PartialEq, Eq)]
231pub struct ReturnStack {
232    /// The entries, top (most recent) first.
233    pub entries: Vec<u32>,
234}
235
236impl ReturnStack {
237    /// Read it through `layout`; `None` when the pointers are not the
238    /// ROM's.
239    pub fn read(mem: &dyn Memory, layout: &ScreenLayout) -> Result<Option<ReturnStack>> {
240        let bottom = field(mem, layout.return_bottom_ptr, 5)?;
241        let top = field(mem, layout.return_top_ptr, 5)?;
242        if top <= bottom || (top - bottom) % 5 != 0 || (top - bottom) / 5 > MAX_DEPTH {
243            return Ok(None);
244        }
245        let depth = (top - bottom) / 5;
246        let mut entries = Vec::with_capacity(depth as usize);
247        for i in 1..=depth {
248            entries.push(field(mem, top - 5 * i, 5)?);
249        }
250        Ok(Some(ReturnStack { entries }))
251    }
252
253    /// Entry `i` from the top, 1-based.
254    fn top(&self, i: u32) -> Option<u32> {
255        self.entries.get(i.checked_sub(1)? as usize).copied()
256    }
257
258    /// Entry `j` from the bottom, 1-based.
259    fn bottom(&self, j: u32) -> Option<u32> {
260        let n = self.entries.len();
261        self.entries.get(n.checked_sub(j as usize)?).copied()
262    }
263
264    /// Whether the stack's outer loop reads the keys, and how many
265    /// programs are halted below it; `None` when the entries do not have
266    /// the outer loop's shape at the bottom.
267    pub fn control(&self, layout: &ScreenLayout) -> Option<(bool, u32)> {
268        if (self.entries.len() as u32) < layout.base_depth || self.bottom(1)? != 0 {
269            return None;
270        }
271        let outer = self.bottom(layout.outer_frame)?;
272        if outer == 0 {
273            return None;
274        }
275        let copies = self.entries.iter().filter(|&&e| e == outer).count() as u32;
276        let in_control = self.top(LOOP_FRAME)? == outer;
277        Some((in_control, copies.saturating_sub(1)))
278    }
279}
280
281/// One temporary environment's bindings.
282#[derive(Clone, Debug, Default, PartialEq, Eq)]
283pub struct Environment {
284    /// The names it binds, in order, without a leading `'`.
285    pub names: Vec<String>,
286    /// The bindings with no name (`NULLLAM`, or a name that does not
287    /// decode).
288    pub unnamed: u32,
289    /// The type of each bound object, every binding in memory order (named
290    /// or not): `None` for one without an object prolog (a command: a
291    /// primitive or a word in ROM).
292    pub types: Vec<Option<ObjectType>>,
293}
294
295impl Environment {
296    /// Whether it binds `name`.
297    pub fn binds(&self, name: &str) -> bool {
298        self.names.iter().any(|n| n == name)
299    }
300
301    /// The types of its objects when it binds no names, else `None`.
302    fn unnamed_types(&self) -> Option<&[Option<ObjectType>]> {
303        self.names.is_empty().then_some(self.types.as_slice())
304    }
305
306    /// Whether it binds `SavedUI` and nothing else (the 48's
307    /// parameterized outer loop's saved state).
308    fn only_saved_ui(&self) -> bool {
309        self.names == ["SavedUI"] && self.unnamed == 0
310    }
311}
312
313/// The temporary environments, newest first.
314pub fn environments(mem: &dyn Memory, layout: &ScreenLayout) -> Result<Vec<Environment>> {
315    let mut envs = Vec::new();
316    let mut a = field(mem, layout.environments_ptr, 5)?;
317    for _ in 0..MAX_ENVIRONMENTS {
318        let link = field(mem, a, 5)?;
319        if link == 0 {
320            break;
321        }
322        let mut env = Environment::default();
323        let mut p = a + 10;
324        let mut n = 0;
325        while p + 10 <= a + link && n < MAX_BINDINGS {
326            let name = field(mem, p, 5)?;
327            match decode_at(name, mem) {
328                Ok(Object::LocalName { value }) if !value.trim_start_matches('\'').is_empty() => {
329                    env.names.push(value.trim_start_matches('\'').to_string());
330                }
331                _ => env.unnamed += 1,
332            }
333            let object = field(mem, p + 5, 5)?;
334            env.types
335                .push(field(mem, object, 5).ok().and_then(ObjectType::from_prolog));
336            p += 10;
337            n += 1;
338        }
339        envs.push(env);
340        a = a.wrapping_add(link) & 0xFFFFF;
341    }
342    Ok(envs)
343}
344
345/// The names of the temporaries bound in the newest environments, down to
346/// and including the first that binds `SavedUI` (the parameterized outer
347/// loop's saved state: what the innermost loop bound); only the newest
348/// environment when none does. Names lose a leading `'`.
349pub fn innermost_names(mem: &dyn Memory, layout: &ScreenLayout) -> Result<Vec<String>> {
350    Ok(innermost(&environments(mem, layout)?))
351}
352
353fn innermost(envs: &[Environment]) -> Vec<String> {
354    match envs.iter().position(|e| e.binds("SavedUI")) {
355        Some(i) => envs[..=i].iter().flat_map(|e| e.names.clone()).collect(),
356        None => envs.first().map(|e| e.names.clone()).unwrap_or_default(),
357    }
358}
359
360/// What the environments above a scrolling EquationWriter bind (wiki:
361/// hardware/ui-state).
362const VIEW_NAMES: [&str; 4] = ["SavedUI", "SAVEDDEPTH", "EXITFCN", "EnvOK"];
363
364/// The 48SX's or 48GX's EquationWriter from the environments, newest
365/// first: [`Kind::EquationWriter`] when its own environment (`ploc`,
366/// `FontGauge`) is the newest or only `SavedUI` ones are above it,
367/// [`Kind::EquationView`] when the scrolling mode's are; `None` when it
368/// is not open or another loop (a box, a form) is above it.
369fn equation_writer(envs: &[Environment]) -> Option<Kind> {
370    let at = envs
371        .iter()
372        .position(|e| e.binds("ploc") && e.binds("FontGauge"))?;
373    let above = &envs[..at];
374    if above.is_empty() {
375        return Some(Kind::EquationWriter);
376    }
377    if above.iter().any(|e| e.unnamed > 0 || e.names.is_empty()) {
378        return None;
379    }
380    let only = |allowed: &[&str]| {
381        above
382            .iter()
383            .all(|e| e.names.iter().all(|n| allowed.contains(&n.as_str())))
384    };
385    if only(&["SavedUI"]) {
386        return Some(Kind::EquationWriter);
387    }
388    if only(&VIEW_NAMES) && above.iter().any(|e| e.binds("EnvOK")) {
389        return Some(Kind::EquationView);
390    }
391    None
392}
393
394/// The interactive stack from the newest environment (wiki:
395/// hardware/ui-state): the 48's binds a command and three system
396/// binaries under one binding only `SavedUI`; the 49G's eight objects.
397fn interactive_stack(envs: &[Environment]) -> bool {
398    let Some(types) = envs.first().and_then(Environment::unnamed_types) else {
399        return false;
400    };
401    match types {
402        [None, Some(Bint), Some(Bint), Some(Bint)] => {
403            envs.get(1).is_some_and(Environment::only_saved_ui)
404        }
405        [
406            Some(Bint),
407            _,
408            None,
409            Some(Bint),
410            None,
411            Some(Bint),
412            Some(Str),
413            Some(Program),
414        ] => true,
415        _ => false,
416    }
417}
418
419/// An object edited on the command line inside another loop (wiki:
420/// hardware/ui-state): the newest environment binds a command, a system
421/// binary, a command and a string, and the next one (past one binding
422/// only `SavedUI`, on the 48) binds one unnamed object, the edited one.
423/// `INPUT` binds the same four; under them it has a named environment, a
424/// system binary (its options) or the stack's own (a command).
425fn object_edit(envs: &[Environment]) -> bool {
426    let Some(types) = envs.first().and_then(Environment::unnamed_types) else {
427        return false;
428    };
429    if !matches!(types, [None, Some(Bint), None, Some(Str)]) {
430        return false;
431    }
432    let mut below = &envs[1..];
433    if below.first().is_some_and(Environment::only_saved_ui) {
434        below = &below[1..];
435    }
436    below
437        .first()
438        .and_then(Environment::unnamed_types)
439        .is_some_and(|t| matches!(t, [Some(edited)] if *edited != Bint))
440}
441
442/// The MatrixWriter from the newest environment (wiki:
443/// hardware/ui-state): the 49G's names `_IDX` and `_TAB2`; the 48's binds
444/// 22 unnamed objects, starting with a system binary, any, a command and a
445/// system binary, under one binding only `SavedUI`.
446fn matrix_writer(envs: &[Environment]) -> bool {
447    let Some(newest) = envs.first() else {
448        return false;
449    };
450    if newest.binds("_IDX") && newest.binds("_TAB2") {
451        return true;
452    }
453    newest
454        .unnamed_types()
455        .is_some_and(|t| t.len() == 22 && matches!(t, [Some(Bint), _, None, Some(Bint), ..]))
456        && envs.get(1).is_some_and(Environment::only_saved_ui)
457}
458
459/// A framed box with a two-dot shadow on the display (the 48GX's and the
460/// 49G's message and choose boxes): `Some(true)` when a row inside it is
461/// dark (a choose box's highlighted item or title rule), `Some(false)`
462/// without, `None` when there is no such box.
463pub fn framed_box(pixels: &[Vec<bool>]) -> Option<bool> {
464    let h = pixels.len();
465    let dark = |x: usize, y: usize| {
466        pixels
467            .get(y)
468            .and_then(|r| r.get(x))
469            .copied()
470            .unwrap_or(false)
471    };
472    for (y0, row) in pixels.iter().enumerate().take(h.saturating_sub(4)) {
473        let w = row.len();
474        let mut x = 0;
475        while x < w {
476            if !dark(x, y0) {
477                x += 1;
478                continue;
479            }
480            let x0 = x;
481            while x < w && dark(x, y0) {
482                x += 1;
483            }
484            let x1 = x - 1;
485            if x1 < x0 + 30 {
486                continue;
487            }
488            // The bottom border: the first row under the top whose dots
489            // run from the left edge to the shadow.
490            let Some(y1) =
491                (y0 + 3..h.saturating_sub(1)).find(|&y| (x0..=x1 + 1).all(|x| dark(x, y)))
492            else {
493                continue;
494            };
495            let edges = (y0 + 1..y1)
496                .all(|y| dark(x0, y) && dark(x1, y) && dark(x1 + 1, y) && !dark(x0 + 1, y));
497            let shadow = (x0 + 1..=x1 + 1).all(|x| dark(x, y1 + 1)) && !dark(x0, y1 + 1);
498            if !edges || !shadow {
499                continue;
500            }
501            let inner = (x0 + 2..=x1.saturating_sub(2)).count().max(1);
502            let banded = (y0 + 1..y1).any(|y| {
503                (x0 + 2..=x1.saturating_sub(2))
504                    .filter(|&x| dark(x, y))
505                    .count()
506                    * 10
507                    >= inner * 9
508            });
509            return Some(banded);
510        }
511    }
512    None
513}
514
515/// Read the screen state through the layouts, with `pixels` the display
516/// for the boxes RAM does not name.
517pub fn read(
518    mem: &dyn Memory,
519    layout: &ScreenLayout,
520    editor: &EditorLayout,
521    pixels: &[Vec<bool>],
522) -> Result<Screen> {
523    let command_line = cmdline::read(mem, editor)?.active;
524    let unknown = Screen {
525        kind: Kind::Unknown,
526        from: Source::Memory,
527        stack_in_control: false,
528        halted: 0,
529        command_line,
530    };
531    let Some(rs) = ReturnStack::read(mem, layout)? else {
532        return Ok(unknown);
533    };
534    let Some((in_control, halted)) = rs.control(layout) else {
535        return Ok(unknown);
536    };
537    let at = |kind, from| Screen {
538        kind,
539        from,
540        stack_in_control: in_control,
541        halted,
542        command_line,
543    };
544    if in_control {
545        let kind = if command_line {
546            Kind::CommandLine
547        } else if halted > 0 {
548            Kind::Halted
549        } else {
550            Kind::Stack
551        };
552        return Ok(at(kind, Source::Memory));
553    }
554    if field(mem, layout.shown_grob_ptr, 5)? == field(mem, layout.pict_ptr, 5)? {
555        return Ok(at(Kind::Graphics, Source::Memory));
556    }
557    let envs = environments(mem, layout)?;
558    let names = innermost(&envs);
559    let has = |n: &str| names.iter().any(|m| m == n);
560    if has("IF") || has("IfMenu") || has("CurrentField") {
561        return Ok(at(Kind::InputForm, Source::Memory));
562    }
563    if has("NbElm") {
564        return Ok(at(Kind::ChooseBox, Source::Memory));
565    }
566    if has("PlotEnv") {
567        return Ok(at(Kind::Graphics, Source::Memory));
568    }
569    match framed_box(pixels) {
570        Some(true) => return Ok(at(Kind::ChooseBox, Source::Display)),
571        Some(false) => return Ok(at(Kind::Message, Source::Display)),
572        None => {}
573    }
574    // The 48's writer never has the command line open itself: an open
575    // line above it (EDIT in selection mode) is an editor of its own.
576    if !command_line && let Some(kind) = equation_writer(&envs) {
577        return Ok(at(kind, Source::Memory));
578    }
579    // A cell typed into keeps the MatrixWriter's own environment newest.
580    if matrix_writer(&envs) {
581        return Ok(at(Kind::MatrixWriter, Source::Memory));
582    }
583    if !command_line && interactive_stack(&envs) {
584        return Ok(at(Kind::InteractiveStack, Source::Memory));
585    }
586    if command_line && object_edit(&envs) {
587        return Ok(at(Kind::ObjectEdit, Source::Memory));
588    }
589    if command_line {
590        return Ok(at(Kind::Input, Source::Memory));
591    }
592    Ok(at(Kind::Unknown, Source::Memory))
593}
594
595/// The screen state of `machine` (48SX, 48GX, 49G).
596pub fn screen(machine: &Machine) -> Result<Screen> {
597    let model = machine.model();
598    let editor = EditorLayout::require(model)?;
599    let layout = ScreenLayout::of(model).ok_or(Error::NoCommandLine(model))?;
600    read(machine, &layout, &editor, &machine.lcd().pixels)
601}
602
603#[cfg(test)]
604mod tests {
605    use super::*;
606    use std::collections::HashMap;
607
608    #[derive(Default)]
609    struct Ram(HashMap<u32, u8>);
610
611    impl Memory for Ram {
612        fn nibble(&self, addr: u32) -> Option<u8> {
613            Some(self.0.get(&addr).copied().unwrap_or(0))
614        }
615    }
616
617    impl Ram {
618        fn put(&mut self, addr: u32, value: u32, len: u32) {
619            for i in 0..len {
620                self.0.insert(addr + i, ((value >> (4 * i)) & 15) as u8);
621            }
622        }
623
624        /// A return stack, bottom entry first, at #71000.
625        fn returns(&mut self, l: &ScreenLayout, bottom_first: &[u32]) {
626            self.put(l.return_bottom_ptr, 0x71000, 5);
627            for (i, e) in bottom_first.iter().enumerate() {
628                self.put(0x71000 + 5 * i as u32, *e, 5);
629            }
630            self.put(l.return_top_ptr, 0x71000 + 5 * bottom_first.len() as u32, 5);
631        }
632    }
633
634    const KEYS: [u32; 4] = [0x4204B, 0x420AF, 0x42190, 0x421C2];
635
636    fn stack(extra: &[u32]) -> Vec<u32> {
637        let mut v = vec![0, 0x38598, 0x385B6];
638        v.extend_from_slice(extra);
639        v.extend_from_slice(&KEYS);
640        v
641    }
642
643    fn read_sx(ram: &Ram) -> Screen {
644        read(ram, &ScreenLayout::HP48SX, &EditorLayout::HP48SX, &[]).unwrap()
645    }
646
647    #[test]
648    fn the_return_stack_tells_the_stack_from_a_loop_and_counts_halts() {
649        // The 48SX's return stack as observed (wiki: hardware/ui-state).
650        let l = ScreenLayout::HP48SX;
651        let mut ram = Ram::default();
652        ram.put(l.shown_grob_ptr, 0x86907, 5);
653        ram.put(l.pict_ptr, 0xCE017, 5);
654        ram.returns(&l, &stack(&[0x385CA]));
655        let s = read_sx(&ram);
656        assert_eq!(
657            (s.kind, s.stack_in_control, s.halted),
658            (Kind::Stack, true, 0)
659        );
660        // A halted program: its frames, then a new outer loop.
661        ram.returns(
662            &l,
663            &stack(&[0x385D4, 0x3A807, 0x40BC4, 0x143DE, 0x385B6, 0x385CA]),
664        );
665        let s = read_sx(&ram);
666        assert_eq!(
667            (s.kind, s.stack_in_control, s.halted),
668            (Kind::Halted, true, 1)
669        );
670        // A parameterized outer loop (the interactive stack): no names, no box.
671        ram.returns(
672            &l,
673            &stack(&[
674                0x385D4, 0x40DBB, 0x43757, 0x4374D, 0x38AF5, 0x38B3B, 0x38B22,
675            ]),
676        );
677        let s = read_sx(&ram);
678        assert_eq!((s.kind, s.stack_in_control), (Kind::Unknown, false));
679        // With the command line open in that loop: INPUT.
680        ram.put(EditorLayout::HP48SX.line, 2, 1);
681        ram.put(EditorLayout::HP48SX.text_end_ptr, 0x7FEE3, 5);
682        ram.put(EditorLayout::HP48SX.stack_end_ptr, 0x7FEB3, 5);
683        assert_eq!(read_sx(&ram).kind, Kind::Input);
684        // The graphics screen: the shown GROB is PICT.
685        ram.put(l.shown_grob_ptr, 0xCE017, 5);
686        assert_eq!(read_sx(&ram).kind, Kind::Graphics);
687        // Pointers that are not the ROM's.
688        ram.put(l.return_top_ptr, 0x70FFF, 5);
689        assert_eq!(read_sx(&ram).kind, Kind::Unknown);
690    }
691
692    #[test]
693    fn named_temporaries_name_the_loop() {
694        let l = ScreenLayout::HP48GX;
695        let mut ram = Ram::default();
696        ram.returns(&l, &stack(&[0x385D4, 0x38AF5, 0x38B3B, 0x38B22]));
697        ram.put(l.shown_grob_ptr, 1, 5);
698        // Local names: prolog #02E6D, length, characters.
699        let lam = |ram: &mut Ram, at: u32, name: &str| {
700            ram.put(at, 0x02E6D, 5);
701            ram.put(at + 5, name.len() as u32, 2);
702            for (i, b) in name.bytes().enumerate() {
703                ram.put(at + 7 + 2 * i as u32, u32::from(b), 2);
704            }
705        };
706        lam(&mut ram, 0x90000, "IF");
707        lam(&mut ram, 0x90100, "SavedUI");
708        // Two environments of one binding each, then the end.
709        ram.put(l.environments_ptr, 0xA0000, 5);
710        ram.put(0xA0000, 20, 5);
711        ram.put(0xA000A, 0x90000, 5);
712        ram.put(0xA0014, 20, 5);
713        ram.put(0xA001E, 0x90100, 5);
714        assert_eq!(innermost_names(&ram, &l).unwrap(), ["IF", "SavedUI"]);
715        let s = read(&ram, &l, &EditorLayout::HP48GX, &[]).unwrap();
716        assert_eq!((s.kind, s.from), (Kind::InputForm, Source::Memory));
717        // A box opened over the form binds its own environment above:
718        // the form's names are below its SavedUI.
719        ram.put(l.environments_ptr, 0xA1000, 5);
720        ram.put(0xA1000, 20, 5);
721        ram.put(0xA100A, 0x90100, 5);
722        ram.put(0xA1014, 0, 5);
723        assert_eq!(innermost_names(&ram, &l).unwrap(), ["SavedUI"]);
724    }
725
726    /// A loop that is not the stack's (no box on the display), with the
727    /// environments `envs`, newest first, each a list of bindings: a name,
728    /// optionally `:` and the bound object's type (`bint`, `real`, `str`,
729    /// `prog`, `arr`, `list`, `name`, `hxs`; else a command), or `:type`
730    /// alone for an unnamed one (`""`: an unnamed command).
731    fn in_loop(l: &ScreenLayout, envs: &[&[&str]]) -> Ram {
732        let mut ram = Ram::default();
733        ram.returns(l, &stack(&[0x385D4, 0x38AF5, 0x38B3B, 0x38B22]));
734        ram.put(l.shown_grob_ptr, 1, 5);
735        let mut names = 0x90000;
736        let mut objects = 0xB0000;
737        let mut a = 0xA0000;
738        ram.put(l.environments_ptr, a, 5);
739        for env in envs {
740            let link = 10 + 10 * env.len() as u32;
741            ram.put(a, link, 5);
742            for (i, binding) in env.iter().enumerate() {
743                let (name, ty) = binding.split_once(':').unwrap_or((binding, ""));
744                // A local name: prolog #02E6D, length, characters.
745                ram.put(names, 0x02E6D, 5);
746                ram.put(names + 5, name.len() as u32, 2);
747                for (j, b) in name.bytes().enumerate() {
748                    ram.put(names + 7 + 2 * j as u32, u32::from(b), 2);
749                }
750                ram.put(a + 10 + 10 * i as u32, names, 5);
751                names += 0x100;
752                let prolog = match ty {
753                    "bint" => 0x02911,
754                    "real" => 0x02933,
755                    "str" => 0x02A2C,
756                    "prog" => 0x02D9D,
757                    "arr" => 0x029E8,
758                    "list" => 0x02A74,
759                    "name" => 0x02E48,
760                    "hxs" => 0x02A4E,
761                    _ => 0x0312B,
762                };
763                ram.put(objects, prolog, 5);
764                ram.put(a + 15 + 10 * i as u32, objects, 5);
765                objects += 0x40;
766            }
767            a += link;
768        }
769        ram.put(a, 0, 5);
770        ram
771    }
772
773    /// Opens the command line on [`in_loop`]'s RAM: its text ends where
774    /// the environments start (the 48GX's text end pointer is theirs).
775    fn open_line(ram: &mut Ram, e: &EditorLayout) {
776        ram.put(e.line, 2, 1);
777        ram.put(e.stack_end_ptr, 0x9FFD0, 5);
778    }
779
780    const WRITER: &[&str] = &["ploc", "FontGauge", "cx", "cy"];
781
782    fn kind_gx(envs: &[&[&str]]) -> Kind {
783        let l = ScreenLayout::HP48GX;
784        read(&in_loop(&l, envs), &l, &EditorLayout::HP48GX, &[])
785            .unwrap()
786            .kind
787    }
788
789    #[test]
790    fn the_equation_writers_environments_name_its_modes() {
791        // Entry mode: the writer's own environment is the newest.
792        assert_eq!(kind_gx(&[WRITER, &["SavedUI"]]), Kind::EquationWriter);
793        // Selection mode: one environment binding only SavedUI above it.
794        assert_eq!(
795            kind_gx(&[&["SavedUI"], WRITER, &["SavedUI"]]),
796            Kind::EquationWriter
797        );
798        // Scrolling mode: the 48GX's and the 48SX's.
799        assert_eq!(
800            kind_gx(&[
801                &["SavedUI"],
802                &["SAVEDDEPTH", "EXITFCN", "EnvOK"],
803                WRITER,
804                &["SavedUI"]
805            ]),
806            Kind::EquationView
807        );
808        assert_eq!(
809            kind_gx(&[&["SavedUI"], &["EXITFCN", "EnvOK"], WRITER]),
810            Kind::EquationView
811        );
812        // A message box over the writer binds unnamed temporaries: not
813        // selection mode.
814        assert_eq!(
815            kind_gx(&[&["SavedUI"], &["", ""], WRITER, &["SavedUI"]]),
816            Kind::Unknown
817        );
818        // Other names above the writer: not its own loop.
819        assert_eq!(
820            kind_gx(&[&["SavedUI"], &["SAVEDDEPTH", "EXITFCN"], WRITER]),
821            Kind::Unknown
822        );
823        // A form opened over the writer names itself.
824        assert_eq!(kind_gx(&[&["IF", "SavedUI"], WRITER]), Kind::InputForm);
825        // Without the writer's names: nothing to tell.
826        assert_eq!(kind_gx(&[&["SavedUI"]]), Kind::Unknown);
827        // A command line open above the writer (EDIT in selection mode):
828        // an editor of its own, not the writer.
829        let l = ScreenLayout::HP48GX;
830        let e = EditorLayout::HP48GX;
831        let mut ram = in_loop(&l, &[&["SavedUI"], WRITER, &["SavedUI"]]);
832        open_line(&mut ram, &e);
833        let s = read(&ram, &l, &e, &[]).unwrap();
834        assert_eq!((s.kind, s.command_line), (Kind::Input, true));
835        let l = ScreenLayout::HP48GX;
836        let ram = in_loop(&l, &[&["SavedUI", ""], WRITER]);
837        assert_eq!(
838            environments(&ram, &l).unwrap()[0],
839            Environment {
840                names: vec!["SavedUI".into()],
841                unnamed: 1,
842                types: vec![None, None],
843            }
844        );
845    }
846
847    /// Reads `envs` on the 48GX with the command line open or not.
848    fn kind_with_line(envs: &[&[&str]], line: bool) -> Screen {
849        let l = ScreenLayout::HP48GX;
850        let e = EditorLayout::HP48GX;
851        let mut ram = in_loop(&l, envs);
852        if line {
853            open_line(&mut ram, &e);
854        }
855        read(&ram, &l, &e, &[]).unwrap()
856    }
857
858    /// The bindings as observed (wiki: hardware/ui-state).
859    const ISTACK_48: &[&str] = &["", ":bint", ":bint", ":bint"];
860    const ISTACK_49: &[&str] = &[":bint", ":hxs", "", ":bint", "", ":bint", ":str", ":prog"];
861    const LINE: &[&str] = &["", ":bint", "", ":str"];
862    const SAVED: &[&str] = &["SavedUI:list"];
863    const LAST_STACK: &[&str] = &["", ":real", ":real"];
864
865    fn mw_48() -> Vec<&'static str> {
866        let mut v = vec![":bint", ":hxs", "", ":bint"];
867        v.resize(21, ":bint");
868        v.push(":arr");
869        v
870    }
871
872    #[test]
873    fn the_interactive_stack_reads_from_its_bindings() {
874        let k = |envs: &[&[&str]]| kind_with_line(envs, false).kind;
875        assert_eq!(k(&[ISTACK_48, SAVED, LAST_STACK]), Kind::InteractiveStack);
876        assert_eq!(k(&[ISTACK_49, LAST_STACK]), Kind::InteractiveStack);
877        // The 48's without the loop's SavedUI under it: not told.
878        assert_eq!(k(&[ISTACK_48, LAST_STACK]), Kind::Unknown);
879        // Other types: the 49G's viewer starts with two commands.
880        assert_eq!(
881            k(&[&["", "", ":str", "", "", ":bint", ":bint", ""], ISTACK_49]),
882            Kind::Unknown
883        );
884        // With a name among them: not the interactive stack.
885        assert_eq!(
886            k(&[&["x", ":bint", ":bint", ":bint"], SAVED]),
887            Kind::Unknown
888        );
889        // A command line open over it is an edit or an editor.
890        assert_eq!(kind_with_line(&[ISTACK_48, SAVED], true).kind, Kind::Input);
891    }
892
893    #[test]
894    fn an_edited_object_is_told_from_input() {
895        let k = |envs: &[&[&str]]| kind_with_line(envs, true).kind;
896        // The 48: ▼ on a real, then VISIT (a name), then EDIT from the
897        // interactive stack.
898        assert_eq!(k(&[LINE, SAVED, &[":real"], LAST_STACK]), Kind::ObjectEdit);
899        assert_eq!(k(&[LINE, SAVED, &[":name"], &[""]]), Kind::ObjectEdit);
900        assert_eq!(
901            k(&[LINE, SAVED, &[":real"], &[":bint"], ISTACK_48, SAVED]),
902            Kind::ObjectEdit
903        );
904        // The 49G binds no SavedUI.
905        assert_eq!(k(&[LINE, &[":str"], LAST_STACK]), Kind::ObjectEdit);
906        // INPUT: from the command line ('est), with options (a system
907        // binary), with local variables, from a menu key (the stack's own
908        // environment, a command).
909        assert_eq!(k(&[LINE, SAVED, &["est"], &[""]]), Kind::Input);
910        assert_eq!(k(&[LINE, SAVED, &[":bint"], &["est"]]), Kind::Input);
911        assert_eq!(k(&[LINE, SAVED, &["a:real"], &["est"]]), Kind::Input);
912        assert_eq!(k(&[LINE, SAVED, &[""]]), Kind::Input);
913        assert_eq!(k(&[LINE, &[""]]), Kind::Input);
914        assert_eq!(k(&[LINE]), Kind::Input);
915        // EDIT in the 48's EquationWriter: another SavedUI under it.
916        assert_eq!(
917            k(&[LINE, SAVED, SAVED, &["ploc", "FontGauge"], SAVED]),
918            Kind::Input
919        );
920        // Without the command line open: not an edit.
921        assert_eq!(
922            kind_with_line(&[LINE, SAVED, &[":real"]], false).kind,
923            Kind::Unknown
924        );
925    }
926
927    #[test]
928    fn the_matrix_writer_reads_from_its_bindings() {
929        let mw = mw_48();
930        let k = |envs: &[&[&str]], line| kind_with_line(envs, line);
931        let s = k(&[&mw, SAVED, &[""]], false);
932        assert_eq!((s.kind, s.command_line), (Kind::MatrixWriter, false));
933        // A cell being typed: still the MatrixWriter.
934        let s = k(&[&mw, SAVED, &[":arr"], LAST_STACK], true);
935        assert_eq!((s.kind, s.command_line), (Kind::MatrixWriter, true));
936        // Over the 48GX's statistics form: the form is under its SavedUI.
937        assert_eq!(
938            k(&[&mw, SAVED, &[""; 40], &["IF"], SAVED], false).kind,
939            Kind::MatrixWriter
940        );
941        // The 49G's names.
942        assert_eq!(
943            k(
944                &[&["", "", ":bint", "_IDX:str", "_TAB2", ":list"], &[""]],
945                true
946            )
947            .kind,
948            Kind::MatrixWriter
949        );
950        // 21 bindings, or without SavedUI under it on the 48: not told.
951        assert_eq!(k(&[&mw[..21], SAVED], false).kind, Kind::Unknown);
952        assert_eq!(k(&[&mw, &[""]], false).kind, Kind::Unknown);
953    }
954
955    fn boxed(band: bool) -> Vec<Vec<bool>> {
956        let mut p = vec![vec![false; 131]; 64];
957        let (x0, x1, y0, y1) = (17, 112, 15, 44);
958        p[y0][x0..=x1].fill(true);
959        for row in p.iter_mut().take(y1).skip(y0 + 1) {
960            row[x0] = true;
961            row[x1] = true;
962            row[x1 + 1] = true;
963        }
964        p[y1][x0..=x1 + 1].fill(true);
965        p[y1 + 1][x0 + 1..=x1 + 1].fill(true);
966        if band {
967            p[20][x0 + 2..x1 - 1].fill(true);
968        }
969        p
970    }
971
972    #[test]
973    fn a_shadowed_frame_is_a_box() {
974        assert_eq!(framed_box(&boxed(false)), Some(false));
975        assert_eq!(framed_box(&boxed(true)), Some(true));
976        assert_eq!(framed_box(&vec![vec![false; 131]; 64]), None);
977        // A filled area is not a frame.
978        assert_eq!(framed_box(&vec![vec![true; 131]; 64]), None);
979    }
980}