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

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

sonar - fix some errors, mainly NPEs

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