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.CheckParameterUtil.ensureParameterNotNull;
006import static org.openstreetmap.josm.tools.I18n.tr;
007
008import java.awt.event.ActionEvent;
009import java.awt.event.KeyEvent;
010import java.util.Collection;
011import java.util.Collections;
012
013import javax.swing.JOptionPane;
014
015import org.openstreetmap.josm.Main;
016import org.openstreetmap.josm.data.osm.DataSet;
017import org.openstreetmap.josm.data.osm.OsmPrimitive;
018import org.openstreetmap.josm.data.osm.OsmPrimitiveType;
019import org.openstreetmap.josm.data.osm.PrimitiveId;
020import org.openstreetmap.josm.gui.ExceptionDialogUtil;
021import org.openstreetmap.josm.gui.io.UpdatePrimitivesTask;
022import org.openstreetmap.josm.gui.progress.NullProgressMonitor;
023import org.openstreetmap.josm.io.MultiFetchServerObjectReader;
024import org.openstreetmap.josm.io.OnlineResource;
025import org.openstreetmap.josm.tools.Shortcut;
026
027/**
028 * This action synchronizes a set of primitives with their state on the server.
029 * @since 1670
030 */
031public class UpdateSelectionAction extends JosmAction {
032
033    /**
034     * handle an exception thrown because a primitive was deleted on the server
035     *
036     * @param id the primitive id
037     * @param type The primitive type. Must be one of {@link OsmPrimitiveType#NODE NODE},
038     * {@link OsmPrimitiveType#WAY WAY}, {@link OsmPrimitiveType#RELATION RELATION}
039     */
040    public static void handlePrimitiveGoneException(long id, OsmPrimitiveType type) {
041        MultiFetchServerObjectReader reader = MultiFetchServerObjectReader.create();
042        reader.append(getCurrentDataSet(), id, type);
043        try {
044            DataSet ds = reader.parseOsm(NullProgressMonitor.INSTANCE);
045            Main.main.getEditLayer().mergeFrom(ds);
046        } catch (Exception e) {
047            ExceptionDialogUtil.explainException(e);
048        }
049    }
050
051    /**
052     * Updates the data for for the {@link OsmPrimitive}s in <code>selection</code>
053     * with the data currently kept on the server.
054     *
055     * @param selection a collection of {@link OsmPrimitive}s to update
056     *
057     */
058    public static void updatePrimitives(final Collection<OsmPrimitive> selection) {
059        UpdatePrimitivesTask task = new UpdatePrimitivesTask(Main.main.getEditLayer(), selection);
060        Main.worker.submit(task);
061    }
062
063    /**
064     * Updates the data for  the {@link OsmPrimitive}s with id <code>id</code>
065     * with the data currently kept on the server.
066     *
067     * @param id  the id of a primitive in the {@link DataSet} of the current edit layer. Must not be null.
068     * @throws IllegalArgumentException if id is null
069     * @throws IllegalStateException if there is no primitive with <code>id</code> in the current dataset
070     * @throws IllegalStateException if there is no current dataset
071     */
072    public static void updatePrimitive(PrimitiveId id) {
073        ensureParameterNotNull(id, "id");
074        if (getEditLayer() == null)
075            throw new IllegalStateException(tr("No current dataset found"));
076        OsmPrimitive primitive = getEditLayer().data.getPrimitiveById(id);
077        if (primitive == null)
078            throw new IllegalStateException(tr("Did not find an object with id {0} in the current dataset", id));
079        updatePrimitives(Collections.singleton(primitive));
080    }
081
082    /**
083     * Constructs a new {@code UpdateSelectionAction}.
084     */
085    public UpdateSelectionAction() {
086        super(tr("Update selection"), "updatedata",
087                tr("Updates the currently selected objects from the server (re-downloads data)"),
088                Shortcut.registerShortcut("file:updateselection",
089                        tr("File: {0}", tr("Update selection")), KeyEvent.VK_U,
090                        Shortcut.ALT_CTRL),
091                true, "updateselection", true);
092        putValue("help", ht("/Action/UpdateSelection"));
093    }
094
095    /**
096     * Constructs a new {@code UpdateSelectionAction}.
097     *
098     * @param name the action's text as displayed on the menu (if it is added to a menu)
099     * @param iconName the filename of the icon to use
100     * @param tooltip  a longer description of the action that will be displayed in the tooltip. Please note
101     *           that html is not supported for menu actions on some platforms.
102     * @param shortcut a ready-created shortcut object or null if you don't want a shortcut. But you always
103     *            do want a shortcut, remember you can always register it with group=none, so you
104     *            won't be assigned a shortcut unless the user configures one. If you pass null here,
105     *            the user CANNOT configure a shortcut for your action.
106     * @param register register this action for the toolbar preferences?
107     * @param toolbarId identifier for the toolbar preferences. The iconName is used, if this parameter is null
108     */
109    public UpdateSelectionAction(String name, String iconName, String tooltip, Shortcut shortcut, boolean register, String toolbarId) {
110        super(name, iconName, tooltip, shortcut, register, toolbarId, true);
111    }
112
113    @Override
114    protected void updateEnabledState() {
115        if (getCurrentDataSet() == null) {
116            setEnabled(false);
117        } else {
118            updateEnabledState(getCurrentDataSet().getAllSelected());
119        }
120    }
121
122    @Override
123    protected void updateEnabledState(Collection<? extends OsmPrimitive> selection) {
124        setEnabled(selection != null && !selection.isEmpty() && !Main.isOffline(OnlineResource.OSM_API));
125    }
126
127    @Override
128    public void actionPerformed(ActionEvent e) {
129        if (!isEnabled())
130            return;
131        Collection<OsmPrimitive> toUpdate = getData();
132        if (toUpdate.isEmpty()) {
133            JOptionPane.showMessageDialog(
134                    Main.parent,
135                    tr("There are no selected objects to update."),
136                    tr("Selection empty"),
137                    JOptionPane.INFORMATION_MESSAGE
138            );
139            return;
140        }
141        updatePrimitives(toUpdate);
142    }
143
144    /**
145     * Returns the data on which this action operates. Override if needed.
146     * @return the data on which this action operates
147     */
148    public Collection<OsmPrimitive> getData() {
149        return getCurrentDataSet().getAllSelected();
150    }
151}