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

Last change on this file since 12314 was 12188, checked in by michael2402, 7 years ago

Use OsmUtils constants.

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