001// License: GPL. For details, see LICENSE file.
002package org.openstreetmap.josm.actions.relation;
003
004import java.util.Collection;
005import java.util.Collections;
006
007import javax.swing.AbstractAction;
008
009import org.openstreetmap.josm.actions.OsmPrimitiveAction;
010import org.openstreetmap.josm.data.osm.OsmPrimitive;
011import org.openstreetmap.josm.data.osm.Relation;
012import org.openstreetmap.josm.tools.SubclassFilteredCollection;
013
014/**
015 * Ancestor for all actions that want to work with relation collection and
016 * to be disabled if the collection is empty
017 * @since 5793
018 */
019public abstract class AbstractRelationAction extends AbstractAction implements OsmPrimitiveAction {
020    protected transient Collection<Relation> relations = Collections.<Relation>emptySet();
021
022    @SuppressWarnings("unused")
023    protected static final Collection<Relation> getRelations(Collection<? extends OsmPrimitive> primitives) {
024        if (primitives == null || primitives.isEmpty()) {
025            return Collections.<Relation>emptySet();
026        } else {
027            // Diamond operator does not work with Java 9 here
028            return new SubclassFilteredCollection<OsmPrimitive, Relation>(
029                    primitives, OsmPrimitive.relationPredicate);
030        }
031    }
032
033    @Override
034    public void setPrimitives(Collection<? extends OsmPrimitive> primitives) {
035        this.relations = getRelations(primitives);
036        updateEnabledState();
037    }
038
039    protected void updateEnabledState() {
040        setEnabled(!relations.isEmpty());
041    }
042}