forked from codefrau/SqueakJS
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvm.js
6916 lines (6876 loc) · 321 KB
/
vm.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
module('users.bert.SqueakJS.vm').requires().toRun(function() {
"use strict";
/*
* Copyright (c) 2013-2015 Bert Freudenberg
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
// shorter name for convenience
window.Squeak = users.bert.SqueakJS.vm;
Object.extend(Squeak,
"version", {
// system attributes
vmVersion: "SqueakJS 0.7.4",
vmBuild: "unknown", // replace at runtime by last-modified?
vmPath: "/",
vmFile: "vm.js",
platformName: "Web",
platformSubtype: "unknown",
osVersion: navigator.userAgent, // might want to parse
windowSystem: "HTML",
},
"object header", {
// object headers
HeaderTypeMask: 3,
HeaderTypeSizeAndClass: 0, //3-word header
HeaderTypeClass: 1, //2-word header
HeaderTypeFree: 2, //free block
HeaderTypeShort: 3, //1-word header
},
"special objects", {
// Indices into SpecialObjects array
splOb_NilObject: 0,
splOb_FalseObject: 1,
splOb_TrueObject: 2,
splOb_SchedulerAssociation: 3,
splOb_ClassBitmap: 4,
splOb_ClassInteger: 5,
splOb_ClassString: 6,
splOb_ClassArray: 7,
splOb_SmalltalkDictionary: 8,
splOb_ClassFloat: 9,
splOb_ClassMethodContext: 10,
splOb_ClassBlockContext: 11,
splOb_ClassPoint: 12,
splOb_ClassLargePositiveInteger: 13,
splOb_TheDisplay: 14,
splOb_ClassMessage: 15,
splOb_ClassCompiledMethod: 16,
splOb_TheLowSpaceSemaphore: 17,
splOb_ClassSemaphore: 18,
splOb_ClassCharacter: 19,
splOb_SelectorDoesNotUnderstand: 20,
splOb_SelectorCannotReturn: 21,
splOb_TheInputSemaphore: 22,
splOb_SpecialSelectors: 23,
splOb_CharacterTable: 24,
splOb_SelectorMustBeBoolean: 25,
splOb_ClassByteArray: 26,
splOb_ClassProcess: 27,
splOb_CompactClasses: 28,
splOb_TheTimerSemaphore: 29,
splOb_TheInterruptSemaphore: 30,
splOb_FloatProto: 31,
splOb_SelectorCannotInterpret: 34,
splOb_MethodContextProto: 35,
splOb_ClassBlockClosure: 36,
splOb_BlockContextProto: 37,
splOb_ExternalObjectsArray: 38,
splOb_ClassPseudoContext: 39,
splOb_ClassTranslatedMethod: 40,
splOb_TheFinalizationSemaphore: 41,
splOb_ClassLargeNegativeInteger: 42,
splOb_ClassExternalAddress: 43,
splOb_ClassExternalStructure: 44,
splOb_ClassExternalData: 45,
splOb_ClassExternalFunction: 46,
splOb_ClassExternalLibrary: 47,
splOb_SelectorAboutToReturn: 48,
splOb_SelectorRunWithIn: 49,
splOb_SelectorAttemptToAssign: 50,
splOb_PrimErrTableIndex: 51,
splOb_ClassAlien: 52,
splOb_InvokeCallbackSelector: 53,
splOb_ClassUnsafeAlien: 54,
splOb_ClassWeakFinalizer: 55,
},
"known classes", {
// Class layout:
Class_superclass: 0,
Class_mdict: 1,
Class_format: 2,
Class_instVars: null, // 3 or 4 depending on image, see instVarNames()
Class_name: 6,
// Context layout:
Context_sender: 0,
Context_instructionPointer: 1,
Context_stackPointer: 2,
Context_method: 3,
Context_closure: 4,
Context_receiver: 5,
Context_tempFrameStart: 6,
Context_smallFrameSize: 17,
Context_largeFrameSize: 57,
BlockContext_caller: 0,
BlockContext_argumentCount: 3,
BlockContext_initialIP: 4,
BlockContext_home: 5,
// Closure layout:
Closure_outerContext: 0,
Closure_startpc: 1,
Closure_numArgs: 2,
Closure_firstCopiedValue: 3,
// Stream layout:
Stream_array: 0,
Stream_position: 1,
Stream_limit: 2,
//ProcessorScheduler layout:
ProcSched_processLists: 0,
ProcSched_activeProcess: 1,
//Link layout:
Link_nextLink: 0,
//LinkedList layout:
LinkedList_firstLink: 0,
LinkedList_lastLink: 1,
//Semaphore layout:
Semaphore_excessSignals: 2,
//Process layout:
Proc_suspendedContext: 1,
Proc_priority: 2,
Proc_myList: 3,
// Association layout:
Assn_key: 0,
Assn_value: 1,
// MethodDict layout:
MethodDict_array: 1,
MethodDict_selectorStart: 2,
// Message layout
Message_selector: 0,
Message_arguments: 1,
Message_lookupClass: 2,
// Point layout:
Point_x: 0,
Point_y: 1,
// LargeInteger layout:
LargeInteger_bytes: 0,
LargeInteger_neg: 1,
// BitBlt layout:
BitBlt_dest: 0,
BitBlt_source: 1,
BitBlt_halftone: 2,
BitBlt_combinationRule: 3,
BitBlt_destX: 4,
BitBlt_destY: 5,
BitBlt_width: 6,
BitBlt_height: 7,
BitBlt_sourceX: 8,
BitBlt_sourceY: 9,
BitBlt_clipX: 10,
BitBlt_clipY: 11,
BitBlt_clipW: 12,
BitBlt_clipH: 13,
BitBlt_colorMap: 14,
BitBlt_warpBase: 15,
// Form layout:
Form_bits: 0,
Form_width: 1,
Form_height: 2,
Form_depth: 3,
Form_offset: 4,
// WeakFinalizationList layout:
WeakFinalizationList_first: 0,
// WeakFinalizerItem layout:
WeakFinalizerItem_list: 0,
WeakFinalizerItem_next: 1,
},
"events", {
Mouse_Blue: 1,
Mouse_Yellow: 2,
Mouse_Red: 4,
Keyboard_Shift: 8,
Keyboard_Ctrl: 16,
Keyboard_Alt: 32,
Keyboard_Cmd: 64,
Mouse_All: 1 + 2 + 4,
Keyboard_All: 8 + 16 + 32 + 64,
EventTypeNone: 0,
EventTypeMouse: 1,
EventTypeKeyboard: 2,
EventTypeDragDropFiles: 3,
EventKeyChar: 0,
EventKeyDown: 1,
EventKeyUp: 2,
EventDragEnter: 1,
EventDragMove: 2,
EventDragLeave: 3,
EventDragDrop: 4,
},
"constants", {
MinSmallInt: -0x40000000,
MaxSmallInt: 0x3FFFFFFF,
NonSmallInt: -0x50000000, // non-small and neg (so non pos32 too)
MillisecondClockMask: 0x1FFFFFFF,
},
"modules", {
// don't clobber registered modules
externalModules: Squeak.externalModules || {},
registerExternalModule: function(name, module) {
this.externalModules[name] = module;
},
},
"files", {
fsck: function(whenDone, dir, files, stats) {
dir = dir || "";
stats = stats || {dirs: 0, files: 0, bytes: 0, deleted: 0};
if (!files) {
// find existing files
files = {};
for (var key in localStorage) {
var match = key.match(/squeak-file(\.lz)?:(.*)$/);
if (match) {files[match[2]] = true};
}
if (typeof indexedDB !== "undefined") {
return this.dbTransaction("readonly", "fsck cursor", function(fileStore) {
var cursorReq = fileStore.openCursor();
cursorReq.onsuccess = function(e) {
var cursor = e.target.result;
if (cursor) {
files[cursor.key] = true;
cursor.continue();
} else { // done
Squeak.fsck(whenDone, dir, files, stats);
}
}
cursorReq.onerror = function(e) {
console.error("fsck failed");
}
});
}
}
// check directories
var entries = Squeak.dirList(dir);
for (var name in entries) {
var path = dir + "/" + name,
isDir = entries[name][3];
if (isDir) {
var exists = "squeak:" + path in localStorage;
if (exists) {
Squeak.fsck(null, path, files, stats);
stats.dirs++;
} else {
console.log("Deleting stale directory " + path);
Squeak.dirDelete(path);
stats.deleted++;
}
} else {
if (!files[path]) {
console.log("Deleting stale file entry " + path);
Squeak.fileDelete(path, true);
stats.deleted++;
} else {
files[path] = false; // mark as visited
stats.files++;
stats.bytes += entries[name][4];
}
}
}
// check orphaned files
if (dir === "") {
console.log("squeak fsck: " + stats.dirs + " directories, " + stats.files + " files, " + (stats.bytes/1000000).toFixed(1) + " MBytes");
var orphaned = [],
total = 0;
for (var path in files) {
total++;
if (files[path]) orphaned.push(path); // not marked visited
}
if (orphaned.length > 0) {
for (var i = 0; i < orphaned.length; i++) {
console.log("Deleting orphaned file " + orphaned[i]);
delete localStorage["squeak-file:" + orphaned[i]];
delete localStorage["squeak-file.lz:" + orphaned[i]];
stats.deleted++;
}
if (typeof indexedDB !== "undefined") {
this.dbTransaction("readwrite", "fsck delete", function(fileStore) {
for (var i = 0; i < orphaned.length; i++) {
fileStore.delete(orphaned[i]);
};
});
}
}
if (whenDone) whenDone(stats);
}
},
dbTransaction: function(mode, description, transactionFunc, completionFunc) {
// File contents is stored in the IndexedDB named "squeak" in object store "files"
// and directory entries in localStorage with prefix "squeak:"
function fakeTransaction() {
transactionFunc(Squeak.dbFake());
if (completionFunc) completionFunc();
}
if (typeof indexedDB == "undefined") {
return fakeTransaction();
}
var startTransaction = function() {
var trans = SqueakDB.transaction("files", mode),
fileStore = trans.objectStore("files");
trans.oncomplete = function(e) { if (completionFunc) completionFunc(); }
trans.onerror = function(e) { console.error(e.target.error.name + ": " + description) }
trans.onabort = function(e) {
console.error(e.target.error.name + ": aborting " + description);
// fall back to local/memory storage
transactionFunc(Squeak.dbFake());
if (completionFunc) completionFunc();
}
transactionFunc(fileStore);
};
// if database connection already opened, just do transaction
if (window.SqueakDB) return startTransaction();
// otherwise, open SqueakDB first
var openReq = indexedDB.open("squeak");
// iOS Safari implements the interface but only returns null
// https://stackoverflow.com/questions/27415998/indexeddb-open-returns-null-on-safari-ios-8-1-1-and-halts-execution-on-cordova
if (openReq === null) {
return fakeTransaction();
}
openReq.onsuccess = function(e) {
console.log("Opened files database.");
window.SqueakDB = this.result;
SqueakDB.onversionchange = function(e) {
delete window.SqueakDB;
this.close();
};
SqueakDB.onerror = function(e) {
console.error("Error accessing database: " + e.target.error.name);
};
startTransaction();
};
openReq.onupgradeneeded = function (e) {
// run only first time, or when version changed
console.log("Creating files database");
var db = e.target.result;
db.createObjectStore("files");
};
openReq.onerror = function(e) {
console.error(e.target.error.name + ": cannot open files database");
console.warn("Falling back to local storage");
fakeTransaction();
};
openReq.onblocked = function(e) {
// If some other tab is loaded with the database, then it needs to be closed
// before we can proceed upgrading the database.
alert("Database upgrade needed. Please close all other tabs with this site open!");
};
},
dbFake: function() {
// indexedDB is not supported by this browser, fake it using localStorage
// since localStorage space is severly limited, use LZString if loaded
// see https://github.com/pieroxy/lz-string
if (typeof SqueakDBFake == "undefined") {
if (typeof indexedDB == "undefined")
console.warn("IndexedDB not supported by this browser, using localStorage");
window.SqueakDBFake = {
bigFiles: {},
bigFileThreshold: 100000,
get: function(filename) {
var buffer = SqueakDBFake.bigFiles[filename];
if (!buffer) {
var string = localStorage["squeak-file:" + filename];
if (!string) {
var compressed = localStorage["squeak-file.lz:" + filename];
if (compressed) {
if (typeof LZString == "object") {
string = LZString.decompressFromUTF16(compressed);
} else {
console.error("LZString not loaded: cannot decompress " + filename);
}
}
}
if (string) {
var bytes = new Uint8Array(string.length);
for (var i = 0; i < bytes.length; i++)
bytes[i] = string.charCodeAt(i) & 0xFF;
buffer = bytes.buffer;
}
}
var req = {result: buffer, error: "file not found"};
setTimeout(function(){
if (buffer && req.onsuccess) req.onsuccess({target: req});
if (!buffer && req.onerror) req.onerror({target: req});
}, 0);
return req;
},
put: function(buffer, filename) {
if (buffer.byteLength > SqueakDBFake.bigFileThreshold) {
if (!SqueakDBFake.bigFiles[filename])
console.log("File " + filename + " (" + buffer.byteLength + " bytes) too large, storing in memory only");
SqueakDBFake.bigFiles[filename] = buffer;
} else {
var string = Squeak.bytesAsString(new Uint8Array(buffer));
if (typeof LZString == "object") {
var compressed = LZString.compressToUTF16(string);
localStorage["squeak-file.lz:" + filename] = compressed;
delete localStorage["squeak-file:" + filename];
} else {
localStorage["squeak-file:" + filename] = string;
}
}
var req = {};
setTimeout(function(){if (req.onsuccess) req.onsuccess()}, 0);
return req;
},
delete: function(filename) {
delete localStorage["squeak-file:" + filename];
delete localStorage["squeak-file.lz:" + filename];
delete SqueakDBFake.bigFiles[filename];
var req = {};
setTimeout(function(){if (req.onsuccess) req.onsuccess()}, 0);
return req;
},
openCursor: function() {
var req = {};
setTimeout(function(){if (req.onsuccess) req.onsuccess({target: req})}, 0);
return req;
},
}
}
return SqueakDBFake;
},
fileGet: function(filepath, thenDo, errorDo) {
if (!errorDo) errorDo = function(err) { console.log(err) };
var path = this.splitFilePath(filepath);
if (!path.basename) return errorDo("Invalid path: " + filepath);
// if we have been writing to memory, return that version
if (window.SqueakDBFake && SqueakDBFake.bigFiles[path.fullname])
return thenDo(SqueakDBFake.bigFiles[path.fullname]);
this.dbTransaction("readonly", "get " + filepath, function(fileStore) {
var getReq = fileStore.get(path.fullname);
getReq.onerror = function(e) { errorDo(e.target.error.name) };
getReq.onsuccess = function(e) {
if (this.result !== undefined) return thenDo(this.result);
// might be a template
Squeak.fetchTemplateFile(path.fullname,
function gotTemplate(template) {thenDo(template)},
function noTemplate() {
// if no indexedDB then we have checked fake db already
if (typeof indexedDB == "undefined") return errorDo("file not found: " + path.fullname);
// fall back on fake db, may be file is there
var fakeReq = Squeak.dbFake().get(path.fullname);
fakeReq.onerror = function(e) { errorDo("file not found: " + path.fullname) };
fakeReq.onsuccess = function(e) { thenDo(this.result); }
});
};
});
},
filePut: function(filepath, contents, optSuccess) {
// store file, return dir entry if successful
var path = this.splitFilePath(filepath); if (!path.basename) return null;
var directory = this.dirList(path.dirname); if (!directory) return null;
// get or create entry
var entry = directory[path.basename],
now = this.totalSeconds();
if (!entry) { // new file
entry = [/*name*/ path.basename, /*ctime*/ now, /*mtime*/ 0, /*dir*/ false, /*size*/ 0];
directory[path.basename] = entry;
} else if (entry[3]) // is a directory
return null;
// update directory entry
entry[2] = now; // modification time
entry[4] = contents.byteLength || contents.length || 0;
localStorage["squeak:" + path.dirname] = JSON.stringify(directory);
// put file contents (async)
this.dbTransaction("readwrite", "put " + filepath,
function(fileStore) {
fileStore.put(contents, path.fullname);
},
function transactionComplete() {
if (optSuccess) optSuccess();
});
return entry;
},
fileDelete: function(filepath, entryOnly) {
var path = this.splitFilePath(filepath); if (!path.basename) return false;
var directory = this.dirList(path.dirname); if (!directory) return false;
var entry = directory[path.basename]; if (!entry || entry[3]) return false; // not found or is a directory
// delete entry from directory
delete directory[path.basename];
localStorage["squeak:" + path.dirname] = JSON.stringify(directory);
if (entryOnly) return true;
// delete file contents (async)
this.dbTransaction("readwrite", "delete " + filepath, function(fileStore) {
fileStore.delete(path.fullname);
});
return true;
},
fileRename: function(from, to) {
var oldpath = this.splitFilePath(from); if (!oldpath.basename) return false;
var newpath = this.splitFilePath(to); if (!newpath.basename) return false;
var olddir = this.dirList(oldpath.dirname); if (!olddir) return false;
var entry = olddir[oldpath.basename]; if (!entry || entry[3]) return false; // not found or is a directory
var samedir = oldpath.dirname == newpath.dirname;
var newdir = samedir ? olddir : this.dirList(newpath.dirname); if (!newdir) return false;
if (newdir[newpath.basename]) return false; // exists already
delete olddir[oldpath.basename]; // delete old entry
entry[0] = newpath.basename; // rename entry
newdir[newpath.basename] = entry; // add new entry
localStorage["squeak:" + newpath.dirname] = JSON.stringify(newdir);
if (!samedir) localStorage["squeak:" + oldpath.dirname] = JSON.stringify(olddir);
// move file contents (async)
this.fileGet(oldpath.fullname,
function success(contents) {
this.dbTransaction("readwrite", "rename " + oldpath.fullname + " to " + newpath.fullname, function(fileStore) {
fileStore.delete(oldpath.fullname);
fileStore.put(contents, newpath.fullname);
});
}.bind(this),
function error(msg) {
console.log("File rename failed: " + msg);
}.bind(this));
return true;
},
fileExists: function(filepath) {
var path = this.splitFilePath(filepath); if (!path.basename) return false;
var directory = this.dirList(path.dirname); if (!directory) return false;
var entry = directory[path.basename]; if (!entry || entry[3]) return false; // not found or is a directory
return true;
},
dirCreate: function(dirpath, withParents) {
var path = this.splitFilePath(dirpath); if (!path.basename) return false;
if (withParents && !localStorage["squeak:" + path.dirname]) Squeak.dirCreate(path.dirname, true);
var directory = this.dirList(path.dirname); if (!directory) return false;
if (directory[path.basename]) return false;
var now = this.totalSeconds(),
entry = [/*name*/ path.basename, /*ctime*/ now, /*mtime*/ now, /*dir*/ true, /*size*/ 0];
directory[path.basename] = entry;
localStorage["squeak:" + path.fullname] = JSON.stringify({});
localStorage["squeak:" + path.dirname] = JSON.stringify(directory);
return true;
},
dirDelete: function(dirpath) {
var path = this.splitFilePath(dirpath); if (!path.basename) return false;
var directory = this.dirList(path.dirname); if (!directory) return false;
if (!directory[path.basename]) return false;
var children = this.dirList(path.fullname);
if (!children) return false;
for (var child in children) return false; // not empty
// delete from parent
delete directory[path.basename];
localStorage["squeak:" + path.dirname] = JSON.stringify(directory);
// delete itself
delete localStorage["squeak:" + path.fullname];
return true;
},
dirList: function(dirpath, includeTemplates) {
// return directory entries or null
var path = this.splitFilePath(dirpath),
localEntries = localStorage["squeak:" + path.fullname],
template = includeTemplates && localStorage["squeak-template:" + path.fullname];
function addEntries(dir, entries) {
for (var key in entries) {
if (entries.hasOwnProperty(key)) {
var entry = entries[key];
dir[entry[0]] = entry;
}
}
}
if (localEntries || template) {
// local entries override templates
var dir = {};
if (template) addEntries(dir, JSON.parse(template).entries);
if (localEntries) addEntries(dir, JSON.parse(localEntries));
return dir;
}
if (path.fullname == "/") return {};
return null;
},
splitFilePath: function(filepath) {
if (filepath[0] !== '/') filepath = '/' + filepath;
filepath = filepath.replace(/\/\//ig, '/'); // replace double-slashes
var matches = filepath.match(/(.*)\/(.*)/),
dirname = matches[1].length ? matches[1] : '/',
basename = matches[2].length ? matches[2] : null;
return {fullname: filepath, dirname: dirname, basename: basename};
},
flushFile: function(file) {
if (file.modified) {
var buffer = file.contents.buffer;
if (buffer.byteLength !== file.size) {
buffer = new ArrayBuffer(file.size);
(new Uint8Array(buffer)).set(file.contents.subarray(0, file.size));
}
Squeak.filePut(file.name, buffer);
// if (/SqueakDebug.log/.test(file.name)) {
// var chars = Squeak.bytesAsString(new Uint8Array(buffer));
// console.warn(chars.replace(/\r/g, '\n'));
// }
file.modified = false;
}
},
flushAllFiles: function() {
if (typeof SqueakFiles == 'undefined') return;
for (var name in SqueakFiles)
this.flushFile(SqueakFiles[name]);
},
closeAllFiles: function() {
// close the files held open in memory
Squeak.flushAllFiles();
delete window.SqueakFiles;
},
fetchTemplateDir: function(path, url) {
// Called on app startup. Fetch url/sqindex.json and
// cache all subdirectory entries in localStorage.
// File contents is only fetched on demand
path = Squeak.splitFilePath(path).fullname;
function ensureTemplateParent(template) {
var path = Squeak.splitFilePath(template);
if (path.dirname !== "/") ensureTemplateParent(path.dirname);
var template = JSON.parse(localStorage["squeak-template:" + path.dirname] || '{"entries": {}}');
if (!template.entries[path.basename]) {
var now = Squeak.totalSeconds();
template.entries[path.basename] = [path.basename, now, now, true, 0];
localStorage["squeak-template:" + path.dirname] = JSON.stringify(template);
}
}
function checkSubTemplates(path, url) {
var template = JSON.parse(localStorage["squeak-template:" + path]);
template.entries.forEach(function(entry) {
if (entry[3]) Squeak.fetchTemplateDir(path + "/" + entry[0], url + "/" + entry[0]);
});
}
if (localStorage["squeak-template:" + path]) {
checkSubTemplates(path, url);
} else {
var index = url + "/sqindex.json";
var rq = new XMLHttpRequest();
rq.open('GET', index, true);
rq.onload = function(e) {
if (rq.status == 200) {
console.log("adding template " + path);
ensureTemplateParent(path);
localStorage["squeak-template:" + path] = '{"url": ' + JSON.stringify(url) + ', "entries": ' + rq.response + '}';
checkSubTemplates(path, url);
}
else rq.onerror(rq.statusText);
};
rq.onerror = function(e) {
console.log("cannot load template index " + index);
}
rq.send();
}
},
fetchTemplateFile: function(path, ifFound, ifNotFound) {
path = Squeak.splitFilePath(path);
var template = localStorage["squeak-template:" + path.dirname];
if (!template) return ifNotFound();
var url = JSON.parse(template).url;
if (!url) return ifNotFound();
url += "/" + path.basename;
var rq = new XMLHttpRequest();
rq.open("get", url, true);
rq.responseType = "arraybuffer";
rq.timeout = 30000;
rq.onreadystatechange = function() {
if (this.readyState != this.DONE) return;
if (this.status == 200) {
var buffer = this.response;
console.log("Got " + buffer.byteLength + " bytes from " + url);
Squeak.dirCreate(path.dirname, true);
Squeak.filePut(path.fullname, buffer);
ifFound(buffer);
} else {
alert("Download failed (" + this.status + ") " + url);
ifNotFound();
}
}
console.log("Fetching " + url);
rq.send();
},
},
"audio", {
startAudioOut: function() {
if (!this.audioOutContext) {
var ctxProto = window.AudioContext || window.webkitAudioContext
|| window.mozAudioContext || window.msAudioContext;
this.audioOutContext = ctxProto && new ctxProto();
}
return this.audioOutContext;
},
startAudioIn: function(thenDo, errorDo) {
if (this.audioInContext) {
this.audioInSource.disconnect();
return thenDo(this.audioInContext, this.audioInSource);
}
navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia
|| navigator.mozGetUserMedia || navigator.msGetUserMedia;
if (!navigator.getUserMedia) return errorDo("test: audio input not supported");
navigator.getUserMedia({audio: true, toString: function() {return "audio"}},
function onSuccess(stream) {
var ctxProto = window.AudioContext || window.webkitAudioContext
|| window.mozAudioContext || window.msAudioContext;
this.audioInContext = ctxProto && new ctxProto();
this.audioInSource = this.audioInContext.createMediaStreamSource(stream);
thenDo(this.audioInContext, this.audioInSource);
},
function onError() {
errorDo("cannot access microphone");
});
},
stopAudio: function() {
if (this.audioInSource)
this.audioInSource.disconnect();
},
},
"time", {
Epoch: Date.UTC(1901,0,1) + (new Date()).getTimezoneOffset()*60000, // local timezone
EpochUTC: Date.UTC(1901,0,1),
totalSeconds: function() {
// seconds since 1901-01-01, local time
return Math.floor((Date.now() - Squeak.Epoch) / 1000);
},
},
"utils", {
bytesAsString: function(bytes) {
var chars = [];
for (var i = 0; i < bytes.length; i++)
chars.push(String.fromCharCode(bytes[i]));
return chars.join('');
},
});
Object.subclass('Squeak.Image',
'about', {
about: function() {
/*
Object Format
=============
Each Squeak object is a Squeak.Object instance, only SmallIntegers are JS numbers.
Instance variables/fields reference other objects directly via the "pointers" property.
{
sqClass: reference to class object
format: format integer as in Squeak oop header
hash: identity hash integer
pointers: (optional) Array referencing inst vars + indexable fields
words: (optional) Array of numbers (words)
bytes: (optional) Array of numbers (bytes)
float: (optional) float value if this is a Float object
isNil: (optional) true if this is the nil object
isTrue: (optional) true if this is the true object
isFalse: (optional) true if this is the false object
isFloat: (optional) true if this is a Float object
isFloatClass: (optional) true if this is the Float class
isCompact: (optional) true if this is a compact class
oop: identifies this object in a snapshot (assigned on GC, new space object oops are negative)
mark: boolean (used only during GC, otherwise false)
nextObject: linked list of objects in old space (new space objects do not have this yet)
}
Object Table
============
There is no actual object table. Instead, objects in old space are a linked list.
New objects are only referenced by other objects' pointers, and thus can be garbage-collected
at any time by the Javascript GC.
Weak references are only finalized during a full GC.
*/
}
},
'initializing', {
initialize: function(name) {
this.totalMemory = 100000000;
this.name = name;
this.gcCount = 0;
this.gcTenured = 0;
this.gcMilliseconds = 0;
this.allocationCount = 0;
this.oldSpaceCount = 0;
this.newSpaceCount = 0;
this.hasNewInstances = {};
},
readFromBuffer: function(arraybuffer, thenDo, progressDo) {
console.log('squeak: reading ' + this.name + ' (' + arraybuffer.byteLength + ' bytes)');
this.startupTime = Date.now();
var data = new DataView(arraybuffer),
littleEndian = false,
pos = 0;
var readWord = function() {
var int = data.getUint32(pos, littleEndian);
pos += 4;
return int;
};
var readBits = function(nWords, format) {
if (format < 5) { // pointers (do endian conversion)
var oops = [];
while (oops.length < nWords)
oops.push(readWord());
return oops;
} else { // words (no endian conversion yet)
var bits = new Uint32Array(arraybuffer, pos, nWords);
pos += nWords*4;
return bits;
}
};
// read version and determine endianness
var versions = [6501, 6502, 6504, 6505, 68000, 68002, 68003],
version = 0,
fileHeaderSize = 0;
while (true) { // try all four endianness + header combos
littleEndian = !littleEndian;
pos = fileHeaderSize;
version = readWord();
if (versions.indexOf(version) >= 0) break;
if (!littleEndian) fileHeaderSize += 512;
if (fileHeaderSize > 512) throw Error("bad image version");
};
this.version = version;
var nativeFloats = [6505, 68003].indexOf(version) >= 0;
this.hasClosures = [6504, 6505, 68002, 68003].indexOf(version) >= 0;
if (version >= 68000) throw Error("64 bit images not supported yet");
// parse image header
var imageHeaderSize = readWord();
var objectMemorySize = readWord(); //first unused location in heap
var oldBaseAddr = readWord(); //object memory base address of image
var specialObjectsOopInt = readWord(); //oop of array of special oops
this.lastHash = readWord(); //Should be loaded from, and saved to the image header
var savedWindowSize = readWord();
var fullScreenFlag = readWord();
var extraVMMemory = readWord();
pos += imageHeaderSize - (9 * 4); //skip to end of header
// read objects
var prevObj;
var oopMap = {};
var headerSize = fileHeaderSize + imageHeaderSize;
while (pos < headerSize + objectMemorySize) {
var nWords = 0;
var classInt = 0;
var header = readWord();
switch (header & Squeak.HeaderTypeMask) {
case Squeak.HeaderTypeSizeAndClass:
nWords = header >> 2;
classInt = readWord();
header = readWord();
break;
case Squeak.HeaderTypeClass:
classInt = header - Squeak.HeaderTypeClass;
header = readWord();
nWords = (header >> 2) & 63;
break;
case Squeak.HeaderTypeShort:
nWords = (header >> 2) & 63;
classInt = (header >> 12) & 31; //compact class index
//Note classInt<32 implies compact class index
break;
case Squeak.HeaderTypeFree:
throw Error("Unexpected free block");
}
nWords--; //length includes base header which we have already read
var oop = pos - 4 - headerSize, //0-rel byte oop of this object (base header)
format = (header>>8) & 15,
hash = (header>>17) & 4095,
bits = readBits(nWords, format);
var object = new Squeak.Object();
object.initFromImage(oop, classInt, format, hash, bits);
if (classInt < 32) object.hash |= 0x10000000; // see fixCompactOops()
if (prevObj) prevObj.nextObject = object;
this.oldSpaceCount++;
prevObj = object;
//oopMap is from old oops to actual objects
oopMap[oldBaseAddr + oop] = object;
}
this.firstOldObject = oopMap[oldBaseAddr+4];
this.lastOldObject = prevObj;
this.oldSpaceBytes = objectMemorySize;
//create proper objects by mapping via oopMap
var splObs = oopMap[specialObjectsOopInt];
var compactClasses = oopMap[splObs.bits[Squeak.splOb_CompactClasses]].bits;
var floatClass = oopMap[splObs.bits[Squeak.splOb_ClassFloat]];
var obj = this.firstOldObject,
done = 0,
self = this;
function mapSomeObjects() {
if (obj) {
var stop = done + (self.oldSpaceCount / 10 | 0); // do it in 10 chunks
while (obj && done < stop) {
obj.installFromImage(oopMap, compactClasses, floatClass, littleEndian, nativeFloats);
obj = obj.nextObject;
done++;
}
if (progressDo) progressDo(done / self.oldSpaceCount);
return true; // do more
} else { // done
self.specialObjectsArray = splObs;
self.decorateKnownObjects();
self.fixCompiledMethods();
self.fixCompactOops();
return false; // don't do more
}
};
function mapSomeObjectsAsync() {
if (mapSomeObjects()) {
window.setTimeout(mapSomeObjectsAsync, 0);
} else {
if (thenDo) thenDo();
}
};
if (!progressDo) {
while (mapSomeObjects()); // do it synchronously
if (thenDo) thenDo();
} else {
window.setTimeout(mapSomeObjectsAsync, 0);
}
},
decorateKnownObjects: function() {
var splObjs = this.specialObjectsArray.pointers;
splObjs[Squeak.splOb_NilObject].isNil = true;
splObjs[Squeak.splOb_TrueObject].isTrue = true;
splObjs[Squeak.splOb_FalseObject].isFalse = true;
splObjs[Squeak.splOb_ClassFloat].isFloatClass = true;
this.compactClasses = this.specialObjectsArray.pointers[Squeak.splOb_CompactClasses].pointers;
for (var i = 0; i < this.compactClasses.length; i++)
if (!this.compactClasses[i].isNil)
this.compactClasses[i].isCompact = true;
if (!Number.prototype.sqInstName)
Object.defineProperty(Number.prototype, 'sqInstName', {
enumerable: false,
value: function() { return this.toString() }
});
},
fixCompactOops: function() {
// instances of compact classes might have been saved with a non-compact header
// fix their oops here so validation succeeds later
var obj = this.firstOldObject,
adjust = 0;
while (obj) {
var hadCompactHeader = obj.hash > 0x0FFFFFFF,
mightBeCompact = !!obj.sqClass.isCompact;
if (hadCompactHeader !== mightBeCompact) {
var isCompact = obj.snapshotSize().header === 0;
if (hadCompactHeader !== isCompact) {
adjust += isCompact ? -4 : 4;
}
}
obj.hash &= 0x0FFFFFFF;
obj.oop += adjust;
obj = obj.nextObject;
}
this.oldSpaceBytes += adjust;
},
fixCompiledMethods: function() {
// in the 6501 pre-release image, some CompiledMethods
// do not have the proper class
if (this.version >= 6502) return;
var obj = this.firstOldObject,
compiledMethodClass = this.specialObjectsArray.pointers[Squeak.splOb_ClassCompiledMethod];
while (obj) {
if (obj.format >= 12) obj.sqClass = compiledMethodClass;
obj = obj.nextObject;
}
},
},
'garbage collection', {
partialGC: function() {
// no partial GC needed since new space uses the Javascript GC
return this.totalMemory - this.oldSpaceBytes;
},
fullGC: function(reason) {
// Collect garbage and return first tenured object (to support object enumeration)
// Old space is a linked list of objects - each object has an "nextObject" reference.
// New space objects do not have that pointer, they are garbage-collected by JavaScript.
// But they have an allocation id so the survivors can be ordered on tenure.
// The "nextObject" references are created by collecting all new objects,
// sorting them by id, and then linking them into old space.
this.vm.addMessage("fullGC: " + reason);
var start = Date.now();