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

Last change on this file since 10737 was 10716, checked in by simon04, 8 years ago

see #11390, see #12890 - Deprecate predicates in OsmPrimitive class

  • Property svn:eol-style set to native
File size: 15.0 KB
RevLine 
[8378]1// License: GPL. For details, see LICENSE file.
[422]2package org.openstreetmap.josm.actions;
3
[2315]4import static org.openstreetmap.josm.gui.help.HelpUtil.ht;
[422]5import static org.openstreetmap.josm.tools.I18n.tr;
[6507]6import static org.openstreetmap.josm.tools.I18n.trn;
[422]7
8import java.awt.event.ActionEvent;
9import java.awt.event.KeyEvent;
[582]10import java.util.ArrayList;
[422]11import java.util.Collection;
[5132]12import java.util.Collections;
[582]13import java.util.HashSet;
[422]14import java.util.LinkedList;
[2113]15import java.util.List;
[422]16import java.util.Set;
17
18import javax.swing.JOptionPane;
19
20import org.openstreetmap.josm.Main;
21import org.openstreetmap.josm.command.ChangeCommand;
[3142]22import org.openstreetmap.josm.command.ChangeNodesCommand;
[422]23import org.openstreetmap.josm.command.Command;
24import org.openstreetmap.josm.command.DeleteCommand;
25import org.openstreetmap.josm.command.SequenceCommand;
[4315]26import org.openstreetmap.josm.data.coor.EastNorth;
[3596]27import org.openstreetmap.josm.data.coor.LatLon;
[582]28import org.openstreetmap.josm.data.osm.Node;
[422]29import org.openstreetmap.josm.data.osm.OsmPrimitive;
[2095]30import org.openstreetmap.josm.data.osm.TagCollection;
[422]31import org.openstreetmap.josm.data.osm.Way;
[2315]32import org.openstreetmap.josm.gui.DefaultNameFormatter;
33import org.openstreetmap.josm.gui.HelpAwareOptionPane;
34import org.openstreetmap.josm.gui.HelpAwareOptionPane.ButtonSpec;
[6130]35import org.openstreetmap.josm.gui.Notification;
[2095]36import org.openstreetmap.josm.gui.conflict.tags.CombinePrimitiveResolverDialog;
37import org.openstreetmap.josm.gui.layer.OsmDataLayer;
[2842]38import org.openstreetmap.josm.tools.CheckParameterUtil;
[2315]39import org.openstreetmap.josm.tools.ImageProvider;
[1084]40import org.openstreetmap.josm.tools.Shortcut;
[8919]41import org.openstreetmap.josm.tools.UserCancelException;
[4315]42
[422]43/**
[2095]44 * Merges a collection of nodes into one node.
[2512]45 *
[3134]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.)
[3530]48 *
[3134]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.
[7509]52 *
[6202]53 * @since 422
[422]54 */
[1820]55public class MergeNodesAction extends JosmAction {
[422]56
[6202]57 /**
58 * Constructs a new {@code MergeNodesAction}.
59 */
[1169]60 public MergeNodesAction() {
61 super(tr("Merge Nodes"), "mergenodes", tr("Merge nodes into the oldest one."),
[4982]62 Shortcut.registerShortcut("tools:mergenodes", tr("Tool: {0}", tr("Merge Nodes")), KeyEvent.VK_M, Shortcut.DIRECT), true);
[3757]63 putValue("help", ht("/Action/MergeNodes"));
[1169]64 }
[422]65
[6084]66 @Override
[1169]67 public void actionPerformed(ActionEvent event) {
[1820]68 if (!isEnabled())
69 return;
[10382]70 Collection<OsmPrimitive> selection = getLayerManager().getEditDataSet().getAllSelected();
[3713]71 List<Node> selectedNodes = OsmPrimitive.getFilteredList(selection, Node.class);
72
73 if (selectedNodes.size() == 1) {
[7859]74 List<Node> nearestNodes = Main.map.mapView.getNearestNodes(
[10716]75 Main.map.mapView.getPoint(selectedNodes.get(0)), selectedNodes, OsmPrimitive::isUsable);
[3713]76 if (nearestNodes.isEmpty()) {
[6130]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();
[3713]81 return;
82 }
83 selectedNodes.addAll(nearestNodes);
[1169]84 }
[422]85
[2095]86 Node targetNode = selectTargetNode(selectedNodes);
[3134]87 Node targetLocationNode = selectTargetLocationNode(selectedNodes);
[10413]88 Command cmd = mergeNodes(Main.getLayerManager().getEditLayer(), selectedNodes, targetNode, targetLocationNode);
[2095]89 if (cmd != null) {
90 Main.main.undoRedo.add(cmd);
[10413]91 Main.getLayerManager().getEditLayer().data.setSelected(targetNode);
[2095]92 }
93 }
94
95 /**
[3134]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 */
[3713]101 public static Node selectTargetLocationNode(List<Node> candidates) {
[4315]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)) {
[7025]107 case 0:
[4315]108 Node targetNode = candidates.get(size - 1);
[3596]109 for (final Node n : candidates) { // pick last one
110 targetNode = n;
111 }
112 return targetNode;
[7025]113 case 1:
114 double east1 = 0, north1 = 0;
[4315]115 for (final Node n : candidates) {
[7025]116 east1 += n.getEastNorth().east();
117 north1 += n.getEastNorth().north();
[4315]118 }
[3596]119
[7025]120 return new Node(new EastNorth(east1 / size, north1 / size));
121 case 2:
[4315]122 final double[] weights = new double[size];
[3596]123
[4315]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
[7025]134 double east2 = 0, north2 = 0, weight = 0;
[4315]135 for (int i = 0; i < size; i++) {
136 final EastNorth en = candidates.get(i).getEastNorth();
137 final double w = weights[i];
[7025]138 east2 += en.east() * w;
139 north2 += en.north() * w;
[4315]140 weight += w;
141 }
142
[7025]143 return new Node(new EastNorth(east2 / weight, north2 / weight));
[4315]144 default:
[7859]145 throw new IllegalStateException("unacceptable merge-nodes.mode");
[4315]146 }
[3134]147 }
[3530]148
[3134]149 /**
[2341]150 * Find which node to merge into (i.e. which one will be left)
[2512]151 *
[2095]152 * @param candidates the collection of candidate nodes
153 * @return the selected target node
154 */
[5216]155 public static Node selectTargetNode(Collection<Node> candidates) {
[5989]156 Node oldestNode = null;
[2095]157 Node targetNode = null;
[3134]158 Node lastNode = null;
159 for (Node n : candidates) {
160 if (!n.isNew()) {
[5989]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;
[3134]172 }
173 }
174 lastNode = n;
[1169]175 }
[3134]176 if (targetNode == null) {
[9970]177 targetNode = oldestNode != null ? oldestNode : lastNode;
[3134]178 }
[2095]179 return targetNode;
[1169]180 }
[422]181
[3530]182
[1169]183 /**
[2113]184 * Fixes the parent ways referring to one of the nodes.
[2512]185 *
[2202]186 * Replies null, if the ways could not be fixed, i.e. because a way would have to be deleted
[2113]187 * which is referred to by a relation.
[2512]188 *
[2113]189 * @param nodesToDelete the collection of nodes to be deleted
190 * @param targetNode the target node the other nodes are merged to
[2202]191 * @return a list of commands; null, if the ways could not be fixed
[2113]192 */
[3142]193 protected static List<Command> fixParentWays(Collection<Node> nodesToDelete, Node targetNode) {
[7005]194 List<Command> cmds = new ArrayList<>();
195 Set<Way> waysToDelete = new HashSet<>();
[2113]196
[2565]197 for (Way w: OsmPrimitive.getFilteredList(OsmPrimitive.getReferrer(nodesToDelete), Way.class)) {
[7005]198 List<Node> newNodes = new ArrayList<>(w.getNodesCount());
[2113]199 for (Node n: w.getNodes()) {
[8443]200 if (!nodesToDelete.contains(n) && !n.equals(targetNode)) {
[2113]201 newNodes.add(n);
202 } else if (newNodes.isEmpty()) {
203 newNodes.add(targetNode);
[7859]204 } else if (!newNodes.get(newNodes.size()-1).equals(targetNode)) {
[2113]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 }
[8513]209 // else: drop the node
[2113]210 }
211 if (newNodes.size() < 2) {
[2565]212 if (w.getReferrers().isEmpty()) {
[2113]213 waysToDelete.add(w);
214 } else {
[2315]215 ButtonSpec[] options = new ButtonSpec[] {
216 new ButtonSpec(
217 tr("Abort Merging"),
218 ImageProvider.get("cancel"),
219 tr("Click to abort merging nodes"),
220 null /* no special help topic */
221 )
222 };
223 HelpAwareOptionPane.showOptionDialog(
[2113]224 Main.parent,
[5059]225 tr("Cannot merge nodes: Would have to delete way {0} which is still used by {1}",
226 DefaultNameFormatter.getInstance().formatAsHtmlUnorderedList(w),
[9473]227 DefaultNameFormatter.getInstance().formatAsHtmlUnorderedList(w.getReferrers(), 20)),
[2113]228 tr("Warning"),
[2315]229 JOptionPane.WARNING_MESSAGE,
230 null, /* no icon */
231 options,
232 options[0],
233 ht("/Action/MergeNodes#WaysToDeleteStillInUse")
[2113]234 );
235 return null;
236 }
[8510]237 } else if (newNodes.size() < 2 && w.getReferrers().isEmpty()) {
[2113]238 waysToDelete.add(w);
239 } else {
[3142]240 cmds.add(new ChangeNodesCommand(w, newNodes));
[2113]241 }
242 }
[2333]243 if (!waysToDelete.isEmpty()) {
244 cmds.add(new DeleteCommand(waysToDelete));
245 }
[2113]246 return cmds;
247 }
248
[6202]249 /**
250 * Merges the nodes in {@code nodes} at the specified node's location. Uses the dataset
251 * managed by {@code layer} as reference.
252 * @param layer layer the reference data layer. Must not be null
253 * @param nodes the collection of nodes. Ignored if null
254 * @param targetLocationNode this node's location will be used for the target node
[8291]255 * @throws IllegalArgumentException if {@code layer} is null
[6202]256 */
[5265]257 public static void doMergeNodes(OsmDataLayer layer, Collection<Node> nodes, Node targetLocationNode) {
[5216]258 if (nodes == null) {
[5265]259 return;
260 }
[7005]261 Set<Node> allNodes = new HashSet<>(nodes);
[5265]262 allNodes.add(targetLocationNode);
[6202]263 Node target;
264 if (nodes.contains(targetLocationNode) && !targetLocationNode.isNew()) {
265 target = targetLocationNode; // keep existing targetLocationNode as target to avoid unnecessary changes (see #2447)
266 } else {
267 target = selectTargetNode(allNodes);
268 }
[5265]269
270 Command cmd = mergeNodes(layer, nodes, target, targetLocationNode);
271 if (cmd != null) {
272 Main.main.undoRedo.add(cmd);
[10448]273 layer.data.setSelected(target);
[5265]274 }
275 }
276
[6202]277 /**
278 * Merges the nodes in {@code nodes} at the specified node's location. Uses the dataset
279 * managed by {@code layer} as reference.
280 *
281 * @param layer layer the reference data layer. Must not be null.
282 * @param nodes the collection of nodes. Ignored if null.
283 * @param targetLocationNode this node's location will be used for the targetNode.
284 * @return The command necessary to run in order to perform action, or {@code null} if there is nothing to do
[8291]285 * @throws IllegalArgumentException if {@code layer} is null
[6202]286 */
[5265]287 public static Command mergeNodes(OsmDataLayer layer, Collection<Node> nodes, Node targetLocationNode) {
288 if (nodes == null) {
[5216]289 return null;
290 }
[7005]291 Set<Node> allNodes = new HashSet<>(nodes);
[5265]292 allNodes.add(targetLocationNode);
293 return mergeNodes(layer, nodes, selectTargetNode(allNodes), targetLocationNode);
[3134]294 }
[3530]295
[2113]296 /**
[2220]297 * Merges the nodes in <code>nodes</code> onto one of the nodes. Uses the dataset
[2565]298 * managed by <code>layer</code> as reference.
[2095]299 *
300 * @param layer layer the reference data layer. Must not be null.
301 * @param nodes the collection of nodes. Ignored if null.
302 * @param targetNode the target node the collection of nodes is merged to. Must not be null.
[3134]303 * @param targetLocationNode this node's location will be used for the targetNode.
[6202]304 * @return The command necessary to run in order to perform action, or {@code null} if there is nothing to do
[8291]305 * @throws IllegalArgumentException if layer is null
[2095]306 */
[3134]307 public static Command mergeNodes(OsmDataLayer layer, Collection<Node> nodes, Node targetNode, Node targetLocationNode) {
[2842]308 CheckParameterUtil.ensureParameterNotNull(layer, "layer");
309 CheckParameterUtil.ensureParameterNotNull(targetNode, "targetNode");
[5132]310 if (nodes == null) {
[2095]311 return null;
[5132]312 }
[422]313
[5132]314 try {
315 TagCollection nodeTags = TagCollection.unionOfAllPrimitives(nodes);
[422]316
[5132]317 // the nodes we will have to delete
318 //
[7005]319 Collection<Node> nodesToDelete = new HashSet<>(nodes);
[5132]320 nodesToDelete.remove(targetNode);
321
322 // fix the ways referring to at least one of the merged nodes
323 //
[9062]324 List<Command> wayFixCommands = fixParentWays(nodesToDelete, targetNode);
[5132]325 if (wayFixCommands == null) {
[1169]326 return null;
[5132]327 }
[9062]328 List<Command> cmds = new LinkedList<>(wayFixCommands);
[422]329
[5132]330 // build the commands
331 //
[7859]332 if (!targetNode.equals(targetLocationNode)) {
[6275]333 LatLon targetLocationCoor = targetLocationNode.getCoor();
334 if (!targetNode.getCoor().equals(targetLocationCoor)) {
335 Node newTargetNode = new Node(targetNode);
336 newTargetNode.setCoor(targetLocationCoor);
337 cmds.add(new ChangeCommand(targetNode, newTargetNode));
338 }
[5132]339 }
[9062]340 cmds.addAll(CombinePrimitiveResolverDialog.launchIfNecessary(nodeTags, nodes, Collections.singleton(targetNode)));
[5132]341 if (!nodesToDelete.isEmpty()) {
342 cmds.add(new DeleteCommand(nodesToDelete));
343 }
[6507]344 return new SequenceCommand(/* for correct i18n of plural forms - see #9110 */
[6679]345 trn("Merge {0} node", "Merge {0} nodes", nodes.size(), nodes.size()), cmds);
[5132]346 } catch (UserCancelException ex) {
[10463]347 Main.trace(ex);
[2113]348 return null;
[3134]349 }
[1169]350 }
[422]351
[1820]352 @Override
[2256]353 protected void updateEnabledState() {
[10548]354 updateEnabledStateOnCurrentSelection();
[2256]355 }
356
357 @Override
358 protected void updateEnabledState(Collection<? extends OsmPrimitive> selection) {
359 if (selection == null || selection.isEmpty()) {
360 setEnabled(false);
[1820]361 return;
362 }
[1169]363 boolean ok = true;
[2256]364 for (OsmPrimitive osm : selection) {
[1169]365 if (!(osm instanceof Node)) {
366 ok = false;
367 break;
368 }
369 }
370 setEnabled(ok);
371 }
[422]372}
Note: See TracBrowser for help on using the repository browser.