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