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

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

Java 7: use Objects.equals and Objects.hash

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