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

Last change on this file since 12116 was 12116, checked in by michael2402, 7 years ago

Sonar: Make AbstractListenerInfo an interface.

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