001// License: GPL. For details, see LICENSE file.
002package org.openstreetmap.josm.actions.relation;
003
004import static org.openstreetmap.josm.tools.I18n.tr;
005
006import java.awt.event.ActionEvent;
007
008import org.openstreetmap.josm.data.osm.IRelation;
009import org.openstreetmap.josm.data.osm.Relation;
010import org.openstreetmap.josm.gui.MainApplication;
011import org.openstreetmap.josm.gui.dialogs.relation.RelationEditor;
012import org.openstreetmap.josm.tools.ImageProvider;
013
014/**
015 * Creates a new relation with a copy of the current editor state
016 * @since 5799
017 */
018public class DuplicateRelationAction extends AbstractRelationAction {
019
020    /**
021     * Constructs a new {@code DuplicateRelationAction}.
022     */
023    public DuplicateRelationAction() {
024        putValue(SHORT_DESCRIPTION, tr("Create a copy of this relation and open it in another editor window"));
025        new ImageProvider("duplicate").getResource().attachImageIcon(this, true);
026        putValue(NAME, tr("Duplicate"));
027    }
028
029    /**
030     * Duplicates the given relation and launches the relation editor for the created copy.
031     * @param original The relation to duplicate
032     */
033    public static void duplicateRelationAndLaunchEditor(Relation original) {
034        Relation copy = new Relation(original, true);
035        copy.setModified(true);
036        RelationEditor editor = RelationEditor.getEditor(
037                MainApplication.getLayerManager().getEditLayer(),
038                copy,
039                null /* no selected members */
040                );
041        editor.setVisible(true);
042    }
043
044    @Override
045    public void actionPerformed(ActionEvent e) {
046        if (!isEnabled() || relations.isEmpty())
047            return;
048        IRelation<?> r = relations.iterator().next();
049        if (r instanceof Relation) {
050            duplicateRelationAndLaunchEditor((Relation) r);
051        }
052    }
053
054    @Override
055    protected void updateEnabledState() {
056        // only one selected relation can be edited
057        setEnabled(relations.size() == 1
058                && relations.iterator().next() instanceof Relation
059                && !relations.iterator().next().getDataSet().isLocked());
060    }
061}