Restructured serializing classes
[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.TreeMap;
9 import java.util.function.Consumer;
10 import java.util.function.Supplier;
11
12 import net.haspamelodica.swt.helper.gcs.GeneralGC;
13 import net.haspamelodica.swt.helper.swtobjectwrappers.Rectangle;
14 import net.mograsim.logic.ui.model.ViewModelModifiable;
15 import net.mograsim.logic.ui.model.wires.Pin;
16 import net.mograsim.logic.ui.serializing.SubmodelComponentParams;
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 Pin>> pinAddedListeners;
42         private final List<Consumer<? super Pin>> pinRemovedListeners;
43         private final List<Runnable> redrawListeners;
44
45         private final Runnable redrawListenerForSubcomponents;
46         // Defines how the GUIComponent is referenced in SubmodelComponentParams
47         protected Supplier<String> identifierDelegate = () -> getClass().getSimpleName();
48
49         // creation and destruction
50
51         public GUIComponent(ViewModelModifiable model)
52         {
53                 this.model = model;
54                 this.bounds = new Rectangle(0, 0, 0, 0);
55                 this.pinsByName = new HashMap<>();
56                 this.pinsUnmodifiable = Collections.unmodifiableMap(pinsByName);
57
58                 this.componentMovedListeners = new ArrayList<>();
59                 this.pinAddedListeners = new ArrayList<>();
60                 this.pinRemovedListeners = new ArrayList<>();
61                 this.redrawListeners = new ArrayList<>();
62
63                 redrawListenerForSubcomponents = this::requestRedraw;
64
65                 model.componentCreated(this);
66         }
67
68         /**
69          * Destroys this component. This method implicitly calls {@link ViewModelModifiable#componentDestroyed(GUIComponent)
70          * componentDestroyed()} for the model this component is a part of.
71          * 
72          * @author Daniel Kirschten
73          */
74         public void destroy()
75         {
76                 pinsByName.values().forEach(p -> pinRemovedListeners.forEach(l -> l.accept(p)));
77                 model.componentDestroyed(this);
78         }
79
80         // pins
81
82         /**
83          * Adds the given pin to this component and calls pinAddedListeners and redrawListeners.
84          * 
85          * @throws IllegalArgumentException if the pin doesn't belong to this component
86          * @throws IllegalArgumentException if there already is a pin with the given name
87          * 
88          * @author Daniel Kirschten
89          */
90         protected void addPin(Pin pin)
91         {
92                 if (pin.component != this)
93                         throw new IllegalArgumentException("Can't add a pin not belonging to this component!");
94                 if (pinsByName.containsKey(pin.name))
95                         throw new IllegalArgumentException("Duplicate pin name: " + pin.name);
96                 pinsByName.put(pin.name, pin);
97                 callPinAddedListeners(pin);
98                 pin.addRedrawListener(redrawListenerForSubcomponents);
99                 requestRedraw();
100         }
101
102         /**
103          * Removes the given pin from this component and calls pinAddedListeners and redrawListeners.
104          * 
105          * @throws NullPointerException if there was no pin with this name
106          * 
107          * @author Daniel Kirschten
108          */
109         protected void removePin(String name)
110         {
111                 Pin pin = pinsByName.remove(name);
112                 callPinRemovedListeners(pin);
113                 pin.removeRedrawListener(redrawListenerForSubcomponents);
114                 requestRedraw();
115         }
116
117         /**
118          * Returns a collection of pins of this component.
119          * 
120          * @author Daniel Kirschten
121          */
122         public Map<String, Pin> getPins()
123         {
124                 return pinsUnmodifiable;
125         }
126
127         /**
128          * Returns the pin with the given name of this component.
129          * 
130          * @throws IllegalArgumentException if there is no pin with the given name
131          * 
132          * @author Daniel Kirschten
133          */
134         public Pin getPin(String name)
135         {
136                 Pin pin = pinsByName.get(name);
137                 if (pin == null)
138                         throw new IllegalArgumentException("No pin with the name " + name);
139                 return pin;
140         }
141
142         // high-level access
143
144         /**
145          * Sets the given high-level state to the given value. <br>
146          * A high level state ID consists of parts separated by dots ('.').<br>
147          * The last part (the part after the last dot) is called "atomic high level state ID". The parts before that part are called
148          * "subcomponent ID"s.<br>
149          * If there is no dot in a high level state ID, the whole high level state ID is called atomic.<br>
150          * Note that subcomponent IDs don't have to correspond to actual subcomponents. For example, a RAM component may supply subcomponent IDs
151          * "c0000", "c0001" ... "cFFFF" without actually having a subcomponent for each cell. It also is allowed for an atomic high level state
152          * ID to be delegated to a subcomponent.
153          * 
154          * @author Daniel Kirschten
155          */
156         @SuppressWarnings({ "static-method", "unused" }) // this method is intended to be overridden
157         public void setHighLevelState(String stateID, Object newState)
158         {
159                 throw new IllegalArgumentException("No high level state with ID " + stateID);
160         }
161
162         /**
163          * Gets the current value of the given high-level state. <br>
164          * See {@link #setHighLevelState(String, Object)} for an explanation of high-level state IDs.
165          * 
166          * @author Daniel Kirschten
167          */
168         @SuppressWarnings("static-method") // this method is intended to be overridden
169         public Object getHighLevelState(String stateID)
170         {
171                 throw new IllegalArgumentException("No high level state with ID " + stateID);
172         }
173
174         // "graphical" operations
175
176         /**
177          * Sets the position of this component and calls componentMovedListeners and redrawListeners.
178          * 
179          * @author Daniel Kirschten
180          */
181         public void moveTo(double x, double y)
182         {
183                 bounds.x = x;
184                 bounds.y = y;
185                 callComponentMovedListeners();
186                 requestRedraw();
187         }
188
189         /**
190          * Sets the size of this component and calls redrawListeners.
191          * 
192          * @author Daniel Kirschten
193          */
194         protected void setSize(double width, double height)
195         {
196                 bounds.width = width;
197                 bounds.height = height;
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         /**
274          * @return an identifier used to reference this GUIComponent inside of {@link SubmodelComponentParams}
275          */
276         public String getIdentifier()
277         {
278                 return identifierDelegate.get();
279         }
280
281         @SuppressWarnings("static-method")
282         public Map<String, Object> getInstantiationParameters()
283         {
284                 return new TreeMap<>();
285         }
286
287         // listeners
288
289         /**
290          * Calls redraw listeners.
291          * 
292          * @author Daniel Kirschten
293          */
294         protected void requestRedraw()
295         {
296                 callRedrawListeners();
297         }
298
299         // @formatter:off
300         public void addComponentMovedListener   (Consumer<? super GUIComponent> listener) {componentMovedListeners.add   (listener);}
301         public void addPinAddedListener         (Consumer<? super Pin         > listener) {pinAddedListeners      .add   (listener);}
302         public void addPinRemovedListener       (Consumer<? super Pin         > listener) {pinRemovedListeners    .add   (listener);}
303         public void addRedrawListener           (Runnable                       listener) {redrawListeners        .add   (listener);}
304
305         public void removeComponentMovedListener(Consumer<? super GUIComponent> listener) {componentMovedListeners .remove(listener);}
306         public void removePinAddedListener      (Consumer<? super Pin         > listener) {pinAddedListeners       .remove(listener);}
307         public void removePinRemovedListener    (Consumer<? super Pin         > listener) {pinRemovedListeners     .remove(listener);}
308         public void removeRedrawListener        (Runnable                       listener) {redrawListeners         .remove(listener);}
309
310         private void callComponentMovedListeners(     ) {componentMovedListeners.forEach(l -> l.accept(this));}
311         private void callPinAddedListeners      (Pin p) {pinAddedListeners      .forEach(l -> l.accept(p   ));}
312         private void callPinRemovedListeners    (Pin p) {pinRemovedListeners    .forEach(l -> l.accept(p   ));}
313         private void callRedrawListeners        (     ) {redrawListeners        .forEach(l -> l.run(       ));}
314         // @formatter:on
315 }