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

Last change on this file since 14121 was 13776, checked in by stoecker, 16 years ago

close #2195. patch by xeen

File size: 32.5 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 if(innerWays != null && innerWays.size() > 0)
239 cmds.add(DeleteCommand.delete(innerWays, true));
240 commitCommands("Delete Ways that are not part of an inner multipolygon");
241
242 // We can attach our new multipolygon relation and pretend it has always been there
243 addOwnMultigonRelation(newInnerWays, outerWay, relations);
244 fixRelations(relations, outerWay);
245 commitCommands("Fix relations");
246
247 stripTags(newInnerWays);
248 makeCommitsOneAction(
249 a.equals(b)
250 ? "Joined self-overlapping area " + a.getName()
251 : "Joined overlapping areas " + a.getName() + " and " + b.getName()
252 );
253
254 if(warnAboutRelations)
255 JOptionPane.showMessageDialog(Main.parent, tr("Some of the ways were part of relations that have been modified. Please verify no errors have been introduced."));
256
257 return true;
258 }
259
260 /**
261 * Checks if tags of two given ways differ, and presents the user a dialog to solve conflicts
262 * @param Way First way to check
263 * @param Way Second Way to check
264 * @return boolean True if not all conflicts could be resolved, False if everything's fine
265 */
266 private boolean checkForTagConflicts(Way a, Way b) {
267 ArrayList<Way> ways = new ArrayList<Way>();
268 ways.add(a);
269 ways.add(b);
270
271 // This is mostly copied and pasted from CombineWayAction.java and one day should be moved into tools
272 Map<String, Set<String>> props = new TreeMap<String, Set<String>>();
273 for (Way w : ways) {
274 for (Entry<String,String> e : w.entrySet()) {
275 if (!props.containsKey(e.getKey()))
276 props.put(e.getKey(), new TreeSet<String>());
277 props.get(e.getKey()).add(e.getValue());
278 }
279 }
280
281 Way ax = new Way(a);
282 Way bx = new Way(b);
283
284 Map<String, JComboBox> components = new HashMap<String, JComboBox>();
285 JPanel p = new JPanel(new GridBagLayout());
286 for (Entry<String, Set<String>> e : props.entrySet()) {
287 if (TigerUtils.isTigerTag(e.getKey())) {
288 String combined = TigerUtils.combineTags(e.getKey(), e.getValue());
289 ax.put(e.getKey(), combined);
290 bx.put(e.getKey(), combined);
291 } else if (e.getValue().size() > 1) {
292 if("created_by".equals(e.getKey()))
293 {
294 ax.put("created_by", "JOSM");
295 bx.put("created_by", "JOSM");
296 } else {
297 JComboBox c = new JComboBox(e.getValue().toArray());
298 c.setEditable(true);
299 p.add(new JLabel(e.getKey()), GBC.std());
300 p.add(Box.createHorizontalStrut(10), GBC.std());
301 p.add(c, GBC.eol());
302 components.put(e.getKey(), c);
303 }
304 } else {
305 String val = e.getValue().iterator().next();
306 ax.put(e.getKey(), val);
307 bx.put(e.getKey(), val);
308 }
309 }
310
311 if (components.isEmpty())
312 return false; // No conflicts found
313
314 int result = new ExtendedDialog(Main.parent,
315 tr("Enter values for all conflicts."),
316 p,
317 new String[] {tr("Solve Conflicts"), tr("Cancel")},
318 new String[] {"dialogs/conflict.png", "cancel.png"}).getValue();
319
320 if (result != 1) return true; // user cancel, unresolvable conflicts
321
322 for (Entry<String, JComboBox> e : components.entrySet()) {
323 String val = e.getValue().getEditor().getItem().toString();
324 ax.put(e.getKey(), val);
325 bx.put(e.getKey(), val);
326 }
327
328 cmds.add(new ChangeCommand(a, ax));
329 cmds.add(new ChangeCommand(b, bx));
330 commitCommands("Fix tag conflicts");
331 return false;
332 }
333
334 /**
335 * Will find all intersection and add nodes there for two given ways
336 * @param Way First way
337 * @param Way Second way
338 * @return ArrayList<OsmPrimitive> List of new nodes
339 */
340 private ArrayList<OsmPrimitive> addIntersections(Way a, Way b) {
341 boolean same = a.equals(b);
342 int nodesSizeA = a.nodes.size();
343 int nodesSizeB = b.nodes.size();
344
345 // We use OsmPrimitive here instead of Node because we later need to split a way at these nodes.
346 // With OsmPrimitve we can simply add the way and don't have to loop over the nodes
347 ArrayList<OsmPrimitive> nodes = new ArrayList<OsmPrimitive>();
348 ArrayList<NodeToSegs> nodesA = new ArrayList<NodeToSegs>();
349 ArrayList<NodeToSegs> nodesB = new ArrayList<NodeToSegs>();
350
351 for (int i = (same ? 1 : 0); i < nodesSizeA - 1; i++) {
352 for (int j = (same ? i + 2 : 0); j < nodesSizeB - 1; j++) {
353 // Avoid re-adding nodes that already exist on (some) intersections
354 if(a.nodes.get(i).equals(b.nodes.get(j)) || a.nodes.get(i+1).equals(b.nodes.get(j))) {
355 nodes.add(b.nodes.get(j));
356 continue;
357 } else
358 if(a.nodes.get(i).equals(b.nodes.get(j+1)) || a.nodes.get(i+1).equals(b.nodes.get(j+1))) {
359 nodes.add(b.nodes.get(j+1));
360 continue;
361 }
362 LatLon intersection = getLineLineIntersection(
363 a.nodes.get(i) .eastNorth.east(), a.nodes.get(i) .eastNorth.north(),
364 a.nodes.get(i+1).eastNorth.east(), a.nodes.get(i+1).eastNorth.north(),
365 b.nodes.get(j) .eastNorth.east(), b.nodes.get(j) .eastNorth.north(),
366 b.nodes.get(j+1).eastNorth.east(), b.nodes.get(j+1).eastNorth.north());
367 if(intersection == null) continue;
368
369 // Create the node. Adding them to the ways must be delayed because we still loop over them
370 Node n = new Node(intersection);
371 cmds.add(new AddCommand(n));
372 nodes.add(n);
373 // The distance is needed to sort and add the nodes in direction of the way
374 nodesA.add(new NodeToSegs(i, n, a.nodes.get(i).coor));
375 if(same)
376 nodesA.add(new NodeToSegs(j, n, a.nodes.get(j).coor));
377 else
378 nodesB.add(new NodeToSegs(j, n, b.nodes.get(j).coor));
379 }
380 }
381
382 addNodesToWay(a, nodesA);
383 if(!same) addNodesToWay(b, nodesB);
384
385 return nodes;
386 }
387
388 /**
389 * Finds the intersection of two lines
390 * @return LatLon null if no intersection was found, the LatLon coordinates of the intersection otherwise
391 */
392 static private LatLon getLineLineIntersection(
393 double x1, double y1, double x2, double y2,
394 double x3, double y3, double x4, double y4) {
395
396 if (!Line2D.linesIntersect(x1, y1, x2, y2, x3, y3, x4, y4)) return null;
397
398 // Convert line from (point, point) form to ax+by=c
399 double a1 = y2 - y1;
400 double b1 = x1 - x2;
401 double c1 = x2*y1 - x1*y2;
402
403 double a2 = y4 - y3;
404 double b2 = x3 - x4;
405 double c2 = x4*y3 - x3*y4;
406
407 // Solve the equations
408 double det = a1*b2 - a2*b1;
409 if(det == 0) return null; // Lines are parallel
410
411 return Main.proj.eastNorth2latlon(new EastNorth(
412 (b1*c2 - b2*c1)/det,
413 (a2*c1 -a1*c2)/det
414 ));
415 }
416
417 /**
418 * Inserts given nodes with positions into the given ways
419 * @param Way The way to insert the nodes into
420 * @param Collection<NodeToSegs> The list of nodes with positions to insert
421 */
422 private void addNodesToWay(Way a, ArrayList<NodeToSegs> nodes) {
423 Way ax=new Way(a);
424 List<NodeToSegs> newnodes = new ArrayList<NodeToSegs>();
425 Collections.sort(nodes);
426
427 int numOfAdds = 1;
428 for(NodeToSegs n : nodes) {
429 ax.addNode(n.pos + numOfAdds, n.n);
430 numOfAdds++;
431 }
432
433 cmds.add(new ChangeCommand(a, ax));
434 }
435
436 /**
437 * Commits the command list with a description
438 * @param String The description of what the commands do
439 */
440 private void commitCommands(String description) {
441 switch(cmds.size()) {
442 case 0:
443 return;
444 case 1:
445 Main.main.undoRedo.add(cmds.getFirst());
446 break;
447 default:
448 Command c = new SequenceCommand(tr(description), cmds);
449 Main.main.undoRedo.add(c);
450 break;
451 }
452
453 cmds.clear();
454 cmdsCount++;
455 }
456
457 /**
458 * Removes a given OsmPrimitive from all relations
459 * @param OsmPrimitive Element to remove from all relations
460 * @return ArrayList<RelationRole> List of relations with roles the primitives was part of
461 */
462 private ArrayList<RelationRole> removeFromRelations(OsmPrimitive osm) {
463 ArrayList<RelationRole> result = new ArrayList<RelationRole>();
464 for (Relation r : Main.ds.relations) {
465 if (r.deleted || r.incomplete) continue;
466 for (RelationMember rm : r.members) {
467 if (rm.member != osm) continue;
468
469 Relation newRel = new Relation(r);
470 newRel.members.remove(rm);
471
472 cmds.add(new ChangeCommand(r, newRel));
473 RelationRole saverel = new RelationRole(r, rm.role);
474 if(!result.contains(saverel)) result.add(saverel);
475 break;
476 }
477 }
478
479 commitCommands("Removed Element from Relations");
480 return result;
481 }
482
483 /**
484 * This is a hacky implementation to make use of the splitWayAction code and
485 * should be improved. SplitWayAction needs to expose its splitWay function though.
486 */
487 private Collection<Way> splitWaysOnNodes(Way a, Way b, Collection<OsmPrimitive> nodes) {
488 ArrayList<Way> ways = new ArrayList<Way>();
489 ways.add(a);
490 if(!a.equals(b)) ways.add(b);
491
492 List<OsmPrimitive> affected = new ArrayList<OsmPrimitive>();
493 for (Way way : ways) {
494 nodes.add(way);
495 Main.ds.setSelected(nodes);
496 nodes.remove(way);
497 new SplitWayAction().actionPerformed(null);
498 cmdsCount++;
499 affected.addAll(Main.ds.getSelectedWays());
500 }
501 return osmprim2way(affected);
502 }
503
504 /**
505 * Converts a list of OsmPrimitives to a list of Ways
506 * @param Collection<OsmPrimitive> The OsmPrimitives list that's needed as a list of Ways
507 * @return Collection<Way> The list as list of Ways
508 */
509 static private Collection<Way> osmprim2way(Collection<OsmPrimitive> ways) {
510 Collection<Way> result = new ArrayList<Way>();
511 for(OsmPrimitive w: ways) {
512 if(w instanceof Way) result.add((Way) w);
513 }
514 return result;
515 }
516
517 /**
518 * Returns all nodes for given ways
519 * @param Collection<Way> The list of ways which nodes are to be returned
520 * @return Collection<Node> The list of nodes the ways contain
521 */
522 private Collection<Node> getNodesFromWays(Collection<Way> ways) {
523 Collection<Node> allNodes = new ArrayList<Node>();
524 for(Way w: ways) allNodes.addAll(w.nodes);
525 return allNodes;
526 }
527
528 /**
529 * Finds all inner ways for a given list of Ways and Nodes from a multigon by constructing a polygon
530 * for each way, looking for inner nodes that are not part of this way. If a node is found, all ways
531 * containing this node are added to the list
532 * @param Collection<Way> A list of (splitted) ways that form a multigon
533 * @param Collection<Node> A list of nodes that belong to the multigon
534 * @return Collection<Way> A list of ways that are positioned inside the outer borders of the multigon
535 */
536 private Collection<Way> findInnerWays(Collection<Way> multigonWays, Collection<Node> multigonNodes) {
537 Collection<Way> innerWays = new ArrayList<Way>();
538 for(Way w: multigonWays) {
539 Polygon poly = new Polygon();
540 for(Node n: ((Way)w).nodes) poly.addPoint(latlonToXY(n.coor.lat()), latlonToXY(n.coor.lon()));
541
542 for(Node n: multigonNodes) {
543 if(!((Way)w).nodes.contains(n) && poly.contains(latlonToXY(n.coor.lat()), latlonToXY(n.coor.lon()))) {
544 innerWays.addAll(getWaysByNode(multigonWays, n));
545 }
546 }
547 }
548
549 return innerWays;
550 }
551
552 // Polygon only supports int coordinates, so convert them
553 private int latlonToXY(double val) {
554 return (int)Math.round(val*1000000);
555 }
556
557 /**
558 * Finds all ways that contain the given node.
559 * @param Collection<OsmPrimitive> A collection of OsmPrimitives, but only ways will be honored
560 * @param Node The node the ways should be checked against
561 * @return Collection<Way> A list of ways that contain the given node
562 */
563 private Collection<Way> getWaysByNode(Collection<Way> w, Node n) {
564 Collection<Way> deletedWays = new ArrayList<Way>();
565 for(Way way : w) {
566 if(!((Way)way).nodes.contains(n)) continue;
567 if(!deletedWays.contains(way)) deletedWays.add(way); // Will need this later for multigons
568 }
569 return deletedWays;
570 }
571
572 /**
573 * Joins the two outer ways and deletes all short ways that can't be part of a multipolygon anyway
574 * @param Collection<OsmPrimitive> The list of all ways that belong to that multigon
575 * @param Collection<Way> The list of inner ways that belong to that multigon
576 * @return Way The newly created outer way
577 */
578 private Way joinOuterWays(Collection<Way> multigonWays, Collection<Way> innerWays) {
579 ArrayList<Way> join = new ArrayList<Way>();
580 for(Way w: multigonWays) {
581 // Skip inner ways
582 if(innerWays.contains(w)) continue;
583
584 if(w.nodes.size() <= 2)
585 cmds.add(new DeleteCommand(w));
586 else
587 join.add(w);
588 }
589
590 commitCommands("Join Areas: Remove Short Ways");
591 return joinWays(join);
592 }
593
594 /**
595 * Joins a list of ways (using CombineWayAction and ReverseWayAction if necessary to quiet the former)
596 * @param ArrayList<Way> The list of ways to join
597 * @return Way The newly created way
598 */
599 private Way joinWays(ArrayList<Way> ways) {
600 if(ways.size() < 2) return ways.get(0);
601 //Main.ds.setSelected(ways);
602
603 // This will turn ways so all of them point in the same direction and CombineAction won't bug
604 // the user about this.
605 Way a = null;
606 for(Way b : ways) {
607 if(a == null) {
608 a = b;
609 continue;
610 }
611 if(a.nodes.get(0).equals(b.nodes.get(0)) ||
612 a.nodes.get(a.nodes.size()-1).equals(b.nodes.get(b.nodes.size()-1))) {
613 Main.ds.setSelected(b);
614 new ReverseWayAction().actionPerformed(null);
615 cmdsCount++;
616 }
617 a = b;
618 }
619 Main.ds.setSelected(ways);
620 new CombineWayAction().actionPerformed(null);
621 cmdsCount++;
622 return (Way)(Main.ds.getSelectedWays().toArray())[0];
623 }
624
625 /**
626 * Finds all ways that may be part of a multipolygon relation and removes them from the given list.
627 * It will automatically combine "good" ways
628 * @param Collection<Way> The list of inner ways to check
629 * @param Way The newly created outer way
630 * @return ArrayList<Way> The List of newly created inner ways
631 */
632 private ArrayList<Way> fixMultigons(Collection<Way> uninterestingWays, Way outerWay) {
633 Collection<Node> innerNodes = getNodesFromWays(uninterestingWays);
634 Collection<Node> outerNodes = outerWay.nodes;
635
636 // The newly created inner ways. uninterestingWays is passed by reference and therefore modified in-place
637 ArrayList<Way> newInnerWays = new ArrayList<Way>();
638
639 // Now we need to find all inner ways that contain a remaining node, but no outer nodes
640 // Remaining nodes are those that contain to more than one way. All nodes that belong to an
641 // inner multigon part will have at least two ways, so we can use this to find which ways do
642 // belong to the multigon.
643 Collection<Way> possibleWays = new ArrayList<Way>();
644 wayIterator: for(Way w : uninterestingWays) {
645 boolean hasInnerNodes = false;
646 for(Node n : w.nodes) {
647 if(outerNodes.contains(n)) continue wayIterator;
648 if(!hasInnerNodes && innerNodes.contains(n)) hasInnerNodes = true;
649 }
650 if(!hasInnerNodes && w.nodes.size() >= 2) continue;
651 possibleWays.add(w);
652 }
653
654 // Join all ways that have one start/ending node in common
655 Way joined = null;
656 outerIterator: do {
657 joined = null;
658 for(Way w1 : possibleWays) {
659 if(w1.isClosed()) {
660 if(!wayIsCollapsed(w1)) {
661 uninterestingWays.remove(w1);
662 newInnerWays.add(w1);
663 }
664 joined = w1;
665 possibleWays.remove(w1);
666 continue outerIterator;
667 }
668 for(Way w2 : possibleWays) {
669 // w2 cannot be closed, otherwise it would have been removed above
670 if(!waysCanBeCombined(w1, w2)) continue;
671
672 ArrayList<Way> joinThem = new ArrayList<Way>();
673 joinThem.add(w1);
674 joinThem.add(w2);
675 uninterestingWays.removeAll(joinThem);
676 possibleWays.removeAll(joinThem);
677
678 // Although we joined the ways, we cannot simply assume that they are closed
679 joined = joinWays(joinThem);
680 uninterestingWays.add(joined);
681 possibleWays.add(joined);
682 continue outerIterator;
683 }
684 }
685 } while(joined != null);
686 return newInnerWays;
687 }
688
689 /**
690 * Checks if a way is collapsed (i.e. looks like <---->)
691 * @param Way A *closed* way to check if it is collapsed
692 * @return boolean If the closed way is collapsed or not
693 */
694 private boolean wayIsCollapsed(Way w) {
695 if(w.nodes.size() <= 3) return true;
696
697 // If a way contains more than one node twice, it must be collapsed (only start/end node may be the same)
698 Way x = new Way(w);
699 int count = 0;
700 for(Node n : w.nodes) {
701 x.nodes.remove(n);
702 if(x.nodes.contains(n)) count++;
703 if(count == 2) return true;
704 }
705 return false;
706 }
707
708 /**
709 * Checks if two ways share one starting/ending node
710 * @param Way first way
711 * @param Way second way
712 * @return boolean Wheter the ways share a starting/ending node or not
713 */
714 private boolean waysCanBeCombined(Way w1, Way w2) {
715 if(w1.equals(w2)) return false;
716
717 if(w1.nodes.get(0).equals(w2.nodes.get(0))) return true;
718 if(w1.nodes.get(0).equals(w2.nodes.get(w2.nodes.size()-1))) return true;
719
720 if(w1.nodes.get(w1.nodes.size()-1).equals(w2.nodes.get(0))) return true;
721 if(w1.nodes.get(w1.nodes.size()-1).equals(w2.nodes.get(w2.nodes.size()-1))) return true;
722
723 return false;
724 }
725
726 /**
727 * Will add own multipolygon relation to the "previously existing" relations. Fixup is done by fixRelations
728 * @param Collection<Way> List of already closed inner ways
729 * @param Way The outer way
730 * @param ArrayList<RelationRole> The list of relation with roles to add own relation to
731 */
732 private void addOwnMultigonRelation(Collection<Way> inner, Way outer, ArrayList<RelationRole> rels) {
733 if(inner.size() == 0) return;
734 // Create new multipolygon relation and add all inner ways to it
735 Relation newRel = new Relation();
736 newRel.put("type", "multipolygon");
737 for(Way w : inner)
738 newRel.members.add(new RelationMember("inner", w));
739 cmds.add(new AddCommand(newRel));
740
741 // We don't add outer to the relation because it will be handed to fixRelations()
742 // which will then do the remaining work. Collections are passed by reference, so no
743 // need to return it
744 rels.add(new RelationRole(newRel, "outer"));
745 //return rels;
746 }
747
748 /**
749 * Adds the previously removed relations again to the outer way. If there are multiple multipolygon
750 * relations where the joined areas were in "outer" role a new relation is created instead with all
751 * members of both. This function depends on multigon relations to be valid already, it won't fix them.
752 * @param ArrayList<RelationRole> List of relations with roles the (original) ways were part of
753 * @param Way The newly created outer area/way
754 */
755 private void fixRelations(ArrayList<RelationRole> rels, Way outer) {
756 ArrayList<RelationRole> multiouters = new ArrayList<RelationRole>();
757 for(RelationRole r : rels) {
758 if( r.rel.get("type") != null &&
759 r.rel.get("type").equalsIgnoreCase("multipolygon") &&
760 r.role.equalsIgnoreCase("outer")
761 ) {
762 multiouters.add(r);
763 continue;
764 }
765 // Add it back!
766 Relation newRel = new Relation(r.rel);
767 newRel.members.add(new RelationMember(r.role, outer));
768 cmds.add(new ChangeCommand(r.rel, newRel));
769 }
770
771 Relation newRel = null;
772 switch(multiouters.size()) {
773 case 0:
774 return;
775 case 1:
776 // Found only one to be part of a multipolygon relation, so just add it back as well
777 newRel = new Relation(multiouters.get(0).rel);
778 newRel.members.add(new RelationMember(multiouters.get(0).role, outer));
779 cmds.add(new ChangeCommand(multiouters.get(0).rel, newRel));
780 return;
781 default:
782 // Create a new relation with all previous members and (Way)outer as outer.
783 newRel = new Relation();
784 for(RelationRole r : multiouters) {
785 // Add members
786 for(RelationMember rm : r.rel.members)
787 if(!newRel.members.contains(rm)) newRel.members.add(rm);
788 // Add tags
789 for (String key : r.rel.keys.keySet()) {
790 newRel.put(key, r.rel.keys.get(key));
791 }
792 // Delete old relation
793 cmds.add(new DeleteCommand(r.rel));
794 }
795 newRel.members.add(new RelationMember("outer", outer));
796 cmds.add(new AddCommand(newRel));
797 }
798 }
799
800 /**
801 * @param Collection<Way> The List of Ways to remove all tags from
802 */
803 private void stripTags(Collection<Way> ways) {
804 for(Way w: ways) stripTags(w);
805 commitCommands("Remove tags from inner ways");
806 }
807
808 /**
809 * @param Way The Way to remove all tags from
810 */
811 private void stripTags(Way x) {
812 if(x.keys == null) return;
813 Way y = new Way(x);
814 for (String key : x.keys.keySet())
815 y.remove(key);
816 cmds.add(new ChangeCommand(x, y));
817 }
818
819 /**
820 * Takes the last cmdsCount actions back and combines them into a single action
821 * (for when the user wants to undo the join action)
822 * @param String The commit message to display
823 */
824 private void makeCommitsOneAction(String message) {
825 UndoRedoHandler ur = Main.main.undoRedo;
826 cmds.clear();
827 for(int i = ur.commands.size() - cmdsCount; i < ur.commands.size(); i++)
828 cmds.add(ur.commands.get(i));
829
830 for(int i = 0; i < cmdsCount; i++)
831 ur.undo();
832
833 commitCommands(message == null ? "Join Areas Function" : message);
834 cmdsCount = 0;
835 }
836}
Note: See TracBrowser for help on using the repository browser.