Added DeserializedSubmodelComponent Editor project
[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.HashSet;
6 import java.util.List;
7 import java.util.Set;
8
9 import org.eclipse.swt.SWT;
10
11 import net.haspamelodica.swt.helper.gcs.GeneralGC;
12 import net.haspamelodica.swt.helper.swtobjectwrappers.Point;
13 import net.haspamelodica.swt.helper.swtobjectwrappers.Rectangle;
14 import net.mograsim.logic.core.LogicObserver;
15 import net.mograsim.logic.core.types.BitVector;
16 import net.mograsim.logic.core.types.BitVectorFormatter;
17 import net.mograsim.logic.core.wires.Wire;
18 import net.mograsim.logic.core.wires.Wire.ReadEnd;
19 import net.mograsim.logic.ui.model.ViewModelModifiable;
20 import net.mograsim.preferences.ColorDefinition;
21 import net.mograsim.preferences.ColorManager;
22
23 /**
24  * A wire connecting exactly two {@link Pin}s.
25  * 
26  * @author Daniel Kirschten
27  */
28 public class GUIWire
29 {
30         
31         private final Set<PathChangedListener> pathChangedListeners;
32
33         /**
34          * The model this wire is a part of.
35          */
36         private final ViewModelModifiable model;
37         /**
38          * The logical width of this wire. Is equal to the logical with of {@link #pin1} and {@link #pin2}.
39          */
40         public final int logicWidth;
41         /**
42          * The {@link Pin} on one side of this wire, usually the signal source.
43          */
44         private Pin pin1;
45         /**
46          * The {@link Pin} on one side of this wire, usually the signal target.
47          */
48         private Pin pin2;
49         /**
50          * The user-defined path between {@link #pin1} and {@link #pin2}.<br>
51          * Special cases: <code>null</code> means "choose an interpolation as fits", and an empty array means "direct connection without any
52          * interpolation".
53          */
54         private Point[] path;
55         /**
56          * The bounds of this wire, excluding line width (and line joins, if the line join is {@link SWT#JOIN_MITER})
57          */
58         private final Rectangle bounds;
59         /**
60          * The effective path of this wire, including automatic interpolation and the position of both {@link Pin}s. Is never null.
61          */
62         protected double[] effectivePath;
63
64         private final List<Runnable> redrawListeners;
65
66         /**
67          * A LogicObserver calling redrawListeners. Used for logic model bindings.
68          */
69         private final LogicObserver logicObs;
70         /**
71          * A ReadEnd of the logic wire this GUI wire currently is bound to.
72          */
73         private ReadEnd end;
74
75         // creation and destruction
76
77         /**
78          * Creates a new {@link GUIWire} with automatic interpolation.
79          * 
80          * @author Daniel Kirschten
81          */
82         public GUIWire(ViewModelModifiable model, ConnectionPoint pin1, ConnectionPoint pin2)
83         {
84                 this(model, pin1, pin2, (Point[]) null);
85         }
86
87         /**
88          * Creates a new {@link GUIWire} without automatic interpolation.
89          * 
90          * @author Daniel Kirschten
91          */
92         public GUIWire(ViewModelModifiable model, ConnectionPoint pin1, ConnectionPoint pin2, Point... path)
93         {
94                 this(model, pin1.getPin(), pin2.getPin(), path);
95         }
96
97         /**
98          * Creates a new {@link GUIWire} without automatic interpolation.
99          * 
100          * @author Daniel Kirschten
101          */
102         GUIWire(ViewModelModifiable model, Pin pin1, Pin pin2, Point... path)
103         {
104                 pathChangedListeners = new HashSet<>();
105                 logicObs = (i) -> callRedrawListeners();
106                 this.model = model;
107                 this.logicWidth = pin1.logicWidth;
108                 if (pin2.logicWidth != pin1.logicWidth)
109                         throw new IllegalArgumentException("Can't connect pins of different logic width");
110
111                 this.pin1 = pin1;
112                 this.pin2 = pin2;
113
114                 this.path = path == null ? null : Arrays.copyOf(path, path.length);
115                 this.bounds = new Rectangle(0, 0, -1, -1);
116
117                 redrawListeners = new ArrayList<>();
118
119                 pin1.addPinMovedListener(p -> pinMoved());
120                 pin2.addPinMovedListener(p -> pinMoved());
121
122                 recalculateEffectivePath();
123
124                 model.wireCreated(this);
125         }
126
127         /**
128          * Destroys this wire. This method implicitly calls {@link ViewModelModifiable#wireDestroyed(GUIWire) wireDestroyed()} for the model
129          * this component is a part of.
130          * 
131          * @author Daniel Kirschten
132          */
133         public void destroy()
134         {
135                 model.wireDestroyed(this);
136         }
137
138         // pins
139
140         /**
141          * Returns the {@link Pin} on one side of this wire, usually the signal source.
142          * 
143          * @author Daniel Kirschten
144          */
145         public Pin getPin1()
146         {
147                 return pin1;
148         }
149
150         /**
151          * Returns the {@link Pin} on one side of this wire, usually the signal target.
152          * 
153          * @author Daniel Kirschten
154          */
155         public Pin getPin2()
156         {
157                 return pin2;
158         }
159
160         /**
161          * Called when {@link #pin1} or {@link #pin2} were moved.
162          * 
163          * @author Daniel Kirschten
164          */
165         private void pinMoved()
166         {
167                 recalculateEffectivePath();
168                 callRedrawListeners();
169         }
170
171         // "graphical" operations
172
173         /**
174          * Recalculates {@link #effectivePath} "from scratch". Also updates {@link #bounds}.
175          * 
176          * @author Daniel Kirschten
177          */
178         private void recalculateEffectivePath()
179         {
180                 Point pos1 = pin1.getPos(), pos2 = pin2.getPos();
181
182                 double boundsX1 = Math.min(pos1.x, pos2.x);
183                 double boundsY1 = Math.min(pos1.y, pos2.y);
184                 double boundsX2 = Math.max(pos1.x, pos2.x);
185                 double boundsY2 = Math.max(pos1.y, pos2.y);
186
187                 if (path == null)
188                         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 };
189                 else
190                 {
191                         effectivePath = new double[path.length * 2 + 4];
192                         effectivePath[0] = pos1.x;
193                         effectivePath[1] = pos1.y;
194                         for (int srcI = 0, dstI = 2; srcI < path.length; srcI++, dstI += 2)
195                         {
196                                 double pathX = path[srcI].x;
197                                 double pathY = path[srcI].y;
198                                 effectivePath[dstI + 0] = pathX;
199                                 effectivePath[dstI + 1] = pathY;
200                                 if (pathX < boundsX1)
201                                         boundsX1 = pathX;
202                                 if (pathX > boundsX2)
203                                         boundsX2 = pathX;
204                                 if (pathY < boundsY1)
205                                         boundsY1 = pathY;
206                                 if (pathY > boundsY2)
207                                         boundsY2 = pathY;
208                         }
209                         effectivePath[effectivePath.length - 2] = pos2.x;
210                         effectivePath[effectivePath.length - 1] = pos2.y;
211                 }
212
213                 bounds.x = boundsX1;
214                 bounds.y = boundsY1;
215                 bounds.width = boundsX2 - boundsX1;
216                 bounds.height = boundsY2 - boundsY1;
217         }
218
219         /**
220          * Returns the bounds of this wire, excluding line width (and line joins, if the line join is {@link SWT#JOIN_MITER})
221          * 
222          * @author Daniel Kirschten
223          */
224         public Rectangle getBounds()
225         {
226                 return new Rectangle(bounds.x, bounds.y, bounds.width, bounds.height);
227         }
228
229         /**
230          * Render this wire to the given gc, in absoulute coordinates.
231          * 
232          * @author Daniel Kirschten
233          */
234         public void render(GeneralGC gc)
235         {
236                 ColorDefinition wireColor = BitVectorFormatter.formatAsColor(end);
237                 if (wireColor != null)
238                         gc.setForeground(ColorManager.current().toColor(wireColor));
239                 gc.drawPolyline(effectivePath);
240         }
241
242         /**
243          * The user-defined path between {@link #pin1} and {@link #pin2}. Note that this is not neccessarily equal to the effective path drawn
244          * in {@link #render(GeneralGC)}.<br>
245          * Special cases: <code>null</code> means "choose an interpolation as fits", and an empty array means "direct connection without any
246          * interpolation".
247          * 
248          * @author Daniel Kirschten
249          */
250         public Point[] getPath()
251         {
252                 return path == null ? null : path.clone();
253         }
254
255         // logic model binding
256
257         /**
258          * Binds this {@link GUIWire} to the given {@link ReadEnd}: The color of this {@link GUIWire} will now depend on the state of the given
259          * {@link ReadEnd}, and further changes of the given {@link ReadEnd} will result in readrawListeners being called.<br>
260          * The argument can be null, in which case the old binding is stopped.
261          * 
262          * @author Daniel Kirschten
263          */
264         public void setLogicModelBinding(ReadEnd end)
265         {
266                 if (this.end != null)
267                         this.end.deregisterObserver(logicObs);
268                 this.end = end;
269                 if (end != null)
270                         end.registerObserver(logicObs);
271         }
272
273         /**
274          * Returns whether this {@link GUIWire} has a logic model binding or not.
275          * 
276          * @author Daniel Kirschten
277          */
278         public boolean hasLogicModelBinding()
279         {
280                 return end != null;
281         }
282
283         /**
284          * If this {@link GUIWire} has a logic model binding, delegates to {@link Wire#forceValues(BitVector)} for the {@link Wire}
285          * corresponding to this {@link GUIWire}.
286          * 
287          * @author Daniel Kirschten
288          */
289         public void forceWireValues(BitVector values)
290         {
291                 end.getWire().forceValues(values);
292         }
293
294         /**
295          * If this {@link GUIWire} has a logic model binding, delegates to {@link ReadEnd#getValues()} for the {@link ReadEnd} corresponding to
296          * this {@link GUIWire}.
297          * 
298          * @author Daniel Kirschten
299          */
300         public BitVector getWireValues()
301         {
302                 return end.getValues();
303         }
304
305         // listeners
306
307         // @formatter:off
308         public void addRedrawListener   (Runnable listener) {redrawListeners         .add   (listener);}
309
310         public void removeRedrawListener(Runnable listener) {redrawListeners         .remove(listener);}
311
312         private void callRedrawListeners() {redrawListeners.forEach(l -> l.run());}
313         
314         public void addPathChangedListener(PathChangedListener l) { pathChangedListeners.add(l); }
315
316         public void removePathChangedListener(PathChangedListener l) { pathChangedListeners.remove(l); }
317
318         public void callPathChangedListeners(int diff) { pathChangedListeners.forEach(l -> l.pathChanged(this, diff)); }
319         
320         @FunctionalInterface
321         public static interface PathChangedListener
322         {
323                 /**
324                  * Called whenever the {@link Wire}'s path changes
325                  * 
326                  * @param wire The wire which had its path changed
327                  * @param diff The length difference between before and after the path change.
328                  */
329                 public void pathChanged(GUIWire wire, int diff);
330         }
331         // @formatter:on
332
333         @Override
334         public String toString()
335         {
336                 return "GUIWire [" + pin1 + "---" + pin2 + ", value=" + (end == null ? "null" : end.getValues()) + "]";
337         }
338
339         public void setPath(Point[] path)
340         {
341                 int diff = (path == null ? 0 : path.length) - (this.path == null ? 0 : this.path.length);
342                 this.path = path == null ? null : path.clone();
343                 recalculateEffectivePath();
344                 callPathChangedListeners(diff);
345                 callRedrawListeners();
346         }
347
348         public void setPathPoint(Point p, int index)
349         {
350                 path[index] = p;
351                 recalculateEffectivePath();
352                 callPathChangedListeners(0);
353                 callRedrawListeners();
354         }
355
356         public void insertPathPoint(Point p, int index)
357         {
358                 Point[] path = getPath();
359                 if (path == null)
360                         setPath(new Point[] { p });
361                 else
362                 {
363                         Point[] newPath = new Point[path.length + 1];
364                         System.arraycopy(path, 0, newPath, 0, index);
365                         if (index < path.length)
366                                 System.arraycopy(path, index, newPath, index + 1, path.length - index);
367                         newPath[index] = p;
368                         setPath(newPath);
369                 }
370         }
371
372         public void removePathPoint(int index)
373         {
374                 Point[] path = getPath();
375                 Point[] newPath = new Point[path.length - 1];
376                 System.arraycopy(path, 0, newPath, 0, index);
377                 if (index < path.length - 1)
378                         System.arraycopy(path, index + 1, newPath, index, path.length - index - 1);
379                 setPath(newPath);
380         }
381
382         /**
383          * @throws IndexOutOfBoundsException
384          */
385         public Point getPathPoint(int index)
386         {
387                 return path[index];
388         }
389
390         public int getPathLength()
391         {
392                 return path.length;
393         }
394
395         public double[] getEffectivePath()
396         {
397                 return effectivePath.clone();
398         }
399 }