The line dash of singlebit wires changes according to their value
[Mograsim.git] / plugins / net.mograsim.logic.model / src / net / mograsim / logic / model / model / wires / ModelWire.java
1 package net.mograsim.logic.model.model.wires;
2
3 import static net.mograsim.logic.model.preferences.RenderPreferences.DEFAULT_LINE_WIDTH;
4 import static net.mograsim.logic.model.preferences.RenderPreferences.WIRE_WIDTH_MULTIBIT;
5 import static net.mograsim.logic.model.preferences.RenderPreferences.WIRE_WIDTH_SINGLEBIT;
6
7 import java.util.ArrayList;
8 import java.util.Arrays;
9 import java.util.List;
10 import java.util.function.Consumer;
11
12 import org.eclipse.swt.SWT;
13
14 import net.haspamelodica.swt.helper.gcs.GeneralGC;
15 import net.haspamelodica.swt.helper.swtobjectwrappers.Point;
16 import net.haspamelodica.swt.helper.swtobjectwrappers.Rectangle;
17 import net.mograsim.logic.core.LogicObserver;
18 import net.mograsim.logic.core.types.BitVector;
19 import net.mograsim.logic.core.wires.CoreWire;
20 import net.mograsim.logic.core.wires.CoreWire.ReadEnd;
21 import net.mograsim.logic.model.BitVectorFormatter;
22 import net.mograsim.logic.model.model.LogicModelModifiable;
23 import net.mograsim.logic.model.preferences.RenderPreferences;
24 import net.mograsim.preferences.ColorDefinition;
25 import net.mograsim.preferences.ColorManager;
26
27 /**
28  * A wire connecting exactly two {@link Pin}s.
29  * 
30  * @author Daniel Kirschten
31  */
32 public class ModelWire
33 {
34         /**
35          * The model this wire is a part of.
36          */
37         private final LogicModelModifiable model;
38         /**
39          * The name of this wire. Is unique for all wires in its model.
40          */
41         public final String name;
42         /**
43          * The logical width of this wire. Is equal to the logical width of {@link #pin1} and {@link #pin2}.
44          */
45         public final int logicWidth;
46         /**
47          * The {@link Pin} on one side of this wire, usually the signal source.
48          */
49         private Pin pin1;
50         /**
51          * The {@link Pin} on one side of this wire, usually the signal target.
52          */
53         private Pin pin2;
54         /**
55          * The user-defined path between {@link #pin1} and {@link #pin2}.<br>
56          * Special cases: <code>null</code> means "choose an interpolation as fits", and an empty array means "direct connection without any
57          * interpolation".
58          */
59         private Point[] path;
60         /**
61          * The bounds of this wire, excluding line width (and line joins, if the line join is {@link SWT#JOIN_MITER})
62          */
63         private final Rectangle bounds;
64         /**
65          * The effective path of this wire, including automatic interpolation and the position of both {@link Pin}s. Is never null.
66          */
67         private double[] effectivePath;
68
69         private final List<Consumer<ModelWire>> pathChangedListeners;
70
71         /**
72          * A LogicObserver calling redrawListeners. Used for core model bindings.
73          */
74         private final LogicObserver logicObs;
75         /**
76          * A ReadEnd of the core wire this model wire currently is bound to.
77          */
78         private ReadEnd end;
79
80         // creation and destruction
81
82         /**
83          * Creates a new {@link ModelWire} with automatic interpolation and using the default name.
84          * 
85          * @author Daniel Kirschten
86          */
87         public ModelWire(LogicModelModifiable model, ModelWireCrossPoint pin1, ModelWireCrossPoint pin2)
88         {
89                 this(model, null, pin1, pin2);
90         }
91
92         /**
93          * Creates a new {@link ModelWire} with automatic interpolation and using the default name.
94          * 
95          * @author Daniel Kirschten
96          */
97         public ModelWire(LogicModelModifiable model, ModelWireCrossPoint pin1, Pin pin2)
98         {
99                 this(model, null, pin1, pin2);
100         }
101
102         /**
103          * Creates a new {@link ModelWire} with automatic interpolation and using the default name.
104          * 
105          * @author Daniel Kirschten
106          */
107         public ModelWire(LogicModelModifiable model, Pin pin1, ModelWireCrossPoint pin2)
108         {
109                 this(model, null, pin1, pin2);
110         }
111
112         /**
113          * Creates a new {@link ModelWire} with automatic interpolation and using the default name.
114          * 
115          * @author Daniel Kirschten
116          */
117         public ModelWire(LogicModelModifiable model, Pin pin1, Pin pin2)
118         {
119                 this(model, null, pin1, pin2);
120         }
121
122         /**
123          * Creates a new {@link ModelWire} without automatic interpolation and using the default name.
124          * 
125          * @author Daniel Kirschten
126          */
127         public ModelWire(LogicModelModifiable model, ModelWireCrossPoint pin1, ModelWireCrossPoint pin2, Point... path)
128         {
129                 this(model, null, pin1, pin2, path);
130         }
131
132         /**
133          * Creates a new {@link ModelWire} without automatic interpolation and using the default name.
134          * 
135          * @author Daniel Kirschten
136          */
137         public ModelWire(LogicModelModifiable model, ModelWireCrossPoint pin1, Pin pin2, Point... path)
138         {
139                 this(model, null, pin1, pin2, path);
140         }
141
142         /**
143          * Creates a new {@link ModelWire} without automatic interpolation and using the default name.
144          * 
145          * @author Daniel Kirschten
146          */
147         public ModelWire(LogicModelModifiable model, Pin pin1, ModelWireCrossPoint pin2, Point... path)
148         {
149                 this(model, null, pin1, pin2, path);
150         }
151
152         /**
153          * Creates a new {@link ModelWire} without automatic interpolation and using the default name.
154          * 
155          * @author Daniel Kirschten
156          */
157         public ModelWire(LogicModelModifiable model, Pin pin1, Pin pin2, Point... path)
158         {
159                 this(model, null, pin1, pin2, path);
160         }
161
162         /**
163          * Creates a new {@link ModelWire} with automatic interpolation.
164          * 
165          * @author Daniel Kirschten
166          */
167         public ModelWire(LogicModelModifiable model, String name, ModelWireCrossPoint pin1, ModelWireCrossPoint pin2)
168         {
169                 this(model, name, pin1, pin2, (Point[]) null);
170         }
171
172         /**
173          * Creates a new {@link ModelWire} with automatic interpolation.
174          * 
175          * @author Daniel Kirschten
176          */
177         public ModelWire(LogicModelModifiable model, String name, ModelWireCrossPoint pin1, Pin pin2)
178         {
179                 this(model, name, pin1, pin2, (Point[]) null);
180         }
181
182         /**
183          * Creates a new {@link ModelWire} with automatic interpolation.
184          * 
185          * @author Daniel Kirschten
186          */
187         public ModelWire(LogicModelModifiable model, String name, Pin pin1, ModelWireCrossPoint pin2)
188         {
189                 this(model, name, pin1, pin2, (Point[]) null);
190         }
191
192         /**
193          * Creates a new {@link ModelWire} with automatic interpolation.
194          * 
195          * @author Daniel Kirschten
196          */
197         public ModelWire(LogicModelModifiable model, String name, Pin pin1, Pin pin2)
198         {
199                 this(model, name, pin1, pin2, (Point[]) null);
200         }
201
202         /**
203          * Creates a new {@link ModelWire} without automatic interpolation.
204          * 
205          * @author Daniel Kirschten
206          */
207         public ModelWire(LogicModelModifiable model, String name, ModelWireCrossPoint pin1, ModelWireCrossPoint pin2, Point... path)
208         {
209                 this(model, name, pin1.getPin(), pin2.getPin(), path);
210         }
211
212         /**
213          * Creates a new {@link ModelWire} without automatic interpolation.
214          * 
215          * @author Daniel Kirschten
216          */
217         public ModelWire(LogicModelModifiable model, String name, ModelWireCrossPoint pin1, Pin pin2, Point... path)
218         {
219                 this(model, name, pin1.getPin(), pin2, path);
220         }
221
222         /**
223          * Creates a new {@link ModelWire} without automatic interpolation.
224          * 
225          * @author Daniel Kirschten
226          */
227         public ModelWire(LogicModelModifiable model, String name, Pin pin1, ModelWireCrossPoint pin2, Point... path)
228         {
229                 this(model, name, pin1, pin2.getPin(), path);
230         }
231
232         /**
233          * Creates a new {@link ModelWire} without automatic interpolation.
234          * 
235          * @author Daniel Kirschten
236          */
237         public ModelWire(LogicModelModifiable model, String name, Pin pin1, Pin pin2, Point... path)
238         {
239                 this.model = model;
240                 this.name = name == null ? model.getDefaultWireName() : name;
241                 this.logicWidth = pin1.logicWidth;
242                 if (pin2.logicWidth != pin1.logicWidth)
243                         throw new IllegalArgumentException("Can't connect pins of different logic width");
244
245                 this.pin1 = pin1;
246                 this.pin2 = pin2;
247
248                 this.path = path == null ? null : Arrays.copyOf(path, path.length);
249                 this.bounds = new Rectangle(0, 0, -1, -1);
250
251                 pathChangedListeners = new ArrayList<>();
252
253                 logicObs = (i) -> model.requestRedraw();
254
255                 pin1.addPinMovedListener(p -> pinMoved());
256                 pin2.addPinMovedListener(p -> pinMoved());
257
258                 recalculateEffectivePath();
259
260                 model.wireCreated(this, this::destroyed);
261         }
262
263         /**
264          * Destroys this wire. This method is called from {@link LogicModelModifiable#wireDestroyed(ModelWire) wireDestroyed()} of the model
265          * this wire is a part of.
266          * 
267          * @author Daniel Kirschten
268          */
269         private void destroyed()
270         {
271                 // nothing to do
272         }
273
274         // pins
275
276         /**
277          * Returns the {@link Pin} on one side of this wire, usually the signal source.
278          * 
279          * @author Daniel Kirschten
280          */
281         public Pin getPin1()
282         {
283                 return pin1;
284         }
285
286         /**
287          * Returns the {@link Pin} on one side of this wire, usually the signal target.
288          * 
289          * @author Daniel Kirschten
290          */
291         public Pin getPin2()
292         {
293                 return pin2;
294         }
295
296         /**
297          * Called when {@link #pin1} or {@link #pin2} were moved.
298          * 
299          * @author Daniel Kirschten
300          */
301         private void pinMoved()
302         {
303                 recalculateEffectivePath();
304                 model.requestRedraw();
305         }
306
307         // "graphical" operations
308
309         /**
310          * Recalculates {@link #effectivePath} "from scratch". Also updates {@link #bounds}.
311          * 
312          * @author Daniel Kirschten
313          */
314         private void recalculateEffectivePath()
315         {
316                 Point pos1 = pin1.getPos(), pos2 = pin2.getPos();
317
318                 double boundsX1 = Math.min(pos1.x, pos2.x);
319                 double boundsY1 = Math.min(pos1.y, pos2.y);
320                 double boundsX2 = Math.max(pos1.x, pos2.x);
321                 double boundsY2 = Math.max(pos1.y, pos2.y);
322
323                 if (path == null)
324                         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 };
325                 else
326                 {
327                         effectivePath = new double[path.length * 2 + 4];
328                         effectivePath[0] = pos1.x;
329                         effectivePath[1] = pos1.y;
330                         for (int srcI = 0, dstI = 2; srcI < path.length; srcI++, dstI += 2)
331                         {
332                                 double pathX = path[srcI].x;
333                                 double pathY = path[srcI].y;
334                                 effectivePath[dstI + 0] = pathX;
335                                 effectivePath[dstI + 1] = pathY;
336                                 if (pathX < boundsX1)
337                                         boundsX1 = pathX;
338                                 if (pathX > boundsX2)
339                                         boundsX2 = pathX;
340                                 if (pathY < boundsY1)
341                                         boundsY1 = pathY;
342                                 if (pathY > boundsY2)
343                                         boundsY2 = pathY;
344                         }
345                         effectivePath[effectivePath.length - 2] = pos2.x;
346                         effectivePath[effectivePath.length - 1] = pos2.y;
347                 }
348
349                 bounds.x = boundsX1;
350                 bounds.y = boundsY1;
351                 bounds.width = boundsX2 - boundsX1;
352                 bounds.height = boundsY2 - boundsY1;
353         }
354
355         /**
356          * Returns the bounds of this wire, excluding line width (and line joins, if the line join is {@link SWT#JOIN_MITER})
357          * 
358          * @author Daniel Kirschten
359          */
360         public Rectangle getBounds()
361         {
362                 return new Rectangle(bounds.x, bounds.y, bounds.width, bounds.height);
363         }
364
365         /**
366          * Render this wire to the given gc, in absoulute coordinates.
367          * 
368          * @author Daniel Kirschten
369          */
370         public void render(GeneralGC gc, RenderPreferences renderPrefs)
371         {
372                 ColorDefinition wireColor = BitVectorFormatter.formatAsColor(renderPrefs, end);
373                 if (wireColor != null)
374                         gc.setForeground(ColorManager.current().toColor(wireColor));
375                 gc.setLineWidth(renderPrefs.getDouble(logicWidth == 1 ? WIRE_WIDTH_SINGLEBIT : WIRE_WIDTH_MULTIBIT));
376                 gc.setLineDash(BitVectorFormatter.formatAsLineDash(renderPrefs, end));
377                 gc.drawPolyline(effectivePath);
378                 gc.setLineDash(null);
379                 gc.setLineWidth(renderPrefs.getDouble(DEFAULT_LINE_WIDTH));
380         }
381
382         // operations concerning the path
383
384         /**
385          * The user-defined path between {@link #pin1} and {@link #pin2}. Note that this is not neccessarily equal to the effective path drawn
386          * in {@link #render(GeneralGC)}.<br>
387          * Special cases: <code>null</code> means "choose an interpolation as fits", and an empty array means "direct connection without any
388          * interpolation".
389          * 
390          * @author Daniel Kirschten
391          */
392         public Point[] getPath()
393         {
394                 return deepPathCopy(path);
395         }
396
397         public void setPath(Point... path)
398         {
399                 this.path = deepPathCopy(path);
400                 recalculateEffectivePath();
401                 callPathChangedListeners();
402                 model.requestRedraw();
403         }
404
405         public Point getPathPoint(int index)
406         {
407                 return pointCopy(path[index]);
408         }
409
410         public void setPathPoint(Point p, int index)
411         {
412                 path[index] = pointCopy(p);
413                 recalculateEffectivePath();
414                 callPathChangedListeners();
415                 model.requestRedraw();
416         }
417
418         public void insertPathPoint(Point p, int index)
419         {
420                 if (path == null)
421                         path = new Point[] { pointCopy(p) };
422                 else
423                 {
424                         Point[] oldPath = path;
425                         path = new Point[oldPath.length + 1];
426                         System.arraycopy(oldPath, 0, path, 0, index);
427                         if (index < oldPath.length)
428                                 System.arraycopy(oldPath, index, path, index + 1, oldPath.length - index);
429                         path[index] = pointCopy(p);
430                 }
431                 recalculateEffectivePath();
432                 callPathChangedListeners();
433         }
434
435         public void removePathPoint(int index)
436         {
437                 if (path.length == 0)
438                         path = null;
439                 else
440                 {
441                         Point[] oldPath = path;
442                         path = new Point[oldPath.length - 1];
443                         System.arraycopy(oldPath, 0, path, 0, index);
444                         if (index < oldPath.length - 1)
445                                 System.arraycopy(oldPath, index + 1, path, index, oldPath.length - index - 1);
446                 }
447                 recalculateEffectivePath();
448                 callPathChangedListeners();
449         }
450
451         public double[] getEffectivePath()
452         {
453                 return Arrays.copyOf(effectivePath, effectivePath.length);
454         }
455
456         private static Point[] deepPathCopy(Point[] path)
457         {
458                 if (path == null)
459                         return null;
460                 Point[] copy = new Point[path.length];
461                 for (int i = 0; i < path.length; i++)
462                         copy[i] = pointCopy(path[i]);
463                 return copy;
464         }
465
466         private static Point pointCopy(Point p)
467         {
468                 return new Point(p.x, p.y);
469         }
470
471         // core model binding
472
473         /**
474          * Binds this {@link ModelWire} to the given {@link ReadEnd}: The color of this {@link ModelWire} will now depend on the state of the
475          * given {@link ReadEnd}, and further changes of the given {@link ReadEnd} will result in readrawListeners being called.<br>
476          * The argument can be null, in which case the old binding is stopped.
477          * 
478          * @author Daniel Kirschten
479          */
480         public void setCoreModelBinding(ReadEnd end)
481         {
482                 if (this.end != null)
483                         this.end.deregisterObserver(logicObs);
484                 this.end = end;
485                 if (end != null)
486                         end.registerObserver(logicObs);
487         }
488
489         /**
490          * Returns whether this {@link ModelWire} has a core model binding or not.
491          * 
492          * @author Daniel Kirschten
493          */
494         public boolean hasCoreModelBinding()
495         {
496                 return end != null;
497         }
498
499         /**
500          * If this {@link ModelWire} has a core model binding, delegates to {@link CoreWire#forceValues(BitVector)} for the {@link CoreWire}
501          * corresponding to this {@link ModelWire}.
502          * 
503          * @author Daniel Kirschten
504          */
505         public void forceWireValues(BitVector values)
506         {
507                 end.getWire().forceValues(values);
508         }
509
510         /**
511          * If this {@link ModelWire} has a core model binding, delegates to {@link ReadEnd#getValues()} for the {@link ReadEnd} corresponding to
512          * this {@link ModelWire}.
513          * 
514          * @author Daniel Kirschten
515          */
516         public BitVector getWireValues()
517         {
518                 return end.getValues();
519         }
520
521         /**
522          * Registers the given {@link LogicObserver} for the {@link ReadEnd} this {@link ModelWire} is bound to.
523          * 
524          * @see ReadEnd#registerObserver(LogicObserver)
525          * @author Daniel Kirschten
526          */
527         public void addObserver(LogicObserver obs)
528         {
529                 end.registerObserver(obs);
530         }
531
532         /**
533          * Deregisters the given {@link LogicObserver} for the {@link ReadEnd} this {@link ModelWire} is bound to.
534          * 
535          * @see ReadEnd#deregisterObserver(LogicObserver)
536          * @author Daniel Kirschten
537          */
538         public void removeObserver(LogicObserver obs)
539         {
540                 end.deregisterObserver(obs);
541         }
542
543         // listeners
544
545         // @formatter:off
546         public void addPathChangedListener   (Consumer<ModelWire> listener) {pathChangedListeners.add    (listener);}
547
548         public void removePathChangedListener(Consumer<ModelWire> listener) {pathChangedListeners.remove(listener);}
549
550         private void callPathChangedListeners() {pathChangedListeners.forEach(l -> l.accept(this));}
551         // @formatter:on
552
553         @Override
554         public String toString()
555         {
556                 return "ModelWire [" + pin1 + "---" + pin2 + ", value=" + (end == null ? "null" : end.getValues()) + "]";
557         }
558 }