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

Last change on this file since 3383 was 3383, checked in by jttt, 14 years ago

Fix #5269 JoinAreasAction

  • Property svn:eol-style set to native
File size: 37.0 KB
Line 
1// License: GPL. Copyright 2007 by Immanuel Scholz and others
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.GridBagLayout;
9import java.awt.Polygon;
10import java.awt.event.ActionEvent;
11import java.awt.event.KeyEvent;
12import java.awt.geom.Area;
13import java.awt.geom.Line2D;
14import java.util.ArrayList;
15import java.util.Collection;
16import java.util.Collections;
17import java.util.HashMap;
18import java.util.LinkedList;
19import java.util.List;
20import java.util.Map;
21import java.util.Set;
22import java.util.TreeMap;
23import java.util.TreeSet;
24import java.util.Map.Entry;
25
26import javax.swing.Box;
27import javax.swing.JComboBox;
28import javax.swing.JLabel;
29import javax.swing.JOptionPane;
30import javax.swing.JPanel;
31
32import org.openstreetmap.josm.Main;
33import org.openstreetmap.josm.command.AddCommand;
34import org.openstreetmap.josm.command.ChangeCommand;
35import org.openstreetmap.josm.command.Command;
36import org.openstreetmap.josm.command.DeleteCommand;
37import org.openstreetmap.josm.command.SequenceCommand;
38import org.openstreetmap.josm.data.UndoRedoHandler;
39import org.openstreetmap.josm.data.coor.EastNorth;
40import org.openstreetmap.josm.data.coor.LatLon;
41import org.openstreetmap.josm.data.osm.DataSet;
42import org.openstreetmap.josm.data.osm.Node;
43import org.openstreetmap.josm.data.osm.OsmPrimitive;
44import org.openstreetmap.josm.data.osm.Relation;
45import org.openstreetmap.josm.data.osm.RelationMember;
46import org.openstreetmap.josm.data.osm.TigerUtils;
47import org.openstreetmap.josm.data.osm.Way;
48import org.openstreetmap.josm.gui.ExtendedDialog;
49import org.openstreetmap.josm.tools.GBC;
50import org.openstreetmap.josm.tools.Shortcut;
51
52public class JoinAreasAction extends JosmAction {
53 // This will be used to commit commands and unite them into one large command sequence at the end
54 private LinkedList<Command> cmds = new LinkedList<Command>();
55 private int cmdsCount = 0;
56
57 // HelperClass
58 // Saves a node and two positions where to insert the node into the ways
59 private static class NodeToSegs implements Comparable<NodeToSegs> {
60 public int pos;
61 public Node n;
62 public double dis;
63 public NodeToSegs(int pos, Node n, LatLon dis) {
64 this.pos = pos;
65 this.n = n;
66 this.dis = n.getCoor().greatCircleDistance(dis);
67 }
68
69 public int compareTo(NodeToSegs o) {
70 if(this.pos == o.pos)
71 return (this.dis - o.dis) > 0 ? 1 : -1;
72 return this.pos - o.pos;
73 }
74
75 @Override
76 public int hashCode() {
77 return pos;
78 }
79
80 @Override
81 public boolean equals(Object o) {
82 if (o instanceof NodeToSegs)
83 return compareTo((NodeToSegs) o) == 0;
84 else
85 return false;
86 }
87 }
88
89 // HelperClass
90 // Saves a relation and a role an OsmPrimitve was part of until it was stripped from all relations
91 private static class RelationRole {
92 public final Relation rel;
93 public final String role;
94 public RelationRole(Relation rel, String role) {
95 this.rel = rel;
96 this.role = role;
97 }
98
99 @Override
100 public int hashCode() {
101 return rel.hashCode();
102 }
103
104 @Override
105 public boolean equals(Object other) {
106 if (!(other instanceof RelationRole)) return false;
107 RelationRole otherMember = (RelationRole) other;
108 return otherMember.role.equals(role) && otherMember.rel.equals(rel);
109 }
110 }
111
112 // Adds the menu entry, Shortcuts, etc.
113 public JoinAreasAction() {
114 super(tr("Join overlapping Areas"), "joinareas", tr("Joins areas that overlap each other"), Shortcut.registerShortcut("tools:joinareas", tr("Tool: {0}", tr("Join overlapping Areas")),
115 KeyEvent.VK_J, Shortcut.GROUP_EDIT, Shortcut.SHIFT_DEFAULT), true);
116 }
117
118 /**
119 * Gets called whenever the shortcut is pressed or the menu entry is selected
120 * Checks whether the selected objects are suitable to join and joins them if so
121 */
122 public void actionPerformed(ActionEvent e) {
123 LinkedList<Way> ways = new LinkedList<Way>(Main.main.getCurrentDataSet().getSelectedWays());
124
125 if (ways.isEmpty()) {
126 JOptionPane.showMessageDialog(Main.parent, tr("Please select at least one closed way that should be joined."));
127 return;
128 }
129
130 // Too many ways
131 if(ways.size() > 2) {
132 JOptionPane.showMessageDialog(Main.parent, tr("Only up to two areas can be joined at the moment."));
133 return;
134 }
135
136 List<Node> allNodes = new ArrayList<Node>();
137 for (Way way: ways) {
138 if(!way.isClosed()) {
139 JOptionPane.showMessageDialog(Main.parent, tr("\"{0}\" is not closed and therefore cannot be joined.", way.getName()));
140 return;
141 }
142
143 allNodes.addAll(way.getNodes());
144 }
145
146 // TODO: Only display this warning when nodes outside dataSourceArea are deleted
147 Area dataSourceArea = Main.main.getCurrentDataSet().getDataSourceArea();
148 if (dataSourceArea != null) {
149 for (Node node: allNodes) {
150 if (!dataSourceArea.contains(node.getCoor())) {
151 int option = JOptionPane.showConfirmDialog(Main.parent,
152 trn("The selected way has nodes outside of the downloaded data region.",
153 "The selected ways have nodes outside of the downloaded data region.",
154 ways.size()) + "\n"
155 + tr("This can lead to nodes being deleted accidentally.") + "\n"
156 + tr("Are you really sure to continue?"),
157 tr("Please abort if you are not sure"), JOptionPane.YES_NO_OPTION,
158 JOptionPane.WARNING_MESSAGE);
159
160 if (option != JOptionPane.YES_OPTION) return;
161 break;
162 }
163 }
164 }
165
166 if(joinAreas(ways.getFirst(), ways.getLast())) {
167 Main.map.mapView.repaint();
168 DataSet ds = Main.main.getCurrentDataSet();
169 ds.fireSelectionChanged();
170 } else {
171 JOptionPane.showMessageDialog(Main.parent, tr("No intersection found. Nothing was changed."));
172 }
173 }
174
175 /**
176 * Will join two overlapping areas
177 * @param Way First way/area
178 * @param Way Second way/area
179 * @return boolean Whether to display the "no operation" message
180 */
181 private boolean joinAreas(Way a, Way b) {
182 // Fix self-overlapping first or other errors
183 boolean same = a.equals(b);
184 boolean hadChanges = false;
185 if(!same) {
186 int i = 0;
187 if(checkForTagConflicts(a, b)) return true; // User aborted, so don't warn again
188 if(joinAreas(a, a)) {
189 ++i;
190 }
191 if(joinAreas(b, b)) {
192 ++i;
193 }
194 hadChanges = i > 0;
195 cmdsCount = i;
196 }
197
198 ArrayList<OsmPrimitive> nodes = addIntersections(a, b);
199 if(nodes.size() == 0) return hadChanges;
200 commitCommands(marktr("Added node on all intersections"));
201
202 // Remove ways from all relations so ways can be combined/split quietly
203 ArrayList<RelationRole> relations = removeFromRelations(a);
204 if(!same) {
205 relations.addAll(removeFromRelations(b));
206 }
207
208 // Don't warn now, because it will really look corrupted
209 boolean warnAboutRelations = relations.size() > 0;
210
211 Collection<Way> allWays = splitWaysOnNodes(a, b, nodes);
212
213 // Find all nodes and inner ways save them to a list
214 Collection<Node> allNodes = getNodesFromWays(allWays);
215 Collection<Way> innerWays = findInnerWays(allWays, allNodes);
216
217 // Join outer ways
218 Way outerWay = joinOuterWays(allWays, innerWays);
219 if (outerWay == null)
220 return true;
221
222 // Fix Multipolygons if there are any
223 Collection<Way> newInnerWays = fixMultipolygons(innerWays, outerWay, same);
224
225 // Delete the remaining inner ways
226 if(innerWays != null && innerWays.size() > 0) {
227 cmds.add(DeleteCommand.delete(Main.map.mapView.getEditLayer(), innerWays, true));
228 }
229 commitCommands(marktr("Delete Ways that are not part of an inner multipolygon"));
230
231 // We can attach our new multipolygon relation and pretend it has always been there
232 addOwnMultigonRelation(newInnerWays, outerWay, relations);
233 fixRelations(relations, outerWay);
234 commitCommands(marktr("Fix relations"));
235
236 stripTags(newInnerWays);
237 makeCommitsOneAction(
238 same
239 ? marktr("Joined self-overlapping area")
240 : marktr("Joined overlapping areas")
241 );
242
243 if(warnAboutRelations) {
244 JOptionPane.showMessageDialog(Main.parent, tr("Some of the ways were part of relations that have been modified. Please verify no errors have been introduced."));
245 }
246
247 return true;
248 }
249
250 /**
251 * Checks if tags of two given ways differ, and presents the user a dialog to solve conflicts
252 * @param Way First way to check
253 * @param Way Second Way to check
254 * @return boolean True if not all conflicts could be resolved, False if everything's fine
255 */
256 private boolean checkForTagConflicts(Way a, Way b) {
257 ArrayList<Way> ways = new ArrayList<Way>();
258 ways.add(a);
259 ways.add(b);
260
261 // FIXME: This is mostly copied and pasted from CombineWayAction.java and one day should be moved into tools
262 // We have TagCollection handling for that now - use it here as well
263 Map<String, Set<String>> props = new TreeMap<String, Set<String>>();
264 for (Way w : ways) {
265 for (String key: w.keySet()) {
266 if (!props.containsKey(key)) {
267 props.put(key, new TreeSet<String>());
268 }
269 props.get(key).add(w.get(key));
270 }
271 }
272
273 Way ax = new Way(a);
274 Way bx = new Way(b);
275
276 Map<String, JComboBox> components = new HashMap<String, JComboBox>();
277 JPanel p = new JPanel(new GridBagLayout());
278 for (Entry<String, Set<String>> e : props.entrySet()) {
279 if (TigerUtils.isTigerTag(e.getKey())) {
280 String combined = TigerUtils.combineTags(e.getKey(), e.getValue());
281 ax.put(e.getKey(), combined);
282 bx.put(e.getKey(), combined);
283 } else if (e.getValue().size() > 1) {
284 if("created_by".equals(e.getKey()))
285 {
286 ax.remove("created_by");
287 bx.remove("created_by");
288 } else {
289 JComboBox c = new JComboBox(e.getValue().toArray());
290 c.setEditable(true);
291 p.add(new JLabel(e.getKey()), GBC.std());
292 p.add(Box.createHorizontalStrut(10), GBC.std());
293 p.add(c, GBC.eol());
294 components.put(e.getKey(), c);
295 }
296 } else {
297 String val = e.getValue().iterator().next();
298 ax.put(e.getKey(), val);
299 bx.put(e.getKey(), val);
300 }
301 }
302
303 if (components.isEmpty())
304 return false; // No conflicts found
305
306 ExtendedDialog ed = new ExtendedDialog(Main.parent,
307 tr("Enter values for all conflicts."),
308 new String[] {tr("Solve Conflicts"), tr("Cancel")});
309 ed.setButtonIcons(new String[] {"dialogs/conflict.png", "cancel.png"});
310 ed.setContent(p);
311 ed.showDialog();
312
313 if (ed.getValue() != 1) return true; // user cancel, unresolvable conflicts
314
315 for (Entry<String, JComboBox> e : components.entrySet()) {
316 String val = e.getValue().getEditor().getItem().toString();
317 ax.put(e.getKey(), val);
318 bx.put(e.getKey(), val);
319 }
320
321 cmds.add(new ChangeCommand(a, ax));
322 cmds.add(new ChangeCommand(b, bx));
323 commitCommands(marktr("Fix tag conflicts"));
324 return false;
325 }
326
327 /**
328 * Will find all intersection and add nodes there for two given ways
329 * @param Way First way
330 * @param Way Second way
331 * @return ArrayList<OsmPrimitive> List of new nodes
332 */
333 private ArrayList<OsmPrimitive> addIntersections(Way a, Way b) {
334 boolean same = a.equals(b);
335 int nodesSizeA = a.getNodesCount();
336 int nodesSizeB = b.getNodesCount();
337
338 // We use OsmPrimitive here instead of Node because we later need to split a way at these nodes.
339 // With OsmPrimitve we can simply add the way and don't have to loop over the nodes
340 ArrayList<OsmPrimitive> nodes = new ArrayList<OsmPrimitive>();
341 ArrayList<NodeToSegs> nodesA = new ArrayList<NodeToSegs>();
342 ArrayList<NodeToSegs> nodesB = new ArrayList<NodeToSegs>();
343
344 for (int i = (same ? 1 : 0); i < nodesSizeA - 1; i++) {
345 for (int j = (same ? i + 2 : 0); j < nodesSizeB - 1; j++) {
346 // Avoid re-adding nodes that already exist on (some) intersections
347 if(a.getNode(i).equals(b.getNode(j)) || a.getNode(i+1).equals(b.getNode(j))) {
348 nodes.add(b.getNode(j));
349 continue;
350 } else
351 if(a.getNode(i).equals(b.getNode(j+1)) || a.getNode(i+1).equals(b.getNode(j+1))) {
352 nodes.add(b.getNode(j+1));
353 continue;
354 }
355 LatLon intersection = getLineLineIntersection(
356 a.getNode(i) .getEastNorth().east(), a.getNode(i) .getEastNorth().north(),
357 a.getNode(i+1).getEastNorth().east(), a.getNode(i+1).getEastNorth().north(),
358 b.getNode(j) .getEastNorth().east(), b.getNode(j) .getEastNorth().north(),
359 b.getNode(j+1).getEastNorth().east(), b.getNode(j+1).getEastNorth().north());
360 if(intersection == null) {
361 continue;
362 }
363
364 // Create the node. Adding them to the ways must be delayed because we still loop over them
365 Node n = new Node(intersection);
366 cmds.add(new AddCommand(n));
367 nodes.add(n);
368 // The distance is needed to sort and add the nodes in direction of the way
369 nodesA.add(new NodeToSegs(i, n, a.getNode(i).getCoor()));
370 if(same) {
371 nodesA.add(new NodeToSegs(j, n, a.getNode(j).getCoor()));
372 } else {
373 nodesB.add(new NodeToSegs(j, n, b.getNode(j).getCoor()));
374 }
375 }
376 }
377
378 addNodesToWay(a, nodesA);
379 if(!same) {
380 addNodesToWay(b, nodesB);
381 }
382
383 return nodes;
384 }
385
386 /**
387 * Finds the intersection of two lines
388 * @return LatLon null if no intersection was found, the LatLon coordinates of the intersection otherwise
389 */
390 static private LatLon getLineLineIntersection(
391 double x1, double y1, double x2, double y2,
392 double x3, double y3, double x4, double y4) {
393
394 if (!Line2D.linesIntersect(x1, y1, x2, y2, x3, y3, x4, y4)) return null;
395
396 // Convert line from (point, point) form to ax+by=c
397 double a1 = y2 - y1;
398 double b1 = x1 - x2;
399 double c1 = x2*y1 - x1*y2;
400
401 double a2 = y4 - y3;
402 double b2 = x3 - x4;
403 double c2 = x4*y3 - x3*y4;
404
405 // Solve the equations
406 double det = a1*b2 - a2*b1;
407 if(det == 0) return null; // Lines are parallel
408
409 return Main.proj.eastNorth2latlon(new EastNorth(
410 (b1*c2 - b2*c1)/det,
411 (a2*c1 -a1*c2)/det
412 ));
413 }
414
415 /**
416 * Inserts given nodes with positions into the given ways
417 * @param Way The way to insert the nodes into
418 * @param Collection<NodeToSegs> The list of nodes with positions to insert
419 */
420 private void addNodesToWay(Way a, ArrayList<NodeToSegs> nodes) {
421 if(nodes.size() == 0)
422 return;
423 Way ax=new Way(a);
424 Collections.sort(nodes);
425
426 int numOfAdds = 1;
427 for(NodeToSegs n : nodes) {
428 ax.addNode(n.pos + numOfAdds, n.n);
429 numOfAdds++;
430 }
431
432 cmds.add(new ChangeCommand(a, ax));
433 }
434
435 /**
436 * Commits the command list with a description
437 * @param String The description of what the commands do
438 */
439 private void commitCommands(String description) {
440 switch(cmds.size()) {
441 case 0:
442 return;
443 case 1:
444 Main.main.undoRedo.add(cmds.getFirst());
445 break;
446 default:
447 Command c = new SequenceCommand(tr(description), cmds);
448 Main.main.undoRedo.add(c);
449 break;
450 }
451
452 cmds.clear();
453 cmdsCount++;
454 }
455
456 /**
457 * Removes a given OsmPrimitive from all relations
458 * @param OsmPrimitive Element to remove from all relations
459 * @return ArrayList<RelationRole> List of relations with roles the primitives was part of
460 */
461 private ArrayList<RelationRole> removeFromRelations(OsmPrimitive osm) {
462 ArrayList<RelationRole> result = new ArrayList<RelationRole>();
463 for (Relation r : Main.main.getCurrentDataSet().getRelations()) {
464 if (r.isDeleted()) {
465 continue;
466 }
467 for (RelationMember rm : r.getMembers()) {
468 if (rm.getMember() != osm) {
469 continue;
470 }
471
472 Relation newRel = new Relation(r);
473 List<RelationMember> members = newRel.getMembers();
474 members.remove(rm);
475 newRel.setMembers(members);
476
477 cmds.add(new ChangeCommand(r, newRel));
478 RelationRole saverel = new RelationRole(r, rm.getRole());
479 if(!result.contains(saverel)) {
480 result.add(saverel);
481 }
482 break;
483 }
484 }
485
486 commitCommands(marktr("Removed Element from Relations"));
487 return result;
488 }
489
490 /**
491 * This is a hacky implementation to make use of the splitWayAction code and
492 * should be improved. SplitWayAction needs to expose its splitWay function though.
493 */
494 private Collection<Way> splitWaysOnNodes(Way a, Way b, Collection<OsmPrimitive> nodes) {
495 ArrayList<Way> ways = new ArrayList<Way>();
496 ways.add(a);
497 if(!a.equals(b)) {
498 ways.add(b);
499 }
500
501 List<OsmPrimitive> affected = new ArrayList<OsmPrimitive>();
502 for (Way way : ways) {
503 nodes.add(way);
504 Main.main.getCurrentDataSet().setSelected(nodes);
505 nodes.remove(way);
506 new SplitWayAction().actionPerformed(null);
507 cmdsCount++;
508 affected.addAll(Main.main.getCurrentDataSet().getSelectedWays());
509 }
510 return osmprim2way(affected);
511 }
512
513 /**
514 * Converts a list of OsmPrimitives to a list of Ways
515 * @param Collection<OsmPrimitive> The OsmPrimitives list that's needed as a list of Ways
516 * @return Collection<Way> The list as list of Ways
517 */
518 static private Collection<Way> osmprim2way(Collection<OsmPrimitive> ways) {
519 Collection<Way> result = new ArrayList<Way>();
520 for(OsmPrimitive w: ways) {
521 if(w instanceof Way) {
522 result.add((Way) w);
523 }
524 }
525 return result;
526 }
527
528 /**
529 * Returns all nodes for given ways
530 * @param Collection<Way> The list of ways which nodes are to be returned
531 * @return Collection<Node> The list of nodes the ways contain
532 */
533 private Collection<Node> getNodesFromWays(Collection<Way> ways) {
534 Collection<Node> allNodes = new ArrayList<Node>();
535 for(Way w: ways) {
536 allNodes.addAll(w.getNodes());
537 }
538 return allNodes;
539 }
540
541 /**
542 * Finds all inner ways for a given list of Ways and Nodes from a multigon by constructing a polygon
543 * for each way, looking for inner nodes that are not part of this way. If a node is found, all ways
544 * containing this node are added to the list
545 * @param Collection<Way> A list of (splitted) ways that form a multigon
546 * @param Collection<Node> A list of nodes that belong to the multigon
547 * @return Collection<Way> A list of ways that are positioned inside the outer borders of the multigon
548 */
549 private Collection<Way> findInnerWays(Collection<Way> multigonWays, Collection<Node> multigonNodes) {
550 Collection<Way> innerWays = new ArrayList<Way>();
551 for(Way w: multigonWays) {
552 Polygon poly = new Polygon();
553 for(Node n: (w).getNodes()) {
554 poly.addPoint(latlonToXY(n.getCoor().lat()), latlonToXY(n.getCoor().lon()));
555 }
556
557 for(Node n: multigonNodes) {
558 if(!(w).containsNode(n) && poly.contains(latlonToXY(n.getCoor().lat()), latlonToXY(n.getCoor().lon()))) {
559 getWaysByNode(innerWays, multigonWays, n);
560 }
561 }
562 }
563
564 return innerWays;
565 }
566
567 // Polygon only supports int coordinates, so convert them
568 private int latlonToXY(double val) {
569 return (int)Math.round(val*1000000);
570 }
571
572 /**
573 * Finds all ways that contain the given node.
574 * @param Collection<Way> A list to which matching ways will be added
575 * @param Collection<Way> A list of ways to check
576 * @param Node The node the ways should be checked against
577 */
578 private void getWaysByNode(Collection<Way> innerWays, Collection<Way> w, Node n) {
579 for(Way way : w) {
580 if(!(way).containsNode(n)) {
581 continue;
582 }
583 if(!innerWays.contains(way)) {
584 innerWays.add(way); // Will need this later for multigons
585 }
586 }
587 }
588
589 /**
590 * Joins the two outer ways and deletes all short ways that can't be part of a multipolygon anyway
591 * @param Collection<OsmPrimitive> The list of all ways that belong to that multigon
592 * @param Collection<Way> The list of inner ways that belong to that multigon
593 * @return Way The newly created outer way
594 */
595 private Way joinOuterWays(Collection<Way> multigonWays, Collection<Way> innerWays) {
596 ArrayList<Way> join = new ArrayList<Way>();
597 for(Way w: multigonWays) {
598 // Skip inner ways
599 if(innerWays.contains(w)) {
600 continue;
601 }
602
603 if(w.getNodesCount() <= 2) {
604 cmds.add(new DeleteCommand(w));
605 } else {
606 join.add(w);
607 }
608 }
609
610 commitCommands(marktr("Join Areas: Remove Short Ways"));
611 Way joinedWay = joinWays(join);
612 if (joinedWay != null)
613 return closeWay(joinedWay);
614 else
615 return null;
616 }
617
618 /**
619 * Ensures a way is closed. If it isn't, last and first node are connected.
620 * @param Way the way to ensure it's closed
621 * @return Way The joined way.
622 */
623 private Way closeWay(Way w) {
624 if(w.isClosed())
625 return w;
626 Main.main.getCurrentDataSet().setSelected(w);
627 Way wnew = new Way(w);
628 wnew.addNode(wnew.firstNode());
629 cmds.add(new ChangeCommand(w, wnew));
630 commitCommands(marktr("Closed Way"));
631 return (Way)(Main.main.getCurrentDataSet().getSelectedWays().toArray())[0];
632 }
633
634 /**
635 * Joins a list of ways (using CombineWayAction and ReverseWayAction if necessary to quiet the former)
636 * @param ArrayList<Way> The list of ways to join
637 * @return Way The newly created way
638 */
639 private Way joinWays(ArrayList<Way> ways) {
640 if(ways.size() < 2) return ways.get(0);
641
642 // This will turn ways so all of them point in the same direction and CombineAction won't bug
643 // the user about this.
644 Way a = null;
645 for(Way b : ways) {
646 if(a == null) {
647 a = b;
648 continue;
649 }
650 if(a.getNode(0).equals(b.getNode(0)) ||
651 a.getNode(a.getNodesCount()-1).equals(b.getNode(b.getNodesCount()-1))) {
652 Main.main.getCurrentDataSet().setSelected(b);
653 new ReverseWayAction().actionPerformed(null);
654 cmdsCount++;
655 }
656 a = b;
657 }
658 if((a = new CombineWayAction().combineWays(ways)) != null) {
659 cmdsCount++;
660 }
661 return a;
662 }
663
664 /**
665 * Finds all ways that may be part of a multipolygon relation and removes them from the given list.
666 * It will automatically combine "good" ways
667 * @param Collection<Way> The list of inner ways to check
668 * @param Way The newly created outer way
669 * @return ArrayList<Way> The List of newly created inner ways
670 */
671 private ArrayList<Way> fixMultipolygons(Collection<Way> uninterestingWays, Way outerWay, boolean selfintersect) {
672 Collection<Node> innerNodes = getNodesFromWays(uninterestingWays);
673 Collection<Node> outerNodes = outerWay.getNodes();
674
675 // The newly created inner ways. uninterestingWays is passed by reference and therefore modified in-place
676 ArrayList<Way> newInnerWays = new ArrayList<Way>();
677
678 // Now we need to find all inner ways that contain a remaining node, but no outer nodes
679 // Remaining nodes are those that contain to more than one way. All nodes that belong to an
680 // inner multigon part will have at least two ways, so we can use this to find which ways do
681 // belong to the multigon.
682 ArrayList<Way> possibleWays = new ArrayList<Way>();
683 wayIterator: for(Way w : uninterestingWays) {
684 boolean hasInnerNodes = false;
685 for(Node n : w.getNodes()) {
686 if(outerNodes.contains(n)) {
687 if(!selfintersect) { // allow outer point for self intersection
688 continue wayIterator;
689 }
690 }
691 else if(!hasInnerNodes && innerNodes.contains(n)) {
692 hasInnerNodes = true;
693 }
694 }
695 if(!hasInnerNodes || w.getNodesCount() < 2) {
696 continue;
697 }
698 possibleWays.add(w);
699 }
700
701 // This removes unnecessary ways that might have been added.
702 removeAlmostAlikeWays(possibleWays);
703
704 // loop twice
705 // in k == 0 prefer ways which allow no Y-joining (i.e. which have only 1 solution)
706 for(int k = 0; k < 2; ++k)
707 {
708 // Join all ways that have one start/ending node in common
709 Way joined = null;
710 outerIterator: do {
711 removePartlyUnconnectedWays(possibleWays);
712 joined = null;
713 for(Way w1 : possibleWays) {
714 if(w1.isClosed()) {
715 if(!wayIsCollapsed(w1)) {
716 uninterestingWays.remove(w1);
717 newInnerWays.add(w1);
718 }
719 joined = w1;
720 possibleWays.remove(w1);
721 continue outerIterator;
722 }
723 ArrayList<Way> secondary = new ArrayList<Way>();
724 for(Way w2 : possibleWays) {
725 int i = 0;
726 // w2 cannot be closed, otherwise it would have been removed above
727 if(w1.equals(w2)) {
728 continue;
729 }
730 if(w2.isFirstLastNode(w1.firstNode())) {
731 ++i;
732 }
733 if(w2.isFirstLastNode(w1.lastNode())) {
734 ++i;
735 }
736 if(i == 2) // this way closes w1 - take it!
737 {
738 if(secondary.size() > 0) {
739 secondary.clear();
740 }
741 secondary.add(w2);
742 break;
743 }
744 else if(i > 0) {
745 secondary.add(w2);
746 }
747 }
748 if(k == 0 ? secondary.size() == 1 : secondary.size() > 0)
749 {
750 ArrayList<Way> joinThem = new ArrayList<Way>();
751 joinThem.add(w1);
752 joinThem.add(secondary.get(0));
753 // Although we joined the ways, we cannot simply assume that they are closed
754 if((joined = joinWays(joinThem)) != null)
755 {
756 uninterestingWays.removeAll(joinThem);
757 possibleWays.removeAll(joinThem);
758
759 //List<Node> nodes = joined.getNodes();
760 // check if we added too much
761 /*for(int i = 1; i < nodes.size()-2; ++i)
762 {
763 if(nodes.get(i) == nodes.get(nodes.size()-1))
764 System.out.println("Joining of ways produced unexpecteded result\n");
765 }*/
766 uninterestingWays.add(joined);
767 possibleWays.add(joined);
768 continue outerIterator;
769 }
770 }
771 }
772 } while(joined != null);
773 }
774 return newInnerWays;
775 }
776
777 /**
778 * Removes almost alike ways (= ways that are on top of each other for all nodes)
779 * @param ArrayList<Way> the ways to remove almost-duplicates from
780 */
781 private void removeAlmostAlikeWays(ArrayList<Way> ways) {
782 Collection<Way> removables = new ArrayList<Way>();
783 outer: for(int i=0; i < ways.size(); i++) {
784 Way a = ways.get(i);
785 for(int j=i+1; j < ways.size(); j++) {
786 Way b = ways.get(j);
787 List<Node> revNodes = new ArrayList<Node>(b.getNodes());
788 Collections.reverse(revNodes);
789 if(a.getNodes().equals(b.getNodes()) || a.getNodes().equals(revNodes)) {
790 removables.add(a);
791 continue outer;
792 }
793 }
794 }
795 ways.removeAll(removables);
796 }
797
798 /**
799 * Removes ways from the given list whose starting or ending node doesn't
800 * connect to other ways from the same list (it's like removing spikes).
801 * @param ArrayList<Way> The list of ways to remove "spikes" from
802 */
803 private void removePartlyUnconnectedWays(ArrayList<Way> ways) {
804 List<Way> removables = new ArrayList<Way>();
805 for(Way a : ways) {
806 if(a.isClosed()) {
807 continue;
808 }
809 boolean connectedStart = false;
810 boolean connectedEnd = false;
811 for(Way b : ways) {
812 if(a.equals(b)) {
813 continue;
814 }
815 if(b.isFirstLastNode(a.firstNode())) {
816 connectedStart = true;
817 }
818 if(b.isFirstLastNode(a.lastNode())) {
819 connectedEnd = true;
820 }
821 }
822 if(!connectedStart || !connectedEnd) {
823 removables.add(a);
824 }
825 }
826 ways.removeAll(removables);
827 }
828
829 /**
830 * Checks if a way is collapsed (i.e. looks like <---->)
831 * @param Way A *closed* way to check if it is collapsed
832 * @return boolean If the closed way is collapsed or not
833 */
834 private boolean wayIsCollapsed(Way w) {
835 if(w.getNodesCount() <= 3) return true;
836
837 // If a way contains more than one node twice, it must be collapsed (only start/end node may be the same)
838 Way x = new Way(w);
839 int count = 0;
840 for(Node n : w.getNodes()) {
841 x.removeNode(n);
842 if(x.containsNode(n)) {
843 count++;
844 }
845 if(count == 2) return true;
846 }
847 return false;
848 }
849
850 /**
851 * Will add own multipolygon relation to the "previously existing" relations. Fixup is done by fixRelations
852 * @param Collection<Way> List of already closed inner ways
853 * @param Way The outer way
854 * @param ArrayList<RelationRole> The list of relation with roles to add own relation to
855 */
856 private void addOwnMultigonRelation(Collection<Way> inner, Way outer, ArrayList<RelationRole> rels) {
857 if(inner.size() == 0) return;
858 // Create new multipolygon relation and add all inner ways to it
859 Relation newRel = new Relation();
860 newRel.put("type", "multipolygon");
861 for(Way w : inner) {
862 newRel.addMember(new RelationMember("inner", w));
863 }
864 cmds.add(new AddCommand(newRel));
865
866 // We don't add outer to the relation because it will be handed to fixRelations()
867 // which will then do the remaining work. Collections are passed by reference, so no
868 // need to return it
869 rels.add(new RelationRole(newRel, "outer"));
870 //return rels;
871 }
872
873 /**
874 * Adds the previously removed relations again to the outer way. If there are multiple multipolygon
875 * relations where the joined areas were in "outer" role a new relation is created instead with all
876 * members of both. This function depends on multigon relations to be valid already, it won't fix them.
877 * @param ArrayList<RelationRole> List of relations with roles the (original) ways were part of
878 * @param Way The newly created outer area/way
879 */
880 private void fixRelations(ArrayList<RelationRole> rels, Way outer) {
881 ArrayList<RelationRole> multiouters = new ArrayList<RelationRole>();
882 for(RelationRole r : rels) {
883 if( r.rel.get("type") != null &&
884 r.rel.get("type").equalsIgnoreCase("multipolygon") &&
885 r.role.equalsIgnoreCase("outer")
886 ) {
887 multiouters.add(r);
888 continue;
889 }
890 // Add it back!
891 Relation newRel = new Relation(r.rel);
892 newRel.addMember(new RelationMember(r.role, outer));
893 cmds.add(new ChangeCommand(r.rel, newRel));
894 }
895
896 Relation newRel = null;
897 switch(multiouters.size()) {
898 case 0:
899 return;
900 case 1:
901 // Found only one to be part of a multipolygon relation, so just add it back as well
902 newRel = new Relation(multiouters.get(0).rel);
903 newRel.addMember(new RelationMember(multiouters.get(0).role, outer));
904 cmds.add(new ChangeCommand(multiouters.get(0).rel, newRel));
905 return;
906 default:
907 // Create a new relation with all previous members and (Way)outer as outer.
908 newRel = new Relation();
909 for(RelationRole r : multiouters) {
910 // Add members
911 for(RelationMember rm : r.rel.getMembers())
912 if(!newRel.getMembers().contains(rm)) {
913 newRel.addMember(rm);
914 }
915 // Add tags
916 for (String key : r.rel.keySet()) {
917 newRel.put(key, r.rel.get(key));
918 }
919 // Delete old relation
920 cmds.add(new DeleteCommand(r.rel));
921 }
922 newRel.addMember(new RelationMember("outer", outer));
923 cmds.add(new AddCommand(newRel));
924 }
925 }
926
927 /**
928 * @param Collection<Way> The List of Ways to remove all tags from
929 */
930 private void stripTags(Collection<Way> ways) {
931 for(Way w: ways) {
932 stripTags(w);
933 }
934 commitCommands(marktr("Remove tags from inner ways"));
935 }
936
937 /**
938 * @param Way The Way to remove all tags from
939 */
940 private void stripTags(Way x) {
941 if(x.getKeys() == null) return;
942 Way y = new Way(x);
943 for (String key : x.keySet()) {
944 y.remove(key);
945 }
946 cmds.add(new ChangeCommand(x, y));
947 }
948
949 /**
950 * Takes the last cmdsCount actions back and combines them into a single action
951 * (for when the user wants to undo the join action)
952 * @param String The commit message to display
953 */
954 private void makeCommitsOneAction(String message) {
955 UndoRedoHandler ur = Main.main.undoRedo;
956 cmds.clear();
957 int i = Math.max(ur.commands.size() - cmdsCount, 0);
958 for(; i < ur.commands.size(); i++) {
959 cmds.add(ur.commands.get(i));
960 }
961
962 for(i = 0; i < cmds.size(); i++) {
963 ur.undo();
964 }
965
966 commitCommands(message == null ? marktr("Join Areas Function") : message);
967 cmdsCount = 0;
968 }
969
970 @Override
971 protected void updateEnabledState() {
972 if (getCurrentDataSet() == null) {
973 setEnabled(false);
974 } else {
975 updateEnabledState(getCurrentDataSet().getSelected());
976 }
977 }
978
979 @Override
980 protected void updateEnabledState(Collection<? extends OsmPrimitive> selection) {
981 setEnabled(selection != null && !selection.isEmpty());
982 }
983}
Note: See TracBrowser for help on using the repository browser.