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