1 package net.mograsim.logic.ui.model.components.submodels;
3 import java.util.Collections;
4 import java.util.HashMap;
5 import java.util.HashSet;
6 import java.util.Iterator;
9 import java.util.Map.Entry;
11 import java.util.function.Function;
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;
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.
36 public abstract class SubmodelComponent extends GUIComponent
39 * A modifiable view of {@link #submodel}.
41 protected final ViewModelModifiable submodelModifiable;
43 * The model this {@link SubmodelComponent} consists of.
45 public final ViewModel submodel;
47 * The list of all submodel interface pins of this {@link SubmodelComponent} on the submodel side.
49 private final Map<String, MovablePin> submodelPins;
51 * An unmodifiable view of {@link #submodelPins}.
53 private final Map<String, MovablePin> submodelMovablePinsUnmodifiable;
55 * An unmodifiable view of {@link #submodelPins} where pins are not movable.
57 private final Map<String, Pin> submodelUnmovablePinsUnmodifiable;
59 * The list of all submodel interface pins of this {@link SubmodelComponent} on the supermodel side.
61 private final Map<String, MovablePin> supermodelPins;
63 * An unmodifiable view of {@link #supermodelPins}.
65 private final Map<String, MovablePin> supermodelMovablePinsUnmodifiable;
67 * An unmodifiable view of {@link #supermodelPins} where pins are not movable.
69 private final Map<String, Pin> supermodelUnmovablePinsUnmodifiable;
71 * A pseudo-component containing all submodel interface pins on the submodel side.
73 private final SubmodelInterface submodelInterface;
76 * The list of all high level state IDs this component supports without delegating to subcomponents.
78 private final Set<String> highLevelAtomicStates;
80 * A map of high level state subcomponent IDs to the {@link GUIComponent} high level state access requests are delegated to.
82 private final Map<String, GUIComponent> subcomponentsByHighLevelStateSubcomponentID;
85 * The factor by which the submodel is scaled when rendering.
87 private double submodelScale;
89 * If this {@link SubmodelComponent} fills at least this amount of the visible region vertically or horizontally, the submodel starts to
92 private double maxVisibleRegionFillRatioForAlpha0;
94 * If this {@link SubmodelComponent} fills at least this amount of the visible region vertically or horizontally, the submodel is fully
97 private double minVisibleRegionFillRatioForAlpha1;
99 * The renderer used for rendering the submodel.
101 private final LogicUIRenderer renderer;
103 // creation and destruction
105 public SubmodelComponent(ViewModelModifiable 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);
118 this.highLevelAtomicStates = new HashSet<>();
119 this.subcomponentsByHighLevelStateSubcomponentID = new HashMap<>();
121 this.submodelScale = 1;
122 this.maxVisibleRegionFillRatioForAlpha0 = 0.4;
123 this.minVisibleRegionFillRatioForAlpha1 = 0.8;
124 this.renderer = new LogicUIRenderer(submodelModifiable);
126 submodelModifiable.addRedrawListener(this::requestRedraw);
132 * Adds a new submodel interface pin.
134 * @param supermodelPin the submodel interface pin on the supermodel side
136 * @return the submodel interface pin on the submodel side
138 * @author Daniel Kirschten
140 protected Pin addSubmodelInterface(MovablePin supermodelPin)
142 super.addPin(supermodelPin);// do this first to be fail-fast if the supermodel does not belong to this component
144 String name = supermodelPin.name;
145 MovablePin submodelPin = new MovablePin(submodelInterface, name, supermodelPin.logicWidth, supermodelPin.getRelX() / submodelScale,
146 supermodelPin.getRelY() / submodelScale);
148 submodelPin.addPinMovedListener(p ->
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);
155 supermodelPin.addPinMovedListener(p ->
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);
163 submodelInterface.addPin(submodelPin);
165 submodelPins.put(name, submodelPin);
166 supermodelPins.put(name, supermodelPin);
168 // no need to call requestRedraw() because addPin() will request a redraw
173 * Removes a submodel interface pin.
175 * @author Daniel Kirschten
177 protected void removeSubmodelInterface(String name)
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);
184 // no need to call requestRedraw() because removePin() will request a redraw
188 * Returns a collection of submodel interface pins on the submodel side of this component.
190 * @author Daniel Kirschten
192 public Map<String, Pin> getSubmodelPins()
194 return submodelUnmovablePinsUnmodifiable;
198 * Returns the submodel interface pin with the given name on the submodel side of this component.
200 * @author Daniel Kirschten
202 public Pin getSubmodelPin(String name)
204 return getSubmodelMovablePin(name);
208 * Returns a collection of movable submodel interface pins on the submodel side of this component.
210 * @author Daniel Kirschten
212 protected Map<String, MovablePin> getSubmodelMovablePins()
214 return submodelMovablePinsUnmodifiable;
218 * Returns the movable submodel interface pin with the given name on the submodel side of this component.
220 * @author Daniel Kirschten
222 protected MovablePin getSubmodelMovablePin(String name)
224 return submodelPins.get(name);
228 * Returns a collection of submodel interface pins on the supermodel side of this component.
230 * @author Daniel Kirschten
232 public Map<String, Pin> getSupermodelPins()
234 return supermodelUnmovablePinsUnmodifiable;
238 * Returns the submodel interface pin with the given name on the supermodel side of this component.
240 * @author Daniel Kirschten
242 public Pin getSupermodelPin(String name)
244 return getSupermodelMovablePin(name);
248 * Returns a collection of movable submodel interface pins on the supermodel side of this component.
250 * @author Daniel Kirschten
252 protected Map<String, MovablePin> getSupermodelMovablePins()
254 return supermodelMovablePinsUnmodifiable;
258 * Returns the movable submodel interface pin with the given name on the supermodel side of this component.
260 * @author Daniel Kirschten
262 protected MovablePin getSupermodelMovablePin(String name)
264 return supermodelPins.get(name);
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.
276 * @author Daniel Kirschten
278 protected void addHighLevelStateSubcomponentID(String subcomponentID, GUIComponent subcomponent)
280 checkHighLevelStateIDPart(subcomponentID);
281 subcomponentsByHighLevelStateSubcomponentID.put(subcomponentID, subcomponent);
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.
290 * @author Daniel Kirschten
292 protected void removeHighLevelStateSubcomponentID(String subcomponentID)
294 subcomponentsByHighLevelStateSubcomponentID.remove(subcomponentID);
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.
301 * @author Daniel Kirschten
303 protected void addAtomicHighLevelStateID(String stateID)
305 checkHighLevelStateIDPart(stateID);
306 highLevelAtomicStates.add(stateID);
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.
313 * @author Daniel Kirschten
315 protected void removeAtomicHighLevelStateID(String stateID)
317 highLevelAtomicStates.remove(stateID);
321 public final void setHighLevelState(String stateID, Object newState)
323 int indexOfDot = stateID.indexOf('.');
324 if (indexOfDot == -1)
325 if (highLevelAtomicStates.contains(stateID))
326 setAtomicHighLevelState(stateID, newState);
328 super.setHighLevelState(stateID, newState);
330 setSubcomponentHighLevelState(stateID.substring(0, indexOfDot), stateID.substring(indexOfDot + 1), newState);
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.
340 * @author Daniel Kirschten
342 protected void setSubcomponentHighLevelState(String subcomponentID, String subcomponentHighLevelStateID, Object newState)
344 GUIComponent subcomponent = subcomponentsByHighLevelStateSubcomponentID.get(subcomponentID);
345 if (subcomponent != null)
346 subcomponent.setHighLevelState(subcomponentHighLevelStateID, newState);
348 super.setHighLevelState(subcomponentID + "." + subcomponentHighLevelStateID, newState);
352 * This method is called in {@link #setHighLevelState(String, Object)} when the state ID is atomic and in the set of allowed atomic
354 * See {@link GUIComponent#setHighLevelState(String, Object)} for details about atomic state IDs.
356 * @author Daniel Kirschten
358 @SuppressWarnings({ "static-method", "unused" }) // this method is intended to be overridden
359 protected void setAtomicHighLevelState(String stateID, Object newState)
361 throw new IllegalStateException("Unknown high level state ID: " + stateID);
365 public final Object getHighLevelState(String stateID)
367 int indexOfDot = stateID.indexOf('.');
368 if (indexOfDot == -1)
370 if (highLevelAtomicStates.contains(stateID))
371 return getAtomicHighLevelState(stateID);
372 return super.getHighLevelState(stateID);
374 return getSubcomponentHighLevelState(stateID.substring(0, indexOfDot), stateID.substring(indexOfDot + 1));
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.
384 * @author Daniel Kirschten
386 protected Object getSubcomponentHighLevelState(String subcomponentID, String subcomponentHighLevelStateID)
388 GUIComponent subcomponent = subcomponentsByHighLevelStateSubcomponentID.get(subcomponentID);
389 if (subcomponent != null)
390 return subcomponent.getHighLevelState(subcomponentHighLevelStateID);
391 return super.getHighLevelState(subcomponentID + "." + subcomponentHighLevelStateID);
395 * This method is called in {@link SubmodelComponent#getHighLevelState(String)} when the state ID is in the set of allowed atomic state
397 * See {@link GUIComponent#setHighLevelState(String, Object)} for details about atomic state IDs.
399 * @author Daniel Kirschten
401 @SuppressWarnings("static-method") // this method is intended to be overridden
402 protected Object getAtomicHighLevelState(String stateID)
404 throw new IllegalStateException("Unknown high level state ID: " + stateID);
407 private static void checkHighLevelStateIDPart(String stateIDPart)
409 if (stateIDPart.indexOf('.') != -1)
410 throw new IllegalArgumentException("Illegal high level state ID part (contains dot): " + stateIDPart);
414 // "graphical" operations
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.
420 * @author Daniel Kirschten
422 protected void setSubmodelScale(double submodelScale)
424 this.submodelScale = submodelScale;
426 for (Entry<String, MovablePin> e : supermodelPins.entrySet())
427 getSubmodelMovablePin(e.getKey()).setRelPos(e.getValue().getRelX() * submodelScale, e.getValue().getRelY() * submodelScale);
429 requestRedraw();// needed if there is no submodel interface pin
433 * Returns the current factor by which the submodel is scaled when rendering.
435 * @author Daniel Kirschten
437 protected double getSubmodelScale()
439 return submodelScale;
443 public void render(GeneralGC gc, Rectangle visibleRegion)
445 GCConfig conf = new GCConfig(gc);
446 TranslatedGC tgc = new TranslatedGC(gc, getPosX(), getPosY(), submodelScale, true);
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)
457 gc.setAlpha(submodelAlpha);
458 renderer.render(tgc, visibleRegion.translate(getPosX() / submodelScale, getPosY() / submodelScale, 1 / submodelScale));
462 gc.setAlpha(labelAlpha);
463 renderSymbol(gc, visibleRegion);
466 // draw the outline after all other operations to make interface pins look better
467 renderOutline(gc, visibleRegion);
470 // TODO make this a path
472 * Render the outline of this {@link SubmodelComponent}, e.g. the graphical elements that should stay visible if the submodel is drawn.
474 * @author Daniel Kirschten
476 protected abstract void renderOutline(GeneralGC gc, Rectangle visibleRegion);
479 * Render the symbol of this {@link SubmodelComponent}, e.g. the things that should be hidden if the submodel is drawn.
481 * @author Daniel Kirschten
483 protected abstract void renderSymbol(GeneralGC gc, Rectangle visibleRegion);
485 private static double map(double val, double valMin, double valMax, double mapMin, double mapMax)
487 return mapMin + (val - valMin) * (mapMax - mapMin) / (valMax - valMin);
491 public boolean clicked(double x, double y)
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))
503 // TODO move the methods below to serializing classes
505 public SubmodelComponentParams calculateParams()
507 return calculateParams(c -> "class:" + c.getClass().getCanonicalName());
511 * @return {@link SubmodelComponentParams}, which describe this {@link SubmodelComponent}.
513 public SubmodelComponentParams calculateParams(Function<GUIComponent, String> getIdentifier)
515 SubmodelComponentParams params = new SubmodelComponentParams();
516 params.submodel = calculateSubmodelParams(getIdentifier);
518 params.width = getWidth();
519 params.height = getHeight();
521 InterfacePinParams[] iPins = new InterfacePinParams[getPins().size()];
523 for (Pin p : getPins().values())
525 InterfacePinParams iPinParams = new InterfacePinParams();
526 iPins[i] = iPinParams;
527 iPinParams.location = p.getRelPos();
528 iPinParams.name = p.name;
529 iPinParams.logicWidth = p.logicWidth;
532 params.interfacePins = iPins;
536 private SubmodelParameters calculateSubmodelParams(Function<GUIComponent, String> getIdentifier)
538 SubmodelParameters params = new SubmodelParameters();
539 params.innerScale = getSubmodelScale();
541 List<GUIComponent> compList = submodel.getComponents();
542 Iterator<GUIComponent> componentIt = compList.iterator();
543 componentIt.next(); // Skip inner SubmodelInterface
544 InnerComponentParams[] comps = new InnerComponentParams[compList.size() - 1];
546 while (componentIt.hasNext())
548 GUIComponent component = componentIt.next();
549 InnerComponentParams inner = new InnerComponentParams();
551 inner.pos = new Point(component.getPosX(), component.getPosY());
552 inner.id = getIdentifier.apply(component);
553 inner.params = component.getParams();
556 params.subComps = comps;
558 List<GUIWire> wireList = submodel.getWires();
559 InnerWireParams wires[] = new InnerWireParams[wireList.size()];
561 for (GUIWire wire : wireList)
563 InnerWireParams inner = new InnerWireParams();
565 InnerPinParams pin1Params = new InnerPinParams(), pin2Params = new InnerPinParams();
567 pin1Params.pinName = wire.getPin1().name;
568 pin1Params.compId = compList.indexOf(wire.getPin1().component);
569 pin2Params.pinName = wire.getPin2().name;
570 pin2Params.compId = compList.indexOf(wire.getPin2().component);
571 inner.pin1 = pin1Params;
572 inner.pin2 = pin2Params;
573 inner.path = wire.getPath();
576 params.innerWires = wires;
580 // operations no longer supported
583 protected void addPin(Pin pin)
585 throw new UnsupportedOperationException("Can't add pins to a SubmodelComponent directly, call addSubmodelInterface instead");
589 protected void removePin(String name)
591 throw new UnsupportedOperationException("Can't remove pins of a SubmodelComponent directly, call removeSubmodelInterface instead");