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

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

sonar - pmd:UseStringBufferForStringAppends

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