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

Last change on this file since 6683 was 6679, checked in by stoecker, 10 years ago

see #9110 - fix singular forms, even if they are useless

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