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

Last change on this file since 8323 was 8323, checked in by stoecker, 9 years ago

see #10684 - remove remaining overlay() calls

  • Property svn:eol-style set to native
File size: 34.7 KB
Line 
1// License: GPL. See LICENSE file for details.
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.Image;
15import java.awt.Point;
16import java.awt.Rectangle;
17import java.awt.TexturePaint;
18import java.awt.event.ActionEvent;
19import java.awt.geom.Area;
20import java.awt.image.BufferedImage;
21import java.io.File;
22import java.util.ArrayList;
23import java.util.Arrays;
24import java.util.Collection;
25import java.util.Collections;
26import java.util.HashMap;
27import java.util.HashSet;
28import java.util.List;
29import java.util.Map;
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.ImageIcon;
37import javax.swing.JLabel;
38import javax.swing.JOptionPane;
39import javax.swing.JPanel;
40import javax.swing.JScrollPane;
41
42import org.openstreetmap.josm.Main;
43import org.openstreetmap.josm.actions.ExpertToggleAction;
44import org.openstreetmap.josm.actions.RenameLayerAction;
45import org.openstreetmap.josm.actions.SaveActionBase;
46import org.openstreetmap.josm.actions.ToggleUploadDiscouragedLayerAction;
47import org.openstreetmap.josm.data.APIDataSet;
48import org.openstreetmap.josm.data.Bounds;
49import org.openstreetmap.josm.data.DataSource;
50import org.openstreetmap.josm.data.SelectionChangedListener;
51import org.openstreetmap.josm.data.conflict.Conflict;
52import org.openstreetmap.josm.data.conflict.ConflictCollection;
53import org.openstreetmap.josm.data.coor.LatLon;
54import org.openstreetmap.josm.data.gpx.GpxConstants;
55import org.openstreetmap.josm.data.gpx.GpxData;
56import org.openstreetmap.josm.data.gpx.GpxLink;
57import org.openstreetmap.josm.data.gpx.ImmutableGpxTrack;
58import org.openstreetmap.josm.data.gpx.WayPoint;
59import org.openstreetmap.josm.data.osm.DataIntegrityProblemException;
60import org.openstreetmap.josm.data.osm.DataSet;
61import org.openstreetmap.josm.data.osm.DataSetMerger;
62import org.openstreetmap.josm.data.osm.DatasetConsistencyTest;
63import org.openstreetmap.josm.data.osm.IPrimitive;
64import org.openstreetmap.josm.data.osm.Node;
65import org.openstreetmap.josm.data.osm.OsmPrimitive;
66import org.openstreetmap.josm.data.osm.Relation;
67import org.openstreetmap.josm.data.osm.Way;
68import org.openstreetmap.josm.data.osm.event.AbstractDatasetChangedEvent;
69import org.openstreetmap.josm.data.osm.event.DataSetListenerAdapter;
70import org.openstreetmap.josm.data.osm.event.DataSetListenerAdapter.Listener;
71import org.openstreetmap.josm.data.osm.visitor.AbstractVisitor;
72import org.openstreetmap.josm.data.osm.visitor.BoundingXYVisitor;
73import org.openstreetmap.josm.data.osm.visitor.paint.MapRendererFactory;
74import org.openstreetmap.josm.data.osm.visitor.paint.Rendering;
75import org.openstreetmap.josm.data.osm.visitor.paint.relations.MultipolygonCache;
76import org.openstreetmap.josm.data.projection.Projection;
77import org.openstreetmap.josm.data.validation.TestError;
78import org.openstreetmap.josm.gui.ExtendedDialog;
79import org.openstreetmap.josm.gui.MapView;
80import org.openstreetmap.josm.gui.dialogs.LayerListDialog;
81import org.openstreetmap.josm.gui.dialogs.LayerListPopup;
82import org.openstreetmap.josm.gui.io.AbstractIOTask;
83import org.openstreetmap.josm.gui.io.AbstractUploadDialog;
84import org.openstreetmap.josm.gui.io.UploadDialog;
85import org.openstreetmap.josm.gui.io.UploadLayerTask;
86import org.openstreetmap.josm.gui.progress.PleaseWaitProgressMonitor;
87import org.openstreetmap.josm.gui.progress.ProgressMonitor;
88import org.openstreetmap.josm.gui.util.GuiHelper;
89import org.openstreetmap.josm.gui.widgets.JosmTextArea;
90import org.openstreetmap.josm.tools.FilteredCollection;
91import org.openstreetmap.josm.tools.GBC;
92import org.openstreetmap.josm.tools.ImageOverlay;
93import org.openstreetmap.josm.tools.ImageProvider;
94import org.openstreetmap.josm.tools.ImageProvider.ImageSizes;
95import org.openstreetmap.josm.tools.date.DateUtils;
96
97/**
98 * A layer that holds OSM data from a specific dataset.
99 * The data can be fully edited.
100 *
101 * @author imi
102 * @since 17
103 */
104public class OsmDataLayer extends AbstractModifiableLayer implements Listener, SelectionChangedListener {
105 /** Property used to know if this layer has to be saved on disk */
106 public static final String REQUIRES_SAVE_TO_DISK_PROP = OsmDataLayer.class.getName() + ".requiresSaveToDisk";
107 /** Property used to know if this layer has to be uploaded */
108 public static final String REQUIRES_UPLOAD_TO_SERVER_PROP = OsmDataLayer.class.getName() + ".requiresUploadToServer";
109
110 private boolean requiresSaveToFile = false;
111 private boolean requiresUploadToServer = false;
112 private boolean isChanged = true;
113 private int highlightUpdateCount;
114
115 /**
116 * List of validation errors in this layer.
117 * @since 3669
118 */
119 public final List<TestError> validationErrors = new ArrayList<>();
120
121 protected void setRequiresSaveToFile(boolean newValue) {
122 boolean oldValue = requiresSaveToFile;
123 requiresSaveToFile = newValue;
124 if (oldValue != newValue) {
125 propertyChangeSupport.firePropertyChange(REQUIRES_SAVE_TO_DISK_PROP, oldValue, newValue);
126 }
127 }
128
129 protected void setRequiresUploadToServer(boolean newValue) {
130 boolean oldValue = requiresUploadToServer;
131 requiresUploadToServer = newValue;
132 if (oldValue != newValue) {
133 propertyChangeSupport.firePropertyChange(REQUIRES_UPLOAD_TO_SERVER_PROP, oldValue, newValue);
134 }
135 }
136
137 /** the global counter for created data layers */
138 private static int dataLayerCounter = 0;
139
140 /**
141 * Replies a new unique name for a data layer
142 *
143 * @return a new unique name for a data layer
144 */
145 public static String createNewName() {
146 dataLayerCounter++;
147 return tr("Data Layer {0}", dataLayerCounter);
148 }
149
150 public static final class DataCountVisitor extends AbstractVisitor {
151 public int nodes;
152 public int ways;
153 public int relations;
154 public int deletedNodes;
155 public int deletedWays;
156 public int deletedRelations;
157
158 @Override
159 public void visit(final Node n) {
160 nodes++;
161 if (n.isDeleted()) {
162 deletedNodes++;
163 }
164 }
165
166 @Override
167 public void visit(final Way w) {
168 ways++;
169 if (w.isDeleted()) {
170 deletedWays++;
171 }
172 }
173
174 @Override
175 public void visit(final Relation r) {
176 relations++;
177 if (r.isDeleted()) {
178 deletedRelations++;
179 }
180 }
181 }
182
183 public interface CommandQueueListener {
184 void commandChanged(int queueSize, int redoSize);
185 }
186
187 /**
188 * Listener called when a state of this layer has changed.
189 */
190 public interface LayerStateChangeListener {
191 /**
192 * Notifies that the "upload discouraged" (upload=no) state has changed.
193 * @param layer The layer that has been modified
194 * @param newValue The new value of the state
195 */
196 void uploadDiscouragedChanged(OsmDataLayer layer, boolean newValue);
197 }
198
199 private final CopyOnWriteArrayList<LayerStateChangeListener> layerStateChangeListeners = new CopyOnWriteArrayList<>();
200
201 /**
202 * Adds a layer state change listener
203 *
204 * @param listener the listener. Ignored if null or already registered.
205 * @since 5519
206 */
207 public void addLayerStateChangeListener(LayerStateChangeListener listener) {
208 if (listener != null) {
209 layerStateChangeListeners.addIfAbsent(listener);
210 }
211 }
212
213 /**
214 * Removes a layer property change listener
215 *
216 * @param listener the listener. Ignored if null or already registered.
217 * @since 5519
218 */
219 public void removeLayerPropertyChangeListener(LayerStateChangeListener listener) {
220 layerStateChangeListeners.remove(listener);
221 }
222
223 /**
224 * The data behind this layer.
225 */
226 public final DataSet data;
227
228 /**
229 * the collection of conflicts detected in this layer
230 */
231 private ConflictCollection conflicts;
232
233 /**
234 * a paint texture for non-downloaded area
235 */
236 private static volatile TexturePaint hatched;
237
238 static {
239 createHatchTexture();
240 }
241
242 /**
243 * Replies background color for downloaded areas.
244 * @return background color for downloaded areas. Black by default
245 */
246 public static Color getBackgroundColor() {
247 return Main.pref.getColor(marktr("background"), Color.BLACK);
248 }
249
250 /**
251 * Replies background color for non-downloaded areas.
252 * @return background color for non-downloaded areas. Yellow by default
253 */
254 public static Color getOutsideColor() {
255 return Main.pref.getColor(marktr("outside downloaded area"), Color.YELLOW);
256 }
257
258 /**
259 * Initialize the hatch pattern used to paint the non-downloaded area
260 */
261 public static void createHatchTexture() {
262 BufferedImage bi = new BufferedImage(15, 15, BufferedImage.TYPE_INT_ARGB);
263 Graphics2D big = bi.createGraphics();
264 big.setColor(getBackgroundColor());
265 Composite comp = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.3f);
266 big.setComposite(comp);
267 big.fillRect(0,0,15,15);
268 big.setColor(getOutsideColor());
269 big.drawLine(0,15,15,0);
270 Rectangle r = new Rectangle(0, 0, 15,15);
271 hatched = new TexturePaint(bi, r);
272 }
273
274 /**
275 * Construct a new {@code OsmDataLayer}.
276 * @param data OSM data
277 * @param name Layer name
278 * @param associatedFile Associated .osm file (can be null)
279 */
280 public OsmDataLayer(final DataSet data, final String name, final File associatedFile) {
281 super(name);
282 this.data = data;
283 this.setAssociatedFile(associatedFile);
284 conflicts = new ConflictCollection();
285 data.addDataSetListener(new DataSetListenerAdapter(this));
286 data.addDataSetListener(MultipolygonCache.getInstance());
287 DataSet.addSelectionListener(this);
288 }
289
290 /**
291 * Return the image provider to get the base icon
292 * @return image provider class which can be modified
293 * @since 8323
294 */
295 protected ImageProvider getBaseIconProvider() {
296 return new ImageProvider("layer", "osmdata_small");
297 }
298
299 @Override
300 public Icon getIcon() {
301 ImageProvider base = getBaseIconProvider().setMaxSize(ImageSizes.LAYER);
302 if (isUploadDiscouraged()) {
303 base.addOverlay(new ImageOverlay(new ImageProvider("warning-small"), 0.5, 0.5, 1.0, 1.0));
304 }
305 return base.get();
306 }
307
308 /**
309 * Draw all primitives in this layer but do not draw modified ones (they
310 * are drawn by the edit layer).
311 * Draw nodes last to overlap the ways they belong to.
312 */
313 @Override public void paint(final Graphics2D g, final MapView mv, Bounds box) {
314 isChanged = false;
315 highlightUpdateCount = data.getHighlightUpdateCount();
316
317 boolean active = mv.getActiveLayer() == this;
318 boolean inactive = !active && Main.pref.getBoolean("draw.data.inactive_color", true);
319 boolean virtual = !inactive && mv.isVirtualNodesEnabled();
320
321 // draw the hatched area for non-downloaded region. only draw if we're the active
322 // and bounds are defined; don't draw for inactive layers or loaded GPX files etc
323 if (active && Main.pref.getBoolean("draw.data.downloaded_area", true) && !data.dataSources.isEmpty()) {
324 // initialize area with current viewport
325 Rectangle b = mv.getBounds();
326 // on some platforms viewport bounds seem to be offset from the left,
327 // over-grow it just to be sure
328 b.grow(100, 100);
329 Area a = new Area(b);
330
331 // now successively subtract downloaded areas
332 for (Bounds bounds : data.getDataSourceBounds()) {
333 if (bounds.isCollapsed()) {
334 continue;
335 }
336 Point p1 = mv.getPoint(bounds.getMin());
337 Point p2 = mv.getPoint(bounds.getMax());
338 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));
339 a.subtract(new Area(r));
340 }
341
342 // paint remainder
343 g.setPaint(hatched);
344 g.fill(a);
345 }
346
347 Rendering painter = MapRendererFactory.getInstance().createActiveRenderer(g, mv, inactive);
348 painter.render(data, virtual, box);
349 Main.map.conflictDialog.paintConflicts(g, mv);
350 }
351
352 @Override public String getToolTipText() {
353 int nodes = new FilteredCollection<>(data.getNodes(), OsmPrimitive.nonDeletedPredicate).size();
354 int ways = new FilteredCollection<>(data.getWays(), OsmPrimitive.nonDeletedPredicate).size();
355 int rels = new FilteredCollection<>(data.getRelations(), OsmPrimitive.nonDeletedPredicate).size();
356
357 String tool = trn("{0} node", "{0} nodes", nodes, nodes)+", ";
358 tool += trn("{0} way", "{0} ways", ways, ways)+", ";
359 tool += trn("{0} relation", "{0} relations", rels, rels);
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 trkseg.add(nodeToWayPoint(n));
584 }
585
586 gpxData.tracks.add(new ImmutableGpxTrack(trk, trkAttr));
587 }
588 }
589
590 private static WayPoint nodeToWayPoint(Node n) {
591 WayPoint wpt = new WayPoint(n.getCoor());
592
593 // Position info
594
595 addDoubleIfPresent(wpt, n, GpxConstants.PT_ELE);
596
597 if (!n.isTimestampEmpty()) {
598 wpt.put("time", DateUtils.fromDate(n.getTimestamp()));
599 wpt.setTime();
600 }
601
602 addDoubleIfPresent(wpt, n, GpxConstants.PT_MAGVAR);
603 addDoubleIfPresent(wpt, n, GpxConstants.PT_GEOIDHEIGHT);
604
605 // Description info
606
607 addStringIfPresent(wpt, n, GpxConstants.GPX_NAME);
608 addStringIfPresent(wpt, n, GpxConstants.GPX_DESC, "description");
609 addStringIfPresent(wpt, n, GpxConstants.GPX_CMT, "comment");
610 addStringIfPresent(wpt, n, GpxConstants.GPX_SRC, "source", "source:position");
611
612 Collection<GpxLink> links = new ArrayList<>();
613 for (String key : new String[]{"link", "url", "website", "contact:website"}) {
614 String value = n.get(key);
615 if (value != null) {
616 links.add(new GpxLink(value));
617 }
618 }
619 wpt.put(GpxConstants.META_LINKS, links);
620
621 addStringIfPresent(wpt, n, GpxConstants.PT_SYM, "wpt_symbol");
622 addStringIfPresent(wpt, n, GpxConstants.PT_TYPE);
623
624 // Accuracy info
625 addStringIfPresent(wpt, n, GpxConstants.PT_FIX, "gps:fix");
626 addIntegerIfPresent(wpt, n, GpxConstants.PT_SAT, "gps:sat");
627 addDoubleIfPresent(wpt, n, GpxConstants.PT_HDOP, "gps:hdop");
628 addDoubleIfPresent(wpt, n, GpxConstants.PT_VDOP, "gps:vdop");
629 addDoubleIfPresent(wpt, n, GpxConstants.PT_PDOP, "gps:pdop");
630 addDoubleIfPresent(wpt, n, GpxConstants.PT_AGEOFDGPSDATA, "gps:ageofdgpsdata");
631 addIntegerIfPresent(wpt, n, GpxConstants.PT_DGPSID, "gps:dgpsid");
632
633 return wpt;
634 }
635
636 private static void nodesToGpxData(Collection<Node> nodes, GpxData gpxData, HashSet<Node> doneNodes) {
637 List<Node> sortedNodes = new ArrayList<>(nodes);
638 sortedNodes.removeAll(doneNodes);
639 Collections.sort(sortedNodes);
640 for (Node n : sortedNodes) {
641 if (n.isIncomplete() || n.isDeleted()) {
642 continue;
643 }
644 gpxData.waypoints.add(nodeToWayPoint(n));
645 }
646 }
647
648 private static void addIntegerIfPresent(WayPoint wpt, OsmPrimitive p, String gpxKey, String ... osmKeys) {
649 ArrayList<String> possibleKeys = new ArrayList<>(Arrays.asList(osmKeys));
650 possibleKeys.add(0, gpxKey);
651 for (String key : possibleKeys) {
652 String value = p.get(key);
653 if (value != null) {
654 try {
655 int i = Integer.parseInt(value);
656 // Sanity checks
657 if ((!GpxConstants.PT_SAT.equals(gpxKey) || i >= 0) &&
658 (!GpxConstants.PT_DGPSID.equals(gpxKey) || (0 <= i && i <= 1023))) {
659 wpt.put(gpxKey, value);
660 break;
661 }
662 } catch (NumberFormatException e) {
663 if (Main.isTraceEnabled()) {
664 Main.trace(e.getMessage());
665 }
666 }
667 }
668 }
669 }
670
671 private static void addDoubleIfPresent(WayPoint wpt, OsmPrimitive p, String gpxKey, String ... osmKeys) {
672 ArrayList<String> possibleKeys = new ArrayList<>(Arrays.asList(osmKeys));
673 possibleKeys.add(0, gpxKey);
674 for (String key : possibleKeys) {
675 String value = p.get(key);
676 if (value != null) {
677 try {
678 double d = Double.parseDouble(value);
679 // Sanity checks
680 if (!GpxConstants.PT_MAGVAR.equals(gpxKey) || (0.0 <= d && d < 360.0)) {
681 wpt.put(gpxKey, value);
682 break;
683 }
684 } catch (NumberFormatException e) {
685 if (Main.isTraceEnabled()) {
686 Main.trace(e.getMessage());
687 }
688 }
689 }
690 }
691 }
692
693 private static void addStringIfPresent(WayPoint wpt, OsmPrimitive p, String gpxKey, String ... osmKeys) {
694 ArrayList<String> possibleKeys = new ArrayList<>(Arrays.asList(osmKeys));
695 possibleKeys.add(0, gpxKey);
696 for (String key : possibleKeys) {
697 String value = p.get(key);
698 if (value != null) {
699 // Sanity checks
700 if (!GpxConstants.PT_FIX.equals(gpxKey) || GpxConstants.FIX_VALUES.contains(value)) {
701 wpt.put(gpxKey, value);
702 break;
703 }
704 }
705 }
706 }
707
708 /**
709 * Converts OSM data behind this layer to GPX data.
710 * @return GPX data
711 */
712 public GpxData toGpxData() {
713 return toGpxData(data, getAssociatedFile());
714 }
715
716 /**
717 * Action that converts this OSM layer to a GPX layer.
718 */
719 public class ConvertToGpxLayerAction extends AbstractAction {
720 /**
721 * Constructs a new {@code ConvertToGpxLayerAction}.
722 */
723 public ConvertToGpxLayerAction() {
724 super(tr("Convert to GPX layer"), ImageProvider.get("converttogpx"));
725 putValue("help", ht("/Action/ConvertToGpxLayer"));
726 }
727 @Override
728 public void actionPerformed(ActionEvent e) {
729 Main.main.addLayer(new GpxLayer(toGpxData(), tr("Converted from: {0}", getName())));
730 Main.main.removeLayer(OsmDataLayer.this);
731 }
732 }
733
734 /**
735 * Determines if this layer contains data at the given coordinate.
736 * @param coor the coordinate
737 * @return {@code true} if data sources bounding boxes contain {@code coor}
738 */
739 public boolean containsPoint(LatLon coor) {
740 // we'll assume that if this has no data sources
741 // that it also has no borders
742 if (this.data.dataSources.isEmpty())
743 return true;
744
745 boolean layer_bounds_point = false;
746 for (DataSource src : this.data.dataSources) {
747 if (src.bounds.contains(coor)) {
748 layer_bounds_point = true;
749 break;
750 }
751 }
752 return layer_bounds_point;
753 }
754
755 /**
756 * Replies the set of conflicts currently managed in this layer.
757 *
758 * @return the set of conflicts currently managed in this layer
759 */
760 public ConflictCollection getConflicts() {
761 return conflicts;
762 }
763
764 @Override
765 public boolean requiresUploadToServer() {
766 return requiresUploadToServer;
767 }
768
769 @Override
770 public boolean requiresSaveToFile() {
771 return getAssociatedFile() != null && requiresSaveToFile;
772 }
773
774 @Override
775 public void onPostLoadFromFile() {
776 setRequiresSaveToFile(false);
777 setRequiresUploadToServer(isModified());
778 }
779
780 /**
781 * Actions run after data has been downloaded to this layer.
782 */
783 public void onPostDownloadFromServer() {
784 setRequiresSaveToFile(true);
785 setRequiresUploadToServer(isModified());
786 }
787
788 @Override
789 public boolean isChanged() {
790 return isChanged || highlightUpdateCount != data.getHighlightUpdateCount();
791 }
792
793 @Override
794 public void onPostSaveToFile() {
795 setRequiresSaveToFile(false);
796 setRequiresUploadToServer(isModified());
797 }
798
799 @Override
800 public void onPostUploadToServer() {
801 setRequiresUploadToServer(isModified());
802 // keep requiresSaveToDisk unchanged
803 }
804
805 private class ConsistencyTestAction extends AbstractAction {
806
807 public ConsistencyTestAction() {
808 super(tr("Dataset consistency test"));
809 }
810
811 @Override
812 public void actionPerformed(ActionEvent e) {
813 String result = DatasetConsistencyTest.runTests(data);
814 if (result.length() == 0) {
815 JOptionPane.showMessageDialog(Main.parent, tr("No problems found"));
816 } else {
817 JPanel p = new JPanel(new GridBagLayout());
818 p.add(new JLabel(tr("Following problems found:")), GBC.eol());
819 JosmTextArea info = new JosmTextArea(result, 20, 60);
820 info.setCaretPosition(0);
821 info.setEditable(false);
822 p.add(new JScrollPane(info), GBC.eop());
823
824 JOptionPane.showMessageDialog(Main.parent, p, tr("Warning"), JOptionPane.WARNING_MESSAGE);
825 }
826 }
827 }
828
829 @Override
830 public void destroy() {
831 DataSet.removeSelectionListener(this);
832 }
833
834 @Override
835 public void processDatasetEvent(AbstractDatasetChangedEvent event) {
836 isChanged = true;
837 setRequiresSaveToFile(true);
838 setRequiresUploadToServer(true);
839 }
840
841 @Override
842 public void selectionChanged(Collection<? extends OsmPrimitive> newSelection) {
843 isChanged = true;
844 }
845
846 @Override
847 public void projectionChanged(Projection oldValue, Projection newValue) {
848 // No reprojection required. The dataset itself is registered as projection
849 // change listener and already got notified.
850 }
851
852 @Override
853 public final boolean isUploadDiscouraged() {
854 return data.isUploadDiscouraged();
855 }
856
857 /**
858 * Sets the "discouraged upload" flag.
859 * @param uploadDiscouraged {@code true} if upload of data managed by this layer is discouraged. This feature allows to use "private" data layers.
860 */
861 public final void setUploadDiscouraged(boolean uploadDiscouraged) {
862 if (uploadDiscouraged ^ isUploadDiscouraged()) {
863 data.setUploadDiscouraged(uploadDiscouraged);
864 for (LayerStateChangeListener l : layerStateChangeListeners) {
865 l.uploadDiscouragedChanged(this, uploadDiscouraged);
866 }
867 }
868 }
869
870 @Override
871 public final boolean isModified() {
872 return data.isModified();
873 }
874
875 @Override
876 public boolean isSavable() {
877 return true; // With OsmExporter
878 }
879
880 @Override
881 public boolean checkSaveConditions() {
882 if (isDataSetEmpty()) {
883 if (1 != GuiHelper.runInEDTAndWaitAndReturn(new Callable<Integer>() {
884 @Override
885 public Integer call() {
886 ExtendedDialog dialog = new ExtendedDialog(
887 Main.parent,
888 tr("Empty document"),
889 new String[] {tr("Save anyway"), tr("Cancel")}
890 );
891 dialog.setContent(tr("The document contains no data."));
892 dialog.setButtonIcons(new String[] {"save", "cancel"});
893 return dialog.showDialog().getValue();
894 }
895 })) {
896 return false;
897 }
898 }
899
900 ConflictCollection conflicts = getConflicts();
901 if (conflicts != null && !conflicts.isEmpty()) {
902 if (1 != GuiHelper.runInEDTAndWaitAndReturn(new Callable<Integer>() {
903 @Override
904 public Integer call() {
905 ExtendedDialog dialog = new ExtendedDialog(
906 Main.parent,
907 /* I18N: Display title of the window showing conflicts */
908 tr("Conflicts"),
909 new String[] {tr("Reject Conflicts and Save"), tr("Cancel")}
910 );
911 dialog.setContent(tr("There are unresolved conflicts. Conflicts will not be saved and handled as if you rejected all. Continue?"));
912 dialog.setButtonIcons(new String[] {"save", "cancel"});
913 return dialog.showDialog().getValue();
914 }
915 })) {
916 return false;
917 }
918 }
919 return true;
920 }
921
922 /**
923 * Check the data set if it would be empty on save. It is empty, if it contains
924 * no objects (after all objects that are created and deleted without being
925 * transferred to the server have been removed).
926 *
927 * @return <code>true</code>, if a save result in an empty data set.
928 */
929 private boolean isDataSetEmpty() {
930 if (data != null) {
931 for (OsmPrimitive osm : data.allNonDeletedPrimitives())
932 if (!osm.isDeleted() || !osm.isNewOrUndeleted())
933 return false;
934 }
935 return true;
936 }
937
938 @Override
939 public File createAndOpenSaveFileChooser() {
940 return SaveActionBase.createAndOpenSaveFileChooser(tr("Save OSM file"), "osm");
941 }
942
943 @Override
944 public AbstractIOTask createUploadTask(final ProgressMonitor monitor) {
945 UploadDialog dialog = UploadDialog.getUploadDialog();
946 return new UploadLayerTask(
947 dialog.getUploadStrategySpecification(),
948 this,
949 monitor,
950 dialog.getChangeset());
951 }
952
953 @Override
954 public AbstractUploadDialog getUploadDialog() {
955 UploadDialog dialog = UploadDialog.getUploadDialog();
956 dialog.setUploadedPrimitives(new APIDataSet(data));
957 return dialog;
958 }
959}
Note: See TracBrowser for help on using the repository browser.