]> gerrit.simantics Code Review - simantics/district.git/commitdiff
Some cleaning and fixing of district functionalities 16/616/1
authorjsimomaa <jani.simomaa@gmail.com>
Mon, 12 Jun 2017 05:31:01 +0000 (08:31 +0300)
committerjsimomaa <jani.simomaa@gmail.com>
Mon, 12 Jun 2017 05:31:01 +0000 (08:31 +0300)
Change-Id: I976cf29c0f606264749025e1998849652cd3c076

28 files changed:
org.simantics.district.maps/src/org/simantics/maps/eclipse/MapPainter.java
org.simantics.district.maps/src/org/simantics/maps/prefs/MapsClientPreferenceInitializer.java
org.simantics.district.maps/src/org/simantics/maps/prefs/MapsClientPreferencePage.java
org.simantics.district.maps/src/org/simantics/maps/prefs/MapsClientPreferences.java
org.simantics.district.maps/src/org/simantics/maps/sg/MapNode.java
org.simantics.district.maps/src/org/simantics/maps/sg/MapScaleNode.java
org.simantics.district.network.ui/src/org/simantics/district/network/ui/DistrictDiagramViewer.java
org.simantics.district.network.ui/src/org/simantics/district/network/ui/DistrictNetworkEdge.java
org.simantics.district.network.ui/src/org/simantics/district/network/ui/NetworkDrawingParticipant.java
org.simantics.district.network.ui/src/org/simantics/district/network/ui/adapters/DistrictNetworkEdgeElement.java
org.simantics.district.network.ui/src/org/simantics/district/network/ui/adapters/DistrictNetworkEdgeElementFactory.java
org.simantics.district.network.ui/src/org/simantics/district/network/ui/adapters/DistrictNetworkVertexElement.java
org.simantics.district.network.ui/src/org/simantics/district/network/ui/adapters/DistrictNetworkVertexElementFactory.java
org.simantics.district.network.ui/src/org/simantics/district/network/ui/nodes/DistrictNetworkEdgeNode.java
org.simantics.district.network.ui/src/org/simantics/district/network/ui/nodes/DistrictNetworkVertexNode.java
org.simantics.district.network.ui/src/org/simantics/district/network/ui/nodes/MapRulerNode.java
org.simantics.district.network.ui/src/org/simantics/district/network/ui/nodes/NetworkDrawingNode.java
org.simantics.district.network.ui/src/org/simantics/district/network/ui/participants/DNTranslateMode.java
org.simantics.district.network.ui/src/org/simantics/district/network/ui/participants/MapRulerPainter.java
org.simantics.maps.server.ui/src/org/simantics/maps/server/ui/prefs/MapsServerPreferencePage.java
org.simantics.maps.server/META-INF/MANIFEST.MF
org.simantics.maps.server/build.properties
org.simantics.maps.server/plugin.xml [new file with mode: 0644]
org.simantics.maps.server/src/org/simantics/district/maps/server/Activator.java
org.simantics.maps.server/src/org/simantics/district/maps/server/TileserverMapnik.java
org.simantics.maps.server/src/org/simantics/district/maps/server/TileserverMapnikInstance.java
org.simantics.maps.server/src/org/simantics/district/maps/server/prefs/MapsServerInitializer.java
org.simantics.maps.server/src/org/simantics/district/maps/server/prefs/MapsServerPreferences.java

index 00f06dea21839e06859a1908524df132a02948d3..ee0c71a6cb54b8767a0aa7acba8ab26decd108c6 100644 (file)
@@ -11,6 +11,8 @@
  *******************************************************************************/
 package org.simantics.maps.eclipse;
 
+import java.awt.geom.AffineTransform;
+
 import org.simantics.g2d.canvas.Hints;
 import org.simantics.g2d.canvas.ICanvasContext;
 import org.simantics.g2d.canvas.impl.AbstractCanvasParticipant;
@@ -60,10 +62,10 @@ public class MapPainter extends AbstractCanvasParticipant {
     protected MapNode node = null;
     protected MapScaleNode scaleNode = null;
 
-    private int scale;
+    private AffineTransform transform;
 
-    public MapPainter(int scale) {
-        this.scale = scale;
+    public MapPainter(AffineTransform transform) {
+        this.transform = transform;
     }
 
     @Override
@@ -102,12 +104,12 @@ public class MapPainter extends AbstractCanvasParticipant {
     @SGInit
     public void initSG(G2DParentNode parent) {
         node = parent.addNode("map", MapNode.class);
-        node.setScale(scale);
+        node.setTransform(transform);
         node.setEnabled(true);
         node.setZIndex(Integer.MIN_VALUE + 999); // Just under the grid
         
         scaleNode = parent.addNode("mapScale", MapScaleNode.class);
-        scaleNode.setScale(scale);
+        scaleNode.setTransform(transform);
         scaleNode.setEnabled(true);
         scaleNode.setZIndex(Integer.MAX_VALUE - 999); // Just under the grid
     }
index 3350ebb2ef46ffa66bca7fd561c84f31cdd55ea8..2f0e61c93b4b9b6a9967da98b2339ea262222b88 100644 (file)
@@ -1,7 +1,10 @@
 package org.simantics.maps.prefs;
 
+import java.util.Arrays;
+import java.util.List;
+
 import org.eclipse.core.runtime.preferences.AbstractPreferenceInitializer;
-import org.eclipse.core.runtime.preferences.DefaultScope;
+import org.osgi.service.prefs.BackingStoreException;
 import org.osgi.service.prefs.Preferences;
 
 public class MapsClientPreferenceInitializer extends AbstractPreferenceInitializer {
@@ -11,7 +14,19 @@ public class MapsClientPreferenceInitializer extends AbstractPreferenceInitializ
 
     @Override
     public void initializeDefaultPreferences() {
-        Preferences node = DefaultScope.INSTANCE.getNode(MapsClientPreferences.P_NODE);
-        node.put(MapsClientPreferences.P_TILESERVER_URL, "http://localhost:8088");
+        Preferences node = MapsClientPreferences.getPreferences();
+        
+        try {
+            String[] keys = node.keys();
+            List<String> keyss = Arrays.asList(keys);
+            if (!keyss.contains(MapsClientPreferences.P_TILESERVER_URL) && node.get(MapsClientPreferences.P_TILESERVER_URL, "").isEmpty()) {
+                String possibleBuiltin = MapsClientPreferences.possibleBuiltinServerURL();
+                if (possibleBuiltin == null)
+                    possibleBuiltin = "";
+                node.put(MapsClientPreferences.P_TILESERVER_URL, possibleBuiltin);
+            }
+        } catch (BackingStoreException e) {
+            e.printStackTrace();
+        }
     }
 }
index ba168368802568a3d51a428961c598d897cdfa85..b81982c98a0fe2d719c0376307a05a47501ed5ea 100644 (file)
@@ -1,6 +1,7 @@
 package org.simantics.maps.prefs;
 
 import org.eclipse.core.runtime.preferences.InstanceScope;
+import org.eclipse.jface.preference.BooleanFieldEditor;
 import org.eclipse.jface.preference.FieldEditor;
 import org.eclipse.jface.preference.FieldEditorPreferencePage;
 import org.eclipse.jface.preference.IPreferenceStore;
@@ -29,8 +30,14 @@ public class MapsClientPreferencePage extends FieldEditorPreferencePage implemen
     @Override
     protected void createFieldEditors() {
         FieldEditor editor = new StringFieldEditor(MapsClientPreferences.P_TILESERVER_URL, "Tileserver URL", getFieldEditorParent());
-        editor.setPreferenceStore(getPreferenceStore());
         addField(editor);
+        
+        BooleanFieldEditor beditor = new BooleanFieldEditor(MapsClientPreferences.P_USE_BUILTIN, "Use builtin server", getFieldEditorParent());
+        addField(beditor);
+    }
+    
+    @Override
+    protected void performApply() {
     }
 
 }
index 5ecfe052dd30ffb78571e8cd12c32ff54ebab7e4..75ad19d6471004b0206a006b46c6d6d0a4222c8e 100644 (file)
@@ -1,8 +1,49 @@
 package org.simantics.maps.prefs;
 
+import java.net.MalformedURLException;
+import java.net.URL;
+
+import org.eclipse.core.runtime.preferences.InstanceScope;
+import org.osgi.service.prefs.Preferences;
+
 public class MapsClientPreferences {
 
     public static final String P_NODE = "org.simantics.district.maps";
     
     public static final String P_TILESERVER_URL = "org.simantics.district.maps.prefs.tileserverURL";
+    public static final String P_USE_BUILTIN = "org.simantics.district.maps.prefs.tileserverURL";
+    
+    // TODO: fix this, currently copied from MapsServerPreferences
+    public static final String P_DEFAULT_PORT = "org.simantics.maps.server.defaultPort";
+    public static final String P_CURRENT_TM2STYLE = "org.simantics.maps.server.currentTM2Style";
+    public static final String P_SERVER_NODE = "org.simantics.maps.server";
+    public static Preferences getServerPreferences() {
+        return InstanceScope.INSTANCE.getNode(P_SERVER_NODE);
+    }
+    
+    public static Preferences getPreferences() {
+        return InstanceScope.INSTANCE.getNode(P_NODE);
+    }
+    
+    public static String tileserverURL() {
+        return getPreferences().get(P_TILESERVER_URL, "");
+    }
+
+    public static boolean useBuiltinServer() {
+        return getPreferences().getBoolean(P_USE_BUILTIN, true);
+    }
+    
+    public static String possibleBuiltinServerURL() {
+        int port = getServerPreferences().getInt(P_DEFAULT_PORT, -1);
+        String style = getServerPreferences().get(P_CURRENT_TM2STYLE, null);
+        if (port != -1 && style != null) {
+            try {
+                return new URL("http", "localhost", port, "/" + style).toString();
+            } catch (MalformedURLException e) {
+                throw new RuntimeException(e);
+            }
+        }
+        return null;
+    }
+
 }
index b8b54e31afa380b30c28a9e773d1122e9fff5d21..84338bfbc62bb4523612cd75aae93e6a4bb47ef8 100644 (file)
@@ -41,6 +41,7 @@ import java.util.concurrent.TimeUnit;
 import org.simantics.maps.WebService;
 import org.simantics.maps.osm.OSMTileProvider;
 import org.simantics.maps.pojo.TileJobQueue;
+import org.simantics.maps.prefs.MapsClientPreferences;
 import org.simantics.maps.tile.IFilter;
 import org.simantics.maps.tile.ITileJobQueue;
 import org.simantics.maps.tile.ITileListener;
@@ -165,11 +166,18 @@ public class MapNode extends G2DNode implements ITileListener  {
         }
     };
 
-    private int scale;
-
     public void init() {
+        // Construct WebService from client properties
+        String url;
+        if (MapsClientPreferences.useBuiltinServer())
+            url = MapsClientPreferences.possibleBuiltinServerURL();
+        else 
+            url = MapsClientPreferences.tileserverURL();
+        if (!url.endsWith("/"))
+            url = url + "/";
+        
         try {
-            ITileProvider provider = new OSMTileProvider(new WebService("http://localhost:8080/mapbox-studio-osm-bright.tm2/"), TILE_PIXEL_SIZE);
+            ITileProvider provider = new OSMTileProvider(new WebService(url), TILE_PIXEL_SIZE);
 
             // Try to load eclipse specific implementation of TileJobQueue, if it doesn't exist, fall back to pojo implementation 
             try {
@@ -223,8 +231,13 @@ public class MapNode extends G2DNode implements ITileListener  {
         if (!enabled)
             return;
 
-        Graphics2D g = (Graphics2D)g2d.create();
-        AffineTransform tr = (AffineTransform)g.getTransform().clone();
+        AffineTransform ot = g2d.getTransform();
+        g2d.transform(transform);
+        
+        AffineTransform tr = g2d.getTransform();
+        
+//        Graphics2D g = (Graphics2D)g2d.create();
+//        AffineTransform tr = (AffineTransform)g.getTransform().clone();
         
         double scaleX = Math.abs(tr.getScaleX());
         double scaleY = Math.abs(tr.getScaleY());
@@ -235,17 +248,17 @@ public class MapNode extends G2DNode implements ITileListener  {
         double offsetX = -tr.getTranslateX();
         double offsetY = -tr.getTranslateY();
 
-        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
+        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
 
         Rectangle2D sp = localToControl(new Rectangle2D.Double(0.0, 0.0, 1.0, 1.0));
-        Rectangle2D b = (Rectangle2D)((Rectangle)g.getRenderingHint(G2DRenderingHints.KEY_CONTROL_BOUNDS)).getBounds2D(); // getClipBounds is not accurate enough, use original clipbounds and scale here
+        Rectangle2D b = (Rectangle2D)((Rectangle)g2d.getRenderingHint(G2DRenderingHints.KEY_CONTROL_BOUNDS)).getBounds2D(); // getClipBounds is not accurate enough, use original clipbounds and scale here
 
         Rectangle2D viewbox = new Rectangle2D.Double(offsetX/scaleX, offsetY/scaleY, b.getWidth()/sp.getWidth(), b.getHeight()/sp.getHeight()); //g.getClipBounds();
         if(viewbox == null) return; // FIXME
 
         double smallerViewboxDimension = viewbox.getWidth() < viewbox.getHeight() ? viewbox.getWidth() * MAP_SCALE : viewbox.getHeight() * MAP_SCALE;
         int level = 0;
-        double tileSize = get360Scaled() * MAP_SCALE*2;
+        double tileSize = 360 * MAP_SCALE*2;
         while (level < MAX_TILE_LEVEL) {
             double ratio = smallerViewboxDimension / tileSize;
             if (ratio >= 0.85) {
@@ -254,7 +267,6 @@ public class MapNode extends G2DNode implements ITileListener  {
             tileSize *= 0.5;
             level++;
         }
-        System.out.println("level " + level);
         /*
          *  To convert y-coordinates to map coordinates in ruler, use:
          *    double val = (y-offsetY)/scaleY;
@@ -262,45 +274,39 @@ public class MapNode extends G2DNode implements ITileListener  {
          *    String str = formatValue(val);
          */
 
-        double minx = Math.min(get180Scaled(), Math.max(viewbox.getMinX(), -get180Scaled()));
-        double maxx = Math.min(get180Scaled(), Math.max(viewbox.getMaxX(), -get180Scaled()));
+        double minx = Math.min(180, Math.max(viewbox.getMinX(), -180));
+        double maxx = Math.min(180, Math.max(viewbox.getMaxX(), -180));
 
-        double miny = Math.min(get360Scaled(), Math.max(viewbox.getMinY()+get180Scaled(), 0));
-        double maxy = Math.min(get360Scaled(), Math.max(viewbox.getMaxY()+get180Scaled(), 0));
+        double miny = Math.min(360, Math.max(viewbox.getMinY()+180, 0));
+        double maxy = Math.min(360, Math.max(viewbox.getMaxY()+180, 0));
 
-        g.setTransform(new AffineTransform());
-        g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
+        g2d.setTransform(new AffineTransform());
+        g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
 
         int levels = (1 << level);
 
         // http://wiki.openstreetmap.org/wiki/Slippy_map_tilenames
-        int left = (int)Math.floor( (minx + get180Scaled()) / get360Scaled() * (1<<level) );
-        int right = (int)Math.floor( (maxx + get180Scaled()) / get360Scaled() * (1<<level) );
-        int top = (int)Math.floor(miny / get360Scaled() * (1<<level));//  (int)Math.floor( (1 - Math.log(Math.tan(Math.toRadians(miny)) + 1 / Math.cos(Math.toRadians(miny))) / Math.PI) / 2 * (1<<level) );
-        int bottom = (int)Math.floor(maxy / get360Scaled() * (1<<level));//  (int)Math.floor( (1 - Math.log(Math.tan(Math.toRadians(maxy)) + 1 / Math.cos(Math.toRadians(maxy))) / Math.PI) / 2 * (1<<level) );
+        int left = (int)Math.floor( (minx + 180) / 360 * (1<<level) );
+        int right = (int)Math.floor( (maxx + 180) / 360 * (1<<level) );
+        int top = (int)Math.floor(miny / 360 * (1<<level));//  (int)Math.floor( (1 - Math.log(Math.tan(Math.toRadians(miny)) + 1 / Math.cos(Math.toRadians(miny))) / Math.PI) / 2 * (1<<level) );
+        int bottom = (int)Math.floor(maxy / 360 * (1<<level));//  (int)Math.floor( (1 - Math.log(Math.tan(Math.toRadians(maxy)) + 1 / Math.cos(Math.toRadians(maxy))) / Math.PI) / 2 * (1<<level) );
 
-        double tsx = get360Scaled() / (double)levels; // Size of tile on zoom level
+        double tsx = 360 / (double)levels; // Size of tile on zoom level
         for(int tx = left; tx <= right; tx++) {
             if(tx < 0 || tx >= levels) continue;
             for(int ty = top; ty <= bottom; ty++) {
                 if(ty < 0 || ty >= levels) continue;
                 TileKey tile = new TileKey(level, tx, ty);
                 double y = (double)ty - (double)levels/2; // In level 0 we have only one tile
-                paintTile(tileCache, g, tr, tile, tx*tsx-get180Scaled(), y*tsx, tsx);
+                paintTile(tileCache, g2d, tr, tile, tx*tsx-180, y*tsx, tsx);
             }
         }
-        g.dispose();
+//        g.dispose();
 
         // Check if transform has changed
         transformChanged(tr, level);
-    }
-
-    private double get360Scaled() {
-        return 360 * scale;
-    }
-    
-    private double get180Scaled() {
-        return 180 * scale;
+        
+        g2d.setTransform(ot);
     }
 
     @Override
@@ -575,8 +581,4 @@ public class MapNode extends G2DNode implements ITileListener  {
         repaint();
     }
 
-    public void setScale(int scale) {
-        this.scale = scale;
-    }
-
 }
\ No newline at end of file
index a0242c11d502781fac0a69e7b3511b6178e09a3c..793550b6087b05b92694b36e0291ab85ae6ce30c 100644 (file)
@@ -28,13 +28,14 @@ public class MapScaleNode extends G2DNode {
 
     protected double           gridSize          = 1.0;
 
-    private double scale;
-
     @Override
     public void render(Graphics2D g) {
         if (!enabled)
             return;
 
+        AffineTransform ot = g.getTransform();
+        g.transform(transform);
+        
         AffineTransform tr = g.getTransform();
         double scaleX = Math.abs(tr.getScaleX());
         double scaleY = Math.abs(tr.getScaleY());
@@ -129,7 +130,7 @@ public class MapScaleNode extends G2DNode {
             label += stepX;
         }
 
-        g.setTransform(tr);
+        g.setTransform(ot);
     }
 
     @Override
@@ -199,10 +200,6 @@ public class MapScaleNode extends G2DNode {
         this.enabled = enabled;
     }
 
-    public void setScale(double scale) {
-        this.scale = scale;
-    }
-    
     @Override
     public void init() {
         try {
@@ -225,11 +222,11 @@ public class MapScaleNode extends G2DNode {
     }
     
     public double getMeterPerPixel(double screenX, double screenY, double scaleX, double scaleY) {
-        double startLon = (screenX / scaleX) / scale;
-        double val = (screenY / scaleY) / scale;
+        double startLon = (screenX / scaleX);
+        double val = (screenY / scaleY);
         val = Math.toDegrees(Math.atan(Math.sinh(Math.toRadians(val))));
         double startLat = val;
-        double endLon = ((screenX + 1) / scaleX) / scale;
+        double endLon = ((screenX + 1) / scaleX);
         double endLat = val;
         
         calculator.setStartingGeographicPoint(startLon, startLat);
index 47a7bc5f12570f26a55cf9182a19835329574150..c150654c46039f090b76239cf4cdf0a911b6319e 100644 (file)
@@ -15,6 +15,7 @@ import org.simantics.g2d.participant.BackgroundPainter;
 import org.simantics.g2d.participant.GridPainter;
 import org.simantics.g2d.participant.PanZoomRotateHandler;
 import org.simantics.g2d.participant.RenderingQualityInteractor;
+import org.simantics.maps.MapScalingTransform;
 import org.simantics.maps.eclipse.MapPainter;
 import org.simantics.modeling.ui.diagramEditor.DiagramViewer;
 import org.simantics.utils.datastructures.hints.IHintContext;
@@ -28,9 +29,9 @@ public class DistrictDiagramViewer extends DiagramViewer {
         ctx.add(new ElementPainter());
         ctx.add(new DNPointerInteractor());
         
-        ctx.add(new MapPainter(100000));
+        ctx.add(new MapPainter(MapScalingTransform.INSTANCE));
         
-        ctx.add(new NetworkDrawingParticipant());
+        ctx.add(new NetworkDrawingParticipant(MapScalingTransform.INSTANCE));
     }
     
     protected String getPopupId() {
index c5021ff11a1ea40c012acf394a90162374a03405..28ac19707fe12a7811f51874113e4afb6a19842b 100644 (file)
@@ -1,25 +1,23 @@
 package org.simantics.district.network.ui;
 
-import java.awt.geom.Path2D;
 import java.awt.geom.Point2D;
-import java.awt.geom.Point2D.Double;
-import java.awt.geom.Rectangle2D;
 
 public class DistrictNetworkEdge {
 
-    private Path2D path;
+    private Point2D startPoint;
+    private Point2D endPoint;
 
-    public DistrictNetworkEdge(Path2D path) {
-        this.path = path;
+    public DistrictNetworkEdge(Point2D startPoint, Point2D endPoint) {
+        this.startPoint = startPoint;
+        this.endPoint = endPoint;
     }
 
-    public Path2D getPath() {
-        return path;
+    public Point2D getStartPoint() {
+        return startPoint;
     }
 
-    public Rectangle2D getBounds(Rectangle2D rect) {
-        rect.setFrame(path.getBounds2D());
-        return rect;
+    public Point2D getEndPoint() {
+        return endPoint;
     }
 
 }
index a340d8591f625f0fdb78a7de27edaec6b34c3112..aa11d6bb10205817145ed325e3f2c8a88cf948be 100644 (file)
@@ -1,6 +1,7 @@
 
 package org.simantics.district.network.ui;
 
+import java.awt.geom.AffineTransform;
 import java.awt.geom.Point2D;
 import java.util.ArrayList;
 import java.util.List;
@@ -15,6 +16,7 @@ import org.simantics.g2d.diagram.handler.PickContext;
 import org.simantics.g2d.diagram.handler.PickRequest;
 import org.simantics.g2d.diagram.participant.AbstractDiagramParticipant;
 import org.simantics.g2d.element.IElement;
+import org.simantics.maps.MapScalingTransform;
 import org.simantics.scenegraph.g2d.G2DNode;
 import org.simantics.scenegraph.g2d.G2DParentNode;
 import org.simantics.utils.datastructures.hints.IHintContext.Key;
@@ -38,10 +40,17 @@ public class NetworkDrawingParticipant extends AbstractDiagramParticipant {
     public static final double PICK_DIST = 10;
     
     private NetworkDrawingNode node;
+
+    private AffineTransform transform;
     
+    public NetworkDrawingParticipant(AffineTransform transform) {
+        this.transform = transform;
+    }
+
     @SGInit
     public void initSG(G2DParentNode parent) {
         node = parent.addNode("networkDrawingNode", NetworkDrawingNode.class);
+        node.setTransform(transform);
         node.setNetworkDrawingParticipant(this);
     }
     
index a7cd09ac63a522d3dfb6d740f9d67652fa527248..db730b1e6fafcec231b54ecdde6afe73d36e0d57 100644 (file)
@@ -60,6 +60,9 @@ public class DistrictNetworkEdgeElement {
                 node.setColor(ElementUtils.getAdditionalColor(edgeElement, Color.BLUE));
                 
                 node.setDNEdge(edge);
+                AffineTransform at = ElementUtils.getTransform(edgeElement);
+                if (at != null)
+                    node.setTransform(at);
             }
         }
 
@@ -84,7 +87,7 @@ public class DistrictNetworkEdgeElement {
             if (size == null)
                 size = new Rectangle2D.Double();
             if (edge != null)
-                edge.getBounds(size);
+                size.setFrame(DistrictNetworkEdgeNode.calculatePath(edge).getBounds2D());
             else
                 LOGGER.debug("Element {} does not have edge!", e);
 
index c3058a0edf5518341c6389ca61ad188019a0b85c..36d573081b8489bec41274311008eed35f33c624 100644 (file)
@@ -1,6 +1,5 @@
 package org.simantics.district.network.ui.adapters;
 
-import java.awt.geom.Path2D;
 import java.awt.geom.Point2D;
 
 import org.simantics.db.AsyncReadGraph;
@@ -14,7 +13,6 @@ import org.simantics.diagram.synchronization.IModifiableSynchronizationContext;
 import org.simantics.diagram.synchronization.SynchronizationHints;
 import org.simantics.diagram.synchronization.graph.GraphSynchronizationHints;
 import org.simantics.diagram.synchronization.graph.layer.GraphLayerManager;
-import org.simantics.district.network.ModelledCRS;
 import org.simantics.district.network.ontology.DistrictNetworkResource;
 import org.simantics.district.network.ui.DistrictNetworkEdge;
 import org.simantics.g2d.canvas.ICanvasContext;
@@ -55,30 +53,19 @@ public class DistrictNetworkEdgeElementFactory extends SyncElementFactory {
         Resource startVertex = graph.getSingleObject(edgeResource, DN.HasStartVertex);
         Resource endVertex = graph.getSingleObject(edgeResource, DN.HasEndVertex);
 
-        // TODO: fix scale..
-        double scale = 100000;
-        
+        // TODO: Find maybe a better way to apply the scaling 
         double[] startCoords = graph.getRelatedValue2(startVertex, DIA.HasLocation);
-        
-        double startLon = ModelledCRS.longitudeToX(startCoords[0]) * scale;
-        double startLat = ModelledCRS.latitudeToY(startCoords[1]) * scale;
-        
         double[] endCoords = graph.getRelatedValue2(endVertex, DIA.HasLocation);
-
-        double endLon = ModelledCRS.longitudeToX(endCoords[0]) * scale;
-        double endLat = ModelledCRS.latitudeToY(endCoords[1]) * scale;
-        
-        Path2D path = new Path2D.Double();
-        path.moveTo(startLon, startLat);
-        path.lineTo(endLon, endLat);
-        
-        DistrictNetworkEdge edge = new DistrictNetworkEdge(path);
+        DistrictNetworkEdge edge = new DistrictNetworkEdge(new Point2D.Double(startCoords[0], startCoords[1]), new Point2D.Double(endCoords[0], endCoords[1]));
 
         Resource mapping = graph.getSingleObject(edgeResource, DistrictNetworkResource.getInstance(graph).HasMapping);
         element.setHint(DistrictNetworkAdditionalColor.KEY_DN_MAPPING_RESOURCE, mapping);
         
         element.setHint(DistrictNetworkEdgeElement.KEY_DN_EDGE, edge);
         
+        // set scaling transform
+        ElementUtils.setTransform(element, MapScalingTransform.INSTANCE);
+        
         IModifiableSynchronizationContext context = diagram.getHint(SynchronizationHints.CONTEXT);
         GraphLayerManager layerManager = context.get(GraphSynchronizationHints.GRAPH_LAYER_MANAGER);
         
index 24f8459dccba859c40590d1d2ab3a7e61e56e48c..2a0cb1229c783f645d416e28a646af6d22311580 100644 (file)
@@ -74,7 +74,8 @@ public class DistrictNetworkVertexElement {
         @Override
         public Rectangle2D getBounds(IElement e, Rectangle2D size) {
             DistrictNetworkVertexNode node = e.getHint(KEY_DN_VERTEX_NODE);
-            size.setFrame(node.getBoundsInLocal());
+            Rectangle2D boundsInLocal = node.getBoundsInLocal();
+            size.setFrame(boundsInLocal);
             return size;
         }
         
index 6fa19c422a2d9439f36a265650f3b3cc051e7409..431beb52d60280de30d44d5bf31c11c5a129a18e 100644 (file)
@@ -1,7 +1,5 @@
 package org.simantics.district.network.ui.adapters;
 
-import java.awt.geom.AffineTransform;
-
 import org.simantics.db.AsyncReadGraph;
 import org.simantics.db.ReadGraph;
 import org.simantics.db.Resource;
@@ -13,7 +11,6 @@ import org.simantics.diagram.synchronization.IModifiableSynchronizationContext;
 import org.simantics.diagram.synchronization.SynchronizationHints;
 import org.simantics.diagram.synchronization.graph.GraphSynchronizationHints;
 import org.simantics.diagram.synchronization.graph.layer.GraphLayerManager;
-import org.simantics.district.network.ModelledCRS;
 import org.simantics.district.network.ontology.DistrictNetworkResource;
 import org.simantics.g2d.canvas.ICanvasContext;
 import org.simantics.g2d.diagram.DiagramHints;
@@ -23,6 +20,7 @@ import org.simantics.g2d.element.ElementUtils;
 import org.simantics.g2d.element.IElement;
 import org.simantics.g2d.element.handler.impl.StaticObjectAdapter;
 import org.simantics.g2d.layers.ILayersEditor;
+import org.simantics.maps.MapScalingTransform;
 
 public class DistrictNetworkVertexElementFactory extends SyncElementFactory {
 
@@ -55,15 +53,8 @@ public class DistrictNetworkVertexElementFactory extends SyncElementFactory {
         element.setHint(DistrictNetworkAdditionalColor.KEY_DN_MAPPING_RESOURCE, mapping);
         element.setHint(DistrictNetworkVertexElement.KEY_DN_VERTEX, vertex);
         
-        // TODO: set element transform based on layer SRS and coords
-        
-        double x = ModelledCRS.longitudeToX(coords[0]);
-        double y = ModelledCRS.latitudeToY(coords[1]);
-        
-        double scale = 100000;
-        
-        AffineTransform at = new AffineTransform(1, 0, 0, 1, x * scale, y * scale);
-        ElementUtils.setTransform(element, at);
+        // set scaling transform for vertices
+        ElementUtils.setTransform(element, MapScalingTransform.INSTANCE);
         
         IModifiableSynchronizationContext context = diagram.getHint(SynchronizationHints.CONTEXT);
         GraphLayerManager layerManager = context.get(GraphSynchronizationHints.GRAPH_LAYER_MANAGER);
index 9170fa15eb4c495535fe9a46105cc044ace194ab..cd35b2f011329ac926fa0e6d51f8b7a0c5046fe5 100644 (file)
@@ -11,7 +11,6 @@ import java.awt.geom.Point2D;
 import java.awt.geom.Rectangle2D;
 
 import org.simantics.district.network.ModelledCRS;
-import org.simantics.district.network.ontology.DistrictNetworkResource;
 import org.simantics.district.network.ui.DistrictNetworkEdge;
 import org.simantics.scenegraph.g2d.G2DNode;
 import org.simantics.scenegraph.utils.GeometryUtils;
@@ -69,9 +68,9 @@ public class DistrictNetworkEdgeNode extends G2DNode {
                 g2d.setStroke(STROKE);
             }
         }
-        // render
-        g2d.draw(edge.getPath());
 
+        g2d.draw(calculatePath(edge));
+        
         // Reset
         g2d.setStroke(oldStroke);
         g2d.setColor(oldColor);
@@ -81,6 +80,20 @@ public class DistrictNetworkEdgeNode extends G2DNode {
             g2d.setTransform(ot);
     }
     
+    public static Path2D calculatePath(DistrictNetworkEdge edge) {
+        // Convert to screen coordinates
+        double startX = ModelledCRS.longitudeToX(edge.getStartPoint().getX());
+        double startY = ModelledCRS.latitudeToY(edge.getStartPoint().getY());
+        double endX = ModelledCRS.longitudeToX(edge.getEndPoint().getX());
+        double endY = ModelledCRS.latitudeToY(edge.getEndPoint().getY());
+        
+        // render
+        Path2D path = new Path2D.Double();
+        path.moveTo(startX, startY);
+        path.lineTo(endX, endY);
+        return path;
+    }
+
     private boolean isSelected() {
         return NodeUtil.isSelected(this, 1);
     }
@@ -98,7 +111,7 @@ public class DistrictNetworkEdgeNode extends G2DNode {
     }
 
     private Rectangle2D calculateBounds(Rectangle2D rect) {
-        return edge.getBounds(rect);
+        return calculatePath(edge).getBounds2D();
     }
 
     public void setDNEdge(DistrictNetworkEdge edge) {
index e9d0713ddb2d4bb34758ad8e279cacae64308263..011d682eb2a419f9dc7e02e4706e39c16850d24c 100644 (file)
@@ -37,6 +37,8 @@ public class DistrictNetworkVertexNode extends G2DNode {
 
     private Color color;
 
+    private Rectangle2D bounds;
+
     @Override
     public void init() {
         setZIndex(2);
@@ -68,11 +70,14 @@ public class DistrictNetworkVertexNode extends G2DNode {
         }
         scaleRecip = 8.0 * scaleRecip;
         
+        // Translate lat and lon to X and Y
+        Point2D res = calculatePoint2D(vertex);
+        
         Rectangle2D toDraw;
         if (hover) {
-            toDraw = new Rectangle2D.Double(HOVERED.getX() * scaleRecip, HOVERED.getY() * scaleRecip, HOVERED.getWidth() * scaleRecip, HOVERED.getHeight() * scaleRecip);
+            toDraw = new Rectangle2D.Double(res.getX() - (HOVERED.getWidth() / 2 * scaleRecip), res.getY() - (HOVERED.getHeight() / 2 * scaleRecip), HOVERED.getWidth() * scaleRecip, HOVERED.getHeight() * scaleRecip);
         } else {
-            toDraw = new Rectangle2D.Double(NORMAL.getX() * scaleRecip, NORMAL.getY() * scaleRecip, NORMAL.getWidth() * scaleRecip, NORMAL.getHeight() * scaleRecip);
+            toDraw = new Rectangle2D.Double(res.getX() - (NORMAL.getWidth() / 2 * scaleRecip), res.getY() - (NORMAL.getHeight() / 2 * scaleRecip), NORMAL.getWidth() * scaleRecip, NORMAL.getHeight() * scaleRecip);
         }
         // render
         g2d.fill(toDraw);
@@ -87,15 +92,49 @@ public class DistrictNetworkVertexNode extends G2DNode {
             g2d.setTransform(ot);
     }
 
+    @Override
+    public Rectangle2D getBounds() {
+        return super.getBounds();
+    }
+    
     @Override
     public Rectangle2D getBoundsInLocal() {
-        if (hover)
-            return HOVERED;
-        return NORMAL;
+        return bounds;
+    }
+    
+    private void updateBounds() {
+        Rectangle2D oldBounds = bounds;
+        if (oldBounds == null)
+            oldBounds = new Rectangle2D.Double();
+        bounds = calculateBounds(oldBounds);
+    }
+
+    @Override
+    public void setTransform(AffineTransform transform) {
+        super.setTransform(transform);
+        // Update bounds
+        updateBounds();
+    }
+    
+    private Rectangle2D calculateBounds(Rectangle2D rect) {
+        Point2D calcPoint = calculatePoint2D(vertex);
+        AffineTransform at = getTransform();
+        return new Rectangle2D.Double(calcPoint.getX(), calcPoint.getY(), 1 / at.getScaleX(), 1 / at.getScaleY()).getBounds2D();
+    }
+
+    private static Point2D calculatePoint2D(DistrictNetworkVertex vertex) {
+        Point2D point= vertex.getPoint();
+        double x = ModelledCRS.longitudeToX(point.getX());
+        double y = ModelledCRS.latitudeToY(point.getY());
+
+        // Apply the scaling
+        Point2D res = new Point2D.Double(x, y);
+        return res;
     }
 
     public void setVertex(DistrictNetworkVertex vertex) {
         this.vertex = vertex;
+        updateBounds();
     }
     
     public boolean hover(boolean hover) {
index ba22aa42aabc61dfa674cde72ed41a9b623d33ca..b19c39bf1f4e5ddd4c16e1899ac105685745bbc4 100644 (file)
@@ -9,18 +9,12 @@ public class MapRulerNode extends RulerNode {
 
     @Override
     protected double modifyHorizontalValue(double value) {
-        // TODO: fix scale!
-        double scale = 100000;
-//        double scale = 1;
-        return ModelledCRS.xToLongitude(value / scale);
+        return ModelledCRS.xToLongitude(value);
     }
 
     @Override
     protected double modifyVerticalValue(double value) {
-        // TODO: fix scale!
-        double scale = 100000;
-//        double scale = 1;
-        return ModelledCRS.yToLatitude(value / scale);
+        return ModelledCRS.yToLatitude(value);
     }
 
 }
index b2c157184f07cf0c96b9eb342b3dc438f7cf53b8..1ccde2c7b18db0c459648af546428b57c3205428 100644 (file)
@@ -163,13 +163,14 @@ public class NetworkDrawingNode extends G2DNode {
          *    String str = formatValue(val);
          */
         // TODO: fix scale
-        double scale = 100000;
-//        double scale = 1;
-        double startLat = ModelledCRS.yToLatitude(start.getY() / scale);
-        double startLon = ModelledCRS.xToLongitude(start.getX() / scale);
+        double scaleY = getTransform().getScaleY();
+        double scaleX = getTransform().getScaleX();
         
-        double endLat = ModelledCRS.yToLatitude(end.getY() / scale);
-        double endLon = ModelledCRS.xToLongitude(end.getX() / scale);
+        double startLat = ModelledCRS.yToLatitude(start.getY() / scaleY);
+        double startLon = ModelledCRS.xToLongitude(start.getX() / scaleX);
+        
+        double endLat = ModelledCRS.yToLatitude(end.getY() / scaleY);
+        double endLon = ModelledCRS.xToLongitude(end.getX() / scaleX);
         
         double[] startCoords = new double[] { startLon, startLat };
         double[] endCoords = new double[] { endLon, endLat };
@@ -179,7 +180,7 @@ public class NetworkDrawingNode extends G2DNode {
             
             @Override
             public void perform(WriteGraph graph) throws DatabaseException {
-                builder.create(graph, startCoords, endCoords, padding / scale);
+                builder.create(graph, startCoords, endCoords, 1 / padding);
             }
         });
         
index 7bec07dc138507ae14f4b344081e8d5b5c9c4fcf..8603add13e995f670265ec0845abfe2476210e84 100644 (file)
@@ -2,6 +2,7 @@ package org.simantics.district.network.ui.participants;
 
 import java.awt.geom.AffineTransform;
 import java.awt.geom.Point2D;
+import java.awt.geom.Rectangle2D;
 import java.util.ArrayList;
 import java.util.Collection;
 
@@ -16,6 +17,8 @@ import org.simantics.diagram.elements.ElementTransforms.TransformedObject;
 import org.simantics.diagram.stubs.DiagramResource;
 import org.simantics.district.network.ModelledCRS;
 import org.simantics.district.network.ontology.DistrictNetworkResource;
+import org.simantics.district.network.ui.adapters.DistrictNetworkVertexElement;
+import org.simantics.district.network.ui.nodes.DistrictNetworkVertexNode;
 import org.simantics.g2d.canvas.Hints;
 import org.simantics.g2d.diagram.participant.pointertool.TranslateMode;
 import org.simantics.g2d.element.ElementUtils;
@@ -45,6 +48,10 @@ public class DNTranslateMode extends TranslateMode {
                     DistrictNetworkResource DN = DistrictNetworkResource.getInstance(graph);
                     DiagramResource DIA = DiagramResource.getInstance(graph);
                     for (IElement e : elementsToReallyTranslate) {
+                        
+                        DistrictNetworkVertexNode node = e.getHint(DistrictNetworkVertexElement.KEY_DN_VERTEX_NODE);
+                        Rectangle2D bounds = node.getBounds();
+                        
                         Object obj = ElementUtils.getObject(e);
                         if (obj instanceof Resource) {
                             Resource res = (Resource) obj;
@@ -53,11 +60,9 @@ public class DNTranslateMode extends TranslateMode {
                                 
                                 double x = at.getTranslateX();
                                 double y = at.getTranslateY();
-                                // TODO: Fix scale!
-                                double scale = 100000;
-//                                double scale = 1;
-                                double lat = ModelledCRS.yToLatitude(y / scale);
-                                double lon = ModelledCRS.xToLongitude(x / scale);
+
+                                double lat = ModelledCRS.yToLatitude(y / at.getScaleY());
+                                double lon = ModelledCRS.xToLongitude(x / at.getScaleX());
                                 
                                 // write to db
                                 double[] coords = new double[] { lon, lat };
index d614610f8dac65feeeea12cea91a9cbd9708b596..ecdbf275d207f2eeb9f1f3c8554db97e672f93bb 100644 (file)
@@ -1,10 +1,22 @@
 package org.simantics.district.network.ui.participants;
 
 import org.simantics.district.network.ui.nodes.MapRulerNode;
+import org.simantics.g2d.canvas.impl.SGNodeReflection.SGInit;
 import org.simantics.g2d.participant.RulerPainter;
+import org.simantics.maps.MapScalingTransform;
+import org.simantics.scenegraph.g2d.G2DParentNode;
 
 public class MapRulerPainter extends RulerPainter {
 
+    @SGInit
+    @Override
+    public void initSG(G2DParentNode parent) {
+        node = parent.addNode("ruler", getNodeClass());
+        node.setTransform(MapScalingTransform.INSTANCE);
+        node.setZIndex(PAINT_PRIORITY);
+        updateNode();
+    }
+    
     @Override
     protected Class<MapRulerNode> getNodeClass() {
         return MapRulerNode.class;
index 548daf310fe663ab277a96f2185d6a40c888d6e3..6dc96877b2e56957d54167891f9d6a827c863ea6 100644 (file)
@@ -2,6 +2,9 @@ package org.simantics.maps.server.ui.prefs;
 
 import java.io.IOException;
 import java.net.URISyntaxException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
 import java.util.List;
 
 import org.eclipse.core.runtime.preferences.InstanceScope;
@@ -13,6 +16,8 @@ import org.eclipse.jface.preference.FieldEditorPreferencePage;
 import org.eclipse.jface.preference.FileFieldEditor;
 import org.eclipse.jface.preference.IPreferenceStore;
 import org.eclipse.jface.preference.IntegerFieldEditor;
+import org.eclipse.jface.util.IPropertyChangeListener;
+import org.eclipse.jface.util.PropertyChangeEvent;
 import org.eclipse.swt.SWT;
 import org.eclipse.swt.events.SelectionAdapter;
 import org.eclipse.swt.events.SelectionEvent;
@@ -26,7 +31,6 @@ import org.eclipse.ui.preferences.ScopedPreferenceStore;
 import org.simantics.district.maps.server.TileserverMapnik;
 import org.simantics.district.maps.server.TileserverMapnikInstance;
 import org.simantics.district.maps.server.prefs.MapsServerPreferences;
-import org.simantics.ui.workbench.e4.E4WorkbenchUtils;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -36,6 +40,8 @@ public class MapsServerPreferencePage extends FieldEditorPreferencePage implemen
     
     private TileserverMapnik server;
 
+    private FileFieldEditor addNew;
+
     public MapsServerPreferencePage() {
         super(GRID);
         setDescription("Maps server preferences");
@@ -157,7 +163,8 @@ public class MapsServerPreferencePage extends FieldEditorPreferencePage implemen
                 namesAndValues[i] = nameAndValue;
             }
             
-            ComboFieldEditor selector = new ComboFieldEditor("Styles", "Tile Styles", namesAndValues, parent);
+            ComboFieldEditor selector = new ComboFieldEditor(MapsServerPreferences.P_CURRENT_TM2STYLE, "Tile Styles", namesAndValues, parent);
+            addField(selector);
         } catch (IOException e) {
             e.printStackTrace();
         }
@@ -170,7 +177,7 @@ public class MapsServerPreferencePage extends FieldEditorPreferencePage implemen
         
         createTilesField(tilesGroup);
         
-        GridLayoutFactory.fillDefaults().numColumns(2).equalWidth(false).extendedMargins(12, 12, 12, 12).spacing(5, 4).applyTo(tilesGroup);
+        GridLayoutFactory.fillDefaults().numColumns(3).equalWidth(false).extendedMargins(12, 12, 12, 12).spacing(5, 4).applyTo(tilesGroup);
     }
 
     private void createTilesField(Composite parent) {
@@ -186,15 +193,52 @@ public class MapsServerPreferencePage extends FieldEditorPreferencePage implemen
                 namesAndValues[i] = nameAndValue;
             }
             
-            ComboFieldEditor selector = new ComboFieldEditor("MBTiles", "MBTiles", namesAndValues, parent);
-            
+            ComboFieldEditor selector = new ComboFieldEditor(MapsServerPreferences.P_CURRENT_MBTILES, "MBTiles", namesAndValues, parent);
+            addField(selector);
             
-            FileFieldEditor addNew = new FileFieldEditor("add new", "Add new tiles", parent);
+            addNew = new FileFieldEditor("Add new tiles", "Add new tiles", parent);
+            addNew.setPropertyChangeListener(new IPropertyChangeListener() {
+                
+                @Override
+                public void propertyChange(PropertyChangeEvent event) {
+                    System.out.println(event);
+                }
+            });
             
         } catch (IOException e) {
             LOGGER.error("Could not create tiles field", e);
         }
     }
     
+    @Override
+    protected void performApply() {
+        // Upload new mbtiles file
+        String fileLocation = addNew.getStringValue();
+        if (fileLocation != null && !fileLocation.isEmpty()) {
+            Path p = Paths.get(fileLocation);
+            Path target = server.getDataDirectory().resolve(p.getFileName());
+            try {
+                Files.copy(p, target);
+            } catch (IOException e) {
+                String message = "Could not upload " + fileLocation + " to " + target.toAbsolutePath(); 
+                LOGGER.error(message, e);
+                setErrorMessage(message);
+            }
+        }
+        super.performApply();
+    }
+    
+    @Override
+    public boolean performOk() {
+        boolean success = super.performOk();
+        
+        try {
+            server.restart();
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+        
+        return success;
+    }
 
 }
index 29555240322c158dd567d11372fb376326456216..7f7732307a23de1f532b0c34c8cf070f4978ac09 100644 (file)
@@ -1,7 +1,7 @@
 Manifest-Version: 1.0
 Bundle-ManifestVersion: 2
 Bundle-Name: Server
-Bundle-SymbolicName: org.simantics.maps.server
+Bundle-SymbolicName: org.simantics.maps.server;singleton:=true
 Bundle-Version: 1.0.0.qualifier
 Bundle-Activator: org.simantics.district.maps.server.Activator
 Require-Bundle: org.eclipse.core.runtime,
index 91a69260736d0db1106260eb9ed8e5489a14e18e..c049e419f9868e59e674d8a3c6f5221f8c807884 100644 (file)
@@ -9,4 +9,5 @@ bin.includes = META-INF/,\
                lib/logback-core-1.2.1.jar,\
                lib/snakeyaml-1.18.jar,\
                lib/jna-4.3.0.jar,\
-               lib/zt-process-killer-1.6.jar
+               lib/zt-process-killer-1.6.jar,\
+               plugin.xml
diff --git a/org.simantics.maps.server/plugin.xml b/org.simantics.maps.server/plugin.xml
new file mode 100644 (file)
index 0000000..e19e0d1
--- /dev/null
@@ -0,0 +1,11 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<?eclipse version="3.4"?>
+<plugin>
+   <extension
+         point="org.eclipse.core.runtime.preferences">
+      <initializer
+            class="org.simantics.district.maps.server.prefs.MapsServerInitializer">
+      </initializer>
+   </extension>
+
+</plugin>
index a09545fbf6034587aa74e90f17e7c382e886df9d..65227c669af3fe3ce0d26641a8d1ffdbae6f0ce0 100644 (file)
@@ -15,6 +15,7 @@ public class Activator implements BundleActivator {
 
     public static final String PLUGIN_ID = "org.simantics.maps.server";
     private static BundleContext context;
+    private static Activator defaultt;
 
     static BundleContext getContext() {
         return context;
@@ -28,6 +29,7 @@ public class Activator implements BundleActivator {
      */
     public void start(BundleContext bundleContext) throws Exception {
         Activator.context = bundleContext;
+        Activator.defaultt = this;
     }
 
     /*
@@ -38,6 +40,7 @@ public class Activator implements BundleActivator {
      */
     public void stop(BundleContext bundleContext) throws Exception {
         Activator.context = null;
+        Activator.defaultt = null;
     }
 
     public static Path getNodeJSRoot() throws IOException, URISyntaxException {
@@ -55,4 +58,8 @@ public class Activator implements BundleActivator {
         return Paths.get(encodedUri);
     }
 
+    public static Activator getDefault() {
+        return defaultt;
+    }
+
 }
index 8f3135dc567c2ddf18124bfaa7a70c14c77dbab1..5b1e735c2ee0f60345cd0e6bcde0c1b709b35b49 100644 (file)
@@ -16,6 +16,7 @@ import java.util.concurrent.TimeUnit;
 import java.util.concurrent.atomic.AtomicBoolean;
 import java.util.stream.Stream;
 
+import org.simantics.district.maps.server.prefs.MapsServerPreferences;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.yaml.snakeyaml.Yaml;
@@ -38,17 +39,11 @@ public class TileserverMapnik {
     
     private SystemProcess process;
     private Path serverRoot;
-    private int port;
     
     private AtomicBoolean running = new AtomicBoolean(false);
     
-    TileserverMapnik(Path serverRoot, int port) {
+    TileserverMapnik(Path serverRoot) {
         this.serverRoot = serverRoot.normalize();
-        this.port = port;
-    }
-    
-    public void setPort(int port) {
-        this.port = port;
     }
 
     public boolean isRunning() throws IOException, InterruptedException {
@@ -80,7 +75,7 @@ public class TileserverMapnik {
             return;
         
         StartedProcess startedProcess = new ProcessExecutor().directory(serverRoot.resolve("tileserver-mapnik").toFile()).destroyOnExit().environment(getEnv())
-                .command(NodeJS.executable().toString(), getTessera().toString(), "-c", getConfigJson().toString())
+                .command(NodeJS.executable().toString(), getTessera().toString(), "-c", getConfigJson().toString(), "-p", Integer.toString(MapsServerPreferences.defaultPort()))
                 .redirectOutput(Slf4jStream.ofCaller().asDebug()).start();
         
         Process nativeProcess = startedProcess.getProcess();
@@ -176,7 +171,7 @@ public class TileserverMapnik {
     }
     
     public List<String> availableMBTiles() throws IOException {
-        Path data = serverRoot.resolve("data").toAbsolutePath();
+        Path data = getDataDirectory();
         List<String> result = new ArrayList<>();
         try (Stream<Path> paths = Files.walk(data)) {
             paths.forEach(p -> {
@@ -192,7 +187,7 @@ public class TileserverMapnik {
     private void checkConfigJson() throws JsonParseException, JsonMappingException, IOException {
         Path configJson = getConfigJson();
         Map<String, Object> config = new HashMap<>();
-        Path tm2 = serverRoot.resolve("tm2").toAbsolutePath();
+        Path tm2 = getStyleDirectory();
         try (DirectoryStream<Path> stream = Files.newDirectoryStream(tm2)) {
             stream.forEach(p -> {
                 Path projectYaml = p.resolve("project.yml");
@@ -214,8 +209,20 @@ public class TileserverMapnik {
         mapper.writerWithDefaultPrettyPrinter().writeValue(Files.newOutputStream(configJson, StandardOpenOption.TRUNCATE_EXISTING), config);
     }
     
+    public Path getStyleDirectory() {
+        return serverRoot.resolve("tm2");
+    }
+    
+    public Path getDataDirectory() {
+        return serverRoot.resolve("data");
+    }
+    
+    public Path getCurrentTiles() {
+        return getDataDirectory().resolve(MapsServerPreferences.currentMBTiles());
+    }
+    
     public void checkTm2Styles() {
-        Path tm2 = serverRoot.resolve("tm2").toAbsolutePath();
+        Path tm2 = getStyleDirectory();
         try (DirectoryStream<Path> stream = Files.newDirectoryStream(tm2)) {
             stream.forEach(p -> {
                 Path projectYaml = p.resolve("project.yml");
@@ -224,8 +231,7 @@ public class TileserverMapnik {
                 try (InputStream input = Files.newInputStream(projectYaml, StandardOpenOption.READ)) {
                     data = yaml.loadAs(input, Map.class);
                     
-                    Path tiles = serverRoot.relativize(serverRoot.resolve("data").resolve("helsinki_finland.mbtiles"));//.toAbsolutePath().toString().replace("\\", "/");
-                    
+                    Path tiles = serverRoot.relativize(getCurrentTiles());
                     
                     String tmStyle = "mbtiles://../" + tiles.toString();
                     data.put("source", tmStyle);
@@ -246,7 +252,7 @@ public class TileserverMapnik {
 
     public List<String> listStyles() throws IOException {
         List<String> results = new ArrayList<>();
-        Path tm2 = serverRoot.resolve("tm2").toAbsolutePath();
+        Path tm2 = getStyleDirectory();
         try (DirectoryStream<Path> stream = Files.newDirectoryStream(tm2)) {
             stream.forEach(p -> {
                 results.add(p.getFileName().toString());
index 192a0ea694bb287374c4c58f9c6c270d84e9d7ad..18b6bca64046713a60deffd7b0509fcc000da31b 100644 (file)
@@ -3,15 +3,13 @@ package org.simantics.district.maps.server;
 import java.io.IOException;
 import java.net.URISyntaxException;
 
-import org.simantics.district.maps.server.prefs.MapsServerPreferences;
-
 public class TileserverMapnikInstance {
 
     private static TileserverMapnik INSTANCE;
     
     public static synchronized TileserverMapnik get() throws IOException, URISyntaxException {
         if (INSTANCE == null)
-            INSTANCE = new TileserverMapnik(Activator.getTileserverMapnikRoot(), MapsServerPreferences.defaultPort());
+            INSTANCE = new TileserverMapnik(Activator.getTileserverMapnikRoot());
         return INSTANCE;
     }
 }
index 7fa25dd82da095483451e7acafd69188da319f57..365a9ee8bc5ca401baeb5067fca9d7e247795eb7 100644 (file)
@@ -1,6 +1,10 @@
 package org.simantics.district.maps.server.prefs;
 
+import java.util.Arrays;
+import java.util.List;
+
 import org.eclipse.core.runtime.preferences.AbstractPreferenceInitializer;
+import org.osgi.service.prefs.BackingStoreException;
 import org.osgi.service.prefs.Preferences;
 
 public class MapsServerInitializer extends AbstractPreferenceInitializer {
@@ -9,8 +13,17 @@ public class MapsServerInitializer extends AbstractPreferenceInitializer {
     public void initializeDefaultPreferences() {
         Preferences node = MapsServerPreferences.getPreferences();
         
-        node.putBoolean(MapsServerPreferences.P_START_AUTOMATICALLY, true);
-        node.putInt(MapsServerPreferences.P_DEFAULT_PORT, 8080);
+        try {
+            String[] keys = node.keys();
+            List<String> keyss = Arrays.asList(keys);
+            if (!keyss.contains(MapsServerPreferences.P_START_AUTOMATICALLY)) {
+                node.putBoolean(MapsServerPreferences.P_START_AUTOMATICALLY, true);
+            }
+            if (!keyss.contains(MapsServerPreferences.P_DEFAULT_PORT)) {
+                node.putInt(MapsServerPreferences.P_DEFAULT_PORT, 8080);
+            }
+        } catch (BackingStoreException e) {
+            e.printStackTrace();
+        }
     }
-
 }
index b9a5845ec44006fc0d729314c5080efde99ee7d1..85b1a453ba6f4c0a8c0722a1cf113524ff084567 100644 (file)
@@ -1,8 +1,7 @@
 package org.simantics.district.maps.server.prefs;
 
-import org.eclipse.core.runtime.preferences.DefaultScope;
+import org.eclipse.core.runtime.preferences.InstanceScope;
 import org.osgi.service.prefs.Preferences;
-//import org.simantics.maps.server.ui.Activator;
 import org.simantics.district.maps.server.Activator;
 
 public class MapsServerPreferences {
@@ -12,9 +11,13 @@ public class MapsServerPreferences {
     public static final String P_START_AUTOMATICALLY = "org.simantics.maps.server.startAutomatically";
 
     public static final String P_DEFAULT_PORT = "org.simantics.maps.server.defaultPort";
+    
+    public static final String P_CURRENT_MBTILES = "org.simantics.maps.server.currentMbTiles";
+    
+    public static final String P_CURRENT_TM2STYLE = "org.simantics.maps.server.currentTM2Style";
 
     public static Preferences getPreferences() {
-        return DefaultScope.INSTANCE.getNode(MapsServerPreferences.P_NODE);
+        return InstanceScope.INSTANCE.getNode(MapsServerPreferences.P_NODE);
     }
     
     public static boolean startAutomatically() {
@@ -24,5 +27,13 @@ public class MapsServerPreferences {
     public static int defaultPort() {
         return getPreferences().getInt(P_DEFAULT_PORT, 8080);
     }
+    
+    public static String currentMBTiles() {
+        return getPreferences().get(P_CURRENT_MBTILES, "");
+    }
+    
+    public static String currentTM2Style() {
+        return getPreferences().get(P_CURRENT_TM2STYLE, "");
+    }
 
 }