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