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