Merge branch 'development' of https://gitlab.lrz.de/lrr-tum/students/eragp-misim...
[Mograsim.git] / plugins / net.mograsim.logic.model / src / net / mograsim / logic / model / LogicUICanvas.java
1 package net.mograsim.logic.model;
2
3 import java.util.ArrayList;
4 import java.util.List;
5 import java.util.concurrent.atomic.AtomicBoolean;
6 import java.util.concurrent.atomic.AtomicReference;
7 import java.util.function.Consumer;
8
9 import org.eclipse.swt.SWT;
10 import org.eclipse.swt.graphics.Color;
11 import org.eclipse.swt.layout.GridData;
12 import org.eclipse.swt.layout.GridLayout;
13 import org.eclipse.swt.widgets.Button;
14 import org.eclipse.swt.widgets.Combo;
15 import org.eclipse.swt.widgets.Composite;
16 import org.eclipse.swt.widgets.Event;
17 import org.eclipse.swt.widgets.Label;
18 import org.eclipse.swt.widgets.Listener;
19 import org.eclipse.swt.widgets.Shell;
20 import org.eclipse.swt.widgets.Text;
21
22 import net.haspamelodica.swt.helper.swtobjectwrappers.Point;
23 import net.haspamelodica.swt.helper.swtobjectwrappers.Rectangle;
24 import net.haspamelodica.swt.helper.zoomablecanvas.ZoomableCanvas;
25 import net.mograsim.logic.core.types.Bit;
26 import net.mograsim.logic.core.types.BitVector;
27 import net.mograsim.logic.model.model.LogicModel;
28 import net.mograsim.logic.model.model.components.ModelComponent;
29 import net.mograsim.logic.model.model.components.submodels.SubmodelComponent;
30 import net.mograsim.logic.model.model.components.submodels.SubmodelInterface;
31 import net.mograsim.logic.model.model.wires.ModelWireCrossPoint;
32 import net.mograsim.preferences.Preferences;
33
34 /**
35  * Simulation visualizer canvas.
36  * 
37  * @author Daniel Kirschten
38  */
39 public class LogicUICanvas extends ZoomableCanvas
40 {
41         private final LogicModel model;
42
43         public LogicUICanvas(Composite parent, int style, LogicModel model)
44         {
45                 super(parent, style, Preferences.current().getBoolean("net.mograsim.logic.model.improvetext"));
46
47                 this.model = model;
48
49                 LogicUIRenderer renderer = new LogicUIRenderer(model);
50                 addZoomedRenderer(gc ->
51                 {
52                         Color background = Preferences.current().getColor("net.mograsim.logic.model.color.background");
53                         if (background != null)
54                                 setBackground(background);// this.setBackground, not gc.setBackground to have the background fill the canvas
55                         renderer.render(gc, new Rectangle(-offX / zoom, -offY / zoom, gW / zoom, gH / zoom));
56                 });
57                 model.setRedrawHandler(this::redrawThreadsafe);
58
59                 addListener(SWT.MouseDown, this::mouseDown);
60
61                 if (Preferences.current().getBoolean("net.mograsim.logic.model.debug.openhlsshell"))
62                         openDebugSetHighLevelStateShell(model);
63         }
64
65         private void mouseDown(Event e)
66         {
67                 if (e.button == 1)
68                 {
69                         Point click = canvasToWorldCoords(e.x, e.y);
70                         for (ModelComponent component : model.getComponentsByName().values())
71                                 if (component.getBounds().contains(click) && component.clicked(click.x, click.y))
72                                 {
73                                         redraw();
74                                         break;
75                                 }
76                 }
77         }
78
79         private void openDebugSetHighLevelStateShell(LogicModel model)
80         {
81                 Shell debugShell = new Shell();
82                 debugShell.setLayout(new GridLayout(2, false));
83                 new Label(debugShell, SWT.NONE).setText("Target component: ");
84                 Combo componentSelector = new Combo(debugShell, SWT.DROP_DOWN | SWT.READ_ONLY);
85                 componentSelector.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));
86                 List<ModelComponent> componentsByItemIndex = new ArrayList<>();
87                 List<LogicModel> models = new ArrayList<>();
88                 AtomicBoolean recalculateQueued = new AtomicBoolean();
89                 AtomicReference<Consumer<? super ModelComponent>> compAdded = new AtomicReference<>();
90                 AtomicReference<Consumer<? super ModelComponent>> compRemoved = new AtomicReference<>();
91                 compAdded.set(c -> compsChanged(compAdded.get(), compRemoved.get(), c, models, componentsByItemIndex, componentSelector, model,
92                                 recalculateQueued, true));
93                 compRemoved.set(c -> compsChanged(compAdded.get(), compRemoved.get(), c, models, componentsByItemIndex, componentSelector, model,
94                                 recalculateQueued, false));
95                 iterateModelTree(compAdded.get(), compRemoved.get(), model, models, true);
96                 debugShell.addListener(SWT.Dispose, e -> models.forEach(m ->
97                 {
98                         m.removeComponentAddedListener(compAdded.get());
99                         m.removeComponentRemovedListener(compRemoved.get());
100                 }));
101                 queueRecalculateComponentSelector(recalculateQueued, componentsByItemIndex, componentSelector, model);
102                 new Label(debugShell, SWT.NONE).setText("Target state ID: ");
103                 Text stateIDText = new Text(debugShell, SWT.SINGLE | SWT.LEAD | SWT.BORDER);
104                 stateIDText.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));
105                 new Label(debugShell, SWT.NONE).setText("Value type: ");
106                 Composite radioGroup = new Composite(debugShell, SWT.NONE);
107                 radioGroup.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));
108                 GridLayout radioGroupLayout = new GridLayout(2, false);
109                 radioGroupLayout.marginHeight = 0;
110                 radioGroupLayout.marginWidth = 0;
111                 radioGroup.setLayout(radioGroupLayout);
112                 Button radioBit = new Button(radioGroup, SWT.RADIO);
113                 radioBit.setText("Single bit");
114                 Button radioBitVector = new Button(radioGroup, SWT.RADIO);
115                 radioBitVector.setText("Bitvector");
116                 new Label(debugShell, SWT.NONE).setText("Value string representation: \n(Bit vectors: MSBit...LSBit)");
117                 Text valueText = new Text(debugShell, SWT.SINGLE | SWT.LEAD | SWT.BORDER);
118                 valueText.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));
119                 Button send = new Button(debugShell, SWT.PUSH);
120                 send.setText("Send!");
121                 Button get = new Button(debugShell, SWT.PUSH);
122                 get.setText("Get!");
123                 Text output = new Text(debugShell, SWT.READ_ONLY);
124                 output.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 2, 1));
125                 Listener sendAction = e ->
126                 {
127                         try
128                         {
129                                 int componentIndex = componentSelector.getSelectionIndex();
130                                 if (componentIndex < 0 || componentIndex >= componentsByItemIndex.size())
131                                         throw new RuntimeException("No component selected");
132                                 ModelComponent target = componentsByItemIndex.get(componentIndex);
133                                 String valueString = valueText.getText();
134                                 Object value;
135                                 if (radioBit.getSelection())
136                                         value = Bit.parse(valueString);
137                                 else if (radioBitVector.getSelection())
138                                         value = BitVector.parse(valueString);
139                                 else
140                                         throw new RuntimeException("No value type selected");
141                                 target.setHighLevelState(stateIDText.getText(), value);
142                                 output.setText("Success!");
143                         }
144                         catch (Exception x)
145                         {
146                                 output.setText(x.getClass().getSimpleName() + (x.getMessage() == null ? "" : ": " + x.getMessage()));
147                         }
148                 };
149                 Listener getAction = e ->
150                 {
151                         try
152                         {
153                                 if (componentSelector.getSelectionIndex() >= componentsByItemIndex.size())
154                                         throw new RuntimeException("No valid component selected");
155                                 output.setText("Success! Value: \r\n"
156                                                 + componentsByItemIndex.get(componentSelector.getSelectionIndex()).getHighLevelState(stateIDText.getText()));
157                         }
158                         catch (Exception x)
159                         {
160                                 output.setText(x.getClass().getSimpleName() + (x.getMessage() == null ? "" : ": " + x.getMessage()));
161                         }
162                 };
163                 send.addListener(SWT.Selection, sendAction);
164                 valueText.addListener(SWT.DefaultSelection, sendAction);
165                 get.addListener(SWT.Selection, getAction);
166                 stateIDText.addListener(SWT.DefaultSelection, getAction);
167                 debugShell.open();
168         }
169
170         private void compsChanged(Consumer<? super ModelComponent> compAdded, Consumer<? super ModelComponent> compRemoved, ModelComponent c,
171                         List<LogicModel> models, List<ModelComponent> componentsByItemIndex, Combo componentSelector, LogicModel model,
172                         AtomicBoolean recalculateQueued, boolean add)
173         {
174                 iterateSubmodelTree(compAdded, compRemoved, c, models, add);
175                 queueRecalculateComponentSelector(recalculateQueued, componentsByItemIndex, componentSelector, model);
176         }
177
178         private void iterateSubmodelTree(Consumer<? super ModelComponent> compAdded, Consumer<? super ModelComponent> compRemoved,
179                         ModelComponent c, List<LogicModel> models, boolean add)
180         {
181                 if (c instanceof SubmodelComponent)
182                         iterateModelTree(compAdded, compRemoved, ((SubmodelComponent) c).submodel, models, add);
183         }
184
185         private void iterateModelTree(Consumer<? super ModelComponent> compAdded, Consumer<? super ModelComponent> compRemoved,
186                         LogicModel model, List<LogicModel> models, boolean add)
187         {
188                 if (add ^ models.contains(model))
189                 {
190                         if (add)
191                         {
192                                 models.add(model);
193                                 model.addComponentAddedListener(compAdded);
194                                 model.addComponentRemovedListener(compRemoved);
195                         } else
196                         {
197                                 models.remove(model);
198                                 model.removeComponentAddedListener(compAdded);
199                                 model.removeComponentRemovedListener(compRemoved);
200                         }
201                         for (ModelComponent c : model.getComponentsByName().values())
202                                 iterateSubmodelTree(compAdded, compRemoved, c, models, add);
203                 }
204         }
205
206         private void queueRecalculateComponentSelector(AtomicBoolean recalculateQueued, List<ModelComponent> componentsByItemIndex,
207                         Combo componentSelector, LogicModel model)
208         {
209                 if (recalculateQueued.compareAndSet(false, true))
210                         getDisplay().asyncExec(() -> recalculateComponentSelector(recalculateQueued, componentsByItemIndex, componentSelector, model));
211         }
212
213         private void recalculateComponentSelector(AtomicBoolean recalculateQueued, List<ModelComponent> componentsByItemIndex,
214                         Combo componentSelector, LogicModel model)
215         {
216                 recalculateQueued.set(false);
217                 componentsByItemIndex.clear();
218                 componentSelector.setItems();
219                 addComponentSelectorItems(componentsByItemIndex, "", componentSelector, model);
220         }
221
222         private void addComponentSelectorItems(List<ModelComponent> componentsByItemIndex, String base, Combo componentSelector,
223                         LogicModel model)
224         {
225                 model.getComponentsByName().values().stream().sorted((c1, c2) -> c1.getName().compareTo(c2.getName())).forEach(c ->
226                 {
227                         if (!(c instanceof ModelWireCrossPoint || c instanceof SubmodelInterface))
228                         {
229                                 String item = base + c.getName();
230                                 componentsByItemIndex.add(c);
231                                 componentSelector.add(item);
232                                 if (c instanceof SubmodelComponent)
233                                         addComponentSelectorItems(componentsByItemIndex, item + " -> ", componentSelector, ((SubmodelComponent) c).submodel);
234                         }
235                 });
236         }
237 }