source: josm/trunk/src/org/openstreetmap/josm/actions/CreateMultipolygonAction.java@ 13186

Last change on this file since 13186 was 13067, checked in by Don-vip, 6 years ago

fix #15507 - Update multipolygon action no longer works (regression from r12726)

  • Property svn:eol-style set to native
File size: 19.1 KB
Line 
1// License: GPL. For details, see LICENSE file.
2package org.openstreetmap.josm.actions;
3
4import static org.openstreetmap.josm.tools.I18n.tr;
5
6import java.awt.event.ActionEvent;
7import java.awt.event.KeyEvent;
8import java.util.ArrayList;
9import java.util.Arrays;
10import java.util.Collection;
11import java.util.Collections;
12import java.util.HashMap;
13import java.util.HashSet;
14import java.util.List;
15import java.util.Map;
16import java.util.Map.Entry;
17import java.util.Set;
18import java.util.TreeSet;
19
20import javax.swing.JOptionPane;
21import javax.swing.SwingUtilities;
22
23import org.openstreetmap.josm.actions.relation.DownloadSelectedIncompleteMembersAction;
24import org.openstreetmap.josm.command.AddCommand;
25import org.openstreetmap.josm.command.ChangeCommand;
26import org.openstreetmap.josm.command.ChangePropertyCommand;
27import org.openstreetmap.josm.command.Command;
28import org.openstreetmap.josm.command.SequenceCommand;
29import org.openstreetmap.josm.data.osm.DataSet;
30import org.openstreetmap.josm.data.osm.MultipolygonBuilder;
31import org.openstreetmap.josm.data.osm.MultipolygonBuilder.JoinedPolygon;
32import org.openstreetmap.josm.data.osm.OsmPrimitive;
33import org.openstreetmap.josm.data.osm.OsmUtils;
34import org.openstreetmap.josm.data.osm.Relation;
35import org.openstreetmap.josm.data.osm.RelationMember;
36import org.openstreetmap.josm.data.osm.Way;
37import org.openstreetmap.josm.gui.MainApplication;
38import org.openstreetmap.josm.gui.Notification;
39import org.openstreetmap.josm.gui.dialogs.relation.DownloadRelationMemberTask;
40import org.openstreetmap.josm.gui.dialogs.relation.DownloadRelationTask;
41import org.openstreetmap.josm.gui.dialogs.relation.RelationEditor;
42import org.openstreetmap.josm.gui.dialogs.relation.sort.RelationSorter;
43import org.openstreetmap.josm.gui.util.GuiHelper;
44import org.openstreetmap.josm.spi.preferences.Config;
45import org.openstreetmap.josm.tools.Pair;
46import org.openstreetmap.josm.tools.Shortcut;
47import org.openstreetmap.josm.tools.Utils;
48
49/**
50 * Create multipolygon from selected ways automatically.
51 *
52 * New relation with type=multipolygon is created.
53 *
54 * If one or more of ways is already in relation with type=multipolygon or the
55 * way is not closed, then error is reported and no relation is created.
56 *
57 * The "inner" and "outer" roles are guessed automatically. First, bbox is
58 * calculated for each way. then the largest area is assumed to be outside and
59 * the rest inside. In cases with one "outside" area and several cut-ins, the
60 * guess should be always good ... In more complex (multiple outer areas) or
61 * buggy (inner and outer ways intersect) scenarios the result is likely to be
62 * wrong.
63 */
64public class CreateMultipolygonAction extends JosmAction {
65
66 private final boolean update;
67
68 /**
69 * Constructs a new {@code CreateMultipolygonAction}.
70 * @param update {@code true} if the multipolygon must be updated, {@code false} if it must be created
71 */
72 public CreateMultipolygonAction(final boolean update) {
73 super(getName(update), /* ICON */ "multipoly_create", getName(update),
74 /* atleast three lines for each shortcut or the server extractor fails */
75 update ? Shortcut.registerShortcut("tools:multipoly_update",
76 tr("Tool: {0}", getName(true)),
77 KeyEvent.VK_B, Shortcut.CTRL_SHIFT)
78 : Shortcut.registerShortcut("tools:multipoly_create",
79 tr("Tool: {0}", getName(false)),
80 KeyEvent.VK_B, Shortcut.CTRL),
81 true, update ? "multipoly_update" : "multipoly_create", true);
82 this.update = update;
83 }
84
85 private static String getName(boolean update) {
86 return update ? tr("Update multipolygon") : tr("Create multipolygon");
87 }
88
89 private static final class CreateUpdateMultipolygonTask implements Runnable {
90 private final Collection<Way> selectedWays;
91 private final Relation multipolygonRelation;
92
93 private CreateUpdateMultipolygonTask(Collection<Way> selectedWays, Relation multipolygonRelation) {
94 this.selectedWays = selectedWays;
95 this.multipolygonRelation = multipolygonRelation;
96 }
97
98 @Override
99 public void run() {
100 final Pair<SequenceCommand, Relation> commandAndRelation = createMultipolygonCommand(selectedWays, multipolygonRelation);
101 if (commandAndRelation == null) {
102 return;
103 }
104 final Command command = commandAndRelation.a;
105 final Relation relation = commandAndRelation.b;
106
107 // to avoid EDT violations
108 SwingUtilities.invokeLater(() -> {
109 MainApplication.undoRedo.add(command);
110
111 // Use 'SwingUtilities.invokeLater' to make sure the relationListDialog
112 // knows about the new relation before we try to select it.
113 // (Yes, we are already in event dispatch thread. But DatasetEventManager
114 // uses 'SwingUtilities.invokeLater' to fire events so we have to do the same.)
115 SwingUtilities.invokeLater(() -> {
116 MainApplication.getMap().relationListDialog.selectRelation(relation);
117 if (Config.getPref().getBoolean("multipoly.show-relation-editor", false)) {
118 //Open relation edit window, if set up in preferences
119 RelationEditor editor = RelationEditor.getEditor(
120 MainApplication.getLayerManager().getEditLayer(), relation, null);
121 editor.setModal(true);
122 editor.setVisible(true);
123 } else {
124 MainApplication.getLayerManager().getEditLayer().setRecentRelation(relation);
125 }
126 });
127 });
128 }
129 }
130
131 @Override
132 public void actionPerformed(ActionEvent e) {
133 DataSet dataSet = getLayerManager().getEditDataSet();
134 if (dataSet == null) {
135 new Notification(
136 tr("No data loaded."))
137 .setIcon(JOptionPane.WARNING_MESSAGE)
138 .setDuration(Notification.TIME_SHORT)
139 .show();
140 return;
141 }
142
143 final Collection<Way> selectedWays = dataSet.getSelectedWays();
144
145 if (selectedWays.isEmpty()) {
146 // Sometimes it make sense creating multipoly of only one way (so it will form outer way)
147 // and then splitting the way later (so there are multiple ways forming outer way)
148 new Notification(
149 tr("You must select at least one way."))
150 .setIcon(JOptionPane.INFORMATION_MESSAGE)
151 .setDuration(Notification.TIME_SHORT)
152 .show();
153 return;
154 }
155
156 final Collection<Relation> selectedRelations = dataSet.getSelectedRelations();
157 final Relation multipolygonRelation = update
158 ? getSelectedMultipolygonRelation(selectedWays, selectedRelations)
159 : null;
160
161 // download incomplete relation or incomplete members if necessary
162 if (multipolygonRelation != null) {
163 if (!multipolygonRelation.isNew() && multipolygonRelation.isIncomplete()) {
164 MainApplication.worker.submit(
165 new DownloadRelationTask(Collections.singleton(multipolygonRelation), getLayerManager().getEditLayer()));
166 } else if (multipolygonRelation.hasIncompleteMembers()) {
167 MainApplication.worker.submit(new DownloadRelationMemberTask(multipolygonRelation,
168 DownloadSelectedIncompleteMembersAction.buildSetOfIncompleteMembers(Collections.singleton(multipolygonRelation)),
169 getLayerManager().getEditLayer()));
170 }
171 }
172 // create/update multipolygon relation
173 MainApplication.worker.submit(new CreateUpdateMultipolygonTask(selectedWays, multipolygonRelation));
174 }
175
176 private Relation getSelectedMultipolygonRelation() {
177 DataSet ds = getLayerManager().getEditDataSet();
178 return getSelectedMultipolygonRelation(ds.getSelectedWays(), ds.getSelectedRelations());
179 }
180
181 private static Relation getSelectedMultipolygonRelation(Collection<Way> selectedWays, Collection<Relation> selectedRelations) {
182 if (selectedRelations.size() == 1 && "multipolygon".equals(selectedRelations.iterator().next().get("type"))) {
183 return selectedRelations.iterator().next();
184 } else {
185 final Set<Relation> relatedRelations = new HashSet<>();
186 for (final Way w : selectedWays) {
187 relatedRelations.addAll(Utils.filteredCollection(w.getReferrers(), Relation.class));
188 }
189 return relatedRelations.size() == 1 ? relatedRelations.iterator().next() : null;
190 }
191 }
192
193 /**
194 * Returns a {@link Pair} of the old multipolygon {@link Relation} (or null) and the newly created/modified multipolygon {@link Relation}.
195 * @param selectedWays selected ways
196 * @param selectedMultipolygonRelation selected multipolygon relation
197 * @return pair of old and new multipolygon relation
198 */
199 public static Pair<Relation, Relation> updateMultipolygonRelation(Collection<Way> selectedWays, Relation selectedMultipolygonRelation) {
200
201 // add ways of existing relation to include them in polygon analysis
202 Set<Way> ways = new HashSet<>(selectedWays);
203 ways.addAll(selectedMultipolygonRelation.getMemberPrimitives(Way.class));
204
205 final MultipolygonBuilder polygon = analyzeWays(ways, true);
206 if (polygon == null) {
207 return null; //could not make multipolygon.
208 } else {
209 return Pair.create(selectedMultipolygonRelation, createRelation(polygon, selectedMultipolygonRelation));
210 }
211 }
212
213 /**
214 * Returns a {@link Pair} null and the newly created/modified multipolygon {@link Relation}.
215 * @param selectedWays selected ways
216 * @param showNotif if {@code true}, shows a notification if an error occurs
217 * @return pair of null and new multipolygon relation
218 */
219 public static Pair<Relation, Relation> createMultipolygonRelation(Collection<Way> selectedWays, boolean showNotif) {
220
221 final MultipolygonBuilder polygon = analyzeWays(selectedWays, showNotif);
222 if (polygon == null) {
223 return null; //could not make multipolygon.
224 } else {
225 return Pair.create(null, createRelation(polygon, null));
226 }
227 }
228
229 /**
230 * Returns a {@link Pair} of a multipolygon creating/modifying {@link Command} as well as the multipolygon {@link Relation}.
231 * @param selectedWays selected ways
232 * @param selectedMultipolygonRelation selected multipolygon relation
233 * @return pair of command and multipolygon relation
234 */
235 public static Pair<SequenceCommand, Relation> createMultipolygonCommand(Collection<Way> selectedWays,
236 Relation selectedMultipolygonRelation) {
237
238 final Pair<Relation, Relation> rr = selectedMultipolygonRelation == null
239 ? createMultipolygonRelation(selectedWays, true)
240 : updateMultipolygonRelation(selectedWays, selectedMultipolygonRelation);
241 if (rr == null) {
242 return null;
243 }
244 final Relation existingRelation = rr.a;
245 final Relation relation = rr.b;
246
247 final List<Command> list = removeTagsFromWaysIfNeeded(relation);
248 final String commandName;
249 if (existingRelation == null) {
250 list.add(new AddCommand(selectedWays.iterator().next().getDataSet(), relation));
251 commandName = getName(false);
252 } else {
253 list.add(new ChangeCommand(existingRelation, relation));
254 commandName = getName(true);
255 }
256 return Pair.create(new SequenceCommand(commandName, list), relation);
257 }
258
259 /** Enable this action only if something is selected */
260 @Override
261 protected void updateEnabledState() {
262 updateEnabledStateOnCurrentSelection();
263 }
264
265 /**
266 * Enable this action only if something is selected
267 *
268 * @param selection the current selection, gets tested for emptyness
269 */
270 @Override
271 protected void updateEnabledState(Collection<? extends OsmPrimitive> selection) {
272 DataSet ds = getLayerManager().getEditDataSet();
273 if (ds == null) {
274 setEnabled(false);
275 } else if (update) {
276 setEnabled(getSelectedMultipolygonRelation() != null);
277 } else {
278 setEnabled(!getLayerManager().getEditDataSet().getSelectedWays().isEmpty());
279 }
280 }
281
282 /**
283 * This method analyzes ways and creates multipolygon.
284 * @param selectedWays list of selected ways
285 * @param showNotif if {@code true}, shows a notification if an error occurs
286 * @return <code>null</code>, if there was a problem with the ways.
287 */
288 private static MultipolygonBuilder analyzeWays(Collection<Way> selectedWays, boolean showNotif) {
289
290 MultipolygonBuilder pol = new MultipolygonBuilder();
291 final String error = pol.makeFromWays(selectedWays);
292
293 if (error != null) {
294 if (showNotif) {
295 GuiHelper.runInEDT(() ->
296 new Notification(error)
297 .setIcon(JOptionPane.INFORMATION_MESSAGE)
298 .show());
299 }
300 return null;
301 } else {
302 return pol;
303 }
304 }
305
306 /**
307 * Builds a relation from polygon ways.
308 * @param pol data storage class containing polygon information
309 * @param clone relation to clone, can be null
310 * @return multipolygon relation
311 */
312 private static Relation createRelation(MultipolygonBuilder pol, Relation clone) {
313 // Create new relation
314 Relation rel = clone != null ? new Relation(clone) : new Relation();
315 rel.put("type", "multipolygon");
316 // Add ways to it
317 for (JoinedPolygon jway:pol.outerWays) {
318 addMembers(jway, rel, "outer");
319 }
320
321 for (JoinedPolygon jway:pol.innerWays) {
322 addMembers(jway, rel, "inner");
323 }
324
325 if (clone == null) {
326 rel.setMembers(RelationSorter.sortMembersByConnectivity(rel.getMembers()));
327 }
328
329 return rel;
330 }
331
332 private static void addMembers(JoinedPolygon polygon, Relation rel, String role) {
333 final int count = rel.getMembersCount();
334 final Set<Way> ways = new HashSet<>(polygon.ways);
335 for (int i = 0; i < count; i++) {
336 final RelationMember m = rel.getMember(i);
337 if (ways.contains(m.getMember()) && !role.equals(m.getRole())) {
338 rel.setMember(i, new RelationMember(role, m.getMember()));
339 }
340 }
341 ways.removeAll(rel.getMemberPrimitivesList());
342 for (final Way way : ways) {
343 rel.addMember(new RelationMember(role, way));
344 }
345 }
346
347 private static final List<String> DEFAULT_LINEAR_TAGS = Arrays.asList("barrier", "fence_type", "source");
348
349 /**
350 * This method removes tags/value pairs from inner and outer ways and put them on relation if necessary
351 * Function was extended in reltoolbox plugin by Zverikk and copied back to the core
352 * @param relation the multipolygon style relation to process
353 * @return a list of commands to execute
354 */
355 public static List<Command> removeTagsFromWaysIfNeeded(Relation relation) {
356 Map<String, String> values = new HashMap<>(relation.getKeys());
357
358 List<Way> innerWays = new ArrayList<>();
359 List<Way> outerWays = new ArrayList<>();
360
361 Set<String> conflictingKeys = new TreeSet<>();
362
363 for (RelationMember m : relation.getMembers()) {
364
365 if (m.hasRole() && "inner".equals(m.getRole()) && m.isWay() && m.getWay().hasKeys()) {
366 innerWays.add(m.getWay());
367 }
368
369 if (m.hasRole() && "outer".equals(m.getRole()) && m.isWay() && m.getWay().hasKeys()) {
370 Way way = m.getWay();
371 outerWays.add(way);
372
373 for (String key : way.keySet()) {
374 if (!values.containsKey(key)) { //relation values take precedence
375 values.put(key, way.get(key));
376 } else if (!relation.hasKey(key) && !values.get(key).equals(way.get(key))) {
377 conflictingKeys.add(key);
378 }
379 }
380 }
381 }
382
383 // filter out empty key conflicts - we need second iteration
384 if (!Config.getPref().getBoolean("multipoly.alltags", false)) {
385 for (RelationMember m : relation.getMembers()) {
386 if (m.hasRole() && "outer".equals(m.getRole()) && m.isWay()) {
387 for (String key : values.keySet()) {
388 if (!m.getWay().hasKey(key) && !relation.hasKey(key)) {
389 conflictingKeys.add(key);
390 }
391 }
392 }
393 }
394 }
395
396 for (String key : conflictingKeys) {
397 values.remove(key);
398 }
399
400 for (String linearTag : Config.getPref().getList("multipoly.lineartagstokeep", DEFAULT_LINEAR_TAGS)) {
401 values.remove(linearTag);
402 }
403
404 if ("coastline".equals(values.get("natural")))
405 values.remove("natural");
406
407 values.put("area", OsmUtils.TRUE_VALUE);
408
409 List<Command> commands = new ArrayList<>();
410 boolean moveTags = Config.getPref().getBoolean("multipoly.movetags", true);
411
412 for (Entry<String, String> entry : values.entrySet()) {
413 List<OsmPrimitive> affectedWays = new ArrayList<>();
414 String key = entry.getKey();
415 String value = entry.getValue();
416
417 for (Way way : innerWays) {
418 if (value.equals(way.get(key))) {
419 affectedWays.add(way);
420 }
421 }
422
423 if (moveTags) {
424 // remove duplicated tags from outer ways
425 for (Way way : outerWays) {
426 if (way.hasKey(key)) {
427 affectedWays.add(way);
428 }
429 }
430 }
431
432 if (!affectedWays.isEmpty()) {
433 // reset key tag on affected ways
434 commands.add(new ChangePropertyCommand(affectedWays, key, null));
435 }
436 }
437
438 if (moveTags) {
439 // add those tag values to the relation
440 boolean fixed = false;
441 Relation r2 = new Relation(relation);
442 for (Entry<String, String> entry : values.entrySet()) {
443 String key = entry.getKey();
444 if (!r2.hasKey(key) && !"area".equals(key)) {
445 if (relation.isNew())
446 relation.put(key, entry.getValue());
447 else
448 r2.put(key, entry.getValue());
449 fixed = true;
450 }
451 }
452 if (fixed && !relation.isNew()) {
453 DataSet ds = relation.getDataSet();
454 if (ds == null) {
455 ds = MainApplication.getLayerManager().getEditDataSet();
456 }
457 commands.add(new ChangeCommand(ds, relation, r2));
458 }
459 }
460
461 return commands;
462 }
463}
Note: See TracBrowser for help on using the repository browser.