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

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

see #15229 - deprecate Main*.undoRedo - make UndoRedoHandler a singleton

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