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.IPrimitiveAction;
010import org.openstreetmap.josm.data.osm.DownloadPolicy;
011import org.openstreetmap.josm.data.osm.IPrimitive;
012import org.openstreetmap.josm.data.osm.IRelation;
013import org.openstreetmap.josm.data.osm.OsmData;
014import org.openstreetmap.josm.io.NetworkManager;
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 * @since 13957 (signature)
023 */
024public abstract class AbstractRelationAction extends AbstractAction implements IPrimitiveAction {
025    /** relation collection */
026    protected transient Collection<IRelation<?>> relations = Collections.<IRelation<?>>emptySet();
027
028    /**
029     * Returns the relations contained in the given collection.
030     * @param primitives collection of primitives
031     * @return the relation contained in {@code primitives}
032     */
033    protected static final Collection<IRelation<?>> getRelations(Collection<? extends IPrimitive> primitives) {
034        if (primitives == null || primitives.isEmpty()) {
035            return Collections.<IRelation<?>>emptySet();
036        } else {
037            return new SubclassFilteredCollection<>(primitives, IRelation.class::isInstance);
038        }
039    }
040
041    @Override
042    public void setPrimitives(Collection<? extends IPrimitive> primitives) {
043        this.relations = getRelations(primitives);
044        updateEnabledState();
045    }
046
047    /**
048     * Override in subclasses to update the enabled state of the action when something changes.
049     */
050    protected void updateEnabledState() {
051        setEnabled(!relations.isEmpty());
052    }
053
054    protected final boolean canDownload() {
055        if (relations.isEmpty()) {
056            return false;
057        }
058        OsmData<?, ?, ?, ?> ds = relations.iterator().next().getDataSet();
059        return !NetworkManager.isOffline(OnlineResource.OSM_API)
060            && ds != null && !ds.isLocked() && DownloadPolicy.BLOCKED != ds.getDownloadPolicy();
061    }
062    
063    protected void setHelpId(String helpId) {
064        putValue("help", helpId);
065    }
066}