1 package org.simantics.district.network.ui;
4 import java.awt.geom.AffineTransform;
5 import java.util.Collections;
7 import java.util.Objects;
8 import java.util.concurrent.TimeUnit;
9 import java.util.function.Consumer;
10 import java.util.function.Supplier;
12 import org.simantics.datatypes.literal.RGB;
13 import org.simantics.db.ReadGraph;
14 import org.simantics.db.Resource;
15 import org.simantics.db.common.request.PossibleIndexRoot;
16 import org.simantics.db.common.request.UnaryRead;
17 import org.simantics.db.exception.DatabaseException;
18 import org.simantics.db.procedure.Listener;
19 import org.simantics.diagram.ui.DiagramModelHints;
20 import org.simantics.district.network.DistrictNetworkUtil;
21 import org.simantics.district.network.ontology.DistrictNetworkResource;
22 import org.simantics.district.network.ui.internal.Activator;
23 import org.simantics.district.network.ui.nodes.DistrictRenderingPreparationNode;
24 import org.simantics.district.network.ui.nodes.DistrictSelectionNode;
25 import org.simantics.district.network.ui.participants.DNPointerInteractor;
26 import org.simantics.district.network.ui.participants.DynamicVisualisationContributionsParticipant;
27 import org.simantics.district.network.ui.participants.ElevationServerParticipant;
28 import org.simantics.district.network.ui.participants.MapRulerPainter;
29 import org.simantics.district.network.visualisations.DynamicVisualisations;
30 import org.simantics.district.network.visualisations.model.ColorBarOptions;
31 import org.simantics.district.network.visualisations.model.DynamicColorContribution;
32 import org.simantics.district.network.visualisations.model.DynamicSizeContribution;
33 import org.simantics.district.network.visualisations.model.SizeBarOptions;
34 import org.simantics.g2d.canvas.ICanvasContext;
35 import org.simantics.g2d.canvas.impl.CanvasContext;
36 import org.simantics.g2d.diagram.handler.PickRequest.PickFilter;
37 import org.simantics.g2d.diagram.participant.DelayedBatchElementPainter;
38 import org.simantics.g2d.diagram.participant.ElementPainter;
39 import org.simantics.g2d.diagram.participant.ElementPainterConfiguration;
40 import org.simantics.g2d.diagram.participant.Selection;
41 import org.simantics.g2d.diagram.participant.ZOrderHandler;
42 import org.simantics.g2d.participant.BackgroundPainter;
43 import org.simantics.g2d.participant.GridPainter;
44 import org.simantics.g2d.participant.PanZoomRotateHandler;
45 import org.simantics.g2d.participant.RenderingQualityInteractor;
46 import org.simantics.g2d.participant.TransformUtil;
47 import org.simantics.g2d.participant.ZoomToAreaHandler;
48 import org.simantics.g2d.scenegraph.SceneGraphConstants;
49 import org.simantics.maps.MapScalingTransform;
50 import org.simantics.maps.eclipse.MapPainter;
51 import org.simantics.maps.sg.commands.MapCommands;
52 import org.simantics.modeling.ui.diagramEditor.DiagramViewer;
53 import org.simantics.scenegraph.g2d.G2DParentNode;
54 import org.simantics.scenegraph.g2d.events.command.Command;
55 import org.simantics.scenegraph.g2d.events.command.CommandEvent;
56 import org.simantics.scenegraph.g2d.events.command.Commands;
57 import org.simantics.utils.datastructures.hints.IHintContext;
58 import org.simantics.utils.datastructures.hints.IHintContext.Key;
59 import org.simantics.utils.datastructures.hints.IHintContext.KeyOf;
60 import org.slf4j.Logger;
61 import org.slf4j.LoggerFactory;
63 public class DistrictDiagramViewer extends DiagramViewer {
65 private static final Logger LOGGER = LoggerFactory.getLogger(DistrictDiagramViewer.class);
68 protected void addDiagramParticipants(ICanvasContext ctx) {
69 ctx.add(new ZOrderHandler());
70 ctx.add(new Selection());
71 ctx.add(new ElementPainter(new ElementPainterConfiguration().selectionNodeClass(DistrictSelectionNode.class)));
72 ctx.add(new DNPointerInteractor());
74 AffineTransform tr = new AffineTransform(MapScalingTransform.INSTANCE);
75 ctx.add(new MapPainter(tr));
77 DynamicVisualisationContributionsParticipant dynamicVisualisationContributionsParticipant = new DynamicVisualisationContributionsParticipant(tr);
78 ctx.add(new NetworkDrawingParticipant(dynamicVisualisationContributionsParticipant, tr));
79 ctx.add(new ElevationServerParticipant(tr));
80 ctx.add(dynamicVisualisationContributionsParticipant);
82 // Optimize AffineTransform memory allocations during district diagram rendering
83 G2DParentNode spatialRoot = (G2DParentNode) ctx.getSceneGraph().lookupNode(SceneGraphConstants.SPATIAL_ROOT_NODE_ID);
84 DistrictRenderingPreparationNode prepNode = new DistrictRenderingPreparationNode();
85 prepNode.setZIndex(Integer.MIN_VALUE / 2);
86 spatialRoot.addNode("districtRenderingPrepareNode", prepNode);
89 protected String getPopupId() {
90 return "#DistrictDiagramPopup";
94 protected void fillInitialDiagramHints(Resource diagram, IHintContext initialHints) throws DatabaseException {
95 super.fillInitialDiagramHints(diagram, initialHints);
100 public void initializeCanvasContext(CanvasContext ctx) {
101 super.initializeCanvasContext(ctx);
102 IHintContext h = ctx.getDefaultHintContext();
103 h.setHint(PanZoomRotateHandler.KEY_ZOOM_IN_LIMIT, 10000.0);
104 h.setHint(PanZoomRotateHandler.KEY_ZOOM_OUT_LIMIT, 0.01);
105 h.setHint(DiagramModelHints.KEY_DIAGRAM_RESOURCE, diagramResource);
109 protected void addPainterParticipants(ICanvasContext ctx) {
110 ctx.add(new RenderingQualityInteractor());
111 ctx.add(new DelayedBatchElementPainter(PickFilter.FILTER_MONITORS, 500, TimeUnit.MILLISECONDS));
115 protected void addGridRulerBackgroundParticipants(CanvasContext ctx) {
116 ctx.add(new GridPainter());
117 ctx.add(new MapRulerPainter());
118 ctx.add(new BackgroundPainter());
121 protected void addViewManipulationParticipants(CanvasContext ctx) {
122 // Let's replace with our special util
123 TransformUtil util = ctx.getAtMostOneItemOfClass(TransformUtil.class);
126 ctx.add(new DistrictTransformUtil());
127 ctx.add(new DistrictPanZoomRotateHandler());
128 //ctx.add(new MousePanZoomInteractor());
129 //ctx.add(new MultitouchPanZoomRotateInteractor());
130 // ctx.add( new OrientationRestorer() );
131 ctx.add(new ZoomToAreaHandler());
135 protected void loadPageSettings(ICanvasContext ctx) {
136 super.loadPageSettings(ctx);
137 // this might be the wrong place to start such listening but at least
138 // super.loadPageSettings() does async-db-operations
139 setupDrawMapEnabled();
140 setupBackgroundColor();
141 setupColoringObjects();
142 setupColorBarOptions();
143 setupSizingObjects();
144 setupSizeBarOptions();
147 DistrictDiagramViewerListener[] listeners = Activator.getInstance().getDistrictDiagramViewerListeners();
148 if (listeners != null) {
149 for (DistrictDiagramViewerListener listener : listeners) {
150 listener.diagramLoaded(getRuntime(), canvasContext);
156 public void dispose() {
157 DistrictDiagramViewerListener[] listeners = Activator.getInstance().getDistrictDiagramViewerListeners();
158 if (listeners != null) {
159 Resource runtime = getRuntime();
160 for (DistrictDiagramViewerListener listener : listeners) {
161 listener.diagramDisposed(runtime, canvasContext);
167 private void setupDrawMapEnabled() {
168 sessionContext.getSession().asyncRequest(new DrawMapEnabledRequest(getInputResource()), new DrawMapEnabledListener(
169 result -> canvasContext.getEventQueue().queueEvent(new CommandEvent(canvasContext, System.currentTimeMillis(), result ? Commands.MAP_ENABLE : Commands.MAP_DISABLE)),
170 () -> DistrictDiagramViewer.this.isDisposed()));
173 private void setupBackgroundColor() {
174 sessionContext.getSession().asyncRequest(new MapBackgroundColorRequest(getInputResource()), new MapBackgroundColorListener(
175 result -> queueBackgroundColorChangeEvent(result),
176 () -> DistrictDiagramViewer.this.isDisposed()));
179 private void queueBackgroundColorChangeEvent(RGB.Integer result) {
180 if (result != null) {
181 Color backgroundColor = new Color(result.red, result.green, result.blue);
182 canvasContext.getDefaultHintContext().setHint(MapCommands.KEY_MAP_BACKGROUND_COLOR, backgroundColor);
183 canvasContext.getEventQueue().queueEvent(new CommandEvent(canvasContext, System.currentTimeMillis(), MapCommands.MAP_BACKGROUND_COLOR_CHANGE));
187 private void setupColoringObjects() {
188 sessionContext.getSession().asyncRequest(new ColoringObjectsRequest(getInputResource()), new ColoringObjectsListener(
189 result -> queueColoringObjectsChangeEvent(result),
190 () -> DistrictDiagramViewer.this.isDisposed()));
194 private void setupColorBarOptions() {
195 sessionContext.getSession().asyncRequest(new ColorBarOptionsRequest(getInputResource()), new ColorBarOptionsListener(
196 result -> queueColorBarOptionsChangeEvent(result),
197 () -> DistrictDiagramViewer.this.isDisposed()));
200 private void setupSizingObjects() {
201 sessionContext.getSession().asyncRequest(new SizingObjectsRequest(getInputResource()), new SizingObjectsListener(
202 result -> queueSizingObjectsChangeEvent(result),
203 () -> DistrictDiagramViewer.this.isDisposed()));
207 private void setupSizeBarOptions() {
208 sessionContext.getSession().asyncRequest(new SizeBarOptionsRequest(getInputResource()), new SizeBarOptionsListener(
209 result -> queueSizeBarOptionsChangeEvent(result),
210 () -> DistrictDiagramViewer.this.isDisposed()));
213 public static final Key KEY_MAP_COLOR_BAR_OPTIONS = new KeyOf(ColorBarOptions.class, "colorBarOptions");
214 public static final Command MAP_COLOR_BAR_OPTIONS_CHANGE = new Command("colorBarOptionsChange");
215 public static final Key KEY_MAP_SIZE_BAR_OPTIONS = new KeyOf(SizeBarOptions.class, "sizeBarOptions");
216 public static final Command MAP_SIZE_BAR_OPTIONS_CHANGE = new Command("sizeBarOptionsChange");
218 public static final Key KEY_MAP_COLORING_OBJECTS = new KeyOf(Map.class, "coloringObjects");
219 public static final Command MAP_COLORING_OBJECTS_CHANGE = new Command("coloringObjectsChange");
221 public static final Key KEY_MAP_SIZING_OBJECTS = new KeyOf(Map.class, "sizingObjects");
222 public static final Command MAP_SIZING_OBJECTS_CHANGE = new Command("sizingObjectsChange");
225 private void queueColoringObjectsChangeEvent(Map<String, DynamicColorContribution> result) {
226 queueEventInternal(KEY_MAP_COLORING_OBJECTS, MAP_COLORING_OBJECTS_CHANGE, result);
229 private void queueColorBarOptionsChangeEvent(ColorBarOptions result) {
230 queueEventInternal(KEY_MAP_COLOR_BAR_OPTIONS, MAP_COLOR_BAR_OPTIONS_CHANGE, result);
233 private void queueSizingObjectsChangeEvent(Map<String, DynamicSizeContribution> result) {
234 queueEventInternal(KEY_MAP_SIZING_OBJECTS, MAP_SIZING_OBJECTS_CHANGE, result);
237 private void queueSizeBarOptionsChangeEvent(SizeBarOptions result) {
238 queueEventInternal(KEY_MAP_SIZE_BAR_OPTIONS, MAP_SIZE_BAR_OPTIONS_CHANGE, result);
241 private void queueEventInternal(Key key, Command command, Object result) {
242 if (result != null && !canvasContext.isDisposed()) {
243 canvasContext.getThreadAccess().asyncExec(() -> {
244 canvasContext.getDefaultHintContext().setHint(key, result);
245 canvasContext.getEventQueue().queueEvent(new CommandEvent(canvasContext, System.currentTimeMillis(), command));
248 LOGGER.info("Result is either null or canvasContext is disposed", String.valueOf(result));
252 private static class DrawMapEnabledRequest extends UnaryRead<Resource, Boolean> {
254 public DrawMapEnabledRequest(Resource diagram) {
259 public Boolean perform(ReadGraph graph) throws DatabaseException {
260 return DistrictNetworkUtil.drawMapEnabled(graph, parameter);
264 private static class DrawMapEnabledListener implements Listener<Boolean> {
266 private static final Logger LOGGER = LoggerFactory.getLogger(DrawMapEnabledListener.class);
268 private Consumer<Boolean> callback;
269 private Supplier<Boolean> isDisposed;
271 private Boolean lastResult;
273 public DrawMapEnabledListener(Consumer<Boolean> callback, Supplier<Boolean> isDisposed) {
274 this.callback = callback;
275 this.isDisposed = isDisposed;
279 public void execute(Boolean result) {
280 // Minor optimization
281 if (!Objects.equals(lastResult, result)) {
283 callback.accept(result);
288 public void exception(Throwable t) {
289 LOGGER.error("Could not listen if draw map is enabled", t);
293 public boolean isDisposed() {
294 return isDisposed.get();
298 private static class MapBackgroundColorRequest extends UnaryRead<Resource, RGB.Integer> {
300 public MapBackgroundColorRequest(Resource diagram) {
305 public RGB.Integer perform(ReadGraph graph) throws DatabaseException {
306 return DistrictNetworkUtil.backgroundColor(graph, parameter);
310 private static class MapBackgroundColorListener implements Listener<RGB.Integer> {
312 private static final Logger LOGGER = LoggerFactory.getLogger(MapBackgroundColorListener.class);
314 private Consumer<RGB.Integer> callback;
315 private Supplier<Boolean> isDisposed;
317 private RGB.Integer lastResult;
319 public MapBackgroundColorListener(Consumer<RGB.Integer> callback, Supplier<Boolean> isDisposed) {
320 this.callback = callback;
321 this.isDisposed = isDisposed;
325 public void execute(RGB.Integer result) {
326 if (!Objects.equals(lastResult, result)) {
328 callback.accept(result);
333 public void exception(Throwable t) {
334 LOGGER.error("Could not listen map background color", t);
338 public boolean isDisposed() {
339 return isDisposed.get();
343 private static class ColorBarOptionsRequest extends UnaryRead<Resource, ColorBarOptions> {
345 public ColorBarOptionsRequest(Resource diagram) {
350 public ColorBarOptions perform(ReadGraph graph) throws DatabaseException {
351 DistrictNetworkResource DN = DistrictNetworkResource.getInstance(graph);
352 Resource model = graph.syncRequest(new PossibleIndexRoot(parameter));
354 Resource vf = DynamicVisualisations.getVisualisationFolder(graph, model);
356 Resource activeVisualisation = graph.getPossibleObject(vf, DN.Diagram_hasActiveVisualisation);
357 if (activeVisualisation != null) {
358 return DynamicVisualisations.colorBarOptions(graph, activeVisualisation);
361 LOGGER.debug("No visualisation folder available for model {}", model);
364 return ColorBarOptions.useDefault();
368 private static class ColoringObjectsRequest extends UnaryRead<Resource, Map<String,DynamicColorContribution>> {
370 public ColoringObjectsRequest(Resource diagram) {
375 public Map<String, DynamicColorContribution> perform(ReadGraph graph) throws DatabaseException {
376 DistrictNetworkResource DN = DistrictNetworkResource.getInstance(graph);
377 Resource model = graph.syncRequest(new PossibleIndexRoot(parameter));
379 Resource vf = DynamicVisualisations.getVisualisationFolder(graph, model);
381 Resource activeVisualisation = graph.getPossibleObject(vf, DN.Diagram_hasActiveVisualisation);
382 if (activeVisualisation != null) {
383 return DynamicVisualisations.colorContributions(graph, activeVisualisation);
386 LOGGER.debug("No visualisation folder available for model {}", model);
389 return Collections.emptyMap();
393 private static class ColoringObjectsListener implements Listener<Map<String,DynamicColorContribution>> {
395 private static final Logger LOGGER = LoggerFactory.getLogger(ColoringObjectsListener.class);
397 private Consumer<Map<String,DynamicColorContribution>> callback;
398 private Supplier<Boolean> isDisposed;
400 //private Map<String, DynamicColorContribution> lastResult
402 public ColoringObjectsListener(Consumer<Map<String,DynamicColorContribution>> callback, Supplier<Boolean> isDisposed) {
403 this.callback = callback;
404 this.isDisposed = isDisposed;
408 public void execute(Map<String,DynamicColorContribution> result) {
409 callback.accept(result);
413 public void exception(Throwable t) {
414 LOGGER.error("Could not listen ColorBarOptions", t);
418 public boolean isDisposed() {
419 return isDisposed.get();
423 private static class ColorBarOptionsListener implements Listener<ColorBarOptions> {
425 private static final Logger LOGGER = LoggerFactory.getLogger(ColorBarOptionsListener.class);
427 private Consumer<ColorBarOptions> callback;
428 private Supplier<Boolean> isDisposed;
430 public ColorBarOptionsListener(Consumer<ColorBarOptions> callback, Supplier<Boolean> isDisposed) {
431 this.callback = callback;
432 this.isDisposed = isDisposed;
436 public void execute(ColorBarOptions result) {
437 callback.accept(result);
441 public void exception(Throwable t) {
442 LOGGER.error("Could not listen ColorBarOptions", t);
446 public boolean isDisposed() {
447 return isDisposed.get();
451 private static class SizeBarOptionsRequest extends UnaryRead<Resource, SizeBarOptions> {
453 public SizeBarOptionsRequest(Resource diagram) {
458 public SizeBarOptions perform(ReadGraph graph) throws DatabaseException {
459 DistrictNetworkResource DN = DistrictNetworkResource.getInstance(graph);
460 Resource model = graph.syncRequest(new PossibleIndexRoot(parameter));
462 Resource vf = DynamicVisualisations.getVisualisationFolder(graph, model);
464 Resource activeVisualisation = graph.getPossibleObject(vf, DN.Diagram_hasActiveVisualisation);
465 if (activeVisualisation != null) {
466 return DynamicVisualisations.sizeBarOptions(graph, activeVisualisation);
469 LOGGER.debug("No visualisation folder available for model {}", model);
472 return SizeBarOptions.useDefault();
476 private static class SizeBarOptionsListener implements Listener<SizeBarOptions> {
478 private static final Logger LOGGER = LoggerFactory.getLogger(SizeBarOptionsListener.class);
480 private Consumer<SizeBarOptions> callback;
481 private Supplier<Boolean> isDisposed;
483 public SizeBarOptionsListener(Consumer<SizeBarOptions> callback, Supplier<Boolean> isDisposed) {
484 this.callback = callback;
485 this.isDisposed = isDisposed;
489 public void execute(SizeBarOptions result) {
490 callback.accept(result);
494 public void exception(Throwable t) {
495 LOGGER.error("Could not listen SizeBarOptions", t);
499 public boolean isDisposed() {
500 return isDisposed.get();
504 private static class SizingObjectsRequest extends UnaryRead<Resource, Map<String, DynamicSizeContribution>> {
506 public SizingObjectsRequest(Resource diagram) {
511 public Map<String, DynamicSizeContribution> perform(ReadGraph graph) throws DatabaseException {
512 DistrictNetworkResource DN = DistrictNetworkResource.getInstance(graph);
513 Resource model = graph.syncRequest(new PossibleIndexRoot(parameter));
515 Resource vf = DynamicVisualisations.getVisualisationFolder(graph, model);
517 Resource activeVisualisation = graph.getPossibleObject(vf, DN.Diagram_hasActiveVisualisation);
518 if (activeVisualisation != null) {
519 return DynamicVisualisations.sizeContributions(graph, activeVisualisation);
522 LOGGER.debug("No visualisation folder available for model {}", model);
525 return Collections.emptyMap();
529 private static class SizingObjectsListener implements Listener<Map<String,DynamicSizeContribution>> {
531 private static final Logger LOGGER = LoggerFactory.getLogger(SizingObjectsListener.class);
533 private Consumer<Map<String,DynamicSizeContribution>> callback;
534 private Supplier<Boolean> isDisposed;
536 public SizingObjectsListener(Consumer<Map<String, DynamicSizeContribution>> callback, Supplier<Boolean> isDisposed) {
537 this.callback = callback;
538 this.isDisposed = isDisposed;
542 public void execute(Map<String, DynamicSizeContribution> result) {
543 callback.accept(result);
547 public void exception(Throwable t) {
548 LOGGER.error("Could not listen ColorBarOptions", t);
552 public boolean isDisposed() {
553 return isDisposed.get();