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

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

remove extra whitespaces

  • Property svn:eol-style set to native
File size: 17.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.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, Relation selectedMultipolygonRelation) {
224
225 final Pair<Relation, Relation> rr = selectedMultipolygonRelation == null
226 ? createMultipolygonRelation(selectedWays, true)
227 : updateMultipolygonRelation(selectedWays, selectedMultipolygonRelation);
228 if (rr == null) {
229 return null;
230 }
231 final Relation existingRelation = rr.a;
232 final Relation relation = rr.b;
233
234 final List<Command> list = removeTagsFromWaysIfNeeded(relation);
235 final String commandName;
236 if (existingRelation == null) {
237 list.add(new AddCommand(relation));
238 commandName = getName(false);
239 } else {
240 list.add(new ChangeCommand(existingRelation, relation));
241 commandName = getName(true);
242 }
243 return Pair.create(new SequenceCommand(commandName, list), relation);
244 }
245
246 /** Enable this action only if something is selected */
247 @Override
248 protected void updateEnabledState() {
249 if (getCurrentDataSet() == null) {
250 setEnabled(false);
251 } else {
252 updateEnabledState(getCurrentDataSet().getSelected());
253 }
254 }
255
256 /**
257 * Enable this action only if something is selected
258 *
259 * @param selection the current selection, gets tested for emptyness
260 */
261 @Override
262 protected void updateEnabledState(Collection<? extends OsmPrimitive> selection) {
263 if (getCurrentDataSet() == null) {
264 setEnabled(false);
265 } else if (update) {
266 setEnabled(getSelectedMultipolygonRelation() != null);
267 } else {
268 setEnabled(!getCurrentDataSet().getSelectedWays().isEmpty());
269 }
270 }
271
272 /**
273 * This method analyzes ways and creates multipolygon.
274 * @param selectedWays list of selected ways
275 * @return <code>null</code>, if there was a problem with the ways.
276 */
277 private static MultipolygonBuilder analyzeWays(Collection<Way> selectedWays, boolean showNotif) {
278
279 MultipolygonBuilder pol = new MultipolygonBuilder();
280 final String error = pol.makeFromWays(selectedWays);
281
282 if (error != null) {
283 if (showNotif) {
284 GuiHelper.runInEDT(new Runnable() {
285 @Override
286 public void run() {
287 new Notification(error)
288 .setIcon(JOptionPane.INFORMATION_MESSAGE)
289 .show();
290 }
291 });
292 }
293 return null;
294 } else {
295 return pol;
296 }
297 }
298
299 /**
300 * Builds a relation from polygon ways.
301 * @param pol data storage class containing polygon information
302 * @return multipolygon relation
303 */
304 private static Relation createRelation(MultipolygonBuilder pol, Relation clone) {
305 // Create new relation
306 Relation rel = clone != null ? new Relation(clone) : new Relation();
307 rel.put("type", "multipolygon");
308 // Add ways to it
309 for (JoinedPolygon jway:pol.outerWays) {
310 addMembers(jway, rel, "outer");
311 }
312
313 for (JoinedPolygon jway:pol.innerWays) {
314 addMembers(jway, rel, "inner");
315 }
316 return rel;
317 }
318
319 private static void addMembers(JoinedPolygon polygon, Relation rel, String role) {
320 final int count = rel.getMembersCount();
321 final Set<Way> ways = new HashSet<>(polygon.ways);
322 for (int i = 0; i < count; i++) {
323 final RelationMember m = rel.getMember(i);
324 if (ways.contains(m.getMember()) && !role.equals(m.getRole())) {
325 rel.setMember(i, new RelationMember(role, m.getMember()));
326 }
327 }
328 ways.removeAll(rel.getMemberPrimitives());
329 for (final Way way : ways) {
330 rel.addMember(new RelationMember(role, way));
331 }
332 }
333
334 public static final List<String> DEFAULT_LINEAR_TAGS = Arrays.asList("barrier", "fence_type", "source");
335
336 /**
337 * This method removes tags/value pairs from inner and outer ways and put them on relation if necessary
338 * Function was extended in reltoolbox plugin by Zverikk and copied back to the core
339 * @param relation the multipolygon style relation to process
340 * @return a list of commands to execute
341 */
342 public static List<Command> removeTagsFromWaysIfNeeded(Relation relation) {
343 Map<String, String> values = new HashMap<>(relation.getKeys());
344
345 List<Way> innerWays = new ArrayList<>();
346 List<Way> outerWays = new ArrayList<>();
347
348 Set<String> conflictingKeys = new TreeSet<>();
349
350 for (RelationMember m : relation.getMembers()) {
351
352 if (m.hasRole() && "inner".equals(m.getRole()) && m.isWay() && m.getWay().hasKeys()) {
353 innerWays.add(m.getWay());
354 }
355
356 if (m.hasRole() && "outer".equals(m.getRole()) && m.isWay() && m.getWay().hasKeys()) {
357 Way way = m.getWay();
358 outerWays.add(way);
359
360 for (String key : way.keySet()) {
361 if (!values.containsKey(key)) { //relation values take precedence
362 values.put(key, way.get(key));
363 } else if (!relation.hasKey(key) && !values.get(key).equals(way.get(key))) {
364 conflictingKeys.add(key);
365 }
366 }
367 }
368 }
369
370 // filter out empty key conflicts - we need second iteration
371 if (!Main.pref.getBoolean("multipoly.alltags", false))
372 for (RelationMember m : relation.getMembers())
373 if (m.hasRole() && "outer".equals(m.getRole()) && m.isWay())
374 for (String key : values.keySet())
375 if (!m.getWay().hasKey(key) && !relation.hasKey(key))
376 conflictingKeys.add(key);
377
378 for (String key : conflictingKeys)
379 values.remove(key);
380
381 for (String linearTag : Main.pref.getCollection("multipoly.lineartagstokeep", DEFAULT_LINEAR_TAGS))
382 values.remove(linearTag);
383
384 if ("coastline".equals(values.get("natural")))
385 values.remove("natural");
386
387 values.put("area", "yes");
388
389 List<Command> commands = new ArrayList<>();
390 boolean moveTags = Main.pref.getBoolean("multipoly.movetags", true);
391
392 for (Entry<String, String> entry : values.entrySet()) {
393 List<OsmPrimitive> affectedWays = new ArrayList<>();
394 String key = entry.getKey();
395 String value = entry.getValue();
396
397 for (Way way : innerWays) {
398 if (value.equals(way.get(key))) {
399 affectedWays.add(way);
400 }
401 }
402
403 if (moveTags) {
404 // remove duplicated tags from outer ways
405 for (Way way : outerWays) {
406 if (way.hasKey(key)) {
407 affectedWays.add(way);
408 }
409 }
410 }
411
412 if (!affectedWays.isEmpty()) {
413 // reset key tag on affected ways
414 commands.add(new ChangePropertyCommand(affectedWays, key, null));
415 }
416 }
417
418 if (moveTags) {
419 // add those tag values to the relation
420 boolean fixed = false;
421 Relation r2 = new Relation(relation);
422 for (Entry<String, String> entry : values.entrySet()) {
423 String key = entry.getKey();
424 if (!r2.hasKey(key) && !"area".equals(key)) {
425 if (relation.isNew())
426 relation.put(key, entry.getValue());
427 else
428 r2.put(key, entry.getValue());
429 fixed = true;
430 }
431 }
432 if (fixed && !relation.isNew())
433 commands.add(new ChangeCommand(relation, r2));
434 }
435
436 return commands;
437 }
438}
Note: See TracBrowser for help on using the repository browser.