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;
12 import net.haspamelodica.swt.helper.gcs.GCConfig;
13 import net.haspamelodica.swt.helper.gcs.GeneralGC;
14 import net.haspamelodica.swt.helper.gcs.TranslatedGC;
15 import net.haspamelodica.swt.helper.swtobjectwrappers.Point;
16 import net.haspamelodica.swt.helper.swtobjectwrappers.Rectangle;
17 import net.mograsim.logic.ui.LogicUIRenderer;
18 import net.mograsim.logic.ui.model.ViewModel;
19 import net.mograsim.logic.ui.model.ViewModelModifiable;
20 import net.mograsim.logic.ui.model.components.GUIComponent;
21 import net.mograsim.logic.ui.model.wires.GUIWire;
22 import net.mograsim.logic.ui.model.wires.MovablePin;
23 import net.mograsim.logic.ui.model.wires.Pin;
24 import net.mograsim.logic.ui.serializing.SubmodelComponentParams;
25 import net.mograsim.logic.ui.serializing.SubmodelComponentParams.ComponentCompositionParams;
26 import net.mograsim.logic.ui.serializing.SubmodelComponentParams.InnerPinParams;
27 import net.mograsim.logic.ui.serializing.SubmodelComponentParams.InnerWireParams;
28 import net.mograsim.logic.ui.serializing.SubmodelComponentParams.InterfacePinParams;
29 import net.mograsim.logic.ui.serializing.SubmodelComponentParams.ComponentCompositionParams.InnerComponentParams;
32 * A {@link GUIComponent} consisting of another model. A <code>SubmodelComponent</code> can have so-called "interface pins" connecting the
33 * inner and outer models.
35 public abstract class SubmodelComponent extends GUIComponent
38 * A modifiable view of {@link #submodel}.
40 protected final ViewModelModifiable submodelModifiable;
42 * The model this {@link SubmodelComponent} consists of.
44 public final ViewModel submodel;
46 * The list of all submodel interface pins of this {@link SubmodelComponent} on the submodel side.
48 private final Map<String, MovablePin> submodelPins;
50 * An unmodifiable view of {@link #submodelPins}.
52 private final Map<String, MovablePin> submodelMovablePinsUnmodifiable;
54 * An unmodifiable view of {@link #submodelPins} where pins are not movable.
56 private final Map<String, Pin> submodelUnmovablePinsUnmodifiable;
58 * The list of all submodel interface pins of this {@link SubmodelComponent} on the supermodel side.
60 private final Map<String, MovablePin> supermodelPins;
62 * An unmodifiable view of {@link #supermodelPins}.
64 private final Map<String, MovablePin> supermodelMovablePinsUnmodifiable;
66 * An unmodifiable view of {@link #supermodelPins} where pins are not movable.
68 private final Map<String, Pin> supermodelUnmovablePinsUnmodifiable;
70 * A pseudo-component containing all submodel interface pins on the submodel side.
72 private final SubmodelInterface submodelInterface;
75 * The list of all high level state IDs this component supports without delegating to subcomponents.
77 private final Set<String> highLevelAtomicStates;
79 * A map of high level state subcomponent IDs to the {@link GUIComponent} high level state access requests are delegated to.
81 private final Map<String, GUIComponent> subcomponentsByHighLevelStateSubcomponentID;
84 * The factor by which the submodel is scaled when rendering.
86 private double submodelScale;
88 * If this {@link SubmodelComponent} fills at least this amount of the visible region vertically or horizontally, the submodel starts to
91 private double maxVisibleRegionFillRatioForAlpha0;
93 * If this {@link SubmodelComponent} fills at least this amount of the visible region vertically or horizontally, the submodel is fully
96 private double minVisibleRegionFillRatioForAlpha1;
98 * The renderer used for rendering the submodel.
100 private final LogicUIRenderer renderer;
102 // creation and destruction
104 public SubmodelComponent(ViewModelModifiable model)
107 this.submodelModifiable = new ViewModelModifiable();
108 this.submodel = submodelModifiable;
109 this.submodelPins = new HashMap<>();
110 this.submodelMovablePinsUnmodifiable = Collections.unmodifiableMap(submodelPins);
111 this.submodelUnmovablePinsUnmodifiable = Collections.unmodifiableMap(submodelPins);
112 this.supermodelPins = new HashMap<>();
113 this.supermodelMovablePinsUnmodifiable = Collections.unmodifiableMap(supermodelPins);
114 this.supermodelUnmovablePinsUnmodifiable = Collections.unmodifiableMap(supermodelPins);
115 this.submodelInterface = new SubmodelInterface(submodelModifiable);
117 this.highLevelAtomicStates = new HashSet<>();
118 this.subcomponentsByHighLevelStateSubcomponentID = new HashMap<>();
120 this.submodelScale = 1;
121 this.maxVisibleRegionFillRatioForAlpha0 = 0.4;
122 this.minVisibleRegionFillRatioForAlpha1 = 0.8;
123 this.renderer = new LogicUIRenderer(submodelModifiable);
125 submodelModifiable.addRedrawListener(this::requestRedraw);
131 * Adds a new submodel interface pin.
133 * @param supermodelPin the submodel interface pin on the supermodel side
135 * @return the submodel interface pin on the submodel side
137 * @author Daniel Kirschten
139 protected Pin addSubmodelInterface(MovablePin supermodelPin)
141 super.addPin(supermodelPin);// do this first to be fail-fast if the supermodel does not belong to this component
143 String name = supermodelPin.name;
144 MovablePin submodelPin = new MovablePin(submodelInterface, name, supermodelPin.logicWidth, supermodelPin.getRelX() / submodelScale,
145 supermodelPin.getRelY() / submodelScale);
147 submodelPin.addPinMovedListener(p ->
149 double newRelX = p.getRelX() * submodelScale;
150 double newRelY = p.getRelY() * submodelScale;
151 if (supermodelPin.getRelX() != newRelX || supermodelPin.getRelY() != newRelY)
152 supermodelPin.setRelPos(newRelX, newRelY);
154 supermodelPin.addPinMovedListener(p ->
156 double newRelX = p.getRelX() / submodelScale;
157 double newRelY = p.getRelY() / submodelScale;
158 if (submodelPin.getRelX() != newRelX || submodelPin.getRelY() != newRelY)
159 submodelPin.setRelPos(newRelX, newRelY);
162 submodelInterface.addPin(submodelPin);
164 submodelPins.put(name, submodelPin);
165 supermodelPins.put(name, supermodelPin);
167 // no need to call requestRedraw() because addPin() will request a redraw
172 * Removes a submodel interface pin.
174 * @author Daniel Kirschten
176 protected void removeSubmodelInterface(String name)
178 super.removePin(name);// do this first to be fail-fast if this component doesn't have a pin with the given name
179 Pin submodelPin = submodelPins.remove(name);
180 submodelInterface.removePin(submodelPin.name);
181 supermodelPins.remove(name);
183 // no need to call requestRedraw() because removePin() will request a redraw
187 * Returns a collection of submodel interface pins on the submodel side of this component.
189 * @author Daniel Kirschten
191 public Map<String, Pin> getSubmodelPins()
193 return submodelUnmovablePinsUnmodifiable;
197 * Returns the submodel interface pin with the given name on the submodel side of this component.
199 * @author Daniel Kirschten
201 public Pin getSubmodelPin(String name)
203 return getSubmodelMovablePin(name);
207 * Returns a collection of movable submodel interface pins on the submodel side of this component.
209 * @author Daniel Kirschten
211 protected Map<String, MovablePin> getSubmodelMovablePins()
213 return submodelMovablePinsUnmodifiable;
217 * Returns the movable submodel interface pin with the given name on the submodel side of this component.
219 * @author Daniel Kirschten
221 protected MovablePin getSubmodelMovablePin(String name)
223 return submodelPins.get(name);
227 * Returns a collection of submodel interface pins on the supermodel side of this component.
229 * @author Daniel Kirschten
231 public Map<String, Pin> getSupermodelPins()
233 return supermodelUnmovablePinsUnmodifiable;
237 * Returns the submodel interface pin with the given name on the supermodel side of this component.
239 * @author Daniel Kirschten
241 public Pin getSupermodelPin(String name)
243 return getSupermodelMovablePin(name);
247 * Returns a collection of movable submodel interface pins on the supermodel side of this component.
249 * @author Daniel Kirschten
251 protected Map<String, MovablePin> getSupermodelMovablePins()
253 return supermodelMovablePinsUnmodifiable;
257 * Returns the movable submodel interface pin with the given name on the supermodel side of this component.
259 * @author Daniel Kirschten
261 protected MovablePin getSupermodelMovablePin(String name)
263 return supermodelPins.get(name);
269 * Adds the given subcomponent ID to the set of allowed subcomponent IDs and links the given {@link GUIComponent} as the delegate target
270 * for this subcomponent ID. <br>
271 * Note that this method does not affect whether {@link #setSubcomponentHighLevelState(String, String, Object)
272 * set}/{@link #getSubcomponentHighLevelState(String, String)} will be called. <br>
273 * See {@link GUIComponent#setHighLevelState(String, Object)} for details about subcomponent IDs.
275 * @author Daniel Kirschten
277 protected void addHighLevelStateSubcomponentID(String subcomponentID, GUIComponent subcomponent)
279 checkHighLevelStateIDPart(subcomponentID);
280 subcomponentsByHighLevelStateSubcomponentID.put(subcomponentID, subcomponent);
284 * Removes the given subcomponent ID from the set of allowed subcomponent IDs. <br>
285 * Note that this method does not affect whether {@link #setSubcomponentHighLevelState(String, String, Object)
286 * set}/{@link #getSubcomponentHighLevelState(String, String)} will be called.<br>
287 * See {@link GUIComponent#setHighLevelState(String, Object)} for details about subcomponent IDs.
289 * @author Daniel Kirschten
291 protected void removeHighLevelStateSubcomponentID(String subcomponentID)
293 subcomponentsByHighLevelStateSubcomponentID.remove(subcomponentID);
297 * Adds the given atomic state ID to the set of allowed atomic state IDs. <br>
298 * See {@link GUIComponent#setHighLevelState(String, Object)} for details about atomic state IDs.
300 * @author Daniel Kirschten
302 protected void addAtomicHighLevelStateID(String stateID)
304 checkHighLevelStateIDPart(stateID);
305 highLevelAtomicStates.add(stateID);
309 * Removes the given atomic state ID from the set of allowed atomic state IDs. <br>
310 * See {@link GUIComponent#setHighLevelState(String, Object)} for details about atomic state IDs.
312 * @author Daniel Kirschten
314 protected void removeAtomicHighLevelStateID(String stateID)
316 highLevelAtomicStates.remove(stateID);
320 public final void setHighLevelState(String stateID, Object newState)
322 int indexOfDot = stateID.indexOf('.');
323 if (indexOfDot == -1)
324 if (highLevelAtomicStates.contains(stateID))
325 setAtomicHighLevelState(stateID, newState);
327 super.setHighLevelState(stateID, newState);
329 setSubcomponentHighLevelState(stateID.substring(0, indexOfDot), stateID.substring(indexOfDot + 1), newState);
333 * This method is called in {@link #setHighLevelState(String, Object)} when the state ID is not atomic. The default implementation uses
334 * the information given to {@link #addHighLevelStateSubcomponentID(String, GUIComponent)
335 * add}/{@link #removeHighLevelStateSubcomponentID(String)} to decide which subcomponent to delegate to.<br>
336 * Note that {@link #addHighLevelStateSubcomponentID(String, GUIComponent) add}/{@link #removeHighLevelStateSubcomponentID(String)}
337 * don't affect whether this method will be called.
339 * @author Daniel Kirschten
341 protected void setSubcomponentHighLevelState(String subcomponentID, String subcomponentHighLevelStateID, Object newState)
343 GUIComponent subcomponent = subcomponentsByHighLevelStateSubcomponentID.get(subcomponentID);
344 if (subcomponent != null)
345 subcomponent.setHighLevelState(subcomponentHighLevelStateID, newState);
347 super.setHighLevelState(subcomponentID + "." + subcomponentHighLevelStateID, newState);
351 * This method is called in {@link #setHighLevelState(String, Object)} when the state ID is atomic and in the set of allowed atomic
353 * See {@link GUIComponent#setHighLevelState(String, Object)} for details about atomic state IDs.
355 * @author Daniel Kirschten
357 @SuppressWarnings({ "static-method", "unused" }) // this method is intended to be overridden
358 protected void setAtomicHighLevelState(String stateID, Object newState)
360 throw new IllegalStateException("Unknown high level state ID: " + stateID);
364 public final Object getHighLevelState(String stateID)
366 int indexOfDot = stateID.indexOf('.');
367 if (indexOfDot == -1)
369 if (highLevelAtomicStates.contains(stateID))
370 return getAtomicHighLevelState(stateID);
371 return super.getHighLevelState(stateID);
373 return getSubcomponentHighLevelState(stateID.substring(0, indexOfDot), stateID.substring(indexOfDot + 1));
377 * This method is called in {@link #getHighLevelState(String, Object)} when the state ID is not atomic. The default implementation uses
378 * the information given to {@link #addHighLevelStateSubcomponentID(String, GUIComponent)
379 * add}/{@link #removeHighLevelStateSubcomponentID(String)} to decide which subcomponent to delegate to. <br>
380 * Note that {@link #addHighLevelStateSubcomponentID(String, GUIComponent) add}/{@link #removeHighLevelStateSubcomponentID(String)}
381 * don't affect whether this method will be called.
383 * @author Daniel Kirschten
385 protected Object getSubcomponentHighLevelState(String subcomponentID, String subcomponentHighLevelStateID)
387 GUIComponent subcomponent = subcomponentsByHighLevelStateSubcomponentID.get(subcomponentID);
388 if (subcomponent != null)
389 return subcomponent.getHighLevelState(subcomponentHighLevelStateID);
390 return super.getHighLevelState(subcomponentID + "." + subcomponentHighLevelStateID);
394 * This method is called in {@link SubmodelComponent#getHighLevelState(String)} when the state ID is in the set of allowed atomic state
396 * See {@link GUIComponent#setHighLevelState(String, Object)} for details about atomic state IDs.
398 * @author Daniel Kirschten
400 @SuppressWarnings("static-method") // this method is intended to be overridden
401 protected Object getAtomicHighLevelState(String stateID)
403 throw new IllegalStateException("Unknown high level state ID: " + stateID);
406 private static void checkHighLevelStateIDPart(String stateIDPart)
408 if (stateIDPart.indexOf('.') != -1)
409 throw new IllegalArgumentException("Illegal high level state ID part (contains dot): " + stateIDPart);
413 // "graphical" operations
416 * Sets the factor by which the submodel is scaled when rendering and calls redrawListeners. Note that the submodel interface pins will
417 * stay at their position relative to the supermodel, which means they will move relative to the submodel.
419 * @author Daniel Kirschten
421 protected void setSubmodelScale(double submodelScale)
423 this.submodelScale = submodelScale;
425 for (Entry<String, MovablePin> e : supermodelPins.entrySet())
426 getSubmodelMovablePin(e.getKey()).setRelPos(e.getValue().getRelX() * submodelScale, e.getValue().getRelY() * submodelScale);
428 requestRedraw();// needed if there is no submodel interface pin
432 * Returns the current factor by which the submodel is scaled when rendering.
434 * @author Daniel Kirschten
436 protected double getSubmodelScale()
438 return submodelScale;
442 public void render(GeneralGC gc, Rectangle visibleRegion)
444 GCConfig conf = new GCConfig(gc);
445 TranslatedGC tgc = new TranslatedGC(gc, getPosX(), getPosY(), submodelScale, true);
447 double visibleRegionFillRatio = Math.max(getWidth() / visibleRegion.width, getHeight() / visibleRegion.height);
448 double alphaFactor = map(visibleRegionFillRatio, maxVisibleRegionFillRatioForAlpha0, minVisibleRegionFillRatioForAlpha1, 0, 1);
449 alphaFactor = Math.max(0, Math.min(1, alphaFactor));
450 // we need to take the old alpha into account to support nested submodules better.
451 int oldAlpha = gc.getAlpha();
452 int submodelAlpha = Math.max(0, Math.min(255, (int) (oldAlpha * alphaFactor)));
453 int labelAlpha = Math.max(0, Math.min(255, (int) (oldAlpha * (1 - alphaFactor))));
454 if (submodelAlpha != 0)
456 gc.setAlpha(submodelAlpha);
457 renderer.render(tgc, visibleRegion.translate(getPosX() / submodelScale, getPosY() / submodelScale, 1 / submodelScale));
461 gc.setAlpha(labelAlpha);
462 renderSymbol(gc, visibleRegion);
465 // draw the outline after all other operations to make interface pins look better
466 renderOutline(gc, visibleRegion);
469 // TODO make this a path
471 * Render the outline of this {@link SubmodelComponent}, e.g. the graphical elements that should stay visible if the submodel is drawn.
473 * @author Daniel Kirschten
475 protected abstract void renderOutline(GeneralGC gc, Rectangle visibleRegion);
478 * Render the symbol of this {@link SubmodelComponent}, e.g. the things that should be hidden if the submodel is drawn.
480 * @author Daniel Kirschten
482 protected abstract void renderSymbol(GeneralGC gc, Rectangle visibleRegion);
484 private static double map(double val, double valMin, double valMax, double mapMin, double mapMax)
486 return mapMin + (val - valMin) * (mapMax - mapMin) / (valMax - valMin);
490 public boolean clicked(double x, double y)
492 double scaledX = (x - getPosX()) / submodelScale;
493 double scaledY = (y - getPosY()) / submodelScale;
494 for (GUIComponent component : submodel.getComponents())
495 if (component.getBounds().contains(scaledX, scaledY) && component.clicked(scaledX, scaledY))
503 * @return {@link SubmodelComponentParams}, which describe this {@link SubmodelComponent}.
505 public SubmodelComponentParams calculateParams()
507 SubmodelComponentParams params = new SubmodelComponentParams();
508 params.name = getIdentifier();
509 params.type = SubmodelComponent.class.getSimpleName();
510 params.composition = calculateCompositionParams();
512 params.width = getWidth();
513 params.height = getHeight();
515 InterfacePinParams[] iPins = new InterfacePinParams[getPins().size()];
517 for (Pin p : getPins().values())
519 InterfacePinParams iPinParams = new InterfacePinParams();
520 iPins[i] = iPinParams;
521 iPinParams.location = p.getRelPos();
522 iPinParams.name = p.name;
523 iPinParams.logicWidth = p.logicWidth;
526 params.interfacePins = iPins;
530 protected ComponentCompositionParams calculateCompositionParams()
532 ComponentCompositionParams params = new ComponentCompositionParams();
533 params.innerScale = getSubmodelScale();
535 List<GUIComponent> compList = submodelModifiable.getComponents();
536 Iterator<GUIComponent> componentIt = compList.iterator();
537 componentIt.next(); // Skip inner SubmodelInterface
538 InnerComponentParams[] comps = new InnerComponentParams[compList.size() - 1];
540 while (componentIt.hasNext())
542 GUIComponent component = componentIt.next();
543 InnerComponentParams inner = new InnerComponentParams();
545 inner.params = component.getInstantiationParameters();
546 inner.pos = new Point(component.getPosX(), component.getPosY());
547 inner.name = component.getIdentifier();
550 params.subComps = comps;
552 List<GUIWire> wireList = submodelModifiable.getWires();
553 InnerWireParams wires[] = new InnerWireParams[wireList.size()];
555 for (GUIWire wire : wireList)
557 InnerWireParams inner = new InnerWireParams();
559 InnerPinParams pin1Params = new InnerPinParams(), pin2Params = new InnerPinParams();
561 pin1Params.pinName = wire.getPin1().name;
562 pin1Params.compId = compList.indexOf(wire.getPin1().component);
563 pin2Params.pinName = wire.getPin2().name;
564 pin2Params.compId = compList.indexOf(wire.getPin2().component);
565 inner.pin1 = pin1Params;
566 inner.pin2 = pin2Params;
567 inner.path = wire.getPath();
570 params.innerWires = wires;
574 // operations no longer supported
577 protected void addPin(Pin pin)
579 throw new UnsupportedOperationException("Can't add pins to a SubmodelComponent directly, call addSubmodelInterface instead");
583 protected void removePin(String name)
585 throw new UnsupportedOperationException("Can't remove pins of a SubmodelComponent directly, call removeSubmodelInterface instead");