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

Last change on this file since 11297 was 11109, checked in by Don-vip, 8 years ago

sonar - squid:S1871 - Two branches in the same conditional structure should not have exactly the same implementation

  • Property svn:eol-style set to native
File size: 14.8 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.Objects;
17import java.util.Set;
18
19import javax.swing.JOptionPane;
20
21import org.openstreetmap.josm.Main;
22import org.openstreetmap.josm.command.ChangeCommand;
23import org.openstreetmap.josm.command.ChangeNodesCommand;
24import org.openstreetmap.josm.command.Command;
25import org.openstreetmap.josm.command.DeleteCommand;
26import org.openstreetmap.josm.command.SequenceCommand;
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;
42import org.openstreetmap.josm.tools.UserCancelException;
43
44/**
45 * Merges a collection of nodes into one node.
46 *
47 * The "surviving" node will be the one with the lowest positive id.
48 * (I.e. it was uploaded to the server and is the oldest one.)
49 *
50 * However we use the location of the node that was selected *last*.
51 * The "surviving" node will be moved to that location if it is
52 * different from the last selected node.
53 *
54 * @since 422
55 */
56public class MergeNodesAction extends JosmAction {
57
58 /**
59 * Constructs a new {@code MergeNodesAction}.
60 */
61 public MergeNodesAction() {
62 super(tr("Merge Nodes"), "mergenodes", tr("Merge nodes into the oldest one."),
63 Shortcut.registerShortcut("tools:mergenodes", tr("Tool: {0}", tr("Merge Nodes")), KeyEvent.VK_M, Shortcut.DIRECT), true);
64 putValue("help", ht("/Action/MergeNodes"));
65 }
66
67 @Override
68 public void actionPerformed(ActionEvent event) {
69 if (!isEnabled())
70 return;
71 Collection<OsmPrimitive> selection = getLayerManager().getEditDataSet().getAllSelected();
72 List<Node> selectedNodes = OsmPrimitive.getFilteredList(selection, Node.class);
73
74 if (selectedNodes.size() == 1) {
75 List<Node> nearestNodes = Main.map.mapView.getNearestNodes(
76 Main.map.mapView.getPoint(selectedNodes.get(0)), selectedNodes, OsmPrimitive::isUsable);
77 if (nearestNodes.isEmpty()) {
78 new Notification(
79 tr("Please select at least two nodes to merge or one node that is close to another node."))
80 .setIcon(JOptionPane.WARNING_MESSAGE)
81 .show();
82 return;
83 }
84 selectedNodes.addAll(nearestNodes);
85 }
86
87 Node targetNode = selectTargetNode(selectedNodes);
88 Node targetLocationNode = selectTargetLocationNode(selectedNodes);
89 Command cmd = mergeNodes(Main.getLayerManager().getEditLayer(), selectedNodes, targetNode, targetLocationNode);
90 if (cmd != null) {
91 Main.main.undoRedo.add(cmd);
92 Main.getLayerManager().getEditLayer().data.setSelected(targetNode);
93 }
94 }
95
96 /**
97 * Select the location of the target node after merge.
98 *
99 * @param candidates the collection of candidate nodes
100 * @return the coordinates of this node are later used for the target node
101 */
102 public static Node selectTargetLocationNode(List<Node> candidates) {
103 int size = candidates.size();
104 if (size == 0)
105 throw new IllegalArgumentException("empty list");
106 if (size == 1) // to avoid division by 0 in mode 2
107 return candidates.get(0);
108
109 switch (Main.pref.getInteger("merge-nodes.mode", 0)) {
110 case 0:
111 return candidates.get(size - 1);
112 case 1:
113 double east1 = 0, north1 = 0;
114 for (final Node n : candidates) {
115 EastNorth en = n.getEastNorth();
116 east1 += en.east();
117 north1 += en.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 || n.getId() < targetNode.getId()) {
164 targetNode = n;
165 }
166 } else if (oldestNode == null || n.getId() < oldestNode.getId()) {
167 oldestNode = n;
168 }
169 }
170 lastNode = n;
171 }
172 if (targetNode == null) {
173 targetNode = oldestNode != null ? oldestNode : lastNode;
174 }
175 return targetNode;
176 }
177
178
179 /**
180 * Fixes the parent ways referring to one of the nodes.
181 *
182 * Replies null, if the ways could not be fixed, i.e. because a way would have to be deleted
183 * which is referred to by a relation.
184 *
185 * @param nodesToDelete the collection of nodes to be deleted
186 * @param targetNode the target node the other nodes are merged to
187 * @return a list of commands; null, if the ways could not be fixed
188 */
189 protected static List<Command> fixParentWays(Collection<Node> nodesToDelete, Node targetNode) {
190 List<Command> cmds = new ArrayList<>();
191 Set<Way> waysToDelete = new HashSet<>();
192
193 for (Way w: OsmPrimitive.getFilteredList(OsmPrimitive.getReferrer(nodesToDelete), Way.class)) {
194 List<Node> newNodes = new ArrayList<>(w.getNodesCount());
195 for (Node n: w.getNodes()) {
196 if (!nodesToDelete.contains(n) && !n.equals(targetNode)) {
197 newNodes.add(n);
198 } else if (newNodes.isEmpty() || !newNodes.get(newNodes.size()-1).equals(targetNode)) {
199 // make sure we collapse a sequence of deleted nodes
200 // to exactly one occurrence of the merged target node
201 newNodes.add(targetNode);
202 }
203 // else: drop the node
204 }
205 if (newNodes.size() < 2) {
206 if (w.getReferrers().isEmpty()) {
207 waysToDelete.add(w);
208 } else {
209 ButtonSpec[] options = new ButtonSpec[] {
210 new ButtonSpec(
211 tr("Abort Merging"),
212 ImageProvider.get("cancel"),
213 tr("Click to abort merging nodes"),
214 null /* no special help topic */
215 )
216 };
217 HelpAwareOptionPane.showOptionDialog(
218 Main.parent,
219 tr("Cannot merge nodes: Would have to delete way {0} which is still used by {1}",
220 DefaultNameFormatter.getInstance().formatAsHtmlUnorderedList(w),
221 DefaultNameFormatter.getInstance().formatAsHtmlUnorderedList(w.getReferrers(), 20)),
222 tr("Warning"),
223 JOptionPane.WARNING_MESSAGE,
224 null, /* no icon */
225 options,
226 options[0],
227 ht("/Action/MergeNodes#WaysToDeleteStillInUse")
228 );
229 return null;
230 }
231 } else if (newNodes.size() < 2 && w.getReferrers().isEmpty()) {
232 waysToDelete.add(w);
233 } else {
234 cmds.add(new ChangeNodesCommand(w, newNodes));
235 }
236 }
237 if (!waysToDelete.isEmpty()) {
238 cmds.add(new DeleteCommand(waysToDelete));
239 }
240 return cmds;
241 }
242
243 /**
244 * Merges the nodes in {@code nodes} at the specified node's location. Uses the dataset
245 * managed by {@code layer} as reference.
246 * @param layer layer the reference data layer. Must not be null
247 * @param nodes the collection of nodes. Ignored if null
248 * @param targetLocationNode this node's location will be used for the target node
249 * @throws IllegalArgumentException if {@code layer} is null
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<>(nodes);
256 allNodes.add(targetLocationNode);
257 Node target;
258 if (nodes.contains(targetLocationNode) && !targetLocationNode.isNew()) {
259 target = targetLocationNode; // keep existing targetLocationNode as target to avoid unnecessary changes (see #2447)
260 } else {
261 target = selectTargetNode(allNodes);
262 }
263
264 Command cmd = mergeNodes(layer, nodes, target, targetLocationNode);
265 if (cmd != null) {
266 Main.main.undoRedo.add(cmd);
267 layer.data.setSelected(target);
268 }
269 }
270
271 /**
272 * Merges the nodes in {@code nodes} at the specified node's location. Uses the dataset
273 * managed by {@code layer} as reference.
274 *
275 * @param layer layer the reference data layer. Must not be null.
276 * @param nodes the collection of nodes. Ignored if null.
277 * @param targetLocationNode this node's location will be used for the targetNode.
278 * @return The command necessary to run in order to perform action, or {@code null} if there is nothing to do
279 * @throws IllegalArgumentException if {@code layer} is null
280 */
281 public static Command mergeNodes(OsmDataLayer layer, Collection<Node> nodes, Node targetLocationNode) {
282 if (nodes == null) {
283 return null;
284 }
285 Set<Node> allNodes = new HashSet<>(nodes);
286 allNodes.add(targetLocationNode);
287 return mergeNodes(layer, nodes, selectTargetNode(allNodes), targetLocationNode);
288 }
289
290 /**
291 * Merges the nodes in <code>nodes</code> onto one of the nodes. Uses the dataset
292 * managed by <code>layer</code> as reference.
293 *
294 * @param layer layer the reference data layer. Must not be null.
295 * @param nodes the collection of nodes. Ignored if null.
296 * @param targetNode the target node the collection of nodes is merged to. Must not be null.
297 * @param targetLocationNode this node's location will be used for the targetNode.
298 * @return The command necessary to run in order to perform action, or {@code null} if there is nothing to do
299 * @throws IllegalArgumentException if layer is null
300 */
301 public static Command mergeNodes(OsmDataLayer layer, Collection<Node> nodes, Node targetNode, Node targetLocationNode) {
302 CheckParameterUtil.ensureParameterNotNull(layer, "layer");
303 CheckParameterUtil.ensureParameterNotNull(targetNode, "targetNode");
304 if (nodes == null) {
305 return null;
306 }
307
308 try {
309 TagCollection nodeTags = TagCollection.unionOfAllPrimitives(nodes);
310
311 // the nodes we will have to delete
312 //
313 Collection<Node> nodesToDelete = new HashSet<>(nodes);
314 nodesToDelete.remove(targetNode);
315
316 // fix the ways referring to at least one of the merged nodes
317 //
318 List<Command> wayFixCommands = fixParentWays(nodesToDelete, targetNode);
319 if (wayFixCommands == null) {
320 return null;
321 }
322 List<Command> cmds = new LinkedList<>(wayFixCommands);
323
324 // build the commands
325 //
326 if (!targetNode.equals(targetLocationNode)) {
327 LatLon targetLocationCoor = targetLocationNode.getCoor();
328 if (!Objects.equals(targetNode.getCoor(), targetLocationCoor)) {
329 Node newTargetNode = new Node(targetNode);
330 newTargetNode.setCoor(targetLocationCoor);
331 cmds.add(new ChangeCommand(targetNode, newTargetNode));
332 }
333 }
334 cmds.addAll(CombinePrimitiveResolverDialog.launchIfNecessary(nodeTags, nodes, Collections.singleton(targetNode)));
335 if (!nodesToDelete.isEmpty()) {
336 cmds.add(new DeleteCommand(nodesToDelete));
337 }
338 return new SequenceCommand(/* for correct i18n of plural forms - see #9110 */
339 trn("Merge {0} node", "Merge {0} nodes", nodes.size(), nodes.size()), cmds);
340 } catch (UserCancelException ex) {
341 Main.trace(ex);
342 return null;
343 }
344 }
345
346 @Override
347 protected void updateEnabledState() {
348 updateEnabledStateOnCurrentSelection();
349 }
350
351 @Override
352 protected void updateEnabledState(Collection<? extends OsmPrimitive> selection) {
353 if (selection == null || selection.isEmpty()) {
354 setEnabled(false);
355 return;
356 }
357 boolean ok = true;
358 for (OsmPrimitive osm : selection) {
359 if (!(osm instanceof Node)) {
360 ok = false;
361 break;
362 }
363 }
364 setEnabled(ok);
365 }
366}
Note: See TracBrowser for help on using the repository browser.