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 pathwebio.js
1654 lines (1581 loc) · 55.3 KB
/
webio.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 Class for basic browser-based support
* @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";
/**
* Media libraries generally consist of an array of Media objects.
*
* @typedef {Object} Media
* @property {string} name
* @property {string} path
*/
/**
* The following properties are the standard set of properties a Config object may contain.
*
* @typedef {Object} Config
* @property {string} [class]
* @property {Object} [bindings]
* @property {number} [version]
* @property {Array.<string>} [overrides]
*/
/**
* @class {WebIO}
* @unrestricted
* @property {Object} bindings
* @property {number} messages
* @property {WebIO} machine
*/
class WebIO extends StdIO {
/**
* WebIO(isMachine)
*
* @this {WebIO}
* @param {boolean} isMachine
*/
constructor(isMachine)
{
super();
this.bindings = {};
this.messages = 0;
/*
* If this is the machine device, initialize a set of per-machine variables; if it's not,
* the Device constructor will update this.machine with the actual machine device (see addDevice()).
*/
this.machine = this;
if (isMachine) {
this.machine.messages = 0;
this.machine.aCommands = [];
this.machine.iCommand = 0;
this.machine.handlers = {};
this.machine.isFullScreen = false;
}
}
/**
* addBinding(binding, element)
*
* @this {WebIO}
* @param {string} binding
* @param {Element} element
*/
addBinding(binding, element)
{
let webIO = this;
switch(binding) {
case WebIO.BINDING.CLEAR:
element.onclick = () => this.clear();
break;
case WebIO.BINDING.PRINT:
this.disableAuto(element);
/*
* An onKeyDown handler has been added to this element to intercept special (non-printable) keys, such as
* the UP and DOWN arrow keys, which are used to implement a simple command history/recall feature.
*/
element.addEventListener(
'keydown',
function onKeyDown(event) {
webIO.onCommandEvent(event, true);
}
);
/*
* One purpose of the onKeyPress handler for this element is to stop event propagation, so that if the
* element has been explicitly given focus, any key presses won't be picked up by the Input device (which,
* as that device's constructor explains, is monitoring key presses for the entire document).
*
* The other purpose is to support the entry of commands and pass them on to parseCommands().
*/
element.addEventListener(
'keypress',
function onKeyPress(event) {
webIO.onCommandEvent(event);
}
);
break;
}
}
/**
* addBindings(bindings)
*
* Use the set of DESIRED bindings (this.config['bindings']) to build the set of ACTUAL bindings (this.bindings).
*
* bindings is usually an object map that maps internal binding IDs to external element IDs, but it can also be
* an array of IDs (aka "direct bindings"); using an array of direct bindings simply means that the web page is
* using element IDs that are the same as our internal IDs. The downside of direct bindings is that you may have
* problems loading more than one machine on the page if there's any overlap in their bindings.
*
* @this {WebIO}
* @param {Object} [bindings]
*/
addBindings(bindings = {})
{
if (!this.config.bindings) {
this.config.bindings = bindings;
}
/*
* To relieve every device from having to explicitly declare its own container, set up a default.
* When using direct bindings, the default is simply 'container'; otherwise, the default 'container'
* element ID is whatever the device ID is.
*/
let fDirectBindings = Array.isArray(bindings);
if (fDirectBindings) {
if (bindings.indexOf('container') < 0) {
bindings.push('container');
}
} else {
if (!bindings['container']) {
bindings['container'] = this.idDevice;
}
}
for (let binding in bindings) {
let id = bindings[binding];
if (fDirectBindings) {
binding = id;
} else {
/*
* This new bit of code allows us to define a binding like this:
*
* "label": "0"
*
* and we will automatically look for "label0", "label1", etc, and build an array of sequential
* bindings for "label". We stop building the array as soon as a missing binding is encountered.
*/
if (id.match(/^[0-9]+$/)) {
let i = +id;
this.bindings[binding] = [];
do {
id = binding + i++;
let element = document.getElementById(id);
if (!element) break;
this.bindings[binding].push(element);
} while (true);
continue;
}
}
let element = document.getElementById(id);
if (element) {
this.bindings[binding] = element;
this.addBinding(binding, element);
continue;
}
if (MAXDEBUG && !fDirectBindings && id != this.idDevice) {
this.printf("unable to find element '%s' for device '%s'\n", id, this.idDevice);
}
}
}
/**
* addBindingOptions(element, options, fReset, sDefault)
*
* @this {WebIO}
* @param {Element|HTMLSelectElement} element
* @param {Object} options (eg, key/value pairs for a series of "option" elements)
* @param {boolean} [fReset]
* @param {string} [sDefault]
*/
addBindingOptions(element, options, fReset, sDefault)
{
if (fReset) {
element.options.length = 0;
}
if (options) {
for (let prop in options) {
let option = document.createElement("option");
option.text = prop;
option.value = (typeof options[prop] == "string"? options[prop] : prop);
element.appendChild(option);
if (option.value == sDefault) element.selectedIndex = element.options.length - 1;
}
}
}
/**
* addHandler(type, func)
*
* @this {WebIO}
* @param {string} type
* @param {function(Array.<string>)} func
*/
addHandler(type, func)
{
if (!this.machine.handlers[type]) this.machine.handlers[type] = [];
this.machine.handlers[type].push(func);
}
/**
* alert(format, args)
*
* The format argument can be preceded by a boolean (fDiag) which, if true, will suppress the alert().
*
* @this {WebIO}
* @param {string|boolean} format
* @param {...} [args]
*/
alert(format, args)
{
let fDiag = false;
if (typeof format == "boolean") {
fDiag = format;
format = args.shift();
}
let s = this.sprintf(format, ...args);
if (s) {
this.println(s);
if (!fDiag) alert(s);
}
}
/**
* assert(f, format, args)
*
* Verifies conditions that must be true (for DEBUG builds only).
*
* The Closure Compiler should automatically remove all references to assert() in non-DEBUG builds.
*
* TODO: Add a task to the build process that "asserts" there are no instances of "assertion failure" in RELEASE builds.
*
* @this {WebIO}
* @param {*} f is the expression asserted to be true
* @param {string} [format] is an optional description of the assertion failure
* @param {...} [args]
*/
assert(f, format, ...args)
{
if (DEBUG) {
if (!f) {
throw new Error(format? this.sprintf(format, ...args) : "assertion failure");
}
}
}
/**
* clear()
*
* @this {WebIO}
*/
clear()
{
let element = this.findBinding(WebIO.BINDING.PRINT, true);
if (element) element.value = "";
}
/**
* disableAuto(element)
*
* @this {WebIO}
* @param {Element} element
*/
disableAuto(element)
{
element.setAttribute("autocapitalize", "off");
element.setAttribute("autocomplete", "off");
element.setAttribute("autocorrect", "off");
element.setAttribute("spellcheck", "false");
/*
* This was added for Firefox (Safari will clear the <textarea> on a page reload, but Firefox does not).
*/
element.value = "";
}
/**
* error(format, args)
*
* @this {WebIO}
* @param {string} format
* @param {...} [args]
*/
error(format, args)
{
this.alert("%s", this.sprintf(format, ...args));
}
/**
* findBinding(name, all)
*
* @this {WebIO}
* @param {string} [name]
* @param {boolean} [all]
* @returns {Element|null|undefined}
*/
findBinding(name, all)
{
return this.bindings[name];
}
/**
* findHandlers(type)
*
* @this {WebIO}
* @param {string} type
* @returns {Array.<function(Array.<string>)>|undefined}
*/
findHandlers(type)
{
return this.machine.handlers[type];
}
/**
* findProperty(obj, sProp, sSuffix)
*
* If both sProp and sSuffix are set, then any browser-specific prefixes are inserted between sProp and sSuffix,
* and if a match is found, it is returned without sProp.
*
* For example, if findProperty(document, 'on', 'fullscreenchange') discovers that 'onwebkitfullscreenchange' exists,
* it will return 'webkitfullscreenchange', in preparation for an addEventListener() call.
*
* More commonly, sSuffix is not used, so whatever property is found is returned as-is.
*
* @this {WebIO}
* @param {Object|null|undefined} obj
* @param {string} sProp
* @param {string} [sSuffix]
* @returns {string|null}
*/
findProperty(obj, sProp, sSuffix)
{
if (obj) {
do {
for (let i = 0; i < WebIO.BrowserPrefixes.length; i++) {
let sName = WebIO.BrowserPrefixes[i];
if (sSuffix) {
sName += sSuffix;
let sEvent = sProp + sName;
if (sEvent in obj) return sName;
} else {
if (!sName) {
sName = sProp[0];
} else {
sName += sProp[0].toUpperCase();
}
sName += sProp.substr(1);
if (sName in obj) return sName;
}
}
if (sProp.indexOf("screen") < 0) break;
sProp = sProp.replace("screen", "Screen");
} while (true);
}
return null;
}
/**
* getBindingID(name)
*
* Since this.bindings contains the actual elements, not their original IDs, we must delve back into
* the original this.config['bindings'] to determine the original ID.
*
* @this {WebIO}
* @param {string} name
* @returns {string|undefined}
*/
getBindingID(name)
{
return this.config['bindings'] && this.config['bindings'][name];
}
/**
* getBindingText(name)
*
* @this {WebIO}
* @param {string} name
* @returns {string|undefined}
*/
getBindingText(name)
{
let text;
let element = this.bindings[name];
if (element) text = element.textContent;
return text;
}
/**
* getBounded(n, min, max)
*
* Restricts n to the bounds defined by min and max. A side-effect is ensuring that the return
* value is ALWAYS a number, even if n is not.
*
* @this {WebIO}
* @param {number} n
* @param {number} min
* @param {number} max
* @returns {number} (updated n)
*/
getBounded(n, min, max)
{
this.assert(min <= max);
n = +n || 0;
if (n < min) n = min;
if (n > max) n = max;
return n;
}
/**
* getDefault(idConfig, defaultValue, mappings)
*
* @this {WebIO}
* @param {string} idConfig
* @param {*} defaultValue
* @param {Object} [mappings] (used to provide optional user-friendly mappings for values)
* @returns {*}
*/
getDefault(idConfig, defaultValue, mappings)
{
let value = this.config[idConfig];
if (value === undefined) {
value = defaultValue;
} else {
if (mappings && mappings[value] !== undefined) {
value = mappings[value];
}
let type = typeof defaultValue;
if (typeof value != type) {
this.assert(false);
if (type == "boolean") {
value = !!value;
} else if (typeof defaultValue == "number") {
value = +value;
}
}
}
return value;
}
/**
* getDefaultBoolean(idConfig, defaultValue)
*
* @this {WebIO}
* @param {string} idConfig
* @param {boolean} defaultValue
* @returns {boolean}
*/
getDefaultBoolean(idConfig, defaultValue)
{
return /** @type {boolean} */ (this.getDefault(idConfig, defaultValue));
}
/**
* getDefaultNumber(idConfig, defaultValue, mappings)
*
* @this {WebIO}
* @param {string} idConfig
* @param {number} defaultValue
* @param {Object} [mappings]
* @returns {number}
*/
getDefaultNumber(idConfig, defaultValue, mappings)
{
return /** @type {number} */ (this.getDefault(idConfig, defaultValue, mappings));
}
/**
* getDefaultString(idConfig, defaultValue)
*
* @this {WebIO}
* @param {string} idConfig
* @param {string} defaultValue
* @returns {string}
*/
getDefaultString(idConfig, defaultValue)
{
return /** @type {string} */ (this.getDefault(idConfig, defaultValue));
}
/**
* getHost()
*
* This is like getHostName() but with the port number, if any.
*
* @this {WebIO}
* @returns {string}
*/
getHost()
{
return (window? window.location.host : "localhost");
}
/**
* getHostName()
*
* @this {WebIO}
* @returns {string}
*/
getHostName()
{
return (window? window.location.hostname : this.getHost());
}
/**
* getHostOrigin()
*
* @this {WebIO}
* @returns {string}
*/
getHostOrigin()
{
return (window? window.location.origin : this.getHost());
}
/**
* getHostPath()
*
* @this {WebIO}
* @returns {string|null}
*/
getHostPath()
{
return (window? window.location.pathname : null);
}
/**
* getHostProtocol()
*
* @this {WebIO}
* @returns {string}
*/
getHostProtocol()
{
return (window? window.location.protocol : "file:");
}
/**
* getHostURL()
*
* @this {WebIO}
* @returns {string|null}
*/
getHostURL()
{
return (window? window.location.href : null);
}
/**
* getMedia(media, done)
*
* Used to load media items and media libraries.
*
* @this {WebIO}
* @param {Object|Array|string} media (if string, then the URL of a media item or library)
* @param {function(*)} done
* @returns {boolean} (true if media item or library already loaded; otherwise, the media is loaded)
*/
getMedia(media, done)
{
let device = this;
if (typeof media == "string") {
this.getResource(media, function onLoadMedia(sURL, sResource, readyState, nErrorCode) {
let fDiag = false;
let sErrorMessage, resource;
if (nErrorCode) {
/*
* Errors can happen for innocuous reasons, such as the user switching away too quickly, forcing
* the request to be cancelled. And unfortunately, the browser cancels XMLHttpRequest requests
* BEFORE it notifies any page event handlers, so if the machine is being powered down, we won't
* know that yet. For now, we suppress the alert() if there's no specific error (nErrorCode < 0).
*/
fDiag = (nErrorCode < 0);
sErrorMessage = sURL;
} else {
if (readyState != 4) return;
try {
resource = JSON.parse(sResource);
} catch(err) {
nErrorCode = 1;
sErrorMessage = err.message || "unknown error";
}
}
if (sErrorMessage) {
device.alert(fDiag, "Unable to load %s media (error %d: %s)", device.idDevice, nErrorCode, sErrorMessage);
}
done(resource);
});
return false;
}
done(media);
return true;
}
/**
* getResource(url, done)
*
* Request the specified resource, and once the request is complete, notify done().
*
* done() is passed four parameters:
*
* done(url, sResource, readyState, nErrorCode)
*
* readyState comes from the request's 'readyState' property, and the operation should not be
* considered complete until readyState is 4.
*
* If nErrorCode is zero, sResource should contain the requested data; otherwise, an error occurred.
*
* @this {WebIO}
* @param {string} url
* @param {function(string,string,number,number)} done
*/
getResource(url, done)
{
let webIO = this;
let nErrorCode = 0, sResource = null;
let xmlHTTP = (window.XMLHttpRequest? new window.XMLHttpRequest() : new window.ActiveXObject("Microsoft.XMLHTTP"));
xmlHTTP.onreadystatechange = function()
{
if (xmlHTTP.readyState !== 4) {
done(url, sResource, xmlHTTP.readyState, nErrorCode);
return;
}
/*
* The following line was recommended for WebKit, as a work-around to prevent the handler firing multiple
* times when debugging. Unfortunately, that's not the only XMLHttpRequest problem that occurs when
* debugging, so I think the WebKit problem is deeper than that. When we have multiple XMLHttpRequests
* pending, any debugging activity means most of them simply get dropped on floor, so what may actually be
* happening are mis-notifications rather than redundant notifications.
*
* xmlHTTP.onreadystatechange = undefined;
*/
sResource = xmlHTTP.responseText;
/*
* The normal "success" case is an HTTP status code of 200, but when testing with files loaded
* from the local file system (ie, when using the "file:" protocol), we have to be a bit more "flexible".
*/
if (xmlHTTP.status == 200 || !xmlHTTP.status && sResource.length && webIO.getHostProtocol() == "file:") {
// if (MAXDEBUG) Web.log("xmlHTTP.onreadystatechange(" + url + "): returned " + sResource.length + " bytes");
}
else {
nErrorCode = xmlHTTP.status || -1;
}
done(url, sResource, xmlHTTP.readyState, nErrorCode);
};
xmlHTTP.open("GET", url, true);
xmlHTTP.send();
}
/**
* getURLParms(sParms)
*
* @this {WebIO}
* @param {string} [sParms] containing the parameter portion of a URL (ie, after the '?')
* @returns {Object} containing properties for each parameter found
*/
getURLParms(sParms)
{
let parms = WebIO.URLParms;
if (!parms) {
parms = {};
if (window) {
if (!sParms) {
/*
* Note that window.location.href returns the entire URL, whereas window.location.search
* returns only parameters, if any (starting with the '?', which we skip over with a substr() call).
*/
sParms = window.location.search.substr(1);
}
let match;
let pl = /\+/g; // RegExp for replacing addition symbol with a space
let search = /([^&=]+)=?([^&]*)/g;
let decode = function decodeParameter(s) {
return decodeURIComponent(s.replace(pl, " ")).trim();
};
while ((match = search.exec(sParms))) {
parms[decode(match[1])] = decode(match[2]);
}
}
WebIO.URLParms = parms;
}
return parms;
}
/**
* hasLocalStorage
*
* If localStorage support exists, is enabled, and works, return true.
*
* @this {WebIO}
* @returns {boolean}
*/
hasLocalStorage()
{
if (WebIO.LocalStorage.Available === undefined) {
let f = false;
if (window) {
try {
window.localStorage.setItem(WebIO.LocalStorage.Test, WebIO.LocalStorage.Test);
f = (window.localStorage.getItem(WebIO.LocalStorage.Test) == WebIO.LocalStorage.Test);
window.localStorage.removeItem(WebIO.LocalStorage.Test);
} catch(err) {
this.println(err.message);
f = false;
}
}
WebIO.LocalStorage.Available = f;
}
return !!WebIO.LocalStorage.Available;
}
/**
* isMessageOn(messages)
*
* If messages is MESSAGE.DEFAULT (0), then the device's default message group(s) are used,
* and if it's MESSAGE.ALL (-1), then the message is always displayed, regardless what's enabled.
*
* @this {WebIO}
* @param {number} [messages] is zero or more MESSAGE flags
* @returns {boolean} true if all specified message enabled, false if not
*/
isMessageOn(messages = 0)
{
if (messages > 1 && (messages % 2)) messages--;
messages = messages || this.messages;
if ((messages|1) == -1 || this.testBits(this.machine.messages, messages)) {
return true;
}
return false;
}
/**
* isUserAgent(s)
*
* Check the browser's user-agent string for the given substring; "iOS" and "MSIE" are special values you can
* use that will match any iOS or MSIE browser, respectively (even IE11, in the case of "MSIE").
*
* 2013-11-06: In a questionable move, MSFT changed the user-agent reported by IE11 on Windows 8.1, eliminating
* the "MSIE" string (which MSDN calls a "version token"; see http://msdn.microsoft.com/library/ms537503.aspx);
* they say "public websites should rely on feature detection, rather than browser detection, in order to design
* their sites for browsers that don't support the features used by the website." So, in IE11, we get a user-agent
* that tries to fool apps into thinking the browser is more like WebKit or Gecko:
*
* Mozilla/5.0 (Windows NT 6.3; Trident/7.0; rv:11.0) like Gecko
*
* 2019-10-26: Apple has pulled a similar stunt in iPadOS 13, trying to pretend that Safari on iPadOS is
* indistinguishable from the desktop version. Except that there are still situations where we need to know the
* difference (eg, when there's only a soft keyboard as opposed to a dedicated keyboard). See monitor.js for details.
*
* @this {WebIO}
* @param {string} s is a substring to search for in the user-agent; as noted above, "iOS" and "MSIE" are special values
* @returns {boolean} is true if the string was found, false if not
*/
isUserAgent(s)
{
if (window) {
let userAgent = window.navigator.userAgent;
return s == "iOS" && (!!userAgent.match(/(iPod|iPhone|iPad)/) || (window.navigator.platform === 'MacIntel' && window.navigator.maxTouchPoints > 1)) || s == "MSIE" && !!userAgent.match(/(MSIE|Trident)/) || (userAgent.indexOf(s) >= 0);
}
return false;
}
/**
* loadLocalStorage()
*
* @this {WebIO}
* @returns {Array|null}
*/
loadLocalStorage()
{
let state = null;
if (this.hasLocalStorage()) {
let sValue;
if (window) {
try {
sValue = window.localStorage.getItem(this.idMachine);
if (sValue) state = /** @type {Array} */ (JSON.parse(sValue));
} catch (err) {
this.println(err.message);
}
}
}
return state;
}
/**
* onCommandEvent(event, down)
*
* @this {WebIO}
* @param {Event} event
* @param {boolean} [down] (true if keydown, false if keyup, undefined if keypress)
*/
onCommandEvent(event, down)
{
event = event || window.event;
let keyCode = event.which || event.keyCode;
if (keyCode) {
let machine = this.machine;
let element = /** @type {HTMLTextAreaElement} */ (event.target);
if (down) {
let consume = false, s;
let text = element.value;
let i = text.lastIndexOf('\n');
/*
* Checking for BACKSPACE is not as important as the UP and DOWN arrows, but it's helpful to ensure
* that BACKSPACE only erases characters on the final line; consume it otherwise.
*/
if (keyCode == WebIO.KEYCODE.BS) {
if (element.selectionStart <= i + 1) {
consume = true;
}
}
if (keyCode == WebIO.KEYCODE.UP) {
consume = true;
if (machine.iCommand > 0) {
s = machine.aCommands[--machine.iCommand];
}
}
else if (keyCode == WebIO.KEYCODE.DOWN) {
consume = true;
if (machine.iCommand < machine.aCommands.length) {
s = machine.aCommands[++machine.iCommand] || "";
}
}
if (consume) event.preventDefault();
if (s != undefined) {
element.value = text.substr(0, i + 1) + s;
}
}
else {
let charCode = keyCode;
let char = String.fromCharCode(charCode);
/*
* Move the caret to the end of any text in the textarea, unless it's already
* past the final LF (because it's OK to insert characters on the last line).
*/
let text = element.value;
let i = text.lastIndexOf('\n');
if (element.selectionStart <= i) {
element.setSelectionRange(text.length, text.length);
}
/*
* Don't let the Input device's document-based keypress handler see any key presses
* that came to this element first.
*/
event.stopPropagation();
/*
* If '@' is pressed as the first character on the line, then append the last command
* that parseCommands() processed, and transform '@' into ENTER.
*/
if (char == '@' && machine.iCommand > 0) {
if (i + 1 == text.length) {
element.value += machine.aCommands[--machine.iCommand];
char = '\r';
}
}
/*
* On the ENTER key, call parseCommands() to look for any COMMAND handlers and invoke
* them until one of them returns true.
*
* Note that even though new lines are entered with the ENTER (CR) key, which uses
* ASCII character '\r' (aka RETURN aka CR), new lines are stored in the text buffer
* as ASCII character '\n' (aka LINEFEED aka LF).
*/
if (char == '\r') {
/*
* At the time we call any command handlers, a LINEFEED will not yet have been
* appended to the text, so for consistency, we prevent the default behavior and
* add the LINEFEED ourselves. Unfortunately, one side-effect is that we must
* go to some extra effort to ensure the cursor remains in view; hence the stupid
* blur() and focus() calls.
*/
event.preventDefault();
text = (element.value += '\n');
element.blur();
element.focus();
let i = text.lastIndexOf('\n', text.length - 2);
let commands = text.slice(i + 1, -1) || "";
let result = this.parseCommands(commands);
if (result) this.println(result.replace(/\n$/, ""), false);
}
}
}
}
/**
* onPageEvent(sName, fn)
*
* This function creates a chain of callbacks, allowing multiple JavaScript modules to define handlers
* for the same event, which wouldn't be possible if everyone modified window['onload'], window['onunload'],
* etc, themselves.
*
* NOTE: It's risky to refer to obscure event handlers with "dot" names, because the Closure Compiler may
* erroneously replace them (eg, window.onpageshow is a good example).
*
* @this {WebIO}
* @param {string} sFunc
* @param {function()} fn
*/
onPageEvent(sFunc, fn)
{
if (window) {
let fnPrev = window[sFunc];
if (typeof fnPrev !== 'function') {
window[sFunc] = fn;
} else {
/*
* TODO: Determine whether there's any value in receiving/sending the Event object that the
* browser provides when it generates the original event.
*/
window[sFunc] = function onWindowEvent() {
if (fnPrev) fnPrev();
fn();
};
}
}
}
/**
* parseBoolean(token)
*
* @this {WebIO}
* @param {string} token (true if token is "on" or "true", false if "off" or "false", undefined otherwise)
* @returns {boolean|undefined}
*/
parseBoolean(token)
{
return (token == "true" || token == "on"? true : (token == "false" || token == "off"? false : undefined));
}
/**
* parseCommand(command)
*
* @this {WebIO}
* @param {string} [command]
* @returns {string|undefined}
*/
parseCommand(command)
{
let result;
if (command != undefined) {
let machine = this.machine;
try {
command = command.trim();
if (command) {
if (machine.iCommand < machine.aCommands.length && command == machine.aCommands[machine.iCommand]) {
machine.iCommand++;
} else {
machine.aCommands.push(command);
machine.iCommand = machine.aCommands.length;
}
}
let aTokens = command.split(' ');
let token = aTokens[0], message, on, list, iToken;
let afnHandlers = this.findHandlers(WebIO.HANDLER.COMMAND);
switch(token[0]) {
case 'm':
if (token[1] == '?') {
result = "";
WebIO.MESSAGE_COMMANDS.forEach((command) => {result += command + '\n';});
if (result) result = "message commands:\n" + result;
break;
}
result = ""; iToken = 1; list = undefined;
token = aTokens[aTokens.length-1].toLowerCase();
on = this.parseBoolean(token);
if (on != undefined) {
aTokens.pop();
}
if (aTokens.length <= 1) {
if (on != undefined) {
list = on;
on = undefined;
}
aTokens[iToken] = "all";
}
if (aTokens[iToken] == "all") {
aTokens = Object.keys(WebIO.MESSAGE_NAMES);
}