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

Last change on this file since 12153 was 12153, checked in by michael2402, 7 years ago

Use a data counter + StringBuilder to create the data set tooltip. Add a new line after each nodes/ways/relations item.

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