This repository has been archived by the owner on Dec 24, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 91
/
Copy pathkeyboard.js
3079 lines (2889 loc) · 137 KB
/
keyboard.js
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
/**
* @fileoverview Implements the PCx86 Keyboard component
* @author <a href="mailto:[email protected]">Jeff Parsons</a>
* @copyright © 2012-2019 Jeff Parsons
*
* This file is part of PCjs, a computer emulation software project at <https://www.pcjs.org>.
*
* PCjs is free software: you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation, either version 3
* of the License, or (at your option) any later version.
*
* PCjs is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with PCjs. If not,
* see <http://www.gnu.org/licenses/gpl.html>.
*
* You are required to include the above copyright notice in every modified copy of this work
* and to display that copyright notice when the software starts running; see COPYRIGHT in
* <https://www.pcjs.org/modules/shared/lib/defines.js>.
*
* Some PCjs files also attempt to load external resource files, such as character-image files,
* ROM files, and disk image files. Those external resource files are not considered part of PCjs
* for purposes of the GNU General Public License, and the author does not claim any copyright
* as to their contents.
*/
"use strict";
if (typeof module !== "undefined") {
var Str = require("../../shared/lib/strlib");
var Usr = require("../../shared/lib/usrlib");
var Web = require("../../shared/lib/weblib");
var Component = require("../../shared/lib/component");
var Keys = require("../../shared/lib/keys");
var State = require("../../shared/lib/state");
var PCX86 = require("./defines");
var Interrupts = require("./interrupts");
var Messages = require("./messages");
var ChipSet = require("./chipset");
var ROMX86 = require("./rom");
}
/**
* class Keyboard
* @unrestricted (allows the class to define properties, both dot and named, outside of the constructor)
*/
class Keyboard extends Component {
/**
* Keyboard(parmsKbd)
*
* The Keyboard component can be configured with the following (parmsKbd) properties:
*
* model: keyboard model string, which must match one of the values listed in Keyboard.MODELS:
*
* "US83" (default)
* "US84"
* "US101" (not fully supported yet)
*
* autoType: string of keys to automatically inject when the machine is ready (undefined if none)
*
* softKeys: boolean set to true to enable the machine's soft keyboard, if any (default is false)
*
* Its main purpose is to receive binding requests for various keyboard events, and to use those events
* to simulate the PC's keyboard hardware.
*
* TODO: Consider finishing 101-key keyboard support, even though that's sort of a "PS/2" thing, and I'm not
* really interested in taking PCjs into the PS/2 line (that's also why we still support only serial mice, not
* "PS/2" mice). In addition, all keyboards *after* the original PC 83-key keyboard supported their own unique
* scan code sets, which the 8042 controller would then convert to PC-compatible scan codes. That's probably
* more important to implement, because that feature was introduced with the 84-key keyboard on the PC AT.
*
* @this {Keyboard}
* @param {Object} parmsKbd
*/
constructor(parmsKbd)
{
super("Keyboard", parmsKbd, Messages.KBD);
this.setModel(parmsKbd['model']);
this.fMobile = Web.isMobile("!iPad");
this.printMessage("mobile keyboard support: " + (this.fMobile? "true" : "false"));
/*
* This flag (formerly fMSIE, for all versions of Microsoft Internet Explorer, up to and including v11)
* has been updated to reflect the Microsoft Windows *platform* rather than the *browser*, because it appears
* that all Windows-based browsers (at least now, as of 2018) have the same behavior with respect to "lock"
* keys: keys like CAPS-LOCK generate both UP and DOWN events on every press. On other platforms (eg, macOS),
* those keys generate only a DOWN event when "locking" and only an UP event when "unlocking".
*/
this.fMSWindows = Web.isUserAgent("Windows");
/*
* This is count of the number of "soft keyboard" keys present. At the moment, its only
* purpose is to signal findBinding() whether to waste any time looking for SOFTCODE matches.
*/
this.cSoftCodes = 0;
this.fSoftKeyboard = parmsKbd['softKeys'];
this.controlSoftKeyboard = null;
this.controlTextKeyboard = null;
/*
* Updated by onFocusChange()
*/
this.fHasFocus = true;
/*
* This can be used to delay ALT key generation (ie, until some other key in conjunction with the
* ALT is pressed as well); however, it is currently off by default, because there are apps (eg, the
* MS-DOS Manager) that don't deal well the rapid back-to-back ALT+key generation that this work-around
* necessitates.
*/
this.fDelayALT = false;
/*
* This is true whenever the physical Escape key is disabled (eg, by pointer locking code),
* giving us the opportunity to map a different physical key to machine's virtual Escape key.
*/
this.fEscapeDisabled = false;
/*
* This is set whenever we notice a discrepancy between our internal CAPS_LOCK state and its
* apparent state; we check whenever aKeysActive has been emptied.
*/
this.fToggleCapsLock = false;
/*
* New unified approach to key event processing: When we process a key on the "down" event,
* we check the aKeysActive array: if the key is already active, do nothing; otherwise, insert
* it into the table, generate the "make" scan code(s), and set a timeout for "repeat" if it's
* a repeatable key (most are).
*
* Similarly, when a key goes "up", if it's already not active, do nothing; otherwise, generate
* the "break" scan code(s), cancel any pending timeout, and remove it from the active key table.
*
* If a "press" event is received, then if the key is already active, remove it and (re)insert
* it at the head of the table, generate the "make" scan code(s), set nRepeat to -1, and set a
* timeout for "break".
*
* This requires an aKeysActive array that keeps track of the status of every active key; only the
* first entry in the array is allowed to repeat. Each entry is a key object with the following
* properties:
*
* simCode: our simulated keyCode from onKeyChange or onKeyPress
* bitsState: snapshot of the current bitsState when the key is added (currently not used)
* fDown: next state to simulate (true for down, false for up)
* nRepeat: > 0 if timer should generate more "make" scan code(s), -1 for "break" scan code(s)
* timer: timer for next key operation, if any
*
* Keys are inserted at the head of aKeysActive, using splice(0, 0, key), but not before zeroing
* nRepeat of any repeating key that already occupies the head (index 0), so that at most only one
* key (ie, the most recent) will ever be in a repeating state.
*
* IBM PC keyboard repeat behavior: when pressing CTRL, then C, and then releasing CTRL while still
* holding C, the repeated CTRL_C characters turn into 'c' characters. We emulate that behavior.
* However, when pressing C, then CTRL, all repeating stops: not a single CTRL_C is generated, and
* even if the CTRL is released before the C, no more more 'c' characters are generated either.
* We do NOT fully emulate that behavior -- we DO stop the repeating, but we also generate one CTRL_C.
* More investigation is required, because I need to confirm whether the IBM keyboard automatically
* "breaks" all non-shift keys before it "makes" the CTRL.
*/
this.aKeysActive = [];
/*
* msTransmit was originally 10ms, but I was getting some warning "beeps" in this machine:
*
* /devices/pcx86/machine/5170/ega/2048kb/rev3/debugger/machine.xml
*
* while typing very fast, so I bumped it to 15ms. Then the COMPAQ Portable BIOS required another bump to 25ms.
*/
this.msTransmit = 25; // minimum number of milliseconds between data transmissions
this.msAutoRepeat = 500;
this.msNextRepeat = 100;
this.msAutoRelease = 50;
this.msInjectDefault = 100; // number of milliseconds between injected keystrokes
this.msInjectDelay = 0; // set by the initial injectKeys() call
this.msDoubleClick = 250; // used by mousedown/mouseup handlers to soft-lock modifier keys
this.cKeysPressed = 0; // count of keys pressed since the last time it was reset
this.softCodeKeys = Object.keys(Keyboard.SOFTCODES);
/*
* Remove all single-character SOFTCODE keys from the softCodeKeys array, because those SOFTCODES
* are not supported by injectKeys(); they can be specified normally using their single-character identity.
*/
for (let i = 0; i < this.softCodeKeys.length; i++) {
if (this.softCodeKeys[i].length < 2) {
this.softCodeKeys.splice(i, 1);
i--;
}
}
/*
* autoType records the machine's specified autoType sequence, if any, and when injectInit() is called
* with the appropriate INJECTION signal, injectInit() pass autoType to injectKeys().
*/
this.autoType = parmsKbd['autoType'];
this.fDOSReady = false;
this.fnDOSReady = this.fnInjectReady = null;
this.nInjection = Keyboard.INJECTION.ON_INPUT;
/*
* HACK: We set fAllDown to false to ignore all down/up events for keys not explicitly marked as ONDOWN;
* even though that prevents those keys from being repeated properly (ie, at the simulation's repeat rate
* rather than the browser's repeat rate), it's the safest thing to do when dealing with international keyboards,
* because our mapping tables are designed for US keyboards, and testing all the permutations of international
* keyboards and web browsers is more work than I can take on right now. TODO: Dig into this some day.
*/
this.fAllDown = false;
this['exports'] = {
'type': this.injectKeys,
'wait': this.waitReady
};
this.setReady();
}
/**
* setBinding(sHTMLType, sBinding, control, sValue)
*
* @this {Keyboard}
* @param {string} sHTMLType is the type of the HTML control (eg, "button", "list", "text", "submit", "textarea", "canvas")
* @param {string} sBinding is the value of the 'binding' parameter stored in the HTML control's "data-value" attribute (eg, "esc")
* @param {HTMLElement} control is the HTML control DOM object (eg, HTMLButtonElement)
* @param {string} [sValue] optional data value
* @return {boolean} true if binding was successful, false if unrecognized binding request
*/
setBinding(sHTMLType, sBinding, control, sValue)
{
let kbd = this;
let className;
let id = sHTMLType + '-' + sBinding, sCode;
let controlText = /** @type {HTMLTextAreaElement} */ (control);
if (this.bindings[id] === undefined) {
switch (sBinding) {
case "keyboard":
try {
/*
* TODO: Fix this rather fragile code, which depends on the current structure of the given xxxx-softkeys.xml
*/
let controlSoftKeyboard = control.parentElement.parentElement.nextElementSibling;
className = controlSoftKeyboard.className;
if (this.fMobile != (className.indexOf('mobile') >= 0)) {
controlSoftKeyboard = controlSoftKeyboard.nextElementSibling;
}
if (controlSoftKeyboard) {
this.controlSoftKeyboard = controlSoftKeyboard;
if (this.fSoftKeyboard != null) {
this.enableSoftKeyboard(this.fSoftKeyboard);
} else {
this.fSoftKeyboard = (controlSoftKeyboard.style.display != "none");
}
control.onclick = function onToggleKeyboard(event) {
kbd.enableSoftKeyboard(!kbd.fSoftKeyboard);
};
/*
* This is added simply to prevent the page from "zooming" around if you accidentally touch between the keys.
*/
if ('ontouchstart' in window) {
controlSoftKeyboard.ontouchstart = function onTouchKeyboard(event) {
event.preventDefault();
};
}
}
} catch(err) {}
return true;
case "screen":
/*
* This is a special binding that the Video component uses to effectively bind its screen to the
* entire keyboard; eg:
*
* this.kbd.setBinding(this.inputTextArea? "textarea" : "canvas", "screen", this.inputScreen);
*
* Recording the binding ID prevents multiple controls (or components) from attempting to erroneously
* bind a control to the same ID, but in the case of a "dual display" configuration, we actually want
* to allow BOTH video components to call setBinding() for "screen", so that it doesn't matter which
* display the user gives focus to.
*
* this.bindings[id] = control;
*/
if (sHTMLType == "textarea") {
this.controlTextKeyboard = controlText;
}
controlText.onkeydown = function onKeyDown(event) {
return kbd.onKeyChange(event, true);
};
controlText.onkeypress = function onKeyPressKbd(event) {
return kbd.onKeyPress(event);
};
controlText.onkeyup = function onKeyUp(event) {
return kbd.onKeyChange(event, false);
};
return true;
case "caps-lock":
if (sHTMLType == 'led') {
this.bindings[id] = control;
control.onclick = function onClickCapsLock(event) {
event.preventDefault();
if (kbd.cmp) kbd.cmp.updateFocus();
return kbd.toggleCapsLock();
};
return true;
}
/* falls through */
case "num-lock":
if (sHTMLType == 'led') {
this.bindings[id] = control;
control.onclick = function onClickNumLock(event) {
event.preventDefault();
if (kbd.cmp) kbd.cmp.updateFocus();
return kbd.toggleNumLock();
};
return true;
}
/* falls through */
case "scroll-lock":
if (sHTMLType == 'led') {
this.bindings[id] = control;
control.onclick = function onClickScrollLock(event) {
event.preventDefault();
if (kbd.cmp) kbd.cmp.updateFocus();
return kbd.toggleScrollLock();
};
return true;
}
/* falls through */
default:
/*
* Maintain support for older button codes; eg, map button code "ctrl-c" to CLICKCODE "CTRL_C"
*/
sCode = sBinding.toUpperCase().replace(/-/g, '_');
if (Keyboard.CLICKCODES[sCode] !== undefined && sHTMLType == "button") {
this.bindings[id] = controlText;
if (MAXDEBUG) console.log("binding click-code '" + sCode + "'");
controlText.onclick = function(kbd, sKey, simCode) {
return function onKeyboardBindingClick(event) {
if (kbd.messageEnabled()) kbd.printMessage(sKey + " clicked", Messages.EVENT | Messages.KEY);
event.preventDefault(); // preventDefault() is necessary...
if (kbd.cmp) kbd.cmp.updateFocus(); // ...for the updateFocus() call to actually work
kbd.sInjectBuffer = ""; // key events should stop any injection currently in progress
kbd.updateShiftState(simCode, true); // future-proofing if/when any LOCK keys are added to CLICKCODES
kbd.addActiveKey(simCode, true);
};
}(this, sCode, Keyboard.CLICKCODES[sCode]);
return true;
}
else if (Keyboard.SOFTCODES[sBinding] !== undefined) {
/*
* TODO: Fix this rather fragile code, which depends on the current structure of the given xxxx-softkeys.xml
*/
className = control.parentElement.parentElement.className;
if (className && this.fMobile != (className.indexOf('mobile') >= 0)) {
break;
}
this.cSoftCodes++;
this.bindings[id] = controlText;
if (MAXDEBUG) console.log("binding soft-code '" + sBinding + "'");
let msLastEvent = 0, nClickState = 0;
let fStateKey = (Keyboard.KEYSTATES[Keyboard.SOFTCODES[sBinding]] <= Keyboard.STATE.ALL_MODIFIERS);
let fnDown = function(kbd, sKey, simCode) {
return function onKeyboardBindingDown(event) {
let msDelta = event.timeStamp - msLastEvent;
nClickState = (nClickState && msDelta < kbd.msDoubleClick? (nClickState << 1) : 1);
msLastEvent = event.timeStamp;
event.preventDefault(); // preventDefault() is necessary to avoid "zooming" when you type rapidly
kbd.sInjectBuffer = ""; // key events should stop any injection currently in progress
kbd.addActiveKey(simCode);
};
}(this, sBinding, Keyboard.SOFTCODES[sBinding]);
let fnUp = function(kbd, sKey, simCode) {
return function onKeyboardBindingUp(event) {
if (nClickState) {
let msDelta = event.timeStamp - msLastEvent;
nClickState = (fStateKey && msDelta < kbd.msDoubleClick? (nClickState << 1) : 0);
msLastEvent = event.timeStamp;
if (nClickState < 8) {
kbd.removeActiveKey(simCode);
} else {
if (MAXDEBUG) console.log("soft-locking '" + sBinding + "'");
nClickState = 0;
}
}
};
}(this, sBinding, Keyboard.SOFTCODES[sBinding]);
if ('ontouchstart' in window) {
controlText.ontouchstart = fnDown;
controlText.ontouchend = fnUp;
} else {
controlText.onmousedown = fnDown;
controlText.onmouseup = controlText.onmouseout = fnUp;
}
return true;
}
else if (sValue) {
/*
* Instead of just having a dedicated "test" control, we now treat any unrecognized control with
* a "value" attribute as a test control. The only caveat is that such controls must have binding IDs
* that do not conflict with predefined controls (which, of course, is the only way you can get here).
*/
this.bindings[id] = control;
control.onclick = function onClickTest(event) {
event.preventDefault(); // preventDefault() is necessary...
if (kbd.cmp) kbd.cmp.updateFocus(); // ...for the updateFocus() call to actually work
return kbd.injectKeys(sValue);
};
return true;
}
break;
}
}
return false;
}
/**
* findBinding(simCode, sType, fDown)
*
* TODO: This function is woefully inefficient, because the SOFTCODES table is designed for converting
* soft key presses into SIMCODES, whereas this function is doing the reverse: looking for the soft key,
* if any, that corresponds to a SIMCODE, simply so we can provide visual feedback of keys activated
* by other means (eg, real keyboard events, button clicks that generate key sequences like CTRL-ALT-DEL,
* etc).
*
* To minimize this function's cost, we would want to dynamically create a reverse-lookup table after
* all the setBinding() calls for the soft keys have been established; note that the reverse-lookup table
* would contain MORE entries than the SOFTCODES table, because there are multiple simCodes that correspond
* to a given soft key (eg, '1' and '!' both map to the same soft key).
*
* @this {Keyboard}
* @param {number} simCode
* @param {string} sType is the type of control (eg, "button" or "key")
* @param {boolean} [fDown] is true if the key is going down, false if up, or undefined if unchanged
* @return {Object} is the HTML control DOM object (eg, HTMLButtonElement), or undefined if no such control exists
*/
findBinding(simCode, sType, fDown)
{
let control;
if (this.cSoftCodes && this.fSoftKeyboard) {
for (let code in Keys.SHIFTED_KEYCODES) {
if (simCode == Keys.SHIFTED_KEYCODES[code]) {
simCode = +code;
code = Keys.NONASCII_KEYCODES[code];
if (code) simCode = +code;
break;
}
}
/*
* TODO: Create a table that maps these SIMCODEs to the corresponding entries in the SOFTCODES table;
* these SIMCODEs can be generated by CLICKCODEs or by the special key remapping HACKs in onKeyChange().
*/
if (simCode == Keyboard.SIMCODE.CTRL_PAUSE) {
simCode = Keyboard.SIMCODE.NUM_LOCK;
}
else if (simCode == Keyboard.SIMCODE.CTRL_BREAK) {
simCode = Keyboard.SIMCODE.SCROLL_LOCK;
}
else if (simCode == Keyboard.SIMCODE.CTRL_ALT_DEL) {
simCode = Keyboard.SIMCODE.DEL;
}
else if (simCode == Keyboard.SIMCODE.CTRL_ALT_INS) {
simCode = Keyboard.SIMCODE.INS;
}
else if (simCode == Keyboard.SIMCODE.CTRL_ALT_ADD) {
simCode = Keyboard.SIMCODE.NUM_ADD;
}
else if (simCode == Keyboard.SIMCODE.CTRL_ALT_SUB) {
simCode = Keyboard.SIMCODE.NUM_SUB;
}
for (let sBinding in Keyboard.SOFTCODES) {
if (Keyboard.SOFTCODES[sBinding] == simCode || Keyboard.SOFTCODES[sBinding] == this.toUpperKey(simCode)) {
let id = sType + '-' + sBinding;
control = this.bindings[id];
if (control && fDown !== undefined) {
this.setSoftKeyState(control, fDown);
}
break;
}
}
}
return control;
}
/**
* initBus(cmp, bus, cpu, dbg)
*
* @this {Keyboard}
* @param {Computer} cmp
* @param {Bus} bus
* @param {CPUX86} cpu
* @param {DebuggerX86} dbg
*/
initBus(cmp, bus, cpu, dbg)
{
this.cmp = cmp;
this.bus = bus;
this.cpu = cpu;
this.dbg = dbg;
let kbd = this;
this.timerInject = this.cpu.addTimer(this.id + ".inject", function injectKeysTimer() {
kbd.injectKeys();
});
this.timerTransmit = this.cpu.addTimer(this.id + ".transmit", function transmitDataTimer() {
kbd.transmitData();
});
this.chipset = cmp.getMachineComponent("ChipSet");
this.autoType = cmp.getMachineParm('autoType') || this.autoType;
let softKeys = cmp.getMachineParm('softKeys');
if (softKeys) this.enableSoftKeyboard(softKeys != "false");
cpu.addIntNotify(Interrupts.DOS, this.intDOS.bind(this));
}
/**
* start()
*
* Notification from the Computer that it's starting.
*
* @this {Keyboard}
*/
start()
{
this.injectInit(Keyboard.INJECTION.ON_START);
}
/**
* intDOS()
*
* Monitors selected DOS interrupts for signals to initialize 'autoType' injection.
*
* @this {Keyboard}
* @param {number} addr
* @return {boolean} true to proceed with the INT 0x21 software interrupt, false to skip
*/
intDOS(addr)
{
let AH = (this.cpu.regEAX >> 8) & 0xff;
if (AH == 0x0A) {
this.fDOSReady = true;
if (this.fnDOSReady) {
this.fnDOSReady();
this.fnDOSReady = null;
this.fDOSReady = false;
} else {
this.injectInit(Keyboard.INJECTION.ON_INPUT);
}
}
return true;
}
/**
* notifyEscape(fDisabled, fAllDown)
*
* When ESC is used by the browser to disable pointer lock, this gives us the option of mapping a different key to ESC.
*
* @this {Keyboard}
* @param {boolean} fDisabled
* @param {boolean} [fAllDown] (an experimental option to re-enable processing of all onkeydown/onkeyup events)
*/
notifyEscape(fDisabled, fAllDown)
{
this.fEscapeDisabled = fDisabled;
if (fAllDown !== undefined) this.fAllDown = fAllDown;
}
/**
* resetDevice()
*
* @this {Keyboard}
*/
resetDevice()
{
/*
* TODO: There's more to reset, like LED indicators, default type rate, and emptying the scan code buffer.
*/
this.printMessage("keyboard reset", Messages.KBD | Messages.PORT);
this.abBuffer = [];
this.setResponse(Keyboard.CMDRES.BAT_OK);
}
/**
* setModel(sModel)
*
* This breaks a model string (eg, "US83") into two parts: modelCountry (eg, "US") and modelKeys (eg, 83).
* If the model string isn't recognized, we use Keyboard.MODELS[0] (ie, the first entry in the model array).
*
* @this {Keyboard}
* @param {string|undefined} sModel
*/
setModel(sModel)
{
let iModel = 0;
this.model = null;
if (typeof sModel == "string") {
this.model = sModel.toUpperCase();
iModel = Keyboard.MODELS.indexOf(this.model);
if (iModel < 0) iModel = 0;
}
sModel = Keyboard.MODELS[iModel];
if (sModel) {
this.modelCountry = sModel.substr(0, 2);
this.modelKeys = parseInt(sModel.substr(2), 10);
}
}
/**
* checkBuffer(b)
*
* This is the ChipSet's interface to let us know it's ready.
*
* @this {Keyboard}
* @param {number} [b] (set to the data, if any, that the ChipSet just delivered)
*/
checkBuffer(b)
{
let fReady = false;
if (b) {
/*
* The following hack is for the 5170 ROM BIOS keyboard diagnostic, which expects the keyboard
* to report BAT_OK immediately after the ACK from a RESET command. The BAT_OK response should already
* be in the keyboard's buffer; we just need to give it a little nudge.
*/
if (b == Keyboard.CMDRES.ACK) {
fReady = true;
}
if (this.cpu) {
this.cpu.setTimer(this.timerTransmit, this.msTransmit, true);
}
}
this.transmitData(fReady);
}
/**
* flushBuffer()
*
* This is the ChipSet's interface to flush any buffered keyboard data.
*
* @this {Keyboard}
*/
flushBuffer()
{
this.abBuffer = [];
if (!COMPILED && this.messageEnabled()) this.printMessage("keyboard data flushed");
}
/**
* receiveCmd(bCmd)
*
* This is the ChipSet's interface for controlling "Model M" keyboards (ie, those used with MODEL_5170
* machines). Commands are delivered through the ChipSet's 8042 Keyboard Controller.
*
* @this {Keyboard}
* @param {number} bCmd should be one of the Keyboard.CMD.* command codes (Model M keyboards only)
* @return {number} response should be one of the Keyboard.CMDRES.* response codes, or -1 if unrecognized
*/
receiveCmd(bCmd)
{
let b = -1;
if (!COMPILED && this.messageEnabled()) this.printMessage("receiveCmd(" + Str.toHexByte(bCmd) + ")");
switch(this.bCmdPending || bCmd) {
case Keyboard.CMD.RESET: // 0xFF
b = Keyboard.CMDRES.ACK;
this.resetDevice();
break;
case Keyboard.CMD.SET_RATE: // 0xF3
if (this.bCmdPending) {
this.setRate(bCmd);
bCmd = 0;
}
this.setResponse(Keyboard.CMDRES.ACK);
this.bCmdPending = bCmd;
break;
case Keyboard.CMD.SET_LEDS: // 0xED
if (this.bCmdPending) {
this.setLEDs(bCmd);
bCmd = 0;
}
this.setResponse(Keyboard.CMDRES.ACK);
this.bCmdPending = bCmd;
break;
default:
if (!COMPILED) this.printMessage("receiveCmd(): unrecognized command");
break;
}
return b;
}
/**
* setEnabled(fData, fClock)
*
* This is the ChipSet's interface for toggling keyboard "data" and "clock" lines.
*
* For MODEL_5150 and MODEL_5160 machines, this function is called from the ChipSet's PPI_B
* output handler. For MODEL_5170 machines, this function is called when selected CMD
* "data bytes" have been written.
*
* @this {Keyboard}
* @param {boolean} fData is true if the keyboard simulated data line should be enabled
* @param {boolean} fClock is true if the keyboard's simulated clock line should be enabled
* @return {boolean} true if keyboard was re-enabled, false if not (or no change)
*/
setEnabled(fData, fClock)
{
let fReset = false;
if (this.fClock !== fClock) {
if (!COMPILED && this.messageEnabled(Messages.KBD | Messages.PORT)) {
this.printMessage("keyboard clock line changing to " + fClock, true);
}
/*
* Toggling the clock line low and then high signals a "reset", which we acknowledge once the
* data line is high as well.
*/
this.fClock = this.fResetOnEnable = fClock;
}
if (this.fData !== fData) {
if (!COMPILED && this.messageEnabled(Messages.KBD | Messages.PORT)) {
this.printMessage("keyboard data line changing to " + fData, true);
}
this.fData = fData;
if (fData && !this.fResetOnEnable) {
this.transmitData(true);
}
}
if (this.fData && this.fResetOnEnable) {
this.resetDevice();
this.fResetOnEnable = false;
fReset = true;
}
return fReset;
}
/**
* setLEDs(b)
*
* This processes the option byte received after a SET_LEDS command byte.
*
* @this {Keyboard}
* @param {number} b
*/
setLEDs(b)
{
this.bLEDs = b; // TODO: Implement
}
/**
* setRate(b)
*
* This processes the rate parameter byte received after a SET_RATE command byte.
*
* @this {Keyboard}
* @param {number} b
*/
setRate(b)
{
this.bRate = b; // TODO: Implement
}
/**
* setResponse(b)
*
* @this {Keyboard}
* @param {number} b
*/
setResponse(b)
{
if (this.chipset) {
this.abBuffer.unshift(b);
if (!COMPILED && this.messageEnabled()) this.printMessage("keyboard response " + Str.toHexByte(b) + " buffered");
this.transmitData();
}
}
/**
* transmitData(fReady)
*
* This manages communication with the ChipSet's receiveKbdData() interface.
*
* @this {Keyboard}
* @param {boolean} [fReady]
*/
transmitData(fReady)
{
if (this.chipset) {
if (fReady || !this.cpu.isTimerSet(this.timerTransmit)) {
/*
* The original IBM PC BIOS performs a "stuck key" test by resetting the keyboard
* (by toggling the CLOCK line), then checking for a BAT_OK response (0xAA), and then
* clocking in the next byte (by toggling the DATA line); if that next byte isn't 0x00,
* then the BIOS reports a "301" error, along with "AA" if we failed to properly flush
* the BAT_OK response.
*/
let b = this.abBuffer.length? this.abBuffer[0] : 0;
if (this.chipset.receiveKbdData(b)) {
if (!COMPILED && this.messageEnabled()) this.printMessage("keyboard data " + Str.toHexByte(b) + " delivered");
this.abBuffer.shift();
}
if (b) this.cpu.setTimer(this.timerTransmit, this.msTransmit);
}
}
}
/**
* powerUp(data, fRepower)
*
* @this {Keyboard}
* @param {Object|null} data
* @param {boolean} [fRepower]
* @return {boolean} true if successful, false if failure
*/
powerUp(data, fRepower)
{
if (!fRepower) {
/*
* TODO: Save/restore support for Keyboard is the barest minimum. In fact, originally, I wasn't
* saving/restoring anything, and that was OK, but if we don't at least re-initialize fClock/fData,
* we can get a spurious reset following a restore. In an ideal world, we might choose to save/restore
* abBuffer as well, but realistically, I think it's going to be safer to always start with an
* empty buffer--and who's going to notice anyway?
*
* So, like Debugger, we deviate from the typical save/restore pattern: instead of reset OR restore,
* we always reset and then perform a (very limited) restore.
*/
this.reset();
if (data && this.restore) {
if (!this.restore(data)) return false;
}
}
return true;
}
/**
* powerDown(fSave, fShutdown)
*
* @this {Keyboard}
* @param {boolean} [fSave]
* @param {boolean} [fShutdown]
* @return {Object|boolean} component state if fSave; otherwise, true if successful, false if failure
*/
powerDown(fSave, fShutdown)
{
return fSave? this.save() : true;
}
/**
* reset()
*
* @this {Keyboard}
*/
reset()
{
/*
* If no keyboard model was specified, our initial setModel() call will select the "US83" keyboard as the
* default, but now that the ChipSet is initialized, we can pick a better default, based on the ChipSet model.
*/
if (!this.model && this.chipset) {
switch(this.chipset.model) {
case ChipSet.MODEL_5150:
case ChipSet.MODEL_5160:
this.setModel(Keyboard.MODELS[0]);
break;
case ChipSet.MODEL_5170:
default:
this.setModel(Keyboard.MODELS[1]);
break;
}
}
this.initState();
}
/**
* save()
*
* This implements save support for the Keyboard component.
*
* @this {Keyboard}
* @return {Object}
*/
save()
{
let state = new State(this);
state.set(0, this.saveState());
return state.data();
}
/**
* restore(data)
*
* This implements restore support for the Keyboard component.
*
* @this {Keyboard}
* @param {Object} data
* @return {boolean} true if successful, false if failure
*/
restore(data)
{
return this.initState(data[0]);
}
/**
* initState(data)
*
* @this {Keyboard}
* @param {Array} [data]
* @return {boolean} true if successful, false if failure
*/
initState(data)
{
if (!data) {
data = [false, false, Keyboard.INJECTION.ON_INPUT];
} else {
/*
* If there is a predefined state for this machine, then the assumption is that any injection
* sequence can be injected as soon as the machine starts. Any other kind of state must disable
* injection, because injection depends on the machine being in a known state.
*/
data[2] = this.cmp.sStatePath? Keyboard.INJECTION.ON_START : (data[2] || Keyboard.INJECTION.NONE);
}
let i = 0;
this.fClock = data[i++];
this.fData = data[i++];
this.nInjection = data[i++];
this.sInjectBuffer = data[i++] || "";
this.msInjectDelay = data[i] || this.msInjectDefault;
this.bCmdPending = 0; // when non-zero, a command is pending (eg, SET_LED or SET_RATE)
/*
* The current (assumed) physical (and simulated) modifier/lock key states, along with a set
* of (fake) modifier key states maintained by simulateKey() to keep track of faked modifiers.
*
* TODO: Determine how (or whether) we can query the browser's initial shift/lock key states.
*/
this.bitsState = this.bitsStateSim = this.bitsStateFake = 0;
/*
* New scan codes are "pushed" onto abBuffer and then "shifted" off.
*/
this.abBuffer = [];
return true;
}
/**
* saveState()
*
* @this {Keyboard}
* @return {Array}
*/
saveState()
{
let data = [], i = 0;
data[i++] = this.fClock;
data[i++] = this.fData;
data[i++] = this.nInjection;
data[i++] = this.sInjectBuffer;
data[i] = this.msInjectDelay;
return data;
}
/**
* enableSoftKeyboard(fEnable)
*
* In addition to enabling or disabling our own soft keyboard (if any), this also attempts to disable or enable
* (as appropriate) the textarea control (if any) that machines use to trigger a touch device's built-in keyboard.
*
* @this {Keyboard}
* @param {boolean} fEnable
*/
enableSoftKeyboard(fEnable)
{
if (this.controlSoftKeyboard) {
if (!fEnable) {
this.controlSoftKeyboard.style.display = "none";
if (this.controlTextKeyboard) {
this.controlTextKeyboard.readOnly = false;
}
} else {
this.controlSoftKeyboard.style.display = "block";
if (this.controlTextKeyboard) {
this.controlTextKeyboard.readOnly = true;
}
}