001// License: GPL. For details, see LICENSE file.
002package org.openstreetmap.josm.actions;
003
004import static org.openstreetmap.josm.gui.help.HelpUtil.ht;
005import static org.openstreetmap.josm.tools.I18n.tr;
006
007import java.awt.event.ActionEvent;
008import java.awt.event.KeyEvent;
009import java.util.Collections;
010
011import org.openstreetmap.josm.Main;
012import org.openstreetmap.josm.command.AddCommand;
013import org.openstreetmap.josm.data.coor.LatLon;
014import org.openstreetmap.josm.data.osm.Node;
015import org.openstreetmap.josm.data.osm.OsmPrimitive;
016import org.openstreetmap.josm.gui.dialogs.LatLonDialog;
017import org.openstreetmap.josm.tools.Shortcut;
018
019/**
020 * This action displays a dialog where the user can enter a latitude and longitude,
021 * and when ok is pressed, a new node is created at the specified position.
022 */
023public final class AddNodeAction extends JosmAction {
024    // remember input from last time
025    private String textLatLon, textEastNorth;
026
027    /**
028     * Constructs a new {@code AddNodeAction}.
029     */
030    public AddNodeAction() {
031        super(tr("Add Node..."), "addnode", tr("Add a node by entering latitude / longitude or easting / northing."),
032                Shortcut.registerShortcut("addnode", tr("Edit: {0}", tr("Add Node...")),
033                        KeyEvent.VK_D, Shortcut.SHIFT), true);
034        putValue("help", ht("/Action/AddNode"));
035    }
036
037    @Override
038    public void actionPerformed(ActionEvent e) {
039        if (!isEnabled())
040            return;
041
042        LatLonDialog dialog = new LatLonDialog(Main.parent, tr("Add Node..."), ht("/Action/AddNode"));
043
044        if (textLatLon != null) {
045            dialog.setLatLonText(textLatLon);
046        }
047        if (textEastNorth != null) {
048            dialog.setEastNorthText(textEastNorth);
049        }
050
051        dialog.showDialog();
052
053        if (dialog.getValue() != 1)
054            return;
055
056        LatLon coordinates = dialog.getCoordinates();
057        if (coordinates == null)
058            return;
059
060        textLatLon = dialog.getLatLonText();
061        textEastNorth = dialog.getEastNorthText();
062
063        Node nnew = new Node(coordinates);
064
065        // add the node
066        Main.main.undoRedo.add(new AddCommand(nnew));
067        getCurrentDataSet().setSelected(nnew);
068        if (Main.map.mapView.getRealBounds().contains(nnew.getCoor())) {
069            Main.map.mapView.repaint();
070        } else {
071            AutoScaleAction.zoomTo(Collections.<OsmPrimitive>singleton(nnew));
072        }
073    }
074
075    @Override
076    protected void updateEnabledState() {
077        setEnabled(getEditLayer() != null);
078    }
079}