source: josm/trunk/src/org/openstreetmap/josm/actions/MergeNodesAction.java@ 6069

Last change on this file since 6069 was 5989, checked in by Don-vip, 11 years ago

fix #8760 - When merging nodes, keep the oldest used one, not just only the oldest one.

  • Property svn:eol-style set to native
File size: 14.0 KB
Line 
1//License: GPL. Copyright 2007 by Immanuel Scholz and others. See LICENSE file for details.
2package org.openstreetmap.josm.actions;
3
4import static org.openstreetmap.josm.gui.help.HelpUtil.ht;
5import static org.openstreetmap.josm.tools.I18n.tr;
6
7import java.awt.event.ActionEvent;
8import java.awt.event.KeyEvent;
9import java.util.ArrayList;
10import java.util.Collection;
11import java.util.Collections;
12import java.util.HashSet;
13import java.util.LinkedList;
14import java.util.List;
15import java.util.Set;
16
17import javax.swing.JOptionPane;
18
19import org.openstreetmap.josm.Main;
20import org.openstreetmap.josm.command.ChangeCommand;
21import org.openstreetmap.josm.command.ChangeNodesCommand;
22import org.openstreetmap.josm.command.Command;
23import org.openstreetmap.josm.command.DeleteCommand;
24import org.openstreetmap.josm.command.SequenceCommand;
25import org.openstreetmap.josm.corrector.UserCancelException;
26import org.openstreetmap.josm.data.coor.EastNorth;
27import org.openstreetmap.josm.data.coor.LatLon;
28import org.openstreetmap.josm.data.osm.Node;
29import org.openstreetmap.josm.data.osm.OsmPrimitive;
30import org.openstreetmap.josm.data.osm.RelationToChildReference;
31import org.openstreetmap.josm.data.osm.TagCollection;
32import org.openstreetmap.josm.data.osm.Way;
33import org.openstreetmap.josm.gui.DefaultNameFormatter;
34import org.openstreetmap.josm.gui.HelpAwareOptionPane;
35import org.openstreetmap.josm.gui.HelpAwareOptionPane.ButtonSpec;
36import org.openstreetmap.josm.gui.conflict.tags.CombinePrimitiveResolverDialog;
37import org.openstreetmap.josm.gui.layer.OsmDataLayer;
38import org.openstreetmap.josm.tools.CheckParameterUtil;
39import org.openstreetmap.josm.tools.ImageProvider;
40import org.openstreetmap.josm.tools.Shortcut;
41
42/**
43 * Merges a collection of nodes into one node.
44 *
45 * The "surviving" node will be the one with the lowest positive id.
46 * (I.e. it was uploaded to the server and is the oldest one.)
47 *
48 * However we use the location of the node that was selected *last*.
49 * The "surviving" node will be moved to that location if it is
50 * different from the last selected node.
51 */
52public class MergeNodesAction extends JosmAction {
53
54 public MergeNodesAction() {
55 super(tr("Merge Nodes"), "mergenodes", tr("Merge nodes into the oldest one."),
56 Shortcut.registerShortcut("tools:mergenodes", tr("Tool: {0}", tr("Merge Nodes")), KeyEvent.VK_M, Shortcut.DIRECT), true);
57 putValue("help", ht("/Action/MergeNodes"));
58 }
59
60 public void actionPerformed(ActionEvent event) {
61 if (!isEnabled())
62 return;
63 Collection<OsmPrimitive> selection = getCurrentDataSet().getAllSelected();
64 List<Node> selectedNodes = OsmPrimitive.getFilteredList(selection, Node.class);
65
66 if (selectedNodes.size() == 1) {
67 List<Node> nearestNodes = Main.map.mapView.getNearestNodes(Main.map.mapView.getPoint(selectedNodes.get(0)), selectedNodes, OsmPrimitive.isUsablePredicate);
68 if (nearestNodes.isEmpty()) {
69 JOptionPane.showMessageDialog(
70 Main.parent,
71 tr("Please select at least two nodes to merge or a node that is close to another node."),
72 tr("Warning"),
73 JOptionPane.WARNING_MESSAGE
74 );
75
76 return;
77 }
78 selectedNodes.addAll(nearestNodes);
79 }
80
81 Node targetNode = selectTargetNode(selectedNodes);
82 Node targetLocationNode = selectTargetLocationNode(selectedNodes);
83 Command cmd = mergeNodes(Main.main.getEditLayer(), selectedNodes, targetNode, targetLocationNode);
84 if (cmd != null) {
85 Main.main.undoRedo.add(cmd);
86 Main.main.getEditLayer().data.setSelected(targetNode);
87 }
88 }
89
90 /**
91 * Select the location of the target node after merge.
92 *
93 * @param candidates the collection of candidate nodes
94 * @return the coordinates of this node are later used for the target node
95 */
96 public static Node selectTargetLocationNode(List<Node> candidates) {
97 int size = candidates.size();
98 if (size == 0)
99 throw new IllegalArgumentException("empty list");
100
101 switch (Main.pref.getInteger("merge-nodes.mode", 0)) {
102 case 0: {
103 Node targetNode = candidates.get(size - 1);
104 for (final Node n : candidates) { // pick last one
105 targetNode = n;
106 }
107 return targetNode;
108 }
109 case 1: {
110 double east = 0, north = 0;
111 for (final Node n : candidates) {
112 east += n.getEastNorth().east();
113 north += n.getEastNorth().north();
114 }
115
116 return new Node(new EastNorth(east / size, north / size));
117 }
118 case 2: {
119 final double[] weights = new double[size];
120
121 for (int i = 0; i < size; i++) {
122 final LatLon c1 = candidates.get(i).getCoor();
123 for (int j = i + 1; j < size; j++) {
124 final LatLon c2 = candidates.get(j).getCoor();
125 final double d = c1.distance(c2);
126 weights[i] += d;
127 weights[j] += d;
128 }
129 }
130
131 double east = 0, north = 0, weight = 0;
132 for (int i = 0; i < size; i++) {
133 final EastNorth en = candidates.get(i).getEastNorth();
134 final double w = weights[i];
135 east += en.east() * w;
136 north += en.north() * w;
137 weight += w;
138 }
139
140 return new Node(new EastNorth(east / weight, north / weight));
141 }
142 default:
143 throw new RuntimeException("unacceptable merge-nodes.mode");
144 }
145
146 }
147
148 /**
149 * Find which node to merge into (i.e. which one will be left)
150 *
151 * @param candidates the collection of candidate nodes
152 * @return the selected target node
153 */
154 public static Node selectTargetNode(Collection<Node> candidates) {
155 Node oldestNode = null;
156 Node targetNode = null;
157 Node lastNode = null;
158 for (Node n : candidates) {
159 if (!n.isNew()) {
160 // Among existing nodes, try to keep the oldest used one
161 if (!n.getReferrers().isEmpty()) {
162 if (targetNode == null) {
163 targetNode = n;
164 } else if (n.getId() < targetNode.getId()) {
165 targetNode = n;
166 }
167 } else if (oldestNode == null) {
168 oldestNode = n;
169 } else if (n.getId() < oldestNode.getId()) {
170 oldestNode = n;
171 }
172 }
173 lastNode = n;
174 }
175 if (targetNode == null) {
176 targetNode = (oldestNode != null ? oldestNode : lastNode);
177 }
178 return targetNode;
179 }
180
181
182 /**
183 * Fixes the parent ways referring to one of the nodes.
184 *
185 * Replies null, if the ways could not be fixed, i.e. because a way would have to be deleted
186 * which is referred to by a relation.
187 *
188 * @param nodesToDelete the collection of nodes to be deleted
189 * @param targetNode the target node the other nodes are merged to
190 * @return a list of commands; null, if the ways could not be fixed
191 */
192 protected static List<Command> fixParentWays(Collection<Node> nodesToDelete, Node targetNode) {
193 List<Command> cmds = new ArrayList<Command>();
194 Set<Way> waysToDelete = new HashSet<Way>();
195
196 for (Way w: OsmPrimitive.getFilteredList(OsmPrimitive.getReferrer(nodesToDelete), Way.class)) {
197 ArrayList<Node> newNodes = new ArrayList<Node>(w.getNodesCount());
198 for (Node n: w.getNodes()) {
199 if (! nodesToDelete.contains(n) && n != targetNode) {
200 newNodes.add(n);
201 } else if (newNodes.isEmpty()) {
202 newNodes.add(targetNode);
203 } else if (newNodes.get(newNodes.size()-1) != targetNode) {
204 // make sure we collapse a sequence of deleted nodes
205 // to exactly one occurrence of the merged target node
206 //
207 newNodes.add(targetNode);
208 } else {
209 // drop the node
210 }
211 }
212 if (newNodes.size() < 2) {
213 if (w.getReferrers().isEmpty()) {
214 waysToDelete.add(w);
215 } else {
216 ButtonSpec[] options = new ButtonSpec[] {
217 new ButtonSpec(
218 tr("Abort Merging"),
219 ImageProvider.get("cancel"),
220 tr("Click to abort merging nodes"),
221 null /* no special help topic */
222 )
223 };
224 HelpAwareOptionPane.showOptionDialog(
225 Main.parent,
226 tr("Cannot merge nodes: Would have to delete way {0} which is still used by {1}",
227 DefaultNameFormatter.getInstance().formatAsHtmlUnorderedList(w),
228 DefaultNameFormatter.getInstance().formatAsHtmlUnorderedList(w.getReferrers())),
229 tr("Warning"),
230 JOptionPane.WARNING_MESSAGE,
231 null, /* no icon */
232 options,
233 options[0],
234 ht("/Action/MergeNodes#WaysToDeleteStillInUse")
235 );
236 return null;
237 }
238 } else if(newNodes.size() < 2 && w.getReferrers().isEmpty()) {
239 waysToDelete.add(w);
240 } else {
241 cmds.add(new ChangeNodesCommand(w, newNodes));
242 }
243 }
244 if (!waysToDelete.isEmpty()) {
245 cmds.add(new DeleteCommand(waysToDelete));
246 }
247 return cmds;
248 }
249
250 public static void doMergeNodes(OsmDataLayer layer, Collection<Node> nodes, Node targetLocationNode) {
251 if (nodes == null) {
252 return;
253 }
254 Set<Node> allNodes = new HashSet<Node>(nodes);
255 allNodes.add(targetLocationNode);
256 Node target = selectTargetNode(allNodes);
257
258 Command cmd = mergeNodes(layer, nodes, target, targetLocationNode);
259 if (cmd != null) {
260 Main.main.undoRedo.add(cmd);
261 getCurrentDataSet().setSelected(target);
262 }
263 }
264
265 public static Command mergeNodes(OsmDataLayer layer, Collection<Node> nodes, Node targetLocationNode) {
266 if (nodes == null) {
267 return null;
268 }
269 Set<Node> allNodes = new HashSet<Node>(nodes);
270 allNodes.add(targetLocationNode);
271 return mergeNodes(layer, nodes, selectTargetNode(allNodes), targetLocationNode);
272 }
273
274 /**
275 * Merges the nodes in <code>nodes</code> onto one of the nodes. Uses the dataset
276 * managed by <code>layer</code> as reference.
277 *
278 * @param layer layer the reference data layer. Must not be null.
279 * @param nodes the collection of nodes. Ignored if null.
280 * @param targetNode the target node the collection of nodes is merged to. Must not be null.
281 * @param targetLocationNode this node's location will be used for the targetNode.
282 * @throws IllegalArgumentException thrown if layer is null
283 */
284 public static Command mergeNodes(OsmDataLayer layer, Collection<Node> nodes, Node targetNode, Node targetLocationNode) {
285 CheckParameterUtil.ensureParameterNotNull(layer, "layer");
286 CheckParameterUtil.ensureParameterNotNull(targetNode, "targetNode");
287 if (nodes == null) {
288 return null;
289 }
290
291 Set<RelationToChildReference> relationToNodeReferences = RelationToChildReference.getRelationToChildReferences(nodes);
292
293 try {
294 TagCollection nodeTags = TagCollection.unionOfAllPrimitives(nodes);
295 List<Command> resultion = CombinePrimitiveResolverDialog.launchIfNecessary(nodeTags, nodes, Collections.singleton(targetNode));
296 LinkedList<Command> cmds = new LinkedList<Command>();
297
298 // the nodes we will have to delete
299 //
300 Collection<Node> nodesToDelete = new HashSet<Node>(nodes);
301 nodesToDelete.remove(targetNode);
302
303 // fix the ways referring to at least one of the merged nodes
304 //
305 Collection<Way> waysToDelete = new HashSet<Way>();
306 List<Command> wayFixCommands = fixParentWays(
307 nodesToDelete,
308 targetNode);
309 if (wayFixCommands == null) {
310 return null;
311 }
312 cmds.addAll(wayFixCommands);
313
314 // build the commands
315 //
316 if (targetNode != targetLocationNode) {
317 Node newTargetNode = new Node(targetNode);
318 newTargetNode.setCoor(targetLocationNode.getCoor());
319 cmds.add(new ChangeCommand(targetNode, newTargetNode));
320 }
321 cmds.addAll(resultion);
322 if (!nodesToDelete.isEmpty()) {
323 cmds.add(new DeleteCommand(nodesToDelete));
324 }
325 if (!waysToDelete.isEmpty()) {
326 cmds.add(new DeleteCommand(waysToDelete));
327 }
328 Command cmd = new SequenceCommand(tr("Merge {0} nodes", nodes.size()), cmds);
329 return cmd;
330 } catch (UserCancelException ex) {
331 return null;
332 }
333 }
334
335 @Override
336 protected void updateEnabledState() {
337 if (getCurrentDataSet() == null) {
338 setEnabled(false);
339 } else {
340 updateEnabledState(getCurrentDataSet().getAllSelected());
341 }
342 }
343
344 @Override
345 protected void updateEnabledState(Collection<? extends OsmPrimitive> selection) {
346 if (selection == null || selection.isEmpty()) {
347 setEnabled(false);
348 return;
349 }
350 boolean ok = true;
351 for (OsmPrimitive osm : selection) {
352 if (!(osm instanceof Node)) {
353 ok = false;
354 break;
355 }
356 }
357 setEnabled(ok);
358 }
359}
Note: See TracBrowser for help on using the repository browser.