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

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

fix copyright/license headers globally

  • 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
409 Area a = data.getDataSourceArea();
410
411 // copy the merged layer's data source info.
412 // only add source rectangles if they are not contained in the layer already.
413 for (DataSource src : from.dataSources) {
414 if (a == null || !a.contains(src.bounds.asRect())) {
415 data.dataSources.add(src);
416 }
417 }
418
419 // copy the merged layer's API version
420 if (data.getVersion() == null) {
421 data.setVersion(from.getVersion());
422 }
423
424 int numNewConflicts = 0;
425 for (Conflict<?> c : visitor.getConflicts()) {
426 if (!conflicts.hasConflict(c)) {
427 numNewConflicts++;
428 conflicts.add(c);
429 }
430 }
431 // repaint to make sure new data is displayed properly.
432 if (Main.isDisplayingMapView()) {
433 Main.map.mapView.repaint();
434 }
435 // warn about new conflicts
436 if (numNewConflicts > 0 && Main.map != null && Main.map.conflictDialog != null) {
437 Main.map.conflictDialog.warnNumNewConflicts(numNewConflicts);
438 }
439 }
440
441 @Override 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 public void visitBoundingBox(final BoundingXYVisitor v) {
447 for (final Node n: data.getNodes()) {
448 if (n.isUsable()) {
449 v.visit(n);
450 }
451 }
452 }
453
454 /**
455 * Clean out the data behind the layer. This means clearing the redo/undo lists,
456 * really deleting all deleted objects and reset the modified flags. This should
457 * be done after an upload, even after a partial upload.
458 *
459 * @param processed A list of all objects that were actually uploaded.
460 * May be <code>null</code>, which means nothing has been uploaded
461 */
462 public void cleanupAfterUpload(final Collection<IPrimitive> processed) {
463 // return immediately if an upload attempt failed
464 if (processed == null || processed.isEmpty())
465 return;
466
467 Main.main.undoRedo.clean(this);
468
469 // if uploaded, clean the modified flags as well
470 data.cleanupDeletedPrimitives();
471 for (OsmPrimitive p: data.allPrimitives()) {
472 if (processed.contains(p)) {
473 p.setModified(false);
474 }
475 }
476 }
477
478
479 @Override public Object getInfoComponent() {
480 final DataCountVisitor counter = new DataCountVisitor();
481 for (final OsmPrimitive osm : data.allPrimitives()) {
482 osm.accept(counter);
483 }
484 final JPanel p = new JPanel(new GridBagLayout());
485
486 String nodeText = trn("{0} node", "{0} nodes", counter.nodes, counter.nodes);
487 if (counter.deletedNodes > 0) {
488 nodeText += " ("+trn("{0} deleted", "{0} deleted", counter.deletedNodes, counter.deletedNodes)+")";
489 }
490
491 String wayText = trn("{0} way", "{0} ways", counter.ways, counter.ways);
492 if (counter.deletedWays > 0) {
493 wayText += " ("+trn("{0} deleted", "{0} deleted", counter.deletedWays, counter.deletedWays)+")";
494 }
495
496 String relationText = trn("{0} relation", "{0} relations", counter.relations, counter.relations);
497 if (counter.deletedRelations > 0) {
498 relationText += " ("+trn("{0} deleted", "{0} deleted", counter.deletedRelations, counter.deletedRelations)+")";
499 }
500
501 p.add(new JLabel(tr("{0} consists of:", getName())), GBC.eol());
502 p.add(new JLabel(nodeText, ImageProvider.get("data", "node"), JLabel.HORIZONTAL), GBC.eop().insets(15,0,0,0));
503 p.add(new JLabel(wayText, ImageProvider.get("data", "way"), JLabel.HORIZONTAL), GBC.eop().insets(15,0,0,0));
504 p.add(new JLabel(relationText, ImageProvider.get("data", "relation"), JLabel.HORIZONTAL), GBC.eop().insets(15,0,0,0));
505 p.add(new JLabel(tr("API version: {0}", (data.getVersion() != null) ? data.getVersion() : tr("unset"))), GBC.eop().insets(15,0,0,0));
506 if (isUploadDiscouraged()) {
507 p.add(new JLabel(tr("Upload is discouraged")), GBC.eop().insets(15,0,0,0));
508 }
509
510 return p;
511 }
512
513 @Override public Action[] getMenuEntries() {
514 List<Action> actions = new ArrayList<>();
515 actions.addAll(Arrays.asList(new Action[]{
516 LayerListDialog.getInstance().createActivateLayerAction(this),
517 LayerListDialog.getInstance().createShowHideLayerAction(),
518 LayerListDialog.getInstance().createDeleteLayerAction(),
519 SeparatorLayerAction.INSTANCE,
520 LayerListDialog.getInstance().createMergeLayerAction(this),
521 new LayerSaveAction(this),
522 new LayerSaveAsAction(this),
523 }));
524 if (ExpertToggleAction.isExpert()) {
525 actions.addAll(Arrays.asList(new Action[]{
526 new LayerGpxExportAction(this),
527 new ConvertToGpxLayerAction()}));
528 }
529 actions.addAll(Arrays.asList(new Action[]{
530 SeparatorLayerAction.INSTANCE,
531 new RenameLayerAction(getAssociatedFile(), this)}));
532 if (ExpertToggleAction.isExpert() && Main.pref.getBoolean("data.layer.upload_discouragement.menu_item", false)) {
533 actions.add(new ToggleUploadDiscouragedLayerAction(this));
534 }
535 actions.addAll(Arrays.asList(new Action[]{
536 new ConsistencyTestAction(),
537 SeparatorLayerAction.INSTANCE,
538 new LayerListPopup.InfoAction(this)}));
539 return actions.toArray(new Action[actions.size()]);
540 }
541
542 /**
543 * Converts given OSM dataset to GPX data.
544 * @param data OSM dataset
545 * @param file output .gpx file
546 * @return GPX data
547 */
548 public static GpxData toGpxData(DataSet data, File file) {
549 GpxData gpxData = new GpxData();
550 gpxData.storageFile = file;
551 Set<Node> doneNodes = new HashSet<>();
552 waysToGpxData(data.getWays(), gpxData, doneNodes);
553 nodesToGpxData(data.getNodes(), gpxData, doneNodes);
554 return gpxData;
555 }
556
557 private static void waysToGpxData(Collection<Way> ways, GpxData gpxData, Set<Node> doneNodes) {
558 for (Way w : ways) {
559 if (!w.isUsable()) {
560 continue;
561 }
562 Collection<Collection<WayPoint>> trk = new ArrayList<>();
563 Map<String, Object> trkAttr = new HashMap<>();
564
565 if (w.get("name") != null) {
566 trkAttr.put("name", w.get("name"));
567 }
568
569 List<WayPoint> trkseg = null;
570 for (Node n : w.getNodes()) {
571 if (!n.isUsable()) {
572 trkseg = null;
573 continue;
574 }
575 if (trkseg == null) {
576 trkseg = new ArrayList<>();
577 trk.add(trkseg);
578 }
579 if (!n.isTagged()) {
580 doneNodes.add(n);
581 }
582 trkseg.add(nodeToWayPoint(n));
583 }
584
585 gpxData.tracks.add(new ImmutableGpxTrack(trk, trkAttr));
586 }
587 }
588
589 private static WayPoint nodeToWayPoint(Node n) {
590 WayPoint wpt = new WayPoint(n.getCoor());
591
592 // Position info
593
594 addDoubleIfPresent(wpt, n, GpxConstants.PT_ELE);
595
596 if (!n.isTimestampEmpty()) {
597 wpt.put("time", DateUtils.fromDate(n.getTimestamp()));
598 wpt.setTime();
599 }
600
601 addDoubleIfPresent(wpt, n, GpxConstants.PT_MAGVAR);
602 addDoubleIfPresent(wpt, n, GpxConstants.PT_GEOIDHEIGHT);
603
604 // Description info
605
606 addStringIfPresent(wpt, n, GpxConstants.GPX_NAME);
607 addStringIfPresent(wpt, n, GpxConstants.GPX_DESC, "description");
608 addStringIfPresent(wpt, n, GpxConstants.GPX_CMT, "comment");
609 addStringIfPresent(wpt, n, GpxConstants.GPX_SRC, "source", "source:position");
610
611 Collection<GpxLink> links = new ArrayList<>();
612 for (String key : new String[]{"link", "url", "website", "contact:website"}) {
613 String value = n.get(key);
614 if (value != null) {
615 links.add(new GpxLink(value));
616 }
617 }
618 wpt.put(GpxConstants.META_LINKS, links);
619
620 addStringIfPresent(wpt, n, GpxConstants.PT_SYM, "wpt_symbol");
621 addStringIfPresent(wpt, n, GpxConstants.PT_TYPE);
622
623 // Accuracy info
624 addStringIfPresent(wpt, n, GpxConstants.PT_FIX, "gps:fix");
625 addIntegerIfPresent(wpt, n, GpxConstants.PT_SAT, "gps:sat");
626 addDoubleIfPresent(wpt, n, GpxConstants.PT_HDOP, "gps:hdop");
627 addDoubleIfPresent(wpt, n, GpxConstants.PT_VDOP, "gps:vdop");
628 addDoubleIfPresent(wpt, n, GpxConstants.PT_PDOP, "gps:pdop");
629 addDoubleIfPresent(wpt, n, GpxConstants.PT_AGEOFDGPSDATA, "gps:ageofdgpsdata");
630 addIntegerIfPresent(wpt, n, GpxConstants.PT_DGPSID, "gps:dgpsid");
631
632 return wpt;
633 }
634
635 private static void nodesToGpxData(Collection<Node> nodes, GpxData gpxData, Set<Node> doneNodes) {
636 List<Node> sortedNodes = new ArrayList<>(nodes);
637 sortedNodes.removeAll(doneNodes);
638 Collections.sort(sortedNodes);
639 for (Node n : sortedNodes) {
640 if (n.isIncomplete() || n.isDeleted()) {
641 continue;
642 }
643 gpxData.waypoints.add(nodeToWayPoint(n));
644 }
645 }
646
647 private static void addIntegerIfPresent(WayPoint wpt, OsmPrimitive p, String gpxKey, String ... osmKeys) {
648 List<String> possibleKeys = new ArrayList<>(Arrays.asList(osmKeys));
649 possibleKeys.add(0, gpxKey);
650 for (String key : possibleKeys) {
651 String value = p.get(key);
652 if (value != null) {
653 try {
654 int i = Integer.parseInt(value);
655 // Sanity checks
656 if ((!GpxConstants.PT_SAT.equals(gpxKey) || i >= 0) &&
657 (!GpxConstants.PT_DGPSID.equals(gpxKey) || (0 <= i && i <= 1023))) {
658 wpt.put(gpxKey, value);
659 break;
660 }
661 } catch (NumberFormatException e) {
662 if (Main.isTraceEnabled()) {
663 Main.trace(e.getMessage());
664 }
665 }
666 }
667 }
668 }
669
670 private static void addDoubleIfPresent(WayPoint wpt, OsmPrimitive p, String gpxKey, String ... osmKeys) {
671 List<String> possibleKeys = new ArrayList<>(Arrays.asList(osmKeys));
672 possibleKeys.add(0, gpxKey);
673 for (String key : possibleKeys) {
674 String value = p.get(key);
675 if (value != null) {
676 try {
677 double d = Double.parseDouble(value);
678 // Sanity checks
679 if (!GpxConstants.PT_MAGVAR.equals(gpxKey) || (0.0 <= d && d < 360.0)) {
680 wpt.put(gpxKey, value);
681 break;
682 }
683 } catch (NumberFormatException e) {
684 if (Main.isTraceEnabled()) {
685 Main.trace(e.getMessage());
686 }
687 }
688 }
689 }
690 }
691
692 private static void addStringIfPresent(WayPoint wpt, OsmPrimitive p, String gpxKey, String ... osmKeys) {
693 List<String> possibleKeys = new ArrayList<>(Arrays.asList(osmKeys));
694 possibleKeys.add(0, gpxKey);
695 for (String key : possibleKeys) {
696 String value = p.get(key);
697 if (value != null) {
698 // Sanity checks
699 if (!GpxConstants.PT_FIX.equals(gpxKey) || GpxConstants.FIX_VALUES.contains(value)) {
700 wpt.put(gpxKey, value);
701 break;
702 }
703 }
704 }
705 }
706
707 /**
708 * Converts OSM data behind this layer to GPX data.
709 * @return GPX data
710 */
711 public GpxData toGpxData() {
712 return toGpxData(data, getAssociatedFile());
713 }
714
715 /**
716 * Action that converts this OSM layer to a GPX layer.
717 */
718 public class ConvertToGpxLayerAction extends AbstractAction {
719 /**
720 * Constructs a new {@code ConvertToGpxLayerAction}.
721 */
722 public ConvertToGpxLayerAction() {
723 super(tr("Convert to GPX layer"), ImageProvider.get("converttogpx"));
724 putValue("help", ht("/Action/ConvertToGpxLayer"));
725 }
726 @Override
727 public void actionPerformed(ActionEvent e) {
728 Main.main.addLayer(new GpxLayer(toGpxData(), tr("Converted from: {0}", getName())));
729 Main.main.removeLayer(OsmDataLayer.this);
730 }
731 }
732
733 /**
734 * Determines if this layer contains data at the given coordinate.
735 * @param coor the coordinate
736 * @return {@code true} if data sources bounding boxes contain {@code coor}
737 */
738 public boolean containsPoint(LatLon coor) {
739 // we'll assume that if this has no data sources
740 // that it also has no borders
741 if (this.data.dataSources.isEmpty())
742 return true;
743
744 boolean layer_bounds_point = false;
745 for (DataSource src : this.data.dataSources) {
746 if (src.bounds.contains(coor)) {
747 layer_bounds_point = true;
748 break;
749 }
750 }
751 return layer_bounds_point;
752 }
753
754 /**
755 * Replies the set of conflicts currently managed in this layer.
756 *
757 * @return the set of conflicts currently managed in this layer
758 */
759 public ConflictCollection getConflicts() {
760 return conflicts;
761 }
762
763 @Override
764 public boolean requiresUploadToServer() {
765 return requiresUploadToServer;
766 }
767
768 @Override
769 public boolean requiresSaveToFile() {
770 return getAssociatedFile() != null && requiresSaveToFile;
771 }
772
773 @Override
774 public void onPostLoadFromFile() {
775 setRequiresSaveToFile(false);
776 setRequiresUploadToServer(isModified());
777 }
778
779 /**
780 * Actions run after data has been downloaded to this layer.
781 */
782 public void onPostDownloadFromServer() {
783 setRequiresSaveToFile(true);
784 setRequiresUploadToServer(isModified());
785 }
786
787 @Override
788 public boolean isChanged() {
789 return isChanged || highlightUpdateCount != data.getHighlightUpdateCount();
790 }
791
792 @Override
793 public void onPostSaveToFile() {
794 setRequiresSaveToFile(false);
795 setRequiresUploadToServer(isModified());
796 }
797
798 @Override
799 public void onPostUploadToServer() {
800 setRequiresUploadToServer(isModified());
801 // keep requiresSaveToDisk unchanged
802 }
803
804 private class ConsistencyTestAction extends AbstractAction {
805
806 public ConsistencyTestAction() {
807 super(tr("Dataset consistency test"));
808 }
809
810 @Override
811 public void actionPerformed(ActionEvent e) {
812 String result = DatasetConsistencyTest.runTests(data);
813 if (result.length() == 0) {
814 JOptionPane.showMessageDialog(Main.parent, tr("No problems found"));
815 } else {
816 JPanel p = new JPanel(new GridBagLayout());
817 p.add(new JLabel(tr("Following problems found:")), GBC.eol());
818 JosmTextArea info = new JosmTextArea(result, 20, 60);
819 info.setCaretPosition(0);
820 info.setEditable(false);
821 p.add(new JScrollPane(info), GBC.eop());
822
823 JOptionPane.showMessageDialog(Main.parent, p, tr("Warning"), JOptionPane.WARNING_MESSAGE);
824 }
825 }
826 }
827
828 @Override
829 public void destroy() {
830 DataSet.removeSelectionListener(this);
831 }
832
833 @Override
834 public void processDatasetEvent(AbstractDatasetChangedEvent event) {
835 isChanged = true;
836 setRequiresSaveToFile(true);
837 setRequiresUploadToServer(true);
838 }
839
840 @Override
841 public void selectionChanged(Collection<? extends OsmPrimitive> newSelection) {
842 isChanged = true;
843 }
844
845 @Override
846 public void projectionChanged(Projection oldValue, Projection newValue) {
847 // No reprojection required. The dataset itself is registered as projection
848 // change listener and already got notified.
849 }
850
851 @Override
852 public final boolean isUploadDiscouraged() {
853 return data.isUploadDiscouraged();
854 }
855
856 /**
857 * Sets the "discouraged upload" flag.
858 * @param uploadDiscouraged {@code true} if upload of data managed by this layer is discouraged. This feature allows to use "private" data layers.
859 */
860 public final void setUploadDiscouraged(boolean uploadDiscouraged) {
861 if (uploadDiscouraged ^ isUploadDiscouraged()) {
862 data.setUploadDiscouraged(uploadDiscouraged);
863 for (LayerStateChangeListener l : layerStateChangeListeners) {
864 l.uploadDiscouragedChanged(this, uploadDiscouraged);
865 }
866 }
867 }
868
869 @Override
870 public final boolean isModified() {
871 return data.isModified();
872 }
873
874 @Override
875 public boolean isSavable() {
876 return true; // With OsmExporter
877 }
878
879 @Override
880 public boolean checkSaveConditions() {
881 if (isDataSetEmpty()) {
882 if (1 != GuiHelper.runInEDTAndWaitAndReturn(new Callable<Integer>() {
883 @Override
884 public Integer call() {
885 ExtendedDialog dialog = new ExtendedDialog(
886 Main.parent,
887 tr("Empty document"),
888 new String[] {tr("Save anyway"), tr("Cancel")}
889 );
890 dialog.setContent(tr("The document contains no data."));
891 dialog.setButtonIcons(new String[] {"save", "cancel"});
892 return dialog.showDialog().getValue();
893 }
894 })) {
895 return false;
896 }
897 }
898
899 ConflictCollection conflicts = getConflicts();
900 if (conflicts != null && !conflicts.isEmpty()) {
901 if (1 != GuiHelper.runInEDTAndWaitAndReturn(new Callable<Integer>() {
902 @Override
903 public Integer call() {
904 ExtendedDialog dialog = new ExtendedDialog(
905 Main.parent,
906 /* I18N: Display title of the window showing conflicts */
907 tr("Conflicts"),
908 new String[] {tr("Reject Conflicts and Save"), tr("Cancel")}
909 );
910 dialog.setContent(tr("There are unresolved conflicts. Conflicts will not be saved and handled as if you rejected all. Continue?"));
911 dialog.setButtonIcons(new String[] {"save", "cancel"});
912 return dialog.showDialog().getValue();
913 }
914 })) {
915 return false;
916 }
917 }
918 return true;
919 }
920
921 /**
922 * Check the data set if it would be empty on save. It is empty, if it contains
923 * no objects (after all objects that are created and deleted without being
924 * transferred to the server have been removed).
925 *
926 * @return <code>true</code>, if a save result in an empty data set.
927 */
928 private boolean isDataSetEmpty() {
929 if (data != null) {
930 for (OsmPrimitive osm : data.allNonDeletedPrimitives())
931 if (!osm.isDeleted() || !osm.isNewOrUndeleted())
932 return false;
933 }
934 return true;
935 }
936
937 @Override
938 public File createAndOpenSaveFileChooser() {
939 return SaveActionBase.createAndOpenSaveFileChooser(tr("Save OSM file"), "osm");
940 }
941
942 @Override
943 public AbstractIOTask createUploadTask(final ProgressMonitor monitor) {
944 UploadDialog dialog = UploadDialog.getUploadDialog();
945 return new UploadLayerTask(
946 dialog.getUploadStrategySpecification(),
947 this,
948 monitor,
949 dialog.getChangeset());
950 }
951
952 @Override
953 public AbstractUploadDialog getUploadDialog() {
954 UploadDialog dialog = UploadDialog.getUploadDialog();
955 dialog.setUploadedPrimitives(new APIDataSet(data));
956 return dialog;
957 }
958}
Note: See TracBrowser for help on using the repository browser.