source: josm/trunk/src/org/openstreetmap/josm/actions/CombineWayAction.java@ 11488

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

findbugs - DLS_DEAD_LOCAL_STORE

  • Property svn:eol-style set to native
File size: 21.4 KB
RevLine 
[6380]1// License: GPL. For details, see LICENSE file.
[283]2package org.openstreetmap.josm.actions;
3
[2564]4import static org.openstreetmap.josm.gui.help.HelpUtil.ht;
[283]5import static org.openstreetmap.josm.tools.I18n.tr;
[6507]6import static org.openstreetmap.josm.tools.I18n.trn;
[283]7
8import java.awt.event.ActionEvent;
9import java.awt.event.KeyEvent;
[1951]10import java.util.ArrayList;
[283]11import java.util.Collection;
[2210]12import java.util.Collections;
[3445]13import java.util.LinkedHashMap;
14import java.util.LinkedHashSet;
[283]15import java.util.LinkedList;
[343]16import java.util.List;
[6317]17import java.util.Map;
[9371]18import java.util.Objects;
[283]19import java.util.Set;
[8856]20import java.util.Stack;
[283]21
22import javax.swing.JOptionPane;
23
24import org.openstreetmap.josm.Main;
25import org.openstreetmap.josm.command.ChangeCommand;
26import org.openstreetmap.josm.command.Command;
27import org.openstreetmap.josm.command.DeleteCommand;
28import org.openstreetmap.josm.command.SequenceCommand;
[2573]29import org.openstreetmap.josm.corrector.ReverseWayTagCorrector;
[10382]30import org.openstreetmap.josm.data.osm.DataSet;
[582]31import org.openstreetmap.josm.data.osm.Node;
[283]32import org.openstreetmap.josm.data.osm.OsmPrimitive;
[2070]33import org.openstreetmap.josm.data.osm.TagCollection;
[283]34import org.openstreetmap.josm.data.osm.Way;
[3409]35import org.openstreetmap.josm.data.preferences.BooleanProperty;
[1397]36import org.openstreetmap.josm.gui.ExtendedDialog;
[6130]37import org.openstreetmap.josm.gui.Notification;
[2095]38import org.openstreetmap.josm.gui.conflict.tags.CombinePrimitiveResolverDialog;
[5452]39import org.openstreetmap.josm.gui.util.GuiHelper;
[429]40import org.openstreetmap.josm.tools.Pair;
[1084]41import org.openstreetmap.josm.tools.Shortcut;
[8919]42import org.openstreetmap.josm.tools.UserCancelException;
[2573]43
[283]44/**
45 * Combines multiple ways into one.
[6156]46 * @since 213
[283]47 */
[1820]48public class CombineWayAction extends JosmAction {
[283]49
[3409]50 private static final BooleanProperty PROP_REVERSE_WAY = new BooleanProperty("tag-correction.reverse-way", true);
51
[6156]52 /**
53 * Constructs a new {@code CombineWayAction}.
54 */
[1169]55 public CombineWayAction() {
56 super(tr("Combine Way"), "combineway", tr("Combine several ways into one."),
[4982]57 Shortcut.registerShortcut("tools:combineway", tr("Tool: {0}", tr("Combine Way")), KeyEvent.VK_C, Shortcut.DIRECT), true);
[2323]58 putValue("help", ht("/Action/CombineWay"));
[1169]59 }
[283]60
[3504]61 protected static boolean confirmChangeDirectionOfWays() {
[2070]62 ExtendedDialog ed = new ExtendedDialog(Main.parent,
63 tr("Change directions?"),
64 new String[] {tr("Reverse and Combine"), tr("Cancel")});
[8061]65 ed.setButtonIcons(new String[] {"wayflip", "cancel"});
[2070]66 ed.setContent(tr("The ways can not be combined in their current directions. "
67 + "Do you want to reverse some of them?"));
[6596]68 ed.toggleEnable("combineway-reverse");
[2070]69 ed.showDialog();
70 return ed.getValue() == 1;
71 }
72
[3504]73 protected static void warnCombiningImpossible() {
[6130]74 String msg = tr("Could not combine ways<br>"
[2070]75 + "(They could not be merged into a single string of nodes)");
[6130]76 new Notification(msg)
77 .setIcon(JOptionPane.INFORMATION_MESSAGE)
78 .show();
[2070]79 }
80
[3504]81 protected static Way getTargetWay(Collection<Way> combinedWays) {
[2070]82 // init with an arbitrary way
83 Way targetWay = combinedWays.iterator().next();
84
85 // look for the first way already existing on
86 // the server
87 for (Way w : combinedWays) {
88 targetWay = w;
[2273]89 if (!w.isNew()) {
[2070]90 break;
91 }
92 }
93 return targetWay;
94 }
95
[2564]96 /**
[8181]97 * Combine multiple ways into one.
98 * @param ways the way to combine to one way
[8459]99 * @return null if ways cannot be combined. Otherwise returns the combined ways and the commands to combine
100 * @throws UserCancelException if the user cancelled a dialog.
[3504]101 */
102 public static Pair<Way, Command> combineWaysWorker(Collection<Way> ways) throws UserCancelException {
103
[2070]104 // prepare and clean the list of ways to combine
105 //
106 if (ways == null || ways.isEmpty())
[3230]107 return null;
[2070]108 ways.remove(null); // just in case - remove all null ways from the collection
109
[3445]110 // remove duplicates, preserving order
[7005]111 ways = new LinkedHashSet<>(ways);
[3445]112
[8459]113 // try to build a new way which includes all the combined ways
[2070]114 //
[8181]115 NodeGraph graph = NodeGraph.createNearlyUndirectedGraphFromNodeWays(ways);
[2070]116 List<Node> path = graph.buildSpanningPath();
117 if (path == null) {
[2573]118 warnCombiningImpossible();
[3230]119 return null;
[2573]120 }
121 // check whether any ways have been reversed in the process
122 // and build the collection of tags used by the ways to combine
123 //
124 TagCollection wayTags = TagCollection.unionOfAllPrimitives(ways);
125
[9439]126 final List<Command> reverseWayTagCommands = new LinkedList<>();
[7005]127 List<Way> reversedWays = new LinkedList<>();
128 List<Way> unreversedWays = new LinkedList<>();
[2573]129 for (Way w: ways) {
[6156]130 // Treat zero or one-node ways as unreversed as Combine action action is a good way to fix them (see #8971)
131 if (w.getNodesCount() < 2 || (path.indexOf(w.getNode(0)) + 1) == path.lastIndexOf(w.getNode(1))) {
[2573]132 unreversedWays.add(w);
[2070]133 } else {
[2573]134 reversedWays.add(w);
[2070]135 }
136 }
[2573]137 // reverse path if all ways have been reversed
138 if (unreversedWays.isEmpty()) {
139 Collections.reverse(path);
140 unreversedWays = reversedWays;
141 reversedWays = null;
142 }
143 if ((reversedWays != null) && !reversedWays.isEmpty()) {
[3230]144 if (!confirmChangeDirectionOfWays()) return null;
[2573]145 // filter out ways that have no direction-dependent tags
146 unreversedWays = ReverseWayTagCorrector.irreversibleWays(unreversedWays);
147 reversedWays = ReverseWayTagCorrector.irreversibleWays(reversedWays);
148 // reverse path if there are more reversed than unreversed ways with direction-dependent tags
149 if (reversedWays.size() > unreversedWays.size()) {
150 Collections.reverse(path);
151 List<Way> tempWays = unreversedWays;
[11389]152 unreversedWays = null;
[2573]153 reversedWays = tempWays;
154 }
155 // if there are still reversed ways with direction-dependent tags, reverse their tags
[3409]156 if (!reversedWays.isEmpty() && PROP_REVERSE_WAY.get()) {
[7005]157 List<Way> unreversedTagWays = new ArrayList<>(ways);
[2573]158 unreversedTagWays.removeAll(reversedWays);
159 ReverseWayTagCorrector reverseWayTagCorrector = new ReverseWayTagCorrector();
[7005]160 List<Way> reversedTagWays = new ArrayList<>(reversedWays.size());
[2573]161 for (Way w : reversedWays) {
162 Way wnew = new Way(w);
163 reversedTagWays.add(wnew);
[9439]164 reverseWayTagCommands.addAll(reverseWayTagCorrector.execute(w, wnew));
[2573]165 }
[9439]166 if (!reverseWayTagCommands.isEmpty()) {
167 // commands need to be executed for CombinePrimitiveResolverDialog
168 Main.main.undoRedo.add(new SequenceCommand(tr("Reverse Ways"), reverseWayTagCommands));
[2573]169 }
170 wayTags = TagCollection.unionOfAllPrimitives(reversedTagWays);
171 wayTags.add(TagCollection.unionOfAllPrimitives(unreversedTagWays));
172 }
173 }
[2070]174
175 // create the new way and apply the new node list
176 //
177 Way targetWay = getTargetWay(ways);
178 Way modifiedTargetWay = new Way(targetWay);
179 modifiedTargetWay.setNodes(path);
180
[9439]181 final List<Command> resolution;
182 try {
183 resolution = CombinePrimitiveResolverDialog.launchIfNecessary(wayTags, ways, Collections.singleton(targetWay));
184 } finally {
185 if (!reverseWayTagCommands.isEmpty()) {
186 // undo reverseWayTagCorrector and merge into SequenceCommand below
187 Main.main.undoRedo.undo();
188 }
189 }
[2079]190
[8338]191 List<Command> cmds = new LinkedList<>();
192 List<Way> deletedWays = new LinkedList<>(ways);
[2070]193 deletedWays.remove(targetWay);
194
195 cmds.add(new ChangeCommand(targetWay, modifiedTargetWay));
[9439]196 cmds.addAll(reverseWayTagCommands);
[5132]197 cmds.addAll(resolution);
[3170]198 cmds.add(new DeleteCommand(deletedWays));
[9070]199 final Command sequenceCommand = new SequenceCommand(/* for correct i18n of plural forms - see #9110 */
[6679]200 trn("Combine {0} way", "Combine {0} ways", ways.size(), ways.size()), cmds);
[2070]201
[9070]202 return new Pair<>(targetWay, sequenceCommand);
[2070]203 }
204
[6084]205 @Override
[1169]206 public void actionPerformed(ActionEvent event) {
[10382]207 final DataSet ds = getLayerManager().getEditDataSet();
208 if (ds == null)
[1817]209 return;
[10382]210 Collection<OsmPrimitive> selection = ds.getSelected();
[2070]211 Set<Way> selectedWays = OsmPrimitive.getFilteredSet(selection, Way.class);
[1169]212 if (selectedWays.size() < 2) {
[6130]213 new Notification(
214 tr("Please select at least two ways to combine."))
215 .setIcon(JOptionPane.INFORMATION_MESSAGE)
216 .setDuration(Notification.TIME_SHORT)
217 .show();
[1169]218 return;
219 }
[3230]220 // combine and update gui
[3504]221 Pair<Way, Command> combineResult;
222 try {
223 combineResult = combineWaysWorker(selectedWays);
224 } catch (UserCancelException ex) {
[10463]225 Main.trace(ex);
[3504]226 return;
227 }
228
229 if (combineResult == null)
230 return;
231 final Way selectedWay = combineResult.a;
232 Main.main.undoRedo.add(combineResult.b);
[8510]233 if (selectedWay != null) {
[10601]234 GuiHelper.runInEDT(() -> ds.setSelected(selectedWay));
[3230]235 }
[2070]236 }
[426]237
[2070]238 @Override
239 protected void updateEnabledState() {
[10548]240 updateEnabledStateOnCurrentSelection();
[2256]241 }
242
243 @Override
244 protected void updateEnabledState(Collection<? extends OsmPrimitive> selection) {
[2070]245 int numWays = 0;
[8513]246 for (OsmPrimitive osm : selection) {
[2070]247 if (osm instanceof Way) {
248 numWays++;
249 }
[8513]250 }
[2070]251 setEnabled(numWays >= 2);
252 }
[426]253
[6156]254 /**
255 * A pair of nodes.
256 */
[6889]257 public static class NodePair {
[6156]258 private final Node a;
259 private final Node b;
[7509]260
[6156]261 /**
262 * Constructs a new {@code NodePair}.
263 * @param a The first node
264 * @param b The second node
265 */
[2070]266 public NodePair(Node a, Node b) {
[6156]267 this.a = a;
[2070]268 this.b = b;
269 }
270
[6156]271 /**
272 * Constructs a new {@code NodePair}.
273 * @param pair An existing {@code Pair} of nodes
274 */
[8510]275 public NodePair(Pair<Node, Node> pair) {
[6156]276 this(pair.a, pair.b);
[2070]277 }
278
[6156]279 /**
280 * Replies the first node.
281 * @return The first node
282 */
[2070]283 public Node getA() {
284 return a;
285 }
286
[6156]287 /**
288 * Replies the second node
289 * @return The second node
290 */
[2070]291 public Node getB() {
292 return b;
293 }
294
295 public boolean isSuccessorOf(NodePair other) {
[10662]296 return other.getB() == a;
[2070]297 }
298
299 public boolean isPredecessorOf(NodePair other) {
[10662]300 return b == other.getA();
[2070]301 }
302
303 public NodePair swap() {
[8510]304 return new NodePair(b, a);
[2070]305 }
306
307 @Override
308 public String toString() {
309 return new StringBuilder()
[8390]310 .append('[')
[2070]311 .append(a.getId())
[8390]312 .append(',')
[2070]313 .append(b.getId())
[8390]314 .append(']')
[2070]315 .toString();
316 }
317
[6156]318 /**
319 * Determines if this pair contains the given node.
320 * @param n The node to look for
321 * @return {@code true} if {@code n} is in the pair, {@code false} otherwise
322 */
[2070]323 public boolean contains(Node n) {
[10662]324 return a == n || b == n;
[2070]325 }
326
327 @Override
328 public int hashCode() {
[9371]329 return Objects.hash(a, b);
[2070]330 }
[7509]331
[2070]332 @Override
333 public boolean equals(Object obj) {
[9371]334 if (this == obj) return true;
335 if (obj == null || getClass() != obj.getClass()) return false;
336 NodePair nodePair = (NodePair) obj;
337 return Objects.equals(a, nodePair.a) &&
[10659]338 Objects.equals(b, nodePair.b);
[2070]339 }
340 }
341
[6889]342 public static class NodeGraph {
343 public static List<NodePair> buildNodePairs(Way way, boolean directed) {
[7005]344 List<NodePair> pairs = new ArrayList<>();
[8510]345 for (Pair<Node, Node> pair: way.getNodePairs(false /* don't sort */)) {
[2070]346 pairs.add(new NodePair(pair));
347 if (!directed) {
348 pairs.add(new NodePair(pair).swap());
[1814]349 }
[1169]350 }
[2070]351 return pairs;
[1169]352 }
[343]353
[6889]354 public static List<NodePair> buildNodePairs(List<Way> ways, boolean directed) {
[7005]355 List<NodePair> pairs = new ArrayList<>();
[2070]356 for (Way w: ways) {
357 pairs.addAll(buildNodePairs(w, directed));
358 }
359 return pairs;
360 }
[2032]361
[6889]362 public static List<NodePair> eliminateDuplicateNodePairs(List<NodePair> pairs) {
[7005]363 List<NodePair> cleaned = new ArrayList<>();
[8510]364 for (NodePair p: pairs) {
[2070]365 if (!cleaned.contains(p) && !cleaned.contains(p.swap())) {
366 cleaned.add(p);
367 }
[1169]368 }
[2070]369 return cleaned;
[1169]370 }
[343]371
[6889]372 public static NodeGraph createDirectedGraphFromNodePairs(List<NodePair> pairs) {
[2070]373 NodeGraph graph = new NodeGraph();
374 for (NodePair pair: pairs) {
375 graph.add(pair);
376 }
377 return graph;
378 }
[699]379
[6889]380 public static NodeGraph createDirectedGraphFromWays(Collection<Way> ways) {
[2070]381 NodeGraph graph = new NodeGraph();
382 for (Way w: ways) {
383 graph.add(buildNodePairs(w, true /* directed */));
[1814]384 }
[2070]385 return graph;
[1169]386 }
[699]387
[8181]388 /**
[8440]389 * Create an undirected graph from the given node pairs.
390 * @param pairs Node pairs to build the graph from
[8181]391 * @return node graph structure
392 */
[6889]393 public static NodeGraph createUndirectedGraphFromNodeList(List<NodePair> pairs) {
[2070]394 NodeGraph graph = new NodeGraph();
395 for (NodePair pair: pairs) {
396 graph.add(pair);
397 graph.add(pair.swap());
398 }
399 return graph;
400 }
[426]401
[8181]402 /**
403 * Create an undirected graph from the given ways, but prevent reversing of all
404 * non-new ways by fix one direction.
405 * @param ways Ways to build the graph from
406 * @return node graph structure
407 * @since 8181
408 */
[6317]409 public static NodeGraph createUndirectedGraphFromNodeWays(Collection<Way> ways) {
[2070]410 NodeGraph graph = new NodeGraph();
411 for (Way w: ways) {
412 graph.add(buildNodePairs(w, false /* undirected */));
[1530]413 }
[2070]414 return graph;
[1169]415 }
[426]416
[8181]417 public static NodeGraph createNearlyUndirectedGraphFromNodeWays(Collection<Way> ways) {
418 boolean dir = true;
419 NodeGraph graph = new NodeGraph();
420 for (Way w: ways) {
[8510]421 if (!w.isNew()) {
[8181]422 /* let the first non-new way give the direction (see #5880) */
423 graph.add(buildNodePairs(w, dir));
424 dir = false;
425 } else {
426 graph.add(buildNodePairs(w, false /* undirected */));
427 }
428 }
429 return graph;
430 }
431
[9067]432 private final Set<NodePair> edges;
[8840]433 private int numUndirectedEges;
[10250]434 private final Map<Node, List<NodePair>> successors = new LinkedHashMap<>();
435 private final Map<Node, List<NodePair>> predecessors = new LinkedHashMap<>();
[2032]436
[2210]437 protected void rememberSuccessor(NodePair pair) {
438 if (successors.containsKey(pair.getA())) {
439 if (!successors.get(pair.getA()).contains(pair)) {
440 successors.get(pair.getA()).add(pair);
441 }
442 } else {
[7005]443 List<NodePair> l = new ArrayList<>();
[2210]444 l.add(pair);
445 successors.put(pair.getA(), l);
446 }
447 }
448
449 protected void rememberPredecessors(NodePair pair) {
450 if (predecessors.containsKey(pair.getB())) {
451 if (!predecessors.get(pair.getB()).contains(pair)) {
452 predecessors.get(pair.getB()).add(pair);
453 }
454 } else {
[7005]455 List<NodePair> l = new ArrayList<>();
[2210]456 l.add(pair);
457 predecessors.put(pair.getB(), l);
458 }
459 }
460
461 protected boolean isTerminalNode(Node n) {
462 if (successors.get(n) == null) return false;
463 if (successors.get(n).size() != 1) return false;
464 if (predecessors.get(n) == null) return true;
465 if (predecessors.get(n).size() == 1) {
[8846]466 NodePair p1 = successors.get(n).get(0);
467 NodePair p2 = predecessors.get(n).get(0);
[2210]468 return p1.equals(p2.swap());
469 }
470 return false;
471 }
472
473 protected void prepare() {
[7005]474 Set<NodePair> undirectedEdges = new LinkedHashSet<>();
[10250]475 successors.clear();
476 predecessors.clear();
[2210]477
[2070]478 for (NodePair pair: edges) {
[8443]479 if (!undirectedEdges.contains(pair) && !undirectedEdges.contains(pair.swap())) {
[2070]480 undirectedEdges.add(pair);
481 }
[2210]482 rememberSuccessor(pair);
483 rememberPredecessors(pair);
[2070]484 }
485 numUndirectedEges = undirectedEdges.size();
486 }
[1621]487
[6156]488 /**
489 * Constructs a new {@code NodeGraph}.
490 */
[2070]491 public NodeGraph() {
[7005]492 edges = new LinkedHashSet<>();
[2070]493 }
[2032]494
[2070]495 public void add(NodePair pair) {
496 if (!edges.contains(pair)) {
497 edges.add(pair);
[1814]498 }
[1169]499 }
[283]500
[2070]501 public void add(List<NodePair> pairs) {
502 for (NodePair pair: pairs) {
503 add(pair);
504 }
505 }
[426]506
[2210]507 protected Set<Node> getTerminalNodes() {
[7005]508 Set<Node> ret = new LinkedHashSet<>();
[2210]509 for (Node n: getNodes()) {
510 if (isTerminalNode(n)) {
511 ret.add(n);
512 }
513 }
514 return ret;
515 }
516
[2070]517 protected List<NodePair> getOutboundPairs(NodePair pair) {
[2210]518 return getOutboundPairs(pair.getB());
[2070]519 }
520
521 protected List<NodePair> getOutboundPairs(Node node) {
[2210]522 List<NodePair> l = successors.get(node);
[2356]523 if (l == null)
524 return Collections.emptyList();
525 return l;
[1169]526 }
[283]527
[2070]528 protected Set<Node> getNodes() {
[7005]529 Set<Node> nodes = new LinkedHashSet<>(2 * edges.size());
[2070]530 for (NodePair pair: edges) {
531 nodes.add(pair.getA());
532 nodes.add(pair.getB());
533 }
534 return nodes;
535 }
[426]536
[8856]537 protected boolean isSpanningWay(Stack<NodePair> way) {
[2070]538 return numUndirectedEges == way.size();
[1814]539 }
[343]540
[8856]541 protected List<Node> buildPathFromNodePairs(Stack<NodePair> path) {
[8338]542 List<Node> ret = new LinkedList<>();
[2070]543 for (NodePair pair: path) {
544 ret.add(pair.getA());
[1169]545 }
[2070]546 ret.add(path.peek().getB());
547 return ret;
[1169]548 }
[343]549
[2210]550 /**
551 * Tries to find a spanning path starting from node <code>startNode</code>.
[2512]552 *
[2210]553 * Traverses the path in depth-first order.
[2512]554 *
[2210]555 * @param startNode the start node
556 * @return the spanning path; null, if no path is found
557 */
[2070]558 protected List<Node> buildSpanningPath(Node startNode) {
559 if (startNode == null)
560 return null;
[8856]561 Stack<NodePair> path = new Stack<>();
[10378]562 Stack<NodePair> nextPairs = new Stack<>();
[2070]563 nextPairs.addAll(getOutboundPairs(startNode));
[8510]564 while (!nextPairs.isEmpty()) {
565 NodePair cur = nextPairs.pop();
[8443]566 if (!path.contains(cur) && !path.contains(cur.swap())) {
[8510]567 while (!path.isEmpty() && !path.peek().isPredecessorOf(cur)) {
[2210]568 path.pop();
569 }
570 path.push(cur);
571 if (isSpanningWay(path)) return buildPathFromNodePairs(path);
572 nextPairs.addAll(getOutboundPairs(path.peek()));
573 }
[2070]574 }
575 return null;
[1817]576 }
577
[2210]578 /**
579 * Tries to find a path through the graph which visits each edge (i.e.
[8181]580 * the segment of a way) exactly once.
[2512]581 *
[2210]582 * @return the path; null, if no path was found
583 */
[2070]584 public List<Node> buildSpanningPath() {
[2210]585 prepare();
586 // try to find a path from each "terminal node", i.e. from a
587 // node which is connected by exactly one undirected edges (or
588 // two directed edges in opposite direction) to the graph. A
589 // graph built up from way segments is likely to include such
590 // nodes, unless all ways are closed.
[8459]591 // In the worst case this loops over all nodes which is very slow for large ways.
[2210]592 //
593 Set<Node> nodes = getTerminalNodes();
594 nodes = nodes.isEmpty() ? getNodes() : nodes;
595 for (Node n: nodes) {
[2070]596 List<Node> path = buildSpanningPath(n);
597 if (path != null)
598 return path;
[1169]599 }
[2070]600 return null;
601 }
[1169]602 }
[283]603}
Note: See TracBrowser for help on using the repository browser.