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

Last change on this file since 11710 was 11710, checked in by bastiK, 7 years ago

see #12731 - make enum field final + fix compiler warning

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