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