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