001// License: GPL. For details, see LICENSE file.
002package org.openstreetmap.josm.command;
003
004import static org.openstreetmap.josm.tools.I18n.trn;
005
006import java.util.Collection;
007import java.util.Collections;
008import java.util.HashSet;
009import java.util.Objects;
010
011import org.openstreetmap.josm.Main;
012import org.openstreetmap.josm.data.osm.OsmPrimitive;
013
014/**
015 * Command that selects OSM primitives
016 *
017 * @author Landwirt
018 */
019public class SelectCommand extends Command {
020
021    /** the primitives to select when executing the command */
022    private final Collection<OsmPrimitive> newSelection;
023
024    /** the selection before applying the new selection */
025    private Collection<OsmPrimitive> oldSelection;
026
027    /**
028     * Constructs a new select command.
029     * @param newSelection the primitives to select when executing the command.
030     */
031    public SelectCommand(Collection<OsmPrimitive> newSelection) {
032        if (newSelection == null || newSelection.isEmpty()) {
033            this.newSelection = Collections.emptySet();
034        } else {
035            this.newSelection = new HashSet<>(newSelection);
036        }
037    }
038
039    @Override
040    public void fillModifiedData(Collection<OsmPrimitive> modified, Collection<OsmPrimitive> deleted, Collection<OsmPrimitive> added) {
041        // Do nothing
042    }
043
044    @Override
045    public void undoCommand() {
046        Main.getLayerManager().getEditLayer().data.setSelected(oldSelection);
047    }
048
049    @Override
050    public boolean executeCommand() {
051        oldSelection = Main.getLayerManager().getEditLayer().data.getSelected();
052        Main.getLayerManager().getEditLayer().data.setSelected(newSelection);
053        return true;
054    }
055
056    @Override
057    public String getDescriptionText() {
058        int size = newSelection != null ? newSelection.size() : 0;
059        return trn("Selected {0} object", "Selected {0} objects", size, size);
060    }
061
062    @Override
063    public int hashCode() {
064        return Objects.hash(super.hashCode(), newSelection, oldSelection);
065    }
066
067    @Override
068    public boolean equals(Object obj) {
069        if (this == obj) return true;
070        if (obj == null || getClass() != obj.getClass()) return false;
071        if (!super.equals(obj)) return false;
072        SelectCommand that = (SelectCommand) obj;
073        return Objects.equals(newSelection, that.newSelection) &&
074                Objects.equals(oldSelection, that.oldSelection);
075    }
076}