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