arcs.js
61.1 KB
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
// ARCS.js : 27/6/2014 16:00
// handling dependencies
//"use strict";
/**
* Main source: describes all the methods needed by the ARCS engine
* @file
*/
/**
* Defines all elements needed for Augmented Reality Component System
* @namespace
*/
var ARCS = ARCS || {};
/******************************************************************************
* Helper functions to determine environment
* ***************************************************************************/
/**
* @return {boolean} true if ARCS is run in a node.js environment
*/
ARCS.isInNode = function () {
return (typeof require === 'function' && require.resolve);
};
/******************************************************************************
* Component implementation
* ***************************************************************************/
/**
* Defines main traits of components in a namespace regrouping important methods
*
* @namespace
*/
ARCS.Component = {
/** Error message */
SourceIsNotComponent : {message : "Source is not a component"},
/** Error message */
UndefinedSignal : {message : "Signal is not defined"},
/** Error message */
UndefinedSlot : {message : "Slot is not defined"},
/**
* External constructor: give component traits to any constructor.
*
* Component traits are the following:
* <ul>
* <li>Slot functions listed in an array;</li>
* <li>A signal list described in an array;</li>
* <li>A method returning the slot list;</li>
* <li>A method returnung the signal list;</li>
* <li>An emit method, to trigger signals by their names;</li>
* <li>A slot method to cast an internal method to a slot;</li>
* <li>A signal mehtod to register a possible signal.</li>
* </ul>
* @param name {string} Class name to transform to a component
* @param sltList {string[]} names of functions designated as slots, may be empty.
* @param sgnList {string[]} names of functions designated as signals, may be empty.
*/
create : function (name, sltList, sgnList) {
if (name.prototype === undefined) {
console.error("Cannot create such a component");
return 0;
}
name.prototype.slots = [];
name.prototype.signals = {};
name.slotList = function () {
return name.prototype.slots;
};
name.prototype.slotList = function () {
return name.prototype.slots;
};
name.prototype.signalList = function () {
var res = [], i;
for (i in name.prototype.signals) {
res.push(i);
}
return res;
};
name.signalList = function () {
return name.prototype.signalList();
};
name.prototype.emit = function (signal) {
var slt, func, obj;
var args = Array.prototype.slice.call(arguments,1);
for (slt in this.signals[signal]) {
func = this.signals[signal][slt].func;
obj = this.signals[signal][slt].obj;
func.apply(obj, args);
}
};
name.slot = function (slot, func) {
var i;
if (slot instanceof Array) {
for (i = 0; i < slot.length; i++) {
name.prototype.slots.push(slot[i]);
}
} else {
name.prototype.slots.push(slot);
if (func !== undefined) {
name.prototype[slot] = func;
}
}
};
name.signal = function (signal) {
var i;
if (signal instanceof Array) {
for (i = 0; i < signal.length; i++) {
name.prototype.signals[signal[i]] = 1;
}
} else {
name.prototype.signals[signal] = 1;
}
};
// code for returning component, and or completing its definition
if (sltList !== undefined) {
name.slot(sltList);
}
if (sgnList !== undefined) {
name.signal(sgnList);
}
return name;
},
/**
* Checks if the given prototype has traits of a component
* @param name {string} name of the prototype
*/
check : function (name) {
if (name.prototype === undefined) {
return false;
}
if (name.prototype.signals === undefined ||
name.prototype.slots === undefined) {
return false;
}
return true;
},
/**
* Connects two different components by using their signal and slots
* @param source {object} component sending data
* @param signal {string} name of the signal to connect
* @param destination {object} component receiving data
* @param slt {string} name of the slot to connect
*/
connect : function (source, signal, destination, slt) {
var orig, p;
// here we can perform various checks.
if (source.signals === undefined) {
throw ARCS.Component.SourceIsNotComponent;
}
if (source.signals[signal] === undefined) {
throw ARCS.Component.UndefinedSignal;
}
if (destination[slt] === undefined) {
throw ARCS.Component.UndefinedSlot;
}
// we must also check if the signals dispose of their own implementation
if (!source.hasOwnProperty('signals')) {
// otherwise, we should clone it so that each component dispose of its
// own signal copy.
orig = source.signals;
source.signals = {};
for (p in orig) {
source.signals[p] = [];
}
}
source.signals[signal].push({obj: destination, func: destination[slt]});
},
/**
* Diconnects a signal/slot connection between two components
* @param source {object} component sending data
* @param signal {string} name of the signal to connect
* @param destination {object} component receiving data
* @param slt {string} name of the slot to connect
*/
disconnect : function (source, signal, destination, slt) {
var i;
for (i = 0; i < source.signals[signal].length; i++) {
if (source.signals[signal][i].obj === destination) {
if (source.signals[signal][i].func === destination[slt]) {
source.signals[signal].splice(i, 1);
i--;
}
}
}
},
/**
* Invokes a specific slot of a given component
* @param destination {object} component upon which invocation is performed
* @param slt {string} name of the slot to invoke
* @param value {mixed} value to input
*/
invoke : function (destination, slt, value) {
if (destination[slt] === undefined) {
throw ARCS.Component.UndefinedSlot;
}
var func = destination[slt];
func.apply(destination, value);
},
/**
* Specific hook that can be called when initializing a component
* @param component {object} prototype of the component
* @param obj {object} the actual object
*/
config : function (component, obj) {
if (typeof component.config === 'function') {
component.config(obj);
}
}
};
/**
* @class ARCS.Context
* @classdesc Class representing a context containing libraries and components
* used by different parts of the framework.
* @param ctx {object} an object representing data for the context.
*/
ARCS.Context = function( ctx ) {
var components = {};
var constants = {};
var factories = {};
var libraries = [];
//var depLibPromises=[];
var self = this;
var loadLibraries;
var loadDataFile;
var promiseLibrary;
var instanciateComponents;
factories.StateMachine = ARCS.Statemachine;
if (ctx !== undefined) {
libraries = ctx.libraries;
var p;
for (p in ctx.components) {
if (ctx.components.hasOwnProperty(p)) {
components[p] = ctx.components[p];
}
}
if (ctx.constants !== undefined) {
for (p in ctx.constants) {
if (ctx.constants.hasOwnProperty(p)) {
constants[p] = ctx.constants[p];
}
}
}
}
var loadDataFile =async function(fileName) {
var dataPromise ;
if (ARCS.isInNode()) {
return new Promise(function (resolve, reject) {
var dep = require(fileName);
if (dep !== undefined) {
resolve(dep);
} else {
reject("[ARCS] File not found");
}
});
} else {
var client = await fetch(fileName);
return client.json();
}
};
var loadLibraries = function () {
var i;
// we will use different instances of require either the one of node
// or the one from require.js
ARCS.Context.currentContext = self;
var res=[];
for(i=0; i < libraries.length; i++) {
res.push(self.loadLibrary(libraries[i]));
}
return Promise.all(res);
};
var instanciateComponents = function() {
var p, promises=[];
for (p in components) {
if (components.hasOwnProperty(p)) {
if (factories[components[p].type] === undefined) {
console.error("[ARCS] Factory " + components[p].type + " not found.");
console.error("[ARCS] Context dump follows: ", libraries, components, constants);
return ;
}
var factory = factories[components[p].type];
//console.log("instanciating ", p);
try {
if (components[p].value !== undefined || components[p].url !== undefined || components[p].ref !== undefined) {
if (components[p].value !== undefined) {
components[p].instance = new factory(components[p].value);
}
if (components[p].url !== undefined) {
// we need currying here !
var delayInstanciation = function(p,factory) {
return function(obj) {
console.log("instanciating from data file");
components[p].instance = new factory(obj);
return Promise.resolve();
}
};
console.log("loading data file", components[p].url);
promises.push(
loadDataFile(components[p].url).then(delayInstanciation(p,factory))
);
}
if (components[p].ref !== undefined) {
if (constants[components[p].ref] !== undefined) {
components[p].instance = new factory(constants[components[p].ref]);
}
}
} else {
components[p].instance = new factory();
}
} catch(e) { console.error("[ARCS] Component of type ", p, " not instanciated.", e);}
}
}
return Promise.all(promises);
};
/**
* loads a given library and, if necessary, launches a call back function
* when the library is loaded.
* @param libName {string} name of the library to load
* @param cbFunction {function} callback function to call when library is loaded
*/
this.loadLibrary = function (libName, cbFunction) {
var libUrl = libName, libActualName = libName;
ARCS.Context.currentContext = self;
if (typeof libName !== "string") {
libActualName = libName.name;
libUrl = libName.url;
}
if (libraries.indexOf(libActualName) < 0) {
libraries.push(libActualName);
}
// TODO promisify call to cbFunction
return import(libUrl).then( function(module) {
// TODO insert here component factories
for (p in module.default) {
if (module.default.hasOwnProperty(p)) {
ARCS.Context.currentContext.setFactory(p,module.default[p]);
}
}
if (cbFunction !== undefined) {
cbFunction();
}
}).catch( function(msg) { console.error("[ARCS] Trouble loading '",libUrl,"' with reason -", msg) });
};
/**
* @return the component list stored inside context
*/
this.getComponentList = function () {
var list = Object.keys(components);
var i;
for (i = 0; i < list.length; i++) {
if ( ! components.hasOwnProperty(list[i])) {
list.splice(i--,1);
}
}
return list;
};
this.getConstant = function(cName) {
/*if (!constants.hasOwnProperty(cName)) {
return undefined;
}*/
return constants[cName];
};
// to determine if really needed
this.getComponentType = function(cName) {
/*if (!components.hasOwnProperty(cName))
return undefined;*/
if (components[cName] === undefined) return undefined;
return components[cName].type;
};
// to determine if really needed
this.getComponentValue = function(cName) {
/*if (!components.hasOwnProperty(cName))
return undefined;*/
if (components[cName] === undefined) return undefined;
return components[cName].value;
};
// to determine if really needed
this.getComponent = function (cName) {
/*if (!components.hasOwnProperty(cName))
return undefined;*/
if (components[cName] === undefined) return undefined;
return components[cName].instance;
};
// to determine if really needed
this.getComponentName = function (cmp) {
var i, keys;
keys = components.getComponentList();
for(i = 0; i < keys.length; i++) {
if (components[keys[i]].instance === cmp) {
return keys[i];
}
}
return undefined;
};
this.setFactory = function(key, factory ) {
factories[key] = factory;
};
this.toJSON = function () {
var res = {}, p;
for (p in components) {
if (components.hasOwnProperty(p)) {
res[p] = { type: components[p].type, value: components[p].value };
}
}
return res;
};
// functions used with editor
this.setComponentValue = function (cName, cValue) {
components[cName].value = cValue; // to modifiy
};
this.addComponent = function (cName, cType, cValue) {
var component;
components[cName] = {};
components[cName].type = cType;
components[cName].value = cValue;
var factory = factories[cType];
if (factory !== undefined) {
component = new factory(cValue);
}
components[cName].instance = component;
};
this.removeComponent = function (cName) {
delete components[cName];
};
// see if it is needed
this.getFactory = function (fName) {
return factories[fName];
};
// see if it is needed
this.getFactoryList = function() {
return Object.keys(factories);
};
// this should return a promise !
this.instanciate = function () {
//! TODO
return loadLibraries().then(instanciateComponents)
.catch(function(msg) { console.error("[ARCS] Trouble instanciating context", msg); });
};
var chainPrototype = function (obj, proto) {
// this stunt seems better than using
// Object.setPrototypeOf or using [object].__proto__
// due to javascript engine optimizations
var newObj = Object.create(proto);
var p ;
for (p in obj) {
if (obj.hasOwnProperty(p)) {
newObj[p] = obj[p];
}
}
return newObj;
};
this.chain = function (cmp,cst,fct) {
// cmp and cst are the children context elements
// we need to chain contexts properly.
return [ chainPrototype(cmp, components),
chainPrototype(cst, constants),
chainPrototype(fct, factories)
];
};
this.setParent = function (ctx) {
// chaining factories is also important if contexts are repeating
// the same things
if (ctx === undefined) return;
var v = ctx.chain(components, constants, factories);
components = v[0];
constants = v[1];
factories = v[2];
};
};
/** pseudo-singleton to current context being used */
ARCS.Context.currentContext = null;
/******************************************************************************
* Invocation implementation
* ***************************************************************************/
/**
* Defines an invocation
* @param destination {object} component on which to perform invocation
* @param slot {string} name of the slot
* @param value {mixed} value passed to the invoked slot
* @constructor
*/
ARCS.Invocation = function (destination, slot, value) {
this.getDestination = function () {
return destination;
};
this.getSlot = function () {
return slot;
};
this.getValue = function () {
return value;
};
this.invoke = function () {
var func = destination[slot];
if (func === undefined) {
console.error("Undefined slot %s of component %s", slot, destination);
return;
}
func.apply(destination, value);
};
};
/**
* Helper function that casts an invocation from a description
* @param obj {object} a raw description of the invocation
* @param context {object} the context in which this invocation takes place.
* @return an invocation
*/
ARCS.Invocation.cast = function (obj, context) {
if (obj.value !== undefined) {
var component = context.getComponent(obj.destination);
if (component === undefined) {
console.error("[ARCS] Destination ",obj.destination, " is undefined");
}
return new ARCS.Invocation(component, obj.slot, obj.value);
}
// this one looks odd, seems there is a failure in the logic.
if (obj.ref !== undefined) {
return new ARCS.Invocation(context.getComponent(obj.destination), obj.slot, context.getConstant(obj.ref));
}
};
/*ARCS.Invocation.revert = function(obj, context) {
return {
destination: context
};
};*/
ARCS.Invocation.PRE_CONNECTION = 0;
ARCS.Invocation.POST_CONNECTION = 1;
ARCS.Invocation.CLEAN_UP = 2;
/******************************************************************************
* Connection implementation
* ***************************************************************************/
/**
* Defines a connection between two components
* @param source {object} component at the source
* @param signal {string} name of the signal emitting data
* @param destination {object} component at the destination
* @param slot {string} name of the signal receiving data
* @class
*/
ARCS.Connection = function (source, signal, destination, slot) {
/**
* Connects two components as described in this object
* @function ARCS.Connection#connect
*/
this.connect = function () {
try {
ARCS.Component.connect(source, signal, destination, slot);
} catch(e) { console.log(e, source, signal, destination, slot); }
};
/**
* Disconnects a signal/slot connection between the two components
* described in this object.
*/
this.disconnect = function () {
ARCS.Component.disconnect(source, signal, destination, slot);
};
this.getSource = function() {
return source;
};
this.getDestination = function () {
return destination;
};
this.getSlot = function () {
return slot;
};
this.getSignal = function () {
return signal;
};
};
/**
* Helper function that casts a connection from a description
* @param obj {object} a raw description of the connection
* @param context {object} the context in which this connection takes place.
* @return a connection
*/
ARCS.Connection.cast = function (obj, context) {
return new ARCS.Connection(context.getComponent(obj.source)/*[obj.source].instance*/, obj.signal,
context.getComponent(obj.destination)/*[obj.destination].instance*/, obj.slot);
};
/******************************************************************************
* Sheet implementation
* ***************************************************************************/
/**
* Constructs a sheet
* @param context {object} a context object
* @class
* @classdesc A Sheet is an operationnal configuration in an application. It
* contains many things: multiple sets of {@link ARCS.Invocation}
* performed at different times
* and a set of {@link ARCS.Connection}. Sheets have two high level operations:
* activation and deactivation.
*/
ARCS.Sheet = function (ctx /*context*/) {
var context = new ARCS.Context();
var preconnections = [], postconnections = [], cleanups = [], connections = [],
invokePreconnections, invokePostconnections, invokeCleanups,
connect, disconnect, getComponentName,
preCount = 0, postCount = 0, cleanCount = 0, connCount = 0;
invokePreconnections = function () {
var i;
for (i = 0; i < preconnections.length; i++) {
preconnections[i].invoke();
}
};
invokePostconnections = function () {
var i;
for (i = 0; i < postconnections.length; i++) {
postconnections[i].invoke();
}
};
invokeCleanups = function () {
var i;
for (i = 0; i < cleanups.length; i++) {
cleanups[i].invoke();
}
};
connect = function () {
var i;
for (i = 0; i < connections.length; i++) {
connections[i].connect();
}
};
disconnect = function () {
var i;
for (i = 0; i < connections.length; i++) {
connections[i].disconnect();
}
};
this.setContext = function (ctx) {
context = ctx;
};
/**
* Activates this sheet. Pre-connection invocations are peformed, then
* connections are established and post-connection invocations are finally
* performed.
*/
this.activate = function () {
context.instanciate().then(function() {
invokePreconnections();
connect();
invokePostconnections();
});
};
/**
* Deactivates this sheet. Connections are removed and then cleanup invocations
* are performed.
*/
this.deactivate = function () {
disconnect();
invokeCleanups();
};
this.addPreConnection = function (obj) {
var pre = ARCS.Invocation.cast(obj, context);
pre.id = preCount++;
preconnections.push(pre);
return pre.id;
};
this.addPostConnection = function (obj) {
var post = ARCS.Invocation.cast(obj, context);
post.id = postCount++;
postconnections.push(post);
return post.id;
};
this.addCleanup = function (obj) {
var cleanup = ARCS.Invocation.cast(obj, context);
cleanup.id = cleanCount++;
cleanups.push(cleanup);
return cleanup.id;
};
this.addConnection = function (obj) {
var connection = ARCS.Connection.cast(obj, context);
connection.id = connCount++;
connections.push(connection);
return connection.id;
};
var removeItem = function(id, tab) {
var i = tab.length;
while ( i-- && tab[i].id !== id );
if (i >= 0) {
tab.splice(i,1);
} else {
console.warn("Could not remove data with id", id);
}
};
this.removePreConnection = function (id) {
removeItem(id, preconnections);
};
this.removePostConnection = function (id) {
removeItem(id, postconnections);
};
this.removeCleanup = function (id) {
removeItem(id, cleanups);
};
var changeItem = function(id, value, tab) {
var i = tab.length;
while ( i-- && tab[i].id !== id );
if (i >= 0) {
tab[i].value = value;
}
};
this.changePreConnection = function (id, value) {
changeItem(id, value, preconnections);
};
this.changePostConnection = function (id, value) {
changeItem(id, value, postconnections);
};
this.changeCleanup = function (id, value) {
changeItem(id, value, cleanups);
};
this.removeConnection = function (id) {
removeItem(id, connections);
};
var swapItems = function (id1, id2, tab) {
var item;
var i = tab.length, j = tab.length;
while( i-- && tab[i].id !== id1 ) ;
while( j-- && tab[j].id !== id2 ) ;
if (i >= 0 && j >= 0) {
item = tab[i];
tab[i] = tab[j];
tab[j] = item;
tab[i].id = id1;
tab[j].id = id2;
}
};
this.swapConnections = function (id1, id2) {
swapItems(id1, id2, connections);
};
this.swapCleanups = function (id1, id2) {
swapItems(id1, id2, cleanups);
};
this.swapPreConnections = function (id1, id2) {
swapItems(id1, id2, preconnections);
};
this.swapPostConnections = function (id1, id2) {
swapItems(id1, id2, postconnections);
};
var cacheConnectionsInvocations = function(object) {
var i = 0, castInvocation = ARCS.Invocation.cast, castConnection = ARCS.Connection.cast;
for (i = 0; i < object.preconnections.length; i++) {
preconnections.push(castInvocation(object.preconnections[i], context));
}
for (i = 0; i < object.postconnections.length; i++) {
postconnections.push(castInvocation(object.postconnections[i], context));
}
for (i = 0; i < object.cleanups.length; i++) {
cleanups.push(castInvocation(object.cleanups[i], context));
}
for (i = 0; i < object.connections.length; i++) {
connections.push(castConnection(object.connections[i], context));
}
};
/**
* Imports a structure object describing the content of a sheet.
* @param object {object} structured object describing sheet's content.
*/
this.import = function (object) {
if (object.hasOwnProperty("context")) {
context = new ARCS.Context(object.context);
context.setParent(ctx);
}
// the caching system below should wait for the context to be proper initialized
// todo: there may be a flow here if the instanciation is too long.
context.instanciate().then( function() {
cacheConnectionsInvocations(object);
});
};
var revertInvocation = function (obj) {
return {
destination: context.getComponentName(obj.getDestination()),
slot: obj.getSlot(),
value: obj.getValue()
};
};
var revertConnection = function (obj) {
return {
source: context.getComponentName(obj.getSource()),
signal: obj.getSignal(),
destination: context.getComponentName(obj.getDestination()),
slot: obj.getSlot()
};
};
this.toJSON = function () {
var preconns = [];
var postconns = [];
var conns = [];
var cleans = [];
var i;
for (i = 0; i < connections.length; i++) {
conns.push(revertConnection(connections[i]))
}
for (i = 0; i < preconnections.length; i++) {
preconns.push(revertInvocation(preconnections[i]))
}
for (i = 0; i < postconnections.length; i++) {
postconns.push(revertInvocation(postconnections[i]))
}
for (i = 0; i < cleanups.length; i++) {
cleans.push(revertInvocation(cleanups[i]))
}
return {
preconnections : preconns,
postconnections : postconns,
connections: conns,
cleanups: cleans
};
};
//console.log("setting parent");
context.setParent(ctx);
};
/****************************************************************************
* PEG.js grammar used to generate Parser
****************************************************************************
start
= expr
expr =
left:primary right:( rexpr )+ {
return [ left ].concat(right);
}
/ primary
rexpr =
AND right:primary {
return { and : right };
} /
OR right:primary {
return { or : right} ;
}
primary
= id:id { return id; }
/ "(" expr:expr ")" { return [ expr ]; }
id "id"
= token:$TOKEN { return token.trim() ; }
// tokens
TOKEN = WS [_a-zA-Z][_a-zA-Z0-9]* WS
OPENPAREN = WS "(" WS
CLOSEPAREN = WS ")" WS
AND = WS "&" WS
OR = WS "|" WS
WS = [ \r\n\t]*
******************************************************************************/
ARCS.EventLogicParser = (function() {
/*
* Generated by PEG.js 0.8.0.
*
* http://pegjs.majda.cz/
*/
function peg$subclass(child, parent) {
function ctor() { this.constructor = child; }
ctor.prototype = parent.prototype;
child.prototype = new ctor();
}
function SyntaxError(message, expected, found, offset, line, column) {
this.message = message;
this.expected = expected;
this.found = found;
this.offset = offset;
this.line = line;
this.column = column;
this.name = "SyntaxError";
}
peg$subclass(SyntaxError, Error);
function parse(input) {
var options = arguments.length > 1 ? arguments[1] : {},
peg$FAILED = {},
peg$startRuleFunctions = { start: peg$parsestart },
peg$startRuleFunction = peg$parsestart,
peg$c0 = peg$FAILED,
peg$c1 = [],
peg$c2 = function(left, right) {
return [ left ].concat(right);
},
peg$c3 = function(right) {
return { and : right };
},
peg$c4 = function(right) {
return { or : right} ;
},
peg$c5 = function(id) { return id; },
peg$c6 = "(",
peg$c7 = { type: "literal", value: "(", description: "\"(\"" },
peg$c8 = ")",
peg$c9 = { type: "literal", value: ")", description: "\")\"" },
peg$c10 = function(expr) { return [ expr ]; },
peg$c11 = { type: "other", description: "id" },
peg$c12 = function(token) { return token.trim() ; },
peg$c13 = /^[_a-zA-Z]/,
peg$c14 = { type: "class", value: "[_a-zA-Z]", description: "[_a-zA-Z]" },
peg$c15 = /^[_a-zA-Z0-9]/,
peg$c16 = { type: "class", value: "[_a-zA-Z0-9]", description: "[_a-zA-Z0-9]" },
peg$c17 = "&",
peg$c18 = { type: "literal", value: "&", description: "\"&\"" },
peg$c19 = "|",
peg$c20 = { type: "literal", value: "|", description: "\"|\"" },
peg$c21 = /^[ \r\n\t]/,
peg$c22 = { type: "class", value: "[ \\r\\n\\t]", description: "[ \\r\\n\\t]" },
peg$currPos = 0,
peg$reportedPos = 0,
peg$cachedPos = 0,
peg$cachedPosDetails = { line: 1, column: 1, seenCR: false },
peg$maxFailPos = 0,
peg$maxFailExpected = [],
peg$silentFails = 0,
peg$result;
if ("startRule" in options) {
if (!(options.startRule in peg$startRuleFunctions)) {
throw new Error("Can't start parsing from rule \"" + options.startRule + "\".");
}
peg$startRuleFunction = peg$startRuleFunctions[options.startRule];
}
function text() {
return input.substring(peg$reportedPos, peg$currPos);
}
function offset() {
return peg$reportedPos;
}
function line() {
return peg$computePosDetails(peg$reportedPos).line;
}
function column() {
return peg$computePosDetails(peg$reportedPos).column;
}
function expected(description) {
throw peg$buildException(
null,
[{ type: "other", description: description }],
peg$reportedPos
);
}
function error(message) {
throw peg$buildException(message, null, peg$reportedPos);
}
function peg$computePosDetails(pos) {
function advance(details, startPos, endPos) {
var p, ch;
for (p = startPos; p < endPos; p++) {
ch = input.charAt(p);
if (ch === "\n") {
if (!details.seenCR) { details.line++; }
details.column = 1;
details.seenCR = false;
} else if (ch === "\r" || ch === "\u2028" || ch === "\u2029") {
details.line++;
details.column = 1;
details.seenCR = true;
} else {
details.column++;
details.seenCR = false;
}
}
}
if (peg$cachedPos !== pos) {
if (peg$cachedPos > pos) {
peg$cachedPos = 0;
peg$cachedPosDetails = { line: 1, column: 1, seenCR: false };
}
advance(peg$cachedPosDetails, peg$cachedPos, pos);
peg$cachedPos = pos;
}
return peg$cachedPosDetails;
}
function peg$fail(expected) {
if (peg$currPos < peg$maxFailPos) { return; }
if (peg$currPos > peg$maxFailPos) {
peg$maxFailPos = peg$currPos;
peg$maxFailExpected = [];
}
peg$maxFailExpected.push(expected);
}
function peg$buildException(message, expected, pos) {
function cleanupExpected(expected) {
var i = 1;
expected.sort(function(a, b) {
if (a.description < b.description) {
return -1;
} else if (a.description > b.description) {
return 1;
} else {
return 0;
}
});
while (i < expected.length) {
if (expected[i - 1] === expected[i]) {
expected.splice(i, 1);
} else {
i++;
}
}
}
function buildMessage(expected, found) {
function stringEscape(s) {
function hex(ch) { return ch.charCodeAt(0).toString(16).toUpperCase(); }
return s
.replace(/\\/g, '\\\\')
.replace(/"/g, '\\"')
.replace(/\x08/g, '\\b')
.replace(/\t/g, '\\t')
.replace(/\n/g, '\\n')
.replace(/\f/g, '\\f')
.replace(/\r/g, '\\r')
.replace(/[\x00-\x07\x0B\x0E\x0F]/g, function(ch) { return '\\x0' + hex(ch); })
.replace(/[\x10-\x1F\x80-\xFF]/g, function(ch) { return '\\x' + hex(ch); })
.replace(/[\u0180-\u0FFF]/g, function(ch) { return '\\u0' + hex(ch); })
.replace(/[\u1080-\uFFFF]/g, function(ch) { return '\\u' + hex(ch); });
}
var expectedDescs = new Array(expected.length),
expectedDesc, foundDesc, i;
for (i = 0; i < expected.length; i++) {
expectedDescs[i] = expected[i].description;
}
expectedDesc = expected.length > 1
? expectedDescs.slice(0, -1).join(", ")
+ " or "
+ expectedDescs[expected.length - 1]
: expectedDescs[0];
foundDesc = found ? "\"" + stringEscape(found) + "\"" : "end of input";
return "Expected " + expectedDesc + " but " + foundDesc + " found.";
}
var posDetails = peg$computePosDetails(pos),
found = pos < input.length ? input.charAt(pos) : null;
if (expected !== null) {
cleanupExpected(expected);
}
return new SyntaxError(
message !== null ? message : buildMessage(expected, found),
expected,
found,
pos,
posDetails.line,
posDetails.column
);
}
function peg$parsestart() {
var s0;
s0 = peg$parseexpr();
return s0;
}
function peg$parseexpr() {
var s0, s1, s2, s3;
s0 = peg$currPos;
s1 = peg$parseprimary();
if (s1 !== peg$FAILED) {
s2 = [];
s3 = peg$parserexpr();
if (s3 !== peg$FAILED) {
while (s3 !== peg$FAILED) {
s2.push(s3);
s3 = peg$parserexpr();
}
} else {
s2 = peg$c0;
}
if (s2 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c2(s1, s2);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
if (s0 === peg$FAILED) {
s0 = peg$parseprimary();
}
return s0;
}
function peg$parserexpr() {
var s0, s1, s2;
s0 = peg$currPos;
s1 = peg$parseAND();
if (s1 !== peg$FAILED) {
s2 = peg$parseprimary();
if (s2 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c3(s2);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
if (s0 === peg$FAILED) {
s0 = peg$currPos;
s1 = peg$parseOR();
if (s1 !== peg$FAILED) {
s2 = peg$parseprimary();
if (s2 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c4(s2);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
}
return s0;
}
function peg$parseprimary() {
var s0, s1, s2, s3;
s0 = peg$currPos;
s1 = peg$parseid();
if (s1 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c5(s1);
}
s0 = s1;
if (s0 === peg$FAILED) {
s0 = peg$currPos;
if (input.charCodeAt(peg$currPos) === 40) {
s1 = peg$c6;
peg$currPos++;
} else {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c7); }
}
if (s1 !== peg$FAILED) {
s2 = peg$parseexpr();
if (s2 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 41) {
s3 = peg$c8;
peg$currPos++;
} else {
s3 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c9); }
}
if (s3 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c10(s2);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
}
return s0;
}
function peg$parseid() {
var s0, s1, s2;
peg$silentFails++;
s0 = peg$currPos;
s1 = peg$currPos;
s2 = peg$parseTOKEN();
if (s2 !== peg$FAILED) {
s2 = input.substring(s1, peg$currPos);
}
s1 = s2;
if (s1 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c12(s1);
}
s0 = s1;
peg$silentFails--;
if (s0 === peg$FAILED) {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c11); }
}
return s0;
}
function peg$parseTOKEN() {
var s0, s1, s2, s3, s4;
s0 = peg$currPos;
s1 = peg$parseWS();
if (s1 !== peg$FAILED) {
if (peg$c13.test(input.charAt(peg$currPos))) {
s2 = input.charAt(peg$currPos);
peg$currPos++;
} else {
s2 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c14); }
}
if (s2 !== peg$FAILED) {
s3 = [];
if (peg$c15.test(input.charAt(peg$currPos))) {
s4 = input.charAt(peg$currPos);
peg$currPos++;
} else {
s4 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c16); }
}
while (s4 !== peg$FAILED) {
s3.push(s4);
if (peg$c15.test(input.charAt(peg$currPos))) {
s4 = input.charAt(peg$currPos);
peg$currPos++;
} else {
s4 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c16); }
}
}
if (s3 !== peg$FAILED) {
s4 = peg$parseWS();
if (s4 !== peg$FAILED) {
s1 = [s1, s2, s3, s4];
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
return s0;
}
function peg$parseOPENPAREN() {
var s0, s1, s2, s3;
s0 = peg$currPos;
s1 = peg$parseWS();
if (s1 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 40) {
s2 = peg$c6;
peg$currPos++;
} else {
s2 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c7); }
}
if (s2 !== peg$FAILED) {
s3 = peg$parseWS();
if (s3 !== peg$FAILED) {
s1 = [s1, s2, s3];
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
return s0;
}
function peg$parseCLOSEPAREN() {
var s0, s1, s2, s3;
s0 = peg$currPos;
s1 = peg$parseWS();
if (s1 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 41) {
s2 = peg$c8;
peg$currPos++;
} else {
s2 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c9); }
}
if (s2 !== peg$FAILED) {
s3 = peg$parseWS();
if (s3 !== peg$FAILED) {
s1 = [s1, s2, s3];
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
return s0;
}
function peg$parseAND() {
var s0, s1, s2, s3;
s0 = peg$currPos;
s1 = peg$parseWS();
if (s1 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 38) {
s2 = peg$c17;
peg$currPos++;
} else {
s2 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c18); }
}
if (s2 !== peg$FAILED) {
s3 = peg$parseWS();
if (s3 !== peg$FAILED) {
s1 = [s1, s2, s3];
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
return s0;
}
function peg$parseOR() {
var s0, s1, s2, s3;
s0 = peg$currPos;
s1 = peg$parseWS();
if (s1 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 124) {
s2 = peg$c19;
peg$currPos++;
} else {
s2 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c20); }
}
if (s2 !== peg$FAILED) {
s3 = peg$parseWS();
if (s3 !== peg$FAILED) {
s1 = [s1, s2, s3];
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
return s0;
}
function peg$parseWS() {
var s0, s1;
s0 = [];
if (peg$c21.test(input.charAt(peg$currPos))) {
s1 = input.charAt(peg$currPos);
peg$currPos++;
} else {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c22); }
}
while (s1 !== peg$FAILED) {
s0.push(s1);
if (peg$c21.test(input.charAt(peg$currPos))) {
s1 = input.charAt(peg$currPos);
peg$currPos++;
} else {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c22); }
}
}
return s0;
}
peg$result = peg$startRuleFunction();
if (peg$result !== peg$FAILED && peg$currPos === input.length) {
return peg$result;
} else {
if (peg$result !== peg$FAILED && peg$currPos < input.length) {
peg$fail({ type: "end", description: "end of input" });
}
throw peg$buildException(null, peg$maxFailExpected, peg$maxFailPos);
}
}
return {
SyntaxError: SyntaxError,
parse: parse
};
})();
// this class creates a promise that can be deferred as long as necessary.
// calls to accept or reject will solve the promise.
ARCS.TokenEvent = function() {
var refResolve;
var refReject;
this.promise = new Promise(function(resolve, reject) {
refResolve = resolve;
refReject = reject;
});
this.accept = function() {
refResolve();
};
this.abort = function() {
refReject();
};
};
/* the aim of the transition network is to build a network of promises */
ARCS.TransitionNetwork = function() {
// object storing token events (that is to say references to promises)
this.promise = {};
this.and = function(tn) {
this.promise = Promise.all([this.promise, tn.promise]);
return this;
};
this.or = function(tn) {
this.promise = Promise.race([this.promise, tn.promise]);
return this;
};
};
ARCS.TransitionNetwork.build = function(tree, tokenEvents) {
var res;
var tmpTN;
var rightTN;
if (typeof tree === "string") {
// here we have a terminal string i.e. a token event
var tokenEvent;
if (tokenEvents.hasOwnProperty(tree)) {
tokenEvent = tokenEvents[tree];
} else {
tokenEvents[tree] = tokenEvent = new ARCS.TokenEvent();
}
var tn = new ARCS.TransitionNetwork();
tn.promise = tokenEvent.promise;
return tn;
}
res = ARCS.TransitionNetwork.build(tree[0],tokenEvents);
var i;
for (i=1; i < tree.length; i++) {
if (tree[i].hasOwnProperty('and')) {
rightTN = ARCS.TransitionNetwork.build(tree[i]['and'], tokenEvents);
tmpTN = res.and(rightTN);
} else {
if (tree[i].hasOwnProperty('or')) {
rightTN = ARCS.TransitionNetwork.build(tree[i]['or'], tokenEvents);
tmpTN = res.or(rightTN);
} else {
console.warn('[ARCS] Illegal tree');
}
}
res = tmpTN;
}
return res;
};
/******************************************************************************
* Statemachine implementation
* ***************************************************************************/
/**
* Describes a statemachine
* @param obj {object} an object describing a state machine. If obj is empty then the statemachine is empty
* @class
*/
ARCS.Statemachine = new ARCS.Component.create(function (obj) {
// dynamic construction: properties are initial state that have properties
// that are tokens and value that are the final state
var initial = "", final = "", transitions = {}, currentState = "", self= this;
var astTokens = {}; // it keeps AST from event logic expressions
var tokenEvents = {}; // it keeps promises for tokens.
var network = {};
var addToken = function(t) {
if ( self.slots.indexOf(t) < 0 ) {
self.slots.push(t);
self[t] = function( s ) {
return function() {
self.setToken(s);
};
} (t);
}
};
/* this function aims at preparing transition networks for a given state*/
var setSheet = function(s) {
// we build promise trees using ast
var t;
if (transitions.hasOwnProperty(s)) {
tokenEvents = {};
for (t in transitions[s]) {
if (transitions[s].hasOwnProperty(t)) {
network = ARCS.TransitionNetwork.build(astTokens[t],tokenEvents).promise;
network.then(
function() {
var token;
// clean up remaining promises
for (token in tokenEvents) {
if (tokenEvents.hasOwnProperty(token)) tokenEvents[token].abort();
}
// then activate next sheet
setSheet(transitions[s][t]);
}
);
}
}
}
currentState = s;
self.emit('requestSheet', currentState);
if (currentState === final) {
self.emit('requestTermination');
}
};
/**
* Sets the initial state of the statemachine
* @param string {string} name of the initial state
*/
this.setInitialState = function (string) {
initial = string;
currentState = initial;
};
/**
* Sets the final state of the statemachine
* @param string {string} name of the final state
*/
this.setFinalState = function (string) { final = string; };
/**
* Adds a transition to the state machine
* @param start {string} name of the state at the beginning of the transition
* @param token {string} name of the token triggering the transition
* @param end {string} name of the state reached at the end of the transition
*/
this.addTransition = function (start, token, end) {
var re = /([A-Za-z_]\w*)/g;
var t, tsd, ts, tsc;
try {
var tsd = ARCS.EventLogicParser.parse(token);
if (typeof tsd === "string") {
addToken(tsd);
} else {
while( (t = re.exec(token)) !== null) {
addToken(t[0]);
}
}
astTokens[token] = tsd;
if (transitions[start] === undefined) {
transitions[start] = {};
}
transitions[start][token] = end;
} catch (e) { }
};
/**
* Gives a token to the statemachine. According to its list of transitions
* and the current state, it may trigger a transition
* @param token {string} name of the token
*/
this.setToken = function (token) {
if (tokenEvents.hasOwnProperty(token)) {
tokenEvents[token].accept();
}
};
/**
* Sets transitions from a list of transitions
* @param obj {object[]} list of transitions
*/
this.setTransitions = function (obj) {
// this function is no longuer a simple affectation
// transitions = obj;
var p, t, i;
for (p in obj) {
if (obj.hasOwnProperty(p)) {
for (t in obj[p]) {
if (obj[p].hasOwnProperty(t)) {
this.addTransition(p, t, obj[p][t]);
}
}
}
}
// we will temporay dump properties in order to understand how the statemachine is built
/*
for (p in transitions) {
if (transitions.hasOwnProperty(p)) {
for (t in transitions[p]) {
if (transitions[p].hasOwnProperty(t)) {
console.log("\t" + p + "\t----\t" + t + "\t--->\t" + transitions[p][t]);
}
}
}
}*/
};
/**
* Initialize and starts the statemachine, setting its current state to
* the initial state (by default, it is the departure of the first transition
*/
this.start = function () {
console.log("statemachine", this, initial,obj);
setSheet(initial);
};
// INIT CODE
if (obj !== undefined) {
initial = obj.initial;
final = obj.final;
this.setTransitions(obj.transitions);
currentState = "";
}
},
['setToken'],
['requestSheet', 'requestTermination']
);
/******************************************************************************
* Application implementation
* ***************************************************************************/
/**
* Creates an application runnable by the ARCS engine.
* @class ARCS.Application
* @classdesc The application is the master class of the ARCS engine.
* It is initialized using a structured object (possibly described in JSON,
* see {@link ARCS.Application#import})
* to load all external scripts describing components, instanciate
* all components and then start the application
*/
ARCS.Application = function () {
var context = new ARCS.Context(),
sheets = {},
controller = {},
dependencies = [],
self = this,
currentSheet = "",
preProcess;
/**
* Exports an object representing an application
*/
this.export = function() {
var i;
var description = {
context: context,
controller: context.getComponentName(controller),
sheets: sheets
} ;
// first problem: when loaded by the editor, libraries are not the good ones
//description.context.libraries = libraries;
return description;
};
this.getContext = function () {
return context;
};
this.getSheetList = function() {
return Object.keys(sheets);
};
this.getSheet = function (sName) {
return sheets[sName];
};
this.addSheet = function (sName, sheet) {
sheets[sName] = sheet;
sheet.setContext(context);
};
this.removeSheet = function (sName) {
delete sheets[sName];
};
preProcess = function () {
// first, we should instanciate components
var i, temp, sheetList;
temp = context.getComponent(controller); //[controller].instance;
controller = temp;
// then we should work on sheets
sheetList = Object.keys(sheets);
for (i = 0; i < sheetList.length; i++) {
temp = new ARCS.Sheet(context);
temp.import(sheets[sheetList[i]], context);
sheets[sheetList[i]] = temp;
}
ARCS.Component.connect(controller, "requestSheet", self, "setSheet");
ARCS.Component.connect(controller, "requestTermination", self, "finish");
controller.start();
};
this.setController = function (ctrlName) {
controller = context.getComponent(ctrlName); //[ctrlName].instance;
};
/**
* Sets the current sheet of the application. This method is in fact designed
* as a slot and may be triggered by a statemachine. If a sheet is already the
* current one, then it is deactivated before activating this new sheet.
* This method may warn that it is trying to activate a hollow sheet. It is
* not inherently an error by itself but it may indicate a problem in your
* application.
* @param sheetName {string} name of the sheet to set as a current sheet.
*/
this.setSheet = function (sheetname) {
if (sheets.hasOwnProperty(sheetname)) {
if (currentSheet) {
sheets[currentSheet].deactivate();
}
currentSheet = sheetname;
sheets[currentSheet].activate();
} else {
console.warn('[ARCS] Tried to activate hollow sheet named: ' + sheetname);
}
};
/**
* This is the end my friend. This triggers the end of the application
*/
this.finish = function () {
if (currentSheet) {
sheets[currentSheet].deactivate();
}
};
/**
* Imports a structured object describing the application. The structured object
* may be described itself in a JSON format.
* @param object {object} structured object describing an application.
*
* @example
* // JSON format of an application description
* {
* context : {
* libraries : [ "library1", "library2"],
* components : [
* // this could be also properties from context
* name1: { type: "type", value: "value if needed" }
* ],
* constants : [
* // the same observation applies here
* name1: { representation : {JSON/objectRepresentation ? } }
* ]
* },
* controller : controllerId,
* sheets : {
* sheetId : {
* preconnections : [
* {
* destination: "id",
* slot : "slot name",
* value : JSON/objectRepresentation ?
* }, {...}, {...}
* ],
* postconnections : [
* {
* destination: "id",
* slot : "slot name",
* value : JSON/objectRepresentation ?
* }, {...}, {...}
* ],
* connections : [
* {
* source: "id",
* destination: "id",
* slot: "slot name",
* signal: "signal name"
* }, {...}, {...}
* ],
* cleanups : [
* {
* destination: "id",
* slot : "slot name",
* value : JSON/objectRepresentation ?
* }, {...}, {...}
* ]
* },
* { ... }
* }
* }
*
*/
this.import = function (object) {
context = new ARCS.Context(object.context/*.components*/);
sheets = object.sheets;
controller = object.controller;
if (controller === undefined) {
console.error("[ARCS] Undefined controller. Cannot start application.");
}
};
/**
* Registers a factory using a key. If a factory was previously existing using
* the same key, then it is overridden.
* @param key {string} name of the factory
* @param factory {object} component factory to register.
*/
this.setFactory = function (key, factory) {
factories[key] = factory;
};
this.setDependency = function (key) {
dependencies[key] = {};
};
/**
* Starts the application
*/
this.start = function () {
console.log("[ARCS] Starting application...");
context.instanciate().then(preProcess);
};
};
ARCS.Application.setDependency = function (app, key) {
app.setDependency(key);
};
ARCS.Component.create(ARCS.Application);
ARCS.Application.slot("setSheet");
ARCS.Application.slot("finish");
// no longer needed with the use of imports
export { ARCS as default};