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