11c4334d6f3417fc1a12a1fbfa1e3e9f0448cbbb
[Mograsim.git] / net.mograsim.logic.model / src / net / mograsim / logic / model / model / components / GUIComponent.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 com.google.gson.JsonElement;
11 import com.google.gson.JsonNull;
12
13 import net.haspamelodica.swt.helper.gcs.GeneralGC;
14 import net.haspamelodica.swt.helper.swtobjectwrappers.Rectangle;
15 import net.mograsim.logic.model.model.ViewModelModifiable;
16 import net.mograsim.logic.model.model.wires.Pin;
17 import net.mograsim.logic.model.serializing.IdentifierGetter;
18 import net.mograsim.logic.model.serializing.JSONSerializable;
19 import net.mograsim.logic.model.snippets.HighLevelStateHandler;
20
21 /**
22  * The base class for all GUI components.<br>
23  * A <code>GUIComponent</code> has a reference to the ViewModel it belongs to.<br>
24  * A <code>GUIComponent</code> has a name. This name is unique in the model the <code>GUIComponent</code> belongs to.<br>
25  * A <code>GUIComponent</code> has a position and size. The size can only be modified by subclasses.
26  * 
27  * @author Daniel Kirschten
28  */
29 public abstract class GUIComponent implements JSONSerializable
30 {
31         /**
32          * The model this component is a part of.
33          */
34         protected final ViewModelModifiable model;
35         /**
36          * The name of this component. Is unique for all components in its model.
37          */
38         public final 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 GUIComponent>> componentMovedListeners;
50         private final List<Consumer<? super GUIComponent>> 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 GUIComponent(ViewModelModifiable model, String name)
59         {
60                 this.model = model;
61                 this.name = name == null ? model.getDefaultComponentName(this) : name;
62                 this.bounds = new Rectangle(0, 0, 0, 0);
63                 this.pinsByName = new HashMap<>();
64                 this.pinsUnmodifiable = Collections.unmodifiableMap(pinsByName);
65
66                 this.componentMovedListeners = new ArrayList<>();
67                 this.componentResizedListeners = new ArrayList<>();
68                 this.pinAddedListeners = new ArrayList<>();
69                 this.pinRemovedListeners = new ArrayList<>();
70
71                 // TODO this will crash the high level state debug shell because submodel is not yet set.
72                 // The same problem exists in ViewModelModifiable.getDefaultComponentName; see there
73                 model.componentCreated(this, this::destroyed);
74         }
75
76         /**
77          * Destroys this component. This method is called from {@link ViewModelModifiable#componentDestroyed(GUIComponent) destroyComponent()}
78          * of the model this component is a part of.<br>
79          * When overriding, make sure to also call the original implementation.
80          * 
81          * @author Daniel Kirschten
82          */
83         protected void destroyed()
84         {
85                 pinsByName.values().forEach(p -> pinRemovedListeners.forEach(l -> l.accept(p)));
86         }
87
88         // pins
89
90         /**
91          * Adds the given pin to this component and calls pinAddedListeners and redrawListeners.
92          * 
93          * @throws IllegalArgumentException if the pin doesn't belong to this component
94          * @throws IllegalArgumentException if there already is a pin with the given name
95          * 
96          * @author Daniel Kirschten
97          */
98         protected void addPin(Pin pin)
99         {
100                 if (pin.component != this)
101                         throw new IllegalArgumentException("Can't add a pin not belonging to this component!");
102                 if (pinsByName.containsKey(pin.name))
103                         throw new IllegalArgumentException("Duplicate pin name: " + pin.name);
104                 pinsByName.put(pin.name, pin);
105                 callPinAddedListeners(pin);
106                 model.requestRedraw();
107         }
108
109         /**
110          * Removes the given pin from this component and calls pinAddedListeners and redrawListeners.
111          * 
112          * @throws NullPointerException if there was no pin with this name
113          * 
114          * @author Daniel Kirschten
115          */
116         protected void removePin(String name)
117         {
118                 Pin pin = pinsByName.remove(name);
119                 callPinRemovedListeners(pin);
120                 model.requestRedraw();
121         }
122
123         /**
124          * Returns a collection of pins of this component.
125          * 
126          * @author Daniel Kirschten
127          */
128         public Map<String, Pin> getPins()
129         {
130                 return pinsUnmodifiable;
131         }
132
133         /**
134          * Returns the pin with the given name of this component.
135          * 
136          * @throws IllegalArgumentException if there is no pin with the given name
137          * 
138          * @author Daniel Kirschten
139          */
140         public Pin getPin(String name)
141         {
142                 Pin pin = pinsByName.get(name);
143                 if (pin == null)
144                         throw new IllegalArgumentException("No pin with the name " + name);
145                 return pin;
146         }
147
148         // high-level access
149
150         /**
151          * @author Daniel Kirschten
152          */
153         protected void setHighLevelStateHandler(HighLevelStateHandler highLevelStateHandler)
154         {
155                 this.highLevelStateHandler = highLevelStateHandler;
156         }
157
158         public HighLevelStateHandler getHighLevelStateHandler()
159         {
160                 return highLevelStateHandler;
161         }
162
163         /**
164          * Gets the current value of the given high-level state. <br>
165          * See {@link HighLevelStateHandler} for an explanation of high-level state IDs.
166          * 
167          * @see #setHighLevelState(String, Object)
168          * @see HighLevelStateHandler#getHighLevelState(String)
169          * 
170          * @author Daniel Kirschten
171          */
172         public Object getHighLevelState(String stateID)
173         {
174                 return highLevelStateHandler.getHighLevelState(stateID);
175         }
176
177         /**
178          * Sets the given high-level state to the given value. <br>
179          * See {@link HighLevelStateHandler} for an explanation of high-level state IDs.
180          * 
181          * @see #getHighLevelState(String)
182          * @see HighLevelStateHandler#setHighLevelState(String, Object)
183          * 
184          * @author Daniel Kirschten
185          */
186         public void setHighLevelState(String stateID, Object newState)
187         {
188                 highLevelStateHandler.setHighLevelState(stateID, newState);
189         }
190
191         // "graphical" operations
192
193         /**
194          * Sets the position of this component and calls componentMovedListeners and redrawListeners.
195          * 
196          * @author Daniel Kirschten
197          */
198         public void moveTo(double x, double y)
199         {
200                 bounds.x = x;
201                 bounds.y = y;
202                 callComponentMovedListeners();
203                 model.requestRedraw();
204         }
205
206         /**
207          * Sets the size of this component and calls redrawListeners.
208          * 
209          * @author Daniel Kirschten
210          */
211         protected void setSize(double width, double height)
212         {
213                 bounds.width = width;
214                 bounds.height = height;
215                 callComponentResizedListener();
216                 model.requestRedraw();
217         }
218
219         /**
220          * Returns the bounds of this component. Is a bit slower than {@link #getPosX()}, {@link #getPosY()}, {@link #getWidth},
221          * {@link #getHeight}, because new objects are created.
222          * 
223          * @author Daniel Kirschten
224          */
225         public final Rectangle getBounds()
226         {
227                 return new Rectangle(bounds.x, bounds.y, bounds.width, bounds.height);
228         }
229
230         /**
231          * Returns the x coordinate of the position of this component. Is a bit faster than {@link #getBounds()} because no objects are created.
232          * 
233          * @author Daniel Kirschten
234          */
235         public double getPosX()
236         {
237                 return bounds.x;
238         }
239
240         /**
241          * Returns the y coordinate of the position of this component. Is a bit faster than {@link #getBounds()} because no objects are created.
242          * 
243          * @author Daniel Kirschten
244          */
245         public double getPosY()
246         {
247                 return bounds.y;
248         }
249
250         /**
251          * Returns the (graphical) width of this component. Is a bit faster than {@link #getBounds()} because no objects are created.
252          * 
253          * @author Daniel Kirschten
254          */
255         public double getWidth()
256         {
257                 return bounds.width;
258         }
259
260         /**
261          * Returns the height of this component. Is a bit faster than {@link #getBounds()} because no objects are created.
262          * 
263          * @author Daniel Kirschten
264          */
265         public double getHeight()
266         {
267                 return bounds.height;
268         }
269
270         /**
271          * Called when this component is clicked. Absolute coordinates of the click are given. Returns true if this component consumed this
272          * click.
273          * 
274          * @author Daniel Kirschten
275          */
276         @SuppressWarnings({ "static-method", "unused" }) // this method is inteded to be overridden
277         public boolean clicked(double x, double y)
278         {
279                 return false;
280         }
281
282         /**
283          * Render this component to the given gc, in absoulute coordinates.
284          * 
285          * @author Daniel Kirschten
286          */
287         public abstract void render(GeneralGC gc, Rectangle visibleRegion);
288
289         // serializing
290
291         @Override
292         public JsonElement getParamsForSerializing(IdentifierGetter idGetter)
293         {
294                 return JsonNull.INSTANCE;
295         }
296
297         // listeners
298
299         // @formatter:off
300         public void addComponentMovedListener      (Consumer<? super GUIComponent> listener) {componentMovedListeners  .add   (listener);}
301         public void addComponentResizedListener    (Consumer<? super GUIComponent> listener) {componentResizedListeners.add   (listener);}
302         public void addPinAddedListener            (Consumer<? super Pin         > listener) {pinAddedListeners        .add   (listener);}
303         public void addPinRemovedListener          (Consumer<? super Pin         > listener) {pinRemovedListeners      .add   (listener);}
304
305         public void removeComponentMovedListener   (Consumer<? super GUIComponent> listener) {componentMovedListeners  .remove(listener);}
306         public void removeComponentResizedListener (Consumer<? super GUIComponent> listener) {componentResizedListeners.remove(listener);}
307         public void removePinAddedListener         (Consumer<? super Pin         > listener) {pinAddedListeners        .remove(listener);}
308         public void removePinRemovedListener       (Consumer<? super Pin         > listener) {pinRemovedListeners      .remove(listener);}
309
310         private void callComponentMovedListeners (     ) {componentMovedListeners  .forEach(l -> l.accept(this));}
311         private void callComponentResizedListener(     ) {componentResizedListeners.forEach(l -> l.accept(this));}
312         private void callPinAddedListeners       (Pin p) {pinAddedListeners        .forEach(l -> l.accept(p   ));}
313         private void callPinRemovedListeners     (Pin p) {pinRemovedListeners      .forEach(l -> l.accept(p   ));}
314         // @formatter:on
315 }