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