mmmk.js 62 KB

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