/
versioning.js
2568 lines (2108 loc) · 98 KB
/
versioning.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
// -*- mode: java; c-basic-offset: 2; -*-
// Copyright © 2013-2018 Massachusetts Institute of Technology, All rights reserved
// Released under the Apache License, Version 2.0
// http://www.apache.org/licenses/LICENSE-2.0
/**
* @license
* @fileoverview Visual blocks editor for App Inventor
* Methods to handle converting apps from older versions to current
*
* @author wolber@usfca.edu (David Wolber)
* @author ewpatton@mit.edu (Evan W. Patton)
*
* [lyn, 2014/10/31] Completely overhauled blocks upgrading architecture.
* All the work is done in Blockly.Version.upgrade.
* As in Liz Looney's AI1 BlocksSaveFile upgraders, all upgrades are based on mismatches
* between component versions or language versions of the screen and those of the current system.
* Unlike Liz's system, in which conditionals based on version numbers are used to express AI1 upgrades,
* all AI2 upgrades are expressed via the dictionary structure in Blockly.Versioning.AllUpgradeMaps,
* which is defined at the end of this file. This is a more declarative approach for expressing upgrades.
*/
'use strict';
goog.provide('AI.Blockly.Versioning');
goog.require('goog.dom');
goog.require('goog.dom.xml');
if (Blockly.Versioning === undefined) Blockly.Versioning = {};
Blockly.Versioning.loggingFlag = true;
Blockly.Versioning.setLogging = function (bool) {
Blockly.Versioning.loggingFlag = bool;
};
Blockly.Versioning.log = function log(string) { // Display feedback on upgrade if Blockly.Versioning.loggingFlag is on.
if (Blockly.Versioning.loggingFlag) {
console.log("Blockly.Versioning: " + string);
}
};
/**
* [lyn, 2014/11/04] Simplified version of Halloween AI2 upgrading architecture.
*
* @param preUpgradeFormJsonString: JSON String from pre-upgrade Form associated with these blocks
* @param blocksContent: String with XML representation of blocks for a screen
* @param {Blockly.WorkspaceSvg=} opt_workspace Optional workspace that will be populated with the
* blocks content. If not specified, Blockly.mainWorkspace is used.
*
* @author fturbak@wellesley.edu (Lyn Turbak)
*
* Perform any upgrades on the blocks implied by mismatches (1) between component version numbers
* in preUpgradeFormJsonString and current system component numbers or (2) between blocks language
* version number in blocksContent and current system blocks language version.
*
* After any upgrades, load the blocks into Blockly.mainWorkspace.
*
* Upgrades may be performed either on the XML dom tree representation or the loaded blocks
* representation in Blockly.mainWorkspace. As a consquence, the upgrading process may
* ping-pong back and forth between these two representations. But in the end, the upgraded
* blocks will be loaded into Blockly.mainWorkspace.
*
* All upgrades are described by the dictionary structure in Blockly.Versioning.AllUpgradeMaps,
* which is defined at the end of this file.
*
*/
Blockly.Versioning.upgrade = function (preUpgradeFormJsonString, blocksContent, opt_workspace) {
opt_workspace = opt_workspace || Blockly.mainWorkspace;
var preUpgradeFormJsonObject = JSON.parse(preUpgradeFormJsonString);
var dom = Blockly.Xml.textToDom(blocksContent); // Initial blocks rep is dom for blocksContent
/**
* Upgrade the given componentType. If componentType is "Language", upgrades the blocks language.
* The rep argument is either a dom or a workspace. It is passed explicitly only to indicate type
* of current rep to determine when conversion needs to be done between dom and workspace (or vice versa).
* @param componentType
* @param preUpgradeVersion
* @param systemVersion
* @param rep: the current blocks representation (dom or Blockly.mainWorkspace).
* This is only passed explicitly to indicate type of current rep to determine
* when conversion needs to be done between dom and workspace (or vice versa).
* @returns: resulting representation (dom or workspace), again only for dynamic type checking.
*/
function upgradeComponentType (componentType, preUpgradeVersion, systemVersion, rep) {
if (componentType == "Form") {
componentType = "Screen"; // Treat Form as if it were Screen
}
Blockly.Versioning.log("In Blockly.Versioning.upgrade, upgradeComponentType(" + componentType + "," +
preUpgradeVersion + "," + systemVersion + "," + rep + ")");
if (preUpgradeVersion > systemVersion) {
// What to do in this case? Currently, throw an exception, but might want to do something else:
// JIS: We simply ignore this situation. It happens when someone imports a project that was
// touched by a newer version of App Inventor. By the time we are run here the user has already
// been shown a warning that the project may not work as expected. However if we throw the
// exception below we *guarantee* that the project will fail to load. Let's give them a
// chance instead (so the lines below are commented out).
// throw "Unexpected situation in Blockly.Versioning.upgrade: preUpgradeVersion of " + componentType +
// " = " + preUpgradeVersion + " > systemVersion = " + systemVersion;
} else if (preUpgradeVersion < systemVersion) {
// Need to upgrade this component
Blockly.Versioning.log("upgrading component type " + componentType + " from version " +
preUpgradeVersion + " to version " + systemVersion);
var upgradeMap = Blockly.Versioning.AllUpgradeMaps[componentType];
if (! upgradeMap) {
throw "Blockly.Versioning.upgrade: no upgrade map for component type " + componentType;
}
for (var version = preUpgradeVersion + 1; version <= systemVersion; version++) {
var versionUpgrader = upgradeMap[version];
if (! versionUpgrader) {
throw "Blockly.Versioning.upgrade: no upgrader to upgrade component type " + componentType +
" to version " + version;
}
// Perform upgrade
Blockly.Versioning.log("applying upgrader for upgrading component type " + componentType +
" from version " + (version-1) + " to version " + version);
// Apply upgrader, possibly mutating rep and changing its dynamic type.
rep = Blockly.Versioning.applyUpgrader(versionUpgrader, rep, opt_workspace);
}
} // otherwise, preUpgradeVersion and systemVersion are equal and no updgrade is necessary
return rep; // Return final blocks representation, for dynamic typing purposes
}
// --------------------------------------------------------------------------------
// Upgrade language based on language version
var systemLanguageVersion = top.BLOCKS_VERSION;
var systemYoungAndroidVersion = top.YA_VERSION;
var versionTags = dom.getElementsByTagName('yacodeblocks');
// if there is no version in the file, then this is an early ai2 project, prior to
// 10/21/13, when the blocks internal xml structure was overhauled
// with descriptive mutator tags. blocksOverhaul translates the blocks
var preUpgradeLanguageVersion;
if (versionTags.length===0) {
Blockly.Versioning.v17_blocksOverhaul(dom, opt_workspace);
preUpgradeLanguageVersion = 17; // default for oldest ai2
}
else {
if (systemYoungAndroidVersion == parseInt(versionTags[0].getAttribute('ya-version'), 10)) {
Blockly.Versioning.ensureWorkspace(dom, opt_workspace);
return;
}
preUpgradeLanguageVersion = parseInt(versionTags[0].getAttribute('language-version'), 10);
}
var blocksRep = dom; // Initial blocks rep is dom
blocksRep = upgradeComponentType("Language", preUpgradeLanguageVersion, systemLanguageVersion, blocksRep);
// --------------------------------------------------------------------------------
// Upgrade components based on pre-upgrade version numbers
var preUpgradeComponentVersionDict = Blockly.Versioning.makeComponentVersionDict(preUpgradeFormJsonObject);
for (var componentType in preUpgradeComponentVersionDict) {
if (!preUpgradeComponentVersionDict.hasOwnProperty(componentType)) continue;
// Cannot upgrade extensions as they are not part of the system
if (Blockly.Versioning.isExternal(componentType, opt_workspace)) continue;
var preUpgradeVersion = preUpgradeComponentVersionDict[componentType];
var systemVersion = Blockly.Versioning.getSystemComponentVersion(componentType, opt_workspace);
blocksRep = upgradeComponentType(componentType, preUpgradeVersion, systemVersion, blocksRep);
}
// Ensure that final blocks rep is Blockly.mainWorkspace
Blockly.Versioning.log("Blockly.Versioning.upgrade: Final conversion to Blockly.mainWorkspace");
Blockly.Versioning.ensureWorkspace(blocksRep, opt_workspace); // No need to use result; does work by side effect on Blockly.mainWorkspace
};
/**
* [lyn, 2014/11/04]
* Check that the given upgrader is a valid form for an upgrader. It must either be:
* (1) a function
* (2) an array of upgraders
* (3) a special string (one of "noUpgrade" or "ai1CantDoUpgrade")
*
* Note: we don't check here in array case that all array elements are themselves upgraders.
* That check will be performed dynamically later when array elements are applied
* by Blockly.Versioning.applyUpgrader.
*/
Blockly.Versioning.checkUpgrader = function (upgrader) {
var specialUpgradeStrings = ["noUpgrade", "ai1CantDoUpgrade"];
if (typeof(upgrader) == "string") {
if (specialUpgradeStrings.indexOf(upgrader) == -1) {
throw "Blockly.Versioning.checkUpgrader: upgrader is unrecognized special string: " + upgrader;
}
} else if (! ((typeof(upgrader) == "function") || Array.isArray (upgrader))) {
throw "Blockly.Versioning.checkUpgrader: upgrader is not a function, special string, or array of upgraders -- "
+ upgrader;
}
};
/**
* Returns true if blocksRep is a workspace; otherwise returns false
*/
Blockly.Versioning.isWorkspace = function (blocksRep) {
return blocksRep instanceof Blockly.Workspace;
};
/*
Blockly.Versioning.isWorkspace =
(function () {
var workspaceInstance = new Blockly.Workspace(); // ignore get & set metrics
return function (blocksRep) {
return (typeof(blocksRep) == "object") && (blocksRep.constructor == workspaceInstance.constructor)
};
})();
*/
/**
* Returns true if blocksRep is a dom; otherwise returns false
*/
Blockly.Versioning.isDom = function (blocksRep) {
try {
return (blocksRep instanceof Element
|| blocksRep instanceof HTMLElement
|| blocksRep instanceof HTMLUnknownElement
|| blocksRep.tagName == 'XML');
} catch (anyErr) {
// In phantomJS testing context, HTMLUnknownElement is undefined and causes an error,
// so handle it this way.
return false;
}
};
/**
* If blocksRep is a dom, returns it; otherwise converts the workspace to a dom
*/
Blockly.Versioning.ensureDom = function (blocksRep) {
if (Blockly.Versioning.isDom(blocksRep)) {
return blocksRep; // already a dom
} else if (Blockly.Versioning.isWorkspace(blocksRep)) {
Blockly.Versioning.log("Blockly.Versioning.ensureDom: converting Blockly.mainWorkspace to dom");
return Blockly.Xml.workspaceToDom(blocksRep);
} else {
throw "Blockly.Versioning.ensureDom: blocksRep is neither dom nor workspace -- " + blocksRep;
}
};
Blockly.Versioning.getBlockChildren = function (dom) {
var result = [];
var gdChildren = goog.dom.getChildren(dom);
for (var gdi = 0, gdChild; gdChild = gdChildren[gdi]; gdi++) {
result.push(gdChild);
}
return result;
};
/**
* If blocksRep is a workspace, returns it; otherwise converts the workspace to a dom
*/
Blockly.Versioning.ensureWorkspace = function (blocksRep, opt_workspace) {
if (Blockly.Versioning.isWorkspace(blocksRep)) {
return blocksRep; // already a workspace
} else if (Blockly.Versioning.isDom(blocksRep)) {
var workspace = opt_workspace || Blockly.mainWorkspace;
Blockly.Versioning.log("Blockly.Versioning.ensureWorkspace: converting dom to Blockly.mainWorkspace");
workspace.clear(); // Remove any existing blocks before we add new ones.
Blockly.Xml.domToWorkspaceHeadless(blocksRep, workspace);
// update top block positions in event of save before rendering.
var blocks = workspace.getTopBlocks();
for (var i = 0; i < blocks.length; i++) {
var block = blocks[i];
var xy = block.getRelativeToSurfaceXY();
xy.x = block.x;
xy.y = block.y;
}
return workspace;
} else {
throw "Blockly.Versioning.ensureWorkspace: blocksRep is neither workspace nor dom -- " + blocksRep;
}
};
/**
* Apply an upgrder to a blocksRepresentation, possibly (1) changing it by side effect and
* (2) changing its representation (dom or workspace). Returns the final representation.
* @param upgrader
* @param blocksRep: an instance of an XML dom tree or a Blockly.Workspace
* @param opt_workspace: Optional workspace to be upgraded
*/
Blockly.Versioning.applyUpgrader = function (upgrader, blocksRep, opt_workspace) {
opt_workspace = opt_workspace || Blockly.mainWorkspace;
opt_workspace.getProcedureDatabase().clear(); // clear the proc database in case of multiple upgrades
Blockly.Versioning.checkUpgrader(upgrader); // ensure it has the correct form.
// Perform upgrade
if (upgrader == "ai1CantDoUpgrade") {
throw "Blockly.Versioning.applyUpgrader: cannot perform an AI Classic upgrade on " + blocksRep;
} else if (typeof(upgrader) == "function") {
return upgrader(blocksRep, opt_workspace); // Apply upgrader, possibly mutating rep and changing its dynamic type.
} else if (Array.isArray (upgrader)) {
// Treat array as sequential composition of upgraders
Blockly.Versioning.log("Blockly.Versioning.applyUpgrader: treating list as sequential composition of upgraders");
return (Blockly.Versioning.composeUpgraders(upgrader))(blocksRep, opt_workspace);
} else { // otherwise, versionUpgrader is "noUpgrade", and nothing is done, so acts like identity
return blocksRep;
}
};
/**
* Return a single upgrader that sequentially composes the upgraders in upgraderList
* @param upgraderList
*/
Blockly.Versioning.composeUpgraders = function (upgraderList, opt_workspace) {
opt_workspace = opt_workspace || Blockly.mainWorkspace;
return function (blocksRep) {
for (var i = 0, upgrader; upgrader = upgraderList[i]; i++) {
blocksRep = Blockly.Versioning.applyUpgrader(upgrader, blocksRep, opt_workspace); // Applying upgrader may convert blocks rep from dom to workspace or vice versa.
}
return blocksRep; // Return the final blocks rep
}
};
/******************************************************************************
* Key functions for determining whether component upgrades are needed
******************************************************************************/
/*
/** createUpgraders takes a pre-upgrade form JSON string and returns an object with two fields:
* 1. The "XML" field denotes a function that upgrades the dom tree by side effect.
* 2. The "blocks" field denotes a function that upgrades the main workspace by side effect.
* /
Blockly.Versioning.createUpgraders = function (preUpgradeFormJsonString) {
var xmlUpgraders = [];
var blocksUpgraders = [];
function collectUpgradersForComponentTypeToVersion(compType, oldVersion, newVersion) {
var upgradeMap = Blockly.Versioning.AllUpgradeMaps[compType];
for (var version = oldVersion; version < newVersion; version = version + 1) {
var versionUpgraders = upgradeMap[version];
var xmlUpgrader = versionUpgraders[0];
xmlUpgraders.push(xmlUpgrader);
var blocksUpgrader = versionUpgraders[1];
blocksUpgraders.push(blocksUpgrader);
}
}
var preUpgradeFormJsonObject = JSON.parse(preUpgradeFormJsonString);
var preUpgradeComponentVersionDict = Blockly.Versioning.makeComponentVersionDict(preUpgradeFormJsonObject);
for (var componentType in preUpgradeComponentVersionDict) {
var preUpgradeVersion = preUpgradeComponentVersionDict[componentType];
var currentVersion = Blockly.Versioning.getCurrentVersion(componentType);
if (preUpgradeVersion > currentVersion) {
// What to do in this case? Currently, do nothing, but at least might want a warning
console.log("Unexpected: preUpgradeVersion of " + componentType + " = " + str(preUpgradVerision)
+ " > currentVersion = " + str(currentVersion));
} else if (preUpgradeVersion < currentVersion) {
// Need to upgrade this component
collectUpgradersForComponentTypeToVersion(componentType, preUpgradeVersion, currentVersion);
} // else they're equal and we really do nothing
}
/**
* Given a list of one-argument side-effecting functions, returns a one-argument
* function that applies each function in the list to the argument, one by one.
* @param functionList
* @returns {Function}
* /
function curriedApplyAll (functionList) {
return function (arg) {
for (var i = 0, fun; fun = functionList[i]; i = i + 1) {
fun(arg)
}
}
}
return {"XML": curriedApplyAll(xmlUpgraders), "blocks": curriedApplyAll(blocksUpgraders)}
}
*/
/**
* Create a dictionary mapping each component mentioned in formJsonObject
* to its version number. Complain if all version numbers for the same
* component are not the same.
*/
Blockly.Versioning.makeComponentVersionDict = function (formJsonObject) {
var versionDict = {};
/**
* Walk over component tree, modifying versionDict to have version of each component encountered.
* @param comps
*/
function processComponents (comps) {
for (var c = 0, comp; comp=comps[c]; c = c+ 1) {
var compType = comp["$Type"];
var compVersion = parseInt(comp["$Version"]);
var versionAlreadyInDict = versionDict[compType];
if (versionAlreadyInDict) {
if (versionAlreadyInDict != compVersion) {
throw "Blockly.Versioning.makeComponentVersionDict: inconsistent versions for component of type"
+ compType + "; [" + str(compVersion) + ", " + versionAlreadyInDict + "]"
} // Otherwise version is same as before and we're happy
} else { // No version yet in dict; add it
versionDict[compType] = compVersion;
}
var subComponents = comp["$Components"];
if (subComponents) { // recursively process any subcomponents
processComponents(subComponents);
}
}
}
processComponents ([formJsonObject["Properties"]]); // Walk the component tree, updating versionDict along the way.
return versionDict;
};
Blockly.Versioning.getSystemComponentVersion = function (componentType, workspace) {
var versionString = workspace.getComponentDatabase().getType(componentType).componentInfo.version;
if (versionString) {
return parseInt(versionString);
} else {
throw "Blockly.Versioning.getSystemComponentVersion: No version for component type " + componentType;
}
};
Blockly.Versioning.isExternal = function(componentType, workspace) {
var description = workspace.getComponentDatabase().getType(componentType);
if (description && description.componentInfo) {
return 'true' === description.componentInfo.external;
} else {
return false;
}
};
/******************************************************************************
* Details for specific upgrades go below, in reverse chronological order.
* The code for each upgrade *MUST* be well-documented in order to help
* those implementing similar upgrades in the future.
******************************************************************************/
/**----------------------------------------------------------------------------
* Upgrade to Blocks Language version 17:
* @author wolber@usfca.edu (David Wolber)
*
* Code for translating early ai2 blocks to 10/20/13 version
* if there is no version # in the Blockly file, then it is an early ai2 project, prior to
* 10/21/13, when the blocks internal xml structure was overhauled
* with descriptive mutator tags. blocksOverhaul translates the blocks
* Methods to handle serialization of the blocks workspace
*
* [lyn, 10/03/2014] Notes:
* * This code used to be in blocklyeditor/src/versioning/017_blocksOverhaul.js
* but I moved it here as part of consolidating all upgrade code in one file.
* * I prefixed all the function names with "v17_" to clarify which
* functions are used in the upgrade to YAVersion 17.
----------------------------------------------------------------------------*/
Blockly.Versioning.v17_blocksOverhaul = function(xmlFromFile, workspace) {
// we loaded in something with no version, we need to translate
var renameAlert = 0;
var blocks = xmlFromFile.getElementsByTagName('block');
for (var i = 0, im = blocks.length; i < im; i++) {
var blockElem = blocks[i];
var blockType = blockElem.getAttribute('type');
// all built-in blocks have an entry already in Blockly.Language
// we don't need to translate those, so if the following is non-null we ignore
if (Blockly.Blocks[blockType] == null)
{
// add some translations for language changes...
// these should really be in a map or at procedure that checks and
// returns replacement...straight translations...we could also put
// lexical_variable_get and set here so that we don't have to have a special
// case below
if (blockType == 'procedures_do_then_return')
blockElem.setAttribute('type',"controls_do_then_return");
else
if (blockType == 'procedure_lexical_variable_get')
blockElem.setAttribute('type',"lexical_variable_get");
else
if (blockType == 'for_lexical_variable_get')
blockElem.setAttribute('type',"lexical_variable_get");
else {
var splitComponent = blockType.split('_');
if (splitComponent.length > 2) {
// This happens when someone puts an _ in a block name!
splitComponent = [splitComponent.slice(0, -1).join('_'), splitComponent.pop()];
}
// there are some blocks that are not built-in but are not component based,
// we want to ignore them
if (splitComponent[0] != 'lexical') {
// methods on any (generics) have a blocktype of _any_someComponent_method
// so 1st check if type has 'any' in it, if so we have a generic method
if (splitComponent[1] == 'any') // we have a generic method call
Blockly.Versioning.v17_translateAnyMethod(blockElem);
else {
// we have a set, get, component get, event, or method
// check if the first thing is a component type. If so, the only
// legal thing it could be is a (generic) component set/get
// but old programs allow instance names same as type names, so
// we can get a Accelerometer.Shaking which is really an instance event
var componentDb = workspace.getComponentDatabase();
if (componentDb.hasType(splitComponent[0]) &&
(splitComponent[1] == 'setproperty' || splitComponent[1] == 'getproperty'))
Blockly.Versioning.v17_translateComponentSetGetProperty(blockElem, workspace);
else {
var instance = splitComponent[0];
var componentType = componentDb.instanceNameToTypeName(instance);
if (componentType == instance && renameAlert === 0) {
alert("Your app was created in an earlier version of App Inventor and may be loaded incorrectly."+
" The problem is that it names a component instance"+
" the same as the component type, which is longer allowed.");
renameAlert = 1;
}
// we should really check for null here so if there are blocks that
// are not instance_ we can ignore. Right now the following ifs
// probably make sure of this-- if none of the questions about rightside
// are answered affirmatively, but this should be checked here as well
var rightside = splitComponent[1];
if (rightside == 'setproperty' || rightside == 'getproperty')
Blockly.Versioning.v17_translateSetGetProperty(blockElem, workspace);
else
if (rightside == 'component')
Blockly.Versioning.v17_translateComponentGet(blockElem, workspace);
else
if (componentDb.getEventForType(componentType, rightside))
Blockly.Versioning.v17_translateEvent(blockElem, workspace);
else
if (componentDb.getMethodForType(componentType, rightside))
Blockly.Versioning.v17_translateMethod(blockElem, workspace);
}
}
}
}
}
}
};
/**
* v17_translateEvent is called when we know we have an Event element that
* needs to be translated.
*/
Blockly.Versioning.v17_translateEvent = function(blockElem, workspace) {
//get the event type and instance name,
// the type attribute is "component_event"
// event block types look like: <block type="Button1_Click" x="132" y="72">
var splitComponent = blockElem.getAttribute('type').split('_');
if (splitComponent.length > 2) {
// This happens when someone puts an _ in a block name!
splitComponent = [splitComponent.slice(0, -1).join('_'), splitComponent.pop()];
}
var instance = splitComponent[0];
var event=splitComponent[1];
// Paul has a function to convert instance to type
var componentType = workspace.getComponentDatabase().instanceNameToTypeName(instance);
// ok, we have all the info, now we can override the old event attribute with 'event'
blockElem.setAttribute('type','component_event');
// <mutation component_type="Canvas" instance_name="Canvas1" event_name="Dragged"></mutation>
// add mutation tag
var mutationElement = goog.dom.createElement('mutation');
//mutationElement.setAttribute('component_type',component);
mutationElement.setAttribute('instance_name', instance);
mutationElement.setAttribute('event_name', event);
mutationElement.setAttribute('component_type',componentType);
blockElem.insertBefore(mutationElement,blockElem.firstChild);
};
/**
* v17_translateMethod is called when we know we have a component method element that
* needs to be translated.
*/
Blockly.Versioning.v17_translateMethod = function(blockElem, workspace) {
// the type attribute is "instance_method"
var blockType = blockElem.getAttribute('type');
// method block types look like: <block type="TinyDB_StoreValue" ...>
var splitComponent = blockType.split('_');
if (splitComponent.length > 2) {
// This happens when someone puts an _ in a block name!
splitComponent = [splitComponent.slice(0, -1).join('_'), splitComponent.pop()];
}
var instance = splitComponent[0];
var method = splitComponent[1];
// Paul has a function to convert instance to type
var componentType = workspace.getComponentDatabase().instanceNameToTypeName(instance);
// ok, we have all the info, now we can override the old event attribute with 'event'
blockElem.setAttribute('type','component_method');
// <mutation component_type="Canvas" instance_name="Canvas1" event_name="Dragged"></mutation>
// add mutation tag
var mutationElement = goog.dom.createElement('mutation');
//mutationElement.setAttribute('component_type',component);
mutationElement.setAttribute('instance_name', instance);
mutationElement.setAttribute('method_name', method);
mutationElement.setAttribute('component_type',componentType);
mutationElement.setAttribute('is_generic','false');
blockElem.insertBefore(mutationElement,blockElem.firstChild);
};
/**
* v17_translateAnyMethod is called when we know we have a method on a generic (any)
* component.
*/
Blockly.Versioning.v17_translateAnyMethod = function(blockElem) {
// the type attribute is "instance_method"
var blockType = blockElem.getAttribute('type');
// any method block types look like: <block type="_any_ImageSprite_MoveTo" inline="false">
var splitComponent = blockType.split('_');
if (splitComponent.length > 3) {
// This happens when someone puts an _ in a block name!
var ctemp = splitComponent.slice(-2);
splitComponent = [splitComponent.slice(0, -2).join('_'), ctemp.pop(), ctemp.pop()];
}
var componentType = splitComponent[2];
var method=splitComponent[3];
// ok, we have all the info, now we can override the old event attribute with 'event'
blockElem.setAttribute('type','component_method');
// <mutation component_type="Canvas" instance_name="Canvas1" event_name="Dragged"></mutation>
// add mutation tag
var mutationElement = goog.dom.createElement('mutation');
mutationElement.setAttribute('method_name', method);
mutationElement.setAttribute('component_type',componentType);
mutationElement.setAttribute('is_generic','true');
blockElem.insertBefore(mutationElement,blockElem.firstChild);
};
/**
* v17_translateComponentGet is called when we know we have a component get, e.g.
* TinyDB_component as the block
*/
Blockly.Versioning.v17_translateComponentGet = function(blockElem, workspace) {
// the type attribute is "instance_method"
var blockType = blockElem.getAttribute('type');
// block type looks like: <block type="TinyDB1_component" ..> note an instance
// not a type as you'd expect
var splitComponent = blockType.split('_');
if (splitComponent.length > 2) {
// This happens when someone puts an _ in a block name!
splitComponent = [splitComponent.slice(0, -1).join('_'), splitComponent.pop()];
}
var instance = splitComponent[0];
// if we got here splitComponent[1] must be "component"
// Paul has a function to convert instance to type
var componentType = workspace.getComponentDatabase().instanceNameToTypeName(instance);
// ok, we have all the info, now we can override the old event attribute with 'event'
blockElem.setAttribute('type','component_component_block');
// <mutation component_type="Canvas" instance_name="Canvas1" event_name="Dragged"></mutation>
// add mutation tag
var mutationElement = goog.dom.createElement('mutation');
//mutationElement.setAttribute('component_type',component);
mutationElement.setAttribute('instance_name', instance);
mutationElement.setAttribute('component_type',componentType);
blockElem.insertBefore(mutationElement,blockElem.firstChild);
};
/**
* v17_translateSetGetProperty is called when we know we have a get or set on an instance
*/
Blockly.Versioning.v17_translateSetGetProperty = function(blockElem, workspace) {
// the type attribute is "instance_setproperty" or "component_getproperty"
var blockType = blockElem.getAttribute('type');
// set block look like: <block type="Button1_setproperty" x="132" y="72">
var splitComponent=blockType.split('_');
if (splitComponent.length > 2) {
// This happens when someone puts an _ in a block name!
splitComponent = [splitComponent.slice(0, -1).join('_'), splitComponent.pop()];
}
var instance = splitComponent[0];
var type=splitComponent[1]; //setproperty or getproperty
// Paul has a function to convert instance to type
var componentType = workspace.getComponentDatabase().instanceNameToTypeName(instance);
// grab titles to find the particular property. There is a title elem with
// a "PROP" attribute right under and within the block element itself
// There might be many titles, but we grab the first.
var titles = blockElem.getElementsByTagName('title');
var propName = 'unknown';
for (var i = 0, len = titles.length; i < len; i++)
{
if (titles[i].getAttribute('name') == 'PROP') {
propName = titles[i].textContent;
break;
}
}
// ok, we have all the info, now we can override the old event attribute with 'event'
blockElem.setAttribute('type','component_set_get');
// <mutation component_type="Canvas" instance_name="Canvas1" event_name="Dragged"></mutation>
// add mutation tag
var mutationElement = blockElem.getElementsByTagName('mutation')[0];
//mutationElement.setAttribute('component_type',component);
mutationElement.setAttribute('instance_name', instance);
mutationElement.setAttribute('property_name', propName);
if (type == 'setproperty') {
mutationElement.setAttribute('set_or_get', 'set');
} else {
mutationElement.setAttribute('set_or_get','get');
}
mutationElement.setAttribute('component_type', componentType);
mutationElement.setAttribute('is_generic','false');
// old blocks had a 'yailtype' attribute in mutator, lets get rid of
if (mutationElement.getAttribute('yailtype') != null)
mutationElement.removeAttribute('yailtype');
};
/**
* v17_translateComponentSetGetProperty is called when we know we have a get or set on a
* generic component.
*/
Blockly.Versioning.v17_translateComponentSetGetProperty = function(blockElem) {
// the type attribute is "component_setproperty" or "component_getproperty"
// where component is a type, e.g., Button
var blockType = blockElem.getAttribute('type');
// set block looks like: <block type="Button_setproperty" >
var splitComponent = blockType.split('_');
if (splitComponent.length > 2) {
// This happens when someone puts an _ in a block name!
splitComponent = [splitComponent.slice(0, -1).join('_'), splitComponent.pop()];
}
var type = splitComponent[1]; //setproperty or getproperty
var componentType = splitComponent[0];
// grab titles to find the particular property
var titles = blockElem.getElementsByTagName('title');
var propName = 'unknown';
for (var i = 0, len = titles.length; i < len; i++)
{
if (titles[i].getAttribute('name') == 'PROP') {
propName = titles[i].textContent;
break;
}
}
// ok, we have all the info, now we can override the old event attribute with 'event'
blockElem.setAttribute('type','component_set_get');
// <mutation component_type="Canvas" instance_name="Canvas1" event_name="Dragged"></mutation>
// add mutation tag
var mutationElement = blockElem.getElementsByTagName('mutation')[0];
//mutationElement.setAttribute('component_type',component);
mutationElement.setAttribute('property_name', propName);
if (type == 'setproperty') {
mutationElement.setAttribute('set_or_get', 'set');
} else {
mutationElement.setAttribute('set_or_get','get');
}
mutationElement.setAttribute('component_type',componentType);
mutationElement.setAttribute('is_generic','true');
// old blocks had a 'yailtype' attribute in mutator, lets get rid of
if (mutationElement.getAttribute('yailtype')!=null)
mutationElement.removeAttribute('yailtype');
};
/******************************************************************************
General helper methods for upgrades go in this section
******************************************************************************/
/**
* @authors wolber@usfca.edu (David Wolber) & fturbak@wellesley.edu (Lyn Turbak)
* changeEventParameterName changes any event handler parameter name. Note this code is
* performed on Blockly blocks after xml has been loaded (when it's much easier
* to correctly handle the subtleties of renaming involving lexical scoping).
*
* There are complications due to handling this renaming in the presence of i18n.
* In particular, all references to the old localized parameter name within
* the body must be renamed to new localized parameter names in a way that
* avoids any accidental variable capture by local variables within the body.
*/
Blockly.Versioning.changeEventParameterName = function(componentType, eventName,
oldParamName, newParamName) {
return function (blocksRep) {
var mainWorkspace = Blockly.Versioning.ensureWorkspace(blocksRep);
var blocks = mainWorkspace.getAllBlocks();
for (var i = 0; i < blocks.length; i++) {
var block = blocks[i];
if (block.blockType === 'event') {
if ((block.eventName === eventName) && (block.typeName === componentType)) {
// Event params will have been saved previously in XML using oldParamName.
// Find i18n translation of oldParamName within block
var eventParamDict = Blockly.LexicalVariable.eventParameterDict(block);
var oldParamTranslation = eventParamDict[oldParamName];
if (oldParamTranslation) { // Is oldParamName referenced in event body?
// If not, no further action is required.
// For consistency, update .eventparam for blocks in which it's oldParamName to newParamName
var descendants = block.getDescendants();
for (var j = 0, descendant; descendant = descendants[j]; j++) {
if (descendant.eventparam && (descendant.eventparam == oldParamName)) {
descendant.eventparam = newParamName;
}
}
// Find i18n translation of newParamName
var newParamTranslation = mainWorkspace.getComponentDatabase().getInternationalizedParameterName(newParamName);
// Event handler block will have been automatically created with newParamTranslation
// So need to rename all occurrences of oldParamTranslation within its body
// to newParamTranslation.
var childBlocks = block.getChildren(); // should be at most one body block
for (var k = 0, childBlock; childBlock = childBlocks[k]; k++) {
var freeSubstitution = new Blockly.Substitution([oldParamTranslation], [newParamTranslation]);
// renameFree does the translation.
Blockly.LexicalVariable.renameFree(childBlock, freeSubstitution);
}
}
}
}
}
return mainWorkspace;
}
};
/**
* Rename all blocks with oldType to newType
* @param oldBlockType: string name of old block type
* @param newBlockType: string name of new block type
*
* @author fturbak@wellesley.edu (Lyn Turbak)
*/
Blockly.Versioning.renameBlockType = function(oldBlockType, newBlockType) {
return function (blocksRep) {
var dom = Blockly.Versioning.ensureDom(blocksRep);
var allBlocks = dom.getElementsByTagName('block');
for (var i = 0, im = allBlocks.length; i < im; i++) {
var blockElem = allBlocks[i];
var blockType = blockElem.getAttribute('type');
if (blockType == oldBlockType) {
blockElem.setAttribute('type', newBlockType);
}
}
return dom; // Return the modified dom, as required by the upgrading structure.
}
};
/**
* @param componentType: name of component type for method
* @param methodName: name of method
* @param argumentIndex: index of the default argument block
* @param defaultXMLArgumentBlockText: string with XML for argument block
* @returns {function(Element|Blockly.Workspace)} a function that maps a blocksRep (An XML DOM or
* workspace) to a modified DOM in which the default argument block has been added to every
* specified method call.
*
* @author fturbak@wellesley.edu (Lyn Turbak)
*
*/
Blockly.Versioning.addDefaultMethodArgument = function(componentType, methodName, argumentIndex, defaultXMLArgumentBlockText) {
return function (blocksRep) {
var dom = Blockly.Versioning.ensureDom(blocksRep);
// For each matching method call block, change it to have new argument block for value child ARG<argumentIndex>
var methodCallBlocks = Blockly.Versioning.findAllMethodCalls(dom, componentType, methodName);
for (var b = 0, methodCallBlock; methodCallBlock = methodCallBlocks[b]; b++) {
var childBlocks = goog.dom.getChildren(methodCallBlock);
var insertionChild = null; // Value with name ARG<N> we want to insert default before
for (var c = 0, child; child = childBlocks[c]; c++) {
if (child.tagName == "VALUE") {
var name = child.getAttribute("name");
if (name.indexOf("ARG") == 0) {
var index = parseInt(name.split("ARG")[1]);
if (index == argumentIndex) {
// There is already an argument block at the given index.
// Don't replace an existing block, but use console.log to report this situation.
console.log("Already a child block at index " + argumentIndex
+ " in Blockly.Versioning.addDefaultMethodArgument(" + componentType
+ ", " + methodName,
+ ", " + argumentIndex,
+ ", " + defaultXMLArgumentBlockText + ")");
} else if (index > argumentIndex) {
insertionChild = child;
break; // exit loop once we find first bigger argument element
}
}
}
}
// Create the new argument block for this method call
// (careful: can't share one dom element across multiple calls!)
var argumentElement = goog.dom.createElement('value');
argumentElement.setAttribute('name', 'ARG' + argumentIndex);
var argumentChild = Blockly.Versioning.xmlBlockTextToDom(defaultXMLArgumentBlockText);
argumentElement.insertBefore(argumentChild, null); // The first and only child (a block)
// Insert the new argument block
methodCallBlock.insertBefore(argumentElement, insertionChild);
}
return dom; // Return the modified dom, as required by the upgrading structure.
}
};
/**
* Rename all event handler blocks for a given component type and event name.
* @param componentType: name of component type for event
* @param oldEventName: name of event
* @param newEventName: new name of event
* @returns {function(Element|Blockly.Workspace)} a function that maps a blocksRep (an XML DOM or
* workspace) to a modified DOM in which every specified event block has been renamed.
*
* @author ewpatton@mit.edu (Evan W. Patton)
*/
Blockly.Versioning.changeEventName = function(componentType, oldEventName, newEventName) {
return function (blocksRep) {
var dom = Blockly.Versioning.ensureDom(blocksRep);
var eventHandlerBlocks = Blockly.Versioning.findAllEventHandlers(dom, componentType, oldEventName);
for (var b = 0, eventBlock; eventBlock = eventHandlerBlocks[b]; b++) {
var mutation = Blockly.Versioning.firstChildWithTagName(eventBlock, 'mutation');
mutation.setAttribute('event_name', newEventName);
}
return dom;
};
};
/**
* Rename all method call blocks for a given component type and method name.
* @param componentType: name of component type for method
* @param oldMethodName: name of method
* @param newMethodName: new name of method
* @returns {function(Element|Blockly.Workspace)} a function that maps a blocksRep (An XML DOM or
* workspace) to a modified DOM in which every specified method call has been renamed.
*
* @author lizlooney@google.com (Liz Looney)
*/
Blockly.Versioning.changeMethodName = function(componentType, oldMethodName, newMethodName) {
return function (blocksRep) {
var dom = Blockly.Versioning.ensureDom(blocksRep);
// For each matching method call block, change the method_name attribute.
var methodCallBlocks = Blockly.Versioning.findAllMethodCalls(dom, componentType, oldMethodName);
for (var b = 0, methodCallBlock; methodCallBlock = methodCallBlocks[b]; b++) {
var mutation = Blockly.Versioning.firstChildWithTagName(methodCallBlock, "mutation");
mutation.setAttribute("method_name", newMethodName);
}
return dom; // Return the modified dom, as required by the upgrading structure.
}
};
/**
* Rename all property get/set blocks for a given component type and property name.
* @param componentType: name of component type for property
* @param oldPropertyName: name of property
* @param newPropertyName: new name of property
* @returns {function(Element|Blockly.Workspace)} a function that maps a blocksRep (An XML DOM or
* workspace) to a modified DOM in which every specified property get/set has been renamed.
*
* @author lizlooney@google.com (Liz Looney)
*/
Blockly.Versioning.changePropertyName = function(componentType, oldPropertyName, newPropertyName) {
return function (blocksRep) {
var dom = Blockly.Versioning.ensureDom(blocksRep);
// For each matching property block, change the property_name attribute.
var propertyBlocks = Blockly.Versioning.findAllPropertyBlocks(dom, componentType, oldPropertyName);
for (var b = 0, propertyBlock; propertyBlock = propertyBlocks[b]; b++) {
var mutation = Blockly.Versioning.firstChildWithTagName(propertyBlock, "mutation");
mutation.setAttribute("property_name", newPropertyName);
var children = goog.dom.getChildren(propertyBlock);
for (var c = 0, child; child = children[c]; c++) {
if (child.tagName.toUpperCase() == "FIELD") {
if (child.getAttribute("name") == "PROP") {
if (child.textContent == oldPropertyName) {
child.textContent = newPropertyName;
}
}
}
}
}
return dom; // Return the modified dom, as required by the upgrading structure.
}
};
/**
* Returns the list of top-level blocks that are event handlers for the given eventName for
* componentType.
* @param dom DOM for XML workspace
* @param componentType name of the component type for event
* @param eventName name of event
* @returns {Array.<Element>} a list of XML elements for the specified event handler blocks.
*
* @author ewpatton@mit.edu (Evan W. Patton)
*/
Blockly.Versioning.findAllEventHandlers = function (dom, componentType, eventName) {
var eventBlocks = [];
for (var i = 0; i < dom.children.length; i++) {
var block = dom.children[i];
if (block.tagName === 'block' && block.getAttribute('type') === 'component_event') {
var mutation = Blockly.Versioning.firstChildWithTagName(block, 'mutation');
if (!mutation) {
throw 'Did not find expected mutation child in Blockly.Versioning.findAllEventHandlers ' +
'with componentType = ' + componentType + ' and eventName = ' + eventName;
} else if ((mutation.getAttribute('component_type') === componentType) &&
(mutation.getAttribute('event_name') === eventName)) {
eventBlocks.push(block);
}
}
}
return eventBlocks;
};
/**
* @param dom: DOM for XML workspace
* @param componentType: name of component type for method
* @param methodName: name of method
* @returns {Element[]} a list of HTML elements for the specfied method call blocks.
*
* @author fturbak@wellesley.edu (Lyn Turbak)
*
*/
Blockly.Versioning.findAllMethodCalls = function (dom, componentType, methodName) {
var allBlocks = dom.getElementsByTagName('block');
var callBlocks = [];
for (var b = 0, block; block = allBlocks[b]; b++) {
if (block.getAttribute('type') == "component_method") {
var mutation = Blockly.Versioning.firstChildWithTagName(block, "mutation");
if (!mutation) {