Merge branch 'development' of https://gitlab.lrz.de/lrr-tum/students/eragp-misim...
[Mograsim.git] / net.mograsim.logic.model / src / net / mograsim / logic / model / model / components / ModelComponent.java
1 package net.mograsim.logic.model.model.components;
2
3 import java.util.ArrayList;
4 import java.util.Collections;
5 import java.util.HashMap;
6 import java.util.List;
7 import java.util.Map;
8 import java.util.function.Consumer;
9
10 import net.haspamelodica.swt.helper.gcs.GeneralGC;
11 import net.haspamelodica.swt.helper.swtobjectwrappers.Rectangle;
12 import net.mograsim.logic.model.model.LogicModelModifiable;
13 import net.mograsim.logic.model.model.wires.Pin;
14 import net.mograsim.logic.model.serializing.IdentifyParams;
15 import net.mograsim.logic.model.serializing.JSONSerializable;
16 import net.mograsim.logic.model.snippets.HighLevelStateHandler;
17
18 /**
19  * The base class for all model components.<br>
20  * A <code>ModelComponent</code> has a reference to the LogicModel it belongs to.<br>
21  * A <code>ModelComponent</code> has a name. This name is unique in the model the <code>ModelComponent</code> belongs to.<br>
22  * A <code>ModelComponent</code> has a position and size. The size can only be modified by subclasses.
23  * 
24  * @author Daniel Kirschten
25  */
26 public abstract class ModelComponent implements JSONSerializable
27 {
28         /**
29          * The model this component is a part of.
30          */
31         protected final LogicModelModifiable model;
32         /**
33          * The name of this component. Is unique for all components in its model.<br>
34          * Does never change, but can't be final since it is set in {@link #init()}.
35          */
36         private String name;
37         private final Rectangle bounds;
38         /**
39          * The list of all pins of this component by name.
40          */
41         private final Map<String, Pin> pinsByName;
42         /**
43          * An unmodifiable view of {@link #pinsByName}.
44          */
45         protected final Map<String, Pin> pinsUnmodifiable;
46
47         private final List<Consumer<? super ModelComponent>> componentMovedListeners;
48         private final List<Consumer<? super ModelComponent>> componentResizedListeners;
49         private final List<Consumer<? super Pin>> pinAddedListeners;
50         private final List<Consumer<? super Pin>> pinRemovedListeners;
51
52         private HighLevelStateHandler highLevelStateHandler;
53
54         // creation and destruction
55
56         public ModelComponent(LogicModelModifiable model, String name)
57         {
58                 this(model, name, true);
59         }
60
61         /**
62          * Creates a new {@link ModelComponent} and, if <code>callInit</code>, initializes the component (See {@link #init()}).<br>
63          * If <code>callInit==false</code>, make sure to call {@link #init()}!
64          * 
65          * @author Daniel Kirschten
66          */
67         protected ModelComponent(LogicModelModifiable model, String name, boolean callInit)
68         {
69                 this.model = model;
70                 this.name = name;
71                 this.bounds = new Rectangle(0, 0, 0, 0);
72                 this.pinsByName = new HashMap<>();
73                 this.pinsUnmodifiable = Collections.unmodifiableMap(pinsByName);
74
75                 this.componentMovedListeners = new ArrayList<>();
76                 this.componentResizedListeners = new ArrayList<>();
77                 this.pinAddedListeners = new ArrayList<>();
78                 this.pinRemovedListeners = new ArrayList<>();
79
80                 if (callInit)
81                         init();
82         }
83
84         /**
85          * Initializes this component. This method should be called exactly once in this component's constructor.<br>
86          * <ul>
87          * <li>If <code>{@link #name}==null</code>, sets {@link #name} to {@link LogicModelModifiable#getDefaultComponentName(ModelComponent)}.
88          * <li>Registers this component in the model.
89          * </ul>
90          */
91         protected void init()
92         {
93                 if (name == null)
94                         name = model.getDefaultComponentName(this);
95                 model.componentCreated(this, this::destroyed);
96         }
97
98         // basic getters
99
100         public String getName()
101         {
102                 return name;
103         }
104
105         /**
106          * Destroys this component. This method is called from {@link LogicModelModifiable#componentDestroyed(ModelComponent)
107          * destroyComponent()} of the model this component is a part of.<br>
108          * When overriding, make sure to also call the original implementation.
109          * 
110          * @author Daniel Kirschten
111          */
112         protected void destroyed()
113         {
114                 pinsByName.values().forEach(this::removePinWithoutRedraw);
115         }
116
117         // pins
118
119         /**
120          * Adds the given pin to this component and calls pinAddedListeners and redrawListeners.
121          * 
122          * @throws IllegalArgumentException if the pin doesn't belong to this component
123          * @throws IllegalArgumentException if there already is a pin with the given name
124          * 
125          * @author Daniel Kirschten
126          */
127         protected void addPin(Pin pin)
128         {
129                 if (pin.component != this)
130                         throw new IllegalArgumentException("Can't add a pin not belonging to this component!");
131                 if (pinsByName.containsKey(pin.name))
132                         throw new IllegalArgumentException("Duplicate pin name: " + pin.name);
133                 pinsByName.put(pin.name, pin);
134                 callPinAddedListeners(pin);
135                 model.requestRedraw();
136         }
137
138         /**
139          * Removes the given pin from this component and calls pinAddedListeners and redrawListeners.
140          * 
141          * @throws NullPointerException if there was no pin with this name
142          * 
143          * @author Daniel Kirschten
144          */
145         protected void removePin(String name)
146         {
147                 removePinWithoutRedraw(pinsByName.remove(name));
148                 model.requestRedraw();
149         }
150
151         private void removePinWithoutRedraw(Pin pin)
152         {
153                 pin.destroyed();
154                 callPinRemovedListeners(pin);
155         }
156
157         /**
158          * Returns a collection of pins of this component.
159          * 
160          * @author Daniel Kirschten
161          */
162         public Map<String, Pin> getPins()
163         {
164                 return pinsUnmodifiable;
165         }
166
167         /**
168          * Returns the pin with the given name of this component.
169          * 
170          * @throws IllegalArgumentException if there is no pin with the given name
171          * 
172          * @author Daniel Kirschten
173          */
174         public Pin getPin(String name)
175         {
176                 Pin pin = pinsByName.get(name);
177                 if (pin == null)
178                         throw new IllegalArgumentException("No pin with the name " + name);
179                 return pin;
180         }
181
182         // high-level access
183
184         /**
185          * @author Daniel Kirschten
186          */
187         protected void setHighLevelStateHandler(HighLevelStateHandler highLevelStateHandler)
188         {
189                 this.highLevelStateHandler = highLevelStateHandler;
190         }
191
192         public HighLevelStateHandler getHighLevelStateHandler()
193         {
194                 return highLevelStateHandler;
195         }
196
197         /**
198          * Gets the current value of the given high-level state. <br>
199          * See {@link HighLevelStateHandler} for an explanation of high-level state IDs.
200          * 
201          * @see #setHighLevelState(String, Object)
202          * @see HighLevelStateHandler#getHighLevelState(String)
203          * 
204          * @author Daniel Kirschten
205          */
206         public Object getHighLevelState(String stateID)
207         {
208                 return highLevelStateHandler.getHighLevelState(stateID);
209         }
210
211         /**
212          * Sets the given high-level state to the given value. <br>
213          * See {@link HighLevelStateHandler} for an explanation of high-level state IDs.
214          * 
215          * @see #getHighLevelState(String)
216          * @see HighLevelStateHandler#setHighLevelState(String, Object)
217          * 
218          * @author Daniel Kirschten
219          */
220         public void setHighLevelState(String stateID, Object newState)
221         {
222                 highLevelStateHandler.setHighLevelState(stateID, newState);
223         }
224
225         // "graphical" operations
226
227         /**
228          * Sets the position of this component and calls componentMovedListeners and redrawListeners.
229          * 
230          * @author Daniel Kirschten
231          */
232         public void moveTo(double x, double y)
233         {
234                 bounds.x = x;
235                 bounds.y = y;
236                 callComponentMovedListeners();
237                 model.requestRedraw();
238         }
239
240         /**
241          * Sets the size of this component and calls redrawListeners.
242          * 
243          * @author Daniel Kirschten
244          */
245         protected void setSize(double width, double height)
246         {
247                 bounds.width = width;
248                 bounds.height = height;
249                 callComponentResizedListener();
250                 model.requestRedraw();
251         }
252
253         /**
254          * Returns the bounds of this component. Is a bit slower than {@link #getPosX()}, {@link #getPosY()}, {@link #getWidth},
255          * {@link #getHeight}, because new objects are created.
256          * 
257          * @author Daniel Kirschten
258          */
259         public final Rectangle getBounds()
260         {
261                 return new Rectangle(bounds.x, bounds.y, bounds.width, bounds.height);
262         }
263
264         /**
265          * Returns the x coordinate of the position of this component. Is a bit faster than {@link #getBounds()} because no objects are created.
266          * 
267          * @author Daniel Kirschten
268          */
269         public double getPosX()
270         {
271                 return bounds.x;
272         }
273
274         /**
275          * Returns the y coordinate of the position of this component. Is a bit faster than {@link #getBounds()} because no objects are created.
276          * 
277          * @author Daniel Kirschten
278          */
279         public double getPosY()
280         {
281                 return bounds.y;
282         }
283
284         /**
285          * Returns the (graphical) width of this component. Is a bit faster than {@link #getBounds()} because no objects are created.
286          * 
287          * @author Daniel Kirschten
288          */
289         public double getWidth()
290         {
291                 return bounds.width;
292         }
293
294         /**
295          * Returns the height of this component. Is a bit faster than {@link #getBounds()} because no objects are created.
296          * 
297          * @author Daniel Kirschten
298          */
299         public double getHeight()
300         {
301                 return bounds.height;
302         }
303
304         /**
305          * Called when this component is clicked. Absolute coordinates of the click are given. Returns true if this component consumed this
306          * click.
307          * 
308          * @author Daniel Kirschten
309          */
310         @SuppressWarnings({ "static-method", "unused" }) // this method is inteded to be overridden
311         public boolean clicked(double x, double y)
312         {
313                 return false;
314         }
315
316         /**
317          * Render this component to the given gc, in absoulute coordinates.
318          * 
319          * @author Daniel Kirschten
320          */
321         public abstract void render(GeneralGC gc, Rectangle visibleRegion);
322
323         // serializing
324
325         @Override
326         public Object getParamsForSerializing(IdentifyParams idParams)
327         {
328                 return null;
329         }
330
331         // listeners
332
333         // @formatter:off
334         public void addComponentMovedListener      (Consumer<? super ModelComponent> listener) {componentMovedListeners  .add   (listener);}
335         public void addComponentResizedListener    (Consumer<? super ModelComponent> listener) {componentResizedListeners.add   (listener);}
336         public void addPinAddedListener            (Consumer<? super Pin         > listener) {pinAddedListeners        .add   (listener);}
337         public void addPinRemovedListener          (Consumer<? super Pin         > listener) {pinRemovedListeners      .add   (listener);}
338
339         public void removeComponentMovedListener   (Consumer<? super ModelComponent> listener) {componentMovedListeners  .remove(listener);}
340         public void removeComponentResizedListener (Consumer<? super ModelComponent> listener) {componentResizedListeners.remove(listener);}
341         public void removePinAddedListener         (Consumer<? super Pin         > listener) {pinAddedListeners        .remove(listener);}
342         public void removePinRemovedListener       (Consumer<? super Pin         > listener) {pinRemovedListeners      .remove(listener);}
343
344         private void callComponentMovedListeners (     ) {componentMovedListeners  .forEach(l -> l.accept(this));}
345         private void callComponentResizedListener(     ) {componentResizedListeners.forEach(l -> l.accept(this));}
346         private void callPinAddedListeners       (Pin p) {pinAddedListeners        .forEach(l -> l.accept(p   ));}
347         private void callPinRemovedListeners     (Pin p) {pinRemovedListeners      .forEach(l -> l.accept(p   ));}
348         // @formatter:on
349 }