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