Changeset 12778 in osm for applications
- Timestamp:
- 2009-01-01T18:28:53+01:00 (16 years ago)
- Location:
- applications/editors/josm/plugins
- Files:
-
- 199 edited
Legend:
- Unmodified
- Added
- Removed
-
applications/editors/josm/plugins/DirectUpload/src/org/openstreetmap/josm/plugins/DirectUpload/UploadDataGui.java
r12707 r12778 40 40 */ 41 41 public class UploadDataGui extends javax.swing.JFrame { 42 43 String tagging; 44 String Descriptionfield; 42 43 String tagging; 44 String Descriptionfield; 45 45 String urlDescription; 46 46 String urlTags; … … 48 48 String PassWord; 49 49 //GpxData gpxData; 50 50 51 51 public static final String API_VERSION = "0.5"; 52 52 private static final String BASE64_ENC = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; 53 53 private static final String BOUNDARY = "----------------------------d10f7aa230e8"; 54 54 private static final String LINE_END = "\r\n"; 55 55 56 56 boolean dfield; 57 57 boolean taggy; … … 60 60 boolean pass; 61 61 boolean publicheck; 62 62 63 63 DateFormat dateFormat = new SimpleDateFormat("yyMMddHHmmss"); 64 Date date = new Date(); 64 Date date = new Date(); 65 65 String datename = dateFormat.format(date); 66 66 67 67 /** Creates new form UploadDataGui */ 68 68 public UploadDataGui() { … … 70 70 } 71 71 72 72 73 73 /** This method is called from within the constructor to 74 74 * initialize the form. … … 142 142 143 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 144 145 Container contentPane = getContentPane(); 146 contentPane.setLayout(new GridBagLayout()); 147 GridBagConstraints c = new GridBagConstraints(); 148 149 c.gridx = 0; 150 c.gridy = 0; 151 c.gridwidth = 2; 152 c.fill = 1; 153 contentPane.add(OutputDisplay, c); 154 155 c.gridwidth = 1; 156 c.gridy = 1; 157 contentPane.add(jLabel3, c); 158 c.gridx = 1; 159 contentPane.add(tagfield, c); 160 161 c.gridy = 2; c.gridx = 0; 162 contentPane.add(jLabel1, c); 163 c.gridx = 1; 164 contentPane.add(descriptionfield, c); 165 166 c.gridy = 3; c.gridx = 0; 167 contentPane.add(jLabel2, c); 168 c.gridx = 1; 169 contentPane.add(PublicTrace, c); 170 171 c.gridy = 4; c.gridx = 0; 172 contentPane.add(CancelButton, c); 173 c.gridx = 1; 174 contentPane.add(OkButton, c); 175 175 176 176 pack(); … … 181 181 public void upload(String username, String password, String Descriptionfield, String tagging , GpxData gpxData ) throws IOException { 182 182 OutputDisplay.setText("Starting to upload selected file to openstreetmap.org"); 183 183 184 184 try { 185 185 186 186 urlDescription = Descriptionfield.replaceAll("\\.;&?,/","_"); 187 187 if (urlDescription == null || urlDescription.length() == 0) { 188 188 OutputDisplay.setText("No description provided .Please provide some description . For the time being ignore the exception error "); 189 189 190 190 } 191 191 urlTags = tagging.replaceAll("\\\\.;&?,/","_"); 192 193 192 193 194 194 URL url = new URL("http://www.openstreetmap.org/api/" + API_VERSION + "/gpx/create"); 195 195 System.err.println("url: " + url); … … 212 212 writeContentDisposition(out, "public", "1"); 213 213 } else { 214 writeContentDisposition(out, "public", "0"); 214 writeContentDisposition(out, "public", "0"); 215 215 } 216 216 out.writeBytes("--" + BOUNDARY + "--" + LINE_END); 217 217 out.flush(); 218 218 219 219 int returnCode = connect.getResponseCode(); 220 220 String returnMsg = connect.getResponseMessage(); 221 221 System.err.println(returnCode); 222 222 OutputDisplay.setText(returnMsg); 223 if (returnCode != 200) { 223 if (returnCode != 200) { 224 224 if (connect.getHeaderField("Error") != null) 225 225 returnMsg += "\n" + connect.getHeaderField("Error"); … … 228 228 out.close(); 229 229 connect.disconnect(); 230 231 } catch(UnsupportedEncodingException ignore) { 230 231 } catch(UnsupportedEncodingException ignore) { 232 232 } catch (MalformedURLException e) { 233 233 OutputDisplay.setText("Cant Upload ."); 234 234 e.printStackTrace(); 235 235 } 236 236 237 237 } 238 238 … … 246 246 247 247 private void OkButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_OkButtonActionPerformed 248 GpxData gpxData; 249 250 UserName = Main.pref.get("osm-server.username"); 248 GpxData gpxData; 249 250 UserName = Main.pref.get("osm-server.username"); 251 251 PassWord = Main.pref.get("osm-server.password"); 252 252 253 253 if(Main.map == null || Main.map.mapView == null ||Main.map.mapView.getActiveLayer() == null || 254 254 !(Main.map.mapView.getActiveLayer() instanceof GpxLayer)){ … … 260 260 gpxData = ((GpxLayer)Main.map.mapView.getActiveLayer()).data; 261 261 System.out.println(Descriptionfield); 262 try { 262 try { 263 263 upload(UserName,PassWord,Descriptionfield ,tagging ,gpxData) ; 264 264 } catch (IOException ex) { 265 265 Logger.getLogger(UploadDataGui.class.getName()).log(Level.SEVERE, null, ex); 266 } 267 266 } 267 268 268 }//GEN-LAST:event_OkButtonActionPerformed 269 269 … … 276 276 if (evt.getStateChange() == ItemEvent.SELECTED) { 277 277 publicheck = true; 278 278 279 279 } 280 280 }//GEN-LAST:event_PublicTraceItemStateChanged … … 284 284 JTextField Descsel = (JTextField)evt.getSource(); 285 285 Descriptionfield = Descsel.getText(); 286 286 287 287 }//GEN-LAST:event_descriptionfieldFocusLost 288 288 … … 291 291 JTextField Tagsel = (JTextField)evt.getSource(); 292 292 tagging = Tagsel.getText(); 293 293 294 294 }//GEN-LAST:event_tagfieldFocusLost 295 295 … … 300 300 out.writeBytes(LINE_END); 301 301 out.writeBytes(value + LINE_END); 302 302 303 303 } 304 304 305 305 private void writeContentDispositionGpxData(DataOutputStream out, String name, GpxData gpxData ) throws IOException { 306 306 307 307 out.writeBytes("--" + BOUNDARY + LINE_END); 308 308 out.writeBytes("Content-Disposition: form-data; name=\"" + name + "\"; filename=\"" + datename +".gpx" + "\"" + LINE_END); … … 310 310 out.writeBytes("Content-Type: application/octet-stream" + LINE_END); 311 311 out.writeBytes(LINE_END); 312 312 313 313 OutputDisplay.setText("Transferring data to server"); 314 314 new GpxWriter(out).write(gpxData); 315 315 out.flush(); 316 out.writeBytes(LINE_END); 317 318 } 319 320 // Taken from Christof Dallermassal java class : 316 out.writeBytes(LINE_END); 317 318 } 319 320 // Taken from Christof Dallermassal java class : 321 321 public String encodeBase64(String s) { 322 322 StringBuilder out = new StringBuilder(); … … 328 328 out.append(l>1 ? BASE64_ENC.charAt((buf.charAt(1) & 0x0f) << 2 | (l==2 ? 0 : (buf.charAt(2) & 0xc0) >> 6)) : '='); 329 329 out.append(l>2 ? BASE64_ENC.charAt(buf.charAt(2) & 0x3f) : '='); 330 330 331 331 } 332 332 return out.toString(); 333 } 333 } 334 334 335 335 // Variables declaration - do not modify//GEN-BEGIN:variables -
applications/editors/josm/plugins/DirectUpload/src/org/openstreetmap/josm/plugins/DirectUpload/UploadDataGuiPlugin.java
r12588 r12778 2 2 * Copyright by Subhodip Biswas 3 3 * This program is free software and licensed under GPL. 4 * 4 * 5 5 */ 6 6 -
applications/editors/josm/plugins/agpifoj/src/org/openstreetmap/josm/plugins/agpifoj/AgpifojDialog.java
r12746 r12778 1 1 // License: GPL. Copyright 2007 by Christian Gallioz (aka khris78) 2 // Parts of code from Geotagged plugin (by Rob Neild) 2 // Parts of code from Geotagged plugin (by Rob Neild) 3 3 // and the core JOSM source code (by Immanuel Scholz and others) 4 4 … … 34 34 private ImageDisplay imgDisplay = new ImageDisplay(); 35 35 private boolean centerView = false; 36 36 37 37 // Only one instance of that class 38 38 static private AgpifojDialog INSTANCE = null; 39 39 40 40 public static AgpifojDialog getInstance() { 41 41 if (INSTANCE == null) { … … 51 51 throw new IllegalStateException("Agpifoj dialog should not be instanciated twice !"); 52 52 } 53 53 54 54 INSTANCE = this; 55 55 56 56 JPanel content = new JPanel(); 57 57 content.setLayout(new BorderLayout()); 58 58 59 59 content.add(imgDisplay, BorderLayout.CENTER); 60 60 61 61 JPanel buttons = new JPanel(); 62 62 buttons.setLayout(new FlowLayout()); 63 63 64 64 JButton button; 65 65 66 66 Dimension buttonDim = new Dimension(26,26); 67 67 button = new JButton(); … … 72 72 button.setPreferredSize(buttonDim); 73 73 buttons.add(button); 74 74 75 75 button = new JButton(); 76 76 button.setIcon(ImageProvider.get("dialogs", "delete")); … … 80 80 button.setPreferredSize(buttonDim); 81 81 buttons.add(button); 82 82 83 83 button = new JButton(); 84 84 button.setIcon(ImageProvider.get("dialogs", "next")); … … 88 88 button.setPreferredSize(buttonDim); 89 89 buttons.add(button); 90 90 91 91 JToggleButton tb = new JToggleButton(); 92 92 tb.setIcon(ImageProvider.get("dialogs", "centreview")); … … 96 96 tb.setPreferredSize(buttonDim); 97 97 buttons.add(tb); 98 98 99 99 button = new JButton(); 100 100 button.setIcon(ImageProvider.get("dialogs", "zoom-best-fit")); … … 104 104 button.setPreferredSize(buttonDim); 105 105 buttons.add(button); 106 106 107 107 content.add(buttons, BorderLayout.SOUTH); 108 108 109 109 add(content, BorderLayout.CENTER); 110 110 111 111 } 112 112 … … 120 120 currentLayer.showPreviousPhoto(); 121 121 } 122 122 123 123 } else if (COMMAND_CENTERVIEW.equals(e.getActionCommand())) { 124 124 centerView = ((JToggleButton) e.getSource()).isSelected(); … … 126 126 Main.map.mapView.zoomTo(currentEntry.pos, Main.map.mapView.getScale()); 127 127 } 128 128 129 129 } else if (COMMAND_ZOOM.equals(e.getActionCommand())) { 130 130 imgDisplay.zoomBestFitOrOne(); 131 131 132 132 } else if (COMMAND_REMOVE.equals(e.getActionCommand())) { 133 133 if (currentLayer != null) { … … 135 135 } 136 136 } 137 137 138 138 } 139 139 … … 144 144 private AgpifojLayer currentLayer = null; 145 145 private ImageEntry currentEntry = null; 146 146 147 147 public void displayImage(AgpifojLayer layer, ImageEntry entry) { 148 148 synchronized(this) { … … 151 151 return; 152 152 } 153 153 154 154 if (centerView && Main.map != null && entry != null && entry.pos != null) { 155 155 Main.map.mapView.zoomTo(entry.pos, Main.map.mapView.getScale()); … … 159 159 currentEntry = entry; 160 160 } 161 161 162 162 if (entry != null) { 163 163 imgDisplay.setImage(entry.file); -
applications/editors/josm/plugins/agpifoj/src/org/openstreetmap/josm/plugins/agpifoj/AgpifojLayer.java
r12747 r12778 1 1 // License: GPL. Copyright 2007 by Christian Gallioz (aka khris78) 2 // Parts of code from Geotagged plugin (by Rob Neild) 2 // Parts of code from Geotagged plugin (by Rob Neild) 3 3 // and the core JOSM source code (by Immanuel Scholz and others) 4 4 … … 48 48 49 49 List<ImageEntry> data; 50 50 51 51 private Icon icon = ImageProvider.get("dialogs/agpifoj-marker"); 52 52 private Icon selectedIcon = ImageProvider.get("dialogs/agpifoj-marker-selected"); 53 53 54 54 private int currentPhoto = -1; 55 55 56 56 /* 57 57 * Stores info about each image … … 83 83 84 84 /** Loads a set of images, while displaying a dialog that indicates what the plugin is currently doing. 85 * In facts, this object is instantiated with a list of files. These files may be JPEG files or 86 * directories. In case of directories, they are scanned to find all the images they contain. 87 * Then all the images that have be found are loaded as ImageEntry instances. 85 * In facts, this object is instantiated with a list of files. These files may be JPEG files or 86 * directories. In case of directories, they are scanned to find all the images they contain. 87 * Then all the images that have be found are loaded as ImageEntry instances. 88 88 */ 89 89 private static final class Loader extends PleaseWaitRunnable { … … 93 93 private final File[] selection; 94 94 private HashSet<String> loadedDirectories = new HashSet<String>(); 95 95 96 96 public Loader(File[] selection) { 97 97 super(tr("Extracting GPS locations from EXIF")); … … 108 108 errorMessage += tr("One of the selected files was null !!!"); 109 109 } 110 110 111 111 if (cancelled) { 112 112 return; 113 113 } 114 114 115 115 Main.pleaseWaitDlg.currentAction.setText(tr("Read photos...")); 116 116 … … 121 121 Main.pleaseWaitDlg.progress.setMaximum(files.size()); 122 122 Main.pleaseWaitDlg.progress.setValue(progress); 123 123 124 124 for (File f : files) { 125 125 … … 149 149 } 150 150 151 private void addRecursiveFiles(List<File> files, File[] sel) { 151 private void addRecursiveFiles(List<File> files, File[] sel) { 152 152 boolean nullFile = false; 153 153 154 154 for (File f : sel) { 155 155 156 156 if(cancelled) { 157 157 break; 158 158 } 159 159 160 160 if (f == null) { 161 161 nullFile = true; 162 162 163 163 } else if (f.isDirectory()) { 164 164 String canonical = null; … … 167 167 } catch (IOException e) { 168 168 e.printStackTrace(); 169 errorMessage += tr("Unable to get canonical path for directory {0}\n", 169 errorMessage += tr("Unable to get canonical path for directory {0}\n", 170 170 f.getAbsolutePath()); 171 171 } 172 172 173 173 if (canonical == null || loadedDirectories.contains(canonical)) { 174 174 continue; … … 176 176 loadedDirectories.add(canonical); 177 177 } 178 178 179 179 File[] children = f.listFiles(AgpifojPlugin.JPEG_FILE_FILTER); 180 180 if (children != null) { … … 189 189 errorMessage += tr("Error while getting files from directory {0}\n", f.getPath()); 190 190 } 191 191 192 192 } else { 193 193 files.add(f); 194 194 } 195 195 } 196 196 197 197 if (nullFile) { 198 198 throw new NullPointerException(); … … 251 251 @Override 252 252 public Component[] getMenuEntries() { 253 253 254 254 JMenuItem correlateItem = new JMenuItem(tr("Correlate to GPX"), ImageProvider.get("dialogs/gpx2img")); 255 255 correlateItem.addActionListener(new CorrelateGpxWithImages(this)); … … 283 283 AgpifojLayer l = (AgpifojLayer) from; 284 284 285 ImageEntry selected = null; 285 ImageEntry selected = null; 286 286 if (l.currentPhoto >= 0) { 287 287 selected = l.data.get(l.currentPhoto); 288 288 } 289 289 290 290 data.addAll(l.data); 291 291 Collections.sort(data); 292 292 293 293 // Supress the double photos. 294 294 if (data.size() > 1) { … … 304 304 } 305 305 } 306 306 307 307 if (selected != null) { 308 308 for (int i = 0; i < data.size() ; i++) { … … 314 314 } 315 315 } 316 316 317 317 name = l.name; 318 318 319 319 } 320 320 … … 324 324 int iconWidth = icon.getIconWidth() / 2; 325 325 int iconHeight = icon.getIconHeight() / 2; 326 326 327 327 for (ImageEntry e : data) { 328 328 if (e.pos != null) { … … 331 331 Rectangle r = new Rectangle(p.x - iconWidth, 332 332 p.y - iconHeight, 333 icon.getIconWidth(), 333 icon.getIconWidth(), 334 334 icon.getIconHeight()); 335 335 icon.paintIcon(mv, g, r.x, r.y); 336 336 } 337 337 } 338 338 339 339 // Draw the selection on top of the other pictures. 340 340 if (currentPhoto >= 0 && currentPhoto < data.size()) { … … 346 346 Rectangle r = new Rectangle(p.x - selectedIcon.getIconWidth() / 2, 347 347 p.y - selectedIcon.getIconHeight() / 2, 348 selectedIcon.getIconWidth(), 348 selectedIcon.getIconWidth(), 349 349 selectedIcon.getIconHeight()); 350 350 selectedIcon.paintIcon(mv, g, r.x, r.y); … … 361 361 /* 362 362 * Extract gps from image exif 363 * 363 * 364 364 * If successful, fills in the LatLon and EastNorth attributes of passed in 365 365 * image; … … 414 414 } 415 415 } 416 416 417 417 public void showNextPhoto() { 418 418 if (data != null && data.size() > 0) { … … 427 427 Main.main.map.repaint(); 428 428 } 429 429 430 430 public void showPreviousPhoto() { 431 431 if (data != null && data.size() > 0) { … … 440 440 Main.main.map.repaint(); 441 441 } 442 442 443 443 public void removeCurrentPhoto() { 444 444 if (data != null && data.size() > 0 && currentPhoto >= 0 && currentPhoto < data.size()) { … … 455 455 Main.main.map.repaint(); 456 456 } 457 457 458 458 private MouseAdapter mouseAdapter = null; 459 459 … … 481 481 continue; 482 482 Point p = Main.map.mapView.getPoint(e.pos); 483 Rectangle r = new Rectangle(p.x - icon.getIconWidth() / 2, 484 p.y - icon.getIconHeight() / 2, 485 icon.getIconWidth(), 483 Rectangle r = new Rectangle(p.x - icon.getIconWidth() / 2, 484 p.y - icon.getIconHeight() / 2, 485 icon.getIconWidth(), 486 486 icon.getIconHeight()); 487 487 if (r.contains(ev.getPoint())) { -
applications/editors/josm/plugins/agpifoj/src/org/openstreetmap/josm/plugins/agpifoj/AgpifojPlugin.java
r12747 r12778 1 1 // License: GPL. Copyright 2007 by Christian Gallioz (aka khris78) 2 // Parts of code from Geotagged plugin (by Rob Neild) 2 // Parts of code from Geotagged plugin (by Rob Neild) 3 3 // and the core JOSM source code (by Immanuel Scholz and others) 4 4 … … 23 23 24 24 public class AgpifojPlugin extends Plugin { 25 26 static class JpegFileFilter extends javax.swing.filechooser.FileFilter 25 26 static class JpegFileFilter extends javax.swing.filechooser.FileFilter 27 27 implements java.io.FileFilter { 28 28 29 29 @Override public boolean accept(File f) { 30 30 if (f.isDirectory()) { … … 40 40 } 41 41 }; 42 42 43 43 static final JpegFileFilter JPEG_FILE_FILTER = new JpegFileFilter(); 44 44 45 45 private class Action extends JosmAction { 46 46 … … 59 59 fc.setAcceptAllFileFilterUsed(false); 60 60 fc.setFileFilter(JPEG_FILE_FILTER); 61 61 62 62 fc.showOpenDialog(Main.parent); 63 63 64 64 File[] sel = fc.getSelectedFiles(); 65 65 if (sel == null || sel.length == 0) { 66 66 return; 67 67 } 68 68 69 69 Main.pref.put("tagimages.lastdirectory", fc.getCurrentDirectory().getPath()); 70 70 71 71 AgpifojLayer.create(sel); 72 72 } 73 73 } 74 74 75 75 public AgpifojPlugin() { 76 76 MainMenu.add(Main.main.menu.fileMenu, new Action()); -
applications/editors/josm/plugins/agpifoj/src/org/openstreetmap/josm/plugins/agpifoj/CorrelateGpxWithImages.java
r12747 r12778 1 1 // License: GPL. Copyright 2007 by Christian Gallioz (aka khris78) 2 // Parts of code from Geotagged plugin (by Rob Neild) 2 // Parts of code from Geotagged plugin (by Rob Neild) 3 3 // and the core JOSM source code (by Immanuel Scholz and others) 4 4 … … 64 64 import org.xml.sax.SAXException; 65 65 66 /** This class displays the window to select the GPX file and the offset (timezone + delta). 66 /** This class displays the window to select the GPX file and the offset (timezone + delta). 67 67 * Then it correlates the images of the layer with that GPX file. 68 68 */ … … 76 76 long offset; 77 77 } 78 78 79 79 AgpifojLayer yLayer = null; 80 80 81 81 private static class GpxDataWrapper { 82 82 String name; 83 83 GpxData data; 84 84 File file; 85 85 86 86 public GpxDataWrapper(String name, GpxData data, File file) { 87 87 this.name = name; 88 this.data = data; 88 this.data = data; 89 89 this.file = file; 90 90 } 91 91 92 92 public String toString() { 93 93 return name; 94 94 } 95 95 } 96 96 97 97 Vector gpxLst = new Vector(); 98 98 JPanel panel = null; … … 103 103 JRadioButton rbUntaggedImg = null; 104 104 JRadioButton rbNoExifImg = null; 105 106 /** This class is called when the user doesn't find the GPX file he needs in the files that have 105 106 /** This class is called when the user doesn't find the GPX file he needs in the files that have 107 107 * been loaded yet. It displays a FileChooser dialog to select the GPX file to be loaded. 108 */ 108 */ 109 109 private class LoadGpxDataActionListener implements ActionListener { 110 110 111 111 public void actionPerformed(ActionEvent arg0) { 112 112 JFileChooser fc = new JFileChooser(Main.pref.get("lastDirectory")); … … 118 118 @Override public boolean accept(File f) { 119 119 return (f.isDirectory() 120 || f .getName().toLowerCase().endsWith(".gpx") 120 || f .getName().toLowerCase().endsWith(".gpx") 121 121 || f.getName().toLowerCase().endsWith(".gpx.gz")); 122 122 } … … 129 129 if (sel == null) 130 130 return; 131 131 132 132 try { 133 133 panel.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); 134 134 135 135 Main.pref.put("lastDirectory", sel.getPath()); 136 136 137 137 for (int i = gpxLst.size() - 1 ; i >= 0 ; i--) { 138 138 if (gpxLst.get(i) instanceof GpxDataWrapper) { 139 GpxDataWrapper wrapper = (GpxDataWrapper) gpxLst.get(i); 139 GpxDataWrapper wrapper = (GpxDataWrapper) gpxLst.get(i); 140 140 if (sel.equals(wrapper.file)) { 141 141 cbGpx.setSelectedIndex(i); 142 142 if (!sel.getName().equals(wrapper.name)) { 143 JOptionPane.showMessageDialog(Main.parent, 143 JOptionPane.showMessageDialog(Main.parent, 144 144 tr("File {0} is loaded yet under the name \"{1}\"", sel.getName(), wrapper.name)); 145 145 } … … 154 154 iStream = new GZIPInputStream(new FileInputStream(sel)); 155 155 } else { 156 iStream = new FileInputStream(sel); 156 iStream = new FileInputStream(sel); 157 157 } 158 158 data = new GpxReader(iStream, sel).data; 159 159 data.storageFile = sel; 160 160 161 161 } catch (SAXException x) { 162 162 x.printStackTrace(); … … 168 168 return; 169 169 } 170 170 171 171 loadedGpxData.add(data); 172 172 if (gpxLst.get(0) instanceof String) { … … 180 180 } 181 181 } 182 183 /** This action listener is called when the user has a photo of the time of his GPS receiver. It 182 183 /** This action listener is called when the user has a photo of the time of his GPS receiver. It 184 184 * displays the list of photos of the layer, and upon selection displays the selected photo. 185 * From that photo, the user can key in the time of the GPS. 186 * Then values of timezone and delta are set. 185 * From that photo, the user can key in the time of the GPS. 186 * Then values of timezone and delta are set. 187 187 * @author chris 188 188 * … … 195 195 ImageDisplay imgDisp; 196 196 JList imgList; 197 197 198 198 public void actionPerformed(ActionEvent arg0) { 199 199 SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss"); … … 203 203 panel.add(new JLabel(tr("<html>Take a photo of your GPS receiver while it displays the time.<br>" 204 204 + "Display that photo here.<br>" 205 + "And then, simply capture the time you read on the photo and select a timezone<hr></html>")), 205 + "And then, simply capture the time you read on the photo and select a timezone<hr></html>")), 206 206 BorderLayout.NORTH); 207 207 208 208 imgDisp = new ImageDisplay(); 209 209 imgDisp.setPreferredSize(new Dimension(300, 225)); 210 210 panel.add(imgDisp, BorderLayout.CENTER); 211 211 212 212 JPanel panelTf = new JPanel(); 213 213 panelTf.setLayout(new GridBagLayout()); 214 214 215 215 GridBagConstraints gc = new GridBagConstraints(); 216 216 gc.gridx = gc.gridy = 0; … … 227 227 gc.gridwidth = 2; 228 228 panelTf.add(lbExifTime, gc); 229 229 230 230 gc.gridx = 0; 231 231 gc.gridy = 1; … … 247 247 gc.weightx = 0.2; 248 248 panelTf.add(new JLabel(tr(" [dd/mm/yyyy hh:mm:ss]")), gc); 249 249 250 250 gc.gridx = 0; 251 251 gc.gridy = 2; … … 255 255 gc.anchor = GridBagConstraints.WEST; 256 256 panelTf.add(new JLabel(tr("I'm in the timezone of: ")), gc); 257 257 258 258 Vector vtTimezones = new Vector<String>(); 259 259 String[] tmp = TimeZone.getAvailableIDs(); 260 260 261 261 for (String tzStr : tmp) { 262 262 TimeZone tz = TimeZone.getTimeZone(tzStr); 263 263 264 264 String tzDesc = new StringBuffer(tzStr).append(" (") 265 265 .append(formatTimezone(tz.getRawOffset() / 3600000.0)) … … 267 267 vtTimezones.add(tzDesc); 268 268 } 269 269 270 270 Collections.sort(vtTimezones); 271 271 272 272 cbTimezones = new JComboBox(vtTimezones); 273 273 274 274 String tzId = Main.pref.get("tagimages.timezoneid", ""); 275 275 TimeZone defaultTz; … … 279 279 defaultTz = TimeZone.getTimeZone(tzId); 280 280 } 281 281 282 282 cbTimezones.setSelectedItem(new StringBuffer(defaultTz.getID()).append(" (") 283 283 .append(formatTimezone(defaultTz.getRawOffset() / 3600000.0)) 284 284 .append(')').toString()); 285 285 286 286 gc.gridx = 1; 287 287 gc.weightx = 1.0; … … 289 289 gc.fill = GridBagConstraints.HORIZONTAL; 290 290 panelTf.add(cbTimezones, gc); 291 291 292 292 panel.add(panelTf, BorderLayout.SOUTH); 293 293 294 294 JPanel panelLst = new JPanel(); 295 295 panelLst.setLayout(new BorderLayout()); 296 296 297 297 imgList = new JList(new AbstractListModel() { 298 298 public Object getElementAt(int i) { … … 312 312 Date date = yLayer.data.get(index).time; 313 313 if (date != null) { 314 lbExifTime.setText(new SimpleDateFormat("dd/MM/yyyy HH:mm:ss").format(date)); 314 lbExifTime.setText(new SimpleDateFormat("dd/MM/yyyy HH:mm:ss").format(date)); 315 315 tfGpsTime.setText(new SimpleDateFormat("dd/MM/yyyy ").format(date)); 316 316 tfGpsTime.setCaretPosition(tfGpsTime.getText().length()); 317 317 tfGpsTime.setEnabled(true); 318 } else { 318 } else { 319 319 lbExifTime.setText(tr("No date")); 320 320 tfGpsTime.setText(""); … … 322 322 } 323 323 } 324 324 325 325 }); 326 326 panelLst.add(new JScrollPane(imgList), BorderLayout.CENTER); 327 327 328 328 JButton openButton = new JButton(tr("Open an other photo")); 329 329 openButton.addActionListener(new ActionListener() { … … 349 349 } 350 350 if (date != null) { 351 lbExifTime.setText(new SimpleDateFormat("dd/MM/yyyy HH:mm:ss").format(date)); 351 lbExifTime.setText(new SimpleDateFormat("dd/MM/yyyy HH:mm:ss").format(date)); 352 352 tfGpsTime.setText(new SimpleDateFormat("dd/MM/yyyy ").format(date)); 353 353 tfGpsTime.setEnabled(true); 354 } else { 354 } else { 355 355 lbExifTime.setText(tr("No date")); 356 356 tfGpsTime.setText(""); … … 360 360 }); 361 361 panelLst.add(openButton, BorderLayout.PAGE_END); 362 362 363 363 panel.add(panelLst, BorderLayout.LINE_START); 364 364 365 365 boolean isOk = false; 366 366 while (! isOk) { … … 370 370 } 371 371 372 long delta; 373 372 long delta; 373 374 374 try { 375 delta = dateFormat.parse(lbExifTime.getText()).getTime() 375 delta = dateFormat.parse(lbExifTime.getText()).getTime() 376 376 - dateFormat.parse(tfGpsTime.getText()).getTime(); 377 377 } catch(ParseException e) { 378 JOptionPane.showMessageDialog(Main.parent, tr("Error while parsing the date.\n" 379 + "Please use the requested format"), 378 JOptionPane.showMessageDialog(Main.parent, tr("Error while parsing the date.\n" 379 + "Please use the requested format"), 380 380 tr("Invalid date"), JOptionPane.ERROR_MESSAGE ); 381 381 continue; 382 382 } 383 383 384 384 String selectedTz = (String) cbTimezones.getSelectedItem(); 385 385 int pos = selectedTz.lastIndexOf('('); 386 386 tzId = selectedTz.substring(0, pos - 1); 387 String tzValue = selectedTz.substring(pos + 1, selectedTz.length() - 1); 388 387 String tzValue = selectedTz.substring(pos + 1, selectedTz.length() - 1); 388 389 389 Main.pref.put("tagimages.timezoneid", tzId); 390 390 tfOffset.setText(Long.toString(delta / 1000)); 391 391 tfTimezone.setText(tzValue); 392 392 393 393 isOk = true; 394 395 } 396 397 } 398 } 399 394 395 } 396 397 } 398 } 399 400 400 public CorrelateGpxWithImages(AgpifojLayer layer) { 401 401 this.yLayer = layer; … … 409 409 Layer cur = iterLayer.next(); 410 410 if (cur instanceof GpxLayer) { 411 gpxLst.add(new GpxDataWrapper(((GpxLayer) cur).name, 412 ((GpxLayer) cur).data, 413 ((GpxLayer) cur).data.storageFile)); 411 gpxLst.add(new GpxDataWrapper(((GpxLayer) cur).name, 412 ((GpxLayer) cur).data, 413 ((GpxLayer) cur).data.storageFile)); 414 414 } 415 415 } 416 416 for (GpxData data : loadedGpxData) { 417 gpxLst.add(new GpxDataWrapper(data.storageFile.getName(), 417 gpxLst.add(new GpxDataWrapper(data.storageFile.getName(), 418 418 data, 419 data.storageFile)); 420 } 421 419 data.storageFile)); 420 } 421 422 422 if (gpxLst.size() == 0) { 423 423 gpxLst.add(tr("<No GPX track loaded yet>")); 424 424 } 425 425 426 426 JPanel panelCb = new JPanel(); 427 427 panelCb.setLayout(new FlowLayout()); 428 428 429 429 panelCb.add(new JLabel(tr("GPX track: "))); 430 430 431 431 cbGpx = new JComboBox(gpxLst); 432 432 panelCb.add(cbGpx); 433 433 434 434 JButton buttonOpen = new JButton(tr("Open another GPX trace")); 435 435 buttonOpen.setIcon(ImageProvider.get("agpifoj-open")); 436 436 buttonOpen.addActionListener(new LoadGpxDataActionListener()); 437 437 438 438 panelCb.add(buttonOpen); 439 439 440 440 JPanel panelTf = new JPanel(); 441 441 panelTf.setLayout(new GridBagLayout()); 442 442 443 443 GridBagConstraints gc = new GridBagConstraints(); 444 444 gc.anchor = GridBagConstraints.WEST; 445 445 446 446 gc.gridx = gc.gridy = 0; 447 447 gc.gridwidth = gc.gridheight = 1; … … 464 464 gc.weighty = 0.0; 465 465 panelTf.add(tfTimezone, gc); 466 466 467 467 gc.gridx = 0; 468 468 gc.gridy = 1; … … 493 493 gc.weighty = 1.0; 494 494 panelTf.add(buttonViewGpsPhoto, gc); 495 495 496 496 gc.gridx = 0; 497 497 gc.gridy = 2; … … 500 500 gc.weightx = gc.weighty = 0.0; 501 501 panelTf.add(new JLabel(tr("Update position for: ")), gc); 502 502 503 503 gc.gridx = 1; 504 504 gc.gridy = 2; … … 510 510 rbAllImg = new JRadioButton(tr("All images")); 511 511 panelTf.add(rbAllImg, gc); 512 512 513 513 gc.gridx = 1; 514 514 gc.gridy = 3; … … 520 520 rbNoExifImg = new JRadioButton(tr("Images with no exif position")); 521 521 panelTf.add(rbNoExifImg, gc); 522 522 523 523 gc.gridx = 1; 524 524 gc.gridy = 4; … … 530 530 rbUntaggedImg = new JRadioButton(tr("Not yet tagged images")); 531 531 panelTf.add(rbUntaggedImg, gc); 532 532 533 533 ButtonGroup group = new ButtonGroup(); 534 534 group.add(rbAllImg); 535 535 group.add(rbNoExifImg); 536 536 group.add(rbUntaggedImg); 537 537 538 538 rbUntaggedImg.setSelected(true); 539 539 540 540 panel = new JPanel(); 541 541 panel.setLayout(new BorderLayout()); 542 542 543 543 panel.add(panelCb, BorderLayout.PAGE_START); 544 544 panel.add(panelTf, BorderLayout.CENTER); … … 555 555 556 556 if (item == null || ! (item instanceof GpxDataWrapper)) { 557 JOptionPane.showMessageDialog(Main.parent, tr("You should select a GPX track"), 557 JOptionPane.showMessageDialog(Main.parent, tr("You should select a GPX track"), 558 558 tr("No selected GPX track"), JOptionPane.ERROR_MESSAGE ); 559 559 continue; … … 563 563 Float timezoneValue = parseTimezone(tfTimezone.getText().trim()); 564 564 if (timezoneValue == null) { 565 JOptionPane.showMessageDialog(Main.parent, tr("Error while parsing timezone.\nExpected format: {0}", "+H:MM"), 565 JOptionPane.showMessageDialog(Main.parent, tr("Error while parsing timezone.\nExpected format: {0}", "+H:MM"), 566 566 tr("Invalid timezone"), JOptionPane.ERROR_MESSAGE); 567 567 continue; 568 568 } 569 569 gpstimezone = timezoneValue.floatValue(); 570 570 571 571 String deltaText = tfOffset.getText().trim(); 572 572 if (deltaText.length() > 0) { … … 574 574 delta = Long.parseLong(deltaText); 575 575 } catch(NumberFormatException nfe) { 576 JOptionPane.showMessageDialog(Main.parent, tr("Error while parsing offset.\nExpected format: {0}", "number"), 576 JOptionPane.showMessageDialog(Main.parent, tr("Error while parsing offset.\nExpected format: {0}", "number"), 577 577 tr("Invalid offset"), JOptionPane.ERROR_MESSAGE); 578 578 continue; … … 581 581 delta = 0; 582 582 } 583 583 584 584 Main.pref.put("tagimages.doublegpstimezone", Double.toString(gpstimezone)); 585 585 Main.pref.put("tagimages.gpstimezone", Long.toString(- ((long) gpstimezone))); 586 586 Main.pref.put("tagimages.delta", Long.toString(delta * 1000)); 587 587 588 588 isOk = true; 589 589 } 590 590 591 591 // Construct a list of images that have a date, and sort them on the date. 592 592 ArrayList<ImageEntry> dateImgLst = new ArrayList<ImageEntry>(yLayer.data.size()); … … 597 597 } 598 598 } 599 599 600 600 } else if (rbNoExifImg.isSelected()) { 601 601 for (ImageEntry e : yLayer.data) { … … 605 605 } 606 606 607 } else { // rbUntaggedImg.isSelected() 607 } else { // rbUntaggedImg.isSelected() 608 608 for (ImageEntry e : yLayer.data) { 609 609 if (e.time != null && e.coor == null) { … … 612 612 } 613 613 } 614 614 615 615 int matched = matchGpxTrack(dateImgLst, selectedGpx.data, (long) (gpstimezone * 3600000) + delta * 1000); 616 616 617 // Search whether an other layer has yet defined some bounding box. 617 // Search whether an other layer has yet defined some bounding box. 618 618 // If none, we'll zoom to the bounding box of the layer with the photos. 619 619 Collection<Layer> layerCol = Main.map.mapView.getAllLayers(); 620 620 Iterator<Layer> layerIter = layerCol.iterator(); 621 boolean boundingBoxedLayerFound = false; 621 boolean boundingBoxedLayerFound = false; 622 622 while (layerIter.hasNext()) { 623 623 Layer l = layerIter.next(); … … 636 636 Main.map.mapView.recalculateCenterScale(bbox); 637 637 } 638 638 639 639 Main.main.map.repaint(); 640 640 641 641 JOptionPane.showMessageDialog(Main.parent, tr("Found {0} matchs of {1} in GPX track {2}", matched, dateImgLst.size(), selectedGpx.name), 642 tr("GPX Track loaded"), 643 ((dateImgLst.size() > 0 && matched == 0) ? JOptionPane.WARNING_MESSAGE 642 tr("GPX Track loaded"), 643 ((dateImgLst.size() > 0 && matched == 0) ? JOptionPane.WARNING_MESSAGE 644 644 : JOptionPane.INFORMATION_MESSAGE)); 645 645 646 646 } 647 647 648 648 private int matchGpxTrack(ArrayList<ImageEntry> dateImgLst, GpxData selectedGpx, long offset) { 649 649 int ret = 0; 650 650 651 651 Collections.sort(dateImgLst, new Comparator<ImageEntry>() { 652 652 public int compare(ImageEntry arg0, ImageEntry arg1) { … … 654 654 } 655 655 }); 656 656 657 657 PrimaryDateParser dateParser = new PrimaryDateParser(); 658 658 659 659 for (GpxTrack trk : selectedGpx.tracks) { 660 660 for (Collection<WayPoint> segment : trk.trackSegs) { 661 661 662 662 long prevDateWp = 0; 663 663 WayPoint prevWp = null; 664 664 665 665 for (WayPoint curWp : segment) { 666 667 String curDateWpStr = (String) curWp.attr.get("time"); 666 667 String curDateWpStr = (String) curWp.attr.get("time"); 668 668 if (curDateWpStr != null) { 669 669 670 670 try { 671 671 long curDateWp = dateParser.parse(curDateWpStr).getTime() + offset; 672 672 ret += matchPoints(dateImgLst, prevWp, prevDateWp, curWp, curDateWp); 673 673 674 674 prevWp = curWp; 675 675 prevDateWp = curDateWp; … … 710 710 } catch (Exception e) { 711 711 } 712 713 while(i >= 0 712 713 while(i >= 0 714 714 && dateImgLst.get(i).time.getTime() == curDateWp) { 715 dateImgLst.get(i).pos = curWp.eastNorth; 715 dateImgLst.get(i).pos = curWp.eastNorth; 716 716 dateImgLst.get(i).coor = Main.proj.eastNorth2latlon(dateImgLst.get(i).pos); 717 717 dateImgLst.get(i).speed = speed; … … 720 720 i--; 721 721 } 722 722 723 723 if (prevDateWp != 0) { 724 724 long imgDate; 725 while(i >= 0 725 while(i >= 0 726 726 && (imgDate = dateImgLst.get(i).time.getTime()) > prevDateWp) { 727 727 dateImgLst.get(i).pos = new EastNorth( 728 728 prevWp.eastNorth.east() + ((curWp.eastNorth.east() - prevWp.eastNorth.east()) * (imgDate - prevDateWp)) / (curDateWp - prevDateWp), 729 prevWp.eastNorth.north() + ((curWp.eastNorth.north() - prevWp.eastNorth.north()) * (imgDate - prevDateWp)) / (curDateWp - prevDateWp)); 729 prevWp.eastNorth.north() + ((curWp.eastNorth.north() - prevWp.eastNorth.north()) * (imgDate - prevDateWp)) / (curDateWp - prevDateWp)); 730 730 dateImgLst.get(i).coor = Main.proj.eastNorth2latlon(dateImgLst.get(i).pos); 731 731 dateImgLst.get(i).speed = speed; 732 732 if (curElevation != null && prevElevation != null) { 733 733 dateImgLst.get(i).elevation = prevElevation + ((curElevation - prevElevation) * (imgDate - prevDateWp)) / (curDateWp - prevDateWp); 734 } 734 } 735 735 ret++; 736 736 i--; … … 757 757 return curIndex; 758 758 } 759 759 760 760 int curIndex = 0; 761 761 int startIndex=0; … … 782 782 private String formatTimezone(double timezone) { 783 783 StringBuffer ret = new StringBuffer(); 784 784 785 785 if (timezone < 0) { 786 786 ret.append('-'); … … 795 795 } 796 796 ret.append(minutes); 797 797 798 798 return ret.toString(); 799 799 } 800 800 801 801 private Float parseTimezone(String timezone) { 802 803 804 805 802 if (timezone.length() == 0) { 803 return new Float(0); 804 } 805 806 806 char sgnTimezone = '+'; 807 807 StringBuffer hTimezone = new StringBuffer(); … … 817 817 break; 818 818 case '+' : 819 case '-' : 819 case '-' : 820 820 if (state == 1) { 821 821 sgnTimezone = c; … … 825 825 } 826 826 break; 827 case ':' : 828 case '.' : 827 case ':' : 828 case '.' : 829 829 if (state == 2) { 830 830 state = 3; … … 833 833 } 834 834 break; 835 case '0' : case '1' : case '2' : case '3' : case '4' : 835 case '0' : case '1' : case '2' : case '3' : case '4' : 836 836 case '5' : case '6' : case '7' : case '8' : case '9' : 837 837 switch(state) { 838 case 1 : 839 case 2 : 838 case 1 : 839 case 2 : 840 840 state = 2; 841 841 hTimezone.append(c); 842 842 break; 843 case 3 : 843 case 3 : 844 844 mTimezone.append(c); 845 845 break; 846 default : 846 default : 847 847 return null; 848 848 } 849 849 break; 850 default : 850 default : 851 851 return null; 852 852 } 853 853 } 854 854 855 855 int h = 0; 856 856 int m = 0; 857 857 try { 858 859 860 861 858 h = Integer.parseInt(hTimezone.toString()); 859 if (mTimezone.length() > 0) { 860 m = Integer.parseInt(mTimezone.toString()); 861 } 862 862 } catch (NumberFormatException nfe) { 863 864 865 } 866 863 // Invalid timezone 864 return null; 865 } 866 867 867 if (h > 12 || m > 59 ) { 868 868 return null; 869 869 } else { 870 871 } 872 } 873 874 /** Return the distance in meters between 2 points 870 return new Float((h + m / 60.0) * (sgnTimezone == '-' ? -1 : 1)); 871 } 872 } 873 874 /** Return the distance in meters between 2 points 875 875 * Formula and earth radius from : http://en.wikipedia.org/wiki/Great-circle_distance */ 876 876 public double getDistance(WayPoint p1, WayPoint p2) { 877 877 double p1Lat = p1.latlon.lat() * Math.PI / 180; 878 double p1Lon = p1.latlon.lon() * Math.PI / 180; 878 double p1Lon = p1.latlon.lon() * Math.PI / 180; 879 879 double p2Lat = p2.latlon.lat() * Math.PI / 180; 880 880 double p2Lon = p2.latlon.lon() * Math.PI / 180; 881 double ret = Math.atan2(Math.sqrt(Math.pow(Math.cos(p2Lat) * Math.sin(p2Lon - p1Lon), 2) 881 double ret = Math.atan2(Math.sqrt(Math.pow(Math.cos(p2Lat) * Math.sin(p2Lon - p1Lon), 2) 882 882 + Math.pow(Math.cos(p1Lat) * Math.sin(p2Lat) 883 - Math.sin(p1Lat) * Math.cos(p2Lat) * Math.cos(p2Lon - p1Lon), 2)), 884 Math.sin(p1Lat) * Math.sin(p2Lat) 883 - Math.sin(p1Lat) * Math.cos(p2Lat) * Math.cos(p2Lon - p1Lon), 2)), 884 Math.sin(p1Lat) * Math.sin(p2Lat) 885 885 + Math.cos(p1Lat) * Math.cos(p2Lat) * Math.cos(p2Lon - p1Lon)) 886 886 * 6372795; // Earth radius, in meters -
applications/editors/josm/plugins/agpifoj/src/org/openstreetmap/josm/plugins/agpifoj/ImageDisplay.java
r10258 r12778 25 25 26 26 public class ImageDisplay extends JComponent { 27 27 28 28 /** The file that is currently displayed */ 29 29 private File file = null; 30 30 31 31 /** The image currently displayed */ 32 32 private Image image = null; 33 33 34 34 /** The image currently displayed */ 35 35 private boolean errorLoading = false; 36 37 /** The rectangle (in image coordinates) of the image that is visible. This rectangle is calculated 36 37 /** The rectangle (in image coordinates) of the image that is visible. This rectangle is calculated 38 38 * each time the zoom is modified */ 39 39 private Rectangle visibleRect = null; 40 40 41 41 /** When a selection is done, the rectangle of the selection (in image coordinates) */ 42 42 private Rectangle selectedRect = null; … … 46 46 47 47 private String osdText = null; 48 48 49 49 /** The thread that reads the images. */ 50 50 private class LoadImageRunnable implements Runnable { 51 51 52 52 File file = null; 53 53 54 54 public LoadImageRunnable(File file) { 55 55 this.file = file; 56 56 } 57 57 58 58 public void run() { 59 59 Image img = Toolkit.getDefaultToolkit().createImage(file.getPath()); 60 60 tracker.addImage(img, 1); 61 61 62 62 // Wait for the end of loading 63 63 while (! tracker.checkID(1, true)) { 64 64 if (this.file != ImageDisplay.this.file) { 65 // The file has changed 65 // The file has changed 66 66 tracker.removeImage(img); 67 67 return; … … 77 77 error = true; 78 78 } 79 79 80 80 synchronized(ImageDisplay.this) { 81 81 if (this.file != ImageDisplay.this.file) { 82 // The file has changed 82 // The file has changed 83 83 tracker.removeImage(img); 84 84 return; … … 93 93 } 94 94 } 95 95 96 96 private class ImgDisplayMouseListener implements MouseListener, MouseWheelListener, MouseMotionListener { 97 97 98 98 boolean mouseIsDragging = false; 99 99 Point mousePointInImg = null; 100 101 /** Zoom in and out, trying to preserve the point of the image that was under the mouse cursor 102 * at the same place */ 100 101 /** Zoom in and out, trying to preserve the point of the image that was under the mouse cursor 102 * at the same place */ 103 103 public void mouseWheelMoved(MouseWheelEvent e) { 104 104 File file; 105 105 Image image; 106 106 Rectangle visibleRect; 107 107 108 108 synchronized (ImageDisplay.this) { 109 109 file = ImageDisplay.this.file; … … 111 111 visibleRect = ImageDisplay.this.visibleRect; 112 112 } 113 113 114 114 mouseIsDragging = false; 115 115 selectedRect = null; 116 116 117 117 if (image == null) { 118 118 return; 119 119 } 120 120 121 // Calculate the mouse cursor position in image coordinates, so that we can center the zoom 122 // on that mouse position. 121 // Calculate the mouse cursor position in image coordinates, so that we can center the zoom 122 // on that mouse position. 123 123 if (e.getClickCount() == 1 || mousePointInImg == null) { 124 124 mousePointInImg = comp2imgCoord(visibleRect, e.getX(), e.getY()); 125 125 } 126 126 127 127 // Applicate the zoom to the visible rectangle in image coordinates 128 128 if (e.getWheelRotation() > 0) { … … 133 133 visibleRect.height = visibleRect.height * 2 / 3; 134 134 } 135 135 136 136 // Check that the zoom doesn't exceed 2:1 137 137 if (visibleRect.width < getSize().width / 2) { … … 141 141 visibleRect.height = getSize().height / 2; 142 142 } 143 143 144 144 // Set the same ratio for the visible rectangle and the display area 145 145 int hFact = visibleRect.height * getSize().width; … … 150 150 visibleRect.height = wFact / getSize().width; 151 151 } 152 152 153 153 // The size of the visible rectangle is limited by the image size. 154 154 checkVisibleRectSize(image, visibleRect); 155 155 156 156 // Set the position of the visible rectangle, so that the mouse cursor doesn't move on the image. 157 157 Rectangle drawRect = calculateDrawImageRectangle(visibleRect); 158 158 visibleRect.x = mousePointInImg.x + ((drawRect.x - e.getX()) * visibleRect.width) / drawRect.width; 159 159 visibleRect.y = mousePointInImg.y + ((drawRect.y - e.getY()) * visibleRect.height) / drawRect.height; 160 160 161 161 // The position is also limited by the image size 162 162 checkVisibleRectPos(image, visibleRect); 163 163 164 164 synchronized(ImageDisplay.this) { 165 165 if (ImageDisplay.this.file == file) { … … 176 176 Image image; 177 177 Rectangle visibleRect; 178 178 179 179 synchronized (ImageDisplay.this) { 180 180 file = ImageDisplay.this.file; … … 190 190 return; 191 191 } 192 192 193 193 // Calculate the translation to set the clicked point the center of the view. 194 194 Point click = comp2imgCoord(visibleRect, e.getX(), e.getY()); 195 195 Point center = getCenterImgCoord(visibleRect); 196 196 197 197 visibleRect.x += click.x - center.x; 198 198 visibleRect.y += click.y - center.y; 199 199 200 200 checkVisibleRectPos(image, visibleRect); 201 201 202 202 synchronized(ImageDisplay.this) { 203 203 if (ImageDisplay.this.file == file) { … … 208 208 } 209 209 210 /** Initialize the dragging, either with button 1 (simple dragging) or button 3 (selection of 210 /** Initialize the dragging, either with button 1 (simple dragging) or button 3 (selection of 211 211 * a picture part) */ 212 212 public void mousePressed(MouseEvent e) { … … 216 216 return; 217 217 } 218 218 219 219 File file; 220 220 Image image; 221 221 Rectangle visibleRect; 222 222 223 223 synchronized (ImageDisplay.this) { 224 224 file = ImageDisplay.this.file; … … 251 251 return; 252 252 } 253 253 254 254 File file; 255 255 Image image; 256 256 Rectangle visibleRect; 257 257 258 258 synchronized (ImageDisplay.this) { 259 259 file = ImageDisplay.this.file; … … 279 279 } 280 280 ImageDisplay.this.repaint(); 281 281 282 282 } else if (selectedRect != null) { 283 283 Point p = comp2imgCoord(visibleRect, e.getX(), e.getY()); … … 300 300 return; 301 301 } 302 302 303 303 File file; 304 304 Image image; 305 305 Rectangle visibleRect; 306 306 307 307 synchronized (ImageDisplay.this) { 308 308 file = ImageDisplay.this.file; … … 319 319 if (mouseIsDragging) { 320 320 mouseIsDragging = false; 321 321 322 322 } else if (selectedRect != null) { 323 323 int oldWidth = selectedRect.width; … … 331 331 selectedRect.height = getSize().height / 2; 332 332 } 333 333 334 334 // Set the same ratio for the visible rectangle and the display area 335 335 int hFact = selectedRect.height * getSize().width; … … 340 340 selectedRect.height = wFact / getSize().width; 341 341 } 342 342 343 343 // Keep the center of the selection 344 344 if (selectedRect.width != oldWidth) { … … 348 348 selectedRect.y -= (selectedRect.height - oldHeight) / 2; 349 349 } 350 350 351 351 checkVisibleRectSize(image, selectedRect); 352 352 checkVisibleRectPos(image, selectedRect); 353 353 354 354 synchronized (ImageDisplay.this) { 355 355 if (file == ImageDisplay.this.file) { 356 356 ImageDisplay.this.visibleRect = selectedRect; 357 357 } 358 } 358 } 359 359 selectedRect = null; 360 360 ImageDisplay.this.repaint(); … … 370 370 public void mouseMoved(MouseEvent e) { 371 371 } 372 372 373 373 private void checkPointInVisibleRect(Point p, Rectangle visibleRect) { 374 374 if (p.x < visibleRect.x) { … … 386 386 } 387 387 } 388 388 389 389 public ImageDisplay() { 390 390 ImgDisplayMouseListener mouseListener = new ImgDisplayMouseListener(); … … 393 393 addMouseMotionListener(mouseListener); 394 394 } 395 395 396 396 public void setImage(File file) { 397 397 synchronized(this) { … … 410 410 this.osdText = text; 411 411 } 412 412 413 413 public void paintComponent(Graphics g) { 414 414 Image image; … … 416 416 Rectangle visibleRect; 417 417 boolean errorLoading; 418 418 419 419 synchronized(this) { 420 420 image = this.image; … … 423 423 errorLoading = this.errorLoading; 424 424 } 425 425 426 426 if (file == null) { 427 427 g.setColor(Color.black); … … 447 447 } else { 448 448 Rectangle target = calculateDrawImageRectangle(visibleRect); 449 g.drawImage(image, 450 target.x, target.y, target.x + target.width, target.y + target.height, 451 visibleRect.x, visibleRect.y, visibleRect.x + visibleRect.width, visibleRect.y + visibleRect.height, 449 g.drawImage(image, 450 target.x, target.y, target.x + target.width, target.y + target.height, 451 visibleRect.x, visibleRect.y, visibleRect.x + visibleRect.width, visibleRect.y + visibleRect.height, 452 452 null); 453 453 if (selectedRect != null) { 454 454 Point topLeft = img2compCoord(visibleRect, selectedRect.x, selectedRect.y); 455 Point bottomRight = img2compCoord(visibleRect, 456 selectedRect.x + selectedRect.width, 455 Point bottomRight = img2compCoord(visibleRect, 456 selectedRect.x + selectedRect.width, 457 457 selectedRect.y + selectedRect.height); 458 458 g.setColor(new Color(128, 128, 128, 180)); … … 502 502 } 503 503 } 504 504 505 505 private final Point img2compCoord(Rectangle visibleRect, int xImg, int yImg) { 506 506 Rectangle drawRect = calculateDrawImageRectangle(visibleRect); … … 524 524 int x, y, w, h; 525 525 x = 0; 526 y = 0; 526 y = 0; 527 527 w = size.width; 528 528 h = size.height; 529 529 530 530 int wFact = w * visibleRect.height; 531 531 int hFact = h * visibleRect.width; … … 546 546 Image image; 547 547 Rectangle visibleRect; 548 548 549 549 synchronized (this) { 550 550 file = ImageDisplay.this.file; … … 560 560 // The display is not at best fit. => Zoom to best fit 561 561 visibleRect = new Rectangle(0, 0, image.getWidth(null), image.getHeight(null)); 562 562 563 563 } else { 564 564 // The display is at best fit => zoom to 1:1 565 565 Point center = getCenterImgCoord(visibleRect); 566 visibleRect = new Rectangle(center.x - getWidth() / 2, center.y - getHeight() / 2, 566 visibleRect = new Rectangle(center.x - getWidth() / 2, center.y - getHeight() / 2, 567 567 getWidth(), getHeight()); 568 568 checkVisibleRectPos(image, visibleRect); 569 569 } 570 570 571 571 synchronized(this) { 572 572 if (file == this.file) { -
applications/editors/josm/plugins/colorscheme/src/at/dallermassl/josm/plugin/colorscheme/ColorSchemePlugin.java
r4278 r12778 14 14 */ 15 15 public class ColorSchemePlugin extends Plugin { 16 16 17 17 /** 18 18 * Default Constructor 19 19 */ 20 20 public ColorSchemePlugin() { 21 21 22 22 } 23 23 … … 26 26 return new ColorSchemePreference(); 27 27 } 28 29 28 29 30 30 31 31 } -
applications/editors/josm/plugins/colorscheme/src/at/dallermassl/josm/plugin/colorscheme/ColorSchemePreference.java
r12588 r12778 36 36 private static final String PREF_KEY_SCHEMES_NAMES = PREF_KEY_SCHEMES_PREFIX + "names"; 37 37 public static final String PREF_KEY_COLOR_PREFIX = "color."; 38 39 40 41 42 43 44 45 46 47 48 38 private JList schemesList; 39 private DefaultListModel listModel; 40 private List<String>colorKeys; 41 private ColorPreference colorPreference; 42 43 /** 44 * Default Constructor 45 */ 46 public ColorSchemePreference() { 47 } 48 49 49 50 51 52 53 50 /* (non-Javadoc) 51 * @see org.openstreetmap.josm.gui.preferences.PreferenceSetting#addGui(org.openstreetmap.josm.gui.preferences.PreferenceDialog) 52 */ 53 public void addGui(final PreferenceDialog gui) { 54 54 Map<String, String> colorMap = Main.pref.getAllPrefix(PREF_KEY_COLOR_PREFIX); 55 55 colorKeys = new ArrayList<String>(colorMap.keySet()); 56 56 Collections.sort(colorKeys); 57 58 57 listModel = new DefaultListModel(); 58 schemesList = new JList(listModel); 59 59 String schemes = Main.pref.get(PREF_KEY_SCHEMES_NAMES); 60 60 StringTokenizer st = new StringTokenizer(schemes, ";"); … … 76 76 } 77 77 }); 78 79 80 81 82 83 84 85 86 78 JButton addScheme = new JButton(tr("Add")); 79 addScheme.addActionListener(new ActionListener(){ 80 public void actionPerformed(ActionEvent e) { 81 String schemeName = JOptionPane.showInputDialog(Main.parent, tr("Color Scheme")); 82 if (schemeName == null) 83 return; 84 schemeName = schemeName.replaceAll("\\.", "_"); 85 setColorScheme(schemeName, getColorPreference().getColorModel()); 86 listModel.addElement(schemeName); 87 87 saveSchemeNamesToPref(); 88 89 88 } 89 }); 90 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 91 JButton deleteScheme = new JButton(tr("Delete")); 92 deleteScheme.addActionListener(new ActionListener(){ 93 public void actionPerformed(ActionEvent e) { 94 if (schemesList.getSelectedIndex() == -1) 95 JOptionPane.showMessageDialog(Main.parent, tr("Please select the scheme to delete.")); 96 else { 97 String schemeName = (String) listModel.get(schemesList.getSelectedIndex()); 98 removeColorSchemeFromPreferences(schemeName); 99 listModel.remove(schemesList.getSelectedIndex()); 100 saveSchemeNamesToPref(); 101 } 102 } 103 }); 104 schemesList.setVisibleRowCount(3); 105 105 106 106 //schemesList.setToolTipText(tr("The sources (url or filename) of annotation preset definition files. See http://josm.eigenheimstrasse.de/wiki/AnnotationPresets for help.")); 107 107 useScheme.setToolTipText(tr("Use the selected scheme from the list.")); 108 109 108 addScheme.setToolTipText(tr("Use the current colors as a new color scheme.")); 109 deleteScheme.setToolTipText(tr("Delete the selected scheme from the list.")); 110 110 111 112 113 114 115 111 gui.map.add(new JLabel(tr("Color Schemes")), GBC.eol().insets(0,5,0,0)); 112 gui.map.add(new JScrollPane(schemesList), GBC.eol().fill(GBC.BOTH)); 113 JPanel buttonPanel = new JPanel(new GridBagLayout()); 114 gui.map.add(buttonPanel, GBC.eol().fill(GBC.HORIZONTAL)); 115 buttonPanel.add(Box.createHorizontalGlue(), GBC.std().fill(GBC.HORIZONTAL)); 116 116 buttonPanel.add(useScheme, GBC.std().insets(0,5,5,0)); 117 118 119 120 121 122 123 124 117 buttonPanel.add(addScheme, GBC.std().insets(0,5,5,0)); 118 buttonPanel.add(deleteScheme, GBC.std().insets(0,5,5,0)); 119 } 120 121 /** 122 * Saves the names of the schemes to the preferences. 123 */ 124 public void saveSchemeNamesToPref() { 125 125 if (schemesList.getModel().getSize() > 0) { 126 126 StringBuilder sb = new StringBuilder(); … … 129 129 Main.pref.put(PREF_KEY_SCHEMES_NAMES, sb.toString().substring(1)); 130 130 } else 131 Main.pref.put(PREF_KEY_SCHEMES_NAMES, null); 132 131 Main.pref.put(PREF_KEY_SCHEMES_NAMES, null); 132 } 133 133 134 135 136 137 138 139 140 141 142 134 public boolean ok() { 135 return false;// nothing to do 136 } 137 138 /** 139 * Remove all color entries for the given scheme from the preferences. 140 * @param schemeName the name of the scheme. 141 */ 142 public void removeColorSchemeFromPreferences(String schemeName) { 143 143 // delete color entries for scheme in preferences: 144 144 Map<String, String> colors = Main.pref.getAllPrefix(PREF_KEY_SCHEMES_PREFIX + schemeName + "."); 145 145 for(String key : colors.keySet()) { 146 146 Main.pref.put(key, null); 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 147 } 148 } 149 150 /** 151 * Copy all color entries from the given map to entries in preferences with the scheme name. 152 * @param schemeName the name of the scheme. 153 * @param the map containing the color key (without prefix) and the html color values. 154 */ 155 public void setColorScheme(String schemeName, Map<String, String> colorMap) { 156 String key; 157 for(String colorKey : colorMap.keySet()) { 158 key = PREF_KEY_SCHEMES_PREFIX + schemeName + "." + PREF_KEY_COLOR_PREFIX + colorKey; 159 Main.pref.put(key, colorMap.get(colorKey)); 160 } 161 } 162 163 /** 164 * Reads all colors for a scheme and returns them in a map (key = color key without prefix, 165 * value = html color code). 166 * @param schemeName the name of the scheme. 167 */ 168 public Map<String, String> getColorMap(String schemeName) { 169 String colorKey; 170 String prefix = PREF_KEY_SCHEMES_PREFIX + schemeName + "." + PREF_KEY_COLOR_PREFIX; 171 Map<String, String>colorMap = new HashMap<String, String>(); 172 for(String schemeColorKey : Main.pref.getAllPrefix(prefix).keySet()) { 173 colorKey = schemeColorKey.substring(prefix.length()); 174 colorMap.put(colorKey, Main.pref.get(schemeColorKey)); 175 } 176 return colorMap; 177 } 178 178 179 179 public ColorPreference getColorPreference() { -
applications/editors/josm/plugins/duplicateway/src/org/openstreetmap/josm/plugins/duplicateway/DuplicateWayAction.java
r12694 r12778 34 34 /** 35 35 * Duplicate an existing set of ordered ways, offset by a specified distance. 36 * 36 * 37 37 * This basic version just creates a completely seperate way and makes no 38 38 * attempt to attach it to any other ways. 39 * 39 * 40 40 * Planned Improvements: 41 * 41 * 42 42 * 1. After creation of the duplicate way and while it is still selected allow 43 43 * the Mouse wheel, or the up and down arrow (probably in association with the 44 44 * shift key) to increase/decrease the offset distance. Clicking anywhere, or 45 45 * moving the mouse out of the view window should finish this mode. 46 * 46 * 47 47 * 2. Locate points close to the end points and pop up a dialog asking of these 48 48 * should be joined. 49 * 49 * 50 50 * 3. Handle intersecting ways. Pop up a dialog for each asking if the 51 51 * intersecting way should be carried accross to intersect the newly created 52 52 * way. Handle multiple intersecting ways at a point. 53 * 54 * 53 * 54 * 55 55 * @author Brent Easton 56 * 56 * 57 57 */ 58 58 public class DuplicateWayAction extends MapMode implements 59 59 SelectionChangedListener, MouseListener { 60 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 61 private static final long serialVersionUID = 1L; 62 63 protected Cursor oldCursor; 64 65 protected List<Way> selectedWays; 66 67 protected MapMode previousMode; 68 69 /** 70 * Create new DuplicateWay Action 71 * 72 * @param name 73 */ 74 public DuplicateWayAction() { 75 super(tr("Duplicate Way"), "duplicateway", 76 tr("Duplicate selected ways."), KeyEvent.VK_W, null, 77 ImageProvider.getCursor("crosshair", "duplicate")); 78 setEnabled(false); 79 DataSet.listeners.add(this); 80 } 81 82 @Override public void enterMode() { 83 super.enterMode(); 84 Main.map.mapView.addMouseListener(this); 85 } 86 87 @Override public void exitMode() { 88 super.exitMode(); 89 Main.map.mapView.removeMouseListener(this); 90 } 91 92 /** 93 * The Duplicate Way button has been clicked 94 * 95 * @param e 96 * Action Event 97 */ 98 @Override public void actionPerformed(ActionEvent e) { 99 100 selectedWays = new ArrayList<Way>(); 101 for (OsmPrimitive osm : Main.ds.getSelected()) { 102 if (osm instanceof Way) { 103 Way way = (Way)osm; 104 EastNorth last = null; 105 for (Segment seg : way.segments) { 106 if (last != null) { 107 if (!seg.from.eastNorth.equals(last)) { 108 JOptionPane.showMessageDialog(Main.parent, 109 tr("Can't duplicate unordered way.")); 110 return; 111 } 112 } 113 last = seg.to.eastNorth; 114 } 115 selectedWays.add(way); 116 } 117 } 118 119 if (Main.map == null) { 120 JOptionPane.showMessageDialog(Main.parent, tr("No data loaded.")); 121 return; 122 } 123 124 if (selectedWays.isEmpty()) { 125 JOptionPane.showMessageDialog(Main.parent, 126 tr("You must select at least one way.")); 127 return; 128 } 129 previousMode = Main.map.mapMode; 130 super.actionPerformed(e); 131 } 132 133 /** 134 * Create a new Node object at a specified Easting/Northing location 135 * 136 * @param east 137 * Easting of new Node 138 * @param north 139 * Northing of new node 140 * @return new Node 141 */ 142 public static Node createNode(double east, double north) { 143 return new Node(Main.proj.eastNorth2latlon(new EastNorth(east, north))); 144 } 145 146 /** 147 * Duplicate the selected ways. The distance to be offset is determined by 148 * finding the distance of the 'offset' point from the nearest segment. 149 * 150 * @param clickPoint 151 * The point in screen co-ordinates used to calculate the offset 152 * distance 153 */ 154 protected void duplicate(Point clickPoint) { 155 156 EastNorth clickEN = Main.map.mapView.getEastNorth(clickPoint.x, 157 clickPoint.y); 158 159 /* 160 * First, find the nearest Segment belonging to a selected way 161 */ 162 Segment cs = null; 163 for (Way way : selectedWays) { 164 double minDistance = Double.MAX_VALUE; 165 // segments 166 for (Segment ls : way.segments) { 167 if (ls.deleted || ls.incomplete) 168 continue; 169 double perDist = JVector.perpDistance(ls, clickEN); 170 if (perDist < minDistance) { 171 minDistance = perDist; 172 cs = ls; 173 } 174 } 175 } 176 177 if (cs == null) { 178 return; 179 } 180 181 /* 182 * Find the distance we need to offset the new way +ve offset is to the 183 * right of the initial way, -ve to the left 184 */ 185 JVector closestSegment = new JVector(cs); 186 double offset = closestSegment.calculateOffset(clickEN); 187 188 Collection<Command> commands = new LinkedList<Command>(); 189 Collection<Way> ways = new LinkedList<Way>(); 190 191 /* 192 * First new node is offset 90 degrees from the first point 193 */ 194 for (Way way : selectedWays) { 195 Way newWay = new Way(); 196 197 Node lastNode = null; 198 JVector lastLine = null; 199 200 for (Segment seg : way.segments) { 201 JVector currentLine = new JVector(seg); 202 Node newNode = null; 203 204 if (lastNode == null) { 205 JVector perpVector = new JVector(currentLine); 206 perpVector.rotate90(offset); 207 newNode = createNode(perpVector.getP2().getX(), perpVector 208 .getP2().getY()); 209 commands.add(new AddCommand(newNode)); 210 } else { 211 JVector bisector = lastLine.bisector(currentLine, offset); 212 newNode = createNode(bisector.getP2().getX(), bisector 213 .getP2().getY()); 214 commands.add(new AddCommand(newNode)); 215 Segment s = new Segment(newNode, lastNode); 216 commands.add(new AddCommand(s)); 217 newWay.segments.add(0, s); 218 } 219 220 lastLine = currentLine; 221 lastNode = newNode; 222 223 } 224 lastLine.reverse(); 225 lastLine.rotate90(-offset); 226 Node newNode = createNode(lastLine.getP2().getX(), lastLine.getP2() 227 .getY()); 228 commands.add(new AddCommand(newNode)); 229 Segment s = new Segment(newNode, lastNode); 230 commands.add(new AddCommand(s)); 231 newWay.segments.add(0, s); 232 233 for (String key : way.keySet()) { 234 newWay.put(key, way.get(key)); 235 } 236 commands.add(new AddCommand(newWay)); 237 ways.add(newWay); 238 } 239 240 Main.main.undoRedo.add(new SequenceCommand(tr("Create duplicate way"), 241 commands)); 242 Main.ds.setSelected(ways); 243 } 244 245 /** 246 * Enable the "Duplicate way" menu option if at least one way is selected 247 * 248 * @param newSelection 249 */ 250 public void selectionChanged(Collection<? extends OsmPrimitive> newSelection) { 251 for (OsmPrimitive osm : newSelection) { 252 if (osm instanceof Way) { 253 setEnabled(true); 254 return; 255 } 256 } 257 setEnabled(false); 258 } 259 260 /** 261 * User has clicked on map to indicate the offset. Create the 262 * duplicate way and exit duplicate mode 263 * 264 * @param e 265 */ 266 public void mouseClicked(MouseEvent e) { 267 duplicate(e.getPoint()); 268 exitMode(); 269 Main.map.selectMapMode(previousMode); 270 } 271 271 } -
applications/editors/josm/plugins/duplicateway/src/org/openstreetmap/josm/plugins/duplicateway/DuplicateWayPlugin.java
r4651 r12778 11 11 /** 12 12 * A plugin to add a duplicate way option to assist with creating divided roads 13 * 13 * 14 14 * @author Brent Easton 15 15 */ … … 38 38 toolsMenu.add(new JMenuItem(new DuplicateWayAction())); 39 39 } 40 40 41 41 } 42 42 -
applications/editors/josm/plugins/globalsat/src/org/kaintoch/gps/globalsat/dg100/ByteHelper.java
r10378 r12778 12 12 { 13 13 14 15 * 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 14 /** 15 * 16 * @param src 17 * @param startS 18 * @param len 19 * @param dest 20 * @param startD 21 * @return 22 */ 23 public static int copyByteArr2ByteArr(byte src[], int startS, int len, byte dest[], int startD) 24 { 25 for (int ii = 0 ; 26 ii < len && startD < dest.length && startS < src.length && startD >= 0 && startS >= 0; 27 ++ii, ++startD, ++startS) 28 { 29 dest[startD] = src[startS]; 30 } 31 return startD; 32 } 33 33 34 35 * 36 37 38 39 40 41 42 34 /** 35 * 36 * @param byt 37 * @return 38 */ 39 public static int byte2IntUnsigned(byte byt) 40 { 41 return ((byt >= 0) ? byt : 256 + byt); 42 } 43 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 return chr; 72 44 /** 45 * 46 * @param nibble 47 */ 48 private static char nibble2Char(int nibble) 49 { 50 char chr = '*'; 51 nibble = nibble & 0xF; 52 switch (nibble) 53 { 54 case 0: chr = '0'; break; 55 case 1: chr = '1'; break; 56 case 2: chr = '2'; break; 57 case 3: chr = '3'; break; 58 case 4: chr = '4'; break; 59 case 5: chr = '5'; break; 60 case 6: chr = '6'; break; 61 case 7: chr = '7'; break; 62 case 8: chr = '8'; break; 63 case 9: chr = '9'; break; 64 case 10: chr = 'A'; break; 65 case 11: chr = 'B'; break; 66 case 12: chr = 'C'; break; 67 case 13: chr = 'D'; break; 68 case 14: chr = 'E'; break; 69 case 15: chr = 'F'; break; 70 } 71 return chr; 72 } 73 73 74 75 * 76 77 78 79 80 81 82 83 84 85 86 74 /** 75 * 76 * @return 77 */ 78 public static String byte2StringUnsigned(byte byt) 79 { 80 StringBuffer buf = new StringBuffer(4); 81 int bb = byte2IntUnsigned(byt); 82 //buf.append("0x"); 83 buf.append(nibble2Char(bb / 16)); 84 buf.append(nibble2Char(bb % 16)); 85 return buf.toString(); 86 } 87 87 88 89 * 90 91 92 93 94 95 88 /** 89 * 90 * @param byt 91 */ 92 public static String byteArray2String(byte byt[]) 93 { 94 return byteArray2String(byt, byt.length); 95 } 96 96 97 98 * 99 100 101 102 103 104 105 106 107 108 109 110 111 97 /** 98 * 99 * @param byt 100 * @param cnt 101 */ 102 public static String byteArray2String(byte byt[], int cnt) 103 { 104 StringBuffer buf = new StringBuffer(cnt * 5); 105 for (int ii = 0 ; ii < cnt && ii < byt.length ; ++ii) 106 { 107 if (ii > 0) {buf.append(" ");} 108 buf.append(byte2StringUnsigned(byt[ii])); 109 } 110 return buf.toString(); 111 } 112 112 113 113 } -
applications/editors/josm/plugins/globalsat/src/org/kaintoch/gps/globalsat/dg100/Dg100Config.java
r11555 r12778 30 30 // nn nn nn nn: distance in m 31 31 // xx xx: checksum 32 // 32 // A0 A2 00 35 B7 jj kk ll ll ll ll mm nn nn nn nn 33 33 // aa aa aa aa bb bb bb bb cc cc cc cc 00 00 gg hh 34 34 // ii dd dd dd dd ee ee ee ee ff ff ff ff 01 61 01 35 35 // 01 0C D5 0D 00 04 CC B0 B3 36 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 return 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 37 private byte logFormat = -1; 38 private byte disableLogSpeed = -1; 39 private int speedThres = -1; 40 private byte disableLogDist = -1; 41 private int distThres = -1; 42 private int swATime = -1; 43 private int swBTime = -1; 44 private int swCTime = -1; 45 private short unk1 = -1; 46 private byte swATimeOrDist = -1; 47 private byte swBTimeOrDist = -1; 48 private byte swCTimeOrDist = -1; 49 private int swADist = -1; 50 private int swBDist = -1; 51 private int swCDist = -1; 52 private byte unk2 = -1; 53 private int remainder = -1; 54 private int unk3 = -1; 55 private int unk4 = -1; 56 57 private static String propLogFormat = "logFormat"; 58 private static String propDisableLogSpeed = "disableLogSpeed"; 59 private static String propSpeedThres = "speedThres"; 60 private static String propDisableLogDist = "disableLogDist"; 61 private static String propDistThres = "distThres"; 62 private static String propSwATime = "swATime"; 63 private static String propSwBTime = "swBTime"; 64 private static String propSwCTime = "swCTime"; 65 private static String propUnk1 = "unk1"; 66 private static String propSwATimeOrDist = "swATimeOrDist"; 67 private static String propSwBTimeOrDist = "swBTimeOrDist"; 68 private static String propSwCTimeOrDist = "swCTimeOrDist"; 69 private static String propSwADist = "swADist"; 70 private static String propSwBDist = "swBDist"; 71 private static String propSwCDist = "swCDist"; 72 private static String propUnk2 = "unk2"; 73 private static String propRemainder = "remainder"; 74 private static String propUnk3 = "unk3"; 75 private static String propUnk4 = "unk4"; 76 77 public Dg100Config(ByteBuffer buf) 78 { 79 logFormat = buf.get(); 80 disableLogSpeed = buf.get(); 81 speedThres = buf.getInt(); 82 disableLogDist = buf.get(); 83 distThres = buf.getInt(); 84 swATime = buf.getInt(); 85 swBTime = buf.getInt(); 86 swCTime = buf.getInt(); 87 unk1 = buf.getShort(); 88 swATimeOrDist = buf.get(); 89 swBTimeOrDist = buf.get(); 90 swCTimeOrDist = buf.get(); 91 swADist = buf.getInt(); 92 swBDist = buf.getInt(); 93 swCDist = buf.getInt(); 94 unk2 = buf.get(); 95 remainder = buf.get(); 96 unk3 = buf.get(); 97 unk4 = buf.get(); 98 } 99 100 public Dg100Config(String fName) 101 throws Exception 102 { 103 readProps(fName); 104 } 105 106 public String toString() 107 { 108 return 109 "[Dg100Config: logFormat = " + logFormat 110 + ",disableLogSpeed = " + disableLogSpeed 111 + ",speedThres = " + speedThres 112 + ",disableLogDist = " + disableLogDist 113 + ",distThres = " + distThres 114 + ",swATime = " + swATime 115 + ",swBTime = " + swBTime 116 + ",swCTime = " + swCTime 117 + ",unk1 = " + unk1 118 + ",swATimeOrDist = " + swATimeOrDist 119 + ",swBTimeOrDist = " + swBTimeOrDist 120 + ",swCTimeOrDist = " + swCTimeOrDist 121 + ",swADist = " + swADist 122 + ",swBDist = " + swBDist 123 + ",swCDist = " + swCDist 124 + ",unk2 = " + unk2 125 + ",remainder = " + remainder 126 + ",unk3 = " + unk3 127 + ",unk4 = " + unk4 128 ; 129 } 130 131 /** 132 * @param buf 133 */ 134 public void write(ByteBuffer buf) 135 { 136 buf.position(5); 137 buf.put(logFormat); 138 buf.put(disableLogSpeed); 139 buf.putInt(speedThres); 140 buf.put(disableLogDist); 141 buf.putInt(distThres); 142 buf.putInt(swATime); 143 buf.putInt(swBTime); 144 buf.putInt(swCTime); 145 buf.putShort(unk1); 146 buf.put(swATimeOrDist); 147 buf.put(swBTimeOrDist); 148 buf.put(swCTimeOrDist); 149 buf.putInt(swADist); 150 buf.putInt(swBDist); 151 buf.putInt(swCDist); 152 buf.put(unk2); 153 } 154 155 /** 156 * @return Returns the disableLogDist. 157 */ 158 public boolean getDisableLogDist() 159 { 160 return disableLogDist != 0; 161 } 162 163 /** 164 * @param disableLogDist The disableLogDist to set. 165 */ 166 public void setDisableLogDist(boolean disableLogDist) 167 { 168 168 this.disableLogDist = (byte)(disableLogDist ? 1 : 0); 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 169 } 170 171 /** 172 * @return Returns the disableLogSpeed. 173 */ 174 public boolean getDisableLogSpeed() 175 { 176 return disableLogSpeed != 0; 177 } 178 179 /** 180 * @param disableLogSpeed The disableLogSpeed to set. 181 */ 182 public void setDisableLogSpeed(boolean disableLogSpeed) 183 { 184 184 this.disableLogSpeed = (byte)(disableLogSpeed ? 1 : 0); 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 419 420 421 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 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 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 185 } 186 187 /** 188 * @return Returns the distThres. 189 */ 190 public int getDistThres() 191 { 192 return distThres; 193 } 194 195 /** 196 * @param distThres The distThres to set. 197 */ 198 public void setDistThres(int distThres) 199 { 200 this.distThres = distThres; 201 } 202 203 /** 204 * @return Returns the logFormat. 205 */ 206 public byte getLogFormat() 207 { 208 return logFormat; 209 } 210 211 /** 212 * @param logFormat The logFormat to set. 213 */ 214 public void setLogFormat(byte logFormat) 215 { 216 this.logFormat = logFormat; 217 } 218 219 /** 220 * @return Returns the speedThres. 221 */ 222 public int getSpeedThres() 223 { 224 return speedThres; 225 } 226 227 /** 228 * @param speedThres The speedThres to set. 229 */ 230 public void setSpeedThres(int speedThres) 231 { 232 this.speedThres = speedThres; 233 } 234 235 /** 236 * @return Returns the swADist. 237 */ 238 public int getSwADist() 239 { 240 return swADist; 241 } 242 243 /** 244 * @param swADist The swADist to set. 245 */ 246 public void setSwADist(int swADist) 247 { 248 this.swADist = swADist; 249 } 250 251 /** 252 * @return Returns the swATime. 253 */ 254 public int getSwATime() 255 { 256 return swATime; 257 } 258 259 /** 260 * @param swATime The swATime to set. 261 */ 262 public void setSwATime(int swATime) 263 { 264 this.swATime = swATime; 265 } 266 267 /** 268 * @return Returns the swATimeOrDist. 269 */ 270 public byte getSwATimeOrDist() 271 { 272 return swATimeOrDist; 273 } 274 275 /** 276 * @param swATimeOrDist The swATimeOrDist to set. 277 */ 278 public void setSwATimeOrDist(byte swATimeOrDist) 279 { 280 this.swATimeOrDist = swATimeOrDist; 281 } 282 283 /** 284 * @return Returns the swBDist. 285 */ 286 public int getSwBDist() 287 { 288 return swBDist; 289 } 290 291 /** 292 * @param swBDist The swBDist to set. 293 */ 294 public void setSwBDist(int swBDist) 295 { 296 this.swBDist = swBDist; 297 } 298 299 /** 300 * @return Returns the swBTime. 301 */ 302 public int getSwBTime() 303 { 304 return swBTime; 305 } 306 307 /** 308 * @param swBTime The swBTime to set. 309 */ 310 public void setSwBTime(int swBTime) 311 { 312 this.swBTime = swBTime; 313 } 314 315 /** 316 * @return Returns the swBTimeOrDist. 317 */ 318 public byte getSwBTimeOrDist() 319 { 320 return swBTimeOrDist; 321 } 322 323 /** 324 * @param swBTimeOrDist The swBTimeOrDist to set. 325 */ 326 public void setSwBTimeOrDist(byte swBTimeOrDist) 327 { 328 this.swBTimeOrDist = swBTimeOrDist; 329 } 330 331 /** 332 * @return Returns the swCDist. 333 */ 334 public int getSwCDist() 335 { 336 return swCDist; 337 } 338 339 /** 340 * @param swCDist The swCDist to set. 341 */ 342 public void setSwCDist(int swCDist) 343 { 344 this.swCDist = swCDist; 345 } 346 347 /** 348 * @return Returns the swCTime. 349 */ 350 public int getSwCTime() 351 { 352 return swCTime; 353 } 354 355 /** 356 * @param swCTime The swCTime to set. 357 */ 358 public void setSwCTime(int swCTime) 359 { 360 this.swCTime = swCTime; 361 } 362 363 /** 364 * @return Returns the swCTimeOrDist. 365 */ 366 public byte getSwCTimeOrDist() 367 { 368 return swCTimeOrDist; 369 } 370 371 /** 372 * @param swCTimeOrDist The swCTimeOrDist to set. 373 */ 374 public void setSwCTimeOrDist(byte swCTimeOrDist) 375 { 376 this.swCTimeOrDist = swCTimeOrDist; 377 } 378 379 /** 380 * @return Returns the unk1. 381 */ 382 public short getUnk1() 383 { 384 return unk1; 385 } 386 387 /** 388 * @param unk1 The unk1 to set. 389 */ 390 public void setUnk1(short unk1) 391 { 392 this.unk1 = unk1; 393 } 394 395 /** 396 * @return Returns the unk2. 397 */ 398 public byte getUnk2() 399 { 400 return unk2; 401 } 402 403 /** 404 * @param unk2 The unk2 to set. 405 */ 406 public void setUnk2(byte unk2) 407 { 408 this.unk2 = unk2; 409 } 410 411 /** 412 * @return Returns the remainder. 413 */ 414 public int getRemainder() 415 { 416 return remainder; 417 } 418 419 /** 420 * @return Returns the unk3. 421 */ 422 public int getUnk3() 423 { 424 return unk3; 425 } 426 427 /** 428 * @return Returns the unk4. 429 */ 430 public int getUnk4() 431 { 432 return unk4; 433 } 434 435 public void writeProps(String fName) 436 throws Exception 437 { 438 Properties props = new Properties(); 439 props.setProperty(propLogFormat, "" + logFormat); 440 props.setProperty(propDisableLogSpeed, "" + disableLogSpeed); 441 props.setProperty(propSpeedThres, "" + speedThres); 442 props.setProperty(propDisableLogDist, "" + disableLogDist); 443 props.setProperty(propDistThres, "" + distThres); 444 props.setProperty(propSwATime, "" + swATime); 445 props.setProperty(propSwBTime, "" + swBTime); 446 props.setProperty(propSwCTime, "" + swCTime); 447 props.setProperty(propUnk1, "" + unk1); 448 props.setProperty(propSwATimeOrDist, "" + swATimeOrDist); 449 props.setProperty(propSwBTimeOrDist, "" + swBTimeOrDist); 450 props.setProperty(propSwCTimeOrDist, "" + swCTimeOrDist); 451 props.setProperty(propSwADist, "" + swADist); 452 props.setProperty(propSwBDist, "" + swBDist); 453 props.setProperty(propSwCDist, "" + swCDist); 454 props.setProperty(propUnk2, "" + unk2); 455 props.setProperty(propRemainder, "" + remainder); 456 props.setProperty(propUnk3, "" + unk3); 457 props.setProperty(propUnk4, "" + unk4); 458 OutputStream os = null; 459 try 460 { 461 os = new FileOutputStream(fName); 462 props.store(os, "dg100 config"); 463 } 464 catch (Exception ex) 465 { 466 ex.printStackTrace(); 467 throw ex; 468 } 469 finally 470 { 471 if (os != null) {os.close();} 472 } 473 } 474 475 public void readProps(String fName) 476 throws Exception 477 { 478 Properties props = new Properties(); 479 InputStream is = null; 480 try 481 { 482 is = new FileInputStream(fName); 483 props.load(is); 484 } 485 catch (Exception ex) 486 { 487 ex.printStackTrace(); 488 throw ex; 489 } 490 finally 491 { 492 if (is != null) {is.close();} 493 } 494 logFormat = Byte.parseByte(props.getProperty(propLogFormat, "2")); 495 disableLogSpeed = Byte.parseByte(props.getProperty(propDisableLogSpeed, "0")); 496 speedThres = Integer.parseInt(props.getProperty(propSpeedThres, "0")); 497 disableLogDist = Byte.parseByte(props.getProperty(propDisableLogDist, "0")); 498 distThres = Integer.parseInt(props.getProperty(propDistThres, "0")); 499 swATime = Integer.parseInt(props.getProperty(propSwATime, "1000")); 500 swBTime = Integer.parseInt(props.getProperty(propSwBTime, "1000")); 501 swCTime = Integer.parseInt(props.getProperty(propSwCTime, "1000")); 502 swATimeOrDist = Byte.parseByte(props.getProperty(propSwATimeOrDist, "0")); 503 swBTimeOrDist = Byte.parseByte(props.getProperty(propSwBTimeOrDist, "0")); 504 swCTimeOrDist = Byte.parseByte(props.getProperty(propSwCTimeOrDist, "0")); 505 swADist = Integer.parseInt(props.getProperty(propSwADist, "0")); 506 swBDist = Integer.parseInt(props.getProperty(propSwBDist, "0")); 507 swCDist = Integer.parseInt(props.getProperty(propSwCDist, "0")); 508 unk1 = Short.parseShort(props.getProperty(propUnk1, "0")); 509 unk2 = Byte.parseByte(props.getProperty(propUnk2, "0")); 510 unk3 = Integer.parseInt(props.getProperty(propUnk3, "0")); 511 unk4 = Integer.parseInt(props.getProperty(propUnk4, "0")); 512 } 513 513 514 514 } -
applications/editors/josm/plugins/globalsat/src/org/kaintoch/gps/globalsat/dg100/FileInfoRec.java
r10378 r12778 13 13 public class FileInfoRec 14 14 { 15 private int timeZ = 0; 16 private int date = 0; 17 private int idx = 0; 18 19 public FileInfoRec(ByteBuffer buf) 20 { 21 timeZ = buf.getInt(); 22 date = buf.getInt(); 23 idx = buf.getInt(); 24 } 25 26 public String toString() 27 { 28 return "[FileInfoRec: timeZ = " + timeZ + ", date = " + date + ", idx = " + idx + "]"; 29 } 15 private int timeZ = 0; 16 private int date = 0; 17 private int idx = 0; 30 18 31 /** 32 * @return Returns the idx. 33 */ 34 public int getIdx() 35 { 36 return idx; 37 } 19 public FileInfoRec(ByteBuffer buf) 20 { 21 timeZ = buf.getInt(); 22 date = buf.getInt(); 23 idx = buf.getInt(); 24 } 25 26 public String toString() 27 { 28 return "[FileInfoRec: timeZ = " + timeZ + ", date = " + date + ", idx = " + idx + "]"; 29 } 30 31 /** 32 * @return Returns the idx. 33 */ 34 public int getIdx() 35 { 36 return idx; 37 } 38 38 } -
applications/editors/josm/plugins/globalsat/src/org/kaintoch/gps/globalsat/dg100/GpsRec.java
r12588 r12778 22 22 // ff ff ff ff: dg100Altitude (m): alt * 10000 23 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 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 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 24 private int dg100Latitude = -1; 25 private int dg100Longitude = -1; 26 private int dg100TimeZ = -1; 27 private int dg100Date = -1; 28 private int dg100Speed = -1; 29 private int dg100Altitude = -1; 30 private int dg100Unk1 = -1; 31 private int dg100TypeOfCurRec = -1; 32 private int dg100TypeOfNextRec = -1; 33 // calculated data 34 private Calendar dateTime = null; 35 36 public GpsRec() 37 { 38 dg100TypeOfNextRec = 2; 39 dg100TypeOfCurRec = 2; 40 dg100Latitude = 0; 41 dg100Longitude = 0; 42 dg100TimeZ = 0; 43 dg100Date = 0; 44 dg100Speed = 0; 45 dg100Altitude = 0; 46 dg100Unk1 = -1; 47 dateTime = null; 48 } 49 50 public void copy(GpsRec init) 51 { 52 dg100TypeOfNextRec = init.dg100TypeOfNextRec; 53 dg100TypeOfCurRec = init.dg100TypeOfCurRec; 54 dg100Latitude = init.dg100Latitude; 55 dg100Longitude = init.dg100Longitude; 56 dg100TimeZ = init.dg100TimeZ; 57 dg100Date = init.dg100Date; 58 dg100Speed = init.dg100Speed; 59 dg100Altitude = init.dg100Altitude; 60 dg100Unk1 = init.dg100Unk1; 61 dateTime = init.dateTime; 62 } 63 64 public GpsRec(GpsRec init) 65 { 66 copy(init); 67 } 68 69 /** 70 * @see java.lang.Object#equals(java.lang.Object) 71 */ 72 public boolean equals(Object arg0) 73 { 74 boolean isEqual = false; 75 if (arg0 != null && arg0 instanceof GpsRec) 76 { 77 GpsRec otherGpsRec = (GpsRec)arg0; 78 isEqual = 79 dg100TypeOfNextRec == otherGpsRec.dg100TypeOfNextRec 80 && dg100TypeOfCurRec == otherGpsRec.dg100TypeOfCurRec 81 && dg100Latitude == otherGpsRec.dg100Latitude 82 && dg100Longitude == otherGpsRec.dg100Longitude 83 && dg100TimeZ == otherGpsRec.dg100TimeZ 84 && dg100Date == otherGpsRec.dg100Date 85 && dg100Speed == otherGpsRec.dg100Speed 86 && dg100Altitude == otherGpsRec.dg100Altitude 87 //&& dg100Unk1 == otherGpsRec.unk1 88 ; 89 } 90 return isEqual; 91 } 92 93 public GpsRec(ByteBuffer buf, int recType) 94 { 95 dg100Latitude = buf.getInt(); 96 dg100Longitude = buf.getInt(); 97 dg100TypeOfNextRec = recType; 98 dg100TypeOfCurRec = recType; 99 dateTime = null; 100 if (dg100TypeOfNextRec >= 1) 101 { 102 dg100TimeZ = buf.getInt(); 103 dg100Date = buf.getInt(); 104 calcDateTime(); 105 dg100Speed = buf.getInt(); 106 if (dg100TypeOfNextRec >= 1) 107 { 108 dg100Altitude = buf.getInt(); 109 dg100Unk1 = buf.getInt(); 110 dg100TypeOfNextRec = buf.getInt(); 111 } 112 } 113 } 114 115 /** 116 * Shows wether this is a valid GPS record. 117 * @return true if GPS record is valid; otherwise false. 118 */ 119 public boolean isValid() 120 { 121 return 122 dg100Latitude <= 360000000 123 && dg100Latitude >= 0 124 && dg100Longitude <= 360000000 125 && dg100Longitude >= 0 126 && dg100TimeZ >= 0 127 && dg100TimeZ <= 240000 128 && dg100Unk1 >= 0 129 && dg100Unk1 <= 1 130 ; 131 } 132 133 public int getDg100TypeOfNextRec() 134 { 135 return dg100TypeOfNextRec; 136 } 137 138 public int getDg100TypeOfCurRec() 139 { 140 return dg100TypeOfCurRec; 141 } 142 143 public String toString() 144 { 145 return "[GpsRec: " 146 + " Lat = " + dg100Latitude 147 + ", Long = " + dg100Longitude 148 + ", TimeZ = " + dg100TimeZ 149 + ", Date = " + dg100Date 150 + ", Speed = " + dg100Speed 151 + ", Alt = " + dg100Altitude 152 + ", Unk1 = " + dg100Unk1 153 + ", TypeOfCurRec = " + dg100TypeOfCurRec 154 + ", TypeOfNextRec = " + dg100TypeOfNextRec 155 + "]"; 156 } 157 158 /** 159 * @return Returns the dg100Latitude. 160 */ 161 public int getDg100Latitude() 162 { 163 return dg100Latitude; 164 } 165 166 /** 167 * Converts this object to its GPX representation. 168 * @return this object's GPX representation as a String. 169 */ 170 public String toGpxTrkpt() 171 { 172 // <trkpt lat="47.6972383333" lon="11.4178650000"> 173 // <ele>662.0000000000</ele> 174 // <time>2007-04-21T13:56:05Z</time> 175 // <dg100Speed>1.0833333333</dg100Speed> 176 // </trkpt> 177 StringBuffer buf = new StringBuffer(500); 178 buf.append("<trkpt"); 179 buf.append(" lat=\"").append(getLatitude()).append("\""); 180 buf.append(" lon=\"").append(getLongitude()).append("\""); 181 buf.append(">"); 182 if (dg100TypeOfCurRec > 0) 183 { 184 if (dg100TypeOfCurRec > 1) 185 { 186 buf.append("<ele>").append(getAltitude()).append("</ele>"); 187 } 188 buf.append("<time>").append(getStringZuluTime()).append("</time>"); 189 buf.append("<speed>").append(getSpeed()).append("</speed>"); 190 } 191 buf.append("</trkpt>"); 192 return buf.toString(); 193 } 194 195 /** 196 * Converts this object to its GPX waypoint representation. 197 * @return this object's GPX representation as a String. 198 */ 199 public String toGpxWpt() 200 { 201 // <wpt lat="47.6972383333" lon="11.4178650000"> 202 // <ele>662.0000000000</ele> 203 // <time>2007-04-21T13:56:05Z</time> 204 // </wpt> 205 StringBuffer buf = new StringBuffer(500); 206 buf.append("<wpt"); 207 buf.append(" lat=\"").append(getLatitude()).append("\""); 208 buf.append(" lon=\"").append(getLongitude()).append("\""); 209 buf.append(">"); 210 if (dg100TypeOfCurRec > 0) 211 { 212 if (dg100TypeOfCurRec > 1) 213 { 214 buf.append("<ele>").append(getAltitude()).append("</ele>"); 215 } 216 buf.append("<time>").append(getStringZuluTime()).append("</time>"); 217 } 218 buf.append("</wpt>"); 219 return buf.toString(); 220 } 221 222 /** 223 * Converts GlobalSat dg100Latitude and dg100Longitude internal format to degrees. 224 * @param gsLatOrLon 225 * @return nodeg in degrees 226 */ 227 private double toDegree(int gsLatOrLon) 228 { 229 int scale = 1000000; 230 double deg = 9999.9999; 231 double degScaled = (double)(gsLatOrLon / scale); 232 double minScaled = ((double)(gsLatOrLon - degScaled * scale)) / 600000.0; 233 deg = degScaled + minScaled; 234 return deg; 235 } 236 237 /** 238 * Gets dg100Date and time as a String in GPX dg100Date-time-format (aka zulu time). 239 * @return a dg100Date-time-string in GPX dg100Date-time-format (aka zulu time). 240 */ 241 public String getStringZuluTime() 242 { 243 return getStringDateTime("yyyy-MM-dd'T'HH:mm:ss'Z'"); 244 } 245 246 /** 247 * Gets dg100Date and time as a String in format "yyyyMMddHHmmss". 248 * @return a dg100Date-time-string in format "yyyyMMddHHmmss". 249 */ 250 public String getStringDateTime() 251 { 252 return getStringDateTime("yyyyMMddHHmmss"); 253 } 254 255 /** 256 * Gets dg100Date and time as a String in given format. 257 * @param dateTimeFormat 258 * @return 259 */ 260 private String getStringDateTime(String dateTimeFormat) 261 { 262 String dateTimeString = "???"; 263 if (dateTime != null) 264 { 265 SimpleDateFormat sdf = new SimpleDateFormat(dateTimeFormat); 266 //logger.info(gsTime + " " + gsDate); 267 dateTimeString = sdf.format(dateTime.getTime()); 268 } 269 return dateTimeString; 270 } 271 272 /** 273 * @return Returns the dg100Altitude. 274 */ 275 public int getDg100Altitude() 276 { 277 return dg100Altitude; 278 } 279 280 /** 281 * @param dg100Altitude The dg100Altitude to set. 282 */ 283 private void setDg100Altitude(int altitude) 284 { 285 this.dg100Altitude = altitude; 286 } 287 288 /** 289 * @return Returns the dg100Date. 290 */ 291 public int getDg100Date() 292 { 293 return dg100Date; 294 } 295 296 /** 297 * @param dg100Date The dg100Date to set. 298 */ 299 private void setDg100Date(int date) 300 { 301 this.dg100Date = date; 302 calcDateTime(); 303 } 304 305 /** 306 * @return 307 */ 308 private void calcDateTime() 309 { 310 int hh = dg100TimeZ / 10000; 311 int mm = (dg100TimeZ - hh * 10000) / 100; 312 int ss = dg100TimeZ - hh * 10000 - mm * 100; 313 int DD = dg100Date / 10000; 314 int MM = (dg100Date - DD * 10000) / 100; 315 int YY = dg100Date - DD * 10000 - MM * 100; 316 dateTime = GregorianCalendar.getInstance(); 317 dateTime.set(2000 + YY, MM, DD, hh, mm, ss); 318 } 319 320 /** 321 * @return Returns the dg100Longitude. 322 */ 323 public int getDg100Longitude() 324 { 325 return dg100Longitude; 326 } 327 328 /** 329 * @param dg100Longitude The dg100Longitude to set. 330 */ 331 private void setDg100Longitude(int longitude) 332 { 333 this.dg100Longitude = longitude; 334 } 335 336 /** 337 * @return Returns the dg100Speed. 338 */ 339 public int getDg100Speed() 340 { 341 return dg100Speed; 342 } 343 344 /** 345 * @param dg100Speed The dg100Speed to set. 346 */ 347 private void setDg100Speed(int speed) 348 { 349 this.dg100Speed = speed; 350 } 351 352 /** 353 * @return Returns the dg100TimeZ. 354 */ 355 public int getDg100TimeZ() 356 { 357 return dg100TimeZ; 358 } 359 360 /** 361 * @param dg100TimeZ The dg100TimeZ to set. 362 */ 363 private void setDg100TimeZ(int timeZ) 364 { 365 this.dg100TimeZ = timeZ; 366 calcDateTime(); 367 } 368 369 /** 370 * @param dg100Latitude The dg100Latitude to set. 371 */ 372 private void setDg100Latitude(int latitude) 373 { 374 this.dg100Latitude = latitude; 375 } 376 377 public void updateMin(GpsRec next) 378 { 379 if (next != null) 380 { 381 if (next.getDg100Latitude() < getDg100Latitude()) {setDg100Latitude(next.getDg100Latitude());} 382 if (next.getDg100Longitude() < getDg100Longitude()) {setDg100Longitude(next.getDg100Longitude());} 383 if (next.getDg100Altitude() < getDg100Altitude()) {setDg100Altitude(next.getDg100Altitude());} 384 if (next.getDg100Date() < getDg100Date() 385 || (next.getDg100Date() == getDg100Date() && next.getDg100TimeZ() < getDg100TimeZ()) 386 ) 387 { 388 setDg100Date(next.getDg100Date()); 389 setDg100TimeZ(next.getDg100TimeZ()); 390 } 391 if (next.getDg100Speed() < getDg100Speed()) {setDg100Speed(next.getDg100Speed());} 392 } 393 } 394 395 public void updateMax(GpsRec next) 396 { 397 if (next != null) 398 { 399 if (next.getDg100Latitude() > getDg100Latitude()) {setDg100Latitude(next.getDg100Latitude());} 400 if (next.getDg100Longitude() > getDg100Longitude()) {setDg100Longitude(next.getDg100Longitude());} 401 if (next.getDg100Altitude() > getDg100Altitude()) {setDg100Altitude(next.getDg100Altitude());} 402 if (next.getDg100Date() > getDg100Date() 403 || (next.getDg100Date() == getDg100Date() && next.getDg100TimeZ() > getDg100TimeZ()) 404 ) 405 { 406 setDg100Date(next.getDg100Date()); 407 setDg100TimeZ(next.getDg100TimeZ()); 408 } 409 if (next.getDg100Speed() > getDg100Speed()) {setDg100Speed(next.getDg100Speed());} 410 } 411 } 412 413 /** 414 * @return Returns the dateTime. 415 */ 416 public Calendar getDateTime() 417 { 418 return dateTime; 419 } 420 421 public double getLatitude() 422 { 423 return toDegree(dg100Latitude); 424 } 425 426 public double getLongitude() 427 { 428 return toDegree(dg100Longitude); 429 } 430 431 public double getAltitude() 432 { 433 return dg100Altitude / (double)10000.0; 434 } 435 436 public double getSpeed() 437 { 438 return dg100Speed / (double)360.0; 439 } 440 440 441 441 } -
applications/editors/josm/plugins/globalsat/src/org/kaintoch/gps/globalsat/dg100/Response.java
r10378 r12778 14 14 public class Response 15 15 { 16 17 18 19 16 final static public byte typeFileInfo = (byte)0xBB; 17 final static public byte typeId = (byte)0xBF; 18 final static public byte typeGpsRec = (byte)0xB5; 19 final static public byte typeConfig = (byte)0xB7; 20 20 21 private int typeOfResponse = 0; 22 private int cntDataCur = 0; 23 private int nextIdx = 0; 24 private Dg100Config config = null; 25 private List data = new ArrayList(100); 26 private long id = 0; 27 28 private Response(int typeOfResponse) 29 { 30 this.typeOfResponse = typeOfResponse; 31 } 21 private int typeOfResponse = 0; 22 private int cntDataCur = 0; 23 private int nextIdx = 0; 24 private Dg100Config config = null; 25 private List data = new ArrayList(100); 26 private long id = 0; 32 27 33 /** 34 * 35 * @param resp 36 */ 37 static public Response parseResponse(byte resp[], int len) 38 { 39 ByteBuffer buf = ByteBuffer.wrap(resp); 40 byte respType = buf.get(4); 41 Response response = new Response(respType); 42 buf.position(5); 43 if (respType == typeFileInfo) // file info 44 { 45 int cntInfoCur = buf.getShort(); 46 int nextIdx = buf.getShort(); 47 response.cntDataCur = cntInfoCur; 48 response.nextIdx = nextIdx; 49 for (int ii = 0 ; ii < cntInfoCur ; ++ii) 50 { 51 FileInfoRec fileInfoRec = new FileInfoRec(buf); 52 response.addRec(fileInfoRec); 53 } 54 } 55 else if (respType == typeGpsRec) // gps recs 56 { 57 int recType = 2; 58 int ii = 0; 59 // read part 1 60 while (buf.position() <= len) 61 { 62 GpsRec gpsRec = new GpsRec(buf, recType); 63 if (gpsRec.isValid() && buf.position() <= len) 64 { 65 response.addRec(gpsRec); 66 } 67 else 68 { 69 break; 70 } 71 recType = gpsRec.getDg100TypeOfNextRec(); 72 ++ii; 73 } 74 // read part 2 75 buf.position(1042); 76 while (buf.position() <= len) 77 { 78 GpsRec gpsRec = new GpsRec(buf, recType); 79 if (gpsRec.isValid() && buf.position() <= len) 80 { 81 response.addRec(gpsRec); 82 } 83 else 84 { 85 break; 86 } 87 recType = gpsRec.getDg100TypeOfNextRec(); 88 ++ii; 89 } 90 } 91 else if (respType == typeConfig) // config 92 { 93 Dg100Config config = new Dg100Config(buf); 94 response.config = config; 95 } 96 else if (respType == typeId) // id 97 { 98 response.id = 0; 99 for (int ii = 0 ; ii < 8 ; ++ii) 100 { 101 int digit = (int)buf.get(); 102 response.id = response.id * 10 + digit; 103 } 104 } 105 else 106 { 107 } 108 return response; 109 } 28 private Response(int typeOfResponse) 29 { 30 this.typeOfResponse = typeOfResponse; 31 } 110 32 111 private void addRec(Object obj) 112 { 113 data.add(obj); 114 } 33 /** 34 * 35 * @param resp 36 */ 37 static public Response parseResponse(byte resp[], int len) 38 { 39 ByteBuffer buf = ByteBuffer.wrap(resp); 40 byte respType = buf.get(4); 41 Response response = new Response(respType); 42 buf.position(5); 43 if (respType == typeFileInfo) // file info 44 { 45 int cntInfoCur = buf.getShort(); 46 int nextIdx = buf.getShort(); 47 response.cntDataCur = cntInfoCur; 48 response.nextIdx = nextIdx; 49 for (int ii = 0 ; ii < cntInfoCur ; ++ii) 50 { 51 FileInfoRec fileInfoRec = new FileInfoRec(buf); 52 response.addRec(fileInfoRec); 53 } 54 } 55 else if (respType == typeGpsRec) // gps recs 56 { 57 int recType = 2; 58 int ii = 0; 59 // read part 1 60 while (buf.position() <= len) 61 { 62 GpsRec gpsRec = new GpsRec(buf, recType); 63 if (gpsRec.isValid() && buf.position() <= len) 64 { 65 response.addRec(gpsRec); 66 } 67 else 68 { 69 break; 70 } 71 recType = gpsRec.getDg100TypeOfNextRec(); 72 ++ii; 73 } 74 // read part 2 75 buf.position(1042); 76 while (buf.position() <= len) 77 { 78 GpsRec gpsRec = new GpsRec(buf, recType); 79 if (gpsRec.isValid() && buf.position() <= len) 80 { 81 response.addRec(gpsRec); 82 } 83 else 84 { 85 break; 86 } 87 recType = gpsRec.getDg100TypeOfNextRec(); 88 ++ii; 89 } 90 } 91 else if (respType == typeConfig) // config 92 { 93 Dg100Config config = new Dg100Config(buf); 94 response.config = config; 95 } 96 else if (respType == typeId) // id 97 { 98 response.id = 0; 99 for (int ii = 0 ; ii < 8 ; ++ii) 100 { 101 int digit = (int)buf.get(); 102 response.id = response.id * 10 + digit; 103 } 104 } 105 else 106 { 107 } 108 return response; 109 } 115 110 116 public List getRecs()117 118 return data;119 111 private void addRec(Object obj) 112 { 113 data.add(obj); 114 } 120 115 121 /** 122 * @return Returns the cntDataCur. 123 */ 124 public int getCntDataCur() 125 { 126 return cntDataCur; 127 } 116 public List getRecs() 117 { 118 return data; 119 } 128 120 129 130 * @return Returns the nextIdx.131 132 public int getNextIdx()133 134 return nextIdx;135 121 /** 122 * @return Returns the cntDataCur. 123 */ 124 public int getCntDataCur() 125 { 126 return cntDataCur; 127 } 136 128 137 138 * @return Returns the typeOfResponse.139 140 public int getTypeOfResponse()141 142 return typeOfResponse;143 129 /** 130 * @return Returns the nextIdx. 131 */ 132 public int getNextIdx() 133 { 134 return nextIdx; 135 } 144 136 145 146 * @return Returns the config.147 148 public Dg100Config getConfig()149 150 return config;151 137 /** 138 * @return Returns the typeOfResponse. 139 */ 140 public int getTypeOfResponse() 141 { 142 return typeOfResponse; 143 } 152 144 153 /** 154 * @return Returns the id. 155 */ 156 public long getId() 157 { 158 return id; 159 } 145 /** 146 * @return Returns the config. 147 */ 148 public Dg100Config getConfig() 149 { 150 return config; 151 } 152 153 /** 154 * @return Returns the id. 155 */ 156 public long getId() 157 { 158 return id; 159 } 160 160 161 161 } -
applications/editors/josm/plugins/globalsat/src/org/openstreetmap/josm/plugins/globalsat/GlobalsatConfigDialog.java
r11555 r12778 50 50 /** 51 51 * Configuration download dialog. 52 * 52 * 53 53 * @author Raphael Mack <ramack@raphael-mack.de> 54 54 * … … 58 58 59 59 public class IntegerTextField extends JTextField { 60 60 61 61 final static String badchars = "-`~!@#$%^&*()_+=\\|\"':;?/>.<, "; 62 62 63 63 public void processKeyEvent(KeyEvent ev) { 64 64 65 65 char c = ev.getKeyChar(); 66 if((Character.isLetter(c) && !ev.isAltDown()) 66 if((Character.isLetter(c) && !ev.isAltDown()) 67 67 || badchars.indexOf(c) > -1) { 68 68 ev.consume(); … … 74 74 75 75 76 76 77 77 // the JOptionPane that contains this dialog. required for the closeDialog() method. 78 78 private JOptionPane optionPane; … … 103 103 104 104 private List<CommPortIdentifier> ports = new LinkedList<CommPortIdentifier>(); 105 105 106 106 private Dg100Config conf; 107 107 … … 132 132 logFormat.add(formatPosTDS); 133 133 logFormat.add(formatPosTDSA); 134 134 135 135 JPanel logPanel = new JPanel(); 136 136 logPanel.setLayout(new BoxLayout(logPanel, BoxLayout.PAGE_AXIS)); … … 209 209 minLogSpeed.setText("" + conf.getSpeedThres()); 210 210 minLogDist.setText("" + conf.getDistThres()); 211 211 212 212 ButtonGroup group = new ButtonGroup(); 213 213 group.add(aTime); … … 261 261 c.gridy = 6; 262 262 add(bMeters, c); 263 263 264 264 group = new ButtonGroup(); 265 265 group.add(cTime); 266 266 group.add(cDist); 267 267 268 268 c.insets = new Insets(4,4,0,4); 269 269 c.gridwidth = 1; … … 307 307 JOptionPane.showMessageDialog(Main.parent, tr("Unknown logFormat")); 308 308 } 309 309 310 310 if(conf.getSwATimeOrDist() == 0){ 311 311 aTime.setSelected(true); -
applications/editors/josm/plugins/globalsat/src/org/openstreetmap/josm/plugins/globalsat/GlobalsatDg100.java
r11555 r12778 45 45 46 46 public static final int TIMEOUT = 2000; 47 public static final int TRACK_TYPE = 1; 48 47 public static final int TRACK_TYPE = 1; 48 49 49 /** delete file: A0 A2 00 02 BC 01 00 BD B0 B3 */ 50 50 private static byte dg100CmdSwitch2Nmea[] = … … 111 111 , (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00 112 112 , (byte) 0x00, (byte) 0xC0, (byte) 0xB0, (byte) 0xB3}; 113 113 114 114 private byte[] response = new byte[65536]; 115 115 116 116 private CommPortIdentifier portIdentifier; 117 117 private SerialPort port = null; 118 118 119 119 private boolean cancelled = false; 120 120 121 121 public GlobalsatDg100(CommPortIdentifier portId){ 122 122 this.portIdentifier = portId; … … 178 178 return result; 179 179 } 180 180 181 181 public void deleteData() throws ConnectionException{ 182 182 if(port == null){ … … 189 189 } 190 190 } 191 191 192 192 public void disconnect(){ 193 193 if(port != null){ … … 210 210 } 211 211 } 212 212 213 213 private List<FileInfoRec> readFileInfoList() throws ConnectionException 214 214 { … … 226 226 } 227 227 } 228 228 229 229 public List<GpsRec> readGpsRecList(List<FileInfoRec> fileInfoList) throws ConnectionException 230 230 { 231 231 int cnt = 0; 232 232 List<GpsRec> result = new ArrayList<GpsRec>(200); 233 233 234 234 try{ 235 235 for(FileInfoRec fileInfoRec:fileInfoList){ … … 243 243 } 244 244 } 245 245 246 246 private Response sendCmdDelFiles() throws IOException, UnsupportedCommOperationException 247 247 { … … 317 317 return Response.parseResponse(response, len); 318 318 } 319 319 320 320 /** 321 321 * … … 348 348 } 349 349 350 350 351 351 private int readResponse(byte[] response, int bytesToRead) throws IOException, UnsupportedCommOperationException 352 352 { … … 396 396 } 397 397 return ((cntBytTot > bytesToRead) ? bytesToRead : cntBytTot); 398 398 } 399 399 return -1; 400 400 } -
applications/editors/josm/plugins/globalsat/src/org/openstreetmap/josm/plugins/globalsat/GlobalsatImportDialog.java
r11555 r12778 39 39 /** 40 40 * Main download dialog. 41 * 41 * 42 42 * @author Raphael Mack <ramack@raphael-mack.de> 43 43 * 44 44 */ 45 45 public class GlobalsatImportDialog extends JPanel { 46 46 47 47 // the JOptionPane that contains this dialog. required for the closeDialog() method. 48 48 private JOptionPane optionPane; … … 111 111 System.out.println("configureing the device"); 112 112 try{ 113 113 114 114 GlobalsatConfigDialog dialog = new GlobalsatConfigDialog(GlobalsatPlugin.dg100().getConfig()); 115 115 JOptionPane pane = new JOptionPane(dialog, JOptionPane.PLAIN_MESSAGE, JOptionPane.OK_CANCEL_OPTION); … … 136 136 add(configBtn, c); 137 137 138 138 139 139 delete = new JCheckBox(tr("delete data after import")); 140 140 delete.setSelected(Main.pref.getBoolean("globalsat.deleteAfterDownload", false)); … … 167 167 168 168 } 169 169 170 170 public boolean deleteFilesAfterDownload(){ 171 171 return delete.isSelected(); -
applications/editors/josm/plugins/globalsat/src/org/openstreetmap/josm/plugins/globalsat/GlobalsatPlugin.java
r12707 r12778 106 106 } 107 107 } 108 108 109 109 class GlobalsatImportAction extends JosmAction{ 110 110 public GlobalsatImportAction(){ -
applications/editors/josm/plugins/grid/src/grid/GridLayer.java
r1544 r12778 45 45 */ 46 46 public class GridLayer extends Layer { 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 System.out.println(new LatLon(10,10) + "->" + 79 gridtoworld.transform(new LatLon(10,10)) + "->" + 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 Object[] options = new Object[]{tr("OK"), tr("Cancel"), tr("World")}; 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 47 48 private static Icon icon = new ImageIcon(Toolkit.getDefaultToolkit().createImage(GridPlugin.class.getResource("/images/grid.png"))); 49 private LatLon origin, pole; 50 private float gridunits; 51 private boolean drawLabels; 52 private Helmert gridtoworld; //worldtogrid; 53 private Color majcol = Color.RED; 54 public double a, b, c; 55 public GridLayer(String url) { 56 super(url.indexOf('/') != -1 ? url.substring(url.indexOf('/')+1) : url); 57 origin = new LatLon(0.0,0.0); 58 pole = new LatLon(0.0,90.0); 59 drawLabels = true; 60 gridtoworld = new Helmert(0.0, 0.0, 0); 61 //worldtogrid = new Helmert(0.0, 0.0, 0); 62 } 63 64 // private void setGrid(LatLon origin, LatLon pole){ 65 // this.origin = origin; 66 // this.pole = pole; 67 //need to check pole is perpendicular from origin; 68 // } 69 private void setGrid(double a, double b, double c){ 70 System.out.println("Setting grid to :" + a + ", " + b + ", " + c); 71 this.origin = origin; 72 this.pole = pole; 73 //need to chech pole is perpendicular from origin; 74 this.a=a; 75 this.b=b; 76 this.c=c; 77 gridtoworld = new Helmert(a, b, c); 78 System.out.println(new LatLon(10,10) + "->" + 79 gridtoworld.transform(new LatLon(10,10)) + "->" + 80 gridtoworld.inverseTransform(gridtoworld.transform(new LatLon(10,10)))); 81 //worldtogrid = new Helmert(-a, -b, -c); 82 } 83 84 private void setUnits(float units){ 85 gridunits = units; 86 } 87 88 private void setUnitsToLatLon(){ 89 gridunits = 0; 90 } 91 92 93 private void toggleLabels(){ 94 drawLabels=!drawLabels; 95 } 96 97 private class toggleLabelsAction extends AbstractAction { 98 GridLayer layer; 99 public toggleLabelsAction(GridLayer layer) { 100 super("show labels"); 101 this.layer = layer; 102 } 103 public void actionPerformed(ActionEvent e) { 104 layer.toggleLabels(); 105 Main.map.repaint(); 106 } 107 } 108 109 private class setWorldAction extends AbstractAction { 110 GridLayer layer; 111 public setWorldAction(GridLayer layer) { 112 super("set to world"); 113 this.layer = layer; 114 } 115 public void actionPerformed(ActionEvent e) { 116 layer.setGrid(0,0,0); 117 Main.map.repaint(); 118 } 119 } 120 private class incAAction extends AbstractAction { 121 GridLayer layer; 122 public incAAction(GridLayer layer) { 123 super("increase a"); 124 this.layer = layer; 125 } 126 public void actionPerformed(ActionEvent e) { 127 layer.setGrid(layer.a+10,layer.b,layer.c); 128 Main.map.repaint(); 129 } 130 } 131 private class incBAction extends AbstractAction { 132 GridLayer layer; 133 public incBAction(GridLayer layer) { 134 super("increase b"); 135 this.layer = layer; 136 } 137 public void actionPerformed(ActionEvent e) { 138 layer.setGrid(layer.a,layer.b+10,layer.c); 139 Main.map.repaint(); 140 } 141 } 142 private class incCAction extends AbstractAction { 143 GridLayer layer; 144 public incCAction(GridLayer layer) { 145 super("increase c"); 146 this.layer = layer; 147 } 148 public void actionPerformed(ActionEvent e) { 149 layer.setGrid(layer.a,layer.b,layer.c+10); 150 Main.map.repaint(); 151 } 152 } 153 private class setColorAction extends AbstractAction { 154 GridLayer layer; 155 public setColorAction(GridLayer layer) { 156 super("Customize Color", ImageProvider.get("colorchooser")); 157 this.layer = layer; 158 } 159 public void actionPerformed(ActionEvent e) { 160 String col=ColorHelper.color2html(layer.majcol); 161 JColorChooser c = new JColorChooser(ColorHelper.html2color(col)); 162 Object[] options = new Object[]{tr("OK"), tr("Cancel"), tr("Default")}; 163 int answer = JOptionPane.showOptionDialog(Main.parent, c, tr("Choose a color"), JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); 164 switch (answer) { 165 case 0: 166 // Main.pref.put("color.layer "+name, ColorHelper.color2html(c.getColor())); 167 majcol = c.getColor(); 168 break; 169 case 1: 170 return; 171 case 2: 172 // Main.pref.put("color.layer "+name, null); 173 majcol = Color.RED; 174 break; 175 } 176 Main.map.repaint(); 177 } 178 } 179 180 private class setGridLayoutAction extends AbstractAction { 181 GridLayer layer; 182 public setGridLayoutAction(GridLayer layer) { 183 super("Set grid origin"); 184 this.layer = layer; 185 } 186 public void actionPerformed(ActionEvent e) { 187 NumberFormat nf = NumberFormat.getInstance(); 188 JPanel p = new JPanel(new GridBagLayout()); 189 JTextField latText = new JTextField(nf.format(layer.a)); 190 JTextField lonText = new JTextField(nf.format(layer.b)); 191 JTextField devText = new JTextField(nf.format(layer.c)); 192 p.add(new JLabel(tr("Grid origin location")), GBC.eol()); 193 p.add(new JLabel(tr("Latitude"))); 194 p.add(latText, GBC.eol()); 195 p.add(new JLabel(tr("Longitude"))); 196 p.add(lonText, GBC.eol()); 197 p.add(new JLabel(tr("Grid rotation"))); 198 p.add(devText, GBC.eol()); 199 Object[] options = new Object[]{tr("OK"), tr("Cancel"), tr("World")}; 200 int answer = JOptionPane.showOptionDialog(Main.parent, p,tr("Grid layout"), JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); 201 switch (answer) { 202 case 0: 203 layer.setGrid( 204 -Double.parseDouble(latText.getText()), 205 -Double.parseDouble(lonText.getText()), 206 Double.parseDouble(devText.getText())); 207 208 case 1: 209 return; 210 case 2: 211 layer.setGrid(0,0,0); 212 } 213 Main.map.repaint(); 214 } 215 } 216 217 @Override public Icon getIcon() { 218 return icon; 219 } 220 221 @Override public String getToolTipText() { 222 return tr("Grid layer:" + a + "," + b + "," + c); 223 } 224 225 @Override public boolean isMergable(Layer other) { 226 return false; 227 } 228 229 @Override public void mergeFrom(Layer from) { 230 } 231 232 @Override public void paint(Graphics g, final MapView mv) { 233 //establish viewport size 234 int w = mv.getWidth(); 235 int h = mv.getHeight(); 236 237 //establish viewport world coordinates 238 238 LatLon tl = mv.getLatLon(0,0); 239 239 LatLon br = mv.getLatLon(w,h); 240 240 241 //establish max visible world coordinates 241 //establish max visible world coordinates 242 242 double wminlat = Math.max(Math.min(tl.lat(),br.lat()),-Main.proj.MAX_LAT); 243 243 double wmaxlat = Math.min(Math.max(tl.lat(),br.lat()), Main.proj.MAX_LAT); 244 244 double wminlon = Math.max(Math.min(tl.lon(),br.lon()),-Main.proj.MAX_LON); 245 245 double wmaxlon = Math.min(Math.max(tl.lon(),br.lon()), Main.proj.MAX_LON); 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 minlon=-180; 271 272 273 274 275 minlon=-180; 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 LatLon ll0, lli, llj; 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 int tw = fm.stringWidth(label); 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 246 247 //establish viewport grid coordinates 248 //because grid is arbitrarily orientated and may be curved check several points on border 249 double minlat = 180, maxlat=-180, minlon=90, maxlon=-90; 250 251 for(double x=0;x<=1;x+=0.2){ 252 LatLon[] p = new LatLon[] { 253 gridtoworld.inverseTransform(new LatLon(wminlat, x*wminlon+(1-x)*wmaxlon)), 254 gridtoworld.inverseTransform(new LatLon(wmaxlat, x*wminlon+(1-x)*wmaxlon)), 255 gridtoworld.inverseTransform(new LatLon(x*wminlat+(1-x)*wmaxlat, wminlon)), 256 gridtoworld.inverseTransform(new LatLon(x*wminlat+(1-x)*wmaxlat, wmaxlon))}; 257 for(int i=0;i<4;i++){ 258 maxlat=Math.max(p[i].lat(),maxlat); 259 minlat=Math.min(p[i].lat(),minlat); 260 maxlon=Math.max(p[i].lon(),maxlon); 261 minlon=Math.min(p[i].lon(),minlon); 262 } 263 } 264 265 //also check if the singularities are visible 266 LatLon northpole = gridtoworld.transform(new LatLon(90,0)); 267 LatLon southpole = gridtoworld.transform(new LatLon(-90,0)); 268 if((northpole.lat()>=wminlat) && (northpole.lat()<=wmaxlat) && (northpole.lon()>=wminlon) && (northpole.lon()<=wmaxlon)){ 269 maxlat=90; 270 minlon=-180; 271 maxlon=180; 272 } 273 if((southpole.lat()>=wminlat) && (southpole.lat()<=wmaxlat) && (southpole.lon()>=wminlon) && (southpole.lon()<=wmaxlon)){ 274 minlat=-90; 275 minlon=-180; 276 maxlon=180; 277 } 278 279 //span is maximum lat/lon span across visible grid normalised to 1600pixels 280 double latspan = (maxlat-minlat) * 1600.0/Math.max(h,w); 281 double lonspan = (maxlon-minlon) * 1600.0/Math.max(h,w); 282 283 //grid spacing is power of ten to use for grid interval. 284 double latspacing = Math.pow(10,Math.floor(Math.log(latspan)/Math.log(10.0))-1.0); 285 double lonspacing = Math.pow(10,Math.floor(Math.log(lonspan)/Math.log(10.0))-1.0); 286 if (Math.max(latspan,lonspan)/Math.min(latspan,lonspan)<4){ 287 lonspacing = latspacing = Math.max(latspacing,lonspacing); 288 } 289 double latmaj = (latspacing>=10)?3:10; 290 double lonmaj = (lonspacing>=10)?3:10; 291 292 //set up stuff need to draw grid 293 NumberFormat nf = NumberFormat.getInstance(); 294 Color mincol = (majcol.darker()).darker(); 295 296 g.setFont (new Font("Helvetica", Font.PLAIN, 8)); 297 FontMetrics fm = g.getFontMetrics(); 298 // g.setWidth(0); 299 for(double lat=latspacing*Math.floor(minlat/latspacing);lat<maxlat;lat+=latspacing){ 300 for(double lon=lonspacing*Math.floor(minlon/lonspacing);lon<maxlon;lon+=lonspacing){ 301 LatLon ll0, lli, llj; 302 ll0 = gridtoworld.transform(new LatLon(lat,lon)); 303 lli = gridtoworld.transform(new LatLon(lat+latspacing,lon)); 304 llj = gridtoworld.transform(new LatLon(lat,lon+lonspacing)); 305 Point p0=mv.getPoint(Main.proj.latlon2eastNorth(ll0)); 306 Point pi=mv.getPoint(Main.proj.latlon2eastNorth(lli)); 307 Point pj=mv.getPoint(Main.proj.latlon2eastNorth(llj)); 308 309 if(Math.round(lon/lonspacing)%lonmaj==0) 310 g.setColor(majcol); 311 else 312 g.setColor(mincol); 313 314 drawGridLine(g, mv, ll0, lli); 315 316 317 if(Math.round(lat/latspacing)%latmaj==0) 318 g.setColor(majcol); 319 else 320 g.setColor(mincol); 321 322 drawGridLine(g, mv, ll0, llj); 323 324 if((Math.round(lon/lonspacing))%lonmaj==0 && (Math.round(lat/latspacing))%latmaj==0 && drawLabels){ 325 String label = nf.format(lat); 326 int tw = fm.stringWidth(label); 327 g.drawString(label,p0.x-tw,p0.y-8); 328 label = nf.format(lon); 329 g.drawString(label,p0.x+2,p0.y+8); 330 } 331 } 332 } 333 334 } 335 336 private void drawGridLine(Graphics g, final MapView mv, LatLon ll0, LatLon ll1){ 337 Point p0=mv.getPoint(Main.proj.latlon2eastNorth(ll0)); 338 Point p1=mv.getPoint(Main.proj.latlon2eastNorth(ll1)); 339 340 if(Math.abs(ll0.lon()-ll1.lon())<180){ 341 g.drawLine(p0.x,p0.y,p1.x,p1.y); 342 } else { 343 double lat0, lat1, lon0, lon1, latm; 344 lon0 = ll0.lon(); 345 lon1 = ll1.lon(); 346 if(lon0<0) lon0+=360; 347 if(lon1<0) lon1+=360; 348 latm = ll0.lat() + (180-lon0)*(ll1.lat()-ll0.lat())/(lon1-lon0); 349 Point pm1 = mv.getPoint(Main.proj.latlon2eastNorth(new LatLon(latm,180))); 350 Point pm2 = mv.getPoint(Main.proj.latlon2eastNorth(new LatLon(latm,-180))); 351 if(lon0<=180){ 352 g.drawLine(p0.x,p0.y,pm1.x,pm1.y); 353 g.drawLine(p1.x,p1.y,pm2.x,pm2.y); 354 } else { 355 g.drawLine(p0.x,p0.y,pm2.x,pm2.y); 356 g.drawLine(p1.x,p1.y,pm1.x,pm1.y); 357 } 358 } 359 } 360 361 @Override public void visitBoundingBox(BoundingXYVisitor v) { 362 // doesn't have a bounding box 363 } 364 365 @Override public Object getInfoComponent() { 366 return getToolTipText(); 367 } 368 369 @Override public Component[] getMenuEntries() { 370 return new Component[]{ 371 new JMenuItem(new LayerListDialog.ShowHideLayerAction(this)), 372 new JMenuItem(new LayerListDialog.DeleteLayerAction(this)), 373 new JMenuItem(new toggleLabelsAction(this)), 374 new JSeparator(), 375 new JMenuItem(new setGridLayoutAction(this)), 376 new JMenuItem(new setWorldAction(this)), 377 new JMenuItem(new incAAction(this)), 378 new JMenuItem(new incBAction(this)), 379 new JMenuItem(new incCAction(this)), 380 new JMenuItem(new setColorAction(this)), 381 new JSeparator(), 382 new JMenuItem(new LayerListPopup.InfoAction(this))}; 383 } 384 384 } -
applications/editors/josm/plugins/grid/src/grid/GridPlugin.java
r1484 r12778 25 25 26 26 private class Action extends AbstractAction { 27 28 29 30 31 32 33 34 27 public Action() { 28 super("add grid"); 29 } 30 public void actionPerformed(ActionEvent e) { 31 GridLayer gridLayer = new GridLayer(""); 32 if (gridLayer != null) 33 Main.main.addLayer(gridLayer); 34 } 35 35 } 36 36 private JMenu edit; 37 37 private JMenuItem addGridMenu = new JMenuItem(new Action()); 38 38 39 39 public GridPlugin() { 40 JMenuBar menu = Main.main.menu; 41 edit = null; 42 for (int i = 0; i < menu.getMenuCount(); ++i) { 43 if (menu.getMenu(i) != null && tr("Edit").equals(menu.getMenu(i).getName())) { 44 edit = menu.getMenu(i); 45 break; 46 } 47 } 48 if (edit == null) { 49 edit = new JMenu(tr("Edit")); 50 menu.add(edit, 2); 51 edit.setVisible(false); 52 } 53 edit.add(addGridMenu); 54 addGridMenu.setVisible(false); 40 JMenuBar menu = Main.main.menu; 41 edit = null; 42 for (int i = 0; i < menu.getMenuCount(); ++i) { 43 if (menu.getMenu(i) != null && tr("Edit").equals(menu.getMenu(i).getName())) { 44 edit = menu.getMenu(i); 45 break; 46 } 55 47 } 56 @Override 57 public void mapFrameInitialized(MapFrame oldFrame, MapFrame newFrame) { 58 if (oldFrame != null && newFrame == null) { 59 // disable 60 addGridMenu.setVisible(false); 61 if (edit.getMenuComponentCount() == 1) 62 edit.setVisible(false); 63 } else if (oldFrame == null && newFrame != null) { 64 // enable 65 addGridMenu.setVisible(true); 66 if (edit.getMenuComponentCount() == 1) 67 edit.setVisible(true); 68 } 69 } 48 if (edit == null) { 49 edit = new JMenu(tr("Edit")); 50 menu.add(edit, 2); 51 edit.setVisible(false); 52 } 53 edit.add(addGridMenu); 54 addGridMenu.setVisible(false); 55 } 56 @Override 57 public void mapFrameInitialized(MapFrame oldFrame, MapFrame newFrame) { 58 if (oldFrame != null && newFrame == null) { 59 // disable 60 addGridMenu.setVisible(false); 61 if (edit.getMenuComponentCount() == 1) 62 edit.setVisible(false); 63 } else if (oldFrame == null && newFrame != null) { 64 // enable 65 addGridMenu.setVisible(true); 66 if (edit.getMenuComponentCount() == 1) 67 edit.setVisible(true); 68 } 69 } 70 70 71 71 } -
applications/editors/josm/plugins/imagewaypoint/src/org/insignificant/josm/plugins/imagewaypoint/ImageEntries.java
r12588 r12778 15 15 public final class ImageEntries { 16 16 private static final class ImageReadyListener implements 17 18 19 20 21 22 23 24 25 26 27 17 IImageReadyListener { 18 private final ImageEntries imageEntries; 19 20 public ImageReadyListener(final ImageEntries imageEntries) { 21 this.imageEntries = imageEntries; 22 } 23 24 public final void onImageReady(final ImageEntry imageEntry, 25 final Image image) { 26 this.imageEntries.setCurrentImage(imageEntry, image); 27 } 28 28 } 29 29 … … 39 39 40 40 private ImageEntries() { 41 42 43 44 45 46 47 41 this.images = new ArrayList<ImageEntry>(); 42 this.locatedImages = new ArrayList<ImageEntry>(); 43 this.listeners = new ArrayList<IImageChangeListener>(); 44 this.listener = new ImageReadyListener(this); 45 46 this.currentImageEntry = null; 47 this.currentImage = null; 48 48 } 49 49 50 50 public static final ImageEntries getInstance() { 51 51 return ImageEntries.INSTANCE; 52 52 } 53 53 54 54 public final void addListener(final IImageChangeListener listener) { 55 55 this.listeners.add(listener); 56 56 } 57 57 58 58 public final void removeListener(final IImageChangeListener listener) { 59 59 this.listeners.remove(listener); 60 60 } 61 61 62 62 public final void add(final File[] imageFiles) { 63 64 65 66 67 68 63 if (null != imageFiles) { 64 for (int index = 0; index < imageFiles.length; index++) { 65 this.images.add(new ImageEntry(imageFiles[index])); 66 } 67 this.associateAllLayers(); 68 } 69 69 } 70 70 71 71 public final void associateAllLayers() { 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 72 for (int index = 0; index < this.images.size(); index++) { 73 this.images.get(index).setWayPoint(null); 74 } 75 this.locatedImages.clear(); 76 77 if (null != Main.map && null != Main.map.mapView) { 78 final Collection<Layer> layerCollection = Main.map.mapView.getAllLayers(); 79 final Layer[] layers = layerCollection.toArray(new Layer[layerCollection.size()]); 80 81 for (int index = 0; index < layers.length; index++) { 82 if (layers[index] instanceof GpxLayer 83 && null != ((GpxLayer) layers[index]).data 84 && !((GpxLayer) layers[index]).data.fromServer) { 85 this.doAssociateLayer((GpxLayer) layers[index]); 86 } 87 } 88 89 for (IImageChangeListener listener : this.listeners) { 90 listener.onSelectedImageEntryChanged(this); 91 } 92 } 93 93 } 94 94 95 95 private final void doAssociateLayer(final GpxLayer gpxLayer) { 96 97 98 99 100 101 102 103 104 105 106 107 108 109 96 if (null != gpxLayer && null != gpxLayer.data 97 && !gpxLayer.data.fromServer) { 98 for (WayPoint wayPoint : gpxLayer.data.waypoints) { 99 final List<String> texts = this.getTextContentsFromWayPoint(wayPoint); 100 101 for (String text : texts) { 102 final ImageEntry image = this.findImageEntryWithFileName(text); 103 if (null != image) { 104 image.setWayPoint(wayPoint); 105 this.locatedImages.add(image); 106 } 107 } 108 } 109 } 110 110 } 111 111 112 112 private final List<String> getTextContentsFromWayPoint( 113 114 115 116 117 118 119 120 121 122 113 final WayPoint wayPoint) { 114 final List<String> texts = new ArrayList<String>(); 115 for(String s : new String[]{"name", "cmt", "desc"}) 116 { 117 String t = wayPoint.getString(s); 118 if(null != t && 0 < t.length()) 119 texts.add(t); 120 } 121 122 return texts; 123 123 } 124 124 … … 134 134 135 135 private final ImageEntry findImageEntryWithFileName(final String fileName) { 136 137 138 139 140 141 142 143 144 145 146 136 ImageEntry foundimage = null; 137 138 for (int index = 0; index < this.images.size() && null == foundimage; index++) { 139 final ImageEntry image = this.images.get(index); 140 if (null == image.getWayPoint() 141 && image.getFileName().startsWith(fileName)) { 142 foundimage = image; 143 } 144 } 145 146 return foundimage; 147 147 } 148 148 149 149 private final void setCurrentImage(final ImageEntry imageEntry, 150 151 152 153 154 155 156 157 150 final Image image) { 151 if (imageEntry == this.currentImageEntry) { 152 this.currentImage = image; 153 } 154 155 for (IImageChangeListener listener : this.listeners) { 156 listener.onSelectedImageEntryChanged(this); 157 } 158 158 } 159 159 160 160 public final ImageEntry[] getImages() { 161 161 return this.locatedImages.toArray(new ImageEntry[this.locatedImages.size()]); 162 162 } 163 163 164 164 public final ImageEntry getCurrentImageEntry() { 165 165 return this.currentImageEntry; 166 166 } 167 167 168 168 public final Image getCurrentImage() { 169 169 return this.currentImage; 170 170 } 171 171 172 172 public final boolean hasNext() { 173 174 173 return null != this.currentImageEntry 174 && this.locatedImages.indexOf(this.currentImageEntry) < this.locatedImages.size() - 1; 175 175 } 176 176 177 177 public final boolean hasPrevious() { 178 179 178 return null != this.currentImageEntry 179 && this.locatedImages.indexOf(this.currentImageEntry) > 0; 180 180 } 181 181 182 182 public final void next() { 183 184 185 186 183 if (null != this.currentImageEntry 184 && this.locatedImages.indexOf(this.currentImageEntry) < this.locatedImages.size() - 1) { 185 this.setCurrentImageEntry(this.locatedImages.get(this.locatedImages.indexOf(this.currentImageEntry) + 1)); 186 } 187 187 } 188 188 189 189 public final void previous() { 190 191 192 193 190 if (null != this.currentImageEntry 191 && this.locatedImages.indexOf(this.currentImageEntry) > 0) { 192 this.setCurrentImageEntry(this.locatedImages.get(this.locatedImages.indexOf(this.currentImageEntry) - 1)); 193 } 194 194 } 195 195 196 196 public final void rotateCurrentImageLeft() { 197 198 199 200 201 202 197 if (null != this.currentImageEntry) { 198 this.currentImageEntry.setOrientation(this.currentImageEntry.getOrientation() 199 .rotateLeft()); 200 } 201 202 this.setCurrentImageEntry(this.currentImageEntry); 203 203 } 204 204 205 205 public final void rotateCurrentImageRight() { 206 207 208 209 210 211 206 if (null != this.currentImageEntry) { 207 this.currentImageEntry.setOrientation(this.currentImageEntry.getOrientation() 208 .rotateRight()); 209 } 210 211 this.setCurrentImageEntry(this.currentImageEntry); 212 212 } 213 213 214 214 public final void setCurrentImageEntry(final ImageEntry imageEntry) { 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 215 if (null == imageEntry || this.locatedImages.contains(imageEntry)) { 216 if (null != this.currentImageEntry) { 217 this.currentImageEntry.flush(); 218 } 219 220 this.currentImageEntry = imageEntry; 221 this.currentImage = null; 222 223 for (IImageChangeListener listener : this.listeners) { 224 listener.onSelectedImageEntryChanged(this); 225 } 226 227 // now try to get the image 228 this.currentImageEntry.requestImage(this.listener); 229 } 230 230 } 231 231 } -
applications/editors/josm/plugins/imagewaypoint/src/org/insignificant/josm/plugins/imagewaypoint/ImageEntry.java
r12588 r12778 1 1 /** 2 * 2 * 3 3 */ 4 4 package org.insignificant.josm.plugins.imagewaypoint; … … 23 23 public final class ImageEntry implements Comparable<ImageEntry> { 24 24 public interface IImageReadyListener { 25 25 void onImageReady(ImageEntry imageEntry, Image image); 26 26 } 27 27 28 28 private static final class Observer implements ImageObserver { 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 29 private final ImageEntry imageEntry; 30 31 public Observer(final ImageEntry imageEntry) { 32 this.imageEntry = imageEntry; 33 } 34 35 /** 36 * @see java.awt.image.ImageObserver#imageUpdate(java.awt.Image, int, 37 * int, int, int, int) 38 * @return true if this ImageObserver still wants to be updates about 39 * image loading progress 40 */ 41 public final boolean imageUpdate(final Image image, 42 final int infoflags, final int x, final int y, final int width, 43 final int height) { 44 final boolean complete = ImageObserver.ALLBITS == (infoflags | ImageObserver.ALLBITS); 45 if (complete) { 46 this.imageEntry.imageLoaded(image); 47 } 48 49 return !complete; 50 } 51 51 } 52 52 53 53 public static final class Orientation { 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 54 private static final Orientation[] orientations = new Orientation[4]; 55 56 public static final Orientation NORMAL = new Orientation(tr("Normal"), 0); 57 public static final Orientation ROTATE_90 = new Orientation(tr("Rotate 90"), 58 1); 59 public static final Orientation ROTATE_180 = new Orientation(tr("Rotate 180"), 60 2); 61 public static final Orientation ROTATE_270 = new Orientation(tr("Rotate 270"), 62 3); 63 64 private final String name; 65 private final int index; 66 67 private Orientation(final String name, final int index) { 68 this.name = name; 69 this.index = index; 70 Orientation.orientations[index] = this; 71 } 72 73 public final Orientation rotateRight() { 74 if (this.index < Orientation.orientations.length - 1) { 75 return Orientation.orientations[this.index + 1]; 76 } else { 77 return Orientation.orientations[0]; 78 } 79 } 80 81 public final Orientation rotateLeft() { 82 if (this.index == 0) { 83 return Orientation.orientations[Orientation.orientations.length - 1]; 84 } else { 85 return Orientation.orientations[this.index - 1]; 86 } 87 } 88 89 @Override 90 public String toString() { 91 return "[" + this.name + "]"; 92 } 93 93 } 94 94 … … 108 108 109 109 public ImageEntry(final File file) { 110 111 112 113 114 115 116 117 118 110 this.filePath = file.getAbsolutePath(); 111 this.fileName = file.getName(); 112 this.observer = new Observer(this); 113 114 this.wayPoint = null; 115 this.orientation = Orientation.NORMAL; 116 this.listener = null; 117 this.normalImage = null; 118 this.rotatedImage = null; 119 119 } 120 120 121 121 public final int compareTo(final ImageEntry image) { 122 122 return this.fileName.compareTo(image.fileName); 123 123 } 124 124 125 125 public final String getFileName() { 126 126 return fileName; 127 127 } 128 128 129 129 public final WayPoint getWayPoint() { 130 130 return wayPoint; 131 131 } 132 132 133 133 public final void setWayPoint(final WayPoint wayPoint) { 134 134 this.wayPoint = wayPoint; 135 135 } 136 136 137 137 public final Orientation getOrientation() { 138 138 return orientation; 139 139 } 140 140 141 141 public final void setOrientation(final Orientation orientation) { 142 143 144 142 this.orientation = orientation; 143 this.normalImage = null; 144 this.rotatedImage = null; 145 145 } 146 146 147 147 public final Rectangle getBounds(final MapView mapView) { 148 149 150 151 152 153 154 155 156 157 158 159 160 148 final Rectangle bounds; 149 150 if (null == this.wayPoint) { 151 bounds = null; 152 } else { 153 final Point point = mapView.getPoint(this.getWayPoint().eastNorth); 154 bounds = new Rectangle(point.x - ImageEntry.ICON_WIDTH, 155 point.y - ImageEntry.ICON_HEIGHT, 156 ImageEntry.ICON_WIDTH, 157 ImageEntry.ICON_WIDTH); 158 } 159 160 return bounds; 161 161 } 162 162 163 163 public final void requestImage(final IImageReadyListener imageReadyListener) { 164 165 166 167 168 169 170 171 172 173 174 175 176 177 164 this.listener = imageReadyListener; 165 166 if (null == this.rotatedImage) { 167 final Image image = Toolkit.getDefaultToolkit() 168 .getImage(this.filePath); 169 if (Toolkit.getDefaultToolkit().prepareImage(image, 170 -1, 171 -1, 172 this.observer)) { 173 this.imageLoaded(image); 174 } 175 } else if (null != this.listener) { 176 this.listener.onImageReady(this, this.rotatedImage); 177 } 178 178 } 179 179 180 180 public final void flush() { 181 182 183 184 185 186 187 188 189 181 if (null != this.normalImage) { 182 this.normalImage.flush(); 183 this.normalImage = null; 184 } 185 186 if (null != this.rotatedImage) { 187 this.rotatedImage.flush(); 188 this.rotatedImage = null; 189 } 190 190 } 191 191 192 192 private final void imageLoaded(final Image image) { 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 193 if (Orientation.NORMAL == this.getOrientation()) { 194 this.rotatedImage = image; 195 } else { 196 final int[] buffer = new int[image.getWidth(null) 197 * image.getHeight(null)]; 198 PixelGrabber grabber = new PixelGrabber(image, 199 0, 200 0, 201 image.getWidth(null), 202 image.getHeight(null), 203 buffer, 204 0, 205 image.getWidth(null)); 206 try { 207 grabber.grabPixels(); 208 209 final int newHeight; 210 final int newWidth; 211 212 if (Orientation.ROTATE_180 == this.getOrientation()) { 213 newHeight = image.getHeight(null); 214 newWidth = image.getWidth(null); 215 } else { 216 newHeight = image.getWidth(null); 217 newWidth = image.getHeight(null); 218 } 219 220 final int[] destination = new int[image.getWidth(null) 221 * image.getHeight(null)]; 222 for (int x = 0; x < image.getWidth(null); x++) { 223 for (int y = 0; y < image.getHeight(null); y++) { 224 final int pix = buffer[x + (y * image.getWidth(null))]; 225 final int newX; 226 final int newY; 227 if (Orientation.ROTATE_90 == this.getOrientation()) { 228 newX = newWidth - y; 229 newY = x; 230 } else if (Orientation.ROTATE_180 == this.getOrientation()) { 231 newX = newWidth - x; 232 newY = newHeight - y; 233 } else { // Orientation.ROTATE_270 == 234 // this.getOrientation() 235 newX = y; 236 newY = newHeight - x; 237 } 238 final int newIndex = newX + (newY * newWidth); 239 if (newIndex < destination.length) { 240 destination[newIndex] = pix; 241 } 242 } 243 } 244 245 this.rotatedImage = Toolkit.getDefaultToolkit() 246 .createImage(new MemoryImageSource(newWidth, 247 newHeight, 248 destination, 249 0, 250 newWidth)); 251 } catch (final InterruptedException e) { 252 this.rotatedImage = null; 253 } 254 } 255 256 if (null != this.listener) { 257 this.listener.onImageReady(this, this.rotatedImage); 258 } 259 259 } 260 260 } -
applications/editors/josm/plugins/imagewaypoint/src/org/insignificant/josm/plugins/imagewaypoint/ImageWayPointDialog.java
r12588 r12778 23 23 public final class ImageWayPointDialog { 24 24 private static final class ImageComponent extends JComponent { 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 25 private static final long serialVersionUID = -5207198660736375133L; 26 27 private Image image; 28 29 public ImageComponent() { 30 this.image = null; 31 } 32 33 @Override 34 public final void paint(final Graphics g) { 35 if (null == this.image || 0 >= this.image.getWidth(null) 36 || 0 >= this.image.getHeight(null)) { 37 g.setColor(Color.white); 38 g.fillRect(0, 0, this.getSize().width, this.getSize().height); 39 } else { 40 final int maxWidth = this.getSize().width; 41 final int maxHeight = this.getSize().height; 42 final int imageWidth = this.image.getWidth(null); 43 final int imageHeight = this.image.getHeight(null); 44 45 final double aspect = 1.0 * imageWidth / imageHeight; 46 47 // what's the width if the height is 100%? 48 final int widthIfHeightIsMax = (int) (aspect * maxHeight); 49 50 // now find the real width and height 51 final int resizedWidth; 52 final int resizedHeight; 53 if (widthIfHeightIsMax > maxWidth) { 54 // oops - burst the width - so width should be the max, and 55 // work out the resulting height 56 resizedWidth = maxWidth; 57 resizedHeight = (int) (resizedWidth / aspect); 58 } else { 59 // that'll do... 60 resizedWidth = widthIfHeightIsMax; 61 resizedHeight = maxHeight; 62 } 63 64 g.drawImage(this.image, 65 (maxWidth - resizedWidth) / 2, 66 (maxHeight - resizedHeight) / 2, 67 resizedWidth, 68 resizedHeight, 69 Color.black, 70 null); 71 } 72 } 73 74 public final void setImage(final Image image) { 75 this.image = image; 76 this.repaint(); 77 } 78 78 } 79 79 80 80 private static final class ImageChangeListener implements 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 81 IImageChangeListener { 82 private final ImageWayPointDialog dialog; 83 84 public ImageChangeListener(final ImageWayPointDialog dialog) { 85 this.dialog = dialog; 86 } 87 88 public final void onAvailableImageEntriesChanged( 89 final ImageEntries entries) { 90 this.dialog.imageDisplay.setImage(entries.getCurrentImage()); 91 this.dialog.updateUI(); 92 } 93 94 public final void onSelectedImageEntryChanged(final ImageEntries entries) { 95 this.dialog.imageDisplay.setImage(entries.getCurrentImage()); 96 this.dialog.updateUI(); 97 } 98 98 } 99 99 100 100 private static final class PreviousAction extends JosmAction { 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 101 private static final long serialVersionUID = -7899209365124237890L; 102 103 private final ImageWayPointDialog dialog; 104 105 public PreviousAction(final ImageWayPointDialog dialog) { 106 super(tr("Previous"), 107 null, 108 tr("Previous image"), 109 null, 110 false); 111 this.dialog = dialog; 112 } 113 114 public final void actionPerformed(final ActionEvent actionEvent) { 115 if (ImageEntries.getInstance().hasPrevious()) { 116 ImageEntries.getInstance().previous(); 117 } 118 } 119 119 } 120 120 121 121 private static final class NextAction extends JosmAction { 122 123 124 125 126 127 128 129 130 131 132 133 134 135 122 private static final long serialVersionUID = 176134010956760988L; 123 124 private final ImageWayPointDialog dialog; 125 126 public NextAction(final ImageWayPointDialog dialog) { 127 super(tr("Next"), null, tr("Next image"), null, false); 128 this.dialog = dialog; 129 } 130 131 public final void actionPerformed(final ActionEvent actionEvent) { 132 if (ImageEntries.getInstance().hasNext()) { 133 ImageEntries.getInstance().next(); 134 } 135 } 136 136 } 137 137 138 138 private static final class RotateLeftAction extends JosmAction { 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 139 private static final long serialVersionUID = 3536922796446259943L; 140 141 private final ImageWayPointDialog dialog; 142 143 public RotateLeftAction(final ImageWayPointDialog dialog) { 144 super(tr("Rotate left"), 145 null, 146 tr("Rotate image left"), 147 null, 148 false); 149 this.dialog = dialog; 150 } 151 152 public final void actionPerformed(final ActionEvent actionEvent) { 153 ImageEntries.getInstance().rotateCurrentImageLeft(); 154 } 155 155 } 156 156 157 157 private static final class RotateRightAction extends JosmAction { 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 158 private static final long serialVersionUID = 1760186810341888993L; 159 160 private final ImageWayPointDialog dialog; 161 162 public RotateRightAction(final ImageWayPointDialog dialog) { 163 super(tr("Rotate right"), 164 null, 165 tr("Rotate image right"), 166 null, 167 false); 168 this.dialog = dialog; 169 } 170 171 public final void actionPerformed(final ActionEvent actionEvent) { 172 ImageEntries.getInstance().rotateCurrentImageRight(); 173 } 174 174 } 175 175 … … 185 185 186 186 private ImageWayPointDialog() { 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 187 this.dialog = new ToggleDialog(tr("WayPoint Image"), 188 "imagewaypoint", 189 tr("Display non-geotagged photos"), 190 Shortcut.registerShortcut("subwindow:imagewaypoint", tr("Toggle: {0}", tr("WayPoint Image")), 191 KeyEvent.VK_Y, Shortcut.GROUP_LAYER), 192 200); 193 194 this.previousAction = new PreviousAction(this); 195 this.nextAction = new NextAction(this); 196 this.rotateLeftAction = new RotateLeftAction(this); 197 this.rotateRightAction = new RotateRightAction(this); 198 199 final JButton previousButton = new JButton(this.previousAction); 200 final JButton nextButton = new JButton(this.nextAction); 201 final JButton rotateLeftButton = new JButton(this.rotateLeftAction); 202 final JButton rotateRightButton = new JButton(this.rotateRightAction); 203 204 // default layout, FlowLayout, is fine 205 final JPanel buttonPanel = new JPanel(); 206 buttonPanel.add(previousButton); 207 buttonPanel.add(nextButton); 208 buttonPanel.add(rotateLeftButton); 209 buttonPanel.add(rotateRightButton); 210 211 final JPanel mainPanel = new JPanel(); 212 mainPanel.setLayout(new BorderLayout()); 213 214 this.imageDisplay = new ImageComponent(); 215 mainPanel.add(buttonPanel, BorderLayout.SOUTH); 216 mainPanel.add(this.imageDisplay, BorderLayout.CENTER); 217 218 this.listener = new ImageChangeListener(this); 219 ImageEntries.getInstance().addListener(this.listener); 220 221 this.updateUI(); 222 dialog.add(mainPanel); 223 223 } 224 224 225 225 private final void updateUI() { 226 227 228 229 230 231 232 233 234 235 226 this.previousAction.setEnabled(ImageEntries.getInstance().hasPrevious()); 227 this.nextAction.setEnabled(ImageEntries.getInstance().hasNext()); 228 this.rotateLeftAction.setEnabled(null != ImageEntries.getInstance() 229 .getCurrentImageEntry()); 230 this.rotateRightAction.setEnabled(null != ImageEntries.getInstance() 231 .getCurrentImageEntry()); 232 233 if (null != Main.map) { 234 Main.map.repaint(); 235 } 236 236 } 237 237 238 238 public static ImageWayPointDialog getInstance() { 239 239 return ImageWayPointDialog.INSTANCE; 240 240 } 241 241 242 242 public final ToggleDialog getDisplayComponent() { 243 243 return this.dialog; 244 244 } 245 245 } -
applications/editors/josm/plugins/imagewaypoint/src/org/insignificant/josm/plugins/imagewaypoint/ImageWayPointLayer.java
r12588 r12778 20 20 public final class ImageWayPointLayer extends Layer { 21 21 private static final class ImageWayPointMouseListener extends MouseAdapter { 22 22 private final ImageWayPointLayer layer; 23 23 24 25 26 24 public ImageWayPointMouseListener(final ImageWayPointLayer layer) { 25 this.layer = layer; 26 } 27 27 28 29 30 31 32 28 @Override 29 public final void mouseClicked(final MouseEvent event) { 30 if (MouseEvent.BUTTON1 == event.getButton() && this.layer.visible) { 31 final ImageEntry[] images = ImageEntries.getInstance() 32 .getImages(); 33 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 34 if (null != images) { 35 boolean found = false; 36 // Note: the images are checked in the *reverse* order to 37 // which they're painted - this means than an image which 38 // partly obscures another will match the click first 39 for (int index = images.length - 1; !found && index >= 0; index--) { 40 final Rectangle bounds = images[index].getBounds(Main.map.mapView); 41 if (null != bounds && bounds.contains(event.getPoint())) { 42 found = true; 43 ImageEntries.getInstance() 44 .setCurrentImageEntry(images[index]); 45 } 46 } 47 } 48 } 49 } 50 50 } 51 51 52 52 private static final class ImageChangeListener implements 53 54 53 IImageChangeListener { 54 private final ImageWayPointLayer layer; 55 55 56 57 58 56 public ImageChangeListener(final ImageWayPointLayer layer) { 57 this.layer = layer; 58 } 59 59 60 61 62 63 60 public final void onAvailableImageEntriesChanged( 61 final ImageEntries entries) { 62 Main.map.repaint(); 63 } 64 64 65 66 67 65 public final void onSelectedImageEntryChanged(final ImageEntries entries) { 66 Main.map.repaint(); 67 } 68 68 } 69 69 … … 72 72 73 73 public ImageWayPointLayer() { 74 74 super(tr("Imported Images")); 75 75 76 76 Main.main.addLayer(this); 77 77 78 79 78 this.layerMouseListener = new ImageWayPointMouseListener(this); 79 Main.map.mapView.addMouseListener(this.layerMouseListener); 80 80 81 82 81 this.imageChangeListener = new ImageChangeListener(this); 82 ImageEntries.getInstance().addListener(this.imageChangeListener); 83 83 } 84 84 85 85 @Override 86 86 public final Icon getIcon() { 87 87 return ImageProvider.get("dialogs/imagewaypoint"); 88 88 } 89 89 90 90 @Override 91 91 public final Object getInfoComponent() { 92 92 return null; 93 93 } 94 94 95 95 @Override 96 96 public final Component[] getMenuEntries() { 97 97 return new Component[0]; 98 98 } 99 99 100 100 @Override 101 101 public final String getToolTipText() { 102 103 102 // TODO 103 return ""; 104 104 } 105 105 106 106 @Override 107 107 public final boolean isMergable(final Layer other) { 108 109 108 // TODO 109 return false; 110 110 } 111 111 112 112 @Override 113 113 public final void mergeFrom(final Layer from) { 114 114 // TODO not supported yet 115 115 } 116 116 117 117 @Override 118 118 public final void paint(final Graphics graphics, final MapView mapView) { 119 119 final ImageEntry[] images = ImageEntries.getInstance().getImages(); 120 120 121 122 123 121 if (null != images) { 122 final ImageEntry currentImage = ImageEntries.getInstance() 123 .getCurrentImageEntry(); 124 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 125 for (int index = 0; index < images.length; index++) { 126 final Rectangle bounds = images[index].getBounds(mapView); 127 if (null != bounds) { 128 if (images[index] == currentImage) { 129 ImageEntry.SELECTED_ICON.paintIcon(mapView, 130 graphics, 131 bounds.x, 132 bounds.y); 133 } else { 134 ImageEntry.ICON.paintIcon(mapView, 135 graphics, 136 bounds.x, 137 bounds.y); 138 } 139 } 140 } 141 } 142 142 } 143 143 144 144 @Override 145 145 public final void visitBoundingBox(final BoundingXYVisitor visitor) { 146 146 final ImageEntry[] images = ImageEntries.getInstance().getImages(); 147 147 148 149 150 148 if (null != images) { 149 for (int index = 0; index < images.length; index++) { 150 final ImageEntry imageEntry = images[index]; 151 151 152 153 154 155 156 157 152 if (null != imageEntry.getWayPoint() 153 && null != imageEntry.getWayPoint().eastNorth) { 154 visitor.visit(imageEntry.getWayPoint().eastNorth); 155 } 156 } 157 } 158 158 } 159 159 160 160 @Override 161 161 public final void destroy() { 162 162 super.destroy(); 163 163 164 165 164 Main.map.mapView.removeMouseListener(this.layerMouseListener); 165 ImageEntries.getInstance().removeListener(this.imageChangeListener); 166 166 } 167 167 } -
applications/editors/josm/plugins/imagewaypoint/src/org/insignificant/josm/plugins/imagewaypoint/ImageWayPointPlugin.java
r12588 r12778 24 24 public final class ImageWayPointPlugin extends org.openstreetmap.josm.plugins.Plugin { 25 25 private static final class ImageFileFilter extends FileFilter { 26 27 28 29 30 31 32 33 26 @Override 27 public final boolean accept(final File file) { 28 return file.isDirectory() 29 || file.getName().toLowerCase().endsWith(".jpg") 30 || file.getName().toLowerCase().endsWith(".jpeg") 31 || file.getName().toLowerCase().endsWith(".png") 32 || file.getName().toLowerCase().endsWith(".gif"); 33 } 34 34 35 36 37 38 35 @Override 36 public final String getDescription() { 37 return tr("Image files (*.jpg, *.jpeg, *.png, *.gif)"); 38 } 39 39 } 40 40 41 41 private static final class LoadImagesAction extends JosmAction { 42 42 private static final long serialVersionUID = 4480306223276347301L; 43 43 44 44 private final ImageWayPointPlugin plugin; 45 45 46 47 48 49 50 51 46 public LoadImagesAction(final ImageWayPointPlugin plugin) { 47 super(tr("Open images with ImageWayPoint"), 48 "imagewaypoint-open", 49 tr("Load set of images as a new layer."), 50 null, 51 false); 52 52 53 54 53 this.plugin = plugin; 54 } 55 55 56 57 58 59 60 61 56 public final void actionPerformed(final ActionEvent actionEvent) { 57 final JFileChooser fileChooser = new JFileChooser(Main.pref.get("tagimages.lastdirectory")); 58 fileChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES); 59 fileChooser.setMultiSelectionEnabled(true); 60 fileChooser.setAcceptAllFileFilterUsed(false); 61 fileChooser.setFileFilter(new ImageFileFilter()); 62 62 63 63 fileChooser.showOpenDialog(Main.parent); 64 64 65 66 67 68 65 final File[] selectedFiles = fileChooser.getSelectedFiles(); 66 if (null != selectedFiles && 0 != selectedFiles.length) { 67 Main.pref.put("tagimages.lastdirectory", 68 fileChooser.getCurrentDirectory().getPath()); 69 69 70 71 72 70 // recursively find all files 71 final List<File> allFiles = new ArrayList<File>(); 72 this.plugin.addFiles(allFiles, selectedFiles); 73 73 74 75 76 74 // add files to ImageEntries 75 ImageEntries.getInstance() 76 .add(allFiles.toArray(new File[allFiles.size()])); 77 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 78 // check to see whether there's already an ImageWayPointLayer 79 boolean foundImageWayPointLayer = false; 80 if (null != Main.map && null != Main.map.mapView) { 81 final Collection<Layer> layerCollection = Main.map.mapView.getAllLayers(); 82 final Iterator<Layer> layerIterator = layerCollection.iterator(); 83 while (layerIterator.hasNext() && !foundImageWayPointLayer) { 84 if (layerIterator.next() instanceof ImageWayPointLayer) { 85 foundImageWayPointLayer = true; 86 } 87 } 88 } 89 if (!foundImageWayPointLayer) { 90 new ImageWayPointLayer(); 91 } 92 } 93 } 94 94 } 95 95 … … 98 98 */ 99 99 public ImageWayPointPlugin() { 100 101 102 100 // find the File menu 101 final JMenuBar menuBar = Main.main.menu; 102 JMenu fileMenu = null; 103 103 104 105 106 107 108 109 110 111 104 if (null != menuBar) { 105 for (int index = 0; index < menuBar.getMenuCount() 106 && null == fileMenu; index++) { 107 if (I18n.tr("File").equals(menuBar.getMenu(index).getText())) { 108 fileMenu = menuBar.getMenu(index); 109 } 110 } 111 } 112 112 113 114 115 116 117 113 if (null != fileMenu) { 114 // now create our 'load' menu item and add to the file menu 115 final JMenuItem menuItem = new JMenuItem(new LoadImagesAction(this)); 116 fileMenu.add(menuItem, 2); 117 } 118 118 } 119 119 120 120 @Override 121 121 public final void mapFrameInitialized(final MapFrame oldFrame, 122 123 124 125 126 127 128 122 final MapFrame newFrame) { 123 if (newFrame != null) { 124 newFrame.addToggleDialog(ImageWayPointDialog.getInstance() 125 .getDisplayComponent()); 126 } else { 127 ImageEntries.getInstance().setCurrentImageEntry(null); 128 } 129 129 } 130 130 131 131 private void addFiles(List<File> allFiles, File[] selectedFiles) { 132 133 134 135 136 137 138 139 132 for (int index = 0; index < selectedFiles.length; index++) { 133 final File selectedFile = selectedFiles[index]; 134 if (selectedFile.isDirectory()) { 135 this.addFiles(allFiles, selectedFile.listFiles()); 136 } else if (selectedFile.getName().toLowerCase().endsWith(".jpg")) { 137 allFiles.add(selectedFile); 138 } 139 } 140 140 } 141 141 } -
applications/editors/josm/plugins/lakewalker/src/org/openstreetmap/josm/plugins/lakewalker/Lakewalker.java
r11938 r12778 16 16 17 17 public class Lakewalker { 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 this.workingdir = workingdir; 50 51 52 53 54 55 56 57 58 59 60 * southeast = 7 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 int[] xy = geo_to_xy(lat,lon,this.resolution); 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 // Check if we got stuck in a loop 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 // Shift back one index 239 240 241 242 243 244 245 246 247 248 * Reduce the number of vertices based on their proximity to each other 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 double x0 = p1[0]; 279 280 double x1 = p2[0]; 281 double y1 = p2[1]; 282 double x2 = p3[0]; 283 284 285 286 287 288 289 290 291 292 293 294 295 296 18 protected Collection<Command> commands = new LinkedList<Command>(); 19 protected Collection<Way> ways = new ArrayList<Way>(); 20 protected boolean cancel; 21 22 private int waylen; 23 private int maxnode; 24 private int threshold; 25 private double epsilon; 26 private int resolution; 27 private int tilesize; 28 private String startdir; 29 private String wmslayer; 30 31 private File workingdir; 32 33 private int[] dirslat = new int[] {0,1,1,1,0,-1,-1,-1}; 34 private int[] dirslon = new int[] {1,1,0,-1,-1,-1,0,1}; 35 36 double start_radius_big = 0.001; 37 double start_radius_small = 0.0002; 38 39 public Lakewalker(int waylen, int maxnode, int threshold, double epsilon, int resolution, int tilesize, String startdir, String wmslayer, File workingdir){ 40 this.waylen = waylen; 41 this.maxnode = maxnode; 42 this.threshold = threshold; 43 this.epsilon = epsilon; 44 this.resolution = resolution; 45 this.tilesize = tilesize; 46 this.startdir = startdir; 47 this.wmslayer = wmslayer; 48 49 this.workingdir = workingdir; 50 } 51 52 /** 53 * east = 0 54 * northeast = 1 55 * north = 2 56 * northwest = 3 57 * west = 4 58 * southwest = 5 59 * south = 6 60 * southeast = 7 61 */ 62 private int getDirectionIndex(String direction) throws ArrayIndexOutOfBoundsException{ 63 int i=0; 64 if(direction.equals("East") || direction.equals("east")){ 65 i = 0; 66 } else if(direction.equals("Northeast") || direction.equals("northeast")){ 67 i = 1; 68 } else if(direction.equals("North") || direction.equals("north")){ 69 i = 2; 70 } else if(direction.equals("Northwest") || direction.equals("northwest")){ 71 i = 3; 72 } else if(direction.equals("West") || direction.equals("west")){ 73 i = 4; 74 } else if(direction.equals("Southwest") || direction.equals("southwest")){ 75 i = 5; 76 } else if(direction.equals("South") || direction.equals("south")){ 77 i = 6; 78 } else if(direction.equals("Southeast") || direction.equals("southeast")){ 79 i = 7; 80 } else { 81 throw new ArrayIndexOutOfBoundsException(tr("Direction index '{0}' not found",direction)); 82 } 83 return i; 84 } 85 86 /** 87 * Do a trace 88 * 89 * @param lat 90 * @param lon 91 * @param tl_lon 92 * @param br_lon 93 * @param tl_lat 94 * @param br_lat 95 */ 96 public ArrayList<double[]> trace(double lat, double lon, double tl_lon, double br_lon, double tl_lat, double br_lat) throws LakewalkerException { 97 98 LakewalkerWMS wms = new LakewalkerWMS(this.resolution, this.tilesize, this.wmslayer, this.workingdir); 99 LakewalkerBBox bbox = new LakewalkerBBox(tl_lat,tl_lon,br_lat,br_lon); 100 101 Boolean detect_loop = false; 102 103 ArrayList<double[]> nodelist = new ArrayList<double[]>(); 104 105 int[] xy = geo_to_xy(lat,lon,this.resolution); 106 107 if(!bbox.contains(lat, lon)){ 108 throw new LakewalkerException(tr("The starting location was not within the bbox")); 109 } 110 111 int v; 112 113 setStatus(tr("Looking for shoreline...")); 114 115 while(true){ 116 double[] geo = xy_to_geo(xy[0],xy[1],this.resolution); 117 if(bbox.contains(geo[0],geo[1])==false){ 118 break; 119 } 120 121 v = wms.getPixel(xy[0], xy[1]); 122 if(v > this.threshold){ 123 break; 124 } 125 126 int delta_lat = this.dirslat[getDirectionIndex(this.startdir)]; 127 int delta_lon = this.dirslon[getDirectionIndex(this.startdir)]; 128 129 xy[0] = xy[0]+delta_lon; 130 xy[1] = xy[1]+delta_lat; 131 132 } 133 134 int[] startxy = new int[] {xy[0], xy[1]}; 135 double[] startgeo = xy_to_geo(xy[0],xy[1],this.resolution); 136 137 //System.out.printf("Found shore at lat %.4f lon %.4f\n",lat,lon); 138 139 int last_dir = this.getDirectionIndex(this.startdir); 140 141 for(int i = 0; i < this.maxnode; i++){ 142 143 // Print a counter 144 if(i % 250 == 0){ 145 setStatus(tr("{0} nodes so far...",i)); 146 //System.out.println(i+" nodes so far..."); 147 } 148 149 // Some variables we need 150 int d; 151 int test_x=0; 152 int test_y=0; 153 int new_dir = 0; 154 155 // Loop through all the directions we can go 156 for(d = 1; d <= this.dirslat.length; d++){ 157 158 // Decide which direction we want to look at from this pixel 159 new_dir = (last_dir + d + 4) % 8; 160 161 test_x = xy[0] + this.dirslon[new_dir]; 162 test_y = xy[1] + this.dirslat[new_dir]; 163 164 double[] geo = xy_to_geo(test_x,test_y,this.resolution); 165 166 if(!bbox.contains(geo[0], geo[1])){ 167 System.out.println("Outside bbox"); 168 break; 169 } 170 171 v = wms.getPixel(test_x, test_y); 172 if(v > this.threshold){ 173 break; 174 } 175 176 if(d == this.dirslat.length-1){ 177 System.out.println("Got stuck"); 178 break; 179 } 180 } 181 182 // Remember this direction 183 last_dir = new_dir; 184 185 // Set the pixel we found as current 186 xy[0] = test_x; 187 xy[1] = test_y; 188 189 // Break the loop if we managed to get back to our starting point 190 if(xy[0] == startxy[0] && xy[1] == startxy[1]){ 191 break; 192 } 193 194 // Store this node 195 double[] geo = xy_to_geo(xy[0],xy[1],this.resolution); 196 nodelist.add(geo); 197 //System.out.println("Adding node at "+xy[0]+","+xy[1]+" ("+geo[1]+","+geo[0]+")"); 198 199 // Check if we got stuck in a loop 200 double start_proximity = Math.pow((geo[0] - startgeo[0]),2) + Math.pow((geo[1] - startgeo[1]),2); 201 202 if(detect_loop){ 203 if(start_proximity < Math.pow(start_radius_small,2)){ 204 System.out.println("Detected loop"); 205 break; 206 } 207 }else{ 208 if(start_proximity > Math.pow(start_radius_big,2)){ 209 detect_loop = true; 210 } 211 } 212 } 213 214 return nodelist; 215 } 216 217 /** 218 * Remove duplicate nodes from the list 219 * 220 * @param nodes 221 * @return 222 */ 223 public ArrayList<double[]> duplicateNodeRemove(ArrayList<double[]> nodes){ 224 225 if(nodes.size() <= 1){ 226 return nodes; 227 } 228 229 double lastnode[] = new double[] {nodes.get(0)[0], nodes.get(0)[1]}; 230 231 for(int i = 1; i < nodes.size(); i++){ 232 double[] thisnode = new double[] {nodes.get(i)[0], nodes.get(i)[1]}; 233 234 if(thisnode[0] == lastnode[0] && thisnode[1] == lastnode[1]){ 235 // Remove the node 236 nodes.remove(i); 237 238 // Shift back one index 239 i = i - 1; 240 } 241 lastnode = thisnode; 242 } 243 244 return nodes; 245 } 246 247 /** 248 * Reduce the number of vertices based on their proximity to each other 249 * 250 * @param nodes 251 * @param proximity 252 * @return 253 */ 254 public ArrayList<double[]> vertexReduce(ArrayList<double[]> nodes, double proximity){ 255 256 // Check if node list is empty 257 if(nodes.size()<=1){ 258 return nodes; 259 } 260 261 double[] test_v = nodes.get(0); 262 ArrayList<double[]> reducednodes = new ArrayList<double[]>(); 263 264 double prox_sq = Math.pow(proximity, 2); 265 266 for(int v = 0; v < nodes.size(); v++){ 267 if(Math.pow(nodes.get(v)[0] - test_v[0],2) + Math.pow(nodes.get(v)[1] - test_v[1],2) > prox_sq){ 268 reducednodes.add(nodes.get(v)); 269 test_v = nodes.get(v); 270 } 271 } 272 273 return reducednodes; 274 } 275 276 public double pointLineDistance(double[] p1, double[] p2, double[] p3){ 277 278 double x0 = p1[0]; 279 double y0 = p1[1]; 280 double x1 = p2[0]; 281 double y1 = p2[1]; 282 double x2 = p3[0]; 283 double y2 = p3[1]; 284 285 if(x2 == x1 && y2 == y1){ 286 return Math.sqrt(Math.pow(x1-x0,2) + Math.pow(y1-y0,2)); 287 } else { 288 return Math.abs((x2-x1)*(y1-y0) - (x1-x0)*(y2-y1)) / Math.sqrt(Math.pow(x2-x1,2) + Math.pow(y2-y1,2)); 289 } 290 } 291 292 public ArrayList<double[]> douglasPeuckerNR(ArrayList<double[]> nodes, double epsilon){ 293 /* 294 command_stack = [(0, len(nodes) - 1)] 295 296 Vector result_stack = new Vector(); 297 297 298 298 while(command_stack.size() > 0){ 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 419 420 421 422 423 424 425 426 299 cmd = command_stack.pop(); 300 if(type(cmd) == tuple){ 301 (start, end) = cmd 302 (node, dist) = dp_findpoint(nodes, start, end) 303 if(dist > epsilon){ 304 command_stack.append("+") 305 command_stack.append((start, node)) 306 command_stack.append((node, end)) 307 } else { 308 result_stack.append((start, end)) 309 } 310 } elseif(cmd == "+"){ 311 first = result_stack.pop() 312 second = result_stack.pop() 313 if(first[-1] == second[0]){ 314 result_stack.append(first + second[1:]) 315 //print "Added %s and %s; result is %s" % (first, second, result_stack[-1]) 316 }else { 317 error("ERROR: Cannot connect nodestrings!") 318 #print first 319 #print second 320 return; 321 } 322 } else { 323 error("ERROR: Can't understand command \"%s\"" % (cmd,)) 324 return 325 326 if(len(result_stack) == 1){ 327 return [nodes[x] for x in result_stack[0]]; 328 } else { 329 error("ERROR: Command stack is empty but result stack has %d nodes!" % len(result_stack)); 330 return; 331 } 332 333 farthest_node = None 334 farthest_dist = 0 335 first = nodes[0] 336 last = nodes[-1] 337 338 for(i in xrange(1, len(nodes) - 1){ 339 d = point_line_distance(nodes[i], first, last) 340 if(d > farthest_dist){ 341 farthest_dist = d 342 farthest_node = i 343 } 344 } 345 if(farthest_dist > epsilon){ 346 seg_a = douglas_peucker(nodes[0:farthest_node+1], epsilon) 347 seg_b = douglas_peucker(nodes[farthest_node:-1], epsilon) 348 //print "Minimized %d nodes to %d + %d nodes" % (len(nodes), len(seg_a), len(seg_b)) 349 nodes = seg_a[:-1] + seg_b 350 } else { 351 return [nodes[0], nodes[-1]]; 352 } 353 */ 354 return nodes; 355 } 356 357 public ArrayList<double[]> douglasPeucker(ArrayList<double[]> nodes, double epsilon){ 358 359 // Check if node list is empty 360 if(nodes.size()<=1){ 361 return nodes; 362 } 363 364 int farthest_node = -1; 365 double farthest_dist = 0; 366 double[] first = nodes.get(0); 367 double[] last = nodes.get(nodes.size()-1); 368 369 ArrayList<double[]> new_nodes = new ArrayList<double[]>(); 370 371 double d = 0; 372 373 for(int i = 1; i < nodes.size(); i++){ 374 d = pointLineDistance(nodes.get(i),first,last); 375 if(d>farthest_dist){ 376 farthest_dist = d; 377 farthest_node = i; 378 } 379 } 380 381 ArrayList<double[]> seg_a = new ArrayList<double[]>(); 382 ArrayList<double[]> seg_b = new ArrayList<double[]>(); 383 384 if(farthest_dist > epsilon){ 385 seg_a = douglasPeucker(sublist(nodes,0,farthest_node+1),epsilon); 386 seg_b = douglasPeucker(sublist(nodes,farthest_node,nodes.size()-1),epsilon); 387 388 new_nodes.addAll(seg_a); 389 new_nodes.addAll(seg_b); 390 } else { 391 new_nodes.add(nodes.get(0)); 392 new_nodes.add(nodes.get(nodes.size()-1)); 393 } 394 return new_nodes; 395 } 396 397 private ArrayList<double[]> sublist(ArrayList<double[]> l, int i, int f) throws ArrayIndexOutOfBoundsException { 398 ArrayList<double[]> sub = new ArrayList<double[]>(); 399 400 if(f<i || i < 0 || f < 0 || f > l.size()){ 401 throw new ArrayIndexOutOfBoundsException(); 402 } 403 404 for(int j = i; j < f; j++){ 405 sub.add(l.get(j)); 406 } 407 return sub; 408 } 409 410 public double[] xy_to_geo(int x, int y, double resolution){ 411 double[] geo = new double[2]; 412 geo[0] = y / resolution; 413 geo[1] = x / resolution; 414 return geo; 415 } 416 417 public int[] geo_to_xy(double lat, double lon, double resolution){ 418 int[] xy = new int[2]; 419 420 xy[0] = (int)Math.floor(lon * resolution + 0.5); 421 xy[1] = (int)Math.floor(lat * resolution + 0.5); 422 423 return xy; 424 } 425 426 /* 427 427 * User has hit the cancel button 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 462 463 464 465 466 467 468 469 470 471 472 473 474 428 */ 429 public void cancel() { 430 cancel = true; 431 } 432 433 protected void setStatus(String s) { 434 Main.pleaseWaitDlg.currentAction.setText(s); 435 Main.pleaseWaitDlg.repaint(); 436 } 437 438 /** 439 * Class to do checking of whether the point is within our bbox 440 * 441 * @author Jason Reid 442 */ 443 private class LakewalkerBBox { 444 445 private double top = 90; 446 private double left = -180; 447 private double bottom = -90; 448 private double right = 180; 449 450 protected LakewalkerBBox(double top, double left, double bottom, double right){ 451 this.left = left; 452 this.right = right; 453 this.top = top; 454 this.bottom = bottom; 455 } 456 457 protected Boolean contains(double lat, double lon){ 458 if(lat >= this.top || lat <= this.bottom){ 459 return false; 460 } 461 if(lon >= this.right || lon <= this.left){ 462 return false; 463 } 464 if((this.right - this.left) % 360 == 0){ 465 return true; 466 } 467 return (lon - this.left) % 360 <= (this.right - this.left) % 360; 468 } 469 } 470 private void printarr(int[] a){ 471 for(int i = 0; i<a.length; i++){ 472 System.out.println(i+": "+a[i]); 473 } 474 } 475 475 } 476 476 -
applications/editors/josm/plugins/lakewalker/src/org/openstreetmap/josm/plugins/lakewalker/LakewalkerAction.java
r12479 r12778 35 35 /** 36 36 * Interface to Darryl Shpak's Lakewalker module 37 * 37 * 38 38 * @author Brent Easton 39 39 */ … … 45 45 protected Thread executeThread; 46 46 protected boolean cancel; 47 47 48 48 protected Collection<Command> commands = new LinkedList<Command>(); 49 49 protected Collection<Way> ways = new ArrayList<Way>(); … … 56 56 setEnabled(true); 57 57 } 58 58 59 59 public void actionPerformed(ActionEvent e) { 60 60 if(Main.map == null || Main.map.mapView == null) … … 78 78 */ 79 79 private void cleanupCache() { 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 80 final long maxCacheAge = System.currentTimeMillis()-Main.pref.getInteger(LakewalkerPreferences.PREF_MAXCACHEAGE, 100)*24*60*60*1000L; 81 final long maxCacheSize = Main.pref.getInteger(LakewalkerPreferences.PREF_MAXCACHESIZE, 300)*1024*1024; 82 83 for (String wmsFolder : LakewalkerPreferences.WMSLAYERS) { 84 String wmsCacheDirName = Main.pref.getPreferencesDir()+"plugins/Lakewalker/"+wmsFolder; 85 File wmsCacheDir = new File(wmsCacheDirName); 86 87 if (wmsCacheDir.exists() && wmsCacheDir.isDirectory()) { 88 File wmsCache[] = wmsCacheDir.listFiles(); 89 90 // sort files by date (most recent first) 91 Arrays.sort(wmsCache, new Comparator<File>() { 92 public int compare(File f1, File f2) { 93 return (int)(f2.lastModified()-f1.lastModified()); 94 } 95 }); 96 97 // delete aged or oversized, keep newest. Once size/age limit was reached delete all older files 98 long folderSize = 0; 99 boolean quickdelete = false; 100 for (File cacheEntry : wmsCache) { 101 if (!cacheEntry.isFile()) continue; 102 if (!quickdelete) { 103 folderSize += cacheEntry.length(); 104 if (folderSize > maxCacheSize) { 105 quickdelete = true; 106 } else if (cacheEntry.lastModified() < maxCacheAge) { 107 quickdelete = true; 108 } 109 } 110 111 if (quickdelete) { 112 cacheEntry.delete(); 113 } 114 } 115 116 } else { 117 // create cache directory 118 if (!wmsCacheDir.mkdirs()) { 119 JOptionPane.showMessageDialog(Main.parent, tr("Error creating cache directory: {0}", wmsCacheDirName)); 120 } 121 } 122 } 123 } 124 125 125 protected void lakewalk(Point clickPoint){ 126 127 128 129 130 131 132 .getHeight()); 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 126 /** 127 * Positional data 128 */ 129 final LatLon pos = Main.map.mapView.getLatLon(clickPoint.x, clickPoint.y); 130 final LatLon topLeft = Main.map.mapView.getLatLon(0, 0); 131 final LatLon botRight = Main.map.mapView.getLatLon(Main.map.mapView.getWidth(), Main.map.mapView 132 .getHeight()); 133 134 /** 135 * Cache/working directory location 136 */ 137 final File working_dir = new File(Main.pref.getPreferencesDir(), "plugins/Lakewalker"); 138 139 /* 140 * Collect options 141 */ 142 final int waylen = Main.pref.getInteger(LakewalkerPreferences.PREF_MAX_SEG, 500); 143 final int maxnode = Main.pref.getInteger(LakewalkerPreferences.PREF_MAX_NODES, 50000); 144 final int threshold = Main.pref.getInteger(LakewalkerPreferences.PREF_THRESHOLD_VALUE, 90); 145 final double epsilon = Main.pref.getDouble(LakewalkerPreferences.PREF_EPSILON, 0.0003); 146 final int resolution = Main.pref.getInteger(LakewalkerPreferences.PREF_LANDSAT_RES, 4000); 147 final int tilesize = Main.pref.getInteger(LakewalkerPreferences.PREF_LANDSAT_SIZE, 2000); 148 final String startdir = Main.pref.get(LakewalkerPreferences.PREF_START_DIR, "east"); 149 final String wmslayer = Main.pref.get(LakewalkerPreferences.PREF_WMS, "IR1"); 150 151 try { 152 152 PleaseWaitRunnable lakewalkerTask = new PleaseWaitRunnable(tr("Tracing")){ 153 153 @Override protected void realRun() throws SAXException { 154 155 156 154 setStatus(tr("checking cache...")); 155 cleanupCache(); 156 processnodelist(pos, topLeft, botRight, waylen,maxnode,threshold,epsilon,resolution,tilesize,startdir,wmslayer,working_dir); 157 157 } 158 158 @Override protected void finish() { 159 159 160 160 } 161 161 @Override protected void cancel() { … … 168 168 catch (Exception ex) { 169 169 System.out.println("Exception caught: " + ex.getMessage()); 170 } 171 } 172 170 } 171 } 172 173 173 private void processnodelist(LatLon pos, LatLon topLeft, LatLon botRight, int waylen, int maxnode, int threshold, double epsilon, int resolution, int tilesize, String startdir, String wmslayer, File workingdir){ 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 try { 241 242 243 244 245 246 247 248 } catch (Exception ex) { 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 174 175 ArrayList<double[]> nodelist = new ArrayList<double[]>(); 176 177 Lakewalker lw = new Lakewalker(waylen,maxnode,threshold,epsilon,resolution,tilesize,startdir,wmslayer,workingdir); 178 try { 179 nodelist = lw.trace(pos.lat(),pos.lon(),topLeft.lon(),botRight.lon(),topLeft.lat(),botRight.lat()); 180 } catch(LakewalkerException e){ 181 System.out.println(e.getError()); 182 } 183 184 System.out.println(nodelist.size()+" nodes generated"); 185 186 /** 187 * Run the nodelist through a vertex reduction algorithm 188 */ 189 190 setStatus(tr("Running vertex reduction...")); 191 192 nodelist = lw.vertexReduce(nodelist, epsilon); 193 194 //System.out.println("After vertex reduction "+nodelist.size()+" nodes remain."); 195 196 /** 197 * And then through douglas-peucker approximation 198 */ 199 200 setStatus(tr("Running Douglas-Peucker approximation...")); 201 202 nodelist = lw.douglasPeucker(nodelist, epsilon); 203 204 //System.out.println("After Douglas-Peucker approximation "+nodelist.size()+" nodes remain."); 205 206 /** 207 * And then through a duplicate node remover 208 */ 209 210 setStatus(tr("Removing duplicate nodes...")); 211 212 nodelist = lw.duplicateNodeRemove(nodelist); 213 214 //System.out.println("After removing duplicate nodes, "+nodelist.size()+" nodes remain."); 215 216 217 // if for some reason (image loading failed, ...) nodelist is empty, no more processing required. 218 if (nodelist.size() == 0) { 219 return; 220 } 221 222 /** 223 * Turn the arraylist into osm nodes 224 */ 225 226 Way way = new Way(); 227 Node n = null; 228 Node fn = null; 229 230 double eastOffset = Main.pref.getDouble(LakewalkerPreferences.PREF_EAST_OFFSET, 0.0); 231 double northOffset = Main.pref.getDouble(LakewalkerPreferences.PREF_NORTH_OFFSET, 0.0); 232 233 int nodesinway = 0; 234 235 for(int i = 0; i< nodelist.size(); i++){ 236 if (cancel) { 237 return; 238 } 239 240 try { 241 LatLon ll = new LatLon(nodelist.get(i)[0]+northOffset, nodelist.get(i)[1]+eastOffset); 242 n = new Node(ll); 243 if(fn==null){ 244 fn = n; 245 } 246 commands.add(new AddCommand(n)); 247 248 } catch (Exception ex) { 249 } 250 251 way.nodes.add(n); 252 253 if(nodesinway > Main.pref.getInteger(LakewalkerPreferences.PREF_MAX_SEG, 500)){ 254 String waytype = Main.pref.get(LakewalkerPreferences.PREF_WAYTYPE, "water"); 255 256 if(!waytype.equals("none")){ 257 way.put("natural",waytype); 258 } 259 260 way.put("created_by", "Dshpak_landsat_lakes"); 261 commands.add(new AddCommand(way)); 262 263 way = new Way(); 264 265 way.nodes.add(n); 266 267 nodesinway = 0; 268 } 269 nodesinway++; 270 } 271 272 273 String waytype = Main.pref.get(LakewalkerPreferences.PREF_WAYTYPE, "water"); 274 275 275 if(!waytype.equals("none")){ 276 277 } 278 276 way.put("natural",waytype); 277 } 278 279 279 way.put("created_by", "Dshpak_landsat_lakes"); 280 281 282 283 284 285 280 281 way.nodes.add(fn); 282 283 commands.add(new AddCommand(way)); 284 285 if (!commands.isEmpty()) { 286 286 Main.main.undoRedo.add(new SequenceCommand(tr("Lakewalker trace"), commands)); 287 287 Main.ds.setSelected(ways); 288 288 } else { 289 290 } 291 292 293 294 295 } 296 289 System.out.println("Failed"); 290 } 291 292 commands = new LinkedList<Command>(); 293 ways = new ArrayList<Way>(); 294 295 } 296 297 297 public void cancel() { 298 298 cancel = true; 299 299 } 300 300 … … 317 317 } 318 318 protected void setStatus(String s) { 319 320 319 Main.pleaseWaitDlg.currentAction.setText(s); 320 Main.pleaseWaitDlg.repaint(); 321 321 } 322 322 } -
applications/editors/josm/plugins/lakewalker/src/org/openstreetmap/josm/plugins/lakewalker/LakewalkerApp.java
r9273 r12778 5 5 6 6 public class LakewalkerApp { 7 8 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 7 public static void main(String[] args){ 8 double lat = 52.31384; 9 double lon = -79.135; 10 double toplat = 52.3165; 11 double botlat = 52.3041; 12 double leftlon = -79.1442; 13 double rightlon = -79.1093; 14 15 // ?lat=39.15579999999999&lon=2.9411&zoom=12&layers=B000F000F 16 lat = 39.1422; 17 lon = 2.9102; 18 19 toplat = 39.2229; 20 botlat = 39.0977; 21 leftlon = 2.8560; 22 rightlon = 3.0462; 23 24 int waylen = 250; 25 int maxnode = 5000; 26 int threshold = 100; 27 double dp = 0.0003; 28 int tilesize = 2000; 29 int resolution = 4000; 30 String startdir = "East"; 31 String wmslayer = "IR2"; 32 33 File working_dir = new File("Lakewalker"); 34 35 ArrayList<double[]> nodelist = null; 36 37 Lakewalker lw = new Lakewalker(waylen,maxnode,threshold,dp,resolution,tilesize,startdir,wmslayer,working_dir); 38 try { 39 nodelist = lw.trace(lat,lon,leftlon,rightlon,toplat,botlat); 40 } catch(LakewalkerException e){ 41 System.out.println(e.getError()); 42 } 43 44 System.out.println(nodelist.size()+" nodes generated"); 45 46 nodelist = lw.vertexReduce(nodelist, dp); 47 48 System.out.println("After vertex reduction, "+nodelist.size()+" nodes remain."); 49 50 nodelist = lw.douglasPeucker(nodelist, dp); 51 52 System.out.println("After dp approximation, "+nodelist.size()+" nodes remain."); 53 54 55 56 } 57 57 } -
applications/editors/josm/plugins/lakewalker/src/org/openstreetmap/josm/plugins/lakewalker/LakewalkerException.java
r6910 r12778 2 2 3 3 class LakewalkerException extends Exception { 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 4 String error; 5 6 public LakewalkerException(){ 7 super(); 8 this.error = "An unknown error has occured"; 9 } 10 11 public LakewalkerException(String err){ 12 super(); 13 this.error = err; 14 } 15 16 public String getError(){ 17 return this.error; 18 } 19 19 } -
applications/editors/josm/plugins/lakewalker/src/org/openstreetmap/josm/plugins/lakewalker/LakewalkerPlugin.java
r12255 r12778 10 10 /** 11 11 * Interface to Darryl Shpak's Lakewalker python module 12 * 12 * 13 13 * @author Brent Easton 14 14 */ … … 18 18 } 19 19 20 public PreferenceSetting getPreferenceSetting() 20 public PreferenceSetting getPreferenceSetting() 21 21 { 22 22 return new LakewalkerPreferences(); -
applications/editors/josm/plugins/lakewalker/src/org/openstreetmap/josm/plugins/lakewalker/LakewalkerReader.java
r10920 r12778 51 51 52 52 try { 53 54 55 53 54 Node n = null; // The current node being created 55 Node tn = null; // The last node of the previous way 56 56 Node fn = null; // Node to hold the first node in the trace 57 57 58 58 while ((line = input.readLine()) != null) { 59 59 if (cancel) { … … 67 67 68 68 if(tn==null){ 69 try { 70 71 72 73 74 75 76 77 78 79 69 try { 70 LatLon ll = new LatLon(Double.parseDouble(tokens[1])+northOffset, Double.parseDouble(tokens[2])+eastOffset); 71 n = new Node(ll); 72 if(fn==null){ 73 fn = n; 74 } 75 commands.add(new AddCommand(n)); 76 } 77 catch (Exception ex) { 78 79 } 80 80 81 81 } else { 82 82 // If there is a last node, and this node has the same coordinates 83 83 // then we substitute for the previous node 84 85 tn = null;84 n = tn; 85 tn = null; 86 86 } 87 88 87 88 way.nodes.add(n); 89 89 90 90 break; … … 98 98 99 99 if(!waytype.equals("none")){ 100 100 way.put("natural",waytype); 101 101 } 102 102 … … 106 106 break; 107 107 108 case 't': 109 110 111 108 case 't': 109 way = new Way(); 110 tn = n; 111 break; 112 112 113 113 case 'e': -
applications/editors/josm/plugins/lakewalker/src/org/openstreetmap/josm/plugins/lakewalker/LakewalkerWMS.java
r11924 r12778 17 17 18 18 public class LakewalkerWMS { 19 20 21 22 23 24 25 26 // Hashmap to hold the mapping of cached images 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 int[] bottom_left_xy = new int[2]; 50 51 52 53 int[] top_right_xy = new int[2]; 19 20 private BufferedImage image; 21 private int imagex; 22 private int imagey; 23 24 // Vector to cache images in memory 25 private Vector<BufferedImage> images = new Vector<BufferedImage>(); 26 // Hashmap to hold the mapping of cached images 27 private HashMap<String,Integer> imageindex = new HashMap<String,Integer>(); 28 29 private int resolution; 30 private int tilesize; 31 32 private String wmslayer; 33 34 private File working_dir; 35 36 public LakewalkerWMS(int resolution, int tilesize, String wmslayer, File workdir){ 37 this.resolution = resolution; 38 this.tilesize = tilesize; 39 this.working_dir = workdir; 40 this.wmslayer = wmslayer; 41 } 42 43 public BufferedImage getTile(int x, int y) throws LakewalkerException { 44 String status = getStatus(); 45 setStatus(tr("Downloading image tile...")); 46 47 String layer = "global_mosaic_base"; 48 49 int[] bottom_left_xy = new int[2]; 50 bottom_left_xy[0] = floor(x,this.tilesize); 51 bottom_left_xy[1] = floor(y,this.tilesize); 52 53 int[] top_right_xy = new int[2]; 54 54 top_right_xy[0] = (int)bottom_left_xy[0] + this.tilesize; 55 55 top_right_xy[1] = (int)bottom_left_xy[1] + this.tilesize; 56 56 57 57 double[] topright_geo = xy_to_geo(top_right_xy[0],top_right_xy[1],this.resolution); 58 58 double[] bottomleft_geo = xy_to_geo(bottom_left_xy[0],bottom_left_xy[1],this.resolution); 59 60 61 62 63 64 59 60 String filename = this.wmslayer+"/landsat_"+this.resolution+"_"+this.tilesize+ 61 "_xy_"+bottom_left_xy[0]+"_"+bottom_left_xy[1]+".png"; 62 63 // The WMS server only understands decimal points using periods, so we need 64 // to convert to a locale that uses that to build the proper URL 65 65 NumberFormat nf = NumberFormat.getInstance(Locale.ENGLISH); 66 67 68 69 70 71 72 73 74 66 DecimalFormat df = (DecimalFormat)nf; 67 df.applyLocalizedPattern("0.000000"); 68 69 String urlloc = "http://onearth.jpl.nasa.gov/wms.cgi?request=GetMap&layers="+layer+ 70 "&styles="+wmslayer+"&srs=EPSG:4326&format=image/png"+ 71 "&bbox="+df.format(bottomleft_geo[1])+","+df.format(bottomleft_geo[0])+ 72 ","+df.format(topright_geo[1])+","+df.format(topright_geo[0])+ 73 "&width="+this.tilesize+"&height="+this.tilesize; 74 75 75 File file = new File(this.working_dir,filename); 76 76 77 77 // Calculate the hashmap key 78 79 78 String hashkey = Integer.toString(bottom_left_xy[0])+":"+Integer.toString(bottom_left_xy[1]); 79 80 80 // See if this image is already loaded 81 if(this.image != null){ 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 } 100 101 try { 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 try { 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 81 if(this.image != null){ 82 if(this.imagex != bottom_left_xy[0] || this.imagey != bottom_left_xy[1]){ 83 84 // Check if this image exists in the hashmap 85 if(this.imageindex.containsKey(hashkey)){ 86 // Store which image we have 87 this.imagex = bottom_left_xy[0]; 88 this.imagey = bottom_left_xy[1]; 89 90 // Retrieve from cache 91 this.image = this.images.get(this.imageindex.get(hashkey)); 92 return this.image; 93 } else { 94 this.image = null; 95 } 96 } else { 97 return this.image; 98 } 99 } 100 101 try { 102 System.out.println("Looking for image in disk cache: "+filename); 103 104 // Read from a file 105 this.image = ImageIO.read(file); 106 107 this.images.add(this.image); 108 this.imageindex.put(hashkey,this.images.size()-1); 109 110 } catch(FileNotFoundException e){ 111 System.out.println("Could not find cached image, downloading."); 112 } catch(IOException e){ 113 System.out.println(e.getMessage()); 114 } catch(Exception e){ 115 System.out.println(e.getMessage()); 116 } 117 118 if(this.image == null){ 119 /** 120 * Try downloading the image 121 */ 122 try { 123 System.out.println("Downloading from "+urlloc); 124 125 // Read from a URL 126 URL url = new URL(urlloc); 127 this.image = ImageIO.read(url); // this can return null! 128 } catch(MalformedURLException e){ 129 System.out.println(e.getMessage()); 130 } catch(IOException e){ 131 System.out.println(e.getMessage()); 132 } catch(Exception e){ 133 System.out.println(e.getMessage()); 134 } 135 136 if (this.image != null) { 137 this.images.add(this.image); 138 this.imageindex.put(hashkey,this.images.size()-1); 139 140 this.saveimage(file,this.image); 141 } 142 } 143 144 this.imagex = bottom_left_xy[0]; 145 this.imagey = bottom_left_xy[1]; 146 147 if(this.image == null){ 148 throw new LakewalkerException(tr("Could not acquire image")); 149 } 150 151 setStatus(status); 152 153 return this.image; 154 } 155 156 public void saveimage(File file, BufferedImage image){ 157 157 /** 158 158 * Save the image to the cache 159 159 */ 160 160 try { 161 162 161 ImageIO.write(image, "png", file); 162 System.out.println("Saved image to cache"); 163 163 } catch(Exception e){ 164 165 } 166 167 168 169 170 171 172 173 174 175 176 177 178 179 throw new LakewalkerException(e.getMessage()); 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 164 System.out.println(e.getMessage()); 165 } 166 } 167 168 public int getPixel(int x, int y) throws LakewalkerException{ 169 170 // Get the previously shown text 171 172 173 BufferedImage image = null; 174 175 try { 176 image = this.getTile(x,y); 177 } catch(LakewalkerException e){ 178 System.out.println(e.getError()); 179 throw new LakewalkerException(e.getMessage()); 180 } 181 182 int tx = floor(x,this.tilesize); 183 int ty = floor(y,this.tilesize); 184 185 int pixel_x = (x-tx); 186 int pixel_y = (this.tilesize-1)-(y-ty); 187 188 //System.out.println("("+x+","+y+") maps to ("+pixel_x+","+pixel_y+") by ("+tx+", "+ty+")"); 189 190 int rgb = image.getRGB(pixel_x,pixel_y); 191 192 int pixel; 193 194 int r = (rgb >> 16) & 0xff; 195 195 int g = (rgb >> 8) & 0xff; 196 196 int b = (rgb >> 0) & 0xff; 197 197 198 198 pixel = (int)((0.30 * r) + (0.59 * b) + (0.11 * g)); 199 200 return pixel; 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 199 200 return pixel; 201 } 202 203 public int floor(int num, int precision){ 204 double dnum = num/(double)precision; 205 BigDecimal val = new BigDecimal(dnum) ; 206 val = val.setScale(0, BigDecimal.ROUND_FLOOR); 207 return val.intValue()*precision; 208 } 209 210 public double floor(double num) { 211 BigDecimal val = new BigDecimal(num) ; 212 val = val.setScale(0, BigDecimal.ROUND_FLOOR); 213 return val.doubleValue() ; 214 } 215 216 public double[] xy_to_geo(int x, int y, double resolution){ 217 double[] geo = new double[2]; 218 geo[0] = y / resolution; 219 geo[1] = x / resolution; 220 return geo; 221 } 222 223 public int[] geo_to_xy(double lat, double lon, double resolution){ 224 int[] xy = new int[2]; 225 226 xy[0] = (int)Math.floor(lon * resolution + 0.5); 227 xy[1] = (int)Math.floor(lat * resolution + 0.5); 228 229 return xy; 230 } 231 232 private void printarr(int[] a){ 233 for(int i = 0; i<a.length; i++){ 234 System.out.println(i+": "+a[i]); 235 } 236 } 237 protected void setStatus(String s) { 238 Main.pleaseWaitDlg.currentAction.setText(s); 239 Main.pleaseWaitDlg.repaint(); 240 } 241 protected String getStatus(){ 242 return Main.pleaseWaitDlg.currentAction.getText(); 243 } 244 244 } -
applications/editors/josm/plugins/lakewalker/src/org/openstreetmap/josm/plugins/lakewalker/StringEnumConfigurer.java
r5979 r12778 96 96 97 97 public void setValidValues(String[] s) { 98 99 100 101 102 98 validValues = s; 99 if (box == null) { 100 getControls(); 101 } 102 box.setModel(new DefaultComboBoxModel(validValues)); 103 103 } 104 104 -
applications/editors/josm/plugins/livegps/livegps/LiveGpsAcquirer.java
r6709 r12778 18 18 19 19 public class LiveGpsAcquirer implements Runnable { 20 21 22 23 24 25 26 20 Socket gpsdSocket; 21 BufferedReader gpsdReader; 22 boolean connected = false; 23 String gpsdHost = "localhost"; 24 int gpsdPort = 2947; 25 String configFile = "liveGPS.conf"; 26 boolean shutdownFlag = false; 27 27 private List<PropertyChangeListener> propertyChangeListener = new ArrayList<PropertyChangeListener>(); 28 28 private PropertyChangeEvent lastStatusEvent; 29 29 private PropertyChangeEvent lastDataEvent; 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 * Adds a property change listener to the acquirer. 30 31 public LiveGpsAcquirer(String pluginDir) { 32 33 Properties liveGPSconfig = new Properties(); 34 35 FileInputStream fis = null; 36 37 try { 38 fis = new FileInputStream(pluginDir + configFile); 39 } catch (FileNotFoundException e) { 40 System.err.println("No liveGPS.conf found, using defaults"); 41 } 42 43 if(fis != null) 44 { 45 try { 46 liveGPSconfig.load(fis); 47 this.gpsdHost = liveGPSconfig.getProperty("host"); 48 this.gpsdPort = Integer.parseInt(liveGPSconfig.getProperty("port")); 49 50 } catch (IOException e) { 51 System.err.println("Error while loading liveGPS.conf, using defaults"); 52 } 53 54 if(this.gpsdHost == null || this.gpsdPort == 0) 55 { 56 System.err.println("Error in liveGPS.conf, using defaults"); 57 this.gpsdHost = "localhost"; 58 this.gpsdPort = 2947; 59 } 60 } 61 62 } 63 64 /** 65 * Adds a property change listener to the acquirer. 66 66 * @param listener the new listener 67 67 */ … … 71 71 } 72 72 } 73 73 74 74 /** 75 75 * Fire a gps status change event. Fires events with key "gpsstatus" and a {@link LiveGpsStatus} … … 87 87 88 88 /** 89 * Fire a gps data change event to all listeners. Fires events with key "gpsdata" and a 89 * Fire a gps data change event to all listeners. Fires events with key "gpsdata" and a 90 90 * {@link LiveGpsData} object as values. 91 91 * @param oldData the old gps data. … … 99 99 } 100 100 } 101 101 102 102 /** 103 103 * Fires the given event to all listeners. … … 107 107 for (PropertyChangeListener listener : propertyChangeListener) { 108 108 listener.propertyChange(event); 109 } 110 } 111 112 public void run() { 113 114 109 } 110 } 111 112 public void run() { 113 LiveGpsData oldGpsData = null; 114 LiveGpsData gpsData = null; 115 115 shutdownFlag = false; 116 117 118 116 while(!shutdownFlag) { 117 double lat = 0; 118 double lon = 0; 119 119 float speed = 0; 120 120 float course = 0; 121 122 123 124 125 126 127 121 boolean haveFix = false; 122 123 try 124 { 125 if (!connected) 126 { 127 System.out.println("LiveGps tries to connect to gpsd"); 128 128 fireGpsStatusChangeEvent(LiveGpsStatus.GpsStatus.CONNECTING, tr("Connecting")); 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 129 InetAddress[] addrs = InetAddress.getAllByName(gpsdHost); 130 for (int i=0; i < addrs.length && gpsdSocket == null; i++) { 131 try { 132 gpsdSocket = new Socket(addrs[i], gpsdPort); 133 break; 134 } catch (Exception e) { 135 System.out.println("LiveGps: Could not open connection to gpsd: " + e); 136 gpsdSocket = null; 137 } 138 } 139 140 if (gpsdSocket != null) 141 { 142 gpsdReader = new BufferedReader(new InputStreamReader(gpsdSocket.getInputStream())); 143 gpsdSocket.getOutputStream().write(new byte[] { 'w', 13, 10 }); 144 144 fireGpsStatusChangeEvent(LiveGpsStatus.GpsStatus.CONNECTING, tr("Connecting")); 145 146 147 148 145 connected = true; 146 System.out.println("LiveGps: Connected to gpsd"); 147 } 148 } 149 149 150 150 … … 153 153 // TODO this read is blocking if gps is connected but has no fix, so gpsd does not send positions 154 154 String line = gpsdReader.readLine(); 155 // </FIXXME> 155 // </FIXXME> 156 156 if (line == null) break; 157 157 String words[] = line.split(","); … … 189 189 } 190 190 break; 191 case 'P': 191 case 'P': 192 192 // position report, tab delimited. 193 193 String[] pos = value.split("\\s+"); … … 217 217 try { Thread.sleep(1000); } catch (InterruptedException ignore) {}; 218 218 } 219 220 221 222 223 224 219 } catch(IOException iox) { 220 connected = false; 221 if(gpsData != null) { 222 gpsData.setFix(false); 223 fireGpsDataChangeEvent(oldGpsData, gpsData); 224 } 225 225 fireGpsStatusChangeEvent(LiveGpsStatus.GpsStatus.CONNECTION_FAILED, tr("Connection Failed")); 226 227 228 229 230 231 226 try { Thread.sleep(1000); } catch (InterruptedException ignore) {}; 227 // send warning to layer 228 229 } 230 } 231 232 232 fireGpsStatusChangeEvent(LiveGpsStatus.GpsStatus.DISCONNECTED, tr("Not connected")); 233 234 try { 235 gpsdSocket.close(); 233 if (gpsdSocket != null) { 234 try { 235 gpsdSocket.close(); 236 236 gpsdSocket = null; 237 238 } 237 System.out.println("LiveGps: Disconnected from gpsd"); 238 } 239 239 catch (Exception e) { 240 240 System.out.println("LiveGps: Unable to close socket; reconnection may not be possible"); 241 241 }; 242 242 } 243 243 } 244 245 246 247 248 244 245 public void shutdown() 246 { 247 shutdownFlag = true; 248 } 249 249 } -
applications/editors/josm/plugins/livegps/livegps/LiveGpsData.java
r3336 r12778 1 1 /** 2 * 2 * 3 3 */ 4 4 package livegps; … … 22 22 private String wayString; 23 23 private Way way; 24 24 25 25 /** 26 26 * @param latitude … … 38 38 } 39 39 /** 40 * 40 * 41 41 */ 42 42 public LiveGpsData() { … … 91 91 this.speed = speed; 92 92 } 93 93 94 94 /** 95 95 * @return the latlon … … 98 98 return this.latLon; 99 99 } 100 100 101 101 /** 102 102 * @param latLon … … 105 105 this.latLon = latLon; 106 106 } 107 107 108 108 public String toString() { 109 return getClass().getSimpleName() + "[fix=" + fix + ", lat=" + latLon.lat() 109 return getClass().getSimpleName() + "[fix=" + fix + ", lat=" + latLon.lat() 110 110 + ", long=" + latLon.lon() + ", speed=" + speed + ", course=" + course + "]"; 111 112 } 113 111 112 } 113 114 114 /** 115 115 * Returns the name of the way that is closest to the current coordinates or an 116 116 * empty string if no way is around. 117 * 117 * 118 118 * @return the name of the way that is closest to the current coordinates. 119 119 */ … … 156 156 return wayString; 157 157 } 158 158 159 159 /** 160 160 * Returns the closest way to this position. … … 163 163 public Way getWay() { 164 164 if(way == null) { 165 EastNorth eastnorth = Main.proj.latlon2eastNorth(getLatLon()); 166 Point xy = Main.map.mapView.getPoint(eastnorth); 165 EastNorth eastnorth = Main.proj.latlon2eastNorth(getLatLon()); 166 Point xy = Main.map.mapView.getPoint(eastnorth); 167 167 way = Main.map.mapView.getNearestWay(xy); 168 168 } 169 169 return way; 170 171 } 172 170 171 } 172 173 173 /* (non-Javadoc) 174 174 * @see java.lang.Object#hashCode() … … 207 207 } 208 208 209 210 209 210 211 211 } -
applications/editors/josm/plugins/livegps/livegps/LiveGpsDialog.java
r11974 r12778 1 1 /** 2 * 2 * 3 3 */ 4 4 package livegps; … … 62 62 add(new JScrollPane(panel), BorderLayout.CENTER); 63 63 } 64 64 65 65 /* (non-Javadoc) 66 66 * @see java.beans.PropertyChangeListener#propertyChange(java.beans.PropertyChangeEvent) … … 79 79 speedLabel.setText((Math.round(mySpeed*100)/100) + "km/h"); // m(s to km/h 80 80 courseLabel.setText(data.getCourse() + "deg"); 81 81 82 82 String wayString = data.getWayInfo(); 83 83 if(wayString.length() > 0) { … … 86 86 wayLabel.setText("unknown"); 87 87 } 88 88 89 89 } else { 90 90 // fixLabel.setText("no fix"); … … 101 101 panel.setBackground(Color.RED); 102 102 } else { 103 panel.setBackground(Color.WHITE); 103 panel.setBackground(Color.WHITE); 104 104 } 105 105 } 106 106 107 107 } 108 109 110 111 108 } -
applications/editors/josm/plugins/livegps/livegps/LiveGpsLayer.java
r11934 r12778 25 25 public static final String LAYER_NAME = tr("LiveGPS layer"); 26 26 public static final String KEY_LIVEGPS_COLOR ="color.livegps.position"; 27 LatLon lastPos; 28 WayPoint lastPoint; 29 GpxTrack trackBeingWritten; 30 Collection<WayPoint> trackSegment; 31 float speed; 32 float course; 33 String status; 34 //JLabel lbl; 35 boolean autocenter; 36 private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS"); 37 38 public LiveGpsLayer(GpxData data) 39 { 40 super (data, LAYER_NAME); 41 trackBeingWritten = new GpxTrack(); 42 trackBeingWritten.attr.put("desc", "josm live gps"); 43 trackSegment = new ArrayList<WayPoint>(); 44 trackBeingWritten.trackSegs.add(trackSegment); 45 data.tracks.add(trackBeingWritten); 46 } 47 48 void setCurrentPosition(double lat, double lon) 49 { 50 //System.out.println("adding pos " + lat + "," + lon); 51 LatLon thisPos = new LatLon(lat, lon); 52 if ((lastPos != null) && (thisPos.equalsEpsilon(lastPos))) { 53 // no change in position 54 // maybe show a "paused" cursor or some such 55 return; 56 } 57 58 lastPos = thisPos; 59 lastPoint = new WayPoint(thisPos); 60 lastPoint.attr.put("time", dateFormat.format(new Date())); 61 // synchronize when adding data, as otherwise the autosave action 62 // needs concurrent access and this results in an exception! 63 synchronized (LiveGpsLock.class) { 64 trackSegment.add(lastPoint); 27 LatLon lastPos; 28 WayPoint lastPoint; 29 GpxTrack trackBeingWritten; 30 Collection<WayPoint> trackSegment; 31 float speed; 32 float course; 33 String status; 34 //JLabel lbl; 35 boolean autocenter; 36 private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS"); 37 38 public LiveGpsLayer(GpxData data) 39 { 40 super (data, LAYER_NAME); 41 trackBeingWritten = new GpxTrack(); 42 trackBeingWritten.attr.put("desc", "josm live gps"); 43 trackSegment = new ArrayList<WayPoint>(); 44 trackBeingWritten.trackSegs.add(trackSegment); 45 data.tracks.add(trackBeingWritten); 46 } 47 48 void setCurrentPosition(double lat, double lon) 49 { 50 //System.out.println("adding pos " + lat + "," + lon); 51 LatLon thisPos = new LatLon(lat, lon); 52 if ((lastPos != null) && (thisPos.equalsEpsilon(lastPos))) { 53 // no change in position 54 // maybe show a "paused" cursor or some such 55 return; 65 56 } 66 if (autocenter) {67 center();68 }69 70 //Main.map.repaint();71 }72 57 73 public void center() 74 { 75 if (lastPoint != null) 76 Main.map.mapView.zoomTo(lastPoint.eastNorth, Main.map.mapView.getScale()); 77 } 78 79 // void setStatus(String status) 80 // { 81 // this.status = status; 82 // Main.map.repaint(); 58 lastPos = thisPos; 59 lastPoint = new WayPoint(thisPos); 60 lastPoint.attr.put("time", dateFormat.format(new Date())); 61 // synchronize when adding data, as otherwise the autosave action 62 // needs concurrent access and this results in an exception! 63 synchronized (LiveGpsLock.class) { 64 trackSegment.add(lastPoint); 65 } 66 if (autocenter) { 67 center(); 68 } 69 70 //Main.map.repaint(); 71 } 72 73 public void center() 74 { 75 if (lastPoint != null) 76 Main.map.mapView.zoomTo(lastPoint.eastNorth, Main.map.mapView.getScale()); 77 } 78 79 // void setStatus(String status) 80 // { 81 // this.status = status; 82 // Main.map.repaint(); 83 83 // System.out.println("LiveGps status: " + status); 84 // } 85 86 void setSpeed(float metresPerSecond) 87 { 88 speed = metresPerSecond; 89 //Main.map.repaint(); 90 } 84 // } 91 85 92 void setCourse(float degrees) 93 { 94 course = degrees; 95 //Main.map.repaint(); 96 } 97 98 public void setAutoCenter(boolean ac) 99 { 100 autocenter = ac; 101 } 86 void setSpeed(float metresPerSecond) 87 { 88 speed = metresPerSecond; 89 //Main.map.repaint(); 90 } 102 91 103 @Override public void paint(Graphics g, MapView mv) 104 { 105 //System.out.println("in paint"); 106 synchronized (LiveGpsLock.class) { 107 //System.out.println("in synced paint"); 108 super.paint(g, mv); 109 // int statusHeight = 50; 110 // Rectangle mvs = mv.getBounds(); 111 // mvs.y = mvs.y + mvs.height - statusHeight; 112 // mvs.height = statusHeight; 113 // g.setColor(new Color(1.0f, 1.0f, 1.0f, 0.8f)); 114 // g.fillRect(mvs.x, mvs.y, mvs.width, mvs.height); 92 void setCourse(float degrees) 93 { 94 course = degrees; 95 //Main.map.repaint(); 96 } 115 97 116 if (lastPoint != null) 117 { 118 Point screen = mv.getPoint(lastPoint.eastNorth); 119 g.setColor(Main.pref.getColor(KEY_LIVEGPS_COLOR, Color.RED)); 120 g.drawOval(screen.x-10, screen.y-10,20,20); 121 g.drawOval(screen.x-9, screen.y-9,18,18); 122 } 98 public void setAutoCenter(boolean ac) 99 { 100 autocenter = ac; 101 } 123 102 124 // lbl.setText("gpsd: "+status+" Speed: " + speed + " Course: "+course); 125 // lbl.setBounds(0, 0, mvs.width-10, mvs.height-10); 126 // Graphics sub = g.create(mvs.x+5, mvs.y+5, mvs.width-10, mvs.height-10); 127 // lbl.paint(sub); 103 @Override public void paint(Graphics g, MapView mv) 104 { 105 //System.out.println("in paint"); 106 synchronized (LiveGpsLock.class) { 107 //System.out.println("in synced paint"); 108 super.paint(g, mv); 109 // int statusHeight = 50; 110 // Rectangle mvs = mv.getBounds(); 111 // mvs.y = mvs.y + mvs.height - statusHeight; 112 // mvs.height = statusHeight; 113 // g.setColor(new Color(1.0f, 1.0f, 1.0f, 0.8f)); 114 // g.fillRect(mvs.x, mvs.y, mvs.width, mvs.height); 128 115 129 // if(status != null) { 130 // g.setColor(Color.WHITE); 131 // g.drawString("gpsd: " + status, 5, mv.getBounds().height - 15); // lower left corner 132 // } 133 } 134 } 135 116 if (lastPoint != null) 117 { 118 Point screen = mv.getPoint(lastPoint.eastNorth); 119 g.setColor(Main.pref.getColor(KEY_LIVEGPS_COLOR, Color.RED)); 120 g.drawOval(screen.x-10, screen.y-10,20,20); 121 g.drawOval(screen.x-9, screen.y-9,18,18); 122 } 123 124 // lbl.setText("gpsd: "+status+" Speed: " + speed + " Course: "+course); 125 // lbl.setBounds(0, 0, mvs.width-10, mvs.height-10); 126 // Graphics sub = g.create(mvs.x+5, mvs.y+5, mvs.width-10, mvs.height-10); 127 // lbl.paint(sub); 128 129 // if(status != null) { 130 // g.setColor(Color.WHITE); 131 // g.drawString("gpsd: " + status, 5, mv.getBounds().height - 15); // lower left corner 132 // } 133 } 134 } 135 136 136 /* (non-Javadoc) 137 137 * @see java.beans.PropertyChangeListener#propertyChange(java.beans.PropertyChangeEvent) … … 154 154 } 155 155 } 156 156 157 157 } 158 158 -
applications/editors/josm/plugins/livegps/livegps/LiveGpsLock.java
r3073 r12778 1 1 /** 2 * 2 * 3 3 */ 4 4 package livegps; … … 8 8 * read or write live gps data must synchronize to this class. Especially the save action 9 9 * takes quite long, so concurrency problems occur. 10 * 10 * 11 11 * @author cdaller 12 12 * -
applications/editors/josm/plugins/livegps/livegps/LiveGpsPlugin.java
r11974 r12778 24 24 public class LiveGpsPlugin extends Plugin 25 25 { 26 27 26 private LiveGpsAcquirer acquirer = null; 27 private Thread acquirerThread = null; 28 28 private JMenu lgpsmenu; 29 29 private JCheckBoxMenuItem lgpscapture; … … 32 32 private LiveGpsDialog lgpsdialog; 33 33 List<PropertyChangeListener>listenerQueue; 34 35 34 35 private GpxData data = new GpxData(); 36 36 private LiveGpsLayer lgpslayer; 37 38 37 38 39 39 public class CaptureAction extends JosmAction { 40 40 public CaptureAction() { … … 77 77 } 78 78 79 public LiveGpsPlugin() 79 public LiveGpsPlugin() 80 80 { 81 81 MainMenu menu = Main.main.menu; … … 111 111 } 112 112 } 113 113 114 114 /** 115 115 * Returns <code>true</code> if autocenter is selected. … … 119 119 return lgpsautocenter.isSelected(); 120 120 } 121 121 122 122 /** 123 123 * Enable or disable gps tracking … … 155 155 } 156 156 } 157 158 157 158 159 159 /** 160 160 * Add a listener for gps events. -
applications/editors/josm/plugins/livegps/livegps/LiveGpsStatus.java
r3073 r12778 1 1 /** 2 * 2 * 3 3 */ 4 4 package livegps; -
applications/editors/josm/plugins/measurement/src/org/openstreetmap/josm/plugins/measurement/MeasurementDialog.java
r12471 r12778 34 34 public class MeasurementDialog extends ToggleDialog implements ActionListener 35 35 { 36 36 private static final long serialVersionUID = 4708541586297950021L; 37 37 38 /** 38 /** 39 39 * The reset button 40 40 */ … … 64 64 * Constructor 65 65 */ 66 public MeasurementDialog() 66 public MeasurementDialog() 67 67 { 68 68 super(tr("Measured values"), "measure", tr("Open the measurement window."), … … 78 78 79 79 JPanel valuePanel = new JPanel(new GridLayout(0,2)); 80 80 81 81 valuePanel.add(new JLabel(tr("Path Length"))); 82 82 83 83 pathLengthLabel = new JLabel("0 m"); 84 84 valuePanel.add(pathLengthLabel); 85 85 86 86 valuePanel.add(new JLabel(tr("Selection Length"))); 87 87 88 88 selectLengthLabel = new JLabel("0 m"); 89 89 valuePanel.add(selectLengthLabel); 90 90 91 91 valuePanel.add(new JLabel(tr("Selection Area"))); 92 92 93 93 selectAreaLabel = new JLabel("0 m\u00b2"); 94 94 valuePanel.add(selectAreaLabel); 95 95 96 96 JLabel angle = new JLabel(tr("Angle")); 97 97 angle.setToolTipText(tr("Angle between two selected Nodes")); 98 98 valuePanel.add(angle); 99 99 100 100 segAngleLabel = new JLabel("- \u00b0"); 101 101 valuePanel.add(segAngleLabel); 102 102 103 103 add(valuePanel, BorderLayout.CENTER); 104 104 105 105 this.setPreferredSize(new Dimension(0, 92)); 106 106 final MeasurementDialog dlg = this; 107 //TODO: is this enough? 107 //TODO: is this enough? 108 108 109 109 Main.ds.selListeners.add(new SelectionChangedListener(){ 110 110 111 112 113 111 public void selectionChanged(Collection<? extends OsmPrimitive> arg0) { 112 double length = 0.0; 113 double segAngle = 0.0; 114 114 double area = 0.0; 115 115 Node lastNode = null; 116 116 for(OsmPrimitive p:arg0){ 117 117 if(p instanceof Node){ 118 118 Node n =(Node)p; … … 132 132 //http://local.wasp.uwa.edu.au/~pbourke/geometry/polyarea/ 133 133 area += (MeasurementLayer.calcX(n.coor) * MeasurementLayer.calcY(lastN.coor)) 134 134 - (MeasurementLayer.calcY(n.coor) * MeasurementLayer.calcX(lastN.coor)); 135 135 } 136 136 lastN = n; … … 142 142 } 143 143 } 144 145 144 } 145 dlg.selectLengthLabel.setText(new DecimalFormat("#0.00").format(length) + " m"); 146 146 147 dlg.segAngleLabel.setText(new DecimalFormat("#0.0").format(segAngle) + " \u00b0"); 148 149 150 151 147 dlg.segAngleLabel.setText(new DecimalFormat("#0.0").format(segAngle) + " \u00b0"); 148 dlg.selectAreaLabel.setText(new DecimalFormat("#0.00").format(area) + " m\u00b2"); 149 } 150 }); 151 } 152 152 153 public void actionPerformed(ActionEvent e) 154 155 156 157 158 159 160 161 162 163 164 165 166 167 153 public void actionPerformed(ActionEvent e) 154 { 155 String actionCommand = e.getActionCommand(); 156 if( actionCommand.equals("Reset")){ 157 resetValues(); 158 } 159 } 160 161 /** 162 * Cleans the active Meausurement Layer 163 */ 164 public void resetValues(){ 165 MeasurementPlugin.getCurrentLayer().reset(); 166 } 167 168 168 } -
applications/editors/josm/plugins/measurement/src/org/openstreetmap/josm/plugins/measurement/MeasurementLayer.java
r12473 r12778 1 1 package org.openstreetmap.josm.plugins.measurement; 2 /// @author Raphael Mack <ramack@raphael-mack.de> 2 /// @author Raphael Mack <ramack@raphael-mack.de> 3 3 import static org.openstreetmap.josm.tools.I18n.tr; 4 4 … … 53 53 */ 54 54 public class MeasurementLayer extends Layer { 55 55 56 56 public MeasurementLayer(String arg0) { 57 57 super(arg0); 58 58 } 59 59 60 private static Icon icon = new ImageIcon(Toolkit.getDefaultToolkit().createImage(MeasurementPlugin.class.getResource("/images/measurement.png"))); 60 private static Icon icon = new ImageIcon(Toolkit.getDefaultToolkit().createImage(MeasurementPlugin.class.getResource("/images/measurement.png"))); 61 61 private Collection<WayPoint> points = new ArrayList<WayPoint>(32); 62 62 63 63 @Override public Icon getIcon() { 64 64 return icon; 65 65 } 66 66 67 67 @Override public String getToolTipText() { 68 68 return tr("Layer to make measurements"); … … 76 76 @Override public void mergeFrom(Layer from) { 77 77 // TODO: nyi - doubts about how this should be done are around. Ideas? 78 78 79 79 } 80 80 … … 110 110 new JMenuItem(new LayerListPopup.InfoAction(this))}; 111 111 } 112 112 113 113 public void removeLastPoint(){ 114 114 WayPoint l = null; … … 116 116 if(l != null) points.remove(l); 117 117 recalculate(); 118 Main.map.repaint(); 119 } 120 121 public void mouseClicked(MouseEvent e){ 118 Main.map.repaint(); 119 } 120 121 public void mouseClicked(MouseEvent e){ 122 122 if (e.getButton() != MouseEvent.BUTTON1) return; 123 123 124 LatLon coor = Main.map.mapView.getLatLon(e.getX(), e.getY()); 124 LatLon coor = Main.map.mapView.getLatLon(e.getX(), e.getY()); 125 125 points.add(new WayPoint(coor)); 126 126 … … 132 132 points.clear(); 133 133 recalculate(); 134 Main.map.repaint(); 135 } 136 134 Main.map.repaint(); 135 } 136 137 137 private void recalculate(){ 138 138 double pathLength = 0.0, segLength = 0.0; // in meters 139 139 WayPoint last = null; 140 140 141 141 pathLength = 0.0; 142 142 for(WayPoint p : points){ … … 151 151 MeasurementPlugin.measurementDialog.pathLengthLabel.setText(pathLength < 800?nf2.format(pathLength) + " m":nf.format(pathLength/1000) + " km"); 152 152 } 153 153 154 154 public static double calcDistance(LatLon p1, LatLon p2){ 155 155 double lat1, lon1, lat2, lon2; 156 156 double dlon, dlat; 157 157 158 158 lat1 = p1.lat() * Math.PI / 180.0; 159 159 lon1 = p1.lon() * Math.PI / 180.0; … … 172 172 double lat1, lon1, lat2, lon2; 173 173 double dlon, dlat; 174 174 175 175 lat1 = p1.lat() * Math.PI / 180.0; 176 176 lon1 = p1.lon() * Math.PI / 180.0; … … 185 185 return 6367000 * c; 186 186 } 187 187 188 188 public static double calcY(LatLon p1){ 189 189 double lat1, lon1, lat2, lon2; 190 190 double dlon, dlat; 191 191 192 192 lat1 = p1.lat() * Math.PI / 180.0; 193 193 lon1 = p1.lon() * Math.PI / 180.0; … … 202 202 return 6367000 * c; 203 203 } 204 204 205 205 public static double calcDistance(WayPoint p1, WayPoint p2){ 206 206 return calcDistance(p1.latlon, p2.latlon); 207 207 } 208 208 209 209 public static double angleBetween(WayPoint p1, WayPoint p2){ 210 210 return angleBetween(p1.latlon, p2.latlon); 211 211 } 212 212 213 213 public static double angleBetween(LatLon p1, LatLon p2){ 214 214 double lat1, lon1, lat2, lon2; 215 215 double dlon; 216 216 double heading; 217 217 218 218 lat1 = p1.lat() * Math.PI / 180.0; 219 219 lon1 = p1.lon() * Math.PI / 180.0; … … 223 223 dlon = lon2 - lon1; 224 224 double coslat2 = Math.cos(lat2); 225 225 226 226 return (180 * Math.atan2(coslat2 * Math.sin(dlon), 227 227 (Math.cos(lat1) * Math.sin(lat2) 228 - 228 - 229 229 Math.sin(lat1) * coslat2 * Math.cos(dlon)))) / Math.PI; 230 230 } … … 234 234 double dlon, dlat; 235 235 double heading; 236 236 237 237 lat1 = p1.lat() * Math.PI / 180.0; 238 238 lon1 = p1.lon() * Math.PI / 180.0; … … 250 250 heading = 2 * Math.PI - heading; 251 251 } 252 252 253 253 return heading * 180 / Math.PI; 254 254 } … … 257 257 private class GPXLayerImportAction extends AbstractAction { 258 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 if(l instanceof GpxLayer){ 259 private MeasurementLayer layer; 260 261 /** 262 * The data model for the list component. 263 */ 264 private DefaultListModel model = new DefaultListModel(); 265 266 /** 267 * @param layer the targeting measurement layer 268 */ 269 public GPXLayerImportAction(MeasurementLayer layer) { 270 super(tr("Import path from GPX layer"), ImageProvider.get("dialogs", "edit")); // TODO: find better image 271 this.layer = layer; 272 } 273 274 public void actionPerformed(ActionEvent e) { 275 Box panel = Box.createVerticalBox(); 276 final JList layerList = new JList(model); 277 Collection<Layer> data = Main.map.mapView.getAllLayers(); 278 Layer lastLayer = null; 279 int layerCnt = 0; 280 281 for (Layer l : data){ 282 if(l instanceof GpxLayer){ 283 283 model.addElement(l); 284 284 lastLayer = l; 285 285 layerCnt++; 286 286 } 287 288 287 } 288 if(layerCnt == 1){ 289 289 layerList.setSelectedValue(lastLayer, true); 290 290 } … … 304 304 305 305 JCheckBox dropFirst = new JCheckBox(tr("Drop existing path")); 306 306 307 307 panel.add(layerList); 308 308 panel.add(dropFirst); 309 309 310 310 final JOptionPane optionPane = new JOptionPane(panel, JOptionPane.QUESTION_MESSAGE, JOptionPane.OK_CANCEL_OPTION){ 311 311 @Override public void selectInitialValue() { … … 315 315 final JDialog dlg = optionPane.createDialog(Main.parent, tr("Import path from GPX layer")); 316 316 dlg.setVisible(true); 317 317 318 318 Object answer = optionPane.getValue(); 319 319 if (answer == null || answer == JOptionPane.UNINITIALIZED_VALUE || … … 326 326 points = new ArrayList<WayPoint>(32); 327 327 } 328 328 329 329 for (GpxTrack trk : gpx.data.tracks) { 330 330 for (Collection<WayPoint> trkseg : trk.trackSegs) { … … 333 333 } 334 334 } 335 335 } 336 336 recalculate(); 337 337 Main.parent.repaint(); -
applications/editors/josm/plugins/measurement/src/org/openstreetmap/josm/plugins/measurement/MeasurementMode.java
r12471 r12778 15 15 public class MeasurementMode extends MapMode { 16 16 17 private static final long serialVersionUID = 3853830673475744263L; 18 19 public MeasurementMode(MapFrame mapFrame, String name, String desc) { 20 super(name, "measurement.png", desc, mapFrame, Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR)); 21 } 17 private static final long serialVersionUID = 3853830673475744263L; 22 18 23 @Override public void enterMode() { 24 super.enterMode(); 25 Main.map.mapView.addMouseListener(this); 26 } 19 public MeasurementMode(MapFrame mapFrame, String name, String desc) { 20 super(name, "measurement.png", desc, mapFrame, Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR)); 21 } 27 22 28 @Override public void exitMode() {29 super.exitMode();30 Main.map.mapView.removeMouseListener(this);31 23 @Override public void enterMode() { 24 super.enterMode(); 25 Main.map.mapView.addMouseListener(this); 26 } 32 27 33 /** 34 * If user clicked with the left button, add a node at the current mouse 35 * position. 36 * 37 * If in nodesegment mode, add the node to the line segment by splitting the 38 * segment. The new created segment will be inserted in every way the segment 39 * was part of. 40 */ 41 @Override public void mouseClicked(MouseEvent e) { 42 if (e.getButton() == MouseEvent.BUTTON3){ 43 MeasurementPlugin.getCurrentLayer().removeLastPoint(); 44 }else if (e.getButton() == MouseEvent.BUTTON1){ 45 LatLon coor = Main.map.mapView.getLatLon(e.getX(), e.getY()); 46 if (coor.isOutSideWorld()) { 47 JOptionPane.showMessageDialog(Main.parent,tr("Can not draw outside of the world.")); 48 return; 49 } 50 MeasurementPlugin.getCurrentLayer().mouseClicked(e); 51 } 52 } 28 @Override public void exitMode() { 29 super.exitMode(); 30 Main.map.mapView.removeMouseListener(this); 31 } 32 33 /** 34 * If user clicked with the left button, add a node at the current mouse 35 * position. 36 * 37 * If in nodesegment mode, add the node to the line segment by splitting the 38 * segment. The new created segment will be inserted in every way the segment 39 * was part of. 40 */ 41 @Override public void mouseClicked(MouseEvent e) { 42 if (e.getButton() == MouseEvent.BUTTON3){ 43 MeasurementPlugin.getCurrentLayer().removeLastPoint(); 44 }else if (e.getButton() == MouseEvent.BUTTON1){ 45 LatLon coor = Main.map.mapView.getLatLon(e.getX(), e.getY()); 46 if (coor.isOutSideWorld()) { 47 JOptionPane.showMessageDialog(Main.parent,tr("Can not draw outside of the world.")); 48 return; 49 } 50 MeasurementPlugin.getCurrentLayer().mouseClicked(e); 51 } 52 } 53 53 54 54 } -
applications/editors/josm/plugins/measurement/src/org/openstreetmap/josm/plugins/measurement/MeasurementPlugin.java
r12473 r12778 12 12 public class MeasurementPlugin extends Plugin { 13 13 14 private IconToggleButton btn; 15 private MeasurementMode mode; 16 protected static MeasurementDialog measurementDialog; 17 protected static MeasurementLayer currentLayer; 18 19 public MeasurementPlugin() { 20 mode = new MeasurementMode(Main.map, "measurement", tr("measurement mode")); 21 btn = new IconToggleButton(mode); 22 btn.setVisible(true); 23 measurementDialog = new MeasurementDialog(); 24 } 25 26 @Override 27 public void mapFrameInitialized(MapFrame oldFrame, MapFrame newFrame) { 28 if(newFrame != null) 29 newFrame.addToggleDialog(measurementDialog); 30 if(Main.map != null) 31 Main.map.addMapMode(btn); 32 } 14 private IconToggleButton btn; 15 private MeasurementMode mode; 16 protected static MeasurementDialog measurementDialog; 17 protected static MeasurementLayer currentLayer; 33 18 34 public static MeasurementLayer getCurrentLayer(){ 35 if(currentLayer == null){ 36 currentLayer = new MeasurementLayer(tr("Measurements")); 37 Main.main.addLayer(currentLayer); 38 currentLayer.listeners.add(new LayerChangeListener(){ 39 public void activeLayerChange(final Layer oldLayer, final Layer newLayer) { 40 if(newLayer instanceof MeasurementLayer) 41 MeasurementPlugin.currentLayer = (MeasurementLayer)newLayer; 42 } 43 public void layerAdded(final Layer newLayer) { 44 } 45 public void layerRemoved(final Layer oldLayer) { 46 } 47 }); 48 } 49 return currentLayer; 50 } 19 public MeasurementPlugin() { 20 mode = new MeasurementMode(Main.map, "measurement", tr("measurement mode")); 21 btn = new IconToggleButton(mode); 22 btn.setVisible(true); 23 measurementDialog = new MeasurementDialog(); 24 } 25 26 @Override 27 public void mapFrameInitialized(MapFrame oldFrame, MapFrame newFrame) { 28 if(newFrame != null) 29 newFrame.addToggleDialog(measurementDialog); 30 if(Main.map != null) 31 Main.map.addMapMode(btn); 32 } 33 34 public static MeasurementLayer getCurrentLayer(){ 35 if(currentLayer == null){ 36 currentLayer = new MeasurementLayer(tr("Measurements")); 37 Main.main.addLayer(currentLayer); 38 currentLayer.listeners.add(new LayerChangeListener(){ 39 public void activeLayerChange(final Layer oldLayer, final Layer newLayer) { 40 if(newLayer instanceof MeasurementLayer) 41 MeasurementPlugin.currentLayer = (MeasurementLayer)newLayer; 42 } 43 public void layerAdded(final Layer newLayer) { 44 } 45 public void layerRemoved(final Layer oldLayer) { 46 } 47 }); 48 } 49 return currentLayer; 50 } 51 51 } -
applications/editors/josm/plugins/namefinder/namefinder/NameFinderPlugin.java
r2925 r12778 10 10 /** 11 11 * Main class for the name finder plugin. 12 * 13 * 12 * 13 * 14 14 * @author Frederik Ramm <frederik@remote.org> 15 15 * 16 16 */ 17 public class NameFinderPlugin extends Plugin 18 { 19 public NameFinderPlugin() 17 public class NameFinderPlugin extends Plugin 18 { 19 public NameFinderPlugin() 20 20 { 21 21 } 22 23 @Override public void addDownloadSelection(List<DownloadSelection> list) 22 23 @Override public void addDownloadSelection(List<DownloadSelection> list) 24 24 { 25 25 list.add(new PlaceSelection()); 26 26 } 27 27 28 28 } -
applications/editors/josm/plugins/namefinder/namefinder/PlaceSelection.java
r12563 r12778 42 42 public class PlaceSelection implements DownloadSelection { 43 43 44 45 46 47 48 49 50 51 52 53 54 55 class SearchResult 56 57 58 59 60 61 62 63 64 65 66 67 * A very primitive parser for the name finder's output. 68 69 70 71 72 73 74 75 76 77 78 * 79 80 @Override public void startElement(String namespaceURI, String localName, String qName, Attributes atts) throws SAXException 81 82 83 try 84 85 if (qName.equals("searchresults")) 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 catch (NumberFormatException x) 113 114 115 116 } 117 catch (NullPointerException x) 118 119 120 121 122 123 /** 124 125 126 127 128 129 if (qName.equals("searchresults")) 130 131 132 133 134 135 136 137 138 139 140 /** 141 142 143 144 145 if (description != null) 146 147 148 149 150 151 152 153 * This queries David Earl's server. Needless to say, stuff should be configurable, and 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 catch (Exception x) 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 44 private JTextField searchTerm = new JTextField(); 45 private JButton submitSearch = new JButton(tr("Search...")); 46 private DefaultTableModel searchResults = new DefaultTableModel() { 47 @Override public boolean isCellEditable(int row, int col) { return false; } 48 }; 49 private JTable searchResultDisplay = new JTable(searchResults); 50 private boolean updatingSelf; 51 52 /** 53 * Data storage for search results. 54 */ 55 class SearchResult 56 { 57 public String name; 58 public String type; 59 public String nearestPlace; 60 public String description; 61 public double lat; 62 public double lon; 63 public int zoom; 64 } 65 66 /** 67 * A very primitive parser for the name finder's output. 68 * Structure of xml described here: http://wiki.openstreetmap.org/index.php/Name_finder 69 * 70 */ 71 private class Parser extends DefaultHandler 72 { 73 private SearchResult currentResult = null; 74 private StringBuffer description = null; 75 private int depth = 0; 76 /** 77 * Detect starting elements. 78 * 79 */ 80 @Override public void startElement(String namespaceURI, String localName, String qName, Attributes atts) throws SAXException 81 { 82 depth++; 83 try 84 { 85 if (qName.equals("searchresults")) 86 { 87 searchResults.setRowCount(0); 88 } 89 else if (qName.equals("named") && (depth == 2)) 90 { 91 currentResult = new PlaceSelection.SearchResult(); 92 currentResult.name = atts.getValue("name"); 93 currentResult.type = atts.getValue("info"); 94 currentResult.lat = Double.parseDouble(atts.getValue("lat")); 95 currentResult.lon = Double.parseDouble(atts.getValue("lon")); 96 currentResult.zoom = Integer.parseInt(atts.getValue("zoom")); 97 searchResults.addRow(new Object[] { currentResult, currentResult, currentResult, currentResult }); 98 } 99 else if (qName.equals("description") && (depth == 3)) 100 { 101 description = new StringBuffer(); 102 } 103 else if (qName.equals("named") && (depth == 4)) 104 { 105 // this is a "named" place in the nearest places list. 106 String info = atts.getValue("info"); 107 if ("city".equals(info) || "town".equals(info) || "village".equals(info)) { 108 currentResult.nearestPlace = atts.getValue("name"); 109 } 110 } 111 } 112 catch (NumberFormatException x) 113 { 114 x.printStackTrace(); // SAXException does not chain correctly 115 throw new SAXException(x.getMessage(), x); 116 } 117 catch (NullPointerException x) 118 { 119 x.printStackTrace(); // SAXException does not chain correctly 120 throw new SAXException(tr("NullPointerException, Possibly some missing tags."), x); 121 } 122 } 123 /** 124 * Detect ending elements. 125 */ 126 @Override public void endElement(String namespaceURI, String localName, String qName) throws SAXException 127 { 128 129 if (qName.equals("searchresults")) 130 { 131 } 132 else if (qName.equals("description") && description != null) 133 { 134 currentResult.description = description.toString(); 135 description = null; 136 } 137 depth--; 138 139 } 140 /** 141 * Read characters for description. 142 */ 143 @Override public void characters(char[] data, int start, int length) throws org.xml.sax.SAXException 144 { 145 if (description != null) 146 { 147 description.append(data, start, length); 148 } 149 } 150 } 151 152 /** 153 * This queries David Earl's server. Needless to say, stuff should be configurable, and 154 * error handling improved. 155 */ 156 public void queryServer(final JComponent component) 157 { 158 final Cursor oldCursor = component.getCursor(); 159 160 // had to put this in a thread as it wouldn't update the cursor properly before. 161 Runnable r = new Runnable() { 162 public void run() { 163 try 164 { 165 String searchtext = searchTerm.getText(); 166 if(searchtext.length()==0) 167 { 168 JOptionPane.showMessageDialog(Main.parent,tr("Please enter a search string")); 169 } 170 else 171 { 172 component.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); 173 component.repaint(); 174 URL url = new URL("http://gazetteer.openstreetmap.org/namefinder/search.xml?find=" 175 +java.net.URLEncoder.encode(searchTerm.getText(), "UTF-8")); 176 HttpURLConnection activeConnection = (HttpURLConnection)url.openConnection(); 177 //System.out.println("got return: "+activeConnection.getResponseCode()); 178 activeConnection.setConnectTimeout(15000); 179 InputStream inputStream = activeConnection.getInputStream(); 180 InputSource inputSource = new InputSource(new InputStreamReader(inputStream, "UTF-8")); 181 SAXParserFactory.newInstance().newSAXParser().parse(inputSource, new Parser()); 182 } 183 } 184 catch (Exception x) 185 { 186 JOptionPane.showMessageDialog(Main.parent,tr("Cannot read place search results from server")); 187 x.printStackTrace(); 188 } 189 component.setCursor(oldCursor); 190 } 191 }; 192 new Thread(r).start(); 193 } 194 195 /** 196 * Adds a new tab to the download dialog in JOSM. 197 * 198 * This method is, for all intents and purposes, the constructor for this class. 199 */ 200 public void addGui(final DownloadDialog gui) { 201 JPanel panel = new JPanel(); 202 panel.setLayout(new GridBagLayout()); 203 204 // this is manually tuned so that it looks nice on a GNOME 205 // desktop - maybe needs some cross platform proofing. 206 panel.add(new JLabel(tr("Enter a place name to search for:")), GBC.eol().insets(5, 5, 5, 5)); 207 panel.add(searchTerm, GBC.std().fill(GBC.BOTH).insets(5, 0, 5, 4)); 208 panel.add(submitSearch, GBC.eol().insets(5, 0, 5, 5)); 209 Dimension btnSize = submitSearch.getPreferredSize(); 210 btnSize.setSize(btnSize.width, btnSize.height * 0.8); 211 submitSearch.setPreferredSize(btnSize); 212 213 GBC c = GBC.std().fill().insets(5, 0, 5, 5); 214 c.gridwidth = 2; 215 JScrollPane scrollPane = new JScrollPane(searchResultDisplay); 216 scrollPane.setPreferredSize(new Dimension(200,200)); 217 panel.add(scrollPane, c); 218 gui.tabpane.add(panel, tr("Places")); 219 220 scrollPane.setPreferredSize(scrollPane.getPreferredSize()); 221 222 // when the button is clicked 223 submitSearch.addActionListener(new ActionListener() { 224 public void actionPerformed(ActionEvent e) { 225 queryServer(gui); 226 } 227 }); 228 229 searchTerm.addActionListener(new ActionListener() { 230 public void actionPerformed(ActionEvent e) { 231 queryServer(gui); 232 } 233 }); 234 235 searchResults.addColumn(tr("name")); 236 searchResults.addColumn(tr("type")); 237 searchResults.addColumn(tr("near")); 238 searchResults.addColumn(tr("zoom")); 239 240 // TODO - this is probably not the coolest way to set relative sizes? 241 searchResultDisplay.getColumn(tr("name")).setPreferredWidth(200); 242 searchResultDisplay.getColumn(tr("type")).setPreferredWidth(100); 243 searchResultDisplay.getColumn(tr("near")).setPreferredWidth(100); 244 searchResultDisplay.getColumn(tr("zoom")).setPreferredWidth(50); 245 searchResultDisplay.getSelectionModel().setSelectionMode(ListSelectionModel.SINGLE_SELECTION); 246 247 // display search results in a table. for simplicity, the table contains 248 // the same SearchResult object in each of the four columns, but it is rendered 249 // differently depending on the column. 250 searchResultDisplay.setDefaultRenderer(Object.class, new DefaultTableCellRenderer() { 251 @Override public Component getTableCellRendererComponent(JTable table, Object value, 252 252 boolean isSelected, boolean hasFocus, int row, int column) { 253 254 255 256 257 case 0: 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 try 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 253 super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column); 254 if (value != null) { 255 SearchResult sr = (SearchResult) value; 256 switch(column) { 257 case 0: 258 setText(sr.name); 259 break; 260 case 1: 261 setText(sr.type); 262 break; 263 case 2: 264 setText(sr.nearestPlace); 265 break; 266 case 3: 267 setText(Integer.toString(sr.zoom)); 268 break; 269 } 270 setToolTipText("<html>"+((SearchResult)value).description+"</html>"); 271 } 272 return this; 273 } 274 }); 275 276 // if item is selected in list, notify dialog 277 searchResultDisplay.getSelectionModel().addListSelectionListener(new ListSelectionListener() { 278 public void valueChanged(ListSelectionEvent lse) { 279 if (lse.getValueIsAdjusting()) return; 280 SearchResult r = null; 281 try 282 { 283 r = (SearchResult) searchResults.getValueAt(lse.getFirstIndex(), 0); 284 } 285 catch (Exception x) 286 { 287 // Ignore 288 } 289 if (r != null) 290 { 291 double size = 180.0 / Math.pow(2, r.zoom); 292 gui.minlat = r.lat - size / 2; 293 gui.maxlat = r.lat + size / 2; 294 gui.minlon = r.lon - size; 295 gui.maxlon = r.lon + size; 296 updatingSelf = true; 297 gui.boundingBoxChanged(null); 298 updatingSelf = false; 299 } 300 } 301 }); 302 303 // TODO - we'd like to finish the download dialog upon double-click but 304 // don't know how to bypass the JOptionPane in which the whole thing is 305 // displayed. 306 searchResultDisplay.addMouseListener(new MouseAdapter() { 307 @Override public void mouseClicked(MouseEvent e) { 308 if (e.getClickCount() > 1) { 309 if (searchResultDisplay.getSelectionModel().getMinSelectionIndex() > -1) { 310 // add sensible action here. 311 } 312 } 313 } 314 }); 315 316 } 317 318 // if bounding box selected on other tab, de-select item 319 public void boundingBoxChanged(DownloadDialog gui) { 320 if (!updatingSelf) searchResultDisplay.clearSelection(); 321 } 322 322 } -
applications/editors/josm/plugins/navigator/src/at/dallermassl/josm/plugin/navigator/JosmEdgeFactory.java
r3686 r12778 1 1 /** 2 * 2 * 3 3 */ 4 4 package at.dallermassl.josm.plugin.navigator; … … 13 13 public class JosmEdgeFactory implements EdgeFactory<Node, WayEdge> { 14 14 15 15 16 16 17 17 /* (non-Javadoc) -
applications/editors/josm/plugins/navigator/src/at/dallermassl/josm/plugin/navigator/NavigatorAction.java
r3749 r12778 1 1 /** 2 * 2 * 3 3 */ 4 4 package at.dallermassl.josm.plugin.navigator; … … 28 28 super(tr("Navigate")); 29 29 this.navigatorPlugin = navigatorPlugin; 30 30 31 31 } 32 32 -
applications/editors/josm/plugins/navigator/src/at/dallermassl/josm/plugin/navigator/NavigatorLayer.java
r3891 r12778 1 1 /** 2 * 2 * 3 3 */ 4 4 package at.dallermassl.josm.plugin.navigator; … … 29 29 /** 30 30 * @author cdaller 31 * 31 * 32 32 */ 33 33 public class NavigatorLayer extends Layer { … … 43 43 /** 44 44 * Constructor 45 * 45 * 46 46 * @param name 47 47 * the name of the layer. … … 53 53 /* 54 54 * (non-Javadoc) 55 * 55 * 56 56 * @see org.openstreetmap.josm.gui.layer.Layer#getIcon() 57 57 */ … … 64 64 /* 65 65 * (non-Javadoc) 66 * 66 * 67 67 * @see org.openstreetmap.josm.gui.layer.Layer#getInfoComponent() 68 68 */ … … 74 74 /* 75 75 * (non-Javadoc) 76 * 76 * 77 77 * @see org.openstreetmap.josm.gui.layer.Layer#getMenuEntries() 78 78 */ … … 85 85 /* 86 86 * (non-Javadoc) 87 * 87 * 88 88 * @see org.openstreetmap.josm.gui.layer.Layer#getToolTipText() 89 89 */ … … 95 95 /* 96 96 * (non-Javadoc) 97 * 97 * 98 98 * @see org.openstreetmap.josm.gui.layer.Layer#isMergable(org.openstreetmap.josm.gui.layer.Layer) 99 99 */ … … 105 105 /* 106 106 * (non-Javadoc) 107 * 107 * 108 108 * @see org.openstreetmap.josm.gui.layer.Layer#mergeFrom(org.openstreetmap.josm.gui.layer.Layer) 109 109 */ … … 115 115 /* 116 116 * (non-Javadoc) 117 * 117 * 118 118 * @see org.openstreetmap.josm.gui.layer.Layer#paint(java.awt.Graphics, 119 119 * org.openstreetmap.josm.gui.MapView) … … 125 125 return; 126 126 } 127 127 128 128 if(startIcon == null) { 129 129 startIcon = ImageProvider.get("navigation", "startflag"); … … 135 135 Point screen = mv.getPoint(node.eastNorth); 136 136 startIcon.paintIcon(mv, g, screen.x, screen.y - startIcon.getIconHeight()); 137 137 138 138 // middle icons: 139 139 for(int index = 1; index < nodes.size() - 1; ++index) { … … 148 148 endIcon.paintIcon(mv, g, screen.x, screen.y - endIcon.getIconHeight()); 149 149 } 150 150 151 151 String colorString = Main.pref.get(KEY_ROUTE_COLOR); 152 152 if(colorString.length() == 0) { … … 170 170 } 171 171 } 172 172 173 173 /** 174 174 * Draw a line with the given color. … … 183 183 } else { 184 184 from = mv.getPoint(edge.getSegment().to.eastNorth); 185 to = mv.getPoint(edge.getSegment().from.eastNorth); 186 } 187 185 to = mv.getPoint(edge.getSegment().from.eastNorth); 186 } 187 188 188 Rectangle screen = g.getClipBounds(); 189 189 Line2D line = new Line2D.Double(from.x, from.y, to.x, to.y); … … 206 206 /* 207 207 * (non-Javadoc) 208 * 208 * 209 209 * @see org.openstreetmap.josm.gui.layer.Layer#visitBoundingBox(org.openstreetmap.josm.data.osm.visitor.BoundingXYVisitor) 210 210 */ … … 225 225 226 226 /** 227 * 227 * 228 228 */ 229 229 public void navigate() { … … 235 235 Main.pref.put(KEY_ROUTE_SELECT, selectString); 236 236 } 237 237 238 238 if(Boolean.parseBoolean(selectString)) { 239 239 List<Segment> path = navigatorNodeModel.getSegmentPath(); … … 244 244 } 245 245 } 246 Main.map.repaint(); 246 Main.map.repaint(); 247 247 } 248 248 -
applications/editors/josm/plugins/navigator/src/at/dallermassl/josm/plugin/navigator/NavigatorModeAction.java
r12707 r12778 1 1 /** 2 * 2 * 3 3 */ 4 4 package at.dallermassl.josm.plugin.navigator; … … 24 24 private NavigatorLayer navigatorLayer; 25 25 private boolean layerAdded; 26 26 27 27 public NavigatorModeAction(MapFrame mapFrame, NavigatorModel navigatorModel, NavigatorLayer navigationLayer) { 28 28 super(tr("Navigator"), "navigation", tr("Set start/end for routing. Middle mouse button to reset."), KeyEvent.VK_F, mapFrame, ImageProvider.getCursor("crosshair", "selection")); … … 30 30 this.navigatorLayer = navigationLayer; 31 31 } 32 32 33 33 @Override public void enterMode() { 34 34 super.enterMode(); … … 50 50 if (e.getButton() == MouseEvent.BUTTON2) { 51 51 navigatorModel.reset(); 52 } else if (e.getButton() == MouseEvent.BUTTON1) { 52 } else if (e.getButton() == MouseEvent.BUTTON1) { 53 53 Node node = Main.map.mapView.getNearestNode(e.getPoint()); 54 54 System.out.println("selected node " + node); -
applications/editors/josm/plugins/navigator/src/at/dallermassl/josm/plugin/navigator/NavigatorModel.java
r3865 r12778 1 1 /** 2 * 2 * 3 3 */ 4 4 package at.dallermassl.josm.plugin.navigator; … … 36 36 highwayWeight = new HashMap<String, Double>(); 37 37 } 38 38 39 39 /** 40 40 * Set the weight for the given highway type. The higher the weight is, … … 46 46 highwayWeight.put(type, weigth); 47 47 } 48 48 49 49 /** 50 50 * @return the selectedNodes … … 67 67 } 68 68 69 70 /** 71 * 69 70 /** 71 * 72 72 */ 73 73 public void calculateShortesPath() { … … 92 92 fullWeight += routing.getPathLength(); 93 93 } 94 94 95 95 edgePath = new ArrayList<SegmentEdge>(); 96 96 edgePath.addAll(fullPath); 97 97 98 98 System.out.println("shortest path found: " + fullPath + "\nweight: " + fullWeight); 99 99 System.out.println(getPathDescription()); … … 104 104 // System.out.println("all added: " + weight2); 105 105 } 106 106 107 107 public String getPathDescription() { 108 108 List<PathDescription> pathDescriptions = getPathDescriptions(); 109 109 110 110 // create text representation from description: 111 111 StringBuilder builder = new StringBuilder(); … … 137 137 Way oldWay = null; 138 138 Way way = null; 139 139 140 140 SegmentEdge edge; 141 141 for(int segIndex = 0; segIndex < edgePath.size(); ++segIndex) { … … 150 150 description = new PathDescription(oldWay, length); // add finished way 151 151 pathDescriptions.add(description); 152 length = 0; 152 length = 0; 153 153 } 154 154 if(segIndex == edgePath.size() - 1) { 155 155 description = new PathDescription(way, length); 156 pathDescriptions.add(description); 156 pathDescriptions.add(description); 157 157 } 158 158 oldWay = way; 159 159 } 160 161 160 161 162 162 // for(SegmentEdge edge : edgePath) { 163 163 // way = edge.getWay(); … … 216 216 return this.edgePath; 217 217 } 218 218 219 219 /** 220 220 * Resets all data (nodes, edges, segments). -
applications/editors/josm/plugins/navigator/src/at/dallermassl/josm/plugin/navigator/NavigatorPlugin.java
r3865 r12778 1 1 /** 2 * 2 * 3 3 */ 4 4 package at.dallermassl.josm.plugin.navigator; … … 21 21 /** 22 22 * Plugin that allows navigation in josm 23 * 23 * 24 24 * @author cdaller 25 * 25 * 26 26 */ 27 27 public class NavigatorPlugin extends Plugin { … … 31 31 32 32 /** 33 * 33 * 34 34 */ 35 35 public NavigatorPlugin() { … … 40 40 navigatorLayer = new NavigatorLayer(tr("Navigation")); 41 41 navigatorLayer.setNavigatorNodeModel(navigatorModel); 42 42 43 43 JMenuBar menu = Main.main.menu; 44 44 JMenu navigatorMenu = new JMenu(tr("Navigation")); … … 55 55 menu.add(navigatorMenu); 56 56 } 57 57 58 58 /** 59 59 * Reads the weight values for the different highway types from the preferences. … … 70 70 } 71 71 } 72 72 73 73 /** 74 * Checks if there are any highway weights set in the preferences. If not, default 74 * Checks if there are any highway weights set in the preferences. If not, default 75 75 * values are used. 76 76 */ … … 86 86 setDefaultWeight("footway", 0.0); 87 87 } 88 88 89 89 private void setDefaultWeight(String type, double value) { 90 90 if(!Main.pref.hasKey(KEY_HIGHWAY_WEIGHT_PREFIX + type)) { … … 92 92 } 93 93 } 94 94 95 95 /* (non-Javadoc) 96 96 * @see org.openstreetmap.josm.plugins.Plugin#mapFrameInitialized(org.openstreetmap.josm.gui.MapFrame, org.openstreetmap.josm.gui.MapFrame) … … 99 99 public void mapFrameInitialized(MapFrame oldFrame, MapFrame newFrame) { 100 100 if(newFrame != null) { 101 IconToggleButton button = new IconToggleButton(new NavigatorModeAction(newFrame, navigatorModel, navigatorLayer)); 101 IconToggleButton button = new IconToggleButton(new NavigatorModeAction(newFrame, navigatorModel, navigatorLayer)); 102 102 newFrame.toolBarActions.add(button); 103 103 newFrame.toolGroup.add(button); -
applications/editors/josm/plugins/navigator/src/at/dallermassl/josm/plugin/navigator/OsmGraphCreator.java
r3892 r12778 1 1 /** 2 * 2 * 3 3 */ 4 4 package at.dallermassl.josm.plugin.navigator; … … 23 23 /** 24 24 * @author cdaller 25 * 25 * 26 26 */ 27 27 public class OsmGraphCreator { … … 38 38 highwayWeight = new HashMap<String, Double>(); 39 39 } 40 40 41 41 /** 42 42 * Set the weight for the given highway type. The higher the weight is, … … 58 58 // iterate all ways and segments for all nodes: 59 59 for(Way way : Main.ds.ways) { 60 if(way != null && !way.deleted) { 60 if(way != null && !way.deleted) { 61 61 for(Segment segment : way.segments) { 62 62 if(segment != null && !segment.deleted && segment.from != null && segment.to != null) { … … 67 67 graph.addEdge(segment.from, segment.to, edge); 68 68 weight = getWeight(way, segment); 69 System.out.println("edge for segment " + segment.id + "(from node "+ segment.from.id + " to node " 69 System.out.println("edge for segment " + segment.id + "(from node "+ segment.from.id + " to node " 70 70 + segment.to.id + ") has weight: " + weight); 71 71 graph.setEdgeWeight(edge, weight); … … 74 74 edge.setWay(way); 75 75 graph.addEdge(segment.to, segment.from, edge); 76 graph.setEdgeWeight(edge, weight); 77 System.out.println("inverse segment " + segment.id + "(from node "+ segment.to.id + " to node " 76 graph.setEdgeWeight(edge, weight); 77 System.out.println("inverse segment " + segment.id + "(from node "+ segment.to.id + " to node " 78 78 + segment.from.id + ") has weight: " + weight); 79 79 } … … 105 105 } 106 106 // deg to m (at equator :-): 107 double distance = Math.sqrt(segment.from.coor.distance(segment.to.coor)) * 111000; 107 double distance = Math.sqrt(segment.from.coor.distance(segment.to.coor)) * 111000; 108 108 if(weight == 0.0) { 109 109 weight = 1E-20; … … 191 191 /** 192 192 * Returns the other segment for the given node (works only for non crossing nodes). 193 * 193 * 194 194 * @param node 195 195 * @param segment -
applications/editors/josm/plugins/navigator/src/at/dallermassl/josm/plugin/navigator/PathDescription.java
r3833 r12778 1 1 /** 2 * 2 * 3 3 */ 4 4 package at.dallermassl.josm.plugin.navigator; -
applications/editors/josm/plugins/navigator/src/at/dallermassl/josm/plugin/navigator/SegmentEdge.java
r3834 r12778 1 1 /** 2 * 2 * 3 3 */ 4 4 package at.dallermassl.josm.plugin.navigator; … … 10 10 /** 11 11 * @author cdaller 12 * 12 * 13 13 */ 14 14 public class SegmentEdge extends DefaultWeightedEdge { -
applications/editors/josm/plugins/navigator/src/at/dallermassl/josm/plugin/navigator/WayEdge.java
r3686 r12778 1 1 /** 2 * 2 * 3 3 */ 4 4 package at.dallermassl.josm.plugin.navigator; … … 18 18 private Node endNode; 19 19 private List<Segment> segments; 20 20 21 21 public WayEdge() { 22 22 23 23 } 24 24 25 25 public WayEdge(int length) { 26 26 this.length = length; … … 82 82 this.endNode = endNode; 83 83 } 84 85 84 85 86 86 87 87 } -
applications/editors/josm/plugins/nearclick/src/nearclick/NearClickPlugin.java
r4088 r12778 20 20 public NearClickPlugin() { 21 21 Toolkit.getDefaultToolkit().addAWTEventListener(this, AWTEvent.MOUSE_EVENT_MASK | AWTEvent.MOUSE_MOTION_EVENT_MASK); 22 23 24 25 26 27 28 29 22 try { 23 int radius = Integer.parseInt(Main.pref.get("nearclick.radius", "7")); 24 radiussquared = radius * radius; 25 delay = Integer.parseInt(Main.pref.get("nearclick.delay", "250")); 26 } catch (NumberFormatException ex) { 27 delay = 250; 28 radiussquared = 7 * 7; 29 } 30 30 } 31 31 … … 35 35 if ( e.getButton() != MouseEvent.BUTTON1 ) 36 36 return; 37 38 39 37 int xdiff = e.getPoint().x - mouseDownX; 38 int ydiff = e.getPoint().y - mouseDownY; 39 40 40 if (e.getID() == MouseEvent.MOUSE_RELEASED) { 41 41 if ( e.getWhen() - mouseDownTime < delay && 42 43 44 45 42 ( e.getPoint().x != mouseDownX || 43 e.getPoint().y != mouseDownY) && 44 xdiff * xdiff + ydiff * ydiff < radiussquared 45 ) { 46 46 try { 47 47 Robot r = new Robot(GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice()); -
applications/editors/josm/plugins/openlayers/src/org/openstreetmap/josm/plugins/openLayers/Browser.java
r8748 r12778 21 21 static 22 22 { 23 23 Logger.getLogger("org.lobobrowser").setLevel(Level.WARNING); 24 24 } 25 25 … … 29 29 30 30 public Browser(String uri) { 31 31 super(); 32 32 33 34 35 33 UserAgentContext ucontext = new CacheableUserAgentContext(); 34 rcontext = new SimpleHtmlRendererContext(this, ucontext); 35 addNotify(); 36 36 37 37 process( uri ); 38 38 } 39 39 40 40 private void process(String uri) { 41 try { 42 URL url; 43 try { 44 url = new URL(uri); 45 } catch (java.net.MalformedURLException mfu) { 46 int idx = uri.indexOf(':'); 47 if (idx == -1 || idx == 1) { 48 // try file 49 url = new URL("file:" + uri); 50 } else { 51 throw mfu; 52 } 53 } 54 // Call SimpleHtmlRendererContext.navigate() 55 // which implements incremental rendering. 56 this.rcontext.navigate(url, null); 57 } catch (Exception err) { 58 err.printStackTrace(); 59 } 41 try { 42 URL url; 43 try { 44 url = new URL(uri); 45 } catch (java.net.MalformedURLException mfu) { 46 int idx = uri.indexOf(':'); 47 if (idx == -1 || idx == 1) { 48 // try file 49 url = new URL("file:" + uri); 50 } else { 51 throw mfu; 52 } 53 } 54 // Call SimpleHtmlRendererContext.navigate() 55 // which implements incremental rendering. 56 this.rcontext.navigate(url, null); 57 } catch (Exception err) { 58 err.printStackTrace(); 60 59 } 61 60 } 61 62 62 @Override 63 63 public void setSize(final Dimension newSize) 64 64 { 65 66 67 68 65 if (!newSize.equals(oldSize)) { 66 oldSize = newSize; 67 super.setSize(newSize); 68 validate(); 69 69 70 71 70 executeAsyncScript("resizeMap(" + newSize.width + "," + newSize.height + ");"); 71 } 72 72 } 73 73 74 74 public void executeAsyncScript(final String script) 75 75 { 76 77 78 79 80 76 EventQueue.invokeLater(new Runnable() { 77 public void run() { 78 executeScript(script); 79 } 80 }); 81 81 } 82 82 83 83 public Object executeScript(String script) 84 84 { 85 86 87 88 89 85 System.out.println("Executing script " + script); 86 try { 87 Window window = Window.getWindow(rcontext); 88 if( window.getDocumentNode() == null ) 89 return null; // Document not loaded yet 90 90 91 return window.eval(script); 92 } catch (EcmaError ecmaError) { 93 logger.log(Level.WARNING, "Javascript error at " + ecmaError.sourceName() + ":" + ecmaError.lineNumber() + ": " + ecmaError.getMessage()); 94 } catch (Throwable err) { 95 logger.log(Level.WARNING, "Unable to evaluate Javascript code", err); 96 } 97 98 return null; 91 return window.eval(script); 92 } catch (EcmaError ecmaError) { 93 logger.log(Level.WARNING, "Javascript error at " + ecmaError.sourceName() + ":" + ecmaError.lineNumber() + ": " + ecmaError.getMessage()); 94 } catch (Throwable err) { 95 logger.log(Level.WARNING, "Unable to evaluate Javascript code", err); 99 96 } 100 101 97 98 return null; 99 } 100 101 102 102 /** 103 103 * Overrided to hide hardcoded scrollbars and insets … … 105 105 @Override 106 106 protected HtmlBlockPanel createHtmlBlockPanel(UserAgentContext ucontext, HtmlRendererContext rcontext) { 107 107 return new MyHtmlBlockPanel(java.awt.Color.WHITE, true, ucontext, rcontext, this); 108 108 } 109 109 } -
applications/editors/josm/plugins/openlayers/src/org/openstreetmap/josm/plugins/openLayers/CacheableHttpRequest.java
r8748 r12778 44 44 45 45 public CacheableHttpRequest(UserAgentContext context, Proxy proxy) { 46 47 46 this.context = context; 47 this.proxy = proxy; 48 48 } 49 49 50 50 public synchronized int getReadyState() { 51 51 return this.readyState; 52 52 } 53 53 54 54 public synchronized String getResponseText() { 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 55 if( response == null ) return null; 56 57 byte[] bytes = this.response.responseBytes; 58 String encoding = this.response.encoding; 59 60 try { 61 return bytes == null ? null : new String(bytes, encoding); 62 } catch (UnsupportedEncodingException uee) { 63 logger.log(Level.WARNING, "getResponseText(): Charset '" + encoding + "' did not work. Retrying with ISO-8859-1.", uee); 64 try { 65 return new String(bytes, "ISO-8859-1"); 66 } catch (UnsupportedEncodingException uee2) { 67 // Ignore this time 68 return null; 69 } 70 } 71 71 } 72 72 73 73 public synchronized Document getResponseXML() { 74 75 76 77 78 79 80 81 82 83 84 85 74 if( response == null ) return null; 75 76 byte[] bytes = this.response.responseBytes; 77 if (bytes == null) return null; 78 79 InputStream in = new ByteArrayInputStream(bytes); 80 try { 81 return DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(in); 82 } catch (Exception err) { 83 logger.log(Level.WARNING, "Unable to parse response as XML.", err); 84 return null; 85 } 86 86 } 87 87 88 88 public synchronized byte[] getResponseBytes() { 89 90 89 if( response == null ) return null; 90 return this.response.responseBytes; 91 91 } 92 92 93 93 public synchronized Image getResponseImage() { 94 95 96 97 98 99 94 if( response == null ) return null; 95 96 byte[] bytes = this.response.responseBytes; 97 if (bytes == null) return null; 98 99 return Toolkit.getDefaultToolkit().createImage(bytes); 100 100 } 101 101 102 102 public synchronized int getStatus() { 103 104 103 if( response == null ) return 0; 104 return this.response.status; 105 105 } 106 106 107 107 public synchronized String getStatusText() { 108 109 108 if( response == null ) return null; 109 return this.response.statusText; 110 110 } 111 111 112 112 public synchronized String getAllResponseHeaders() { 113 114 113 if( response == null ) return null; 114 return this.response.responseHeaders; 115 115 } 116 116 117 117 public synchronized String getResponseHeader(String headerName) { 118 119 120 118 if( response == null ) return null; 119 Map headers = this.response.responseHeadersMap; 120 return headers == null ? null : (String) headers.get(headerName); 121 121 } 122 122 123 123 public void open(String method, String url) throws IOException { 124 124 this.open(method, url, true); 125 125 } 126 126 127 127 public void open(String method, URL url) throws IOException { 128 128 this.open(method, url, true, null, null); 129 129 } 130 130 131 131 public void open(String method, URL url, boolean asyncFlag) throws IOException { 132 132 this.open(method, url, asyncFlag, null, null); 133 133 } 134 134 135 135 public void open(String method, String url, boolean asyncFlag) throws IOException { 136 137 136 URL urlObj = Urls.createURL(null, url); 137 this.open(method, urlObj, asyncFlag, null); 138 138 } 139 139 140 140 public void open(String method, URL url, boolean asyncFlag, String userName) throws IOException { 141 141 this.open(method, url, asyncFlag, userName, null); 142 142 } 143 143 144 144 public void abort() { 145 146 147 148 149 150 151 152 153 154 155 156 157 158 145 URLConnection c; 146 synchronized (this) { 147 c = this.connection; 148 response = null; 149 } 150 if (c instanceof HttpURLConnection) { 151 ((HttpURLConnection) c).disconnect(); 152 } else if (c != null) { 153 try { 154 c.getInputStream().close(); 155 } catch (IOException ioe) { 156 ioe.printStackTrace(); 157 } 158 } 159 159 } 160 160 161 161 /** 162 162 * Opens the request. Call {@link #send(String)} to complete it. 163 * 163 * 164 164 * @param method The request method. 165 165 * @param url The request URL. … … 170 170 */ 171 171 public void open(final String method, final URL url, boolean asyncFlag, final String userName, final String password) throws IOException { 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 172 this.abort(); 173 174 HttpResponse response = HttpResponse.lookup(url); 175 URLConnection c = null; 176 177 if( response == null ) 178 { 179 c = proxy == null || proxy == Proxy.NO_PROXY ? url.openConnection() : url.openConnection(proxy); 180 response = new HttpResponse(); 181 } 182 183 synchronized (this) { 184 this.connection = c; 185 this.isAsync = asyncFlag; 186 this.requestMethod = method; 187 this.requestUserName = userName; 188 this.requestPassword = password; 189 this.requestURL = url; 190 this.response = response; 191 192 if( response.loaded ) 193 changeState(HttpRequest.STATE_LOADING); 194 else 195 changeState(HttpRequest.STATE_LOADING, 0, null, null); 196 } 197 197 } 198 198 … … 201 201 * <p> 202 202 * In the case of asynchronous requests, a new thread is created. 203 * 203 * 204 204 * @param content POST content or <code>null</code> if there's no such 205 205 * content. 206 206 */ 207 207 public void send(final String content) throws IOException { 208 209 210 211 212 213 214 215 208 final URL url = this.requestURL; 209 if (url == null) { 210 throw new IOException("No URL has been provided."); 211 } 212 if (this.isAsync) { 213 // Should use a thread pool instead 214 new Thread("SimpleHttpRequest-" + url.getHost()) { 215 @Override 216 216 public void run() { 217 218 219 220 221 222 223 224 225 226 217 try { 218 sendSync(content); 219 } catch (Throwable thrown) { 220 logger.log(Level.WARNING,"send(): Error in asynchronous request on " + url, thrown); 221 } 222 } 223 }.start(); 224 } else { 225 sendSync(content); 226 } 227 227 } 228 228 … … 232 232 */ 233 233 protected String getPostCharset() { 234 234 return "UTF-8"; 235 235 } 236 236 … … 238 238 * This is a synchronous implementation of {@link #send(String)} method 239 239 * functionality. It may be overridden to change the behavior of the class. 240 * 240 * 241 241 * @param content POST content if any. It may be <code>null</code>. 242 242 * @throws IOException 243 243 */ 244 244 protected void sendSync(String content) throws IOException { 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 245 if( response.loaded ) 246 { 247 // Response from cache 248 changeState(HttpRequest.STATE_LOADED); 249 changeState(HttpRequest.STATE_INTERACTIVE); 250 changeState(HttpRequest.STATE_COMPLETE); 251 return; 252 } 253 254 try { 255 URLConnection c; 256 synchronized (this) { 257 c = this.connection; 258 } 259 c.setRequestProperty("User-Agent", this.context.getUserAgent()); 260 int istatus = 0; 261 String istatusText = ""; 262 InputStream err = null; 263 264 if (c instanceof HttpURLConnection) { 265 HttpURLConnection hc = (HttpURLConnection) c; 266 String method = requestMethod.toUpperCase(); 267 hc.setRequestMethod(method); 268 if ("POST".equals(method) && content != null) { 269 hc.setDoOutput(true); 270 byte[] contentBytes = content.getBytes(this.getPostCharset()); 271 hc.setFixedLengthStreamingMode(contentBytes.length); 272 OutputStream out = hc.getOutputStream(); 273 try { 274 out.write(contentBytes); 275 } finally { 276 out.flush(); 277 } 278 } 279 istatus = hc.getResponseCode(); 280 istatusText = hc.getResponseMessage(); 281 err = hc.getErrorStream(); 282 } 283 284 response.setConnectionInfo(c); 285 changeState(HttpRequest.STATE_LOADED, istatus, istatusText, null); 286 InputStream in = err == null ? c.getInputStream() : err; 287 int contentLength = c.getContentLength(); 288 changeState(HttpRequest.STATE_INTERACTIVE, istatus, istatusText, null); 289 byte[] bytes = IORoutines.load(in, contentLength == -1 ? 4096 : contentLength); 290 changeState(HttpRequest.STATE_COMPLETE, istatus, istatusText, bytes); 291 response.store(requestURL); 292 } finally { 293 synchronized (this) { 294 this.connection = null; 295 } 296 } 297 297 } 298 298 … … 300 300 301 301 public void addReadyStateChangeListener( final ReadyStateChangeListener listener) { 302 303 304 305 306 307 } 308 302 readyEvent.addListener(new GenericEventListener() { 303 public void processEvent(EventObject event) { 304 listener.readyStateChanged(); 305 } 306 }); 307 } 308 309 309 protected void changeState(int readyState, int status, String statusMessage, byte[] bytes) { 310 310 synchronized (this) { -
applications/editors/josm/plugins/openlayers/src/org/openstreetmap/josm/plugins/openLayers/CacheableUserAgentContext.java
r8748 r12778 9 9 public class CacheableUserAgentContext extends SimpleUserAgentContext { 10 10 11 /** 11 /** 12 12 * Returns a cache aware HttpRequest 13 13 */ 14 14 @Override 15 15 public HttpRequest createHttpRequest() { 16 16 return new CacheableHttpRequest(this, this.getProxy()); 17 17 } 18 18 } -
applications/editors/josm/plugins/openlayers/src/org/openstreetmap/josm/plugins/openLayers/HttpResponse.java
r8748 r12778 1 1 /** 2 * 2 * 3 3 */ 4 4 package org.openstreetmap.josm.plugins.openLayers; … … 16 16 public class HttpResponse implements Serializable { 17 17 private static final long serialVersionUID = -8605486951415515445L; 18 18 19 19 /** The status of the response */ 20 20 protected int status; … … 27 27 /** Whether this response has been already loaded */ 28 28 protected boolean loaded = false; 29 29 30 30 /** Response headers are set in this map after a response is received. */ 31 31 protected Map<String, List<String>> responseHeadersMap; … … 33 33 /** Response headers are set in this string after a response is received. */ 34 34 protected String responseHeaders; 35 35 36 36 /** 37 37 * Sets the information about this response: headers and encoding … … 43 43 if (encoding == null) 44 44 encoding = "ISO-8859-1"; 45 45 46 46 responseHeaders = getAllResponseHeaders(c); 47 47 responseHeadersMap = c.getHeaderFields(); … … 50 50 /** 51 51 * Sets the state of this response 52 * 52 * 53 53 * @param status The response status 54 54 * @param statusMessage The status message … … 56 56 */ 57 57 public synchronized void changeState(int status, String statusMessage, byte[] bytes) { 58 58 this.status = status; 59 59 this.statusText = statusMessage; 60 60 this.responseBytes = bytes; 61 61 } 62 62 63 63 /** 64 64 * Returns the headers of the connection as a String … … 68 68 private String getAllResponseHeaders(URLConnection c) { 69 69 int idx = 0; 70 71 72 73 74 75 76 77 78 79 80 81 82 83 70 String value; 71 StringBuffer buf = new StringBuffer(); 72 while((value = c.getHeaderField(idx)) != null) { 73 String key = c.getHeaderFieldKey(idx); 74 if( key != null ) 75 { 76 buf.append(key); 77 buf.append("="); 78 } 79 buf.append(value); 80 buf.append("\n"); 81 idx++; 82 } 83 return buf.toString(); 84 84 } 85 85 … … 89 89 */ 90 90 public void store(URL requestURL) { 91 92 91 loaded = true; 92 StorageManager.getInstance().put(requestURL, this); 93 93 } 94 94 95 95 /** 96 96 * Looks up the requested URL in the cache 97 * @param requestURL The requested URL 97 * @param requestURL The requested URL 98 98 * @return The response, if available 99 99 */ 100 100 public static HttpResponse lookup(URL requestURL) { 101 101 return StorageManager.getInstance().get(requestURL); 102 102 } 103 103 } -
applications/editors/josm/plugins/openlayers/src/org/openstreetmap/josm/plugins/openLayers/MyHtmlBlockPanel.java
r8748 r12778 43 43 this.rblock = null; 44 44 } 45 45 46 46 this.invalidate(); 47 47 this.validateAll(); -
applications/editors/josm/plugins/openlayers/src/org/openstreetmap/josm/plugins/openLayers/OpenLayersLayer.java
r8748 r12778 21 21 /** 22 22 * Class that displays a OpenLayers layer. 23 * 23 * 24 24 * @author Francisco R. Santos <frsantos@gmail.com> 25 * 25 * 26 26 */ 27 27 public class OpenLayersLayer extends Layer implements PreferenceChangedListener, PropertyChangeListener { … … 33 33 */ 34 34 public OpenLayersLayer() { 35 36 37 38 39 40 41 42 43 44 35 super("OpenLayers"); 36 37 this.browser = new Browser(OpenLayersPlugin.pluginDir + "yahoo.html"); 38 39 if( Main.map != null ) 40 { 41 LatLon bottomLeft = Main.map.mapView.getLatLon(0,Main.map.mapView.getHeight()); 42 LatLon topRight = Main.map.mapView.getLatLon(Main.map.mapView.getWidth(), 0); 43 browser.executeAsyncScript("zoomMapToExtent(" + bottomLeft.lon() + "," + bottomLeft.lat() + "," + topRight.lon() + "," + topRight.lat() + ")"); 44 } 45 45 } 46 46 … … 50 50 @Override 51 51 public void paint(Graphics g, MapView mv) { 52 53 52 setSize(Main.map.mapView.getSize()); 53 browser.paint(g); 54 54 } 55 55 … … 58 58 */ 59 59 public void setSize(Dimension dim) { 60 60 browser.setSize(dim); 61 61 } 62 62 63 63 @Override 64 64 public Icon getIcon() { 65 65 return ImageProvider.get("OpenLayers.png"); 66 66 } 67 67 68 68 @Override 69 69 public Object getInfoComponent() { 70 70 return null; 71 71 } 72 72 73 73 @Override 74 74 public Component[] getMenuEntries() { 75 76 77 78 79 80 81 82 75 return new Component[] { 76 new JMenuItem(new LayerListDialog.ShowHideLayerAction(this)), 77 new JMenuItem(new LayerListDialog.DeleteLayerAction(this)), 78 new JSeparator(), 79 // color, 80 new JMenuItem(new RenameLayerAction(associatedFile, this)), 81 new JSeparator(), 82 new JMenuItem(new LayerListPopup.InfoAction(this)) }; 83 83 } 84 84 85 85 @Override 86 86 public String getToolTipText() { 87 87 return null; 88 88 } 89 89 90 90 @Override 91 91 public boolean isMergable(Layer other) { 92 92 return false; 93 93 } 94 94 … … 103 103 @Override 104 104 public void destroy() { 105 105 Main.pref.listener.remove(this); 106 106 107 108 109 110 111 107 if( Main.map != null ) 108 Main.map.mapView.removePropertyChangeListener(this); 109 110 OpenLayersPlugin.layer = null; 111 StorageManager.flush(); 112 112 } 113 113 … … 116 116 117 117 public void propertyChange(PropertyChangeEvent evt) { 118 119 120 118 if( !visible ) 119 return; 120 121 121 String prop = evt.getPropertyName(); 122 if ("center".equals(prop) || "scale".equals(prop)) { 123 zoomToMapView(); 124 } 122 if ("center".equals(prop) || "scale".equals(prop)) { 123 zoomToMapView(); 125 124 } 126 125 } 126 127 127 public void zoomToMapView() 128 128 { … … 133 133 { 134 134 // TODO wrong calculations 135 135 136 136 // Get actual extent from browser 137 137 NativeArray array = (NativeArray)value; … … 140 140 double right = ((Double)array.get(2, null)).doubleValue(); 141 141 double top = ((Double)array.get(3, null)).doubleValue(); 142 143 144 145 146 147 148 149 142 bottomLeft = new LatLon( bottom, left ); 143 topRight = new LatLon( top, right); 144 145 BoundingXYVisitor v = new BoundingXYVisitor(); 146 v.visit(Main.proj.latlon2eastNorth(bottomLeft)); 147 v.visit(Main.proj.latlon2eastNorth(topRight)); 148 System.out.println("Recalculating position (" + left + "," + bottom + "," + right + "," + top + ")"); 149 Main.map.mapView.recalculateCenterScale(v); 150 150 } 151 151 } -
applications/editors/josm/plugins/openlayers/src/org/openstreetmap/josm/plugins/openLayers/OpenLayersPlugin.java
r8748 r12778 14 14 /** 15 15 * Main class for the OpenLayers plugin. 16 * 16 * 17 17 * @author Francisco R. Santos <frsantos@gmail.com> 18 * 18 * 19 19 */ 20 20 public class OpenLayersPlugin extends Plugin { … … 25 25 26 26 public OpenLayersPlugin() { 27 pluginDir = getPluginDir(); 28 try { 29 copy("/resources/yahoo.html", "yahoo.html"); 30 } catch (FileNotFoundException e) { 31 // TODO Auto-generated catch block 32 e.printStackTrace(); 33 } catch (IOException e) { 34 // TODO Auto-generated catch block 35 e.printStackTrace(); 36 } 37 StorageManager.initStorage( pluginDir ); 38 refreshMenu(); 27 pluginDir = getPluginDir(); 28 try { 29 copy("/resources/yahoo.html", "yahoo.html"); 30 } catch (FileNotFoundException e) { 31 // TODO Auto-generated catch block 32 e.printStackTrace(); 33 } catch (IOException e) { 34 // TODO Auto-generated catch block 35 e.printStackTrace(); 39 36 } 40 37 StorageManager.initStorage( pluginDir ); 38 refreshMenu(); 39 } 40 41 41 public static void refreshMenu() { 42 43 44 45 46 47 48 49 50 42 JMenuBar menuBar = Main.main.menu; 43 if (menu == null) { 44 menu = new JMenu(tr("OpenLayers")); 45 menuBar.add(menu, 5); 46 } else { 47 menu.removeAll(); 48 } 49 50 menu.add(new JMenuItem(new ShowOpenLayersAction("Yahoo"))); 51 51 } 52 52 53 53 /* 54 54 * (non-Javadoc) 55 * 55 * 56 56 * @see org.openstreetmap.josm.plugins.Plugin#getPreferenceSetting() 57 57 */ 58 58 @Override 59 59 public PreferenceSetting getPreferenceSetting() { 60 60 return null; 61 61 } 62 62 -
applications/editors/josm/plugins/openlayers/src/org/openstreetmap/josm/plugins/openLayers/ShowOpenLayersAction.java
r8748 r12778 10 10 11 11 public ShowOpenLayersAction(String name) { 12 12 super(name, "OpenLayers", "Show layer" + name, 0, 0, false); 13 13 } 14 14 15 15 public void actionPerformed(ActionEvent e) { 16 17 18 19 20 21 22 23 24 25 26 27 28 29 16 final OpenLayersLayer layer = OpenLayersPlugin.layer != null ? OpenLayersPlugin.layer : new OpenLayersLayer(); 17 OpenLayersPlugin.layer = layer; 18 Main.main.addLayer(layer); 19 20 EventQueue.invokeLater(new Runnable() { 21 public void run() { 22 layer.setSize(Main.map.mapView.getSize()); 23 } 24 }); 25 26 // Get notifications of scale and position 27 Main.map.mapView.addPropertyChangeListener("scale", layer); 28 Main.map.mapView.addPropertyChangeListener("center", layer); 29 30 30 } 31 31 }; -
applications/editors/josm/plugins/openlayers/src/org/openstreetmap/josm/plugins/openLayers/StorageManager.java
r8748 r12778 10 10 * too big, with many jars, it should be replaced for a hand-made storage to 11 11 * disk. 12 * 12 * 13 13 * @author frsantos 14 * 14 * 15 15 */ 16 16 public class StorageManager { 17 17 18 18 private Cache cache; 19 19 20 20 private static StorageManager storage; 21 21 22 22 public static void initStorage(String basedir) 23 23 { 24 25 26 24 if( storage != null ) storage.dispose(); 25 26 storage = new StorageManager(basedir); 27 27 } 28 28 29 29 protected StorageManager(String basedir) 30 30 { 31 System.setProperty("net.sf.ehcache.enableShutdownHook", "true"); 32 33 31 System.setProperty("net.sf.ehcache.enableShutdownHook", "true"); 32 cache = new Cache("OpenLayers", 500, MemoryStoreEvictionPolicy.LRU, true, basedir + "cache", false, 300*24*7, 300, true, 3600*24*7, null); 33 CacheManager.getInstance().addCache(cache); 34 34 } 35 35 36 36 protected void dispose() 37 37 { 38 39 38 if( cache != null ) 39 cache.dispose(); 40 40 } 41 41 42 42 public static StorageManager getInstance() 43 43 { 44 44 return storage; 45 45 } 46 46 47 47 public HttpResponse get(URL key) 48 48 { 49 50 51 52 53 49 Element element = cache.get(key); 50 if( element != null ) 51 return (HttpResponse)element.getObjectValue(); 52 53 return null; 54 54 } 55 55 56 56 public void put(URL key, HttpResponse value) 57 57 { 58 59 58 Element element = new Element(key, value); 59 cache.put(element); 60 60 } 61 61 … … 64 64 */ 65 65 public static void flush() { 66 67 66 if( storage != null ) 67 storage.cache.flush(); 68 68 } 69 69 } -
applications/editors/josm/plugins/openstreetbugs/src/org/openstreetmap/josm/plugins/osb/ConfigKeys.java
r11157 r12778 1 1 /* Copyright (c) 2008, Henrik Niehaus 2 2 * All rights reserved. 3 * 3 * 4 4 * Redistribution and use in source and binary forms, with or without 5 5 * modification, are permitted provided that the following conditions are met: 6 * 6 * 7 7 * 1. Redistributions of source code must retain the above copyright notice, 8 8 * this list of conditions and the following disclaimer. 9 * 2. Redistributions in binary form must reproduce the above copyright notice, 10 * this list of conditions and the following disclaimer in the documentation 9 * 2. Redistributions in binary form must reproduce the above copyright notice, 10 * this list of conditions and the following disclaimer in the documentation 11 11 * and/or other materials provided with the distribution. 12 * 3. Neither the name of the project nor the names of its 13 * contributors may be used to endorse or promote products derived from this 12 * 3. Neither the name of the project nor the names of its 13 * contributors may be used to endorse or promote products derived from this 14 14 * software without specific prior written permission. 15 * 15 * 16 16 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 17 17 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE … … 29 29 30 30 public class ConfigKeys { 31 32 33 34 35 36 37 31 public static final String OSB_API_DISABLED = "osb.api.disabled"; 32 public static final String OSB_API_URI_CLOSE = "osb.uri.close"; 33 public static final String OSB_API_URI_EDIT = "osb.uri.edit"; 34 public static final String OSB_API_URI_DOWNLOAD = "osb.uri.download"; 35 public static final String OSB_API_URI_NEW = "osb.uri.new"; 36 public static final String OSB_NICKNAME = "osb.nickname"; 37 public static final String OSB_AUTO_DOWNLOAD = "osb.auto_download"; 38 38 } -
applications/editors/josm/plugins/openstreetbugs/src/org/openstreetmap/josm/plugins/osb/OsbDownloadLoop.java
r12588 r12778 1 1 /* Copyright (c) 2008, Henrik Niehaus 2 2 * All rights reserved. 3 * 3 * 4 4 * Redistribution and use in source and binary forms, with or without 5 5 * modification, are permitted provided that the following conditions are met: 6 * 6 * 7 7 * 1. Redistributions of source code must retain the above copyright notice, 8 8 * this list of conditions and the following disclaimer. 9 * 2. Redistributions in binary form must reproduce the above copyright notice, 10 * this list of conditions and the following disclaimer in the documentation 9 * 2. Redistributions in binary form must reproduce the above copyright notice, 10 * this list of conditions and the following disclaimer in the documentation 11 11 * and/or other materials provided with the distribution. 12 * 3. Neither the name of the project nor the names of its 13 * contributors may be used to endorse or promote products derived from this 12 * 3. Neither the name of the project nor the names of its 13 * contributors may be used to endorse or promote products derived from this 14 14 * software without specific prior written permission. 15 * 15 * 16 16 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 17 17 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE … … 36 36 37 37 public class OsbDownloadLoop extends Thread { 38 39 private static OsbDownloadLoop instance;40 41 private long countdown = TimeUnit.SECONDS.toMillis(1);42 43 private boolean downloadDone = false;44 45 private final int INTERVAL = 100;46 47 private OsbPlugin plugin;48 49 private Point2D lastCenter;50 51 public OsbDownloadLoop() {52 setName(tr("OpenStreetBugs download loop"));53 start();54 }55 56 public static synchronized OsbDownloadLoop getInstance() {57 if(instance == null) {58 instance = new OsbDownloadLoop();59 }60 return instance;61 }62 63 @Override64 public void run() {65 try {66 while(true) {67 countdown -= INTERVAL;68 69 // if the center of the map has changed, the user has dragged or70 // zoomed the map71 if(Main.map != null && Main.map.mapView != null) {72 Point2D currentCenter = Main.map.mapView.getCenter();73 if(currentCenter != null && !currentCenter.equals(lastCenter)) {74 resetCountdown();75 lastCenter = currentCenter;76 }77 }78 79 // auto download if configured80 if( Main.pref.getBoolean(ConfigKeys.OSB_AUTO_DOWNLOAD) && OsbPlugin.active ) {81 if(countdown < 0) {82 if(!downloadDone) {83 if(plugin != null) {84 plugin.updateData();85 downloadDone = true;86 }87 } else {88 countdown = -1;89 }90 }91 }92 93 Thread.sleep(INTERVAL);94 }95 } catch (InterruptedException e) {96 e.printStackTrace();97 }98 }99 100 public void resetCountdown() {101 downloadDone = false;102 countdown = TimeUnit.SECONDS.toMillis(1);103 }104 38 105 public void setPlugin(OsbPlugin plugin) { 106 this.plugin = plugin; 107 } 39 private static OsbDownloadLoop instance; 40 41 private long countdown = TimeUnit.SECONDS.toMillis(1); 42 43 private boolean downloadDone = false; 44 45 private final int INTERVAL = 100; 46 47 private OsbPlugin plugin; 48 49 private Point2D lastCenter; 50 51 public OsbDownloadLoop() { 52 setName(tr("OpenStreetBugs download loop")); 53 start(); 54 } 55 56 public static synchronized OsbDownloadLoop getInstance() { 57 if(instance == null) { 58 instance = new OsbDownloadLoop(); 59 } 60 return instance; 61 } 62 63 @Override 64 public void run() { 65 try { 66 while(true) { 67 countdown -= INTERVAL; 68 69 // if the center of the map has changed, the user has dragged or 70 // zoomed the map 71 if(Main.map != null && Main.map.mapView != null) { 72 Point2D currentCenter = Main.map.mapView.getCenter(); 73 if(currentCenter != null && !currentCenter.equals(lastCenter)) { 74 resetCountdown(); 75 lastCenter = currentCenter; 76 } 77 } 78 79 // auto download if configured 80 if( Main.pref.getBoolean(ConfigKeys.OSB_AUTO_DOWNLOAD) && OsbPlugin.active ) { 81 if(countdown < 0) { 82 if(!downloadDone) { 83 if(plugin != null) { 84 plugin.updateData(); 85 downloadDone = true; 86 } 87 } else { 88 countdown = -1; 89 } 90 } 91 } 92 93 Thread.sleep(INTERVAL); 94 } 95 } catch (InterruptedException e) { 96 e.printStackTrace(); 97 } 98 } 99 100 public void resetCountdown() { 101 downloadDone = false; 102 countdown = TimeUnit.SECONDS.toMillis(1); 103 } 104 105 public void setPlugin(OsbPlugin plugin) { 106 this.plugin = plugin; 107 } 108 108 } -
applications/editors/josm/plugins/openstreetbugs/src/org/openstreetmap/josm/plugins/osb/OsbLayer.java
r12588 r12778 1 1 /* Copyright (c) 2008, Henrik Niehaus 2 2 * All rights reserved. 3 * 3 * 4 4 * Redistribution and use in source and binary forms, with or without 5 5 * modification, are permitted provided that the following conditions are met: 6 * 6 * 7 7 * 1. Redistributions of source code must retain the above copyright notice, 8 8 * this list of conditions and the following disclaimer. 9 * 2. Redistributions in binary form must reproduce the above copyright notice, 10 * this list of conditions and the following disclaimer in the documentation 9 * 2. Redistributions in binary form must reproduce the above copyright notice, 10 * this list of conditions and the following disclaimer in the documentation 11 11 * and/or other materials provided with the distribution. 12 * 3. Neither the name of the project nor the names of its 13 * contributors may be used to endorse or promote products derived from this 12 * 3. Neither the name of the project nor the names of its 13 * contributors may be used to endorse or promote products derived from this 14 14 * software without specific prior written permission. 15 * 15 * 16 16 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 17 17 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE … … 62 62 63 63 public class OsbLayer extends Layer implements MouseListener { 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 64 65 private DataSet data; 66 67 private Collection<? extends OsmPrimitive> selection; 68 69 private JToolTip tooltip = new JToolTip(); 70 71 public OsbLayer(DataSet dataSet, String name) { 72 super(name); 73 this.data = dataSet; 74 DataSet.selListeners.add(new SelectionChangedListener() { 75 public void selectionChanged(Collection<? extends OsmPrimitive> newSelection) { 76 selection = newSelection; 77 } 78 }); 79 80 Main.map.mapView.addMouseListener(this); 81 } 82 83 @Override 84 public Object getInfoComponent() { 85 return getToolTipText(); 86 } 87 88 @Override 89 public Component[] getMenuEntries() { 90 return new Component[]{ 91 91 new JMenuItem(new LayerListDialog.ShowHideLayerAction(this)), 92 92 new JMenuItem(new LayerListDialog.DeleteLayerAction(this)), … … 95 95 new JSeparator(), 96 96 new JMenuItem(new LayerListPopup.InfoAction(this))}; 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 int tooltipHeight = lineCount * (int)fontBounds.getHeight() + HR_SIZE * (lineCount - 1); 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 97 } 98 99 @Override 100 public String getToolTipText() { 101 return tr("Displays OpenStreetBugs issues"); 102 } 103 104 @Override 105 public boolean isMergable(Layer other) { 106 return false; 107 } 108 109 @Override 110 public void mergeFrom(Layer from) {} 111 112 @Override 113 public void paint(Graphics g, MapView mv) { 114 Object[] nodes = data.nodes.toArray(); 115 for (int i = 0; i < nodes.length; i++) { 116 Node node = (Node) nodes[i]; 117 118 // don't paint deleted nodes 119 if(node.deleted) { 120 continue; 121 } 122 123 Point p = mv.getPoint(node.eastNorth); 124 125 ImageIcon icon = OsbPlugin.loadIcon("icon_error16.png"); 126 if("1".equals(node.get("state"))) { 127 icon = OsbPlugin.loadIcon("icon_valid16.png"); 128 } 129 int width = icon.getIconWidth(); 130 int height = icon.getIconHeight(); 131 132 g.drawImage(icon.getImage(), p.x - (width / 2), p.y - (height / 2), new ImageObserver() { 133 public boolean imageUpdate(Image img, int infoflags, int x, int y, int width, int height) { 134 return false; 135 } 136 }); 137 138 139 if(selection != null && selection.contains(node)) { 140 // draw description 141 String desc = node.get("note"); 142 if(desc != null) { 143 // format with html 144 StringBuilder sb = new StringBuilder("<html>"); 145 //sb.append(desc.replaceAll("\\|", "<br>")); 146 sb.append(desc.replaceAll("<hr />", "<hr>")); 147 sb.append("</html>"); 148 desc = sb.toString(); 149 150 // determine tooltip dimensions 151 int tooltipWidth = 0; 152 Rectangle2D fontBounds = null; 153 String[] lines = desc.split("<hr>"); 154 for (int j = 0; j < lines.length; j++) { 155 String line = lines[j]; 156 fontBounds = g.getFontMetrics().getStringBounds(line, g); 157 tooltipWidth = Math.max(tooltipWidth, (int)fontBounds.getWidth()); 158 } 159 160 // FIXME hiehgt calculations doesn't work with all LAFs 161 int lineCount = lines.length; 162 int HR_SIZE = 10; 163 int tooltipHeight = lineCount * (int)fontBounds.getHeight() + HR_SIZE * (lineCount - 1); 164 165 // draw description as a tooltip 166 tooltip.setTipText(desc); 167 tooltip.setSize(tooltipWidth+10, tooltipHeight + 6); 168 169 int tx = p.x + (width / 2) + 5; 170 int ty = (int)(p.y - height / 2); 171 g.translate(tx, ty); 172 tooltip.paint(g); 173 g.translate(-tx, -ty); 174 } 175 176 // draw selection border 177 g.setColor(ColorHelper.html2color(Main.pref.get("color.selected"))); 178 g.drawRect(p.x - (width / 2), p.y - (height / 2), 16, 16); 179 } 180 } 181 } 182 183 @Override 184 public void visitBoundingBox(BoundingXYVisitor v) {} 185 186 @Override 187 public Icon getIcon() { 188 return OsbPlugin.loadIcon("icon_error16.png"); 189 } 190 191 private Node getNearestNode(Point p) { 192 double snapDistance = 10; 193 double minDistanceSq = Double.MAX_VALUE; 194 Node minPrimitive = null; 195 for (Node n : data.nodes) { 196 if (n.deleted || n.incomplete) 197 continue; 198 Point sp = Main.map.mapView.getPoint(n.eastNorth); 199 double dist = p.distanceSq(sp); 200 if (minDistanceSq > dist && p.distance(sp) < snapDistance) { 201 minDistanceSq = p.distanceSq(sp); 202 minPrimitive = n; 203 } 204 // prefer already selected node when multiple nodes on one point 205 else if(minDistanceSq == dist && n.selected && !minPrimitive.selected) 206 { 207 minPrimitive = n; 208 } 209 } 210 return minPrimitive; 211 } 212 213 public void mouseClicked(MouseEvent e) { 214 if(e.getButton() == MouseEvent.BUTTON1) { 215 if(Main.map.mapView.getActiveLayer() == this) { 216 Node n = (Node) getNearestNode(e.getPoint()); 217 if(data.nodes.contains(n)) { 218 data.setSelected(n); 219 } 220 } 221 } 222 } 223 224 public void mousePressed(MouseEvent e) { 225 225 mayTriggerPopup(e); 226 226 } … … 229 229 mayTriggerPopup(e); 230 230 } 231 231 232 232 private void mayTriggerPopup(MouseEvent e) { 233 233 if(e.isPopupTrigger()) { 234 235 236 237 238 239 240 241 } 242 } 243 244 245 246 234 if(Main.map.mapView.getActiveLayer() == this) { 235 Node n = (Node) getNearestNode(e.getPoint()); 236 OsbAction.setSelectedNode(n); 237 if(data.nodes.contains(n)) { 238 PopupFactory.createPopup(n).show(e.getComponent(), e.getX(), e.getY()); 239 } 240 } 241 } 242 } 243 244 public void mouseEntered(MouseEvent e) {} 245 246 public void mouseExited(MouseEvent e) {} 247 247 } -
applications/editors/josm/plugins/openstreetbugs/src/org/openstreetmap/josm/plugins/osb/OsbObserver.java
r11157 r12778 1 1 /* Copyright (c) 2008, Henrik Niehaus 2 2 * All rights reserved. 3 * 3 * 4 4 * Redistribution and use in source and binary forms, with or without 5 5 * modification, are permitted provided that the following conditions are met: 6 * 6 * 7 7 * 1. Redistributions of source code must retain the above copyright notice, 8 8 * this list of conditions and the following disclaimer. 9 * 2. Redistributions in binary form must reproduce the above copyright notice, 10 * this list of conditions and the following disclaimer in the documentation 9 * 2. Redistributions in binary form must reproduce the above copyright notice, 10 * this list of conditions and the following disclaimer in the documentation 11 11 * and/or other materials provided with the distribution. 12 * 3. Neither the name of the project nor the names of its 13 * contributors may be used to endorse or promote products derived from this 12 * 3. Neither the name of the project nor the names of its 13 * contributors may be used to endorse or promote products derived from this 14 14 * software without specific prior written permission. 15 * 15 * 16 16 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 17 17 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE … … 31 31 32 32 public interface OsbObserver { 33 33 public void update(DataSet dataset); 34 34 } -
applications/editors/josm/plugins/openstreetbugs/src/org/openstreetmap/josm/plugins/osb/OsbPlugin.java
r12588 r12778 60 60 public class OsbPlugin extends Plugin implements LayerChangeListener { 61 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 62 private DataSet dataSet; 63 64 private UploadHook uploadHook; 65 66 private OsbDialog dialog; 67 68 private OsbLayer layer; 69 70 public static boolean active = false; 71 72 private DownloadAction download = new DownloadAction(); 73 74 public OsbPlugin() { 75 super(); 76 initConfig(); 77 dataSet = new DataSet(); 78 uploadHook = new OsbUploadHook(); 79 dialog = new OsbDialog(this); 80 80 OsbLayer.listeners.add(dialog); 81 81 OsbLayer.listeners.add(this); 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 82 } 83 84 private void initConfig() { 85 String debug = Main.pref.get(ConfigKeys.OSB_API_DISABLED); 86 if(debug == null || debug.length() == 0) { 87 debug = "false"; 88 Main.pref.put(ConfigKeys.OSB_API_DISABLED, debug); 89 } 90 91 String uri = Main.pref.get(ConfigKeys.OSB_API_URI_EDIT); 92 if(uri == null || uri.length() == 0) { 93 uri = "http://openstreetbugs.appspot.com/editPOIexec"; 94 Main.pref.put(ConfigKeys.OSB_API_URI_EDIT, uri); 95 } 96 97 uri = Main.pref.get(ConfigKeys.OSB_API_URI_CLOSE); 98 if(uri == null || uri.length() == 0) { 99 uri = "http://openstreetbugs.appspot.com/closePOIexec"; 100 Main.pref.put(ConfigKeys.OSB_API_URI_CLOSE, uri); 101 } 102 103 uri = Main.pref.get(ConfigKeys.OSB_API_URI_DOWNLOAD); 104 if(uri == null || uri.length() == 0) { 105 uri = "http://openstreetbugs.appspot.com/getBugs"; 106 Main.pref.put(ConfigKeys.OSB_API_URI_DOWNLOAD, uri); 107 } 108 109 uri = Main.pref.get(ConfigKeys.OSB_API_URI_NEW); 110 if(uri == null || uri.length() == 0) { 111 uri = "http://openstreetbugs.appspot.com/addPOIexec"; 112 Main.pref.put(ConfigKeys.OSB_API_URI_NEW, uri); 113 } 114 115 String auto_download = Main.pref.get(ConfigKeys.OSB_AUTO_DOWNLOAD); 116 if(auto_download == null || auto_download.length() == 0) { 117 auto_download = "true"; 118 Main.pref.put(ConfigKeys.OSB_AUTO_DOWNLOAD, auto_download); 119 } 120 } 121 122 /** 123 * Determines the bounds of the current selected layer 124 * @return 125 */ 126 protected Bounds bounds(){ 127 MapView mv = Main.map.mapView; 128 return new Bounds( 129 mv.getLatLon(0, mv.getHeight()), 130 mv.getLatLon(mv.getWidth(), 0)); 131 } 132 133 public void updateData() { 134 // determine the bounds of the currently visible area 135 Bounds bounds = null; 136 try { 137 bounds = bounds(); 138 } catch (Exception e) { 139 // something went wrong, probably the mapview isn't fully initialized 140 System.err.println("OpenStreetBugs: Couldn't determine bounds of currently visible rect. Cancel auto update"); 141 return; 142 } 143 144 try { 145 // download the data 146 download.execute(dataSet, bounds); 147 148 // display the parsed data 149 if(!dataSet.nodes.isEmpty()) { 150 updateGui(); 151 } 152 } catch (Exception e) { 153 JOptionPane.showMessageDialog(Main.parent, e.getMessage()); 154 e.printStackTrace(); 155 } 156 } 157 158 public void updateGui() { 159 // update dialog 160 dialog.update(dataSet); 161 162 // create a new layer if necessary 163 updateLayer(dataSet); 164 165 // repaint view, so that changes get visible 166 Main.map.mapView.repaint(); 167 } 168 169 private void updateLayer(DataSet osbData) { 170 if(layer == null) { 171 layer = new OsbLayer(osbData, "OpenStreetBugs"); 172 Main.main.addLayer(layer); 173 } 174 } 175 176 @Override 177 public void mapFrameInitialized(MapFrame oldFrame, MapFrame newFrame) { 178 if (oldFrame==null && newFrame!=null) { // map frame added 179 // add the dialog 180 newFrame.addToggleDialog(dialog); 181 182 // add the upload hook 183 LinkedList<UploadHook> hooks = ((UploadAction) Main.main.menu.upload).uploadHooks; 184 hooks.add(0, uploadHook); 185 186 // add a listener to the plugin toggle button 187 final JToggleButton toggle = (JToggleButton) dialog.action.button; 188 active = toggle.isSelected(); 189 toggle.addActionListener(new ActionListener() { 190 private boolean download = true; 191 192 public void actionPerformed(ActionEvent e) { 193 active = toggle.isSelected(); 194 if (toggle.isSelected() && download) { 195 Main.worker.execute(new Runnable() { 196 public void run() { 197 updateData(); 198 } 199 }); 200 download = false; 201 } 202 } 203 }); 204 } else if (oldFrame!=null && newFrame==null ) { // map frame removed 205 206 } 207 } 208 209 public static ImageIcon loadIcon(String name) { 210 URL url = OsbPlugin.class.getResource("/images/".concat(name)); 211 return new ImageIcon(url); 212 } 213 214 public void activeLayerChange(Layer oldLayer, Layer newLayer) {} 215 216 public void layerAdded(Layer newLayer) { 217 if(newLayer instanceof OsmDataLayer) { 218 active = ((JToggleButton)dialog.action.button).isSelected(); 219 220 // start the auto download loop 221 OsbDownloadLoop.getInstance().setPlugin(this); 222 } 223 } 224 225 public void layerRemoved(Layer oldLayer) { 226 if(oldLayer == layer) { 227 layer = null; 228 } 229 } 230 231 public OsbLayer getLayer() { 232 return layer; 233 } 234 235 public void setLayer(OsbLayer layer) { 236 this.layer = layer; 237 } 238 239 public DataSet getDataSet() { 240 return dataSet; 241 } 242 243 public void setDataSet(DataSet dataSet) { 244 this.dataSet = dataSet; 245 } 246 246 } -
applications/editors/josm/plugins/openstreetbugs/src/org/openstreetmap/josm/plugins/osb/OsbUploadHook.java
r12588 r12778 1 1 /* Copyright (c) 2008, Henrik Niehaus 2 2 * All rights reserved. 3 * 3 * 4 4 * Redistribution and use in source and binary forms, with or without 5 5 * modification, are permitted provided that the following conditions are met: 6 * 6 * 7 7 * 1. Redistributions of source code must retain the above copyright notice, 8 8 * this list of conditions and the following disclaimer. 9 * 2. Redistributions in binary form must reproduce the above copyright notice, 10 * this list of conditions and the following disclaimer in the documentation 9 * 2. Redistributions in binary form must reproduce the above copyright notice, 10 * this list of conditions and the following disclaimer in the documentation 11 11 * and/or other materials provided with the distribution. 12 * 3. Neither the name of the project nor the names of its 13 * contributors may be used to endorse or promote products derived from this 12 * 3. Neither the name of the project nor the names of its 13 * contributors may be used to endorse or promote products derived from this 14 14 * software without specific prior written permission. 15 * 15 * 16 16 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 17 17 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE … … 41 41 public class OsbUploadHook implements UploadHook { 42 42 43 44 Collection<OsmPrimitive> delete) 45 46 47 48 49 50 JOptionPane.showMessageDialog(Main.parent, 51 52 "You cannot upload these data. Maybe you have selected the wrong layer?"), 53 54 55 56 57 58 43 public boolean checkUpload(Collection<OsmPrimitive> add, Collection<OsmPrimitive> update, 44 Collection<OsmPrimitive> delete) 45 { 46 boolean containsOsbData = checkOpenStreetBugs(add); 47 containsOsbData |= checkOpenStreetBugs(update); 48 containsOsbData |= checkOpenStreetBugs(delete); 49 if(containsOsbData) { 50 JOptionPane.showMessageDialog(Main.parent, 51 tr("<html>The selected data contains data from OpenStreetBugs.<br>" + 52 "You cannot upload these data. Maybe you have selected the wrong layer?"), 53 tr("Warning"), JOptionPane.WARNING_MESSAGE); 54 return false; 55 } else { 56 return true; 57 } 58 } 59 59 60 61 62 63 64 65 66 67 68 60 private boolean checkOpenStreetBugs(Collection<OsmPrimitive> osmPrimitives) { 61 for (Iterator<OsmPrimitive> iterator = osmPrimitives.iterator(); iterator.hasNext();) { 62 OsmPrimitive osmPrimitive = iterator.next(); 63 if(osmPrimitive.get("openstreetbug") != null) { 64 return true; 65 } 66 } 67 return false; 68 } 69 69 } -
applications/editors/josm/plugins/openstreetbugs/src/org/openstreetmap/josm/plugins/osb/api/CloseAction.java
r12640 r12778 1 1 /* Copyright (c) 2008, Henrik Niehaus 2 2 * All rights reserved. 3 * 3 * 4 4 * Redistribution and use in source and binary forms, with or without 5 5 * modification, are permitted provided that the following conditions are met: 6 * 6 * 7 7 * 1. Redistributions of source code must retain the above copyright notice, 8 8 * this list of conditions and the following disclaimer. 9 * 2. Redistributions in binary form must reproduce the above copyright notice, 10 * this list of conditions and the following disclaimer in the documentation 9 * 2. Redistributions in binary form must reproduce the above copyright notice, 10 * this list of conditions and the following disclaimer in the documentation 11 11 * and/or other materials provided with the distribution. 12 * 3. Neither the name of the project nor the names of its 13 * contributors may be used to endorse or promote products derived from this 12 * 3. Neither the name of the project nor the names of its 13 * contributors may be used to endorse or promote products derived from this 14 14 * software without specific prior written permission. 15 * 15 * 16 16 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 17 17 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE … … 40 40 41 41 public class CloseAction { 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 42 43 private final String CHARSET = "UTF-8"; 44 45 public void execute(Node n) throws IOException { 46 // create the URI for the data download 47 String uri = Main.pref.get(ConfigKeys.OSB_API_URI_CLOSE); 48 String post = new StringBuilder("id=") 49 .append(n.get("id")) 50 .toString(); 51 52 String result = null; 53 if(Main.pref.getBoolean(ConfigKeys.OSB_API_DISABLED)) { 54 result = "ok"; 55 } else { 56 result = HttpUtils.post(uri, null, post, CHARSET); 57 } 58 59 if("ok".equalsIgnoreCase(result)) { 60 n.put("state", "1"); 61 Main.map.mapView.repaint(); 62 } else { 63 JOptionPane.showMessageDialog(Main.parent, 64 tr("An error occurred: {0}", new Object[] {result}), 65 tr("Error"), 66 JOptionPane.ERROR_MESSAGE); 67 } 68 } 69 69 } -
applications/editors/josm/plugins/openstreetbugs/src/org/openstreetmap/josm/plugins/osb/api/DownloadAction.java
r11579 r12778 1 1 /* Copyright (c) 2008, Henrik Niehaus 2 2 * All rights reserved. 3 * 3 * 4 4 * Redistribution and use in source and binary forms, with or without 5 5 * modification, are permitted provided that the following conditions are met: 6 * 6 * 7 7 * 1. Redistributions of source code must retain the above copyright notice, 8 8 * this list of conditions and the following disclaimer. 9 * 2. Redistributions in binary form must reproduce the above copyright notice, 10 * this list of conditions and the following disclaimer in the documentation 9 * 2. Redistributions in binary form must reproduce the above copyright notice, 10 * this list of conditions and the following disclaimer in the documentation 11 11 * and/or other materials provided with the distribution. 12 * 3. Neither the name of the project nor the names of its 13 * contributors may be used to endorse or promote products derived from this 12 * 3. Neither the name of the project nor the names of its 13 * contributors may be used to endorse or promote products derived from this 14 14 * software without specific prior written permission. 15 * 15 * 16 16 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 17 17 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE … … 41 41 42 42 public class DownloadAction { 43 44 private final String CHARSET = "UTF-8";45 46 public void execute(DataSet dataset, Bounds bounds) throws IOException {47 // create the URI for the data download48 String uri = Main.pref.get(ConfigKeys.OSB_API_URI_DOWNLOAD);49 43 50 // check zoom level 51 if(Main.map.mapView.zoom() > 15 || Main.map.mapView.zoom() < 9) { 52 return; 53 } 54 55 // add query params to the uri 56 StringBuilder sb = new StringBuilder(uri) 57 .append("?b=").append(bounds.min.lat()) 58 .append("&t=").append(bounds.max.lat()) 59 .append("&l=").append(bounds.min.lon()) 60 .append("&r=").append(bounds.max.lon()); 61 uri = sb.toString(); 44 private final String CHARSET = "UTF-8"; 62 45 63 // download the data 64 String content = HttpUtils.get(uri, null, CHARSET); 65 66 // clear dataset 67 dataset.nodes.clear(); 68 dataset.relations.clear(); 69 dataset.ways.clear(); 70 71 // parse the data 72 parseData(dataset, content); 73 } 46 public void execute(DataSet dataset, Bounds bounds) throws IOException { 47 // create the URI for the data download 48 String uri = Main.pref.get(ConfigKeys.OSB_API_URI_DOWNLOAD); 74 49 75 private void parseData(DataSet dataSet, String content) { 76 String idPattern = "\\d+"; 77 String floatPattern = "-?\\d+\\.\\d+"; 78 String pattern = "putAJAXMarker\\(("+idPattern+"),("+floatPattern+"),("+floatPattern+"),\"(.*)\",([01])\\)"; 79 Pattern p = Pattern.compile(pattern); 80 Matcher m = p.matcher(content); 81 while(m.find()) { 82 double lat = Double.parseDouble(m.group(3)); 83 double lon = Double.parseDouble(m.group(2)); 84 LatLon latlon = new LatLon(lat, lon); 85 Node osmNode = new Node(latlon); 86 osmNode.id = Long.parseLong(m.group(1)); 87 osmNode.put("id", m.group(1)); 88 osmNode.put("note", m.group(4)); 89 osmNode.put("openstreetbug", "FIXME"); 90 osmNode.put("state", m.group(5)); 91 dataSet.addPrimitive(osmNode); 92 } 93 } 50 // check zoom level 51 if(Main.map.mapView.zoom() > 15 || Main.map.mapView.zoom() < 9) { 52 return; 53 } 54 55 // add query params to the uri 56 StringBuilder sb = new StringBuilder(uri) 57 .append("?b=").append(bounds.min.lat()) 58 .append("&t=").append(bounds.max.lat()) 59 .append("&l=").append(bounds.min.lon()) 60 .append("&r=").append(bounds.max.lon()); 61 uri = sb.toString(); 62 63 // download the data 64 String content = HttpUtils.get(uri, null, CHARSET); 65 66 // clear dataset 67 dataset.nodes.clear(); 68 dataset.relations.clear(); 69 dataset.ways.clear(); 70 71 // parse the data 72 parseData(dataset, content); 73 } 74 75 private void parseData(DataSet dataSet, String content) { 76 String idPattern = "\\d+"; 77 String floatPattern = "-?\\d+\\.\\d+"; 78 String pattern = "putAJAXMarker\\(("+idPattern+"),("+floatPattern+"),("+floatPattern+"),\"(.*)\",([01])\\)"; 79 Pattern p = Pattern.compile(pattern); 80 Matcher m = p.matcher(content); 81 while(m.find()) { 82 double lat = Double.parseDouble(m.group(3)); 83 double lon = Double.parseDouble(m.group(2)); 84 LatLon latlon = new LatLon(lat, lon); 85 Node osmNode = new Node(latlon); 86 osmNode.id = Long.parseLong(m.group(1)); 87 osmNode.put("id", m.group(1)); 88 osmNode.put("note", m.group(4)); 89 osmNode.put("openstreetbug", "FIXME"); 90 osmNode.put("state", m.group(5)); 91 dataSet.addPrimitive(osmNode); 92 } 93 } 94 94 } -
applications/editors/josm/plugins/openstreetbugs/src/org/openstreetmap/josm/plugins/osb/api/EditAction.java
r12640 r12778 1 1 /* Copyright (c) 2008, Henrik Niehaus 2 2 * All rights reserved. 3 * 3 * 4 4 * Redistribution and use in source and binary forms, with or without 5 5 * modification, are permitted provided that the following conditions are met: 6 * 6 * 7 7 * 1. Redistributions of source code must retain the above copyright notice, 8 8 * this list of conditions and the following disclaimer. 9 * 2. Redistributions in binary form must reproduce the above copyright notice, 10 * this list of conditions and the following disclaimer in the documentation 9 * 2. Redistributions in binary form must reproduce the above copyright notice, 10 * this list of conditions and the following disclaimer in the documentation 11 11 * and/or other materials provided with the distribution. 12 * 3. Neither the name of the project nor the names of its 13 * contributors may be used to endorse or promote products derived from this 12 * 3. Neither the name of the project nor the names of its 13 * contributors may be used to endorse or promote products derived from this 14 14 * software without specific prior written permission. 15 * 15 * 16 16 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 17 17 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE … … 41 41 42 42 public class EditAction { 43 44 private final String CHARSET = "UTF-8";45 46 public void execute(Node n, String comment) throws IOException {47 // create the URI for the data download48 String uri = Main.pref.get(ConfigKeys.OSB_API_URI_EDIT);49 String post = new StringBuilder("id=")50 .append(n.get("id"))51 .append("&text=")52 .append(URLEncoder.encode(comment, CHARSET))53 .toString();54 55 String result = null;56 if(Main.pref.getBoolean(ConfigKeys.OSB_API_DISABLED)) {57 result = "ok";58 } else {59 result = HttpUtils.post(uri, null, post, CHARSET);60 }61 43 62 if("ok".equalsIgnoreCase(result)) { 63 String desc = n.get("note"); 64 desc = desc.concat("<hr />").concat(comment); 65 n.put("note", desc); 66 Main.map.mapView.repaint(); 67 } else { 68 JOptionPane.showMessageDialog(Main.parent, 69 tr("An error occurred: {0}", new Object[] {result}), 70 tr("Error"), 71 JOptionPane.ERROR_MESSAGE); 72 } 73 } 44 private final String CHARSET = "UTF-8"; 45 46 public void execute(Node n, String comment) throws IOException { 47 // create the URI for the data download 48 String uri = Main.pref.get(ConfigKeys.OSB_API_URI_EDIT); 49 String post = new StringBuilder("id=") 50 .append(n.get("id")) 51 .append("&text=") 52 .append(URLEncoder.encode(comment, CHARSET)) 53 .toString(); 54 55 String result = null; 56 if(Main.pref.getBoolean(ConfigKeys.OSB_API_DISABLED)) { 57 result = "ok"; 58 } else { 59 result = HttpUtils.post(uri, null, post, CHARSET); 60 } 61 62 if("ok".equalsIgnoreCase(result)) { 63 String desc = n.get("note"); 64 desc = desc.concat("<hr />").concat(comment); 65 n.put("note", desc); 66 Main.map.mapView.repaint(); 67 } else { 68 JOptionPane.showMessageDialog(Main.parent, 69 tr("An error occurred: {0}", new Object[] {result}), 70 tr("Error"), 71 JOptionPane.ERROR_MESSAGE); 72 } 73 } 74 74 } -
applications/editors/josm/plugins/openstreetbugs/src/org/openstreetmap/josm/plugins/osb/api/NewAction.java
r12588 r12778 1 1 /* Copyright (c) 2008, Henrik Niehaus 2 2 * All rights reserved. 3 * 3 * 4 4 * Redistribution and use in source and binary forms, with or without 5 5 * modification, are permitted provided that the following conditions are met: 6 * 6 * 7 7 * 1. Redistributions of source code must retain the above copyright notice, 8 8 * this list of conditions and the following disclaimer. 9 * 2. Redistributions in binary form must reproduce the above copyright notice, 10 * this list of conditions and the following disclaimer in the documentation 9 * 2. Redistributions in binary form must reproduce the above copyright notice, 10 * this list of conditions and the following disclaimer in the documentation 11 11 * and/or other materials provided with the distribution. 12 * 3. Neither the name of the project nor the names of its 13 * contributors may be used to endorse or promote products derived from this 12 * 3. Neither the name of the project nor the names of its 13 * contributors may be used to endorse or promote products derived from this 14 14 * software without specific prior written permission. 15 * 15 * 16 16 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 17 17 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE … … 43 43 44 44 public class NewAction { 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 45 46 private final String CHARSET = "UTF-8"; 47 48 public Node execute(Point p, String text) throws IOException { 49 // where has the issue been added 50 LatLon latlon = Main.map.mapView.getLatLon(p.x, p.y); 51 52 // create the URI for the data download 53 String uri = Main.pref.get(ConfigKeys.OSB_API_URI_NEW); 54 55 String post = new StringBuilder("lon=") 56 .append(latlon.lon()) 57 .append("&lat=") 58 .append(latlon.lat()) 59 .append("&text=") 60 .append(URLEncoder.encode(text, CHARSET)) 61 .toString(); 62 63 String result = null; 64 if(Main.pref.getBoolean(ConfigKeys.OSB_API_DISABLED)) { 65 result = "ok 12345"; 66 } else { 67 result = HttpUtils.post(uri, null, post, CHARSET); 68 } 69 70 Pattern resultPattern = Pattern.compile("ok\\s+(\\d+)"); 71 Matcher m = resultPattern.matcher(result); 72 String id = "-1"; 73 if(m.matches()) { 74 id = m.group(1); 75 } else { 76 throw new RuntimeException(tr("Couldn't create new bug. Result: {0}" + result)); 77 } 78 79 Node osmNode = new Node(latlon); 80 osmNode.put("id", id); 81 osmNode.put("note", text); 82 osmNode.put("openstreetbug", "FIXME"); 83 osmNode.put("state", "0"); 84 return osmNode; 85 } 86 86 } -
applications/editors/josm/plugins/openstreetbugs/src/org/openstreetmap/josm/plugins/osb/api/util/HttpResponse.java
r11157 r12778 1 1 /* Copyright (c) 2008, Henrik Niehaus 2 2 * All rights reserved. 3 * 3 * 4 4 * Redistribution and use in source and binary forms, with or without 5 5 * modification, are permitted provided that the following conditions are met: 6 * 6 * 7 7 * 1. Redistributions of source code must retain the above copyright notice, 8 8 * this list of conditions and the following disclaimer. 9 * 2. Redistributions in binary form must reproduce the above copyright notice, 10 * this list of conditions and the following disclaimer in the documentation 9 * 2. Redistributions in binary form must reproduce the above copyright notice, 10 * this list of conditions and the following disclaimer in the documentation 11 11 * and/or other materials provided with the distribution. 12 * 3. Neither the name of the project nor the names of its 13 * contributors may be used to endorse or promote products derived from this 12 * 3. Neither the name of the project nor the names of its 13 * contributors may be used to endorse or promote products derived from this 14 14 * software without specific prior written permission. 15 * 15 * 16 16 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 17 17 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -
applications/editors/josm/plugins/openstreetbugs/src/org/openstreetmap/josm/plugins/osb/api/util/HttpUtils.java
r12588 r12778 1 1 /* Copyright (c) 2008, Henrik Niehaus 2 2 * All rights reserved. 3 * 3 * 4 4 * Redistribution and use in source and binary forms, with or without 5 5 * modification, are permitted provided that the following conditions are met: 6 * 6 * 7 7 * 1. Redistributions of source code must retain the above copyright notice, 8 8 * this list of conditions and the following disclaimer. 9 * 2. Redistributions in binary form must reproduce the above copyright notice, 10 * this list of conditions and the following disclaimer in the documentation 9 * 2. Redistributions in binary form must reproduce the above copyright notice, 10 * this list of conditions and the following disclaimer in the documentation 11 11 * and/or other materials provided with the distribution. 12 * 3. Neither the name of the project nor the names of its 13 * contributors may be used to endorse or promote products derived from this 12 * 3. Neither the name of the project nor the names of its 13 * contributors may be used to endorse or promote products derived from this 14 14 * software without specific prior written permission. 15 * 15 * 16 16 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 17 17 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE … … 51 51 } 52 52 } 53 53 54 54 ByteArrayOutputStream bos = new ByteArrayOutputStream(); 55 55 int length = -1; … … 59 59 bos.write(b, 0, length); 60 60 } 61 61 62 62 return new String(bos.toByteArray(), charset); 63 63 } 64 64 65 65 public static HttpResponse getResponse(String url, Map<String, String> headers, String charset) throws IOException { 66 66 URL page = new URL(url); … … 72 72 } 73 73 } 74 74 75 75 ByteArrayOutputStream bos = new ByteArrayOutputStream(); 76 76 int length = -1; … … 80 80 bos.write(b, 0, length); 81 81 } 82 82 83 83 HttpResponse response = new HttpResponse(new String(bos.toByteArray(), charset), con.getHeaderFields()); 84 84 return response; 85 85 } 86 86 87 87 /** 88 * 88 * 89 89 * @param url 90 90 * @param headers … … 105 105 } 106 106 } 107 107 108 108 //send the post 109 109 OutputStream os = con.getOutputStream(); 110 110 os.write(content.getBytes("UTF-8")); 111 111 os.flush(); 112 112 113 113 // read the response 114 114 ByteArrayOutputStream bos = new ByteArrayOutputStream(); … … 119 119 bos.write(b, 0, length); 120 120 } 121 121 122 122 return new String(bos.toByteArray(), responseCharset); 123 123 } 124 124 125 125 /** 126 126 * Adds a parameter to a given URI … … 137 137 sb.append('?'); 138 138 } 139 139 140 140 sb.append(param); 141 141 sb.append('='); 142 142 sb.append(value); 143 143 144 144 return sb.toString(); 145 145 } … … 154 154 } 155 155 } 156 156 157 157 return con.getHeaderFields(); 158 158 } 159 159 160 160 public static String getHeaderField(Map<String, List<String>> headers, String headerField) { 161 161 if(!headers.containsKey(headerField)) { 162 162 return null; 163 163 } 164 164 165 165 List<String> value = headers.get(headerField); 166 166 if(value.size() == 1) { -
applications/editors/josm/plugins/openstreetbugs/src/org/openstreetmap/josm/plugins/osb/gui/OsbDialog.java
r12670 r12778 1 1 /* Copyright (c) 2008, Henrik Niehaus 2 2 * All rights reserved. 3 * 3 * 4 4 * Redistribution and use in source and binary forms, with or without 5 5 * modification, are permitted provided that the following conditions are met: 6 * 6 * 7 7 * 1. Redistributions of source code must retain the above copyright notice, 8 8 * this list of conditions and the following disclaimer. 9 * 2. Redistributions in binary form must reproduce the above copyright notice, 10 * this list of conditions and the following disclaimer in the documentation 9 * 2. Redistributions in binary form must reproduce the above copyright notice, 10 * this list of conditions and the following disclaimer in the documentation 11 11 * and/or other materials provided with the distribution. 12 * 3. Neither the name of the project nor the names of its 13 * contributors may be used to endorse or promote products derived from this 12 * 3. Neither the name of the project nor the names of its 13 * contributors may be used to endorse or promote products derived from this 14 14 * software without specific prior written permission. 15 * 15 * 16 16 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 17 17 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE … … 77 77 78 78 public class OsbDialog extends ToggleDialog implements OsbObserver, ListSelectionListener, LayerChangeListener, 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 KeyEvent.VK_O, Shortcut.GROUP_MENU, Shortcut.SHIFT_DEFAULT), 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 JOptionPane.showMessageDialog(Main.parent, 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 79 DataChangeListener, MouseListener, OsbActionObserver { 80 81 private static final long serialVersionUID = 1L; 82 private DefaultListModel model; 83 private JList list; 84 private OsbPlugin osbPlugin; 85 private boolean fireSelectionChanged = true; 86 private JButton refresh; 87 private JButton addComment = new JButton(new AddCommentAction()); 88 private JButton closeIssue = new JButton(new CloseIssueAction()); 89 private JToggleButton newIssue = new JToggleButton(); 90 91 public OsbDialog(final OsbPlugin plugin) { 92 super(tr("Open OpenStreetBugs"), "icon_error22", 93 tr("Opens the OpenStreetBugs window and activates the automatic download"), 94 Shortcut.registerShortcut( 95 "view:openstreetbugs", 96 tr("Toggle: {0}", tr("Open OpenStreetBugs")), 97 KeyEvent.VK_O, Shortcut.GROUP_MENU, Shortcut.SHIFT_DEFAULT), 98 150); 99 100 osbPlugin = plugin; 101 102 model = new DefaultListModel(); 103 list = new JList(model); 104 list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); 105 list.addListSelectionListener(this); 106 list.addMouseListener(this); 107 list.setCellRenderer(new OsbListCellRenderer()); 108 add(new JScrollPane(list), BorderLayout.CENTER); 109 110 // create dialog buttons 111 JPanel buttonPanel = new JPanel(new GridLayout(2, 2)); 112 add(buttonPanel, BorderLayout.SOUTH); 113 refresh = new JButton(tr("Refresh")); 114 refresh.setToolTipText(tr("Refresh")); 115 refresh.setIcon(OsbPlugin.loadIcon("view-refresh22.png")); 116 refresh.setHorizontalAlignment(SwingConstants.LEFT); 117 refresh.addActionListener(new ActionListener() { 118 119 public void actionPerformed(ActionEvent e) { 120 // check zoom level 121 if(Main.map.mapView.zoom() > 15 || Main.map.mapView.zoom() < 9) { 122 JOptionPane.showMessageDialog(Main.parent, 123 tr("The visible area is either too small or too big to download data from OpenStreetBugs"), 124 tr("Warning"), 125 JOptionPane.INFORMATION_MESSAGE); 126 return; 127 } 128 129 plugin.updateData(); 130 } 131 }); 132 133 addComment.setEnabled(false); 134 addComment.setToolTipText((String) addComment.getAction().getValue(Action.NAME)); 135 addComment.setIcon(OsbPlugin.loadIcon("add_comment22.png")); 136 addComment.setHorizontalAlignment(SwingConstants.LEFT); 137 closeIssue.setEnabled(false); 138 closeIssue.setToolTipText((String) closeIssue.getAction().getValue(Action.NAME)); 139 closeIssue.setIcon(OsbPlugin.loadIcon("icon_valid22.png")); 140 closeIssue.setHorizontalAlignment(SwingConstants.LEFT); 141 NewIssueAction nia = new NewIssueAction(newIssue, osbPlugin); 142 newIssue.setAction(nia); 143 newIssue.setToolTipText((String) newIssue.getAction().getValue(Action.NAME)); 144 newIssue.setIcon(OsbPlugin.loadIcon("icon_error_add22.png")); 145 newIssue.setHorizontalAlignment(SwingConstants.LEFT); 146 147 buttonPanel.add(refresh); 148 buttonPanel.add(newIssue); 149 buttonPanel.add(addComment); 150 buttonPanel.add(closeIssue); 151 152 // add a selection listener to the data 153 DataSet.selListeners.add(new SelectionChangedListener() { 154 public void selectionChanged(Collection<? extends OsmPrimitive> newSelection) { 155 fireSelectionChanged = false; 156 list.clearSelection(); 157 for (OsmPrimitive osmPrimitive : newSelection) { 158 for (int i = 0; i < model.getSize(); i++) { 159 OsbListItem item = (OsbListItem) model.get(i); 160 if(item.getNode() == osmPrimitive) { 161 list.addSelectionInterval(i, i); 162 } 163 } 164 } 165 fireSelectionChanged = true; 166 } 167 }); 168 169 AddCommentAction.addActionObserver(this); 170 CloseIssueAction.addActionObserver(this); 171 } 172 173 public synchronized void update(final DataSet dataset) { 174 Node lastNode = OsbAction.getSelectedNode(); 175 model = new DefaultListModel(); 176 List<Node> sortedList = new ArrayList<Node>(dataset.nodes); 177 Collections.sort(sortedList, new BugComparator()); 178 179 for (Node node : sortedList) { 180 if (!node.deleted) { 181 model.addElement(new OsbListItem(node)); 182 } 183 } 184 list.setModel(model); 185 list.setSelectedValue(new OsbListItem(lastNode), true); 186 } 187 188 public void valueChanged(ListSelectionEvent e) { 189 if(list.getSelectedValues().length == 0) { 190 addComment.setEnabled(false); 191 closeIssue.setEnabled(false); 192 OsbAction.setSelectedNode(null); 193 return; 194 } 195 196 List<OsmPrimitive> selected = new ArrayList<OsmPrimitive>(); 197 for (Object listItem : list.getSelectedValues()) { 198 Node node = ((OsbListItem) listItem).getNode(); 199 selected.add(node); 200 201 if ("1".equals(node.get("state"))) { 202 addComment.setEnabled(false); 203 closeIssue.setEnabled(false); 204 } else { 205 addComment.setEnabled(true); 206 closeIssue.setEnabled(true); 207 } 208 209 OsbAction.setSelectedNode(node); 210 211 scrollToSelected(node); 212 213 if (fireSelectionChanged) { 214 Main.ds.setSelected(selected); 215 } 216 } 217 } 218 219 private void scrollToSelected(Node node) { 220 for (int i = 0; i < model.getSize();i++) { 221 Node current = ((OsbListItem)model.get(i)).getNode(); 222 if(current.id == node.id) { 223 list.scrollRectToVisible(list.getCellBounds(i, i)); 224 list.setSelectedIndex(i); 225 return; 226 } 227 } 228 } 229 230 public void activeLayerChange(Layer oldLayer, Layer newLayer) {} 231 232 public void layerAdded(Layer newLayer) { 233 if(newLayer == osbPlugin.getLayer()) { 234 update(osbPlugin.getDataSet()); 235 Main.map.mapView.moveLayer(newLayer, 0); 236 } 237 } 238 239 public void layerRemoved(Layer oldLayer) { 240 if(oldLayer == osbPlugin.getLayer()) { 241 model.removeAllElements(); 242 } 243 } 244 245 public void dataChanged(OsmDataLayer l) { 246 update(l.data); 247 } 248 249 public void zoomToNode(Node node) { 250 double scale = Main.map.mapView.getScale(); 251 Main.map.mapView.zoomTo(node.eastNorth, scale); 252 } 253 254 public void mouseClicked(MouseEvent e) { 255 if(e.getButton() == MouseEvent.BUTTON1 && e.getClickCount() == 2) { 256 OsbListItem item = (OsbListItem)list.getSelectedValue(); 257 zoomToNode(item.getNode()); 258 } 259 } 260 261 public void mousePressed(MouseEvent e) { 262 262 mayTriggerPopup(e); 263 263 } … … 266 266 mayTriggerPopup(e); 267 267 } 268 268 269 269 private void mayTriggerPopup(MouseEvent e) { 270 270 if(e.isPopupTrigger()) { 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 271 int selectedRow = list.locationToIndex(e.getPoint()); 272 list.setSelectedIndex(selectedRow); 273 Node n = ((OsbListItem)list.getSelectedValue()).getNode(); 274 OsbAction.setSelectedNode(n); 275 PopupFactory.createPopup(n).show(e.getComponent(), e.getX(), e.getY()); 276 } 277 } 278 279 public void mouseEntered(MouseEvent e) {} 280 281 public void mouseExited(MouseEvent e) {} 282 283 public void actionPerformed(OsbAction action) { 284 if(action instanceof AddCommentAction || action instanceof CloseIssueAction) { 285 update(osbPlugin.getDataSet()); 286 } 287 } 288 289 private class BugComparator implements Comparator<Node> { 290 291 public int compare(Node o1, Node o2) { 292 String state1 = o1.get("state"); 293 String state2 = o2.get("state"); 294 if(state1.equals(state2)) { 295 return o1.get("note").compareTo(o2.get("note")); 296 } 297 return state1.compareTo(state2); 298 } 299 300 } 301 301 } -
applications/editors/josm/plugins/openstreetbugs/src/org/openstreetmap/josm/plugins/osb/gui/OsbListCellRenderer.java
r11161 r12778 1 1 /* Copyright (c) 2008, Henrik Niehaus 2 2 * All rights reserved. 3 * 3 * 4 4 * Redistribution and use in source and binary forms, with or without 5 5 * modification, are permitted provided that the following conditions are met: 6 * 6 * 7 7 * 1. Redistributions of source code must retain the above copyright notice, 8 8 * this list of conditions and the following disclaimer. 9 * 2. Redistributions in binary form must reproduce the above copyright notice, 10 * this list of conditions and the following disclaimer in the documentation 9 * 2. Redistributions in binary form must reproduce the above copyright notice, 10 * this list of conditions and the following disclaimer in the documentation 11 11 * and/or other materials provided with the distribution. 12 * 3. Neither the name of the project nor the names of its 13 * contributors may be used to endorse or promote products derived from this 12 * 3. Neither the name of the project nor the names of its 13 * contributors may be used to endorse or promote products derived from this 14 14 * software without specific prior written permission. 15 * 15 * 16 16 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 17 17 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE … … 45 45 private Color background = Color.WHITE; 46 46 private Color altBackground = new Color(250, 250, 220); 47 48 49 50 51 52 53 47 48 public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, 49 boolean cellHasFocus) { 50 51 JLabel label = new JLabel(); 52 label.setOpaque(true); 53 54 54 if(isSelected) { 55 55 label.setBackground(UIManager.getColor("List.selectionBackground")); 56 56 } else { 57 57 label.setBackground(index % 2 == 0 ? background : altBackground); 58 58 } 59 59 60 60 OsbListItem item = (OsbListItem) value; 61 61 Node n = item.getNode(); 62 62 Icon icon = null; 63 63 if("0".equals(n.get("state"))) { 64 64 icon = OsbPlugin.loadIcon("icon_error16.png"); 65 65 } else if("1".equals(n.get("state"))) { 66 66 icon = OsbPlugin.loadIcon("icon_valid16.png"); 67 67 } 68 68 label.setIcon(icon); 69 69 String text = n.get("note"); 70 70 if(text.indexOf("<hr />") > 0) { 71 71 text = text.substring(0, text.indexOf("<hr />")); 72 72 } 73 73 label.setText(text); 74 75 76 77 78 79 80 74 75 Dimension d = label.getPreferredSize(); 76 d.height += 10; 77 label.setPreferredSize(d); 78 79 return label; 80 } 81 81 82 82 } -
applications/editors/josm/plugins/openstreetbugs/src/org/openstreetmap/josm/plugins/osb/gui/OsbListItem.java
r11157 r12778 1 1 /* Copyright (c) 2008, Henrik Niehaus 2 2 * All rights reserved. 3 * 3 * 4 4 * Redistribution and use in source and binary forms, with or without 5 5 * modification, are permitted provided that the following conditions are met: 6 * 6 * 7 7 * 1. Redistributions of source code must retain the above copyright notice, 8 8 * this list of conditions and the following disclaimer. 9 * 2. Redistributions in binary form must reproduce the above copyright notice, 10 * this list of conditions and the following disclaimer in the documentation 9 * 2. Redistributions in binary form must reproduce the above copyright notice, 10 * this list of conditions and the following disclaimer in the documentation 11 11 * and/or other materials provided with the distribution. 12 * 3. Neither the name of the project nor the names of its 13 * contributors may be used to endorse or promote products derived from this 12 * 3. Neither the name of the project nor the names of its 13 * contributors may be used to endorse or promote products derived from this 14 14 * software without specific prior written permission. 15 * 15 * 16 16 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 17 17 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE … … 31 31 32 32 public class OsbListItem { 33 private Node node; 34 35 public OsbListItem(Node node) { 36 super(); 37 this.node = node; 38 } 33 private Node node; 39 34 40 public Node getNode() { 41 return node; 42 } 35 public OsbListItem(Node node) { 36 super(); 37 this.node = node; 38 } 43 39 44 public void setNode(Node node) { 45 this.node = node; 46 } 47 48 @Override 49 public String toString() { 50 if(node.get("note") != null) { 51 StringBuilder sb = new StringBuilder("<html>"); 52 sb.append(node.get("note").replaceAll("\\|", "<br>")); 53 sb.append("</html>"); 54 return sb.toString(); 55 } else { 56 return "N/A"; 57 } 58 } 59 60 @Override 61 public boolean equals(Object obj) { 62 if(obj instanceof OsbListItem) { 63 OsbListItem other = (OsbListItem)obj; 64 if(getNode() != null && other.getNode() != null) { 65 return getNode().id == other.getNode().id; 66 } 67 } 68 69 return false; 70 } 40 public Node getNode() { 41 return node; 42 } 43 44 public void setNode(Node node) { 45 this.node = node; 46 } 47 48 @Override 49 public String toString() { 50 if(node.get("note") != null) { 51 StringBuilder sb = new StringBuilder("<html>"); 52 sb.append(node.get("note").replaceAll("\\|", "<br>")); 53 sb.append("</html>"); 54 return sb.toString(); 55 } else { 56 return "N/A"; 57 } 58 } 59 60 @Override 61 public boolean equals(Object obj) { 62 if(obj instanceof OsbListItem) { 63 OsbListItem other = (OsbListItem)obj; 64 if(getNode() != null && other.getNode() != null) { 65 return getNode().id == other.getNode().id; 66 } 67 } 68 69 return false; 70 } 71 71 } -
applications/editors/josm/plugins/openstreetbugs/src/org/openstreetmap/josm/plugins/osb/gui/action/AddCommentAction.java
r12588 r12778 1 1 /* Copyright (c) 2008, Henrik Niehaus 2 2 * All rights reserved. 3 * 3 * 4 4 * Redistribution and use in source and binary forms, with or without 5 5 * modification, are permitted provided that the following conditions are met: 6 * 6 * 7 7 * 1. Redistributions of source code must retain the above copyright notice, 8 8 * this list of conditions and the following disclaimer. 9 * 2. Redistributions in binary form must reproduce the above copyright notice, 10 * this list of conditions and the following disclaimer in the documentation 9 * 2. Redistributions in binary form must reproduce the above copyright notice, 10 * this list of conditions and the following disclaimer in the documentation 11 11 * and/or other materials provided with the distribution. 12 * 3. Neither the name of the project nor the names of its 13 * contributors may be used to endorse or promote products derived from this 12 * 3. Neither the name of the project nor the names of its 13 * contributors may be used to endorse or promote products derived from this 14 14 * software without specific prior written permission. 15 * 15 * 16 16 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 17 17 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE … … 40 40 public class AddCommentAction extends OsbAction { 41 41 42 42 private static final long serialVersionUID = 1L; 43 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 44 private EditAction editAction = new EditAction(); 45 46 public AddCommentAction() { 47 super(tr("Add a comment")); 48 } 49 50 @Override 51 protected void doActionPerformed(ActionEvent e) throws Exception { 52 // get the user nickname 53 String nickname = Main.pref.get(ConfigKeys.OSB_NICKNAME); 54 if(nickname == null || nickname.length() == 0) { 55 nickname = JOptionPane.showInputDialog(Main.parent, tr("Please enter a user name")); 56 if(nickname == null) { 57 nickname = tr("NoName"); 58 } else { 59 Main.pref.put(ConfigKeys.OSB_NICKNAME, nickname); 60 } 61 } 62 63 String comment = JOptionPane.showInputDialog(Main.parent, tr("Enter your comment")); 64 if(comment != null) { 65 comment = comment.concat(" [").concat(nickname).concat("]"); 66 editAction.execute(getSelectedNode(), comment); 67 } 68 } 69 69 } -
applications/editors/josm/plugins/openstreetbugs/src/org/openstreetmap/josm/plugins/osb/gui/action/CloseIssueAction.java
r12588 r12778 1 1 /* Copyright (c) 2008, Henrik Niehaus 2 2 * All rights reserved. 3 * 3 * 4 4 * Redistribution and use in source and binary forms, with or without 5 5 * modification, are permitted provided that the following conditions are met: 6 * 6 * 7 7 * 1. Redistributions of source code must retain the above copyright notice, 8 8 * this list of conditions and the following disclaimer. 9 * 2. Redistributions in binary form must reproduce the above copyright notice, 10 * this list of conditions and the following disclaimer in the documentation 9 * 2. Redistributions in binary form must reproduce the above copyright notice, 10 * this list of conditions and the following disclaimer in the documentation 11 11 * and/or other materials provided with the distribution. 12 * 3. Neither the name of the project nor the names of its 13 * contributors may be used to endorse or promote products derived from this 12 * 3. Neither the name of the project nor the names of its 13 * contributors may be used to endorse or promote products derived from this 14 14 * software without specific prior written permission. 15 * 15 * 16 16 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 17 17 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE … … 40 40 public class CloseIssueAction extends OsbAction { 41 41 42 42 private static final long serialVersionUID = 1L; 43 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 } 60 44 private CloseAction closeAction = new CloseAction(); 45 46 public CloseIssueAction() { 47 super(tr("Mark as done")); 48 } 49 50 @Override 51 protected void doActionPerformed(ActionEvent e) throws IOException { 52 int result = JOptionPane.showConfirmDialog(Main.parent, 53 tr("Really mark this issue as ''done''?"), 54 tr("Really close?"), 55 JOptionPane.YES_NO_OPTION); 56 57 if(result == JOptionPane.YES_OPTION) { 58 closeAction.execute(getSelectedNode()); 59 } 60 } 61 61 } -
applications/editors/josm/plugins/openstreetbugs/src/org/openstreetmap/josm/plugins/osb/gui/action/NewIssueAction.java
r12640 r12778 1 1 /* Copyright (c) 2008, Henrik Niehaus 2 2 * All rights reserved. 3 * 3 * 4 4 * Redistribution and use in source and binary forms, with or without 5 5 * modification, are permitted provided that the following conditions are met: 6 * 6 * 7 7 * 1. Redistributions of source code must retain the above copyright notice, 8 8 * this list of conditions and the following disclaimer. 9 * 2. Redistributions in binary form must reproduce the above copyright notice, 10 * this list of conditions and the following disclaimer in the documentation 9 * 2. Redistributions in binary form must reproduce the above copyright notice, 10 * this list of conditions and the following disclaimer in the documentation 11 11 * and/or other materials provided with the distribution. 12 * 3. Neither the name of the project nor the names of its 13 * contributors may be used to endorse or promote products derived from this 12 * 3. Neither the name of the project nor the names of its 13 * contributors may be used to endorse or promote products derived from this 14 14 * software without specific prior written permission. 15 * 15 * 16 16 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 17 17 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE … … 47 47 public class NewIssueAction extends OsbAction implements MouseListener { 48 48 49 49 private static final long serialVersionUID = 1L; 50 50 51 private NewAction newAction = new NewAction(); 52 53 private JToggleButton button; 54 55 private OsbPlugin plugin; 56 57 public NewIssueAction(JToggleButton button, OsbPlugin plugin) { 58 super(tr("New issue")); 59 this.button = button; 60 this.plugin = plugin; 61 } 62 63 @Override 64 protected void doActionPerformed(ActionEvent e) throws IOException { 65 if(button.isSelected()) { 66 Main.map.mapView.setCursor(new Cursor(Cursor.CROSSHAIR_CURSOR)); 67 Main.map.mapView.addMouseListener(this); 68 } else { 69 reset(); 70 } 71 } 51 private NewAction newAction = new NewAction(); 72 52 73 private void reset() { 74 Main.map.mapView.setCursor(new Cursor(Cursor.DEFAULT_CURSOR)); 75 Main.map.mapView.removeMouseListener(this); 76 button.setSelected(false); 77 } 53 private JToggleButton button; 78 54 79 public void mouseClicked(MouseEvent e) { 80 addNewIssue(e); 81 } 55 private OsbPlugin plugin; 82 56 83 public void mouseEntered(MouseEvent e) {} 57 public NewIssueAction(JToggleButton button, OsbPlugin plugin) { 58 super(tr("New issue")); 59 this.button = button; 60 this.plugin = plugin; 61 } 84 62 85 public void mouseExited(MouseEvent e) {} 63 @Override 64 protected void doActionPerformed(ActionEvent e) throws IOException { 65 if(button.isSelected()) { 66 Main.map.mapView.setCursor(new Cursor(Cursor.CROSSHAIR_CURSOR)); 67 Main.map.mapView.addMouseListener(this); 68 } else { 69 reset(); 70 } 71 } 86 72 87 public void mousePressed(MouseEvent e) { 88 addNewIssue(e); 89 } 73 private void reset() { 74 Main.map.mapView.setCursor(new Cursor(Cursor.DEFAULT_CURSOR)); 75 Main.map.mapView.removeMouseListener(this); 76 button.setSelected(false); 77 } 90 78 91 private void addNewIssue(MouseEvent e) { 92 // get the user nickname 93 String nickname = Main.pref.get(ConfigKeys.OSB_NICKNAME); 94 if(nickname == null || nickname.length() == 0) { 95 nickname = JOptionPane.showInputDialog(Main.parent, tr("Please enter a user name")); 96 if(nickname == null) { 97 nickname = "NoName"; 98 } else { 99 Main.pref.put(ConfigKeys.OSB_NICKNAME, nickname); 100 } 101 } 102 103 // get the comment 104 String result = JOptionPane.showInputDialog(Main.parent, 105 tr("Describe the problem precisely"), 106 tr("Create issue"), 107 JOptionPane.QUESTION_MESSAGE); 108 109 if(result != null && result.length() > 0) { 110 try { 111 result = result.concat(" [").concat(nickname).concat("]"); 112 Node n = newAction.execute(e.getPoint(), result); 113 plugin.getDataSet().addPrimitive(n); 114 if(Main.pref.getBoolean(ConfigKeys.OSB_API_DISABLED)) { 115 plugin.updateGui(); 116 } else { 117 plugin.updateData(); 118 } 119 } catch (Exception e1) { 120 e1.printStackTrace(); 121 JOptionPane.showMessageDialog(Main.parent, 122 tr("An error occurred: {0}", new Object[] {result}), 123 tr("Error"), 124 JOptionPane.ERROR_MESSAGE); 125 } 126 } 127 128 reset(); 129 } 79 public void mouseClicked(MouseEvent e) { 80 addNewIssue(e); 81 } 130 82 131 public void mouseReleased(MouseEvent e) {} 83 public void mouseEntered(MouseEvent e) {} 84 85 public void mouseExited(MouseEvent e) {} 86 87 public void mousePressed(MouseEvent e) { 88 addNewIssue(e); 89 } 90 91 private void addNewIssue(MouseEvent e) { 92 // get the user nickname 93 String nickname = Main.pref.get(ConfigKeys.OSB_NICKNAME); 94 if(nickname == null || nickname.length() == 0) { 95 nickname = JOptionPane.showInputDialog(Main.parent, tr("Please enter a user name")); 96 if(nickname == null) { 97 nickname = "NoName"; 98 } else { 99 Main.pref.put(ConfigKeys.OSB_NICKNAME, nickname); 100 } 101 } 102 103 // get the comment 104 String result = JOptionPane.showInputDialog(Main.parent, 105 tr("Describe the problem precisely"), 106 tr("Create issue"), 107 JOptionPane.QUESTION_MESSAGE); 108 109 if(result != null && result.length() > 0) { 110 try { 111 result = result.concat(" [").concat(nickname).concat("]"); 112 Node n = newAction.execute(e.getPoint(), result); 113 plugin.getDataSet().addPrimitive(n); 114 if(Main.pref.getBoolean(ConfigKeys.OSB_API_DISABLED)) { 115 plugin.updateGui(); 116 } else { 117 plugin.updateData(); 118 } 119 } catch (Exception e1) { 120 e1.printStackTrace(); 121 JOptionPane.showMessageDialog(Main.parent, 122 tr("An error occurred: {0}", new Object[] {result}), 123 tr("Error"), 124 JOptionPane.ERROR_MESSAGE); 125 } 126 } 127 128 reset(); 129 } 130 131 public void mouseReleased(MouseEvent e) {} 132 132 } -
applications/editors/josm/plugins/openstreetbugs/src/org/openstreetmap/josm/plugins/osb/gui/action/OsbAction.java
r11568 r12778 1 1 /* Copyright (c) 2008, Henrik Niehaus 2 2 * All rights reserved. 3 * 3 * 4 4 * Redistribution and use in source and binary forms, with or without 5 5 * modification, are permitted provided that the following conditions are met: 6 * 6 * 7 7 * 1. Redistributions of source code must retain the above copyright notice, 8 8 * this list of conditions and the following disclaimer. 9 * 2. Redistributions in binary form must reproduce the above copyright notice, 10 * this list of conditions and the following disclaimer in the documentation 9 * 2. Redistributions in binary form must reproduce the above copyright notice, 10 * this list of conditions and the following disclaimer in the documentation 11 11 * and/or other materials provided with the distribution. 12 * 3. Neither the name of the project nor the names of its 13 * contributors may be used to endorse or promote products derived from this 12 * 3. Neither the name of the project nor the names of its 13 * contributors may be used to endorse or promote products derived from this 14 14 * software without specific prior written permission. 15 * 15 * 16 16 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 17 17 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE … … 38 38 public abstract class OsbAction extends AbstractAction { 39 39 40 40 private static final long serialVersionUID = 1L; 41 41 42 private static List<OsbActionObserver> observers = new ArrayList<OsbActionObserver>(); 43 44 private static Node selectedNode; 45 46 public OsbAction(String name) { 47 super(name); 48 } 42 private static List<OsbActionObserver> observers = new ArrayList<OsbActionObserver>(); 49 43 50 public static Node getSelectedNode() { 51 return selectedNode; 52 } 44 private static Node selectedNode; 53 45 54 public static void setSelectedNode(Node selectedNode) { 55 OsbAction.selectedNode = selectedNode; 56 } 57 58 public void actionPerformed(ActionEvent e) { 59 try { 60 doActionPerformed(e); 61 for (OsbActionObserver obs : observers) { 62 obs.actionPerformed(this); 63 } 64 } catch (Exception e1) { 65 System.err.println("Couldn't execute action " + getClass().getSimpleName()); 66 e1.printStackTrace(); 67 } 68 } 69 70 protected abstract void doActionPerformed(ActionEvent e) throws Exception; 71 72 public static void addActionObserver(OsbActionObserver obs) { 73 observers.add(obs); 74 } 75 76 public static void removeActionObserver(OsbActionObserver obs) { 77 observers.remove(obs); 78 } 46 public OsbAction(String name) { 47 super(name); 48 } 49 50 public static Node getSelectedNode() { 51 return selectedNode; 52 } 53 54 public static void setSelectedNode(Node selectedNode) { 55 OsbAction.selectedNode = selectedNode; 56 } 57 58 public void actionPerformed(ActionEvent e) { 59 try { 60 doActionPerformed(e); 61 for (OsbActionObserver obs : observers) { 62 obs.actionPerformed(this); 63 } 64 } catch (Exception e1) { 65 System.err.println("Couldn't execute action " + getClass().getSimpleName()); 66 e1.printStackTrace(); 67 } 68 } 69 70 protected abstract void doActionPerformed(ActionEvent e) throws Exception; 71 72 public static void addActionObserver(OsbActionObserver obs) { 73 observers.add(obs); 74 } 75 76 public static void removeActionObserver(OsbActionObserver obs) { 77 observers.remove(obs); 78 } 79 79 } -
applications/editors/josm/plugins/openstreetbugs/src/org/openstreetmap/josm/plugins/osb/gui/action/OsbActionObserver.java
r11157 r12778 1 1 /* Copyright (c) 2008, Henrik Niehaus 2 2 * All rights reserved. 3 * 3 * 4 4 * Redistribution and use in source and binary forms, with or without 5 5 * modification, are permitted provided that the following conditions are met: 6 * 6 * 7 7 * 1. Redistributions of source code must retain the above copyright notice, 8 8 * this list of conditions and the following disclaimer. 9 * 2. Redistributions in binary form must reproduce the above copyright notice, 10 * this list of conditions and the following disclaimer in the documentation 9 * 2. Redistributions in binary form must reproduce the above copyright notice, 10 * this list of conditions and the following disclaimer in the documentation 11 11 * and/or other materials provided with the distribution. 12 * 3. Neither the name of the project nor the names of its 13 * contributors may be used to endorse or promote products derived from this 12 * 3. Neither the name of the project nor the names of its 13 * contributors may be used to endorse or promote products derived from this 14 14 * software without specific prior written permission. 15 * 15 * 16 16 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 17 17 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE … … 29 29 30 30 public interface OsbActionObserver { 31 31 public void actionPerformed(OsbAction action); 32 32 } -
applications/editors/josm/plugins/openstreetbugs/src/org/openstreetmap/josm/plugins/osb/gui/action/PopupFactory.java
r12588 r12778 1 1 /* Copyright (c) 2008, Henrik Niehaus 2 2 * All rights reserved. 3 * 3 * 4 4 * Redistribution and use in source and binary forms, with or without 5 5 * modification, are permitted provided that the following conditions are met: 6 * 6 * 7 7 * 1. Redistributions of source code must retain the above copyright notice, 8 8 * this list of conditions and the following disclaimer. 9 * 2. Redistributions in binary form must reproduce the above copyright notice, 10 * this list of conditions and the following disclaimer in the documentation 9 * 2. Redistributions in binary form must reproduce the above copyright notice, 10 * this list of conditions and the following disclaimer in the documentation 11 11 * and/or other materials provided with the distribution. 12 * 3. Neither the name of the project nor the names of its 13 * contributors may be used to endorse or promote products derived from this 12 * 3. Neither the name of the project nor the names of its 13 * contributors may be used to endorse or promote products derived from this 14 14 * software without specific prior written permission. 15 * 15 * 16 16 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 17 17 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE … … 37 37 38 38 public class PopupFactory { 39 40 private static JPopupMenu issuePopup;41 private static JPopupMenu fixedPopup;42 43 public static synchronized JPopupMenu createPopup(Node node) {44 if("0".equals(node.get("state"))) {45 return getIssuePopup();46 } else if("1".equals(node.get("state"))) {47 return getFixedPopup();48 } else {49 throw new RuntimeException(tr("Unknown issue state"));50 }51 }52 39 53 private static JPopupMenu getIssuePopup() { 54 if(issuePopup == null) { 55 issuePopup = new JPopupMenu(); 56 JMenuItem add = new JMenuItem(); 57 add.setAction(new AddCommentAction()); 58 add.setIcon(OsbPlugin.loadIcon("add_comment16.png")); 59 issuePopup.add(add); 60 JMenuItem close = new JMenuItem(); 61 close.setAction(new CloseIssueAction()); 62 close.setIcon(OsbPlugin.loadIcon("icon_valid16.png")); 63 issuePopup.add(close); 64 } 65 return issuePopup; 66 } 67 68 private static JPopupMenu getFixedPopup() { 69 if(fixedPopup == null) { 70 fixedPopup = new JPopupMenu(); 71 JMenuItem add = new JMenuItem(); 72 AddCommentAction aca = new AddCommentAction(); 73 aca.setEnabled(false); 74 add.setAction(aca); 75 add.setIcon(OsbPlugin.loadIcon("add_comment16.png")); 76 JMenuItem close = new JMenuItem(); 77 CloseIssueAction cia = new CloseIssueAction(); 78 cia.setEnabled(false); 79 close.setAction(cia); 80 close.setIcon(OsbPlugin.loadIcon("icon_valid16.png")); 81 fixedPopup.add(add); 82 fixedPopup.add(close); 83 } 84 return fixedPopup; 85 } 40 private static JPopupMenu issuePopup; 41 private static JPopupMenu fixedPopup; 42 43 public static synchronized JPopupMenu createPopup(Node node) { 44 if("0".equals(node.get("state"))) { 45 return getIssuePopup(); 46 } else if("1".equals(node.get("state"))) { 47 return getFixedPopup(); 48 } else { 49 throw new RuntimeException(tr("Unknown issue state")); 50 } 51 } 52 53 private static JPopupMenu getIssuePopup() { 54 if(issuePopup == null) { 55 issuePopup = new JPopupMenu(); 56 JMenuItem add = new JMenuItem(); 57 add.setAction(new AddCommentAction()); 58 add.setIcon(OsbPlugin.loadIcon("add_comment16.png")); 59 issuePopup.add(add); 60 JMenuItem close = new JMenuItem(); 61 close.setAction(new CloseIssueAction()); 62 close.setIcon(OsbPlugin.loadIcon("icon_valid16.png")); 63 issuePopup.add(close); 64 } 65 return issuePopup; 66 } 67 68 private static JPopupMenu getFixedPopup() { 69 if(fixedPopup == null) { 70 fixedPopup = new JPopupMenu(); 71 JMenuItem add = new JMenuItem(); 72 AddCommentAction aca = new AddCommentAction(); 73 aca.setEnabled(false); 74 add.setAction(aca); 75 add.setIcon(OsbPlugin.loadIcon("add_comment16.png")); 76 JMenuItem close = new JMenuItem(); 77 CloseIssueAction cia = new CloseIssueAction(); 78 cia.setEnabled(false); 79 close.setAction(cia); 80 close.setIcon(OsbPlugin.loadIcon("icon_valid16.png")); 81 fixedPopup.add(add); 82 fixedPopup.add(close); 83 } 84 return fixedPopup; 85 } 86 86 } -
applications/editors/josm/plugins/openvisible/src/at/dallermassl/josm/plugin/openvisible/OpenVisibleAction.java
r12588 r12778 1 1 /** 2 * 2 * 3 3 */ 4 4 package at.dallermassl.josm.plugin.openvisible; … … 40 40 public class OpenVisibleAction extends JosmAction { 41 41 private File lastDirectory; 42 42 43 43 public OpenVisibleAction() { 44 44 super(tr("Open Visible ..."), "openvisible", … … 60 60 LatLon bottomLeft = view.getLatLon(bounds.x, bounds.y + bounds.height); 61 61 LatLon topRight = view.getLatLon(bounds.x + bounds.width, bounds.y); 62 62 63 63 System.err.println("FileFind Bounds: " + bottomLeft + " to " + topRight); 64 64 65 65 JFileChooser fileChooser; 66 66 if(lastDirectory != null) { … … 73 73 File[] files = fileChooser.getSelectedFiles(); 74 74 lastDirectory = fileChooser.getCurrentDirectory(); 75 75 76 76 for(File file : files) { 77 77 try { … … 85 85 openFileAsGpx(file); 86 86 } 87 87 88 88 } 89 89 } catch (FileNotFoundException e1) { … … 95 95 } 96 96 } 97 97 98 98 } 99 99 100 100 private void openAsData(File file) throws SAXException, IOException, FileNotFoundException { 101 101 String fn = file.getName(); -
applications/editors/josm/plugins/openvisible/src/at/dallermassl/josm/plugin/openvisible/OpenVisiblePlugin.java
r12588 r12778 1 1 /** 2 * 2 * 3 3 */ 4 4 package at.dallermassl.josm.plugin.openvisible; -
applications/editors/josm/plugins/openvisible/src/at/dallermassl/josm/plugin/openvisible/OsmGpxBounds.java
r5138 r12778 1 1 /** 2 * 2 * 3 3 */ 4 4 package at.dallermassl.josm.plugin.openvisible; … … 27 27 private double minLon = 90.0; 28 28 private double maxLon = -90.0; 29 29 30 30 public OsmGpxBounds() { 31 31 32 32 } 33 33 34 34 /** 35 35 * Parses the given input stream (gpx or osm file). … … 46 46 } 47 47 } 48 49 @Override 48 49 @Override 50 50 public void startElement(String ns, String lname, String qname, Attributes a) { 51 51 if (qname.equals("node") || qname.equals("trkpt")) { … … 58 58 } 59 59 } 60 60 61 61 /** 62 62 * Returns <code>true</code>, if the given coordinates intersect with the … … 75 75 return ((lat2-lat1) > 0) && ((lon2-lon1) > 0); 76 76 } 77 77 78 78 public static void main(String[] args) { 79 79 if(args.length < 5) { … … 87 87 String[] files = new String[args.length - 4]; 88 88 System.arraycopy(args, 4, files, 0, args.length - 4); 89 90 try { 89 90 try { 91 91 File file; 92 92 for(String fileName : files) { 93 93 file = new File(fileName); 94 if(!file.isDirectory() 94 if(!file.isDirectory() 95 95 && (file.getName().endsWith("gpx") || file.getName().endsWith("osm"))) { 96 96 OsmGpxBounds parser = new OsmGpxBounds(); 97 97 parser.parse(new BufferedInputStream(new FileInputStream(file))); 98 98 if(parser.intersects(minLat, maxLat, minLon, maxLon)) { 99 System.out.println(file.getAbsolutePath()); // + "," + parser.minLat + "," + parser.maxLat + "," + parser.minLon + "," + parser.maxLon); 99 System.out.println(file.getAbsolutePath()); // + "," + parser.minLat + "," + parser.maxLat + "," + parser.minLon + "," + parser.maxLon); 100 100 } 101 101 // System.out.println(parser.intersects(47.0555, 47.09, 15.406, 15.4737)); … … 112 112 113 113 /** 114 * 114 * 115 115 */ 116 116 private static void printHelp() { 117 117 System.out.println(OsmGpxBounds.class.getName() + " <minLat> <maxLat> <minLon> <maxLon> <files+>"); 118 118 119 119 } 120 120 -
applications/editors/josm/plugins/osmarender/src/OsmarenderPlugin.java
r12603 r12778 38 38 public class OsmarenderPlugin extends Plugin { 39 39 40 40 private class Action extends JosmAction { 41 41 42 43 44 42 public Action() { 43 super(tr("Osmarender"), null, tr("Osmarender"), null, true); 44 } 45 45 46 47 48 49 50 46 public void actionPerformed(ActionEvent e) { 47 // get all stuff visible on screen 48 LatLon bottomLeft = Main.map.mapView.getLatLon(0,Main.map.mapView.getHeight()); 49 LatLon topRight = Main.map.mapView.getLatLon(Main.map.mapView.getWidth(), 0); 50 Bounds b = new Bounds(bottomLeft, topRight); 51 51 52 53 54 55 56 52 try { 53 writeGenerated(b); 54 } catch(Exception ex) { 55 //how handle the exception? 56 } 57 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 58 CollectBackReferencesVisitor backRefsV = new CollectBackReferencesVisitor(Main.ds, true); 59 DataSet fromDataSet = new DataSet(); 60 for (Node n : Main.ds.nodes) { 61 if (n.deleted || n.incomplete) continue; 62 if (n.coor.isWithin(b)) { 63 fromDataSet.nodes.add(n); 64 n.visit(backRefsV); 65 } 66 } 67 for (OsmPrimitive p : new HashSet<OsmPrimitive>(backRefsV.data)) { 68 if (p instanceof Way) { 69 backRefsV.data.addAll(((Way) p).nodes); 70 } 71 } 72 for (OsmPrimitive p : backRefsV.data) 73 fromDataSet.addPrimitive(p); 74 74 75 76 77 78 75 String firefox = Main.pref.get("osmarender.firefox", "firefox"); 76 try { 77 // write to plugin dir 78 OsmWriter.output(new FileOutputStream(getPluginDir()+File.separator+"data.osm"), new OsmWriter.All(fromDataSet, true)); 79 79 80 81 82 83 84 85 80 // get the exec line 81 String exec = firefox; 82 if (System.getProperty("os.name").startsWith("Windows")) 83 exec += " file:///"+getPluginDir().replace('\\','/').replace(" ","%20")+File.separator+"generated.xml\""; 84 else 85 exec += " "+getPluginDir()+File.separator+"generated.xml"; 86 86 87 88 89 90 91 92 93 87 // launch up the viewer 88 Runtime.getRuntime().exec(exec); 89 } catch (IOException e1) { 90 JOptionPane.showMessageDialog(Main.parent, tr("Firefox not found. Please set firefox executable in the Map Settings page of the preferences.")); 91 } 92 } 93 } 94 94 95 95 private JMenuItem osmarenderMenu; 96 96 97 98 99 97 public OsmarenderPlugin() throws IOException { 98 osmarenderMenu = MainMenu.add(Main.main.menu.viewMenu, new Action()); 99 osmarenderMenu.setVisible(false); 100 100 101 102 103 104 101 // install the xsl and xml file 102 copy("/osmarender.xsl", "osmarender.xsl"); 103 copy("/osm-map-features.xml", "osm-map-features.xml"); 104 } 105 105 106 107 108 109 110 111 112 113 114 115 106 @Override 107 public void mapFrameInitialized(MapFrame oldFrame, MapFrame newFrame) { 108 if (oldFrame != null && newFrame == null) { 109 // disable 110 osmarenderMenu.setVisible(false); 111 } else if (oldFrame == null && newFrame != null) { 112 // enable 113 osmarenderMenu.setVisible(true); 114 } 115 } 116 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 117 @Override public PreferenceSetting getPreferenceSetting() { 118 return new PreferenceSetting(){ 119 private JTextField firefox = new JTextField(10); 120 public void addGui(PreferenceDialog gui) { 121 gui.map.add(new JLabel(tr("osmarender options")), GBC.eol().insets(0,5,0,0)); 122 gui.map.add(new JLabel(tr("Firefox executable")), GBC.std().insets(10,5,5,0)); 123 gui.map.add(firefox, GBC.eol().insets(0,5,0,0).fill(GBC.HORIZONTAL)); 124 firefox.setText(Main.pref.get("osmarender.firefox")); 125 } 126 public boolean ok() { 127 Main.pref.put("osmarender.firefox", firefox.getText()); 128 return false; 129 } 130 }; 131 } 132 132 133 134 135 136 137 138 133 private void writeGenerated(Bounds b) throws IOException { 134 String bounds_tag = "<bounds " + 135 "minlat=\"" + b.min.lat() + "\" " + 136 "maxlat=\"" + b.max.lat() + "\" " + 137 "minlon=\"" + b.min.lon() + "\" " + 138 "maxlon=\"" + b.max.lon() + "\" " + "/>"; 139 139 140 141 142 140 BufferedReader reader = new BufferedReader( 141 new FileReader( getPluginDir() + File.separator + "osm-map-features.xml") ); 142 PrintWriter writer = new PrintWriter( getPluginDir() + File.separator + "generated.xml"); 143 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 144 // osm-map-fetaures.xml contain two placemark 145 // (bounds_mkr1 and bounds_mkr2). We write the bounds tag 146 // between the two 147 String str = null; 148 while( (str = reader.readLine()) != null ) { 149 if(str.contains("<!--bounds_mkr1-->")) { 150 writer.println(str); 151 writer.println(" " + bounds_tag); 152 while(!str.contains("<!--bounds_mkr2-->")) { 153 str = reader.readLine(); 154 } 155 writer.println(str); 156 } else { 157 writer.println(str); 158 } 159 } 160 160 161 162 161 writer.close(); 162 } 163 163 } -
applications/editors/josm/plugins/plastic_laf/src/plastic_laf/Plugin.java
r1467 r12778 7 7 8 8 public class Plugin { 9 10 11 12 9 public Plugin() throws UnsupportedLookAndFeelException { 10 UIManager.getDefaults().put("ClassLoader", getClass().getClassLoader()); 11 UIManager.setLookAndFeel(new PlasticLookAndFeel()); 12 } 13 13 } -
applications/editors/josm/plugins/pluginmanager/src/at/dallermassl/josm/plugin/pluginmanager/InstallPanel.java
r3335 r12778 1 1 /** 2 * 2 * 3 3 */ 4 4 package at.dallermassl.josm.plugin.pluginmanager; … … 30 30 /** 31 31 * @param pluginUpdateFrame 32 * @param descriptions 32 * @param descriptions 33 33 */ 34 34 public InstallPanel(PluginUpdateFrame pluginUpdateFrame, List<SiteDescription> descriptions) { … … 36 36 setBorder(new javax.swing.border.EmptyBorder(12,12,12,12)); 37 37 final JSplitPane split = new JSplitPane(JSplitPane.VERTICAL_SPLIT, true); 38 38 39 39 /* Setup the table */ 40 40 table = new JTable(pluginModel = new PluginTableModel(descriptions)); … … 44 44 table.setPreferredScrollableViewportSize(new Dimension(500,200)); 45 45 table.getSelectionModel().addListSelectionListener(this); 46 46 47 47 TableColumn col1 = table.getColumnModel().getColumn(0); 48 48 TableColumn col2 = table.getColumnModel().getColumn(1); … … 82 82 83 83 /** 84 * 84 * 85 85 */ 86 86 public void install() { … … 101 101 infoBox.setText(text); 102 102 infoBox.setCaretPosition(0); 103 103 104 104 } 105 105 -
applications/editors/josm/plugins/pluginmanager/src/at/dallermassl/josm/plugin/pluginmanager/PluginDescription.java
r3412 r12778 1 1 /** 2 * 2 * 3 3 */ 4 4 package at.dallermassl.josm.plugin.pluginmanager; … … 23 23 private String description; 24 24 private List<PluginResource> resources = new ArrayList<PluginResource>(); 25 25 26 26 /** 27 27 * Add a resource to the plugin description. … … 31 31 resources.add(resource); 32 32 } 33 33 34 34 /** 35 35 * @return the id … … 87 87 return this.resources; 88 88 } 89 89 90 90 /** 91 91 * @return the installedVersion … … 136 136 } 137 137 if(errorReported) { 138 JOptionPane.showMessageDialog(Main.parent, "One or more installs had an error: " + errorMessages.toString()); 138 JOptionPane.showMessageDialog(Main.parent, "One or more installs had an error: " + errorMessages.toString()); 139 139 } 140 140 } 141 141 142 142 /* (non-Javadoc) 143 143 * @see java.lang.Object#toString() 144 144 */ 145 145 public String toString() { 146 return getClass().getSimpleName() + "[id=" + id 147 + ", name=" + name 148 + ", version=" + version 149 + ", desc=" + description 150 + ", resources=" + resources 146 return getClass().getSimpleName() + "[id=" + id 147 + ", name=" + name 148 + ", version=" + version 149 + ", desc=" + description 150 + ", resources=" + resources 151 151 + "]"; 152 152 } -
applications/editors/josm/plugins/pluginmanager/src/at/dallermassl/josm/plugin/pluginmanager/PluginHelper.java
r9948 r12778 1 1 /** 2 * 2 * 3 3 */ 4 4 package at.dallermassl.josm.plugin.pluginmanager; … … 18 18 */ 19 19 public class PluginHelper { 20 20 21 21 private static PluginHelper INSTANCE = new PluginHelper(); 22 22 private Map<String, JMenu>menus; 23 23 private VariableHelper variableHelper; 24 24 25 25 /** 26 26 * Private constructor … … 35 35 // registerMenu("layer", Main.main.menu.layerMenu); 36 36 registerMenu("help", Main.main.menu.helpMenu); 37 37 38 38 variableHelper = new VariableHelper(); 39 39 variableHelper.addAll(Main.pref.getAllPrefix("")); 40 40 variableHelper.add("josm.user.dir", Main.pref.getPreferencesDir()); 41 41 } 42 42 43 43 /** 44 44 * Returns the singleton instance of this helper. … … 48 48 return INSTANCE; 49 49 } 50 50 51 51 /** 52 52 * Adds a menu to the main menu of JOSM and registers it under the given id. … … 59 59 registerMenu(menuId, menu); 60 60 } 61 61 62 62 /** 63 63 * Register the menu under the given id so other plugins can retrieve 64 * the menu with {@link #getMenu(String)}. 64 * the menu with {@link #getMenu(String)}. 65 65 * @param menuId 66 66 * @param menu … … 69 69 menus.put(menuId, menu); 70 70 } 71 71 72 72 /** 73 * Returns the main menu that was registered with the given id or <code>null</code> 73 * Returns the main menu that was registered with the given id or <code>null</code> 74 74 * if no menu was registered with that id. The default menus have the ids: 75 75 * <code>file</code>, <code>view</code>, <code>edit</code>, <code>tools</code>, … … 87 87 return this.variableHelper; 88 88 } 89 89 90 90 /** 91 91 * Returns the plugin with the given id or <code>null</code> … … 104 104 return null; 105 105 } 106 107 106 108 107 108 109 109 110 110 } -
applications/editors/josm/plugins/pluginmanager/src/at/dallermassl/josm/plugin/pluginmanager/PluginManagerAction.java
r3335 r12778 1 1 /** 2 * 2 * 3 3 */ 4 4 package at.dallermassl.josm.plugin.pluginmanager; … … 16 16 */ 17 17 public class PluginManagerAction extends AbstractAction { 18 18 19 19 /** 20 20 * Constructor … … 36 36 // left a list of sites, right buttons "add remote site" 37 37 // list has checkboxes 38 // adding: name and url where site.xml can be found. 38 // adding: name and url where site.xml can be found. 39 39 // site.xml containing a list of plugin.xml files 40 40 // plugin info holds name, version and dependencies (including versions) … … 43 43 // page to download, page to install, page to enable new plugins 44 44 // finish 45 45 46 46 // plugin.xml holds info 47 // name, version, dependencies, installpath, 48 47 // name, version, dependencies, installpath, 48 49 49 // info about other resources: images, log4j.jar, .... 50 50 // need source url and target dir (relative to .josm? or main app dir (for josm update)) 51 51 // need restart of josm afterwards 52 52 53 53 // pluginmanager could also load the plugins itself, so dependencies could be respected 54 54 } -
applications/editors/josm/plugins/pluginmanager/src/at/dallermassl/josm/plugin/pluginmanager/PluginManagerPlugin.java
r3335 r12778 1 1 /** 2 * 2 * 3 3 */ 4 4 package at.dallermassl.josm.plugin.pluginmanager; … … 14 14 */ 15 15 public class PluginManagerPlugin extends Plugin { 16 16 17 17 public PluginManagerPlugin() { 18 18 // JMenu menu = PluginHelper.getInstance().getMenu("tools"); … … 20 20 // menu.add(new PluginManagerAction()); 21 21 } 22 22 23 23 @Override 24 24 public PreferenceSetting getPreferenceSetting() { -
applications/editors/josm/plugins/pluginmanager/src/at/dallermassl/josm/plugin/pluginmanager/PluginManagerPreference.java
r12707 r12778 1 1 /** 2 * 2 * 3 3 */ 4 4 package at.dallermassl.josm.plugin.pluginmanager; … … 56 56 if(sites.keySet().size() == 0) { 57 57 // add default entry (for demonstration purpose) 58 sites.put(PREF_KEY_REMOTE_SITE_PREFIX + "0"+PREF_KEY_SITE_URL_SUFFIX, 58 sites.put(PREF_KEY_REMOTE_SITE_PREFIX + "0"+PREF_KEY_SITE_URL_SUFFIX, 59 59 "http://www.tegmento.org/~cdaller/josm/"); 60 60 } … … 73 73 } 74 74 ++siteCount; 75 } 75 } 76 76 return listModel; 77 77 } … … 82 82 // only in 1.6 allowed @Override 83 83 public void addGui(final PreferenceDialog gui) { 84 84 85 85 siteListModel = createListModel(); 86 86 siteList = new JList(siteListModel); … … 114 114 else { 115 115 int[] selected = siteList.getSelectedIndices(); 116 for (int i = selected.length - 1; i >=0; --i) { 116 for (int i = selected.length - 1; i >=0; --i) { 117 117 siteListModel.removeElementAt(selected[i]); 118 118 } -
applications/editors/josm/plugins/pluginmanager/src/at/dallermassl/josm/plugin/pluginmanager/PluginResource.java
r3415 r12778 1 1 /** 2 * 2 * 3 3 */ 4 4 package at.dallermassl.josm.plugin.pluginmanager; … … 22 22 private String errorMessage; 23 23 private Exception errorException; 24 24 25 25 /** 26 26 * @return the resourceUrl … … 47 47 this.target = target; 48 48 } 49 49 50 50 /** 51 51 * @return the errorMessage … … 73 73 } 74 74 /** 75 * Installs the resource into to the target location. 76 * @throws IOException if the resource could not be read or written. 75 * Installs the resource into to the target location. 76 * @throws IOException if the resource could not be read or written. 77 77 */ 78 78 public void install() { 79 79 File targetFile = new File(target); 80 if(targetFile.isDirectory() 81 || targetFile.getAbsolutePath().endsWith("/") 80 if(targetFile.isDirectory() 81 || targetFile.getAbsolutePath().endsWith("/") 82 82 || targetFile.getAbsolutePath().endsWith("\\")) { 83 83 targetFile = new File(targetFile, resourceUrl.getFile()); … … 88 88 return; 89 89 } 90 90 91 91 // copy resource to local filesystem: 92 92 System.out.println("Install " + resourceUrl + " to " + targetFile); … … 112 112 } catch(IOException ignore) {} 113 113 } 114 114 115 115 } 116 116 /* (non-Javadoc) … … 120 120 return getClass().getSimpleName() + "[url=" + resourceUrl + ", target=" + target + "]"; 121 121 } 122 122 123 123 } -
applications/editors/josm/plugins/pluginmanager/src/at/dallermassl/josm/plugin/pluginmanager/PluginTableModel.java
r3335 r12778 1 1 /** 2 * 2 * 3 3 */ 4 4 package at.dallermassl.josm.plugin.pluginmanager; … … 17 17 private List<SiteDescription> sites; 18 18 private List<PluginDescription> plugins; 19 19 20 20 public PluginTableModel(List<SiteDescription> descriptions) { 21 21 this.sites = descriptions; 22 22 update(); 23 23 } 24 24 25 25 private void update() { 26 26 plugins = new ArrayList<PluginDescription>(); … … 29 29 } 30 30 } 31 32 31 32 33 33 34 34 /* (non-Javadoc) … … 65 65 return plugin.getInstalledVersion() + " -> " + plugin.getVersion(); 66 66 } else { 67 return plugin.getVersion(); 67 return plugin.getVersion(); 68 68 } 69 69 default: throw new IllegalArgumentException("Illegal Column Index " + columnIndex); 70 70 } 71 71 } 72 73 72 73 74 74 75 75 /* (non-Javadoc) … … 121 121 } 122 122 } 123 123 124 124 } 125 125 … … 151 151 this.plugins = plugins; 152 152 } 153 154 155 156 153 154 155 156 157 157 158 158 } -
applications/editors/josm/plugins/pluginmanager/src/at/dallermassl/josm/plugin/pluginmanager/PluginUpdateFrame.java
r3335 r12778 1 1 /** 2 * 2 * 3 3 */ 4 4 package at.dallermassl.josm.plugin.pluginmanager; … … 32 32 /** 33 33 * @param title 34 * @param descriptions 34 * @param descriptions 35 35 * @throws HeadlessException 36 36 */ … … 39 39 init(descriptions); 40 40 } 41 41 42 42 public void init(List<SiteDescription> descriptions) { 43 43 44 44 /* Setup panes */ 45 45 JPanel content = new JPanel(new BorderLayout(12,12)); … … 53 53 54 54 content.add(BorderLayout.CENTER,tabPane); 55 55 56 56 JPanel buttonPannel = new JPanel(); 57 57 // <FIXXME date="23.06.2007" author="cdaller"> … … 59 59 JButton okButton = new JButton(tr("Install")); 60 60 JButton cancelButton = new JButton(tr("Cancel")); 61 // </FIXXME> 61 // </FIXXME> 62 62 buttonPannel.add(okButton); 63 63 buttonPannel.add(cancelButton); … … 68 68 setVisible(false); 69 69 dispose(); 70 } 70 } 71 71 }); 72 72 73 73 cancelButton.addActionListener(new ActionListener() { 74 74 public void actionPerformed(ActionEvent e) { 75 75 setVisible(false); 76 76 dispose(); 77 } 77 } 78 78 }); 79 79 content.add(BorderLayout.SOUTH,buttonPannel); 80 80 81 81 pack(); 82 82 } -
applications/editors/josm/plugins/pluginmanager/src/at/dallermassl/josm/plugin/pluginmanager/SiteDescription.java
r9948 r12778 1 1 /** 2 * 2 * 3 3 */ 4 4 package at.dallermassl.josm.plugin.pluginmanager; … … 30 30 private URL url; 31 31 List<PluginDescription>plugins = new ArrayList<PluginDescription>(); 32 32 33 33 /** 34 34 * Default Constructor … … 47 47 this.url = new URL(url); 48 48 } 49 49 50 50 /** 51 51 * @param name … … 56 56 this.name = name; 57 57 } 58 58 59 59 60 60 /** … … 71 71 } 72 72 73 73 74 74 /** 75 75 * Load the site description from the url. 76 * @throws IOException 76 * @throws IOException 77 77 */ 78 78 public void loadFromUrl() throws IOException { … … 84 84 // TODO check and remember modified since date to compare and not load sites that did not change 85 85 // connection.getIfModifiedSince() 86 // </FIXXME> 87 86 // </FIXXME> 87 88 88 Reader in = new InputStreamReader(connection.getInputStream()); 89 89 SiteDescriptionParser parser = new SiteDescriptionParser(this); … … 111 111 if(info != null) { 112 112 if(info.version == null) { 113 plugin.setInstalledVersion("?"); 113 plugin.setInstalledVersion("?"); 114 114 } else { 115 115 plugin.setInstalledVersion(info.version); … … 118 118 } 119 119 } 120 120 121 121 /** 122 122 * @return the plugins … … 133 133 } 134 134 135 135 136 136 /** 137 137 * @return the url … … 158 158 return name; 159 159 } 160 160 161 161 } 162 162 163 163 /** 164 164 * Used by ListCellRenderer, so not only a debug method! … … 168 168 return getLabelName(); 169 169 } 170 170 171 171 public static void main(String[] args) { 172 172 try { -
applications/editors/josm/plugins/pluginmanager/src/at/dallermassl/josm/plugin/pluginmanager/SiteDescriptionParser.java
r9948 r12778 1 1 /** 2 * 2 * 3 3 */ 4 4 package at.dallermassl.josm.plugin.pluginmanager; … … 23 23 private StringBuilder characters; 24 24 private VariableHelper variableHelper; 25 25 26 26 /** 27 27 * Constructor using a new SiteDescription object. … … 33 33 * Constructor using a description object to fill. 34 34 * @param siteDescription the object to fill. 35 * @param in the reader to fill the description with. 35 * @param in the reader to fill the description with. 36 36 */ 37 37 public SiteDescriptionParser(SiteDescription siteDescription) { 38 38 this.siteDescription = siteDescription; 39 39 } 40 40 41 41 /** 42 42 * Returns the site description object. … … 117 117 } 118 118 } 119 120 /** 119 120 /** 121 121 * Read characters for description. 122 122 */ … … 127 127 characters.append(data, start, length); 128 128 } 129 129 130 130 /* (non-Javadoc) 131 131 * @see uk.co.wilson.xml.MinML2#endElement(java.lang.String, java.lang.String, java.lang.String) … … 158 158 } 159 159 } 160 160 161 161 /** 162 162 * Clears the characters and returns the its previous content. … … 168 168 return chars; 169 169 } 170 171 170 171 172 172 173 173 } -
applications/editors/josm/plugins/pluginmanager/src/at/dallermassl/josm/plugin/pluginmanager/VariableHelper.java
r3335 r12778 1 1 /** 2 * 2 * 3 3 */ 4 4 package at.dallermassl.josm.plugin.pluginmanager; … … 10 10 11 11 /** 12 * Helper class that replaces variables in strings with its values. The variables are in the 12 * Helper class that replaces variables in strings with its values. The variables are in the 13 13 * form ${name}. Replacement values may be set. As a fallback (if the variable is not found) 14 14 * the system properties are used. If neither is found, the variable is not replaced. 15 * 15 * 16 16 * @author cdaller 17 17 * … … 20 20 private Pattern varPattern = Pattern.compile("\\$\\{(.+?)\\}"); 21 21 private Map<String, String> variables; 22 22 23 23 public VariableHelper() { 24 24 variables = new HashMap<String, String>(); 25 25 } 26 26 27 27 /** 28 28 * Adds all key/values as variables. … … 32 32 variables.putAll(values); 33 33 } 34 34 35 35 /** 36 36 * Adds a single key/value pair. … … 41 41 variables.put(key, value); 42 42 } 43 43 44 44 /** 45 45 * Replaces all variable placeholder in the given string with the replacement. … … 71 71 return source.toString(); 72 72 } 73 73 74 74 public static void main(String[] args) { 75 75 VariableHelper helper = new VariableHelper(); -
applications/editors/josm/plugins/remotecontrol/src/org/openstreetmap/josm/plugins/remotecontrol/HttpServer.java
r9465 r12778 8 8 9 9 /** 10 * Simple HTTP server that spawns a {@link RequestProcessor} for every 10 * Simple HTTP server that spawns a {@link RequestProcessor} for every 11 11 * connection. 12 12 * … … 17 17 18 18 /** Default port for the HTTP server */ 19 public static final int DEFAULT_PORT = 8111; 20 21 /** The server socket */ 22 private ServerSocket server; 19 public static final int DEFAULT_PORT = 8111; 23 20 24 /** 25 * Constructor 26 * @param port The port this server will listen on 27 * @throws IOException when connection errors 28 */ 29 public HttpServer(int port) 30 throws IOException 31 { 32 super("RemoteControl HTTP Server"); 33 this.setDaemon(true); 34 // Start the server socket with only 1 connection. 21 /** The server socket */ 22 private ServerSocket server; 23 24 /** 25 * Constructor 26 * @param port The port this server will listen on 27 * @throws IOException when connection errors 28 */ 29 public HttpServer(int port) 30 throws IOException 31 { 32 super("RemoteControl HTTP Server"); 33 this.setDaemon(true); 34 // Start the server socket with only 1 connection. 35 35 // Also make sure we only listen 36 36 // on the local interface so nobody from the outside can connect! 37 this.server = new ServerSocket(port, 1, 37 this.server = new ServerSocket(port, 1, 38 38 InetAddress.getByAddress(new byte[] { 127, 0, 0, 1 })); 39 39 } 40 40 41 42 43 44 public void run() 45 46 47 while (true) 48 49 try 50 51 52 53 54 55 56 57 58 59 catch (IOException ioe) 60 61 62 63 64 65 66 41 /** 42 * The main loop, spawns a {@link RequestProcessor} for each connection 43 */ 44 public void run() 45 { 46 System.out.println("RemoteControl::Accepting connections on port " + server.getLocalPort()); 47 while (true) 48 { 49 try 50 { 51 Socket request = server.accept(); 52 RequestProcessor.processRequest(request); 53 } 54 catch( SocketException se) 55 { 56 if( !server.isClosed() ) 57 se.printStackTrace(); 58 } 59 catch (IOException ioe) 60 { 61 ioe.printStackTrace(); 62 } 63 } 64 } 65 66 /** 67 67 * Stops the HTTP server 68 * 68 * 69 69 * @throws IOException 70 71 72 73 74 70 */ 71 public void stopServer() throws IOException 72 { 73 server.close(); 74 } 75 75 } -
applications/editors/josm/plugins/remotecontrol/src/org/openstreetmap/josm/plugins/remotecontrol/RemoteControlPlugin.java
r9417 r12778 12 12 public class RemoteControlPlugin extends Plugin 13 13 { 14 15 14 /** The HTTP server this plugin launches */ 15 static HttpServer server; 16 16 17 18 19 20 21 22 23 24 17 /** 18 * Creates the plugin, and starts the HTTP server 19 */ 20 public RemoteControlPlugin() 21 { 22 restartServer(); 23 } 24 25 25 @Override 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 26 public PreferenceSetting getPreferenceSetting() 27 { 28 return new RemoteControlPreferences(); 29 } 30 31 /** 32 * Starts or restarts the HTTP server 33 * 34 */ 35 public void restartServer() 36 { 37 try 38 { 39 if (server != null) 40 server.stopServer(); 41 42 int port = HttpServer.DEFAULT_PORT; 43 server = new HttpServer(port); 44 server.start(); 45 } 46 catch(IOException ioe) 47 { 48 ioe.printStackTrace(); 49 } 50 } 51 51 } -
applications/editors/josm/plugins/remotecontrol/src/org/openstreetmap/josm/plugins/remotecontrol/RemoteControlPreferences.java
r12588 r12778 18 18 /** 19 19 * Preference settings for the Remote Control plugin 20 * 20 * 21 21 * @author Frederik Ramm 22 22 */ 23 23 public class RemoteControlPreferences implements PreferenceSetting 24 24 { 25 26 27 28 29 30 public void addGui(final PreferenceDialog gui) 25 private JCheckBox permissionLoadData = new JCheckBox(tr("load data from API")); 26 private JCheckBox permissionChangeSelection = new JCheckBox(tr("change the selection")); 27 private JCheckBox permissionChangeViewport = new JCheckBox(tr("change the viewport")); 28 private JCheckBox alwaysAskUserConfirm = new JCheckBox(tr("confirm all Remote Control actions manually")); 29 30 public void addGui(final PreferenceDialog gui) 31 31 { 32 33 34 35 36 JPanel remote = gui.createPreferenceTab("remotecontrol.gif", tr("Remote Control"), tr("Settings for the Remote Control plugin."));37 remote.add(new JLabel("<html>"+tr("The Remote Control plugin will always listen on port 8111 on localhost." +38 32 Version ver = Util.getVersion(); 33 String description = tr("A plugin that allows JOSM to be controlled from other applications."); 34 if (ver != null) 35 description += "<br><br>" + tr("Version: {0}<br>Last change at {1}", ver.revision, ver.time) + "<br><br>"; 36 JPanel remote = gui.createPreferenceTab("remotecontrol.gif", tr("Remote Control"), tr("Settings for the Remote Control plugin.")); 37 remote.add(new JLabel("<html>"+tr("The Remote Control plugin will always listen on port 8111 on localhost." + 38 "The port is not variable because it is referenced by external applications talking to the plugin.") + "</html>"), GBC.eol().insets(0,5,0,10).fill(GBC.HORIZONTAL)); 39 39 40 41 42 40 JPanel perms = new JPanel(); 41 perms.setLayout(new GridBagLayout()); 42 perms.setBorder(BorderFactory.createTitledBorder(BorderFactory.createLineBorder(Color.gray), tr("Permitted actions"))); 43 43 perms.add(permissionLoadData, GBC.eol().insets(0,5,0,0).fill(GBC.HORIZONTAL)); 44 44 perms.add(permissionChangeSelection, GBC.eol().insets(0,5,0,0).fill(GBC.HORIZONTAL)); 45 perms.add(permissionChangeViewport, GBC.eol().insets(0,5,0,0).fill(GBC.HORIZONTAL)); 45 perms.add(permissionChangeViewport, GBC.eol().insets(0,5,0,0).fill(GBC.HORIZONTAL)); 46 46 remote.add(perms, GBC.eol().fill(GBC.HORIZONTAL)); 47 47 48 48 remote.add(alwaysAskUserConfirm, GBC.eol().insets(0,5,0,0).fill(GBC.HORIZONTAL)); 49 49 remote.add(Box.createVerticalGlue(), GBC.eol().fill(GBC.VERTICAL)); 50 50 51 51 52 52 permissionLoadData.setSelected(Main.pref.getBoolean("remotecontrol.permission.load-data", true)); 53 53 permissionChangeSelection.setSelected(Main.pref.getBoolean("remotecontrol.permission.change-selection", true)); 54 54 permissionChangeViewport.setSelected(Main.pref.getBoolean("remotecontrol.permission.change-viewport", true)); 55 55 alwaysAskUserConfirm.setSelected(Main.pref.getBoolean("remotecontrol.always-confirm", false)); 56 56 57 57 } 58 58 59 59 public boolean ok() { 60 61 62 63 64 60 Main.pref.put("remotecontrol.permission.load-data", permissionLoadData.isSelected()); 61 Main.pref.put("remotecontrol.permission.change-selection", permissionChangeSelection.isSelected()); 62 Main.pref.put("remotecontrol.permission.change-viewport", permissionChangeViewport.isSelected()); 63 Main.pref.put("remotecontrol.always-confirm", alwaysAskUserConfirm.isSelected()); 64 return false; 65 65 } 66 66 } -
applications/editors/josm/plugins/remotecontrol/src/org/openstreetmap/josm/plugins/remotecontrol/RequestProcessor.java
r12431 r12778 30 30 * Processes HTTP "remote control" requests. 31 31 */ 32 public class RequestProcessor extends Thread 32 public class RequestProcessor extends Thread 33 33 { 34 35 36 37 38 39 40 41 42 43 * 44 * @param request 45 46 public RequestProcessor(Socket request) 47 48 49 50 51 52 53 54 55 * 56 57 58 public static void processRequest(Socket request) 59 60 61 62 } 63 64 65 66 67 public void run() 68 69 70 try 71 { 72 OutputStream raw = new BufferedOutputStream( request.getOutputStream()); 73 74 75 76 77 while (true) 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 34 /** The socket this processor listens on */ 35 private Socket request; 36 37 private class AlreadyLoadedException extends Exception {}; 38 private class DeniedException extends Exception {}; 39 private class LoadDeniedException extends Exception {}; 40 41 /** 42 * Constructor 43 * 44 * @param request 45 */ 46 public RequestProcessor(Socket request) 47 { 48 super("RemoteControl request processor"); 49 this.setDaemon(true); 50 this.request = request; 51 } 52 53 /** 54 * Spawns a new thread for the request 55 * 56 * @param request The WMS request 57 */ 58 public static void processRequest(Socket request) 59 { 60 RequestProcessor processor = new RequestProcessor(request); 61 processor.start(); 62 } 63 64 /** 65 * The work is done here. 66 */ 67 public void run() 68 { 69 Writer out = null; 70 try 71 { 72 OutputStream raw = new BufferedOutputStream( request.getOutputStream()); 73 out = new OutputStreamWriter(raw); 74 Reader in = new InputStreamReader(new BufferedInputStream(request.getInputStream()), "ASCII"); 75 76 StringBuffer requestLine = new StringBuffer(); 77 while (true) 78 { 79 int c = in.read(); 80 if (c == '\r' || c == '\n') break; 81 requestLine.append((char) c); 82 } 83 84 System.out.println("RemoteControl received: " + requestLine); 85 String get = requestLine.toString(); 86 StringTokenizer st = new StringTokenizer(get); 87 String method = st.nextToken(); 88 String url = st.nextToken(); 89 90 if(!method.equals("GET")) { 91 sendNotImplemented(out); 92 return; 93 } 94 94 95 95 st = new StringTokenizer(url, "&?"); 96 String command = null; 96 String command = null; 97 97 HashMap<String,String> args = new HashMap<String,String>(); 98 98 while (st.hasMoreTokens()) … … 106 106 } 107 107 } 108 108 109 109 if (command.equals("/load_and_zoom")) { 110 111 112 110 if (Main.pref.getBoolean("remotecontrol.always-confirm", false)) { 111 if (JOptionPane.showConfirmDialog(Main.parent, 112 "<html>" + tr("Remote Control has been asked to load data from the API.") + 113 113 "<br>" + tr("Request details: {0}", url) + "<br>" + tr("Do you want to allow this?"), 114 115 116 117 118 119 120 121 if (!(args.containsKey("bottom") && args.containsKey("top") && 122 123 124 125 return; 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 if (item.startsWith("way")){175 176 177 178 179 180 181 182 183 184 185 186 for (Relation r : Main.ds.relations) if (relations.contains(r.id)) newSel.add(r); 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 114 tr("Confirm Remote Control action"), 115 JOptionPane.YES_NO_OPTION) != JOptionPane.YES_OPTION) { 116 sendForbidden(out); 117 return; 118 } 119 } 120 DownloadTask osmTask = new DownloadOsmTask(); 121 if (!(args.containsKey("bottom") && args.containsKey("top") && 122 args.containsKey("left") && args.containsKey("right"))) { 123 sendBadRequest(out); 124 System.out.println("load_and_zoom remote control request must have bottom,top,left,right parameters"); 125 return; 126 } 127 double minlat = 0; 128 double maxlat = 0; 129 double minlon = 0; 130 double maxlon = 0; 131 try { 132 minlat = Double.parseDouble(args.get("bottom")); 133 maxlat = Double.parseDouble(args.get("top")); 134 minlon = Double.parseDouble(args.get("left")); 135 maxlon = Double.parseDouble(args.get("right")); 136 137 if (!Main.pref.getBoolean("remotecontrol.permission.load-data", true)) 138 throw new LoadDeniedException(); 139 140 // find out whether some data has already been downloaded 141 Area present = Main.ds.getDataSourceArea(); 142 if (present != null && !present.isEmpty()) { 143 Area toDownload = new Area(new Rectangle2D.Double(minlon,minlat,maxlon-minlon,maxlat-minlat)); 144 toDownload.subtract(present); 145 if (toDownload.isEmpty()) throw new AlreadyLoadedException(); 146 // the result might not be a rectangle (L shaped etc) 147 Rectangle2D downloadBounds = toDownload.getBounds2D(); 148 minlat = downloadBounds.getMinY(); 149 minlon = downloadBounds.getMinX(); 150 maxlat = downloadBounds.getMaxY(); 151 maxlon = downloadBounds.getMaxX(); 152 } 153 osmTask.download(null, minlat,minlon,maxlat,maxlon); 154 } catch (AlreadyLoadedException ex) { 155 System.out.println("RemoteControl: no download necessary"); 156 } catch (LoadDeniedException ex) { 157 System.out.println("RemoteControl: download forbidden by preferences"); 158 } catch (Exception ex) { 159 sendError(out); 160 System.out.println("RemoteControl: Error parsing load_and_zoom remote control request:"); 161 ex.printStackTrace(); 162 return; 163 } 164 if (args.containsKey("select") && Main.pref.getBoolean("remotecontrol.permission.change-selection", true)) { 165 // select objects after downloading, zoom to selection. 166 final String selection = args.get("select"); 167 Main.worker.execute(new Runnable() { 168 public void run() { 169 HashSet<Long> ways = new HashSet<Long>(); 170 HashSet<Long> nodes = new HashSet<Long>(); 171 HashSet<Long> relations = new HashSet<Long>(); 172 HashSet<OsmPrimitive> newSel = new HashSet<OsmPrimitive>(); 173 for (String item : selection.split(",")) { 174 if (item.startsWith("way")) { 175 ways.add(Long.parseLong(item.substring(3))); 176 } else if (item.startsWith("node")) { 177 nodes.add(Long.parseLong(item.substring(4))); 178 } else if (item.startsWith("relation")) { 179 relations.add(Long.parseLong(item.substring(8))); 180 } else { 181 System.out.println("RemoteControl: invalid selection '"+item+"' ignored"); 182 } 183 } 184 for (Way w : Main.ds.ways) if (ways.contains(w.id)) newSel.add(w); 185 for (Node n : Main.ds.nodes) if (nodes.contains(n.id)) newSel.add(n); 186 for (Relation r : Main.ds.relations) if (relations.contains(r.id)) newSel.add(r); 187 Main.ds.setSelected(newSel); 188 if (Main.pref.getBoolean("remotecontrol.permission.change-viewport", true)) 189 new AutoScaleAction("selection").actionPerformed(null); 190 } 191 }); 192 } else if (Main.pref.getBoolean("remotecontrol.permission.change-viewport", true)) { 193 // after downloading, zoom to downloaded area. 194 final LatLon min = new LatLon(minlat, minlon); 195 final LatLon max = new LatLon(maxlat, maxlon); 196 197 Main.worker.execute(new Runnable() { 198 public void run() { 199 BoundingXYVisitor bbox = new BoundingXYVisitor(); 200 bbox.min = Main.proj.latlon2eastNorth(min); 201 bbox.max = Main.proj.latlon2eastNorth(max); 202 Main.map.mapView.recalculateCenterScale(bbox); 203 } 204 }); 205 } 206 206 } else if (command.equals("/import")) { 207 208 209 "<html>" + tr("Remote Control has been asked to import data from the following URL:") +210 "<br>" + url + 207 if (Main.pref.getBoolean("remotecontrol.always-confirm", false)) { 208 if (JOptionPane.showConfirmDialog(Main.parent, 209 "<html>" + tr("Remote Control has been asked to import data from the following URL:") + 210 "<br>" + url + 211 211 "<br>" + tr("Do you want to allow this?"), 212 213 214 215 216 217 218 219 220 221 return; 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 212 tr("Confirm Remote Control action"), 213 JOptionPane.YES_NO_OPTION) != JOptionPane.YES_OPTION) { 214 sendForbidden(out); 215 return; 216 } 217 } 218 if (!(args.containsKey("url"))) { 219 sendBadRequest(out); 220 System.out.println("'import' remote control request must have url parameter"); 221 return; 222 } 223 try { 224 if (!Main.pref.getBoolean("remotecontrol.permission.import", true)) 225 throw new LoadDeniedException(); 226 227 DownloadTask osmTask = new DownloadOsmTask(); 228 osmTask.loadUrl(false, URLDecoder.decode(args.get("url"), "UTF-8")); 229 } catch (LoadDeniedException ex) { 230 System.out.println("RemoteControl: import forbidden by preferences"); 231 } catch (Exception ex) { 232 sendError(out); 233 System.out.println("RemoteControl: Error parsing import remote control request:"); 234 ex.printStackTrace(); 235 return; 236 } 237 237 // TODO: select/zoom to downloaded 238 238 } 239 239 sendHeader(out, "200 OK", "text/plain", false); 240 240 out.write("Content-length: 4\r\n"); 241 241 out.write("\r\n"); 242 242 out.write("OK\r\n"); 243 243 out.flush(); 244 245 246 247 248 249 250 251 252 253 request.close(); 254 } catch (IOException e) {} 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 244 } 245 catch (IOException ioe) { } 246 catch(Exception e) { 247 e.printStackTrace(); 248 try { 249 sendError(out); 250 } catch (IOException e1) { } 251 } finally { 252 try { 253 request.close(); 254 } catch (IOException e) {} 255 } 256 } 257 258 /** 259 * Sends a 500 error: server error 260 * @param out The writer where the error is written 261 * @throws IOException If the error can not be written 262 */ 263 private void sendError(Writer out) throws IOException 264 { 265 sendHeader(out, "500 Internal Server Error", "text/html", true); 266 out.write("<HTML>\r\n"); 267 out.write("<HEAD><TITLE>Internal Error</TITLE>\r\n"); 268 out.write("</HEAD>\r\n"); 269 out.write("<BODY>"); 270 out.write("<H1>HTTP Error 500: Internal Server Error</h2>\r\n"); 271 out.write("</BODY></HTML>\r\n"); 272 out.flush(); 273 } 274 275 /** 276 * Sends a 501 error: not implemented 277 * @param out The writer where the error is written 278 * @throws IOException If the error can not be written 279 */ 280 private void sendNotImplemented(Writer out) throws IOException 281 { 282 sendHeader(out, "501 Not Implemented", "text/html", true); 283 out.write("<HTML>\r\n"); 284 out.write("<HEAD><TITLE>Not Implemented</TITLE>\r\n"); 285 out.write("</HEAD>\r\n"); 286 out.write("<BODY>"); 287 out.write("<H1>HTTP Error 501: Not Implemented</h2>\r\n"); 288 out.write("</BODY></HTML>\r\n"); 289 out.flush(); 290 } 291 292 /** 293 * Sends a 403 error: forbidden 294 * @param out The writer where the error is written 295 * @throws IOException If the error can not be written 296 */ 297 private void sendForbidden(Writer out) throws IOException 298 { 299 sendHeader(out, "403 Forbidden", "text/html", true); 300 out.write("<HTML>\r\n"); 301 out.write("<HEAD><TITLE>Forbidden</TITLE>\r\n"); 302 out.write("</HEAD>\r\n"); 303 out.write("<BODY>"); 304 out.write("<H1>HTTP Error 403: Forbidden</h2>\r\n"); 305 out.write("</BODY></HTML>\r\n"); 306 out.flush(); 307 } 308 /** 309 * Sends a 403 error: forbidden 310 * @param out The writer where the error is written 311 * @throws IOException If the error can not be written 312 */ 313 private void sendBadRequest(Writer out) throws IOException 314 { 315 sendHeader(out, "400 Bad Request", "text/html", true); 316 out.write("<HTML>\r\n"); 317 out.write("<HEAD><TITLE>Bad Request</TITLE>\r\n"); 318 out.write("</HEAD>\r\n"); 319 out.write("<BODY>"); 320 out.write("<H1>HTTP Error 400: Bad Request</h2>\r\n"); 321 out.write("</BODY></HTML>\r\n"); 322 out.flush(); 323 } 324 325 /** 326 * Send common HTTP headers to the client. 327 * 328 * @param out The Writer 329 * @param status The status string ("200 OK", "500", etc) 330 * @param contentType The content type of the data sent 331 * @param endHeaders If true, adds a new line, ending the headers. 332 * @throws IOException When error 333 */ 334 private void sendHeader(Writer out, String status, String contentType, boolean endHeaders) throws IOException 335 { 336 out.write("HTTP/1.1 " + status + "\r\n"); 337 Date now = new Date(); 338 out.write("Date: " + now + "\r\n"); 339 339 out.write("Server: JOSM RemoteControl\r\n"); 340 340 out.write("Content-type: " + contentType + "\r\n"); 341 341 if (endHeaders) 342 343 342 out.write("\r\n"); 343 } 344 344 } -
applications/editors/josm/plugins/remotecontrol/src/org/openstreetmap/josm/plugins/remotecontrol/Util.java
r9465 r12778 17 17 /** 18 18 * Utility class 19 * 19 * 20 20 */ 21 public class Util 21 public class Util 22 22 { 23 23 /** 24 24 * Utility method to retrieve the plugin for classes that can't access to the plugin object directly. 25 * 25 * 26 26 * @param clazz The plugin class 27 27 * @return The YWMS plugin … … 29 29 public static Plugin getPlugin(Class<? extends Plugin> clazz) 30 30 { 31 31 String classname = clazz.getName(); 32 32 for (PluginProxy plugin : Main.plugins) 33 33 { … … 39 39 return null; 40 40 } 41 42 /**43 * Returns the plugin's directory of the plugin44 *45 * @return The directory of the plugin46 */47 public static String getPluginDir()48 {49 return Main.pref.getPreferencesDir() + "plugins/ywms/";50 }51 41 52 /** 53 * Returns the version 54 * @return The version of the application 55 */ 56 public static Version getVersion() 42 /** 43 * Returns the plugin's directory of the plugin 44 * 45 * @return The directory of the plugin 46 */ 47 public static String getPluginDir() 48 { 49 return Main.pref.getPreferencesDir() + "plugins/ywms/"; 50 } 51 52 /** 53 * Returns the version 54 * @return The version of the application 55 */ 56 public static Version getVersion() 57 57 { 58 58 PluginInformation info = PluginInformation.getLoaded("ywms"); 59 if (info == null) 59 if (info == null) 60 60 return null; 61 61 … … 65 65 /** 66 66 * Utility class for displaying versions 67 * 67 * 68 68 * @author frsantos 69 69 */ 70 70 public static class Version 71 71 { 72 73 74 75 76 72 /** The revision */ 73 public String revision; 74 /** The build time */ 75 public String time; 76 77 77 /** 78 78 * Constructor … … 80 80 * @param time 81 81 */ 82 public Version(String revision, String time) 82 public Version(String revision, String time) 83 83 { 84 85 86 84 this.revision = revision; 85 this.time = time; 86 } 87 87 } 88 88 } -
applications/editors/josm/plugins/slippy_map_chooser/src/OsmMapControl.java
r9623 r12778 23 23 public class OsmMapControl extends MouseAdapter implements MouseMotionListener, MouseListener { 24 24 25 26 27 25 // start and end point of selection rectangle 26 private Point iStartSelectionPoint; 27 private Point iEndSelectionPoint; 28 28 29 30 29 // the SlippyMapChooserComponent 30 private final SlippyMapChooser iSlippyMapChooser; 31 31 32 33 32 private SizeButton iSizeButton = null; 33 private SourceButton iSourceButton = null; 34 34 35 36 37 38 39 40 41 35 /** 36 * Create a new OsmMapControl 37 */ 38 public OsmMapControl(SlippyMapChooser navComp, JPanel contentPane, SizeButton sizeButton, SourceButton sourceButton) { 39 this.iSlippyMapChooser = navComp; 40 iSlippyMapChooser.addMouseListener(this); 41 iSlippyMapChooser.addMouseMotionListener(this); 42 42 43 44 45 46 43 String[] n = { ",", ".", "up", "right", "down", "left" }; 44 int[] k = 45 { KeyEvent.VK_COMMA, KeyEvent.VK_PERIOD, KeyEvent.VK_UP, KeyEvent.VK_RIGHT, 46 KeyEvent.VK_DOWN, KeyEvent.VK_LEFT }; 47 47 48 49 50 51 52 53 54 55 56 57 48 if (contentPane != null) { 49 for (int i = 0; i < n.length; ++i) { 50 contentPane.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put( 51 KeyStroke.getKeyStroke(k[i], KeyEvent.CTRL_DOWN_MASK), 52 "MapMover.Zoomer." + n[i]); 53 } 54 } 55 iSizeButton = sizeButton; 56 iSourceButton = sourceButton; 57 } 58 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 59 /** 60 * Start drawing the selection rectangle if it was the 1st button (left 61 * button) 62 */ 63 @Override 64 public void mousePressed(MouseEvent e) { 65 if (e.getButton() == MouseEvent.BUTTON1) { 66 if (!iSizeButton.hit(e.getPoint())) { 67 iStartSelectionPoint = e.getPoint(); 68 iEndSelectionPoint = e.getPoint(); 69 } 70 } 71 72 } 73 73 74 public void mouseDragged(MouseEvent e) { 75 76 if (iStartSelectionPoint != null) { 77 78 79 80 81 74 public void mouseDragged(MouseEvent e) { 75 if((e.getModifiersEx() & MouseEvent.BUTTON1_DOWN_MASK) == MouseEvent.BUTTON1_DOWN_MASK){ 76 if (iStartSelectionPoint != null) { 77 iEndSelectionPoint = e.getPoint(); 78 iSlippyMapChooser.setSelection(iStartSelectionPoint, iEndSelectionPoint); 79 } 80 } 81 } 82 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 83 /** 84 * When dragging the map change the cursor back to it's pre-move cursor. If 85 * a double-click occurs center and zoom the map on the clicked location. 86 */ 87 @Override 88 public void mouseReleased(MouseEvent e) { 89 if (e.getButton() == MouseEvent.BUTTON1) { 90 91 int sourceButton = iSourceButton.hit(e.getPoint()); 92 93 if (iSizeButton.hit(e.getPoint())) { 94 iSizeButton.toggle(); 95 iSlippyMapChooser.resizeSlippyMap(); 96 } 97 else if(sourceButton == SourceButton.HIDE_OR_SHOW) { 98 iSourceButton.toggle(); 99 iSlippyMapChooser.repaint(); 100 101 }else if(sourceButton == SourceButton.MAPNIK || sourceButton == SourceButton.OSMARENDER) { 102 iSlippyMapChooser.toggleMapSource(sourceButton); 103 } 104 else { 105 if (e.getClickCount() == 1) { 106 iSlippyMapChooser.setSelection(iStartSelectionPoint, e.getPoint()); 107 107 108 109 110 111 112 113 114 115 108 // reset the selections start and end 109 iEndSelectionPoint = null; 110 iStartSelectionPoint = null; 111 } 112 } 113 114 } 115 } 116 116 117 118 117 public void mouseMoved(MouseEvent e) { 118 } 119 119 120 120 } -
applications/editors/josm/plugins/slippy_map_chooser/src/SizeButton.java
r7199 r12778 15 15 */ 16 16 public class SizeButton{ 17 18 19 20 21 22 23 24 25 26 27 28 shrinkImage = ImageProvider.get("", "view-fullscreen-revert.png"); 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 if(y < point.y && point.y < y + enlargeImage.getIconHeight() ){ 48 49 50 51 52 17 18 private int x = 0; 19 private int y = 0; 20 21 private ImageIcon enlargeImage; 22 private ImageIcon shrinkImage; 23 private boolean isEnlarged = false; 24 25 26 public SizeButton(){ 27 enlargeImage = ImageProvider.get("", "view-fullscreen.png"); 28 shrinkImage = ImageProvider.get("", "view-fullscreen-revert.png"); 29 } 30 31 public void paint(Graphics g){ 32 if(isEnlarged){ 33 if(shrinkImage != null) 34 g.drawImage(shrinkImage.getImage(),x,y, null); 35 }else{ 36 if(enlargeImage != null) 37 g.drawImage(enlargeImage.getImage(),x,y, null); 38 } 39 } 40 41 public void toggle(){ 42 isEnlarged = !isEnlarged; 43 } 44 45 public boolean hit(Point point){ 46 if(x < point.x && point.x < x + enlargeImage.getIconWidth()){ 47 if(y < point.y && point.y < y + enlargeImage.getIconHeight() ){ 48 return true; 49 } 50 } 51 return false; 52 } 53 53 54 54 } -
applications/editors/josm/plugins/slippy_map_chooser/src/SlippyMapChooser.java
r10310 r12778 40 40 public class SlippyMapChooser extends JMapViewer implements DownloadSelection, ComponentListener { 41 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 42 private DownloadDialog iGui; 43 44 // upper left and lower right corners of the selection rectangle (x/y on 45 // ZOOM_MAX) 46 Point iSelectionRectStart; 47 Point iSelectionRectEnd; 48 49 private SizeButton iSizeButton = new SizeButton(); 50 private SourceButton iSourceButton = new SourceButton(); 51 52 // standard dimension 53 private Dimension iDownloadDialogDimension; 54 // screen size 55 private Dimension iScreenSize; 56 57 private TileSource[] sources = { new OsmTileSource.Mapnik(), new OsmTileSource.TilesAtHome() }; 58 TileLoader cachedLoader; 59 TileLoader uncachedLoader; 60 JPanel slipyyMapTabPanel; 61 boolean firstShown = true; 62 63 /** 64 * Create the chooser component. 65 */ 66 public SlippyMapChooser() { 67 super(); 68 cachedLoader = new OsmFileCacheTileLoader(this); 69 uncachedLoader = new OsmTileLoader(this); 70 setZoomContolsVisible(false); 71 setMapMarkerVisible(false); 72 setMinimumSize(new Dimension(350, 350 / 2)); 73 setFileCacheEnabled(SlippyMapChooserPlugin.ENABLE_FILE_CACHE); 74 setMaxTilesInmemory(SlippyMapChooserPlugin.MAX_TILES_IN_MEMORY); 75 addComponentListener(this); 76 } 77 78 public void setMaxTilesInmemory(int tiles) { 79 ((MemoryTileCache) getTileCache()).setCacheSize(tiles); 80 } 81 82 public void setFileCacheEnabled(boolean enabled) { 83 if (enabled) 84 setTileLoader(cachedLoader); 85 else 86 setTileLoader(uncachedLoader); 87 } 88 89 public void addGui(final DownloadDialog gui) { 90 iGui = gui; 91 slipyyMapTabPanel = new JPanel(); 92 slipyyMapTabPanel.setLayout(new BorderLayout()); 93 slipyyMapTabPanel.add(this, BorderLayout.CENTER); 94 slipyyMapTabPanel.add(new JLabel((tr("Zoom: Mousewheel or double click. " 95 + "Move map: Hold right mousebutton and move mouse. Select: Click."))), 96 BorderLayout.SOUTH); 97 iGui.tabpane.add(slipyyMapTabPanel, tr("Slippy map")); 98 iGui.tabpane.addComponentListener(this); 99 new OsmMapControl(this, slipyyMapTabPanel, iSizeButton, iSourceButton); 100 } 101 102 protected Point getTopLeftCoordinates() { 103 return new Point(center.x - (getWidth() / 2), center.y - (getHeight() / 2)); 104 } 105 106 /** 107 * Draw the map. 108 */ 109 @Override 110 public void paint(Graphics g) { 111 try { 112 super.paint(g); 113 114 // draw selection rectangle 115 if (iSelectionRectStart != null && iSelectionRectEnd != null) { 116 117 int zoomDiff = MAX_ZOOM - zoom; 118 Point tlc = getTopLeftCoordinates(); 119 int x_min = (iSelectionRectStart.x >> zoomDiff) - tlc.x; 120 int y_min = (iSelectionRectStart.y >> zoomDiff) - tlc.y; 121 int x_max = (iSelectionRectEnd.x >> zoomDiff) - tlc.x; 122 int y_max = (iSelectionRectEnd.y >> zoomDiff) - tlc.y; 123 124 int w = x_max - x_min; 125 int h = y_max - y_min; 126 g.setColor(new Color(0.9f, 0.7f, 0.7f, 0.6f)); 127 g.fillRect(x_min, y_min, w, h); 128 129 g.setColor(Color.BLACK); 130 g.drawRect(x_min, y_min, w, h); 131 132 } 133 134 iSizeButton.paint(g); 135 iSourceButton.paint(g); 136 } catch (Exception e) { 137 e.printStackTrace(); 138 } 139 } 140 141 public void boundingBoxChanged(DownloadDialog gui) { 142 143 // test if a bounding box has been set set 144 if (gui.minlat == 0.0 && gui.minlon == 0.0 && gui.maxlat == 0.0 && gui.maxlon == 0.0) 145 return; 146 147 int y1 = OsmMercator.LatToY(gui.minlat, MAX_ZOOM); 148 int y2 = OsmMercator.LatToY(gui.maxlat, MAX_ZOOM); 149 int x1 = OsmMercator.LonToX(gui.minlon, MAX_ZOOM); 150 int x2 = OsmMercator.LonToX(gui.maxlon, MAX_ZOOM); 151 152 iSelectionRectStart = new Point(Math.min(x1, x2), Math.min(y1, y2)); 153 iSelectionRectEnd = new Point(Math.max(x1, x2), Math.max(y1, y2)); 154 155 // calc the screen coordinates for the new selection rectangle 156 MapMarkerDot xmin_ymin = new MapMarkerDot(gui.minlat, gui.minlon); 157 MapMarkerDot xmax_ymax = new MapMarkerDot(gui.maxlat, gui.maxlon); 158 159 Vector<MapMarker> marker = new Vector<MapMarker>(2); 160 marker.add(xmin_ymin); 161 marker.add(xmax_ymax); 162 setMapMarkerList(marker); 163 setDisplayToFitMapMarkers(); 164 zoomOut(); 165 } 166 167 /** 168 * Callback for the OsmMapControl. (Re-)Sets the start and end point of the 169 * selection rectangle. 170 * 171 * @param aStart 172 * @param aEnd 173 */ 174 public void setSelection(Point aStart, Point aEnd) { 175 if (aStart == null || aEnd == null) 176 return; 177 Point p_max = new Point(Math.max(aEnd.x, aStart.x), Math.max(aEnd.y, aStart.y)); 178 Point p_min = new Point(Math.min(aEnd.x, aStart.x), Math.min(aEnd.y, aStart.y)); 179 180 Point tlc = getTopLeftCoordinates(); 181 int zoomDiff = MAX_ZOOM - zoom; 182 Point pEnd = new Point(p_max.x + tlc.x, p_max.y + tlc.y); 183 Point pStart = new Point(p_min.x + tlc.x, p_min.y + tlc.y); 184 185 pEnd.x <<= zoomDiff; 186 pEnd.y <<= zoomDiff; 187 pStart.x <<= zoomDiff; 188 pStart.y <<= zoomDiff; 189 190 iSelectionRectStart = pStart; 191 iSelectionRectEnd = pEnd; 192 193 Point2D.Double l1 = getPosition(p_max); 194 Point2D.Double l2 = getPosition(p_min); 195 iGui.minlat = Math.min(l2.x, l1.x); 196 iGui.minlon = Math.min(l1.y, l2.y); 197 iGui.maxlat = Math.max(l2.x, l1.x); 198 iGui.maxlon = Math.max(l1.y, l2.y); 199 200 iGui.boundingBoxChanged(this); 201 repaint(); 202 } 203 204 /** 205 * Performs resizing of the DownloadDialog in order to enlarge or shrink the 206 * map. 207 */ 208 public void resizeSlippyMap() { 209 if (iScreenSize == null) { 210 Component c = 211 iGui.getParent().getParent().getParent().getParent().getParent().getParent() 212 .getParent().getParent().getParent(); 213 // remember the initial set screen dimensions 214 iDownloadDialogDimension = c.getSize(); 215 // retrive the size of the display 216 iScreenSize = Toolkit.getDefaultToolkit().getScreenSize(); 217 } 218 219 // resize 220 Component co = 221 iGui.getParent().getParent().getParent().getParent().getParent().getParent() 222 .getParent().getParent().getParent(); 223 Dimension currentDimension = co.getSize(); 224 225 // enlarge 226 if (currentDimension.equals(iDownloadDialogDimension)) { 227 // make the each dimension 90% of the absolute display size and 228 // center the DownloadDialog 229 int w = iScreenSize.width * 90 / 100; 230 int h = iScreenSize.height * 90 / 100; 231 co.setBounds((iScreenSize.width - w) / 2, (iScreenSize.height - h) / 2, w, h); 232 233 } 234 // shrink 235 else { 236 // set the size back to the initial dimensions and center the 237 // DownloadDialog 238 int w = iDownloadDialogDimension.width; 239 int h = iDownloadDialogDimension.height; 240 co.setBounds((iScreenSize.width - w) / 2, (iScreenSize.height - h) / 2, w, h); 241 242 } 243 244 repaint(); 245 } 246 247 public void toggleMapSource(int mapSource) { 248 this.tileCache = new MemoryTileCache(); 249 if (mapSource == SourceButton.MAPNIK) { 250 this.setTileSource(sources[0]); 251 } else { 252 this.setTileSource(sources[1]); 253 } 254 } 255 256 public void componentHidden(ComponentEvent e) { 257 } 258 259 public void componentMoved(ComponentEvent e) { 260 } 261 262 public void componentShown(ComponentEvent e) { 263 } 264 265 public void componentResized(ComponentEvent e) { 266 if (!this.equals(e.getSource()) || getHeight() == 0 || getWidth() == 0) 267 return; 268 firstShown = false; 269 // The bounding box has to be set after SlippyMapChooser's size has been 270 // finally set - otherwise the zoom level will be totally wrong (too wide) 271 boundingBoxChanged(iGui); 272 } 273 273 274 274 } -
applications/editors/josm/plugins/slippy_map_chooser/src/SlippyMapChooserPlugin.java
r9851 r12778 14 14 public class SlippyMapChooserPlugin extends Plugin implements PreferenceChangedListener { 15 15 16 16 static String iPluginFolder = ""; 17 17 18 19 18 private static final String KEY_MAX_TILES_IN_MEMORY = "slippy_map_chooser.max_tiles"; 19 private static final String KEY_ENABLE_FILE_CACHE = "slippy_map_chooser.file_cache"; 20 20 21 22 21 static int MAX_TILES_IN_MEMORY = 200; 22 static boolean ENABLE_FILE_CACHE = true; 23 23 24 25 26 27 28 29 30 // 31 32 24 public SlippyMapChooserPlugin() { 25 // create the plugin folder 26 // iPluginFolder = getPluginDir(); 27 // File pluginFolder = new File(iPluginFolder); 28 // if(!pluginFolder.exists()) 29 // pluginFolder.mkdir(); 30 // 31 // //init the logger 32 // Logger.setLogFile(iPluginFolder+"\\slippy_map_chooser.log"); 33 33 34 35 34 // Add this plugin to the preference changed listener list 35 Main.pref.listener.add(this); 36 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 37 // load prefs 38 String maxTiles = Main.pref.get(KEY_MAX_TILES_IN_MEMORY); 39 if (!maxTiles.equals("")) { 40 preferenceChanged(KEY_MAX_TILES_IN_MEMORY, maxTiles); 41 } else { 42 Main.pref.put(KEY_MAX_TILES_IN_MEMORY, Integer.toString(MAX_TILES_IN_MEMORY)); 43 } 44 String enableFileCache = Main.pref.get(KEY_ENABLE_FILE_CACHE); 45 if (!enableFileCache.equals("")) { 46 preferenceChanged(KEY_ENABLE_FILE_CACHE, enableFileCache); 47 } else { 48 Main.pref.put(KEY_ENABLE_FILE_CACHE, Boolean.toString(ENABLE_FILE_CACHE)); 49 } 50 } 51 51 52 53 54 52 public void addDownloadSelection(List<DownloadSelection> list) { 53 list.add(new SlippyMapChooser()); 54 } 55 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 56 public void preferenceChanged(String key, String newValue) { 57 if (KEY_MAX_TILES_IN_MEMORY.equals(key)) { 58 try { 59 MAX_TILES_IN_MEMORY = Integer.parseInt(newValue); 60 } catch (Exception e) { 61 MAX_TILES_IN_MEMORY = 1000; 62 } 63 } else if (KEY_ENABLE_FILE_CACHE.equals(key)) { 64 try { 65 ENABLE_FILE_CACHE = Boolean.parseBoolean(newValue); 66 } catch (Exception e) { 67 MAX_TILES_IN_MEMORY = 1000; 68 } 69 } 70 } 71 71 72 72 } -
applications/editors/josm/plugins/slippy_map_chooser/src/SourceButton.java
r9819 r12778 8 8 public class SourceButton { 9 9 10 11 10 private int x = 0; 11 private int y = 30; 12 12 13 14 15 16 13 private ImageIcon enlargeImage; 14 private ImageIcon shrinkImage; 15 private ImageIcon imageMapnik; 16 private ImageIcon imageOsmarender; 17 17 18 18 private boolean isEnlarged = false; 19 19 20 20 private boolean isMapnik = true; 21 21 22 23 24 22 public static final int HIDE_OR_SHOW = 1; 23 public static final int MAPNIK = 2; 24 public static final int OSMARENDER = 3; 25 25 26 27 28 29 30 31 26 public SourceButton() { 27 enlargeImage = ImageProvider.get("", "layer-switcher-maximize.png"); 28 shrinkImage = ImageProvider.get("", "layer-switcher-minimize.png"); 29 imageMapnik = ImageProvider.get("", "blue_Mapnik.png"); 30 imageOsmarender = ImageProvider.get("", "blue_Osmarender.png"); 31 } 32 32 33 33 public void paint(Graphics g) { 34 34 35 36 37 38 39 40 41 42 35 if (isEnlarged) { 36 if (isMapnik) { 37 g.drawImage(imageMapnik.getImage(), g.getClipBounds().width 38 - imageMapnik.getIconWidth(), y, null); 39 } else { 40 g.drawImage(imageOsmarender.getImage(), g.getClipBounds().width 41 - imageMapnik.getIconWidth(), y, null); 42 } 43 43 44 45 46 47 44 if (shrinkImage != null) { 45 this.x = g.getClipBounds().width - shrinkImage.getIconWidth(); 46 g.drawImage(shrinkImage.getImage(), x, y, null); 47 } 48 48 49 50 51 52 53 54 55 49 } else { 50 if (enlargeImage != null) { 51 this.x = g.getClipBounds().width - enlargeImage.getIconWidth(); 52 g.drawImage(enlargeImage.getImage(), x, y, null); 53 } 54 } 55 } 56 56 57 58 57 public void toggle() { 58 this.isEnlarged = !this.isEnlarged; 59 59 60 60 } 61 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 62 public int hit(Point point) { 63 if (isEnlarged) { 64 if (x < point.x && point.x < x + shrinkImage.getIconWidth()) { 65 if (y < point.y && point.y < y + shrinkImage.getIconHeight()) { 66 return HIDE_OR_SHOW; 67 } 68 } else if (x - imageMapnik.getIconWidth() < point.x && point.x < x) { 69 if (y < point.y && point.y < y + imageMapnik.getIconHeight() / 2) { 70 isMapnik = false; 71 return OSMARENDER; 72 } else if (y + imageMapnik.getIconHeight() / 2 < point.y 73 && point.y < y + imageMapnik.getIconHeight()) { 74 isMapnik = true; 75 return MAPNIK; 76 } 77 } 78 } else { 79 if (x < point.x && point.x < x + enlargeImage.getIconWidth()) { 80 if (y < point.y && point.y < y + enlargeImage.getIconHeight()) { 81 return HIDE_OR_SHOW; 82 } 83 } 84 } 85 85 86 87 86 return 0; 87 } 88 88 } -
applications/editors/josm/plugins/slippymap/src/org/openstreetmap/josm/plugins/slippymap/SlippyMapLayer.java
r10775 r12778 35 35 /** 36 36 * Class that displays a slippy map layer. 37 * 37 * 38 38 * @author Frederik Ramm <frederik@remote.org> 39 * 39 * 40 40 */ 41 41 public class SlippyMapLayer extends Layer implements ImageObserver, … … 57 57 { 58 58 super(tr("Slippy Map")); 59 59 background = true; 60 60 61 61 clearTileStorage(); … … 468 468 /* 469 469 * (non-Javadoc) 470 * 470 * 471 471 * @see org.openstreetmap.josm.data.Preferences.PreferenceChangedListener#preferenceChanged(java.lang.String, 472 472 * java.lang.String) -
applications/editors/josm/plugins/slippymap/src/org/openstreetmap/josm/plugins/slippymap/SlippyMapPlugin.java
r12104 r12778 8 8 /** 9 9 * Main class for the slippy map plugin. 10 * 10 * 11 11 * @author Frederik Ramm <frederik@remote.org> 12 * 12 * 13 13 */ 14 14 public class SlippyMapPlugin extends Plugin … … 21 21 public void mapFrameInitialized(MapFrame oldFrame, MapFrame newFrame) 22 22 { 23 24 25 26 27 23 if (newFrame != null){ 24 SlippyMapLayer smlayer; 25 smlayer = new SlippyMapLayer(); 26 Main.main.addLayer(smlayer); 27 } 28 28 } 29 29 30 30 /* 31 31 * (non-Javadoc) 32 * 32 * 33 33 * @see org.openstreetmap.josm.plugins.Plugin#getPreferenceSetting() 34 34 */ -
applications/editors/josm/plugins/slippymap/src/org/openstreetmap/josm/plugins/slippymap/SlippyMapPreferenceSetting.java
r12588 r12778 20 20 /** 21 21 * Preference Dialog for Slippy Map Tiles 22 * 22 * 23 23 * @author Hakan Tandogan <hakan@gurkensalat.com> 24 * 24 * 25 25 */ 26 26 public class SlippyMapPreferenceSetting implements PreferenceSetting -
applications/editors/josm/plugins/slippymap/src/org/openstreetmap/josm/plugins/slippymap/SlippyMapPreferences.java
r5691 r12778 5 5 /** 6 6 * Preferences for Slippy Map Tiles 7 * 7 * 8 8 * @author Hakan Tandogan <hakan@gurkensalat.com> 9 * 9 * 10 10 */ 11 11 public class SlippyMapPreferences … … 14 14 15 15 public static String PREFERENCE_TILE_URL = PREFERENCE_PREFIX + ".tile_url"; 16 16 17 17 public static String getMapUrl() 18 18 { -
applications/editors/josm/plugins/slippymap/src/org/openstreetmap/josm/plugins/slippymap/SlippyMapTile.java
r10120 r12778 13 13 /** 14 14 * Class that contains information about one single slippy map tile. 15 * 15 * 16 16 * @author Frederik Ramm <frederik@remote.org> 17 * 17 * 18 18 */ 19 19 public class SlippyMapTile -
applications/editors/josm/plugins/surveyor/src/at/dallermassl/josm/plugin/surveyor/ActionConstants.java
r4277 r12778 14 14 */ 15 15 public final class ActionConstants { 16 17 18 * 19 20 16 17 /** 18 * 19 */ 20 private ActionConstants() { } 21 21 22 22 public static final String SELECTED_KEY = "actionConstants.selected"; -
applications/editors/josm/plugins/surveyor/src/at/dallermassl/josm/plugin/surveyor/AutoSaveAction.java
r12486 r12778 48 48 autoSave = ((AbstractButton)e.getSource()).isSelected(); 49 49 } 50 50 51 51 if(autoSave) { 52 52 if(gpsDataTimer == null) { … … 54 54 } 55 55 TimerTask task; 56 56 57 57 String gpxFilename = MessageFormat.format(GPS_FILE_NAME_PATTERN, new Date()); 58 58 task = new AutoSaveGpsLayerTimerTask(gpxFilename, LiveGpsLayer.LAYER_NAME); 59 59 gpsDataTimer.schedule(task, 1000, AUTO_SAVE_PERIOD_SEC * 1000); 60 60 61 61 String osmFilename = MessageFormat.format(OSM_FILE_NAME_PATTERN, new Date()); 62 62 task = new AutoSaveEditLayerTimerTask(osmFilename); … … 67 67 } 68 68 } 69 70 69 70 71 71 } 72 72 } -
applications/editors/josm/plugins/surveyor/src/at/dallermassl/josm/plugin/surveyor/AutoSaveEditLayerTimerTask.java
r4522 r12778 28 28 public class AutoSaveEditLayerTimerTask extends TimerTask { 29 29 private File file; 30 30 31 31 public AutoSaveEditLayerTimerTask(String filename) { 32 32 file = new File(filename); … … 49 49 // outFile = file; 50 50 // } 51 51 52 52 // write to temporary file, on success, rename tmp file to target file: 53 53 File tmpFile = new File(file.getAbsoluteFile()+".tmp"); … … 60 60 } catch (IOException x) { 61 61 x.printStackTrace(); 62 JOptionPane.showMessageDialog(Main.parent, 63 tr("Error while exporting {0}: {1}", file.getAbsoluteFile(), x.getMessage()), 64 tr("Error"), 62 JOptionPane.showMessageDialog(Main.parent, 63 tr("Error while exporting {0}: {1}", file.getAbsoluteFile(), x.getMessage()), 64 tr("Error"), 65 65 JOptionPane.ERROR_MESSAGE); 66 } 66 } 67 67 } 68 68 -
applications/editors/josm/plugins/surveyor/src/at/dallermassl/josm/plugin/surveyor/AutoSaveGpsLayerTimerTask.java
r6164 r12778 29 29 * if the layer does not exist at the start of the timer task. If the layer does not exist, 30 30 * the file is not written. 31 * 31 * 32 32 * @author cdaller 33 33 * … … 36 36 private String gpsLayerName; 37 37 private File file; 38 38 39 39 /** 40 40 * Constructor using the file to write to and the name of the layer. … … 47 47 this.file = new File(filename); 48 48 } 49 49 50 50 /** 51 51 * @return the gpsLayerName … … 62 62 public void run() { 63 63 64 try { 64 try { 65 65 66 66 GpxLayer gpsLayer = LayerUtil.findGpsLayer(gpsLayerName, GpxLayer.class); … … 78 78 synchronized(LiveGpsLock.class) { 79 79 gpxWriter.write(gpsLayer.data); 80 } 80 } 81 81 tmpFile.renameTo(file); 82 82 } catch (IOException ioExc) { 83 83 ioExc.printStackTrace(); 84 JOptionPane.showMessageDialog(Main.parent, 85 tr("Error while exporting {0}: {1}", file.getAbsoluteFile(), ioExc.getMessage()), 86 tr("Error"), 84 JOptionPane.showMessageDialog(Main.parent, 85 tr("Error while exporting {0}: {1}", file.getAbsoluteFile(), ioExc.getMessage()), 86 tr("Error"), 87 87 JOptionPane.ERROR_MESSAGE); 88 } 88 } 89 89 } 90 90 } -
applications/editors/josm/plugins/surveyor/src/at/dallermassl/josm/plugin/surveyor/ButtonDescription.java
r4499 r12778 44 44 45 45 /** 46 * Default Constructor 46 * Default Constructor 47 47 */ 48 48 public ButtonDescription() { … … 52 52 * @param hotkey 53 53 * @param actions a list of actions to be performed. 54 * @param type if <code>null</code> {@link ButtonType#SINGLE} is used. 54 * @param type if <code>null</code> {@link ButtonType#SINGLE} is used. 55 55 */ 56 56 public ButtonDescription(String label, String hotkey, String iconName, String buttonAction, ButtonType type) { … … 61 61 * @param hotkey 62 62 * @param actions a list of actions to be performed. 63 * @param type if <code>null</code> {@link ButtonType#SINGLE} is used. 63 * @param type if <code>null</code> {@link ButtonType#SINGLE} is used. 64 64 */ 65 65 public ButtonDescription(String label, String hotkey, String iconName, SurveyorActionDescription actionDescription, ButtonType type) { … … 77 77 return list; 78 78 } 79 79 80 80 /** 81 81 * @param hotkey 82 82 * @param actions a list of actions to be performed. 83 * @param type if <code>null</code> {@link ButtonType#SINGLE} is used. 83 * @param type if <code>null</code> {@link ButtonType#SINGLE} is used. 84 84 */ 85 85 public ButtonDescription(String label, String hotkey, String iconName, List<SurveyorActionDescription> actions, ButtonType type) { … … 140 140 return this.type; 141 141 } 142 142 143 143 /** 144 144 * Set the button type as a string. … … 159 159 this.type = type; 160 160 } 161 161 162 162 /** 163 163 * Sets the name of the icon. … … 167 167 this.iconName = icon; 168 168 } 169 169 170 170 /** 171 171 * Creates the button. … … 173 173 */ 174 174 public JComponent createComponent() { 175 175 176 176 String actionName = tr(getLabel()) + " (" + hotkey + ")"; 177 177 178 178 Icon icon = ImageProvider.getIfAvailable("markers",iconName); 179 179 if (icon == null) … … 185 185 action.setActions(actions); 186 186 action.setGpsDataSource(gpsDataSource); 187 187 188 188 AbstractButton button; 189 189 if(type == ButtonType.TOGGLE) { … … 206 206 return button; 207 207 } 208 208 209 209 private static void connectActionAndButton(Action action, AbstractButton button) { 210 210 SelectionStateAdapter adapter = new SelectionStateAdapter(action, button); 211 211 adapter.configure(); 212 212 } 213 214 /** 215 * Class that connects the selection state of the action 213 214 /** 215 * Class that connects the selection state of the action 216 216 * to the selection state of the button. 217 * 217 * 218 218 * @author R.J. Lorimer 219 219 */ … … 223 223 public SelectionStateAdapter(Action theAction, AbstractButton theButton) { 224 224 action = theAction; 225 button = theButton; 225 button = theButton; 226 226 } 227 227 protected void configure() { … … 234 234 action.putValue(ActionConstants.SELECTED_KEY, valueObj); 235 235 } 236 236 237 237 public void propertyChange(PropertyChangeEvent evt) { 238 238 if(evt.getPropertyName().equals(ActionConstants.SELECTED_KEY)) { -
applications/editors/josm/plugins/surveyor/src/at/dallermassl/josm/plugin/surveyor/ButtonType.java
r4277 r12778 9 9 * 10 10 */ 11 public enum ButtonType { 12 SINGLE, 13 TOGGLE 11 public enum ButtonType { 12 SINGLE, 13 TOGGLE 14 14 } -
applications/editors/josm/plugins/surveyor/src/at/dallermassl/josm/plugin/surveyor/GpsActionEvent.java
r4277 r12778 16 16 private static final long serialVersionUID = 2674961758007055637L; 17 17 private LatLon coordinates; 18 18 19 19 20 20 /** … … 36 36 } 37 37 38 38 39 39 40 40 } -
applications/editors/josm/plugins/surveyor/src/at/dallermassl/josm/plugin/surveyor/MetaAction.java
r4277 r12778 18 18 /** 19 19 * Action that fires a {@link SurveyorAction} to the registered actions. 20 * 20 * 21 21 * @author cdaller 22 * 22 * 23 23 */ 24 24 public class MetaAction extends AbstractAction { … … 30 30 31 31 /** 32 * 32 * 33 33 */ 34 34 public MetaAction() { … … 70 70 /* 71 71 * (non-Javadoc) 72 * 72 * 73 73 * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent) 74 74 */ -
applications/editors/josm/plugins/surveyor/src/at/dallermassl/josm/plugin/surveyor/SurveyorAction.java
r4277 r12778 18 18 */ 19 19 public void actionPerformed(GpsActionEvent event); 20 20 21 21 /** 22 22 * Sets the parameters for the action execution. -
applications/editors/josm/plugins/surveyor/src/at/dallermassl/josm/plugin/surveyor/SurveyorActionDescription.java
r4277 r12778 19 19 private List<String> params; 20 20 private SurveyorAction action; 21 22 21 22 23 23 /** 24 * Default Constructor 24 * Default Constructor 25 25 */ 26 26 public SurveyorActionDescription() { … … 80 80 this.params = params; 81 81 } 82 82 83 83 public void actionPerformed(GpsActionEvent e) { 84 84 if(action == null) { … … 88 88 action.actionPerformed(e); 89 89 } 90 90 91 91 /** 92 92 * Sets the classname of the action to use. Callback method of xml parser. … … 96 96 setActionClass(claszName); 97 97 } 98 98 99 99 /** 100 100 * Set the params as a comma separated string. -
applications/editors/josm/plugins/surveyor/src/at/dallermassl/josm/plugin/surveyor/SurveyorActionFactory.java
r4277 r12778 12 12 * the action instances are used as singletons! 13 13 * A package name of "at.dallermassl.josm.plugin.surveyor.action" is assumed, if the class could 14 * not be found. 15 * 14 * not be found. 15 * 16 16 * @author cdaller 17 17 * -
applications/editors/josm/plugins/surveyor/src/at/dallermassl/josm/plugin/surveyor/SurveyorComponent.java
r12486 r12778 32 32 /** 33 33 * @author cdaller 34 * 34 * 35 35 */ 36 36 public class SurveyorComponent extends JComponent implements PropertyChangeListener, GpsDataSource { … … 57 57 add(buttonPanel, BorderLayout.CENTER); 58 58 } 59 59 60 60 /** 61 61 * Set the number of rows as a string (callback method from xml parser). … … 66 66 buttonPanel.setLayout(new GridLayout(rows, columns)); 67 67 } 68 68 69 69 /** 70 70 * Set the number of columns as a string (callback method from xml parser). … … 76 76 buttonPanel.setLayout(new GridLayout(rows, columns)); 77 77 } 78 78 79 79 /** 80 80 * Set the width as a string. … … 87 87 } 88 88 } 89 89 90 90 /** 91 91 * Set the width as a string. … … 115 115 } 116 116 } 117 118 117 118 119 119 120 120 public static void main(String[] args) { 121 122 121 122 123 123 // parse xml file and create component from it: 124 124 Reader in = new InputStreamReader(SurveyorComponent.class.getClassLoader().getResourceAsStream("surveyor.xml")); … … 151 151 } catch (SAXException e) { 152 152 e.printStackTrace(); 153 } 154 153 } 154 155 155 // SurveyorComponent surveyorComponent = new SurveyorComponent(); 156 156 // surveyorComponent.setGridSize(3,3); … … 163 163 // surveyorComponent.addButton(new ButtonDescription("Residential", "R", null, "ConsolePrinterAction", null)); 164 164 // surveyorComponent.addButton(new ButtonDescription("Parking", "P", "images/symbols/parking.png", "ConsolePrinterAction", null)); 165 165 166 166 JFrame frame = new JFrame(); 167 167 frame.add(surveyorComponent); … … 179 179 streetLabel.setText(tr("Way: ") + gpsData.getWayInfo()); 180 180 } 181 181 182 182 } 183 183 -
applications/editors/josm/plugins/surveyor/src/at/dallermassl/josm/plugin/surveyor/SurveyorPlugin.java
r12486 r12778 27 27 * Plugin that uses live gps data and a button panel to add nodes/waypoints etc at the current 28 28 * position. 29 * 29 * 30 30 * TODO: auto save marker layer and data layer? 31 31 * TODO: in action retrieve buttontype state to set on/off values … … 34 34 */ 35 35 public class SurveyorPlugin { 36 36 37 37 private static JFrame surveyorFrame; 38 38 public static final String PREF_KEY_STREET_NAME_FONT_SIZE = "surveyor.way.fontsize"; 39 39 40 40 /** 41 * 41 * 42 42 */ 43 43 public SurveyorPlugin() { 44 44 super(); 45 45 46 46 // try to determine if the livegps plugin was already loaded: 47 47 // PluginInformation pluginInfo = PluginInformation.getLoaded("livegps"); … … 57 57 Class.forName("livegps.LiveGpsPlugin"); 58 58 } catch(ClassNotFoundException cnfe) { 59 String message = 59 String message = 60 60 tr("SurveyorPlugin depends on LiveGpsPlugin!") + "\n" + 61 61 tr("LiveGpsPlugin not found, please install and activate.") + "\n" + 62 tr("SurveyorPlugin is disabled for the moment"); 62 tr("SurveyorPlugin is disabled for the moment"); 63 63 JOptionPane.showMessageDialog(Main.parent, message, tr("SurveyorPlugin"), JOptionPane.ERROR_MESSAGE); 64 64 return; 65 65 } 66 67 66 67 68 68 LiveGpsPlugin gpsPlugin = null; 69 69 Iterator<PluginProxy> proxyIter = Main.plugins.iterator(); … … 101 101 SurveyorPlugin.surveyorFrame = surveyorFrame; 102 102 } 103 103 104 104 } -
applications/editors/josm/plugins/surveyor/src/at/dallermassl/josm/plugin/surveyor/SurveyorShowAction.java
r12486 r12778 68 68 // comp.addButton(new ButtonDescription("Residential", "R", null, 69 69 // new SurveyorActionDescription("SetWaypointAction", new String[] {"residential", "images/reorder.png"}), null)); 70 // comp.addButton(new ButtonDescription("Parking", "P", "images/symbols/parking.png", 70 // comp.addButton(new ButtonDescription("Parking", "P", "images/symbols/parking.png", 71 71 // new SurveyorActionDescription("SetNodeAction", new String[] {"amenity", "parking", "createdby", "surveyor"}), null)); 72 72 73 73 // add component as gps event listener: 74 74 gpsPlugin.addPropertyChangeListener(comp); 75 75 76 76 // add some hotkeys to the component: 77 77 ActionMap actionMap = comp.getActionMap(); … … 103 103 }); 104 104 inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_HOME, 0), "autocenter"); 105 105 106 106 surveyorFrame.add(comp); 107 107 surveyorFrame.pack(); … … 111 111 // <FIXXME date="28.04.2007" author="cdaller"> 112 112 // TODO get old pos of frame from properties 113 // </FIXXME> 113 // </FIXXME> 114 114 SurveyorPlugin.setSurveyorFrame(surveyorFrame); 115 115 } … … 127 127 // <FIXXME date="04.05.2007" author="cdaller"> 128 128 // TODO copy xml file to .josm directory if it does not exist! 129 // </FIXXME> 129 // </FIXXME> 130 130 } 131 131 SurveyorComponent component= null; -
applications/editors/josm/plugins/surveyor/src/at/dallermassl/josm/plugin/surveyor/action/AbstractSurveyorAction.java
r4277 r12778 15 15 public abstract class AbstractSurveyorAction implements SurveyorAction { 16 16 private List<String> parameters; 17 17 18 18 /** 19 19 * Returns the parameters. … … 23 23 return parameters; 24 24 } 25 25 26 26 /* (non-Javadoc) 27 27 * @see at.dallermassl.josm.plugin.surveyor.SurveyorAction#setParameters(java.util.List) -
applications/editors/josm/plugins/surveyor/src/at/dallermassl/josm/plugin/surveyor/action/ConsolePrinterAction.java
r4277 r12778 20 20 public void actionPerformed(GpsActionEvent event) { 21 21 LatLon coordinates = event.getCoordinates(); 22 System.out.println(getClass().getSimpleName() + " KOORD: " + coordinates.lat() + ", " 22 System.out.println(getClass().getSimpleName() + " KOORD: " + coordinates.lat() + ", " 23 23 + coordinates.lon() + " params: " + getParameters()); 24 24 } -
applications/editors/josm/plugins/surveyor/src/at/dallermassl/josm/plugin/surveyor/action/PlayAudioAction.java
r4277 r12778 25 25 /** 26 26 * Action that plays an audio file. 27 * 27 * 28 28 * @author cdaller 29 29 * … … 86 86 } 87 87 } 88 88 89 89 }); 90 90 91 91 } 92 92 } -
applications/editors/josm/plugins/surveyor/src/at/dallermassl/josm/plugin/surveyor/action/SetNodeAction.java
r4277 r12778 29 29 public class SetNodeAction implements SurveyorAction { 30 30 private Collection<Tuple<String, String>> keyValues; 31 31 32 32 /** 33 33 * Default Constructor 34 34 */ 35 35 public SetNodeAction() { 36 36 37 37 } 38 38 39 39 /* (non-Javadoc) 40 40 * @see at.dallermassl.josm.plugin.surveyor.SurveyorAction#setParameters(java.util.List) … … 55 55 System.err.println("SetNodeAction: ignoring invalid key value pair: " + keyValuePair); 56 56 } 57 } 57 } 58 58 } 59 59 … … 73 73 Main.ds.setSelected(node); 74 74 } 75 Main.map.repaint(); 75 Main.map.repaint(); 76 76 } 77 77 78 78 79 79 } -
applications/editors/josm/plugins/surveyor/src/at/dallermassl/josm/plugin/surveyor/action/SetWaypointAction.java
r9400 r12778 31 31 * Action that sets a marker into a marker layer. The first parameter of the action 32 32 * is used as the text of the marker, the second (if it exists) as an icon. 33 * 33 * 34 34 * @author cdaller 35 35 * … … 40 40 public static final String MARKER_LAYER_NAME = "surveyorwaypointlayer"; 41 41 private WaypointDialog dialog; 42 42 43 43 /** 44 44 * Default Constructor. 45 45 */ 46 46 public SetWaypointAction() { 47 47 48 48 } 49 49 … … 61 61 markerTitle = markerTitle + " " + tr("start"); 62 62 } else { 63 markerTitle = markerTitle + " " + tr("end"); 63 markerTitle = markerTitle + " " + tr("end"); 64 64 } 65 65 } 66 66 67 67 if(dialog == null) { 68 68 dialog = new WaypointDialog(); 69 69 } 70 70 71 71 String markerText = markerTitle; 72 72 String inputText = dialog.openDialog(SurveyorPlugin.getSurveyorFrame(), "Waypoint Description"); … … 75 75 markerText = markerText + " " + inputText; 76 76 } 77 77 78 78 String iconName = getParameters().size() > 1 ? getParameters().get(1) : null; 79 80 // add the waypoint to the marker layer AND to the gpx layer 79 80 // add the waypoint to the marker layer AND to the gpx layer 81 81 // (easy export of data + waypoints): 82 82 MarkerLayer layer = getMarkerLayer(); … … 87 87 synchronized(LiveGpsLock.class) { 88 88 //layer.data.add(new Marker(event.getCoordinates(), markerText, iconName)); 89 89 layer.data.add(new Marker(event.getCoordinates(), markerText, iconName, null, -1.0, 0.0)); 90 90 if(gpsLayer != null) { 91 91 gpsLayer.data.waypoints.add(waypoint); 92 92 } 93 93 } 94 94 95 95 Main.map.repaint(); 96 96 } 97 97 98 98 /** 99 99 * Returns the marker layer with the name {@link #MARKER_LAYER_NAME}. … … 103 103 if(markerLayer == null) { 104 104 markerLayer = LayerUtil.findGpsLayer(MARKER_LAYER_NAME, MarkerLayer.class); 105 105 106 106 if(markerLayer == null) { 107 107 // not found, add a new one 108 108 //markerLayer = new MarkerLayer(new GpxData(), MARKER_LAYER_NAME, null); 109 109 markerLayer = new MarkerLayer(new GpxData(), MARKER_LAYER_NAME, null, null); 110 110 Main.main.addLayer(markerLayer); 111 111 } … … 113 113 return markerLayer; 114 114 } 115 115 116 116 /** 117 117 * Returns the gpx layer that is filled by the live gps data. … … 126 126 break; 127 127 } 128 } 128 } 129 129 } 130 130 return liveGpsLayer; -
applications/editors/josm/plugins/surveyor/src/at/dallermassl/josm/plugin/surveyor/action/TaggingPresetAction.java
r4277 r12778 23 23 private String presetName; 24 24 private TaggingPreset preset; 25 25 26 26 27 27 /* (non-Javadoc) … … 34 34 } 35 35 LatLon coordinates = event.getCoordinates(); 36 System.out.println(getClass().getSimpleName() + " KOORD: " + coordinates.lat() + ", " 36 System.out.println(getClass().getSimpleName() + " KOORD: " + coordinates.lat() + ", " 37 37 + coordinates.lon() + ", preset=" + presetName); 38 38 // Node node = new Node(coordinates); … … 43 43 // } 44 44 // Main.map.repaint(); 45 45 46 46 // call an annotationpreset to add additional properties... 47 47 preset.actionPerformed(null); … … 63 63 System.err.println("No valid preset '" + parameters.get(0) + "' found - disable action!"); 64 64 return; 65 } 65 } 66 66 } 67 67 -
applications/editors/josm/plugins/surveyor/src/at/dallermassl/josm/plugin/surveyor/action/gui/DialogClosingThread.java
r4277 r12778 24 24 private long timeout; 25 25 private long loopCount; 26 26 27 27 /** 28 28 * Using the given dialog and the default timeout. … … 31 31 public DialogClosingThread(JDialog dialog) { 32 32 this(dialog, DEFAULT_TIMEOUT); 33 } 34 33 } 34 35 35 /** 36 36 * @param dialog … … 61 61 dialog.dispose(); 62 62 } 63 63 64 64 public void reset() { 65 65 this.loopCount = timeout / 1000; … … 105 105 } 106 106 } 107 107 108 108 public void observe(Component component) { 109 109 component.addKeyListener(this); 110 110 } 111 111 112 112 public void observe(JTextField textfield) { 113 113 textfield.getDocument().addDocumentListener(this); … … 120 120 public void changedUpdate(DocumentEvent e) { 121 121 reset(); 122 System.out.println("changedUpdate: " + e); 122 System.out.println("changedUpdate: " + e); 123 123 } 124 124 … … 138 138 public void removeUpdate(DocumentEvent e) { 139 139 reset(); 140 System.out.println("removeUpdate: " + e); 140 System.out.println("removeUpdate: " + e); 141 141 } 142 142 } -
applications/editors/josm/plugins/surveyor/src/at/dallermassl/josm/plugin/surveyor/action/gui/WaypointDialog.java
r4277 r12778 21 21 */ 22 22 public class WaypointDialog { 23 23 24 24 public String openDialog(JFrame frame, String message) { 25 25 26 26 JTextField textField = new JTextField(10); 27 27 … … 66 66 dialog.pack(); 67 67 dialog.setVisible(true); 68 68 69 69 70 70 System.out.println("value: " + optionPane.getValue()); -
applications/editors/josm/plugins/surveyor/src/at/dallermassl/josm/plugin/surveyor/util/LayerUtil.java
r6164 r12778 1 1 /** 2 * 2 * 3 3 */ 4 4 package at.dallermassl.josm.plugin.surveyor.util; -
applications/editors/josm/plugins/surveyor/src/at/dallermassl/josm/plugin/surveyor/util/ResourceLoader.java
r4277 r12778 15 15 */ 16 16 public class ResourceLoader { 17 17 18 18 private ResourceLoader() { 19 19 20 20 } 21 21 22 22 /** 23 23 * Returns an inputstream from urls, files and classloaders, depending on the name. -
applications/editors/josm/plugins/surveyor/src/org/dinopolis/util/collection/Tuple.java
r4277 r12778 9 9 /** 10 10 * Simple implementation of a tuple (two objects). 11 * 11 * 12 12 * @author cdaller 13 13 * … … 16 16 T1 first; 17 17 T2 second; 18 18 19 19 /** 20 * Default Constructor 20 * Default Constructor 21 21 */ 22 22 public Tuple() { 23 23 } 24 24 25 25 /** 26 26 * Constructor filling the values. -
applications/editors/josm/plugins/tagging-preset-tester/src/org/openstreetmap/josm/plugins/taggingpresettester/TaggingPresetTester.java
r10409 r12778 30 30 public class TaggingPresetTester extends JFrame { 31 31 32 33 34 35 32 private JComboBox taggingPresets; 33 private final String[] args; 34 private JPanel taggingPresetPanel = new JPanel(new BorderLayout()); 35 private JPanel panel = new JPanel(new BorderLayout()); 36 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 37 public void reload() { 38 Vector<TaggingPreset> allPresets = new Vector<TaggingPreset>(); 39 for (String source : args) { 40 InputStream in = null; 41 try { 42 if (source.startsWith("http") || source.startsWith("ftp") || source.startsWith("file")) 43 in = new URL(source).openStream(); 44 else 45 in = new FileInputStream(source); 46 allPresets.addAll(TaggingPreset.readAll(new BufferedReader(new InputStreamReader(in)))); 47 } catch (IOException e) { 48 e.printStackTrace(); 49 JOptionPane.showMessageDialog(null, "Could not read tagging preset source: "+source); 50 } catch (SAXException e) { 51 e.printStackTrace(); 52 JOptionPane.showMessageDialog(null, "Error parsing "+source+": "+e.getMessage()); 53 } 54 54 55 56 57 58 59 60 61 62 55 try { 56 if (in != null) 57 in.close(); 58 } catch (IOException e) { 59 } 60 } 61 taggingPresets.setModel(new DefaultComboBoxModel(allPresets)); 62 } 63 63 64 65 66 67 68 69 70 71 72 73 74 75 76 64 public void reselect() { 65 taggingPresetPanel.removeAll(); 66 TaggingPreset preset = (TaggingPreset)taggingPresets.getSelectedItem(); 67 if (preset == null) 68 return; 69 Collection<OsmPrimitive> x = Collections.emptySet(); 70 JPanel p = preset.createPanel(x); 71 p.setBorder(BorderFactory.createEmptyBorder(5,5,5,5)); 72 if (p != null) 73 taggingPresetPanel.add(p, BorderLayout.NORTH); 74 panel.validate(); 75 panel.repaint(); 76 } 77 77 78 79 80 81 82 83 78 public TaggingPresetTester(String[] args) { 79 super("Tagging Preset Tester"); 80 this.args = args; 81 taggingPresets = new JComboBox(); 82 taggingPresets.setRenderer(new TaggingCellRenderer()); 83 reload(); 84 84 85 86 87 88 89 90 91 92 85 panel.add(taggingPresets, BorderLayout.NORTH); 86 panel.add(taggingPresetPanel, BorderLayout.CENTER); 87 taggingPresets.addActionListener(new ActionListener(){ 88 public void actionPerformed(ActionEvent e) { 89 reselect(); 90 } 91 }); 92 reselect(); 93 93 94 95 96 97 98 99 100 101 102 94 JButton b = new JButton("Reload"); 95 b.addActionListener(new ActionListener(){ 96 public void actionPerformed(ActionEvent e) { 97 int i = taggingPresets.getSelectedIndex(); 98 reload(); 99 taggingPresets.setSelectedIndex(i); 100 } 101 }); 102 panel.add(b, BorderLayout.SOUTH); 103 103 104 105 106 107 104 setContentPane(panel); 105 setSize(300,500); 106 setVisible(true); 107 } 108 108 109 110 111 112 113 114 115 116 117 118 109 public static void main(String[] args) { 110 if (args.length == 0) { 111 JFileChooser c = new JFileChooser(); 112 if (c.showOpenDialog(null) != JFileChooser.APPROVE_OPTION) 113 return; 114 args = new String[]{c.getSelectedFile().getPath()}; 115 } 116 JFrame f = new TaggingPresetTester(args); 117 f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 118 } 119 119 } -
applications/editors/josm/plugins/tagging-preset-tester/src/org/openstreetmap/josm/plugins/taggingpresettester/TaggingPresetTesterAction.java
r12588 r12778 19 19 public class TaggingPresetTesterAction extends JosmAction { 20 20 21 22 23 24 25 26 27 28 29 21 public TaggingPresetTesterAction() { 22 super(tr("Tagging Preset Tester"), "tagging-preset-tester", 23 tr("Open the tagging preset test tool for previewing tagging preset dialogs."), 24 Shortcut.registerShortcut("tools:taggingresettester", 25 tr("Tool: {0}", tr("Tagging Preset Tester")), 26 KeyEvent.VK_A, Shortcut.GROUP_EDIT, Shortcut.SHIFT_DEFAULT), true); 27 Main.main.menu.helpMenu.addSeparator(); 28 MainMenu.add(Main.main.menu.helpMenu, this); 29 } 30 30 31 32 33 34 35 36 37 38 39 31 public void actionPerformed(ActionEvent e) { 32 String taggingPresetSources = Main.pref.get("taggingpreset.sources"); 33 if (taggingPresetSources.equals("")) { 34 JOptionPane.showMessageDialog(Main.parent, tr("You have to specify tagging preset sources in the preferences first.")); 35 return; 36 } 37 String[] args = taggingPresetSources.split(";"); 38 new TaggingPresetTester(args); 39 } 40 40 } -
applications/editors/josm/plugins/tcxplugin/src/org/openstreetmap/josm/io/TcxReader.java
r10833 r12778 47 47 public class TcxReader { 48 48 49 49 private File tcxFile; 50 50 51 51 private GpxData gpxData; 52 52 53 54 55 56 57 58 59 60 53 /** 54 * @param tcxFile 55 */ 56 public TcxReader(File tcxFile) { 57 super(); 58 this.tcxFile = tcxFile; 59 parseFile(); 60 } 61 61 62 63 64 65 66 67 68 69 70 71 62 /** 63 * 64 */ 65 @SuppressWarnings("unchecked") private void parseFile() { 66 try { 67 JAXBContext jc = JAXBContext 68 .newInstance(TrainingCenterDatabaseT.class); 69 Unmarshaller unmarshaller = jc.createUnmarshaller(); 70 JAXBElement<TrainingCenterDatabaseT> element = (JAXBElement<TrainingCenterDatabaseT>)unmarshaller 71 .unmarshal(tcxFile); 72 72 73 73 TrainingCenterDatabaseT tcd = element.getValue(); 74 74 75 75 gpxData = new GpxData(); 76 76 77 78 79 80 81 77 // Usually logged activities are in the activities tag. 78 parseDataFromActivities(tcd); 79 // GPS tracks in the course tag are generated by the user. 80 // Maybe not a good idea to import them. 81 parseDataFromCourses(tcd); 82 82 83 84 85 86 83 } catch (JAXBException e) { 84 throw new RuntimeException(e); 85 } 86 } 87 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 88 /** 89 * @param tcd 90 */ 91 private void parseDataFromActivities(TrainingCenterDatabaseT tcd) { 92 if ((tcd.getActivities() != null) 93 && (tcd.getActivities().getActivity() != null)) { 94 for (ActivityT activity : tcd.getActivities().getActivity()) { 95 if (activity.getLap() != null) { 96 for (ActivityLapT activityLap : activity.getLap()) { 97 if (activityLap.getTrack() != null) { 98 GpxTrack currentTrack = new GpxTrack(); 99 gpxData.tracks.add(currentTrack); 100 for (TrackT track : activityLap.getTrack()) { 101 if (track.getTrackpoint() != null) { 102 Collection<WayPoint> currentTrackSeg = new ArrayList<WayPoint>(); 103 currentTrack.trackSegs.add(currentTrackSeg); 104 for (TrackpointT trackpoint : track 105 .getTrackpoint()) { 106 // Some trackspoints don't have a 107 // position. 108 // Check it 109 // first to avoid an NPE! 110 if (trackpoint.getPosition() != null) { 111 LatLon latLon = new LatLon( 112 trackpoint 113 .getPosition() 114 .getLatitudeDegrees(), 115 trackpoint 116 .getPosition() 117 .getLongitudeDegrees()); 118 WayPoint currentWayPoint = new WayPoint( 119 latLon); 120 // We usually have altitude info 121 // here 122 // (trackpoint.getAltitudeMeters()) 123 // Don't know how to add it to 124 // the GPX 125 // Data... 126 currentTrackSeg 127 .add(currentWayPoint); 128 } 129 } 130 } 131 } 132 } 133 } 134 } 135 } 136 } 137 } 138 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 139 /** 140 * @param tcd 141 */ 142 private void parseDataFromCourses(TrainingCenterDatabaseT tcd) { 143 if ((tcd.getCourses() != null) 144 && (tcd.getCourses().getCourse() != null)) { 145 for (CourseT course : tcd.getCourses().getCourse()) { 146 if (course.getTrack() != null) { 147 GpxTrack currentTrack = new GpxTrack(); 148 gpxData.tracks.add(currentTrack); 149 for (TrackT track : course.getTrack()) { 150 if (track.getTrackpoint() != null) { 151 Collection<WayPoint> currentTrackSeg = new ArrayList<WayPoint>(); 152 currentTrack.trackSegs.add(currentTrackSeg); 153 for (TrackpointT trackpoint : track.getTrackpoint()) { 154 // Some trackspoints don't have a position. 155 // Check it 156 // first to avoid an NPE! 157 if (trackpoint.getPosition() != null) { 158 LatLon latLon = new LatLon( 159 trackpoint.getPosition() 160 .getLatitudeDegrees(), 161 trackpoint.getPosition() 162 .getLongitudeDegrees()); 163 WayPoint currentWayPoint = new WayPoint( 164 latLon); 165 // We usually have altitude info here 166 // (trackpoint.getAltitudeMeters()) 167 // Don't know how to add it to the GPX 168 // Data... 169 currentTrackSeg.add(currentWayPoint); 170 } 171 } 172 } 173 } 174 } 175 } 176 } 177 } 178 178 179 180 181 179 public GpxData getGpxData() { 180 return gpxData; 181 } 182 182 } -
applications/editors/josm/plugins/utilsplugin/src/UtilsPlugin/SimplifyWayAction.java
r12707 r12778 49 49 if (bounds.size() > 0) { 50 50 Way way = (Way) prim; 51 // We check if each node of each way is at least in one download 51 // We check if each node of each way is at least in one download 52 52 // bounding box. Otherwise nodes may get deleted that are necessary by 53 53 // unloaded ways (see Ticket #1594) … … 83 83 return; 84 84 } else if (ways > 10) { 85 85 //TRANSLATION: Although for English the use of trn is needless it is important for other languages 86 86 int option = JOptionPane.showConfirmDialog(Main.parent, trn( 87 87 "The selection contains {0} way. Are you sure you want to simplify it?", -
applications/editors/josm/plugins/utilsplugin/src/UtilsPlugin/UtilsPlugin.java
r12579 r12778 22 22 23 23 public class UtilsPlugin extends Plugin { 24 24 JMenuItem SimplifyWay; 25 25 26 27 28 29 30 31 32 33 34 35 36 26 public UtilsPlugin() { 27 SimplifyWay = MainMenu.add(Main.main.menu.toolsMenu, new SimplifyWayAction()); 28 SimplifyWay.setEnabled(false); 29 } 30 31 @Override 32 public void mapFrameInitialized(MapFrame oldFrame, MapFrame newFrame) { 33 if (oldFrame == null && newFrame != null) { 34 SimplifyWay.setEnabled(true); 35 } 36 } 37 37 } -
applications/editors/josm/plugins/validator/src/org/openstreetmap/josm/plugins/validator/ErrorTreeRenderer.java
r9598 r12778 16 16 public class ErrorTreeRenderer extends DefaultTreeCellRenderer 17 17 { 18 19 18 /** Serializable ID */ 19 private static final long serialVersionUID = 5567632718124640198L; 20 20 21 @Override 22 public Component getTreeCellRendererComponent(JTree tree, Object value, 23 boolean selected, boolean expanded, boolean leaf, int row, 24 boolean hasFocus) 25 { 26 super.getTreeCellRendererComponent(tree, value, selected, expanded, leaf, row, hasFocus); 27 28 DefaultMutableTreeNode node = (DefaultMutableTreeNode)value; 29 Object nodeInfo = node.getUserObject(); 21 @Override 22 public Component getTreeCellRendererComponent(JTree tree, Object value, 23 boolean selected, boolean expanded, boolean leaf, int row, 24 boolean hasFocus) 25 { 26 super.getTreeCellRendererComponent(tree, value, selected, expanded, leaf, row, hasFocus); 30 27 31 if (nodeInfo instanceof Severity) 32 { 33 Severity s = (Severity)nodeInfo; 34 setIcon(ImageProvider.get("data", s.getIcon())); 35 } 36 else if (nodeInfo instanceof TestError) 37 { 38 TestError error = (TestError)nodeInfo; 39 MultipleNameVisitor v = new MultipleNameVisitor(); 40 v.visit(error.getPrimitives()); 41 setText(v.getText()); 42 setIcon(v.getIcon()); 43 } 28 DefaultMutableTreeNode node = (DefaultMutableTreeNode)value; 29 Object nodeInfo = node.getUserObject(); 44 30 45 return this; 46 } 31 if (nodeInfo instanceof Severity) 32 { 33 Severity s = (Severity)nodeInfo; 34 setIcon(ImageProvider.get("data", s.getIcon())); 35 } 36 else if (nodeInfo instanceof TestError) 37 { 38 TestError error = (TestError)nodeInfo; 39 MultipleNameVisitor v = new MultipleNameVisitor(); 40 v.visit(error.getPrimitives()); 41 setText(v.getText()); 42 setIcon(v.getIcon()); 43 } 44 45 return this; 46 } 47 47 } -
applications/editors/josm/plugins/validator/src/org/openstreetmap/josm/plugins/validator/GridLayer.java
r4844 r12778 28 28 public class GridLayer extends Layer 29 29 { 30 31 32 33 34 30 /** 31 * Constructor 32 * @param name 33 */ 34 public GridLayer(String name) 35 35 { 36 37 36 super(name); 37 } 38 38 39 40 41 42 43 44 39 /** 40 * Return a static icon. 41 */ 42 @Override public Icon getIcon() { 43 return ImageProvider.get("layer", "validator"); 44 } 45 45 46 46 /** … … 50 50 public void paint(final Graphics g, final MapView mv) 51 51 { 52 53 54 55 56 57 52 if( !Main.pref.hasKey(PreferenceEditor.PREF_DEBUG + ".grid") ) 53 return; 54 55 int gridWidth = Integer.parseInt(Main.pref.get(PreferenceEditor.PREF_DEBUG + ".grid") ); 56 int width = mv.getWidth(); 57 int height = mv.getHeight(); 58 58 59 60 59 EastNorth origin = mv.getEastNorth(0, 0); 60 EastNorth border = mv.getEastNorth(width, height); 61 61 62 63 62 if( border.east() * gridWidth > 50 ) 63 return; 64 64 65 65 g.setColor(Color.RED.darker().darker()); 66 67 68 66 HighlightCellVisitor visitor = new HighlightCellVisitor(g, mv, gridWidth); 67 for(OsmPrimitive p : Main.ds.getSelected() ) 68 p.visit(visitor); 69 69 70 70 long x0 = (long)Math.floor(origin.east() * gridWidth); 71 71 long x1 = (long)Math.floor(border.east() * gridWidth); 72 72 long y0 = (long)Math.floor(origin.north() * gridWidth) + 1; 73 73 long y1 = (long)Math.floor(border.north() * gridWidth) + 1; … … 77 77 78 78 g.setColor(Color.RED.brighter().brighter()); 79 80 81 82 83 79 for( double x = x0; x <= x1; x++) 80 { 81 Point point = mv.getPoint( new EastNorth(x/gridWidth, 0)); 82 g.drawLine(point.x, 0, point.x, height); 83 } 84 84 85 86 87 88 89 85 for( double y = y0; y <= y1; y++) 86 { 87 Point point = mv.getPoint( new EastNorth(0, y/gridWidth)); 88 g.drawLine(0, point.y, width, point.y); 89 } 90 90 } 91 91 92 92 @Override 93 93 public String getToolTipText() 94 94 { 95 96 95 return null; 96 } 97 97 98 99 98 @Override 99 public void mergeFrom(Layer from) {} 100 100 101 102 103 104 101 @Override 102 public boolean isMergable(Layer other) { 103 return false; 104 } 105 105 106 107 106 @Override 107 public void visitBoundingBox(BoundingXYVisitor v) {} 108 108 109 110 109 @Override 110 public Object getInfoComponent() 111 111 { 112 113 112 return getToolTipText(); 113 } 114 114 115 116 115 @Override 116 public Component[] getMenuEntries() 117 117 { 118 118 return new Component[]{ … … 125 125 } 126 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 127 @Override public void destroy() { } 128 129 /** 130 * Visitor that highlights all cells the selected primitives go through 131 */ 132 class HighlightCellVisitor implements Visitor 133 { 134 /** The MapView */ 135 private final MapView mv; 136 /** The graphics */ 137 private final Graphics g; 138 /** The grid width */ 139 private final int gridDetail; 140 /** The width of a cell */ 141 private int cellWidth; 142 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 143 /** 144 * Constructor 145 * @param g the graphics 146 * @param mv The MapView 147 * @param gridDetail The grid detail 148 */ 149 public HighlightCellVisitor(final Graphics g, final MapView mv, int gridDetail) 150 { 151 this.g = g; 152 this.mv = mv; 153 this.gridDetail = gridDetail; 154 155 Point p = mv.getPoint( new EastNorth(0, 0) ); 156 Point p2 = mv.getPoint( new EastNorth(1d/gridDetail, 1d/gridDetail) ); 157 cellWidth = Math.abs(p2.x - p.x); 158 } 159 159 160 161 162 163 160 public void visit(Node n) 161 { 162 double x = n.eastNorth.east() * gridDetail; 163 double y = n.eastNorth.north()* gridDetail + 1; 164 164 165 166 165 drawCell( Math.floor(x), Math.floor(y) ); 166 } 167 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 168 public void visit(Way w) 169 { 170 Node lastN = null; 171 for (Node n : w.nodes) { 172 if (lastN == null) { 173 lastN = n; 174 continue; 175 } 176 for (Point2D p : Util.getSegmentCells(lastN, n, gridDetail)) { 177 drawCell( p.getX(), p.getY() ); 178 } 179 lastN = n; 180 } 181 } 182 182 183 184 185 186 187 188 189 190 191 192 193 194 195 183 public void visit(Relation r) {} 184 185 /** 186 * Draws a solid cell at the (x,y) location 187 * @param x 188 * @param y 189 */ 190 protected void drawCell(double x, double y) 191 { 192 Point p = mv.getPoint( new EastNorth(x/gridDetail, y/gridDetail) ); 193 g.fillRect(p.x, p.y, cellWidth, cellWidth); 194 } 195 } 196 196 } -
applications/editors/josm/plugins/validator/src/org/openstreetmap/josm/plugins/validator/PreferenceEditor.java
r12777 r12778 26 26 public class PreferenceEditor implements PreferenceSetting 27 27 { 28 28 private OSMValidatorPlugin plugin; 29 29 30 31 30 /** The preferences prefix */ 31 public static final String PREFIX = "validator"; 32 32 33 34 33 /** The preferences key for debug preferences */ 34 public static final String PREF_DEBUG = PREFIX + ".debug"; 35 35 36 37 36 /** The preferences key for debug preferences */ 37 public static final String PREF_LAYER = PREFIX + ".layer"; 38 38 39 40 39 /** The preferences key for enabled tests */ 40 public static final String PREF_TESTS = PREFIX + ".tests"; 41 41 42 43 42 /** The preferences key for enabled tests */ 43 public static final String PREF_USE_IGNORE = PREFIX + ".ignore"; 44 44 45 46 45 /** The preferences key for enabled tests before upload*/ 46 public static final String PREF_TESTS_BEFORE_UPLOAD = PREFIX + ".testsBeforeUpload"; 47 47 48 49 50 51 48 /** 49 * The preferences key for enabling the permanent filtering 50 * of the displayed errors in the tree regarding the current selection 51 */ 52 52 public static final String PREF_FILTER_BY_SELECTION = PREFIX + ".selectionFilter"; 53 53 54 55 54 private JCheckBox prefUseIgnore; 55 private JCheckBox prefUseLayer; 56 56 57 58 57 /** The list of all tests */ 58 private Collection<Test> allTests; 59 59 60 61 62 60 public PreferenceEditor(OSMValidatorPlugin plugin) { 61 this.plugin = plugin; 62 } 63 63 64 65 66 67 64 public void addGui(PreferenceDialog gui) 65 { 66 JPanel testPanel = new JPanel(new GridBagLayout()); 67 testPanel.setBorder(BorderFactory.createEmptyBorder(5,5,5,5)); 68 68 69 70 71 69 prefUseIgnore = new JCheckBox(tr("Use ignore list."), Main.pref.getBoolean(PREF_USE_IGNORE, true)); 70 prefUseIgnore.setToolTipText(tr("Use the ignore list to suppress warnings.")); 71 testPanel.add(prefUseIgnore, GBC.eol()); 72 72 73 74 75 73 prefUseLayer = new JCheckBox(tr("Use error layer."), Main.pref.getBoolean(PREF_LAYER, true)); 74 prefUseLayer.setToolTipText(tr("Use the error layer to display problematic elements.")); 75 testPanel.add(prefUseLayer, GBC.eol()); 76 76 77 78 79 80 77 GBC a = GBC.eol().insets(-5,0,0,0); 78 a.anchor = GBC.EAST; 79 testPanel.add( new JLabel(tr("On demand")), GBC.std() ); 80 testPanel.add( new JLabel(tr("On upload")), a ); 81 81 82 83 84 85 86 82 allTests = OSMValidatorPlugin.getTests(); 83 for(Test test: allTests) 84 { 85 test.addGui(testPanel); 86 } 87 87 88 89 88 JScrollPane testPane = new JScrollPane(testPanel, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); 89 testPane.setBorder(null); 90 90 91 92 93 94 95 96 97 98 91 Version ver = Util.getVersion(); 92 String description = tr("A OSM data validator that checks for common errors made by users and editor programs."); 93 if( ver != null ) 94 description += "<br>" + tr("Version {0} - Last change at {1}", ver.revision, ver.time); 95 JPanel tab = gui.createPreferenceTab("validator", tr("Data validator"), description); 96 tab.add(testPane, GBC.eol().fill(GBC.BOTH)); 97 tab.add(GBC.glue(0,10), a); 98 } 99 99 100 101 102 103 104 100 public boolean ok() 101 { 102 StringBuilder tests = new StringBuilder(); 103 StringBuilder testsBeforeUpload = new StringBuilder(); 104 Boolean res = false; 105 105 106 107 108 109 110 111 112 113 106 for (Test test : allTests) 107 { 108 if(test.ok()) 109 res = false; 110 String name = test.getClass().getSimpleName(); 111 tests.append( ',' ).append( name ).append( '=' ).append( test.enabled ); 112 testsBeforeUpload.append( ',' ).append( name ).append( '=' ).append( test.testBeforeUpload ); 113 } 114 114 115 116 115 if (tests.length() > 0 ) tests = tests.deleteCharAt(0); 116 if (testsBeforeUpload.length() > 0 ) testsBeforeUpload = testsBeforeUpload.deleteCharAt(0); 117 117 118 118 plugin.initializeTests( allTests ); 119 119 120 121 122 123 124 125 120 Main.pref.put( PREF_TESTS, tests.toString()); 121 Main.pref.put( PREF_TESTS_BEFORE_UPLOAD, testsBeforeUpload.toString()); 122 Main.pref.put( PREF_USE_IGNORE, prefUseIgnore.isSelected()); 123 Main.pref.put( PREF_LAYER, prefUseLayer.isSelected()); 124 return false; 125 } 126 126 } -
applications/editors/josm/plugins/validator/src/org/openstreetmap/josm/plugins/validator/Severity.java
r9913 r12778 10 10 /** The error severity */ 11 11 public enum Severity { 12 13 14 /** Warning messages */ 15 WARNING(tr("Warnings"), "warning.gif", Main.pref.getColor(marktr("validation warning"), Color.YELLOW)), 16 /** Other messages */ 17 OTHER(tr("Other"), "other.gif", Main.pref.getColor(marktr("validation other"), Color.CYAN)); 18 19 20 21 12 /** Error messages */ 13 ERROR(tr("Errors"), "error.gif", Main.pref.getColor(marktr("validation error"), Color.RED)), 14 /** Warning messages */ 15 WARNING(tr("Warnings"), "warning.gif", Main.pref.getColor(marktr("validation warning"), Color.YELLOW)), 16 /** Other messages */ 17 OTHER(tr("Other"), "other.gif", Main.pref.getColor(marktr("validation other"), Color.CYAN)); 18 19 /** Description of the severity code */ 20 private final String message; 21 22 22 /** Associated icon */ 23 23 private final String icon; … … 26 26 private final Color color; 27 27 28 29 30 * 31 32 33 34 35 Severity(String message, String icon, Color color) 28 /** 29 * Constructor 30 * 31 * @param message Description 32 * @param icon Associated icon 33 * @param color The color of this severity 34 */ 35 Severity(String message, String icon, Color color) 36 36 { 37 37 this.message = message; 38 38 this.icon = icon; 39 39 this.color = color; 40 40 } 41 41 42 43 public String toString() 44 45 46 42 @Override 43 public String toString() 44 { 45 return message; 46 } 47 47 48 /** 49 50 51 52 public String getIcon() 53 54 55 48 /** 49 * Gets the associated icon 50 * @return the associated icon 51 */ 52 public String getIcon() 53 { 54 return icon; 55 } 56 56 57 57 /** … … 63 63 return color; 64 64 } 65 66 65 66 67 67 } -
applications/editors/josm/plugins/validator/src/org/openstreetmap/josm/plugins/validator/Test.java
r12777 r12778 27 27 public class Test implements Visitor 28 28 { 29 30 31 32 33 34 29 /** Name of the test */ 30 protected String name; 31 32 /** Description of the test */ 33 protected String description; 34 35 35 /** Whether this test is enabled. Enabled by default */ 36 36 protected boolean enabled = true; … … 48 48 protected boolean isBeforeUpload; 49 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 50 /** The list of errors */ 51 protected List<TestError> errors = new ArrayList<TestError>(30); 52 53 /** Whether the test is run on a partial selection data */ 54 protected boolean partialSelection; 55 56 /** 57 * Constructor 58 * @param name Name of the test 59 * @param description Description of the test 60 */ 61 public Test(String name, String description) 62 { 63 this.name = name; 64 this.description = description; 65 } 66 67 /** 68 * Constructor 69 * @param name Name of the test 70 */ 71 public Test(String name) 72 { 73 this.name = name; 74 } 75 76 /** 77 * Initializes any global data used this tester. 78 * @param plugin The plugin 79 * @throws Exception When cannot initialize the test 80 */ 81 public static void initialize(OSMValidatorPlugin plugin) throws Exception {} 82 83 /** 84 * Notification of the start of the test. The tester can initialize the 85 * structures it may need for this test 86 */ 87 public void startTest() 88 { 89 errors = new ArrayList<TestError>(30); 90 } 91 92 /** 93 * Flag notifying that this test is run over a partial data selection 94 * @param partialSelection Whether the test is on a partial selection data 95 */ 96 public void setPartialSelection(boolean partialSelection) 97 { 98 this.partialSelection = partialSelection; 99 } 100 101 /** 102 * Gets the validation errors accumulated until this moment. 103 * @return The list of errors 104 */ 105 public List<TestError> getErrors() 106 { 107 return errors; 108 } 109 110 /** 111 * Notification of the end of the test. The tester may perform additional 112 * actions and destroy the used structures 113 */ 114 public void endTest() {} 115 115 116 116 /** … … 124 124 for (OsmPrimitive p : selection) 125 125 { 126 127 126 if( !p.deleted && !p.incomplete ) 127 p.visit(this); 128 128 } 129 129 } … … 131 131 public void visit(Node n) {} 132 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 133 public void visit(Way w) {} 134 135 public void visit(Relation r) {} 136 137 /** 138 * Allow the tester to manage its own preferences 139 * @param testPanel The panel to add any preferences component 140 */ 141 public void addGui(JPanel testPanel) 142 { 143 checkEnabled = new JCheckBox(name, enabled); 144 checkEnabled.setToolTipText(description); 145 testPanel.add(checkEnabled, GBC.std()); 146 147 GBC a = GBC.eol(); 148 a.anchor = GBC.EAST; 149 checkBeforeUpload = new JCheckBox(); 150 checkBeforeUpload.setSelected(testBeforeUpload); 151 testPanel.add(checkBeforeUpload, a); 152 } 153 154 /** 155 * Called when the used submits the preferences 156 */ 157 public boolean ok() 158 { 159 enabled = checkEnabled.isSelected(); 160 testBeforeUpload = checkBeforeUpload.isSelected(); 161 return false; 162 } 163 164 /** 165 * Fixes the error with the appropiate command 166 * 167 * @param testError 168 * @return The command to fix the error 169 */ 170 public Command fixError(TestError testError) 171 { 172 return null; 173 } 174 175 /** 176 * Returns true if the given error can be fixed automatically 177 * 178 * @param testError The error to check if can be fixed 179 * @return true if the error can be fixed 180 */ 181 public boolean isFixable(TestError testError) 182 { 183 return false; 184 } 185 185 186 186 /** -
applications/editors/josm/plugins/validator/src/org/openstreetmap/josm/plugins/validator/TestError.java
r10540 r12778 372 372 * Checks if the given segment is in the visible area. 373 373 * NOTE: This will return true for a small number of non-visible 374 * 374 * segments. 375 375 * @param ls The segment to check 376 376 * @return true if the segment is visible -
applications/editors/josm/plugins/validator/src/org/openstreetmap/josm/plugins/validator/ValidateUploadHook.java
r11530 r12778 29 29 public class ValidateUploadHook implements UploadHook 30 30 { 31 32 31 /** Serializable ID */ 32 private static final long serialVersionUID = -2304521273582574603L; 33 33 34 34 private OSMValidatorPlugin plugin; 35 35 36 37 38 39 36 public ValidateUploadHook(OSMValidatorPlugin plugin) 37 { 38 this.plugin = plugin; 39 } 40 40 41 42 43 44 45 46 47 48 41 /** 42 * Validate the modified data before uploading 43 */ 44 public boolean checkUpload(Collection<OsmPrimitive> add, Collection<OsmPrimitive> update, Collection<OsmPrimitive> delete) 45 { 46 Collection<Test> tests = OSMValidatorPlugin.getEnabledTests(true); 47 if( tests.isEmpty() ) 48 return true; 49 49 50 51 52 50 AgregatePrimitivesVisitor v = new AgregatePrimitivesVisitor(); 51 v.visit(add); 52 Collection<OsmPrimitive> selection = v.visit(update); 53 53 54 55 56 57 58 59 60 61 62 63 64 65 66 54 List<TestError> errors = new ArrayList<TestError>(30); 55 for(Test test : tests) 56 { 57 test.setBeforeUpload(true); 58 test.setPartialSelection(true); 59 test.startTest(); 60 test.visit(selection); 61 test.endTest(); 62 errors.addAll( test.getErrors() ); 63 } 64 tests = null; 65 if(errors == null || errors.isEmpty()) 66 return 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 68 if(Main.pref.getBoolean(PreferenceEditor.PREF_USE_IGNORE, true)) 69 { 70 int nume = 0; 71 for(TestError error : errors) 72 { 73 List<String> s = new ArrayList<String>(); 74 s.add(error.getIgnoreState()); 75 s.add(error.getIgnoreGroup()); 76 s.add(error.getIgnoreSubGroup()); 77 for(String state : s) 78 { 79 if(state != null && plugin.ignoredErrors.contains(state)) 80 { 81 error.setIgnored(true); 82 } 83 } 84 if(!error.getIgnored()) 85 ++nume; 86 } 87 if(nume == 0) 88 return true; 89 } 90 return displayErrorScreen(errors); 91 } 92 92 93 94 95 96 97 98 99 100 101 102 103 104 105 93 /** 94 * Displays a screen where the actions that would be taken are displayed and 95 * give the user the possibility to cancel the upload. 96 * @param errors The errors displayed in the screen 97 * @return <code>true</code>, if the upload should continue. <code>false</code> 98 * if the user requested cancel. 99 */ 100 private boolean displayErrorScreen(List<TestError> errors) 101 { 102 JPanel p = new JPanel(new GridBagLayout()); 103 ErrorTreePanel errorPanel = new ErrorTreePanel(errors); 104 errorPanel.expandAll(); 105 p.add(new JScrollPane(errorPanel), GBC.eol()); 106 106 107 108 109 110 111 112 113 114 115 116 107 int res = JOptionPane.showConfirmDialog(Main.parent, p, 108 tr("Data with errors. Upload anyway?"), JOptionPane.YES_NO_OPTION); 109 if(res == JOptionPane.NO_OPTION) 110 { 111 plugin.validationDialog.tree.setErrors(errors); 112 plugin.validationDialog.setVisible(true); 113 DataSet.fireSelectionChanged(Main.ds.getSelected()); 114 } 115 return res == JOptionPane.YES_OPTION; 116 } 117 117 } -
applications/editors/josm/plugins/validator/src/org/openstreetmap/josm/plugins/validator/tests/ChangePropertyKeyCommand.java
r7804 r12778 22 22 */ 23 23 public class ChangePropertyKeyCommand extends Command { 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 24 /** 25 * All primitives, that are affected with this command. 26 */ 27 private final List<OsmPrimitive> objects; 28 /** 29 * The key that is subject to change. 30 */ 31 private final String key; 32 /** 33 * The mew key. 34 */ 35 private final String newKey; 36 37 /** 38 * Constructor 39 * 40 * @param objects all objects subject to change replacement 41 * @param key The key to replace 42 * @param newKey the new value of the key 43 */ 44 public ChangePropertyKeyCommand(Collection<? extends OsmPrimitive> objects, String key, String newKey) { 45 this.objects = new LinkedList<OsmPrimitive>(objects); 46 this.key = key; 47 this.newKey = newKey; 48 } 49 50 @Override public boolean executeCommand() { 51 if (!super.executeCommand()) return false; // save old 52 for (OsmPrimitive osm : objects) { 53 if(osm.keys != null) 54 { 55 osm.modified = true; 56 osm.put(newKey, osm.keys.remove(key) ); 57 } 58 } 59 59 return true; 60 60 } 61 61 62 63 64 62 @Override public void fillModifiedData(Collection<OsmPrimitive> modified, Collection<OsmPrimitive> deleted, Collection<OsmPrimitive> added) { 63 modified.addAll(objects); 64 } 65 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 66 @Override public MutableTreeNode description() { 67 String text = tr( "Replace \"{0}\" by \"{1}\" for", key, newKey); 68 if (objects.size() == 1) { 69 NameVisitor v = new NameVisitor(); 70 objects.iterator().next().visit(v); 71 text += " "+tr(v.className)+" "+v.name; 72 } else 73 text += " "+objects.size()+" "+trn("object","objects",objects.size()); 74 DefaultMutableTreeNode root = new DefaultMutableTreeNode(new JLabel(text, ImageProvider.get("data", "key"), JLabel.HORIZONTAL)); 75 if (objects.size() == 1) 76 return root; 77 NameVisitor v = new NameVisitor(); 78 for (OsmPrimitive osm : objects) { 79 osm.visit(v); 80 root.add(new DefaultMutableTreeNode(v.toLabel())); 81 } 82 return root; 83 83 } 84 84 } -
applications/editors/josm/plugins/validator/src/org/openstreetmap/josm/plugins/validator/tests/Coastlines.java
r9684 r12778 21 21 public class Coastlines extends Test 22 22 { 23 23 protected static int UNORDERED_COASTLINES = 901; 24 24 25 26 27 28 25 /** All ways, grouped by cells */ 26 Map<Point2D,List<Way>> _cellWays; 27 /** The already detected errors */ 28 Bag<Way, Way> _errorWays; 29 29 30 31 32 33 34 35 36 37 30 /** 31 * Constructor 32 */ 33 public Coastlines() 34 { 35 super(tr("Coastlines."), 36 tr("This test checks that coastlines are correct.")); 37 } 38 38 39 40 41 42 43 44 39 @Override 40 public void startTest() 41 { 42 _cellWays = new HashMap<Point2D,List<Way>>(1000); 43 _errorWays = new Bag<Way, Way>(); 44 } 45 45 46 47 48 49 50 51 46 @Override 47 public void endTest() 48 { 49 _cellWays = null; 50 _errorWays = null; 51 } 52 52 53 54 55 56 57 53 @Override 54 public void visit(Way w) 55 { 56 if( w.deleted || w.incomplete ) 57 return; 58 58 59 60 61 59 String natural = w.get("natural"); 60 if( natural == null || !natural.equals("coastline") ) 61 return; 62 62 63 64 65 66 67 68 69 63 List<List<Way>> cellWays = Util.getWaysInCell(w, _cellWays); 64 for( List<Way> ways : cellWays) 65 { 66 for( Way w2 : ways) 67 { 68 if( _errorWays.contains(w, w2) || _errorWays.contains(w2, w) ) 69 continue; 70 70 71 72 73 71 String natural2 = w.get("natural"); 72 if( natural2 == null || !natural2.equals("coastline") ) 73 continue; 74 74 75 76 77 78 79 80 81 82 83 84 85 86 75 if( w.nodes.get(0).equals(w2.nodes.get(0)) || w.nodes.get(w.nodes.size() - 1).equals(w2.nodes.get(w2.nodes.size() - 1))) 76 { 77 List<OsmPrimitive> primitives = new ArrayList<OsmPrimitive>(); 78 primitives.add(w); 79 primitives.add(w2); 80 errors.add( new TestError(this, Severity.ERROR, tr("Unordered coastline"), UNORDERED_COASTLINES, primitives) ); 81 _errorWays.add(w, w2); 82 } 83 } 84 ways.add(w); 85 } 86 } 87 87 } -
applications/editors/josm/plugins/validator/src/org/openstreetmap/josm/plugins/validator/tests/CrossingWays.java
r12257 r12778 28 28 public class CrossingWays extends Test 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 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 30 protected static int CROSSING_WAYS = 601; 31 32 /** All way segments, grouped by cells */ 33 Map<Point2D,List<ExtendedSegment>> cellSegments; 34 /** The already detected errors */ 35 HashSet<WaySegment> errorSegments; 36 /** The already detected ways in error */ 37 Map<List<Way>, List<WaySegment>> ways_seen; 38 39 40 /** 41 * Constructor 42 */ 43 public CrossingWays() 44 { 45 super(tr("Crossing ways."), 46 tr("This test checks if two roads, railways or waterways crosses in the same layer, but are not connected by a node.")); 47 } 48 49 50 @Override 51 public void startTest() 52 { 53 cellSegments = new HashMap<Point2D,List<ExtendedSegment>>(1000); 54 errorSegments = new HashSet<WaySegment>(); 55 ways_seen = new HashMap<List<Way>, List<WaySegment>>(50); 56 } 57 58 @Override 59 public void endTest() 60 { 61 cellSegments = null; 62 errorSegments = null; 63 ways_seen = null; 64 } 65 66 @Override 67 public void visit(Way w) 68 { 69 if( w.deleted || w.incomplete ) 70 return; 71 72 String coastline1 = w.get("natural"); 73 boolean isCoastline1 = coastline1 != null && (coastline1.equals("water") || coastline1.equals("coastline")); 74 String railway1 = w.get("railway"); 75 boolean isSubway1 = railway1 != null && railway1.equals("subway"); 76 if( w.get("highway") == null && w.get("waterway") == null && (railway1 == null || isSubway1) && !isCoastline1) 77 return; 78 79 String layer1 = w.get("layer"); 80 81 int nodesSize = w.nodes.size(); 82 for (int i = 0; i < nodesSize - 1; i++) { 83 WaySegment ws = new WaySegment(w, i); 84 ExtendedSegment es1 = new ExtendedSegment(ws, layer1, railway1, coastline1); 85 List<List<ExtendedSegment>> cellSegments = getSegments(es1.n1, es1.n2); 86 for( List<ExtendedSegment> segments : cellSegments) 87 { 88 for( ExtendedSegment es2 : segments) 89 { 90 List<Way> prims; 91 List<WaySegment> highlight; 92 93 if (errorSegments.contains(ws) && errorSegments.contains(es2.ws)) 94 continue; 95 96 String layer2 = es2.layer; 97 String railway2 = es2.railway; 98 String coastline2 = es2.coastline; 99 if (layer1 == null ? layer2 != null : !layer1.equals(layer2)) 100 continue; 101 102 if( !es1.intersects(es2) ) continue; 103 if( isSubway1 && "subway".equals(railway2)) continue; 104 105 boolean isCoastline2 = coastline2 != null && (coastline2.equals("water") || coastline2.equals("coastline")); 106 if( isCoastline1 != isCoastline2 ) continue; 107 108 prims = Arrays.asList(es1.ws.way, es2.ws.way); 109 if ((highlight = ways_seen.get(prims)) == null) 110 { 111 highlight = new ArrayList<WaySegment>(); 112 highlight.add(es1.ws); 113 highlight.add(es2.ws); 114 115 errors.add(new TestError(this, Severity.WARNING, 116 tr("Crossing ways"), CROSSING_WAYS, prims, highlight)); 117 ways_seen.put(prims, highlight); 118 } 119 else 120 { 121 highlight.add(es1.ws); 122 highlight.add(es2.ws); 123 } 124 } 125 segments.add(es1); 126 } 127 } 128 } 129 130 /** 131 * Returns all the cells this segment crosses. Each cell contains the list 132 * of segments already processed 133 * 134 * @param n1 The first node 135 * @param n2 The second node 136 * @return A list with all the cells the segment crosses 137 */ 138 public List<List<ExtendedSegment>> getSegments(Node n1, Node n2) 139 { 140 List<List<ExtendedSegment>> cells = new ArrayList<List<ExtendedSegment>>(); 141 for( Point2D cell : Util.getSegmentCells(n1, n2, OSMValidatorPlugin.griddetail) ) 142 { 143 List<ExtendedSegment> segments = cellSegments.get( cell ); 144 if( segments == null ) 145 { 146 segments = new ArrayList<ExtendedSegment>(); 147 cellSegments.put(cell, segments); 148 } 149 cells.add(segments); 150 } 151 152 return cells; 153 } 154 155 /** 156 * A way segment with some additional information 157 * @author frsantos 158 */ 159 private class ExtendedSegment 160 { 161 public Node n1, n2; 162 163 public WaySegment ws; 164 165 /** The layer */ 166 public String layer; 167 168 /** The railway type */ 169 public String railway; 170 171 /** The coastline type */ 172 public String coastline; 173 174 /** 175 * Constructor 176 * @param ws The way segment 177 * @param layer The layer of the way this segment is in 178 * @param railway The railway type of the way this segment is in 179 * @param coastline The coastlyne typo of the way the segment is in 180 */ 181 public ExtendedSegment(WaySegment ws, String layer, String railway, String coastline) 182 { 183 this.ws = ws; 184 this.n1 = ws.way.nodes.get(ws.lowerIndex); 185 this.n2 = ws.way.nodes.get(ws.lowerIndex + 1); 186 this.layer = layer; 187 this.railway = railway; 188 this.coastline = coastline; 189 } 190 191 /** 192 * Checks whether this segment crosses other segment 193 * @param s2 The other segment 194 * @return true if both segements crosses 195 */ 196 public boolean intersects(ExtendedSegment s2) 197 { 198 if( n1.equals(s2.n1) || n2.equals(s2.n2) || 199 n1.equals(s2.n2) || n2.equals(s2.n1) ) 200 { 201 return false; 202 } 203 204 return Line2D.linesIntersect( 205 n1.eastNorth.east(), n1.eastNorth.north(), 206 n2.eastNorth.east(), n2.eastNorth.north(), 207 s2.n1.eastNorth.east(), s2.n1.eastNorth.north(), 208 s2.n2.eastNorth.east(), s2.n2.eastNorth.north()); 209 } 210 } 211 211 } -
applications/editors/josm/plugins/validator/src/org/openstreetmap/josm/plugins/validator/tests/DuplicateNode.java
r12279 r12778 20 20 public class DuplicateNode extends Test 21 21 { 22 22 protected static int DUPLICATE_NODE = 1; 23 23 24 25 24 /** Bag of all nodes */ 25 Bag<LatLon, OsmPrimitive> nodes; 26 26 27 28 29 30 31 32 33 34 27 /** 28 * Constructor 29 */ 30 public DuplicateNode() 31 { 32 super(tr("Duplicated nodes."), 33 tr("This test checks that there are no nodes at the very same location.")); 34 } 35 35 36 36 37 38 39 40 41 37 @Override 38 public void startTest() 39 { 40 nodes = new Bag<LatLon, OsmPrimitive>(1000); 41 } 42 42 43 44 45 46 47 48 49 50 51 52 53 54 55 43 @Override 44 public void endTest() 45 { 46 for(List<OsmPrimitive> duplicated : nodes.values() ) 47 { 48 if( duplicated.size() > 1) 49 { 50 TestError testError = new TestError(this, Severity.ERROR, tr("Duplicated nodes"), DUPLICATE_NODE, duplicated); 51 errors.add( testError ); 52 } 53 } 54 nodes = null; 55 } 56 56 57 58 59 60 61 62 57 @Override 58 public void visit(Node n) 59 { 60 if(!n.deleted && !n.incomplete) 61 nodes.add(n.coor, n); 62 } 63 63 64 65 66 67 68 69 70 71 72 64 /** 65 * Merge the nodes into one. 66 * Copied from UtilsPlugin.MergePointsAction 67 */ 68 @Override 69 public Command fixError(TestError testError) 70 { 71 Collection<? extends OsmPrimitive> sel = testError.getPrimitives(); 72 LinkedList<Node> nodes = new LinkedList<Node>(); 73 73 74 74 for (OsmPrimitive osm : sel) … … 80 80 81 81 Node target = null; 82 82 // select the target node in the same way as in the core action MergeNodesAction, rev.1084 83 83 for (Node n: nodes) { 84 84 if (n.id > 0) { … … 93 93 94 94 return null; // undoRedo handling done in mergeNodes 95 95 } 96 96 97 98 99 100 101 97 @Override 98 public boolean isFixable(TestError testError) 99 { 100 return (testError.getTester() instanceof DuplicateNode); 101 } 102 102 } -
applications/editors/josm/plugins/validator/src/org/openstreetmap/josm/plugins/validator/tests/DuplicatedWayNodes.java
r11530 r12778 16 16 17 17 public class DuplicatedWayNodes extends Test { 18 18 protected static int DUPLICATE_WAY_NODE = 501; 19 19 20 21 22 23 20 public DuplicatedWayNodes() { 21 super(tr("Duplicated way nodes."), 22 tr("Checks for ways with identical consecutive nodes.")); 23 } 24 24 25 26 25 @Override public void visit(Way w) { 26 if (w.deleted || w.incomplete) return; 27 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 28 Node lastN = null; 29 for (Node n : w.nodes) { 30 if (lastN == null) { 31 lastN = n; 32 continue; 33 } 34 if (lastN == n) { 35 errors.add(new TestError(this, Severity.ERROR, tr("Duplicated way nodes"), DUPLICATE_WAY_NODE, 36 Arrays.asList(w), Arrays.asList(n))); 37 break; 38 } 39 lastN = n; 40 } 41 } 42 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 43 @Override public Command fixError(TestError testError) { 44 Way w = (Way) testError.getPrimitives().iterator().next(); 45 Way wnew = new Way(w); 46 wnew.nodes.clear(); 47 Node lastN = null; 48 for (Node n : w.nodes) { 49 if (lastN == null) { 50 wnew.nodes.add(n); 51 } else if (n == lastN) { 52 // Skip this node 53 } else { 54 wnew.nodes.add(n); 55 } 56 lastN = n; 57 } 58 if (wnew.nodes.size() < 2) { 59 // Empty way, delete 60 return DeleteCommand.delete(Collections.singleton(w)); 61 } else { 62 return new ChangeCommand(w, wnew); 63 } 64 } 65 65 66 67 68 } 66 @Override public boolean isFixable(TestError testError) { 67 return testError.getTester() instanceof DuplicatedWayNodes; 68 } 69 69 } -
applications/editors/josm/plugins/validator/src/org/openstreetmap/josm/plugins/validator/tests/NodesWithSameName.java
r10520 r12778 14 14 15 15 public class NodesWithSameName extends Test { 16 16 protected static int SAME_NAME = 801; 17 17 18 18 private Map<String, List<Node>> namesToNodes; 19 19 20 21 22 23 20 public NodesWithSameName() { 21 super(tr("Nodes with same name"), 22 tr("This test finds nodes that have the same name (might be duplicates).")); 23 } 24 24 25 26 27 25 @Override public void startTest() { 26 namesToNodes = new HashMap<String, List<Node>>(); 27 } 28 28 29 30 29 @Override public void visit(Node n) { 30 if (n.deleted || n.incomplete) return; 31 31 32 33 34 32 String name = n.get("name"); 33 String sign = n.get("traffic_sign"); 34 if (name == null || (sign != null && sign.equals("city_limit"))) return; 35 35 36 37 38 36 List<Node> nodes = namesToNodes.get(name); 37 if (nodes == null) 38 namesToNodes.put(name, nodes = new ArrayList<Node>()); 39 39 40 41 40 nodes.add(n); 41 } 42 42 43 44 45 46 47 48 49 43 @Override public void endTest() { 44 for (List<Node> nodes : namesToNodes.values()) { 45 if (nodes.size() > 1) { 46 errors.add(new TestError(this, Severity.OTHER, 47 tr("Nodes with same name"), SAME_NAME, nodes)); 48 } 49 } 50 50 51 52 51 namesToNodes = null; 52 } 53 53 } -
applications/editors/josm/plugins/validator/src/org/openstreetmap/josm/plugins/validator/tests/OverlappingWays.java
r11530 r12778 21 21 /** 22 22 * Tests if there are overlapping ways 23 * 23 * 24 24 * @author frsantos 25 25 */ 26 26 public class OverlappingWays extends Test 27 27 { 28 29 28 /** Bag of all way segments */ 29 Bag<Pair<Node,Node>, WaySegment> nodePairs; 30 30 31 32 33 34 35 36 37 31 protected static int OVERLAPPING_HIGHWAY = 101; 32 protected static int OVERLAPPING_RAILWAY = 102; 33 protected static int OVERLAPPING_WAY = 103; 34 protected static int OVERLAPPING_HIGHWAY_AREA = 111; 35 protected static int OVERLAPPING_RAILWAY_AREA = 112; 36 protected static int OVERLAPPING_WAY_AREA = 113; 37 protected static int OVERLAPPING_AREA = 120; 38 38 39 40 41 42 43 44 45 46 39 /** Constructor */ 40 public OverlappingWays() 41 { 42 super(tr("Overlapping ways."), 43 tr("This test checks that a connection between two nodes " 44 + "is not used by more than one way.")); 45 46 } 47 47 48 48 49 50 public void startTest() 51 52 53 49 @Override 50 public void startTest() 51 { 52 nodePairs = new Bag<Pair<Node,Node>, WaySegment>(1000); 53 } 54 54 55 56 57 58 55 @Override 56 public void endTest() 57 { 58 Map<List<Way>, List<WaySegment>> ways_seen = new HashMap<List<Way>, List<WaySegment>>(500); 59 59 60 61 62 60 for (List<WaySegment> duplicated : nodePairs.values()) 61 { 62 int ways = duplicated.size(); 63 63 64 65 66 67 68 69 70 71 64 if (ways > 1) 65 { 66 List<OsmPrimitive> prims = new ArrayList<OsmPrimitive>(); 67 List<Way> current_ways = new ArrayList<Way>(); 68 List<WaySegment> highlight; 69 int highway = 0; 70 int railway = 0; 71 int area = 0; 72 72 73 for (WaySegment ws : duplicated) 74 75 76 77 78 79 80 81 82 83 84 85 86 87 73 for (WaySegment ws : duplicated) 74 { 75 if (ws.way.get("highway") != null) 76 highway++; 77 else if (ws.way.get("railway") != null) 78 railway++; 79 Boolean ar = OsmUtils.getOsmBoolean(ws.way.get("area")); 80 if (ar != null && ar) 81 area++; 82 if (ws.way.get("landuse") != null || ws.way.get("natural") != null 83 || ws.way.get("amenity") != null || ws.way.get("leisure") != null 84 || ws.way.get("building") != null) 85 { 86 area++; ways--; 87 } 88 88 89 90 91 92 93 94 95 96 97 98 99 89 prims.add(ws.way); 90 current_ways.add(ws.way); 91 } 92 /* These ways not seen before 93 * If two or more of the overlapping ways are 94 * highways or railways mark a seperate error 95 */ 96 if ((highlight = ways_seen.get(current_ways)) == null) 97 { 98 String errortype; 99 int type; 100 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 101 if(area > 0) 102 { 103 if (ways == 0 || duplicated.size() == area) 104 { 105 errortype = tr("Overlapping areas"); 106 type = OVERLAPPING_AREA; 107 } 108 else if (highway == ways) 109 { 110 errortype = tr("Overlapping highways (with area)"); 111 type = OVERLAPPING_HIGHWAY_AREA; 112 } 113 else if (railway == ways) 114 { 115 errortype = tr("Overlapping railways (with area)"); 116 type = OVERLAPPING_RAILWAY_AREA; 117 } 118 else 119 { 120 errortype = tr("Overlapping ways (with area)"); 121 type = OVERLAPPING_WAY_AREA; 122 } 123 } 124 else if (highway == ways) 125 { 126 errortype = tr("Overlapping highways"); 127 type = OVERLAPPING_HIGHWAY; 128 } 129 else if (railway == ways) 130 { 131 errortype = tr("Overlapping railways"); 132 type = OVERLAPPING_RAILWAY; 133 } 134 else 135 { 136 errortype = tr("Overlapping ways"); 137 type = OVERLAPPING_WAY; 138 } 139 139 140 141 142 143 144 else/* way seen, mark highlight layer only */145 146 147 148 149 150 151 152 140 errors.add(new TestError(this, type < OVERLAPPING_HIGHWAY_AREA 141 ? Severity.WARNING : Severity.OTHER, tr(errortype), type, prims, duplicated)); 142 ways_seen.put(current_ways, duplicated); 143 } 144 else /* way seen, mark highlight layer only */ 145 { 146 for (WaySegment ws : duplicated) 147 highlight.add(ws); 148 } 149 } 150 } 151 nodePairs = null; 152 } 153 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 154 @Override 155 public void visit(Way w) 156 { 157 Node lastN = null; 158 int i = -2; 159 for (Node n : w.nodes) { 160 i++; 161 if (lastN == null) { 162 lastN = n; 163 continue; 164 } 165 nodePairs.add(Pair.sort(new Pair<Node,Node>(lastN, n)), 166 new WaySegment(w, i)); 167 lastN = n; 168 } 169 } 170 170 } -
applications/editors/josm/plugins/validator/src/org/openstreetmap/josm/plugins/validator/tests/SelfIntersectingWay.java
r10520 r12778 16 16 */ 17 17 public class SelfIntersectingWay extends Test { 18 18 protected static int SELF_INTERSECT = 401; 19 19 20 21 22 23 24 20 public SelfIntersectingWay() { 21 super(tr("Self-intersecting ways"), 22 tr("This test checks for ways " + 23 "that contain some of their nodes more than once.")); 24 } 25 25 26 27 26 @Override public void visit(Way w) { 27 HashSet<Node> nodes = new HashSet<Node>(); 28 28 29 30 31 32 33 34 35 36 37 38 39 40 29 for (int i = 1; i < w.nodes.size() - 1; i++) { 30 Node n = w.nodes.get(i); 31 if (nodes.contains(n)) { 32 errors.add(new TestError(this, 33 Severity.WARNING, tr("Self-intersecting ways"), SELF_INTERSECT, 34 Arrays.asList(w), Arrays.asList(n))); 35 break; 36 } else { 37 nodes.add(n); 38 } 39 } 40 } 41 41 } -
applications/editors/josm/plugins/validator/src/org/openstreetmap/josm/plugins/validator/tests/SimilarNamedWays.java
r9684 r12778 22 22 public class SimilarNamedWays extends Test 23 23 { 24 24 protected static int SIMILAR_NAMED = 701; 25 25 26 27 28 29 26 /** All ways, grouped by cells */ 27 Map<Point2D,List<Way>> cellWays; 28 /** The already detected errors */ 29 Bag<Way, Way> errorWays; 30 30 31 32 33 34 35 36 37 38 31 /** 32 * Constructor 33 */ 34 public SimilarNamedWays() 35 { 36 super(tr("Similar named ways."), 37 tr("This test checks for ways with similar names that may have been misspelled.")); 38 } 39 39 40 41 42 43 44 45 40 @Override 41 public void startTest() 42 { 43 cellWays = new HashMap<Point2D,List<Way>>(1000); 44 errorWays = new Bag<Way, Way>(); 45 } 46 46 47 48 49 50 51 52 47 @Override 48 public void endTest() 49 { 50 cellWays = null; 51 errorWays = null; 52 } 53 53 54 55 56 57 58 54 @Override 55 public void visit(Way w) 56 { 57 if( w.deleted || w.incomplete ) 58 return; 59 59 60 61 62 60 String name = w.get("name"); 61 if( name == null || name.length() < 6 ) 62 return; 63 63 64 65 66 67 68 69 70 64 List<List<Way>> theCellWays = Util.getWaysInCell(w, cellWays); 65 for( List<Way> ways : theCellWays) 66 { 67 for( Way w2 : ways) 68 { 69 if( errorWays.contains(w, w2) || errorWays.contains(w2, w) ) 70 continue; 71 71 72 73 74 72 String name2 = w2.get("name"); 73 if( name2 == null || name2.length() < 6 ) 74 continue; 75 75 76 77 78 79 80 81 82 83 84 85 86 87 88 76 int levenshteinDistance = getLevenshteinDistance(name, name2); 77 if( 0 < levenshteinDistance && levenshteinDistance <= 2 ) 78 { 79 List<OsmPrimitive> primitives = new ArrayList<OsmPrimitive>(); 80 primitives.add(w); 81 primitives.add(w2); 82 errors.add( new TestError(this, Severity.WARNING, tr("Similar named ways"), SIMILAR_NAMED, primitives) ); 83 errorWays.add(w, w2); 84 } 85 } 86 ways.add(w); 87 } 88 } 89 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 90 /** 91 * Compute Levenshtein distance 92 * 93 * @param s First word 94 * @param t Second word 95 * @return The distance between words 96 */ 97 public int getLevenshteinDistance(String s, String t) 98 { 99 int d[][]; // matrix 100 int n; // length of s 101 int m; // length of t 102 int i; // iterates through s 103 int j; // iterates through t 104 char s_i; // ith character of s 105 char t_j; // jth character of t 106 int cost; // cost 107 107 108 108 // Step 1 109 109 110 111 112 113 114 110 n = s.length(); 111 m = t.length(); 112 if (n == 0) return m; 113 if (m == 0) return n; 114 d = new int[n + 1][m + 1]; 115 115 116 117 118 116 // Step 2 117 for (i = 0; i <= n; i++) d[i][0] = i; 118 for (j = 0; j <= m; j++) d[0][j] = j; 119 119 120 121 122 123 120 // Step 3 121 for (i = 1; i <= n; i++) 122 { 123 s_i = s.charAt(i - 1); 124 124 125 126 127 128 125 // Step 4 126 for (j = 1; j <= m; j++) 127 { 128 t_j = t.charAt(j - 1); 129 129 130 131 132 133 134 135 136 137 138 130 // Step 5 131 if (s_i == t_j) 132 { 133 cost = 0; 134 } 135 else 136 { 137 cost = 1; 138 } 139 139 140 141 142 143 140 // Step 6 141 d[i][j] = Minimum(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + cost); 142 } 143 } 144 144 145 146 147 145 // Step 7 146 return d[n][m]; 147 } 148 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 149 /** 150 * Get minimum of three values 151 * @param a First value 152 * @param b Second value 153 * @param c Third value 154 * @return The minimum of the tre values 155 */ 156 private static int Minimum(int a, int b, int c) 157 { 158 int mi = a; 159 if (b < mi) 160 { 161 mi = b; 162 } 163 if (c < mi) 164 { 165 mi = c; 166 } 167 return mi; 168 } 169 169 } -
applications/editors/josm/plugins/validator/src/org/openstreetmap/josm/plugins/validator/tests/TagChecker.java
r12777 r12778 63 63 public class TagChecker extends Test 64 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 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 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 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 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 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 65 /** The default data files */ 66 public static final String DATA_FILE = "http://svn.openstreetmap.org/applications/editors/josm/plugins/validator/tagchecker.cfg"; 67 public static final String SPELL_FILE = "http://svn.openstreetmap.org/applications/utils/planet.osm/java/speller/words.cfg"; 68 69 /** The spell check key substitutions: the key should be substituted by the value */ 70 protected static Map<String, String> spellCheckKeyData; 71 /** The spell check preset values */ 72 protected static Bag<String, String> presetsValueData; 73 /** The TagChecker data */ 74 protected static List<CheckerData> checkerData = new ArrayList<CheckerData>(); 75 76 /** The preferences prefix */ 77 protected static final String PREFIX = PreferenceEditor.PREFIX + "." + TagChecker.class.getSimpleName(); 78 79 public static final String PREF_CHECK_VALUES = PREFIX + ".checkValues"; 80 public static final String PREF_CHECK_KEYS = PREFIX + ".checkKeys"; 81 public static final String PREF_CHECK_COMPLEX = PREFIX + ".checkComplex"; 82 public static final String PREF_CHECK_FIXMES = PREFIX + ".checkFixmes"; 83 public static final String PREF_CHECK_PAINT = PREFIX + ".paint"; 84 85 public static final String PREF_SOURCES = PREFIX + ".sources"; 86 public static final String PREF_USE_DATA_FILE = PREFIX + ".usedatafile"; 87 public static final String PREF_USE_SPELL_FILE = PREFIX + ".usespellfile"; 88 89 public static final String PREF_CHECK_KEYS_BEFORE_UPLOAD = PREF_CHECK_KEYS + "BeforeUpload"; 90 public static final String PREF_CHECK_VALUES_BEFORE_UPLOAD = PREF_CHECK_VALUES + "BeforeUpload"; 91 public static final String PREF_CHECK_COMPLEX_BEFORE_UPLOAD = PREF_CHECK_COMPLEX + "BeforeUpload"; 92 public static final String PREF_CHECK_FIXMES_BEFORE_UPLOAD = PREF_CHECK_FIXMES + "BeforeUpload"; 93 public static final String PREF_CHECK_PAINT_BEFORE_UPLOAD = PREF_CHECK_PAINT + "BeforeUpload"; 94 95 protected boolean checkKeys = false; 96 protected boolean checkValues = false; 97 protected boolean checkComplex = false; 98 protected boolean checkFixmes = false; 99 protected boolean checkPaint = false; 100 101 protected JCheckBox prefCheckKeys; 102 protected JCheckBox prefCheckValues; 103 protected JCheckBox prefCheckComplex; 104 protected JCheckBox prefCheckFixmes; 105 protected JCheckBox prefCheckPaint; 106 107 protected JCheckBox prefCheckKeysBeforeUpload; 108 protected JCheckBox prefCheckValuesBeforeUpload; 109 protected JCheckBox prefCheckComplexBeforeUpload; 110 protected JCheckBox prefCheckFixmesBeforeUpload; 111 protected JCheckBox prefCheckPaintBeforeUpload; 112 113 protected JCheckBox prefUseDataFile; 114 protected JCheckBox prefUseSpellFile; 115 116 protected JButton addSrcButton; 117 protected JButton editSrcButton; 118 protected JButton deleteSrcButton; 119 120 protected static int EMPTY_VALUES = 1200; 121 protected static int INVALID_KEY = 1201; 122 protected static int INVALID_VALUE = 1202; 123 protected static int FIXME = 1203; 124 protected static int INVALID_SPACE = 1204; 125 protected static int INVALID_KEY_SPACE = 1205; 126 protected static int INVALID_HTML = 1206; 127 protected static int PAINT = 1207; 128 /** 1250 and up is used by tagcheck */ 129 130 /** List of sources for spellcheck data */ 131 protected JList Sources; 132 133 134 protected static Entities entities = new Entities(); 135 /** 136 * Constructor 137 */ 138 public TagChecker() 139 { 140 super(tr("Properties checker :"), 141 tr("This plugin checks for errors in property keys and values.")); 142 } 143 144 public static void initialize(OSMValidatorPlugin plugin) throws Exception 145 { 146 initializeData(); 147 initializePresets(); 148 } 149 150 /** 151 * Reads the spellcheck file into a HashMap. 152 * The data file is a list of words, beginning with +/-. If it starts with +, 153 * the word is valid, but if it starts with -, the word should be replaced 154 * by the nearest + word before this. 155 * 156 * @throws FileNotFoundException 157 * @throws IOException 158 */ 159 private static void initializeData() throws IOException 160 { 161 spellCheckKeyData = new HashMap<String, String>(); 162 String sources = Main.pref.get( PREF_SOURCES, ""); 163 if(Main.pref.getBoolean(PREF_USE_DATA_FILE, true)) 164 { 165 if( sources == null || sources.length() == 0) 166 sources = DATA_FILE; 167 else 168 sources = DATA_FILE + ";" + sources; 169 } 170 if(Main.pref.getBoolean(PREF_USE_SPELL_FILE, true)) 171 { 172 if( sources == null || sources.length() == 0) 173 sources = SPELL_FILE; 174 else 175 sources = SPELL_FILE + ";" + sources; 176 } 177 178 String errorSources = ""; 179 if(sources.length() == 0) 180 return; 181 for(String source: sources.split(";")) 182 { 183 try 184 { 185 MirroredInputStream s = new MirroredInputStream(source, Util.getPluginDir(), -1); 186 InputStreamReader r; 187 try 188 { 189 r = new InputStreamReader(s, "UTF-8"); 190 } 191 catch (UnsupportedEncodingException e) 192 { 193 r = new InputStreamReader(s); 194 } 195 BufferedReader reader = new BufferedReader(r); 196 197 String okValue = null; 198 Boolean tagcheckerfile = false; 199 String line; 200 while((line = reader.readLine()) != null && (tagcheckerfile || line.length() != 0)) 201 { 202 if(line.startsWith("#")) 203 { 204 if(line.startsWith("# JOSM TagChecker")) 205 tagcheckerfile = true; 206 } 207 else if(tagcheckerfile) 208 { 209 if(line.length() > 0) 210 { 211 CheckerData d = new CheckerData(); 212 String err = d.getData(line); 213 214 if(err == null) 215 checkerData.add(d); 216 else 217 System.err.println(tr("Invalid tagchecker line - {0}: {1}", err, line)); 218 } 219 } 220 else if(line.charAt(0) == '+') 221 { 222 okValue = line.substring(1); 223 } 224 else if(line.charAt(0) == '-' && okValue != null) 225 { 226 spellCheckKeyData.put(line.substring(1), okValue); 227 } 228 else 229 { 230 System.err.println(tr("Invalid spellcheck line: {0}", line)); 231 } 232 } 233 } 234 catch (IOException e) 235 { 236 errorSources += source + "\n"; 237 } 238 } 239 240 if( errorSources.length() > 0 ) 241 throw new IOException( tr("Could not access data file(s):\n{0}", errorSources) ); 242 } 243 244 /** 245 * Reads the presets data. 246 * 247 * @throws Exception 248 */ 249 public static void initializePresets() throws Exception 250 { 251 if( !Main.pref.getBoolean(PREF_CHECK_VALUES, true) ) 252 return; 253 254 Collection<TaggingPreset> presets = TaggingPresetPreference.taggingPresets; 255 if(presets != null) 256 { 257 presetsValueData = new Bag<String, String>(); 258 for(TaggingPreset p : presets) 259 { 260 for(TaggingPreset.Item i : p.data) 261 { 262 if(i instanceof TaggingPreset.Combo) 263 { 264 TaggingPreset.Combo combo = (TaggingPreset.Combo) i; 265 for(String value : combo.values.split(",")) 266 presetsValueData.add(combo.key, value); 267 } 268 else if(i instanceof TaggingPreset.Key) 269 { 270 TaggingPreset.Key k = (TaggingPreset.Key) i; 271 presetsValueData.add(k.key, k.value); 272 } 273 } 274 } 275 } 276 } 277 278 @Override 279 public void visit(Node n) 280 { 281 checkPrimitive(n); 282 } 283 284 285 @Override 286 public void visit(Relation n) 287 { 288 checkPrimitive(n); 289 } 290 291 292 @Override 293 public void visit(Way w) 294 { 295 checkPrimitive(w); 296 } 297 298 /** 299 * Checks the primitive properties 300 * @param p The primitive to check 301 */ 302 private void checkPrimitive(OsmPrimitive p) 303 { 304 // Just a collection to know if a primitive has been already marked with error 305 Bag<OsmPrimitive, String> withErrors = new Bag<OsmPrimitive, String>(); 306 307 if(checkComplex) 308 { 309 for(CheckerData d : checkerData) 310 { 311 if(d.match(p)) 312 { 313 errors.add( new TestError(this, d.getSeverity(), tr("Illegal tag/value combinations"), 314 d.getDescription(), d.getDescriptionOrig(), d.getCode(), p) ); 315 withErrors.add(p, "TC"); 316 break; 317 } 318 } 319 } 320 if(checkPaint && p.errors != null) 321 { 322 for(String s: p.errors) 323 { 324 /* passing translated text also to original string, as we already 325 translated the stuff before. Makes the ignore file language dependend. */ 326 errors.add( new TestError(this, Severity.WARNING, tr("Painting problem"), 327 s, s, PAINT, p) ); 328 withErrors.add(p, "P"); 329 } 330 } 331 332 Map<String, String> props = (p.keys == null) ? Collections.<String, String>emptyMap() : p.keys; 333 for(Entry<String, String> prop: props.entrySet() ) 334 { 335 String s = marktr("Key ''{0}'' invalid."); 336 String key = prop.getKey(); 337 String value = prop.getValue(); 338 if( checkValues && (value==null || value.trim().length() == 0) && !withErrors.contains(p, "EV")) 339 { 340 errors.add( new TestError(this, Severity.WARNING, tr("Tags with empty values"), 341 tr(s, key), MessageFormat.format(s, key), EMPTY_VALUES, p) ); 342 withErrors.add(p, "EV"); 343 } 344 if( checkKeys && spellCheckKeyData.containsKey(key) && !withErrors.contains(p, "IPK")) 345 { 346 errors.add( new TestError(this, Severity.WARNING, tr("Invalid property key"), 347 tr(s, key), MessageFormat.format(s, key), INVALID_KEY, p) ); 348 withErrors.add(p, "IPK"); 349 } 350 if( checkKeys && key.indexOf(" ") >= 0 && !withErrors.contains(p, "IPK")) 351 { 352 errors.add( new TestError(this, Severity.WARNING, tr("Invalid white space in property key"), 353 tr(s, key), MessageFormat.format(s, key), INVALID_KEY_SPACE, p) ); 354 withErrors.add(p, "IPK"); 355 } 356 if( checkValues && value != null && (value.startsWith(" ") || value.endsWith(" ")) && !withErrors.contains(p, "SPACE")) 357 { 358 errors.add( new TestError(this, Severity.OTHER, tr("Property values start or end with white space"), 359 tr(s, key), MessageFormat.format(s, key), INVALID_SPACE, p) ); 360 withErrors.add(p, "SPACE"); 361 } 362 if( checkValues && value != null && !value.equals(entities.unescape(value)) && !withErrors.contains(p, "HTML")) 363 { 364 errors.add( new TestError(this, Severity.OTHER, tr("Property values contain HTML entity"), 365 tr(s, key), MessageFormat.format(s, key), INVALID_HTML, p) ); 366 withErrors.add(p, "HTML"); 367 } 368 if( checkValues && value != null && value.length() > 0 && presetsValueData != null) 369 { 370 List<String> values = presetsValueData.get(key); 371 if( values != null && !values.contains(prop.getValue()) && !withErrors.contains(p, "UPV")) 372 { 373 String i = marktr("Key ''{0}'' unknown."); 374 errors.add( new TestError(this, Severity.OTHER, tr("Unknown property values"), 375 tr(i, key), MessageFormat.format(i, key), INVALID_VALUE, p) ); 376 withErrors.add(p, "UPV"); 377 } 378 } 379 if( checkFixmes && value != null && value.length() > 0 ) 380 { 381 if( (value.contains("FIXME") || value.contains("check and delete") || key.contains("todo") || key.contains("fixme")) 382 && !withErrors.contains(p, "FIXME")) 383 { 384 errors.add( new TestError(this, Severity.OTHER, tr("FIXMES"), FIXME, p) ); 385 withErrors.add(p, "FIXME"); 386 } 387 } 388 } 389 } 390 391 @Override 392 public void startTest() 393 { 394 checkKeys = Main.pref.getBoolean(PREF_CHECK_KEYS, true); 395 if( isBeforeUpload ) 396 checkKeys = checkKeys && Main.pref.getBoolean(PREF_CHECK_KEYS_BEFORE_UPLOAD, true); 397 398 checkValues = Main.pref.getBoolean(PREF_CHECK_VALUES, true); 399 if( isBeforeUpload ) 400 checkValues = checkValues && Main.pref.getBoolean(PREF_CHECK_VALUES_BEFORE_UPLOAD, true); 401 402 checkComplex = Main.pref.getBoolean(PREF_CHECK_COMPLEX, true); 403 if( isBeforeUpload ) 404 checkComplex = checkValues && Main.pref.getBoolean(PREF_CHECK_COMPLEX_BEFORE_UPLOAD, true); 405 406 checkFixmes = Main.pref.getBoolean(PREF_CHECK_FIXMES, true); 407 if( isBeforeUpload ) 408 checkFixmes = checkFixmes && Main.pref.getBoolean(PREF_CHECK_FIXMES_BEFORE_UPLOAD, true); 409 410 checkPaint = Main.pref.getBoolean(PREF_CHECK_PAINT, true); 411 if( isBeforeUpload ) 412 checkPaint = checkPaint && Main.pref.getBoolean(PREF_CHECK_PAINT_BEFORE_UPLOAD, true); 413 } 414 415 @Override 416 public void visit(Collection<OsmPrimitive> selection) 417 { 418 if( checkKeys || checkValues || checkComplex) 419 super.visit(selection); 420 } 421 422 @Override 423 public void addGui(JPanel testPanel) 424 { 425 GBC a = GBC.eol(); 426 a.anchor = GBC.EAST; 427 428 testPanel.add( new JLabel(name), GBC.eol().insets(3,0,0,0) ); 429 430 prefCheckKeys = new JCheckBox(tr("Check property keys."), Main.pref.getBoolean(PREF_CHECK_KEYS, true)); 431 prefCheckKeys.setToolTipText(tr("Validate that property keys are valid checking against list of words.")); 432 testPanel.add(prefCheckKeys, GBC.std().insets(20,0,0,0)); 433 434 prefCheckKeysBeforeUpload = new JCheckBox(); 435 prefCheckKeysBeforeUpload.setSelected(Main.pref.getBoolean(PREF_CHECK_KEYS_BEFORE_UPLOAD, true)); 436 testPanel.add(prefCheckKeysBeforeUpload, a); 437 438 prefCheckComplex = new JCheckBox(tr("Use complex property checker."), Main.pref.getBoolean(PREF_CHECK_COMPLEX, true)); 439 prefCheckComplex.setToolTipText(tr("Validate property values and tags using complex rules.")); 440 testPanel.add(prefCheckComplex, GBC.std().insets(20,0,0,0)); 441 442 prefCheckComplexBeforeUpload = new JCheckBox(); 443 prefCheckComplexBeforeUpload.setSelected(Main.pref.getBoolean(PREF_CHECK_COMPLEX_BEFORE_UPLOAD, true)); 444 testPanel.add(prefCheckComplexBeforeUpload, a); 445 446 Sources = new JList(new DefaultListModel()); 447 448 String sources = Main.pref.get( PREF_SOURCES ); 449 if(sources != null && sources.length() > 0) 450 { 451 for(String source : sources.split(";")) 452 ((DefaultListModel)Sources.getModel()).addElement(source); 453 } 454 455 addSrcButton = new JButton(tr("Add")); 456 addSrcButton.addActionListener(new ActionListener(){ 457 public void actionPerformed(ActionEvent e) { 458 String source = JOptionPane.showInputDialog(Main.parent, tr("TagChecker source")); 459 if (source != null) 460 ((DefaultListModel)Sources.getModel()).addElement(source); 461 Sources.clearSelection(); 462 } 463 }); 464 465 editSrcButton = new JButton(tr("Edit")); 466 editSrcButton.addActionListener(new ActionListener(){ 467 public void actionPerformed(ActionEvent e) { 468 int row = Sources.getSelectedIndex(); 469 if(row == -1 && Sources.getModel().getSize() == 1) 470 { 471 Sources.setSelectedIndex(0); 472 row = 0; 473 } 474 if (row == -1) 475 { 476 if(Sources.getModel().getSize() == 0) 477 { 478 String source = JOptionPane.showInputDialog(Main.parent, tr("TagChecker source")); 479 if (source != null) 480 ((DefaultListModel)Sources.getModel()).addElement(source); 481 } 482 else 483 { 484 JOptionPane.showMessageDialog(Main.parent, tr("Please select the row to edit.")); 485 } 486 } 487 else { 488 String source = JOptionPane.showInputDialog(Main.parent, tr("TagChecker source"), Sources.getSelectedValue()); 489 if (source != null) 490 ((DefaultListModel)Sources.getModel()).setElementAt(source, row); 491 } 492 Sources.clearSelection(); 493 } 494 }); 495 496 deleteSrcButton = new JButton(tr("Delete")); 497 deleteSrcButton.addActionListener(new ActionListener(){ 498 public void actionPerformed(ActionEvent e) { 499 if (Sources.getSelectedIndex() == -1) 500 JOptionPane.showMessageDialog(Main.parent, tr("Please select the row to delete.")); 501 else { 502 ((DefaultListModel)Sources.getModel()).remove(Sources.getSelectedIndex()); 503 } 504 } 505 }); 506 Sources.setMinimumSize(new Dimension(300,50)); 507 Sources.setVisibleRowCount(3); 508 509 Sources.setToolTipText(tr("The sources (URL or filename) of spell check (see http://wiki.openstreetmap.org/index.php/User:JLS/speller) or tag checking data files.")); 510 addSrcButton.setToolTipText(tr("Add a new source to the list.")); 511 editSrcButton.setToolTipText(tr("Edit the selected source.")); 512 deleteSrcButton.setToolTipText(tr("Delete the selected source from the list.")); 513 514 testPanel.add(new JLabel(tr("Data sources")), GBC.eol().insets(23,0,0,0)); 515 testPanel.add(new JScrollPane(Sources), GBC.eol().insets(23,0,0,0).fill(GBC.HORIZONTAL)); 516 final JPanel buttonPanel = new JPanel(new GridBagLayout()); 517 testPanel.add(buttonPanel, GBC.eol().fill(GBC.HORIZONTAL)); 518 buttonPanel.add(addSrcButton, GBC.std().insets(0,5,0,0)); 519 buttonPanel.add(editSrcButton, GBC.std().insets(5,5,5,0)); 520 buttonPanel.add(deleteSrcButton, GBC.std().insets(0,5,0,0)); 521 522 ActionListener disableCheckActionListener = new ActionListener(){ 523 public void actionPerformed(ActionEvent e) { 524 handlePrefEnable(); 525 } 526 }; 527 prefCheckKeys.addActionListener(disableCheckActionListener); 528 prefCheckKeysBeforeUpload.addActionListener(disableCheckActionListener); 529 prefCheckComplex.addActionListener(disableCheckActionListener); 530 prefCheckComplexBeforeUpload.addActionListener(disableCheckActionListener); 531 532 handlePrefEnable(); 533 534 prefCheckValues = new JCheckBox(tr("Check property values."), Main.pref.getBoolean(PREF_CHECK_VALUES, true)); 535 prefCheckValues.setToolTipText(tr("Validate that property values are valid checking against presets.")); 536 testPanel.add(prefCheckValues, GBC.std().insets(20,0,0,0)); 537 538 prefCheckValuesBeforeUpload = new JCheckBox(); 539 prefCheckValuesBeforeUpload.setSelected(Main.pref.getBoolean(PREF_CHECK_VALUES_BEFORE_UPLOAD, true)); 540 testPanel.add(prefCheckValuesBeforeUpload, a); 541 542 prefCheckFixmes = new JCheckBox(tr("Check for FIXMES."), Main.pref.getBoolean(PREF_CHECK_FIXMES, true)); 543 prefCheckFixmes.setToolTipText(tr("Looks for nodes or ways with FIXME in any property value.")); 544 testPanel.add(prefCheckFixmes, GBC.std().insets(20,0,0,0)); 545 546 prefCheckFixmesBeforeUpload = new JCheckBox(); 547 prefCheckFixmesBeforeUpload.setSelected(Main.pref.getBoolean(PREF_CHECK_FIXMES_BEFORE_UPLOAD, true)); 548 testPanel.add(prefCheckFixmesBeforeUpload, a); 549 550 prefCheckPaint = new JCheckBox(tr("Check for paint notes."), Main.pref.getBoolean(PREF_CHECK_PAINT, true)); 551 prefCheckPaint.setToolTipText(tr("Check if map paining found data errors.")); 552 testPanel.add(prefCheckPaint, GBC.std().insets(20,0,0,0)); 553 554 prefCheckPaintBeforeUpload = new JCheckBox(); 555 prefCheckPaintBeforeUpload.setSelected(Main.pref.getBoolean(PREF_CHECK_PAINT_BEFORE_UPLOAD, true)); 556 testPanel.add(prefCheckPaintBeforeUpload, a); 557 558 prefUseDataFile = new JCheckBox(tr("Use default data file."), Main.pref.getBoolean(PREF_USE_DATA_FILE, true)); 559 prefUseDataFile.setToolTipText(tr("Use the default data file (recommended).")); 560 testPanel.add(prefUseDataFile, GBC.eol().insets(20,0,0,0)); 561 562 prefUseSpellFile = new JCheckBox(tr("Use default spellcheck file."), Main.pref.getBoolean(PREF_USE_SPELL_FILE, true)); 563 prefUseSpellFile.setToolTipText(tr("Use the default spellcheck file (recommended).")); 564 testPanel.add(prefUseSpellFile, GBC.eol().insets(20,0,0,0)); 565 } 566 567 public void handlePrefEnable() 568 { 569 boolean selected = prefCheckKeys.isSelected() || prefCheckKeysBeforeUpload.isSelected() 570 || prefCheckComplex.isSelected() || prefCheckComplexBeforeUpload.isSelected(); 571 Sources.setEnabled( selected ); 572 addSrcButton.setEnabled(selected); 573 editSrcButton.setEnabled(selected); 574 deleteSrcButton.setEnabled(selected); 575 } 576 577 @Override 578 public boolean ok() 579 { 580 enabled = prefCheckKeys.isSelected() || prefCheckValues.isSelected() || prefCheckComplex.isSelected() || prefCheckFixmes.isSelected(); 581 testBeforeUpload = prefCheckKeysBeforeUpload.isSelected() || prefCheckValuesBeforeUpload.isSelected() 582 || prefCheckFixmesBeforeUpload.isSelected() || prefCheckComplexBeforeUpload.isSelected(); 583 584 Main.pref.put(PREF_CHECK_VALUES, prefCheckValues.isSelected()); 585 Main.pref.put(PREF_CHECK_COMPLEX, prefCheckComplex.isSelected()); 586 Main.pref.put(PREF_CHECK_KEYS, prefCheckKeys.isSelected()); 587 Main.pref.put(PREF_CHECK_FIXMES, prefCheckFixmes.isSelected()); 588 Main.pref.put(PREF_CHECK_PAINT, prefCheckPaint.isSelected()); 589 Main.pref.put(PREF_CHECK_VALUES_BEFORE_UPLOAD, prefCheckValuesBeforeUpload.isSelected()); 590 Main.pref.put(PREF_CHECK_COMPLEX_BEFORE_UPLOAD, prefCheckComplexBeforeUpload.isSelected()); 591 Main.pref.put(PREF_CHECK_KEYS_BEFORE_UPLOAD, prefCheckKeysBeforeUpload.isSelected()); 592 Main.pref.put(PREF_CHECK_FIXMES_BEFORE_UPLOAD, prefCheckFixmesBeforeUpload.isSelected()); 593 Main.pref.put(PREF_CHECK_PAINT_BEFORE_UPLOAD, prefCheckPaintBeforeUpload.isSelected()); 594 Main.pref.put(PREF_USE_DATA_FILE, prefUseDataFile.isSelected()); 595 Main.pref.put(PREF_USE_SPELL_FILE, prefUseSpellFile.isSelected()); 596 String sources = ""; 597 if( Sources.getModel().getSize() > 0 ) 598 { 599 String sb = ""; 600 for (int i = 0; i < Sources.getModel().getSize(); ++i) 601 sb += ";"+Sources.getModel().getElementAt(i); 602 sources = sb.substring(1); 603 } 604 if(sources.length() == 0) 605 sources = null; 606 return Main.pref.put(PREF_SOURCES, sources); 607 } 608 609 @Override 610 public Command fixError(TestError testError) 611 { 612 List<Command> commands = new ArrayList<Command>(50); 613 614 int i = -1; 615 List<? extends OsmPrimitive> primitives = testError.getPrimitives(); 616 for(OsmPrimitive p : primitives ) 617 { 618 i++; 619 Map<String, String> tags = p.keys; 620 if( tags == null || tags.size() == 0 ) 621 continue; 622 623 for(Entry<String, String> prop: tags.entrySet() ) 624 { 625 String key = prop.getKey(); 626 String value = prop.getValue(); 627 if( value == null || value.trim().length() == 0 ) 628 commands.add( new ChangePropertyCommand(Collections.singleton(primitives.get(i)), key, null) ); 629 else if(value.startsWith(" ") || value.endsWith(" ")) 630 commands.add( new ChangePropertyCommand(Collections.singleton(primitives.get(i)), key, value.trim()) ); 631 else if(key.startsWith(" ") || key.endsWith(" ")) 632 commands.add( new ChangePropertyKeyCommand(Collections.singleton(primitives.get(i)), key, key.trim()) ); 633 else 634 { 635 String evalue = entities.unescape(value); 636 if(!evalue.equals(value)) 637 commands.add( new ChangePropertyCommand(Collections.singleton(primitives.get(i)), key, evalue) ); 638 else 639 { 640 String replacementKey = spellCheckKeyData.get(key); 641 if( replacementKey != null ) 642 { 643 commands.add( new ChangePropertyKeyCommand(Collections.singleton(primitives.get(i)), 644 key, replacementKey) ); 645 } 646 } 647 } 648 } 649 } 650 651 if( commands.size() == 0 ) 652 return null; 653 else if( commands.size() == 1 ) 654 return commands.get(0); 655 else 656 return new SequenceCommand(tr("Fix properties"), commands); 657 } 658 659 @Override 660 public boolean isFixable(TestError testError) 661 { 662 if( testError.getTester() instanceof TagChecker) 663 { 664 int code = testError.getCode(); 665 return code == INVALID_KEY || code == EMPTY_VALUES || code == INVALID_SPACE || code == INVALID_KEY_SPACE || code == INVALID_HTML; 666 } 667 668 return false; 669 } 670 671 private static class CheckerData { 672 private String description; 673 private List<CheckerElement> data = new ArrayList<CheckerElement>(); 674 private Integer type = 0; 675 private Integer code; 676 protected Severity severity; 677 protected static int NODE = 1; 678 protected static int WAY = 2; 679 protected static int RELATION = 3; 680 protected static int ALL = 4; 681 protected static int TAG_CHECK_ERROR = 1250; 682 protected static int TAG_CHECK_WARN = 1260; 683 protected static int TAG_CHECK_INFO = 1270; 684 685 private class CheckerElement { 686 public Object tag; 687 public Object value; 688 public Boolean noMatch; 689 public Boolean tagAll = false; 690 public Boolean valueAll = false; 691 public Boolean valueBool = false; 692 private Pattern getPattern(String str) throws IllegalStateException, PatternSyntaxException 693 { 694 if(str.endsWith("/i")) 695 return Pattern.compile(str.substring(1,str.length()-2), Pattern.CASE_INSENSITIVE); 696 else if(str.endsWith("/")) 697 return Pattern.compile(str.substring(1,str.length()-1)); 698 throw new IllegalStateException(); 699 } 700 public CheckerElement(String exp) throws IllegalStateException, PatternSyntaxException 701 { 702 Matcher m = Pattern.compile("(.+)([!=]=)(.+)").matcher(exp); 703 m.matches(); 704 705 String n = m.group(1).trim(); 706 if(n.equals("*")) 707 tagAll = true; 708 else 709 tag = n.startsWith("/") ? getPattern(n) : n; 710 noMatch = m.group(2).equals("!="); 711 n = m.group(3).trim(); 712 if(n.equals("*")) 713 valueAll = true; 714 else if(n.equals("BOOLEAN_TRUE")) 715 { 716 valueBool = true; 717 value = OsmUtils.trueval; 718 } 719 else if(n.equals("BOOLEAN_FALSE")) 720 { 721 valueBool = true; 722 value = OsmUtils.falseval; 723 } 724 else 725 value = n.startsWith("/") ? getPattern(n) : n; 726 } 727 public Boolean match(OsmPrimitive osm) 728 { 729 for(Entry<String, String> prop: osm.keys.entrySet()) 730 { 731 String key = prop.getKey(); 732 String val = valueBool ? OsmUtils.getNamedOsmBoolean(prop.getValue()) : prop.getValue(); 733 if((tagAll || (tag instanceof Pattern ? ((Pattern)tag).matcher(key).matches() : key.equals(tag))) 734 && (valueAll || (value instanceof Pattern ? ((Pattern)value).matcher(val).matches() : val.equals(value)))) 735 return !noMatch; 736 } 737 return noMatch; 738 } 739 }; 740 741 public String getData(String str) 742 { 743 Matcher m = Pattern.compile(" *# *([^#]+) *$").matcher(str); 744 str = m.replaceFirst("").trim(); 745 try 746 { 747 description = m.group(1); 748 if(description != null && description.length() == 0) 749 description = null; 750 } 751 catch (IllegalStateException e) 752 { 753 description = null; 754 } 755 String[] n = str.split(" *: *", 3); 756 if(n[0].equals("way")) 757 type = WAY; 758 else if(n[0].equals("node")) 759 type = NODE; 760 else if(n[0].equals("relation")) 761 type = RELATION; 762 else if(n[0].equals("*")) 763 type = ALL; 764 if(type == 0 || n.length != 3) 765 return tr("Could not find element type"); 766 if(n[1].equals("W")) 767 { 768 severity = Severity.WARNING; 769 code = TAG_CHECK_WARN; 770 } 771 else if(n[1].equals("E")) 772 { 773 severity = Severity.ERROR; 774 code = TAG_CHECK_ERROR; 775 } 776 else if(n[1].equals("I")) 777 { 778 severity = Severity.OTHER; 779 code = TAG_CHECK_INFO; 780 } 781 else 782 return tr("Could not find warning level"); 783 for(String exp: n[2].split(" *&& *")) 784 { 785 try 786 { 787 data.add(new CheckerElement(exp)); 788 } 789 catch(IllegalStateException e) 790 { 791 return tr("Illegal expression ''{0}''", exp); 792 } 793 catch(PatternSyntaxException e) 794 { 795 return tr("Illegal regular expression ''{0}''", exp); 796 } 797 } 798 return null; 799 } 800 public Boolean match(OsmPrimitive osm) 801 { 802 if(osm.keys == null || (type == NODE && !(osm instanceof Node)) 803 || (type == RELATION && !(osm instanceof Relation)) || (type == WAY && !(osm instanceof Way))) 804 return false; 805 for(CheckerElement ce : data) 806 { 807 if(!ce.match(osm)) 808 return false; 809 } 810 return true; 811 } 812 public String getDescription() 813 { 814 return tr(description); 815 } 816 public String getDescriptionOrig() 817 { 818 return description; 819 } 820 public Severity getSeverity() 821 { 822 return severity; 823 } 824 public int getCode() 825 { 826 return code + type; 827 } 828 } 829 829 } -
applications/editors/josm/plugins/validator/src/org/openstreetmap/josm/plugins/validator/tests/UnconnectedWays.java
r10774 r12778 25 25 public class UnconnectedWays extends Test 26 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 27 protected static int UNCONNECTED_WAYS = 1301; 28 protected static final String PREFIX = PreferenceEditor.PREFIX + "." + UnconnectedWays.class.getSimpleName(); 29 30 Set<MyWaySegment> ways; 31 Set<Node> endnodes; // nodes at end of way 32 Set<Node> endnodes_highway; // nodes at end of way 33 Set<Node> middlenodes; // nodes in middle of way 34 Set<Node> othernodes; // nodes appearing at least twice 35 36 double mindist; 37 double minmiddledist; 38 /** 39 * Constructor 40 */ 41 public UnconnectedWays() 42 { 43 super(tr("Unconnected ways."), 44 tr("This test checks if a way has an endpoint very near to another way.")); 45 } 46 47 @Override 48 public void startTest() 49 { 50 ways = new HashSet<MyWaySegment>(); 51 endnodes = new HashSet<Node>(); 52 endnodes_highway = new HashSet<Node>(); 53 middlenodes = new HashSet<Node>(); 54 othernodes = new HashSet<Node>(); 55 mindist = Main.pref.getDouble(PREFIX + ".node_way_distance", 10.0)/6378135.0; 56 minmiddledist = Main.pref.getDouble(PREFIX + ".way_way_distance", 0.0)/6378135.0; 57 } 58 59 @Override 60 public void endTest() 61 { 62 Map<Node, Way> map = new HashMap<Node, Way>(); 63 for(Node en : endnodes_highway) 64 { 65 for(MyWaySegment s : ways) 66 { 67 if(s.highway && s.nearby(en, mindist)) 68 map.put(en, s.w); 69 } 70 } 71 if(map.size() > 0) 72 { 73 for(Map.Entry<Node, Way> error : map.entrySet()) 74 { 75 errors.add(new TestError(this, Severity.WARNING, 76 tr("Way end node near other highway"), UNCONNECTED_WAYS, 77 Arrays.asList(error.getKey(), error.getValue()))); 78 } 79 } 80 map.clear(); 81 for(Node en : endnodes_highway) 82 { 83 for(MyWaySegment s : ways) 84 { 85 if(!s.highway && s.nearby(en, mindist)) 86 map.put(en, s.w); 87 } 88 } 89 for(Node en : endnodes) 90 { 91 for(MyWaySegment s : ways) 92 { 93 if(s.nearby(en, mindist)) 94 map.put(en, s.w); 95 } 96 } 97 if(map.size() > 0) 98 { 99 for(Map.Entry<Node, Way> error : map.entrySet()) 100 { 101 errors.add(new TestError(this, Severity.WARNING, 102 tr("Way end node near other way"), UNCONNECTED_WAYS, 103 Arrays.asList(error.getKey(), error.getValue()))); 104 } 105 } 106 /* the following two use a shorter distance */ 107 if(minmiddledist > 0.0) 108 { 109 map.clear(); 110 for(Node en : middlenodes) 111 { 112 for(MyWaySegment s : ways) 113 { 114 if(s.nearby(en, minmiddledist)) 115 map.put(en, s.w); 116 } 117 } 118 if(map.size() > 0) 119 { 120 for(Map.Entry<Node, Way> error : map.entrySet()) 121 { 122 errors.add(new TestError(this, Severity.OTHER, 123 tr("Way node near other way"), UNCONNECTED_WAYS, 124 Arrays.asList(error.getKey(), error.getValue()))); 125 } 126 } 127 map.clear(); 128 for(Node en : othernodes) 129 { 130 for(MyWaySegment s : ways) 131 { 132 if(s.nearby(en, minmiddledist)) 133 map.put(en, s.w); 134 } 135 } 136 if(map.size() > 0) 137 { 138 for(Map.Entry<Node, Way> error : map.entrySet()) 139 { 140 errors.add(new TestError(this, Severity.OTHER, 141 tr("Connected way end node near other way"), UNCONNECTED_WAYS, 142 Arrays.asList(error.getKey(), error.getValue()))); 143 } 144 } 145 } 146 ways = null; 147 endnodes = null; 148 } 149 150 private class MyWaySegment 151 { 152 private Line2D line; 153 public Way w; 154 public Boolean highway; 155 156 public MyWaySegment(Way w, Node n1, Node n2) 157 { 158 this.w = w; 159 this.highway = w.get("highway") != null || w.get("railway") != null; 160 line = new Line2D.Double(n1.eastNorth.east(), n1.eastNorth.north(), 161 n2.eastNorth.east(), n2.eastNorth.north()); 162 } 163 164 public boolean nearby(Node n, double dist) 165 { 166 return !w.nodes.contains(n) 167 && line.ptSegDist(n.eastNorth.east(), n.eastNorth.north()) < dist; 168 } 169 } 170 171 @Override 172 public void visit(Way w) 173 { 174 if( w.deleted || w.incomplete ) 175 return; 176 int size = w.nodes.size(); 177 if(size < 2) 178 return; 179 for(int i = 1; i < size; ++i) 180 { 181 if(i < size-1) 182 addNode(w.nodes.get(i), middlenodes); 183 ways.add(new MyWaySegment(w, w.nodes.get(i-1), w.nodes.get(i))); 184 } 185 Set<Node> set = endnodes; 186 if(w.get("highway") != null || w.get("railway") != null) 187 set = endnodes_highway; 188 addNode(w.nodes.get(0), set); 189 addNode(w.nodes.get(size-1), set); 190 } 191 private void addNode(Node n, Set<Node> s) 192 { 193 Boolean m = middlenodes.contains(n); 194 Boolean e = endnodes.contains(n); 195 Boolean eh = endnodes_highway.contains(n); 196 Boolean o = othernodes.contains(n); 197 if(!m && !e && !o && !eh) 198 s.add(n); 199 else if(!o) 200 { 201 othernodes.add(n); 202 if(e) 203 endnodes.remove(n); 204 else if(eh) 205 endnodes_highway.remove(n); 206 else 207 middlenodes.remove(n); 208 } 209 } 210 210 } -
applications/editors/josm/plugins/validator/src/org/openstreetmap/josm/plugins/validator/tests/UntaggedNode.java
r10774 r12778 22 22 public class UntaggedNode extends Test 23 23 { 24 24 protected static int UNTAGGED_NODE = 201; 25 25 26 27 26 /** Bag of all nodes */ 27 Set<Node> emptyNodes; 28 28 29 30 31 32 33 34 35 36 29 /** 30 * Constructor 31 */ 32 public UntaggedNode() 33 { 34 super(tr("Untagged nodes."), 35 tr("This test checks for untagged nodes that are not part of any way.")); 36 } 37 37 38 39 40 41 42 38 @Override 39 public void startTest() 40 { 41 emptyNodes = new HashSet<Node>(100); 42 } 43 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 44 @Override 45 public void visit(Collection<OsmPrimitive> selection) 46 { 47 // If there is a partial selection, it may be false positives if a 48 // node is selected, but not the container way. So, in this 49 // case, we must visit all ways, selected or not. 50 if (partialSelection) { 51 for (OsmPrimitive p : selection) { 52 if (!p.deleted && !p.incomplete && p instanceof Node) { 53 p.visit(this); 54 } 55 } 56 for (Way w : Main.ds.ways) { 57 visit(w); 58 } 59 } else { 60 for (OsmPrimitive p : selection) { 61 if (!p.deleted && !p.incomplete) { 62 p.visit(this); 63 } 64 } 65 } 66 } 67 67 68 69 70 71 72 73 68 @Override 69 public void visit(Node n) 70 { 71 if(!n.incomplete && !n.deleted && !n.tagged) 72 emptyNodes.add(n); 73 } 74 74 75 76 77 78 79 80 81 75 @Override 76 public void visit(Way w) 77 { 78 for (Node n : w.nodes) { 79 emptyNodes.remove(n); 80 } 81 } 82 82 83 84 85 86 87 88 89 90 91 83 @Override 84 public void endTest() 85 { 86 for(Node node : emptyNodes) 87 { 88 errors.add( new TestError(this, Severity.OTHER, tr("Untagged and unconnected nodes"), UNTAGGED_NODE, node) ); 89 } 90 emptyNodes = null; 91 } 92 92 93 94 95 96 97 93 @Override 94 public Command fixError(TestError testError) 95 { 96 return DeleteCommand.delete(testError.getPrimitives()); 97 } 98 98 99 100 101 102 103 99 @Override 100 public boolean isFixable(TestError testError) 101 { 102 return (testError.getTester() instanceof UntaggedNode); 103 } 104 104 } -
applications/editors/josm/plugins/validator/src/org/openstreetmap/josm/plugins/validator/tests/UntaggedWay.java
r10774 r12778 21 21 public class UntaggedWay extends Test 22 22 { 23 24 25 26 27 28 29 30 23 /** Empty way error */ 24 protected static final int EMPTY_WAY = 301; 25 /** Untagged way error */ 26 protected static final int UNTAGGED_WAY = 302; 27 /** Unnamed way error */ 28 protected static final int UNNAMED_WAY = 303; 29 /** One node way error */ 30 protected static final int ONE_NODE_WAY = 304; 31 31 32 33 34 35 36 37 38 39 40 41 42 43 32 /** Ways that must have a name */ 33 public static final Set<String> NAMED_WAYS = new HashSet<String>(); 34 static 35 { 36 NAMED_WAYS.add( "motorway" ); 37 NAMED_WAYS.add( "trunk" ); 38 NAMED_WAYS.add( "primary" ); 39 NAMED_WAYS.add( "secondary" ); 40 NAMED_WAYS.add( "tertiary" ); 41 NAMED_WAYS.add( "residential" ); 42 NAMED_WAYS.add( "pedestrian" ); ; 43 } 44 44 45 46 47 48 49 50 51 52 45 /** 46 * Constructor 47 */ 48 public UntaggedWay() 49 { 50 super(tr("Untagged, empty, and one node ways."), 51 tr("This test checks for untagged, empty and one node ways.")); 52 } 53 53 54 55 56 57 54 @Override 55 public void visit(Way w) 56 { 57 if (w.deleted || w.incomplete) return; 58 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 59 Map<String, String> tags = w.keys; 60 if( tags != null ) 61 { 62 String highway = tags.get("highway"); 63 if(highway != null && NAMED_WAYS.contains(highway)) 64 { 65 if( !tags.containsKey("name") && !tags.containsKey("ref") ) 66 { 67 boolean hasName = false; 68 for( String key : w.keySet()) 69 { 70 hasName = key.startsWith("name:") || key.endsWith("_name") || key.endsWith("_ref"); 71 if( hasName ) 72 break; 73 } 74 74 75 76 77 78 79 75 if( !hasName) 76 errors.add( new TestError(this, Severity.WARNING, tr("Unnamed ways"), UNNAMED_WAY, w) ); 77 } 78 } 79 } 80 80 81 82 83 84 81 if(!w.tagged) 82 { 83 errors.add( new TestError(this, Severity.WARNING, tr("Untagged ways"), UNTAGGED_WAY, w) ); 84 } 85 85 86 87 88 89 90 91 92 93 86 if( w.nodes.size() == 0 ) 87 { 88 errors.add( new TestError(this, Severity.ERROR, tr("Empty ways"), EMPTY_WAY, w) ); 89 } 90 else if( w.nodes.size() == 1 ) 91 { 92 errors.add( new TestError(this, Severity.ERROR, tr("One node ways"), ONE_NODE_WAY, w) ); 93 } 94 94 95 95 } 96 96 97 98 99 100 101 102 103 104 97 @Override 98 public boolean isFixable(TestError testError) 99 { 100 if( testError.getTester() instanceof UntaggedWay ) 101 { 102 return testError.getCode() == EMPTY_WAY 103 || testError.getCode() == ONE_NODE_WAY; 104 } 105 105 106 107 106 return false; 107 } 108 108 109 110 111 112 113 109 @Override 110 public Command fixError(TestError testError) 111 { 112 return DeleteCommand.delete(testError.getPrimitives()); 113 } 114 114 } -
applications/editors/josm/plugins/validator/src/org/openstreetmap/josm/plugins/validator/tests/WronglyOrderedWays.java
r11530 r12778 19 19 */ 20 20 public class WronglyOrderedWays extends Test { 21 22 23 21 protected static int WRONGLY_ORDERED_COAST = 1001; 22 protected static int WRONGLY_ORDERED_WATER = 1002; 23 protected static int WRONGLY_ORDERED_LAND = 1003; 24 24 25 26 25 /** The already detected errors */ 26 Bag<Way, Way> _errorWays; 27 27 28 29 30 31 32 33 34 35 28 /** 29 * Constructor 30 */ 31 public WronglyOrderedWays() 32 { 33 super(tr("Wrongly Ordered Ways."), 34 tr("This test checks the direction of water, land and coastline ways.")); 35 } 36 36 37 38 39 40 41 37 @Override 38 public void startTest() 39 { 40 _errorWays = new Bag<Way, Way>(); 41 } 42 42 43 44 45 46 47 43 @Override 44 public void endTest() 45 { 46 _errorWays = null; 47 } 48 48 49 50 51 52 53 49 @Override 50 public void visit(Way w) 51 { 52 String errortype = ""; 53 int type; 54 54 55 56 55 if( w.deleted || w.incomplete ) 56 return; 57 57 58 59 60 58 String natural = w.get("natural"); 59 if( natural == null) 60 return; 61 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 62 if( natural.equals("coastline") ) 63 { 64 errortype = tr("Reversed coastline: land not on left side"); 65 type= WRONGLY_ORDERED_COAST; 66 } 67 else if(natural.equals("water") ) 68 { 69 errortype = tr("Reversed water: land not on left side"); 70 type= WRONGLY_ORDERED_WATER; 71 } 72 else if( natural.equals("land") ) 73 { 74 errortype = tr("Reversed land: land not on left side"); 75 type= WRONGLY_ORDERED_LAND; 76 } 77 else 78 return; 79 79 80 80 81 82 83 84 85 86 87 88 81 /** 82 * Test the directionality of the way 83 * 84 * Assuming a closed non-looping way, compute twice the area 85 * of the polygon using the formula 2*a = sum (Xn * Yn+1 - Xn+1 * Yn) 86 * If the area is negative the way is ordered in a clockwise direction 87 * 88 */ 89 89 90 91 92 90 if(w.nodes.get(0) == w.nodes.get(w.nodes.size()-1)) 91 { 92 double area2 = 0; 93 93 94 95 96 97 98 94 for (int node = 1; node < w.nodes.size(); node++) 95 { 96 area2 += (w.nodes.get(node-1).coor.lon() * w.nodes.get(node).coor.lat() 97 - w.nodes.get(node).coor.lon() * w.nodes.get(node-1).coor.lat()); 98 } 99 99 100 101 102 103 104 105 106 107 108 109 100 if(((natural.equals("coastline") || natural.equals("land")) && area2 < 0.) 101 || (natural.equals("water") && area2 > 0.)) 102 { 103 List<OsmPrimitive> primitives = new ArrayList<OsmPrimitive>(); 104 primitives.add(w); 105 errors.add( new TestError(this, Severity.WARNING, errortype, type, primitives) ); 106 _errorWays.add(w,w); 107 } 108 } 109 } 110 110 } -
applications/editors/josm/plugins/validator/src/org/openstreetmap/josm/plugins/validator/util/AgregatePrimitivesVisitor.java
r12777 r12778 12 12 * <p> 13 13 * The primitives are sorted according to their type: first nodes, then ways. 14 * 14 * 15 15 * @author frsantos 16 16 */ 17 17 public class AgregatePrimitivesVisitor implements Visitor 18 18 { 19 20 19 /** Aggregated data */ 20 Collection<OsmPrimitive> aggregatedData; 21 21 22 23 24 25 public AgregatePrimitivesVisitor() 26 27 28 22 /** 23 * Constructor 24 */ 25 public AgregatePrimitivesVisitor() 26 { 27 aggregatedData = new LinkedList<OsmPrimitive>(); 28 } 29 29 30 /** 31 * Visits a collection of primitives 32 * @param data The collection of primitives 33 * @return The aggregated primitives 34 */ 35 public Collection<OsmPrimitive> visit(Collection<OsmPrimitive> data) 36 { 37 for (OsmPrimitive osm : data) 38 { 39 osm.visit(this); 40 } 41 42 return aggregatedData; 43 } 30 /** 31 * Visits a collection of primitives 32 * @param data The collection of primitives 33 * @return The aggregated primitives 34 */ 35 public Collection<OsmPrimitive> visit(Collection<OsmPrimitive> data) 36 { 37 for (OsmPrimitive osm : data) 38 { 39 osm.visit(this); 40 } 44 41 45 public void visit(Node n) 46 { 47 if(!aggregatedData.contains(n)) 48 aggregatedData.add(n); 49 } 42 return aggregatedData; 43 } 50 44 51 public void visit(Way w) 52 { 53 if(!aggregatedData.contains(w)) 54 { 55 aggregatedData.add(w); 56 for (Node n : w.nodes) 57 visit(n); 58 } 59 } 45 public void visit(Node n) 46 { 47 if(!aggregatedData.contains(n)) 48 aggregatedData.add(n); 49 } 60 50 61 public void visit(Relation r) { 62 if (!aggregatedData.contains(r)) { 63 aggregatedData.add(r); 64 for (RelationMember m : r.members) { 65 m.member.visit(this); 66 } 67 } 68 } 51 public void visit(Way w) 52 { 53 if(!aggregatedData.contains(w)) 54 { 55 aggregatedData.add(w); 56 for (Node n : w.nodes) 57 visit(n); 58 } 59 } 60 61 public void visit(Relation r) { 62 if (!aggregatedData.contains(r)) { 63 aggregatedData.add(r); 64 for (RelationMember m : r.members) { 65 m.member.visit(this); 66 } 67 } 68 } 69 69 } -
applications/editors/josm/plugins/validator/src/org/openstreetmap/josm/plugins/validator/util/Bag.java
r2453 r12778 6 6 7 7 /** 8 * 8 * 9 9 * A very simple bag to store multiple occurences of a same key. 10 10 * <p> 11 11 * The bag will keep, for each key, a list of values. 12 * 12 * 13 13 * @author frsantos 14 14 * … … 16 16 * @param <V> The value class 17 17 */ 18 public class Bag<K,V> extends HashMap<K, List<V>> 18 public class Bag<K,V> extends HashMap<K, List<V>> 19 19 { 20 20 /** Serializable ID */ … … 22 22 23 23 /** 24 25 26 27 28 public List<V> get(K key) 29 30 31 24 * Returns the list of elements with the same key 25 * @param key The key to obtain the elements 26 * @return the list of elements with the same key 27 */ 28 public List<V> get(K key) 29 { 30 return super.get(key); 31 } 32 32 33 34 35 36 37 38 public void add(K key, V value) 39 40 41 42 43 44 45 46 47 33 /** 34 * Adds an element to the bag 35 * @param key The key of the element 36 * @param value The element to add 37 */ 38 public void add(K key, V value) 39 { 40 List<V> values = get(key); 41 if( values == null ) 42 { 43 values = new ArrayList<V>(); 44 put(key, values); 45 } 46 values.add(value); 47 } 48 48 49 50 51 52 public Bag() 53 54 55 49 /** 50 * Constructor 51 */ 52 public Bag() 53 { 54 super(); 55 } 56 56 57 58 59 * 60 61 62 public Bag(int initialCapacity) 63 64 65 57 /** 58 * Constructor 59 * 60 * @param initialCapacity The initial capacity 61 */ 62 public Bag(int initialCapacity) 63 { 64 super(initialCapacity); 65 } 66 66 67 68 69 70 71 72 73 74 75 76 77 67 /** 68 * Returns true if the bag contains a value for a key 69 * @param key The key 70 * @param value The value 71 * @return true if the key contains the value 72 */ 73 public boolean contains(K key, V value) 74 { 75 List<V> values = get(key); 76 return (values == null) ? false : values.contains(value); 77 } 78 78 } -
applications/editors/josm/plugins/validator/src/org/openstreetmap/josm/plugins/validator/util/Entities.java
r10532 r12778 6 6 * (the "License"); you may not use this file except in compliance with 7 7 * the License. You may obtain a copy of the License at 8 * 8 * 9 9 * http://www.apache.org/licenses/LICENSE-2.0 10 * 10 * 11 11 * Unless required by applicable law or agreed to in writing, software 12 12 * distributed under the License is distributed on an "AS IS" BASIS, -
applications/editors/josm/plugins/validator/src/org/openstreetmap/josm/plugins/validator/util/MultipleNameVisitor.java
r9598 r12778 15 15 /** 16 16 * Able to create a name and an icon for a collection of elements. 17 * 17 * 18 18 * @author frsantos 19 19 */ 20 public class MultipleNameVisitor extends NameVisitor 20 public class MultipleNameVisitor extends NameVisitor 21 21 { 22 /** The class name of the combined primitives */ 23 String multipleClassname; 24 /* name to be displayed */ 25 String displayName; 26 /** Size of the collection */ 27 int size; 28 29 /** 30 * Visits a collection of primitives 31 * @param data The collection of primitives 32 */ 33 public void visit(Collection<? extends OsmPrimitive> data) 34 { 35 String multipleName = null; 36 String multiplePluralClassname = null; 37 String firstName = null; 38 boolean initializedname = false; 39 size = data.size(); 22 /** The class name of the combined primitives */ 23 String multipleClassname; 24 /* name to be displayed */ 25 String displayName; 26 /** Size of the collection */ 27 int size; 40 28 41 multipleClassname = null; 42 for (OsmPrimitive osm : data) 43 { 44 String name = osm.get("name"); 45 if(name == null) name = osm.get("ref"); 46 if(!initializedname) 47 { 48 multipleName = name; initializedname = true; 49 } 50 else if(multipleName != null && (name == null || !name.equals(multipleName))) 51 { 52 multipleName = null; 53 } 29 /** 30 * Visits a collection of primitives 31 * @param data The collection of primitives 32 */ 33 public void visit(Collection<? extends OsmPrimitive> data) 34 { 35 String multipleName = null; 36 String multiplePluralClassname = null; 37 String firstName = null; 38 boolean initializedname = false; 39 size = data.size(); 54 40 55 if(firstName == null && name != null) 56 firstName = name; 57 osm.visit(this); 58 if (multipleClassname == null) 59 { 60 multipleClassname = className; 61 multiplePluralClassname = classNamePlural; 62 } 63 else if (!multipleClassname.equals(className)) 64 { 65 multipleClassname = "object"; 66 multiplePluralClassname = trn("object", "objects", 2); 67 } 68 } 41 multipleClassname = null; 42 for (OsmPrimitive osm : data) 43 { 44 String name = osm.get("name"); 45 if(name == null) name = osm.get("ref"); 46 if(!initializedname) 47 { 48 multipleName = name; initializedname = true; 49 } 50 else if(multipleName != null && (name == null || !name.equals(multipleName))) 51 { 52 multipleName = null; 53 } 69 54 70 if( size == 1 ) 71 displayName = name; 72 else if(multipleName != null) 73 displayName = size + " " + trn(multipleClassname, multiplePluralClassname, size) + ": " + multipleName; 74 else if(firstName != null) 75 displayName = size + " " + trn(multipleClassname, multiplePluralClassname, size) + ": " + tr("{0}, ...", firstName); 76 else 77 displayName = size + " " + trn(multipleClassname, multiplePluralClassname, size); 78 } 55 if(firstName == null && name != null) 56 firstName = name; 57 osm.visit(this); 58 if (multipleClassname == null) 59 { 60 multipleClassname = className; 61 multiplePluralClassname = classNamePlural; 62 } 63 else if (!multipleClassname.equals(className)) 64 { 65 multipleClassname = "object"; 66 multiplePluralClassname = trn("object", "objects", 2); 67 } 68 } 79 69 80 @Override 81 public JLabel toLabel() 82 { 83 return new JLabel(getText(), getIcon(), JLabel.HORIZONTAL); 84 } 70 if( size == 1 ) 71 displayName = name; 72 else if(multipleName != null) 73 displayName = size + " " + trn(multipleClassname, multiplePluralClassname, size) + ": " + multipleName; 74 else if(firstName != null) 75 displayName = size + " " + trn(multipleClassname, multiplePluralClassname, size) + ": " + tr("{0}, ...", firstName); 76 else 77 displayName = size + " " + trn(multipleClassname, multiplePluralClassname, size); 78 } 85 79 86 /** 87 * Gets the name of the items 88 * @return the name of the items 89 */ 90 public String getText() 91 { 92 return displayName; 93 } 80 @Override 81 public JLabel toLabel() 82 { 83 return new JLabel(getText(), getIcon(), JLabel.HORIZONTAL); 84 } 94 85 95 /** 96 * Gets the icon of the items 97 * @return the icon of the items 98 */ 99 public Icon getIcon() 100 { 101 if( size == 1 ) 102 return icon; 103 else 104 return ImageProvider.get("data", multipleClassname); 105 } 86 /** 87 * Gets the name of the items 88 * @return the name of the items 89 */ 90 public String getText() 91 { 92 return displayName; 93 } 94 95 /** 96 * Gets the icon of the items 97 * @return the icon of the items 98 */ 99 public Icon getIcon() 100 { 101 if( size == 1 ) 102 return icon; 103 else 104 return ImageProvider.get("data", multipleClassname); 105 } 106 106 } -
applications/editors/josm/plugins/validator/src/org/openstreetmap/josm/plugins/validator/util/Util.java
r12257 r12778 22 22 public class Util 23 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 24 /** 25 * Returns the plugin's directory of the plugin 26 * 27 * @return The directory of the plugin 28 */ 29 public static String getPluginDir() 30 { 31 return Main.pref.getPreferencesDir() + "plugins/validator/"; 32 } 33 34 /** 35 * Returns the version 36 * @return The version of the application 37 */ 38 public static Version getVersion() 39 { 40 PluginInformation info = PluginInformation.getLoaded("validator"); 41 if( info == null ) 42 return null; 43 44 return new Version(info.version, info.attr.get("Plugin-Date")); 45 } 46 47 /** 48 * Utility class for displaying versions 49 * 50 * @author frsantos 51 */ 52 public static class Version 53 { 54 /** The revision */ 55 public String revision; 56 /** The build time */ 57 public String time; 58 59 /** 60 * Constructor 61 * @param revision 62 * @param time 63 */ 64 public Version(String revision, String time) 65 { 66 this.revision = revision; 67 this.time = time; 68 } 69 } 70 71 /** 72 * Returns the start and end cells of a way. 73 * @param w The way 74 * @param cellWays The map with all cells 75 * @return A list with all the cells the way starts or ends 76 */ 77 public static List<List<Way>> getWaysInCell(Way w, Map<Point2D,List<Way>> cellWays) 78 { 79 if (w.nodes.size() == 0) 80 return Collections.emptyList(); 81 82 Node n1 = w.nodes.get(0); 83 Node n2 = w.nodes.get(w.nodes.size() - 1); 84 85 List<List<Way>> cells = new ArrayList<List<Way>>(2); 86 Set<Point2D> cellNodes = new HashSet<Point2D>(); 87 Point2D cell; 88 89 // First, round coordinates 90 long x0 = Math.round(n1.eastNorth.east() * OSMValidatorPlugin.griddetail); 91 long y0 = Math.round(n1.eastNorth.north() * OSMValidatorPlugin.griddetail); 92 long x1 = Math.round(n2.eastNorth.east() * OSMValidatorPlugin.griddetail); 93 long y1 = Math.round(n2.eastNorth.north() * OSMValidatorPlugin.griddetail); 94 95 // Start of the way 96 cell = new Point2D.Double(x0, y0); 97 cellNodes.add(cell); 98 List<Way> ways = cellWays.get( cell ); 99 if( ways == null ) 100 { 101 ways = new ArrayList<Way>(); 102 cellWays.put(cell, ways); 103 } 104 cells.add(ways); 105 106 // End of the way 107 cell = new Point2D.Double(x1, y1); 108 if( !cellNodes.contains(cell) ) 109 { 110 cellNodes.add(cell); 111 ways = cellWays.get( cell ); 112 if( ways == null ) 113 { 114 ways = new ArrayList<Way>(); 115 cellWays.put(cell, ways); 116 } 117 cells.add(ways); 118 } 119 120 // Then floor coordinates, in case the way is in the border of the cell. 121 x0 = (long)Math.floor(n1.eastNorth.east() * OSMValidatorPlugin.griddetail); 122 y0 = (long)Math.floor(n1.eastNorth.north() * OSMValidatorPlugin.griddetail); 123 x1 = (long)Math.floor(n2.eastNorth.east() * OSMValidatorPlugin.griddetail); 124 y1 = (long)Math.floor(n2.eastNorth.north() * OSMValidatorPlugin.griddetail); 125 126 // Start of the way 127 cell = new Point2D.Double(x0, y0); 128 if( !cellNodes.contains(cell) ) 129 { 130 cellNodes.add(cell); 131 ways = cellWays.get( cell ); 132 if( ways == null ) 133 { 134 ways = new ArrayList<Way>(); 135 cellWays.put(cell, ways); 136 } 137 cells.add(ways); 138 } 139 140 // End of the way 141 cell = new Point2D.Double(x1, y1); 142 if( !cellNodes.contains(cell) ) 143 { 144 cellNodes.add(cell); 145 ways = cellWays.get( cell ); 146 if( ways == null ) 147 { 148 ways = new ArrayList<Way>(); 149 cellWays.put(cell, ways); 150 } 151 cells.add(ways); 152 } 153 154 return cells; 155 } 156 157 /** 158 * Returns the coordinates of all cells in a grid that a line between 2 159 * nodes intersects with. 160 * 161 * @param n1 The first node. 162 * @param n2 The second node. 163 * @param gridDetail The detail of the grid. Bigger values give smaller 164 * cells, but a bigger number of them. 165 * @return A list with the coordinates of all cells 166 */ 167 public static List<Point2D> getSegmentCells(Node n1, Node n2, double gridDetail) 168 { 169 List<Point2D> cells = new ArrayList<Point2D>(); 170 double x0 = n1.eastNorth.east() * gridDetail; 171 double x1 = n2.eastNorth.east() * gridDetail; 172 double y0 = n1.eastNorth.north() * gridDetail + 1; 173 double y1 = n2.eastNorth.north() * gridDetail + 1; 174 175 if( x0 > x1 ) 176 { 177 // Move to 1st-4th cuadrants 178 double aux; 179 aux = x0; x0 = x1; x1 = aux; 180 aux = y0; y0 = y1; y1 = aux; 181 } 182 183 double dx = x1 - x0; 184 double dy = y1 - y0; 185 long stepY = y0 <= y1 ? 1 : -1; 186 long gridX0 = (long)Math.floor(x0); 187 long gridX1 = (long)Math.floor(x1); 188 long gridY0 = (long)Math.floor(y0); 189 long gridY1 = (long)Math.floor(y1); 190 191 long maxSteps = (gridX1 - gridX0) + Math.abs(gridY1 - gridY0) + 1; 192 while( (gridX0 <= gridX1 && (gridY0 - gridY1)*stepY <= 0) && maxSteps-- > 0) 193 { 194 cells.add( new Point2D.Double(gridX0, gridY0) ); 195 196 // Is the cross between the segment and next vertical line nearer than the cross with next horizontal line? 197 // Note: segment line formula: y=dy/dx(x-x1)+y1 198 // Note: if dy < 0, must use *bottom* line. If dy > 0, must use upper line 199 double scanY = dy/dx * (gridX0 + 1 - x1) + y1 + (dy < 0 ? -1 : 0); 200 double scanX = dx/dy * (gridY0 + (dy < 0 ? 0 : 1)*stepY - y1) + x1; 201 202 double distX = Math.pow(gridX0 + 1 - x0, 2) + Math.pow(scanY - y0, 2); 203 double distY = Math.pow(scanX - x0, 2) + Math.pow(gridY0 + stepY - y0, 2); 204 205 if( distX < distY) 206 gridX0 += 1; 207 else 208 gridY0 += stepY; 209 } 210 211 return cells; 212 } 213 213 } -
applications/editors/josm/plugins/waypoints/src/WaypointOpenAction.java
r12575 r12778 29 29 */ 30 30 public class WaypointOpenAction extends DiskAccessAction { 31 32 33 34 35 36 37 38 39 31 32 /** 33 * Create an open action. The name is "Open a file". 34 */ 35 public WaypointOpenAction() { 36 super(tr("Open waypoints file"), "open", tr("Open a waypoints file."), 37 Shortcut.registerShortcut("tools:waypoints", tr("Menu: {0}", 38 tr("Open waypoints file")), KeyEvent.VK_W, Shortcut.GROUP_MENU, Shortcut.SHIFT_DEFAULT)); 39 } 40 40 41 42 43 44 45 46 47 48 41 public void actionPerformed(ActionEvent e) { 42 JFileChooser fc = createAndOpenFileChooser(true, true, null); 43 if (fc == null) 44 return; 45 File[] files = fc.getSelectedFiles(); 46 for (int i = files.length; i > 0; --i) 47 openFile(files[i-1]); 48 } 49 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 50 /** 51 * Open the given file. 52 */ 53 public void openFile(File file) { 54 String fn = file.getName(); 55 try { 56 DataSet dataSet = 57 WaypointReader.parse(new FileInputStream(file)); 58 Main.main.addLayer(new OsmDataLayer(dataSet, file.getName(), 59 file)); 60 } catch (SAXException x) { 61 x.printStackTrace(); 62 JOptionPane.showMessageDialog(Main.parent, 63 tr("Error while parsing {0}",fn)+": "+x.getMessage()); 64 } catch (ParserConfigurationException x) { 65 x.printStackTrace(); // broken SAXException chaining 66 JOptionPane.showMessageDialog(Main.parent, 67 tr("Error while parsing {0}",fn)+": "+x.getMessage()); 68 } catch (IOException x) { 69 x.printStackTrace(); 70 JOptionPane.showMessageDialog(Main.parent, 71 tr("Could not read \"{0}\"",fn)+"\n"+x.getMessage()); 72 } 73 } 74 74 } -
applications/editors/josm/plugins/waypoints/src/WaypointPlugin.java
r1495 r12778 11 11 12 12 13 14 15 16 17 13 public WaypointPlugin() { 14 JMenuItem waypointItem = new JMenuItem(new WaypointOpenAction()); 15 int index = findFirstSeparator(); 16 Main.main.menu.fileMenu.add(waypointItem,index<0 ? 0: index); 17 } 18 18 19 20 21 22 23 24 25 26 27 28 19 private int findFirstSeparator() 20 { 21 Component[] components = Main.main.menu.fileMenu.getMenuComponents(); 22 for(int count=0; count<components.length; count++) 23 { 24 if(components[count] instanceof JSeparator) 25 return count; 26 } 27 return -1; 28 } 29 29 } -
applications/editors/josm/plugins/waypoints/src/WaypointReader.java
r9949 r12778 1 package waypoints; 1 package waypoints; 2 2 3 3 import static org.openstreetmap.josm.tools.I18n.tr; … … 23 23 public class WaypointReader { 24 24 25 26 27 28 29 30 31 32 33 25 private static class Parser extends DefaultHandler { 26 /** 27 * Current track to be read. The last entry is the current trkpt. 28 * If in wpt-mode, it contain only one GpsPoint. 29 */ 30 private DataSet dataSet; 31 private LatLon currentLatLon; 32 private String curWptName; 33 private boolean inName = false; 34 34 35 // NW start 36 37 38 39 40 41 42 43 44 45 46 35 // NW start 36 // data now has two components: the GPS points and an OsmDataLayer. 37 // This is to allow us to convert waypoints straight to nodes. 38 // The way this works is that waypoints with a name not beginning 39 // with 0 - i.e. waypoints specially named - will be loaded in as 40 // nodes, in addition to going into the gpx layer. Other waypoints will 41 // only go into the gpx layer. 42 public Parser() 43 { 44 dataSet = new DataSet(); 45 } 46 // NW end 47 47 48 @Override public void startElement(String namespaceURI, 49 String localName, String qName, Attributes atts) 50 51 52 53 54 55 56 57 (tr("Data error: lat value \"{0}\" is out of bound.", 58 59 60 61 (tr("Data error: lon value \"{0}\" is out of bound.", 62 63 48 @Override public void startElement(String namespaceURI, 49 String localName, String qName, Attributes atts) 50 throws SAXException { 51 if (qName.equals("wpt")) { 52 try { 53 double lat = Double.parseDouble(atts.getValue("lat")); 54 double lon = Double.parseDouble(atts.getValue("lon")); 55 if (Math.abs(lat) > 90) 56 throw new SAXException 57 (tr("Data error: lat value \"{0}\" is out of bound.", 58 lat)); 59 if (Math.abs(lon) > 180) 60 throw new SAXException 61 (tr("Data error: lon value \"{0}\" is out of bound.", 62 lon)); 63 currentLatLon = new LatLon(lat, lon); 64 64 } catch (NumberFormatException e) { 65 66 65 e.printStackTrace(); 66 throw new SAXException(e); 67 67 } 68 69 70 71 curWptName = ""; 72 } 73 68 } 69 else if (qName.equals("name")) { 70 inName = true; 71 curWptName = ""; 72 } 73 } 74 74 75 76 77 78 79 80 81 75 @Override public void characters(char[] ch, int start, int length) { 76 // NW start 77 if (inName) { 78 curWptName = new String (ch,start,length); 79 } 80 // NW end 81 } 82 82 83 84 85 if (qName.equals("wpt") && curWptName!="") { 86 87 System.out.println("Found a waypoint to convert to a node: " 88 89 90 91 92 93 94 95 83 @Override public void endElement(String namespaceURI, String localName, 84 String qName) { 85 if (qName.equals("wpt") && curWptName!="") { 86 // create a new node from the latitude and longitude 87 System.out.println("Found a waypoint to convert to a node: " 88 + curWptName); 89 Node node = new Node(currentLatLon); 90 node.put("name",curWptName); 91 dataSet.nodes.add(node); 92 } 93 else if (qName.equals("name")) { 94 inName = false; 95 } 96 96 } 97 97 } 98 98 99 100 101 102 public static DataSet parse(InputStream source) 103 104 105 106 107 99 /** 100 * Parse and return the read data 101 */ 102 public static DataSet parse(InputStream source) 103 throws SAXException, IOException, ParserConfigurationException { 104 Parser parser = new Parser(); 105 SAXParserFactory.newInstance().newSAXParser().parse(new InputSource(new InputStreamReader(source, "UTF-8")), parser); 106 return parser.dataSet; 107 } 108 108 } -
applications/editors/josm/plugins/wmsplugin/src/uk/me/jstott/jcoord/LatLng.java
r6775 r12778 3 3 /** 4 4 * Class to represent a latitude/longitude pair. 5 * 5 * 6 6 * (c) 2006 Jonathan Stott 7 * 7 * 8 8 * Created on 11-02-2006 9 * 9 * 10 10 * @author Jonathan Stott 11 11 * @version 1.0 … … 27 27 /** 28 28 * Create a new LatLng object to represent a latitude/longitude pair. 29 * 29 * 30 30 * @param lat 31 31 * the latitude in degrees … … 42 42 /** 43 43 * Get a String representation of this LatLng object. 44 * 44 * 45 45 * @return a String representation of this LatLng object. 46 46 * @since 1.0 … … 54 54 * Convert this latitude and longitude into an OSGB (Ordnance Survey of Great 55 55 * Britain) grid reference. 56 * 56 * 57 57 * @return the converted OSGB grid reference 58 58 * @since 1.0 … … 124 124 /** 125 125 * Convert this latitude and longitude to a UTM reference. 126 * 126 * 127 127 * @return the converted UTM reference 128 128 * @since 1.0 … … 212 212 * Convert this LatLng from the OSGB36 datum to the WGS84 datum using an 213 213 * approximate Helmert transformation. 214 * 214 * 215 215 * @since 1.0 216 216 */ … … 260 260 * Convert this LatLng from the WGS84 datum to the OSGB36 datum using an 261 261 * approximate Helmert transformation. 262 * 262 * 263 263 * @since 1.0 264 264 */ … … 310 310 * Calculate the surface distance in kilometres from the this LatLng to the 311 311 * given LatLng. 312 * 312 * 313 313 * @param ll 314 314 * @return the surface distance in km … … 334 334 /** 335 335 * Return the latitude in degrees. 336 * 336 * 337 337 * @return the latitude in degrees 338 338 * @since 1.0 … … 345 345 /** 346 346 * Return the longitude in degrees. 347 * 347 * 348 348 * @return the longitude in degrees 349 349 * @since 1.0 -
applications/editors/josm/plugins/wmsplugin/src/uk/me/jstott/jcoord/OSRef.java
r6775 r12778 3 3 /** 4 4 * Class to represent an Ordnance Survey grid reference 5 * 5 * 6 6 * (c) 2006 Jonathan Stott 7 * 7 * 8 8 * Created on 11-02-2006 9 * 9 * 10 10 * @author Jonathan Stott 11 11 * @version 1.0 … … 27 27 /** 28 28 * Create a new Ordnance Survey grid reference. 29 * 29 * 30 30 * @param easting 31 31 * the easting in metres … … 45 45 * first character must be H, N, S, O or T. The second character can be any 46 46 * uppercase character from A through Z excluding I. 47 * 47 * 48 48 * @param ref 49 49 * a String representing a six-figure Ordnance Survey grid reference … … 83 83 * Return a String representation of this OSGB grid reference showing the 84 84 * easting and northing. 85 * 85 * 86 86 * @return a String represenation of this OSGB grid reference 87 87 * @since 1.0 … … 95 95 * Return a String representation of this OSGB grid reference using the 96 96 * six-figure notation in the form XY123456 97 * 97 * 98 98 * @return a String representing this OSGB grid reference in six-figure 99 99 * notation … … 147 147 * OSGB36 datum. Note that, the LatLng object may need to be converted to the 148 148 * WGS84 datum depending on the application. 149 * 149 * 150 150 * @return a LatLng object representing this OSGB grid reference using the 151 151 * OSGB36 datum … … 225 225 /** 226 226 * Get the easting. 227 * 227 * 228 228 * @return the easting in metres 229 229 * @since 1.0 … … 236 236 /** 237 237 * Get the northing. 238 * 238 * 239 239 * @return the northing in metres 240 240 * @since 1.0 -
applications/editors/josm/plugins/wmsplugin/src/uk/me/jstott/jcoord/RefEll.java
r6775 r12778 4 4 * Class to represent a reference ellipsoid. Also provides a number of 5 5 * pre-determined reference ellipsoids as constants. 6 * 6 * 7 7 * (c) 2006 Jonathan Stott 8 * 8 * 9 9 * Created on 11-Feb-2006 10 * 10 * 11 11 * @author Jonathan Stott 12 12 * @version 1.0 … … 43 43 /** 44 44 * Create a new reference ellipsoid 45 * 45 * 46 46 * @param maj 47 47 * semi-major axis … … 59 59 /** 60 60 * Return the semi-major axis. 61 * 61 * 62 62 * @return the semi-major axis 63 63 * @since 1.0 … … 70 70 /** 71 71 * Return the semi-minor axis 72 * 72 * 73 73 * @return the semi-minor axis 74 74 * @since 1.0 … … 81 81 /** 82 82 * Return the eccentricity. 83 * 83 * 84 84 * @return the eccentricity 85 85 * @since 1.0 -
applications/editors/josm/plugins/wmsplugin/src/uk/me/jstott/jcoord/Test.java
r6775 r12778 4 4 * Class to illustrate the use of the various functions of the classes in the 5 5 * Jcoord package. 6 * 6 * 7 7 * (c) 2006 Jonathan Stott 8 * 8 * 9 9 * Created on 11-Feb-2006 10 * 10 * 11 11 * @author Jonathan Stott 12 12 * @version 1.0 … … 17 17 /** 18 18 * Main method 19 * 19 * 20 20 * @param args 21 21 * not used … … 26 26 /* 27 27 * Calculate Surface Distance between two Latitudes/Longitudes 28 * 28 * 29 29 * The distance() function takes a reference to a LatLng object as a 30 30 * parameter and calculates the surface distance between the the given … … 45 45 /* 46 46 * Convert OS Grid Reference to Latitude/Longitude 47 * 47 * 48 48 * Note that the OSGB-Latitude/Longitude conversions use the OSGB36 datum by 49 49 * default. The majority of applications use the WGS84 datum, for which the … … 76 76 /* 77 77 * Convert Latitude/Longitude to OS Grid Reference 78 * 78 * 79 79 * Note that the OSGB-Latitude/Longitude conversions use the OSGB36 datum by 80 80 * default. The majority of applications use the WGS84 datum, for which the … … 107 107 /* 108 108 * Convert Six-Figure OS Grid Reference String to an OSRef Object 109 * 109 * 110 110 * To convert a string representing a six-figure OSGB grid reference: 111 111 */ -
applications/editors/josm/plugins/wmsplugin/src/uk/me/jstott/jcoord/UTMRef.java
r6775 r12778 3 3 /** 4 4 * Class to represent a UTM reference 5 * 5 * 6 6 * (c) 2006 Jonathan Stott 7 * 7 * 8 8 * Created on 11-Feb-2006 9 * 9 * 10 10 * @author Jonathan Stott 11 11 * @version 1.0 … … 37 37 /** 38 38 * Create a new UTM reference object. 39 * 39 * 40 40 * @param easting 41 41 * the easting … … 58 58 /** 59 59 * Convert this UTM reference to a latitude and longitude. 60 * 60 * 61 61 * @return the converted latitude and longitude 62 62 * @since 1.0 … … 130 130 /** 131 131 * Work out the UTM latitude zone from the latitude. 132 * 132 * 133 133 * @param latitude 134 134 * the latitude to find the UTM latitude zone for … … 184 184 /** 185 185 * Convert this UTM reference to a String representation for printing out. 186 * 186 * 187 187 * @return a String representation of this UTM reference 188 188 * @since 1.0 … … 196 196 /** 197 197 * Get the easting. 198 * 198 * 199 199 * @return the easting 200 200 * @since 1.0 … … 207 207 /** 208 208 * Get the northing. 209 * 209 * 210 210 * @return the northing 211 211 * @since 1.0 … … 218 218 /** 219 219 * Get the latitude zone character. 220 * 220 * 221 221 * @return the latitude zone character 222 222 * @since 1.0 … … 229 229 /** 230 230 * Get the longitude zone number. 231 * 231 * 232 232 * @return the longitude zone number 233 233 * @since 1.0 -
applications/editors/josm/plugins/wmsplugin/src/uk/me/jstott/jcoord/Util.java
r6775 r12778 3 3 /** 4 4 * Some utility functions used by classes in the uk.me.jstott.jcoord package. 5 * 5 * 6 6 * (c) 2006 Jonathan Stott 7 * 7 * 8 8 * Created on 11-Feb-2006 9 * 9 * 10 10 * @author Jonathan Stott 11 11 * @version 1.0 … … 16 16 /** 17 17 * Calculate sin^2(x). 18 * 18 * 19 19 * @param x 20 20 * x … … 29 29 /** 30 30 * Calculate cos^2(x). 31 * 31 * 32 32 * @param x 33 33 * x … … 42 42 /** 43 43 * Calculate tan^2(x). 44 * 44 * 45 45 * @param x 46 46 * x … … 55 55 /** 56 56 * Calculate sec(x). 57 * 57 * 58 58 * @param x 59 59 * x -
applications/editors/josm/plugins/wmsplugin/src/wmsplugin/GeorefImage.java
r12438 r12778 15 15 16 16 public class GeorefImage implements Serializable { 17 18 19 17 public BufferedImage image = null; 18 public EastNorth min, max; 19 public boolean downloadingStarted; 20 20 21 22 23 21 public GeorefImage(boolean downloadingStarted) { 22 this.downloadingStarted = downloadingStarted; 23 } 24 24 25 26 27 28 25 public boolean contains(EastNorth en, double dx, double dy) { 26 return min.east()+dx <= en.east() && en.east() <= max.east()+dx 27 && min.north()+dy <= en.north() && en.north() <= max.north()+dy; 28 } 29 29 30 31 32 33 30 /* this does not take dx and dy offset into account! */ 31 public boolean isVisible(NavigatableComponent nc) { 32 Point minPt = nc.getPoint(min), maxPt = nc.getPoint(max); 33 Graphics g = nc.getGraphics(); 34 34 35 36 37 35 return (g.hitClip(minPt.x, maxPt.y, 36 maxPt.x - minPt.x, minPt.y - maxPt.y)); 37 } 38 38 39 40 39 public boolean paint(Graphics g, NavigatableComponent nc, double dx, double dy) { 40 if (image == null || min == null || max == null) return false; 41 41 42 43 44 42 EastNorth mi = new EastNorth(min.east()+dx, min.north()+dy); 43 EastNorth ma = new EastNorth(max.east()+dx, max.north()+dy); 44 Point minPt = nc.getPoint(mi), maxPt = nc.getPoint(ma); 45 45 46 47 48 49 46 /* this is isVisible() but taking dx, dy into account */ 47 if(!(g.hitClip(minPt.x, maxPt.y, 48 maxPt.x - minPt.x, minPt.y - maxPt.y))) 49 return false; 50 50 51 52 53 54 51 g.drawImage(image, 52 minPt.x, maxPt.y, maxPt.x, minPt.y, // dest 53 0, 0, image.getWidth(), image.getHeight(), // src 54 null); 55 55 56 57 56 return true; 57 } 58 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 59 private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { 60 max = (EastNorth) in.readObject(); 61 min = (EastNorth) in.readObject(); 62 image = (BufferedImage) ImageIO.read(ImageIO.createImageInputStream(in)); 63 } 64 65 private void writeObject(ObjectOutputStream out) throws IOException { 66 out.writeObject(max); 67 out.writeObject(min); 68 if(image == null) 69 out.writeObject(null); 70 else 71 ImageIO.write(image, "png", ImageIO.createImageOutputStream(out)); 72 } 73 73 } -
applications/editors/josm/plugins/wmsplugin/src/wmsplugin/Grabber.java
r11301 r12778 14 14 15 15 abstract public class Grabber implements Runnable { 16 17 18 19 20 21 16 protected Bounds b; 17 protected Projection proj; 18 protected double pixelPerDegree; 19 protected MapView mv; 20 protected WMSLayer layer; 21 protected GeorefImage image; 22 22 23 24 25 26 27 28 29 30 31 23 Grabber(Bounds b, Projection proj, 24 double pixelPerDegree, GeorefImage image, MapView mv, WMSLayer layer) { 25 this.b = b; 26 this.proj = proj; 27 this.pixelPerDegree = pixelPerDegree; 28 this.image = image; 29 this.mv = mv; 30 this.layer = layer; 31 } 32 32 33 33 abstract void fetch() throws Exception; // the image fetch code 34 34 35 36 37 38 39 40 35 int width(){ 36 return (int) ((b.max.lon() - b.min.lon()) * pixelPerDegree); 37 } 38 int height(){ 39 return (int) ((b.max.lat() - b.min.lat()) * pixelPerDegree); 40 } 41 41 42 protected void grabError(Exception e){ // report error when grabing image 43 e.printStackTrace(); 44 45 BufferedImage img = new BufferedImage(width(), height(), BufferedImage.TYPE_INT_ARGB); 46 Graphics g = img.getGraphics(); 47 g.setColor(Color.RED); 48 g.fillRect(0, 0, width(), height()); 49 Font font = g.getFont(); 50 Font tempFont = font.deriveFont(Font.PLAIN).deriveFont(36.0f); 51 g.setFont(tempFont); 52 g.setColor(Color.BLACK); 53 g.drawString(tr("Exception occurred"), 10, height()/2); 54 image.image = img; 55 g.setFont(font); 56 } 42 protected void grabError(Exception e){ // report error when grabing image 43 e.printStackTrace(); 57 44 58 protected void attempt(){ // try to fetch the image 59 int maxTries = 5; // n tries for every image 60 for (int i = 1; i <= maxTries; i++) { 61 try { 62 fetch(); 63 break; // break out of the retry loop 64 } catch (Exception e) { 65 try { // sleep some time and then ask the server again 66 Thread.sleep(random(1000, 2000)); 67 } catch (InterruptedException e1) {} 45 BufferedImage img = new BufferedImage(width(), height(), BufferedImage.TYPE_INT_ARGB); 46 Graphics g = img.getGraphics(); 47 g.setColor(Color.RED); 48 g.fillRect(0, 0, width(), height()); 49 Font font = g.getFont(); 50 Font tempFont = font.deriveFont(Font.PLAIN).deriveFont(36.0f); 51 g.setFont(tempFont); 52 g.setColor(Color.BLACK); 53 g.drawString(tr("Exception occurred"), 10, height()/2); 54 image.image = img; 55 g.setFont(font); 56 } 68 57 69 if(i == maxTries) grabError(e); 70 } 71 } 72 } 58 protected void attempt(){ // try to fetch the image 59 int maxTries = 5; // n tries for every image 60 for (int i = 1; i <= maxTries; i++) { 61 try { 62 fetch(); 63 break; // break out of the retry loop 64 } catch (Exception e) { 65 try { // sleep some time and then ask the server again 66 Thread.sleep(random(1000, 2000)); 67 } catch (InterruptedException e1) {} 73 68 74 public static int random(int min, int max) { 75 return (int)(Math.random() * ((max+1)-min) ) + min; 76 } 69 if(i == maxTries) grabError(e); 70 } 71 } 72 } 73 74 public static int random(int min, int max) { 75 return (int)(Math.random() * ((max+1)-min) ) + min; 76 } 77 77 } -
applications/editors/josm/plugins/wmsplugin/src/wmsplugin/Help_WMSmenuAction.java
r12707 r12778 11 11 public class Help_WMSmenuAction extends JosmAction { 12 12 13 14 15 16 13 /** 14 * 15 */ 16 17 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 18 public Help_WMSmenuAction() { 19 //super("Help / About"); 20 super(tr("help"), "help", tr("Help / About"), null, false); 21 22 } 23 24 public void actionPerformed(ActionEvent e) { 25 //todo - put this into a txt file? 26 String helptext = 27 tr("You can add, edit and delete WMS entries in the WMSplugin Preference Tab - " + 28 "these will then show up in the WMS menu.\n\n"+ 29 30 "You can also do this manually in the Advanced Preferences, using the following schema:\n"+ 31 "wmsplugin.url.1.name=Landsat\n"+ 32 "wmsplugin.url.1.url=http://onearth.jpl.nasa.gov....\n"+ 33 "wmsplugin.url.2.name=NPE Maps... etc\n\n"+ 34 35 "Full WMS URL input format example (landsat)\n"+ 36 "http://onearth.jpl.nasa.gov/wms.cgi?request=GetMap&\n"+ 37 "layers=global_mosaic&styles=&srs=EPSG:4326&\n"+ 38 "format=image/jpeg \n\n"+ 39 40 "For Metacarta's Map Rectifier http://labs.metacarta.com/rectifier/ , you only need to input the relevant 'id'.\n" + 41 "To add a Metacarta Map Rectifier menu item, manually create the URL like in this example," + 42 "replacing 73 with your image id: \n" + 43 "http://labs.metacarta.com/rectifier/wms.cgi?id=73\n" + 44 "&srs=EPSG:4326&Service=WMS&Version=1.1.0&Request=GetMap&format=image/png\n" + 45 " \n" + 46 "Note: Make sure the image is suitable, copyright-wise, if in doubt, don't use."); 47 48 JTextPane tp = new JTextPane(); 49 JScrollPane js = new JScrollPane(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, 50 JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS); 51 52 53 js.getViewport().add(tp); 54 JFrame jf = new JFrame(tr("WMS Plugin Help")); 55 jf.getContentPane().add(js); 56 jf.pack(); 57 jf.setSize(400,500); 58 jf.setVisible(true); 59 tp.setText(helptext); 60 } 61 61 } -
applications/editors/josm/plugins/wmsplugin/src/wmsplugin/Map_Rectifier_WMSmenuAction.java
r12707 r12778 12 12 public class Map_Rectifier_WMSmenuAction extends JosmAction { 13 13 14 15 16 17 14 /** 15 * tim waters "chippy" 16 */ 17 private static final long serialVersionUID = 1L; 18 18 19 20 21 19 public Map_Rectifier_WMSmenuAction() { 20 super(tr("Rectified Image ..."), "OLmarker", tr("Download Rectified Image from Metacarta's Map Rectifier WMS"), null, false); 21 } 22 22 23 24 25 23 public void actionPerformed(ActionEvent e) { 24 String newid = JOptionPane.showInputDialog(Main.parent, tr("Metacarta Map Rectifier image id"), 25 Main.pref.get("wmsplugin.rectifier_id")); 26 26 27 28 29 27 if (newid != null && !newid.equals("")) { 28 String newURL = "http://labs.metacarta.com/rectifier/wms.cgi?id="+newid+ 29 "&srs=EPSG:4326&Service=WMS&Version=1.1.0&Request=GetMap&format=image/png"; 30 30 31 32 33 34 35 31 Main.pref.put("wmsplugin.rectifier_id", newid); 32 WMSLayer wmsLayer = new WMSLayer(tr("rectifier id={0}",newid), newURL); 33 Main.main.addLayer(wmsLayer); 34 } 35 } 36 36 } -
applications/editors/josm/plugins/wmsplugin/src/wmsplugin/OSGBGrabber.java
r10382 r12778 15 15 // FIXME: Remove this hack when we have proper projection support. 16 16 public class OSGBGrabber extends WMSGrabber { 17 18 19 17 public OSGBGrabber(String baseURL) { 18 super(baseURL); 19 } 20 20 21 21 private Epsg4326 latlonProj = new Epsg4326(); 22 22 23 24 25 26 27 28 23 @Override public GeorefImage grab(Bounds b, Projection proj, 24 double pixelPerDegree) throws IOException { 25 Bounds bnew = toOSGB(b); 26 double pixelPerDegreeNew = 27 pixelPerDegree / (bnew.max.lon() - bnew.min.lon()) 28 * (b.max.lon() - b.min.lon()); 29 29 30 30 GeorefImage img = super.grab(bnew, latlonProj, pixelPerDegreeNew); 31 31 32 33 32 img.min = proj.latlon2eastNorth(fromOSGB(img.min)); 33 img.max = proj.latlon2eastNorth(fromOSGB(img.max)); 34 34 35 36 35 return img; 36 } 37 37 38 39 40 41 42 43 38 protected static Bounds toOSGB(Bounds b) { 39 LatLng[] lls = new LatLng[] { 40 new LatLng(b.min.lat(), b.min.lon()), 41 new LatLng(b.min.lat(), b.max.lon()), 42 new LatLng(b.max.lat(), b.min.lon()), 43 new LatLng(b.max.lat(), b.max.lon()) }; 44 44 45 45 for (LatLng ll : lls) ll.toOSGB36(); 46 46 47 48 47 OSRef[] grs = new OSRef[lls.length]; 48 for (int i = 0; i < lls.length; i++) grs[i] = lls[i].toOSRef(); 49 49 50 51 52 53 50 LatLon latlon = new LatLon(grs[0].getNorthing(), grs[0].getEasting()); 51 Bounds bnew = new Bounds(latlon, latlon); 52 for (int i = 1; i < grs.length; i++) 53 bnew.extend(new LatLon(grs[i].getNorthing(), grs[i].getEasting())); 54 54 55 56 55 return bnew; 56 } 57 57 58 59 60 61 62 58 protected static LatLon fromOSGB(EastNorth en) { 59 LatLng ll = new OSRef(en.east(), en.north()).toLatLng(); 60 ll.toWGS84(); 61 return new LatLon(ll.getLat(), ll.getLng()); 62 } 63 63 } 64 64 */ -
applications/editors/josm/plugins/wmsplugin/src/wmsplugin/WMSAdjustAction.java
r12438 r12778 17 17 18 18 public class WMSAdjustAction extends MapMode implements 19 19 MouseListener, MouseMotionListener{ 20 20 21 22 23 24 21 GeorefImage selectedImage; 22 WMSLayer selectedLayer; 23 boolean mouseDown; 24 EastNorth prevEastNorth; 25 25 26 27 28 29 30 26 public WMSAdjustAction(MapFrame mapFrame) { 27 super(tr("Adjust WMS"), "adjustwms", 28 tr("Adjust the position of the WMS layer"), mapFrame, 29 ImageProvider.getCursor("normal", "move")); 30 } 31 31 32 33 34 35 36 32 @Override public void enterMode() { 33 super.enterMode(); 34 Main.map.mapView.addMouseListener(this); 35 Main.map.mapView.addMouseMotionListener(this); 36 } 37 37 38 39 40 41 42 38 @Override public void exitMode() { 39 super.exitMode(); 40 Main.map.mapView.removeMouseListener(this); 41 Main.map.mapView.removeMouseMotionListener(this); 42 } 43 43 44 45 46 44 @Override public void mousePressed(MouseEvent e) { 45 if (e.getButton() != MouseEvent.BUTTON1) 46 return; 47 47 48 49 50 51 52 53 54 55 56 57 58 59 48 for(Layer layer:Main.map.mapView.getAllLayers()) { 49 if (layer.visible && layer instanceof WMSLayer) { 50 prevEastNorth=Main.map.mapView.getEastNorth(e.getX(),e.getY()); 51 selectedLayer = ((WMSLayer)layer); 52 selectedImage = selectedLayer.findImage(prevEastNorth); 53 if(selectedImage!=null){ 54 Main.map.mapView.setCursor 55 (Cursor.getPredefinedCursor(Cursor.MOVE_CURSOR)); 56 } 57 } 58 } 59 } 60 60 61 62 63 64 65 61 @Override public void mouseDragged(MouseEvent e) { 62 /* 63 if (e.getButton() != MouseEvent.BUTTON1) 64 return; 65 */ 66 66 67 68 69 70 71 72 73 74 75 67 if(selectedImage!=null) { 68 EastNorth eastNorth= 69 Main.map.mapView.getEastNorth(e.getX(),e.getY()); 70 selectedLayer.displace(eastNorth.east()-prevEastNorth.east(), 71 eastNorth.north()-prevEastNorth.north()); 72 prevEastNorth = eastNorth; 73 Main.map.mapView.repaint(); 74 } 75 } 76 76 77 78 79 80 selectedImage = null; 81 82 83 77 @Override public void mouseReleased(MouseEvent e) { 78 Main.map.mapView.repaint(); 79 Main.map.mapView.setCursor(Cursor.getDefaultCursor()); 80 selectedImage = null; 81 prevEastNorth = null; 82 selectedLayer = null; 83 } 84 84 85 86 87 88 89 90 85 public void mouseEntered(MouseEvent e) { 86 } 87 public void mouseExited(MouseEvent e) { 88 } 89 public void mouseMoved(MouseEvent e) { 90 } 91 91 92 93 92 @Override public void mouseClicked(MouseEvent e) { 93 } 94 94 } -
applications/editors/josm/plugins/wmsplugin/src/wmsplugin/WMSDownloadAction.java
r12187 r12778 13 13 public class WMSDownloadAction extends JosmAction { 14 14 15 private WMSInfo info; 16 17 public WMSDownloadAction(WMSInfo info) { 18 super(info.name, "wmsmenu", tr("Download WMS tile from {0}",info.name), null, false); 19 this.info = info; 20 } 21 22 public void actionPerformed(ActionEvent e) { 23 System.out.println(info.url); 24 25 WMSLayer wmsLayer = new WMSLayer(info.name, info.url); 26 Main.main.addLayer(wmsLayer); 27 } 15 private WMSInfo info; 28 16 29 public static WMSLayer getLayer(WMSInfo info) { 30 // FIXME: move this to WMSPlugin/WMSInfo/preferences. 31 WMSLayer wmsLayer = new WMSLayer(info.name, info.url); 32 Main.main.addLayer(wmsLayer); 33 return wmsLayer; 34 } 17 public WMSDownloadAction(WMSInfo info) { 18 super(info.name, "wmsmenu", tr("Download WMS tile from {0}",info.name), null, false); 19 this.info = info; 20 } 21 22 public void actionPerformed(ActionEvent e) { 23 System.out.println(info.url); 24 25 WMSLayer wmsLayer = new WMSLayer(info.name, info.url); 26 Main.main.addLayer(wmsLayer); 27 } 28 29 public static WMSLayer getLayer(WMSInfo info) { 30 // FIXME: move this to WMSPlugin/WMSInfo/preferences. 31 WMSLayer wmsLayer = new WMSLayer(info.name, info.url); 32 Main.main.addLayer(wmsLayer); 33 return wmsLayer; 34 } 35 35 }; -
applications/editors/josm/plugins/wmsplugin/src/wmsplugin/WMSGrabber.java
r11400 r12778 25 25 26 26 public class WMSGrabber extends Grabber { 27 27 protected String baseURL; 28 28 29 30 31 32 33 29 WMSGrabber(String baseURL, Bounds b, Projection proj, 30 double pixelPerDegree, GeorefImage image, MapView mv, WMSLayer layer) { 31 super(b, proj, pixelPerDegree, image, mv, layer); 32 this.baseURL = baseURL; 33 } 34 34 35 36 37 38 35 public void run() { 36 attempt(); 37 mv.repaint(); 38 } 39 39 40 void fetch() throws Exception{ 41 URL url = null; 42 try { 43 url = getURL( 44 b.min.lon(), b.min.lat(), 45 b.max.lon(), b.max.lat(), 46 width(), height()); 47 48 image.min = proj.latlon2eastNorth(b.min); 49 image.max = proj.latlon2eastNorth(b.max); 40 void fetch() throws Exception{ 41 URL url = null; 42 try { 43 url = getURL( 44 b.min.lon(), b.min.lat(), 45 b.max.lon(), b.max.lat(), 46 width(), height()); 50 47 51 if(image.isVisible(mv)) //don't download, if the image isn't visible already 52 image.image = grab(url); 53 image.downloadingStarted = false; 54 } catch(Exception e) { 55 throw new Exception(e.getMessage() + "\nImage couldn't be fetched: " + (url != null ? url.toString() : "")); 56 } 57 } 48 image.min = proj.latlon2eastNorth(b.min); 49 image.max = proj.latlon2eastNorth(b.max); 58 50 59 public static final NumberFormat 60 latLonFormat = new DecimalFormat("###0.0000000", 61 new DecimalFormatSymbols(Locale.US)); 51 if(image.isVisible(mv)) //don't download, if the image isn't visible already 52 image.image = grab(url); 53 image.downloadingStarted = false; 54 } catch(Exception e) { 55 throw new Exception(e.getMessage() + "\nImage couldn't be fetched: " + (url != null ? url.toString() : "")); 56 } 57 } 62 58 63 protected URL getURL(double w, double s,double e,double n, 64 int wi, int ht) throws MalformedURLException { 65 String str = baseURL; 66 if(!str.endsWith("?")) 67 str += "&"; 68 str += "bbox=" 69 + latLonFormat.format(w) + "," 70 + latLonFormat.format(s) + "," 71 + latLonFormat.format(e) + "," 72 + latLonFormat.format(n) 73 + "&width=" + wi + "&height=" + ht; 74 return new URL(str.replace(" ", "%20")); 75 } 59 public static final NumberFormat 60 latLonFormat = new DecimalFormat("###0.0000000", 61 new DecimalFormatSymbols(Locale.US)); 76 62 77 protected BufferedImage grab(URL url) throws IOException { 78 HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 79 80 String contentType = conn.getHeaderField("Content-Type"); 81 if( conn.getResponseCode() != 200 82 || contentType != null && !contentType.startsWith("image") ) { 83 throw new IOException(readException(conn)); 84 } 85 86 InputStream is = new ProgressInputStream(conn, null); 87 BufferedImage img = ImageIO.read(is); 88 is.close(); 89 return img; 90 } 63 protected URL getURL(double w, double s,double e,double n, 64 int wi, int ht) throws MalformedURLException { 65 String str = baseURL; 66 if(!str.endsWith("?")) 67 str += "&"; 68 str += "bbox=" 69 + latLonFormat.format(w) + "," 70 + latLonFormat.format(s) + "," 71 + latLonFormat.format(e) + "," 72 + latLonFormat.format(n) 73 + "&width=" + wi + "&height=" + ht; 74 return new URL(str.replace(" ", "%20")); 75 } 91 76 92 protected String readException(URLConnection conn) throws IOException { 93 StringBuilder exception = new StringBuilder(); 94 InputStream in = conn.getInputStream(); 95 BufferedReader br = new BufferedReader(new InputStreamReader(in)); 96 97 String line = null; 98 while( (line = br.readLine()) != null) { 99 exception.append(line); 100 exception.append('\n'); 101 } 102 return exception.toString(); 103 } 77 protected BufferedImage grab(URL url) throws IOException { 78 HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 79 80 String contentType = conn.getHeaderField("Content-Type"); 81 if( conn.getResponseCode() != 200 82 || contentType != null && !contentType.startsWith("image") ) { 83 throw new IOException(readException(conn)); 84 } 85 86 InputStream is = new ProgressInputStream(conn, null); 87 BufferedImage img = ImageIO.read(is); 88 is.close(); 89 return img; 90 } 91 92 protected String readException(URLConnection conn) throws IOException { 93 StringBuilder exception = new StringBuilder(); 94 InputStream in = conn.getInputStream(); 95 BufferedReader br = new BufferedReader(new InputStreamReader(in)); 96 97 String line = null; 98 while( (line = br.readLine()) != null) { 99 exception.append(line); 100 exception.append('\n'); 101 } 102 return exception.toString(); 103 } 104 104 } -
applications/editors/josm/plugins/wmsplugin/src/wmsplugin/WMSInfo.java
r10767 r12778 5 5 /** 6 6 * Class that stores info about a WMS server. 7 * 7 * 8 8 * @author Frederik Ramm <frederik@remote.org> 9 9 */ 10 10 public class WMSInfo implements Comparable { 11 12 String name;13 String url;14 int prefid;15 16 public WMSInfo(String name, String url, int prefid) {17 this.name=name; this.url=url; this.prefid=prefid;18 }19 11 20 21 public void save() { 22 Main.pref.put("wmsplugin.url." + prefid + ".name", name); 23 Main.pref.put("wmsplugin.url." + prefid + ".url", url); 24 } 25 public int compareTo(Object c) 26 { 27 Integer i = 0; 28 if(c instanceof WMSInfo) 29 { 30 WMSInfo in = (WMSInfo)c; 31 i = name.compareTo(in.name); 32 if(i == 0) 33 i = url.compareTo(in.url); 34 if(i == 0) 35 i = prefid-in.prefid; 36 } 37 return i; 38 } 12 String name; 13 String url; 14 int prefid; 15 16 public WMSInfo(String name, String url, int prefid) { 17 this.name=name; this.url=url; this.prefid=prefid; 18 } 19 20 21 public void save() { 22 Main.pref.put("wmsplugin.url." + prefid + ".name", name); 23 Main.pref.put("wmsplugin.url." + prefid + ".url", url); 24 } 25 public int compareTo(Object c) 26 { 27 Integer i = 0; 28 if(c instanceof WMSInfo) 29 { 30 WMSInfo in = (WMSInfo)c; 31 i = name.compareTo(in.name); 32 if(i == 0) 33 i = url.compareTo(in.url); 34 if(i == 0) 35 i = prefid-in.prefid; 36 } 37 return i; 38 } 39 39 } -
applications/editors/josm/plugins/wmsplugin/src/wmsplugin/WMSLayer.java
r12707 r12778 45 45 public class WMSLayer extends Layer { 46 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 return new Bounds( 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 new JMenuItem(new LayerListDialog.DeleteLayerAction(this)), 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 47 protected static final Icon icon = 48 new ImageIcon(Toolkit.getDefaultToolkit().createImage(WMSPlugin.class.getResource("/images/wms_small.png"))); 49 50 public int messageNum = 5; //limit for messages per layer 51 protected MapView mv; 52 protected String resolution; 53 protected boolean stopAfterPaint = false; 54 protected int ImageSize = 500; 55 protected int dax = 10; 56 protected int day = 10; 57 protected int minZoom = 3; 58 protected double dx = 0.0; 59 protected double dy = 0.0; 60 protected double pixelPerDegree; 61 protected GeorefImage[][] images = new GeorefImage[dax][day]; 62 JCheckBoxMenuItem startstop = new JCheckBoxMenuItem(tr("Automatic downloading"), true); 63 64 protected String baseURL; 65 protected final int serializeFormatVersion = 4; 66 67 private ExecutorService executor; 68 69 public WMSLayer() { 70 this(tr("Blank Layer"), null); 71 initializeImages(); 72 mv = Main.map.mapView; 73 } 74 75 public WMSLayer(String name, String baseURL) { 76 super(name); 77 background = true; /* set global background variable */ 78 initializeImages(); 79 this.baseURL = baseURL; 80 mv = Main.map.mapView; 81 getPPD(); 82 83 executor = Executors.newFixedThreadPool(3); 84 } 85 86 public void getPPD(){ 87 pixelPerDegree = mv.getWidth() / (bounds().max.lon() - bounds().min.lon()); 88 } 89 90 public void initializeImages() { 91 images = new GeorefImage[dax][day]; 92 for(int x = 0; x<dax; ++x) 93 for(int y = 0; y<day; ++y) 94 images[x][y]= new GeorefImage(false); 95 } 96 97 @Override public Icon getIcon() { 98 return icon; 99 } 100 101 public String scale(){ 102 LatLon ll1 = mv.getLatLon(0,0); 103 LatLon ll2 = mv.getLatLon(100,0); 104 double dist = ll1.greatCircleDistance(ll2); 105 return dist > 1000 ? (Math.round(dist/100)/10.0)+" km" : Math.round(dist*10)/10+" m"; 106 } 107 108 @Override public String getToolTipText() { 109 if(startstop.isSelected()) 110 return tr("WMS layer ({0}), automatically downloading in zoom {1}", name, resolution); 111 else 112 return tr("WMS layer ({0}), downloading in zoom {1}", name, resolution); 113 } 114 115 @Override public boolean isMergable(Layer other) { 116 return false; 117 } 118 119 @Override public void mergeFrom(Layer from) { 120 } 121 122 private Bounds XYtoBounds (int x, int y) { 123 return new Bounds( 124 new LatLon( x * ImageSize / pixelPerDegree, 125 y * ImageSize / pixelPerDegree), 126 new LatLon((x + 1) * ImageSize / pixelPerDegree, 127 (y + 1) * ImageSize / pixelPerDegree)); 128 } 129 130 private int modulo (int a, int b) { 131 if(a%b>=0)return a%b; 132 else return a%b+b; 133 } 134 135 protected Bounds bounds(){ 136 return new Bounds( 137 mv.getLatLon(0, mv.getHeight()), 138 mv.getLatLon(mv.getWidth(), 0)); 139 } 140 141 @Override public void paint(Graphics g, final MapView mv) { 142 if(baseURL == null) return; 143 144 if( !startstop.isSelected() || (pixelPerDegree / (mv.getWidth() / (bounds().max.lon() - bounds().min.lon())) > minZoom) ){ //don't download when it's too outzoomed 145 for(int x = 0; x<dax; ++x) 146 for(int y = 0; y<day; ++y) 147 images[modulo(x,dax)][modulo(y,day)].paint(g, mv, dx, dy); 148 } else 149 downloadAndPaintVisible(g, mv); 150 } 151 152 public void displace(double dx, double dy) { 153 this.dx += dx; 154 this.dy += dy; 155 } 156 157 protected void downloadAndPaintVisible(Graphics g, final MapView mv){ 158 int bminx= (int)Math.floor ((bounds().min.lat() * pixelPerDegree ) / ImageSize ); 159 int bminy= (int)Math.floor ((bounds().min.lon() * pixelPerDegree ) / ImageSize ); 160 int bmaxx= (int)Math.ceil ((bounds().max.lat() * pixelPerDegree ) / ImageSize ); 161 int bmaxy= (int)Math.ceil ((bounds().max.lon() * pixelPerDegree ) / ImageSize ); 162 163 if((bmaxx - bminx > dax) || (bmaxy - bminy > day)){ 164 JOptionPane.showMessageDialog(Main.parent, tr("The requested area is too big. Please zoom in a little, or change resolution")); 165 return; 166 } 167 168 for(int x = bminx; x<bmaxx; ++x) 169 for(int y = bminy; y<bmaxy; ++y){ 170 GeorefImage img = images[modulo(x,dax)][modulo(y,day)]; 171 if(!img.paint(g, mv, dx, dy) && !img.downloadingStarted){ 172 img.downloadingStarted = true; 173 img.image = null; 174 Grabber gr = WMSPlugin.getGrabber(baseURL, XYtoBounds(x,y), Main.main.proj, pixelPerDegree, img, mv, this); 175 executor.submit(gr); 176 } 177 } 178 } 179 180 @Override public void visitBoundingBox(BoundingXYVisitor v) { 181 for(int x = 0; x<dax; ++x) 182 for(int y = 0; y<day; ++y) 183 if(images[x][y].image!=null){ 184 v.visit(images[x][y].min); 185 v.visit(images[x][y].max); 186 } 187 } 188 189 @Override public Object getInfoComponent() { 190 return getToolTipText(); 191 } 192 193 @Override public Component[] getMenuEntries() { 194 return new Component[]{ 195 new JMenuItem(new LayerListDialog.ShowHideLayerAction(this)), 196 new JMenuItem(new LayerListDialog.DeleteLayerAction(this)), 197 new JSeparator(), 198 new JMenuItem(new LoadWmsAction()), 199 new JMenuItem(new SaveWmsAction()), 200 new JSeparator(), 201 startstop, 202 new JMenuItem(new changeResolutionAction()), 203 new JMenuItem(new downloadAction()), 204 new JSeparator(), 205 new JMenuItem(new LayerListPopup.InfoAction(this)) 206 }; 207 } 208 209 public GeorefImage findImage(EastNorth eastNorth) { 210 for(int x = 0; x<dax; ++x) 211 for(int y = 0; y<day; ++y) 212 if(images[x][y].image!=null && images[x][y].min!=null && images[x][y].max!=null) 213 if(images[x][y].contains(eastNorth, dx, dy)) 214 return images[x][y]; 215 return null; 216 } 217 218 public class downloadAction extends AbstractAction { 219 public downloadAction() { 220 super(tr("Download visible tiles")); 221 } 222 public void actionPerformed(ActionEvent ev) { 223 downloadAndPaintVisible(mv.getGraphics(), mv); 224 } 225 } 226 227 public class changeResolutionAction extends AbstractAction { 228 public changeResolutionAction() { 229 super(tr("Change resolution")); 230 } 231 public void actionPerformed(ActionEvent ev) { 232 initializeImages(); 233 resolution = scale(); 234 getPPD(); 235 mv.repaint(); 236 } 237 } 238 239 public class SaveWmsAction extends AbstractAction { 240 public SaveWmsAction() { 241 super(tr("Save WMS layer to file"), ImageProvider.get("save")); 242 } 243 public void actionPerformed(ActionEvent ev) { 244 File f = openFileDialog(false); 245 try 246 { 247 FileOutputStream fos = new FileOutputStream(f); 248 ObjectOutputStream oos = new ObjectOutputStream(fos); 249 oos.writeInt(serializeFormatVersion); 250 oos.writeInt(dax); 251 oos.writeInt(day); 252 oos.writeInt(ImageSize); 253 oos.writeDouble(pixelPerDegree); 254 oos.writeObject(name); 255 oos.writeObject(baseURL); 256 oos.writeObject(images); 257 oos.close(); 258 fos.close(); 259 } 260 catch (Exception ex) { 261 ex.printStackTrace(System.out); 262 } 263 } 264 } 265 266 public class LoadWmsAction extends AbstractAction { 267 public LoadWmsAction() { 268 super(tr("Load WMS layer from file"), ImageProvider.get("load")); 269 } 270 public void actionPerformed(ActionEvent ev) { 271 File f = openFileDialog(true); 272 if (f == null) return; 273 try 274 { 275 FileInputStream fis = new FileInputStream(f); 276 ObjectInputStream ois = new ObjectInputStream(fis); 277 int sfv = ois.readInt(); 278 if (sfv != serializeFormatVersion) { 279 JOptionPane.showMessageDialog(Main.parent, 280 tr("Unsupported WMS file version; found {0}, expected {1}", sfv, serializeFormatVersion), 281 tr("File Format Error"), 282 JOptionPane.ERROR_MESSAGE); 283 return; 284 } 285 startstop.setSelected(false); 286 dax = ois.readInt(); 287 day = ois.readInt(); 288 ImageSize = ois.readInt(); 289 pixelPerDegree = ois.readDouble(); 290 name = (String) ois.readObject(); 291 baseURL = (String) ois.readObject(); 292 images = (GeorefImage[][])ois.readObject(); 293 ois.close(); 294 fis.close(); 295 mv.repaint(); 296 } 297 catch (Exception ex) { 298 // FIXME be more specific 299 ex.printStackTrace(System.out); 300 JOptionPane.showMessageDialog(Main.parent, 301 tr("Error loading file"), 302 tr("Error"), 303 JOptionPane.ERROR_MESSAGE); 304 return; 305 } 306 } 307 } 308 309 protected static JFileChooser createAndOpenFileChooser(boolean open, boolean multiple) { 310 String curDir = Main.pref.get("lastDirectory"); 311 if (curDir.equals("")) 312 curDir = "."; 313 JFileChooser fc = new JFileChooser(new File(curDir)); 314 fc.setMultiSelectionEnabled(multiple); 315 for (int i = 0; i < ExtensionFileFilter.filters.length; ++i) 316 fc.addChoosableFileFilter(ExtensionFileFilter.filters[i]); 317 fc.setAcceptAllFileFilterUsed(true); 318 319 int answer = open ? fc.showOpenDialog(Main.parent) : fc.showSaveDialog(Main.parent); 320 if (answer != JFileChooser.APPROVE_OPTION) 321 return null; 322 323 if (!fc.getCurrentDirectory().getAbsolutePath().equals(curDir)) 324 Main.pref.put("lastDirectory", fc.getCurrentDirectory().getAbsolutePath()); 325 326 if (!open) { 327 File file = fc.getSelectedFile(); 328 if (file == null || (file.exists() && JOptionPane.YES_OPTION != 329 JOptionPane.showConfirmDialog(Main.parent, tr("File exists. Overwrite?"), tr("Overwrite"), JOptionPane.YES_NO_OPTION))) 330 return null; 331 } 332 333 return fc; 334 } 335 336 public static File openFileDialog(boolean open) { 337 JFileChooser fc = createAndOpenFileChooser(open, false); 338 if (fc == null) 339 return null; 340 341 File file = fc.getSelectedFile(); 342 343 String fn = file.getPath(); 344 if (fn.indexOf('.') == -1) { 345 FileFilter ff = fc.getFileFilter(); 346 if (ff instanceof ExtensionFileFilter) 347 fn = "." + ((ExtensionFileFilter)ff).defaultExtension; 348 else 349 fn += ".osm"; 350 file = new File(fn); 351 } 352 return file; 353 } 354 354 } -
applications/editors/josm/plugins/wmsplugin/src/wmsplugin/WMSPlugin.java
r12472 r12778 39 39 public class WMSPlugin extends Plugin { 40 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 wmsJMenu.add(new JMenuItem(new 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 else 193 194 195 196 //return new OSGBGrabber(_b, _proj, _pixelPerDegree, _images, _mv, _layer);197 198 //return new WMSGrabber(_b, _proj, _pixelPerDegree, _images, _mv, _layer);199 200 201 202 203 204 205 206 207 41 WMSLayer wmsLayer; 42 static JMenu wmsJMenu; 43 44 static ArrayList<WMSInfo> wmsList = new ArrayList<WMSInfo>(); 45 static TreeMap<String,String> wmsListDefault = new TreeMap<String,String>(); 46 47 // remember state of menu item to restore on changed preferences 48 static private boolean menuEnabled = false; 49 50 public WMSPlugin() { 51 try 52 { 53 copy("/resources/ymap.html", "ymap.html"); 54 } 55 catch(IOException e) { 56 e.printStackTrace(); 57 } 58 refreshMenu(); 59 } 60 61 // this parses the preferences settings. preferences for the wms plugin have to 62 // look like this: 63 // wmsplugin.1.name=Landsat 64 // wmsplugin.1.url=http://and.so.on/ 65 66 public void copy(String from, String to) throws FileNotFoundException, IOException 67 { 68 File pluginDir = new File(Main.pref.getPreferencesDir() + "plugins/wmsplugin/"); 69 if (!pluginDir.exists()) 70 pluginDir.mkdirs(); 71 FileOutputStream out = new FileOutputStream(Main.pref.getPreferencesDir() + "plugins/wmsplugin/" + to); 72 InputStream in = WMSPlugin.class.getResourceAsStream(from); 73 byte[] buffer = new byte[8192]; 74 for(int len = in.read(buffer); len > 0; len = in.read(buffer)) 75 out.write(buffer, 0, len); 76 in.close(); 77 out.close(); 78 } 79 80 81 public static void refreshMenu() { 82 wmsList.clear(); 83 Map<String,String> prefs = Main.pref.getAllPrefix("wmsplugin.url."); 84 85 TreeSet<String> keys = new TreeSet<String>(prefs.keySet()); 86 int prefid = 0; 87 String name = null; 88 String url = null; 89 int lastid = -1; 90 for (String key : keys) { 91 String[] elements = key.split("\\."); 92 if (elements.length != 4) continue; 93 try { 94 prefid = Integer.parseInt(elements[2]); 95 } catch(NumberFormatException e) { 96 continue; 97 } 98 if (prefid != lastid) { 99 name = url = null; lastid = prefid; 100 } 101 if (elements[3].equals("name")) 102 name = prefs.get(key); 103 else if (elements[3].equals("url")) 104 url = prefs.get(key); 105 if (name != null && url != null) 106 wmsList.add(new WMSInfo(name, url, prefid)); 107 } 108 String source = "http://svn.openstreetmap.org/applications/editors/josm/plugins/wmsplugin/sources.cfg"; 109 try 110 { 111 MirroredInputStream s = new MirroredInputStream(source, 112 Main.pref.getPreferencesDir() + "plugins/wmsplugin/", -1); 113 InputStreamReader r; 114 try 115 { 116 r = new InputStreamReader(s, "UTF-8"); 117 } 118 catch (UnsupportedEncodingException e) 119 { 120 r = new InputStreamReader(s); 121 } 122 BufferedReader reader = new BufferedReader(r); 123 String line; 124 while((line = reader.readLine()) != null) 125 { 126 String val[] = line.split(";"); 127 if(!line.startsWith("#") && val.length == 3) 128 setDefault("true".equals(val[0]), tr(val[1]), val[2]); 129 } 130 } 131 catch (IOException e) 132 { 133 } 134 135 Collections.sort(wmsList); 136 MainMenu menu = Main.main.menu; 137 138 if (wmsJMenu == null) { 139 wmsJMenu = new JMenu(tr("WMS")); 140 menu.add(wmsJMenu, KeyEvent.VK_W, "wms"); 141 menu.add(wmsJMenu, 5); 142 } else { 143 wmsJMenu.removeAll(); 144 } 145 146 // for each configured WMSInfo, add a menu entry. 147 for (final WMSInfo u : wmsList) { 148 wmsJMenu.add(new JMenuItem(new WMSDownloadAction(u))); 149 } 150 wmsJMenu.addSeparator(); 151 wmsJMenu.add(new JMenuItem(new Map_Rectifier_WMSmenuAction())); 152 153 wmsJMenu.addSeparator(); 154 wmsJMenu.add(new JMenuItem(new 155 JosmAction(tr("Blank Layer"), "blankmenu", tr("Open a blank WMS layer to load data from a file"), null, false) { 156 public void actionPerformed(ActionEvent ev) { 157 Main.main.addLayer(new WMSLayer()); 158 } 159 })); 160 wmsJMenu.addSeparator(); 161 wmsJMenu.add(new JMenuItem(new Help_WMSmenuAction())); 162 setEnabledAll(menuEnabled); 163 } 164 165 /* add a default entry in case the URL does not yet exist */ 166 private static void setDefault(Boolean force, String name, String url) 167 { 168 String testurl = url.replaceAll("=", "_"); 169 wmsListDefault.put(name, url); 170 171 if(force && !Main.pref.getBoolean("wmsplugin.default."+testurl)) 172 { 173 Main.pref.put("wmsplugin.default."+testurl, true); 174 int id = -1; 175 for(WMSInfo i : wmsList) 176 { 177 if(url.equals(i.url)) 178 return; 179 if(i.prefid > id) 180 id = i.prefid; 181 } 182 WMSInfo newinfo = new WMSInfo(name, url, id+1); 183 newinfo.save(); 184 wmsList.add(newinfo); 185 } 186 } 187 188 public static Grabber getGrabber(String _baseURL, Bounds _b, Projection _proj, 189 double _pixelPerDegree, GeorefImage _image, MapView _mv, WMSLayer _layer){ 190 if(_baseURL.startsWith("yahoo://")) 191 return new YAHOOGrabber(_baseURL, _b, _proj, _pixelPerDegree, _image, _mv, _layer); 192 else 193 return new WMSGrabber(_baseURL, _b, _proj, _pixelPerDegree, _image, _mv, _layer); 194 // OSBGrabber should be rewrite for thread support first 195 //if (wmsurl.matches("(?i).*layers=npeoocmap.*") || wmsurl.matches("(?i).*layers=npe.*") ){ 196 // return new OSGBGrabber(_b, _proj, _pixelPerDegree, _images, _mv, _layer); 197 //} else { 198 // return new WMSGrabber(_b, _proj, _pixelPerDegree, _images, _mv, _layer); 199 //} 200 } 201 202 private static void setEnabledAll(boolean isEnabled) { 203 for(int i=0; i < wmsJMenu.getItemCount(); i++) { 204 JMenuItem item = wmsJMenu.getItem(i); 205 206 if(item != null) item.setEnabled(isEnabled); 207 } 208 208 menuEnabled = isEnabled; 209 210 211 212 if (oldFrame==null && newFrame!=null) { 213 214 215 216 217 218 219 220 221 222 223 209 } 210 211 public void mapFrameInitialized(MapFrame oldFrame, MapFrame newFrame) { 212 if (oldFrame==null && newFrame!=null) { 213 setEnabledAll(true); 214 Main.map.addMapMode(new IconToggleButton 215 (new WMSAdjustAction(Main.map))); 216 } else if (oldFrame!=null && newFrame==null ) { 217 setEnabledAll(false); 218 } 219 } 220 221 public PreferenceSetting getPreferenceSetting() { 222 return new WMSPreferenceEditor(); 223 } 224 224 } -
applications/editors/josm/plugins/wmsplugin/src/wmsplugin/WMSPreferenceEditor.java
r12588 r12778 27 27 28 28 public class WMSPreferenceEditor implements PreferenceSetting { 29 30 private Map<String,String> orig;31 private DefaultTableModel model;32 private HashMap<Integer, WMSInfo> oldValues = new HashMap<Integer, WMSInfo>();33 29 34 public void addGui(final PreferenceDialog gui) { 35 JPanel p = gui.createPreferenceTab("wms", tr("WMS Plugin Preferences"), tr("Modify list of WMS servers displayed in the WMS plugin menu")); 36 37 model = new DefaultTableModel(new String[]{tr("Menu Name"), tr("WMS URL")}, 0); 38 final JTable list = new JTable(model); 39 JScrollPane scroll = new JScrollPane(list); 40 p.add(scroll, GBC.eol().fill(GBC.BOTH)); 41 scroll.setPreferredSize(new Dimension(200,200)); 42 43 for (WMSInfo i : WMSPlugin.wmsList) { 44 oldValues.put(i.prefid, i); 45 model.addRow(new String[]{i.name, i.url}); 46 } 30 private Map<String,String> orig; 31 private DefaultTableModel model; 32 private HashMap<Integer, WMSInfo> oldValues = new HashMap<Integer, WMSInfo>(); 47 33 48 final DefaultTableModel modeldef = new DefaultTableModel( 49 new String[]{tr("Menu Name (Default)"), tr("WMS URL (Default)")}, 0); 50 final JTable listdef = new JTable(modeldef){ 51 public boolean isCellEditable(int row,int column){return false;} 52 };; 53 JScrollPane scrolldef = new JScrollPane(listdef); 54 p.add(scrolldef, GBC.eol().insets(0,5,0,0).fill(GBC.BOTH)); 55 scrolldef.setPreferredSize(new Dimension(200,200)); 34 public void addGui(final PreferenceDialog gui) { 35 JPanel p = gui.createPreferenceTab("wms", tr("WMS Plugin Preferences"), tr("Modify list of WMS servers displayed in the WMS plugin menu")); 56 36 57 for (Map.Entry<String,String> i : WMSPlugin.wmsListDefault.entrySet()) { 58 modeldef.addRow(new String[]{i.getKey(), i.getValue()}); 59 } 37 model = new DefaultTableModel(new String[]{tr("Menu Name"), tr("WMS URL")}, 0); 38 final JTable list = new JTable(model); 39 JScrollPane scroll = new JScrollPane(list); 40 p.add(scroll, GBC.eol().fill(GBC.BOTH)); 41 scroll.setPreferredSize(new Dimension(200,200)); 60 42 61 JButton add = new JButton(tr("Add")); 62 p.add(Box.createHorizontalGlue(), GBC.std().fill(GBC.HORIZONTAL)); 63 p.add(add, GBC.std().insets(0,5,0,0)); 64 add.addActionListener(new ActionListener(){ 65 public void actionPerformed(ActionEvent e) { 66 JPanel p = new JPanel(new GridBagLayout()); 67 p.add(new JLabel(tr("Menu Name")), GBC.std().insets(0,0,5,0)); 68 JTextField key = new JTextField(10); 69 JTextField value = new JTextField(10); 70 p.add(key, GBC.eop().insets(5,0,0,0).fill(GBC.HORIZONTAL)); 71 p.add(new JLabel(tr("WMS URL")), GBC.std().insets(0,0,5,0)); 72 p.add(value, GBC.eol().insets(5,0,0,0).fill(GBC.HORIZONTAL)); 73 int answer = JOptionPane.showConfirmDialog(gui, p, tr("Enter a menu name and WMS URL"), JOptionPane.OK_CANCEL_OPTION); 74 if (answer == JOptionPane.OK_OPTION) { 75 model.addRow(new String[]{key.getText(), value.getText()}); 76 } 77 } 78 }); 43 for (WMSInfo i : WMSPlugin.wmsList) { 44 oldValues.put(i.prefid, i); 45 model.addRow(new String[]{i.name, i.url}); 46 } 79 47 80 JButton delete = new JButton(tr("Delete")); 81 p.add(delete, GBC.std().insets(0,5,0,0)); 82 delete.addActionListener(new ActionListener(){ 83 public void actionPerformed(ActionEvent e) { 84 if (list.getSelectedRow() == -1) 85 JOptionPane.showMessageDialog(gui, tr("Please select the row to delete.")); 86 else 87 { 88 Integer i; 89 while ((i = list.getSelectedRow()) != -1) 90 model.removeRow(i); 91 } 92 } 93 }); 94 95 JButton copy = new JButton(tr("Copy Default")); 96 p.add(copy, GBC.std().insets(0,5,0,0)); 97 copy.addActionListener(new ActionListener(){ 98 public void actionPerformed(ActionEvent e) { 99 Integer line = listdef.getSelectedRow(); 100 if (line == -1) 101 JOptionPane.showMessageDialog(gui, tr("Please select the row to copy.")); 102 else 103 { 104 model.addRow(new String[]{modeldef.getValueAt(line, 0).toString(), 105 modeldef.getValueAt(line, 1).toString()}); 106 } 107 } 108 }); 109 } 110 111 public boolean ok() { 112 boolean change = false; 113 for (int i = 0; i < model.getRowCount(); ++i) { 114 String name = model.getValueAt(i,0).toString(); 115 String url = model.getValueAt(i,1).toString(); 48 final DefaultTableModel modeldef = new DefaultTableModel( 49 new String[]{tr("Menu Name (Default)"), tr("WMS URL (Default)")}, 0); 50 final JTable listdef = new JTable(modeldef){ 51 public boolean isCellEditable(int row,int column){return false;} 52 };; 53 JScrollPane scrolldef = new JScrollPane(listdef); 54 p.add(scrolldef, GBC.eol().insets(0,5,0,0).fill(GBC.BOTH)); 55 scrolldef.setPreferredSize(new Dimension(200,200)); 116 56 117 WMSInfo origValue = oldValues.get(i); 118 if (origValue == null) 119 { 120 new WMSInfo(name, url, i).save(); 121 change = true; 122 } 123 else 124 { 125 if (!origValue.name.equals(name) || !origValue.url.equals(url)) 126 { 127 origValue.name = name; 128 origValue.url = url; 129 origValue.save(); 130 change = true; 131 } 132 oldValues.remove(i); 133 } 134 } 135 136 // using null values instead of empty string really deletes 137 // the preferences entry 138 for (WMSInfo i : oldValues.values()) 139 { 140 i.url = null; 141 i.name = null; 142 i.save(); 143 change = true; 144 } 57 for (Map.Entry<String,String> i : WMSPlugin.wmsListDefault.entrySet()) { 58 modeldef.addRow(new String[]{i.getKey(), i.getValue()}); 59 } 145 60 146 if (change) WMSPlugin.refreshMenu(); 147 return false; 148 } 149 61 JButton add = new JButton(tr("Add")); 62 p.add(Box.createHorizontalGlue(), GBC.std().fill(GBC.HORIZONTAL)); 63 p.add(add, GBC.std().insets(0,5,0,0)); 64 add.addActionListener(new ActionListener(){ 65 public void actionPerformed(ActionEvent e) { 66 JPanel p = new JPanel(new GridBagLayout()); 67 p.add(new JLabel(tr("Menu Name")), GBC.std().insets(0,0,5,0)); 68 JTextField key = new JTextField(10); 69 JTextField value = new JTextField(10); 70 p.add(key, GBC.eop().insets(5,0,0,0).fill(GBC.HORIZONTAL)); 71 p.add(new JLabel(tr("WMS URL")), GBC.std().insets(0,0,5,0)); 72 p.add(value, GBC.eol().insets(5,0,0,0).fill(GBC.HORIZONTAL)); 73 int answer = JOptionPane.showConfirmDialog(gui, p, tr("Enter a menu name and WMS URL"), JOptionPane.OK_CANCEL_OPTION); 74 if (answer == JOptionPane.OK_OPTION) { 75 model.addRow(new String[]{key.getText(), value.getText()}); 76 } 77 } 78 }); 79 80 JButton delete = new JButton(tr("Delete")); 81 p.add(delete, GBC.std().insets(0,5,0,0)); 82 delete.addActionListener(new ActionListener(){ 83 public void actionPerformed(ActionEvent e) { 84 if (list.getSelectedRow() == -1) 85 JOptionPane.showMessageDialog(gui, tr("Please select the row to delete.")); 86 else 87 { 88 Integer i; 89 while ((i = list.getSelectedRow()) != -1) 90 model.removeRow(i); 91 } 92 } 93 }); 94 95 JButton copy = new JButton(tr("Copy Default")); 96 p.add(copy, GBC.std().insets(0,5,0,0)); 97 copy.addActionListener(new ActionListener(){ 98 public void actionPerformed(ActionEvent e) { 99 Integer line = listdef.getSelectedRow(); 100 if (line == -1) 101 JOptionPane.showMessageDialog(gui, tr("Please select the row to copy.")); 102 else 103 { 104 model.addRow(new String[]{modeldef.getValueAt(line, 0).toString(), 105 modeldef.getValueAt(line, 1).toString()}); 106 } 107 } 108 }); 109 } 110 111 public boolean ok() { 112 boolean change = false; 113 for (int i = 0; i < model.getRowCount(); ++i) { 114 String name = model.getValueAt(i,0).toString(); 115 String url = model.getValueAt(i,1).toString(); 116 117 WMSInfo origValue = oldValues.get(i); 118 if (origValue == null) 119 { 120 new WMSInfo(name, url, i).save(); 121 change = true; 122 } 123 else 124 { 125 if (!origValue.name.equals(name) || !origValue.url.equals(url)) 126 { 127 origValue.name = name; 128 origValue.url = url; 129 origValue.save(); 130 change = true; 131 } 132 oldValues.remove(i); 133 } 134 } 135 136 // using null values instead of empty string really deletes 137 // the preferences entry 138 for (WMSInfo i : oldValues.values()) 139 { 140 i.url = null; 141 i.name = null; 142 i.save(); 143 change = true; 144 } 145 146 if (change) WMSPlugin.refreshMenu(); 147 return false; 148 } 149 150 150 /** 151 151 * Updates a server URL in the preferences dialog. Used by other plugins. 152 * 152 * 153 153 * @param server The server name 154 154 * @param url The server URL … … 156 156 public void setServerUrl(String server, String url) 157 157 { 158 for (int i = 0; i < model.getRowCount(); i++) 158 for (int i = 0; i < model.getRowCount(); i++) 159 159 { 160 160 if( server.equals(model.getValueAt(i,0).toString()) ) … … 175 175 public String getServerUrl(String server) 176 176 { 177 for (int i = 0; i < model.getRowCount(); i++) 177 for (int i = 0; i < model.getRowCount(); i++) 178 178 { 179 179 if( server.equals(model.getValueAt(i,0).toString()) ) -
applications/editors/josm/plugins/wmsplugin/src/wmsplugin/YAHOOGrabber.java
r11400 r12778 20 20 21 21 public class YAHOOGrabber extends WMSGrabber{ 22 22 protected String browserCmd; 23 23 24 25 26 24 YAHOOGrabber(String baseURL, Bounds b, Projection proj, 25 double pixelPerDegree, GeorefImage image, MapView mv, WMSLayer layer) { 26 super("file:///" + Main.pref.getPreferencesDir() + "plugins/wmsplugin/ymap.html?" 27 27 // + "request=getmap&format=image/jpeg" 28 29 30 28 , b, proj, pixelPerDegree, image, mv, layer); 29 this.browserCmd = baseURL.replaceFirst("yahoo://", ""); 30 } 31 31 32 33 34 35 36 37 38 39 40 32 protected BufferedImage grab(URL url) throws IOException { 33 ArrayList<String> cmdParams = new ArrayList<String>(); 34 String urlstring = url.toExternalForm(); 35 // work around a problem in URL removing 2 slashes 36 if(!urlstring.startsWith("file:///")) 37 urlstring = urlstring.replaceFirst("file:", "file://"); 38 StringTokenizer st = new StringTokenizer(MessageFormat.format(browserCmd, urlstring)); 39 while( st.hasMoreTokens() ) 40 cmdParams.add(st.nextToken()); 41 41 42 43 42 System.out.println("WMS::Browsing YAHOO: " + cmdParams); 43 ProcessBuilder builder = new ProcessBuilder( cmdParams); 44 44 45 46 47 48 49 50 45 Process browser; 46 try { 47 browser = builder.start(); 48 } catch(IOException ioe) { 49 throw new IOException( "Could not start browser. Please check that the executable path is correct.\n" + ioe.getMessage() ); 50 } 51 51 52 53 52 return ImageIO.read(browser.getInputStream()); 53 } 54 54 }
Note:
See TracChangeset
for help on using the changeset viewer.