mmmk.js 62 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921
  1. /* This file is part of AToMPM - A Tool for Multi-Paradigm Modelling
  2. * Copyright 2011 by the AToMPM team and licensed under the LGPL
  3. * See COPYING.lesser and README.md in the root of this project for full details
  4. */
  5. /* NOTES:
  6. atom3 supported pre/post actions and constraints for the 'SAVE' EVENT...
  7. this never really made any sense (e.g., the user could be prevented from
  8. saving and, technically, the effects of post-actions were never saved)...
  9. atom3 supported 'save' events as a hack to enable forcing mm validation...
  10. in atompm, such validation is carried out by _mmmk.validateModel (which
  11. clients can 'call') and thus, we do no support 'save' events... */
  12. const _utils = require('./utils');
  13. module.exports = {
  14. /********************************* GLOBALS *********************************/
  15. 'metamodels':{},
  16. 'model':{'nodes':{},'edges':[],'metamodels':[]},
  17. 'name':'',
  18. 'next_id':0,
  19. /********************************* ENV SETUP *******************************/
  20. /* produce a bundle of internal state variables sufficient to fully clone
  21. this instance
  22. OR
  23. use a provided bundle to overwrite this instance's internal state */
  24. 'clone' :
  25. function(clone)
  26. {
  27. if( clone )
  28. {
  29. this.metamodels = clone.metamodels;
  30. this.model = clone.model;
  31. this.name = clone.name;
  32. this.next_id = clone.next_id;
  33. this.journal = clone.journal;
  34. this.journalIndex = clone.journalIndex;
  35. this.undoredoJournal = clone.undoredoJournal;
  36. }
  37. else
  38. return _utils.clone(
  39. {'metamodels': this.metamodels,
  40. 'model': this.model,
  41. 'name': this.name,
  42. 'next_id': this.next_id,
  43. 'journal': this.journal,
  44. 'journalIndex': this.journalIndex,
  45. 'undoredoJournal': this.undoredoJournal});
  46. },
  47. /* load a model into this.model
  48. 0. create step-checkpoint
  49. 1. make sure all required metamodels are loaded
  50. 2. if 'insert' is specified,
  51. a) append 'model' to this.model (via __resetm__)
  52. 2. otherwise, load 'model' into this.model and 'name' into this.name
  53. (via __resetm__) */
  54. 'loadModel' :
  55. function(name,model,insert)
  56. {
  57. this.__setStepCheckpoint();
  58. var new_model = eval('('+ model +')');
  59. for( var i in new_model.metamodels )
  60. if( this.metamodels[new_model.metamodels[i]] == undefined )
  61. return {'$err':'metamodel not loaded :: '+new_model.metamodels[i]};
  62. this.__resetm__(name,model,insert);
  63. return {'changelog':this.__changelog()};
  64. },
  65. /* load a metamodel
  66. 0. create a step-checkpoint
  67. 1. load metamodel into this.model.metamodels and this.metamodels (via
  68. __loadmm__) */
  69. 'loadMetamodel' :
  70. function(name,mm)
  71. {
  72. this.__setStepCheckpoint();
  73. this.__loadmm__(name,mm);
  74. return {'changelog':this.__changelog()};
  75. },
  76. /* unload a metamodel and delete all entities from that metamodel
  77. 0. create a step-checkpoint
  78. 1. deletes nodes from specified metamodel
  79. 2. delete edges where deleted nodes appear
  80. 3. remove metamodel from this.model.metamodels and this.metamodels
  81. (via __dumpmm__) */
  82. 'unloadMetamodel' :
  83. function(name)
  84. {
  85. this.__setStepCheckpoint();
  86. for( var i=0; i<this.model.edges.length; i++ )
  87. {
  88. var edge = this.model.edges[i];
  89. if( this.__getMetamodel(this.model.nodes[edge['src']]['$type']) == name ||
  90. this.__getMetamodel(this.model.nodes[edge['dest']]['$type']) == name )
  91. this.__rmedge__(i--);
  92. }
  93. for( var id in this.model.nodes )
  94. if( this.__getMetamodel(this.model.nodes[id]['$type']) == name )
  95. this.__rmnode__(id);
  96. this.__dumpmm__(name);
  97. return {'changelog':this.__changelog()};
  98. },
  99. /******************************** MODEL CRUD *******************************/
  100. /* wraps crud operations with generic boilerplate
  101. 0. setup next_type hack : the next_type variable is used to carry the type
  102. of the to-be-created node for the special case of pre-create handlers
  103. because their target nodes aren't yet in this.model.nodes
  104. 1. create a checkpoint (any failure along the way causes checkpoint
  105. restore)
  106. 2. run all applicable pre-events constraints and actions
  107. 3. perform the specified crud operation
  108. 4. run all applicable post-events actions and constraints
  109. 5. clear unused checkpoint */
  110. '__crudOp' :
  111. function(metamodel,events,eventTargets,op,args)
  112. {
  113. if( this.metamodels[metamodel] == undefined )
  114. return {'$err':'metamodel not loaded :: '+metamodel};
  115. if( _utils.contains(events,'create') )
  116. this.next_type = args.fulltype || args.connectorType;
  117. this.__checkpoint();
  118. var pre_events = events.slice(0).map(function(ev) {return 'pre-'+ev;}),
  119. post_events = events.slice(0).map(function(ev) {return 'post-'+ev;});
  120. if( (err = this.__runEventHandlers(this.metamodels[metamodel]['constraints'], pre_events, eventTargets, 'constraint')) ||
  121. (err = this.__runEventHandlers(this.metamodels[metamodel]['actions'], pre_events, eventTargets, 'action')) ||
  122. (err = this[op](args)) ||
  123. (err = this.__runEventHandlers(this.metamodels[metamodel]['actions'], post_events, eventTargets, 'action')) ||
  124. (err = this.__runEventHandlers(this.metamodels[metamodel]['constraints'], post_events, eventTargets, 'constraint')) )
  125. {
  126. this.__restoreCheckpoint();
  127. return err;
  128. }
  129. this.__clearCheckpoint();
  130. },
  131. /* connect specified nodes with instance of connectorType
  132. __connectNN: (connect 2 nodes)
  133. 1. run pre-connect on end nodes
  134. 2. run __create to create instance and connect it to end nodes
  135. 3. run post-connect on end nodes
  136. __connectCN: (connect 1 node and 1 connector)
  137. 1. add an appropriate edge to this.model.edges
  138. connect:
  139. 0. create a step-checkpoint
  140. 1. verify validity of requested connection (i.e., connection is legal
  141. and max cardinalities haven't been reached)
  142. 2. if one of the nodes is a connector
  143. a) run pre-connect on end nodes
  144. b) create appropriate new edge between them (via __connectCN)
  145. c) run post-connect on end nodes
  146. 2. if both nodes are non-connectors
  147. a) run pre-create on connectorType
  148. b) create connectorType instance and connect it to end nodes (via
  149. __connectNN)
  150. c) run post-create on connectorType
  151. 3. return err or (new or existing) connector's id */
  152. '__connectNN' :
  153. function(args/*id1,id2,connectorType,attrs*/)
  154. {
  155. return this.__crudOp(
  156. this.__getMetamodel(args.connectorType),
  157. ['connect'],
  158. [args.id1,args.id2],
  159. '__create',
  160. {'fulltype':args.connectorType,
  161. 'id1':args.id1,
  162. 'id2':args.id2,
  163. 'attrs':args.attrs});
  164. },
  165. '__connectCN' :
  166. function(args/*id1,id2,connectorId*/)
  167. {
  168. this.__mkedge__(args.id1,args.id2);
  169. },
  170. 'connect' :
  171. function(id1,id2,connectorType,attrs)
  172. {
  173. this.__setStepCheckpoint();
  174. var metamodel = this.__getMetamodel(connectorType),
  175. t1 = this.__getType(this.model.nodes[id1]['$type']),
  176. t2 = this.__getType(this.model.nodes[id2]['$type']),
  177. tc = this.__getType(connectorType),
  178. into = (t1 == tc ? t2 : tc),
  179. from = (t2 == tc ? t1 : tc),
  180. card_into = undefined,
  181. card_from = undefined,
  182. num_id1to = 0,
  183. num_toid2 = 0,
  184. self = this;
  185. [t1,'$*','__p$*'].some(
  186. function(t)
  187. {
  188. for( var i in self.metamodels[metamodel]['cardinalities'][t] )
  189. {
  190. var cardinality = self.metamodels[metamodel]['cardinalities'][t][i];
  191. if( cardinality['type'] == into && cardinality['dir'] == 'out' )
  192. {
  193. card_into = cardinality;
  194. return true;
  195. }
  196. }
  197. });
  198. [t2,'$*','__p$*'].some(
  199. function(t)
  200. {
  201. for( var i in self.metamodels[metamodel]['cardinalities'][t] )
  202. {
  203. var cardinality = self.metamodels[metamodel]['cardinalities'][t][i];
  204. if( cardinality['type'] == from && cardinality['dir'] == 'in' )
  205. {
  206. card_from = cardinality;
  207. return true;
  208. }
  209. }
  210. });
  211. if( card_into == undefined || card_from == undefined )
  212. return {'$err':'can not connect types '+t1+' and '+t2};
  213. else if( card_into['max'] == 0 )
  214. return {'$err':'maximum outbound multiplicity reached for '+t1+' ('+id1+') and type '+into};
  215. else if( card_from['max'] == 0 )
  216. return {'$err':'maximum inbound multiplicity reached for '+t2+' ('+id2+') and type '+from};
  217. for( var i in this.model.edges )
  218. {
  219. var edge = this.model.edges[i];
  220. if( edge['src'] == id1 &&
  221. this.__getType(this.model.nodes[edge['dest']]['$type']) == into &&
  222. ++num_id1to >= card_into['max'] )
  223. return {'$err':'maximum outbound multiplicity reached for '+t1+' ('+id1+') and type '+into};
  224. if( edge['dest'] == id2 &&
  225. this.__getType(this.model.nodes[edge['src']]['$type']) == from &&
  226. ++num_toid2 >= card_from['max'] )
  227. return {'$err':'maximum inbound multiplicity reached for '+t2+' ('+id2+') and type '+from};
  228. }
  229. if( t1 == tc || t2 == tc )
  230. {
  231. var connectorId = (t1 == tc ? id1 : id2),
  232. err = this.__crudOp(
  233. metamodel,
  234. ['connect'],
  235. [id1,id2],
  236. '__connectCN',
  237. {'id1':id1,
  238. 'id2':id2,
  239. 'connectorId':connectorId});
  240. return err ||
  241. {'id':connectorId,
  242. 'changelog':this.__changelog()};
  243. }
  244. else
  245. {
  246. var err = this.__crudOp(
  247. metamodel,
  248. ['create'],
  249. [this.next_id],
  250. '__connectNN',
  251. {'id1':id1,
  252. 'id2':id2,
  253. 'connectorType':connectorType,
  254. 'attrs':attrs});
  255. return err ||
  256. {'id':this.next_id++,
  257. 'changelog':this.__changelog()};
  258. }
  259. },
  260. /* create an instance of fulltype
  261. __create:
  262. 1. create [default] instance using metamodel [and possibly specified
  263. attrs] + init $type
  264. 2. add to current model nodes
  265. [3. if fulltype is a connectorType, create edges between node id1
  266. and new instance and between new instance and node id2
  267. create:
  268. 0. create a step-checkpoint
  269. 1. wrap __create in crudOp
  270. 2. return err or new instance id */
  271. '__create' :
  272. function(args/*fulltype,attrs,[,id1,id2]*/)
  273. {
  274. var metamodel = this.__getMetamodel(args.fulltype),
  275. type = this.__getType(args.fulltype),
  276. typeAttrs = this.metamodels[metamodel]['types'][type],
  277. new_node = {};
  278. if( typeAttrs == undefined )
  279. return {'$err':'can not create instance of unknown type :: '+args.fulltype};
  280. typeAttrs.forEach(
  281. function(attr)
  282. {
  283. var val = (args.attrs && attr['name'] in args.attrs ?
  284. args.attrs[attr['name']] :
  285. attr['default']);
  286. new_node[attr['name']] =
  287. {'type':attr['type'],
  288. 'value':(typeof attr['default'] == 'object' ?
  289. _utils.clone(val) :
  290. val)};
  291. });
  292. new_node['$type'] = args.fulltype;
  293. this.__mknode__(this.next_id,new_node);
  294. if( args.id1 != undefined )
  295. {
  296. this.__mkedge__(args.id1,String(this.next_id));
  297. this.__mkedge__(String(this.next_id),args.id2);
  298. }
  299. },
  300. 'create' :
  301. function(fulltype,attrs)
  302. {
  303. this.__setStepCheckpoint();
  304. var err = this.__crudOp(
  305. this.__getMetamodel(fulltype),
  306. ['create'],
  307. [this.next_id],
  308. '__create',
  309. {'fulltype':fulltype,
  310. 'attrs':attrs});
  311. return err ||
  312. {'id':this.next_id++,
  313. 'changelog':this.__changelog()};
  314. },
  315. /* delete the specified node (and appropriate edges and/or connectors)
  316. __delete:
  317. 1. determine specified node's neighbors
  318. 2. if specified node is a connector (neighbors are non-connectors),
  319. a) run pre-disconnect constraints and actions and on its neighbors
  320. b) delete it and all appropriate edges (via __deleteConnector)
  321. c) run post-disconnect constraints and actions and on its neighbors
  322. 2. if specified node is not a connector (neighbors are connectors),
  323. a) recursively run __delete on each of its neighbors
  324. b) delete it
  325. __deleteConnector:
  326. 1. delete all appropriate edges then delete node
  327. delete:
  328. 0. create a step-checkpoint
  329. 1. wrap __delete in crudOp
  330. 2. return err or nothing */
  331. '__delete' :
  332. function(args/*id*/)
  333. {
  334. var id = args.id,
  335. metamodel = this.__getMetamodel(this.model.nodes[id]['$type']),
  336. type = this.__getType(this.model.nodes[id]['$type']),
  337. isConnector = (this.metamodels[metamodel]['connectorTypes'][type] != undefined),
  338. neighbors = [];
  339. this.model.edges.forEach(
  340. function(edge)
  341. {
  342. if( edge['src'] == id && ! _utils.contains(neighbors,edge['dest']) )
  343. neighbors.push(edge['dest']);
  344. else if( edge['dest'] == id && ! _utils.contains(neighbors,edge['src']) )
  345. neighbors.push(edge['src']);
  346. });
  347. if( isConnector )
  348. {
  349. if( (res = this.__crudOp(
  350. metamodel,
  351. ['disconnect'],
  352. neighbors,
  353. '__deleteConnector',
  354. {'id':id})) )
  355. return res;
  356. }
  357. else
  358. {
  359. for( var i in neighbors )
  360. if( (res = this.__crudOp(
  361. metamodel,
  362. ['delete'],
  363. [neighbors[i]],
  364. '__delete',
  365. {'id':neighbors[i]})) )
  366. return res;
  367. this.__rmnode__(id);
  368. }
  369. },
  370. '__deleteConnector' :
  371. function(args/*id*/)
  372. {
  373. for( var i=0; i<this.model.edges.length; i++ )
  374. {
  375. var edge = this.model.edges[i];
  376. if( edge['src'] == args.id || edge['dest'] == args.id )
  377. this.__rmedge__(i--);
  378. }
  379. this.__rmnode__(args.id);
  380. },
  381. 'delete' :
  382. function(id)
  383. {
  384. this.__setStepCheckpoint();
  385. if( this.model.nodes[id] == undefined )
  386. return {'$err':'invalid id :: '+id};
  387. var err = this.__crudOp(
  388. this.__getMetamodel(this.model.nodes[id]['$type']),
  389. ['delete'],
  390. [id],
  391. '__delete',
  392. {'id':id});
  393. return err ||
  394. {'changelog':this.__changelog()};
  395. },
  396. /* returns the stringified full model, a stringified node, or a copy of an
  397. attribute's value */
  398. 'read' :
  399. function(id,attr)
  400. {
  401. if( id == undefined )
  402. return _utils.jsons(this.model);
  403. else if( this.model.nodes[id] == undefined )
  404. return {'$err':'instance not found :: '+id};
  405. else if( attr == undefined )
  406. return _utils.jsons(this.model.nodes[id]);
  407. else if( attr.match(/.+\/.+/) )
  408. {
  409. var curr = this.model.nodes[id];
  410. for( var i in (path = attr.split('/')) )
  411. if( typeof curr == 'object' && path[i] in curr )
  412. curr = curr[path[i]];
  413. else
  414. return {'$err':'instance '+id+' has no attribute :: '+attr};
  415. }
  416. else if( !(attr in this.model.nodes[id]) )
  417. return {'$err':'instance '+id+' has no attribute :: '+attr};
  418. var attrVal = (curr ? curr['value'] : this.model.nodes[id][attr]['value']);
  419. if( typeof attrVal == 'object' )
  420. return _utils.clone(attrVal);
  421. else
  422. return attrVal;
  423. },
  424. /* returns a copy of one or all metamodels in this.metamodels */
  425. 'readMetamodels' :
  426. function(metamodel)
  427. {
  428. if( metamodel == undefined )
  429. return _utils.jsons(this.metamodels);
  430. else if( this.metamodels[metamodel] == undefined )
  431. return {'$err':'metamodel not found :: '+metamodel};
  432. else
  433. return _utils.jsons(this.metamodels[metamodel]);
  434. },
  435. /* returns this.name */
  436. 'readName' :
  437. function()
  438. {
  439. return this.name;
  440. },
  441. /* runs accesor-code that conforms to the DesignerCode API and returns its
  442. results */
  443. 'runDesignerAccessorCode' :
  444. function(code,desc,id)
  445. {
  446. var res = this.__runDesignerCode(code,desc,'accessor',id);
  447. if( res && res['$err'] )
  448. return res;
  449. return res;
  450. },
  451. /* runs action-code that conforms to the DesignerCode API (of interest is
  452. that this 'operation' is checkpointed and can thus be undone/redone; and
  453. that any exceptions thrown by the code cause a full rollback to before it
  454. was run and are then returned to the querier) */
  455. 'runDesignerActionCode' :
  456. function(code,desc,type,id)
  457. {
  458. this.__setStepCheckpoint();
  459. this.__checkpoint();
  460. if( (err = this.__runDesignerCode(code,desc,type,id)) )
  461. {
  462. this.__restoreCheckpoint();
  463. return err;
  464. }
  465. this.__clearCheckpoint();
  466. return {'changelog':this.__changelog()};
  467. },
  468. /* updates node with specified id
  469. __update:
  470. 1. update instance as per data
  471. 2. return err on unknown attributes
  472. 3. TBA: type verification on new values
  473. update:
  474. 0. create a step-checkpoint
  475. 1. wrap __update in crudOp
  476. 2. return err or nothing */
  477. '__update' :
  478. function(args/*id,data*/)
  479. {
  480. for( var attr in args.data )
  481. if( args.data[attr] == null )
  482. return {'$err':'tried to set attribute '+attr+' to "null"'};
  483. else if( (res = this.read(args.id,attr))['$err'] )
  484. return res;
  485. else
  486. this.__chattr__(args.id,attr,args.data[attr]);
  487. },
  488. 'update' :
  489. function(id,data/*{..., attr_i:val_i, ...}*/)
  490. {
  491. this.__setStepCheckpoint();
  492. if( this.model.nodes[id] == undefined )
  493. return {'$err':'invalid id :: '+id};
  494. var err = this.__crudOp(
  495. this.__getMetamodel(this.model.nodes[id]['$type']),
  496. ['edit'],
  497. [id],
  498. '__update',
  499. {'id':id,
  500. 'data':data});
  501. return err ||
  502. {'changelog':this.__changelog()};
  503. },
  504. /*************************** EVENT HANDLER EXEC ****************************/
  505. /* run the given constraint|action|accessor... when id is specified, we
  506. consider it to be the id of the node that "owns" the current
  507. constraint|action|accessor...
  508. this function is divided in 3 parts
  509. 1. constraints/actions/accessors API definition
  510. 2. safe_eval definition
  511. 3. actual code that runs the handler and handles its output */
  512. '__runDesignerCode' :
  513. function(code,desc,type,id)
  514. {
  515. /* the functions below implement the API available for constraints,
  516. actions and 'accessors'... they can only be called from "designer"
  517. code (i.e., from actions/constraints/accessors written by language
  518. and/or model transformation designers)... the main consequence of
  519. this is our design decision that setAttr() is not treated like a
  520. normal crud operation: it does not go through the crudOp pipeline
  521. of pre/post edit constraints/actions... on one hand, this decision
  522. avoids any weird recursion cases (e.g., setAttr() in pre-edit action
  523. triggers pre-edit action and on and on and on)... on the other hand,
  524. designers should be aware that:
  525. 1. setAttr() may set attributes to values that the user could not
  526. input (e.g., due to constraints)
  527. 2. consequences (specified as edit actions) of a user setting an
  528. attribute A to value 'a' might not take effect if setAttr()
  529. sets attribute A to value 'a' : for instance, if an edit
  530. action says that attribute B should be 'a'+2, setAttr() won't
  531. trigger that action
  532. 3. even though setAttr() bypasses crudOp constraints/actions, its
  533. effects are still immediate: a getAttr() on the next line (of
  534. designer code) reports the updated value
  535. moral of story:
  536. designers must be very careful with setAttr() to avoid putting
  537. the model into otherwise unreachable states
  538. API:
  539. hasAttr(_attr[,_id])
  540. return true if the specified node has an attribute of the
  541. given name
  542. getAttr(_attr[,_id])
  543. return the requested attr of the specified node... to ensure
  544. getAttr can't be used to edit the model, JSON parse+stringify
  545. is used to return a *copy* of the attribute when its value has
  546. an object type (i.e., hash or array)
  547. getAllNodes([_fulltypes])
  548. if _fulltypes is undefined, return the ids all of nodes...
  549. otherwise, return ids of all nodes with specified fulltypes
  550. getNeighbors(_dir[,_type,_id])
  551. return all inbound (_dir = '<'), outbound (_dir = '>') or both
  552. (_dir = '*') neighbor ids for specified type (if any)
  553. print(str)
  554. print something to the console that launched the server
  555. setAttr(_attr,_val[,_id])
  556. ((this function is only available in actions))... update the
  557. requested attr of the specified node using __chattr__ (s.t.
  558. the change is logged)...
  559. TBA:: type-checking on _val
  560. basic checks are made on input parameters to aid in debugging faulty
  561. actions and constraints... for functions with id parameters, if no
  562. id is given, we use the id passed to __runDesignerCode... which is
  563. either the id of the node that "owns" the current constraint|action|
  564. accessor, or undefined if the parameter was omitted */
  565. var self = this;
  566. function getAttr(_attr,_id)
  567. {
  568. if( _id == undefined )
  569. _id = id;
  570. if( self.model.nodes[_id] == undefined )
  571. throw 'invalid getAttr() id :: '+_id;
  572. else if( !(_attr in self.model.nodes[_id]) )
  573. throw 'invalid getAttr() attribute :: '+_attr;
  574. if( _attr.charAt(0) == '$' )
  575. return self.model.nodes[_id][_attr];
  576. else if( typeof self.model.nodes[_id][_attr]['value'] == 'object' )
  577. return _utils.clone(self.model.nodes[_id][_attr]['value']);
  578. else
  579. return self.model.nodes[_id][_attr]['value'];
  580. }
  581. function getAttrNames(_id)
  582. {
  583. if( _id == undefined )
  584. _id = id;
  585. if( self.model.nodes[_id] == undefined )
  586. throw 'invalid getAttrNames() id :: '+_id;
  587. return Object.getOwnPropertyNames(self.model.nodes[_id]);
  588. }
  589. function hasAttr(_attr,_id)
  590. {
  591. if( _id == undefined )
  592. _id = id;
  593. if( self.model.nodes[_id] == undefined )
  594. throw 'invalid getAttr() id :: '+_id;
  595. return _attr in self.model.nodes[_id];
  596. }
  597. function getAllNodes(_fulltypes)
  598. {
  599. if( _fulltypes != undefined && !(_fulltypes instanceof Array) )
  600. throw 'invalid getAllNodes() types array :: '+_fulltypes;
  601. var ids = [];
  602. for( var _id in self.model.nodes )
  603. {
  604. if( _fulltypes == undefined ||
  605. _utils.contains(_fulltypes,self.model.nodes[_id]['$type']) )
  606. ids.push(_id);
  607. }
  608. return ids;
  609. }
  610. function getNeighbors(_dir,_type,_id)
  611. {
  612. if( _id == undefined )
  613. _id = id;
  614. if( _type == undefined )
  615. _type = '*';
  616. if( self.model.nodes[_id] == undefined )
  617. throw 'invalid getNeighbors() id :: '+_id;
  618. var ids = [];
  619. for( var i in self.model.edges )
  620. {
  621. var edge = self.model.edges[i];
  622. if( edge['src'] == _id &&
  623. (_dir == '>' || _dir == '*' || _dir == "out") &&
  624. (_type == '*' || self.model.nodes[edge['dest']]['$type'] == _type) &&
  625. ! _utils.contains(ids,edge['dest']) )
  626. ids.push(edge['dest']);
  627. else if( edge['dest'] == _id &&
  628. (_dir == '<' || _dir == '*' || _dir == "in") &&
  629. (_type == '*' || self.model.nodes[edge['src']]['$type'] == _type) &&
  630. ! _utils.contains(ids,edge['src']) )
  631. ids.push(edge['src']);
  632. }
  633. return ids;
  634. }
  635. function print(str)
  636. {
  637. _util.log(str);
  638. }
  639. function setAttr(_attr,_val,_id)
  640. {
  641. if( type != 'action' )
  642. throw 'setAttr() can only be used within actions';
  643. if( _id == undefined )
  644. _id = id;
  645. if( self.model.nodes[_id] == undefined )
  646. throw 'invalid setAttr() id :: '+_id;
  647. else if( !(_attr in self.model.nodes[_id]) || _attr.charAt(0) == '$' )
  648. throw 'invalid setAttr() attribute :: '+_attr;
  649. self.__chattr__(_id,_attr,_val);
  650. }
  651. /* evaluate provided code without the said code having access to
  652. globals (i.e., model, journal) or to 'self' (which we use above to
  653. allow non-global functions to access globals), and catching any
  654. exceptions it may throw... escaped newlines if any are unescaped */
  655. function safe_eval(code)
  656. {
  657. var self = undefined;
  658. try
  659. {
  660. return eval(code);
  661. }
  662. catch(err)
  663. {
  664. if( err == 'IgnoredConstraint' )
  665. return true;
  666. return {'$err':err};
  667. }
  668. }
  669. var res = safe_eval(code);
  670. if( res != undefined && res['$err'] != undefined )
  671. return {'$err':type+' ('+desc+') crashed on :: '+res['$err']};
  672. /* completed accessor */
  673. else if( type == 'accessor' )
  674. return res;
  675. /* failed constraint */
  676. else if( res == false )
  677. return {'$err':type+' ('+desc+') failed'};
  678. },
  679. /* run actions or constraints for specified events and specified nodes
  680. 1. get types of specified nodes (note that we do a little hack for the
  681. special case of pre-create handlers because this.model.nodes does not
  682. yet contain a node with the to-be-created node's id... thus its type
  683. is read from this.next_type)
  684. 2. identify and run applicable handlers based on events and targetTypes */
  685. '__runEventHandlers' :
  686. function(allHandlers,events,ids,handlerType)
  687. {
  688. var types2ids = {};
  689. for( var i in ids )
  690. {
  691. var id = ids[i];
  692. if( id == this.next_id )
  693. var type = this.__getType(this.next_type);
  694. else if( this.model.nodes[id] == undefined )
  695. continue;
  696. else
  697. var type = this.__getType(this.model.nodes[id]['$type']);
  698. if( types2ids[type] == undefined )
  699. types2ids[type] = [];
  700. types2ids[type].push(id);
  701. }
  702. for( var i in allHandlers )
  703. {
  704. var handler = allHandlers[i];
  705. if( _utils.contains(events,handler['event']) )
  706. {
  707. if( handler['targetType'] == '*' )
  708. {
  709. for( var j in ids )
  710. if( (res = this.__runDesignerCode(
  711. handler['code'],
  712. handler['event']+' '+handler['name'],
  713. handlerType,
  714. ids[j])) )
  715. return res;
  716. if( ids.length == 0 )
  717. if( (res = this.__runDesignerCode(
  718. handler['code'],
  719. handler['event']+' '+handler['name'],
  720. handlerType)) )
  721. return res;
  722. }
  723. else
  724. for( var j in types2ids[handler['targetType']] )
  725. {
  726. var id = types2ids[handler['targetType']][j];
  727. if( (res = this.__runDesignerCode(
  728. handler['code'],
  729. handler['event']+' '+handler['name'],
  730. handlerType,
  731. id)) )
  732. return res;
  733. }
  734. }
  735. }
  736. },
  737. /**************************** MODEL VALIDATION *****************************/
  738. /* verifies that the current model satisfies (1) the min cardinalities set
  739. by its metamodel(s) and (2) all global eventless constraints... returns
  740. the first encountered discrepancy or nothing
  741. 1. count incoming and outgoing connections of each type for each node
  742. 2. compare the above to the min cardinalities
  743. 3. run all global eventless constraints */
  744. 'validateModel' :
  745. function(model)
  746. {
  747. var inCounts = {},
  748. outCounts = {},
  749. model = (model == undefined ? this.model : model),
  750. outContainments = {},
  751. containmentTargets = {};
  752. if( model.nodes == undefined ||
  753. model.edges == undefined ||
  754. model.metamodels == undefined ||
  755. model.metamodels.length == 0 )
  756. return {'$err':'provided model is either empty or not an atompm model'};
  757. for( var i in model.edges )
  758. {
  759. var edge = model.edges[i],
  760. srcType = this.__getType(model.nodes[edge['src']]['$type']),
  761. destType = this.__getType(model.nodes[edge['dest']]['$type']),
  762. srcMetamodel = this.__getMetamodel(model.nodes[edge['src']]['$type']),
  763. destMetamodel = this.__getMetamodel(model.nodes[edge['dest']]['$type']);
  764. if( inCounts[edge['dest']] == undefined )
  765. inCounts[edge['dest']] = {};
  766. if( inCounts[edge['dest']][srcType] == undefined )
  767. inCounts[edge['dest']][srcType] = 0;
  768. inCounts[edge['dest']][srcType]++;
  769. if( outCounts[edge['src']] == undefined )
  770. outCounts[edge['src']] = {};
  771. if( outCounts[edge['src']][destType] == undefined )
  772. outCounts[edge['src']][destType] = 0;
  773. outCounts[edge['src']][destType]++;
  774. if ( outContainments[edge['src']] == undefined ) {
  775. outContainments[edge['src']] = [];
  776. }
  777. if (destType in this.metamodels[destMetamodel]['connectorTypes'] && this.metamodels[destMetamodel]['connectorTypes'][destType] == 'containment') {
  778. outContainments[edge['src']].push(edge['dest']);
  779. }
  780. if ( containmentTargets[edge['src']] == undefined ) {
  781. containmentTargets[edge['src']] = [];
  782. }
  783. if (srcType in this.metamodels[srcMetamodel]['connectorTypes'] && this.metamodels[srcMetamodel]['connectorTypes'][srcType] == 'containment') {
  784. containmentTargets[edge['src']].push(edge['dest']);
  785. }
  786. }
  787. var checked_for_loops = [];
  788. for( var id in model.nodes )
  789. {
  790. var metamodel = this.__getMetamodel(model.nodes[id]['$type']),
  791. type = this.__getType(model.nodes[id]['$type']);
  792. for( var i in this.metamodels[metamodel]['cardinalities'][type] )
  793. {
  794. var cardinality = this.metamodels[metamodel]['cardinalities'][type][i],
  795. tc = cardinality['type'];
  796. if( cardinality['dir'] == 'out' &&
  797. cardinality['min'] > (outCounts[id] == undefined || outCounts[id][tc] == undefined ? 0 : outCounts[id][tc]) )
  798. return {'$err':'insufficient outgoing connections of type '+tc+' for '+model.nodes[id]['$type']+'/'+id};
  799. else if( cardinality['dir'] == 'in' &&
  800. cardinality['min'] > (inCounts[id] == undefined || inCounts[id][tc] == undefined ? 0 : inCounts[id][tc]) )
  801. return {'$err':'insufficient incoming connections of type '+tc+' for '+model.nodes[id]['$type']+'/'+id};
  802. }
  803. if (checked_for_loops.indexOf(id) < 0 && !(type in this.metamodels[metamodel]['connectorTypes'])) {
  804. var visited = [],
  805. tv = [id];
  806. // eslint-disable-next-line no-inner-declarations
  807. function dfs(to_visit) {
  808. var curr = to_visit.pop();
  809. if( curr == undefined )
  810. return undefined; // no more to check
  811. else if( visited.indexOf(curr) > -1 )
  812. return {'$err':'containment loop found for ' + model.nodes[id]['$type']+'/'+id}; // error: loop found!
  813. else {
  814. visited.push(curr);
  815. // find all (containment) associations linked to the object, and add their targets to the to_visit list.
  816. for ( var oc_idx in outContainments[curr] ) {
  817. to_visit = to_visit.concat(containmentTargets[outContainments[curr][oc_idx]]);
  818. }
  819. return dfs( to_visit );
  820. }
  821. }
  822. var res = dfs(tv);
  823. if (res != undefined) {
  824. return res;
  825. }
  826. checked_for_loops= checked_for_loops.concat(visited);
  827. }
  828. }
  829. for( var metamodel in this.metamodels )
  830. if( (err=this.__runEventHandlers(this.metamodels[metamodel]['constraints'], [''], [], 'constraint')) )
  831. return err;
  832. },
  833. /**************************** MODEL COMPILATION ****************************/
  834. /* compile the current model and the given CS model into an icon definition
  835. metamodel
  836. 0. the entire function body is wrapped in a try/catch... this is our lazy
  837. approach to verifying that the current model is indeed a valid model of
  838. an icon definition metamodel
  839. 1. if the current model is missing the CS formalism, return error
  840. 2. extract information about types from current model
  841. a) find all ConcreteSyntax/Icons and ConcreteSyntax/Links
  842. b) map all CS/Icons to their IconIcon in the CS model (argument)
  843. c) map all CS/Icons to the nodes they're [transitively] connected to
  844. (except their IconContents links)
  845. d) save all edges between contained nodes from step c)
  846. e) enhance every contained node (from step c)) with information about
  847. its associated IconIcon (e.g., position, orientation)... this is
  848. needed so that the final '$contents' attributes of each generated
  849. *Icon hold sufficient information to render icons as the user
  850. specified them... note that position attributes are adjusted to make
  851. them relative to the containing IconIcon's top-left corner
  852. e*) enhance nodes contained within Links with link decorator
  853. positioning information (e.g., xratio, yoffset)
  854. f) when pre-defined arrowheads/tails have been selected by the user,
  855. pretend the user has actually drawn them s.t. they get handled by
  856. link decorator positioning code during modelling... in practice:
  857. i. identify pre-defined arrowheads/tails
  858. ii. locate corresponding drawings within relevant Link's
  859. LinkIcon $contents
  860. iii. copy them into relevant Link's compiled $contents
  861. iv. enhance them with link decorator information (c.f., step e*)
  862. 3. construct mm.types based on information from step 2... the resulting
  863. mm.types wil look very much like ConcreteSyntax.types, with a few added
  864. 'special' attributes (e.g., $asuri, $contents, etc.)
  865. 4. check whether all non-abstract types have an icon, and no abstract types have an icon
  866. 5. return mm stringified (ensures no references to objects in this.model
  867. are returned) */
  868. 'compileToIconDefinitionMetamodel' :
  869. function(csm, asmm)
  870. {
  871. var CS = '/Formalisms/__LanguageSyntax__/ConcreteSyntax/ConcreteSyntax';
  872. try
  873. {
  874. /* 1 */
  875. if( ! _utils.contains(this.model.metamodels,CS) )
  876. throw 'icon definition models must have the '+CS+' formalism loaded';
  877. else
  878. var model = _utils.jsonp(this.read());
  879. nodes = {};
  880. for (var id in model.nodes) {
  881. if (model.nodes[id]['$type'].slice(0, CS.length) == CS) {
  882. nodes[id] = model.nodes[id];
  883. }
  884. }
  885. model.nodes = nodes;
  886. /* 2 */
  887. var mm =
  888. {'types':{},
  889. 'constraints':[],
  890. 'actions':[],
  891. 'cardinalities':{},
  892. 'legalConnections':{},
  893. 'connectorTypes':{},
  894. 'types2parentTypes':{}},
  895. iids = [],
  896. iids2contents = {},
  897. ids2csids = {},
  898. self = this,
  899. outNeighbors =
  900. /* returns the given node's outbound neighbors */
  901. function(source)
  902. {
  903. return model.edges.filter(function(edge) {return edge['src'] == source && model.nodes[edge['dest']] != undefined;}).
  904. map(function(edge) {return edge['dest'];});
  905. },
  906. getConnectedNodes =
  907. /* compute the [transitive] contents of 'container'... this
  908. function is a bit of an oversimplification: it makes the
  909. reasonable but not necessarily correct assumption that
  910. anything that is [transitively] connected to a CS/Icon or
  911. CS/Link is inside it */
  912. function(container,contents)
  913. {
  914. var _contents = {};
  915. outNeighbors(container).forEach(
  916. function(n)
  917. {
  918. if( !(n in contents) )
  919. _contents[n] = 1;
  920. });
  921. if( _utils.keys(_contents).length == 0 )
  922. return contents;
  923. contents = _utils.mergeDicts([contents,_contents]);
  924. return _utils.mergeDicts(
  925. _utils.keys(_contents).map(
  926. function(_c) {return getConnectedNodes(_c,contents);} ));
  927. };
  928. /* 2a */
  929. for( var id in model.nodes )
  930. if( model.nodes[id]['$type'] == CS+'/Icon' ||
  931. model.nodes[id]['$type'] == CS+'/Link' )
  932. {
  933. iids.push(id);
  934. iids2contents[id] = {'nodes':{},'edges':[]};
  935. }
  936. /* 2b */
  937. csm = _utils.jsonp(csm);
  938. for( var csid in csm.nodes )
  939. {
  940. var id = csm.nodes[csid]['$asuri']['value'].match(/.*\/(.*)\.instance$/)[1];
  941. ids2csids[id] = csid;
  942. }
  943. iids.forEach(
  944. function(iid)
  945. {
  946. /* 2c */
  947. _utils.keys(getConnectedNodes(iid,{})).filter(
  948. function(id)
  949. {
  950. return model.nodes[id]['$type'] != CS+'/IconContents';
  951. }).forEach(
  952. function(id)
  953. {
  954. iids2contents[iid].nodes[id] = model.nodes[id];
  955. });
  956. /* 2d */
  957. model.edges.forEach(
  958. function(edge)
  959. {
  960. if( iids2contents[iid].nodes[edge['src']] != undefined &&
  961. iids2contents[iid].nodes[edge['dest']] != undefined )
  962. iids2contents[iid].edges.push(edge);
  963. });
  964. /* 2e */
  965. var iidCSIcon = csm.nodes[ ids2csids[iid] ];
  966. for( var vid in iids2contents[iid].nodes )
  967. {
  968. var vidCSIcon = csm.nodes[ ids2csids[vid] ],
  969. vidContentsNode = iids2contents[iid].nodes[vid];
  970. ['position','orientation','scale','link-style'].forEach(
  971. function(_) {vidContentsNode[_] = vidCSIcon[_];});
  972. var vidContentsNodePosition = vidContentsNode['position']['value'],
  973. iidCSIconPosition = iidCSIcon['position']['value'],
  974. vidContentsNodeRelX = vidContentsNodePosition[0] - iidCSIconPosition[0],
  975. vidContentsNodeRelY = vidContentsNodePosition[1] - iidCSIconPosition[1];
  976. vidContentsNode['position']['value'] = [vidContentsNodeRelX,vidContentsNodeRelY];
  977. /* 2e* */
  978. if( model.nodes[iid]['$type'] == CS+'/Link' )
  979. {
  980. var sx = iidCSIcon['scale']['value'][0],
  981. sy = iidCSIcon['scale']['value'][1],
  982. linkPathBBox =
  983. {'x':sx*35,
  984. 'y':sy*77,
  985. 'width': sx*198,
  986. 'height': sy*(model.nodes[iid]['link-style']['stroke-width'] || 1)};
  987. vidContentsNode['position']['value'] = [0,0];
  988. vidContentsNode['$linkDecoratorInfo'] =
  989. {'type':'map<string,double>',
  990. 'value':
  991. {'xratio' :(vidContentsNodeRelX-linkPathBBox.x) / (linkPathBBox.width-linkPathBBox.x),
  992. 'yoffset':vidContentsNodeRelY - (linkPathBBox.y+linkPathBBox.height/2)}};
  993. }
  994. }
  995. /* 2f */
  996. if( model.nodes[iid]['$type'] == CS+'/Link' )
  997. {
  998. var contents = csm.nodes[ids2csids[iid]]['$contents']['value'].nodes,
  999. sy = iidCSIcon['scale']['value'][1];
  1000. ['arrowHead','arrowTail'].forEach(
  1001. function(at)
  1002. {
  1003. if( !(at in model.nodes[iid]) )
  1004. throw 'migrate to new Link specification means to compile';
  1005. var a = model.nodes[iid][at]['value'];
  1006. if( a != 'custom' )
  1007. for( var vid in contents )
  1008. if( 'mapper' in contents[vid] &&
  1009. ( _styleinfo[a + ':' + at] ) && (matches = contents[vid]['mapper']['value'].match("^'"+a+":"+at+":(.*)';")) )
  1010. {
  1011. iids2contents[iid].nodes[vid] = contents[vid];
  1012. iids2contents[iid].nodes[vid]['mapper']['value'] = '';
  1013. iids2contents[iid].nodes[vid]['position']['value'] = [0,0];
  1014. iids2contents[iid].nodes[vid]['$linkDecoratorInfo'] =
  1015. {'type':'map<string,double>',
  1016. 'value':
  1017. {'xratio' :(at == 'arrowHead' ? -1 : 1),
  1018. 'yoffset':-_styleinfo[a + ':' + at]/2*sy}};
  1019. break;
  1020. }
  1021. });
  1022. }
  1023. /* 3 */
  1024. var node = model.nodes[iid];
  1025. type = node['typename']['value'];
  1026. isConnectorType = 'link-style' in node;
  1027. mm.types[type] = [];
  1028. self.metamodels[CS].
  1029. types[(isConnectorType ? 'Link' : 'Icon')].forEach(
  1030. function(attr)
  1031. {
  1032. if( _utils.contains(['link-style','typename','mapper','parser','position'],attr['name']) )
  1033. mm.types[type].push(
  1034. {'name': attr['name'],
  1035. 'type': node[attr['name']]['type'],
  1036. 'default': node[attr['name']]['value']});
  1037. else
  1038. mm.types[type].push(attr);
  1039. });
  1040. mm.types[type].push(
  1041. {'name': '$contents',
  1042. 'type': 'map<string,*>',
  1043. 'default': iids2contents[iid]},
  1044. {'name': '$asuri',
  1045. 'type': 'string',
  1046. 'default': '-1'});
  1047. if( isConnectorType )
  1048. mm.types[type].push(
  1049. {'name': '$segments',
  1050. 'type': 'map<string,list<string>>',
  1051. 'default': {}});
  1052. mm.cardinalities[type] = [];
  1053. mm.types2parentTypes[type] = [];
  1054. });
  1055. /* 4 */
  1056. var types = [],
  1057. abstractTypes = [];
  1058. for (var idx in asmm["constraints"]) {
  1059. var curr_constraint = asmm["constraints"][idx];
  1060. if (curr_constraint["name"] == "noAbstractInstances") {
  1061. abstractTypes.push(curr_constraint["targetType"]);
  1062. }
  1063. }
  1064. for (var curr_type in asmm["types"]) {
  1065. if ((curr_type + 'Link' in mm["types"]) || (curr_type + 'Icon' in mm["types"])) {
  1066. if (abstractTypes.indexOf(curr_type) >= 0) {
  1067. return {'$err':'abstract type '+curr_type+' cannot have a visual representation'};
  1068. }
  1069. } else {
  1070. if (abstractTypes.indexOf(curr_type) < 0) {
  1071. return {'$err':'concrete type '+curr_type+' needs to have a visual representation'};
  1072. }
  1073. }
  1074. }
  1075. for (var curr_type in mm["types"]) {
  1076. if (!(curr_type.slice(0, -4) in asmm["types"])) {
  1077. return {'$err':'type '+curr_type.slice(0, -4)+' not found in the abstract syntax metamodel, visual representation ' + curr_type + ' invalid'};
  1078. }
  1079. }
  1080. /* 5 */
  1081. return _utils.jsons(mm,null,"\t");
  1082. }
  1083. catch(err)
  1084. {
  1085. return {'$err':'invalid metamodel model, crashed on :: '+err};
  1086. }
  1087. },
  1088. /* compile the current model into a metamodel
  1089. 0. the entire function body is wrapped in a try/catch... this is our lazy
  1090. approach to verifying that the current model is indeed a valid model of
  1091. a metamodel
  1092. 1. if the current model is not an ER or a SCD model, return error
  1093. 2. if the current model is a SCD model, transform it into an ER model
  1094. before beginning compilation (via _mt.transform)
  1095. 3. copy information about types, constraints, actions, cardinalities,
  1096. connectorTypes and types2parentTypes from current model to mm
  1097. 4. add any missing cardinalities (relationships between entities define
  1098. legal connections but the user might have omitted to specify their
  1099. cardinalities), then construct legalConnections and store it in mm
  1100. 5. return mm stringified (ensures no references to objects in this.model
  1101. are returned) */
  1102. 'compileToMetamodel' :
  1103. function()
  1104. {
  1105. var ER = '/Formalisms/__LanguageSyntax__/EntityRelationship/EntityRelationship',
  1106. SCD = '/Formalisms/__LanguageSyntax__/SimpleClassDiagram/SimpleClassDiagram',
  1107. isolateMMModel =
  1108. /* remove all non-ER/SCD entities from the provided model...
  1109. doing so considerably eases compilation */
  1110. function(m)
  1111. {
  1112. m = _utils.jsonp(m);
  1113. for( var id in m.nodes )
  1114. if( ! m.nodes[id]['$type'].match('^'+ER) &&
  1115. ! m.nodes[id]['$type'].match('^'+SCD) )
  1116. delete m.nodes[id];
  1117. var keepEdges = [];
  1118. m.edges.forEach(
  1119. function(edge,i)
  1120. {
  1121. if( edge['src'] in m.nodes && edge['dest'] in m.nodes )
  1122. keepEdges.push(edge);
  1123. });
  1124. m.edges = keepEdges;
  1125. return m;
  1126. };
  1127. try
  1128. {
  1129. /* 1-2 */
  1130. if( _utils.contains(this.model.metamodels,ER) &&
  1131. _utils.contains(this.model.metamodels,SCD) )
  1132. throw 'metamodel models should not have more than one loaded metametamodel';
  1133. else if( _utils.contains(this.model.metamodels,ER) )
  1134. var model = isolateMMModel(this.read());
  1135. else if( _utils.contains(this.model.metamodels,SCD) )
  1136. var model = _mt.transform(
  1137. _utils.jsons(isolateMMModel(this.read())),
  1138. 'SimpleClassDiagram-2-EntityRelationship');
  1139. else
  1140. throw 'metamodel models should have at least one loaded metametamodel';
  1141. /* 3 */
  1142. var mm =
  1143. {'types':{},
  1144. 'constraints':[],
  1145. 'actions':[],
  1146. 'cardinalities':{},
  1147. 'legalConnections':{},
  1148. 'connectorTypes':{},
  1149. 'types2parentTypes':{}};
  1150. for( var id in model.nodes )
  1151. {
  1152. var node = model.nodes[id];
  1153. if( node['$type'] == ER+'/Entity' ||
  1154. node['$type'] == ER+'/Relationship' )
  1155. {
  1156. var type = node['name']['value'];
  1157. mm.types[type] = [];
  1158. node['attributes']['value'].forEach(
  1159. function(attr) {mm.types[type].push(attr);});
  1160. node['constraints']['value'].forEach(
  1161. function(constraint)
  1162. {
  1163. constraint['targetType'] = type;
  1164. mm.constraints.push(constraint);
  1165. });
  1166. node['actions']['value'].forEach(
  1167. function(action)
  1168. {
  1169. action['targetType'] = type;
  1170. mm.actions.push(action);
  1171. });
  1172. mm.cardinalities[type] = node['cardinalities']['value'];
  1173. if( node['linktype'] != undefined )
  1174. mm.connectorTypes[type] = node['linktype']['value'];
  1175. }
  1176. else if( node['$type'] == ER+'/GlobalConstraint' )
  1177. mm.constraints.push(
  1178. {'name':node['name']['value'],
  1179. 'event':node['event']['value'],
  1180. 'targetType':'*',
  1181. 'code':node['code']['value']});
  1182. else if( node['$type'] == ER+'/GlobalAction' )
  1183. mm.actions.push(
  1184. {'name':node['name']['value'],
  1185. 'event':node['event']['value'],
  1186. 'targetType':'*',
  1187. 'code':node['code']['value']});
  1188. else
  1189. throw 'node "'+id+'" does not conform to the '+ER+' metamodel';
  1190. }
  1191. mm.types2parentTypes = model.types2parentTypes || {};
  1192. /* 4 */
  1193. var types2legalNeighborTypes = {},
  1194. addMissingCardinalities =
  1195. function(t1,t2,dir)
  1196. {
  1197. /* if there is no cardinality between t1 and t2 for dir, add a default cardinality...
  1198. 1:1 for links
  1199. 0:Infinity for nodes */
  1200. if( ! mm.cardinalities[t1].some( function(c) {return c['type'] == t2 && c['dir'] == dir;} ) )
  1201. {
  1202. if( mm.connectorTypes[t1] )
  1203. mm.cardinalities[t1].push(
  1204. {'dir':dir,
  1205. 'type':t2,
  1206. 'min':'0',
  1207. 'max':'1'});
  1208. else
  1209. mm.cardinalities[t1].push(
  1210. {'dir':dir,
  1211. 'type':t2,
  1212. 'min':'0',
  1213. 'max':'Infinity'});
  1214. }
  1215. };
  1216. model.edges.forEach(
  1217. function(edge)
  1218. {
  1219. var srcType = model.nodes[edge['src']]['name']['value'],
  1220. destType = model.nodes[edge['dest']]['name']['value'];
  1221. addMissingCardinalities(srcType,destType,'out',mm.connectorTypes[srcType]);
  1222. addMissingCardinalities(destType,srcType,'in',mm.connectorTypes[destType]);
  1223. });
  1224. for( var type in mm.types )
  1225. {
  1226. if( types2legalNeighborTypes[type] == undefined )
  1227. types2legalNeighborTypes[type] = [];
  1228. mm.cardinalities[type].forEach(
  1229. function(cardinality)
  1230. {
  1231. if( cardinality['dir'] == 'out' )
  1232. types2legalNeighborTypes[type].push(cardinality['type']);
  1233. });
  1234. }
  1235. for( var type in types2legalNeighborTypes )
  1236. {
  1237. if( mm.connectorTypes[type] != undefined )
  1238. continue;
  1239. types2legalNeighborTypes[type].forEach(
  1240. function(ntype)
  1241. {
  1242. types2legalNeighborTypes[ntype].forEach(
  1243. function(nntype)
  1244. {
  1245. if( mm.legalConnections[type] == undefined )
  1246. mm.legalConnections[type] = {};
  1247. if( mm.legalConnections[type][nntype] == undefined )
  1248. mm.legalConnections[type][nntype] = [];
  1249. mm.legalConnections[type][nntype].push(ntype);
  1250. });
  1251. });
  1252. }
  1253. /* 5 */
  1254. return _utils.jsons(mm,null,"\t");
  1255. }
  1256. catch(err)
  1257. {
  1258. return {'$err':'invalid metamodel model, crashed on :: '+err};
  1259. }
  1260. },
  1261. /************************* JOURNALING + UNDO/REDO **************************/
  1262. 'journal':[],
  1263. 'journalIndex':0,
  1264. /* NOTE: on this.undoredoJournal
  1265. this.undoredoJournal contains cud operations performed during the last
  1266. undo()/redo() call provided no user-operations was performed since the
  1267. said call (in which case this.undoredoJournal is empty)... undo/redo
  1268. ops need to be logged for __changelog() to be able to return their
  1269. effects... however, they should not be logged in the main journal since
  1270. all they conceptually do is move a cursor in it... in practice,
  1271. this.undoredoJournal is emptied on every call to undo(), redo() and
  1272. __setStepCheckpoint() */
  1273. /* create a checkpoint : add an entry in the log used as a delimiter to know
  1274. where to stop when restoring (i.e., undoing failed pre-/post-actions or
  1275. crud ops) */
  1276. '__checkpoint' :
  1277. function()
  1278. {
  1279. this.__log({'op':'MKCHKPT'});
  1280. },
  1281. /* deletes the last checkpoint of the current model (other than tidying the
  1282. journal, there's no reason for ever clearing unused checkpoints) */
  1283. '__clearCheckpoint' :
  1284. function()
  1285. {
  1286. for( var i=this.journal.length-1; i>=0; i-- )
  1287. if( this.journal[i]['op'] == 'MKCHKPT' )
  1288. {
  1289. this.journal.splice(i,1);
  1290. this.journalIndex--;
  1291. break;
  1292. }
  1293. },
  1294. /* case 1: 'this.undoredoJournal is defined (possibly empty)'
  1295. returns the operations performed by the last undo()/redo()
  1296. case 2: 'this.undoredoJournal = undefined'
  1297. returns a copy of the portion of the journal that describes the changes
  1298. made by the last user-operation... note that user-operations always call
  1299. __setStepCheckpoint before running */
  1300. '__changelog' :
  1301. function()
  1302. {
  1303. if( this.undoredoJournal != undefined )
  1304. return _utils.clone( this.undoredoJournal.splice(0) );
  1305. var ji = this.journalIndex;
  1306. while( ji > 0 )
  1307. if( this.journal[--ji]['op'] == 'MKSTPCHKPT' )
  1308. break;
  1309. return _utils.clone( this.journal.slice(ji+1,this.journalIndex) );
  1310. },
  1311. /* case 1: 'log=undefined'
  1312. logs an internal cud operation into the journal... if the current index in
  1313. the journal is anything but the end of the journal, clear everything after
  1314. the index (this effectively erases the command "future-history" when
  1315. editing an "undone" model)
  1316. case 2: 'log="UNDOREDO"'
  1317. logs an internal cud operation into this.undoredoJournal
  1318. case 3: 'log="DONTLOG"'
  1319. do nothing
  1320. legal logging commands:
  1321. MKNODE id,node
  1322. RMNODE id,node
  1323. MKEDGE id,id
  1324. RMEDGE id,id
  1325. CHATTR id,attr,new_val,old_val
  1326. LOADMM name,mm
  1327. DUMPMM name,mm
  1328. RESETM name,model
  1329. MKCHKPT
  1330. MKSTPCHKPT
  1331. MKUSRCHKPT */
  1332. '__log' :
  1333. function(step,log)
  1334. {
  1335. if( log == undefined )
  1336. {
  1337. if( this.journalIndex != this.journal.length )
  1338. this.journal.splice(this.journalIndex);
  1339. this.journal.push(step);
  1340. this.journalIndex++;
  1341. }
  1342. else if( log == 'UNDOREDO' )
  1343. this.undoredoJournal.push(step);
  1344. else if( log == 'DONTLOG' )
  1345. ;
  1346. },
  1347. /* redo a single step
  1348. 1. identify the nature of the logged operation
  1349. 2. reproduce its effects (these are logged in this.undoredoJournal) */
  1350. '__redo' :
  1351. function(step)
  1352. {
  1353. var log = 'UNDOREDO';
  1354. if( step['op'] == 'CHATTR' ) this.__chattr__(step['id'],step['attr'],step['new_val'],log);
  1355. else if( step['op'] == 'DUMPMM' ) this.__dumpmm__(step['name'],log);
  1356. else if( step['op'] == 'LOADMM' ) this.__loadmm__(step['name'],step['mm'],log);
  1357. else if( step['op'] == 'MKEDGE' ) this.__mkedge__(step['id1'],step['id2'],step['i'],log);
  1358. else if( step['op'] == 'MKNODE' ) this.__mknode__(step['id'],_utils.jsonp(step['node']),log);
  1359. else if( step['op'] == 'RESETM' ) this.__resetm__(step['new_name'],step['new_model'],false,log);
  1360. else if( step['op'] == 'RMEDGE' ) this.__rmedge__(step['i'],log);
  1361. else if( step['op'] == 'RMNODE' ) this.__rmnode__(step['id'],log);
  1362. },
  1363. /* redo all of the changes until the next step-checkpoint or until after the
  1364. specified user-checkpoint, if any... when complete the journal index is
  1365. after the redone MKSTPCHKPT/MKUSRCHKPT entry... redoing when the journal
  1366. index is at the end of the journal will have no effect */
  1367. 'redo' :
  1368. function(uchkpt)
  1369. {
  1370. this.undoredoJournal = [];
  1371. var stopMarkerReached =
  1372. (uchkpt == undefined ?
  1373. function(step) {return step['op'] == 'MKSTPCHKPT';} :
  1374. function(step) {return uchkptEncountered && step['op'] == 'MKUSRCHKPT';}),
  1375. self = this,
  1376. uchkptEncountered = false,
  1377. uchkptReached = function(step) {return step['op'] == 'MKUSRCHKPT' && step['name'] == uchkpt;},
  1378. uchkptFound =
  1379. function(i)
  1380. {
  1381. while( i < self.journal.length )
  1382. if( uchkptReached(self.journal[i++]) )
  1383. return true;
  1384. return false;
  1385. };
  1386. if( uchkpt == undefined || uchkptFound(this.journalIndex) )
  1387. while( this.journalIndex < this.journal.length )
  1388. {
  1389. if( uchkpt != undefined &&
  1390. ! uchkptEncountered &&
  1391. uchkptReached(this.journal[this.journalIndex]) )
  1392. uchkptEncountered = true;
  1393. if( this.journal[++this.journalIndex] == undefined ||
  1394. stopMarkerReached( this.journal[this.journalIndex] ) )
  1395. break;
  1396. else
  1397. this.__redo(this.journal[this.journalIndex]);
  1398. }
  1399. return {'changelog':this.__changelog()};
  1400. },
  1401. /* undo every logged operation until a MKCHKPT is reached (and remove them
  1402. and the said MKCHKPT from the journal)... note that this operation is only
  1403. called internally and that the journalIndex will always be at the end of
  1404. the journal when it's called (and after its called) */
  1405. '__restoreCheckpoint' :
  1406. function()
  1407. {
  1408. while( this.journal.length > 0 )
  1409. {
  1410. var step = this.journal.pop();
  1411. if(step['op'] == 'MKCHKPT' )
  1412. break;
  1413. else
  1414. this.__undo(step,'DONTLOG');
  1415. }
  1416. this.journalIndex = this.journal.length;
  1417. },
  1418. /* create a step-checkpoint : add an entry in the log used as a delimiter to
  1419. know where to stop when undoing/redoing (i.e., on client undo/redo)
  1420. 1. create new step-checkpoint or re-use a 'zombie' step-checkpoint (zombie
  1421. step-checkpoints (SC) are SCs associated to failed or effectless user
  1422. operations... they are recognizable as SCs with no following log
  1423. entries... there's at most 1 zombie SC in the log at any given time) */
  1424. '__setStepCheckpoint' :
  1425. function()
  1426. {
  1427. this.undoredoJournal = undefined;
  1428. if( this.journal.length == 0 ||
  1429. this.journal[this.journal.length-1]['op'] != 'MKSTPCHKPT' )
  1430. this.__log({'op':'MKSTPCHKPT'});
  1431. },
  1432. /* create a user-checkpoint : add an entry in the log used as a delimiter to
  1433. enable undoing/redoing until a specified marker
  1434. 1. create new step-checkpoint or re-use a 'zombie' user-checkpoint (zombie
  1435. user-checkpoints (UC) are UCs associated to failed or effectless user
  1436. operations... they are recognizable as same-name UCs with no following
  1437. log entries... there's at most 1 zombie UC per name in the log at any
  1438. given time) */
  1439. 'setUserCheckpoint' :
  1440. function(name)
  1441. {
  1442. this.undoredoJournal = undefined;
  1443. if( this.journal.length == 0 ||
  1444. this.journal[this.journal.length-1]['op'] != 'MKUSRCHKPT' ||
  1445. this.journal[this.journal.length-1]['name'] != name )
  1446. this.__log({'op':'MKUSRCHKPT','name':name});
  1447. },
  1448. /* undo a single step
  1449. 1. identify the nature of the logged operation
  1450. 2. invert its effects (these may be ignored (log = 'DONTLOG') or logged in
  1451. this.undoredoJournal (log = 'UNDOREDO') */
  1452. '__undo' :
  1453. function(step,log)
  1454. {
  1455. if( step['op'] == 'CHATTR' ) this.__chattr__(step['id'],step['attr'],step['old_val'],log);
  1456. else if( step['op'] == 'DUMPMM' ) this.__loadmm__(step['name'],step['mm'],log);
  1457. else if( step['op'] == 'LOADMM' ) this.__dumpmm__(step['name'],log);
  1458. else if( step['op'] == 'MKEDGE' ) this.__rmedge__(step['i'],log);
  1459. else if( step['op'] == 'MKNODE' ) this.__rmnode__(step['id'],log);
  1460. else if( step['op'] == 'RESETM' ) this.__resetm__(step['old_name'],step['old_model'],false,log);
  1461. else if( step['op'] == 'RMEDGE' ) this.__mkedge__(step['id1'],step['id2'],step['i'],log);
  1462. else if( step['op'] == 'RMNODE' ) this.__mknode__(step['id'],_utils.jsonp(step['node']),log);
  1463. },
  1464. /* undo all of the changes since the last step-checkpoint or since the
  1465. specified user-checkpoint, if any... when complete the journal index is on
  1466. the undone MKSTPCHKPT/MKUSRCHKPT entry... undoing when the journal index is 0
  1467. or when a non-existing user-checkpoint is given will have no effect */
  1468. 'undo':
  1469. function(uchkpt)
  1470. {
  1471. this.undoredoJournal = [];
  1472. var stopMarkerReached =
  1473. (uchkpt == undefined ?
  1474. function(step) {return step['op'] == 'MKSTPCHKPT';} :
  1475. function(step) {return step['op'] == 'MKUSRCHKPT' && step['name'] == uchkpt;}),
  1476. self = this,
  1477. stopMarkerFound =
  1478. function(i)
  1479. {
  1480. while( --i >= 0 )
  1481. if( stopMarkerReached(self.journal[i]) )
  1482. return true;
  1483. return false;
  1484. };
  1485. if( uchkpt == undefined || stopMarkerFound(this.journalIndex) )
  1486. while( this.journalIndex > 0 )
  1487. if( stopMarkerReached( this.journal[--this.journalIndex] ) )
  1488. break;
  1489. else
  1490. this.__undo(this.journal[this.journalIndex],'UNDOREDO');
  1491. return {'changelog':this.__changelog()};
  1492. },
  1493. /****************************** INTERNAL CUD *******************************/
  1494. /* the following functions are super basic and low-level, they offer cud (no
  1495. read) commands on this' internal data structures... their main purposes
  1496. are (1) to localize the said cud operations, and (2) to log everything
  1497. they do... logging enables undoing and redoing (on constraint/action/...
  1498. failure or on client requests) and facilitates change pushing (i.e., push
  1499. a short change log rather the full model)... note that it is assumed that
  1500. only valid parameters are passed to these functions... last but not least,
  1501. the optional 'log' parameter is used when undoing/redoing to log undoing/
  1502. redoing cud ops elsewhere than in this.journal
  1503. __chattr__ change an attribute's value
  1504. > log id,attr,new_val,old_val
  1505. __dumpmm__ remove mm from this.model.metamodels and this.metamodels
  1506. > log name,mm
  1507. __loadmm__ add a mm to this.model.metamodels and this.metamodels
  1508. > log name,mm
  1509. __mkedge__ add an edge to this.model.edges... optional 'i' parameter
  1510. specifies index of new edge in this.model.edges
  1511. > log id1,id2,i
  1512. __mknode__ add a node to this.model.nodes
  1513. > log id,node
  1514. __resetm__ when the 'insert' parameter is false, replaces the current
  1515. model with another + updates this.next_id to account for ids
  1516. in loaded model + updates model.metamodels to account for
  1517. metamodels loaded before the model
  1518. when the 'insert' parameter is true, inserts the given model
  1519. alongside the current model + alters the given model's ids to
  1520. avoid clashes with existing ids + updates this.next_id... the
  1521. logged value of 'insert' ends up being the offset we applied
  1522. to the provided model's ids
  1523. > log new_name,new_model,old_name,old_model,insert
  1524. __rmedge__ remove an edge from this.model.edges
  1525. > log id1,id2,i
  1526. __rmnode__ remove a node from this.model.nodes
  1527. > log id,node
  1528. note: these functions never log any 'live' data into the log (i.e., any
  1529. references that could be altered elsewhere thereby altering the
  1530. journal's contents) */
  1531. '__chattr__' :
  1532. function(id,attr,new_val,log)
  1533. {
  1534. var getattr = undefined,
  1535. setattr = undefined,
  1536. attrval = function(v) {return (v == undefined ? v : _utils.jsonp(v));},
  1537. self = this;
  1538. if( attr.match(/.+\/.+/) )
  1539. {
  1540. var curr = this.model.nodes[id];
  1541. for( var i in (path = attr.split('/')) )
  1542. curr = curr[path[i]];
  1543. getattr = function() {return curr['value'];};
  1544. setattr = function(v) {curr['value'] = v;};
  1545. }
  1546. else
  1547. {
  1548. getattr = function() {return self.model.nodes[id][attr]['value'];};
  1549. setattr = function(v) {self.model.nodes[id][attr]['value'] = v;};
  1550. }
  1551. var _old_val = _utils.jsons(getattr()),
  1552. _new_val = _utils.jsons(new_val);
  1553. if( _old_val == _new_val )
  1554. return;
  1555. setattr( attrval(_new_val) );
  1556. this.__log(
  1557. {'op':'CHATTR',
  1558. 'id':id,
  1559. 'attr':attr,
  1560. 'new_val': attrval(_new_val),
  1561. 'old_val': attrval(_old_val)},
  1562. log);
  1563. },
  1564. '__dumpmm__' :
  1565. function(name,log)
  1566. {
  1567. for( var i in this.model.metamodels )
  1568. if( this.model.metamodels[i] == name )
  1569. {
  1570. this.model.metamodels.splice(i,1);
  1571. break;
  1572. }
  1573. var mm = this.metamodels[name];
  1574. delete this.metamodels[name];
  1575. this.__log(
  1576. {'op':'DUMPMM',
  1577. 'name':name,
  1578. 'mm':_utils.jsons(mm)},
  1579. log);
  1580. },
  1581. '__loadmm__' :
  1582. function(name,mm,log)
  1583. {
  1584. this.metamodels[name] = eval('('+ mm +')');
  1585. if( ! _utils.contains(this.model.metamodels,name) )
  1586. this.model.metamodels.push(name);
  1587. this.__log(
  1588. {'op':'LOADMM',
  1589. 'name':name,
  1590. 'mm':mm},
  1591. log);
  1592. },
  1593. '__mkedge__' :
  1594. function(id1,id2,i,log)
  1595. {
  1596. if( i == undefined )
  1597. i = this.model.edges.push({'src':id1, 'dest':id2})-1;
  1598. else
  1599. this.model.edges.splice(i,0,{'src':id1, 'dest':id2});
  1600. this.__log(
  1601. {'op':'MKEDGE',
  1602. 'id1':id1,
  1603. 'id2':id2,
  1604. 'i':i},
  1605. log);
  1606. },
  1607. '__mknode__' :
  1608. function(id,node,log)
  1609. {
  1610. this.model.nodes[id] = node;
  1611. this.__log(
  1612. {'op':'MKNODE',
  1613. 'id':id,
  1614. 'node':_utils.jsons(node)},
  1615. log);
  1616. },
  1617. '__resetm__' :
  1618. function(new_name,new_model,insert,log)
  1619. {
  1620. var old_model = this.read(),
  1621. old_name = this.name;
  1622. if( insert )
  1623. {
  1624. var _new_model = eval('('+ new_model +')');
  1625. for( var id in _new_model.nodes )
  1626. this.model.nodes[parseInt(id)+this.next_id] = _new_model.nodes[id];
  1627. _new_model.edges.forEach(
  1628. function(edge)
  1629. {
  1630. this.model.edges.push(
  1631. {'src': parseInt(edge.src)+this.next_id,
  1632. 'dest': parseInt(edge.dest)+this.next_id});
  1633. }, this);
  1634. new_model = this.read();
  1635. insert = this.next_id;
  1636. }
  1637. else
  1638. {
  1639. this.model = eval('('+ new_model +')');
  1640. for( var mm in this.metamodels )
  1641. if( ! _utils.contains(this.model.metamodels,mm) )
  1642. this.model.metamodels.push(mm);
  1643. }
  1644. this.name = new_name;
  1645. for( var id in this.model.nodes )
  1646. if( id >= this.next_id )
  1647. this.next_id = parseInt(id)+1;
  1648. this.__log(
  1649. {'op':'RESETM',
  1650. 'new_name': new_name,
  1651. 'new_model':new_model,
  1652. 'old_name': old_name,
  1653. 'old_model':old_model,
  1654. 'insert':insert},
  1655. log);
  1656. },
  1657. '__rmedge__' :
  1658. function(i,log)
  1659. {
  1660. var edge = this.model.edges.splice(i,1).pop();
  1661. this.__log(
  1662. {'op':'RMEDGE',
  1663. 'i':i,
  1664. 'id1':edge['src'],
  1665. 'id2':edge['dest']},
  1666. log);
  1667. },
  1668. '__rmnode__' :
  1669. function(id,log)
  1670. {
  1671. node = this.model.nodes[id];
  1672. delete this.model.nodes[id];
  1673. this.__log(
  1674. {'op':'RMNODE',
  1675. 'id':id,
  1676. 'node':_utils.jsons(node)},
  1677. log);
  1678. },
  1679. /***************************** INTERNAL UTILS ******************************/
  1680. /* splits a full type of the form '/path/to/metamodel/type' and returns
  1681. '/path/to/metamodel' */
  1682. '__getMetamodel' :
  1683. function(fulltype)
  1684. {
  1685. return fulltype.match(/(.*)\/.*/)[1];
  1686. },
  1687. /* splits a full type of the form '/path/to/metamodel/type' and returns
  1688. 'type' */
  1689. '__getType' :
  1690. function(fulltype)
  1691. {
  1692. return fulltype.match(/.*\/(.*)/)[1];
  1693. }
  1694. };