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