Changeset 15707 in osm for applications/editors/josm
- Timestamp:
- 2009-06-06T22:25:31+02:00 (16 years ago)
- Location:
- applications/editors/josm/plugins
- Files:
-
- 3 deleted
- 33 edited
-
build.xml (modified) (2 diffs)
-
cadastre-fr/build.xml (modified) (1 diff)
-
cadastre-fr/src/cadastre_fr/WMSLayer.java (modified) (21 diffs)
-
czechaddress/build.xml (modified) (1 diff)
-
openlayers/src/org/openstreetmap/josm/plugins/openLayers/OpenLayersLayer.java (modified) (1 diff)
-
openvisible/build.xml (modified) (1 diff)
-
openvisible/src/at/dallermassl/josm/plugin/openvisible/OpenVisibleAction.java (modified) (2 diffs)
-
routing/build.xml (modified) (1 diff)
-
routing/src/com/innovant/josm/jrt/core/EdgeIterator.java (modified) (1 diff)
-
routing/src/com/innovant/josm/jrt/core/PreferencesKeys.java (modified) (1 diff)
-
routing/src/com/innovant/josm/jrt/core/RoutingEdge.java (modified) (1 diff)
-
routing/src/com/innovant/josm/jrt/core/RoutingGraph.java (modified) (1 diff)
-
routing/src/com/innovant/josm/jrt/core/RoutingGraphDelegator.java (modified) (1 diff)
-
routing/src/com/innovant/josm/jrt/core/RoutingProfile.java (modified) (1 diff)
-
routing/src/com/innovant/josm/jrt/gtfs/GTFSTransportModes.java (modified) (1 diff)
-
routing/src/com/innovant/josm/jrt/osm/OsmEdge.java (modified) (2 diffs)
-
routing/src/com/innovant/josm/jrt/osm/OsmWayTypes.java (modified) (1 diff)
-
routing/src/com/innovant/josm/plugin/routing/RoutingLayer.java (modified) (11 diffs)
-
routing/src/com/innovant/josm/plugin/routing/RoutingModel.java (modified) (7 diffs)
-
routing/src/com/innovant/josm/plugin/routing/RoutingPlugin.java (modified) (5 diffs)
-
routing/src/com/innovant/josm/plugin/routing/actions/AddRouteNodeAction.java (modified) (4 diffs)
-
routing/src/com/innovant/josm/plugin/routing/actions/MoveRouteNodeAction.java (modified) (4 diffs)
-
routing/src/com/innovant/josm/plugin/routing/actions/RemoveRouteNodeAction.java (modified) (2 diffs)
-
routing/src/com/innovant/josm/plugin/routing/gui/RoutingDialog.java (modified) (1 diff)
-
routing/src/com/innovant/josm/plugin/routing/gui/RoutingMenu.java (modified) (3 diffs)
-
routing/src/com/innovant/josm/plugin/routing/gui/RoutingPreferenceDialog.java (modified) (1 diff)
-
slippymap/build.xml (modified) (1 diff)
-
slippymap/src/org/openstreetmap/josm/plugins/slippymap/SlippyMapLayer.java (modified) (1 diff)
-
tageditor/build.xml (modified) (1 diff)
-
waydownloader (modified) (1 prop)
-
wmsplugin/build.xml (modified) (1 diff)
-
wmsplugin/src/META-INF (deleted)
-
wmsplugin/src/uk (deleted)
-
wmsplugin/src/wmsplugin/OSGBGrabber.java (deleted)
-
wmsplugin/src/wmsplugin/WMSGrabber.java (modified) (1 diff)
-
wmsplugin/src/wmsplugin/WMSLayer.java (modified) (4 diffs)
Legend:
- Unmodified
- Added
- Removed
-
applications/editors/josm/plugins/build.xml
r15167 r15707 37 37 <ant antfile="build.xml" target="dist" dir="utilsplugin"/> 38 38 <ant antfile="build.xml" target="dist" dir="validator"/> 39 <ant antfile="build.xml" target="dist" dir="waydownloader"/> 39 40 <ant antfile="build.xml" target="dist" dir="wmsplugin"/> 40 41 </target> … … 76 77 <ant antfile="build.xml" target="clean" dir="utilsplugin"/> 77 78 <ant antfile="build.xml" target="clean" dir="validator"/> 79 <ant antfile="build.xml" target="clean" dir="waydownloader"/> 78 80 <ant antfile="build.xml" target="clean" dir="wmsplugin"/> 79 81 </target> -
applications/editors/josm/plugins/cadastre-fr/build.xml
r14120 r15707 26 26 <attribute name="Plugin-Description" value="A special handler for the french land registry WMS server."/> 27 27 <attribute name="Plugin-Link" value="http://wiki.openstreetmap.org/wiki/FR:JOSM/Fr:Plugin/Cadastre"/> 28 <attribute name="Plugin-Mainversion" value="1 498"/>28 <attribute name="Plugin-Mainversion" value="1646"/> 29 29 <attribute name="Plugin-Stage" value="60"/> 30 30 <attribute name="Plugin-Version" value="${version.entry.commit.revision}"/> -
applications/editors/josm/plugins/cadastre-fr/src/cadastre_fr/WMSLayer.java
r13784 r15707 25 25 import javax.swing.JOptionPane; 26 26 import javax.swing.JSeparator; 27 import javax.swing.filechooser.FileFilter;28 27 29 28 import org.openstreetmap.josm.Main; 30 import org.openstreetmap.josm.actions. ExtensionFileFilter;29 import org.openstreetmap.josm.actions.DiskAccessAction; 31 30 import org.openstreetmap.josm.data.osm.visitor.BoundingXYVisitor; 32 31 import org.openstreetmap.josm.data.projection.Lambert; … … 46 45 public class WMSLayer extends Layer { 47 46 48 Component[] component = null; 47 Component[] component = null; 49 48 50 49 public int lambertZone = -1; … … 54 53 55 54 protected ArrayList<GeorefImage> images = new ArrayList<GeorefImage>(); 56 55 57 56 protected final int serializeFormatVersion = 2; 58 57 59 58 private ArrayList<EastNorthBound> dividedBbox = new ArrayList<EastNorthBound>(); 60 59 61 60 private CacheControl cacheControl = null; 62 61 63 62 private String location = ""; 64 63 65 64 private String codeCommune = ""; 66 65 67 66 private EastNorthBound communeBBox = new EastNorthBound(new EastNorth(0,0), new EastNorth(0,0)); 68 67 69 68 private boolean isRaster = false; 70 69 71 70 private EastNorth rasterMin; 72 71 73 72 private EastNorth rasterCenter; 74 73 75 74 private double rasterRatio; 76 75 … … 81 80 this(tr("Blank Layer"), "", -1); 82 81 } 83 82 84 83 public WMSLayer(String location, String codeCommune, int lambertZone) { 85 84 super(buildName(location, codeCommune)); … … 90 89 CadastrePlugin.pluginUsed = true; 91 90 } 92 91 93 92 private static String buildName(String location, String codeCommune) { 94 93 String ret = new String(location.toUpperCase()); … … 138 137 139 138 /** 140 * 139 * 141 140 * @param b the original bbox, usually the current bbox on screen 142 141 * @param factor 1 = source bbox 1:1 … … 202 201 public void paint(Graphics g, final MapView mv) { 203 202 for (GeorefImage img : images) 204 img.paint((Graphics2D) g, mv, CadastrePlugin.backgroundTransparent, 203 img.paint((Graphics2D) g, mv, CadastrePlugin.backgroundTransparent, 205 204 CadastrePlugin.transparency, CadastrePlugin.drawBoundaries); 206 205 } … … 244 243 return null; 245 244 } 246 245 247 246 public boolean isOverlapping(Bounds bounds) { 248 GeorefImage georefImage = 247 GeorefImage georefImage = 249 248 new GeorefImage(new BufferedImage(1,1,BufferedImage.TYPE_INT_RGB ), // not really important 250 249 Main.proj.latlon2eastNorth(bounds.min), … … 262 261 } 263 262 } 264 263 265 264 public void saveNewCache() { 266 265 if (CacheControl.cacheEnabled) { … … 270 269 } 271 270 } 272 271 273 272 public CacheControl getCacheControl() { 274 273 if (cacheControl == null) … … 276 275 return cacheControl; 277 276 } 278 277 279 278 public class SaveWmsAction extends AbstractAction { 280 279 private static final long serialVersionUID = 1L; … … 285 284 286 285 public void actionPerformed(ActionEvent ev) { 287 File f = openFileDialog(false); 286 File f = DiskAccessAction.createAndOpenSaveFileChooser( 287 tr("Save WMS layer"), ".wms"); 288 288 try { 289 289 FileOutputStream fos = new FileOutputStream(f); … … 311 311 312 312 public void actionPerformed(ActionEvent ev) { 313 File f = openFileDialog(true); 314 if (f == null) 315 return; 313 JFileChooser fc = DiskAccessAction.createAndOpenFileChooser(true, 314 false, tr("Load WMS layer")); 315 if(fc == null) return; 316 File f = fc.getSelectedFile(); 317 if (f == null) return; 316 318 try { 317 319 FileInputStream fis = new FileInputStream(f); … … 342 344 } 343 345 344 protected static JFileChooser createAndOpenFileChooser(boolean open, boolean multiple) {345 String curDir = Main.pref.get("lastDirectory");346 if (curDir.equals(""))347 curDir = ".";348 JFileChooser fc = new JFileChooser(new File(curDir));349 fc.setMultiSelectionEnabled(multiple);350 for (int i = 0; i < ExtensionFileFilter.filters.length; ++i)351 fc.addChoosableFileFilter(ExtensionFileFilter.filters[i]);352 fc.setAcceptAllFileFilterUsed(true);353 354 int answer = open ? fc.showOpenDialog(Main.parent) : fc.showSaveDialog(Main.parent);355 if (answer != JFileChooser.APPROVE_OPTION)356 return null;357 358 if (!fc.getCurrentDirectory().getAbsolutePath().equals(curDir))359 Main.pref.put("lastDirectory", fc.getCurrentDirectory().getAbsolutePath());360 361 if (!open) {362 File file = fc.getSelectedFile();363 if (file == null364 || (file.exists() && JOptionPane.YES_OPTION != JOptionPane.showConfirmDialog(Main.parent,365 tr("File exists. Overwrite?"), tr("Overwrite"), JOptionPane.YES_NO_OPTION)))366 return null;367 }368 369 return fc;370 }371 372 public static File openFileDialog(boolean open) {373 JFileChooser fc = createAndOpenFileChooser(open, false);374 if (fc == null)375 return null;376 377 File file = fc.getSelectedFile();378 379 String fn = file.getPath();380 if (fn.indexOf('.') == -1) {381 FileFilter ff = fc.getFileFilter();382 if (ff instanceof ExtensionFileFilter)383 fn = "." + ((ExtensionFileFilter) ff).defaultExtension;384 else385 fn += ".osm";386 file = new File(fn);387 }388 return file;389 }390 391 346 /** 392 347 * Convert the eastNorth input coordinates to raster coordinates. … … 434 389 /** 435 390 * Set the eastNorth position in rasterMin which is the 0,0 coordinate (bottom left corner). 436 * The bounds width is the raster width and height is calculate on a fixed image ratio. 391 * The bounds width is the raster width and height is calculate on a fixed image ratio. 437 392 * @param bounds 438 393 */ … … 470 425 img.resize(rasterCenter, proportion); 471 426 } 472 427 473 428 public void rotate(double angle) { 474 429 this.rasterMin = rasterMin.rotate(rasterCenter, angle); … … 476 431 img.rotate(rasterCenter, angle); 477 432 } 478 433 479 434 /** 480 435 * Repaint the LayerList dialog. … … 491 446 } 492 447 } 493 448 494 449 /** 495 450 * Called by CacheControl when a new cache file is created on disk … … 503 458 oos.writeInt(this.lambertZone); 504 459 oos.writeBoolean(this.isRaster); 505 if (this.isRaster) { 460 if (this.isRaster) { 506 461 oos.writeObject(this.rasterMin); 507 462 oos.writeObject(this.rasterCenter); … … 514 469 } 515 470 } 516 471 517 472 /** 518 473 * Called by CacheControl when a cache file is read from disk … … 532 487 this.lambertZone = ois.readInt(); 533 488 this.isRaster = ois.readBoolean(); 534 if (this.isRaster) { 489 if (this.isRaster) { 535 490 this.rasterMin = (EastNorth) ois.readObject(); 536 491 this.rasterCenter = (EastNorth) ois.readObject(); -
applications/editors/josm/plugins/czechaddress/build.xml
r15582 r15707 1 1 <project name="czechaddress" default="dist" basedir="."> 2 <property name="josm.base" value="../../core"/> 3 <property name="josm.jar" value="${josm.base}/dist/josm-custom.jar"/> 4 <property name="josm.doc.dir" value="${josm.base}/doc"/> 2 <property name="josm" location="../../core/dist/josm-custom.jar"/> 5 3 <property name="plugin.dist.dir" value="../../dist"/> 6 4 <property name="plugin.build.dir" value="build"/> 7 <property name="plugin.javadoc.dir" value="doc"/>8 <property name="plugin.basepackage" value="org.openstreetmap.josm.plugins.czechaddress"/>9 <property name="plugin.basepackage.dir" value="org/openstreetmap/josm/plugins/czechaddress"/>10 5 <property name="plugin.jar" value="${plugin.dist.dir}/${ant.project.name}.jar"/> 11 6 <property name="ant.build.javac.target" value="1.5"/> 12 13 <target name="clean">14 <delete dir="${plugin.build.dir}"/>15 <delete dir="${plugin.jar}"/>16 </target>17 7 <target name="init"> 18 8 <mkdir dir="${plugin.build.dir}"/> 19 <mkdir dir="${plugin.build.dir}"/>20 9 </target> 21 22 <target name="compile" 23 depends="init" 24 description="Compile the plugin"> 25 26 <!-- compile the plugin --> 27 <javac srcdir="src" 28 classpath="${josm.jar}" 29 destdir="${plugin.build.dir}" 30 debug="true"/> 31 32 <!-- create the manifest --> 33 <manifest file="${plugin.build.dir}/${plugin.basepackage.dir}/MANIFEST.MF"> 34 <attribute name="Author" value="Radomír Černoch"/> 35 <attribute name="Plugin-Description" value="Creating and handling address nodes and buildings within Czech Republic."/> 36 <attribute name="Plugin-Mainversion" value="1607"/> 37 <attribute name="Plugin-Version" value="0.2.0"/> 38 <attribute name="Plugin-Class" value="${plugin.basepackage}.CzechAddressPlugin"/> 39 </manifest> 40 41 <!-- include the images --> 10 <target name="compile" depends="init"> 11 <echo message="creating ${plugin.jar}"/> 12 <javac srcdir="src" classpath="${josm}" debug="true" destdir="${plugin.build.dir}"> 13 <compilerarg value="-Xlint:deprecation"/> 14 <compilerarg value="-Xlint:unchecked"/> 15 </javac> 16 </target> 17 <target name="dist" depends="compile,revision"> 42 18 <copy todir="${plugin.build.dir}/images"> 43 19 <fileset dir="images"/> 44 20 </copy> 21 <jar destfile="${plugin.jar}" basedir="${plugin.build.dir}"> 22 <manifest> 23 <attribute name="Author" value="Radomír Černoch"/> 24 <attribute name="Plugin-Class" value="org.openstreetmap.josm.plugins.czechaddress.CzechAddressPlugin"/> 25 <attribute name="Plugin-Date" value="${version.entry.commit.date}"/> 26 <attribute name="Plugin-Description" value="Creating and handling address nodes and buildings within Czech Republic."/> 27 <attribute name="Plugin-Link" value="http://wiki.openstreetmap.org/index.php/JOSM/Plugins/SlippyMap"/> 28 <attribute name="Plugin-Mainversion" value="1607"/> 29 <attribute name="Plugin-Version" value="${version.entry.commit.revision}"/> 30 </manifest> 31 </jar> 45 32 </target> 46 47 <target name="dist" 48 depends="compile" 49 description="Create the .jar file for distribution"> 50 <mkdir dir="${plugin.dist.dir}"/> 51 <jar destfile="${plugin.jar}" 52 basedir="${plugin.build.dir}" 53 manifest="${plugin.build.dir}/${plugin.basepackage.dir}/MANIFEST.MF"/> 33 <target name="revision"> 34 <exec append="false" output="REVISION" executable="svn" failifexecutionfails="false"> 35 <env key="LANG" value="C"/> 36 <arg value="info"/> 37 <arg value="--xml"/> 38 <arg value="."/> 39 </exec> 40 <xmlproperty file="REVISION" prefix="version" keepRoot="false" collapseAttributes="true"/> 41 <delete file="REVISION"/> 54 42 </target> 55 56 <target name="doc" description="Create Javadoc API documentation"> 57 <!--<ant antfile="build.xml" target="doc" dir="${josm.base}"/>--> 58 <mkdir dir="${plugin.javadoc.dir}"/> 59 <javadoc sourcepath="src" 60 packagenames="*" 61 destdir="${plugin.javadoc.dir}" 62 use="true" 63 charset="UTF-8"> 64 <doctitle><![CDATA[Czech Address JOSM plugin]]></doctitle> 65 <bottom><![CDATA[<i>Licenced under GPLv3. Bugreports should be sent to 66 <a href='mailto:radomir.cernoch@gmail.com'>Radomír Černoch</a></i>]]> 67 </bottom> 68 <!--<tag name="todo" scope="all" description="To do:"/>--> 69 <link href="http://java.sun.com/j2se/1.5.0/docs/api/"/> 70 <link href="http://developer.java.sun.com/developer/products/xml/docs/api/"/> 71 <!--<link href="file://${user.home}/devel/core/doc"/>--> 72 </javadoc> 43 <target name="clean"> 44 <delete dir="${plugin.build.dir}"/> 45 <delete file="${plugin.jar}"/> 73 46 </target> 74 75 47 <target name="install" depends="dist"> 76 48 <property environment="env"/> 77 <condition property="josm.plugins.dir" 78 value="${env.APPDATA}/JOSM/plugins"79 else="${user.home}/.josm/plugins">80 < and><os family="windows"/></and>49 <condition property="josm.plugins.dir" value="${env.APPDATA}/JOSM/plugins" else="${user.home}/.josm/plugins"> 50 <and> 51 <os family="windows"/> 52 </and> 81 53 </condition> 82 54 <copy file="${plugin.jar}" todir="${josm.plugins.dir}"/> 83 55 </target> 84 85 <!-- Before running "run" target, please "ant dist" the JOSM. -->86 <target name="run" depends="compile">87 <java classname="JOSM" fork="true">88 <jvmarg value="-Xmx1024m"/>89 <jvmarg value="-Xdebug"/>90 <jvmarg value="-ea"/>91 <classpath>92 <pathelement location="${plugin.build.dir}"/>93 <pathelement path="${java.class.path}"/>94 </classpath>95 <classpath>96 <pathelement location="${josm.jar}"/>97 <pathelement path="${java.class.path}"/>98 </classpath>99 </java>100 </target>101 102 56 </project> -
applications/editors/josm/plugins/openlayers/src/org/openstreetmap/josm/plugins/openLayers/OpenLayersLayer.java
r13582 r15707 80 80 new JSeparator(), 81 81 // color, 82 new JMenuItem(new RenameLayerAction( associatedFile, this)),82 new JMenuItem(new RenameLayerAction(getAssociatedFile(), this)), 83 83 new JSeparator(), 84 84 new JMenuItem(new LayerListPopup.InfoAction(this)) }; -
applications/editors/josm/plugins/openvisible/build.xml
r14015 r15707 26 26 <attribute name="Plugin-Dependencies" value="jgrapht-jdk1.5"/> 27 27 <attribute name="Plugin-Description" value="Allows opening gpx/osm files that intersect the currently visible screen area"/> 28 <attribute name="Plugin-Mainversion" value="1 465"/>28 <attribute name="Plugin-Mainversion" value="1646"/> 29 29 <attribute name="Plugin-Stage" value="50"/> 30 30 <attribute name="Plugin-Version" value="${version.entry.commit.revision}"/> -
applications/editors/josm/plugins/openvisible/src/at/dallermassl/josm/plugin/openvisible/OpenVisibleAction.java
r13497 r15707 29 29 import org.openstreetmap.josm.gui.layer.OsmDataLayer; 30 30 import org.openstreetmap.josm.gui.layer.markerlayer.MarkerLayer; 31 import org.openstreetmap.josm.io.GpxImporter; 31 32 import org.openstreetmap.josm.io.GpxReader; 33 import org.openstreetmap.josm.io.OsmImporter; 32 34 import org.openstreetmap.josm.io.OsmReader; 33 35 import org.openstreetmap.josm.tools.Shortcut; … … 100 102 private void openAsData(File file) throws SAXException, IOException, FileNotFoundException { 101 103 String fn = file.getName(); 102 if ( ExtensionFileFilter.filters[ExtensionFileFilter.OSM].acceptName(fn)) {104 if (new OsmImporter().acceptFile(file)) { 103 105 DataSet dataSet = OsmReader.parseDataSet(new FileInputStream(file), null, Main.pleaseWaitDlg); 104 OsmDataLayer layer = new OsmDataLayer(dataSet, f ile.getName(), file);106 OsmDataLayer layer = new OsmDataLayer(dataSet, fn, file); 105 107 Main.main.addLayer(layer); 106 108 } 107 109 else 108 JOptionPane.showMessageDialog(Main.parent, fn+": "+tr("Unknown file extension: {0}", fn.substring(f ile.getName().lastIndexOf('.')+1)));110 JOptionPane.showMessageDialog(Main.parent, fn+": "+tr("Unknown file extension: {0}", fn.substring(fn.lastIndexOf('.')+1))); 109 111 } 110 112 111 113 private void openFileAsGpx(File file) throws SAXException, IOException, FileNotFoundException { 112 114 String fn = file.getName(); 113 if ( ExtensionFileFilter.filters[ExtensionFileFilter.GPX].acceptName(fn)) {115 if (new GpxImporter().acceptFile(file)) { 114 116 GpxReader r = null; 115 117 if (file.getName().endsWith(".gpx.gz")) { -
applications/editors/josm/plugins/routing/build.xml
r14287 r15707 44 44 <attribute name="Plugin-Description" value="Provides routing capabilities."/> 45 45 <attribute name="Plugin-Link" value="http://wiki.openstreetmap.org/index.php/JOSM/Plugins/Routing"/> 46 <attribute name="Plugin-Mainversion" value="1 510"/>46 <attribute name="Plugin-Mainversion" value="1646"/> 47 47 <attribute name="Plugin-Stage" value="50"/> 48 48 <attribute name="Plugin-Version" value="${version.entry.commit.revision}"/> -
applications/editors/josm/plugins/routing/src/com/innovant/josm/jrt/core/EdgeIterator.java
r15106 r15707 3 3 public interface EdgeIterator { 4 4 5 public boolean hasNext();6 7 public RoutingEdge next();5 public boolean hasNext(); 6 7 public RoutingEdge next(); 8 8 9 9 } -
applications/editors/josm/plugins/routing/src/com/innovant/josm/jrt/core/PreferencesKeys.java
r14423 r15707 28 28 29 29 public enum PreferencesKeys { 30 KEY_ACTIVE_ROUTE_COLOR ("routing.active.route.color"),31 KEY_INACTIVE_ROUTE_COLOR ("routing.inactive.route.color"),32 KEY_ROUTE_WIDTH ("routing.route.width"),33 KEY_ROUTE_SELECT ("routing.route.select");30 KEY_ACTIVE_ROUTE_COLOR ("routing.active.route.color"), 31 KEY_INACTIVE_ROUTE_COLOR ("routing.inactive.route.color"), 32 KEY_ROUTE_WIDTH ("routing.route.width"), 33 KEY_ROUTE_SELECT ("routing.route.select"); 34 34 35 public final String key;36 PreferencesKeys (String key) {37 this.key=key;38 }35 public final String key; 36 PreferencesKeys (String key) { 37 this.key=key; 38 } 39 39 40 public String getKey() {return key;};40 public String getKey() {return key;}; 41 41 } -
applications/editors/josm/plugins/routing/src/com/innovant/josm/jrt/core/RoutingEdge.java
r15106 r15707 5 5 public interface RoutingEdge { 6 6 7 public LatLon fromLatLon();7 public LatLon fromLatLon(); 8 8 9 public LatLon toLatLon();10 11 public Object fromV();9 public LatLon toLatLon(); 10 11 public Object fromV(); 12 12 13 public Object toV();13 public Object toV(); 14 14 15 public double getLength();16 17 public void setLength(double length);18 19 public double getSpeed();15 public double getLength(); 16 17 public void setLength(double length); 18 19 public double getSpeed(); 20 20 21 public void setSpeed(double speed);22 23 public boolean isOneway();24 25 public void setOneway(boolean isOneway);21 public void setSpeed(double speed); 22 23 public boolean isOneway(); 24 25 public void setOneway(boolean isOneway); 26 26 27 27 } -
applications/editors/josm/plugins/routing/src/com/innovant/josm/jrt/core/RoutingGraph.java
r15106 r15707 52 52 public class RoutingGraph { 53 53 54 /**54 /** 55 55 * Routing Profile 56 56 */ 57 57 private RoutingProfile routingProfile; 58 58 59 /**60 * Diferent algorithms to apply to the graph.61 */62 public enum Algorithm {63 ROUTING_ALG_DIJKSTRA, ROUTING_ALG_BELLMANFORD64 };65 66 /**67 * Search criteria for the route.68 */69 public enum RouteType {FASTEST,SHORTEST};70 71 /**72 *73 */74 private RouteType routeType;59 /** 60 * Diferent algorithms to apply to the graph. 61 */ 62 public enum Algorithm { 63 ROUTING_ALG_DIJKSTRA, ROUTING_ALG_BELLMANFORD 64 }; 65 66 /** 67 * Search criteria for the route. 68 */ 69 public enum RouteType {FASTEST,SHORTEST}; 70 71 /** 72 * 73 */ 74 private RouteType routeType; 75 75 76 76 /** 77 77 * Associated Osm DataSet 78 78 */ 79 private DataSet data;80 81 /**82 * Logger.83 */84 static Logger logger = Logger.getLogger(RoutingGraph.class);85 86 /**87 * Graph state88 * <code>true</code> Graph in memory.89 * <code>false</code> Graph not created.90 */91 // public boolean graphState;92 93 /**94 * OSM Graph.95 */96 // private DirectedWeightedMultigraph<Node, OsmEdge> graph;97 // private WeightedMultigraph<Node, OsmEdge> graph;98 private Graph<Node, OsmEdge> graph;99 private RoutingGraphDelegator rgDelegator=null;100 101 /**102 * Speeds103 */104 private Map<String,Double> waySpeeds;105 106 /**107 * Default Constructor.108 */109 public RoutingGraph(DataSet data) {110 // this.graphState = false;111 this.graph = null;112 //this.data = data;113 routeType=RouteType.SHORTEST;114 routingProfile=new RoutingProfile("default");115 routingProfile.setOnewayUse(true); // Don't ignore oneways by default116 this.setWaySpeeds(routingProfile.getWaySpeeds());117 logger.debug("Created RoutingGraph");118 }119 120 /**121 * Create OSM graph for routing122 *123 * @return124 */125 public void createGraph() {126 127 logger.debug("Creating Graph...");128 graph = new DirectedWeightedMultigraph<Node, OsmEdge>(OsmEdge.class);129 rgDelegator=new RoutingGraphDelegator(graph);130 rgDelegator.setRouteType(this.routeType);131 // iterate all ways and segments for all nodes:132 for (Way way : data.ways) {133 if (way != null && !way.deleted && this.isvalidWay(way)) {134 Node from = null;135 for (Node to : way.nodes) {136 // Ignore the node if deleted137 if (!to.deleted) {138 graph.addVertex(to);139 if (from != null) {140 addEdge(way, from, to);141 if (!isOneWay(way)){142 addEdge(way, to, from);}143 }144 from = to;145 }146 }147 }148 }149 // graph.vertexSet().size();150 logger.debug("End Create Graph");151 logger.debug("Vertex: "+graph.vertexSet().size());152 logger.debug("Edges: "+graph.edgeSet().size());153 }154 155 /**156 * Compute weight and add edge to the graph157 * @param way158 * @param from159 * @param to160 */161 private void addEdge(Way way,Node from, Node to) {162 double length = from.coor.greatCircleDistance(to.coor);163 164 OsmEdge edge = new OsmEdge(way, from, to);165 edge.setSpeed(12.1);166 graph.addEdge(from, to, edge);167 // weight = getWeight(way);168 double weight = getWeight(way, length);169 setWeight(edge, length);170 logger.debug("edge for way " + way.id171 + "(from node " + from.id + " to node "172 + to.id + ") has weight: " + weight);173 //((GraphDelegator<Node,OsmEdge>) graph).setEdgeWeight(edge, weight);174 ((DirectedWeightedMultigraph<Node,OsmEdge>)graph).setEdgeWeight(edge, weight);175 }176 177 /**178 * Set the weight for the given segment depending on the highway type179 * and the length of the segment. The higher the value, the less it is used180 * in routing.181 *182 * @param way183 * the way.184 * @return185 */186 private void setWeight(OsmEdge osmedge, double length) {187 188 osmedge.setLength(length);189 if (this.waySpeeds.containsKey(osmedge.getWay().get("highway")))190 osmedge.setSpeed(this.waySpeeds.get(osmedge.getWay().get("highway")));191 192 }193 194 /**195 * Returns the weight for the given segment depending on the highway type196 * and the length of the segment. The higher the value, the less it is used197 * in routing.198 *199 * @param way200 * the way.201 * @return202 */203 private double getWeight(Way way, double length) {204 // Default speed if no setting is found205 double speed = 1;206 207 switch (routeType) {208 case SHORTEST:209 // Same speed for all types of ways210 if (this.waySpeeds.containsKey("residential"))211 speed=this.waySpeeds.get("residential");212 break;213 case FASTEST:214 // Each type of way may have a different speed215 if (this.waySpeeds.containsKey(way.get("highway")))216 speed=this.waySpeeds.get(way.get("highway"));217 logger.debug("Speed="+speed);218 break;219 default:220 break;221 }222 // Return the time spent to traverse the way223 return length / speed;224 }225 226 /**227 * Check is One Way.228 *229 * @param way230 * the way.231 * @return <code>true</code> is a one way. <code>false</code> is not a one232 * way.233 */234 private boolean isOneWay(Way way) {235 // FIXME: oneway=-1 is ignored for the moment!236 return way.get("oneway") != null237 || "motorway".equals(way.get("highway"));238 }239 240 /**241 * Check if a Way is correct.242 *243 * @param way244 * The way.245 * @return <code>true</code> is valid. <code>false</code> is not valid.246 */247 public boolean isvalidWay(Way way) {248 if (!way.isTagged())249 return false;250 251 return way.get("highway") != null || way.get("junction") != null252 || way.get("service") != null;253 254 }255 256 public boolean isvalidNode(Node node) {257 return true;258 }259 260 /**261 * Apply selected routing algorithm to the graph.262 *263 * @param nodes264 * Nodes used to calculate path.265 * @param algorithm266 * Algorithm used to compute the path,267 * RoutingGraph.Algorithm.ROUTING_ALG_DIJKSTRA or268 * RoutingGraph.Algorithm.ROUTING_ALG_BELLMANFORD269 * @return new path.270 */271 public List<OsmEdge> applyAlgorithm(List<Node> nodes, Algorithm algorithm) {272 List<OsmEdge> path = new ArrayList<OsmEdge>();273 Graph<Node,OsmEdge> g;274 double totalWeight = 0;275 276 if (graph == null)277 this.createGraph();278 logger.debug("apply algorithm between nodes ");279 280 for (Node node : nodes) {281 logger.debug(node.id);282 }283 logger.debug("-----------------------------------");284 285 // Assign the graph or an undirected view of the graph to g,286 // depending on whether oneway tags are used or not287 if (routingProfile.isOnewayUsed())288 g = graph;289 else290 g = new AsUndirectedGraph<Node, OsmEdge>((DirectedWeightedMultigraph<Node,OsmEdge>)graph);291 //TODO: Problemas no tiene encuenta el tema de oneway.292 switch (algorithm) {293 case ROUTING_ALG_DIJKSTRA:294 logger.debug("Using Dijkstra algorithm");295 DijkstraShortestPath<Node, OsmEdge> routingk = null;296 for (int index = 1; index < nodes.size(); ++index) {297 routingk = new DijkstraShortestPath<Node, OsmEdge>(rgDelegator, nodes298 .get(index - 1), nodes.get(index));299 if (routingk.getPathEdgeList() == null) {300 logger.debug("no path found!");301 break;302 }303 path.addAll(routingk.getPathEdgeList());304 totalWeight += routingk.getPathLength();305 }306 break;307 case ROUTING_ALG_BELLMANFORD:308 logger.debug("Using Bellman Ford algorithm");309 for (int index = 1; index < nodes.size(); ++index) {310 path = BellmanFordShortestPath.findPathBetween(rgDelegator, nodes311 .get(index - 1), nodes.get(index));312 if (path == null) {313 logger.debug("no path found!");314 return null;315 }316 }317 break;318 default:319 logger.debug("Wrong algorithm");320 break;321 }322 323 logger.debug("shortest path found: " + path + "\nweight: "324 + totalWeight);325 return path;326 }327 328 /**329 * Return the number of vertices.330 * @return the number of vertices.331 */332 public int getVertexCount(){333 int value=0;334 if (graph!=null) value=graph.vertexSet().size();335 return value;336 }337 338 /**339 * Return the number of edges.340 * @return the number of edges.341 */342 public int getEdgeCount(){343 int value=0;344 if (graph!=null) value=graph.edgeSet().size();345 return value;346 }347 348 /**349 * @param routeType the routeType to set350 */351 public void setTypeRoute(RouteType routetype) {352 this.routeType = routetype;353 this.rgDelegator.setRouteType(routetype);354 }355 356 /**357 * @return the routeType358 */359 public RouteType getTypeRoute() {360 return routeType;361 }362 363 public Map<String, Double> getWaySpeeds() {364 return waySpeeds;365 }366 367 public void setWaySpeeds(Map<String, Double> waySpeeds) {368 this.waySpeeds = waySpeeds;369 }370 371 public void resetGraph() {372 graph=null;373 }374 375 public RoutingProfile getRoutingProfile() {376 return routingProfile;377 }79 private DataSet data; 80 81 /** 82 * Logger. 83 */ 84 static Logger logger = Logger.getLogger(RoutingGraph.class); 85 86 /** 87 * Graph state 88 * <code>true</code> Graph in memory. 89 * <code>false</code> Graph not created. 90 */ 91 // public boolean graphState; 92 93 /** 94 * OSM Graph. 95 */ 96 // private DirectedWeightedMultigraph<Node, OsmEdge> graph; 97 // private WeightedMultigraph<Node, OsmEdge> graph; 98 private Graph<Node, OsmEdge> graph; 99 private RoutingGraphDelegator rgDelegator=null; 100 101 /** 102 * Speeds 103 */ 104 private Map<String,Double> waySpeeds; 105 106 /** 107 * Default Constructor. 108 */ 109 public RoutingGraph(DataSet data) { 110 // this.graphState = false; 111 this.graph = null; 112 this.data = data; 113 routeType=RouteType.SHORTEST; 114 routingProfile=new RoutingProfile("default"); 115 routingProfile.setOnewayUse(true); // Don't ignore oneways by default 116 this.setWaySpeeds(routingProfile.getWaySpeeds()); 117 logger.debug("Created RoutingGraph"); 118 } 119 120 /** 121 * Create OSM graph for routing 122 * 123 * @return 124 */ 125 public void createGraph() { 126 127 logger.debug("Creating Graph..."); 128 graph = new DirectedWeightedMultigraph<Node, OsmEdge>(OsmEdge.class); 129 rgDelegator=new RoutingGraphDelegator(graph); 130 rgDelegator.setRouteType(this.routeType); 131 // iterate all ways and segments for all nodes: 132 for (Way way : data.ways) { 133 if (way != null && !way.deleted && this.isvalidWay(way)) { 134 Node from = null; 135 for (Node to : way.nodes) { 136 // Ignore the node if deleted 137 if (!to.deleted) { 138 graph.addVertex(to); 139 if (from != null) { 140 addEdge(way, from, to); 141 if (!isOneWay(way)){ 142 addEdge(way, to, from);} 143 } 144 from = to; 145 } 146 } 147 } 148 } 149 // graph.vertexSet().size(); 150 logger.debug("End Create Graph"); 151 logger.debug("Vertex: "+graph.vertexSet().size()); 152 logger.debug("Edges: "+graph.edgeSet().size()); 153 } 154 155 /** 156 * Compute weight and add edge to the graph 157 * @param way 158 * @param from 159 * @param to 160 */ 161 private void addEdge(Way way,Node from, Node to) { 162 double length = from.coor.greatCircleDistance(to.coor); 163 164 OsmEdge edge = new OsmEdge(way, from, to); 165 edge.setSpeed(12.1); 166 graph.addEdge(from, to, edge); 167 // weight = getWeight(way); 168 double weight = getWeight(way, length); 169 setWeight(edge, length); 170 logger.debug("edge for way " + way.id 171 + "(from node " + from.id + " to node " 172 + to.id + ") has weight: " + weight); 173 //((GraphDelegator<Node,OsmEdge>) graph).setEdgeWeight(edge, weight); 174 ((DirectedWeightedMultigraph<Node,OsmEdge>)graph).setEdgeWeight(edge, weight); 175 } 176 177 /** 178 * Set the weight for the given segment depending on the highway type 179 * and the length of the segment. The higher the value, the less it is used 180 * in routing. 181 * 182 * @param way 183 * the way. 184 * @return 185 */ 186 private void setWeight(OsmEdge osmedge, double length) { 187 188 osmedge.setLength(length); 189 if (this.waySpeeds.containsKey(osmedge.getWay().get("highway"))) 190 osmedge.setSpeed(this.waySpeeds.get(osmedge.getWay().get("highway"))); 191 192 } 193 194 /** 195 * Returns the weight for the given segment depending on the highway type 196 * and the length of the segment. The higher the value, the less it is used 197 * in routing. 198 * 199 * @param way 200 * the way. 201 * @return 202 */ 203 private double getWeight(Way way, double length) { 204 // Default speed if no setting is found 205 double speed = 1; 206 207 switch (routeType) { 208 case SHORTEST: 209 // Same speed for all types of ways 210 if (this.waySpeeds.containsKey("residential")) 211 speed=this.waySpeeds.get("residential"); 212 break; 213 case FASTEST: 214 // Each type of way may have a different speed 215 if (this.waySpeeds.containsKey(way.get("highway"))) 216 speed=this.waySpeeds.get(way.get("highway")); 217 logger.debug("Speed="+speed); 218 break; 219 default: 220 break; 221 } 222 // Return the time spent to traverse the way 223 return length / speed; 224 } 225 226 /** 227 * Check is One Way. 228 * 229 * @param way 230 * the way. 231 * @return <code>true</code> is a one way. <code>false</code> is not a one 232 * way. 233 */ 234 private boolean isOneWay(Way way) { 235 // FIXME: oneway=-1 is ignored for the moment! 236 return way.get("oneway") != null 237 || "motorway".equals(way.get("highway")); 238 } 239 240 /** 241 * Check if a Way is correct. 242 * 243 * @param way 244 * The way. 245 * @return <code>true</code> is valid. <code>false</code> is not valid. 246 */ 247 public boolean isvalidWay(Way way) { 248 if (!way.isTagged()) 249 return false; 250 251 return way.get("highway") != null || way.get("junction") != null 252 || way.get("service") != null; 253 254 } 255 256 public boolean isvalidNode(Node node) { 257 return true; 258 } 259 260 /** 261 * Apply selected routing algorithm to the graph. 262 * 263 * @param nodes 264 * Nodes used to calculate path. 265 * @param algorithm 266 * Algorithm used to compute the path, 267 * RoutingGraph.Algorithm.ROUTING_ALG_DIJKSTRA or 268 * RoutingGraph.Algorithm.ROUTING_ALG_BELLMANFORD 269 * @return new path. 270 */ 271 public List<OsmEdge> applyAlgorithm(List<Node> nodes, Algorithm algorithm) { 272 List<OsmEdge> path = new ArrayList<OsmEdge>(); 273 Graph<Node,OsmEdge> g; 274 double totalWeight = 0; 275 276 if (graph == null) 277 this.createGraph(); 278 logger.debug("apply algorithm between nodes "); 279 280 for (Node node : nodes) { 281 logger.debug(node.id); 282 } 283 logger.debug("-----------------------------------"); 284 285 // Assign the graph or an undirected view of the graph to g, 286 // depending on whether oneway tags are used or not 287 if (routingProfile.isOnewayUsed()) 288 g = graph; 289 else 290 g = new AsUndirectedGraph<Node, OsmEdge>((DirectedWeightedMultigraph<Node,OsmEdge>)graph); 291 //TODO: Problemas no tiene encuenta el tema de oneway. 292 switch (algorithm) { 293 case ROUTING_ALG_DIJKSTRA: 294 logger.debug("Using Dijkstra algorithm"); 295 DijkstraShortestPath<Node, OsmEdge> routingk = null; 296 for (int index = 1; index < nodes.size(); ++index) { 297 routingk = new DijkstraShortestPath<Node, OsmEdge>(rgDelegator, nodes 298 .get(index - 1), nodes.get(index)); 299 if (routingk.getPathEdgeList() == null) { 300 logger.debug("no path found!"); 301 break; 302 } 303 path.addAll(routingk.getPathEdgeList()); 304 totalWeight += routingk.getPathLength(); 305 } 306 break; 307 case ROUTING_ALG_BELLMANFORD: 308 logger.debug("Using Bellman Ford algorithm"); 309 for (int index = 1; index < nodes.size(); ++index) { 310 path = BellmanFordShortestPath.findPathBetween(rgDelegator, nodes 311 .get(index - 1), nodes.get(index)); 312 if (path == null) { 313 logger.debug("no path found!"); 314 return null; 315 } 316 } 317 break; 318 default: 319 logger.debug("Wrong algorithm"); 320 break; 321 } 322 323 logger.debug("shortest path found: " + path + "\nweight: " 324 + totalWeight); 325 return path; 326 } 327 328 /** 329 * Return the number of vertices. 330 * @return the number of vertices. 331 */ 332 public int getVertexCount(){ 333 int value=0; 334 if (graph!=null) value=graph.vertexSet().size(); 335 return value; 336 } 337 338 /** 339 * Return the number of edges. 340 * @return the number of edges. 341 */ 342 public int getEdgeCount(){ 343 int value=0; 344 if (graph!=null) value=graph.edgeSet().size(); 345 return value; 346 } 347 348 /** 349 * @param routeType the routeType to set 350 */ 351 public void setTypeRoute(RouteType routetype) { 352 this.routeType = routetype; 353 this.rgDelegator.setRouteType(routetype); 354 } 355 356 /** 357 * @return the routeType 358 */ 359 public RouteType getTypeRoute() { 360 return routeType; 361 } 362 363 public Map<String, Double> getWaySpeeds() { 364 return waySpeeds; 365 } 366 367 public void setWaySpeeds(Map<String, Double> waySpeeds) { 368 this.waySpeeds = waySpeeds; 369 } 370 371 public void resetGraph() { 372 graph=null; 373 } 374 375 public RoutingProfile getRoutingProfile() { 376 return routingProfile; 377 } 378 378 } -
applications/editors/josm/plugins/routing/src/com/innovant/josm/jrt/core/RoutingGraphDelegator.java
r14760 r15707 19 19 public class RoutingGraphDelegator extends GraphDelegator<Node, OsmEdge> { 20 20 21 /**22 * Logger.23 */24 static Logger logger = Logger.getLogger(RoutingGraphDelegator.class);25 26 /**27 *28 */29 private RouteType routeType;30 31 public RoutingGraphDelegator(Graph<Node, OsmEdge> arg0) {32 super(arg0);33 }34 21 /** 22 * Logger. 23 */ 24 static Logger logger = Logger.getLogger(RoutingGraphDelegator.class); 25 26 /** 27 * 28 */ 29 private RouteType routeType; 30 31 public RoutingGraphDelegator(Graph<Node, OsmEdge> arg0) { 32 super(arg0); 33 } 34 35 35 36 public RouteType getRouteType() {37 return routeType;38 }36 public RouteType getRouteType() { 37 return routeType; 38 } 39 39 40 public void setRouteType(RouteType routeType) {41 this.routeType = routeType;42 }40 public void setRouteType(RouteType routeType) { 41 this.routeType = routeType; 42 } 43 43 44 44 45 /**46 *47 */48 private static final long serialVersionUID = 1L;45 /** 46 * 47 */ 48 private static final long serialVersionUID = 1L; 49 49 50 @Override51 public double getEdgeWeight(OsmEdge edge) {52 double weight=Double.MAX_VALUE;53 54 if (routeType==RouteType.SHORTEST) weight=edge.getLength();55 if (routeType==RouteType.FASTEST) weight=edge.getLength() / edge.getSpeed();56 // Return the time spent to traverse the way57 return weight;58 }50 @Override 51 public double getEdgeWeight(OsmEdge edge) { 52 double weight=Double.MAX_VALUE; 53 54 if (routeType==RouteType.SHORTEST) weight=edge.getLength(); 55 if (routeType==RouteType.FASTEST) weight=edge.getLength() / edge.getSpeed(); 56 // Return the time spent to traverse the way 57 return weight; 58 } 59 59 60 60 } -
applications/editors/josm/plugins/routing/src/com/innovant/josm/jrt/core/RoutingProfile.java
r14287 r15707 29 29 */ 30 30 public class RoutingProfile { 31 /**32 * logger33 */34 static Logger logger = Logger.getLogger(RoutingProfile.class);35 /**36 * True if oneway is used for routing (i.e. for cars).37 */38 private boolean useOneway;31 /** 32 * logger 33 */ 34 static Logger logger = Logger.getLogger(RoutingProfile.class); 35 /** 36 * True if oneway is used for routing (i.e. for cars). 37 */ 38 private boolean useOneway; 39 39 40 /**41 * True if turn restrictions are used for routing (i.e. for cars).42 */43 private boolean useRestrictions;40 /** 41 * True if turn restrictions are used for routing (i.e. for cars). 42 */ 43 private boolean useRestrictions; 44 44 45 /**46 * True if maximum allowed speed of ways is considered for routing (i.e. for cars).47 */48 private boolean useMaxAllowedSpeed;45 /** 46 * True if maximum allowed speed of ways is considered for routing (i.e. for cars). 47 */ 48 private boolean useMaxAllowedSpeed; 49 49 50 /**51 * Name of the routing profile, for identification issues (i.e. "pedestrian").52 */53 private String name;50 /** 51 * Name of the routing profile, for identification issues (i.e. "pedestrian"). 52 */ 53 private String name; 54 54 55 /**56 * Holds traverse speed for each type of way, using the type as key.57 * A speed of zero means that this type of way cannot be traversed.58 */59 private Map<String,Double> waySpeeds;55 /** 56 * Holds traverse speed for each type of way, using the type as key. 57 * A speed of zero means that this type of way cannot be traversed. 58 */ 59 private Map<String,Double> waySpeeds; 60 60 61 61 62 62 63 /**64 * Holds permission of use for each type of transport mode, using the mode as key.65 */66 private Map<String,Boolean> allowedModes;63 /** 64 * Holds permission of use for each type of transport mode, using the mode as key. 65 */ 66 private Map<String,Boolean> allowedModes; 67 67 68 /**69 * Constructor70 * @param name The name for the routing profile. Please use a name that is71 * self descriptive, i.e., something that an application user would72 * understand (like "pedestrian", "motorbike", "bicycle", etc.)73 */74 public RoutingProfile(String name) {75 logger.debug("Init RoutingProfile with name: "+name);76 this.name = name;77 waySpeeds=new HashMap<String,Double>();78 Map<String,String> prefs=Main.pref.getAllPrefix("routing.profile."+name+".speed");79 for(String key:prefs.keySet()){80 waySpeeds.put((key.split("\\.")[4]), Double.valueOf(prefs.get(key)));81 }82 for (String key:waySpeeds.keySet())83 logger.debug(key+ "-- speed: "+waySpeeds.get(key));84 logger.debug("End init RoutingProfile with name: "+name);85 }68 /** 69 * Constructor 70 * @param name The name for the routing profile. Please use a name that is 71 * self descriptive, i.e., something that an application user would 72 * understand (like "pedestrian", "motorbike", "bicycle", etc.) 73 */ 74 public RoutingProfile(String name) { 75 logger.debug("Init RoutingProfile with name: "+name); 76 this.name = name; 77 waySpeeds=new HashMap<String,Double>(); 78 Map<String,String> prefs=Main.pref.getAllPrefix("routing.profile."+name+".speed"); 79 for(String key:prefs.keySet()){ 80 waySpeeds.put((key.split("\\.")[4]), Double.valueOf(prefs.get(key))); 81 } 82 for (String key:waySpeeds.keySet()) 83 logger.debug(key+ "-- speed: "+waySpeeds.get(key)); 84 logger.debug("End init RoutingProfile with name: "+name); 85 } 86 86 87 public void setName(String name) {88 this.name = name;89 }87 public void setName(String name) { 88 this.name = name; 89 } 90 90 91 public String getName() {92 return name;93 }91 public String getName() { 92 return name; 93 } 94 94 95 public void setOnewayUse(boolean useOneway) {96 this.useOneway = useOneway;97 }95 public void setOnewayUse(boolean useOneway) { 96 this.useOneway = useOneway; 97 } 98 98 99 public boolean isOnewayUsed() {100 return useOneway;101 }99 public boolean isOnewayUsed() { 100 return useOneway; 101 } 102 102 103 public void setRestrictionsUse(boolean useRestrictions) {104 this.useRestrictions = useRestrictions;105 }103 public void setRestrictionsUse(boolean useRestrictions) { 104 this.useRestrictions = useRestrictions; 105 } 106 106 107 public boolean isRestrictionsUsed() {108 return useRestrictions;109 }107 public boolean isRestrictionsUsed() { 108 return useRestrictions; 109 } 110 110 111 public void setMaxAllowedSpeedUse(boolean useMaxAllowedSpeed) {112 this.useMaxAllowedSpeed = useMaxAllowedSpeed;113 }111 public void setMaxAllowedSpeedUse(boolean useMaxAllowedSpeed) { 112 this.useMaxAllowedSpeed = useMaxAllowedSpeed; 113 } 114 114 115 public boolean isMaxAllowedSpeedUsed() {116 return useMaxAllowedSpeed;117 }115 public boolean isMaxAllowedSpeedUsed() { 116 return useMaxAllowedSpeed; 117 } 118 118 119 public void setWayTypeSpeed(String type, double speed) {120 waySpeeds.put(type, speed);121 }119 public void setWayTypeSpeed(String type, double speed) { 120 waySpeeds.put(type, speed); 121 } 122 122 123 public void setTransportModePermission(String mode, boolean permission) {124 allowedModes.put(mode, permission);125 }123 public void setTransportModePermission(String mode, boolean permission) { 124 allowedModes.put(mode, permission); 125 } 126 126 127 /**128 * Return whether the driving profile specifies that a particular type of way129 * can be traversed130 * @param type Key for the way type131 * @return True if the way type can be traversed132 */133 public boolean isWayTypeAllowed(String type) {134 if (waySpeeds.get(type) != 0.0)135 return true;136 return false;137 }127 /** 128 * Return whether the driving profile specifies that a particular type of way 129 * can be traversed 130 * @param type Key for the way type 131 * @return True if the way type can be traversed 132 */ 133 public boolean isWayTypeAllowed(String type) { 134 if (waySpeeds.get(type) != 0.0) 135 return true; 136 return false; 137 } 138 138 139 /**140 * Return whether the driving profile specifies that a particular type of transport141 * mode can be used142 * @param mode Key for the way type143 * @return True if the way type can be traversed144 */145 public boolean isTransportModeAllowed(String mode) {146 return allowedModes.get(mode);147 }139 /** 140 * Return whether the driving profile specifies that a particular type of transport 141 * mode can be used 142 * @param mode Key for the way type 143 * @return True if the way type can be traversed 144 */ 145 public boolean isTransportModeAllowed(String mode) { 146 return allowedModes.get(mode); 147 } 148 148 149 public double getSpeed(String key){150 if(!waySpeeds.containsKey(key)) return 0.0;151 return waySpeeds.get(key);152 }149 public double getSpeed(String key){ 150 if(!waySpeeds.containsKey(key)) return 0.0; 151 return waySpeeds.get(key); 152 } 153 153 154 public Map<String, Double> getWaySpeeds() {155 return waySpeeds;156 }154 public Map<String, Double> getWaySpeeds() { 155 return waySpeeds; 156 } 157 157 158 public void setWaySpeeds(Map<String, Double> waySpeeds) {159 this.waySpeeds = waySpeeds;160 }158 public void setWaySpeeds(Map<String, Double> waySpeeds) { 159 this.waySpeeds = waySpeeds; 160 } 161 161 } -
applications/editors/josm/plugins/routing/src/com/innovant/josm/jrt/gtfs/GTFSTransportModes.java
r14287 r15707 9 9 public class GTFSTransportModes { 10 10 11 /**12 * 0 - Tram, Streetcar, Light rail. Any light rail or street level system within13 * a metropolitan area.14 */15 public static final int TRAM = 0;16 public static final int STREETCAR = 0;17 public static final int LIGHT_RAIL = 0;11 /** 12 * 0 - Tram, Streetcar, Light rail. Any light rail or street level system within 13 * a metropolitan area. 14 */ 15 public static final int TRAM = 0; 16 public static final int STREETCAR = 0; 17 public static final int LIGHT_RAIL = 0; 18 18 19 /**20 * 1 - Subway, Metro. Any underground rail system within a metropolitan area.21 */22 public static final int SUBWAY = 1;23 public static final int METRO = 1;19 /** 20 * 1 - Subway, Metro. Any underground rail system within a metropolitan area. 21 */ 22 public static final int SUBWAY = 1; 23 public static final int METRO = 1; 24 24 25 25 /** 26 26 * 2 - Rail. Used for intercity or long-distance travel. 27 27 */ 28 public static final int RAIL = 2;28 public static final int RAIL = 2; 29 29 30 30 /** 31 31 * 3 - Bus. Used for short- and long-distance bus routes. 32 32 */ 33 public static final int BUS = 3;33 public static final int BUS = 3; 34 34 35 35 /** 36 36 * 4 - Ferry. Used for short- and long-distance boat service. 37 37 */ 38 public static final int FERRY = 4;38 public static final int FERRY = 4; 39 39 40 /**41 * 5 - Cable car. Used for street-level cable cars where the cable runs beneath the car.42 */43 public static final int CABLE_CAR = 5;40 /** 41 * 5 - Cable car. Used for street-level cable cars where the cable runs beneath the car. 42 */ 43 public static final int CABLE_CAR = 5; 44 44 45 /**46 * 6 - Gondola, Suspended cable car. Typically used for aerial cable cars where47 * the car is suspended from the cable.48 */49 public static final int GONDOLA = 6;50 public static final int SUSPENDED_CABLE_CAR = 6;45 /** 46 * 6 - Gondola, Suspended cable car. Typically used for aerial cable cars where 47 * the car is suspended from the cable. 48 */ 49 public static final int GONDOLA = 6; 50 public static final int SUSPENDED_CABLE_CAR = 6; 51 51 52 52 /** 53 53 * 7 - Funicular. Any rail system designed for steep inclines. 54 54 */ 55 public static final int FUNICULAR = 7;55 public static final int FUNICULAR = 7; 56 56 57 57 } -
applications/editors/josm/plugins/routing/src/com/innovant/josm/jrt/osm/OsmEdge.java
r14760 r15707 65 65 */ 66 66 public OsmEdge(Way way, Node from, Node to) { 67 super();68 this.way = way;69 this.from = from;70 this.to = to;71 this.length = from.coor.greatCircleDistance(to.coor);72 }67 super(); 68 this.way = way; 69 this.from = from; 70 this.to = to; 71 this.length = from.coor.greatCircleDistance(to.coor); 72 } 73 73 74 74 /** … … 92 92 */ 93 93 public double getLength() { 94 return length;94 return length; 95 95 } 96 96 97 97 public void setLength(double length) { 98 this.length = length;98 this.length = length; 99 99 } 100 100 101 101 public double getSpeed() { 102 return speed;102 return speed; 103 103 } 104 104 105 105 public void setSpeed(double speed) { 106 this.speed = speed;106 this.speed = speed; 107 107 } 108 108 } -
applications/editors/josm/plugins/routing/src/com/innovant/josm/jrt/osm/OsmWayTypes.java
r14287 r15707 34 34 */ 35 35 public enum OsmWayTypes { 36 MOTORWAY ("motorway",120),37 MOTORWAY_LINK ("motorway_link",120),38 TRUNK ("trunk",120),39 TRUNK_LINK ("trunk_link",120),40 PRIMARY ("primary",100),41 PRIMARY_LINK ("primary_link",100),42 SECONDARY ("secondary",90),43 TERTIARY ("tertiary",90),44 UNCLASSIFIED ("unclassified",50),45 ROAD ("road",100),36 MOTORWAY ("motorway",120), 37 MOTORWAY_LINK ("motorway_link",120), 38 TRUNK ("trunk",120), 39 TRUNK_LINK ("trunk_link",120), 40 PRIMARY ("primary",100), 41 PRIMARY_LINK ("primary_link",100), 42 SECONDARY ("secondary",90), 43 TERTIARY ("tertiary",90), 44 UNCLASSIFIED ("unclassified",50), 45 ROAD ("road",100), 46 46 RESIDENTIAL ("residential",50), 47 LIVING_STREET ("living_street",30),48 SERVICE ("service",30),49 TRACK ("track",50),50 PEDESTRIAN ("pedestrian",30),51 BUS_GUIDEWAY ("bus_guideway",50),52 PATH ("path",40),53 CYCLEWAY ("cycleway",40),54 FOOTWAY ("footway",20),55 BRIDLEWAY ("bridleway",40),56 BYWAY ("byway",50),57 STEPS ("steps",10);47 LIVING_STREET ("living_street",30), 48 SERVICE ("service",30), 49 TRACK ("track",50), 50 PEDESTRIAN ("pedestrian",30), 51 BUS_GUIDEWAY ("bus_guideway",50), 52 PATH ("path",40), 53 CYCLEWAY ("cycleway",40), 54 FOOTWAY ("footway",20), 55 BRIDLEWAY ("bridleway",40), 56 BYWAY ("byway",50), 57 STEPS ("steps",10); 58 58 59 /**60 * Default Constructor61 * @param tag62 */63 OsmWayTypes(String tag,int speed) {64 this.tag = tag;65 this.speed = speed;66 }59 /** 60 * Default Constructor 61 * @param tag 62 */ 63 OsmWayTypes(String tag,int speed) { 64 this.tag = tag; 65 this.speed = speed; 66 } 67 67 68 /**69 * Tag70 */71 private final String tag;72 private final int speed;68 /** 69 * Tag 70 */ 71 private final String tag; 72 private final int speed; 73 73 74 /**75 * @return76 */77 public String getTag() {return tag;};78 public int getSpeed() {return speed;};74 /** 75 * @return 76 */ 77 public String getTag() {return tag;}; 78 public int getSpeed() {return speed;}; 79 79 } -
applications/editors/josm/plugins/routing/src/com/innovant/josm/plugin/routing/RoutingLayer.java
r14884 r15707 70 70 public class RoutingLayer extends Layer { 71 71 72 /**73 * Logger74 */75 static Logger logger = Logger.getLogger(RoutingLayer.class);72 /** 73 * Logger 74 */ 75 static Logger logger = Logger.getLogger(RoutingLayer.class); 76 76 77 77 /** … … 99 99 * @param name Layer name. 100 100 */ 101 public RoutingLayer(String name, OsmDataLayer dataLayer) {102 super(name);103 logger.debug("Creating Routing Layer...");101 public RoutingLayer(String name, OsmDataLayer dataLayer) { 102 super(name); 103 logger.debug("Creating Routing Layer..."); 104 104 if(startIcon == null) startIcon = ImageProvider.get("routing", "startflag"); 105 105 if(middleIcon == null) middleIcon = ImageProvider.get("routing", "middleflag"); … … 108 108 this.routingModel = new RoutingModel(dataLayer.data); 109 109 logger.debug("Routing Layer created."); 110 }111 112 /**113 * Getter Routing Model.114 * @return the routingModel115 */116 public RoutingModel getRoutingModel() {117 return this.routingModel;118 }119 120 /**121 * Gets associated data layer122 * @return OsmDataLayer associated to the RoutingLayer123 */124 public OsmDataLayer getDataLayer() {125 return dataLayer;126 }127 128 /**129 * Gets nearest node belonging to a highway tagged way130 * @param p Point on the screen131 * @return The nearest highway node, in the range of the snap distance132 */110 } 111 112 /** 113 * Getter Routing Model. 114 * @return the routingModel 115 */ 116 public RoutingModel getRoutingModel() { 117 return this.routingModel; 118 } 119 120 /** 121 * Gets associated data layer 122 * @return OsmDataLayer associated to the RoutingLayer 123 */ 124 public OsmDataLayer getDataLayer() { 125 return dataLayer; 126 } 127 128 /** 129 * Gets nearest node belonging to a highway tagged way 130 * @param p Point on the screen 131 * @return The nearest highway node, in the range of the snap distance 132 */ 133 133 public final Node getNearestHighwayNode(Point p) { 134 Node nearest = null;135 double minDist = 0;134 Node nearest = null; 135 double minDist = 0; 136 136 for (Way w : dataLayer.data.ways) { 137 137 if (w.deleted || w.incomplete || w.get("highway")==null) continue; … … 142 142 double dist = p.distanceSq(P); 143 143 if (dist < NavigatableComponent.snapDistance) { 144 if ((nearest == null) || (dist < minDist)) {145 nearest = n;146 minDist = dist;147 }144 if ((nearest == null) || (dist < minDist)) { 145 nearest = n; 146 minDist = dist; 147 } 148 148 } 149 149 } … … 152 152 } 153 153 154 /*155 * (non-Javadoc)156 * @see org.openstreetmap.josm.gui.layer.Layer#getIcon()157 */158 @Override159 public Icon getIcon() {154 /* 155 * (non-Javadoc) 156 * @see org.openstreetmap.josm.gui.layer.Layer#getIcon() 157 */ 158 @Override 159 public Icon getIcon() { 160 160 Icon icon = ImageProvider.get("layer", "routing_small"); 161 161 return icon; 162 }163 164 /*165 * (non-Javadoc)166 * @see org.openstreetmap.josm.gui.layer.Layer#getInfoComponent()167 */168 @Override169 public Object getInfoComponent() {170 String info = "<html>"171 + "<body>"172 +"Graph Vertex: "+this.routingModel.routingGraph.getVertexCount()+"<br/>"173 +"Graph Edges: "+this.routingModel.routingGraph.getEdgeCount()+"<br/>"174 + "</body>"175 + "</html>";162 } 163 164 /* 165 * (non-Javadoc) 166 * @see org.openstreetmap.josm.gui.layer.Layer#getInfoComponent() 167 */ 168 @Override 169 public Object getInfoComponent() { 170 String info = "<html>" 171 + "<body>" 172 +"Graph Vertex: "+this.routingModel.routingGraph.getVertexCount()+"<br/>" 173 +"Graph Edges: "+this.routingModel.routingGraph.getEdgeCount()+"<br/>" 174 + "</body>" 175 + "</html>"; 176 176 return info; 177 }178 179 /*180 * (non-Javadoc)181 * @see org.openstreetmap.josm.gui.layer.Layer#getMenuEntries()182 */183 @Override184 public Component[] getMenuEntries() {177 } 178 179 /* 180 * (non-Javadoc) 181 * @see org.openstreetmap.josm.gui.layer.Layer#getMenuEntries() 182 */ 183 @Override 184 public Component[] getMenuEntries() { 185 185 Collection<Component> components = new ArrayList<Component>(); 186 186 components.add(new JMenuItem(new LayerListDialog.ShowHideLayerAction(this))); … … 188 188 components.add(new JMenuItem(new LayerListDialog.DeleteLayerAction(this))); 189 189 components.add(new JSeparator()); 190 components.add(new JMenuItem(new RenameLayerAction( associatedFile, this)));190 components.add(new JMenuItem(new RenameLayerAction(getAssociatedFile(), this))); 191 191 components.add(new JSeparator()); 192 192 components.add(new JMenuItem(new LayerListPopup.InfoAction(this))); 193 193 return components.toArray(new Component[0]); 194 }195 196 /*197 * (non-Javadoc)198 * @see org.openstreetmap.josm.gui.layer.Layer#getToolTipText()199 */200 @Override201 public String getToolTipText() {202 String tooltip = this.routingModel.routingGraph.getVertexCount() + " vertices, "203 + this.routingModel.routingGraph.getEdgeCount() + " edges";204 return tooltip;205 }206 207 /*208 * (non-Javadoc)209 * @see org.openstreetmap.josm.gui.layer.Layer#isMergable(org.openstreetmap.josm.gui.layer.Layer)210 */211 @Override212 public boolean isMergable(Layer other) {213 return false;214 }215 216 /*217 * (non-Javadoc)218 * @see org.openstreetmap.josm.gui.layer.Layer#mergeFrom(org.openstreetmap.josm.gui.layer.Layer)219 */220 @Override221 public void mergeFrom(Layer from) {222 // This layer is not mergable, so do nothing223 }224 225 /*226 * (non-Javadoc)227 * @see org.openstreetmap.josm.gui.layer.Layer#paint(java.awt.Graphics, org.openstreetmap.josm.gui.MapView)228 */229 @Override230 public void paint(Graphics g, MapView mv) {231 boolean isActiveLayer = (mv.getActiveLayer().equals(this));232 // Get routing nodes (start, middle, end)194 } 195 196 /* 197 * (non-Javadoc) 198 * @see org.openstreetmap.josm.gui.layer.Layer#getToolTipText() 199 */ 200 @Override 201 public String getToolTipText() { 202 String tooltip = this.routingModel.routingGraph.getVertexCount() + " vertices, " 203 + this.routingModel.routingGraph.getEdgeCount() + " edges"; 204 return tooltip; 205 } 206 207 /* 208 * (non-Javadoc) 209 * @see org.openstreetmap.josm.gui.layer.Layer#isMergable(org.openstreetmap.josm.gui.layer.Layer) 210 */ 211 @Override 212 public boolean isMergable(Layer other) { 213 return false; 214 } 215 216 /* 217 * (non-Javadoc) 218 * @see org.openstreetmap.josm.gui.layer.Layer#mergeFrom(org.openstreetmap.josm.gui.layer.Layer) 219 */ 220 @Override 221 public void mergeFrom(Layer from) { 222 // This layer is not mergable, so do nothing 223 } 224 225 /* 226 * (non-Javadoc) 227 * @see org.openstreetmap.josm.gui.layer.Layer#paint(java.awt.Graphics, org.openstreetmap.josm.gui.MapView) 228 */ 229 @Override 230 public void paint(Graphics g, MapView mv) { 231 boolean isActiveLayer = (mv.getActiveLayer().equals(this)); 232 // Get routing nodes (start, middle, end) 233 233 List<Node> nodes = routingModel.getSelectedNodes(); 234 234 if(nodes == null || nodes.size() == 0) { 235 logger.debug("no nodes selected");235 logger.debug("no nodes selected"); 236 236 return; 237 237 } … … 241 241 String colorString; 242 242 if (isActiveLayer) { 243 if (Main.pref.hasKey(PreferencesKeys.KEY_ACTIVE_ROUTE_COLOR.key))244 colorString = Main.pref.get(PreferencesKeys.KEY_ACTIVE_ROUTE_COLOR.key);245 else {246 colorString = ColorHelper.color2html(Color.RED);247 Main.pref.put(PreferencesKeys.KEY_ACTIVE_ROUTE_COLOR.key, colorString);248 }243 if (Main.pref.hasKey(PreferencesKeys.KEY_ACTIVE_ROUTE_COLOR.key)) 244 colorString = Main.pref.get(PreferencesKeys.KEY_ACTIVE_ROUTE_COLOR.key); 245 else { 246 colorString = ColorHelper.color2html(Color.RED); 247 Main.pref.put(PreferencesKeys.KEY_ACTIVE_ROUTE_COLOR.key, colorString); 248 } 249 249 } else { 250 if (Main.pref.hasKey(PreferencesKeys.KEY_INACTIVE_ROUTE_COLOR.key))251 colorString = Main.pref.get(PreferencesKeys.KEY_INACTIVE_ROUTE_COLOR.key);252 else {253 colorString = ColorHelper.color2html(Color.decode("#dd2222"));254 Main.pref.put(PreferencesKeys.KEY_INACTIVE_ROUTE_COLOR.key, colorString);255 }250 if (Main.pref.hasKey(PreferencesKeys.KEY_INACTIVE_ROUTE_COLOR.key)) 251 colorString = Main.pref.get(PreferencesKeys.KEY_INACTIVE_ROUTE_COLOR.key); 252 else { 253 colorString = ColorHelper.color2html(Color.decode("#dd2222")); 254 Main.pref.put(PreferencesKeys.KEY_INACTIVE_ROUTE_COLOR.key, colorString); 255 } 256 256 } 257 257 Color color = ColorHelper.html2color(colorString); … … 277 277 Point screen = mv.getPoint(node.eastNorth); 278 278 startIcon.paintIcon(mv, g, screen.x - startIcon.getIconWidth()/2, 279 screen.y - startIcon.getIconHeight());279 screen.y - startIcon.getIconHeight()); 280 280 281 281 // paint middle icons … … 284 284 screen = mv.getPoint(node.eastNorth); 285 285 middleIcon.paintIcon(mv, g, screen.x - startIcon.getIconWidth()/2, 286 screen.y - middleIcon.getIconHeight());286 screen.y - middleIcon.getIconHeight()); 287 287 } 288 288 // paint end icon … … 291 291 screen = mv.getPoint(node.eastNorth); 292 292 endIcon.paintIcon(mv, g, screen.x - startIcon.getIconWidth()/2, 293 screen.y - endIcon.getIconHeight());294 } 295 }296 297 /*298 * (non-Javadoc)299 * @see org.openstreetmap.josm.gui.layer.Layer#visitBoundingBox(org.openstreetmap.josm.data.osm.visitor.BoundingXYVisitor)300 */301 @Override302 public void visitBoundingBox(BoundingXYVisitor v) {293 screen.y - endIcon.getIconHeight()); 294 } 295 } 296 297 /* 298 * (non-Javadoc) 299 * @see org.openstreetmap.josm.gui.layer.Layer#visitBoundingBox(org.openstreetmap.josm.data.osm.visitor.BoundingXYVisitor) 300 */ 301 @Override 302 public void visitBoundingBox(BoundingXYVisitor v) { 303 303 for (Node node : routingModel.getSelectedNodes()) { 304 304 v.visit(node); 305 305 } 306 }307 308 /*309 * (non-Javadoc)310 * @see org.openstreetmap.josm.gui.layer.Layer#destroy()311 */312 @Override306 } 307 308 /* 309 * (non-Javadoc) 310 * @see org.openstreetmap.josm.gui.layer.Layer#destroy() 311 */ 312 @Override 313 313 public void destroy() { 314 routingModel.reset();315 // layerAdded = false;316 }314 routingModel.reset(); 315 // layerAdded = false; 316 } 317 317 318 318 /** … … 320 320 */ 321 321 private void drawEdge(Graphics g, MapView mv, OsmEdge edge, Color col, int width, 322 boolean showDirection) {322 boolean showDirection) { 323 323 g.setColor(col); 324 324 Point from; -
applications/editors/josm/plugins/routing/src/com/innovant/josm/plugin/routing/RoutingModel.java
r14884 r15707 48 48 public class RoutingModel { 49 49 50 /**51 * Logger52 */53 static Logger logger = Logger.getLogger(RoutingModel.class);50 /** 51 * Logger 52 */ 53 static Logger logger = Logger.getLogger(RoutingModel.class); 54 54 55 55 /** 56 56 * Graph to calculate route 57 57 */ 58 public RoutingGraph routingGraph=null;58 public RoutingGraph routingGraph=null; 59 59 60 60 /** … … 71 71 * Default Constructor. 72 72 */ 73 public RoutingModel(DataSet data) {73 public RoutingModel(DataSet data) { 74 74 nodes = new ArrayList<Node>(); 75 System.out.println("gr " + data); 75 76 routingGraph = new RoutingGraph(data); 76 }77 } 77 78 78 79 /** … … 98 99 */ 99 100 public void removeNode(int index) { 100 if (nodes.size()>index){101 nodes.remove(index);102 this.changeNodes=true;103 }101 if (nodes.size()>index) { 102 nodes.remove(index); 103 this.changeNodes=true; 104 } 104 105 } 105 106 … … 110 111 */ 111 112 public void insertNode(int index, Node node) { 112 if (nodes.size()>=index) {113 nodes.add(index, node);114 this.changeNodes=true;115 }113 if (nodes.size()>=index) { 114 nodes.add(index, node); 115 this.changeNodes=true; 116 } 116 117 } 117 118 … … 120 121 */ 121 122 public void reverseNodes() { 122 List<Node> aux = new ArrayList<Node>();123 for (Node n : nodes) {124 aux.add(0,n);125 }126 nodes = aux;127 this.changeNodes=true;123 List<Node> aux = new ArrayList<Node>(); 124 for (Node n : nodes) { 125 aux.add(0,n); 126 } 127 nodes = aux; 128 this.changeNodes=true; 128 129 } 129 130 … … 133 134 */ 134 135 public List<OsmEdge> getRouteEdges() { 135 if (this.changeNodes || path==null)136 {137 path=this.routingGraph.applyAlgorithm(nodes, Algorithm.ROUTING_ALG_DIJKSTRA);138 this.changeNodes=false;139 }140 return path;136 if (this.changeNodes || path==null) 137 { 138 path=this.routingGraph.applyAlgorithm(nodes, Algorithm.ROUTING_ALG_DIJKSTRA); 139 this.changeNodes=false; 140 } 141 return path; 141 142 } 142 143 … … 145 146 */ 146 147 public void setNodesChanged() { 147 this.changeNodes = true;148 this.changeNodes = true; 148 149 } 149 150 -
applications/editors/josm/plugins/routing/src/com/innovant/josm/plugin/routing/RoutingPlugin.java
r14884 r15707 26 26 */ 27 27 28 29 28 package com.innovant.josm.plugin.routing; 30 29 30 import static org.openstreetmap.josm.tools.I18n.marktr; 31 31 import static org.openstreetmap.josm.tools.I18n.tr; 32 32 … … 60 60 */ 61 61 public class RoutingPlugin extends Plugin implements LayerChangeListener { 62 /**63 * Logger64 */65 static Logger logger = Logger.getLogger(RoutingPlugin.class);62 /** 63 * Logger 64 */ 65 static Logger logger = Logger.getLogger(RoutingPlugin.class); 66 66 67 67 /** … … 126 126 * Default Constructor 127 127 */ 128 public RoutingPlugin() {129 super();130 plugin = this; // Assign reference to the plugin class131 DOMConfigurator.configure("log4j.xml");132 logger.debug("Loading routing plugin...");133 preferenceSettings=new RoutingPreferenceDialog();134 // Create side dialog135 routingDialog = new RoutingDialog();136 // Initialize layers list137 layers = new ArrayList<RoutingLayer>();128 public RoutingPlugin() { 129 super(); 130 plugin = this; // Assign reference to the plugin class 131 DOMConfigurator.configure("log4j.xml"); 132 logger.debug("Loading routing plugin..."); 133 preferenceSettings=new RoutingPreferenceDialog(); 134 // Create side dialog 135 routingDialog = new RoutingDialog(); 136 // Initialize layers list 137 layers = new ArrayList<RoutingLayer>(); 138 138 // Add menu 139 menu = new RoutingMenu(tr("Routing")); 140 Main.main.menu.add(menu); 139 menu = new RoutingMenu(marktr("Routing")); 141 140 // Register this class as LayerChangeListener 142 141 Layer.listeners.add(this); 143 142 logger.debug("Finished loading plugin"); 144 }145 146 /**147 * Provides static access to the plugin instance, to enable access to the plugin methods148 * @return the instance of the plugin149 */150 public static RoutingPlugin getInstance() {151 return plugin;152 }153 154 /**155 * Get the routing side dialog156 * @return The instance of the routing side dialog157 */158 public RoutingDialog getRoutingDialog() {159 return routingDialog;160 }161 162 public void addLayer() {163 OsmDataLayer osmLayer = Main.main.editLayer();164 RoutingLayer layer = new RoutingLayer(tr("Routing") + " [" + osmLayer.name + "]", osmLayer);165 layers.add(layer);166 Main.main.addLayer(layer);167 }168 169 /*170 * (non-Javadoc)171 * @see org.openstreetmap.josm.plugins.Plugin#mapFrameInitialized(org.openstreetmap.josm.gui.MapFrame, org.openstreetmap.josm.gui.MapFrame)172 */143 } 144 145 /** 146 * Provides static access to the plugin instance, to enable access to the plugin methods 147 * @return the instance of the plugin 148 */ 149 public static RoutingPlugin getInstance() { 150 return plugin; 151 } 152 153 /** 154 * Get the routing side dialog 155 * @return The instance of the routing side dialog 156 */ 157 public RoutingDialog getRoutingDialog() { 158 return routingDialog; 159 } 160 161 public void addLayer() { 162 OsmDataLayer osmLayer = Main.main.editLayer(); 163 RoutingLayer layer = new RoutingLayer(tr("Routing") + " [" + osmLayer.name + "]", osmLayer); 164 layers.add(layer); 165 Main.main.addLayer(layer); 166 } 167 168 /* 169 * (non-Javadoc) 170 * @see org.openstreetmap.josm.plugins.Plugin#mapFrameInitialized(org.openstreetmap.josm.gui.MapFrame, org.openstreetmap.josm.gui.MapFrame) 171 */ 173 172 @Override 174 173 public void mapFrameInitialized(MapFrame oldFrame, MapFrame newFrame) { 175 174 if(newFrame != null) { 176 // Create plugin map modes177 addRouteNodeAction = new AddRouteNodeAction(newFrame);178 removeRouteNodeAction = new RemoveRouteNodeAction(newFrame);179 moveRouteNodeAction = new MoveRouteNodeAction(newFrame);180 // Create plugin buttons and add them to the toolbar181 addRouteNodeButton = new IconToggleButton(addRouteNodeAction);182 removeRouteNodeButton = new IconToggleButton(removeRouteNodeAction);183 moveRouteNodeButton = new IconToggleButton(moveRouteNodeAction);175 // Create plugin map modes 176 addRouteNodeAction = new AddRouteNodeAction(newFrame); 177 removeRouteNodeAction = new RemoveRouteNodeAction(newFrame); 178 moveRouteNodeAction = new MoveRouteNodeAction(newFrame); 179 // Create plugin buttons and add them to the toolbar 180 addRouteNodeButton = new IconToggleButton(addRouteNodeAction); 181 removeRouteNodeButton = new IconToggleButton(removeRouteNodeAction); 182 moveRouteNodeButton = new IconToggleButton(moveRouteNodeAction); 184 183 newFrame.addMapMode(addRouteNodeButton); 185 184 newFrame.addMapMode(removeRouteNodeButton); … … 189 188 newFrame.toolGroup.add(moveRouteNodeButton); 190 189 // Hide them by default 191 addRouteNodeButton.setVisible(false);192 removeRouteNodeButton.setVisible(false);193 moveRouteNodeButton.setVisible(false);194 // Enable menu195 menu.enableStartItem();190 addRouteNodeButton.setVisible(false); 191 removeRouteNodeButton.setVisible(false); 192 moveRouteNodeButton.setVisible(false); 193 // Enable menu 194 menu.enableStartItem(); 196 195 newFrame.addToggleDialog(routingDialog); 197 196 } … … 202 201 * @see org.openstreetmap.josm.gui.layer.Layer.LayerChangeListener#activeLayerChange(org.openstreetmap.josm.gui.layer.Layer, org.openstreetmap.josm.gui.layer.Layer) 203 202 */ 204 public void activeLayerChange(Layer oldLayer, Layer newLayer) {205 routingDialog.refresh();206 }207 208 /*209 * (non-Javadoc)210 * @see org.openstreetmap.josm.gui.layer.Layer.LayerChangeListener#layerAdded(org.openstreetmap.josm.gui.layer.Layer)211 */212 public void layerAdded(Layer newLayer) {213 // Add button(s) to the tool bar when the routing layer is added214 if (newLayer instanceof RoutingLayer) {215 addRouteNodeButton.setVisible(true);216 removeRouteNodeButton.setVisible(true);217 moveRouteNodeButton.setVisible(true);218 menu.enableRestOfItems();219 // Set layer on top and select layer, also refresh toggleDialog to reflect selection220 Main.map.mapView.moveLayer(newLayer, 0);221 logger.debug("Added routing layer.");222 }223 }224 225 /*226 * (non-Javadoc)227 * @see org.openstreetmap.josm.gui.layer.Layer.LayerChangeListener#layerRemoved(org.openstreetmap.josm.gui.layer.Layer)228 */229 public void layerRemoved(Layer oldLayer) {230 if ((oldLayer instanceof RoutingLayer) & (layers.size()==1)) {231 // Remove button(s) from the tool bar when the last routing layer is removed232 addRouteNodeButton.setVisible(false);233 removeRouteNodeButton.setVisible(false);234 moveRouteNodeButton.setVisible(false);235 menu.disableRestOfItems();236 layers.remove(oldLayer);237 logger.debug("Removed routing layer.");238 } else if (oldLayer instanceof OsmDataLayer) {239 // Remove all associated routing layers240 // Convert to Array to prevent ConcurrentModificationException when removing layers from ArrayList241 // FIXME: can't remove associated routing layers without triggering exceptions in some cases242 RoutingLayer[] layersArray = layers.toArray(new RoutingLayer[0]);243 for (int i=0;i<layersArray.length;i++) {244 if (layersArray[i].getDataLayer().equals(oldLayer)) {245 try {246 // Remove layer247 Main.map.mapView.removeLayer(layersArray[i]);248 } catch (IllegalArgumentException e) {249 }250 }251 }252 }253 // Reload RoutingDialog table model254 routingDialog.refresh();255 }256 257 /* (non-Javadoc)258 * @see org.openstreetmap.josm.plugins.Plugin#getPreferenceSetting()259 */260 @Override261 public PreferenceSetting getPreferenceSetting() {262 return preferenceSettings;263 }203 public void activeLayerChange(Layer oldLayer, Layer newLayer) { 204 routingDialog.refresh(); 205 } 206 207 /* 208 * (non-Javadoc) 209 * @see org.openstreetmap.josm.gui.layer.Layer.LayerChangeListener#layerAdded(org.openstreetmap.josm.gui.layer.Layer) 210 */ 211 public void layerAdded(Layer newLayer) { 212 // Add button(s) to the tool bar when the routing layer is added 213 if (newLayer instanceof RoutingLayer) { 214 addRouteNodeButton.setVisible(true); 215 removeRouteNodeButton.setVisible(true); 216 moveRouteNodeButton.setVisible(true); 217 menu.enableRestOfItems(); 218 // Set layer on top and select layer, also refresh toggleDialog to reflect selection 219 Main.map.mapView.moveLayer(newLayer, 0); 220 logger.debug("Added routing layer."); 221 } 222 } 223 224 /* 225 * (non-Javadoc) 226 * @see org.openstreetmap.josm.gui.layer.Layer.LayerChangeListener#layerRemoved(org.openstreetmap.josm.gui.layer.Layer) 227 */ 228 public void layerRemoved(Layer oldLayer) { 229 if ((oldLayer instanceof RoutingLayer) & (layers.size()==1)) { 230 // Remove button(s) from the tool bar when the last routing layer is removed 231 addRouteNodeButton.setVisible(false); 232 removeRouteNodeButton.setVisible(false); 233 moveRouteNodeButton.setVisible(false); 234 menu.disableRestOfItems(); 235 layers.remove(oldLayer); 236 logger.debug("Removed routing layer."); 237 } else if (oldLayer instanceof OsmDataLayer) { 238 // Remove all associated routing layers 239 // Convert to Array to prevent ConcurrentModificationException when removing layers from ArrayList 240 // FIXME: can't remove associated routing layers without triggering exceptions in some cases 241 RoutingLayer[] layersArray = layers.toArray(new RoutingLayer[0]); 242 for (int i=0;i<layersArray.length;i++) { 243 if (layersArray[i].getDataLayer().equals(oldLayer)) { 244 try { 245 // Remove layer 246 Main.map.mapView.removeLayer(layersArray[i]); 247 } catch (IllegalArgumentException e) { 248 } 249 } 250 } 251 } 252 // Reload RoutingDialog table model 253 routingDialog.refresh(); 254 } 255 256 /* (non-Javadoc) 257 * @see org.openstreetmap.josm.plugins.Plugin#getPreferenceSetting() 258 */ 259 @Override 260 public PreferenceSetting getPreferenceSetting() { 261 return preferenceSettings; 262 } 264 263 } -
applications/editors/josm/plugins/routing/src/com/innovant/josm/plugin/routing/actions/AddRouteNodeAction.java
r14423 r15707 51 51 */ 52 52 public class AddRouteNodeAction extends MapMode { 53 /**54 * Serial.55 */56 private static final long serialVersionUID = 1L;57 /**58 * Logger.59 */60 static Logger logger = Logger.getLogger(AddRouteNodeAction.class);61 /**62 * Routing Dialog.63 */53 /** 54 * Serial. 55 */ 56 private static final long serialVersionUID = 1L; 57 /** 58 * Logger. 59 */ 60 static Logger logger = Logger.getLogger(AddRouteNodeAction.class); 61 /** 62 * Routing Dialog. 63 */ 64 64 private RoutingDialog routingDialog; 65 65 … … 68 68 * @param mapFrame 69 69 */ 70 public AddRouteNodeAction(MapFrame mapFrame) {71 // TODO Use constructor with shortcut72 super(tr("Routing"), "add",73 tr("Click to add destination."),74 mapFrame, ImageProvider.getCursor("crosshair", null));70 public AddRouteNodeAction(MapFrame mapFrame) { 71 // TODO Use constructor with shortcut 72 super(tr("Routing"), "add", 73 tr("Click to add destination."), 74 mapFrame, ImageProvider.getCursor("crosshair", null)); 75 75 this.routingDialog = RoutingPlugin.getInstance().getRoutingDialog(); 76 }76 } 77 77 78 78 @Override public void enterMode() { … … 89 89 // If left button is clicked 90 90 if (e.getButton() == MouseEvent.BUTTON1) { 91 // Search for nearest highway node92 Node node = null;93 if (Main.map.mapView.getActiveLayer() instanceof RoutingLayer) {94 RoutingLayer layer = (RoutingLayer)Main.map.mapView.getActiveLayer();95 node = layer.getNearestHighwayNode(e.getPoint());91 // Search for nearest highway node 92 Node node = null; 93 if (Main.map.mapView.getActiveLayer() instanceof RoutingLayer) { 94 RoutingLayer layer = (RoutingLayer)Main.map.mapView.getActiveLayer(); 95 node = layer.getNearestHighwayNode(e.getPoint()); 96 96 if(node == null) { 97 logger.debug("no selected node");97 logger.debug("no selected node"); 98 98 return; 99 99 } … … 101 101 layer.getRoutingModel().addNode(node); 102 102 routingDialog.addNode(node); 103 }103 } 104 104 } 105 105 Main.map.repaint(); -
applications/editors/josm/plugins/routing/src/com/innovant/josm/plugin/routing/actions/MoveRouteNodeAction.java
r14423 r15707 54 54 */ 55 55 public class MoveRouteNodeAction extends MapMode { 56 /**57 * Serial.58 */59 private static final long serialVersionUID = 1L;56 /** 57 * Serial. 58 */ 59 private static final long serialVersionUID = 1L; 60 60 61 /**62 * Square of the distance radius where route nodes can be selected for dragging63 */64 private static final int DRAG_SQR_RADIUS = 100;61 /** 62 * Square of the distance radius where route nodes can be selected for dragging 63 */ 64 private static final int DRAG_SQR_RADIUS = 100; 65 65 66 /**67 * Logger.68 */69 static Logger logger = Logger.getLogger(RoutingLayer.class);66 /** 67 * Logger. 68 */ 69 static Logger logger = Logger.getLogger(RoutingLayer.class); 70 70 71 /**72 * Routing Dialog.73 */71 /** 72 * Routing Dialog. 73 */ 74 74 private RoutingDialog routingDialog; 75 75 … … 83 83 * @param mapFrame 84 84 */ 85 public MoveRouteNodeAction(MapFrame mapFrame) {86 // TODO Use constructor with shortcut87 super(tr("Routing"), "move",88 tr("Click and drag to move destination"),89 mapFrame, ImageProvider.getCursor("normal", "move"));85 public MoveRouteNodeAction(MapFrame mapFrame) { 86 // TODO Use constructor with shortcut 87 super(tr("Routing"), "move", 88 tr("Click and drag to move destination"), 89 mapFrame, ImageProvider.getCursor("normal", "move")); 90 90 this.routingDialog = RoutingPlugin.getInstance().getRoutingDialog(); 91 }91 } 92 92 93 93 @Override public void enterMode() { … … 104 104 // If left button is pressed 105 105 if (e.getButton() == MouseEvent.BUTTON1) { 106 if (Main.map.mapView.getActiveLayer() instanceof RoutingLayer) {107 RoutingLayer layer = (RoutingLayer)Main.map.mapView.getActiveLayer();108 RoutingModel routingModel = layer.getRoutingModel();109 // Search for the nearest node in the list110 List<Node> nl = routingModel.getSelectedNodes();111 index = -1;112 double dmax = DRAG_SQR_RADIUS; // maximum distance, in pixels113 for (int i=0;i<nl.size();i++) {114 Node node = nl.get(i);115 double d = Main.map.mapView.getPoint(node.eastNorth).distanceSq(e.getPoint());116 if (d < dmax) {117 dmax = d;118 index = i;119 }120 }121 if (index>=0)106 if (Main.map.mapView.getActiveLayer() instanceof RoutingLayer) { 107 RoutingLayer layer = (RoutingLayer)Main.map.mapView.getActiveLayer(); 108 RoutingModel routingModel = layer.getRoutingModel(); 109 // Search for the nearest node in the list 110 List<Node> nl = routingModel.getSelectedNodes(); 111 index = -1; 112 double dmax = DRAG_SQR_RADIUS; // maximum distance, in pixels 113 for (int i=0;i<nl.size();i++) { 114 Node node = nl.get(i); 115 double d = Main.map.mapView.getPoint(node.eastNorth).distanceSq(e.getPoint()); 116 if (d < dmax) { 117 dmax = d; 118 index = i; 119 } 120 } 121 if (index>=0) 122 122 logger.debug("Moved from node " + nl.get(index)); 123 }123 } 124 124 } 125 125 } 126 126 127 127 @Override public void mouseReleased(MouseEvent e) { 128 // If left button is released and a route node is being dragged129 if ((e.getButton() == MouseEvent.BUTTON1) && (index>=0)) {130 searchAndReplaceNode(e.getPoint());128 // If left button is released and a route node is being dragged 129 if ((e.getButton() == MouseEvent.BUTTON1) && (index>=0)) { 130 searchAndReplaceNode(e.getPoint()); 131 131 } 132 132 } … … 136 136 137 137 private void searchAndReplaceNode(Point point) { 138 if (Main.map.mapView.getActiveLayer() instanceof RoutingLayer) {139 RoutingLayer layer = (RoutingLayer)Main.map.mapView.getActiveLayer();140 RoutingModel routingModel = layer.getRoutingModel();141 // Search for nearest highway node142 Node node = null;143 node = layer.getNearestHighwayNode(point);138 if (Main.map.mapView.getActiveLayer() instanceof RoutingLayer) { 139 RoutingLayer layer = (RoutingLayer)Main.map.mapView.getActiveLayer(); 140 RoutingModel routingModel = layer.getRoutingModel(); 141 // Search for nearest highway node 142 Node node = null; 143 node = layer.getNearestHighwayNode(point); 144 144 if (node == null) { 145 logger.debug("Didn't found a close node to move to.");145 logger.debug("Didn't found a close node to move to."); 146 146 return; 147 147 } 148 148 logger.debug("Moved to node " + node); 149 149 routingModel.removeNode(index); 150 routingDialog.removeNode(index);150 routingDialog.removeNode(index); 151 151 routingModel.insertNode(index, node); 152 routingDialog.insertNode(index, node);152 routingDialog.insertNode(index, node); 153 153 Main.map.repaint(); 154 }154 } 155 155 } 156 156 } -
applications/editors/josm/plugins/routing/src/com/innovant/josm/plugin/routing/actions/RemoveRouteNodeAction.java
r14423 r15707 53 53 */ 54 54 public class RemoveRouteNodeAction extends MapMode { 55 /**56 * Serial.57 */58 private static final long serialVersionUID = 1L;55 /** 56 * Serial. 57 */ 58 private static final long serialVersionUID = 1L; 59 59 60 /**61 * Square of the distance radius where route nodes can be removed62 */63 private static final int REMOVE_SQR_RADIUS = 100;60 /** 61 * Square of the distance radius where route nodes can be removed 62 */ 63 private static final int REMOVE_SQR_RADIUS = 100; 64 64 65 /**66 * Logger.67 */68 static Logger logger = Logger.getLogger(RoutingLayer.class);69 /**70 * Routing Dialog.71 */65 /** 66 * Logger. 67 */ 68 static Logger logger = Logger.getLogger(RoutingLayer.class); 69 /** 70 * Routing Dialog. 71 */ 72 72 private RoutingDialog routingDialog; 73 73 74 public RemoveRouteNodeAction(MapFrame mapFrame) {75 // TODO Use constructor with shortcut76 super(tr("Routing"), "remove",77 tr("Click to remove destination"),78 mapFrame, ImageProvider.getCursor("normal", "delete"));74 public RemoveRouteNodeAction(MapFrame mapFrame) { 75 // TODO Use constructor with shortcut 76 super(tr("Routing"), "remove", 77 tr("Click to remove destination"), 78 mapFrame, ImageProvider.getCursor("normal", "delete")); 79 79 this.routingDialog = RoutingPlugin.getInstance().getRoutingDialog(); 80 }80 } 81 81 82 82 @Override public void enterMode() { … … 93 93 // If left button is clicked 94 94 if (e.getButton() == MouseEvent.BUTTON1) { 95 if (Main.map.mapView.getActiveLayer() instanceof RoutingLayer) {96 RoutingLayer layer = (RoutingLayer)Main.map.mapView.getActiveLayer();97 RoutingModel routingModel = layer.getRoutingModel();98 // Search for the nearest node in the list99 List<Node> nl = routingModel.getSelectedNodes();100 int index = -1;101 double dmax = REMOVE_SQR_RADIUS; // maximum distance, in pixels102 for (int i=0;i<nl.size();i++) {103 Node node = nl.get(i);104 double d = Main.map.mapView.getPoint(node.eastNorth).distanceSq(e.getPoint());105 if (d < dmax) {106 dmax = d;107 index = i;108 }109 }110 // If found a close node, remove it and recalculate route95 if (Main.map.mapView.getActiveLayer() instanceof RoutingLayer) { 96 RoutingLayer layer = (RoutingLayer)Main.map.mapView.getActiveLayer(); 97 RoutingModel routingModel = layer.getRoutingModel(); 98 // Search for the nearest node in the list 99 List<Node> nl = routingModel.getSelectedNodes(); 100 int index = -1; 101 double dmax = REMOVE_SQR_RADIUS; // maximum distance, in pixels 102 for (int i=0;i<nl.size();i++) { 103 Node node = nl.get(i); 104 double d = Main.map.mapView.getPoint(node.eastNorth).distanceSq(e.getPoint()); 105 if (d < dmax) { 106 dmax = d; 107 index = i; 108 } 109 } 110 // If found a close node, remove it and recalculate route 111 111 if (index >= 0) { 112 // Remove node113 logger.debug("Removing node " + nl.get(index));112 // Remove node 113 logger.debug("Removing node " + nl.get(index)); 114 114 routingModel.removeNode(index); 115 routingDialog.removeNode(index);115 routingDialog.removeNode(index); 116 116 Main.map.repaint(); 117 117 } else { 118 logger.debug("Can't find a node to remove.");118 logger.debug("Can't find a node to remove."); 119 119 } 120 }120 } 121 121 } 122 122 } -
applications/editors/josm/plugins/routing/src/com/innovant/josm/plugin/routing/gui/RoutingDialog.java
r14404 r15707 56 56 public class RoutingDialog extends ToggleDialog { 57 57 58 private DefaultListModel model;59 private JList jList = null;60 private JScrollPane jScrollPane = null;58 private DefaultListModel model; 59 private JList jList = null; 60 private JScrollPane jScrollPane = null; 61 61 62 /**63 * Serial UID64 */65 private static final long serialVersionUID = 8625615652900341987L;62 /** 63 * Serial UID 64 */ 65 private static final long serialVersionUID = 8625615652900341987L; 66 66 67 public RoutingDialog() {68 super(tr("Routing"), "routing", tr("Open a list of routing nodes"),69 Shortcut.registerShortcut("subwindow:relations", tr("Toggle: {0}", tr("Routing")), KeyEvent.VK_R, Shortcut.GROUP_LAYER), 150);70 model= new DefaultListModel();71 this.setSize(456, 292);72 this.setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));73 this.setBorder(BorderFactory.createEtchedBorder(EtchedBorder.RAISED));74 this.setName("PrincipalDialog");75 this.setFont(new Font("Dialog", Font.PLAIN, 12));76 this.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);77 this.add(getJScrollPane(), null);67 public RoutingDialog() { 68 super(tr("Routing"), "routing", tr("Open a list of routing nodes"), 69 Shortcut.registerShortcut("subwindow:relations", tr("Toggle: {0}", tr("Routing")), KeyEvent.VK_R, Shortcut.GROUP_LAYER), 150); 70 model= new DefaultListModel(); 71 this.setSize(456, 292); 72 this.setLayout(new BoxLayout(this, BoxLayout.Y_AXIS)); 73 this.setBorder(BorderFactory.createEtchedBorder(EtchedBorder.RAISED)); 74 this.setName("PrincipalDialog"); 75 this.setFont(new Font("Dialog", Font.PLAIN, 12)); 76 this.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT); 77 this.add(getJScrollPane(), null); 78 78 79 }79 } 80 80 81 /**82 * This method initializes jScrollPane83 *84 * @return javax.swing.JScrollPane85 */86 private JScrollPane getJScrollPane() {87 if (jScrollPane == null) {88 jScrollPane = new JScrollPane();89 jScrollPane.setBorder(BorderFactory.createEtchedBorder(EtchedBorder.LOWERED));90 jScrollPane.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);91 jScrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);92 jScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);93 jScrollPane.setName("nList");94 jScrollPane.setViewportBorder(BorderFactory.createEtchedBorder(EtchedBorder.LOWERED));95 jScrollPane.setViewportView(getJList());96 }97 return jScrollPane;98 }81 /** 82 * This method initializes jScrollPane 83 * 84 * @return javax.swing.JScrollPane 85 */ 86 private JScrollPane getJScrollPane() { 87 if (jScrollPane == null) { 88 jScrollPane = new JScrollPane(); 89 jScrollPane.setBorder(BorderFactory.createEtchedBorder(EtchedBorder.LOWERED)); 90 jScrollPane.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT); 91 jScrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); 92 jScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED); 93 jScrollPane.setName("nList"); 94 jScrollPane.setViewportBorder(BorderFactory.createEtchedBorder(EtchedBorder.LOWERED)); 95 jScrollPane.setViewportView(getJList()); 96 } 97 return jScrollPane; 98 } 99 99 100 /**101 * This method initializes jList102 *103 * @return javax.swing.JList104 */105 private JList getJList() {106 if (jList == null) {107 jList = new JList();108 jList.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);109 jList.setModel(model);110 }111 return jList;112 }100 /** 101 * This method initializes jList 102 * 103 * @return javax.swing.JList 104 */ 105 private JList getJList() { 106 if (jList == null) { 107 jList = new JList(); 108 jList.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT); 109 jList.setModel(model); 110 } 111 return jList; 112 } 113 113 114 /**115 * Remove item from the list of nodes116 * @param index117 */118 public void removeNode(int index) {119 model.remove(index);120 }114 /** 115 * Remove item from the list of nodes 116 * @param index 117 */ 118 public void removeNode(int index) { 119 model.remove(index); 120 } 121 121 122 /**123 * Add item to the list of nodes124 * @param obj125 */126 public void addNode(Node n) {127 model.addElement(n.id+" ["+n.coor.toDisplayString()+"]");128 }122 /** 123 * Add item to the list of nodes 124 * @param obj 125 */ 126 public void addNode(Node n) { 127 model.addElement(n.id+" ["+n.coor.toDisplayString()+"]"); 128 } 129 129 130 /**131 * Insert item to the list of nodes132 * @param index133 * @param obj134 */135 public void insertNode(int index, Node n) {136 model.insertElementAt(n.id+" ["+n.coor.toDisplayString()+"]", index);137 }130 /** 131 * Insert item to the list of nodes 132 * @param index 133 * @param obj 134 */ 135 public void insertNode(int index, Node n) { 136 model.insertElementAt(n.id+" ["+n.coor.toDisplayString()+"]", index); 137 } 138 138 139 /**140 * Clear list of nodes141 */142 public void clearNodes() {143 model.clear();144 }139 /** 140 * Clear list of nodes 141 */ 142 public void clearNodes() { 143 model.clear(); 144 } 145 145 146 public void refresh() {147 clearNodes();148 if (Main.map.mapView.getActiveLayer() instanceof RoutingLayer) {149 RoutingLayer routingLayer = (RoutingLayer)Main.map.mapView.getActiveLayer();150 RoutingModel routingModel = routingLayer.getRoutingModel();151 for (Node n : routingModel.getSelectedNodes()) {152 addNode(n);153 }154 }155 }146 public void refresh() { 147 clearNodes(); 148 if (Main.map.mapView.getActiveLayer() instanceof RoutingLayer) { 149 RoutingLayer routingLayer = (RoutingLayer)Main.map.mapView.getActiveLayer(); 150 RoutingModel routingModel = routingLayer.getRoutingModel(); 151 for (Node n : routingModel.getSelectedNodes()) { 152 addNode(n); 153 } 154 } 155 } 156 156 } -
applications/editors/josm/plugins/routing/src/com/innovant/josm/plugin/routing/gui/RoutingMenu.java
r14760 r15707 34 34 import java.awt.event.ItemEvent; 35 35 import java.awt.event.ItemListener; 36 import java.awt.event.KeyEvent; 36 37 37 38 import javax.swing.ButtonGroup; … … 42 43 43 44 import org.openstreetmap.josm.Main; 45 import org.openstreetmap.josm.gui.MainMenu; 44 46 45 47 import com.innovant.josm.jrt.core.RoutingGraph.RouteType; … … 55 57 public class RoutingMenu extends JMenu { 56 58 57 /**58 * Default serial version UID59 */60 private static final long serialVersionUID = 3559922048225708480L;59 /** 60 * Default serial version UID 61 */ 62 private static final long serialVersionUID = 3559922048225708480L; 61 63 62 private JMenuItem startMI; 63 private JMenuItem reverseMI; 64 private JMenuItem clearMI; 65 private JMenu criteriaM; 64 private JMenuItem startMI; 65 private JMenuItem reverseMI; 66 private JMenuItem clearMI; 67 private JMenu criteriaM; 68 private JMenu menu; 66 69 67 /** 68 * @param s 69 */ 70 public RoutingMenu(final String name) { 71 super(name); 70 /** 71 * @param s 72 */ 73 public RoutingMenu(final String name) { 74 MainMenu mm = Main.main.menu; 75 menu = mm.addMenu(name, KeyEvent.VK_R, mm.defaultMenuPos); 72 76 73 JMenuItem mi; 74 JMenu m; 77 startMI = new JMenuItem(tr("Add routing layer")); 78 startMI.addActionListener(new ActionListener() { 79 public void actionPerformed(ActionEvent e) { 80 RoutingPlugin.getInstance().addLayer(); 81 } 82 }); 83 menu.add(startMI); 75 84 76 startMI = new JMenuItem(tr("Add routing layer")); 77 startMI.addActionListener(new ActionListener() { 78 public void actionPerformed(ActionEvent e) { 79 RoutingPlugin.getInstance().addLayer(); 80 } 81 }); 82 this.add(startMI); 85 menu.addSeparator(); 86 ButtonGroup group = new ButtonGroup(); 83 87 84 this.addSeparator(); 85 ButtonGroup group = new ButtonGroup(); 88 criteriaM = new JMenu(tr("Criteria")); 86 89 87 criteriaM = new JMenu(tr("Criteria")); 90 JRadioButtonMenuItem rshorter = new JRadioButtonMenuItem(tr("Shortest")); 91 rshorter.setSelected(true); 92 rshorter.addItemListener(new ItemListener() { 93 public void itemStateChanged(ItemEvent e) { 94 if (Main.map.mapView.getActiveLayer() instanceof RoutingLayer) { 95 RoutingLayer layer = (RoutingLayer)Main.map.mapView.getActiveLayer(); 96 RoutingModel routingModel = layer.getRoutingModel(); 97 if (e.getStateChange()==ItemEvent.SELECTED) { 98 routingModel.routingGraph.setTypeRoute(RouteType.SHORTEST); 99 } else { 100 routingModel.routingGraph.setTypeRoute(RouteType.FASTEST); 101 } 102 // routingModel.routingGraph.resetGraph(); 103 // routingModel.routingGraph.createGraph(); 104 //TODO: Change this way 105 //FIXME: do not change node but recalculate routing. 106 routingModel.setNodesChanged(); 107 Main.map.repaint(); 108 } 109 } 88 110 89 JRadioButtonMenuItem rshorter = new JRadioButtonMenuItem(tr("Shortest")); 90 rshorter.setSelected(true); 91 rshorter.addItemListener(new ItemListener() { 92 public void itemStateChanged(ItemEvent e) { 93 if (Main.map.mapView.getActiveLayer() instanceof RoutingLayer) { 94 RoutingLayer layer = (RoutingLayer)Main.map.mapView.getActiveLayer(); 95 RoutingModel routingModel = layer.getRoutingModel(); 96 if (e.getStateChange()==ItemEvent.SELECTED) { 97 routingModel.routingGraph.setTypeRoute(RouteType.SHORTEST); 98 } else { 99 routingModel.routingGraph.setTypeRoute(RouteType.FASTEST); 100 } 101 // routingModel.routingGraph.resetGraph(); 102 // routingModel.routingGraph.createGraph(); 103 //TODO: Change this way 104 //FIXME: do not change node but recalculate routing. 105 routingModel.setNodesChanged(); 106 Main.map.repaint(); 107 } 108 } 111 }); 109 112 110 }); 113 JRadioButtonMenuItem rfaster = new JRadioButtonMenuItem(tr("Fastest")); 114 group.add(rshorter); 115 group.add(rfaster); 116 criteriaM.add(rshorter); 117 criteriaM.add(rfaster); 111 118 112 JRadioButtonMenuItem rfaster = new JRadioButtonMenuItem(tr("Fastest")); 113 group.add(rshorter); 114 group.add(rfaster); 115 criteriaM.add(rshorter); 116 criteriaM.add(rfaster); 119 criteriaM.addSeparator(); 120 JCheckBoxMenuItem cbmi = new JCheckBoxMenuItem("Ignore oneways"); 121 cbmi.addItemListener(new ItemListener() { 122 public void itemStateChanged(ItemEvent e) { 123 if (Main.map.mapView.getActiveLayer() instanceof RoutingLayer) { 124 RoutingLayer layer = (RoutingLayer)Main.map.mapView.getActiveLayer(); 125 RoutingModel routingModel = layer.getRoutingModel(); 126 if (e.getStateChange()==ItemEvent.SELECTED) 127 routingModel.routingGraph.getRoutingProfile().setOnewayUse(false); 128 else 129 routingModel.routingGraph.getRoutingProfile().setOnewayUse(true); 130 routingModel.setNodesChanged(); 131 Main.map.repaint(); 132 } 133 } 134 }); 135 criteriaM.add(cbmi); 136 menu.add(criteriaM); 117 137 118 criteriaM.addSeparator(); 119 JCheckBoxMenuItem cbmi = new JCheckBoxMenuItem("Ignore oneways"); 120 cbmi.addItemListener(new ItemListener() { 121 public void itemStateChanged(ItemEvent e) { 122 if (Main.map.mapView.getActiveLayer() instanceof RoutingLayer) { 123 RoutingLayer layer = (RoutingLayer)Main.map.mapView.getActiveLayer(); 124 RoutingModel routingModel = layer.getRoutingModel(); 125 if (e.getStateChange()==ItemEvent.SELECTED) 126 routingModel.routingGraph.getRoutingProfile().setOnewayUse(false); 127 else 128 routingModel.routingGraph.getRoutingProfile().setOnewayUse(true); 129 routingModel.setNodesChanged(); 130 Main.map.repaint(); 131 } 132 } 133 }); 134 criteriaM.add(cbmi); 135 this.add(criteriaM); 138 menu.addSeparator(); 139 reverseMI = new JMenuItem(tr("Reverse route")); 140 reverseMI.addActionListener(new ActionListener() { 141 public void actionPerformed(ActionEvent e) { 142 if (Main.map.mapView.getActiveLayer() instanceof RoutingLayer) { 143 RoutingLayer layer = (RoutingLayer)Main.map.mapView.getActiveLayer(); 144 RoutingModel routingModel = layer.getRoutingModel(); 145 routingModel.reverseNodes(); 146 Main.map.repaint(); 147 } 148 } 149 }); 150 menu.add(reverseMI); 136 151 137 this.addSeparator(); 138 reverseMI = new JMenuItem(tr("Reverse route")); 139 reverseMI.addActionListener(new ActionListener() { 140 public void actionPerformed(ActionEvent e) { 141 if (Main.map.mapView.getActiveLayer() instanceof RoutingLayer) { 142 RoutingLayer layer = (RoutingLayer)Main.map.mapView.getActiveLayer(); 143 RoutingModel routingModel = layer.getRoutingModel(); 144 routingModel.reverseNodes(); 145 Main.map.repaint(); 146 } 147 } 148 }); 149 this.add(reverseMI); 152 clearMI = new JMenuItem(tr("Clear route")); 153 clearMI.addActionListener(new ActionListener() { 154 public void actionPerformed(ActionEvent e) { 155 if (Main.map.mapView.getActiveLayer() instanceof RoutingLayer) { 156 RoutingLayer layer = (RoutingLayer)Main.map.mapView.getActiveLayer(); 157 RoutingModel routingModel = layer.getRoutingModel(); 158 // Reset routing nodes and paths 159 routingModel.reset(); 160 RoutingPlugin.getInstance().getRoutingDialog().clearNodes(); 161 Main.map.repaint(); 162 } 163 } 164 }); 165 menu.add(clearMI); 150 166 151 clearMI = new JMenuItem(tr("Clear route")); 152 clearMI.addActionListener(new ActionListener() { 153 public void actionPerformed(ActionEvent e) { 154 if (Main.map.mapView.getActiveLayer() instanceof RoutingLayer) { 155 RoutingLayer layer = (RoutingLayer)Main.map.mapView.getActiveLayer(); 156 RoutingModel routingModel = layer.getRoutingModel(); 157 // Reset routing nodes and paths 158 routingModel.reset(); 159 RoutingPlugin.getInstance().getRoutingDialog().clearNodes(); 160 Main.map.repaint(); 161 } 162 } 163 }); 164 this.add(clearMI); 167 // Initially disabled 168 disableAllItems(); 169 } 165 170 166 // Initially disabled 167 disableAllItems(); 168 } 171 public void disableAllItems() { 172 startMI.setEnabled(false); 173 reverseMI.setEnabled(false); 174 clearMI.setEnabled(false); 175 criteriaM.setEnabled(false); 176 } 169 177 170 public void disableAllItems() { 171 startMI.setEnabled(false); 172 reverseMI.setEnabled(false); 173 clearMI.setEnabled(false); 174 criteriaM.setEnabled(false); 175 } 178 public void enableStartItem() { 179 startMI.setEnabled(true); 180 } 176 181 177 public void enableStartItem() { 178 startMI.setEnabled(true); 179 } 182 public void enableRestOfItems() { 183 reverseMI.setEnabled(true); 184 clearMI.setEnabled(true); 185 criteriaM.setEnabled(true); 186 } 180 187 181 public void enableRestOfItems() { 182 reverseMI.setEnabled(true); 183 clearMI.setEnabled(true); 184 criteriaM.setEnabled(true); 185 } 186 187 public void disableRestOfItems() { 188 reverseMI.setEnabled(false); 189 clearMI.setEnabled(false); 190 criteriaM.setEnabled(false); 191 } 188 public void disableRestOfItems() { 189 reverseMI.setEnabled(false); 190 clearMI.setEnabled(false); 191 criteriaM.setEnabled(false); 192 } 192 193 } -
applications/editors/josm/plugins/routing/src/com/innovant/josm/plugin/routing/gui/RoutingPreferenceDialog.java
r14287 r15707 64 64 public class RoutingPreferenceDialog implements PreferenceSetting { 65 65 66 /**67 * Logger68 */69 static Logger logger = Logger.getLogger(RoutingPreferenceDialog.class);70 71 private Map<String, String> orig;72 private DefaultTableModel model;73 74 /**75 * Constructor76 */77 public RoutingPreferenceDialog() {78 super();79 readPreferences();80 }81 82 public void addGui(final PreferenceDialog gui) {83 84 JPanel principal = gui.createPreferenceTab("routing",85 tr("Routing Plugin Preferences"), tr("Configure routing preferences."));86 87 JPanel p = new JPanel();88 p.setLayout(new GridBagLayout());89 90 model = new DefaultTableModel(new String[] { tr("Highway type"),91 tr("Speed (Km/h)") }, 0) {92 private static final long serialVersionUID = 4253339034781567453L;93 94 @Override95 public boolean isCellEditable(int row, int column) {96 return column != 0;97 }98 };99 final JTable list = new JTable(model);100 loadSpeeds(model);101 102 JScrollPane scroll = new JScrollPane(list);103 104 p.add(scroll, GBC.eol().fill(GBC.BOTH));105 scroll.setPreferredSize(new Dimension(200, 200));106 107 JButton add = new JButton(tr("Add"));108 p.add(Box.createHorizontalGlue(), GBC.std().fill(GBC.HORIZONTAL));109 p.add(add, GBC.std().insets(0, 5, 0, 0));110 add.addActionListener(new ActionListener() {111 public void actionPerformed(ActionEvent e) {112 JPanel p = new JPanel(new GridBagLayout());113 p.add(new JLabel(tr("Weight")), GBC.std().insets(0, 0, 5, 0));114 JComboBox key = new JComboBox();115 for (OsmWayTypes pk : OsmWayTypes.values())116 key.addItem(pk.getTag());117 JTextField value = new JTextField(10);118 p.add(key, GBC.eop().insets(5, 0, 0, 0).fill(GBC.HORIZONTAL));119 p.add(new JLabel(tr("Value")), GBC.std().insets(0, 0, 5, 0));120 p.add(value, GBC.eol().insets(5, 0, 0, 0).fill(GBC.HORIZONTAL));121 int answer = JOptionPane.showConfirmDialog(gui, p,122 tr("Enter weight values"),123 JOptionPane.OK_CANCEL_OPTION);124 if (answer == JOptionPane.OK_OPTION) {125 model126 .addRow(new String[] {127 key.getSelectedItem().toString(),128 value.getText() });129 }130 }131 });132 133 JButton delete = new JButton(tr("Delete"));134 p.add(delete, GBC.std().insets(0, 5, 0, 0));135 delete.addActionListener(new ActionListener() {136 public void actionPerformed(ActionEvent e) {137 if (list.getSelectedRow() == -1)138 JOptionPane.showMessageDialog(gui,139 tr("Please select the row to delete."));140 else {141 Integer i;142 while ((i = list.getSelectedRow()) != -1)143 model.removeRow(i);144 }145 }146 });147 148 JButton edit = new JButton(tr("Edit"));149 p.add(edit, GBC.std().insets(5, 5, 5, 0));150 edit.addActionListener(new ActionListener() {151 public void actionPerformed(ActionEvent e) {152 edit(gui, list);153 }154 });155 156 JTabbedPane Opciones = new JTabbedPane();157 Opciones.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);158 159 Opciones.addTab("Profile", null, p, null);160 // Opciones.addTab("Preferences", new JPanel());161 162 list.addMouseListener(new MouseAdapter(){163 @Override public void mouseClicked(MouseEvent e) {164 if (e.getClickCount() == 2)165 edit(gui, list);166 }167 });168 169 principal.add(Opciones, GBC.eol().fill(GBC.BOTH));170 171 }172 173 public boolean ok() {174 for (int i = 0; i < model.getRowCount(); ++i) {175 String value = model.getValueAt(i, 1).toString();176 if (value.length() != 0) {177 String key = model.getValueAt(i, 0).toString();178 String origValue = orig.get(key);179 if (origValue == null || !origValue.equals(value))180 Main.pref.put(key, value);181 orig.remove(key); // processed.182 }183 }184 for (Entry<String, String> e : orig.entrySet())185 Main.pref.put(e.getKey(), null);186 return false;187 }188 189 private void edit(final PreferenceDialog gui, final JTable list) {190 if (list.getSelectedRowCount() != 1) {191 JOptionPane.showMessageDialog(gui,192 tr("Please select the row to edit."));193 return;194 }195 String v = JOptionPane.showInputDialog(tr("New value for {0}", model196 .getValueAt(list.getSelectedRow(), 0)), model.getValueAt(list197 .getSelectedRow(), 1));198 if (v != null)199 model.setValueAt(v, list.getSelectedRow(), 1);200 }201 202 private void loadSpeeds(DefaultTableModel model) {203 // Read dialog values from preferences204 readPreferences();205 // Put these values in the model206 for (String tag : orig.keySet()) {207 model.addRow(new String[] { tag, orig.get(tag) });208 }209 }210 211 private void readPreferences() {212 orig = Main.pref.getAllPrefix("routing.profile.default.speed");213 if (orig.size() == 0) { // defaults214 logger.debug("Loading Default Preferences.");215 for (OsmWayTypes owt : OsmWayTypes.values()) {216 Main.pref.putInteger("routing.profile.default.speed."217 + owt.getTag(), owt.getSpeed());218 }219 orig = Main.pref.getAllPrefix("routing.profile.default.speed");220 }221 else logger.debug("Default preferences already exist.");222 }223 224 private String getKeyTag(String tag) {225 return tag.split(".", 5)[4];226 }227 228 private String getTypeTag(String tag) {229 return tag.split(".", 5)[3];230 }231 232 private String getNameTag(String tag) {233 return tag.split(".", 5)[2];234 }66 /** 67 * Logger 68 */ 69 static Logger logger = Logger.getLogger(RoutingPreferenceDialog.class); 70 71 private Map<String, String> orig; 72 private DefaultTableModel model; 73 74 /** 75 * Constructor 76 */ 77 public RoutingPreferenceDialog() { 78 super(); 79 readPreferences(); 80 } 81 82 public void addGui(final PreferenceDialog gui) { 83 84 JPanel principal = gui.createPreferenceTab("routing", 85 tr("Routing Plugin Preferences"), tr("Configure routing preferences.")); 86 87 JPanel p = new JPanel(); 88 p.setLayout(new GridBagLayout()); 89 90 model = new DefaultTableModel(new String[] { tr("Highway type"), 91 tr("Speed (Km/h)") }, 0) { 92 private static final long serialVersionUID = 4253339034781567453L; 93 94 @Override 95 public boolean isCellEditable(int row, int column) { 96 return column != 0; 97 } 98 }; 99 final JTable list = new JTable(model); 100 loadSpeeds(model); 101 102 JScrollPane scroll = new JScrollPane(list); 103 104 p.add(scroll, GBC.eol().fill(GBC.BOTH)); 105 scroll.setPreferredSize(new Dimension(200, 200)); 106 107 JButton add = new JButton(tr("Add")); 108 p.add(Box.createHorizontalGlue(), GBC.std().fill(GBC.HORIZONTAL)); 109 p.add(add, GBC.std().insets(0, 5, 0, 0)); 110 add.addActionListener(new ActionListener() { 111 public void actionPerformed(ActionEvent e) { 112 JPanel p = new JPanel(new GridBagLayout()); 113 p.add(new JLabel(tr("Weight")), GBC.std().insets(0, 0, 5, 0)); 114 JComboBox key = new JComboBox(); 115 for (OsmWayTypes pk : OsmWayTypes.values()) 116 key.addItem(pk.getTag()); 117 JTextField value = new JTextField(10); 118 p.add(key, GBC.eop().insets(5, 0, 0, 0).fill(GBC.HORIZONTAL)); 119 p.add(new JLabel(tr("Value")), GBC.std().insets(0, 0, 5, 0)); 120 p.add(value, GBC.eol().insets(5, 0, 0, 0).fill(GBC.HORIZONTAL)); 121 int answer = JOptionPane.showConfirmDialog(gui, p, 122 tr("Enter weight values"), 123 JOptionPane.OK_CANCEL_OPTION); 124 if (answer == JOptionPane.OK_OPTION) { 125 model 126 .addRow(new String[] { 127 key.getSelectedItem().toString(), 128 value.getText() }); 129 } 130 } 131 }); 132 133 JButton delete = new JButton(tr("Delete")); 134 p.add(delete, GBC.std().insets(0, 5, 0, 0)); 135 delete.addActionListener(new ActionListener() { 136 public void actionPerformed(ActionEvent e) { 137 if (list.getSelectedRow() == -1) 138 JOptionPane.showMessageDialog(gui, 139 tr("Please select the row to delete.")); 140 else { 141 Integer i; 142 while ((i = list.getSelectedRow()) != -1) 143 model.removeRow(i); 144 } 145 } 146 }); 147 148 JButton edit = new JButton(tr("Edit")); 149 p.add(edit, GBC.std().insets(5, 5, 5, 0)); 150 edit.addActionListener(new ActionListener() { 151 public void actionPerformed(ActionEvent e) { 152 edit(gui, list); 153 } 154 }); 155 156 JTabbedPane Opciones = new JTabbedPane(); 157 Opciones.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT); 158 159 Opciones.addTab("Profile", null, p, null); 160 // Opciones.addTab("Preferences", new JPanel()); 161 162 list.addMouseListener(new MouseAdapter(){ 163 @Override public void mouseClicked(MouseEvent e) { 164 if (e.getClickCount() == 2) 165 edit(gui, list); 166 } 167 }); 168 169 principal.add(Opciones, GBC.eol().fill(GBC.BOTH)); 170 171 } 172 173 public boolean ok() { 174 for (int i = 0; i < model.getRowCount(); ++i) { 175 String value = model.getValueAt(i, 1).toString(); 176 if (value.length() != 0) { 177 String key = model.getValueAt(i, 0).toString(); 178 String origValue = orig.get(key); 179 if (origValue == null || !origValue.equals(value)) 180 Main.pref.put(key, value); 181 orig.remove(key); // processed. 182 } 183 } 184 for (Entry<String, String> e : orig.entrySet()) 185 Main.pref.put(e.getKey(), null); 186 return false; 187 } 188 189 private void edit(final PreferenceDialog gui, final JTable list) { 190 if (list.getSelectedRowCount() != 1) { 191 JOptionPane.showMessageDialog(gui, 192 tr("Please select the row to edit.")); 193 return; 194 } 195 String v = JOptionPane.showInputDialog(tr("New value for {0}", model 196 .getValueAt(list.getSelectedRow(), 0)), model.getValueAt(list 197 .getSelectedRow(), 1)); 198 if (v != null) 199 model.setValueAt(v, list.getSelectedRow(), 1); 200 } 201 202 private void loadSpeeds(DefaultTableModel model) { 203 // Read dialog values from preferences 204 readPreferences(); 205 // Put these values in the model 206 for (String tag : orig.keySet()) { 207 model.addRow(new String[] { tag, orig.get(tag) }); 208 } 209 } 210 211 private void readPreferences() { 212 orig = Main.pref.getAllPrefix("routing.profile.default.speed"); 213 if (orig.size() == 0) { // defaults 214 logger.debug("Loading Default Preferences."); 215 for (OsmWayTypes owt : OsmWayTypes.values()) { 216 Main.pref.putInteger("routing.profile.default.speed." 217 + owt.getTag(), owt.getSpeed()); 218 } 219 orig = Main.pref.getAllPrefix("routing.profile.default.speed"); 220 } 221 else logger.debug("Default preferences already exist."); 222 } 223 224 private String getKeyTag(String tag) { 225 return tag.split(".", 5)[4]; 226 } 227 228 private String getTypeTag(String tag) { 229 return tag.split(".", 5)[3]; 230 } 231 232 private String getNameTag(String tag) { 233 return tag.split(".", 5)[2]; 234 } 235 235 } -
applications/editors/josm/plugins/slippymap/build.xml
r14015 r15707 26 26 <attribute name="Plugin-Description" value="Displays a slippy map grid in JOSM. Can load tiles from slippy map as background and request updates."/> 27 27 <attribute name="Plugin-Link" value="http://wiki.openstreetmap.org/index.php/JOSM/Plugins/SlippyMap"/> 28 <attribute name="Plugin-Mainversion" value="1 465"/>28 <attribute name="Plugin-Mainversion" value="1646"/> 29 29 <attribute name="Plugin-Version" value="${version.entry.commit.revision}"/> 30 30 </manifest> -
applications/editors/josm/plugins/slippymap/src/org/openstreetmap/josm/plugins/slippymap/SlippyMapLayer.java
r14732 r15707 36 36 /** 37 37 * Class that displays a slippy map layer. 38 * 38 * 39 39 * @author Frederik Ramm <frederik@remote.org> 40 40 * @author LuVar <lubomir.varga@freemap.sk> 41 41 * @author Dave Hansen <dave@sr71.net> 42 * 42 * 43 43 */ 44 44 public class SlippyMapLayer extends Layer implements ImageObserver, 45 PreferenceChangedListener { 46 /** 47 * Actual zoom lvl. Initial zoom lvl is set to 48 * {@link SlippyMapPreferences#getMinZoomLvl()}. 49 */ 50 public int currentZoomLevel = SlippyMapPreferences.getMinZoomLvl(); 51 private HashMap<SlippyMapKey, SlippyMapTile> tileStorage = null; 52 53 Point[][] pixelpos = new Point[21][21]; 54 LatLon lastTopLeft; 55 LatLon lastBotRight; 56 int z12x0, z12x1, z12y0, z12y1; 57 private Image bufferImage; 58 private SlippyMapTile clickedTile; 59 private boolean needRedraw; 60 private JPopupMenu tileOptionMenu; 61 62 @SuppressWarnings("serial") 63 public SlippyMapLayer() { 64 super(tr("Slippy Map")); 65 background = true; 66 67 clearTileStorage(); 68 69 tileOptionMenu = new JPopupMenu(); 70 tileOptionMenu.add(new JMenuItem(new AbstractAction(tr("Load Tile")) { 71 public void actionPerformed(ActionEvent ae) { 72 if (clickedTile != null) { 73 loadSingleTile(clickedTile); 74 needRedraw = true; 75 Main.map.repaint(); 76 } 77 } 78 })); 79 80 tileOptionMenu.add(new JMenuItem(new AbstractAction( 81 tr("Show Tile Status")) { 82 public void actionPerformed(ActionEvent ae) { 83 if (clickedTile != null) { 84 clickedTile.loadMetadata(); 85 needRedraw = true; 86 Main.map.repaint(); 87 } 88 } 89 })); 90 91 tileOptionMenu.add(new JMenuItem(new AbstractAction( 92 tr("Request Update")) { 93 public void actionPerformed(ActionEvent ae) { 94 if (clickedTile != null) { 95 clickedTile.requestUpdate(); 96 needRedraw = true; 97 Main.map.repaint(); 98 } 99 } 100 })); 101 102 tileOptionMenu.add(new JMenuItem(new AbstractAction( 103 tr("Load All Tiles")) { 104 public void actionPerformed(ActionEvent ae) { 105 loadAllTiles(); 106 needRedraw = true; 107 Main.map.repaint(); 108 } 109 })); 110 111 // increase and decrease commands 112 tileOptionMenu.add(new JMenuItem( 113 new AbstractAction(tr("Increase zoom")) { 114 public void actionPerformed(ActionEvent ae) { 115 increaseZoomLevel(); 116 needRedraw = true; 117 Main.map.repaint(); 118 } 119 })); 120 121 tileOptionMenu.add(new JMenuItem( 122 new AbstractAction(tr("Decrease zoom")) { 123 public void actionPerformed(ActionEvent ae) { 124 decreaseZoomLevel(); 125 Main.map.repaint(); 126 } 127 })); 128 // end of adding menu commands 129 130 SwingUtilities.invokeLater(new Runnable() { 131 public void run() { 132 Main.map.mapView.addMouseListener(new MouseAdapter() { 133 @Override 134 public void mouseClicked(MouseEvent e) { 135 if (e.getButton() != MouseEvent.BUTTON3) 136 return; 137 clickedTile = getTileForPixelpos(e.getX(), e.getY()); 138 tileOptionMenu.show(e.getComponent(), e.getX(), e 139 .getY()); 140 } 141 }); 142 143 listeners.add(new LayerChangeListener() { 144 public void activeLayerChange(Layer oldLayer, Layer newLayer) { 145 } 146 147 public void layerAdded(Layer newLayer) { 148 } 149 150 public void layerRemoved(Layer oldLayer) { 151 Main.pref.listener.remove(SlippyMapLayer.this); 152 } 153 }); 154 } 155 }); 156 157 Main.pref.listener.add(this); 158 } 159 160 /** 161 * Zoom in, go closer to map. 162 */ 163 public void increaseZoomLevel() { 164 if (currentZoomLevel < SlippyMapPreferences.getMaxZoomLvl()) { 165 currentZoomLevel++; 166 Main.debug("increasing zoom level to: " + currentZoomLevel); 167 needRedraw = true; 168 } else { 169 System.err.println("current zoom lvl ("+currentZoomLevel+") couldnt be increased. "+ 170 "MaxZoomLvl ("+SlippyMapPreferences.getMaxZoomLvl()+") reached."); 171 } 172 } 173 174 /** 175 * Zoom out from map. 176 */ 177 public void decreaseZoomLevel() { 178 if (currentZoomLevel > SlippyMapPreferences.getMinZoomLvl()) { 179 Main.debug("decreasing zoom level to: " + currentZoomLevel); 180 currentZoomLevel--; 181 needRedraw = true; 182 } else { 183 System.err.println("current zoom lvl couldnt be decreased. MinZoomLvl reached."); 184 } 185 } 186 187 public void clearTileStorage() { 188 // when max zoom lvl is begin saved, this method is called and probably 189 // the setting isnt saved yet. 190 int maxZoom = 30; // SlippyMapPreferences.getMaxZoomLvl(); 191 tileStorage = new HashMap<SlippyMapKey, SlippyMapTile>(); 192 193 checkTileStorage(); 194 } 195 196 class TileTimeComp implements Comparator<SlippyMapTile> { 197 public int compare(SlippyMapTile s1, SlippyMapTile s2) { 198 long t1 = s1.access_time(); 199 long t2 = s2.access_time(); 200 if (s1 == s2) 201 return 0; 202 if (t1 == t2) { 203 t1 = s1.hashCode(); 204 t2 = s2.hashCode(); 205 } 206 if (t1 < t2) 207 return -1; 208 return 1; 209 } 210 } 211 212 long lastCheck = 0; 213 /** 214 * <p> 215 * Check if tiles.size() is not more than max_nr_tiles. If yes, oldest tiles by timestamp 216 * are fired out from cache. 217 * </p> 218 */ 219 public void checkTileStorage() { 220 int maxZoom = 30; // SlippyMapPreferences.getMaxZoomLvl(); 221 long now = System.currentTimeMillis(); 222 if (now - lastCheck < 1000) 223 return; 224 lastCheck = now; 225 TreeSet<SlippyMapTile> tiles = new TreeSet<SlippyMapTile>(new TileTimeComp()); 226 tiles.addAll(tileStorage.values()); 227 int max_nr_tiles = 100; 228 if (tiles.size() < max_nr_tiles) { 229 Main.debug("total of " + tiles.size() + " loaded tiles, size OK " + now); 230 return; 231 } 232 int nr_to_drop = tiles.size() - max_nr_tiles;; 233 Main.debug("total of " + tiles.size() + " tiles, need to flush " + nr_to_drop + " tiles"); 234 for (SlippyMapTile t : tiles) { 235 if (nr_to_drop <= 0) 236 break; 237 t.dropImage(); 238 nr_to_drop--; 239 } 240 } 241 242 void loadSingleTile(SlippyMapTile tile) 243 { 244 tile.loadImage(); 245 this.checkTileStorage(); 246 } 247 248 void loadAllTiles() { 249 MapView mv = Main.map.mapView; 250 LatLon topLeft = mv.getLatLon(0, 0); 251 LatLon botRight = mv.getLatLon(mv.getWidth(), mv.getHeight()); 252 z12x0 = lonToTileX(topLeft.lon()); 253 z12x1 = lonToTileX(botRight.lon()); 254 z12y0 = latToTileY(topLeft.lat()); 255 z12y1 = latToTileY(botRight.lat()); 256 if (z12x0 > z12x1) { 257 int tmp = z12x0; 258 z12x0 = z12x1; 259 z12x1 = tmp; 260 } 261 if (z12y0 > z12y1) { 262 int tmp = z12y0; 263 z12y0 = z12y1; 264 z12y1 = tmp; 265 } 266 // if there is more than 18 tiles on screen in any direction, do not 267 // load all tiles! 268 if (z12x1 - z12x0 > 18) { 269 System.out 270 .println("Not downloading all tiles because there is more than 18 tiles on X axis!"); 271 return; 272 } 273 if (z12y1 - z12y0 > 18) { 274 System.out 275 .println("Not downloading all tiles because there is more than 18 tiles on Y axis!"); 276 return; 277 } 278 279 for (int x = z12x0 - 1; x <= z12x1; x++) { 280 for (int y = z12y0 - 1; y <= z12y1; y++) { 281 SlippyMapKey key = new SlippyMapKey(currentZoomLevel, x, y); 282 SlippyMapTile tile = tileStorage.get(key); 283 if (!key.valid) { 284 System.out.println("paint-1() made invalid key"); 285 continue; 286 } 287 if (tile == null) 288 tileStorage.put(key, 289 tile = new SlippyMapTile(x, y, currentZoomLevel)); 290 if (tile.getImage() == null) { 291 this.loadSingleTile(tile); 292 } 293 } 294 } 295 } 296 297 /* 298 * Attempt to approximate how much the image is 299 * being scaled. For instance, a 100x100 image 300 * being scaled to 50x50 would return 0.25. 301 */ 302 double getImageScaling(Image img, Point p0, Point p1) 303 { 304 int realWidth = img.getWidth(this); 305 int realHeight = img.getHeight(this); 306 if (realWidth == -1 || realHeight == -1) 307 return 1.0; 308 int drawWidth = p1.x - p0.x; 309 int drawHeight = p1.x - p0.x; 310 311 double drawArea = drawWidth * drawHeight; 312 double realArea = realWidth * realHeight; 313 314 return drawArea / realArea; 315 } 316 317 /** 45 PreferenceChangedListener { 46 /** 47 * Actual zoom lvl. Initial zoom lvl is set to 48 * {@link SlippyMapPreferences#getMinZoomLvl()}. 318 49 */ 319 @Override 320 public void paint(Graphics g, MapView mv) { 321 long start = System.currentTimeMillis(); 322 LatLon topLeft = mv.getLatLon(0, 0); 323 LatLon botRight = mv.getLatLon(mv.getWidth(), mv.getHeight()); 324 Graphics oldg = g; 325 326 if (botRight.lon() == 0.0 || botRight.lat() == 0) { 327 // probably still initializing 328 return; 329 } 330 if (lastTopLeft != null && lastBotRight != null 331 && topLeft.equalsEpsilon(lastTopLeft) 332 && botRight.equalsEpsilon(lastBotRight) && bufferImage != null 333 && mv.getWidth() == bufferImage.getWidth(null) 334 && mv.getHeight() == bufferImage.getHeight(null) && !needRedraw) { 335 336 g.drawImage(bufferImage, 0, 0, null); 337 return; 338 } 339 340 needRedraw = false; 341 lastTopLeft = topLeft; 342 lastBotRight = botRight; 343 bufferImage = mv.createImage(mv.getWidth(), mv.getHeight()); 344 g = bufferImage.getGraphics(); 345 346 z12x0 = lonToTileX(topLeft.lon()); 347 z12x1 = lonToTileX(botRight.lon()); 348 z12y0 = latToTileY(topLeft.lat()); 349 z12y1 = latToTileY(botRight.lat()); 350 351 if (z12x0 > z12x1) { 352 int tmp = z12x0; 353 z12x0 = z12x1; 354 z12x1 = tmp; 355 } 356 if (z12y0 > z12y1) { 357 int tmp = z12y0; 358 z12y0 = z12y1; 359 z12y1 = tmp; 360 } 361 362 if (z12x1 - z12x0 > 18) 363 return; 364 if (z12y1 - z12y0 > 18) 365 return; 366 367 for (int x = z12x0 - 1; x <= z12x1 + 1; x++) { 368 double lon = tileXToLon(x); 369 for (int y = z12y0 - 1; y <= z12y1 + 1; y++) { 370 LatLon tmpLL = new LatLon(tileYToLat(y), lon); 371 pixelpos[x - z12x0 + 1][y - z12y0 + 1] = mv.getPoint(Main.proj 372 .latlon2eastNorth(tmpLL)); 373 } 374 } 375 376 int fontHeight = g.getFontMetrics().getHeight(); 377 378 g.setColor(Color.DARK_GRAY); 379 380 float fadeBackground = SlippyMapPreferences.getFadeBackground(); 381 382 Double imageScale = null; 383 int count = 0; 384 for (int x = z12x0 - 1; x <= z12x1; x++) { 385 for (int y = z12y0 - 1; y <= z12y1; y++) { 386 SlippyMapKey key = new SlippyMapKey(currentZoomLevel, x, y); 387 SlippyMapTile tile; 388 tile = tileStorage.get(key); 389 if (!key.valid) { 390 System.out.println("loadAllTiles() made invalid key"); 391 continue; 392 } 393 if (tile == null) { 394 tile = new SlippyMapTile(x, y, currentZoomLevel); 395 tileStorage.put(key, tile); 396 if (SlippyMapPreferences.getAutoloadTiles()) { 397 // TODO probably do on background 398 loadSingleTile(tile); 399 } 400 checkTileStorage(); 401 } 402 Image img = tile.getImage(); 403 404 if (img != null) { 405 Point p = pixelpos[x - z12x0 + 1][y - z12y0 + 1]; 406 Point p2 = pixelpos[x - z12x0 + 2][y - z12y0 + 2]; 407 g.drawImage(img, p.x, p.y, p2.x - p.x, p2.y - p.y, this); 408 if (imageScale == null) 409 imageScale = new Double(getImageScaling(img, p, p2)); 410 count++; 411 if (fadeBackground != 0f) { 412 // dimm by painting opaque rect... 413 g.setColor(new Color(1f, 1f, 1f, fadeBackground)); 414 g.fillRect(p.x, p.y, p2.x - p.x, p2.y - p.y); 415 }// end of if dim != 0 416 }// end of if img != null 417 }// end of for 418 }// end of for 419 g.setColor(Color.red); 420 for (int x = z12x0 - 1; x <= z12x1; x++) { 421 Point p = pixelpos[x - z12x0 + 1][0]; 422 423 if(SlippyMapPreferences.getDrawDebug()) { 424 if (x % 32 == 0) { 425 // level 7 tile boundary 426 g.fillRect(p.x - 1, 0, 3, mv.getHeight()); 427 } else { 428 g.drawLine(p.x, 0, p.x, mv.getHeight()); 429 } 430 }//end of if draw debug 431 432 for (int y = z12y0 - 1; y <= z12y1; y++) { 433 SlippyMapKey key = new SlippyMapKey(currentZoomLevel, x, y); 434 int texty = p.y + 2 + fontHeight; 435 SlippyMapTile tile = tileStorage.get(key); 436 if (tile == null) { 437 continue; 438 } 439 if (!key.valid) { 440 System.out.println("paint-0() made invalid key"); 441 continue; 442 } 443 if (tile.getImage() == null) { 444 loadSingleTile(tile); 445 } 446 p = pixelpos[x - z12x0 + 1][y - z12y0 + 2]; 447 448 if(SlippyMapPreferences.getDrawDebug()) { 449 g.drawString("x=" + x + " y=" + y + " z=" + currentZoomLevel 450 + "", p.x + 2, texty); 451 texty += 1 + fontHeight; 452 if ((x % 32 == 0) && (y % 32 == 0)) { 453 g.drawString("x=" + x / 32 + " y=" + y / 32 + " z=7", 454 p.x + 2, texty); 455 texty += 1 + fontHeight; 456 } 457 }//end of if draw debug 458 459 String md = tile.getMetadata(); 460 if (md != null) { 461 g.drawString(md, p.x + 2, texty); 462 texty += 1 + fontHeight; 463 } 464 465 if (tile.getImage() == null) { 466 g.drawString(tr("image not loaded"), p.x + 2, texty); 467 texty += 1 + fontHeight; 468 } 469 470 if(SlippyMapPreferences.getDrawDebug()) { 471 if (x == z12x0 - 1) { 472 if (y % 32 == 31) { 473 g.fillRect(0, p.y - 1, mv.getWidth(), 3); 474 } else { 475 g.drawLine(0, p.y, mv.getWidth(), p.y); 476 } 477 } 478 }//end of if draw debug 479 } // end of for 480 } 481 482 oldg.drawImage(bufferImage, 0, 0, null); 483 484 if (imageScale != null) { 485 // If each source image pixel is being stretched into > 3 486 // drawn pixels, zoom in... getting too pixelated 487 if (imageScale > 3) { 488 if (SlippyMapPreferences.getAutozoom()) { 489 Main.debug("autozoom increase: "+z12x1+" " + z12x0 + " " + z12y1 + " " + z12y0 490 + topLeft + " " + botRight + " scale: " + imageScale); 491 increaseZoomLevel(); 492 } 493 this.paint(oldg, mv); 494 } 495 496 // If each source image pixel is being squished into > 0.32 497 // of a drawn pixels, zoom out. 498 if (imageScale < 0.32) { 499 if (SlippyMapPreferences.getAutozoom()) { 500 Main.debug("autozoom decrease: "+z12x1+" " + z12x0 + " " + z12y1 + " " + z12y0 501 + topLeft + " " + botRight + " scale: " + imageScale); 502 decreaseZoomLevel(); 503 } 504 this.paint(oldg, mv); 505 } 506 } 507 g.setColor(Color.black); 508 g.drawString("currentZoomLevel=" + currentZoomLevel, 120, 120); 509 }// end of paint metod 510 511 SlippyMapTile getTileForPixelpos(int px, int py) { 512 int tilex = z12x1; 513 int tiley = z12y1; 514 for (int x = z12x0; x <= z12x1; x++) { 515 516 if (pixelpos[x - z12x0 + 1][0].x > px) { 517 tilex = x - 1; 518 break; 519 } 520 } 521 if (tilex == -1) 522 return null; 523 for (int y = z12y0; y <= z12y1; y++) { 524 525 if (pixelpos[0][y - z12y0 + 1].y > py) { 526 tiley = y - 1; 527 break; 528 } 529 } 530 if (tiley == -1) { 531 return null; 532 } 533 534 SlippyMapKey key = new SlippyMapKey(currentZoomLevel, tilex, tiley); 535 if (!key.valid) { 536 System.err.println("getTileForPixelpos("+px+","+py+") made invalid key"); 537 return null; 538 } 539 SlippyMapTile tile = tileStorage.get(key); 540 if (tile == null) 541 tileStorage.put(key, tile = new SlippyMapTile(tilex, tiley, currentZoomLevel)); 542 checkTileStorage(); 543 return tile; 544 } 545 546 @Override 547 public Icon getIcon() { 548 return ImageProvider.get("slippymap"); 549 } 550 551 @Override 552 public Object getInfoComponent() { 553 return null; 554 } 555 556 @Override 557 public Component[] getMenuEntries() { 558 return new Component[] { 559 new JMenuItem(new LayerListDialog.ShowHideLayerAction(this)), 560 new JMenuItem(new LayerListDialog.DeleteLayerAction(this)), 561 new JSeparator(), 562 // color, 563 new JMenuItem(new RenameLayerAction(associatedFile, this)), 564 new JSeparator(), 565 new JMenuItem(new LayerListPopup.InfoAction(this)) }; 566 } 567 568 @Override 569 public String getToolTipText() { 570 return null; 571 } 572 573 @Override 574 public boolean isMergable(Layer other) { 575 return false; 576 } 577 578 @Override 579 public void mergeFrom(Layer from) { 580 } 581 582 @Override 583 public void visitBoundingBox(BoundingXYVisitor v) { 584 } 585 586 private int latToTileY(double lat) { 587 double l = lat / 180 * Math.PI; 588 double pf = Math.log(Math.tan(l) + (1 / Math.cos(l))); 589 return (int) (Math.pow(2.0, currentZoomLevel - 1) * (Math.PI - pf) / Math.PI); 590 } 591 592 private int lonToTileX(double lon) { 593 return (int) (Math.pow(2.0, currentZoomLevel - 3) * (lon + 180.0) / 45.0); 594 } 595 596 private double tileYToLat(int y) { 597 return Math.atan(Math.sinh(Math.PI 598 - (Math.PI * y / Math.pow(2.0, currentZoomLevel - 1)))) 599 * 180 / Math.PI; 600 } 601 602 private double tileXToLon(int x) { 603 return x * 45.0 / Math.pow(2.0, currentZoomLevel - 3) - 180.0; 604 } 605 606 public boolean imageUpdate(Image img, int infoflags, int x, int y, 607 int width, int height) { 608 boolean done = ((infoflags & (ERROR | FRAMEBITS | ALLBITS)) != 0); 609 if ((infoflags & ERROR) != 0) { 610 String url = "unknown"; 611 for (SlippyMapTile tile : tileStorage.values()) { 612 if (tile.getImage() != img) 613 continue; 614 url = tile.getImageURL().toString(); 615 } 616 System.err.println("imageUpdate(" + img + ") error " + url +")"); 617 } 618 if ((infoflags & SOMEBITS) != 0) { 619 //if (y%100 == 0) 620 // System.out.println("imageUpdate("+img+") SOMEBITS ("+x+","+y+")"); 621 } 622 // Repaint immediately if we are done, otherwise batch up 623 // repaint requests every 100 milliseconds 624 needRedraw = true; 625 Main.map.repaint(done ? 0 : 100); 626 return !done; 627 } 628 629 /* 630 * (non-Javadoc) 631 * 632 * @seeorg.openstreetmap.josm.data.Preferences.PreferenceChangedListener# 633 * preferenceChanged(java.lang.String, java.lang.String) 634 */ 635 public void preferenceChanged(String key, String newValue) { 636 if (key.startsWith(SlippyMapPreferences.PREFERENCE_PREFIX)) { 637 // System.err.println(this + ".preferenceChanged('" + key + "', '" 638 // + newValue + "') called"); 639 // when fade background changed, no need to clear tile storage 640 // TODO move this code to SlippyMapPreferences class. 641 if (!key.equals(SlippyMapPreferences.PREFERENCE_FADE_BACKGROUND)) { 642 clearTileStorage(); 643 } 644 } 645 } 646 647 @Override 648 public void destroy() { 649 Main.pref.listener.remove(SlippyMapLayer.this); 650 } 50 public int currentZoomLevel = SlippyMapPreferences.getMinZoomLvl(); 51 private HashMap<SlippyMapKey, SlippyMapTile> tileStorage = null; 52 53 Point[][] pixelpos = new Point[21][21]; 54 LatLon lastTopLeft; 55 LatLon lastBotRight; 56 int z12x0, z12x1, z12y0, z12y1; 57 private Image bufferImage; 58 private SlippyMapTile clickedTile; 59 private boolean needRedraw; 60 private JPopupMenu tileOptionMenu; 61 62 @SuppressWarnings("serial") 63 public SlippyMapLayer() { 64 super(tr("Slippy Map")); 65 background = true; 66 67 clearTileStorage(); 68 69 tileOptionMenu = new JPopupMenu(); 70 tileOptionMenu.add(new JMenuItem(new AbstractAction(tr("Load Tile")) { 71 public void actionPerformed(ActionEvent ae) { 72 if (clickedTile != null) { 73 loadSingleTile(clickedTile); 74 needRedraw = true; 75 Main.map.repaint(); 76 } 77 } 78 })); 79 80 tileOptionMenu.add(new JMenuItem(new AbstractAction( 81 tr("Show Tile Status")) { 82 public void actionPerformed(ActionEvent ae) { 83 if (clickedTile != null) { 84 clickedTile.loadMetadata(); 85 needRedraw = true; 86 Main.map.repaint(); 87 } 88 } 89 })); 90 91 tileOptionMenu.add(new JMenuItem(new AbstractAction( 92 tr("Request Update")) { 93 public void actionPerformed(ActionEvent ae) { 94 if (clickedTile != null) { 95 clickedTile.requestUpdate(); 96 needRedraw = true; 97 Main.map.repaint(); 98 } 99 } 100 })); 101 102 tileOptionMenu.add(new JMenuItem(new AbstractAction( 103 tr("Load All Tiles")) { 104 public void actionPerformed(ActionEvent ae) { 105 loadAllTiles(); 106 needRedraw = true; 107 Main.map.repaint(); 108 } 109 })); 110 111 // increase and decrease commands 112 tileOptionMenu.add(new JMenuItem( 113 new AbstractAction(tr("Increase zoom")) { 114 public void actionPerformed(ActionEvent ae) { 115 increaseZoomLevel(); 116 needRedraw = true; 117 Main.map.repaint(); 118 } 119 })); 120 121 tileOptionMenu.add(new JMenuItem( 122 new AbstractAction(tr("Decrease zoom")) { 123 public void actionPerformed(ActionEvent ae) { 124 decreaseZoomLevel(); 125 Main.map.repaint(); 126 } 127 })); 128 // end of adding menu commands 129 130 SwingUtilities.invokeLater(new Runnable() { 131 public void run() { 132 Main.map.mapView.addMouseListener(new MouseAdapter() { 133 @Override 134 public void mouseClicked(MouseEvent e) { 135 if (e.getButton() != MouseEvent.BUTTON3) 136 return; 137 clickedTile = getTileForPixelpos(e.getX(), e.getY()); 138 tileOptionMenu.show(e.getComponent(), e.getX(), e 139 .getY()); 140 } 141 }); 142 143 listeners.add(new LayerChangeListener() { 144 public void activeLayerChange(Layer oldLayer, Layer newLayer) { 145 } 146 147 public void layerAdded(Layer newLayer) { 148 } 149 150 public void layerRemoved(Layer oldLayer) { 151 Main.pref.listener.remove(SlippyMapLayer.this); 152 } 153 }); 154 } 155 }); 156 157 Main.pref.listener.add(this); 158 } 159 160 /** 161 * Zoom in, go closer to map. 162 */ 163 public void increaseZoomLevel() { 164 if (currentZoomLevel < SlippyMapPreferences.getMaxZoomLvl()) { 165 currentZoomLevel++; 166 Main.debug("increasing zoom level to: " + currentZoomLevel); 167 needRedraw = true; 168 } else { 169 System.err.println("current zoom lvl ("+currentZoomLevel+") couldnt be increased. "+ 170 "MaxZoomLvl ("+SlippyMapPreferences.getMaxZoomLvl()+") reached."); 171 } 172 } 173 174 /** 175 * Zoom out from map. 176 */ 177 public void decreaseZoomLevel() { 178 if (currentZoomLevel > SlippyMapPreferences.getMinZoomLvl()) { 179 Main.debug("decreasing zoom level to: " + currentZoomLevel); 180 currentZoomLevel--; 181 needRedraw = true; 182 } else { 183 System.err.println("current zoom lvl couldnt be decreased. MinZoomLvl reached."); 184 } 185 } 186 187 public void clearTileStorage() { 188 // when max zoom lvl is begin saved, this method is called and probably 189 // the setting isnt saved yet. 190 int maxZoom = 30; // SlippyMapPreferences.getMaxZoomLvl(); 191 tileStorage = new HashMap<SlippyMapKey, SlippyMapTile>(); 192 193 checkTileStorage(); 194 } 195 196 class TileTimeComp implements Comparator<SlippyMapTile> { 197 public int compare(SlippyMapTile s1, SlippyMapTile s2) { 198 long t1 = s1.access_time(); 199 long t2 = s2.access_time(); 200 if (s1 == s2) 201 return 0; 202 if (t1 == t2) { 203 t1 = s1.hashCode(); 204 t2 = s2.hashCode(); 205 } 206 if (t1 < t2) 207 return -1; 208 return 1; 209 } 210 } 211 212 long lastCheck = 0; 213 /** 214 * <p> 215 * Check if tiles.size() is not more than max_nr_tiles. If yes, oldest tiles by timestamp 216 * are fired out from cache. 217 * </p> 218 */ 219 public void checkTileStorage() { 220 int maxZoom = 30; // SlippyMapPreferences.getMaxZoomLvl(); 221 long now = System.currentTimeMillis(); 222 if (now - lastCheck < 1000) 223 return; 224 lastCheck = now; 225 TreeSet<SlippyMapTile> tiles = new TreeSet<SlippyMapTile>(new TileTimeComp()); 226 tiles.addAll(tileStorage.values()); 227 int max_nr_tiles = 100; 228 if (tiles.size() < max_nr_tiles) { 229 Main.debug("total of " + tiles.size() + " loaded tiles, size OK " + now); 230 return; 231 } 232 int nr_to_drop = tiles.size() - max_nr_tiles;; 233 Main.debug("total of " + tiles.size() + " tiles, need to flush " + nr_to_drop + " tiles"); 234 for (SlippyMapTile t : tiles) { 235 if (nr_to_drop <= 0) 236 break; 237 t.dropImage(); 238 nr_to_drop--; 239 } 240 } 241 242 void loadSingleTile(SlippyMapTile tile) 243 { 244 tile.loadImage(); 245 this.checkTileStorage(); 246 } 247 248 void loadAllTiles() { 249 MapView mv = Main.map.mapView; 250 LatLon topLeft = mv.getLatLon(0, 0); 251 LatLon botRight = mv.getLatLon(mv.getWidth(), mv.getHeight()); 252 z12x0 = lonToTileX(topLeft.lon()); 253 z12x1 = lonToTileX(botRight.lon()); 254 z12y0 = latToTileY(topLeft.lat()); 255 z12y1 = latToTileY(botRight.lat()); 256 if (z12x0 > z12x1) { 257 int tmp = z12x0; 258 z12x0 = z12x1; 259 z12x1 = tmp; 260 } 261 if (z12y0 > z12y1) { 262 int tmp = z12y0; 263 z12y0 = z12y1; 264 z12y1 = tmp; 265 } 266 // if there is more than 18 tiles on screen in any direction, do not 267 // load all tiles! 268 if (z12x1 - z12x0 > 18) { 269 System.out 270 .println("Not downloading all tiles because there is more than 18 tiles on X axis!"); 271 return; 272 } 273 if (z12y1 - z12y0 > 18) { 274 System.out 275 .println("Not downloading all tiles because there is more than 18 tiles on Y axis!"); 276 return; 277 } 278 279 for (int x = z12x0 - 1; x <= z12x1; x++) { 280 for (int y = z12y0 - 1; y <= z12y1; y++) { 281 SlippyMapKey key = new SlippyMapKey(currentZoomLevel, x, y); 282 SlippyMapTile tile = tileStorage.get(key); 283 if (!key.valid) { 284 System.out.println("paint-1() made invalid key"); 285 continue; 286 } 287 if (tile == null) 288 tileStorage.put(key, 289 tile = new SlippyMapTile(x, y, currentZoomLevel)); 290 if (tile.getImage() == null) { 291 this.loadSingleTile(tile); 292 } 293 } 294 } 295 } 296 297 /* 298 * Attempt to approximate how much the image is 299 * being scaled. For instance, a 100x100 image 300 * being scaled to 50x50 would return 0.25. 301 */ 302 double getImageScaling(Image img, Point p0, Point p1) 303 { 304 int realWidth = img.getWidth(this); 305 int realHeight = img.getHeight(this); 306 if (realWidth == -1 || realHeight == -1) 307 return 1.0; 308 int drawWidth = p1.x - p0.x; 309 int drawHeight = p1.x - p0.x; 310 311 double drawArea = drawWidth * drawHeight; 312 double realArea = realWidth * realHeight; 313 314 return drawArea / realArea; 315 } 316 317 /** 318 */ 319 @Override 320 public void paint(Graphics g, MapView mv) { 321 long start = System.currentTimeMillis(); 322 LatLon topLeft = mv.getLatLon(0, 0); 323 LatLon botRight = mv.getLatLon(mv.getWidth(), mv.getHeight()); 324 Graphics oldg = g; 325 326 if (botRight.lon() == 0.0 || botRight.lat() == 0) { 327 // probably still initializing 328 return; 329 } 330 if (lastTopLeft != null && lastBotRight != null 331 && topLeft.equalsEpsilon(lastTopLeft) 332 && botRight.equalsEpsilon(lastBotRight) && bufferImage != null 333 && mv.getWidth() == bufferImage.getWidth(null) 334 && mv.getHeight() == bufferImage.getHeight(null) && !needRedraw) { 335 336 g.drawImage(bufferImage, 0, 0, null); 337 return; 338 } 339 340 needRedraw = false; 341 lastTopLeft = topLeft; 342 lastBotRight = botRight; 343 bufferImage = mv.createImage(mv.getWidth(), mv.getHeight()); 344 g = bufferImage.getGraphics(); 345 346 z12x0 = lonToTileX(topLeft.lon()); 347 z12x1 = lonToTileX(botRight.lon()); 348 z12y0 = latToTileY(topLeft.lat()); 349 z12y1 = latToTileY(botRight.lat()); 350 351 if (z12x0 > z12x1) { 352 int tmp = z12x0; 353 z12x0 = z12x1; 354 z12x1 = tmp; 355 } 356 if (z12y0 > z12y1) { 357 int tmp = z12y0; 358 z12y0 = z12y1; 359 z12y1 = tmp; 360 } 361 362 if (z12x1 - z12x0 > 18) 363 return; 364 if (z12y1 - z12y0 > 18) 365 return; 366 367 for (int x = z12x0 - 1; x <= z12x1 + 1; x++) { 368 double lon = tileXToLon(x); 369 for (int y = z12y0 - 1; y <= z12y1 + 1; y++) { 370 LatLon tmpLL = new LatLon(tileYToLat(y), lon); 371 pixelpos[x - z12x0 + 1][y - z12y0 + 1] = mv.getPoint(Main.proj 372 .latlon2eastNorth(tmpLL)); 373 } 374 } 375 376 int fontHeight = g.getFontMetrics().getHeight(); 377 378 g.setColor(Color.DARK_GRAY); 379 380 float fadeBackground = SlippyMapPreferences.getFadeBackground(); 381 382 Double imageScale = null; 383 int count = 0; 384 for (int x = z12x0 - 1; x <= z12x1; x++) { 385 for (int y = z12y0 - 1; y <= z12y1; y++) { 386 SlippyMapKey key = new SlippyMapKey(currentZoomLevel, x, y); 387 SlippyMapTile tile; 388 tile = tileStorage.get(key); 389 if (!key.valid) { 390 System.out.println("loadAllTiles() made invalid key"); 391 continue; 392 } 393 if (tile == null) { 394 tile = new SlippyMapTile(x, y, currentZoomLevel); 395 tileStorage.put(key, tile); 396 if (SlippyMapPreferences.getAutoloadTiles()) { 397 // TODO probably do on background 398 loadSingleTile(tile); 399 } 400 checkTileStorage(); 401 } 402 Image img = tile.getImage(); 403 404 if (img != null) { 405 Point p = pixelpos[x - z12x0 + 1][y - z12y0 + 1]; 406 Point p2 = pixelpos[x - z12x0 + 2][y - z12y0 + 2]; 407 g.drawImage(img, p.x, p.y, p2.x - p.x, p2.y - p.y, this); 408 if (imageScale == null) 409 imageScale = new Double(getImageScaling(img, p, p2)); 410 count++; 411 if (fadeBackground != 0f) { 412 // dimm by painting opaque rect... 413 g.setColor(new Color(1f, 1f, 1f, fadeBackground)); 414 g.fillRect(p.x, p.y, p2.x - p.x, p2.y - p.y); 415 }// end of if dim != 0 416 }// end of if img != null 417 }// end of for 418 }// end of for 419 g.setColor(Color.red); 420 for (int x = z12x0 - 1; x <= z12x1; x++) { 421 Point p = pixelpos[x - z12x0 + 1][0]; 422 423 if(SlippyMapPreferences.getDrawDebug()) { 424 if (x % 32 == 0) { 425 // level 7 tile boundary 426 g.fillRect(p.x - 1, 0, 3, mv.getHeight()); 427 } else { 428 g.drawLine(p.x, 0, p.x, mv.getHeight()); 429 } 430 }//end of if draw debug 431 432 for (int y = z12y0 - 1; y <= z12y1; y++) { 433 SlippyMapKey key = new SlippyMapKey(currentZoomLevel, x, y); 434 int texty = p.y + 2 + fontHeight; 435 SlippyMapTile tile = tileStorage.get(key); 436 if (tile == null) { 437 continue; 438 } 439 if (!key.valid) { 440 System.out.println("paint-0() made invalid key"); 441 continue; 442 } 443 if (tile.getImage() == null) { 444 loadSingleTile(tile); 445 } 446 p = pixelpos[x - z12x0 + 1][y - z12y0 + 2]; 447 448 if(SlippyMapPreferences.getDrawDebug()) { 449 g.drawString("x=" + x + " y=" + y + " z=" + currentZoomLevel 450 + "", p.x + 2, texty); 451 texty += 1 + fontHeight; 452 if ((x % 32 == 0) && (y % 32 == 0)) { 453 g.drawString("x=" + x / 32 + " y=" + y / 32 + " z=7", 454 p.x + 2, texty); 455 texty += 1 + fontHeight; 456 } 457 }//end of if draw debug 458 459 String md = tile.getMetadata(); 460 if (md != null) { 461 g.drawString(md, p.x + 2, texty); 462 texty += 1 + fontHeight; 463 } 464 465 if (tile.getImage() == null) { 466 g.drawString(tr("image not loaded"), p.x + 2, texty); 467 texty += 1 + fontHeight; 468 } 469 470 if(SlippyMapPreferences.getDrawDebug()) { 471 if (x == z12x0 - 1) { 472 if (y % 32 == 31) { 473 g.fillRect(0, p.y - 1, mv.getWidth(), 3); 474 } else { 475 g.drawLine(0, p.y, mv.getWidth(), p.y); 476 } 477 } 478 }//end of if draw debug 479 } // end of for 480 } 481 482 oldg.drawImage(bufferImage, 0, 0, null); 483 484 if (imageScale != null) { 485 // If each source image pixel is being stretched into > 3 486 // drawn pixels, zoom in... getting too pixelated 487 if (imageScale > 3) { 488 if (SlippyMapPreferences.getAutozoom()) { 489 Main.debug("autozoom increase: "+z12x1+" " + z12x0 + " " + z12y1 + " " + z12y0 490 + topLeft + " " + botRight + " scale: " + imageScale); 491 increaseZoomLevel(); 492 } 493 this.paint(oldg, mv); 494 } 495 496 // If each source image pixel is being squished into > 0.32 497 // of a drawn pixels, zoom out. 498 if (imageScale < 0.32) { 499 if (SlippyMapPreferences.getAutozoom()) { 500 Main.debug("autozoom decrease: "+z12x1+" " + z12x0 + " " + z12y1 + " " + z12y0 501 + topLeft + " " + botRight + " scale: " + imageScale); 502 decreaseZoomLevel(); 503 } 504 this.paint(oldg, mv); 505 } 506 } 507 g.setColor(Color.black); 508 g.drawString("currentZoomLevel=" + currentZoomLevel, 120, 120); 509 }// end of paint metod 510 511 SlippyMapTile getTileForPixelpos(int px, int py) { 512 int tilex = z12x1; 513 int tiley = z12y1; 514 for (int x = z12x0; x <= z12x1; x++) { 515 516 if (pixelpos[x - z12x0 + 1][0].x > px) { 517 tilex = x - 1; 518 break; 519 } 520 } 521 if (tilex == -1) 522 return null; 523 for (int y = z12y0; y <= z12y1; y++) { 524 525 if (pixelpos[0][y - z12y0 + 1].y > py) { 526 tiley = y - 1; 527 break; 528 } 529 } 530 if (tiley == -1) { 531 return null; 532 } 533 534 SlippyMapKey key = new SlippyMapKey(currentZoomLevel, tilex, tiley); 535 if (!key.valid) { 536 System.err.println("getTileForPixelpos("+px+","+py+") made invalid key"); 537 return null; 538 } 539 SlippyMapTile tile = tileStorage.get(key); 540 if (tile == null) 541 tileStorage.put(key, tile = new SlippyMapTile(tilex, tiley, currentZoomLevel)); 542 checkTileStorage(); 543 return tile; 544 } 545 546 @Override 547 public Icon getIcon() { 548 return ImageProvider.get("slippymap"); 549 } 550 551 @Override 552 public Object getInfoComponent() { 553 return null; 554 } 555 556 @Override 557 public Component[] getMenuEntries() { 558 return new Component[] { 559 new JMenuItem(new LayerListDialog.ShowHideLayerAction(this)), 560 new JMenuItem(new LayerListDialog.DeleteLayerAction(this)), 561 new JSeparator(), 562 // color, 563 new JMenuItem(new RenameLayerAction(getAssociatedFile(), this)), 564 new JSeparator(), 565 new JMenuItem(new LayerListPopup.InfoAction(this)) }; 566 } 567 568 @Override 569 public String getToolTipText() { 570 return null; 571 } 572 573 @Override 574 public boolean isMergable(Layer other) { 575 return false; 576 } 577 578 @Override 579 public void mergeFrom(Layer from) { 580 } 581 582 @Override 583 public void visitBoundingBox(BoundingXYVisitor v) { 584 } 585 586 private int latToTileY(double lat) { 587 double l = lat / 180 * Math.PI; 588 double pf = Math.log(Math.tan(l) + (1 / Math.cos(l))); 589 return (int) (Math.pow(2.0, currentZoomLevel - 1) * (Math.PI - pf) / Math.PI); 590 } 591 592 private int lonToTileX(double lon) { 593 return (int) (Math.pow(2.0, currentZoomLevel - 3) * (lon + 180.0) / 45.0); 594 } 595 596 private double tileYToLat(int y) { 597 return Math.atan(Math.sinh(Math.PI 598 - (Math.PI * y / Math.pow(2.0, currentZoomLevel - 1)))) 599 * 180 / Math.PI; 600 } 601 602 private double tileXToLon(int x) { 603 return x * 45.0 / Math.pow(2.0, currentZoomLevel - 3) - 180.0; 604 } 605 606 public boolean imageUpdate(Image img, int infoflags, int x, int y, 607 int width, int height) { 608 boolean done = ((infoflags & (ERROR | FRAMEBITS | ALLBITS)) != 0); 609 if ((infoflags & ERROR) != 0) { 610 String url = "unknown"; 611 for (SlippyMapTile tile : tileStorage.values()) { 612 if (tile.getImage() != img) 613 continue; 614 url = tile.getImageURL().toString(); 615 } 616 System.err.println("imageUpdate(" + img + ") error " + url +")"); 617 } 618 if ((infoflags & SOMEBITS) != 0) { 619 //if (y%100 == 0) 620 // System.out.println("imageUpdate("+img+") SOMEBITS ("+x+","+y+")"); 621 } 622 // Repaint immediately if we are done, otherwise batch up 623 // repaint requests every 100 milliseconds 624 needRedraw = true; 625 Main.map.repaint(done ? 0 : 100); 626 return !done; 627 } 628 629 /* 630 * (non-Javadoc) 631 * 632 * @seeorg.openstreetmap.josm.data.Preferences.PreferenceChangedListener# 633 * preferenceChanged(java.lang.String, java.lang.String) 634 */ 635 public void preferenceChanged(String key, String newValue) { 636 if (key.startsWith(SlippyMapPreferences.PREFERENCE_PREFIX)) { 637 // System.err.println(this + ".preferenceChanged('" + key + "', '" 638 // + newValue + "') called"); 639 // when fade background changed, no need to clear tile storage 640 // TODO move this code to SlippyMapPreferences class. 641 if (!key.equals(SlippyMapPreferences.PREFERENCE_FADE_BACKGROUND)) { 642 clearTileStorage(); 643 } 644 } 645 } 646 647 @Override 648 public void destroy() { 649 Main.pref.listener.remove(SlippyMapLayer.this); 650 } 651 651 } -
applications/editors/josm/plugins/tageditor/build.xml
r14839 r15707 50 50 --> 51 51 <target name="compile" depends="init"> 52 <echo message="compiling sources for ${plugin.jar .name} ... "/>52 <echo message="compiling sources for ${plugin.jar} ... "/> 53 53 <javac srcdir="src" classpath="${josm}" debug="true" destdir="${plugin.build.dir}"> 54 54 <compilerarg value="-Xlint:deprecation"/> -
applications/editors/josm/plugins/waydownloader
-
Property svn:ignore
set to
build
-
Property svn:ignore
set to
-
applications/editors/josm/plugins/wmsplugin/build.xml
r15185 r15707 29 29 <attribute name="Plugin-Description" value="Display georeferenced images as background in JOSM (WMS servers, Yahoo, ...)."/> 30 30 <attribute name="Plugin-Link" value="http://wiki.openstreetmap.org/wiki/JOSM/Plugins/WMSPlugin"/> 31 <attribute name="Plugin-Mainversion" value="16 10"/>31 <attribute name="Plugin-Mainversion" value="1646"/> 32 32 <attribute name="Plugin-Version" value="${version.entry.commit.revision}"/> 33 33 <attribute name="de_Plugin-Link" value="http://wiki.openstreetmap.org/wiki/DE:JOSM/Plugins/WMSPlugin"/> -
applications/editors/josm/plugins/wmsplugin/src/wmsplugin/WMSGrabber.java
r15185 r15707 85 85 if (urlWithPatterns) { 86 86 String proj = Main.proj.toCode(); 87 if( proj.equals("EPSG:3785")) // don't use mercator code87 if(Main.proj instanceof org.openstreetmap.josm.data.projection.Mercator) // don't use mercator code directly 88 88 proj = "EPSG:4326"; 89 89 -
applications/editors/josm/plugins/wmsplugin/src/wmsplugin/WMSLayer.java
r15185 r15707 23 23 import javax.swing.JOptionPane; 24 24 import javax.swing.JSeparator; 25 import javax.swing.filechooser.FileFilter;26 25 27 26 import org.openstreetmap.josm.Main; 28 import org.openstreetmap.josm.actions. ExtensionFileFilter;27 import org.openstreetmap.josm.actions.DiskAccessAction; 29 28 import org.openstreetmap.josm.data.Bounds; 30 29 import org.openstreetmap.josm.data.coor.EastNorth; … … 295 294 } 296 295 public void actionPerformed(ActionEvent ev) { 297 File f = openFileDialog(false); 296 File f = DiskAccessAction.createAndOpenSaveFileChooser( 297 tr("Save WMS layer"), ".wms"); 298 298 try 299 299 { … … 322 322 } 323 323 public void actionPerformed(ActionEvent ev) { 324 File f = openFileDialog(true); 324 JFileChooser fc = DiskAccessAction.createAndOpenFileChooser(true, 325 false, tr("Load WMS layer")); 326 if(fc == null) return; 327 File f = fc.getSelectedFile(); 325 328 if (f == null) return; 326 329 try … … 359 362 } 360 363 } 361 362 protected static JFileChooser createAndOpenFileChooser(boolean open, boolean multiple) {363 String curDir = Main.pref.get("lastDirectory");364 if (curDir.equals(""))365 curDir = ".";366 JFileChooser fc = new JFileChooser(new File(curDir));367 fc.setMultiSelectionEnabled(multiple);368 for (int i = 0; i < ExtensionFileFilter.filters.length; ++i)369 fc.addChoosableFileFilter(ExtensionFileFilter.filters[i]);370 fc.setAcceptAllFileFilterUsed(true);371 372 int answer = open ? fc.showOpenDialog(Main.parent) : fc.showSaveDialog(Main.parent);373 if (answer != JFileChooser.APPROVE_OPTION)374 return null;375 376 if (!fc.getCurrentDirectory().getAbsolutePath().equals(curDir))377 Main.pref.put("lastDirectory", fc.getCurrentDirectory().getAbsolutePath());378 379 if (!open) {380 File file = fc.getSelectedFile();381 if (file == null || (file.exists() && JOptionPane.YES_OPTION !=382 JOptionPane.showConfirmDialog(Main.parent, tr("File exists. Overwrite?"), tr("Overwrite"), JOptionPane.YES_NO_OPTION)))383 return null;384 }385 386 return fc;387 }388 389 public static File openFileDialog(boolean open) {390 JFileChooser fc = createAndOpenFileChooser(open, false);391 if (fc == null)392 return null;393 394 File file = fc.getSelectedFile();395 396 String fn = file.getPath();397 if (fn.indexOf('.') == -1) {398 FileFilter ff = fc.getFileFilter();399 if (ff instanceof ExtensionFileFilter)400 fn = "." + ((ExtensionFileFilter)ff).defaultExtension;401 else402 fn += ".osm";403 file = new File(fn);404 }405 return file;406 }407 364 }
Note:
See TracChangeset
for help on using the changeset viewer.
