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