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

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

use IRelation in RelationListDialog and *RelationActions

  • Property svn:eol-style set to native
File size: 19.4 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 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}
Note: See TracBrowser for help on using the repository browser.