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 pathinput.js
1481 lines (1395 loc) · 58 KB
/
input.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 Maps keyboard, mouse, and touch inputs to device inputs
* @author <a href="mailto:[email protected]">Jeff Parsons</a>
* @copyright © 2012-2020 Jeff Parsons
* @license MIT
*
* This file is part of PCjs, a computer emulation software project at <https://www.pcjs.org>.
*/
"use strict";
/**
* @typedef {Config} InputConfig
* @property {string} class
* @property {Object} [bindings]
* @property {number} [version]
* @property {Array.<string>} [overrides]
* @property {Array.<number>} location
* @property {Array.<Array.<number>>|Object} [map]
* @property {boolean} [drag]
* @property {boolean} [scroll]
* @property {boolean} [hexagonal]
* @property {number} [releaseDelay]
*/
/**
* @typedef {Object} ActiveKey
* @property {number} keyNum (key number from the supplied keyMap)
* @property {number} msDown (timestamp of the most recent "down" event)
* @property {boolean} autoRelease (true to auto-release the key after 'releaseDelay'; set when "up" occurs too quickly)
*/
/**
* @typedef {Object} KeyListener
* @property {string|number} id
* @property {function(string,boolean)} func
*/
/**
* @typedef {Object} SurfaceListener
* @property {string} id
* @property {number} cxGrid
* @property {number} cyGrid
* @property {number} xGrid
* @property {number} yGrid
* @property {function(boolean)} func
*/
/**
* @typedef {Object} SurfaceState
* @property {number} xInput
* @property {number} yInput
* @property {number} cxInput
* @property {number} cyInput
* @property {number} hGap
* @property {number} vGap
* @property {number} cxSurface
* @property {number} cySurface
* @property {number} xPower
* @property {number} yPower
* @property {number} cxPower
* @property {number} cyPower
* @property {number} nRows
* @property {number} nCols
* @property {number} cxButton
* @property {number} cyButton
* @property {number} cxGap
* @property {number} cyGap
* @property {number} xStart
* @property {number} yStart
*/
/**
* @class {Input}
* @unrestricted
* @property {InputConfig} config
* @property {Array.<number>} location
* @property {Array.<Array.<number>>|Object} map
* @property {boolean} fDrag
* @property {boolean} fScroll
* @property {boolean} fHexagonal
* @property {number} releaseDelay
* @property {{
* surface: Element|undefined
* }} bindings
* @property {function(number,number)} onInput
* @property {function(number,number)} onHover
* @property {Array.<KeyListener>} aKeyListeners
* @property {Array.<SurfaceListener>} aSurfaceListeners
* @property {Array.<ActiveKey>} aActiveKeys
* @property {number} keyMods
*/
class Input extends Device {
/**
* Input(idMachine, idDevice, config)
*
* Sample config:
*
* "input": {
* "class": "Input",
* "location": [139, 325, 368, 478, 0.34, 0.5, 640, 853],
* "map": [
* ["2nd", "inv", "lnx", "\\b", "clr"],
* ["lrn", "xchg", "sq", "sqrt", "rcp"],
* ["sst", "sto", "rcl", "sum", "exp"],
* ["bst", "ee", "(", ")", "/"],
* ["gto", "7", "8", "9", "*"],
* ["sbr", "4", "5", "6", "-"],
* ["rst", "1", "2", "3", "+"],
* ["r/s", "0", ".", "+/-", "=|\\r"]
* ],
* "drag": false,
* "bindings": {
* "surface": "imageTI57",
* "power": "powerTI57",
* "reset": "resetTI57"
* }
* }
*
* A word about the "power" button: the page will likely use absolute positioning to overlay the HTML button
* onto the image of the physical button, and the temptation might be to use the style "display:none" to hide
* it, but "opacity:0" should be used instead, because otherwise our efforts to use it as focusable element
* may fail.
*
* @this {Input}
* @param {string} idMachine
* @param {string} idDevice
* @param {InputConfig} [config]
*/
constructor(idMachine, idDevice, config)
{
super(idMachine, idDevice, config);
this.messages = MESSAGE.INPUT;
this.onInput = this.onHover = null;
this.time = /** @type {Time} */ (this.findDeviceByClass("Time"));
this.machine = /** @type {Machine} */ (this.findDeviceByClass("Machine"));
/*
* If 'drag' is true, then the onInput() handler will be called whenever the current col and/or row
* changes, even if the mouse hasn't been released since the previous onInput() call.
*
* The default is false, because in general, allowing drag is a bad idea for calculator buttons. But
* I've made this an option for other input surfaces, like LED arrays, where you might want to turn a
* series of LEDs on or off.
*/
this.fDrag = this.getDefaultBoolean('drag', false);
/*
* If 'scroll' is true, then we do NOT call preventDefault() on touch events; this permits the input
* surface to be scrolled like any other part of the page. The default is false, because this has other
* side-effects (eg, inadvertent zooms).
*/
this.fScroll = this.getDefaultBoolean('scroll', false);
/*
* If 'hexagonal' is true, then we treat the input grid as hexagonal, where even rows of the associated
* display are offset.
*/
this.fHexagonal = this.getDefaultBoolean('hexagonal', false);
/*
* The 'releaseDelay' setting is necessary for devices (eg, old calculators) that are either too slow to
* notice every input transition and/or have debouncing logic that would otherwise be defeated.
*/
this.releaseDelay = this.getDefaultNumber('releaseDelay', 0);
/*
* This is set on receipt of the first 'touch' event of any kind, and is used by the 'mouse' event
* handlers to disregard mouse events if set.
*/
this.fTouch = false;
/*
* There are two supported configuration maps: a two-dimensional grid (gridMap) and a list of IDs (idMap).
*
* The two-dimensional button layouts do not (currently) support individual listeners; instead, any key event
* that corresponds to a position within the button layout is transformed into an (x,y) position that is passed
* on to a special function supplied to addInput().
*
* Any two-dimensional layout COULD be converted to a list of logical buttons, each with their own grid
* coordinates, but for devices like calculators that have a natural grid design, the two-dimensional layout
* is much simpler.
*
* Each ID in an idMap references an object with a "keys" array, a "grid" array, and a "state" value;
* the code below ensures that every object has all three. As "keys" go down and up (or mouse/touch events
* occur within a "grid"), the corresponding "state" is updated (0 or 1).
*
* A third type of map (keyMap) is supported, but not as a configuration parameter; any keyMap must be supplied
* by another device, via an addKeyMap() call.
*/
let map = this.config['map'];
this.gridMap = this.idMap = this.keyMap = null;
if (map) {
if (map.length) {
this.gridMap = map;
} else {
this.idMap = {};
let ids = Object.keys(map);
for (let i = 0; i < ids.length; i++) {
let grid = [];
let id = ids[i];
let keys = map[id];
if (typeof keys == "string") {
keys = [keys];
} else if (keys.length == undefined) {
grid = keys['grid'];
keys = keys['keys'];
if (typeof keys == "string") keys = [keys];
}
let state = 0;
this.idMap[id] = {keys, grid, state};
}
}
}
this.aKeyListeners = [];
this.aSurfaceListeners = [];
this.altFocus = false;
this.focusElement = this.altFocusElement = null;
let element = this.bindings[Input.BINDING.SURFACE];
if (element) this.addSurface(element, this.findBinding(config['focusBinding'], true), this.config['location']);
this.onReset();
}
/**
* addHover(onHover)
*
* @this {Input}
* @param {function(number,number)} onHover
*/
addHover(onHover)
{
this.onHover = onHover;
}
/**
* addInput(onInput)
*
* Called by the CPU device to set up input notifications.
*
* @this {Input}
* @param {function(number,number)} onInput
*/
addInput(onInput)
{
this.onInput = onInput;
}
/**
* addListener(type, id, func, init)
*
* @this {Input}
* @param {string} type (see Input.TYPE)
* @param {string|number} id
* @param {function(string,boolean)|function(number,boolean)|null} [func]
* @param {number|boolean|string} [init] (initial state; treated as a boolean for the SWITCH type)
* @returns {boolean} (true if successful, false if not)
*/
addListener(type, id, func, init)
{
if (type == Input.TYPE.KEYCODE) {
this.aKeyListeners.push({id, func});
return true;
}
if (type == Input.TYPE.IDMAP && this.idMap) {
let map = this.idMap[id];
if (map) {
let keys = map.keys;
if (keys && keys.length) {
this.aKeyListeners.push({id, func});
}
let grid = map.grid;
if (grid && grid.length) {
this.aSurfaceListeners.push({id, cxGrid: grid[0], cyGrid: grid[1], xGrid: grid[2], yGrid: grid[3], func});
}
return true;
}
return false;
}
/*
* The visual state of a SWITCH control (which could be a div or button or any other element) is controlled
* by its class attribute -- specifically, the last class name in the attribute. You must define two classes:
* one that ends with "On" for the on (true) state and another that ends with "Off" for the off (false) state.
*
* The first addListener() call should include both your listener function and the initial state; the control's
* class is automatically switched every time the control is clicked, and the newly switched state is passed to
* your function. If you need to change the state of the switch for other reasons, call addListener() with NO
* function, just a new initial state.
*/
if (type == Input.TYPE.SWITCH) {
let element = this.findBinding(/** @type {string} */ (id), true);
if (element) {
let getClass = function() {
return element.getAttribute("class") || "";
};
let setClass = function(s) {
element.setAttribute("class", s);
};
let getState = function() {
return (getClass().slice(-2) == "On")? true : false;
};
let setState = function(state) {
setClass(getClass().replace(/(On|Off)$/, state? "On" : "Off"));
return state;
};
if (init != undefined) setState(init);
if (func) {
element.addEventListener('click', function onSwitchClick() {
func(id, setState(!getState()));
});
}
}
return false;
}
return false;
}
/**
* addKeyMap(device, keyMap, clickMap)
*
* This records the caller's keyMap, changes onKeyCode() to record any physical keyCode
* that exists in the keyMap as an active key, and allows the caller to use getActiveKey()
* to get the mapped keyNum of an active key.
*
* It also supports an optional clickMap, which lists a set of bindings that the caller
* supports. For every valid binding, we add an onclick handler that simulates a call to
* onKeyCode() with the corresponding keyCode.
*
* @this {Input}
* @param {Device} device
* @param {Object} keyMap
* @param {Object} [clickMap]
* @returns {boolean}
*/
addKeyMap(device, keyMap, clickMap)
{
if (!this.keyMap) {
let input = this;
this.keyMap = keyMap;
this.timerAutoRelease = this.time.addTimer("timerAutoRelease", function onAutoRelease() {
input.checkAutoRelease();
});
if (clickMap) {
for (let binding in clickMap) {
let element = device.bindings[binding];
if (element) {
element.addEventListener('click', function onKeyClick() {
let clickBinding = clickMap[binding];
let keyCode, down = true, autoRelease = true;
if (typeof clickBinding == "number") {
keyCode = clickBinding;
} else {
/*
* If clickBinding is not a number, the only other possibility currently supported
* is an Array where the first entry is a keyCode modifier; specifically, KEYCODE.LOCK.
*/
keyCode = clickBinding[0];
input.assert(keyCode == WebIO.KEYCODE.LOCK);
if (keyCode == WebIO.KEYCODE.LOCK) {
/*
* In the case of KEYCODE.LOCK, the next entry is the actual keyCode, and we look
* to the element's "data-value" attribute for whether clicking the element should
* "lock" the keyCode ("0") or "unlock" it ("1"). Locking a key is a simple matter
* of simulating a keydown without autoRelease; unlocking is the equivalent of a keyup.
*/
let clickState = +element.getAttribute("data-value") || 0;
keyCode = clickBinding[1];
down = !clickState;
autoRelease = false;
element.setAttribute("data-value", 1 - clickState);
element.style.fontWeight = down? "bold" : "normal";
}
}
input.onKeyCode(keyCode, down, autoRelease);
input.setFocus();
});
} else {
if (DEBUG) input.printf("click map element '%s' not found\n", binding);
}
}
}
return true;
}
return false;
}
/**
* checkKeyListeners(id, down)
*
* @this {Input}
* @param {string|number} id
* @param {boolean} down
*/
checkKeyListeners(id, down)
{
for (let i = 0; i < this.aKeyListeners.length; i++) {
let listener = this.aKeyListeners[i];
if (listener.id === id) {
listener.func(id, down);
}
}
}
/**
* addSurface(inputElement, focusElement, location)
*
* @this {Input}
* @param {Element} inputElement (surface element)
* @param {Element|null} [focusElement] (should be provided if surface element is non-focusable)
* @param {Array} [location]
*/
addSurface(inputElement, focusElement, location = [])
{
/*
* The location array, eg:
*
* "location": [139, 325, 368, 478, 0.34, 0.5, 640, 853, 180, 418, 75, 36],
*
* contains the top left corner (xInput, yInput) and dimensions (cxInput, cyInput)
* of the input rectangle where the buttons described in the map are located, relative
* to the surface image. It also describes the average amount of horizontal and vertical
* space between buttons, as fractions of the average button width and height (hGap, vGap).
*
* With all that, we can now calculate the center lines for each column and row. This
* obviously assumes that all the buttons are evenly laid out in a perfect grid. For
* devices that don't have such a nice layout, a different location array format will
* have to be defined.
*
* NOTE: While element.naturalWidth and element.naturalHeight should, for all modern
* browsers, contain the surface image's dimensions as well, those values still might not
* be available if our constructor is called before the page's onload event has fired,
* so we allow them to be stored in the next two elements of the location array, too.
*
* Finally, the position and size of the device's power button may be stored in the array
* as well, in case some browsers refuse to generate onClickPower() events (eg, if they
* think the button is inaccessible/not visible).
*/
if (location.length || this.gridMap || this.idMap) {
let state = {};
state.xInput = location[0] || 0;
state.yInput = location[1] || 0;
state.cxInput = location[2] || inputElement.clientWidth;
state.cyInput = location[3] || inputElement.clientHeight;
state.hGap = location[4] || 1.0;
state.vGap = location[5] || 1.0;
state.cxSurface = location[6] || inputElement.naturalWidth || state.cxInput;
state.cySurface = location[7] || inputElement.naturalHeight || state.cyInput;
state.xPower = location[8] || 0;
state.yPower = location[9] || 0;
state.cxPower = location[10] || 0;
state.cyPower = location[11] || 0;
if (this.gridMap) {
state.nRows = this.gridMap.length;
state.nCols = this.gridMap[0].length;
} else {
state.nCols = state.hGap;
state.nRows = state.vGap;
state.hGap = state.vGap = 0;
}
/*
* To calculate the average button width (cxButton), we know that the overall width
* must equal the sum of all the button widths + the sum of all the button gaps:
*
* cxInput = nCols * cxButton + nCols * (cxButton * hGap)
*
* The number of gaps would normally be (nCols - 1), but we require that cxInput include
* only 1/2 the gap at the edges, too. Solving for cxButton:
*
* cxButton = cxInput / (nCols + nCols * hGap)
*/
state.cxButton = (state.cxInput / (state.nCols + state.nCols * state.hGap))|0;
state.cyButton = (state.cyInput / (state.nRows + state.nRows * state.vGap))|0;
state.cxGap = (state.cxButton * state.hGap)|0;
state.cyGap = (state.cyButton * state.vGap)|0;
/*
* xStart and yStart record the last 'touchstart' or 'mousedown' position on the surface
* image; they will be reset to -1 when movement has ended (eg, 'touchend' or 'mouseup').
*/
state.xStart = state.yStart = -1;
this.captureMouse(inputElement, state);
this.captureTouch(inputElement, state);
/*
* We use a timer for the touch/mouse release events, to ensure that the machine had
* enough time to notice the input before releasing it.
*/
if (this.time && this.releaseDelay) {
let input = this;
this.timerInputRelease = this.time.addTimer("timerInputRelease", function onInputRelease() {
if (state.xStart < 0 && state.yStart < 0) { // auto-release ONLY if it's REALLY released
input.setPosition(-1, -1);
}
});
}
}
if (this.gridMap || this.idMap || this.keyMap) {
/*
* This auto-releases the last key reported after an appropriate delay, to ensure that
* the machine had enough time to notice the corresponding button was pressed.
*/
if (this.time && this.releaseDelay) {
let input = this;
this.timerKeyRelease = this.time.addTimer("timerKeyRelease", function onKeyRelease() {
input.onKeyTimer();
});
}
/*
* I used to maintain a single-key buffer (this.keyPressed) and would immediately release
* that key as soon as another key was pressed, but it appears that the ROM wants a minimum
* delay between release and the next press -- probably for de-bouncing purposes. So we
* maintain a key state: 0 means no key has gone down or up recently, 1 means a key just went
* down, and 2 means a key just went up. keysPressed maintains a queue of keys (up to 16)
* received while key state is non-zero.
*/
this.keyState = 0;
this.keyActive = "";
this.keysPressed = [];
/*
* I'm attaching my key event handlers to the document object, since image elements are
* not focusable. I'm disinclined to do what I've done with other machines (ie, create an
* invisible <textarea> overlay), because in this case, I don't really want a soft keyboard
* popping up and obscuring part of the display.
*
* A side-effect, however, is that if the user attempts to explicitly give the image
* focus, we don't have anything for focus to attach to. We address that in onMouseDown(),
* by redirecting focus to the "power" button, if any, not because we want that or any other
* button to have focus, but simply to remove focus from any other input element on the page.
*/
let element = inputElement;
if (focusElement) {
element = focusElement;
if (!this.focusElement && focusElement.nodeName == "BUTTON") {
element = document;
this.focusElement = focusElement;
/*
* Although we've elected to attach key handlers to the document object in this case,
* we also attach to the inputElement as an alternative.
*/
this.captureKeys(inputElement);
this.altFocusElement = inputElement;
}
}
this.captureKeys(element);
if (!this.focusElement) {
this.focusElement = element;
}
}
}
/**
* checkSurfaceListeners(action, x, y, cx, cy)
*
* @this {Input}
* @param {number} action (eg, Input.ACTION.MOVE, Input.ACTION.PRESS, Input.ACTION.RELEASE)
* @param {number} x (valid for MOVE and PRESS, not RELEASE)
* @param {number} y (valid for MOVE and PRESS, not RELEASE)
* @param {number} cx (width of the element that received the event)
* @param {number} cy (height of the element that received the event)
*/
checkSurfaceListeners(action, x, y, cx, cy)
{
if (action == Input.ACTION.PRESS || action == Input.ACTION.RELEASE) {
for (let i = 0; i < this.aSurfaceListeners.length; i++) {
let listener = this.aSurfaceListeners[i];
if (action == Input.ACTION.RELEASE) {
listener.func(listener.id, false);
continue;
}
let cxSpan = (cx / listener.cxGrid)|0, xActive = (x / cxSpan)|0;
let cySpan = (cy / listener.cyGrid)|0, yActive = (y / cySpan)|0;
if (xActive == listener.xGrid && yActive == listener.yGrid) {
listener.func(listener.id, true);
}
}
}
}
/**
* advanceKeyState()
*
* @this {Input}
*/
advanceKeyState()
{
if (!this.releaseDelay) {
this.onKeyTimer();
} else {
this.time.setTimer(this.timerKeyRelease, this.releaseDelay);
}
}
/**
* addSelect(device, binding, text, value, top)
*
* @this {Input}
* @param {Device} device
* @param {string} binding
* @param {string} text
* @param {string} value
* @param {boolean} [top] (default is false)
* @returns {boolean}
*/
addSelect(device, binding, text, value, top = false)
{
let select = /** @type {HTMLSelectElement} */ (device.bindings[binding]);
if (select) {
let i;
for (let i = 0; i < select.options.length; i++) {
if (select.options[i].text == text) break;
}
if (i == select.options.length) {
let option = document.createElement("option");
option.text = text;
option.value = value;
// select.add(option);
if (top && select.childNodes[0]) {
select.insertBefore(option, select.childNodes[0]);
} else {
select.appendChild(option);
}
return true;
}
}
return false;
}
/**
* bindSelect(device, binding, items, onSelect)
*
* @this {Input}
* @param {Device} device
* @param {string} binding
* @param {Array.<Media>} items
* @param {function(Event)} [onSelect]
*/
bindSelect(device, binding, items, onSelect)
{
let select = device.bindings[binding];
if (select) {
for (let i = 0; i < items.length; i++) {
let name = items[i]['name'];
let path = items[i]['path'];
this.addSelect(device, binding, name, path);
}
}
if (onSelect) select.onchange = onSelect;
}
/**
* captureKeys(element)
*
* @this {Input}
* @param {Document|Element} element
*/
captureKeys(element)
{
let input = this;
/**
* isFocus(element, event)
*
* TODO: Determine the wisdom of having more than one element on the page with KeyboardEvent handlers.
* Originally, my idea was to use a non-textarea element (such as a button) to capture "raw" keyboard
* events for machines with virtual keyboards, at least when not running full-screen, to avoid issues with
* composition keystrokes. However, that approach creates focus challenges, as well as the apparent
* duplication of certain key events (eg, CAPS-LOCK).
*
* @param {Element} element
* @param {Event} event
* @returns {KeyboardEvent|null}
*/
let isFocus = function(element, event) {
let activeElement = /* element || */ document.activeElement;
if (!input.focusElement || activeElement == input.focusElement || activeElement == input.altFocusElement) {
return /** @type {KeyboardEvent} */ (event || window.event);
}
return null;
};
/**
* printEvent(type, code, used)
*
* @param {string} type
* @param {number} code
* @param {boolean} [used]
*/
let printEvent = function(type, code, used) {
let activeElement = document.activeElement;
input.printf(MESSAGE.KEY + MESSAGE.EVENT, "%s.onKey%s(%d): %5.2f (%s)\n", activeElement.id || activeElement.nodeName, type, code, (Date.now() / 1000) % 60, used != undefined? (used? "used" : "unused") : "ignored");
};
element.addEventListener(
'keydown',
function onKeyDown(event) {
event = isFocus(this, event);
if (event) {
let keyCode = event.which || event.keyCode;
let used = input.onKeyCode(keyCode, true, false, event);
printEvent("Down", keyCode, used);
if (used) event.preventDefault();
}
}
);
element.addEventListener(
'keypress',
function onKeyPress(event) {
event = isFocus(this, event);
if (event) {
let charCode = event.which || event.charCode;
let used = input.onKeyCode(charCode);
printEvent("Press", charCode, used);
if (used) event.preventDefault();
}
}
);
element.addEventListener(
'keyup',
function onKeyUp(event) {
event = isFocus(this, event);
if (event) {
let keyCode = event.which || event.keyCode;
let used = input.onKeyCode(keyCode, false, false, event);
printEvent("Up", keyCode);
if (used) event.preventDefault();
/*
* We reset the contents of any textarea element being used exclusively
* for keyboard input, to prevent its contents from growing uncontrollably.
*/
if (element.nodeName == "TEXTAREA") element.value = "";
}
}
);
/*
* The following onBlur() and onFocus() handlers are currently just for debugging purposes, but
* PCx86 experience suggests that we may also eventually need them for future pointer-locking support.
*/
if (DEBUG) {
element.addEventListener(
'blur',
function onBlur(event) {
input.printf(MESSAGE.KEY + MESSAGE.EVENT, "onBlur(%s)\n", event.target.id || event.target.nodeName);
}
);
element.addEventListener(
'focus',
function onFocus(event) {
input.printf(MESSAGE.KEY + MESSAGE.EVENT, "onFocus(%s)\n", event.target.id || event.target.nodeName);
}
);
}
}
/**
* captureMouse(element, state)
*
* @this {Input}
* @param {Element} element
* @param {SurfaceState} state
*/
captureMouse(element, state)
{
let input = this;
element.addEventListener(
'mousedown',
function onMouseDown(event) {
if (input.fTouch) return;
/*
* If there are any text input elements on the page that might currently have focus,
* this is a good time to divert focus to a focusable element of our own (eg, focusElement).
* Otherwise, key presses could be confusingly processed in two places.
*
* Unfortunately, setting focus on an element can cause the browser to scroll the element
* into view, so to avoid that, we use the following scrollTo() work-around.
*/
let focusElement = input.altFocus? input.altFocusElement : input.focusElement;
if (focusElement) {
let x = window.scrollX, y = window.scrollY;
focusElement.focus();
window.scrollTo(x, y);
}
if (!event.button) {
input.onSurfaceEvent(element, Input.ACTION.PRESS, event, state);
}
}
);
element.addEventListener(
'mousemove',
function onMouseMove(event) {
if (input.fTouch) return;
input.onSurfaceEvent(element, Input.ACTION.MOVE, event, state);
}
);
element.addEventListener(
'mouseup',
function onMouseUp(event) {
if (input.fTouch) return;
if (!event.button) {
input.onSurfaceEvent(element, Input.ACTION.RELEASE, event, state);
}
}
);
element.addEventListener(
'mouseout',
function onMouseOut(event) {
if (input.fTouch) return;
if (state.xStart < 0) {
input.onSurfaceEvent(element, Input.ACTION.MOVE, event, state);
} else {
input.onSurfaceEvent(element, Input.ACTION.RELEASE, event, state);
}
}
);
}
/**
* captureTouch(element, state)
*
* @this {Input}
* @param {Element} element
* @param {SurfaceState} state
*/
captureTouch(element, state)
{
let input = this;
/*
* NOTE: The mouse event handlers below deal only with events where the left button is involved
* (ie, left button is pressed, down, or released).
*/
element.addEventListener(
'touchstart',
function onTouchStart(event) {
/*
* Under normal circumstances (ie, when fScroll is false), when any touch events arrive,
* onSurfaceEvent() calls preventDefault(), which prevents a variety of potentially annoying
* behaviors (ie, zooming, scrolling, fake mouse events, etc). Under non-normal circumstances,
* (ie, when fScroll is true), we set fTouch on receipt of a 'touchstart' event, which will
* help our mouse event handlers avoid any redundant actions due to fake mouse events.
*/
if (input.fScroll) input.fTouch = true;
input.onSurfaceEvent(element, Input.ACTION.PRESS, event, state);
}
);
element.addEventListener(
'touchmove',
function onTouchMove(event) {
input.onSurfaceEvent(element, Input.ACTION.MOVE, event, state);
}
);
element.addEventListener(
'touchend',
function onTouchEnd(event) {
input.onSurfaceEvent(element, Input.ACTION.RELEASE, event, state);
}
);
}
/**
* checkAutoRelease()
*
* Auto-release handler for active keys.
*
* @this {Input}
*/
checkAutoRelease()
{
let i = 0;
let msDelayMin = -1;
while (i < this.aActiveKeys.length) {
let activeKey = this.aActiveKeys[i];
if (activeKey.autoRelease) {
let keyNum = activeKey.keyNum;
let msDown = activeKey.msDown;
let msDuration = Date.now() - msDown;
let msDelay = this.releaseDelay - msDuration;
if (msDelay > 0) {
if (msDelayMin < 0 || msDelayMin > msDelay) {
msDelayMin = msDelay;
}
} else {
/*
* Because the key is already in the auto-release state, this next call guarantees that the
* key will be removed from the array; a consequence of that removal, however, is that we must
* reset our array index to zero.
*/
this.removeActiveKey(keyNum);
i = 0;
continue;
}
}
i++;
}
if (msDelayMin >= 0) {
this.time.setTimer(this.timerAutoRelease, msDelayMin);
}
}
/**
* getActiveKey(index)
*
* @this {Input}
* @param {number} index
* @returns {number} (the requested active keyNum, -1 if none)
*/
getActiveKey(index)
{
let keyNum = -1;
if (index < this.aActiveKeys.length) {
keyNum = this.aActiveKeys[index].keyNum;
}
return keyNum;
}
/**
* addActiveKey(keyNum, autoRelease)
*
* @this {Input}
* @param {number|Array.<number>} keyNum
* @param {boolean} [autoRelease]
*/
addActiveKey(keyNum, autoRelease = false)
{
if (typeof keyNum != "number") {
for (let i = 0; i < keyNum.length; i++) {
this.addActiveKey(keyNum[i], autoRelease);
}
return;
}
let i = this.isActiveKey(keyNum);
let msDown = Date.now();
if (i < 0) {
this.aActiveKeys.push({
keyNum, msDown, autoRelease
});
this.printf(MESSAGE.KEY + MESSAGE.INPUT, "addActiveKey(keyNum=%d,autoRelease=%b)\n", keyNum, autoRelease);
} else {
this.aActiveKeys[i].msDown = msDown;
this.aActiveKeys[i].autoRelease = autoRelease;
}
if (autoRelease) this.checkAutoRelease();
}
/**
* isActiveKey(keyNum)
*
* @this {Input}
* @param {number} keyNum
* @returns {number} index of keyNum in aActiveKeys, or -1 if not found
*/
isActiveKey(keyNum)
{
for (let i = 0; i < this.aActiveKeys.length; i++) {
if (this.aActiveKeys[i].keyNum == keyNum) return i;
}
return -1;
}
/**
* removeActiveKey(keyNum)
*
* @this {Input}
* @param {number|Array.<number>} keyNum
*/
removeActiveKey(keyNum)
{
if (typeof keyNum != "number") {
for (let i = 0; i < keyNum.length; i++) {
this.removeActiveKey(keyNum[i]);
}
return;
}
let i = this.isActiveKey(keyNum);
if (i >= 0) {
let activeKey = this.aActiveKeys[i];
let msNow = Date.now();
let msDown = activeKey.msDown;
this.assert(msDown && msNow >= msDown);
let msDuration = msNow - msDown;
if (msDuration < this.releaseDelay) {
activeKey.autoRelease = true;
this.checkAutoRelease();