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

Last change on this file since 2842 was 2842, checked in by mjulius, 14 years ago

fix messages for actions

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