001// License: GPL. For details, see LICENSE file. 002package org.openstreetmap.josm.actions; 003 004import static org.openstreetmap.josm.gui.help.HelpUtil.ht; 005import static org.openstreetmap.josm.tools.I18n.tr; 006 007import java.awt.GridBagLayout; 008import java.awt.GridLayout; 009import java.awt.event.ActionEvent; 010import java.awt.event.KeyEvent; 011import java.util.ArrayList; 012import java.util.Collection; 013import java.util.Collections; 014import java.util.LinkedList; 015import java.util.List; 016import java.util.Objects; 017import java.util.concurrent.Future; 018import java.util.stream.Collectors; 019 020import javax.swing.JCheckBox; 021import javax.swing.JLabel; 022import javax.swing.JList; 023import javax.swing.JOptionPane; 024import javax.swing.JPanel; 025 026import org.openstreetmap.josm.Main; 027import org.openstreetmap.josm.actions.downloadtasks.DownloadGpsTask; 028import org.openstreetmap.josm.actions.downloadtasks.DownloadNotesTask; 029import org.openstreetmap.josm.actions.downloadtasks.DownloadNotesUrlBoundsTask; 030import org.openstreetmap.josm.actions.downloadtasks.DownloadNotesUrlIdTask; 031import org.openstreetmap.josm.actions.downloadtasks.DownloadOsmChangeCompressedTask; 032import org.openstreetmap.josm.actions.downloadtasks.DownloadOsmChangeTask; 033import org.openstreetmap.josm.actions.downloadtasks.DownloadOsmCompressedTask; 034import org.openstreetmap.josm.actions.downloadtasks.DownloadOsmIdTask; 035import org.openstreetmap.josm.actions.downloadtasks.DownloadOsmTask; 036import org.openstreetmap.josm.actions.downloadtasks.DownloadOsmUrlTask; 037import org.openstreetmap.josm.actions.downloadtasks.DownloadSessionTask; 038import org.openstreetmap.josm.actions.downloadtasks.DownloadParams; 039import org.openstreetmap.josm.actions.downloadtasks.DownloadTask; 040import org.openstreetmap.josm.actions.downloadtasks.PostDownloadHandler; 041import org.openstreetmap.josm.data.preferences.BooleanProperty; 042import org.openstreetmap.josm.gui.ExtendedDialog; 043import org.openstreetmap.josm.gui.HelpAwareOptionPane; 044import org.openstreetmap.josm.gui.MainApplication; 045import org.openstreetmap.josm.gui.progress.swing.PleaseWaitProgressMonitor; 046import org.openstreetmap.josm.gui.util.WindowGeometry; 047import org.openstreetmap.josm.gui.widgets.HistoryComboBox; 048import org.openstreetmap.josm.spi.preferences.Config; 049import org.openstreetmap.josm.tools.GBC; 050import org.openstreetmap.josm.tools.Logging; 051import org.openstreetmap.josm.tools.Shortcut; 052import org.openstreetmap.josm.tools.Utils; 053 054/** 055 * Open an URL input dialog and load data from the given URL. 056 * 057 * @author imi 058 */ 059public class OpenLocationAction extends JosmAction { 060 /** 061 * true if the URL needs to be opened in a new layer, false otherwise 062 */ 063 private static final BooleanProperty USE_NEW_LAYER = new BooleanProperty("download.location.newlayer", false); 064 /** 065 * true to zoom to entire newly downloaded data, false otherwise 066 */ 067 private static final BooleanProperty DOWNLOAD_ZOOMTODATA = new BooleanProperty("download.location.zoomtodata", true); 068 /** 069 * the list of download tasks 070 */ 071 protected final transient List<Class<? extends DownloadTask>> downloadTasks; 072 073 static class WhichTasksToPerformDialog extends ExtendedDialog { 074 WhichTasksToPerformDialog(JList<DownloadTask> list) { 075 super(Main.parent, tr("Which tasks to perform?"), new String[]{tr("Ok"), tr("Cancel")}, true); 076 setButtonIcons("ok", "cancel"); 077 final JPanel pane = new JPanel(new GridLayout(2, 1)); 078 pane.add(new JLabel(tr("Which tasks to perform?"))); 079 pane.add(list); 080 setContent(pane); 081 } 082 } 083 084 /** 085 * Create an open action. The name is "Open a file". 086 */ 087 public OpenLocationAction() { 088 /* I18N: Command to download a specific location/URL */ 089 super(tr("Open Location..."), "openlocation", tr("Open an URL."), 090 Shortcut.registerShortcut("system:open_location", tr("File: {0}", tr("Open Location...")), 091 KeyEvent.VK_L, Shortcut.CTRL), true); 092 putValue("help", ht("/Action/OpenLocation")); 093 this.downloadTasks = new ArrayList<>(); 094 addDownloadTaskClass(DownloadOsmTask.class); 095 addDownloadTaskClass(DownloadGpsTask.class); 096 addDownloadTaskClass(DownloadNotesTask.class); 097 addDownloadTaskClass(DownloadOsmChangeTask.class); 098 addDownloadTaskClass(DownloadOsmUrlTask.class); 099 addDownloadTaskClass(DownloadOsmIdTask.class); 100 addDownloadTaskClass(DownloadOsmCompressedTask.class); 101 addDownloadTaskClass(DownloadOsmChangeCompressedTask.class); 102 addDownloadTaskClass(DownloadSessionTask.class); 103 addDownloadTaskClass(DownloadNotesUrlBoundsTask.class); 104 addDownloadTaskClass(DownloadNotesUrlIdTask.class); 105 } 106 107 /** 108 * Restore the current history from the preferences 109 * 110 * @param cbHistory the history combo box 111 */ 112 protected void restoreUploadAddressHistory(HistoryComboBox cbHistory) { 113 List<String> cmtHistory = new LinkedList<>(Config.getPref().getList(getClass().getName() + ".uploadAddressHistory", 114 new LinkedList<String>())); 115 // we have to reverse the history, because ComboBoxHistory will reverse it again in addElement() 116 // 117 Collections.reverse(cmtHistory); 118 cbHistory.setPossibleItems(cmtHistory); 119 } 120 121 /** 122 * Remind the current history in the preferences 123 * @param cbHistory the history combo box 124 */ 125 protected void remindUploadAddressHistory(HistoryComboBox cbHistory) { 126 cbHistory.addCurrentItemToHistory(); 127 Config.getPref().putList(getClass().getName() + ".uploadAddressHistory", cbHistory.getHistory()); 128 } 129 130 @Override 131 public void actionPerformed(ActionEvent e) { 132 JPanel all = new JPanel(new GridBagLayout()); 133 134 // download URL selection 135 all.add(new JLabel(tr("Enter URL to download:")), GBC.eol()); 136 HistoryComboBox uploadAddresses = new HistoryComboBox(); 137 uploadAddresses.setToolTipText(tr("Enter an URL from where data should be downloaded")); 138 restoreUploadAddressHistory(uploadAddresses); 139 all.add(uploadAddresses, GBC.eop().fill(GBC.BOTH)); 140 141 // use separate layer 142 JCheckBox layer = new JCheckBox(tr("Download as new layer")); 143 layer.setToolTipText(tr("Select if the data should be downloaded into a new layer")); 144 layer.setSelected(USE_NEW_LAYER.get()); 145 all.add(layer, GBC.eop().fill(GBC.BOTH)); 146 147 // zoom to downloaded data 148 JCheckBox zoom = new JCheckBox(tr("Zoom to downloaded data")); 149 zoom.setToolTipText(tr("Select to zoom to entire newly downloaded data.")); 150 zoom.setSelected(DOWNLOAD_ZOOMTODATA.get()); 151 all.add(zoom, GBC.eop().fill(GBC.BOTH)); 152 153 ExpertToggleAction.addVisibilitySwitcher(zoom); 154 155 ExtendedDialog dialog = new ExtendedDialog(Main.parent, 156 tr("Download Location"), 157 tr("Download URL"), tr("Cancel")) 158 .setContent(all, false /* don't embedded content in JScrollpane */) 159 .setButtonIcons("download", "cancel") 160 .setToolTipTexts( 161 tr("Start downloading data"), 162 tr("Close dialog and cancel downloading")) 163 .configureContextsensitiveHelp("/Action/OpenLocation", true /* show help button */); 164 dialog.setupDialog(); 165 dialog.pack(); 166 dialog.setRememberWindowGeometry(getClass().getName() + ".geometry", 167 WindowGeometry.centerInWindow(Main.parent, dialog.getPreferredSize())); 168 if (dialog.showDialog().getValue() == 1) { 169 USE_NEW_LAYER.put(layer.isSelected()); 170 DOWNLOAD_ZOOMTODATA.put(zoom.isSelected()); 171 remindUploadAddressHistory(uploadAddresses); 172 openUrl(Utils.strip(uploadAddresses.getText())); 173 } 174 } 175 176 /** 177 * Replies the list of download tasks accepting the given url. 178 * @param url The URL to open 179 * @param isRemotecontrol True if download request comes from remotecontrol. 180 * @return The list of download tasks accepting the given url. 181 * @since 5691 182 */ 183 public Collection<DownloadTask> findDownloadTasks(final String url, boolean isRemotecontrol) { 184 return downloadTasks.stream() 185 .filter(Objects::nonNull) 186 .map(taskClass -> { 187 try { 188 return taskClass.getConstructor().newInstance(); 189 } catch (ReflectiveOperationException e) { 190 Logging.error(e); 191 return null; 192 } 193 }) 194 .filter(Objects::nonNull) 195 .filter(task -> task.acceptsUrl(url, isRemotecontrol)) 196 .collect(Collectors.toList()); 197 } 198 199 /** 200 * Summarizes acceptable urls for error message purposes. 201 * @return The HTML message to be displayed 202 * @since 6031 203 */ 204 public String findSummaryDocumentation() { 205 StringBuilder result = new StringBuilder("<table>"); 206 for (Class<? extends DownloadTask> taskClass : downloadTasks) { 207 if (taskClass != null) { 208 try { 209 DownloadTask task = taskClass.getConstructor().newInstance(); 210 result.append(task.acceptsDocumentationSummary()); 211 } catch (ReflectiveOperationException e) { 212 Logging.error(e); 213 } 214 } 215 } 216 result.append("</table>"); 217 return result.toString(); 218 } 219 220 /** 221 * Open the given URL. 222 * @param newLayer true if the URL needs to be opened in a new layer, false otherwise 223 * @param url The URL to open 224 * @return the list of tasks that have been started successfully (can be empty). 225 * @since 11986 (return type) 226 */ 227 public List<Future<?>> openUrl(boolean newLayer, String url) { 228 return openUrl(new DownloadParams().withNewLayer(newLayer), url); 229 } 230 231 /** 232 * Open the given URL. 233 * @param settings download settings 234 * @param url The URL to open 235 * @return the list of tasks that have been started successfully (can be empty). 236 * @since 13927 237 */ 238 public List<Future<?>> openUrl(DownloadParams settings, String url) { 239 return openUrl(settings, DOWNLOAD_ZOOMTODATA.get(), url); 240 } 241 242 /** 243 * Open the given URL. This class checks the {@link #USE_NEW_LAYER} preference to check if a new layer should be used. 244 * @param url The URL to open 245 * @return the list of tasks that have been started successfully (can be empty). 246 * @since 11986 (return type) 247 */ 248 public List<Future<?>> openUrl(String url) { 249 return openUrl(USE_NEW_LAYER.get(), DOWNLOAD_ZOOMTODATA.get(), url); 250 } 251 252 /** 253 * Open the given URL. 254 * @param newLayer true if the URL needs to be opened in a new layer, false otherwise 255 * @param zoomToData true to zoom to entire newly downloaded data, false otherwise 256 * @param url The URL to open 257 * @return the list of tasks that have been started successfully (can be empty). 258 * @since 13261 259 */ 260 public List<Future<?>> openUrl(boolean newLayer, boolean zoomToData, String url) { 261 return openUrl(new DownloadParams().withNewLayer(newLayer), zoomToData, url); 262 } 263 264 /** 265 * Open the given URL. 266 * @param settings download settings 267 * @param zoomToData true to zoom to entire newly downloaded data, false otherwise 268 * @param url The URL to open 269 * @return the list of tasks that have been started successfully (can be empty). 270 * @since 13927 271 */ 272 public List<Future<?>> openUrl(DownloadParams settings, boolean zoomToData, String url) { 273 Collection<DownloadTask> tasks = findDownloadTasks(url, false); 274 275 if (tasks.size() > 1) { 276 tasks = askWhichTasksToLoad(tasks); 277 } else if (tasks.isEmpty()) { 278 warnNoSuitableTasks(url); 279 return Collections.emptyList(); 280 } 281 282 PleaseWaitProgressMonitor monitor = new PleaseWaitProgressMonitor(tr("Download data")); 283 284 List<Future<?>> result = new ArrayList<>(); 285 for (final DownloadTask task : tasks) { 286 try { 287 task.setZoomAfterDownload(zoomToData); 288 result.add(MainApplication.worker.submit(new PostDownloadHandler(task, task.loadUrl(settings, url, monitor)))); 289 } catch (IllegalArgumentException e) { 290 Logging.error(e); 291 } 292 } 293 return result; 294 } 295 296 /** 297 * Asks the user which of the possible tasks to perform. 298 * @param tasks a list of possible tasks 299 * @return the selected tasks from the user or an empty list if the dialog has been canceled 300 */ 301 Collection<DownloadTask> askWhichTasksToLoad(final Collection<DownloadTask> tasks) { 302 final JList<DownloadTask> list = new JList<>(tasks.toArray(new DownloadTask[0])); 303 list.addSelectionInterval(0, tasks.size() - 1); 304 final ExtendedDialog dialog = new WhichTasksToPerformDialog(list); 305 dialog.showDialog(); 306 return dialog.getValue() == 1 ? list.getSelectedValuesList() : Collections.<DownloadTask>emptyList(); 307 } 308 309 /** 310 * Displays an error message dialog that no suitable tasks have been found for the given url. 311 * @param url the given url 312 */ 313 protected void warnNoSuitableTasks(final String url) { 314 final String details = findSummaryDocumentation(); // Explain what patterns are supported 315 HelpAwareOptionPane.showMessageDialogInEDT(Main.parent, "<html><p>" + tr( 316 "Cannot open URL ''{0}''<br>The following download tasks accept the URL patterns shown:<br>{1}", 317 url, details) + "</p></html>", tr("Download Location"), JOptionPane.ERROR_MESSAGE, ht("/Action/OpenLocation")); 318 } 319 320 /** 321 * Adds a new download task to the supported ones. 322 * @param taskClass The new download task to add 323 * @return <code>true</code> (as specified by {@link Collection#add}) 324 */ 325 public final boolean addDownloadTaskClass(Class<? extends DownloadTask> taskClass) { 326 return this.downloadTasks.add(taskClass); 327 } 328}