forked from jmoenig/Snap
-
Notifications
You must be signed in to change notification settings - Fork 1
/
store.js
1713 lines (1550 loc) · 52.3 KB
/
store.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
/*
store.js
saving and loading Snap! projects
written by Jens Mönig
Copyright (C) 2013 by Jens Mönig
This file is part of Snap!.
Snap! is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of
the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
prerequisites:
--------------
needs morphic.js, xml.js, and most of Snap!'s other modules
hierarchy
---------
the following tree lists all constructors hierarchically,
indentation indicating inheritance. Refer to this list to get a
contextual overview:
XML_Serializer
SnapSerializer
credits
-------
Nathan Dinsmore contributed to the design and implemented a first
working version of a complete XMLSerializer. I have taken much of the
overall design and many of the functions and methods in this file from
Nathan's fine original prototype.
*/
/*global modules, XML_Element, XML_Serializer, VariableFrame, StageMorph,
SpriteMorph, WatcherMorph, Point, CustomBlockDefinition, Context,
ReporterBlockMorph, CommandBlockMorph, HatBlockMorph, RingMorph, contains,
detect, CustomCommandBlockMorph, CustomReporterBlockMorph, Color, List,
newCanvas, Costume, Sound, Audio, IDE_Morph, ScriptsMorph, BlockMorph,
ArgMorph, InputSlotMorph, TemplateSlotMorph, CommandSlotMorph,
FunctionSlotMorph, MultiArgMorph, ColorSlotMorph, nop, CommentMorph, isNil,
localize, sizeOf, ArgLabelMorph, SVG_Costume, MorphicPreferences,
SyntaxElementMorph*/
// Global stuff ////////////////////////////////////////////////////////
modules.store = '2013-April-25';
// XML_Serializer ///////////////////////////////////////////////////////
/*
I am an abstract protype for my heirs.
I manage object identities and keep track of circular data structures.
Objects are "touched" and a property named "serializationID" is added
to each, representing an index integer in the list, starting with 1.
*/
// XML_Serializer instance creation:
function XML_Serializer() {
this.contents = [];
this.media = [];
this.isCollectingMedia = false;
}
// XML_Serializer preferences settings:
XML_Serializer.prototype.idProperty = 'serializationID';
XML_Serializer.prototype.mediaIdProperty = 'serializationMediaID';
XML_Serializer.prototype.mediaDetectionProperty = 'isMedia';
XML_Serializer.prototype.version = 1; // increment on structural change
// XML_Serializer accessing:
XML_Serializer.prototype.serialize = function (object) {
// public: answer an XML string representing the given object
var xml;
this.flush(); // in case an error occurred in an earlier attempt
this.flushMedia();
xml = this.store(object);
this.flush();
return xml;
};
XML_Serializer.prototype.store = function (object, mediaID) {
// private - mediaID is optional
if (isNil(object) || !object.toXML) {
// unsupported type, to be checked before calling store()
// when debugging, be sure to throw an error at this point
return '';
}
if (this.isCollectingMedia && object[this.mediaDetectionProperty]) {
this.addMedia(object, mediaID);
return this.format(
'<ref mediaID="@"></ref>',
object[this.mediaIdProperty]
);
}
if (object[this.idProperty]) {
return this.format('<ref id="@"></ref>', object[this.idProperty]);
}
this.add(object);
return object.toXML(this, mediaID).replace(
'~',
this.format('id="@"', object[this.idProperty])
);
};
XML_Serializer.prototype.mediaXML = function () {
// answer a project's collected media module as XML
var xml = '<media>',
myself = this;
this.media.forEach(function (object) {
var str = object.toXML(myself).replace(
'~',
myself.format('mediaID="@"', object[myself.mediaIdProperty])
);
xml = xml + str;
});
return xml + '</media>';
};
XML_Serializer.prototype.add = function (object) {
// private - mark the object with a serializationID property and add it
if (object[this.idProperty]) { // already present
return -1;
}
this.contents.push(object);
object[this.idProperty] = this.contents.length;
return this.contents.length;
};
XML_Serializer.prototype.addMedia = function (object, mediaID) {
// private - mark the object with a serializationMediaID property
// and add it to media
// if a mediaID is given, take it, otherwise generate one
if (object[this.mediaIdProperty]) { // already present
return -1;
}
this.media.push(object);
if (mediaID) {
object[this.mediaIdProperty] = mediaID + '_' + object.name;
} else {
object[this.mediaIdProperty] = this.media.length;
}
return this.media.length;
};
XML_Serializer.prototype.at = function (integer) {
// private
return this.contents[integer - 1];
};
XML_Serializer.prototype.flush = function () {
// private - free all objects and empty my contents
var myself = this;
this.contents.forEach(function (obj) {
delete obj[myself.idProperty];
});
this.contents = [];
};
XML_Serializer.prototype.flushMedia = function () {
// private - free all media objects and empty my media
var myself = this;
if (this.media instanceof Array) {
this.media.forEach(function (obj) {
delete obj[myself.mediaIdProperty];
});
}
this.media = [];
};
// XML_Serializer formatting:
XML_Serializer.prototype.escape = XML_Element.prototype.escape;
XML_Serializer.prototype.unescape = XML_Element.prototype.unescape;
XML_Serializer.prototype.format = function (string) {
// private
var myself = this,
i = -1,
values = arguments,
value;
return string.replace(/[@$%]([\d]+)?/g, function (spec, index) {
index = parseInt(index, 10);
value = values[(isNaN(index) ? (i += 1) : index) + 1];
return spec === '@' ?
myself.escape(value)
: spec === '$' ?
myself.escape(value, true)
: value;
});
};
// XML_Serializer loading:
XML_Serializer.prototype.load = function (xmlString) {
// public - answer a new object which is represented by the given
// XML string.
nop(xmlString);
throw new Error(
'loading should be implemented in heir of XML_Serializer'
);
};
XML_Serializer.prototype.parse = function (xmlString) {
// private - answer an XML_Element representing the given XML String
var element = new XML_Element();
element.parseString(xmlString);
return element;
};
// SnapSerializer ////////////////////////////////////////////////////////////
var SnapSerializer;
// SnapSerializer inherits from XML_Serializer:
SnapSerializer.prototype = new XML_Serializer();
SnapSerializer.prototype.constructor = SnapSerializer;
SnapSerializer.uber = XML_Serializer.prototype;
// SnapSerializer constants:
SnapSerializer.prototype.app = 'Snap! 4.0, http://snap.berkeley.edu';
SnapSerializer.prototype.thumbnailSize = new Point(160, 120);
SnapSerializer.prototype.watcherLabels = {
xPosition: 'x position',
yPosition: 'y position',
direction: 'direction',
getScale: 'size',
getLastAnswer: 'answer',
getTimer: 'timer',
getCostumeIdx: 'costume #'
};
// SnapSerializer instance creation:
function SnapSerializer() {
this.init();
}
// SnapSerializer initialization:
SnapSerializer.prototype.init = function () {
this.project = {};
this.objects = {};
this.mediaDict = {};
};
// SnapSerializer saving:
XML_Serializer.prototype.mediaXML = function (name) {
// under construction....
var xml = '<media name="' +
(name || 'untitled') +
'" app="' + this.app +
'" version="' +
this.version +
'">',
myself = this;
this.media.forEach(function (object) {
var str = object.toXML(myself).replace(
'~',
myself.format('mediaID="@"', object[myself.mediaIdProperty])
);
xml = xml + str;
});
return xml + '</media>';
};
// SnapSerializer loading:
SnapSerializer.prototype.load = function (xmlString) {
// public - answer a new Project represented by the given XML String
return this.loadProjectModel(this.parse(xmlString));
};
SnapSerializer.prototype.loadProjectModel = function (xmlNode) {
// public - answer a new Project represented by the given XML top node
var myself = this,
project = this.project = {sprites: {}},
model,
nameID;
model = {project: xmlNode };
if (+xmlNode.attributes.version > this.version) {
throw 'Project uses newer version of Serializer';
}
/* Project Info */
this.objects = {};
project.name = model.project.attributes.name;
if (!project.name) {
nameID = 1;
while (
Object.prototype.hasOwnProperty.call(
localStorage,
'-snap-project-Untitled ' + nameID
)
) {
nameID += 1;
}
project.name = 'Untitled ' + nameID;
}
model.notes = model.project.childNamed('notes');
if (model.notes) {
project.notes = model.notes.contents;
}
model.globalVariables = model.project.childNamed('variables');
project.globalVariables = new VariableFrame();
/* Stage */
model.stage = model.project.require('stage');
StageMorph.prototype.frameRate = 0;
project.stage = new StageMorph(project.globalVariables);
if (Object.prototype.hasOwnProperty.call(
model.stage.attributes,
'id'
)) {
this.objects[model.stage.attributes.id] = project.stage;
}
if (model.stage.attributes.name) {
project.stage.name = model.stage.attributes.name;
}
if (model.stage.attributes.scheduled === 'true') {
project.stage.fps = 30;
StageMorph.prototype.frameRate = 30;
}
model.pentrails = model.stage.childNamed('pentrails');
if (model.pentrails) {
project.pentrails = new Image();
project.pentrails.onload = function () {
var context = project.stage.trailsCanvas.getContext('2d');
context.drawImage(project.pentrails, 0, 0);
project.stage.changed();
};
project.pentrails.src = model.pentrails.contents;
}
project.stage.setTempo(model.stage.attributes.tempo);
project.stage.setExtent(StageMorph.prototype.dimensions);
project.stage.isThreadSafe =
model.stage.attributes.threadsafe === 'true';
model.hiddenPrimitives = model.project.childNamed('hidden');
if (model.hiddenPrimitives) {
model.hiddenPrimitives.contents.split(' ').forEach(
function (sel) {
if (sel) {
StageMorph.prototype.hiddenPrimitives[sel] = true;
}
}
);
}
model.globalBlocks = model.project.childNamed('blocks');
if (model.globalBlocks) {
this.loadCustomBlocks(project.stage, model.globalBlocks, true);
this.populateCustomBlocks(
project.stage,
model.globalBlocks,
true
);
}
this.loadObject(project.stage, model.stage);
/* Sprites */
model.sprites = model.stage.require('sprites');
project.sprites[project.stage.name] = project.stage;
model.sprites.childrenNamed('sprite').forEach(function (model) {
myself.loadValue(model);
});
/* Global Variables */
if (model.globalVariables) {
this.loadVariables(
project.globalVariables,
model.globalVariables
);
}
/* Watchers */
model.sprites.childrenNamed('watcher').forEach(function (model) {
var watcher, color, target, hidden, extX, extY;
color = myself.loadColor(model.attributes.color);
target = Object.prototype.hasOwnProperty.call(
model.attributes,
'scope'
) ? project.sprites[model.attributes.scope] : null;
// determine whether the watcher is hidden, slightly
// complicated to retain backward compatibility
// with former tag format: hidden="hidden"
// now it's: hidden="true"
hidden = Object.prototype.hasOwnProperty.call(
model.attributes,
'hidden'
) && (model.attributes.hidden !== 'false');
if (Object.prototype.hasOwnProperty.call(
model.attributes,
'var'
)) {
watcher = new WatcherMorph(
model.attributes['var'],
color,
isNil(target) ? project.globalVariables
: target.variables,
model.attributes['var'],
hidden
);
} else {
watcher = new WatcherMorph(
localize(myself.watcherLabels[model.attributes.s]),
color,
target,
model.attributes.s,
hidden
);
}
watcher.setStyle(model.attributes.style || 'normal');
if (watcher.style === 'slider') {
watcher.setSliderMin(model.attributes.min || '1');
watcher.setSliderMax(model.attributes.max || '100');
}
watcher.setPosition(
project.stage.topLeft().add(new Point(
+model.attributes.x || 0,
+model.attributes.y || 0
))
);
project.stage.add(watcher);
watcher.update();
// set watcher's contentsMorph's extent if it is showing a list and
// its monitor dimensions are given
if (watcher.currentValue instanceof List) {
extX = model.attributes.extX;
if (extX) {
watcher.cellMorph.contentsMorph.setWidth(+extX);
}
extY = model.attributes.extY;
if (extY) {
watcher.cellMorph.contentsMorph.setHeight(+extY);
}
// adjust my contentsMorph's handle position
watcher.cellMorph.contentsMorph.handle.drawNew();
}
});
this.objects = {};
return project;
};
SnapSerializer.prototype.loadBlocks = function (xmlString, targetStage) {
// public - answer a new Array of custom block definitions
// represented by the given XML String
var stage = new StageMorph(),
model;
this.project = {
stage: stage,
sprites: {},
targetStage: targetStage // for secondary custom block def look-up
};
model = this.parse(xmlString);
if (+model.attributes.version > this.version) {
throw 'Module uses newer version of Serializer';
}
this.loadCustomBlocks(stage, model, true);
this.populateCustomBlocks(
stage,
model,
true
);
this.objects = {};
stage.globalBlocks.forEach(function (def) {
def.receiver = null;
});
this.objects = {};
this.project = {};
this.mediaDict = {};
return stage.globalBlocks;
};
SnapSerializer.prototype.loadSprites = function (xmlString, ide) {
// public - import a set of sprites represented by xmlString
// into the current project of the ide
var model, project, myself = this;
project = this.project = {
globalVariables: ide.globalVariables,
stage: ide.stage,
sprites: {}
};
project.sprites[project.stage.name] = project.stage;
model = this.parse(xmlString);
if (+model.attributes.version > this.version) {
throw 'Module uses newer version of Serializer';
}
model.childrenNamed('sprite').forEach(function (model) {
var sprite = new SpriteMorph(project.globalVariables);
if (model.attributes.id) {
myself.objects[model.attributes.id] = sprite;
}
if (model.attributes.name) {
sprite.name = model.attributes.name;
project.sprites[model.attributes.name] = sprite;
}
if (model.attributes.color) {
sprite.color = myself.loadColor(model.attributes.color);
}
if (model.attributes.pen) {
sprite.penPoint = model.attributes.pen;
}
project.stage.add(sprite);
ide.sprites.add(sprite);
sprite.scale = parseFloat(model.attributes.scale || '1');
sprite.rotationStyle = parseFloat(
model.attributes.rotation || '1'
);
sprite.isDraggable = model.attributes.draggable !== 'false';
sprite.isVisible = model.attributes.hidden !== 'true';
sprite.heading = parseFloat(model.attributes.heading) || 0;
sprite.drawNew();
sprite.gotoXY(+model.attributes.x || 0, +model.attributes.y || 0);
myself.loadObject(sprite, model);
});
this.objects = {};
this.project = {};
this.mediaDict = {};
// ide.stage.drawNew();
ide.createCorral();
ide.fixLayout();
};
SnapSerializer.prototype.loadMedia = function (xmlString) {
// public - load the media represented by xmlString into memory
// to be referenced by a media-less project later
return this.loadMediaModel(this.parse(xmlString));
};
SnapSerializer.prototype.loadMediaModel = function (xmlNode) {
// public - load the media represented by xmlNode into memory
// to be referenced by a media-less project later
var myself = this,
model = xmlNode;
this.mediaDict = {};
if (+model.attributes.version > this.version) {
throw 'Module uses newer version of Serializer';
}
model.children.forEach(function (model) {
myself.loadValue(model);
});
return this.mediaDict;
};
SnapSerializer.prototype.loadObject = function (object, model) {
// private
var blocks = model.require('blocks');
this.loadCostumes(object, model);
this.loadSounds(object, model);
this.loadCustomBlocks(object, blocks);
this.populateCustomBlocks(object, blocks);
this.loadVariables(object.variables, model.require('variables'));
this.loadScripts(object.scripts, model.require('scripts'));
};
SnapSerializer.prototype.loadCostumes = function (object, model) {
// private
var costumes = model.childNamed('costumes'),
costume;
if (costumes) {
object.costumes = this.loadValue(costumes.require('list'));
}
if (Object.prototype.hasOwnProperty.call(
model.attributes,
'costume'
)) {
costume = object.costumes.asArray()[model.attributes.costume - 1];
if (costume) {
if (costume.loaded) {
object.wearCostume(costume);
} else {
costume.loaded = function () {
object.wearCostume(costume);
};
}
}
}
};
SnapSerializer.prototype.loadSounds = function (object, model) {
// private
var sounds = model.childNamed('sounds');
if (sounds) {
object.sounds = this.loadValue(sounds.require('list'));
}
};
SnapSerializer.prototype.loadVariables = function (varFrame, element) {
// private
var myself = this;
element.children.forEach(function (child) {
var value;
if (child.tag !== 'variable') {
return;
}
value = child.children[0];
varFrame.vars[child.attributes.name] = value ?
myself.loadValue(value) : 0;
});
};
SnapSerializer.prototype.loadCustomBlocks = function (
object,
element,
isGlobal
) {
// private
var myself = this;
element.children.forEach(function (child) {
var definition, names, inputs, comment, i;
if (child.tag !== 'block-definition') {
return;
}
definition = new CustomBlockDefinition(
child.attributes.s || '',
object
);
definition.category = child.attributes.category || 'other';
definition.type = child.attributes.type || 'command';
definition.isGlobal = (isGlobal === true);
if (definition.isGlobal) {
object.globalBlocks.push(definition);
} else {
object.customBlocks.push(definition);
}
names = definition.parseSpec(definition.spec).filter(
function (str) {
return str.charAt(0) === '%';
}
).map(function (str) {
return str.substr(1);
});
definition.names = names;
inputs = child.childNamed('inputs');
if (inputs) {
i = -1;
inputs.children.forEach(function (child) {
if (child.tag !== 'input') {
return;
}
definition.declarations[names[i += 1]]
= [child.attributes.type, child.contents];
});
}
comment = child.childNamed('comment');
if (comment) {
definition.comment = myself.loadComment(comment);
}
});
};
SnapSerializer.prototype.populateCustomBlocks = function (
object,
element,
isGlobal
) {
// private
var myself = this;
element.children.forEach(function (child, index) {
var definition, script, scripts;
if (child.tag !== 'block-definition') {
return;
}
definition = isGlobal ? object.globalBlocks[index]
: object.customBlocks[index];
script = child.childNamed('script');
if (script) {
definition.body = new Context(
null,
script ? myself.loadScript(script) : null,
null,
object
);
definition.body.inputs = definition.names.slice(0);
}
scripts = child.childNamed('scripts');
if (scripts) {
definition.scripts = myself.loadScriptsArray(scripts);
}
delete definition.names;
});
};
SnapSerializer.prototype.loadScripts = function (scripts, model) {
// private
var myself = this,
scale = SyntaxElementMorph.prototype.scale;
scripts.texture = 'scriptsPaneTexture.gif';
model.children.forEach(function (child) {
var element;
if (child.tag === 'script') {
element = myself.loadScript(child);
if (!element) {
return;
}
element.setPosition(new Point(
(+child.attributes.x || 0) * scale,
(+child.attributes.y || 0) * scale
).add(scripts.topLeft()));
scripts.add(element);
element.fixBlockColor(null, true); // force zebra coloring
element.allComments().forEach(function (comment) {
comment.align(element);
});
} else if (child.tag === 'comment') {
element = myself.loadComment(child);
if (!element) {
return;
}
element.setPosition(new Point(
(+child.attributes.x || 0) * scale,
(+child.attributes.y || 0) * scale
).add(scripts.topLeft()));
scripts.add(element);
}
});
};
SnapSerializer.prototype.loadScriptsArray = function (model) {
// private - answer an array containting the model's scripts
var myself = this,
scale = SyntaxElementMorph.prototype.scale,
scripts = [];
model.children.forEach(function (child) {
var element;
if (child.tag === 'script') {
element = myself.loadScript(child);
if (!element) {
return;
}
element.setPosition(new Point(
(+child.attributes.x || 0) * scale,
(+child.attributes.y || 0) * scale
));
scripts.push(element);
element.fixBlockColor(null, true); // force zebra coloring
} else if (child.tag === 'comment') {
element = myself.loadComment(child);
if (!element) {
return;
}
element.setPosition(new Point(
(+child.attributes.x || 0) * scale,
(+child.attributes.y || 0) * scale
));
scripts.push(element);
}
});
return scripts;
};
SnapSerializer.prototype.loadScript = function (model) {
// private
var topBlock, block, nextBlock,
myself = this;
model.children.forEach(function (child) {
nextBlock = myself.loadBlock(child);
if (!nextBlock) {
return;
}
if (block) {
block.nextBlock(nextBlock);
} else {
topBlock = nextBlock;
}
block = nextBlock;
});
return topBlock;
};
SnapSerializer.prototype.loadComment = function (model) {
// private
var comment = new CommentMorph(model.contents),
scale = SyntaxElementMorph.prototype.scale;
comment.isCollapsed = (model.attributes.collapsed === 'true');
comment.setTextWidth(+model.attributes.w * scale);
return comment;
};
SnapSerializer.prototype.loadBlock = function (model, isReporter) {
// private
var block, info, inputs, isGlobal, rm, receiver;
if (model.tag === 'block') {
if (Object.prototype.hasOwnProperty.call(
model.attributes,
'var'
)) {
return SpriteMorph.prototype.variableBlock(
model.attributes['var']
);
}
block = SpriteMorph.prototype.blockForSelector(model.attributes.s);
} else if (model.tag === 'custom-block') {
isGlobal = model.attributes.scope ? false : true;
receiver = isGlobal ? this.project.stage
: this.project.sprites[model.attributes.scope];
rm = model.childNamed('receiver');
if (rm && rm.children[0]) {
receiver = this.loadValue(
model.childNamed('receiver').children[0]
);
}
if (!receiver) {
return this.obsoleteBlock(isReporter);
}
if (isGlobal) {
info = detect(receiver.globalBlocks, function (block) {
return block.blockSpec() === model.attributes.s;
});
if (!info && this.project.targetStage) { // importing block files
info = detect(
this.project.targetStage.globalBlocks,
function (block) {
return block.blockSpec() === model.attributes.s;
}
);
}
} else {
info = detect(receiver.customBlocks, function (block) {
return block.blockSpec() === model.attributes.s;
});
}
if (!info) {
return this.obsoleteBlock(isReporter);
}
block = info.type === 'command' ? new CustomCommandBlockMorph(
info,
false
) : new CustomReporterBlockMorph(
info,
info.type === 'predicate',
false
);
}
if (block === null) {
block = this.obsoleteBlock(isReporter);
}
block.isDraggable = true;
inputs = block.inputs();
model.children.forEach(function (child, i) {
if (child.tag === 'comment') {
block.comment = this.loadComment(child);
block.comment.block = block;
} else if (child.tag === 'receiver') {
nop(); // ignore
} else {
this.loadInput(child, inputs[i], block);
}
}, this);
return block;
};
SnapSerializer.prototype.obsoleteBlock = function (isReporter) {
// private
var block = isReporter ? new ReporterBlockMorph()
: new CommandBlockMorph();
block.selector = 'nop';
block.color = new Color(200, 0, 20);
block.setSpec('Obsolete!');
block.isDraggable = true;
return block;
};
SnapSerializer.prototype.loadInput = function (model, input, block) {
// private
var inp, val, myself = this;
if (model.tag === 'script') {
inp = this.loadScript(model);
if (inp) {
input.add(inp);
input.fixLayout();
}
} else if (model.tag === 'autolambda' && model.children[0]) {
inp = this.loadBlock(model.children[0], true);
if (inp) {
input.silentReplaceInput(input.children[0], inp);
input.fixLayout();
}
} else if (model.tag === 'list') {
while (input.inputs().length > 0) {
input.removeInput();
}
model.children.forEach(function (item) {
input.addInput();
myself.loadInput(
item,
input.children[input.children.length - 2],
input
);
});
input.fixLayout();
} else if (model.tag === 'block' || model.tag === 'custom-block') {
block.silentReplaceInput(input, this.loadBlock(model, true));
} else if (model.tag === 'color') {
input.setColor(this.loadColor(model.contents));
} else {
val = this.loadValue(model);
if (val) {
input.setContents(this.loadValue(model));
}
}
};
SnapSerializer.prototype.loadValue = function (model) {
// private
var v, items, el, center, image, name, audio, option,
myself = this;
function record() {
if (Object.prototype.hasOwnProperty.call(
model.attributes,
'id'
)) {
myself.objects[model.attributes.id] = v;
}
if (Object.prototype.hasOwnProperty.call(
model.attributes,
'mediaID'
)) {
myself.mediaDict[model.attributes.mediaID] = v;
}
}
switch (model.tag) {
case 'ref':
if (Object.prototype.hasOwnProperty.call(model.attributes, 'id')) {
return this.objects[model.attributes.id];
}
if (Object.prototype.hasOwnProperty.call(
model.attributes,
'mediaID'
)) {
return this.mediaDict[model.attributes.mediaID];
}
throw new Error('expecting a reference id');
case 'l':
option = model.childNamed('option');
return option ? [option.contents] : model.contents;
case 'bool':
return model.contents === 'true';
case 'list':
if (model.attributes.hasOwnProperty('linked')) {
items = model.childrenNamed('item');
if (items.length === 0) {
v = new List();
record();
return v;
}
items.forEach(function (item) {
var value = item.children[0];