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

Last change on this file since 10548 was 10548, checked in by simon04, 8 years ago

Remove duplicated code

Use updateEnabledStateOnCurrentSelection introduced r10409

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