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
077        if (ValidatorPrefHelper.PREF_USE_IGNORE.get()) {
078            int nume = 0;
079            for (TestError error : errors) {
080                List<String> s = new ArrayList<>();
081                s.add(error.getIgnoreState());
082                s.add(error.getIgnoreGroup());
083                s.add(error.getIgnoreSubGroup());
084                for (String state : s) {
085                    if (state != null && OsmValidator.hasIgnoredError(state)) {
086                        error.setIgnored(true);
087                    }
088                }
089                if (!error.isIgnored()) {
090                    ++nume;
091                }
092            }
093            if (nume == 0)
094                return true;
095        }
096
097        OsmDataLayer editLayer = MainApplication.getLayerManager().getEditLayer();
098        if (editLayer != null) {
099            editLayer.validationErrors.clear();
100            editLayer.validationErrors.addAll(errors);
101        }
102        MapFrame map = MainApplication.getMap();
103        if (map != null) {
104            map.validatorDialog.tree.setErrors(errors);
105        }
106        if (errors.isEmpty())
107            return true;
108
109        return displayErrorScreen(errors);
110    }
111
112    /**
113     * Displays a screen where the actions that would be taken are displayed and
114     * give the user the possibility to cancel the upload.
115     * @param errors The errors displayed in the screen
116     * @return <code>true</code>, if the upload should continue. <code>false</code>
117     *          if the user requested cancel.
118     */
119    private static boolean displayErrorScreen(List<TestError> errors) {
120        JPanel p = new JPanel(new GridBagLayout());
121        ValidatorTreePanel errorPanel = new ValidatorTreePanel(errors);
122        errorPanel.expandAll();
123        HtmlPanel pnlMessage = new HtmlPanel();
124        pnlMessage.setText("<html><body>"
125                + tr("The following are results of automatic validation. Try fixing"
126                + " these, but be careful (don''t destroy valid data)."
127                + " When in doubt ignore them.<br>When you"
128                + " cancel this dialog, you can find the entries in the validator"
129                + " side panel to inspect them.")
130                + "<table align=\"center\">"
131                + "<tr><td align=\"left\"><b>"+tr("Errors")
132                + "&nbsp;</b></td><td align=\"left\">"
133                + tr("Usually this should be fixed.")+"</td></tr>"
134                + "<tr><td align=\"left\"><b>"+tr("Warnings")
135                + "&nbsp;</b></td><td align=\"left\">"
136                + tr("Fix these when possible.")+"</td></tr>"
137                + "<tr><td align=\"left\"><b>"+tr("Other")
138                + "&nbsp;</b></td><td align=\"left\">"
139                + tr("Informational warnings, expect many false entries.")+"</td></tr>"
140                + "</table>"
141        );
142        pnlMessage.setPreferredSize(new Dimension(500, 150));
143        p.add(pnlMessage, GBC.eol().fill(GBC.HORIZONTAL));
144        p.add(new JScrollPane(errorPanel), GBC.eol().fill(GBC.BOTH));
145
146        ExtendedDialog ed = new ExtendedDialog(Main.parent,
147                tr("Suspicious data found. Upload anyway?"),
148                tr("Continue upload"), tr("Cancel"))
149            .setButtonIcons("ok", "cancel")
150            .setContent(p);
151
152        if (ed.showDialog().getValue() != 1) {
153            OsmValidator.initializeTests();
154            OsmValidator.initializeErrorLayer();
155            MainApplication.getMap().validatorDialog.unfurlDialog();
156            MainApplication.getLayerManager().getLayersOfType(ValidatorLayer.class).forEach(ValidatorLayer::invalidate);
157            return false;
158        }
159        return true;
160    }
161}