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.Main;
010import org.openstreetmap.josm.actions.OsmPrimitiveAction;
011import org.openstreetmap.josm.data.osm.DataSet;
012import org.openstreetmap.josm.data.osm.DownloadPolicy;
013import org.openstreetmap.josm.data.osm.OsmPrimitive;
014import org.openstreetmap.josm.data.osm.Relation;
015import org.openstreetmap.josm.io.OnlineResource;
016import org.openstreetmap.josm.tools.SubclassFilteredCollection;
017
018/**
019 * Ancestor for all actions that want to work with relation collection and
020 * to be disabled if the collection is empty
021 * @since 5793
022 */
023public abstract class AbstractRelationAction extends AbstractAction implements OsmPrimitiveAction {
024    /** relation collection */
025    protected transient Collection<Relation> relations = Collections.<Relation>emptySet();
026
027    /**
028     * Returns the relations contained in the given collection.
029     * @param primitives collection of primitives
030     * @return the relation contained in {@code primitives}
031     */
032    protected static final Collection<Relation> getRelations(Collection<? extends OsmPrimitive> primitives) {
033        if (primitives == null || primitives.isEmpty()) {
034            return Collections.<Relation>emptySet();
035        } else {
036            return new SubclassFilteredCollection<>(primitives, Relation.class::isInstance);
037        }
038    }
039
040    @Override
041    public void setPrimitives(Collection<? extends OsmPrimitive> primitives) {
042        this.relations = getRelations(primitives);
043        updateEnabledState();
044    }
045
046    /**
047     * Override in subclasses to update the enabled state of the action when something changes.
048     */
049    protected void updateEnabledState() {
050        setEnabled(!relations.isEmpty());
051    }
052
053    protected final boolean canDownload() {
054        if (relations.isEmpty()) {
055            return false;
056        }
057        DataSet ds = relations.iterator().next().getDataSet();
058        return !Main.isOffline(OnlineResource.OSM_API)
059            && ds != null && !ds.isLocked() && !DownloadPolicy.BLOCKED.equals(ds.getDownloadPolicy());
060    }
061}