mmmk.js 62 KB

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