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.MapView;
046import org.openstreetmap.josm.gui.Notification;
047import org.openstreetmap.josm.gui.dialogs.relation.RelationEditor;
048import org.openstreetmap.josm.gui.layer.Layer;
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 MapView.LayerChangeListener, 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 Set<TaggingPresetType> types;
099    public 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        MapView.addLayerChangeListener(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.getImageIcon(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 (org.openstreetmap.josm.actions.search.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    public PresetPanel createPanel(Collection<OsmPrimitive> selected) {
241        if (data == null)
242            return null;
243        PresetPanel p = new PresetPanel();
244        List<Link> l = new LinkedList<>();
245        List<PresetLink> presetLink = new LinkedList<>();
246        if (types != null) {
247            JPanel pp = new JPanel();
248            for (TaggingPresetType t : types) {
249                JLabel la = new JLabel(ImageProvider.get(t.getIconName()));
250                la.setToolTipText(tr("Elements of type {0} are supported.", tr(t.getName())));
251                pp.add(la);
252            }
253            p.add(pp, GBC.eol());
254        }
255        if (preset_name_label) {
256            Label.addLabel(p, getIcon(), getName());
257        }
258
259        boolean presetInitiallyMatches = !selected.isEmpty() && Utils.forAll(selected, this);
260        JPanel items = new JPanel(new GridBagLayout());
261        for (TaggingPresetItem i : data) {
262            if (i instanceof Link) {
263                l.add((Link) i);
264                p.hasElements = true;
265            } else if (i instanceof PresetLink) {
266                presetLink.add((PresetLink) i);
267            } else {
268                if (i.addToPanel(items, selected, presetInitiallyMatches)) {
269                    p.hasElements = true;
270                }
271            }
272        }
273        p.add(items, GBC.eol().fill());
274        if (selected.isEmpty() && !supportsRelation()) {
275            GuiHelper.setEnabledRec(items, false);
276        }
277
278        // add PresetLink
279        if (!presetLink.isEmpty()) {
280            p.add(new JLabel(tr("Edit also …")), GBC.eol().insets(0, 8, 0, 0));
281            for (PresetLink link : presetLink) {
282                link.addToPanel(p, selected, presetInitiallyMatches);
283            }
284        }
285
286        // add Link
287        for (Link link : l) {
288            link.addToPanel(p, selected, presetInitiallyMatches);
289        }
290
291        // "Add toolbar button"
292        JToggleButton tb = new JToggleButton(new ToolbarButtonAction());
293        tb.setFocusable(false);
294        p.add(tb, GBC.std(0, 0).anchor(GBC.LINE_END));
295        return p;
296    }
297
298    /**
299     * Determines whether a dialog can be shown for this preset, i.e., at least one tag can/must be set by the user.
300     *
301     * @return {@code true} if a dialog can be shown for this preset
302     */
303    public boolean isShowable() {
304        for (TaggingPresetItem i : data) {
305            if (!(i instanceof Optional || i instanceof Space || i instanceof Key))
306                return true;
307        }
308        return false;
309    }
310
311    public String suggestRoleForOsmPrimitive(OsmPrimitive osm) {
312        if (roles != null && osm != null) {
313            for (Role i : roles.roles) {
314                if (i.memberExpression != null && i.memberExpression.match(osm)
315                        && (i.types == null || i.types.isEmpty() || i.types.contains(TaggingPresetType.forPrimitive(osm)))) {
316                    return i.key;
317                }
318            }
319        }
320        return null;
321    }
322
323    @Override
324    public void actionPerformed(ActionEvent e) {
325        if (Main.main == null) {
326            return;
327        }
328        DataSet ds = Main.main.getCurrentDataSet();
329        Collection<OsmPrimitive> participants = Collections.emptyList();
330        if (Main.main != null && ds != null) {
331            participants = ds.getSelected();
332        }
333
334        // Display dialog even if no data layer (used by preset-tagging-tester plugin)
335        Collection<OsmPrimitive> sel = createSelection(participants);
336        int answer = showDialog(sel, supportsRelation());
337
338        if (ds == null) {
339            return;
340        }
341
342        if (!sel.isEmpty() && answer == DIALOG_ANSWER_APPLY) {
343            Command cmd = createCommand(sel, getChangedTags());
344            if (cmd != null) {
345                Main.main.undoRedo.add(cmd);
346            }
347        } else if (answer == DIALOG_ANSWER_NEW_RELATION) {
348            final Relation r = new Relation();
349            final Collection<RelationMember> members = new HashSet<>();
350            for (Tag t : getChangedTags()) {
351                r.put(t.getKey(), t.getValue());
352            }
353            for (OsmPrimitive osm : ds.getSelected()) {
354                String role = suggestRoleForOsmPrimitive(osm);
355                RelationMember rm = new RelationMember(role == null ? "" : role, osm);
356                r.addMember(rm);
357                members.add(rm);
358            }
359            SwingUtilities.invokeLater(new Runnable() {
360                @Override
361                public void run() {
362                    RelationEditor.getEditor(Main.main.getEditLayer(), r, members).setVisible(true);
363                }
364            });
365        }
366        ds.setSelected(ds.getSelected()); // force update
367    }
368
369    private static class PresetDialog extends ExtendedDialog {
370        PresetDialog(Component content, String title, ImageIcon icon, boolean disableApply, boolean showNewRelation) {
371            super(Main.parent, title,
372                    showNewRelation ?
373                            new String[] {tr("Apply Preset"), tr("New relation"), tr("Cancel")} :
374                                new String[] {tr("Apply Preset"), tr("Cancel")},
375                                true);
376            if (icon != null)
377                setIconImage(icon.getImage());
378            contentInsets = new Insets(10, 5, 0, 5);
379            if (showNewRelation) {
380                setButtonIcons(new String[] {"ok", "dialogs/addrelation", "cancel" });
381            } else {
382                setButtonIcons(new String[] {"ok", "cancel" });
383            }
384            setContent(content);
385            setDefaultButton(1);
386            setupDialog();
387            buttons.get(0).setEnabled(!disableApply);
388            buttons.get(0).setToolTipText(title);
389            // Prevent dialogs of being too narrow (fix #6261)
390            Dimension d = getSize();
391            if (d.width < 350) {
392                d.width = 350;
393                setSize(d);
394            }
395            showDialog();
396        }
397    }
398
399    public int showDialog(Collection<OsmPrimitive> sel, boolean showNewRelation) {
400        PresetPanel p = createPanel(sel);
401        if (p == null)
402            return DIALOG_ANSWER_CANCEL;
403
404        int answer = 1;
405        boolean canCreateRelation = types == null || types.contains(TaggingPresetType.RELATION);
406        if (originalSelectionEmpty && !canCreateRelation) {
407            new Notification(
408                    tr("The preset <i>{0}</i> cannot be applied since nothing has been selected!", getLocaleName()))
409                    .setIcon(JOptionPane.WARNING_MESSAGE)
410                    .show();
411            return DIALOG_ANSWER_CANCEL;
412        } else if (sel.isEmpty() && !canCreateRelation) {
413            new Notification(
414                    tr("The preset <i>{0}</i> cannot be applied since the selection is unsuitable!", getLocaleName()))
415                    .setIcon(JOptionPane.WARNING_MESSAGE)
416                    .show();
417            return DIALOG_ANSWER_CANCEL;
418        } else if (p.getComponentCount() != 0 && (sel.isEmpty() || p.hasElements)) {
419            String title = trn("Change {0} object", "Change {0} objects", sel.size(), sel.size());
420            if (sel.isEmpty()) {
421                if (originalSelectionEmpty) {
422                    title = tr("Nothing selected!");
423                } else {
424                    title = tr("Selection unsuitable!");
425                }
426            }
427
428            answer = new PresetDialog(p, title, preset_name_label ? null : (ImageIcon) getValue(Action.SMALL_ICON),
429                    sel.isEmpty(), showNewRelation).getValue();
430        }
431        if (!showNewRelation && answer == 2)
432            return DIALOG_ANSWER_CANCEL;
433        else
434            return answer;
435    }
436
437    /**
438     * Removes all unsuitable OsmPrimitives from the given list
439     * @param participants List of possible OsmPrimitives to tag
440     * @return Cleaned list with suitable OsmPrimitives only
441     */
442    public Collection<OsmPrimitive> createSelection(Collection<OsmPrimitive> participants) {
443        originalSelectionEmpty = participants.isEmpty();
444        Collection<OsmPrimitive> sel = new LinkedList<>();
445        for (OsmPrimitive osm : participants) {
446            if (typeMatches(EnumSet.of(TaggingPresetType.forPrimitive(osm)))) {
447                sel.add(osm);
448            }
449        }
450        return sel;
451    }
452
453    public List<Tag> getChangedTags() {
454        List<Tag> result = new ArrayList<>();
455        for (TaggingPresetItem i: data) {
456            i.addCommands(result);
457        }
458        return result;
459    }
460
461    public static Command createCommand(Collection<OsmPrimitive> sel, List<Tag> changedTags) {
462        List<Command> cmds = new ArrayList<>();
463        for (Tag tag: changedTags) {
464            ChangePropertyCommand cmd = new ChangePropertyCommand(sel, tag.getKey(), tag.getValue());
465            if (cmd.getObjectsNumber() > 0) {
466                cmds.add(cmd);
467            }
468        }
469
470        if (cmds.isEmpty())
471            return null;
472        else if (cmds.size() == 1)
473            return cmds.get(0);
474        else
475            return new SequenceCommand(tr("Change Tags"), cmds);
476    }
477
478    private boolean supportsRelation() {
479        return types == null || types.contains(TaggingPresetType.RELATION);
480    }
481
482    protected final void updateEnabledState() {
483        setEnabled(Main.main != null && Main.main.getCurrentDataSet() != null);
484    }
485
486    @Override
487    public void activeLayerChange(Layer oldLayer, Layer newLayer) {
488        updateEnabledState();
489    }
490
491    @Override
492    public void layerAdded(Layer newLayer) {
493        updateEnabledState();
494    }
495
496    @Override
497    public void layerRemoved(Layer oldLayer) {
498        updateEnabledState();
499    }
500
501    @Override
502    public String toString() {
503        return (types == null ? "" : types) + " " + name;
504    }
505
506    public boolean typeMatches(Collection<TaggingPresetType> t) {
507        return t == null || types == null || types.containsAll(t);
508    }
509
510    /**
511     * Determines whether this preset matches the given primitive, i.e.,
512     * whether the {@link #typeMatches(Collection) type matches} and the {@link TaggingPresetItem#matches(Map) tags match}.
513     *
514     * @param p the primitive
515     * @return {@code true} if this preset matches the primitive
516     */
517     @Override
518    public boolean evaluate(OsmPrimitive p) {
519        return matches(EnumSet.of(TaggingPresetType.forPrimitive(p)), p.getKeys(), false);
520    }
521
522    /**
523     * Determines whether this preset matches the parameters.
524     *
525     * @param t the preset types to include, see {@link #typeMatches(Collection)}
526     * @param tags the tags to perform matching on, see {@link TaggingPresetItem#matches(Map)}
527     * @param onlyShowable whether the preset must be {@link #isShowable() showable}
528     * @return {@code true} if this preset matches the parameters.
529     */
530    public boolean matches(Collection<TaggingPresetType> t, Map<String, String> tags, boolean onlyShowable) {
531        if (onlyShowable && !isShowable())
532            return false;
533        else if (!typeMatches(t))
534            return false;
535        boolean atLeastOnePositiveMatch = false;
536        for (TaggingPresetItem item : data) {
537            Boolean m = item.matches(tags);
538            if (m != null && !m)
539                return false;
540            else if (m != null) {
541                atLeastOnePositiveMatch = true;
542            }
543        }
544        return atLeastOnePositiveMatch;
545    }
546
547    /**
548     * Action that adds or removes the button on main toolbar
549     */
550    public class ToolbarButtonAction extends AbstractAction {
551        private final int toolbarIndex;
552
553        /**
554         * Constructs a new {@code ToolbarButtonAction}.
555         */
556        public ToolbarButtonAction() {
557            super("", ImageProvider.get("dialogs", "pin"));
558            putValue(SHORT_DESCRIPTION, tr("Add or remove toolbar button"));
559            List<String> t = new LinkedList<>(ToolbarPreferences.getToolString());
560            toolbarIndex = t.indexOf(getToolbarString());
561            putValue(SELECTED_KEY, toolbarIndex >= 0);
562        }
563
564        @Override
565        public void actionPerformed(ActionEvent ae) {
566            String res = getToolbarString();
567            Main.toolbar.addCustomButton(res, toolbarIndex, true);
568        }
569    }
570
571    public String getToolbarString() {
572        ToolbarPreferences.ActionParser actionParser = new ToolbarPreferences.ActionParser(null);
573        return actionParser.saveAction(new ToolbarPreferences.ActionDefinition(this));
574    }
575}