Restructured serializing / deserializing
[Mograsim.git] / net.mograsim.logic.ui / src / net / mograsim / logic / ui / model / components / submodels / SubmodelComponent.java
1 package net.mograsim.logic.ui.model.components.submodels;
2
3 import java.util.Collections;
4 import java.util.HashMap;
5 import java.util.HashSet;
6 import java.util.Iterator;
7 import java.util.List;
8 import java.util.Map;
9 import java.util.Map.Entry;
10 import java.util.Set;
11 import java.util.function.Function;
12
13 import net.haspamelodica.swt.helper.gcs.GCConfig;
14 import net.haspamelodica.swt.helper.gcs.GeneralGC;
15 import net.haspamelodica.swt.helper.gcs.TranslatedGC;
16 import net.haspamelodica.swt.helper.swtobjectwrappers.Point;
17 import net.haspamelodica.swt.helper.swtobjectwrappers.Rectangle;
18 import net.mograsim.logic.ui.LogicUIRenderer;
19 import net.mograsim.logic.ui.model.ViewModel;
20 import net.mograsim.logic.ui.model.ViewModelModifiable;
21 import net.mograsim.logic.ui.model.components.GUIComponent;
22 import net.mograsim.logic.ui.model.wires.GUIWire;
23 import net.mograsim.logic.ui.model.wires.MovablePin;
24 import net.mograsim.logic.ui.model.wires.Pin;
25 import net.mograsim.logic.ui.serializing.SubmodelComponentParams;
26 import net.mograsim.logic.ui.serializing.SubmodelComponentParams.InterfacePinParams;
27 import net.mograsim.logic.ui.serializing.SubmodelComponentParams.SubmodelParameters;
28 import net.mograsim.logic.ui.serializing.SubmodelComponentParams.SubmodelParameters.InnerComponentParams;
29 import net.mograsim.logic.ui.serializing.SubmodelComponentParams.SubmodelParameters.InnerWireParams;
30 import net.mograsim.logic.ui.serializing.SubmodelComponentParams.SubmodelParameters.InnerWireParams.InnerPinParams;
31
32 /**
33  * A {@link GUIComponent} consisting of another model. A <code>SubmodelComponent</code> can have so-called "interface pins" connecting the
34  * inner and outer models.
35  */
36 public abstract class SubmodelComponent extends GUIComponent
37 {
38         /**
39          * A modifiable view of {@link #submodel}.
40          */
41         protected final ViewModelModifiable submodelModifiable;
42         /**
43          * The model this {@link SubmodelComponent} consists of.
44          */
45         public final ViewModel submodel;
46         /**
47          * The list of all submodel interface pins of this {@link SubmodelComponent} on the submodel side.
48          */
49         private final Map<String, MovablePin> submodelPins;
50         /**
51          * An unmodifiable view of {@link #submodelPins}.
52          */
53         private final Map<String, MovablePin> submodelMovablePinsUnmodifiable;
54         /**
55          * An unmodifiable view of {@link #submodelPins} where pins are not movable.
56          */
57         private final Map<String, Pin> submodelUnmovablePinsUnmodifiable;
58         /**
59          * The list of all submodel interface pins of this {@link SubmodelComponent} on the supermodel side.
60          */
61         private final Map<String, MovablePin> supermodelPins;
62         /**
63          * An unmodifiable view of {@link #supermodelPins}.
64          */
65         private final Map<String, MovablePin> supermodelMovablePinsUnmodifiable;
66         /**
67          * An unmodifiable view of {@link #supermodelPins} where pins are not movable.
68          */
69         private final Map<String, Pin> supermodelUnmovablePinsUnmodifiable;
70         /**
71          * A pseudo-component containing all submodel interface pins on the submodel side.
72          */
73         private final SubmodelInterface submodelInterface;
74
75         /**
76          * The list of all high level state IDs this component supports without delegating to subcomponents.
77          */
78         private final Set<String> highLevelAtomicStates;
79         /**
80          * A map of high level state subcomponent IDs to the {@link GUIComponent} high level state access requests are delegated to.
81          */
82         private final Map<String, GUIComponent> subcomponentsByHighLevelStateSubcomponentID;
83
84         /**
85          * The factor by which the submodel is scaled when rendering.
86          */
87         private double submodelScale;
88         /**
89          * If this {@link SubmodelComponent} fills at least this amount of the visible region vertically or horizontally, the submodel starts to
90          * be visible.
91          */
92         private double maxVisibleRegionFillRatioForAlpha0;
93         /**
94          * If this {@link SubmodelComponent} fills at least this amount of the visible region vertically or horizontally, the submodel is fully
95          * visible.
96          */
97         private double minVisibleRegionFillRatioForAlpha1;
98         /**
99          * The renderer used for rendering the submodel.
100          */
101         private final LogicUIRenderer renderer;
102
103         // creation and destruction
104
105         public SubmodelComponent(ViewModelModifiable model)
106         {
107                 super(model);
108                 this.submodelModifiable = new ViewModelModifiable();
109                 this.submodel = submodelModifiable;
110                 this.submodelPins = new HashMap<>();
111                 this.submodelMovablePinsUnmodifiable = Collections.unmodifiableMap(submodelPins);
112                 this.submodelUnmovablePinsUnmodifiable = Collections.unmodifiableMap(submodelPins);
113                 this.supermodelPins = new HashMap<>();
114                 this.supermodelMovablePinsUnmodifiable = Collections.unmodifiableMap(supermodelPins);
115                 this.supermodelUnmovablePinsUnmodifiable = Collections.unmodifiableMap(supermodelPins);
116                 this.submodelInterface = new SubmodelInterface(submodelModifiable);
117
118                 this.highLevelAtomicStates = new HashSet<>();
119                 this.subcomponentsByHighLevelStateSubcomponentID = new HashMap<>();
120
121                 this.submodelScale = 1;
122                 this.maxVisibleRegionFillRatioForAlpha0 = 0.4;
123                 this.minVisibleRegionFillRatioForAlpha1 = 0.8;
124                 this.renderer = new LogicUIRenderer(submodelModifiable);
125
126                 submodelModifiable.addRedrawListener(this::requestRedraw);
127         }
128
129         // pins
130
131         /**
132          * Adds a new submodel interface pin.
133          * 
134          * @param supermodelPin the submodel interface pin on the supermodel side
135          * 
136          * @return the submodel interface pin on the submodel side
137          * 
138          * @author Daniel Kirschten
139          */
140         protected Pin addSubmodelInterface(MovablePin supermodelPin)
141         {
142                 super.addPin(supermodelPin);// do this first to be fail-fast if the supermodel does not belong to this component
143
144                 String name = supermodelPin.name;
145                 MovablePin submodelPin = new MovablePin(submodelInterface, name, supermodelPin.logicWidth, supermodelPin.getRelX() / submodelScale,
146                                 supermodelPin.getRelY() / submodelScale);
147
148                 submodelPin.addPinMovedListener(p ->
149                 {
150                         double newRelX = p.getRelX() * submodelScale;
151                         double newRelY = p.getRelY() * submodelScale;
152                         if (supermodelPin.getRelX() != newRelX || supermodelPin.getRelY() != newRelY)
153                                 supermodelPin.setRelPos(newRelX, newRelY);
154                 });
155                 supermodelPin.addPinMovedListener(p ->
156                 {
157                         double newRelX = p.getRelX() / submodelScale;
158                         double newRelY = p.getRelY() / submodelScale;
159                         if (submodelPin.getRelX() != newRelX || submodelPin.getRelY() != newRelY)
160                                 submodelPin.setRelPos(newRelX, newRelY);
161                 });
162
163                 submodelInterface.addPin(submodelPin);
164
165                 submodelPins.put(name, submodelPin);
166                 supermodelPins.put(name, supermodelPin);
167
168                 // no need to call requestRedraw() because addPin() will request a redraw
169                 return submodelPin;
170         }
171
172         /**
173          * Removes a submodel interface pin.
174          * 
175          * @author Daniel Kirschten
176          */
177         protected void removeSubmodelInterface(String name)
178         {
179                 super.removePin(name);// do this first to be fail-fast if this component doesn't have a pin with the given name
180                 Pin submodelPin = submodelPins.remove(name);
181                 submodelInterface.removePin(submodelPin.name);
182                 supermodelPins.remove(name);
183
184                 // no need to call requestRedraw() because removePin() will request a redraw
185         }
186
187         /**
188          * Returns a collection of submodel interface pins on the submodel side of this component.
189          * 
190          * @author Daniel Kirschten
191          */
192         public Map<String, Pin> getSubmodelPins()
193         {
194                 return submodelUnmovablePinsUnmodifiable;
195         }
196
197         /**
198          * Returns the submodel interface pin with the given name on the submodel side of this component.
199          * 
200          * @author Daniel Kirschten
201          */
202         public Pin getSubmodelPin(String name)
203         {
204                 return getSubmodelMovablePin(name);
205         }
206
207         /**
208          * Returns a collection of movable submodel interface pins on the submodel side of this component.
209          * 
210          * @author Daniel Kirschten
211          */
212         protected Map<String, MovablePin> getSubmodelMovablePins()
213         {
214                 return submodelMovablePinsUnmodifiable;
215         }
216
217         /**
218          * Returns the movable submodel interface pin with the given name on the submodel side of this component.
219          * 
220          * @author Daniel Kirschten
221          */
222         protected MovablePin getSubmodelMovablePin(String name)
223         {
224                 return submodelPins.get(name);
225         }
226
227         /**
228          * Returns a collection of submodel interface pins on the supermodel side of this component.
229          * 
230          * @author Daniel Kirschten
231          */
232         public Map<String, Pin> getSupermodelPins()
233         {
234                 return supermodelUnmovablePinsUnmodifiable;
235         }
236
237         /**
238          * Returns the submodel interface pin with the given name on the supermodel side of this component.
239          * 
240          * @author Daniel Kirschten
241          */
242         public Pin getSupermodelPin(String name)
243         {
244                 return getSupermodelMovablePin(name);
245         }
246
247         /**
248          * Returns a collection of movable submodel interface pins on the supermodel side of this component.
249          * 
250          * @author Daniel Kirschten
251          */
252         protected Map<String, MovablePin> getSupermodelMovablePins()
253         {
254                 return supermodelMovablePinsUnmodifiable;
255         }
256
257         /**
258          * Returns the movable submodel interface pin with the given name on the supermodel side of this component.
259          * 
260          * @author Daniel Kirschten
261          */
262         protected MovablePin getSupermodelMovablePin(String name)
263         {
264                 return supermodelPins.get(name);
265         }
266
267         // high-level access
268
269         /**
270          * Adds the given subcomponent ID to the set of allowed subcomponent IDs and links the given {@link GUIComponent} as the delegate target
271          * for this subcomponent ID. <br>
272          * Note that this method does not affect whether {@link #setSubcomponentHighLevelState(String, String, Object)
273          * set}/{@link #getSubcomponentHighLevelState(String, String)} will be called. <br>
274          * See {@link GUIComponent#setHighLevelState(String, Object)} for details about subcomponent IDs.
275          * 
276          * @author Daniel Kirschten
277          */
278         protected void addHighLevelStateSubcomponentID(String subcomponentID, GUIComponent subcomponent)
279         {
280                 checkHighLevelStateIDPart(subcomponentID);
281                 subcomponentsByHighLevelStateSubcomponentID.put(subcomponentID, subcomponent);
282         }
283
284         /**
285          * Removes the given subcomponent ID from the set of allowed subcomponent IDs. <br>
286          * Note that this method does not affect whether {@link #setSubcomponentHighLevelState(String, String, Object)
287          * set}/{@link #getSubcomponentHighLevelState(String, String)} will be called.<br>
288          * See {@link GUIComponent#setHighLevelState(String, Object)} for details about subcomponent IDs.
289          * 
290          * @author Daniel Kirschten
291          */
292         protected void removeHighLevelStateSubcomponentID(String subcomponentID)
293         {
294                 subcomponentsByHighLevelStateSubcomponentID.remove(subcomponentID);
295         }
296
297         /**
298          * Adds the given atomic state ID to the set of allowed atomic state IDs. <br>
299          * See {@link GUIComponent#setHighLevelState(String, Object)} for details about atomic state IDs.
300          * 
301          * @author Daniel Kirschten
302          */
303         protected void addAtomicHighLevelStateID(String stateID)
304         {
305                 checkHighLevelStateIDPart(stateID);
306                 highLevelAtomicStates.add(stateID);
307         }
308
309         /**
310          * Removes the given atomic state ID from the set of allowed atomic state IDs. <br>
311          * See {@link GUIComponent#setHighLevelState(String, Object)} for details about atomic state IDs.
312          * 
313          * @author Daniel Kirschten
314          */
315         protected void removeAtomicHighLevelStateID(String stateID)
316         {
317                 highLevelAtomicStates.remove(stateID);
318         }
319
320         @Override
321         public final void setHighLevelState(String stateID, Object newState)
322         {
323                 int indexOfDot = stateID.indexOf('.');
324                 if (indexOfDot == -1)
325                         if (highLevelAtomicStates.contains(stateID))
326                                 setAtomicHighLevelState(stateID, newState);
327                         else
328                                 super.setHighLevelState(stateID, newState);
329                 else
330                         setSubcomponentHighLevelState(stateID.substring(0, indexOfDot), stateID.substring(indexOfDot + 1), newState);
331         }
332
333         /**
334          * This method is called in {@link #setHighLevelState(String, Object)} when the state ID is not atomic. The default implementation uses
335          * the information given to {@link #addHighLevelStateSubcomponentID(String, GUIComponent)
336          * add}/{@link #removeHighLevelStateSubcomponentID(String)} to decide which subcomponent to delegate to.<br>
337          * Note that {@link #addHighLevelStateSubcomponentID(String, GUIComponent) add}/{@link #removeHighLevelStateSubcomponentID(String)}
338          * don't affect whether this method will be called.
339          * 
340          * @author Daniel Kirschten
341          */
342         protected void setSubcomponentHighLevelState(String subcomponentID, String subcomponentHighLevelStateID, Object newState)
343         {
344                 GUIComponent subcomponent = subcomponentsByHighLevelStateSubcomponentID.get(subcomponentID);
345                 if (subcomponent != null)
346                         subcomponent.setHighLevelState(subcomponentHighLevelStateID, newState);
347                 else
348                         super.setHighLevelState(subcomponentID + "." + subcomponentHighLevelStateID, newState);
349         }
350
351         /**
352          * This method is called in {@link #setHighLevelState(String, Object)} when the state ID is atomic and in the set of allowed atomic
353          * state IDs. <br>
354          * See {@link GUIComponent#setHighLevelState(String, Object)} for details about atomic state IDs.
355          * 
356          * @author Daniel Kirschten
357          */
358         @SuppressWarnings({ "static-method", "unused" }) // this method is intended to be overridden
359         protected void setAtomicHighLevelState(String stateID, Object newState)
360         {
361                 throw new IllegalStateException("Unknown high level state ID: " + stateID);
362         }
363
364         @Override
365         public final Object getHighLevelState(String stateID)
366         {
367                 int indexOfDot = stateID.indexOf('.');
368                 if (indexOfDot == -1)
369                 {
370                         if (highLevelAtomicStates.contains(stateID))
371                                 return getAtomicHighLevelState(stateID);
372                         return super.getHighLevelState(stateID);
373                 }
374                 return getSubcomponentHighLevelState(stateID.substring(0, indexOfDot), stateID.substring(indexOfDot + 1));
375         }
376
377         /**
378          * This method is called in {@link #getHighLevelState(String, Object)} when the state ID is not atomic. The default implementation uses
379          * the information given to {@link #addHighLevelStateSubcomponentID(String, GUIComponent)
380          * add}/{@link #removeHighLevelStateSubcomponentID(String)} to decide which subcomponent to delegate to. <br>
381          * Note that {@link #addHighLevelStateSubcomponentID(String, GUIComponent) add}/{@link #removeHighLevelStateSubcomponentID(String)}
382          * don't affect whether this method will be called.
383          * 
384          * @author Daniel Kirschten
385          */
386         protected Object getSubcomponentHighLevelState(String subcomponentID, String subcomponentHighLevelStateID)
387         {
388                 GUIComponent subcomponent = subcomponentsByHighLevelStateSubcomponentID.get(subcomponentID);
389                 if (subcomponent != null)
390                         return subcomponent.getHighLevelState(subcomponentHighLevelStateID);
391                 return super.getHighLevelState(subcomponentID + "." + subcomponentHighLevelStateID);
392         }
393
394         /**
395          * This method is called in {@link SubmodelComponent#getHighLevelState(String)} when the state ID is in the set of allowed atomic state
396          * IDs. <br>
397          * See {@link GUIComponent#setHighLevelState(String, Object)} for details about atomic state IDs.
398          * 
399          * @author Daniel Kirschten
400          */
401         @SuppressWarnings("static-method") // this method is intended to be overridden
402         protected Object getAtomicHighLevelState(String stateID)
403         {
404                 throw new IllegalStateException("Unknown high level state ID: " + stateID);
405         }
406
407         private static void checkHighLevelStateIDPart(String stateIDPart)
408         {
409                 if (stateIDPart.indexOf('.') != -1)
410                         throw new IllegalArgumentException("Illegal high level state ID part (contains dot): " + stateIDPart);
411
412         }
413
414         // "graphical" operations
415
416         /**
417          * Sets the factor by which the submodel is scaled when rendering and calls redrawListeners. Note that the submodel interface pins will
418          * stay at their position relative to the supermodel, which means they will move relative to the submodel.
419          * 
420          * @author Daniel Kirschten
421          */
422         protected void setSubmodelScale(double submodelScale)
423         {
424                 this.submodelScale = submodelScale;
425
426                 for (Entry<String, MovablePin> e : supermodelPins.entrySet())
427                         getSubmodelMovablePin(e.getKey()).setRelPos(e.getValue().getRelX() * submodelScale, e.getValue().getRelY() * submodelScale);
428
429                 requestRedraw();// needed if there is no submodel interface pin
430         }
431
432         /**
433          * Returns the current factor by which the submodel is scaled when rendering.
434          * 
435          * @author Daniel Kirschten
436          */
437         protected double getSubmodelScale()
438         {
439                 return submodelScale;
440         }
441
442         @Override
443         public void render(GeneralGC gc, Rectangle visibleRegion)
444         {
445                 GCConfig conf = new GCConfig(gc);
446                 TranslatedGC tgc = new TranslatedGC(gc, getPosX(), getPosY(), submodelScale, true);
447                 conf.reset(tgc);
448                 double visibleRegionFillRatio = Math.max(getWidth() / visibleRegion.width, getHeight() / visibleRegion.height);
449                 double alphaFactor = map(visibleRegionFillRatio, maxVisibleRegionFillRatioForAlpha0, minVisibleRegionFillRatioForAlpha1, 0, 1);
450                 alphaFactor = Math.max(0, Math.min(1, alphaFactor));
451                 // we need to take the old alpha into account to support nested submodules better.
452                 int oldAlpha = gc.getAlpha();
453                 int submodelAlpha = Math.max(0, Math.min(255, (int) (oldAlpha * alphaFactor)));
454                 int labelAlpha = Math.max(0, Math.min(255, (int) (oldAlpha * (1 - alphaFactor))));
455                 if (submodelAlpha != 0)
456                 {
457                         gc.setAlpha(submodelAlpha);
458                         renderer.render(tgc, visibleRegion.translate(getPosX() / submodelScale, getPosY() / submodelScale, 1 / submodelScale));
459                 }
460                 if (labelAlpha != 0)
461                 {
462                         gc.setAlpha(labelAlpha);
463                         renderSymbol(gc, visibleRegion);
464                 }
465                 conf.reset(gc);
466                 // draw the outline after all other operations to make interface pins look better
467                 renderOutline(gc, visibleRegion);
468         }
469
470         // TODO make this a path
471         /**
472          * Render the outline of this {@link SubmodelComponent}, e.g. the graphical elements that should stay visible if the submodel is drawn.
473          * 
474          * @author Daniel Kirschten
475          */
476         protected abstract void renderOutline(GeneralGC gc, Rectangle visibleRegion);
477
478         /**
479          * Render the symbol of this {@link SubmodelComponent}, e.g. the things that should be hidden if the submodel is drawn.
480          * 
481          * @author Daniel Kirschten
482          */
483         protected abstract void renderSymbol(GeneralGC gc, Rectangle visibleRegion);
484
485         private static double map(double val, double valMin, double valMax, double mapMin, double mapMax)
486         {
487                 return mapMin + (val - valMin) * (mapMax - mapMin) / (valMax - valMin);
488         }
489
490         @Override
491         public boolean clicked(double x, double y)
492         {
493                 double scaledX = (x - getPosX()) / submodelScale;
494                 double scaledY = (y - getPosY()) / submodelScale;
495                 for (GUIComponent component : submodel.getComponents())
496                         if (component.getBounds().contains(scaledX, scaledY) && component.clicked(scaledX, scaledY))
497                                 return true;
498                 return false;
499         }
500
501         // serializing; TODO move to serializing classes
502
503         public SubmodelComponentParams calculateParams()
504         {
505                 return calculateParams(c -> "class:" + c.getClass().getCanonicalName());
506         }
507
508         /**
509          * @return {@link SubmodelComponentParams}, which describe this {@link SubmodelComponent}.
510          */
511         public SubmodelComponentParams calculateParams(Function<GUIComponent, String> getIdentifier)
512         {
513                 SubmodelComponentParams params = new SubmodelComponentParams();
514                 params.submodel = calculateSubmodelParams(getIdentifier);
515
516                 params.width = getWidth();
517                 params.height = getHeight();
518
519                 InterfacePinParams[] iPins = new InterfacePinParams[getPins().size()];
520                 int i = 0;
521                 for (Pin p : getPins().values())
522                 {
523                         InterfacePinParams iPinParams = new InterfacePinParams();
524                         iPins[i] = iPinParams;
525                         iPinParams.location = p.getRelPos();
526                         iPinParams.name = p.name;
527                         iPinParams.logicWidth = p.logicWidth;
528                         i++;
529                 }
530                 params.interfacePins = iPins;
531                 return params;
532         }
533
534         private SubmodelParameters calculateSubmodelParams(Function<GUIComponent, String> getIdentifier)
535         {
536                 SubmodelParameters params = new SubmodelParameters();
537                 params.innerScale = getSubmodelScale();
538
539                 List<GUIComponent> compList = submodel.getComponents();
540                 Iterator<GUIComponent> componentIt = compList.iterator();
541                 componentIt.next(); // Skip inner SubmodelInterface
542                 InnerComponentParams[] comps = new InnerComponentParams[compList.size() - 1];
543                 int i = 0;
544                 while (componentIt.hasNext())
545                 {
546                         GUIComponent component = componentIt.next();
547                         InnerComponentParams inner = new InnerComponentParams();
548                         comps[i] = inner;
549                         inner.pos = new Point(component.getPosX(), component.getPosY());
550                         inner.id = getIdentifier.apply(component);
551                         i++;
552                 }
553                 params.subComps = comps;
554
555                 List<GUIWire> wireList = submodel.getWires();
556                 InnerWireParams wires[] = new InnerWireParams[wireList.size()];
557                 i = 0;
558                 for (GUIWire wire : wireList)
559                 {
560                         InnerWireParams inner = new InnerWireParams();
561                         wires[i] = inner;
562                         InnerPinParams pin1Params = new InnerPinParams(), pin2Params = new InnerPinParams();
563
564                         pin1Params.pinName = wire.getPin1().name;
565                         pin1Params.compId = compList.indexOf(wire.getPin1().component);
566                         pin2Params.pinName = wire.getPin2().name;
567                         pin2Params.compId = compList.indexOf(wire.getPin2().component);
568                         inner.pin1 = pin1Params;
569                         inner.pin2 = pin2Params;
570                         inner.path = wire.getPath();
571                         i++;
572                 }
573                 params.innerWires = wires;
574                 return params;
575         }
576
577         // operations no longer supported
578
579         @Override
580         protected void addPin(Pin pin)
581         {
582                 throw new UnsupportedOperationException("Can't add pins to a SubmodelComponent directly, call addSubmodelInterface instead");
583         }
584
585         @Override
586         protected void removePin(String name)
587         {
588                 throw new UnsupportedOperationException("Can't remove pins of a SubmodelComponent directly, call removeSubmodelInterface instead");
589         }
590 }