001// License: GPL. For details, see LICENSE file.
002package org.openstreetmap.josm.gui.tagging;
003
004import static org.openstreetmap.josm.tools.I18n.tr;
005import static org.openstreetmap.josm.tools.I18n.trc;
006import static org.openstreetmap.josm.tools.I18n.trn;
007
008import java.awt.Component;
009import java.awt.Dimension;
010import java.awt.GridBagLayout;
011import java.awt.Insets;
012import java.awt.event.ActionEvent;
013import java.io.File;
014import java.util.ArrayList;
015import java.util.Collection;
016import java.util.Collections;
017import java.util.EnumSet;
018import java.util.HashSet;
019import java.util.LinkedList;
020import java.util.List;
021import java.util.Map;
022
023import javax.swing.AbstractAction;
024import javax.swing.Action;
025import javax.swing.ImageIcon;
026import javax.swing.JLabel;
027import javax.swing.JPanel;
028import javax.swing.JToggleButton;
029import javax.swing.SwingUtilities;
030
031import org.openstreetmap.josm.Main;
032import org.openstreetmap.josm.actions.search.SearchCompiler;
033import org.openstreetmap.josm.actions.search.SearchCompiler.Match;
034import org.openstreetmap.josm.command.ChangePropertyCommand;
035import org.openstreetmap.josm.command.Command;
036import org.openstreetmap.josm.command.SequenceCommand;
037import org.openstreetmap.josm.data.osm.DataSet;
038import org.openstreetmap.josm.data.osm.OsmPrimitive;
039import org.openstreetmap.josm.data.osm.Relation;
040import org.openstreetmap.josm.data.osm.RelationMember;
041import org.openstreetmap.josm.data.osm.Tag;
042import org.openstreetmap.josm.gui.ExtendedDialog;
043import org.openstreetmap.josm.gui.MapView;
044import org.openstreetmap.josm.gui.dialogs.relation.RelationEditor;
045import org.openstreetmap.josm.gui.layer.Layer;
046import org.openstreetmap.josm.gui.preferences.ToolbarPreferences;
047import org.openstreetmap.josm.gui.tagging.TaggingPresetItems.Link;
048import org.openstreetmap.josm.gui.tagging.TaggingPresetItems.PresetLink;
049import org.openstreetmap.josm.gui.tagging.TaggingPresetItems.Role;
050import org.openstreetmap.josm.gui.tagging.TaggingPresetItems.Roles;
051import org.openstreetmap.josm.gui.util.GuiHelper;
052import org.openstreetmap.josm.tools.GBC;
053import org.openstreetmap.josm.tools.ImageProvider;
054import org.openstreetmap.josm.tools.ImageResource;
055import org.openstreetmap.josm.tools.Predicate;
056import org.openstreetmap.josm.tools.Utils;
057import org.openstreetmap.josm.tools.template_engine.ParseError;
058import org.openstreetmap.josm.tools.template_engine.TemplateEntry;
059import org.openstreetmap.josm.tools.template_engine.TemplateParser;
060import org.xml.sax.SAXException;
061
062/**
063 * This class read encapsulate one tagging preset. A class method can
064 * read in all predefined presets, either shipped with JOSM or that are
065 * in the config directory.
066 *
067 * It is also able to construct dialogs out of preset definitions.
068 * @since 294
069 */
070public class TaggingPreset extends AbstractAction implements MapView.LayerChangeListener, Predicate<OsmPrimitive> {
071
072    public static final int DIALOG_ANSWER_APPLY = 1;
073    public static final int DIALOG_ANSWER_NEW_RELATION = 2;
074    public static final int DIALOG_ANSWER_CANCEL = 3;
075
076    public TaggingPresetMenu group = null;
077    public String name;
078    public String name_context;
079    public String locale_name;
080    public boolean preset_name_label;
081    public static final String OPTIONAL_TOOLTIP_TEXT = "Optional tooltip text";
082
083    /**
084     * The types as preparsed collection.
085     */
086    public EnumSet<TaggingPresetType> types;
087    public List<TaggingPresetItem> data = new LinkedList<>();
088    public Roles roles;
089    public TemplateEntry nameTemplate;
090    public Match nameTemplateFilter;
091
092    /**
093     * Create an empty tagging preset. This will not have any items and
094     * will be an empty string as text. createPanel will return null.
095     * Use this as default item for "do not select anything".
096     */
097    public TaggingPreset() {
098        MapView.addLayerChangeListener(this);
099        updateEnabledState();
100    }
101
102    /**
103     * Change the display name without changing the toolbar value.
104     */
105    public void setDisplayName() {
106        putValue(Action.NAME, getName());
107        putValue("toolbar", "tagging_" + getRawName());
108        putValue(OPTIONAL_TOOLTIP_TEXT, (group != null ?
109                tr("Use preset ''{0}'' of group ''{1}''", getLocaleName(), group.getName()) :
110                    tr("Use preset ''{0}''", getLocaleName())));
111    }
112
113    public String getLocaleName() {
114        if(locale_name == null) {
115            if(name_context != null) {
116                locale_name = trc(name_context, TaggingPresetItems.fixPresetString(name));
117            } else {
118                locale_name = tr(TaggingPresetItems.fixPresetString(name));
119            }
120        }
121        return locale_name;
122    }
123
124    public String getName() {
125        return group != null ? group.getName() + "/" + getLocaleName() : getLocaleName();
126    }
127    public String getRawName() {
128        return group != null ? group.getRawName() + "/" + name : name;
129    }
130
131    /**
132     * Returns the preset icon.
133     * @return The preset icon, or {@code null} if none defined
134     * @since 6403
135     */
136    public final ImageIcon getIcon() {
137        Object icon = getValue(Action.SMALL_ICON);
138        if (icon instanceof ImageIcon) {
139            return (ImageIcon) icon;
140        }
141        return null;
142    }
143
144    /**
145     * Called from the XML parser to set the icon.
146     * This task is performed in the background in order to speedup startup.
147     */
148    public void setIcon(final String iconName) {
149        File arch = TaggingPresetReader.getZipIcons();
150        final Collection<String> s = Main.pref.getCollection("taggingpreset.icon.sources", null);
151        ImageProvider imgProv = new ImageProvider(iconName);
152        imgProv.setDirs(s);
153        imgProv.setId("presets");
154        imgProv.setArchive(arch);
155        imgProv.setOptional(true);
156        imgProv.getInBackground(new ImageProvider.ImageResourceCallback() {
157            @Override
158            public void finished(final ImageResource result) {
159                if (result != null) {
160                    GuiHelper.runInEDT(new Runnable() {
161                        @Override
162                        public void run() {
163                            result.getImageIcon(TaggingPreset.this);
164                        }
165                    });
166                } else {
167                    Main.warn("Could not get presets icon " + iconName);
168                }
169            }
170        });
171    }
172
173    /**
174     * Called from the XML parser to set the types this preset affects.
175     */
176    public void setType(String types) throws SAXException {
177        this.types = TaggingPresetItems.getType(types);
178    }
179
180    public void setName_template(String pattern) throws SAXException {
181        try {
182            this.nameTemplate = new TemplateParser(pattern).parse();
183        } catch (ParseError e) {
184            Main.error("Error while parsing " + pattern + ": " + e.getMessage());
185            throw new SAXException(e);
186        }
187    }
188
189    public void setName_template_filter(String filter) throws SAXException {
190        try {
191            this.nameTemplateFilter = SearchCompiler.compile(filter, false, false);
192        } catch (org.openstreetmap.josm.actions.search.SearchCompiler.ParseError e) {
193            Main.error("Error while parsing" + filter + ": " + e.getMessage());
194            throw new SAXException(e);
195        }
196    }
197
198    private static class PresetPanel extends JPanel {
199        boolean hasElements = false;
200        PresetPanel() {
201            super(new GridBagLayout());
202        }
203    }
204
205    public PresetPanel createPanel(Collection<OsmPrimitive> selected) {
206        if (data == null)
207            return null;
208        PresetPanel p = new PresetPanel();
209        List<Link> l = new LinkedList<>();
210        List<PresetLink> presetLink = new LinkedList<>();
211        if (types != null){
212            JPanel pp = new JPanel();
213            for (TaggingPresetType t : types) {
214                JLabel la = new JLabel(ImageProvider.get(t.getIconName()));
215                la.setToolTipText(tr("Elements of type {0} are supported.", tr(t.getName())));
216                pp.add(la);
217            }
218            p.add(pp, GBC.eol());
219        }
220        if (preset_name_label) {
221            TaggingPresetItems.Label.addLabel(p, getIcon(), getName());
222        }
223
224        boolean presetInitiallyMatches = !selected.isEmpty() && Utils.forAll(selected, this);
225        JPanel items = new JPanel(new GridBagLayout());
226        for (TaggingPresetItem i : data) {
227            if (i instanceof Link) {
228                l.add((Link) i);
229                p.hasElements = true;
230            } else if (i instanceof PresetLink) {
231                presetLink.add((PresetLink) i);
232            } else {
233                if (i.addToPanel(items, selected, presetInitiallyMatches)) {
234                    p.hasElements = true;
235                }
236            }
237        }
238        p.add(items, GBC.eol().fill());
239        if (selected.isEmpty() && !supportsRelation()) {
240            GuiHelper.setEnabledRec(items, false);
241        }
242
243        // add PresetLink
244        if (!presetLink.isEmpty()) {
245            p.add(new JLabel(tr("Edit also …")), GBC.eol().insets(0, 8, 0, 0));
246            for (PresetLink link : presetLink) {
247                link.addToPanel(p, selected, presetInitiallyMatches);
248            }
249        }
250
251        // add Link
252        for (Link link : l) {
253            link.addToPanel(p, selected, presetInitiallyMatches);
254        }
255
256        // "Add toolbar button"
257        JToggleButton tb = new JToggleButton(new ToolbarButtonAction());
258        tb.setFocusable(false);
259        p.add(tb, GBC.std(0,0).anchor(GBC.LINE_END));
260        return p;
261    }
262
263    public boolean isShowable() {
264        for (TaggingPresetItem i : data) {
265            if (!(i instanceof TaggingPresetItems.Optional || i instanceof TaggingPresetItems.Space || i instanceof TaggingPresetItems.Key))
266                return true;
267        }
268        return false;
269    }
270
271    public String suggestRoleForOsmPrimitive(OsmPrimitive osm) {
272        if (roles != null && osm != null) {
273            for (Role i : roles.roles) {
274                if (i.memberExpression != null && i.memberExpression.match(osm)
275                        && (i.types == null || i.types.isEmpty() || i.types.contains(TaggingPresetType.forPrimitive(osm)) )) {
276                    return i.key;
277                }
278            }
279        }
280        return null;
281    }
282
283    @Override
284    public void actionPerformed(ActionEvent e) {
285        if (Main.main == null) {
286            return;
287        }
288        DataSet ds = Main.main.getCurrentDataSet();
289        Collection<OsmPrimitive> participants = Collections.emptyList();
290        if (Main.main != null && ds != null) {
291            participants = ds.getSelected();
292        }
293
294        // Display dialog even if no data layer (used by preset-tagging-tester plugin)
295        Collection<OsmPrimitive> sel = createSelection(participants);
296        int answer = showDialog(sel, supportsRelation());
297
298        if (ds == null) {
299            return;
300        }
301
302        if (!sel.isEmpty() && answer == DIALOG_ANSWER_APPLY) {
303            Command cmd = createCommand(sel, getChangedTags());
304            if (cmd != null) {
305                Main.main.undoRedo.add(cmd);
306            }
307        } else if (answer == DIALOG_ANSWER_NEW_RELATION) {
308            final Relation r = new Relation();
309            final Collection<RelationMember> members = new HashSet<>();
310            for(Tag t : getChangedTags()) {
311                r.put(t.getKey(), t.getValue());
312            }
313            for (OsmPrimitive osm : ds.getSelected()) {
314                String role = suggestRoleForOsmPrimitive(osm);
315                RelationMember rm = new RelationMember(role == null ? "" : role, osm);
316                r.addMember(rm);
317                members.add(rm);
318            }
319            SwingUtilities.invokeLater(new Runnable() {
320                @Override
321                public void run() {
322                    RelationEditor.getEditor(Main.main.getEditLayer(), r, members).setVisible(true);
323                }
324            });
325        }
326        ds.setSelected(ds.getSelected()); // force update
327    }
328
329    private static class PresetDialog extends ExtendedDialog {
330        public PresetDialog(Component content, String title, ImageIcon icon, boolean disableApply, boolean showNewRelation) {
331            super(Main.parent, title,
332                    showNewRelation?
333                            new String[] { tr("Apply Preset"), tr("New relation"), tr("Cancel") }:
334                                new String[] { tr("Apply Preset"), tr("Cancel") },
335                                true);
336            if (icon != null)
337                setIconImage(icon.getImage());
338            contentInsets = new Insets(10,5,0,5);
339            if (showNewRelation) {
340                setButtonIcons(new String[] {"ok", "dialogs/addrelation", "cancel" });
341            } else {
342                setButtonIcons(new String[] {"ok", "cancel" });
343            }
344            setContent(content);
345            setDefaultButton(1);
346            setupDialog();
347            buttons.get(0).setEnabled(!disableApply);
348            buttons.get(0).setToolTipText(title);
349            // Prevent dialogs of being too narrow (fix #6261)
350            Dimension d = getSize();
351            if (d.width < 350) {
352                d.width = 350;
353                setSize(d);
354            }
355            showDialog();
356        }
357    }
358
359    public int showDialog(Collection<OsmPrimitive> sel, boolean showNewRelation) {
360        PresetPanel p = createPanel(sel);
361        if (p == null)
362            return DIALOG_ANSWER_CANCEL;
363
364        int answer = 1;
365        if (p.getComponentCount() != 0 && (sel.isEmpty() || p.hasElements)) {
366            String title = trn("Change {0} object", "Change {0} objects", sel.size(), sel.size());
367            if(sel.isEmpty()) {
368                if(originalSelectionEmpty) {
369                    title = tr("Nothing selected!");
370                } else {
371                    title = tr("Selection unsuitable!");
372                }
373            }
374
375            answer = new PresetDialog(p, title, preset_name_label ? null : (ImageIcon) getValue(Action.SMALL_ICON),
376                    sel.isEmpty(), showNewRelation).getValue();
377        }
378        if (!showNewRelation && answer == 2)
379            return DIALOG_ANSWER_CANCEL;
380        else
381            return answer;
382    }
383
384    /**
385     * True whenever the original selection given into createSelection was empty
386     */
387    private boolean originalSelectionEmpty = false;
388
389    /**
390     * Removes all unsuitable OsmPrimitives from the given list
391     * @param participants List of possible OsmPrimitives to tag
392     * @return Cleaned list with suitable OsmPrimitives only
393     */
394    public Collection<OsmPrimitive> createSelection(Collection<OsmPrimitive> participants) {
395        originalSelectionEmpty = participants.isEmpty();
396        Collection<OsmPrimitive> sel = new LinkedList<>();
397        for (OsmPrimitive osm : participants) {
398            if (typeMatches(EnumSet.of(TaggingPresetType.forPrimitive(osm)))) {
399                sel.add(osm);
400            }
401        }
402        return sel;
403    }
404
405    public List<Tag> getChangedTags() {
406        List<Tag> result = new ArrayList<>();
407        for (TaggingPresetItem i: data) {
408            i.addCommands(result);
409        }
410        return result;
411    }
412
413    public static Command createCommand(Collection<OsmPrimitive> sel, List<Tag> changedTags) {
414        List<Command> cmds = new ArrayList<>();
415        for (Tag tag: changedTags) {
416            cmds.add(new ChangePropertyCommand(sel, tag.getKey(), tag.getValue()));
417        }
418
419        if (cmds.size() == 0)
420            return null;
421        else if (cmds.size() == 1)
422            return cmds.get(0);
423        else
424            return new SequenceCommand(tr("Change Tags"), cmds);
425    }
426
427    private boolean supportsRelation() {
428        return types == null || types.contains(TaggingPresetType.RELATION);
429    }
430
431    protected final void updateEnabledState() {
432        setEnabled(Main.main != null && Main.main.getCurrentDataSet() != null);
433    }
434
435    @Override
436    public void activeLayerChange(Layer oldLayer, Layer newLayer) {
437        updateEnabledState();
438    }
439
440    @Override
441    public void layerAdded(Layer newLayer) {
442        updateEnabledState();
443    }
444
445    @Override
446    public void layerRemoved(Layer oldLayer) {
447        updateEnabledState();
448    }
449
450    @Override
451    public String toString() {
452        return (types == null?"":types) + " " + name;
453    }
454
455    public boolean typeMatches(Collection<TaggingPresetType> t) {
456        return t == null || types == null || types.containsAll(t);
457    }
458
459    @Override
460    public boolean evaluate(OsmPrimitive p) {
461        return matches(EnumSet.of(TaggingPresetType.forPrimitive(p)), p.getKeys(), false);
462    }
463
464    public boolean matches(Collection<TaggingPresetType> t, Map<String, String> tags, boolean onlyShowable) {
465        if (onlyShowable && !isShowable())
466            return false;
467        else if (!typeMatches(t))
468            return false;
469        boolean atLeastOnePositiveMatch = false;
470        for (TaggingPresetItem item : data) {
471            Boolean m = item.matches(tags);
472            if (m != null && !m)
473                return false;
474            else if (m != null) {
475                atLeastOnePositiveMatch = true;
476            }
477        }
478        return atLeastOnePositiveMatch;
479    }
480
481    public static Collection<TaggingPreset> getMatchingPresets(final Collection<TaggingPresetType> t, final Map<String, String> tags, final boolean onlyShowable) {
482        return Utils.filter(TaggingPresets.getTaggingPresets(), new Predicate<TaggingPreset>() {
483            @Override
484            public boolean evaluate(TaggingPreset object) {
485                return object.matches(t, tags, onlyShowable);
486            }
487        });
488    }
489
490    /**
491     * Action that adds or removes the button on main toolbar
492     */
493    public class ToolbarButtonAction extends AbstractAction {
494        private final int toolbarIndex;
495
496        /**
497         * Constructs a new {@code ToolbarButtonAction}.
498         */
499        public ToolbarButtonAction() {
500            super("", ImageProvider.get("dialogs", "pin"));
501            putValue(SHORT_DESCRIPTION, tr("Add or remove toolbar button"));
502            LinkedList<String> t = new LinkedList<>(ToolbarPreferences.getToolString());
503            toolbarIndex = t.indexOf(getToolbarString());
504            putValue(SELECTED_KEY, toolbarIndex >= 0);
505        }
506
507        @Override
508        public void actionPerformed(ActionEvent ae) {
509            String res = getToolbarString();
510            Main.toolbar.addCustomButton(res, toolbarIndex, true);
511        }
512    }
513
514    public String getToolbarString() {
515        ToolbarPreferences.ActionParser actionParser = new ToolbarPreferences.ActionParser(null);
516        return actionParser.saveAction(new ToolbarPreferences.ActionDefinition(this));
517    }
518}