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

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

fix #13303 - Fixes for hatched texture (modified patch by michael2402) - gsoc-core

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