001// License: GPL. For details, see LICENSE file.
002package org.openstreetmap.josm.gui.util;
003
004import java.awt.Component;
005import java.util.ArrayList;
006import java.util.Collection;
007import java.util.HashMap;
008import java.util.Map;
009
010import javax.swing.JPopupMenu;
011import javax.swing.event.PopupMenuEvent;
012import javax.swing.event.PopupMenuListener;
013
014import org.openstreetmap.josm.actions.OpenBrowserAction;
015import org.openstreetmap.josm.tools.Tag2Link;
016
017/**
018 * A popup listener which adds web links based on tags of OSM primitives.
019 *
020 * @since 15673
021 */
022public abstract class AbstractTag2LinkPopupListener implements PopupMenuListener {
023
024    private final Map<String, OpenBrowserAction> browserActions = new HashMap<>();
025    private final Collection<Component> itemList = new ArrayList<>();
026
027    protected AbstractTag2LinkPopupListener() {
028    }
029
030    @Override
031    public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
032        JPopupMenu popup = (JPopupMenu) e.getSource();
033        browserActions.clear();
034        itemList.forEach(popup::remove);
035        itemList.clear();
036    }
037
038    @Override
039    public void popupMenuCanceled(PopupMenuEvent e) {
040    }
041
042    protected void addLinks(JPopupMenu popup, String key, String value) {
043        Tag2Link.getLinksForTag(key, value, (name, url, icon) -> {
044            if (itemList.isEmpty()) {
045                itemList.add(popup.add(new JPopupMenu.Separator()));
046            }
047
048            if (browserActions.containsKey(name)) {
049                browserActions.get(name).addUrl(url);
050            } else {
051                final OpenBrowserAction action = new OpenBrowserAction(name, url, icon);
052                browserActions.put(name, action);
053                itemList.add(popup.add(action));
054            }
055        });
056    }
057}