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

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

remove deprecated stuff - gsoc-core

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