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

Last change on this file since 8684 was 8540, checked in by Don-vip, 9 years ago

fix remaining checkstyle issues

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