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

Last change on this file since 8459 was 8459, checked in by Don-vip, 9 years ago

javadoc / Unit test fixes

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