001// License: GPL. For details, see LICENSE file.
002package org.openstreetmap.josm.gui.dialogs.properties;
003
004import java.awt.Dimension;
005import java.awt.GridBagLayout;
006import java.awt.event.MouseAdapter;
007import java.awt.event.MouseEvent;
008import java.util.Collection;
009import java.util.Map;
010
011import javax.swing.JLabel;
012import javax.swing.JPanel;
013
014import org.openstreetmap.josm.data.osm.OsmPrimitive;
015import org.openstreetmap.josm.gui.tagging.presets.TaggingPreset;
016import org.openstreetmap.josm.gui.tagging.presets.TaggingPresetHandler;
017import org.openstreetmap.josm.gui.tagging.presets.TaggingPresetLabel;
018import org.openstreetmap.josm.gui.tagging.presets.TaggingPresetType;
019import org.openstreetmap.josm.tools.GBC;
020
021/**
022 * A list of matching presets for a set of tags.
023 */
024public class PresetListPanel extends JPanel {
025
026    /**
027     * Constructs a new {@code PresetListPanel}.
028     */
029    public PresetListPanel() {
030        super(new GridBagLayout());
031    }
032
033    /**
034     * Updates the preset list based on the {@code tags} and {@code types},
035     * and associates an interaction with (matching) presets via {@code presetHandler}.
036     */
037    public void updatePresets(final Collection<TaggingPresetType> types, final Map<String, String> tags,
038            final TaggingPresetHandler presetHandler) {
039
040        removeAll();
041        if (types.isEmpty()) {
042            setVisible(false);
043            return;
044        }
045
046        for (final TaggingPreset t : TaggingPreset.getMatchingPresets(types, tags, true)) {
047            final JLabel lbl = new TaggingPresetLabel(t);
048            lbl.addMouseListener(new MouseAdapter() {
049                @Override
050                public void mouseClicked(MouseEvent e) {
051                    Collection<OsmPrimitive> selection = t.createSelection(presetHandler.getSelection());
052                    if (selection == null || selection.isEmpty())
053                        return;
054                    int answer = t.showDialog(selection, false);
055
056                    if (answer == TaggingPreset.DIALOG_ANSWER_APPLY) {
057                        presetHandler.updateTags(t.getChangedTags());
058                    }
059                }
060            });
061            add(lbl, GBC.eol().fill(GBC.HORIZONTAL));
062        }
063
064        if (getComponentCount() > 0) {
065            setVisible(true);
066            // This ensures the presets are exactly as high as needed.
067            int height = getComponentCount() * getComponent(0).getHeight();
068            Dimension size = new Dimension(getWidth(), height);
069            setMaximumSize(size);
070            setMinimumSize(size);
071        } else {
072            setVisible(false);
073        }
074    }
075}