001// License: GPL. For details, see LICENSE file. 002package org.openstreetmap.josm.command; 003 004import static org.openstreetmap.josm.tools.I18n.marktr; 005import static org.openstreetmap.josm.tools.I18n.tr; 006 007import java.util.Collection; 008import java.util.Collections; 009 010import javax.swing.Icon; 011 012import org.openstreetmap.josm.data.osm.OsmPrimitive; 013import org.openstreetmap.josm.data.osm.OsmPrimitiveType; 014import org.openstreetmap.josm.gui.DefaultNameFormatter; 015import org.openstreetmap.josm.gui.layer.OsmDataLayer; 016import org.openstreetmap.josm.tools.ImageProvider; 017 018/** 019 * A command that adds an osm primitive to a dataset. Keys cannot be added this way. 020 * 021 * See {@link ChangeCommand} for comments on relation back references. 022 * 023 * @author imi 024 */ 025public class AddCommand extends Command { 026 027 /** 028 * The primitive to add to the dataset. 029 */ 030 private final OsmPrimitive osm; 031 032 /** 033 * Creates the command and specify the element to add in the context of the current edit layer, if any. 034 * @param osm The primitive to add 035 */ 036 public AddCommand(OsmPrimitive osm) { 037 this.osm = osm; 038 } 039 040 /** 041 * Creates the command and specify the element to add in the context of the given data layer. 042 * @param layer The data layer. Must not be {@code null} 043 * @param osm The primitive to add 044 */ 045 public AddCommand(OsmDataLayer layer, OsmPrimitive osm) { 046 super(layer); 047 this.osm = osm; 048 } 049 050 @Override 051 public boolean executeCommand() { 052 getLayer().data.addPrimitive(osm); 053 osm.setModified(true); 054 return true; 055 } 056 057 @Override 058 public void undoCommand() { 059 getLayer().data.removePrimitive(osm); 060 } 061 062 @Override 063 public void fillModifiedData(Collection<OsmPrimitive> modified, Collection<OsmPrimitive> deleted, Collection<OsmPrimitive> added) { 064 added.add(osm); 065 } 066 067 @Override 068 public String getDescriptionText() { 069 String msg; 070 switch(OsmPrimitiveType.from(osm)) { 071 case NODE: msg = marktr("Add node {0}"); break; 072 case WAY: msg = marktr("Add way {0}"); break; 073 case RELATION: msg = marktr("Add relation {0}"); break; 074 default: /* should not happen */msg = ""; break; 075 } 076 return tr(msg, osm.getDisplayName(DefaultNameFormatter.getInstance())); 077 } 078 079 @Override 080 public Icon getDescriptionIcon() { 081 return ImageProvider.get(osm.getDisplayType()); 082 } 083 084 @Override 085 public Collection<OsmPrimitive> getParticipatingPrimitives() { 086 return Collections.singleton(osm); 087 } 088}