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

Last change on this file since 13107 was 12846, checked in by bastiK, 7 years ago

see #15229 - use Config.getPref() wherever possible

  • 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.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.newlayer", false);
62 /**
63 * the list of download tasks
64 */
65 protected final transient List<Class<? extends DownloadTask>> downloadTasks;
66
67 static class WhichTasksToPerformDialog extends ExtendedDialog {
68 WhichTasksToPerformDialog(JList<DownloadTask> list) {
69 super(Main.parent, tr("Which tasks to perform?"), new String[]{tr("Ok"), tr("Cancel")}, true);
70 setButtonIcons("ok", "cancel");
71 final JPanel pane = new JPanel(new GridLayout(2, 1));
72 pane.add(new JLabel(tr("Which tasks to perform?")));
73 pane.add(list);
74 setContent(pane);
75 }
76 }
77
78 /**
79 * Create an open action. The name is "Open a file".
80 */
81 public OpenLocationAction() {
82 /* I18N: Command to download a specific location/URL */
83 super(tr("Open Location..."), "openlocation", tr("Open an URL."),
84 Shortcut.registerShortcut("system:open_location", tr("File: {0}", tr("Open Location...")),
85 KeyEvent.VK_L, Shortcut.CTRL), true);
86 putValue("help", ht("/Action/OpenLocation"));
87 this.downloadTasks = new ArrayList<>();
88 addDownloadTaskClass(DownloadOsmTask.class);
89 addDownloadTaskClass(DownloadGpsTask.class);
90 addDownloadTaskClass(DownloadNotesTask.class);
91 addDownloadTaskClass(DownloadOsmChangeTask.class);
92 addDownloadTaskClass(DownloadOsmUrlTask.class);
93 addDownloadTaskClass(DownloadOsmIdTask.class);
94 addDownloadTaskClass(DownloadOsmCompressedTask.class);
95 addDownloadTaskClass(DownloadOsmChangeCompressedTask.class);
96 addDownloadTaskClass(DownloadSessionTask.class);
97 addDownloadTaskClass(DownloadNotesUrlBoundsTask.class);
98 addDownloadTaskClass(DownloadNotesUrlIdTask.class);
99 }
100
101 /**
102 * Restore the current history from the preferences
103 *
104 * @param cbHistory the history combo box
105 */
106 protected void restoreUploadAddressHistory(HistoryComboBox cbHistory) {
107 List<String> cmtHistory = new LinkedList<>(Config.getPref().getList(getClass().getName() + ".uploadAddressHistory",
108 new LinkedList<String>()));
109 // we have to reverse the history, because ComboBoxHistory will reverse it again in addElement()
110 //
111 Collections.reverse(cmtHistory);
112 cbHistory.setPossibleItems(cmtHistory);
113 }
114
115 /**
116 * Remind the current history in the preferences
117 * @param cbHistory the history combo box
118 */
119 protected void remindUploadAddressHistory(HistoryComboBox cbHistory) {
120 cbHistory.addCurrentItemToHistory();
121 Config.getPref().putList(getClass().getName() + ".uploadAddressHistory", cbHistory.getHistory());
122 }
123
124 @Override
125 public void actionPerformed(ActionEvent e) {
126 JPanel all = new JPanel(new GridBagLayout());
127
128 // download URL selection
129 all.add(new JLabel(tr("Enter URL to download:")), GBC.eol());
130 HistoryComboBox uploadAddresses = new HistoryComboBox();
131 uploadAddresses.setToolTipText(tr("Enter an URL from where data should be downloaded"));
132 restoreUploadAddressHistory(uploadAddresses);
133 all.add(uploadAddresses, GBC.eop().fill(GBC.BOTH));
134
135 // use separate layer
136 JCheckBox layer = new JCheckBox(tr("Separate Layer"));
137 layer.setToolTipText(tr("Select if the data should be downloaded into a new layer"));
138 layer.setSelected(USE_NEW_LAYER.get());
139 all.add(layer, GBC.eop().fill(GBC.BOTH));
140
141 ExtendedDialog dialog = new ExtendedDialog(Main.parent,
142 tr("Download Location"),
143 tr("Download URL"), tr("Cancel"))
144 .setContent(all, false /* don't embedded content in JScrollpane */)
145 .setButtonIcons("download", "cancel")
146 .setToolTipTexts(
147 tr("Start downloading data"),
148 tr("Close dialog and cancel downloading"))
149 .configureContextsensitiveHelp("/Action/OpenLocation", true /* show help button */);
150 if (dialog.showDialog().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 Logging.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 Logging.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(MainApplication.worker.submit(new PostDownloadHandler(task, task.loadUrl(newLayer, url, monitor))));
238 } catch (IllegalArgumentException e) {
239 Logging.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.