| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853 |
- import sys, json, threading
- import Tkinter as tk
- from modelverse import *
- places = []
- transitions = []
- p2ts = []
- t2ps = []
- cond = threading.Condition()
- small_step_cond = threading.Condition()
- small_step_input = None
- node_ids = set([])
- transition_ids = set([])
- class AttributeEditor(tk.Toplevel):
- def __init__(self, title, entries, callback):
- tk.Toplevel.__init__(self)
-
- self.geometry("800x600")
- self.title(title)
- self.entries = entries
-
- self.window = VerticallyScrolledWindow(self)
-
- self.entries_vis = {}
-
- for i, k in enumerate(self.entries.keys()):
- tk.Label(self.window.frame, text=k).grid(row=i)
- if (self.entries[k]["type"] == "string"):
- content = tk.StringVar()
- content.set(self.entries[k]["value"])
- self.entries[k]["entry"] = tk.Entry(self.window.frame, width=40, textvariable=content)
- self.entries[k]["entry"].grid(row=i, column=1, sticky= 'w', pady=10)
- elif (self.entries[k]["type"] == "text"):
- frame = tk.Frame(self.window.frame)
- frame.grid(row=i, column=1, sticky='w', pady=10)
- scroll = tk.Scrollbar(frame, orient=tk.VERTICAL)
- content = tk.Text(frame, height=25, width=80)
- content.insert(tk.END, self.entries[k]["value"])
- scroll.pack(side=tk.RIGHT, fill=tk.Y, expand=tk.FALSE)
- content.pack(side=tk.LEFT, fill=tk.Y)
- scroll.config(command=content.yview)
- # content.config(yscrollcommand=scroll.set)
- self.entries[k]["entry"] = content
- self.window.pack(side="top", fill="both", expand=True)
-
- 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))
- self.submit_button.grid(row=i+1, column=1)
-
- self.grab_set()
- self.focus_force()
-
- class PlaceVis:
- R = 20
-
- def __init__(self, canvas, x, y, name="", tokens=0):
- self.canvas = canvas
- self.vis = canvas.create_oval(x - PlaceVis.R, y - PlaceVis.R, x + PlaceVis.R, y + PlaceVis.R, fill="white")
- self.name = name
- self.name_text = canvas.create_text(x, y + PlaceVis.R + 10, text=name, font=('Helvetica', '12'))
- self.tokens = tokens
- self.tokens_text = canvas.create_text(x, y, text=tokens, font=('Helvetica', '12'))
- canvas.tag_bind(self.vis, "<Button-1>", self.clicked)
- canvas.tag_bind(self.name_text, "<Button-1>", self.clicked)
- canvas.tag_bind(self.tokens_text, "<Button-1>", self.clicked)
- canvas.tag_bind(self.vis, "<Double-Button-1>", self.edit)
- canvas.tag_bind(self.name_text, "<Double-Button-1>", self.edit)
- canvas.tag_bind(self.tokens_text, "<Double-Button-1>", self.edit)
- canvas.tag_bind(self.vis, "<B1-Motion>", self.move)
- canvas.tag_bind(self.name_text, "<B1-Motion>", self.move)
- canvas.tag_bind(self.tokens_text, "<B1-Motion>", self.move)
- canvas.tag_bind(self.vis, "<Double-Button-3>", self.delete)
- canvas.tag_bind(self.name_text, "<Double-Button-3>", self.delete)
- canvas.tag_bind(self.tokens_text, "<Double-Button-3>", self.delete)
- self.x = x
- self.y = y
- self.t2ps = []
- self.p2ts = []
- self.last_click_x = None
- self.last_click_y = None
-
- def get_name(self):
- return self.name
-
- def clicked(self, event):
- event.widget.clicked = True
- self.last_click_x = event.x
- self.last_click_y = event.y
-
- def delete(self, event):
- self.canvas.delete(self.vis)
- self.canvas.delete(self.name_text)
- self.canvas.delete(self.tokens_text)
-
- for t2p in self.t2ps:
- t2p.delete()
- for p2t in self.p2ts:
- p2t.delete()
-
- global places
- places = [el for el in places if el.name != self.name]
-
- def move(self, event):
- delta_x = event.x - self.last_click_x
- delta_y = event.y - self.last_click_y
- self.canvas.move(self.vis, delta_x, delta_y)
- self.canvas.move(self.name_text, delta_x, delta_y)
- self.canvas.move(self.tokens_text, delta_x, delta_y)
- self.x += delta_x
- self.y += delta_y
- self.last_click_x = event.x
- self.last_click_y = event.y
-
- for t2p in self.t2ps:
- t2p.moved()
- for p2t in self.p2ts:
- p2t.moved()
-
- def edit(self, event):
- event.widget.clicked = True
- 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)
-
- def edit_done(self, attr_vals, window):
- self.set_name(attr_vals["name"])
- self.set_tokens(int(attr_vals["tokens"]))
- window.destroy()
-
- def set_name(self, name):
- self.canvas.itemconfig(self.name_text, text=str(name))
- self.name = name
-
- def set_tokens(self, tokens):
- self.canvas.itemconfig(self.tokens_text, text=str(tokens))
- self.tokens = tokens
-
- class TransitionVis:
- H = 30
- W = 10
-
- def __init__(self, canvas, x, y, name=""):
- self.canvas = canvas
- self.vis = canvas.create_rectangle(x - TransitionVis.W/2, y - TransitionVis.H/2, x + TransitionVis.W/2, y + TransitionVis.H/2, fill="black")
- self.name = name
- self.name_text = canvas.create_text(x, y + TransitionVis.H/2 + 10, text=name, font=('Helvetica', '12'))
- canvas.tag_bind(self.vis, "<Button-1>", self.clicked)
- canvas.tag_bind(self.name_text, "<Button-1>", self.clicked)
- canvas.tag_bind(self.vis, "<Double-Button-1>", self.edit)
- canvas.tag_bind(self.name_text, "<Double-Button-1>", self.edit)
- canvas.tag_bind(self.vis, "<B1-Motion>", self.move)
- canvas.tag_bind(self.name_text, "<B1-Motion>", self.move)
- canvas.tag_bind(self.vis, "<Button-3>", self.select)
- canvas.tag_bind(self.name_text, "<Button-3>", self.select)
- canvas.tag_bind(self.vis, "<Double-Button-3>", self.delete)
- canvas.tag_bind(self.name_text, "<Double-Button-3>", self.delete)
- self.x = x
- self.y = y
- self.t2ps = []
- self.p2ts = []
- self.last_click_x = None
- self.last_click_y = None
-
- def get_name(self):
- return self.name
-
- def clicked(self, event):
- event.widget.clicked = True
- self.last_click_x = event.x
- self.last_click_y = event.y
-
- def set_enabled(self, enabled=False):
- if enabled:
- self.canvas.itemconfig(self.vis, fill="green")
- else:
- self.canvas.itemconfig(self.vis, fill="black")
-
- def select(self, event):
- global small_step_input
- small_step_input = {'type': 'selected_transition', 'value': self.name}
- with small_step_cond:
- small_step_cond.notify()
-
- def delete(self, event):
- self.canvas.delete(self.vis)
- self.canvas.delete(self.name_text)
-
- for t2p in self.t2ps:
- t2p.delete()
- for p2t in self.p2ts:
- p2t.delete()
-
- global transitions
- transitions = [el for el in transitions if el.name != self.name]
-
- def move(self, event):
- delta_x = event.x - self.last_click_x
- delta_y = event.y - self.last_click_y
- self.canvas.move(self.vis, delta_x, delta_y)
- self.canvas.move(self.name_text, delta_x, delta_y)
- self.x += delta_x
- self.y += delta_y
- self.last_click_x = event.x
- self.last_click_y = event.y
-
- for t2p in self.t2ps:
- t2p.moved()
- for p2t in self.p2ts:
- p2t.moved()
-
- def edit(self, event):
- event.widget.clicked = True
- editor = AttributeEditor('Attributes of Transitions', {"name": {"type": "string", "value": self.canvas.itemcget(self.name_text, "text")}}, self.edit_done)
-
- def edit_done(self, attr_vals, window):
- self.set_name(attr_vals["name"])
- window.destroy()
-
- def set_name(self, name):
- self.canvas.itemconfig(self.name_text, text=name)
- self.name = name
-
- class TransitionToPlaceVis:
- def __init__(self, canvas, transition, place, weight=1):
- self.canvas = canvas
- self.transition = transition
- self.place = place
- self.weight = 1
-
- self.line = self.canvas.create_line(transition.x, transition.y, place.x, place.y, fill="black", arrow=tk.LAST, arrowshape=(12, 14, 6))
- x_coords = sorted([self.transition.x, self.place.x])
- y_coords = sorted([self.transition.y, self.place.y])
- 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'))
- canvas.tag_bind(self.line, "<Double-Button-3>", self.delete)
- canvas.tag_bind(self.text, "<Double-Button-3>", self.delete)
-
- self.transition.t2ps.append(self)
- self.place.t2ps.append(self)
-
- def moved(self):
- self.canvas.coords(self.line, self.transition.x, self.transition.y, self.place.x, self.place.y)
- x_coords = sorted([self.transition.x, self.place.x])
- y_coords = sorted([self.transition.y, self.place.y])
- 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)
-
- def delete(self, event=None):
- self.canvas.delete(self.line)
- self.canvas.delete(self.text)
-
- global t2ps
- t2ps = [el for el in t2ps if el.transition != self.transition and el.place != self.place]
-
- class PlaceToTransitionVis:
- def __init__(self, canvas, place, transition, weight=1):
- self.canvas = canvas
- self.place = place
- self.transition = transition
- self.weight = 1
-
- self.line = self.canvas.create_line(place.x, place.y, transition.x, transition.y, fill="black", arrow=tk.LAST, arrowshape=(12, 14, 6))
- x_coords = sorted([self.transition.x, self.place.x])
- y_coords = sorted([self.transition.y, self.place.y])
- 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'))
- canvas.tag_bind(self.line, "<Double-Button-3>", self.delete)
- canvas.tag_bind(self.text, "<Double-Button-3>", self.delete)
-
- self.place.p2ts.append(self)
- self.transition.p2ts.append(self)
-
- def moved(self):
- self.canvas.coords(self.line, self.place.x, self.place.y, self.transition.x, self.transition.y)
- x_coords = sorted([self.transition.x, self.place.x])
- y_coords = sorted([self.transition.y, self.place.y])
- 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)
-
- def delete(self, event=None):
- self.canvas.delete(self.line)
- self.canvas.delete(self.text)
-
- global p2ts
- p2ts = [el for el in p2ts if el.place != self.place and el.transition != self.transition]
-
- class MarkingVis:
- def __init__(self, canvas, x, y, node_id, content={}):
- global node_ids
- node_ids.add(node_id)
-
- self.node_id = node_id
- self.canvas = canvas
- self.marking_val = content
- self.vis = canvas.create_text(x, y, text=str(content).replace(',', ',\n'), font=('Helvetica', '14'))
- self.bbox = canvas.bbox(self.vis)
- canvas.move(self.vis, (self.bbox[2]-self.bbox[0])/2, (self.bbox[3]-self.bbox[1])/2)
- self.bbox = canvas.bbox(self.vis)
- self.rect = canvas.create_rectangle(*self.bbox, fill="")
- canvas.tag_bind(self.vis, "<Button-1>", self.clicked)
- canvas.tag_bind(self.rect, "<Button-1>", self.clicked)
- canvas.tag_bind(self.vis, "<B1-Motion>", self.move)
- canvas.tag_bind(self.rect, "<B1-Motion>", self.move)
- canvas.tag_bind(self.vis, "<Button-3>", self.rightclicked)
- canvas.tag_bind(self.rect, "<Button-3>", self.rightclicked)
- canvas.tag_lower(self.rect)
- self.x = x
- self.y = y
- self.m2ms = []
- self.last_click_x = None
- self.last_click_y = None
-
- def get_width(self):
- return self.bbox[2]-self.bbox[0]
-
- def get_height(self):
- return self.bbox[3]-self.bbox[1]
-
- def set_current(self, current=False):
- if current:
- self.canvas.itemconfig(self.rect, fill="yellow")
- else:
- self.canvas.itemconfig(self.rect, fill="")
-
- def rightclicked(self, event):
- global small_step_input
- small_step_input = {'type': 'selected_marking', 'value': self.node_id}
- with small_step_cond:
- small_step_cond.notify()
-
- def clicked(self, event):
- event.widget.clicked = True
- self.last_click_x = event.x
- self.last_click_y = event.y
-
- def move(self, event):
- delta_x = event.x - self.last_click_x
- delta_y = event.y - self.last_click_y
- self.canvas.move(self.vis, delta_x, delta_y)
- self.canvas.move(self.rect, delta_x, delta_y)
- self.x += delta_x
- self.y += delta_y
- self.last_click_x = event.x
- self.last_click_y = event.y
-
- for m2m in self.m2ms:
- m2m.moved()
-
- class MarkingToMarkingVis:
- def __init__(self, canvas, transition_id, m1, m2, transition):
- global transition_ids
- transition_ids.add(transition_id)
-
- self.canvas = canvas
- self.m1 = m1
- self.m2 = m2
- self.transition = transition
-
- 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))
- x_coords = sorted([self.m1.x, self.m2.x])
- y_coords = sorted([self.m1.y+self.m1.get_height(), self.m2.y])
- 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'))
-
- self.m1.m2ms.append(self)
- self.m2.m2ms.append(self)
-
- def moved(self):
- self.canvas.coords(self.line, self.m1.x, self.m1.y+self.m1.get_height(), self.m2.x, self.m2.y)
- x_coords = sorted([self.m1.x, self.m2.x])
- y_coords = sorted([self.m1.y+self.m1.get_height(), self.m2.y])
- 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)
- class PNInterface(tk.Tk):
- MAX_WIDTH = 8192
- MAX_HEIGHT = 8192
-
- def __init__(self, *args, **kwargs):
- tk.Tk.__init__(self, *args, **kwargs)
-
- print("Init")
- init()
- print("Login")
- #login(str(random.random()), str(random.random()))
- login("admin", "admin")
- # Add the metamodels for PetriNet and ReachabilityGraph
- print("Add metamodels")
- try:
- model_add("formalisms/PetriNet", "formalisms/SimpleClassDiagrams", open("../../models/petrinets.mvc").read())
- except ModelExists:
- pass
- try:
- model_add("formalisms/ReachabilityGraph", "formalisms/SimpleClassDiagrams", open("../../models/reachability_graph.mvc").read())
- except ModelExists:
- pass
-
- # Remove the action language code to transform between them
- print("Remove AL model")
- try:
- model_delete("models/analyseReachability")
- except ModelverseException:
- pass
- # Add the action language code to transform between them
- print("Add AL model")
- try:
- transformation_add_AL({"PetriNet": "formalisms/PetriNet"}, {"ReachabilityGraph": "formalisms/ReachabilityGraph"}, "models/analyseReachability", open("../../models/reachability.alc", "r").read())
- except ModelExists:
- pass
-
- # Add an example model transformation to print the reachability graph
- print("Add MT model")
- try:
- transformation_add_MT({"ReachabilityGraph": "formalisms/ReachabilityGraph"}, {}, "models/printReachability", open("../../models/reachabilitygraph_print.mvc").read())
- except ModelExists:
- pass
-
- self.markings = []
- self.m2ms = []
- self.mode = "PLACE"
- self.sim_mode = None
- # global attributes
- self.title('Petrinets Debugging Interface')
- self.minsize(self.winfo_screenwidth() / 2, self.winfo_screenheight() / 2)
-
- # modelling toolbar
- self.modelling_toolbar_frame = tk.Frame(self)
- self.modelling_toolbar_frame.grid(row=0, column=0, columnspan=2, sticky=tk.W)
-
- self.INTER_SPACING = 5
-
- self.buttons = ["PLACE", "TRANSITION", "P2T", "T2P"]
- self.button_config = {"PLACE": self.place,
- "TRANSITION": self.transition,
- "P2T": self.place_to_transition,
- "T2P": self.transition_to_place}
- self.button_img = {}
- self.buttons_vis = {}
- i = 0
- for k in self.buttons:
- v = self.button_config[k]
- if k in self.button_img:
- btn = tk.Button(self.modelling_toolbar_frame, image=self.button_img[k], command=v)
- else:
- btn = tk.Button(self.modelling_toolbar_frame, text=k, command=v)
- btn.grid(row=0, column=i, padx=self.INTER_SPACING, sticky=tk.W)
- self.buttons_vis[k] = btn
- i += 1
-
- # debugging toolbar
- self.debugging_toolbar_frame = tk.Frame(self)
- self.debugging_toolbar_frame.grid(row=0, column=2, columnspan=2, sticky=tk.W)
-
- self.INTER_SPACING = 5
-
- self.buttons = ["load", "continuous", "step", "manual", "add_breakpoint"]
- self.button_config = {"load": self.load,
- "continuous": self.continuous,
- "step": self.step,
- "manual": self.manual,
- "add_breakpoint": self.add_breakpoint}
- self.button_img = {"load": tk.PhotoImage(file="load.icon.gif"),
- "continuous": tk.PhotoImage(file="simulate.icon.gif"),
- "step": tk.PhotoImage(file="step.icon.gif"),
- "manual": tk.PhotoImage(file="godevent.icon.gif"),
- "add_breakpoint": tk.PhotoImage(file="addbp.icon.gif")}
- self.button_img_disabled = {"load": tk.PhotoImage(file="load.disabled.icon.gif"),
- "continuous": tk.PhotoImage(file="simulate.disabled.icon.gif"),
- "step": tk.PhotoImage(file="step.disabled.icon.gif"),
- "manual": tk.PhotoImage(file="godevent.disabled.icon.gif"),
- "add_breakpoint": tk.PhotoImage(file="addbp.disabled.icon.gif")}
- self.buttons_vis = {}
- i = 0
- for k in self.buttons:
- v = self.button_config[k]
- if k in self.button_img:
- btn = tk.Button(self.debugging_toolbar_frame, image=self.button_img[k], command=v)
- else:
- btn = tk.Button(self.debugging_toolbar_frame, text=k, command=v)
- btn.grid(row=0, column=i, padx=self.INTER_SPACING, sticky=tk.W)
- self.buttons_vis[k] = btn
- if k != "load":
- btn.config(state=tk.DISABLED)
- btn.config(image=self.button_img_disabled[k])
- i += 1
-
- # Petrinets canvas
- CANVAS_SIZE_TUPLE = (0, 0, PNInterface.MAX_WIDTH, PNInterface.MAX_HEIGHT)
- self.pn_canvas = tk.Canvas(self, relief=tk.RIDGE, scrollregion=CANVAS_SIZE_TUPLE, bg="white")
- self.pn_vbar = tk.Scrollbar(self, orient=tk.VERTICAL)
- self.pn_vbar.config(command=self.pn_canvas.yview)
- self.pn_hbar = tk.Scrollbar(self, orient=tk.HORIZONTAL)
- self.pn_hbar.config(command=self.pn_canvas.xview)
- # self.pn_canvas.config(background='white', yscrollcommand=self.pn_vbar.set, xscrollcommand=self.pn_hbar.set)
- self.pn_canvas.config(background='white')
-
- self.pn_canvas.bind("<Button-1>", self.clicked)
- self.pn_canvas.bind("<Button-3>", self.draw)
- self.pn_canvas.bind("<ButtonRelease-3>", self.release)
-
- self.rg_canvas = tk.Canvas(self, relief=tk.RIDGE, scrollregion=CANVAS_SIZE_TUPLE, bg="white")
- self.rg_vbar = tk.Scrollbar(self, orient=tk.VERTICAL)
- self.rg_vbar.config(command=self.rg_canvas.yview)
- self.rg_hbar = tk.Scrollbar(self, orient=tk.HORIZONTAL)
- self.rg_hbar.config(command=self.rg_canvas.xview)
- # self.rg_canvas.config(background='white', yscrollcommand=self.rg_vbar.set, xscrollcommand=self.rg_hbar.set)
- self.rg_canvas.config(background='white')
- self.pn_canvas.grid(row=1, column=0, sticky=tk.W+tk.E+tk.N+tk.S)
- self.pn_vbar.grid(row=1, column=1, sticky=tk.N+tk.S, pady=(0, 16))
- self.pn_hbar.grid(row=2, column=0, columnspan=2, sticky=tk.W+tk.E)
- self.rg_canvas.grid(row=1, column=2, sticky=tk.W+tk.E+tk.N+tk.S)
- self.rg_vbar.grid(row=1, column=3, sticky=tk.N+tk.S, pady=(0, 16))
- self.rg_hbar.grid(row=2, column=2, columnspan=2, sticky=tk.W+tk.E)
-
- self.grid_columnconfigure(0, weight=1)
- self.grid_columnconfigure(2, weight=1)
- self.grid_rowconfigure(1, weight=1)
-
- self.setup()
-
- def enable_buttons(self, commands):
- for (k, btn) in self.buttons_vis.items():
- if k in commands:
- btn.config(state=tk.NORMAL)
- btn.config(image=self.button_img[k])
- else:
- btn.config(state=tk.DISABLED)
- btn.config(image=self.button_img_disabled[k])
- def setup(self):
- free = PlaceVis(self.pn_canvas, 100, 200, "free", 3)
- max_items = PlaceVis(self.pn_canvas, 150, 400, "maximum items", 3)
- producing = PlaceVis(self.pn_canvas, 200, 200, "producing", 0)
- produced = PlaceVis(self.pn_canvas, 300, 200, "produced", 0)
- waiting = PlaceVis(self.pn_canvas, 400, 200, "waiting", 2)
- consuming = PlaceVis(self.pn_canvas, 500, 200, "consuming", 0)
- global places
- places = [free, producing, produced, waiting, consuming, max_items]
-
- start_produce = TransitionVis(self.pn_canvas, 150, 100, "start producing")
- end_produce = TransitionVis(self.pn_canvas, 150, 300, "end producing")
- start_consume = TransitionVis(self.pn_canvas, 450, 100, "start consuming")
- end_consume = TransitionVis(self.pn_canvas, 450, 300, "end consuming")
- global transitions
- transitions = [start_produce, end_produce, start_consume, end_consume]
-
- f_to_s_p = PlaceToTransitionVis(self.pn_canvas, free, start_produce)
- s_p_to_p = TransitionToPlaceVis(self.pn_canvas, start_produce, producing)
- p_to_e_p = PlaceToTransitionVis(self.pn_canvas, producing, end_produce)
- m_i_to_e_p = PlaceToTransitionVis(self.pn_canvas, max_items, end_produce)
- e_p_to_f = TransitionToPlaceVis(self.pn_canvas, end_produce, free)
-
- w_to_s_c = PlaceToTransitionVis(self.pn_canvas, waiting, start_consume)
- s_c_to_c = TransitionToPlaceVis(self.pn_canvas, start_consume, consuming)
- c_to_e_c = PlaceToTransitionVis(self.pn_canvas, consuming, end_consume)
- e_c_to_w = TransitionToPlaceVis(self.pn_canvas, end_consume, waiting)
-
- e_p_to_p = TransitionToPlaceVis(self.pn_canvas, end_produce, produced)
- p_to_s_c = PlaceToTransitionVis(self.pn_canvas, produced, start_consume)
- global p2ts
- 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]
- global t2ps
- t2ps = [s_p_to_p, e_p_to_f, s_c_to_c, e_c_to_w, e_p_to_p]
-
- def place(self):
- self.mode = "PLACE"
-
- def transition(self):
- self.mode = "TRANSITION"
-
- def place_to_transition(self):
- def create_p2t(attr_vals, window):
- src = [p for p in places if p.get_name() == attr_vals["src"]]
- dst = [t for t in transitions if t.get_name() == attr_vals["dst"]]
- if len(src) == 1 and len(dst) == 1:
- global p2ts
- p2ts.append(PlaceToTransitionVis(self.pn_canvas, src[0], dst[0], attr_vals["weight"]))
- else:
- print 'could not find source and/or target nodes'
- window.destroy()
- editor = AttributeEditor('Create P2T', {"weight": {"type": "string", "value": 1}, "src": {"type": "string", "value": ""}, "dst": {"type": "string", "value": ""}}, create_p2t)
-
- def transition_to_place(self):
- def create_t2p(attr_vals, window):
- src = [t for t in transitions if t.get_name() == attr_vals["src"]]
- dst = [p for p in places if p.get_name() == attr_vals["dst"]]
- if len(src) == 1 and len(dst) == 1:
- global t2ps
- t2ps.append(TransitionToPlaceVis(self.pn_canvas, src[0], dst[0], attr_vals["weight"]))
- else:
- print 'could not find source and/or target nodes'
- window.destroy()
- editor = AttributeEditor('Create T2P', {"weight": {"type": "string", "value": 1}, "src": {"type": "string", "value": ""}, "dst": {"type": "string", "value": ""}}, create_t2p)
-
- def load(self):
- self.enable_buttons([])
- with open("model.mvc", "w+") as model_file:
- for p in places:
- model_file.write("Place %s {\n" % p.name.replace(" ", "_"))
- model_file.write("\ttokens = %i\n" % p.tokens)
- model_file.write("\tname = \"%s\"\n" % p.name)
- model_file.write("}\n")
- for t in transitions:
- model_file.write("Transition %s {\n" % t.name.replace(" ", "_"))
- model_file.write("\tname = \"%s\"\n" % t.name)
- model_file.write("}\n")
- for t2p in t2ps:
- model_file.write("T2P (%s, %s) {\n" % (t2p.transition.name.replace(" ", "_"), t2p.place.name.replace(" ", "_")))
- model_file.write("\tweight = %i\n" % t2p.weight)
- model_file.write("}\n")
- for p2t in p2ts:
- model_file.write("P2T (%s, %s) {\n" % (p2t.place.name.replace(" ", "_"), p2t.transition.name.replace(" ", "_")))
- model_file.write("\tweight = %i\n" % p2t.weight)
- model_file.write("}\n")
- print("Delete model")
- try:
- model_delete("models/my_pn")
- except ModelverseException:
- pass
-
- print("Add model")
- try:
- model_add("models/my_pn", "formalisms/PetriNet", open("model.mvc").read())
- except ModelExists:
- pass
-
- def executeAL():
- print("Execute AL")
- status = transformation_execute_AL("models/analyseReachability", {"PetriNet": "models/my_pn"}, {"ReachabilityGraph": "models/my_reachability"}, callback=self.callback)
- print("Reachability generation success: " + str(status))
-
- print("Execute MT")
- def print_mv(value):
- print(value)
- status = transformation_execute_MT("models/printReachability", {"ReachabilityGraph": "models/my_reachability"}, {}, callback=print_mv)
- print("Reachability printing success: " + str(status))
-
- # Start the reachability graph generation
- thrd = threading.Thread(target=executeAL)
- thrd.daemon = True
- thrd.start()
-
- def callback(self, value):
- global small_step_input
- if value.startswith("{"):
- print(value)
- parsed_value = json.loads(value)
- if parsed_value["msg_type"] == 'node_added':
- self.markings.append(MarkingVis(self.rg_canvas, 100, 50, parsed_value['node_info']['node_id'], parsed_value['node_info']['node_marking']))
- elif parsed_value["msg_type"] == 'link_added':
- m1 = [m for m in self.markings if m.node_id == parsed_value['link_info']['source']][0]
- m2 = [m for m in self.markings if m.node_id == parsed_value['link_info']['target']][0]
- t = [t for t in transitions if t.name == parsed_value['link_info']['transition']][0]
- self.m2ms.append(MarkingToMarkingVis(self.rg_canvas, parsed_value['link_info']['transition_id'], m1, m2, t))
- elif parsed_value["msg_type"] == "reachable_nodes":
- for n in parsed_value["nodes"]:
- if not (n['node_id'] in node_ids):
- node_id = n['node_id']
- if len([m for m in self.markings if m.node_id == node_id]) == 0:
- self.markings.append(MarkingVis(self.rg_canvas, 100, 50, node_id, n['node_marking']))
- elif parsed_value["msg_type"] == "node_links":
- for n in parsed_value["links"]:
- if not (n['transition_id'] in transition_ids):
- m1 = [m for m in self.markings if m.node_id == n['source']][0]
- m2 = [m for m in self.markings if m.node_id == n['target']][0]
- t = [t for t in transitions if t.name == n['transition']][0]
- self.m2ms.append(MarkingToMarkingVis(self.rg_canvas, n['transition_id'], m1, m2, t))
- elif parsed_value["msg_type"] == "input_required":
- if (not self.breakpoint_info_entered):
- print 'waiting'
- with cond:
- cond.wait()
- print 'waiting done'
- if parsed_value["name"] == "breakpoint name":
- return self.breakpoint_name
- elif parsed_value["name"] == "disable on trigger?":
- return self.breakpoint_disable_on_trigger
- elif parsed_value["name"] == "breakpoint function":
- upload_code(self.breakpoint_code)
- elif parsed_value["msg_type"] == "enabled_commands":
- self.enable_buttons(set(parsed_value["commands"]))
- if (len(parsed_value["commands"]) == 0):
- return
- return
- elif parsed_value["msg_type"] == "unexplored_markings":
- unexplored_markings = set(parsed_value["markings"])
- for m in self.markings:
- if m.node_id in unexplored_markings:
- m.set_current(True)
- small_step_input = None
- while (small_step_input == None or small_step_input['type'] != 'selected_marking'):
- print 'waiting'
- with small_step_cond:
- small_step_cond.wait()
- print 'waiting done'
- if self.sim_mode != 'manual':
- # simulation mode has changed
- for t in transitions:
- t.set_enabled(False)
- for m in self.markings:
- m.set_current(False)
- return ["simulation_mode", self.sim_mode]
- if (small_step_input['type'] == 'selected_marking'):
- self.load_marking(small_step_input['value'])
- return [small_step_input['type'], small_step_input['value']]
- elif parsed_value["msg_type"] == "enabled_transitions":
- enabled_transitions = set(parsed_value["transitions"])
- for t in transitions:
- if t.name in enabled_transitions:
- t.set_enabled(True)
- else:
- t.set_enabled(False)
- small_step_input = None
- while (small_step_input == None or small_step_input['type'] not in ('selected_transition', 'selected_marking')):
- print 'waiting'
- with small_step_cond:
- small_step_cond.wait()
- print 'waiting done'
- if self.sim_mode != 'manual':
- # simulation mode has changed
- for t in transitions:
- t.set_enabled(False)
- for m in self.markings:
- m.set_current(False)
- return ["simulation_mode", self.sim_mode]
- if (small_step_input['type'] == 'selected_transition'):
- for t in transitions:
- t.set_enabled(False)
- for m in self.markings:
- m.set_current(False)
- if (small_step_input['type'] == 'selected_marking'):
- self.load_marking(small_step_input['value'])
- return [small_step_input['type'], small_step_input['value']]
- elif parsed_value["msg_type"] == "mode_change":
- if parsed_value["mode"] == "paused":
- print 'waiting'
- with cond:
- cond.wait()
- print 'waiting done'
- return self.sim_mode
- elif parsed_value["mode"] == "running":
- return
- return
- if value.startswith("#"):
- value = value[1:]
- print(value)
- return
-
- def load_marking(self, node_id):
- marking = [m for m in self.markings if m.node_id == node_id][0]
- for (k, v) in marking.marking_val.iteritems():
- place = [p for p in places if p.name == k][0]
- place.set_tokens(v)
-
- def continuous(self):
- self.sim_mode = "continuous"
- with cond:
- cond.notify()
- with small_step_cond:
- small_step_cond.notify()
-
- def step(self):
- self.sim_mode = "step"
- with cond:
- cond.notify()
- with small_step_cond:
- small_step_cond.notify()
-
- def manual(self):
- self.sim_mode = "manual"
- with cond:
- cond.notify()
-
- def add_breakpoint(self):
- self.sim_mode = "add_breakpoint"
- with cond:
- cond.notify()
- self.breakpoint_name = None
- self.breakpoint_disable_on_trigger = "False"
- self.breakpoint_code = None
- def edit_done(attr_vals, window):
- self.breakpoint_name = attr_vals["breakpoint name"]
- if attr_vals["disable on trigger?"] == "True":
- self.breakpoint_disable_on_trigger = "True"
- self.breakpoint_code = attr_vals["code"]
- window.destroy()
- with cond:
- cond.notify()
- self.breakpoint_info_entered = True
- self.breakpoint_info_entered = False
- default_breakpoint_code = \
- """
- include "primitives.alh"
- Boolean function bp_1(reachable_states: Element, mappings: Element):
- Element keys
- Element node
- String msg
- keys = dict_keys(reachable_states)
- while (read_nr_out(keys) > 0):
- node = reachable_states[set_pop(keys)]
- if (integer_gt(node["PetriNet/produced"], 0)):
- return True!
- return False!
- """
- editor = AttributeEditor('Input', {"breakpoint name": {"type": "string", "value": ""}, "disable on trigger?": {"type": "string", "value": "True"}, "code": {"type": "text", "value": default_breakpoint_code}}, edit_done)
-
- def clicked(self, event):
- if hasattr(event.widget, 'clicked') and event.widget.clicked:
- event.widget.clicked = False
- return
- global places
- global transitions
- if self.mode in ["PLACE", "TRANSITION"]:
- if self.mode == "PLACE":
- places.append(PlaceVis(self.pn_canvas, event.x, event.y))
- if self.mode == "TRANSITION":
- transitions.append(TransitionVis(self.pn_canvas, event.x, event.y))
-
- def draw(self, event):
- pass
-
- def release(self, event):
- pass
-
- class VerticallyScrolledWindow(tk.Frame):
- def __init__(self, root):
- tk.Frame.__init__(self, root)
- defaultbg = root.cget('bg')
- self.canvas = tk.Canvas(root, borderwidth=0, background=defaultbg)
- self.frame = tk.Frame(self.canvas, background=defaultbg)
- self.vsb = tk.Scrollbar(root, orient="vertical", command=self.canvas.yview)
- # self.canvas.configure(yscrollcommand=self.vsb.set)
- self.vsb.pack(side="right", fill="y")
- self.canvas.pack(side="left", fill="both", expand=True)
- self.canvas.create_window((4,4), window=self.frame, anchor="nw",
- tags="self.frame")
- self.frame.bind("<Configure>", self.onFrameConfigure)
- self.frame.bind_all("<MouseWheel>", self.scroll)
- def scroll(self, event):
- self.canvas.yview_scroll(-1 * (event.delta / 120), "units")
- def onFrameConfigure(self, event):
- '''Reset the scroll region to encompass the inner frame'''
- self.canvas.configure(scrollregion=self.canvas.bbox("all"))
-
- if __name__ == "__main__":
- app = PNInterface()
- app.mainloop()
|