Skip to main content

saturnus_core/io/
keyboard.rs

1//! Keyboard matrices of the supported models (wiki: hardware/keyboard).
2//!
3//! The CPU drives OUT lines and reads back IN lines: a pressed key
4//! connects one OUT line to one IN line. The ON key is wired to IN bit 15
5//! and reads as pressed regardless of OUT. The 48SX and 48GX share one
6//! matrix ("HP48 matrix": 9 OUT x 6 IN); the 49G has its own ("HP49G
7//! matrix": 8 OUT x 8 IN, see [`super::keyboard49`]). The 38G uses the 48
8//! matrix and the 39G/40G the 49G matrix, each with its own key labels
9//! (see [`super::keyboard_aplet`]). The 42S has its own 6 OUT x 7 IN
10//! matrix with EXIT on the ON line (see [`super::keyboard42`]); the 27S
11//! and the 17B/17BII put their own keys on it (see
12//! [`super::keyboard_pioneer`]).
13//!
14//! [`Key`] is one key set across models: keys with the same label and
15//! function share a variant and a script name ("enter", "sto", "sin"),
16//! and a model only answers the keys it has ([`Key::position`]). A label
17//! sits wherever that model has it: SIN on the 38G is at the 48's COS
18//! position. The six softkeys (menu keys) are `A`-`F` on every model
19//! (their alpha letters on the 48 and 49G); "f1"-"f6" are accepted as
20//! names for them.
21
22/// Which keyboard matrix a model has.
23#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Default)]
24pub enum Layout {
25    /// HP48 SX/GX (and the 38G, which uses the same matrix).
26    #[default]
27    Hp48,
28    /// HP49G.
29    Hp49,
30    /// HP 38G: the 48 matrix with the 38G's labels, VAR and NXT positions
31    /// empty (wiki: hardware/hp38g "Keyboard").
32    Hp38,
33    /// HP 39G and 40G: the 49G matrix with the 39G's labels (wiki:
34    /// hardware/hp39g-40g "Keyboard").
35    Hp39,
36    /// HP 42S: 6 OUT x 7 IN, EXIT on IN bit 15 (wiki: hardware/hp42s
37    /// "Keyboard").
38    Hp42,
39    /// HP 27S: the 42S's matrix with the 27S's keys (wiki: hardware/hp27s
40    /// "Keyboard").
41    Hp27,
42    /// HP 17B and 17BII: the 42S's matrix with the 17B's keys (wiki:
43    /// hardware/hp17bii "Keyboard").
44    Hp17,
45    /// HP 28S: 7 OUT x 12 IN, ON on IN bit 15 (wiki: hardware/hp28s
46    /// "Keyboard").
47    Hp28,
48    /// HP 19BII: the 28S's 7 OUT x 12 IN matrix with the 19BII's keys
49    /// (wiki: hardware/hp19bii "Keyboard").
50    Hp19,
51}
52
53impl Layout {
54    /// IN lines the matrix uses: 6 on the 48 matrix, 8 on the 49G's, 7
55    /// on the 42S's, 12 on the 28S's.
56    pub fn in_mask(self) -> u16 {
57        match self {
58            Layout::Hp48 | Layout::Hp38 => 0x3F,
59            Layout::Hp42 | Layout::Hp27 | Layout::Hp17 => 0x7F,
60            Layout::Hp49 | Layout::Hp39 => 0xFF,
61            Layout::Hp28 | Layout::Hp19 => 0xFFF,
62        }
63    }
64}
65
66/// Where a key sits in a matrix.
67#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
68pub enum KeyPos {
69    /// Crossing of OUT bit `out` and the IN bits in `mask`.
70    Matrix {
71        /// OUT bit index.
72        out: usize,
73        /// IN mask (one bit).
74        mask: u16,
75    },
76    /// The ON key: IN bit 15 for any OUT.
77    On,
78}
79
80/// A calculator key.
81#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
82#[allow(missing_docs)]
83pub enum Key {
84    // Softkeys A-F (48: OUT bit 8 and #002/#10; 49G: F1-F6)
85    A,
86    B,
87    C,
88    D,
89    E,
90    F,
91    Prg,
92    Cst,
93    Var,
94    Up,
95    Nxt,
96    Sto,
97    Eval,
98    Left,
99    Down,
100    Right,
101    Cos,
102    Tan,
103    Sqrt,
104    Power,
105    Inv,
106    Enter,
107    Neg,
108    Eex,
109    Del,
110    Backspace,
111    Alpha,
112    Sin,
113    Seven,
114    Eight,
115    Nine,
116    Divide,
117    LeftShift,
118    Mth,
119    Four,
120    Five,
121    Six,
122    Multiply,
123    RightShift,
124    One,
125    Two,
126    Three,
127    Minus,
128    Quote,
129    Zero,
130    Point,
131    Space,
132    Plus,
133    // 49G only
134    Apps,
135    Mode,
136    Tool,
137    Hist,
138    Cat,
139    Eqw,
140    Symb,
141    /// The 49G's variable key "X".
142    X,
143    // 38G and 39G/40G labels
144    Plot,
145    Num,
146    Lib,
147    Math,
148    Home,
149    /// The X,T,θ key.
150    Xt,
151    LParen,
152    RParen,
153    Shift,
154    Comma,
155    Aplet,
156    Views,
157    Vars,
158    /// The 39G's d/dx key.
159    Ddx,
160    Ln,
161    Log,
162    /// The 39G's x² key.
163    Square,
164    // 42S labels
165    /// Σ+ (the 42S's first top-row key).
166    SigmaPlus,
167    /// XEQ, execute.
168    Xeq,
169    /// RCL, recall.
170    Rcl,
171    /// R↓, roll down.
172    RollDown,
173    /// x≷y, swap X and Y.
174    Swap,
175    /// R/S, run/stop.
176    Rs,
177    // 27S and 17B/17BII labels
178    /// %, percent (17B/17BII).
179    Percent,
180    /// DSP, display format (17B/17BII).
181    Dsp,
182    /// PRT, print (17B/17BII).
183    Prt,
184    /// EXIT, leave a menu: a matrix key on the 27S and 17B/17BII. On the
185    /// 42S, whose ON key is labelled EXIT, the name presses ON.
186    Exit,
187    /// INPUT, the wide key of the third row (ENTER in RPN on the 17BII).
188    Input,
189    /// =, equals.
190    Equals,
191    // 28S labels: the letter keys of its left half (its menu keys are A-F),
192    // delimiters and its own keys
193    /// The 28S's letter key A.
194    LetterA,
195    /// The 28S's letter key B.
196    LetterB,
197    /// The 28S's letter key C.
198    LetterC,
199    /// The 28S's letter key D.
200    LetterD,
201    /// The 28S's letter key E.
202    LetterE,
203    /// The 28S's letter key F.
204    LetterF,
205    /// The 28S's letter key G.
206    LetterG,
207    /// The 28S's letter key H.
208    LetterH,
209    /// The 28S's letter key I.
210    LetterI,
211    /// The 28S's letter key J.
212    LetterJ,
213    /// The 28S's letter key K.
214    LetterK,
215    /// The 28S's letter key L.
216    LetterL,
217    /// The 28S's letter key M.
218    LetterM,
219    /// The 28S's letter key N.
220    LetterN,
221    /// The 28S's letter key O.
222    LetterO,
223    /// The 28S's letter key P.
224    LetterP,
225    /// The 28S's letter key Q.
226    LetterQ,
227    /// The 28S's letter key R.
228    LetterR,
229    /// The 28S's letter key S.
230    LetterS,
231    /// The 28S's letter key T.
232    LetterT,
233    /// The 28S's letter key U.
234    LetterU,
235    /// The 28S's letter key V.
236    LetterV,
237    /// The 28S's letter key W.
238    LetterW,
239    /// The 28S's letter key X.
240    LetterX,
241    /// The 28S's letter key Y.
242    LetterY,
243    /// The 28S's letter key Z.
244    LetterZ,
245    /// #, binary integers (28S).
246    Hash,
247    /// { }, list delimiters (28S).
248    LBrace,
249    /// [ ], vector and matrix delimiters (28S).
250    LBracket,
251    /// « », program delimiters (28S).
252    Program,
253    /// LC, lowercase lock (28S).
254    Lc,
255    /// The cursor-menu key between shift and TRIG (28S).
256    Cursor,
257    /// TRIG menu (28S).
258    Trig,
259    /// SOLV menu (28S).
260    Solv,
261    /// USER menu (28S).
262    User,
263    /// DROP (28S).
264    Drop,
265    // 19BII labels on its letter half
266    /// INS, insert mode (19BII).
267    Ins,
268    /// The 19BII's ? key.
269    Question,
270    /// The 19BII's $ key.
271    Dollar,
272    /// The 19BII's : key.
273    Colon,
274    /// The ON key, wired to IN bit 15 independent of OUT.
275    On,
276}
277
278/// IN bit of the ON key.
279const ON_IN_BIT: u16 = 0x8000;
280
281impl Key {
282    /// Every key of every model, ON last.
283    pub const ALL: [Key; 126] = [
284        Key::A,
285        Key::B,
286        Key::C,
287        Key::D,
288        Key::E,
289        Key::F,
290        Key::Prg,
291        Key::Cst,
292        Key::Var,
293        Key::Up,
294        Key::Nxt,
295        Key::Sto,
296        Key::Eval,
297        Key::Left,
298        Key::Down,
299        Key::Right,
300        Key::Cos,
301        Key::Tan,
302        Key::Sqrt,
303        Key::Power,
304        Key::Inv,
305        Key::Enter,
306        Key::Neg,
307        Key::Eex,
308        Key::Del,
309        Key::Backspace,
310        Key::Alpha,
311        Key::Sin,
312        Key::Seven,
313        Key::Eight,
314        Key::Nine,
315        Key::Divide,
316        Key::LeftShift,
317        Key::Mth,
318        Key::Four,
319        Key::Five,
320        Key::Six,
321        Key::Multiply,
322        Key::RightShift,
323        Key::One,
324        Key::Two,
325        Key::Three,
326        Key::Minus,
327        Key::Quote,
328        Key::Zero,
329        Key::Point,
330        Key::Space,
331        Key::Plus,
332        Key::Apps,
333        Key::Mode,
334        Key::Tool,
335        Key::Hist,
336        Key::Cat,
337        Key::Eqw,
338        Key::Symb,
339        Key::X,
340        Key::Plot,
341        Key::Num,
342        Key::Lib,
343        Key::Math,
344        Key::Home,
345        Key::Xt,
346        Key::LParen,
347        Key::RParen,
348        Key::Shift,
349        Key::Comma,
350        Key::Aplet,
351        Key::Views,
352        Key::Vars,
353        Key::Ddx,
354        Key::Ln,
355        Key::Log,
356        Key::Square,
357        Key::SigmaPlus,
358        Key::Xeq,
359        Key::Rcl,
360        Key::RollDown,
361        Key::Swap,
362        Key::Rs,
363        Key::Percent,
364        Key::Dsp,
365        Key::Prt,
366        Key::Exit,
367        Key::Input,
368        Key::Equals,
369        Key::LetterA,
370        Key::LetterB,
371        Key::LetterC,
372        Key::LetterD,
373        Key::LetterE,
374        Key::LetterF,
375        Key::LetterG,
376        Key::LetterH,
377        Key::LetterI,
378        Key::LetterJ,
379        Key::LetterK,
380        Key::LetterL,
381        Key::LetterM,
382        Key::LetterN,
383        Key::LetterO,
384        Key::LetterP,
385        Key::LetterQ,
386        Key::LetterR,
387        Key::LetterS,
388        Key::LetterT,
389        Key::LetterU,
390        Key::LetterV,
391        Key::LetterW,
392        Key::LetterX,
393        Key::LetterY,
394        Key::LetterZ,
395        Key::Hash,
396        Key::LBrace,
397        Key::LBracket,
398        Key::Program,
399        Key::Lc,
400        Key::Cursor,
401        Key::Trig,
402        Key::Solv,
403        Key::User,
404        Key::Drop,
405        Key::Ins,
406        Key::Question,
407        Key::Dollar,
408        Key::Colon,
409        Key::On,
410    ];
411
412    /// Position of the key on `layout`, or `None` if that keyboard does
413    /// not have it.
414    pub(crate) fn position(self, layout: Layout) -> Option<KeyPos> {
415        if self.is_alias(layout) {
416            return Key::On.position(layout);
417        }
418        match layout {
419            Layout::Hp48 => position_48(self),
420            Layout::Hp49 => super::keyboard49::position(self),
421            Layout::Hp38 => super::keyboard_aplet::as_48_key(self).and_then(position_48),
422            Layout::Hp39 => {
423                super::keyboard_aplet::as_49_key(self).and_then(super::keyboard49::position)
424            }
425            Layout::Hp42 => super::keyboard42::position(self),
426            Layout::Hp27 | Layout::Hp17 => super::keyboard_pioneer::position(self, layout),
427            Layout::Hp28 => super::keyboard28::position(self),
428            Layout::Hp19 => super::keyboard19::position(self),
429        }
430    }
431
432    /// Whether the key is another name for a key `layout` has under its own
433    /// name: `exit` is the ON key wherever EXIT is not a key of its own (the
434    /// 42S labels its ON key EXIT; on the 48 and 49 families it is ON's
435    /// CANCEL/EXIT role, kept for old scripts).
436    fn is_alias(self, layout: Layout) -> bool {
437        self == Key::Exit && !matches!(layout, Layout::Hp27 | Layout::Hp17 | Layout::Hp19)
438    }
439
440    /// The keys `layout` has, in [`Key::ALL`] order (aliases left out).
441    pub(crate) fn on_layout(layout: Layout) -> impl Iterator<Item = Key> {
442        Key::ALL
443            .into_iter()
444            .filter(move |k| k.position(layout).is_some() && !k.is_alias(layout))
445    }
446
447    /// Script name: "0".."9" for digit keys, the lowercase variant name
448    /// otherwise (e.g. "enter", "leftshift", "on").
449    pub fn name(self) -> &'static str {
450        match self {
451            Key::A => "a",
452            Key::B => "b",
453            Key::C => "c",
454            Key::D => "d",
455            Key::E => "e",
456            Key::F => "f",
457            Key::Prg => "prg",
458            Key::Cst => "cst",
459            Key::Var => "var",
460            Key::Up => "up",
461            Key::Nxt => "nxt",
462            Key::Sto => "sto",
463            Key::Eval => "eval",
464            Key::Left => "left",
465            Key::Down => "down",
466            Key::Right => "right",
467            Key::Cos => "cos",
468            Key::Tan => "tan",
469            Key::Sqrt => "sqrt",
470            Key::Power => "power",
471            Key::Inv => "inv",
472            Key::Enter => "enter",
473            Key::Neg => "neg",
474            Key::Eex => "eex",
475            Key::Del => "del",
476            Key::Backspace => "backspace",
477            Key::Alpha => "alpha",
478            Key::Sin => "sin",
479            Key::Seven => "7",
480            Key::Eight => "8",
481            Key::Nine => "9",
482            Key::Divide => "divide",
483            Key::LeftShift => "leftshift",
484            Key::Mth => "mth",
485            Key::Four => "4",
486            Key::Five => "5",
487            Key::Six => "6",
488            Key::Multiply => "multiply",
489            Key::RightShift => "rightshift",
490            Key::One => "1",
491            Key::Two => "2",
492            Key::Three => "3",
493            Key::Minus => "minus",
494            Key::Quote => "quote",
495            Key::Zero => "0",
496            Key::Point => "point",
497            Key::Space => "space",
498            Key::Plus => "plus",
499            Key::Apps => "apps",
500            Key::Mode => "mode",
501            Key::Tool => "tool",
502            Key::Hist => "hist",
503            Key::Cat => "cat",
504            Key::Eqw => "eqw",
505            Key::Symb => "symb",
506            Key::X => "x",
507            Key::Plot => "plot",
508            Key::Num => "num",
509            Key::Lib => "lib",
510            Key::Math => "math",
511            Key::Home => "home",
512            Key::Xt => "xt",
513            Key::LParen => "lparen",
514            Key::RParen => "rparen",
515            Key::Shift => "shift",
516            Key::Comma => "comma",
517            Key::Aplet => "aplet",
518            Key::Views => "views",
519            Key::Vars => "vars",
520            Key::Ddx => "ddx",
521            Key::Ln => "ln",
522            Key::Log => "log",
523            Key::Square => "square",
524            Key::SigmaPlus => "sigmaplus",
525            Key::Xeq => "xeq",
526            Key::Rcl => "rcl",
527            Key::RollDown => "rdn",
528            Key::Swap => "swap",
529            Key::Rs => "rs",
530            Key::Percent => "percent",
531            Key::Dsp => "dsp",
532            Key::Prt => "prt",
533            Key::Exit => "exit",
534            Key::Input => "input",
535            Key::Equals => "equals",
536            Key::LetterA => "lettera",
537            Key::LetterB => "letterb",
538            Key::LetterC => "letterc",
539            Key::LetterD => "letterd",
540            Key::LetterE => "lettere",
541            Key::LetterF => "letterf",
542            Key::LetterG => "letterg",
543            Key::LetterH => "letterh",
544            Key::LetterI => "letteri",
545            Key::LetterJ => "letterj",
546            Key::LetterK => "letterk",
547            Key::LetterL => "letterl",
548            Key::LetterM => "letterm",
549            Key::LetterN => "lettern",
550            Key::LetterO => "lettero",
551            Key::LetterP => "letterp",
552            Key::LetterQ => "letterq",
553            Key::LetterR => "letterr",
554            Key::LetterS => "letters",
555            Key::LetterT => "lettert",
556            Key::LetterU => "letteru",
557            Key::LetterV => "letterv",
558            Key::LetterW => "letterw",
559            Key::LetterX => "letterx",
560            Key::LetterY => "lettery",
561            Key::LetterZ => "letterz",
562            Key::Hash => "hash",
563            Key::LBrace => "lbrace",
564            Key::LBracket => "lbracket",
565            Key::Program => "program",
566            Key::Lc => "lc",
567            Key::Cursor => "cursor",
568            Key::Trig => "trig",
569            Key::Solv => "solv",
570            Key::User => "user",
571            Key::Drop => "drop",
572            Key::Ins => "ins",
573            Key::Question => "question",
574            Key::Dollar => "dollar",
575            Key::Colon => "colon",
576            Key::On => "on",
577        }
578    }
579
580    /// Look up a key by its script name (case-insensitive); "f1"-"f6"
581    /// name the softkeys A-F. Model-agnostic by design: "f1" is A
582    /// everywhere (the 42S, which has no A-F, then refuses it), and "exit"
583    /// is [`Key::Exit`]: the EXIT key on the 27S, 17B and 17BII, the ON key
584    /// on every other model.
585    pub fn from_name(name: &str) -> Option<Key> {
586        const SOFTKEYS: [(&str, Key); 6] = [
587            ("f1", Key::A),
588            ("f2", Key::B),
589            ("f3", Key::C),
590            ("f4", Key::D),
591            ("f5", Key::E),
592            ("f6", Key::F),
593        ];
594        Key::ALL
595            .iter()
596            .copied()
597            .find(|k| k.name().eq_ignore_ascii_case(name))
598            .or_else(|| {
599                SOFTKEYS
600                    .iter()
601                    .find(|(n, _)| n.eq_ignore_ascii_case(name))
602                    .map(|&(_, k)| k)
603            })
604    }
605}
606
607/// The HP48 matrix (wiki: hardware/keyboard "HP48 matrix").
608pub(crate) fn position_48(key: Key) -> Option<KeyPos> {
609    let (out, mask) = match key {
610        Key::B => (8, 0x10),
611        Key::C => (8, 0x08),
612        Key::D => (8, 0x04),
613        Key::E => (8, 0x02),
614        Key::F => (8, 0x01),
615        Key::Prg => (7, 0x10),
616        Key::Cst => (7, 0x08),
617        Key::Var => (7, 0x04),
618        Key::Up => (7, 0x02),
619        Key::Nxt => (7, 0x01),
620        Key::Sto => (6, 0x10),
621        Key::Eval => (6, 0x08),
622        Key::Left => (6, 0x04),
623        Key::Down => (6, 0x02),
624        Key::Right => (6, 0x01),
625        Key::Cos => (5, 0x10),
626        Key::Tan => (5, 0x08),
627        Key::Sqrt => (5, 0x04),
628        Key::Power => (5, 0x02),
629        Key::Inv => (5, 0x01),
630        Key::Enter => (4, 0x10),
631        Key::Neg => (4, 0x08),
632        Key::Eex => (4, 0x04),
633        Key::Del => (4, 0x02),
634        Key::Backspace => (4, 0x01),
635        Key::Alpha => (3, 0x20),
636        Key::Sin => (3, 0x10),
637        Key::Seven => (3, 0x08),
638        Key::Eight => (3, 0x04),
639        Key::Nine => (3, 0x02),
640        Key::Divide => (3, 0x01),
641        Key::LeftShift => (2, 0x20),
642        Key::Mth => (2, 0x10),
643        Key::Four => (2, 0x08),
644        Key::Five => (2, 0x04),
645        Key::Six => (2, 0x02),
646        Key::Multiply => (2, 0x01),
647        Key::RightShift => (1, 0x20),
648        Key::A => (1, 0x10),
649        Key::One => (1, 0x08),
650        Key::Two => (1, 0x04),
651        Key::Three => (1, 0x02),
652        Key::Minus => (1, 0x01),
653        Key::Quote => (0, 0x10),
654        Key::Zero => (0, 0x08),
655        Key::Point => (0, 0x04),
656        Key::Space => (0, 0x02),
657        Key::Plus => (0, 0x01),
658        Key::On => return Some(KeyPos::On),
659        Key::Apps
660        | Key::Mode
661        | Key::Tool
662        | Key::Hist
663        | Key::Cat
664        | Key::Eqw
665        | Key::Symb
666        | Key::X
667        | Key::Plot
668        | Key::Num
669        | Key::Lib
670        | Key::Math
671        | Key::Home
672        | Key::Xt
673        | Key::LParen
674        | Key::RParen
675        | Key::Shift
676        | Key::Comma
677        | Key::Aplet
678        | Key::Views
679        | Key::Vars
680        | Key::Ddx
681        | Key::Ln
682        | Key::Log
683        | Key::Square
684        | Key::SigmaPlus
685        | Key::Xeq
686        | Key::Rcl
687        | Key::RollDown
688        | Key::Swap
689        | Key::Rs
690        | Key::Percent
691        | Key::Dsp
692        | Key::Prt
693        | Key::Exit
694        | Key::Input
695        | Key::Equals
696        | Key::LetterA
697        | Key::LetterB
698        | Key::LetterC
699        | Key::LetterD
700        | Key::LetterE
701        | Key::LetterF
702        | Key::LetterG
703        | Key::LetterH
704        | Key::LetterI
705        | Key::LetterJ
706        | Key::LetterK
707        | Key::LetterL
708        | Key::LetterM
709        | Key::LetterN
710        | Key::LetterO
711        | Key::LetterP
712        | Key::LetterQ
713        | Key::LetterR
714        | Key::LetterS
715        | Key::LetterT
716        | Key::LetterU
717        | Key::LetterV
718        | Key::LetterW
719        | Key::LetterX
720        | Key::LetterY
721        | Key::LetterZ
722        | Key::Hash
723        | Key::LBrace
724        | Key::LBracket
725        | Key::Program
726        | Key::Lc
727        | Key::Cursor
728        | Key::Trig
729        | Key::Solv
730        | Key::User
731        | Key::Drop
732        | Key::Ins
733        | Key::Question
734        | Key::Dollar
735        | Key::Colon => return None,
736    };
737    Some(KeyPos::Matrix { out, mask })
738}
739
740/// Pressed-key state of the keyboard matrix.
741#[derive(Clone, Debug, PartialEq, Eq, Default)]
742pub struct Keyboard {
743    /// The matrix keys are placed on.
744    pub(crate) layout: Layout,
745    /// IN bits pressed on each OUT line (index = OUT bit).
746    pub(crate) rows: [u16; 9],
747    /// ON key state.
748    pub(crate) on: bool,
749}
750
751impl Keyboard {
752    /// An HP48 keyboard with no key pressed.
753    #[cfg(test)]
754    pub fn new() -> Self {
755        Self::default()
756    }
757
758    /// A keyboard of `layout` with no key pressed.
759    pub fn with_layout(layout: Layout) -> Self {
760        Self {
761            layout,
762            ..Self::default()
763        }
764    }
765
766    /// The matrix this keyboard uses.
767    pub fn layout(&self) -> Layout {
768        self.layout
769    }
770
771    /// Press `k`. Returns false, changing nothing, when the layout does
772    /// not have the key; [`crate::Machine::key_down`] turns that into an
773    /// error before it gets here.
774    pub fn press(&mut self, k: Key) -> bool {
775        match k.position(self.layout) {
776            Some(KeyPos::Matrix { out, mask }) => self.rows[out] |= mask,
777            Some(KeyPos::On) => self.on = true,
778            None => return false,
779        }
780        true
781    }
782
783    /// Release `k`. Returns false, changing nothing, when the layout does
784    /// not have the key.
785    pub fn release(&mut self, k: Key) -> bool {
786        match k.position(self.layout) {
787            Some(KeyPos::Matrix { out, mask }) => self.rows[out] &= !mask,
788            Some(KeyPos::On) => self.on = false,
789            None => return false,
790        }
791        true
792    }
793
794    /// Release every key.
795    pub fn release_all(&mut self) {
796        *self = Self::with_layout(self.layout);
797    }
798
799    /// Whether `k` is held down. A key the layout lacks is never held, so
800    /// this is false for it.
801    pub fn is_pressed(&self, k: Key) -> bool {
802        match k.position(self.layout) {
803            Some(KeyPos::Matrix { out, mask }) => self.rows[out] & mask != 0,
804            Some(KeyPos::On) => self.on,
805            None => false,
806        }
807    }
808
809    /// Whether ON is held down.
810    pub fn on_pressed(&self) -> bool {
811        self.on
812    }
813
814    /// IN lines seen by the CPU for the OUT lines it drives: the OR of the
815    /// rows of every set OUT bit (0..9; the 49G uses 0..8 and its row 8
816    /// stays empty), plus bit 15 while ON is held.
817    pub fn read_in(&self, out: u16) -> u16 {
818        let mut value = self
819            .rows
820            .iter()
821            .enumerate()
822            .filter(|(i, _)| out & (1 << i) != 0)
823            .fold(0u16, |acc, (_, row)| acc | *row);
824        if self.on {
825            value |= ON_IN_BIT;
826        }
827        value
828    }
829}
830
831#[cfg(test)]
832mod tests {
833    use super::*;
834
835    #[test]
836    fn enter_row() {
837        let mut kb = Keyboard::new();
838        kb.press(Key::Enter);
839        assert_eq!(kb.read_in(0x010), 0x0010);
840        assert_eq!(kb.read_in(0x1FF), 0x0010);
841        assert_eq!(kb.read_in(0x001), 0);
842        kb.release(Key::Enter);
843        assert_eq!(kb.read_in(0x1FF), 0);
844    }
845
846    #[test]
847    fn on_ignores_out() {
848        let mut kb = Keyboard::new();
849        kb.press(Key::On);
850        assert_eq!(kb.read_in(0), 0x8000);
851        assert!(kb.on_pressed());
852        kb.release_all();
853        assert_eq!(kb.read_in(0x1FF), 0);
854    }
855
856    #[test]
857    fn exit_is_on_where_exit_is_no_key_of_its_own() {
858        for layout in [
859            Layout::Hp48,
860            Layout::Hp49,
861            Layout::Hp38,
862            Layout::Hp39,
863            Layout::Hp42,
864        ] {
865            assert_eq!(Key::Exit.position(layout), Some(KeyPos::On), "{layout:?}");
866            assert!(
867                !Key::on_layout(layout).any(|k| k == Key::Exit),
868                "{layout:?}"
869            );
870        }
871        for layout in [Layout::Hp27, Layout::Hp17] {
872            assert!(matches!(
873                Key::Exit.position(layout),
874                Some(KeyPos::Matrix { .. })
875            ));
876        }
877    }
878
879    #[test]
880    fn names_round_trip() {
881        assert_eq!(Key::from_name("F1"), Some(Key::A));
882        assert_eq!(Key::from_name("f6"), Some(Key::F));
883        let names: std::collections::HashSet<_> = Key::ALL.iter().map(|k| k.name()).collect();
884        assert_eq!(names.len(), Key::ALL.len());
885        for k in Key::ALL {
886            assert_eq!(Key::from_name(k.name()), Some(k));
887            assert_eq!(Key::from_name(&k.name().to_uppercase()), Some(k));
888        }
889        assert_eq!(Key::from_name("7"), Some(Key::Seven));
890        assert_eq!(Key::from_name("LeftShift"), Some(Key::LeftShift));
891        assert_eq!(Key::from_name("nope"), None);
892    }
893
894    /// The HP48 matrix from wiki: hardware/keyboard ("HP48 matrix"), cell
895    /// by cell as (OUT mask, IN mask), written out independently of
896    /// `Key::matrix`. Left shift is OUT #004 / IN #20 and right shift OUT
897    /// #002 / IN #20 (the tutorial and Ervin; Mastracci 4.9 has them
898    /// swapped). ON is IN #8000 for any OUT, so its OUT mask here is 0.
899    const WIKI_MATRIX: [(Key, u16, u16); 49] = [
900        (Key::B, 0x100, 0x10),
901        (Key::C, 0x100, 0x08),
902        (Key::D, 0x100, 0x04),
903        (Key::E, 0x100, 0x02),
904        (Key::F, 0x100, 0x01),
905        (Key::Prg, 0x080, 0x10),
906        (Key::Cst, 0x080, 0x08),
907        (Key::Var, 0x080, 0x04),
908        (Key::Up, 0x080, 0x02),
909        (Key::Nxt, 0x080, 0x01),
910        (Key::Sto, 0x040, 0x10),
911        (Key::Eval, 0x040, 0x08),
912        (Key::Left, 0x040, 0x04),
913        (Key::Down, 0x040, 0x02),
914        (Key::Right, 0x040, 0x01),
915        (Key::Cos, 0x020, 0x10),
916        (Key::Tan, 0x020, 0x08),
917        (Key::Sqrt, 0x020, 0x04),
918        (Key::Power, 0x020, 0x02),
919        (Key::Inv, 0x020, 0x01),
920        (Key::Enter, 0x010, 0x10),
921        (Key::Neg, 0x010, 0x08),
922        (Key::Eex, 0x010, 0x04),
923        (Key::Del, 0x010, 0x02),
924        (Key::Backspace, 0x010, 0x01),
925        (Key::Alpha, 0x008, 0x20),
926        (Key::Sin, 0x008, 0x10),
927        (Key::Seven, 0x008, 0x08),
928        (Key::Eight, 0x008, 0x04),
929        (Key::Nine, 0x008, 0x02),
930        (Key::Divide, 0x008, 0x01),
931        (Key::LeftShift, 0x004, 0x20),
932        (Key::Mth, 0x004, 0x10),
933        (Key::Four, 0x004, 0x08),
934        (Key::Five, 0x004, 0x04),
935        (Key::Six, 0x004, 0x02),
936        (Key::Multiply, 0x004, 0x01),
937        (Key::RightShift, 0x002, 0x20),
938        (Key::A, 0x002, 0x10),
939        (Key::One, 0x002, 0x08),
940        (Key::Two, 0x002, 0x04),
941        (Key::Three, 0x002, 0x02),
942        (Key::Minus, 0x002, 0x01),
943        (Key::Quote, 0x001, 0x10),
944        (Key::Zero, 0x001, 0x08),
945        (Key::Point, 0x001, 0x04),
946        (Key::Space, 0x001, 0x02),
947        (Key::Plus, 0x001, 0x01),
948        (Key::On, 0x000, 0x8000),
949    ];
950
951    #[test]
952    fn every_key_matches_the_wiki_matrix() {
953        let listed: Vec<Key> = WIKI_MATRIX.iter().map(|e| e.0).collect();
954        let mut on_48: Vec<Key> = Key::on_layout(Layout::Hp48).collect();
955        let mut listed = listed;
956        listed.sort_by_key(|k| k.name());
957        on_48.sort_by_key(|k| k.name());
958        assert_eq!(listed, on_48, "table covers exactly the 48 keys");
959        for (key, out, inp) in WIKI_MATRIX {
960            let mut kb = Keyboard::new();
961            kb.press(key);
962            // Driving only the key's row gives exactly its column.
963            assert_eq!(kb.read_in(out), inp, "{key:?} on its own row");
964            // Every other single row is silent, except ON, which ignores OUT.
965            for bit in 0..12 {
966                let other = 1u16 << bit;
967                if other == out {
968                    continue;
969                }
970                let want = if key == Key::On { 0x8000 } else { 0 };
971                assert_eq!(kb.read_in(other), want, "{key:?} with OUT {other:#05X}");
972            }
973            // All rows at once, plus the buzzer bit (OUT bit 11), which
974            // the matrix ignores (wiki: hardware/keyboard, Voyage p. 80).
975            assert_eq!(kb.read_in(0x1FF), inp);
976            assert_eq!(kb.read_in(0x9FF), inp);
977            assert_eq!(kb.read_in(0x800), if key == Key::On { inp } else { 0 });
978        }
979    }
980
981    #[test]
982    fn matrix_positions_unique() {
983        let positions: std::collections::HashSet<_> = Key::ALL
984            .iter()
985            .filter_map(|k| k.position(Layout::Hp48))
986            .collect();
987        assert_eq!(positions.len(), 49, "48 matrix cells and ON");
988        let mut kb = Keyboard::new();
989        for k in Key::on_layout(Layout::Hp48) {
990            assert!(!kb.is_pressed(k));
991            kb.press(k);
992            assert!(kb.is_pressed(k));
993        }
994        assert_eq!(kb.read_in(0x1FF), 0x803F);
995        // 49G-only keys are not on the 48.
996        kb.release_all();
997        assert!(!kb.press(Key::Apps), "APPS is not on the 48");
998        assert!(!kb.release(Key::Apps));
999        assert!(!kb.is_pressed(Key::Apps));
1000        assert_eq!(kb.read_in(0x1FF), 0);
1001    }
1002}