001// License: GPL. For details, see LICENSE file. 002package org.openstreetmap.josm.actions; 003 004import static org.openstreetmap.josm.tools.I18n.tr; 005 006import java.awt.event.ActionEvent; 007import java.awt.event.KeyEvent; 008import java.util.ArrayList; 009import java.util.Arrays; 010import java.util.Collection; 011import java.util.Collections; 012import java.util.HashMap; 013import java.util.HashSet; 014import java.util.List; 015import java.util.Map; 016import java.util.Map.Entry; 017import java.util.Set; 018import java.util.TreeSet; 019 020import javax.swing.JOptionPane; 021import javax.swing.SwingUtilities; 022 023import org.openstreetmap.josm.actions.relation.DownloadSelectedIncompleteMembersAction; 024import org.openstreetmap.josm.command.AddCommand; 025import org.openstreetmap.josm.command.ChangeCommand; 026import org.openstreetmap.josm.command.ChangePropertyCommand; 027import org.openstreetmap.josm.command.Command; 028import org.openstreetmap.josm.command.SequenceCommand; 029import org.openstreetmap.josm.data.osm.DataSet; 030import org.openstreetmap.josm.data.osm.MultipolygonBuilder; 031import org.openstreetmap.josm.data.osm.MultipolygonBuilder.JoinedPolygon; 032import org.openstreetmap.josm.data.osm.OsmPrimitive; 033import org.openstreetmap.josm.data.osm.OsmUtils; 034import org.openstreetmap.josm.data.osm.Relation; 035import org.openstreetmap.josm.data.osm.RelationMember; 036import org.openstreetmap.josm.data.osm.Way; 037import org.openstreetmap.josm.gui.MainApplication; 038import org.openstreetmap.josm.gui.Notification; 039import org.openstreetmap.josm.gui.dialogs.relation.DownloadRelationMemberTask; 040import org.openstreetmap.josm.gui.dialogs.relation.DownloadRelationTask; 041import org.openstreetmap.josm.gui.dialogs.relation.RelationEditor; 042import org.openstreetmap.josm.gui.dialogs.relation.sort.RelationSorter; 043import org.openstreetmap.josm.gui.layer.OsmDataLayer; 044import org.openstreetmap.josm.gui.util.GuiHelper; 045import org.openstreetmap.josm.spi.preferences.Config; 046import org.openstreetmap.josm.tools.Pair; 047import org.openstreetmap.josm.tools.Shortcut; 048import org.openstreetmap.josm.tools.Utils; 049 050/** 051 * Create multipolygon from selected ways automatically. 052 * 053 * New relation with type=multipolygon is created. 054 * 055 * If one or more of ways is already in relation with type=multipolygon or the 056 * way is not closed, then error is reported and no relation is created. 057 * 058 * The "inner" and "outer" roles are guessed automatically. First, bbox is 059 * calculated for each way. then the largest area is assumed to be outside and 060 * the rest inside. In cases with one "outside" area and several cut-ins, the 061 * guess should be always good ... In more complex (multiple outer areas) or 062 * buggy (inner and outer ways intersect) scenarios the result is likely to be 063 * wrong. 064 */ 065public class CreateMultipolygonAction extends JosmAction { 066 067 private final boolean update; 068 069 /** 070 * Constructs a new {@code CreateMultipolygonAction}. 071 * @param update {@code true} if the multipolygon must be updated, {@code false} if it must be created 072 */ 073 public CreateMultipolygonAction(final boolean update) { 074 super(getName(update), /* ICON */ "multipoly_create", getName(update), 075 /* atleast three lines for each shortcut or the server extractor fails */ 076 update ? Shortcut.registerShortcut("tools:multipoly_update", 077 tr("Tool: {0}", getName(true)), 078 KeyEvent.VK_B, Shortcut.CTRL_SHIFT) 079 : Shortcut.registerShortcut("tools:multipoly_create", 080 tr("Tool: {0}", getName(false)), 081 KeyEvent.VK_B, Shortcut.CTRL), 082 true, update ? "multipoly_update" : "multipoly_create", true); 083 this.update = update; 084 } 085 086 private static String getName(boolean update) { 087 return update ? tr("Update multipolygon") : tr("Create multipolygon"); 088 } 089 090 private static final class CreateUpdateMultipolygonTask implements Runnable { 091 private final Collection<Way> selectedWays; 092 private final Relation multipolygonRelation; 093 094 private CreateUpdateMultipolygonTask(Collection<Way> selectedWays, Relation multipolygonRelation) { 095 this.selectedWays = selectedWays; 096 this.multipolygonRelation = multipolygonRelation; 097 } 098 099 @Override 100 public void run() { 101 final Pair<SequenceCommand, Relation> commandAndRelation = createMultipolygonCommand(selectedWays, multipolygonRelation); 102 if (commandAndRelation == null) { 103 return; 104 } 105 final Command command = commandAndRelation.a; 106 final Relation relation = commandAndRelation.b; 107 108 // to avoid EDT violations 109 SwingUtilities.invokeLater(() -> { 110 MainApplication.undoRedo.add(command); 111 112 // Use 'SwingUtilities.invokeLater' to make sure the relationListDialog 113 // knows about the new relation before we try to select it. 114 // (Yes, we are already in event dispatch thread. But DatasetEventManager 115 // uses 'SwingUtilities.invokeLater' to fire events so we have to do the same.) 116 SwingUtilities.invokeLater(() -> { 117 MainApplication.getMap().relationListDialog.selectRelation(relation); 118 if (Config.getPref().getBoolean("multipoly.show-relation-editor", false)) { 119 //Open relation edit window, if set up in preferences 120 RelationEditor editor = RelationEditor.getEditor( 121 MainApplication.getLayerManager().getEditLayer(), relation, null); 122 editor.setModal(true); 123 editor.setVisible(true); 124 } else { 125 MainApplication.getLayerManager().getEditLayer().setRecentRelation(relation); 126 } 127 }); 128 }); 129 } 130 } 131 132 @Override 133 public void actionPerformed(ActionEvent e) { 134 DataSet dataSet = getLayerManager().getEditDataSet(); 135 if (dataSet == null) { 136 new Notification( 137 tr("No data loaded.")) 138 .setIcon(JOptionPane.WARNING_MESSAGE) 139 .setDuration(Notification.TIME_SHORT) 140 .show(); 141 return; 142 } 143 144 final Collection<Way> selectedWays = dataSet.getSelectedWays(); 145 146 if (selectedWays.isEmpty()) { 147 // Sometimes it make sense creating multipoly of only one way (so it will form outer way) 148 // and then splitting the way later (so there are multiple ways forming outer way) 149 new Notification( 150 tr("You must select at least one way.")) 151 .setIcon(JOptionPane.INFORMATION_MESSAGE) 152 .setDuration(Notification.TIME_SHORT) 153 .show(); 154 return; 155 } 156 157 final Collection<Relation> selectedRelations = dataSet.getSelectedRelations(); 158 final Relation multipolygonRelation = update 159 ? getSelectedMultipolygonRelation(selectedWays, selectedRelations) 160 : null; 161 162 // download incomplete relation or incomplete members if necessary 163 OsmDataLayer editLayer = getLayerManager().getEditLayer(); 164 if (multipolygonRelation != null && editLayer != null && editLayer.isDownloadable()) { 165 if (!multipolygonRelation.isNew() && multipolygonRelation.isIncomplete()) { 166 MainApplication.worker.submit( 167 new DownloadRelationTask(Collections.singleton(multipolygonRelation), editLayer)); 168 } else if (multipolygonRelation.hasIncompleteMembers()) { 169 MainApplication.worker.submit(new DownloadRelationMemberTask(multipolygonRelation, 170 Utils.filteredCollection( 171 DownloadSelectedIncompleteMembersAction.buildSetOfIncompleteMembers( 172 Collections.singleton(multipolygonRelation)), OsmPrimitive.class), 173 editLayer)); 174 } 175 } 176 // create/update multipolygon relation 177 MainApplication.worker.submit(new CreateUpdateMultipolygonTask(selectedWays, multipolygonRelation)); 178 } 179 180 private Relation getSelectedMultipolygonRelation() { 181 DataSet ds = getLayerManager().getEditDataSet(); 182 return getSelectedMultipolygonRelation(ds.getSelectedWays(), ds.getSelectedRelations()); 183 } 184 185 private static Relation getSelectedMultipolygonRelation(Collection<Way> selectedWays, Collection<Relation> selectedRelations) { 186 if (selectedRelations.size() == 1 && "multipolygon".equals(selectedRelations.iterator().next().get("type"))) { 187 return selectedRelations.iterator().next(); 188 } else { 189 final Set<Relation> relatedRelations = new HashSet<>(); 190 for (final Way w : selectedWays) { 191 relatedRelations.addAll(Utils.filteredCollection(w.getReferrers(), Relation.class)); 192 } 193 return relatedRelations.size() == 1 ? relatedRelations.iterator().next() : null; 194 } 195 } 196 197 /** 198 * Returns a {@link Pair} of the old multipolygon {@link Relation} (or null) and the newly created/modified multipolygon {@link Relation}. 199 * @param selectedWays selected ways 200 * @param selectedMultipolygonRelation selected multipolygon relation 201 * @return pair of old and new multipolygon relation 202 */ 203 public static Pair<Relation, Relation> updateMultipolygonRelation(Collection<Way> selectedWays, Relation selectedMultipolygonRelation) { 204 205 // add ways of existing relation to include them in polygon analysis 206 Set<Way> ways = new HashSet<>(selectedWays); 207 ways.addAll(selectedMultipolygonRelation.getMemberPrimitives(Way.class)); 208 209 final MultipolygonBuilder polygon = analyzeWays(ways, true); 210 if (polygon == null) { 211 return null; //could not make multipolygon. 212 } else { 213 return Pair.create(selectedMultipolygonRelation, createRelation(polygon, selectedMultipolygonRelation)); 214 } 215 } 216 217 /** 218 * Returns a {@link Pair} null and the newly created/modified multipolygon {@link Relation}. 219 * @param selectedWays selected ways 220 * @param showNotif if {@code true}, shows a notification if an error occurs 221 * @return pair of null and new multipolygon relation 222 */ 223 public static Pair<Relation, Relation> createMultipolygonRelation(Collection<Way> selectedWays, boolean showNotif) { 224 225 final MultipolygonBuilder polygon = analyzeWays(selectedWays, showNotif); 226 if (polygon == null) { 227 return null; //could not make multipolygon. 228 } else { 229 return Pair.create(null, createRelation(polygon, null)); 230 } 231 } 232 233 /** 234 * Returns a {@link Pair} of a multipolygon creating/modifying {@link Command} as well as the multipolygon {@link Relation}. 235 * @param selectedWays selected ways 236 * @param selectedMultipolygonRelation selected multipolygon relation 237 * @return pair of command and multipolygon relation 238 */ 239 public static Pair<SequenceCommand, Relation> createMultipolygonCommand(Collection<Way> selectedWays, 240 Relation selectedMultipolygonRelation) { 241 242 final Pair<Relation, Relation> rr = selectedMultipolygonRelation == null 243 ? createMultipolygonRelation(selectedWays, true) 244 : updateMultipolygonRelation(selectedWays, selectedMultipolygonRelation); 245 if (rr == null) { 246 return null; 247 } 248 final Relation existingRelation = rr.a; 249 final Relation relation = rr.b; 250 251 final List<Command> list = removeTagsFromWaysIfNeeded(relation); 252 final String commandName; 253 if (existingRelation == null) { 254 list.add(new AddCommand(selectedWays.iterator().next().getDataSet(), relation)); 255 commandName = getName(false); 256 } else { 257 list.add(new ChangeCommand(existingRelation, relation)); 258 commandName = getName(true); 259 } 260 return Pair.create(new SequenceCommand(commandName, list), relation); 261 } 262 263 /** Enable this action only if something is selected */ 264 @Override 265 protected void updateEnabledState() { 266 updateEnabledStateOnCurrentSelection(); 267 } 268 269 /** 270 * Enable this action only if something is selected 271 * 272 * @param selection the current selection, gets tested for emptyness 273 */ 274 @Override 275 protected void updateEnabledState(Collection<? extends OsmPrimitive> selection) { 276 DataSet ds = getLayerManager().getEditDataSet(); 277 if (ds == null) { 278 setEnabled(false); 279 } else if (update) { 280 setEnabled(getSelectedMultipolygonRelation() != null); 281 } else { 282 setEnabled(!getLayerManager().getEditDataSet().getSelectedWays().isEmpty()); 283 } 284 } 285 286 /** 287 * This method analyzes ways and creates multipolygon. 288 * @param selectedWays list of selected ways 289 * @param showNotif if {@code true}, shows a notification if an error occurs 290 * @return <code>null</code>, if there was a problem with the ways. 291 */ 292 private static MultipolygonBuilder analyzeWays(Collection<Way> selectedWays, boolean showNotif) { 293 294 MultipolygonBuilder pol = new MultipolygonBuilder(); 295 final String error = pol.makeFromWays(selectedWays); 296 297 if (error != null) { 298 if (showNotif) { 299 GuiHelper.runInEDT(() -> 300 new Notification(error) 301 .setIcon(JOptionPane.INFORMATION_MESSAGE) 302 .show()); 303 } 304 return null; 305 } else { 306 return pol; 307 } 308 } 309 310 /** 311 * Builds a relation from polygon ways. 312 * @param pol data storage class containing polygon information 313 * @param clone relation to clone, can be null 314 * @return multipolygon relation 315 */ 316 private static Relation createRelation(MultipolygonBuilder pol, Relation clone) { 317 // Create new relation 318 Relation rel = clone != null ? new Relation(clone) : new Relation(); 319 rel.put("type", "multipolygon"); 320 // Add ways to it 321 for (JoinedPolygon jway:pol.outerWays) { 322 addMembers(jway, rel, "outer"); 323 } 324 325 for (JoinedPolygon jway:pol.innerWays) { 326 addMembers(jway, rel, "inner"); 327 } 328 329 if (clone == null) { 330 rel.setMembers(RelationSorter.sortMembersByConnectivity(rel.getMembers())); 331 } 332 333 return rel; 334 } 335 336 private static void addMembers(JoinedPolygon polygon, Relation rel, String role) { 337 final int count = rel.getMembersCount(); 338 final Set<Way> ways = new HashSet<>(polygon.ways); 339 for (int i = 0; i < count; i++) { 340 final RelationMember m = rel.getMember(i); 341 if (ways.contains(m.getMember()) && !role.equals(m.getRole())) { 342 rel.setMember(i, new RelationMember(role, m.getMember())); 343 } 344 } 345 ways.removeAll(rel.getMemberPrimitivesList()); 346 for (final Way way : ways) { 347 rel.addMember(new RelationMember(role, way)); 348 } 349 } 350 351 private static final List<String> DEFAULT_LINEAR_TAGS = Arrays.asList("barrier", "fence_type", "source"); 352 353 /** 354 * This method removes tags/value pairs from inner and outer ways and put them on relation if necessary 355 * Function was extended in reltoolbox plugin by Zverikk and copied back to the core 356 * @param relation the multipolygon style relation to process 357 * @return a list of commands to execute 358 */ 359 public static List<Command> removeTagsFromWaysIfNeeded(Relation relation) { 360 Map<String, String> values = new HashMap<>(relation.getKeys()); 361 362 List<Way> innerWays = new ArrayList<>(); 363 List<Way> outerWays = new ArrayList<>(); 364 365 Set<String> conflictingKeys = new TreeSet<>(); 366 367 for (RelationMember m : relation.getMembers()) { 368 369 if (m.hasRole() && "inner".equals(m.getRole()) && m.isWay() && m.getWay().hasKeys()) { 370 innerWays.add(m.getWay()); 371 } 372 373 if (m.hasRole() && "outer".equals(m.getRole()) && m.isWay() && m.getWay().hasKeys()) { 374 Way way = m.getWay(); 375 outerWays.add(way); 376 377 for (String key : way.keySet()) { 378 if (!values.containsKey(key)) { //relation values take precedence 379 values.put(key, way.get(key)); 380 } else if (!relation.hasKey(key) && !values.get(key).equals(way.get(key))) { 381 conflictingKeys.add(key); 382 } 383 } 384 } 385 } 386 387 // filter out empty key conflicts - we need second iteration 388 if (!Config.getPref().getBoolean("multipoly.alltags", false)) { 389 for (RelationMember m : relation.getMembers()) { 390 if (m.hasRole() && "outer".equals(m.getRole()) && m.isWay()) { 391 for (String key : values.keySet()) { 392 if (!m.getWay().hasKey(key) && !relation.hasKey(key)) { 393 conflictingKeys.add(key); 394 } 395 } 396 } 397 } 398 } 399 400 for (String key : conflictingKeys) { 401 values.remove(key); 402 } 403 404 for (String linearTag : Config.getPref().getList("multipoly.lineartagstokeep", DEFAULT_LINEAR_TAGS)) { 405 values.remove(linearTag); 406 } 407 408 if ("coastline".equals(values.get("natural"))) 409 values.remove("natural"); 410 411 values.put("area", OsmUtils.TRUE_VALUE); 412 413 List<Command> commands = new ArrayList<>(); 414 boolean moveTags = Config.getPref().getBoolean("multipoly.movetags", true); 415 416 for (Entry<String, String> entry : values.entrySet()) { 417 List<OsmPrimitive> affectedWays = new ArrayList<>(); 418 String key = entry.getKey(); 419 String value = entry.getValue(); 420 421 for (Way way : innerWays) { 422 if (value.equals(way.get(key))) { 423 affectedWays.add(way); 424 } 425 } 426 427 if (moveTags) { 428 // remove duplicated tags from outer ways 429 for (Way way : outerWays) { 430 if (way.hasKey(key)) { 431 affectedWays.add(way); 432 } 433 } 434 } 435 436 if (!affectedWays.isEmpty()) { 437 // reset key tag on affected ways 438 commands.add(new ChangePropertyCommand(affectedWays, key, null)); 439 } 440 } 441 442 if (moveTags) { 443 // add those tag values to the relation 444 boolean fixed = false; 445 Relation r2 = new Relation(relation); 446 for (Entry<String, String> entry : values.entrySet()) { 447 String key = entry.getKey(); 448 if (!r2.hasKey(key) && !"area".equals(key)) { 449 if (relation.isNew()) 450 relation.put(key, entry.getValue()); 451 else 452 r2.put(key, entry.getValue()); 453 fixed = true; 454 } 455 } 456 if (fixed && !relation.isNew()) { 457 DataSet ds = relation.getDataSet(); 458 if (ds == null) { 459 ds = MainApplication.getLayerManager().getEditDataSet(); 460 } 461 commands.add(new ChangeCommand(ds, relation, r2)); 462 } 463 } 464 465 return commands; 466 } 467}