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

Last change on this file since 13187 was 13173, checked in by Don-vip, 6 years ago

see #15310 - remove most of deprecated APIs

  • 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.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 selectedNodes.removeIf(n -> n.isDeleted() || n.isIncomplete());
79
80 if (selectedNodes.size() == 1) {
81 MapView mapView = MainApplication.getMap().mapView;
82 List<Node> nearestNodes = mapView.getNearestNodes(
83 mapView.getPoint(selectedNodes.get(0)), selectedNodes, OsmPrimitive::isUsable);
84 if (nearestNodes.isEmpty()) {
85 new Notification(
86 tr("Please select at least two nodes to merge or one node that is close to another node."))
87 .setIcon(JOptionPane.WARNING_MESSAGE)
88 .show();
89 return;
90 }
91 selectedNodes.addAll(nearestNodes);
92 }
93
94 Node targetNode = selectTargetNode(selectedNodes);
95 if (targetNode != null) {
96 Node targetLocationNode = selectTargetLocationNode(selectedNodes);
97 Command cmd = mergeNodes(selectedNodes, targetNode, targetLocationNode);
98 if (cmd != null) {
99 MainApplication.undoRedo.add(cmd);
100 getLayerManager().getEditLayer().data.setSelected(targetNode);
101 }
102 }
103 }
104
105 /**
106 * Select the location of the target node after merge.
107 *
108 * @param candidates the collection of candidate nodes
109 * @return the coordinates of this node are later used for the target node
110 */
111 public static Node selectTargetLocationNode(List<Node> candidates) {
112 int size = candidates.size();
113 if (size == 0)
114 throw new IllegalArgumentException("empty list");
115 if (size == 1) // to avoid division by 0 in mode 2
116 return candidates.get(0);
117
118 switch (Config.getPref().getInt("merge-nodes.mode", 0)) {
119 case 0:
120 return candidates.get(size - 1);
121 case 1:
122 double east1 = 0;
123 double north1 = 0;
124 for (final Node n : candidates) {
125 EastNorth en = n.getEastNorth();
126 east1 += en.east();
127 north1 += en.north();
128 }
129
130 return new Node(new EastNorth(east1 / size, north1 / size));
131 case 2:
132 final double[] weights = new double[size];
133
134 for (int i = 0; i < size; i++) {
135 final LatLon c1 = candidates.get(i).getCoor();
136 for (int j = i + 1; j < size; j++) {
137 final LatLon c2 = candidates.get(j).getCoor();
138 final double d = c1.distance(c2);
139 weights[i] += d;
140 weights[j] += d;
141 }
142 }
143
144 double east2 = 0;
145 double north2 = 0;
146 double weight = 0;
147 for (int i = 0; i < size; i++) {
148 final EastNorth en = candidates.get(i).getEastNorth();
149 final double w = weights[i];
150 east2 += en.east() * w;
151 north2 += en.north() * w;
152 weight += w;
153 }
154
155 if (weight == 0) // to avoid division by 0
156 return candidates.get(0);
157
158 return new Node(new EastNorth(east2 / weight, north2 / weight));
159 default:
160 throw new IllegalStateException("unacceptable merge-nodes.mode");
161 }
162 }
163
164 /**
165 * Find which node to merge into (i.e. which one will be left)
166 *
167 * @param candidates the collection of candidate nodes
168 * @return the selected target node
169 */
170 public static Node selectTargetNode(Collection<Node> candidates) {
171 Node oldestNode = null;
172 Node targetNode = null;
173 Node lastNode = null;
174 for (Node n : candidates) {
175 if (!n.isNew()) {
176 // Among existing nodes, try to keep the oldest used one
177 if (!n.getReferrers().isEmpty()) {
178 if (targetNode == null || n.getId() < targetNode.getId()) {
179 targetNode = n;
180 }
181 } else if (oldestNode == null || n.getId() < oldestNode.getId()) {
182 oldestNode = n;
183 }
184 }
185 lastNode = n;
186 }
187 return Optional.ofNullable(targetNode).orElse(oldestNode != null ? oldestNode : lastNode);
188 }
189
190 /**
191 * Fixes the parent ways referring to one of the nodes.
192 *
193 * Replies null, if the ways could not be fixed, i.e. because a way would have to be deleted
194 * which is referred to by a relation.
195 *
196 * @param nodesToDelete the collection of nodes to be deleted
197 * @param targetNode the target node the other nodes are merged to
198 * @return a list of commands; null, if the ways could not be fixed
199 */
200 protected static List<Command> fixParentWays(Collection<Node> nodesToDelete, Node targetNode) {
201 List<Command> cmds = new ArrayList<>();
202 Set<Way> waysToDelete = new HashSet<>();
203
204 for (Way w: OsmPrimitive.getFilteredList(OsmPrimitive.getReferrer(nodesToDelete), Way.class)) {
205 List<Node> newNodes = new ArrayList<>(w.getNodesCount());
206 for (Node n: w.getNodes()) {
207 if (!nodesToDelete.contains(n) && !n.equals(targetNode)) {
208 newNodes.add(n);
209 } else if (newNodes.isEmpty() || !newNodes.get(newNodes.size()-1).equals(targetNode)) {
210 // make sure we collapse a sequence of deleted nodes
211 // to exactly one occurrence of the merged target node
212 newNodes.add(targetNode);
213 }
214 // else: drop the node
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(), 20)),
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 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<>(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 if (target != null) {
276 Command cmd = mergeNodes(nodes, target, targetLocationNode);
277 if (cmd != null) {
278 MainApplication.undoRedo.add(cmd);
279 layer.data.setSelected(target);
280 }
281 }
282 }
283
284 /**
285 * Merges the nodes in {@code nodes} at the specified node's location.
286 *
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 * @since 12689
292 */
293 public static Command mergeNodes(Collection<Node> nodes, Node targetLocationNode) {
294 if (nodes == null) {
295 return null;
296 }
297 Set<Node> allNodes = new HashSet<>(nodes);
298 allNodes.add(targetLocationNode);
299 return mergeNodes(nodes, selectTargetNode(allNodes), targetLocationNode);
300 }
301
302 /**
303 * Merges the nodes in <code>nodes</code> onto one of the nodes.
304 *
305 * @param nodes the collection of nodes. Ignored if null.
306 * @param targetNode the target node the collection of nodes is merged to. Must not be null.
307 * @param targetLocationNode this node's location will be used for the targetNode.
308 * @return The command necessary to run in order to perform action, or {@code null} if there is nothing to do
309 * @throws IllegalArgumentException if layer is null
310 */
311 public static Command mergeNodes(Collection<Node> nodes, Node targetNode, Node targetLocationNode) {
312 CheckParameterUtil.ensureParameterNotNull(targetNode, "targetNode");
313 if (nodes == null) {
314 return null;
315 }
316
317 try {
318 TagCollection nodeTags = TagCollection.unionOfAllPrimitives(nodes);
319
320 // the nodes we will have to delete
321 //
322 Collection<Node> nodesToDelete = new HashSet<>(nodes);
323 nodesToDelete.remove(targetNode);
324
325 // fix the ways referring to at least one of the merged nodes
326 //
327 List<Command> wayFixCommands = fixParentWays(nodesToDelete, targetNode);
328 if (wayFixCommands == null) {
329 return null;
330 }
331 List<Command> cmds = new LinkedList<>(wayFixCommands);
332
333 // build the commands
334 //
335 if (!targetNode.equals(targetLocationNode)) {
336 LatLon targetLocationCoor = targetLocationNode.getCoor();
337 if (!Objects.equals(targetNode.getCoor(), targetLocationCoor)) {
338 Node newTargetNode = new Node(targetNode);
339 newTargetNode.setCoor(targetLocationCoor);
340 cmds.add(new ChangeCommand(targetNode, newTargetNode));
341 }
342 }
343 cmds.addAll(CombinePrimitiveResolverDialog.launchIfNecessary(nodeTags, nodes, Collections.singleton(targetNode)));
344 if (!nodesToDelete.isEmpty()) {
345 cmds.add(new DeleteCommand(nodesToDelete));
346 }
347 return new SequenceCommand(/* for correct i18n of plural forms - see #9110 */
348 trn("Merge {0} node", "Merge {0} nodes", nodes.size(), nodes.size()), cmds);
349 } catch (UserCancelException ex) {
350 Logging.trace(ex);
351 return null;
352 }
353 }
354
355 @Override
356 protected void updateEnabledState() {
357 updateEnabledStateOnCurrentSelection();
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}
Note: See TracBrowser for help on using the repository browser.