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