-
Notifications
You must be signed in to change notification settings - Fork 6
/
snapin8r.js
736 lines (698 loc) · 26.6 KB
/
snapin8r.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
/* Snapin8r
Snapin8r.js
Hardmath123 - 2013
*/
! function () {
// Block libraries
// Copied from the decompiled Scratch player Flash source
var blib = {};
! function (s8) {
s8.BLOCK_LIBRARY = {
"forward:": "forward",
"turnRight:": "turn",
"turnLeft:": "turnLeft",
"heading:": "setHeading",
"pointTowards:": "doFaceTowards",
"gotoX:y:": "gotoXY",
"gotoSpriteOrMouse:": "doGotoObject",
"glideSecs:toX:y:elapsed:from:": "doGlide",
"changeXposBy:": "changeXPosition",
"xpos:": "setXPosition",
"changeYposBy:": "changeYPosition",
"ypos:": "setYPosition",
"bounceOffEdge": "bounceOffEdge",
// "setRotationStyle":"",
"xpos": "xPosition",
"ypos": "yPosition",
"heading": "direction",
"say:duration:elapsed:from:": "doSayFor",
"say:": "bubble",
"think:duration:elapsed:from:": "doThinkFor",
"think:": "doThink",
"show": "show",
"hide": "hide",
"lookLike:": "doSwitchToCostume",
"nextCostume": "doWearNextCostume",
"startScene": "doSwitchToCostume",
"changeGraphicEffect:by:": "changeEffect",
"setGraphicEffect:to:": "setEffect",
"filterReset": "clearEffects",
"changeSizeBy:": "changeScale",
"setSizeTo:": "setScale",
"comeToFront": "comeToFront",
"goBackByLayers:": "goBack",
"costumeIndex": "getCostumeIdx",
// "sceneName":"",
"scale": "getScale",
// "startScene":"",
// "startSceneAndWait":"",
// "nextScene":"",
// "changeGraphicEffect:by:":"changeEffect",
// "setGraphicEffect:to:":"setEffect",
// "filterReset":"clearEffects",
// "setVideoState":"",
// "setVideoTransparency":"",
// "sceneName":"",
"backgroundIndex": "getCostumeIdx",
"playSound:": "playSound",
"doPlaySoundAndWait": "doPlaySoundUntilDone",
"stopAllSounds": "doStopAllSounds",
// "playDrum":"",
"rest:elapsed:from:": "doRest",
"noteOn:duration:elapsed:from:": "doPlayNote",
// "instrument:":"",
// "changeVolumeBy:":"",
// "setVolumeTo:":"",
// "volume":"",
"changeTempoBy:": "doChangeTempo",
"setTempoTo:": "doSetTempo",
"tempo": "getTempo",
"clearPenTrails": "clear",
"stampCostume": "doStamp",
"putPenDown": "down",
"putPenUp": "up",
"penColor:": "setColor",
"changePenHueBy:": "changeHue",
"setPenHueTo:": "setHue",
"changePenShadeBy:": "changeBrightness",
"setPenShadeTo:": "setBrightness",
"changePenSizeBy:": "changeSize",
"penSize:": "setSize",
// "clearPenTrails":"",
"whenGreenFlag": "receiveGo",
"whenKeyPressed": "receiveKey",
"whenClicked": "receiveClick",
"whenSceneStarts": "receiveMessage",
// "whenSensorGreaterThan":"",
"whenIReceive": "receiveMessage",
"broadcast:": "doBroadcast",
"doBroadcastAndWait": "doBroadcastAndWait",
"wait:elapsed:from:": "doWait",
"doRepeat": "doRepeat",
"doForever": "doForever",
"doIf": "doIf",
"doIfElse": "doIfElse",
"doWaitUntil": "doWaitUntil",
"doUntil": "doUntil",
"stopScripts": "doStop",
"whenCloned": "receiveOnClone",
"createCloneOf": "createClone",
"deleteClone": "removeClone",
// "wait:elapsed:from:":"",
// "doRepeat":"",
// "doForever":"",
// "doIf":"",
// "doIfElse":"",
// "doWaitUntil":"",
// "doUntil":"",
// "stopScripts":"",
// "createCloneOf":"",
"touching:": "reportTouchingObject",
"touchingColor:": "reportTouchingColor",
"color:sees:": "reportColorIsTouchingColor",
"distanceTo:": "reportDistanceTo",
"doAsk": "doAsk",
"answer": "reportLastAnswer",
"keyPressed:": "reportKeyPressed",
"mousePressed": "reportMouseDown",
"mouseX": "reportMouseX",
"mouseY": "reportMouseY",
// "soundLevel":"",
// "senseVideoMotion":"",
"timer": "reportTimer",
"timerReset": "doResetTimer",
"getAttribute:of:": "reportAttributeOf",
"timeAndDate":"reportDate",
// "timestamp":"",
// "getUserId":"",
// "doAsk":"",
// "answer":"",
// "keyPressed:":"",
// "mousePressed":"",
// "mouseX":"",
// "mouseY":"",
// "soundLevel":"",
// "senseVideoMotion":"",
// "timer":"",
// "timerReset":"",
// "getAttribute:of:":"",
// "timeAndDate":"",
// "timestamp":"",
// "getUserId":"",
"+": "reportSum",
"-": "reportDifference",
"*": "reportProduct",
"/": "reportQuotient",
"randomFrom:to:": "reportRandom",
"<": "reportLessThan",
"=": "reportEquals",
">": "reportGreaterThan",
"&": "reportAnd",
"|": "reportOr",
"not": "reportNot",
"concatenate:with:": "reportJoinWords",
"letter:of:": "reportLetter",
"stringLength:": "reportStringSize",
"%": "reportModulus",
"rounded": "reportRound",
"computeFunction:of:": "reportMonadic",
"readVar": "",
"setVar:to:": "doSetVar",
"changeVar:by:": "doChangeVar",
"showVariable:": "doShowVar",
"hideVariable:": "doHideVar",
"append:toList:": "doAddToList",
"deleteLine:ofList:": "doDeleteFromList",
"insert:at:ofList:": "doInsertInList",
"setLine:ofList:to:": "doReplaceInList",
"getLine:ofList:": "reportListItem",
"lineCountOfList:": "reportListLength",
"list:contains:": "reportListContainsItem",
"showList:": "doShowVar",
"hideList:": "doHideVar",
// "whenSensorConnected":"",
// "sensorPressed:":"",
// "sensor:":"",
// "motorOnFor:elapsed:from:":"",
// "allMotorsOn":"",
// "allMotorsOff":"",
// "startMotorPower:":"",
// "setMotorDirection:":"",
// "whenDistanceLessThan":"",
// "whenTiltIs":"",
// "wedoDistance":"",
// "wedoTilt":"",
// "midiNoteOn":"",
// "midiNoteOff":"",
// "midiPitchBend":"",
// "midiController":"",
// "midiProgram":"",
// "midiReset":"",
// "midiUseJavaSynth":"",
// "midiTime":"",
// "drum:duration:elapsed:from:":"",
// "midiInstrument:":"",
// "isLoud":"",
// "abs":"",
// "sqrt":"",
"doReturn": "doReport",
"stopAll": "doStopAll",
// "showBackground:":"",
// "nextBackground":"",
// "doForeverIf":"",
// "COUNT":"",
// "COUNT":"",
// "CLR_COUNT":"",
// "INCR_COUNT":"",
// "doForLoop":"",
// "doWhile":"",
"warpSpeed": "doWarp"
// "scrollRight":"",
// "scrollUp":"",
// "scrollAlign":"",
// "xScroll":"",
// "yScroll":"",
// "hideAll":"",
};
s8.C_INPUTS = {
"doRepeat": [1],
"doForever": [0],
"doIf": [1],
"doIfElse": [1, 2],
"doUntil": [1]
};
s8.LIST_INPUTS = {
"append:toList:": [1],
"deleteLine:ofList:": [1],
"insert:at:ofList:": [2],
"setLine:ofList:to:": [1],
"getLine:ofList:": [1],
"lineCountOfList:": [0],
"list:contains:": [0]
};
s8.COLOR_INPUTS = {
"penColor:": [0],
"touchingColor:": [0],
"color:sees:": [0, 1]
};
s8.DD_INPUTS = {
"reportMonadic": [0],
"gotoSpriteOrMouse": [0]
};
}(blib);
// XMLData is an abstraction of XML-style data
function XMLData(tag_name, attribs, content) {
this.tag_name = tag_name || "null";
this.attribs = attribs || [];
this.content = content || [];
}
XMLData.prototype.toString = function () {
var result = "";
result += "<";
result += this.tag_name;
this.attribs.forEach(function (attribute) {
result += " ";
result += attribute[0];
result += "=";
result += "\"";
result += attribute[1];
result += "\"";
});
result += ">";
if (this.content instanceof Array) {
this.content.forEach(function (attribute) {
result += attribute.toString();
});
} else {
result += this.content;
}
result += "</";
result += this.tag_name;
result += ">";
return result;
};
XMLData.prototype.property = function (name, val) {
// convenience method
this.attribs.push([name, val]);
};
// Custom error class so that Snap! can catch conversion issues
function ConversionError(m) {
this.name = "ConversionError";
this.message = m;
}
ConversionError.prototype = new Error();
ConversionError.prototype.constructor = ConversionError;
function extract_costume(zip, costume) {
var f = zip.file(
costume.baseLayerID + "." + costume.baseLayerMD5.split(".")[1]
).asUint8Array();
var old_str = "";
for (var i=0; i<f.length; i++) {
old_str += String.fromCharCode(f[i]);
}
var str = btoa(
//String.fromCharCode.apply(null, f)
old_str
);
var ext = costume.baseLayerMD5.split(".")[1];
ext = ext === "svg" ? "svg+xml" : ext;
return "data:image/" + ext + ";base64," + str;
}
function convert_costume(zip, costume) {
var cos = extract_costume(zip, costume);
var result = new XMLData("costume");
result.property("name", costume["costumeName"]);
result.property("center-x", costume["rotationCenterX"]);
result.property("center-y", costume["rotationCenterY"]);
result.property("image", cos);
return result;
}
function convert_variables(scriptable) {
var result = new XMLData("variables");
if (scriptable["variables"]) {
scriptable["variables"].forEach(
function (v) {
result.content.push(
new XMLData(
"variable", [
["name", v["name"]]
],
new XMLData("l", null, v["value"])
)
);
}
);
}
if (scriptable["lists"]) {
scriptable["lists"].forEach(
function (l) {
var lxml = new XMLData("list");
l["contents"].forEach(
function (item) {
var itemxml = new XMLData(
"item",
null,
new XMLData("l", null, item)
);
lxml.content.push(itemxml);
}
);
result.content.push(
new XMLData(
"variable", [
["name", l["listName"]]
],
lxml
)
);
}
);
}
return result;
}
function extract_sound(zip, sound) {
var f = zip.file(
sound.soundID + "." + sound.md5.split(".")[1]
).asUint8Array();
var old_str = "";
for (var i=0; i<f.length; i++) {
old_str += String.fromCharCode(f[i]);
}
var str = btoa(
//String.fromCharCode.apply(null, f)
old_str
);
return "data:audio/" + sound.md5.split(".")[1] + ";base64," + str;
}
function convert_script(script, objName, ignoreCoords) {
var result = new XMLData("script");
var blocks;
if (!ignoreCoords) {
result.property("x", script[0]);
result.property("y", script[1]);
blocks = script[2];
} else {
blocks = script;
}
if (blocks) {
blocks.forEach(
function (blk) {
result.content.push(convert_block(blk, objName));
}
);
}
return result;
}
function convert_block(blk, objName) {
var proc = blk[0];
if (proc === "readVariable" || proc === "getParam") {
return new XMLData("block", [
["var", blk[1]]
]);
}
var mainblk, args, arglist;
if (proc === "call") {
mainblk = new XMLData(
"custom-block", [
["s", blk[1]],
["scope", objName]
]
);
args = blk.slice(2);
} else {
mainblk = new XMLData("block");
mainblk.property("s", blib.BLOCK_LIBRARY[proc] || !function() {
throw new ConversionError("Unknown spec "+proc);
}());
args = blk.slice(1);
}
if (proc === "concatenate:with:") {
arglist = new XMLData("list");
}
for (var i = 0; i < args.length; i++) {
var arg = args[i];
if (arg === "_mouse_") arg = new XMLData("option", null, "mouse-pointer");
if (arg === "_edge_") arg = new XMLData("option", null, "edge");
if (arg === "_myself_") arg = new XMLData("option", null, "myself");
if (arg === "_stage_") arg = "Stage";
if (arg === "e^") arg = "e ^";
if (arg === false) {
mainblk.content.push(new XMLData("l"));
continue;
}
if (proc === "getAttribute:of:") {
if (arg === "backdrop name") arg = "costume name";
if (arg === "backdrop #") arg = "costume #";
if (["volume", "x position", "y position", "direction", "costume #", "costume name"].indexOf(arg) !== -1) {
arg = new XMLData("option", null, arg).toString();
console.log(arg);
}
mainblk.content.push(new XMLData("l", null, arg));
} else if (blib.C_INPUTS[proc] && blib.C_INPUTS[proc].indexOf(i) !== -1) {
mainblk.content.push(convert_script(arg, objName, true));
} else if (blib.LIST_INPUTS[proc] && blib.LIST_INPUTS[proc].indexOf(i) !== -1) {
mainblk.content.push(new XMLData("block", [
["var", arg]
]));
} else if (blib.DD_INPUTS[proc] && blib.DD_INPUTS[proc].indexOf(i) !== -1) {
mainblk.content.push(new XMLData("option", null, arg));
} else if (proc === "stopScripts") {
if (arg === "all") {
return new XMLData("block", [
["s", "doStopAll"]
]);
}
if (arg === "this script") {
return new XMLData("block", [
["s", "doStop"]
]);
}
if (arg === "other scripts in sprite" || arg === "other scripts in stage") {
return new XMLData("block", [
["s", "doStopOthers"],
],
[new XMLData("l", null, new XMLData("option", null, "other scripts in sprite"))]
);
}
throw new ConversionError("Snap! can't stop all scripts except the current one.");
} else if (blib.COLOR_INPUTS[proc] && blib.COLOR_INPUTS[proc].indexOf(i) !== -1) {
var h = Math.abs(parseInt(arg)).toString(16);
while (h.length < 6) {
h = "0" + h;
}
var c1 = parseInt(h[0], 16) * 16 + parseInt(h[1], 16);
var c2 = parseInt(h[2], 16) * 16 + parseInt(h[3], 16);
var c3 = parseInt(h[4], 16) * 16 + parseInt(h[5], 16);
mainblk.content.push(new XMLData("color", null, c1 + "," + c2 + "," + c3));
} else {
if (proc === "concatenate:with:") {
if (arg instanceof Array) {
arglist.content.push(convert_block(arg, objName));
} else {
if (arg === 0) {
arg = "0";
}
arglist.content.push(new XMLData("l", null, arg));
}
} else {
if (arg instanceof Array) {
mainblk.content.push(convert_block(arg, objName));
} else {
if (arg === 0) {
arg = "0";
}
mainblk.content.push(new XMLData("l", null, arg));
}
}
}
}
if (proc === "concatenate:with:") {
mainblk.content.push(arglist);
}
return mainblk;
}
function convert_scriptable(data, zip, stage) {
var result = new XMLData(stage ? "stage" : "sprite");
result.property("name", data["objName"]);
result.property("costume", data["currentCostumeIndex"] + 1);
if (data["tempoBPM"]) {
result.property("tempo", data["tempoBPM"]);
}
if (stage) {
result.property("pentrails", "");
result.property("threadsafe", "false");
} else {
result.property("x", data["scratchX"]);
result.property("y", data["scratchY"]);
result.property("heading", data["direction"]);
result.property("scale", data["scale"]);
}
var blocksXML = new XMLData("blocks");
var scriptsXML = new XMLData("scripts");
if (data["scripts"]) {
data["scripts"].forEach(
function (script) {
if (script[2][0][0] === "procDef") {
// Custom block
// [Xpos, Ypos, [procdef, name, inputs, defaults, turbo]]
// TODO
var label = script[2][0][1];
var inputs = script[2][0][2];
var defaults = script[2][0][3];
var turbo = script[2][0][4];
var label_new = "";
var inputs_new = [];
var split = label.split("%");
for (var i = 0; i < split.length; i++) {
if (i === 0) {
label_new = split[i];
} else {
var ld = {
"n": "%n",
"b": "%b",
"s": "%s"
};
label_new += "%'" + inputs[i - 1] + "'";
label_new += split[i].slice(1);
inputs_new.push(
new XMLData(
"input", [
["type", ld[split[i][0]]]
],
defaults[i - 1]
)
);
}
}
var scr = convert_script(script[2].slice(1), data["objName"], true);
if (turbo) {
var rbscr = new XMLData(
"script",
null,
new XMLData(
"block", [
["s", "doWarp"]
],
scr
)
);
} else {
var rbscr = scr;
}
var def = new XMLData(
"block-definition", [
["s", label_new],
["category", "other"],
["type", "command"]
], [new XMLData("inputs", null, inputs_new), rbscr]
);
blocksXML.content.push(def);
} else {
scriptsXML.content.push(convert_script(script, data["objName"]));
}
}
);
}
result.content.push(blocksXML);
result.content.push(scriptsXML);
if (data["children"]) {
var children = new XMLData("sprites");
data["children"].forEach(
function (child) {
if (child["objName"]) {
// Sprite
children.content.push(convert_scriptable(child, zip));
} else {
// Watcher
var wat = new XMLData("watcher");
wat.property("var", child["param"]);
wat.property(
"style", ["normal", "large", "slider"][child["mode"] - 1]
);
wat.property("color", "243,118,29");
wat.property("x", child["x"]);
wat.property("y", child["y"]);
children.content.push(wat);
}
}
);
result.content.push(children);
}
if (data["costumes"]) {
var costumes = new XMLData("costumes");
var costumeslist = new XMLData("list");
data["costumes"].forEach(function (cos) {
costumeslist.content.push(
new XMLData("item", null, convert_costume(zip, cos))
);
});
costumes.content = costumeslist;
result.content.push(costumes);
}
if (data["sounds"]) {
var sounds = new XMLData("sounds");
var soundslist = new XMLData("list");
data["sounds"].forEach(function (snd) {
var soundxml = new XMLData("sound");
soundxml.property("name", snd["soundName"]);
soundxml.property("sound", extract_sound(zip, snd));
soundslist.content.push(
new XMLData("item", null, soundxml)
);
});
sounds.content = soundslist;
result.content.push(sounds);
}
var varks = new XMLData("variables");
if (!stage && (data["variables"] || data["lists"])) {
varks = convert_variables(data);
}
result.content.push(varks);
return result;
}
// Actual exported function
window.Snapin8r = function (zip, name) {
// Convert a zip object output by JSZip into an XML string for Snap!.
if (!zip.file("project.json")) {
throw new ConversionError("project.json does not exist.");
}
var json_data = zip.file("project.json").asText();
try {
json_data = JSON.parse(json_data);
} catch (SyntaxError) {
throw new ConversionError(
"Corrupted project.json (JSON parse error)"
);
}
var result = new XMLData("project");
result.property("name", name||"Untitled");
result.property("app", "Snapin8r");
result.property("version", "1");
result.content.push(new XMLData("notes", null, "Converted by Snapin8r."));
result.content.push(new XMLData("thumbnail", null, ""));
// global variables (special case)
var varks = new XMLData("variables");
if (json_data["variables"] || json_data["lists"]) {
varks = convert_variables(json_data);
}
result.content.push(varks);
result.content.push(convert_scriptable(json_data, zip, true));
return result.toString();
};
// Exports:
window.Snapin8r.blib = blib;
window.Snapin8r.XMLData = XMLData;
window.Snapin8r.ConversionError = ConversionError;
}();
if (window.IDE_Morph) { // I'm on Snap!--make some modifications
IDE_Morph.prototype.droppedBinary = function (anArrayBuffer, name) {
// dynamically load ypr->Snap!
var ypr = document.getElementById('ypr'),
myself = this,
suffix = name.substring(name.length - 3);
// @n I'm messing with your code
if (suffix.toLowerCase() !== 'ypr') {
// It's a ZIP. sb2 or zip.
var zip = new JSZip(anArrayBuffer);
myself.droppedText(Snapin8r(zip));
return;
}
function loadYPR (buffer, lbl) {
var reader = new sb.Reader(),
pname = lbl.split('.')[0]; // up to period
reader.onload = function (info) {
myself.droppedText(new sb.XMLWriter().write(pname, info));
};
reader.readYPR(new Uint8Array(buffer));
}
if (!ypr) {
ypr = document.createElement('script');
ypr.id = 'ypr';
ypr.onload = function () {loadYPR(anArrayBuffer, name); };
document.head.appendChild(ypr);
ypr.src = 'ypr.js';
} else {
loadYPR(anArrayBuffer, name);
}
};
}