Ticket #21825: 21825.3.patch

File 21825.3.patch, 14.1 KB (added by taylor.smock, 4 years ago)

Add validate and isUseful functions to IRelation, use both in GenericRelationEditor -- isUseful controls whether or not the relation will be deleted and validate provides live validator feedback.

  • src/org/openstreetmap/josm/data/osm/IRelation.java

    diff --git a/src/org/openstreetmap/josm/data/osm/IRelation.java b/src/org/openstreetmap/josm/data/osm/IRelation.java
    index 6d59bd427a..9a7897d36f 100644
    a b  
    22package org.openstreetmap.josm.data.osm;
    33
    44import java.util.Collection;
     5import java.util.Collections;
    56import java.util.List;
    67import java.util.stream.Collectors;
    78
     9import org.openstreetmap.josm.data.validation.TestError;
    810import org.openstreetmap.josm.tools.Utils;
    911
    1012/**
    public interface IRelation<M extends IRelationMember<?>> extends IPrimitive {  
    138140        return getMembers().stream().filter(rmv -> role.equals(rmv.getRole()))
    139141                .map(IRelationMember::getMember).collect(Collectors.toList());
    140142    }
     143
     144    /**
     145     * Check if this relation is useful
     146     * @return {@code true} if this relation is useful
     147     */
     148    default boolean isUseful() {
     149        return !this.isEmpty() && this.hasKey("type");
     150    }
     151
     152    /**
     153     * Check if this relation is valid
     154     * @return A collection of errors, if any
     155     */
     156    default Collection<TestError> validate() {
     157        return Collections.emptyList();
     158    }
    141159}
  • src/org/openstreetmap/josm/data/osm/Relation.java

    diff --git a/src/org/openstreetmap/josm/data/osm/Relation.java b/src/org/openstreetmap/josm/data/osm/Relation.java
    index 3b12c48c80..d0405bd938 100644
    a b import java.util.stream.Stream;  
    1414
    1515import org.openstreetmap.josm.data.osm.visitor.OsmPrimitiveVisitor;
    1616import org.openstreetmap.josm.data.osm.visitor.PrimitiveVisitor;
     17import org.openstreetmap.josm.data.validation.OsmValidator;
     18import org.openstreetmap.josm.data.validation.TestError;
     19import org.openstreetmap.josm.data.validation.tests.MultipolygonTest;
     20import org.openstreetmap.josm.data.validation.tests.RelationChecker;
     21import org.openstreetmap.josm.data.validation.tests.TurnrestrictionTest;
     22import org.openstreetmap.josm.gui.progress.NullProgressMonitor;
    1723import org.openstreetmap.josm.spi.preferences.Config;
    1824import org.openstreetmap.josm.tools.CopyList;
    1925import org.openstreetmap.josm.tools.SubclassFilteredCollection;
    public final class Relation extends OsmPrimitive implements IRelation<RelationMe  
    567573    public UniqueIdGenerator getIdGenerator() {
    568574        return idGenerator;
    569575    }
     576
     577    @Override
     578    public Collection<TestError> validate() {
     579        return Stream.of(MultipolygonTest.class, TurnrestrictionTest.class, RelationChecker.class)
     580                .map(OsmValidator::getTest).filter(test -> test.enabled || test.testBeforeUpload).flatMap(test -> {
     581            test.startTest(NullProgressMonitor.INSTANCE);
     582            test.visit((Relation) this);
     583            test.endTest();
     584            return test.getErrors().stream();
     585        }).collect(Collectors.toList());
     586    }
    570587}
  • src/org/openstreetmap/josm/data/validation/tests/RelationChecker.java

    diff --git a/src/org/openstreetmap/josm/data/validation/tests/RelationChecker.java b/src/org/openstreetmap/josm/data/validation/tests/RelationChecker.java
    index 959f73d1d0..26184c7725 100644
    a b public class RelationChecker extends Test implements TaggingPresetListener {  
    154154                    .message(tr("Route scheme is unspecified. Add {0} ({1}=public_transport; {2}=legacy)", "public_transport:version", "2", "1"))
    155155                    .primitives(n)
    156156                    .build());
    157         } else if (n.hasKey("type") && allroles.isEmpty()) {
     157        } else if (n.hasKey("type") && allroles.isEmpty() || !n.hasKey("type")) {
    158158            errors.add(TestError.builder(this, Severity.OTHER, RELATION_UNKNOWN)
    159159                    .message(tr("Relation type is unknown"))
    160160                    .primitives(n)
  • src/org/openstreetmap/josm/gui/dialogs/relation/GenericRelationEditor.java

    diff --git a/src/org/openstreetmap/josm/gui/dialogs/relation/GenericRelationEditor.java b/src/org/openstreetmap/josm/gui/dialogs/relation/GenericRelationEditor.java
    index 743e05f4e0..52f17e72e7 100644
    a b package org.openstreetmap.josm.gui.dialogs.relation;  
    33
    44import static org.openstreetmap.josm.gui.help.HelpUtil.ht;
    55import static org.openstreetmap.josm.tools.I18n.tr;
     6import static org.openstreetmap.josm.tools.I18n.trn;
    67
    78import java.awt.BorderLayout;
    89import java.awt.Component;
    import java.util.ArrayList;  
    2627import java.util.Arrays;
    2728import java.util.Collection;
    2829import java.util.Collections;
     30import java.util.Comparator;
    2931import java.util.EnumSet;
    3032import java.util.List;
    3133import java.util.Set;
    import javax.swing.JTabbedPane;  
    4749import javax.swing.JTable;
    4850import javax.swing.JToolBar;
    4951import javax.swing.KeyStroke;
     52import javax.swing.event.TableModelListener;
    5053
    5154import org.openstreetmap.josm.actions.JosmAction;
    5255import org.openstreetmap.josm.command.ChangeMembersCommand;
    import org.openstreetmap.josm.data.osm.OsmPrimitive;  
    5861import org.openstreetmap.josm.data.osm.Relation;
    5962import org.openstreetmap.josm.data.osm.RelationMember;
    6063import org.openstreetmap.josm.data.osm.Tag;
     64import org.openstreetmap.josm.data.validation.TestError;
    6165import org.openstreetmap.josm.data.validation.tests.RelationChecker;
    6266import org.openstreetmap.josm.gui.ConditionalOptionPaneUtil;
    6367import org.openstreetmap.josm.gui.MainApplication;
    import org.openstreetmap.josm.gui.tagging.presets.TaggingPresets;  
    108112import org.openstreetmap.josm.gui.util.WindowGeometry;
    109113import org.openstreetmap.josm.spi.preferences.Config;
    110114import org.openstreetmap.josm.tools.CheckParameterUtil;
     115import org.openstreetmap.josm.tools.GBC;
     116import org.openstreetmap.josm.tools.ImageProvider;
    111117import org.openstreetmap.josm.tools.InputMapUtils;
    112118import org.openstreetmap.josm.tools.Logging;
    113119import org.openstreetmap.josm.tools.Shortcut;
    public class GenericRelationEditor extends RelationEditor implements CommandQueu  
    276282
    277283        getContentPane().add(buildToolBar(refreshAction, applyAction, selectAction, duplicateAction, deleteAction), BorderLayout.NORTH);
    278284        getContentPane().add(tabbedPane, BorderLayout.CENTER);
    279         getContentPane().add(buildOkCancelButtonPanel(okAction, cancelAction), BorderLayout.SOUTH);
     285        getContentPane().add(buildOkCancelButtonPanel(okAction, deleteAction, cancelAction), BorderLayout.SOUTH);
    280286
    281287        setSize(findMaxDialogSize());
    282288
    public class GenericRelationEditor extends RelationEditor implements CommandQueu  
    407413     *
    408414     * @return the panel with the OK and the Cancel button
    409415     */
    410     protected static JPanel buildOkCancelButtonPanel(OKAction okAction, CancelAction cancelAction) {
    411         JPanel pnl = new JPanel(new FlowLayout(FlowLayout.CENTER));
    412         pnl.add(new JButton(okAction));
     416    protected JPanel buildOkCancelButtonPanel(OKAction okAction, DeleteCurrentRelationAction deleteAction,
     417            CancelAction cancelAction) {
     418        JPanel mainPanel = new JPanel(new GridBagLayout());
     419        final JLabel errorLabel = new JLabel(" ");
     420        final JPanel pnl = new JPanel(new FlowLayout(FlowLayout.CENTER));
     421        mainPanel.add(errorLabel, GBC.eol().anchor(GridBagConstraints.CENTER));
     422        mainPanel.add(pnl, GBC.eol().anchor(GridBagConstraints.CENTER));
     423        final JButton okButton = new JButton(okAction);
     424        final JButton deleteButton = new JButton(deleteAction);
     425        okButton.setPreferredSize(deleteButton.getPreferredSize());
     426        pnl.add(okButton);
     427        pnl.add(deleteButton);
    413428        pnl.add(new JButton(cancelAction));
    414429        pnl.add(new JButton(new ContextSensitiveHelpAction(ht("/Dialog/RelationEditor"))));
    415         return pnl;
     430        // Keep users from saving invalid relations -- a relation MUST have at least a tag with the key "type"
     431        // AND must contain at least one other OSM object.
     432        final TableModelListener listener = l -> {
     433            final Relation newRelation = new Relation();
     434            this.tagEditorPanel.getModel().applyToPrimitive(newRelation);
     435            this.memberTableModel.applyToRelation(newRelation);
     436            updateOkPanel(newRelation, okButton, deleteButton);
     437            updateErrorMessage(newRelation, errorLabel);
     438        };
     439        listener.tableChanged(null);
     440        this.memberTableModel.addTableModelListener(listener);
     441        this.tagEditorPanel.getModel().addTableModelListener(listener);
     442        return mainPanel;
     443    }
     444
     445    /**
     446     * Update the OK panel area
     447     * @param newRelation What the new relation would "look" like if it were to be saved now
     448     * @param okButton The OK button
     449     * @param deleteButton The delete button
     450     */
     451    private void updateOkPanel(Relation newRelation, JButton okButton, JButton deleteButton) {
     452        okButton.setVisible(newRelation.isUseful() || this.getRelationSnapshot() == null);
     453        deleteButton.setVisible(!newRelation.isUseful() && this.getRelationSnapshot() != null);
     454        if (this.getRelationSnapshot() == null && !newRelation.isUseful()) {
     455            okButton.setText(tr("Delete"));
     456        } else {
     457            okButton.setText(tr("OK"));
     458        }
     459    }
     460
     461    /**
     462     * Update the error message
     463     * @param newRelation What the new relation would "look" like if it were to be saved now
     464     * @param errorPane The pane (used for background colour)
     465     * @param errorLabel The label to update
     466     */
     467    private void updateErrorMessage(Relation newRelation, JLabel errorLabel) {
     468        Collection<TestError> errors = newRelation.validate();
     469        if (errors.isEmpty()) {
     470            // Setting " " helps keep the label in place for layout calculations
     471            errorLabel.setText(" ");
     472            errorLabel.setIcon(null);
     473        } else {
     474            final TestError error = errors.stream()
     475                    .min(Comparator.comparingInt(testError -> testError.getSeverity().getLevel()))
     476                    .orElse(errors.iterator().next());
     477            final StringBuilder sb = new StringBuilder();
     478            if (error.getDescription() != null) {
     479                sb.append(error.getDescription()).append(": ");
     480            }
     481            sb.append(error.getMessage());
     482            if (errors.size() > 1) {
     483                sb.append(trn(" with {0} more problem", " with {0} more problems", errors.size() - 1, errors.size() - 1));
     484            }
     485            errorLabel.setIcon(ImageProvider.get("data", error.getSeverity().getIcon()));
     486            errorLabel.setText(sb.toString());
     487        }
    416488    }
    417489
    418490    /**
  • src/org/openstreetmap/josm/gui/dialogs/relation/actions/CancelAction.java

    diff --git a/src/org/openstreetmap/josm/gui/dialogs/relation/actions/CancelAction.java b/src/org/openstreetmap/josm/gui/dialogs/relation/actions/CancelAction.java
    index 6efdaeabdf..e36ae38182 100644
    a b import java.awt.event.ActionEvent;  
    88import javax.swing.JOptionPane;
    99import javax.swing.RootPaneContainer;
    1010
     11import org.openstreetmap.josm.data.osm.IRelation;
    1112import org.openstreetmap.josm.data.osm.Relation;
    1213import org.openstreetmap.josm.gui.HelpAwareOptionPane;
    1314import org.openstreetmap.josm.gui.HelpAwareOptionPane.ButtonSpec;
    public class CancelAction extends SavingAction {  
    4748        if ((!getMemberTableModel().hasSameMembersAs(snapshot) || getTagModel().isDirty())
    4849         && !(snapshot == null && getTagModel().getTags().isEmpty())) {
    4950            //give the user a chance to save the changes
    50             int ret = confirmClosingByCancel();
     51            final Relation newRelation;
     52            if (getEditor().getRelation() != null) {
     53                newRelation = getEditor().getRelation();
     54            } else {
     55                newRelation = new Relation();
     56                getTagModel().applyToPrimitive(newRelation);
     57                getMemberTableModel().applyToRelation(newRelation);
     58            }
     59            int ret = confirmClosingByCancel(newRelation);
    5160            if (ret == 0) { //Yes, save the changes
    5261                //copied from OKAction.run()
    5362                Config.getPref().put("relation.editor.generic.lastrole", Utils.strip(tfRole.getText()));
    public class CancelAction extends SavingAction {  
    6069        hideEditor();
    6170    }
    6271
    63     protected int confirmClosingByCancel() {
     72    protected int confirmClosingByCancel(final IRelation<?> newRelation) {
    6473        ButtonSpec[] options = {
    6574                new ButtonSpec(
    6675                        tr("Yes, save the changes and close"),
    public class CancelAction extends SavingAction {  
    8291                )
    8392        };
    8493
     94        // Keep users from saving invalid relations -- a relation MUST have at least a tag with the key "type"
     95        // AND must contain at least one other OSM object.
     96        options[0].setEnabled(newRelation.isUseful());
     97
    8598        return HelpAwareOptionPane.showOptionDialog(
    8699                MainApplication.getMainFrame(),
    87100                tr("<html>The relation has been changed.<br><br>Do you want to save your changes?</html>"),
  • src/org/openstreetmap/josm/gui/dialogs/relation/actions/SavingAction.java

    diff --git a/src/org/openstreetmap/josm/gui/dialogs/relation/actions/SavingAction.java b/src/org/openstreetmap/josm/gui/dialogs/relation/actions/SavingAction.java
    index 26813f23c1..35ca1dcfb7 100644
    a b abstract class SavingAction extends AbstractRelationEditorAction {  
    5454        tagEditorModel.applyToPrimitive(newRelation);
    5555        getMemberTableModel().applyToRelation(newRelation);
    5656        // If the user wanted to create a new relation, but hasn't added any members or
    57         // tags, don't add an empty relation
    58         if (newRelation.isEmpty() && !newRelation.hasKeys())
     57        // tags (specifically the "type" tag), don't add the relation
     58        if (!newRelation.isUseful())
    5959            return;
    6060        UndoRedoHandler.getInstance().add(new AddCommand(getLayer().getDataSet(), newRelation));
    6161