Changeset 23192 in osm
- Timestamp:
- 2010-09-15T18:59:53+02:00 (14 years ago)
- Location:
- applications/editors/josm/plugins
- Files:
-
- 140 edited
Legend:
- Unmodified
- Added
- Removed
-
applications/editors/josm/plugins/00_plugin_dir_template/src/org/openstreetmap/josm/plugins/ImportImagePlugin/ImageImportPlugin.java
r23139 r23192 31 31 */ 32 32 public class ImageImportPlugin extends Plugin{ 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 33 34 private static Logger logger; 35 36 JMenu mainmenu = null; 37 JosmAction loadFileAction = null; 38 39 // custom Classloader 40 static ClassLoader pluginClassLoader; 41 42 // plugin proerties 43 static Properties pluginProps; 44 45 // path constants 46 static final String PLUGIN_DIR = Main.pref.getPluginsDirectory().getAbsolutePath() + "/ImageImportPlugin/"; 47 static final String PLUGINPROPERTIES_PATH = Main.pref.getPluginsDirectory().getAbsolutePath() + "/ImageImportPlugin/pluginProperties.properties"; 48 static final String PLUGINLIBRARIES_DIR = Main.pref.getPluginsDirectory().getAbsolutePath() + "/ImageImportPlugin/lib/"; 49 static final String PLUGINPROPERTIES_FILENAME = "pluginProperties.properties"; 50 static final String LOGGING_PROPERTIES_FILEPATH = Main.pref.getPluginsDirectory().getAbsolutePath() + "/ImageImportPlugin/log4j.properties/"; 51 52 53 public Properties getPluginProps() { 54 return pluginProps; 55 } 56 57 58 /** 59 * constructor 60 * 61 * @param info 62 */ 63 public ImageImportPlugin(PluginInformation info){ 64 super(info); 65 66 try { 67 68 // First create custom ClassLoader to load resources from the main JAR 69 pluginClassLoader = createPluginClassLoader(); 70 71 // Initialize logger 72 initializeLogger(pluginClassLoader); 73 74 // Check whether plugin has already been installed. Otherwise install 75 checkInstallation(); 76 77 // If resources are available load properties from plugin directory 78 if(pluginProps == null || pluginProps.isEmpty()) 79 { 80 pluginProps = new Properties(); 81 pluginProps.load(new File(PLUGINPROPERTIES_PATH).toURI().toURL().openStream()); 82 logger.debug("Plugin properties loaded"); 83 } 84 85 /* Change class path: 86 * Use java reflection methods to add URLs to the class-path. 87 * Changes take effect when calling methods of other plugin classes 88 * (new threads) 89 * */ 90 URLClassLoader sysLoader = (URLClassLoader) ClassLoader.getSystemClassLoader(); 91 String[] libraryNames = pluginProps.getProperty("libraries").split(","); 92 Class<URLClassLoader> sysclass = URLClassLoader.class; 93 Method method = sysclass.getDeclaredMethod("addURL", new Class[]{URL.class}); 94 method.setAccessible(true); 95 for (int i = 0; i < libraryNames.length; i++) { 96 File library = new File(PLUGINLIBRARIES_DIR + "/" + libraryNames[i]); 97 method.invoke(sysLoader, new Object[]{library.toURI().toURL()}); 98 } 99 100 101 // load information about supported reference systems 102 PluginOperations.loadCRSData(pluginProps); 103 104 // create new Action for menu entry 105 LoadImageAction loadFileAction = new LoadImageAction(); 106 loadFileAction.setEnabled(true); 107 108 // add menu entries 109 Main.main.menu.fileMenu.insert(loadFileAction, 8); 110 Main.main.menu.fileMenu.insertSeparator(9); 111 112 113 } catch (Exception e) { 114 logger.fatal("Error while loading plugin", e); 115 try { 116 throw e; 117 } catch (Exception e1) { 118 e1.printStackTrace(); 119 } 120 } 121 122 logger.info("Plugin successfully loaded."); 123 124 } 125 126 127 128 /** 129 * Checks whether plugin resources are available. 130 * If not, start install procedure. 131 * 132 * @throws IOException 133 */ 134 private void checkInstallation() throws IOException 135 { 136 137 // check plugin resource state 138 boolean isInstalled = true; 139 if(!new File(PLUGINPROPERTIES_PATH).exists() 140 || !new File(PLUGIN_DIR).exists() 141 || !new File(PLUGINLIBRARIES_DIR).exists()) 142 isInstalled = false; 143 144 145 // if properties file doesn't exist, install plugin 146 if(!isInstalled) 147 { 148 149 /*----------- Begin installation ---------------*/ 150 151 // check if plugin directory exist 152 File pluginDir = new File(PLUGIN_DIR); 153 if(!pluginDir.exists()){ 154 pluginDir.mkdir(); 155 } 156 157 // check if "lib" directory exist 158 File libDir = new File(PLUGINLIBRARIES_DIR); 159 if(!libDir.exists()){ 160 libDir.mkdir(); 161 } 162 163 // create local properties file 164 if(pluginProps == null || pluginProps.isEmpty()){ 165 166 FileWriter fw = new FileWriter(new File(PLUGINPROPERTIES_PATH)); 167 URL propertiesURL = pluginClassLoader.getResource("resources/" + PLUGINPROPERTIES_FILENAME); 168 pluginProps = new Properties(); 169 pluginProps.load(propertiesURL.openStream()); 170 pluginProps.store(fw, null); 171 fw.close(); 172 logger.debug("Plugin properties loaded"); 173 } 174 175 if(!new File(LOGGING_PROPERTIES_FILEPATH).exists()) 176 { 177 FileWriter fw = new FileWriter(new File(LOGGING_PROPERTIES_FILEPATH)); 178 URL propertiesURL = pluginClassLoader.getResource("resources/log4j.properties"); 179 Properties loggingProps = new Properties(); 180 loggingProps.load(propertiesURL.openStream()); 181 loggingProps.store(fw, null); 182 fw.close(); 183 logger.debug("Logging properties created"); 184 } 185 186 187 // Copy all needed JAR files to $PLUGIN_DIR$/lib/ 188 String[] libStrings = pluginProps.getProperty("libraries").split(","); 189 190 for (int i = 0; i < libStrings.length; i++) { 191 192 URL url = pluginClassLoader.getResource("lib/" + libStrings[i]); 193 194 FileOutputStream out = null; 195 196 try{ 197 out = new FileOutputStream(new File(libDir, libStrings[i])); 198 } catch (FileNotFoundException e) { 199 break; 200 } 201 202 BufferedInputStream in = null; 203 try 204 { 205 in = new BufferedInputStream(url.openStream()); 206 207 byte[] buffer = new byte[1024]; 208 while (true) 209 { 210 int count = in.read(buffer); 211 if (count == -1) 212 break; 213 out.write(buffer, 0, count); 214 } 215 } 216 finally 217 { 218 if (in != null) 219 in.close(); 220 } 221 } 222 logger.debug("Plugin successfully installed"); 223 } 224 } 225 226 227 /** 228 * Initialize logger using plugin classloader. 229 * 230 * @param cl 231 */ 232 private void initializeLogger(ClassLoader cl) { 233 234 Properties props = new Properties(); 235 try { 236 props.load(new File(LOGGING_PROPERTIES_FILEPATH).toURI().toURL().openStream()); 237 238 // Set file for logging here: 239 props.setProperty("log4j.appender.MyRoFiAppender.file", 240 (Main.pref.getPluginsDirectory().getAbsolutePath() + "/ImageImportPlugin/" + "log.log")); 241 242 PropertyConfigurator.configure(props); 243 244 logger = Logger.getLogger(ImageImportPlugin.class); 245 246 logger.info("Logger successfully initialized."); 247 248 return; 249 250 } catch (IOException e) { 251 System.out.println("Logging properties file not found. Using standard settings."); 252 } 253 254 // if no log4j.properties file can be found, initialize manually: 255 256 props.setProperty("log4j.rootLogger", "INFO, A"); 257 props.setProperty("log4j.appender.A", "org.apache.log4j.FileAppender"); 258 259 props.setProperty("log4j.appender.A.layout", 260 "org.apache.log4j.PatternLayout "); 261 props.setProperty("log4j.appender.A.layout.ConversionPattern", 262 "%d{ISO8601} %-5p [%t] %c: %m%n"); 263 264 // Set file for logging here: 265 props.setProperty("log4j.appender.A.file", 266 (Main.pref.getPluginsDirectory().getAbsolutePath() + "/ImageImportPlugin/" + "log.log")); 267 268 PropertyConfigurator.configure(props); 269 logger = Logger.getLogger(ImageImportPlugin.class); 270 logger.info("Logger successfully initialized with standard settings."); 271 272 } 273 274 /** 275 * get a plugin-specific classloader. 276 * 277 * @return 278 * @throws MalformedURLException 279 */ 280 private ClassLoader createPluginClassLoader() throws MalformedURLException 281 { 282 ClassLoader loader = null; 283 loader = URLClassLoader.newInstance( 284 new URL[] { new File(Main.pref.getPluginsDirectory().getAbsolutePath() + "/ImportImagePlugin.jar").toURI().toURL()}, 285 ImageImportPlugin.class.getClassLoader() 286 ); 287 288 return loader; 289 } 290 291 291 } -
applications/editors/josm/plugins/00_plugin_dir_template/src/org/openstreetmap/josm/plugins/ImportImagePlugin/ImageLayer.java
r23139 r23192 40 40 41 41 /** 42 * 42 * Layer which contains spatial referenced image data. 43 43 * 44 44 * @author Christoph Beekmans, Fabian Kowitz, Anna Robaszkiewicz, Oliver Kuhn, Martin Ulitzny … … 47 47 public class ImageLayer extends Layer { 48 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 // 150 // 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 49 private Logger logger = Logger.getLogger(ImageLayer.class); 50 51 private File imageFile; 52 53 private BufferedImage image = null; 54 55 // coordinates of upper left corner 56 private EastNorth upperLeft; 57 // Angle of rotation of the image 58 private double angle = 0.0; 59 60 // current bbox 61 private Envelope2D bbox; 62 63 // Layer icon 64 private Icon layericon = null; 65 66 // reference system of the oringinal image 67 private CoordinateReferenceSystem sourceRefSys; 68 69 70 71 /** 72 * Constructor 73 * 74 * @param file 75 * @throws IOException 76 */ 77 public ImageLayer(File file) throws IOException { 78 super(file.getName()); 79 80 this.imageFile = file; 81 this.image = (BufferedImage) createImage(); 82 layericon = new ImageIcon(ImageImportPlugin.pluginClassLoader.getResource("images/layericon.png")); 83 84 } 85 86 /** 87 * create spatial referenced image. 88 * 89 * @return 90 * @throws IOException 91 */ 92 private Image createImage() throws IOException { 93 94 // geotools type for images and value coverages 95 GridCoverage2D coverage = null; 96 try { 97 // create a grid coverage from the image 98 coverage = PluginOperations.createGridFromFile(imageFile, null); 99 this.sourceRefSys = coverage.getCoordinateReferenceSystem(); 100 101 // now reproject grid coverage 102 coverage = PluginOperations.reprojectCoverage(coverage, CRS.decode(Main.proj.toCode())); 103 104 } catch (FactoryException e) { 105 logger.error("Error while creating GridCoverage:",e); 106 throw new IOException(e.getMessage()); 107 } catch (Exception e) { 108 if(e.getMessage().contains("No projection file found")) 109 { 110 int useDefaultCRS = JOptionPane.showConfirmDialog(Main.parent, "<html>No projection file (.prj) found.<br>Use the default Coordinate Reference System instead?</html>", "Missing projection", JOptionPane.YES_NO_OPTION); 111 if (useDefaultCRS == 0) 112 { 113 try { 114 // create a grid coverage from the image 115 coverage = PluginOperations.createGridFromFile(imageFile, PluginOperations.defaultSourceCRS); 116 this.sourceRefSys = coverage.getCoordinateReferenceSystem(); 117 118 // now reproject grid coverage 119 coverage = PluginOperations.reprojectCoverage(coverage, CRS.decode(Main.proj.toCode())); 120 } catch (Exception e1) { 121 logger.error("Error while creating GridCoverage:",e1); 122 throw new IOException(e1); 123 } 124 } 125 else{ 126 logger.debug("Layer creation cancled by user due to missing projection information."); 127 throw new LayerCreationCancledException(); 128 } 129 130 } 131 else 132 { 133 logger.error("Error while creating GridCoverage:",e); 134 throw new IOException(e); 135 } 136 137 } 138 logger.debug("Coverage created: " + coverage); 139 140 // TODO 141 upperLeft = new EastNorth(coverage.getEnvelope2D().y, coverage 142 .getEnvelope2D().x 143 + coverage.getEnvelope2D().width); 144 angle = 0; 145 bbox = coverage.getEnvelope2D(); 146 147 // Refresh 148 // Main.map.mapView.repaint(); 149 // PlanarImage image = (PlanarImage) coverage.getRenderedImage(); 150 // logger.info("Color Model: " + coverage.getRenderedImage().getColorModel()); 151 ImageWorker worker = new ImageWorker(coverage.getRenderedImage()); 152 153 return worker.getBufferedImage(); 154 } 155 156 @Override 157 public void paint(Graphics2D g2, MapView mv, Bounds bounds) { 158 159 if (image != null && g2 != null) { 160 161 // Position image at the right graphical place 162 EastNorth center = Main.map.mapView.getCenter(); 163 EastNorth leftop = Main.map.mapView.getEastNorth(0, 0); 164 double pixel_per_lon_degree = (Main.map.mapView.getWidth() / 2.0) 165 / (center.east() - leftop.east()); 166 double pixel_per_lat_degree = (Main.map.mapView.getHeight() / 2.0) 167 / (leftop.north() - center.north()); 168 169 // This is now the offset in screen pixels 170 double pic_offset_x = ((upperLeft.east() - leftop.east()) * pixel_per_lon_degree); 171 double pic_offset_y = ((leftop.north() - upperLeft.north()) * pixel_per_lat_degree); 172 173 Graphics2D g = (Graphics2D) g2.create(); 174 175 // Move picture by offset from upper left corner 176 g.translate(pic_offset_x, pic_offset_y); 177 178 // Rotate image by angle 179 g.rotate(angle * Math.PI / 180.0); 180 181 // Determine scale to fit JOSM extents 182 ProjectionBounds projbounds = Main.map.mapView 183 .getProjectionBounds(); 184 185 double width = projbounds.max.getX() - projbounds.min.getX(); 186 double height = projbounds.max.getY() - projbounds.min.getY(); 187 188 double ratio_x = (this.bbox.getMaxY() - this.bbox.getMinY()) 189 / width; 190 double ratio_y = (this.bbox.getMaxX() - this.bbox.getMinX()) 191 / height; 192 193 double pixels4bbox_width = ratio_x * Main.map.mapView.getWidth(); 194 double pixels4bbox_height = ratio_y * Main.map.mapView.getHeight(); 195 196 // Scale image to JOSM extents 197 double scalex = pixels4bbox_width / image.getWidth(); 198 double scaley = pixels4bbox_height / image.getHeight(); 199 200 g.scale(scalex, scaley); 201 202 // Draw picture 203 g.drawImage(image, 0, 0, null); 204 205 } else { 206 logger.error("Error while dawing image: image == null or Graphics == null"); 207 } 208 } 209 210 public Envelope2D getBbox() { 211 return bbox; 212 } 213 214 @Override 215 public Icon getIcon() { 216 // TODO Auto-generated method stub 217 return this.layericon; 218 } 219 220 @Override 221 public Object getInfoComponent() { 222 // TODO Auto-generated method stub 223 return null; 224 } 225 226 @Override 227 public Component[] getMenuEntries() { 228 228 return new Component[]{ 229 229 new JMenuItem(LayerListDialog.getInstance().createActivateLayerAction(this)), … … 235 235 new JSeparator(), 236 236 new JMenuItem(new LayerListPopup.InfoAction(this))}; 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 237 } 238 239 @Override 240 public boolean isMergable(Layer arg0) { 241 // TODO Auto-generated method stub 242 return false; 243 } 244 245 @Override 246 public void mergeFrom(Layer arg0) { 247 // TODO Auto-generated method stub 248 249 } 250 251 @Override 252 public void visitBoundingBox(BoundingXYVisitor arg0) { 253 // TODO Auto-generated method stub 254 } 255 256 257 @Override 258 public String getToolTipText() { 259 // TODO Auto-generated method stub 260 return this.getName(); 261 } 262 263 264 public File getImageFile() { 265 return imageFile; 266 } 267 268 public BufferedImage getImage() { 269 return image; 270 } 271 272 /** 273 * loads the image and reprojects it using a transformation 274 * calculated by the new reference system. 275 * 276 * @param newRefSys 277 * @throws IOException 278 * @throws FactoryException 279 * @throws NoSuchAuthorityCodeException 280 */ 281 void resample(CoordinateReferenceSystem refSys) throws IOException, NoSuchAuthorityCodeException, FactoryException 282 { 283 284 GridCoverage2D coverage = PluginOperations.createGridFromFile(this.imageFile, refSys); 285 coverage = PluginOperations.reprojectCoverage(coverage, CRS.decode(Main.proj.toCode())); 286 this.bbox = coverage.getEnvelope2D(); 287 this.image = ((PlanarImage)coverage.getRenderedImage()).getAsBufferedImage(); 288 289 // TODO 290 upperLeft = new EastNorth(coverage.getEnvelope2D().y, coverage 291 .getEnvelope2D().x 292 + coverage.getEnvelope2D().width); 293 angle = 0; 294 295 // repaint and zoom to new bbox 296 Main.map.mapView.repaint(); 297 LatLon min = new LatLon(bbox.getMinX(), bbox.getMinY()); 298 LatLon max = new LatLon(bbox.getMaxX(), bbox.getMaxY()); 299 Main.map.mapView.zoomTo(new Bounds(min, max)); 300 301 302 } 303 304 /** 305 * Action that creates a dialog GUI element with properties of a layer. 306 * 307 */ 308 public class LayerPropertiesAction extends AbstractAction 309 { 310 public ImageLayer imageLayer; 311 312 public LayerPropertiesAction(ImageLayer imageLayer){ 313 super(tr("Layer Properties")); 314 this.imageLayer = imageLayer; 315 } 316 317 public void actionPerformed(ActionEvent arg0) { 318 319 LayerPropertiesDialog layerProps = new LayerPropertiesDialog(imageLayer, PluginOperations.crsDescriptions); 320 layerProps.setLocation(Main.parent.getWidth() / 4 , Main.parent.getHeight() / 4); 321 layerProps.setVisible(true); 322 } 323 324 } 325 326 /** 327 * Exception which represents that the layer creation has been cancled by the 328 * user. 329 * 330 */ 331 class LayerCreationCancledException extends IOException{ 332 } 333 334 335 336 public CoordinateReferenceSystem getSourceRefSys() { 337 return sourceRefSys; 338 } 339 340 public void setSourceRefSys(CoordinateReferenceSystem sourceRefSys) { 341 this.sourceRefSys = sourceRefSys; 342 } 343 343 } -
applications/editors/josm/plugins/00_plugin_dir_template/src/org/openstreetmap/josm/plugins/ImportImagePlugin/LayerPropertiesDialog.java
r23139 r23192 42 42 */ 43 43 public class LayerPropertiesDialog extends JFrame{ 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 44 45 private Vector<String> supportedCRS; 46 private ImageLayer imageLayer; 47 48 private JPanel mainPanel = null; 49 private JPanel jPanel = null; 50 private JPanel buttonPanel = null; 51 private JTabbedPane jTabbedPane = null; 52 private JPanel infoPanel = null; 53 private JPanel crsPanel = null; 54 private JButton okButton = null; 55 private JLabel layerNameLabel = null; 56 private JLabel layerNameValueLabel = null; 57 private JLabel imageFileLabel = null; 58 private JLabel imageFileValueLabel = null; 59 private JLabel sizeLabel = null; 60 private JLabel sizeValueLabel = null; 61 private JLabel crsLabel = null; 62 private JLabel crsValueLabel = null; 63 private JLabel extentLabel = null; 64 private JLabel defaultCRSDescriptorLabel = null; 65 private JLabel defaultCRSLabel = null; 66 private JTextField searchField = null; 67 private JScrollPane crsListScrollPane = null; 68 private JList crsJList = null; 69 private JButton useDefaultCRSButton = null; 70 private JButton applySelectedCRSButton = null; 71 private JButton setSelectedCRSAsDefaultButton = null; 72 private JLabel searchFieldLabel = null; 73 private JCheckBox eastingFirstCheckBox = null; 74 private JLabel eastingFirstLabel = null; 75 private JLabel tabDescriptionLabel = null; 76 private JLabel upperLeftLabel = null; 77 private JLabel lowerLeftLabel = null; 78 private JLabel upperRightLabel = null; 79 private JLabel lowerRightLabel = null; 80 private JLabel upperLeftValueLabel = null; 81 private JLabel upperRightValueLabel = null; 82 private JLabel lowerLeftValueLabel = null; 83 private JLabel lowerRightValueLabel = null; 84 private JLabel currentCRSLabel = null; 85 private JLabel currentCRSValueLabel = null; 86 87 /** 88 * This method initializes 89 * 90 */ 91 public LayerPropertiesDialog(ImageLayer imageLayer, Vector<String> supportedCRS) { 92 super(imageLayer.getName()); 93 this.supportedCRS = supportedCRS; 94 this.imageLayer = imageLayer; 95 initialize(); 96 } 97 98 /** 99 * This method initializes 100 * 101 */ 102 public LayerPropertiesDialog(Vector<String> supportedCRS) { 103 super(); 104 this.supportedCRS = supportedCRS; 105 initialize(); 106 } 107 108 109 /** 110 * This method initializes this 111 * 112 */ 113 private void initialize() { 114 114 this.setMinimumSize(new Dimension(404, 485)); 115 115 this.setContentPane(getMainPanel()); 116 116 this.setPreferredSize(new Dimension(404, 485)); 117 118 119 120 121 * This method initializes mainPanel 122 * 123 * @return javax.swing.JPanel 124 125 126 127 128 129 130 131 132 133 134 135 136 * This method initializes jPanel 137 * 138 * @return javax.swing.JPanel 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 * This method initializes buttonPanel 158 * 159 * @return javax.swing.JPanel 160 161 162 163 164 165 166 167 168 169 170 171 172 * This method initializes jTabbedPane 173 * 174 * @return javax.swing.JTabbedPane 175 176 177 178 179 180 181 182 183 184 185 186 * This method initializes infoPanel 187 * 188 * @return javax.swing.JPanel 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 * This method initializes crsPanel 284 * 285 * @return javax.swing.JPanel 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 * This method initializes okButton 342 * 343 * @return javax.swing.JButton 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 * This method initializes searchField 363 * 364 * @return javax.swing.JTextField 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 * This method initializes crsListScrollPane 393 * 394 * @return javax.swing.JScrollPane 395 396 397 398 399 400 401 402 403 404 405 406 * This method initializes crsJList 407 * 408 * @return javax.swing.JList 409 410 411 412 413 414 415 416 417 418 419 * This method initializes useDefaultCRSButton 420 * 421 * @return javax.swing.JButton 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 * This method initializes applySelectedCRSButton 462 * 463 * @return javax.swing.JButton 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 * This method initializes setSelectedCRSAsDefaultButton 509 * 510 * @return javax.swing.JButton 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 * This method initializes eastingFirstCheckBox 560 * 561 * @return javax.swing.JCheckBox 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 117 118 } 119 120 /** 121 * This method initializes mainPanel 122 * 123 * @return javax.swing.JPanel 124 */ 125 private JPanel getMainPanel() { 126 if (mainPanel == null) { 127 mainPanel = new JPanel(); 128 mainPanel.setLayout(null); 129 mainPanel.add(getJPanel(), null); 130 mainPanel.add(getButtonPanel(), null); 131 } 132 return mainPanel; 133 } 134 135 /** 136 * This method initializes jPanel 137 * 138 * @return javax.swing.JPanel 139 */ 140 private JPanel getJPanel() { 141 if (jPanel == null) { 142 GridBagConstraints gridBagConstraints = new GridBagConstraints(); 143 gridBagConstraints.fill = GridBagConstraints.BOTH; 144 gridBagConstraints.gridy = 0; 145 gridBagConstraints.weightx = 1.0; 146 gridBagConstraints.weighty = 1.0; 147 gridBagConstraints.gridx = 0; 148 jPanel = new JPanel(); 149 jPanel.setLayout(new GridBagLayout()); 150 jPanel.setBounds(new Rectangle(0, 0, 391, 406)); 151 jPanel.add(getJTabbedPane(), gridBagConstraints); 152 } 153 return jPanel; 154 } 155 156 /** 157 * This method initializes buttonPanel 158 * 159 * @return javax.swing.JPanel 160 */ 161 private JPanel getButtonPanel() { 162 if (buttonPanel == null) { 163 buttonPanel = new JPanel(); 164 buttonPanel.setLayout(null); 165 buttonPanel.setBounds(new Rectangle(0, 405, 391, 46)); 166 buttonPanel.add(getOkButton(), null); 167 } 168 return buttonPanel; 169 } 170 171 /** 172 * This method initializes jTabbedPane 173 * 174 * @return javax.swing.JTabbedPane 175 */ 176 private JTabbedPane getJTabbedPane() { 177 if (jTabbedPane == null) { 178 jTabbedPane = new JTabbedPane(); 179 jTabbedPane.addTab("General Information", null, getInfoPanel(), null); 180 jTabbedPane.addTab("Source Reference System", null, getCrsPanel(), null); 181 } 182 return jTabbedPane; 183 } 184 185 /** 186 * This method initializes infoPanel 187 * 188 * @return javax.swing.JPanel 189 */ 190 private JPanel getInfoPanel() { 191 if (infoPanel == null) { 192 lowerRightValueLabel = new JLabel(); 193 lowerRightValueLabel.setBounds(new Rectangle(210, 315, 134, 16)); 194 lowerRightValueLabel.setHorizontalAlignment(SwingConstants.RIGHT); 195 lowerRightValueLabel.setText((float)imageLayer.getBbox().getMinX() + ", " + (float)imageLayer.getBbox().getMaxY()); 196 lowerLeftValueLabel = new JLabel(); 197 lowerLeftValueLabel.setBounds(new Rectangle(30, 315, 133, 16)); 198 lowerLeftValueLabel.setHorizontalAlignment(SwingConstants.LEFT); 199 lowerLeftValueLabel.setText((float)imageLayer.getBbox().getMinX() + ", " + (float)imageLayer.getBbox().getMinY()); 200 upperRightValueLabel = new JLabel(); 201 upperRightValueLabel.setBounds(new Rectangle(210, 255, 138, 16)); 202 upperRightValueLabel.setHorizontalAlignment(SwingConstants.RIGHT); 203 upperRightValueLabel.setText((float)imageLayer.getBbox().getMaxX() + ", " + (float)imageLayer.getBbox().getMaxY()); 204 upperLeftValueLabel = new JLabel(); 205 upperLeftValueLabel.setBounds(new Rectangle(30, 255, 133, 16)); 206 upperLeftValueLabel.setHorizontalAlignment(SwingConstants.LEFT); 207 upperLeftValueLabel.setText((float)imageLayer.getBbox().getMaxX() + ", " + (float)imageLayer.getBbox().getMinY()); 208 lowerRightLabel = new JLabel(); 209 lowerRightLabel.setBounds(new Rectangle(287, 344, 74, 16)); 210 lowerRightLabel.setText("Lower Right"); 211 upperRightLabel = new JLabel(); 212 upperRightLabel.setBounds(new Rectangle(285, 225, 91, 16)); 213 upperRightLabel.setText("Upper Right"); 214 lowerLeftLabel = new JLabel(); 215 lowerLeftLabel.setBounds(new Rectangle(15, 345, 92, 16)); 216 lowerLeftLabel.setText("Lower Left"); 217 upperLeftLabel = new JLabel(); 218 upperLeftLabel.setBounds(new Rectangle(15, 224, 91, 16)); 219 upperLeftLabel.setText("Upper Left"); 220 extentLabel = new JLabel(); 221 extentLabel.setBounds(new Rectangle(120, 195, 136, 16)); 222 extentLabel.setEnabled(false); 223 extentLabel.setHorizontalAlignment(SwingConstants.CENTER); 224 extentLabel.setDisplayedMnemonic(KeyEvent.VK_UNDEFINED); 225 extentLabel.setText("Extent"); 226 crsValueLabel = new JLabel(); 227 crsValueLabel.setBounds(new Rectangle(150, 150, 226, 16)); 228 229 String crsDescription = ""; 230 try { 231 crsDescription = imageLayer.getBbox().getCoordinateReferenceSystem().getIdentifiers().iterator().next().toString(); 232 } catch (Exception e) { 233 } 234 crsValueLabel.setText(crsDescription + "(" + imageLayer.getBbox().getCoordinateReferenceSystem().getName().toString() + ")"); 235 236 crsLabel = new JLabel(); 237 crsLabel.setBounds(new Rectangle(15, 150, 118, 16)); 238 crsLabel.setText("Reference System"); 239 sizeValueLabel = new JLabel(); 240 sizeValueLabel.setBounds(new Rectangle(150, 105, 226, 16)); 241 sizeValueLabel.setText(imageLayer.getImage().getHeight() + " x " + imageLayer.getImage().getWidth()); 242 sizeLabel = new JLabel(); 243 sizeLabel.setBounds(new Rectangle(15, 105, 121, 16)); 244 sizeLabel.setText("Image size"); 245 imageFileValueLabel = new JLabel(); 246 imageFileValueLabel.setBounds(new Rectangle(150, 60, 226, 16)); 247 imageFileValueLabel.setText(imageLayer.getImageFile().getAbsolutePath()); 248 imageFileValueLabel.setToolTipText(imageLayer.getImageFile().getAbsolutePath()); 249 imageFileLabel = new JLabel(); 250 imageFileLabel.setBounds(new Rectangle(15, 60, 121, 16)); 251 imageFileLabel.setText("Image file"); 252 layerNameValueLabel = new JLabel(); 253 layerNameValueLabel.setBounds(new Rectangle(150, 15, 226, 16)); 254 layerNameValueLabel.setText(imageLayer.getName()); 255 layerNameLabel = new JLabel(); 256 layerNameLabel.setBounds(new Rectangle(15, 15, 121, 16)); 257 layerNameLabel.setText("Layer name"); 258 infoPanel = new JPanel(); 259 infoPanel.setLayout(null); 260 infoPanel.setFont(new Font("Dialog", Font.BOLD, 12)); 261 infoPanel.add(layerNameLabel, null); 262 infoPanel.add(layerNameValueLabel, null); 263 infoPanel.add(imageFileLabel, null); 264 infoPanel.add(imageFileValueLabel, null); 265 infoPanel.add(sizeLabel, null); 266 infoPanel.add(sizeValueLabel, null); 267 infoPanel.add(crsLabel, null); 268 infoPanel.add(crsValueLabel, null); 269 infoPanel.add(extentLabel, null); 270 infoPanel.add(upperLeftLabel, null); 271 infoPanel.add(lowerLeftLabel, null); 272 infoPanel.add(upperRightLabel, null); 273 infoPanel.add(lowerRightLabel, null); 274 infoPanel.add(upperLeftValueLabel, null); 275 infoPanel.add(upperRightValueLabel, null); 276 infoPanel.add(lowerLeftValueLabel, null); 277 infoPanel.add(lowerRightValueLabel, null); 278 } 279 return infoPanel; 280 } 281 282 /** 283 * This method initializes crsPanel 284 * 285 * @return javax.swing.JPanel 286 */ 287 private JPanel getCrsPanel() { 288 if (crsPanel == null) { 289 currentCRSValueLabel = new JLabel(); 290 currentCRSValueLabel.setBounds(new Rectangle(78, 33, 297, 16)); 291 String crsDescription = "unknown"; 292 try { 293 crsDescription = imageLayer.getSourceRefSys().getIdentifiers().iterator().next().toString(); 294 } catch (Exception e) { 295 } 296 currentCRSValueLabel.setText(crsDescription); 297 298 currentCRSLabel = new JLabel(); 299 currentCRSLabel.setBounds(new Rectangle(15, 33, 52, 16)); 300 currentCRSLabel.setText("Current:"); 301 tabDescriptionLabel = new JLabel(); 302 tabDescriptionLabel.setBounds(new Rectangle(15, 9, 361, 16)); 303 tabDescriptionLabel.setText("Set here the source reference system of the image"); 304 eastingFirstLabel = new JLabel(); 305 eastingFirstLabel.setBounds(new Rectangle(315, 210, 76, 46)); 306 eastingFirstLabel.setHorizontalTextPosition(SwingConstants.TRAILING); 307 eastingFirstLabel.setHorizontalAlignment(SwingConstants.CENTER); 308 eastingFirstLabel.setText("<html>Easting<br>first</html>"); 309 searchFieldLabel = new JLabel(); 310 searchFieldLabel.setBounds(new Rectangle(298, 114, 84, 16)); 311 searchFieldLabel.setDisplayedMnemonic(KeyEvent.VK_UNDEFINED); 312 searchFieldLabel.setHorizontalTextPosition(SwingConstants.TRAILING); 313 searchFieldLabel.setHorizontalAlignment(SwingConstants.CENTER); 314 searchFieldLabel.setText("Search"); 315 defaultCRSLabel = new JLabel(); 316 defaultCRSLabel.setBounds(new Rectangle(15, 89, 361, 16)); 317 defaultCRSLabel.setText(PluginOperations.defaultSourceCRSDescription); 318 defaultCRSDescriptorLabel = new JLabel(); 319 defaultCRSDescriptorLabel.setBounds(new Rectangle(15, 63, 226, 16)); 320 defaultCRSDescriptorLabel.setText("Default Reference System:"); 321 crsPanel = new JPanel(); 322 crsPanel.setLayout(null); 323 crsPanel.add(defaultCRSDescriptorLabel, null); 324 crsPanel.add(defaultCRSLabel, null); 325 crsPanel.add(getSearchField(), null); 326 crsPanel.add(getCrsListScrollPane(), null); 327 crsPanel.add(getUseDefaultCRSButton(), null); 328 crsPanel.add(getApplySelectedCRSButton(), null); 329 crsPanel.add(getSetSelectedCRSAsDefaultButton(), null); 330 crsPanel.add(searchFieldLabel, null); 331 crsPanel.add(getEastingFirstCheckBox(), null); 332 crsPanel.add(eastingFirstLabel, null); 333 crsPanel.add(tabDescriptionLabel, null); 334 crsPanel.add(currentCRSLabel, null); 335 crsPanel.add(currentCRSValueLabel, null); 336 } 337 return crsPanel; 338 } 339 340 /** 341 * This method initializes okButton 342 * 343 * @return javax.swing.JButton 344 */ 345 private JButton getOkButton() { 346 if (okButton == null) { 347 okButton = new JButton(); 348 okButton.setBounds(new Rectangle(134, 5, 136, 31)); 349 okButton.setText("OK"); 350 okButton.addActionListener(new java.awt.event.ActionListener() { 351 public void actionPerformed(java.awt.event.ActionEvent e) { 352 353 setVisible(false); 354 dispose(); 355 } 356 }); 357 } 358 return okButton; 359 } 360 361 /** 362 * This method initializes searchField 363 * 364 * @return javax.swing.JTextField 365 */ 366 private JTextField getSearchField() { 367 if (searchField == null) { 368 searchField = new JTextField(); 369 searchField.setBounds(new Rectangle(13, 111, 282, 20)); 370 searchField.setToolTipText("Enter keywords or EPSG codes"); 371 searchField.addKeyListener(new java.awt.event.KeyAdapter() { 372 public void keyTyped(java.awt.event.KeyEvent e) { 373 374 for (Iterator iterator = supportedCRS.iterator(); iterator 375 .hasNext();) { 376 String type = (String) iterator.next(); 377 if(type.contains(searchField.getText())) 378 { 379 crsJList.setSelectedIndex(supportedCRS.indexOf(type)); 380 crsJList.ensureIndexIsVisible(supportedCRS.indexOf(type)); 381 break; 382 } 383 384 } 385 } 386 }); 387 } 388 return searchField; 389 } 390 391 /** 392 * This method initializes crsListScrollPane 393 * 394 * @return javax.swing.JScrollPane 395 */ 396 private JScrollPane getCrsListScrollPane() { 397 if (crsListScrollPane == null) { 398 crsListScrollPane = new JScrollPane(); 399 crsListScrollPane.setBounds(new Rectangle(15, 135, 301, 241)); 400 crsListScrollPane.setViewportView(getCrsJList()); 401 } 402 return crsListScrollPane; 403 } 404 405 /** 406 * This method initializes crsJList 407 * 408 * @return javax.swing.JList 409 */ 410 private JList getCrsJList() { 411 if (crsJList == null) { 412 crsJList = new JList(supportedCRS); 413 crsJList.addListSelectionListener(new ListSelectionHandler()); 414 } 415 return crsJList; 416 } 417 418 /** 419 * This method initializes useDefaultCRSButton 420 * 421 * @return javax.swing.JButton 422 */ 423 private JButton getUseDefaultCRSButton() { 424 if (useDefaultCRSButton == null) { 425 useDefaultCRSButton = new JButton(); 426 useDefaultCRSButton.setBounds(new Rectangle(253, 54, 118, 28)); 427 useDefaultCRSButton.setText("Apply Default"); 428 useDefaultCRSButton.addActionListener(new java.awt.event.ActionListener() { 429 public void actionPerformed(java.awt.event.ActionEvent e) { 430 431 try { 432 433 setCursor(new Cursor(Cursor.WAIT_CURSOR)); 434 if(PluginOperations.defaultSourceCRS != null){ 435 imageLayer.resample(PluginOperations.defaultSourceCRS); 436 }else 437 { 438 JOptionPane.showMessageDialog(getContentPane(), "<html>No default reference system available.<br>Please select one from the list</html>"); 439 } 440 441 } catch (NoSuchAuthorityCodeException e1) { 442 // TODO Auto-generated catch block 443 e1.printStackTrace(); 444 } catch (FactoryException e1) { 445 // TODO Auto-generated catch block 446 e1.printStackTrace(); 447 } catch (IOException e2) { 448 // TODO Auto-generated catch block 449 e2.printStackTrace(); 450 } 451 finally{ 452 setCursor(new Cursor(Cursor.DEFAULT_CURSOR)); 453 } 454 } 455 }); 456 } 457 return useDefaultCRSButton; 458 } 459 460 /** 461 * This method initializes applySelectedCRSButton 462 * 463 * @return javax.swing.JButton 464 */ 465 private JButton getApplySelectedCRSButton() { 466 if (applySelectedCRSButton == null) { 467 applySelectedCRSButton = new JButton(); 468 applySelectedCRSButton.setBounds(new Rectangle(315, 135, 69, 61)); 469 applySelectedCRSButton.setHorizontalAlignment(SwingConstants.CENTER); 470 applySelectedCRSButton.setHorizontalTextPosition(SwingConstants.TRAILING); 471 applySelectedCRSButton.setText("<html>Apply<br>Selection</html>"); 472 applySelectedCRSButton.addActionListener(new java.awt.event.ActionListener() { 473 public void actionPerformed(java.awt.event.ActionEvent e) { 474 475 String selection = (String) crsJList.getSelectedValue(); 476 String code = selection.substring(selection.indexOf("[-") + 2, selection.indexOf("-]")); 477 478 CoordinateReferenceSystem newRefSys = null; 479 try { 480 newRefSys = CRS.decode(code, eastingFirstCheckBox.isSelected()); 481 482 setCursor(new Cursor(Cursor.WAIT_CURSOR)); 483 484 imageLayer.resample(newRefSys); 485 486 } catch (NoSuchAuthorityCodeException e1) { 487 // TODO Auto-generated catch block 488 e1.printStackTrace(); 489 } catch (FactoryException e1) { 490 // TODO Auto-generated catch block 491 e1.printStackTrace(); 492 } catch (IOException e2) { 493 // TODO Auto-generated catch block 494 e2.printStackTrace(); 495 } 496 finally{ 497 setCursor(new Cursor(Cursor.DEFAULT_CURSOR)); 498 } 499 500 501 } 502 }); 503 } 504 return applySelectedCRSButton; 505 } 506 507 /** 508 * This method initializes setSelectedCRSAsDefaultButton 509 * 510 * @return javax.swing.JButton 511 */ 512 private JButton getSetSelectedCRSAsDefaultButton() { 513 if (setSelectedCRSAsDefaultButton == null) { 514 setSelectedCRSAsDefaultButton = new JButton(); 515 setSelectedCRSAsDefaultButton.setBounds(new Rectangle(315, 300, 69, 61)); 516 setSelectedCRSAsDefaultButton.setText("<html>Set as<br>Default</html>"); 517 setSelectedCRSAsDefaultButton 518 .addActionListener(new java.awt.event.ActionListener() { 519 public void actionPerformed(java.awt.event.ActionEvent e) { 520 521 if(crsJList.getSelectedValue() != null){ 522 String selection = (String) crsJList.getSelectedValue(); 523 String code = selection.substring(selection.indexOf("[-") + 2, selection.indexOf("-]")); 524 525 try { 526 PluginOperations.defaultSourceCRS = CRS.decode(code, eastingFirstCheckBox.isSelected()); 527 PluginOperations.defaultSourceCRSDescription = selection; 528 529 ImageImportPlugin.pluginProps.setProperty("default_crs_eastingfirst", "" + eastingFirstCheckBox.isSelected()); 530 ImageImportPlugin.pluginProps.setProperty("default_crs_srid", code); 531 FileWriter fileWriter = new FileWriter(new File(ImageImportPlugin.PLUGINPROPERTIES_PATH)); 532 ImageImportPlugin.pluginProps.store(fileWriter, null); 533 fileWriter.close(); 534 535 defaultCRSLabel.setText(selection); 536 537 } catch (IOException e2) { 538 // TODO Auto-generated catch block 539 e2.printStackTrace(); 540 } catch (NoSuchAuthorityCodeException e3) { 541 // TODO Auto-generated catch block 542 e3.printStackTrace(); 543 } catch (FactoryException e4) { 544 // TODO Auto-generated catch block 545 e4.printStackTrace(); 546 } 547 }else{ 548 JOptionPane.showMessageDialog(getContentPane(), "Please make a selection from the list."); 549 } 550 551 552 } 553 }); 554 } 555 return setSelectedCRSAsDefaultButton; 556 } 557 558 /** 559 * This method initializes eastingFirstCheckBox 560 * 561 * @return javax.swing.JCheckBox 562 */ 563 private JCheckBox getEastingFirstCheckBox() { 564 if (eastingFirstCheckBox == null) { 565 eastingFirstCheckBox = new JCheckBox(); 566 eastingFirstCheckBox.setBounds(new Rectangle(345, 255, 21, 21)); 567 } 568 return eastingFirstCheckBox; 569 } 570 571 572 573 /** 574 * Listener setting text in the search field if selection has changed. 575 * 576 */ 577 577 class ListSelectionHandler implements ListSelectionListener { 578 578 public void valueChanged(ListSelectionEvent e) { 579 580 581 582 583 579 if(e.getValueIsAdjusting()) 580 { 581 searchField.setText(supportedCRS.get(e.getLastIndex())); 582 searchField.setEditable(true); 583 } 584 584 } 585 585 } -
applications/editors/josm/plugins/00_plugin_dir_template/src/org/openstreetmap/josm/plugins/ImportImagePlugin/LoadImageAction.java
r23139 r23192 26 26 */ 27 27 public class LoadImageAction extends JosmAction { 28 29 28 29 private Logger logger = Logger.getLogger(LoadImageAction.class); 30 30 31 32 33 34 35 36 31 /** 32 * Constructor... 33 */ 34 public LoadImageAction() { 35 super(tr("Import image"), null, tr("Import georeferenced image"), null, false); 36 } 37 37 38 38 public void actionPerformed(ActionEvent arg0) { 39 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 40 // Choose a file 41 JFileChooser fc = new JFileChooser(); 42 fc.setAcceptAllFileFilterUsed(false); 43 int result = fc.showOpenDialog(Main.parent); 44 45 ImageLayer layer = null; 46 if (result == JFileChooser.APPROVE_OPTION) { 47 logger.info("File choosed:" + fc.getSelectedFile()); 48 try { 49 layer = new ImageLayer(fc.getSelectedFile()); 50 } catch (LayerCreationCancledException e) { 51 // if user decides that layer should not be created just return. 52 return; 53 }catch (Exception e) { 54 logger.error("Error while creating image layer: \n" + e.getMessage()); 55 JOptionPane.showMessageDialog(null, marktr("Error while creating image layer: " + e.getCause())); 56 return; 57 58 } 59 60 // Add layer: 61 Main.main.addLayer(layer); 62 LatLon min = new LatLon(layer.getBbox().getMinX(), layer.getBbox().getMinY()); 63 LatLon max = new LatLon(layer.getBbox().getMaxX(), layer.getBbox().getMaxY()); 64 BoundingXYVisitor boundingXYVisitor = new BoundingXYVisitor(); 65 boundingXYVisitor.visit(new Bounds(min, max)); 66 Main.map.mapView.recalculateCenterScale(boundingXYVisitor); 67 Main.map.mapView.zoomTo(new Bounds(min, max)); 68 } 69 } 70 70 } -
applications/editors/josm/plugins/00_plugin_dir_template/src/org/openstreetmap/josm/plugins/ImportImagePlugin/PluginOperations.java
r23139 r23192 47 47 public class PluginOperations { 48 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 49 private static final Logger logger = Logger.getLogger(PluginOperations.class); 50 51 // contains descriptions of all available CRS 52 static Vector<String> crsDescriptions; 53 54 // the standard native CRS of user images 55 static CoordinateReferenceSystem defaultSourceCRS; 56 // description of 'defaultSourceCRS' 57 static String defaultSourceCRSDescription; 58 59 60 61 public static enum SUPPORTEDIMAGETYPES { 62 tiff, tif, jpg, jpeg, bmp, png 63 } 64 65 public static enum POSTFIXES_WORLDFILE { 66 wld, jgw, jpgw, pgw, pngw, tfw, tifw, bpw, bmpw, 67 }; 68 69 /** 70 * Reprojects a GridCoverage to a given CRS. 71 * 72 * @param coverage 73 * @param targetCrs 74 * @return destination 75 * @throws FactoryException 76 * @throws NoSuchAuthorityCodeException 77 */ 78 public static GridCoverage2D reprojectCoverage(GridCoverage2D coverage, 79 CoordinateReferenceSystem targetCrs) throws NoSuchAuthorityCodeException, FactoryException { 80 81 // TODO: add category for NO_DATA values in coverage (transparency in 82 // image) 83 84 GridCoverage2D destination = null; 85 86 DefaultProcessor processor = new DefaultProcessor(null); 87 ParameterValueGroup resampleParams = processor.getOperation("Resample") 88 .getParameters(); 89 90 // set parameters 91 resampleParams.parameter("Source").setValue(coverage); 92 resampleParams.parameter("CoordinateReferenceSystem").setValue( 93 targetCrs); 94 95 // resample coverage with given parameters 96 destination = (GridCoverage2D) processor.doOperation(resampleParams); 97 98 return destination; 99 } 100 101 /** 102 * Creates a org.geotools.coverage.grid.GridCoverage2D from a given file. 103 * 104 * @param file 105 * @return 106 * @throws IOException 107 * @throws Exception 108 */ 109 public static GridCoverage2D createGridFromFile(File file, CoordinateReferenceSystem refSys) throws IOException{ 110 111 GridCoverage2D coverage = null; 112 113 if (!file.exists()) throw new FileNotFoundException("File not found."); 114 115 String extension = null; 116 String fileNameWithoutExt = null; 117 int dotPos = file.getAbsolutePath().lastIndexOf("."); 118 extension = file.getAbsolutePath().substring(dotPos); 119 fileNameWithoutExt = file.getAbsolutePath().substring(0, dotPos); 120 121 /*------- switch for file type -----------*/ 122 if (extension.equalsIgnoreCase(".tif") 123 || extension.equalsIgnoreCase(".tiff")) 124 { 125 126 // try to read GeoTIFF: 127 try{ 128 coverage = readGeoTiff(file, refSys); 129 return coverage; 130 }catch (DataSourceException dse) { 131 if(!dse.getMessage().contains("Coordinate Reference System is not available")){ 132 dse.printStackTrace(); 133 } 134 } catch (FactoryException facte) { 135 logger.fatal("Error while reading from GeoTIFF:", facte); 136 throw new IOException(facte); 137 } 138 139 // file is no GeoTiff, searching for Worldfile and projection file: 140 String[] postfixes = {"wld", "tfw", "tifw"}; 141 // try to read Worldfile: 142 WorldFileReader tfwReader = null; 143 for (int i = 0; i < postfixes.length; i++) { 144 File prjFile = new File(fileNameWithoutExt + "." + postfixes[i]); 145 if(prjFile.exists()){ 146 tfwReader = new WorldFileReader(prjFile); 147 } 148 } 149 if(tfwReader == null){ 150 throw new IOException("No Worldfile found."); 151 } 152 153 if(refSys == null){ 154 // if no crs is delivered try to read projection file: 155 refSys = readPrjFile(file); 156 if(refSys == null) throw new IOException("No projection file found."); 157 } 158 159 BufferedImage img = ImageIO.read(file); 160 161 // create Envelope 162 double width = (double) (img.getWidth() * tfwReader.getXPixelSize()); 163 double height = (double) (img.getHeight() * (-tfwReader.getYPixelSize())); 164 double lowerLeft_x = (double) tfwReader.getXULC(); 165 double lowerLeft_y = (double) tfwReader.getYULC() - height; 166 Envelope2D bbox = new Envelope2D(null, new Rectangle2D.Double(lowerLeft_x, lowerLeft_y, width, height)); 167 168 coverage = createGridCoverage(img, bbox, refSys); 169 170 } 171 // 172 else if (extension.equalsIgnoreCase(".jpg") 173 || extension.equalsIgnoreCase(".jpeg")) 174 { 175 String[] postfixes = {"wld", "jgw", "jpgw"}; 176 // try to read Worldfile: 177 WorldFileReader tfwReader = null; 178 for (int i = 0; i < postfixes.length; i++) { 179 File prjFile = new File(fileNameWithoutExt + "." + postfixes[i]); 180 if(prjFile.exists()){ 181 tfwReader = new WorldFileReader(prjFile); 182 } 183 } 184 if(tfwReader == null) throw new IOException("No Worldfile found."); 185 186 if(refSys == null){ 187 // if no crs is delivered try to read projection file: 188 refSys = readPrjFile(file); 189 if(refSys == null) throw new IOException("No projection file found."); 190 } 191 192 BufferedImage img = ImageIO.read(file); 193 194 // create Envelope 195 double width = (double) (img.getWidth() * tfwReader.getXPixelSize()); 196 double height = (double) (img.getHeight() * (-tfwReader.getYPixelSize())); 197 double lowerLeft_x = (double) tfwReader.getXULC(); 198 double lowerLeft_y = (double) tfwReader.getYULC() - height; 199 Envelope2D bbox = new Envelope2D(null, new Rectangle2D.Double(lowerLeft_x, lowerLeft_y, width, height)); 200 201 coverage = createGridCoverage(img, bbox, refSys); 202 203 } 204 else if(extension.equalsIgnoreCase(".bmp")) 205 { 206 String[] postfixes = {"wld", "bmpw", "bpw"}; 207 // try to read Worldfile: 208 WorldFileReader tfwReader = null; 209 for (int i = 0; i < postfixes.length; i++) { 210 File prjFile = new File(fileNameWithoutExt + "." + postfixes[i]); 211 if(prjFile.exists()){ 212 tfwReader = new WorldFileReader(prjFile); 213 } 214 } 215 if(tfwReader == null) throw new IOException("No Worldfile found."); 216 217 if(refSys == null){ 218 // if no crs is delivered try to read projection file: 219 refSys = readPrjFile(file); 220 if(refSys == null) throw new IOException("No projection file found."); 221 } 222 223 BufferedImage img = ImageIO.read(file); 224 225 // create Envelope 226 double width = (double) (img.getWidth() * tfwReader.getXPixelSize()); 227 double height = (double) (img.getHeight() * (-tfwReader.getYPixelSize())); 228 double lowerLeft_x = (double) tfwReader.getXULC(); 229 double lowerLeft_y = (double) tfwReader.getYULC() - height; 230 Envelope2D bbox = new Envelope2D(null, new Rectangle2D.Double(lowerLeft_x, lowerLeft_y, width, height)); 231 232 coverage = createGridCoverage(img, bbox, refSys); 233 } 234 else if(extension.equalsIgnoreCase(".png")) 235 { 236 237 String[] postfixes = {"wld", "pgw", "pngw"}; 238 // try to read Worldfile: 239 WorldFileReader tfwReader = null; 240 for (int i = 0; i < postfixes.length; i++) { 241 File prjFile = new File(fileNameWithoutExt + "." + postfixes[i]); 242 if(prjFile.exists()){ 243 tfwReader = new WorldFileReader(prjFile); 244 } 245 } 246 if(tfwReader == null) throw new IOException("No Worldfile found."); 247 248 if(refSys == null){ 249 // if no crs is delivered try to read projection file: 250 refSys = readPrjFile(file); 251 if(refSys == null) throw new IOException("No projection file found."); 252 } 253 254 BufferedImage img = ImageIO.read(file); 255 256 // create Envelope 257 double width = (double) (img.getWidth() * tfwReader.getXPixelSize()); 258 double height = (double) (img.getHeight() * (-tfwReader.getYPixelSize())); 259 double lowerLeft_x = (double) tfwReader.getXULC(); 260 double lowerLeft_y = (double) tfwReader.getYULC() - height; 261 Envelope2D bbox = new Envelope2D(null, new Rectangle2D.Double(lowerLeft_x, lowerLeft_y, width, height)); 262 263 coverage = createGridCoverage(img, bbox, refSys); 264 } 265 else{ 266 throw new IOException("Image type not supported. Supported formats are: \n" + 267 Arrays.toString(SUPPORTEDIMAGETYPES.values())); 268 } 269 270 return coverage; 271 } 272 273 /** 274 * Searches for a projection file (.prj) with the same name of 'file' 275 * tries to parse it. 276 * 277 * 278 * @param file image file, not the real world file (will be searched) 279 * @return 280 * @throws IOException 281 */ 282 public static CoordinateReferenceSystem readPrjFile(File file) throws IOException 283 { 284 285 CoordinateReferenceSystem refSys = null; 286 287 String prjFilename = null; 288 int dotPos = file.getAbsolutePath().lastIndexOf("."); 289 prjFilename = file.getAbsolutePath().substring(0, dotPos) + ".prj"; 290 291 File prjFile = new File(prjFilename); 292 if(!prjFile.exists()) throw new IOException("No projection file found (.prj) for image '" + file.getName() + "'"); 293 logger.debug("Loading .prj file: " + prjFile.getAbsolutePath()); 294 295 StringBuilder sb = new StringBuilder(); 296 String content = null; 297 BufferedReader br = new BufferedReader(new FileReader(prjFile)); 298 while((content = br.readLine()) != null) 299 { 300 sb.append(content); 301 } 302 303 try { 304 refSys = CRS.parseWKT(sb.toString().trim()); 305 } catch (FactoryException e) { 306 throw new IOException("Unable to parse prj-file: '" + prjFile.getName() + "'"); 307 } 308 309 return refSys; 310 311 } 312 313 314 /** 315 * Method for external use. 316 * 317 * @param img 318 * @param bbox 319 * @param crs 320 * @return 321 */ 322 public static GridCoverage2D createGridCoverage(BufferedImage img, Envelope2D bbox, CoordinateReferenceSystem crs) 323 { 324 bbox.setCoordinateReferenceSystem(crs); 325 return new GridCoverageFactory().create("", img, bbox); 326 } 327 328 /** 329 * Method for reading a GeoTIFF file. 330 * 331 * @param file 332 * @param refSys if delivered, the coverage will be forced to use this crs 333 * @return 334 * @throws IOException 335 * @throws FactoryException 336 */ 337 public static GridCoverage2D readGeoTiff(File file, CoordinateReferenceSystem refSys) throws IOException, FactoryException 338 { 339 GridCoverage2D coverage = null; 340 Hints hints = new Hints(); 341 if(refSys != null) 342 { 343 hints.put(Hints.DEFAULT_COORDINATE_REFERENCE_SYSTEM, refSys); 344 345 } 346 // dont't use the EPSG-Factory because of wrong behaviour 347 hints.put(Hints.CRS_AUTHORITY_FACTORY, CRS.getAuthorityFactory(true)); 348 349 GeoTiffReader reader = new GeoTiffReader(file, hints); 350 351 coverage = (GridCoverage2D) reader.read(null); 352 353 return coverage; 354 } 355 356 357 /** 358 * Loads CRS data from an EPSG database and creates descrptions for each one. 359 * 360 * @param pluginProps 361 * @throws Exception 362 */ 363 public static void loadCRSData(Properties pluginProps) 364 { 365 String defaultcrsString = pluginProps.getProperty("default_crs_srid"); 366 367 crsDescriptions = new Vector<String>(); 368 Set<String> supportedCodes = CRS.getSupportedCodes("EPSG"); 369 CRSAuthorityFactory fac = CRS.getAuthorityFactory(false); 370 371 for (Iterator iterator = supportedCodes.iterator(); iterator.hasNext();) { 372 String string = (String) iterator.next(); 373 try { 374 InternationalString desc = fac.getDescriptionText("EPSG:" + string); 375 376 String description = desc.toString() + " [-EPSG:" + string + "-]"; 377 378 crsDescriptions.add(description); 379 380 if(defaultcrsString != null && defaultcrsString.equalsIgnoreCase("EPSG:" + string)){ 381 boolean isEastingFirst = Boolean.valueOf(pluginProps.getProperty("default_crs_eastingfirst")); 382 defaultSourceCRS = CRS.decode("EPSG:" + string, isEastingFirst); 383 defaultSourceCRSDescription = description; 384 } 385 } catch (NoSuchAuthorityCodeException e) { 386 if(!string.equalsIgnoreCase("WGS84(DD)")){ 387 logger.error("Error while loading EPSG data: " + e.getMessage()); 388 } 389 } catch (FactoryException e) { 390 logger.error("Error while loading EPSG data: " + e.getMessage()); 391 } 392 } 393 } 394 395 395 } -
applications/editors/josm/plugins/Create_grid_of_ways/src/CreateGridOfWaysPlugin/CreateGridOfWaysPlugin.java
r19428 r23192 8 8 public class CreateGridOfWaysPlugin extends Plugin { 9 9 public CreateGridOfWaysPlugin(PluginInformation info) { 10 10 super(info); 11 11 MainMenu.add(Main.main.menu.toolsMenu, new CreateGridOfWaysAction()); 12 12 } -
applications/editors/josm/plugins/ImportImagePlugin
-
Property svn:ignore
set to
build
-
Property svn:ignore
set to
-
applications/editors/josm/plugins/OpeningHoursEditor/src/org/openstreetmap/josm/plugins/ohe/OhePlugin.java
r22873 r23192 38 38 public class OhePlugin extends Plugin { 39 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 * 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 40 // Strings for choosing which key of an object with given tags should be 41 // edited 42 // the order is referencing the preference of the keys 43 // String[] -> {key, value, to-editing-key} key and value can contain regexp 44 private final String[][] TAG_EDIT_STRINGS = new String[][] { 45 { "opening_hours", ".*", "opening_hours" }, 46 { "collection_times", ".*", "collection_times" }, 47 { "collection_times:local", ".*", "collection_times:local" }, 48 { "lit", ".*", "lit" }, 49 { "amenity", "post_box", "collection_times" }, 50 { "amenity", ".*", "opening_hours" }, 51 { "shop", ".*", "opening_hours" }, { "highway", ".*", "lit" } }; 52 53 /** 54 * Will be invoked by JOSM to bootstrap the plugin 55 * 56 * @param info 57 * information about the plugin and its local installation 58 */ 59 public OhePlugin(PluginInformation info) { 60 super(info); 61 Main.main.menu.toolsMenu.add(new OheMenuAction()); 62 } 63 64 class OheMenuAction extends JosmAction { 65 public OheMenuAction() { 66 super( 67 tr("Edit opening hours"), 68 "opening_hours.png", 69 tr("Edit time-tag of selected element in a graphical interface"), 70 Shortcut.registerShortcut("tools:opening_hourseditor", tr( 71 "Tool: {0}", tr("Edit opening hours")), 72 KeyEvent.VK_T, Shortcut.GROUP_MENU), false); 73 } 74 75 @Override 76 protected void updateEnabledState() { 77 if (getCurrentDataSet() == null) { 78 setEnabled(false); 79 } else { 80 updateEnabledState(getCurrentDataSet().getSelected()); 81 } 82 } 83 84 @Override 85 protected void updateEnabledState( 86 Collection<? extends OsmPrimitive> selection) { 87 setEnabled(selection != null && !selection.isEmpty()); 88 } 89 90 public void actionPerformed(ActionEvent evt) { 91 // fetch active Layer 92 OsmDataLayer osmlayer = Main.main.getEditLayer(); 93 if (osmlayer != null) { 94 Collection<OsmPrimitive> selection = osmlayer.data 95 .getSelected(); 96 if (selection.size() == 1) { // one object selected 97 OsmPrimitive object = selection.iterator().next(); 98 String[] keyValuePair = editTimeTags(object.getKeys()); 99 if (keyValuePair != null) { 100 String key = keyValuePair[0].trim(); 101 String newkey = keyValuePair[1].trim(); 102 String value = keyValuePair[2].trim(); 103 104 if (value.equals("")) { 105 value = null; // delete the key 106 } 107 if (newkey.equals("")) { 108 newkey = key; 109 value = null; // delete the key instead 110 } 111 if (key.equals(newkey) 112 && tr("<different>").equals(value)) 113 return; 114 if (key.equals(newkey) || value == null) { 115 Main.main.undoRedo.add(new ChangePropertyCommand( 116 object, newkey, value)); 117 } else { 118 Collection<Command> commands = new Vector<Command>(); 119 commands.add(new ChangePropertyCommand(object, key, 120 null)); 121 commands.add(new ChangePropertyCommand(object, 122 newkey, value)); 123 Main.main.undoRedo.add(new SequenceCommand( 124 tr("Change properties of 1 object"), 125 commands)); 126 } 127 } 128 } else { // Not possible to edit 0, 2 or more objects 129 JOptionPane 130 .showMessageDialog( 131 Main.parent, 132 tr( 133 "You have {0} Elements selected. But you can edit only one element!", 134 selection.size()), 135 "openingHoursEditor Warning", 136 JOptionPane.ERROR_MESSAGE); 137 } 138 } 139 } 140 } 141 142 // opens up dialogs to change one of the key-value-pairs and returns the 143 // changed pair 144 private String[] editTimeTags(Map<String, String> keyValueMap) { 145 String selectedKey = ""; 146 147 if ((selectedKey = tagChooseDialog(keyValueMap)) == null) 148 return null; 149 150 final String value = (keyValueMap.containsKey(selectedKey)) ? keyValueMap 151 .get(selectedKey) 152 : ""; 153 OheDialogPanel panel = new OheDialogPanel(this, selectedKey, value); 154 155 final JOptionPane optionPane = new JOptionPane(panel, 156 JOptionPane.PLAIN_MESSAGE, JOptionPane.OK_CANCEL_OPTION); 157 final JDialog dlg = optionPane.createDialog(Main.parent, tr("Edit")); 158 159 dlg.setResizable(true); 160 dlg.setVisible(true); 161 162 Object answer = optionPane.getValue(); 163 if (!(answer == null || answer == JOptionPane.UNINITIALIZED_VALUE || (answer instanceof Integer && (Integer) answer != JOptionPane.OK_OPTION))) 164 return panel.getChangedKeyValuePair(); 165 166 return null; 167 } 168 169 // opens a dialog for choosing from a set of tags which can be edited 170 // the chosen one is returned 171 private String tagChooseDialog(Map<String, String> keyValueMap) { 172 String preSelectedKey = getPreSelectedKey(keyValueMap); 173 int preSelectedRow = -1; 174 175 String[][] rowData = new String[keyValueMap.size()][2]; 176 int cnt = 0; 177 for (Object key : keyValueMap.keySet().toArray()) { 178 rowData[cnt][0] = key.toString(); 179 rowData[cnt][1] = keyValueMap.get(key); 180 if (key.toString().equals(preSelectedKey)) 181 preSelectedRow = cnt; 182 cnt++; 183 } 184 185 final JTable table = new JTable(rowData, 186 new String[] { "key", "value" }) { 187 public boolean isCellEditable(int rowIndex, int colIndex) { 188 return false; // Disallow the editing of any cell 189 } 190 }; 191 table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); 192 JScrollPane sp = new JScrollPane( 193 JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, 194 JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); 195 sp.setViewportView(table); 196 197 final JTextField tf = new JTextField(); 198 199 ActionListener al = new ActionListener() { 200 @Override 201 public void actionPerformed(ActionEvent e) { 202 if (e.getActionCommand().equals("edit")) { 203 table.setEnabled(true); 204 tf.setEnabled(false); 205 } else if (e.getActionCommand().equals("new")) { 206 table.setEnabled(false); 207 tf.setEnabled(true); 208 } 209 } 210 }; 211 212 JRadioButton editButton = new JRadioButton("edit existing tag"); 213 editButton.setActionCommand("edit"); 214 editButton.addActionListener(al); 215 JRadioButton newButton = new JRadioButton("edit new tag"); 216 newButton.setActionCommand("new"); 217 newButton.addActionListener(al); 218 ButtonGroup group = new ButtonGroup(); 219 group.add(newButton); 220 group.add(editButton); 221 222 if (preSelectedRow != -1) { 223 table.setEnabled(true); 224 tf.setEnabled(false); 225 table.setRowSelectionInterval(preSelectedRow, preSelectedRow); 226 editButton.setSelected(true); 227 } else { 228 table.setEnabled(false); 229 tf.setEnabled(true); 230 tf.setText(preSelectedKey); 231 newButton.setSelected(true); 232 } 233 234 JPanel dlgPanel = new JPanel(new GridBagLayout()); 235 dlgPanel.add(editButton, GBC.std().anchor(GBC.CENTER)); 236 dlgPanel.add(sp, GBC.eol().fill(GBC.BOTH)); 237 dlgPanel.add(newButton, GBC.std().anchor(GBC.CENTER)); 238 dlgPanel.add(tf, GBC.eol().fill(GBC.HORIZONTAL)); 239 240 JOptionPane optionPane = new JOptionPane(dlgPanel, 241 JOptionPane.QUESTION_MESSAGE, JOptionPane.OK_CANCEL_OPTION); 242 JDialog dlg = optionPane.createDialog(Main.parent, tr("Choose key")); 243 244 dlg.pack(); 245 dlg.setResizable(true); 246 dlg.setVisible(true); 247 248 Object answer = optionPane.getValue(); 249 if (answer != null 250 && answer != JOptionPane.UNINITIALIZED_VALUE 251 && (answer instanceof Integer && (Integer) answer == JOptionPane.OK_OPTION)) 252 if (editButton.isSelected() && table.getSelectedRow() != -1) 253 return rowData[table.getSelectedRow()][0]; 254 else if (newButton.isSelected()) 255 return tf.getText(); 256 257 return null; 258 } 259 260 private String getPreSelectedKey(Map<String, String> keyValueMap) { 261 for (String[] pattern : TAG_EDIT_STRINGS) { 262 Pattern keyPattern = Pattern.compile(pattern[0]); 263 Pattern valuePattern = Pattern.compile(pattern[1]); 264 for (Object key : keyValueMap.keySet().toArray()) { 265 Matcher keyMatcher = keyPattern.matcher(key.toString()); 266 if (keyMatcher.matches()) { 267 Matcher valueMatcher = valuePattern.matcher(keyValueMap 268 .get(key)); 269 if (valueMatcher.matches()) { 270 return pattern[2]; 271 } 272 } 273 } 274 } 275 return ""; 276 } 277 277 } -
applications/editors/josm/plugins/OpeningHoursEditor/src/org/openstreetmap/josm/plugins/ohe/OpeningTimeUtils.java
r22751 r23192 7 7 8 8 public class OpeningTimeUtils { 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 9 // implements the subtraction of daytimes in spans of days when a day in 10 // the list occurs direct afterwards 11 public static ArrayList<int[]> convert(ArrayList<DateTime> dateTimes) { 12 ArrayList<int[]> ret = new ArrayList<int[]>(); // the list which is 13 // returned 14 for (int i = 0; i < dateTimes.size(); ++i) { // iterate over every entry 15 DateTime dateTime = dateTimes.get(i); 16 ArrayList<DateTime> newDateTimes = new ArrayList<DateTime>(); 17 18 // test if the given entry is a single dayspan 19 if (dateTime.daySpans.size() == 1 20 && dateTime.daySpans.get(0).isSpan()) { 21 ArrayList<DaySpan> partDaySpans = new ArrayList<DaySpan>(); 22 int start_day = dateTime.daySpans.get(0).startDay; 23 24 // look in every entry behind 25 while (i + 1 < dateTimes.size()) { 26 ArrayList<DaySpan> following = dateTimes.get(i + 1).daySpans; 27 if (following.size() == 1 28 && following.get(0).startDay > dateTime.daySpans 29 .get(0).startDay 30 && following.get(0).endDay < dateTime.daySpans 31 .get(0).endDay) { 32 partDaySpans.add(new DaySpan(start_day, following 33 .get(0).startDay - 1)); 34 start_day = following.get(0).endDay + 1; 35 newDateTimes.add(dateTimes.get(i + 1)); 36 i++; 37 } else 38 break; 39 } 40 41 partDaySpans.add(new DaySpan(start_day, dateTime.daySpans 42 .get(0).endDay)); 43 newDateTimes.add(new DateTime(partDaySpans, 44 dateTime.daytimeSpans)); 45 } 46 if (newDateTimes.isEmpty()) 47 newDateTimes.add(dateTime); 48 49 // create the int-array 50 for (int j = 0; j < newDateTimes.size(); ++j) { 51 DateTime dateTime2 = newDateTimes.get(j); 52 for (DaySpan dayspan : dateTime2.daySpans) { 53 for (DaytimeSpan timespan : dateTime2.daytimeSpans) { 54 if (!timespan.isOff()) 55 ret.add(new int[] { dayspan.startDay, 56 dayspan.endDay, timespan.startMinute, 57 timespan.endMinute }); 58 } 59 } 60 } 61 } 62 return ret; 63 } 64 65 public static class DaySpan { 66 public int startDay; 67 public int endDay; 68 69 public DaySpan(int startDay, int endDay) { 70 this.startDay = startDay; 71 this.endDay = endDay; 72 } 73 74 public boolean isSpan() { 75 return endDay > startDay; 76 } 77 78 public boolean isSingleDay() { 79 return startDay == endDay; 80 } 81 } 82 83 public static class DaytimeSpan { 84 public int startMinute; 85 public int endMinute; 86 87 public DaytimeSpan(int startMinute, int endMinute) { 88 this.startMinute = startMinute; 89 this.endMinute = endMinute; 90 } 91 92 public boolean isOff() { 93 return startMinute == -1; 94 } 95 96 public boolean isSpan() { 97 return endMinute > startMinute; 98 } 99 } 100 101 public static class DateTime { 102 public ArrayList<DaySpan> daySpans; 103 public ArrayList<DaytimeSpan> daytimeSpans; 104 105 public DateTime(ArrayList<DaySpan> daySpans, 106 ArrayList<DaytimeSpan> daytimeSpans) { 107 this.daySpans = daySpans; 108 this.daytimeSpans = daytimeSpans; 109 } 110 } 111 112 // returns a String (e.g "Mo-Sa 10:00-20:00; Tu off") representing the 113 // TimeRects 114 public static String makeStringFromRects(ArrayList<TimeRect> givenTimeRects) { 115 // create an array of booleans representing every minute on all the days 116 // in a week 117 boolean[][] minuteArray = new boolean[7][24 * 60 + 2]; 118 for (int day = 0; day < 7; ++day) 119 for (int minute = 0; minute < 24 * 60 + 2; ++minute) 120 minuteArray[day][minute] = false; 121 for (TimeRect timeRect : givenTimeRects) 122 for (int day = timeRect.getDayStart(); day <= timeRect.getDayEnd(); ++day) 123 for (int minute = timeRect.getMinuteStart(); minute <= timeRect 124 .getMinuteEnd(); ++minute) 125 minuteArray[day][minute] = true; 126 127 String ret = ""; 128 int[] days = new int[7]; // an array representing the status of the days 129 // 0 means nothing done with this day yet 130 // 8 means the day is off 131 // 0<x<8 means the day have the openinghours of day x 132 // -8<x<0 means nothing done with this day yet, but it intersects a 133 // range of days with same opening_hours 134 for (int i = 0; i < 7; ++i) { 135 String add = ""; 136 137 if (isArrayEmpty(minuteArray[i]) && days[i] == 0) { 138 days[i] = 8; 139 } else if (isArrayEmpty(minuteArray[i]) && days[i] < 0) { 140 add = OpeningTimeCompiler.WEEKDAYS[i] + " off"; 141 days[i] = -8; 142 } else if (days[i] <= 0) { 143 days[i] = i + 1; 144 int lastSameDay = i; 145 int sameDayCount = 1; 146 for (int j = i + 1; j < 7; ++j) { 147 if (arraysEqual(minuteArray[i], minuteArray[j])) { 148 days[j] = i + 1; 149 lastSameDay = j; 150 sameDayCount++; 151 } 152 } 153 if (sameDayCount == 1) { 154 // a single Day with this special opening_hours 155 add = OpeningTimeCompiler.WEEKDAYS[i] + " " 156 + makeStringFromMinuteArray(minuteArray[i]); 157 } else if (sameDayCount == 2) { 158 // exactly two Days with this special opening_hours 159 add = OpeningTimeCompiler.WEEKDAYS[i] + "," 160 + OpeningTimeCompiler.WEEKDAYS[lastSameDay] + " " 161 + makeStringFromMinuteArray(minuteArray[i]); 162 } else if (sameDayCount > 2) { 163 // more than two Days with this special opening_hours 164 add = OpeningTimeCompiler.WEEKDAYS[i] + "-" 165 + OpeningTimeCompiler.WEEKDAYS[lastSameDay] + " " 166 + makeStringFromMinuteArray(minuteArray[i]); 167 for (int j = i + 1; j < lastSameDay; ++j) { 168 if (days[j] == 0) 169 days[j] = -i - 1; 170 } 171 } 172 } 173 174 if (!add.isEmpty()) { 175 if (!ret.isEmpty()) 176 ret += "; "; 177 ret += add; 178 } 179 } 180 return ret; 181 } 182 183 // returns a String representing the openinghours on one special day (e.g. 184 // "10:00-20:00") 185 private static String makeStringFromMinuteArray(boolean[] minutes) { 186 String ret = ""; 187 for (int i = 0; i < minutes.length; ++i) { 188 if (minutes[i]) { 189 int start = i; 190 while (i < minutes.length && minutes[i]) 191 ++i; 192 String addString = timeString(start); 193 if (i - 1 == 24 * 60 + 1) // open end 194 addString += "+"; 195 else if (start != i - 1) // closing time 196 addString += "-" + timeString(i - 1); 197 if (!ret.isEmpty()) 198 ret += ","; 199 ret += addString; 200 } 201 } 202 return ret; 203 } 204 205 public static String timeString(int minutes) { 206 int h = minutes / 60; 207 int m = minutes % 60; 208 return (h < 10 ? "0" : "") + h + ":" + (m < 10 ? "0" : "") + m; 209 } 210 211 private static boolean isArrayEmpty(boolean[] bs) { 212 for (int i = 0; i < bs.length; i++) 213 if (bs[i]) 214 return false; 215 return true; 216 } 217 218 private static boolean arraysEqual(boolean[] bs, boolean[] bs2) { 219 boolean ret = true; 220 for (int i = 0; i < bs.length; i++) 221 ret &= bs[i] == bs2[i]; 222 return ret; 223 } 224 224 } -
applications/editors/josm/plugins/OpeningHoursEditor/src/org/openstreetmap/josm/plugins/ohe/gui/OheDialogPanel.java
r22751 r23192 26 26 public class OheDialogPanel extends JPanel { 27 27 28 28 private final JTextField keyField; 29 29 30 31 30 // The Component for showing the Time as a Text 31 private final JTextField valueField; 32 32 33 34 33 private final JButton twentyfourSevenButton; 34 private final JLabel actualPostionLabel; 35 35 36 37 36 // The important Panel for showing/editing the Time graphical 37 private final OheEditor editorPanel; 38 38 39 39 private final String oldkey; 40 40 41 42 43 41 public OheDialogPanel(OhePlugin plugin, String key, String value) { 42 oldkey = key; 43 keyField = new JTextField(key); 44 44 45 46 47 48 49 50 51 52 45 valueField = new JTextField(value); 46 valueField.addActionListener(new ActionListener() { 47 @Override 48 public void actionPerformed(ActionEvent evt) { 49 // on every action in the textfield the timeRects are reloaded 50 editorPanel.initTimeRects(); 51 } 52 }); 53 53 54 55 56 57 58 59 60 61 54 twentyfourSevenButton = new JButton(tr("apply {0}", "24/7")); 55 twentyfourSevenButton.addActionListener(new ActionListener() { 56 @Override 57 public void actionPerformed(ActionEvent arg0) { 58 valueField.setText("24/7"); 59 editorPanel.initTimeRects(); 60 } 61 }); 62 62 63 64 65 66 67 63 actualPostionLabel = new JLabel("Mo 00:00"); 64 JPanel toolsPanel = new JPanel(new GridBagLayout()); 65 toolsPanel.add(twentyfourSevenButton, GBC.std()); 66 toolsPanel.add(Box.createGlue(), GBC.std().fill(GBC.HORIZONTAL)); 67 toolsPanel.add(actualPostionLabel, GBC.eop()); 68 68 69 69 editorPanel = new OheEditor(this); 70 70 71 72 73 74 75 76 77 78 79 80 71 // adding all Components in a Gridbaglayout 72 setLayout(new GridBagLayout()); 73 add(new JLabel(tr("Key")), GBC.std()); 74 add(Box.createHorizontalStrut(10), GBC.std()); 75 add(keyField, GBC.eol().fill(GBC.HORIZONTAL)); 76 add(new JLabel(tr("Value")), GBC.std()); 77 add(Box.createHorizontalStrut(10), GBC.std()); 78 add(valueField, GBC.eop().fill(GBC.HORIZONTAL)); 79 add(toolsPanel, GBC.eol().fill(GBC.HORIZONTAL)); 80 add(editorPanel, GBC.eol().fill()); 81 81 82 83 84 82 valueField.requestFocus(); 83 setPreferredSize(new Dimension(480, 520)); 84 } 85 85 86 87 88 86 public String[] getChangedKeyValuePair() { 87 return new String[] { oldkey, keyField.getText(), valueField.getText() }; 88 } 89 89 90 91 92 93 94 95 96 97 98 99 100 90 // returns the compiled Time from the valueField 91 public ArrayList<int[]> getTime() throws Exception { 92 String value = valueField.getText(); 93 ArrayList<int[]> time = null; 94 if (value.length() > 0) { 95 OpeningTimeCompiler compiler = new OpeningTimeCompiler(value); 96 try { 97 time = OpeningTimeUtils.convert(compiler.startCompile()); 98 } catch (Throwable t) { 99 int tColumns[] = null; 100 String info = null; 101 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 102 if (t instanceof ParseException) { 103 ParseException parserExc = (ParseException) t; 104 tColumns = new int[] { 105 parserExc.currentToken.beginColumn - 1, 106 parserExc.currentToken.endColumn + 1 }; 107 } else if (t instanceof SyntaxException) { 108 SyntaxException syntaxError = (SyntaxException) t; 109 tColumns = new int[] { syntaxError.getStartColumn(), 110 syntaxError.getEndColumn() }; 111 info = syntaxError.getInfo(); 112 } else if (t instanceof TokenMgrError) { 113 TokenMgrError tokenMgrError = (TokenMgrError) t; 114 tColumns = new int[] { tokenMgrError.errorColumn - 1, 115 tokenMgrError.errorColumn + 1 }; 116 } else { 117 t.printStackTrace(); 118 } 119 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 120 // shows a Information Dialog, where the Error occurred 121 if (tColumns != null) { 122 int first = Math.max(0, tColumns[0]); 123 int last = Math.min(value.length(), tColumns[1]); 124 String begin = value.substring(0, first); 125 String middle = value.substring(first, last); 126 String end = value.substring(last); 127 String message = "<html>" 128 + tr("There is something wrong in the value near:") 129 + "<br>" + begin 130 + "<span style='background-color:red;'>" + middle 131 + "</span>" + end; 132 if (info != null) 133 message += "<br>" + tr("Info: {0}", tr(info)); 134 message += "<br>" 135 + tr("Correct the value manually and than press Enter."); 136 message += "</html>"; 137 JOptionPane.showMessageDialog(this, message, 138 tr("Error in timeformat"), 139 JOptionPane.INFORMATION_MESSAGE); 140 } 141 141 142 143 144 142 throw new Exception("Error in the TimeValue"); 143 } 144 } 145 145 146 147 146 return time; 147 } 148 148 149 150 151 152 153 149 // updates the valueField with the given timeRects 150 public void updateValueField(ArrayList<TimeRect> timeRects) { 151 if (valueField != null && timeRects != null) 152 valueField.setText(OpeningTimeUtils.makeStringFromRects(timeRects)); 153 } 154 154 155 156 157 155 public void setMousePositionText(String positionText) { 156 actualPostionLabel.setText(positionText); 157 } 158 158 } -
applications/editors/josm/plugins/OpeningHoursEditor/src/org/openstreetmap/josm/plugins/ohe/gui/OheEditor.java
r22751 r23192 20 20 21 21 public class OheEditor extends JPanel implements MouseListener, 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 22 MouseMotionListener { 23 final OheDialogPanel dialog; 24 25 final private JScrollPane scrollPane; 26 final JPanel contentPanel; 27 28 ArrayList<TimeRect> timeRects; 29 30 final private int dayAxisHeight = 20; 31 final private int timeAxisWidth = 45; 32 33 public OheEditor(OheDialogPanel oheDialogPanel) { 34 dialog = oheDialogPanel; 35 36 // the MainPanel for showing the TimeRects 37 contentPanel = new JPanel() { 38 @Override 39 public void setSize(Dimension d) { 40 super.setSize(d); 41 repositionTimeRects(); 42 } 43 44 @Override 45 public void paintComponent(Graphics g) { 46 if (OheEditor.this.isEnabled()) { 47 g.setColor(Color.WHITE); 48 g.fillRect(0, 0, getWidth(), getHeight()); 49 50 // horizontal Lines 51 for (int i = 1; i < 24; ++i) { 52 if (i % 3 == 0) 53 g.setColor(Color.BLACK); 54 else 55 g.setColor(Color.LIGHT_GRAY); 56 57 g.drawLine(0, getMinutePosition(i * 60), getWidth(), 58 getMinutePosition(i * 60)); 59 } 60 61 // vertical Lines 62 g.setColor(Color.BLACK); 63 for (int i = 1; i < 7; ++i) 64 g.drawLine(getDayPosition(i), 0, getDayPosition(i), 65 getHeight()); 66 67 // if a new Rect is dragged draw it 68 if (day0 >= 0) { 69 Graphics2D g2D = (Graphics2D) g; 70 71 int day2 = Math.min(day0, day1); 72 int day3 = Math.max(day0, day1); 73 int minute2 = Math.min(minute0, minute1); 74 int minute3 = Math.max(minute0, minute1); 75 Rectangle bounds = getPanelBoundsForTimeinterval(day2, 76 day3 + 1, minute2, minute3); 77 78 TimeRect.drawTimeRect(g2D, bounds, minute2 == minute3, false); 79 } 80 } else { 81 g.setColor(Color.LIGHT_GRAY); 82 g.fillRect(0, 0, getWidth(), getHeight()); 83 } 84 } 85 }; 86 contentPanel.addMouseListener(this); 87 contentPanel.addMouseMotionListener(this); 88 contentPanel.setLayout(null); 89 contentPanel.setPreferredSize(new Dimension(180, 384)); 90 91 initTimeRects(); 92 93 scrollPane = new JScrollPane(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, 94 JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); 95 scrollPane.setViewportView(contentPanel); 96 97 // the upper Panel for showing Weekdays 98 scrollPane.setColumnHeaderView(new JPanel() { 99 @Override 100 public Dimension getPreferredSize() { 101 return new Dimension(contentPanel.getWidth(), dayAxisHeight); 102 } 103 104 @Override 105 public void paintComponent(Graphics g) { 106 g.setColor(Color.WHITE); 107 g.fillRect(0, 0, getWidth(), getHeight()); 108 109 g.setColor(Color.BLACK); 110 for (int i = 0; i < 7; ++i) { 111 if (i > 0) 112 g.drawLine(getDayPosition(i) + 1, 0, 113 getDayPosition(i) + 1, getHeight()); 114 115 String text = OpeningTimeCompiler.WEEKDAYS[i]; 116 g.drawString(text, (int) (getDayPosition(i + 0.5) - g 117 .getFontMetrics().stringWidth(text) * 0.5), 118 (int) (dayAxisHeight * 0.5 + g.getFontMetrics() 119 .getHeight() * 0.35)); 120 } 121 } 122 }); 123 124 // the left Panel for showing the hours 125 scrollPane.setRowHeaderView(new JPanel() { 126 @Override 127 public Dimension getPreferredSize() { 128 return new Dimension(timeAxisWidth, contentPanel.getHeight()); 129 } 130 131 @Override 132 public void paintComponent(Graphics g) { 133 g.setColor(Color.WHITE); 134 g.fillRect(0, 0, getWidth(), getHeight()); 135 136 for (int i = 1; i < 24; ++i) { 137 if (i % 3 == 0) { 138 g.setColor(Color.BLACK); 139 String text = ((i < 10) ? "0" + i : i) + ":00"; 140 g 141 .drawString(text, timeAxisWidth - 10 142 - g.getFontMetrics().stringWidth(text), 143 getMinutePosition(i * 60) 144 + (int) (g.getFontMetrics() 145 .getHeight() * 0.35)); 146 } else 147 g.setColor(Color.LIGHT_GRAY); 148 149 g.drawLine(getWidth() - 4, getMinutePosition(i * 60) + 1, 150 getWidth(), getMinutePosition(i * 60) + 1); 151 } 152 } 153 }); 154 155 setLayout(new BorderLayout()); 156 add(scrollPane, BorderLayout.CENTER); 157 } 158 159 // update all the TimeRects with new Data 160 public void initTimeRects() { 161 contentPanel.removeAll(); 162 163 ArrayList<int[]> time; 164 try { 165 time = dialog.getTime(); 166 } catch (Exception exc) { 167 setEnabled(false); 168 return; 169 } 170 171 setEnabled(true); 172 timeRects = new ArrayList<TimeRect>(); 173 if (time != null) { 174 for (int[] timeRectValues : time) { 175 int day0 = timeRectValues[0]; 176 int day1 = timeRectValues[1]; 177 int minute0 = timeRectValues[2]; 178 int minute1 = timeRectValues[3]; 179 TimeRect timeRect = new TimeRect(OheEditor.this, day0, day1, 180 minute0, minute1); 181 timeRects.add(timeRect); 182 contentPanel.add(timeRect); 183 } 184 } 185 186 repositionTimeRects(); 187 repaint(); 188 } 189 190 protected void repositionTimeRects() { 191 if (timeRects != null) 192 for (TimeRect timeRect : timeRects) 193 timeRect.reposition(); 194 } 195 196 // returns the physical Borders of the TimeRect on the mainPanel 197 public Rectangle getPanelBoundsForTimeinterval(int dayStart, int dayEnd, 198 int minutesStart, int minutesEnd) { 199 int x = getDayPosition(dayStart); 200 int y = getMinutePosition(minutesStart); 201 int width = getDayPosition(dayEnd) - getDayPosition(dayStart); 202 int height = getMinutePosition(minutesEnd) 203 - getMinutePosition(minutesStart); 204 205 // work around openjdk bug 206 if (Main.isOpenjdk) { 207 x++; 208 y++; 209 } 210 211 if (minutesStart == minutesEnd) 212 return new Rectangle(x, y - 2 - TimeRect.verticalNonDrawedPixels, 213 width, height + 5 + 2 * TimeRect.verticalNonDrawedPixels); 214 215 return new Rectangle(x, y, width, height + 1); 216 } 217 218 public double getDayWidth() { 219 return (contentPanel.getWidth() - 1) / 7.0; 220 } 221 222 public int getDayPosition(double d) { 223 return (int) (d * getDayWidth()); 224 } 225 226 public double getMinuteHeight() { 227 return (contentPanel.getHeight() - 1) / (24.0 * 60); 228 } 229 230 public int getMinutePosition(int minute) { 231 return (int) (minute * getMinuteHeight()); 232 } 233 234 // removes the given timerect from the panel and from the arraylist 235 public void removeTimeRect(TimeRect timeRectToRemove) { 236 timeRects.remove(timeRectToRemove); 237 contentPanel.remove(timeRectToRemove); 238 dialog.updateValueField(timeRects); 239 repaint(); 240 } 241 242 // drawing a new Rect 243 private int day0 = -1; 244 private int minute0; 245 private int day1; 246 private int minute1; 247 private int xDragStart; 248 private int yDragStart; 249 250 @Override 251 public void mouseClicked(MouseEvent evt) { 252 } 253 254 @Override 255 public void mouseEntered(MouseEvent evt) { 256 } 257 258 @Override 259 public void mouseExited(MouseEvent evt) { 260 } 261 262 @Override 263 public void mousePressed(MouseEvent evt) { 264 day0 = (int) Math.floor(evt.getX() / getDayWidth()); 265 minute0 = (int) Math.floor(evt.getY() 266 / (getMinuteHeight() * TimeRect.minuteResterize)) 267 * TimeRect.minuteResterize; 268 day1 = day0; 269 minute1 = minute0; 270 xDragStart = evt.getX(); 271 yDragStart = evt.getY(); 272 } 273 274 @Override 275 public void mouseReleased(MouseEvent evt) { 276 // mouse must be moved 5px before creating a rect 277 if (xDragStart == -1 278 || Math.abs(evt.getX() - xDragStart) 279 + Math.abs(evt.getY() - yDragStart) > 5) { 280 int day2 = Math.min(day0, day1); 281 int day3 = Math.max(day0, day1); 282 int minute2 = Math.min(minute0, minute1); 283 int minute3 = Math.max(minute0, minute1); 284 285 TimeRect timeRect = new TimeRect(OheEditor.this, day2, day3, 286 minute2, minute3); 287 timeRects.add(timeRect); 288 contentPanel.add(timeRect); 289 timeRect.reposition(); 290 dialog.updateValueField(timeRects); 291 292 day0 = -1; 293 repaint(); 294 } 295 } 296 297 @Override 298 public void mouseDragged(MouseEvent evt) { 299 // mouse must be moved 5px before drawing a rect 300 if (xDragStart == -1 301 || Math.abs(evt.getX() - xDragStart) 302 + Math.abs(evt.getY() - yDragStart) > 5) { 303 xDragStart = -1; 304 day1 = (int) Math.floor(evt.getX() / getDayWidth()); 305 minute1 = (int) Math.floor(evt.getY() 306 / (getMinuteHeight() * TimeRect.minuteResterize)) 307 * TimeRect.minuteResterize; 308 repaint(); 309 } 310 } 311 312 @Override 313 public void mouseMoved(MouseEvent evt) { 314 mousePositionChanged(evt.getX(), evt.getY()); 315 } 316 317 public void mousePositionChanged(int x, int y) { 318 int actualDay = (int) Math.floor(x / getDayWidth()); 319 int minutes = (int) Math.floor(y 320 / (getMinuteHeight() * TimeRect.minuteResterize)) 321 * TimeRect.minuteResterize; 322 actualDay = Math.max(0, Math.min(6, actualDay)); 323 minutes = Math.max(0, Math.min(24 * 60, minutes)); 324 dialog.setMousePositionText(OpeningTimeCompiler.WEEKDAYS[actualDay] 325 + " " + OpeningTimeUtils.timeString(minutes)); 326 } 327 327 } -
applications/editors/josm/plugins/OpeningHoursEditor/src/org/openstreetmap/josm/plugins/ohe/gui/TimeRect.java
r22751 r23192 20 20 21 21 public class TimeRect extends JPanel implements MouseListener, 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 22 MouseMotionListener { 23 public static final int[] transformCursorTypes = new int[] { 24 Cursor.MOVE_CURSOR, Cursor.N_RESIZE_CURSOR, 25 Cursor.NE_RESIZE_CURSOR, Cursor.E_RESIZE_CURSOR, 26 Cursor.SE_RESIZE_CURSOR, Cursor.S_RESIZE_CURSOR, 27 Cursor.SW_RESIZE_CURSOR, Cursor.W_RESIZE_CURSOR, 28 Cursor.NW_RESIZE_CURSOR }; 29 30 public static final int minuteResterize = 15; 31 public static final int verticalNonDrawedPixels = 5; 32 33 public static final boolean[][] transformDirections = new boolean[][] { 34 { true, true, true, true }, // Drag 35 { true, false, false, false }, // N 36 { true, true, false, false }, // NE 37 { false, true, false, false }, // E 38 { false, true, true, false }, // SE 39 { false, false, true, false }, // S 40 { false, false, true, true }, // SW 41 { false, false, false, true }, // W 42 { true, false, false, true }, // NW 43 }; 44 45 public static final int roundCornerSize = 8; 46 private final int clickAreaSize = 16; 47 48 private OheEditor editor; 49 50 private int dayStart; 51 private int dayEnd; 52 private int minuteStart; 53 private int minuteEnd; 54 55 public TimeRect(OheEditor editor, int dayStart, int dayEnd, 56 int minutesStart, int minutesEnd) { 57 this.editor = editor; 58 59 this.dayStart = dayStart; 60 this.dayEnd = dayEnd; 61 this.minuteStart = minutesStart; 62 this.minuteEnd = minutesEnd; 63 64 transformType = -1; 65 66 setOpaque(true); 67 68 addMouseListener(this); 69 addMouseMotionListener(this); 70 } 71 72 public int getDayStart() { 73 return dayStart; 74 } 75 76 public int getDayEnd() { 77 return dayEnd; 78 } 79 80 public int getMinuteStart() { 81 return minuteStart; 82 } 83 84 public int getMinuteEnd() { 85 return minuteEnd; 86 } 87 88 public void reposition() { 89 setBounds(editor.getPanelBoundsForTimeinterval(dayStart, dayEnd + 1, 90 minuteStart, minuteEnd)); 91 editor.contentPanel.repaint(); 92 } 93 94 private boolean isZeroMinuteInterval() { 95 return minuteStart == minuteEnd; 96 } 97 98 private boolean isOpenEndInterval() { 99 return minuteEnd == 24 * 60 + 1; 100 } 101 102 private void updateTimeInterval(int newDayStart, int newDayEnd, 103 int newMinuteStart, int newMinuteEnd) { 104 dayStart = newDayStart; 105 dayEnd = newDayEnd; 106 minuteStart = newMinuteStart; 107 minuteEnd = newMinuteEnd; 108 109 editor.dialog.updateValueField(editor.timeRects); 110 reposition(); 111 } 112 113 @Override 114 public void paintComponent(Graphics g) { 115 drawTimeRect((Graphics2D) g, new Rectangle(0, 0, getWidth(), 116 getHeight()), isZeroMinuteInterval(), isOpenEndInterval()); 117 } 118 119 public static void drawTimeRect(Graphics2D g2D, Rectangle bounds, 120 boolean isZeroMinuteInterval, boolean isOpenEndInterval) { 121 122 Color innerColor = new Color(135, 135, 234); 123 if (isOpenEndInterval) 124 innerColor = new Color(234, 135, 135); 125 126 int tmpRoundCornerSize = TimeRect.roundCornerSize; 127 int verticalNonFilledBorder = 1; 128 if (isZeroMinuteInterval) { 129 innerColor = new Color(135, 234, 135); 130 tmpRoundCornerSize = 0; 131 verticalNonFilledBorder = verticalNonDrawedPixels; 132 } 133 134 g2D.setColor(innerColor); 135 g2D.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 136 .6f)); 137 g2D.fillRoundRect(bounds.x + 1, bounds.y + verticalNonFilledBorder, 138 bounds.width - 2, bounds.height - 1 - 2 139 * verticalNonFilledBorder, tmpRoundCornerSize, 140 tmpRoundCornerSize); 141 142 g2D.setColor(new Color(255, 0, 0)); 143 g2D.setComposite(AlphaComposite 144 .getInstance(AlphaComposite.SRC_OVER, 1f)); 145 g2D.drawRoundRect(bounds.x + 1, bounds.y + verticalNonFilledBorder, 146 bounds.width - 2, bounds.height - 1 - 2 147 * verticalNonFilledBorder, tmpRoundCornerSize, 148 tmpRoundCornerSize); 149 150 } 151 152 private int actualDayDrag; 153 private int actualMinuteDrag; 154 private int dragX; 155 private int dragY; 156 private int transformType; 157 158 // Calculate where the Component was clicked and returns the 159 // transformtype 160 private int getTransformType(MouseEvent evt) { 161 int tmpClickAreaWidth = Math.min(clickAreaSize, getWidth() / 3); 162 int tmpClickAreaHeight = Math.min(clickAreaSize, getHeight() / 3); 163 164 boolean isInNorthernTransformClickArea = evt.getY() < tmpClickAreaHeight; 165 boolean isInEasternTransformClickArea = evt.getX() > getWidth() 166 - tmpClickAreaWidth; 167 boolean isInSouthernTransformClickArea = evt.getY() > getHeight() 168 - tmpClickAreaHeight; 169 boolean isInWesternTransformClickArea = evt.getX() < tmpClickAreaWidth; 170 171 if (isZeroMinuteInterval()) { 172 isInNorthernTransformClickArea = false; 173 isInSouthernTransformClickArea = false; 174 } 175 176 int tType = 0; 177 for (int i = 1; i < transformDirections.length && tType == 0; i++) { 178 if (isInNorthernTransformClickArea == transformDirections[i][0] 179 && isInEasternTransformClickArea == transformDirections[i][1] 180 && isInSouthernTransformClickArea == transformDirections[i][2] 181 && isInWesternTransformClickArea == transformDirections[i][3]) 182 tType = i; 183 } 184 185 return tType; 186 } 187 188 public void showMenu(MouseEvent evt) { 189 JPopupMenu menu = new JPopupMenu(); 190 final JCheckBoxMenuItem cbMenuItem = new JCheckBoxMenuItem( 191 tr("open end"), isOpenEndInterval()); 192 menu.add(cbMenuItem); 193 cbMenuItem.addActionListener(new ActionListener() { 194 @Override 195 public void actionPerformed(ActionEvent e) { 196 if (cbMenuItem.isSelected()) 197 updateTimeInterval(dayStart, dayEnd, minuteStart, 198 24 * 60 + 1); 199 else 200 updateTimeInterval(dayStart, dayEnd, minuteStart, 24 * 60); 201 } 202 }); 203 menu.show(this, evt.getX(), evt.getY()); 204 } 205 206 @Override 207 public void mouseClicked(MouseEvent evt) { 208 } 209 210 @Override 211 public void mouseEntered(MouseEvent evt) { 212 } 213 214 @Override 215 public void mouseExited(MouseEvent evt) { 216 if (transformType < 0) 217 setCursor(new Cursor(Cursor.DEFAULT_CURSOR)); 218 } 219 220 @Override 221 public void mousePressed(MouseEvent evt) { 222 if (evt.isPopupTrigger()) { 223 showMenu(evt); 224 } else { 225 actualDayDrag = 0; 226 actualMinuteDrag = 0; 227 dragX = evt.getXOnScreen(); 228 dragY = evt.getYOnScreen(); 229 transformType = getTransformType(evt); 230 } 231 } 232 233 @Override 234 public void mouseReleased(MouseEvent evt) { 235 transformType = -1; 236 } 237 238 @Override 239 public void mouseDragged(MouseEvent evt) { 240 if (transformType >= 0) { 241 int xDiff = evt.getXOnScreen() - dragX; 242 int yDiff = evt.getYOnScreen() - dragY; 243 244 xDiff = (int) Math.round(xDiff / editor.getDayWidth()) 245 - actualDayDrag; 246 yDiff = (int) Math.round(yDiff 247 / (editor.getMinuteHeight() * minuteResterize)) 248 * minuteResterize - actualMinuteDrag; 249 250 if (xDiff != 0) { 251 int newDayStart = dayStart; 252 int newDayEnd = dayEnd; 253 254 if (transformDirections[transformType][3]) 255 newDayStart += xDiff; 256 if (transformDirections[transformType][1]) 257 newDayEnd += xDiff; 258 259 if (newDayStart > newDayEnd) { 260 editor.removeTimeRect(this); 261 transformType = -1; 262 setCursor(new Cursor(Cursor.DEFAULT_CURSOR)); 263 } else if (newDayStart >= 0 && newDayEnd <= 6) { 264 actualDayDrag += xDiff; 265 updateTimeInterval(newDayStart, newDayEnd, minuteStart, 266 minuteEnd); 267 } 268 } 269 if (yDiff != 0 && transformType >= 0) { 270 int newMinutesStart = minuteStart; 271 int newMinutesEnd = minuteEnd; 272 273 if (transformDirections[transformType][0]) 274 newMinutesStart = newMinutesStart + yDiff; 275 if (transformDirections[transformType][2] 276 && !isOpenEndInterval()) 277 newMinutesEnd = newMinutesEnd + yDiff; 278 279 if (newMinutesStart >= 0 280 && (newMinutesEnd <= 24 * 60 || isOpenEndInterval())) { 281 actualMinuteDrag += yDiff; 282 updateTimeInterval(dayStart, dayEnd, newMinutesStart, 283 newMinutesEnd); 284 } 285 } 286 } 287 editor.mousePositionChanged(evt.getX() + getX(), evt.getY() + getY()); 288 } 289 290 @Override 291 public void mouseMoved(MouseEvent evt) { 292 if (transformType < 0) 293 setCursor(new Cursor(transformCursorTypes[getTransformType(evt)])); 294 editor.mousePositionChanged(evt.getX() + getX(), evt.getY() + getY()); 295 } 296 296 } -
applications/editors/josm/plugins/OpeningHoursEditor/src/org/openstreetmap/josm/plugins/ohe/parser/OpeningTimeCompilerTokenManager.java
r22751 r23192 274 274 /** Token literal values. */ 275 275 public static final String[] jjstrLiteralImages = { 276 "", null, null, "\53", "\157\146\146", "\62\64\57\67", "\73\40", "\40", "\54", 276 "", null, null, "\53", "\157\146\146", "\62\64\57\67", "\73\40", "\40", "\54", 277 277 "\55", "\72", }; 278 278 … … 362 362 363 363 /** Get the next Token. */ 364 public Token getNextToken() 364 public Token getNextToken() 365 365 { 366 366 Token matchedToken; -
applications/editors/josm/plugins/OpeningHoursEditor/src/org/openstreetmap/josm/plugins/ohe/parser/SyntaxException.java
r22751 r23192 3 3 public class SyntaxException extends Exception { 4 4 5 6 7 5 private int startColumn; 6 private int endColumn; 7 private String info; 8 8 9 10 11 9 public int getStartColumn() { 10 return startColumn; 11 } 12 12 13 14 15 13 public int getEndColumn() { 14 return endColumn; 15 } 16 16 17 18 19 17 public String getInfo() { 18 return info; 19 } 20 20 21 22 23 24 25 21 public SyntaxException(String info, int startColumn, int endColumn) { 22 this.startColumn = startColumn; 23 this.endColumn = endColumn; 24 this.info = info; 25 } 26 26 } -
applications/editors/josm/plugins/OpeningHoursEditor/src/org/openstreetmap/josm/plugins/ohe/parser/TokenMgrError.java
r22751 r23192 6 6 public class TokenMgrError extends Error { 7 7 8 9 10 11 12 8 /** 9 * The version identifier for this Serializable class. Increment only if the 10 * <i>serialized</i> form of the class changes. 11 */ 12 private static final long serialVersionUID = 1L; 13 13 14 15 16 14 /* 15 * Ordinals for various reasons why an Error of this type can be thrown. 16 */ 17 17 18 19 20 21 18 /** 19 * Lexical error occurred. 20 */ 21 static final int LEXICAL_ERROR = 0; 22 22 23 24 25 26 27 23 /** 24 * An attempt was made to create a second instance of a static token 25 * manager. 26 */ 27 static final int STATIC_LEXER_ERROR = 1; 28 28 29 30 31 32 29 /** 30 * Tried to change to an invalid lexical state. 31 */ 32 static final int INVALID_LEXICAL_STATE = 2; 33 33 34 35 36 37 34 /** 35 * Detected (and bailed out of) an infinite loop in the token manager. 36 */ 37 static final int LOOP_DETECTED = 3; 38 38 39 40 41 42 43 39 /** 40 * Indicates the reason why the exception is thrown. It will have one of the 41 * above 4 values. 42 */ 43 int errorCode; 44 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 45 /** 46 * Replaces unprintable characters by their escaped (or unicode escaped) 47 * equivalents in the given string 48 */ 49 protected static final String addEscapes(String str) { 50 StringBuffer retval = new StringBuffer(); 51 char ch; 52 for (int i = 0; i < str.length(); i++) { 53 switch (str.charAt(i)) { 54 case 0: 55 continue; 56 case '\b': 57 retval.append("\\b"); 58 continue; 59 case '\t': 60 retval.append("\\t"); 61 continue; 62 case '\n': 63 retval.append("\\n"); 64 continue; 65 case '\f': 66 retval.append("\\f"); 67 continue; 68 case '\r': 69 retval.append("\\r"); 70 continue; 71 case '\"': 72 retval.append("\\\""); 73 continue; 74 case '\'': 75 retval.append("\\\'"); 76 continue; 77 case '\\': 78 retval.append("\\\\"); 79 continue; 80 default: 81 if ((ch = str.charAt(i)) < 0x20 || ch > 0x7e) { 82 String s = "0000" + Integer.toString(ch, 16); 83 retval.append("\\u" 84 + s.substring(s.length() - 4, s.length())); 85 } else { 86 retval.append(ch); 87 } 88 continue; 89 } 90 } 91 return retval.toString(); 92 } 93 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 94 /** 95 * Returns a detailed message for the Error when it is thrown by the token 96 * manager to indicate a lexical error. Parameters : EOFSeen : indicates if 97 * EOF caused the lexical error curLexState : lexical state in which this 98 * error occurred errorLine : line number when the error occurred 99 * errorColumn : column number when the error occurred errorAfter : prefix 100 * that was seen before this error occurred curchar : the offending 101 * character Note: You can customize the lexical error message by modifying 102 * this method. 103 */ 104 protected static String LexicalError(boolean EOFSeen, int lexState, 105 int errorLine, int errorColumn, String errorAfter, char curChar) { 106 return ("Lexical error at line " 107 + errorLine 108 + ", column " 109 + errorColumn 110 + ". Encountered: " 111 + (EOFSeen ? "<EOF> " : ("\"" 112 + addEscapes(String.valueOf(curChar)) + "\"") 113 + " (" + (int) curChar + "), ") + "after : \"" 114 + addEscapes(errorAfter) + "\""); 115 } 116 116 117 118 119 120 121 122 123 124 125 126 127 128 129 117 /** 118 * You can also modify the body of this method to customize your error 119 * messages. For example, cases like LOOP_DETECTED and INVALID_LEXICAL_STATE 120 * are not of end-users concern, so you can return something like : 121 * 122 * "Internal Error : Please file a bug report .... " 123 * 124 * from this method for such cases in the release version of your parser. 125 */ 126 @Override 127 public String getMessage() { 128 return super.getMessage(); 129 } 130 130 131 132 133 131 /* 132 * Constructors of various flavors follow. 133 */ 134 134 135 136 137 135 /** No arg constructor. */ 136 public TokenMgrError() { 137 } 138 138 139 140 141 142 143 139 /** Constructor with message and reason. */ 140 public TokenMgrError(String message, int reason) { 141 super(message); 142 errorCode = reason; 143 } 144 144 145 146 147 148 149 150 151 145 public boolean EOFSeen; 146 public int lexState; 147 public int errorLine; 148 public int errorColumn; 149 public String errorAfter; 150 public char curChar; 151 public int reason; 152 152 153 154 155 156 157 158 159 160 161 162 163 153 /** Full Constructor. */ 154 public TokenMgrError(boolean EOFSeen, int lexState, int errorLine, 155 int errorColumn, String errorAfter, char curChar, int reason) { 156 this.EOFSeen = EOFSeen; 157 this.lexState = lexState; 158 this.errorLine = errorLine; 159 this.errorColumn = errorColumn; 160 this.errorAfter = errorAfter; 161 this.curChar = curChar; 162 this.reason = reason; 163 } 164 164 } 165 165 /* -
applications/editors/josm/plugins/alignways/src/org/openstreetmap/josm/plugins/alignways/AlignWaysMode.java
r23165 r23192 28 28 public class AlignWaysMode extends MapMode /* implements MapViewPaintable */{ 29 29 30 31 32 33 34 35 36 37 30 private static final long serialVersionUID = -1090955708412011141L; 31 private final AlignWaysState noneSelected; 32 private final AlignWaysState referenceSelected; 33 private final AlignWaysState aligneeSelected; 34 private final AlignWaysState bothSelected; 35 private AlignWaysState currentState; 36 private AlignWaysSegmentMgr awSegs; 37 boolean tipShown; 38 38 39 40 41 42 43 44 45 46 47 48 49 39 public AlignWaysMode(MapFrame mapFrame, String name, String desc) { 40 super(tr(name), "alignways.png", tr(desc), 41 Shortcut.registerShortcut("mapmode:alignways", 42 tr("Mode: {0}", tr("Align Ways")), 43 KeyEvent.VK_N, Shortcut.GROUP_EDIT, Shortcut.SHIFT_DEFAULT), 44 mapFrame, Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); 45 noneSelected = new AlignWaysSelNoneState(); 46 referenceSelected = new AlignWaysSelRefState(); 47 aligneeSelected = new AlignWaysSelAlgnState(); 48 bothSelected = new AlignWaysSelBothState(); 49 tipShown = false; 50 50 51 51 } 52 52 53 54 55 56 57 58 59 60 61 62 63 53 @Override 54 public void enterMode() { 55 super.enterMode(); 56 boolean showTips = Boolean.parseBoolean(Main.pref.get("alignways.showtips", "true")); 57 if ((showTips) && (!tipShown)) { 58 showTips(); 59 } 60 awSegs = AlignWaysSegmentMgr.getInstance(Main.map.mapView); 61 Main.map.mapView.addMouseListener(this); 62 setCurrentState(noneSelected); 63 } 64 64 65 66 67 68 69 70 71 65 @Override 66 public void exitMode() { 67 super.exitMode(); 68 setCurrentState(noneSelected); 69 Main.map.mapView.removeMouseListener(this); 70 AlignWaysPlugin.getAwAction().setEnabled(false); 71 } 72 72 73 74 73 @Override 74 public void mouseClicked(MouseEvent e) { 75 75 76 77 76 boolean ctrlPressed = (e.getModifiers() & ActionEvent.CTRL_MASK) != 0; 77 boolean altPressed = (e.getModifiers() & (ActionEvent.ALT_MASK | InputEvent.ALT_GRAPH_MASK)) != 0; 78 78 79 79 if (e.getButton() == MouseEvent.BUTTON1) { 80 80 81 82 81 if (altPressed) { 82 currentState.altLClick(this); 83 83 84 85 84 } else { 85 Point clickedPoint = new Point(e.getX(), e.getY()); 86 86 87 88 87 if (!ctrlPressed) { 88 // Alignee could change 89 89 90 91 92 90 if (awSegs.algnUpdate(clickedPoint)) { 91 currentState.leftClick(this); 92 } 93 93 94 95 96 97 98 99 100 101 94 } else { 95 // Reference could change 96 if (awSegs.refUpdate(clickedPoint)) { 97 currentState.ctrlLClick(this); 98 } 99 } 100 } 101 } 102 102 103 104 105 106 107 108 109 110 103 // Activate the Align Ways button if we have enough selections 104 if (currentState == bothSelected) { 105 AlignWaysPlugin.getAwAction().setEnabled(true); 106 } else { 107 AlignWaysPlugin.getAwAction().setEnabled(false); 108 } 109 Main.map.mapView.repaint(); 110 } 111 111 112 113 114 115 116 117 118 112 /** 113 * @param currentState 114 * One of the AlignWays states 115 */ 116 public void setCurrentState(AlignWaysState currentState) { 117 this.currentState = currentState; 118 currentState.setHelpText(); 119 119 120 121 122 123 124 125 126 127 128 129 120 if (currentState == noneSelected) { 121 awSegs.cleanupWays(); 122 // FIX: getCurrentDataSet may return null when the editable layer had 123 // already been removed by JOSM. This happens e.g. when the user closes 124 // JOSM while AlignWays mode is still active. 125 if (getCurrentDataSet() != null) { 126 getCurrentDataSet().clearSelection(); 127 } 128 } 129 } 130 130 131 132 133 134 135 136 131 /** 132 * @return the noneSelected 133 */ 134 public AlignWaysState getNoneSelected() { 135 return noneSelected; 136 } 137 137 138 139 140 141 142 143 138 /** 139 * @return the referenceSelected 140 */ 141 public AlignWaysState getReferenceSelected() { 142 return referenceSelected; 143 } 144 144 145 146 147 148 149 150 145 /** 146 * @return the aligneeSelected 147 */ 148 public AlignWaysState getAligneeSelected() { 149 return aligneeSelected; 150 } 151 151 152 153 154 155 156 157 152 /** 153 * @return the bothSelected 154 */ 155 public AlignWaysState getBothSelected() { 156 return bothSelected; 157 } 158 158 159 160 161 162 163 164 159 /** 160 * @return the current state 161 */ 162 public AlignWaysState getCurrentState() { 163 return currentState; 164 } 165 165 166 166 private void showTips() { 167 167 168 169 170 171 172 173 174 168 AlignWaysTipsPanel atd = new AlignWaysTipsPanel(); 169 Object[] okButton = {tr("I''m ready!")}; 170 JOptionPane tipPane = new JOptionPane(atd, JOptionPane.PLAIN_MESSAGE, JOptionPane.DEFAULT_OPTION, null, okButton, okButton[0]); 171 // JDialog tipDialog = tipPane.createDialog(null, tr("AlignWays Tips")); 172 // Take Main.map as frame as it's better to inherit its icon than the default Java cup 173 JDialog tipDialog = tipPane.createDialog(Main.parent, tr("AlignWays Tips")); 174 // ((Frame)tipDialog.getOwner()).setIconImage(new ImageIcon(getClass().getResource("/images/blank.png")).getImage()); 175 175 176 177 178 176 tipDialog.setResizable(true); 177 tipDialog.setVisible(true); 178 tipShown = true; 179 179 180 180 tipDialog.dispose(); 181 181 182 182 Main.pref.put("alignways.showtips", !atd.isChkBoxSelected()); 183 183 184 184 } 185 185 } -
applications/editors/josm/plugins/colorscheme/src/at/dallermassl/josm/plugin/colorscheme/ColorSchemePlugin.java
r19426 r23192 20 20 */ 21 21 public ColorSchemePlugin(PluginInformation info) { 22 22 super(info); 23 23 } 24 24 -
applications/editors/josm/plugins/download_along/src/org/openstreetmap/josm/plugin/download_along/DownloadAlong.java
r22427 r23192 48 48 private static class DownloadAlongAction extends JosmAction { 49 49 /** 50 * 51 50 * 51 */ 52 52 private static final long serialVersionUID = 1L; 53 53 … … 193 193 * however we can only download rectangles, so the following is an attempt 194 194 * at finding a number of rectangles to download. 195 * 195 * 196 196 * The idea is simply: Start out with the full bounding box. If it is too 197 197 * large, then split it in half and repeat recursively for each half until -
applications/editors/josm/plugins/nearclick/src/nearclick/NearClickPlugin.java
r19458 r23192 13 13 public class NearClickPlugin implements AWTEventListener { 14 14 15 16 17 18 19 15 private int mouseDownX = -1; 16 private int mouseDownY = -1; 17 private long mouseDownTime = -1; 18 private int radiussquared = 49; 19 private int delay = 250; 20 20 21 22 23 24 25 26 27 28 29 30 31 32 33 21 public NearClickPlugin(PluginInformation info) { 22 Toolkit.getDefaultToolkit().addAWTEventListener(this, 23 AWTEvent.MOUSE_EVENT_MASK | AWTEvent.MOUSE_MOTION_EVENT_MASK); 24 try { 25 int radius = Integer.parseInt(Main.pref 26 .get("nearclick.radius", "7")); 27 radiussquared = radius * radius; 28 delay = Integer.parseInt(Main.pref.get("nearclick.delay", "250")); 29 } catch (NumberFormatException ex) { 30 delay = 250; 31 radiussquared = 7 * 7; 32 } 33 } 34 34 35 36 37 38 39 40 41 35 public void eventDispatched(AWTEvent event) { 36 if (event instanceof MouseEvent) { 37 MouseEvent e = (MouseEvent) event; 38 if (e.getButton() != MouseEvent.BUTTON1) 39 return; 40 int xdiff = e.getPoint().x - mouseDownX; 41 int ydiff = e.getPoint().y - mouseDownY; 42 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 43 if (e.getID() == MouseEvent.MOUSE_RELEASED) { 44 if (e.getWhen() - mouseDownTime < delay 45 && (e.getPoint().x != mouseDownX || e.getPoint().y != mouseDownY) 46 && xdiff * xdiff + ydiff * ydiff < radiussquared) { 47 try { 48 Robot r = new Robot(GraphicsEnvironment 49 .getLocalGraphicsEnvironment() 50 .getDefaultScreenDevice()); 51 r.mousePress(MouseEvent.BUTTON1_MASK); 52 r.mouseRelease(MouseEvent.BUTTON1_MASK); 53 } catch (AWTException e1) { 54 } 55 } 56 } 57 if (e.getID() == MouseEvent.MOUSE_PRESSED) { 58 mouseDownX = e.getPoint().x; 59 mouseDownY = e.getPoint().y; 60 mouseDownTime = e.getWhen(); 61 } 62 } 63 } 64 64 } -
applications/editors/josm/plugins/osmarender/src/org/openstreetmap/josm/plugins/osmarender/OsmarenderPlugin.java
r21423 r23192 80 80 for (Node n : ((Way) p).getNodes()) { 81 81 if (n.getCoor().isWithin(b)) 82 82 parents.add(n); 83 83 } 84 84 } … … 87 87 // Write ways 88 88 for (OsmPrimitive p: parents) { 89 90 91 89 if (p instanceof Way) { 90 w.visit((Way)p); 91 } 92 92 } 93 93 94 94 // Write relations (should be parent relation also written?) 95 95 for (OsmPrimitive p: parents) { 96 97 98 96 if (p instanceof Relation) { 97 w.visit((Relation)p); 98 } 99 99 } 100 100 … … 120 120 121 121 public OsmarenderPlugin(PluginInformation info) throws IOException { 122 122 super(info); 123 123 osmarenderMenu = MainMenu.add(Main.main.menu.viewMenu, new Action()); 124 124 osmarenderMenu.setVisible(false); -
applications/editors/josm/plugins/photo_geotagging/src/org/openstreetmap/josm/plugins/photo_geotagging/GeotaggingAction.java
r22551 r23192 50 50 51 51 public GeotaggingAction() { 52 52 super(tr("Write coordinates to image header"), ImageProvider.get("geotagging")); 53 53 } 54 54 55 55 public void actionPerformed(ActionEvent arg0) { 56 56 57 57 GeoImageLayer layer = getLayer(); 58 58 59 59 final List<ImageEntry> images = new ArrayList<ImageEntry>(); … … 316 316 317 317 private GeoImageLayer getLayer() { 318 318 return (GeoImageLayer)LayerListDialog.getInstance().getModel().getSelectedLayers().get(0); 319 319 } 320 320 … … 330 330 } 331 331 332 332 public Component createMenuComponent() { 333 333 JMenuItem geotaggingItem = new JMenuItem(this); 334 334 geotaggingItem.setEnabled(enabled(getLayer())); 335 335 return geotaggingItem; 336 337 338 339 340 336 } 337 338 public boolean supportLayers(List<Layer> layers) { 339 return layers.size() == 1 && layers.get(0) instanceof GeoImageLayer; 340 } 341 341 } -
applications/editors/josm/plugins/public_transport/src/public_transport/GTFSAddCommand.java
r22148 r23192 16 16 private GTFSStopTableModel gtfsStopTM = null; 17 17 private String type = null; 18 18 19 19 public GTFSAddCommand(GTFSImporterAction controller) 20 20 { … … 23 23 workingLines = new Vector< Integer >(); 24 24 typesForUndo = new Vector< String >(); 25 25 26 26 // use either selected lines or all lines if no line is selected 27 27 int[] selectedLines = controller.getDialog().getGTFSStopTable().getSelectedRows(); … … 30 30 { 31 31 for (int i = 0; i < selectedLines.length; ++i) 32 32 consideredLines.add(selectedLines[i]); 33 33 } 34 34 else 35 35 { 36 36 for (int i = 0; i < gtfsStopTM.getRowCount(); ++i) 37 37 consideredLines.add(new Integer(i)); 38 38 } 39 39 40 40 // keep only lines where a node can be added 41 41 for (int i = 0; i < consideredLines.size(); ++i) 42 42 { 43 43 if (gtfsStopTM.nodes.elementAt(consideredLines.elementAt(i)) == null) 44 44 workingLines.add(consideredLines.elementAt(i)); 45 45 } 46 46 } 47 47 48 48 public boolean executeCommand() 49 49 { … … 61 61 return true; 62 62 } 63 63 64 64 public void undoCommand() 65 65 { … … 71 71 gtfsStopTM.setValueAt(typesForUndo.elementAt(i), j, 2); 72 72 if (node == null) 73 73 continue; 74 74 Main.main.getCurrentDataSet().removePrimitive(node); 75 75 node.setDeleted(true); 76 76 } 77 77 } 78 78 79 79 public void fillModifiedData 80 80 (Collection< OsmPrimitive > modified, Collection< OsmPrimitive > deleted, … … 82 82 { 83 83 } 84 84 85 85 @Override public JLabel getDescription() 86 86 { -
applications/editors/josm/plugins/public_transport/src/public_transport/GTFSCatchCommand.java
r22148 r23192 18 18 private GTFSStopTableModel gtfsStopTM = null; 19 19 private String type = null; 20 20 21 21 public GTFSCatchCommand(GTFSImporterAction controller) 22 22 { 23 23 gtfsStopTM = controller.getGTFSStopTableModel(); 24 24 workingLines = new Vector< Integer >(); 25 25 26 26 // use either selected lines or all lines if no line is selected 27 27 int[] selectedLines = controller.getDialog().getGTFSStopTable().getSelectedRows(); … … 30 30 workingLines.add(selectedLines[0]); 31 31 } 32 32 33 33 public boolean executeCommand() 34 34 { … … 43 43 Node n = iter.next(); 44 44 if ((n != null) && (n.equals(gtfsStopTM.nodes.elementAt(j)))) 45 45 continue; 46 46 if (dest != null) 47 47 return false; 48 48 dest = n; 49 49 } … … 51 51 return false; 52 52 undoMapNode = new Node(dest); 53 53 54 54 Node node = gtfsStopTM.nodes.elementAt(j); 55 55 undoTableNode = node; … … 59 59 node.setDeleted(true); 60 60 } 61 61 62 62 dest.setCoor(gtfsStopTM.coors.elementAt(j)); 63 63 dest.put("highway", "bus_stop"); … … 69 69 type = (String)gtfsStopTM.getValueAt(j, 2); 70 70 gtfsStopTM.setValueAt("fed", j, 2); 71 71 72 72 return true; 73 73 } 74 74 75 75 public void undoCommand() 76 76 { … … 78 78 return; 79 79 int j = workingLines.elementAt(0); 80 80 81 81 Node node = gtfsStopTM.nodes.elementAt(j); 82 82 if (node != null) … … 85 85 node.setDeleted(true); 86 86 } 87 87 88 88 if (undoMapNode != null) 89 89 { … … 99 99 gtfsStopTM.setValueAt(type, j, 2); 100 100 } 101 101 102 102 public void fillModifiedData 103 103 (Collection< OsmPrimitive > modified, Collection< OsmPrimitive > deleted, … … 105 105 { 106 106 } 107 107 108 108 @Override public JLabel getDescription() 109 109 { -
applications/editors/josm/plugins/public_transport/src/public_transport/GTFSDeleteCommand.java
r22148 r23192 16 16 private Vector< String > typesForUndo = null; 17 17 private GTFSStopTableModel gtfsStopTM = null; 18 18 19 19 public GTFSDeleteCommand(GTFSImporterAction controller) 20 20 { … … 23 23 nodesForUndo = new Vector< Node >(); 24 24 typesForUndo = new Vector< String >(); 25 25 26 26 // use either selected lines or all lines if no line is selected 27 27 int[] selectedLines = controller.getDialog().getGTFSStopTable().getSelectedRows(); … … 30 30 { 31 31 for (int i = 0; i < selectedLines.length; ++i) 32 32 consideredLines.add(selectedLines[i]); 33 33 } 34 34 else 35 35 { 36 36 for (int i = 0; i < gtfsStopTM.getRowCount(); ++i) 37 37 consideredLines.add(new Integer(i)); 38 38 } 39 39 40 40 // keep only lines where a node can be added 41 41 for (int i = 0; i < consideredLines.size(); ++i) 42 42 { 43 43 if (gtfsStopTM.nodes.elementAt(consideredLines.elementAt(i)) != null) 44 44 workingLines.add(consideredLines.elementAt(i)); 45 45 } 46 46 } 47 47 48 48 public boolean executeCommand() 49 49 { … … 57 57 typesForUndo.add((String)gtfsStopTM.getValueAt(j, 2)); 58 58 if (node == null) 59 59 continue; 60 60 gtfsStopTM.nodes.set(j, null); 61 61 gtfsStopTM.setValueAt("skipped", j, 2); … … 65 65 return true; 66 66 } 67 67 68 68 public void undoCommand() 69 69 { … … 75 75 gtfsStopTM.setValueAt(typesForUndo.elementAt(i), j, 2); 76 76 if (node == null) 77 77 continue; 78 78 node.setDeleted(false); 79 79 Main.main.getCurrentDataSet().addPrimitive(node); 80 80 } 81 81 } 82 82 83 83 public void fillModifiedData 84 84 (Collection< OsmPrimitive > modified, Collection< OsmPrimitive > deleted, … … 86 86 { 87 87 } 88 88 89 89 @Override public JLabel getDescription() 90 90 { -
applications/editors/josm/plugins/public_transport/src/public_transport/GTFSImporterAction.java
r23094 r23192 63 63 64 64 public class GTFSImporterAction extends JosmAction 65 { 65 { 66 66 private static GTFSImporterDialog dialog = null; 67 67 private static DefaultListModel tracksListModel = null; … … 70 70 private static GTFSStopTableModel gtfsStopTM = null; 71 71 public boolean inEvent = false; 72 72 73 73 public GTFSImporterAction() 74 74 { 75 75 super(tr("Create Stops from GTFS ..."), null, 76 76 tr("Create Stops from a GTFS file"), null, true); 77 77 } 78 78 … … 81 81 return gtfsStopTM; 82 82 } 83 83 84 84 public GTFSImporterDialog getDialog() 85 85 { … … 93 93 return tracksListModel; 94 94 } 95 95 96 96 public TrackReference getCurrentTrack() 97 97 { … … 102 102 { 103 103 DataSet mainDataSet = Main.main.getCurrentDataSet(); 104 104 105 105 if (dialog == null) 106 106 dialog = new GTFSImporterDialog(this); 107 107 108 108 dialog.setVisible(true); 109 109 … … 113 113 if (curDir.equals("")) 114 114 { 115 115 curDir = "."; 116 116 } 117 117 JFileChooser fc = new JFileChooser(new File(curDir)); 118 fc.setDialogTitle("Select GTFS file (stops.txt)"); 118 fc.setDialogTitle("Select GTFS file (stops.txt)"); 119 119 fc.setMultiSelectionEnabled(false); 120 120 121 121 int answer = fc.showOpenDialog(Main.parent); 122 122 if (answer != JFileChooser.APPROVE_OPTION) 123 124 123 return; 124 125 125 if (!fc.getCurrentDirectory().getAbsolutePath().equals(curDir)) 126 127 126 Main.pref.put("lastDirectory", fc.getCurrentDirectory().getAbsolutePath()); 127 128 128 importData(fc.getSelectedFile()); 129 129 130 130 refreshData(); 131 131 } … … 133 133 { 134 134 if ((!inEvent) && (dialog.gpsTimeStartValid()) && (currentTrack != null)) 135 135 Main.main.undoRedo.add(new TrackStoplistRelocateCommand(this)); 136 136 } 137 137 else if ("stopImporter.settingsStopwatchStart".equals(event.getActionCommand())) 138 138 { 139 139 if ((!inEvent) && (dialog.stopwatchStartValid()) && (currentTrack != null)) 140 140 Main.main.undoRedo.add(new TrackStoplistRelocateCommand(this)); 141 141 } 142 142 else if ("stopImporter.settingsTimeWindow".equals(event.getActionCommand())) 143 143 { 144 144 if (currentTrack != null) 145 145 currentTrack.timeWindow = dialog.getTimeWindow(); 146 146 } 147 147 else if ("stopImporter.settingsThreshold".equals(event.getActionCommand())) 148 148 { 149 149 if (currentTrack != null) 150 150 currentTrack.threshold = dialog.getThreshold(); 151 151 } 152 152 else if ("stopImporter.settingsSuggestStops".equals(event.getActionCommand())) … … 181 181 private void importData(final File file) 182 182 { 183 try 183 try 184 184 { 185 185 FileReader is = new FileReader(file); 186 186 final BufferedReader r = new BufferedReader(is); 187 187 188 188 if (data == null) 189 189 data = new Vector< String >(); 190 190 else 191 192 191 data.clear(); 192 193 193 while (r.ready()) 194 195 } 196 catch (FileNotFoundException e) 194 data.add(r.readLine()); 195 } 196 catch (FileNotFoundException e) 197 197 { 198 198 e.printStackTrace(); … … 211 211 { 212 212 Vector< Node > existingStops = new Vector< Node >(); 213 213 214 214 if (Main.main.getCurrentDataSet() == null) 215 215 { 216 216 JOptionPane.showMessageDialog(null, "There exists no dataset." 217 217 + " Try to download data from the server or open an OSM file.", 218 218 "No data found", JOptionPane.ERROR_MESSAGE); 219 219 220 220 System.out.println("Public Transport: StopInserter: No data found"); 221 221 … … 224 224 else 225 225 { 226 227 228 229 230 231 232 233 234 } 235 226 Iterator< Node > iter = 227 Main.main.getCurrentDataSet().getNodes().iterator(); 228 while (iter.hasNext()) 229 { 230 Node node = iter.next(); 231 if ("bus_stop".equals(node.get("highway"))) 232 existingStops.add(node); 233 } 234 } 235 236 236 Iterator< String > iter = data.iterator(); 237 237 if (iter.hasNext()) 238 238 gtfsStopTM = new GTFSStopTableModel(this, iter.next()); 239 239 else 240 240 { 241 242 243 244 241 JOptionPane.showMessageDialog 242 (null, "The GTFS file was empty.", "No data found", 243 JOptionPane.ERROR_MESSAGE); 244 245 245 System.out.println("Public Transport: GTFSImporter: No data found"); 246 246 247 247 return; 248 248 } 249 249 250 250 while (iter.hasNext()) 251 251 { 252 253 252 String s = iter.next(); 253 gtfsStopTM.addRow(s, existingStops); 254 254 } 255 255 dialog.setGTFSStopTableModel(gtfsStopTM); … … 260 260 (null, "The GTFS file was empty.", "No data found", 261 261 JOptionPane.ERROR_MESSAGE); 262 262 263 263 System.out.println("Public Transport: GTFSImporter: No data found"); 264 264 } 265 265 } 266 266 267 267 // public void tracksSelectionChanged(int selectedPos) 268 268 // { … … 271 271 // currentTrack = ((TrackReference)tracksListModel.elementAt(selectedPos)); 272 272 // dialog.setTrackValid(true); 273 // 273 // 274 274 // //Prepare Settings 275 275 // dialog.setSettings 276 // 277 // 278 // 276 // (currentTrack.gpsSyncTime, currentTrack.stopwatchStart, 277 // currentTrack.timeWindow, currentTrack.threshold); 278 // 279 279 // //Prepare Stoplist 280 280 // dialog.setStoplistTableModel … … 297 297 { 298 298 JOptionPane.showMessageDialog(null, "There exists no dataset." 299 299 + " Try to download data from the server or open an OSM file.", 300 300 "No data found", JOptionPane.ERROR_MESSAGE); 301 301 302 302 System.out.println("Public Transport: StopInserter: No data found"); 303 303 304 304 return null; 305 305 } … … 317 317 { 318 318 for (int i = 0; i < selectedLines.length; ++i) 319 319 consideredLines.add(selectedLines[i]); 320 320 } 321 321 else 322 322 { 323 323 for (int i = 0; i < table.getRowCount(); ++i) 324 324 consideredLines.add(new Integer(i)); 325 325 } 326 326 return consideredLines; … … 332 332 if (Main.main.getCurrentDataSet() == null) 333 333 return; 334 334 335 335 table.clearSelection(); 336 336 337 337 for (int i = 0; i < table.getRowCount(); ++i) 338 338 { 339 339 if ((nodes.elementAt(i) != null) && 340 341 342 } 343 } 344 340 (Main.main.getCurrentDataSet().isSelected(nodes.elementAt(i)))) 341 table.addRowSelectionInterval(i, i); 342 } 343 } 344 345 345 /* shows the nodes that correspond to the marked lines in the table. 346 346 If no lines are marked in the table, show all nodes from the vector */ … … 353 353 int j = consideredLines.elementAt(i); 354 354 if (nodes.elementAt(j) != null) 355 355 nodes.elementAt(j).visit(box); 356 356 } 357 357 if (box.getBounds() == null) … … 360 360 Main.map.mapView.recalculateCenterScale(box); 361 361 } 362 362 363 363 /* marks the nodes that correspond to the marked lines in the table. 364 364 If no lines are marked in the table, mark all nodes from the vector */ … … 372 372 int j = consideredLines.elementAt(i); 373 373 if (nodes.elementAt(j) != null) 374 375 } 376 } 377 374 Main.main.getCurrentDataSet().addSelected(nodes.elementAt(j)); 375 } 376 } 377 378 378 public static String timeOf(double t) 379 379 { 380 380 t -= Math.floor(t/24/60/60)*24*60*60; 381 381 382 382 int hour = (int)Math.floor(t/60/60); 383 383 t -= Math.floor(t/60/60)*60*60; … … 385 385 t -= Math.floor(t/60)*60; 386 386 double second = t; 387 387 388 388 Format format = new DecimalFormat("00"); 389 389 Format formatS = new DecimalFormat("00.###"); 390 390 return (format.format(hour) + ":" + format.format(minute) + ":" 391 392 } 393 391 + formatS.format(second)); 392 } 393 394 394 public Action getFocusAddAction() 395 395 { 396 396 return new FocusAddAction(); 397 397 } 398 398 399 399 private class FocusAddAction extends AbstractAction 400 400 { … … 405 405 } 406 406 }; 407 407 408 408 /* public Action getFocusWaypointShelterAction(String shelter) 409 409 { … … 417 417 public void actionPerformed(ActionEvent e) 418 418 { 419 420 421 422 423 424 425 /* 426 419 JTable table = dialog.getWaypointsTable(); 420 int row = table.getEditingRow(); 421 if (row < 0) 422 return; 423 table.clearSelection(); 424 table.addRowSelectionInterval(row, row); 425 /* Main.main.undoRedo.add 426 (new WaypointsDisableCommand(GTFSImporterAction.this));* 427 427 } 428 428 }; … … 433 433 return new FocusTrackStoplistNameAction(); 434 434 } 435 435 436 436 public Action getFocusTrackStoplistShelterAction(String shelter) 437 437 { … … 445 445 public void actionPerformed(ActionEvent e) 446 446 { 447 448 449 450 451 452 453 /* 454 447 JTable table = dialog.getStoplistTable(); 448 int row = table.getEditingRow(); 449 if (row < 0) 450 return; 451 table.clearSelection(); 452 table.addRowSelectionInterval(row, row); 453 /* Main.main.undoRedo.add 454 (new TrackStoplistDeleteCommand(GTFSImporterAction.this));* 455 455 } 456 456 }; … … 466 466 int row = table.getEditingRow(); 467 467 if (row < 0) 468 468 row = 0; 469 469 waypointTM.inEvent = true; 470 470 if (table.getCellEditor() != null) 471 471 { 472 473 472 if (!table.getCellEditor().stopCellEditing()) 473 table.getCellEditor().cancelCellEditing(); 474 474 } 475 475 table.editCellAt(row, 1); 476 476 table.getCellEditor().getTableCellEditorComponent 477 477 (table, "", true, row, 1); 478 478 waypointTM.inEvent = false; 479 479 } 480 480 }; 481 481 482 482 private class FocusWaypointShelterAction extends AbstractAction 483 483 { 484 484 private String defaultShelter = null; 485 485 486 486 public FocusWaypointShelterAction(String defaultShelter) 487 487 { 488 488 this.defaultShelter = defaultShelter; 489 489 } 490 490 491 491 public void actionPerformed(ActionEvent e) 492 492 { … … 496 496 int row = table.getEditingRow(); 497 497 if (row < 0) 498 498 row = 0; 499 499 waypointTM.inEvent = true; 500 500 if (table.getCellEditor() != null) 501 501 { 502 503 502 if (!table.getCellEditor().stopCellEditing()) 503 table.getCellEditor().cancelCellEditing(); 504 504 } 505 505 table.editCellAt(row, 2); … … 509 509 } 510 510 }; 511 511 512 512 private class FocusTrackStoplistNameAction extends AbstractAction 513 513 { … … 519 519 int row = table.getEditingRow(); 520 520 if (row < 0) 521 521 row = 0; 522 522 currentTrack.inEvent = true; 523 523 if (table.getCellEditor() != null) 524 524 { 525 526 525 if (!table.getCellEditor().stopCellEditing()) 526 table.getCellEditor().cancelCellEditing(); 527 527 } 528 528 table.editCellAt(row, 1); … … 532 532 } 533 533 }; 534 534 535 535 private class FocusTrackStoplistShelterAction extends AbstractAction 536 536 { 537 537 private String defaultShelter = null; 538 538 539 539 public FocusTrackStoplistShelterAction(String defaultShelter) 540 540 { 541 541 this.defaultShelter = defaultShelter; 542 542 } 543 543 544 544 public void actionPerformed(ActionEvent e) 545 545 { … … 549 549 int row = table.getEditingRow(); 550 550 if (row < 0) 551 551 row = 0; 552 552 currentTrack.inEvent = true; 553 553 if (table.getCellEditor() != null) 554 554 { 555 556 555 if (!table.getCellEditor().stopCellEditing()) 556 table.getCellEditor().cancelCellEditing(); 557 557 } 558 558 table.editCellAt(row, 2); -
applications/editors/josm/plugins/public_transport/src/public_transport/GTFSImporterDialog.java
r22148 r23192 63 63 64 64 public class GTFSImporterDialog 65 { 65 { 66 66 private JDialog jDialog = null; 67 67 private JTabbedPane tabbedPane = null; … … 74 74 private JTable stoplistTable = null; 75 75 private JTable gtfsStopTable = null; 76 76 77 77 public GTFSImporterDialog(GTFSImporterAction controller) 78 78 { … … 87 87 tabbedPane.setEnabledAt(1, true); 88 88 jDialog.add(tabbedPane); 89 89 90 90 //Settings Tab 91 91 JPanel contentPane = tabSettings; … … 93 93 GridBagConstraints layoutCons = new GridBagConstraints(); 94 94 contentPane.setLayout(gridbag); 95 95 96 96 JLabel label = new JLabel("Type of stops to add"); 97 97 98 98 layoutCons.gridx = 0; 99 99 layoutCons.gridy = 0; … … 104 104 gridbag.setConstraints(label, layoutCons); 105 105 contentPane.add(label); 106 106 107 107 cbStoptype = new JComboBox(); 108 108 cbStoptype.setEditable(false); … … 114 114 cbStoptype.setActionCommand("gtfsImporter.settingsStoptype"); 115 115 cbStoptype.addActionListener(controller); 116 116 117 117 layoutCons.gridx = 0; 118 118 layoutCons.gridy = 1; … … 123 123 gridbag.setConstraints(cbStoptype, layoutCons); 124 124 contentPane.add(cbStoptype); 125 125 126 126 label = new JLabel("Time on your GPS device"); 127 127 128 128 layoutCons.gridx = 0; 129 129 layoutCons.gridy = 2; … … 134 134 gridbag.setConstraints(label, layoutCons); 135 135 contentPane.add(label); 136 136 137 137 tfGPSTimeStart = new JTextField("00:00:00", 15); 138 138 tfGPSTimeStart.setActionCommand("gtfsImporter.settingsGPSTimeStart"); 139 139 tfGPSTimeStart.addActionListener(controller); 140 140 141 141 layoutCons.gridx = 0; 142 142 layoutCons.gridy = 3; … … 147 147 gridbag.setConstraints(tfGPSTimeStart, layoutCons); 148 148 contentPane.add(tfGPSTimeStart); 149 149 150 150 label = new JLabel("HH:MM:SS.sss"); 151 151 152 152 layoutCons.gridx = 1; 153 153 layoutCons.gridy = 3; … … 158 158 gridbag.setConstraints(label, layoutCons); 159 159 contentPane.add(label); 160 160 161 161 label = new JLabel("Time on your stopwatch"); 162 162 163 163 layoutCons.gridx = 0; 164 164 layoutCons.gridy = 4; … … 169 169 gridbag.setConstraints(label, layoutCons); 170 170 contentPane.add(label); 171 171 172 172 tfStopwatchStart = new JTextField("00:00:00", 15); 173 173 tfStopwatchStart.setActionCommand("gtfsImporter.settingsStopwatchStart"); 174 174 tfStopwatchStart.addActionListener(controller); 175 175 176 176 layoutCons.gridx = 0; 177 177 layoutCons.gridy = 5; … … 182 182 gridbag.setConstraints(tfStopwatchStart, layoutCons); 183 183 contentPane.add(tfStopwatchStart); 184 184 185 185 label = new JLabel("HH:MM:SS.sss"); 186 186 187 187 layoutCons.gridx = 1; 188 188 layoutCons.gridy = 5; … … 193 193 gridbag.setConstraints(label, layoutCons); 194 194 contentPane.add(label); 195 195 196 196 label = new JLabel("Time window"); 197 197 198 198 layoutCons.gridx = 0; 199 199 layoutCons.gridy = 6; … … 204 204 gridbag.setConstraints(label, layoutCons); 205 205 contentPane.add(label); 206 206 207 207 tfTimeWindow = new JTextField("15", 4); 208 208 tfTimeWindow.setActionCommand("gtfsImporter.settingsTimeWindow"); 209 209 tfTimeWindow.addActionListener(controller); 210 210 211 211 layoutCons.gridx = 0; 212 212 layoutCons.gridy = 7; … … 217 217 gridbag.setConstraints(tfTimeWindow, layoutCons); 218 218 contentPane.add(tfTimeWindow); 219 219 220 220 label = new JLabel("seconds"); 221 221 222 222 layoutCons.gridx = 1; 223 223 layoutCons.gridy = 7; … … 228 228 gridbag.setConstraints(label, layoutCons); 229 229 contentPane.add(label); 230 230 231 231 label = new JLabel("Move Threshold"); 232 232 233 233 layoutCons.gridx = 0; 234 234 layoutCons.gridy = 8; … … 239 239 gridbag.setConstraints(label, layoutCons); 240 240 contentPane.add(label); 241 241 242 242 tfThreshold = new JTextField("20", 4); 243 243 tfThreshold.setActionCommand("gtfsImporter.settingsThreshold"); 244 244 tfThreshold.addActionListener(controller); 245 245 246 246 layoutCons.gridx = 0; 247 247 layoutCons.gridy = 9; … … 252 252 gridbag.setConstraints(tfThreshold, layoutCons); 253 253 contentPane.add(tfThreshold); 254 254 255 255 label = new JLabel("meters"); 256 256 257 257 layoutCons.gridx = 1; 258 258 layoutCons.gridy = 9; … … 263 263 gridbag.setConstraints(label, layoutCons); 264 264 contentPane.add(label); 265 265 266 266 JButton bSuggestStops = new JButton("Suggest Stops"); 267 267 bSuggestStops.setActionCommand("gtfsImporter.settingsSuggestStops"); 268 268 bSuggestStops.addActionListener(controller); 269 269 270 270 layoutCons.gridx = 0; 271 271 layoutCons.gridy = 10; … … 276 276 gridbag.setConstraints(bSuggestStops, layoutCons); 277 277 contentPane.add(bSuggestStops); 278 278 279 279 //Waypoints Tab 280 280 contentPane = tabWaypoints; … … 285 285 (KeyStroke.getKeyStroke("alt N"), "gtfsImporter.gtfsStopsFocusAdd"); 286 286 contentPane.getActionMap().put 287 287 ("gtfsImporter.gtfsStopsFocusAdd", controller.getFocusAddAction()); 288 288 /* contentPane.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put 289 289 (KeyStroke.getKeyStroke("alt S"), "gtfsImporter.focusShelterYes"); 290 290 contentPane.getActionMap().put 291 292 291 ("gtfsImporter.focusShelterYes", 292 controller.getFocusWaypointShelterAction("yes")); 293 293 contentPane.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put 294 294 (KeyStroke.getKeyStroke("alt T"), "gtfsImporter.focusShelterNo"); 295 295 contentPane.getActionMap().put 296 297 296 ("gtfsImporter.focusShelterNo", 297 controller.getFocusWaypointShelterAction("no")); 298 298 contentPane.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put 299 299 (KeyStroke.getKeyStroke("alt U"), "gtfsImporter.focusShelterImplicit"); 300 300 contentPane.getActionMap().put 301 302 301 ("gtfsImporter.focusShelterImplicit", 302 controller.getFocusWaypointShelterAction("implicit")); 303 303 contentPane.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put 304 304 (KeyStroke.getKeyStroke("alt D"), "gtfsImporter.gtfsStopsDelete"); 305 305 contentPane.getActionMap().put 306 307 308 306 ("gtfsImporter.gtfsStopsDelete", 307 controller.getFocusWaypointDeleteAction());*/ 308 309 309 gtfsStopTable = new JTable(); 310 310 JScrollPane tableSP = new JScrollPane(gtfsStopTable); 311 311 312 312 layoutCons.gridx = 0; 313 313 layoutCons.gridy = 0; … … 318 318 gridbag.setConstraints(tableSP, layoutCons); 319 319 contentPane.add(tableSP); 320 320 321 321 JButton bFind = new JButton("Find"); 322 322 bFind.setActionCommand("gtfsImporter.gtfsStopsFind"); 323 323 bFind.addActionListener(controller); 324 324 325 325 layoutCons.gridx = 0; 326 326 layoutCons.gridy = 1; … … 331 331 gridbag.setConstraints(bFind, layoutCons); 332 332 contentPane.add(bFind); 333 333 334 334 JButton bShow = new JButton("Show"); 335 335 bShow.setActionCommand("gtfsImporter.gtfsStopsShow"); 336 336 bShow.addActionListener(controller); 337 337 338 338 layoutCons.gridx = 0; 339 339 layoutCons.gridy = 2; … … 344 344 gridbag.setConstraints(bShow, layoutCons); 345 345 contentPane.add(bShow); 346 346 347 347 JButton bMark = new JButton("Mark"); 348 348 bMark.setActionCommand("gtfsImporter.gtfsStopsMark"); 349 349 bMark.addActionListener(controller); 350 350 351 351 layoutCons.gridx = 1; 352 352 layoutCons.gridy = 1; … … 358 358 gridbag.setConstraints(bMark, layoutCons); 359 359 contentPane.add(bMark); 360 360 361 361 JButton bCatch = new JButton("Catch"); 362 362 bCatch.setActionCommand("gtfsImporter.gtfsStopsCatch"); 363 363 bCatch.addActionListener(controller); 364 364 365 365 layoutCons.gridx = 2; 366 366 layoutCons.gridy = 1; … … 372 372 gridbag.setConstraints(bCatch, layoutCons); 373 373 contentPane.add(bCatch); 374 374 375 375 JButton bJoin = new JButton("Join"); 376 376 bJoin.setActionCommand("gtfsImporter.gtfsStopsJoin"); 377 377 bJoin.addActionListener(controller); 378 378 379 379 layoutCons.gridx = 2; 380 380 layoutCons.gridy = 2; … … 386 386 gridbag.setConstraints(bJoin, layoutCons); 387 387 contentPane.add(bJoin); 388 388 389 389 JButton bAdd = new JButton("Enable"); 390 390 bAdd.setActionCommand("gtfsImporter.gtfsStopsAdd"); 391 391 bAdd.addActionListener(controller); 392 392 393 393 layoutCons.gridx = 3; 394 394 layoutCons.gridy = 1; … … 400 400 gridbag.setConstraints(bAdd, layoutCons); 401 401 contentPane.add(bAdd); 402 402 403 403 JButton bDelete = new JButton("Disable"); 404 404 bDelete.setActionCommand("gtfsImporter.gtfsStopsDelete"); 405 405 bDelete.addActionListener(controller); 406 406 407 407 layoutCons.gridx = 3; 408 408 layoutCons.gridy = 2; … … 413 413 gridbag.setConstraints(bDelete, layoutCons); 414 414 contentPane.add(bDelete); 415 415 416 416 jDialog.pack(); 417 417 jDialog.setLocationRelativeTo(frame); 418 418 } 419 419 420 420 public void setTrackValid(boolean valid) 421 421 { 422 422 tabbedPane.setEnabledAt(2, valid); 423 423 } 424 424 425 425 public void setVisible(boolean visible) 426 426 { 427 427 jDialog.setVisible(visible); 428 428 } 429 429 430 430 public void setSettings 431 431 (String gpsSyncTime, String stopwatchStart, … … 437 437 tfThreshold.setText(Double.toString(threshold)); 438 438 } 439 439 440 440 public String getStoptype() 441 441 { 442 442 return (String)cbStoptype.getSelectedItem(); 443 443 } 444 444 445 445 public boolean gpsTimeStartValid() 446 446 { … … 452 452 { 453 453 JOptionPane.showMessageDialog 454 455 454 (null, "Can't parse a time from this string.", "Invalid value", 455 JOptionPane.ERROR_MESSAGE); 456 456 return false; 457 457 } 458 458 } 459 459 460 460 public String getGpsTimeStart() 461 461 { 462 462 return tfGPSTimeStart.getText(); 463 463 } 464 464 465 465 public void setGpsTimeStart(String s) 466 466 { 467 467 tfGPSTimeStart.setText(s); 468 468 } 469 469 470 470 public boolean stopwatchStartValid() 471 471 { … … 477 477 { 478 478 JOptionPane.showMessageDialog 479 480 479 (null, "Can't parse a time from this string.", "Invalid value", 480 JOptionPane.ERROR_MESSAGE); 481 481 return false; 482 482 } 483 483 } 484 484 485 485 public String getStopwatchStart() 486 486 { 487 487 return tfStopwatchStart.getText(); 488 488 } 489 489 490 490 public void setStopwatchStart(String s) 491 491 { 492 492 tfStopwatchStart.setText(s); 493 493 } 494 494 495 495 public double getTimeWindow() 496 496 { 497 497 return Double.parseDouble(tfTimeWindow.getText()); 498 498 } 499 499 500 500 public double getThreshold() 501 501 { 502 502 return Double.parseDouble(tfThreshold.getText()); 503 503 } 504 504 505 505 public JTable getGTFSStopTable() 506 506 { 507 507 return gtfsStopTable; 508 508 } 509 509 510 510 public void setGTFSStopTableModel(GTFSStopTableModel model) 511 511 { … … 516 516 gtfsStopTable.getColumnModel().getColumn(2).setPreferredWidth((int)(width * 0.1)); 517 517 } 518 518 519 519 public static double parseTime(String s) 520 520 { 521 521 double result = 0; 522 522 if ((s.charAt(2) != ':') || (s.charAt(2) != ':') 523 523 || (s.length() < 8)) 524 524 return -1; 525 525 int hour = Integer.parseInt(s.substring(0, 2)); … … 527 527 double second = Double.parseDouble(s.substring(6, s.length())); 528 528 if ((hour < 0) || (hour > 23) || (minute < 0) || (minute > 59) 529 529 || (second < 0) || (second >= 60.0)) 530 530 return -1; 531 531 return (second + minute*60 + hour*60*60); 532 532 } 533 533 534 534 /* private class TracksLSL implements ListSelectionListener 535 535 { 536 536 GTFSImporterAction root = null; 537 537 538 538 public TracksLSL(GTFSImporterAction sia) 539 539 { 540 540 root = sia; 541 541 } 542 542 543 543 public void valueChanged(ListSelectionEvent e) 544 544 { 545 545 int selectedPos = tracksList.getAnchorSelectionIndex(); 546 546 if (tracksList.isSelectedIndex(selectedPos)) 547 547 root.tracksSelectionChanged(selectedPos); 548 548 else 549 549 root.tracksSelectionChanged(-1); 550 550 } 551 551 };*/ -
applications/editors/josm/plugins/public_transport/src/public_transport/GTFSJoinCommand.java
r22148 r23192 18 18 private GTFSStopTableModel gtfsStopTM = null; 19 19 private String type = null; 20 20 21 21 public GTFSJoinCommand(GTFSImporterAction controller) 22 22 { 23 23 gtfsStopTM = controller.getGTFSStopTableModel(); 24 24 workingLines = new Vector< Integer >(); 25 25 26 26 // use either selected lines or all lines if no line is selected 27 27 int[] selectedLines = controller.getDialog().getGTFSStopTable().getSelectedRows(); … … 30 30 workingLines.add(selectedLines[0]); 31 31 } 32 32 33 33 public boolean executeCommand() 34 34 { … … 43 43 Node n = iter.next(); 44 44 if ((n != null) && (n.equals(gtfsStopTM.nodes.elementAt(j)))) 45 45 continue; 46 46 if (dest != null) 47 47 return false; 48 48 dest = n; 49 49 } … … 51 51 return false; 52 52 undoMapNode = new Node(dest); 53 53 54 54 Node node = gtfsStopTM.nodes.elementAt(j); 55 55 undoTableNode = node; … … 59 59 node.setDeleted(true); 60 60 } 61 61 62 62 dest.put("highway", "bus_stop"); 63 63 dest.put("stop_id", (String)gtfsStopTM.getValueAt(j, 0)); … … 67 67 type = (String)gtfsStopTM.getValueAt(j, 2); 68 68 gtfsStopTM.setValueAt("moved", j, 2); 69 69 70 70 return true; 71 71 } 72 72 73 73 public void undoCommand() 74 74 { … … 76 76 return; 77 77 int j = workingLines.elementAt(0); 78 78 79 79 Node node = gtfsStopTM.nodes.elementAt(j); 80 80 if (node != null) … … 83 83 node.setDeleted(true); 84 84 } 85 85 86 86 if (undoMapNode != null) 87 87 { … … 97 97 gtfsStopTM.setValueAt(type, j, 2); 98 98 } 99 99 100 100 public void fillModifiedData 101 101 (Collection< OsmPrimitive > modified, Collection< OsmPrimitive > deleted, … … 103 103 { 104 104 } 105 105 106 106 @Override public JLabel getDescription() 107 107 { -
applications/editors/josm/plugins/public_transport/src/public_transport/GTFSStopTableModel.java
r23095 r23192 27 27 private int lonCol = -1; 28 28 private char separator = ','; 29 29 30 30 public GTFSStopTableModel(GTFSImporterAction controller, 31 31 String columnConfig) 32 32 { 33 33 int pos = columnConfig.indexOf(separator); … … 48 48 String title = columnConfig.substring(oldPos, pos); 49 49 if ("stop_id".equals(title)) 50 50 idCol = i; 51 51 else if ("stop_name".equals(title)) 52 52 nameCol = i; 53 53 else if ("stop_lat".equals(title)) 54 54 latCol = i; 55 55 else if ("stop_lon".equals(title)) 56 56 lonCol = i; 57 57 ++i; 58 58 oldPos = pos + 1; … … 68 68 else if ("stop_lon".equals(title)) 69 69 lonCol = i; 70 70 71 71 this.controller = controller; 72 72 addColumn("Id"); … … 75 75 addTableModelListener(this); 76 76 } 77 77 78 78 public boolean isCellEditable(int row, int column) 79 79 { 80 80 return false; 81 81 } 82 82 83 83 public void addRow(Object[] obj) 84 84 { 85 85 throw new UnsupportedOperationException(); 86 86 } 87 87 88 88 public void insertRow(int insPos, Object[] obj) 89 89 { 90 90 throw new UnsupportedOperationException(); 91 91 } 92 92 93 93 public void addRow(String s) 94 94 { 95 95 insertRow(-1, s, new Vector< Node >()); 96 96 } 97 97 98 98 public void addRow(String s, Vector< Node > existingStops) 99 99 { … … 135 135 return s; 136 136 } 137 137 138 138 public void insertRow(int insPos, String s, Vector< Node > existingStops) 139 139 { … … 147 147 { 148 148 if (i == idCol) 149 149 buf[0] = stripQuot(s.substring(oldPos, pos)); 150 150 else if (i == nameCol) 151 151 buf[1] = stripQuot(s.substring(oldPos, pos)); 152 152 else if (i == latCol) 153 153 lat = Double.parseDouble(stripQuot(s.substring(oldPos, pos))); 154 154 else if (i == lonCol) 155 155 lon = Double.parseDouble(stripQuot(s.substring(oldPos, pos))); 156 156 ++i; 157 157 oldPos = pos + 1; … … 166 166 else if (i == lonCol) 167 167 lon = Double.parseDouble(stripQuot(s.substring(oldPos))); 168 168 169 169 LatLon coor = new LatLon(lat, lon); 170 170 171 171 if (Main.main.getCurrentDataSet() != null) 172 172 { … … 176 176 while (iter.hasNext()) 177 177 { 178 179 180 181 182 178 if (iter.next().bounds.contains(coor)) 179 { 180 inside = true; 181 break; 182 } 183 183 } 184 184 if (!inside) 185 186 } 187 185 buf[2] = "outside"; 186 } 187 188 188 boolean nearBusStop = false; 189 189 Iterator< Node > iter = existingStops.iterator(); … … 193 193 if (coor.greatCircleDistance(node.getCoor()) < 1000) 194 194 { 195 196 197 } 198 } 199 195 nearBusStop = true; 196 break; 197 } 198 } 199 200 200 if (insPos == -1) 201 201 { 202 202 if ((nearBusStop) || !("pending".equals(buf[2]))) 203 203 nodes.addElement(null); 204 204 else 205 205 { 206 207 208 206 Node node = GTFSImporterAction.createNode(coor, buf[0], buf[1]); 207 nodes.addElement(node); 208 buf[2] = "added"; 209 209 } 210 210 coors.addElement(coor); … … 214 214 { 215 215 if ((nearBusStop) || !("pending".equals(buf[2]))) 216 216 nodes.insertElementAt(null, insPos); 217 217 else 218 218 { 219 220 221 219 Node node = GTFSImporterAction.createNode(coor, buf[0], buf[1]); 220 nodes.insertElementAt(node, insPos); 221 buf[2] = "added"; 222 222 } 223 223 coors.insertElementAt(coor, insPos); … … 225 225 } 226 226 } 227 227 228 228 public void clear() 229 229 { … … 231 231 super.setRowCount(0); 232 232 } 233 233 234 234 public void tableChanged(TableModelEvent e) 235 235 { -
applications/editors/josm/plugins/public_transport/src/public_transport/ItineraryTableModel.java
r20895 r23192 3 3 // import static org.openstreetmap.josm.tools.I18n.marktr; 4 4 // import static org.openstreetmap.josm.tools.I18n.tr; 5 // 5 // 6 6 // import java.awt.BorderLayout; 7 7 // import java.awt.Container; … … 21 21 // import java.util.TreeSet; 22 22 import java.util.Vector; 23 // 23 // 24 24 // import javax.swing.DefaultCellEditor; 25 25 // import javax.swing.DefaultListModel; … … 43 43 import javax.swing.table.DefaultTableModel; 44 44 // import javax.swing.table.TableCellEditor; 45 // 45 // 46 46 // import org.openstreetmap.josm.Main; 47 47 // import org.openstreetmap.josm.actions.JosmAction; … … 64 64 public Vector<Way> ways = new Vector<Way>(); 65 65 public boolean inEvent = false; 66 66 67 67 public boolean isCellEditable(int row, int column) 68 68 { … … 73 73 return true; 74 74 } 75 75 76 76 public void addRow(Object[] obj) 77 77 { … … 79 79 super.addRow(obj); 80 80 } 81 81 82 82 public void insertRow(int insPos, Object[] obj) 83 83 { … … 93 93 } 94 94 } 95 95 96 96 public void addRow(Way way, String role) 97 97 { 98 98 insertRow(-1, way, role); 99 99 } 100 100 101 101 public void insertRow(int insPos, Way way, String role) 102 102 { … … 123 123 } 124 124 } 125 125 126 126 public void clear() 127 127 { … … 129 129 super.setRowCount(0); 130 130 } 131 131 132 132 public void cleanupGaps() 133 133 { 134 134 inEvent = true; 135 135 Node lastNode = null; 136 136 137 137 for (int i = 0; i < getRowCount(); ++i) 138 138 { 139 139 if (ways.elementAt(i) == null) 140 140 { 141 142 143 141 ++i; 142 if (i >= getRowCount()) 143 break; 144 144 } 145 145 while ((ways.elementAt(i) == null) && 146 147 { 148 149 150 151 146 ((i == 0) || (ways.elementAt(i-1) == null))) 147 { 148 ways.removeElementAt(i); 149 removeRow(i); 150 if (i >= getRowCount()) 151 break; 152 152 } 153 153 if (i >= getRowCount()) 154 155 154 break; 155 156 156 boolean gapRequired = gapNecessary 157 157 (ways.elementAt(i), (String)(getValueAt(i, 1)), lastNode); 158 158 if ((i > 0) && (!gapRequired) && (ways.elementAt(i-1) == null)) 159 159 { 160 161 162 160 ways.removeElementAt(i-1); 161 removeRow(i-1); 162 --i; 163 163 } 164 164 else if ((i > 0) && gapRequired && (ways.elementAt(i-1) != null)) 165 165 { 166 167 168 169 166 String[] buf = { "", "" }; 167 buf[0] = "[gap]"; 168 insertRow(i, buf); 169 ++i; 170 170 } 171 171 lastNode = getLastNode(ways.elementAt(i), (String)(getValueAt(i, 1))); … … 179 179 inEvent = false; 180 180 } 181 181 182 182 public void tableChanged(TableModelEvent e) 183 183 { … … 185 185 { 186 186 if (inEvent) 187 187 return; 188 188 cleanupGaps(); 189 189 RoutePatternAction.rebuildWays(); 190 190 } 191 191 } 192 192 193 193 private Node getLastNode(Way way, String role) 194 194 { … … 200 200 return way.getNode(0); 201 201 else 202 203 } 204 } 205 202 return way.getNode(way.getNodesCount() - 1); 203 } 204 } 205 206 206 private boolean gapNecessary(Way way, String role, Node lastNode) 207 207 { … … 212 212 firstNode = way.getNode(way.getNodesCount() - 1); 213 213 else 214 214 firstNode = way.getNode(0); 215 215 if ((lastNode != null) && (!lastNode.equals(firstNode))) 216 216 return true; 217 217 } 218 218 return false; -
applications/editors/josm/plugins/public_transport/src/public_transport/PublicTransportPlugin.java
r22148 r23192 23 23 24 24 public class PublicTransportPlugin extends Plugin { 25 25 26 26 static JMenu jMenu; 27 27 -
applications/editors/josm/plugins/public_transport/src/public_transport/RoutePatternAction.java
r21867 r23192 60 60 61 61 public class RoutePatternAction extends JosmAction { 62 62 63 63 private class RoutesLSL implements ListSelectionListener { 64 64 RoutePatternAction root = null; 65 65 66 66 public RoutesLSL(RoutePatternAction rpa) { 67 67 root = rpa; 68 68 } 69 69 70 70 public void valueChanged(ListSelectionEvent e) { 71 71 root.routesSelectionChanged(); 72 72 } 73 73 }; 74 74 75 75 private class RouteReference implements Comparable< RouteReference > { 76 76 Relation route; 77 77 78 78 public RouteReference(Relation route) { 79 79 this.route = route; 80 80 } 81 81 82 82 public int compareTo(RouteReference rr) { 83 83 if (route.get("route") != null) 84 84 { 85 86 87 88 89 85 if (rr.route.get("route") == null) 86 return -1; 87 int result = route.get("route").compareTo(rr.route.get("route")); 88 if (result != 0) 89 return result; 90 90 } 91 91 else if (rr.route.get("route") != null) 92 92 return 1; 93 93 if (route.get("ref") != null) 94 94 { 95 96 97 98 99 95 if (rr.route.get("ref") == null) 96 return -1; 97 int result = route.get("ref").compareTo(rr.route.get("ref")); 98 if (result != 0) 99 return result; 100 100 } 101 101 else if (rr.route.get("ref") != null) 102 102 return 1; 103 103 if (route.get("to") != null) 104 104 { 105 106 107 108 109 105 if (rr.route.get("to") == null) 106 return -1; 107 int result = route.get("to").compareTo(rr.route.get("to")); 108 if (result != 0) 109 return result; 110 110 } 111 111 else if (rr.route.get("to") != null) 112 112 return 1; 113 113 if (route.get("direction") != null) 114 114 { 115 116 117 118 119 115 if (rr.route.get("direction") == null) 116 return -1; 117 int result = route.get("direction").compareTo(rr.route.get("direction")); 118 if (result != 0) 119 return result; 120 120 } 121 121 else if (rr.route.get("direction") != null) 122 122 return 1; 123 123 if (route.getId() < rr.route.getId()) 124 124 return -1; 125 125 else if (route.getId() > rr.route.getId()) 126 126 return 1; 127 127 return 0; 128 128 } 129 129 130 130 public String toString() { 131 131 String buf = route.get("route"); 132 132 if ((route.get("ref") != null) && (route.get("ref") != "")) 133 133 { 134 135 136 137 138 139 140 141 142 143 144 145 134 if ((route.get("to") != null) && (route.get("to") != "")) 135 { 136 buf += " " + route.get("ref") + ": " + route.get("to"); 137 } 138 else if ((route.get("direction") != null) && (route.get("direction") != "")) 139 { 140 buf += " " + route.get("ref") + ": " + route.get("direction"); 141 } 142 else 143 { 144 buf += " " + route.get("ref"); 145 } 146 146 } 147 147 buf += " [ID " + Long.toString(route.getId()) + "]"; 148 148 149 149 return buf; 150 150 } 151 151 }; 152 152 153 153 private class TagTableModel extends DefaultTableModel implements TableModelListener { 154 154 Relation relation = null; 155 155 TreeSet< String > blacklist = null; 156 156 boolean hasFixedKeys = true; 157 157 158 158 public TagTableModel(boolean hasFixedKeys) { 159 159 this.hasFixedKeys = hasFixedKeys; … … 162 162 public boolean isCellEditable(int row, int column) { 163 163 if ((column == 0) && (hasFixedKeys)) 164 164 return false; 165 165 return true; 166 166 } 167 167 168 168 public void readRelation(Relation rel) { 169 169 relation = rel; 170 170 171 171 for (int i = 0; i < getRowCount(); ++i) 172 172 { 173 174 175 176 177 } 178 } 179 173 String value = rel.get((String)getValueAt(i, 0)); 174 if (value == null) 175 value = ""; 176 setValueAt(value, i, 1); 177 } 178 } 179 180 180 public void readRelation(Relation rel, TreeSet< String > blacklist) { 181 181 relation = rel; 182 182 this.blacklist = blacklist; 183 183 184 184 setRowCount(0); 185 185 Iterator< Map.Entry< String, String > > iter = rel.getKeys().entrySet().iterator(); 186 186 while (iter.hasNext()) 187 187 { 188 189 190 191 192 193 194 195 196 } 197 188 Map.Entry< String, String > entry = iter.next(); 189 if (!blacklist.contains(entry.getKey())) 190 { 191 Vector< String > newRow = new Vector< String >(); 192 newRow.add(entry.getKey()); 193 newRow.add(entry.getValue()); 194 addRow(newRow); 195 } 196 } 197 198 198 for (int i = 0; i < getRowCount(); ++i) 199 199 { 200 201 202 203 204 } 205 } 206 200 String value = rel.get((String)getValueAt(i, 0)); 201 if (value == null) 202 value = ""; 203 setValueAt(value, i, 1); 204 } 205 } 206 207 207 public void tableChanged(TableModelEvent e) 208 208 { 209 209 if (e.getType() == TableModelEvent.UPDATE) 210 210 { 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 211 relation.setModified(true); 212 213 String key = (String)getValueAt(e.getFirstRow(), 0); 214 if (key == null) 215 return; 216 if ((blacklist == null) || (!blacklist.contains(key))) 217 { 218 relation.setModified(true); 219 if ("".equals(getValueAt(e.getFirstRow(), 1))) 220 relation.remove(key); 221 else 222 relation.put(key, (String)getValueAt(e.getFirstRow(), 1)); 223 } 224 else 225 { 226 if (e.getColumn() == 0) 227 setValueAt("", e.getFirstRow(), 0); 228 } 229 229 } 230 230 } 231 231 }; 232 232 233 233 private class CustomCellEditorTable extends JTable { 234 234 TreeMap< Integer, TableCellEditor > col1 = null; 235 235 TreeMap< Integer, TableCellEditor > col2 = null; 236 236 237 237 public CustomCellEditorTable() { 238 238 col1 = new TreeMap< Integer, TableCellEditor >(); 239 239 col2 = new TreeMap< Integer, TableCellEditor >(); 240 240 } 241 241 242 242 public TableCellEditor getCellEditor(int row, int column) { 243 243 TableCellEditor editor = null; 244 244 if (column == 0) 245 245 editor = col1.get(new Integer(row)); 246 246 else 247 247 editor = col2.get(new Integer(row)); 248 248 if (editor == null) 249 249 return new DefaultCellEditor(new JTextField()); 250 250 else 251 252 } 253 251 return editor; 252 } 253 254 254 public void setCellEditor(int row, int column, TableCellEditor editor) { 255 255 if (column == 0) 256 256 col1.put(new Integer(row), editor); 257 257 else 258 258 col2.put(new Integer(row), editor); 259 259 } 260 260 }; 261 261 262 262 private class StoplistTableModel extends DefaultTableModel { 263 263 public Vector<Node> nodes = new Vector<Node>(); 264 264 265 265 public boolean isCellEditable(int row, int column) { 266 266 if (column != 1) 267 267 return false; 268 268 return true; 269 269 } 270 270 271 271 public void addRow(Object[] obj) { 272 272 throw new UnsupportedOperationException(); 273 273 } 274 274 275 275 public void insertRow(int insPos, Object[] obj) { 276 276 throw new UnsupportedOperationException(); 277 277 } 278 278 279 279 public void addRow(Node node, String role) { 280 280 insertRow(-1, node, role); 281 281 } 282 282 283 283 public void insertRow(int insPos, Node node, String role) { 284 284 String[] buf = { "", "" }; … … 286 286 if (curName != null) 287 287 { 288 288 buf[0] = curName; 289 289 } 290 290 else 291 291 { 292 292 buf[0] = "[ID] " + (new Long(node.getId())).toString(); 293 293 } 294 294 buf[1] = role; 295 295 if (insPos == -1) 296 296 { 297 298 297 nodes.addElement(node); 298 super.addRow(buf); 299 299 } 300 300 else 301 301 { 302 303 304 } 305 } 306 302 nodes.insertElementAt(node, insPos); 303 super.insertRow(insPos, buf); 304 } 305 } 306 307 307 public void clear() 308 308 { … … 311 311 } 312 312 }; 313 313 314 314 private class StoplistTableModelListener implements TableModelListener { 315 315 public void tableChanged(TableModelEvent e) … … 317 317 if (e.getType() == TableModelEvent.UPDATE) 318 318 { 319 319 rebuildNodes(); 320 320 } 321 321 } 322 322 }; 323 323 324 324 private class SegmentMetric { 325 325 public double aLat, aLon; 326 326 public double length; 327 327 public double d1, d2, o1, o2; 328 328 329 329 public SegmentMetric(double fromLat, double fromLon, double toLat, double toLon) { 330 330 aLat = fromLat; 331 331 aLon = fromLon; 332 332 333 333 //Compute length and direction 334 334 //length is in units of latitude degrees … … 336 336 d2 = (toLon - fromLon) * Math.cos(fromLat * Math.PI/180.0); 337 337 length = Math.sqrt(d1*d1 + d2*d2); 338 338 339 339 //Normalise direction 340 340 d1 = d1 / length; 341 341 d2 = d2 / length; 342 342 343 343 //Compute orthogonal direction (right hand size is positive) 344 344 o1 = - d2; 345 345 o2 = d1; 346 346 347 347 //Prepare lon direction to reduce the number of necessary multiplications 348 348 d2 = d2 * Math.cos(fromLat * Math.PI/180.0); … … 350 350 } 351 351 }; 352 352 353 353 private class StopReference implements Comparable< StopReference > { 354 354 public int index = 0; … … 358 358 public String role = ""; 359 359 public Node node; 360 360 361 361 public StopReference(int inIndex, double inPos, double inDistance, 362 362 String inName, String inRole, Node inNode) { 363 363 index = inIndex; 364 364 pos = inPos; … … 368 368 node = inNode; 369 369 } 370 370 371 371 public int compareTo(StopReference sr) { 372 372 if (this.index < sr.index) 373 373 return -1; 374 374 if (this.index > sr.index) 375 375 return 1; 376 376 if (this.pos < sr.pos) 377 377 return -1; 378 378 if (this.pos > sr.pos) 379 379 return 1; 380 380 return 0; 381 381 } 382 382 }; 383 383 384 384 private static JDialog jDialog = null; 385 385 private static JTabbedPane tabbedPane = null; … … 403 403 private static Vector< RelationMember > markedWays = new Vector< RelationMember >(); 404 404 private static Vector< RelationMember > markedNodes = new Vector< RelationMember >(); 405 405 406 406 private static Relation copy = null; 407 407 408 408 public RoutePatternAction() { 409 409 super(tr("Route patterns ..."), null, 410 410 tr("Edit Route patterns for public transport"), null, true); 411 411 } 412 412 … … 414 414 Frame frame = JOptionPane.getFrameForComponent(Main.parent); 415 415 DataSet mainDataSet = Main.main.getCurrentDataSet(); 416 416 417 417 if (jDialog == null) 418 418 { … … 435 435 tabbedPane.setEnabledAt(4, false); 436 436 jDialog.add(tabbedPane); 437 437 438 438 //Overview Tab 439 439 Container contentPane = tabOverview; … … 441 441 GridBagConstraints layoutCons = new GridBagConstraints(); 442 442 contentPane.setLayout(gridbag); 443 443 444 444 JLabel headline = new JLabel("Existing route patterns:"); 445 445 446 446 layoutCons.gridx = 0; 447 447 layoutCons.gridy = 0; … … 452 452 gridbag.setConstraints(headline, layoutCons); 453 453 contentPane.add(headline); 454 454 455 455 relsListModel = new DefaultListModel(); 456 456 relsList = new JList(relsListModel); … … 460 460 relsList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); 461 461 relsList.addListSelectionListener(new RoutesLSL(this)); 462 462 463 463 layoutCons.gridx = 0; 464 464 layoutCons.gridy = 1; … … 469 469 gridbag.setConstraints(rpListSP, layoutCons); 470 470 contentPane.add(rpListSP); 471 471 472 472 JButton bRefresh = new JButton("Refresh"); 473 473 bRefresh.setActionCommand("routePattern.refresh"); 474 474 bRefresh.addActionListener(this); 475 475 476 476 layoutCons.gridx = 0; 477 477 layoutCons.gridy = 2; … … 483 483 gridbag.setConstraints(bRefresh, layoutCons); 484 484 contentPane.add(bRefresh); 485 485 486 486 JButton bNew = new JButton("New"); 487 487 bNew.setActionCommand("routePattern.overviewNew"); 488 488 bNew.addActionListener(this); 489 489 490 490 layoutCons.gridx = 1; 491 491 layoutCons.gridy = 2; … … 497 497 gridbag.setConstraints(bNew, layoutCons); 498 498 contentPane.add(bNew); 499 499 500 500 JButton bDelete = new JButton("Delete"); 501 501 bDelete.setActionCommand("routePattern.overviewDelete"); 502 502 bDelete.addActionListener(this); 503 503 504 504 layoutCons.gridx = 1; 505 505 layoutCons.gridy = 3; … … 511 511 gridbag.setConstraints(bDelete, layoutCons); 512 512 contentPane.add(bDelete); 513 513 514 514 JButton bDuplicate = new JButton("Duplicate"); 515 515 bDuplicate.setActionCommand("routePattern.overviewDuplicate"); 516 516 bDuplicate.addActionListener(this); 517 517 518 518 layoutCons.gridx = 2; 519 519 layoutCons.gridy = 2; … … 525 525 gridbag.setConstraints(bDuplicate, layoutCons); 526 526 contentPane.add(bDuplicate); 527 527 528 528 JButton bReflect = new JButton("Reflect"); 529 529 bReflect.setActionCommand("routePattern.overviewReflect"); 530 530 bReflect.addActionListener(this); 531 531 532 532 layoutCons.gridx = 2; 533 533 layoutCons.gridy = 3; … … 539 539 gridbag.setConstraints(bReflect, layoutCons); 540 540 contentPane.add(bReflect); 541 541 542 542 //Tags Tab 543 543 /*Container*/ contentPane = tabTags; … … 545 545 /*GridBagConstraints*/ layoutCons = new GridBagConstraints(); 546 546 contentPane.setLayout(gridbag); 547 547 548 548 /*JLabel*/ headline = new JLabel("Required tags:"); 549 549 550 550 layoutCons.gridx = 0; 551 551 layoutCons.gridy = 0; … … 555 555 gridbag.setConstraints(headline, layoutCons); 556 556 contentPane.add(headline); 557 557 558 558 requiredTagsTable = new CustomCellEditorTable(); 559 559 requiredTagsData = new TagTableModel(true); … … 600 600 JScrollPane tableSP = new JScrollPane(requiredTagsTable); 601 601 requiredTagsData.addTableModelListener(requiredTagsData); 602 602 603 603 layoutCons.gridx = 0; 604 604 layoutCons.gridy = 1; … … 611 611 tableSP.setPreferredSize(preferredSize); 612 612 contentPane.add(tableSP); 613 613 614 614 headline = new JLabel("Common tags:"); 615 615 616 616 layoutCons.gridx = 0; 617 617 layoutCons.gridy = 2; … … 621 621 gridbag.setConstraints(headline, layoutCons); 622 622 contentPane.add(headline); 623 623 624 624 commonTagsTable = new CustomCellEditorTable(); 625 625 commonTagsData = new TagTableModel(true); … … 654 654 /*JScrollPane*/ tableSP = new JScrollPane(commonTagsTable); 655 655 commonTagsData.addTableModelListener(commonTagsData); 656 656 657 657 layoutCons.gridx = 0; 658 658 layoutCons.gridy = 3; … … 665 665 tableSP.setPreferredSize(preferredSize); 666 666 contentPane.add(tableSP); 667 667 668 668 headline = new JLabel("Additional tags:"); 669 669 670 670 layoutCons.gridx = 0; 671 671 layoutCons.gridy = 4; … … 675 675 gridbag.setConstraints(headline, layoutCons); 676 676 contentPane.add(headline); 677 677 678 678 otherTagsTable = new CustomCellEditorTable(); 679 679 otherTagsData = new TagTableModel(false); … … 683 683 /*JScrollPane*/ tableSP = new JScrollPane(otherTagsTable); 684 684 otherTagsData.addTableModelListener(otherTagsData); 685 685 686 686 layoutCons.gridx = 0; 687 687 layoutCons.gridy = 5; … … 694 694 tableSP.setPreferredSize(preferredSize); 695 695 contentPane.add(tableSP); 696 696 697 697 JButton bAddTag = new JButton("Add a new Tag"); 698 698 bAddTag.setActionCommand("routePattern.tagAddTag"); 699 699 bAddTag.addActionListener(this); 700 700 701 701 layoutCons.gridx = 0; 702 702 layoutCons.gridy = 6; … … 707 707 gridbag.setConstraints(bAddTag, layoutCons); 708 708 contentPane.add(bAddTag); 709 709 710 710 //Itinerary Tab 711 711 contentPane = tabItinerary; … … 713 713 layoutCons = new GridBagConstraints(); 714 714 contentPane.setLayout(gridbag); 715 715 716 716 itineraryTable = new JTable(); 717 717 itineraryData = new ItineraryTableModel(); … … 725 725 comboBox.addItem("backward"); 726 726 itineraryTable.getColumnModel().getColumn(1) 727 727 .setCellEditor(new DefaultCellEditor(comboBox)); 728 728 itineraryData.addTableModelListener(itineraryData); 729 729 730 730 layoutCons.gridx = 0; 731 731 layoutCons.gridy = 0; … … 736 736 gridbag.setConstraints(tableSP, layoutCons); 737 737 contentPane.add(tableSP); 738 738 739 739 JButton bFind = new JButton("Find"); 740 740 bFind.setActionCommand("routePattern.itineraryFind"); 741 741 bFind.addActionListener(this); 742 742 743 743 layoutCons.gridx = 0; 744 744 layoutCons.gridy = 1; … … 749 749 gridbag.setConstraints(bFind, layoutCons); 750 750 contentPane.add(bFind); 751 751 752 752 JButton bShow = new JButton("Show"); 753 753 bShow.setActionCommand("routePattern.itineraryShow"); 754 754 bShow.addActionListener(this); 755 755 756 756 layoutCons.gridx = 0; 757 757 layoutCons.gridy = 2; … … 762 762 gridbag.setConstraints(bShow, layoutCons); 763 763 contentPane.add(bShow); 764 764 765 765 JButton bMark = new JButton("Mark"); 766 766 bMark.setActionCommand("routePattern.itineraryMark"); 767 767 bMark.addActionListener(this); 768 768 769 769 layoutCons.gridx = 1; 770 770 layoutCons.gridy = 1; … … 776 776 gridbag.setConstraints(bMark, layoutCons); 777 777 contentPane.add(bMark); 778 778 779 779 JButton bAdd = new JButton("Add"); 780 780 bAdd.setActionCommand("routePattern.itineraryAdd"); 781 781 bAdd.addActionListener(this); 782 782 783 783 layoutCons.gridx = 2; 784 784 layoutCons.gridy = 1; … … 790 790 gridbag.setConstraints(bAdd, layoutCons); 791 791 contentPane.add(bAdd); 792 792 793 793 /*JButton*/ bDelete = new JButton("Delete"); 794 794 bDelete.setActionCommand("routePattern.itineraryDelete"); 795 795 bDelete.addActionListener(this); 796 796 797 797 layoutCons.gridx = 2; 798 798 layoutCons.gridy = 2; … … 803 803 gridbag.setConstraints(bDelete, layoutCons); 804 804 contentPane.add(bDelete); 805 805 806 806 JButton bSort = new JButton("Sort"); 807 807 bSort.setActionCommand("routePattern.itinerarySort"); 808 808 bSort.addActionListener(this); 809 809 810 810 layoutCons.gridx = 3; 811 811 layoutCons.gridy = 1; … … 816 816 gridbag.setConstraints(bSort, layoutCons); 817 817 contentPane.add(bSort); 818 818 819 819 /*JButton*/ bReflect = new JButton("Reflect"); 820 820 bReflect.setActionCommand("routePattern.itineraryReflect"); 821 821 bReflect.addActionListener(this); 822 822 823 823 layoutCons.gridx = 3; 824 824 layoutCons.gridy = 2; … … 829 829 gridbag.setConstraints(bReflect, layoutCons); 830 830 contentPane.add(bReflect); 831 831 832 832 //Stoplist Tab 833 833 contentPane = tabStoplist; … … 835 835 layoutCons = new GridBagConstraints(); 836 836 contentPane.setLayout(gridbag); 837 837 838 838 stoplistTable = new JTable(); 839 839 stoplistData = new StoplistTableModel(); … … 847 847 comboBox.addItem("backward_stop"); 848 848 stoplistTable.getColumnModel().getColumn(1) 849 849 .setCellEditor(new DefaultCellEditor(comboBox)); 850 850 stoplistData.addTableModelListener(new StoplistTableModelListener()); 851 851 852 852 layoutCons.gridx = 0; 853 853 layoutCons.gridy = 0; … … 858 858 gridbag.setConstraints(tableSP, layoutCons); 859 859 contentPane.add(tableSP); 860 860 861 861 /*JButton*/ bFind = new JButton("Find"); 862 862 bFind.setActionCommand("routePattern.stoplistFind"); 863 863 bFind.addActionListener(this); 864 864 865 865 layoutCons.gridx = 0; 866 866 layoutCons.gridy = 1; … … 871 871 gridbag.setConstraints(bFind, layoutCons); 872 872 contentPane.add(bFind); 873 873 874 874 /*JButton*/ bShow = new JButton("Show"); 875 875 bShow.setActionCommand("routePattern.stoplistShow"); 876 876 bShow.addActionListener(this); 877 877 878 878 layoutCons.gridx = 0; 879 879 layoutCons.gridy = 2; … … 884 884 gridbag.setConstraints(bShow, layoutCons); 885 885 contentPane.add(bShow); 886 886 887 887 /*JButton*/ bMark = new JButton("Mark"); 888 888 bMark.setActionCommand("routePattern.stoplistMark"); 889 889 bMark.addActionListener(this); 890 890 891 891 layoutCons.gridx = 1; 892 892 layoutCons.gridy = 1; … … 898 898 gridbag.setConstraints(bMark, layoutCons); 899 899 contentPane.add(bMark); 900 900 901 901 /*JButton*/ bAdd = new JButton("Add"); 902 902 bAdd.setActionCommand("routePattern.stoplistAdd"); 903 903 bAdd.addActionListener(this); 904 904 905 905 layoutCons.gridx = 2; 906 906 layoutCons.gridy = 1; … … 912 912 gridbag.setConstraints(bAdd, layoutCons); 913 913 contentPane.add(bAdd); 914 914 915 915 /*JButton*/ bDelete = new JButton("Delete"); 916 916 bDelete.setActionCommand("routePattern.stoplistDelete"); 917 917 bDelete.addActionListener(this); 918 918 919 919 layoutCons.gridx = 2; 920 920 layoutCons.gridy = 2; … … 925 925 gridbag.setConstraints(bDelete, layoutCons); 926 926 contentPane.add(bDelete); 927 927 928 928 /*JButton*/ bSort = new JButton("Sort"); 929 929 bSort.setActionCommand("routePattern.stoplistSort"); 930 930 bSort.addActionListener(this); 931 931 932 932 layoutCons.gridx = 3; 933 933 layoutCons.gridy = 1; … … 938 938 gridbag.setConstraints(bSort, layoutCons); 939 939 contentPane.add(bSort); 940 940 941 941 /*JButton*/ bReflect = new JButton("Reflect"); 942 942 bReflect.setActionCommand("routePattern.stoplistReflect"); 943 943 bReflect.addActionListener(this); 944 944 945 945 layoutCons.gridx = 3; 946 946 layoutCons.gridy = 2; … … 951 951 gridbag.setConstraints(bReflect, layoutCons); 952 952 contentPane.add(bReflect); 953 953 954 954 //Meta Tab 955 955 contentPane = tabMeta; … … 957 957 layoutCons = new GridBagConstraints(); 958 958 contentPane.setLayout(gridbag); 959 959 960 960 JLabel rightleft = new JLabel("Stops are possible on the"); 961 961 962 962 layoutCons.gridx = 0; 963 963 layoutCons.gridy = 1; … … 968 968 gridbag.setConstraints(rightleft, layoutCons); 969 969 contentPane.add(rightleft); 970 970 971 971 cbRight = new JCheckBox("right hand side", true); 972 972 973 973 layoutCons.gridx = 0; 974 974 layoutCons.gridy = 2; … … 979 979 gridbag.setConstraints(cbRight, layoutCons); 980 980 contentPane.add(cbRight); 981 981 982 982 cbLeft = new JCheckBox("left hand side", false); 983 983 984 984 layoutCons.gridx = 0; 985 985 layoutCons.gridy = 3; … … 990 990 gridbag.setConstraints(cbLeft, layoutCons); 991 991 contentPane.add(cbLeft); 992 992 993 993 JLabel maxdist = new JLabel("Maximum distance from route"); 994 994 995 995 layoutCons.gridx = 0; 996 996 layoutCons.gridy = 4; … … 1001 1001 gridbag.setConstraints(maxdist, layoutCons); 1002 1002 contentPane.add(maxdist); 1003 1003 1004 1004 tfSuggestStopsLimit = new JTextField("20", 4); 1005 1005 1006 1006 layoutCons.gridx = 0; 1007 1007 layoutCons.gridy = 5; … … 1012 1012 gridbag.setConstraints(tfSuggestStopsLimit, layoutCons); 1013 1013 contentPane.add(tfSuggestStopsLimit); 1014 1014 1015 1015 JLabel meters = new JLabel("meters"); 1016 1016 1017 1017 layoutCons.gridx = 1; 1018 1018 layoutCons.gridy = 5; … … 1023 1023 gridbag.setConstraints(meters, layoutCons); 1024 1024 contentPane.add(meters); 1025 1025 1026 1026 JButton bSuggestStops = new JButton("Suggest Stops"); 1027 1027 bSuggestStops.setActionCommand("routePattern.metaSuggestStops"); 1028 1028 bSuggestStops.addActionListener(this); 1029 1029 1030 1030 layoutCons.gridx = 0; 1031 1031 layoutCons.gridy = 6; … … 1036 1036 gridbag.setConstraints(bSuggestStops, layoutCons); 1037 1037 contentPane.add(bSuggestStops); 1038 1038 1039 1039 jDialog.pack(); 1040 1040 } 1041 1041 1042 1042 if ("routePattern.refresh".equals(event.getActionCommand())) 1043 1043 { … … 1050 1050 currentRoute.put("route", "bus"); 1051 1051 mainDataSet.addPrimitive(currentRoute); 1052 1052 1053 1053 refreshData(); 1054 1054 1055 1055 for (int i = 0; i < relsListModel.size(); ++i) 1056 1056 { 1057 1058 1057 if (currentRoute == ((RouteReference)relsListModel.elementAt(i)).route) 1058 relsList.setSelectedIndex(i); 1059 1059 } 1060 1060 } … … 1065 1065 currentRoute.put("route", "bus"); 1066 1066 mainDataSet.addPrimitive(currentRoute); 1067 1067 1068 1068 refreshData(); 1069 1069 1070 1070 for (int i = 0; i < relsListModel.size(); ++i) 1071 1071 { 1072 1073 1072 if (currentRoute == ((RouteReference)relsListModel.elementAt(i)).route) 1073 relsList.setSelectedIndex(i); 1074 1074 } 1075 1075 } … … 1081 1081 currentRoute.put("from", tag_to); 1082 1082 currentRoute.put("to", tag_from); 1083 1083 1084 1084 Vector< RelationMember > itemsToReflect = new Vector< RelationMember >(); 1085 1085 Vector< RelationMember > otherItems = new Vector< RelationMember >(); 1086 1086 int insPos = itineraryTable.getSelectedRow(); 1087 1087 1088 1088 for (int i = 0; i < currentRoute.getMembersCount(); ++i) 1089 1089 { 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 } 1109 1090 RelationMember item = currentRoute.getMember(i); 1091 1092 if (item.isWay()) 1093 { 1094 String role = item.getRole(); 1095 if ("backward".equals(role)) 1096 role = "forward"; 1097 else if ("forward".equals(role)) 1098 role = "backward"; 1099 else 1100 role = "backward"; 1101 1102 itemsToReflect.add(new RelationMember(role, item.getWay())); 1103 } 1104 else if (item.isNode()) 1105 itemsToReflect.add(item); 1106 else 1107 otherItems.add(item); 1108 } 1109 1110 1110 currentRoute.setMembers(null); 1111 1111 for (int i = itemsToReflect.size()-1; i >= 0; --i) 1112 1112 currentRoute.addMember(itemsToReflect.elementAt(i)); 1113 1113 for (int i = 0; i < otherItems.size(); ++i) 1114 1115 1114 currentRoute.addMember(otherItems.elementAt(i)); 1115 1116 1116 refreshData(); 1117 1117 1118 1118 for (int i = 0; i < relsListModel.size(); ++i) 1119 1119 { 1120 1121 1120 if (currentRoute == ((RouteReference)relsListModel.elementAt(i)).route) 1121 relsList.setSelectedIndex(i); 1122 1122 } 1123 1123 } … … 1125 1125 { 1126 1126 DeleteAction.deleteRelation(Main.main.getEditLayer(), currentRoute); 1127 1127 1128 1128 currentRoute = null; 1129 1129 tabbedPane.setEnabledAt(1, false); … … 1131 1131 tabbedPane.setEnabledAt(3, false); 1132 1132 tabbedPane.setEnabledAt(4, false); 1133 1133 1134 1134 refreshData(); 1135 1135 } … … 1144 1144 { 1145 1145 if (mainDataSet == null) 1146 1147 1146 return; 1147 1148 1148 itineraryTable.clearSelection(); 1149 1149 1150 1150 for (int i = 0; i < itineraryData.getRowCount(); ++i) 1151 1151 { 1152 1153 1154 1152 if ((itineraryData.ways.elementAt(i) != null) && 1153 (mainDataSet.isSelected(itineraryData.ways.elementAt(i)))) 1154 itineraryTable.addRowSelectionInterval(i, i); 1155 1155 } 1156 1156 } … … 1160 1160 if (itineraryTable.getSelectedRowCount() > 0) 1161 1161 { 1162 1163 1164 1165 1166 1167 1168 1162 for (int i = 0; i < itineraryData.getRowCount(); ++i) 1163 { 1164 if ((itineraryTable.isRowSelected(i)) && (itineraryData.ways.elementAt(i) != null)) 1165 { 1166 itineraryData.ways.elementAt(i).visit(box); 1167 } 1168 } 1169 1169 } 1170 1170 else 1171 1171 { 1172 1173 1174 1175 1176 1177 1178 1172 for (int i = 0; i < itineraryData.getRowCount(); ++i) 1173 { 1174 if (itineraryData.ways.elementAt(i) != null) 1175 { 1176 itineraryData.ways.elementAt(i).visit(box); 1177 } 1178 } 1179 1179 } 1180 1180 if (box.getBounds() == null) 1181 1181 return; 1182 1182 box.enlargeBoundingBox(); 1183 1183 Main.map.mapView.recalculateCenterScale(box); … … 1190 1190 if (itineraryTable.getSelectedRowCount() > 0) 1191 1191 { 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1192 for (int i = 0; i < itineraryData.getRowCount(); ++i) 1193 { 1194 if ((itineraryTable.isRowSelected(i)) && (itineraryData.ways.elementAt(i) != null)) 1195 { 1196 mainDataSet.addSelected(itineraryData.ways.elementAt(i)); 1197 1198 RelationMember markedWay = new RelationMember 1199 ((String)(itineraryData.getValueAt(i, 1)), itineraryData.ways.elementAt(i)); 1200 markedWays.addElement(markedWay); 1201 } 1202 } 1203 1203 } 1204 1204 else 1205 1205 { 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1206 for (int i = 0; i < itineraryData.getRowCount(); ++i) 1207 { 1208 if (itineraryData.ways.elementAt(i) != null) 1209 { 1210 mainDataSet.addSelected(itineraryData.ways.elementAt(i)); 1211 1212 RelationMember markedWay = new RelationMember 1213 ((String)(itineraryData.getValueAt(i, 1)), itineraryData.ways.elementAt(i)); 1214 markedWays.addElement(markedWay); 1215 } 1216 } 1217 1217 } 1218 1218 } … … 1223 1223 TreeSet<Way> addedWays = new TreeSet<Way>(); 1224 1224 if (mainDataSet == null) 1225 1226 1225 return; 1226 1227 1227 while (relIter.hasNext()) 1228 1228 { 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 } 1239 1229 RelationMember curMember = relIter.next(); 1230 if ((curMember.isWay()) && (mainDataSet.isSelected(curMember.getWay()))) 1231 { 1232 itineraryData.insertRow(insPos, curMember.getWay(), curMember.getRole()); 1233 if (insPos >= 0) 1234 ++insPos; 1235 1236 addedWays.add(curMember.getWay()); 1237 } 1238 } 1239 1240 1240 Collection<Way> selectedWays = mainDataSet.getSelectedWays(); 1241 1241 Iterator<Way> wayIter = selectedWays.iterator(); 1242 1242 1243 1243 while (wayIter.hasNext()) 1244 1244 { 1245 1246 1247 1248 1249 1250 1251 1252 } 1253 1245 Way curMember = wayIter.next(); 1246 if (!(addedWays.contains(curMember))) 1247 { 1248 itineraryData.insertRow(insPos, curMember, ""); 1249 if (insPos >= 0) 1250 ++insPos; 1251 } 1252 } 1253 1254 1254 if ((insPos > 0) && (insPos < itineraryData.getRowCount())) 1255 1255 { 1256 1257 1258 1259 1260 1261 1256 while ((insPos < itineraryData.getRowCount()) 1257 && (itineraryData.ways.elementAt(insPos) == null)) 1258 ++insPos; 1259 itineraryTable.removeRowSelectionInterval(0, itineraryData.getRowCount()-1); 1260 if (insPos < itineraryData.getRowCount()) 1261 itineraryTable.addRowSelectionInterval(insPos, insPos); 1262 1262 } 1263 1263 … … 1269 1269 for (int i = itineraryData.getRowCount()-1; i >=0; --i) 1270 1270 { 1271 1272 1273 1274 1275 1276 } 1277 1271 if ((itineraryTable.isRowSelected(i)) && (itineraryData.ways.elementAt(i) != null)) 1272 { 1273 itineraryData.ways.removeElementAt(i); 1274 itineraryData.removeRow(i); 1275 } 1276 } 1277 1278 1278 itineraryData.cleanupGaps(); 1279 1279 rebuildWays(); … … 1283 1283 TreeSet<Way> usedWays = new TreeSet<Way>(); 1284 1284 TreeMap<Node, LinkedList<RelationMember> > frontNodes = 1285 1285 new TreeMap<Node, LinkedList<RelationMember> >(); 1286 1286 TreeMap<Node, LinkedList<RelationMember> > backNodes = 1287 1287 new TreeMap<Node, LinkedList<RelationMember> >(); 1288 1288 Vector< LinkedList<RelationMember> > loops = 1289 1289 new Vector< LinkedList<RelationMember> >(); 1290 1290 int insPos = itineraryTable.getSelectedRow(); 1291 1291 1292 1292 if (itineraryTable.getSelectedRowCount() > 0) 1293 1293 { 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1294 for (int i = itineraryData.getRowCount()-1; i >=0; --i) 1295 { 1296 if ((itineraryTable.isRowSelected(i)) && (itineraryData.ways.elementAt(i) != null)) 1297 { 1298 if (!(usedWays.contains(itineraryData.ways.elementAt(i)))) 1299 { 1300 addWayToSortingData 1301 (itineraryData.ways.elementAt(i), frontNodes, backNodes, loops); 1302 usedWays.add(itineraryData.ways.elementAt(i)); 1303 } 1304 1305 itineraryData.ways.removeElementAt(i); 1306 itineraryData.removeRow(i); 1307 } 1308 } 1309 1309 } 1310 1310 else 1311 1311 { 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1312 for (int i = itineraryData.getRowCount()-1; i >=0; --i) 1313 { 1314 if (itineraryData.ways.elementAt(i) != null) 1315 { 1316 if (!(usedWays.contains(itineraryData.ways.elementAt(i)))) 1317 { 1318 addWayToSortingData 1319 (itineraryData.ways.elementAt(i), frontNodes, backNodes, loops); 1320 usedWays.add(itineraryData.ways.elementAt(i)); 1321 } 1322 } 1323 } 1324 1325 itineraryData.clear(); 1326 1326 } 1327 1327 1328 1328 Iterator< Map.Entry< Node, LinkedList<RelationMember> > > entryIter 1329 1329 = frontNodes.entrySet().iterator(); 1330 1330 while (entryIter.hasNext()) 1331 1331 { 1332 1333 1334 1335 1336 1337 1338 1339 1340 } 1341 1332 Iterator<RelationMember> relIter = entryIter.next().getValue().iterator(); 1333 while (relIter.hasNext()) 1334 { 1335 RelationMember curMember = relIter.next(); 1336 itineraryData.insertRow(insPos, curMember.getWay(), curMember.getRole()); 1337 if (insPos >= 0) 1338 ++insPos; 1339 } 1340 } 1341 1342 1342 Iterator< LinkedList<RelationMember> > listIter = loops.iterator(); 1343 1343 while (listIter.hasNext()) 1344 1344 { 1345 1346 1347 1348 1349 1350 1351 1352 1353 } 1354 1345 Iterator<RelationMember> relIter = listIter.next().iterator(); 1346 while (relIter.hasNext()) 1347 { 1348 RelationMember curMember = relIter.next(); 1349 itineraryData.insertRow(insPos, curMember.getWay(), curMember.getRole()); 1350 if (insPos >= 0) 1351 ++insPos; 1352 } 1353 } 1354 1355 1355 itineraryData.cleanupGaps(); 1356 1356 rebuildWays(); … … 1360 1360 Vector<RelationMember> itemsToReflect = new Vector<RelationMember>(); 1361 1361 int insPos = itineraryTable.getSelectedRow(); 1362 1362 1363 1363 if (itineraryTable.getSelectedRowCount() > 0) 1364 1364 { 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1365 for (int i = itineraryData.getRowCount()-1; i >=0; --i) 1366 { 1367 if ((itineraryTable.isRowSelected(i)) && (itineraryData.ways.elementAt(i) != null)) 1368 { 1369 String role = (String)(itineraryData.getValueAt(i, 1)); 1370 if ("backward".equals(role)) 1371 role = "forward"; 1372 else if ("forward".equals(role)) 1373 role = "backward"; 1374 else 1375 role = "backward"; 1376 RelationMember markedWay = new RelationMember 1377 (role, itineraryData.ways.elementAt(i)); 1378 itemsToReflect.addElement(markedWay); 1379 1380 itineraryData.ways.removeElementAt(i); 1381 itineraryData.removeRow(i); 1382 } 1383 } 1384 1384 } 1385 1385 else 1386 1386 { 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1387 for (int i = itineraryData.getRowCount()-1; i >=0; --i) 1388 { 1389 if (itineraryData.ways.elementAt(i) != null) 1390 { 1391 String role = (String)(itineraryData.getValueAt(i, 1)); 1392 if ("backward".equals(role)) 1393 role = "forward"; 1394 else if ("forward".equals(role)) 1395 role = "backward"; 1396 else 1397 role = "backward"; 1398 RelationMember markedWay = new RelationMember 1399 (role, itineraryData.ways.elementAt(i)); 1400 itemsToReflect.addElement(markedWay); 1401 } 1402 } 1403 1404 itineraryData.clear(); 1405 1405 } 1406 1406 … … 1409 1409 while (relIter.hasNext()) 1410 1410 { 1411 RelationMember curMember = relIter.next(); 1412 if (curMember.isWay()) 1413 { 1414 itineraryData.insertRow(insPos, curMember.getWay(), curMember.getRole()); 1415 if (insPos >= 0) 1416 ++insPos; 1417 } 1418 } 1411 RelationMember curMember = relIter.next(); 1412 if (curMember.isWay()) 1413 { 1414 itineraryData.insertRow(insPos, curMember.getWay(), curMember.getRole()); 1419 1415 if (insPos >= 0) 1420 itineraryTable.addRowSelectionInterval(startPos, insPos-1); 1421 1416 ++insPos; 1417 } 1418 } 1419 if (insPos >= 0) 1420 itineraryTable.addRowSelectionInterval(startPos, insPos-1); 1421 1422 1422 itineraryData.cleanupGaps(); 1423 1423 rebuildWays(); … … 1426 1426 { 1427 1427 if (mainDataSet == null) 1428 1429 1428 return; 1429 1430 1430 stoplistTable.clearSelection(); 1431 1431 1432 1432 for (int i = 0; i < stoplistData.getRowCount(); ++i) 1433 1433 { 1434 1435 1436 1434 if ((stoplistData.nodes.elementAt(i) != null) && 1435 (mainDataSet.isSelected(stoplistData.nodes.elementAt(i)))) 1436 stoplistTable.addRowSelectionInterval(i, i); 1437 1437 } 1438 1438 } … … 1442 1442 if (stoplistTable.getSelectedRowCount() > 0) 1443 1443 { 1444 1445 1446 1447 1448 1449 1450 1444 for (int i = 0; i < stoplistData.getRowCount(); ++i) 1445 { 1446 if (stoplistTable.isRowSelected(i)) 1447 { 1448 stoplistData.nodes.elementAt(i).visit(box); 1449 } 1450 } 1451 1451 } 1452 1452 else 1453 1453 { 1454 1455 1456 1457 1454 for (int i = 0; i < stoplistData.getRowCount(); ++i) 1455 { 1456 stoplistData.nodes.elementAt(i).visit(box); 1457 } 1458 1458 } 1459 1459 if (box.getBounds() == null) 1460 1460 return; 1461 1461 box.enlargeBoundingBox(); 1462 1462 Main.map.mapView.recalculateCenterScale(box); … … 1469 1469 if (stoplistTable.getSelectedRowCount() > 0) 1470 1470 { 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1471 for (int i = 0; i < stoplistData.getRowCount(); ++i) 1472 { 1473 if (stoplistTable.isRowSelected(i)) 1474 { 1475 mainDataSet.addSelected(stoplistData.nodes.elementAt(i)); 1476 1477 RelationMember markedNode = new RelationMember 1478 ((String)(stoplistData.getValueAt(i, 1)), stoplistData.nodes.elementAt(i)); 1479 markedNodes.addElement(markedNode); 1480 } 1481 } 1482 1482 } 1483 1483 else 1484 1484 { 1485 1486 1487 1488 1489 1490 1491 1492 1485 for (int i = 0; i < stoplistData.getRowCount(); ++i) 1486 { 1487 mainDataSet.addSelected(stoplistData.nodes.elementAt(i)); 1488 1489 RelationMember markedNode = new RelationMember 1490 ((String)(stoplistData.getValueAt(i, 1)), stoplistData.nodes.elementAt(i)); 1491 markedNodes.addElement(markedNode); 1492 } 1493 1493 } 1494 1494 } … … 1499 1499 TreeSet<Node> addedNodes = new TreeSet<Node>(); 1500 1500 if (mainDataSet == null) 1501 1502 1501 return; 1502 1503 1503 while (relIter.hasNext()) 1504 1504 { 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 } 1515 1505 RelationMember curMember = relIter.next(); 1506 if ((curMember.isNode()) && (mainDataSet.isSelected(curMember.getNode()))) 1507 { 1508 stoplistData.insertRow(insPos, curMember.getNode(), curMember.getRole()); 1509 if (insPos >= 0) 1510 ++insPos; 1511 1512 addedNodes.add(curMember.getNode()); 1513 } 1514 } 1515 1516 1516 Collection<Node> selectedNodes = mainDataSet.getSelectedNodes(); 1517 1517 Iterator<Node> nodeIter = selectedNodes.iterator(); 1518 1518 1519 1519 while (nodeIter.hasNext()) 1520 1520 { 1521 1522 1523 1524 1525 1526 1527 1528 } 1529 1521 Node curMember = nodeIter.next(); 1522 if (!(addedNodes.contains(curMember))) 1523 { 1524 stoplistData.insertRow(insPos, curMember, ""); 1525 if (insPos >= 0) 1526 ++insPos; 1527 } 1528 } 1529 1530 1530 if ((insPos > 0) && (insPos < stoplistData.getRowCount())) 1531 1531 { 1532 1533 1534 1535 1536 1537 1532 while ((insPos < stoplistData.getRowCount()) 1533 && (stoplistData.nodes.elementAt(insPos) == null)) 1534 ++insPos; 1535 stoplistTable.removeRowSelectionInterval(0, stoplistData.getRowCount()-1); 1536 if (insPos < stoplistData.getRowCount()) 1537 stoplistTable.addRowSelectionInterval(insPos, insPos); 1538 1538 } 1539 1539 … … 1544 1544 for (int i = stoplistData.getRowCount()-1; i >=0; --i) 1545 1545 { 1546 1547 1548 1549 1550 1551 } 1552 1546 if (stoplistTable.isRowSelected(i)) 1547 { 1548 stoplistData.nodes.removeElementAt(i); 1549 stoplistData.removeRow(i); 1550 } 1551 } 1552 1553 1553 rebuildNodes(); 1554 1554 } … … 1560 1560 for (int i = 0; i < itineraryData.getRowCount(); ++i) 1561 1561 { 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 } 1594 1562 if (itineraryData.ways.elementAt(i) != null) 1563 { 1564 Way way = itineraryData.ways.elementAt(i); 1565 if (!(way.isIncomplete())) 1566 { 1567 if ("backward".equals((String)(itineraryData.getValueAt(i, 1)))) 1568 { 1569 for (int j = way.getNodesCount()-2; j >= 0; --j) 1570 { 1571 SegmentMetric sm = new SegmentMetric 1572 (way.getNode(j+1).getCoor().lat(), way.getNode(j+1).getCoor().lon(), 1573 way.getNode(j).getCoor().lat(), way.getNode(j).getCoor().lon()); 1574 segmentMetrics.add(sm); 1575 } 1576 } 1577 else 1578 { 1579 for (int j = 0; j < way.getNodesCount()-1; ++j) 1580 { 1581 SegmentMetric sm = new SegmentMetric 1582 (way.getNode(j).getCoor().lat(), way.getNode(j).getCoor().lon(), 1583 way.getNode(j+1).getCoor().lat(), way.getNode(j+1).getCoor().lon()); 1584 segmentMetrics.add(sm); 1585 } 1586 } 1587 } 1588 } 1589 else 1590 { 1591 segmentMetrics.add(null); 1592 } 1593 } 1594 1595 1595 Vector< StopReference > srm = new Vector< StopReference >(); 1596 1596 int insPos = stoplistTable.getSelectedRow(); … … 1599 1599 // Determine for each member its position on the itinerary: position means here the 1600 1600 // point on the itinerary that has minimal distance to the coor 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1601 for (int i = stoplistData.getRowCount()-1; i >= 0; --i) 1602 { 1603 if (stoplistTable.isRowSelected(i)) 1604 { 1605 StopReference sr = detectMinDistance 1606 (stoplistData.nodes.elementAt(i), segmentMetrics, 1607 cbRight.isSelected(), cbLeft.isSelected()); 1608 if (sr != null) 1609 { 1610 if (sr.distance < 1611 Double.parseDouble(tfSuggestStopsLimit.getText()) * 9.0 / 1000000.0 ) 1612 { 1613 sr.role = (String)stoplistData.getValueAt(i, 1); 1614 srm.addElement(sr); 1615 } 1616 else 1617 { 1618 sr.role = (String)stoplistData.getValueAt(i, 1); 1619 sr.index = segmentMetrics.size()*2; 1620 sr.pos = 0; 1621 srm.addElement(sr); 1622 } 1623 1624 stoplistData.nodes.removeElementAt(i); 1625 stoplistData.removeRow(i); 1626 } 1627 1628 } 1629 } 1630 1630 } 1631 1631 else 1632 1632 { 1633 1633 // Determine for each member its position on the itinerary: position means here the 1634 1634 // point on the itinerary that has minimal distance to the coor 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1635 for (int i = stoplistData.getRowCount()-1; i >= 0; --i) 1636 { 1637 StopReference sr = detectMinDistance 1638 (stoplistData.nodes.elementAt(i), segmentMetrics, 1639 cbRight.isSelected(), cbLeft.isSelected()); 1640 if (sr != null) 1641 { 1642 if (sr.distance < 1643 Double.parseDouble(tfSuggestStopsLimit.getText()) * 9.0 / 1000000.0 ) 1644 { 1645 sr.role = (String)stoplistData.getValueAt(i, 1); 1646 srm.addElement(sr); 1647 } 1648 else 1649 { 1650 sr.role = (String)stoplistData.getValueAt(i, 1); 1651 sr.index = segmentMetrics.size()*2; 1652 sr.pos = 0; 1653 srm.addElement(sr); 1654 } 1655 } 1656 } 1657 1658 stoplistData.clear(); 1659 1659 } 1660 1660 1661 1661 Collections.sort(srm); 1662 1662 1663 1663 for (int i = 0; i < srm.size(); ++i) 1664 1664 { 1665 1666 1667 1668 } 1669 1665 stoplistData.insertRow(insPos, srm.elementAt(i).node, srm.elementAt(i).role); 1666 if (insPos >= 0) 1667 ++insPos; 1668 } 1669 1670 1670 rebuildNodes(); 1671 1671 } … … 1674 1674 Vector<RelationMember> itemsToReflect = new Vector<RelationMember>(); 1675 1675 int insPos = stoplistTable.getSelectedRow(); 1676 1676 1677 1677 if (stoplistTable.getSelectedRowCount() > 0) 1678 1678 { 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1679 for (int i = stoplistData.getRowCount()-1; i >=0; --i) 1680 { 1681 if (stoplistTable.isRowSelected(i)) 1682 { 1683 String role = (String)(stoplistData.getValueAt(i, 1)); 1684 RelationMember markedNode = new RelationMember 1685 (role, stoplistData.nodes.elementAt(i)); 1686 itemsToReflect.addElement(markedNode); 1687 1688 stoplistData.nodes.removeElementAt(i); 1689 stoplistData.removeRow(i); 1690 } 1691 } 1692 1692 } 1693 1693 else 1694 1694 { 1695 1696 1697 1698 1699 1700 1701 1702 1703 1695 for (int i = stoplistData.getRowCount()-1; i >=0; --i) 1696 { 1697 String role = (String)(stoplistData.getValueAt(i, 1)); 1698 RelationMember markedNode = new RelationMember 1699 (role, stoplistData.nodes.elementAt(i)); 1700 itemsToReflect.addElement(markedNode); 1701 } 1702 1703 stoplistData.clear(); 1704 1704 } 1705 1705 … … 1708 1708 while (relIter.hasNext()) 1709 1709 { 1710 RelationMember curMember = relIter.next(); 1711 if (curMember.isNode()) 1712 { 1713 stoplistData.insertRow(insPos, curMember.getNode(), curMember.getRole()); 1714 if (insPos >= 0) 1715 ++insPos; 1716 } 1717 } 1710 RelationMember curMember = relIter.next(); 1711 if (curMember.isNode()) 1712 { 1713 stoplistData.insertRow(insPos, curMember.getNode(), curMember.getRole()); 1718 1714 if (insPos >= 0) 1719 stoplistTable.addRowSelectionInterval(startPos, insPos-1); 1720 1715 ++insPos; 1716 } 1717 } 1718 if (insPos >= 0) 1719 stoplistTable.addRowSelectionInterval(startPos, insPos-1); 1720 1721 1721 rebuildNodes(); 1722 1722 } … … 1728 1728 for (int i = 0; i < itineraryData.getRowCount(); ++i) 1729 1729 { 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 } 1762 1730 if (itineraryData.ways.elementAt(i) != null) 1731 { 1732 Way way = itineraryData.ways.elementAt(i); 1733 if (!(way.isIncomplete())) 1734 { 1735 if ("backward".equals((String)(itineraryData.getValueAt(i, 1)))) 1736 { 1737 for (int j = way.getNodesCount()-2; j >= 0; --j) 1738 { 1739 SegmentMetric sm = new SegmentMetric 1740 (way.getNode(j+1).getCoor().lat(), way.getNode(j+1).getCoor().lon(), 1741 way.getNode(j).getCoor().lat(), way.getNode(j).getCoor().lon()); 1742 segmentMetrics.add(sm); 1743 } 1744 } 1745 else 1746 { 1747 for (int j = 0; j < way.getNodesCount()-1; ++j) 1748 { 1749 SegmentMetric sm = new SegmentMetric 1750 (way.getNode(j).getCoor().lat(), way.getNode(j).getCoor().lon(), 1751 way.getNode(j+1).getCoor().lat(), way.getNode(j+1).getCoor().lon()); 1752 segmentMetrics.add(sm); 1753 } 1754 } 1755 } 1756 } 1757 else 1758 { 1759 segmentMetrics.add(null); 1760 } 1761 } 1762 1763 1763 Vector< StopReference > srm = new Vector< StopReference >(); 1764 1764 // Determine for each member its position on the itinerary: position means here the … … 1767 1767 if (mainDataSet != null) 1768 1768 { 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 if ((sr != null) && (sr.distance < 1815 1816 1817 1818 1769 String stopKey = ""; 1770 String stopValue = ""; 1771 if ("bus".equals(currentRoute.get("route"))) 1772 { 1773 stopKey = "highway"; 1774 stopValue = "bus_stop"; 1775 } 1776 else if ("trolleybus".equals(currentRoute.get("route"))) 1777 { 1778 stopKey = "highway"; 1779 stopValue = "bus_stop"; 1780 } 1781 else if ("tram".equals(currentRoute.get("route"))) 1782 { 1783 stopKey = "railway"; 1784 stopValue = "tram_stop"; 1785 } 1786 else if ("light_rail".equals(currentRoute.get("route"))) 1787 { 1788 stopKey = "railway"; 1789 stopValue = "station"; 1790 } 1791 else if ("subway".equals(currentRoute.get("route"))) 1792 { 1793 stopKey = "railway"; 1794 stopValue = "station"; 1795 } 1796 else if ("rail".equals(currentRoute.get("route"))) 1797 { 1798 stopKey = "railway"; 1799 stopValue = "station"; 1800 } 1801 1802 Collection< Node > nodeCollection = mainDataSet.getNodes(); 1803 Iterator< Node > nodeIter = nodeCollection.iterator(); 1804 while (nodeIter.hasNext()) 1805 { 1806 Node currentNode = nodeIter.next(); 1807 if (!currentNode.isUsable()) 1808 continue; 1809 if (stopValue.equals(currentNode.get(stopKey))) 1810 { 1811 StopReference sr = detectMinDistance 1812 (currentNode, segmentMetrics, 1813 cbRight.isSelected(), cbLeft.isSelected()); 1814 if ((sr != null) && (sr.distance < 1815 Double.parseDouble(tfSuggestStopsLimit.getText()) * 9.0 / 1000000.0 )) 1816 srm.addElement(sr); 1817 } 1818 } 1819 1819 } 1820 1820 else 1821 1821 { 1822 1823 1822 JOptionPane.showMessageDialog(null, "There exists no dataset." 1823 + " Try to download data from the server or open an OSM file.", 1824 1824 "No data found", JOptionPane.ERROR_MESSAGE); 1825 1826 1827 } 1828 1825 1826 System.out.println("Public Transport: RoutePattern: No data found"); 1827 } 1828 1829 1829 for (int i = 0; i < stoplistData.getRowCount(); ++i) 1830 1830 { … … 1832 1832 1833 1833 Collections.sort(srm); 1834 1834 1835 1835 stoplistData.clear(); 1836 1836 for (int i = 0; i < srm.size(); ++i) 1837 1837 { 1838 1839 } 1840 1838 stoplistData.addRow(srm.elementAt(i).node, srm.elementAt(i).role); 1839 } 1840 1841 1841 rebuildNodes(); 1842 1842 } … … 1844 1844 { 1845 1845 refreshData(); 1846 1846 1847 1847 jDialog.setLocationRelativeTo(frame); 1848 1848 jDialog.setVisible(true); 1849 1849 } 1850 1850 } 1851 1851 1852 1852 private void refreshData() { 1853 1853 Relation copy = currentRoute; 1854 1854 relsListModel.clear(); 1855 1855 currentRoute = copy; 1856 1856 1857 1857 DataSet mainDataSet = Main.main.getCurrentDataSet(); 1858 1858 if (mainDataSet != null) … … 1861 1861 Collection< Relation > relCollection = mainDataSet.getRelations(); 1862 1862 Iterator< Relation > relIter = relCollection.iterator(); 1863 1863 1864 1864 while (relIter.hasNext()) 1865 1865 { 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 } 1884 1866 Relation currentRel = relIter.next(); 1867 if (!currentRel.isDeleted()) 1868 { 1869 String routeVal = currentRel.get("route"); 1870 if ("bus".equals(routeVal)) 1871 relRefs.add(new RouteReference(currentRel)); 1872 else if ("trolleybus".equals(routeVal)) 1873 relRefs.add(new RouteReference(currentRel)); 1874 else if ("tram".equals(routeVal)) 1875 relRefs.add(new RouteReference(currentRel)); 1876 else if ("light_rail".equals(routeVal)) 1877 relRefs.add(new RouteReference(currentRel)); 1878 else if ("subway".equals(routeVal)) 1879 relRefs.add(new RouteReference(currentRel)); 1880 else if ("rail".equals(routeVal)) 1881 relRefs.add(new RouteReference(currentRel)); 1882 } 1883 } 1884 1885 1885 Collections.sort(relRefs); 1886 1886 1887 1887 Iterator< RouteReference > iter = relRefs.iterator(); 1888 1888 while (iter.hasNext()) 1889 1889 relsListModel.addElement(iter.next()); 1890 1890 } 1891 1891 else 1892 1892 { 1893 1893 JOptionPane.showMessageDialog(null, "There exists no dataset." 1894 1894 + " Try to download data from the server or open an OSM file.", 1895 1895 "No data found", JOptionPane.ERROR_MESSAGE); 1896 1896 1897 1897 System.out.println("Public Transport: No data found"); 1898 1898 } 1899 1899 } 1900 1900 1901 1901 //Rebuild ways in the relation currentRoute 1902 1902 public static void rebuildWays() { … … 1907 1907 { 1908 1908 if (iter.next().isWay()) 1909 1909 iter.remove(); 1910 1910 } 1911 1911 for (int i = 0; i < itineraryData.getRowCount(); ++i) … … 1913 1913 if (itineraryData.ways.elementAt(i) != null) 1914 1914 { 1915 1916 1917 1918 1915 RelationMember member = new RelationMember 1916 ((String)(itineraryData.getValueAt(i, 1)), 1917 itineraryData.ways.elementAt(i)); 1918 members.add(member); 1919 1919 } 1920 1920 } 1921 1921 currentRoute.setMembers(members); 1922 1922 } 1923 1923 1924 1924 //Rebuild nodes in the relation currentRoute 1925 1925 private void rebuildNodes() { … … 1929 1929 if (currentRoute.getMember(i).isNode()) 1930 1930 { 1931 1931 currentRoute.removeMember(i); 1932 1932 } 1933 1933 } … … 1935 1935 { 1936 1936 RelationMember member = new RelationMember 1937 1937 ((String)(stoplistData.getValueAt(i, 1)), stoplistData.nodes.elementAt(i)); 1938 1938 currentRoute.addMember(member); 1939 1939 } 1940 1940 } 1941 1941 1942 1942 private void addWayToSortingData 1943 1943 (Way way, TreeMap<Node, LinkedList<RelationMember> > frontNodes, … … 1947 1947 if (way.getNodesCount() < 1) 1948 1948 return; 1949 1949 1950 1950 Node firstNode = way.getNode(0); 1951 1951 Node lastNode = way.getNode(way.getNodesCount() - 1); 1952 1952 1953 1953 if (frontNodes.get(firstNode) != null) 1954 1954 { … … 1956 1956 list.addFirst(new RelationMember("backward", way)); 1957 1957 frontNodes.remove(firstNode); 1958 1958 1959 1959 Node lastListNode = null; 1960 1960 if ("backward".equals(list.getLast().getRole())) 1961 1961 lastListNode = list.getLast().getWay().getNode(0); 1962 1962 else 1963 1964 1963 lastListNode = list.getLast().getWay().getNode 1964 (list.getLast().getWay().getNodesCount() - 1); 1965 1965 if (lastNode.equals(lastListNode)) 1966 1966 { 1967 1968 1967 backNodes.remove(lastListNode); 1968 loops.add(list); 1969 1969 } 1970 1970 else if (frontNodes.get(lastNode) != null) 1971 1971 { 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1972 backNodes.remove(lastListNode); 1973 LinkedList<RelationMember> listToAppend = frontNodes.get(lastNode); 1974 Iterator<RelationMember> memberIter = list.iterator(); 1975 while (memberIter.hasNext()) 1976 { 1977 RelationMember member = memberIter.next(); 1978 if ("backward".equals(member.getRole())) 1979 listToAppend.addFirst(new RelationMember("forward", member.getWay())); 1980 else 1981 listToAppend.addFirst(new RelationMember("backward", member.getWay())); 1982 } 1983 frontNodes.remove(lastNode); 1984 frontNodes.put(lastListNode, listToAppend); 1985 1985 } 1986 1986 else if (backNodes.get(lastNode) != null) 1987 1987 { 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1988 backNodes.remove(lastListNode); 1989 LinkedList<RelationMember> listToAppend = backNodes.get(lastNode); 1990 Iterator<RelationMember> memberIter = list.iterator(); 1991 while (memberIter.hasNext()) 1992 { 1993 RelationMember member = memberIter.next(); 1994 listToAppend.addLast(member); 1995 } 1996 backNodes.remove(lastNode); 1997 backNodes.put(lastListNode, listToAppend); 1998 1998 } 1999 1999 else 2000 2000 frontNodes.put(lastNode, list); 2001 2001 } 2002 2002 else if (backNodes.get(firstNode) != null) … … 2005 2005 list.addLast(new RelationMember("forward", way)); 2006 2006 backNodes.remove(firstNode); 2007 2007 2008 2008 Node firstListNode = null; 2009 2009 if ("backward".equals(list.getFirst().getRole())) 2010 2011 2010 firstListNode = list.getFirst().getWay().getNode 2011 (list.getFirst().getWay().getNodesCount() - 1); 2012 2012 else 2013 2013 firstListNode = list.getFirst().getWay().getNode(0); 2014 2014 if (lastNode.equals(firstListNode)) 2015 2015 { 2016 2017 2016 frontNodes.remove(firstListNode); 2017 loops.add(list); 2018 2018 } 2019 2019 else if (frontNodes.get(lastNode) != null) 2020 2020 { 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2021 frontNodes.remove(firstListNode); 2022 LinkedList<RelationMember> listToAppend = frontNodes.get(lastNode); 2023 ListIterator<RelationMember> memberIter = list.listIterator(list.size()); 2024 while (memberIter.hasPrevious()) 2025 { 2026 RelationMember member = memberIter.previous(); 2027 listToAppend.addFirst(member); 2028 } 2029 frontNodes.remove(lastNode); 2030 frontNodes.put(firstListNode, listToAppend); 2031 2031 } 2032 2032 else if (backNodes.get(lastNode) != null) 2033 2033 { 2034 frontNodes.remove(firstListNode); 2035 LinkedList<RelationMember> listToAppend = backNodes.get(lastNode); 2036 ListIterator<RelationMember> memberIter = list.listIterator(list.size()); 2037 while (memberIter.hasPrevious()) 2038 { 2039 RelationMember member = memberIter.previous(); 2040 if ("backward".equals(member.getRole())) 2041 listToAppend.addLast(new RelationMember("forward", member.getWay())); 2042 else 2043 listToAppend.addLast(new RelationMember("backward", member.getWay())); 2044 } 2045 backNodes.remove(lastNode); 2046 backNodes.put(firstListNode, listToAppend); 2047 } 2034 frontNodes.remove(firstListNode); 2035 LinkedList<RelationMember> listToAppend = backNodes.get(lastNode); 2036 ListIterator<RelationMember> memberIter = list.listIterator(list.size()); 2037 while (memberIter.hasPrevious()) 2038 { 2039 RelationMember member = memberIter.previous(); 2040 if ("backward".equals(member.getRole())) 2041 listToAppend.addLast(new RelationMember("forward", member.getWay())); 2048 2042 else 2049 backNodes.put(lastNode, list); 2043 listToAppend.addLast(new RelationMember("backward", member.getWay())); 2044 } 2045 backNodes.remove(lastNode); 2046 backNodes.put(firstListNode, listToAppend); 2047 } 2048 else 2049 backNodes.put(lastNode, list); 2050 2050 } 2051 2051 else if (frontNodes.get(lastNode) != null) … … 2071 2071 } 2072 2072 } 2073 2073 2074 2074 private void routesSelectionChanged() { 2075 2075 int selectedPos = relsList.getAnchorSelectionIndex(); … … 2081 2081 tabbedPane.setEnabledAt(3, true); 2082 2082 tabbedPane.setEnabledAt(4, true); 2083 2083 2084 2084 //Prepare Tags 2085 2085 requiredTagsData.readRelation(currentRoute); 2086 2086 commonTagsData.readRelation(currentRoute); 2087 2087 otherTagsData.readRelation(currentRoute, tagBlacklist); 2088 2088 2089 2089 //Prepare Itinerary 2090 2090 itineraryData.clear(); … … 2092 2092 Iterator<RelationMember> relIter = relMembers.iterator(); 2093 2093 fillItineraryTable(relIter, 0, -1); 2094 2094 2095 2095 //Prepare Stoplist 2096 2096 stoplistData.clear(); … … 2108 2108 } 2109 2109 } 2110 2110 2111 2111 private void fillItineraryTable 2112 2112 (Iterator<RelationMember> relIter, long lastNodeId, int insPos) { … … 2116 2116 if (curMember.isWay()) 2117 2117 { 2118 2119 2120 2118 itineraryData.insertRow(insPos, curMember.getWay(), curMember.getRole()); 2119 if (insPos >= 0) 2120 ++insPos; 2121 2121 } 2122 2122 } 2123 2123 itineraryData.cleanupGaps(); 2124 2124 } 2125 2125 2126 2126 private void fillStoplistTable 2127 2127 (Iterator<RelationMember> relIter, int insPos) { … … 2131 2131 if (curMember.isNode()) 2132 2132 { 2133 2134 2135 2133 stoplistData.insertRow(insPos, curMember.getNode(), curMember.getRole()); 2134 if (insPos >= 0) 2135 ++insPos; 2136 2136 } 2137 2137 } 2138 2138 } 2139 2139 2140 2140 private StopReference detectMinDistance 2141 2141 (Node node, Vector< SegmentMetric > segmentMetrics, … … 2146 2146 double lat = node.getCoor().lat(); 2147 2147 double lon = node.getCoor().lon(); 2148 2148 2149 2149 int curIndex = -2; 2150 2150 double angleLat = 100.0; … … 2155 2155 curIndex += 2; 2156 2156 SegmentMetric sm = iter.next(); 2157 2157 2158 2158 if (sm == null) 2159 2159 { 2160 2161 2162 2163 2164 } 2165 2160 angleLat = 100.0; 2161 angleLon = 200.0; 2162 2163 continue; 2164 } 2165 2166 2166 double curPosition = (lat - sm.aLat)*sm.d1 + (lon - sm.aLon)*sm.d2; 2167 2167 2168 2168 if (curPosition < 0) 2169 2169 { 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2170 if (angleLat <= 90.0) 2171 { 2172 double lastSegAngle = Math.atan2(angleLat - sm.aLat, angleLon - sm.aLon); 2173 double segAngle = Math.atan2(sm.d1, -sm.o1); 2174 double vertexAngle = Math.atan2(lat - sm.aLat, lon - sm.aLon); 2175 2176 boolean vertexOnSeg = (vertexAngle == segAngle) || 2177 (vertexAngle == lastSegAngle); 2178 boolean vertexOnTheLeft = (!vertexOnSeg) && 2179 (((lastSegAngle > vertexAngle) && (vertexAngle > segAngle)) 2180 || ((vertexAngle > segAngle) && (segAngle > lastSegAngle)) 2181 || ((segAngle > lastSegAngle) && (lastSegAngle > vertexAngle))); 2182 2183 double currentDistance = Math.sqrt((lat - sm.aLat)*(lat - sm.aLat) 2184 + (lon - sm.aLon)*(lon - sm.aLon) 2185 *Math.cos(sm.aLat * Math.PI/180.0)*Math.cos(sm.aLat * Math.PI/180.0)); 2186 curPosition = vertexAngle - segAngle; 2187 if (vertexOnTheLeft) 2188 curPosition = -curPosition; 2189 if (curPosition < 0) 2190 curPosition += 2*Math.PI; 2191 if ((Math.abs(currentDistance) < distance) 2192 && (((!vertexOnTheLeft) && (rhsPossible)) 2193 || ((vertexOnTheLeft) && (lhsPossible)) 2194 || (vertexOnSeg))) 2195 { 2196 distance = Math.abs(currentDistance); 2197 minIndex = curIndex-1; 2198 position = curPosition; 2199 } 2200 } 2201 angleLat = 100.0; 2202 angleLon = 200.0; 2203 2203 } 2204 2204 else if (curPosition > sm.length) 2205 2205 { 2206 2207 2206 angleLat = sm.aLat; 2207 angleLon = sm.aLon; 2208 2208 } 2209 2209 else 2210 2210 { 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 } 2224 } 2225 2211 double currentDistance = (lat - sm.aLat)*sm.o1 + (lon - sm.aLon)*sm.o2; 2212 if ((Math.abs(currentDistance) < distance) 2213 && (((currentDistance >= 0) && (rhsPossible)) 2214 || ((currentDistance <= 0) && (lhsPossible)))) 2215 { 2216 distance = Math.abs(currentDistance); 2217 minIndex = curIndex; 2218 position = curPosition; 2219 } 2220 2221 angleLat = 100.0; 2222 angleLon = 200.0; 2223 } 2224 } 2225 2226 2226 if (minIndex == -1) 2227 2227 return new StopReference(segmentMetrics.size()*2, 0, 180.0, node.get("name"), 2228 2229 2228 "", node); 2229 2230 2230 return new StopReference(minIndex, position, distance, node.get("name"), 2231 2231 "", node); 2232 2232 } 2233 2233 } -
applications/editors/josm/plugins/public_transport/src/public_transport/SettingsStoptypeCommand.java
r22048 r23192 21 21 railway = node.get("railway"); 22 22 } 23 23 24 24 public Node node; 25 25 public String highway; 26 26 public String railway; 27 27 }; 28 28 29 29 private Vector< HighwayRailway > oldStrings = null; 30 30 private WaypointTableModel waypointTM = null; 31 31 private DefaultListModel tracksListModel = null; 32 32 private String type = null; 33 33 34 34 public SettingsStoptypeCommand(StopImporterAction controller) 35 35 { … … 39 39 oldStrings = new Vector< HighwayRailway >(); 40 40 } 41 41 42 42 public boolean executeCommand() 43 43 { … … 47 47 if ((Node)waypointTM.nodes.elementAt(i) != null) 48 48 { 49 50 51 49 Node node = (Node)waypointTM.nodes.elementAt(i); 50 oldStrings.add(new HighwayRailway(node)); 51 StopImporterAction.setTagsWrtType(node, type); 52 52 } 53 53 } … … 57 57 for (int i = 0; i < track.stoplistTM.getRowCount(); ++i) 58 58 { 59 60 61 62 63 64 59 if (track.stoplistTM.nodeAt(i) != null) 60 { 61 Node node = track.stoplistTM.nodeAt(i); 62 oldStrings.add(new HighwayRailway(node)); 63 StopImporterAction.setTagsWrtType(node, type); 64 } 65 65 } 66 66 } 67 67 return true; 68 68 } 69 69 70 70 public void undoCommand() 71 71 { … … 77 77 } 78 78 } 79 79 80 80 public void fillModifiedData 81 81 (Collection< OsmPrimitive > modified, Collection< OsmPrimitive > deleted, … … 83 83 { 84 84 } 85 85 86 86 @Override public JLabel getDescription() 87 87 { 88 88 return new JLabel("public_transport.Settings.ChangeStoptype"); 89 89 } 90 90 91 91 }; -
applications/editors/josm/plugins/public_transport/src/public_transport/StopImporterAction.java
r20867 r23192 62 62 63 63 public class StopImporterAction extends JosmAction 64 { 64 { 65 65 private static StopImporterDialog dialog = null; 66 66 private static DefaultListModel tracksListModel = null; … … 69 69 private static WaypointTableModel waypointTM = null; 70 70 public boolean inEvent = false; 71 71 72 72 public StopImporterAction() 73 73 { 74 74 super(tr("Create Stops from GPX ..."), null, 75 75 tr("Create Stops from a GPX file"), null, true); 76 76 } 77 77 … … 80 80 return waypointTM; 81 81 } 82 82 83 83 public StopImporterDialog getDialog() 84 84 { … … 92 92 return tracksListModel; 93 93 } 94 94 95 95 public TrackReference getCurrentTrack() 96 96 { … … 101 101 { 102 102 DataSet mainDataSet = Main.main.getCurrentDataSet(); 103 103 104 104 if (dialog == null) 105 105 dialog = new StopImporterDialog(this); 106 106 107 107 dialog.setVisible(true); 108 108 … … 112 112 if (curDir.equals("")) 113 113 { 114 114 curDir = "."; 115 115 } 116 116 JFileChooser fc = new JFileChooser(new File(curDir)); 117 fc.setDialogTitle("Select GPX file"); 117 fc.setDialogTitle("Select GPX file"); 118 118 fc.setMultiSelectionEnabled(false); 119 119 120 120 int answer = fc.showOpenDialog(Main.parent); 121 121 if (answer != JFileChooser.APPROVE_OPTION) 122 123 122 return; 123 124 124 if (!fc.getCurrentDirectory().getAbsolutePath().equals(curDir)) 125 126 125 Main.pref.put("lastDirectory", fc.getCurrentDirectory().getAbsolutePath()); 126 127 127 importData(fc.getSelectedFile()); 128 128 129 129 refreshData(); 130 130 } … … 132 132 { 133 133 if ((!inEvent) && (dialog.gpsTimeStartValid()) && (currentTrack != null)) 134 134 Main.main.undoRedo.add(new TrackStoplistRelocateCommand(this)); 135 135 } 136 136 else if ("stopImporter.settingsStopwatchStart".equals(event.getActionCommand())) 137 137 { 138 138 if ((!inEvent) && (dialog.stopwatchStartValid()) && (currentTrack != null)) 139 139 Main.main.undoRedo.add(new TrackStoplistRelocateCommand(this)); 140 140 } 141 141 else if ("stopImporter.settingsTimeWindow".equals(event.getActionCommand())) 142 142 { 143 143 if (currentTrack != null) 144 144 currentTrack.timeWindow = dialog.getTimeWindow(); 145 145 } 146 146 else if ("stopImporter.settingsThreshold".equals(event.getActionCommand())) 147 147 { 148 148 if (currentTrack != null) 149 149 currentTrack.threshold = dialog.getThreshold(); 150 150 } 151 151 else if ("stopImporter.settingsSuggestStops".equals(event.getActionCommand())) … … 189 189 private void importData(final File file) 190 190 { 191 try 191 try 192 192 { 193 193 InputStream is; 194 194 if (file.getName().endsWith(".gpx.gz")) 195 195 is = new GZIPInputStream(new FileInputStream(file)); 196 196 else 197 197 is = new FileInputStream(file); 198 198 // Workaround for SAX BOM bug 199 199 // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6206835 200 200 if (!((is.read() == 0xef) && (is.read() == 0xbb) && (is.read() == 0xbf))) 201 201 { 202 203 204 205 206 202 is.close(); 203 if (file.getName().endsWith(".gpx.gz")) 204 is = new GZIPInputStream(new FileInputStream(file)); 205 else 206 is = new FileInputStream(file); 207 207 } 208 208 final GpxReader r = new GpxReader(is); 209 209 final boolean parsedProperly = r.parse(true); 210 210 data = r.data; 211 211 212 212 if (!parsedProperly) 213 213 { 214 215 } 216 } 217 catch (FileNotFoundException e) 214 JOptionPane.showMessageDialog(null, tr("Error occured while parsing gpx file {0}. Only part of the file will be available", file.getName())); 215 } 216 } 217 catch (FileNotFoundException e) 218 218 { 219 219 e.printStackTrace(); … … 241 241 while (trackIter.hasNext()) 242 242 { 243 244 245 } 246 243 GpxTrack track = trackIter.next(); 244 trackRefs.add(new TrackReference(track, this)); 245 } 246 247 247 Collections.sort(trackRefs); 248 248 249 249 Iterator< TrackReference > iter = trackRefs.iterator(); 250 250 while (iter.hasNext()) 251 252 251 tracksListModel.addElement(iter.next()); 252 253 253 waypointTM = new WaypointTableModel(this); 254 254 Iterator< WayPoint > waypointIter = data.waypoints.iterator(); 255 255 while (waypointIter.hasNext()) 256 256 { 257 258 257 WayPoint waypoint = waypointIter.next(); 258 waypointTM.addRow(waypoint); 259 259 } 260 260 dialog.setWaypointsTableModel(waypointTM); … … 265 265 (null, "The GPX file contained no tracks or waypoints.", "No data found", 266 266 JOptionPane.ERROR_MESSAGE); 267 267 268 268 System.out.println("Public Transport: StopImporter: No data found"); 269 269 } 270 270 } 271 271 272 272 public void tracksSelectionChanged(int selectedPos) 273 273 { … … 276 276 currentTrack = ((TrackReference)tracksListModel.elementAt(selectedPos)); 277 277 dialog.setTrackValid(true); 278 278 279 279 //Prepare Settings 280 280 dialog.setSettings 281 282 283 281 (currentTrack.gpsSyncTime, currentTrack.stopwatchStart, 282 currentTrack.timeWindow, currentTrack.threshold); 283 284 284 //Prepare Stoplist 285 285 dialog.setStoplistTableModel … … 297 297 return createNode(latLon, dialog.getStoptype(), name); 298 298 } 299 299 300 300 public static Node createNode(LatLon latLon, String type, String name) 301 301 { … … 306 306 { 307 307 JOptionPane.showMessageDialog(null, "There exists no dataset." 308 308 + " Try to download data from the server or open an OSM file.", 309 309 "No data found", JOptionPane.ERROR_MESSAGE); 310 310 311 311 System.out.println("Public Transport: StopInserter: No data found"); 312 312 313 313 return null; 314 314 } … … 333 333 node.put("railway", "station"); 334 334 } 335 335 336 336 /* returns a collection of all selected lines or 337 337 a collection of all lines otherwise */ … … 343 343 { 344 344 for (int i = 0; i < selectedLines.length; ++i) 345 345 consideredLines.add(selectedLines[i]); 346 346 } 347 347 else 348 348 { 349 349 for (int i = 0; i < table.getRowCount(); ++i) 350 350 consideredLines.add(new Integer(i)); 351 351 } 352 352 return consideredLines; … … 358 358 if (Main.main.getCurrentDataSet() == null) 359 359 return; 360 360 361 361 table.clearSelection(); 362 362 363 363 for (int i = 0; i < table.getRowCount(); ++i) 364 364 { 365 365 if ((nodes.elementAt(i) != null) && 366 367 368 } 369 } 370 366 (Main.main.getCurrentDataSet().isSelected(nodes.elementAt(i)))) 367 table.addRowSelectionInterval(i, i); 368 } 369 } 370 371 371 /* shows the nodes that correspond to the marked lines in the table. 372 372 If no lines are marked in the table, show all nodes from the vector */ … … 379 379 int j = consideredLines.elementAt(i); 380 380 if (nodes.elementAt(j) != null) 381 381 nodes.elementAt(j).visit(box); 382 382 } 383 383 if (box.getBounds() == null) … … 386 386 Main.map.mapView.recalculateCenterScale(box); 387 387 } 388 388 389 389 /* marks the nodes that correspond to the marked lines in the table. 390 390 If no lines are marked in the table, mark all nodes from the vector */ … … 398 398 int j = consideredLines.elementAt(i); 399 399 if (nodes.elementAt(j) != null) 400 401 } 402 } 403 400 Main.main.getCurrentDataSet().addSelected(nodes.elementAt(j)); 401 } 402 } 403 404 404 public static String timeOf(double t) 405 405 { 406 406 t -= Math.floor(t/24/60/60)*24*60*60; 407 407 408 408 int hour = (int)Math.floor(t/60/60); 409 409 t -= Math.floor(t/60/60)*60*60; … … 411 411 t -= Math.floor(t/60)*60; 412 412 double second = t; 413 413 414 414 Format format = new DecimalFormat("00"); 415 415 Format formatS = new DecimalFormat("00.###"); 416 416 return (format.format(hour) + ":" + format.format(minute) + ":" 417 418 } 419 417 + formatS.format(second)); 418 } 419 420 420 public Action getFocusWaypointNameAction() 421 421 { 422 422 return new FocusWaypointNameAction(); 423 423 } 424 424 425 425 public Action getFocusWaypointShelterAction(String shelter) 426 426 { … … 434 434 public void actionPerformed(ActionEvent e) 435 435 { 436 437 438 439 440 441 442 443 436 JTable table = dialog.getWaypointsTable(); 437 int row = table.getEditingRow(); 438 if (row < 0) 439 return; 440 table.clearSelection(); 441 table.addRowSelectionInterval(row, row); 442 Main.main.undoRedo.add 443 (new WaypointsDisableCommand(StopImporterAction.this)); 444 444 } 445 445 }; … … 450 450 return new FocusTrackStoplistNameAction(); 451 451 } 452 452 453 453 public Action getFocusTrackStoplistShelterAction(String shelter) 454 454 { … … 462 462 public void actionPerformed(ActionEvent e) 463 463 { 464 465 466 467 468 469 470 471 464 JTable table = dialog.getStoplistTable(); 465 int row = table.getEditingRow(); 466 if (row < 0) 467 return; 468 table.clearSelection(); 469 table.addRowSelectionInterval(row, row); 470 Main.main.undoRedo.add 471 (new TrackStoplistDeleteCommand(StopImporterAction.this)); 472 472 } 473 473 }; … … 483 483 int row = table.getEditingRow(); 484 484 if (row < 0) 485 485 row = 0; 486 486 waypointTM.inEvent = true; 487 487 if (table.getCellEditor() != null) 488 488 { 489 490 489 if (!table.getCellEditor().stopCellEditing()) 490 table.getCellEditor().cancelCellEditing(); 491 491 } 492 492 table.editCellAt(row, 1); 493 493 table.getCellEditor().getTableCellEditorComponent 494 494 (table, "", true, row, 1); 495 495 waypointTM.inEvent = false; 496 496 } 497 497 }; 498 498 499 499 private class FocusWaypointShelterAction extends AbstractAction 500 500 { 501 501 private String defaultShelter = null; 502 502 503 503 public FocusWaypointShelterAction(String defaultShelter) 504 504 { 505 505 this.defaultShelter = defaultShelter; 506 506 } 507 507 508 508 public void actionPerformed(ActionEvent e) 509 509 { … … 513 513 int row = table.getEditingRow(); 514 514 if (row < 0) 515 515 row = 0; 516 516 waypointTM.inEvent = true; 517 517 if (table.getCellEditor() != null) 518 518 { 519 520 519 if (!table.getCellEditor().stopCellEditing()) 520 table.getCellEditor().cancelCellEditing(); 521 521 } 522 522 table.editCellAt(row, 2); … … 526 526 } 527 527 }; 528 528 529 529 private class FocusTrackStoplistNameAction extends AbstractAction 530 530 { … … 536 536 int row = table.getEditingRow(); 537 537 if (row < 0) 538 538 row = 0; 539 539 currentTrack.inEvent = true; 540 540 if (table.getCellEditor() != null) 541 541 { 542 543 542 if (!table.getCellEditor().stopCellEditing()) 543 table.getCellEditor().cancelCellEditing(); 544 544 } 545 545 table.editCellAt(row, 1); … … 549 549 } 550 550 }; 551 551 552 552 private class FocusTrackStoplistShelterAction extends AbstractAction 553 553 { 554 554 private String defaultShelter = null; 555 555 556 556 public FocusTrackStoplistShelterAction(String defaultShelter) 557 557 { 558 558 this.defaultShelter = defaultShelter; 559 559 } 560 560 561 561 public void actionPerformed(ActionEvent e) 562 562 { … … 566 566 int row = table.getEditingRow(); 567 567 if (row < 0) 568 568 row = 0; 569 569 currentTrack.inEvent = true; 570 570 if (table.getCellEditor() != null) 571 571 { 572 573 572 if (!table.getCellEditor().stopCellEditing()) 573 table.getCellEditor().cancelCellEditing(); 574 574 } 575 575 table.editCellAt(row, 2); -
applications/editors/josm/plugins/public_transport/src/public_transport/StopImporterDialog.java
r20867 r23192 63 63 64 64 public class StopImporterDialog 65 { 65 { 66 66 private JDialog jDialog = null; 67 67 private JTabbedPane tabbedPane = null; … … 74 74 private JTable stoplistTable = null; 75 75 private JTable waypointTable = null; 76 76 77 77 public StopImporterDialog(StopImporterAction controller) 78 78 { … … 93 93 tabbedPane.setEnabledAt(3, true); 94 94 jDialog.add(tabbedPane); 95 95 96 96 //Tracks Tab 97 97 JPanel contentPane = tabTracks; … … 99 99 GridBagConstraints layoutCons = new GridBagConstraints(); 100 100 contentPane.setLayout(gridbag); 101 101 102 102 JLabel label = new JLabel("Tracks in this GPX file:"); 103 103 104 104 layoutCons.gridx = 0; 105 105 layoutCons.gridy = 0; … … 110 110 gridbag.setConstraints(label, layoutCons); 111 111 contentPane.add(label); 112 112 113 113 DefaultListModel tracksListModel = controller.getTracksListModel(); 114 114 tracksList = new JList(tracksListModel); … … 118 118 tracksList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); 119 119 tracksList.addListSelectionListener(new TracksLSL(controller)); 120 120 121 121 layoutCons.gridx = 0; 122 122 layoutCons.gridy = 1; … … 124 124 layoutCons.weightx = 1.0; 125 125 layoutCons.weighty = 1.0; 126 layoutCons.fill = GridBagConstraints.BOTH; 126 layoutCons.fill = GridBagConstraints.BOTH; 127 127 gridbag.setConstraints(rpListSP, layoutCons); 128 128 contentPane.add(rpListSP); 129 129 130 130 //Settings Tab 131 131 contentPane = tabSettings; … … 133 133 layoutCons = new GridBagConstraints(); 134 134 contentPane.setLayout(gridbag); 135 135 136 136 label = new JLabel("Type of stops to add"); 137 137 138 138 layoutCons.gridx = 0; 139 139 layoutCons.gridy = 0; … … 144 144 gridbag.setConstraints(label, layoutCons); 145 145 contentPane.add(label); 146 146 147 147 cbStoptype = new JComboBox(); 148 148 cbStoptype.setEditable(false); … … 154 154 cbStoptype.setActionCommand("stopImporter.settingsStoptype"); 155 155 cbStoptype.addActionListener(controller); 156 156 157 157 layoutCons.gridx = 0; 158 158 layoutCons.gridy = 1; … … 163 163 gridbag.setConstraints(cbStoptype, layoutCons); 164 164 contentPane.add(cbStoptype); 165 165 166 166 label = new JLabel("Time on your GPS device"); 167 167 168 168 layoutCons.gridx = 0; 169 169 layoutCons.gridy = 2; … … 174 174 gridbag.setConstraints(label, layoutCons); 175 175 contentPane.add(label); 176 176 177 177 tfGPSTimeStart = new JTextField("00:00:00", 15); 178 178 tfGPSTimeStart.setActionCommand("stopImporter.settingsGPSTimeStart"); 179 179 tfGPSTimeStart.addActionListener(controller); 180 180 181 181 layoutCons.gridx = 0; 182 182 layoutCons.gridy = 3; … … 187 187 gridbag.setConstraints(tfGPSTimeStart, layoutCons); 188 188 contentPane.add(tfGPSTimeStart); 189 189 190 190 label = new JLabel("HH:MM:SS.sss"); 191 191 192 192 layoutCons.gridx = 1; 193 193 layoutCons.gridy = 3; … … 198 198 gridbag.setConstraints(label, layoutCons); 199 199 contentPane.add(label); 200 200 201 201 label = new JLabel("Time on your stopwatch"); 202 202 203 203 layoutCons.gridx = 0; 204 204 layoutCons.gridy = 4; … … 209 209 gridbag.setConstraints(label, layoutCons); 210 210 contentPane.add(label); 211 211 212 212 tfStopwatchStart = new JTextField("00:00:00", 15); 213 213 tfStopwatchStart.setActionCommand("stopImporter.settingsStopwatchStart"); 214 214 tfStopwatchStart.addActionListener(controller); 215 215 216 216 layoutCons.gridx = 0; 217 217 layoutCons.gridy = 5; … … 222 222 gridbag.setConstraints(tfStopwatchStart, layoutCons); 223 223 contentPane.add(tfStopwatchStart); 224 224 225 225 label = new JLabel("HH:MM:SS.sss"); 226 226 227 227 layoutCons.gridx = 1; 228 228 layoutCons.gridy = 5; … … 233 233 gridbag.setConstraints(label, layoutCons); 234 234 contentPane.add(label); 235 235 236 236 label = new JLabel("Time window"); 237 237 238 238 layoutCons.gridx = 0; 239 239 layoutCons.gridy = 6; … … 244 244 gridbag.setConstraints(label, layoutCons); 245 245 contentPane.add(label); 246 246 247 247 tfTimeWindow = new JTextField("15", 4); 248 248 tfTimeWindow.setActionCommand("stopImporter.settingsTimeWindow"); 249 249 tfTimeWindow.addActionListener(controller); 250 250 251 251 layoutCons.gridx = 0; 252 252 layoutCons.gridy = 7; … … 257 257 gridbag.setConstraints(tfTimeWindow, layoutCons); 258 258 contentPane.add(tfTimeWindow); 259 259 260 260 label = new JLabel("seconds"); 261 261 262 262 layoutCons.gridx = 1; 263 263 layoutCons.gridy = 7; … … 268 268 gridbag.setConstraints(label, layoutCons); 269 269 contentPane.add(label); 270 270 271 271 label = new JLabel("Move Threshold"); 272 272 273 273 layoutCons.gridx = 0; 274 274 layoutCons.gridy = 8; … … 279 279 gridbag.setConstraints(label, layoutCons); 280 280 contentPane.add(label); 281 281 282 282 tfThreshold = new JTextField("20", 4); 283 283 tfThreshold.setActionCommand("stopImporter.settingsThreshold"); 284 284 tfThreshold.addActionListener(controller); 285 285 286 286 layoutCons.gridx = 0; 287 287 layoutCons.gridy = 9; … … 292 292 gridbag.setConstraints(tfThreshold, layoutCons); 293 293 contentPane.add(tfThreshold); 294 294 295 295 label = new JLabel("meters"); 296 296 297 297 layoutCons.gridx = 1; 298 298 layoutCons.gridy = 9; … … 303 303 gridbag.setConstraints(label, layoutCons); 304 304 contentPane.add(label); 305 305 306 306 JButton bSuggestStops = new JButton("Suggest Stops"); 307 307 bSuggestStops.setActionCommand("stopImporter.settingsSuggestStops"); 308 308 bSuggestStops.addActionListener(controller); 309 309 310 310 layoutCons.gridx = 0; 311 311 layoutCons.gridy = 10; … … 316 316 gridbag.setConstraints(bSuggestStops, layoutCons); 317 317 contentPane.add(bSuggestStops); 318 318 319 319 //Stops Tab 320 320 contentPane = tabStops; … … 325 325 (KeyStroke.getKeyStroke("alt N"), "stopImporter.focusName"); 326 326 contentPane.getActionMap().put 327 327 ("stopImporter.focusName", controller.getFocusTrackStoplistNameAction()); 328 328 contentPane.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put 329 329 (KeyStroke.getKeyStroke("alt S"), "stopImporter.focusShelterYes"); 330 330 contentPane.getActionMap().put 331 332 331 ("stopImporter.focusShelterYes", 332 controller.getFocusTrackStoplistShelterAction("yes")); 333 333 contentPane.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put 334 334 (KeyStroke.getKeyStroke("alt T"), "stopImporter.focusShelterNo"); 335 335 contentPane.getActionMap().put 336 337 336 ("stopImporter.focusShelterNo", 337 controller.getFocusTrackStoplistShelterAction("no")); 338 338 contentPane.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put 339 339 (KeyStroke.getKeyStroke("alt U"), "stopImporter.focusShelterImplicit"); 340 340 contentPane.getActionMap().put 341 342 341 ("stopImporter.focusShelterImplicit", 342 controller.getFocusTrackStoplistShelterAction("implicit")); 343 343 contentPane.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put 344 344 (KeyStroke.getKeyStroke("alt D"), "stopImporter.stoplistDelete"); 345 345 contentPane.getActionMap().put 346 347 348 346 ("stopImporter.stoplistDelete", 347 controller.getFocusStoplistDeleteAction()); 348 349 349 stoplistTable = new JTable(); 350 350 JScrollPane tableSP = new JScrollPane(stoplistTable); 351 351 352 352 layoutCons.gridx = 0; 353 353 layoutCons.gridy = 0; … … 358 358 gridbag.setConstraints(tableSP, layoutCons); 359 359 contentPane.add(tableSP); 360 360 361 361 JButton bFind = new JButton("Find"); 362 362 bFind.setActionCommand("stopImporter.stoplistFind"); 363 363 bFind.addActionListener(controller); 364 364 365 365 layoutCons.gridx = 0; 366 366 layoutCons.gridy = 1; … … 371 371 gridbag.setConstraints(bFind, layoutCons); 372 372 contentPane.add(bFind); 373 373 374 374 JButton bShow = new JButton("Show"); 375 375 bShow.setActionCommand("stopImporter.stoplistShow"); 376 376 bShow.addActionListener(controller); 377 377 378 378 layoutCons.gridx = 0; 379 379 layoutCons.gridy = 2; … … 384 384 gridbag.setConstraints(bShow, layoutCons); 385 385 contentPane.add(bShow); 386 386 387 387 JButton bMark = new JButton("Mark"); 388 388 bMark.setActionCommand("stopImporter.stoplistMark"); 389 389 bMark.addActionListener(controller); 390 390 391 391 layoutCons.gridx = 1; 392 392 layoutCons.gridy = 1; … … 398 398 gridbag.setConstraints(bMark, layoutCons); 399 399 contentPane.add(bMark); 400 400 401 401 JButton bDetach = new JButton("Detach"); 402 402 bDetach.setActionCommand("stopImporter.stoplistDetach"); 403 403 bDetach.addActionListener(controller); 404 404 405 405 layoutCons.gridx = 1; 406 406 layoutCons.gridy = 2; … … 412 412 gridbag.setConstraints(bDetach, layoutCons); 413 413 contentPane.add(bDetach); 414 414 415 415 JButton bAdd = new JButton("Add"); 416 416 bAdd.setActionCommand("stopImporter.stoplistAdd"); 417 417 bAdd.addActionListener(controller); 418 418 419 419 layoutCons.gridx = 2; 420 420 layoutCons.gridy = 1; … … 426 426 gridbag.setConstraints(bAdd, layoutCons); 427 427 contentPane.add(bAdd); 428 428 429 429 JButton bDelete = new JButton("Delete"); 430 430 bDelete.setActionCommand("stopImporter.stoplistDelete"); 431 431 bDelete.addActionListener(controller); 432 432 433 433 layoutCons.gridx = 2; 434 434 layoutCons.gridy = 2; … … 439 439 gridbag.setConstraints(bDelete, layoutCons); 440 440 contentPane.add(bDelete); 441 441 442 442 JButton bSort = new JButton("Sort"); 443 443 bSort.setActionCommand("stopImporter.stoplistSort"); 444 444 bSort.addActionListener(controller); 445 445 446 446 layoutCons.gridx = 3; 447 447 layoutCons.gridy = 1; … … 453 453 gridbag.setConstraints(bSort, layoutCons); 454 454 contentPane.add(bSort); 455 455 456 456 //Waypoints Tab 457 457 contentPane = tabWaypoints; … … 462 462 (KeyStroke.getKeyStroke("alt N"), "stopImporter.focusName"); 463 463 contentPane.getActionMap().put 464 464 ("stopImporter.focusName", controller.getFocusWaypointNameAction()); 465 465 contentPane.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put 466 466 (KeyStroke.getKeyStroke("alt S"), "stopImporter.focusShelterYes"); 467 467 contentPane.getActionMap().put 468 469 468 ("stopImporter.focusShelterYes", 469 controller.getFocusWaypointShelterAction("yes")); 470 470 contentPane.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put 471 471 (KeyStroke.getKeyStroke("alt T"), "stopImporter.focusShelterNo"); 472 472 contentPane.getActionMap().put 473 474 473 ("stopImporter.focusShelterNo", 474 controller.getFocusWaypointShelterAction("no")); 475 475 contentPane.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put 476 476 (KeyStroke.getKeyStroke("alt U"), "stopImporter.focusShelterImplicit"); 477 477 contentPane.getActionMap().put 478 479 478 ("stopImporter.focusShelterImplicit", 479 controller.getFocusWaypointShelterAction("implicit")); 480 480 contentPane.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put 481 481 (KeyStroke.getKeyStroke("alt D"), "stopImporter.waypointsDelete"); 482 482 contentPane.getActionMap().put 483 484 485 483 ("stopImporter.waypointsDelete", 484 controller.getFocusWaypointDeleteAction()); 485 486 486 waypointTable = new JTable(); 487 487 tableSP = new JScrollPane(waypointTable); 488 488 489 489 layoutCons.gridx = 0; 490 490 layoutCons.gridy = 0; … … 495 495 gridbag.setConstraints(tableSP, layoutCons); 496 496 contentPane.add(tableSP); 497 497 498 498 bFind = new JButton("Find"); 499 499 bFind.setActionCommand("stopImporter.waypointsFind"); 500 500 bFind.addActionListener(controller); 501 501 502 502 layoutCons.gridx = 0; 503 503 layoutCons.gridy = 1; … … 508 508 gridbag.setConstraints(bFind, layoutCons); 509 509 contentPane.add(bFind); 510 510 511 511 bShow = new JButton("Show"); 512 512 bShow.setActionCommand("stopImporter.waypointsShow"); 513 513 bShow.addActionListener(controller); 514 514 515 515 layoutCons.gridx = 0; 516 516 layoutCons.gridy = 2; … … 521 521 gridbag.setConstraints(bShow, layoutCons); 522 522 contentPane.add(bShow); 523 523 524 524 bMark = new JButton("Mark"); 525 525 bMark.setActionCommand("stopImporter.waypointsMark"); 526 526 bMark.addActionListener(controller); 527 527 528 528 layoutCons.gridx = 1; 529 529 layoutCons.gridy = 1; … … 535 535 gridbag.setConstraints(bMark, layoutCons); 536 536 contentPane.add(bMark); 537 537 538 538 bDetach = new JButton("Detach"); 539 539 bDetach.setActionCommand("stopImporter.waypointsDetach"); 540 540 bDetach.addActionListener(controller); 541 541 542 542 layoutCons.gridx = 1; 543 543 layoutCons.gridy = 2; … … 549 549 gridbag.setConstraints(bDetach, layoutCons); 550 550 contentPane.add(bDetach); 551 551 552 552 bAdd = new JButton("Enable"); 553 553 bAdd.setActionCommand("stopImporter.waypointsAdd"); 554 554 bAdd.addActionListener(controller); 555 555 556 556 layoutCons.gridx = 2; 557 557 layoutCons.gridy = 1; … … 563 563 gridbag.setConstraints(bAdd, layoutCons); 564 564 contentPane.add(bAdd); 565 565 566 566 bDelete = new JButton("Disable"); 567 567 bDelete.setActionCommand("stopImporter.waypointsDelete"); 568 568 bDelete.addActionListener(controller); 569 569 570 570 layoutCons.gridx = 2; 571 571 layoutCons.gridy = 2; … … 576 576 gridbag.setConstraints(bDelete, layoutCons); 577 577 contentPane.add(bDelete); 578 578 579 579 jDialog.pack(); 580 580 jDialog.setLocationRelativeTo(frame); 581 581 } 582 582 583 583 public void setTrackValid(boolean valid) 584 584 { 585 585 tabbedPane.setEnabledAt(2, valid); 586 586 } 587 587 588 588 public void setVisible(boolean visible) 589 589 { 590 590 jDialog.setVisible(visible); 591 591 } 592 592 593 593 public void setSettings 594 594 (String gpsSyncTime, String stopwatchStart, … … 600 600 tfThreshold.setText(Double.toString(threshold)); 601 601 } 602 602 603 603 public String getStoptype() 604 604 { 605 605 return (String)cbStoptype.getSelectedItem(); 606 606 } 607 607 608 608 public boolean gpsTimeStartValid() 609 609 { … … 615 615 { 616 616 JOptionPane.showMessageDialog 617 618 617 (null, "Can't parse a time from this string.", "Invalid value", 618 JOptionPane.ERROR_MESSAGE); 619 619 return false; 620 620 } 621 621 } 622 622 623 623 public String getGpsTimeStart() 624 624 { 625 625 return tfGPSTimeStart.getText(); 626 626 } 627 627 628 628 public void setGpsTimeStart(String s) 629 629 { 630 630 tfGPSTimeStart.setText(s); 631 631 } 632 632 633 633 public boolean stopwatchStartValid() 634 634 { … … 640 640 { 641 641 JOptionPane.showMessageDialog 642 643 642 (null, "Can't parse a time from this string.", "Invalid value", 643 JOptionPane.ERROR_MESSAGE); 644 644 return false; 645 645 } 646 646 } 647 647 648 648 public String getStopwatchStart() 649 649 { 650 650 return tfStopwatchStart.getText(); 651 651 } 652 652 653 653 public void setStopwatchStart(String s) 654 654 { 655 655 tfStopwatchStart.setText(s); 656 656 } 657 657 658 658 public double getTimeWindow() 659 659 { 660 660 return Double.parseDouble(tfTimeWindow.getText()); 661 661 } 662 662 663 663 public double getThreshold() 664 664 { 665 665 return Double.parseDouble(tfThreshold.getText()); 666 666 } 667 667 668 668 public JTable getStoplistTable() 669 669 { 670 670 return stoplistTable; 671 671 } 672 672 673 673 public void setStoplistTableModel(TrackStoplistTableModel model) 674 674 { … … 680 680 comboBox.addItem("implicit"); 681 681 stoplistTable.getColumnModel().getColumn(2) 682 682 .setCellEditor(new DefaultCellEditor(comboBox)); 683 683 int width = stoplistTable.getPreferredSize().width; 684 684 stoplistTable.getColumnModel().getColumn(0).setPreferredWidth((int)(width * 0.4)); … … 686 686 stoplistTable.getColumnModel().getColumn(2).setPreferredWidth((int)(width * 0.1)); 687 687 } 688 688 689 689 public JTable getWaypointsTable() 690 690 { 691 691 return waypointTable; 692 692 } 693 693 694 694 public void setWaypointsTableModel(WaypointTableModel model) 695 695 { … … 701 701 comboBox.addItem("implicit"); 702 702 waypointTable.getColumnModel().getColumn(2) 703 703 .setCellEditor(new DefaultCellEditor(comboBox)); 704 704 int width = waypointTable.getPreferredSize().width; 705 705 waypointTable.getColumnModel().getColumn(0).setPreferredWidth((int)(width * 0.4)); … … 707 707 waypointTable.getColumnModel().getColumn(2).setPreferredWidth((int)(width * 0.1)); 708 708 } 709 709 710 710 public static double parseTime(String s) 711 711 { 712 712 double result = 0; 713 713 if ((s.charAt(2) != ':') || (s.charAt(2) != ':') 714 714 || (s.length() < 8)) 715 715 return -1; 716 716 int hour = Integer.parseInt(s.substring(0, 2)); … … 718 718 double second = Double.parseDouble(s.substring(6, s.length())); 719 719 if ((hour < 0) || (hour > 23) || (minute < 0) || (minute > 59) 720 720 || (second < 0) || (second >= 60.0)) 721 721 return -1; 722 722 return (second + minute*60 + hour*60*60); 723 723 } 724 724 725 725 private class TracksLSL implements ListSelectionListener 726 726 { 727 727 StopImporterAction root = null; 728 728 729 729 public TracksLSL(StopImporterAction sia) 730 730 { 731 731 root = sia; 732 732 } 733 733 734 734 public void valueChanged(ListSelectionEvent e) 735 735 { 736 736 int selectedPos = tracksList.getAnchorSelectionIndex(); 737 737 if (tracksList.isSelectedIndex(selectedPos)) 738 738 root.tracksSelectionChanged(selectedPos); 739 739 else 740 740 root.tracksSelectionChanged(-1); 741 741 } 742 742 }; -
applications/editors/josm/plugins/public_transport/src/public_transport/TrackReference.java
r20839 r23192 32 32 private StopImporterAction controller = null; 33 33 public boolean inEvent = false; 34 34 35 35 public TrackReference(GpxTrack track, StopImporterAction controller) 36 36 { … … 46 46 while ((siter.hasNext()) && (this.gpsSyncTime == null)) 47 47 { 48 49 50 51 52 53 54 48 Iterator< WayPoint > witer = siter.next().getWayPoints().iterator(); 49 if (witer.hasNext()) 50 { 51 this.gpsStartTime = witer.next().getString("time"); 52 if (this.gpsStartTime != null) 53 this.gpsSyncTime = this.gpsStartTime.substring(11, 19); 54 } 55 55 } 56 56 if (this.gpsSyncTime == null) 57 57 { 58 59 60 58 JOptionPane.showMessageDialog 59 (null, "The GPX file doesn't contain valid trackpoints. " 60 + "Please use a GPX file that has trackpoints.", "GPX File Trouble", 61 61 JOptionPane.ERROR_MESSAGE); 62 63 64 62 63 this.gpsStartTime = "1970-01-01T00:00:00Z"; 64 this.gpsSyncTime = this.stopwatchStart; 65 65 } 66 66 } … … 70 70 this.threshold = 20; 71 71 } 72 72 73 73 public GpxTrack getGpxTrack() 74 74 { 75 75 return track; 76 76 } 77 77 78 78 public int compareTo(TrackReference tr) 79 79 { … … 83 83 { 84 84 if (tr_name == null) 85 85 return -1; 86 86 return name.compareTo(tr_name); 87 87 } 88 88 return 1; 89 89 } 90 90 91 91 public String toString() 92 92 { … … 96 96 return buf; 97 97 } 98 98 99 99 public void tableChanged(TableModelEvent e) 100 100 { … … 102 102 { 103 103 if (inEvent) 104 105 104 return; 105 106 106 double time = StopImporterDialog.parseTime 107 107 ((String)stoplistTM.getValueAt(e.getFirstRow(), 0)); 108 108 if (time < 0) 109 109 { 110 111 112 113 114 115 110 stoplistTM.setValueAt 111 (stoplistTM.timeAt(e.getFirstRow()), e.getFirstRow(), 0); 112 JOptionPane.showMessageDialog 113 (null, "Can't parse a time from this string.", "Invalid value", 114 JOptionPane.ERROR_MESSAGE); 115 return; 116 116 } 117 117 … … 119 119 (this, e.getFirstRow())); 120 120 stoplistTM.setTimeAt 121 121 (e.getFirstRow(), (String)stoplistTM.getValueAt(e.getFirstRow(), 0)); 122 122 } 123 123 } 124 124 125 125 public LatLon computeCoor(double time) 126 126 { … … 131 131 double timeDelta = gpsSyncTime - StopImporterDialog.parseTime(stopwatchStart); 132 132 time += timeDelta; 133 133 134 134 WayPoint wayPoint = null; 135 135 WayPoint lastWayPoint = null; … … 142 142 while (witer.hasNext()) 143 143 { 144 145 146 147 148 149 150 151 152 144 wayPoint = witer.next(); 145 String startTime = wayPoint.getString("time"); 146 wayPointTime = StopImporterDialog.parseTime(startTime.substring(11, 19)); 147 if (startTime.substring(11, 19).compareTo(gpsStartTime.substring(11, 19)) == -1) 148 wayPointTime += 24*60*60; 149 if (wayPointTime >= time) 150 break; 151 lastWayPoint = wayPoint; 152 lastWayPointTime = wayPointTime; 153 153 } 154 154 if (wayPointTime >= time) 155 155 break; 156 156 } 157 157 158 158 double lat = 0; 159 159 if ((wayPointTime == lastWayPointTime) || (lastWayPoint == null)) … … 161 161 else 162 162 lat = wayPoint.getCoor().lat() 163 164 165 163 *(time - lastWayPointTime)/(wayPointTime - lastWayPointTime) 164 + lastWayPoint.getCoor().lat() 165 *(wayPointTime - time)/(wayPointTime - lastWayPointTime); 166 166 double lon = 0; 167 167 if ((wayPointTime == lastWayPointTime) || (lastWayPoint == null)) … … 169 169 else 170 170 lon = wayPoint.getCoor().lon() 171 172 173 174 171 *(time - lastWayPointTime)/(wayPointTime - lastWayPointTime) 172 + lastWayPoint.getCoor().lon() 173 *(wayPointTime - time)/(wayPointTime - lastWayPointTime); 174 175 175 return new LatLon(lat, lon); 176 176 } 177 177 178 178 public void relocateNodes() 179 179 { … … 182 182 Node node = stoplistTM.nodeAt(i); 183 183 if (node == null) 184 185 184 continue; 185 186 186 double time = StopImporterDialog.parseTime 187 187 ((String)stoplistTM.getValueAt(i, 0)); 188 188 LatLon latLon = computeCoor(time); 189 189 … … 193 193 if (cmd != null) 194 194 { 195 195 Main.main.undoRedo.add(cmd); 196 196 } 197 197 } -
applications/editors/josm/plugins/public_transport/src/public_transport/TrackStoplistAddCommand.java
r22048 r23192 14 14 private int workingLine; 15 15 private TrackStoplistTableModel stoplistTM = null; 16 16 17 17 public TrackStoplistAddCommand(StopImporterAction controller) 18 18 { … … 20 20 workingLine = controller.getDialog().getStoplistTable().getSelectedRow(); 21 21 } 22 22 23 23 public boolean executeCommand() 24 24 { … … 26 26 return true; 27 27 } 28 28 29 29 public void undoCommand() 30 30 { … … 34 34 stoplistTM.removeRow(workingLine); 35 35 } 36 36 37 37 public void fillModifiedData 38 38 (Collection< OsmPrimitive > modified, Collection< OsmPrimitive > deleted, … … 40 40 { 41 41 } 42 42 43 43 @Override public JLabel getDescription() 44 44 { -
applications/editors/josm/plugins/public_transport/src/public_transport/TrackStoplistDeleteCommand.java
r22048 r23192 21 21 this.shelter = shelter; 22 22 } 23 23 24 24 public Node node; 25 25 public String time; … … 27 27 public String shelter; 28 28 }; 29 29 30 30 private Vector< Integer > workingLines = null; 31 31 private Vector< NodeTimeName > nodesForUndo = null; 32 32 private TrackStoplistTableModel stoplistTM = null; 33 33 34 34 public TrackStoplistDeleteCommand(StopImporterAction controller) 35 35 { … … 37 37 workingLines = new Vector< Integer >(); 38 38 nodesForUndo = new Vector< NodeTimeName >(); 39 39 40 40 // use selected lines or all lines if no line is selected 41 41 int[] selectedLines = controller.getDialog().getStoplistTable().getSelectedRows(); … … 44 44 for (int i = 0; i < selectedLines.length; ++i) 45 45 { 46 46 workingLines.add(selectedLines[i]); 47 47 } 48 48 } … … 50 50 { 51 51 for (int i = 0; i < stoplistTM.getRowCount(); ++i) 52 52 workingLines.add(new Integer(i)); 53 53 } 54 54 } 55 55 56 56 public boolean executeCommand() 57 57 { … … 62 62 Node node = stoplistTM.nodeAt(j); 63 63 nodesForUndo.add(new NodeTimeName 64 65 66 64 (node, (String)stoplistTM.getValueAt(j, 0), 65 (String)stoplistTM.getValueAt(j, 1), 66 (String)stoplistTM.getValueAt(j, 2))); 67 67 stoplistTM.removeRow(j); 68 68 if (node == null) 69 69 continue; 70 70 Main.main.getCurrentDataSet().removePrimitive(node); 71 71 node.setDeleted(true); … … 73 73 return true; 74 74 } 75 75 76 76 public void undoCommand() 77 77 { … … 82 82 stoplistTM.insertRow(j, ntn.node, ntn.time, ntn.name, ntn.shelter); 83 83 if (ntn.node == null) 84 84 continue; 85 85 ntn.node.setDeleted(false); 86 86 Main.main.getCurrentDataSet().addPrimitive(ntn.node); 87 87 } 88 88 } 89 89 90 90 public void fillModifiedData 91 91 (Collection< OsmPrimitive > modified, Collection< OsmPrimitive > deleted, … … 93 93 { 94 94 } 95 95 96 96 @Override public JLabel getDescription() 97 97 { -
applications/editors/josm/plugins/public_transport/src/public_transport/TrackStoplistDetachCommand.java
r22048 r23192 15 15 private Vector< Node > nodesForUndo = null; 16 16 private TrackStoplistTableModel stoplistTM = null; 17 17 18 18 public TrackStoplistDetachCommand(StopImporterAction controller) 19 19 { … … 21 21 workingLines = new Vector< Integer >(); 22 22 nodesForUndo = new Vector< Node >(); 23 23 24 24 // use either selected lines or all lines if no line is selected 25 25 int[] selectedLines = controller.getDialog().getStoplistTable().getSelectedRows(); … … 28 28 { 29 29 for (int i = 0; i < selectedLines.length; ++i) 30 30 consideredLines.add(selectedLines[i]); 31 31 } 32 32 else 33 33 { 34 34 for (int i = 0; i < stoplistTM.getRowCount(); ++i) 35 35 consideredLines.add(new Integer(i)); 36 36 } 37 37 38 38 // keep only lines where a node can be added 39 39 for (int i = 0; i < consideredLines.size(); ++i) 40 40 { 41 41 if (stoplistTM.nodeAt(consideredLines.elementAt(i)) != null) 42 42 workingLines.add(consideredLines.elementAt(i)); 43 43 } 44 44 } 45 45 46 46 public boolean executeCommand() 47 47 { … … 56 56 return true; 57 57 } 58 58 59 59 public void undoCommand() 60 60 { … … 66 66 } 67 67 } 68 68 69 69 public void fillModifiedData 70 70 (Collection< OsmPrimitive > modified, Collection< OsmPrimitive > deleted, … … 72 72 { 73 73 } 74 74 75 75 @Override public JLabel getDescription() 76 76 { -
applications/editors/josm/plugins/public_transport/src/public_transport/TrackStoplistNameCommand.java
r22048 r23192 22 22 private String shelter = null; 23 23 private LatLon oldLatLon = null; 24 24 25 25 @SuppressWarnings("unchecked") 26 26 public TrackStoplistNameCommand(TrackReference trackref, int workingLine) … … 42 42 this.shelter = null; 43 43 } 44 44 45 45 public boolean executeCommand() 46 46 { … … 69 69 return true; 70 70 } 71 71 72 72 public void undoCommand() 73 73 { … … 94 94 trackref.inEvent = false; 95 95 } 96 96 97 97 public void fillModifiedData 98 98 (Collection< OsmPrimitive > modified, Collection< OsmPrimitive > deleted, … … 100 100 { 101 101 } 102 102 103 103 @Override public JLabel getDescription() 104 104 { -
applications/editors/josm/plugins/public_transport/src/public_transport/TrackStoplistRelocateCommand.java
r22048 r23192 21 21 private String gpsSyncTime = null; 22 22 private String stopwatchStart = null; 23 23 24 24 public TrackStoplistRelocateCommand(StopImporterAction controller) 25 25 { … … 31 31 this.oldStopwatchStart = currentTrack.stopwatchStart; 32 32 } 33 33 34 34 public boolean executeCommand() 35 35 { … … 40 40 Node node = currentTrack.stoplistTM.nodeAt(i); 41 41 if (node == null) 42 43 42 continue; 43 44 44 double time = StopImporterDialog.parseTime 45 45 ((String)currentTrack.stoplistTM.getValueAt(i, 0)); 46 46 node.setCoor(currentTrack.computeCoor(time)); 47 47 } … … 53 53 controller.inEvent = false; 54 54 } 55 55 56 56 return true; 57 57 } 58 58 59 59 public void undoCommand() 60 60 { … … 65 65 Node node = currentTrack.stoplistTM.nodeAt(i); 66 66 if (node == null) 67 68 67 continue; 68 69 69 double time = StopImporterDialog.parseTime 70 70 ((String)currentTrack.stoplistTM.getValueAt(i, 0)); 71 71 node.setCoor(currentTrack.computeCoor(time)); 72 72 } … … 79 79 } 80 80 } 81 81 82 82 public void fillModifiedData 83 83 (Collection< OsmPrimitive > modified, Collection< OsmPrimitive > deleted, … … 85 85 { 86 86 } 87 87 88 88 @Override public JLabel getDescription() 89 89 { -
applications/editors/josm/plugins/public_transport/src/public_transport/TrackStoplistSortCommand.java
r22048 r23192 22 22 private int insPos; 23 23 private String stopwatchStart; 24 24 25 25 public TrackStoplistSortCommand(StopImporterAction controller) 26 26 { … … 29 29 insPos = controller.getDialog().getStoplistTable().getSelectedRow(); 30 30 stopwatchStart = controller.getCurrentTrack().stopwatchStart; 31 31 32 32 // use either selected lines or all lines if no line is selected 33 33 int[] selectedLines = controller.getDialog().getStoplistTable().getSelectedRows(); … … 35 35 { 36 36 for (int i = 0; i < selectedLines.length; ++i) 37 37 workingLines.add(selectedLines[i]); 38 38 } 39 39 else 40 40 { 41 41 for (int i = 0; i < stoplistTM.getRowCount(); ++i) 42 42 workingLines.add(new Integer(i)); 43 43 } 44 44 } 45 45 46 46 @SuppressWarnings("unchecked") 47 47 public boolean executeCommand() 48 48 { 49 49 tableDataModel = (Vector< Vector< Object > >)stoplistTM.getDataVector() 50 50 .clone(); 51 51 nodes = (Vector< Node >)stoplistTM.getNodes().clone(); 52 52 times = (Vector< String >)stoplistTM.getTimes().clone(); 53 53 54 54 Vector< NodeSortEntry > nodesToSort = new Vector< NodeSortEntry >(); 55 55 for (int i = workingLines.size()-1; i >= 0; --i) … … 57 57 int j = workingLines.elementAt(i).intValue(); 58 58 nodesToSort.add(new NodeSortEntry 59 60 61 62 59 (stoplistTM.nodeAt(j), (String)stoplistTM.getValueAt(j, 0), 60 (String)stoplistTM.getValueAt(j, 1), 61 (String)stoplistTM.getValueAt(j, 2), 62 StopImporterDialog.parseTime(stopwatchStart))); 63 63 stoplistTM.removeRow(j); 64 64 } 65 65 66 66 Collections.sort(nodesToSort); 67 67 68 68 int insPos = this.insPos; 69 69 Iterator< NodeSortEntry > iter = nodesToSort.iterator(); … … 73 73 stoplistTM.insertRow(insPos, nse.node, nse.time, nse.name, nse.shelter); 74 74 if (insPos >= 0) 75 75 ++insPos; 76 76 } 77 77 return true; 78 78 } 79 79 80 80 public void undoCommand() 81 81 { … … 84 84 stoplistTM.setTimes(times); 85 85 } 86 86 87 87 public void fillModifiedData 88 88 (Collection< OsmPrimitive > modified, Collection< OsmPrimitive > deleted, … … 90 90 { 91 91 } 92 92 93 93 @Override public JLabel getDescription() 94 94 { 95 95 return new JLabel("public_transport.TrackStoplist.Sort"); 96 96 } 97 97 98 98 private class NodeSortEntry implements Comparable< NodeSortEntry > 99 99 { … … 103 103 public String shelter = null; 104 104 public double startTime = 0; 105 105 106 106 public NodeSortEntry 107 107 (Node node, String time, String name, String shelter, double startTime) … … 112 112 this.shelter = shelter; 113 113 } 114 114 115 115 public int compareTo(NodeSortEntry nse) 116 116 { 117 117 double time = StopImporterDialog.parseTime(this.time); 118 118 if (time - startTime > 12*60*60) 119 120 119 time -= 24*60*60; 120 121 121 double nseTime = StopImporterDialog.parseTime(nse.time); 122 122 if (nseTime - startTime > 12*60*60) 123 124 123 nseTime -= 24*60*60; 124 125 125 if (time < nseTime) 126 126 return -1; 127 127 else if (time > nseTime) 128 128 return 1; 129 129 else 130 130 return 0; 131 131 } 132 132 }; -
applications/editors/josm/plugins/public_transport/src/public_transport/TrackStoplistTableModel.java
r20839 r23192 14 14 private Vector< String > times = null; 15 15 private static Vector< String > columns = null; 16 16 17 17 public TrackStoplistTableModel(TrackReference tr) 18 18 { … … 26 26 nodes = new Vector< Node >(); 27 27 times = new Vector< String >(); 28 28 29 29 setColumnIdentifiers(columns); 30 30 addTableModelListener(tr); 31 31 } 32 32 33 33 public boolean isCellEditable(int row, int column) { 34 34 return true; 35 35 } 36 36 37 37 public void addRow(Object[] obj) { 38 38 throw new UnsupportedOperationException(); 39 39 } 40 40 41 41 public void insertRow(int insPos, Object[] obj) { 42 42 throw new UnsupportedOperationException(); 43 43 } 44 44 45 45 public void addRow(String time) { 46 46 insertRow(-1, time); 47 47 } 48 48 49 49 public void insertRow(int insPos, String time) 50 50 { … … 118 118 } 119 119 } 120 120 121 121 public void clear() 122 122 { … … 125 125 super.setRowCount(0); 126 126 } 127 127 128 128 public void setDataVector(Vector< Vector< Object > > dataVector) 129 129 { -
applications/editors/josm/plugins/public_transport/src/public_transport/TrackSuggestStopsCommand.java
r22048 r23192 29 29 private Vector< Node > nodes = null; 30 30 private Vector< String > times = null; 31 31 32 32 public TrackSuggestStopsCommand(StopImporterAction controller) 33 33 { … … 43 43 segments = controller.getCurrentTrack().getGpxTrack().getSegments(); 44 44 } 45 45 46 46 @SuppressWarnings("unchecked") 47 47 public boolean executeCommand() … … 50 50 return false; 51 51 tableDataModel = (Vector< Vector< Object > >)stoplistTM.getDataVector() 52 52 .clone(); 53 53 nodes = (Vector< Node >)stoplistTM.getNodes().clone(); 54 54 times = (Vector< String >)stoplistTM.getTimes().clone(); 55 55 56 56 for (int i = 0; i < stoplistTM.getNodes().size(); ++i) 57 57 { 58 58 Node node = stoplistTM.nodeAt(i); 59 59 if (node == null) 60 60 continue; 61 61 Main.main.getCurrentDataSet().removePrimitive(node); 62 62 node.setDeleted(true); … … 70 70 Iterator< WayPoint > witer = siter.next().getWayPoints().iterator(); 71 71 while (witer.hasNext()) 72 72 wayPoints.add(witer.next()); 73 73 } 74 74 Vector< Double > wayPointsDist = new Vector< Double >(wayPoints.size()); 75 75 76 76 int i = 0; 77 77 double time = -48*60*60; … … 80 80 { 81 81 if (wayPoints.elementAt(i).getString("time") != null) 82 83 82 time = StopImporterDialog.parseTime(wayPoints.elementAt(i) 83 .getString("time").substring(11,19)); 84 84 if (time < dGpsStartTime) 85 85 time += 24*60*60; 86 86 wayPointsDist.add(Double.valueOf(Double.POSITIVE_INFINITY)); 87 87 ++i; … … 93 93 while ((j > 0) && (time - timeWindow/2 < time2)) 94 94 { 95 96 97 98 99 100 95 --j; 96 if (wayPoints.elementAt(j).getString("time") != null) 97 time2 = StopImporterDialog.parseTime(wayPoints.elementAt(j) 98 .getString("time").substring(11,19)); 99 if (time2 < dGpsStartTime) 100 time2 += 24*60*60; 101 101 } 102 102 int k = i + 1; … … 104 104 while ((k < wayPoints.size()) && (time + timeWindow/2 > time2)) 105 105 { 106 107 108 109 110 111 112 } 113 106 if (wayPoints.elementAt(k).getString("time") != null) 107 time2 = StopImporterDialog.parseTime(wayPoints.elementAt(k) 108 .getString("time").substring(11,19)); 109 if (time2 < dGpsStartTime) 110 time2 += 24*60*60; 111 ++k; 112 } 113 114 114 if (j < k) 115 115 { 116 117 118 119 120 121 122 123 124 116 double dist = 0; 117 LatLon latLonI = wayPoints.elementAt(i).getCoor(); 118 for (int l = j; l < k; ++l) 119 { 120 double distL = latLonI.greatCircleDistance(wayPoints.elementAt(l).getCoor()); 121 if (distL > dist) 122 dist = distL; 123 } 124 wayPointsDist.add(Double.valueOf(dist)); 125 125 } 126 126 else 127 128 127 wayPointsDist.add(Double.valueOf(Double.POSITIVE_INFINITY)); 128 129 129 if (wayPoints.elementAt(i).getString("time") != null) 130 131 130 time = StopImporterDialog.parseTime(wayPoints.elementAt(i) 131 .getString("time").substring(11,19)); 132 132 if (time < dGpsStartTime) 133 133 time += 24*60*60; 134 134 ++i; 135 135 } 136 136 137 137 LatLon lastStopCoor = null; 138 138 for (i = 1; i < wayPoints.size()-1; ++i) 139 139 { 140 140 if (wayPointsDist.elementAt(i).doubleValue() >= threshold) 141 141 continue; 142 142 if ((wayPointsDist.elementAt(i).compareTo(wayPointsDist.elementAt(i-1)) != -1) 143 144 145 143 || (wayPointsDist.elementAt(i).compareTo(wayPointsDist.elementAt(i+1)) != -1)) 144 continue; 145 146 146 LatLon latLon = wayPoints.elementAt(i).getCoor(); 147 147 if ((lastStopCoor != null) && (lastStopCoor.greatCircleDistance(latLon) < threshold)) 148 149 148 continue; 149 150 150 if (wayPoints.elementAt(i).getString("time") != null) 151 151 { 152 153 154 155 156 157 158 159 160 161 } 162 152 time = StopImporterDialog.parseTime(wayPoints.elementAt(i) 153 .getString("time").substring(11,19)); 154 double gpsSyncTime = StopImporterDialog.parseTime(this.gpsSyncTime); 155 if (gpsSyncTime < dGpsStartTime - 12*60*60) 156 gpsSyncTime += 24*60*60; 157 double timeDelta = gpsSyncTime - StopImporterDialog.parseTime(stopwatchStart); 158 time -= timeDelta; 159 Node node = StopImporterAction.createNode(latLon, type, ""); 160 stoplistTM.insertRow(-1, node, StopImporterAction.timeOf(time), "", ""); 161 } 162 163 163 lastStopCoor = latLon; 164 164 } 165 165 166 166 return true; 167 167 } 168 168 169 169 public void undoCommand() 170 170 { … … 175 175 Node node = stoplistTM.nodeAt(i); 176 176 if (node == null) 177 177 continue; 178 178 Main.main.getCurrentDataSet().removePrimitive(node); 179 179 node.setDeleted(true); 180 180 } 181 181 182 182 stoplistTM.setDataVector(tableDataModel); 183 183 stoplistTM.setNodes(nodes); 184 184 stoplistTM.setTimes(times); 185 185 186 186 for (int i = 0; i < stoplistTM.getNodes().size(); ++i) 187 187 { 188 188 Node node = stoplistTM.nodeAt(i); 189 189 if (node == null) 190 190 continue; 191 191 node.setDeleted(false); 192 192 Main.main.getCurrentDataSet().addPrimitive(node); 193 193 } 194 194 } 195 195 196 196 public void fillModifiedData 197 197 (Collection< OsmPrimitive > modified, Collection< OsmPrimitive > deleted, … … 199 199 { 200 200 } 201 201 202 202 @Override public JLabel getDescription() 203 203 { 204 204 return new JLabel("public_transport.TrackStoplist.SuggestStops"); 205 205 } 206 206 207 207 private class NodeSortEntry implements Comparable< NodeSortEntry > 208 208 { … … 211 211 public String name = null; 212 212 public double startTime = 0; 213 213 214 214 public NodeSortEntry(Node node, String time, String name, double startTime) 215 215 { … … 218 218 this.name = name; 219 219 } 220 220 221 221 public int compareTo(NodeSortEntry nse) 222 222 { 223 223 double time = StopImporterDialog.parseTime(this.time); 224 224 if (time - startTime > 12*60*60) 225 226 225 time -= 24*60*60; 226 227 227 double nseTime = StopImporterDialog.parseTime(nse.time); 228 228 if (nseTime - startTime > 12*60*60) 229 230 229 nseTime -= 24*60*60; 230 231 231 if (time < nseTime) 232 232 return -1; 233 233 else if (time > nseTime) 234 234 return 1; 235 235 else 236 236 return 0; 237 237 } 238 238 }; -
applications/editors/josm/plugins/public_transport/src/public_transport/WaypointTableModel.java
r20835 r23192 21 21 public Vector< Node > nodes = new Vector< Node >(); 22 22 public Vector< LatLon > coors = new Vector< LatLon >(); 23 23 24 24 public WaypointTableModel(StopImporterAction controller) 25 25 { … … 30 30 addTableModelListener(this); 31 31 } 32 32 33 33 public boolean isCellEditable(int row, int column) 34 34 { … … 37 37 return false; 38 38 } 39 39 40 40 public void addRow(Object[] obj) 41 41 { 42 42 throw new UnsupportedOperationException(); 43 43 } 44 44 45 45 public void insertRow(int insPos, Object[] obj) 46 46 { 47 47 throw new UnsupportedOperationException(); 48 48 } 49 49 50 50 public void addRow(WayPoint wp) 51 51 { 52 52 insertRow(-1, wp); 53 53 } 54 54 55 55 public void insertRow(int insPos, WayPoint wp) 56 56 { … … 64 64 65 65 Node node = controller.createNode(wp.getCoor(), buf[1]); 66 66 67 67 if (insPos == -1) 68 68 { … … 78 78 } 79 79 } 80 80 81 81 public void clear() 82 82 { … … 84 84 super.setRowCount(0); 85 85 } 86 86 87 87 public void tableChanged(TableModelEvent e) 88 88 { … … 90 90 { 91 91 if (inEvent) 92 92 return; 93 93 Main.main.undoRedo.add(new WaypointsNameCommand 94 95 94 (this, e.getFirstRow(), (String)getValueAt(e.getFirstRow(), 1), 95 (String)getValueAt(e.getFirstRow(), 2))); 96 96 } 97 97 } -
applications/editors/josm/plugins/public_transport/src/public_transport/WaypointsDetachCommand.java
r22048 r23192 15 15 private Vector< Node > nodesForUndo = null; 16 16 private WaypointTableModel waypointTM = null; 17 17 18 18 public WaypointsDetachCommand(StopImporterAction controller) 19 19 { … … 21 21 workingLines = new Vector< Integer >(); 22 22 nodesForUndo = new Vector< Node >(); 23 23 24 24 // use either selected lines or all lines if no line is selected 25 25 int[] selectedLines = controller.getDialog().getWaypointsTable().getSelectedRows(); … … 28 28 { 29 29 for (int i = 0; i < selectedLines.length; ++i) 30 30 consideredLines.add(selectedLines[i]); 31 31 } 32 32 else 33 33 { 34 34 for (int i = 0; i < waypointTM.getRowCount(); ++i) 35 35 consideredLines.add(new Integer(i)); 36 36 } 37 37 38 38 // keep only lines where a node can be added 39 39 for (int i = 0; i < consideredLines.size(); ++i) 40 40 { 41 41 if (waypointTM.nodes.elementAt(consideredLines.elementAt(i)) != null) 42 42 workingLines.add(consideredLines.elementAt(i)); 43 43 } 44 44 } 45 45 46 46 public boolean executeCommand() 47 47 { … … 56 56 return true; 57 57 } 58 58 59 59 public void undoCommand() 60 60 { … … 66 66 } 67 67 } 68 68 69 69 public void fillModifiedData 70 70 (Collection< OsmPrimitive > modified, Collection< OsmPrimitive > deleted, … … 72 72 { 73 73 } 74 74 75 75 @Override public JLabel getDescription() 76 76 { -
applications/editors/josm/plugins/public_transport/src/public_transport/WaypointsDisableCommand.java
r22048 r23192 15 15 private Vector< Node > nodesForUndo = null; 16 16 private WaypointTableModel waypointTM = null; 17 17 18 18 public WaypointsDisableCommand(StopImporterAction controller) 19 19 { … … 21 21 workingLines = new Vector< Integer >(); 22 22 nodesForUndo = new Vector< Node >(); 23 23 24 24 // use either selected lines or all lines if no line is selected 25 25 int[] selectedLines = controller.getDialog().getWaypointsTable().getSelectedRows(); … … 28 28 { 29 29 for (int i = 0; i < selectedLines.length; ++i) 30 30 consideredLines.add(selectedLines[i]); 31 31 } 32 32 else 33 33 { 34 34 for (int i = 0; i < waypointTM.getRowCount(); ++i) 35 35 consideredLines.add(new Integer(i)); 36 36 } 37 37 38 38 // keep only lines where a node can be added 39 39 for (int i = 0; i < consideredLines.size(); ++i) 40 40 { 41 41 if (waypointTM.nodes.elementAt(consideredLines.elementAt(i)) != null) 42 42 workingLines.add(consideredLines.elementAt(i)); 43 43 } 44 44 } 45 45 46 46 public boolean executeCommand() 47 47 { … … 53 53 nodesForUndo.add(node); 54 54 if (node == null) 55 55 continue; 56 56 waypointTM.nodes.set(j, null); 57 57 Main.main.getCurrentDataSet().removePrimitive(node); … … 60 60 return true; 61 61 } 62 62 63 63 public void undoCommand() 64 64 { … … 69 69 waypointTM.nodes.set(j, node); 70 70 if (node == null) 71 71 continue; 72 72 node.setDeleted(false); 73 73 Main.main.getCurrentDataSet().addPrimitive(node); 74 74 } 75 75 } 76 76 77 77 public void fillModifiedData 78 78 (Collection< OsmPrimitive > modified, Collection< OsmPrimitive > deleted, … … 80 80 { 81 81 } 82 82 83 83 @Override public JLabel getDescription() 84 84 { -
applications/editors/josm/plugins/public_transport/src/public_transport/WaypointsEnableCommand.java
r22048 r23192 15 15 private WaypointTableModel waypointTM = null; 16 16 private String type = null; 17 17 18 18 public WaypointsEnableCommand(StopImporterAction controller) 19 19 { … … 21 21 type = controller.getDialog().getStoptype(); 22 22 workingLines = new Vector< Integer >(); 23 23 24 24 // use either selected lines or all lines if no line is selected 25 25 int[] selectedLines = controller.getDialog().getWaypointsTable().getSelectedRows(); … … 28 28 { 29 29 for (int i = 0; i < selectedLines.length; ++i) 30 30 consideredLines.add(selectedLines[i]); 31 31 } 32 32 else 33 33 { 34 34 for (int i = 0; i < waypointTM.getRowCount(); ++i) 35 35 consideredLines.add(new Integer(i)); 36 36 } 37 37 38 38 // keep only lines where a node can be added 39 39 for (int i = 0; i < consideredLines.size(); ++i) 40 40 { 41 41 if (waypointTM.nodes.elementAt(consideredLines.elementAt(i)) == null) 42 42 workingLines.add(consideredLines.elementAt(i)); 43 43 } 44 44 } 45 45 46 46 public boolean executeCommand() 47 47 { … … 52 52 (waypointTM.coors.elementAt(j), type, (String)waypointTM.getValueAt(j, 1)); 53 53 if ("".equals((String)waypointTM.getValueAt(j, 2))) 54 54 node.put("shelter", null); 55 55 else 56 56 node.put("shelter", (String)waypointTM.getValueAt(j, 2)); 57 57 waypointTM.nodes.set(j, node); 58 58 } 59 59 return true; 60 60 } 61 61 62 62 public void undoCommand() 63 63 { … … 68 68 waypointTM.nodes.set(j, null); 69 69 if (node == null) 70 70 continue; 71 71 Main.main.getCurrentDataSet().removePrimitive(node); 72 72 node.setDeleted(true); 73 73 } 74 74 } 75 75 76 76 public void fillModifiedData 77 77 (Collection< OsmPrimitive > modified, Collection< OsmPrimitive > deleted, … … 79 79 { 80 80 } 81 81 82 82 @Override public JLabel getDescription() 83 83 { -
applications/editors/josm/plugins/public_transport/src/public_transport/WaypointsNameCommand.java
r22048 r23192 18 18 private String oldShelter = null; 19 19 private String shelter = null; 20 20 21 21 public WaypointsNameCommand 22 22 (WaypointTableModel waypointTM, int workingLine, String name, String shelter) … … 34 34 this.shelter = null; 35 35 } 36 36 37 37 public boolean executeCommand() 38 38 { … … 54 54 return true; 55 55 } 56 56 57 57 public void undoCommand() 58 58 { … … 73 73 waypointTM.inEvent = false; 74 74 } 75 75 76 76 public void fillModifiedData 77 77 (Collection< OsmPrimitive > modified, Collection< OsmPrimitive > deleted, … … 79 79 { 80 80 } 81 81 82 82 @Override public JLabel getDescription() 83 83 { -
applications/editors/josm/plugins/reverter/src/reverter/ChangesetIdQuery.java
r22533 r23192 31 31 try { 32 32 return NumberFormat.getInstance().parse(tcid.getText()).intValue(); 33 } catch (ParseException e) { 33 } catch (ParseException e) { 34 34 return 0; 35 35 } … … 50 50 panel.add(new JLabel(tr("Changeset id:"))); 51 51 panel.add(tcid, GBC.eol().fill(GBC.HORIZONTAL)); 52 52 53 53 bgRevertType.add(rbFull); 54 54 bgRevertType.add(rbSelection); 55 55 bgRevertType.add(rbSelectionUndelete); 56 56 57 57 rbFull.setSelected(true); 58 58 panel.add(rbFull, GBC.eol().insets(0,10,0,0).fill(GBC.HORIZONTAL)); 59 59 panel.add(rbSelection, GBC.eol().fill(GBC.HORIZONTAL)); 60 60 panel.add(rbSelectionUndelete, GBC.eol().fill(GBC.HORIZONTAL)); 61 61 62 62 setContent(panel); 63 setupDialog(); 63 setupDialog(); 64 64 } 65 65 } -
applications/editors/josm/plugins/reverter/src/reverter/ChangesetReverter.java
r21807 r23192 54 54 public final RevertType revertType; 55 55 56 private final OsmDataLayer layer; // data layer associated with reverter 57 private final DataSet ds; // DataSet associated with reverter 58 private final ChangesetDataSet cds; // Current changeset data 56 private final OsmDataLayer layer; // data layer associated with reverter 57 private final DataSet ds; // DataSet associated with reverter 58 private final ChangesetDataSet cds; // Current changeset data 59 59 private DataSet nds; // Dataset that contains new objects downloaded by reverter 60 60 … … 68 68 //////////////////////////////////////// 69 69 private void addIfMissing(PrimitiveId id) { 70 OsmPrimitive p = ds.getPrimitiveById(id); 70 OsmPrimitive p = ds.getPrimitiveById(id); 71 71 if (p == null || p.isIncomplete()) { 72 72 missing.add(id); … … 94 94 } 95 95 } 96 96 97 97 /** 98 98 * Checks if {@see ChangesetDataSetEntry} conforms to current RevertType 99 99 * @param entry entry to be checked 100 * @return <code>true</code> if {@see ChangesetDataSetEntry} conforms to current RevertType 100 * @return <code>true</code> if {@see ChangesetDataSetEntry} conforms to current RevertType 101 101 */ 102 102 private boolean CheckOsmChangeEntry(ChangesetDataSetEntry entry) { … … 110 110 return p.isSelected(); 111 111 } 112 112 113 113 /** 114 114 * creates a reverter for specific changeset and fetches initial data … … 132 132 monitor.finishTask(); 133 133 } 134 134 135 135 // Build our own lists of created/updated/modified objects for better performance 136 136 for (Iterator<ChangesetDataSetEntry> it = cds.iterator();it.hasNext();) { … … 163 163 public void downloadObjectsHistory(ProgressMonitor progressMonitor) throws OsmTransferException { 164 164 final OsmServerMultiObjectReader rdr = new OsmServerMultiObjectReader(); 165 165 166 166 progressMonitor.beginTask("Downloading objects history",updated.size()+deleted.size()+1); 167 167 try { … … 182 182 } 183 183 } 184 184 185 185 public void downloadMissingPrimitives(ProgressMonitor monitor) throws OsmTransferException { 186 186 if (!hasMissingObjects()) return; … … 200 200 } 201 201 } 202 DataSet source = rdr.parseOsm(monitor); 202 DataSet source = rdr.parseOsm(monitor); 203 203 for (OsmPrimitive p : source.allPrimitives()) { 204 204 if (!p.isVisible() && !p.isDeleted()) { … … 210 210 missing.clear(); 211 211 } 212 212 213 213 private static Conflict<? extends OsmPrimitive> CreateConflict(OsmPrimitive p, boolean isMyDeleted) { 214 214 switch (p.getType()) { … … 222 222 } 223 223 } 224 224 225 225 private static boolean hasEqualSemanticAttributes(OsmPrimitive current,HistoryOsmPrimitive history) { 226 226 if (!current.getKeys().equals(history.getTags())) return false; … … 237 237 return true; 238 238 case RELATION: 239 List<org.openstreetmap.josm.data.osm.RelationMember> currentMembers = 239 List<org.openstreetmap.josm.data.osm.RelationMember> currentMembers = 240 240 ((Relation)current).getMembers(); 241 241 List<RelationMember> historyMembers = ((HistoryRelation)history).getMembers(); 242 242 if (currentMembers.size() != historyMembers.size()) return false; 243 243 for (int i = 0; i < currentMembers.size(); i++) { 244 org.openstreetmap.josm.data.osm.RelationMember currentMember = 244 org.openstreetmap.josm.data.osm.RelationMember currentMember = 245 245 currentMembers.get(i); 246 246 RelationMember historyMember = historyMembers.get(i); … … 253 253 } 254 254 } 255 255 256 256 /** 257 257 * Builds a list of commands that will revert the changeset 258 * 258 * 259 259 */ 260 260 public List<Command> getCommands() { 261 261 if (this.nds == null) return null; 262 262 263 263 ////////////////////////////////////////////////////////////////////////// 264 264 // Create commands to restore/update all affected objects … … 282 282 if (p != null) toDelete.add(p); 283 283 } 284 284 285 285 286 286 ////////////////////////////////////////////////////////////////////////// 287 287 // Check reversion against current dataset and create necessary conflicts 288 288 289 289 HashSet<OsmPrimitive> conflicted = new HashSet<OsmPrimitive>(); 290 290 291 291 for (Conflict<? extends OsmPrimitive> conflict : merger.getConflicts()) { 292 292 cmds.add(new ConflictAddCommand(layer,conflict)); 293 293 } 294 294 295 295 // Check objects versions 296 296 for (Iterator<ChangesetDataSetEntry> it = cds.iterator();it.hasNext();) { … … 302 302 throw new IllegalStateException(tr("Missing merge target for {0} with id {1}", 303 303 hp.getType(), hp.getId())); 304 304 305 305 if (hp.getVersion() != dp.getVersion() 306 306 && (hp.isVisible() || dp.isVisible()) && … … 309 309 */ 310 310 !hasEqualSemanticAttributes(dp,hp)) { 311 312 313 cmds.add(new ConflictAddCommand(layer,CreateConflict(dp, 311 312 313 cmds.add(new ConflictAddCommand(layer,CreateConflict(dp, 314 314 entry.getModificationType() == ChangesetModificationType.CREATED))); 315 315 conflicted.add(dp); 316 316 } 317 317 } 318 318 319 319 /* Check referrers for deleted objects: if object is referred by another object that 320 320 * isn't going to be deleted or modified, create a conflict. … … 340 340 } 341 341 } 342 342 343 343 // Create a Command to delete all marked objects 344 344 List<? extends OsmPrimitive> list; -
applications/editors/josm/plugins/reverter/src/reverter/MultiOsmReader.java
r21634 r23192 561 561 processRelationsAfterParsing(); 562 562 } 563 564 563 564 565 565 } -
applications/editors/josm/plugins/reverter/src/reverter/ObjectsHistoryAction.java
r21634 r23192 16 16 Shortcut.registerShortcut("tool:history", 17 17 "Tool: Display objects history dialog", 18 KeyEvent.VK_H, Shortcut.GROUP_EDIT, 18 KeyEvent.VK_H, Shortcut.GROUP_EDIT, 19 19 Shortcut.SHIFT_DEFAULT), 20 20 true); -
applications/editors/josm/plugins/reverter/src/reverter/ObjectsHistoryDialog.java
r22533 r23192 18 18 setButtonIcons(new String[] {"ok.png", "cancel.png" }); 19 19 setContent(new JPanel(new GridBagLayout())); 20 setupDialog(); 20 setupDialog(); 21 21 } 22 22 } -
applications/editors/josm/plugins/reverter/src/reverter/PrimitiveIdVersion.java
r21700 r23192 20 20 return version; 21 21 } 22 22 23 23 @Override 24 24 public int hashCode() { -
applications/editors/josm/plugins/reverter/src/reverter/RevertChangesetAction.java
r21726 r23192 27 27 Shortcut.registerShortcut("tool:revert", 28 28 tr("Tool: {0}", tr("Revert changeset")), 29 KeyEvent.VK_T, Shortcut.GROUP_EDIT, 30 Shortcut.SHIFT_DEFAULT), 29 KeyEvent.VK_T, Shortcut.GROUP_EDIT, 30 Shortcut.SHIFT_DEFAULT), 31 31 true); 32 32 } 33 33 34 34 @Override 35 35 protected void updateEnabledState() { … … 47 47 if (changesetId == 0) return; 48 48 if (revertType == null) return; 49 49 50 50 Main.worker.submit(new PleaseWaitRunnable(tr("Reverting...")) { 51 51 private ChangesetReverter rev; 52 52 private boolean downloadConfirmed = false; 53 53 54 54 private boolean checkAndDownloadMissing() throws OsmTransferException { 55 55 if (!rev.hasMissingObjects()) return true; 56 56 if (!downloadConfirmed) { 57 57 downloadConfirmed = JOptionPane.showConfirmDialog(Main.parent, 58 tr("This changeset has objects that are not present in current dataset.\n" + 58 tr("This changeset has objects that are not present in current dataset.\n" + 59 59 "It is needed to download them before reverting. Do you want to continue?"), 60 60 tr("Confirm"), JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION; 61 61 if (!downloadConfirmed) return false; 62 62 } 63 final PleaseWaitProgressMonitor monitor = 63 final PleaseWaitProgressMonitor monitor = 64 64 new PleaseWaitProgressMonitor(tr("Fetching missing primitives")); 65 65 try { … … 70 70 return !monitor.isCancelled(); 71 71 } 72 72 73 73 @Override 74 74 protected void realRun() throws OsmTransferException { … … 90 90 rev.downloadMissingPrimitives(progressMonitor.createSubTaskMonitor(0, false)); 91 91 } 92 92 93 93 if (progressMonitor.isCancelled()) return; 94 94 rev.downloadObjectsHistory(progressMonitor.createSubTaskMonitor(ProgressMonitor.ALL_TICKS, false)); … … 96 96 if (!checkAndDownloadMissing()) return; 97 97 List<Command> cmds = rev.getCommands(); 98 Command cmd = new SequenceCommand(tr(revertType == RevertType.FULL ? "Revert changeset #{0}" : 98 Command cmd = new SequenceCommand(tr(revertType == RevertType.FULL ? "Revert changeset #{0}" : 99 99 "Partially revert changeset #{0}",changesetId),cmds); 100 100 Main.main.undoRedo.add(cmd); -
applications/editors/josm/plugins/reverter/src/reverter/ReverterPlugin.java
r21807 r23192 18 18 JMenu historyMenu = Main.main.menu.addMenu(marktr("History"), KeyEvent.VK_R, 19 19 Main.main.menu.defaultMenuPos,ht("/Plugin/Reverter")); 20 //MainMenu.add(historyMenu, new ObjectsHistoryAction()); 20 //MainMenu.add(historyMenu, new ObjectsHistoryAction()); 21 21 MainMenu.add(historyMenu, new RevertChangesetAction()); 22 22 } -
applications/editors/josm/plugins/roadsigns/src/org/openstreetmap/josm/plugins/roadsigns/RoadSignInputDialog.java
r22423 r23192 471 471 public JComponent buildPreviewPanel() { 472 472 JPanel previewPanel = new JPanel(new GridBagLayout()); 473 473 474 474 String[] columnNames = {tr("Key"), tr("Value")}; 475 475 String[][] data = {{}}; … … 495 495 scroll.setPreferredSize(dim); 496 496 scroll.setMinimumSize(dim); /* minimum size is relevant for multisplit layout */ 497 497 498 498 addTrafficSignTag = new JCheckBox(tr("{0} tag", "traffic_sign")); 499 499 addTrafficSignTag.setSelected(Main.pref.getBoolean("plugin.roadsigns.addTrafficSignTag")); … … 503 503 } 504 504 }); 505 505 506 506 previewPanel.add(scroll, GBC.eol().fill()); 507 507 previewPanel.add(addTrafficSignTag, GBC.eol()); … … 544 544 final TreeMap<String, String> map= new TreeMap<String, String>(); 545 545 String traffic_sign = ""; 546 546 547 547 for (SignCombination sc : sel.combos) { 548 548 final Map<String, String> env = new HashMap<String, String>(); … … 596 596 } 597 597 } 598 598 599 599 Map<String, TagEvaluater> tags = new LinkedHashMap<String, TagEvaluater>(); 600 600 for (SignWrapper sw : sc.signs) { … … 654 654 map.putAll(result); 655 655 } 656 656 657 657 if (combo_traffic_sign.length() != 0) { 658 658 if (traffic_sign.length() != 0) { -
applications/editors/josm/plugins/roadsigns/src/org/openstreetmap/josm/plugins/roadsigns/RoadSignsReader.java
r22420 r23192 104 104 } 105 105 curSign.iconURL = iconURL; 106 106 107 107 if ("yes".equals(atts.getValue("supplementary"))) { 108 108 curSign.isSupplementing = true; 109 109 } 110 110 111 111 curSign.wiki = atts.getValue("wiki"); 112 112 curSign.loc_wiki = getLocalized(atts, "wiki"); … … 296 296 } 297 297 } 298 298 299 299 /** 300 300 * -
applications/editors/josm/plugins/roadsigns/src/org/openstreetmap/josm/plugins/roadsigns/javacc/ParamStringScannerConstants.java
r21967 r23192 3 3 4 4 5 /** 5 /** 6 6 * Token literal values and constants. 7 7 * Generated by org.javacc.parser.OtherFilesGen#start() -
applications/editors/josm/plugins/roadsigns/src/org/openstreetmap/josm/plugins/roadsigns/javacc/ParamStringScannerTokenManager.java
r21967 r23192 167 167 } 168 168 static final int[] jjnextStates = { 169 1, 3, 5, 6, 9, 10, 169 1, 3, 5, 6, 9, 10, 170 170 }; 171 171 … … 176 176 /** Lexer state names. */ 177 177 public static final String[] lexStateNames = { 178 "DEFAULT", 178 "DEFAULT", 179 179 }; 180 180 protected SimpleCharStream input_stream; … … 259 259 260 260 /** Get the next Token. */ 261 public Token getNextToken() 261 public Token getNextToken() 262 262 { 263 263 Token matchedToken; … … 266 266 EOFLoop : 267 267 for (;;) 268 { 269 try 270 { 268 { 269 try 270 { 271 271 curChar = input_stream.BeginToken(); 272 } 272 } 273 273 catch(java.io.IOException e) 274 { 274 { 275 275 jjmatchedKind = 0; 276 276 matchedToken = jjFillToken(); -
applications/editors/josm/plugins/roadsigns/src/org/openstreetmap/josm/plugins/roadsigns/javacc/ParseException.java
r21967 r23192 127 127 retval += add_escapes(tok.image); 128 128 retval += " \""; 129 tok = tok.next; 129 tok = tok.next; 130 130 } 131 131 retval += "\" at line " + currentToken.next.beginLine + ", column " + currentToken.next.beginColumn; … … 144 144 */ 145 145 protected String eol = System.getProperty("line.separator", "\n"); 146 146 147 147 /** 148 148 * Used to convert raw characters to their escaped version -
applications/editors/josm/plugins/roadsigns/src/org/openstreetmap/josm/plugins/roadsigns/javacc/SimpleCharStream.java
r21967 r23192 205 205 206 206 /** 207 * @deprecated 207 * @deprecated 208 208 * @see #getEndColumn 209 209 */ … … 214 214 215 215 /** 216 * @deprecated 216 * @deprecated 217 217 * @see #getEndLine 218 218 */ … … 449 449 columnDiff = nextColDiff; 450 450 i++; 451 } 451 } 452 452 453 453 if (i < len) -
applications/editors/josm/plugins/roadsigns/src/org/openstreetmap/josm/plugins/roadsigns/javacc/TokenMgrError.java
r21967 r23192 89 89 * Returns a detailed message for the Error when it is thrown by the 90 90 * token manager to indicate a lexical error. 91 * Parameters : 91 * Parameters : 92 92 * EOFSeen : indicates if EOF caused the lexical error 93 93 * curLexState : lexical state in which this error occurred … … 109 109 * You can also modify the body of this method to customize your error messages. 110 110 * For example, cases like LOOP_DETECTED and INVALID_LEXICAL_STATE are not 111 * of end-users concern, so you can return something like : 111 * of end-users concern, so you can return something like : 112 112 * 113 113 * "Internal Error : Please file a bug report .... " -
applications/editors/josm/plugins/turnrestrictions/src/org/openstreetmap/josm/plugins/turnrestrictions/CreateOrEditTurnRestrictionAction.java
r20701 r23192 29 29 */ 30 30 public class CreateOrEditTurnRestrictionAction extends JosmAction { 31 32 33 34 35 36 37 38 39 40 41 42 43 System.out.println(tr("Warning: turnrestrictions plugin replaces already existing action ''{0}'' behind shortcut ''{1}'' by action ''{2}''", actionMapKey.toString(), keyStroke.toString(), "turnrestrictions:create-or-edit")); 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 } 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 31 static private final Logger logger = Logger.getLogger(CreateOrEditTurnRestrictionAction.class.getName()); 32 33 /** 34 * Installs the global key stroke with which creating/editing a turn restriction 35 * is triggered. 36 * 37 * @param keyStroke the key stroke 38 */ 39 static public void install(KeyStroke keyStroke){ 40 InputMap im = Main.contentPane.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW); 41 Object actionMapKey = im.get(keyStroke); 42 if (actionMapKey != null && !actionMapKey.toString().equals("turnrestrictions:create-or-edit")) { 43 System.out.println(tr("Warning: turnrestrictions plugin replaces already existing action ''{0}'' behind shortcut ''{1}'' by action ''{2}''", actionMapKey.toString(), keyStroke.toString(), "turnrestrictions:create-or-edit")); 44 } 45 KeyStroke[] keys = im.keys(); 46 if (keys != null){ 47 for(KeyStroke ks: im.keys()){ 48 if (im.get(ks).equals("turnrestrictions:create-or-edit")) { 49 im.remove(ks); 50 } 51 } 52 } 53 im.put(keyStroke, "turnrestrictions:create-or-edit"); 54 ActionMap am = Main.contentPane.getActionMap(); 55 am.put("turnrestrictions:create-or-edit", getInstance()); 56 } 57 58 /** 59 * Installs global key stroke configured in the preferences. 60 * 61 * @param keyStroke the key stroke 62 */ 63 static public void install(){ 64 String value = Main.pref.get(PreferenceKeys.EDIT_SHORTCUT, "shift ctrl T"); 65 KeyStroke key = KeyStroke.getKeyStroke(value); 66 if (key == null){ 67 System.out.println(tr("Warning: illegal value ''{0}'' for preference key ''{1}''. Falling back to default value ''shift ctrl T''.", value, PreferenceKeys.EDIT_SHORTCUT)); 68 key = KeyStroke.getKeyStroke("shift ctrl T"); 69 } 70 install(key); 71 } 72 73 /** the singleton instance of this action */ 74 private static CreateOrEditTurnRestrictionAction instance; 75 76 /** 77 * Replies the unique instance of this action 78 * 79 * @return 80 */ 81 public static CreateOrEditTurnRestrictionAction getInstance() { 82 if (instance == null){ 83 instance = new CreateOrEditTurnRestrictionAction(); 84 } 85 return instance; 86 } 87 88 protected CreateOrEditTurnRestrictionAction() { 89 super( 90 tr("Create/Edit turn restriction..."), 91 null, 92 tr("Create or edit a turn restriction."), 93 null, // shortcut is going to be registered later 94 false 95 ); 96 } 97 98 public void actionPerformed(ActionEvent e) { 99 OsmDataLayer layer = Main.main.getEditLayer(); 100 if (layer == null) return; 101 Collection<Relation> trs = TurnRestrictionSelectionPopupPanel.getTurnRestrictionsParticipatingIn(layer.data.getSelected()); 102 if (layer == null) return; 103 if (trs.isEmpty()){ 104 // current selection isn't participating in turn restrictions. Launch 105 // an editor for a new turn restriction 106 // 107 Relation tr = new TurnRestrictionBuilder().buildFromSelection(layer); 108 TurnRestrictionEditor editor = new TurnRestrictionEditor(Main.map.mapView,layer,tr); 109 TurnRestrictionEditorManager.getInstance().positionOnScreen(editor); 110 TurnRestrictionEditorManager.getInstance().register(layer, tr, editor); 111 editor.setVisible(true); 112 } else { 113 // let the user choose whether he wants to create a new turn restriction or 114 // edit one of the turn restrictions participating in the current selection 115 TurnRestrictionSelectionPopupPanel pnl = new TurnRestrictionSelectionPopupPanel( 116 layer 117 ); 118 pnl.launch(); 119 } 120 } 121 121 } -
applications/editors/josm/plugins/turnrestrictions/src/org/openstreetmap/josm/plugins/turnrestrictions/TurnRestrictionBuilder.java
r20724 r23192 21 21 public class TurnRestrictionBuilder { 22 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 23 private Way from; 24 private Way to; 25 private final ArrayList<OsmPrimitive> vias = new ArrayList<OsmPrimitive>(); 26 27 public TurnRestrictionBuilder(){ 28 } 29 30 /** 31 * Initializes the 'from' leg. Proposes the first element 32 * in {@code primitives} as 'from' leg if this element is a 33 * non-deleted, visible way. 34 * 35 * @param primitives 36 */ 37 protected void initFromLeg(List<OsmPrimitive> primitives){ 38 if (primitives == null || primitives.isEmpty()) return; 39 OsmPrimitive p = primitives.get(0); 40 if (! (p instanceof Way)) return; 41 Way fromLeg = (Way)p; 42 if (fromLeg.isDeleted() || ! fromLeg.isVisible()) return; 43 this.from = fromLeg; 44 } 45 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 if (from == null || to == null) return; 71 72 73 74 75 76 77 78 79 80 81 82 } 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 46 /** 47 * Initializes the 'to' leg. Proposes the last element 48 * in {@code primitives} as 'to' leg if this element is a 49 * non-deleted, visible way. 50 * 51 * @param primitives 52 */ 53 protected void initToLeg(List<OsmPrimitive> primitives){ 54 if (primitives == null || primitives.isEmpty()) return; 55 if (primitives.size() < 2) return; 56 OsmPrimitive p = primitives.get(primitives.size()-1); 57 if (! (p instanceof Way)) return; 58 Way toLeg = (Way)p; 59 if (toLeg.isDeleted() || ! toLeg.isVisible()) return; 60 this.to = toLeg; 61 } 62 63 /** 64 * Initializes the vias from the two turn restriction legs. The two 65 * legs have to be defined, otherwise no via is proposed. This methods 66 * proposes exactly one node as via, if the two turn restriction 67 * legs intersect at exactly one node. 68 */ 69 protected void initViaFromLegs(){ 70 if (from == null || to == null) return; 71 // check whether 'from' and 'to' have exactly one intersecting 72 // node. This node is proposed as via node. The turn restriction 73 // node will also provide functionality to split either or both 74 // of 'from' and 'to' way if they aren't connected from tail to 75 // head 76 // 77 HashSet<Node> nodes = new HashSet<Node>(); 78 nodes.addAll(from.getNodes()); 79 nodes.retainAll(to.getNodes()); 80 if (nodes.size() == 1){ 81 vias.add(nodes.iterator().next()); 82 } 83 } 84 85 /** 86 * Initializes the vias with the primitives (1..size-2), provided 87 * these primitives aren't relations and they are visible and non-deleted. 88 * 89 * @param primitives 90 */ 91 protected void initViasFromPrimitives(List<OsmPrimitive> primitives) { 92 if (primitives == null || primitives.size() <=2) return; 93 // if we didn't find a from or a to way, we don't propose via objects 94 // either 95 if (from == null || to == null) return; 96 for(int i=1; i< primitives.size() -2;i++){ 97 OsmPrimitive p = primitives.get(i); 98 if (p == null) continue; 99 if (p instanceof Relation) continue; 100 if (p.isDeleted() || ! p.isVisible()) continue; 101 vias.add(p); 102 } 103 } 104 105 /** 106 * Resets the builder 107 */ 108 protected void reset() { 109 this.from = null; 110 this.to = null; 111 this.vias.clear(); 112 } 113 114 /** 115 * Creates and initializes a new turn restriction based on the primitives 116 * currently selected in layer {@code layer}. 117 * 118 * @param layer the layer. Must not be null. 119 * @return the new initialized turn restriction. The turn restriction isn't 120 * added to the layer yet. 121 * @throws IllegalArgumentException thrown if layer is null 122 */ 123 public synchronized Relation buildFromSelection(OsmDataLayer layer) { 124 CheckParameterUtil.ensureParameterNotNull(layer, "layer"); 125 List<OsmPrimitive> selection = new ArrayList<OsmPrimitive>(layer.data.getSelected()); 126 return build(selection); 127 } 128 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 } 129 /** 130 * Creates and initializes a new turn restriction based on primitives 131 * in {@code primitives}. 132 * 133 * @param primitives the primitives 134 * @return the new initialized turn restriction. The turn restriction isn't 135 * added to the layer yet. 136 */ 137 public synchronized Relation build(List<OsmPrimitive> primitives){ 138 Relation tr = new Relation(); 139 tr.put("type", "restriction"); 140 if (primitives == null || primitives.isEmpty()) return tr; 141 if (primitives.size() <=2){ 142 initFromLeg(primitives); 143 initToLeg(primitives); 144 initViaFromLegs(); 145 } else if (primitives.size() > 2) { 146 initFromLeg(primitives); 147 initToLeg(primitives); 148 initViasFromPrimitives(primitives); 149 } 150 151 if (from != null){ 152 tr.addMember(new RelationMember("from", from)); 153 } 154 if (to != null){ 155 tr.addMember(new RelationMember("to", to)); 156 } 157 for(OsmPrimitive via: vias){ 158 tr.addMember(new RelationMember("via", via)); 159 } 160 return tr; 161 } 162 162 } -
applications/editors/josm/plugins/turnrestrictions/src/org/openstreetmap/josm/plugins/turnrestrictions/TurnRestrictionsPlugin.java
r20701 r23192 13 13 */ 14 14 public class TurnRestrictionsPlugin extends Plugin{ 15 16 17 super(info); 18 19 20 21 22 23 24 public void mapFrameInitialized(MapFrame oldFrame, MapFrame newFrame) { 25 26 27 28 29 30 31 15 16 public TurnRestrictionsPlugin(PluginInformation info) { 17 super(info); 18 } 19 20 /** 21 * Called when the JOSM map frame is created or destroyed. 22 */ 23 @Override 24 public void mapFrameInitialized(MapFrame oldFrame, MapFrame newFrame) { 25 if (oldFrame == null && newFrame != null) { // map frame added 26 TurnRestrictionsListDialog dialog = new TurnRestrictionsListDialog(); 27 // add the dialog 28 newFrame.addToggleDialog(dialog); 29 CreateOrEditTurnRestrictionAction.install(); 30 } 31 } 32 32 33 34 35 36 33 @Override 34 public PreferenceSetting getPreferenceSetting() { 35 return new PreferenceEditor(); 36 } 37 37 } -
applications/editors/josm/plugins/turnrestrictions/src/org/openstreetmap/josm/plugins/turnrestrictions/dnd/PrimitiveIdListProvider.java
r20489 r23192 5 5 import org.openstreetmap.josm.data.osm.PrimitiveId;; 6 6 public interface PrimitiveIdListProvider { 7 8 9 10 11 12 13 7 /** 8 * Replies the list of currently selected primitive IDs. Replies an empty list if no primitive IDs 9 * are selected. 10 * 11 * @return the list of currently selected primitive IDs 12 */ 13 List<PrimitiveId> getSelectedPrimitiveIds(); 14 14 } -
applications/editors/josm/plugins/turnrestrictions/src/org/openstreetmap/josm/plugins/turnrestrictions/dnd/PrimitiveIdListTransferHandler.java
r20724 r23192 20 20 */ 21 21 public class PrimitiveIdListTransferHandler extends TransferHandler { 22 23 24 25 26 22 static private final Logger logger = Logger.getLogger(PrimitiveIdListTransferHandler.class.getName()); 23 private PrimitiveIdListProvider provider; 24 25 /** 26 * Replies true if {@code transferFlavors} includes the data flavor {@see PrimitiveIdTransferable#PRIMITIVE_ID_LIST_FLAVOR}. 27 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 28 * @param transferFlavors an array of transferFlavors 29 * @return true if {@code transferFlavors} includes the data flavor {@see PrimitiveIdTransferable#PRIMITIVE_ID_LIST_FLAVOR}. 30 */ 31 public static boolean isSupportedFlavor(DataFlavor[] transferFlavors) { 32 for (DataFlavor df: transferFlavors) { 33 if (df.equals(PrimitiveIdTransferable.PRIMITIVE_ID_LIST_FLAVOR)) return true; 34 } 35 return false; 36 } 37 38 /** 39 * Creates the transfer handler 40 * 41 * @param provider the provider of the primitive IDs. Must not be null. 42 * @throws IllegalArgumentException thrown if provider is null. 43 */ 44 public PrimitiveIdListTransferHandler(PrimitiveIdListProvider provider) throws IllegalArgumentException{ 45 CheckParameterUtil.ensureParameterNotNull(provider, "provider"); 46 this.provider = provider; 47 } 48 48 49 50 51 52 return new PrimitiveIdTransferable(provider.getSelectedPrimitiveIds()); 53 49 50 51 protected Transferable createTransferable(JComponent c) { 52 return new PrimitiveIdTransferable(provider.getSelectedPrimitiveIds()); 53 } 54 54 55 56 57 55 public int getSourceActions(JComponent c) { 56 return COPY; 57 } 58 58 59 60 61 return isSupportedFlavor(transferFlavors); 62 } 59 @Override 60 public boolean canImport(JComponent comp, DataFlavor[] transferFlavors) { 61 return isSupportedFlavor(transferFlavors); 62 } 63 63 } -
applications/editors/josm/plugins/turnrestrictions/src/org/openstreetmap/josm/plugins/turnrestrictions/dnd/PrimitiveIdTransferable.java
r20489 r23192 18 18 */ 19 19 public class PrimitiveIdTransferable implements Transferable{ 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 20 21 /** the data flower for the set of of primitive ids */ 22 static public final DataFlavor PRIMITIVE_ID_LIST_FLAVOR = 23 new DataFlavor(Set.class, "a set of OSM primitive ids"); 24 25 /** 26 * this transferable supports two flavors: (1) {@see #PRIMITIVE_ID_LIST_FLAVOR} and 27 * (2) {@see DataFlavor#stringFlavor}. 28 * 29 * See also {@see #getPrimitiveIds()} and {@see #getAsString()} 30 */ 31 static public final DataFlavor[] SUPPORTED_FLAVORS = new DataFlavor[] { 32 PRIMITIVE_ID_LIST_FLAVOR, 33 DataFlavor.stringFlavor 34 }; 35 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 36 37 private List<PrimitiveId> ids = new ArrayList<PrimitiveId>(); 38 39 /** 40 * Creates a transferable from a collection of {@see PrimitiveId}s 41 * 42 * @param ids 43 */ 44 public PrimitiveIdTransferable(List<PrimitiveId> ids) { 45 if (ids == null) return; 46 for(PrimitiveId id: ids) { 47 this.ids.add(new SimplePrimitiveId(id.getUniqueId(), id.getType())); 48 } 49 } 50 51 /** 52 * If flavor is {@see #PRIMITIVE_ID_SET_FLAVOR}, replies a the list of 53 * transferred {@see PrimitiveId}s 54 * 55 * If flavor is {@see DataFlavor#stringFlavor}, replies a string representation 56 * of the list of transferred {@see PrimitiveId}s 57 */ 58 public Object getTransferData(DataFlavor flavor) 59 throws UnsupportedFlavorException, IOException { 60 if (PRIMITIVE_ID_LIST_FLAVOR.equals(flavor)) { 61 return getPrimitiveIds(); 62 } else if (DataFlavor.stringFlavor.equals(flavor)) { 63 return getAsString(); 64 } 65 throw new UnsupportedFlavorException(flavor); 66 } 67 68 /** 69 * Replies the list of OSM primitive ids 70 * 71 * @return the list of OSM primitive ids 72 */ 73 public List<PrimitiveId> getPrimitiveIds() { 74 return ids; 75 } 76 77 /** 78 * Replies a string representation of the list of OSM primitive ids 79 * 80 * @return a string representation of the list of OSM primitive ids 81 */ 82 public String getAsString() { 83 StringBuffer sb = new StringBuffer(); 84 for(PrimitiveId id: ids) { 85 if (sb.length() > 0) sb.append(","); 86 sb.append(id.getType().getAPIName()).append("/").append(id.getUniqueId()); 87 } 88 return sb.toString(); 89 } 90 90 91 92 93 91 public DataFlavor[] getTransferDataFlavors() { 92 return SUPPORTED_FLAVORS; 93 } 94 94 95 96 97 98 99 100 } 95 public boolean isDataFlavorSupported(DataFlavor flavor) { 96 for(DataFlavor df: SUPPORTED_FLAVORS) { 97 if (df.equals(flavor)) return true; 98 } 99 return false; 100 } 101 101 } -
applications/editors/josm/plugins/turnrestrictions/src/org/openstreetmap/josm/plugins/turnrestrictions/editor/AdvancedEditorPanel.java
r20735 r23192 23 23 */ 24 24 public class AdvancedEditorPanel extends JPanel { 25 25 private static final Logger logger = Logger.getLogger(AdvancedEditorPanel.class.getName()); 26 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 pnlTagEditor = new TagEditorPanel(model.getTagEditorModel()); 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 } 120 } 121 27 private TurnRestrictionEditorModel model; 28 private TagEditorPanel pnlTagEditor; 29 private JPanel pnlRelationMemberEditor; 30 private JTable tblRelationMemberEditor; 31 private JSplitPane spEditors; 32 33 /** 34 * Creates the panel with the tag editor 35 * 36 * @return 37 */ 38 protected JPanel buildTagEditorPanel() { 39 JPanel pnl = new JPanel(new BorderLayout()); 40 HtmlPanel msg = new HtmlPanel(); 41 msg.setText("<html><body>" + 42 tr("In the following table you can edit the <strong>raw tags</strong>" 43 + " of the OSM relation representing this turn restriction.") 44 + "</body></html>" 45 ); 46 pnl.add(msg, BorderLayout.NORTH); 47 pnlTagEditor = new TagEditorPanel(model.getTagEditorModel()); 48 pnlTagEditor.initAutoCompletion(model.getLayer()); 49 pnl.add(pnlTagEditor, BorderLayout.CENTER); 50 return pnl; 51 } 52 53 /** 54 * Builds the panel with the table for editing relation members 55 * 56 * @return 57 */ 58 protected JPanel buildMemberEditorPanel() { 59 JPanel pnl = new JPanel(new BorderLayout()); 60 HtmlPanel msg = new HtmlPanel(); 61 msg.setText("<html><body>" 62 + tr("In the following table you can edit the <strong>raw members</strong>" 63 + " of the OSM relation representing this turn restriction.") + "</body></html>" 64 ); 65 pnl.add(msg, BorderLayout.NORTH); 66 67 tblRelationMemberEditor = new RelationMemberTable(model); 68 JScrollPane pane = new JScrollPane(tblRelationMemberEditor); 69 pane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED); 70 pane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); 71 pnl.add(pane); 72 return pnl; 73 } 74 75 /** 76 * Creates the main split panel 77 * @return 78 */ 79 protected JSplitPane buildSplitPane() { 80 spEditors = new JSplitPane(JSplitPane.VERTICAL_SPLIT); 81 spEditors.setTopComponent(buildTagEditorPanel()); 82 spEditors.setBottomComponent(buildMemberEditorPanel()); 83 spEditors.setOneTouchExpandable(false); 84 spEditors.setDividerSize(5); 85 spEditors.addHierarchyListener(new SplitPaneDividerInitializer()); 86 return spEditors; 87 } 88 89 /** 90 * Builds the user interface 91 */ 92 protected void build() { 93 setLayout(new BorderLayout()); 94 add(buildSplitPane(), BorderLayout.CENTER); 95 } 96 97 /** 98 * Creates the advanced editor 99 * 100 * @param model the editor model. Must not be null. 101 * @throws IllegalArgumentException thrown if model is null 102 */ 103 public AdvancedEditorPanel(TurnRestrictionEditorModel model) throws IllegalArgumentException{ 104 CheckParameterUtil.ensureParameterNotNull(model, "model"); 105 this.model = model; 106 build(); 107 HelpUtil.setHelpContext(this, HelpUtil.ht("/Plugins/turnrestrictions#AdvancedEditor")); 108 } 109 110 /** 111 * Initializes the divider location when the components becomes visible the 112 * first time 113 */ 114 class SplitPaneDividerInitializer implements HierarchyListener { 115 public void hierarchyChanged(HierarchyEvent e) { 116 if (isShowing()) { 117 spEditors.setDividerLocation(0.5); 118 spEditors.removeHierarchyListener(this); 119 } 120 } 121 } 122 122 } -
applications/editors/josm/plugins/turnrestrictions/src/org/openstreetmap/josm/plugins/turnrestrictions/editor/BasicEditorPanel.java
r20917 r23192 28 28 public class BasicEditorPanel extends VerticallyScrollablePanel { 29 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 gc.insets = new Insets(0,0,5,5); 54 55 56 57 58 30 /** the turn restriction model */ 31 private TurnRestrictionEditorModel model; 32 33 /** the UI widgets */ 34 private TurnRestrictionLegEditor fromEditor; 35 private TurnRestrictionLegEditor toEditor; 36 private ViaList lstVias; 37 private JLabel lblVias; 38 private JScrollPane spVias; 39 private TurnRestrictionComboBox cbTurnRestrictions; 40 private VehicleExceptionEditor vehicleExceptionsEditor; 41 42 /** 43 * builds the UI 44 */ 45 protected void build() { 46 setLayout(new GridBagLayout()); 47 GridBagConstraints gc = new GridBagConstraints(); 48 gc.anchor = GridBagConstraints.WEST; 49 gc.fill = GridBagConstraints.HORIZONTAL; 50 gc.weightx = 0.0; 51 52 // the editor for selecting the 'from' leg 53 gc.insets = new Insets(0,0,5,5); 54 add(new JLabel(tr("Type:")), gc); 55 56 gc.gridx = 1; 57 gc.weightx = 1.0; 58 add(cbTurnRestrictions = new TurnRestrictionComboBox(new TurnRestrictionComboBoxModel(model)), gc); 59 59 60 61 62 gc.gridy = 1; 63 64 65 66 67 68 60 // the editor for selecting the 'from' leg 61 gc.gridx = 0; 62 gc.gridy = 1; 63 gc.weightx = 0.0; 64 add(new JLabel(tr("From:")), gc); 65 66 gc.gridx = 1; 67 gc.weightx = 1.0; 68 add(fromEditor = new TurnRestrictionLegEditor(model, TurnRestrictionLegRole.FROM),gc); 69 69 70 71 72 73 74 gc.insets = new Insets(0,0,5,5); 75 76 77 78 79 80 81 82 83 84 85 gc.insets = new Insets(0,0,5,5); 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 gc.insets = new Insets(0,0,5,5); 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 } 155 156 157 158 159 160 161 162 public void initIconSetFromPreferences(Preferences prefs){ 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 70 // the editor for selecting the 'to' leg 71 gc.gridx = 0; 72 gc.gridy = 2; 73 gc.weightx = 0.0; 74 gc.insets = new Insets(0,0,5,5); 75 add(new JLabel(tr("To:")), gc); 76 77 gc.gridx = 1; 78 gc.weightx = 1.0; 79 add(toEditor = new TurnRestrictionLegEditor(model, TurnRestrictionLegRole.TO),gc); 80 81 // the editor for selecting the 'vias' 82 gc.gridx = 0; 83 gc.gridy = 3; 84 gc.weightx = 0.0; 85 gc.insets = new Insets(0,0,5,5); 86 add(lblVias = new JLabel(tr("Vias:")), gc); 87 88 gc.gridx = 1; 89 gc.weightx = 1.0; 90 DefaultListSelectionModel selectionModel = new DefaultListSelectionModel(); 91 add(spVias = new JScrollPane(lstVias = new ViaList(new ViaListModel(model, selectionModel), selectionModel)),gc); 92 if (!Main.pref.getBoolean(PreferenceKeys.SHOW_VIAS_IN_BASIC_EDITOR, false)) { 93 lblVias.setVisible(false); 94 spVias.setVisible(false); 95 } 96 97 // the editor for vehicle exceptions 98 vehicleExceptionsEditor = new VehicleExceptionEditor(model); 99 gc.gridx = 0; 100 gc.gridy = 4; 101 gc.weightx = 1.0; 102 gc.gridwidth = 2; 103 gc.insets = new Insets(0,0,5,5); 104 add(vehicleExceptionsEditor, gc); 105 106 // just a filler - grabs remaining space 107 gc.gridx = 0; 108 gc.gridy = 5; 109 gc.gridwidth = 2; 110 gc.weighty = 1.0; 111 gc.fill = GridBagConstraints.BOTH; 112 add(new JPanel(), gc); 113 114 setBorder(BorderFactory.createEmptyBorder(5,5,5,5)); 115 } 116 117 118 /** 119 * Creates the panel. 120 * 121 * @param model the editor model. Must not be null. 122 * @throws IllegalArgumentException thrown if model is null 123 */ 124 public BasicEditorPanel(TurnRestrictionEditorModel model) { 125 CheckParameterUtil.ensureParameterNotNull(model, "model"); 126 this.model = model; 127 build(); 128 HelpUtil.setHelpContext(this, HelpUtil.ht("/Plugins/turnrestrictions#BasicEditor")); 129 } 130 131 /** 132 * Requests the focus on one of the input widgets for turn 133 * restriction data. 134 * 135 * @param focusTarget the target component to request focus for. 136 * Ignored if null. 137 */ 138 public void requestFocusFor(BasicEditorFokusTargets focusTarget){ 139 if (focusTarget == null) return; 140 switch(focusTarget){ 141 case RESTRICION_TYPE: 142 cbTurnRestrictions.requestFocusInWindow(); 143 break; 144 case FROM: 145 fromEditor.requestFocusInWindow(); 146 break; 147 case TO: 148 toEditor.requestFocusInWindow(); 149 break; 150 case VIA: 151 lstVias.requestFocusInWindow(); 152 break; 153 } 154 } 155 156 /** 157 * Initializes the set of icons used from the preference key 158 * {@see PreferenceKeys#ROAD_SIGNS}. 159 * 160 * @param prefs the JOSM preferences 161 */ 162 public void initIconSetFromPreferences(Preferences prefs){ 163 cbTurnRestrictions.initIconSetFromPreferences(prefs); 164 } 165 166 /** 167 * Initializes the visibility of the list of via-objects depending 168 * on values in the JOSM preferences 169 * 170 * @param prefs the JOSM preferences 171 */ 172 public void initViasVisibilityFromPreferences(Preferences prefs){ 173 boolean value = prefs.getBoolean(PreferenceKeys.SHOW_VIAS_IN_BASIC_EDITOR, false); 174 if (value != lblVias.isVisible()){ 175 lblVias.setVisible(value); 176 spVias.setVisible(value); 177 } 178 } 179 179 } -
applications/editors/josm/plugins/turnrestrictions/src/org/openstreetmap/josm/plugins/turnrestrictions/editor/ExceptValueModel.java
r20586 r23192 14 14 */ 15 15 public class ExceptValueModel { 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 } 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 } 16 /** 17 * The set of standard vehicle types which can be used in the 18 * 'except' tag 19 */ 20 static public final Set<String> STANDARD_VEHICLE_EXCEPTION_VALUES; 21 static { 22 HashSet<String> s = new HashSet<String>(); 23 s.add("psv"); 24 s.add("hgv"); 25 s.add("bicycle"); 26 s.add("motorcar"); 27 STANDARD_VEHICLE_EXCEPTION_VALUES = Collections.unmodifiableSet(s); 28 } 29 30 /** 31 * Replies true, if {@code v} is a standard vehicle type. Replies 32 * false if {@code v} is null 33 * 34 * @param v the vehicle type. 35 * @return true, if {@code v} is a standard vehicle type. 36 */ 37 static public boolean isStandardVehicleExceptionValue(String v){ 38 if (v == null) return false; 39 v = v.trim().toLowerCase(); 40 return STANDARD_VEHICLE_EXCEPTION_VALUES.contains(v); 41 } 42 43 private String value = ""; 44 private boolean isStandard = true; 45 private final Set<String> vehicleExceptions = new HashSet<String>(); 46 47 48 protected void parseValue(String value) { 49 if (value == null || value.trim().equals("")) value = ""; 50 this.value = value; 51 isStandard = true; 52 vehicleExceptions.clear(); 53 if (value.equals("")) return; 54 String[] values = value.split(";"); 55 for (String v: values){ 56 v = v.trim().toLowerCase(); 57 if (isStandardVehicleExceptionValue(v)) { 58 vehicleExceptions.add(v); 59 } else { 60 isStandard = false; 61 } 62 } 63 } 64 65 /** 66 * Creates a new model for an empty standard value 67 */ 68 public ExceptValueModel() {} 69 70 /** 71 * Creates a new model for the tag value {@code value}. 72 * 73 * @param value the tag value 74 * @see #parseValue(String) 75 */ 76 public ExceptValueModel(String value){ 77 if (value == null || value.trim().equals("")) 78 return; 79 parseValue(value); 80 } 81 82 /** 83 * Replies the tag value representing the state of this model. 84 * 85 * @return 86 */ 87 public String getValue() { 88 if (isStandard){ 89 StringBuffer sb = new StringBuffer(); 90 // we use an ordered list because equals() 91 // is based on getValue() 92 // 93 List<String> values = new ArrayList<String>(vehicleExceptions); 94 Collections.sort(values); 95 for (String v: values){ 96 if (sb.length() > 0) { 97 sb.append(";"); 98 } 99 sb.append(v); 100 } 101 return sb.toString(); 102 } else { 103 return value; 104 } 105 } 106 107 /** 108 * Sets the value in this model 109 * 110 * @param value 111 */ 112 public void setValue(String value) { 113 parseValue(value); 114 } 115 116 /** 117 * Replies true if this model currently holds a standard 'except' value 118 * 119 * @return 120 */ 121 public boolean isStandard() { 122 return isStandard; 123 } 124 125 /** 126 * Tells this model to use standard values only. 127 * 128 */ 129 public void setStandard(boolean isStandard) { 130 this.isStandard = isStandard; 131 } 132 133 /** 134 * Replies true if {@code vehicleType} is currently set as exception in this 135 * model. 136 * 137 * @param vehicleType one of the standard vehicle types from {@see #STANDARD_VEHICLE_EXCEPTION_VALUES} 138 * @return true if {@code vehicleType} is currently set as exception in this 139 * model. 140 * @exception IllegalArgumentException thrown if {@code vehicleType} isn't a standard vehicle type 141 */ 142 public boolean isVehicleException(String vehicleType) throws IllegalArgumentException{ 143 if (vehicleType == null) return false; 144 if (!isStandardVehicleExceptionValue(vehicleType)) { 145 throw new IllegalArgumentException(MessageFormat.format("vehicleType ''{0}'' isn''t a valid standard vehicle type", vehicleType)); 146 } 147 vehicleType = vehicleType.trim().toLowerCase(); 148 return vehicleExceptions.contains(vehicleType); 149 } 150 151 /** 152 * Sets the {@code vehicleType} as exception in this turn restriction. 153 * 154 * @param vehicleType one of the standard vehicle types from {@see #STANDARD_VEHICLE_EXCEPTION_VALUES} 155 * @exception IllegalArgumentException thrown if {@code vehicleType} isn't a standard vehicle type 156 */ 157 public void setVehicleException(String vehicleType) throws IllegalArgumentException{ 158 if (!isStandardVehicleExceptionValue(vehicleType)) { 159 throw new IllegalArgumentException(MessageFormat.format("vehicleType ''{0}'' isn''t a valid standard vehicle type", vehicleType)); 160 } 161 vehicleExceptions.add(vehicleType.trim().toLowerCase()); 162 } 163 164 165 /** 166 * Sets or removes the {@code vehicleType} as exception in this turn restriction, depending 167 * on whether {@code setOrRemove} is true or false, respectively. 168 * 169 * @param vehicleType one of the standard vehicle types from {@see #STANDARD_VEHICLE_EXCEPTION_VALUES} 170 * @param setOrRemove if true, the exception is set; otherwise, it is removed 171 * @exception IllegalArgumentException thrown if {@code vehicleType} isn't a standard vehicle type 172 */ 173 public void setVehicleException(String vehicleType, boolean setOrRemove) throws IllegalArgumentException{ 174 if (setOrRemove){ 175 setVehicleException(vehicleType); 176 } else { 177 removeVehicleException(vehicleType); 178 } 179 } 180 181 /** 182 * Removes the {@code vehicleType} as exception in this turn restriction 183 * 184 * @param vehicleType one of the standard vehicle types from {@see #STANDARD_VEHICLE_EXCEPTION_VALUES} 185 * @exception IllegalArgumentException thrown if {@code vehicleType} isn't a standard vehicle type 186 */ 187 public void removeVehicleException(String vehicleType) throws IllegalArgumentException{ 188 if (!isStandardVehicleExceptionValue(vehicleType)) { 189 throw new IllegalArgumentException(MessageFormat.format("vehicleType ''{0}'' isn''t a valid standard vehicle type", vehicleType)); 190 } 191 vehicleExceptions.remove(vehicleType.trim().toLowerCase()); 192 } 193 194 @Override 195 public int hashCode() { 196 final int prime = 31; 197 int result = 1; 198 result = prime * result + getValue().hashCode(); 199 return result; 200 } 201 202 @Override 203 public boolean equals(Object obj) { 204 if (this == obj) 205 return true; 206 if (obj == null) 207 return false; 208 if (getClass() != obj.getClass()) 209 return false; 210 ExceptValueModel other = (ExceptValueModel) obj; 211 return getValue().equals(other.getValue()); 212 } 213 213 } -
applications/editors/josm/plugins/turnrestrictions/src/org/openstreetmap/josm/plugins/turnrestrictions/editor/JosmSelectionListModel.java
r20735 r23192 40 40 */ 41 41 public class JosmSelectionListModel extends AbstractListModel implements EditLayerChangeListener, SelectionChangedListener, DataSetListener, PrimitiveIdListProvider{ 42 43 42 static private final Logger logger = Logger.getLogger(JosmSelectionListModel.class.getName()); 43 44 44 private final List<OsmPrimitive> selection = new ArrayList<OsmPrimitive>(); 45 45 private DefaultListSelectionModel selectionModel; … … 55 55 */ 56 56 public JosmSelectionListModel(OsmDataLayer layer, DefaultListSelectionModel selectionModel) { 57 58 59 57 CheckParameterUtil.ensureParameterNotNull(selectionModel, "selectionModel"); 58 CheckParameterUtil.ensureParameterNotNull(layer, "layer"); 59 this.layer = layer; 60 60 this.selectionModel = selectionModel; 61 61 setJOSMSelection(layer.data.getSelected()); … … 115 115 */ 116 116 public void setJOSMSelection(Collection<? extends OsmPrimitive> selection) { 117 117 Collection<OsmPrimitive> sel = getSelected(); 118 118 this.selection.clear(); 119 119 if (selection == null) { … … 150 150 public void editLayerChanged(OsmDataLayer oldLayer, OsmDataLayer newLayer) { 151 151 if (newLayer == null) { 152 152 // don't show a JOSM selection if we don't have a data layer 153 153 setJOSMSelection(null); 154 154 } else if (newLayer != layer){ 155 156 157 155 // don't show a JOSM selection if this turn restriction editor doesn't 156 // manipulate data in the current data layer 157 setJOSMSelection(null); 158 158 } else { 159 159 setJOSMSelection(newLayer.data.getSelected()); … … 165 165 /* ------------------------------------------------------------------------ */ 166 166 public void selectionChanged(Collection<? extends OsmPrimitive> newSelection) { 167 168 169 170 171 167 // only update the JOSM selection if it is changed in the same data layer 168 // this turn restriction editor is working on 169 OsmDataLayer layer = Main.main.getEditLayer(); 170 if(layer == null) return; 171 if (layer != this.layer) return; 172 172 setJOSMSelection(newSelection); 173 173 } … … 184 184 if (event.getDataset() != layer.data) return; 185 185 // may influence the display name of primitives, update the data 186 186 update(event.getPrimitives()); 187 187 } 188 188 … … 217 217 /* interface PrimitiveIdListProvider */ 218 218 /* ------------------------------------------------------------------------ */ 219 220 221 222 223 224 225 226 227 219 public List<PrimitiveId> getSelectedPrimitiveIds() { 220 List<PrimitiveId> ret = new ArrayList<PrimitiveId>(getSelected().size()); 221 for(int i=0; i< selection.size(); i++) { 222 if (selectionModel.isSelectedIndex(i)) { 223 ret.add(selection.get(i).getPrimitiveId()); 224 } 225 } 226 return ret; 227 } 228 228 } -
applications/editors/josm/plugins/turnrestrictions/src/org/openstreetmap/josm/plugins/turnrestrictions/editor/JosmSelectionPanel.java
r20586 r23192 42 42 */ 43 43 public class JosmSelectionPanel extends JPanel { 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 setBorder(BorderFactory.createEmptyBorder(5,5,5,5)); 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 SelectionEventManager.getInstance().removeSelectionListener(model); 101 102 103 104 105 106 107 } 108 109 110 111 112 113 114 115 116 44 /** the list view */ 45 private JList lstSelection; 46 /** the model managing the selection */ 47 private JosmSelectionListModel model; 48 49 private CopyAction actCopy; 50 private TransferHandler transferHandler; 51 52 /** 53 * builds the UI for the panel 54 */ 55 protected void build(OsmDataLayer layer) { 56 setLayout(new BorderLayout()); 57 DefaultListSelectionModel selectionModel = new DefaultListSelectionModel(); 58 model = new JosmSelectionListModel(layer,selectionModel); 59 lstSelection = new JList(model); 60 lstSelection.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); 61 lstSelection.setSelectionModel(selectionModel); 62 lstSelection.setCellRenderer(new OsmPrimitivRenderer()); 63 lstSelection.setTransferHandler(transferHandler = new JosmSelectionTransferHandler(model)); 64 lstSelection.setDragEnabled(true); 65 66 add(new JScrollPane(lstSelection), BorderLayout.CENTER); 67 add(new JLabel(tr("Selection")), BorderLayout.NORTH); 68 69 setBorder(BorderFactory.createEmptyBorder(5,5,5,5)); 70 actCopy = new CopyAction(); 71 lstSelection.addMouseListener(new PopupLauncher()); 72 } 73 74 /** 75 * Creates the JOSM selection panel for the selection in an OSM data layer 76 * 77 * @param layer the data layer. Must not be null. 78 * @exception IllegalArgumentException thrown if {@code layer} is null 79 */ 80 public JosmSelectionPanel(OsmDataLayer layer) throws IllegalArgumentException{ 81 CheckParameterUtil.ensureParameterNotNull(layer, "layer"); 82 build(layer); 83 } 84 85 /** 86 * wires the UI as listener to global event sources 87 */ 88 public void wireListeners() { 89 MapView.addEditLayerChangeListener(model); 90 DatasetEventManager.getInstance().addDatasetListener(model, FireMode.IN_EDT); 91 SelectionEventManager.getInstance().addSelectionListener(model, FireMode.IN_EDT_CONSOLIDATED); 92 } 93 94 /** 95 * removes the UI as listener to global event sources 96 */ 97 public void unwireListeners() { 98 MapView.removeEditLayerChangeListener(model); 99 DatasetEventManager.getInstance().removeDatasetListener(model); 100 SelectionEventManager.getInstance().removeSelectionListener(model); 101 } 102 103 class PopupLauncher extends PopupMenuLauncher { 104 @Override 105 public void launch(MouseEvent evt) { 106 new PopupMenu().show(lstSelection, evt.getX(), evt.getY()); 107 } 108 } 109 110 class PopupMenu extends JPopupMenu { 111 public PopupMenu() { 112 JMenuItem item = add(actCopy); 113 item.setTransferHandler(transferHandler); 114 actCopy.setEnabled(!model.getSelected().isEmpty()); 115 } 116 } 117 117 118 119 120 121 122 123 124 125 126 127 118 class CopyAction extends AbstractAction { 119 private Action delegate; 120 121 public CopyAction(){ 122 putValue(NAME, tr("Copy")); 123 putValue(SHORT_DESCRIPTION, tr("Copy to the clipboard")); 124 putValue(SMALL_ICON, ImageProvider.get("copy")); 125 putValue(ACCELERATOR_KEY, Shortcut.getCopyKeyStroke()); 126 delegate = lstSelection.getActionMap().get("copy"); 127 } 128 128 129 130 131 132 133 134 135 136 137 129 public void actionPerformed(ActionEvent e) { 130 delegate.actionPerformed(e); 131 } 132 } 133 134 static private class JosmSelectionTransferHandler extends PrimitiveIdListTransferHandler { 135 public JosmSelectionTransferHandler(PrimitiveIdListProvider provider) { 136 super(provider); 137 } 138 138 139 140 141 142 143 144 145 139 @Override 140 public boolean canImport(JComponent comp, DataFlavor[] transferFlavors) { 141 // the JOSM selection list is read-only. Don't allow to drop or paste 142 // data on it 143 return false; 144 } 145 } 146 146 } -
applications/editors/josm/plugins/turnrestrictions/src/org/openstreetmap/josm/plugins/turnrestrictions/editor/NavigationControler.java
r20586 r23192 2 2 3 3 public interface NavigationControler { 4 5 6 7 8 9 } 10 void gotoBasicEditor(); 11 12 void gotoBasicEditor(BasicEditorFokusTargets focusTarget); 4 public enum BasicEditorFokusTargets { 5 RESTRICION_TYPE, 6 FROM, 7 TO, 8 VIA 9 } 10 void gotoBasicEditor(); 11 void gotoAdvancedEditor(); 12 void gotoBasicEditor(BasicEditorFokusTargets focusTarget); 13 13 } -
applications/editors/josm/plugins/turnrestrictions/src/org/openstreetmap/josm/plugins/turnrestrictions/editor/RelationMemberColumnModel.java
r20724 r23192 14 14 */ 15 15 public class RelationMemberColumnModel extends DefaultTableColumnModel{ 16 17 18 19 20 21 22 col.setPreferredWidth(100); 23 24 25 26 27 28 29 30 31 32 33 addColumn(col);34 35 36 37 38 39 40 41 42 43 44 45 46 16 protected void build() { 17 TableColumn col = new TableColumn(); 18 19 // the role column 20 col.setHeaderValue(tr("Role")); 21 col.setResizable(true); 22 col.setPreferredWidth(100); 23 col.setCellEditor(new MemberRoleCellEditor()); 24 col.setCellRenderer(new RelationMemberRoleCellRenderer()); 25 addColumn(col); 26 27 // column 1 - the member 28 col = new TableColumn(1); 29 col.setHeaderValue(tr("Refers to")); 30 col.setResizable(true); 31 col.setPreferredWidth(300); 32 col.setCellRenderer(new RelationMemberTargetCellRenderer()); 33 addColumn(col); 34 } 35 36 /** 37 * Creates the column model with a given column selection model. 38 * 39 * @param colSelectionModel the column selection model. Must not be null. 40 * @throws IllegalArgumentException thrown if {@code colSelectionModel} is null 41 */ 42 public RelationMemberColumnModel(DefaultListSelectionModel colSelectionModel) throws IllegalArgumentException{ 43 CheckParameterUtil.ensureParameterNotNull(colSelectionModel, "colSelectionModel"); 44 setSelectionModel(colSelectionModel); 45 build(); 46 } 47 47 } -
applications/editors/josm/plugins/turnrestrictions/src/org/openstreetmap/josm/plugins/turnrestrictions/editor/RelationMemberEditorModel.java
r20724 r23192 24 24 import org.openstreetmap.josm.tools.CheckParameterUtil; 25 25 26 public class RelationMemberEditorModel extends AbstractTableModel{ 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 return getPrimitivesWithRole("from"); 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 } 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 if (ids == null) return; 419 420 421 422 423 424 425 426 throw new IllegalArgumentException(tr("Cannot add object ''{0}'' as relation member because it is deleted or invisible in layer ''{1}''", p.getDisplayName(DefaultNameFormatter.getInstance()), layer.getName())); 427 428 429 430 431 432 433 434 435 436 437 438 if (insertPos < 0) insertPos = 0; 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 26 public class RelationMemberEditorModel extends AbstractTableModel{ 27 static private final Logger logger = Logger.getLogger(RelationMemberEditorModel.class.getName()); 28 private final ArrayList<RelationMemberModel> members = new ArrayList<RelationMemberModel>(); 29 private OsmDataLayer layer; 30 private DefaultListSelectionModel rowSelectionModel; 31 private DefaultListSelectionModel colSelectionModel; 32 33 /** 34 * Creates a new model in the context of an {@see OsmDataLayer}. Internally allocates 35 * a row and a column selection model, see {@see #getRowSelectionModel()} and 36 * {@see #getColSelectionModel()}. 37 * 38 * @param layer the data layer. Must not be null. 39 * @exception IllegalArgumentException thrown if layer is null 40 */ 41 public RelationMemberEditorModel(OsmDataLayer layer) throws IllegalArgumentException{ 42 CheckParameterUtil.ensureParameterNotNull(layer, "layer"); 43 this.layer = layer; 44 rowSelectionModel = new DefaultListSelectionModel(); 45 colSelectionModel = new DefaultListSelectionModel(); 46 } 47 48 /** 49 * Creates a new model in the context of an {@see OsmDataLayer} 50 * 51 * @param layer layer the data layer. Must not be null. 52 * @param rowSelectionModel the row selection model. Must not be null. 53 * @param colSelectionModel the column selection model. Must not be null. 54 * @throws IllegalArgumentException thrown if layer is null 55 * @throws IllegalArgumentException thrown if rowSelectionModel is null 56 * @throws IllegalArgumentException thrown if colSelectionModel is null 57 */ 58 public RelationMemberEditorModel(OsmDataLayer layer, DefaultListSelectionModel rowSelectionModel, DefaultListSelectionModel colSelectionModel) throws IllegalArgumentException{ 59 CheckParameterUtil.ensureParameterNotNull(layer, "layer"); 60 CheckParameterUtil.ensureParameterNotNull(rowSelectionModel, "rowSelectionModel"); 61 CheckParameterUtil.ensureParameterNotNull(colSelectionModel, "colSelectionModel"); 62 this.layer = layer; 63 this.rowSelectionModel = rowSelectionModel; 64 this.colSelectionModel = colSelectionModel; 65 } 66 67 /** 68 * Replies the row selection model used in this table model. 69 * 70 * @return the row selection model 71 */ 72 public DefaultListSelectionModel getRowSelectionModel() { 73 return rowSelectionModel; 74 } 75 76 /** 77 * Replies the column selection model used in this table model. 78 * 79 * @return the col selection model 80 */ 81 public DefaultListSelectionModel getColSelectionModel() { 82 return colSelectionModel; 83 } 84 85 /** 86 * Replies the set of {@see OsmPrimitive}s with the role {@code role}. If no 87 * such primitives exists, the empty set is returned. 88 * 89 * @return the set of {@see OsmPrimitive}s with the role {@code role} 90 */ 91 protected Set<OsmPrimitive> getPrimitivesWithRole(String role) { 92 HashSet<OsmPrimitive> ret = new HashSet<OsmPrimitive>(); 93 for (RelationMemberModel rm: members){ 94 if (rm.getRole().equals(role)){ 95 OsmPrimitive p = layer.data.getPrimitiveById(rm.getTarget()); 96 if (p != null){ 97 ret.add(p); 98 } 99 } 100 } 101 return ret; 102 } 103 104 /** 105 * Replies the list of {@see RelationMemberModel}s with the role {@code role}. If no 106 * such primitives exists, the empty set is returned. 107 * 108 * @return the set of {@see RelationMemberModel}s with the role {@code role} 109 */ 110 protected List<RelationMemberModel> getRelationMembersWithRole(String role) { 111 ArrayList<RelationMemberModel> ret = new ArrayList<RelationMemberModel>(); 112 for (RelationMemberModel rm: members){ 113 if (rm.getRole().equals(role)){ 114 ret.add(rm); 115 } 116 } 117 return ret; 118 } 119 120 /** 121 * Removes all members with role {@code role}. 122 * 123 * @param role the role. Ignored if null. 124 * @return true if the list of members was modified; false, otherwise 125 */ 126 protected boolean removeMembersWithRole(String role){ 127 if (role == null) return false; 128 boolean isChanged = false; 129 for(Iterator<RelationMemberModel> it = members.iterator(); it.hasNext(); ){ 130 RelationMemberModel rm = it.next(); 131 if (rm.getRole().equals(role)) { 132 it.remove(); 133 isChanged = true; 134 } 135 } 136 return isChanged; 137 } 138 139 /** 140 * Replies the set of {@see OsmPrimitive}s with the role 'from'. If no 141 * such primitives exists, the empty set is returned. 142 * 143 * @return the set of {@see OsmPrimitive}s with the role 'from' 144 */ 145 public Set<OsmPrimitive> getFromPrimitives() { 146 return getPrimitivesWithRole("from"); 147 } 148 149 /** 150 * Replies the set of {@see OsmPrimitive}s with the role 'to'. If no 151 * such primitives exists, the empty set is returned. 152 * 153 * @return the set of {@see OsmPrimitive}s with the role 'from' 154 */ 155 public Set<OsmPrimitive> getToPrimitives() { 156 return getPrimitivesWithRole("to"); 157 } 158 159 /** 160 * Replies the list of 'via' objects in the order they occur in the 161 * member list. Replies an empty list if no vias exist 162 * 163 * @return 164 */ 165 public List<OsmPrimitive> getVias() { 166 ArrayList<OsmPrimitive> ret = new ArrayList<OsmPrimitive>(); 167 for (RelationMemberModel rm: getRelationMembersWithRole("via")){ 168 ret.add(layer.data.getPrimitiveById(rm.getTarget())); 169 } 170 return ret; 171 } 172 173 /** 174 * Sets the list of vias. Removes all 'vias' if {@code vias} is null. 175 * 176 * null vias are skipped. A via must belong to the dataset of the layer in whose context 177 * this editor is working, otherwise an {@see IllegalArgumentException} is thrown. 178 * 179 * @param vias the vias. 180 * @exception IllegalArgumentException thrown if a via doesn't belong to the dataset of the layer 181 * in whose context this editor is working 182 */ 183 public void setVias(List<OsmPrimitive> vias) throws IllegalArgumentException{ 184 boolean viasDeleted = removeMembersWithRole("via"); 185 if (vias == null || vias.isEmpty()){ 186 if (viasDeleted){ 187 fireTableDataChanged(); 188 } 189 return; 190 } 191 // check vias 192 for (OsmPrimitive via: vias) { 193 if (via == null) continue; 194 if (via.getDataSet() == null || via.getDataSet() != layer.data){ 195 throw new IllegalArgumentException(MessageFormat.format("via object ''{0}'' must belong to dataset of layer ''{1}''", via.getDisplayName(DefaultNameFormatter.getInstance()), layer.getName())); 196 } 197 } 198 // add vias 199 for (OsmPrimitive via: vias) { 200 if (via == null) continue; 201 RelationMemberModel model = new RelationMemberModel("via", via); 202 members.add(model); 203 } 204 fireTableDataChanged(); 205 } 206 207 /** 208 * Sets the turn restriction member with role {@code role}. Removes all 209 * members with role {@code role} if {@code id} is null. 210 * 211 * @param id the id 212 * @return true if the model was modified; false, otherwise 213 */ 214 protected boolean setPrimitiveWithRole(PrimitiveId id, String role){ 215 if (id == null){ 216 return removeMembersWithRole(role); 217 } 218 219 List<RelationMemberModel> fromMembers = getRelationMembersWithRole(role); 220 if (fromMembers.isEmpty()){ 221 RelationMemberModel rm = new RelationMemberModel(role, id); 222 members.add(rm); 223 return true; 224 } else if (fromMembers.size() == 1){ 225 RelationMemberModel rm = fromMembers.get(0); 226 if (!rm.getTarget().equals(id)){ 227 rm.setTarget(id); 228 return true; 229 } 230 return false; 231 } else { 232 removeMembersWithRole(role); 233 RelationMemberModel rm = new RelationMemberModel(role, id); 234 members.add(rm); 235 return true; 236 } 237 } 238 239 /** 240 * Sets the turn restriction member with role 'from'. Removes all 241 * members with role 'from' if {@code id} is null. 242 * 243 * @param id the id 244 */ 245 public void setFromPrimitive(PrimitiveId id){ 246 if (setPrimitiveWithRole(id, "from")) { 247 fireTableDataChanged(); 248 } 249 } 250 251 /** 252 * Sets the turn restriction member with role 'to'. Removes all 253 * members with role 'to' if {@code id} is null. 254 * 255 * @param id the id 256 */ 257 public void setToPrimitive(PrimitiveId id){ 258 if (setPrimitiveWithRole(id, "to")) { 259 fireTableDataChanged(); 260 } 261 } 262 263 /** 264 * Replies the set of {@see OsmPrimitive}s referred to by members in 265 * this model. 266 * 267 * @return the set of {@see OsmPrimitive}s referred to by members in 268 * this model. 269 */ 270 public Set<OsmPrimitive> getMemberPrimitives() { 271 Set<OsmPrimitive> ret = new HashSet<OsmPrimitive>(); 272 for (RelationMemberModel rm: members){ 273 OsmPrimitive p = layer.data.getPrimitiveById(rm.getTarget()); 274 if (p != null) ret.add(p); 275 } 276 return ret; 277 } 278 279 /** 280 * Populates the model with the relation member of a turn restriction. Clears 281 * the model if {@code tr} is null. 282 * 283 * @param tr the turn restriction 284 */ 285 public void populate(Relation tr){ 286 members.clear(); 287 if (tr == null){ 288 fireTableDataChanged(); 289 return; 290 } 291 for(RelationMember rm: tr.getMembers()){ 292 members.add(new RelationMemberModel(rm)); 293 } 294 fireTableDataChanged(); 295 } 296 297 /** 298 * Replaces the member of turn restriction {@code tr} by the relation members currently 299 * edited in this model. 300 * 301 * @param tr the turn restriction. Ignored if null. 302 */ 303 public void applyTo(Relation tr){ 304 if (tr == null) return; 305 List<RelationMember> newMembers = new ArrayList<RelationMember>(); 306 for(RelationMemberModel model: members){ 307 RelationMember rm = new RelationMember(model.getRole(), layer.data.getPrimitiveById(model.getTarget())); 308 newMembers.add(rm); 309 } 310 tr.setMembers(newMembers); 311 } 312 313 /** 314 * Clears the roles of all relation members currently selected in the 315 * table. 316 */ 317 protected void clearSelectedRoles(){ 318 for(int i=0; i < getRowCount();i++){ 319 if (rowSelectionModel.isSelectedIndex(i)) { 320 members.get(i).setRole(""); 321 } 322 } 323 } 324 325 /** 326 * Removes the currently selected rows from the model 327 */ 328 protected void removedSelectedMembers() { 329 for(int i=getRowCount()-1; i >= 0;i--){ 330 if (rowSelectionModel.isSelectedIndex(i)) { 331 members.remove(i); 332 } 333 } 334 } 335 336 /** 337 * Deletes the current selection. 338 * 339 * If only cells in the first column are selected, the roles of the selected 340 * members are reset to the empty string. Otherwise the selected members are 341 * removed from the model. 342 * 343 */ 344 public void deleteSelected() { 345 if (colSelectionModel.isSelectedIndex(0) && !colSelectionModel.isSelectedIndex(1)) { 346 clearSelectedRoles(); 347 } else if (rowSelectionModel.getMinSelectionIndex() >= 0){ 348 removedSelectedMembers(); 349 } 350 fireTableDataChanged(); 351 } 352 353 protected List<Integer> getSelectedIndices() { 354 ArrayList<Integer> ret = new ArrayList<Integer>(); 355 for(int i =0; i < members.size(); i++){ 356 if (rowSelectionModel.isSelectedIndex(i)) 357 ret.add(i); 358 } 359 return ret; 360 } 361 362 public boolean canMoveUp() { 363 List<Integer> sel = getSelectedIndices(); 364 if (sel.isEmpty()) return false; 365 return sel.get(0) > 0; 366 } 367 368 public boolean canMoveDown() { 369 List<Integer> sel = getSelectedIndices(); 370 if (sel.isEmpty()) return false; 371 return sel.get(sel.size()-1) < members.size()-1; 372 } 373 374 public void moveUpSelected() { 375 if (!canMoveUp()) return; 376 List<Integer> sel = getSelectedIndices(); 377 for (int idx: sel){ 378 RelationMemberModel m = members.remove(idx); 379 members.add(idx-1, m); 380 } 381 fireTableDataChanged(); 382 rowSelectionModel.clearSelection(); 383 colSelectionModel.setSelectionInterval(0, 1); 384 for (int idx: sel){ 385 rowSelectionModel.addSelectionInterval(idx-1, idx-1); 386 } 387 } 388 389 public void moveDownSelected() { 390 if (!canMoveDown()) return; 391 List<Integer> sel = getSelectedIndices(); 392 for (int i = sel.size()-1; i>=0;i--){ 393 int idx = sel.get(i); 394 RelationMemberModel m = members.remove(idx); 395 members.add(idx+1, m); 396 } 397 fireTableDataChanged(); 398 rowSelectionModel.clearSelection(); 399 colSelectionModel.setSelectionInterval(0, 1); 400 for (int idx: sel){ 401 rowSelectionModel.addSelectionInterval(idx+1, idx+1); 402 } 403 } 404 405 /** 406 * Inserts a list of new relation members with the empty role for the primitives 407 * with id in {@code ids}. Inserts the new primitives at the position of the first 408 * selected row. If no row is selected, at the end of the list. 409 * 410 * null values are skipped. If there is an id for which there is no primitive in the context 411 * layer, if the primitive is deleted or invisible, an {@see IllegalArgumentException} 412 * is thrown and nothing is inserted. 413 * 414 * @param ids the list of ids. Ignored if null. 415 * @throws IllegalArgumentException thrown if one of the ids can't be inserted 416 */ 417 public void insertMembers(Collection<PrimitiveId> ids) throws IllegalArgumentException { 418 if (ids == null) return; 419 ArrayList<RelationMemberModel> newMembers = new ArrayList<RelationMemberModel>(); 420 for (PrimitiveId id: ids){ 421 OsmPrimitive p = layer.data.getPrimitiveById(id); 422 if (p == null){ 423 throw new IllegalArgumentException(tr("Cannot find object with id ''{0}'' in layer ''{1}''", id.toString(), layer.getName())); 424 } 425 if (p.isDeleted() || ! p.isVisible()) { 426 throw new IllegalArgumentException(tr("Cannot add object ''{0}'' as relation member because it is deleted or invisible in layer ''{1}''", p.getDisplayName(DefaultNameFormatter.getInstance()), layer.getName())); 427 } 428 newMembers.add(new RelationMemberModel("",id)); 429 } 430 if (newMembers.isEmpty()) return; 431 int insertPos = rowSelectionModel.getMinSelectionIndex(); 432 if ( insertPos >=0){ 433 members.addAll(insertPos, newMembers); 434 } else { 435 members.addAll(newMembers); 436 } 437 fireTableDataChanged(); 438 if (insertPos < 0) insertPos = 0; 439 colSelectionModel.setSelectionInterval(0, 1); // select both columns 440 rowSelectionModel.setSelectionInterval(insertPos, insertPos + newMembers.size()-1); 441 } 442 443 public int getColumnCount() { 444 return 2; 445 } 446 447 public int getRowCount() { 448 if (members.size() > 0) return members.size(); 449 450 // we display an empty row if the model is empty because otherwise 451 // we can't drag/drop into the empty table. 452 // FIXME: use JTable.setFillsViewportHeight(boolean) after the migration 453 // to Java 6. 454 return 1; 455 } 456 457 public Object getValueAt(int rowIndex, int columnIndex) { 458 if (members.size() == 0 && rowIndex == 0){ 459 // we display an empty row if the model is empty because otherwise 460 // we can't drag/drop into the empty table. 461 // FIXME: use JTable.setFillsViewportHeight(boolean) after the migration 462 // to Java 6. 463 return null; 464 } 465 switch(columnIndex){ 466 case 0: return members.get(rowIndex).getRole(); 467 case 1: return layer.data.getPrimitiveById(members.get(rowIndex).getTarget()); 468 } 469 return null; 470 } 471 472 @Override 473 public boolean isCellEditable(int rowIndex, int columnIndex) { 474 // we display an empty row if the model is empty because otherwise 475 // we can't drag/drop into the empty table. This row isn't editable 476 // FIXME: use JTable.setFillsViewportHeight(boolean) after the migration 477 // to Java 6. 478 if (members.size() == 0 && rowIndex == 0) return false; 479 480 // otherwise only the column with the member roles is editable 481 return columnIndex == 0; 482 } 483 484 @Override 485 public void setValueAt(Object aValue, int rowIndex, int columnIndex) { 486 if (columnIndex !=0)return; 487 String role = (String)aValue; 488 RelationMemberModel model = members.get(rowIndex); 489 model.setRole(role); 490 fireTableCellUpdated(rowIndex, columnIndex); 491 } 492 492 } -
applications/editors/josm/plugins/turnrestrictions/src/org/openstreetmap/josm/plugins/turnrestrictions/editor/RelationMemberModel.java
r20527 r23192 16 16 */ 17 17 public class RelationMemberModel implements Serializable{ 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 18 private String role; 19 private SimplePrimitiveId target; 20 21 /** 22 * Creates a new relation member model 23 * 24 * @param role the member role. Reset to "" if null. 25 * @param target the id of the target object. Must not be null. 26 * @throws IllegalArgumentException thrown if {@code target} is null 27 */ 28 public RelationMemberModel(String role, PrimitiveId target) throws IllegalArgumentException { 29 CheckParameterUtil.ensureParameterNotNull(target, "target"); 30 this.role = role == null? "" : role; 31 this.target = new SimplePrimitiveId(target.getUniqueId(), target.getType()); 32 } 33 34 /** 35 * Creates a new relation member model from a relation member 36 * 37 * @param member the relation member. Must not be null. 38 * @throws IllegalArgumentException thrown if {@code member} is null 39 */ 40 public RelationMemberModel(RelationMember member) throws IllegalArgumentException{ 41 CheckParameterUtil.ensureParameterNotNull(member, "member"); 42 this.role = member.getRole(); 43 setTarget(member.getMember().getPrimitiveId()); 44 } 45 45 46 47 48 49 50 51 52 53 46 /** 47 * Replies the current role in this model. Never null. 48 * 49 * @return the current role in this model 50 */ 51 public String getRole() { 52 return role; 53 } 54 54 55 56 57 58 59 60 61 62 55 /** 56 * Sets the current role in this model. 57 * 58 * @param role the role. Reset to "" if null. 59 */ 60 public void setRole(String role) { 61 this.role = role == null? "" : role; 62 } 63 63 64 65 66 67 68 69 70 71 64 /** 65 * Replies the id of the target object of this relation member. 66 * 67 * @return the id of the target object of this relation member. 68 */ 69 public PrimitiveId getTarget() { 70 return target; 71 } 72 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 73 /** 74 * Sets the id of the target object. 75 * 76 * @param target the id of the target object. Must not be null. 77 * @throws IllegalArgumentException thrown if {@code target} is null 78 */ 79 public void setTarget(PrimitiveId target) throws IllegalArgumentException{ 80 CheckParameterUtil.ensureParameterNotNull(target, "target"); 81 this.target = new SimplePrimitiveId(target.getUniqueId(), target.getType()); 82 } 83 84 @Override 85 public int hashCode() { 86 final int prime = 31; 87 int result = 1; 88 result = prime * result + ((role == null) ? 0 : role.hashCode()); 89 result = prime * result + ((target == null) ? 0 : target.hashCode()); 90 return result; 91 } 92 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 93 @Override 94 public boolean equals(Object obj) { 95 if (this == obj) 96 return true; 97 if (obj == null) 98 return false; 99 if (getClass() != obj.getClass()) 100 return false; 101 RelationMemberModel other = (RelationMemberModel) obj; 102 if (role == null) { 103 if (other.role != null) 104 return false; 105 } else if (!role.equals(other.role)) 106 return false; 107 if (target == null) { 108 if (other.target != null) 109 return false; 110 } else if (!target.equals(other.target)) 111 return false; 112 return true; 113 } 114 114 } -
applications/editors/josm/plugins/turnrestrictions/src/org/openstreetmap/josm/plugins/turnrestrictions/editor/RelationMemberRoleCellRenderer.java
r20724 r23192 10 10 public class RelationMemberRoleCellRenderer extends DefaultTableCellRenderer{ 11 11 private JLabel mockCell; 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 } 36 37 12 13 public RelationMemberRoleCellRenderer() { 14 mockCell = new JLabel(); 15 mockCell.setText(""); 16 mockCell.setOpaque(true); 17 } 18 19 public Component getTableCellRendererComponent(JTable table, Object value, 20 boolean isSelected, boolean hasFocus, int row, int column) { 21 if (value != null){ 22 return super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column); 23 } 24 25 // FIXME: required to always draw a mock row, even if the table is empty. 26 // Otherwise, drag and drop onto the table fails. 27 // Replace with JTable.setFillsViewportHeight(boolean) after the migration 28 // to Java 6. 29 if (isSelected){ 30 mockCell.setBackground(UIManager.getColor("Table.selectionBackground")); 31 mockCell.setForeground(UIManager.getColor("Table.selectionForeground")); 32 } else { 33 mockCell.setBackground(UIManager.getColor("Panel.background")); 34 mockCell.setForeground(UIManager.getColor("Panel.foreground")); 35 } 36 return mockCell; 37 } 38 38 } -
applications/editors/josm/plugins/turnrestrictions/src/org/openstreetmap/josm/plugins/turnrestrictions/editor/RelationMemberTable.java
r20675 r23192 46 46 */ 47 47 public class RelationMemberTable extends JTable { 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 48 static private final Logger logger = Logger.getLogger(RelationMemberTable.class.getName()); 49 50 private TurnRestrictionEditorModel model; 51 private DeleteAction actDelete; 52 private PasteAction actPaste; 53 private MoveUpAction actMoveUp; 54 private MoveDownAction actMoveDown; 55 private TransferHandler transferHandler; 56 57 public RelationMemberTable(TurnRestrictionEditorModel model) { 58 super( 59 model.getRelationMemberEditorModel(), 60 new RelationMemberColumnModel(model.getRelationMemberEditorModel().getColSelectionModel()), 61 model.getRelationMemberEditorModel().getRowSelectionModel() 62 ); 63 this.model = model; 64 setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); 65 65 setRowSelectionAllowed(true); 66 66 setColumnSelectionAllowed(true); 67 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 } 120 121 122 123 124 125 class PasteAction extends AbstractAction{ 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 } 162 163 class MoveDownAction extends AbstractAction implements ListSelectionListener{ 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 updateEnabledState(); 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 updateEnabledState(); 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 } 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 class RelationMemberTableDropTarget extends DropTarget{ 285 private boolean dropAccepted = false; 286 287 288 289 290 291 292 293 294 295 296 297 298 } 299 300 301 302 303 dtde.acceptDrag(DnDConstants.ACTION_COPY_OR_MOVE); 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 } 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 68 // register the popup menu launcher 69 addMouseListener(new TablePopupLauncher()); 70 71 // transfer handling 72 setDragEnabled(true); 73 setTransferHandler(new RelationMemberTransferHandler()); 74 setDropTarget(new RelationMemberTableDropTarget()); 75 76 // initialize the delete action 77 // 78 actDelete = new DeleteAction(); 79 model.getRelationMemberEditorModel().getRowSelectionModel().addListSelectionListener(actDelete); 80 registerKeyboardAction(actDelete, KeyStroke.getKeyStroke(KeyEvent.VK_DELETE,0), WHEN_ANCESTOR_OF_FOCUSED_COMPONENT); 81 82 // initialize the paste action (will be used in the popup, the action map already includes 83 // the standard paste action for transfer handling) 84 actPaste = new PasteAction(); 85 86 actMoveUp = new MoveUpAction(); 87 model.getRelationMemberEditorModel().getRowSelectionModel().addListSelectionListener(actMoveUp); 88 registerKeyboardAction(actMoveUp,actMoveUp.getKeyStroke(), WHEN_FOCUSED); 89 90 actMoveDown = new MoveDownAction(); 91 model.getRelationMemberEditorModel().getRowSelectionModel().addListSelectionListener(actMoveDown); 92 registerKeyboardAction(actMoveDown, actMoveDown.getKeyStroke(), WHEN_FOCUSED); 93 } 94 95 /** 96 * The action for deleting the selected table cells 97 * 98 */ 99 class DeleteAction extends AbstractAction implements ListSelectionListener{ 100 public DeleteAction() { 101 putValue(NAME, tr("Delete")); 102 putValue(SHORT_DESCRIPTION, tr("Clear the selected roles or delete the selected members")); 103 putValue(SMALL_ICON, ImageProvider.get("deletesmall")); 104 putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_DELETE,0)); 105 updateEnabledState(); 106 } 107 108 public void updateEnabledState() { 109 setEnabled(model.getRelationMemberEditorModel().getRowSelectionModel().getMinSelectionIndex()>=0); 110 } 111 112 public void actionPerformed(ActionEvent e) { 113 model.getRelationMemberEditorModel().deleteSelected(); 114 } 115 116 public void valueChanged(ListSelectionEvent e) { 117 updateEnabledState(); 118 } 119 } 120 121 /** 122 * The action for pasting into the relation member table 123 * 124 */ 125 class PasteAction extends AbstractAction{ 126 public PasteAction() { 127 putValue(NAME, tr("Paste")); 128 putValue(SHORT_DESCRIPTION, tr("Insert new relation members from object in the clipboard")); 129 putValue(SMALL_ICON, ImageProvider.get("paste")); 130 putValue(ACCELERATOR_KEY, Shortcut.getPasteKeyStroke()); 131 updateEnabledState(); 132 } 133 134 public void updateEnabledState() { 135 DataFlavor[] flavors = Toolkit.getDefaultToolkit().getSystemClipboard().getAvailableDataFlavors(); 136 setEnabled(PrimitiveIdListTransferHandler.isSupportedFlavor(flavors)); 137 } 138 139 public void actionPerformed(ActionEvent evt) { 140 // tried to delegate to 'paste' action in the action map of the 141 // table, but didn't work. Now duplicating the logic of importData(...) in 142 // the transfer handler. 143 // 144 Clipboard cp = Toolkit.getDefaultToolkit().getSystemClipboard(); 145 if (!PrimitiveIdListTransferHandler.isSupportedFlavor(cp.getAvailableDataFlavors())) return; 146 try { 147 List<PrimitiveId> ids; 148 ids = (List<PrimitiveId>)cp.getData(PrimitiveIdTransferable.PRIMITIVE_ID_LIST_FLAVOR); 149 try { 150 model.getRelationMemberEditorModel().insertMembers(ids); 151 } catch(IllegalArgumentException e){ 152 e.printStackTrace(); 153 // FIXME: provide user feedback 154 } 155 } catch(IOException e){ 156 e.printStackTrace(); 157 } catch(UnsupportedFlavorException e){ 158 e.printStackTrace(); 159 } 160 } 161 } 162 163 class MoveDownAction extends AbstractAction implements ListSelectionListener{ 164 private KeyStroke keyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, KeyEvent.ALT_DOWN_MASK); 165 public MoveDownAction(){ 166 putValue(NAME, tr("Move down")); 167 putValue(SHORT_DESCRIPTION, tr("Move the selected relation members down by one position")); 168 putValue(ACCELERATOR_KEY,keyStroke); 169 putValue(SMALL_ICON, ImageProvider.get("dialogs", "movedown")); 170 updateEnabledState(); 171 } 172 173 public void actionPerformed(ActionEvent e) { 174 model.getRelationMemberEditorModel().moveDownSelected(); 175 } 176 177 public void updateEnabledState(){ 178 setEnabled(model.getRelationMemberEditorModel().canMoveDown()); 179 } 180 181 public void valueChanged(ListSelectionEvent e) { 182 updateEnabledState(); 183 } 184 public KeyStroke getKeyStroke() { 185 return keyStroke; 186 } 187 } 188 189 class MoveUpAction extends AbstractAction implements ListSelectionListener{ 190 private KeyStroke keyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_UP, KeyEvent.ALT_DOWN_MASK); 191 192 public MoveUpAction() { 193 putValue(NAME, tr("Move up")); 194 putValue(SHORT_DESCRIPTION, tr("Move the selected relation members up by one position")); 195 putValue(ACCELERATOR_KEY,keyStroke); 196 putValue(SMALL_ICON, ImageProvider.get("dialogs", "moveup")); 197 updateEnabledState(); 198 } 199 200 public void actionPerformed(ActionEvent e) { 201 model.getRelationMemberEditorModel().moveUpSelected(); 202 } 203 204 public void updateEnabledState(){ 205 setEnabled(model.getRelationMemberEditorModel().canMoveUp()); 206 } 207 208 public void valueChanged(ListSelectionEvent e) { 209 updateEnabledState(); 210 } 211 public KeyStroke getKeyStroke() { 212 return keyStroke; 213 } 214 } 215 216 class TablePopupLauncher extends PopupMenuLauncher { 217 @Override 218 public void launch(MouseEvent evt) { 219 int row = rowAtPoint(evt.getPoint()); 220 if (getSelectionModel().getMinSelectionIndex() < 0 && row >=0){ 221 getSelectionModel().setSelectionInterval(row, row); 222 getColumnModel().getSelectionModel().setSelectionInterval(0, 1); 223 } 224 new PopupMenu().show(RelationMemberTable.this, evt.getX(), evt.getY()); 225 } 226 } 227 228 class PopupMenu extends JPopupMenu { 229 public PopupMenu() { 230 JMenuItem item = add(actPaste); 231 item.setTransferHandler(transferHandler); 232 actPaste.updateEnabledState(); 233 addSeparator(); 234 add(actDelete); 235 addSeparator(); 236 add(actMoveUp); 237 add(actMoveDown); 238 } 239 } 240 241 /** 242 * The transfer handler for the relation member table. 243 * 244 */ 245 class RelationMemberTransferHandler extends TransferHandler { 246 247 @Override 248 public boolean canImport(JComponent comp, DataFlavor[] transferFlavors) { 249 return PrimitiveIdListTransferHandler.isSupportedFlavor(transferFlavors); 250 } 251 252 @Override 253 public boolean importData(JComponent comp, Transferable t) { 254 try { 255 List<PrimitiveId> ids; 256 ids = (List<PrimitiveId>)t.getTransferData(PrimitiveIdTransferable.PRIMITIVE_ID_LIST_FLAVOR); 257 try { 258 model.getRelationMemberEditorModel().insertMembers(ids); 259 } catch(IllegalArgumentException e){ 260 e.printStackTrace(); 261 // FIXME: provide user feedback 262 return false; 263 } 264 return true; 265 } catch(IOException e){ 266 e.printStackTrace(); 267 } catch(UnsupportedFlavorException e){ 268 e.printStackTrace(); 269 } 270 return false; 271 } 272 273 @Override 274 public int getSourceActions(JComponent c) { 275 return COPY_OR_MOVE; 276 } 277 } 278 279 /** 280 * A custom drop target for the relation member table. During dragging we need to 281 * disable colum selection model. 282 * 283 */ 284 class RelationMemberTableDropTarget extends DropTarget{ 285 private boolean dropAccepted = false; 286 287 /** 288 * Replies true if {@code transferFlavors} includes the data flavor {@see PrimitiveIdTransferable#PRIMITIVE_ID_LIST_FLAVOR}. 289 290 * @param transferFlavors an array of transferFlavors 291 * @return 292 */ 293 protected boolean isSupportedFlavor(DataFlavor[] transferFlavors) { 294 for (DataFlavor df: transferFlavors) { 295 if (df.equals(PrimitiveIdTransferable.PRIMITIVE_ID_LIST_FLAVOR)) return true; 296 } 297 return false; 298 } 299 300 public synchronized void dragEnter(DropTargetDragEvent dtde) { 301 if (isSupportedFlavor(dtde.getCurrentDataFlavors())) { 302 if ((dtde.getSourceActions() & DnDConstants.ACTION_COPY_OR_MOVE) != 0){ 303 dtde.acceptDrag(DnDConstants.ACTION_COPY_OR_MOVE); 304 setColumnSelectionAllowed(false); 305 dropAccepted = true; 306 } else { 307 dtde.rejectDrag(); 308 } 309 } else { 310 dtde.rejectDrag(); 311 } 312 } 313 314 public synchronized void dragExit(DropTargetEvent dte) { 315 setColumnSelectionAllowed(true); 316 dropAccepted = false; 317 } 318 319 @Override 320 public synchronized void dragOver(DropTargetDragEvent dtde) { 321 int row = rowAtPoint(dtde.getLocation()); 322 int selectedRow = getSelectionModel().getMinSelectionIndex(); 323 if (row >= 0 && row != selectedRow){ 324 getSelectionModel().setSelectionInterval(row, row); 325 } 326 } 327 328 public synchronized void drop(DropTargetDropEvent dtde) { 329 try { 330 if (!dropAccepted) return; 331 if ((dtde.getSourceActions() & DnDConstants.ACTION_COPY_OR_MOVE) == 0) { 332 return; 333 } 334 List<PrimitiveId> ids; 335 ids = (List<PrimitiveId>)dtde.getTransferable().getTransferData(PrimitiveIdTransferable.PRIMITIVE_ID_LIST_FLAVOR); 336 try { 337 model.getRelationMemberEditorModel().insertMembers(ids); 338 } catch(IllegalArgumentException e){ 339 e.printStackTrace(); 340 // FIXME: provide user feedback 341 } 342 } catch(IOException e){ 343 e.printStackTrace(); 344 } catch(UnsupportedFlavorException e){ 345 e.printStackTrace(); 346 } finally { 347 setColumnSelectionAllowed(true); 348 } 349 } 350 351 public synchronized void dropActionChanged(DropTargetDragEvent dtde) { 352 if ((dtde.getSourceActions() & DnDConstants.ACTION_COPY_OR_MOVE) == 0) { 353 dtde.rejectDrag(); 354 } else { 355 dtde.acceptDrag(DnDConstants.ACTION_COPY_OR_MOVE); 356 } 357 } 358 } 359 359 } -
applications/editors/josm/plugins/turnrestrictions/src/org/openstreetmap/josm/plugins/turnrestrictions/editor/RelationMemberTargetCellRenderer.java
r20724 r23192 11 11 12 12 public class RelationMemberTargetCellRenderer extends OsmPrimitivRenderer{ 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 } 40 return mockCell; 41 13 static private final Logger logger = Logger.getLogger(RelationMemberTargetCellRenderer.class.getName()); 14 private JLabel mockCell; 15 16 public RelationMemberTargetCellRenderer() { 17 mockCell = new JLabel(); 18 mockCell.setText(""); 19 mockCell.setOpaque(true); 20 } 21 22 @Override 23 public Component getTableCellRendererComponent(JTable table, Object value, 24 boolean isSelected, boolean hasFocus, int row, int column) { 25 if (value != null){ 26 return super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column); 27 } 28 29 // FIXME: required to always draw a mock row, even if the table is empty. 30 // Otherwise, drag and drop onto the table fails. 31 // Replace with JTable.setFillsViewportHeight(boolean) after the migration 32 // to Java 6. 33 if (isSelected){ 34 mockCell.setBackground(UIManager.getColor("Table.selectionBackground")); 35 mockCell.setForeground(UIManager.getColor("Table.selectionForeground")); 36 } else { 37 mockCell.setBackground(UIManager.getColor("Panel.background")); 38 mockCell.setForeground(UIManager.getColor("Panel.foreground")); 39 } 40 return mockCell; 41 } 42 42 } -
applications/editors/josm/plugins/turnrestrictions/src/org/openstreetmap/josm/plugins/turnrestrictions/editor/TurnRestrictionComboBox.java
r20666 r23192 9 9 */ 10 10 public class TurnRestrictionComboBox extends JComboBox{ 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 11 12 /** 13 * Constructor 14 * 15 * @param model the combo box model. Must not be null. 16 */ 17 public TurnRestrictionComboBox(TurnRestrictionComboBoxModel model){ 18 super(model); 19 setEditable(false); 20 setRenderer(new TurnRestrictionTypeRenderer()); 21 } 22 23 /** 24 * Replies the turn restriction combo box model 25 * 26 * @return the turn restriction combo box model 27 */ 28 public TurnRestrictionComboBoxModel getTurnRestrictionComboBoxModel() { 29 return (TurnRestrictionComboBoxModel)getModel(); 30 } 31 32 /** 33 * Initializes the set of icons used from the preference key 34 * {@see PreferenceKeys#ROAD_SIGNS}. 35 * 36 * @param prefs the JOSM preferences 37 */ 38 public void initIconSetFromPreferences(Preferences prefs){ 39 TurnRestrictionTypeRenderer renderer = (TurnRestrictionTypeRenderer)getRenderer(); 40 renderer.initIconSetFromPreferences(prefs); 41 repaint(); 42 } 43 43 } -
applications/editors/josm/plugins/turnrestrictions/src/org/openstreetmap/josm/plugins/turnrestrictions/editor/TurnRestrictionComboBoxModel.java
r20606 r23192 21 21 */ 22 22 public class TurnRestrictionComboBoxModel implements ComboBoxModel, Observer{ 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 } 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 23 static private final Logger logger = Logger.getLogger(TurnRestrictionComboBoxModel.class.getName()); 24 25 private TurnRestrictionEditorModel model; 26 final private List<Object> values = new ArrayList<Object>(); 27 private String selectedTagValue = null; 28 private final transient EventListenerList listeners = new EventListenerList(); 29 30 /** 31 * Populates the model with the list of standard values. If the 32 * data contains a non-standard value it is displayed in the combo 33 * box as an additional element. 34 */ 35 protected void populate() { 36 values.clear(); 37 for (TurnRestrictionType type: TurnRestrictionType.values()) { 38 values.add(type); 39 } 40 41 String tagValue = model.getRestrictionTagValue(); 42 if (tagValue.trim().equals("")) { 43 selectedTagValue = null; 44 } else { 45 TurnRestrictionType type = TurnRestrictionType.fromTagValue(tagValue); 46 if (type == null) { 47 values.add(0, tagValue); 48 selectedTagValue = tagValue; 49 } else { 50 selectedTagValue = type.getTagValue(); 51 } 52 } 53 fireContentsChanged(); 54 } 55 56 /** 57 * Creates the combo box model. 58 * 59 * @param model the turn restriction editor model. Must not be null. 60 */ 61 public TurnRestrictionComboBoxModel(TurnRestrictionEditorModel model){ 62 CheckParameterUtil.ensureParameterNotNull(model, "model"); 63 this.model = model; 64 model.addObserver(this); 65 populate(); 66 } 67 67 68 69 70 71 72 68 public Object getSelectedItem() { 69 TurnRestrictionType type = TurnRestrictionType.fromTagValue(selectedTagValue); 70 if (type != null) return type; 71 return selectedTagValue; 72 } 73 73 74 75 76 77 78 79 80 81 82 74 public void setSelectedItem(Object anItem) { 75 String tagValue = null; 76 if (anItem instanceof String) { 77 tagValue = (String)anItem; 78 } else if (anItem instanceof TurnRestrictionType){ 79 tagValue = ((TurnRestrictionType)anItem).getTagValue(); 80 } 81 model.setRestrictionTagValue(tagValue); 82 } 83 83 84 85 86 84 public Object getElementAt(int index) { 85 return values.get(index); 86 } 87 87 88 89 90 91 92 93 listeners.add(ListDataListener.class, l); 94 95 96 97 listeners.remove(ListDataListener.class, l); 98 99 100 101 102 103 104 105 106 107 108 109 public void update(Observable o, Object arg) { 110 111 112 113 114 115 116 117 118 119 120 88 public int getSize() { 89 return values.size(); 90 } 91 92 public void addListDataListener(ListDataListener l) { 93 listeners.add(ListDataListener.class, l); 94 } 95 96 public void removeListDataListener(ListDataListener l) { 97 listeners.remove(ListDataListener.class, l); 98 } 99 100 protected void fireContentsChanged() { 101 for(ListDataListener l: listeners.getListeners(ListDataListener.class)) { 102 l.contentsChanged(new ListDataEvent(this, ListDataEvent.CONTENTS_CHANGED, 0, getSize())); 103 } 104 } 105 106 /* ------------------------------------------------------------------------------------ */ 107 /* interface Observer */ 108 /* ------------------------------------------------------------------------------------ */ 109 public void update(Observable o, Object arg) { 110 String tagValue = model.getRestrictionTagValue(); 111 if (tagValue == null && selectedTagValue != null) { 112 populate(); 113 } else if (tagValue != null && selectedTagValue == null){ 114 populate(); 115 } else if (tagValue != null) { 116 if (!tagValue.equals(selectedTagValue)) { 117 populate(); 118 } 119 } 120 } 121 121 } -
applications/editors/josm/plugins/turnrestrictions/src/org/openstreetmap/josm/plugins/turnrestrictions/editor/TurnRestrictionEditor.java
r20916 r23192 58 58 59 59 public class TurnRestrictionEditor extends JDialog implements NavigationControler{ 60 61 60 final private static Logger logger = Logger.getLogger(TurnRestrictionEditor.class.getName()); 61 62 62 /** the property name for the current turn restriction 63 63 * @see #setRelation(Relation) … … 84 84 /** the data layer the turn restriction belongs to */ 85 85 private OsmDataLayer layer; 86 86 87 87 private JosmSelectionPanel pnlJosmSelection; 88 88 private BasicEditorPanel pnlBasicEditor; … … 114 114 */ 115 115 protected JPanel buildJOSMSelectionPanel() { 116 117 116 pnlJosmSelection = new JosmSelectionPanel(layer); 117 return pnlJosmSelection; 118 118 } 119 119 … … 125 125 */ 126 126 protected JPanel buildEditorPanel() { 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 127 JPanel pnl = new JPanel(new BorderLayout()); 128 tpEditors = new JTabbedPane(); 129 JScrollPane pane = new JScrollPane(pnlBasicEditor =new BasicEditorPanel(editorModel)); 130 pane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); 131 pane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED); 132 tpEditors.add(pane); 133 tpEditors.setTitleAt(0, tr("Basic")); 134 tpEditors.setToolTipTextAt(0, tr("Edit basic attributes of a turn restriction")); 135 136 tpEditors.add(pnlAdvancedEditor = new AdvancedEditorPanel(editorModel)); 137 tpEditors.setTitleAt(1, tr("Advanced")); 138 tpEditors.setToolTipTextAt(1, tr("Edit the raw tags and members of this turn restriction")); 139 140 tpEditors.add(pnlIssuesView = new IssuesView(editorModel.getIssuesModel())); 141 tpEditors.setTitleAt(2, tr("Errors/Warnings")); 142 tpEditors.setToolTipTextAt(2, tr("Show errors and warnings related to this turn restriction")); 143 144 pnl.add(tpEditors, BorderLayout.CENTER); 145 return pnl; 146 146 } 147 147 … … 153 153 */ 154 154 protected JPanel buildContentPanel() { 155 156 157 158 159 155 JPanel pnl = new JPanel(new BorderLayout()); 156 final JSplitPane sp = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT); 157 pnl.add(sp, BorderLayout.CENTER); 158 sp.setLeftComponent(buildEditorPanel()); 159 sp.setRightComponent(buildJOSMSelectionPanel()); 160 160 addWindowListener(new WindowAdapter() { 161 161 @Override … … 167 167 }); 168 168 169 169 return pnl; 170 170 } 171 171 … … 197 197 * builds the UI 198 198 */ 199 protected void build() { 200 201 202 203 204 c.add(buildContentPanel(), BorderLayout.CENTER);205 206 207 208 setSize(600,600);199 protected void build() { 200 editorModel = new TurnRestrictionEditorModel(getLayer(), this); 201 Container c = getContentPane(); 202 c.setLayout(new BorderLayout()); 203 c.add(buildToolBar(), BorderLayout.NORTH); 204 c.add(buildContentPanel(), BorderLayout.CENTER); 205 c.add(buildOkCancelButtonPanel(), BorderLayout.SOUTH); 206 207 editorModel.getIssuesModel().addObserver(new IssuesModelObserver()); 208 setSize(600,600); 209 209 } 210 211 210 211 /** 212 212 * Creates a new turn restriction editor 213 213 * … … 216 216 * @throws IllegalArgumentException thrown if layer is null 217 217 */ 218 219 220 221 222 218 public TurnRestrictionEditor(Component owner, OsmDataLayer layer) { 219 this(owner, layer, null); 220 } 221 222 /** 223 223 * Creates a new turn restriction editor 224 224 * … … 229 229 */ 230 230 public TurnRestrictionEditor(Component owner, OsmDataLayer layer, Relation turnRestriction) throws IllegalArgumentException{ 231 231 super(JOptionPane.getFrameForComponent(owner),false /* not modal */); 232 232 CheckParameterUtil.ensureParameterNotNull(layer, "layer"); 233 233 this.layer = layer; … … 260 260 protected void setTurnRestriction(Relation turnRestriction) { 261 261 if (turnRestriction == null) { 262 262 editorModel.populate(new Relation()); 263 263 } else if (turnRestriction.getDataSet() == null || turnRestriction.getDataSet() == getLayer().data) { 264 264 editorModel.populate(turnRestriction); 265 265 } else { 266 266 throw new IllegalArgumentException(MessageFormat.format("turnRestriction must belong to layer ''{0}''", getLayer().getName())); 267 267 } 268 268 setTurnRestrictionSnapshot(turnRestriction == null ? null : new Relation(turnRestriction)); … … 332 332 */ 333 333 public TurnRestrictionEditorModel getModel() { 334 334 return editorModel; 335 335 } 336 336 337 337 public void setVisible(boolean visible) { 338 339 340 341 342 343 344 345 346 347 348 349 350 351 338 if (visible && ! isVisible()) { 339 pnlJosmSelection.wireListeners(); 340 editorModel.registerAsEventListener(); 341 Main.pref.addPreferenceChangeListener(this.preferenceChangeHandler = new PreferenceChangeHandler()); 342 pnlBasicEditor.initIconSetFromPreferences(Main.pref); 343 } else if (!visible && isVisible()) { 344 pnlJosmSelection.unwireListeners(); 345 editorModel.unregisterAsEventListener(); 346 Main.pref.removePreferenceChangeListener(preferenceChangeHandler); 347 } 348 super.setVisible(visible); 349 if (!visible){ 350 dispose(); 351 } 352 352 } 353 353 … … 371 371 /* ----------------------------------------------------------------------- */ 372 372 public void gotoBasicEditor() { 373 374 373 tpEditors.setSelectedIndex(0); 374 } 375 375 376 376 public void gotoAdvancedEditor() { 377 378 379 380 381 382 383 384 385 377 tpEditors.setSelectedIndex(1); 378 } 379 380 public void gotoBasicEditor(BasicEditorFokusTargets focusTarget) { 381 tpEditors.setSelectedIndex(0); 382 pnlBasicEditor.requestFocusFor(focusTarget); 383 } 384 385 /** 386 386 * The abstract base action for applying the updates of a turn restriction 387 387 * to the dataset. 388 388 */ 389 abstract class SavingAction extends AbstractAction { 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 return ret == 0 /* OK */;433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 protected boolean confirmSaveTurnRestrictionWithDeletePrimitives(List<RelationMember> deletedMembers) {482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 );525 526 527 389 abstract class SavingAction extends AbstractAction { 390 protected boolean confirmSaveDespiteOfErrorsAndWarnings(){ 391 int numErrors = editorModel.getIssuesModel().getNumErrors(); 392 int numWarnings = editorModel.getIssuesModel().getNumWarnings(); 393 if (numErrors + numWarnings == 0) return true; 394 395 StringBuffer sb = new StringBuffer(); 396 sb.append("<html>"); 397 sb.append(trn( 398 "There is still an unresolved error or warning identified for this turn restriction. " 399 + "You are recommended to resolve this issue first.", 400 "There are still {0} errors and/or warnings identified for this turn restriction. " 401 + "You are recommended to resolve these issues first.", 402 numErrors + numWarnings, 403 numErrors + numWarnings 404 )); 405 sb.append("<br>"); 406 sb.append(tr("Do you want to save anyway?")); 407 ButtonSpec[] options = new ButtonSpec[] { 408 new ButtonSpec( 409 tr("Yes, save anyway"), 410 ImageProvider.get("ok"), 411 tr("Save the turn restriction despite of errors and/or warnings"), 412 null // no specific help topic 413 ), 414 new ButtonSpec( 415 tr("No, resolve issues first"), 416 ImageProvider.get("cancel"), 417 tr("Cancel saving and start resolving pending issues first"), 418 null // no specific help topic 419 ) 420 }; 421 422 int ret = HelpAwareOptionPane.showOptionDialog( 423 JOptionPane.getFrameForComponent(TurnRestrictionEditor.this), 424 sb.toString(), 425 tr("Pending errors and warnings"), 426 JOptionPane.WARNING_MESSAGE, 427 null, // no special icon 428 options, 429 options[1], // cancel is default operation 430 HelpUtil.ht("/Plugins/turnrestrictions#PendingErrorsAndWarnings") 431 ); 432 return ret == 0 /* OK */; 433 } 434 435 /** 436 * Replies the list of relation members in {@code r} which refer to 437 * a deleted or invisible primitives. 438 * 439 * @param r the relation 440 * @return the list of relation members in {@code r} which refer to 441 * a deleted or invisible member 442 */ 443 protected List<RelationMember> getDeletedRelationMembers(Relation r) { 444 List<RelationMember> ret = new ArrayList<RelationMember>(); 445 for(RelationMember rm: r.getMembers()) { 446 if (rm.getMember().isDeleted() || !rm.getMember().isVisible()) { 447 ret.add(rm); 448 } 449 } 450 return ret; 451 } 452 453 /** 454 * Removes all members referring to deleted or invisible primitives 455 * from the turn restriction {@code tr}. 456 * 457 * @param tr the turn restriction 458 */ 459 protected void removeDeletedMembers(Relation tr) { 460 List<RelationMember> members = tr.getMembers(); 461 for(Iterator<RelationMember> it = members.iterator(); it.hasNext();) { 462 RelationMember rm = it.next(); 463 if (rm.getMember().isDeleted() || !rm.getMember().isVisible()) { 464 it.remove(); 465 } 466 } 467 tr.setMembers(members); 468 } 469 470 /** 471 * Asks the user how to proceed if a turn restriction refers to deleted or invisible 472 * primitives. 473 * 474 * If this method returns true the respective members should be removed and the turn 475 * restriction should be saved anyway. If it replies false, the turn restriction must not 476 * be saved. 477 * 478 * @param deletedMembers the list of members referring to deleted or invisible primitives 479 * @return the confirmation 480 */ 481 protected boolean confirmSaveTurnRestrictionWithDeletePrimitives(List<RelationMember> deletedMembers) { 482 StringBuffer sb = new StringBuffer(); 483 sb.append("<html>"); 484 sb.append(trn("This turn restriction refers to an object which was deleted outside " 485 + "of this turn restriction editor:", 486 "This turn restriction refers to {0} which were deleted outside " 487 + "of this turn restriction editor:", deletedMembers.size(), deletedMembers.size())); 488 sb.append("<ul>"); 489 for(RelationMember rm: deletedMembers){ 490 sb.append("<li>"); 491 if (!rm.getRole().equals("")) { 492 sb.append(rm.getRole()).append(": "); 493 } 494 sb.append(rm.getMember().getDisplayName(DefaultNameFormatter.getInstance())); 495 sb.append("</li>"); 496 } 497 sb.append(tr("Updates to this turn restriction can''t be saved unless deleted members are removed.<br>" 498 + "How to you want to proceed?")); 499 500 ButtonSpec[] options = new ButtonSpec[] { 501 new ButtonSpec( 502 tr("Remove deleted members and save"), 503 ImageProvider.get("OK"), 504 tr("Remove deleted members and save"), 505 null 506 ), 507 new ButtonSpec( 508 tr("Cancel and return to editor"), 509 ImageProvider.get("cancel"), 510 tr("Cancel and return to editor"), 511 null 512 ) 513 }; 514 515 int ret = HelpAwareOptionPane.showOptionDialog( 516 TurnRestrictionEditor.this, 517 sb.toString(), 518 tr("Deleted members in turn restriction"), 519 JOptionPane.WARNING_MESSAGE, 520 null, // no special icon 521 options, 522 options[1], // cancel is default 523 null // FIXME: provide help topic 524 ); 525 return ret == 0 /* OK button */; 526 } 527 528 528 /** 529 529 * apply updates to a new turn restriction 530 530 */ 531 protected boolean applyNewTurnRestriction() { 531 protected boolean applyNewTurnRestriction() { 532 532 Relation newTurnRestriction = new Relation(); 533 533 editorModel.apply(newTurnRestriction); … … 541 541 List<RelationMember> deletedMembers = getDeletedRelationMembers(newTurnRestriction); 542 542 if (!deletedMembers.isEmpty()) { 543 544 545 546 543 if (!confirmSaveTurnRestrictionWithDeletePrimitives(deletedMembers)) { 544 return false; 545 } 546 removeDeletedMembers(newTurnRestriction); 547 547 } 548 548 … … 576 576 * outside of the turn restriction editor. 577 577 */ 578 protected void applyExistingNonConflictingTurnRestriction() { 578 protected void applyExistingNonConflictingTurnRestriction() { 579 579 if (getTurnRestriction().getDataSet() == null) { 580 581 580 editorModel.apply(getTurnRestriction()); 581 Main.main.undoRedo.add(new AddCommand(getTurnRestriction())); 582 582 } else { 583 583 Relation toUpdate = new Relation(getTurnRestriction()); 584 584 editorModel.apply(toUpdate); 585 585 Main.main.undoRedo.add(new ChangeCommand(getTurnRestriction(), toUpdate)); 586 586 } 587 587 // this will refresh the snapshot and update the dialog title … … 646 646 647 647 public void run() { 648 649 650 651 648 if (!confirmSaveDespiteOfErrorsAndWarnings()){ 649 tpEditors.setSelectedIndex(2); // show the errors and warnings 650 return; 651 } 652 652 if (getTurnRestriction() == null) { 653 653 applyNewTurnRestriction(); … … 658 658 editorModel.apply(toUpdate); 659 659 if (TurnRestrictionEditorModel.hasSameMembersAndTags(toUpdate, getTurnRestriction())) 660 661 660 // nothing to update 661 return; 662 662 663 663 if (isDirtyTurnRestriction()) { … … 689 689 690 690 public void run() { 691 692 693 694 691 if (!confirmSaveDespiteOfErrorsAndWarnings()){ 692 tpEditors.setSelectedIndex(2); // show the errors and warnings 693 return; 694 } 695 695 if (getTurnRestriction() == null) { 696 696 // it's a new turn restriction. Try to save it and close the dialog 697 697 if (applyNewTurnRestriction()) { 698 698 setVisible(false); 699 699 } 700 700 return; … … 704 704 editorModel.apply(toUpdate); 705 705 if (TurnRestrictionEditorModel.hasSameMembersAndTags(toUpdate, getTurnRestriction())){ 706 707 708 706 // nothing to update 707 setVisible(false); 708 return; 709 709 } 710 710 711 711 if (isDirtyTurnRestriction()) { 712 713 712 // the turn restriction this editor is working on has changed outside 713 // of the editor. 714 714 if (confirmClosingBecauseOfDirtyState()) { 715 715 if (getLayer().getConflicts().hasConflictForMy(getTurnRestriction())) { … … 750 750 751 751 class DeleteAction extends AbstractAction implements PropertyChangeListener{ 752 753 754 755 756 757 758 759 protected void updateEnabledState() {760 761 762 763 764 765 766 767 752 public DeleteAction() { 753 putValue(NAME, tr("Delete")); 754 putValue(SHORT_DESCRIPTION, tr("Delete this turn restriction")); 755 putValue(SMALL_ICON, ImageProvider.get("dialogs", "delete")); 756 updateEnabledState(); 757 } 758 759 protected void updateEnabledState() { 760 Relation tr = getTurnRestriction(); 761 setEnabled(tr != null && tr.getDataSet() != null); 762 } 763 764 public void actionPerformed(ActionEvent e) { 765 Relation tr = getTurnRestriction(); 766 if (tr == null || tr.getDataSet() == null) return; 767 org.openstreetmap.josm.actions.mapmode.DeleteAction.deleteRelation( 768 768 getLayer(), 769 769 tr 770 770 ); 771 772 773 774 775 776 777 778 771 setVisible(false); 772 } 773 774 public void propertyChange(PropertyChangeEvent evt) { 775 if (evt.getPropertyName().equals(TURN_RESTRICION_PROP)){ 776 updateEnabledState(); 777 } 778 } 779 779 } 780 780 781 781 class SelectAction extends AbstractAction implements PropertyChangeListener{ 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 782 public SelectAction() { 783 putValue(NAME, tr("Select")); 784 putValue(SHORT_DESCRIPTION, tr("Select this turn restriction")); 785 putValue(SMALL_ICON, ImageProvider.get("dialogs", "select")); 786 updateEnabledState(); 787 } 788 789 protected void updateEnabledState() { 790 Relation tr = getTurnRestriction(); 791 setEnabled(tr != null && tr.getDataSet() != null); 792 } 793 794 public void actionPerformed(ActionEvent e) { 795 Relation tr = getTurnRestriction(); 796 if (tr == null || tr.getDataSet() == null) return; 797 getLayer().data.setSelected(tr); 798 } 799 800 public void propertyChange(PropertyChangeEvent evt) { 801 if (evt.getPropertyName().equals(TURN_RESTRICION_PROP)){ 802 updateEnabledState(); 803 } 804 } 805 805 } 806 806 807 807 class ZoomToAction extends AbstractAction implements PropertyChangeListener{ 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 getLayer().data.setSelected(tr);827 828 829 830 831 832 833 834 808 public ZoomToAction() { 809 putValue(NAME, tr("Zoom to")); 810 putValue(SHORT_DESCRIPTION, tr("Activate the layer this turn restriction belongs to and zoom to it")); 811 putValue(SMALL_ICON, ImageProvider.get("dialogs/autoscale", "data")); 812 updateEnabledState(); 813 } 814 815 protected void updateEnabledState() { 816 Relation tr = getTurnRestriction(); 817 setEnabled(tr != null && tr.getDataSet() != null); 818 } 819 820 public void actionPerformed(ActionEvent e) { 821 if (Main.main.getActiveLayer() != getLayer()){ 822 Main.map.mapView.setActiveLayer(getLayer()); 823 } 824 Relation tr = getTurnRestriction(); 825 if (tr == null || tr.getDataSet() == null) return; 826 getLayer().data.setSelected(tr); 827 AutoScaleAction.zoomToSelection(); 828 } 829 830 public void propertyChange(PropertyChangeEvent evt) { 831 if (evt.getPropertyName().equals(TURN_RESTRICION_PROP)){ 832 updateEnabledState(); 833 } 834 } 835 835 } 836 836 837 837 class IssuesModelObserver implements Observer { 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 } 838 public void update(Observable o, Object arg) { 839 int numWarnings = editorModel.getIssuesModel().getNumWarnings(); 840 int numErrors = editorModel.getIssuesModel().getNumErrors(); 841 String warningText = null; 842 if (numWarnings > 0){ 843 warningText = trn("{0} warning", "{0} warnings", numWarnings, numWarnings); 844 } 845 String errorText = null; 846 if (numErrors > 0){ 847 errorText = trn("{0} error", "{0} errors", numErrors, numErrors); 848 } 849 String title = ""; 850 if (errorText != null) { 851 title += errorText; 852 } 853 if (warningText != null){ 854 if (title.length() > 0){ 855 title += "/"; 856 } 857 title += warningText; 858 } 859 if (title.length() == 0){ 860 title = tr("no issues"); 861 } 862 tpEditors.setTitleAt(2, title); 863 tpEditors.setEnabledAt(2, numWarnings + numErrors > 0); 864 } 865 865 } 866 866 … … 874 874 * 875 875 */ 876 class PreferenceChangeHandler implements PreferenceChangedListener { 877 878 879 880 881 public void preferenceChanged(PreferenceChangeEvent evt) { 882 883 884 885 886 } 887 876 class PreferenceChangeHandler implements PreferenceChangedListener { 877 public void refreshIconSet() { 878 pnlBasicEditor.initIconSetFromPreferences(Main.pref); 879 } 880 881 public void preferenceChanged(PreferenceChangeEvent evt) { 882 if (evt.getKey().equals(PreferenceKeys.ROAD_SIGNS)){ 883 refreshIconSet(); 884 } else if (evt.getKey().equals(PreferenceKeys.SHOW_VIAS_IN_BASIC_EDITOR)) { 885 pnlBasicEditor.initViasVisibilityFromPreferences(Main.pref); 886 } 887 } 888 888 } 889 889 } -
applications/editors/josm/plugins/turnrestrictions/src/org/openstreetmap/josm/plugins/turnrestrictions/editor/TurnRestrictionEditorManager.java
r20489 r23192 23 23 */ 24 24 public class TurnRestrictionEditorManager extends WindowAdapter implements MapView.LayerChangeListener{ 25 25 static private final Logger logger = Logger.getLogger(TurnRestrictionEditorManager.class.getName()); 26 26 27 27 /** keeps track of open relation editors */ … … 55 55 56 56 @Override 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 57 public int hashCode() { 58 final int prime = 31; 59 int result = 1; 60 result = prime * result + ((layer == null) ? 0 : layer.hashCode()); 61 result = prime * result 62 + ((primitiveId == null) ? 0 : primitiveId.hashCode()); 63 return result; 64 } 65 66 @Override 67 public boolean equals(Object obj) { 68 if (this == obj) 69 return true; 70 if (obj == null) 71 return false; 72 if (getClass() != obj.getClass()) 73 return false; 74 DialogContext other = (DialogContext) obj; 75 if (layer == null) { 76 if (other.layer != null) 77 return false; 78 } else if (!layer.equals(other.layer)) 79 return false; 80 if (primitiveId == null) { 81 if (other.primitiveId != null) 82 return false; 83 } else if (!primitiveId.equals(other.primitiveId)) 84 return false; 85 return true; 86 } 87 88 public boolean matchesLayer(OsmDataLayer layer) { 89 89 if (layer == null) return false; 90 90 return this.layer.equals(layer); … … 187 187 @Override 188 188 public void windowClosed(WindowEvent e) { 189 189 TurnRestrictionEditor editor = (TurnRestrictionEditor)e.getWindow(); 190 190 DialogContext context = null; 191 191 for (DialogContext c : openDialogs.keySet()) { … … 200 200 } 201 201 202 202 /** 203 203 * Positions an {@see TurnRestrictionEditor} centered on the screen 204 204 * … … 286 286 Entry<DialogContext,TurnRestrictionEditor> entry = it.next(); 287 287 if (entry.getKey().matchesLayer(dataLayer)) { 288 288 TurnRestrictionEditor editor = entry.getValue(); 289 289 it.remove(); 290 290 editor.setVisible(false); -
applications/editors/josm/plugins/turnrestrictions/src/org/openstreetmap/josm/plugins/turnrestrictions/editor/TurnRestrictionEditorModel.java
r20735 r23192 40 40 */ 41 41 public class TurnRestrictionEditorModel extends Observable implements DataSetListener{ 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 } 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 throw new IllegalStateException(MessageFormat.format("didn''t find way with id {0} in layer ''{1}''", wayId, layer.getName())); 133 134 135 } 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 if (turnRestriction.getDataSet() != null && turnRestriction.getDataSet() != layer.data) { 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 CheckParameterUtil.ensureParameterNotNull(turnRestriction, "turnRestriction"); 212 213 214 215 memberModel.applyTo(turnRestriction); 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 tagEditorModel.delete("restriction"); 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 notifyObservers(); 358 359 return; 360 361 362 363 364 365 366 367 368 369 370 371 372 } 373 374 375 376 377 /* ----------------------------------------------------------------------------------------- */ 378 379 380 381 382 383 384 385 386 387 388 389 390 notifyObservers(); 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 } 425 } 426 427 428 429 430 431 } 432 433 434 435 436 /* ----------------------------------------------------------------------------------------- */ 437 438 439 440 441 } 442 42 static private final Logger logger = Logger.getLogger(TurnRestrictionEditorModel.class.getName()); 43 44 /** 45 * Replies true if {@code tp1} and {@code tp2} have the same tags and 46 * the same members 47 * 48 * @param tp1 a turn restriction. Must not be null. 49 * @param tp2 a turn restriction . Must not be null. 50 * @return true if {@code tp1} and {@code tp2} have the same tags and 51 * the same members 52 * @throws IllegalArgumentException thrown if {@code tp1} is null 53 * @throws IllegalArgumentException thrown if {@code tp2} is null 54 */ 55 static public boolean hasSameMembersAndTags(Relation tp1, Relation tp2) throws IllegalArgumentException { 56 CheckParameterUtil.ensureParameterNotNull(tp1, "tp1"); 57 CheckParameterUtil.ensureParameterNotNull(tp2, "tp2"); 58 if (!TagCollection.from(tp1).asSet().equals(TagCollection.from(tp2).asSet())) return false; 59 if (tp1.getMembersCount() != tp2.getMembersCount()) return false; 60 for(int i=0; i < tp1.getMembersCount();i++){ 61 if (!tp1.getMember(i).equals(tp2.getMember(i))) return false; 62 } 63 return true; 64 } 65 66 private OsmDataLayer layer; 67 private final TagEditorModel tagEditorModel = new TagEditorModel(); 68 private RelationMemberEditorModel memberModel; 69 private IssuesModel issuesModel; 70 private NavigationControler navigationControler; 71 72 /** 73 * Creates a model in the context of a {@see OsmDataLayer} 74 * 75 * @param layer the layer. Must not be null. 76 * @param navigationControler control to direct the user to specific UI components. Must not be null 77 * @throws IllegalArgumentException thrown if {@code layer} is null 78 */ 79 public TurnRestrictionEditorModel(OsmDataLayer layer, NavigationControler navigationControler) throws IllegalArgumentException{ 80 CheckParameterUtil.ensureParameterNotNull(layer, "layer"); 81 CheckParameterUtil.ensureParameterNotNull(navigationControler, "navigationControler"); 82 this.layer = layer; 83 this.navigationControler = navigationControler; 84 memberModel = new RelationMemberEditorModel(layer); 85 memberModel.addTableModelListener(new RelationMemberModelListener()); 86 issuesModel = new IssuesModel(this); 87 addObserver(issuesModel); 88 tagEditorModel.addTableModelListener(new TagEditorModelObserver()); 89 } 90 91 /** 92 * Sets the way participating in the turn restriction in a given role. 93 * 94 * @param role the role. Must not be null. 95 * @param way the way which participates in the turn restriction in the respective role. 96 * null, to remove the way with the given role. 97 * @exception IllegalArgumentException thrown if role is null 98 */ 99 public void setTurnRestrictionLeg(TurnRestrictionLegRole role, Way way) { 100 CheckParameterUtil.ensureParameterNotNull(role, "role"); 101 switch(role){ 102 case FROM: 103 memberModel.setFromPrimitive(way); 104 break; 105 case TO: 106 memberModel.setToPrimitive(way); 107 break; 108 } 109 } 110 111 /** 112 * Sets the way participating in the turn restriction in a given role. 113 * 114 * @param role the role. Must not be null. 115 * @param wayId the id of the way to set 116 * @exception IllegalArgumentException thrown if role is null 117 * @exception IllegalArgumentException thrown if wayId != null isn't the id of a way 118 * @exception IllegalStateException thrown the no way with this id was found in the dataset 119 */ 120 public void setTurnRestrictionLeg(TurnRestrictionLegRole role, PrimitiveId wayId) { 121 CheckParameterUtil.ensureParameterNotNull(role, "role"); 122 if (wayId == null) { 123 setTurnRestrictionLeg(role, (Way)null); 124 return; 125 } 126 if (!wayId.getType().equals(OsmPrimitiveType.WAY)) { 127 throw new IllegalArgumentException(MessageFormat.format("parameter ''wayId'' of type {0} expected, got {1}", OsmPrimitiveType.WAY, wayId.getType())); 128 } 129 130 OsmPrimitive p = layer.data.getPrimitiveById(wayId); 131 if (p == null) { 132 throw new IllegalStateException(MessageFormat.format("didn''t find way with id {0} in layer ''{1}''", wayId, layer.getName())); 133 } 134 setTurnRestrictionLeg(role, (Way)p); 135 } 136 137 /** 138 * "Officially" a turn restriction should have exactly one member with 139 * role {@see TurnRestrictionLegRole#FROM} and one member with role {@see TurnRestrictionLegRole#TO}, 140 * both referring to an OSM {@see Way}. In order to deals with turn restrictions where these 141 * integrity constraints are violated, this model also supports relation with multiple or no 142 * 'from' or 'to' members. 143 * 144 * Replies the turn restriction legs with role {@code role}. If no leg with this 145 * role exists, an empty set is returned. If multiple legs exists, the set of referred 146 * primitives is returned. 147 * 148 * @param role the role. Must not be null. 149 * @return the set of turn restriction legs with role {@code role}. The empty set, if 150 * no such turn restriction leg exists 151 * @throws IllegalArgumentException thrown if role is null 152 */ 153 public Set<OsmPrimitive>getTurnRestrictionLeg(TurnRestrictionLegRole role){ 154 CheckParameterUtil.ensureParameterNotNull(role, "role"); 155 switch(role){ 156 case FROM: return memberModel.getFromPrimitives(); 157 case TO: return memberModel.getToPrimitives(); 158 } 159 // should not happen 160 return null; 161 } 162 163 /** 164 * Initializes the model from a relation representing a turn 165 * restriction 166 * 167 * @param turnRestriction the turn restriction 168 */ 169 protected void initFromTurnRestriction(Relation turnRestriction) { 170 171 // populate the member model 172 memberModel.populate(turnRestriction); 173 174 // make sure we have a restriction tag 175 TagCollection tags = TagCollection.from(turnRestriction); 176 tags.setUniqueForKey("type", "restriction"); 177 tagEditorModel.initFromTags(tags); 178 179 setChanged(); 180 notifyObservers(); 181 } 182 183 /** 184 * Populates the turn restriction editor model with a turn restriction. 185 * {@code turnRestriction} is an arbitrary relation. A tag type=restriction 186 * isn't required. If it is missing, it is added here. {@code turnRestriction} 187 * must not be null and it must belong to a dataset. 188 * 189 * @param turnRestriction the turn restriction 190 * @throws IllegalArgumentException thrown if turnRestriction is null 191 * @throws IllegalArgumentException thrown if turnRestriction doesn't belong to a dataset 192 */ 193 public void populate(Relation turnRestriction) { 194 CheckParameterUtil.ensureParameterNotNull(turnRestriction, "turnRestriction"); 195 if (turnRestriction.getDataSet() != null && turnRestriction.getDataSet() != layer.data) { 196 throw new IllegalArgumentException( 197 // don't translate - it's a technical message 198 MessageFormat.format("turnRestriction {0} must not belong to a different dataset than the dataset of layer ''{1}''", turnRestriction.getId(), layer.getName()) 199 ); 200 } 201 initFromTurnRestriction(turnRestriction); 202 } 203 204 205 /** 206 * Applies the current state in the model to a turn restriction 207 * 208 * @param turnRestriction the turn restriction. Must not be null. 209 */ 210 public void apply(Relation turnRestriction) { 211 CheckParameterUtil.ensureParameterNotNull(turnRestriction, "turnRestriction"); 212 TagCollection tags = tagEditorModel.getTagCollection(); 213 turnRestriction.removeAll(); 214 tags.applyTo(turnRestriction); 215 memberModel.applyTo(turnRestriction); 216 } 217 218 /** 219 * Replies the current tag value for the tag <tt>restriction</tt>. 220 * The empty tag, if there isn't a tag <tt>restriction</tt>. 221 * 222 * @return the tag value 223 */ 224 public String getRestrictionTagValue() { 225 TagCollection tags = tagEditorModel.getTagCollection(); 226 if (!tags.hasTagsFor("restriction")) return ""; 227 return tags.getJoinedValues("restriction"); 228 } 229 230 /** 231 * Sets the current value for the restriction tag. If {@code value} is 232 * null or an empty string, the restriction tag is removed. 233 * 234 * @param value the value of the restriction tag 235 */ 236 public void setRestrictionTagValue(String value){ 237 if (value == null || value.trim().equals("")) { 238 tagEditorModel.delete("restriction"); 239 } else { 240 TagModel tm = tagEditorModel.get("restriction"); 241 if (tm != null){ 242 tm.setValue(value); 243 } else { 244 tagEditorModel.prepend(new TagModel("restriction", value.trim().toLowerCase())); 245 } 246 } 247 setChanged(); 248 notifyObservers(); 249 } 250 251 /** 252 * Replies the list of 'via' objects. The return value is an 253 * unmodifiable list. 254 * 255 * @return the list of 'via' objects 256 */ 257 public List<OsmPrimitive> getVias() { 258 return memberModel.getVias(); 259 } 260 261 /** 262 * Sets the list of vias for the edited turn restriction. 263 * 264 * If {@code vias} is null, all vias are removed. All primitives 265 * in {@code vias} must be assigned to a dataset and the dataset 266 * must be equal to the dataset of this editor model, see {@see #getDataSet()} 267 * 268 * null values in {@see vias} are skipped. 269 * 270 * @param vias the list of vias 271 * @throws IllegalArgumentException thrown if one of the via objects belongs to the wrong dataset 272 */ 273 public void setVias(List<OsmPrimitive> vias) throws IllegalArgumentException{ 274 memberModel.setVias(vias); 275 } 276 277 /** 278 * Replies the layer in whose context this editor is working 279 * 280 * @return the layer in whose context this editor is working 281 */ 282 public OsmDataLayer getLayer() { 283 return layer; 284 } 285 286 /** 287 * Registers this model with global event sources like {@see DatasetEventManager} 288 */ 289 public void registerAsEventListener(){ 290 DatasetEventManager.getInstance().addDatasetListener(this, FireMode.IN_EDT); 291 } 292 293 /** 294 * Removes this model as listener from global event sources like {@see DatasetEventManager} 295 */ 296 public void unregisterAsEventListener() { 297 DatasetEventManager.getInstance().removeDatasetListener(this); 298 } 299 300 /** 301 * Replies the tag editor model 302 * 303 * @return the tag editor model 304 */ 305 public TagEditorModel getTagEditorModel() { 306 return tagEditorModel; 307 } 308 309 /** 310 * Replies the editor model for the relation members 311 * 312 * @return the editor model for the relation members 313 */ 314 public RelationMemberEditorModel getRelationMemberEditorModel() { 315 return memberModel; 316 } 317 318 /** 319 * Replies the model for the open issues in this turn restriction 320 * editor. 321 * 322 * @return the model for the open issues in this turn restriction 323 * editor 324 */ 325 public IssuesModel getIssuesModel() { 326 return issuesModel; 327 } 328 329 public NavigationControler getNavigationControler() { 330 return navigationControler; 331 } 332 333 /** 334 * Replies the current value of the tag "except", or the empty string 335 * if the tag doesn't exist. 336 * 337 * @return 338 */ 339 public ExceptValueModel getExcept() { 340 TagModel tag = tagEditorModel.get("except"); 341 if (tag == null) return new ExceptValueModel(""); 342 return new ExceptValueModel(tag.getValue()); 343 } 344 345 /** 346 * Sets the current value of the tag "except". Removes the 347 * tag is {@code value} is null or consists of white 348 * space only. 349 * 350 * @param value the new value for 'except' 351 */ 352 public void setExcept(ExceptValueModel value){ 353 if (value == null || value.getValue().equals("")) { 354 if (tagEditorModel.get("except") != null){ 355 tagEditorModel.delete("except"); 356 setChanged(); 357 notifyObservers(); 358 } 359 return; 360 } 361 TagModel tag = tagEditorModel.get("except"); 362 if (tag == null) { 363 tagEditorModel.prepend(new TagModel("except", value.getValue())); 364 setChanged(); 365 notifyObservers(); 366 } else { 367 if (!tag.getValue().equals(value.getValue())) { 368 tag.setValue(value.getValue().trim()); 369 setChanged(); 370 notifyObservers(); 371 } 372 } 373 } 374 375 /* ----------------------------------------------------------------------------------------- */ 376 /* interface DataSetListener */ 377 /* ----------------------------------------------------------------------------------------- */ 378 protected boolean isAffectedByDataSetUpdate(DataSet ds, List<? extends OsmPrimitive> updatedPrimitives) { 379 if (ds != layer.data) return false; 380 if (updatedPrimitives == null || updatedPrimitives.isEmpty()) return false; 381 Set<OsmPrimitive> myPrimitives = memberModel.getMemberPrimitives(); 382 int size1 = myPrimitives.size(); 383 myPrimitives.retainAll(updatedPrimitives); 384 return size1 != myPrimitives.size(); 385 } 386 387 public void dataChanged(DataChangedEvent event) { 388 // refresh the views 389 setChanged(); 390 notifyObservers(); 391 } 392 393 public void nodeMoved(NodeMovedEvent event) { 394 // may affect the display name of node in the list of vias 395 if (isAffectedByDataSetUpdate(event.getDataset(), event.getPrimitives())) { 396 setChanged(); 397 notifyObservers(); 398 } 399 } 400 401 public void otherDatasetChange(AbstractDatasetChangedEvent event) {/* irrelevant in this context */} 402 403 public void primtivesAdded(PrimitivesAddedEvent event) {/* irrelevant in this context */} 404 public void primtivesRemoved(PrimitivesRemovedEvent event) { 405 // relevant for the state of this model but not handled here. When the 406 // state of this model is applied to the dataset we check whether the 407 // the turn restriction refers to deleted or invisible primitives 408 } 409 410 public void relationMembersChanged(RelationMembersChangedEvent event) {/* irrelevant in this context */} 411 public void tagsChanged(TagsChangedEvent event) { 412 // may affect the display name of 'from', 'to' or 'via' elements 413 if (isAffectedByDataSetUpdate(event.getDataset(), event.getPrimitives())) { 414 setChanged(); 415 notifyObservers(); 416 } 417 } 418 419 public void wayNodesChanged(WayNodesChangedEvent event) { 420 // may affect the display name of 'from', 'to' or 'via' elements 421 if (isAffectedByDataSetUpdate(event.getDataset(), event.getPrimitives())) { 422 setChanged(); 423 notifyObservers(); 424 } 425 } 426 427 class RelationMemberModelListener implements TableModelListener { 428 public void tableChanged(TableModelEvent e) { 429 setChanged(); 430 notifyObservers(); 431 } 432 } 433 434 /* ----------------------------------------------------------------------------------------- */ 435 /* inner classes */ 436 /* ----------------------------------------------------------------------------------------- */ 437 class TagEditorModelObserver implements TableModelListener { 438 public void tableChanged(TableModelEvent e) { 439 setChanged(); 440 notifyObservers(); 441 } 442 } 443 443 } -
applications/editors/josm/plugins/turnrestrictions/src/org/openstreetmap/josm/plugins/turnrestrictions/editor/TurnRestrictionLegEditor.java
r20701 r23192 55 55 */ 56 56 public class TurnRestrictionLegEditor extends JPanel implements Observer, PrimitiveIdListProvider { 57 57 static private final Logger logger = Logger.getLogger(TurnRestrictionLegEditor.class.getName()); 58 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 add(lblOsmObject = new JLabel(), BorderLayout.CENTER); 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 lblOsmObject.setFocusable(true); 93 lblOsmObject.addFocusListener(fh); 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 th.exportAsDrag(c, e, TransferHandler.COPY); 116 } 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 refresh(); 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 lblOsmObject.setToolTipText(null); 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 } 197 198 199 200 201 202 refresh(); 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 /* ----------------------------------------------------------------------------- */ 218 219 220 221 222 223 224 225 226 227 228 229 230 } 231 232 233 234 235 236 237 } 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 model.setTurnRestrictionLeg(role, null); 254 } 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 } 304 305 306 307 308 309 310 311 312 item = add(actPaste); 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 } 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 delegate.actionPerformed(e); 366 367 59 private JLabel lblOsmObject; 60 private final Set<OsmPrimitive> legs = new HashSet<OsmPrimitive>(); 61 private TurnRestrictionEditorModel model; 62 private TurnRestrictionLegRole role; 63 private DeleteAction actDelete; 64 private CopyAction actCopy; 65 private PasteAction actPaste; 66 private TransferHandler transferHandler; 67 68 /** 69 * builds the UI 70 */ 71 protected void build() { 72 setLayout(new BorderLayout()); 73 add(lblOsmObject = new JLabel(), BorderLayout.CENTER); 74 lblOsmObject.setOpaque(true); 75 lblOsmObject.setBorder(null); 76 setBorder( 77 BorderFactory.createCompoundBorder( 78 BorderFactory.createEtchedBorder(), 79 BorderFactory.createEmptyBorder(1,1,1,1) 80 ) 81 ); 82 83 JButton btn; 84 actDelete = new DeleteAction(); 85 add(btn = new JButton(actDelete), BorderLayout.EAST); 86 btn.setFocusable(false); 87 btn.setText(null); 88 btn.setBorder(BorderFactory.createRaisedBevelBorder()); 89 90 // focus handling 91 FocusHandler fh = new FocusHandler(); 92 lblOsmObject.setFocusable(true); 93 lblOsmObject.addFocusListener(fh); 94 this.addFocusListener(fh); 95 96 // mouse event handling 97 MouseEventHandler meh = new MouseEventHandler(); 98 lblOsmObject.addMouseListener(meh); 99 addMouseListener(meh); 100 lblOsmObject.addMouseListener(new PopupLauncher()); 101 102 // enable DEL to remove the object from the turn restriction 103 registerKeyboardAction(actDelete,KeyStroke.getKeyStroke(KeyEvent.VK_DELETE,0) , JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT); 104 105 getInputMap().put(Shortcut.getCopyKeyStroke(), TransferHandler.getCopyAction().getValue(Action.NAME));; 106 getInputMap().put(Shortcut.getPasteKeyStroke(), TransferHandler.getPasteAction().getValue(Action.NAME));; 107 getActionMap().put(TransferHandler.getCopyAction().getValue(Action.NAME), TransferHandler.getCopyAction()); 108 getActionMap().put(TransferHandler.getPasteAction().getValue(Action.NAME), TransferHandler.getPasteAction()); 109 lblOsmObject.setTransferHandler(transferHandler = new LegEditorTransferHandler(this)); 110 lblOsmObject.addMouseMotionListener(new MouseMotionAdapter(){ 111 @Override 112 public void mouseDragged(MouseEvent e) { 113 JComponent c = (JComponent)e.getSource(); 114 TransferHandler th = c.getTransferHandler(); 115 th.exportAsDrag(c, e, TransferHandler.COPY); 116 } 117 }); 118 actCopy = new CopyAction(); 119 actPaste = new PasteAction(); 120 } 121 122 /** 123 * Constructor 124 * 125 * @param model the model. Must not be null. 126 * @param role the leg role of the leg this editor is editing. Must not be null. 127 * @exception IllegalArgumentException thrown if model is null 128 * @exception IllegalArgumentException thrown if role is null 129 */ 130 public TurnRestrictionLegEditor(TurnRestrictionEditorModel model, TurnRestrictionLegRole role) { 131 CheckParameterUtil.ensureParameterNotNull(model, "model"); 132 CheckParameterUtil.ensureParameterNotNull(role, "role"); 133 134 this.model = model; 135 this.role = role; 136 build(); 137 model.addObserver(this); 138 refresh(); 139 } 140 141 protected void refresh(){ 142 legs.clear(); 143 legs.addAll(model.getTurnRestrictionLeg(role)); 144 if (legs.isEmpty()) { 145 lblOsmObject.setFont(UIManager.getFont("Label.font").deriveFont(Font.ITALIC)); 146 lblOsmObject.setIcon(null); 147 lblOsmObject.setText(tr("please select a way")); 148 lblOsmObject.setToolTipText(null); 149 } else if (legs.size() == 1){ 150 OsmPrimitive leg = legs.iterator().next(); 151 lblOsmObject.setFont(UIManager.getFont("Label.font")); 152 lblOsmObject.setIcon(ImageProvider.get("data", "way")); 153 lblOsmObject.setText(leg.getDisplayName(DefaultNameFormatter.getInstance())); 154 lblOsmObject.setToolTipText(DefaultNameFormatter.getInstance().buildDefaultToolTip(leg)); 155 } else { 156 lblOsmObject.setFont(UIManager.getFont("Label.font").deriveFont(Font.ITALIC)); 157 lblOsmObject.setIcon(null); 158 lblOsmObject.setText(tr("multiple objects with role ''{0}''",this.role.getOsmRole())); 159 lblOsmObject.setToolTipText(null); 160 } 161 renderColors(); 162 actDelete.updateEnabledState(); 163 } 164 165 /** 166 * Render the foreground and background color 167 */ 168 protected void renderColors() { 169 if (lblOsmObject.hasFocus()) { 170 setBackground(UIManager.getColor("List.selectionBackground")); 171 setForeground(UIManager.getColor("List.selectionForeground")); 172 lblOsmObject.setBackground(UIManager.getColor("List.selectionBackground")); 173 lblOsmObject.setForeground(UIManager.getColor("List.selectionForeground")); 174 } else { 175 lblOsmObject.setBackground(UIManager.getColor("List.background")); 176 lblOsmObject.setForeground(UIManager.getColor("List.foreground")); 177 } 178 } 179 180 /** 181 * Replies the model for this editor 182 * 183 * @return the model 184 */ 185 public TurnRestrictionEditorModel getModel() { 186 return model; 187 } 188 189 /** 190 * Replies the role of this editor 191 * 192 * @return the role 193 */ 194 public TurnRestrictionLegRole getRole() { 195 return role; 196 } 197 198 /* ----------------------------------------------------------------------------- */ 199 /* interface Observer */ 200 /* ----------------------------------------------------------------------------- */ 201 public void update(Observable o, Object arg) { 202 refresh(); 203 } 204 205 /* ----------------------------------------------------------------------------- */ 206 /* interface PrimitiveIdListProvider */ 207 /* ----------------------------------------------------------------------------- */ 208 public List<PrimitiveId> getSelectedPrimitiveIds() { 209 if (legs.size() == 1) { 210 return Collections.singletonList(legs.iterator().next().getPrimitiveId()); 211 } 212 return Collections.emptyList(); 213 } 214 215 /* ----------------------------------------------------------------------------- */ 216 /* inner classes */ 217 /* ----------------------------------------------------------------------------- */ 218 /** 219 * Responds to focus change events 220 */ 221 class FocusHandler extends FocusAdapter { 222 @Override 223 public void focusGained(FocusEvent e) { 224 renderColors(); 225 } 226 227 @Override 228 public void focusLost(FocusEvent e) { 229 renderColors(); 230 } 231 } 232 233 class MouseEventHandler extends MouseAdapter { 234 @Override 235 public void mouseClicked(MouseEvent e) { 236 lblOsmObject.requestFocusInWindow(); 237 } 238 } 239 240 /** 241 * Deletes the way from the turn restriction 242 */ 243 class DeleteAction extends AbstractAction { 244 public DeleteAction() { 245 putValue(SHORT_DESCRIPTION, tr("Delete from turn restriction")); 246 putValue(NAME, tr("Delete")); 247 putValue(SMALL_ICON, ImageProvider.get("deletesmall")); 248 putValue(ACCELERATOR_KEY,KeyStroke.getKeyStroke(KeyEvent.VK_DELETE,0)); 249 updateEnabledState(); 250 } 251 252 public void actionPerformed(ActionEvent e) { 253 model.setTurnRestrictionLeg(role, null); 254 } 255 256 public void updateEnabledState() { 257 setEnabled(legs.size()>0); 258 } 259 } 260 261 /** 262 * The transfer handler for Drag-and-Drop. 263 */ 264 class LegEditorTransferHandler extends PrimitiveIdListTransferHandler { 265 Logger logger = Logger.getLogger(LegEditorTransferHandler.class.getName()); 266 267 public LegEditorTransferHandler(PrimitiveIdListProvider provider){ 268 super(provider); 269 } 270 271 @SuppressWarnings("unchecked") 272 @Override 273 public boolean importData(JComponent comp, Transferable t) { 274 try { 275 List<PrimitiveId> ids = (List<PrimitiveId>)t.getTransferData(PrimitiveIdTransferable.PRIMITIVE_ID_LIST_FLAVOR); 276 if (ids.size() !=1) { 277 return false; 278 } 279 PrimitiveId id = ids.get(0); 280 if (!id.getType().equals(OsmPrimitiveType.WAY)) return false; 281 model.setTurnRestrictionLeg(role, id); 282 return true; 283 } catch(IOException e) { 284 // ignore 285 return false; 286 } catch(UnsupportedFlavorException e) { 287 // ignore 288 return false; 289 } 290 } 291 292 @Override 293 protected Transferable createTransferable(JComponent c) { 294 if (legs.size() != 1) return null; 295 return super.createTransferable(c); 296 } 297 } 298 299 class PopupLauncher extends PopupMenuLauncher { 300 @Override 301 public void launch(MouseEvent evt) { 302 new PopupMenu().show(lblOsmObject, evt.getX(), evt.getY()); 303 } 304 } 305 306 class PopupMenu extends JPopupMenu { 307 public PopupMenu() { 308 actCopy.updateEnabledState(); 309 JMenuItem item = add(actCopy); 310 item.setTransferHandler(transferHandler); 311 actPaste.updateEnabledState(); 312 item = add(actPaste); 313 item.setTransferHandler(transferHandler); 314 addSeparator(); 315 add(actDelete); 316 } 317 } 318 319 class CopyAction extends AbstractAction { 320 private Action delegate; 321 322 public CopyAction(){ 323 putValue(NAME, tr("Copy")); 324 putValue(SHORT_DESCRIPTION, tr("Copy to the clipboard")); 325 putValue(SMALL_ICON, ImageProvider.get("copy")); 326 putValue(ACCELERATOR_KEY, Shortcut.getCopyKeyStroke()); 327 delegate = TurnRestrictionLegEditor.this.getActionMap().get("copy"); 328 updateEnabledState(); 329 } 330 331 public void actionPerformed(ActionEvent e) { 332 delegate.actionPerformed(e); 333 } 334 335 public void updateEnabledState() { 336 setEnabled(legs.size() == 1); 337 } 338 } 339 340 class PasteAction extends AbstractAction { 341 private Action delegate; 342 343 public boolean canPaste() { 344 Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); 345 for (DataFlavor df: clipboard.getAvailableDataFlavors()) { 346 if (df.equals(PrimitiveIdTransferable.PRIMITIVE_ID_LIST_FLAVOR)) return true; 347 } 348 // FIXME: check whether there are selected objects in the JOSM copy/paste buffer 349 return false; 350 } 351 352 public PasteAction(){ 353 putValue(NAME, tr("Paste")); 354 putValue(SHORT_DESCRIPTION, tr("Paste from the clipboard")); 355 putValue(SMALL_ICON, ImageProvider.get("paste")); 356 putValue(ACCELERATOR_KEY, Shortcut.getPasteKeyStroke()); 357 delegate = TurnRestrictionLegEditor.this.getActionMap().get("paste"); 358 } 359 360 public void updateEnabledState() { 361 setEnabled(canPaste()); 362 } 363 364 public void actionPerformed(ActionEvent e) { 365 delegate.actionPerformed(e); 366 } 367 } 368 368 } -
applications/editors/josm/plugins/turnrestrictions/src/org/openstreetmap/josm/plugins/turnrestrictions/editor/TurnRestrictionLegRole.java
r20622 r23192 4 4 * Enumerates the two roles a "leg" in a turn restriction can have. 5 5 */ 6 public enum TurnRestrictionLegRole { 7 8 9 10 11 12 13 14 15 16 17 18 6 public enum TurnRestrictionLegRole { 7 FROM("from"), 8 TO("to"); 9 10 private String osmRoleName; 11 12 private TurnRestrictionLegRole(String osmRoleName) { 13 this.osmRoleName = osmRoleName; 14 } 15 16 public String getOsmRole() { 17 return osmRoleName; 18 } 19 19 } -
applications/editors/josm/plugins/turnrestrictions/src/org/openstreetmap/josm/plugins/turnrestrictions/editor/TurnRestrictionSelectionPopupPanel.java
r20606 r23192 50 50 */ 51 51 public class TurnRestrictionSelectionPopupPanel extends JPanel{ 52 53 54 55 56 57 58 59 private JTable tblTurnRestrictions; 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 return pnl; 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 add(buildTurnRestrictionTablePanel(editCandiates), BorderLayout.CENTER); 163 164 165 166 setBackground(UIManager.getColor("Table.background")); 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 } 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 editTurnRestrictionAtRow(row); 285 286 287 288 289 290 291 292 293 294 295 296 297 } 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 private static class TurnRestrictionTableColumnModel extends DefaultTableColumnModel { 336 public TurnRestrictionTableColumnModel() { 337 338 TableColumn col = new TableColumn(0); 339 340 341 342 343 344 col = new TableColumn(1); 345 346 347 348 addColumn(col); 349 350 351 352 private class FocusHandler extends FocusAdapter { 353 354 355 356 // we hide the popup 357 358 359 360 361 362 363 52 static private final Logger logger = Logger.getLogger(TurnRestrictionSelectionPopupPanel.class.getName()); 53 54 /** the parent popup */ 55 private Popup parentPopup; 56 /** the button for creating a new turn restriction */ 57 private JButton btnNew; 58 /** the table with the turn restrictions which can be edited */ 59 private JTable tblTurnRestrictions; 60 private OsmDataLayer layer; 61 62 63 64 /** 65 * Replies the collection of turn restrictions the primitives in {@code primitives} 66 * currently participate in. 67 * 68 * @param primitives the collection of primitives. May be null. 69 * @return the collection of "parent" turn restrictions. 70 */ 71 static public Collection<Relation> getTurnRestrictionsParticipatingIn(Collection<OsmPrimitive> primitives){ 72 HashSet<Relation> ret = new HashSet<Relation>(); 73 if (primitives == null) return ret; 74 for (OsmPrimitive p: primitives){ 75 if (p == null) continue; 76 if (p.isDeleted() || !p.isVisible()) continue; 77 for (OsmPrimitive parent: p.getReferrers()){ 78 if (!(parent instanceof Relation)) continue; 79 String type = parent.get("type"); 80 if (type == null || ! type.equals("restriction")) continue; 81 if (parent.isDeleted() || ! parent.isVisible()) continue; 82 ret.add((Relation)parent); 83 } 84 } 85 return ret; 86 } 87 88 /** 89 * Registers 1..9 shortcuts for the first 9 turn restrictions to 90 * edit 91 * 92 * @param editCandiates the edit candidates 93 */ 94 protected void registerEditShortcuts(Collection<Relation> editCandiates){ 95 for(int i=1; i <= Math.min(editCandiates.size(),9);i++){ 96 int vkey = 0; 97 switch(i){ 98 case 1: vkey = KeyEvent.VK_1; break; 99 case 2: vkey = KeyEvent.VK_2; break; 100 case 3: vkey = KeyEvent.VK_3; break; 101 case 4: vkey = KeyEvent.VK_4; break; 102 case 5: vkey = KeyEvent.VK_5; break; 103 case 6: vkey = KeyEvent.VK_6; break; 104 case 7: vkey = KeyEvent.VK_7; break; 105 case 8: vkey = KeyEvent.VK_8; break; 106 case 9: vkey = KeyEvent.VK_9; break; 107 } 108 registerKeyboardAction(new EditTurnRestrictionAction(i-1), KeyStroke.getKeyStroke(vkey,0), WHEN_ANCESTOR_OF_FOCUSED_COMPONENT); 109 } 110 } 111 /** 112 * Builds the panel with the turn restrictions table 113 * 114 * @param editCandiates the list of edit candiates 115 * @return the panel 116 */ 117 protected JPanel buildTurnRestrictionTablePanel(Collection<Relation> editCandiates) { 118 tblTurnRestrictions = new JTable(new TurnRestrictionTableModel(editCandiates), new TurnRestrictionTableColumnModel()); 119 tblTurnRestrictions.setColumnSelectionAllowed(false); 120 tblTurnRestrictions.getSelectionModel().setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION); 121 TurnRestrictionCellRenderer renderer = new TurnRestrictionCellRenderer(); 122 tblTurnRestrictions.setRowHeight((int)renderer.getPreferredSize().getHeight()); 123 124 // create a scroll pane, remove the table header 125 JScrollPane pane = new JScrollPane(tblTurnRestrictions); 126 pane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); 127 pane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED); 128 tblTurnRestrictions.setTableHeader(null); 129 pane.setColumnHeaderView(null); 130 131 // respond to double click and ENTER 132 EditSelectedTurnRestrictionAction action = new EditSelectedTurnRestrictionAction(); 133 tblTurnRestrictions.addMouseListener(action); 134 tblTurnRestrictions.registerKeyboardAction(action, KeyStroke.getKeyStroke(KeyEvent.VK_ENTER,0), WHEN_FOCUSED); 135 136 tblTurnRestrictions.addFocusListener(new FocusHandler()); 137 138 JPanel pnl = new JPanel(new BorderLayout()); 139 pnl.add(pane, BorderLayout.CENTER); 140 141 pnl.setBackground(UIManager.getColor("Table.background")); 142 pane.setBackground(UIManager.getColor("Table.background")); 143 return pnl; 144 } 145 146 /** 147 * Builds the panel 148 * 149 * @param editCandiates the edit candidates 150 */ 151 protected void build(Collection<Relation> editCandiates) { 152 setLayout(new BorderLayout()); 153 add(btnNew = new JButton(new NewAction()), BorderLayout.NORTH); 154 btnNew.setFocusable(true); 155 btnNew.registerKeyboardAction(btnNew.getAction(), KeyStroke.getKeyStroke(KeyEvent.VK_ENTER,0), WHEN_FOCUSED); 156 registerKeyboardAction(new CloseAction(), KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE,0), WHEN_ANCESTOR_OF_FOCUSED_COMPONENT); 157 registerKeyboardAction(btnNew.getAction(), KeyStroke.getKeyStroke(KeyEvent.VK_N,0), WHEN_ANCESTOR_OF_FOCUSED_COMPONENT); 158 159 btnNew.addFocusListener(new FocusHandler()); 160 161 if (editCandiates != null && ! editCandiates.isEmpty()) { 162 add(buildTurnRestrictionTablePanel(editCandiates), BorderLayout.CENTER); 163 registerEditShortcuts(editCandiates); 164 } 165 166 setBackground(UIManager.getColor("Table.background")); 167 } 168 169 170 /** 171 * Creates the panel 172 * 173 * @param layer the reference OSM data layer. Must not be null. 174 * @throws IllegalArgumentException thrown if {@code layer} is null 175 */ 176 public TurnRestrictionSelectionPopupPanel(OsmDataLayer layer) throws IllegalArgumentException { 177 CheckParameterUtil.ensureParameterNotNull(layer, "layer"); 178 this.layer = layer; 179 build(getTurnRestrictionsParticipatingIn(layer.data.getSelected())); 180 } 181 182 /** 183 * Creates the panel 184 * 185 * @param layer the reference OSM data layer. Must not be null. 186 * @param editCandidates a collection of turn restrictions as edit candidates. May be null. 187 * @throws IllegalArgumentException thrown if {@code layer} is null 188 */ 189 public TurnRestrictionSelectionPopupPanel(OsmDataLayer layer, Collection<Relation> editCandiates) { 190 CheckParameterUtil.ensureParameterNotNull(layer, "layer"); 191 this.layer = layer; 192 build(editCandiates); 193 } 194 195 /** 196 * Launches a popup with this panel as content 197 */ 198 public void launch(){ 199 PointerInfo info = MouseInfo.getPointerInfo(); 200 Point pt = info.getLocation(); 201 parentPopup = PopupFactory.getSharedInstance().getPopup(Main.map.mapView,this, pt.x, pt.y); 202 parentPopup.show(); 203 btnNew.requestFocusInWindow(); 204 } 205 206 @Override 207 public Dimension getPreferredSize() { 208 int bestheight = (int)btnNew.getPreferredSize().getHeight() 209 + Math.min(2, tblTurnRestrictions.getRowCount()) * tblTurnRestrictions.getRowHeight() 210 + 5; 211 return new Dimension(300, bestheight); 212 } 213 214 /* --------------------------------------------------------------------------------------- */ 215 /* inner classes */ 216 /* --------------------------------------------------------------------------------------- */ 217 218 private class NewAction extends AbstractAction { 219 public NewAction() { 220 putValue(NAME, tr("Create new turn restriction")); 221 putValue(SHORT_DESCRIPTION, tr("Launch the turn restriction editor to create a new turn restriction")); 222 putValue(SMALL_ICON, ImageProvider.get("new")); 223 putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_N, 0)); 224 } 225 226 public void actionPerformed(ActionEvent e) { 227 Relation tr = new TurnRestrictionBuilder().buildFromSelection(layer); 228 TurnRestrictionEditor editor = new TurnRestrictionEditor(Main.map.mapView,layer,tr); 229 TurnRestrictionEditorManager.getInstance().positionOnScreen(editor); 230 TurnRestrictionEditorManager.getInstance().register(layer, tr, editor); 231 if (parentPopup != null){ 232 parentPopup.hide(); 233 } 234 editor.setVisible(true); 235 } 236 } 237 238 abstract private class AbstractEditTurnRestrictionAction extends AbstractAction { 239 protected void launchEditor(Relation tr){ 240 TurnRestrictionEditorManager manager = TurnRestrictionEditorManager.getInstance(); 241 TurnRestrictionEditor editor = manager.getEditorForRelation(layer, tr); 242 if (parentPopup != null){ 243 parentPopup.hide(); 244 } 245 if (editor != null) { 246 editor.setVisible(true); 247 editor.toFront(); 248 } else { 249 editor = new TurnRestrictionEditor(Main.map.mapView, layer,tr); 250 manager.positionOnScreen(editor); 251 manager.register(layer, tr,editor); 252 editor.setVisible(true); 253 } 254 } 255 } 256 257 private class EditTurnRestrictionAction extends AbstractEditTurnRestrictionAction { 258 private int idx; 259 260 public EditTurnRestrictionAction(int idx){ 261 this.idx = idx; 262 } 263 264 public void actionPerformed(ActionEvent e) { 265 Relation tr = (Relation)tblTurnRestrictions.getModel().getValueAt(idx, 1); 266 launchEditor(tr); 267 } 268 } 269 270 private class EditSelectedTurnRestrictionAction extends AbstractEditTurnRestrictionAction implements MouseListener{ 271 public void editTurnRestrictionAtRow(int row){ 272 if (row < 0) return; 273 Relation tr = (Relation)tblTurnRestrictions.getModel().getValueAt(row, 1); 274 launchEditor(tr); 275 } 276 public void actionPerformed(ActionEvent e) { 277 int row = tblTurnRestrictions.getSelectedRow(); 278 editTurnRestrictionAtRow(row); 279 } 280 public void mouseClicked(MouseEvent e) { 281 if (!(SwingUtilities.isLeftMouseButton(e) && e.getClickCount() >= 2)) return; 282 int row = tblTurnRestrictions.rowAtPoint(e.getPoint()); 283 if (row < 0) return; 284 editTurnRestrictionAtRow(row); 285 } 286 public void mouseEntered(MouseEvent e) {} 287 public void mouseExited(MouseEvent e) {} 288 public void mousePressed(MouseEvent e) {} 289 public void mouseReleased(MouseEvent e) {} 290 } 291 292 private class CloseAction extends AbstractAction { 293 public void actionPerformed(ActionEvent e) { 294 if (parentPopup != null){ 295 parentPopup.hide(); 296 } 297 } 298 } 299 300 private static class TurnRestrictionTableModel extends AbstractTableModel { 301 private final ArrayList<Relation> turnrestrictions = new ArrayList<Relation>(); 302 303 public TurnRestrictionTableModel(Collection<Relation> turnrestrictions){ 304 this.turnrestrictions.clear(); 305 if (turnrestrictions != null){ 306 this.turnrestrictions.addAll(turnrestrictions); 307 } 308 fireTableDataChanged(); 309 } 310 311 public int getRowCount() { 312 return turnrestrictions.size(); 313 } 314 315 public int getColumnCount() { 316 return 2; 317 } 318 319 public Object getValueAt(int rowIndex, int columnIndex) { 320 switch(columnIndex){ 321 case 0: 322 if (rowIndex <=8 ) { 323 return Integer.toString(rowIndex+1); 324 } else { 325 return ""; 326 } 327 case 1: 328 return turnrestrictions.get(rowIndex); 329 } 330 // should not happen 331 return null; 332 } 333 } 334 335 private static class TurnRestrictionTableColumnModel extends DefaultTableColumnModel { 336 public TurnRestrictionTableColumnModel() { 337 // the idx column 338 TableColumn col = new TableColumn(0); 339 col.setResizable(false); 340 col.setWidth(50); 341 addColumn(col); 342 343 // the column displaying turn restrictions 344 col = new TableColumn(1); 345 col.setResizable(false); 346 col.setPreferredWidth(400); 347 col.setCellRenderer(new TurnRestrictionCellRenderer()); 348 addColumn(col); 349 } 350 } 351 352 private class FocusHandler extends FocusAdapter { 353 @Override 354 public void focusLost(FocusEvent e) { 355 // if we loose the focus to a component outside of the popup panel 356 // we hide the popup 357 if (e.getOppositeComponent() == null ||!SwingUtilities.isDescendingFrom(e.getOppositeComponent(), TurnRestrictionSelectionPopupPanel.this)) { 358 if (parentPopup != null){ 359 parentPopup.hide(); 360 } 361 } 362 } 363 } 364 364 } -
applications/editors/josm/plugins/turnrestrictions/src/org/openstreetmap/josm/plugins/turnrestrictions/editor/TurnRestrictionType.java
r20586 r23192 9 9 */ 10 10 public enum TurnRestrictionType { 11 12 13 14 NO_STRAIGHT_ON("no_straight_on", tr("No Straight On")), 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 } 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 11 NO_RIGHT_TURN("no_right_turn", tr("No Right Turn")), 12 NO_LEFT_TURN("no_left_turn", tr("No Left Turn")), 13 NO_U_TURN("no_u_turn", tr("No U-Turn")), 14 NO_STRAIGHT_ON("no_straight_on", tr("No Straight On")), 15 ONLY_RIGHT_TURN("only_right_turn", tr("Only Right Turn")), 16 ONLY_LEFT_TURN("only_left_turn", tr("Only Left Turn")), 17 ONLY_STRAIGHT_ON("only_straight_on", tr("Only Straight On")); 18 19 private String tagValue; 20 private String displayName; 21 22 TurnRestrictionType(String tagValue, String displayName) { 23 this.tagValue = tagValue; 24 this.displayName = displayName; 25 } 26 27 /** 28 * Replies the tag value for a specific turn restriction type 29 * 30 * @return the tag value for a specific turn restriction type 31 */ 32 public String getTagValue() { 33 return tagValue; 34 } 35 36 /** 37 * Replies the localized display name for a turn restriction type 38 */ 39 public String getDisplayName() { 40 return displayName; 41 } 42 43 /** 44 * Replies the enumeration value for a given tag value. null, 45 * if {@code tagValue} is null or if there isnt an enumeration value 46 * for this {@code tagValue} 47 * 48 * @param tagValue the tag value, i.e. <tt>no_left_turn</tt> 49 * @return the enumeration value 50 */ 51 static public TurnRestrictionType fromTagValue(String tagValue) { 52 if (tagValue == null) return null; 53 for(TurnRestrictionType type: values()) { 54 if(type.getTagValue().equals(tagValue)) return type; 55 } 56 return null; 57 } 58 58 59 60 61 62 63 64 65 66 67 59 /** 60 * Replies true if {@code tagValue} is a standard restriction type. 61 * 62 * @param tagValue the tag value 63 * @return true if {@code tagValue} is a standard restriction type 64 */ 65 static public boolean isStandardTagValue(String tagValue){ 66 return fromTagValue(tagValue) != null; 67 } 68 68 } -
applications/editors/josm/plugins/turnrestrictions/src/org/openstreetmap/josm/plugins/turnrestrictions/editor/TurnRestrictionTypeRenderer.java
r20666 r23192 20 20 public class TurnRestrictionTypeRenderer extends JLabel implements ListCellRenderer{ 21 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 e.printStackTrace(); 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 setForeground(UIManager.getColor("List.foreground")); 52 53 54 55 56 57 58 59 60 61 public void initIconSetFromPreferences(Preferences prefs){ 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 } 22 final private Map<TurnRestrictionType, ImageIcon> icons = new HashMap<TurnRestrictionType, ImageIcon>(); 23 private String iconSet = "set-a"; 24 25 /** 26 * Loads the image icons for the rendered turn restriction types 27 */ 28 protected void loadImages() { 29 for(TurnRestrictionType type: TurnRestrictionType.values()) { 30 try { 31 ImageIcon icon = new ImageIcon(ImageProvider.get("types/" + iconSet, type.getTagValue()).getImage().getScaledInstance(16, 16, Image.SCALE_SMOOTH)); 32 icons.put(type,icon); 33 } catch(Exception e){ 34 System.out.println(tr("Warning: failed to load icon for turn restriction type ''{0}''", type.getTagValue())); 35 e.printStackTrace(); 36 } 37 } 38 } 39 40 public TurnRestrictionTypeRenderer() { 41 setOpaque(true); 42 loadImages(); 43 } 44 45 protected void renderColors(boolean isSelected){ 46 if (isSelected){ 47 setBackground(UIManager.getColor("List.selectionBackground")); 48 setForeground(UIManager.getColor("List.selectionForeground")); 49 } else { 50 setBackground(UIManager.getColor("List.background")); 51 setForeground(UIManager.getColor("List.foreground")); 52 } 53 } 54 55 /** 56 * Initializes the set of icons used from the preference key 57 * {@see PreferenceKeys#ROAD_SIGNS}. 58 * 59 * @param prefs the JOSM preferences 60 */ 61 public void initIconSetFromPreferences(Preferences prefs){ 62 iconSet = prefs.get(PreferenceKeys.ROAD_SIGNS, "set-a"); 63 iconSet = iconSet.trim().toLowerCase(); 64 if (!iconSet.equals("set-a") && !iconSet.equals("set-b")) { 65 iconSet = "set-a"; 66 } 67 loadImages(); 68 } 69 70 public Component getListCellRendererComponent(JList list, Object value, 71 int index, boolean isSelected, boolean cellHasFocus) { 72 73 renderColors(isSelected); 74 if (value == null) { 75 setText(tr("please select a turn restriction type")); 76 setIcon(null); 77 } else if (value instanceof String){ 78 setText((String)value); 79 setIcon(null); // FIXME: special icon for non-standard types? 80 } else if (value instanceof TurnRestrictionType){ 81 TurnRestrictionType type = (TurnRestrictionType)value; 82 setText(type.getDisplayName()); 83 setIcon(icons.get(type)); 84 } 85 return this; 86 } 87 87 } -
applications/editors/josm/plugins/turnrestrictions/src/org/openstreetmap/josm/plugins/turnrestrictions/editor/VehicleExceptionEditor.java
r20648 r23192 36 36 */ 37 37 public class VehicleExceptionEditor extends JPanel implements Observer{ 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 add(buildStandardInputPanel(), gc); 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 persist(); 325 326 38 static private final Logger logger = Logger.getLogger(VehicleExceptionEditor.class.getName()); 39 40 private TurnRestrictionEditorModel model; 41 private JCheckBox cbPsv; 42 private JCheckBox cbBicyle; 43 private JCheckBox cbHgv; 44 private JCheckBox cbMotorcar; 45 private JTextField tfNonStandardValue; 46 private ButtonGroup bgStandardOrNonStandard; 47 private JRadioButton rbStandardException; 48 private JRadioButton rbNonStandardException; 49 private JPanel pnlStandard; 50 private JPanel pnlNonStandard; 51 private ExceptValueModel exceptValue = new ExceptValueModel(); 52 53 private JPanel buildMessagePanel() { 54 JPanel pnl = new JPanel(new BorderLayout()); 55 HtmlPanel msg = new HtmlPanel(); 56 pnl.add(msg, BorderLayout.CENTER); 57 msg.setText( 58 "<html><body>" 59 + tr("Select the vehicle types this turn restriction is <strong>not</strong> applicable for.") 60 + "</body></html>" 61 ); 62 return pnl; 63 } 64 65 private JPanel buildStandardInputPanel() { 66 if (pnlStandard != null) 67 return pnlStandard; 68 69 StandardVehicleTypeChangeListener changeHandler = new StandardVehicleTypeChangeListener(); 70 71 GridBagConstraints gc = new GridBagConstraints(); 72 gc.anchor = GridBagConstraints.NORTHWEST; 73 gc.fill = GridBagConstraints.HORIZONTAL; 74 gc.gridx = 0; 75 gc.gridy = 0; 76 77 pnlStandard = new JPanel(new GridBagLayout()); 78 JLabel lbl; 79 cbPsv = new JCheckBox(); 80 cbPsv.addItemListener(changeHandler); 81 lbl = new JLabel(); 82 lbl.setText(tr("Public Service Vehicles")); 83 lbl.setToolTipText(tr("Public service vehicles like buses, tramways, etc.")); 84 lbl.setIcon(ImageProvider.get("vehicle", "psv")); 85 86 gc.weightx = 0.0; 87 pnlStandard.add(cbPsv, gc); 88 gc.weightx = 1.0; 89 gc.gridx++; 90 pnlStandard.add(lbl, gc); 91 92 cbHgv = new JCheckBox(); 93 cbHgv.addItemListener(changeHandler); 94 lbl = new JLabel(); 95 lbl.setText(tr("Heavy Goods Vehicles")); 96 lbl.setIcon(ImageProvider.get("vehicle", "hgv")); 97 98 gc.weightx = 0.0; 99 gc.gridx++; 100 pnlStandard.add(cbHgv, gc); 101 gc.weightx = 1.0; 102 gc.gridx++; 103 pnlStandard.add(lbl, gc); 104 105 cbMotorcar = new JCheckBox(); 106 cbMotorcar.addItemListener(changeHandler); 107 lbl = new JLabel(); 108 lbl.setText(tr("Motorcars")); 109 lbl.setIcon(ImageProvider.get("vehicle", "motorcar")); 110 111 gc.weightx = 0.0; 112 gc.gridx = 0; 113 gc.gridy = 1; 114 pnlStandard.add(cbMotorcar, gc); 115 gc.weightx = 1.0; 116 gc.gridx++; 117 pnlStandard.add(lbl, gc); 118 119 cbBicyle = new JCheckBox(); 120 cbBicyle.addItemListener(changeHandler); 121 lbl = new JLabel(); 122 lbl.setText(tr("Bicycles")); 123 lbl.setIcon(ImageProvider.get("vehicle", "bicycle")); 124 125 126 gc.weightx = 0.0; 127 gc.gridx++; 128 pnlStandard.add(cbBicyle, gc); 129 gc.weightx = 1.0; 130 gc.gridx++; 131 pnlStandard.add(lbl, gc); 132 133 return pnlStandard; 134 } 135 136 private JPanel buildNonStandardInputPanel() { 137 if (pnlNonStandard != null) 138 return pnlNonStandard; 139 pnlNonStandard = new JPanel(new GridBagLayout()); 140 GridBagConstraints gc = new GridBagConstraints(); 141 gc.anchor = GridBagConstraints.NORTHWEST; 142 gc.fill = GridBagConstraints.HORIZONTAL; 143 gc.weightx = 0.0; 144 gc.insets = new Insets(0, 0, 4, 0); 145 gc.gridx = 0; 146 gc.gridy = 0; 147 148 pnlNonStandard.add(new JLabel(tr("Value:")), gc); 149 gc.gridx = 1; 150 gc.weightx = 1.0; 151 pnlNonStandard.add(tfNonStandardValue = new JTextField(), gc); 152 SelectAllOnFocusGainedDecorator.decorate(tfNonStandardValue); 153 154 NonStandardVehicleTypesHandler inputChangedHandler = new NonStandardVehicleTypesHandler(); 155 tfNonStandardValue.addActionListener(inputChangedHandler); 156 tfNonStandardValue.addFocusListener(inputChangedHandler); 157 return pnlNonStandard; 158 } 159 160 /** 161 * Builds the UI for entering standard values 162 */ 163 protected void buildStandard() { 164 setLayout(new GridBagLayout()); 165 GridBagConstraints gc = new GridBagConstraints(); 166 gc.anchor = GridBagConstraints.NORTHWEST; 167 gc.fill = GridBagConstraints.HORIZONTAL; 168 gc.weightx = 1.0; 169 gc.gridx = 0; 170 gc.gridy = 0; 171 add(buildMessagePanel(), gc); 172 173 gc.gridy=1; 174 add(buildStandardInputPanel(), gc); 175 } 176 177 /** 178 * Builds the UI for entering either standard or non-standard values 179 */ 180 protected void buildNonStandard() { 181 setLayout(new GridBagLayout()); 182 GridBagConstraints gc = new GridBagConstraints(); 183 gc.anchor = GridBagConstraints.NORTHWEST; 184 gc.fill = GridBagConstraints.HORIZONTAL; 185 gc.weightx = 1.0; 186 gc.gridx = 0; 187 gc.gridy = 0; 188 add(buildMessagePanel(), gc); 189 190 gc.gridx=0; 191 gc.gridy=1; 192 gc.insets = new Insets(0,0,0,0); 193 add(rbStandardException = new JRadioButton(tr("Use standard exceptions")), gc); 194 195 gc.gridx=0; 196 gc.gridy=2; 197 gc.insets = new Insets(0, 20, 0,0); 198 add(buildStandardInputPanel(), gc); 199 200 gc.gridx=0; 201 gc.gridy=3; 202 gc.insets = new Insets(0,0,0,0); 203 add(rbNonStandardException = new JRadioButton(tr("Use non-standard exceptions")), gc); 204 205 gc.gridx=0; 206 gc.gridy=4; 207 gc.insets = new Insets(0, 20, 0,0); 208 add(buildNonStandardInputPanel(), gc); 209 210 bgStandardOrNonStandard = new ButtonGroup(); 211 bgStandardOrNonStandard.add(rbNonStandardException); 212 bgStandardOrNonStandard.add(rbStandardException); 213 214 StandardNonStandardChangeHander changeHandler = new StandardNonStandardChangeHander(); 215 rbNonStandardException.addItemListener(changeHandler); 216 rbStandardException.addItemListener(changeHandler); 217 } 218 219 protected void build() { 220 removeAll(); 221 buildNonStandardInputPanel(); 222 buildStandardInputPanel(); 223 if (exceptValue.isStandard()){ 224 buildStandard(); 225 } else { 226 buildNonStandard(); 227 } 228 init(); 229 invalidate(); 230 } 231 232 protected void init() { 233 cbPsv.setSelected(exceptValue.isVehicleException("psv")); 234 cbBicyle.setSelected(exceptValue.isVehicleException("bicycle")); 235 cbMotorcar.setSelected(exceptValue.isVehicleException("motorcar")); 236 cbHgv.setSelected(exceptValue.isVehicleException("hgv")); 237 if (!exceptValue.isStandard()){ 238 rbNonStandardException.setSelected(true); 239 tfNonStandardValue.setText(exceptValue.getValue()); 240 setEnabledNonStandardInputPanel(true); 241 setEnabledStandardInputPanel(false); 242 } else { 243 setEnabledNonStandardInputPanel(false); 244 setEnabledStandardInputPanel(true); 245 } 246 } 247 248 protected void setEnabledStandardInputPanel(boolean enabled) { 249 for (Component c: pnlStandard.getComponents()){ 250 c.setEnabled(enabled); 251 } 252 } 253 254 protected void setEnabledNonStandardInputPanel(boolean enabled) { 255 for (Component c: pnlNonStandard.getComponents()){ 256 c.setEnabled(enabled); 257 } 258 } 259 260 261 /** 262 * Creates the editor 263 * 264 * @param model the editor model. Must not be null. 265 * @throws IllegalArgumentException thrown if {@code model} is null 266 */ 267 public VehicleExceptionEditor(TurnRestrictionEditorModel model) throws IllegalArgumentException { 268 CheckParameterUtil.ensureParameterNotNull(model, "model"); 269 this.model = model; 270 build(); 271 model.addObserver(this); 272 } 273 274 /* ------------------------------------------------------------------------------------ */ 275 /* interface Observer */ 276 /* ------------------------------------------------------------------------------------ */ 277 public void update(Observable o, Object arg) { 278 if (!this.exceptValue.equals(model.getExcept())) { 279 this.exceptValue = model.getExcept(); 280 build(); 281 } 282 } 283 284 /* ------------------------------------------------------------------------------------ */ 285 /* inner classes */ 286 /* ------------------------------------------------------------------------------------ */ 287 class StandardNonStandardChangeHander implements ItemListener { 288 public void itemStateChanged(ItemEvent e) { 289 if (rbNonStandardException.isSelected()){ 290 setEnabledNonStandardInputPanel(true); 291 setEnabledStandardInputPanel(false); 292 exceptValue.setStandard(false); 293 } else { 294 setEnabledNonStandardInputPanel(false); 295 setEnabledStandardInputPanel(true); 296 exceptValue.setStandard(true); 297 } 298 model.setExcept(exceptValue); 299 } 300 } 301 302 class StandardVehicleTypeChangeListener implements ItemListener { 303 public void itemStateChanged(ItemEvent e) { 304 exceptValue.setVehicleException("bicycle", cbBicyle.isSelected()); 305 exceptValue.setVehicleException("hgv", cbHgv.isSelected()); 306 exceptValue.setVehicleException("psv", cbPsv.isSelected()); 307 exceptValue.setVehicleException("motorcar", cbMotorcar.isSelected()); 308 model.setExcept(exceptValue); 309 } 310 } 311 312 class NonStandardVehicleTypesHandler implements ActionListener, FocusListener { 313 public void persist() { 314 exceptValue.setValue(tfNonStandardValue.getText()); 315 model.setExcept(exceptValue); 316 } 317 318 public void focusGained(FocusEvent e) {} 319 public void focusLost(FocusEvent e) { 320 persist(); 321 } 322 323 public void actionPerformed(ActionEvent e) { 324 persist(); 325 } 326 } 327 327 } -
applications/editors/josm/plugins/turnrestrictions/src/org/openstreetmap/josm/plugins/turnrestrictions/editor/ViaList.java
r20489 r23192 46 46 */ 47 47 public class ViaList extends JList{ 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 setDragEnabled(true); 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 addMouseListener(new ViaListPopupMenuLaucher()); 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 return isSupportedFlavor(transferFlavors); 113 114 115 116 117 public boolean importData(JComponent comp, Transferable t) { 118 119 120 121 122 123 model.moveVias(selectedRowsMemento, targetRow); 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 } 150 } 151 152 153 154 155 156 putValue(SHORT_DESCRIPTION,tr("Remove the currently selected vias")); 157 putValue(ACCELERATOR_KEY,KeyStroke.getKeyStroke(KeyEvent.VK_DELETE,0)); 158 159 160 161 162 updateEnabledState(); 163 164 165 166 167 168 169 170 model.removeSelectedVias(); 171 172 173 174 class MoveDownAction extends AbstractAction implements ListSelectionListener{ 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 updateEnabledState(); 197 198 199 200 class MoveUpAction extends AbstractAction implements ListSelectionListener{ 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 updateEnabledState(); 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 public void actionPerformed(ActionEvent e) { 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 } 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 delegate.actionPerformed(e); 277 278 279 280 281 282 283 item.setTransferHandler(transferHandler); 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 } 306 } 48 49 static private final Logger logger = Logger.getLogger(ViaList.class.getName()); 50 51 private ViaListModel model; 52 private DeleteAction actDelete; 53 private MoveUpAction actMoveUp; 54 private MoveDownAction actMoveDown; 55 private CopyAction actCopy; 56 private PasteAction actPaste; 57 private TransferHandler transferHandler; 58 59 /** 60 * Constructor 61 * 62 * @param model the via list model. Must not be null. 63 * @param selectionModel the selection model. Must not be null. 64 * 65 */ 66 public ViaList(ViaListModel model, DefaultListSelectionModel selectionModel) { 67 super(model); 68 this.model = model; 69 setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); 70 setSelectionModel(selectionModel); 71 setCellRenderer(new OsmPrimitivRenderer()); 72 setDragEnabled(true); 73 setTransferHandler(transferHandler =new ViaListTransferHandler(model)); 74 setVisibleRowCount(4); 75 76 actDelete = new DeleteAction(); 77 selectionModel.addListSelectionListener(actDelete); 78 registerKeyboardAction(actDelete, KeyStroke.getKeyStroke(KeyEvent.VK_DELETE,0), JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT); 79 80 actMoveDown = new MoveDownAction(); 81 selectionModel.addListSelectionListener(actMoveDown); 82 registerKeyboardAction(actMoveDown, KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, KeyEvent.ALT_DOWN_MASK), JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT); 83 84 actMoveUp = new MoveUpAction(); 85 selectionModel.addListSelectionListener(actMoveUp); 86 registerKeyboardAction(actMoveUp, KeyStroke.getKeyStroke(KeyEvent.VK_UP, KeyEvent.ALT_DOWN_MASK), JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT); 87 88 actCopy = new CopyAction(); 89 actPaste = new PasteAction(); 90 getSelectionModel().addListSelectionListener(actCopy); 91 92 addMouseListener(new ViaListPopupMenuLaucher()); 93 } 94 95 /** 96 * The transfer handler for Drag-and-Drop. 97 */ 98 class ViaListTransferHandler extends PrimitiveIdListTransferHandler { 99 Logger logger = Logger.getLogger(ViaListTransferHandler.class.getName()); 100 101 private boolean isViaListInDragOperation = false; 102 private List<Integer> selectedRowsMemento = null; 103 104 public ViaListTransferHandler(PrimitiveIdListProvider provider) { 105 super(provider); 106 } 107 108 @Override 109 public boolean canImport(JComponent comp, DataFlavor[] transferFlavors) { 110 // a drag operation on itself is always allowed 111 if (isViaListInDragOperation) return true; 112 return isSupportedFlavor(transferFlavors); 113 } 114 115 @SuppressWarnings("unchecked") 116 @Override 117 public boolean importData(JComponent comp, Transferable t) { 118 if (!isSupportedFlavor(t.getTransferDataFlavors())) return false; 119 if (isViaListInDragOperation) { 120 // this is a drag operation on itself 121 int targetRow = getSelectedIndex(); 122 if (targetRow <0) return true; 123 model.moveVias(selectedRowsMemento, targetRow); 124 } else { 125 // this is a drag operation from another component 126 try { 127 List<PrimitiveId> idsToAdd = (List<PrimitiveId>)t.getTransferData(PrimitiveIdTransferable.PRIMITIVE_ID_LIST_FLAVOR); 128 model.insertVias(idsToAdd); 129 } catch(IOException e){ 130 e.printStackTrace(); 131 } catch(UnsupportedFlavorException e){ 132 e.printStackTrace(); 133 } 134 } 135 return true; 136 } 137 138 @Override 139 protected void exportDone(JComponent source, Transferable data, int action) { 140 isViaListInDragOperation = false; 141 super.exportDone(source, data, action); 142 } 143 144 @Override 145 public void exportAsDrag(JComponent comp, InputEvent e, int action) { 146 isViaListInDragOperation = true; 147 selectedRowsMemento = model.getSelectedRows(); 148 super.exportAsDrag(comp, e, action); 149 } 150 } 151 152 class DeleteAction extends AbstractAction implements ListSelectionListener { 153 public DeleteAction() { 154 putValue(NAME, tr("Remove")); 155 putValue(SMALL_ICON, ImageProvider.get("dialogs", "delete")); 156 putValue(SHORT_DESCRIPTION,tr("Remove the currently selected vias")); 157 putValue(ACCELERATOR_KEY,KeyStroke.getKeyStroke(KeyEvent.VK_DELETE,0)); 158 updateEnabledState(); 159 } 160 161 public void valueChanged(ListSelectionEvent e) { 162 updateEnabledState(); 163 } 164 165 public void updateEnabledState() { 166 setEnabled(getSelectedIndex() >= 0); 167 } 168 169 public void actionPerformed(ActionEvent e) { 170 model.removeSelectedVias(); 171 } 172 } 173 174 class MoveDownAction extends AbstractAction implements ListSelectionListener{ 175 public MoveDownAction(){ 176 putValue(NAME, tr("Move down")); 177 putValue(SHORT_DESCRIPTION, tr("Move the selected vias down by one position")); 178 putValue(ACCELERATOR_KEY,KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, KeyEvent.ALT_DOWN_MASK)); 179 putValue(SMALL_ICON, ImageProvider.get("dialogs", "movedown")); 180 updateEnabledState(); 181 } 182 183 public void actionPerformed(ActionEvent e) { 184 model.moveDown(); 185 } 186 187 public void updateEnabledState(){ 188 if (getSelectedIndex() < 0) { 189 setEnabled(false); 190 return; 191 } 192 setEnabled(getSelectionModel().getMaxSelectionIndex() < getModel().getSize() -1); 193 } 194 195 public void valueChanged(ListSelectionEvent e) { 196 updateEnabledState(); 197 } 198 } 199 200 class MoveUpAction extends AbstractAction implements ListSelectionListener{ 201 public MoveUpAction() { 202 putValue(NAME, tr("Move up")); 203 putValue(SHORT_DESCRIPTION, tr("Move the selected vias up by one position")); 204 putValue(ACCELERATOR_KEY,KeyStroke.getKeyStroke(KeyEvent.VK_UP, KeyEvent.ALT_DOWN_MASK)); 205 putValue(SMALL_ICON, ImageProvider.get("dialogs", "moveup")); 206 updateEnabledState(); 207 } 208 209 public void actionPerformed(ActionEvent e) { 210 model.moveUp(); 211 } 212 213 public void updateEnabledState(){ 214 if (getSelectedIndex() < 0) { 215 setEnabled(false); 216 return; 217 } 218 setEnabled(getSelectionModel().getMinSelectionIndex() > 0); 219 } 220 221 public void valueChanged(ListSelectionEvent e) { 222 updateEnabledState(); 223 } 224 } 225 226 class CopyAction extends AbstractAction implements ListSelectionListener { 227 private Action delegate; 228 229 public CopyAction(){ 230 putValue(NAME, tr("Copy")); 231 putValue(SHORT_DESCRIPTION, tr("Copy the selected vias to the clipboard")); 232 putValue(SMALL_ICON, ImageProvider.get("copy")); 233 putValue(ACCELERATOR_KEY, Shortcut.getCopyKeyStroke()); 234 delegate = ViaList.this.getActionMap().get("copy"); 235 } 236 237 public void actionPerformed(ActionEvent e) { 238 delegate.actionPerformed(e); 239 } 240 241 protected void updateEnabledState() { 242 setEnabled(!model.getSelectedVias().isEmpty()); 243 } 244 245 public void valueChanged(ListSelectionEvent e) { 246 updateEnabledState(); 247 } 248 } 249 250 class PasteAction extends AbstractAction { 251 private Action delegate; 252 253 public boolean canPaste() { 254 Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); 255 for (DataFlavor df: clipboard.getAvailableDataFlavors()) { 256 if (df.equals(PrimitiveIdTransferable.PRIMITIVE_ID_LIST_FLAVOR)) return true; 257 } 258 // FIXME: check whether there are selected objects in the JOSM copy/paste buffer 259 return false; 260 } 261 262 public PasteAction(){ 263 putValue(NAME, tr("Paste")); 264 putValue(SHORT_DESCRIPTION, tr("Insert 'via' objects from the clipboard")); 265 putValue(SMALL_ICON, ImageProvider.get("paste")); 266 putValue(ACCELERATOR_KEY, Shortcut.getPasteKeyStroke()); 267 delegate = ViaList.this.getActionMap().get("paste"); 268 updateEnabledState(); 269 } 270 271 public void updateEnabledState() { 272 setEnabled(canPaste()); 273 } 274 275 public void actionPerformed(ActionEvent e) { 276 delegate.actionPerformed(e); 277 } 278 } 279 280 class ViaListPopupMenu extends JPopupMenu { 281 public ViaListPopupMenu() { 282 JMenuItem item = add(actCopy); 283 item.setTransferHandler(transferHandler); 284 item = add(actPaste); 285 actPaste.updateEnabledState(); 286 item.setTransferHandler(transferHandler); 287 addSeparator(); 288 add(actDelete); 289 addSeparator(); 290 add(actMoveUp); 291 add(actMoveDown); 292 } 293 } 294 295 class ViaListPopupMenuLaucher extends PopupMenuLauncher { 296 @Override 297 public void launch(MouseEvent evt) { 298 if (getSelectedIndex() <0) { 299 int idx = locationToIndex(evt.getPoint()); 300 if (idx >=0) { 301 setSelectedIndex(idx); 302 } 303 } 304 new ViaListPopupMenu().show(ViaList.this, evt.getX(), evt.getY()); 305 } 306 } 307 307 } -
applications/editors/josm/plugins/turnrestrictions/src/org/openstreetmap/josm/plugins/turnrestrictions/editor/ViaListModel.java
r20527 r23192 23 23 */ 24 24 public class ViaListModel extends AbstractListModel implements PrimitiveIdListProvider, Observer{ 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 } 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 } 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 vias.addAll(model.getVias()); 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 } 25 static private final Logger logger = Logger.getLogger(ViaListModel.class.getName()); 26 27 private DefaultListSelectionModel selectionModel; 28 private final ArrayList<OsmPrimitive> vias = new ArrayList<OsmPrimitive>(); 29 private TurnRestrictionEditorModel model; 30 31 /** 32 * Constructor 33 * 34 * @param model the turn restriction editor model. Must not be null. 35 * @param selectionModel the selection model. Must not be null. 36 * @throws IllegalArgumentException thrown if model is null 37 * @throws IllegalArgumentException thrown if selectionModel is null 38 */ 39 public ViaListModel(TurnRestrictionEditorModel model, DefaultListSelectionModel selectionModel) { 40 CheckParameterUtil.ensureParameterNotNull(model, "model"); 41 CheckParameterUtil.ensureParameterNotNull(selectionModel, "selectionModel"); 42 this.model = model; 43 this.selectionModel = selectionModel; 44 model.addObserver(this); 45 refresh(); 46 } 47 48 /** 49 * Replies the list of currently selected vias 50 * 51 * @return the list of currently selected vias 52 */ 53 public List<OsmPrimitive> getSelectedVias() { 54 ArrayList<OsmPrimitive> ret = new ArrayList<OsmPrimitive>(); 55 for (int i=0; i < getSize(); i++) { 56 if (selectionModel.isSelectedIndex(i)) { 57 ret.add(vias.get(i)); 58 } 59 } 60 return ret; 61 } 62 63 /** 64 * Sets the collection of currently selected vias 65 * 66 * @param vias a collection of vias 67 */ 68 public void setSelectedVias(Collection<OsmPrimitive> vias) { 69 selectionModel.clearSelection(); 70 if (vias == null) return; 71 for(OsmPrimitive via: vias) { 72 int idx = this.vias.indexOf(via); 73 if (idx < 0) continue; 74 selectionModel.addSelectionInterval(idx, idx); 75 } 76 } 77 78 /** 79 * Replies the list of selected rows 80 * 81 * @return the list of selected rows 82 */ 83 public List<Integer> getSelectedRows() { 84 ArrayList<Integer> ret = new ArrayList<Integer>(); 85 for (int i=0; i < getSize(); i++) { 86 if (selectionModel.isSelectedIndex(i)) { 87 ret.add(i); 88 } 89 } 90 return ret; 91 } 92 93 protected List<Integer> moveUp(List<Integer> rows, int targetRow) { 94 List<Integer> ret = new ArrayList<Integer>(rows.size()); 95 int delta = rows.get(0) - targetRow; 96 for(int row: rows) { 97 OsmPrimitive via = vias.remove(row); 98 vias.add(row - delta, via); 99 ret.add(row - delta); 100 } 101 return ret; 102 } 103 104 protected List<Integer> moveDown(List<Integer> rows, int targetRow) { 105 List<Integer> ret = new ArrayList<Integer>(rows.size()); 106 int delta = targetRow - rows.get(0); 107 for(int i = rows.size()-1; i >=0; i--) { 108 int row = rows.get(i); 109 OsmPrimitive via = vias.remove(row); 110 vias.add(row + delta, via); 111 ret.add(row + delta); 112 } 113 return ret; 114 } 115 116 public void moveVias(List<Integer> selectedRows, int targetRow){ 117 if (selectedRows == null) return; 118 if (selectedRows.size() == 1){ 119 int sourceRow = selectedRows.get(0); 120 if (sourceRow == targetRow) return; 121 OsmPrimitive via = vias.remove(sourceRow); 122 vias.add(targetRow, via); 123 fireContentsChanged(this, 0, getSize()); 124 selectionModel.setSelectionInterval(targetRow, targetRow); 125 return; 126 } 127 int min = selectedRows.get(0); 128 int max = selectedRows.get(selectedRows.size()-1); 129 if (targetRow < min) { 130 selectedRows = moveUp(selectedRows, targetRow); 131 } else if (targetRow == min){ 132 // do nothing 133 } else if (targetRow - min < getSize() - max){ 134 int delta = Math.min(targetRow - min, getSize()-1 - max); 135 targetRow = min + delta; 136 if (targetRow > min) { 137 selectedRows = moveDown(selectedRows, targetRow); 138 } 139 } 140 fireContentsChanged(this, 0, getSize()); 141 selectionModel.clearSelection(); 142 for(int row: selectedRows) { 143 selectionModel.addSelectionInterval(row, row); 144 } 145 } 146 147 /** 148 * Move the currently selected vias up by one position 149 */ 150 public void moveUp() { 151 List<Integer> sel = getSelectedRows(); 152 if (sel.isEmpty() || sel.get(0) == 0) return; 153 moveVias(sel, sel.get(0)-1); 154 } 155 156 /** 157 * Move the currently selected vias down by one position 158 */ 159 public void moveDown() { 160 List<Integer> sel = getSelectedRows(); 161 if (sel.isEmpty() || sel.get(sel.size()-1) == getSize()-1) return; 162 moveVias(sel, sel.get(sel.size()-1)+1); 163 } 164 165 /** 166 * Inserts a list of OSM objects given by OSM primitive ids. 167 * 168 * @param idsToInsert the ids of the objects to insert 169 */ 170 public void insertVias(List<PrimitiveId> idsToInsert) { 171 if (idsToInsert == null) return; 172 List<OsmPrimitive> primitives = new ArrayList<OsmPrimitive>(idsToInsert.size()); 173 DataSet ds = model.getLayer().data; 174 for(PrimitiveId id: idsToInsert){ 175 OsmPrimitive p = ds.getPrimitiveById(id); 176 if (p == null){ 177 System.out.println(tr("Failed to retrieve OSM object with id {0} from dataset {1}. Cannot add it as ''via''.", id, ds)); 178 continue; 179 } 180 primitives.add(p); 181 } 182 int targetRow = Math.max(selectionModel.getMinSelectionIndex(),0); 183 List<OsmPrimitive> newVias = new ArrayList<OsmPrimitive>(vias); 184 newVias.addAll(targetRow, primitives); 185 model.setVias(newVias); 186 fireContentsChanged(this, 0, getSize()); 187 selectionModel.clearSelection(); 188 for(int i=targetRow; i< targetRow + primitives.size();i++) { 189 selectionModel.addSelectionInterval(i, i); 190 } 191 } 192 193 /** 194 * Removes the currently selected vias 195 */ 196 public void removeSelectedVias() { 197 ArrayList<OsmPrimitive> newVias = new ArrayList<OsmPrimitive>(vias); 198 int j = 0; 199 for(int i=0; i< getSize();i++){ 200 if (!selectionModel.isSelectedIndex(i)) continue; 201 newVias.remove(i-j); 202 j++; 203 } 204 if (j == 0) return; // nothing selected, nothing deleted 205 model.setVias(newVias); 206 } 207 208 /** 209 * Refreshes the list of 'vias' in this model with the current list of 210 * vias from the turn restriction model. 211 */ 212 protected void refresh() { 213 List<OsmPrimitive> sel = getSelectedVias(); 214 vias.clear(); 215 vias.addAll(model.getVias()); 216 fireContentsChanged(this, 0, getSize()); 217 setSelectedVias(sel); 218 } 219 220 public Object getElementAt(int index) { 221 return vias.get(index); 222 } 223 224 public int getSize() { 225 return vias.size(); 226 } 227 228 /* ----------------------------------------------------------------------- */ 229 /* interface PrimitiveIdListProvider */ 230 /* ----------------------------------------------------------------------- */ 231 public List<PrimitiveId> getSelectedPrimitiveIds() { 232 ArrayList<PrimitiveId> ids = new ArrayList<PrimitiveId>(); 233 for (OsmPrimitive p: getSelectedVias()) { 234 ids.add(p.getPrimitiveId()); 235 } 236 return ids; 237 } 238 239 /* ----------------------------------------------------------------------- */ 240 /* interface Observer */ 241 /* ----------------------------------------------------------------------- */ 242 public void update(Observable o, Object arg) { 243 refresh(); 244 } 245 245 } -
applications/editors/josm/plugins/turnrestrictions/src/org/openstreetmap/josm/plugins/turnrestrictions/list/AbstractTurnRestrictionsListView.java
r20666 r23192 15 15 */ 16 16 abstract class AbstractTurnRestrictionsListView extends JPanel { 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 17 protected TurnRestrictionsListModel model; 18 protected JList lstTurnRestrictions; 19 20 public TurnRestrictionsListModel getModel(){ 21 return model; 22 } 23 24 public JList getList() { 25 return lstTurnRestrictions; 26 } 27 28 public void addListSelectionListener(ListSelectionListener listener) { 29 lstTurnRestrictions.addListSelectionListener(listener); 30 } 31 32 public void removeListSelectionListener(ListSelectionListener listener) { 33 lstTurnRestrictions.addListSelectionListener(listener); 34 } 35 36 public void initIconSetFromPreferences(Preferences prefs){ 37 TurnRestrictionCellRenderer renderer = (TurnRestrictionCellRenderer)lstTurnRestrictions.getCellRenderer(); 38 renderer.initIconSetFromPreferences(prefs); 39 } 40 40 } -
applications/editors/josm/plugins/turnrestrictions/src/org/openstreetmap/josm/plugins/turnrestrictions/list/TurnRestrictionCellRenderer.java
r20701 r23192 41 41 */ 42 42 public class TurnRestrictionCellRenderer extends JPanel implements ListCellRenderer, TableCellRenderer{ 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 // the turn restriction icon 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 renderTo(tr); 243 244 245 246 247 248 249 250 251 renderColor(isSelected); 252 253 254 255 renderTo(tr); 256 257 } 43 static private final Logger logger = Logger.getLogger(TurnRestrictionCellRenderer.class.getName()); 44 45 /** the names of restriction types */ 46 static private Set<String> RESTRICTION_TYPES = new HashSet<String>( 47 Arrays.asList(new String[] { 48 "no_left_turn", 49 "no_right_turn", 50 "no_straight_on", 51 "no_u_turn", 52 "only_left_turn", 53 "only_right_turn", 54 "only_straight_on" 55 }) 56 ); 57 58 /** components used to render the turn restriction */ 59 private JLabel icon; 60 private JLabel from; 61 private JLabel to; 62 private String iconSet = "set-a"; 63 64 public TurnRestrictionCellRenderer() { 65 build(); 66 } 67 68 /** 69 * Replies true if {@code restrictionType} is a valid restriction 70 * type. 71 * 72 * @param restrictionType the restriction type 73 * @return true if {@code restrictionType} is a valid restriction 74 * type 75 */ 76 protected boolean isValidRestrictionType(String restrictionType) { 77 if (restrictionType == null) return false; 78 restrictionType = restrictionType.trim().toLowerCase(); 79 return RESTRICTION_TYPES.contains(restrictionType); 80 } 81 82 /** 83 * Builds the icon name for a given restriction type 84 * 85 * @param restrictionType the restriction type 86 * @return the icon name 87 */ 88 protected String buildImageName(String restrictionType) { 89 return "types/" + iconSet + "/" + restrictionType; 90 } 91 92 /** 93 * Replies the icon for a given restriction type 94 * @param restrictionType the restriction type 95 * @return the icon 96 */ 97 protected ImageIcon getIcon(String restrictionType) { 98 if (!isValidRestrictionType(restrictionType)) { 99 return ImageProvider.get("types", "non-standard-type"); 100 } 101 return ImageProvider.get(buildImageName(restrictionType)); 102 } 103 104 /** 105 * Builds the UI used to render turn restrictions 106 */ 107 protected void build() { 108 setLayout(new GridBagLayout()); 109 GridBagConstraints gc = new GridBagConstraints(); 110 111 // the turn restriction icon 112 gc.fill = GridBagConstraints.HORIZONTAL; 113 gc.weightx = 0.0; 114 gc.gridheight = 2; 115 gc.anchor = GridBagConstraints.CENTER; 116 gc.insets = new Insets(0,0,2,2); 117 add(icon = new JLabel(), gc); 118 119 120 // the name of the way with role "from" 121 gc.anchor = GridBagConstraints.NORTHWEST; 122 gc.gridx = 1; 123 gc.gridheight = 1; 124 gc.weightx = 0.0; 125 add(new JMultilineLabel("<html><strong>" + trc("turnrestrictions","From:") + "</strong></html>"), gc); 126 127 gc.gridx = 2; 128 gc.weightx = 1.0; 129 add(from = new JLabel(), gc); 130 131 // the name of the way with role "to" 132 gc.anchor = GridBagConstraints.NORTHWEST; 133 gc.gridx = 1; 134 gc.gridy = 1; 135 gc.weightx = 0.0; 136 add(new JMultilineLabel("<html><strong>" + trc("turnrestriction", "To:") + "</strong></html>"), gc); 137 138 gc.gridx = 2; 139 gc.weightx = 1.0; 140 add(to = new JLabel(), gc); 141 } 142 143 /** 144 * Renders the icon for the turn restriction 145 * 146 * @param tr the turn restriction 147 */ 148 protected void renderIcon(Relation tr) { 149 String restrictionType = tr.get("restriction"); 150 icon.setIcon(getIcon(restrictionType)); 151 } 152 153 /** 154 * Replies a way participating in this turn restriction in a given role 155 * 156 * @param tr the turn restriction 157 * @param role the role (either "from" or "to") 158 * @return the participating way; null, if no way is participating in this role 159 */ 160 private Way getParticipatingWay(Relation tr, String role){ 161 for(RelationMember rm: tr.getMembers()){ 162 if (rm.getRole().trim().toLowerCase().equals(role) && rm.getType().equals(OsmPrimitiveType.WAY)) { 163 return (Way)rm.getMember(); 164 } 165 } 166 return null; 167 } 168 169 protected void renderFrom(Relation tr) { 170 Way from = getParticipatingWay(tr, "from"); 171 if (from == null) { 172 // FIXME: render as warning/error (red background?) 173 this.from.setText(tr("no participating way with role ''from''")); 174 return; 175 } 176 this.from.setText(DefaultNameFormatter.getInstance().format(from)); 177 } 178 179 protected void renderTo(Relation tr) { 180 Way to = getParticipatingWay(tr, "to"); 181 if (to == null) { 182 // FIXME: render as warning/error (red background?) 183 this.to.setText(tr("no participating way with role ''to''")); 184 return; 185 } 186 this.to.setText(DefaultNameFormatter.getInstance().format(to)); 187 } 188 189 /** 190 * Renders the foreground and background color depending on whether 191 * the turn restriction is selected 192 * 193 * @param isSelected true if the turn restriction is selected; false, 194 * otherwise 195 */ 196 protected void renderColor(boolean isSelected) { 197 Color bg; 198 Color fg; 199 if (isSelected) { 200 bg = UIManager.getColor("List.selectionBackground"); 201 fg = UIManager.getColor("List.selectionForeground"); 202 } else { 203 bg = UIManager.getColor("background"); 204 fg = UIManager.getColor("foreground"); 205 } 206 setBackground(bg); 207 this.icon.setBackground(bg); 208 this.from.setBackground(bg); 209 this.to.setBackground(bg); 210 211 setForeground(fg); 212 this.icon.setForeground(fg); 213 this.from.setForeground(fg); 214 this.to.setForeground(fg); 215 } 216 217 /** 218 * Initializes the set of icons used from the preference key 219 * {@see PreferenceKeys#ROAD_SIGNS}. 220 * 221 * @param prefs the JOSM preferences 222 */ 223 public void initIconSetFromPreferences(Preferences prefs){ 224 225 iconSet = prefs.get(PreferenceKeys.ROAD_SIGNS, "set-a"); 226 iconSet = iconSet.trim().toLowerCase(); 227 if (!iconSet.equals("set-a") && !iconSet.equals("set-b")) { 228 iconSet = "set-a"; 229 } 230 } 231 232 /* ---------------------------------------------------------------------------------- */ 233 /* interface ListCellRenderer */ 234 /* ---------------------------------------------------------------------------------- */ 235 public Component getListCellRendererComponent(JList list, Object value, 236 int index, boolean isSelected, boolean cellHasFocus) { 237 238 renderColor(isSelected); 239 Relation tr = (Relation)value; 240 renderIcon(tr); 241 renderFrom(tr); 242 renderTo(tr); 243 return this; 244 } 245 246 /* ---------------------------------------------------------------------------------- */ 247 /* interface TableCellRenderer */ 248 /* ---------------------------------------------------------------------------------- */ 249 public Component getTableCellRendererComponent(JTable table, Object value, 250 boolean isSelected, boolean hasFocus, int row, int column) { 251 renderColor(isSelected); 252 Relation tr = (Relation)value; 253 renderIcon(tr); 254 renderFrom(tr); 255 renderTo(tr); 256 return this; 257 } 258 258 } -
applications/editors/josm/plugins/turnrestrictions/src/org/openstreetmap/josm/plugins/turnrestrictions/list/TurnRestrictionsInDatasetListModel.java
r20489 r23192 34 34 */ 35 35 public class TurnRestrictionsInDatasetListModel extends TurnRestrictionsListModel implements EditLayerChangeListener, DataSetListener { 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 /* --------------------------------------------------------------------------- */ 79 public void dataChanged(DataChangedEvent event) { 80 81 82 83 84 85 86 87 36 private static final Logger logger = Logger.getLogger(TurnRestrictionsInDatasetListModel.class.getName()); 37 38 public TurnRestrictionsInDatasetListModel( 39 DefaultListSelectionModel selectionModel) { 40 super(selectionModel); 41 } 42 43 /** 44 * Filters the list of turn restrictions from a collection of OSM primitives. 45 * 46 * @param primitives the primitives 47 * @return the list of turn restrictions 48 */ 49 protected List<Relation> filterTurnRestrictions(Collection<? extends OsmPrimitive> primitives) { 50 List<Relation> ret = new LinkedList<Relation>(); 51 if (primitives == null) return ret; 52 for(OsmPrimitive p: primitives){ 53 if (!isTurnRestriction(p)) continue; 54 ret.add((Relation)p); 55 } 56 return ret; 57 } 58 59 /* --------------------------------------------------------------------------- */ 60 /* interface EditLayerChangeListener */ 61 /* --------------------------------------------------------------------------- */ 62 public void editLayerChanged(OsmDataLayer oldLayer, OsmDataLayer newLayer) { 63 if (newLayer == null) { 64 setTurnRestrictions(null); 65 return; 66 } 67 List<Relation> turnRestrictions = new LinkedList<Relation>(); 68 for (Relation r: newLayer.data.getRelations()) { 69 if (isValid(r) && isTurnRestriction(r)) { 70 turnRestrictions.add(r); 71 } 72 } 73 setTurnRestrictions(turnRestrictions); 74 } 75 76 /* --------------------------------------------------------------------------- */ 77 /* interface DataSetListener */ 78 /* --------------------------------------------------------------------------- */ 79 public void dataChanged(DataChangedEvent event) { 80 OsmDataLayer layer = Main.map.mapView.getEditLayer(); 81 if (layer == null) { 82 setTurnRestrictions(null); 83 } else { 84 List<Relation> turnRestrictions = filterTurnRestrictions(layer.data.getRelations()); 85 setTurnRestrictions(turnRestrictions); 86 } 87 } 88 88 89 90 91 92 93 94 89 public void primtivesAdded(PrimitivesAddedEvent event) { 90 List<Relation> turnRestrictions = filterTurnRestrictions(event.getPrimitives()); 91 if (!turnRestrictions.isEmpty()) { 92 addTurnRestrictions(turnRestrictions); 93 } 94 } 95 95 96 97 98 99 100 101 96 public void primtivesRemoved(PrimitivesRemovedEvent event) { 97 List<Relation> turnRestrictions = filterTurnRestrictions(event.getPrimitives()); 98 if (!turnRestrictions.isEmpty()) { 99 removeTurnRestrictions(turnRestrictions); 100 } 101 } 102 102 103 104 105 106 107 for(Relation tr: turnRestrictions) { 108 109 110 111 112 113 114 103 public void relationMembersChanged(RelationMembersChangedEvent event) { 104 List<Relation> turnRestrictions = filterTurnRestrictions(event.getPrimitives()); 105 if (!turnRestrictions.isEmpty()) { 106 List<Relation> sel = getSelectedTurnRestrictions(); 107 for(Relation tr: turnRestrictions) { 108 // enforce a repaint of the respective turn restriction 109 int idx = getTurnRestrictionIndex(tr); 110 fireContentsChanged(this, idx,idx); 111 } 112 setSelectedTurnRestrictions(sel); 113 } 114 } 115 115 116 117 118 119 120 for(Relation tr: turnRestrictions) { 121 122 123 124 125 126 } 127 116 public void tagsChanged(TagsChangedEvent event) { 117 List<Relation> turnRestrictions = filterTurnRestrictions(event.getPrimitives()); 118 if (!turnRestrictions.isEmpty()) { 119 List<Relation> sel = getSelectedTurnRestrictions(); 120 for(Relation tr: turnRestrictions) { 121 // enforce a repaint of the respective turn restriction 122 int idx = getTurnRestrictionIndex(tr); 123 fireContentsChanged(this, idx,idx); 124 } 125 setSelectedTurnRestrictions(sel); 126 } 127 } 128 128 129 130 131 129 public void wayNodesChanged(WayNodesChangedEvent event) {/* ignore */} 130 public void nodeMoved(NodeMovedEvent event) {/* ignore */} 131 public void otherDatasetChange(AbstractDatasetChangedEvent event) {/* ignore */} 132 132 } -
applications/editors/josm/plugins/turnrestrictions/src/org/openstreetmap/josm/plugins/turnrestrictions/list/TurnRestrictionsInDatasetView.java
r20711 r23192 18 18 * This is the view for the list of turn restrictions in the current data set. 19 19 */ 20 public class TurnRestrictionsInDatasetView extends AbstractTurnRestrictionsListView{ 21 22 23 24 25 26 27 28 29 30 31 20 public class TurnRestrictionsInDatasetView extends AbstractTurnRestrictionsListView{ 21 protected void build() { 22 DefaultListSelectionModel selectionModel = new DefaultListSelectionModel(); 23 model = new TurnRestrictionsInDatasetListModel(selectionModel); 24 lstTurnRestrictions = new JList(model); 25 lstTurnRestrictions.setSelectionModel(selectionModel); 26 lstTurnRestrictions.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); 27 lstTurnRestrictions.setCellRenderer(new TurnRestrictionCellRenderer()); 28 29 setLayout(new BorderLayout()); 30 add(new JScrollPane(lstTurnRestrictions), BorderLayout.CENTER); 31 } 32 32 33 34 35 36 37 38 39 33 protected void registerAsListener() { 34 MapView.addEditLayerChangeListener((EditLayerChangeListener)model); 35 DatasetEventManager.getInstance().addDatasetListener((DataSetListener)model, FireMode.IN_EDT); 36 if (Main.main.getEditLayer() != null) { 37 model.setTurnRestrictions(Main.main.getEditLayer().data.getRelations()); 38 } 39 } 40 40 41 42 43 44 41 protected void unregisterAsListener() { 42 MapView.removeEditLayerChangeListener((EditLayerChangeListener)model); 43 DatasetEventManager.getInstance().removeDatasetListener((DataSetListener)model); 44 } 45 45 46 47 48 46 public TurnRestrictionsInDatasetView() { 47 build(); 48 } 49 49 } -
applications/editors/josm/plugins/turnrestrictions/src/org/openstreetmap/josm/plugins/turnrestrictions/list/TurnRestrictionsInSelectionListModel.java
r20489 r23192 19 19 */ 20 20 public class TurnRestrictionsInSelectionListModel extends TurnRestrictionsListModel implements EditLayerChangeListener, SelectionChangedListener { 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 21 private static final Logger logger = Logger.getLogger(TurnRestrictionsInSelectionListModel.class.getName()); 22 23 public TurnRestrictionsInSelectionListModel( 24 DefaultListSelectionModel selectionModel) { 25 super(selectionModel); 26 } 27 28 /** 29 * Initializes the model with the turn restrictions the primitives in 30 * {@code selection} participate. 31 * 32 * @param selection the collection of selected primitives 33 */ 34 public void initFromSelection(Collection<? extends OsmPrimitive> selection) { 35 Set<Relation> turnRestrictions = new HashSet<Relation>(); 36 if (selection == null) return; 37 for (OsmPrimitive p: selection) { 38 for (OsmPrimitive parent: p.getReferrers()) { 39 if (isTurnRestriction(parent)) 40 turnRestrictions.add((Relation)parent); 41 } 42 } 43 setTurnRestrictions(turnRestrictions); 44 } 45 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 /* --------------------------------------------------------------------------- */ 60 61 62 46 /* --------------------------------------------------------------------------- */ 47 /* interface EditLayerChangeListener */ 48 /* --------------------------------------------------------------------------- */ 49 public void editLayerChanged(OsmDataLayer oldLayer, OsmDataLayer newLayer) { 50 if (newLayer == null) { 51 setTurnRestrictions(null); 52 return; 53 } 54 initFromSelection(newLayer.data.getSelected()); 55 } 56 57 /* --------------------------------------------------------------------------- */ 58 /* interface SelectionChangedListener */ 59 /* --------------------------------------------------------------------------- */ 60 public void selectionChanged(Collection<? extends OsmPrimitive> newSelection) { 61 initFromSelection(newSelection); 62 } 63 63 } -
applications/editors/josm/plugins/turnrestrictions/src/org/openstreetmap/josm/plugins/turnrestrictions/list/TurnRestrictionsInSelectionView.java
r20711 r23192 24 24 public class TurnRestrictionsInSelectionView extends AbstractTurnRestrictionsListView { 25 25 26 27 28 29 30 31 32 33 34 35 36 26 protected void build() { 27 DefaultListSelectionModel selectionModel = new DefaultListSelectionModel(); 28 model = new TurnRestrictionsInSelectionListModel(selectionModel); 29 lstTurnRestrictions = new JList(model); 30 lstTurnRestrictions.setSelectionModel(selectionModel); 31 lstTurnRestrictions.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); 32 lstTurnRestrictions.setCellRenderer(new TurnRestrictionCellRenderer()); 33 34 setLayout(new BorderLayout()); 35 add(new JScrollPane(lstTurnRestrictions), BorderLayout.CENTER); 36 } 37 37 38 39 40 41 42 43 44 45 46 47 38 protected void registerAsListener() { 39 MapView.addEditLayerChangeListener((EditLayerChangeListener)model); 40 SelectionEventManager.getInstance().addSelectionListener((SelectionChangedListener)model, FireMode.IN_EDT_CONSOLIDATED); 41 TurnRestrictionsInSelectionListModel m = (TurnRestrictionsInSelectionListModel)model; 42 if (Main.main.getEditLayer() != null){ 43 m.initFromSelection(Main.main.getEditLayer().data.getSelected()); 44 } else { 45 m.initFromSelection(Collections.<OsmPrimitive>emptyList()); 46 } 47 } 48 48 49 50 51 SelectionEventManager.getInstance().removeSelectionListener((SelectionChangedListener)model); 52 49 protected void unregisterAsListener() { 50 MapView.removeEditLayerChangeListener((EditLayerChangeListener)model); 51 SelectionEventManager.getInstance().removeSelectionListener((SelectionChangedListener)model); 52 } 53 53 54 55 56 54 public TurnRestrictionsInSelectionView() { 55 build(); 56 } 57 57 } -
applications/editors/josm/plugins/turnrestrictions/src/org/openstreetmap/josm/plugins/turnrestrictions/list/TurnRestrictionsListDialog.java
r20735 r23192 52 52 */ 53 53 public class TurnRestrictionsListDialog extends ToggleDialog{ 54 55 56 57 58 59 60 61 62 63 64 65 66 private DeleteAction actDelete;67 68 69 70 71 72 73 74 75 76 77 78 79 pnlTurnRestrictionsInDataSet.registerAsListener(); 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 } 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 currentListView = view; 186 187 188 189 190 191 192 193 194 195 currentListView.repaint(); 196 197 198 199 200 201 202 203 204 case ItemEvent.DESELECTED: 205 206 207 208 209 210 211 54 private static final Logger logger = Logger.getLogger(TurnRestrictionsListDialog.class.getName()); 55 56 /** checkbox for switching between the two list views */ 57 private JCheckBox cbInSelectionOnly; 58 /** the view for the turn restrictions in the current data set */ 59 private TurnRestrictionsInDatasetView pnlTurnRestrictionsInDataSet; 60 /** the view for the turn restrictions related to the current selection */ 61 private TurnRestrictionsInSelectionView pnlTurnRestrictionsInSelection; 62 63 /** three actions */ 64 private NewAction actNew; 65 private EditAction actEdit; 66 private DeleteAction actDelete; 67 private SelectSelectedTurnRestrictions actSelectSelectedTurnRestrictions; 68 private ZoomToAction actZoomTo; 69 private SwitchListViewHandler switchListViewHandler; 70 71 private AbstractTurnRestrictionsListView currentListView = null; 72 73 /** the main content panel in this toggle dialog */ 74 private JPanel pnlContent; 75 private PreferenceChangeHandler preferenceChangeHandler; 76 77 @Override 78 public void showNotify() { 79 pnlTurnRestrictionsInDataSet.registerAsListener(); 80 pnlTurnRestrictionsInSelection.registerAsListener(); 81 MapView.addEditLayerChangeListener(actNew); 82 actNew.updateEnabledState(); 83 Main.pref.addPreferenceChangeListener(preferenceChangeHandler); 84 preferenceChangeHandler.refreshIconSet(); 85 } 86 87 @Override 88 public void hideNotify() { 89 pnlTurnRestrictionsInDataSet.unregisterAsListener(); 90 pnlTurnRestrictionsInSelection.unregisterAsListener(); 91 MapView.removeEditLayerChangeListener(actNew); 92 Main.pref.removePreferenceChangeListener(preferenceChangeHandler); 93 } 94 95 /** 96 * Builds the panel with the checkbox for switching between the two 97 * list views 98 * 99 * @return the panel 100 */ 101 protected JPanel buildInSelectionOnlyTogglePanel(){ 102 JPanel pnl = new JPanel(new FlowLayout(FlowLayout.LEFT,0,0)); 103 pnl.setBorder(null); 104 pnl.add(cbInSelectionOnly = new JCheckBox(tr("Only participating in selection"))); 105 cbInSelectionOnly.setToolTipText(tr( 106 "<html>Select to display turn restrictions related to object in the current selection only.<br>" 107 + "Deselect to display all turn restrictions in the current data set.</html>")); 108 return pnl; 109 } 110 111 /** 112 * Builds the panel with the action buttons 113 * 114 * @return the panel 115 */ 116 protected JPanel buildCommandPanel() { 117 JPanel pnl = new JPanel(new FlowLayout(FlowLayout.LEFT,0,0)); 118 pnl.setBorder(null); 119 pnl.add(new SideButton(actNew = new NewAction(), false /* don't show the name */)); 120 pnl.add(new SideButton(actEdit = new EditAction(), false /* don't show the name */)); 121 pnl.add(new SideButton(actDelete = new DeleteAction(), false /* don't show the name */)); 122 123 actSelectSelectedTurnRestrictions = new SelectSelectedTurnRestrictions(); 124 actZoomTo = new ZoomToAction(); 125 return pnl; 126 } 127 128 /** 129 * Builds the UI 130 */ 131 protected void build() { 132 pnlContent = new JPanel(new BorderLayout(0,0)); 133 pnlContent.setBorder(null); 134 pnlContent.add(buildInSelectionOnlyTogglePanel(), BorderLayout.NORTH); 135 pnlContent.add(buildCommandPanel(), BorderLayout.SOUTH); 136 137 add(pnlContent, BorderLayout.CENTER); 138 139 // create the two list views 140 pnlTurnRestrictionsInDataSet = new TurnRestrictionsInDatasetView(); 141 pnlTurnRestrictionsInSelection = new TurnRestrictionsInSelectionView(); 142 143 // wire the handler for switching between list views 144 switchListViewHandler = new SwitchListViewHandler(); 145 switchListViewHandler.activateListView(pnlTurnRestrictionsInDataSet); 146 cbInSelectionOnly.addItemListener(switchListViewHandler); 147 148 // wire the popup menu launcher to the two turn restriction lists 149 TurnRestrictionsPopupLauncher launcher = new TurnRestrictionsPopupLauncher(); 150 pnlTurnRestrictionsInDataSet.getList().addMouseListener(launcher); 151 pnlTurnRestrictionsInSelection.getList().addMouseListener(launcher); 152 153 preferenceChangeHandler = new PreferenceChangeHandler(); 154 155 } 156 157 /** 158 * Constructor 159 */ 160 public TurnRestrictionsListDialog() { 161 super( 162 tr("Turn Restrictions"), 163 "turnrestrictions", 164 tr("Display and manage turn restrictions in the current data set"), 165 null, // no shortcut 166 150 // default height 167 ); 168 build(); 169 HelpUtil.setHelpContext(this, HelpUtil.ht("/Plugins/turnrestrictions#TurnRestrictionToggleDialog")); 170 } 171 172 /** 173 * Switches between the two list view. 174 */ 175 class SwitchListViewHandler implements ItemListener { 176 public void activateListView(AbstractTurnRestrictionsListView view) { 177 if (currentListView != null) { 178 currentListView.removeListSelectionListener(actEdit); 179 currentListView.removeListSelectionListener(actDelete); 180 currentListView.removeListSelectionListener(actSelectSelectedTurnRestrictions); 181 currentListView.removeListSelectionListener(actZoomTo); 182 pnlContent.remove(currentListView); 183 } 184 pnlContent.add(view,BorderLayout.CENTER); 185 currentListView = view; 186 view.addListSelectionListener(actEdit); 187 view.addListSelectionListener(actDelete); 188 view.addListSelectionListener(actSelectSelectedTurnRestrictions); 189 view.addListSelectionListener(actZoomTo); 190 actEdit.updateEnabledState(); 191 actDelete.updateEnabledState(); 192 actSelectSelectedTurnRestrictions.updateEnabledState(); 193 actZoomTo.updateEnabledState(); 194 currentListView.revalidate(); 195 currentListView.repaint(); 196 } 197 198 public void itemStateChanged(ItemEvent e) { 199 switch(e.getStateChange()) { 200 case ItemEvent.SELECTED: 201 activateListView(pnlTurnRestrictionsInSelection); 202 break; 203 204 case ItemEvent.DESELECTED: 205 activateListView(pnlTurnRestrictionsInDataSet); 206 break; 207 } 208 } 209 } 210 211 /** 212 212 * The edit action 213 213 * … … 231 231 } 232 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 233 public void launchEditor(Relation toEdit) { 234 if (toEdit == null) 235 return; 236 OsmDataLayer layer = Main.main.getEditLayer(); 237 TurnRestrictionEditorManager manager = TurnRestrictionEditorManager.getInstance(); 238 TurnRestrictionEditor editor = manager.getEditorForRelation(layer, toEdit); 239 if (editor != null) { 240 editor.setVisible(true); 241 editor.toFront(); 242 } else { 243 editor = new TurnRestrictionEditor( 244 TurnRestrictionsListDialog.this, layer,toEdit); 245 manager.positionOnScreen(editor); 246 manager.register(layer, toEdit,editor); 247 editor.setVisible(true); 248 } 249 } 250 250 251 251 public void actionPerformed(ActionEvent e) { … … 258 258 259 259 public void updateEnabledState() { 260 260 setEnabled(currentListView!= null && currentListView.getModel().getSelectedTurnRestrictions().size() == 1); 261 261 } 262 262 … … 298 298 299 299 public void updateEnabledState() { 300 300 setEnabled(currentListView != null && !currentListView.getModel().getSelectedTurnRestrictions().isEmpty()); 301 301 } 302 302 303 303 public void valueChanged(ListSelectionEvent e) { 304 304 updateEnabledState(); 305 305 } 306 306 } … … 319 319 320 320 public void run() { 321 322 323 324 321 OsmDataLayer layer = Main.main.getEditLayer(); 322 if (layer == null) return; 323 Relation tr = new TurnRestrictionBuilder().buildFromSelection(layer); 324 TurnRestrictionEditor editor = new TurnRestrictionEditor(TurnRestrictionsListDialog.this, layer, tr); 325 325 TurnRestrictionEditorManager.getInstance().positionOnScreen(editor); 326 326 TurnRestrictionEditorManager.getInstance().register(layer, tr, editor); … … 336 336 } 337 337 338 339 340 updateEnabledState(); 341 338 public void editLayerChanged(OsmDataLayer oldLayer, 339 OsmDataLayer newLayer) { 340 updateEnabledState(); 341 } 342 342 } 343 343 … … 367 367 368 368 public void updateEnabledState() { 369 369 setEnabled(currentListView != null && !currentListView.getModel().getSelectedTurnRestrictions().isEmpty()); 370 370 } 371 371 372 372 public void valueChanged(ListSelectionEvent e) { 373 373 updateEnabledState(); 374 374 } 375 375 } … … 401 401 402 402 public void updateEnabledState() { 403 403 setEnabled(currentListView != null && !currentListView.getModel().getSelectedTurnRestrictions().isEmpty()); 404 404 } 405 405 406 406 public void valueChanged(ListSelectionEvent e) { 407 407 updateEnabledState(); 408 408 } 409 409 } … … 448 448 * 449 449 */ 450 class PreferenceChangeHandler implements PreferenceChangedListener { 451 452 453 454 455 456 457 public void preferenceChanged(PreferenceChangeEvent evt) { 458 459 460 450 class PreferenceChangeHandler implements PreferenceChangedListener { 451 public void refreshIconSet() { 452 pnlTurnRestrictionsInDataSet.initIconSetFromPreferences(Main.pref); 453 pnlTurnRestrictionsInSelection.initIconSetFromPreferences(Main.pref); 454 repaint(); 455 } 456 457 public void preferenceChanged(PreferenceChangeEvent evt) { 458 if (!evt.getKey().equals(PreferenceKeys.ROAD_SIGNS)) return; 459 refreshIconSet(); 460 } 461 461 } 462 462 } -
applications/editors/josm/plugins/turnrestrictions/src/org/openstreetmap/josm/plugins/turnrestrictions/list/TurnRestrictionsListModel.java
r20489 r23192 73 73 */ 74 74 protected boolean isTurnRestriction(OsmPrimitive primitive) { 75 76 77 78 79 75 if (primitive == null) return false; 76 if (! (primitive instanceof Relation)) return false; 77 String type = primitive.get("type"); 78 if (type == null || ! type.equals("restriction")) return false; 79 return true; 80 80 } 81 81 … … 122 122 continue; 123 123 } 124 125 124 turnrestrictions.add(r); 125 added = true; 126 126 } 127 127 if (added) { … … 143 143 Set<Relation> removedTurnRestrictions = new HashSet<Relation>(); 144 144 for (OsmPrimitive p: removedPrimitives) { 145 145 if (!isTurnRestriction(p)) continue; 146 146 removedTurnRestrictions.add((Relation)p); 147 147 } -
applications/editors/josm/plugins/turnrestrictions/src/org/openstreetmap/josm/plugins/turnrestrictions/preferences/PreferenceEditor.java
r20675 r23192 31 31 */ 32 32 public class PreferenceEditor extends JPanel implements PreferenceSetting{ 33 34 33 34 private PreferencesPanel pnlIconPreferences; 35 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 36 /** 37 * builds the panel with the sponsoring information 38 * 39 * @return 40 */ 41 protected JPanel buildCreditPanel() { 42 JPanel pnl = new JPanel(new GridBagLayout()); 43 pnl.setBorder(BorderFactory.createEmptyBorder(5,5,5,5)); 44 GridBagConstraints gc = new GridBagConstraints(); 45 gc.anchor = GridBagConstraints.NORTHWEST; 46 gc.fill = GridBagConstraints.HORIZONTAL; 47 gc.insets = new Insets(0, 0,0, 5); 48 gc.weightx = 0.0; 49 JLabel lbl = new JLabel(); 50 pnl.add(lbl, gc); 51 lbl.setIcon(ImageProvider.get("skobbler-logo")); 52 53 gc.gridx = 1; 54 gc.weightx = 1.0; 55 HtmlPanel msg =new HtmlPanel(); 56 msg.setText("<html><body>" 57 + tr("Development of the turn restriction plugin was sponsored " 58 + "by <a href=\"http://www.skobbler.de\">skobbler GmbH</a>.") 59 +"</body></html>"); 60 pnl.add(msg, gc); 61 62 // filler - grab remaining space 63 gc.gridy = 1; 64 gc.gridx = 0; 65 gc.gridwidth = 2; 66 gc.weightx = 1.0; 67 gc.weighty = 1.0; 68 pnl.add(new JPanel(), gc); 69 70 SkobblerUrlLauncher urlLauncher = new SkobblerUrlLauncher(); 71 msg.getEditorPane().addHyperlinkListener(urlLauncher); 72 lbl.addMouseListener(urlLauncher); 73 return pnl; 74 } 75 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 tp.add(buildCreditPanel()); 95 96 97 98 99 100 101 102 103 104 105 106 107 76 protected JPanel buildIconPreferencePanel() { 77 JPanel pnl = new JPanel(new BorderLayout()); 78 79 pnlIconPreferences = new PreferencesPanel(); 80 pnlIconPreferences.initFromPreferences(Main.pref); 81 82 JScrollPane sp = new JScrollPane(pnlIconPreferences); 83 sp.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); 84 sp.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED); 85 86 pnl.add(sp, BorderLayout.CENTER); 87 return pnl; 88 } 89 90 protected void build() { 91 setLayout(new BorderLayout()); 92 JTabbedPane tp = new JTabbedPane(); 93 tp.add(buildIconPreferencePanel()); 94 tp.add(buildCreditPanel()); 95 tp.setTitleAt(0, tr("Preferences")); 96 tp.setToolTipTextAt(0,tr("Configure the preferences for the turnrestrictions plugin")); 97 tp.setTitleAt(1, tr("Sponsor")); 98 add(tp, BorderLayout.CENTER); 99 } 100 101 public PreferenceEditor() { 102 build(); 103 } 104 105 public void addGui(PreferenceTabbedPane gui) { 106 String description = tr("An OSM plugin for editing turn restrictions."); 107 JPanel tab = gui.createPreferenceTab("turnrestrictions", tr("Turn Restrictions"), description); 108 108 tab.add(this, GBC.eol().fill(GBC.BOTH)); 109 109 } 110 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 111 public boolean ok() { 112 pnlIconPreferences.saveToPreferences(Main.pref); 113 return false; 114 } 115 116 /** 117 * Launches an external browser with the sponsors home page 118 */ 119 class SkobblerUrlLauncher extends MouseAdapter implements HyperlinkListener { 120 protected void launchBrowser() { 121 OpenBrowser.displayUrl("http://www.skobbler.de"); 122 } 123 124 public void hyperlinkUpdate(HyperlinkEvent e) { 125 if (e.getEventType().equals(HyperlinkEvent.EventType.ACTIVATED)) { 126 launchBrowser(); 127 } 128 } 129 129 130 131 132 133 134 130 @Override 131 public void mouseClicked(MouseEvent e) { 132 launchBrowser(); 133 } 134 } 135 135 } -
applications/editors/josm/plugins/turnrestrictions/src/org/openstreetmap/josm/plugins/turnrestrictions/preferences/PreferenceKeys.java
r20701 r23192 9 9 */ 10 10 public interface PreferenceKeys { 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 11 /** 12 * Indicates which of two sets of road sign icons to use. Supported 13 * values are: 14 * <ul> 15 * <li><tt>set-a</tt> - the set of icons in the directory <tt>/images/types/set-a</tt></li> 16 * <li><tt>set-b</tt> - the set of icons in the directory <tt>/images/types/set-b</tt></li> 17 * </ul> 18 * 19 */ 20 String ROAD_SIGNS = "turnrestrictions.road-signs"; 21 22 /** 23 * Indicates whether the Basic Editor should include a widget for for displaying 24 * and editing the via-objects of a turn restriction. 25 * 26 * Supported values are: 27 * <ul> 28 * <li><tt>true</tt> - display the list of vias in the basic editor </li> 29 * <li><tt>false</tt> - don't display the list of vias in the basic editor </li> 30 * </ul> 31 */ 32 String SHOW_VIAS_IN_BASIC_EDITOR = "turnrestrictions.show-vias-in-basic-editor"; 33 34 /** 35 * The shortcut which triggers creating a new or editing and existing turn 36 * restriction. The value must be parseable by {@see KeyStroke#getKeyStroke(String)}. 37 * If missing, the default value "ctrl shift T" is assumed. 38 */ 39 String EDIT_SHORTCUT= "turnrestrictions.edit-shortcut"; 40 40 } -
applications/editors/josm/plugins/turnrestrictions/src/org/openstreetmap/josm/plugins/turnrestrictions/preferences/PreferencesPanel.java
r20701 r23192 30 30 */ 31 31 public class PreferencesPanel extends VerticallyScrollablePanel { 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 return pnl; 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 return pnl; 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 protected void build() { 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 add(new JSeparator(), gc); 158 159 160 161 162 163 164 165 166 167 168 169 add(new JPanel(), gc);170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 String oldSet = prefs.get(PreferenceKeys.ROAD_SIGNS, "set-a"); 216 217 218 219 220 221 222 223 224 } 225 226 227 228 229 230 231 } 32 private static final Logger logger = Logger.getLogger(PreferencesPanel.class.getName()); 33 private JRadioButton rbSetA; 34 private JRadioButton rbSetB; 35 private ButtonGroup bgIconSet; 36 private JCheckBox cbShowViaListInBasicEditor; 37 private ShortcutPreferencePanel pnlShortcutPreference; 38 39 protected JPanel buildShowViaListInBasicEditorPanel() { 40 JPanel pnl = new JPanel(new GridBagLayout()); 41 GridBagConstraints gc = new GridBagConstraints(); 42 gc.anchor = GridBagConstraints.NORTHWEST; 43 gc.fill = GridBagConstraints.HORIZONTAL; 44 gc.weightx = 1.0; 45 gc.gridx = 0; 46 gc.gridy = 0; 47 48 HtmlPanel msg = new HtmlPanel(); 49 msg.setText("<html><body>" 50 + tr("The Basic Editor can optionally display the list of via-objects " 51 + "of a turn restriction. If enabled, one can edit them " 52 + "in the Basic editor too. If disabled, editing of via-objects is " 53 + "possible in the Advanced Editor only." 54 ) 55 + "</body></html>" 56 ); 57 pnl.add(msg, gc); 58 59 gc.gridy++; 60 pnl.add(cbShowViaListInBasicEditor = new JCheckBox(tr("Display and edit list of via-objects in the Basic Editor")), gc); 61 return pnl; 62 } 63 64 /** 65 * Builds the panel for the icon set "set-a" 66 * 67 * @return 68 */ 69 protected JPanel buildSetAPanel() { 70 JPanel pnl = new JPanel(new GridBagLayout());; 71 GridBagConstraints gc = new GridBagConstraints(); 72 gc.anchor = GridBagConstraints.NORTHWEST; 73 gc.fill = GridBagConstraints.HORIZONTAL; 74 gc.weightx = 1.0; 75 gc.gridx = 0; 76 gc.gridy = 0; 77 78 pnl.add(rbSetA = new JRadioButton(tr("Road signs - Set A")),gc); 79 80 JPanel icons = new JPanel(new FlowLayout(FlowLayout.LEFT)); 81 for (TurnRestrictionType type: TurnRestrictionType.values()){ 82 JLabel lbl = new JLabel(); 83 icons.add(lbl); 84 lbl.setIcon(ImageProvider.get("types/set-a",type.getTagValue())); 85 } 86 87 gc.gridy = 1; 88 gc.insets = new Insets(0,20,0,0); 89 pnl.add(icons, gc); 90 return pnl; 91 } 92 93 /** 94 * Builds the panel for the icon set "set-b" 95 * 96 * @return 97 */ 98 protected JPanel buildSetBPanel() { 99 JPanel pnl = new JPanel(new GridBagLayout());; 100 GridBagConstraints gc = new GridBagConstraints(); 101 gc.anchor = GridBagConstraints.NORTHWEST; 102 gc.fill = GridBagConstraints.HORIZONTAL; 103 gc.weightx = 1.0; 104 gc.gridx = 0; 105 gc.gridy = 0; 106 107 pnl.add(rbSetB = new JRadioButton(tr("Road signs - Set B")),gc); 108 109 JPanel icons = new JPanel(new FlowLayout(FlowLayout.LEFT)); 110 for (TurnRestrictionType type: TurnRestrictionType.values()){ 111 JLabel lbl = new JLabel(); 112 icons.add(lbl); 113 lbl.setIcon(ImageProvider.get("types/set-b",type.getTagValue())); 114 } 115 116 gc.gridy = 1; 117 gc.insets = new Insets(0,20,0,0); 118 pnl.add(icons, gc); 119 return pnl; 120 } 121 122 /** 123 * Builds the message panel at the top 124 * 125 * @return 126 */ 127 protected JPanel buildMessagePanel() { 128 HtmlPanel pnl = new HtmlPanel(); 129 pnl.setText( 130 "<html><body>" 131 + tr("Please select the set of road sign icons to be used in the plugin.") 132 + "</body></html>" 133 ); 134 return pnl; 135 } 136 137 /** 138 * Builds the UI 139 * 140 * @return 141 */ 142 protected void build() { 143 setLayout(new GridBagLayout()); 144 GridBagConstraints gc = new GridBagConstraints(); 145 gc.anchor = GridBagConstraints.NORTHWEST; 146 gc.fill = GridBagConstraints.HORIZONTAL; 147 gc.weightx = 1.0; 148 gc.gridx = 0; 149 gc.gridy = 0; 150 151 add(buildMessagePanel(), gc); 152 gc.gridy++; 153 add(buildSetAPanel(), gc); 154 gc.gridy++; 155 add(buildSetBPanel(), gc); 156 gc.gridy++; 157 add(new JSeparator(), gc); 158 gc.gridy++; 159 add(buildShowViaListInBasicEditorPanel(), gc); 160 gc.gridy++; 161 add(new JSeparator(), gc); 162 gc.gridy++; 163 add(pnlShortcutPreference = new ShortcutPreferencePanel(), gc); 164 165 // filler - just grab remaining space 166 gc.gridy++; 167 gc.fill = GridBagConstraints.BOTH; 168 gc.weighty = 1.0; 169 add(new JPanel(), gc); 170 171 bgIconSet = new ButtonGroup(); 172 bgIconSet.add(rbSetA); 173 bgIconSet.add(rbSetB); 174 175 setBorder(BorderFactory.createEmptyBorder(5,5,5,5)); 176 } 177 178 /** 179 * Initializes the UI from the current settings in the JOSM preferences 180 * {@code prefs} 181 * 182 * @param prefs the preferences 183 */ 184 public void initFromPreferences(Preferences prefs){ 185 String set = prefs.get(PreferenceKeys.ROAD_SIGNS, "set-a"); 186 set = set.trim().toLowerCase(); 187 if (! set.equals("set-a") && ! set.equals("set-b")) { 188 System.out.println(tr("Warning: the preference with key ''{0}'' has an unsupported value ''{1}''. Assuming the default value ''set-a''.", PreferenceKeys.ROAD_SIGNS, set)); 189 set = "set-a"; 190 } 191 if (set.equals("set-a")){ 192 rbSetA.setSelected(true); 193 } else { 194 rbSetB.setSelected(true); 195 } 196 197 boolean b = prefs.getBoolean(PreferenceKeys.SHOW_VIAS_IN_BASIC_EDITOR, false); 198 cbShowViaListInBasicEditor.setSelected(b); 199 200 pnlShortcutPreference.initFromPreferences(prefs); 201 } 202 203 /** 204 * Saves the current settings to the JOSM preferences {@code prefs}. 205 * 206 * @param prefs the preferences 207 */ 208 public void saveToPreferences(Preferences prefs){ 209 String set = null; 210 if (rbSetA.isSelected()){ 211 set = "set-a"; 212 } else { 213 set = "set-b"; 214 } 215 String oldSet = prefs.get(PreferenceKeys.ROAD_SIGNS, "set-a"); 216 if (!set.equals(oldSet)){ 217 prefs.put(PreferenceKeys.ROAD_SIGNS, set); 218 } 219 220 boolean newValue = cbShowViaListInBasicEditor.isSelected(); 221 boolean oldValue = prefs.getBoolean(PreferenceKeys.SHOW_VIAS_IN_BASIC_EDITOR, false); 222 if (newValue != oldValue){ 223 prefs.put(PreferenceKeys.SHOW_VIAS_IN_BASIC_EDITOR, newValue); 224 } 225 226 pnlShortcutPreference.saveToPreferences(prefs); 227 } 228 229 public PreferencesPanel() { 230 build(); 231 } 232 232 } -
applications/editors/josm/plugins/turnrestrictions/src/org/openstreetmap/josm/plugins/turnrestrictions/preferences/ShortcutPreferencePanel.java
r20701 r23192 36 36 */ 37 37 public class ShortcutPreferencePanel extends JPanel { 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 if (cbMeta.isSelected()) modifiers |= KeyEvent.META_DOWN_MASK; 131 132 133 pref.put(PreferenceKeys.EDIT_SHORTCUT, ks.toString()); 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 this.selected = (Integer)anItem; 165 166 167 168 169 170 171 172 173 } 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 } 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 return new Integer(f1).compareTo(f2); 220 221 222 } 223 } 224 38 39 private JCheckBox cbCtrl; 40 private JCheckBox cbAlt; 41 private JCheckBox cbShift; 42 private JCheckBox cbMeta; 43 private JComboBox cmKeyCodes; 44 45 protected JPanel buildMessagePanel() { 46 HtmlPanel pnl = new HtmlPanel(); 47 pnl.setText("<html><body>" 48 + tr("Please configure the <strong>keyboard shortcut</strong> which triggers " 49 + "creating/editing a turn restriction from the current JOSM selection.") 50 + "</body></html>" 51 ); 52 return pnl; 53 } 54 55 protected JPanel buildShortCutConfigPanel() { 56 JPanel pnl = new JPanel(new GridBagLayout()); 57 GridBagConstraints gc = new GridBagConstraints(); 58 gc.anchor = GridBagConstraints.NORTHWEST; 59 gc.fill = GridBagConstraints.HORIZONTAL; 60 gc.weightx = 0.0; 61 gc.gridx = 0; 62 gc.gridy = 0; 63 64 pnl.add(new JLabel(trc("keyboard-key", "Key:")), gc); 65 gc.gridx++; 66 gc.gridwidth=4; 67 gc.weightx = 1.0; 68 pnl.add(cmKeyCodes = new JComboBox(new VKeyComboBoxModel()), gc); 69 cmKeyCodes.setRenderer(new VKeyCellRenderer()); 70 71 gc.gridx = 0; 72 gc.gridy = 1; 73 gc.gridwidth = 1; 74 gc.weightx = 0.0; 75 pnl.add(new JLabel(trc("keyboard-modifiers", "Modifiers:")), gc); 76 77 gc.gridx++; 78 pnl.add(cbShift = new JCheckBox(trc("keyboard-modifiers", "Shift")), gc); 79 gc.gridx++; 80 pnl.add(cbCtrl = new JCheckBox(trc("keyboard-modifiers", "Ctrl")), gc); 81 gc.gridx++; 82 pnl.add(cbAlt = new JCheckBox(trc("keyboard-modifiers", "Alt")), gc); 83 gc.gridx++; 84 gc.weightx = 1.0; 85 pnl.add(cbMeta = new JCheckBox(trc("keyboard-modifiers", "Meta")), gc); 86 87 return pnl; 88 } 89 90 protected void build() { 91 setLayout(new GridBagLayout()); 92 GridBagConstraints gc = new GridBagConstraints(); 93 gc.anchor = GridBagConstraints.NORTHWEST; 94 gc.fill = GridBagConstraints.HORIZONTAL; 95 gc.weightx = 1.0; 96 gc.gridx = 0; 97 gc.gridy = 0; 98 add(buildMessagePanel(), gc); 99 gc.gridy++; 100 add(buildShortCutConfigPanel(), gc); 101 } 102 103 public ShortcutPreferencePanel() { 104 build(); 105 } 106 107 public void initFromPreferences(Preferences pref){ 108 String value = pref.get(PreferenceKeys.EDIT_SHORTCUT, "shift ctrl T"); 109 KeyStroke key = KeyStroke.getKeyStroke(value); 110 if (key == null){ 111 System.out.println(tr("Warning: illegal value ''{0}'' for preference key ''{1}''. Falling back to default value ''shift ctrl T''.", value, PreferenceKeys.EDIT_SHORTCUT)); 112 key = KeyStroke.getKeyStroke("shift ctrl T"); 113 } 114 cmKeyCodes.getModel().setSelectedItem(key.getKeyCode()); 115 cbAlt.setSelected((key.getModifiers() & KeyEvent.ALT_DOWN_MASK) != 0); 116 cbCtrl.setSelected((key.getModifiers() & KeyEvent.CTRL_DOWN_MASK) != 0); 117 cbShift.setSelected((key.getModifiers() & KeyEvent.SHIFT_DOWN_MASK) != 0); 118 cbMeta.setSelected((key.getModifiers() & KeyEvent.META_DOWN_MASK) != 0); 119 } 120 121 public void saveToPreferences(Preferences pref){ 122 Integer code = (Integer)cmKeyCodes.getModel().getSelectedItem(); 123 if (code == null) { 124 code = KeyEvent.VK_T; 125 } 126 int modifiers = 0; 127 if (cbAlt.isSelected()) modifiers |= KeyEvent.ALT_DOWN_MASK; 128 if (cbCtrl.isSelected()) modifiers |= KeyEvent.CTRL_DOWN_MASK; 129 if (cbShift.isSelected()) modifiers |= KeyEvent.SHIFT_DOWN_MASK; 130 if (cbMeta.isSelected()) modifiers |= KeyEvent.META_DOWN_MASK; 131 KeyStroke ks = KeyStroke.getKeyStroke(code, modifiers); 132 133 pref.put(PreferenceKeys.EDIT_SHORTCUT, ks.toString()); 134 CreateOrEditTurnRestrictionAction.install(ks); 135 } 136 137 static private class VKeyComboBoxModel extends AbstractListModel implements ComboBoxModel { 138 private final ArrayList<Integer> keys = new ArrayList<Integer>(); 139 private Integer selected = null; 140 141 public VKeyComboBoxModel() { 142 populate(); 143 } 144 145 public void populate() { 146 for (Field f :KeyEvent.class.getFields()) { 147 if (! Modifier.isStatic(f.getModifiers())) continue; 148 if (! f.getName().startsWith("VK_")) continue; 149 try { 150 keys.add((Integer)f.get(null)); 151 } catch(IllegalAccessException e){ 152 // ignore 153 } 154 } 155 156 Collections.sort(keys, new KeyCodeComparator()); 157 } 158 159 public Object getSelectedItem() { 160 return selected; 161 } 162 163 public void setSelectedItem(Object anItem) { 164 this.selected = (Integer)anItem; 165 } 166 167 public Object getElementAt(int index) { 168 return keys.get(index); 169 } 170 171 public int getSize() { 172 return keys.size(); 173 } 174 } 175 176 static private class VKeyCellRenderer extends JLabel implements ListCellRenderer { 177 public Component getListCellRendererComponent(JList list, Object value, 178 int index, boolean isSelected, boolean cellHasFocus) { 179 if (isSelected) { 180 setBackground(UIManager.getColor("ComboBox.selectionBackground")); 181 setForeground(UIManager.getColor("ComboBox.selectionForeground")); 182 } else { 183 setBackground(UIManager.getColor("ComboBox.background")); 184 setForeground(UIManager.getColor("ComboBox.foreground")); 185 } 186 setText(KeyEvent.getKeyText((Integer)value)); 187 return this; 188 } 189 } 190 191 static private class KeyCodeComparator implements Comparator<Integer> { 192 private final static Map<Integer, String> keyNames = new HashMap<Integer, String>(); 193 194 protected String keyName(Integer code){ 195 String name = keyNames.get(code); 196 if (name == null){ 197 name = KeyEvent.getKeyText(code); 198 keyNames.put(code, name); 199 } 200 return name; 201 } 202 /** 203 * Make sure single letter keys (A-Z, 0-9) are at the top of the list. 204 * Make sure function key F1-F19 are sorted numerically, not lexicografically. 205 * 206 */ 207 public int compare(Integer kc1, Integer kc2) { 208 String n1 = keyName(kc1); 209 String n2 = keyName(kc2); 210 if (n1.length() == 1 && n2.length()==1){ 211 return n1.compareTo(n2); 212 } else if (n1.length() == 1){ 213 return -1; 214 } else if (n2.length() == 1){ 215 return 1; 216 } else if (n1.matches("F\\d+") && n2.matches("F\\d+")){ 217 int f1 = Integer.parseInt(n1.substring(1)); 218 int f2 = Integer.parseInt(n2.substring(1)); 219 return new Integer(f1).compareTo(f2); 220 } else { 221 return n1.compareTo(n2); 222 } 223 } 224 } 225 225 } -
applications/editors/josm/plugins/turnrestrictions/src/org/openstreetmap/josm/plugins/turnrestrictions/qa/IdenticalTurnRestrictionLegsError.java
r20701 r23192 15 15 */ 16 16 public class IdenticalTurnRestrictionLegsError extends Issue{ 17 18 19 20 21 22 23 24 25 17 private OsmPrimitive leg; 18 19 public IdenticalTurnRestrictionLegsError(IssuesModel parent, OsmPrimitive leg) { 20 super(parent, Severity.ERROR); 21 actions.add(new DeleteFromAction()); 22 actions.add(new DeleteToAction()); 23 actions.add(new FixInEditorAction()); 24 this.leg = leg; 25 } 26 26 27 28 public String getText() { 29 30 31 32 ); 33 34 35 36 37 38 39 40 41 getIssuesModel().getEditorModel().getRelationMemberEditorModel().setFromPrimitive(null); 42 } 43 44 45 46 47 48 49 50 51 getIssuesModel().getEditorModel().getRelationMemberEditorModel().setToPrimitive(null); 52 } 53 54 55 56 57 58 59 60 61 getIssuesModel().getNavigationControler().gotoBasicEditor(); 62 } 63 27 @Override 28 public String getText() { 29 return tr("This turn restriction uses the OSM way <span class=\"object-name\">{0}</span> with role <tt>from</tt> <strong>and</strong> with role <tt>to</tt>. " 30 + "In a turn restriction, the way with role <tt>from</tt> should be different from the way with role <tt>to</tt>, though.", 31 leg.getDisplayName(DefaultNameFormatter.getInstance()) 32 ); 33 } 34 35 class DeleteFromAction extends AbstractAction { 36 public DeleteFromAction() { 37 putValue(NAME, tr("Delete ''from''")); 38 putValue(SHORT_DESCRIPTION, tr("Removes the member with role ''from''")); 39 } 40 public void actionPerformed(ActionEvent e) { 41 getIssuesModel().getEditorModel().getRelationMemberEditorModel().setFromPrimitive(null); 42 } 43 } 44 45 class DeleteToAction extends AbstractAction { 46 public DeleteToAction() { 47 putValue(NAME, tr("Delete ''to''")); 48 putValue(SHORT_DESCRIPTION, tr("Removes the member with role ''to''")); 49 } 50 public void actionPerformed(ActionEvent e) { 51 getIssuesModel().getEditorModel().getRelationMemberEditorModel().setToPrimitive(null); 52 } 53 } 54 55 class FixInEditorAction extends AbstractAction { 56 public FixInEditorAction() { 57 putValue(NAME, tr("Fix in editor")); 58 putValue(SHORT_DESCRIPTION, tr("Go to Basic Editor and manually choose members with roles ''from'' and ''to''")); 59 } 60 public void actionPerformed(ActionEvent e) { 61 getIssuesModel().getNavigationControler().gotoBasicEditor(); 62 } 63 } 64 64 } -
applications/editors/josm/plugins/turnrestrictions/src/org/openstreetmap/josm/plugins/turnrestrictions/qa/IllegalRestrictionTypeError.java
r20622 r23192 15 15 */ 16 16 public class IllegalRestrictionTypeError extends Issue{ 17 18 19 20 21 22 23 17 private String value; 18 19 public IllegalRestrictionTypeError(IssuesModel parent, String value) { 20 super(parent, Severity.ERROR); 21 actions.add(new FixInEditorAction()); 22 this.value = value; 23 } 24 24 25 26 public String getText() { 27 28 29 30 ); 31 32 33 34 35 36 37 38 39 getIssuesModel().getNavigationControler().gotoBasicEditor(NavigationControler.BasicEditorFokusTargets.RESTRICION_TYPE); 40 } 41 25 @Override 26 public String getText() { 27 return tr("This turn restriction uses a non-standard restriction type <tt>{0}</tt> for the tag key <tt>restriction</tt>. " 28 + "It is recommended to use standard values only. Please select one in the Basic editor.", 29 value 30 ); 31 } 32 33 class FixInEditorAction extends AbstractAction { 34 public FixInEditorAction() { 35 putValue(NAME, tr("Fix in editor")); 36 putValue(SHORT_DESCRIPTION, tr("Go to Basic Editor and manually choose a turn restriction type")); 37 } 38 public void actionPerformed(ActionEvent e) { 39 getIssuesModel().getNavigationControler().gotoBasicEditor(NavigationControler.BasicEditorFokusTargets.RESTRICION_TYPE); 40 } 41 } 42 42 } -
applications/editors/josm/plugins/turnrestrictions/src/org/openstreetmap/josm/plugins/turnrestrictions/qa/IntersectionMissingAsViaError.java
r20701 r23192 20 20 */ 21 21 public class IntersectionMissingAsViaError extends Issue{ 22 23 24 25 26 27 28 29 30 31 32 33 22 private Way from; 23 private Way to; 24 private Node interesect; 25 26 public IntersectionMissingAsViaError(IssuesModel parent, Way from, Way to, Node intersect) { 27 super(parent, Severity.ERROR); 28 this.from = from; 29 this.to = to; 30 this.interesect = intersect; 31 actions.add(new SetVia()); 32 actions.add(new FixInEditorAction()); 33 } 34 34 35 36 public String getText() { 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 getIssuesModel().getEditorModel().setVias(Collections.<OsmPrimitive>singletonList(interesect)); 54 } 55 56 57 58 59 60 61 62 63 getIssuesModel().getNavigationControler().gotoBasicEditor(BasicEditorFokusTargets.VIA); 64 } 65 35 @Override 36 public String getText() { 37 String msg = tr("The <strong>from</strong>-way <span class=\"object-name\">{0}</span> and the <strong>to</strong>-way <span class=\"object-name\">{1}</span> " 38 + "interesect at node <span class=\"object-name\">{2}</span> but <span class=\"object-name\">{2}</span> isn''t a <strong>via</strong>-object.<br> " 39 + "It is recommended to set <span class=\"object-name\">{2}</span> as unique <strong>via</strong>-object.", 40 this.from.getDisplayName(DefaultNameFormatter.getInstance()), 41 this.to.getDisplayName(DefaultNameFormatter.getInstance()), 42 this.interesect.getDisplayName(DefaultNameFormatter.getInstance()) 43 ); 44 return msg; 45 } 46 47 class SetVia extends AbstractAction { 48 public SetVia() { 49 putValue(NAME, tr("Set via-Object")); 50 putValue(SHORT_DESCRIPTION, tr("Replaces the currently configured via-objects with the node at the intersection")); 51 } 52 public void actionPerformed(ActionEvent e) { 53 getIssuesModel().getEditorModel().setVias(Collections.<OsmPrimitive>singletonList(interesect)); 54 } 55 } 56 57 class FixInEditorAction extends AbstractAction { 58 public FixInEditorAction() { 59 putValue(NAME, tr("Fix in editor")); 60 putValue(SHORT_DESCRIPTION, tr("Go to Basic Editor and manually fix the list of via-objects")); 61 } 62 public void actionPerformed(ActionEvent e) { 63 getIssuesModel().getNavigationControler().gotoBasicEditor(BasicEditorFokusTargets.VIA); 64 } 65 } 66 66 } -
applications/editors/josm/plugins/turnrestrictions/src/org/openstreetmap/josm/plugins/turnrestrictions/qa/Issue.java
r20622 r23192 18 18 */ 19 19 abstract public class Issue { 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 20 /** the parent model for this issue */ 21 protected IssuesModel parent; 22 protected Severity severity; 23 protected final ArrayList<Action> actions = new ArrayList<Action>(); 24 25 /** 26 * Creates a new issue associated with a parent model. Severity is 27 * initialized to {@see Severity#WARNING}. 28 * 29 * @param parent the parent model. Must not be null. 30 * @throws IllegalArgumentException thrown if parent is null 31 */ 32 public Issue(IssuesModel parent) throws IllegalArgumentException{ 33 CheckParameterUtil.ensureParameterNotNull(parent, "parent"); 34 this.parent = parent; 35 this.severity = Severity.WARNING; 36 } 37 38 /** 39 * Creates a new issue of severity {@code severity} associated with 40 * the parent model {@code parent}. 41 * 42 * @param parent the parent model. Must not be null. 43 * @param severity the severity. Must not be null. 44 * @throws IllegalArgumentException thrown if parent is null 45 * @throws IllegalArgumentException thrown if severity is null 46 */ 47 public Issue(IssuesModel parent, Severity severity){ 48 CheckParameterUtil.ensureParameterNotNull(parent, "parent"); 49 CheckParameterUtil.ensureParameterNotNull(severity, "severity"); 50 this.parent = parent; 51 this.severity = severity; 52 } 53 53 54 55 56 57 58 59 60 61 54 /** 55 * Replies the parent model this issue is associated with 56 * 57 * @return the parent model 58 */ 59 public IssuesModel getIssuesModel() { 60 return parent; 61 } 62 62 63 64 65 66 67 68 69 70 63 /** 64 * Replies the severity of this issue 65 * 66 * @return the severity 67 */ 68 public Severity getSeverity() { 69 return severity; 70 } 71 71 72 73 74 75 76 77 78 79 80 81 72 /** 73 * Sets the severity of this issue. 74 * 75 * @param severity the severity. Must not be null. 76 * @throws IllegalArgumentException thrown if severity is null 77 */ 78 public void setSeverity(Severity severity) throws IllegalArgumentException { 79 CheckParameterUtil.ensureParameterNotNull(severity, "severity"); 80 this.severity = severity; 81 } 82 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 83 /** 84 * Replies the HTML formatted description of the issue. The text should neither include 85 * the <html>, nor the <body> tag. 86 * 87 * @return the HTML formatted description of the issue. 88 */ 89 public abstract String getText(); 90 91 /** 92 * Replies a list of actions which can be applied to this issue in order to fix 93 * it. The default implementation replies an empty list. 94 * 95 * @return a list of action 96 */ 97 public List<Action> getActions() { 98 return Collections.unmodifiableList(actions); 99 } 100 100 } -
applications/editors/josm/plugins/turnrestrictions/src/org/openstreetmap/josm/plugins/turnrestrictions/qa/IssueView.java
r20645 r23192 26 26 public class IssueView extends JPanel{ 27 27 28 29 30 31 32 33 34 28 private HtmlPanel pnlMessage; 29 private JPanel pnlActions; 30 private Issue issue; 31 private JLabel lblIcon; 32 private StyleSheet styleSheet; 33 34 /** 35 35 * Builds the style sheet used in the internal help browser 36 36 * … … 43 43 ss.addRule(".object-name {background-color:rgb(240,240,240); color: blue;}"); 44 44 } 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 45 46 protected void build() { 47 setLayout(new GridBagLayout()); 48 setBackground(Color.WHITE); 49 setBorder(BorderFactory.createLineBorder(Color.DARK_GRAY, 1)); 50 51 // add the icon for the severity 52 GridBagConstraints gc = new GridBagConstraints(); 53 gc.anchor = GridBagConstraints.NORTHWEST; 54 gc.fill = GridBagConstraints.VERTICAL; 55 gc.gridheight = 2; 56 gc.weightx = 0.0; 57 gc.weighty = 1.0; 58 gc.gridx = 0; 59 gc.gridy = 0; 60 gc.insets = new Insets(2,2,2,2); 61 add(lblIcon = new JLabel(), gc); 62 lblIcon.setVerticalAlignment(SwingConstants.TOP); 63 lblIcon.setHorizontalAlignment(SwingConstants.CENTER); 64 lblIcon.setBorder(BorderFactory.createEmptyBorder(2,2,2,2)); 65 65 66 67 68 69 70 71 72 73 74 75 76 77 78 66 // add the html panel with the issue description 67 gc.insets = new Insets(0,0,0,0); 68 gc.anchor = GridBagConstraints.NORTHWEST; 69 gc.fill = GridBagConstraints.BOTH; 70 gc.gridx = 1; 71 gc.gridy = 0; 72 gc.gridheight = 1; 73 gc.weightx = 1.0; 74 gc.weighty = 1.0; 75 add(pnlMessage = new HtmlPanel(), gc); 76 initStyleSheet(pnlMessage); 77 pnlMessage.setBackground(Color.white); 78 pnlMessage.setText("<html><body>" + issue.getText() + "</html></bod>"); 79 79 80 81 82 83 84 85 86 87 pnlActions.add(btn); 88 89 90 gc.gridx = 1; 91 gc.gridy = 1; 92 93 94 95 } 96 97 98 99 100 101 102 103 104 105 } 106 107 108 109 110 111 112 113 114 115 116 117 build(); 118 80 81 // if there are any actions available to resolve the issue, add a panel with action buttons 82 if (!issue.getActions().isEmpty()) { 83 pnlActions = new JPanel(new FlowLayout(FlowLayout.LEFT)); 84 pnlActions.setBackground(Color.WHITE); 85 for (Action action: issue.getActions()){ 86 JButton btn = new JButton(action); 87 pnlActions.add(btn); 88 } 89 90 gc.gridx = 1; 91 gc.gridy = 1; 92 gc.fill = GridBagConstraints.HORIZONTAL; 93 gc.weighty = 0.0; 94 add(pnlActions,gc); 95 } 96 97 // set the severity icon 98 switch(issue.getSeverity()){ 99 case WARNING: 100 lblIcon.setIcon(ImageProvider.get("warning-small")); 101 break; 102 case ERROR: 103 lblIcon.setIcon(ImageProvider.get("error")); 104 break; 105 } 106 } 107 108 /** 109 * Creates an issue view for an issue. 110 * 111 * @param issue the issue. Must not be null. 112 * @throws IllegalArgumentException thrown if issue is null. 113 */ 114 public IssueView(Issue issue) throws IllegalArgumentException{ 115 CheckParameterUtil.ensureParameterNotNull(issue, "issue"); 116 this.issue = issue; 117 build(); 118 } 119 119 120 121 122 123 120 @Override 121 public Dimension getMinimumSize() { 122 return super.getPreferredSize(); 123 } 124 124 } -
applications/editors/josm/plugins/turnrestrictions/src/org/openstreetmap/josm/plugins/turnrestrictions/qa/IssuesModel.java
r20724 r23192 31 31 */ 32 32 public class IssuesModel extends Observable implements Observer{ 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 } 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 } 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 populate(); 263 33 private final ArrayList<Issue> issues = new ArrayList<Issue>(); 34 private TurnRestrictionEditorModel editorModel; 35 36 /** 37 * Creates the model 38 * 39 * {@code controler} is used in resolution actions for issues in 40 * this model to direct the user to a specific input field in one 41 * of the editor tabs in order to fix an issue. 42 * 43 * @param editorModel the editor model. Must not be null. 44 * @throws IllegalArgumentException thrown if controler is null 45 */ 46 public IssuesModel(TurnRestrictionEditorModel editorModel) throws IllegalArgumentException{ 47 CheckParameterUtil.ensureParameterNotNull(editorModel, "editorModel"); 48 this.editorModel = editorModel; 49 this.editorModel.addObserver(this); 50 } 51 52 /** 53 * Populates the model with a list of issues. Just clears the model 54 * if {@code issues} is null or empty. 55 * 56 * @param issues the list of issues. 57 */ 58 public void populate(List<Issue> issues){ 59 this.issues.clear(); 60 if (issues != null){ 61 this.issues.addAll(issues); 62 } 63 setChanged(); 64 notifyObservers(); 65 } 66 67 /** 68 * Replies the (unmodifiable) list of issues in this model. 69 * 70 * @return the (unmodifiable) list of issues in this model. 71 */ 72 public List<Issue> getIssues() { 73 return Collections.unmodifiableList(issues); 74 } 75 76 /** 77 * Replies the turn restriction editor model 78 * 79 * @return 80 */ 81 public TurnRestrictionEditorModel getEditorModel() { 82 return editorModel; 83 } 84 85 /** 86 * Populates this model with issues derived from the state of the 87 * turn restriction editor model. If {@code editorModel} is null, the 88 * list of issues is cleared. 89 * 90 * @param editorModel the editor model. 91 */ 92 public void populate() { 93 issues.clear(); 94 if (editorModel != null) { 95 checkTags(editorModel); 96 checkFromLeg(editorModel); 97 checkToLeg(editorModel); 98 checkFromAndToEquals(editorModel); 99 checkVias(editorModel); 100 } 101 setChanged(); 102 notifyObservers(); 103 } 104 105 /** 106 * Checks whether there are required tags missing. 107 * 108 * @param editorModel 109 */ 110 protected void checkTags(TurnRestrictionEditorModel editorModel) { 111 TagEditorModel tagEditorModel = editorModel.getTagEditorModel(); 112 TagModel tag = tagEditorModel.get("type"); 113 114 // missing marker tag for a turn restriction 115 if (tag == null || ! tag.getValue().trim().equals("restriction")) { 116 issues.add(new RequiredTagMissingError(this, "type", "restriction")); 117 } 118 119 // missing or illegal restriction type ? 120 tag = tagEditorModel.get("restriction"); 121 if (tag == null) { 122 issues.add(new MissingRestrictionTypeError(this)); 123 } else if (!TurnRestrictionType.isStandardTagValue(tag.getValue())) { 124 issues.add(new IllegalRestrictionTypeError(this, tag.getValue())); 125 } 126 127 // non-standard value for the 'except' tag? 128 ExceptValueModel except = getEditorModel().getExcept(); 129 if (!except.isStandard()) { 130 issues.add(new NonStandardExceptWarning(this, except)); 131 } 132 } 133 134 /** 135 * Checks various data integrity restriction for the relation member with 136 * role 'from'. 137 * 138 */ 139 protected void checkFromLeg(TurnRestrictionEditorModel editorModel) { 140 Set<OsmPrimitive> froms = editorModel.getTurnRestrictionLeg(TurnRestrictionLegRole.FROM); 141 if (froms.isEmpty()){ 142 issues.add(new MissingTurnRestrictionLegError(this, TurnRestrictionLegRole.FROM)); 143 return; 144 } else if (froms.size() > 1){ 145 issues.add(new MultipleTurnRestrictionLegError(this, TurnRestrictionLegRole.FROM, froms.size())); 146 return; 147 } 148 OsmPrimitive p = froms.iterator().next(); 149 if (! (p instanceof Way)) { 150 issues.add(new WrongTurnRestrictionLegTypeError(this, TurnRestrictionLegRole.FROM, p)); 151 } 152 } 153 154 /** 155 * Checks various data integrity restriction for the relation member with 156 * role 'to'. 157 * 158 */ 159 protected void checkToLeg(TurnRestrictionEditorModel editorModel) { 160 Set<OsmPrimitive> toLegs = editorModel.getTurnRestrictionLeg(TurnRestrictionLegRole.TO); 161 if (toLegs.isEmpty()){ 162 issues.add(new MissingTurnRestrictionLegError(this, TurnRestrictionLegRole.TO)); 163 return; 164 } else if (toLegs.size() > 1){ 165 issues.add(new MultipleTurnRestrictionLegError(this, TurnRestrictionLegRole.TO, toLegs.size())); 166 return; 167 } 168 OsmPrimitive p = toLegs.iterator().next(); 169 if (! (p instanceof Way)) { 170 issues.add(new WrongTurnRestrictionLegTypeError(this, TurnRestrictionLegRole.TO, p)); 171 } 172 } 173 174 /** 175 * Creates an issue if this turn restriction has identical 'from' and to'. 176 * 177 * @param editorModel 178 */ 179 protected void checkFromAndToEquals(TurnRestrictionEditorModel editorModel){ 180 Set<OsmPrimitive> toLegs = editorModel.getTurnRestrictionLeg(TurnRestrictionLegRole.TO); 181 Set<OsmPrimitive> fromLegs = editorModel.getTurnRestrictionLeg(TurnRestrictionLegRole.FROM); 182 if (toLegs.size() != 1 || fromLegs.size() != 1) return; 183 184 OsmPrimitive from = fromLegs.iterator().next(); 185 OsmPrimitive to = toLegs.iterator().next(); 186 187 if (! (from instanceof Way)) return; 188 if (! (to instanceof Way)) return; 189 if (from.equals(to) && ! "no_u_turn".equals(editorModel.getRestrictionTagValue())){ 190 // identical from and to allowed for "no_u_turn" only 191 // 192 issues.add(new IdenticalTurnRestrictionLegsError(this, from)); 193 } 194 } 195 196 protected Node getNodeAtIntersection(Way from, Way to){ 197 Set<Node> fromNodes = new HashSet<Node>(from.getNodes()); 198 fromNodes.retainAll(to.getNodes()); 199 if (fromNodes.size() == 1){ 200 return fromNodes.iterator().next(); 201 } else { 202 return null; 203 } 204 } 205 206 /** 207 * Checks the 'via' members in the turn restriction 208 * 209 * @param editorModel the editor model 210 */ 211 protected void checkVias(TurnRestrictionEditorModel editorModel){ 212 Set<OsmPrimitive> toLegs = editorModel.getTurnRestrictionLeg(TurnRestrictionLegRole.TO); 213 Set<OsmPrimitive> fromLegs = editorModel.getTurnRestrictionLeg(TurnRestrictionLegRole.FROM); 214 // we only check vias if 'to' and 'from' are already OK 215 if (toLegs.size() != 1 || fromLegs.size() != 1) return; 216 if (! (toLegs.iterator().next() instanceof Way)) return; 217 if (! (fromLegs.iterator().next() instanceof Way)) return; 218 219 Way from = (Way)fromLegs.iterator().next(); 220 Way to = (Way)toLegs.iterator().next(); 221 Node intersect = getNodeAtIntersection(from, to); 222 if (intersect != null){ 223 if (!editorModel.getVias().contains(intersect)) { 224 issues.add(new IntersectionMissingAsViaError(this, from, to, intersect)); 225 } 226 } 227 228 // 'from' intersects with 'to' - should be split 229 if (intersect != null && from.getNode(0) != intersect && from.getNode(from.getNodesCount()-1) != intersect){ 230 issues.add(new TurnRestrictionLegSplitRequiredError(this, TurnRestrictionLegRole.FROM, from, to, intersect)); 231 } 232 // 'to' intersects with 'from' - should be split 233 if (intersect != null && to.getNode(0) != intersect && to.getNode(to.getNodesCount()-1) != intersect){ 234 issues.add(new TurnRestrictionLegSplitRequiredError(this, TurnRestrictionLegRole.TO, from, to, intersect)); 235 } 236 } 237 238 public NavigationControler getNavigationControler() { 239 return editorModel.getNavigationControler(); 240 } 241 242 public int getNumWarnings() { 243 int ret = 0; 244 for (Issue issue: issues){ 245 if (issue.getSeverity().equals(Severity.WARNING)) ret++; 246 } 247 return ret; 248 } 249 250 public int getNumErrors() { 251 int ret = 0; 252 for (Issue issue: issues){ 253 if (issue.getSeverity().equals(Severity.ERROR)) ret++; 254 } 255 return ret; 256 } 257 258 /* ------------------------------------------------------------------------------------- */ 259 /* interface Observer */ 260 /* ------------------------------------------------------------------------------------- */ 261 public void update(Observable o, Object arg) { 262 populate(); 263 } 264 264 } -
applications/editors/josm/plugins/turnrestrictions/src/org/openstreetmap/josm/plugins/turnrestrictions/qa/IssuesView.java
r20735 r23192 17 17 */ 18 18 public class IssuesView extends VerticallyScrollablePanel implements Observer{ 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 gc.weighty = 1.0; 61 62 63 64 19 static private final Logger logger = Logger.getLogger(IssuesView.class.getName()); 20 21 /** the issues model */ 22 private IssuesModel model; 23 24 protected void build(){ 25 setLayout(new GridBagLayout()); 26 } 27 28 /** 29 * Creates the view 30 * 31 * @param model the model. Must not be null. 32 * @exception IllegalArgumentException thrown if model is null 33 */ 34 public IssuesView(IssuesModel model) throws IllegalArgumentException{ 35 CheckParameterUtil.ensureParameterNotNull(model, "model"); 36 this.model = model; 37 model.addObserver(this); 38 build(); 39 HelpUtil.setHelpContext(this, HelpUtil.ht("/Plugins/turnrestrictions#ErrorsAndWarnings")); 40 } 41 42 /** 43 * Refreshes the view with the current state in the model 44 */ 45 public void refresh() { 46 removeAll(); 47 if (! model.getIssues().isEmpty()){ 48 GridBagConstraints gc = new GridBagConstraints(); 49 gc.anchor = GridBagConstraints.NORTHWEST; 50 gc.fill = GridBagConstraints.HORIZONTAL; 51 gc.weightx = 1.0; 52 gc.weighty = 0.0; 53 gc.gridx = 0; 54 gc.gridy = 0; 55 for (Issue issue: model.getIssues()){ 56 add(new IssueView(issue), gc); 57 gc.gridy++; 58 } 59 // filler - grabs remaining space 60 gc.weighty = 1.0; 61 add(new JPanel(), gc); 62 } 63 invalidate(); 64 } 65 65 66 67 68 69 70 refresh(); 71 66 /* ------------------------------------------------------------------------------- */ 67 /* interface Observer */ 68 /* ------------------------------------------------------------------------------- */ 69 public void update(Observable o, Object arg) { 70 refresh(); 71 } 72 72 } -
applications/editors/josm/plugins/turnrestrictions/src/org/openstreetmap/josm/plugins/turnrestrictions/qa/MissingRestrictionTypeError.java
r20586 r23192 15 15 */ 16 16 public class MissingRestrictionTypeError extends Issue{ 17 18 19 20 21 17 18 public MissingRestrictionTypeError(IssuesModel parent) { 19 super(parent, Severity.ERROR); 20 actions.add(new FixInEditorAction()); 21 } 22 22 23 24 25 return tr("A turn restriction must declare the type of restriction. Please select a type in the Basic Editor."); 26 27 28 29 30 31 32 33 34 getIssuesModel().getNavigationControler().gotoBasicEditor(NavigationControler.BasicEditorFokusTargets.RESTRICION_TYPE); 35 } 36 23 @Override 24 public String getText() { 25 return tr("A turn restriction must declare the type of restriction. Please select a type in the Basic Editor."); 26 } 27 28 class FixInEditorAction extends AbstractAction { 29 public FixInEditorAction() { 30 putValue(NAME, tr("Fix in editor")); 31 putValue(SHORT_DESCRIPTION, tr("Go to Basic Editor and manually choose a turn restriction type")); 32 } 33 public void actionPerformed(ActionEvent e) { 34 getIssuesModel().getNavigationControler().gotoBasicEditor(NavigationControler.BasicEditorFokusTargets.RESTRICION_TYPE); 35 } 36 } 37 37 } -
applications/editors/josm/plugins/turnrestrictions/src/org/openstreetmap/josm/plugins/turnrestrictions/qa/MissingTurnRestrictionLegError.java
r20633 r23192 15 15 */ 16 16 public class MissingTurnRestrictionLegError extends Issue { 17 17 private TurnRestrictionLegRole role; 18 18 19 20 21 22 23 24 25 26 27 28 29 19 /** 20 * Creates the issue. 21 * 22 * @param parent the parent model 23 * @param role the role of the missing way 24 */ 25 public MissingTurnRestrictionLegError(IssuesModel parent, TurnRestrictionLegRole role) { 26 super(parent, Severity.ERROR); 27 this.role = role; 28 actions.add(new FixAction()); 29 } 30 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 31 @Override 32 public String getText() { 33 String msg = ""; 34 switch(role){ 35 case FROM: 36 msg = tr("An OSM way with role <tt>from</tt> is required in a turn restriction."); 37 break; 38 case TO: 39 msg = tr("An OSM way with role <tt>to</tt> is required in a turn restriction."); 40 break; 41 } 42 msg += " " + tr("Please go to the Basic editor and manually choose an OSM way."); 43 return msg; 44 } 45 45 46 47 48 49 50 51 52 53 54 55 break; 56 } 57 58 59 60 61 62 63 64 65 break; 66 } 67 } 68 46 class FixAction extends AbstractAction { 47 public FixAction() { 48 putValue(NAME, tr("Add in editor")); 49 switch(role){ 50 case FROM: 51 putValue(SHORT_DESCRIPTION, tr("Add an OSM way with role ''from''")); 52 break; 53 case TO: 54 putValue(SHORT_DESCRIPTION, tr("Add an OSM way with role ''to''")); 55 break; 56 } 57 } 58 public void actionPerformed(ActionEvent e) { 59 switch(role){ 60 case FROM: 61 getIssuesModel().getNavigationControler().gotoBasicEditor(FROM); 62 break; 63 case TO: 64 getIssuesModel().getNavigationControler().gotoBasicEditor(TO); 65 break; 66 } 67 } 68 } 69 69 } -
applications/editors/josm/plugins/turnrestrictions/src/org/openstreetmap/josm/plugins/turnrestrictions/qa/MultipleTurnRestrictionLegError.java
r20701 r23192 14 14 */ 15 15 public class MultipleTurnRestrictionLegError extends Issue { 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 16 private TurnRestrictionLegRole role; 17 private int numLegs; 18 19 /** 20 * Create the issue 21 * 22 * @param parent the parent model 23 * @param role the role of the turn restriction leg with multiple entries 24 * @param numLegs the number of legs 25 */ 26 public MultipleTurnRestrictionLegError(IssuesModel parent, TurnRestrictionLegRole role, int numLegs) { 27 super(parent, Severity.ERROR); 28 this.role = role; 29 this.numLegs = numLegs; 30 actions.add(new FixAction()); 31 } 32 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 33 @Override 34 public String getText() { 35 switch(role){ 36 case FROM: 37 return tr("A turn restriction requires exactly one way with role <tt>from</tt>. " 38 + "This turn restriction has {0} ways in this role. Please remove " 39 + "{1} of them.", 40 numLegs, 41 numLegs -1 42 ); 43 case TO: 44 return tr("A turn restriction requires exactly one way with role <tt>to</tt>. " 45 + "This turn restriction has {0} ways in this role. Please remove " 46 + "{1} of them.", 47 numLegs, 48 numLegs -1 49 ); 50 } 51 return ""; 52 } 53 53 54 55 56 57 58 59 60 61 } 62 54 class FixAction extends AbstractAction { 55 public FixAction() { 56 putValue(NAME, tr("Fix in editor")); 57 putValue(SHORT_DESCRIPTION, tr("Go to the Advanced Editor and remove the members")); 58 } 59 public void actionPerformed(ActionEvent e) { 60 getIssuesModel().getNavigationControler().gotoAdvancedEditor(); 61 } 62 } 63 63 } -
applications/editors/josm/plugins/turnrestrictions/src/org/openstreetmap/josm/plugins/turnrestrictions/qa/NonStandardExceptWarning.java
r20586 r23192 14 14 */ 15 15 public class NonStandardExceptWarning extends Issue{ 16 17 18 19 20 21 16 private ExceptValueModel value; 17 public NonStandardExceptWarning(IssuesModel parent, ExceptValueModel value) { 18 super(parent, Severity.WARNING); 19 actions.add(new FixInEditorAction()); 20 this.value = value; 21 } 22 22 23 24 public String getText() { 25 26 27 28 ); 29 30 31 32 33 34 35 36 37 getIssuesModel().getNavigationControler().gotoBasicEditor(); 38 } 39 23 @Override 24 public String getText() { 25 return tr("The tag <tt>except</tt> has the non-standard value <tt>{0}</tt>. " 26 + "It is recommended to use standard values for <tt>except</tt> only.", 27 value.getValue() 28 ); 29 } 30 31 class FixInEditorAction extends AbstractAction { 32 public FixInEditorAction() { 33 putValue(NAME, tr("Fix in editor")); 34 putValue(SHORT_DESCRIPTION, tr("Go to Basic Editor and select standard vehicle type based exceptions")); 35 } 36 public void actionPerformed(ActionEvent e) { 37 getIssuesModel().getNavigationControler().gotoBasicEditor(); 38 } 39 } 40 40 } -
applications/editors/josm/plugins/turnrestrictions/src/org/openstreetmap/josm/plugins/turnrestrictions/qa/RequiredTagMissingError.java
r20586 r23192 15 15 */ 16 16 public class RequiredTagMissingError extends Issue { 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 17 static private final Logger logger = Logger.getLogger(RequiredTagMissingError.class.getName()); 18 private String tagKey; 19 private String tagValue; 20 21 /** 22 * Create the issue 23 * 24 * @param parent the issues model 25 * @param tagKey the tag key 26 * @param tagValue the tag value 27 */ 28 public RequiredTagMissingError(IssuesModel parent, String tagKey, String tagValue) { 29 super(parent, Severity.ERROR); 30 this.tagKey = tagKey; 31 this.tagValue = tagValue; 32 actions.add(new AddTagAction()); 33 } 34 34 35 36 public String getText() { 37 return tr("The required tag <tt>{0}={1}</tt> is missing.", 38 39 40 41 35 @Override 36 public String getText() { 37 return tr("The required tag <tt>{0}={1}</tt> is missing.", 38 this.tagKey, 39 this.tagValue 40 ); 41 } 42 42 43 44 45 46 putValue(SHORT_DESCRIPTION, tr("Add the missing tag {0}={1}", tagKey, tagValue)); 47 48 49 50 51 52 53 54 55 } 56 }57 43 private class AddTagAction extends AbstractAction { 44 public AddTagAction(){ 45 putValue(NAME,tr("Add missing tag")); 46 putValue(SHORT_DESCRIPTION, tr("Add the missing tag {0}={1}", tagKey, tagValue)); 47 } 48 49 public void actionPerformed(ActionEvent e) { 50 TagEditorModel model = getIssuesModel().getEditorModel().getTagEditorModel(); 51 TagModel t = model.get(tagKey); 52 if (t == null){ 53 t = new TagModel(tagKey, tagValue); 54 model.prepend(t); 55 } 56 } 57 } 58 58 } -
applications/editors/josm/plugins/turnrestrictions/src/org/openstreetmap/josm/plugins/turnrestrictions/qa/Severity.java
r20586 r23192 2 2 3 3 public enum Severity { 4 5 4 WARNING, 5 ERROR 6 6 } -
applications/editors/josm/plugins/turnrestrictions/src/org/openstreetmap/josm/plugins/turnrestrictions/qa/TurnRestrictionLegSplitRequiredError.java
r22477 r23192 23 23 */ 24 24 public class TurnRestrictionLegSplitRequiredError extends Issue{ 25 26 27 28 25 private TurnRestrictionLegRole role; 26 private Way from; 27 private Way to; 28 private Node interesect; 29 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 30 /** 31 * Create the issue 32 * 33 * @param parent the parent model 34 * @param role the role of the way which should be splitted 35 * @param from the way with role 'from' 36 * @param to the way with role 'to' 37 * @param interesect the node at the intersection 38 */ 39 public TurnRestrictionLegSplitRequiredError(IssuesModel parent, TurnRestrictionLegRole role, Way from, Way to, Node intersect) { 40 super(parent, Severity.ERROR); 41 this.role = role; 42 this.from = from; 43 this.to = to; 44 this.interesect = intersect; 45 actions.add(new SplitAction()); 46 } 47 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 48 @Override 49 public String getText() { 50 String msg = null; 51 switch(role){ 52 case FROM: 53 msg = tr("The OSM way <span class=\"object-name\">{0}</span> with role <tt>{1}</tt> should be split " 54 + "at node <span class=\"object-name\">{2}</span> where it connects to way <span class=\"object-name\">{3}</span>.", 55 from.getDisplayName(DefaultNameFormatter.getInstance()), 56 role.getOsmRole(), 57 interesect.getDisplayName(DefaultNameFormatter.getInstance()), 58 to.getDisplayName(DefaultNameFormatter.getInstance()) 59 ); 60 break; 61 case TO: 62 msg = tr("The OSM way <span class=\"object-name\">{0}</span> with role <tt>{1}</tt> should be split " 63 + "at node <span class=\"object-name\">{2}</span> where it connects to way <span class=\"object-name\">{3}</span>.", 64 to.getDisplayName(DefaultNameFormatter.getInstance()), 65 role.getOsmRole(), 66 interesect.getDisplayName(DefaultNameFormatter.getInstance()), 67 from.getDisplayName(DefaultNameFormatter.getInstance()) 68 ); 69 break; 70 } 71 return msg; 72 } 73 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 74 class SplitAction extends AbstractAction { 75 public SplitAction() { 76 putValue(NAME, tr("Split now")); 77 putValue(SHORT_DESCRIPTION, tr("Splits the way")); 78 } 79 public void actionPerformed(ActionEvent e) { 80 Way way = null; 81 switch(role){ 82 case FROM: way = from; break; 83 case TO: way = to; break; 84 } 85 SplitWayResult result = SplitWayAction.split( 86 parent.getEditorModel().getLayer(), 87 way, 88 Collections.singletonList(interesect), 89 Collections.<OsmPrimitive>emptyList() 90 ); 91 if (result != null){ 92 Main.main.undoRedo.add(result.getCommand()); 93 } 94 } 95 } 96 96 } -
applications/editors/josm/plugins/turnrestrictions/src/org/openstreetmap/josm/plugins/turnrestrictions/qa/WrongTurnRestrictionLegTypeError.java
r20622 r23192 19 19 */ 20 20 public class WrongTurnRestrictionLegTypeError extends Issue { 21 22 21 private TurnRestrictionLegRole role; 22 private OsmPrimitive leg; 23 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 24 /** 25 * Create the issue 26 * 27 * @param parent the parent model 28 * @param role the role of the turn restriction leg 29 * @param leg the leg 30 */ 31 public WrongTurnRestrictionLegTypeError(IssuesModel parent, TurnRestrictionLegRole role, OsmPrimitive leg) { 32 super(parent, Severity.ERROR); 33 this.role = role; 34 this.leg = leg; 35 actions.add(new DeleteAction()); 36 actions.add(new FixInEditorAction()); 37 } 38 38 39 40 public String getText() { 41 42 43 44 45 46 47 48 49 50 51 52 53 54 ); 55 break; 56 57 58 39 @Override 40 public String getText() { 41 String msg = null; 42 switch(leg.getType()){ 43 case NODE: 44 msg = tr( 45 "This turn restriction uses the OSM node <span class=\"object-name\">{0}</span> as member with role <tt>{1}</tt>.", 46 leg.getDisplayName(DefaultNameFormatter.getInstance()), 47 role.toString() 48 ); 49 break; 50 case RELATION: 51 msg = tr("This turn restriction uses the OSM relation <span class=\"object-name\">{0}</span> as member with role <tt>{1}</tt>.", 52 leg.getDisplayName(DefaultNameFormatter.getInstance()), 53 role.toString() 54 ); 55 break; 56 } 57 return msg + " " + tr("An OSM way is required instead."); 58 } 59 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 } 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 } 94 60 class DeleteAction extends AbstractAction { 61 public DeleteAction() { 62 putValue(NAME, tr("Delete")); 63 putValue(SHORT_DESCRIPTION, tr("Delete the member from the turn restriction")); 64 } 65 public void actionPerformed(ActionEvent e) { 66 RelationMemberEditorModel model = getIssuesModel().getEditorModel().getRelationMemberEditorModel(); 67 switch(role){ 68 case FROM: 69 model.setFromPrimitive(null); 70 break; 71 case TO: 72 model.setToPrimitive(null); 73 break; 74 } 75 } 76 } 77 78 class FixInEditorAction extends AbstractAction { 79 public FixInEditorAction() { 80 putValue(NAME, tr("Fix in editor")); 81 putValue(SHORT_DESCRIPTION, tr("Change to the Basic Editor and select an OSM way")); 82 } 83 public void actionPerformed(ActionEvent e) { 84 NavigationControler controler = getIssuesModel().getNavigationControler(); 85 switch(role){ 86 case FROM: 87 controler.gotoBasicEditor(BasicEditorFokusTargets.FROM); 88 break; 89 case TO: 90 controler.gotoBasicEditor(BasicEditorFokusTargets.TO); 91 break; 92 } 93 } 94 } 95 95 } -
applications/editors/josm/plugins/turnrestrictions/test/org/openstreetmap/josm/plugins/turnrestrictions/editor/BasicEditorPanelTest.java
r20586 r23192 15 15 public class BasicEditorPanelTest extends JFrame { 16 16 17 18 19 20 21 22 23 24 25 26 17 private TurnRestrictionEditorModel model; 18 private DataSet ds; 19 20 public BasicEditorPanelTest() { 21 ds = new DataSet(); 22 OsmDataLayer layer =new OsmDataLayer(ds, "test",null); 23 // mock a controler 24 NavigationControler controler = new NavigationControler() { 25 public void gotoAdvancedEditor() { 26 } 27 27 28 29 28 public void gotoBasicEditor() { 29 } 30 30 31 32 } 33 34 35 36 37 38 39 40 c.add(panel, BorderLayout.CENTER); 41 42 43 44 45 46 47 48 31 public void gotoBasicEditor(BasicEditorFokusTargets focusTarget) { 32 } 33 }; 34 model = new TurnRestrictionEditorModel(layer, controler); 35 36 BasicEditorPanel panel = new BasicEditorPanel(model); 37 38 Container c = getContentPane(); 39 c.setLayout(new BorderLayout()); 40 c.add(panel, BorderLayout.CENTER); 41 setSize(600,600); 42 setDefaultCloseOperation(EXIT_ON_CLOSE); 43 } 44 45 46 static public void main(String args[]) { 47 new BasicEditorPanelTest().setVisible(true); 48 } 49 49 } -
applications/editors/josm/plugins/turnrestrictions/test/org/openstreetmap/josm/plugins/turnrestrictions/editor/TurnRestrictionComboBoxTest.java
r20606 r23192 16 16 */ 17 17 public class TurnRestrictionComboBoxTest extends JFrame { 18 19 20 21 22 23 24 25 26 27 28 18 19 private TurnRestrictionEditorModel model; 20 private DataSet ds = new DataSet(); 21 22 protected void build() { 23 ds = new DataSet(); 24 OsmDataLayer layer =new OsmDataLayer(ds, "test",null); 25 // mock a controler 26 NavigationControler controler = new NavigationControler() { 27 public void gotoAdvancedEditor() { 28 } 29 29 30 31 30 public void gotoBasicEditor() { 31 } 32 32 33 34 } 35 36 37 38 39 40 41 42 43 44 45 46 47 48 add(cb, gc); 49 50 51 52 53 54 55 56 57 58 59 33 public void gotoBasicEditor(BasicEditorFokusTargets focusTarget) { 34 } 35 }; 36 model = new TurnRestrictionEditorModel(layer, controler); 37 38 Container c = getContentPane(); 39 c.setLayout(new GridBagLayout()); 40 GridBagConstraints gc = new GridBagConstraints(); 41 gc.anchor = GridBagConstraints.NORTHWEST; 42 gc.fill = GridBagConstraints.HORIZONTAL; 43 gc.weightx = 1.0; 44 45 TurnRestrictionComboBox cb = new TurnRestrictionComboBox( 46 new TurnRestrictionComboBoxModel(model) 47 ); 48 add(cb, gc); 49 } 50 51 public TurnRestrictionComboBoxTest() { 52 build(); 53 setSize(600,600); 54 setDefaultCloseOperation(EXIT_ON_CLOSE); 55 } 56 57 public static void main(String args[]) { 58 new TurnRestrictionComboBoxTest().setVisible(true); 59 } 60 60 61 61 } -
applications/editors/josm/plugins/turnrestrictions/test/org/openstreetmap/josm/plugins/turnrestrictions/editor/TurnRestrictionEditorTest.java
r20606 r23192 10 10 */ 11 11 public class TurnRestrictionEditorTest extends JFrame { 12 13 14 15 16 17 18 19 20 21 22 23 24 12 13 public TurnRestrictionEditorTest() { 14 setSize(10,10); 15 TurnRestrictionEditor editor = new TurnRestrictionEditor(this, new OsmDataLayer(new DataSet(), "test", null)); 16 editor.setSize(600,600); 17 editor.setVisible(true); 18 19 setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 20 } 21 22 static public void main(String args[]) { 23 new TurnRestrictionEditorTest().setVisible(true); 24 } 25 25 } -
applications/editors/josm/plugins/turnrestrictions/test/org/openstreetmap/josm/plugins/turnrestrictions/editor/TurnRestrictionLegEditorTest.java
r20606 r23192 34 34 */ 35 35 public class TurnRestrictionLegEditorTest extends JFrame { 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 36 37 private JTextArea taTest; 38 private TurnRestrictionLegEditor editor; 39 private TurnRestrictionEditorModel model; 40 private JList lstObjects; 41 private DefaultListModel listModel; 42 private DataSet dataSet; 43 44 45 protected JPanel buildLegEditorPanel() { 46 DataSet ds = new DataSet(); 47 OsmDataLayer layer =new OsmDataLayer(ds, "test",null); 48 // mock a controler 49 NavigationControler controler = new NavigationControler() { 50 public void gotoAdvancedEditor() { 51 } 52 52 53 54 53 public void gotoBasicEditor() { 54 } 55 55 56 57 } 58 59 60 61 62 63 gc.weightx = 0.0; 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 lstObjects.setCellRenderer(new OsmPrimitivRenderer()); 81 82 PrimitiveIdListProvider provider = new PrimitiveIdListProvider() { 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 gc.fill = GridBagConstraints.HORIZONTAL; 105 106 gc.weightx = 1.0; 107 108 109 110 111 112 113 114 115 setSize(600,600); 116 117 118 119 120 121 122 123 124 125 126 127 w.put("name", "way-1"); 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 56 public void gotoBasicEditor(BasicEditorFokusTargets focusTarget) { 57 } 58 }; 59 JPanel pnl = new JPanel(new GridBagLayout()); 60 GridBagConstraints gc = new GridBagConstraints(); 61 gc.anchor = GridBagConstraints.NORTHWEST; 62 gc.fill = GridBagConstraints.HORIZONTAL; 63 gc.weightx = 0.0; 64 pnl.add(new JLabel("From"), gc); 65 66 gc.weightx = 1.0; 67 gc.gridx = 1; 68 model = new TurnRestrictionEditorModel(layer, controler); 69 dataSet = new DataSet(); 70 model.populate(new Relation()); 71 pnl.add(editor = new TurnRestrictionLegEditor(model, TurnRestrictionLegRole.FROM), gc); 72 73 return pnl; 74 } 75 76 protected JPanel buildObjectListPanel() { 77 JPanel pnl = new JPanel(new BorderLayout()); 78 listModel = new DefaultListModel(); 79 pnl.add(new JScrollPane(lstObjects = new JList(listModel)), BorderLayout.CENTER); 80 lstObjects.setCellRenderer(new OsmPrimitivRenderer()); 81 82 PrimitiveIdListProvider provider = new PrimitiveIdListProvider() { 83 public List<PrimitiveId> getSelectedPrimitiveIds() { 84 List<PrimitiveId> ret = new ArrayList<PrimitiveId>(); 85 int [] sel = lstObjects.getSelectedIndices(); 86 for (int i: sel){ 87 ret.add(((OsmPrimitive)lstObjects.getModel().getElementAt(i)).getPrimitiveId()); 88 } 89 return ret; 90 } 91 }; 92 93 lstObjects.setTransferHandler(new PrimitiveIdListTransferHandler(provider)); 94 lstObjects.setDragEnabled(true); 95 return pnl; 96 } 97 98 protected void build() { 99 Container c = getContentPane(); 100 c.setLayout(new GridBagLayout()); 101 102 GridBagConstraints gc = new GridBagConstraints(); 103 gc.anchor = GridBagConstraints.NORTHWEST; 104 gc.fill = GridBagConstraints.HORIZONTAL; 105 gc.insets = new Insets(20, 0, 20, 0); 106 gc.weightx = 1.0; 107 gc.weighty = 0.0; 108 add(buildLegEditorPanel(), gc); 109 110 gc.gridy = 1; 111 gc.weightx = 1.0; 112 gc.weighty = 1.0; 113 gc.fill = GridBagConstraints.BOTH; 114 add(buildObjectListPanel(), gc); 115 setSize(600,600); 116 } 117 118 protected void initForTest1() { 119 Way w = new Way(1); 120 w.put("name", "way-1"); 121 122 editor.getModel().setTurnRestrictionLeg(TurnRestrictionLegRole.FROM, w); 123 } 124 125 protected void initForTest2() { 126 Way w = new Way(1); 127 w.put("name", "way-1"); 128 dataSet.addPrimitive(w); 129 editor.getModel().setTurnRestrictionLeg(TurnRestrictionLegRole.FROM, w); 130 131 Node n = new Node(new LatLon(1,1)); 132 n.setOsmId(1, 1); 133 n.put("name", "node.1"); 134 dataSet.addPrimitive(n); 135 listModel.addElement(n); 136 137 w = new Way(); 138 w.setOsmId(2,1); 139 w.put("name", "way.1"); 140 dataSet.addPrimitive(w); 141 listModel.addElement(w); 142 143 Relation r = new Relation(); 144 r.setOsmId(3,1); 145 r.put("name", "relation.1"); 146 dataSet.addPrimitive(r); 147 listModel.addElement(r); 148 } 149 149 150 151 152 153 154 155 156 157 150 public TurnRestrictionLegEditorTest(){ 151 build(); 152 initForTest2(); 153 } 154 155 static public void main(String args[]) { 156 new TurnRestrictionLegEditorTest().setVisible(true); 157 } 158 158 } -
applications/editors/josm/plugins/turnrestrictions/test/org/openstreetmap/josm/plugins/turnrestrictions/editor/VehicleExceptionEditorTest.java
r20606 r23192 15 15 */ 16 16 public class VehicleExceptionEditorTest extends JFrame { 17 18 19 20 21 22 23 24 17 TurnRestrictionEditorModel model; 18 OsmDataLayer layer; 19 VehicleExceptionEditor editor; 20 21 protected void build() { 22 Container c = getContentPane(); 23 c.setLayout(new BorderLayout()); 24 layer = new OsmDataLayer(new DataSet(), "test", null); 25 25 26 model = new TurnRestrictionEditorModel(layer, new MockNavigationControler()); 27 28 29 30 31 32 33 34 35 36 setSize(500,500); 37 38 39 40 41 42 43 26 model = new TurnRestrictionEditorModel(layer, new MockNavigationControler()); 27 editor = new VehicleExceptionEditor(model); 28 c.add(editor, BorderLayout.CENTER); 29 30 model.getTagEditorModel().add(new TagModel("except", "non-standard-value")); 31 } 32 33 public VehicleExceptionEditorTest(){ 34 build(); 35 setDefaultCloseOperation(EXIT_ON_CLOSE); 36 setSize(500,500); 37 } 38 39 public static void main(String args[]){ 40 new VehicleExceptionEditorTest().setVisible(true); 41 } 42 43 static private class MockNavigationControler implements NavigationControler{ 44 44 45 46 47 48 45 public void gotoAdvancedEditor() { 46 // TODO Auto-generated method stub 47 48 } 49 49 50 51 52 53 50 public void gotoBasicEditor() { 51 // TODO Auto-generated method stub 52 53 } 54 54 55 56 57 58 59 55 public void gotoBasicEditor(BasicEditorFokusTargets focusTarget) { 56 // TODO Auto-generated method stub 57 58 } 59 } 60 60 } -
applications/editors/josm/plugins/turnrestrictions/test/org/openstreetmap/josm/plugins/turnrestrictions/editor/ViaListTest.java
r20606 r23192 22 22 */ 23 23 public class ViaListTest extends JFrame{ 24 25 26 27 28 29 30 31 32 33 34 35 36 24 25 private ViaList lstVias; 26 private TurnRestrictionEditorModel model; 27 private JList lstJOSMSelection; 28 29 30 protected void build() { 31 DataSet ds = new DataSet(); 32 OsmDataLayer layer =new OsmDataLayer(ds, "test",null); 33 // mock a controler 34 NavigationControler controler = new NavigationControler() { 35 public void gotoAdvancedEditor() { 36 } 37 37 38 39 38 public void gotoBasicEditor() { 39 } 40 40 41 42 } 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 setSize(600,600); 62 63 64 65 66 67 68 69 70 n = new Node(new LatLon(i,i)); 71 72 73 74 } 75 76 77 78 79 build(); 80 81 82 83 84 85 41 public void gotoBasicEditor(BasicEditorFokusTargets focusTarget) { 42 } 43 }; 44 model = new TurnRestrictionEditorModel(layer, controler); 45 Container c = getContentPane(); 46 47 c.setLayout(new GridBagLayout()); 48 GridBagConstraints gc = new GridBagConstraints(); 49 gc.anchor = GridBagConstraints.NORTHWEST; 50 gc.insets = new Insets(5,5,5,20); 51 gc.fill = GridBagConstraints.BOTH; 52 gc.weightx = 0.5; 53 gc.weighty = 1.0; 54 55 DefaultListSelectionModel selectionModel = new DefaultListSelectionModel(); 56 c.add(lstVias = new ViaList(new ViaListModel(model, selectionModel), selectionModel), gc); 57 58 gc.gridx = 1; 59 c.add(lstJOSMSelection = new JList(), gc); 60 61 setSize(600,600); 62 setDefaultCloseOperation(EXIT_ON_CLOSE); 63 } 64 65 protected void initTest1() { 66 DataSet ds = new DataSet(); 67 Relation r = new Relation(); 68 Node n; 69 for (int i = 1; i<10; i++){ 70 n = new Node(new LatLon(i,i)); 71 n.put("name", "node." + i); 72 ds.addPrimitive(n); 73 r.addMember(new RelationMember("via",n)); 74 } 75 model.populate(r); 76 } 77 78 public ViaListTest() { 79 build(); 80 initTest1(); 81 } 82 83 static public void main(String args[]) { 84 new ViaListTest().setVisible(true); 85 } 86 86 } -
applications/editors/josm/plugins/turnrestrictions/test/org/openstreetmap/josm/plugins/turnrestrictions/qa/IssuesViewTest.java
r20606 r23192 19 19 */ 20 20 public class IssuesViewTest extends JFrame { 21 22 23 24 25 26 27 28 29 21 private IssuesModel model; 22 23 protected void build() { 24 Container c = getContentPane(); 25 c.setLayout(new GridBagLayout()); 26 // mock a controler 27 NavigationControler controler = new NavigationControler() { 28 public void gotoAdvancedEditor() { 29 } 30 30 31 32 31 public void gotoBasicEditor() { 32 } 33 33 34 35 } 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 34 public void gotoBasicEditor(BasicEditorFokusTargets focusTarget) { 35 } 36 }; 37 OsmDataLayer layer = new OsmDataLayer(new DataSet(), "test", null); 38 TurnRestrictionEditorModel editorModel = new TurnRestrictionEditorModel(layer, controler); 39 model = new IssuesModel(editorModel); 40 GridBagConstraints gc = new GridBagConstraints(); 41 gc.anchor = GridBagConstraints.NORTHWEST; 42 gc.fill = GridBagConstraints.BOTH; 43 gc.weightx = 1.0; 44 gc.weighty = 1.0; 45 JScrollPane pane = new JScrollPane(new IssuesView(model)); 46 pane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); 47 pane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED); 48 c.add(pane, gc); 49 50 List<Issue> issues = new ArrayList<Issue>(); 51 issues.add(new RequiredTagMissingError(model, "type", "restriction")); 52 issues.add(new MissingRestrictionTypeError(model)); 53 model.populate(issues); 54 } 55 56 public IssuesViewTest() { 57 setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 58 setSize(400,600); 59 build(); 60 } 61 62 public static void main(String args[]) { 63 new IssuesViewTest().setVisible(true); 64 } 65 65 } -
applications/editors/josm/plugins/validator/src/org/openstreetmap/josm/plugins/validator/OSMValidatorPlugin.java
r21616 r23192 111 111 */ 112 112 public OSMValidatorPlugin(PluginInformation info) { 113 113 super(info); 114 114 checkPluginDir(); 115 115 initializeGridDetail(); … … 175 175 MapView.addLayerChangeListener(this); 176 176 } else 177 177 MapView.removeLayerChangeListener(this); 178 178 if (newFrame != null) { 179 179 UploadAction.registerUploadHook(uploadHook = new ValidateUploadHook(this)); 180 180 } else { 181 182 181 UploadAction.unregisterUploadHook(uploadHook); 182 uploadHook = null; 183 183 } 184 184 } … … 280 280 e.printStackTrace(); 281 281 JOptionPane.showMessageDialog(Main.parent, 282 282 tr("Error initializing test {0}:\n {1}", test.getClass() 283 283 .getSimpleName(), e), 284 284 tr("Error"), … … 306 306 307 307 public void layerRemoved(Layer oldLayer) { 308 309 310 311 308 if (oldLayer == errorLayer) { 309 errorLayer = null; 310 return; 311 } 312 312 layerErrors.remove(oldLayer); 313 313 if (Main.map.mapView.getLayersOfType(OsmDataLayer.class).isEmpty()) { 314 315 316 314 if (errorLayer != null) { 315 Main.map.mapView.removeLayer(errorLayer); 316 } 317 317 } 318 318 } -
applications/editors/josm/plugins/validator/src/org/openstreetmap/josm/plugins/validator/PreferenceEditor.java
r20828 r23192 22 22 /** 23 23 * Preference settings for the validator plugin 24 * 24 * 25 25 * @author frsantos 26 26 */ … … 52 52 /** 53 53 * The preferences key for enabling the permanent filtering 54 * of the displayed errors in the tree regarding the current selection 54 * of the displayed errors in the tree regarding the current selection 55 55 */ 56 56 public static final String PREF_FILTER_BY_SELECTION = PREFIX + ".selectionFilter"; -
applications/editors/josm/plugins/validator/src/org/openstreetmap/josm/plugins/validator/tests/Coastlines.java
r20828 r23192 47 47 public void startTest(ProgressMonitor monitor) 48 48 { 49 49 super.startTest(monitor); 50 50 51 51 OsmDataLayer layer = Main.map.mapView.getEditLayer(); -
applications/editors/josm/plugins/validator/src/org/openstreetmap/josm/plugins/validator/tests/CrossingWays.java
r20828 r23192 53 53 public void startTest(ProgressMonitor monitor) 54 54 { 55 55 super.startTest(monitor); 56 56 cellSegments = new HashMap<Point2D,List<ExtendedSegment>>(1000); 57 57 errorSegments = new HashSet<WaySegment>(); … … 62 62 public void endTest() 63 63 { 64 64 super.endTest(); 65 65 cellSegments = null; 66 66 errorSegments = null; -
applications/editors/josm/plugins/validator/src/org/openstreetmap/josm/plugins/validator/tests/DuplicateWay.java
r22714 r23192 70 70 public void startTest(ProgressMonitor monitor) 71 71 { 72 72 super.startTest(monitor); 73 73 ways = new Bag<WayPair, OsmPrimitive>(1000); 74 74 } … … 77 77 public void endTest() 78 78 { 79 79 super.endTest(); 80 80 for(List<OsmPrimitive> duplicated : ways.values() ) 81 81 { -
applications/editors/josm/plugins/validator/src/org/openstreetmap/josm/plugins/validator/tests/DuplicatedWayNodes.java
r20828 r23192 50 50 for (Node n : w.getNodes()) { 51 51 if (lastN == null) { 52 52 wnew.addNode(n); 53 53 } else if (n == lastN) { 54 54 // Skip this node 55 55 } else { 56 56 wnew.addNode(n); 57 57 } 58 58 lastN = n; -
applications/editors/josm/plugins/validator/src/org/openstreetmap/josm/plugins/validator/tests/NameMismatch.java
r20828 r23192 74 74 tr("A name is missing, even though name:* exists."), 75 75 NAME_MISSING, p)); 76 77 76 return; 77 } 78 78 79 79 if (names.contains(name)) return; -
applications/editors/josm/plugins/validator/src/org/openstreetmap/josm/plugins/validator/tests/OverlappingWays.java
r20828 r23192 52 52 public void startTest(ProgressMonitor monitor) 53 53 { 54 54 super.startTest(monitor); 55 55 nodePairs = new Bag<Pair<Node,Node>, WaySegment>(1000); 56 56 } -
applications/editors/josm/plugins/validator/src/org/openstreetmap/josm/plugins/validator/tests/SimilarNamedWays.java
r20828 r23192 44 44 public void startTest(ProgressMonitor monitor) 45 45 { 46 46 super.startTest(monitor); 47 47 cellWays = new HashMap<Point2D,List<Way>>(1000); 48 48 errorWays = new Bag<Way, Way>(); -
applications/editors/josm/plugins/validator/src/org/openstreetmap/josm/plugins/validator/tests/WronglyOrderedWays.java
r20828 r23192 40 40 public void startTest(ProgressMonitor monitor) 41 41 { 42 42 super.startTest(monitor); 43 43 _errorWays = new Bag<Way, Way>(); 44 44 } -
applications/editors/josm/plugins/waypoint_search/src/org/openstreetmap/josm/plugins/waypointSearch/SelectWaypointDialog.java
r23190 r23192 63 63 64 64 65 66 67 68 69 70 71 72 73 74 75 76 77 65 public void updateSearchResults(){ 66 String searchfor = ""; 67 listModel.clear(); 68 SearchResultObjectCache.clear(); 69 if (!first_time_search) { 70 searchfor = searchPattern.getText(); 71 } 72 for (Iterator<Marker> i = engine.searchGpxWaypoints(searchfor).iterator(); i.hasNext();) { 73 Marker marker = i.next(); 74 listModel.addElement(marker.getText()); 75 SearchResultObjectCache.add(marker); 76 } 77 } 78 78 79 79 … … 91 91 92 92 93 94 95 96 93 @Override 94 public void keyTyped(KeyEvent arg0) { 95 first_time_search = false; 96 } 97 97 98 98 -
applications/editors/josm/plugins/waypoint_search/src/org/openstreetmap/josm/plugins/waypointSearch/WaypointSearchPlugin.java
r23190 r23192 29 29 } 30 30 31 32 33 34 35 36 37 38 39 40 41 42 31 32 @Override 33 public void layerAdded(Layer newLayer) { 34 //add dialog 35 if (Main.map.getToggleDialog(SelectWaypointDialog.class)==null) { 36 Main.map.addToggleDialog(waypointDialog); 37 } 38 //update search 39 if (engine.gpxLayersExist()) { 40 waypointDialog.updateSearchResults(); 41 } 42 } 43 43 44 44
Note:
See TracChangeset
for help on using the changeset viewer.