d543c543ebc2050f044e8cd309e6b07a36f98e1a
[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          * @see #getPinOrNull(String)
172          * 
173          * @author Daniel Kirschten
174          */
175         public Pin getPin(String name)
176         {
177                 Pin pin = getPinOrNull(name);
178                 if (pin == null)
179                         throw new IllegalArgumentException("No pin with the name " + name);
180                 return pin;
181         }
182
183         /**
184          * Returns the pin with the given name of this component, or <code>null</code> if there is no such pin.
185          * 
186          * @see #getPin(String)
187          * 
188          * @author Daniel Kirschten
189          */
190         public Pin getPinOrNull(String name)
191         {
192                 return pinsByName.get(name);
193         }
194
195         // high-level access
196
197         /**
198          * @author Daniel Kirschten
199          */
200         protected void setHighLevelStateHandler(HighLevelStateHandler highLevelStateHandler)
201         {
202                 this.highLevelStateHandler = highLevelStateHandler;
203         }
204
205         public HighLevelStateHandler getHighLevelStateHandler()
206         {
207                 return highLevelStateHandler;
208         }
209
210         /**
211          * Gets the current value of the given high-level state. <br>
212          * See {@link HighLevelStateHandler} for an explanation of high-level state IDs.
213          * 
214          * @see #setHighLevelState(String, Object)
215          * @see HighLevelStateHandler#getHighLevelState(String)
216          * 
217          * @author Daniel Kirschten
218          */
219         public Object getHighLevelState(String stateID)
220         {
221                 return highLevelStateHandler.getHighLevelState(stateID);
222         }
223
224         /**
225          * Sets the given high-level state to the given value. <br>
226          * See {@link HighLevelStateHandler} for an explanation of high-level state IDs.
227          * 
228          * @see #getHighLevelState(String)
229          * @see HighLevelStateHandler#setHighLevelState(String, Object)
230          * 
231          * @author Daniel Kirschten
232          */
233         public void setHighLevelState(String stateID, Object newState)
234         {
235                 highLevelStateHandler.setHighLevelState(stateID, newState);
236         }
237
238         // "graphical" operations
239
240         /**
241          * Sets the position of this component and calls componentMovedListeners and redrawListeners.
242          * 
243          * @author Daniel Kirschten
244          */
245         public void moveTo(double x, double y)
246         {
247                 bounds.x = x;
248                 bounds.y = y;
249                 callComponentMovedListeners();
250                 model.requestRedraw();
251         }
252
253         /**
254          * Sets the size of this component and calls redrawListeners.
255          * 
256          * @author Daniel Kirschten
257          */
258         protected void setSize(double width, double height)
259         {
260                 bounds.width = width;
261                 bounds.height = height;
262                 callComponentResizedListener();
263                 model.requestRedraw();
264         }
265
266         /**
267          * Returns the bounds of this component. Is a bit slower than {@link #getPosX()}, {@link #getPosY()}, {@link #getWidth},
268          * {@link #getHeight}, because new objects are created.
269          * 
270          * @author Daniel Kirschten
271          */
272         public final Rectangle getBounds()
273         {
274                 return new Rectangle(bounds.x, bounds.y, bounds.width, bounds.height);
275         }
276
277         /**
278          * Returns the x coordinate of the position of this component. Is a bit faster than {@link #getBounds()} because no objects are created.
279          * 
280          * @author Daniel Kirschten
281          */
282         public double getPosX()
283         {
284                 return bounds.x;
285         }
286
287         /**
288          * Returns the y coordinate of the position of this component. Is a bit faster than {@link #getBounds()} because no objects are created.
289          * 
290          * @author Daniel Kirschten
291          */
292         public double getPosY()
293         {
294                 return bounds.y;
295         }
296
297         /**
298          * Returns the (graphical) width of this component. Is a bit faster than {@link #getBounds()} because no objects are created.
299          * 
300          * @author Daniel Kirschten
301          */
302         public double getWidth()
303         {
304                 return bounds.width;
305         }
306
307         /**
308          * Returns the height of this component. Is a bit faster than {@link #getBounds()} because no objects are created.
309          * 
310          * @author Daniel Kirschten
311          */
312         public double getHeight()
313         {
314                 return bounds.height;
315         }
316
317         /**
318          * Called when this component is clicked. Absolute coordinates of the click are given. Returns true if this component consumed this
319          * click.
320          * 
321          * @author Daniel Kirschten
322          */
323         @SuppressWarnings({ "static-method", "unused" }) // this method is inteded to be overridden
324         public boolean clicked(double x, double y)
325         {
326                 return false;
327         }
328
329         /**
330          * Render this component to the given gc, in absoulute coordinates.
331          * 
332          * @author Daniel Kirschten
333          */
334         public abstract void render(GeneralGC gc, Rectangle visibleRegion);
335
336         // serializing
337
338         @Override
339         public Object getParamsForSerializing(IdentifyParams idParams)
340         {
341                 return null;
342         }
343
344         // listeners
345
346         // @formatter:off
347         public void addComponentMovedListener      (Consumer<? super ModelComponent> listener) {componentMovedListeners  .add   (listener);}
348         public void addComponentResizedListener    (Consumer<? super ModelComponent> listener) {componentResizedListeners.add   (listener);}
349         public void addPinAddedListener            (Consumer<? super Pin         > listener) {pinAddedListeners        .add   (listener);}
350         public void addPinRemovedListener          (Consumer<? super Pin         > listener) {pinRemovedListeners      .add   (listener);}
351
352         public void removeComponentMovedListener   (Consumer<? super ModelComponent> listener) {componentMovedListeners  .remove(listener);}
353         public void removeComponentResizedListener (Consumer<? super ModelComponent> listener) {componentResizedListeners.remove(listener);}
354         public void removePinAddedListener         (Consumer<? super Pin         > listener) {pinAddedListeners        .remove(listener);}
355         public void removePinRemovedListener       (Consumer<? super Pin         > listener) {pinRemovedListeners      .remove(listener);}
356
357         private void callComponentMovedListeners (     ) {componentMovedListeners  .forEach(l -> l.accept(this));}
358         private void callComponentResizedListener(     ) {componentResizedListeners.forEach(l -> l.accept(this));}
359         private void callPinAddedListeners       (Pin p) {pinAddedListeners        .forEach(l -> l.accept(p   ));}
360         private void callPinRemovedListeners     (Pin p) {pinRemovedListeners      .forEach(l -> l.accept(p   ));}
361         // @formatter:on
362 }