mmmk.js 62 KB

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