Преглед изворни кода

Semi-working version of interface

Yentl Van Tendeloo пре 8 година
родитељ
комит
2bd47fd193

+ 6 - 5
core/core_algorithm.alc

@@ -32,17 +32,17 @@ String function JSON_print(model : Element):
 
 		if (bool_or(type == "Class", type == "Association")):
 			result = result + "{"
-			result = (((result + "\"id\": \"") + v_m) + "\"") + ","
-			result = (((result + "\"type\": \"") + read_type(model, v_m)) + "\"") + ","
+			result = (((result + "\"id\": \"") + v_m) + "\"")
+			result = (((result + ",") + "\"type\": \"") + read_type(model, v_m)) + "\""
 			if (type == "Association"):
-				result = ((result + "\"__source\": \"") + reverseKeyLookup(model["model"], read_edge_src(model["model"][v_m]))) + "\","
-				result = ((result + "\"__target\": \"") + reverseKeyLookup(model["model"], read_edge_dst(model["model"][v_m]))) + "\","
+				result = (((result + ", \"__source\": \"") + reverseKeyLookup(model["model"], read_edge_src(model["model"][v_m]))) + "\"")
+				result = (((result + ", \"__target\": \"") + reverseKeyLookup(model["model"], read_edge_dst(model["model"][v_m]))) + "\"")
 
 			// Has attributes
 			attr_keys = dict_keys(getAttributeList(model, v_m))
 			while (0 < read_nr_out(attr_keys)):
 				attr_key = set_pop(attr_keys)
-				result = ((((result + "\"") + attr_key) + "\": ") + cast_v2s(read_attribute(model, v_m, attr_key))) + ","
+				result = ((((result + ", \"") + attr_key) + "\": ") + cast_v2s(read_attribute(model, v_m, attr_key)))
 
 			result = result + "}"
 
@@ -372,6 +372,7 @@ Element function user_function():
 	exec(root["bootstrap/ramify.alc"]["initializers"])
 	exec(root["bootstrap/transform.alc"]["initializers"])
 	exec(root["bootstrap/conformance_scd.alc"]["initializers"])
+	exec(root["bootstrap/metamodels.alc"]["initializers"])
 	exec(root["core/core_algorithm.alc"]["initializers"])
 
 	// Load in a hard-reference to the previously created model

+ 1 - 1
core/mini_modify.alc

@@ -307,7 +307,7 @@ Element function modify(model : Element, write : Boolean):
 			while (read_nr_out(keys_t) > 0):
 				v_t = set_pop(keys_t)
 				if (bool_not(string_startswith(v_t, "__"))):
-					output(string_join(("  " + v_t) + " : ", read_type(model, v_t)))
+					output(string_join(("  " + v_t) + " : ", read_type(model["metamodel"], v_t)))
 
 		elif (cmd == "retype"):
 			if (write):

+ 89 - 14
interface/graphical/main.py

@@ -16,6 +16,7 @@ address = "http://127.0.0.1:8001"
 taskname = str(random.random())
 MAX_WIDTH = 500
 MAX_HEIGHT = 500
+MM_RENDERED = "MM_rendered_graphical"
 
 init()
 login("admin", "admin")
@@ -23,6 +24,51 @@ login("admin", "admin")
 root = Tk()
 canvas = Canvas(root, width=MAX_WIDTH, height=MAX_HEIGHT, bg="white")
 
+selected_model = StringVar(root)
+selected_mapper = StringVar(root)
+
+mm_buttons = []
+available_models = model_list()
+available_mappers = []
+model_options = OptionMenu(root, selected_model, *[i[0] for i in available_models])
+mapper_options = OptionMenu(root, selected_mapper, "", *available_mappers)
+
+def visualize(model):
+    print("Visualizing model: " + str(model))
+
+def reset_optionmenu(optionmenu, options, var):
+    menu = optionmenu.children["menu"]
+    menu.delete(0, "end")
+    var.set("")
+    for option in options:
+        menu.add_command(label=option, command=lambda value=option: var.set(value))
+
+reset_optionmenu(mapper_options, [], selected_mapper)
+
+def read_available_mappers(instance_model):
+    # Get instance model's type first, as transformations are defined on the type
+    models = dict(model_list())
+    type_model = models[instance_model]
+    print("Found type model: " + type_model)
+    print("Found MM_Rendered model: " + MM_RENDERED)
+
+    # Switch to the core to find all information on megamodel relations
+    model_modify("core")
+
+    all_elems = [n for n, t in element_list() if t in ["Model", "ModelTransformation"]]
+    all_attrs = {i: read_attrs(i) for i in all_elems}
+    model_map = {all_attrs[i]["name"]: i for i in all_attrs}
+    print("Got model_map: " + str(model_map))
+    a = set([read_association_source(i) for i in read_incoming(model_map[MM_RENDERED], "transformOutput")])
+    b = set([read_association_source(i) for i in read_incoming(model_map[type_model], "transformInput")])
+    model_exit()
+
+    print("All mappers for this tool: " + str(a))
+    print("All transformations for this model: " + str(b))
+    mappers = [all_attrs[i]["name"] for i in a & b]
+    print("Overlap: " + str(mappers))
+    return mappers
+
 class PromptDialog(tkSimpleDialog.Dialog):
     def __init__(self, master, query):
         self.query = query
@@ -39,19 +85,48 @@ class PromptDialog(tkSimpleDialog.Dialog):
     def apply(self):
         self.result = {self.query[i]: self.entries[i].get() for i in range(len(self.entries))}
 
+def create_element(t):
+    def create_elem():
+        print("Create element of type " + str(t))
+    return create_elem
+
+def render_model():
+    try:
+        model_exit()
+    except InvalidMode:
+        pass
+    rendered = model_render(selected_model.get(), selected_mapper.get())
+
+    #TODO visualize rendered model
+    print("Rendering model: " + rendered)
+    import json
+    visualize(json.loads(rendered))
+
 def open_model():
     try:
-        # Exit if necessary
         model_exit()
     except InvalidMode:
         pass
-    # Clear the canvas!
-    print("Opening model: " + variable.get())
-    model_modify(variable.get())
+    print("Opening model: " + selected_model.get())
+    available_mappers = read_available_mappers(selected_model.get())
+    reset_optionmenu(mapper_options, available_mappers, selected_mapper)
+
+    model_modify(selected_model.get())
+
+    print(types_full())
+    available_types = [i[0] for i in types_full() if i[1] == "Class"]
+
+    global mm_buttons
+    for button in mm_buttons:
+        button.destroy()
+
+    mm_buttons = []
+    for i, t in enumerate(available_types):
+        mm_buttons.append(Button(root, text=t, command=lambda : create_element(t)))
+        mm_buttons[-1].grid(row=1, column=i)
 
 def instantiate_model():
     try:
-        # Exit if necessary
         model_exit()
     except InvalidMode:
         pass
@@ -59,9 +134,10 @@ def instantiate_model():
     if d.result is not None:
         name = str(d.result["Name:"])
         print("Creating new model named " + name)
-        model_add(name, variable.get())
-        options.children["menu"].add_command(label=name, command=lambda v=name: variable.set(v))
-        model_modify(name)
+        model_add(name, selected_model.get())
+        reset_optionmenu(available_models, model_list())
+        selected_model.set(name)
+        open_model()
 
 def verify_model():
     try:
@@ -69,20 +145,19 @@ def verify_model():
         model_exit()
     except InvalidMode:
         pass
-    print(verify(variable.get()))
+    print(verify(selected_model.get()))
 
 bound_functions = {
     "open": open_model,
+    "render": render_model,
     "instantiate": instantiate_model,
     "verify": verify_model,
     }
 
 buttons = []
 
-models = model_list()
-variable = StringVar(root)
-options = OptionMenu(root, variable, *[i[0] for i in models])
-buttons.append(options)
+buttons.append(model_options)
+buttons.append(mapper_options)
 
 for k, v in bound_functions.items():
     buttons.append(Button(root, text=k, command=v))
@@ -90,7 +165,7 @@ for k, v in bound_functions.items():
 for i, b in enumerate(buttons):
     b.grid(row=0, column=i)
 
-canvas.grid(row=1,column=0,columnspan=len(buttons))
+canvas.grid(row=2,column=0,columnspan=len(buttons))
 
 def left_clicked():
     pass

+ 78 - 0
interface/graphical/upload_mappers.py

@@ -0,0 +1,78 @@
+import sys
+sys.path.append("interface/HUTN")
+from hutn_compiler.compiler import main as do_compile
+
+address = "http://127.0.0.1:8001"
+
+def get_model_constructor(code):
+    # First change multiple spaces to a tab
+    code_fragments = code.split("\n")
+    code_fragments = [i for i in code_fragments if i.strip() != ""]
+    code_fragments = [i.replace("    ", "\t") for i in code_fragments]
+    initial_tabs = min([len(i) - len(i.lstrip("\t")) for i in code_fragments])
+    code_fragments = [i[initial_tabs:] for i in code_fragments]
+    code_fragments.append("")
+    code = "\n".join(code_fragments)
+
+    with open("__model.mvc", "w") as f:
+        f.write(code)
+        f.flush()
+
+    return get_model_constructor_2("__model.mvc")
+
+def get_model_constructor_2(f):
+    return do_compile(f, "interface/HUTN/grammars/modelling.g", "M") + ["exit"]
+
+commands = [ "root", "root", "root",
+                "model_add",
+                    "SimpleClassDiagrams",
+                    "CausalBlockDiagrams",
+                    ] + get_model_constructor(open("integration/code/cbd_design.mvc", "r").read()) + [
+                "model_add",
+                    "SimpleClassDiagrams",
+                    "MM_rendered_graphical",
+                    ] + get_model_constructor(open("models/MM_rendered_graphical.mvc", "r").read()) + [
+                "model_add",
+                    "CausalBlockDiagrams",
+                    "my_CBD",
+                    ] + get_model_constructor(open("integration/code/my_cbd.mvc", "r").read()) + [
+                "model_list",
+                "transformation_add_MT_language",
+                "CausalBlockDiagrams",
+                "MM_rendered_graphical",
+                "",
+                "CBD_RAM",
+                "model_modify",
+                    "__merged_CBD_RAM",
+                        "instantiate",
+                            "Association",
+                            "TracabilityLink",
+                            "CausalBlockDiagrams/Block",
+                            "MM_rendered_graphical/Group",
+                        "exit",
+                "transformation_RAMify",
+                    "__merged_CBD_RAM",
+                    "CBD_RAM",
+                "transformation_add_MT",
+                    "CBD_RAM",
+                    "CausalBlockDiagrams",
+                    "MM_rendered_graphical",
+                    "",
+                    "MM_rendered_graphical",
+                    "",
+                    "render_graphical_CBD",
+                    ] + get_model_constructor(open("models/CBD_mapper.mvc", "r").read()) + [
+                "model_list",
+                "model_render",
+                    "my_CBD",
+                    "render_graphical_CBD",
+            ]
+
+import urllib2
+import urllib
+import json
+import random
+taskname = str(random.random())
+INIT_TIMEOUT = 9999
+urllib2.urlopen(urllib2.Request(address, urllib.urlencode({"op": "set_input", "value": '"%s"' % taskname, "taskname": "task_manager"})), timeout=INIT_TIMEOUT).read()
+urllib2.urlopen(urllib2.Request(address, urllib.urlencode({"op": "set_input", "data": json.dumps(commands), "taskname": taskname})), timeout=INIT_TIMEOUT).read()

+ 19 - 1
wrappers/modelverse.py

@@ -370,6 +370,7 @@ def model_render(model, mapper):
     _input(model)
     _output()
     _input(mapper)
+    _output("Mapping success")
     rendered = _output()
     _output("Ready for command...")
     return rendered
@@ -469,7 +470,7 @@ def element_list():
     # raises UnknownError
     if mode != 3:
         raise InvalidMode()
-    _input("list")
+    _input("list_full")
     lst = []
     _output("List of all elements:")
     while (_output() != "Please give your command."):
@@ -496,6 +497,23 @@ def types():
         lst.append(m)
     return lst
 
+def types_full():
+    """Return a list of full types usable in the model"""
+    # return [(type1, typetype1), (type2, typetype2), ...]
+    # raises UnknownError
+    if mode != 3:
+        raise InvalidMode()
+    _input("types")
+    _output("List of types:")
+    lst = []
+    while (_output() != "Please give your command."):
+        v = _last_output()
+        m, mm = v.split(":")
+        m = m.strip()
+        mm = mm.strip()
+        lst.append((m, mm))
+    return lst
+
 def read(ID):
     """Return a tuple of information on the element: its type and source/target (None if not an edge)"""
     # return (type, (source, target))