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.GridBagConstraints;
008import java.awt.GridBagLayout;
009import java.awt.GridLayout;
010import java.awt.event.ActionEvent;
011import java.awt.event.KeyEvent;
012import java.util.ArrayList;
013import java.util.Collection;
014import java.util.Collections;
015import java.util.LinkedList;
016import java.util.List;
017import java.util.concurrent.Future;
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.Main;
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.DownloadOsmChangeCompressedTask;
031import org.openstreetmap.josm.actions.downloadtasks.DownloadOsmChangeTask;
032import org.openstreetmap.josm.actions.downloadtasks.DownloadOsmCompressedTask;
033import org.openstreetmap.josm.actions.downloadtasks.DownloadOsmIdTask;
034import org.openstreetmap.josm.actions.downloadtasks.DownloadOsmTask;
035import org.openstreetmap.josm.actions.downloadtasks.DownloadOsmUrlTask;
036import org.openstreetmap.josm.actions.downloadtasks.DownloadSessionTask;
037import org.openstreetmap.josm.actions.downloadtasks.DownloadTask;
038import org.openstreetmap.josm.actions.downloadtasks.PostDownloadHandler;
039import org.openstreetmap.josm.gui.ExtendedDialog;
040import org.openstreetmap.josm.gui.HelpAwareOptionPane;
041import org.openstreetmap.josm.gui.progress.PleaseWaitProgressMonitor;
042import org.openstreetmap.josm.gui.widgets.HistoryComboBox;
043import org.openstreetmap.josm.tools.Shortcut;
044import org.openstreetmap.josm.tools.Utils;
045
046/**
047 * Open an URL input dialog and load data from the given URL.
048 *
049 * @author imi
050 */
051public class OpenLocationAction extends JosmAction {
052
053    protected final transient List<Class<? extends DownloadTask>> downloadTasks;
054
055    /**
056     * Create an open action. The name is "Open a file".
057     */
058    public OpenLocationAction() {
059        /* I18N: Command to download a specific location/URL */
060        super(tr("Open Location..."), "openlocation", tr("Open an URL."),
061                Shortcut.registerShortcut("system:open_location", tr("File: {0}", tr("Open Location...")),
062                        KeyEvent.VK_L, Shortcut.CTRL), true);
063        putValue("help", ht("/Action/OpenLocation"));
064        this.downloadTasks = new ArrayList<>();
065        addDownloadTaskClass(DownloadOsmTask.class);
066        addDownloadTaskClass(DownloadGpsTask.class);
067        addDownloadTaskClass(DownloadNotesTask.class);
068        addDownloadTaskClass(DownloadOsmChangeTask.class);
069        addDownloadTaskClass(DownloadOsmUrlTask.class);
070        addDownloadTaskClass(DownloadOsmIdTask.class);
071        addDownloadTaskClass(DownloadOsmCompressedTask.class);
072        addDownloadTaskClass(DownloadOsmChangeCompressedTask.class);
073        addDownloadTaskClass(DownloadSessionTask.class);
074        addDownloadTaskClass(DownloadNotesUrlBoundsTask.class);
075        addDownloadTaskClass(DownloadNotesUrlIdTask.class);
076    }
077
078    /**
079     * Restore the current history from the preferences
080     *
081     * @param cbHistory the history combo box
082     */
083    protected void restoreUploadAddressHistory(HistoryComboBox cbHistory) {
084        List<String> cmtHistory = new LinkedList<>(Main.pref.getCollection(getClass().getName() + ".uploadAddressHistory",
085                new LinkedList<String>()));
086        // we have to reverse the history, because ComboBoxHistory will reverse it again in addElement()
087        //
088        Collections.reverse(cmtHistory);
089        cbHistory.setPossibleItems(cmtHistory);
090    }
091
092    /**
093     * Remind the current history in the preferences
094     * @param cbHistory the history combo box
095     */
096    protected void remindUploadAddressHistory(HistoryComboBox cbHistory) {
097        cbHistory.addCurrentItemToHistory();
098        Main.pref.putCollection(getClass().getName() + ".uploadAddressHistory", cbHistory.getHistory());
099    }
100
101    @Override
102    public void actionPerformed(ActionEvent e) {
103
104        JCheckBox layer = new JCheckBox(tr("Separate Layer"));
105        layer.setToolTipText(tr("Select if the data should be downloaded into a new layer"));
106        layer.setSelected(Main.pref.getBoolean("download.newlayer"));
107        JPanel all = new JPanel(new GridBagLayout());
108        GridBagConstraints gc = new GridBagConstraints();
109        gc.fill = GridBagConstraints.HORIZONTAL;
110        gc.weightx = 1.0;
111        gc.anchor = GridBagConstraints.FIRST_LINE_START;
112        all.add(new JLabel(tr("Enter URL to download:")), gc);
113        HistoryComboBox uploadAddresses = new HistoryComboBox();
114        uploadAddresses.setToolTipText(tr("Enter an URL from where data should be downloaded"));
115        restoreUploadAddressHistory(uploadAddresses);
116        gc.gridy = 1;
117        all.add(uploadAddresses, gc);
118        gc.gridy = 2;
119        gc.fill = GridBagConstraints.BOTH;
120        gc.weighty = 1.0;
121        all.add(layer, gc);
122        ExtendedDialog dialog = new ExtendedDialog(Main.parent,
123                tr("Download Location"),
124                new String[] {tr("Download URL"), tr("Cancel")}
125        );
126        dialog.setContent(all, false /* don't embedded content in JScrollpane  */);
127        dialog.setButtonIcons(new String[] {"download", "cancel"});
128        dialog.setToolTipTexts(new String[] {
129                tr("Start downloading data"),
130                tr("Close dialog and cancel downloading")
131        });
132        dialog.configureContextsensitiveHelp("/Action/OpenLocation", true /* show help button */);
133        dialog.showDialog();
134        if (dialog.getValue() != 1) return;
135        remindUploadAddressHistory(uploadAddresses);
136        openUrl(layer.isSelected(), Utils.strip(uploadAddresses.getText()));
137    }
138
139    /**
140     * Replies the list of download tasks accepting the given url.
141     * @param url The URL to open
142     * @param isRemotecontrol True if download request comes from remotecontrol.
143     * @return The list of download tasks accepting the given url.
144     * @since 5691
145     */
146    public Collection<DownloadTask> findDownloadTasks(final String url, boolean isRemotecontrol) {
147        List<DownloadTask> result = new ArrayList<>();
148        for (Class<? extends DownloadTask> taskClass : downloadTasks) {
149            if (taskClass != null) {
150                try {
151                    DownloadTask task = taskClass.getConstructor().newInstance();
152                    if (task.acceptsUrl(url, isRemotecontrol)) {
153                        result.add(task);
154                    }
155                } catch (Exception e) {
156                    Main.error(e);
157                }
158            }
159        }
160        return result;
161    }
162
163    /**
164     * Summarizes acceptable urls for error message purposes.
165     * @return The HTML message to be displayed
166     * @since 6031
167     */
168    public String findSummaryDocumentation() {
169        StringBuilder result = new StringBuilder("<table>");
170        for (Class<? extends DownloadTask> taskClass : downloadTasks) {
171            if (taskClass != null) {
172                try {
173                    DownloadTask task = taskClass.getConstructor().newInstance();
174                    result.append(task.acceptsDocumentationSummary());
175                } catch (Exception e) {
176                    Main.error(e);
177                }
178            }
179        }
180        result.append("</table>");
181        return result.toString();
182    }
183
184    /**
185     * Open the given URL.
186     * @param newLayer true if the URL needs to be opened in a new layer, false otherwise
187     * @param url The URL to open
188     */
189    public void openUrl(boolean newLayer, final String url) {
190        Collection<DownloadTask> tasks = findDownloadTasks(url, false);
191
192        if (tasks.size() > 1) {
193            tasks = askWhichTasksToLoad(tasks);
194        } else if (tasks.isEmpty()) {
195            warnNoSuitableTasks(url);
196            return;
197        }
198
199        PleaseWaitProgressMonitor monitor = new PleaseWaitProgressMonitor(tr("Download Data"));
200
201        for (final DownloadTask task : tasks) {
202            try {
203                Future<?> future = task.loadUrl(newLayer, url, monitor);
204                Main.worker.submit(new PostDownloadHandler(task, future));
205            } catch (IllegalArgumentException e) {
206                Main.error(e);
207            }
208        }
209    }
210
211    /**
212     * Asks the user which of the possible tasks to perform.
213     * @param tasks a list of possible tasks
214     * @return the selected tasks from the user or an empty list if the dialog has been canceled
215     */
216    Collection<DownloadTask> askWhichTasksToLoad(final Collection<DownloadTask> tasks) {
217        final JList<DownloadTask> list = new JList<>(tasks.toArray(new DownloadTask[tasks.size()]));
218        list.addSelectionInterval(0, tasks.size() - 1);
219        final ExtendedDialog dialog = new ExtendedDialog(Main.parent,
220                tr("Which tasks to perform?"), new String[]{tr("Ok"), tr("Cancel")}, true) { {
221            setButtonIcons(new String[]{"ok", "cancel"});
222            final JPanel pane = new JPanel(new GridLayout(2, 1));
223            pane.add(new JLabel(tr("Which tasks to perform?")));
224            pane.add(list);
225            setContent(pane);
226        } };
227        dialog.showDialog();
228        return dialog.getValue() == 1 ? list.getSelectedValuesList() : Collections.<DownloadTask>emptyList();
229    }
230
231    /**
232     * Displays an error message dialog that no suitable tasks have been found for the given url.
233     * @param url the given url
234     */
235    void warnNoSuitableTasks(final String url) {
236        final String details = findSummaryDocumentation();    // Explain what patterns are supported
237        HelpAwareOptionPane.showMessageDialogInEDT(Main.parent, "<html><p>" + tr(
238                "Cannot open URL ''{0}''<br>The following download tasks accept the URL patterns shown:<br>{1}",
239                url, details) + "</p></html>", tr("Download Location"), JOptionPane.ERROR_MESSAGE, ht("/Action/OpenLocation"));
240    }
241
242    /**
243     * Adds a new download task to the supported ones.
244     * @param taskClass The new download task to add
245     * @return <tt>true</tt> (as specified by {@link Collection#add})
246     */
247    public final boolean addDownloadTaskClass(Class<? extends DownloadTask> taskClass) {
248        return this.downloadTasks.add(taskClass);
249    }
250}