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