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

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

see #15182 - move the Swing-based ProgressMonitor implementations from gui.progress to gui.progress.swing. Progress monitor concept is used in very large parts of JOSM, a console-based implementation could be added later

  • Property svn:eol-style set to native
File size: 11.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.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.DownloadTask;
39import org.openstreetmap.josm.actions.downloadtasks.PostDownloadHandler;
40import org.openstreetmap.josm.data.preferences.BooleanProperty;
41import org.openstreetmap.josm.gui.ExtendedDialog;
42import org.openstreetmap.josm.gui.HelpAwareOptionPane;
43import org.openstreetmap.josm.gui.MainApplication;
44import org.openstreetmap.josm.gui.progress.swing.PleaseWaitProgressMonitor;
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.newlayer", false);
61 /**
62 * the list of download tasks
63 */
64 protected final transient List<Class<? extends DownloadTask>> downloadTasks;
65
66 static class WhichTasksToPerformDialog extends ExtendedDialog {
67 WhichTasksToPerformDialog(JList<DownloadTask> list) {
68 super(Main.parent, tr("Which tasks to perform?"), new String[]{tr("Ok"), tr("Cancel")}, true);
69 setButtonIcons("ok", "cancel");
70 final JPanel pane = new JPanel(new GridLayout(2, 1));
71 pane.add(new JLabel(tr("Which tasks to perform?")));
72 pane.add(list);
73 setContent(pane);
74 }
75 }
76
77 /**
78 * Create an open action. The name is "Open a file".
79 */
80 public OpenLocationAction() {
81 /* I18N: Command to download a specific location/URL */
82 super(tr("Open Location..."), "openlocation", tr("Open an URL."),
83 Shortcut.registerShortcut("system:open_location", tr("File: {0}", tr("Open Location...")),
84 KeyEvent.VK_L, Shortcut.CTRL), true);
85 putValue("help", ht("/Action/OpenLocation"));
86 this.downloadTasks = new ArrayList<>();
87 addDownloadTaskClass(DownloadOsmTask.class);
88 addDownloadTaskClass(DownloadGpsTask.class);
89 addDownloadTaskClass(DownloadNotesTask.class);
90 addDownloadTaskClass(DownloadOsmChangeTask.class);
91 addDownloadTaskClass(DownloadOsmUrlTask.class);
92 addDownloadTaskClass(DownloadOsmIdTask.class);
93 addDownloadTaskClass(DownloadOsmCompressedTask.class);
94 addDownloadTaskClass(DownloadOsmChangeCompressedTask.class);
95 addDownloadTaskClass(DownloadSessionTask.class);
96 addDownloadTaskClass(DownloadNotesUrlBoundsTask.class);
97 addDownloadTaskClass(DownloadNotesUrlIdTask.class);
98 }
99
100 /**
101 * Restore the current history from the preferences
102 *
103 * @param cbHistory the history combo box
104 */
105 protected void restoreUploadAddressHistory(HistoryComboBox cbHistory) {
106 List<String> cmtHistory = new LinkedList<>(Main.pref.getCollection(getClass().getName() + ".uploadAddressHistory",
107 new LinkedList<String>()));
108 // we have to reverse the history, because ComboBoxHistory will reverse it again in addElement()
109 //
110 Collections.reverse(cmtHistory);
111 cbHistory.setPossibleItems(cmtHistory);
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 Main.pref.putCollection(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("Separate 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 ExtendedDialog dialog = new ExtendedDialog(Main.parent,
141 tr("Download Location"),
142 tr("Download URL"), tr("Cancel"))
143 .setContent(all, false /* don't embedded content in JScrollpane */)
144 .setButtonIcons("download", "cancel")
145 .setToolTipTexts(
146 tr("Start downloading data"),
147 tr("Close dialog and cancel downloading"))
148 .configureContextsensitiveHelp("/Action/OpenLocation", true /* show help button */);
149 if (dialog.showDialog().getValue() == 1) {
150 USE_NEW_LAYER.put(layer.isSelected());
151 remindUploadAddressHistory(uploadAddresses);
152 openUrl(Utils.strip(uploadAddresses.getText()));
153 }
154 }
155
156 /**
157 * Replies the list of download tasks accepting the given url.
158 * @param url The URL to open
159 * @param isRemotecontrol True if download request comes from remotecontrol.
160 * @return The list of download tasks accepting the given url.
161 * @since 5691
162 */
163 public Collection<DownloadTask> findDownloadTasks(final String url, boolean isRemotecontrol) {
164 return downloadTasks.stream()
165 .filter(Objects::nonNull)
166 .map(taskClass -> {
167 try {
168 return taskClass.getConstructor().newInstance();
169 } catch (ReflectiveOperationException e) {
170 Logging.error(e);
171 return null;
172 }
173 })
174 .filter(Objects::nonNull)
175 .filter(task -> task.acceptsUrl(url, isRemotecontrol))
176 .collect(Collectors.toList());
177 }
178
179 /**
180 * Summarizes acceptable urls for error message purposes.
181 * @return The HTML message to be displayed
182 * @since 6031
183 */
184 public String findSummaryDocumentation() {
185 StringBuilder result = new StringBuilder("<table>");
186 for (Class<? extends DownloadTask> taskClass : downloadTasks) {
187 if (taskClass != null) {
188 try {
189 DownloadTask task = taskClass.getConstructor().newInstance();
190 result.append(task.acceptsDocumentationSummary());
191 } catch (ReflectiveOperationException e) {
192 Logging.error(e);
193 }
194 }
195 }
196 result.append("</table>");
197 return result.toString();
198 }
199
200 /**
201 * Open the given URL.
202 * @param newLayer true if the URL needs to be opened in a new layer, false otherwise
203 * @param url The URL to open
204 * @return the list of tasks that have been started successfully (can be empty).
205 * @since 11986 (return type)
206 */
207 public List<Future<?>> openUrl(boolean newLayer, String url) {
208 return realOpenUrl(newLayer, url);
209 }
210
211 /**
212 * Open the given URL. This class checks the {@link #USE_NEW_LAYER} preference to check if a new layer should be used.
213 * @param url The URL to open
214 * @return the list of tasks that have been started successfully (can be empty).
215 * @since 11986 (return type)
216 */
217 public List<Future<?>> openUrl(String url) {
218 return realOpenUrl(USE_NEW_LAYER.get(), url);
219 }
220
221 private List<Future<?>> realOpenUrl(boolean newLayer, String url) {
222 Collection<DownloadTask> tasks = findDownloadTasks(url, false);
223
224 if (tasks.size() > 1) {
225 tasks = askWhichTasksToLoad(tasks);
226 } else if (tasks.isEmpty()) {
227 warnNoSuitableTasks(url);
228 return Collections.emptyList();
229 }
230
231 PleaseWaitProgressMonitor monitor = new PleaseWaitProgressMonitor(tr("Download Data"));
232
233 List<Future<?>> result = new ArrayList<>();
234 for (final DownloadTask task : tasks) {
235 try {
236 result.add(MainApplication.worker.submit(new PostDownloadHandler(task, task.loadUrl(newLayer, url, monitor))));
237 } catch (IllegalArgumentException e) {
238 Logging.error(e);
239 }
240 }
241 return result;
242 }
243
244 /**
245 * Asks the user which of the possible tasks to perform.
246 * @param tasks a list of possible tasks
247 * @return the selected tasks from the user or an empty list if the dialog has been canceled
248 */
249 Collection<DownloadTask> askWhichTasksToLoad(final Collection<DownloadTask> tasks) {
250 final JList<DownloadTask> list = new JList<>(tasks.toArray(new DownloadTask[tasks.size()]));
251 list.addSelectionInterval(0, tasks.size() - 1);
252 final ExtendedDialog dialog = new WhichTasksToPerformDialog(list);
253 dialog.showDialog();
254 return dialog.getValue() == 1 ? list.getSelectedValuesList() : Collections.<DownloadTask>emptyList();
255 }
256
257 /**
258 * Displays an error message dialog that no suitable tasks have been found for the given url.
259 * @param url the given url
260 */
261 protected void warnNoSuitableTasks(final String url) {
262 final String details = findSummaryDocumentation(); // Explain what patterns are supported
263 HelpAwareOptionPane.showMessageDialogInEDT(Main.parent, "<html><p>" + tr(
264 "Cannot open URL ''{0}''<br>The following download tasks accept the URL patterns shown:<br>{1}",
265 url, details) + "</p></html>", tr("Download Location"), JOptionPane.ERROR_MESSAGE, ht("/Action/OpenLocation"));
266 }
267
268 /**
269 * Adds a new download task to the supported ones.
270 * @param taskClass The new download task to add
271 * @return <tt>true</tt> (as specified by {@link Collection#add})
272 */
273 public final boolean addDownloadTaskClass(Class<? extends DownloadTask> taskClass) {
274 return this.downloadTasks.add(taskClass);
275 }
276}
Note: See TracBrowser for help on using the repository browser.