001// License: GPL. See LICENSE file for details. 002package org.openstreetmap.josm.gui.layer; 003 004import static org.openstreetmap.josm.gui.help.HelpUtil.ht; 005import static org.openstreetmap.josm.tools.I18n.marktr; 006import static org.openstreetmap.josm.tools.I18n.tr; 007import static org.openstreetmap.josm.tools.I18n.trn; 008 009import java.awt.AlphaComposite; 010import java.awt.Color; 011import java.awt.Composite; 012import java.awt.Graphics2D; 013import java.awt.GridBagLayout; 014import java.awt.Image; 015import java.awt.Point; 016import java.awt.Rectangle; 017import java.awt.TexturePaint; 018import java.awt.event.ActionEvent; 019import java.awt.geom.Area; 020import java.awt.image.BufferedImage; 021import java.io.File; 022import java.util.ArrayList; 023import java.util.Arrays; 024import java.util.Collection; 025import java.util.Collections; 026import java.util.HashMap; 027import java.util.HashSet; 028import java.util.List; 029import java.util.Map; 030import java.util.concurrent.Callable; 031import java.util.concurrent.CopyOnWriteArrayList; 032 033import javax.swing.AbstractAction; 034import javax.swing.Action; 035import javax.swing.Icon; 036import javax.swing.ImageIcon; 037import javax.swing.JLabel; 038import javax.swing.JOptionPane; 039import javax.swing.JPanel; 040import javax.swing.JScrollPane; 041 042import org.openstreetmap.josm.Main; 043import org.openstreetmap.josm.actions.ExpertToggleAction; 044import org.openstreetmap.josm.actions.RenameLayerAction; 045import org.openstreetmap.josm.actions.SaveActionBase; 046import org.openstreetmap.josm.actions.ToggleUploadDiscouragedLayerAction; 047import org.openstreetmap.josm.data.APIDataSet; 048import org.openstreetmap.josm.data.Bounds; 049import org.openstreetmap.josm.data.DataSource; 050import org.openstreetmap.josm.data.SelectionChangedListener; 051import org.openstreetmap.josm.data.conflict.Conflict; 052import org.openstreetmap.josm.data.conflict.ConflictCollection; 053import org.openstreetmap.josm.data.coor.LatLon; 054import org.openstreetmap.josm.data.gpx.GpxConstants; 055import org.openstreetmap.josm.data.gpx.GpxData; 056import org.openstreetmap.josm.data.gpx.GpxLink; 057import org.openstreetmap.josm.data.gpx.ImmutableGpxTrack; 058import org.openstreetmap.josm.data.gpx.WayPoint; 059import org.openstreetmap.josm.data.osm.DataIntegrityProblemException; 060import org.openstreetmap.josm.data.osm.DataSet; 061import org.openstreetmap.josm.data.osm.DataSetMerger; 062import org.openstreetmap.josm.data.osm.DatasetConsistencyTest; 063import org.openstreetmap.josm.data.osm.IPrimitive; 064import org.openstreetmap.josm.data.osm.Node; 065import org.openstreetmap.josm.data.osm.OsmPrimitive; 066import org.openstreetmap.josm.data.osm.Relation; 067import org.openstreetmap.josm.data.osm.Way; 068import org.openstreetmap.josm.data.osm.event.AbstractDatasetChangedEvent; 069import org.openstreetmap.josm.data.osm.event.DataSetListenerAdapter; 070import org.openstreetmap.josm.data.osm.event.DataSetListenerAdapter.Listener; 071import org.openstreetmap.josm.data.osm.visitor.AbstractVisitor; 072import org.openstreetmap.josm.data.osm.visitor.BoundingXYVisitor; 073import org.openstreetmap.josm.data.osm.visitor.paint.MapRendererFactory; 074import org.openstreetmap.josm.data.osm.visitor.paint.Rendering; 075import org.openstreetmap.josm.data.osm.visitor.paint.relations.MultipolygonCache; 076import org.openstreetmap.josm.data.projection.Projection; 077import org.openstreetmap.josm.data.validation.TestError; 078import org.openstreetmap.josm.gui.ExtendedDialog; 079import org.openstreetmap.josm.gui.MapView; 080import org.openstreetmap.josm.gui.dialogs.LayerListDialog; 081import org.openstreetmap.josm.gui.dialogs.LayerListPopup; 082import org.openstreetmap.josm.gui.io.AbstractIOTask; 083import org.openstreetmap.josm.gui.io.AbstractUploadDialog; 084import org.openstreetmap.josm.gui.io.UploadDialog; 085import org.openstreetmap.josm.gui.io.UploadLayerTask; 086import org.openstreetmap.josm.gui.progress.PleaseWaitProgressMonitor; 087import org.openstreetmap.josm.gui.progress.ProgressMonitor; 088import org.openstreetmap.josm.gui.util.GuiHelper; 089import org.openstreetmap.josm.gui.widgets.JosmTextArea; 090import org.openstreetmap.josm.tools.FilteredCollection; 091import org.openstreetmap.josm.tools.GBC; 092import org.openstreetmap.josm.tools.ImageProvider; 093import org.openstreetmap.josm.tools.date.DateUtils; 094 095/** 096 * A layer that holds OSM data from a specific dataset. 097 * The data can be fully edited. 098 * 099 * @author imi 100 * @since 17 101 */ 102public class OsmDataLayer extends AbstractModifiableLayer implements Listener, SelectionChangedListener { 103 /** Property used to know if this layer has to be saved on disk */ 104 public static final String REQUIRES_SAVE_TO_DISK_PROP = OsmDataLayer.class.getName() + ".requiresSaveToDisk"; 105 /** Property used to know if this layer has to be uploaded */ 106 public static final String REQUIRES_UPLOAD_TO_SERVER_PROP = OsmDataLayer.class.getName() + ".requiresUploadToServer"; 107 108 private boolean requiresSaveToFile = false; 109 private boolean requiresUploadToServer = false; 110 private boolean isChanged = true; 111 private int highlightUpdateCount; 112 113 /** 114 * List of validation errors in this layer. 115 * @since 3669 116 */ 117 public final List<TestError> validationErrors = new ArrayList<>(); 118 119 protected void setRequiresSaveToFile(boolean newValue) { 120 boolean oldValue = requiresSaveToFile; 121 requiresSaveToFile = newValue; 122 if (oldValue != newValue) { 123 propertyChangeSupport.firePropertyChange(REQUIRES_SAVE_TO_DISK_PROP, oldValue, newValue); 124 } 125 } 126 127 protected void setRequiresUploadToServer(boolean newValue) { 128 boolean oldValue = requiresUploadToServer; 129 requiresUploadToServer = newValue; 130 if (oldValue != newValue) { 131 propertyChangeSupport.firePropertyChange(REQUIRES_UPLOAD_TO_SERVER_PROP, oldValue, newValue); 132 } 133 } 134 135 /** the global counter for created data layers */ 136 private static int dataLayerCounter = 0; 137 138 /** 139 * Replies a new unique name for a data layer 140 * 141 * @return a new unique name for a data layer 142 */ 143 public static String createNewName() { 144 dataLayerCounter++; 145 return tr("Data Layer {0}", dataLayerCounter); 146 } 147 148 public static final class DataCountVisitor extends AbstractVisitor { 149 public int nodes; 150 public int ways; 151 public int relations; 152 public int deletedNodes; 153 public int deletedWays; 154 public int deletedRelations; 155 156 @Override 157 public void visit(final Node n) { 158 nodes++; 159 if (n.isDeleted()) { 160 deletedNodes++; 161 } 162 } 163 164 @Override 165 public void visit(final Way w) { 166 ways++; 167 if (w.isDeleted()) { 168 deletedWays++; 169 } 170 } 171 172 @Override 173 public void visit(final Relation r) { 174 relations++; 175 if (r.isDeleted()) { 176 deletedRelations++; 177 } 178 } 179 } 180 181 public interface CommandQueueListener { 182 void commandChanged(int queueSize, int redoSize); 183 } 184 185 /** 186 * Listener called when a state of this layer has changed. 187 */ 188 public interface LayerStateChangeListener { 189 /** 190 * Notifies that the "upload discouraged" (upload=no) state has changed. 191 * @param layer The layer that has been modified 192 * @param newValue The new value of the state 193 */ 194 void uploadDiscouragedChanged(OsmDataLayer layer, boolean newValue); 195 } 196 197 private final CopyOnWriteArrayList<LayerStateChangeListener> layerStateChangeListeners = new CopyOnWriteArrayList<>(); 198 199 /** 200 * Adds a layer state change listener 201 * 202 * @param listener the listener. Ignored if null or already registered. 203 * @since 5519 204 */ 205 public void addLayerStateChangeListener(LayerStateChangeListener listener) { 206 if (listener != null) { 207 layerStateChangeListeners.addIfAbsent(listener); 208 } 209 } 210 211 /** 212 * Removes a layer property change listener 213 * 214 * @param listener the listener. Ignored if null or already registered. 215 * @since 5519 216 */ 217 public void removeLayerPropertyChangeListener(LayerStateChangeListener listener) { 218 layerStateChangeListeners.remove(listener); 219 } 220 221 /** 222 * The data behind this layer. 223 */ 224 public final DataSet data; 225 226 /** 227 * the collection of conflicts detected in this layer 228 */ 229 private ConflictCollection conflicts; 230 231 /** 232 * a paint texture for non-downloaded area 233 */ 234 private static TexturePaint hatched; 235 236 static { 237 createHatchTexture(); 238 } 239 240 /** 241 * Replies background color for downloaded areas. 242 * @return background color for downloaded areas. Black by default 243 */ 244 public static Color getBackgroundColor() { 245 return Main.pref.getColor(marktr("background"), Color.BLACK); 246 } 247 248 /** 249 * Replies background color for non-downloaded areas. 250 * @return background color for non-downloaded areas. Yellow by default 251 */ 252 public static Color getOutsideColor() { 253 return Main.pref.getColor(marktr("outside downloaded area"), Color.YELLOW); 254 } 255 256 /** 257 * Initialize the hatch pattern used to paint the non-downloaded area 258 */ 259 public static void createHatchTexture() { 260 BufferedImage bi = new BufferedImage(15, 15, BufferedImage.TYPE_INT_ARGB); 261 Graphics2D big = bi.createGraphics(); 262 big.setColor(getBackgroundColor()); 263 Composite comp = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.3f); 264 big.setComposite(comp); 265 big.fillRect(0,0,15,15); 266 big.setColor(getOutsideColor()); 267 big.drawLine(0,15,15,0); 268 Rectangle r = new Rectangle(0, 0, 15,15); 269 hatched = new TexturePaint(bi, r); 270 } 271 272 /** 273 * Construct a new {@code OsmDataLayer}. 274 * @param data OSM data 275 * @param name Layer name 276 * @param associatedFile Associated .osm file (can be null) 277 */ 278 public OsmDataLayer(final DataSet data, final String name, final File associatedFile) { 279 super(name); 280 this.data = data; 281 this.setAssociatedFile(associatedFile); 282 conflicts = new ConflictCollection(); 283 data.addDataSetListener(new DataSetListenerAdapter(this)); 284 data.addDataSetListener(MultipolygonCache.getInstance()); 285 DataSet.addSelectionListener(this); 286 } 287 288 protected Icon getBaseIcon() { 289 return ImageProvider.get("layer", "osmdata_small"); 290 } 291 292 /** 293 * TODO: @return Return a dynamic drawn icon of the map data. The icon is 294 * updated by a background thread to not disturb the running programm. 295 */ 296 @Override public Icon getIcon() { 297 Icon baseIcon = getBaseIcon(); 298 if (isUploadDiscouraged()) { 299 return ImageProvider.overlay(baseIcon, 300 new ImageIcon(ImageProvider.get("warning-small").getImage().getScaledInstance(8, 8, Image.SCALE_SMOOTH)), 301 ImageProvider.OverlayPosition.SOUTHEAST); 302 } else { 303 return baseIcon; 304 } 305 } 306 307 /** 308 * Draw all primitives in this layer but do not draw modified ones (they 309 * are drawn by the edit layer). 310 * Draw nodes last to overlap the ways they belong to. 311 */ 312 @Override public void paint(final Graphics2D g, final MapView mv, Bounds box) { 313 isChanged = false; 314 highlightUpdateCount = data.getHighlightUpdateCount(); 315 316 boolean active = mv.getActiveLayer() == this; 317 boolean inactive = !active && Main.pref.getBoolean("draw.data.inactive_color", true); 318 boolean virtual = !inactive && mv.isVirtualNodesEnabled(); 319 320 // draw the hatched area for non-downloaded region. only draw if we're the active 321 // and bounds are defined; don't draw for inactive layers or loaded GPX files etc 322 if (active && Main.pref.getBoolean("draw.data.downloaded_area", true) && !data.dataSources.isEmpty()) { 323 // initialize area with current viewport 324 Rectangle b = mv.getBounds(); 325 // on some platforms viewport bounds seem to be offset from the left, 326 // over-grow it just to be sure 327 b.grow(100, 100); 328 Area a = new Area(b); 329 330 // now successively subtract downloaded areas 331 for (Bounds bounds : data.getDataSourceBounds()) { 332 if (bounds.isCollapsed()) { 333 continue; 334 } 335 Point p1 = mv.getPoint(bounds.getMin()); 336 Point p2 = mv.getPoint(bounds.getMax()); 337 Rectangle r = new Rectangle(Math.min(p1.x, p2.x),Math.min(p1.y, p2.y),Math.abs(p2.x-p1.x),Math.abs(p2.y-p1.y)); 338 a.subtract(new Area(r)); 339 } 340 341 // paint remainder 342 g.setPaint(hatched); 343 g.fill(a); 344 } 345 346 Rendering painter = MapRendererFactory.getInstance().createActiveRenderer(g, mv, inactive); 347 painter.render(data, virtual, box); 348 Main.map.conflictDialog.paintConflicts(g, mv); 349 } 350 351 @Override public String getToolTipText() { 352 int nodes = new FilteredCollection<>(data.getNodes(), OsmPrimitive.nonDeletedPredicate).size(); 353 int ways = new FilteredCollection<>(data.getWays(), OsmPrimitive.nonDeletedPredicate).size(); 354 355 String tool = trn("{0} node", "{0} nodes", nodes, nodes)+", "; 356 tool += trn("{0} way", "{0} ways", ways, ways); 357 358 if (data.getVersion() != null) { 359 tool += ", " + tr("version {0}", data.getVersion()); 360 } 361 File f = getAssociatedFile(); 362 if (f != null) { 363 tool = "<html>"+tool+"<br>"+f.getPath()+"</html>"; 364 } 365 return tool; 366 } 367 368 @Override public void mergeFrom(final Layer from) { 369 final PleaseWaitProgressMonitor monitor = new PleaseWaitProgressMonitor(tr("Merging layers")); 370 monitor.setCancelable(false); 371 if (from instanceof OsmDataLayer && ((OsmDataLayer)from).isUploadDiscouraged()) { 372 setUploadDiscouraged(true); 373 } 374 mergeFrom(((OsmDataLayer)from).data, monitor); 375 monitor.close(); 376 } 377 378 /** 379 * merges the primitives in dataset <code>from</code> into the dataset of 380 * this layer 381 * 382 * @param from the source data set 383 */ 384 public void mergeFrom(final DataSet from) { 385 mergeFrom(from, null); 386 } 387 388 /** 389 * merges the primitives in dataset <code>from</code> into the dataset of 390 * this layer 391 * 392 * @param from the source data set 393 * @param progressMonitor the progress monitor, can be {@code null} 394 */ 395 public void mergeFrom(final DataSet from, ProgressMonitor progressMonitor) { 396 final DataSetMerger visitor = new DataSetMerger(data,from); 397 try { 398 visitor.merge(progressMonitor); 399 } catch (DataIntegrityProblemException e) { 400 JOptionPane.showMessageDialog( 401 Main.parent, 402 e.getHtmlMessage() != null ? e.getHtmlMessage() : e.getMessage(), 403 tr("Error"), 404 JOptionPane.ERROR_MESSAGE 405 ); 406 return; 407 408 } 409 410 Area a = data.getDataSourceArea(); 411 412 // copy the merged layer's data source info. 413 // only add source rectangles if they are not contained in the layer already. 414 for (DataSource src : from.dataSources) { 415 if (a == null || !a.contains(src.bounds.asRect())) { 416 data.dataSources.add(src); 417 } 418 } 419 420 // copy the merged layer's API version 421 if (data.getVersion() == null) { 422 data.setVersion(from.getVersion()); 423 } 424 425 int numNewConflicts = 0; 426 for (Conflict<?> c : visitor.getConflicts()) { 427 if (!conflicts.hasConflict(c)) { 428 numNewConflicts++; 429 conflicts.add(c); 430 } 431 } 432 // repaint to make sure new data is displayed properly. 433 if (Main.isDisplayingMapView()) { 434 Main.map.mapView.repaint(); 435 } 436 // warn about new conflicts 437 if (numNewConflicts > 0 && Main.map != null && Main.map.conflictDialog != null) { 438 Main.map.conflictDialog.warnNumNewConflicts(numNewConflicts); 439 } 440 } 441 442 @Override public boolean isMergable(final Layer other) { 443 // isUploadDiscouraged commented to allow merging between normal layers and discouraged layers with a warning (see #7684) 444 return other instanceof OsmDataLayer;// && (isUploadDiscouraged() == ((OsmDataLayer)other).isUploadDiscouraged()); 445 } 446 447 @Override public void visitBoundingBox(final BoundingXYVisitor v) { 448 for (final Node n: data.getNodes()) { 449 if (n.isUsable()) { 450 v.visit(n); 451 } 452 } 453 } 454 455 /** 456 * Clean out the data behind the layer. This means clearing the redo/undo lists, 457 * really deleting all deleted objects and reset the modified flags. This should 458 * be done after an upload, even after a partial upload. 459 * 460 * @param processed A list of all objects that were actually uploaded. 461 * May be <code>null</code>, which means nothing has been uploaded 462 */ 463 public void cleanupAfterUpload(final Collection<IPrimitive> processed) { 464 // return immediately if an upload attempt failed 465 if (processed == null || processed.isEmpty()) 466 return; 467 468 Main.main.undoRedo.clean(this); 469 470 // if uploaded, clean the modified flags as well 471 data.cleanupDeletedPrimitives(); 472 for (OsmPrimitive p: data.allPrimitives()) { 473 if (processed.contains(p)) { 474 p.setModified(false); 475 } 476 } 477 } 478 479 480 @Override public Object getInfoComponent() { 481 final DataCountVisitor counter = new DataCountVisitor(); 482 for (final OsmPrimitive osm : data.allPrimitives()) { 483 osm.accept(counter); 484 } 485 final JPanel p = new JPanel(new GridBagLayout()); 486 487 String nodeText = trn("{0} node", "{0} nodes", counter.nodes, counter.nodes); 488 if (counter.deletedNodes > 0) { 489 nodeText += " ("+trn("{0} deleted", "{0} deleted", counter.deletedNodes, counter.deletedNodes)+")"; 490 } 491 492 String wayText = trn("{0} way", "{0} ways", counter.ways, counter.ways); 493 if (counter.deletedWays > 0) { 494 wayText += " ("+trn("{0} deleted", "{0} deleted", counter.deletedWays, counter.deletedWays)+")"; 495 } 496 497 String relationText = trn("{0} relation", "{0} relations", counter.relations, counter.relations); 498 if (counter.deletedRelations > 0) { 499 relationText += " ("+trn("{0} deleted", "{0} deleted", counter.deletedRelations, counter.deletedRelations)+")"; 500 } 501 502 p.add(new JLabel(tr("{0} consists of:", getName())), GBC.eol()); 503 p.add(new JLabel(nodeText, ImageProvider.get("data", "node"), JLabel.HORIZONTAL), GBC.eop().insets(15,0,0,0)); 504 p.add(new JLabel(wayText, ImageProvider.get("data", "way"), JLabel.HORIZONTAL), GBC.eop().insets(15,0,0,0)); 505 p.add(new JLabel(relationText, ImageProvider.get("data", "relation"), JLabel.HORIZONTAL), GBC.eop().insets(15,0,0,0)); 506 p.add(new JLabel(tr("API version: {0}", (data.getVersion() != null) ? data.getVersion() : tr("unset"))), GBC.eop().insets(15,0,0,0)); 507 if (isUploadDiscouraged()) { 508 p.add(new JLabel(tr("Upload is discouraged")), GBC.eop().insets(15,0,0,0)); 509 } 510 511 return p; 512 } 513 514 @Override public Action[] getMenuEntries() { 515 List<Action> actions = new ArrayList<>(); 516 actions.addAll(Arrays.asList(new Action[]{ 517 LayerListDialog.getInstance().createActivateLayerAction(this), 518 LayerListDialog.getInstance().createShowHideLayerAction(), 519 LayerListDialog.getInstance().createDeleteLayerAction(), 520 SeparatorLayerAction.INSTANCE, 521 LayerListDialog.getInstance().createMergeLayerAction(this), 522 new LayerSaveAction(this), 523 new LayerSaveAsAction(this), 524 })); 525 if (ExpertToggleAction.isExpert()) { 526 actions.addAll(Arrays.asList(new Action[]{ 527 new LayerGpxExportAction(this), 528 new ConvertToGpxLayerAction()})); 529 } 530 actions.addAll(Arrays.asList(new Action[]{ 531 SeparatorLayerAction.INSTANCE, 532 new RenameLayerAction(getAssociatedFile(), this)})); 533 if (ExpertToggleAction.isExpert() && Main.pref.getBoolean("data.layer.upload_discouragement.menu_item", false)) { 534 actions.add(new ToggleUploadDiscouragedLayerAction(this)); 535 } 536 actions.addAll(Arrays.asList(new Action[]{ 537 new ConsistencyTestAction(), 538 SeparatorLayerAction.INSTANCE, 539 new LayerListPopup.InfoAction(this)})); 540 return actions.toArray(new Action[actions.size()]); 541 } 542 543 /** 544 * Converts given OSM dataset to GPX data. 545 * @param data OSM dataset 546 * @param file output .gpx file 547 * @return GPX data 548 */ 549 public static GpxData toGpxData(DataSet data, File file) { 550 GpxData gpxData = new GpxData(); 551 gpxData.storageFile = file; 552 HashSet<Node> doneNodes = new HashSet<>(); 553 waysToGpxData(data.getWays(), gpxData, doneNodes); 554 nodesToGpxData(data.getNodes(), gpxData, doneNodes); 555 return gpxData; 556 } 557 558 private static void waysToGpxData(Collection<Way> ways, GpxData gpxData, HashSet<Node> doneNodes) { 559 for (Way w : ways) { 560 if (!w.isUsable()) { 561 continue; 562 } 563 Collection<Collection<WayPoint>> trk = new ArrayList<>(); 564 Map<String, Object> trkAttr = new HashMap<>(); 565 566 if (w.get("name") != null) { 567 trkAttr.put("name", w.get("name")); 568 } 569 570 List<WayPoint> trkseg = null; 571 for (Node n : w.getNodes()) { 572 if (!n.isUsable()) { 573 trkseg = null; 574 continue; 575 } 576 if (trkseg == null) { 577 trkseg = new ArrayList<>(); 578 trk.add(trkseg); 579 } 580 if (!n.isTagged()) { 581 doneNodes.add(n); 582 } 583 WayPoint wpt = new WayPoint(n.getCoor()); 584 if (!n.isTimestampEmpty()) { 585 wpt.put("time", DateUtils.fromDate(n.getTimestamp())); 586 wpt.setTime(); 587 } 588 trkseg.add(wpt); 589 } 590 591 gpxData.tracks.add(new ImmutableGpxTrack(trk, trkAttr)); 592 } 593 } 594 595 private static void nodesToGpxData(Collection<Node> nodes, GpxData gpxData, HashSet<Node> doneNodes) { 596 List<Node> sortedNodes = new ArrayList<>(nodes); 597 sortedNodes.removeAll(doneNodes); 598 Collections.sort(sortedNodes); 599 for (Node n : sortedNodes) { 600 if (n.isIncomplete() || n.isDeleted()) { 601 continue; 602 } 603 WayPoint wpt = new WayPoint(n.getCoor()); 604 605 // Position info 606 607 addDoubleIfPresent(wpt, n, GpxConstants.PT_ELE); 608 609 if (!n.isTimestampEmpty()) { 610 wpt.put("time", DateUtils.fromDate(n.getTimestamp())); 611 wpt.setTime(); 612 } 613 614 addDoubleIfPresent(wpt, n, GpxConstants.PT_MAGVAR); 615 addDoubleIfPresent(wpt, n, GpxConstants.PT_GEOIDHEIGHT); 616 617 // Description info 618 619 addStringIfPresent(wpt, n, GpxConstants.GPX_NAME); 620 addStringIfPresent(wpt, n, GpxConstants.GPX_DESC, "description"); 621 addStringIfPresent(wpt, n, GpxConstants.GPX_CMT, "comment"); 622 addStringIfPresent(wpt, n, GpxConstants.GPX_SRC, "source", "source:position"); 623 624 Collection<GpxLink> links = new ArrayList<>(); 625 for (String key : new String[]{"link", "url", "website", "contact:website"}) { 626 String value = n.get(key); 627 if (value != null) { 628 links.add(new GpxLink(value)); 629 } 630 } 631 wpt.put(GpxConstants.META_LINKS, links); 632 633 addStringIfPresent(wpt, n, GpxConstants.PT_SYM, "wpt_symbol"); 634 addStringIfPresent(wpt, n, GpxConstants.PT_TYPE); 635 636 // Accuracy info 637 addStringIfPresent(wpt, n, GpxConstants.PT_FIX, "gps:fix"); 638 addIntegerIfPresent(wpt, n, GpxConstants.PT_SAT, "gps:sat"); 639 addDoubleIfPresent(wpt, n, GpxConstants.PT_HDOP, "gps:hdop"); 640 addDoubleIfPresent(wpt, n, GpxConstants.PT_VDOP, "gps:vdop"); 641 addDoubleIfPresent(wpt, n, GpxConstants.PT_PDOP, "gps:pdop"); 642 addDoubleIfPresent(wpt, n, GpxConstants.PT_AGEOFDGPSDATA, "gps:ageofdgpsdata"); 643 addIntegerIfPresent(wpt, n, GpxConstants.PT_DGPSID, "gps:dgpsid"); 644 645 gpxData.waypoints.add(wpt); 646 } 647 } 648 649 private static void addIntegerIfPresent(WayPoint wpt, OsmPrimitive p, String gpxKey, String ... osmKeys) { 650 ArrayList<String> possibleKeys = new ArrayList<>(Arrays.asList(osmKeys)); 651 possibleKeys.add(0, gpxKey); 652 for (String key : possibleKeys) { 653 String value = p.get(key); 654 if (value != null) { 655 try { 656 int i = Integer.parseInt(value); 657 // Sanity checks 658 if ((!GpxConstants.PT_SAT.equals(gpxKey) || i >= 0) && 659 (!GpxConstants.PT_DGPSID.equals(gpxKey) || (0 <= i && i <= 1023))) { 660 wpt.put(gpxKey, value); 661 break; 662 } 663 } catch (NumberFormatException e) { 664 if (Main.isTraceEnabled()) { 665 Main.trace(e.getMessage()); 666 } 667 } 668 } 669 } 670 } 671 672 private static void addDoubleIfPresent(WayPoint wpt, OsmPrimitive p, String gpxKey, String ... osmKeys) { 673 ArrayList<String> possibleKeys = new ArrayList<>(Arrays.asList(osmKeys)); 674 possibleKeys.add(0, gpxKey); 675 for (String key : possibleKeys) { 676 String value = p.get(key); 677 if (value != null) { 678 try { 679 double d = Double.parseDouble(value); 680 // Sanity checks 681 if (!GpxConstants.PT_MAGVAR.equals(gpxKey) || (0.0 <= d && d < 360.0)) { 682 wpt.put(gpxKey, value); 683 break; 684 } 685 } catch (NumberFormatException e) { 686 if (Main.isTraceEnabled()) { 687 Main.trace(e.getMessage()); 688 } 689 } 690 } 691 } 692 } 693 694 private static void addStringIfPresent(WayPoint wpt, OsmPrimitive p, String gpxKey, String ... osmKeys) { 695 ArrayList<String> possibleKeys = new ArrayList<>(Arrays.asList(osmKeys)); 696 possibleKeys.add(0, gpxKey); 697 for (String key : possibleKeys) { 698 String value = p.get(key); 699 if (value != null) { 700 // Sanity checks 701 if (!GpxConstants.PT_FIX.equals(gpxKey) || GpxConstants.FIX_VALUES.contains(value)) { 702 wpt.put(gpxKey, value); 703 break; 704 } 705 } 706 } 707 } 708 709 /** 710 * Converts OSM data behind this layer to GPX data. 711 * @return GPX data 712 */ 713 public GpxData toGpxData() { 714 return toGpxData(data, getAssociatedFile()); 715 } 716 717 /** 718 * Action that converts this OSM layer to a GPX layer. 719 */ 720 public class ConvertToGpxLayerAction extends AbstractAction { 721 /** 722 * Constructs a new {@code ConvertToGpxLayerAction}. 723 */ 724 public ConvertToGpxLayerAction() { 725 super(tr("Convert to GPX layer"), ImageProvider.get("converttogpx")); 726 putValue("help", ht("/Action/ConvertToGpxLayer")); 727 } 728 @Override 729 public void actionPerformed(ActionEvent e) { 730 Main.main.addLayer(new GpxLayer(toGpxData(), tr("Converted from: {0}", getName()))); 731 Main.main.removeLayer(OsmDataLayer.this); 732 } 733 } 734 735 /** 736 * Determines if this layer contains data at the given coordinate. 737 * @param coor the coordinate 738 * @return {@code true} if data sources bounding boxes contain {@code coor} 739 */ 740 public boolean containsPoint(LatLon coor) { 741 // we'll assume that if this has no data sources 742 // that it also has no borders 743 if (this.data.dataSources.isEmpty()) 744 return true; 745 746 boolean layer_bounds_point = false; 747 for (DataSource src : this.data.dataSources) { 748 if (src.bounds.contains(coor)) { 749 layer_bounds_point = true; 750 break; 751 } 752 } 753 return layer_bounds_point; 754 } 755 756 /** 757 * Replies the set of conflicts currently managed in this layer. 758 * 759 * @return the set of conflicts currently managed in this layer 760 */ 761 public ConflictCollection getConflicts() { 762 return conflicts; 763 } 764 765 @Override 766 public boolean requiresUploadToServer() { 767 return requiresUploadToServer; 768 } 769 770 @Override 771 public boolean requiresSaveToFile() { 772 return getAssociatedFile() != null && requiresSaveToFile; 773 } 774 775 @Override 776 public void onPostLoadFromFile() { 777 setRequiresSaveToFile(false); 778 setRequiresUploadToServer(isModified()); 779 } 780 781 /** 782 * Actions run after data has been downloaded to this layer. 783 */ 784 public void onPostDownloadFromServer() { 785 setRequiresSaveToFile(true); 786 setRequiresUploadToServer(isModified()); 787 } 788 789 @Override 790 public boolean isChanged() { 791 return isChanged || highlightUpdateCount != data.getHighlightUpdateCount(); 792 } 793 794 @Override 795 public void onPostSaveToFile() { 796 setRequiresSaveToFile(false); 797 setRequiresUploadToServer(isModified()); 798 } 799 800 @Override 801 public void onPostUploadToServer() { 802 setRequiresUploadToServer(isModified()); 803 // keep requiresSaveToDisk unchanged 804 } 805 806 private class ConsistencyTestAction extends AbstractAction { 807 808 public ConsistencyTestAction() { 809 super(tr("Dataset consistency test")); 810 } 811 812 @Override 813 public void actionPerformed(ActionEvent e) { 814 String result = DatasetConsistencyTest.runTests(data); 815 if (result.length() == 0) { 816 JOptionPane.showMessageDialog(Main.parent, tr("No problems found")); 817 } else { 818 JPanel p = new JPanel(new GridBagLayout()); 819 p.add(new JLabel(tr("Following problems found:")), GBC.eol()); 820 JosmTextArea info = new JosmTextArea(result, 20, 60); 821 info.setCaretPosition(0); 822 info.setEditable(false); 823 p.add(new JScrollPane(info), GBC.eop()); 824 825 JOptionPane.showMessageDialog(Main.parent, p, tr("Warning"), JOptionPane.WARNING_MESSAGE); 826 } 827 } 828 } 829 830 @Override 831 public void destroy() { 832 DataSet.removeSelectionListener(this); 833 } 834 835 @Override 836 public void processDatasetEvent(AbstractDatasetChangedEvent event) { 837 isChanged = true; 838 setRequiresSaveToFile(true); 839 setRequiresUploadToServer(true); 840 } 841 842 @Override 843 public void selectionChanged(Collection<? extends OsmPrimitive> newSelection) { 844 isChanged = true; 845 } 846 847 @Override 848 public void projectionChanged(Projection oldValue, Projection newValue) { 849 // No reprojection required. The dataset itself is registered as projection 850 // change listener and already got notified. 851 } 852 853 @Override 854 public final boolean isUploadDiscouraged() { 855 return data.isUploadDiscouraged(); 856 } 857 858 /** 859 * Sets the "discouraged upload" flag. 860 * @param uploadDiscouraged {@code true} if upload of data managed by this layer is discouraged. This feature allows to use "private" data layers. 861 */ 862 public final void setUploadDiscouraged(boolean uploadDiscouraged) { 863 if (uploadDiscouraged ^ isUploadDiscouraged()) { 864 data.setUploadDiscouraged(uploadDiscouraged); 865 for (LayerStateChangeListener l : layerStateChangeListeners) { 866 l.uploadDiscouragedChanged(this, uploadDiscouraged); 867 } 868 } 869 } 870 871 @Override 872 public final boolean isModified() { 873 return data.isModified(); 874 } 875 876 @Override 877 public boolean isSavable() { 878 return true; // With OsmExporter 879 } 880 881 @Override 882 public boolean checkSaveConditions() { 883 if (isDataSetEmpty()) { 884 if (1 != GuiHelper.runInEDTAndWaitAndReturn(new Callable<Integer>() { 885 @Override 886 public Integer call() { 887 ExtendedDialog dialog = new ExtendedDialog( 888 Main.parent, 889 tr("Empty document"), 890 new String[] {tr("Save anyway"), tr("Cancel")} 891 ); 892 dialog.setContent(tr("The document contains no data.")); 893 dialog.setButtonIcons(new String[] {"save.png", "cancel.png"}); 894 return dialog.showDialog().getValue(); 895 } 896 })) { 897 return false; 898 } 899 } 900 901 ConflictCollection conflicts = getConflicts(); 902 if (conflicts != null && !conflicts.isEmpty()) { 903 if (1 != GuiHelper.runInEDTAndWaitAndReturn(new Callable<Integer>() { 904 @Override 905 public Integer call() { 906 ExtendedDialog dialog = new ExtendedDialog( 907 Main.parent, 908 /* I18N: Display title of the window showing conflicts */ 909 tr("Conflicts"), 910 new String[] {tr("Reject Conflicts and Save"), tr("Cancel")} 911 ); 912 dialog.setContent(tr("There are unresolved conflicts. Conflicts will not be saved and handled as if you rejected all. Continue?")); 913 dialog.setButtonIcons(new String[] {"save.png", "cancel.png"}); 914 return dialog.showDialog().getValue(); 915 } 916 })) { 917 return false; 918 } 919 } 920 return true; 921 } 922 923 /** 924 * Check the data set if it would be empty on save. It is empty, if it contains 925 * no objects (after all objects that are created and deleted without being 926 * transferred to the server have been removed). 927 * 928 * @return <code>true</code>, if a save result in an empty data set. 929 */ 930 private boolean isDataSetEmpty() { 931 if (data != null) { 932 for (OsmPrimitive osm : data.allNonDeletedPrimitives()) 933 if (!osm.isDeleted() || !osm.isNewOrUndeleted()) 934 return false; 935 } 936 return true; 937 } 938 939 @Override 940 public File createAndOpenSaveFileChooser() { 941 return SaveActionBase.createAndOpenSaveFileChooser(tr("Save OSM file"), "osm"); 942 } 943 944 @Override 945 public AbstractIOTask createUploadTask(final ProgressMonitor monitor) { 946 UploadDialog dialog = UploadDialog.getUploadDialog(); 947 return new UploadLayerTask( 948 dialog.getUploadStrategySpecification(), 949 this, 950 monitor, 951 dialog.getChangeset()); 952 } 953 954 @Override 955 public AbstractUploadDialog getUploadDialog() { 956 UploadDialog dialog = UploadDialog.getUploadDialog(); 957 dialog.setUploadedPrimitives(new APIDataSet(data)); 958 return dialog; 959 } 960}