source: josm/trunk/src/org/openstreetmap/josm/actions/OpenLocationAction.java @ 13927

Last change on this file since 13927 was 13927, checked in by Don-vip, 4 months ago

see #11000 - Remote control: allow to specify layer_name for import

  • Property svn:eol-style set to native
File size: 13.9 KB
Line 
1// License: GPL. For details, see LICENSE file.
2package org.openstreetmap.josm.actions;
3
4import static org.openstreetmap.josm.gui.help.HelpUtil.ht;
5import static org.openstreetmap.josm.tools.I18n.tr;
6
7import java.awt.GridBagLayout;
8import java.awt.GridLayout;
9import java.awt.event.ActionEvent;
10import java.awt.event.KeyEvent;
11import java.util.ArrayList;
12import java.util.Collection;
13import java.util.Collections;
14import java.util.LinkedList;
15import java.util.List;
16import java.util.Objects;
17import java.util.concurrent.Future;
18import java.util.stream.Collectors;
19
20import javax.swing.JCheckBox;
21import javax.swing.JLabel;
22import javax.swing.JList;
23import javax.swing.JOptionPane;
24import javax.swing.JPanel;
25
26import org.openstreetmap.josm.Main;
27import org.openstreetmap.josm.actions.downloadtasks.DownloadGpsTask;
28import org.openstreetmap.josm.actions.downloadtasks.DownloadNotesTask;
29import org.openstreetmap.josm.actions.downloadtasks.DownloadNotesUrlBoundsTask;
30import org.openstreetmap.josm.actions.downloadtasks.DownloadNotesUrlIdTask;
31import org.openstreetmap.josm.actions.downloadtasks.DownloadOsmChangeCompressedTask;
32import org.openstreetmap.josm.actions.downloadtasks.DownloadOsmChangeTask;
33import org.openstreetmap.josm.actions.downloadtasks.DownloadOsmCompressedTask;
34import org.openstreetmap.josm.actions.downloadtasks.DownloadOsmIdTask;
35import org.openstreetmap.josm.actions.downloadtasks.DownloadOsmTask;
36import org.openstreetmap.josm.actions.downloadtasks.DownloadOsmUrlTask;
37import org.openstreetmap.josm.actions.downloadtasks.DownloadSessionTask;
38import org.openstreetmap.josm.actions.downloadtasks.DownloadParams;
39import org.openstreetmap.josm.actions.downloadtasks.DownloadTask;
40import org.openstreetmap.josm.actions.downloadtasks.PostDownloadHandler;
41import org.openstreetmap.josm.data.preferences.BooleanProperty;
42import org.openstreetmap.josm.gui.ExtendedDialog;
43import org.openstreetmap.josm.gui.HelpAwareOptionPane;
44import org.openstreetmap.josm.gui.MainApplication;
45import org.openstreetmap.josm.gui.progress.swing.PleaseWaitProgressMonitor;
46import org.openstreetmap.josm.gui.util.WindowGeometry;
47import org.openstreetmap.josm.gui.widgets.HistoryComboBox;
48import org.openstreetmap.josm.spi.preferences.Config;
49import org.openstreetmap.josm.tools.GBC;
50import org.openstreetmap.josm.tools.Logging;
51import org.openstreetmap.josm.tools.Shortcut;
52import org.openstreetmap.josm.tools.Utils;
53
54/**
55 * Open an URL input dialog and load data from the given URL.
56 *
57 * @author imi
58 */
59public class OpenLocationAction extends JosmAction {
60    /**
61     * true if the URL needs to be opened in a new layer, false otherwise
62     */
63    private static final BooleanProperty USE_NEW_LAYER = new BooleanProperty("download.location.newlayer", false);
64    /**
65     * true to zoom to entire newly downloaded data, false otherwise
66     */
67    private static final BooleanProperty DOWNLOAD_ZOOMTODATA = new BooleanProperty("download.location.zoomtodata", true);
68    /**
69     * the list of download tasks
70     */
71    protected final transient List<Class<? extends DownloadTask>> downloadTasks;
72
73    static class WhichTasksToPerformDialog extends ExtendedDialog {
74        WhichTasksToPerformDialog(JList<DownloadTask> list) {
75            super(Main.parent, tr("Which tasks to perform?"), new String[]{tr("Ok"), tr("Cancel")}, true);
76            setButtonIcons("ok", "cancel");
77            final JPanel pane = new JPanel(new GridLayout(2, 1));
78            pane.add(new JLabel(tr("Which tasks to perform?")));
79            pane.add(list);
80            setContent(pane);
81        }
82    }
83
84    /**
85     * Create an open action. The name is "Open a file".
86     */
87    public OpenLocationAction() {
88        /* I18N: Command to download a specific location/URL */
89        super(tr("Open Location..."), "openlocation", tr("Open an URL."),
90                Shortcut.registerShortcut("system:open_location", tr("File: {0}", tr("Open Location...")),
91                        KeyEvent.VK_L, Shortcut.CTRL), true);
92        putValue("help", ht("/Action/OpenLocation"));
93        this.downloadTasks = new ArrayList<>();
94        addDownloadTaskClass(DownloadOsmTask.class);
95        addDownloadTaskClass(DownloadGpsTask.class);
96        addDownloadTaskClass(DownloadNotesTask.class);
97        addDownloadTaskClass(DownloadOsmChangeTask.class);
98        addDownloadTaskClass(DownloadOsmUrlTask.class);
99        addDownloadTaskClass(DownloadOsmIdTask.class);
100        addDownloadTaskClass(DownloadOsmCompressedTask.class);
101        addDownloadTaskClass(DownloadOsmChangeCompressedTask.class);
102        addDownloadTaskClass(DownloadSessionTask.class);
103        addDownloadTaskClass(DownloadNotesUrlBoundsTask.class);
104        addDownloadTaskClass(DownloadNotesUrlIdTask.class);
105    }
106
107    /**
108     * Restore the current history from the preferences
109     *
110     * @param cbHistory the history combo box
111     */
112    protected void restoreUploadAddressHistory(HistoryComboBox cbHistory) {
113        List<String> cmtHistory = new LinkedList<>(Config.getPref().getList(getClass().getName() + ".uploadAddressHistory",
114                new LinkedList<String>()));
115        // we have to reverse the history, because ComboBoxHistory will reverse it again in addElement()
116        //
117        Collections.reverse(cmtHistory);
118        cbHistory.setPossibleItems(cmtHistory);
119    }
120
121    /**
122     * Remind the current history in the preferences
123     * @param cbHistory the history combo box
124     */
125    protected void remindUploadAddressHistory(HistoryComboBox cbHistory) {
126        cbHistory.addCurrentItemToHistory();
127        Config.getPref().putList(getClass().getName() + ".uploadAddressHistory", cbHistory.getHistory());
128    }
129
130    @Override
131    public void actionPerformed(ActionEvent e) {
132        JPanel all = new JPanel(new GridBagLayout());
133
134        // download URL selection
135        all.add(new JLabel(tr("Enter URL to download:")), GBC.eol());
136        HistoryComboBox uploadAddresses = new HistoryComboBox();
137        uploadAddresses.setToolTipText(tr("Enter an URL from where data should be downloaded"));
138        restoreUploadAddressHistory(uploadAddresses);
139        all.add(uploadAddresses, GBC.eop().fill(GBC.BOTH));
140
141        // use separate layer
142        JCheckBox layer = new JCheckBox(tr("Download as new layer"));
143        layer.setToolTipText(tr("Select if the data should be downloaded into a new layer"));
144        layer.setSelected(USE_NEW_LAYER.get());
145        all.add(layer, GBC.eop().fill(GBC.BOTH));
146
147        // zoom to downloaded data
148        JCheckBox zoom = new JCheckBox(tr("Zoom to downloaded data"));
149        zoom.setToolTipText(tr("Select to zoom to entire newly downloaded data."));
150        zoom.setSelected(DOWNLOAD_ZOOMTODATA.get());
151        all.add(zoom, GBC.eop().fill(GBC.BOTH));
152
153        ExpertToggleAction.addVisibilitySwitcher(zoom);
154
155        ExtendedDialog dialog = new ExtendedDialog(Main.parent,
156                tr("Download Location"),
157                tr("Download URL"), tr("Cancel"))
158            .setContent(all, false /* don't embedded content in JScrollpane  */)
159            .setButtonIcons("download", "cancel")
160            .setToolTipTexts(
161                tr("Start downloading data"),
162                tr("Close dialog and cancel downloading"))
163            .configureContextsensitiveHelp("/Action/OpenLocation", true /* show help button */);
164        dialog.setupDialog();
165        dialog.pack();
166        dialog.setRememberWindowGeometry(getClass().getName() + ".geometry",
167                    WindowGeometry.centerInWindow(Main.parent, dialog.getPreferredSize()));
168        if (dialog.showDialog().getValue() == 1) {
169            USE_NEW_LAYER.put(layer.isSelected());
170            DOWNLOAD_ZOOMTODATA.put(zoom.isSelected());
171            remindUploadAddressHistory(uploadAddresses);
172            openUrl(Utils.strip(uploadAddresses.getText()));
173        }
174    }
175
176    /**
177     * Replies the list of download tasks accepting the given url.
178     * @param url The URL to open
179     * @param isRemotecontrol True if download request comes from remotecontrol.
180     * @return The list of download tasks accepting the given url.
181     * @since 5691
182     */
183    public Collection<DownloadTask> findDownloadTasks(final String url, boolean isRemotecontrol) {
184        return downloadTasks.stream()
185                .filter(Objects::nonNull)
186                .map(taskClass -> {
187                    try {
188                        return taskClass.getConstructor().newInstance();
189                    } catch (ReflectiveOperationException e) {
190                        Logging.error(e);
191                        return null;
192                    }
193                })
194                .filter(Objects::nonNull)
195                .filter(task -> task.acceptsUrl(url, isRemotecontrol))
196                .collect(Collectors.toList());
197    }
198
199    /**
200     * Summarizes acceptable urls for error message purposes.
201     * @return The HTML message to be displayed
202     * @since 6031
203     */
204    public String findSummaryDocumentation() {
205        StringBuilder result = new StringBuilder("<table>");
206        for (Class<? extends DownloadTask> taskClass : downloadTasks) {
207            if (taskClass != null) {
208                try {
209                    DownloadTask task = taskClass.getConstructor().newInstance();
210                    result.append(task.acceptsDocumentationSummary());
211                } catch (ReflectiveOperationException e) {
212                    Logging.error(e);
213                }
214            }
215        }
216        result.append("</table>");
217        return result.toString();
218    }
219
220    /**
221     * Open the given URL.
222     * @param newLayer true if the URL needs to be opened in a new layer, false otherwise
223     * @param url The URL to open
224     * @return the list of tasks that have been started successfully (can be empty).
225     * @since 11986 (return type)
226     */
227    public List<Future<?>> openUrl(boolean newLayer, String url) {
228        return openUrl(new DownloadParams().withNewLayer(newLayer), url);
229    }
230
231    /**
232     * Open the given URL.
233     * @param settings download settings
234     * @param url The URL to open
235     * @return the list of tasks that have been started successfully (can be empty).
236     * @since 13927
237     */
238    public List<Future<?>> openUrl(DownloadParams settings, String url) {
239        return openUrl(settings, DOWNLOAD_ZOOMTODATA.get(), url);
240    }
241
242    /**
243     * Open the given URL. This class checks the {@link #USE_NEW_LAYER} preference to check if a new layer should be used.
244     * @param url The URL to open
245     * @return the list of tasks that have been started successfully (can be empty).
246     * @since 11986 (return type)
247     */
248    public List<Future<?>> openUrl(String url) {
249        return openUrl(USE_NEW_LAYER.get(), DOWNLOAD_ZOOMTODATA.get(), url);
250    }
251
252    /**
253     * Open the given URL.
254     * @param newLayer true if the URL needs to be opened in a new layer, false otherwise
255     * @param zoomToData true to zoom to entire newly downloaded data, false otherwise
256     * @param url The URL to open
257     * @return the list of tasks that have been started successfully (can be empty).
258     * @since 13261
259     */
260    public List<Future<?>> openUrl(boolean newLayer, boolean zoomToData, String url) {
261        return openUrl(new DownloadParams().withNewLayer(newLayer), zoomToData, url);
262    }
263
264    /**
265     * Open the given URL.
266     * @param settings download settings
267     * @param zoomToData true to zoom to entire newly downloaded data, false otherwise
268     * @param url The URL to open
269     * @return the list of tasks that have been started successfully (can be empty).
270     * @since 13927
271     */
272    public List<Future<?>> openUrl(DownloadParams settings, boolean zoomToData, String url) {
273        Collection<DownloadTask> tasks = findDownloadTasks(url, false);
274
275        if (tasks.size() > 1) {
276            tasks = askWhichTasksToLoad(tasks);
277        } else if (tasks.isEmpty()) {
278            warnNoSuitableTasks(url);
279            return Collections.emptyList();
280        }
281
282        PleaseWaitProgressMonitor monitor = new PleaseWaitProgressMonitor(tr("Download data"));
283
284        List<Future<?>> result = new ArrayList<>();
285        for (final DownloadTask task : tasks) {
286            try {
287                task.setZoomAfterDownload(zoomToData);
288                result.add(MainApplication.worker.submit(new PostDownloadHandler(task, task.loadUrl(settings, url, monitor))));
289            } catch (IllegalArgumentException e) {
290                Logging.error(e);
291            }
292        }
293        return result;
294    }
295
296    /**
297     * Asks the user which of the possible tasks to perform.
298     * @param tasks a list of possible tasks
299     * @return the selected tasks from the user or an empty list if the dialog has been canceled
300     */
301    Collection<DownloadTask> askWhichTasksToLoad(final Collection<DownloadTask> tasks) {
302        final JList<DownloadTask> list = new JList<>(tasks.toArray(new DownloadTask[0]));
303        list.addSelectionInterval(0, tasks.size() - 1);
304        final ExtendedDialog dialog = new WhichTasksToPerformDialog(list);
305        dialog.showDialog();
306        return dialog.getValue() == 1 ? list.getSelectedValuesList() : Collections.<DownloadTask>emptyList();
307    }
308
309    /**
310     * Displays an error message dialog that no suitable tasks have been found for the given url.
311     * @param url the given url
312     */
313    protected void warnNoSuitableTasks(final String url) {
314        final String details = findSummaryDocumentation();    // Explain what patterns are supported
315        HelpAwareOptionPane.showMessageDialogInEDT(Main.parent, "<html><p>" + tr(
316                "Cannot open URL ''{0}''<br>The following download tasks accept the URL patterns shown:<br>{1}",
317                url, details) + "</p></html>", tr("Download Location"), JOptionPane.ERROR_MESSAGE, ht("/Action/OpenLocation"));
318    }
319
320    /**
321     * Adds a new download task to the supported ones.
322     * @param taskClass The new download task to add
323     * @return <code>true</code> (as specified by {@link Collection#add})
324     */
325    public final boolean addDownloadTaskClass(Class<? extends DownloadTask> taskClass) {
326        return this.downloadTasks.add(taskClass);
327    }
328}
Note: See TracBrowser for help on using the repository browser.