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

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

see #14120 - fix java warnings

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