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

Last change on this file since 10759 was 10662, checked in by Don-vip, 8 years ago

see #12472, fix #13230, fix #13225, fix #13228 - disable ReferenceEquality warning + partial revert of r10656 + r10659, causes too much problems

  • Property svn:eol-style set to native
File size: 21.4 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 GuiHelper.runInEDT(() -> ds.setSelected(selectedWay));
236 }
237 }
238
239 @Override
240 protected void updateEnabledState() {
241 updateEnabledStateOnCurrentSelection();
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 * Replies the first node.
282 * @return The first node
283 */
284 public Node getA() {
285 return a;
286 }
287
288 /**
289 * Replies the second node
290 * @return The second node
291 */
292 public Node getB() {
293 return b;
294 }
295
296 public boolean isSuccessorOf(NodePair other) {
297 return other.getB() == a;
298 }
299
300 public boolean isPredecessorOf(NodePair other) {
301 return b == other.getA();
302 }
303
304 public NodePair swap() {
305 return new NodePair(b, a);
306 }
307
308 @Override
309 public String toString() {
310 return new StringBuilder()
311 .append('[')
312 .append(a.getId())
313 .append(',')
314 .append(b.getId())
315 .append(']')
316 .toString();
317 }
318
319 /**
320 * Determines if this pair contains the given node.
321 * @param n The node to look for
322 * @return {@code true} if {@code n} is in the pair, {@code false} otherwise
323 */
324 public boolean contains(Node n) {
325 return a == n || b == n;
326 }
327
328 @Override
329 public int hashCode() {
330 return Objects.hash(a, b);
331 }
332
333 @Override
334 public boolean equals(Object obj) {
335 if (this == obj) return true;
336 if (obj == null || getClass() != obj.getClass()) return false;
337 NodePair nodePair = (NodePair) obj;
338 return Objects.equals(a, nodePair.a) &&
339 Objects.equals(b, nodePair.b);
340 }
341 }
342
343 public static class NodeGraph {
344 public static List<NodePair> buildNodePairs(Way way, boolean directed) {
345 List<NodePair> pairs = new ArrayList<>();
346 for (Pair<Node, Node> pair: way.getNodePairs(false /* don't sort */)) {
347 pairs.add(new NodePair(pair));
348 if (!directed) {
349 pairs.add(new NodePair(pair).swap());
350 }
351 }
352 return pairs;
353 }
354
355 public static List<NodePair> buildNodePairs(List<Way> ways, boolean directed) {
356 List<NodePair> pairs = new ArrayList<>();
357 for (Way w: ways) {
358 pairs.addAll(buildNodePairs(w, directed));
359 }
360 return pairs;
361 }
362
363 public static List<NodePair> eliminateDuplicateNodePairs(List<NodePair> pairs) {
364 List<NodePair> cleaned = new ArrayList<>();
365 for (NodePair p: pairs) {
366 if (!cleaned.contains(p) && !cleaned.contains(p.swap())) {
367 cleaned.add(p);
368 }
369 }
370 return cleaned;
371 }
372
373 public static NodeGraph createDirectedGraphFromNodePairs(List<NodePair> pairs) {
374 NodeGraph graph = new NodeGraph();
375 for (NodePair pair: pairs) {
376 graph.add(pair);
377 }
378 return graph;
379 }
380
381 public static NodeGraph createDirectedGraphFromWays(Collection<Way> ways) {
382 NodeGraph graph = new NodeGraph();
383 for (Way w: ways) {
384 graph.add(buildNodePairs(w, true /* directed */));
385 }
386 return graph;
387 }
388
389 /**
390 * Create an undirected graph from the given node pairs.
391 * @param pairs Node pairs to build the graph from
392 * @return node graph structure
393 */
394 public static NodeGraph createUndirectedGraphFromNodeList(List<NodePair> pairs) {
395 NodeGraph graph = new NodeGraph();
396 for (NodePair pair: pairs) {
397 graph.add(pair);
398 graph.add(pair.swap());
399 }
400 return graph;
401 }
402
403 /**
404 * Create an undirected graph from the given ways, but prevent reversing of all
405 * non-new ways by fix one direction.
406 * @param ways Ways to build the graph from
407 * @return node graph structure
408 * @since 8181
409 */
410 public static NodeGraph createUndirectedGraphFromNodeWays(Collection<Way> ways) {
411 NodeGraph graph = new NodeGraph();
412 for (Way w: ways) {
413 graph.add(buildNodePairs(w, false /* undirected */));
414 }
415 return graph;
416 }
417
418 public static NodeGraph createNearlyUndirectedGraphFromNodeWays(Collection<Way> ways) {
419 boolean dir = true;
420 NodeGraph graph = new NodeGraph();
421 for (Way w: ways) {
422 if (!w.isNew()) {
423 /* let the first non-new way give the direction (see #5880) */
424 graph.add(buildNodePairs(w, dir));
425 dir = false;
426 } else {
427 graph.add(buildNodePairs(w, false /* undirected */));
428 }
429 }
430 return graph;
431 }
432
433 private final Set<NodePair> edges;
434 private int numUndirectedEges;
435 private final Map<Node, List<NodePair>> successors = new LinkedHashMap<>();
436 private final Map<Node, List<NodePair>> predecessors = new LinkedHashMap<>();
437
438 protected void rememberSuccessor(NodePair pair) {
439 if (successors.containsKey(pair.getA())) {
440 if (!successors.get(pair.getA()).contains(pair)) {
441 successors.get(pair.getA()).add(pair);
442 }
443 } else {
444 List<NodePair> l = new ArrayList<>();
445 l.add(pair);
446 successors.put(pair.getA(), l);
447 }
448 }
449
450 protected void rememberPredecessors(NodePair pair) {
451 if (predecessors.containsKey(pair.getB())) {
452 if (!predecessors.get(pair.getB()).contains(pair)) {
453 predecessors.get(pair.getB()).add(pair);
454 }
455 } else {
456 List<NodePair> l = new ArrayList<>();
457 l.add(pair);
458 predecessors.put(pair.getB(), l);
459 }
460 }
461
462 protected boolean isTerminalNode(Node n) {
463 if (successors.get(n) == null) return false;
464 if (successors.get(n).size() != 1) return false;
465 if (predecessors.get(n) == null) return true;
466 if (predecessors.get(n).size() == 1) {
467 NodePair p1 = successors.get(n).get(0);
468 NodePair p2 = predecessors.get(n).get(0);
469 return p1.equals(p2.swap());
470 }
471 return false;
472 }
473
474 protected void prepare() {
475 Set<NodePair> undirectedEdges = new LinkedHashSet<>();
476 successors.clear();
477 predecessors.clear();
478
479 for (NodePair pair: edges) {
480 if (!undirectedEdges.contains(pair) && !undirectedEdges.contains(pair.swap())) {
481 undirectedEdges.add(pair);
482 }
483 rememberSuccessor(pair);
484 rememberPredecessors(pair);
485 }
486 numUndirectedEges = undirectedEdges.size();
487 }
488
489 /**
490 * Constructs a new {@code NodeGraph}.
491 */
492 public NodeGraph() {
493 edges = new LinkedHashSet<>();
494 }
495
496 public void add(NodePair pair) {
497 if (!edges.contains(pair)) {
498 edges.add(pair);
499 }
500 }
501
502 public void add(List<NodePair> pairs) {
503 for (NodePair pair: pairs) {
504 add(pair);
505 }
506 }
507
508 protected Set<Node> getTerminalNodes() {
509 Set<Node> ret = new LinkedHashSet<>();
510 for (Node n: getNodes()) {
511 if (isTerminalNode(n)) {
512 ret.add(n);
513 }
514 }
515 return ret;
516 }
517
518 protected List<NodePair> getOutboundPairs(NodePair pair) {
519 return getOutboundPairs(pair.getB());
520 }
521
522 protected List<NodePair> getOutboundPairs(Node node) {
523 List<NodePair> l = successors.get(node);
524 if (l == null)
525 return Collections.emptyList();
526 return l;
527 }
528
529 protected Set<Node> getNodes() {
530 Set<Node> nodes = new LinkedHashSet<>(2 * edges.size());
531 for (NodePair pair: edges) {
532 nodes.add(pair.getA());
533 nodes.add(pair.getB());
534 }
535 return nodes;
536 }
537
538 protected boolean isSpanningWay(Stack<NodePair> way) {
539 return numUndirectedEges == way.size();
540 }
541
542 protected List<Node> buildPathFromNodePairs(Stack<NodePair> path) {
543 List<Node> ret = new LinkedList<>();
544 for (NodePair pair: path) {
545 ret.add(pair.getA());
546 }
547 ret.add(path.peek().getB());
548 return ret;
549 }
550
551 /**
552 * Tries to find a spanning path starting from node <code>startNode</code>.
553 *
554 * Traverses the path in depth-first order.
555 *
556 * @param startNode the start node
557 * @return the spanning path; null, if no path is found
558 */
559 protected List<Node> buildSpanningPath(Node startNode) {
560 if (startNode == null)
561 return null;
562 Stack<NodePair> path = new Stack<>();
563 Stack<NodePair> nextPairs = new Stack<>();
564 nextPairs.addAll(getOutboundPairs(startNode));
565 while (!nextPairs.isEmpty()) {
566 NodePair cur = nextPairs.pop();
567 if (!path.contains(cur) && !path.contains(cur.swap())) {
568 while (!path.isEmpty() && !path.peek().isPredecessorOf(cur)) {
569 path.pop();
570 }
571 path.push(cur);
572 if (isSpanningWay(path)) return buildPathFromNodePairs(path);
573 nextPairs.addAll(getOutboundPairs(path.peek()));
574 }
575 }
576 return null;
577 }
578
579 /**
580 * Tries to find a path through the graph which visits each edge (i.e.
581 * the segment of a way) exactly once.
582 *
583 * @return the path; null, if no path was found
584 */
585 public List<Node> buildSpanningPath() {
586 prepare();
587 // try to find a path from each "terminal node", i.e. from a
588 // node which is connected by exactly one undirected edges (or
589 // two directed edges in opposite direction) to the graph. A
590 // graph built up from way segments is likely to include such
591 // nodes, unless all ways are closed.
592 // In the worst case this loops over all nodes which is very slow for large ways.
593 //
594 Set<Node> nodes = getTerminalNodes();
595 nodes = nodes.isEmpty() ? getNodes() : nodes;
596 for (Node n: nodes) {
597 List<Node> path = buildSpanningPath(n);
598 if (path != null)
599 return path;
600 }
601 return null;
602 }
603 }
604}
Note: See TracBrowser for help on using the repository browser.