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

Last change on this file since 17436 was 17436, checked in by guggis, 16 years ago

applied #3377: patch by xeen

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