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