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