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

Last change on this file since 9857 was 9751, checked in by Don-vip, 8 years ago

see #12462 - Extend Save Layers dialog for more layer types (patch by holgermappt, modified for checkstyle compliance)

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