001// License: GPL. See LICENSE file for details.
002package org.openstreetmap.josm.gui.layer;
003
004import static org.openstreetmap.josm.gui.help.HelpUtil.ht;
005import static org.openstreetmap.josm.tools.I18n.marktr;
006import static org.openstreetmap.josm.tools.I18n.tr;
007import static org.openstreetmap.josm.tools.I18n.trn;
008
009import java.awt.AlphaComposite;
010import java.awt.Color;
011import java.awt.Composite;
012import java.awt.Graphics2D;
013import java.awt.GridBagLayout;
014import java.awt.Image;
015import java.awt.Point;
016import java.awt.Rectangle;
017import java.awt.TexturePaint;
018import java.awt.event.ActionEvent;
019import java.awt.geom.Area;
020import java.awt.image.BufferedImage;
021import java.io.File;
022import java.util.ArrayList;
023import java.util.Arrays;
024import java.util.Collection;
025import java.util.Collections;
026import java.util.HashMap;
027import java.util.HashSet;
028import java.util.List;
029import java.util.Map;
030import java.util.concurrent.Callable;
031import java.util.concurrent.CopyOnWriteArrayList;
032
033import javax.swing.AbstractAction;
034import javax.swing.Action;
035import javax.swing.Icon;
036import javax.swing.ImageIcon;
037import javax.swing.JLabel;
038import javax.swing.JOptionPane;
039import javax.swing.JPanel;
040import javax.swing.JScrollPane;
041
042import org.openstreetmap.josm.Main;
043import org.openstreetmap.josm.actions.ExpertToggleAction;
044import org.openstreetmap.josm.actions.RenameLayerAction;
045import org.openstreetmap.josm.actions.SaveActionBase;
046import org.openstreetmap.josm.actions.ToggleUploadDiscouragedLayerAction;
047import org.openstreetmap.josm.data.APIDataSet;
048import org.openstreetmap.josm.data.Bounds;
049import org.openstreetmap.josm.data.DataSource;
050import org.openstreetmap.josm.data.SelectionChangedListener;
051import org.openstreetmap.josm.data.conflict.Conflict;
052import org.openstreetmap.josm.data.conflict.ConflictCollection;
053import org.openstreetmap.josm.data.coor.LatLon;
054import org.openstreetmap.josm.data.gpx.GpxConstants;
055import org.openstreetmap.josm.data.gpx.GpxData;
056import org.openstreetmap.josm.data.gpx.GpxLink;
057import org.openstreetmap.josm.data.gpx.ImmutableGpxTrack;
058import org.openstreetmap.josm.data.gpx.WayPoint;
059import org.openstreetmap.josm.data.osm.DataIntegrityProblemException;
060import org.openstreetmap.josm.data.osm.DataSet;
061import org.openstreetmap.josm.data.osm.DataSetMerger;
062import org.openstreetmap.josm.data.osm.DatasetConsistencyTest;
063import org.openstreetmap.josm.data.osm.IPrimitive;
064import org.openstreetmap.josm.data.osm.Node;
065import org.openstreetmap.josm.data.osm.OsmPrimitive;
066import org.openstreetmap.josm.data.osm.Relation;
067import org.openstreetmap.josm.data.osm.Way;
068import org.openstreetmap.josm.data.osm.event.AbstractDatasetChangedEvent;
069import org.openstreetmap.josm.data.osm.event.DataSetListenerAdapter;
070import org.openstreetmap.josm.data.osm.event.DataSetListenerAdapter.Listener;
071import org.openstreetmap.josm.data.osm.visitor.AbstractVisitor;
072import org.openstreetmap.josm.data.osm.visitor.BoundingXYVisitor;
073import org.openstreetmap.josm.data.osm.visitor.paint.MapRendererFactory;
074import org.openstreetmap.josm.data.osm.visitor.paint.Rendering;
075import org.openstreetmap.josm.data.osm.visitor.paint.relations.MultipolygonCache;
076import org.openstreetmap.josm.data.projection.Projection;
077import org.openstreetmap.josm.data.validation.TestError;
078import org.openstreetmap.josm.gui.ExtendedDialog;
079import org.openstreetmap.josm.gui.MapView;
080import org.openstreetmap.josm.gui.dialogs.LayerListDialog;
081import org.openstreetmap.josm.gui.dialogs.LayerListPopup;
082import org.openstreetmap.josm.gui.io.AbstractIOTask;
083import org.openstreetmap.josm.gui.io.AbstractUploadDialog;
084import org.openstreetmap.josm.gui.io.UploadDialog;
085import org.openstreetmap.josm.gui.io.UploadLayerTask;
086import org.openstreetmap.josm.gui.progress.PleaseWaitProgressMonitor;
087import org.openstreetmap.josm.gui.progress.ProgressMonitor;
088import org.openstreetmap.josm.gui.util.GuiHelper;
089import org.openstreetmap.josm.gui.widgets.JosmTextArea;
090import org.openstreetmap.josm.tools.FilteredCollection;
091import org.openstreetmap.josm.tools.GBC;
092import org.openstreetmap.josm.tools.ImageProvider;
093import org.openstreetmap.josm.tools.date.DateUtils;
094
095/**
096 * A layer that holds OSM data from a specific dataset.
097 * The data can be fully edited.
098 *
099 * @author imi
100 * @since 17
101 */
102public class OsmDataLayer extends AbstractModifiableLayer implements Listener, SelectionChangedListener {
103    /** Property used to know if this layer has to be saved on disk */
104    public static final String REQUIRES_SAVE_TO_DISK_PROP = OsmDataLayer.class.getName() + ".requiresSaveToDisk";
105    /** Property used to know if this layer has to be uploaded */
106    public static final String REQUIRES_UPLOAD_TO_SERVER_PROP = OsmDataLayer.class.getName() + ".requiresUploadToServer";
107
108    private boolean requiresSaveToFile = false;
109    private boolean requiresUploadToServer = false;
110    private boolean isChanged = true;
111    private int highlightUpdateCount;
112
113    /**
114     * List of validation errors in this layer.
115     * @since 3669
116     */
117    public final List<TestError> validationErrors = new ArrayList<>();
118
119    protected void setRequiresSaveToFile(boolean newValue) {
120        boolean oldValue = requiresSaveToFile;
121        requiresSaveToFile = newValue;
122        if (oldValue != newValue) {
123            propertyChangeSupport.firePropertyChange(REQUIRES_SAVE_TO_DISK_PROP, oldValue, newValue);
124        }
125    }
126
127    protected void setRequiresUploadToServer(boolean newValue) {
128        boolean oldValue = requiresUploadToServer;
129        requiresUploadToServer = newValue;
130        if (oldValue != newValue) {
131            propertyChangeSupport.firePropertyChange(REQUIRES_UPLOAD_TO_SERVER_PROP, oldValue, newValue);
132        }
133    }
134
135    /** the global counter for created data layers */
136    private static int dataLayerCounter = 0;
137
138    /**
139     * Replies a new unique name for a data layer
140     *
141     * @return a new unique name for a data layer
142     */
143    public static String createNewName() {
144        dataLayerCounter++;
145        return tr("Data Layer {0}", dataLayerCounter);
146    }
147
148    public static final class DataCountVisitor extends AbstractVisitor {
149        public int nodes;
150        public int ways;
151        public int relations;
152        public int deletedNodes;
153        public int deletedWays;
154        public int deletedRelations;
155
156        @Override
157        public void visit(final Node n) {
158            nodes++;
159            if (n.isDeleted()) {
160                deletedNodes++;
161            }
162        }
163
164        @Override
165        public void visit(final Way w) {
166            ways++;
167            if (w.isDeleted()) {
168                deletedWays++;
169            }
170        }
171
172        @Override
173        public void visit(final Relation r) {
174            relations++;
175            if (r.isDeleted()) {
176                deletedRelations++;
177            }
178        }
179    }
180
181    public interface CommandQueueListener {
182        void commandChanged(int queueSize, int redoSize);
183    }
184
185    /**
186     * Listener called when a state of this layer has changed.
187     */
188    public interface LayerStateChangeListener {
189        /**
190         * Notifies that the "upload discouraged" (upload=no) state has changed.
191         * @param layer The layer that has been modified
192         * @param newValue The new value of the state
193         */
194        void uploadDiscouragedChanged(OsmDataLayer layer, boolean newValue);
195    }
196
197    private final CopyOnWriteArrayList<LayerStateChangeListener> layerStateChangeListeners = new CopyOnWriteArrayList<>();
198
199    /**
200     * Adds a layer state change listener
201     *
202     * @param listener the listener. Ignored if null or already registered.
203     * @since 5519
204     */
205    public void addLayerStateChangeListener(LayerStateChangeListener listener) {
206        if (listener != null) {
207            layerStateChangeListeners.addIfAbsent(listener);
208        }
209    }
210
211    /**
212     * Removes a layer property change listener
213     *
214     * @param listener the listener. Ignored if null or already registered.
215     * @since 5519
216     */
217    public void removeLayerPropertyChangeListener(LayerStateChangeListener listener) {
218        layerStateChangeListeners.remove(listener);
219    }
220
221    /**
222     * The data behind this layer.
223     */
224    public final DataSet data;
225
226    /**
227     * the collection of conflicts detected in this layer
228     */
229    private ConflictCollection conflicts;
230
231    /**
232     * a paint texture for non-downloaded area
233     */
234    private static TexturePaint hatched;
235
236    static {
237        createHatchTexture();
238    }
239
240    /**
241     * Replies background color for downloaded areas.
242     * @return background color for downloaded areas. Black by default
243     */
244    public static Color getBackgroundColor() {
245        return Main.pref.getColor(marktr("background"), Color.BLACK);
246    }
247
248    /**
249     * Replies background color for non-downloaded areas.
250     * @return background color for non-downloaded areas. Yellow by default
251     */
252    public static Color getOutsideColor() {
253        return Main.pref.getColor(marktr("outside downloaded area"), Color.YELLOW);
254    }
255
256    /**
257     * Initialize the hatch pattern used to paint the non-downloaded area
258     */
259    public static void createHatchTexture() {
260        BufferedImage bi = new BufferedImage(15, 15, BufferedImage.TYPE_INT_ARGB);
261        Graphics2D big = bi.createGraphics();
262        big.setColor(getBackgroundColor());
263        Composite comp = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.3f);
264        big.setComposite(comp);
265        big.fillRect(0,0,15,15);
266        big.setColor(getOutsideColor());
267        big.drawLine(0,15,15,0);
268        Rectangle r = new Rectangle(0, 0, 15,15);
269        hatched = new TexturePaint(bi, r);
270    }
271
272    /**
273     * Construct a new {@code OsmDataLayer}.
274     * @param data OSM data
275     * @param name Layer name
276     * @param associatedFile Associated .osm file (can be null)
277     */
278    public OsmDataLayer(final DataSet data, final String name, final File associatedFile) {
279        super(name);
280        this.data = data;
281        this.setAssociatedFile(associatedFile);
282        conflicts = new ConflictCollection();
283        data.addDataSetListener(new DataSetListenerAdapter(this));
284        data.addDataSetListener(MultipolygonCache.getInstance());
285        DataSet.addSelectionListener(this);
286    }
287
288    protected Icon getBaseIcon() {
289        return ImageProvider.get("layer", "osmdata_small");
290    }
291
292    /**
293     * TODO: @return Return a dynamic drawn icon of the map data. The icon is
294     *         updated by a background thread to not disturb the running programm.
295     */
296    @Override public Icon getIcon() {
297        Icon baseIcon = getBaseIcon();
298        if (isUploadDiscouraged()) {
299            return ImageProvider.overlay(baseIcon,
300                    new ImageIcon(ImageProvider.get("warning-small").getImage().getScaledInstance(8, 8, Image.SCALE_SMOOTH)),
301                    ImageProvider.OverlayPosition.SOUTHEAST);
302        } else {
303            return baseIcon;
304        }
305    }
306
307    /**
308     * Draw all primitives in this layer but do not draw modified ones (they
309     * are drawn by the edit layer).
310     * Draw nodes last to overlap the ways they belong to.
311     */
312    @Override public void paint(final Graphics2D g, final MapView mv, Bounds box) {
313        isChanged = false;
314        highlightUpdateCount = data.getHighlightUpdateCount();
315
316        boolean active = mv.getActiveLayer() == this;
317        boolean inactive = !active && Main.pref.getBoolean("draw.data.inactive_color", true);
318        boolean virtual = !inactive && mv.isVirtualNodesEnabled();
319
320        // draw the hatched area for non-downloaded region. only draw if we're the active
321        // and bounds are defined; don't draw for inactive layers or loaded GPX files etc
322        if (active && Main.pref.getBoolean("draw.data.downloaded_area", true) && !data.dataSources.isEmpty()) {
323            // initialize area with current viewport
324            Rectangle b = mv.getBounds();
325            // on some platforms viewport bounds seem to be offset from the left,
326            // over-grow it just to be sure
327            b.grow(100, 100);
328            Area a = new Area(b);
329
330            // now successively subtract downloaded areas
331            for (Bounds bounds : data.getDataSourceBounds()) {
332                if (bounds.isCollapsed()) {
333                    continue;
334                }
335                Point p1 = mv.getPoint(bounds.getMin());
336                Point p2 = mv.getPoint(bounds.getMax());
337                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));
338                a.subtract(new Area(r));
339            }
340
341            // paint remainder
342            g.setPaint(hatched);
343            g.fill(a);
344        }
345
346        Rendering painter = MapRendererFactory.getInstance().createActiveRenderer(g, mv, inactive);
347        painter.render(data, virtual, box);
348        Main.map.conflictDialog.paintConflicts(g, mv);
349    }
350
351    @Override public String getToolTipText() {
352        int nodes = new FilteredCollection<>(data.getNodes(), OsmPrimitive.nonDeletedPredicate).size();
353        int ways = new FilteredCollection<>(data.getWays(), OsmPrimitive.nonDeletedPredicate).size();
354        int rels = new FilteredCollection<>(data.getRelations(), OsmPrimitive.nonDeletedPredicate).size();
355
356        String tool = trn("{0} node", "{0} nodes", nodes, nodes)+", ";
357        tool += trn("{0} way", "{0} ways", ways, ways)+", ";
358        tool += trn("{0} relation", "{0} relations", rels, rels);
359
360        File f = getAssociatedFile();
361        if (f != null) {
362            tool = "<html>"+tool+"<br>"+f.getPath()+"</html>";
363        }
364        return tool;
365    }
366
367    @Override public void mergeFrom(final Layer from) {
368        final PleaseWaitProgressMonitor monitor = new PleaseWaitProgressMonitor(tr("Merging layers"));
369        monitor.setCancelable(false);
370        if (from instanceof OsmDataLayer && ((OsmDataLayer)from).isUploadDiscouraged()) {
371            setUploadDiscouraged(true);
372        }
373        mergeFrom(((OsmDataLayer)from).data, monitor);
374        monitor.close();
375    }
376
377    /**
378     * merges the primitives in dataset <code>from</code> into the dataset of
379     * this layer
380     *
381     * @param from  the source data set
382     */
383    public void mergeFrom(final DataSet from) {
384        mergeFrom(from, null);
385    }
386
387    /**
388     * merges the primitives in dataset <code>from</code> into the dataset of
389     * this layer
390     *
391     * @param from  the source data set
392     * @param progressMonitor the progress monitor, can be {@code null}
393     */
394    public void mergeFrom(final DataSet from, ProgressMonitor progressMonitor) {
395        final DataSetMerger visitor = new DataSetMerger(data,from);
396        try {
397            visitor.merge(progressMonitor);
398        } catch (DataIntegrityProblemException e) {
399            JOptionPane.showMessageDialog(
400                    Main.parent,
401                    e.getHtmlMessage() != null ? e.getHtmlMessage() : e.getMessage(),
402                    tr("Error"),
403                    JOptionPane.ERROR_MESSAGE
404            );
405            return;
406
407        }
408
409        Area a = data.getDataSourceArea();
410
411        // copy the merged layer's data source info.
412        // only add source rectangles if they are not contained in the layer already.
413        for (DataSource src : from.dataSources) {
414            if (a == null || !a.contains(src.bounds.asRect())) {
415                data.dataSources.add(src);
416            }
417        }
418
419        // copy the merged layer's API version
420        if (data.getVersion() == null) {
421            data.setVersion(from.getVersion());
422        }
423
424        int numNewConflicts = 0;
425        for (Conflict<?> c : visitor.getConflicts()) {
426            if (!conflicts.hasConflict(c)) {
427                numNewConflicts++;
428                conflicts.add(c);
429            }
430        }
431        // repaint to make sure new data is displayed properly.
432        if (Main.isDisplayingMapView()) {
433            Main.map.mapView.repaint();
434        }
435        // warn about new conflicts
436        if (numNewConflicts > 0 && Main.map != null && Main.map.conflictDialog != null) {
437            Main.map.conflictDialog.warnNumNewConflicts(numNewConflicts);
438        }
439    }
440
441    @Override public boolean isMergable(final Layer other) {
442        // isUploadDiscouraged commented to allow merging between normal layers and discouraged layers with a warning (see #7684)
443        return other instanceof OsmDataLayer;// && (isUploadDiscouraged() == ((OsmDataLayer)other).isUploadDiscouraged());
444    }
445
446    @Override public void visitBoundingBox(final BoundingXYVisitor v) {
447        for (final Node n: data.getNodes()) {
448            if (n.isUsable()) {
449                v.visit(n);
450            }
451        }
452    }
453
454    /**
455     * Clean out the data behind the layer. This means clearing the redo/undo lists,
456     * really deleting all deleted objects and reset the modified flags. This should
457     * be done after an upload, even after a partial upload.
458     *
459     * @param processed A list of all objects that were actually uploaded.
460     *         May be <code>null</code>, which means nothing has been uploaded
461     */
462    public void cleanupAfterUpload(final Collection<IPrimitive> processed) {
463        // return immediately if an upload attempt failed
464        if (processed == null || processed.isEmpty())
465            return;
466
467        Main.main.undoRedo.clean(this);
468
469        // if uploaded, clean the modified flags as well
470        data.cleanupDeletedPrimitives();
471        for (OsmPrimitive p: data.allPrimitives()) {
472            if (processed.contains(p)) {
473                p.setModified(false);
474            }
475        }
476    }
477
478
479    @Override public Object getInfoComponent() {
480        final DataCountVisitor counter = new DataCountVisitor();
481        for (final OsmPrimitive osm : data.allPrimitives()) {
482            osm.accept(counter);
483        }
484        final JPanel p = new JPanel(new GridBagLayout());
485
486        String nodeText = trn("{0} node", "{0} nodes", counter.nodes, counter.nodes);
487        if (counter.deletedNodes > 0) {
488            nodeText += " ("+trn("{0} deleted", "{0} deleted", counter.deletedNodes, counter.deletedNodes)+")";
489        }
490
491        String wayText = trn("{0} way", "{0} ways", counter.ways, counter.ways);
492        if (counter.deletedWays > 0) {
493            wayText += " ("+trn("{0} deleted", "{0} deleted", counter.deletedWays, counter.deletedWays)+")";
494        }
495
496        String relationText = trn("{0} relation", "{0} relations", counter.relations, counter.relations);
497        if (counter.deletedRelations > 0) {
498            relationText += " ("+trn("{0} deleted", "{0} deleted", counter.deletedRelations, counter.deletedRelations)+")";
499        }
500
501        p.add(new JLabel(tr("{0} consists of:", getName())), GBC.eol());
502        p.add(new JLabel(nodeText, ImageProvider.get("data", "node"), JLabel.HORIZONTAL), GBC.eop().insets(15,0,0,0));
503        p.add(new JLabel(wayText, ImageProvider.get("data", "way"), JLabel.HORIZONTAL), GBC.eop().insets(15,0,0,0));
504        p.add(new JLabel(relationText, ImageProvider.get("data", "relation"), JLabel.HORIZONTAL), GBC.eop().insets(15,0,0,0));
505        p.add(new JLabel(tr("API version: {0}", (data.getVersion() != null) ? data.getVersion() : tr("unset"))), GBC.eop().insets(15,0,0,0));
506        if (isUploadDiscouraged()) {
507            p.add(new JLabel(tr("Upload is discouraged")), GBC.eop().insets(15,0,0,0));
508        }
509
510        return p;
511    }
512
513    @Override public Action[] getMenuEntries() {
514        List<Action> actions = new ArrayList<>();
515        actions.addAll(Arrays.asList(new Action[]{
516                LayerListDialog.getInstance().createActivateLayerAction(this),
517                LayerListDialog.getInstance().createShowHideLayerAction(),
518                LayerListDialog.getInstance().createDeleteLayerAction(),
519                SeparatorLayerAction.INSTANCE,
520                LayerListDialog.getInstance().createMergeLayerAction(this),
521                new LayerSaveAction(this),
522                new LayerSaveAsAction(this),
523        }));
524        if (ExpertToggleAction.isExpert()) {
525            actions.addAll(Arrays.asList(new Action[]{
526                    new LayerGpxExportAction(this),
527                    new ConvertToGpxLayerAction()}));
528        }
529        actions.addAll(Arrays.asList(new Action[]{
530                SeparatorLayerAction.INSTANCE,
531                new RenameLayerAction(getAssociatedFile(), this)}));
532        if (ExpertToggleAction.isExpert() && Main.pref.getBoolean("data.layer.upload_discouragement.menu_item", false)) {
533            actions.add(new ToggleUploadDiscouragedLayerAction(this));
534        }
535        actions.addAll(Arrays.asList(new Action[]{
536                new ConsistencyTestAction(),
537                SeparatorLayerAction.INSTANCE,
538                new LayerListPopup.InfoAction(this)}));
539        return actions.toArray(new Action[actions.size()]);
540    }
541
542    /**
543     * Converts given OSM dataset to GPX data.
544     * @param data OSM dataset
545     * @param file output .gpx file
546     * @return GPX data
547     */
548    public static GpxData toGpxData(DataSet data, File file) {
549        GpxData gpxData = new GpxData();
550        gpxData.storageFile = file;
551        HashSet<Node> doneNodes = new HashSet<>();
552        waysToGpxData(data.getWays(), gpxData, doneNodes);
553        nodesToGpxData(data.getNodes(), gpxData, doneNodes);
554        return gpxData;
555    }
556
557    private static void waysToGpxData(Collection<Way> ways, GpxData gpxData, HashSet<Node> doneNodes) {
558        for (Way w : ways) {
559            if (!w.isUsable()) {
560                continue;
561            }
562            Collection<Collection<WayPoint>> trk = new ArrayList<>();
563            Map<String, Object> trkAttr = new HashMap<>();
564
565            if (w.get("name") != null) {
566                trkAttr.put("name", w.get("name"));
567            }
568
569            List<WayPoint> trkseg = null;
570            for (Node n : w.getNodes()) {
571                if (!n.isUsable()) {
572                    trkseg = null;
573                    continue;
574                }
575                if (trkseg == null) {
576                    trkseg = new ArrayList<>();
577                    trk.add(trkseg);
578                }
579                if (!n.isTagged()) {
580                    doneNodes.add(n);
581                }
582                WayPoint wpt = new WayPoint(n.getCoor());
583                if (!n.isTimestampEmpty()) {
584                    wpt.put("time", DateUtils.fromDate(n.getTimestamp()));
585                    wpt.setTime();
586                }
587                trkseg.add(wpt);
588            }
589
590            gpxData.tracks.add(new ImmutableGpxTrack(trk, trkAttr));
591        }
592    }
593
594    private static void nodesToGpxData(Collection<Node> nodes, GpxData gpxData, HashSet<Node> doneNodes) {
595        List<Node> sortedNodes = new ArrayList<>(nodes);
596        sortedNodes.removeAll(doneNodes);
597        Collections.sort(sortedNodes);
598        for (Node n : sortedNodes) {
599            if (n.isIncomplete() || n.isDeleted()) {
600                continue;
601            }
602            WayPoint wpt = new WayPoint(n.getCoor());
603
604            // Position info
605
606            addDoubleIfPresent(wpt, n, GpxConstants.PT_ELE);
607
608            if (!n.isTimestampEmpty()) {
609                wpt.put("time", DateUtils.fromDate(n.getTimestamp()));
610                wpt.setTime();
611            }
612
613            addDoubleIfPresent(wpt, n, GpxConstants.PT_MAGVAR);
614            addDoubleIfPresent(wpt, n, GpxConstants.PT_GEOIDHEIGHT);
615
616            // Description info
617
618            addStringIfPresent(wpt, n, GpxConstants.GPX_NAME);
619            addStringIfPresent(wpt, n, GpxConstants.GPX_DESC, "description");
620            addStringIfPresent(wpt, n, GpxConstants.GPX_CMT, "comment");
621            addStringIfPresent(wpt, n, GpxConstants.GPX_SRC, "source", "source:position");
622
623            Collection<GpxLink> links = new ArrayList<>();
624            for (String key : new String[]{"link", "url", "website", "contact:website"}) {
625                String value = n.get(key);
626                if (value != null) {
627                    links.add(new GpxLink(value));
628                }
629            }
630            wpt.put(GpxConstants.META_LINKS, links);
631
632            addStringIfPresent(wpt, n, GpxConstants.PT_SYM, "wpt_symbol");
633            addStringIfPresent(wpt, n, GpxConstants.PT_TYPE);
634
635            // Accuracy info
636            addStringIfPresent(wpt, n, GpxConstants.PT_FIX, "gps:fix");
637            addIntegerIfPresent(wpt, n, GpxConstants.PT_SAT, "gps:sat");
638            addDoubleIfPresent(wpt, n, GpxConstants.PT_HDOP, "gps:hdop");
639            addDoubleIfPresent(wpt, n, GpxConstants.PT_VDOP, "gps:vdop");
640            addDoubleIfPresent(wpt, n, GpxConstants.PT_PDOP, "gps:pdop");
641            addDoubleIfPresent(wpt, n, GpxConstants.PT_AGEOFDGPSDATA, "gps:ageofdgpsdata");
642            addIntegerIfPresent(wpt, n, GpxConstants.PT_DGPSID, "gps:dgpsid");
643
644            gpxData.waypoints.add(wpt);
645        }
646    }
647
648    private static void addIntegerIfPresent(WayPoint wpt, OsmPrimitive p, String gpxKey, String ... osmKeys) {
649        ArrayList<String> possibleKeys = new ArrayList<>(Arrays.asList(osmKeys));
650        possibleKeys.add(0, gpxKey);
651        for (String key : possibleKeys) {
652            String value = p.get(key);
653            if (value != null) {
654                try {
655                    int i = Integer.parseInt(value);
656                    // Sanity checks
657                    if ((!GpxConstants.PT_SAT.equals(gpxKey) || i >= 0) &&
658                        (!GpxConstants.PT_DGPSID.equals(gpxKey) || (0 <= i && i <= 1023))) {
659                        wpt.put(gpxKey, value);
660                        break;
661                    }
662                } catch (NumberFormatException e) {
663                    if (Main.isTraceEnabled()) {
664                        Main.trace(e.getMessage());
665                    }
666                }
667            }
668        }
669    }
670
671    private static void addDoubleIfPresent(WayPoint wpt, OsmPrimitive p, String gpxKey, String ... osmKeys) {
672        ArrayList<String> possibleKeys = new ArrayList<>(Arrays.asList(osmKeys));
673        possibleKeys.add(0, gpxKey);
674        for (String key : possibleKeys) {
675            String value = p.get(key);
676            if (value != null) {
677                try {
678                    double d = Double.parseDouble(value);
679                    // Sanity checks
680                    if (!GpxConstants.PT_MAGVAR.equals(gpxKey) || (0.0 <= d && d < 360.0)) {
681                        wpt.put(gpxKey, value);
682                        break;
683                    }
684                } catch (NumberFormatException e) {
685                    if (Main.isTraceEnabled()) {
686                        Main.trace(e.getMessage());
687                    }
688                }
689            }
690        }
691    }
692
693    private static void addStringIfPresent(WayPoint wpt, OsmPrimitive p, String gpxKey, String ... osmKeys) {
694        ArrayList<String> possibleKeys = new ArrayList<>(Arrays.asList(osmKeys));
695        possibleKeys.add(0, gpxKey);
696        for (String key : possibleKeys) {
697            String value = p.get(key);
698            if (value != null) {
699                // Sanity checks
700                if (!GpxConstants.PT_FIX.equals(gpxKey) || GpxConstants.FIX_VALUES.contains(value)) {
701                    wpt.put(gpxKey, value);
702                    break;
703                }
704            }
705        }
706    }
707
708    /**
709     * Converts OSM data behind this layer to GPX data.
710     * @return GPX data
711     */
712    public GpxData toGpxData() {
713        return toGpxData(data, getAssociatedFile());
714    }
715
716    /**
717     * Action that converts this OSM layer to a GPX layer.
718     */
719    public class ConvertToGpxLayerAction extends AbstractAction {
720        /**
721         * Constructs a new {@code ConvertToGpxLayerAction}.
722         */
723        public ConvertToGpxLayerAction() {
724            super(tr("Convert to GPX layer"), ImageProvider.get("converttogpx"));
725            putValue("help", ht("/Action/ConvertToGpxLayer"));
726        }
727        @Override
728        public void actionPerformed(ActionEvent e) {
729            Main.main.addLayer(new GpxLayer(toGpxData(), tr("Converted from: {0}", getName())));
730            Main.main.removeLayer(OsmDataLayer.this);
731        }
732    }
733
734    /**
735     * Determines if this layer contains data at the given coordinate.
736     * @param coor the coordinate
737     * @return {@code true} if data sources bounding boxes contain {@code coor}
738     */
739    public boolean containsPoint(LatLon coor) {
740        // we'll assume that if this has no data sources
741        // that it also has no borders
742        if (this.data.dataSources.isEmpty())
743            return true;
744
745        boolean layer_bounds_point = false;
746        for (DataSource src : this.data.dataSources) {
747            if (src.bounds.contains(coor)) {
748                layer_bounds_point = true;
749                break;
750            }
751        }
752        return layer_bounds_point;
753    }
754
755    /**
756     * Replies the set of conflicts currently managed in this layer.
757     *
758     * @return the set of conflicts currently managed in this layer
759     */
760    public ConflictCollection getConflicts() {
761        return conflicts;
762    }
763
764    @Override
765    public boolean requiresUploadToServer() {
766        return requiresUploadToServer;
767    }
768
769    @Override
770    public boolean requiresSaveToFile() {
771        return getAssociatedFile() != null && requiresSaveToFile;
772    }
773
774    @Override
775    public void onPostLoadFromFile() {
776        setRequiresSaveToFile(false);
777        setRequiresUploadToServer(isModified());
778    }
779
780    /**
781     * Actions run after data has been downloaded to this layer.
782     */
783    public void onPostDownloadFromServer() {
784        setRequiresSaveToFile(true);
785        setRequiresUploadToServer(isModified());
786    }
787
788    @Override
789    public boolean isChanged() {
790        return isChanged || highlightUpdateCount != data.getHighlightUpdateCount();
791    }
792
793    @Override
794    public void onPostSaveToFile() {
795        setRequiresSaveToFile(false);
796        setRequiresUploadToServer(isModified());
797    }
798
799    @Override
800    public void onPostUploadToServer() {
801        setRequiresUploadToServer(isModified());
802        // keep requiresSaveToDisk unchanged
803    }
804
805    private class ConsistencyTestAction extends AbstractAction {
806
807        public ConsistencyTestAction() {
808            super(tr("Dataset consistency test"));
809        }
810
811        @Override
812        public void actionPerformed(ActionEvent e) {
813            String result = DatasetConsistencyTest.runTests(data);
814            if (result.length() == 0) {
815                JOptionPane.showMessageDialog(Main.parent, tr("No problems found"));
816            } else {
817                JPanel p = new JPanel(new GridBagLayout());
818                p.add(new JLabel(tr("Following problems found:")), GBC.eol());
819                JosmTextArea info = new JosmTextArea(result, 20, 60);
820                info.setCaretPosition(0);
821                info.setEditable(false);
822                p.add(new JScrollPane(info), GBC.eop());
823
824                JOptionPane.showMessageDialog(Main.parent, p, tr("Warning"), JOptionPane.WARNING_MESSAGE);
825            }
826        }
827    }
828
829    @Override
830    public void destroy() {
831        DataSet.removeSelectionListener(this);
832    }
833
834    @Override
835    public void processDatasetEvent(AbstractDatasetChangedEvent event) {
836        isChanged = true;
837        setRequiresSaveToFile(true);
838        setRequiresUploadToServer(true);
839    }
840
841    @Override
842    public void selectionChanged(Collection<? extends OsmPrimitive> newSelection) {
843        isChanged = true;
844    }
845
846    @Override
847    public void projectionChanged(Projection oldValue, Projection newValue) {
848         // No reprojection required. The dataset itself is registered as projection
849         // change listener and already got notified.
850    }
851
852    @Override
853    public final boolean isUploadDiscouraged() {
854        return data.isUploadDiscouraged();
855    }
856
857    /**
858     * Sets the "discouraged upload" flag.
859     * @param uploadDiscouraged {@code true} if upload of data managed by this layer is discouraged. This feature allows to use "private" data layers.
860     */
861    public final void setUploadDiscouraged(boolean uploadDiscouraged) {
862        if (uploadDiscouraged ^ isUploadDiscouraged()) {
863            data.setUploadDiscouraged(uploadDiscouraged);
864            for (LayerStateChangeListener l : layerStateChangeListeners) {
865                l.uploadDiscouragedChanged(this, uploadDiscouraged);
866            }
867        }
868    }
869
870    @Override
871    public final boolean isModified() {
872        return data.isModified();
873    }
874
875    @Override
876    public boolean isSavable() {
877        return true; // With OsmExporter
878    }
879
880    @Override
881    public boolean checkSaveConditions() {
882        if (isDataSetEmpty()) {
883            if (1 != GuiHelper.runInEDTAndWaitAndReturn(new Callable<Integer>() {
884                @Override
885                public Integer call() {
886                    ExtendedDialog dialog = new ExtendedDialog(
887                            Main.parent,
888                            tr("Empty document"),
889                            new String[] {tr("Save anyway"), tr("Cancel")}
890                    );
891                    dialog.setContent(tr("The document contains no data."));
892                    dialog.setButtonIcons(new String[] {"save.png", "cancel.png"});
893                    return dialog.showDialog().getValue();
894                }
895            })) {
896                return false;
897            }
898        }
899
900        ConflictCollection conflicts = getConflicts();
901        if (conflicts != null && !conflicts.isEmpty()) {
902            if (1 != GuiHelper.runInEDTAndWaitAndReturn(new Callable<Integer>() {
903                @Override
904                public Integer call() {
905                    ExtendedDialog dialog = new ExtendedDialog(
906                            Main.parent,
907                            /* I18N: Display title of the window showing conflicts */
908                            tr("Conflicts"),
909                            new String[] {tr("Reject Conflicts and Save"), tr("Cancel")}
910                    );
911                    dialog.setContent(tr("There are unresolved conflicts. Conflicts will not be saved and handled as if you rejected all. Continue?"));
912                    dialog.setButtonIcons(new String[] {"save.png", "cancel.png"});
913                    return dialog.showDialog().getValue();
914                }
915            })) {
916                return false;
917            }
918        }
919        return true;
920    }
921
922    /**
923     * Check the data set if it would be empty on save. It is empty, if it contains
924     * no objects (after all objects that are created and deleted without being
925     * transferred to the server have been removed).
926     *
927     * @return <code>true</code>, if a save result in an empty data set.
928     */
929    private boolean isDataSetEmpty() {
930        if (data != null) {
931            for (OsmPrimitive osm : data.allNonDeletedPrimitives())
932                if (!osm.isDeleted() || !osm.isNewOrUndeleted())
933                    return false;
934        }
935        return true;
936    }
937
938    @Override
939    public File createAndOpenSaveFileChooser() {
940        return SaveActionBase.createAndOpenSaveFileChooser(tr("Save OSM file"), "osm");
941    }
942
943    @Override
944    public AbstractIOTask createUploadTask(final ProgressMonitor monitor) {
945        UploadDialog dialog = UploadDialog.getUploadDialog();
946        return new UploadLayerTask(
947                dialog.getUploadStrategySpecification(),
948                this,
949                monitor,
950                dialog.getChangeset());
951    }
952
953    @Override
954    public AbstractUploadDialog getUploadDialog() {
955        UploadDialog dialog = UploadDialog.getUploadDialog();
956        dialog.setUploadedPrimitives(new APIDataSet(data));
957        return dialog;
958    }
959}