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