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

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

fix EDT violation

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