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

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

sonar - fb-contrib - minor performance improvements:

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