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