modelverse.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786
  1. from sccd.runtime.statecharts_core import Event
  2. import sccd.runtime.socket2event as socket2event
  3. import modelverse_SCCD as modelverse_SCCD
  4. import time
  5. import threading
  6. import sys
  7. if sys.version_info[0] < 3:
  8. from urllib2 import urlopen as urlopen
  9. from urllib2 import Request as Request
  10. from urllib import urlencode as urlencode
  11. else:
  12. from urllib.request import urlopen as urlopen
  13. from urllib.request import Request as Request
  14. from urllib.parse import urlencode as urlencode
  15. # Exceptions
  16. class ModelverseException(Exception):
  17. pass
  18. class SuperclassAttribute(ModelverseException):
  19. pass
  20. class CallbackOnEmptySignature(ModelverseException):
  21. pass
  22. class NotAModel(ModelverseException):
  23. pass
  24. class ManualActivityRequiresIO(ModelverseException):
  25. pass
  26. class UserNotInGroup(ModelverseException):
  27. pass
  28. class IncorrectFormat(ModelverseException):
  29. pass
  30. class SignatureMismatch(ModelverseException):
  31. pass
  32. class EmptySignature(SignatureMismatch):
  33. pass
  34. class SourceModelNotBound(SignatureMismatch):
  35. pass
  36. class TargetModelNotBound(SignatureMismatch):
  37. pass
  38. class DifferingModelsForKey(SignatureMismatch):
  39. pass
  40. class TypeMismatch(SignatureMismatch):
  41. pass
  42. class UnknownError(ModelverseException):
  43. pass
  44. class UnknownM3(ModelverseException):
  45. pass
  46. class UnknownIdentifier(ModelverseException):
  47. pass
  48. class CompilationError(ModelverseException):
  49. pass
  50. class NotAnActivity(ModelverseException):
  51. pass
  52. class NotAProcess(ModelverseException):
  53. pass
  54. class NotAValidProcess(ModelverseException):
  55. pass
  56. class UnknownAttribute(UnknownIdentifier):
  57. pass
  58. class UnknownElement(UnknownIdentifier):
  59. pass
  60. class UnknownModel(UnknownIdentifier):
  61. pass
  62. class UnknownLocation(UnknownIdentifier):
  63. pass
  64. class UnknownGroup(UnknownIdentifier):
  65. pass
  66. class UnknownUser(UnknownIdentifier):
  67. pass
  68. class ConnectionError(ModelverseException):
  69. pass
  70. class ExistsError(ModelverseException):
  71. pass
  72. class AttributeExists(ExistsError):
  73. pass
  74. class ElementExists(ExistsError):
  75. pass
  76. class ModelExists(ExistsError):
  77. pass
  78. class FolderExists(ExistsError):
  79. pass
  80. class GroupExists(ExistsError):
  81. pass
  82. class UserExists(ExistsError):
  83. pass
  84. class PermissionDenied(ModelverseException):
  85. pass
  86. class ReadPermissionDenied(PermissionDenied):
  87. pass
  88. class WritePermissionDenied(PermissionDenied):
  89. pass
  90. class ExecutePermissionDenied(PermissionDenied):
  91. pass
  92. class UserPermissionDenied(PermissionDenied):
  93. pass
  94. class GroupPermissionDenied(PermissionDenied):
  95. pass
  96. class AdminPermissionDenied(PermissionDenied):
  97. pass
  98. class InterfaceMismatch(ModelverseException):
  99. pass
  100. class UnknownMetamodellingHierarchy(ModelverseException):
  101. pass
  102. class NotAnAssociation(ModelverseException):
  103. pass
  104. def run_controller():
  105. try:
  106. controller.start()
  107. finally:
  108. controller.stop()
  109. def _next_ID():
  110. global ID
  111. ID += 1
  112. return ID
  113. def __run_new_modelverse(address, username, password, callback, model):
  114. init(address)
  115. login(username, password)
  116. callback(model)
  117. exit_save(model)
  118. disconnect()
  119. def __run_new_modelverse_activity(address, username, password, taskname, pipe, callback):
  120. init(address, taskname=taskname)
  121. controller.username = username
  122. controller.password = password
  123. t = OUTPUT()
  124. if t == "OP":
  125. model = OUTPUT()
  126. if callback is not None:
  127. __invoke(callback, model)
  128. controller.addInput(Event("data_input", "action_in", [None]))
  129. time.sleep(2)
  130. elif t == "SC":
  131. while 1:
  132. empty = True
  133. # Fetch output from the MV
  134. response = responses.fetch(0)
  135. if response is not None:
  136. if response.name == "data_output":
  137. # Got output of MV, so forward to SCCD
  138. if pipe is not None:
  139. pipe.send(("input", response.parameters))
  140. elif response.name == "result":
  141. # Finished execution, so continue and return result
  142. if pipe is not None:
  143. pipe.send(("terminate", []))
  144. pipe.close()
  145. return
  146. else:
  147. raise Exception("Unknown data from MV to SC: " + str(response))
  148. empty = False
  149. # Fetch output from the SC
  150. if pipe is not None and pipe.poll():
  151. response = pipe.recv()
  152. if response.name == "output":
  153. controller.addInput(Event("data_input", "action_in", [response.parameters]))
  154. else:
  155. raise Exception("Unknown data from SC to MV: " + str(response))
  156. empty = False
  157. if empty:
  158. time.sleep(0.05)
  159. def __invoke(callback, model):
  160. import multiprocessing
  161. p = multiprocessing.Process(target=__run_new_modelverse, args=[controller.address, controller.username, controller.password, callback, model])
  162. p.start()
  163. p.join()
  164. def _process_SC(statechart, port_sc, taskname):
  165. import multiprocessing
  166. p2c_pipe, c2p_pipe = multiprocessing.Pipe()
  167. p = multiprocessing.Process(target=__run_new_modelverse_activity, args=[controller.address, controller.username, controller.password, taskname, c2p_pipe, None])
  168. p.start()
  169. while 1:
  170. empty = True
  171. if p2c_pipe.poll():
  172. response = p2c_pipe.recv()
  173. statechart[0].addInput(Event(response[0], statechart[1], response[1]))
  174. if response[0] == "terminate":
  175. p2c_pipe.close()
  176. break
  177. empty = False
  178. response = port_sc.fetch(0)
  179. if response is not None:
  180. p2c_pipe.send(response)
  181. empty = False
  182. if empty:
  183. time.sleep(0.05)
  184. p.join()
  185. def _process_OP(callback, taskname):
  186. import multiprocessing
  187. p = multiprocessing.Process(target=__run_new_modelverse_activity, args=[controller.address, controller.username, controller.password, taskname, None, callback])
  188. p.start()
  189. p.join()
  190. def INPUT(action, parameters):
  191. controller.addInput(Event("action", "action_in", [action, _next_ID(), parameters]))
  192. def OUTPUT():
  193. while 1:
  194. response = responses.fetch(-1)
  195. if response.name == "result":
  196. return response.parameters[1]
  197. elif response.name == "exception":
  198. try:
  199. raise eval(response.parameters[1])(*response.parameters[2:])
  200. except NameError:
  201. raise UnknownError(response.parameters[1:])
  202. def init(address_param="127.0.0.1:8001", timeout=60.0, taskname=None):
  203. global controller
  204. global ID
  205. global responses
  206. controller = modelverse_SCCD.Controller(taskname)
  207. socket2event.boot_translation_service(controller)
  208. ID = 0
  209. thrd = threading.Thread(target=run_controller)
  210. thrd.daemon = True
  211. thrd.start()
  212. responses = controller.addOutputListener("action_out")
  213. controller.addOutputListener("ready").fetch(-1)
  214. INPUT("init", [address_param, timeout])
  215. controller.address = address_param
  216. OUTPUT()
  217. return
  218. def login(username, password):
  219. controller.username = username
  220. controller.password = password
  221. INPUT("login", [username, password])
  222. return OUTPUT()
  223. def model_list(location):
  224. INPUT("model_list", [location])
  225. return OUTPUT()
  226. def user_password(username, password):
  227. INPUT("user_password", [username, password])
  228. return OUTPUT()
  229. def model_add(model_name, metamodel_name, model_code=""):
  230. INPUT("model_add", [model_name, metamodel_name, model_code])
  231. return OUTPUT()
  232. def model_define(model_name, metamodel_name, model_code=""):
  233. try:
  234. INPUT("model_add", [model_name, metamodel_name, model_code])
  235. return OUTPUT()
  236. except ModelExists:
  237. INPUT("model_overwrite", [model_name, model_code])
  238. return OUTPUT()
  239. def model_move(source_name, target_name):
  240. INPUT("model_move", [source_name, target_name])
  241. return OUTPUT()
  242. def model_delete(model_name):
  243. INPUT("model_delete", [model_name])
  244. return OUTPUT()
  245. def model_list_full(location):
  246. INPUT("model_list_full", [location])
  247. return OUTPUT()
  248. def verify(model_name, metamodel_name, conformance_function=""):
  249. INPUT("verify", [model_name, metamodel_name, conformance_function])
  250. return OUTPUT()
  251. def model_overwrite(model_name, new_model):
  252. INPUT("model_overwrite", [model_name, new_model])
  253. return OUTPUT()
  254. def disconnect():
  255. INPUT("disconnect", [])
  256. return OUTPUT()
  257. def user_logout():
  258. INPUT("user_logout", [])
  259. return OUTPUT()
  260. def model_render(model_name, mapper_name, rendered_name):
  261. INPUT("model_render", [model_name, mapper_name, rendered_name])
  262. return OUTPUT()
  263. def transformation_between(sources, targets):
  264. INPUT("transformation_between", [sources, targets])
  265. return OUTPUT()
  266. def transformation_add_MT(source_metamodels, target_metamodels, operation_name, code, callback=None):
  267. if len(source_metamodels) + len(target_metamodels) == 0:
  268. if callback is not None:
  269. raise CallbackOnEmptySignature()
  270. INPUT("transformation_add_MT", [source_metamodels, target_metamodels, operation_name, code, True])
  271. model = OUTPUT()
  272. if model is None:
  273. return OUTPUT()
  274. else:
  275. if callback is not None:
  276. __invoke(callback, model)
  277. controller.addInput(Event("data_input", "action_in", [None]))
  278. return OUTPUT()
  279. def transformation_add_AL(source_metamodels, target_metamodels, operation_name, code, callback=None):
  280. if len(source_metamodels) + len(target_metamodels) == 0:
  281. if callback is not None:
  282. raise CallbackOnEmptySignature()
  283. INPUT("transformation_add_AL", [source_metamodels, target_metamodels, operation_name, code, True])
  284. model = OUTPUT()
  285. if model is None:
  286. return OUTPUT()
  287. else:
  288. if callback is not None:
  289. __invoke(callback, model)
  290. controller.addInput(Event("data_input", "action_in", [None]))
  291. return OUTPUT()
  292. def transformation_add_MANUAL(source_metamodels, target_metamodels, operation_name, callback=None):
  293. if len(source_metamodels) + len(target_metamodels) == 0:
  294. if callback is not None:
  295. raise CallbackOnEmptySignature()
  296. INPUT("transformation_add_MANUAL", [source_metamodels, target_metamodels, operation_name, True])
  297. model = OUTPUT()
  298. if model is None:
  299. return None
  300. else:
  301. if callback is not None:
  302. __invoke(callback, model)
  303. controller.addInput(Event("data_input", "action_in", [None]))
  304. return OUTPUT()
  305. def __transformation_execute(operation_name, input_models_dict, output_models_dict, statechart, tracability_model, fetch_output):
  306. if statechart is not None:
  307. port_sc = statechart[0].addOutputListener(statechart[2])
  308. INPUT("transformation_execute", [operation_name, input_models_dict, output_models_dict, tracability_model, fetch_output])
  309. taskname = OUTPUT()
  310. if statechart is not None:
  311. threading.Thread(target=_process_SC, args=[statechart, port_sc, taskname]).start()
  312. return OUTPUT()
  313. def transformation_execute_MT(operation_name, input_models_dict, output_models_dict, statechart=None, tracability_model="", fetch_output=True):
  314. return __transformation_execute(operation_name, input_models_dict, output_models_dict, statechart, tracability_model, fetch_output)
  315. def transformation_execute_AL(operation_name, input_models_dict, output_models_dict, statechart=None, tracability_model="", fetch_output=True):
  316. return __transformation_execute(operation_name, input_models_dict, output_models_dict, statechart, tracability_model, fetch_output)
  317. def transformation_execute_MANUAL(operation_name, input_models_dict, output_models_dict, callback=None, tracability_model=""):
  318. INPUT("transformation_execute", [operation_name, input_models_dict, output_models_dict, tracability_model])
  319. taskname = OUTPUT()
  320. _process_OP(callback, taskname)
  321. return OUTPUT()
  322. def transformation_signature(operation_name):
  323. INPUT("transformation_signature", [operation_name])
  324. return OUTPUT()
  325. def process_signature(process_name):
  326. INPUT("process_signature", [process_name])
  327. return OUTPUT()
  328. def permission_modify(model_name, permissions):
  329. INPUT("permission_modify", [model_name, permissions])
  330. return OUTPUT()
  331. def permission_owner(model_name, permission):
  332. INPUT("permission_owner", [model_name, permission])
  333. return OUTPUT()
  334. def permission_group(model_name, group):
  335. INPUT("permission_group", [model_name, group])
  336. return OUTPUT()
  337. def group_create(group_name):
  338. INPUT("group_create", [group_name])
  339. return OUTPUT()
  340. def group_delete(group_name):
  341. INPUT("group_delete", [group_name])
  342. return OUTPUT()
  343. def group_owner_add(group_name, user_name):
  344. INPUT("group_owner_add", [group_name, user_name])
  345. return OUTPUT()
  346. def group_owner_delete(group_name, user_name):
  347. INPUT("group_owner_delete", [group_name, user_name])
  348. return OUTPUT()
  349. def group_join(group_name, user_name):
  350. INPUT("group_join", [group_name, user_name])
  351. return OUTPUT()
  352. def group_kick(group_name, user_name):
  353. INPUT("group_kick", [group_name, user_name])
  354. return OUTPUT()
  355. def group_list():
  356. INPUT("group_list", [])
  357. return OUTPUT()
  358. def admin_promote(user_name):
  359. INPUT("admin_promote", [user_name])
  360. return OUTPUT()
  361. def admin_demote(user_name):
  362. INPUT("admin_demote", [user_name])
  363. return OUTPUT()
  364. def conformance_delete(model_name, metamodel_name, type_mapping_name):
  365. INPUT("conformance_delete", [model_name, metamodel_name, type_mapping_name])
  366. return OUTPUT()
  367. def conformance_add(model_name, metamodel_name):
  368. INPUT("conformance_add", [model_name, metamodel_name])
  369. return OUTPUT()
  370. def folder_create(folder_name):
  371. INPUT("folder_create", [folder_name])
  372. return OUTPUT()
  373. def model_types(model_name):
  374. INPUT("model_types", [model_name])
  375. return OUTPUT()
  376. def alter_context(model_name, metamodel_name):
  377. INPUT("alter_context", [model_name, metamodel_name])
  378. def reset_context():
  379. INPUT("reset_context", [])
  380. def element_list(model_name):
  381. INPUT("element_list", [model_name])
  382. return OUTPUT()
  383. def element_list_nice(model_name):
  384. INPUT("element_list_nice", [model_name])
  385. return OUTPUT()
  386. def types(model_name):
  387. INPUT("types", [model_name])
  388. return OUTPUT()
  389. def read_info(model_name, ID):
  390. INPUT("read_info", [model_name, ID])
  391. return OUTPUT()
  392. def read_attrs(model_name, ID):
  393. INPUT("read_attrs", [model_name, ID])
  394. return OUTPUT()
  395. def instantiate(model_name, typename, edge=None, ID=""):
  396. INPUT("instantiate", [model_name, typename, edge, ID])
  397. return OUTPUT()
  398. def delete_element(model_name, ID):
  399. INPUT("delete_element", [model_name, ID])
  400. return OUTPUT()
  401. def attr_assign(model_name, ID, attr, value):
  402. INPUT("attr_assign", [model_name, ID, attr, value])
  403. return OUTPUT()
  404. def attr_assign_code(model_name, ID, attr, code):
  405. INPUT("attr_assign_code", [model_name, ID, attr, code])
  406. return OUTPUT()
  407. def attr_delete(model_name, ID, attr):
  408. INPUT("attr_delete", [model_name, ID, attr])
  409. return OUTPUT()
  410. def AL_text(code_location):
  411. INPUT("AL_text", [code_location])
  412. return OUTPUT()
  413. def read_outgoing(model_name, ID, typename):
  414. INPUT("read_outgoing", [model_name, ID, typename])
  415. return OUTPUT()
  416. def read_incoming(model_name, ID, typename):
  417. INPUT("read_incoming", [model_name, ID, typename])
  418. return OUTPUT()
  419. def read_association_source(model_name, ID):
  420. INPUT("read_association_source", [model_name, ID])
  421. return OUTPUT()
  422. def read_association_destination(model_name, ID):
  423. INPUT("read_association_destination", [model_name, ID])
  424. return OUTPUT()
  425. def connections_between(model_name, source, target):
  426. INPUT("connections_between", [model_name, source, target])
  427. return OUTPUT()
  428. def define_attribute(model_name, node, attr_name, attr_type):
  429. INPUT("define_attribute", [model_name, node, attr_name, attr_type])
  430. return OUTPUT()
  431. def undefine_attribute(model_name, node, attr_name):
  432. INPUT("undefine_attribute", [model_name, node, attr_name])
  433. return OUTPUT()
  434. def attribute_optional(model_name, node, attr_name, optionality):
  435. INPUT("attr_optional", [model_name, node, attr_name, optionality])
  436. return OUTPUT()
  437. def attribute_name(model_name, node, attr_name, new_name):
  438. INPUT("attr_name", [model_name, node, attr_name, new_name])
  439. return OUTPUT()
  440. def attribute_type(model_name, node, attr_name, new_type):
  441. INPUT("attr_type", [model_name, node, attr_name, new_type])
  442. return OUTPUT()
  443. def read_defined_attrs(model_name, node):
  444. INPUT("read_defined_attrs", [model_name, node])
  445. return OUTPUT()
  446. def all_instances(model_name, type_name):
  447. INPUT("all_instances", [model_name, type_name])
  448. return OUTPUT()
  449. def read_permissions(model_name):
  450. INPUT("read_permissions", [model_name])
  451. return OUTPUT()
  452. def process_execute(process_name, model_mapping, callbacks={}):
  453. # for all callbacks to SCs, start up the output port already
  454. sc_ports = {}
  455. for k, v in callbacks.items():
  456. if isinstance(v, (tuple, list)):
  457. # Is a statechart, so register already
  458. sc_ports[k] = v[0].addOutputListener(v[2])
  459. INPUT("process_execute", [process_name, model_mapping])
  460. while 1:
  461. result = OUTPUT()
  462. if result == "Success":
  463. # Finished
  464. return None
  465. else:
  466. taskname, operation = result
  467. if (operation in callbacks):
  468. data = callbacks[operation]
  469. if isinstance(data, (tuple, list)):
  470. # Statechart, so consider like that
  471. threading.Thread(target=_process_SC, args=[data, sc_ports[operation], taskname]).start()
  472. else:
  473. # Assume function
  474. threading.Thread(target=_process_OP, args=[data, taskname]).start()
  475. else:
  476. # Assume empty function
  477. threading.Thread(target=_process_OP, args=[None, taskname]).start()
  478. def get_taskname():
  479. """Fetch the taskname of the current connection."""
  480. return controller.taskname
  481. def exit_save(model_name):
  482. INPUT("exit_save", [model_name])
  483. return OUTPUT()
  484. """ Some hardcoded functions... Way easier to express them with code than with statecharts!"""
  485. import json
  486. import urllib
  487. try:
  488. import urllib2
  489. except ImportError:
  490. import urllib as urllib2
  491. def service_register(name, function):
  492. """Register a function as a service with a specific name."""
  493. INPUT("service_register", [name, function])
  494. port = OUTPUT()
  495. return port
  496. def service_stop():
  497. """Stop the currently executing process."""
  498. INPUT("service_stop", [])
  499. return OUTPUT()
  500. def service_get(port):
  501. """Get the values on the specified port."""
  502. data = urlencode({"op": "get_output", "taskname": port}).encode()
  503. val = json.loads(urlopen(Request("http://%s" % controller.address, data), timeout=99999).read())
  504. return val
  505. def service_set(port, value):
  506. """Set a value on a specified port."""
  507. if isinstance(value, type([])):
  508. value = json.dumps(value)
  509. data = urlencode({"op": "set_input", "data": value, "taskname": port}).encode()
  510. urlopen(Request("http://%s" % controller.address, data), timeout=99999).read()
  511. else:
  512. value = json.dumps(value)
  513. data = urlencode({"op": "set_input", "value": value, "taskname": port}).encode()
  514. urlopen(Request("http://%s" % controller.address, data), timeout=99999).read()
  515. def service_poll(port):
  516. """Checks whether or not the Modelverse side has any input ready to be processed."""
  517. raise NotImplementedError()
  518. def show(model_name):
  519. data_list = INPUT("element_list_nice", [model_name])
  520. result = OUTPUT()
  521. import uuid
  522. INPUT("model_types", [model_name])
  523. is_scd = len([i for i in OUTPUT() if i[0] == "formalisms/SimpleClassDiagrams"]) > 0
  524. edges = []
  525. texts = []
  526. rectangles = []
  527. defined_attributes = {}
  528. names = {}
  529. group_counter = 0
  530. todo_edges = []
  531. locations = {}
  532. if is_scd:
  533. for elem in result:
  534. if elem["__type"] == "AttributeLink":
  535. defined_attributes.setdefault(elem["__source"], []).append((elem["name"], elem["__target"], True if elem["optional"] == True else False))
  536. if "name" in elem:
  537. names[elem["__id"]] = elem["name"]
  538. for elem in list(result):
  539. is_edge = False
  540. attrs = {}
  541. for key, value in elem.items():
  542. if key == "__id":
  543. element_id = value
  544. elif key == "__source":
  545. element_source = value
  546. is_edge = True
  547. elif key == "__target":
  548. element_target = value
  549. is_edge = True
  550. elif key == "__type":
  551. element_type = value
  552. else:
  553. attrs[key] = value
  554. max_text = 0
  555. if is_edge:
  556. edge_edge = len([x for x in result if (x["__id"] == element_source or x["__id"] == element_target) and "__source" in x]) > 0
  557. else:
  558. edge_edge = False
  559. if is_edge:
  560. if not (elem["__type"] == "AttributeLink" and is_scd):
  561. todo_edges.append({"source": element_source, "target": element_target, "source_x": 0 if edge_edge else 100, "source_y": 0 if edge_edge else 30, "target_x": 100, "target_y": 30})
  562. else:
  563. # Add the group
  564. x, y = 30 + (group_counter * 250) % 1000, 30 + ((group_counter / 4) * 250)
  565. locations[element_id] = (x, y)
  566. group_counter += 1
  567. # Add the text elements
  568. # First the header
  569. texts.append({"text": "%s : %s" % (element_id, element_type), "x": x + 10, "y": y + 10})
  570. max_text = max(len(texts[-1]["text"]), max_text)
  571. # Then the attributes
  572. text_counter = 1
  573. for name, attr_type, optional in defined_attributes.get(elem["__id"], []):
  574. text = "%s : %s" % (name, names.get(attr_type, "(%s)" % attr_type))
  575. if optional:
  576. text = text.replace(" : ", " ?: ")
  577. texts.append({"text": text, "x": x + 10, "y": y + 25 + text_counter * 11})
  578. max_text = max(len(text), max_text)
  579. text_counter += 1
  580. if text_counter > 1:
  581. text_counter += 1
  582. for key, value in attrs.items():
  583. if isinstance(value, dict):
  584. if value["AL"] == "":
  585. text = "(%s)" % key
  586. else:
  587. text = "%s = ^%s" % (key, value['AL'])
  588. else:
  589. text = ("%s = %s" % (key, value)) if value is not None else ("(%s)" % key)
  590. texts.append({"text": text, "x": x + 10, "y": y + 25 + text_counter * 11})
  591. max_text = max(len(text), max_text)
  592. text_counter += 1
  593. # Add the rectangle
  594. rectangles.append({"x": x, "y": y, "width": max_text * 8, "height": 35 + text_counter * 11})
  595. # Add the line
  596. edges.append({"sx": x, "sy": y + 20, "tx": x + max_text * 8, "ty": y + 20})
  597. for edge in todo_edges:
  598. edges.append({"sx": locations[edge["source"]][0] + edge["source_x"], "sy": locations[edge["source"]][1] + edge["source_y"], "tx": locations[edge["target"]][0] + edge["target_x"], "ty": locations[edge["target"]][1]})
  599. print("Got rectangles: " + str(rectangles))
  600. print("Got edges: " + str(edges))
  601. print("Got text: " + str(texts))
  602. data_content = '<svg width="1000" height="800">'
  603. for rec in rectangles:
  604. data_content += '<rect x="%s" y="%s" width="%s" height="%s" fill="white" stroke="black"/>' % (rec["x"], rec["y"], rec["width"], rec["height"])
  605. for edge in edges:
  606. data_content += '<line x1="%s" y1="%s" x2="%s" y2="%s" fill="black"/>' % (edge["sx"], edge["sy"], edge["tx"], edge["ty"])
  607. for text in texts:
  608. data_content += '<text x="%s" y="%s" fill="black">%s</text>' % (text["x"], text["y"], text["text"])
  609. data_content += '</svg>'
  610. return data_content