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 pathdevice.js
926 lines (870 loc) · 28.9 KB
/
device.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
/**
* @fileoverview Base class for devices, with assorted handy services
* @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/devices/machine.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";
/**
* @define {boolean}
*/
var COMPILED = false;
/**
* @define {boolean}
*/
var DEBUG = true; // (window.location.hostname == "pcjs" || window.location.hostname == "jeffpar.local");
/**
* @type {string}
*/
var MACHINE = "Machine";
/**
* @define {string}
*/
var VERSION = "1.21";
/**
* The following properties are the standard set of properties a Device's config object may contain.
* Other devices will generally define their own extended versions (eg, LEDConfig, InputConfig, etc).
*
* @typedef {Object} Config
* @property {string} [class]
* @property {Object} [bindings]
* @property {number} [version]
* @property {Array.<string>} [overrides]
*/
/**
* @class {Device}
* @unrestricted
* @property {string} idMachine
* @property {string} idDevice
* @property {Config} config
* @property {Object} bindings [added by addBindings()]
* @property {string} categories
* @property {string} sCommandPrev
*/
class Device extends StdIO {
/**
* Device()
*
* Supported config properties:
*
* "bindings": object containing name/value pairs, where name is the generic name
* of a element, and value is the ID of the DOM element that should be mapped to it
*
* The properties in the "bindings" object are copied to our own bindings object in addBindings(),
* but only for DOM elements that actually exist, and it is the elements themselves (rather than
* their IDs) that we store.
*
* Also, URL parameters can be used to override config properties. For example, the URL:
*
* http://pcjs:8088/devices/ti57/machine/?cyclesPerSecond=100000
*
* will set the Time device's cyclesPerSecond config property to 100000. In general, the values
* will be treated as strings, unless they contain all digits (number), or equal "true" or "false"
* (boolean).
*
* @this {Device}
* @param {string} idMachine
* @param {string} idDevice
* @param {number} [version]
* @param {Config} [config]
*/
constructor(idMachine, idDevice, version, config)
{
super();
this.config = config || {};
this.idMachine = idMachine;
this.idDevice = idDevice;
this.version = version || 0;
this.bindings = {};
this.categories = "";
this.addDevice();
this.checkVersion(this.config);
this.checkOverrides(this.config);
this.addBindings(this.config['bindings']);
this.sCommandPrev = "";
}
/**
* addBinding(binding, element)
*
* @this {Device}
* @param {string} binding
* @param {Element} element
*/
addBinding(binding, element)
{
let device = this, elementTextArea;
switch (binding) {
case Device.BINDING.CLEAR:
element.onclick = function onClickClear() {
device.clear();
};
break;
case Device.BINDING.PRINT:
elementTextArea = /** @type {HTMLTextAreaElement} */ (element);
/*
* This was added for Firefox (Safari will clear the <textarea> on a page reload, but Firefox does not).
*/
elementTextArea.value = "";
/*
* An onKeyPress handler has been added to this element simply 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).
*/
elementTextArea.addEventListener(
'keypress',
function onKeyPress(event) {
event = event || window.event;
let keyCode = event.which || event.keyCode;
if (keyCode) {
/*
* Move the caret to the end of any text in the textarea.
*/
let sText = elementTextArea.value;
elementTextArea.setSelectionRange(sText.length, sText.length);
/*
* Don't let the Input device's document-based keypress handler see any key presses
* that came to this element first.
*/
event.stopPropagation();
/*
* On the ENTER key, look for any COMMAND handlers and invoke them until one of them
* returns true.
*/
if (keyCode == 13) {
/*
* 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();
sText = (elementTextArea.value += '\n');
elementTextArea.blur();
elementTextArea.focus();
device.doCommand(sText);
}
}
}
);
break;
}
}
/**
* addBindings(bindings)
*
* Builds the set of ACTUAL bindings (this.bindings) from the set of DESIRED bindings (this.config['bindings']),
* using either a "bindings" object map OR an array of "direct bindings".
*
* @this {Device}
* @param {Object} bindings
*/
addBindings(bindings)
{
let fDirectBindings = Array.isArray(bindings);
for (let binding in bindings) {
let id = bindings[binding];
if (fDirectBindings) binding = id;
let element = document.getElementById(id);
if (element) {
this.bindings[binding] = element;
this.addBinding(binding, element);
continue;
}
if (DEBUG && !fDirectBindings) this.println("unable to find device ID: " + id);
}
}
/**
* addBindingOptions(element, options, fReset, sDefault)
*
* @this {Device}
* @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;
}
}
}
/**
* addDevice()
*
* Adds this Device to the global set of Devices, so that findDevice(), findBinding(), etc, will work.
*
* @this {Device}
*/
addDevice()
{
if (!Device.Machines[this.idMachine]) Device.Machines[this.idMachine] = [];
Device.Machines[this.idMachine].push(this);
}
/**
* addHandler(sType, fn)
*
* @this {Device}
* @param {string} sType
* @param {function(Array.<string>,Device)} fn
*/
addHandler(sType, fn)
{
if (!Device.Handlers[this.idMachine]) Device.Handlers[this.idMachine] = {};
if (!Device.Handlers[this.idMachine][sType]) Device.Handlers[this.idMachine][sType] = [];
Device.Handlers[this.idMachine][sType].push(fn);
}
/**
* alert(s, type)
*
* @this {Device}
* @param {string} s
* @param {string} [type]
*/
alert(s, type)
{
if (type && Device.Alerts.list.indexOf(type) < 0) {
alert(s);
Device.Alerts.list.push(type);
}
this.println(s);
}
/**
* assert(f, s)
*
* 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 {Device}
* @param {*} f is the expression asserted to be true
* @param {string} [s] is description of the assertion on failure
*/
assert(f, s)
{
if (DEBUG) {
if (!f) {
throw new Error(s || "assertion failure");
}
}
}
/**
* checkOverrides(config)
*
* @this {Device}
* @param {Config} config
*/
checkOverrides(config)
{
/*
* If this device's config contains an "overrides" array, then any of the properties listed in
* that array may be overridden with a URL parameter. We don't impose any checks on the overriding
* value, so it is the responsibility of the component with overridable properties to validate them.
*/
if (config['overrides']) {
let parms = this.getURLParms();
for (let prop in parms) {
if (config['overrides'].indexOf(prop) >= 0) {
let value;
let s = parms[prop];
/*
* You might think we could simply call parseInt() and check isNaN(), but parseInt() has
* some annoying quirks, like stopping at the first non-numeric character. If the ENTIRE
* string isn't a number, then we don't want to treat ANY part of it as a number.
*/
if (s.match(/^[+-]?[0-9.]+$/)) {
value = Number.parseInt(s, 10);
} else if (s == "true") {
value = true;
} else if (s == "false") {
value = false;
} else {
value = s;
s = '"' + s + '"';
}
config[prop] = value;
this.println("overriding " + this.idDevice + " property '" + prop + "' with " + s);
}
}
}
}
/**
* checkVersion(config)
*
* Verify that device's version matches the machine's version, and also that the config version stored in
* the JSON (if any) matches the device's version.
*
* This is normally performed by the constructor, but the Machine device cannot be fully initialized in the
* constructor, so it calls this separately.
*
* @this {Device}
* @param {Config} config
*/
checkVersion(config)
{
if (this.version) {
let sVersion = "", version;
let machine = this.findDevice(this.idMachine);
if (machine.version != this.version) {
sVersion = "Machine";
version = machine.version;
}
else if (config.version && config.version > this.version) {
sVersion = "Config";
version = config.version;
}
if (sVersion) {
let sError = this.sprintf("%s Device version (%3.2f) incompatible with %s version (%3.2f)", config.class, this.version, sVersion, version);
this.alert("Error: " + sError + '\n\n' + "Clearing your browser's cache may resolve the issue.", Device.Alerts.Version);
}
}
}
/**
* clear()
*
* @this {Device}
*/
clear()
{
let element = this.findBinding(Device.BINDING.PRINT, true);
if (element) element.value = "";
}
/**
* doCommand(sText)
*
* @this {Device}
* @param {string} sText
*/
doCommand(sText)
{
let afnHandlers = this.findHandlers(Device.HANDLER.COMMAND);
if (afnHandlers) {
let c, i = sText.lastIndexOf('\n', sText.length - 2);
let sCommand = sText.slice(i + 1, -1) || this.sCommandPrev, sResult;
this.sCommandPrev = "";
sCommand = sCommand.trim();
let aTokens = sCommand.split(' ');
switch(aTokens[0]) {
case 'c':
c = aTokens[1];
if (c) {
this.println("set category '" + c + "'");
this.setCategory(c);
} else {
c = this.setCategory();
if (c) {
this.println("cleared category '" + c + "'");
} else {
this.println("no category set");
}
}
break;
case '?':
sResult = "";
Device.COMMANDS.forEach((cmd) => {sResult += '\n' + cmd;});
if (sResult) this.println("default commands:" + sResult);
/* falls through */
default:
aTokens.unshift(sCommand);
for (i = 0; i < afnHandlers.length; i++) {
if (afnHandlers[i](aTokens, this)) break;
}
break;
}
}
}
/**
* findBinding(name, fAll)
*
* This will search the current device's bindings, and optionally all the device bindings within the
* machine. If the binding is found in another device, that binding is recorded in this device as well.
*
* @this {Device}
* @param {string} name
* @param {boolean} [fAll]
* @returns {Element|null|undefined}
*/
findBinding(name, fAll = false)
{
let element = this.bindings[name];
if (element === undefined && fAll) {
let devices = Device.Machines[this.idMachine];
for (let i in devices) {
element = devices[i].bindings[name];
if (element) break;
}
if (!element) element = null;
this.bindings[name] = element;
}
return element;
}
/**
* findDevice(idDevice)
*
* @this {Device}
* @param {string} idDevice
* @returns {Device|undefined}
*/
findDevice(idDevice)
{
let device;
let devices = Device.Machines[this.idMachine];
if (devices) {
for (let i in devices) {
if (devices[i].idDevice == idDevice) {
device = devices[i];
break;
}
}
}
return device;
}
/**
* findDeviceByClass(idClass)
*
* @this {Device}
* @param {string} idClass
* @returns {Device|undefined}
*/
findDeviceByClass(idClass)
{
let device;
let devices = Device.Machines[this.idMachine];
if (devices) {
for (let i in devices) {
if (devices[i].config['class'] == idClass) {
device = devices[i];
break;
}
}
}
return device;
}
/**
* findHandlers(sType)
*
* @this {Device}
* @param {string} sType
* @returns {Array.<function(Array.<string>,Device)>|undefined}
*/
findHandlers(sType)
{
return Device.Handlers[this.idMachine] && Device.Handlers[this.idMachine][sType];
}
/**
* 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 {Device}
* @param {string} name
* @returns {string|undefined}
*/
getBindingID(name)
{
return this.config['bindings'] && this.config['bindings'][name];
}
/**
* getBindingText(name)
*
* @this {Device}
* @param {string} name
* @return {string|undefined}
*/
getBindingText(name)
{
let sText;
let element = this.bindings[name];
if (element) sText = element.textContent;
return sText;
}
/**
* 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 n is not.
*
* @this {Device}
* @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)
*
* @this {Device}
* @param {string} idConfig
* @param {*} defaultValue
* @returns {*}
*/
getDefault(idConfig, defaultValue)
{
let value = this.config[idConfig];
if (value === undefined) {
value = defaultValue;
} else {
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 {Device}
* @param {string} idConfig
* @param {boolean} defaultValue
* @returns {boolean}
*/
getDefaultBoolean(idConfig, defaultValue)
{
return /** @type {boolean} */ (this.getDefault(idConfig, defaultValue));
}
/**
* getDefaultNumber(idConfig, defaultValue)
*
* @this {Device}
* @param {string} idConfig
* @param {number} defaultValue
* @returns {number}
*/
getDefaultNumber(idConfig, defaultValue)
{
return /** @type {number} */ (this.getDefault(idConfig, defaultValue));
}
/**
* getDefaultString(idConfig, defaultValue)
*
* @this {Device}
* @param {string} idConfig
* @param {string} defaultValue
* @returns {string}
*/
getDefaultString(idConfig, defaultValue)
{
return /** @type {string} */ (this.getDefault(idConfig, defaultValue));
}
/**
* getURLParms(sParms)
*
* @this {Device}
* @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 = Device.URLParms;
if (!parms) {
parms = {};
if (window) {
if (!sParms) {
/*
* Note that window.location.href returns the entire URL, whereas window.location.search
* returns only the 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]);
}
}
Device.URLParms = parms;
}
return parms;
}
/**
* hasLocalStorage
*
* If localStorage support exists, is enabled, and works, return true.
*
* @this {Device}
* @returns {boolean}
*/
hasLocalStorage()
{
if (Device.LocalStorage.Available === undefined) {
let f = false;
if (window) {
try {
window.localStorage.setItem(Device.LocalStorage.Test, Device.LocalStorage.Test);
f = (window.localStorage.getItem(Device.LocalStorage.Test) == Device.LocalStorage.Test);
window.localStorage.removeItem(Device.LocalStorage.Test);
} catch(err) {
this.println(err.message);
f = false;
}
}
Device.LocalStorage.Available = f;
}
return !!Device.LocalStorage.Available;
}
/**
* isCategory(category)
*
* Use this function to enable/disable any code (eg, print() calls) based on 1) whether specific
* categories are required, and 2) whether the specified category is one of them.
*
* @this {Device}
* @param {string} category
*/
isCategoryOn(category)
{
return (this.categories.indexOf(category) >= 0);
}
/**
* 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
*
* @this {Device}
* @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)/) && !!userAgent.match(/AppleWebKit/) || s == "MSIE" && !!userAgent.match(/(MSIE|Trident)/) || (userAgent.indexOf(s) >= 0);
}
return false;
}
/**
* loadLocalStorage()
*
* @this {Device}
* @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;
}
/**
* print(s)
*
* This overrides StdIO.print(), in case the device has a PRINT binding that should be used instead.
*
* @this {Device}
* @param {string} s
*/
print(s)
{
let fBuffer = true;
if (!this.isCategoryOn(Device.CATEGORY.BUFFER)) {
fBuffer = false;
let element = this.findBinding(Device.BINDING.PRINT, true);
if (element) {
element.value += s;
/*
* Prevent the <textarea> from getting too large; otherwise, printing becomes slower and slower.
*/
if (!DEBUG && element.value.length > 8192) {
element.value = element.value.substr(element.value.length - 4096);
}
element.scrollTop = element.scrollHeight;
return;
}
}
super.print(s, fBuffer);
}
/**
* removeDevice(idDevice)
*
* @this {Device}
* @param {string} idDevice
* @returns {boolean} (true if successfully removed, false if not)
*/
removeDevice(idDevice)
{
let device;
let devices = Device.Machines[this.idMachine];
if (devices) {
for (let i in devices) {
if (devices[i].idDevice == idDevice) {
devices.splice(i, 1);
return true;
}
}
}
return false;
}
/**
* saveLocalStorage(state)
*
* @this {Device}
* @param {Array} state
* @returns {boolean} true if successful, false if error
*/
saveLocalStorage(state)
{
if (this.hasLocalStorage()) {
let sValue = JSON.stringify(state);
try {
window.localStorage.setItem(this.idMachine, sValue);
return true;
} catch(err) {
this.println(err.message);
}
}
return false;
}
/**
* setBindingText(name, text)
*
* @this {Device}
* @param {string} name
* @param {string} text
*/
setBindingText(name, text)
{
let element = this.bindings[name];
if (element) element.textContent = text;
}
/**
* setCategory(category)
*
* Use this function to set/clear categories. Generally, these are thought of as print categories,
* allowing code to use isCategoryOn() to decide whether to print a certain category of messages, but
* it can be used to control any functionality related to a given category, not just printing.
*
* You usually want to use one of the predefined category strings in Device.CATEGORIES, but in reality,
* the category string can be anything you want.
*
* If you want to enable multiple categories, specify them all in a single string (eg, "time|buffer",
* or Device.CATEGORY.TIME + Device.CATEGORY.BUFFER).
*
* Device.CATEGORY.BUFFER is special, causing all print calls to be buffered; the print buffer will be
* dumped as soon as setCategory() clears Device.CATEGORY.BUFFER.
*
* @this {Device}
* @param {string} [category] (if undefined, clear previous category)
* @returns {string}
*/
setCategory(category = "")
{
let cPrev = this.categories;
let fFlush = (!category && this.isCategoryOn(Device.CATEGORY.BUFFER));
this.categories = category;
if (fFlush) {
let sBuffer = this.bufferPrint;
this.bufferPrint = "";
this.print(sBuffer);
}
return cPrev;
}
}
Device.BINDING = {
CLEAR: "clear",
PRINT: "print"
};
/*
* List of standard categories.
*
* Device.CATEGORY.BUFFER is special, causing all print calls to be buffered; the print buffer will be
* dumped as soon as setCategory() clears Device.CATEGORY.BUFFER.
*/
Device.CATEGORY = {
TIME: "time",
BUFFER: "buffer"
};
Device.COMMANDS = [
"c\t\tset category"
];
Device.HANDLER = {
COMMAND: "command"
};
Device.Alerts = {
list: [],
Version: "version"
};
Device.LocalStorage = {
Available: undefined,
Test: "PCjs.localStorage"
};
/**
* Handlers is a global object whose properties are machine IDs, each of which contains zero or more
* handler IDs, each of which contains an arrays of functions.
*
* @type {Object}
*/
Device.Handlers = {};
/**
* Machines is a global object whose properties are machine IDs and whose values are arrays of Devices.
*
* @type {Object}
*/
Device.Machines = {};