main.py 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853
  1. import sys, json, threading
  2. import Tkinter as tk
  3. from modelverse import *
  4. places = []
  5. transitions = []
  6. p2ts = []
  7. t2ps = []
  8. cond = threading.Condition()
  9. small_step_cond = threading.Condition()
  10. small_step_input = None
  11. node_ids = set([])
  12. transition_ids = set([])
  13. class AttributeEditor(tk.Toplevel):
  14. def __init__(self, title, entries, callback):
  15. tk.Toplevel.__init__(self)
  16. self.geometry("800x600")
  17. self.title(title)
  18. self.entries = entries
  19. self.window = VerticallyScrolledWindow(self)
  20. self.entries_vis = {}
  21. for i, k in enumerate(self.entries.keys()):
  22. tk.Label(self.window.frame, text=k).grid(row=i)
  23. if (self.entries[k]["type"] == "string"):
  24. content = tk.StringVar()
  25. content.set(self.entries[k]["value"])
  26. self.entries[k]["entry"] = tk.Entry(self.window.frame, width=40, textvariable=content)
  27. self.entries[k]["entry"].grid(row=i, column=1, sticky= 'w', pady=10)
  28. elif (self.entries[k]["type"] == "text"):
  29. frame = tk.Frame(self.window.frame)
  30. frame.grid(row=i, column=1, sticky='w', pady=10)
  31. scroll = tk.Scrollbar(frame, orient=tk.VERTICAL)
  32. content = tk.Text(frame, height=25, width=80)
  33. content.insert(tk.END, self.entries[k]["value"])
  34. scroll.pack(side=tk.RIGHT, fill=tk.Y, expand=tk.FALSE)
  35. content.pack(side=tk.LEFT, fill=tk.Y)
  36. scroll.config(command=content.yview)
  37. # content.config(yscrollcommand=scroll.set)
  38. self.entries[k]["entry"] = content
  39. self.window.pack(side="top", fill="both", expand=True)
  40. self.submit_button = tk.Button(self.window.frame, text="OK", command=lambda: callback({k: (self.entries[k]["entry"].get("1.0", tk.END) if isinstance(self.entries[k]["entry"], tk.Text) else self.entries[k]["entry"].get()) for k in self.entries.keys()}, self))
  41. self.submit_button.grid(row=i+1, column=1)
  42. self.grab_set()
  43. self.focus_force()
  44. class PlaceVis:
  45. R = 20
  46. def __init__(self, canvas, x, y, name="", tokens=0):
  47. self.canvas = canvas
  48. self.vis = canvas.create_oval(x - PlaceVis.R, y - PlaceVis.R, x + PlaceVis.R, y + PlaceVis.R, fill="white")
  49. self.name = name
  50. self.name_text = canvas.create_text(x, y + PlaceVis.R + 10, text=name, font=('Helvetica', '12'))
  51. self.tokens = tokens
  52. self.tokens_text = canvas.create_text(x, y, text=tokens, font=('Helvetica', '12'))
  53. canvas.tag_bind(self.vis, "<Button-1>", self.clicked)
  54. canvas.tag_bind(self.name_text, "<Button-1>", self.clicked)
  55. canvas.tag_bind(self.tokens_text, "<Button-1>", self.clicked)
  56. canvas.tag_bind(self.vis, "<Double-Button-1>", self.edit)
  57. canvas.tag_bind(self.name_text, "<Double-Button-1>", self.edit)
  58. canvas.tag_bind(self.tokens_text, "<Double-Button-1>", self.edit)
  59. canvas.tag_bind(self.vis, "<B1-Motion>", self.move)
  60. canvas.tag_bind(self.name_text, "<B1-Motion>", self.move)
  61. canvas.tag_bind(self.tokens_text, "<B1-Motion>", self.move)
  62. canvas.tag_bind(self.vis, "<Double-Button-3>", self.delete)
  63. canvas.tag_bind(self.name_text, "<Double-Button-3>", self.delete)
  64. canvas.tag_bind(self.tokens_text, "<Double-Button-3>", self.delete)
  65. self.x = x
  66. self.y = y
  67. self.t2ps = []
  68. self.p2ts = []
  69. self.last_click_x = None
  70. self.last_click_y = None
  71. def get_name(self):
  72. return self.name
  73. def clicked(self, event):
  74. event.widget.clicked = True
  75. self.last_click_x = event.x
  76. self.last_click_y = event.y
  77. def delete(self, event):
  78. self.canvas.delete(self.vis)
  79. self.canvas.delete(self.name_text)
  80. self.canvas.delete(self.tokens_text)
  81. for t2p in self.t2ps:
  82. t2p.delete()
  83. for p2t in self.p2ts:
  84. p2t.delete()
  85. global places
  86. places = [el for el in places if el.name != self.name]
  87. def move(self, event):
  88. delta_x = event.x - self.last_click_x
  89. delta_y = event.y - self.last_click_y
  90. self.canvas.move(self.vis, delta_x, delta_y)
  91. self.canvas.move(self.name_text, delta_x, delta_y)
  92. self.canvas.move(self.tokens_text, delta_x, delta_y)
  93. self.x += delta_x
  94. self.y += delta_y
  95. self.last_click_x = event.x
  96. self.last_click_y = event.y
  97. for t2p in self.t2ps:
  98. t2p.moved()
  99. for p2t in self.p2ts:
  100. p2t.moved()
  101. def edit(self, event):
  102. event.widget.clicked = True
  103. editor = AttributeEditor('Attributes of Place', {"name": {"type": "string", "value": self.canvas.itemcget(self.name_text, "text")}, "tokens": {"type": "string", "value": self.canvas.itemcget(self.tokens_text, "text")}}, self.edit_done)
  104. def edit_done(self, attr_vals, window):
  105. self.set_name(attr_vals["name"])
  106. self.set_tokens(int(attr_vals["tokens"]))
  107. window.destroy()
  108. def set_name(self, name):
  109. self.canvas.itemconfig(self.name_text, text=str(name))
  110. self.name = name
  111. def set_tokens(self, tokens):
  112. self.canvas.itemconfig(self.tokens_text, text=str(tokens))
  113. self.tokens = tokens
  114. class TransitionVis:
  115. H = 30
  116. W = 10
  117. def __init__(self, canvas, x, y, name=""):
  118. self.canvas = canvas
  119. self.vis = canvas.create_rectangle(x - TransitionVis.W/2, y - TransitionVis.H/2, x + TransitionVis.W/2, y + TransitionVis.H/2, fill="black")
  120. self.name = name
  121. self.name_text = canvas.create_text(x, y + TransitionVis.H/2 + 10, text=name, font=('Helvetica', '12'))
  122. canvas.tag_bind(self.vis, "<Button-1>", self.clicked)
  123. canvas.tag_bind(self.name_text, "<Button-1>", self.clicked)
  124. canvas.tag_bind(self.vis, "<Double-Button-1>", self.edit)
  125. canvas.tag_bind(self.name_text, "<Double-Button-1>", self.edit)
  126. canvas.tag_bind(self.vis, "<B1-Motion>", self.move)
  127. canvas.tag_bind(self.name_text, "<B1-Motion>", self.move)
  128. canvas.tag_bind(self.vis, "<Button-3>", self.select)
  129. canvas.tag_bind(self.name_text, "<Button-3>", self.select)
  130. canvas.tag_bind(self.vis, "<Double-Button-3>", self.delete)
  131. canvas.tag_bind(self.name_text, "<Double-Button-3>", self.delete)
  132. self.x = x
  133. self.y = y
  134. self.t2ps = []
  135. self.p2ts = []
  136. self.last_click_x = None
  137. self.last_click_y = None
  138. def get_name(self):
  139. return self.name
  140. def clicked(self, event):
  141. event.widget.clicked = True
  142. self.last_click_x = event.x
  143. self.last_click_y = event.y
  144. def set_enabled(self, enabled=False):
  145. if enabled:
  146. self.canvas.itemconfig(self.vis, fill="green")
  147. else:
  148. self.canvas.itemconfig(self.vis, fill="black")
  149. def select(self, event):
  150. global small_step_input
  151. small_step_input = {'type': 'selected_transition', 'value': self.name}
  152. with small_step_cond:
  153. small_step_cond.notify()
  154. def delete(self, event):
  155. self.canvas.delete(self.vis)
  156. self.canvas.delete(self.name_text)
  157. for t2p in self.t2ps:
  158. t2p.delete()
  159. for p2t in self.p2ts:
  160. p2t.delete()
  161. global transitions
  162. transitions = [el for el in transitions if el.name != self.name]
  163. def move(self, event):
  164. delta_x = event.x - self.last_click_x
  165. delta_y = event.y - self.last_click_y
  166. self.canvas.move(self.vis, delta_x, delta_y)
  167. self.canvas.move(self.name_text, delta_x, delta_y)
  168. self.x += delta_x
  169. self.y += delta_y
  170. self.last_click_x = event.x
  171. self.last_click_y = event.y
  172. for t2p in self.t2ps:
  173. t2p.moved()
  174. for p2t in self.p2ts:
  175. p2t.moved()
  176. def edit(self, event):
  177. event.widget.clicked = True
  178. editor = AttributeEditor('Attributes of Transitions', {"name": {"type": "string", "value": self.canvas.itemcget(self.name_text, "text")}}, self.edit_done)
  179. def edit_done(self, attr_vals, window):
  180. self.set_name(attr_vals["name"])
  181. window.destroy()
  182. def set_name(self, name):
  183. self.canvas.itemconfig(self.name_text, text=name)
  184. self.name = name
  185. class TransitionToPlaceVis:
  186. def __init__(self, canvas, transition, place, weight=1):
  187. self.canvas = canvas
  188. self.transition = transition
  189. self.place = place
  190. self.weight = 1
  191. self.line = self.canvas.create_line(transition.x, transition.y, place.x, place.y, fill="black", arrow=tk.LAST, arrowshape=(12, 14, 6))
  192. x_coords = sorted([self.transition.x, self.place.x])
  193. y_coords = sorted([self.transition.y, self.place.y])
  194. self.text = self.canvas.create_text(5 + x_coords[0] + (x_coords[1] - x_coords[0]) / 2, y_coords[0] + (y_coords[1] - y_coords[0]) / 2, text=self.weight, font=('Helvetica', '12'))
  195. canvas.tag_bind(self.line, "<Double-Button-3>", self.delete)
  196. canvas.tag_bind(self.text, "<Double-Button-3>", self.delete)
  197. self.transition.t2ps.append(self)
  198. self.place.t2ps.append(self)
  199. def moved(self):
  200. self.canvas.coords(self.line, self.transition.x, self.transition.y, self.place.x, self.place.y)
  201. x_coords = sorted([self.transition.x, self.place.x])
  202. y_coords = sorted([self.transition.y, self.place.y])
  203. self.canvas.coords(self.text, 5 + x_coords[0] + (x_coords[1] - x_coords[0]) / 2, y_coords[0] + (y_coords[1] - y_coords[0]) / 2)
  204. def delete(self, event=None):
  205. self.canvas.delete(self.line)
  206. self.canvas.delete(self.text)
  207. global t2ps
  208. t2ps = [el for el in t2ps if el.transition != self.transition and el.place != self.place]
  209. class PlaceToTransitionVis:
  210. def __init__(self, canvas, place, transition, weight=1):
  211. self.canvas = canvas
  212. self.place = place
  213. self.transition = transition
  214. self.weight = 1
  215. self.line = self.canvas.create_line(place.x, place.y, transition.x, transition.y, fill="black", arrow=tk.LAST, arrowshape=(12, 14, 6))
  216. x_coords = sorted([self.transition.x, self.place.x])
  217. y_coords = sorted([self.transition.y, self.place.y])
  218. self.text = self.canvas.create_text(5 + x_coords[0] + (x_coords[1] - x_coords[0]) / 2, y_coords[0] + (y_coords[1] - y_coords[0]) / 2, text=self.weight, font=('Helvetica', '12'))
  219. canvas.tag_bind(self.line, "<Double-Button-3>", self.delete)
  220. canvas.tag_bind(self.text, "<Double-Button-3>", self.delete)
  221. self.place.p2ts.append(self)
  222. self.transition.p2ts.append(self)
  223. def moved(self):
  224. self.canvas.coords(self.line, self.place.x, self.place.y, self.transition.x, self.transition.y)
  225. x_coords = sorted([self.transition.x, self.place.x])
  226. y_coords = sorted([self.transition.y, self.place.y])
  227. self.canvas.coords(self.text, 5 + x_coords[0] + (x_coords[1] - x_coords[0]) / 2, y_coords[0] + (y_coords[1] - y_coords[0]) / 2)
  228. def delete(self, event=None):
  229. self.canvas.delete(self.line)
  230. self.canvas.delete(self.text)
  231. global p2ts
  232. p2ts = [el for el in p2ts if el.place != self.place and el.transition != self.transition]
  233. class MarkingVis:
  234. def __init__(self, canvas, x, y, node_id, content={}):
  235. global node_ids
  236. node_ids.add(node_id)
  237. self.node_id = node_id
  238. self.canvas = canvas
  239. self.marking_val = content
  240. self.vis = canvas.create_text(x, y, text=str(content).replace(',', ',\n'), font=('Helvetica', '14'))
  241. self.bbox = canvas.bbox(self.vis)
  242. canvas.move(self.vis, (self.bbox[2]-self.bbox[0])/2, (self.bbox[3]-self.bbox[1])/2)
  243. self.bbox = canvas.bbox(self.vis)
  244. self.rect = canvas.create_rectangle(*self.bbox, fill="")
  245. canvas.tag_bind(self.vis, "<Button-1>", self.clicked)
  246. canvas.tag_bind(self.rect, "<Button-1>", self.clicked)
  247. canvas.tag_bind(self.vis, "<B1-Motion>", self.move)
  248. canvas.tag_bind(self.rect, "<B1-Motion>", self.move)
  249. canvas.tag_bind(self.vis, "<Button-3>", self.rightclicked)
  250. canvas.tag_bind(self.rect, "<Button-3>", self.rightclicked)
  251. canvas.tag_lower(self.rect)
  252. self.x = x
  253. self.y = y
  254. self.m2ms = []
  255. self.last_click_x = None
  256. self.last_click_y = None
  257. def get_width(self):
  258. return self.bbox[2]-self.bbox[0]
  259. def get_height(self):
  260. return self.bbox[3]-self.bbox[1]
  261. def set_current(self, current=False):
  262. if current:
  263. self.canvas.itemconfig(self.rect, fill="yellow")
  264. else:
  265. self.canvas.itemconfig(self.rect, fill="")
  266. def rightclicked(self, event):
  267. global small_step_input
  268. small_step_input = {'type': 'selected_marking', 'value': self.node_id}
  269. with small_step_cond:
  270. small_step_cond.notify()
  271. def clicked(self, event):
  272. event.widget.clicked = True
  273. self.last_click_x = event.x
  274. self.last_click_y = event.y
  275. def move(self, event):
  276. delta_x = event.x - self.last_click_x
  277. delta_y = event.y - self.last_click_y
  278. self.canvas.move(self.vis, delta_x, delta_y)
  279. self.canvas.move(self.rect, delta_x, delta_y)
  280. self.x += delta_x
  281. self.y += delta_y
  282. self.last_click_x = event.x
  283. self.last_click_y = event.y
  284. for m2m in self.m2ms:
  285. m2m.moved()
  286. class MarkingToMarkingVis:
  287. def __init__(self, canvas, transition_id, m1, m2, transition):
  288. global transition_ids
  289. transition_ids.add(transition_id)
  290. self.canvas = canvas
  291. self.m1 = m1
  292. self.m2 = m2
  293. self.transition = transition
  294. self.line = self.canvas.create_line(self.m1.x, self.m1.y+self.m1.get_height(), self.m2.x, self.m2.y, fill="black", arrow=tk.LAST, arrowshape=(12, 14, 6))
  295. x_coords = sorted([self.m1.x, self.m2.x])
  296. y_coords = sorted([self.m1.y+self.m1.get_height(), self.m2.y])
  297. self.text = self.canvas.create_text(x_coords[0] + (x_coords[1] - x_coords[0]) / 2, y_coords[0] + (y_coords[1] - y_coords[0]) / 2, text=self.transition.name, font=('Helvetica', '12'))
  298. self.m1.m2ms.append(self)
  299. self.m2.m2ms.append(self)
  300. def moved(self):
  301. self.canvas.coords(self.line, self.m1.x, self.m1.y+self.m1.get_height(), self.m2.x, self.m2.y)
  302. x_coords = sorted([self.m1.x, self.m2.x])
  303. y_coords = sorted([self.m1.y+self.m1.get_height(), self.m2.y])
  304. self.canvas.coords(self.text, x_coords[0] + (x_coords[1] - x_coords[0]) / 2, y_coords[0] + (y_coords[1] - y_coords[0]) / 2)
  305. class PNInterface(tk.Tk):
  306. MAX_WIDTH = 8192
  307. MAX_HEIGHT = 8192
  308. def __init__(self, *args, **kwargs):
  309. tk.Tk.__init__(self, *args, **kwargs)
  310. print("Init")
  311. init()
  312. print("Login")
  313. #login(str(random.random()), str(random.random()))
  314. login("admin", "admin")
  315. # Add the metamodels for PetriNet and ReachabilityGraph
  316. print("Add metamodels")
  317. try:
  318. model_add("formalisms/PetriNet", "formalisms/SimpleClassDiagrams", open("../../models/petrinets.mvc").read())
  319. except ModelExists:
  320. pass
  321. try:
  322. model_add("formalisms/ReachabilityGraph", "formalisms/SimpleClassDiagrams", open("../../models/reachability_graph.mvc").read())
  323. except ModelExists:
  324. pass
  325. # Remove the action language code to transform between them
  326. print("Remove AL model")
  327. try:
  328. model_delete("models/analyseReachability")
  329. except ModelverseException:
  330. pass
  331. # Add the action language code to transform between them
  332. print("Add AL model")
  333. try:
  334. transformation_add_AL({"PetriNet": "formalisms/PetriNet"}, {"ReachabilityGraph": "formalisms/ReachabilityGraph"}, "models/analyseReachability", open("../../models/reachability.alc", "r").read())
  335. except ModelExists:
  336. pass
  337. # Add an example model transformation to print the reachability graph
  338. print("Add MT model")
  339. try:
  340. transformation_add_MT({"ReachabilityGraph": "formalisms/ReachabilityGraph"}, {}, "models/printReachability", open("../../models/reachabilitygraph_print.mvc").read())
  341. except ModelExists:
  342. pass
  343. self.markings = []
  344. self.m2ms = []
  345. self.mode = "PLACE"
  346. self.sim_mode = None
  347. # global attributes
  348. self.title('Petrinets Debugging Interface')
  349. self.minsize(self.winfo_screenwidth() / 2, self.winfo_screenheight() / 2)
  350. # modelling toolbar
  351. self.modelling_toolbar_frame = tk.Frame(self)
  352. self.modelling_toolbar_frame.grid(row=0, column=0, columnspan=2, sticky=tk.W)
  353. self.INTER_SPACING = 5
  354. self.buttons = ["PLACE", "TRANSITION", "P2T", "T2P"]
  355. self.button_config = {"PLACE": self.place,
  356. "TRANSITION": self.transition,
  357. "P2T": self.place_to_transition,
  358. "T2P": self.transition_to_place}
  359. self.button_img = {}
  360. self.buttons_vis = {}
  361. i = 0
  362. for k in self.buttons:
  363. v = self.button_config[k]
  364. if k in self.button_img:
  365. btn = tk.Button(self.modelling_toolbar_frame, image=self.button_img[k], command=v)
  366. else:
  367. btn = tk.Button(self.modelling_toolbar_frame, text=k, command=v)
  368. btn.grid(row=0, column=i, padx=self.INTER_SPACING, sticky=tk.W)
  369. self.buttons_vis[k] = btn
  370. i += 1
  371. # debugging toolbar
  372. self.debugging_toolbar_frame = tk.Frame(self)
  373. self.debugging_toolbar_frame.grid(row=0, column=2, columnspan=2, sticky=tk.W)
  374. self.INTER_SPACING = 5
  375. self.buttons = ["load", "continuous", "step", "manual", "add_breakpoint"]
  376. self.button_config = {"load": self.load,
  377. "continuous": self.continuous,
  378. "step": self.step,
  379. "manual": self.manual,
  380. "add_breakpoint": self.add_breakpoint}
  381. self.button_img = {"load": tk.PhotoImage(file="load.icon.gif"),
  382. "continuous": tk.PhotoImage(file="simulate.icon.gif"),
  383. "step": tk.PhotoImage(file="step.icon.gif"),
  384. "manual": tk.PhotoImage(file="godevent.icon.gif"),
  385. "add_breakpoint": tk.PhotoImage(file="addbp.icon.gif")}
  386. self.button_img_disabled = {"load": tk.PhotoImage(file="load.disabled.icon.gif"),
  387. "continuous": tk.PhotoImage(file="simulate.disabled.icon.gif"),
  388. "step": tk.PhotoImage(file="step.disabled.icon.gif"),
  389. "manual": tk.PhotoImage(file="godevent.disabled.icon.gif"),
  390. "add_breakpoint": tk.PhotoImage(file="addbp.disabled.icon.gif")}
  391. self.buttons_vis = {}
  392. i = 0
  393. for k in self.buttons:
  394. v = self.button_config[k]
  395. if k in self.button_img:
  396. btn = tk.Button(self.debugging_toolbar_frame, image=self.button_img[k], command=v)
  397. else:
  398. btn = tk.Button(self.debugging_toolbar_frame, text=k, command=v)
  399. btn.grid(row=0, column=i, padx=self.INTER_SPACING, sticky=tk.W)
  400. self.buttons_vis[k] = btn
  401. if k != "load":
  402. btn.config(state=tk.DISABLED)
  403. btn.config(image=self.button_img_disabled[k])
  404. i += 1
  405. # Petrinets canvas
  406. CANVAS_SIZE_TUPLE = (0, 0, PNInterface.MAX_WIDTH, PNInterface.MAX_HEIGHT)
  407. self.pn_canvas = tk.Canvas(self, relief=tk.RIDGE, scrollregion=CANVAS_SIZE_TUPLE, bg="white")
  408. self.pn_vbar = tk.Scrollbar(self, orient=tk.VERTICAL)
  409. self.pn_vbar.config(command=self.pn_canvas.yview)
  410. self.pn_hbar = tk.Scrollbar(self, orient=tk.HORIZONTAL)
  411. self.pn_hbar.config(command=self.pn_canvas.xview)
  412. # self.pn_canvas.config(background='white', yscrollcommand=self.pn_vbar.set, xscrollcommand=self.pn_hbar.set)
  413. self.pn_canvas.config(background='white')
  414. self.pn_canvas.bind("<Button-1>", self.clicked)
  415. self.pn_canvas.bind("<Button-3>", self.draw)
  416. self.pn_canvas.bind("<ButtonRelease-3>", self.release)
  417. self.rg_canvas = tk.Canvas(self, relief=tk.RIDGE, scrollregion=CANVAS_SIZE_TUPLE, bg="white")
  418. self.rg_vbar = tk.Scrollbar(self, orient=tk.VERTICAL)
  419. self.rg_vbar.config(command=self.rg_canvas.yview)
  420. self.rg_hbar = tk.Scrollbar(self, orient=tk.HORIZONTAL)
  421. self.rg_hbar.config(command=self.rg_canvas.xview)
  422. # self.rg_canvas.config(background='white', yscrollcommand=self.rg_vbar.set, xscrollcommand=self.rg_hbar.set)
  423. self.rg_canvas.config(background='white')
  424. self.pn_canvas.grid(row=1, column=0, sticky=tk.W+tk.E+tk.N+tk.S)
  425. self.pn_vbar.grid(row=1, column=1, sticky=tk.N+tk.S, pady=(0, 16))
  426. self.pn_hbar.grid(row=2, column=0, columnspan=2, sticky=tk.W+tk.E)
  427. self.rg_canvas.grid(row=1, column=2, sticky=tk.W+tk.E+tk.N+tk.S)
  428. self.rg_vbar.grid(row=1, column=3, sticky=tk.N+tk.S, pady=(0, 16))
  429. self.rg_hbar.grid(row=2, column=2, columnspan=2, sticky=tk.W+tk.E)
  430. self.grid_columnconfigure(0, weight=1)
  431. self.grid_columnconfigure(2, weight=1)
  432. self.grid_rowconfigure(1, weight=1)
  433. self.setup()
  434. def enable_buttons(self, commands):
  435. for (k, btn) in self.buttons_vis.items():
  436. if k in commands:
  437. btn.config(state=tk.NORMAL)
  438. btn.config(image=self.button_img[k])
  439. else:
  440. btn.config(state=tk.DISABLED)
  441. btn.config(image=self.button_img_disabled[k])
  442. def setup(self):
  443. free = PlaceVis(self.pn_canvas, 100, 200, "free", 3)
  444. max_items = PlaceVis(self.pn_canvas, 150, 400, "maximum items", 3)
  445. producing = PlaceVis(self.pn_canvas, 200, 200, "producing", 0)
  446. produced = PlaceVis(self.pn_canvas, 300, 200, "produced", 0)
  447. waiting = PlaceVis(self.pn_canvas, 400, 200, "waiting", 2)
  448. consuming = PlaceVis(self.pn_canvas, 500, 200, "consuming", 0)
  449. global places
  450. places = [free, producing, produced, waiting, consuming, max_items]
  451. start_produce = TransitionVis(self.pn_canvas, 150, 100, "start producing")
  452. end_produce = TransitionVis(self.pn_canvas, 150, 300, "end producing")
  453. start_consume = TransitionVis(self.pn_canvas, 450, 100, "start consuming")
  454. end_consume = TransitionVis(self.pn_canvas, 450, 300, "end consuming")
  455. global transitions
  456. transitions = [start_produce, end_produce, start_consume, end_consume]
  457. f_to_s_p = PlaceToTransitionVis(self.pn_canvas, free, start_produce)
  458. s_p_to_p = TransitionToPlaceVis(self.pn_canvas, start_produce, producing)
  459. p_to_e_p = PlaceToTransitionVis(self.pn_canvas, producing, end_produce)
  460. m_i_to_e_p = PlaceToTransitionVis(self.pn_canvas, max_items, end_produce)
  461. e_p_to_f = TransitionToPlaceVis(self.pn_canvas, end_produce, free)
  462. w_to_s_c = PlaceToTransitionVis(self.pn_canvas, waiting, start_consume)
  463. s_c_to_c = TransitionToPlaceVis(self.pn_canvas, start_consume, consuming)
  464. c_to_e_c = PlaceToTransitionVis(self.pn_canvas, consuming, end_consume)
  465. e_c_to_w = TransitionToPlaceVis(self.pn_canvas, end_consume, waiting)
  466. e_p_to_p = TransitionToPlaceVis(self.pn_canvas, end_produce, produced)
  467. p_to_s_c = PlaceToTransitionVis(self.pn_canvas, produced, start_consume)
  468. global p2ts
  469. p2ts = [f_to_s_p, p_to_e_p, w_to_s_c, c_to_e_c, p_to_s_c, m_i_to_e_p]
  470. global t2ps
  471. t2ps = [s_p_to_p, e_p_to_f, s_c_to_c, e_c_to_w, e_p_to_p]
  472. def place(self):
  473. self.mode = "PLACE"
  474. def transition(self):
  475. self.mode = "TRANSITION"
  476. def place_to_transition(self):
  477. def create_p2t(attr_vals, window):
  478. src = [p for p in places if p.get_name() == attr_vals["src"]]
  479. dst = [t for t in transitions if t.get_name() == attr_vals["dst"]]
  480. if len(src) == 1 and len(dst) == 1:
  481. global p2ts
  482. p2ts.append(PlaceToTransitionVis(self.pn_canvas, src[0], dst[0], attr_vals["weight"]))
  483. else:
  484. print 'could not find source and/or target nodes'
  485. window.destroy()
  486. editor = AttributeEditor('Create P2T', {"weight": {"type": "string", "value": 1}, "src": {"type": "string", "value": ""}, "dst": {"type": "string", "value": ""}}, create_p2t)
  487. def transition_to_place(self):
  488. def create_t2p(attr_vals, window):
  489. src = [t for t in transitions if t.get_name() == attr_vals["src"]]
  490. dst = [p for p in places if p.get_name() == attr_vals["dst"]]
  491. if len(src) == 1 and len(dst) == 1:
  492. global t2ps
  493. t2ps.append(TransitionToPlaceVis(self.pn_canvas, src[0], dst[0], attr_vals["weight"]))
  494. else:
  495. print 'could not find source and/or target nodes'
  496. window.destroy()
  497. editor = AttributeEditor('Create T2P', {"weight": {"type": "string", "value": 1}, "src": {"type": "string", "value": ""}, "dst": {"type": "string", "value": ""}}, create_t2p)
  498. def load(self):
  499. self.enable_buttons([])
  500. with open("model.mvc", "w+") as model_file:
  501. for p in places:
  502. model_file.write("Place %s {\n" % p.name.replace(" ", "_"))
  503. model_file.write("\ttokens = %i\n" % p.tokens)
  504. model_file.write("\tname = \"%s\"\n" % p.name)
  505. model_file.write("}\n")
  506. for t in transitions:
  507. model_file.write("Transition %s {\n" % t.name.replace(" ", "_"))
  508. model_file.write("\tname = \"%s\"\n" % t.name)
  509. model_file.write("}\n")
  510. for t2p in t2ps:
  511. model_file.write("T2P (%s, %s) {\n" % (t2p.transition.name.replace(" ", "_"), t2p.place.name.replace(" ", "_")))
  512. model_file.write("\tweight = %i\n" % t2p.weight)
  513. model_file.write("}\n")
  514. for p2t in p2ts:
  515. model_file.write("P2T (%s, %s) {\n" % (p2t.place.name.replace(" ", "_"), p2t.transition.name.replace(" ", "_")))
  516. model_file.write("\tweight = %i\n" % p2t.weight)
  517. model_file.write("}\n")
  518. print("Delete model")
  519. try:
  520. model_delete("models/my_pn")
  521. except ModelverseException:
  522. pass
  523. print("Add model")
  524. try:
  525. model_add("models/my_pn", "formalisms/PetriNet", open("model.mvc").read())
  526. except ModelExists:
  527. pass
  528. def executeAL():
  529. print("Execute AL")
  530. status = transformation_execute_AL("models/analyseReachability", {"PetriNet": "models/my_pn"}, {"ReachabilityGraph": "models/my_reachability"}, callback=self.callback)
  531. print("Reachability generation success: " + str(status))
  532. print("Execute MT")
  533. def print_mv(value):
  534. print(value)
  535. status = transformation_execute_MT("models/printReachability", {"ReachabilityGraph": "models/my_reachability"}, {}, callback=print_mv)
  536. print("Reachability printing success: " + str(status))
  537. # Start the reachability graph generation
  538. thrd = threading.Thread(target=executeAL)
  539. thrd.daemon = True
  540. thrd.start()
  541. def callback(self, value):
  542. global small_step_input
  543. if value.startswith("{"):
  544. print(value)
  545. parsed_value = json.loads(value)
  546. if parsed_value["msg_type"] == 'node_added':
  547. self.markings.append(MarkingVis(self.rg_canvas, 100, 50, parsed_value['node_info']['node_id'], parsed_value['node_info']['node_marking']))
  548. elif parsed_value["msg_type"] == 'link_added':
  549. m1 = [m for m in self.markings if m.node_id == parsed_value['link_info']['source']][0]
  550. m2 = [m for m in self.markings if m.node_id == parsed_value['link_info']['target']][0]
  551. t = [t for t in transitions if t.name == parsed_value['link_info']['transition']][0]
  552. self.m2ms.append(MarkingToMarkingVis(self.rg_canvas, parsed_value['link_info']['transition_id'], m1, m2, t))
  553. elif parsed_value["msg_type"] == "reachable_nodes":
  554. for n in parsed_value["nodes"]:
  555. if not (n['node_id'] in node_ids):
  556. node_id = n['node_id']
  557. if len([m for m in self.markings if m.node_id == node_id]) == 0:
  558. self.markings.append(MarkingVis(self.rg_canvas, 100, 50, node_id, n['node_marking']))
  559. elif parsed_value["msg_type"] == "node_links":
  560. for n in parsed_value["links"]:
  561. if not (n['transition_id'] in transition_ids):
  562. m1 = [m for m in self.markings if m.node_id == n['source']][0]
  563. m2 = [m for m in self.markings if m.node_id == n['target']][0]
  564. t = [t for t in transitions if t.name == n['transition']][0]
  565. self.m2ms.append(MarkingToMarkingVis(self.rg_canvas, n['transition_id'], m1, m2, t))
  566. elif parsed_value["msg_type"] == "input_required":
  567. if (not self.breakpoint_info_entered):
  568. print 'waiting'
  569. with cond:
  570. cond.wait()
  571. print 'waiting done'
  572. if parsed_value["name"] == "breakpoint name":
  573. return self.breakpoint_name
  574. elif parsed_value["name"] == "disable on trigger?":
  575. return self.breakpoint_disable_on_trigger
  576. elif parsed_value["name"] == "breakpoint function":
  577. upload_code(self.breakpoint_code)
  578. elif parsed_value["msg_type"] == "enabled_commands":
  579. self.enable_buttons(set(parsed_value["commands"]))
  580. if (len(parsed_value["commands"]) == 0):
  581. return
  582. return
  583. elif parsed_value["msg_type"] == "unexplored_markings":
  584. unexplored_markings = set(parsed_value["markings"])
  585. for m in self.markings:
  586. if m.node_id in unexplored_markings:
  587. m.set_current(True)
  588. small_step_input = None
  589. while (small_step_input == None or small_step_input['type'] != 'selected_marking'):
  590. print 'waiting'
  591. with small_step_cond:
  592. small_step_cond.wait()
  593. print 'waiting done'
  594. if self.sim_mode != 'manual':
  595. # simulation mode has changed
  596. for t in transitions:
  597. t.set_enabled(False)
  598. for m in self.markings:
  599. m.set_current(False)
  600. return ["simulation_mode", self.sim_mode]
  601. if (small_step_input['type'] == 'selected_marking'):
  602. self.load_marking(small_step_input['value'])
  603. return [small_step_input['type'], small_step_input['value']]
  604. elif parsed_value["msg_type"] == "enabled_transitions":
  605. enabled_transitions = set(parsed_value["transitions"])
  606. for t in transitions:
  607. if t.name in enabled_transitions:
  608. t.set_enabled(True)
  609. else:
  610. t.set_enabled(False)
  611. small_step_input = None
  612. while (small_step_input == None or small_step_input['type'] not in ('selected_transition', 'selected_marking')):
  613. print 'waiting'
  614. with small_step_cond:
  615. small_step_cond.wait()
  616. print 'waiting done'
  617. if self.sim_mode != 'manual':
  618. # simulation mode has changed
  619. for t in transitions:
  620. t.set_enabled(False)
  621. for m in self.markings:
  622. m.set_current(False)
  623. return ["simulation_mode", self.sim_mode]
  624. if (small_step_input['type'] == 'selected_transition'):
  625. for t in transitions:
  626. t.set_enabled(False)
  627. for m in self.markings:
  628. m.set_current(False)
  629. if (small_step_input['type'] == 'selected_marking'):
  630. self.load_marking(small_step_input['value'])
  631. return [small_step_input['type'], small_step_input['value']]
  632. elif parsed_value["msg_type"] == "mode_change":
  633. if parsed_value["mode"] == "paused":
  634. print 'waiting'
  635. with cond:
  636. cond.wait()
  637. print 'waiting done'
  638. return self.sim_mode
  639. elif parsed_value["mode"] == "running":
  640. return
  641. return
  642. if value.startswith("#"):
  643. value = value[1:]
  644. print(value)
  645. return
  646. def load_marking(self, node_id):
  647. marking = [m for m in self.markings if m.node_id == node_id][0]
  648. for (k, v) in marking.marking_val.iteritems():
  649. place = [p for p in places if p.name == k][0]
  650. place.set_tokens(v)
  651. def continuous(self):
  652. self.sim_mode = "continuous"
  653. with cond:
  654. cond.notify()
  655. with small_step_cond:
  656. small_step_cond.notify()
  657. def step(self):
  658. self.sim_mode = "step"
  659. with cond:
  660. cond.notify()
  661. with small_step_cond:
  662. small_step_cond.notify()
  663. def manual(self):
  664. self.sim_mode = "manual"
  665. with cond:
  666. cond.notify()
  667. def add_breakpoint(self):
  668. self.sim_mode = "add_breakpoint"
  669. with cond:
  670. cond.notify()
  671. self.breakpoint_name = None
  672. self.breakpoint_disable_on_trigger = "False"
  673. self.breakpoint_code = None
  674. def edit_done(attr_vals, window):
  675. self.breakpoint_name = attr_vals["breakpoint name"]
  676. if attr_vals["disable on trigger?"] == "True":
  677. self.breakpoint_disable_on_trigger = "True"
  678. self.breakpoint_code = attr_vals["code"]
  679. window.destroy()
  680. with cond:
  681. cond.notify()
  682. self.breakpoint_info_entered = True
  683. self.breakpoint_info_entered = False
  684. default_breakpoint_code = \
  685. """
  686. include "primitives.alh"
  687. Boolean function bp_1(reachable_states: Element, mappings: Element):
  688. Element keys
  689. Element node
  690. String msg
  691. keys = dict_keys(reachable_states)
  692. while (read_nr_out(keys) > 0):
  693. node = reachable_states[set_pop(keys)]
  694. if (integer_gt(node["PetriNet/produced"], 0)):
  695. return True!
  696. return False!
  697. """
  698. editor = AttributeEditor('Input', {"breakpoint name": {"type": "string", "value": ""}, "disable on trigger?": {"type": "string", "value": "True"}, "code": {"type": "text", "value": default_breakpoint_code}}, edit_done)
  699. def clicked(self, event):
  700. if hasattr(event.widget, 'clicked') and event.widget.clicked:
  701. event.widget.clicked = False
  702. return
  703. global places
  704. global transitions
  705. if self.mode in ["PLACE", "TRANSITION"]:
  706. if self.mode == "PLACE":
  707. places.append(PlaceVis(self.pn_canvas, event.x, event.y))
  708. if self.mode == "TRANSITION":
  709. transitions.append(TransitionVis(self.pn_canvas, event.x, event.y))
  710. def draw(self, event):
  711. pass
  712. def release(self, event):
  713. pass
  714. class VerticallyScrolledWindow(tk.Frame):
  715. def __init__(self, root):
  716. tk.Frame.__init__(self, root)
  717. defaultbg = root.cget('bg')
  718. self.canvas = tk.Canvas(root, borderwidth=0, background=defaultbg)
  719. self.frame = tk.Frame(self.canvas, background=defaultbg)
  720. self.vsb = tk.Scrollbar(root, orient="vertical", command=self.canvas.yview)
  721. # self.canvas.configure(yscrollcommand=self.vsb.set)
  722. self.vsb.pack(side="right", fill="y")
  723. self.canvas.pack(side="left", fill="both", expand=True)
  724. self.canvas.create_window((4,4), window=self.frame, anchor="nw",
  725. tags="self.frame")
  726. self.frame.bind("<Configure>", self.onFrameConfigure)
  727. self.frame.bind_all("<MouseWheel>", self.scroll)
  728. def scroll(self, event):
  729. self.canvas.yview_scroll(-1 * (event.delta / 120), "units")
  730. def onFrameConfigure(self, event):
  731. '''Reset the scroll region to encompass the inner frame'''
  732. self.canvas.configure(scrollregion=self.canvas.bbox("all"))
  733. if __name__ == "__main__":
  734. app = PNInterface()
  735. app.mainloop()