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

Last change on this file since 9670 was 9670, checked in by bastiK, 8 years ago

applied #12392 - default filename when saving layer (patch by kolesar)

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