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

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

see #13309 - fix most of deprecation 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.regex.Pattern;
34
35import javax.swing.AbstractAction;
36import javax.swing.Action;
37import javax.swing.Icon;
38import javax.swing.JLabel;
39import javax.swing.JOptionPane;
40import javax.swing.JPanel;
41import javax.swing.JScrollPane;
42
43import org.openstreetmap.josm.Main;
44import org.openstreetmap.josm.actions.ExpertToggleAction;
45import org.openstreetmap.josm.actions.RenameLayerAction;
46import org.openstreetmap.josm.actions.ToggleUploadDiscouragedLayerAction;
47import org.openstreetmap.josm.data.APIDataSet;
48import org.openstreetmap.josm.data.Bounds;
49import org.openstreetmap.josm.data.DataSource;
50import org.openstreetmap.josm.data.ProjectionBounds;
51import org.openstreetmap.josm.data.SelectionChangedListener;
52import org.openstreetmap.josm.data.conflict.Conflict;
53import org.openstreetmap.josm.data.conflict.ConflictCollection;
54import org.openstreetmap.josm.data.coor.EastNorth;
55import org.openstreetmap.josm.data.coor.LatLon;
56import org.openstreetmap.josm.data.gpx.GpxConstants;
57import org.openstreetmap.josm.data.gpx.GpxData;
58import org.openstreetmap.josm.data.gpx.GpxLink;
59import org.openstreetmap.josm.data.gpx.ImmutableGpxTrack;
60import org.openstreetmap.josm.data.gpx.WayPoint;
61import org.openstreetmap.josm.data.osm.DataIntegrityProblemException;
62import org.openstreetmap.josm.data.osm.DataSet;
63import org.openstreetmap.josm.data.osm.DataSetMerger;
64import org.openstreetmap.josm.data.osm.DatasetConsistencyTest;
65import org.openstreetmap.josm.data.osm.IPrimitive;
66import org.openstreetmap.josm.data.osm.Node;
67import org.openstreetmap.josm.data.osm.OsmPrimitive;
68import org.openstreetmap.josm.data.osm.OsmPrimitiveComparator;
69import org.openstreetmap.josm.data.osm.Relation;
70import org.openstreetmap.josm.data.osm.Way;
71import org.openstreetmap.josm.data.osm.event.AbstractDatasetChangedEvent;
72import org.openstreetmap.josm.data.osm.event.DataSetListenerAdapter;
73import org.openstreetmap.josm.data.osm.event.DataSetListenerAdapter.Listener;
74import org.openstreetmap.josm.data.osm.visitor.AbstractVisitor;
75import org.openstreetmap.josm.data.osm.visitor.BoundingXYVisitor;
76import org.openstreetmap.josm.data.osm.visitor.paint.MapRendererFactory;
77import org.openstreetmap.josm.data.osm.visitor.paint.Rendering;
78import org.openstreetmap.josm.data.osm.visitor.paint.relations.MultipolygonCache;
79import org.openstreetmap.josm.data.preferences.ColorProperty;
80import org.openstreetmap.josm.data.preferences.IntegerProperty;
81import org.openstreetmap.josm.data.preferences.StringProperty;
82import org.openstreetmap.josm.data.projection.Projection;
83import org.openstreetmap.josm.data.validation.TestError;
84import org.openstreetmap.josm.gui.ExtendedDialog;
85import org.openstreetmap.josm.gui.MapView;
86import org.openstreetmap.josm.gui.MapViewState.MapViewPoint;
87import org.openstreetmap.josm.gui.dialogs.LayerListDialog;
88import org.openstreetmap.josm.gui.dialogs.LayerListPopup;
89import org.openstreetmap.josm.gui.io.AbstractIOTask;
90import org.openstreetmap.josm.gui.io.AbstractUploadDialog;
91import org.openstreetmap.josm.gui.io.UploadDialog;
92import org.openstreetmap.josm.gui.io.UploadLayerTask;
93import org.openstreetmap.josm.gui.layer.markerlayer.MarkerLayer;
94import org.openstreetmap.josm.gui.progress.PleaseWaitProgressMonitor;
95import org.openstreetmap.josm.gui.progress.ProgressMonitor;
96import org.openstreetmap.josm.gui.util.GuiHelper;
97import org.openstreetmap.josm.gui.widgets.FileChooserManager;
98import org.openstreetmap.josm.gui.widgets.JosmTextArea;
99import org.openstreetmap.josm.io.OsmImporter;
100import org.openstreetmap.josm.tools.CheckParameterUtil;
101import org.openstreetmap.josm.tools.GBC;
102import org.openstreetmap.josm.tools.ImageOverlay;
103import org.openstreetmap.josm.tools.ImageProvider;
104import org.openstreetmap.josm.tools.ImageProvider.ImageSizes;
105import org.openstreetmap.josm.tools.SubclassFilteredCollection;
106import org.openstreetmap.josm.tools.date.DateUtils;
107
108/**
109 * A layer that holds OSM data from a specific dataset.
110 * The data can be fully edited.
111 *
112 * @author imi
113 * @since 17
114 */
115public class OsmDataLayer extends AbstractModifiableLayer implements Listener, SelectionChangedListener {
116 private static final int HATCHED_SIZE = 15;
117 /** Property used to know if this layer has to be saved on disk */
118 public static final String REQUIRES_SAVE_TO_DISK_PROP = OsmDataLayer.class.getName() + ".requiresSaveToDisk";
119 /** Property used to know if this layer has to be uploaded */
120 public static final String REQUIRES_UPLOAD_TO_SERVER_PROP = OsmDataLayer.class.getName() + ".requiresUploadToServer";
121
122 private boolean requiresSaveToFile;
123 private boolean requiresUploadToServer;
124 private boolean isChanged = true;
125 private int highlightUpdateCount;
126
127 /**
128 * List of validation errors in this layer.
129 * @since 3669
130 */
131 public final List<TestError> validationErrors = new ArrayList<>();
132
133 public static final int DEFAULT_RECENT_RELATIONS_NUMBER = 20;
134 public static final IntegerProperty PROPERTY_RECENT_RELATIONS_NUMBER = new IntegerProperty("properties.last-closed-relations-size",
135 DEFAULT_RECENT_RELATIONS_NUMBER);
136 public static final StringProperty PROPERTY_SAVE_EXTENSION = new StringProperty("save.extension.osm", "osm");
137
138 private static final ColorProperty PROPERTY_BACKGROUND_COLOR = new ColorProperty(marktr("background"), Color.BLACK);
139 private static final ColorProperty PROPERTY_OUTSIDE_COLOR = new ColorProperty(marktr("outside downloaded area"), Color.YELLOW);
140
141 /** List of recent relations */
142 private final Map<Relation, Void> recentRelations = new LinkedHashMap<Relation, Void>(PROPERTY_RECENT_RELATIONS_NUMBER.get()+1, 1.1f, true) {
143 @Override
144 protected boolean removeEldestEntry(Map.Entry<Relation, Void> eldest) {
145 return size() > PROPERTY_RECENT_RELATIONS_NUMBER.get();
146 }
147 };
148
149 /**
150 * Returns list of recently closed relations or null if none.
151 * @return list of recently closed relations or <code>null</code> if none
152 * @since 9668
153 */
154 public ArrayList<Relation> getRecentRelations() {
155 ArrayList<Relation> list = new ArrayList<>(recentRelations.keySet());
156 Collections.reverse(list);
157 return list;
158 }
159
160 /**
161 * Adds recently closed relation.
162 * @param relation new entry for the list of recently closed relations
163 * @since 9668
164 */
165 public void setRecentRelation(Relation relation) {
166 recentRelations.put(relation, null);
167 if (Main.map != null && Main.map.relationListDialog != null) {
168 Main.map.relationListDialog.enableRecentRelations();
169 }
170 }
171
172 /**
173 * Remove relation from list of recent relations.
174 * @param relation relation to remove
175 * @since 9668
176 */
177 public void removeRecentRelation(Relation relation) {
178 recentRelations.remove(relation);
179 if (Main.map != null && Main.map.relationListDialog != null) {
180 Main.map.relationListDialog.enableRecentRelations();
181 }
182 }
183
184 protected void setRequiresSaveToFile(boolean newValue) {
185 boolean oldValue = requiresSaveToFile;
186 requiresSaveToFile = newValue;
187 if (oldValue != newValue) {
188 propertyChangeSupport.firePropertyChange(REQUIRES_SAVE_TO_DISK_PROP, oldValue, newValue);
189 }
190 }
191
192 protected void setRequiresUploadToServer(boolean newValue) {
193 boolean oldValue = requiresUploadToServer;
194 requiresUploadToServer = newValue;
195 if (oldValue != newValue) {
196 propertyChangeSupport.firePropertyChange(REQUIRES_UPLOAD_TO_SERVER_PROP, oldValue, newValue);
197 }
198 }
199
200 /** the global counter for created data layers */
201 private static int dataLayerCounter;
202
203 /**
204 * Replies a new unique name for a data layer
205 *
206 * @return a new unique name for a data layer
207 */
208 public static String createNewName() {
209 dataLayerCounter++;
210 return tr("Data Layer {0}", dataLayerCounter);
211 }
212
213 public static final class DataCountVisitor extends AbstractVisitor {
214 public int nodes;
215 public int ways;
216 public int relations;
217 public int deletedNodes;
218 public int deletedWays;
219 public int deletedRelations;
220
221 @Override
222 public void visit(final Node n) {
223 nodes++;
224 if (n.isDeleted()) {
225 deletedNodes++;
226 }
227 }
228
229 @Override
230 public void visit(final Way w) {
231 ways++;
232 if (w.isDeleted()) {
233 deletedWays++;
234 }
235 }
236
237 @Override
238 public void visit(final Relation r) {
239 relations++;
240 if (r.isDeleted()) {
241 deletedRelations++;
242 }
243 }
244 }
245
246 @FunctionalInterface
247 public interface CommandQueueListener {
248 void commandChanged(int queueSize, int redoSize);
249 }
250
251 /**
252 * Listener called when a state of this layer has changed.
253 * @since 10600 (functional interface)
254 */
255 @FunctionalInterface
256 public interface LayerStateChangeListener {
257 /**
258 * Notifies that the "upload discouraged" (upload=no) state has changed.
259 * @param layer The layer that has been modified
260 * @param newValue The new value of the state
261 */
262 void uploadDiscouragedChanged(OsmDataLayer layer, boolean newValue);
263 }
264
265 private final CopyOnWriteArrayList<LayerStateChangeListener> layerStateChangeListeners = new CopyOnWriteArrayList<>();
266
267 /**
268 * Adds a layer state change listener
269 *
270 * @param listener the listener. Ignored if null or already registered.
271 * @since 5519
272 */
273 public void addLayerStateChangeListener(LayerStateChangeListener listener) {
274 if (listener != null) {
275 layerStateChangeListeners.addIfAbsent(listener);
276 }
277 }
278
279 /**
280 * Removes a layer state change listener
281 *
282 * @param listener the listener. Ignored if null or already registered.
283 * @since 5519
284 * @deprecated Method name contains a typo, use {@link #removeLayerStateChangeListener(LayerStateChangeListener)}.
285 */
286 @Deprecated
287 public void removeLayerPropertyChangeListener(LayerStateChangeListener listener) {
288 removeLayerStateChangeListener(listener);
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 }
368
369 /**
370 * Return the image provider to get the base icon
371 * @return image provider class which can be modified
372 * @since 8323
373 */
374 protected ImageProvider getBaseIconProvider() {
375 return new ImageProvider("layer", "osmdata_small");
376 }
377
378 @Override
379 public Icon getIcon() {
380 ImageProvider base = getBaseIconProvider().setMaxSize(ImageSizes.LAYER);
381 if (isUploadDiscouraged()) {
382 base.addOverlay(new ImageOverlay(new ImageProvider("warning-small"), 0.5, 0.5, 1.0, 1.0));
383 }
384 return base.get();
385 }
386
387 /**
388 * Draw all primitives in this layer but do not draw modified ones (they
389 * are drawn by the edit layer).
390 * Draw nodes last to overlap the ways they belong to.
391 */
392 @Override public void paint(final Graphics2D g, final MapView mv, Bounds box) {
393 isChanged = false;
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 final List<Way> sortedWays = new ArrayList<>(ways);
653 sortedWays.sort(new OsmPrimitiveComparator(true, false)); // sort by OsmPrimitive#getUniqueId ascending
654 Collections.reverse(sortedWays); // sort by OsmPrimitive#getUniqueId descending
655 for (Way w : sortedWays) {
656 if (!w.isUsable()) {
657 continue;
658 }
659 Collection<Collection<WayPoint>> trk = new ArrayList<>();
660 Map<String, Object> trkAttr = new HashMap<>();
661
662 if (w.get("name") != null) {
663 trkAttr.put("name", w.get("name"));
664 }
665
666 List<WayPoint> trkseg = null;
667 for (Node n : w.getNodes()) {
668 if (!n.isUsable()) {
669 trkseg = null;
670 continue;
671 }
672 if (trkseg == null) {
673 trkseg = new ArrayList<>();
674 trk.add(trkseg);
675 }
676 if (!n.isTagged()) {
677 doneNodes.add(n);
678 }
679 trkseg.add(nodeToWayPoint(n));
680 }
681
682 gpxData.tracks.add(new ImmutableGpxTrack(trk, trkAttr));
683 }
684 }
685
686 private static WayPoint nodeToWayPoint(Node n) {
687 WayPoint wpt = new WayPoint(n.getCoor());
688
689 // Position info
690
691 addDoubleIfPresent(wpt, n, GpxConstants.PT_ELE);
692
693 if (!n.isTimestampEmpty()) {
694 wpt.put("time", DateUtils.fromTimestamp(n.getRawTimestamp()));
695 wpt.setTime();
696 }
697
698 addDoubleIfPresent(wpt, n, GpxConstants.PT_MAGVAR);
699 addDoubleIfPresent(wpt, n, GpxConstants.PT_GEOIDHEIGHT);
700
701 // Description info
702
703 addStringIfPresent(wpt, n, GpxConstants.GPX_NAME);
704 addStringIfPresent(wpt, n, GpxConstants.GPX_DESC, "description");
705 addStringIfPresent(wpt, n, GpxConstants.GPX_CMT, "comment");
706 addStringIfPresent(wpt, n, GpxConstants.GPX_SRC, "source", "source:position");
707
708 Collection<GpxLink> links = new ArrayList<>();
709 for (String key : new String[]{"link", "url", "website", "contact:website"}) {
710 String value = n.get(key);
711 if (value != null) {
712 links.add(new GpxLink(value));
713 }
714 }
715 wpt.put(GpxConstants.META_LINKS, links);
716
717 addStringIfPresent(wpt, n, GpxConstants.PT_SYM, "wpt_symbol");
718 addStringIfPresent(wpt, n, GpxConstants.PT_TYPE);
719
720 // Accuracy info
721 addStringIfPresent(wpt, n, GpxConstants.PT_FIX, "gps:fix");
722 addIntegerIfPresent(wpt, n, GpxConstants.PT_SAT, "gps:sat");
723 addDoubleIfPresent(wpt, n, GpxConstants.PT_HDOP, "gps:hdop");
724 addDoubleIfPresent(wpt, n, GpxConstants.PT_VDOP, "gps:vdop");
725 addDoubleIfPresent(wpt, n, GpxConstants.PT_PDOP, "gps:pdop");
726 addDoubleIfPresent(wpt, n, GpxConstants.PT_AGEOFDGPSDATA, "gps:ageofdgpsdata");
727 addIntegerIfPresent(wpt, n, GpxConstants.PT_DGPSID, "gps:dgpsid");
728
729 return wpt;
730 }
731
732 private static void nodesToGpxData(Collection<Node> nodes, GpxData gpxData, Set<Node> doneNodes) {
733 List<Node> sortedNodes = new ArrayList<>(nodes);
734 sortedNodes.removeAll(doneNodes);
735 Collections.sort(sortedNodes);
736 for (Node n : sortedNodes) {
737 if (n.isIncomplete() || n.isDeleted()) {
738 continue;
739 }
740 gpxData.waypoints.add(nodeToWayPoint(n));
741 }
742 }
743
744 private static void addIntegerIfPresent(WayPoint wpt, OsmPrimitive p, String gpxKey, String ... osmKeys) {
745 List<String> possibleKeys = new ArrayList<>(Arrays.asList(osmKeys));
746 possibleKeys.add(0, gpxKey);
747 for (String key : possibleKeys) {
748 String value = p.get(key);
749 if (value != null) {
750 try {
751 int i = Integer.parseInt(value);
752 // Sanity checks
753 if ((!GpxConstants.PT_SAT.equals(gpxKey) || i >= 0) &&
754 (!GpxConstants.PT_DGPSID.equals(gpxKey) || (0 <= i && i <= 1023))) {
755 wpt.put(gpxKey, value);
756 break;
757 }
758 } catch (NumberFormatException e) {
759 Main.trace(e);
760 }
761 }
762 }
763 }
764
765 private static void addDoubleIfPresent(WayPoint wpt, OsmPrimitive p, String gpxKey, String ... osmKeys) {
766 List<String> possibleKeys = new ArrayList<>(Arrays.asList(osmKeys));
767 possibleKeys.add(0, gpxKey);
768 for (String key : possibleKeys) {
769 String value = p.get(key);
770 if (value != null) {
771 try {
772 double d = Double.parseDouble(value);
773 // Sanity checks
774 if (!GpxConstants.PT_MAGVAR.equals(gpxKey) || (0.0 <= d && d < 360.0)) {
775 wpt.put(gpxKey, value);
776 break;
777 }
778 } catch (NumberFormatException e) {
779 Main.trace(e);
780 }
781 }
782 }
783 }
784
785 private static void addStringIfPresent(WayPoint wpt, OsmPrimitive p, String gpxKey, String ... osmKeys) {
786 List<String> possibleKeys = new ArrayList<>(Arrays.asList(osmKeys));
787 possibleKeys.add(0, gpxKey);
788 for (String key : possibleKeys) {
789 String value = p.get(key);
790 // Sanity checks
791 if (value != null && (!GpxConstants.PT_FIX.equals(gpxKey) || GpxConstants.FIX_VALUES.contains(value))) {
792 wpt.put(gpxKey, value);
793 break;
794 }
795 }
796 }
797
798 /**
799 * Converts OSM data behind this layer to GPX data.
800 * @return GPX data
801 */
802 public GpxData toGpxData() {
803 return toGpxData(data, getAssociatedFile());
804 }
805
806 /**
807 * Action that converts this OSM layer to a GPX layer.
808 */
809 public class ConvertToGpxLayerAction extends AbstractAction {
810 /**
811 * Constructs a new {@code ConvertToGpxLayerAction}.
812 */
813 public ConvertToGpxLayerAction() {
814 super(tr("Convert to GPX layer"), ImageProvider.get("converttogpx"));
815 putValue("help", ht("/Action/ConvertToGpxLayer"));
816 }
817
818 @Override
819 public void actionPerformed(ActionEvent e) {
820 final GpxData gpxData = toGpxData();
821 final GpxLayer gpxLayer = new GpxLayer(gpxData, tr("Converted from: {0}", getName()));
822 if (getAssociatedFile() != null) {
823 String filename = getAssociatedFile().getName().replaceAll(Pattern.quote(".gpx.osm") + '$', "") + ".gpx";
824 gpxLayer.setAssociatedFile(new File(getAssociatedFile().getParentFile(), filename));
825 }
826 Main.getLayerManager().addLayer(gpxLayer);
827 if (Main.pref.getBoolean("marker.makeautomarkers", true) && !gpxData.waypoints.isEmpty()) {
828 Main.getLayerManager().addLayer(new MarkerLayer(gpxData, tr("Converted from: {0}", getName()), null, gpxLayer));
829 }
830 Main.getLayerManager().removeLayer(OsmDataLayer.this);
831 }
832 }
833
834 /**
835 * Determines if this layer contains data at the given coordinate.
836 * @param coor the coordinate
837 * @return {@code true} if data sources bounding boxes contain {@code coor}
838 */
839 public boolean containsPoint(LatLon coor) {
840 // we'll assume that if this has no data sources
841 // that it also has no borders
842 if (this.data.dataSources.isEmpty())
843 return true;
844
845 boolean layerBoundsPoint = false;
846 for (DataSource src : this.data.dataSources) {
847 if (src.bounds.contains(coor)) {
848 layerBoundsPoint = true;
849 break;
850 }
851 }
852 return layerBoundsPoint;
853 }
854
855 /**
856 * Replies the set of conflicts currently managed in this layer.
857 *
858 * @return the set of conflicts currently managed in this layer
859 */
860 public ConflictCollection getConflicts() {
861 return conflicts;
862 }
863
864 @Override
865 public boolean isUploadable() {
866 return true;
867 }
868
869 @Override
870 public boolean requiresUploadToServer() {
871 return requiresUploadToServer;
872 }
873
874 @Override
875 public boolean requiresSaveToFile() {
876 return getAssociatedFile() != null && requiresSaveToFile;
877 }
878
879 @Override
880 public void onPostLoadFromFile() {
881 setRequiresSaveToFile(false);
882 setRequiresUploadToServer(isModified());
883 invalidate();
884 }
885
886 /**
887 * Actions run after data has been downloaded to this layer.
888 */
889 public void onPostDownloadFromServer() {
890 setRequiresSaveToFile(true);
891 setRequiresUploadToServer(isModified());
892 invalidate();
893 }
894
895 @Override
896 public boolean isChanged() {
897 return isChanged || highlightUpdateCount != data.getHighlightUpdateCount();
898 }
899
900 @Override
901 public void onPostSaveToFile() {
902 setRequiresSaveToFile(false);
903 setRequiresUploadToServer(isModified());
904 }
905
906 @Override
907 public void onPostUploadToServer() {
908 setRequiresUploadToServer(isModified());
909 // keep requiresSaveToDisk unchanged
910 }
911
912 private class ConsistencyTestAction extends AbstractAction {
913
914 ConsistencyTestAction() {
915 super(tr("Dataset consistency test"));
916 }
917
918 @Override
919 public void actionPerformed(ActionEvent e) {
920 String result = DatasetConsistencyTest.runTests(data);
921 if (result.isEmpty()) {
922 JOptionPane.showMessageDialog(Main.parent, tr("No problems found"));
923 } else {
924 JPanel p = new JPanel(new GridBagLayout());
925 p.add(new JLabel(tr("Following problems found:")), GBC.eol());
926 JosmTextArea info = new JosmTextArea(result, 20, 60);
927 info.setCaretPosition(0);
928 info.setEditable(false);
929 p.add(new JScrollPane(info), GBC.eop());
930
931 JOptionPane.showMessageDialog(Main.parent, p, tr("Warning"), JOptionPane.WARNING_MESSAGE);
932 }
933 }
934 }
935
936 @Override
937 public void 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 invalidate() {
955 isChanged = true;
956 super.invalidate();
957 }
958
959 @Override
960 public void projectionChanged(Projection oldValue, Projection newValue) {
961 // No reprojection required. The dataset itself is registered as projection
962 // change listener and already got notified.
963 }
964
965 @Override
966 public final boolean isUploadDiscouraged() {
967 return data.isUploadDiscouraged();
968 }
969
970 /**
971 * Sets the "discouraged upload" flag.
972 * @param uploadDiscouraged {@code true} if upload of data managed by this layer is discouraged.
973 * This feature allows to use "private" data layers.
974 */
975 public final void setUploadDiscouraged(boolean uploadDiscouraged) {
976 if (uploadDiscouraged ^ isUploadDiscouraged()) {
977 data.setUploadDiscouraged(uploadDiscouraged);
978 for (LayerStateChangeListener l : layerStateChangeListeners) {
979 l.uploadDiscouragedChanged(this, uploadDiscouraged);
980 }
981 }
982 }
983
984 @Override
985 public final boolean isModified() {
986 return data.isModified();
987 }
988
989 @Override
990 public boolean isSavable() {
991 return true; // With OsmExporter
992 }
993
994 @Override
995 public boolean checkSaveConditions() {
996 if (isDataSetEmpty() && 1 != GuiHelper.runInEDTAndWaitAndReturn(() -> {
997 if (GraphicsEnvironment.isHeadless()) {
998 return 2;
999 }
1000 ExtendedDialog dialog = new ExtendedDialog(
1001 Main.parent,
1002 tr("Empty document"),
1003 new String[] {tr("Save anyway"), tr("Cancel")}
1004 );
1005 dialog.setContent(tr("The document contains no data."));
1006 dialog.setButtonIcons(new String[] {"save", "cancel"});
1007 return dialog.showDialog().getValue();
1008 })) {
1009 return false;
1010 }
1011
1012 ConflictCollection conflictsCol = getConflicts();
1013 if (conflictsCol != null && !conflictsCol.isEmpty() && 1 != GuiHelper.runInEDTAndWaitAndReturn(() -> {
1014 ExtendedDialog dialog = new ExtendedDialog(
1015 Main.parent,
1016 /* I18N: Display title of the window showing conflicts */
1017 tr("Conflicts"),
1018 new String[] {tr("Reject Conflicts and Save"), tr("Cancel")}
1019 );
1020 dialog.setContent(
1021 tr("There are unresolved conflicts. Conflicts will not be saved and handled as if you rejected all. Continue?"));
1022 dialog.setButtonIcons(new String[] {"save", "cancel"});
1023 return dialog.showDialog().getValue();
1024 })) {
1025 return false;
1026 }
1027 return true;
1028 }
1029
1030 /**
1031 * Check the data set if it would be empty on save. It is empty, if it contains
1032 * no objects (after all objects that are created and deleted without being
1033 * transferred to the server have been removed).
1034 *
1035 * @return <code>true</code>, if a save result in an empty data set.
1036 */
1037 private boolean isDataSetEmpty() {
1038 if (data != null) {
1039 for (OsmPrimitive osm : data.allNonDeletedPrimitives()) {
1040 if (!osm.isDeleted() || !osm.isNewOrUndeleted())
1041 return false;
1042 }
1043 }
1044 return true;
1045 }
1046
1047 @Override
1048 public File createAndOpenSaveFileChooser() {
1049 String extension = PROPERTY_SAVE_EXTENSION.get();
1050 File file = getAssociatedFile();
1051 if (file == null && isRenamed()) {
1052 String filename = Main.pref.get("lastDirectory") + '/' + getName();
1053 if (!OsmImporter.FILE_FILTER.acceptName(filename))
1054 filename = filename + '.' + extension;
1055 file = new File(filename);
1056 }
1057 return new FileChooserManager()
1058 .title(tr("Save OSM file"))
1059 .extension(extension)
1060 .file(file)
1061 .allTypes(true)
1062 .getFileForSave();
1063 }
1064
1065 @Override
1066 public AbstractIOTask createUploadTask(final ProgressMonitor monitor) {
1067 UploadDialog dialog = UploadDialog.getUploadDialog();
1068 return new UploadLayerTask(
1069 dialog.getUploadStrategySpecification(),
1070 this,
1071 monitor,
1072 dialog.getChangeset());
1073 }
1074
1075 @Override
1076 public AbstractUploadDialog getUploadDialog() {
1077 UploadDialog dialog = UploadDialog.getUploadDialog();
1078 dialog.setUploadedPrimitives(new APIDataSet(data));
1079 return dialog;
1080 }
1081
1082 @Override
1083 public ProjectionBounds getViewProjectionBounds() {
1084 BoundingXYVisitor v = new BoundingXYVisitor();
1085 v.visit(data.getDataSourceBoundingBox());
1086 if (!v.hasExtend()) {
1087 v.computeBoundingBox(data.getNodes());
1088 }
1089 return v.getBounds();
1090 }
1091}
Note: See TracBrowser for help on using the repository browser.