001 // License: GPL. For details, see LICENSE file.
002 package org.openstreetmap.josm.actions;
003
004 import static org.openstreetmap.josm.tools.I18n.tr;
005
006 import java.awt.event.ActionEvent;
007 import javax.swing.Action;
008 import javax.swing.ImageIcon;
009 import javax.swing.JOptionPane;
010 import org.openstreetmap.josm.Main;
011 import org.openstreetmap.josm.data.imagery.ImageryInfo;
012 import org.openstreetmap.josm.data.imagery.ImageryInfo.ImageryType;
013 import org.openstreetmap.josm.gui.actionsupport.AlignImageryPanel;
014 import org.openstreetmap.josm.gui.layer.ImageryLayer;
015 import org.openstreetmap.josm.tools.ImageProvider;
016
017 public class AddImageryLayerAction extends JosmAction implements AdaptableAction {
018
019 private static final int MAX_ICON_SIZE = 24;
020 private final ImageryInfo info;
021
022 public AddImageryLayerAction(ImageryInfo info) {
023 super(info.getMenuName(), /* ICON */"imagery_menu", tr("Add imagery layer {0}",info.getName()), null, false, false);
024 putValue("toolbar", "imagery_" + info.getToolbarName());
025 this.info = info;
026 installAdapters();
027
028 // change toolbar icon from if specified
029 try {
030 if (info.getIcon() != null) {
031 ImageIcon i = new ImageProvider(info.getIcon()).setOptional(true).
032 setMaxHeight(MAX_ICON_SIZE).setMaxWidth(MAX_ICON_SIZE).get();
033 if (i != null) {
034 putValue(Action.SMALL_ICON, i);
035 }
036 }
037 } catch (Exception ex) {
038 throw new RuntimeException(ex.getMessage(), ex);
039 }
040 }
041
042 @Override
043 public void actionPerformed(ActionEvent e) {
044 if (!isEnabled()) return;
045 try {
046 Main.main.addLayer(ImageryLayer.create(info));
047 AlignImageryPanel.addNagPanelIfNeeded();
048 } catch (IllegalArgumentException ex) {
049 if (ex.getMessage() == null || ex.getMessage().isEmpty()) {
050 throw ex;
051 } else {
052 JOptionPane.showMessageDialog(Main.parent,
053 ex.getMessage(), tr("Error"),
054 JOptionPane.ERROR_MESSAGE);
055 }
056 }
057 }
058
059 protected boolean isLayerAlreadyPresent() {
060 if (Main.isDisplayingMapView()) {
061 for (ImageryLayer layer : Main.map.mapView.getLayersOfType(ImageryLayer.class)) {
062 if (info.equals(layer.getInfo())) {
063 return true;
064 }
065 }
066 }
067 return false;
068 }
069
070 @Override
071 protected void updateEnabledState() {
072 // never enable blacklisted entries. Do not add same imagery layer twice (fix #2519)
073 if (info.isBlacklisted() /*|| isLayerAlreadyPresent()*/) { // FIXME check disabled to allow several instances with different settings (see #7981)
074 setEnabled(false);
075 } else if (info.getImageryType() == ImageryType.TMS || info.getImageryType() == ImageryType.BING || info.getImageryType() == ImageryType.SCANEX) {
076 setEnabled(true);
077 } else if (Main.isDisplayingMapView() && !Main.map.mapView.getAllLayers().isEmpty()) {
078 setEnabled(true);
079 } else {
080 setEnabled(false);
081 }
082 }
083 }