1 package net.mograsim.logic.ui.model.components;
3 import java.io.IOException;
4 import java.io.InputStream;
5 import java.lang.reflect.Constructor;
6 import java.lang.reflect.InvocationTargetException;
7 import java.util.HashMap;
10 import net.mograsim.logic.ui.model.ViewModelModifiable;
11 import net.mograsim.logic.ui.model.wires.WireCrossPoint;
12 import net.mograsim.logic.ui.util.JsonHandler;
14 public class GUIComponentCreator
16 private final static Map<String, String> componentMapping;
20 Map<String, String> tmp;
21 try (InputStream s = GUIComponentCreator.class.getResourceAsStream("./mapping.json"))
23 tmp = JsonHandler.readJson(s, Map.class);
27 System.err.println("Failed to initialize component mapping; Components cannot be created from file.");
29 tmp = new HashMap<>();
31 componentMapping = tmp;
34 public static GUIComponent create(ViewModelModifiable model, String name, Map<String, Object> params)
38 String path = componentMapping.get(name);
39 if (path.startsWith("class:"))
41 path = path.substring(6);
42 return createComponentFromClass(model, path, params);
43 } else if (path.startsWith("file:"))
45 path = path.substring(5);
46 return GUICustomComponentCreator.create(model, path);
48 throw new IllegalArgumentException("Invalid submodel type! Type was neither prefixed by 'class:' nor by 'file:'");
50 catch (NullPointerException | InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException
51 | SecurityException | ClassNotFoundException | IllegalArgumentException e)
53 System.err.println("Failed to create requested component!");
55 return new SimpleRectangularSubmodelComponent(model, 1, "ERROR");
59 private static GUIComponent createComponentFromClass(ViewModelModifiable model, String classname, Map<String, Object> params)
60 throws InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException, SecurityException,
61 ClassNotFoundException
63 Class<?> c = Class.forName(classname);
65 if (SimpleRectangularGUIGate.class.isAssignableFrom(c) || WireCrossPoint.class.equals(c))
67 Constructor<?> constructor = c.getConstructor(ViewModelModifiable.class, int.class);
68 comp = constructor.newInstance(model, ((Number) params.get(SimpleRectangularGUIGate.kLogicWidth)).intValue());
71 Constructor<?> constructor = c.getConstructor(ViewModelModifiable.class);
72 comp = constructor.newInstance(model);
74 return (GUIComponent) comp;