Added preferences for mouse button assignments
[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.snippets.highlevelstatehandlers.DefaultHighLevelStateHandler;
31 import net.mograsim.preferences.Preferences;
32
33 /**
34  * Simulation visualizer canvas.
35  * 
36  * @author Daniel Kirschten
37  */
38 public class LogicUICanvas extends ZoomableCanvas
39 {
40         private final LogicModel model;
41
42         public LogicUICanvas(Composite parent, int style, LogicModel model)
43         {
44                 super(parent, style, Preferences.current().getBoolean("net.mograsim.logic.model.improvetext"));
45
46                 this.model = model;
47
48                 LogicUIRenderer renderer = new LogicUIRenderer(model);
49                 addZoomedRenderer(gc ->
50                 {
51                         Color background = Preferences.current().getColor("net.mograsim.logic.model.color.background");
52                         if (background != null)
53                                 setBackground(background);// this.setBackground, not gc.setBackground to have the background fill the canvas
54                         renderer.render(gc, new Rectangle(-offX / zoom, -offY / zoom, gW / zoom, gH / zoom));
55                 });
56                 model.setRedrawHandler(this::redrawThreadsafe);
57
58                 addListener(SWT.MouseDown, this::mouseDown);
59
60                 if (Preferences.current().getBoolean("net.mograsim.logic.model.debug.openhlsshell"))
61                         openDebugSetHighLevelStateShell(model);
62         }
63
64         private void mouseDown(Event e)
65         {
66                 if (e.button == Preferences.current().getInt("net.mograsim.logic.model.button.action"))
67                 {
68                         Point click = canvasToWorldCoords(e.x, e.y);
69                         for (ModelComponent component : model.getComponentsByName().values())
70                                 if (component.getBounds().contains(click) && component.clicked(click.x, click.y))
71                                 {
72                                         redraw();
73                                         break;
74                                 }
75                 }
76         }
77
78         private void openDebugSetHighLevelStateShell(LogicModel model)
79         {
80                 Shell debugShell = new Shell();
81                 debugShell.setLayout(new GridLayout(2, false));
82                 new Label(debugShell, SWT.NONE).setText("Target component: ");
83                 Combo componentSelector = new Combo(debugShell, SWT.DROP_DOWN | SWT.READ_ONLY);
84                 componentSelector.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));
85                 List<ModelComponent> componentsByItemIndex = new ArrayList<>();
86                 List<LogicModel> models = new ArrayList<>();
87                 AtomicBoolean recalculateQueued = new AtomicBoolean();
88                 AtomicReference<Consumer<? super ModelComponent>> compAdded = new AtomicReference<>();
89                 AtomicReference<Consumer<? super ModelComponent>> compRemoved = new AtomicReference<>();
90                 compAdded.set(c -> compsChanged(compAdded.get(), compRemoved.get(), c, models, componentsByItemIndex, componentSelector, model,
91                                 recalculateQueued, true));
92                 compRemoved.set(c -> compsChanged(compAdded.get(), compRemoved.get(), c, models, componentsByItemIndex, componentSelector, model,
93                                 recalculateQueued, false));
94                 iterateModelTree(compAdded.get(), compRemoved.get(), model, models, true);
95                 debugShell.addListener(SWT.Dispose, e -> models.forEach(m ->
96                 {
97                         m.removeComponentAddedListener(compAdded.get());
98                         m.removeComponentRemovedListener(compRemoved.get());
99                 }));
100                 queueRecalculateComponentSelector(recalculateQueued, componentsByItemIndex, componentSelector, model);
101                 new Label(debugShell, SWT.NONE).setText("Target state ID: ");
102                 Text stateIDText = new Text(debugShell, SWT.SINGLE | SWT.LEAD | SWT.BORDER);
103                 stateIDText.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));
104                 new Label(debugShell, SWT.NONE).setText("Value type: ");
105                 Composite radioGroup = new Composite(debugShell, SWT.NONE);
106                 radioGroup.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));
107                 GridLayout radioGroupLayout = new GridLayout(2, false);
108                 radioGroupLayout.marginHeight = 0;
109                 radioGroupLayout.marginWidth = 0;
110                 radioGroup.setLayout(radioGroupLayout);
111                 Button radioBit = new Button(radioGroup, SWT.RADIO);
112                 radioBit.setText("Single bit");
113                 Button radioBitVector = new Button(radioGroup, SWT.RADIO);
114                 radioBitVector.setText("Bitvector");
115                 new Label(debugShell, SWT.NONE).setText("Value string representation: \n(Bit vectors: MSBit...LSBit)");
116                 Text valueText = new Text(debugShell, SWT.SINGLE | SWT.LEAD | SWT.BORDER);
117                 valueText.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));
118                 Button send = new Button(debugShell, SWT.PUSH);
119                 send.setText("Send!");
120                 Button get = new Button(debugShell, SWT.PUSH);
121                 get.setText("Get!");
122                 Text output = new Text(debugShell, SWT.READ_ONLY);
123                 output.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 2, 1));
124                 Listener sendAction = e ->
125                 {
126                         try
127                         {
128                                 int componentIndex = componentSelector.getSelectionIndex();
129                                 if (componentIndex < 0 || componentIndex >= componentsByItemIndex.size())
130                                         throw new RuntimeException("No component selected");
131                                 ModelComponent target = componentsByItemIndex.get(componentIndex);
132                                 String valueString = valueText.getText();
133                                 Object value;
134                                 if (radioBit.getSelection())
135                                         value = Bit.parse(valueString);
136                                 else if (radioBitVector.getSelection())
137                                         value = BitVector.parse(valueString);
138                                 else
139                                         throw new RuntimeException("No value type selected");
140                                 target.setHighLevelState(stateIDText.getText(), value);
141                                 output.setText("Success!");
142                         }
143                         catch (Exception x)
144                         {
145                                 output.setText(x.getClass().getSimpleName() + (x.getMessage() == null ? "" : ": " + x.getMessage()));
146                         }
147                 };
148                 Listener getAction = e ->
149                 {
150                         try
151                         {
152                                 if (componentSelector.getSelectionIndex() >= componentsByItemIndex.size())
153                                         throw new RuntimeException("No valid component selected");
154                                 output.setText("Success! Value: \r\n"
155                                                 + componentsByItemIndex.get(componentSelector.getSelectionIndex()).getHighLevelState(stateIDText.getText()));
156                         }
157                         catch (Exception x)
158                         {
159                                 output.setText(x.getClass().getSimpleName() + (x.getMessage() == null ? "" : ": " + x.getMessage()));
160                         }
161                 };
162                 send.addListener(SWT.Selection, sendAction);
163                 valueText.addListener(SWT.DefaultSelection, sendAction);
164                 get.addListener(SWT.Selection, getAction);
165                 stateIDText.addListener(SWT.DefaultSelection, getAction);
166                 debugShell.open();
167                 addDisposeListener(e -> debugShell.dispose());
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                                 Preferences.current().getInt("net.mograsim.logic.model.debug.hlsshelldepth") - 1);
221         }
222
223         private void addComponentSelectorItems(List<ModelComponent> componentsByItemIndex, String base, Combo componentSelector,
224                         LogicModel model, int depth)
225         {
226                 model.getComponentsByName().values().stream().sorted((c1, c2) -> c1.getName().compareTo(c2.getName())).forEach(c ->
227                 {
228                         if (!(c.getHighLevelStateHandler() instanceof DefaultHighLevelStateHandler))
229                         {
230                                 String item = base + c.getName();
231                                 componentsByItemIndex.add(c);
232                                 componentSelector.add(item);
233                                 // this causes negative numbers to result in infinite depth
234                                 if (depth != 0 && c instanceof SubmodelComponent)
235                                         addComponentSelectorItems(componentsByItemIndex, item + " -> ", componentSelector, ((SubmodelComponent) c).submodel,
236                                                         depth - 1);
237                         }
238                 });
239         }
240 }