]> gerrit.simantics Code Review - simantics/district.git/blob
7dd11b7ab83225bcd5e943b42099fffa24df1d1f
[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.concurrent.CompletableFuture;
7 import java.util.concurrent.ExecutionException;
8 import java.util.concurrent.ScheduledFuture;
9 import java.util.concurrent.TimeUnit;
10
11 import org.simantics.Simantics;
12 import org.simantics.db.ReadGraph;
13 import org.simantics.db.Resource;
14 import org.simantics.db.common.request.ReadRequest;
15 import org.simantics.db.exception.DatabaseException;
16 import org.simantics.district.network.ontology.DistrictNetworkResource;
17 import org.simantics.district.network.profile.RuntimeDynamicVisualisationsRequest;
18 import org.simantics.district.network.ui.DistrictDiagramViewer;
19 import org.simantics.district.network.ui.nodes.DistrictNetworkHoverInfoNode;
20 import org.simantics.district.network.ui.nodes.DynamicVisualisationContributionsNode;
21 import org.simantics.district.network.ui.styles.DistrictNetworkHoverInfoStyle;
22 import org.simantics.district.network.ui.styles.DistrictNetworkHoverInfoStyle.StyleResult;
23 import org.simantics.district.network.visualisations.model.ColorBarOptions;
24 import org.simantics.district.network.visualisations.model.DynamicColorContribution;
25 import org.simantics.district.network.visualisations.model.DynamicSizeContribution;
26 import org.simantics.district.network.visualisations.model.DynamicVisualisation;
27 import org.simantics.district.network.visualisations.model.SizeBarOptions;
28 import org.simantics.g2d.canvas.ICanvasContext;
29 import org.simantics.g2d.canvas.impl.AbstractCanvasParticipant;
30 import org.simantics.g2d.canvas.impl.SGNodeReflection.SGInit;
31 import org.simantics.layer0.Layer0;
32 import org.simantics.scenegraph.g2d.G2DParentNode;
33 import org.simantics.scenegraph.g2d.events.EventHandlerReflection.EventHandler;
34 import org.simantics.scenegraph.g2d.events.command.CommandEvent;
35 import org.simantics.utils.datastructures.hints.HintListenerAdapter;
36 import org.simantics.utils.datastructures.hints.IHintContext.Key;
37 import org.simantics.utils.datastructures.hints.IHintListener;
38 import org.simantics.utils.datastructures.hints.IHintObservable;
39 import org.simantics.utils.threads.IThreadWorkQueue;
40 import org.simantics.utils.threads.ThreadUtils;
41 import org.slf4j.Logger;
42 import org.slf4j.LoggerFactory;
43
44 public class DynamicVisualisationContributionsParticipant extends AbstractCanvasParticipant {
45
46     private static final Logger LOGGER = LoggerFactory.getLogger(DynamicVisualisationContributionsParticipant.class);
47
48     IHintListener hintListener = new HintListenerAdapter() {
49         public void hintChanged(IHintObservable sender, Key key, Object oldValue, Object newValue) {
50             ICanvasContext cc = getContext();
51             if (cc != null) {
52                 updateNode();
53                 cc.getContentContext().setDirty();
54             }
55         }
56     };
57     
58     private DynamicVisualisationContributionsNode node;
59     private AffineTransform transform;
60
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 //    @Override
113 //    protected boolean handleCommand(CommandEvent e) {
114 //        if (e.command.equals(DistrictDiagramViewer.MAP_COLOR_BAR_OPTIONS_CHANGE)) {
115 //            ICanvasContext context = (ICanvasContext) e.getContext();
116 //            ColorBarOptions options = context.getHintStack().getHint(DistrictDiagramViewer.KEY_MAP_COLOR_BAR_OPTIONS);
117 //            this.colorBarsOptions = options;
118 //            repaint();
119 //            return true;
120 //        } else {
121 //            return super.handleCommand(e);
122 //        }
123 //    }
124     
125     protected void updateNode() {
126         node.setDynamicColoringObjects(getDynamicColoringObjects());
127         node.setColorBarOptions(getColorBarOptions());
128         node.setDynamicSizingObjects(getDynamicSizingObjects());
129         node.setSizeBarOptions(getSizeBarOptions());
130     }
131
132     private Map<String,DynamicColorContribution> getDynamicColoringObjects() {
133         Map<String,DynamicColorContribution> objects = getHint(DistrictDiagramViewer.KEY_MAP_COLORING_OBJECTS);
134         return objects;
135     }
136
137     private ColorBarOptions getColorBarOptions() {
138         ColorBarOptions options = getHint(DistrictDiagramViewer.KEY_MAP_COLOR_BAR_OPTIONS);
139         return options;
140     }
141
142     private Map<String, DynamicSizeContribution> getDynamicSizingObjects() {
143         Map<String, DynamicSizeContribution> objects = getHint(DistrictDiagramViewer.KEY_MAP_SIZING_OBJECTS);
144         return objects;
145     }
146
147     private SizeBarOptions getSizeBarOptions() {
148         SizeBarOptions options = getHint(DistrictDiagramViewer.KEY_MAP_SIZE_BAR_OPTIONS);
149         return options;
150     }
151
152     private ScheduledFuture<?> hoverUpdateSchedule;
153     private static final Object COMPLETE = new Object();
154     
155     public void hoverNode(Resource runtimeDiagram, Resource mapElement, G2DParentNode hoveredNode) {
156         IThreadWorkQueue thread = getThread();
157         Simantics.getSession().asyncRequest(new ReadRequest() {
158
159             @Override
160             public void run(ReadGraph graph) throws DatabaseException {
161                 DynamicVisualisation visualisation = graph.syncRequest(new RuntimeDynamicVisualisationsRequest(runtimeDiagram));
162                 if (visualisation == null)
163                     return;
164                 if (hoverUpdateSchedule != null && !hoverUpdateSchedule.isDone()) {
165                     hoverUpdateSchedule.cancel(false);
166                 }
167                 hoverUpdateSchedule = ThreadUtils.getNonBlockingWorkExecutor().scheduleWithFixedDelay(() -> {
168                     
169                     CompletableFuture<Object> future = new CompletableFuture<>();
170                     try {
171                         Simantics.getSession().syncRequest(new ReadRequest() {
172
173                             @Override
174                             public void run(ReadGraph graph) throws DatabaseException {
175                                 boolean keyVariablesVertexHover = visualisation.isKeyVariablesVertexHover();
176                                 boolean keyVariablesEdgesHover = visualisation.isKeyVariablesEdgesHover();
177
178                                 Resource mapElementInstanceOf = graph.getPossibleObject(mapElement, Layer0.getInstance(graph).InstanceOf);
179                                 if (mapElementInstanceOf == null) {
180                                     future.complete(COMPLETE);
181                                     return;
182                                 }
183
184                                 DistrictNetworkResource DN = DistrictNetworkResource.getInstance(graph);
185                                 
186                                 boolean doHover = true;
187                                 if (mapElementInstanceOf.equals(DN.Vertex) && !keyVariablesVertexHover) {
188                                     doHover = false;
189                                 } else if (mapElementInstanceOf.equals(DN.Edge) && !keyVariablesEdgesHover) {
190                                     doHover = false;
191                                 }
192                                 final boolean finalDoHover = doHover;
193                                 
194                                 StyleResult results = DistrictNetworkHoverInfoStyle.doCalculateStyleResult(graph, runtimeDiagram, mapElement);
195                                 if (results != null) {
196                                     Point2D location = DistrictNetworkHoverInfoStyle.calculatePoint(graph, mapElement);
197                                     thread.asyncExec(() -> {
198                                         if (isRemoved())
199                                             return;
200                                         if (finalDoHover) {
201                                             hoverInfoNode.setLabels(results.getLabels());
202                                             hoverInfoNode.setOrigin(results.getOrigin());
203                                             
204                                             hoverInfoNode.setMousePosition(location);
205                                             hoverInfoNode.hover2(hoveredNode);
206                                         } else {
207                                             hoverInfoNode.hover2(null);
208                                         }
209                                         future.complete(COMPLETE);
210                                     });
211                                 } else {
212                                     future.complete(COMPLETE);
213                                 }
214                             }
215                         });
216                     } catch (DatabaseException e) {
217                         future.completeExceptionally(e);
218                     }
219                     // this waits until everything is done
220                     try {
221                         future.get();
222                     } catch (InterruptedException | ExecutionException e) {
223                         LOGGER.debug("Interrupted hovering", e);
224                     }
225                 }, 0, visualisation.getInterval(), TimeUnit.MILLISECONDS);
226             }
227         });
228     }
229
230     public boolean doHover(boolean hover, boolean isConnectionTool) {
231         return hoverInfoNode.hover(hover, isConnectionTool);
232     }
233 }