Merge branch 'development' of https://gitlab.lrz.de/lrr-tum/students/eragp-misim...
[Mograsim.git] / net.mograsim.logic.ui / src / net / mograsim / logic / ui / model / components / GUIComponent.java
1 package net.mograsim.logic.ui.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.ui.model.ViewModelModifiable;
16 import net.mograsim.logic.ui.model.wires.Pin;
17
18 /**
19  * The base class for all GUI components.<br>
20  * A <code>GUIComponent</code> has a position and size. The size can only be modified by subclasses.<br>
21  * 
22  * @author Daniel Kirschten
23  */
24 public abstract class GUIComponent
25 {
26         /**
27          * The model this component is a part of.
28          */
29         protected final ViewModelModifiable model;
30         private final Rectangle bounds;
31         /**
32          * The list of all pins of this component by name.
33          */
34         private final Map<String, Pin> pinsByName;
35         /**
36          * An unmodifiable view of {@link #pinsByName}.
37          */
38         protected final Map<String, Pin> pinsUnmodifiable;
39
40         private final List<Consumer<? super GUIComponent>> componentMovedListeners;
41         private final List<Consumer<? super GUIComponent>> componentResizedListeners;
42         private final List<Consumer<? super Pin>> pinAddedListeners;
43         private final List<Consumer<? super Pin>> pinRemovedListeners;
44         private final List<Runnable> redrawListeners;
45
46         private final Runnable redrawListenerForSubcomponents;
47         // creation and destruction
48
49         public GUIComponent(ViewModelModifiable model)
50         {
51                 this.model = model;
52                 this.bounds = new Rectangle(0, 0, 0, 0);
53                 this.pinsByName = new HashMap<>();
54                 this.pinsUnmodifiable = Collections.unmodifiableMap(pinsByName);
55
56                 this.componentMovedListeners = new ArrayList<>();
57                 this.componentResizedListeners = new ArrayList<>();
58                 this.pinAddedListeners = new ArrayList<>();
59                 this.pinRemovedListeners = new ArrayList<>();
60                 this.redrawListeners = new ArrayList<>();
61
62                 redrawListenerForSubcomponents = this::requestRedraw;
63
64                 model.componentCreated(this);
65         }
66
67         /**
68          * Destroys this component. This method implicitly calls {@link ViewModelModifiable#componentDestroyed(GUIComponent)
69          * componentDestroyed()} for the model this component is a part of.
70          * 
71          * @author Daniel Kirschten
72          */
73         public void destroy()
74         {
75                 pinsByName.values().forEach(p -> pinRemovedListeners.forEach(l -> l.accept(p)));
76                 model.componentDestroyed(this);
77         }
78
79         // pins
80
81         /**
82          * Adds the given pin to this component and calls pinAddedListeners and redrawListeners.
83          * 
84          * @throws IllegalArgumentException if the pin doesn't belong to this component
85          * @throws IllegalArgumentException if there already is a pin with the given name
86          * 
87          * @author Daniel Kirschten
88          */
89         protected void addPin(Pin pin)
90         {
91                 if (pin.component != this)
92                         throw new IllegalArgumentException("Can't add a pin not belonging to this component!");
93                 if (pinsByName.containsKey(pin.name))
94                         throw new IllegalArgumentException("Duplicate pin name: " + pin.name);
95                 pinsByName.put(pin.name, pin);
96                 callPinAddedListeners(pin);
97                 pin.addRedrawListener(redrawListenerForSubcomponents);
98                 requestRedraw();
99         }
100
101         /**
102          * Removes the given pin from this component and calls pinAddedListeners and redrawListeners.
103          * 
104          * @throws NullPointerException if there was no pin with this name
105          * 
106          * @author Daniel Kirschten
107          */
108         protected void removePin(String name)
109         {
110                 Pin pin = pinsByName.remove(name);
111                 callPinRemovedListeners(pin);
112                 pin.removeRedrawListener(redrawListenerForSubcomponents);
113                 requestRedraw();
114         }
115
116         /**
117          * Returns a collection of pins of this component.
118          * 
119          * @author Daniel Kirschten
120          */
121         public Map<String, Pin> getPins()
122         {
123                 return pinsUnmodifiable;
124         }
125
126         /**
127          * Returns the pin with the given name of this component.
128          * 
129          * @throws IllegalArgumentException if there is no pin with the given name
130          * 
131          * @author Daniel Kirschten
132          */
133         public Pin getPin(String name)
134         {
135                 Pin pin = pinsByName.get(name);
136                 if (pin == null)
137                         throw new IllegalArgumentException("No pin with the name " + name);
138                 return pin;
139         }
140
141         // high-level access
142
143         /**
144          * Sets the given high-level state to the given value. <br>
145          * A high level state ID consists of parts separated by dots ('.').<br>
146          * The last part (the part after the last dot) is called "atomic high level state ID". The parts before that part are called
147          * "subcomponent ID"s.<br>
148          * If there is no dot in a high level state ID, the whole high level state ID is called atomic.<br>
149          * Note that subcomponent IDs don't have to correspond to actual subcomponents. For example, a RAM component may supply subcomponent IDs
150          * "c0000", "c0001" ... "cFFFF" without actually having a subcomponent for each cell. It also is allowed for an atomic high level state
151          * ID to be delegated to a subcomponent.
152          * 
153          * @author Daniel Kirschten
154          */
155         @SuppressWarnings({ "static-method", "unused" }) // this method is intended to be overridden
156         public void setHighLevelState(String stateID, Object newState)
157         {
158                 throw new IllegalArgumentException("No high level state with ID " + stateID);
159         }
160
161         /**
162          * Gets the current value of the given high-level state. <br>
163          * See {@link #setHighLevelState(String, Object)} for an explanation of high-level state IDs.
164          * 
165          * @author Daniel Kirschten
166          */
167         @SuppressWarnings("static-method") // this method is intended to be overridden
168         public Object getHighLevelState(String stateID)
169         {
170                 throw new IllegalArgumentException("No high level state with ID " + stateID);
171         }
172
173         // "graphical" operations
174
175         /**
176          * Sets the position of this component and calls componentMovedListeners and redrawListeners.
177          * 
178          * @author Daniel Kirschten
179          */
180         public void moveTo(double x, double y)
181         {
182                 bounds.x = x;
183                 bounds.y = y;
184                 callComponentMovedListeners();
185                 requestRedraw();
186         }
187
188         /**
189          * Sets the size of this component and calls redrawListeners.
190          * 
191          * @author Daniel Kirschten
192          */
193         protected void setSize(double width, double height)
194         {
195                 bounds.width = width;
196                 bounds.height = height;
197                 callComponentResizedListener();
198                 requestRedraw();
199         }
200
201         /**
202          * Returns the bounds of this component. Is a bit slower than {@link #getPosX()}, {@link #getPosY()}, {@link #getWidth},
203          * {@link #getHeight}, because new objects are created.
204          * 
205          * @author Daniel Kirschten
206          */
207         public final Rectangle getBounds()
208         {
209                 return new Rectangle(bounds.x, bounds.y, bounds.width, bounds.height);
210         }
211
212         /**
213          * Returns the x coordinate of the position of this component. Is a bit faster than {@link #getBounds()} because no objects are created.
214          * 
215          * @author Daniel Kirschten
216          */
217         public double getPosX()
218         {
219                 return bounds.x;
220         }
221
222         /**
223          * Returns the y coordinate of the position of this component. Is a bit faster than {@link #getBounds()} because no objects are created.
224          * 
225          * @author Daniel Kirschten
226          */
227         public double getPosY()
228         {
229                 return bounds.y;
230         }
231
232         /**
233          * Returns the (graphical) width of this component. Is a bit faster than {@link #getBounds()} because no objects are created.
234          * 
235          * @author Daniel Kirschten
236          */
237         public double getWidth()
238         {
239                 return bounds.width;
240         }
241
242         /**
243          * Returns the height of this component. Is a bit faster than {@link #getBounds()} because no objects are created.
244          * 
245          * @author Daniel Kirschten
246          */
247         public double getHeight()
248         {
249                 return bounds.height;
250         }
251
252         /**
253          * Called when this component is clicked. Absolute coordinates of the click are given. Returns true if this component consumed this
254          * click.
255          * 
256          * @author Daniel Kirschten
257          */
258         @SuppressWarnings({ "static-method", "unused" }) // this method is inteded to be overridden
259         public boolean clicked(double x, double y)
260         {
261                 return false;
262         }
263
264         /**
265          * Render this component to the given gc, in absoulute coordinates.
266          * 
267          * @author Daniel Kirschten
268          */
269         public abstract void render(GeneralGC gc, Rectangle visibleRegion);
270
271         // serializing
272
273         @SuppressWarnings("static-method") // this method is intended to be overridden
274         public JsonElement getParams()
275         {
276                 return JsonNull.INSTANCE;
277         }
278
279         // listeners
280
281         /**
282          * Calls redraw listeners.
283          * 
284          * @author Daniel Kirschten
285          */
286         protected void requestRedraw()
287         {
288                 callRedrawListeners();
289         }
290
291         // @formatter:off
292         public void addComponentMovedListener      (Consumer<? super GUIComponent> listener) {componentMovedListeners  .add   (listener);}
293         public void addComponentResizedListener    (Consumer<? super GUIComponent> listener) {componentResizedListeners.add   (listener);}
294         public void addPinAddedListener            (Consumer<? super Pin         > listener) {pinAddedListeners        .add   (listener);}
295         public void addPinRemovedListener          (Consumer<? super Pin         > listener) {pinRemovedListeners      .add   (listener);}
296         public void addRedrawListener              (Runnable                       listener) {redrawListeners          .add   (listener);}
297
298         public void removeComponentMovedListener   (Consumer<? super GUIComponent> listener) {componentMovedListeners  .remove(listener);}
299         public void removeComponentResizedListener (Consumer<? super GUIComponent> listener) {componentResizedListeners.remove(listener);}
300         public void removePinAddedListener         (Consumer<? super Pin         > listener) {pinAddedListeners        .remove(listener);}
301         public void removePinRemovedListener       (Consumer<? super Pin         > listener) {pinRemovedListeners      .remove(listener);}
302         public void removeRedrawListener           (Runnable                       listener) {redrawListeners          .remove(listener);}
303
304         private void callComponentMovedListeners (     ) {componentMovedListeners  .forEach(l -> l.accept(this));}
305         private void callComponentResizedListener(     ) {componentResizedListeners.forEach(l -> l.accept(this));}
306         private void callPinAddedListeners       (Pin p) {pinAddedListeners        .forEach(l -> l.accept(p   ));}
307         private void callPinRemovedListeners     (Pin p) {pinRemovedListeners      .forEach(l -> l.accept(p   ));}
308         private void callRedrawListeners         (     ) {redrawListeners          .forEach(l -> l.run(       ));}
309         // @formatter:on
310 }