Timeline now passed via constructor
[Mograsim.git] / SampleERCP / src / sampleercp / parts / LogicUIPart.java
1 package sampleercp.parts;
2
3 import javax.annotation.PostConstruct;
4 import javax.inject.Inject;
5
6 import org.eclipse.e4.ui.model.application.ui.basic.MPart;
7 import org.eclipse.swt.SWT;
8 import org.eclipse.swt.widgets.Composite;
9
10 import era.mi.gui.LogicUICanvas;
11 import era.mi.gui.examples.RSLatchGUIExample;
12 import era.mi.logic.timeline.Timeline;
13 import net.haspamelodica.swt.helper.zoomablecanvas.helper.ZoomableCanvasUserInput;
14
15 public class LogicUIPart
16 {
17         @Inject
18         private MPart part;
19
20         @PostConstruct
21         public void create(Composite parent)
22         {
23                 Timeline timeline = new Timeline(11);
24                 LogicUICanvas ui = new LogicUICanvas(parent, SWT.NONE);
25                 RSLatchGUIExample.addComponentsAndWires(ui);
26                 ui.addTransformListener((x, y, z) -> part.setDirty(z < 1));
27                 ZoomableCanvasUserInput userInput = new ZoomableCanvasUserInput(ui);
28                 userInput.buttonDrag = 3;
29                 userInput.buttonZoom = 2;
30                 userInput.enableUserInput();
31                 Thread simulationThread = new Thread(() ->
32                 {
33                         // TODO find a better condition
34                         while (!ui.isDisposed())
35                         {
36                                 // always execute to keep timeline from "hanging behind" for too long
37                                 timeline.executeUpTo(System.currentTimeMillis(), System.currentTimeMillis() + 10);
38                                 long sleepTime;
39                                 if (timeline.hasNext())
40                                         sleepTime = timeline.nextEventTime() - System.currentTimeMillis();
41                                 else
42                                         sleepTime = 10;
43                                 try
44                                 {
45                                         if (sleepTime > 0)
46                                                 Thread.sleep(sleepTime);
47                                 }
48                                 catch (InterruptedException e)
49                                 {
50                                 } // it is normal execution flow to be interrupted
51                         }
52                 });
53                 simulationThread.start();
54                 timeline.addEventAddedListener(event ->
55                 {
56                         if (event.getTiming() <= System.currentTimeMillis())
57                                 simulationThread.interrupt();
58                 });
59         }
60 }