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

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

see #15182 - deprecate all Main logging methods and introduce suitable replacements in Logging for most of them

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