001// License: GPL. For details, see LICENSE file.
002package org.openstreetmap.josm.actions;
003
004import static org.openstreetmap.josm.tools.I18n.tr;
005
006import java.awt.event.ActionEvent;
007import java.awt.event.KeyEvent;
008import java.util.ArrayList;
009import java.util.Arrays;
010import java.util.Collection;
011import java.util.Collections;
012import java.util.HashMap;
013import java.util.HashSet;
014import java.util.List;
015import java.util.Map;
016import java.util.Map.Entry;
017import java.util.Set;
018import java.util.TreeSet;
019
020import javax.swing.JOptionPane;
021import javax.swing.SwingUtilities;
022
023import org.openstreetmap.josm.Main;
024import org.openstreetmap.josm.command.AddCommand;
025import org.openstreetmap.josm.command.ChangeCommand;
026import org.openstreetmap.josm.command.ChangePropertyCommand;
027import org.openstreetmap.josm.command.Command;
028import org.openstreetmap.josm.command.SequenceCommand;
029import org.openstreetmap.josm.data.osm.MultipolygonBuilder;
030import org.openstreetmap.josm.data.osm.MultipolygonBuilder.JoinedPolygon;
031import org.openstreetmap.josm.data.osm.OsmPrimitive;
032import org.openstreetmap.josm.data.osm.Relation;
033import org.openstreetmap.josm.data.osm.RelationMember;
034import org.openstreetmap.josm.data.osm.Way;
035import org.openstreetmap.josm.gui.Notification;
036import org.openstreetmap.josm.gui.dialogs.relation.DownloadRelationTask;
037import org.openstreetmap.josm.gui.dialogs.relation.RelationEditor;
038import org.openstreetmap.josm.tools.Pair;
039import org.openstreetmap.josm.tools.Shortcut;
040import org.openstreetmap.josm.tools.Utils;
041
042/**
043 * Create multipolygon from selected ways automatically.
044 *
045 * New relation with type=multipolygon is created.
046 *
047 * If one or more of ways is already in relation with type=multipolygon or the
048 * way is not closed, then error is reported and no relation is created.
049 *
050 * The "inner" and "outer" roles are guessed automatically. First, bbox is
051 * calculated for each way. then the largest area is assumed to be outside and
052 * the rest inside. In cases with one "outside" area and several cut-ins, the
053 * guess should be always good ... In more complex (multiple outer areas) or
054 * buggy (inner and outer ways intersect) scenarios the result is likely to be
055 * wrong.
056 */
057public class CreateMultipolygonAction extends JosmAction {
058
059    private final boolean update;
060
061    /**
062     * Constructs a new {@code CreateMultipolygonAction}.
063     * @param update {@code true} if the multipolygon must be updated, {@code false} if it must be created
064     */
065    public CreateMultipolygonAction(final boolean update) {
066        super(getName(update), "multipoly_create", getName(update),
067                update  ? Shortcut.registerShortcut("tools:multipoly_update", tr("Tool: {0}", getName(true)), KeyEvent.VK_B, Shortcut.CTRL_SHIFT)
068                        : Shortcut.registerShortcut("tools:multipoly_create", tr("Tool: {0}", getName(false)), KeyEvent.VK_B, Shortcut.CTRL),
069                true, update ? "multipoly_update" : "multipoly_create", true);
070        this.update = update;
071    }
072
073    private static String getName(boolean update) {
074        return update ? tr("Update multipolygon") : tr("Create multipolygon");
075    }
076
077    private static class CreateUpdateMultipolygonTask implements Runnable {
078        private final Collection<Way> selectedWays;
079        private final Relation multipolygonRelation;
080
081        public CreateUpdateMultipolygonTask(Collection<Way> selectedWays, Relation multipolygonRelation) {
082            this.selectedWays = selectedWays;
083            this.multipolygonRelation = multipolygonRelation;
084        }
085
086        @Override
087        public void run() {
088            final Pair<SequenceCommand, Relation> commandAndRelation = createMultipolygonCommand(selectedWays, multipolygonRelation);
089            if (commandAndRelation == null) {
090                return;
091            }
092            final Command command = commandAndRelation.a;
093            final Relation relation = commandAndRelation.b;
094
095            // to avoid EDT violations
096            SwingUtilities.invokeLater(new Runnable() {
097                @Override
098                public void run() {
099                    Main.main.undoRedo.add(command);
100
101                    // Use 'SwingUtilities.invokeLater' to make sure the relationListDialog
102                    // knows about the new relation before we try to select it.
103                    // (Yes, we are already in event dispatch thread. But DatasetEventManager
104                    // uses 'SwingUtilities.invokeLater' to fire events so we have to do the same.)
105                    SwingUtilities.invokeLater(new Runnable() {
106                        @Override
107                        public void run() {
108                            Main.map.relationListDialog.selectRelation(relation);
109                            if (Main.pref.getBoolean("multipoly.show-relation-editor", false)) {
110                                //Open relation edit window, if set up in preferences
111                                RelationEditor editor = RelationEditor.getEditor(Main.main.getEditLayer(), relation, null);
112
113                                editor.setModal(true);
114                                editor.setVisible(true);
115                            }
116                        }
117                    });
118                }
119            });
120        }
121    }
122
123    @Override
124    public void actionPerformed(ActionEvent e) {
125        if (!Main.main.hasEditLayer()) {
126            new Notification(
127                    tr("No data loaded."))
128                    .setIcon(JOptionPane.WARNING_MESSAGE)
129                    .setDuration(Notification.TIME_SHORT)
130                    .show();
131            return;
132        }
133
134        final Collection<Way> selectedWays = Main.main.getCurrentDataSet().getSelectedWays();
135        final Collection<Relation> selectedRelations = Main.main.getCurrentDataSet().getSelectedRelations();
136
137        if (selectedWays.size() < 1) {
138            // Sometimes it make sense creating multipoly of only one way (so it will form outer way)
139            // and then splitting the way later (so there are multiple ways forming outer way)
140            new Notification(
141                    tr("You must select at least one way."))
142                    .setIcon(JOptionPane.INFORMATION_MESSAGE)
143                    .setDuration(Notification.TIME_SHORT)
144                    .show();
145            return;
146        }
147
148        final Relation multipolygonRelation = update
149                ? getSelectedMultipolygonRelation(selectedWays, selectedRelations)
150                : null;
151
152        // download incomplete relation if necessary
153        if (multipolygonRelation != null && (multipolygonRelation.isIncomplete() || multipolygonRelation.hasIncompleteMembers())) {
154            Main.worker.submit(new DownloadRelationTask(Collections.singleton(multipolygonRelation), Main.main.getEditLayer()));
155        }
156        // create/update multipolygon relation
157        Main.worker.submit(new CreateUpdateMultipolygonTask(selectedWays, multipolygonRelation));
158
159    }
160
161    private Relation getSelectedMultipolygonRelation() {
162        return getSelectedMultipolygonRelation(getCurrentDataSet().getSelectedWays(), getCurrentDataSet().getSelectedRelations());
163    }
164
165    private static Relation getSelectedMultipolygonRelation(Collection<Way> selectedWays, Collection<Relation> selectedRelations) {
166        if (selectedRelations.size() == 1 && "multipolygon".equals(selectedRelations.iterator().next().get("type"))) {
167            return selectedRelations.iterator().next();
168        } else {
169            final HashSet<Relation> relatedRelations = new HashSet<>();
170            for (final Way w : selectedWays) {
171                relatedRelations.addAll(Utils.filteredCollection(w.getReferrers(), Relation.class));
172            }
173            return relatedRelations.size() == 1 ? relatedRelations.iterator().next() : null;
174        }
175    }
176
177    /**
178     * Returns a {@link Pair} of the old multipolygon {@link Relation} (or null) and the newly created/modified multipolygon {@link Relation}.
179     */
180    public static Pair<Relation, Relation> updateMultipolygonRelation(Collection<Way> selectedWays, Relation selectedMultipolygonRelation) {
181
182        // add ways of existing relation to include them in polygon analysis
183        Set<Way> ways = new HashSet<>(selectedWays);
184        ways.addAll(selectedMultipolygonRelation.getMemberPrimitives(Way.class));
185
186        final MultipolygonBuilder polygon = analyzeWays(ways, true);
187        if (polygon == null) {
188            return null; //could not make multipolygon.
189        } else {
190            return Pair.create(selectedMultipolygonRelation, createRelation(polygon, new Relation(selectedMultipolygonRelation)));
191        }
192    }
193
194    /**
195     * Returns a {@link Pair} null and the newly created/modified multipolygon {@link Relation}.
196     */
197    public static Pair<Relation, Relation> createMultipolygonRelation(Collection<Way> selectedWays, boolean showNotif) {
198
199        final MultipolygonBuilder polygon = analyzeWays(selectedWays, showNotif);
200        if (polygon == null) {
201            return null; //could not make multipolygon.
202        } else {
203            return Pair.create(null, createRelation(polygon, new Relation()));
204        }
205    }
206
207    /**
208     * Returns a {@link Pair} of a multipolygon creating/modifying {@link Command} as well as the multipolygon {@link Relation}.
209     */
210    public static Pair<SequenceCommand, Relation> createMultipolygonCommand(Collection<Way> selectedWays, Relation selectedMultipolygonRelation) {
211
212        final Pair<Relation, Relation> rr = selectedMultipolygonRelation == null
213                ? createMultipolygonRelation(selectedWays, true)
214                : updateMultipolygonRelation(selectedWays, selectedMultipolygonRelation);
215        if (rr == null) {
216            return null;
217        }
218        final Relation existingRelation = rr.a;
219        final Relation relation = rr.b;
220
221        final List<Command> list = removeTagsFromWaysIfNeeded(relation);
222        final String commandName;
223        if (existingRelation == null) {
224            list.add(new AddCommand(relation));
225            commandName = getName(false);
226        } else {
227            list.add(new ChangeCommand(existingRelation, relation));
228            commandName = getName(true);
229        }
230        return Pair.create(new SequenceCommand(commandName, list), relation);
231    }
232
233    /** Enable this action only if something is selected */
234    @Override
235    protected void updateEnabledState() {
236        if (getCurrentDataSet() == null) {
237            setEnabled(false);
238        } else {
239            updateEnabledState(getCurrentDataSet().getSelected());
240        }
241    }
242
243    /**
244      * Enable this action only if something is selected
245      *
246      * @param selection the current selection, gets tested for emptyness
247      */
248    @Override
249    protected void updateEnabledState(Collection<? extends OsmPrimitive> selection) {
250        if (update) {
251            setEnabled(getSelectedMultipolygonRelation() != null);
252        } else {
253            setEnabled(!getCurrentDataSet().getSelectedWays().isEmpty());
254        }
255    }
256
257    /**
258     * This method analyzes ways and creates multipolygon.
259     * @param selectedWays list of selected ways
260     * @return <code>null</code>, if there was a problem with the ways.
261     */
262    private static MultipolygonBuilder analyzeWays(Collection<Way> selectedWays, boolean showNotif) {
263
264        MultipolygonBuilder pol = new MultipolygonBuilder();
265        String error = pol.makeFromWays(selectedWays);
266
267        if (error != null) {
268            if (showNotif) {
269                new Notification(error)
270                        .setIcon(JOptionPane.INFORMATION_MESSAGE)
271                        .show();
272            }
273            return null;
274        } else {
275            return pol;
276        }
277    }
278
279    /**
280     * Builds a relation from polygon ways.
281     * @param pol data storage class containing polygon information
282     * @return multipolygon relation
283     */
284    private static Relation createRelation(MultipolygonBuilder pol, final Relation rel) {
285        // Create new relation
286        rel.put("type", "multipolygon");
287        // Add ways to it
288        for (JoinedPolygon jway:pol.outerWays) {
289            addMembers(jway, rel, "outer");
290        }
291
292        for (JoinedPolygon jway:pol.innerWays) {
293            addMembers(jway, rel, "inner");
294        }
295        return rel;
296    }
297
298    private static void addMembers(JoinedPolygon polygon, Relation rel, String role) {
299        final int count = rel.getMembersCount();
300        final HashSet<Way> ways = new HashSet<>(polygon.ways);
301        for (int i = 0; i < count; i++) {
302            final RelationMember m = rel.getMember(i);
303            if (ways.contains(m.getMember()) && !role.equals(m.getRole())) {
304                rel.setMember(i, new RelationMember(role, m.getMember()));
305            }
306        }
307        ways.removeAll(rel.getMemberPrimitives());
308        for (final Way way : ways) {
309            rel.addMember(new RelationMember(role, way));
310        }
311    }
312
313    public static final List<String> DEFAULT_LINEAR_TAGS = Arrays.asList("barrier", "fence_type", "source");
314
315    /**
316     * This method removes tags/value pairs from inner and outer ways and put them on relation if necessary
317     * Function was extended in reltoolbox plugin by Zverikk and copied back to the core
318     * @param relation the multipolygon style relation to process
319     * @return a list of commands to execute
320     */
321    public static List<Command> removeTagsFromWaysIfNeeded(Relation relation) {
322        Map<String, String> values = new HashMap<>(relation.getKeys());
323
324        List<Way> innerWays = new ArrayList<>();
325        List<Way> outerWays = new ArrayList<>();
326
327        Set<String> conflictingKeys = new TreeSet<>();
328
329        for( RelationMember m : relation.getMembers() ) {
330
331            if( m.hasRole() && "inner".equals(m.getRole()) && m.isWay() && m.getWay().hasKeys() ) {
332                innerWays.add(m.getWay());
333            }
334
335            if( m.hasRole() && "outer".equals(m.getRole()) && m.isWay() && m.getWay().hasKeys() ) {
336                Way way = m.getWay();
337                outerWays.add(way);
338
339                for (String key : way.keySet()) {
340                    if (!values.containsKey(key)) { //relation values take precedence
341                        values.put(key, way.get(key));
342                    } else if (!relation.hasKey(key) && !values.get(key).equals(way.get(key))) {
343                        conflictingKeys.add(key);
344                    }
345                }
346            }
347        }
348
349        // filter out empty key conflicts - we need second iteration
350        if (!Main.pref.getBoolean("multipoly.alltags", false))
351            for (RelationMember m : relation.getMembers())
352                if (m.hasRole() && "outer".equals(m.getRole()) && m.isWay())
353                    for (String key : values.keySet())
354                        if (!m.getWay().hasKey(key) && !relation.hasKey(key))
355                            conflictingKeys.add(key);
356
357        for (String key : conflictingKeys)
358            values.remove(key);
359
360        for (String linearTag : Main.pref.getCollection("multipoly.lineartagstokeep", DEFAULT_LINEAR_TAGS))
361            values.remove(linearTag);
362
363        if ("coastline".equals(values.get("natural")))
364            values.remove("natural");
365
366        values.put("area", "yes");
367
368        List<Command> commands = new ArrayList<>();
369        boolean moveTags = Main.pref.getBoolean("multipoly.movetags", true);
370
371        for (Entry<String, String> entry : values.entrySet()) {
372            List<OsmPrimitive> affectedWays = new ArrayList<>();
373            String key = entry.getKey();
374            String value = entry.getValue();
375
376            for (Way way : innerWays) {
377                if (value.equals(way.get(key))) {
378                    affectedWays.add(way);
379                }
380            }
381
382            if (moveTags) {
383                // remove duplicated tags from outer ways
384                for( Way way : outerWays ) {
385                    if( way.hasKey(key) ) {
386                        affectedWays.add(way);
387                    }
388                }
389            }
390
391            if (!affectedWays.isEmpty()) {
392                // reset key tag on affected ways
393                commands.add(new ChangePropertyCommand(affectedWays, key, null));
394            }
395        }
396
397        if (moveTags) {
398            // add those tag values to the relation
399            boolean fixed = false;
400            Relation r2 = new Relation(relation);
401            for (Entry<String, String> entry : values.entrySet()) {
402                String key = entry.getKey();
403                if (!r2.hasKey(key) && !"area".equals(key) ) {
404                    if (relation.isNew())
405                        relation.put(key, entry.getValue());
406                    else
407                        r2.put(key, entry.getValue());
408                    fixed = true;
409                }
410            }
411            if (fixed && !relation.isNew())
412                commands.add(new ChangeCommand(relation, r2));
413        }
414
415        return commands;
416    }
417}