001// License: GPL. For details, see LICENSE file.
002package org.openstreetmap.josm.gui.layer;
003
004import static org.openstreetmap.josm.tools.I18n.tr;
005
006import java.awt.event.ActionEvent;
007import java.util.ArrayList;
008import java.util.Arrays;
009import java.util.Collection;
010import java.util.List;
011import java.util.Objects;
012
013import javax.swing.AbstractAction;
014import javax.swing.Action;
015
016import org.apache.commons.jcs3.access.CacheAccess;
017import org.openstreetmap.gui.jmapviewer.interfaces.TileLoader;
018import org.openstreetmap.josm.data.cache.BufferedImageCacheEntry;
019import org.openstreetmap.josm.data.coor.LatLon;
020import org.openstreetmap.josm.data.imagery.AbstractWMSTileSource;
021import org.openstreetmap.josm.data.imagery.ImageryInfo;
022import org.openstreetmap.josm.data.imagery.ImageryInfo.ImageryType;
023import org.openstreetmap.josm.data.imagery.ImageryLayerInfo;
024import org.openstreetmap.josm.data.imagery.TemplatedWMSTileSource;
025import org.openstreetmap.josm.data.imagery.WMSCachedTileLoader;
026import org.openstreetmap.josm.data.imagery.WMSEndpointTileSource;
027import org.openstreetmap.josm.data.preferences.BooleanProperty;
028import org.openstreetmap.josm.data.preferences.IntegerProperty;
029import org.openstreetmap.josm.data.projection.Projection;
030import org.openstreetmap.josm.data.projection.ProjectionRegistry;
031import org.openstreetmap.josm.data.projection.Projections;
032import org.openstreetmap.josm.gui.MainApplication;
033import org.openstreetmap.josm.gui.layer.imagery.TileSourceDisplaySettings;
034import org.openstreetmap.josm.tools.CheckParameterUtil;
035import org.openstreetmap.josm.tools.Logging;
036
037/**
038 * This is a layer that grabs the current screen from an WMS server. The data
039 * fetched this way is tiled and managed to the disc to reduce server load.
040 *
041 */
042public class WMSLayer extends AbstractCachedTileSourceLayer<AbstractWMSTileSource> {
043    private static final String PREFERENCE_PREFIX = "imagery.wms";
044    /**
045     * Registers all setting properties
046     */
047    static {
048        new TileSourceDisplaySettings(PREFERENCE_PREFIX);
049    }
050
051    /** default tile size for WMS Layer */
052    public static final IntegerProperty PROP_IMAGE_SIZE = new IntegerProperty(PREFERENCE_PREFIX + ".imageSize", 512);
053
054    /** should WMS layer autozoom in default mode */
055    public static final BooleanProperty PROP_DEFAULT_AUTOZOOM = new BooleanProperty(PREFERENCE_PREFIX + ".default_autozoom", true);
056
057    private static final String CACHE_REGION_NAME = "WMS";
058
059    private List<String> serverProjections;
060
061    /**
062     * Constructs a new {@code WMSLayer}.
063     * @param info ImageryInfo description of the layer
064     */
065    public WMSLayer(ImageryInfo info) {
066        super(info);
067        CheckParameterUtil.ensureThat(
068                info.getImageryType() == ImageryType.WMS || info.getImageryType() == ImageryType.WMS_ENDPOINT, "ImageryType is WMS");
069        CheckParameterUtil.ensureParameterNotNull(info.getUrl(), "info.url");
070        if (info.getImageryType() == ImageryType.WMS) {
071            TemplatedWMSTileSource.checkUrl(info.getUrl());
072
073        }
074        this.serverProjections = new ArrayList<>(info.getServerProjections());
075    }
076
077    @Override
078    protected TileSourceDisplaySettings createDisplaySettings() {
079        return new TileSourceDisplaySettings(PREFERENCE_PREFIX);
080    }
081
082    @Override
083    public Action[] getMenuEntries() {
084        List<Action> ret = new ArrayList<>(Arrays.asList(super.getMenuEntries()));
085        ret.add(SeparatorLayerAction.INSTANCE);
086        ret.add(new LayerSaveAction(this));
087        ret.add(new LayerSaveAsAction(this));
088        ret.add(new BookmarkWmsAction());
089        return ret.toArray(new Action[0]);
090    }
091
092    @Override
093    protected AbstractWMSTileSource getTileSource() {
094        AbstractWMSTileSource tileSource;
095        if (info.getImageryType() == ImageryType.WMS) {
096            tileSource = new TemplatedWMSTileSource(info, chooseProjection(ProjectionRegistry.getProjection()));
097        } else {
098            /*
099             *  Chicken-and-egg problem. We want to create tile source, but supported projections we can get only
100             *  from this tile source. So create tilesource first with dummy ProjectionRegistry.getProjection(), and then update
101             *  once we update server projections.
102             *
103             *  Thus:
104             *  * it is not required to provide projections for wms_endpoint imagery types
105             *  * we always use current definitions returned by server
106             */
107            WMSEndpointTileSource endpointTileSource = new WMSEndpointTileSource(info, ProjectionRegistry.getProjection());
108            this.serverProjections = endpointTileSource.getServerProjections();
109            endpointTileSource.setTileProjection(chooseProjection(ProjectionRegistry.getProjection()));
110            tileSource = endpointTileSource;
111        }
112        info.setAttribution(tileSource);
113        return tileSource;
114    }
115
116    /**
117     * This action will add a WMS layer menu entry with the current WMS layer
118     * URL and name extended by the current resolution.
119     * When using the menu entry again, the WMS cache will be used properly.
120     */
121    public class BookmarkWmsAction extends AbstractAction {
122        /**
123         * Constructs a new {@code BookmarkWmsAction}.
124         */
125        public BookmarkWmsAction() {
126            super(tr("Set WMS Bookmark"));
127        }
128
129        @Override
130        public void actionPerformed(ActionEvent ev) {
131            ImageryLayerInfo.addLayer(new ImageryInfo(info));
132        }
133    }
134
135    @Override
136    public Collection<String> getNativeProjections() {
137        return serverProjections;
138    }
139
140    @Override
141    public void projectionChanged(Projection oldValue, Projection newValue) {
142        super.projectionChanged(oldValue, newValue);
143        Projection tileProjection = chooseProjection(newValue);
144        if (!Objects.equals(tileSource.getTileProjection(), tileProjection)) {
145            tileSource.setTileProjection(tileProjection);
146        }
147    }
148
149    private Projection chooseProjection(Projection requested) {
150        if (serverProjections.contains(requested.toCode())) {
151            return requested;
152        } else {
153            LatLon center = MainApplication.isDisplayingMapView() ?
154                    requested.eastNorth2latlon(MainApplication.getMap().mapView.getCenter()) : null;
155            Projection firstNonNullproj = null;
156            Projection firstProjInBounds = null;
157            for (String code : serverProjections) {
158                Projection proj = Projections.getProjectionByCode(code);
159                if (proj != null) {
160                    if (firstNonNullproj == null) {
161                        firstNonNullproj = proj;
162                    }
163                    if (center != null && proj.getWorldBoundsLatLon().contains(center)) {
164                        firstProjInBounds = proj;
165                        break;
166                    }
167                }
168            }
169            if (firstProjInBounds != null) {
170                return selectProjection(firstProjInBounds);
171            } else if (firstNonNullproj != null) {
172                return selectProjection(firstNonNullproj);
173            }
174            Logging.warn(tr("Unable to find supported projection for layer {0}. Using {1}.", getName(), requested.toCode()));
175            return requested;
176        }
177    }
178
179    private Projection selectProjection(Projection proj) {
180        Logging.info(tr("Reprojecting layer {0} from {1} to {2}. For best image quality and performance,"
181                + " switch to one of the supported projections: {3}",
182                getName(), proj.toCode(), ProjectionRegistry.getProjection().toCode(), String.join(", ", getNativeProjections())));
183        return proj;
184    }
185
186    @Override
187    protected Class<? extends TileLoader> getTileLoaderClass() {
188        return WMSCachedTileLoader.class;
189    }
190
191    @Override
192    protected String getCacheName() {
193        return CACHE_REGION_NAME;
194    }
195
196    /**
197     * Returns cache region for WMS layer.
198     * @return cache region for WMS layer
199     */
200    public static CacheAccess<String, BufferedImageCacheEntry> getCache() {
201        return AbstractCachedTileSourceLayer.getCache(CACHE_REGION_NAME);
202    }
203}