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

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

fix #8039, see #10456 - fix bugs with non-downloadable layers

  • Property svn:eol-style set to native
File size: 19.3 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.layer.OsmDataLayer;
44import org.openstreetmap.josm.gui.util.GuiHelper;
45import org.openstreetmap.josm.spi.preferences.Config;
46import org.openstreetmap.josm.tools.Pair;
47import org.openstreetmap.josm.tools.Shortcut;
48import org.openstreetmap.josm.tools.Utils;
49
50/**
51 * Create multipolygon from selected ways automatically.
52 *
53 * New relation with type=multipolygon is created.
54 *
55 * If one or more of ways is already in relation with type=multipolygon or the
56 * way is not closed, then error is reported and no relation is created.
57 *
58 * The "inner" and "outer" roles are guessed automatically. First, bbox is
59 * calculated for each way. then the largest area is assumed to be outside and
60 * the rest inside. In cases with one "outside" area and several cut-ins, the
61 * guess should be always good ... In more complex (multiple outer areas) or
62 * buggy (inner and outer ways intersect) scenarios the result is likely to be
63 * wrong.
64 */
65public class CreateMultipolygonAction extends JosmAction {
66
67 private final boolean update;
68
69 /**
70 * Constructs a new {@code CreateMultipolygonAction}.
71 * @param update {@code true} if the multipolygon must be updated, {@code false} if it must be created
72 */
73 public CreateMultipolygonAction(final boolean update) {
74 super(getName(update), /* ICON */ "multipoly_create", getName(update),
75 /* atleast three lines for each shortcut or the server extractor fails */
76 update ? Shortcut.registerShortcut("tools:multipoly_update",
77 tr("Tool: {0}", getName(true)),
78 KeyEvent.VK_B, Shortcut.CTRL_SHIFT)
79 : Shortcut.registerShortcut("tools:multipoly_create",
80 tr("Tool: {0}", getName(false)),
81 KeyEvent.VK_B, Shortcut.CTRL),
82 true, update ? "multipoly_update" : "multipoly_create", true);
83 this.update = update;
84 }
85
86 private static String getName(boolean update) {
87 return update ? tr("Update multipolygon") : tr("Create multipolygon");
88 }
89
90 private static final class CreateUpdateMultipolygonTask implements Runnable {
91 private final Collection<Way> selectedWays;
92 private final Relation multipolygonRelation;
93
94 private CreateUpdateMultipolygonTask(Collection<Way> selectedWays, Relation multipolygonRelation) {
95 this.selectedWays = selectedWays;
96 this.multipolygonRelation = multipolygonRelation;
97 }
98
99 @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 DownloadSelectedIncompleteMembersAction.buildSetOfIncompleteMembers(Collections.singleton(multipolygonRelation)),
171 editLayer));
172 }
173 }
174 // create/update multipolygon relation
175 MainApplication.worker.submit(new CreateUpdateMultipolygonTask(selectedWays, multipolygonRelation));
176 }
177
178 private Relation getSelectedMultipolygonRelation() {
179 DataSet ds = getLayerManager().getEditDataSet();
180 return getSelectedMultipolygonRelation(ds.getSelectedWays(), ds.getSelectedRelations());
181 }
182
183 private static Relation getSelectedMultipolygonRelation(Collection<Way> selectedWays, Collection<Relation> selectedRelations) {
184 if (selectedRelations.size() == 1 && "multipolygon".equals(selectedRelations.iterator().next().get("type"))) {
185 return selectedRelations.iterator().next();
186 } else {
187 final Set<Relation> relatedRelations = new HashSet<>();
188 for (final Way w : selectedWays) {
189 relatedRelations.addAll(Utils.filteredCollection(w.getReferrers(), Relation.class));
190 }
191 return relatedRelations.size() == 1 ? relatedRelations.iterator().next() : null;
192 }
193 }
194
195 /**
196 * Returns a {@link Pair} of the old multipolygon {@link Relation} (or null) and the newly created/modified multipolygon {@link Relation}.
197 * @param selectedWays selected ways
198 * @param selectedMultipolygonRelation selected multipolygon relation
199 * @return pair of old and new multipolygon relation
200 */
201 public static Pair<Relation, Relation> updateMultipolygonRelation(Collection<Way> selectedWays, Relation selectedMultipolygonRelation) {
202
203 // add ways of existing relation to include them in polygon analysis
204 Set<Way> ways = new HashSet<>(selectedWays);
205 ways.addAll(selectedMultipolygonRelation.getMemberPrimitives(Way.class));
206
207 final MultipolygonBuilder polygon = analyzeWays(ways, true);
208 if (polygon == null) {
209 return null; //could not make multipolygon.
210 } else {
211 return Pair.create(selectedMultipolygonRelation, createRelation(polygon, selectedMultipolygonRelation));
212 }
213 }
214
215 /**
216 * Returns a {@link Pair} null and the newly created/modified multipolygon {@link Relation}.
217 * @param selectedWays selected ways
218 * @param showNotif if {@code true}, shows a notification if an error occurs
219 * @return pair of null and new multipolygon relation
220 */
221 public static Pair<Relation, Relation> createMultipolygonRelation(Collection<Way> selectedWays, boolean showNotif) {
222
223 final MultipolygonBuilder polygon = analyzeWays(selectedWays, showNotif);
224 if (polygon == null) {
225 return null; //could not make multipolygon.
226 } else {
227 return Pair.create(null, createRelation(polygon, null));
228 }
229 }
230
231 /**
232 * Returns a {@link Pair} of a multipolygon creating/modifying {@link Command} as well as the multipolygon {@link Relation}.
233 * @param selectedWays selected ways
234 * @param selectedMultipolygonRelation selected multipolygon relation
235 * @return pair of command and multipolygon relation
236 */
237 public static Pair<SequenceCommand, Relation> createMultipolygonCommand(Collection<Way> selectedWays,
238 Relation selectedMultipolygonRelation) {
239
240 final Pair<Relation, Relation> rr = selectedMultipolygonRelation == null
241 ? createMultipolygonRelation(selectedWays, true)
242 : updateMultipolygonRelation(selectedWays, selectedMultipolygonRelation);
243 if (rr == null) {
244 return null;
245 }
246 final Relation existingRelation = rr.a;
247 final Relation relation = rr.b;
248
249 final List<Command> list = removeTagsFromWaysIfNeeded(relation);
250 final String commandName;
251 if (existingRelation == null) {
252 list.add(new AddCommand(selectedWays.iterator().next().getDataSet(), relation));
253 commandName = getName(false);
254 } else {
255 list.add(new ChangeCommand(existingRelation, relation));
256 commandName = getName(true);
257 }
258 return Pair.create(new SequenceCommand(commandName, list), relation);
259 }
260
261 /** Enable this action only if something is selected */
262 @Override
263 protected void updateEnabledState() {
264 updateEnabledStateOnCurrentSelection();
265 }
266
267 /**
268 * Enable this action only if something is selected
269 *
270 * @param selection the current selection, gets tested for emptyness
271 */
272 @Override
273 protected void updateEnabledState(Collection<? extends OsmPrimitive> selection) {
274 DataSet ds = getLayerManager().getEditDataSet();
275 if (ds == null) {
276 setEnabled(false);
277 } else if (update) {
278 setEnabled(getSelectedMultipolygonRelation() != null);
279 } else {
280 setEnabled(!getLayerManager().getEditDataSet().getSelectedWays().isEmpty());
281 }
282 }
283
284 /**
285 * This method analyzes ways and creates multipolygon.
286 * @param selectedWays list of selected ways
287 * @param showNotif if {@code true}, shows a notification if an error occurs
288 * @return <code>null</code>, if there was a problem with the ways.
289 */
290 private static MultipolygonBuilder analyzeWays(Collection<Way> selectedWays, boolean showNotif) {
291
292 MultipolygonBuilder pol = new MultipolygonBuilder();
293 final String error = pol.makeFromWays(selectedWays);
294
295 if (error != null) {
296 if (showNotif) {
297 GuiHelper.runInEDT(() ->
298 new Notification(error)
299 .setIcon(JOptionPane.INFORMATION_MESSAGE)
300 .show());
301 }
302 return null;
303 } else {
304 return pol;
305 }
306 }
307
308 /**
309 * Builds a relation from polygon ways.
310 * @param pol data storage class containing polygon information
311 * @param clone relation to clone, can be null
312 * @return multipolygon relation
313 */
314 private static Relation createRelation(MultipolygonBuilder pol, Relation clone) {
315 // Create new relation
316 Relation rel = clone != null ? new Relation(clone) : new Relation();
317 rel.put("type", "multipolygon");
318 // Add ways to it
319 for (JoinedPolygon jway:pol.outerWays) {
320 addMembers(jway, rel, "outer");
321 }
322
323 for (JoinedPolygon jway:pol.innerWays) {
324 addMembers(jway, rel, "inner");
325 }
326
327 if (clone == null) {
328 rel.setMembers(RelationSorter.sortMembersByConnectivity(rel.getMembers()));
329 }
330
331 return rel;
332 }
333
334 private static void addMembers(JoinedPolygon polygon, Relation rel, String role) {
335 final int count = rel.getMembersCount();
336 final Set<Way> ways = new HashSet<>(polygon.ways);
337 for (int i = 0; i < count; i++) {
338 final RelationMember m = rel.getMember(i);
339 if (ways.contains(m.getMember()) && !role.equals(m.getRole())) {
340 rel.setMember(i, new RelationMember(role, m.getMember()));
341 }
342 }
343 ways.removeAll(rel.getMemberPrimitivesList());
344 for (final Way way : ways) {
345 rel.addMember(new RelationMember(role, way));
346 }
347 }
348
349 private static final List<String> DEFAULT_LINEAR_TAGS = Arrays.asList("barrier", "fence_type", "source");
350
351 /**
352 * This method removes tags/value pairs from inner and outer ways and put them on relation if necessary
353 * Function was extended in reltoolbox plugin by Zverikk and copied back to the core
354 * @param relation the multipolygon style relation to process
355 * @return a list of commands to execute
356 */
357 public static List<Command> removeTagsFromWaysIfNeeded(Relation relation) {
358 Map<String, String> values = new HashMap<>(relation.getKeys());
359
360 List<Way> innerWays = new ArrayList<>();
361 List<Way> outerWays = new ArrayList<>();
362
363 Set<String> conflictingKeys = new TreeSet<>();
364
365 for (RelationMember m : relation.getMembers()) {
366
367 if (m.hasRole() && "inner".equals(m.getRole()) && m.isWay() && m.getWay().hasKeys()) {
368 innerWays.add(m.getWay());
369 }
370
371 if (m.hasRole() && "outer".equals(m.getRole()) && m.isWay() && m.getWay().hasKeys()) {
372 Way way = m.getWay();
373 outerWays.add(way);
374
375 for (String key : way.keySet()) {
376 if (!values.containsKey(key)) { //relation values take precedence
377 values.put(key, way.get(key));
378 } else if (!relation.hasKey(key) && !values.get(key).equals(way.get(key))) {
379 conflictingKeys.add(key);
380 }
381 }
382 }
383 }
384
385 // filter out empty key conflicts - we need second iteration
386 if (!Config.getPref().getBoolean("multipoly.alltags", false)) {
387 for (RelationMember m : relation.getMembers()) {
388 if (m.hasRole() && "outer".equals(m.getRole()) && m.isWay()) {
389 for (String key : values.keySet()) {
390 if (!m.getWay().hasKey(key) && !relation.hasKey(key)) {
391 conflictingKeys.add(key);
392 }
393 }
394 }
395 }
396 }
397
398 for (String key : conflictingKeys) {
399 values.remove(key);
400 }
401
402 for (String linearTag : Config.getPref().getList("multipoly.lineartagstokeep", DEFAULT_LINEAR_TAGS)) {
403 values.remove(linearTag);
404 }
405
406 if ("coastline".equals(values.get("natural")))
407 values.remove("natural");
408
409 values.put("area", OsmUtils.TRUE_VALUE);
410
411 List<Command> commands = new ArrayList<>();
412 boolean moveTags = Config.getPref().getBoolean("multipoly.movetags", true);
413
414 for (Entry<String, String> entry : values.entrySet()) {
415 List<OsmPrimitive> affectedWays = new ArrayList<>();
416 String key = entry.getKey();
417 String value = entry.getValue();
418
419 for (Way way : innerWays) {
420 if (value.equals(way.get(key))) {
421 affectedWays.add(way);
422 }
423 }
424
425 if (moveTags) {
426 // remove duplicated tags from outer ways
427 for (Way way : outerWays) {
428 if (way.hasKey(key)) {
429 affectedWays.add(way);
430 }
431 }
432 }
433
434 if (!affectedWays.isEmpty()) {
435 // reset key tag on affected ways
436 commands.add(new ChangePropertyCommand(affectedWays, key, null));
437 }
438 }
439
440 if (moveTags) {
441 // add those tag values to the relation
442 boolean fixed = false;
443 Relation r2 = new Relation(relation);
444 for (Entry<String, String> entry : values.entrySet()) {
445 String key = entry.getKey();
446 if (!r2.hasKey(key) && !"area".equals(key)) {
447 if (relation.isNew())
448 relation.put(key, entry.getValue());
449 else
450 r2.put(key, entry.getValue());
451 fixed = true;
452 }
453 }
454 if (fixed && !relation.isNew()) {
455 DataSet ds = relation.getDataSet();
456 if (ds == null) {
457 ds = MainApplication.getLayerManager().getEditDataSet();
458 }
459 commands.add(new ChangeCommand(ds, relation, r2));
460 }
461 }
462
463 return commands;
464 }
465}
Note: See TracBrowser for help on using the repository browser.