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