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

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

Encalupse OsmPrimitive.incomplete

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