]> gerrit.simantics Code Review - simantics/district.git/blob
36eaaf619f618e8e0bd9d572018e8ce7a251e2c2
[simantics/district.git] /
1 package org.simantics.district.network.ui.participants;
2
3 import java.awt.geom.AffineTransform;
4 import java.awt.geom.Point2D;
5 import java.util.Map;
6 import java.util.Set;
7 import java.util.concurrent.CompletableFuture;
8 import java.util.concurrent.ExecutionException;
9 import java.util.concurrent.ScheduledFuture;
10 import java.util.concurrent.TimeUnit;
11
12 import org.simantics.Simantics;
13 import org.simantics.db.ReadGraph;
14 import org.simantics.db.Resource;
15 import org.simantics.db.common.request.ReadRequest;
16 import org.simantics.db.exception.DatabaseException;
17 import org.simantics.district.network.ontology.DistrictNetworkResource;
18 import org.simantics.district.network.profile.RuntimeDynamicVisualisationsRequest;
19 import org.simantics.district.network.ui.DistrictDiagramViewer;
20 import org.simantics.district.network.ui.nodes.DeferredRenderingNode;
21 import org.simantics.district.network.ui.nodes.DistrictNetworkEdgeArrayNode;
22 import org.simantics.district.network.ui.nodes.DistrictNetworkHoverInfoNode;
23 import org.simantics.district.network.ui.nodes.DynamicVisualisationContributionsNode;
24 import org.simantics.district.network.ui.styles.DistrictNetworkHoverInfoStyle;
25 import org.simantics.district.network.ui.styles.DistrictNetworkHoverInfoStyle.StyleResult;
26 import org.simantics.district.network.visualisations.model.ColorBarOptions;
27 import org.simantics.district.network.visualisations.model.DynamicColorContribution;
28 import org.simantics.district.network.visualisations.model.DynamicSizeContribution;
29 import org.simantics.district.network.visualisations.model.DynamicVisualisation;
30 import org.simantics.district.network.visualisations.model.SizeBarOptions;
31 import org.simantics.g2d.canvas.ICanvasContext;
32 import org.simantics.g2d.canvas.impl.AbstractCanvasParticipant;
33 import org.simantics.g2d.canvas.impl.SGNodeReflection.SGInit;
34 import org.simantics.scenegraph.INode;
35 import org.simantics.scenegraph.g2d.G2DParentNode;
36 import org.simantics.scenegraph.g2d.events.EventHandlerReflection.EventHandler;
37 import org.simantics.scenegraph.g2d.events.command.CommandEvent;
38 import org.simantics.utils.datastructures.Pair;
39 import org.simantics.utils.datastructures.hints.HintListenerAdapter;
40 import org.simantics.utils.datastructures.hints.IHintContext.Key;
41 import org.simantics.utils.datastructures.hints.IHintListener;
42 import org.simantics.utils.datastructures.hints.IHintObservable;
43 import org.simantics.utils.threads.IThreadWorkQueue;
44 import org.simantics.utils.threads.ThreadUtils;
45 import org.slf4j.Logger;
46 import org.slf4j.LoggerFactory;
47
48 public class DynamicVisualisationContributionsParticipant extends AbstractCanvasParticipant {
49
50     private static final Logger LOGGER = LoggerFactory.getLogger(DynamicVisualisationContributionsParticipant.class);
51
52     IHintListener hintListener = new HintListenerAdapter() {
53         public void hintChanged(IHintObservable sender, Key key, Object oldValue, Object newValue) {
54             ICanvasContext cc = getContext();
55             if (cc != null) {
56                 updateNode();
57                 cc.getContentContext().setDirty();
58             }
59         }
60     };
61
62     private DynamicVisualisationContributionsNode node;
63     private AffineTransform transform;
64     private DistrictNetworkHoverInfoNode hoverInfoNode;
65     private DeferredRenderingNode deferredEdgeArrowRendererNode;
66
67     public DynamicVisualisationContributionsParticipant(AffineTransform tr) {
68         this.transform = tr;
69     }
70
71     @Override
72     public void addedToContext(ICanvasContext ctx) {
73         super.addedToContext(ctx);
74         getHintStack().addKeyHintListener(getThread(), DistrictDiagramViewer.KEY_MAP_COLORING_OBJECTS, hintListener);
75         getHintStack().addKeyHintListener(getThread(), DistrictDiagramViewer.KEY_MAP_COLOR_BAR_OPTIONS, hintListener);
76         getHintStack().addKeyHintListener(getThread(), DistrictDiagramViewer.KEY_MAP_SIZING_OBJECTS, hintListener);
77         getHintStack().addKeyHintListener(getThread(), DistrictDiagramViewer.KEY_MAP_SIZE_BAR_OPTIONS, hintListener);
78     }
79
80     @Override
81     public void removedFromContext(ICanvasContext ctx) {
82         // Ensure hover polling is stopped
83         if (hoverUpdateSchedule != null && !hoverUpdateSchedule.isDone()) {
84             hoverUpdateSchedule.cancel(false);
85         }
86
87         getHintStack().removeKeyHintListener(getThread(), DistrictDiagramViewer.KEY_MAP_COLORING_OBJECTS, hintListener);
88         getHintStack().removeKeyHintListener(getThread(), DistrictDiagramViewer.KEY_MAP_COLOR_BAR_OPTIONS, hintListener);
89         getHintStack().removeKeyHintListener(getThread(), DistrictDiagramViewer.KEY_MAP_SIZING_OBJECTS, hintListener);
90         getHintStack().removeKeyHintListener(getThread(), DistrictDiagramViewer.KEY_MAP_SIZE_BAR_OPTIONS, hintListener);
91         super.removedFromContext(ctx);
92     }
93
94     @SGInit
95     public void initSG(G2DParentNode parent) {
96         node = parent.addNode(DynamicVisualisationContributionsNode.ID, DynamicVisualisationContributionsNode.class);
97         node.setTransform(transform);
98         node.setEnabled(true);
99         node.setZIndex(1000);
100
101         hoverInfoNode = parent.addNode("districtNetworkHoverInfoNode", DistrictNetworkHoverInfoNode.class);
102         hoverInfoNode.setLookupId("districtNetworkHoverInfoNode");
103         hoverInfoNode.setTransform(transform);
104         hoverInfoNode.setZIndex(Integer.MAX_VALUE - 500);
105         
106         Pair<String, Class<DeferredRenderingNode>> dearn = DistrictNetworkEdgeArrayNode.renderer();
107         deferredEdgeArrowRendererNode = parent.addNode(dearn.first, dearn.second);
108     }
109
110     @EventHandler(priority = 0)
111     protected boolean handleKeyEvent(CommandEvent e) {
112         if (e.command.equals(DistrictDiagramViewer.MAP_COLOR_BAR_OPTIONS_CHANGE)) {
113             System.out.println(e);
114             return true;
115         }
116         return false;
117     }
118
119     protected void updateNode() {
120         node.setDynamicColoringObjects(getDynamicColoringObjects());
121         node.setColorBarOptions(getColorBarOptions());
122         node.setDynamicSizingObjects(getDynamicSizingObjects());
123         node.setSizeBarOptions(getSizeBarOptions());
124     }
125
126     private Map<String, DynamicColorContribution> getDynamicColoringObjects() {
127         return getHint(DistrictDiagramViewer.KEY_MAP_COLORING_OBJECTS);
128     }
129
130     private ColorBarOptions getColorBarOptions() {
131         return getHint(DistrictDiagramViewer.KEY_MAP_COLOR_BAR_OPTIONS);
132     }
133
134     private Map<String, DynamicSizeContribution> getDynamicSizingObjects() {
135         return getHint(DistrictDiagramViewer.KEY_MAP_SIZING_OBJECTS);
136     }
137
138     private SizeBarOptions getSizeBarOptions() {
139         return getHint(DistrictDiagramViewer.KEY_MAP_SIZE_BAR_OPTIONS);
140     }
141
142     private ScheduledFuture<?> hoverUpdateSchedule;
143     private static final Object COMPLETE = new Object();
144
145     public void hoverNode(Resource runtimeDiagram, Resource mapElement, INode hoveredNode, int zoomLevel) {
146         IThreadWorkQueue thread = getThread();
147         Simantics.getSession().asyncRequest(new ReadRequest() {
148             @Override
149             public void run(ReadGraph graph) throws DatabaseException {
150                 DynamicVisualisation visualisation = graph.syncRequest(new RuntimeDynamicVisualisationsRequest(runtimeDiagram));
151                 if (visualisation == null)
152                     return;
153                 cancelCurrentHoverUpdate();
154                 hoverUpdateSchedule = ThreadUtils.getNonBlockingWorkExecutor().scheduleWithFixedDelay(
155                         () -> updateHoverInfo(runtimeDiagram, mapElement, hoveredNode, zoomLevel, visualisation, thread),
156                         0,
157                         visualisation.getInterval(),
158                         TimeUnit.MILLISECONDS);
159             }
160         });
161     }
162
163     private void updateHoverInfo(Resource runtimeDiagram, Resource mapElement, INode hoveredNode, int zoomLevel, DynamicVisualisation visualisation, IThreadWorkQueue thread) {
164         CompletableFuture<Object> future = new CompletableFuture<>();
165         try {
166             Simantics.getSession().syncRequest(new ReadRequest() {
167                 @Override
168                 public void run(ReadGraph graph) throws DatabaseException {
169                     Set<Resource> mapElementTypes = graph.getTypes(mapElement);
170                     if (mapElementTypes.isEmpty()) {
171                         future.complete(COMPLETE);
172                         return;
173                     }
174
175                     DistrictNetworkResource DN = DistrictNetworkResource.getInstance(graph);
176
177                     boolean doHover =
178                             (mapElementTypes.contains(DN.Vertex) && visualisation.isKeyVariablesVertexHover())
179                             || (mapElementTypes.contains(DN.Edge) && visualisation.isKeyVariablesEdgesHover());
180
181                     StyleResult results = DistrictNetworkHoverInfoStyle.doCalculateStyleResult(graph, runtimeDiagram, mapElement);
182                     if (results != null) {
183                         Point2D location = DistrictNetworkHoverInfoStyle.calculatePoint(hoveredNode, zoomLevel, null);
184                         thread.asyncExec(() -> {
185                             if (isRemoved())
186                                 return;
187                             if (doHover) {
188                                 hoverInfoNode.setLabels(results.getLabels());
189                                 hoverInfoNode.setOrigin(results.getOrigin());
190                                 hoverInfoNode.setMousePosition(location);
191                                 hoverInfoNode.setHoveredNode(hoveredNode);
192                             } else {
193                                 hoverInfoNode.setHoveredNode(null);
194                             }
195                             future.complete(COMPLETE);
196                         });
197                     } else {
198                         future.complete(COMPLETE);
199                     }
200                 }
201             });
202         } catch (DatabaseException e) {
203             future.completeExceptionally(e);
204         }
205         // this waits until everything is done
206         try {
207             future.get();
208         } catch (InterruptedException | ExecutionException e) {
209             LOGGER.debug("Interrupted hovering", e);
210         }
211     }
212
213     public boolean doHover(boolean hover, boolean isConnectionTool) {
214         if (!hover)
215             cancelCurrentHoverUpdate();
216         return hoverInfoNode.hover(hover, isConnectionTool);
217     }
218
219     private void cancelCurrentHoverUpdate() {
220         if (hoverUpdateSchedule != null && !hoverUpdateSchedule.isDone())
221             hoverUpdateSchedule.cancel(false);
222     }
223
224 }