001// License: GPL. For details, see LICENSE file. 002package org.openstreetmap.josm.actions; 003 004import static org.openstreetmap.josm.gui.help.HelpUtil.ht; 005import static org.openstreetmap.josm.tools.I18n.tr; 006import static org.openstreetmap.josm.tools.I18n.trn; 007 008import java.awt.event.ActionEvent; 009import java.awt.event.KeyEvent; 010import java.util.ArrayList; 011import java.util.Collection; 012import java.util.Collections; 013import java.util.HashSet; 014import java.util.LinkedList; 015import java.util.List; 016import java.util.Set; 017 018import javax.swing.JOptionPane; 019 020import org.openstreetmap.josm.Main; 021import org.openstreetmap.josm.command.ChangeCommand; 022import org.openstreetmap.josm.command.ChangeNodesCommand; 023import org.openstreetmap.josm.command.Command; 024import org.openstreetmap.josm.command.DeleteCommand; 025import org.openstreetmap.josm.command.SequenceCommand; 026import org.openstreetmap.josm.data.coor.EastNorth; 027import org.openstreetmap.josm.data.coor.LatLon; 028import org.openstreetmap.josm.data.osm.Node; 029import org.openstreetmap.josm.data.osm.OsmPrimitive; 030import org.openstreetmap.josm.data.osm.TagCollection; 031import org.openstreetmap.josm.data.osm.Way; 032import org.openstreetmap.josm.gui.DefaultNameFormatter; 033import org.openstreetmap.josm.gui.HelpAwareOptionPane; 034import org.openstreetmap.josm.gui.HelpAwareOptionPane.ButtonSpec; 035import org.openstreetmap.josm.gui.Notification; 036import org.openstreetmap.josm.gui.conflict.tags.CombinePrimitiveResolverDialog; 037import org.openstreetmap.josm.gui.layer.OsmDataLayer; 038import org.openstreetmap.josm.tools.CheckParameterUtil; 039import org.openstreetmap.josm.tools.ImageProvider; 040import org.openstreetmap.josm.tools.Shortcut; 041import org.openstreetmap.josm.tools.UserCancelException; 042 043/** 044 * Merges a collection of nodes into one node. 045 * 046 * The "surviving" node will be the one with the lowest positive id. 047 * (I.e. it was uploaded to the server and is the oldest one.) 048 * 049 * However we use the location of the node that was selected *last*. 050 * The "surviving" node will be moved to that location if it is 051 * different from the last selected node. 052 * 053 * @since 422 054 */ 055public class MergeNodesAction extends JosmAction { 056 057 /** 058 * Constructs a new {@code MergeNodesAction}. 059 */ 060 public MergeNodesAction() { 061 super(tr("Merge Nodes"), "mergenodes", tr("Merge nodes into the oldest one."), 062 Shortcut.registerShortcut("tools:mergenodes", tr("Tool: {0}", tr("Merge Nodes")), KeyEvent.VK_M, Shortcut.DIRECT), true); 063 putValue("help", ht("/Action/MergeNodes")); 064 } 065 066 @Override 067 public void actionPerformed(ActionEvent event) { 068 if (!isEnabled()) 069 return; 070 Collection<OsmPrimitive> selection = getCurrentDataSet().getAllSelected(); 071 List<Node> selectedNodes = OsmPrimitive.getFilteredList(selection, Node.class); 072 073 if (selectedNodes.size() == 1) { 074 List<Node> nearestNodes = Main.map.mapView.getNearestNodes( 075 Main.map.mapView.getPoint(selectedNodes.get(0)), selectedNodes, OsmPrimitive.isUsablePredicate); 076 if (nearestNodes.isEmpty()) { 077 new Notification( 078 tr("Please select at least two nodes to merge or one node that is close to another node.")) 079 .setIcon(JOptionPane.WARNING_MESSAGE) 080 .show(); 081 return; 082 } 083 selectedNodes.addAll(nearestNodes); 084 } 085 086 Node targetNode = selectTargetNode(selectedNodes); 087 Node targetLocationNode = selectTargetLocationNode(selectedNodes); 088 Command cmd = mergeNodes(Main.main.getEditLayer(), selectedNodes, targetNode, targetLocationNode); 089 if (cmd != null) { 090 Main.main.undoRedo.add(cmd); 091 Main.main.getEditLayer().data.setSelected(targetNode); 092 } 093 } 094 095 /** 096 * Select the location of the target node after merge. 097 * 098 * @param candidates the collection of candidate nodes 099 * @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 } 209 // else: drop the node 210 } 211 if (newNodes.size() < 2) { 212 if (w.getReferrers().isEmpty()) { 213 waysToDelete.add(w); 214 } else { 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( 224 Main.parent, 225 tr("Cannot merge nodes: Would have to delete way {0} which is still used by {1}", 226 DefaultNameFormatter.getInstance().formatAsHtmlUnorderedList(w), 227 DefaultNameFormatter.getInstance().formatAsHtmlUnorderedList(w.getReferrers())), 228 tr("Warning"), 229 JOptionPane.WARNING_MESSAGE, 230 null, /* no icon */ 231 options, 232 options[0], 233 ht("/Action/MergeNodes#WaysToDeleteStillInUse") 234 ); 235 return null; 236 } 237 } else if (newNodes.size() < 2 && w.getReferrers().isEmpty()) { 238 waysToDelete.add(w); 239 } else { 240 cmds.add(new ChangeNodesCommand(w, newNodes)); 241 } 242 } 243 if (!waysToDelete.isEmpty()) { 244 cmds.add(new DeleteCommand(waysToDelete)); 245 } 246 return cmds; 247 } 248 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 255 * @throws IllegalArgumentException if {@code layer} is null 256 */ 257 public static void doMergeNodes(OsmDataLayer layer, Collection<Node> nodes, Node targetLocationNode) { 258 if (nodes == null) { 259 return; 260 } 261 Set<Node> allNodes = new HashSet<>(nodes); 262 allNodes.add(targetLocationNode); 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 } 269 270 Command cmd = mergeNodes(layer, nodes, target, targetLocationNode); 271 if (cmd != null) { 272 Main.main.undoRedo.add(cmd); 273 getCurrentDataSet().setSelected(target); 274 } 275 } 276 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 285 * @throws IllegalArgumentException if {@code layer} is null 286 */ 287 public static Command mergeNodes(OsmDataLayer layer, Collection<Node> nodes, Node targetLocationNode) { 288 if (nodes == null) { 289 return null; 290 } 291 Set<Node> allNodes = new HashSet<>(nodes); 292 allNodes.add(targetLocationNode); 293 return mergeNodes(layer, nodes, selectTargetNode(allNodes), targetLocationNode); 294 } 295 296 /** 297 * Merges the nodes in <code>nodes</code> onto one of the nodes. Uses the dataset 298 * managed by <code>layer</code> as reference. 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. 303 * @param targetLocationNode this node's location will be used for the targetNode. 304 * @return The command necessary to run in order to perform action, or {@code null} if there is nothing to do 305 * @throws IllegalArgumentException if layer is null 306 */ 307 public static Command mergeNodes(OsmDataLayer layer, Collection<Node> nodes, Node targetNode, Node targetLocationNode) { 308 CheckParameterUtil.ensureParameterNotNull(layer, "layer"); 309 CheckParameterUtil.ensureParameterNotNull(targetNode, "targetNode"); 310 if (nodes == null) { 311 return null; 312 } 313 314 try { 315 TagCollection nodeTags = TagCollection.unionOfAllPrimitives(nodes); 316 317 // the nodes we will have to delete 318 // 319 Collection<Node> nodesToDelete = new HashSet<>(nodes); 320 nodesToDelete.remove(targetNode); 321 322 // fix the ways referring to at least one of the merged nodes 323 // 324 List<Command> wayFixCommands = fixParentWays(nodesToDelete, targetNode); 325 if (wayFixCommands == null) { 326 return null; 327 } 328 List<Command> cmds = new LinkedList<>(wayFixCommands); 329 330 // build the commands 331 // 332 if (!targetNode.equals(targetLocationNode)) { 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 } 339 } 340 cmds.addAll(CombinePrimitiveResolverDialog.launchIfNecessary(nodeTags, nodes, Collections.singleton(targetNode))); 341 if (!nodesToDelete.isEmpty()) { 342 cmds.add(new DeleteCommand(nodesToDelete)); 343 } 344 return new SequenceCommand(/* for correct i18n of plural forms - see #9110 */ 345 trn("Merge {0} node", "Merge {0} nodes", nodes.size(), nodes.size()), cmds); 346 } catch (UserCancelException ex) { 347 return null; 348 } 349 } 350 351 @Override 352 protected void updateEnabledState() { 353 if (getCurrentDataSet() == null) { 354 setEnabled(false); 355 } else { 356 updateEnabledState(getCurrentDataSet().getAllSelected()); 357 } 358 } 359 360 @Override 361 protected void updateEnabledState(Collection<? extends OsmPrimitive> selection) { 362 if (selection == null || selection.isEmpty()) { 363 setEnabled(false); 364 return; 365 } 366 boolean ok = true; 367 for (OsmPrimitive osm : selection) { 368 if (!(osm instanceof Node)) { 369 ok = false; 370 break; 371 } 372 } 373 setEnabled(ok); 374 } 375}