source: josm/trunk/src/org/openstreetmap/josm/gui/layer/OsmDataLayer.java@ 8510

Last change on this file since 8510 was 8510, checked in by Don-vip, 9 years ago

checkstyle: enable relevant whitespace checks and fix them

  • Property svn:eol-style set to native
File size: 34.7 KB
Line 
1// License: GPL. For details, see LICENSE file.
2package org.openstreetmap.josm.gui.layer;
3
4import static org.openstreetmap.josm.gui.help.HelpUtil.ht;
5import static org.openstreetmap.josm.tools.I18n.marktr;
6import static org.openstreetmap.josm.tools.I18n.tr;
7import static org.openstreetmap.josm.tools.I18n.trn;
8
9import java.awt.AlphaComposite;
10import java.awt.Color;
11import java.awt.Composite;
12import java.awt.Graphics2D;
13import java.awt.GridBagLayout;
14import java.awt.Point;
15import java.awt.Rectangle;
16import java.awt.TexturePaint;
17import java.awt.event.ActionEvent;
18import java.awt.geom.Area;
19import java.awt.image.BufferedImage;
20import java.io.File;
21import java.util.ArrayList;
22import java.util.Arrays;
23import java.util.Collection;
24import java.util.Collections;
25import java.util.HashMap;
26import java.util.HashSet;
27import java.util.List;
28import java.util.Map;
29import java.util.Set;
30import java.util.concurrent.Callable;
31import java.util.concurrent.CopyOnWriteArrayList;
32
33import javax.swing.AbstractAction;
34import javax.swing.Action;
35import javax.swing.Icon;
36import javax.swing.JLabel;
37import javax.swing.JOptionPane;
38import javax.swing.JPanel;
39import javax.swing.JScrollPane;
40
41import org.openstreetmap.josm.Main;
42import org.openstreetmap.josm.actions.ExpertToggleAction;
43import org.openstreetmap.josm.actions.RenameLayerAction;
44import org.openstreetmap.josm.actions.SaveActionBase;
45import org.openstreetmap.josm.actions.ToggleUploadDiscouragedLayerAction;
46import org.openstreetmap.josm.data.APIDataSet;
47import org.openstreetmap.josm.data.Bounds;
48import org.openstreetmap.josm.data.DataSource;
49import org.openstreetmap.josm.data.SelectionChangedListener;
50import org.openstreetmap.josm.data.conflict.Conflict;
51import org.openstreetmap.josm.data.conflict.ConflictCollection;
52import org.openstreetmap.josm.data.coor.LatLon;
53import org.openstreetmap.josm.data.gpx.GpxConstants;
54import org.openstreetmap.josm.data.gpx.GpxData;
55import org.openstreetmap.josm.data.gpx.GpxLink;
56import org.openstreetmap.josm.data.gpx.ImmutableGpxTrack;
57import org.openstreetmap.josm.data.gpx.WayPoint;
58import org.openstreetmap.josm.data.osm.DataIntegrityProblemException;
59import org.openstreetmap.josm.data.osm.DataSet;
60import org.openstreetmap.josm.data.osm.DataSetMerger;
61import org.openstreetmap.josm.data.osm.DatasetConsistencyTest;
62import org.openstreetmap.josm.data.osm.IPrimitive;
63import org.openstreetmap.josm.data.osm.Node;
64import org.openstreetmap.josm.data.osm.OsmPrimitive;
65import org.openstreetmap.josm.data.osm.Relation;
66import org.openstreetmap.josm.data.osm.Way;
67import org.openstreetmap.josm.data.osm.event.AbstractDatasetChangedEvent;
68import org.openstreetmap.josm.data.osm.event.DataSetListenerAdapter;
69import org.openstreetmap.josm.data.osm.event.DataSetListenerAdapter.Listener;
70import org.openstreetmap.josm.data.osm.visitor.AbstractVisitor;
71import org.openstreetmap.josm.data.osm.visitor.BoundingXYVisitor;
72import org.openstreetmap.josm.data.osm.visitor.paint.MapRendererFactory;
73import org.openstreetmap.josm.data.osm.visitor.paint.Rendering;
74import org.openstreetmap.josm.data.osm.visitor.paint.relations.MultipolygonCache;
75import org.openstreetmap.josm.data.projection.Projection;
76import org.openstreetmap.josm.data.validation.TestError;
77import org.openstreetmap.josm.gui.ExtendedDialog;
78import org.openstreetmap.josm.gui.MapView;
79import org.openstreetmap.josm.gui.dialogs.LayerListDialog;
80import org.openstreetmap.josm.gui.dialogs.LayerListPopup;
81import org.openstreetmap.josm.gui.io.AbstractIOTask;
82import org.openstreetmap.josm.gui.io.AbstractUploadDialog;
83import org.openstreetmap.josm.gui.io.UploadDialog;
84import org.openstreetmap.josm.gui.io.UploadLayerTask;
85import org.openstreetmap.josm.gui.progress.PleaseWaitProgressMonitor;
86import org.openstreetmap.josm.gui.progress.ProgressMonitor;
87import org.openstreetmap.josm.gui.util.GuiHelper;
88import org.openstreetmap.josm.gui.widgets.JosmTextArea;
89import org.openstreetmap.josm.tools.FilteredCollection;
90import org.openstreetmap.josm.tools.GBC;
91import org.openstreetmap.josm.tools.ImageOverlay;
92import org.openstreetmap.josm.tools.ImageProvider;
93import org.openstreetmap.josm.tools.ImageProvider.ImageSizes;
94import org.openstreetmap.josm.tools.date.DateUtils;
95
96/**
97 * A layer that holds OSM data from a specific dataset.
98 * The data can be fully edited.
99 *
100 * @author imi
101 * @since 17
102 */
103public class OsmDataLayer extends AbstractModifiableLayer implements Listener, SelectionChangedListener {
104 /** Property used to know if this layer has to be saved on disk */
105 public static final String REQUIRES_SAVE_TO_DISK_PROP = OsmDataLayer.class.getName() + ".requiresSaveToDisk";
106 /** Property used to know if this layer has to be uploaded */
107 public static final String REQUIRES_UPLOAD_TO_SERVER_PROP = OsmDataLayer.class.getName() + ".requiresUploadToServer";
108
109 private boolean requiresSaveToFile = false;
110 private boolean requiresUploadToServer = false;
111 private boolean isChanged = true;
112 private int highlightUpdateCount;
113
114 /**
115 * List of validation errors in this layer.
116 * @since 3669
117 */
118 public final List<TestError> validationErrors = new ArrayList<>();
119
120 protected void setRequiresSaveToFile(boolean newValue) {
121 boolean oldValue = requiresSaveToFile;
122 requiresSaveToFile = newValue;
123 if (oldValue != newValue) {
124 propertyChangeSupport.firePropertyChange(REQUIRES_SAVE_TO_DISK_PROP, oldValue, newValue);
125 }
126 }
127
128 protected void setRequiresUploadToServer(boolean newValue) {
129 boolean oldValue = requiresUploadToServer;
130 requiresUploadToServer = newValue;
131 if (oldValue != newValue) {
132 propertyChangeSupport.firePropertyChange(REQUIRES_UPLOAD_TO_SERVER_PROP, oldValue, newValue);
133 }
134 }
135
136 /** the global counter for created data layers */
137 private static int dataLayerCounter = 0;
138
139 /**
140 * Replies a new unique name for a data layer
141 *
142 * @return a new unique name for a data layer
143 */
144 public static String createNewName() {
145 dataLayerCounter++;
146 return tr("Data Layer {0}", dataLayerCounter);
147 }
148
149 public static final class DataCountVisitor extends AbstractVisitor {
150 public int nodes;
151 public int ways;
152 public int relations;
153 public int deletedNodes;
154 public int deletedWays;
155 public int deletedRelations;
156
157 @Override
158 public void visit(final Node n) {
159 nodes++;
160 if (n.isDeleted()) {
161 deletedNodes++;
162 }
163 }
164
165 @Override
166 public void visit(final Way w) {
167 ways++;
168 if (w.isDeleted()) {
169 deletedWays++;
170 }
171 }
172
173 @Override
174 public void visit(final Relation r) {
175 relations++;
176 if (r.isDeleted()) {
177 deletedRelations++;
178 }
179 }
180 }
181
182 public interface CommandQueueListener {
183 void commandChanged(int queueSize, int redoSize);
184 }
185
186 /**
187 * Listener called when a state of this layer has changed.
188 */
189 public interface LayerStateChangeListener {
190 /**
191 * Notifies that the "upload discouraged" (upload=no) state has changed.
192 * @param layer The layer that has been modified
193 * @param newValue The new value of the state
194 */
195 void uploadDiscouragedChanged(OsmDataLayer layer, boolean newValue);
196 }
197
198 private final CopyOnWriteArrayList<LayerStateChangeListener> layerStateChangeListeners = new CopyOnWriteArrayList<>();
199
200 /**
201 * Adds a layer state change listener
202 *
203 * @param listener the listener. Ignored if null or already registered.
204 * @since 5519
205 */
206 public void addLayerStateChangeListener(LayerStateChangeListener listener) {
207 if (listener != null) {
208 layerStateChangeListeners.addIfAbsent(listener);
209 }
210 }
211
212 /**
213 * Removes a layer property change listener
214 *
215 * @param listener the listener. Ignored if null or already registered.
216 * @since 5519
217 */
218 public void removeLayerPropertyChangeListener(LayerStateChangeListener listener) {
219 layerStateChangeListeners.remove(listener);
220 }
221
222 /**
223 * The data behind this layer.
224 */
225 public final DataSet data;
226
227 /**
228 * the collection of conflicts detected in this layer
229 */
230 private ConflictCollection conflicts;
231
232 /**
233 * a paint texture for non-downloaded area
234 */
235 private static volatile TexturePaint hatched;
236
237 static {
238 createHatchTexture();
239 }
240
241 /**
242 * Replies background color for downloaded areas.
243 * @return background color for downloaded areas. Black by default
244 */
245 public static Color getBackgroundColor() {
246 return Main.pref.getColor(marktr("background"), Color.BLACK);
247 }
248
249 /**
250 * Replies background color for non-downloaded areas.
251 * @return background color for non-downloaded areas. Yellow by default
252 */
253 public static Color getOutsideColor() {
254 return Main.pref.getColor(marktr("outside downloaded area"), Color.YELLOW);
255 }
256
257 /**
258 * Initialize the hatch pattern used to paint the non-downloaded area
259 */
260 public static void createHatchTexture() {
261 BufferedImage bi = new BufferedImage(15, 15, BufferedImage.TYPE_INT_ARGB);
262 Graphics2D big = bi.createGraphics();
263 big.setColor(getBackgroundColor());
264 Composite comp = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.3f);
265 big.setComposite(comp);
266 big.fillRect(0, 0, 15, 15);
267 big.setColor(getOutsideColor());
268 big.drawLine(0, 15, 15, 0);
269 Rectangle r = new Rectangle(0, 0, 15, 15);
270 hatched = new TexturePaint(bi, r);
271 }
272
273 /**
274 * Construct a new {@code OsmDataLayer}.
275 * @param data OSM data
276 * @param name Layer name
277 * @param associatedFile Associated .osm file (can be null)
278 */
279 public OsmDataLayer(final DataSet data, final String name, final File associatedFile) {
280 super(name);
281 this.data = data;
282 this.setAssociatedFile(associatedFile);
283 conflicts = new ConflictCollection();
284 data.addDataSetListener(new DataSetListenerAdapter(this));
285 data.addDataSetListener(MultipolygonCache.getInstance());
286 DataSet.addSelectionListener(this);
287 }
288
289 /**
290 * Return the image provider to get the base icon
291 * @return image provider class which can be modified
292 * @since 8323
293 */
294 protected ImageProvider getBaseIconProvider() {
295 return new ImageProvider("layer", "osmdata_small");
296 }
297
298 @Override
299 public Icon getIcon() {
300 ImageProvider base = getBaseIconProvider().setMaxSize(ImageSizes.LAYER);
301 if (isUploadDiscouraged()) {
302 base.addOverlay(new ImageOverlay(new ImageProvider("warning-small"), 0.5, 0.5, 1.0, 1.0));
303 }
304 return base.get();
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 int rels = new FilteredCollection<>(data.getRelations(), OsmPrimitive.nonDeletedPredicate).size();
355
356 String tool = trn("{0} node", "{0} nodes", nodes, nodes)+", ";
357 tool += trn("{0} way", "{0} ways", ways, ways)+", ";
358 tool += trn("{0} relation", "{0} relations", rels, rels);
359
360 File f = getAssociatedFile();
361 if (f != null) {
362 tool = "<html>"+tool+"<br>"+f.getPath()+"</html>";
363 }
364 return tool;
365 }
366
367 @Override public void mergeFrom(final Layer from) {
368 final PleaseWaitProgressMonitor monitor = new PleaseWaitProgressMonitor(tr("Merging layers"));
369 monitor.setCancelable(false);
370 if (from instanceof OsmDataLayer && ((OsmDataLayer) from).isUploadDiscouraged()) {
371 setUploadDiscouraged(true);
372 }
373 mergeFrom(((OsmDataLayer) from).data, monitor);
374 monitor.close();
375 }
376
377 /**
378 * merges the primitives in dataset <code>from</code> into the dataset of
379 * this layer
380 *
381 * @param from the source data set
382 */
383 public void mergeFrom(final DataSet from) {
384 mergeFrom(from, null);
385 }
386
387 /**
388 * merges the primitives in dataset <code>from</code> into the dataset of
389 * this layer
390 *
391 * @param from the source data set
392 * @param progressMonitor the progress monitor, can be {@code null}
393 */
394 public void mergeFrom(final DataSet from, ProgressMonitor progressMonitor) {
395 final DataSetMerger visitor = new DataSetMerger(data, from);
396 try {
397 visitor.merge(progressMonitor);
398 } catch (DataIntegrityProblemException e) {
399 JOptionPane.showMessageDialog(
400 Main.parent,
401 e.getHtmlMessage() != null ? e.getHtmlMessage() : e.getMessage(),
402 tr("Error"),
403 JOptionPane.ERROR_MESSAGE
404 );
405 return;
406 }
407
408 Area a = data.getDataSourceArea();
409
410 // copy the merged layer's data source info.
411 // only add source rectangles if they are not contained in the layer already.
412 for (DataSource src : from.dataSources) {
413 if (a == null || !a.contains(src.bounds.asRect())) {
414 data.dataSources.add(src);
415 }
416 }
417
418 // copy the merged layer's API version
419 if (data.getVersion() == null) {
420 data.setVersion(from.getVersion());
421 }
422
423 int numNewConflicts = 0;
424 for (Conflict<?> c : visitor.getConflicts()) {
425 if (!conflicts.hasConflict(c)) {
426 numNewConflicts++;
427 conflicts.add(c);
428 }
429 }
430 // repaint to make sure new data is displayed properly.
431 if (Main.isDisplayingMapView()) {
432 Main.map.mapView.repaint();
433 }
434 // warn about new conflicts
435 if (numNewConflicts > 0 && Main.map != null && Main.map.conflictDialog != null) {
436 Main.map.conflictDialog.warnNumNewConflicts(numNewConflicts);
437 }
438 }
439
440 @Override
441 public boolean isMergable(final Layer other) {
442 // isUploadDiscouraged commented to allow merging between normal layers and discouraged layers with a warning (see #7684)
443 return other instanceof OsmDataLayer; // && (isUploadDiscouraged() == ((OsmDataLayer)other).isUploadDiscouraged());
444 }
445
446 @Override
447 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 @Override
480 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"))),
507 GBC.eop().insets(15, 0, 0, 0));
508 if (isUploadDiscouraged()) {
509 p.add(new JLabel(tr("Upload is discouraged")), GBC.eop().insets(15, 0, 0, 0));
510 }
511
512 return p;
513 }
514
515 @Override public Action[] getMenuEntries() {
516 List<Action> actions = new ArrayList<>();
517 actions.addAll(Arrays.asList(new Action[]{
518 LayerListDialog.getInstance().createActivateLayerAction(this),
519 LayerListDialog.getInstance().createShowHideLayerAction(),
520 LayerListDialog.getInstance().createDeleteLayerAction(),
521 SeparatorLayerAction.INSTANCE,
522 LayerListDialog.getInstance().createMergeLayerAction(this),
523 new LayerSaveAction(this),
524 new LayerSaveAsAction(this),
525 }));
526 if (ExpertToggleAction.isExpert()) {
527 actions.addAll(Arrays.asList(new Action[]{
528 new LayerGpxExportAction(this),
529 new ConvertToGpxLayerAction()}));
530 }
531 actions.addAll(Arrays.asList(new Action[]{
532 SeparatorLayerAction.INSTANCE,
533 new RenameLayerAction(getAssociatedFile(), this)}));
534 if (ExpertToggleAction.isExpert() && Main.pref.getBoolean("data.layer.upload_discouragement.menu_item", false)) {
535 actions.add(new ToggleUploadDiscouragedLayerAction(this));
536 }
537 actions.addAll(Arrays.asList(new Action[]{
538 new ConsistencyTestAction(),
539 SeparatorLayerAction.INSTANCE,
540 new LayerListPopup.InfoAction(this)}));
541 return actions.toArray(new Action[actions.size()]);
542 }
543
544 /**
545 * Converts given OSM dataset to GPX data.
546 * @param data OSM dataset
547 * @param file output .gpx file
548 * @return GPX data
549 */
550 public static GpxData toGpxData(DataSet data, File file) {
551 GpxData gpxData = new GpxData();
552 gpxData.storageFile = file;
553 Set<Node> doneNodes = new HashSet<>();
554 waysToGpxData(data.getWays(), gpxData, doneNodes);
555 nodesToGpxData(data.getNodes(), gpxData, doneNodes);
556 return gpxData;
557 }
558
559 private static void waysToGpxData(Collection<Way> ways, GpxData gpxData, Set<Node> doneNodes) {
560 for (Way w : ways) {
561 if (!w.isUsable()) {
562 continue;
563 }
564 Collection<Collection<WayPoint>> trk = new ArrayList<>();
565 Map<String, Object> trkAttr = new HashMap<>();
566
567 if (w.get("name") != null) {
568 trkAttr.put("name", w.get("name"));
569 }
570
571 List<WayPoint> trkseg = null;
572 for (Node n : w.getNodes()) {
573 if (!n.isUsable()) {
574 trkseg = null;
575 continue;
576 }
577 if (trkseg == null) {
578 trkseg = new ArrayList<>();
579 trk.add(trkseg);
580 }
581 if (!n.isTagged()) {
582 doneNodes.add(n);
583 }
584 trkseg.add(nodeToWayPoint(n));
585 }
586
587 gpxData.tracks.add(new ImmutableGpxTrack(trk, trkAttr));
588 }
589 }
590
591 private static WayPoint nodeToWayPoint(Node n) {
592 WayPoint wpt = new WayPoint(n.getCoor());
593
594 // Position info
595
596 addDoubleIfPresent(wpt, n, GpxConstants.PT_ELE);
597
598 if (!n.isTimestampEmpty()) {
599 wpt.put("time", DateUtils.fromDate(n.getTimestamp()));
600 wpt.setTime();
601 }
602
603 addDoubleIfPresent(wpt, n, GpxConstants.PT_MAGVAR);
604 addDoubleIfPresent(wpt, n, GpxConstants.PT_GEOIDHEIGHT);
605
606 // Description info
607
608 addStringIfPresent(wpt, n, GpxConstants.GPX_NAME);
609 addStringIfPresent(wpt, n, GpxConstants.GPX_DESC, "description");
610 addStringIfPresent(wpt, n, GpxConstants.GPX_CMT, "comment");
611 addStringIfPresent(wpt, n, GpxConstants.GPX_SRC, "source", "source:position");
612
613 Collection<GpxLink> links = new ArrayList<>();
614 for (String key : new String[]{"link", "url", "website", "contact:website"}) {
615 String value = n.get(key);
616 if (value != null) {
617 links.add(new GpxLink(value));
618 }
619 }
620 wpt.put(GpxConstants.META_LINKS, links);
621
622 addStringIfPresent(wpt, n, GpxConstants.PT_SYM, "wpt_symbol");
623 addStringIfPresent(wpt, n, GpxConstants.PT_TYPE);
624
625 // Accuracy info
626 addStringIfPresent(wpt, n, GpxConstants.PT_FIX, "gps:fix");
627 addIntegerIfPresent(wpt, n, GpxConstants.PT_SAT, "gps:sat");
628 addDoubleIfPresent(wpt, n, GpxConstants.PT_HDOP, "gps:hdop");
629 addDoubleIfPresent(wpt, n, GpxConstants.PT_VDOP, "gps:vdop");
630 addDoubleIfPresent(wpt, n, GpxConstants.PT_PDOP, "gps:pdop");
631 addDoubleIfPresent(wpt, n, GpxConstants.PT_AGEOFDGPSDATA, "gps:ageofdgpsdata");
632 addIntegerIfPresent(wpt, n, GpxConstants.PT_DGPSID, "gps:dgpsid");
633
634 return wpt;
635 }
636
637 private static void nodesToGpxData(Collection<Node> nodes, GpxData gpxData, Set<Node> doneNodes) {
638 List<Node> sortedNodes = new ArrayList<>(nodes);
639 sortedNodes.removeAll(doneNodes);
640 Collections.sort(sortedNodes);
641 for (Node n : sortedNodes) {
642 if (n.isIncomplete() || n.isDeleted()) {
643 continue;
644 }
645 gpxData.waypoints.add(nodeToWayPoint(n));
646 }
647 }
648
649 private static void addIntegerIfPresent(WayPoint wpt, OsmPrimitive p, String gpxKey, String ... osmKeys) {
650 List<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 List<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 List<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
729 @Override
730 public void actionPerformed(ActionEvent e) {
731 Main.main.addLayer(new GpxLayer(toGpxData(), tr("Converted from: {0}", getName())));
732 Main.main.removeLayer(OsmDataLayer.this);
733 }
734 }
735
736 /**
737 * Determines if this layer contains data at the given coordinate.
738 * @param coor the coordinate
739 * @return {@code true} if data sources bounding boxes contain {@code coor}
740 */
741 public boolean containsPoint(LatLon coor) {
742 // we'll assume that if this has no data sources
743 // that it also has no borders
744 if (this.data.dataSources.isEmpty())
745 return true;
746
747 boolean layer_bounds_point = false;
748 for (DataSource src : this.data.dataSources) {
749 if (src.bounds.contains(coor)) {
750 layer_bounds_point = true;
751 break;
752 }
753 }
754 return layer_bounds_point;
755 }
756
757 /**
758 * Replies the set of conflicts currently managed in this layer.
759 *
760 * @return the set of conflicts currently managed in this layer
761 */
762 public ConflictCollection getConflicts() {
763 return conflicts;
764 }
765
766 @Override
767 public boolean requiresUploadToServer() {
768 return requiresUploadToServer;
769 }
770
771 @Override
772 public boolean requiresSaveToFile() {
773 return getAssociatedFile() != null && requiresSaveToFile;
774 }
775
776 @Override
777 public void onPostLoadFromFile() {
778 setRequiresSaveToFile(false);
779 setRequiresUploadToServer(isModified());
780 }
781
782 /**
783 * Actions run after data has been downloaded to this layer.
784 */
785 public void onPostDownloadFromServer() {
786 setRequiresSaveToFile(true);
787 setRequiresUploadToServer(isModified());
788 }
789
790 @Override
791 public boolean isChanged() {
792 return isChanged || highlightUpdateCount != data.getHighlightUpdateCount();
793 }
794
795 @Override
796 public void onPostSaveToFile() {
797 setRequiresSaveToFile(false);
798 setRequiresUploadToServer(isModified());
799 }
800
801 @Override
802 public void onPostUploadToServer() {
803 setRequiresUploadToServer(isModified());
804 // keep requiresSaveToDisk unchanged
805 }
806
807 private class ConsistencyTestAction extends AbstractAction {
808
809 public ConsistencyTestAction() {
810 super(tr("Dataset consistency test"));
811 }
812
813 @Override
814 public void actionPerformed(ActionEvent e) {
815 String result = DatasetConsistencyTest.runTests(data);
816 if (result.isEmpty()) {
817 JOptionPane.showMessageDialog(Main.parent, tr("No problems found"));
818 } else {
819 JPanel p = new JPanel(new GridBagLayout());
820 p.add(new JLabel(tr("Following problems found:")), GBC.eol());
821 JosmTextArea info = new JosmTextArea(result, 20, 60);
822 info.setCaretPosition(0);
823 info.setEditable(false);
824 p.add(new JScrollPane(info), GBC.eop());
825
826 JOptionPane.showMessageDialog(Main.parent, p, tr("Warning"), JOptionPane.WARNING_MESSAGE);
827 }
828 }
829 }
830
831 @Override
832 public void destroy() {
833 DataSet.removeSelectionListener(this);
834 }
835
836 @Override
837 public void processDatasetEvent(AbstractDatasetChangedEvent event) {
838 isChanged = true;
839 setRequiresSaveToFile(true);
840 setRequiresUploadToServer(true);
841 }
842
843 @Override
844 public void selectionChanged(Collection<? extends OsmPrimitive> newSelection) {
845 isChanged = true;
846 }
847
848 @Override
849 public void projectionChanged(Projection oldValue, Projection newValue) {
850 // No reprojection required. The dataset itself is registered as projection
851 // change listener and already got notified.
852 }
853
854 @Override
855 public final boolean isUploadDiscouraged() {
856 return data.isUploadDiscouraged();
857 }
858
859 /**
860 * Sets the "discouraged upload" flag.
861 * @param uploadDiscouraged {@code true} if upload of data managed by this layer is discouraged. This feature allows to use "private" data layers.
862 */
863 public final void setUploadDiscouraged(boolean uploadDiscouraged) {
864 if (uploadDiscouraged ^ isUploadDiscouraged()) {
865 data.setUploadDiscouraged(uploadDiscouraged);
866 for (LayerStateChangeListener l : layerStateChangeListeners) {
867 l.uploadDiscouragedChanged(this, uploadDiscouraged);
868 }
869 }
870 }
871
872 @Override
873 public final boolean isModified() {
874 return data.isModified();
875 }
876
877 @Override
878 public boolean isSavable() {
879 return true; // With OsmExporter
880 }
881
882 @Override
883 public boolean checkSaveConditions() {
884 if (isDataSetEmpty()) {
885 if (1 != GuiHelper.runInEDTAndWaitAndReturn(new Callable<Integer>() {
886 @Override
887 public Integer call() {
888 ExtendedDialog dialog = new ExtendedDialog(
889 Main.parent,
890 tr("Empty document"),
891 new String[] {tr("Save anyway"), tr("Cancel")}
892 );
893 dialog.setContent(tr("The document contains no data."));
894 dialog.setButtonIcons(new String[] {"save", "cancel"});
895 return dialog.showDialog().getValue();
896 }
897 })) {
898 return false;
899 }
900 }
901
902 ConflictCollection conflicts = getConflicts();
903 if (conflicts != null && !conflicts.isEmpty()) {
904 if (1 != GuiHelper.runInEDTAndWaitAndReturn(new Callable<Integer>() {
905 @Override
906 public Integer call() {
907 ExtendedDialog dialog = new ExtendedDialog(
908 Main.parent,
909 /* I18N: Display title of the window showing conflicts */
910 tr("Conflicts"),
911 new String[] {tr("Reject Conflicts and Save"), tr("Cancel")}
912 );
913 dialog.setContent(
914 tr("There are unresolved conflicts. Conflicts will not be saved and handled as if you rejected all. Continue?"));
915 dialog.setButtonIcons(new String[] {"save", "cancel"});
916 return dialog.showDialog().getValue();
917 }
918 })) {
919 return false;
920 }
921 }
922 return true;
923 }
924
925 /**
926 * Check the data set if it would be empty on save. It is empty, if it contains
927 * no objects (after all objects that are created and deleted without being
928 * transferred to the server have been removed).
929 *
930 * @return <code>true</code>, if a save result in an empty data set.
931 */
932 private boolean isDataSetEmpty() {
933 if (data != null) {
934 for (OsmPrimitive osm : data.allNonDeletedPrimitives())
935 if (!osm.isDeleted() || !osm.isNewOrUndeleted())
936 return false;
937 }
938 return true;
939 }
940
941 @Override
942 public File createAndOpenSaveFileChooser() {
943 return SaveActionBase.createAndOpenSaveFileChooser(tr("Save OSM file"), "osm");
944 }
945
946 @Override
947 public AbstractIOTask createUploadTask(final ProgressMonitor monitor) {
948 UploadDialog dialog = UploadDialog.getUploadDialog();
949 return new UploadLayerTask(
950 dialog.getUploadStrategySpecification(),
951 this,
952 monitor,
953 dialog.getChangeset());
954 }
955
956 @Override
957 public AbstractUploadDialog getUploadDialog() {
958 UploadDialog dialog = UploadDialog.getUploadDialog();
959 dialog.setUploadedPrimitives(new APIDataSet(data));
960 return dialog;
961 }
962}
Note: See TracBrowser for help on using the repository browser.