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.tr;
006
007import java.awt.GridBagLayout;
008import java.awt.GridLayout;
009import java.awt.event.ActionEvent;
010import java.awt.event.KeyEvent;
011import java.util.ArrayList;
012import java.util.Collection;
013import java.util.Collections;
014import java.util.List;
015import java.util.Objects;
016import java.util.concurrent.Future;
017import java.util.stream.Collectors;
018
019import javax.swing.JCheckBox;
020import javax.swing.JLabel;
021import javax.swing.JList;
022import javax.swing.JOptionPane;
023import javax.swing.JPanel;
024
025import org.openstreetmap.josm.actions.downloadtasks.DownloadGeoJsonTask;
026import org.openstreetmap.josm.actions.downloadtasks.DownloadGpsTask;
027import org.openstreetmap.josm.actions.downloadtasks.DownloadNotesTask;
028import org.openstreetmap.josm.actions.downloadtasks.DownloadNotesUrlBoundsTask;
029import org.openstreetmap.josm.actions.downloadtasks.DownloadNotesUrlIdTask;
030import org.openstreetmap.josm.actions.downloadtasks.DownloadOsmChangeTask;
031import org.openstreetmap.josm.actions.downloadtasks.DownloadOsmIdTask;
032import org.openstreetmap.josm.actions.downloadtasks.DownloadOsmTask;
033import org.openstreetmap.josm.actions.downloadtasks.DownloadOsmUrlTask;
034import org.openstreetmap.josm.actions.downloadtasks.DownloadParams;
035import org.openstreetmap.josm.actions.downloadtasks.DownloadSessionTask;
036import org.openstreetmap.josm.actions.downloadtasks.DownloadTask;
037import org.openstreetmap.josm.actions.downloadtasks.PostDownloadHandler;
038import org.openstreetmap.josm.data.preferences.BooleanProperty;
039import org.openstreetmap.josm.gui.ExtendedDialog;
040import org.openstreetmap.josm.gui.HelpAwareOptionPane;
041import org.openstreetmap.josm.gui.MainApplication;
042import org.openstreetmap.josm.gui.progress.swing.PleaseWaitProgressMonitor;
043import org.openstreetmap.josm.gui.util.WindowGeometry;
044import org.openstreetmap.josm.gui.widgets.HistoryComboBox;
045import org.openstreetmap.josm.spi.preferences.Config;
046import org.openstreetmap.josm.tools.GBC;
047import org.openstreetmap.josm.tools.Logging;
048import org.openstreetmap.josm.tools.Shortcut;
049import org.openstreetmap.josm.tools.Utils;
050
051/**
052 * Open an URL input dialog and load data from the given URL.
053 *
054 * @author imi
055 */
056public class OpenLocationAction extends JosmAction {
057    /**
058     * true if the URL needs to be opened in a new layer, false otherwise
059     */
060    private static final BooleanProperty USE_NEW_LAYER = new BooleanProperty("download.location.newlayer", false);
061    /**
062     * true to zoom to entire newly downloaded data, false otherwise
063     */
064    private static final BooleanProperty DOWNLOAD_ZOOMTODATA = new BooleanProperty("download.location.zoomtodata", true);
065    /**
066     * the list of download tasks
067     */
068    protected final transient List<Class<? extends DownloadTask>> downloadTasks;
069
070    static class WhichTasksToPerformDialog extends ExtendedDialog {
071        WhichTasksToPerformDialog(JList<DownloadTask> list) {
072            super(MainApplication.getMainFrame(), tr("Which tasks to perform?"), new String[]{tr("Ok"), tr("Cancel")}, true);
073            setButtonIcons("ok", "cancel");
074            final JPanel pane = new JPanel(new GridLayout(2, 1));
075            pane.add(new JLabel(tr("Which tasks to perform?")));
076            pane.add(list);
077            setContent(pane);
078        }
079    }
080
081    /**
082     * Create an open action. The name is "Open a file".
083     */
084    public OpenLocationAction() {
085        /* I18N: Command to download a specific location/URL */
086        super(tr("Open Location..."), "openlocation", tr("Open an URL."),
087                Shortcut.registerShortcut("system:open_location", tr("File: {0}", tr("Open Location...")),
088                        KeyEvent.VK_L, Shortcut.CTRL), true);
089        setHelpId(ht("/Action/OpenLocation"));
090        this.downloadTasks = new ArrayList<>();
091        addDownloadTaskClass(DownloadOsmTask.class);
092        addDownloadTaskClass(DownloadGpsTask.class);
093        addDownloadTaskClass(DownloadNotesTask.class);
094        addDownloadTaskClass(DownloadOsmChangeTask.class);
095        addDownloadTaskClass(DownloadOsmUrlTask.class);
096        addDownloadTaskClass(DownloadOsmIdTask.class);
097        addDownloadTaskClass(DownloadSessionTask.class);
098        addDownloadTaskClass(DownloadNotesUrlBoundsTask.class);
099        addDownloadTaskClass(DownloadNotesUrlIdTask.class);
100        addDownloadTaskClass(DownloadGeoJsonTask.class);
101    }
102
103    /**
104     * Restore the current history from the preferences
105     *
106     * @param cbHistory the history combo box
107     */
108    protected void restoreUploadAddressHistory(HistoryComboBox cbHistory) {
109        cbHistory.setPossibleItemsTopDown(Config.getPref().getList(getClass().getName() + ".uploadAddressHistory",
110                Collections.emptyList()));
111    }
112
113    /**
114     * Remind the current history in the preferences
115     * @param cbHistory the history combo box
116     */
117    protected void remindUploadAddressHistory(HistoryComboBox cbHistory) {
118        cbHistory.addCurrentItemToHistory();
119        Config.getPref().putList(getClass().getName() + ".uploadAddressHistory", cbHistory.getHistory());
120    }
121
122    @Override
123    public void actionPerformed(ActionEvent e) {
124        JPanel all = new JPanel(new GridBagLayout());
125
126        // download URL selection
127        all.add(new JLabel(tr("Enter URL to download:")), GBC.eol());
128        HistoryComboBox uploadAddresses = new HistoryComboBox();
129        uploadAddresses.setToolTipText(tr("Enter an URL from where data should be downloaded"));
130        restoreUploadAddressHistory(uploadAddresses);
131        all.add(uploadAddresses, GBC.eop().fill(GBC.BOTH));
132
133        // use separate layer
134        JCheckBox layer = new JCheckBox(tr("Download as new layer"));
135        layer.setToolTipText(tr("Select if the data should be downloaded into a new layer"));
136        layer.setSelected(USE_NEW_LAYER.get());
137        all.add(layer, GBC.eop().fill(GBC.BOTH));
138
139        // zoom to downloaded data
140        JCheckBox zoom = new JCheckBox(tr("Zoom to downloaded data"));
141        zoom.setToolTipText(tr("Select to zoom to entire newly downloaded data."));
142        zoom.setSelected(DOWNLOAD_ZOOMTODATA.get());
143        all.add(zoom, GBC.eop().fill(GBC.BOTH));
144
145        ExpertToggleAction.addVisibilitySwitcher(zoom);
146
147        ExtendedDialog dialog = new ExtendedDialog(MainApplication.getMainFrame(),
148                tr("Download Location"),
149                tr("Download URL"), tr("Cancel"))
150            .setContent(all, false /* don't embedded content in JScrollpane  */)
151            .setButtonIcons("download", "cancel")
152            .setToolTipTexts(
153                tr("Start downloading data"),
154                tr("Close dialog and cancel downloading"))
155            .configureContextsensitiveHelp("/Action/OpenLocation", true /* show help button */);
156        dialog.setupDialog();
157        dialog.pack();
158        dialog.setRememberWindowGeometry(getClass().getName() + ".geometry",
159                    WindowGeometry.centerInWindow(MainApplication.getMainFrame(), dialog.getPreferredSize()));
160        if (dialog.showDialog().getValue() == 1) {
161            USE_NEW_LAYER.put(layer.isSelected());
162            DOWNLOAD_ZOOMTODATA.put(zoom.isSelected());
163            remindUploadAddressHistory(uploadAddresses);
164            openUrl(Utils.strip(uploadAddresses.getText()));
165        }
166    }
167
168    /**
169     * Replies the list of download tasks accepting the given url.
170     * @param url The URL to open
171     * @param isRemotecontrol True if download request comes from remotecontrol.
172     * @return The list of download tasks accepting the given url.
173     * @since 5691
174     */
175    public Collection<DownloadTask> findDownloadTasks(final String url, boolean isRemotecontrol) {
176        return downloadTasks.stream()
177                .filter(Objects::nonNull)
178                .map(taskClass -> {
179                    try {
180                        return taskClass.getConstructor().newInstance();
181                    } catch (ReflectiveOperationException e) {
182                        Logging.error(e);
183                        return null;
184                    }
185                })
186                .filter(Objects::nonNull)
187                .filter(task -> task.acceptsUrl(url, isRemotecontrol))
188                .collect(Collectors.toList());
189    }
190
191    /**
192     * Summarizes acceptable urls for error message purposes.
193     * @return The HTML message to be displayed
194     * @since 6031
195     */
196    public String findSummaryDocumentation() {
197        StringBuilder result = new StringBuilder("<table>");
198        for (Class<? extends DownloadTask> taskClass : downloadTasks) {
199            if (taskClass != null) {
200                try {
201                    DownloadTask task = taskClass.getConstructor().newInstance();
202                    result.append(task.acceptsDocumentationSummary());
203                } catch (ReflectiveOperationException e) {
204                    Logging.error(e);
205                }
206            }
207        }
208        result.append("</table>");
209        return result.toString();
210    }
211
212    /**
213     * Open the given URL.
214     * @param newLayer true if the URL needs to be opened in a new layer, false otherwise
215     * @param url The URL to open
216     * @return the list of tasks that have been started successfully (can be empty).
217     * @since 11986 (return type)
218     */
219    public List<Future<?>> openUrl(boolean newLayer, String url) {
220        return openUrl(new DownloadParams().withNewLayer(newLayer), url);
221    }
222
223    /**
224     * Open the given URL.
225     * @param settings download settings
226     * @param url The URL to open
227     * @return the list of tasks that have been started successfully (can be empty).
228     * @since 13927
229     */
230    public List<Future<?>> openUrl(DownloadParams settings, String url) {
231        return openUrl(settings, DOWNLOAD_ZOOMTODATA.get(), url);
232    }
233
234    /**
235     * Open the given URL. This class checks the {@link #USE_NEW_LAYER} preference to check if a new layer should be used.
236     * @param url The URL to open
237     * @return the list of tasks that have been started successfully (can be empty).
238     * @since 11986 (return type)
239     */
240    public List<Future<?>> openUrl(String url) {
241        return openUrl(USE_NEW_LAYER.get(), DOWNLOAD_ZOOMTODATA.get(), url);
242    }
243
244    /**
245     * Open the given URL.
246     * @param newLayer true if the URL needs to be opened in a new layer, false otherwise
247     * @param zoomToData true to zoom to entire newly downloaded data, false otherwise
248     * @param url The URL to open
249     * @return the list of tasks that have been started successfully (can be empty).
250     * @since 13261
251     */
252    public List<Future<?>> openUrl(boolean newLayer, boolean zoomToData, String url) {
253        return openUrl(new DownloadParams().withNewLayer(newLayer), zoomToData, url);
254    }
255
256    /**
257     * Open the given URL.
258     * @param settings download settings
259     * @param zoomToData true to zoom to entire newly downloaded data, false otherwise
260     * @param url The URL to open
261     * @return the list of tasks that have been started successfully (can be empty).
262     * @since 13927
263     */
264    public List<Future<?>> openUrl(DownloadParams settings, boolean zoomToData, String url) {
265        Collection<DownloadTask> tasks = findDownloadTasks(url, false);
266
267        if (tasks.size() > 1) {
268            tasks = askWhichTasksToLoad(tasks);
269        } else if (tasks.isEmpty()) {
270            warnNoSuitableTasks(url);
271            return Collections.emptyList();
272        }
273
274        PleaseWaitProgressMonitor monitor = new PleaseWaitProgressMonitor(tr("Download data"));
275
276        List<Future<?>> result = new ArrayList<>();
277        for (final DownloadTask task : tasks) {
278            try {
279                task.setZoomAfterDownload(zoomToData);
280                result.add(MainApplication.worker.submit(new PostDownloadHandler(task, task.loadUrl(settings, url, monitor))));
281            } catch (IllegalArgumentException e) {
282                Logging.error(e);
283            }
284        }
285        return result;
286    }
287
288    /**
289     * Asks the user which of the possible tasks to perform.
290     * @param tasks a list of possible tasks
291     * @return the selected tasks from the user or an empty list if the dialog has been canceled
292     */
293    Collection<DownloadTask> askWhichTasksToLoad(final Collection<DownloadTask> tasks) {
294        final JList<DownloadTask> list = new JList<>(tasks.toArray(new DownloadTask[0]));
295        list.addSelectionInterval(0, tasks.size() - 1);
296        final ExtendedDialog dialog = new WhichTasksToPerformDialog(list);
297        dialog.showDialog();
298        return dialog.getValue() == 1 ? list.getSelectedValuesList() : Collections.<DownloadTask>emptyList();
299    }
300
301    /**
302     * Displays an error message dialog that no suitable tasks have been found for the given url.
303     * @param url the given url
304     */
305    protected void warnNoSuitableTasks(final String url) {
306        final String details = findSummaryDocumentation();    // Explain what patterns are supported
307        HelpAwareOptionPane.showMessageDialogInEDT(MainApplication.getMainFrame(), "<html><p>" + tr(
308                "Cannot open URL ''{0}''<br>The following download tasks accept the URL patterns shown:<br>{1}",
309                url, details) + "</p></html>", tr("Download Location"), JOptionPane.ERROR_MESSAGE, ht("/Action/OpenLocation"));
310    }
311
312    /**
313     * Adds a new download task to the supported ones.
314     * @param taskClass The new download task to add
315     * @return <code>true</code> (as specified by {@link Collection#add})
316     */
317    public final boolean addDownloadTaskClass(Class<? extends DownloadTask> taskClass) {
318        return this.downloadTasks.add(taskClass);
319    }
320}