source: josm/trunk/src/org/openstreetmap/josm/actions/JoinAreasAction.java@ 8378

Last change on this file since 8378 was 8357, checked in by Don-vip, 9 years ago

fix some Findbugs violations

  • Property svn:eol-style set to native
File size: 54.4 KB
Line 
1// License: GPL. For details, see LICENSE file.
2package org.openstreetmap.josm.actions;
3
4import static org.openstreetmap.josm.tools.I18n.marktr;
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.HashMap;
14import java.util.HashSet;
15import java.util.LinkedHashSet;
16import java.util.LinkedList;
17import java.util.List;
18import java.util.Map;
19import java.util.Set;
20import java.util.TreeMap;
21
22import javax.swing.JOptionPane;
23
24import org.openstreetmap.josm.Main;
25import org.openstreetmap.josm.actions.ReverseWayAction.ReverseWayResult;
26import org.openstreetmap.josm.actions.SplitWayAction.SplitWayResult;
27import org.openstreetmap.josm.command.AddCommand;
28import org.openstreetmap.josm.command.ChangeCommand;
29import org.openstreetmap.josm.command.Command;
30import org.openstreetmap.josm.command.DeleteCommand;
31import org.openstreetmap.josm.command.SequenceCommand;
32import org.openstreetmap.josm.corrector.UserCancelException;
33import org.openstreetmap.josm.data.UndoRedoHandler;
34import org.openstreetmap.josm.data.coor.EastNorth;
35import org.openstreetmap.josm.data.osm.DataSet;
36import org.openstreetmap.josm.data.osm.Node;
37import org.openstreetmap.josm.data.osm.NodePositionComparator;
38import org.openstreetmap.josm.data.osm.OsmPrimitive;
39import org.openstreetmap.josm.data.osm.Relation;
40import org.openstreetmap.josm.data.osm.RelationMember;
41import org.openstreetmap.josm.data.osm.TagCollection;
42import org.openstreetmap.josm.data.osm.Way;
43import org.openstreetmap.josm.gui.Notification;
44import org.openstreetmap.josm.gui.conflict.tags.CombinePrimitiveResolverDialog;
45import org.openstreetmap.josm.tools.Geometry;
46import org.openstreetmap.josm.tools.Pair;
47import org.openstreetmap.josm.tools.Shortcut;
48
49/**
50 * Join Areas (i.e. closed ways and multipolygons).
51 * @since 2575
52 */
53public class JoinAreasAction extends JosmAction {
54 // This will be used to commit commands and unite them into one large command sequence at the end
55 private final LinkedList<Command> cmds = new LinkedList<>();
56 private int cmdsCount = 0;
57 private final transient List<Relation> addedRelations = new LinkedList<>();
58
59 /**
60 * This helper class describes join areas action result.
61 * @author viesturs
62 */
63 public static class JoinAreasResult {
64
65 public boolean hasChanges;
66
67 public List<Multipolygon> polygons;
68 }
69
70 public static class Multipolygon {
71 public Way outerWay;
72 public List<Way> innerWays;
73
74 public Multipolygon(Way way) {
75 outerWay = way;
76 innerWays = new ArrayList<>();
77 }
78 }
79
80 // HelperClass
81 // Saves a relation and a role an OsmPrimitve was part of until it was stripped from all relations
82 private static class RelationRole {
83 public final Relation rel;
84 public final String role;
85 public RelationRole(Relation rel, String role) {
86 this.rel = rel;
87 this.role = role;
88 }
89
90 @Override
91 public int hashCode() {
92 return rel.hashCode();
93 }
94
95 @Override
96 public boolean equals(Object other) {
97 if (!(other instanceof RelationRole)) return false;
98 RelationRole otherMember = (RelationRole) other;
99 return otherMember.role.equals(role) && otherMember.rel.equals(rel);
100 }
101 }
102
103
104 /**
105 * HelperClass - saves a way and the "inside" side.
106 *
107 * insideToTheLeft: if true left side is "in", false -right side is "in".
108 * Left and right are determined along the orientation of way.
109 */
110 public static class WayInPolygon {
111 public final Way way;
112 public boolean insideToTheRight;
113
114 public WayInPolygon(Way way, boolean insideRight) {
115 this.way = way;
116 this.insideToTheRight = insideRight;
117 }
118
119 @Override
120 public int hashCode() {
121 return way.hashCode();
122 }
123
124 @Override
125 public boolean equals(Object other) {
126 if (!(other instanceof WayInPolygon)) return false;
127 WayInPolygon otherMember = (WayInPolygon) other;
128 return otherMember.way.equals(this.way) && otherMember.insideToTheRight == this.insideToTheRight;
129 }
130 }
131
132 /**
133 * This helper class describes a polygon, assembled from several ways.
134 * @author viesturs
135 *
136 */
137 public static class AssembledPolygon {
138 public List<WayInPolygon> ways;
139
140 public AssembledPolygon(List<WayInPolygon> boundary) {
141 this.ways = boundary;
142 }
143
144 public List<Node> getNodes() {
145 List<Node> nodes = new ArrayList<>();
146 for (WayInPolygon way : this.ways) {
147 //do not add the last node as it will be repeated in the next way
148 if (way.insideToTheRight) {
149 for (int pos = 0; pos < way.way.getNodesCount() - 1; pos++) {
150 nodes.add(way.way.getNode(pos));
151 }
152 } else {
153 for (int pos = way.way.getNodesCount() - 1; pos > 0; pos--) {
154 nodes.add(way.way.getNode(pos));
155 }
156 }
157 }
158
159 return nodes;
160 }
161
162 /**
163 * Inverse inside and outside
164 */
165 public void reverse() {
166 for(WayInPolygon way: ways)
167 way.insideToTheRight = !way.insideToTheRight;
168 Collections.reverse(ways);
169 }
170 }
171
172 public static class AssembledMultipolygon {
173 public AssembledPolygon outerWay;
174 public List<AssembledPolygon> innerWays;
175
176 public AssembledMultipolygon(AssembledPolygon way) {
177 outerWay = way;
178 innerWays = new ArrayList<>();
179 }
180 }
181
182 /**
183 * This hepler class implements algorithm traversing trough connected ways.
184 * Assumes you are going in clockwise orientation.
185 * @author viesturs
186 */
187 private static class WayTraverser {
188
189 /** Set of {@link WayInPolygon} to be joined by walk algorithm */
190 private Set<WayInPolygon> availableWays;
191 /** Current state of walk algorithm */
192 private WayInPolygon lastWay;
193 /** Direction of current way */
194 private boolean lastWayReverse;
195
196 /** Constructor */
197 public WayTraverser(Collection<WayInPolygon> ways) {
198 availableWays = new HashSet<>(ways);
199 lastWay = null;
200 }
201
202 /**
203 * Remove ways from available ways
204 * @param ways Collection of WayInPolygon
205 */
206 public void removeWays(Collection<WayInPolygon> ways) {
207 availableWays.removeAll(ways);
208 }
209
210 /**
211 * Remove a single way from available ways
212 * @param way WayInPolygon
213 */
214 public void removeWay(WayInPolygon way) {
215 availableWays.remove(way);
216 }
217
218 /**
219 * Reset walk algorithm to a new start point
220 * @param way New start point
221 */
222 public void setStartWay(WayInPolygon way) {
223 lastWay = way;
224 lastWayReverse = !way.insideToTheRight;
225 }
226
227 /**
228 * Reset walk algorithm to a new start point.
229 * @return The new start point or null if no available way remains
230 */
231 public WayInPolygon startNewWay() {
232 if (availableWays.isEmpty()) {
233 lastWay = null;
234 } else {
235 lastWay = availableWays.iterator().next();
236 lastWayReverse = !lastWay.insideToTheRight;
237 }
238
239 return lastWay;
240 }
241
242 /**
243 * Walking through {@link WayInPolygon} segments, head node is the current position
244 * @return Head node
245 */
246 private Node getHeadNode() {
247 return !lastWayReverse ? lastWay.way.lastNode() : lastWay.way.firstNode();
248 }
249
250 /**
251 * Node just before head node.
252 * @return Previous node
253 */
254 private Node getPrevNode() {
255 return !lastWayReverse ? lastWay.way.getNode(lastWay.way.getNodesCount() - 2) : lastWay.way.getNode(1);
256 }
257
258 /**
259 * Oriented angle (N1N2, N1N3) in range [0; 2*Math.PI[
260 */
261 private static double getAngle(Node N1, Node N2, Node N3) {
262 EastNorth en1 = N1.getEastNorth();
263 EastNorth en2 = N2.getEastNorth();
264 EastNorth en3 = N3.getEastNorth();
265 double angle = Math.atan2(en3.getY() - en1.getY(), en3.getX() - en1.getX()) -
266 Math.atan2(en2.getY() - en1.getY(), en2.getX() - en1.getX());
267 while(angle >= 2*Math.PI)
268 angle -= 2*Math.PI;
269 while(angle < 0)
270 angle += 2*Math.PI;
271 return angle;
272 }
273
274 /**
275 * Get the next way creating a clockwise path, ensure it is the most right way. #7959
276 * @return The next way.
277 */
278 public WayInPolygon walk() {
279 Node headNode = getHeadNode();
280 Node prevNode = getPrevNode();
281
282 double headAngle = Math.atan2(headNode.getEastNorth().east() - prevNode.getEastNorth().east(),
283 headNode.getEastNorth().north() - prevNode.getEastNorth().north());
284 double bestAngle = 0;
285
286 //find best next way
287 WayInPolygon bestWay = null;
288 boolean bestWayReverse = false;
289
290 for (WayInPolygon way : availableWays) {
291 Node nextNode;
292
293 // Check for a connected way
294 if (way.way.firstNode().equals(headNode) && way.insideToTheRight) {
295 nextNode = way.way.getNode(1);
296 } else if (way.way.lastNode().equals(headNode) && !way.insideToTheRight) {
297 nextNode = way.way.getNode(way.way.getNodesCount() - 2);
298 } else {
299 continue;
300 }
301
302 if(nextNode == prevNode) {
303 // go back
304 lastWay = way;
305 lastWayReverse = !way.insideToTheRight;
306 return lastWay;
307 }
308
309 double angle = Math.atan2(nextNode.getEastNorth().east() - headNode.getEastNorth().east(),
310 nextNode.getEastNorth().north() - headNode.getEastNorth().north()) - headAngle;
311 if(angle > Math.PI)
312 angle -= 2*Math.PI;
313 if(angle <= -Math.PI)
314 angle += 2*Math.PI;
315
316 // Now we have a valid candidate way, is it better than the previous one ?
317 if (bestWay == null || angle > bestAngle) {
318 //the new way is better
319 bestWay = way;
320 bestWayReverse = !way.insideToTheRight;
321 bestAngle = angle;
322 }
323 }
324
325 lastWay = bestWay;
326 lastWayReverse = bestWayReverse;
327 return lastWay;
328 }
329
330 /**
331 * Search for an other way coming to the same head node at left side from last way. #9951
332 * @return left way or null if none found
333 */
334 public WayInPolygon leftComingWay() {
335 Node headNode = getHeadNode();
336 Node prevNode = getPrevNode();
337
338 WayInPolygon mostLeft = null; // most left way connected to head node
339 boolean comingToHead = false; // true if candidate come to head node
340 double angle = 2*Math.PI;
341
342 for (WayInPolygon candidateWay : availableWays) {
343 boolean candidateComingToHead;
344 Node candidatePrevNode;
345
346 if(candidateWay.way.firstNode().equals(headNode)) {
347 candidateComingToHead = !candidateWay.insideToTheRight;
348 candidatePrevNode = candidateWay.way.getNode(1);
349 } else if(candidateWay.way.lastNode().equals(headNode)) {
350 candidateComingToHead = candidateWay.insideToTheRight;
351 candidatePrevNode = candidateWay.way.getNode(candidateWay.way.getNodesCount() - 2);
352 } else
353 continue;
354 if(candidateWay.equals(lastWay) && candidateComingToHead)
355 continue;
356
357 double candidateAngle = getAngle(headNode, candidatePrevNode, prevNode);
358
359 if(mostLeft == null || candidateAngle < angle || (candidateAngle == angle && !candidateComingToHead)) {
360 // Candidate is most left
361 mostLeft = candidateWay;
362 comingToHead = candidateComingToHead;
363 angle = candidateAngle;
364 }
365 }
366
367 return comingToHead ? mostLeft : null;
368 }
369 }
370
371 /**
372 * Helper storage class for finding findOuterWays
373 * @author viesturs
374 */
375 static class PolygonLevel {
376 public final int level;
377 public final AssembledMultipolygon pol;
378
379 public PolygonLevel(AssembledMultipolygon pol, int level) {
380 this.pol = pol;
381 this.level = level;
382 }
383 }
384
385 /**
386 * Constructs a new {@code JoinAreasAction}.
387 */
388 public JoinAreasAction() {
389 super(tr("Join overlapping Areas"), "joinareas", tr("Joins areas that overlap each other"),
390 Shortcut.registerShortcut("tools:joinareas", tr("Tool: {0}", tr("Join overlapping Areas")),
391 KeyEvent.VK_J, Shortcut.SHIFT), true);
392 }
393
394 /**
395 * Gets called whenever the shortcut is pressed or the menu entry is selected.
396 * Checks whether the selected objects are suitable to join and joins them if so.
397 */
398 @Override
399 public void actionPerformed(ActionEvent e) {
400 join(Main.main.getCurrentDataSet().getSelectedWays());
401 }
402
403 /**
404 * Joins the given ways.
405 * @param ways Ways to join
406 * @since 7534
407 */
408 public void join(Collection<Way> ways) {
409 addedRelations.clear();
410
411 if (ways.isEmpty()) {
412 new Notification(
413 tr("Please select at least one closed way that should be joined."))
414 .setIcon(JOptionPane.INFORMATION_MESSAGE)
415 .show();
416 return;
417 }
418
419 List<Node> allNodes = new ArrayList<>();
420 for (Way way : ways) {
421 if (!way.isClosed()) {
422 new Notification(
423 tr("One of the selected ways is not closed and therefore cannot be joined."))
424 .setIcon(JOptionPane.INFORMATION_MESSAGE)
425 .show();
426 return;
427 }
428
429 allNodes.addAll(way.getNodes());
430 }
431
432 // TODO: Only display this warning when nodes outside dataSourceArea are deleted
433 boolean ok = Command.checkAndConfirmOutlyingOperation("joinarea", tr("Join area confirmation"),
434 trn("The selected way has nodes outside of the downloaded data region.",
435 "The selected ways have nodes outside of the downloaded data region.",
436 ways.size()) + "<br/>"
437 + tr("This can lead to nodes being deleted accidentally.") + "<br/>"
438 + tr("Are you really sure to continue?")
439 + tr("Please abort if you are not sure"),
440 tr("The selected area is incomplete. Continue?"),
441 allNodes, null);
442 if(!ok) return;
443
444 //analyze multipolygon relations and collect all areas
445 List<Multipolygon> areas = collectMultipolygons(ways);
446
447 if (areas == null)
448 //too complex multipolygon relations found
449 return;
450
451 if (!testJoin(areas)) {
452 new Notification(
453 tr("No intersection found. Nothing was changed."))
454 .setIcon(JOptionPane.INFORMATION_MESSAGE)
455 .show();
456 return;
457 }
458
459 if (!resolveTagConflicts(areas))
460 return;
461 //user canceled, do nothing.
462
463 try {
464 // see #11026 - Because <ways> is a dynamic filtered (on ways) of a filtered (on selected objects) collection,
465 // retrieve effective dataset before joining the ways (which affects the selection, thus, the <ways> collection)
466 // Dataset retrieving allows to call this code without relying on Main.getCurrentDataSet(), thus, on a mapview instance
467 DataSet ds = ways.iterator().next().getDataSet();
468
469 // Do the job of joining areas
470 JoinAreasResult result = joinAreas(areas);
471
472 if (result.hasChanges) {
473 // move tags from ways to newly created relations
474 // TODO: do we need to also move tags for the modified relations?
475 for (Relation r: addedRelations) {
476 cmds.addAll(CreateMultipolygonAction.removeTagsFromWaysIfNeeded(r));
477 }
478 commitCommands(tr("Move tags from ways to relations"));
479
480 List<Way> allWays = new ArrayList<>();
481 for (Multipolygon pol : result.polygons) {
482 allWays.add(pol.outerWay);
483 allWays.addAll(pol.innerWays);
484 }
485 if (ds != null) {
486 ds.setSelected(allWays);
487 Main.map.mapView.repaint();
488 }
489 } else {
490 new Notification(
491 tr("No intersection found. Nothing was changed."))
492 .setIcon(JOptionPane.INFORMATION_MESSAGE)
493 .show();
494 }
495 } catch (UserCancelException exception) {
496 //revert changes
497 //FIXME: this is dirty hack
498 makeCommitsOneAction(tr("Reverting changes"));
499 Main.main.undoRedo.undo();
500 Main.main.undoRedo.redoCommands.clear();
501 }
502 }
503
504 /**
505 * Tests if the areas have some intersections to join.
506 * @param areas Areas to test
507 * @return {@code true} if areas are joinable
508 */
509 private boolean testJoin(List<Multipolygon> areas) {
510 List<Way> allStartingWays = new ArrayList<>();
511
512 for (Multipolygon area : areas) {
513 allStartingWays.add(area.outerWay);
514 allStartingWays.addAll(area.innerWays);
515 }
516
517 //find intersection points
518 Set<Node> nodes = Geometry.addIntersections(allStartingWays, true, cmds);
519 return !nodes.isEmpty();
520 }
521
522 /**
523 * Will join two or more overlapping areas
524 * @param areas list of areas to join
525 * @return new area formed.
526 */
527 private JoinAreasResult joinAreas(List<Multipolygon> areas) throws UserCancelException {
528
529 JoinAreasResult result = new JoinAreasResult();
530 result.hasChanges = false;
531
532 List<Way> allStartingWays = new ArrayList<>();
533 List<Way> innerStartingWays = new ArrayList<>();
534 List<Way> outerStartingWays = new ArrayList<>();
535
536 for (Multipolygon area : areas) {
537 outerStartingWays.add(area.outerWay);
538 innerStartingWays.addAll(area.innerWays);
539 }
540
541 allStartingWays.addAll(innerStartingWays);
542 allStartingWays.addAll(outerStartingWays);
543
544 //first remove nodes in the same coordinate
545 boolean removedDuplicates = false;
546 removedDuplicates |= removeDuplicateNodes(allStartingWays);
547
548 if (removedDuplicates) {
549 result.hasChanges = true;
550 commitCommands(marktr("Removed duplicate nodes"));
551 }
552
553 //find intersection points
554 Set<Node> nodes = Geometry.addIntersections(allStartingWays, false, cmds);
555
556 //no intersections, return.
557 if (nodes.isEmpty())
558 return result;
559 commitCommands(marktr("Added node on all intersections"));
560
561 List<RelationRole> relations = new ArrayList<>();
562
563 // Remove ways from all relations so ways can be combined/split quietly
564 for (Way way : allStartingWays) {
565 relations.addAll(removeFromAllRelations(way));
566 }
567
568 // Don't warn now, because it will really look corrupted
569 boolean warnAboutRelations = !relations.isEmpty() && allStartingWays.size() > 1;
570
571 List<WayInPolygon> preparedWays = new ArrayList<>();
572
573 for (Way way : outerStartingWays) {
574 List<Way> splitWays = splitWayOnNodes(way, nodes);
575 preparedWays.addAll(markWayInsideSide(splitWays, false));
576 }
577
578 for (Way way : innerStartingWays) {
579 List<Way> splitWays = splitWayOnNodes(way, nodes);
580 preparedWays.addAll(markWayInsideSide(splitWays, true));
581 }
582
583 // Find boundary ways
584 List<Way> discardedWays = new ArrayList<>();
585 List<AssembledPolygon> bounadries = findBoundaryPolygons(preparedWays, discardedWays);
586
587 //find polygons
588 List<AssembledMultipolygon> preparedPolygons = findPolygons(bounadries);
589
590
591 //assemble final polygons
592 List<Multipolygon> polygons = new ArrayList<>();
593 Set<Relation> relationsToDelete = new LinkedHashSet<>();
594
595 for (AssembledMultipolygon pol : preparedPolygons) {
596
597 //create the new ways
598 Multipolygon resultPol = joinPolygon(pol);
599
600 //create multipolygon relation, if necessary.
601 RelationRole ownMultipolygonRelation = addOwnMultigonRelation(resultPol.innerWays, resultPol.outerWay);
602
603 //add back the original relations, merged with our new multipolygon relation
604 fixRelations(relations, resultPol.outerWay, ownMultipolygonRelation, relationsToDelete);
605
606 //strip tags from inner ways
607 //TODO: preserve tags on existing inner ways
608 stripTags(resultPol.innerWays);
609
610 polygons.add(resultPol);
611 }
612
613 commitCommands(marktr("Assemble new polygons"));
614
615 for(Relation rel: relationsToDelete) {
616 cmds.add(new DeleteCommand(rel));
617 }
618
619 commitCommands(marktr("Delete relations"));
620
621 // Delete the discarded inner ways
622 if (!discardedWays.isEmpty()) {
623 Command deleteCmd = DeleteCommand.delete(Main.main.getEditLayer(), discardedWays, true);
624 if (deleteCmd != null) {
625 cmds.add(deleteCmd);
626 commitCommands(marktr("Delete Ways that are not part of an inner multipolygon"));
627 }
628 }
629
630 makeCommitsOneAction(marktr("Joined overlapping areas"));
631
632 if (warnAboutRelations) {
633 new Notification(
634 tr("Some of the ways were part of relations that have been modified.<br>Please verify no errors have been introduced."))
635 .setIcon(JOptionPane.INFORMATION_MESSAGE)
636 .setDuration(Notification.TIME_LONG)
637 .show();
638 }
639
640 result.hasChanges = true;
641 result.polygons = polygons;
642 return result;
643 }
644
645 /**
646 * Checks if tags of two given ways differ, and presents the user a dialog to solve conflicts
647 * @param polygons ways to check
648 * @return {@code true} if all conflicts are resolved, {@code false} if conflicts remain.
649 */
650 private boolean resolveTagConflicts(List<Multipolygon> polygons) {
651
652 List<Way> ways = new ArrayList<>();
653
654 for (Multipolygon pol : polygons) {
655 ways.add(pol.outerWay);
656 ways.addAll(pol.innerWays);
657 }
658
659 if (ways.size() < 2) {
660 return true;
661 }
662
663 TagCollection wayTags = TagCollection.unionOfAllPrimitives(ways);
664 try {
665 cmds.addAll(CombinePrimitiveResolverDialog.launchIfNecessary(wayTags, ways, ways));
666 commitCommands(marktr("Fix tag conflicts"));
667 return true;
668 } catch (UserCancelException ex) {
669 return false;
670 }
671 }
672
673 /**
674 * This method removes duplicate points (if any) from the input way.
675 * @param ways the ways to process
676 * @return {@code true} if any changes where made
677 */
678 private boolean removeDuplicateNodes(List<Way> ways) {
679 //TODO: maybe join nodes with JoinNodesAction, rather than reconnect the ways.
680
681 Map<Node, Node> nodeMap = new TreeMap<>(new NodePositionComparator());
682 int totalNodesRemoved = 0;
683
684 for (Way way : ways) {
685 if (way.getNodes().size() < 2) {
686 continue;
687 }
688
689 int nodesRemoved = 0;
690 List<Node> newNodes = new ArrayList<>();
691 Node prevNode = null;
692
693 for (Node node : way.getNodes()) {
694 if (!nodeMap.containsKey(node)) {
695 //new node
696 nodeMap.put(node, node);
697
698 //avoid duplicate nodes
699 if (prevNode != node) {
700 newNodes.add(node);
701 } else {
702 nodesRemoved ++;
703 }
704 } else {
705 //node with same coordinates already exists, substitute with existing node
706 Node representator = nodeMap.get(node);
707
708 if (representator != node) {
709 nodesRemoved ++;
710 }
711
712 //avoid duplicate node
713 if (prevNode != representator) {
714 newNodes.add(representator);
715 }
716 }
717 prevNode = node;
718 }
719
720 if (nodesRemoved > 0) {
721
722 if (newNodes.size() == 1) { //all nodes in the same coordinate - add one more node, to have closed way.
723 newNodes.add(newNodes.get(0));
724 }
725
726 Way newWay=new Way(way);
727 newWay.setNodes(newNodes);
728 cmds.add(new ChangeCommand(way, newWay));
729 totalNodesRemoved += nodesRemoved;
730 }
731 }
732
733 return totalNodesRemoved > 0;
734 }
735
736 /**
737 * Commits the command list with a description
738 * @param description The description of what the commands do
739 */
740 private void commitCommands(String description) {
741 switch(cmds.size()) {
742 case 0:
743 return;
744 case 1:
745 Main.main.undoRedo.add(cmds.getFirst());
746 break;
747 default:
748 Command c = new SequenceCommand(tr(description), cmds);
749 Main.main.undoRedo.add(c);
750 break;
751 }
752
753 cmds.clear();
754 cmdsCount++;
755 }
756
757 /**
758 * This method analyzes the way and assigns each part what direction polygon "inside" is.
759 * @param parts the split parts of the way
760 * @param isInner - if true, reverts the direction (for multipolygon islands)
761 * @return list of parts, marked with the inside orientation.
762 */
763 private List<WayInPolygon> markWayInsideSide(List<Way> parts, boolean isInner) {
764
765 List<WayInPolygon> result = new ArrayList<>();
766
767 //prepare next map
768 Map<Way, Way> nextWayMap = new HashMap<>();
769
770 for (int pos = 0; pos < parts.size(); pos ++) {
771
772 if (!parts.get(pos).lastNode().equals(parts.get((pos + 1) % parts.size()).firstNode()))
773 throw new RuntimeException("Way not circular");
774
775 nextWayMap.put(parts.get(pos), parts.get((pos + 1) % parts.size()));
776 }
777
778 //find the node with minimum y - it's guaranteed to be outer. (What about the south pole?)
779 Way topWay = null;
780 Node topNode = null;
781 int topIndex = 0;
782 double minY = Double.POSITIVE_INFINITY;
783
784 for (Way way : parts) {
785 for (int pos = 0; pos < way.getNodesCount(); pos ++) {
786 Node node = way.getNode(pos);
787
788 if (node.getEastNorth().getY() < minY) {
789 minY = node.getEastNorth().getY();
790 topWay = way;
791 topNode = node;
792 topIndex = pos;
793 }
794 }
795 }
796
797 //get the upper way and it's orientation.
798
799 boolean wayClockwise; // orientation of the top way.
800
801 if (topNode.equals(topWay.firstNode()) || topNode.equals(topWay.lastNode())) {
802 Node headNode = null; // the node at junction
803 Node prevNode = null; // last node from previous path
804 wayClockwise = false;
805
806 //node is in split point - find the outermost way from this point
807
808 headNode = topNode;
809 //make a fake node that is downwards from head node (smaller Y). It will be a division point between paths.
810 prevNode = new Node(new EastNorth(headNode.getEastNorth().getX(), headNode.getEastNorth().getY() - 1e5));
811
812 topWay = null;
813 wayClockwise = false;
814 Node bestWayNextNode = null;
815
816 for (Way way : parts) {
817 if (way.firstNode().equals(headNode)) {
818 Node nextNode = way.getNode(1);
819
820 if (topWay == null || !Geometry.isToTheRightSideOfLine(prevNode, headNode, bestWayNextNode, nextNode)) {
821 //the new way is better
822 topWay = way;
823 wayClockwise = true;
824 bestWayNextNode = nextNode;
825 }
826 }
827
828 if (way.lastNode().equals(headNode)) {
829 //end adjacent to headNode
830 Node nextNode = way.getNode(way.getNodesCount() - 2);
831
832 if (topWay == null || !Geometry.isToTheRightSideOfLine(prevNode, headNode, bestWayNextNode, nextNode)) {
833 //the new way is better
834 topWay = way;
835 wayClockwise = false;
836 bestWayNextNode = nextNode;
837 }
838 }
839 }
840 } else {
841 //node is inside way - pick the clockwise going end.
842 Node prev = topWay.getNode(topIndex - 1);
843 Node next = topWay.getNode(topIndex + 1);
844
845 //there will be no parallel segments in the middle of way, so all fine.
846 wayClockwise = Geometry.angleIsClockwise(prev, topNode, next);
847 }
848
849 Way curWay = topWay;
850 boolean curWayInsideToTheRight = wayClockwise ^ isInner;
851
852 //iterate till full circle is reached
853 while (true) {
854
855 //add cur way
856 WayInPolygon resultWay = new WayInPolygon(curWay, curWayInsideToTheRight);
857 result.add(resultWay);
858
859 //process next way
860 Way nextWay = nextWayMap.get(curWay);
861 Node prevNode = curWay.getNode(curWay.getNodesCount() - 2);
862 Node headNode = curWay.lastNode();
863 Node nextNode = nextWay.getNode(1);
864
865 if (nextWay == topWay) {
866 //full loop traversed - all done.
867 break;
868 }
869
870 //find intersecting segments
871 // the intersections will look like this:
872 //
873 // ^
874 // |
875 // X wayBNode
876 // |
877 // wayB |
878 // |
879 // curWay | nextWay
880 //----X----------------->X----------------------X---->
881 // prevNode ^headNode nextNode
882 // |
883 // |
884 // wayA |
885 // |
886 // X wayANode
887 // |
888
889 int intersectionCount = 0;
890
891 for (Way wayA : parts) {
892
893 if (wayA == curWay) {
894 continue;
895 }
896
897 if (wayA.lastNode().equals(headNode)) {
898
899 Way wayB = nextWayMap.get(wayA);
900
901 //test if wayA is opposite wayB relative to curWay and nextWay
902
903 Node wayANode = wayA.getNode(wayA.getNodesCount() - 2);
904 Node wayBNode = wayB.getNode(1);
905
906 boolean wayAToTheRight = Geometry.isToTheRightSideOfLine(prevNode, headNode, nextNode, wayANode);
907 boolean wayBToTheRight = Geometry.isToTheRightSideOfLine(prevNode, headNode, nextNode, wayBNode);
908
909 if (wayAToTheRight != wayBToTheRight) {
910 intersectionCount ++;
911 }
912 }
913 }
914
915 //if odd number of crossings, invert orientation
916 if (intersectionCount % 2 != 0) {
917 curWayInsideToTheRight = !curWayInsideToTheRight;
918 }
919
920 curWay = nextWay;
921 }
922
923 return result;
924 }
925
926 /**
927 * This is a method splits way into smaller parts, using the prepared nodes list as split points.
928 * Uses {@link SplitWayAction#splitWay} for the heavy lifting.
929 * @return list of split ways (or original ways if no splitting is done).
930 */
931 private List<Way> splitWayOnNodes(Way way, Set<Node> nodes) {
932
933 List<Way> result = new ArrayList<>();
934 List<List<Node>> chunks = buildNodeChunks(way, nodes);
935
936 if (chunks.size() > 1) {
937 SplitWayResult split = SplitWayAction.splitWay(getEditLayer(), way, chunks, Collections.<OsmPrimitive>emptyList());
938
939 //execute the command, we need the results
940 cmds.add(split.getCommand());
941 commitCommands(marktr("Split ways into fragments"));
942
943 result.add(split.getOriginalWay());
944 result.addAll(split.getNewWays());
945 } else {
946 //nothing to split
947 result.add(way);
948 }
949
950 return result;
951 }
952
953 /**
954 * Simple chunking version. Does not care about circular ways and result being
955 * proper, we will glue it all back together later on.
956 * @param way the way to chunk
957 * @param splitNodes the places where to cut.
958 * @return list of node paths to produce.
959 */
960 private List<List<Node>> buildNodeChunks(Way way, Collection<Node> splitNodes) {
961 List<List<Node>> result = new ArrayList<>();
962 List<Node> curList = new ArrayList<>();
963
964 for (Node node : way.getNodes()) {
965 curList.add(node);
966 if (curList.size() > 1 && splitNodes.contains(node)) {
967 result.add(curList);
968 curList = new ArrayList<>();
969 curList.add(node);
970 }
971 }
972
973 if (curList.size() > 1) {
974 result.add(curList);
975 }
976
977 return result;
978 }
979
980 /**
981 * This method finds which ways are outer and which are inner.
982 * @param boundaries list of joined boundaries to search in
983 * @return outer ways
984 */
985 private List<AssembledMultipolygon> findPolygons(Collection<AssembledPolygon> boundaries) {
986
987 List<PolygonLevel> list = findOuterWaysImpl(0, boundaries);
988 List<AssembledMultipolygon> result = new ArrayList<>();
989
990 //take every other level
991 for (PolygonLevel pol : list) {
992 if (pol.level % 2 == 0) {
993 result.add(pol.pol);
994 }
995 }
996
997 return result;
998 }
999
1000 /**
1001 * Collects outer way and corresponding inner ways from all boundaries.
1002 * @param level depth level
1003 * @param boundaryWays
1004 * @return the outermostWay.
1005 */
1006 private List<PolygonLevel> findOuterWaysImpl(int level, Collection<AssembledPolygon> boundaryWays) {
1007
1008 //TODO: bad performance for deep nestings...
1009 List<PolygonLevel> result = new ArrayList<>();
1010
1011 for (AssembledPolygon outerWay : boundaryWays) {
1012
1013 boolean outerGood = true;
1014 List<AssembledPolygon> innerCandidates = new ArrayList<>();
1015
1016 for (AssembledPolygon innerWay : boundaryWays) {
1017 if (innerWay == outerWay) {
1018 continue;
1019 }
1020
1021 if (wayInsideWay(outerWay, innerWay)) {
1022 outerGood = false;
1023 break;
1024 } else if (wayInsideWay(innerWay, outerWay)) {
1025 innerCandidates.add(innerWay);
1026 }
1027 }
1028
1029 if (!outerGood) {
1030 continue;
1031 }
1032
1033 //add new outer polygon
1034 AssembledMultipolygon pol = new AssembledMultipolygon(outerWay);
1035 PolygonLevel polLev = new PolygonLevel(pol, level);
1036
1037 //process inner ways
1038 if (!innerCandidates.isEmpty()) {
1039 List<PolygonLevel> innerList = findOuterWaysImpl(level + 1, innerCandidates);
1040 result.addAll(innerList);
1041
1042 for (PolygonLevel pl : innerList) {
1043 if (pl.level == level + 1) {
1044 pol.innerWays.add(pl.pol.outerWay);
1045 }
1046 }
1047 }
1048
1049 result.add(polLev);
1050 }
1051
1052 return result;
1053 }
1054
1055 /**
1056 * Finds all ways that form inner or outer boundaries.
1057 * @param multigonWays A list of (splitted) ways that form a multigon and share common end nodes on intersections.
1058 * @param discardedResult this list is filled with ways that are to be discarded
1059 * @return A list of ways that form the outer and inner boundaries of the multigon.
1060 */
1061 public static List<AssembledPolygon> findBoundaryPolygons(Collection<WayInPolygon> multigonWays,
1062 List<Way> discardedResult) {
1063 //first find all discardable ways, by getting outer shells.
1064 //this will produce incorrect boundaries in some cases, but second pass will fix it.
1065 List<WayInPolygon> discardedWays = new ArrayList<>();
1066
1067 // In multigonWays collection, some way are just a point (i.e. way like nodeA-nodeA)
1068 // This seems to appear when is apply over invalid way like #9911 test-case
1069 // Remove all of these way to make the next work.
1070 List<WayInPolygon> cleanMultigonWays = new ArrayList<>();
1071 for(WayInPolygon way: multigonWays)
1072 if(way.way.getNodesCount() == 2 && way.way.firstNode() == way.way.lastNode())
1073 discardedWays.add(way);
1074 else
1075 cleanMultigonWays.add(way);
1076
1077 WayTraverser traverser = new WayTraverser(cleanMultigonWays);
1078 List<AssembledPolygon> result = new ArrayList<>();
1079
1080 WayInPolygon startWay;
1081 while((startWay = traverser.startNewWay()) != null) {
1082 List<WayInPolygon> path = new ArrayList<>();
1083 List<WayInPolygon> startWays = new ArrayList<>();
1084 path.add(startWay);
1085 while(true) {
1086 WayInPolygon leftComing;
1087 while((leftComing = traverser.leftComingWay()) != null) {
1088 if(startWays.contains(leftComing))
1089 break;
1090 // Need restart traverser walk
1091 path.clear();
1092 path.add(leftComing);
1093 traverser.setStartWay(leftComing);
1094 startWays.add(leftComing);
1095 break;
1096 }
1097 WayInPolygon nextWay = traverser.walk();
1098 if(nextWay == null)
1099 throw new RuntimeException("Join areas internal error.");
1100 if(path.get(0) == nextWay) {
1101 // path is closed -> stop here
1102 AssembledPolygon ring = new AssembledPolygon(path);
1103 if(ring.getNodes().size() <= 2) {
1104 // Invalid ring (2 nodes) -> remove
1105 traverser.removeWays(path);
1106 for(WayInPolygon way: path)
1107 discardedResult.add(way.way);
1108 } else {
1109 // Close ring -> add
1110 result.add(ring);
1111 traverser.removeWays(path);
1112 }
1113 break;
1114 }
1115 if(path.contains(nextWay)) {
1116 // Inner loop -> remove
1117 int index = path.indexOf(nextWay);
1118 while(path.size() > index) {
1119 WayInPolygon currentWay = path.get(index);
1120 discardedResult.add(currentWay.way);
1121 traverser.removeWay(currentWay);
1122 path.remove(index);
1123 }
1124 traverser.setStartWay(path.get(index-1));
1125 } else {
1126 path.add(nextWay);
1127 }
1128 }
1129 }
1130
1131 return fixTouchingPolygons(result);
1132 }
1133
1134 /**
1135 * This method checks if polygons have several touching parts and splits them in several polygons.
1136 * @param polygons the polygons to process.
1137 */
1138 public static List<AssembledPolygon> fixTouchingPolygons(List<AssembledPolygon> polygons) {
1139 List<AssembledPolygon> newPolygons = new ArrayList<>();
1140
1141 for (AssembledPolygon ring : polygons) {
1142 ring.reverse();
1143 WayTraverser traverser = new WayTraverser(ring.ways);
1144 WayInPolygon startWay;
1145
1146 while((startWay = traverser.startNewWay()) != null) {
1147 List<WayInPolygon> simpleRingWays = new ArrayList<>();
1148 simpleRingWays.add(startWay);
1149 WayInPolygon nextWay;
1150 while((nextWay = traverser.walk()) != startWay) {
1151 if(nextWay == null)
1152 throw new RuntimeException("Join areas internal error.");
1153 simpleRingWays.add(nextWay);
1154 }
1155 traverser.removeWays(simpleRingWays);
1156 AssembledPolygon simpleRing = new AssembledPolygon(simpleRingWays);
1157 simpleRing.reverse();
1158 newPolygons.add(simpleRing);
1159 }
1160 }
1161
1162 return newPolygons;
1163 }
1164
1165 /**
1166 * Tests if way is inside other way
1167 * @param outside outer polygon description
1168 * @param inside inner polygon description
1169 * @return {@code true} if inner is inside outer
1170 */
1171 public static boolean wayInsideWay(AssembledPolygon inside, AssembledPolygon outside) {
1172 Set<Node> outsideNodes = new HashSet<>(outside.getNodes());
1173 List<Node> insideNodes = inside.getNodes();
1174
1175 for (Node insideNode : insideNodes) {
1176
1177 if (!outsideNodes.contains(insideNode))
1178 //simply test the one node
1179 return Geometry.nodeInsidePolygon(insideNode, outside.getNodes());
1180 }
1181
1182 //all nodes shared.
1183 return false;
1184 }
1185
1186 /**
1187 * Joins the lists of ways.
1188 * @param polygon The list of outer ways that belong to that multigon.
1189 * @return The newly created outer way
1190 */
1191 private Multipolygon joinPolygon(AssembledMultipolygon polygon) throws UserCancelException {
1192 Multipolygon result = new Multipolygon(joinWays(polygon.outerWay.ways));
1193
1194 for (AssembledPolygon pol : polygon.innerWays) {
1195 result.innerWays.add(joinWays(pol.ways));
1196 }
1197
1198 return result;
1199 }
1200
1201 /**
1202 * Joins the outer ways and deletes all short ways that can't be part of a multipolygon anyway.
1203 * @param ways The list of outer ways that belong to that multigon.
1204 * @return The newly created outer way
1205 */
1206 private Way joinWays(List<WayInPolygon> ways) throws UserCancelException {
1207
1208 //leave original orientation, if all paths are reverse.
1209 boolean allReverse = true;
1210 for (WayInPolygon way : ways) {
1211 allReverse &= !way.insideToTheRight;
1212 }
1213
1214 if (allReverse) {
1215 for (WayInPolygon way : ways) {
1216 way.insideToTheRight = !way.insideToTheRight;
1217 }
1218 }
1219
1220 Way joinedWay = joinOrientedWays(ways);
1221
1222 //should not happen
1223 if (joinedWay == null || !joinedWay.isClosed())
1224 throw new RuntimeException("Join areas internal error.");
1225
1226 return joinedWay;
1227 }
1228
1229 /**
1230 * Joins a list of ways (using CombineWayAction and ReverseWayAction as specified in WayInPath)
1231 * @param ways The list of ways to join and reverse
1232 * @return The newly created way
1233 */
1234 private Way joinOrientedWays(List<WayInPolygon> ways) throws UserCancelException{
1235 if (ways.size() < 2)
1236 return ways.get(0).way;
1237
1238 // This will turn ways so all of them point in the same direction and CombineAction won't bug
1239 // the user about this.
1240
1241 //TODO: ReverseWay and Combine way are really slow and we use them a lot here. This slows down large joins.
1242 List<Way> actionWays = new ArrayList<>(ways.size());
1243
1244 for (WayInPolygon way : ways) {
1245 actionWays.add(way.way);
1246
1247 if (!way.insideToTheRight) {
1248 ReverseWayResult res = ReverseWayAction.reverseWay(way.way);
1249 Main.main.undoRedo.add(res.getReverseCommand());
1250 cmdsCount++;
1251 }
1252 }
1253
1254 Pair<Way, Command> result = CombineWayAction.combineWaysWorker(actionWays);
1255
1256 Main.main.undoRedo.add(result.b);
1257 cmdsCount ++;
1258
1259 return result.a;
1260 }
1261
1262 /**
1263 * This method analyzes multipolygon relationships of given ways and collects addition inner ways to consider.
1264 * @param selectedWays the selected ways
1265 * @return list of polygons, or null if too complex relation encountered.
1266 */
1267 private List<Multipolygon> collectMultipolygons(Collection<Way> selectedWays) {
1268
1269 List<Multipolygon> result = new ArrayList<>();
1270
1271 //prepare the lists, to minimize memory allocation.
1272 List<Way> outerWays = new ArrayList<>();
1273 List<Way> innerWays = new ArrayList<>();
1274
1275 Set<Way> processedOuterWays = new LinkedHashSet<>();
1276 Set<Way> processedInnerWays = new LinkedHashSet<>();
1277
1278 for (Relation r : OsmPrimitive.getParentRelations(selectedWays)) {
1279 if (r.isDeleted() || !r.isMultipolygon()) {
1280 continue;
1281 }
1282
1283 boolean hasKnownOuter = false;
1284 outerWays.clear();
1285 innerWays.clear();
1286
1287 for (RelationMember rm : r.getMembers()) {
1288 if ("outer".equalsIgnoreCase(rm.getRole())) {
1289 outerWays.add(rm.getWay());
1290 hasKnownOuter |= selectedWays.contains(rm.getWay());
1291 } else if ("inner".equalsIgnoreCase(rm.getRole())) {
1292 innerWays.add(rm.getWay());
1293 }
1294 }
1295
1296 if (!hasKnownOuter) {
1297 continue;
1298 }
1299
1300 if (outerWays.size() > 1) {
1301 new Notification(
1302 tr("Sorry. Cannot handle multipolygon relations with multiple outer ways."))
1303 .setIcon(JOptionPane.INFORMATION_MESSAGE)
1304 .show();
1305 return null;
1306 }
1307
1308 Way outerWay = outerWays.get(0);
1309
1310 //retain only selected inner ways
1311 innerWays.retainAll(selectedWays);
1312
1313 if (processedOuterWays.contains(outerWay)) {
1314 new Notification(
1315 tr("Sorry. Cannot handle way that is outer in multiple multipolygon relations."))
1316 .setIcon(JOptionPane.INFORMATION_MESSAGE)
1317 .show();
1318 return null;
1319 }
1320
1321 if (processedInnerWays.contains(outerWay)) {
1322 new Notification(
1323 tr("Sorry. Cannot handle way that is both inner and outer in multipolygon relations."))
1324 .setIcon(JOptionPane.INFORMATION_MESSAGE)
1325 .show();
1326 return null;
1327 }
1328
1329 for (Way way :innerWays)
1330 {
1331 if (processedOuterWays.contains(way)) {
1332 new Notification(
1333 tr("Sorry. Cannot handle way that is both inner and outer in multipolygon relations."))
1334 .setIcon(JOptionPane.INFORMATION_MESSAGE)
1335 .show();
1336 return null;
1337 }
1338
1339 if (processedInnerWays.contains(way)) {
1340 new Notification(
1341 tr("Sorry. Cannot handle way that is inner in multiple multipolygon relations."))
1342 .setIcon(JOptionPane.INFORMATION_MESSAGE)
1343 .show();
1344 return null;
1345 }
1346 }
1347
1348 processedOuterWays.add(outerWay);
1349 processedInnerWays.addAll(innerWays);
1350
1351 Multipolygon pol = new Multipolygon(outerWay);
1352 pol.innerWays.addAll(innerWays);
1353
1354 result.add(pol);
1355 }
1356
1357 //add remaining ways, not in relations
1358 for (Way way : selectedWays) {
1359 if (processedOuterWays.contains(way) || processedInnerWays.contains(way)) {
1360 continue;
1361 }
1362
1363 result.add(new Multipolygon(way));
1364 }
1365
1366 return result;
1367 }
1368
1369 /**
1370 * Will add own multipolygon relation to the "previously existing" relations. Fixup is done by fixRelations
1371 * @param inner List of already closed inner ways
1372 * @param outer The outer way
1373 * @return The list of relation with roles to add own relation to
1374 */
1375 private RelationRole addOwnMultigonRelation(Collection<Way> inner, Way outer) {
1376 if (inner.isEmpty()) return null;
1377 // Create new multipolygon relation and add all inner ways to it
1378 Relation newRel = new Relation();
1379 newRel.put("type", "multipolygon");
1380 for (Way w : inner) {
1381 newRel.addMember(new RelationMember("inner", w));
1382 }
1383 cmds.add(new AddCommand(newRel));
1384 addedRelations.add(newRel);
1385
1386 // We don't add outer to the relation because it will be handed to fixRelations()
1387 // which will then do the remaining work.
1388 return new RelationRole(newRel, "outer");
1389 }
1390
1391 /**
1392 * Removes a given OsmPrimitive from all relations.
1393 * @param osm Element to remove from all relations
1394 * @return List of relations with roles the primitives was part of
1395 */
1396 private List<RelationRole> removeFromAllRelations(OsmPrimitive osm) {
1397 List<RelationRole> result = new ArrayList<>();
1398
1399 for (Relation r : Main.main.getCurrentDataSet().getRelations()) {
1400 if (r.isDeleted()) {
1401 continue;
1402 }
1403 for (RelationMember rm : r.getMembers()) {
1404 if (rm.getMember() != osm) {
1405 continue;
1406 }
1407
1408 Relation newRel = new Relation(r);
1409 List<RelationMember> members = newRel.getMembers();
1410 members.remove(rm);
1411 newRel.setMembers(members);
1412
1413 cmds.add(new ChangeCommand(r, newRel));
1414 RelationRole saverel = new RelationRole(r, rm.getRole());
1415 if (!result.contains(saverel)) {
1416 result.add(saverel);
1417 }
1418 break;
1419 }
1420 }
1421
1422 commitCommands(marktr("Removed Element from Relations"));
1423 return result;
1424 }
1425
1426 /**
1427 * Adds the previously removed relations again to the outer way. If there are multiple multipolygon
1428 * relations where the joined areas were in "outer" role a new relation is created instead with all
1429 * members of both. This function depends on multigon relations to be valid already, it won't fix them.
1430 * @param rels List of relations with roles the (original) ways were part of
1431 * @param outer The newly created outer area/way
1432 * @param ownMultipol elements to directly add as outer
1433 * @param relationsToDelete set of relations to delete.
1434 */
1435 private void fixRelations(List<RelationRole> rels, Way outer, RelationRole ownMultipol, Set<Relation> relationsToDelete) {
1436 List<RelationRole> multiouters = new ArrayList<>();
1437
1438 if (ownMultipol != null) {
1439 multiouters.add(ownMultipol);
1440 }
1441
1442 for (RelationRole r : rels) {
1443 if (r.rel.isMultipolygon() && "outer".equalsIgnoreCase(r.role)) {
1444 multiouters.add(r);
1445 continue;
1446 }
1447 // Add it back!
1448 Relation newRel = new Relation(r.rel);
1449 newRel.addMember(new RelationMember(r.role, outer));
1450 cmds.add(new ChangeCommand(r.rel, newRel));
1451 }
1452
1453 Relation newRel;
1454 switch (multiouters.size()) {
1455 case 0:
1456 return;
1457 case 1:
1458 // Found only one to be part of a multipolygon relation, so just add it back as well
1459 newRel = new Relation(multiouters.get(0).rel);
1460 newRel.addMember(new RelationMember(multiouters.get(0).role, outer));
1461 cmds.add(new ChangeCommand(multiouters.get(0).rel, newRel));
1462 return;
1463 default:
1464 // Create a new relation with all previous members and (Way)outer as outer.
1465 newRel = new Relation();
1466 for (RelationRole r : multiouters) {
1467 // Add members
1468 for (RelationMember rm : r.rel.getMembers())
1469 if (!newRel.getMembers().contains(rm)) {
1470 newRel.addMember(rm);
1471 }
1472 // Add tags
1473 for (String key : r.rel.keySet()) {
1474 newRel.put(key, r.rel.get(key));
1475 }
1476 // Delete old relation
1477 relationsToDelete.add(r.rel);
1478 }
1479 newRel.addMember(new RelationMember("outer", outer));
1480 cmds.add(new AddCommand(newRel));
1481 }
1482 }
1483
1484 /**
1485 * Remove all tags from the all the way
1486 * @param ways The List of Ways to remove all tags from
1487 */
1488 private void stripTags(Collection<Way> ways) {
1489 for (Way w : ways) {
1490 stripTags(w);
1491 }
1492 /* I18N: current action printed in status display */
1493 commitCommands(marktr("Remove tags from inner ways"));
1494 }
1495
1496 /**
1497 * Remove all tags from the way
1498 * @param x The Way to remove all tags from
1499 */
1500 private void stripTags(Way x) {
1501 Way y = new Way(x);
1502 for (String key : x.keySet()) {
1503 y.remove(key);
1504 }
1505 cmds.add(new ChangeCommand(x, y));
1506 }
1507
1508 /**
1509 * Takes the last cmdsCount actions back and combines them into a single action
1510 * (for when the user wants to undo the join action)
1511 * @param message The commit message to display
1512 */
1513 private void makeCommitsOneAction(String message) {
1514 UndoRedoHandler ur = Main.main.undoRedo;
1515 cmds.clear();
1516 int i = Math.max(ur.commands.size() - cmdsCount, 0);
1517 for (; i < ur.commands.size(); i++) {
1518 cmds.add(ur.commands.get(i));
1519 }
1520
1521 for (i = 0; i < cmds.size(); i++) {
1522 ur.undo();
1523 }
1524
1525 commitCommands(message == null ? marktr("Join Areas Function") : message);
1526 cmdsCount = 0;
1527 }
1528
1529 @Override
1530 protected void updateEnabledState() {
1531 if (getCurrentDataSet() == null) {
1532 setEnabled(false);
1533 } else {
1534 updateEnabledState(getCurrentDataSet().getSelected());
1535 }
1536 }
1537
1538 @Override
1539 protected void updateEnabledState(Collection<? extends OsmPrimitive> selection) {
1540 setEnabled(selection != null && !selection.isEmpty());
1541 }
1542}
Note: See TracBrowser for help on using the repository browser.