-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathshell.js
More file actions
3110 lines (2616 loc) · 114 KB
/
shell.js
File metadata and controls
3110 lines (2616 loc) · 114 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// R47 Web shell - bootstraps WASM, lays out keys, drives render + input.
// Plain JS, no build step. Loaded from index.html after c47-web.js.
(() => {
'use strict';
// Single source of truth for the web release. assemble-web.sh stamps
// this into dist/sw.js (VERSION) and dist/index.html (softwareVersion).
const WEB_VERSION = '4.11v4';
/* Key Mapping Reference (Index to Primary Label in C47):
* 0: Σ+ 1: 1/x 2: √x 3: LOG 4: LN 5: XEQ
* 6: STO 7: RCL 8: R↓ 9: SIN 10: COS 11: TAN
* (Note: In R47 mode, 10 is f and 11 is g. In C47, 27 is f/g)
*
* Format for adding multiple keys per section:
* Use comma-separated key-value pairs (standard JS object syntax).
* e.g., separate: { 6: 5, 7: 5, 27: 3 }
*/
const LABEL_OFFSETS = {
'R47': {
separate: {}, // e.g., 10: 5 (key index: offset in px)
closer: {9: 2, 13: 5, 14: 5, 18: 2, 19: 2, 20: 2, 21: 2, 22: 3, 23: 2, 24: 2, 25: 2, 26:2, 27:2, 28:2, 29:2, 30:2, 31:2, 32:2, 34:2, 33:2, 35:2, 36 :2}
},
'C47': {
separate: {},
closer: {0:3, 10: 2, 11: 2, 13: 4, 14: 4, 15:2, 17:3, 18:2, 19:2, 20:2, 21:2, 22:3, 23:2, 24:2, 25:2, 26:2, 27:3, 28:2, 29:2,30:2, 31:3, 32:2, 33:2, 34:2, 35: 2}
},
'DM42': {
separate: {},
closer: {}
}
};
let keysEl = null;
let ctx = null;
let mod = null;
// ---------- Layout constants (from src/c47/defines.h, R47 portrait) ------
const X_LEFT = 45; // reverted to uncropped defaults
const Y_TOP = 376; // reverted to uncropped defaults
const DELTA_X = 78; // column step
const DELTA_Y = 74; // row step
const KEY_W1 = 47; // standard button width
const KEY_W2 = 56; // wide nav button width (XEQ/↑/↓/EXIT)
const KEY_H = 28; // button height
const LK_GAP1 = 18; // large-key spacing 1 (after nav col, row 5)
const LK_GAP2 = 17; // large-key spacing 2 (rows 6-8)
// ROW_Y_SHIFT removed: shifting everything (f/g labels, letter labels,
// buttons) looked wrong. The visible dark-button body is now offset
// via CSS (.key::before uses --btn-y-offset) so only the painted
// rectangle and its primary label move down, while the f/g shift
// labels and letter labels stay at their GTK positions.
// ---------- Key table -----------------------------------------------------
// Each entry: [idx, x, y, w, h, label]
// idx is the engine's kbd_std_R47f_g table index (0..36 for main keys,
// or -(1..6) for the 6 F-keys which route through the softmenu handler).
//
// Layout derived from src/c47-gtk/gtkGui.c construction code.
// Labels for the 37 calculator keys (kbd_std_R47f_g[0..36] in assign.c:368).
// Each: [idx, main, letter, fShift, gShift]. Empty strings omit the label.
// Letter column mirrors src/c47/assign.c:368 kbd_std_R47f_g[].primaryAim
// (the AIM-mode primary character for each key). For ITM_SPACE the C47
// font has no glyph for U+0020, so gtkGui.c renders it as ·_· — we do
// the same. Buttons whose primaryAim is a function (ENTER/BACKSPACE/
// UP1/DOWN1/EXIT1) get no letter, matching the physical R47.
const KEY_META = [
// idx main letter fShift (orange) gShift (cyan)
[0, 'x\u00B2', 'A', 'i\u2133\u2192R', '\u2192REC'],
[1, '\u221Ax', 'B', 'i\u2133\u2192P', '\u2192POL'],
[2, '1/x', 'C', 'x!.ms', '.ms'],
[3, 'y\u02E3', 'D', '\u221Ay.d', '.d'],
[4, 'LOG', 'E', '10\u02E3\u2192I', 'R\u2134'],
[5, 'LN', 'F', 'e\u02E3', '#'],
[6, 'STO', 'G', '|x|', 'arg'],
[7, 'RCL', 'H', '%', '\u0394%'],
[8, 'R\u2193', 'I', '\u03C0', 'R\u2191'],
[9, 'DRG', 'J', 'USER', 'ASN'],
[10, 'f', '', '', ''],
[11, 'g', '', '', ''],
[12, 'ENTER', '', 'CPX', 'STK'],
[13, 'x\u21C4y', 'K', 'LASTx', 'DISP'],
[14, 'CHS', 'L', 'TRG', 'PFX'],
[15, 'EEX', 'M', 'EXP', 'CLR'],
[16, '\u2190', '', 'UNDO', ''],
[17, 'XEQ', '_', 'AIM', 'GTO'],
[18, '7', 'N', 'sin', 'asin'],
[19, '8', 'O', 'cos', 'acos'],
[20, '9', 'P', 'tan', 'atan'],
[21, '\u00F7', 'Q', 'STAT', 'PLOT'],
[22, '\u2191', '', 'BST', 'RBR'],
[23, '4', 'R', 'BASE', 'BITS'],
[24, '5', 'S', 'INTS', 'REAL'],
[25, '6', 'T', 'MATX', 'FN'],
[26, '\u00D7', 'U', 'EQN', 'ADV'],
[27, '\u2193', '', 'SST', 'FLGS'],
[28, '1', 'V', 'PREF', 'KEYS'],
[29, '2', 'W', 'CONV', 'CLK'],
[30, '3', 'X', 'FLAG', 'FN'],
[31, '\u2212', 'Y', 'PROB', 'FIN'],
[32, 'EXIT', '', 'OFF', 'INFO'],
[33, '0', 'Z', 'VIEW', 'I/O'],
[34, '.', ',', 'SHOW', 'b/c'],
[35, 'R/S', '?', 'PR', 'PFN'],
[36, '+', '\u00B7_\u00B7', 'CAT', 'CNST'],
];
// ---------- Keyboard shortcuts --------------------------------------------
// Primary labels match the GTK R47-facing shortcut legend. We keep a few
// practical aliases that GTK also accepts (for example '^' for yˣ, Tab for
// x↔y, ',' for '.', and z for R/S on some layouts).
// Each binding is [KeyboardEvent.key, engineIdx, labelForTooltip].
const KEYBOARD_BINDINGS = [
// digits
['0', 33, '0'], ['1', 28, '1'], ['2', 29, '2'], ['3', 30, '3'],
['4', 23, '4'], ['5', 24, '5'], ['6', 25, '6'],
['7', 18, '7'], ['8', 19, '8'], ['9', 20, '9'],
// operators
['+', 36, '+'], ['-', 31, '-'], ['*', 26, '*'], ['/', 21, '/'],
// core
['Enter', 12, 'Enter'],
['Backspace', 16, 'Backspace'],
['Delete', 16, 'Del'],
['.', 34, '.'],
[',', 34, ','],
['Escape', 32, 'Esc'],
['ArrowUp', 22, 'Up'],
['ArrowDown', 27, 'Dn'],
// GTK R47 row shortcuts
['Q', 0, 'Q'],
['q', 1, 'q'],
['v', 2, 'v'],
['Y', 3, 'Y'],
['^', 3, '^'],
['o', 4, 'o'],
['l', 5, 'l'],
['m', 6, 'm'],
['r', 7, 'r'],
['d', 8, 'd'],
['>', 9, '>'],
['w', 13, 'w'],
['Tab', 13, 'Tab'],
['n', 14, 'n'],
['e', 15, 'e'],
['x', 17, 'x'],
['\\', 35, '\\'],
['z', 35, 'z'],
];
const KEYBOARD_MAP = Object.create(null);
const IDX_TO_KEYS = new Map();
for (const [key, idx, label] of KEYBOARD_BINDINGS) {
KEYBOARD_MAP[key] = idx;
if (!IDX_TO_KEYS.has(idx)) IDX_TO_KEYS.set(idx, []);
const labels = IDX_TO_KEYS.get(idx);
if (!labels.includes(label)) labels.push(label);
}
// F-key shortcuts + Left/Right arrow for menu scroll (GTK desktop behavior).
const KEYBOARD_FN_MAP = { 'F1':1,'F2':2,'F3':3,'F4':4,'F5':5,'F6':6,'ArrowLeft':5,'ArrowRight':6 };
function buildKeyTable() {
const T = [];
// Row 1: six function keys F1..F6 at (45 + i*78, 376), w=47
for (let i = 0; i < 6; i++) {
T.push({ idx: -(i+1), x: X_LEFT + i*DELTA_X, y: Y_TOP, w: KEY_W1, h: KEY_H, fn: true });
}
// Rows 2-3: six calc keys each, uniform x step.
// Shift DOWN by ROW_Y_SHIFT so the button bottoms align with the
// bottom of the letter labels beside each button.
for (let r = 0; r < 2; r++) {
for (let c = 0; c < 6; c++) {
T.push({ idx: r*6 + c,
x: X_LEFT + c*DELTA_X,
y: Y_TOP + (r+1)*DELTA_Y,
w: KEY_W1, h: KEY_H, fn: false });
}
}
// Row 4: ENTER(wide, 2 cols) + x↔y + CHS + EEX + ← (5 entries, idx 12..16)
const y4 = Y_TOP + 3*DELTA_Y;
const enterW = KEY_W1 + DELTA_X;
T.push({ idx:12, x:X_LEFT, y:y4, w:enterW, h:KEY_H, fn:false });
T.push({ idx:13, x:X_LEFT + 2*DELTA_X, y:y4, w:KEY_W1, h:KEY_H, fn:false });
T.push({ idx:14, x:X_LEFT + 3*DELTA_X, y:y4, w:KEY_W1, h:KEY_H, fn:false });
T.push({ idx:15, x:X_LEFT + 4*DELTA_X, y:y4, w:KEY_W1, h:KEY_H, fn:false });
T.push({ idx:16, x:X_LEFT + 5*DELTA_X, y:y4, w:KEY_W1, h:KEY_H, fn:false });
// Rows 5-8: five keys each (nav + 4 wider number/op keys).
for (let r = 0; r < 4; r++) {
const y = Y_TOP + (4+r)*DELTA_Y;
const base = 17 + r*5;
T.push({ idx: base+0, x: 45, y, w: KEY_W1, h: KEY_H, fn:false });
T.push({ idx: base+1, x: 141, y, w: KEY_W2, h: KEY_H, fn:false });
T.push({ idx: base+2, x: 236, y, w: KEY_W2, h: KEY_H, fn:false });
T.push({ idx: base+3, x: 331, y, w: KEY_W2, h: KEY_H, fn:false });
T.push({ idx: base+4, x: 426, y, w: KEY_W2, h: KEY_H, fn:false });
}
return T;
}
// ---------- Fit-to-viewport scaling ---------------------------------------
// Centers and scales the calculator to fit the actual visible area.
// On narrow portrait phones we bias toward a fuller-width fit, while
// still centering the device inside the safe-area box so the bezel, not
// the live controls, absorbs any notch/home-indicator overlap. On larger
// devices (notably iPad portrait), fit against the safe-area height first.
function getSafeAreaInset(prop) {
// env(safe-area-inset-*) is a CSS value; resolve it via a dummy
// element so we can read it as a number in JS.
const probe = document.createElement('div');
probe.style.cssText = `position:fixed;top:0;left:0;padding-${prop}:env(safe-area-inset-${prop});visibility:hidden;`;
document.body.appendChild(probe);
const v = parseFloat(getComputedStyle(probe).getPropertyValue('padding-' + prop)) || 0;
probe.remove();
return v;
}
// User-controlled zoom factor, set by the calculator explorer page via
// postMessage({ type: 'r47-set-scale', scale: N }). Multiplied into the
// viewport-fit scale so the calc grows/shrinks within its iframe.
let _userScale = 1.0;
function fitScale() {
const W = 482, H = 930;
const vv = window.visualViewport;
const vw = vv ? vv.width : window.innerWidth;
// Take the LARGER of layout vs. visual viewport for height so iOS
// Safari's bottom URL bar doesn't hold back the calculator's scale.
// The bar briefly overlaps the bottom row but disappears as soon as
// the user scrolls / it minimizes.
const vh = Math.max(window.innerHeight || 0, vv ? vv.height : 0);
const safeLeft = getSafeAreaInset('left');
const safeRight = getSafeAreaInset('right');
const safeW = Math.max(1, vw - safeLeft - safeRight);
const portrait = vh >= vw;
const phoneLikePortrait = portrait && safeW <= 500;
// "Fill screen" mode (user toggle in the theme picker): ignore both
// top and bottom safe areas and center the calculator vertically.
// This fills the full viewport width and splits the remaining vertical
// slack evenly above and below — the notch covers a sliver of the LCD
// frame at the top, and the home indicator overlaps the bottom keys
// slightly, but both are minor and symmetric.
// In "safe" mode (default) the LCD frame border bleeds behind the
// notch but the LCD canvas stays below it.
const rawSafeTop = getSafeAreaInset('top');
let fillScreen = false;
try { fillScreen = localStorage.getItem('r47-fill-screen') === '1'; } catch (_) {}
const phoneFill = phoneLikePortrait && fillScreen;
// In safe mode, force a gap at the top to clear camera, even if height limited.
const forcedTopGap = 50;
const safeTop = phoneFill ? 0 : (phoneLikePortrait ? Math.max(0, rawSafeTop - 5 * (vw / W)) : rawSafeTop);
const safeBottom = phoneFill ? 0 : getSafeAreaInset('bottom');
const baseSafeH = Math.max(1, vh - safeTop - safeBottom);
const safeH = phoneFill ? baseSafeH : Math.max(1, baseSafeH - forcedTopGap);
const topMargin = phoneFill ? 0 : forcedTopGap;
const fitW = (phoneLikePortrait ? vw : safeW) / W;
const fitH = safeH / H;
const s = Math.min(fitW, fitH);
// Fill screen: center vertically in the full viewport.
// Safe mode: pin to the bottom of the safe area to leave gap at top.
const centerX = phoneLikePortrait ? (vw / 2) : (safeLeft + safeW / 2);
const topEdge = phoneFill ? Math.max(0, (vh - H * s) / 2 + 12) : (safeTop + topMargin + (safeH - H * s));
const centerY = topEdge + (H * s) / 2;
document.documentElement.style.setProperty('--device-scale', s);
document.documentElement.style.setProperty('--device-left', centerX + 'px');
document.documentElement.style.setProperty('--device-top', centerY + 'px');
document.documentElement.style.setProperty('--device-top-edge', topEdge + 'px');
document.documentElement.dataset.fillWidth = '0';
}
// ---------- Main ----------------------------------------------------------
// Debug overlay - toggle by pressing D in the URL (?debug). Otherwise
// all engine output goes to console only.
const DEBUG = new URLSearchParams(location.search).has('debug');
function dbg(s) {
console.log('[R47]', s);
if (!DEBUG) return;
let el = document.getElementById('r47dbg');
if (!el) {
el = document.createElement('pre');
el.id = 'r47dbg';
el.style = 'position:fixed;left:2px;top:2px;color:#0f0;background:rgba(0,0,0,0.6);'
+ 'z-index:99;padding:4px;font:10px monospace;max-height:180px;'
+ 'max-width:50vw;overflow:auto;';
document.body.appendChild(el);
}
el.textContent += s + '\n';
}
// ---------- Themes --------------------------------------------------------
// Shared theme catalog for the independent Keys and LCD selectors.
// The same IDs power:
// 1. Keys/body theme via CSS on <html data-keys-theme="...">
// 2. LCD theme via pixel remap colors + the --lcd-bg fallback
// This lets users mix and match while keeping the old single-theme
// setting as a migration fallback. hex -> [r,g,b] helper below.
const hex2rgb = (s) => {
const n = parseInt(s.replace('#',''), 16);
return [(n>>16)&0xff, (n>>8)&0xff, n&0xff];
};
const THEMES = [
// id, name, kind, swatches (for picker tiles), lcdBg, lcdFg
['c47', 'C47', 'dark', ['#1A1A1A','#222222','#E5AE5A','#7EB6BA'], '#C8D8A0','#1C3014'],
['hp-classic', 'HP Classic', 'dark', ['#2B2A29','#212121','#E5AE5A','#7EB6BA'], '#e0e0e0','#303030'],
['hp-clean', 'HP Clean', 'dark', ['#2B2A29','#2B2A29','#E5AE5A','#7EB6BA'], '#2A1B08','#FFBF4A'],
['hp-10b-clean', 'HP 10B Clean', 'dark', ['#182331','#182331','#6499D3','#5A8FCA'], '#061936','#91C8FF'],
['nord-dark', 'Nord Dark', 'dark', ['#2E3440','#3B4252','#EBCB8B','#88C0D0'], '#2B3340','#ECEFF4'],
['dracula', 'Nightfall', 'dark', ['#282A36','#44475A','#FFB86C','#8BE9FD'], '#1C2535','#F5F8FF'],
['monokai', 'Monokai', 'dark', ['#272822','#3E3D32','#FD971F','#66D9EF'], '#1F201B','#F8F8F2'],
['solarized-dark', 'Solarized Dark','dark', ['#002B36','#073642','#B58900','#2AA198'], '#00212B','#EEE8D5'],
['tokyo-night', 'Tokyo Night', 'dark', ['#1A1B26','#24283B','#E0AF68','#7DCFFF'], '#1F2335','#C0CAF5'],
['catppuccin-mocha','Catppuccin Mocha','dark',['#1E1E2E','#313244','#F9E2AF','#89B4FA'], '#1A2434','#D8E7FF'],
['twilight', 'Twilight', 'dark', ['#2A2826','#5A5E68','#F0B284','#E8A2A2'], '#EDE4CC','#261C10'],
['ti-89-classic', 'TI-89 Classic', 'dark', ['#2C3442','#6B87A6','#E1C54D','#315D38'], '#C6D7CF','#20303F'],
['hp-48g', 'HP 48G', 'dark', ['#374541','#E6EBE1','#A486C9','#4D9C7A'], '#C9D7A7','#183022'],
['irixium', 'Irixium', 'light',['#6F93A6','#C5BBB2','#C98572','#3E88A8'], '#C8D9E7','#25344F'],
['cde', 'CDE', 'light',['#3F8F87','#B7D3DD','#F0A45D','#78AFC8'], '#B8D6D0','#173946'],
['platinum', 'Platinum', 'light',['#C8CDD5','#45505D','#5F97EC','#5CA56F'], '#D6DCE4','#2E4053'],
['hp-10b', 'HP 10B', 'light',['#C8CED6','#1A1D22','#3C78BC','#22374F'], '#AFC7DB','#0D2032'],
['hp-silver', 'HP Silver', 'light',['#B8AE9C','#E8E1D0','#B57600','#0F66AA'], '#C9D5A9','#0F1A20'],
['blue-steel', 'Blue Steel', 'light',['#A8B5C2','#E1E7EE','#B77A14','#236EA8'], '#CBD8E6','#13253C'],
['blue-steel-clean','Blue Steel Clean','light',['#A8B5C2','#A8B5C2','#6A3A00','#004878'], '#102836','#86E8FF'],
['rose-quartz', 'Rose Quartz', 'light',['#D5C0C3','#F0E5E6','#B97C2F','#5A82A3'], '#E5CDD2','#4A2E35'],
['solarized-light','Solarized Light','light',['#FDF6E3','#EEE8D5','#B58900','#2AA198'], '#FDF6E3','#002B36'],
['nord-light', 'Nord Light', 'light',['#ECEFF4','#E5E9F0','#D08770','#5E81AC'], '#ECEFF4','#2E3440'],
['gruvbox-light', 'Gruvbox Light', 'light',['#FBF1C7','#EBDBB2','#B57614','#076678'], '#FBF1C7','#3C3836'],
['github-light', 'GitHub Light', 'light',['#F6F8FA','#FFFFFF','#DAFBE1','#DDF4FF'], '#FFFFFF','#24292F'],
];
const DEFAULT_THEME_ID = 'hp-classic';
const LEGACY_THEME_KEY = 'r47-theme';
const KEYS_THEME_KEY = 'r47-keys-theme';
const LCD_THEME_KEY = 'r47-lcd-theme';
const LCD_SMOOTH_KEY = 'r47-lcd-smooth';
const LAYOUT_KEY = 'r47-layout';
const THEME_ALIASES = {
'hpb-clean': 'hp-10b-clean',
};
// When embedded in the docs page (iframe src="/?docs=1") we default to
// Blue Steel keys + HP Classic LCD, and intentionally do NOT persist
// theme changes — otherwise opening the docs would overwrite the
// user's standalone-calc theme.
const IS_DOCS = (() => {
try { return new URLSearchParams(location.search).get('docs') === '1'; }
catch (_) { return false; }
})();
const DOCS_DEFAULT_KEYS_THEME = 'blue-steel';
const DOCS_DEFAULT_LCD_THEME = 'github-light';
// When embedded in the docs page as an iframe, wheel events over the
// calc body are normally "consumed" by the iframe (the iframe itself
// isn't scrollable, but the event doesn't auto-bubble to the parent
// document's scroll). Forward them explicitly so the parent page
// scrolls when the user rolls the wheel over the calculator — users
// expect "scroll wheel over anywhere on the page = scroll the page."
if (IS_DOCS) {
window.addEventListener('wheel', (e) => {
// Same-origin iframe — we can scroll the parent directly.
try {
window.parent.scrollBy({ top: e.deltaY, left: e.deltaX });
e.preventDefault();
} catch (_) { /* cross-origin or detached; ignore */ }
}, { passive: false });
}
function getTheme(id) {
const canonical = THEME_ALIASES[id] || id;
return THEMES.find((t) => t[0] === canonical) || THEMES[0];
}
function getStoredTheme(key) {
if (IS_DOCS) {
return key === LCD_THEME_KEY ? DOCS_DEFAULT_LCD_THEME : DOCS_DEFAULT_KEYS_THEME;
}
try {
return localStorage.getItem(key) || localStorage.getItem(LEGACY_THEME_KEY) || DEFAULT_THEME_ID;
} catch (_) {
return DEFAULT_THEME_ID;
}
}
function getStoredLcdSmooth() {
try {
const v = localStorage.getItem(LCD_SMOOTH_KEY);
return v == null ? true : v !== '0';
} catch (_) {
return true;
}
}
function setBrowserThemeColor(color) {
const meta = document.querySelector('meta[name="theme-color"]');
if (meta) meta.setAttribute('content', color);
}
let currentKeysTheme = DEFAULT_THEME_ID;
let currentLcdTheme = DEFAULT_THEME_ID;
let currentLcdSmooth = getStoredLcdSmooth();
// Mutable LCD-remap state, overwritten by applyLcdTheme(). The blit loop
// reads these to rescale engine pixel intensities into theme colors.
const LCD_REMAP = { bg: [224,224,224], fg: [48,48,48] };
let workDirHandle = null;
async function createSubfoldersInDirectory(handle) {
try {
await handle.getDirectoryHandle('STATE', { create: true });
await handle.getDirectoryHandle('PROGRAMS', { create: true });
await handle.getDirectoryHandle('SAVFILES', { create: true });
await handle.getDirectoryHandle('SCREENS', { create: true });
dbg("Subfolders created in Work Directory");
} catch (e) {
dbg("Failed to create subfolders in Work Directory: " + e.message);
}
}
function idb_get(storeName, key) {
return new Promise((resolve, reject) => {
const req = indexedDB.open('r47-db', 2);
req.onupgradeneeded = (e) => {
const db = e.target.result;
if (!db.objectStoreNames.contains(storeName)) {
db.createObjectStore(storeName);
}
};
req.onsuccess = (e) => {
const db = e.target.result;
const tx = db.transaction(storeName, 'readonly');
const store = tx.objectStore(storeName);
const getReq = store.get(key);
getReq.onsuccess = () => resolve(getReq.result);
getReq.onerror = () => reject(getReq.error);
};
req.onerror = () => reject(req.error);
});
}
function idb_set(storeName, key, value) {
return new Promise((resolve, reject) => {
const req = indexedDB.open('r47-db', 2);
req.onupgradeneeded = (e) => {
const db = e.target.result;
if (!db.objectStoreNames.contains(storeName)) {
db.createObjectStore(storeName);
}
};
req.onsuccess = (e) => {
const db = e.target.result;
const tx = db.transaction(storeName, 'readwrite');
const store = tx.objectStore(storeName);
const putReq = store.put(value, key);
putReq.onsuccess = () => resolve();
putReq.onerror = () => reject(putReq.error);
};
req.onerror = () => reject(req.error);
});
}
async function handleDirectorySelection(handle) {
dbg("Directory selected: " + handle.name);
window.workDirHandle = handle;
try {
await idb_set('handles', 'workDir', handle);
dbg("Saved directory handle to IndexedDB.");
} catch (e) {
dbg("Failed to save directory handle to IndexedDB: " + e.message);
}
await createSubfoldersInDirectory(handle);
try {
const savFilesHandle = await handle.getDirectoryHandle('SAVFILES');
const savFileHandle = await savFilesHandle.getFileHandle('R47.sav');
const file = await savFileHandle.getFile();
const buffer = await file.arrayBuffer();
const bytes = new Uint8Array(buffer);
// Stage it into the virtual filesystem
try { window.Module.FS.mkdir('/persist/SAVFILES'); } catch (e) {}
window.Module.FS.writeFile('/persist/SAVFILES/R47.sav', bytes);
dbg("Auto-loaded R47.sav to virtual FS. Use manual LOAD if not applied.");
} catch (e) {
dbg("No R47.sav found in Work Directory to auto-load: " + e.message);
}
}
window.getSubfolderHandle = async function(subfolderName) {
if (!window.workDirHandle) return null;
try {
return await window.workDirHandle.getDirectoryHandle(subfolderName);
} catch (e) {
console.error(`Failed to get subfolder handle for ${subfolderName}:`, e);
return null;
}
}
function applyKeysTheme(id) {
const t = getTheme(id);
currentKeysTheme = t[0];
document.documentElement.dataset.keysTheme = t[0];
setBrowserThemeColor(t[3][0]);
if (!IS_DOCS) { try { localStorage.setItem(KEYS_THEME_KEY, t[0]); } catch (_) {} }
}
function applyLcdTheme(id) {
const t = getTheme(id);
currentLcdTheme = t[0];
document.documentElement.dataset.lcdTheme = t[0];
document.documentElement.style.setProperty('--lcd-bg', t[4]);
LCD_REMAP.bg = hex2rgb(t[4]);
LCD_REMAP.fg = hex2rgb(t[5]);
if (!IS_DOCS) { try { localStorage.setItem(LCD_THEME_KEY, t[0]); } catch (_) {} }
}
// Apply saved themes as early as possible (before first paint).
try { applyKeysTheme(getStoredTheme(KEYS_THEME_KEY)); } catch (_) {}
try { applyLcdTheme(getStoredTheme(LCD_THEME_KEY)); } catch (_) {}
let r47 = null;
function applyLcdRenderMode() {
const smooth = currentLcdSmooth;
document.documentElement.dataset.lcdRender = smooth ? 'smooth' : 'pixelated';
const lcd = document.getElementById('lcd');
if (!lcd) return;
const ctx = lcd.getContext('2d', { alpha: false });
ctx.imageSmoothingEnabled = smooth;
ctx.mozImageSmoothingEnabled = smooth;
ctx.webkitImageSmoothingEnabled = smooth;
ctx.msImageSmoothingEnabled = smooth;
}
async function boot() {
dbg('boot start');
dbg('Version: ' + WEB_VERSION);
keysEl = document.getElementById('keys');
const lcd = document.getElementById('lcd');
applyLcdRenderMode();
// 1. Build and mount the key grid.
// Each button's CSS --pad (default 10px) widens the clickable/tap
// area so fingers don't need to be pixel-accurate. The VISUAL
// button is painted inward by that pad via a CSS pseudo-element,
// so the GTK-matching pixel layout is preserved. We set inline
// left/top that are the VISUAL position (from buildKeyTable) minus
// the pad, and width/height that are the VISUAL size plus 2*pad.
const HIT_PAD = 12;
const keys = buildKeyTable();
const keyBtnByIdx = new Map(); // engineIdx → button element (for keyboard handler)
keysEl.innerHTML = '';
for (const k of keys) {
const container = document.createElement('div');
container.className = 'key-container';
const isFKey = k.fn;
const heightScale = isFKey ? 1.0 : 1.20;
const newH = k.h * heightScale;
const newY = isFKey ? k.y : (k.y + k.h - newH);
container.style.left = (k.x - HIT_PAD) + 'px';
container.style.top = (newY - HIT_PAD) + 'px';
container.style.width = (k.w + 2*HIT_PAD) + 'px';
container.style.height = (newH + 2*HIT_PAD) + 'px';
container.dataset.idx = k.idx;
const btn = document.createElement('button');
btn.type = 'button';
btn.className = 'key';
btn.dataset.idx = k.idx;
btn.dataset.fn = k.fn ? '1' : '0';
container.appendChild(btn);
if (k.fn) {
const fnNum = -k.idx;
btn.setAttribute('aria-label', 'F' + fnNum);
btn.classList.add('key-fn');
const fnHints = ['F' + fnNum];
if (fnNum === 5) fnHints.push('Left');
if (fnNum === 6) fnHints.push('Right');
btn.title = 'F' + fnNum + ' (softkey) [' + fnHints.join(' / ') + ']';
} else {
const meta = KEY_META[k.idx] || [];
const letter = meta[2] || '';
const numericIdx = { 18:1, 19:1, 20:1, 23:1, 24:1, 25:1, 28:1, 29:1, 30:1, 33:1 };
const operatorIdx = { 21:1, 26:1, 31:1, 36:1 };
if (numericIdx[k.idx]) btn.classList.add('numeric');
if (operatorIdx[k.idx]) btn.classList.add('operator');
if (k.idx === 10) btn.classList.add('key-f');
if (k.idx === 11) btn.classList.add('key-g');
btn.innerHTML = `<span class="key-label" data-role="primary"></span>`;
btn.setAttribute('aria-label', 'key-' + k.idx);
{
const [, main, , fsh, gsh] = meta;
// Removed hardcoded labels to avoid double rows.
const parts = [];
if (main) parts.push(main);
if (fsh) parts.push('f\u2192 ' + fsh);
if (gsh) parts.push('g\u2192 ' + gsh);
const sc = IDX_TO_KEYS.get(k.idx);
if (sc && sc.length) parts.push('[' + sc.join(' / ') + ']');
if (parts.length) btn.title = parts.join(' \u2022 ');
}
if (letter) {
const lEl = document.createElement('span');
lEl.className = 'alpha';
lEl.textContent = letter;
container.appendChild(lEl);
}
{
const lblEl = document.createElement('div');
lblEl.className = 'lbl';
lblEl.dataset.idx = k.idx;
lblEl.innerHTML =
`<span class="shift-f gold"></span><span class="shift-g blue"></span>`;
container.insertBefore(lblEl, btn);
}
}
keyBtnByIdx.set(k.idx, btn);
keysEl.appendChild(container);
}
// 2. Boot the WASM module. IDBFS is mounted at /persist in preRun so
// when the engine calls fopen("/persist/...") the reads/writes are
// backed by IndexedDB.
dbg('R47Module loading...');
// Filter: lines we consider "engine user output" vs internal debug spam.
// The engine is chatty on stdout with refresh counters, freeList stats,
// function-name traces, etc. We only surface things that don't match
// those noise patterns.
const NOISE_RE = [
/^\s*refrsh\(/,
/^--- /, /^-------/, /^#{3,}/,
/^#\d+/,
/^\s*frame #/,
/^freeProgramBytes/,
/^RestoreCalc$/,
/^Cannot open file /,
/^R47 Web:/,
/^gmpMemInBytes/,
/^error:gmpMemInBytes/,
/^This happened after/,
/^addItemToNim/,
/^calcModel/,
/^\[shim\]/,
/^\s*$/,
];
const isEngineUserOutput = (s) => {
if (!s) return false;
for (const re of NOISE_RE) if (re.test(s)) return false;
return true;
};
// ---- Family-reload protocol (docsmd/firmwarekeys.md §5, §8) ---------
// Register the reload hook BEFORE R47Module boots so the engine finds
// it defined if any future early-boot path ever calls fnKeysManagement
// with a cross-family layout. The hook body closes over `mod` and
// `r47` (both declared below); calling it before those bindings
// resolve would throw TDZ ReferenceError, but the current design
// has nothing triggering the hook during r47_init.
//
// Overlay must block user input during the async save → syncfs →
// reload window: without that, a keypress between saveCalc() and
// reload() could mutate state after the flush, silently losing work.
function r47_showSwitchOverlay(name) {
const ov = document.createElement('div');
ov.className = 'r47-switch-overlay';
ov.innerHTML = `<div class="r47-switch-msg">Switching to <strong>${name}</strong>…</div>`;
document.body.appendChild(ov);
return ov;
}
function r47_freezeInput() {
document.documentElement.setAttribute('data-switching', '1');
}
function r47_thawInput() {
document.documentElement.removeAttribute('data-switching');
}
let inFamilySwitch = false;
window.r47RequestFamilyReload = async function(targetModel) {
if (inFamilySwitch) return;
// USER_R47f_g..USER_R47fg_g = 61..64; USER_C47 = 46; USER_DM42 = 45.
const targetIsR47 = (targetModel >= 61 && targetModel <= 64);
const currentModel = r47.calc_model();
const currentIsR47 = (currentModel >= 61 && currentModel <= 64);
if (currentIsR47 && targetIsR47) {
console.log(`[R47] In-family switch from ${currentModel} to ${targetModel}`);
inFamilySwitch = true;
r47.set_calc_model(targetModel);
console.log(`[R47] Invoking window.refreshKeyLabels() after switch`);
if (window.refreshKeyLabels) window.refreshKeyLabels();
inFamilySwitch = false;
return;
}
const displayName = targetIsR47
? 'R47'
: (targetModel === 45 ? 'DM42' : 'C47');
const ov = r47_showSwitchOverlay(displayName);
r47_freezeInput();
try {
// 1. Flush the current binary's state to its backup.cfg. This is
// the file the inbound binary's restoreCalc() reads on boot.
// The engine's saveCalc() has a non-permanent-layout guard but
// config.c's fnKeysManagement intercept bails before calcModel
// mutates, so we're still in-family here.
r47.save_calc();
// 2. Persist IDBFS to IndexedDB so the flushed cfg survives reload.
await new Promise((resolve, reject) =>
mod.FS.syncfs(false, (err) => err ? reject(err) : resolve()));
// 3. Stash the target so the post-reload boot picks the right
// binary and layout.
localStorage.setItem('r47-target', JSON.stringify({
binary: targetIsR47 ? 'r47' : 'c47',
initialLayout: targetModel,
}));
// 4. Reload. An HTTP failure on the next page load surfaces in
// the boot-time recovery path (index.html's onerror handler).
window.location.reload();
} catch (err) {
// Pre-reload failure — don't leave r47-target set or the user
// will reload into the same broken state.
try { localStorage.removeItem('r47-target'); } catch (_) {}
ov.remove();
r47_thawInput();
console.error('Family reload failed:', err);
alert('Could not switch calculator. See console for details.');
}
};
// --------------------------------------------------------------------
mod = await R47Module({
print: (s) => {
if (s.includes('Invalid UTF-8 leading byte')) return;
if (isEngineUserOutput(s)) {
dbg('wasm: ' + s);
if (window.r47Printer) window.r47Printer.appendLine(s);
}
// Intercept SAVE completion
if (s.includes('item=1586=SAVE')) {
setTimeout(() => triggerSaveToPhysicalFolder(), 500);
}
},
printErr: (s) => {
if (s.includes('Invalid UTF-8 leading byte')) return;
dbg('wasm!: ' + s);
if (s.includes('This happened after SAVE')) {
setTimeout(() => triggerSaveToPhysicalFolder(), 500);
}
},
locateFile: (p) => 'wasm/' + p,
noInitialRun: true, // we'll call main() manually after IDBFS is mounted
});
dbg('R47Module loaded');
window.Module = mod;
window.wasmInitialized = true;
if (typeof window.onWasmLoaded === 'function') {
window.onWasmLoaded();
}