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

Last change on this file since 8447 was 8443, checked in by Don-vip, 9 years ago

remove extra whitespaces

  • Property svn:eol-style set to native
File size: 15.4 KB
Line 
1// License: GPL. For details, see LICENSE file.
2package org.openstreetmap.josm.actions;
3
4import static org.openstreetmap.josm.gui.help.HelpUtil.ht;
5import static org.openstreetmap.josm.tools.I18n.tr;
6import static org.openstreetmap.josm.tools.I18n.trn;
7
8import java.awt.event.ActionEvent;
9import java.awt.event.KeyEvent;
10import java.util.ArrayList;
11import java.util.Collection;
12import java.util.Collections;
13import java.util.HashSet;
14import java.util.LinkedList;
15import java.util.List;
16import java.util.Set;
17
18import javax.swing.JOptionPane;
19
20import org.openstreetmap.josm.Main;
21import org.openstreetmap.josm.command.ChangeCommand;
22import org.openstreetmap.josm.command.ChangeNodesCommand;
23import org.openstreetmap.josm.command.Command;
24import org.openstreetmap.josm.command.DeleteCommand;
25import org.openstreetmap.josm.command.SequenceCommand;
26import org.openstreetmap.josm.corrector.UserCancelException;
27import org.openstreetmap.josm.data.coor.EastNorth;
28import org.openstreetmap.josm.data.coor.LatLon;
29import org.openstreetmap.josm.data.osm.Node;
30import org.openstreetmap.josm.data.osm.OsmPrimitive;
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.Notification;
37import org.openstreetmap.josm.gui.conflict.tags.CombinePrimitiveResolverDialog;
38import org.openstreetmap.josm.gui.layer.OsmDataLayer;
39import org.openstreetmap.josm.tools.CheckParameterUtil;
40import org.openstreetmap.josm.tools.ImageProvider;
41import org.openstreetmap.josm.tools.Shortcut;
42
43/**
44 * Merges a collection of nodes into one node.
45 *
46 * The "surviving" node will be the one with the lowest positive id.
47 * (I.e. it was uploaded to the server and is the oldest one.)
48 *
49 * However we use the location of the node that was selected *last*.
50 * The "surviving" node will be moved to that location if it is
51 * different from the last selected node.
52 *
53 * @since 422
54 */
55public class MergeNodesAction extends JosmAction {
56
57 /**
58 * Constructs a new {@code MergeNodesAction}.
59 */
60 public MergeNodesAction() {
61 super(tr("Merge Nodes"), "mergenodes", tr("Merge nodes into the oldest one."),
62 Shortcut.registerShortcut("tools:mergenodes", tr("Tool: {0}", tr("Merge Nodes")), KeyEvent.VK_M, Shortcut.DIRECT), true);
63 putValue("help", ht("/Action/MergeNodes"));
64 }
65
66 @Override
67 public void actionPerformed(ActionEvent event) {
68 if (!isEnabled())
69 return;
70 Collection<OsmPrimitive> selection = getCurrentDataSet().getAllSelected();
71 List<Node> selectedNodes = OsmPrimitive.getFilteredList(selection, Node.class);
72
73 if (selectedNodes.size() == 1) {
74 List<Node> nearestNodes = Main.map.mapView.getNearestNodes(
75 Main.map.mapView.getPoint(selectedNodes.get(0)), selectedNodes, OsmPrimitive.isUsablePredicate);
76 if (nearestNodes.isEmpty()) {
77 new Notification(
78 tr("Please select at least two nodes to merge or one node that is close to another node."))
79 .setIcon(JOptionPane.WARNING_MESSAGE)
80 .show();
81 return;
82 }
83 selectedNodes.addAll(nearestNodes);
84 }
85
86 Node targetNode = selectTargetNode(selectedNodes);
87 Node targetLocationNode = selectTargetLocationNode(selectedNodes);
88 Command cmd = mergeNodes(Main.main.getEditLayer(), selectedNodes, targetNode, targetLocationNode);
89 if (cmd != null) {
90 Main.main.undoRedo.add(cmd);
91 Main.main.getEditLayer().data.setSelected(targetNode);
92 }
93 }
94
95 /**
96 * Select the location of the target node after merge.
97 *
98 * @param candidates the collection of candidate nodes
99 * @return the coordinates of this node are later used for the target node
100 */
101 public static Node selectTargetLocationNode(List<Node> candidates) {
102 int size = candidates.size();
103 if (size == 0)
104 throw new IllegalArgumentException("empty list");
105
106 switch (Main.pref.getInteger("merge-nodes.mode", 0)) {
107 case 0:
108 Node targetNode = candidates.get(size - 1);
109 for (final Node n : candidates) { // pick last one
110 targetNode = n;
111 }
112 return targetNode;
113 case 1:
114 double east1 = 0, north1 = 0;
115 for (final Node n : candidates) {
116 east1 += n.getEastNorth().east();
117 north1 += n.getEastNorth().north();
118 }
119
120 return new Node(new EastNorth(east1 / size, north1 / size));
121 case 2:
122 final double[] weights = new double[size];
123
124 for (int i = 0; i < size; i++) {
125 final LatLon c1 = candidates.get(i).getCoor();
126 for (int j = i + 1; j < size; j++) {
127 final LatLon c2 = candidates.get(j).getCoor();
128 final double d = c1.distance(c2);
129 weights[i] += d;
130 weights[j] += d;
131 }
132 }
133
134 double east2 = 0, north2 = 0, weight = 0;
135 for (int i = 0; i < size; i++) {
136 final EastNorth en = candidates.get(i).getEastNorth();
137 final double w = weights[i];
138 east2 += en.east() * w;
139 north2 += en.north() * w;
140 weight += w;
141 }
142
143 return new Node(new EastNorth(east2 / weight, north2 / weight));
144 default:
145 throw new IllegalStateException("unacceptable merge-nodes.mode");
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<>();
195 Set<Way> waysToDelete = new HashSet<>();
196
197 for (Way w: OsmPrimitive.getFilteredList(OsmPrimitive.getReferrer(nodesToDelete), Way.class)) {
198 List<Node> newNodes = new ArrayList<>(w.getNodesCount());
199 for (Node n: w.getNodes()) {
200 if (!nodesToDelete.contains(n) && !n.equals(targetNode)) {
201 newNodes.add(n);
202 } else if (newNodes.isEmpty()) {
203 newNodes.add(targetNode);
204 } else if (!newNodes.get(newNodes.size()-1).equals(targetNode)) {
205 // make sure we collapse a sequence of deleted nodes
206 // to exactly one occurrence of the merged target node
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 /**
251 * Merges the nodes in {@code nodes} at the specified node's location. Uses the dataset
252 * managed by {@code layer} as reference.
253 * @param layer layer the reference data layer. Must not be null
254 * @param nodes the collection of nodes. Ignored if null
255 * @param targetLocationNode this node's location will be used for the target node
256 * @throws IllegalArgumentException if {@code layer} is null
257 */
258 public static void doMergeNodes(OsmDataLayer layer, Collection<Node> nodes, Node targetLocationNode) {
259 if (nodes == null) {
260 return;
261 }
262 Set<Node> allNodes = new HashSet<>(nodes);
263 allNodes.add(targetLocationNode);
264 Node target;
265 if (nodes.contains(targetLocationNode) && !targetLocationNode.isNew()) {
266 target = targetLocationNode; // keep existing targetLocationNode as target to avoid unnecessary changes (see #2447)
267 } else {
268 target = selectTargetNode(allNodes);
269 }
270
271 Command cmd = mergeNodes(layer, nodes, target, targetLocationNode);
272 if (cmd != null) {
273 Main.main.undoRedo.add(cmd);
274 getCurrentDataSet().setSelected(target);
275 }
276 }
277
278 /**
279 * Merges the nodes in {@code nodes} at the specified node's location. Uses the dataset
280 * managed by {@code layer} as reference.
281 *
282 * @param layer layer the reference data layer. Must not be null.
283 * @param nodes the collection of nodes. Ignored if null.
284 * @param targetLocationNode this node's location will be used for the targetNode.
285 * @return The command necessary to run in order to perform action, or {@code null} if there is nothing to do
286 * @throws IllegalArgumentException if {@code layer} is null
287 */
288 public static Command mergeNodes(OsmDataLayer layer, Collection<Node> nodes, Node targetLocationNode) {
289 if (nodes == null) {
290 return null;
291 }
292 Set<Node> allNodes = new HashSet<>(nodes);
293 allNodes.add(targetLocationNode);
294 return mergeNodes(layer, nodes, selectTargetNode(allNodes), targetLocationNode);
295 }
296
297 /**
298 * Merges the nodes in <code>nodes</code> onto one of the nodes. Uses the dataset
299 * managed by <code>layer</code> as reference.
300 *
301 * @param layer layer the reference data layer. Must not be null.
302 * @param nodes the collection of nodes. Ignored if null.
303 * @param targetNode the target node the collection of nodes is merged to. Must not be null.
304 * @param targetLocationNode this node's location will be used for the targetNode.
305 * @return The command necessary to run in order to perform action, or {@code null} if there is nothing to do
306 * @throws IllegalArgumentException if layer is null
307 */
308 public static Command mergeNodes(OsmDataLayer layer, Collection<Node> nodes, Node targetNode, Node targetLocationNode) {
309 CheckParameterUtil.ensureParameterNotNull(layer, "layer");
310 CheckParameterUtil.ensureParameterNotNull(targetNode, "targetNode");
311 if (nodes == null) {
312 return null;
313 }
314
315 try {
316 TagCollection nodeTags = TagCollection.unionOfAllPrimitives(nodes);
317 List<Command> resultion = CombinePrimitiveResolverDialog.launchIfNecessary(nodeTags, nodes, Collections.singleton(targetNode));
318 List<Command> cmds = new LinkedList<>();
319
320 // the nodes we will have to delete
321 //
322 Collection<Node> nodesToDelete = new HashSet<>(nodes);
323 nodesToDelete.remove(targetNode);
324
325 // fix the ways referring to at least one of the merged nodes
326 //
327 Collection<Way> waysToDelete = new HashSet<>();
328 List<Command> wayFixCommands = fixParentWays(
329 nodesToDelete,
330 targetNode);
331 if (wayFixCommands == null) {
332 return null;
333 }
334 cmds.addAll(wayFixCommands);
335
336 // build the commands
337 //
338 if (!targetNode.equals(targetLocationNode)) {
339 LatLon targetLocationCoor = targetLocationNode.getCoor();
340 if (!targetNode.getCoor().equals(targetLocationCoor)) {
341 Node newTargetNode = new Node(targetNode);
342 newTargetNode.setCoor(targetLocationCoor);
343 cmds.add(new ChangeCommand(targetNode, newTargetNode));
344 }
345 }
346 cmds.addAll(resultion);
347 if (!nodesToDelete.isEmpty()) {
348 cmds.add(new DeleteCommand(nodesToDelete));
349 }
350 if (!waysToDelete.isEmpty()) {
351 cmds.add(new DeleteCommand(waysToDelete));
352 }
353 return new SequenceCommand(/* for correct i18n of plural forms - see #9110 */
354 trn("Merge {0} node", "Merge {0} nodes", nodes.size(), nodes.size()), cmds);
355 } catch (UserCancelException ex) {
356 return null;
357 }
358 }
359
360 @Override
361 protected void updateEnabledState() {
362 if (getCurrentDataSet() == null) {
363 setEnabled(false);
364 } else {
365 updateEnabledState(getCurrentDataSet().getAllSelected());
366 }
367 }
368
369 @Override
370 protected void updateEnabledState(Collection<? extends OsmPrimitive> selection) {
371 if (selection == null || selection.isEmpty()) {
372 setEnabled(false);
373 return;
374 }
375 boolean ok = true;
376 for (OsmPrimitive osm : selection) {
377 if (!(osm instanceof Node)) {
378 ok = false;
379 break;
380 }
381 }
382 setEnabled(ok);
383 }
384}
Note: See TracBrowser for help on using the repository browser.