001// License: GPL. For details, see LICENSE file.
002package org.openstreetmap.josm.actions;
003
004import static org.openstreetmap.josm.gui.help.HelpUtil.ht;
005import static org.openstreetmap.josm.tools.I18n.marktr;
006import static org.openstreetmap.josm.tools.I18n.tr;
007
008import java.awt.Dimension;
009import java.awt.GraphicsEnvironment;
010import java.awt.GridBagConstraints;
011import java.awt.GridBagLayout;
012import java.awt.event.ActionEvent;
013import java.io.IOException;
014import java.net.MalformedURLException;
015import java.nio.file.InvalidPathException;
016import java.time.Year;
017import java.time.ZoneOffset;
018import java.util.Collection;
019import java.util.Collections;
020import java.util.List;
021import java.util.function.Function;
022import java.util.stream.Collectors;
023
024import javax.swing.JCheckBox;
025import javax.swing.JComboBox;
026import javax.swing.JOptionPane;
027import javax.swing.JPanel;
028import javax.swing.JScrollPane;
029
030import org.openstreetmap.josm.data.coor.LatLon;
031import org.openstreetmap.josm.data.imagery.DefaultLayer;
032import org.openstreetmap.josm.data.imagery.ImageryInfo;
033import org.openstreetmap.josm.data.imagery.ImageryInfo.ImageryType;
034import org.openstreetmap.josm.data.imagery.LayerDetails;
035import org.openstreetmap.josm.data.imagery.TemplatedWMSTileSource;
036import org.openstreetmap.josm.data.imagery.WMTSTileSource;
037import org.openstreetmap.josm.data.imagery.WMTSTileSource.Layer;
038import org.openstreetmap.josm.data.imagery.WMTSTileSource.WMTSGetCapabilitiesException;
039import org.openstreetmap.josm.data.projection.ProjectionRegistry;
040import org.openstreetmap.josm.gui.ExtendedDialog;
041import org.openstreetmap.josm.gui.MainApplication;
042import org.openstreetmap.josm.gui.layer.AlignImageryPanel;
043import org.openstreetmap.josm.gui.layer.ImageryLayer;
044import org.openstreetmap.josm.gui.preferences.ToolbarPreferences;
045import org.openstreetmap.josm.gui.preferences.imagery.WMSLayerTree;
046import org.openstreetmap.josm.gui.util.GuiHelper;
047import org.openstreetmap.josm.io.imagery.WMSImagery;
048import org.openstreetmap.josm.io.imagery.WMSImagery.WMSGetCapabilitiesException;
049import org.openstreetmap.josm.tools.CheckParameterUtil;
050import org.openstreetmap.josm.tools.GBC;
051import org.openstreetmap.josm.tools.ImageProvider;
052import org.openstreetmap.josm.tools.Logging;
053import org.openstreetmap.josm.tools.Utils;
054import org.openstreetmap.josm.tools.bugreport.ReportedException;
055
056/**
057 * Action displayed in imagery menu to add a new imagery layer.
058 * @since 3715
059 */
060public class AddImageryLayerAction extends JosmAction implements AdaptableAction {
061    private static final String WMS_ERROR = marktr("WMS Error");
062    private final transient ImageryInfo info;
063
064    static class SelectWmsLayersDialog extends ExtendedDialog {
065        SelectWmsLayersDialog(WMSLayerTree tree, JComboBox<String> formats) {
066            super(MainApplication.getMainFrame(), tr("Select WMS layers"), tr("Add layers"), tr("Cancel"));
067            final JScrollPane scrollPane = new JScrollPane(tree.getLayerTree());
068            scrollPane.setPreferredSize(new Dimension(400, 400));
069            final JPanel panel = new JPanel(new GridBagLayout());
070            panel.add(scrollPane, GBC.eol().fill());
071            panel.add(formats, GBC.eol().fill(GridBagConstraints.HORIZONTAL));
072            setContent(panel);
073        }
074    }
075
076    /**
077     * Constructs a new {@code AddImageryLayerAction} for the given {@code ImageryInfo}.
078     * If an http:// icon is specified, it is fetched asynchronously.
079     * @param info The imagery info
080     */
081    public AddImageryLayerAction(ImageryInfo info) {
082        super(info.getMenuName(), /* ICON */"imagery_menu", info.getToolTipText(), null,
083                true, ToolbarPreferences.IMAGERY_PREFIX + info.getToolbarName(), false);
084        setHelpId(ht("/Preferences/Imagery"));
085        this.info = info;
086        installAdapters();
087
088        // change toolbar icon from if specified
089        final String icon = info.getIcon();
090        if (icon != null) {
091            new ImageProvider(icon).setOptional(true).getResourceAsync(result -> {
092                if (result != null) {
093                    GuiHelper.runInEDT(() -> result.attachImageIcon(this));
094                }
095            });
096        }
097    }
098
099    /**
100     * Converts general ImageryInfo to specific one, that does not need any user action to initialize
101     * see: https://josm.openstreetmap.de/ticket/13868
102     * @param info ImageryInfo that will be converted (or returned when no conversion needed)
103     * @return ImageryInfo object that's ready to be used to create TileSource
104     */
105    private static ImageryInfo convertImagery(ImageryInfo info) {
106        try {
107            if (info.getUrl() != null && info.getUrl().contains("{time}")) {
108                final String instant = Year.now(ZoneOffset.UTC).atDay(1).atStartOfDay(ZoneOffset.UTC).toInstant().toString();
109                final String example = String.join("/", instant, instant);
110                final String initialSelectionValue = info.getDate() != null ? info.getDate() : example;
111                final String userDate = JOptionPane.showInputDialog(MainApplication.getMainFrame(),
112                        tr("Time filter for \"{0}\" such as \"{1}\"", info.getName(), example),
113                        initialSelectionValue);
114                if (userDate == null) {
115                    return null;
116                }
117                info.setDate(userDate);
118                // TODO persist new {time} value (via ImageryLayerInfo.save?)
119            }
120            switch (info.getImageryType()) {
121            case WMS_ENDPOINT:
122                // convert to WMS type
123                if (Utils.isEmpty(info.getDefaultLayers())) {
124                    return getWMSLayerInfo(info);
125                } else {
126                    return info;
127                }
128            case WMTS:
129                // specify which layer to use
130                if (Utils.isEmpty(info.getDefaultLayers())) {
131                    final WMTSTileSource tileSource = new WMTSTileSource(info);
132                    final DefaultLayer layerId = tileSource.userSelectLayer();
133                    if (layerId != null) {
134                        final ImageryInfo copy = new ImageryInfo(info);
135                        copy.setDefaultLayers(Collections.singletonList(layerId));
136                        final String layerName = tileSource.getLayers().stream()
137                                .filter(x -> x.getIdentifier().equals(layerId.getLayerName()))
138                                .map(Layer::getUserTitle)
139                                .findFirst()
140                                .orElse("");
141                        copy.setName(copy.getName() + ": " + layerName);
142                        return copy;
143                    }
144                    return null;
145                } else {
146                    return info;
147                }
148            default:
149                return info;
150            }
151        } catch (MalformedURLException ex) {
152            handleException(ex, tr("Invalid service URL."), tr(WMS_ERROR), null);
153        } catch (IOException ex) {
154            handleException(ex, tr("Could not retrieve WMS layer list."), tr(WMS_ERROR), null);
155        } catch (WMSGetCapabilitiesException ex) {
156            handleException(ex, tr("Could not parse WMS layer list."), tr(WMS_ERROR),
157                    "Could not parse WMS layer list. Incoming data:\n" + ex.getIncomingData());
158        } catch (WMTSGetCapabilitiesException ex) {
159            handleException(ex, tr("Could not parse WMTS layer list."), tr("WMTS Error"),
160                    "Could not parse WMTS layer list.");
161        }
162        return null;
163    }
164
165    @Override
166    public void actionPerformed(ActionEvent e) {
167        if (!isEnabled()) {
168            return;
169        }
170        ImageryLayer layer = null;
171        try {
172            final ImageryInfo infoToAdd = convertImagery(info);
173            if (infoToAdd != null) {
174                layer = ImageryLayer.create(infoToAdd);
175                getLayerManager().addLayer(layer, false);
176                AlignImageryPanel.addNagPanelIfNeeded(infoToAdd);
177            }
178        } catch (IllegalArgumentException | ReportedException ex) {
179            if (Utils.isEmpty(ex.getMessage()) || GraphicsEnvironment.isHeadless()) {
180                throw ex;
181            } else {
182                Logging.error(ex);
183                JOptionPane.showMessageDialog(MainApplication.getMainFrame(), ex.getMessage(), tr("Error"), JOptionPane.ERROR_MESSAGE);
184                if (layer != null) {
185                    getLayerManager().removeLayer(layer);
186                }
187            }
188        }
189    }
190
191    /**
192     * Represents the user choices when selecting layers to display.
193     * @since 14549
194     */
195    public static class LayerSelection {
196        private final List<LayerDetails> layers;
197        private final String format;
198        private final boolean transparent;
199
200        /**
201         * Constructs a new {@code LayerSelection}.
202         * @param layers selected layers
203         * @param format selected image format
204         * @param transparent enable transparency?
205         */
206        public LayerSelection(List<LayerDetails> layers, String format, boolean transparent) {
207            this.layers = layers;
208            this.format = format;
209            this.transparent = transparent;
210        }
211    }
212
213    private static LayerSelection askToSelectLayers(WMSImagery wms) {
214        final WMSLayerTree tree = new WMSLayerTree();
215
216        final Collection<String> wmsFormats = wms.getFormats();
217        final JComboBox<String> formats = new JComboBox<>(wmsFormats.toArray(new String[0]));
218        formats.setSelectedItem(wms.getPreferredFormat());
219        formats.setToolTipText(tr("Select image format for WMS layer"));
220
221        final JCheckBox checkBounds = new JCheckBox(tr("Show only layers for current view"), true);
222        final Runnable updateTree = () -> {
223            final LatLon latLon = checkBounds.isSelected() && MainApplication.isDisplayingMapView()
224                    ? MainApplication.getMap().mapView.getProjection().eastNorth2latlon(MainApplication.getMap().mapView.getCenter())
225                    : null;
226            tree.setCheckBounds(latLon);
227            tree.updateTree(wms);
228            System.out.println(wms);
229        };
230        checkBounds.addActionListener(ignore -> updateTree.run());
231        updateTree.run();
232
233        if (!GraphicsEnvironment.isHeadless()) {
234            final ExtendedDialog dialog = new ExtendedDialog(MainApplication.getMainFrame(),
235                    tr("Select WMS layers"), tr("Add layers"), tr("Cancel"));
236            final JScrollPane scrollPane = new JScrollPane(tree.getLayerTree());
237            scrollPane.setPreferredSize(new Dimension(400, 400));
238            final JPanel panel = new JPanel(new GridBagLayout());
239            panel.add(scrollPane, GBC.eol().fill());
240            panel.add(checkBounds, GBC.eol().fill(GridBagConstraints.HORIZONTAL));
241            panel.add(formats, GBC.eol().fill(GridBagConstraints.HORIZONTAL));
242            dialog.setContent(panel);
243
244            if (dialog.showDialog().getValue() != 1) {
245                return null;
246            }
247        }
248        return new LayerSelection(
249                tree.getSelectedLayers(),
250                (String) formats.getSelectedItem(),
251                true); // TODO: ask the user if transparent layer is wanted
252    }
253
254    /**
255     * Asks user to choose a WMS layer from a WMS endpoint.
256     * @param info the WMS endpoint.
257     * @return chosen WMS layer, or null
258     * @throws IOException if any I/O error occurs while contacting the WMS endpoint
259     * @throws WMSGetCapabilitiesException if the WMS getCapabilities request fails
260     * @throws InvalidPathException if a Path object cannot be constructed for the capabilities cached file
261     */
262    protected static ImageryInfo getWMSLayerInfo(ImageryInfo info) throws IOException, WMSGetCapabilitiesException {
263        try {
264            return getWMSLayerInfo(info, AddImageryLayerAction::askToSelectLayers);
265        } catch (MalformedURLException ex) {
266            handleException(ex, tr("Invalid service URL."), tr(WMS_ERROR), null);
267        } catch (IOException ex) {
268            handleException(ex, tr("Could not retrieve WMS layer list."), tr(WMS_ERROR), null);
269        } catch (WMSGetCapabilitiesException ex) {
270            handleException(ex, tr("Could not parse WMS layer list."), tr(WMS_ERROR),
271                    "Could not parse WMS layer list. Incoming data:\n" + ex.getIncomingData());
272        }
273        return null;
274    }
275
276    /**
277     * Asks user to choose a WMS layer from a WMS endpoint.
278     * @param info the WMS endpoint.
279     * @param choice how the user may choose the WMS layer
280     * @return chosen WMS layer, or null
281     * @throws IOException if any I/O error occurs while contacting the WMS endpoint
282     * @throws WMSGetCapabilitiesException if the WMS getCapabilities request fails
283     * @throws InvalidPathException if a Path object cannot be constructed for the capabilities cached file
284     * @since 14549
285     */
286    public static ImageryInfo getWMSLayerInfo(ImageryInfo info, Function<WMSImagery, LayerSelection> choice)
287            throws IOException, WMSGetCapabilitiesException {
288        CheckParameterUtil.ensureThat(ImageryType.WMS_ENDPOINT == info.getImageryType(), "wms_endpoint imagery type expected");
289        // We need to get the URL with {apikey} replaced. See #22642.
290        final TemplatedWMSTileSource tileSource = new TemplatedWMSTileSource(info, ProjectionRegistry.getProjection());
291        final WMSImagery wms = new WMSImagery(tileSource.getBaseUrl(), info.getCustomHttpHeaders());
292        final LayerSelection selection = choice.apply(wms);
293        if (selection == null) {
294            return null;
295        }
296
297        final String url = wms.buildGetMapUrl(
298                selection.layers.stream().map(LayerDetails::getName).collect(Collectors.toList()),
299                (List<String>) null,
300                selection.format,
301                selection.transparent
302                );
303
304        final String selectedLayers = selection.layers.stream()
305                .map(LayerDetails::getName)
306                .collect(Collectors.joining(", "));
307        // Use full copy of original Imagery info to copy all attributes. Only overwrite what's different
308        final ImageryInfo ret = new ImageryInfo(info);
309        ret.setUrl(url);
310        ret.setImageryType(ImageryType.WMS);
311        ret.setName(info.getName() + " - " + selectedLayers);
312        ret.setServerProjections(wms.getServerProjections(selection.layers));
313        return ret;
314    }
315
316    private static void handleException(Exception ex, String uiMessage, String uiTitle, String logMessage) {
317        if (!GraphicsEnvironment.isHeadless()) {
318            JOptionPane.showMessageDialog(MainApplication.getMainFrame(), uiMessage, uiTitle, JOptionPane.ERROR_MESSAGE);
319        }
320        Logging.log(Logging.LEVEL_ERROR, logMessage, ex);
321    }
322
323    @Override
324    protected boolean listenToSelectionChange() {
325        return false;
326    }
327
328    @Override
329    protected void updateEnabledState() {
330        setEnabled(!info.isBlacklisted());
331    }
332
333    @Override
334    public String toString() {
335        return "AddImageryLayerAction [info=" + info + ']';
336    }
337}