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

Last change on this file since 10598 was 10548, checked in by simon04, 8 years ago

Remove duplicated code

Use updateEnabledStateOnCurrentSelection introduced r10409

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