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

Last change on this file was 18173, checked in by Don-vip, 3 years ago

fix #20690 - fix #21240 - Refactoring of UploadDialog, HistoryComboBox and AutoCompletingComboBox (patch by marcello)

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