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

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

fix #12935 - One pixel is out of order in the hatched texture (patch by michael2402) - gsoc-core

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