001// License: GPL. For details, see LICENSE file. 002package org.openstreetmap.josm.actions; 003 004import static javax.swing.JFileChooser.FILES_AND_DIRECTORIES; 005import static org.openstreetmap.josm.gui.help.HelpUtil.ht; 006import static org.openstreetmap.josm.tools.I18n.tr; 007import static org.openstreetmap.josm.tools.I18n.trn; 008 009import java.awt.GraphicsEnvironment; 010import java.awt.event.ActionEvent; 011import java.awt.event.KeyEvent; 012import java.io.BufferedReader; 013import java.io.File; 014import java.io.IOException; 015import java.nio.charset.StandardCharsets; 016import java.nio.file.Files; 017import java.util.ArrayList; 018import java.util.Arrays; 019import java.util.Collection; 020import java.util.Collections; 021import java.util.EnumSet; 022import java.util.HashSet; 023import java.util.LinkedHashSet; 024import java.util.LinkedList; 025import java.util.List; 026import java.util.Objects; 027import java.util.Set; 028import java.util.concurrent.Future; 029import java.util.regex.Matcher; 030import java.util.regex.Pattern; 031import java.util.stream.Stream; 032 033import javax.swing.JOptionPane; 034import javax.swing.SwingUtilities; 035import javax.swing.filechooser.FileFilter; 036 037import org.openstreetmap.josm.data.PreferencesUtils; 038import org.openstreetmap.josm.gui.HelpAwareOptionPane; 039import org.openstreetmap.josm.gui.MainApplication; 040import org.openstreetmap.josm.gui.MapFrame; 041import org.openstreetmap.josm.gui.Notification; 042import org.openstreetmap.josm.gui.PleaseWaitRunnable; 043import org.openstreetmap.josm.gui.io.importexport.AllFormatsImporter; 044import org.openstreetmap.josm.gui.io.importexport.FileImporter; 045import org.openstreetmap.josm.gui.io.importexport.Options; 046import org.openstreetmap.josm.gui.layer.Layer; 047import org.openstreetmap.josm.gui.layer.geoimage.GeoImageLayer; 048import org.openstreetmap.josm.gui.util.GuiHelper; 049import org.openstreetmap.josm.gui.widgets.AbstractFileChooser; 050import org.openstreetmap.josm.gui.widgets.FileChooserManager; 051import org.openstreetmap.josm.gui.widgets.NativeFileChooser; 052import org.openstreetmap.josm.io.OsmTransferException; 053import org.openstreetmap.josm.spi.preferences.Config; 054import org.openstreetmap.josm.tools.Logging; 055import org.openstreetmap.josm.tools.MultiMap; 056import org.openstreetmap.josm.tools.PlatformManager; 057import org.openstreetmap.josm.tools.Shortcut; 058import org.openstreetmap.josm.tools.Utils; 059import org.xml.sax.SAXException; 060 061/** 062 * Open a file chooser dialog and select a file to import. 063 * 064 * @author imi 065 * @since 1146 066 */ 067public class OpenFileAction extends DiskAccessAction { 068 069 /** 070 * The {@link ExtensionFileFilter} matching .url files 071 */ 072 public static final ExtensionFileFilter URL_FILE_FILTER = new ExtensionFileFilter("url", "url", tr("URL Files") + " (*.url)"); 073 074 /** 075 * Create an open action. The name is "Open a file". 076 */ 077 public OpenFileAction() { 078 super(tr("Open..."), "open", tr("Open a file."), 079 Shortcut.registerShortcut("system:open", tr("File: {0}", tr("Open...")), KeyEvent.VK_O, Shortcut.CTRL), 080 true, null, false); 081 setHelpId(ht("/Action/Open")); 082 } 083 084 @Override 085 public void actionPerformed(ActionEvent e) { 086 final AbstractFileChooser fc; 087 // If the user explicitly wants native file dialogs, let them use it. 088 // Rather unfortunately, this means that they will not be able to select files and directories. 089 if (Boolean.TRUE.equals(FileChooserManager.PROP_USE_NATIVE_FILE_DIALOG.get()) 090 // This is almost redundant, as the JDK currently doesn't support this with (all?) native file choosers. 091 && !NativeFileChooser.supportsSelectionMode(FILES_AND_DIRECTORIES)) { 092 fc = createAndOpenFileChooser(true, true, null); 093 } else { 094 fc = createAndOpenFileChooser(true, true, null, null, FILES_AND_DIRECTORIES, true, null); 095 } 096 if (fc == null) { 097 return; 098 } 099 final File[] files = fc.getSelectedFiles(); 100 final OpenFileTask task = new OpenFileTask(Arrays.asList(files), fc.getFileFilter()); 101 task.setOptions(Options.RECORD_HISTORY); 102 MainApplication.worker.submit(task); 103 } 104 105 @Override 106 protected void updateEnabledState() { 107 setEnabled(true); 108 } 109 110 /** 111 * Open a list of files. The complete list will be passed to batch importers. 112 * Filenames will not be saved in history. 113 * @param fileList A list of files 114 * @return the future task 115 * @since 11986 (return task) 116 */ 117 public static Future<?> openFiles(List<File> fileList) { 118 return openFiles(fileList, (Options[]) null); 119 } 120 121 /** 122 * Open a list of files. The complete list will be passed to batch importers. 123 * @param fileList A list of files 124 * @param options The options to use 125 * @return the future task 126 * @since 17534 ({@link Options}) 127 */ 128 public static Future<?> openFiles(List<File> fileList, Options... options) { 129 final OpenFileTask task = new OpenFileTask(fileList, null); 130 task.setOptions(options); 131 return MainApplication.worker.submit(task); 132 } 133 134 /** 135 * Task to open files. 136 */ 137 public static class OpenFileTask extends PleaseWaitRunnable { 138 private final List<File> files; 139 private final List<File> successfullyOpenedFiles = new ArrayList<>(); 140 private final Set<String> fileHistory = new LinkedHashSet<>(); 141 private final Set<String> failedAll = new HashSet<>(); 142 private final FileFilter fileFilter; 143 private boolean canceled; 144 private final EnumSet<Options> options = EnumSet.noneOf(Options.class); 145 146 /** 147 * Constructs a new {@code OpenFileTask}. 148 * @param files files to open 149 * @param fileFilter file filter 150 * @param title message for the user 151 */ 152 public OpenFileTask(final List<File> files, final FileFilter fileFilter, final String title) { 153 super(title, false /* don't ignore exception */); 154 this.fileFilter = fileFilter; 155 this.files = new ArrayList<>(files.size()); 156 for (final File file : files) { 157 if (file.exists()) { 158 this.files.add(PlatformManager.getPlatform().resolveFileLink(file)); 159 } else if (file.getParentFile() != null) { 160 // try to guess an extension using the specified fileFilter 161 final File[] matchingFiles = file.getParentFile().listFiles((dir, name) -> 162 name.startsWith(file.getName()) && fileFilter != null && fileFilter.accept(new File(dir, name))); 163 if (matchingFiles != null && matchingFiles.length == 1) { 164 // use the unique match as filename 165 this.files.add(matchingFiles[0]); 166 } else { 167 // add original filename for error reporting later on 168 this.files.add(file); 169 } 170 } else { 171 final String message = tr("Unable to locate file ''{0}''.", file.getPath()); 172 Logging.warn(message); 173 new Notification(message).setIcon(JOptionPane.WARNING_MESSAGE).show(); 174 } 175 } 176 } 177 178 /** 179 * Constructs a new {@code OpenFileTask}. 180 * @param files files to open 181 * @param fileFilter file filter 182 */ 183 public OpenFileTask(List<File> files, FileFilter fileFilter) { 184 this(files, fileFilter, tr("Opening files")); 185 } 186 187 /** 188 * Set the options for the task. 189 * @param options The options to set 190 * @see Options 191 * @since 17556 192 */ 193 public void setOptions(Options... options) { 194 this.options.clear(); 195 if (options != null) { 196 Stream.of(options).filter(Objects::nonNull).forEach(this.options::add); 197 } 198 } 199 200 /** 201 * Determines if filename must be saved in history (for list of recently opened files). 202 * @return {@code true} if filename must be saved in history 203 */ 204 public boolean isRecordHistory() { 205 return this.options.contains(Options.RECORD_HISTORY); 206 } 207 208 /** 209 * Get the options for this task 210 * @return A set of options 211 * @since 17534 212 */ 213 public Set<Options> getOptions() { 214 return Collections.unmodifiableSet(this.options); 215 } 216 217 @Override 218 protected void cancel() { 219 this.canceled = true; 220 } 221 222 @Override 223 protected void finish() { 224 final MapFrame map = MainApplication.getMap(); 225 if (map != null) { 226 map.repaint(); 227 } 228 } 229 230 protected void alertFilesNotMatchingWithImporter(Collection<File> files, FileImporter importer) { 231 final StringBuilder msg = new StringBuilder(128).append("<html>").append( 232 trn("Cannot open {0} file with the file importer ''{1}''.", 233 "Cannot open {0} files with the file importer ''{1}''.", 234 files.size(), 235 files.size(), 236 Utils.escapeReservedCharactersHTML(importer.filter.getDescription()) 237 ) 238 ).append("<br><ul>"); 239 for (File f: files) { 240 msg.append("<li>").append(f.getAbsolutePath()).append("</li>"); 241 } 242 msg.append("</ul></html>"); 243 244 HelpAwareOptionPane.showMessageDialogInEDT( 245 MainApplication.getMainFrame(), 246 msg.toString(), 247 tr("Warning"), 248 JOptionPane.WARNING_MESSAGE, 249 ht("/Action/Open#ImporterCantImportFiles") 250 ); 251 } 252 253 protected void alertFilesWithUnknownImporter(Collection<File> files) { 254 final StringBuilder msg = new StringBuilder(115 + 30 * files.size()).append("<html>").append( 255 trn("Cannot open {0} file because file does not exist or no suitable file importer is available.", 256 "Cannot open {0} files because files do not exist or no suitable file importer is available.", 257 files.size(), 258 files.size() 259 ) 260 ).append("<br><ul>"); 261 for (File f: files) { 262 msg.append("<li>").append(f.getAbsolutePath()).append(" (<i>") 263 .append(f.exists() ? tr("no importer") : tr("does not exist")) 264 .append("</i>)</li>"); 265 } 266 msg.append("</ul></html>"); 267 268 HelpAwareOptionPane.showMessageDialogInEDT( 269 MainApplication.getMainFrame(), 270 msg.toString(), 271 tr("Warning"), 272 JOptionPane.WARNING_MESSAGE, 273 ht("/Action/Open#MissingImporterForFiles") 274 ); 275 } 276 277 @Override 278 protected void realRun() throws SAXException, IOException, OsmTransferException { 279 if (Utils.isEmpty(files)) { 280 return; 281 } 282 final List<Layer> oldLayers = MainApplication.getLayerManager().getLayers(); 283 284 /* 285 * Find the importer with the chosen file filter 286 */ 287 FileImporter chosenImporter = null; 288 if (fileFilter != null) { 289 for (FileImporter importer : ExtensionFileFilter.getImporters()) { 290 if (fileFilter.equals(importer.filter)) { 291 chosenImporter = importer; 292 } 293 } 294 } 295 /* 296 * If the filter hasn't been changed in the dialog, chosenImporter is null now. 297 * When the filter has been set explicitly to AllFormatsImporter, treat this the same. 298 */ 299 if (chosenImporter instanceof AllFormatsImporter) { 300 chosenImporter = null; 301 } 302 getProgressMonitor().setTicksCount(files.size()); 303 304 if (chosenImporter != null) { 305 // The importer was explicitly chosen, so use it. 306 final List<File> filesNotMatchingWithImporter = new LinkedList<>(); 307 final List<File> filesMatchingWithImporter = new LinkedList<>(); 308 for (final File f : files) { 309 if (!chosenImporter.acceptFile(f)) { 310 if (f.isDirectory()) { 311 SwingUtilities.invokeLater(() -> JOptionPane.showMessageDialog(MainApplication.getMainFrame(), tr( 312 "<html>Cannot open directory ''{0}''.<br>Please select a file.</html>", 313 f.getAbsolutePath()), tr("Open file"), JOptionPane.ERROR_MESSAGE)); 314 // TODO when changing to Java 6: Don't cancel the task here but use different modality. (Currently 2 dialogs 315 // would block each other.) 316 return; 317 } else { 318 filesNotMatchingWithImporter.add(f); 319 } 320 } else { 321 filesMatchingWithImporter.add(f); 322 } 323 } 324 325 if (!filesNotMatchingWithImporter.isEmpty()) { 326 alertFilesNotMatchingWithImporter(filesNotMatchingWithImporter, chosenImporter); 327 } 328 if (!filesMatchingWithImporter.isEmpty()) { 329 importData(chosenImporter, filesMatchingWithImporter); 330 } 331 } else { 332 // find appropriate importer 333 final MultiMap<FileImporter, File> importerMap = new MultiMap<>(); 334 final List<File> filesWithUnknownImporter = new LinkedList<>(); 335 final List<File> urlFiles = new LinkedList<>(); 336 for (File f : files) { 337 boolean imported = false; 338 for (FileImporter importer : ExtensionFileFilter.getImporters()) { 339 if (importer.acceptFile(f)) { 340 importerMap.put(importer, f); 341 imported = true; 342 break; 343 } 344 } 345 if (!imported) { 346 if (URL_FILE_FILTER.accept(f)) { 347 urlFiles.add(f); 348 } else { 349 filesWithUnknownImporter.add(f); 350 } 351 } 352 } 353 354 if (!filesWithUnknownImporter.isEmpty()) { 355 alertFilesWithUnknownImporter(filesWithUnknownImporter); 356 } 357 final List<FileImporter> importers = new ArrayList<>(importerMap.keySet()); 358 importers.sort(Collections.reverseOrder()); 359 360 for (FileImporter importer : importers) { 361 importData(importer, new ArrayList<>(importerMap.get(importer))); 362 } 363 364 final Pattern urlPattern = Pattern.compile(".*(https?://.*)"); 365 for (File urlFile: urlFiles) { 366 try (BufferedReader reader = Files.newBufferedReader(urlFile.toPath(), StandardCharsets.UTF_8)) { 367 String line; 368 while ((line = reader.readLine()) != null) { 369 final Matcher m = urlPattern.matcher(line); 370 if (m.matches()) { 371 final String url = m.group(1); 372 MainApplication.getMenu().openLocation.openUrl(false, url); 373 } 374 } 375 } catch (IOException | RuntimeException | LinkageError e) { 376 Logging.error(e); 377 GuiHelper.runInEDT( 378 () -> new Notification(Utils.getRootCause(e).getMessage()).setIcon(JOptionPane.ERROR_MESSAGE).show()); 379 } 380 } 381 } 382 383 if (this.options.contains(Options.RECORD_HISTORY)) { 384 final Collection<String> oldFileHistory = Config.getPref().getList("file-open.history"); 385 fileHistory.addAll(oldFileHistory); 386 // remove the files which failed to load from the list 387 fileHistory.removeAll(failedAll); 388 final int maxsize = Math.max(0, Config.getPref().getInt("file-open.history.max-size", 15)); 389 PreferencesUtils.putListBounded(Config.getPref(), "file-open.history", maxsize, new ArrayList<>(fileHistory)); 390 } 391 if (!canceled && !GraphicsEnvironment.isHeadless()) { 392 checkNewLayers(oldLayers); 393 } 394 } 395 396 private static void checkNewLayers(List<Layer> oldLayers) { 397 // We do have to wrap the EDT call in a worker call, since layers may be created in the EDT. 398 // And the layer(s) must be added to the layer list in order for the dialog to work properly. 399 MainApplication.worker.execute(() -> GuiHelper.runInEDT(() -> { 400 final List<Layer> newLayers = MainApplication.getLayerManager().getLayers(); 401 // see #23728: open first image of topmost new image layer 402 for (Layer l : newLayers) { 403 if (oldLayers.contains(l)) { 404 return; 405 } 406 if (l instanceof GeoImageLayer) { 407 final GeoImageLayer imageLayer = (GeoImageLayer) l; 408 imageLayer.jumpToNextMarker(); 409 return; 410 } 411 } 412 })); 413 } 414 415 /** 416 * Import data files with the given importer. 417 * @param importer file importer 418 * @param files data files to import 419 */ 420 public void importData(FileImporter importer, List<File> files) { 421 importer.setOptions(this.options.toArray(new Options[0])); 422 if (importer.isBatchImporter()) { 423 if (canceled) { 424 return; 425 } 426 final String msg = trn("Opening {0} file...", "Opening {0} files...", files.size(), files.size()); 427 getProgressMonitor().setCustomText(msg); 428 getProgressMonitor().indeterminateSubTask(msg); 429 if (importer.importDataHandleExceptions(files, getProgressMonitor().createSubTaskMonitor(files.size(), false))) { 430 successfullyOpenedFiles.addAll(files); 431 } 432 } else { 433 for (File f : files) { 434 if (canceled) { 435 return; 436 } 437 getProgressMonitor().indeterminateSubTask(tr("Opening file ''{0}'' ...", f.getAbsolutePath())); 438 if (importer.importDataHandleExceptions(f, getProgressMonitor().createSubTaskMonitor(1, false))) { 439 successfullyOpenedFiles.add(f); 440 } 441 } 442 } 443 if (this.options.contains(Options.RECORD_HISTORY) && !importer.isBatchImporter()) { 444 for (File f : files) { 445 try { 446 if (successfullyOpenedFiles.contains(f)) { 447 fileHistory.add(f.getCanonicalPath()); 448 } else { 449 failedAll.add(f.getCanonicalPath()); 450 } 451 } catch (IOException e) { 452 Logging.warn(e); 453 } 454 } 455 } 456 } 457 458 /** 459 * Replies the list of files that have been successfully opened. 460 * @return The list of files that have been successfully opened. 461 */ 462 public List<File> getSuccessfullyOpenedFiles() { 463 return successfullyOpenedFiles; 464 } 465 } 466}