001// License: GPL. For details, see LICENSE file.
002package org.openstreetmap.josm.actions.upload;
003
004import static org.openstreetmap.josm.tools.I18n.tr;
005
006import java.awt.Dimension;
007import java.awt.GridBagLayout;
008import java.util.ArrayList;
009import java.util.Collection;
010import java.util.List;
011
012import javax.swing.JPanel;
013import javax.swing.JScrollPane;
014
015import org.openstreetmap.josm.Main;
016import org.openstreetmap.josm.data.APIDataSet;
017import org.openstreetmap.josm.data.osm.OsmPrimitive;
018import org.openstreetmap.josm.data.preferences.sources.ValidatorPrefHelper;
019import org.openstreetmap.josm.data.validation.OsmValidator;
020import org.openstreetmap.josm.data.validation.Severity;
021import org.openstreetmap.josm.data.validation.Test;
022import org.openstreetmap.josm.data.validation.TestError;
023import org.openstreetmap.josm.data.validation.util.AggregatePrimitivesVisitor;
024import org.openstreetmap.josm.gui.ExtendedDialog;
025import org.openstreetmap.josm.gui.MainApplication;
026import org.openstreetmap.josm.gui.MapFrame;
027import org.openstreetmap.josm.gui.dialogs.validator.ValidatorTreePanel;
028import org.openstreetmap.josm.gui.layer.OsmDataLayer;
029import org.openstreetmap.josm.gui.layer.ValidatorLayer;
030import org.openstreetmap.josm.gui.widgets.HtmlPanel;
031import org.openstreetmap.josm.tools.GBC;
032
033/**
034 * The action that does the validate thing.
035 * <p>
036 * This action iterates through all active tests and give them the data, so that
037 * each one can test it.
038 *
039 * @author frsantos
040 * @since 3669
041 */
042public class ValidateUploadHook implements UploadHook {
043
044    /**
045     * Validate the modified data before uploading
046     */
047    @Override
048    public boolean checkUpload(APIDataSet apiDataSet) {
049
050        OsmValidator.initializeTests();
051        Collection<Test> tests = OsmValidator.getEnabledTests(true);
052        if (tests.isEmpty())
053            return true;
054
055        AggregatePrimitivesVisitor v = new AggregatePrimitivesVisitor();
056        v.visit(apiDataSet.getPrimitivesToAdd());
057        Collection<OsmPrimitive> selection = v.visit(apiDataSet.getPrimitivesToUpdate());
058
059        List<TestError> errors = new ArrayList<>(30);
060        for (Test test : tests) {
061            test.setBeforeUpload(true);
062            test.setPartialSelection(true);
063            test.startTest(null);
064            test.visit(selection);
065            test.endTest();
066            if (ValidatorPrefHelper.PREF_OTHER.get() && ValidatorPrefHelper.PREF_OTHER_UPLOAD.get()) {
067                errors.addAll(test.getErrors());
068            } else {
069                for (TestError e : test.getErrors()) {
070                    if (e.getSeverity() != Severity.OTHER) {
071                        errors.add(e);
072                    }
073                }
074            }
075        }
076        OsmDataLayer editLayer = MainApplication.getLayerManager().getEditLayer();
077        if (editLayer != null) {
078            editLayer.validationErrors.clear();
079            editLayer.validationErrors.addAll(errors);
080        }
081        MapFrame map = MainApplication.getMap();
082        if (map != null) {
083            map.validatorDialog.tree.setErrors(errors);
084        }
085        if (errors.isEmpty())
086            return true;
087
088        if (ValidatorPrefHelper.PREF_USE_IGNORE.get()) {
089            int nume = 0;
090            for (TestError error : errors) {
091                List<String> s = new ArrayList<>();
092                s.add(error.getIgnoreState());
093                s.add(error.getIgnoreGroup());
094                s.add(error.getIgnoreSubGroup());
095                for (String state : s) {
096                    if (state != null && OsmValidator.hasIgnoredError(state)) {
097                        error.setIgnored(true);
098                    }
099                }
100                if (!error.isIgnored()) {
101                    ++nume;
102                }
103            }
104            if (nume == 0)
105                return true;
106        }
107        return displayErrorScreen(errors);
108    }
109
110    /**
111     * Displays a screen where the actions that would be taken are displayed and
112     * give the user the possibility to cancel the upload.
113     * @param errors The errors displayed in the screen
114     * @return <code>true</code>, if the upload should continue. <code>false</code>
115     *          if the user requested cancel.
116     */
117    private static boolean displayErrorScreen(List<TestError> errors) {
118        JPanel p = new JPanel(new GridBagLayout());
119        ValidatorTreePanel errorPanel = new ValidatorTreePanel(errors);
120        errorPanel.expandAll();
121        HtmlPanel pnlMessage = new HtmlPanel();
122        pnlMessage.setText("<html><body>"
123                + tr("The following are results of automatic validation. Try fixing"
124                + " these, but be careful (don''t destroy valid data)."
125                + " When in doubt ignore them.<br>When you"
126                + " cancel this dialog, you can find the entries in the validator"
127                + " side panel to inspect them.")
128                + "<table align=\"center\">"
129                + "<tr><td align=\"left\"><b>"+tr("Errors")
130                + "&nbsp;</b></td><td align=\"left\">"
131                + tr("Usually this should be fixed.")+"</td></tr>"
132                + "<tr><td align=\"left\"><b>"+tr("Warnings")
133                + "&nbsp;</b></td><td align=\"left\">"
134                + tr("Fix these when possible.")+"</td></tr>"
135                + "<tr><td align=\"left\"><b>"+tr("Other")
136                + "&nbsp;</b></td><td align=\"left\">"
137                + tr("Informational warnings, expect many false entries.")+"</td></tr>"
138                + "</table>"
139        );
140        pnlMessage.setPreferredSize(new Dimension(500, 150));
141        p.add(pnlMessage, GBC.eol().fill(GBC.HORIZONTAL));
142        p.add(new JScrollPane(errorPanel), GBC.eol().fill(GBC.BOTH));
143
144        ExtendedDialog ed = new ExtendedDialog(Main.parent,
145                tr("Suspicious data found. Upload anyway?"),
146                tr("Continue upload"), tr("Cancel"))
147            .setButtonIcons("ok", "cancel")
148            .setContent(p);
149
150        if (ed.showDialog().getValue() != 1) {
151            OsmValidator.initializeTests();
152            OsmValidator.initializeErrorLayer();
153            MainApplication.getMap().validatorDialog.unfurlDialog();
154            MainApplication.getLayerManager().getLayersOfType(ValidatorLayer.class).forEach(ValidatorLayer::invalidate);
155            return false;
156        }
157        return true;
158    }
159}