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