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

Last change on this file since 11334 was 11329, checked in by simon04, 7 years ago

see #13201 - OsmUrlToBounds: also take Geo URLs into account

This adds Geo URL support to various actions, such as:

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