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

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

see #18613 - rework download tasks / URL patterns

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