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

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

see #20139 - avoid shortcut conflict between "open location" actions

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