627ebaf752786fa41d3e5c0ae4e0c4b07321f44a
[Mograsim.git] / plugins / net.mograsim.logic.model.am2900 / src / net / mograsim / logic / model / examples / ReserializeAndVerifyJSONs.java
1 package net.mograsim.logic.model.examples;
2
3 import java.io.FileWriter;
4 import java.io.IOException;
5 import java.nio.file.Files;
6 import java.nio.file.Path;
7 import java.nio.file.Paths;
8 import java.util.Arrays;
9 import java.util.Collection;
10 import java.util.Comparator;
11 import java.util.HashMap;
12 import java.util.HashSet;
13 import java.util.Map;
14 import java.util.Map.Entry;
15 import java.util.Scanner;
16 import java.util.Set;
17 import java.util.TreeMap;
18 import java.util.stream.Collectors;
19 import java.util.stream.Stream;
20
21 import net.haspamelodica.swt.helper.swtobjectwrappers.Point;
22 import net.mograsim.logic.model.am2900.Am2900Loader;
23 import net.mograsim.logic.model.model.LogicModelModifiable;
24 import net.mograsim.logic.model.model.components.ModelComponent;
25 import net.mograsim.logic.model.model.components.atomic.ModelTextComponent;
26 import net.mograsim.logic.model.model.components.submodels.SubmodelComponent;
27 import net.mograsim.logic.model.model.wires.ModelWire;
28 import net.mograsim.logic.model.model.wires.ModelWireCrossPoint;
29 import net.mograsim.logic.model.model.wires.MovablePin;
30 import net.mograsim.logic.model.model.wires.Pin;
31 import net.mograsim.logic.model.model.wires.PinUsage;
32 import net.mograsim.logic.model.serializing.DeserializedSubmodelComponent;
33 import net.mograsim.logic.model.serializing.IdentifyParams;
34 import net.mograsim.logic.model.serializing.LogicModelParams.ComponentParams;
35 import net.mograsim.logic.model.serializing.LogicModelParams.WireParams;
36 import net.mograsim.logic.model.serializing.SubmodelComponentParams;
37 import net.mograsim.logic.model.serializing.SubmodelComponentSerializer;
38 import net.mograsim.logic.model.snippets.highlevelstatehandlers.standard.StandardHighLevelStateHandler.StandardHighLevelStateHandlerParams;
39 import net.mograsim.logic.model.snippets.highlevelstatehandlers.standard.atomic.AtomicHighLevelStateHandler.AtomicHighLevelStateHandlerParams;
40 import net.mograsim.logic.model.snippets.highlevelstatehandlers.standard.atomic.DelegatingAtomicHighLevelStateHandler.DelegatingAtomicHighLevelStateHandlerParams;
41 import net.mograsim.logic.model.snippets.highlevelstatehandlers.standard.atomic.WireForcingAtomicHighLevelStateHandler.WireForcingAtomicHighLevelStateHandlerParams;
42 import net.mograsim.logic.model.snippets.highlevelstatehandlers.standard.subcomponent.DelegatingSubcomponentHighLevelStateHandler.DelegatingSubcomponentHighLevelStateHandlerParams;
43 import net.mograsim.logic.model.snippets.highlevelstatehandlers.standard.subcomponent.SubcomponentHighLevelStateHandler.SubcomponentHighLevelStateHandlerParams;
44 import net.mograsim.logic.model.util.JsonHandler;
45
46 public class ReserializeAndVerifyJSONs
47 {
48         public static double GRIDSIZE = 2.5;
49         public static boolean changePinUsages = false;
50         public static boolean changeComponentNames = true;
51         public static boolean forceDefaultComponentNames = true;
52         public static boolean changeWireNames = true;
53         public static boolean forceDefaultWireNames = true;
54         public static boolean snapWCPs = true;
55         public static boolean warnNonSnappedPoints = true;
56         public static boolean warnNonVertHorizLines = true;
57         public static boolean warnRedundantWires = true;
58
59         public static void main(String[] args) throws IOException
60         {
61                 Am2900Loader.setup();
62                 try (Scanner sysin = new Scanner(System.in))
63                 {
64                         System.out.print("Directory to search for JSONs in / JSON file to reserialize >");
65                         Path root = Paths.get(sysin.nextLine());
66                         if (!Files.exists(root))
67                                 throw new IllegalArgumentException("Path doesn't exist");
68                         if (Files.isRegularFile(root))
69                                 reserializeJSON(root, sysin);
70                         else
71                         {
72                                 System.out.print("Recursive? >");
73                                 boolean recursive = Boolean.valueOf(sysin.nextLine());
74                                 try (Stream<Path> jsons = recursive ? Files.walk(root) : Files.list(root))
75                                 {
76                                         jsons.filter(Files::isRegularFile).filter(p -> p.getFileName().toString().endsWith(".json"))
77                                                         .forEach(j -> reserializeJSON(j, sysin));
78                                 }
79                         }
80                 }
81         }
82
83         public static void reserializeJSON(Path componentPath, Scanner sysin)
84         {
85                 try
86                 {
87                         SubmodelComponentParams oldComponentJSON = JsonHandler.readJson(componentPath.toString(), SubmodelComponentParams.class);
88                         DeserializedSubmodelComponent comp = (DeserializedSubmodelComponent) SubmodelComponentSerializer
89                                         .deserialize(new LogicModelModifiable(), oldComponentJSON);
90                         System.out.println("Reserializing " + componentPath);
91                         LogicModelModifiable submodelModifiable = comp.getSubmodelModifiable();
92                         Map<String, String> componentNameRemapping = new HashMap<>();
93                         Map<String, String> wireNameRemapping = new HashMap<>();
94
95                         if (changePinUsages)
96                                 changePinUsages(sysin, comp);
97                         if (changeComponentNames)
98                                 changeComponentNames(sysin, submodelModifiable, componentNameRemapping);
99                         if (changeWireNames)
100                                 changeWireNames(sysin, submodelModifiable, wireNameRemapping);
101                         if (snapWCPs)
102                                 snapWCPs(submodelModifiable);
103                         if (warnNonSnappedPoints)
104                                 warnNonSnappedPoints(comp, submodelModifiable);
105                         if (warnNonVertHorizLines)
106                                 warnNonVertHorizLines(submodelModifiable);
107                         if (warnRedundantWires)
108                                 warnRedundantWires(submodelModifiable);
109
110                         SubmodelComponentParams newComponentJSON = SubmodelComponentSerializer.serialize(comp);
111
112                         if (changeComponentNames)
113                                 changeComponentNames_AfterSerialization(newComponentJSON, componentNameRemapping);
114                         if (changeWireNames)
115                                 changeWireNames_AfterSerialization(newComponentJSON, wireNameRemapping);
116                         sortAllJSONArrays(newComponentJSON);
117
118                         try (FileWriter writer = new FileWriter(componentPath.toString()))
119                         {
120                                 String json = JsonHandler.toJson(newComponentJSON);
121                                 json = json.replace("\u00b5", "\\u00b5");
122                                 writer.write(json);
123                         }
124                 }
125                 catch (Exception e)
126                 {
127                         System.err.println("An error occurred visiting " + componentPath + ":");
128                         e.printStackTrace();
129                 }
130         }
131
132         private static void warnRedundantWires(LogicModelModifiable submodelModifiable)
133         {
134                 Map<Pin, Set<Pin>> connectedPinGroups = new HashMap<>();
135                 submodelModifiable.getComponentsByName().values().stream().map(ModelComponent::getPins).map(Map::values).flatMap(Collection::stream)
136                                 .forEach(p -> connectedPinGroups.put(p, new HashSet<>(Arrays.asList(p))));
137                 submodelModifiable.getWiresByName().values().forEach(w ->
138                 {
139                         Pin pin1 = w.getPin1();
140                         Pin pin2 = w.getPin2();
141                         Set<Pin> pin1Group = connectedPinGroups.get(pin1);
142                         Set<Pin> pin2Group = connectedPinGroups.get(pin2);
143                         if (pin1Group == pin2Group)
144                                 System.out.println("  Wire " + w.name + " connecting " + pin1 + " and " + pin2 + " is redundant");
145                         else
146                         {
147                                 pin1Group.addAll(pin2Group);
148                                 pin2Group.forEach(p -> connectedPinGroups.put(p, pin1Group));
149                         }
150                 });
151         }
152
153         private static void changePinUsages(Scanner sysin, DeserializedSubmodelComponent comp)
154         {
155                 comp.getSupermodelPins().entrySet().stream().sorted(Comparator.comparing(Entry::getKey)).map(Entry::getValue).forEach(pin ->
156                 {
157                         PinUsage usage = null;
158                         while (usage == null)
159                                 try
160                                 {
161                                         System.out.print("  Usage for interface pin " + pin.name + " (empty: " + pin.usage + ") >");
162                                         String usageStr = sysin.nextLine().toUpperCase();
163                                         usage = usageStr.equals("") ? pin.usage
164                                                         : usageStr.equals("I") ? PinUsage.INPUT
165                                                                         : usageStr.equals("O") ? PinUsage.OUTPUT
166                                                                                         : usageStr.equals("T") ? PinUsage.TRISTATE : PinUsage.valueOf(usageStr);
167                                 }
168                                 catch (@SuppressWarnings("unused") IllegalArgumentException e)
169                                 {
170                                         System.err.println("  Illegal usage");
171                                 }
172                         setInterfacePinUsage(comp, pin, usage);
173                 });
174         }
175
176         @SuppressWarnings("unused") // TextComponent
177         private static void changeComponentNames(Scanner sysin, LogicModelModifiable submodelModifiable,
178                         Map<String, String> componentNameRemapping)
179         {
180                 componentNameRemapping.put(SubmodelComponent.SUBMODEL_INTERFACE_NAME, SubmodelComponent.SUBMODEL_INTERFACE_NAME);
181                 LogicModelModifiable tempModel = new LogicModelModifiable();
182                 IdentifyParams iP = new IdentifyParams();
183                 submodelModifiable.getComponentsByName().entrySet().stream()
184                                 .filter(e -> !e.getKey().equals(SubmodelComponent.SUBMODEL_INTERFACE_NAME))
185                                 .sorted(Comparator.comparing(Entry::getKey, ReserializeAndVerifyJSONs::compareStringsWithIntegers)).forEach(e ->
186                                 {
187                                         String oldName = e.getKey();
188                                         ModelComponent subcomp = e.getValue();
189                                         String defaultName = tempModel.getDefaultComponentName(subcomp);
190                                         String newName = forceDefaultComponentNames ? defaultName : null;
191                                         while (newName == null)
192                                         {
193                                                 System.out.print("  New name for component " + oldName + " of type " + subcomp.getIDForSerializing(iP) + " (empty: "
194                                                                 + defaultName + ") >");
195                                                 newName = sysin.nextLine();
196                                                 if (newName.equals(""))
197                                                         newName = defaultName;
198                                                 if (tempModel.getComponentsByName().containsKey(newName))
199                                                 {
200                                                         System.err.println("  There already is a component with that name");
201                                                         newName = null;
202                                                 }
203                                         }
204                                         componentNameRemapping.put(oldName, newName);
205                                         new ModelTextComponent(tempModel, "", newName);
206                                 });
207         }
208
209         private static void changeComponentNames_AfterSerialization(SubmodelComponentParams newComponentJSON,
210                         Map<String, String> componentNameRemapping)
211         {
212                 for (ComponentParams cParams : newComponentJSON.submodel.components)
213                         cParams.name = componentNameRemapping.get(cParams.name);
214                 for (WireParams wParams : newComponentJSON.submodel.wires)
215                 {
216                         wParams.pin1.compName = componentNameRemapping.get(wParams.pin1.compName);
217                         wParams.pin2.compName = componentNameRemapping.get(wParams.pin2.compName);
218                 }
219                 if ("standard".equals(newComponentJSON.highLevelStateHandlerSnippetID))
220                 {
221                         StandardHighLevelStateHandlerParams hlshParams = JsonHandler.fromJsonTree(newComponentJSON.highLevelStateHandlerParams,
222                                         StandardHighLevelStateHandlerParams.class);
223                         for (AtomicHighLevelStateHandlerParams ahlshParams : hlshParams.atomicHighLevelStates.values())
224                                 if ("delegating".equals(ahlshParams.id))
225                                 {
226                                         DelegatingAtomicHighLevelStateHandlerParams dhlshParams = JsonHandler.fromJsonTree(ahlshParams.params,
227                                                         DelegatingAtomicHighLevelStateHandlerParams.class);
228                                         dhlshParams.delegateTarget = componentNameRemapping.get(dhlshParams.delegateTarget);
229                                         ahlshParams.params = JsonHandler.toJsonTree(dhlshParams);
230                                 }
231                         for (SubcomponentHighLevelStateHandlerParams shlshParams : hlshParams.subcomponentHighLevelStates.values())
232                                 if ("delegating".equals(shlshParams.id))
233                                 {
234                                         DelegatingSubcomponentHighLevelStateHandlerParams dhlshParams = JsonHandler.fromJsonTree(shlshParams.params,
235                                                         DelegatingSubcomponentHighLevelStateHandlerParams.class);
236                                         dhlshParams.delegateTarget = componentNameRemapping.get(dhlshParams.delegateTarget);
237                                         shlshParams.params = JsonHandler.toJsonTree(dhlshParams);
238                                 }
239                         newComponentJSON.highLevelStateHandlerParams = JsonHandler.toJsonTree(hlshParams);
240                 }
241         }
242
243         @SuppressWarnings("unused") // Wire
244         private static void changeWireNames(Scanner sysin, LogicModelModifiable submodelModifiable, Map<String, String> wireNameRemapping)
245         {
246                 LogicModelModifiable tempModel = new LogicModelModifiable();
247                 Pin p = new ModelWireCrossPoint(tempModel, 1).getPin();
248                 IdentifyParams iP = new IdentifyParams();
249                 submodelModifiable.getWiresByName().entrySet().stream()
250                                 .sorted(Comparator.comparing(Entry::getKey, ReserializeAndVerifyJSONs::compareStringsWithIntegers)).forEach(e ->
251                                 {
252                                         String oldName = e.getKey();
253                                         String defaultName = tempModel.getDefaultWireName();
254                                         String newName = forceDefaultWireNames ? defaultName : null;
255                                         while (newName == null)
256                                         {
257                                                 System.out.print("  New name for wire " + oldName + " (empty: " + defaultName + ") >");
258                                                 newName = sysin.nextLine();
259                                                 if (newName.equals(""))
260                                                         newName = defaultName;
261                                                 if (tempModel.getComponentsByName().containsKey(newName))
262                                                 {
263                                                         System.err.println("  There already is a component with that name");
264                                                         newName = null;
265                                                 }
266                                         }
267                                         wireNameRemapping.put(oldName, newName);
268                                         new ModelWire(tempModel, newName, p, p);
269                                 });
270         }
271
272         private static void changeWireNames_AfterSerialization(SubmodelComponentParams newComponentJSON, Map<String, String> wireNameRemapping)
273         {
274                 for (WireParams wParams : newComponentJSON.submodel.wires)
275                         wParams.name = wireNameRemapping.get(wParams.name);
276                 if ("standard".equals(newComponentJSON.highLevelStateHandlerSnippetID))
277                 {
278                         StandardHighLevelStateHandlerParams hlshParams = JsonHandler.fromJsonTree(newComponentJSON.highLevelStateHandlerParams,
279                                         StandardHighLevelStateHandlerParams.class);
280                         for (AtomicHighLevelStateHandlerParams ahlshParams : hlshParams.atomicHighLevelStates.values())
281                                 if ("wireForcing".equals(ahlshParams.id))
282                                 {
283                                         WireForcingAtomicHighLevelStateHandlerParams whlshParams = JsonHandler.fromJsonTree(ahlshParams.params,
284                                                         WireForcingAtomicHighLevelStateHandlerParams.class);
285                                         whlshParams.wiresToForce = whlshParams.wiresToForce.stream().map(wireNameRemapping::get).collect(Collectors.toList());
286                                         whlshParams.wiresToForceInverted = whlshParams.wiresToForceInverted.stream().map(wireNameRemapping::get)
287                                                         .collect(Collectors.toList());
288                                         ahlshParams.params = JsonHandler.toJsonTree(whlshParams);
289                                 }
290                         newComponentJSON.highLevelStateHandlerParams = JsonHandler.toJsonTree(hlshParams);
291                 }
292         }
293
294         private static void snapWCPs(LogicModelModifiable submodelModifiable)
295         {
296                 submodelModifiable.getComponentsByName().values().stream().filter(c -> c instanceof ModelWireCrossPoint).forEach(c ->
297                 {
298                         double x = c.getPosX();
299                         double y = c.getPosY();
300                         double newX = x % GRIDSIZE == 0 ? x - 1 : x;
301                         double newY = y % GRIDSIZE == 0 ? y - 1 : y;
302                         if (x != newX || y != newY)
303                         {
304                                 c.moveTo(newX, newY);
305                                 System.out.println("  Snapping WCP " + c.getName());
306                         }
307                 });
308         }
309
310         private static void warnNonSnappedPoints(DeserializedSubmodelComponent comp, LogicModelModifiable submodelModifiable)
311         {
312                 if (comp.getWidth() % GRIDSIZE != 0 || comp.getHeight() % GRIDSIZE != 0)
313                         System.out.println("  Size is not snapped to grid: " + comp.getWidth() + "," + comp.getHeight());
314                 submodelModifiable.getComponentsByName().values().forEach(c ->
315                 {
316                         double x = c.getPosX();
317                         double y = c.getPosY();
318                         if (c instanceof ModelWireCrossPoint)
319                         {
320                                 x++;
321                                 y++;
322                         }
323                         if (x % GRIDSIZE != 0 || y % GRIDSIZE != 0)
324                                 System.out.println("  Component " + c.getName() + " (type " + c.getIDForSerializing(new IdentifyParams())
325                                                 + ") is not snapped to grid: " + x + "," + y);
326                 });
327                 submodelModifiable.getWiresByName().values().forEach(w ->
328                 {
329                         Point[] p = w.getPath();
330                         if (p != null)
331                                 for (int i = 0; i < p.length; i++)
332                                         if (p[i].x % GRIDSIZE != 0 || p[i].y % GRIDSIZE != 0)
333                                                 System.out.println("  Wire " + w.name + " path point #" + i + " is not snapped to grid: " + p[i].x + "," + p[i].y);
334                 });
335                 comp.getPins().values().forEach(p ->
336                 {
337                         if (p.getRelX() % GRIDSIZE != 0 || p.getRelY() % GRIDSIZE != 0)
338                                 System.out.println("  Interface point " + p.name + " is not snapped to grid: " + p.getRelX() + "," + p.getRelY());
339                 });
340         }
341
342         private static void warnNonVertHorizLines(LogicModelModifiable submodelModifiable)
343         {
344                 submodelModifiable.getWiresByName().values().forEach(w ->
345                 {
346                         double[] p = w.getEffectivePath();
347                         for (int i = 1; i < p.length / 2; i++)
348                         {
349                                 double x1 = p[2 * i - 2];
350                                 double y1 = p[2 * i - 1];
351                                 double x2 = p[2 * i + 0];
352                                 double y2 = p[2 * i + 1];
353                                 if (x1 != x2 && y1 != y2)
354                                         System.out.println("  Wire " + w.name + " part #" + (i - 1) + " is neither vertical nor horizontal");
355                         }
356                 });
357         }
358
359         private static void sortAllJSONArrays(SubmodelComponentParams newComponentJSON)
360         {
361                 Comparator<String> c = ReserializeAndVerifyJSONs::compareStringsWithIntegers;
362                 Arrays.sort(newComponentJSON.interfacePins, Comparator.comparing(p -> p.name, c));
363                 Arrays.sort(newComponentJSON.submodel.components, Comparator.comparing(p -> p.name, c));
364                 Arrays.sort(newComponentJSON.submodel.wires, Comparator.comparing(p -> p.name, c));
365                 if ("standard".equals(newComponentJSON.highLevelStateHandlerSnippetID))
366                 {
367                         StandardHighLevelStateHandlerParams hlshP = JsonHandler.fromJsonTree(newComponentJSON.highLevelStateHandlerParams,
368                                         StandardHighLevelStateHandlerParams.class);
369                         TreeMap<String, AtomicHighLevelStateHandlerParams> tmp1 = new TreeMap<>(c);
370                         tmp1.putAll(hlshP.atomicHighLevelStates);
371                         hlshP.atomicHighLevelStates = tmp1;
372                         TreeMap<String, SubcomponentHighLevelStateHandlerParams> tmp2 = new TreeMap<>(c);
373                         tmp2.putAll(hlshP.subcomponentHighLevelStates);
374                         hlshP.subcomponentHighLevelStates = tmp2;
375                         newComponentJSON.highLevelStateHandlerParams = JsonHandler.toJsonTree(hlshP);
376                 }
377         }
378
379         private static int compareStringsWithIntegers(String a, String b)
380         {
381                 int aLoc = 0;
382                 int bLoc = 0;
383                 for (;;)
384                 {
385                         if (aLoc == a.length())
386                         {
387                                 if (bLoc == b.length())
388                                         return 0;
389                                 return -1;
390                         }
391                         if (bLoc == b.length())
392                                 return 1;
393                         int aInt = 1, bInt = 1;// 1 so a longer number is always greater (makes a difference for leading zeroes)
394                         boolean aHasNumber = false, bHasNumber = false;
395                         char nextCharA, nextCharB;
396                         for (;;)
397                         {
398                                 nextCharA = a.charAt(aLoc++);
399                                 if (nextCharA < '0' || nextCharA > '9')
400                                         break;
401                                 aHasNumber = true;
402                                 aInt = aInt * 10 + nextCharA - '0';
403                                 if (aLoc == a.length())
404                                         break;
405                         }
406                         for (;;)
407                         {
408                                 nextCharB = b.charAt(bLoc++);
409                                 if (nextCharB < '0' || nextCharB > '9')
410                                         break;
411                                 bHasNumber = true;
412                                 bInt = bInt * 10 + nextCharB - '0';
413                                 if (bLoc == b.length())
414                                         break;
415                         }
416                         if (aHasNumber)
417                         {
418                                 if (!bHasNumber)
419                                         return -1;
420                                 int comp = Integer.compare(aInt, bInt);
421                                 if (comp != 0)
422                                         return comp;
423                         } else
424                         {
425                                 if (bHasNumber)
426                                         return 1;
427                                 int comp = Character.compare(nextCharA, nextCharB);
428                                 if (comp != 0)
429                                         return comp;
430                         }
431                 }
432         }
433
434         private static void setInterfacePinUsage(DeserializedSubmodelComponent comp, Pin interfacePin, PinUsage usage)
435         {
436                 Set<ModelWire> wiresConnectedToPin = comp.submodel.getWiresByName().values().stream()
437                                 .filter(w -> w.getPin1() == interfacePin || w.getPin2() == interfacePin).collect(Collectors.toSet());
438                 LogicModelModifiable submodelModifiable = comp.getSubmodelModifiable();
439                 wiresConnectedToPin.forEach(submodelModifiable::destroyWire);
440                 comp.removeSubmodelInterface(interfacePin.name);
441                 comp.addSubmodelInterface(new MovablePin(submodelModifiable, comp, interfacePin.name, interfacePin.logicWidth, usage,
442                                 interfacePin.getRelX(), interfacePin.getRelY()));
443                 wiresConnectedToPin.forEach(w -> new ModelWire(submodelModifiable, w.getPin1(), w.getPin2()));
444         }
445 }