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