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

Last change on this file since 6111 was 6084, checked in by bastiK, 11 years ago

see #8902 - add missing @Override annotations (patch by shinigami)

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