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

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

fix #13424 - Remove unneccessary isChanged flag (patch by michael2402, modified) - gsoc-core

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