Common ConnectionPoint interface to simplify many things
[Mograsim.git] / net.mograsim.logic.ui / src / net / mograsim / logic / ui / model / wires / GUIWire.java
1 package net.mograsim.logic.ui.model.wires;
2
3 import java.util.ArrayList;
4 import java.util.Arrays;
5 import java.util.List;
6
7 import org.eclipse.swt.SWT;
8
9 import net.haspamelodica.swt.helper.gcs.GeneralGC;
10 import net.haspamelodica.swt.helper.swtobjectwrappers.Point;
11 import net.haspamelodica.swt.helper.swtobjectwrappers.Rectangle;
12 import net.mograsim.logic.core.LogicObserver;
13 import net.mograsim.logic.core.types.BitVector;
14 import net.mograsim.logic.core.types.BitVectorFormatter;
15 import net.mograsim.logic.core.wires.Wire;
16 import net.mograsim.logic.core.wires.Wire.ReadEnd;
17 import net.mograsim.logic.ui.ColorHelper;
18 import net.mograsim.logic.ui.model.ViewModelModifiable;
19
20 /**
21  * A wire connecting exactly two {@link Pin}s.
22  * 
23  * @author Daniel Kirschten
24  */
25 public class GUIWire
26 {
27         /**
28          * The model this wire is a part of.
29          */
30         private final ViewModelModifiable model;
31         /**
32          * The logical width of this wire. Is equal to the logical with of {@link #pin1} and {@link #pin2}.
33          */
34         public final int logicWidth;
35         /**
36          * The {@link Pin} on one side of this wire, usually the signal source.
37          */
38         private Pin pin1;
39         /**
40          * The {@link Pin} on one side of this wire, usually the signal target.
41          */
42         private Pin pin2;
43         /**
44          * The user-defined path between {@link #pin1} and {@link #pin2}.<br>
45          * Special cases: <code>null</code> means "choose an interpolation as fits", and an empty array means "direct connection without any
46          * interpolation".
47          */
48         private Point[] path;
49         /**
50          * The bounds of this wire, excluding line width (and line joins, if the line join is {@link SWT#JOIN_MITER})
51          */
52         private final Rectangle bounds;
53         /**
54          * The effective path of this wire, including automatic interpolation and the position of both {@link Pin}s. Is never null.
55          */
56         private double[] effectivePath;
57
58         private final List<Runnable> redrawListeners;
59
60         /**
61          * A LogicObserver calling redrawListeners. Used for logic model bindings.
62          */
63         private final LogicObserver logicObs;
64         /**
65          * A ReadEnd of the logic wire this GUI wire currently is bound to.
66          */
67         private ReadEnd end;
68
69         // creation and destruction
70
71         /**
72          * Creates a new {@link GUIWire} with automatic interpolation.
73          * 
74          * @author Daniel Kirschten
75          */
76         public GUIWire(ViewModelModifiable model, ConnectionPoint pin1, ConnectionPoint pin2)
77         {
78                 this(model, pin1, pin2, (Point[]) null);
79         }
80
81         /**
82          * Creates a new {@link GUIWire} without automatic interpolation.
83          * 
84          * @author Daniel Kirschten
85          */
86         public GUIWire(ViewModelModifiable model, ConnectionPoint pin1, ConnectionPoint pin2, Point... path)
87         {
88                 this(model, pin1.getPin(), pin2.getPin(), path);
89         }
90
91         /**
92          * Creates a new {@link GUIWire} without automatic interpolation.
93          * 
94          * @author Daniel Kirschten
95          */
96         GUIWire(ViewModelModifiable model, Pin pin1, Pin pin2, Point... path)
97         {
98                 logicObs = (i) -> callRedrawListeners();
99                 this.model = model;
100                 this.logicWidth = pin1.logicWidth;
101                 if (pin2.logicWidth != pin1.logicWidth)
102                         throw new IllegalArgumentException("Can't connect pins of different logic width");
103
104                 this.pin1 = pin1;
105                 this.pin2 = pin2;
106
107                 this.path = path == null ? null : Arrays.copyOf(path, path.length);
108                 this.bounds = new Rectangle(0, 0, -1, -1);
109
110                 redrawListeners = new ArrayList<>();
111
112                 pin1.addPinMovedListener(p -> pinMoved());
113                 pin2.addPinMovedListener(p -> pinMoved());
114
115                 recalculateEffectivePath();
116
117                 model.wireCreated(this);
118         }
119
120         /**
121          * Destroys this wire. This method implicitly calls {@link ViewModelModifiable#wireDestroyed(GUIWire) wireDestroyed()} for the model
122          * this component is a part of.
123          * 
124          * @author Daniel Kirschten
125          */
126         public void destroy()
127         {
128                 model.wireDestroyed(this);
129         }
130
131         // pins
132
133         /**
134          * Returns the {@link Pin} on one side of this wire, usually the signal source.
135          * 
136          * @author Daniel Kirschten
137          */
138         public Pin getPin1()
139         {
140                 return pin1;
141         }
142
143         /**
144          * Returns the {@link Pin} on one side of this wire, usually the signal target.
145          * 
146          * @author Daniel Kirschten
147          */
148         public Pin getPin2()
149         {
150                 return pin2;
151         }
152
153         /**
154          * Called when {@link #pin1} or {@link #pin2} were moved.
155          * 
156          * @author Daniel Kirschten
157          */
158         private void pinMoved()
159         {
160                 recalculateEffectivePath();
161                 callRedrawListeners();
162         }
163
164         // "graphical" operations
165
166         /**
167          * Recalculates {@link #effectivePath} "from scratch". Also updates {@link #bounds}.
168          * 
169          * @author Daniel Kirschten
170          */
171         private void recalculateEffectivePath()
172         {
173                 Point pos1 = pin1.getPos(), pos2 = pin2.getPos();
174
175                 double boundsX1 = Math.min(pos1.x, pos2.x);
176                 double boundsY1 = Math.min(pos1.y, pos2.y);
177                 double boundsX2 = Math.max(pos1.x, pos2.x);
178                 double boundsY2 = Math.max(pos1.y, pos2.y);
179
180                 if (path == null)
181                         effectivePath = new double[] { pos1.x, pos1.y, (pos1.x + pos2.x) / 2, pos1.y, (pos1.x + pos2.x) / 2, pos2.y, pos2.x, pos2.y };
182                 else
183                 {
184                         effectivePath = new double[path.length * 2 + 4];
185                         effectivePath[0] = pos1.x;
186                         effectivePath[1] = pos1.y;
187                         for (int srcI = 0, dstI = 2; srcI < path.length; srcI++, dstI += 2)
188                         {
189                                 double pathX = path[srcI].x;
190                                 double pathY = path[srcI].y;
191                                 effectivePath[dstI + 0] = pathX;
192                                 effectivePath[dstI + 1] = pathY;
193                                 if (pathX < boundsX1)
194                                         boundsX1 = pathX;
195                                 if (pathX > boundsX2)
196                                         boundsX2 = pathX;
197                                 if (pathY < boundsY1)
198                                         boundsY1 = pathY;
199                                 if (pathY > boundsY2)
200                                         boundsY2 = pathY;
201                         }
202                         effectivePath[effectivePath.length - 2] = pos2.x;
203                         effectivePath[effectivePath.length - 1] = pos2.y;
204                 }
205
206                 bounds.x = boundsX1;
207                 bounds.y = boundsY1;
208                 bounds.width = boundsX2 - boundsX1;
209                 bounds.height = boundsY2 - boundsY1;
210         }
211
212         /**
213          * Returns the bounds of this wire, excluding line width (and line joins, if the line join is {@link SWT#JOIN_MITER})
214          * 
215          * @author Daniel Kirschten
216          */
217         public Rectangle getBounds()
218         {
219                 return new Rectangle(bounds.x, bounds.y, bounds.width, bounds.height);
220         }
221
222         /**
223          * Render this wire to the given gc, in absoulute coordinates.
224          * 
225          * @author Daniel Kirschten
226          */
227         public void render(GeneralGC gc)
228         {
229                 ColorHelper.executeWithDifferentForeground(gc, BitVectorFormatter.formatAsColor(end), () -> gc.drawPolyline(effectivePath));
230         }
231
232         /**
233          * The user-defined path between {@link #pin1} and {@link #pin2}. Note that this is not neccessarily equal to the effective path drawn
234          * in {@link #render(GeneralGC)}.<br>
235          * Special cases: <code>null</code> means "choose an interpolation as fits", and an empty array means "direct connection without any
236          * interpolation".
237          * 
238          * @author Daniel Kirschten
239          */
240         public Point[] getPath()
241         {
242                 return path == null ? null : path.clone();
243         }
244
245         // logic model binding
246
247         /**
248          * Binds this {@link GUIWire} to the given {@link ReadEnd}: The color of this {@link GUIWire} will now depend on the state of the given
249          * {@link ReadEnd}, and further changes of the given {@link ReadEnd} will result in readrawListeners being called.<br>
250          * The argument can be null, in which case the old binding is stopped.
251          * 
252          * @author Daniel Kirschten
253          */
254         public void setLogicModelBinding(ReadEnd end)
255         {
256                 if (this.end != null)
257                         this.end.deregisterObserver(logicObs);
258                 this.end = end;
259                 if (end != null)
260                         end.registerObserver(logicObs);
261         }
262
263         /**
264          * Returns whether this {@link GUIWire} has a logic model binding or not.
265          * 
266          * @author Daniel Kirschten
267          */
268         public boolean hasLogicModelBinding()
269         {
270                 return end != null;
271         }
272
273         /**
274          * If this {@link GUIWire} has a logic model binding, delegates to {@link Wire#forceValues(BitVector)} for the {@link Wire}
275          * corresponding to this {@link GUIWire}.
276          * 
277          * @author Daniel Kirschten
278          */
279         public void forceWireValues(BitVector values)
280         {
281                 end.getWire().forceValues(values);
282         }
283
284         /**
285          * If this {@link GUIWire} has a logic model binding, delegates to {@link ReadEnd#getValues()} for the {@link ReadEnd} corresponding to
286          * this {@link GUIWire}.
287          * 
288          * @author Daniel Kirschten
289          */
290         public BitVector getWireValues()
291         {
292                 return end.getValues();
293         }
294
295         // listeners
296
297         // @formatter:off
298         public void addRedrawListener   (Runnable listener) {redrawListeners         .add   (listener);}
299
300         public void removeRedrawListener(Runnable listener) {redrawListeners         .remove(listener);}
301
302         private void callRedrawListeners() {redrawListeners.forEach(l -> l.run());}
303         // @formatter:on
304
305         @Override
306         public String toString()
307         {
308                 return "GUIWire [" + pin1 + "---" + pin2 + ", value=" + (end == null ? "null" : end.getValues()) + "]";
309         }
310 }