Search in sources :

Example 1 with MnemonicAwareAction

use of org.jabref.gui.actions.MnemonicAwareAction in project jabref by JabRef.

the class ImportFormats method getImportAction.

/**
     * Create an AbstractAction for performing an Import operation.
     * @param frame The JabRefFrame of this JabRef instance.
     * @param openInNew Indicate whether the action should open into a new database or
     *  into the currently open one.
     * @return The action.
     */
public static AbstractAction getImportAction(JabRefFrame frame, boolean openInNew) {
    class ImportAction extends MnemonicAwareAction {

        private final boolean newDatabase;

        public ImportAction(boolean newDatabase) {
            this.newDatabase = newDatabase;
            if (newDatabase) {
                putValue(Action.NAME, Localization.menuTitle("Import into new library"));
                putValue(Action.ACCELERATOR_KEY, Globals.getKeyPrefs().getKey(KeyBinding.IMPORT_INTO_NEW_DATABASE));
            } else {
                putValue(Action.NAME, Localization.menuTitle("Import into current library"));
                putValue(Action.ACCELERATOR_KEY, Globals.getKeyPrefs().getKey(KeyBinding.IMPORT_INTO_CURRENT_DATABASE));
            }
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            SortedSet<Importer> importers = Globals.IMPORT_FORMAT_READER.getImportFormats();
            List<FileExtensions> extensions = importers.stream().map(Importer::getExtensions).collect(Collectors.toList());
            FileChooser.ExtensionFilter allImports = ImportFileFilter.convert(Localization.lang("Available import formats"), importers);
            FileDialogConfiguration fileDialogConfiguration = new FileDialogConfiguration.Builder().addExtensionFilters(extensions).withInitialDirectory(Globals.prefs.get(JabRefPreferences.IMPORT_WORKING_DIRECTORY)).build();
            DialogService ds = new FXDialogService();
            FileChooser fs = ds.getConfiguredFileChooser(fileDialogConfiguration);
            fs.setSelectedExtensionFilter(allImports);
            File f = DefaultTaskExecutor.runInJavaFXThread(() -> fs.showOpenDialog(null));
            Optional<Path> selectedFile = Optional.ofNullable(f).map(File::toPath);
            FileChooser.ExtensionFilter selectedExtension = fs.getSelectedExtensionFilter();
            // Add file filter for all supported types
            selectedFile.ifPresent(file -> {
                try {
                    if (!Files.exists(file)) {
                        JOptionPane.showMessageDialog(frame, Localization.lang("File not found") + ": '" + file.getFileName() + "'.", Localization.lang("Import"), JOptionPane.ERROR_MESSAGE);
                        return;
                    }
                    Optional<Importer> format = ImportFileFilter.convert(selectedExtension, importers);
                    ImportMenuItem importMenu = new ImportMenuItem(frame, newDatabase, format.orElse(null));
                    importMenu.automatedImport(Collections.singletonList(file.toString()));
                    Globals.prefs.put(JabRefPreferences.IMPORT_WORKING_DIRECTORY, file.getParent().toString());
                } catch (Exception ex) {
                    LOGGER.warn("Cannot import file", ex);
                }
            });
        }
    }
    return new ImportAction(openInNew);
}
Also used : Path(java.nio.file.Path) DialogService(org.jabref.gui.DialogService) FXDialogService(org.jabref.gui.FXDialogService) ActionEvent(java.awt.event.ActionEvent) FileDialogConfiguration(org.jabref.gui.util.FileDialogConfiguration) FXDialogService(org.jabref.gui.FXDialogService) MnemonicAwareAction(org.jabref.gui.actions.MnemonicAwareAction) FileExtensions(org.jabref.logic.util.FileExtensions) FileChooser(javafx.stage.FileChooser) File(java.io.File) Importer(org.jabref.logic.importer.Importer)

Example 2 with MnemonicAwareAction

use of org.jabref.gui.actions.MnemonicAwareAction in project jabref by JabRef.

the class ExportAction method getExportAction.

/**
     * Create an AbstractAction for performing an export operation.
     *
     * @param frame
     *            The JabRefFrame of this JabRef instance.
     * @param selectedOnly
     *            true indicates that only selected entries should be exported,
     *            false indicates that all entries should be exported.
     * @return The action.
     */
public static AbstractAction getExportAction(JabRefFrame frame, boolean selectedOnly) {
    class InternalExportAction extends MnemonicAwareAction {

        private final JabRefFrame frame;

        private final boolean selectedOnly;

        public InternalExportAction(JabRefFrame frame, boolean selectedOnly) {
            this.frame = frame;
            this.selectedOnly = selectedOnly;
            putValue(Action.NAME, selectedOnly ? Localization.menuTitle("Export selected entries") : Localization.menuTitle("Export"));
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            Map<String, ExportFormat> customFormats = Globals.prefs.customExports.getCustomExportFormats(Globals.prefs, Globals.journalAbbreviationLoader);
            LayoutFormatterPreferences layoutPreferences = Globals.prefs.getLayoutFormatterPreferences(Globals.journalAbbreviationLoader);
            SavePreferences savePreferences = SavePreferences.loadForExportFromPreferences(Globals.prefs);
            ExportFormats.initAllExports(customFormats, layoutPreferences, savePreferences);
            JFileChooser fc = ExportAction.createExportFileChooser(Globals.prefs.get(JabRefPreferences.EXPORT_WORKING_DIRECTORY));
            fc.showSaveDialog(frame);
            File file = fc.getSelectedFile();
            if (file == null) {
                return;
            }
            FileFilter ff = fc.getFileFilter();
            if (ff instanceof ExportFileFilter) {
                ExportFileFilter eff = (ExportFileFilter) ff;
                String path = file.getPath();
                if (!path.endsWith(eff.getExtension())) {
                    path = path + eff.getExtension();
                }
                file = new File(path);
                if (file.exists()) {
                    // Warn that the file exists:
                    if (JOptionPane.showConfirmDialog(frame, Localization.lang("'%0' exists. Overwrite file?", file.getName()), Localization.lang("Export"), JOptionPane.OK_CANCEL_OPTION) != JOptionPane.OK_OPTION) {
                        return;
                    }
                }
                final IExportFormat format = eff.getExportFormat();
                List<BibEntry> entries;
                if (selectedOnly) {
                    // Selected entries
                    entries = frame.getCurrentBasePanel().getSelectedEntries();
                } else {
                    // All entries
                    entries = frame.getCurrentBasePanel().getDatabase().getEntries();
                }
                // Set the global variable for this database's file directory before exporting,
                // so formatters can resolve linked files correctly.
                // (This is an ugly hack!)
                Globals.prefs.fileDirForDatabase = frame.getCurrentBasePanel().getBibDatabaseContext().getFileDirectories(Globals.prefs.getFileDirectoryPreferences());
                // Make sure we remember which filter was used, to set
                // the default for next time:
                Globals.prefs.put(JabRefPreferences.LAST_USED_EXPORT, format.getConsoleName());
                Globals.prefs.put(JabRefPreferences.EXPORT_WORKING_DIRECTORY, file.getParent());
                final File finFile = file;
                final List<BibEntry> finEntries = entries;
                AbstractWorker exportWorker = new AbstractWorker() {

                    String errorMessage;

                    @Override
                    public void run() {
                        try {
                            format.performExport(frame.getCurrentBasePanel().getBibDatabaseContext(), finFile.getPath(), frame.getCurrentBasePanel().getBibDatabaseContext().getMetaData().getEncoding().orElse(Globals.prefs.getDefaultEncoding()), finEntries);
                        } catch (Exception ex) {
                            LOGGER.warn("Problem exporting", ex);
                            if (ex.getMessage() == null) {
                                errorMessage = ex.toString();
                            } else {
                                errorMessage = ex.getMessage();
                            }
                        }
                    }

                    @Override
                    public void update() {
                        // No error message. Report success:
                        if (errorMessage == null) {
                            frame.output(Localization.lang("%0 export successful", format.getDisplayName()));
                        } else // ... or show an error dialog:
                        {
                            frame.output(Localization.lang("Could not save file.") + " - " + errorMessage);
                            // Need to warn the user that saving failed!
                            JOptionPane.showMessageDialog(frame, Localization.lang("Could not save file.") + "\n" + errorMessage, Localization.lang("Save library"), JOptionPane.ERROR_MESSAGE);
                        }
                    }
                };
                // Run the export action in a background thread:
                exportWorker.getWorker().run();
                // Run the update method:
                exportWorker.update();
            }
        }
    }
    return new InternalExportAction(frame, selectedOnly);
}
Also used : BibEntry(org.jabref.model.entry.BibEntry) ActionEvent(java.awt.event.ActionEvent) IExportFormat(org.jabref.logic.exporter.IExportFormat) ExportFormat(org.jabref.logic.exporter.ExportFormat) IExportFormat(org.jabref.logic.exporter.IExportFormat) JabRefFrame(org.jabref.gui.JabRefFrame) LayoutFormatterPreferences(org.jabref.logic.layout.LayoutFormatterPreferences) MnemonicAwareAction(org.jabref.gui.actions.MnemonicAwareAction) JFileChooser(javax.swing.JFileChooser) SavePreferences(org.jabref.logic.exporter.SavePreferences) AbstractWorker(org.jabref.gui.worker.AbstractWorker) FileFilter(javax.swing.filechooser.FileFilter) File(java.io.File)

Aggregations

ActionEvent (java.awt.event.ActionEvent)2 File (java.io.File)2 MnemonicAwareAction (org.jabref.gui.actions.MnemonicAwareAction)2 Path (java.nio.file.Path)1 FileChooser (javafx.stage.FileChooser)1 JFileChooser (javax.swing.JFileChooser)1 FileFilter (javax.swing.filechooser.FileFilter)1 DialogService (org.jabref.gui.DialogService)1 FXDialogService (org.jabref.gui.FXDialogService)1 JabRefFrame (org.jabref.gui.JabRefFrame)1 FileDialogConfiguration (org.jabref.gui.util.FileDialogConfiguration)1 AbstractWorker (org.jabref.gui.worker.AbstractWorker)1 ExportFormat (org.jabref.logic.exporter.ExportFormat)1 IExportFormat (org.jabref.logic.exporter.IExportFormat)1 SavePreferences (org.jabref.logic.exporter.SavePreferences)1 Importer (org.jabref.logic.importer.Importer)1 LayoutFormatterPreferences (org.jabref.logic.layout.LayoutFormatterPreferences)1 FileExtensions (org.jabref.logic.util.FileExtensions)1 BibEntry (org.jabref.model.entry.BibEntry)1