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, 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            } else if (i instanceof PresetLink) {
231                presetLink.add((PresetLink) i);
232            } else {
233                if (i.addToPanel(items, selected, presetInitiallyMatches)) {
234                    p.hasElements = true;
235                }
236            }
237        }
238        p.add(items, GBC.eol().fill());
239        if (selected.isEmpty() && !supportsRelation()) {
240            GuiHelper.setEnabledRec(items, false);
241        }
242
243        // add PresetLink
244        if (!presetLink.isEmpty()) {
245            p.add(new JLabel(tr("Edit also ?")), GBC.eol().insets(0, 8, 0, 0));
246            for (PresetLink link : presetLink) {
247                link.addToPanel(p, selected, presetInitiallyMatches);
248            }
249        }
250
251        // add Link
252        for (Link link : l) {
253            link.addToPanel(p, selected, presetInitiallyMatches);
254        }
255
256        // "Add toolbar button"
257        JToggleButton tb = new JToggleButton(new ToolbarButtonAction());
258        tb.setFocusable(false);
259        p.add(tb, GBC.std(0,0).anchor(GBC.LINE_END));
260        return p;
261    }
262
263    public boolean isShowable() {
264        for (TaggingPresetItem i : data) {
265            if (!(i instanceof TaggingPresetItems.Optional || i instanceof TaggingPresetItems.Space || i instanceof TaggingPresetItems.Key))
266                return true;
267        }
268        return false;
269    }
270
271    public String suggestRoleForOsmPrimitive(OsmPrimitive osm) {
272        if (roles != null && osm != null) {
273            for (Role i : roles.roles) {
274                if (i.memberExpression != null && i.memberExpression.match(osm)
275                        && (i.types == null || i.types.isEmpty() || i.types.contains(TaggingPresetType.forPrimitive(osm)) )) {
276                    return i.key;
277                }
278            }
279        }
280        return null;
281    }
282
283    @Override
284    public void actionPerformed(ActionEvent e) {
285        if (Main.main == null) {
286            return;
287        }
288        DataSet ds = Main.main.getCurrentDataSet();
289        Collection<OsmPrimitive> participants = Collections.emptyList();
290        if (Main.main != null && ds != null) {
291            participants = ds.getSelected();
292        }
293
294        // Display dialog even if no data layer (used by preset-tagging-tester plugin)
295        Collection<OsmPrimitive> sel = createSelection(participants);
296        int answer = showDialog(sel, supportsRelation());
297
298        if (ds == null) {
299            return;
300        }
301
302        if (!sel.isEmpty() && answer == DIALOG_ANSWER_APPLY) {
303            Command cmd = createCommand(sel, getChangedTags());
304            if (cmd != null) {
305                Main.main.undoRedo.add(cmd);
306            }
307        } else if (answer == DIALOG_ANSWER_NEW_RELATION) {
308            final Relation r = new Relation();
309            final Collection<RelationMember> members = new HashSet<>();
310            for(Tag t : getChangedTags()) {
311                r.put(t.getKey(), t.getValue());
312            }
313            for (OsmPrimitive osm : ds.getSelected()) {
314                String role = suggestRoleForOsmPrimitive(osm);
315                RelationMember rm = new RelationMember(role == null ? "" : role, osm);
316                r.addMember(rm);
317                members.add(rm);
318            }
319            SwingUtilities.invokeLater(new Runnable() {
320                @Override
321                public void run() {
322                    RelationEditor.getEditor(Main.main.getEditLayer(), r, members).setVisible(true);
323                }
324            });
325        }
326        ds.setSelected(ds.getSelected()); // force update
327    }
328
329    private static class PresetDialog extends ExtendedDialog {
330        public PresetDialog(Component content, String title, ImageIcon icon, boolean disableApply, boolean showNewRelation) {
331            super(Main.parent, title,
332                    showNewRelation?
333                            new String[] { tr("Apply Preset"), tr("New relation"), tr("Cancel") }:
334                                new String[] { tr("Apply Preset"), tr("Cancel") },
335                                true);
336            if (icon != null)
337                setIconImage(icon.getImage());
338            contentInsets = new Insets(10,5,0,5);
339            if (showNewRelation) {
340                setButtonIcons(new String[] {"ok.png", "dialogs/addrelation.png", "cancel.png" });
341            } else {
342                setButtonIcons(new String[] {"ok.png", "cancel.png" });
343            }
344            setContent(content);
345            setDefaultButton(1);
346            setupDialog();
347            buttons.get(0).setEnabled(!disableApply);
348            buttons.get(0).setToolTipText(title);
349            // Prevent dialogs of being too narrow (fix #6261)
350            Dimension d = getSize();
351            if (d.width < 350) {
352                d.width = 350;
353                setSize(d);
354            }
355            showDialog();
356        }
357    }
358
359    public int showDialog(Collection<OsmPrimitive> sel, boolean showNewRelation) {
360        PresetPanel p = createPanel(sel);
361        if (p == null)
362            return DIALOG_ANSWER_CANCEL;
363
364        int answer = 1;
365        if (p.getComponentCount() != 0 && (sel.isEmpty() || p.hasElements)) {
366            String title = trn("Change {0} object", "Change {0} objects", sel.size(), sel.size());
367            if(sel.isEmpty()) {
368                if(originalSelectionEmpty) {
369                    title = tr("Nothing selected!");
370                } else {
371                    title = tr("Selection unsuitable!");
372                }
373            }
374
375            answer = new PresetDialog(p, title, (ImageIcon) getValue(Action.SMALL_ICON),
376                    sel.isEmpty(), showNewRelation).getValue();
377        }
378        if (!showNewRelation && answer == 2)
379            return DIALOG_ANSWER_CANCEL;
380        else
381            return answer;
382    }
383
384    /**
385     * True whenever the original selection given into createSelection was empty
386     */
387    private boolean originalSelectionEmpty = false;
388
389    /**
390     * Removes all unsuitable OsmPrimitives from the given list
391     * @param participants List of possible OsmPrimitives to tag
392     * @return Cleaned list with suitable OsmPrimitives only
393     */
394    public Collection<OsmPrimitive> createSelection(Collection<OsmPrimitive> participants) {
395        originalSelectionEmpty = participants.isEmpty();
396        Collection<OsmPrimitive> sel = new LinkedList<>();
397        for (OsmPrimitive osm : participants) {
398            if (typeMatches(EnumSet.of(TaggingPresetType.forPrimitive(osm)))) {
399                sel.add(osm);
400            }
401        }
402        return sel;
403    }
404
405    public List<Tag> getChangedTags() {
406        List<Tag> result = new ArrayList<>();
407        for (TaggingPresetItem i: data) {
408            i.addCommands(result);
409        }
410        return result;
411    }
412
413    public static Command createCommand(Collection<OsmPrimitive> sel, List<Tag> changedTags) {
414        List<Command> cmds = new ArrayList<>();
415        for (Tag tag: changedTags) {
416            cmds.add(new ChangePropertyCommand(sel, tag.getKey(), tag.getValue()));
417        }
418
419        if (cmds.size() == 0)
420            return null;
421        else if (cmds.size() == 1)
422            return cmds.get(0);
423        else
424            return new SequenceCommand(tr("Change Tags"), cmds);
425    }
426
427    private boolean supportsRelation() {
428        return types == null || types.contains(TaggingPresetType.RELATION);
429    }
430
431    protected final void updateEnabledState() {
432        setEnabled(Main.main != null && Main.main.getCurrentDataSet() != null);
433    }
434
435    @Override
436    public void activeLayerChange(Layer oldLayer, Layer newLayer) {
437        updateEnabledState();
438    }
439
440    @Override
441    public void layerAdded(Layer newLayer) {
442        updateEnabledState();
443    }
444
445    @Override
446    public void layerRemoved(Layer oldLayer) {
447        updateEnabledState();
448    }
449
450    @Override
451    public String toString() {
452        return (types == null?"":types) + " " + name;
453    }
454
455    public boolean typeMatches(Collection<TaggingPresetType> t) {
456        return t == null || types == null || types.containsAll(t);
457    }
458
459    @Override
460    public boolean evaluate(OsmPrimitive p) {
461        return matches(EnumSet.of(TaggingPresetType.forPrimitive(p)), p.getKeys(), false);
462    }
463
464    public boolean matches(Collection<TaggingPresetType> t, Map<String, String> tags, boolean onlyShowable) {
465        if (onlyShowable && !isShowable())
466            return false;
467        else if (!typeMatches(t))
468            return false;
469        boolean atLeastOnePositiveMatch = false;
470        for (TaggingPresetItem item : data) {
471            Boolean m = item.matches(tags);
472            if (m != null && !m)
473                return false;
474            else if (m != null) {
475                atLeastOnePositiveMatch = true;
476            }
477        }
478        return atLeastOnePositiveMatch;
479    }
480
481    public static Collection<TaggingPreset> getMatchingPresets(final Collection<TaggingPresetType> t, final Map<String, String> tags, final boolean onlyShowable) {
482        return Utils.filter(TaggingPresets.getTaggingPresets(), new Predicate<TaggingPreset>() {
483            @Override
484            public boolean evaluate(TaggingPreset object) {
485                return object.matches(t, tags, onlyShowable);
486            }
487        });
488    }
489
490    /**
491     * Action that adds or removes the button on main toolbar
492     */
493    public class ToolbarButtonAction extends AbstractAction {
494        private final int toolbarIndex;
495
496        /**
497         * Constructs a new {@code ToolbarButtonAction}.
498         */
499        public ToolbarButtonAction() {
500            super("", ImageProvider.get("styles/standard/waypoint","pin"));
501            putValue(SHORT_DESCRIPTION, tr("Add or remove toolbar button"));
502            LinkedList<String> t = new LinkedList<>(ToolbarPreferences.getToolString());
503            toolbarIndex = t.indexOf(getToolbarString());
504            putValue(SELECTED_KEY, toolbarIndex >= 0);
505        }
506
507        @Override
508        public void actionPerformed(ActionEvent ae) {
509            String res = getToolbarString();
510            Main.toolbar.addCustomButton(res, toolbarIndex, true);
511        }
512    }
513
514    public String getToolbarString() {
515        ToolbarPreferences.ActionParser actionParser = new ToolbarPreferences.ActionParser(null);
516        return actionParser.saveAction(new ToolbarPreferences.ActionDefinition(this));
517    }
518}