-
Notifications
You must be signed in to change notification settings - Fork 595
/
Copy pathbrowserutils.ts
1477 lines (1301 loc) · 57.6 KB
/
browserutils.ts
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
/// <reference path="../localtypings/dom.d.ts" />
namespace pxt.BrowserUtils {
export function isDocumentVisible() {
return typeof window !== "undefined" && document.visibilityState === 'visible'
}
export function isIFrame(): boolean {
try {
return window && window.self !== window.top;
} catch (e) {
return true;
}
}
export function hasNavigator(): boolean {
return typeof navigator !== "undefined";
}
export function hasWindow(): boolean {
return typeof window !== "undefined";
}
export function isWindows(): boolean {
return hasNavigator() && /(Win32|Win64|WOW64)/i.test(navigator.platform);
}
export function isWindows10(): boolean {
return hasNavigator() && /(Win32|Win64|WOW64)/i.test(navigator.platform) && /Windows NT 10/i.test(navigator.userAgent);
}
export function isMobile(): boolean {
return hasNavigator() && /mobi/i.test(navigator.userAgent);
}
export function isIOS(): boolean {
return hasNavigator() &&
(/iPad|iPhone|iPod/.test(navigator.userAgent) ||
navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 1)
}
export function isAndroid(): boolean {
return hasNavigator() && /android/i.test(navigator.userAgent);
}
//MacIntel on modern Macs
export function isMac(): boolean {
return hasNavigator() && /Mac/i.test(navigator.platform);
}
//This is generally appears for Linux
//Android *sometimes* returns this
export function isLinux(): boolean {
return !!navigator && /Linux/i.test(navigator.platform);
}
// Detects if we are running on ARM (Raspberry pi)
export function isARM(): boolean {
return hasNavigator() && /arm/i.test(navigator.platform);
}
/*
Notes on browser detection
Actually: Claims to be:
IE MicrosoftEdge Chrome Safari Firefox NewEdge
IE X X?
Microsoft Edge X X X
Chrome X X
Safari X X
Firefox X
New Edge X X X
I allow Opera to go about claiming to be Chrome because it might as well be. Same for Chromium-based Edge.
*/
//Microsoft Edge lies about its user agent and claims to be Chrome, but Microsoft Edge/Version
//is always at the end
export function isEdge(): boolean {
return hasNavigator() && /Edge/i.test(navigator.userAgent);
}
//Chromium-based Edge. Note that `isChrome()` also detects this browser, and that's ok. In most cases Chromium-Edge can be treated like Chrome. Use this method if you need to differentiate them.
export function isChromiumEdge(): boolean {
return hasNavigator() && /Edg\//i.test(navigator.userAgent);
}
//IE11 also lies about its user agent, but has Trident appear somewhere in
//the user agent. Detecting the different between IE11 and Microsoft Edge isn't
//super-important because the UI is similar enough
export function isIE(): boolean {
return hasNavigator() && /Trident/i.test(navigator.userAgent);
}
//Microsoft Edge and IE11 lie about being Chrome. Chromium-based Edge ("Edgeium") will be detected as Chrome, that is ok. If you're looking for Edgeium, use `isChromiumEdge()`.
export function isChrome(): boolean {
return !isEdge() && !isIE() && !!navigator && (/Chrome/i.test(navigator.userAgent) || /Chromium/i.test(navigator.userAgent));
}
//Chrome and Microsoft Edge lie about being Safari
export function isSafari(): boolean {
//Could also check isMac but I don't want to risk excluding iOS
//Checking for iPhone, iPod or iPad as well as Safari in order to detect home screen browsers on iOS
return !isChrome() && !isEdge() && !!navigator && /(Macintosh|Safari|iPod|iPhone|iPad)/i.test(navigator.userAgent);
}
//Safari and WebKit lie about being Firefox
export function isFirefox(): boolean {
return !isSafari() && !!navigator && (/Firefox/i.test(navigator.userAgent) || /Seamonkey/i.test(navigator.userAgent));
}
//These days Opera's core is based on Chromium so we shouldn't distinguish between them too much
export function isOpera(): boolean {
return hasNavigator() && /Opera|OPR/i.test(navigator.userAgent);
}
//Midori *was* the default browser on Raspbian, however isn't any more
export function isMidori(): boolean {
return hasNavigator() && /Midori/i.test(navigator.userAgent);
}
//Epiphany (code name for GNOME Web) is the default browser on Raspberry Pi
//Epiphany also lies about being Chrome, Safari, and Chromium
export function isEpiphany(): boolean {
return hasNavigator() && /Epiphany/i.test(navigator.userAgent);
}
export function isTouchEnabled(): boolean {
return typeof window !== "undefined" &&
('ontouchstart' in window // works on most browsers
|| (navigator && navigator.maxTouchPoints > 0)); // works on IE10/11 and Surface);
}
export function isPxtElectron(): boolean {
return typeof window != "undefined" && !!(window as any).pxtElectron;
}
export function isIpcRenderer(): boolean {
return typeof window != "undefined" && !!(window as any).ipcRenderer;
}
export function isElectron() {
return isPxtElectron() || isIpcRenderer();
}
declare let Windows: any;
export let isWinRT = () => typeof (Windows as any) !== "undefined";
export function isLocalHost(ignoreFlags?: boolean): boolean {
try {
return typeof window !== "undefined"
&& /^https?:\/\/(?:localhost|127\.0\.0\.1|192\.168\.\d{1,3}\.\d{1,3}|[a-zA-Z0-9.-]+\.local):\d+\/?/.test(window.location.href)
&& (ignoreFlags || !/nolocalhost=1/.test(window.location.href))
&& !(pxt?.webConfig?.isStatic);
} catch (e) { return false; }
}
export function isLocalHostDev(): boolean {
return isLocalHost() && !isElectron();
}
export function isSkillmapEditor(): boolean {
try {
return /skill(?:s?)map=1/i.test(window.location.href);
} catch (e) { return false; }
}
export function isTabletSize(): boolean {
return window?.innerWidth <= pxt.BREAKPOINT_TABLET;
}
export function isComputerSize(): boolean {
return window?.innerWidth > pxt.BREAKPOINT_TABLET;
}
export function isInGame(): boolean {
const inGame = /inGame=1/i.exec(window.location.href);
return !!inGame;
}
export function hasFileAccess(): boolean {
const disableForMacIos = pxt.appTarget.appTheme.disableFileAccessinMaciOs && (pxt.BrowserUtils.isMac() || pxt.BrowserUtils.isIOS());
const disableForAndroid = pxt.appTarget.appTheme.disableFileAccessinAndroid && pxt.BrowserUtils.isAndroid();
return !disableForMacIos && !disableForAndroid;
}
export function noSharedLocalStorage(): boolean {
try {
return /nosharedlocalstorage/i.test(window.location.href);
} catch (e) { return false; }
}
export function useOldTutorialLayout(): boolean {
if (pxt.appTarget?.appTheme?.legacyTutorial) return true;
try {
return (/tutorialview=old/.test(window.location.href));
} catch (e) { return false; }
}
export function hasPointerEvents(): boolean {
return typeof window != "undefined" && !!(window as any).PointerEvent;
}
export function os(): string {
if (isWindows()) return "windows";
else if (isMac()) return "mac";
else if (isLinux() && isARM()) return "rpi";
else if (isLinux()) return "linux";
else return "unknown";
}
export function browser(): string {
if (isEdge()) return "edge";
if (isEpiphany()) return "epiphany";
else if (isMidori()) return "midori";
else if (isOpera()) return "opera";
else if (isIE()) return "ie";
else if (isChrome()) return "chrome";
else if (isSafari()) return "safari";
else if (isFirefox()) return "firefox";
else return "unknown";
}
export function browserVersion(): string {
if (!hasNavigator()) return null;
//Unsurprisingly browsers also lie about this and include other browser versions...
let matches: string[] = [];
if (isOpera()) {
matches = /(Opera|OPR)\/([0-9\.]+)/i.exec(navigator.userAgent);
}
if (isEpiphany()) {
matches = /Epiphany\/([0-9\.]+)/i.exec(navigator.userAgent);
}
else if (isMidori()) {
matches = /Midori\/([0-9\.]+)/i.exec(navigator.userAgent);
}
else if (isSafari()) {
matches = /Version\/([0-9\.]+)/i.exec(navigator.userAgent);
// pinned web sites and WKWebview for embedded browsers have a different user agent
// Mozilla/5.0 (iPhone; CPU iPhone OS 10_2_1 like Mac OS X) AppleWebKit/602.4.6 (KHTML, like Gecko) Mobile/14D27
// Mozilla/5.0 (iPad; CPU OS 10_3_3 like Mac OS X) AppleWebKit/603.3.8 (KHTML, like Gecko) Mobile/14G60
// Mozilla/5.0 (iPod; CPU OS 10_3_3 like Mac OS X) AppleWebKit/603.3.8 (KHTML, like Gecko) Mobile/14G60
// Mozilla/5.0 (iPod touch; CPU iPhone OS 14_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148;
// Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_5) AppleWebKit/605.1.15 (KHTML, like Gecko)
if (!matches)
matches = /(Macintosh|iPod( touch)?|iPhone|iPad); (CPU|Intel).*?OS (X )?(\d+)/i.exec(navigator.userAgent);
}
else if (isChrome()) {
matches = /(Chrome|Chromium)\/([0-9\.]+)/i.exec(navigator.userAgent);
}
else if (isEdge()) {
matches = /Edge\/([0-9\.]+)/i.exec(navigator.userAgent);
}
else if (isIE()) {
matches = /(MSIE |rv:)([0-9\.]+)/i.exec(navigator.userAgent);
}
else {
matches = /(Firefox|Seamonkey)\/([0-9\.]+)/i.exec(navigator.userAgent);
}
if (!matches || matches.length == 0) {
return null;
}
return matches[matches.length - 1];
}
let hasLoggedBrowser = false
// Note that IE11 is no longer supported in any target. Redirect handled in docfiles/pxtweb/browserRedirect.ts
export function isBrowserSupported(): boolean {
if (!navigator) {
return true; //All browsers define this, but we can't make any predictions if it isn't defined, so assume the best
}
// allow bots in general
if (/bot|crawler|spider|crawling/i.test(navigator.userAgent))
return true;
// Check target theme to see if this browser is supported
const unsupportedBrowsers = pxt.appTarget?.unsupportedBrowsers
|| (window as any).pxtTargetBundle?.unsupportedBrowsers as BrowserOptions[];
if (unsupportedBrowsers?.some(b => b.id == browser())) {
return false
}
// testing browser versions
const versionString = browserVersion();
const v = parseInt(versionString || "0")
const isRecentChrome = isChrome() && v >= 38;
const isRecentFirefox = isFirefox() && v >= 31;
const isRecentEdge = isEdge();
const isRecentSafari = isSafari() && v >= 9;
const isRecentOpera = (isOpera() && isChrome()) && v >= 21;
const isModernBrowser = isRecentChrome || isRecentFirefox || isRecentEdge || isRecentSafari || isRecentOpera
//In the future this should check for the availability of features, such
//as web workers
let isSupported = isModernBrowser
const isUnsupportedRPI = isMidori() || (isLinux() && isARM() && isEpiphany());
const isNotSupported = isUnsupportedRPI;
isSupported = isSupported && !isNotSupported
//Bypass
isSupported = isSupported || /anybrowser=(true|1)/.test(window.location.href)
if (!hasLoggedBrowser) {
pxt.log(`Browser: ${browser()} ${versionString} on ${os()}`)
if (!isSupported) {
pxt.tickEvent("browser.unsupported", { useragent: navigator.userAgent })
}
hasLoggedBrowser = true
}
return isSupported
}
export function devicePixelRatio(): number {
if (typeof window === "undefined" || !window.screen) return 1;
// these are IE specific
const sysXDPI = (window.screen as any).systemXDPI
const logicalXDPI = (window.screen as any).logicalXDPI
if (sysXDPI !== undefined
&& logicalXDPI !== undefined
&& sysXDPI > logicalXDPI) {
return sysXDPI / logicalXDPI;
}
else if (window && window.devicePixelRatio !== undefined) {
return window.devicePixelRatio;
}
return 1;
}
export function browserDownloadBinText(text: string, name: string, opt?: BrowserDownloadOptions): string {
return browserDownloadBase64(ts.pxtc.encodeBase64(text), name, opt)
}
export function browserDownloadText(text: string, name: string, opt?: BrowserDownloadOptions): string {
return browserDownloadBase64(ts.pxtc.encodeBase64(Util.toUTF8(text)), name, opt);
}
export function isBrowserDownloadInSameWindow(): boolean {
const windowOpen = isMobile() && isSafari() && !/downloadWindowOpen=0/i.test(window.location.href);
return windowOpen;
}
// for browsers that strictly require that a download gets initiated within a user click
export function isBrowserDownloadWithinUserContext(): boolean {
const versionString = browserVersion();
const v = parseInt(versionString || "0")
const r = (isMobile() && isSafari() && v >= 11) || /downloadUserContext=1/i.test(window.location.href);
return r;
}
export function browserDownloadDataUri(uri: string, name: string, userContextWindow?: Window) {
const windowOpen = isBrowserDownloadInSameWindow();
const versionString = browserVersion();
const v = parseInt(versionString || "0")
if (windowOpen) {
if (userContextWindow) userContextWindow.location.href = uri;
else window.open(uri, "_self");
} else if (pxt.BrowserUtils.isSafari()
&& (v < 10 || (versionString.indexOf('10.0') == 0) || isMobile())) {
// For Safari versions prior to 10.1 and all Mobile Safari versions
// For mysterious reasons, the "link" trick closes the
// PouchDB database
let iframe = document.getElementById("downloader") as HTMLIFrameElement;
if (!iframe) {
pxt.debug('injecting downloader iframe')
iframe = document.createElement("iframe") as HTMLIFrameElement;
iframe.id = "downloader";
iframe.style.position = "absolute";
iframe.style.right = "0";
iframe.style.bottom = "0";
iframe.style.zIndex = "-1";
iframe.style.width = "1px";
iframe.style.height = "1px";
document.body.appendChild(iframe);
}
iframe.src = uri;
} else if (/^data:/i.test(uri) && (pxt.BrowserUtils.isEdge() || pxt.BrowserUtils.isIE())) {
//Fix for edge
let byteString = atob(uri.split(',')[1]);
let ia = Util.stringToUint8Array(byteString);
let blob = new Blob([ia], { type: "img/png" });
window.navigator.msSaveOrOpenBlob(blob, name);
} else {
let link = <any>window.document.createElement('a');
if (typeof link.download == "string") {
link.href = uri;
link.download = name;
document.body.appendChild(link); // for FF
link.click();
document.body.removeChild(link);
} else {
document.location.href = uri;
}
}
}
export function browserDownloadUInt8Array(buf: Uint8Array, name: string, opt?: BrowserDownloadOptions): string {
return browserDownloadBase64(ts.pxtc.encodeBase64(Util.uint8ArrayToString(buf)), name, opt);
}
export function toDownloadDataUri(b64: string, contentType: string): string {
let protocol = "data";
if (isMobile() && isSafari() && pxt.appTarget.appTheme.mobileSafariDownloadProtocol)
protocol = pxt.appTarget.appTheme.mobileSafariDownloadProtocol;
const m = /downloadProtocol=([a-z0-9:/?]+)/i.exec(window.location.href);
if (m) protocol = m[1];
const dataurl = protocol + ":" + contentType + ";base64," + b64
return dataurl;
}
export interface BrowserDownloadOptions {
contentType?: string; // defl: application/octet-stream
userContextWindow?: Window;
onError?: (err: any) => void;
maintainObjectURL?: boolean;
}
export function browserDownloadBase64(b64: string, name: string, opt: BrowserDownloadOptions = {}): string {
pxt.debug('trigger download');
const {
contentType = "application/octet-stream",
userContextWindow,
onError,
maintainObjectURL
} = opt;
const createObjectURL = window.URL?.createObjectURL;
const asDataUri = pxt.appTarget.appTheme.disableBlobObjectDownload;
let downloadurl: string;
try {
if (!!createObjectURL && !asDataUri) {
const b = new Blob([Util.stringToUint8Array(atob(b64))], { type: contentType });
const objUrl = createObjectURL(b);
browserDownloadDataUri(objUrl, name, userContextWindow);
if (maintainObjectURL) {
downloadurl = objUrl;
} else {
window.setTimeout(() => window.URL.revokeObjectURL(downloadurl), 0);
}
} else {
downloadurl = toDownloadDataUri(b64, name);
browserDownloadDataUri(downloadurl, name, userContextWindow);
}
} catch (e) {
if (onError) onError(e);
pxt.debug("saving failed");
}
return downloadurl;
}
export function loadImageAsync(data: string): Promise<HTMLImageElement> {
const img = document.createElement("img")
return new Promise<HTMLImageElement>((resolve, reject) => {
img.onload = () => resolve(img);
img.onerror = () => resolve(undefined);
img.crossOrigin = "anonymous";
img.src = data;
});
}
export function loadCanvasAsync(url: string): Promise<HTMLCanvasElement> {
return loadImageAsync(url)
.then(img => {
const canvas = document.createElement("canvas")
canvas.width = img.width
canvas.height = img.height
const ctx = canvas.getContext("2d")
ctx.drawImage(img, 0, 0);
return canvas;
})
}
export function scaleImageData(img: ImageData, scale: number): ImageData {
const inputCanvas = document.createElement("canvas");
const outputCanvas = document.createElement("canvas");
inputCanvas.width = img.width;
inputCanvas.height = img.height;
outputCanvas.width = img.width * scale;
outputCanvas.height = img.height * scale;
const ctx = inputCanvas.getContext("2d");
const outCtx = outputCanvas.getContext("2d");
ctx.putImageData(img, 0, 0);
outCtx.imageSmoothingEnabled = false;
outCtx.scale(scale, scale);
outCtx.drawImage(inputCanvas, 0, 0);
return outCtx.getImageData(0, 0, img.width * scale, img.height * scale);
}
export function imageDataToPNG(img: ImageData, scale = 1): string {
if (!img) return undefined;
const inputCanvas = document.createElement("canvas");
const outputCanvas = document.createElement("canvas");
inputCanvas.width = img.width;
inputCanvas.height = img.height;
outputCanvas.width = img.width * scale;
outputCanvas.height = img.height * scale;
const ctx = inputCanvas.getContext("2d");
const outCtx = outputCanvas.getContext("2d");
ctx.putImageData(img, 0, 0);
outCtx.imageSmoothingEnabled = false;
outCtx.scale(scale, scale);
outCtx.drawImage(inputCanvas, 0, 0);
return outputCanvas.toDataURL("image/png");
}
const MAX_SCREENSHOT_SIZE = 10e6; // max 10Mb
export function encodeToPngAsync(dataUri: string,
options?: {
width?: number,
height?: number,
pixelDensity?: number,
maxSize?: number,
text?: string
}): Promise<string> {
const { width, height, pixelDensity = 4, maxSize = MAX_SCREENSHOT_SIZE, text } = options || {};
return new Promise<string>((resolve, reject) => {
const img = new Image;
img.onload = function () {
const cvs = document.createElement("canvas") as HTMLCanvasElement;
const ctx = cvs.getContext("2d");
cvs.width = (width || img.width) * pixelDensity;
cvs.height = (height || img.height) * pixelDensity;
if (text) {
ctx.fillStyle = "#fff";
ctx.fillRect(0, 0, cvs.width, cvs.height);
}
ctx.drawImage(img, 0, 0, width, height, 0, 0, cvs.width, cvs.height);
let canvasdata = cvs.toDataURL("image/png");
// if the generated image is too big, shrink image
while (canvasdata.length > maxSize) {
cvs.width = (cvs.width / 2) >> 0;
cvs.height = (cvs.height / 2) >> 0;
pxt.debug(`screenshot size ${canvasdata.length}b, shrinking to ${cvs.width}x${cvs.height}`)
ctx.drawImage(img, 0, 0, width, height, 0, 0, cvs.width, cvs.height);
canvasdata = cvs.toDataURL("image/png");
}
if (text) {
let p = pxt.lzmaCompressAsync(text).then(blob => {
const datacvs = pxt.Util.encodeBlobAsync(cvs, blob);
resolve(datacvs.toDataURL("image/png"));
});
} else {
resolve(canvasdata);
}
};
img.onerror = ev => {
pxt.reportError("png", "png rendering failed");
resolve(undefined)
}
img.src = dataUri;
})
}
export function resolveCdnUrl(path: string): string {
// don't expand full urls
if (/^https?:\/\//i.test(path))
return path;
const monacoPaths: Map<string> = (window as any).MonacoPaths || {};
const blobPath = monacoPaths[path];
// find compute blob url
if (blobPath)
return blobPath;
// might have been exanded already
if (U.startsWith(path, pxt.webConfig.commitCdnUrl))
return path;
// append CDN
return pxt.webConfig.commitCdnUrl + path;
}
export function loadStyleAsync(path: string, rtl?: boolean): Promise<void> {
if (rtl) path = "rtl" + path;
const id = "style-" + path;
if (document.getElementById(id)) return Promise.resolve();
const url = resolveCdnUrl(path);
const links = Util.toArray(document.head.getElementsByTagName("link"));
const link = links.filter(l => l.getAttribute("href") == url)[0];
if (link) {
if (!link.id) link.id = id;
return Promise.resolve();
}
return new Promise<void>((resolve, reject) => {
const el = document.createElement("link");
el.href = url;
el.rel = "stylesheet";
el.type = "text/css";
el.id = id;
el.addEventListener('load', () => resolve());
el.addEventListener('error', (e) => reject(e));
document.head.appendChild(el);
});
}
let loadScriptPromises: pxt.Map<Promise<void>> = {};
export function loadScriptAsync(path: string): Promise<void> {
const url = resolveCdnUrl(path);
let p = loadScriptPromises[url];
if (!p) {
p = loadScriptPromises[url] = new Promise<void>((resolve, reject) => {
pxt.debug(`script: loading ${url}`);
const script = document.createElement('script');
script.type = 'text/javascript';
script.addEventListener('load', () => resolve());
script.addEventListener('error', (e) => {
// might have had connection issue, allow to try later
delete loadScriptPromises[url];
reject(e);
});
script.src = url;
script.async = true;
document.body.appendChild(script);
});
}
return p;
}
export function loadAjaxAsync(url: string): Promise<string> {
return new Promise<string>((resolve, reject) => {
let httprequest = new XMLHttpRequest();
httprequest.onreadystatechange = function () {
if (httprequest.readyState == XMLHttpRequest.DONE) {
if (httprequest.status == 200) {
resolve(httprequest.responseText);
}
else {
reject(httprequest.status);
}
}
};
httprequest.open("GET", url, true);
httprequest.send();
})
}
let loadBlocklyPromise: Promise<void>;
export function loadBlocklyAsync(): Promise<void> {
if (!loadBlocklyPromise) {
pxt.debug(`blockly: delay load`);
let p = pxt.BrowserUtils.loadStyleAsync("blockly.css", ts.pxtc.Util.isUserLanguageRtl());
p = p.then(() => {
pxt.debug(`blockly: loaded`)
});
loadBlocklyPromise = p;
}
return loadBlocklyPromise;
}
export function patchCdn(url: string): string {
if (!url) return url;
const online = pxt.getOnlineCdnUrl();
if (online)
return url.replace("@cdnUrl@", online);
else
return url.replace(/@cdnUrl@\/(blob|commit)\/[a-f0-9]{40}\//, "./");
}
export function initTheme() {
const theme = pxt.appTarget.appTheme;
if (theme) {
if (theme.accentColor) {
let style = document.createElement('style');
style.type = 'text/css';
style.appendChild(document.createTextNode(
`.ui.accent { color: ${theme.accentColor}; }
.ui.inverted.menu .accent.active.item, .ui.inverted.accent.menu { background-color: ${theme.accentColor}; }`));
document.getElementsByTagName('head')[0].appendChild(style);
}
}
// RTL languages
if (Util.isUserLanguageRtl()) {
pxt.debug("rtl layout");
pxt.BrowserUtils.addClass(document.body, "rtl");
document.body.style.direction = "rtl";
// replace semantic.css with rtlsemantic.css
const links = Util.toArray(document.head.getElementsByTagName("link"));
const semanticLink = links.filter(l => Util.endsWith(l.getAttribute("href"), "semantic.css"))[0];
if (semanticLink) {
const semanticHref = semanticLink.getAttribute("data-rtl");
if (semanticHref) {
pxt.debug(`swapping to ${semanticHref}`)
semanticLink.setAttribute("href", semanticHref);
}
}
// replace blockly.css with rtlblockly.css if possible
const blocklyLink = links.filter(l => Util.endsWith(l.getAttribute("href"), "blockly.css"))[0];
if (blocklyLink) {
const blocklyHref = blocklyLink.getAttribute("data-rtl");
if (blocklyHref) {
pxt.debug(`swapping to ${blocklyHref}`)
blocklyLink.setAttribute("href", blocklyHref);
blocklyLink.removeAttribute("data-rtl");
}
}
}
}
/**
* Utility method to change the hash.
* Pass keepHistory to retain an entry of the change in the browser history.
*/
export function changeHash(hash: string, keepHistory?: boolean) {
if (hash.charAt(0) != '#') hash = '#' + hash;
if (keepHistory) {
window.location.hash = hash;
} else {
window.history.replaceState('', '', hash)
}
}
/**
* Simple utility method to join urls.
*/
export function urlJoin(urlPath1: string, urlPath2: string): string {
if (!urlPath1) return urlPath2;
if (!urlPath2) return urlPath1;
const normalizedUrl1 = (urlPath1.indexOf('/') == urlPath1.length - 1) ?
urlPath1.substring(0, urlPath1.length - 1) : urlPath1;
const normalizedUrl2 = (urlPath2.indexOf('/') == 0) ?
urlPath2.substring(1) : urlPath2;
return normalizedUrl1 + "/" + normalizedUrl2;
}
/**
* Simple utility method to join multiple urls.
*/
export function joinURLs(...parts: string[]): string {
let result: string;
if (parts) {
for (let i = 0; i < parts.length; i++) {
result = urlJoin(result, parts[i]);
}
}
return result;
}
export function storageEstimateAsync(): Promise<{ quota?: number; usage?: number; }> {
const nav = hasNavigator() && <any>window.navigator;
if (nav && nav.storage && nav.storage.estimate)
return nav.storage.estimate();
else return Promise.resolve({});
}
export const scheduleStorageCleanup = hasNavigator() && (<any>navigator).storage && (<any>navigator).storage.estimate // some browser don't support this
? ts.pxtc.Util.throttle(function () {
const MIN_QUOTA = 1000000; // 1Mb
const MAX_USAGE_RATIO = 0.9; // max 90%
storageEstimateAsync()
.then(estimate => {
// quota > 50%
pxt.debug(`storage estimate: ${(estimate.usage / estimate.quota * 100) >> 0}%, ${(estimate.usage / 1000000) >> 0}/${(estimate.quota / 1000000) >> 0}Mb`)
if (estimate.quota
&& estimate.usage
&& estimate.quota > MIN_QUOTA
&& (estimate.usage / estimate.quota) > MAX_USAGE_RATIO) {
pxt.log(`quota usage exceeded, clearing translations`);
pxt.tickEvent('storage.cleanup');
return clearTranslationDbAsync();
}
return Promise.resolve();
})
.catch(e => {
pxt.reportException(e);
})
}, 10000, false)
: () => { };
export function stressTranslationsAsync(): Promise<void> {
let md = "...";
for (let i = 0; i < 16; ++i)
md += md + Math.random();
pxt.log(`adding entry ${md.length * 2} bytes`);
return U.delay(1)
.then(() => translationDbAsync())
.then(db => db.setAsync("foobar", Math.random().toString(), null, undefined, md))
.then(() => pxt.BrowserUtils.storageEstimateAsync())
.then(estimate => !estimate.quota || estimate.usage / estimate.quota < 0.8 ? stressTranslationsAsync() : Promise.resolve());
}
export interface ITranslationDbEntry {
id?: string;
etag: string;
time: number;
strings?: pxt.Map<string>; // UI string translations
md?: string; // markdown content
}
export interface ITranslationDb {
getAsync(lang: string, filename: string): Promise<ITranslationDbEntry>;
setAsync(lang: string, filename: string, etag: string, strings?: pxt.Map<string>, md?: string): Promise<void>;
// delete all
clearAsync(): Promise<void>;
}
class MemTranslationDb implements ITranslationDb {
translations: pxt.Map<ITranslationDbEntry> = {};
key(lang: string, filename: string) {
return `${lang}|${filename}|master`;
}
get(lang: string, filename: string): ITranslationDbEntry {
return this.translations[this.key(lang, filename)];
}
getAsync(lang: string, filename: string): Promise<ITranslationDbEntry> {
return Promise.resolve(this.get(lang, filename));
}
set(lang: string, filename: string, etag: string, time: number, strings?: pxt.Map<string>, md?: string) {
this.translations[this.key(lang, filename)] = {
etag,
time,
strings,
md
}
}
setAsync(lang: string, filename: string, etag: string, strings?: pxt.Map<string>, md?: string): Promise<void> {
this.set(lang, filename, etag, Util.now(), strings);
return Promise.resolve();
}
clearAsync() {
this.translations = {};
return Promise.resolve();
}
}
// IndexedDB wrapper class
export type IDBUpgradeHandler = (ev: IDBVersionChangeEvent, request: IDBRequest) => void;
export class IDBWrapper {
private _db: IDBDatabase;
constructor(
private name: string,
private version: number,
private upgradeHandler?: IDBUpgradeHandler,
private quotaExceededHandler?: () => void,
private skipErrorLog = false) {
}
private throwIfNotOpened(): void {
if (!this._db) {
throw new Error("Database not opened; call IDBWrapper.openAsync() first");
}
}
private errorHandler(err: Error, op: string, reject: (err: Error) => void): void {
if (this.skipErrorLog) {
reject(err);
return;
}
pxt.error(new Error(`${this.name} IDBWrapper error for ${op}: ${err.message}`));
reject(err);
// special case for quota exceeded
if (err.name == "QuotaExceededError") {
// oops, we ran out of space
pxt.log(`storage quota exceeded...`);
pxt.tickEvent('storage.quotaexceedederror');
if (this.quotaExceededHandler)
this.quotaExceededHandler();
}
}
private getObjectStore(name: string, mode: "readonly" | "readwrite" = "readonly"): IDBObjectStore {
this.throwIfNotOpened();
const transaction = this._db.transaction([name], mode);
return transaction.objectStore(name);
}
static deleteDatabaseAsync(name: string): Promise<void> {
return new Promise((resolve, reject) => {
const idbFactory: IDBFactory = window.indexedDB || (<any>window).mozIndexedDB || (<any>window).webkitIndexedDB || (<any>window).msIndexedDB;
const request = idbFactory.deleteDatabase(name);
request.onsuccess = () => resolve();
request.onerror = () => reject(request.error);
});
}
public openAsync(): Promise<void> {
return new Promise((resolve, reject) => {
const idbFactory: IDBFactory = window.indexedDB || (<any>window).mozIndexedDB || (<any>window).webkitIndexedDB || (<any>window).msIndexedDB;
const request = idbFactory.open(this.name, this.version);
request.onsuccess = () => {
this._db = request.result;
resolve();
};
request.onerror = () => this.errorHandler(request.error, "open", reject);
request.onupgradeneeded = (ev) => this.upgradeHandler(ev, request);
});
}
public getAsync<T>(storeName: string, id: string): Promise<T> {
return new Promise((resolve, reject) => {
const store = this.getObjectStore(storeName);
const request = store.get(id);
request.onsuccess = () => resolve(request.result as T);
request.onerror = () => this.errorHandler(request.error, "get", reject);
});
}
public getAllAsync<T>(storeName: string): Promise<T[]> {
return new Promise((resolve, reject) => {
const store = this.getObjectStore(storeName);
const cursor = store.openCursor();
const data: T[] = [];
cursor.onsuccess = () => {
if (cursor.result) {
data.push(cursor.result.value);
cursor.result.continue();
} else {
resolve(data);
}
};
cursor.onerror = () => this.errorHandler(cursor.error, "getAll", reject);
});
}
public setAsync(storeName: string, data: any): Promise<void> {
return new Promise((resolve, reject) => {
const store = this.getObjectStore(storeName, "readwrite");
let request: IDBRequest;
if (typeof data.id !== "undefined" && data.id !== null) {
request = store.put(data);
} else {
request = store.add(data);
}
request.onsuccess = () => resolve();
request.onerror = () => this.errorHandler(request.error, "set", reject);
});
}
public deleteAsync(storeName: string, id: string): Promise<void> {
return new Promise((resolve, reject) => {
const store = this.getObjectStore(storeName, "readwrite");
const request = store.delete(id);
request.onsuccess = () => resolve();
request.onerror = () => this.errorHandler(request.error, "delete", reject);
});
}
public deleteAllAsync(storeName: string): Promise<void> {
return new Promise((resolve, reject) => {
const store = this.getObjectStore(storeName, "readwrite");
const request = store.clear();
request.onsuccess = () => resolve();
request.onerror = () => this.errorHandler(request.error, "deleteAll", reject);
});
}
public getObjectStoreWrapper<T>(storeName: string): IDBObjectStoreWrapper<T> {
return new IDBObjectStoreWrapper(this, storeName);
}
}
export class IDBObjectStoreWrapper<T> {
constructor(protected db: IDBWrapper, protected storeName: string) {}
public getAsync(id: string): Promise<T> {
return this.db.getAsync(this.storeName, id);
}
public getAllAsync(): Promise<T[]> {
return this.db.getAllAsync(this.storeName);
}
public setAsync(data: T): Promise<void> {
return this.db.setAsync(this.storeName, data);
}
public async deleteAsync(id: string): Promise<void> {
await this.db.deleteAsync(this.storeName, id);
}
public async deleteAllAsync(): Promise<void> {
await this.db.deleteAllAsync(this.storeName);
}
}
class IndexedDbTranslationDb implements ITranslationDb {
static TABLE = "files";
static KEYPATH = "id";
static dbName() {
return `__pxt_translations_${pxt.appTarget.id || ""}`;
}
static createAsync(): Promise<IndexedDbTranslationDb> {
function openAsync() {