source: osm/applications/editors/josm/plugins/utilsplugin/src/UtilsPlugin/JoinAreasAction.java@ 13775

Last change on this file since 13775 was 13723, checked in by stoecker, 16 years ago

close #1652

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