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

Last change on this file since 10436 was 10413, checked in by Don-vip, 8 years ago

fix #12983 - replace calls to Main.main.get[Active|Edit]Layer() by Main.getLayerManager().get[Active|Edit]Layer() - gsoc-core

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