Added a check in addPin()
[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.Collection;
5 import java.util.Collections;
6 import java.util.HashMap;
7 import java.util.List;
8 import java.util.Map;
9 import java.util.TreeMap;
10 import java.util.function.Consumer;
11 import java.util.function.Supplier;
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
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}<code>.</code>{@link Map#values() values()}.
37          */
38         protected final Collection<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 = () -> "class:".concat(getClass().getCanonicalName());
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.unmodifiableCollection(pinsByName.values());
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         protected void addPin(Pin pin)
86         {
87                 if (pin.component != this)
88                         throw new IllegalArgumentException("Can't add a pin not belonging to this component!");
89                 if (pinsByName.containsKey(pin.name))
90                         throw new IllegalArgumentException("Duplicate pin name: " + pin.name);
91                 pinsByName.put(pin.name, pin);
92                 callPinAddedListeners(pin);
93                 pin.addRedrawListener(redrawListenerForSubcomponents);
94                 requestRedraw();
95         }
96
97         /**
98          * Removes the given pin from this component and calls pinAddedListeners and redrawListeners.
99          * 
100          * @throws NullPointerException if there was no pin with this name.
101          */
102         protected void removePin(String name)
103         {
104                 Pin pin = pinsByName.remove(name);
105                 callPinRemovedListeners(pin);
106                 pin.removeRedrawListener(redrawListenerForSubcomponents);
107                 requestRedraw();
108         }
109
110         /**
111          * Returns a collection of pins of this component.
112          * 
113          * @author Daniel Kirschten
114          */
115         public Collection<Pin> getPins()
116         {
117                 return pinsUnmodifiable;
118         }
119
120         /**
121          * Returns the pin with the given name of this component.
122          * 
123          * @throws IllegalArgumentException if there is no pin with the given name
124          * 
125          * @author Daniel Kirschten
126          */
127         public Pin getPin(String name)
128         {
129                 Pin pin = pinsByName.get(name);
130                 if (pin == null)
131                         throw new IllegalArgumentException("No pin with the name " + name);
132                 return pin;
133         }
134
135         // "graphical" operations
136
137         /**
138          * Sets the position of this component and calls componentMovedListeners and redrawListeners.
139          * 
140          * @author Daniel Kirschten
141          */
142         public void moveTo(double x, double y)
143         {
144                 bounds.x = x;
145                 bounds.y = y;
146                 callComponentMovedListeners();
147                 requestRedraw();
148         }
149
150         /**
151          * Sets the size of this component and calls redrawListeners.
152          * 
153          * @author Daniel Kirschten
154          */
155         protected void setSize(double width, double height)
156         {
157                 bounds.width = width;
158                 bounds.height = height;
159                 requestRedraw();
160         }
161
162         /**
163          * Returns the bounds of this component. Is a bit slower than {@link #getPosX()}, {@link #getPosY()}, {@link #getWidth},
164          * {@link #getHeight}, because new objects are created.
165          * 
166          * @author Daniel Kirschten
167          */
168         public Rectangle getBounds()
169         {
170                 return new Rectangle(bounds.x, bounds.y, bounds.width, bounds.height);
171         }
172
173         /**
174          * Returns the x coordinate of the position of this component. Is a bit faster than {@link #getBounds()} because no objects are created.
175          * 
176          * @author Daniel Kirschten
177          */
178         public double getPosX()
179         {
180                 return bounds.x;
181         }
182
183         /**
184          * Returns the y coordinate of the position of this component. Is a bit faster than {@link #getBounds()} because no objects are created.
185          * 
186          * @author Daniel Kirschten
187          */
188         public double getPosY()
189         {
190                 return bounds.y;
191         }
192
193         /**
194          * Returns the (graphical) width of this component. Is a bit faster than {@link #getBounds()} because no objects are created.
195          * 
196          * @author Daniel Kirschten
197          */
198         public double getWidth()
199         {
200                 return bounds.width;
201         }
202
203         /**
204          * Returns the height of this component. Is a bit faster than {@link #getBounds()} because no objects are created.
205          * 
206          * @author Daniel Kirschten
207          */
208         public double getHeight()
209         {
210                 return bounds.height;
211         }
212
213         /**
214          * Called when this component is clicked. Absolute coordinates of the click are given. Returns true if this component consumed this
215          * click.
216          */
217         @SuppressWarnings({ "static-method", "unused" }) // this method is inteded to be overridden
218         public boolean clicked(double x, double y)
219         {
220                 return false;
221         }
222
223         /**
224          * Render this component to the given gc, in absoulute coordinates.
225          * 
226          * @author Daniel Kirschten
227          */
228         public abstract void render(GeneralGC gc, Rectangle visibleRegion);
229
230         // serializing
231
232         /**
233          * @return an identifier used to reference this GUIComponent inside of {@link SubmodelComponentParams}
234          */
235         public String getIdentifier()
236         {
237                 return identifierDelegate.get();
238         }
239
240         @SuppressWarnings("static-method")
241         public Map<String, Object> getInstantiationParameters()
242         {
243                 return new TreeMap<>();
244         }
245
246         // listeners
247
248         /**
249          * Calls redraw listeners.
250          * 
251          * @author Daniel Kirschten
252          */
253         protected void requestRedraw()
254         {
255                 callRedrawListeners();
256         }
257
258         // @formatter:off
259         public void addComponentMovedListener   (Consumer<? super GUIComponent> listener) {componentMovedListeners.add   (listener);}
260         public void addPinAddedListener         (Consumer<? super Pin         > listener) {pinAddedListeners      .add   (listener);}
261         public void addPinRemovedListener       (Consumer<? super Pin         > listener) {pinRemovedListeners    .add   (listener);}
262         public void addRedrawListener           (Runnable                       listener) {redrawListeners        .add   (listener);}
263
264         public void removeComponentMovedListener(Consumer<? super GUIComponent> listener) {componentMovedListeners .remove(listener);}
265         public void removePinAddedListener      (Consumer<? super Pin         > listener) {pinAddedListeners       .remove(listener);}
266         public void removePinRemovedListener    (Consumer<? super Pin         > listener) {pinRemovedListeners     .remove(listener);}
267         public void removeRedrawListener        (Runnable                       listener) {redrawListeners         .remove(listener);}
268
269         private void callComponentMovedListeners(     ) {componentMovedListeners.forEach(l -> l.accept(this));}
270         private void callPinAddedListeners      (Pin p) {pinAddedListeners      .forEach(l -> l.accept(p   ));}
271         private void callPinRemovedListeners    (Pin p) {pinRemovedListeners    .forEach(l -> l.accept(p   ));}
272         private void callRedrawListeners        (     ) {redrawListeners        .forEach(l -> l.run(       ));}
273         // @formatter:on
274 }