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

Last change on this file since 12718 was 12689, checked in by Don-vip, 7 years ago

see #15182 - refactor MergeNodesAction to avoid unneeded GUI dependence in DuplicateNode test

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