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

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

see #15182 - deprecate Main.worker, replace it by gui.MainApplication.worker + code refactoring to make sure only editor packages use it

  • Property svn:eol-style set to native
File size: 18.8 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.MainApplication;
39import org.openstreetmap.josm.gui.Notification;
40import org.openstreetmap.josm.gui.dialogs.relation.DownloadRelationMemberTask;
41import org.openstreetmap.josm.gui.dialogs.relation.DownloadRelationTask;
42import org.openstreetmap.josm.gui.dialogs.relation.RelationEditor;
43import org.openstreetmap.josm.gui.dialogs.relation.sort.RelationSorter;
44import org.openstreetmap.josm.gui.util.GuiHelper;
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 Main.main.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 (Main.pref.getBoolean("multipoly.show-relation-editor", false)) {
118 //Open relation edit window, if set up in preferences
119 RelationEditor editor = RelationEditor.getEditor(Main.getLayerManager().getEditLayer(), relation, null);
120 editor.setModal(true);
121 editor.setVisible(true);
122 } else {
123 Main.getLayerManager().getEditLayer().setRecentRelation(relation);
124 }
125 });
126 });
127 }
128 }
129
130 @Override
131 public void actionPerformed(ActionEvent e) {
132 DataSet dataSet = Main.getLayerManager().getEditDataSet();
133 if (dataSet == null) {
134 new Notification(
135 tr("No data loaded."))
136 .setIcon(JOptionPane.WARNING_MESSAGE)
137 .setDuration(Notification.TIME_SHORT)
138 .show();
139 return;
140 }
141
142 final Collection<Way> selectedWays = dataSet.getSelectedWays();
143
144 if (selectedWays.isEmpty()) {
145 // Sometimes it make sense creating multipoly of only one way (so it will form outer way)
146 // and then splitting the way later (so there are multiple ways forming outer way)
147 new Notification(
148 tr("You must select at least one way."))
149 .setIcon(JOptionPane.INFORMATION_MESSAGE)
150 .setDuration(Notification.TIME_SHORT)
151 .show();
152 return;
153 }
154
155 final Collection<Relation> selectedRelations = dataSet.getSelectedRelations();
156 final Relation multipolygonRelation = update
157 ? getSelectedMultipolygonRelation(selectedWays, selectedRelations)
158 : null;
159
160 // download incomplete relation or incomplete members if necessary
161 if (multipolygonRelation != null) {
162 if (!multipolygonRelation.isNew() && multipolygonRelation.isIncomplete()) {
163 MainApplication.worker.submit(new DownloadRelationTask(Collections.singleton(multipolygonRelation), Main.getLayerManager().getEditLayer()));
164 } else if (multipolygonRelation.hasIncompleteMembers()) {
165 MainApplication.worker.submit(new DownloadRelationMemberTask(multipolygonRelation,
166 DownloadSelectedIncompleteMembersAction.buildSetOfIncompleteMembers(Collections.singleton(multipolygonRelation)),
167 Main.getLayerManager().getEditLayer()));
168 }
169 }
170 // create/update multipolygon relation
171 MainApplication.worker.submit(new CreateUpdateMultipolygonTask(selectedWays, multipolygonRelation));
172 }
173
174 private Relation getSelectedMultipolygonRelation() {
175 DataSet ds = getLayerManager().getEditDataSet();
176 return getSelectedMultipolygonRelation(ds.getSelectedWays(), ds.getSelectedRelations());
177 }
178
179 private static Relation getSelectedMultipolygonRelation(Collection<Way> selectedWays, Collection<Relation> selectedRelations) {
180 if (selectedRelations.size() == 1 && "multipolygon".equals(selectedRelations.iterator().next().get("type"))) {
181 return selectedRelations.iterator().next();
182 } else {
183 final Set<Relation> relatedRelations = new HashSet<>();
184 for (final Way w : selectedWays) {
185 relatedRelations.addAll(Utils.filteredCollection(w.getReferrers(), Relation.class));
186 }
187 return relatedRelations.size() == 1 ? relatedRelations.iterator().next() : null;
188 }
189 }
190
191 /**
192 * Returns a {@link Pair} of the old multipolygon {@link Relation} (or null) and the newly created/modified multipolygon {@link Relation}.
193 * @param selectedWays selected ways
194 * @param selectedMultipolygonRelation selected multipolygon relation
195 * @return pair of old and new multipolygon relation
196 */
197 public static Pair<Relation, Relation> updateMultipolygonRelation(Collection<Way> selectedWays, Relation selectedMultipolygonRelation) {
198
199 // add ways of existing relation to include them in polygon analysis
200 Set<Way> ways = new HashSet<>(selectedWays);
201 ways.addAll(selectedMultipolygonRelation.getMemberPrimitives(Way.class));
202
203 final MultipolygonBuilder polygon = analyzeWays(ways, true);
204 if (polygon == null) {
205 return null; //could not make multipolygon.
206 } else {
207 return Pair.create(selectedMultipolygonRelation, createRelation(polygon, selectedMultipolygonRelation));
208 }
209 }
210
211 /**
212 * Returns a {@link Pair} null and the newly created/modified multipolygon {@link Relation}.
213 * @param selectedWays selected ways
214 * @param showNotif if {@code true}, shows a notification if an error occurs
215 * @return pair of null and new multipolygon relation
216 */
217 public static Pair<Relation, Relation> createMultipolygonRelation(Collection<Way> selectedWays, boolean showNotif) {
218
219 final MultipolygonBuilder polygon = analyzeWays(selectedWays, showNotif);
220 if (polygon == null) {
221 return null; //could not make multipolygon.
222 } else {
223 return Pair.create(null, createRelation(polygon, null));
224 }
225 }
226
227 /**
228 * Returns a {@link Pair} of a multipolygon creating/modifying {@link Command} as well as the multipolygon {@link Relation}.
229 * @param selectedWays selected ways
230 * @param selectedMultipolygonRelation selected multipolygon relation
231 * @return pair of command and multipolygon relation
232 */
233 public static Pair<SequenceCommand, Relation> createMultipolygonCommand(Collection<Way> selectedWays,
234 Relation selectedMultipolygonRelation) {
235
236 final Pair<Relation, Relation> rr = selectedMultipolygonRelation == null
237 ? createMultipolygonRelation(selectedWays, true)
238 : updateMultipolygonRelation(selectedWays, selectedMultipolygonRelation);
239 if (rr == null) {
240 return null;
241 }
242 final Relation existingRelation = rr.a;
243 final Relation relation = rr.b;
244
245 final List<Command> list = removeTagsFromWaysIfNeeded(relation);
246 final String commandName;
247 if (existingRelation == null) {
248 list.add(new AddCommand(relation));
249 commandName = getName(false);
250 } else {
251 list.add(new ChangeCommand(existingRelation, relation));
252 commandName = getName(true);
253 }
254 return Pair.create(new SequenceCommand(commandName, list), relation);
255 }
256
257 /** Enable this action only if something is selected */
258 @Override
259 protected void updateEnabledState() {
260 updateEnabledStateOnCurrentSelection();
261 }
262
263 /**
264 * Enable this action only if something is selected
265 *
266 * @param selection the current selection, gets tested for emptyness
267 */
268 @Override
269 protected void updateEnabledState(Collection<? extends OsmPrimitive> selection) {
270 DataSet ds = getLayerManager().getEditDataSet();
271 if (ds == null) {
272 setEnabled(false);
273 } else if (update) {
274 setEnabled(getSelectedMultipolygonRelation() != null);
275 } else {
276 setEnabled(!getLayerManager().getEditDataSet().getSelectedWays().isEmpty());
277 }
278 }
279
280 /**
281 * This method analyzes ways and creates multipolygon.
282 * @param selectedWays list of selected ways
283 * @param showNotif if {@code true}, shows a notification if an error occurs
284 * @return <code>null</code>, if there was a problem with the ways.
285 */
286 private static MultipolygonBuilder analyzeWays(Collection<Way> selectedWays, boolean showNotif) {
287
288 MultipolygonBuilder pol = new MultipolygonBuilder();
289 final String error = pol.makeFromWays(selectedWays);
290
291 if (error != null) {
292 if (showNotif) {
293 GuiHelper.runInEDT(() ->
294 new Notification(error)
295 .setIcon(JOptionPane.INFORMATION_MESSAGE)
296 .show());
297 }
298 return null;
299 } else {
300 return pol;
301 }
302 }
303
304 /**
305 * Builds a relation from polygon ways.
306 * @param pol data storage class containing polygon information
307 * @param clone relation to clone, can be null
308 * @return multipolygon relation
309 */
310 private static Relation createRelation(MultipolygonBuilder pol, Relation clone) {
311 // Create new relation
312 Relation rel = clone != null ? new Relation(clone) : new Relation();
313 rel.put("type", "multipolygon");
314 // Add ways to it
315 for (JoinedPolygon jway:pol.outerWays) {
316 addMembers(jway, rel, "outer");
317 }
318
319 for (JoinedPolygon jway:pol.innerWays) {
320 addMembers(jway, rel, "inner");
321 }
322
323 if (clone == null) {
324 rel.setMembers(RelationSorter.sortMembersByConnectivity(rel.getMembers()));
325 }
326
327 return rel;
328 }
329
330 private static void addMembers(JoinedPolygon polygon, Relation rel, String role) {
331 final int count = rel.getMembersCount();
332 final Set<Way> ways = new HashSet<>(polygon.ways);
333 for (int i = 0; i < count; i++) {
334 final RelationMember m = rel.getMember(i);
335 if (ways.contains(m.getMember()) && !role.equals(m.getRole())) {
336 rel.setMember(i, new RelationMember(role, m.getMember()));
337 }
338 }
339 ways.removeAll(rel.getMemberPrimitivesList());
340 for (final Way way : ways) {
341 rel.addMember(new RelationMember(role, way));
342 }
343 }
344
345 private static final List<String> DEFAULT_LINEAR_TAGS = Arrays.asList("barrier", "fence_type", "source");
346
347 /**
348 * This method removes tags/value pairs from inner and outer ways and put them on relation if necessary
349 * Function was extended in reltoolbox plugin by Zverikk and copied back to the core
350 * @param relation the multipolygon style relation to process
351 * @return a list of commands to execute
352 */
353 public static List<Command> removeTagsFromWaysIfNeeded(Relation relation) {
354 Map<String, String> values = new HashMap<>(relation.getKeys());
355
356 List<Way> innerWays = new ArrayList<>();
357 List<Way> outerWays = new ArrayList<>();
358
359 Set<String> conflictingKeys = new TreeSet<>();
360
361 for (RelationMember m : relation.getMembers()) {
362
363 if (m.hasRole() && "inner".equals(m.getRole()) && m.isWay() && m.getWay().hasKeys()) {
364 innerWays.add(m.getWay());
365 }
366
367 if (m.hasRole() && "outer".equals(m.getRole()) && m.isWay() && m.getWay().hasKeys()) {
368 Way way = m.getWay();
369 outerWays.add(way);
370
371 for (String key : way.keySet()) {
372 if (!values.containsKey(key)) { //relation values take precedence
373 values.put(key, way.get(key));
374 } else if (!relation.hasKey(key) && !values.get(key).equals(way.get(key))) {
375 conflictingKeys.add(key);
376 }
377 }
378 }
379 }
380
381 // filter out empty key conflicts - we need second iteration
382 if (!Main.pref.getBoolean("multipoly.alltags", false)) {
383 for (RelationMember m : relation.getMembers()) {
384 if (m.hasRole() && "outer".equals(m.getRole()) && m.isWay()) {
385 for (String key : values.keySet()) {
386 if (!m.getWay().hasKey(key) && !relation.hasKey(key)) {
387 conflictingKeys.add(key);
388 }
389 }
390 }
391 }
392 }
393
394 for (String key : conflictingKeys) {
395 values.remove(key);
396 }
397
398 for (String linearTag : Main.pref.getCollection("multipoly.lineartagstokeep", DEFAULT_LINEAR_TAGS)) {
399 values.remove(linearTag);
400 }
401
402 if ("coastline".equals(values.get("natural")))
403 values.remove("natural");
404
405 values.put("area", OsmUtils.TRUE_VALUE);
406
407 List<Command> commands = new ArrayList<>();
408 boolean moveTags = Main.pref.getBoolean("multipoly.movetags", true);
409
410 for (Entry<String, String> entry : values.entrySet()) {
411 List<OsmPrimitive> affectedWays = new ArrayList<>();
412 String key = entry.getKey();
413 String value = entry.getValue();
414
415 for (Way way : innerWays) {
416 if (value.equals(way.get(key))) {
417 affectedWays.add(way);
418 }
419 }
420
421 if (moveTags) {
422 // remove duplicated tags from outer ways
423 for (Way way : outerWays) {
424 if (way.hasKey(key)) {
425 affectedWays.add(way);
426 }
427 }
428 }
429
430 if (!affectedWays.isEmpty()) {
431 // reset key tag on affected ways
432 commands.add(new ChangePropertyCommand(affectedWays, key, null));
433 }
434 }
435
436 if (moveTags) {
437 // add those tag values to the relation
438 boolean fixed = false;
439 Relation r2 = new Relation(relation);
440 for (Entry<String, String> entry : values.entrySet()) {
441 String key = entry.getKey();
442 if (!r2.hasKey(key) && !"area".equals(key)) {
443 if (relation.isNew())
444 relation.put(key, entry.getValue());
445 else
446 r2.put(key, entry.getValue());
447 fixed = true;
448 }
449 }
450 if (fixed && !relation.isNew())
451 commands.add(new ChangeCommand(relation, r2));
452 }
453
454 return commands;
455 }
456}
Note: See TracBrowser for help on using the repository browser.