source: josm/trunk/src/org/openstreetmap/josm/command/Command.java @ 12636

Last change on this file since 12636 was 12636, checked in by Don-vip, 3 months ago

see #15182 - deprecate Main.getLayerManager(). Replacement: gui.MainApplication.getLayerManager()

  • Property svn:eol-style set to native
File size: 13.0 KB
Line 
1// License: GPL. For details, see LICENSE file.
2package org.openstreetmap.josm.command;
3
4import java.awt.GridBagLayout;
5import java.util.ArrayList;
6import java.util.Collection;
7import java.util.HashMap;
8import java.util.LinkedHashMap;
9import java.util.Map;
10import java.util.Map.Entry;
11import java.util.Objects;
12
13import javax.swing.JOptionPane;
14import javax.swing.JPanel;
15
16import org.openstreetmap.josm.Main;
17import org.openstreetmap.josm.data.coor.EastNorth;
18import org.openstreetmap.josm.data.coor.LatLon;
19import org.openstreetmap.josm.data.osm.DataSet;
20import org.openstreetmap.josm.data.osm.Node;
21import org.openstreetmap.josm.data.osm.OsmPrimitive;
22import org.openstreetmap.josm.data.osm.PrimitiveData;
23import org.openstreetmap.josm.data.osm.Relation;
24import org.openstreetmap.josm.data.osm.Way;
25import org.openstreetmap.josm.data.osm.visitor.AbstractVisitor;
26import org.openstreetmap.josm.gui.ConditionalOptionPaneUtil;
27import org.openstreetmap.josm.gui.MainApplication;
28import org.openstreetmap.josm.gui.layer.Layer;
29import org.openstreetmap.josm.gui.layer.OsmDataLayer;
30import org.openstreetmap.josm.gui.widgets.JMultilineLabel;
31import org.openstreetmap.josm.tools.CheckParameterUtil;
32
33/**
34 * Classes implementing Command modify a dataset in a specific way. A command is
35 * one atomic action on a specific dataset, such as move or delete.
36 *
37 * The command remembers the {@link OsmDataLayer} it is operating on.
38 *
39 * @author imi
40 * @since 21 (creation)
41 * @since 10599 (signature)
42 */
43public abstract class Command implements PseudoCommand {
44
45    /** IS_OK : operation is okay */
46    public static final int IS_OK = 0;
47    /** IS_OUTSIDE : operation on element outside of download area */
48    public static final int IS_OUTSIDE = 1;
49    /** IS_INCOMPLETE: operation on incomplete target */
50    public static final int IS_INCOMPLETE = 2;
51
52    private static final class CloneVisitor extends AbstractVisitor {
53        public final Map<OsmPrimitive, PrimitiveData> orig = new LinkedHashMap<>();
54
55        @Override
56        public void visit(Node n) {
57            orig.put(n, n.save());
58        }
59
60        @Override
61        public void visit(Way w) {
62            orig.put(w, w.save());
63        }
64
65        @Override
66        public void visit(Relation e) {
67            orig.put(e, e.save());
68        }
69    }
70
71    /**
72     * Small helper for holding the interesting part of the old data state of the objects.
73     */
74    public static class OldNodeState {
75
76        private final LatLon latLon;
77        private final EastNorth eastNorth; // cached EastNorth to be used for applying exact displacement
78        private final boolean modified;
79
80        /**
81         * Constructs a new {@code OldNodeState} for the given node.
82         * @param node The node whose state has to be remembered
83         */
84        public OldNodeState(Node node) {
85            latLon = node.getCoor();
86            eastNorth = node.getEastNorth();
87            modified = node.isModified();
88        }
89
90        /**
91         * Returns old lat/lon.
92         * @return old lat/lon
93         * @see Node#getCoor()
94         * @since 10248
95         */
96        public final LatLon getLatLon() {
97            return latLon;
98        }
99
100        /**
101         * Returns old east/north.
102         * @return old east/north
103         * @see Node#getEastNorth()
104         */
105        public final EastNorth getEastNorth() {
106            return eastNorth;
107        }
108
109        /**
110         * Returns old modified state.
111         * @return old modified state
112         * @see Node #isModified()
113         */
114        public final boolean isModified() {
115            return modified;
116        }
117
118        @Override
119        public int hashCode() {
120            return Objects.hash(latLon, eastNorth, modified);
121        }
122
123        @Override
124        public boolean equals(Object obj) {
125            if (this == obj) return true;
126            if (obj == null || getClass() != obj.getClass()) return false;
127            OldNodeState that = (OldNodeState) obj;
128            return modified == that.modified &&
129                    Objects.equals(latLon, that.latLon) &&
130                    Objects.equals(eastNorth, that.eastNorth);
131        }
132    }
133
134    /** the map of OsmPrimitives in the original state to OsmPrimitives in cloned state */
135    private Map<OsmPrimitive, PrimitiveData> cloneMap = new HashMap<>();
136
137    /** the layer which this command is applied to */
138    private final OsmDataLayer layer;
139
140    /** the dataset which this command is applied to */
141    private final DataSet data;
142
143    /**
144     * Creates a new command in the context of the current edit layer, if any
145     */
146    public Command() {
147        this.layer = MainApplication.getLayerManager().getEditLayer();
148        this.data = layer != null ? layer.data : null;
149    }
150
151    /**
152     * Creates a new command in the context of a specific data layer
153     *
154     * @param layer the data layer. Must not be null.
155     * @throws IllegalArgumentException if layer is null
156     */
157    public Command(OsmDataLayer layer) {
158        CheckParameterUtil.ensureParameterNotNull(layer, "layer");
159        this.layer = layer;
160        this.data = layer.data;
161    }
162
163    /**
164     * Creates a new command in the context of a specific data set, without data layer
165     *
166     * @param data the data set. Must not be null.
167     * @throws IllegalArgumentException if data is null
168     * @since 11240
169     */
170    public Command(DataSet data) {
171        CheckParameterUtil.ensureParameterNotNull(data, "data");
172        this.layer = null;
173        this.data = data;
174    }
175
176    /**
177     * Executes the command on the dataset. This implementation will remember all
178     * primitives returned by fillModifiedData for restoring them on undo.
179     * <p>
180     * The layer should be invalidated after execution so that it can be re-painted.
181     * @return true
182     * @see #invalidateAffectedLayers()
183     */
184    public boolean executeCommand() {
185        CloneVisitor visitor = new CloneVisitor();
186        Collection<OsmPrimitive> all = new ArrayList<>();
187        fillModifiedData(all, all, all);
188        for (OsmPrimitive osm : all) {
189            osm.accept(visitor);
190        }
191        cloneMap = visitor.orig;
192        return true;
193    }
194
195    /**
196     * Undoes the command.
197     * It can be assumed that all objects are in the same state they were before.
198     * It can also be assumed that executeCommand was called exactly once before.
199     *
200     * This implementation undoes all objects stored by a former call to executeCommand.
201     */
202    public void undoCommand() {
203        for (Entry<OsmPrimitive, PrimitiveData> e : cloneMap.entrySet()) {
204            OsmPrimitive primitive = e.getKey();
205            if (primitive.getDataSet() != null) {
206                e.getKey().load(e.getValue());
207            }
208        }
209    }
210
211    /**
212     * Called when a layer has been removed to have the command remove itself from
213     * any buffer if it is not longer applicable to the dataset (e.g. it was part of
214     * the removed layer)
215     *
216     * @param oldLayer the old layer that was removed
217     * @return true if this command is invalid after that layer is removed.
218     */
219    public boolean invalidBecauselayerRemoved(Layer oldLayer) {
220        return layer == oldLayer;
221    }
222
223    /**
224     * Lets other commands access the original version
225     * of the object. Usually for undoing.
226     * @param osm The requested OSM object
227     * @return The original version of the requested object, if any
228     */
229    public PrimitiveData getOrig(OsmPrimitive osm) {
230        return cloneMap.get(osm);
231    }
232
233    /**
234     * Replies the layer this command is (or was) applied to.
235     * @return the layer this command is (or was) applied to
236     */
237    protected OsmDataLayer getLayer() {
238        return layer;
239    }
240
241    /**
242     * Gets the data set this command affects.
243     * @return The data set. May be <code>null</code> if no layer was set and no edit layer was found.
244     * @since 10467
245     */
246    public DataSet getAffectedDataSet() {
247        return data;
248    }
249
250    /**
251     * Fill in the changed data this command operates on.
252     * Add to the lists, don't clear them.
253     *
254     * @param modified The modified primitives
255     * @param deleted The deleted primitives
256     * @param added The added primitives
257     */
258    public abstract void fillModifiedData(Collection<OsmPrimitive> modified,
259            Collection<OsmPrimitive> deleted,
260            Collection<OsmPrimitive> added);
261
262    /**
263     * Return the primitives that take part in this command.
264     * The collection is computed during execution.
265     */
266    @Override
267    public Collection<? extends OsmPrimitive> getParticipatingPrimitives() {
268        return cloneMap.keySet();
269    }
270
271    /**
272     * Check whether user is about to operate on data outside of the download area.
273     *
274     * @param primitives the primitives to operate on
275     * @param ignore {@code null} or a primitive to be ignored
276     * @return true, if operating on outlying primitives is OK; false, otherwise
277     */
278    public static int checkOutlyingOrIncompleteOperation(
279            Collection<? extends OsmPrimitive> primitives,
280            Collection<? extends OsmPrimitive> ignore) {
281        int res = 0;
282        for (OsmPrimitive osm : primitives) {
283            if (osm.isIncomplete()) {
284                res |= IS_INCOMPLETE;
285            } else if (osm.isOutsideDownloadArea()
286                    && (ignore == null || !ignore.contains(osm))) {
287                res |= IS_OUTSIDE;
288            }
289        }
290        return res;
291    }
292
293    /**
294     * Check whether user is about to operate on data outside of the download area.
295     * Request confirmation if he is.
296     *
297     * @param operation the operation name which is used for setting some preferences
298     * @param dialogTitle the title of the dialog being displayed
299     * @param outsideDialogMessage the message text to be displayed when data is outside of the download area
300     * @param incompleteDialogMessage the message text to be displayed when data is incomplete
301     * @param primitives the primitives to operate on
302     * @param ignore {@code null} or a primitive to be ignored
303     * @return true, if operating on outlying primitives is OK; false, otherwise
304     */
305    public static boolean checkAndConfirmOutlyingOperation(String operation,
306            String dialogTitle, String outsideDialogMessage, String incompleteDialogMessage,
307            Collection<? extends OsmPrimitive> primitives,
308            Collection<? extends OsmPrimitive> ignore) {
309        int checkRes = checkOutlyingOrIncompleteOperation(primitives, ignore);
310        if ((checkRes & IS_OUTSIDE) != 0) {
311            JPanel msg = new JPanel(new GridBagLayout());
312            msg.add(new JMultilineLabel("<html>" + outsideDialogMessage + "</html>"));
313            boolean answer = ConditionalOptionPaneUtil.showConfirmationDialog(
314                    operation + "_outside_nodes",
315                    Main.parent,
316                    msg,
317                    dialogTitle,
318                    JOptionPane.YES_NO_OPTION,
319                    JOptionPane.QUESTION_MESSAGE,
320                    JOptionPane.YES_OPTION);
321            if (!answer)
322                return false;
323        }
324        if ((checkRes & IS_INCOMPLETE) != 0) {
325            JPanel msg = new JPanel(new GridBagLayout());
326            msg.add(new JMultilineLabel("<html>" + incompleteDialogMessage + "</html>"));
327            boolean answer = ConditionalOptionPaneUtil.showConfirmationDialog(
328                    operation + "_incomplete",
329                    Main.parent,
330                    msg,
331                    dialogTitle,
332                    JOptionPane.YES_NO_OPTION,
333                    JOptionPane.QUESTION_MESSAGE,
334                    JOptionPane.YES_OPTION);
335            if (!answer)
336                return false;
337        }
338        return true;
339    }
340
341    /**
342     * Ensures that all primitives that are participating in this command belong to the affected data set.
343     *
344     * Commands may use this in their update methods to check the consitency of the primitives they operate on.
345     * @throws AssertionError if no {@link DataSet} is set or if any primitive does not belong to that dataset.
346     */
347    protected void ensurePrimitivesAreInDataset() {
348        for (OsmPrimitive primitive : this.getParticipatingPrimitives()) {
349            if (primitive.getDataSet() != this.getAffectedDataSet()) {
350                throw new AssertionError("Primitive is of wrong data set for this command: " + primitive);
351            }
352        }
353    }
354
355    @Override
356    public int hashCode() {
357        return Objects.hash(cloneMap, layer, data);
358    }
359
360    @Override
361    public boolean equals(Object obj) {
362        if (this == obj) return true;
363        if (obj == null || getClass() != obj.getClass()) return false;
364        Command command = (Command) obj;
365        return Objects.equals(cloneMap, command.cloneMap) &&
366               Objects.equals(layer, command.layer) &&
367               Objects.equals(data, command.data);
368    }
369
370    /**
371     * Invalidate all layers that were affected by this command.
372     * @see Layer#invalidate()
373     */
374    public void invalidateAffectedLayers() {
375        OsmDataLayer layer = getLayer();
376        if (layer != null) {
377            layer.invalidate();
378        }
379    }
380}
Note: See TracBrowser for help on using the repository browser.