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