1 package net.mograsim.logic.ui.model.wires;
3 import java.util.ArrayList;
6 import net.haspamelodica.swt.helper.gcs.GeneralGC;
7 import net.haspamelodica.swt.helper.swtobjectwrappers.Point;
8 import net.mograsim.logic.core.LogicObservable;
9 import net.mograsim.logic.core.LogicObserver;
10 import net.mograsim.logic.core.types.BitVectorFormatter;
11 import net.mograsim.logic.core.wires.Wire.ReadEnd;
12 import net.mograsim.logic.ui.ColorHelper;
13 import net.mograsim.logic.ui.model.ViewModelModifiable;
17 private final ViewModelModifiable model;
18 public final int logicWidth;
21 private double[] path;
23 private final List<Runnable> redrawListeners;
25 private final LogicObserver logicObs;
28 public GUIWire(ViewModelModifiable model, WireCrossPoint pin1, WireCrossPoint pin2, Point... path)
30 this(model, pin1.getPin(), pin2.getPin(), path);
33 public GUIWire(ViewModelModifiable model, WireCrossPoint pin1, Pin pin2, Point... path)
35 this(model, pin1.getPin(), pin2, path);
38 public GUIWire(ViewModelModifiable model, Pin pin1, WireCrossPoint pin2, Point... path)
40 this(model, pin1, pin2.getPin(), path);
43 public GUIWire(ViewModelModifiable model, Pin pin1, Pin pin2, Point... path)
45 logicObs = (i) -> callRedrawListeners();
47 this.logicWidth = pin1.logicWidth;
48 if (pin2.logicWidth != pin1.logicWidth)
49 throw new IllegalArgumentException("Can't connect pins of different logic width");
50 this.path = new double[path.length * 2 + 4];
51 for (int srcI = 0, dstI = 2; srcI < path.length; srcI++, dstI += 2)
53 this.path[dstI + 0] = path[srcI].x;
54 this.path[dstI + 1] = path[srcI].y;
60 redrawListeners = new ArrayList<>();
62 pin1.addPinMovedListener(p -> pin1Moved());
63 pin2.addPinMovedListener(p -> pin2Moved());
67 model.wireCreated(this);
70 private void pin1Moved()
72 Point pos = pin1.getPos();
75 callRedrawListeners();
78 private void pin2Moved()
80 Point pos = pin2.getPos();
81 this.path[this.path.length - 2] = pos.x;
82 this.path[this.path.length - 1] = pos.y;
83 callRedrawListeners();
88 model.wireDestroyed(this);
91 public void render(GeneralGC gc)
93 ColorHelper.executeWithDifferentForeground(gc, BitVectorFormatter.formatAsColor(end), () -> gc.drawPolyline(path));
96 public void setLogicModelBinding(ReadEnd end)
98 deregisterLogicObs(this.end);
100 registerLogicObs(end);
103 private void registerLogicObs(LogicObservable observable)
105 if (observable != null)
106 observable.registerObserver(logicObs);
109 private void deregisterLogicObs(LogicObservable observable)
111 if (observable != null)
112 observable.deregisterObserver(logicObs);
126 public void addRedrawListener (Runnable listener) {redrawListeners .add (listener);}
128 public void removeRedrawListener(Runnable listener) {redrawListeners .remove(listener);}
130 private void callRedrawListeners() {redrawListeners.forEach(l -> l.run());}