mmmk.js 62 KB

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