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

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

see #12943 - gsoc-core - fix most of deprecation warnings (static accesses must be fixed)

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