-
Notifications
You must be signed in to change notification settings - Fork 9
/
qb.js
4517 lines (4051 loc) · 145 KB
/
qb.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
var QB = new function() {
// QB sound functionality
// original source: https://siderite.dev/blog/qbasic-play-in-javascript
class QBasicSound {
constructor() {
this.octave = 4;
this.noteLength = 4;
this.tempo = 120;
this.mode = 7 / 8;
this.foreground = true;
this.type = 'square';
}
stop() {
if (this._audioContext) {
this._audioContext.suspend();
this._audioContext.close();
}
}
setType(type) {
this.type = type;
}
async playSound(frequency, duration) {
if (!this._audioContext) {
this._audioContext = new AudioContext();
}
// a 0 frequency means a pause
if (frequency == 0) {
await delay(duration);
} else {
const o = this._audioContext.createOscillator();
const g = this._audioContext.createGain();
o.connect(g);
g.connect(this._audioContext.destination);
g.gain.value = 0.25;
o.frequency.value = frequency;
o.type = this.type;
o.start();
const actualDuration = duration * this.mode;
const pause = duration - actualDuration;
await delay(actualDuration);
o.stop();
if (pause) { await delay(pause); }
}
}
getNoteValue(octave, note) {
const octaveNotes = 'C D EF G A B';
const index = octaveNotes.indexOf(note.toUpperCase());
if (index < 0) {
throw new Error(note + ' is not a valid note');
}
return octave * 12 + index;
}
async play(commandString) {
commandString = commandString.replace(/ /g, "");
const reg = /(?<octave>O\d+)|(?<octaveUp>>)|(?<octaveDown><)|(?<note>[A-G][#+-]?\d*\.?[,]?)|(?<noteN>N\d+\.?)|(?<length>L\d+)|(?<legato>ML)|(?<normal>MN)|(?<staccato>MS)|(?<pause>P\d+\.?)|(?<tempo>T\d+)|(?<foreground>MF)|(?<background>MB)/gi;
let match = reg.exec(commandString);
let promise = Promise.resolve();
let nowait = false;
while (match) {
let noteValue = null;
let longerNote = false;
let temporaryLength = 0;
if (match.groups.octave) {
this.octave = parseInt(match[0].substring(1));
}
if (match.groups.octaveUp) {
this.octave++;
}
if (match.groups.octaveDown) {
this.octave--;
}
if (match.groups.note) {
const noteMatch = /(?<note>[A-G])(?<suffix>[#+-]?)(?<shorthand>\d*)(?<longerNote>\.?)(?<nowait>,?)/i.exec(match[0]);
if (noteMatch.groups.longerNote) {
longerNote = true;
}
if (noteMatch.groups.shorthand) {
temporaryLength = parseInt(noteMatch.groups.shorthand);
}
if (noteMatch.groups.nowait) {
nowait = true;
}
noteValue = this.getNoteValue(this.octave, noteMatch.groups.note);
switch (noteMatch.groups.suffix) {
case '#':
case '+':
noteValue++;
break;
case '-':
noteValue--;
break;
}
}
if (match.groups.noteN) {
const noteNMatch = /N(?<noteValue>\d+)(?<longerNote>\.?)/i.exec(match[0]);
if (noteNMatch.groups.longerNote) {
longerNote = true;
}
noteValue = parseInt(noteNMatch.groups.noteValue);
}
if (match.groups.length) {
this.noteLength = parseInt(match[0].substring(1));
}
if (match.groups.legato) {
this.mode = 1;
}
if (match.groups.normal) {
this.mode = 7 / 8;
}
if (match.groups.staccato) {
this.mode = 3 / 4;
}
if (match.groups.pause) {
const pauseMatch = /P(?<length>\d+)(?<longerNote>\.?)/i.exec(match[0]);
if (pauseMatch.groups.longerNote) {
longerNote = true;
}
noteValue = 0;
temporaryLength = parseInt(pauseMatch.groups.length);
}
if (match.groups.tempo) {
this.tempo = parseInt(match[0].substring(1));
}
if (match.groups.foreground) {
this.foreground = true;
}
if (match.groups.background) {
this.foreground = false;
}
if (noteValue !== null) {
const noteDuration = (60000 * 4 / this.tempo);
const duration = temporaryLength
? noteDuration / temporaryLength
: noteDuration / this.noteLength;
const C6 = 1047;
const freq = noteValue == 0
? 0
: C6 * Math.pow(2, (noteValue - 48) / 12);
if (nowait) {
this.playSound(freq, duration);
nowait = false;
}
else {
await this.playSound(freq, duration);
}
}
match = reg.exec(commandString);
}
if (this.foreground) {
await promise;
} else {
promise;
}
}
}
function delay(duration) {
return new Promise(resolve => setTimeout(resolve, duration));
}
// QB public constants
this._KEEPBACKGROUND = 1;
this._ONLYBACKGROUND = 2;
this._FILLBACKGROUND = 3;
// QB constants
this.COLUMN_ADVANCE = Symbol("COLUMN_ADVANCE");
this.PREVENT_NEWLINE = Symbol("PREVENT_NEWLINE");
this.STRETCH = Symbol("STRETCH");
this.SQUAREPIXELS = Symbol("SQUAREPIXELS");
this.APPEND = Symbol("APPEND");
this.BINARY = Symbol("BINARY");
this.INPUT = Symbol("INPUT");
this.OUTPUT = Symbol("OUTPUT");
this.RANDOM = Symbol("RANDOM");
var _activeImage = 0;
var _bgColor = null;
var _colormap = [];
var _currScreenImage = null;
var _dataBulk = [];
var _dataLabelMap;
var _font = 16;
var _fgColor = null;
var _fonts = {};
var _haltedFlag = false;
var _images = {};
var _inkeyBuffer = [];
var _inkeymap = {};
var _inkeynp = {};
var _inputMode = false;
var _inputCursor = false;
var _inputTimeout = false;
var _keyDownMap = {};
var _keyHitBuffer = [];
var _keyhitmap = {};
var _lastLimitTime;
var _lastKey = null;
var _locX = 0;
var _lastTextX = 0;
var _locY = 0;
var _nextImageId = 1000;
var _nextFontId = 1000;
var _printMode = this._FILLBACKGROUND;
var _readCursorPosition;
var _resize = false;
var _resizeWidth = 0;
var _resizeHeight = 0;
var _rndSeed;
var _runningFlag = false;
var _screenDiagInv;
var _screenMode;
var _screenText;
var _sourceImage = 0;
var _strokeDrawLength = null;
var _strokeDrawAngle = null;
var _strokeDrawColor = null;
var _strokeLineThickness = 2;
var _windowAspect = [];
var _windowDef = [];
var _fileHandles = {};
var _typeMap = {};
var _ucharMap = {};
var _ccharMap = {};
var _player = null;
var _soundCtx = null;
// Array handling methods
// ----------------------------------------------------
this.initArray = function(dimensions, obj) {
var a = {};
if (dimensions && dimensions.length > 0) {
a._dimensions = dimensions;
}
else {
// default to single dimension to support Dim myArray() syntax
// for convenient hashtable declaration
a._dimensions = [{l:0,u:1}];
}
a._newObj = { value: obj };
return a;
};
this.resizeArray = function(a, dimensions, obj, preserve) {
if (!preserve) {
var props = Object.getOwnPropertyNames(a);
for (var i = 0; i < props.length; i++) {
if (props[i] != "_newObj") {
delete a[props[i]];
}
}
}
if (dimensions && dimensions.length > 0) {
a._dimensions = dimensions;
}
else {
// default to single dimension to support Dim myArray() syntax
// for convenient hashtable declaration
a._dimensions = [{l:0,u:1}];
}
};
this.arrayValue = function(a, indexes) {
var value = a;
for (var i=0; i < indexes.length; i++) {
if (value[indexes[i]] == undefined) {
if (i == indexes.length-1) {
value[indexes[i]] = JSON.parse(JSON.stringify(a._newObj));
}
else {
value[indexes[i]] = {};
}
}
value = value[indexes[i]];
}
return value;
};
this.resize = function(width, height) {
_resize = true;
_resizeWidth = width;
_resizeHeight = height;
}
// Data type conversions
this.toInteger = function(value) {
var result = parseInt(value);
if (isNaN(result)) {
result = 0;
}
return result;
};
this.toFloat = function(value) {
var result = parseFloat(value);
if (isNaN(result)) {
result = 0;
}
return result;
};
this.toBoolean = function(value) {
return value ? 0 : -1;
};
// Process control methods
// -------------------------------------------
this.halt = function() {
_haltedFlag = true;
_runningFlag = false;
_inputMode = false;
_player.stop();
_soundCtx.pause();
GX.soundStopAll();
toggleCursor(true);
};
this.halted = function() {
return _haltedFlag;
};
this.end = function() {
_flushAllScreenCache();
_runningFlag = false;
};
this.start = function() {
_activeImage = 0;
_currScreenImage = null;
_dataLabelMap = {};
_haltedFlag = false;
_lastLimitTime = new Date();
_nextImageId = 1000;
_printMode = QB._FILLBACKGROUND;
_readCursorPosition = 0;
_rndSeed = 327680;
_runningFlag = true;
_sourceImage = 0;
_strokeLineThickness = 2;
_player = new QBasicSound();
_soundCtx = new AudioContext();
// initialize the default fonts
_nextFontId = 1000;
_font = 16;
_fonts = {};
_fonts[8] = { name: "dosvga", size: "16px", style: "", offset: 4, monospace: true };
_fonts[14] = { name: "dosvga", size: "16px", style: "", offset: 4, monospace: true };
_fonts[16] = { name: "dosvga", size: "16px", style: "", offset: 4, monospace: true };
GX.vfsCwd(GX.vfs().rootDirectory());
_fileHandles = {};
_initColorTable();
GX._enableTouchMouse(true);
GX.registerGameEvents(function(e){});
QB.sub_Screen(0);
};
this.setData = function(data) {
_dataBulk = data;
};
this.setDataLabel = function(label, dataIndex) {
_dataLabelMap[label] = dataIndex;
}
this.setTypeMap = function(typeMap) {
_typeMap = typeMap;
}
this.running = function() {
return _runningFlag;
};
// Access methods for std libraries
// --------------------------------------------
this.getImage = function(imageId) {
return _images[imageId].canvas;
};
this.defaultLineWidth = function(width) {
if (width != undefined) {
_strokeLineThickness = width;
}
return _strokeLineThickness;
};
this.colorToRGB = _color;
this.vfs = function() { return GX.vfs(); }
this.vfsCwd = function() { return GX.vfsCwd(); }
this.downloadFile = async function(data, defaultName) {
if (window.showSaveFilePicker) {
const handle = await showSaveFilePicker({ suggestedName: defaultName });
const writable = await handle.createWritable();
await writable.write(data);
writable.close();
}
else {
const link = document.createElement("a");
link.href = URL.createObjectURL(data);
link.download = defaultName;
link.click();
link.remove();
}
};
// Runtime Assertions
function _assertParam(param, arg) {
if (arg == undefined) { arg = 1; }
if (param == undefined) { throw new Error("Method argument " + arg + " is required"); }
}
function _assertNumber(param, arg) {
if (arg == undefined) { arg = 1; }
if (isNaN(param)) { throw new Error("Number required for method argument " + arg); }
}
// Extended QB64 Keywords
// --------------------------------------------
this.func__Acos = function(x) {
_assertNumber(x);
return Math.acos(x);
};
this.func__Acosh = function(x) {
_assertNumber(x);
return Math.acosh(x);
};
this.func__Arccot = function(x) {
_assertNumber(x);
return 2 * Math.atan(1) - Math.atan(x);
};
this.func__Arccsc = function(x) {
_assertNumber(x);
return Math.asin(1 / x);
};
this.func__Arcsec = function(x) {
_assertNumber(x);
return Math.acos(1 / x);
};
this.func__Alpha = function(rgb, imageHandle) {
_assertParam(rgb);
// TODO: implement corresponding logic when an image handle is supplied (maybe)
return _color(rgb).a;
};
this.func__Alpha32 = function(rgb) {
_assertParam(rgb);
// TODO: implement corresponding logic when an image handle is supplied (maybe)
return _color(rgb).a;
};
this.func__Asin = function(x) {
_assertNumber(x);
return Math.asin(x);
};
this.func__Asinh = function(x) {
_assertNumber(x);
return Math.asinh(x);
};
this.func__Atanh = function(x) {
_assertNumber(x);
return Math.atanh(x);
};
this.func__Atan2 = function(y, x) {
_assertNumber(x);
return Math.atan2(y, x);
};
// the canvas handles the display for us, there is effectively no difference
// between _display and _autodisplay, included here for compatibility
this.func__AutoDisplay = function() { return -1; }
this.sub__AutoDisplay = function() {}
this.func__BackgroundColor = function() {
return _bgColor;
};
this.func__Blue = function(rgb, imageHandle) {
_assertParam(rgb);
// TODO: implement corresponding logic when an image handle is supplied (maybe)
return _color(rgb).b;
};
this.func__Blue32 = function(rgb) {
_assertParam(rgb);
// TODO: implement corresponding logic when an image handle is supplied (maybe)
return _color(rgb).b;
};
this.func__CapsLock = function() {
return _keyDownMap._CapsLock ? -1 : 0;
};
this.func__Ceil = function(x) {
_assertNumber(x);
return Math.ceil(x);
};
this.func__CommandCount = function() {
return 0;
};
this.func__CopyImage = function(srcImageId) {
_assertNumber(srcImageId);
var srcCanvas = _images[srcImageId].canvas;
var destImageId = QB.func__NewImage(srcCanvas.width, srcCanvas.height);
var ctx = _images[destImageId].ctx;
ctx.drawImage(srcCanvas, 0, 0);
return destImageId;
};
this.func__Cosh = function(x) {
_assertNumber(x);
return Math.cosh(x);
};
this.func__Cot = function(x) {
_assertNumber(x);
return 1 / Math.tan(x);
}
this.func__Coth = function(x) {
_assertNumber(x);
return 1 / Math.tanh(x);
};
this.func__Csc = function(x) {
_assertNumber(x);
return 1 / Math.sin(x);
};
this.func__Csch = function(x) {
_assertNumber(x);
return 1 / Math.sinh(x);
};
this.func__CWD = function() {
return GX.vfs().fullPath(GX.vfsCwd());
};
this.func__D2R = function(x) {
_assertNumber(x);
return x * Math.PI / 180;
};
this.func__D2G = function(x) {
_assertNumber(x);
return (x * 10 / 9);
};
this.func__DefaultColor = function(imageHandle) {
// TODO: implement imageHandle version?
// at present we have a global default color rather than one per image
return _fgColor;
};
this.func__Deflate = function(src) {
_assertParam(src);
var result = pako.deflate(src);//, { to: "string" });
return String.fromCharCode.apply(String, result);
};
this.sub__Delay = async function(seconds) {
_assertNumber(seconds);
await GX.sleep(seconds*1000);
};
this.func__DesktopHeight = function() {
return window.screen.height * window.devicePixelRatio;
};
this.func__DesktopWidth = function() {
return window.screen.width * window.devicePixelRatio;
};
this.func__Dest = function() {
return _activeImage;
};
this.sub__Dest = function(imageId) {
_assertNumber(imageId);
_flushScreenCache(_images[_activeImage]);
_activeImage = imageId;
};
this.func__Dir = function(folder) {
return "./";
};
this.func__DirExists = function(path) {
_assertParam(path);
var vfs = GX.vfs();
var dir = vfs.getNode(path, GX.vfsCwd());
if (dir && dir.type == vfs.DIRECTORY) {
return -1;
}
return 0;
};
this.func__Display = function() {
return 0;
};
this.sub__Display = function() {
// The canvas handles this for us, this method is included for compatibility
};
this.sub__Echo = function(msg) {
_assertParam(msg);
console.log(msg);
};
this.func__EnvironCount = function() {
/* no-op: included for compatibility */
return 0;
};
this.func__FileExists = function(path) {
_assertParam(path);
var vfs = GX.vfs();
var file = vfs.getNode(path, GX.vfsCwd());
if (file && file.type == vfs.FILE) {
return -1;
}
return 0;
};
this.sub__Font = function(fnt) {
_assertNumber(fnt);
_font = fnt;
_locX = 0;
_lastTextX = 0;
_locY = 0;
_initScreenText();
};
this.func__Font = function() {
return _font;
};
this.func__FontHeight = function(fnt) {
if (fnt == undefined) {
fnt = _font;
}
if (fnt < 1000) {
return 16;
}
return _fonts[fnt].height;
};
this.func__FontWidth = function(fnt) {
if (fnt == undefined) {
fnt = _font;
}
if (fnt < 1000) {
return 8;
}
return _fonts[fnt].width;
};
this.sub__FreeImage = function(imageId) {
if (imageId == undefined) {
imageId = _activeImage;
}
_images[imageId] = undefined;
};
this.func__FullScreen = function() {
return GX.fullScreen() ? 2 : 0;
};
this.sub__FullScreen = function(mode, smooth) {
if (mode == QB.OFF) {
GX.fullScreen(false);
}
else if (mode == QB.STRETCH || mode == QB.SQUAREPIXELS) {
// TODO: not making any distinction at present
GX.fullScreen(true, smooth);
}
}
this.func__G2D = function(x) {
return (x * 9/10);
};
this.func__G2R = function(x) {
_assertNumber(x);
return (x * 9/10) * Math.PI/180;
};
this.func__Green = function(rgb, imageHandle) {
_assertParam(rgb);
// TODO: implement corresponding logic when an image handle is supplied (maybe)
return _color(rgb).g;
};
this.func__Green32 = function(rgb) {
_assertParam(rgb);
// TODO: implement corresponding logic when an image handle is supplied (maybe)
return _color(rgb).g;
};
this.func__Height = function(imageId) {
if (imageId == undefined) { imageId = _activeImage; }
if (_images[imageId].charSizeMode) {
return _height(imageId) / this.func__FontWidth();
}
return _height(imageId);
};
function _height(imageId) {
if (imageId == undefined) { imageId = _activeImage; }
return _images[imageId].canvas.height;
}
this.func__Hypot = function(x, y) {
_assertNumber(x, 1);
_assertNumber(y, 1);
return Math.hypot(x, y);
};
this.func__Inflate = function(src) {
_assertParam(src);
var result = pako.inflate(GX.vfs().textToData(src), { to: "string" });
return result;
};
this.func__InStrRev = function(arg1, arg2, arg3) {
_assertParam(arg1, 1);
_assertParam(arg2, 2);
var startIndex = +Infinity;
var strSource = "";
var strSearch = "";
if (arg3 != undefined) {
startIndex = arg1-1;
strSource = String(arg2);
strSearch = String(arg3);
}
else {
strSource = String(arg1);
strSearch = String(arg2);
}
return strSource.lastIndexOf(strSearch, startIndex)+1;
};
this.sub__KeyClear = function(buffer) {
if (buffer == undefined || buffer == 1) {
_inkeyBuffer = [];
}
if (buffer == undefined || buffer == 2) {
_keyHitBuffer = [];
}
};
this.func__KeyDown = function(keyCode) {
return (_keyDownMap[keyCode]) ? -1 : 0;
};
this.func__KeyHit = function() {
if (_keyHitBuffer.length < 1) {
return "";
}
return _keyHitBuffer.shift();
};
this.sub__Limit = async function(fps) {
_assertNumber(fps);
_flushAllScreenCache();
var frameMillis = 1000 / fps / 1.15;
await GX.sleep(0);
while (Date.now() - _lastLimitTime < frameMillis) {
await GX.sleep(0);
}
_lastLimitTime = new Date();
};
this.autoLimit = async function() {
var timeElapsed = new Date() - _lastLimitTime;
if (timeElapsed > 1000) {
_flushAllScreenCache();
await GX.sleep(1);
_lastLimitTime = new Date();
}
};
this.func__LoadFont = async function(name, size, opts) {
_assertParam(name, 1);
_assertParam(size, 2);
if (!isNaN(size)) {
size = size + "px";
}
var id = _nextFontId;
_nextFontId++;
var nameLower = name.toLowerCase();
if (nameLower.startsWith("http://") || nameLower.startsWith("https://") || nameLower.startsWith("data:")) {
// load the font from the url
var url = name;
name = "Font-" + id;
await _loadFont(name, url);
}
else if (nameLower.endsWith(".ttf") || nameLower.endsWith(".otf") || nameLower.endsWith("woff") || nameLower.endsWith("woff2")) {
// attempt to load the font from the vfs
// TODO: what if it is a local URL?
var vfs = GX.vfs();
var f = vfs.getNode(name, GX.vfsCwd());
if (f && f.type == vfs.FILE) {
var url = await vfs.getDataURL(f);
name = "Font-" + id;
await _loadFont(name, url);
}
}
_fonts[id] = { name: name, size: size, style: ""};
// determine the font width and height
var ctx = GX.ctx();
ctx.font = size + " " + name;
var tm = ctx.measureText("M");
if (tm.fontBoundingBoxAscent) {
_fonts[id].height = tm.fontBoundingBoxAscent + tm.fontBoundingBoxDescent;
_fonts[id].offset = tm.fontBoundingBoxAscent - tm.actualBoundingBoxAscent;
}
else {
// sad, firefox does not support fontBoundingBox... so it will just not work as well
_fonts[id].height = tm.actualBoundingBoxAscent + tm.actualBoundingBoxDescent + 2;
_fonts[id].offset = 0;
}
if (tm.width != ctx.measureText("i").width) {
_fonts[id].width = 0;
_fonts[id].monospace = false;
}
else {
_fonts[id].width = tm.width;
_fonts[id].monospace = true;
}
return id;
async function _loadFont(name, url) {
var fontFace = new FontFace(name, "url(" + url + ")");
document.fonts.add(fontFace);
await fontFace.load();
}
};
this.func__LoadImage = async function(url) {
_assertParam(url);
var vfs = GX.vfs();
var vfsCwd = GX.vfsCwd();
var img = null;
// attempt to read the image from the virtual file system
var file = vfs.getNode(url, vfsCwd);
if (file && file.type == vfs.FILE) {
img = new Image();
img.src = await vfs.getDataURL(file);
while (!img.complete) {
await GX.sleep(10);
}
}
else {
// otherwise, read it from the url location
var img = new Image();
img.src = url;
while (!img.complete) {
await GX.sleep(10);
}
}
var imgId = QB.func__NewImage(img.width, img.height);
var ctx = _images[imgId].ctx;
ctx.drawImage(img, 0, 0);
return imgId;
};
this.func__MouseInput = function() {
return GX._mouseInput();
};
this.sub__MouseHide = function() {
var canvas = _images[0].canvas;
canvas.style.cursor = "none";
};
this.sub__MouseShow = function(style) {
if (style == undefined) {
style = "DEFAULT";
}
else {
style = style.trim().toUpperCase();
}
var canvas = _images[0].canvas;
if (style == "LINK") { canvas.style.cursor = "pointer"; }
else if (style == "TEXT") { canvas.style.cursor = "text"; }
else if (style == "CROSSHAIR") { canvas.style.cursor = "crosshair"; }
else if (style == "VERTICAL") { canvas.style.cursor = "ns-resize"; }
else if (style == "HORIZONTAL") { canvas.style.cursor = "ew-resize"; }
else if (style == "TOPLEFT_BOTTOMRIGHT") { canvas.style.cursor = "nwse-resize"; }
else if (style == "TOPRIGHT_BOTTOMLEFT") { canvas.style.cursor = "nesw-resize"; }
else if (style == "PROGRESS") { canvas.style.cursor = "progress"; }
else if (style == "WAIT") { canvas.style.cursor = "wait"; }
else if (style == "MOVE") { canvas.style.cursor = "move"; }
else if (style == "NOT_ALLOWED") { canvas.style.cursor = "not-allowed"; }
else if (style == "GRAB") { canvas.style.cursor = "grab"; }
else if (style == "GRABBING") { canvas.style.cursor = "grabbing"; }
else if (style == "ZOOM_IN") { canvas.style.cursor = "zoom-in"; }
else if (style == "ZOOM_OUT") { canvas.style.cursor = "zoom-out"; }
else { canvas.style.cursor = "default"; }
};
this.func__MouseX = function() {
return GX.mouseX();
};
this.func__MouseY = function() {
return GX.mouseY();
};
this.func__MouseButton = function(button) {
_assertNumber(button);
return GX.mouseButton(button);
};
this.func__MouseWheel = function() {
return GX.mouseWheel();
};
this.func__NewImage = function(iwidth, iheight, mode) {
_assertNumber(iwidth, 1);
_assertNumber(iheight, 2);
var canvas = document.createElement("canvas");
canvas.id = "qb-canvas-" + _nextImageId;
if (mode == 0) {
canvas.width = this.func__FontWidth() * iwidth;
canvas.height = this.func__FontHeight() * iheight;
}
else {
canvas.width = iwidth;
canvas.height = iheight;
}
ctx = canvas.getContext("2d");
ctx.lineCap = "butt";
_images[_nextImageId] = { canvas: canvas, ctx: ctx, lastX: 0, lastY: 0, charSizeMode: (mode == 0), dirty: true };
var tmpId = _nextImageId;
_nextImageId++;
return tmpId;
};
this.func__NumLock = function() {
return _keyDownMap._NumLock ? -1 : 0;
};
this.func__OS = function() {
var browser = "";
if ((navigator.userAgent.indexOf("Opera") || navigator.userAgent.indexOf('OPR')) != -1 ) {
browser = "Opera";
}
else if (navigator.userAgent.indexOf("Edg") != -1 ) {
browser = "Edge";
}
else if (navigator.userAgent.indexOf("Chrome") != -1 ) {
browser = "Chrome";
}
else if (navigator.userAgent.indexOf("Safari") != -1) {
browser = "Safari";
}
else if(navigator.userAgent.indexOf("Firefox") != -1 ) {
browser = "Firefox";
}
else if((navigator.userAgent.indexOf("MSIE") != -1 ) || (!!document.documentMode == true )) //IF IE > 10
{
browser = "IE";