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

Last change on this file since 12942 was 12846, checked in by bastiK, 7 years ago

see #15229 - use Config.getPref() wherever possible

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