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.data.osm.DataSet; 012import org.openstreetmap.josm.data.osm.OsmPrimitive; 013import org.openstreetmap.josm.tools.Utils; 014 015/** 016 * Command that selects OSM primitives 017 * 018 * @author Landwirt 019 */ 020public class SelectCommand extends Command { 021 022 /** the primitives to select when executing the command */ 023 private final Collection<OsmPrimitive> newSelection; 024 025 /** the selection before applying the new selection */ 026 private Collection<OsmPrimitive> oldSelection; 027 028 /** 029 * Constructs a new select command. 030 * @param dataset The dataset the selection belongs to 031 * @param newSelection the primitives to select when executing the command. 032 * @since 12349 033 */ 034 public SelectCommand(DataSet dataset, Collection<OsmPrimitive> newSelection) { 035 super(dataset); 036 if (Utils.isEmpty(newSelection)) { 037 this.newSelection = Collections.emptySet(); 038 } else if (newSelection.contains(null)) { 039 throw new IllegalArgumentException("null primitive in selection"); 040 } else { 041 this.newSelection = new HashSet<>(newSelection); 042 } 043 } 044 045 @Override 046 public void fillModifiedData(Collection<OsmPrimitive> modified, Collection<OsmPrimitive> deleted, Collection<OsmPrimitive> added) { 047 // Do nothing 048 } 049 050 @Override 051 public void undoCommand() { 052 ensurePrimitivesAreInDataset(); 053 054 getAffectedDataSet().setSelected(oldSelection); 055 } 056 057 @Override 058 public boolean executeCommand() { 059 ensurePrimitivesAreInDataset(); 060 061 oldSelection = getAffectedDataSet().getSelected(); 062 getAffectedDataSet().setSelected(newSelection); 063 return true; 064 } 065 066 @Override 067 public Collection<? extends OsmPrimitive> getParticipatingPrimitives() { 068 return Collections.unmodifiableCollection(newSelection); 069 } 070 071 @Override 072 public String getDescriptionText() { 073 int size = newSelection != null ? newSelection.size() : 0; 074 return trn("Selected {0} object", "Selected {0} objects", size, size); 075 } 076 077 @Override 078 public int hashCode() { 079 return Objects.hash(super.hashCode(), newSelection, oldSelection); 080 } 081 082 @Override 083 public boolean equals(Object obj) { 084 if (this == obj) return true; 085 if (obj == null || getClass() != obj.getClass()) return false; 086 if (!super.equals(obj)) return false; 087 SelectCommand that = (SelectCommand) obj; 088 return Objects.equals(newSelection, that.newSelection) && 089 Objects.equals(oldSelection, that.oldSelection); 090 } 091}