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

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

add unit test for Main.postConstructorProcessCmdLine

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