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

Last change on this file since 2575 was 2575, checked in by stoecker, 14 years ago

include utilsplugin, fix #4086

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