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

Last change on this file since 6699 was 6679, checked in by stoecker, 10 years ago

see #9110 - fix singular forms, even if they are useless

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