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

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

remove extra whitespaces

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