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

Last change on this file since 2220 was 2220, checked in by Gubaer, 15 years ago

fixed #3556: False positive conflicts when merging nodes
fixed #3460: show only conflicting tags at conflict resolution dialog
fixed #3103: resolve conflicts after combining just one conflict

  • Property svn:eol-style set to native
File size: 22.3 KB
Line 
1// License: GPL. Copyright 2007 by Immanuel Scholz and others
2package org.openstreetmap.josm.actions;
3
4import static org.openstreetmap.josm.gui.conflict.tags.TagConflictResolutionUtil.combineTigerTags;
5import static org.openstreetmap.josm.gui.conflict.tags.TagConflictResolutionUtil.completeTagCollectionForEditing;
6import static org.openstreetmap.josm.gui.conflict.tags.TagConflictResolutionUtil.normalizeTagCollectionBeforeEditing;
7import static org.openstreetmap.josm.tools.I18n.tr;
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.HashMap;
15import java.util.HashSet;
16import java.util.LinkedList;
17import java.util.List;
18import java.util.Map;
19import java.util.Set;
20import java.util.Stack;
21
22import javax.swing.JOptionPane;
23import javax.swing.SwingUtilities;
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.data.osm.DataSet;
31import org.openstreetmap.josm.data.osm.Node;
32import org.openstreetmap.josm.data.osm.OsmPrimitive;
33import org.openstreetmap.josm.data.osm.Relation;
34import org.openstreetmap.josm.data.osm.RelationMember;
35import org.openstreetmap.josm.data.osm.TagCollection;
36import org.openstreetmap.josm.data.osm.Way;
37import org.openstreetmap.josm.gui.ExtendedDialog;
38import org.openstreetmap.josm.gui.conflict.tags.CombinePrimitiveResolverDialog;
39import org.openstreetmap.josm.tools.Pair;
40import org.openstreetmap.josm.tools.Shortcut;
41/**
42 * Combines multiple ways into one.
43 *
44 */
45public class CombineWayAction extends JosmAction {
46
47 public CombineWayAction() {
48 super(tr("Combine Way"), "combineway", tr("Combine several ways into one."),
49 Shortcut.registerShortcut("tools:combineway", tr("Tool: {0}", tr("Combine Way")), KeyEvent.VK_C, Shortcut.GROUP_EDIT), true);
50 }
51
52 protected boolean confirmChangeDirectionOfWays() {
53 ExtendedDialog ed = new ExtendedDialog(Main.parent,
54 tr("Change directions?"),
55 new String[] {tr("Reverse and Combine"), tr("Cancel")});
56 ed.setButtonIcons(new String[] {"wayflip.png", "cancel.png"});
57 ed.setContent(tr("The ways can not be combined in their current directions. "
58 + "Do you want to reverse some of them?"));
59 ed.showDialog();
60 return ed.getValue() == 1;
61 }
62
63 protected void warnCombiningImpossible() {
64 String msg = tr("Could not combine ways "
65 + "(They could not be merged into a single string of nodes)");
66 JOptionPane.showMessageDialog(
67 Main.parent,
68 msg,
69 tr("Information"),
70 JOptionPane.INFORMATION_MESSAGE
71 );
72 return;
73 }
74
75 protected Way getTargetWay(Collection<Way> combinedWays) {
76 // init with an arbitrary way
77 Way targetWay = combinedWays.iterator().next();
78
79 // look for the first way already existing on
80 // the server
81 for (Way w : combinedWays) {
82 targetWay = w;
83 if (w.getId() != 0) {
84 break;
85 }
86 }
87 return targetWay;
88 }
89
90
91 public void combineWays(Collection<Way> ways) {
92
93 // prepare and clean the list of ways to combine
94 //
95 if (ways == null || ways.isEmpty())
96 return;
97 ways.remove(null); // just in case - remove all null ways from the collection
98 ways = new HashSet<Way>(ways); // remove duplicates
99
100 // build the list of relations referring to the ways to combine
101 //
102 WayReferringRelations referringRelations = new WayReferringRelations(ways);
103 referringRelations.build(getCurrentDataSet());
104
105 // build the collection of tags used by the ways to combine
106 //
107 TagCollection wayTags = TagCollection.unionOfAllPrimitives(ways);
108
109
110 // try to build a new way which includes all the combined
111 // ways
112 //
113 NodeGraph graph = NodeGraph.createDirectedGraphFromWays(ways);
114 List<Node> path = graph.buildSpanningPath();
115 if (path == null) {
116 graph = NodeGraph.createUndirectedGraphFromNodeWays(ways);
117 path = graph.buildSpanningPath();
118 if (path != null) {
119 if (!confirmChangeDirectionOfWays())
120 return;
121 } else {
122 warnCombiningImpossible();
123 return;
124 }
125 }
126
127 // create the new way and apply the new node list
128 //
129 Way targetWay = getTargetWay(ways);
130 Way modifiedTargetWay = new Way(targetWay);
131 modifiedTargetWay.setNodes(path);
132
133 TagCollection completeWayTags = new TagCollection(wayTags);
134 combineTigerTags(completeWayTags);
135 normalizeTagCollectionBeforeEditing(completeWayTags, ways);
136 TagCollection tagsToEdit = new TagCollection(completeWayTags);
137 completeTagCollectionForEditing(tagsToEdit);
138
139 CombinePrimitiveResolverDialog dialog = CombinePrimitiveResolverDialog.getInstance();
140 dialog.getTagConflictResolverModel().populate(tagsToEdit, completeWayTags.getKeysWithMultipleValues());
141 dialog.setTargetPrimitive(targetWay);
142 dialog.getRelationMemberConflictResolverModel().populate(
143 referringRelations.getRelations(),
144 referringRelations.getWays()
145 );
146 dialog.prepareDefaultDecisions();
147
148 // resolve tag conflicts if necessary
149 //
150 if (!completeWayTags.isApplicableToPrimitive() || !referringRelations.getRelations().isEmpty()) {
151 dialog.setVisible(true);
152 if (dialog.isCancelled())
153 return;
154 }
155
156 LinkedList<Command> cmds = new LinkedList<Command>();
157 LinkedList<Way> deletedWays = new LinkedList<Way>(ways);
158 deletedWays.remove(targetWay);
159
160 cmds.add(new DeleteCommand(deletedWays));
161 cmds.add(new ChangeCommand(targetWay, modifiedTargetWay));
162 cmds.addAll(dialog.buildResolutionCommands());
163 final SequenceCommand sequenceCommand = new SequenceCommand(tr("Combine {0} ways", ways.size()), cmds);
164
165 // update gui
166 final Way selectedWay = targetWay;
167 Runnable guiTask = new Runnable() {
168 public void run() {
169 Main.main.undoRedo.add(sequenceCommand);
170 getCurrentDataSet().setSelected(selectedWay);
171 }
172 };
173 if (SwingUtilities.isEventDispatchThread()) {
174 guiTask.run();
175 } else {
176 SwingUtilities.invokeLater(guiTask);
177 }
178 }
179
180 public void actionPerformed(ActionEvent event) {
181 if (getCurrentDataSet() == null)
182 return;
183 Collection<OsmPrimitive> selection = getCurrentDataSet().getSelected();
184 Set<Way> selectedWays = OsmPrimitive.getFilteredSet(selection, Way.class);
185 if (selectedWays.size() < 2) {
186 JOptionPane.showMessageDialog(
187 Main.parent,
188 tr("Please select at least two ways to combine."),
189 tr("Information"),
190 JOptionPane.INFORMATION_MESSAGE
191 );
192 return;
193 }
194 combineWays(selectedWays);
195 }
196
197 @Override
198 protected void updateEnabledState() {
199 if (getCurrentDataSet() == null) {
200 setEnabled(false);
201 return;
202 }
203 Collection<OsmPrimitive> selection = getCurrentDataSet().getSelected();
204 int numWays = 0;
205
206 for (OsmPrimitive osm : selection)
207 if (osm instanceof Way) {
208 numWays++;
209 }
210 setEnabled(numWays >= 2);
211 }
212
213 /**
214 * This is a collection of relations referring to at least one out of a set of
215 * ways.
216 *
217 *
218 */
219 static private class WayReferringRelations {
220 /**
221 * the map references between relations and ways. The key is a ways, the value is a
222 * set of relations referring to that way.
223 */
224 private Map<Way, Set<Relation>> wayRelationMap;
225
226 /**
227 *
228 * @param ways a collection of ways
229 */
230 public WayReferringRelations(Collection<Way> ways) {
231 wayRelationMap = new HashMap<Way, Set<Relation>>();
232 if (ways == null) return;
233 ways.remove(null); // just in case - remove null values
234 for (Way way: ways) {
235 if (!wayRelationMap.containsKey(way)) {
236 wayRelationMap.put(way, new HashSet<Relation>());
237 }
238 }
239 }
240
241 /**
242 * build the sets of referring relations from the relations in the dataset <code>ds</code>
243 *
244 * @param ds the data set
245 */
246 public void build(DataSet ds) {
247 for (Relation r: ds.relations) {
248 if (!r.isUsable()) {
249 continue;
250 }
251 Set<Way> referringWays = OsmPrimitive.getFilteredSet(r.getMemberPrimitives(), Way.class);
252 for (Way w : wayRelationMap.keySet()) {
253 if (referringWays.contains(w)) {
254 wayRelationMap.get(w).add(r);
255 }
256 }
257 }
258 }
259
260 /**
261 * Replies the ways
262 * @return the ways
263 */
264 public Set<Way> getWays() {
265 return wayRelationMap.keySet();
266 }
267
268 /**
269 * Replies the set of referring relations
270 *
271 * @return the set of referring relations
272 */
273 public Set<Relation> getRelations() {
274 HashSet<Relation> ret = new HashSet<Relation>();
275 for (Way w: wayRelationMap.keySet()) {
276 ret.addAll(wayRelationMap.get(w));
277 }
278 return ret;
279 }
280
281 /**
282 * Replies the set of referring relations for a specific way
283 *
284 * @return the set of referring relations
285 */
286 public Set<Relation> getRelations(Way way) {
287 return wayRelationMap.get(way);
288 }
289
290 protected Command buildRelationUpdateCommand(Relation relation, Collection<Way> ways, Way targetWay) {
291 List<RelationMember> newMembers = new ArrayList<RelationMember>();
292 for (RelationMember rm : relation.getMembers()) {
293 if (ways.contains(rm.getMember())) {
294 RelationMember newMember = new RelationMember(rm.getRole(),targetWay);
295 newMembers.add(newMember);
296 } else {
297 newMembers.add(rm);
298 }
299 }
300 Relation newRelation = new Relation(relation);
301 newRelation.setMembers(newMembers);
302 return new ChangeCommand(relation, newRelation);
303 }
304
305 public List<Command> buildRelationUpdateCommands(Way targetWay) {
306 Collection<Way> toRemove = getWays();
307 toRemove.remove(targetWay);
308 ArrayList<Command> cmds = new ArrayList<Command>();
309 for (Relation r : getRelations()) {
310 Command cmd = buildRelationUpdateCommand(r, toRemove, targetWay);
311 cmds.add(cmd);
312 }
313 return cmds;
314 }
315 }
316
317 static public class NodePair {
318 private Node a;
319 private Node b;
320 public NodePair(Node a, Node b) {
321 this.a =a;
322 this.b = b;
323 }
324
325 public NodePair(Pair<Node,Node> pair) {
326 this.a = pair.a;
327 this.b = pair.b;
328 }
329
330 public NodePair(NodePair other) {
331 this.a = other.a;
332 this.b = other.b;
333 }
334
335 public Node getA() {
336 return a;
337 }
338
339 public Node getB() {
340 return b;
341 }
342
343 public boolean isAdjacentToA(NodePair other) {
344 return other.getA() == a || other.getB() == a;
345 }
346
347 public boolean isAdjacentToB(NodePair other) {
348 return other.getA() == b || other.getB() == b;
349 }
350
351 public boolean isSuccessorOf(NodePair other) {
352 return other.getB() == a;
353 }
354
355 public boolean isPredecessorOf(NodePair other) {
356 return b == other.getA();
357 }
358
359 public NodePair swap() {
360 return new NodePair(b,a);
361 }
362
363 @Override
364 public String toString() {
365 return new StringBuilder()
366 .append("[")
367 .append(a.getId())
368 .append(",")
369 .append(b.getId())
370 .append("]")
371 .toString();
372 }
373
374 public boolean contains(Node n) {
375 return a == n || b == n;
376 }
377
378 @Override
379 public int hashCode() {
380 final int prime = 31;
381 int result = 1;
382 result = prime * result + ((a == null) ? 0 : a.hashCode());
383 result = prime * result + ((b == null) ? 0 : b.hashCode());
384 return result;
385 }
386 @Override
387 public boolean equals(Object obj) {
388 if (this == obj)
389 return true;
390 if (obj == null)
391 return false;
392 if (getClass() != obj.getClass())
393 return false;
394 NodePair other = (NodePair) obj;
395 if (a == null) {
396 if (other.a != null)
397 return false;
398 } else if (!a.equals(other.a))
399 return false;
400 if (b == null) {
401 if (other.b != null)
402 return false;
403 } else if (!b.equals(other.b))
404 return false;
405 return true;
406 }
407 }
408
409
410 static public class NodeGraph {
411 static public List<NodePair> buildNodePairs(Way way, boolean directed) {
412 ArrayList<NodePair> pairs = new ArrayList<NodePair>();
413 for (Pair<Node,Node> pair: way.getNodePairs(false /* don't sort */)) {
414 pairs.add(new NodePair(pair));
415 if (!directed) {
416 pairs.add(new NodePair(pair).swap());
417 }
418 }
419 return pairs;
420 }
421
422 static public List<NodePair> buildNodePairs(List<Way> ways, boolean directed) {
423 ArrayList<NodePair> pairs = new ArrayList<NodePair>();
424 for (Way w: ways) {
425 pairs.addAll(buildNodePairs(w, directed));
426 }
427 return pairs;
428 }
429
430 static public List<NodePair> eliminateDuplicateNodePairs(List<NodePair> pairs) {
431 ArrayList<NodePair> cleaned = new ArrayList<NodePair>();
432 for(NodePair p: pairs) {
433 if (!cleaned.contains(p) && !cleaned.contains(p.swap())) {
434 cleaned.add(p);
435 }
436 }
437 return cleaned;
438 }
439
440 static public NodeGraph createDirectedGraphFromNodePairs(List<NodePair> pairs) {
441 NodeGraph graph = new NodeGraph();
442 for (NodePair pair: pairs) {
443 graph.add(pair);
444 }
445 return graph;
446 }
447
448 static public NodeGraph createDirectedGraphFromWays(Collection<Way> ways) {
449 NodeGraph graph = new NodeGraph();
450 for (Way w: ways) {
451 graph.add(buildNodePairs(w, true /* directed */));
452 }
453 return graph;
454 }
455
456 static public NodeGraph createUndirectedGraphFromNodeList(List<NodePair> pairs) {
457 NodeGraph graph = new NodeGraph();
458 for (NodePair pair: pairs) {
459 graph.add(pair);
460 graph.add(pair.swap());
461 }
462 return graph;
463 }
464
465 static public NodeGraph createUndirectedGraphFromNodeWays(Collection<Way> ways) {
466 NodeGraph graph = new NodeGraph();
467 for (Way w: ways) {
468 graph.add(buildNodePairs(w, false /* undirected */));
469 }
470 return graph;
471 }
472
473 private Set<NodePair> edges;
474 private int numUndirectedEges = 0;
475 private HashMap<Node, List<NodePair>> successors;
476 private HashMap<Node, List<NodePair>> predecessors;
477
478
479 protected void rememberSuccessor(NodePair pair) {
480 if (successors.containsKey(pair.getA())) {
481 if (!successors.get(pair.getA()).contains(pair)) {
482 successors.get(pair.getA()).add(pair);
483 }
484 } else {
485 ArrayList<NodePair> l = new ArrayList<NodePair>();
486 l.add(pair);
487 successors.put(pair.getA(), l);
488 }
489 }
490
491 protected void rememberPredecessors(NodePair pair) {
492 if (predecessors.containsKey(pair.getB())) {
493 if (!predecessors.get(pair.getB()).contains(pair)) {
494 predecessors.get(pair.getB()).add(pair);
495 }
496 } else {
497 ArrayList<NodePair> l = new ArrayList<NodePair>();
498 l.add(pair);
499 predecessors.put(pair.getB(), l);
500 }
501 }
502
503 protected boolean isTerminalNode(Node n) {
504 if (successors.get(n) == null) return false;
505 if (successors.get(n).size() != 1) return false;
506 if (predecessors.get(n) == null) return true;
507 if (predecessors.get(n).size() == 1) {
508 NodePair p1 = successors.get(n).iterator().next();
509 NodePair p2 = predecessors.get(n).iterator().next();
510 return p1.equals(p2.swap());
511 }
512 return false;
513 }
514
515 protected void prepare() {
516 Set<NodePair> undirectedEdges = new HashSet<NodePair>();
517 successors = new HashMap<Node, List<NodePair>>();
518 predecessors = new HashMap<Node, List<NodePair>>();
519
520 for (NodePair pair: edges) {
521 if (!undirectedEdges.contains(pair) && ! undirectedEdges.contains(pair.swap())) {
522 undirectedEdges.add(pair);
523 }
524 rememberSuccessor(pair);
525 rememberPredecessors(pair);
526 }
527 numUndirectedEges = undirectedEdges.size();
528 }
529
530 public NodeGraph() {
531 edges = new HashSet<NodePair>();
532 }
533
534 public void add(NodePair pair) {
535 if (!edges.contains(pair)) {
536 edges.add(pair);
537 }
538 }
539
540 public void add(List<NodePair> pairs) {
541 for (NodePair pair: pairs) {
542 add(pair);
543 }
544 }
545
546 protected Node getStartNode() {
547 Set<Node> nodes = getNodes();
548 for (Node n: nodes) {
549 if (successors.get(n) != null && successors.get(n).size() ==1)
550 return n;
551 }
552 return null;
553 }
554
555 protected Set<Node> getTerminalNodes() {
556 Set<Node> ret = new HashSet<Node>();
557 for (Node n: getNodes()) {
558 if (isTerminalNode(n)) {
559 ret.add(n);
560 }
561 }
562 return ret;
563 }
564
565 protected Set<Node> getNodes(Stack<NodePair> pairs) {
566 HashSet<Node> nodes = new HashSet<Node>();
567 for (NodePair pair: pairs) {
568 nodes.add(pair.getA());
569 nodes.add(pair.getB());
570 }
571 return nodes;
572 }
573
574 protected List<NodePair> getOutboundPairs(NodePair pair) {
575 return getOutboundPairs(pair.getB());
576 }
577
578 protected List<NodePair> getOutboundPairs(Node node) {
579 List<NodePair> l = successors.get(node);
580 return l == null ? Collections.EMPTY_LIST : l;
581 }
582
583 protected Set<Node> getNodes() {
584 Set<Node> nodes = new HashSet<Node>();
585 for (NodePair pair: edges) {
586 nodes.add(pair.getA());
587 nodes.add(pair.getB());
588 }
589 return nodes;
590 }
591
592 protected boolean isSpanningWay(Stack<NodePair> way) {
593 return numUndirectedEges == way.size();
594 }
595
596 protected List<Node> buildPathFromNodePairs(Stack<NodePair> path) {
597 LinkedList<Node> ret = new LinkedList<Node>();
598 for (NodePair pair: path) {
599 ret.add(pair.getA());
600 }
601 ret.add(path.peek().getB());
602 return ret;
603 }
604
605 /**
606 * Tries to find a spanning path starting from node <code>startNode</code>.
607 *
608 * Traverses the path in depth-first order.
609 *
610 * @param startNode the start node
611 * @return the spanning path; null, if no path is found
612 */
613 protected List<Node> buildSpanningPath(Node startNode) {
614 if (startNode == null)
615 return null;
616 Stack<NodePair> path = new Stack<NodePair>();
617 Stack<NodePair> nextPairs = new Stack<NodePair>();
618 nextPairs.addAll(getOutboundPairs(startNode));
619 while(!nextPairs.isEmpty()) {
620 NodePair cur= nextPairs.pop();
621 if (! path.contains(cur) && ! path.contains(cur.swap())) {
622 while(!path.isEmpty() && !path.peek().isPredecessorOf(cur)) {
623 path.pop();
624 }
625 path.push(cur);
626 if (isSpanningWay(path)) return buildPathFromNodePairs(path);
627 nextPairs.addAll(getOutboundPairs(path.peek()));
628 }
629 }
630 return null;
631 }
632
633 /**
634 * Tries to find a path through the graph which visits each edge (i.e.
635 * the segment of a way) exactly one.
636 *
637 * @return the path; null, if no path was found
638 */
639 public List<Node> buildSpanningPath() {
640 prepare();
641 // try to find a path from each "terminal node", i.e. from a
642 // node which is connected by exactly one undirected edges (or
643 // two directed edges in opposite direction) to the graph. A
644 // graph built up from way segments is likely to include such
645 // nodes, unless all ways are closed.
646 // In the worst case this loops over all nodes which is
647 // very slow for large ways.
648 //
649 Set<Node> nodes = getTerminalNodes();
650 nodes = nodes.isEmpty() ? getNodes() : nodes;
651 for (Node n: nodes) {
652 List<Node> path = buildSpanningPath(n);
653 if (path != null)
654 return path;
655 }
656 return null;
657 }
658 }
659}
Note: See TracBrowser for help on using the repository browser.