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

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

refactor handling of null values - use Java 8 Optional where possible

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