Search in sources :

Example 1 with ExternalFileType

use of org.jabref.gui.externalfiletype.ExternalFileType in project jabref by JabRef.

the class JabRefDesktop method openExternalFileUnknown.

public static boolean openExternalFileUnknown(JabRefFrame frame, BibEntry entry, BibDatabaseContext databaseContext, String link, UnknownExternalFileType fileType) throws IOException {
    String cancelMessage = Localization.lang("Unable to open file.");
    String[] options = new String[] { Localization.lang("Define '%0'", fileType.getName()), Localization.lang("Change file type"), Localization.lang("Cancel") };
    String defOption = options[0];
    int answer = JOptionPane.showOptionDialog(frame, Localization.lang("This external link is of the type '%0', which is undefined. What do you want to do?", fileType.getName()), Localization.lang("Undefined file type"), JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, defOption);
    if (answer == JOptionPane.CANCEL_OPTION) {
        frame.output(cancelMessage);
        return false;
    } else if (answer == JOptionPane.YES_OPTION) {
        // User wants to define the new file type. Show the dialog:
        ExternalFileType newType = new ExternalFileType(fileType.getName(), "", "", "", "new", IconTheme.JabRefIcon.FILE.getSmallIcon());
        ExternalFileTypeEntryEditor editor = new ExternalFileTypeEntryEditor(frame, newType);
        editor.setVisible(true);
        if (editor.okPressed()) {
            // Get the old list of types, add this one, and update the list in prefs:
            List<ExternalFileType> fileTypes = new ArrayList<>(ExternalFileTypes.getInstance().getExternalFileTypeSelection());
            fileTypes.add(newType);
            Collections.sort(fileTypes);
            ExternalFileTypes.getInstance().setExternalFileTypes(fileTypes);
            // Finally, open the file:
            return openExternalFileAnyFormat(databaseContext, link, Optional.of(newType));
        } else {
            // Canceled:
            frame.output(cancelMessage);
            return false;
        }
    } else {
        // User wants to change the type of this link.
        // First get a model of all file links for this entry:
        FileListTableModel tModel = new FileListTableModel();
        Optional<String> oldValue = entry.getField(FieldName.FILE);
        oldValue.ifPresent(tModel::setContent);
        FileListEntry flEntry = null;
        // Then find which one we are looking at:
        for (int i = 0; i < tModel.getRowCount(); i++) {
            FileListEntry iEntry = tModel.getEntry(i);
            if (iEntry.getLink().equals(link)) {
                flEntry = iEntry;
                break;
            }
        }
        if (flEntry == null) {
            // This shouldn't happen, so I'm not sure what to put in here:
            throw new RuntimeException("Could not find the file list entry " + link + " in " + entry);
        }
        FileListEntryEditor editor = new FileListEntryEditor(frame, flEntry, false, true, databaseContext);
        editor.setVisible(true, false);
        if (editor.okPressed()) {
            // Store the changes and add an undo edit:
            String newValue = tModel.getStringRepresentation();
            UndoableFieldChange ce = new UndoableFieldChange(entry, FieldName.FILE, oldValue.orElse(null), newValue);
            entry.setField(FieldName.FILE, newValue);
            frame.getCurrentBasePanel().getUndoManager().addEdit(ce);
            frame.getCurrentBasePanel().markBaseChanged();
            // Finally, open the link:
            return openExternalFileAnyFormat(databaseContext, flEntry.getLink(), flEntry.getType());
        } else {
            // Canceled:
            frame.output(cancelMessage);
            return false;
        }
    }
}
Also used : FileListTableModel(org.jabref.gui.filelist.FileListTableModel) ExternalFileTypeEntryEditor(org.jabref.gui.externalfiletype.ExternalFileTypeEntryEditor) Optional(java.util.Optional) FileListEntry(org.jabref.gui.filelist.FileListEntry) Eprint(org.jabref.model.entry.identifier.Eprint) UnknownExternalFileType(org.jabref.gui.externalfiletype.UnknownExternalFileType) ExternalFileType(org.jabref.gui.externalfiletype.ExternalFileType) FileListEntryEditor(org.jabref.gui.filelist.FileListEntryEditor) UndoableFieldChange(org.jabref.gui.undo.UndoableFieldChange) ArrayList(java.util.ArrayList) List(java.util.List)

Example 2 with ExternalFileType

use of org.jabref.gui.externalfiletype.ExternalFileType in project jabref by JabRef.

the class LinkedFilesEditorViewModel method fromFile.

/**
     * Creates an instance of {@link LinkedFile} based on the given file.
     * We try to guess the file type and relativize the path against the given file directories.
     *
     * TODO: Move this method to {@link LinkedFile} as soon as {@link ExternalFileType} lives in model.
     */
private static LinkedFile fromFile(Path file, List<Path> fileDirectories) {
    String fileExtension = FileHelper.getFileExtension(file).orElse("");
    ExternalFileType suggestedFileType = ExternalFileTypes.getInstance().getExternalFileTypeByExt(fileExtension).orElse(new UnknownExternalFileType(fileExtension));
    Path relativePath = FileUtil.shortenFileName(file, fileDirectories);
    return new LinkedFile("", relativePath.toString(), suggestedFileType.getName());
}
Also used : UnknownExternalFileType(org.jabref.gui.externalfiletype.UnknownExternalFileType) ExternalFileType(org.jabref.gui.externalfiletype.ExternalFileType) Path(java.nio.file.Path) LinkedFile(org.jabref.model.entry.LinkedFile) UnknownExternalFileType(org.jabref.gui.externalfiletype.UnknownExternalFileType)

Example 3 with ExternalFileType

use of org.jabref.gui.externalfiletype.ExternalFileType in project jabref by JabRef.

the class LinkedFilesEditorViewModel method findAssociatedNotLinkedFiles.

/**
     * Find files that are probably associated  to the given entry but not yet linked.
     */
private List<LinkedFileViewModel> findAssociatedNotLinkedFiles(BibEntry entry) {
    final List<Path> dirs = databaseContext.getFileDirectoriesAsPaths(Globals.prefs.getFileDirectoryPreferences());
    final List<String> extensions = ExternalFileTypes.getInstance().getExternalFileTypeSelection().stream().map(ExternalFileType::getExtension).collect(Collectors.toList());
    // Run the search operation:
    FileFinder fileFinder = FileFinders.constructFromConfiguration(Globals.prefs.getAutoLinkPreferences());
    List<Path> newFiles = fileFinder.findAssociatedFiles(entry, dirs, extensions);
    List<LinkedFileViewModel> result = new ArrayList<>();
    for (Path newFile : newFiles) {
        boolean alreadyLinked = files.get().stream().map(file -> file.findIn(dirs)).anyMatch(file -> file.isPresent() && file.get().equals(newFile));
        if (!alreadyLinked) {
            LinkedFileViewModel newLinkedFile = new LinkedFileViewModel(fromFile(newFile, dirs));
            newLinkedFile.markAsAutomaticallyFound();
            result.add(newLinkedFile);
        }
    }
    return result;
}
Also used : Path(java.nio.file.Path) URL(java.net.URL) BindingsHelper(org.jabref.gui.util.BindingsHelper) FXCollections(javafx.collections.FXCollections) DialogService(org.jabref.gui.DialogService) SimpleListProperty(javafx.beans.property.SimpleListProperty) JabRefPreferences(org.jabref.preferences.JabRefPreferences) FileDownloadTask(org.jabref.gui.externalfiles.FileDownloadTask) LinkedFile(org.jabref.model.entry.LinkedFile) ArrayList(java.util.ArrayList) URLDownload(org.jabref.logic.net.URLDownload) FulltextFetchers(org.jabref.logic.importer.FulltextFetchers) UnknownExternalFileType(org.jabref.gui.externalfiletype.UnknownExternalFileType) Localization(org.jabref.logic.l10n.Localization) FileFieldWriter(org.jabref.model.entry.FileFieldWriter) ListProperty(javafx.beans.property.ListProperty) BibDatabaseContext(org.jabref.model.database.BibDatabaseContext) Path(java.nio.file.Path) ExternalFileType(org.jabref.gui.externalfiletype.ExternalFileType) FileFinders(org.jabref.logic.util.io.FileFinders) FileUtil(org.jabref.logic.util.io.FileUtil) FileDialogConfiguration(org.jabref.gui.util.FileDialogConfiguration) MalformedURLException(java.net.MalformedURLException) BibEntry(org.jabref.model.entry.BibEntry) DownloadExternalFile(org.jabref.gui.externalfiles.DownloadExternalFile) BackgroundTask(org.jabref.gui.util.BackgroundTask) IOException(java.io.IOException) Collectors(java.util.stream.Collectors) Globals(org.jabref.Globals) FileFinder(org.jabref.logic.util.io.FileFinder) FileHelper(org.jabref.model.util.FileHelper) TaskExecutor(org.jabref.gui.util.TaskExecutor) FileFieldParser(org.jabref.model.entry.FileFieldParser) List(java.util.List) BooleanProperty(javafx.beans.property.BooleanProperty) SimpleBooleanProperty(javafx.beans.property.SimpleBooleanProperty) Paths(java.nio.file.Paths) OS(org.jabref.logic.util.OS) Optional(java.util.Optional) Log(org.apache.commons.logging.Log) ObservableList(javafx.collections.ObservableList) ExternalFileTypes(org.jabref.gui.externalfiletype.ExternalFileTypes) LogFactory(org.apache.commons.logging.LogFactory) ArrayList(java.util.ArrayList) FileFinder(org.jabref.logic.util.io.FileFinder)

Example 4 with ExternalFileType

use of org.jabref.gui.externalfiletype.ExternalFileType in project jabref by JabRef.

the class EntryTableTransferHandler method loadOrImportFiles.

/**
     * Take a set of filenames. Those with names indicating BIB files are opened as such if possible. All other files we
     * will attempt to import into the current library.
     *
     * @param fileNames The names of the files to open.
     * @param dropRow success status for the operation
     */
private void loadOrImportFiles(List<String> fileNames, int dropRow) {
    OpenDatabaseAction openAction = new OpenDatabaseAction(frame, false);
    List<String> notBibFiles = new ArrayList<>();
    List<String> bibFiles = new ArrayList<>();
    for (String fileName : fileNames) {
        // Find the file's extension, if any:
        Optional<String> extension = FileHelper.getFileExtension(fileName);
        Optional<ExternalFileType> fileType;
        if (extension.isPresent() && "bib".equals(extension.get())) {
            // we assume that it is a BibTeX file.
            // When a user wants to import something with file extension "bib", but which is not a BibTeX file, he should use "file -> import"
            bibFiles.add(fileName);
            continue;
        }
        fileType = ExternalFileTypes.getInstance().getExternalFileTypeByExt(extension.orElse(""));
        /*
             * This is a linkable file. If the user dropped it on an entry, we
             * should offer options for autolinking to this files:
             *
             * TODO we should offer an option to highlight the row the user is on too.
             */
        if ((fileType.isPresent()) && (dropRow >= 0)) {
            /*
                 * TODO: make this an instance variable?
                 */
            DroppedFileHandler dfh = new DroppedFileHandler(frame, panel);
            dfh.handleDroppedfile(fileName, fileType.get(), entryTable, dropRow);
            continue;
        }
        notBibFiles.add(fileName);
    }
    openAction.openFilesAsStringList(bibFiles, true);
    if (!notBibFiles.isEmpty()) {
        // Import into new if entryTable==null, otherwise into current
        // database:
        ImportMenuItem importer = new ImportMenuItem(frame, entryTable == null);
        importer.automatedImport(notBibFiles);
    }
}
Also used : ExternalFileType(org.jabref.gui.externalfiletype.ExternalFileType) OpenDatabaseAction(org.jabref.gui.importer.actions.OpenDatabaseAction) ArrayList(java.util.ArrayList) DroppedFileHandler(org.jabref.gui.externalfiles.DroppedFileHandler) ImportMenuItem(org.jabref.gui.importer.ImportMenuItem)

Example 5 with ExternalFileType

use of org.jabref.gui.externalfiletype.ExternalFileType in project jabref by JabRef.

the class FileListEntryEditor method storeSettings.

private void storeSettings(FileListEntry listEntry) {
    String descriptionText = this.description.getText().trim();
    String fileLink = "";
    // See if we should trim the file link to be relative to the file directory:
    try {
        List<String> dirs = databaseContext.getFileDirectories(Globals.prefs.getFileDirectoryPreferences());
        if (dirs.isEmpty()) {
            fileLink = this.link.getText().trim();
        } else {
            boolean found = false;
            for (String dir : dirs) {
                String canPath = (new File(dir)).getCanonicalPath();
                File fl = new File(this.link.getText().trim());
                if (fl.isAbsolute()) {
                    String flPath = fl.getCanonicalPath();
                    if ((flPath.length() > canPath.length()) && (flPath.startsWith(canPath))) {
                        fileLink = fl.getCanonicalPath().substring(canPath.length() + 1);
                        found = true;
                        break;
                    }
                }
            }
            if (!found) {
                fileLink = this.link.getText().trim();
            }
        }
    } catch (IOException ex) {
        // Don't think this should happen, but set the file link directly as a fallback:
        fileLink = this.link.getText().trim();
    }
    ExternalFileType type = (ExternalFileType) types.getSelectedItem();
    listEntry.setDescription(descriptionText);
    listEntry.setType(Optional.ofNullable(type));
    listEntry.setLink(fileLink);
}
Also used : UnknownExternalFileType(org.jabref.gui.externalfiletype.UnknownExternalFileType) ExternalFileType(org.jabref.gui.externalfiletype.ExternalFileType) IOException(java.io.IOException) File(java.io.File)

Aggregations

ExternalFileType (org.jabref.gui.externalfiletype.ExternalFileType)15 FileListEntry (org.jabref.gui.filelist.FileListEntry)8 IOException (java.io.IOException)6 Path (java.nio.file.Path)6 UnknownExternalFileType (org.jabref.gui.externalfiletype.UnknownExternalFileType)6 List (java.util.List)5 Optional (java.util.Optional)5 FileListTableModel (org.jabref.gui.filelist.FileListTableModel)5 File (java.io.File)4 ArrayList (java.util.ArrayList)4 JLabel (javax.swing.JLabel)4 UndoableFieldChange (org.jabref.gui.undo.UndoableFieldChange)4 BibEntry (org.jabref.model.entry.BibEntry)4 Log (org.apache.commons.logging.Log)3 LogFactory (org.apache.commons.logging.LogFactory)3 Globals (org.jabref.Globals)3 NamedCompound (org.jabref.gui.undo.NamedCompound)3 LinkedFile (org.jabref.model.entry.LinkedFile)3 URL (java.net.URL)2 Paths (java.nio.file.Paths)2