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

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

sonar - fix recently added warnings

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