Search in sources :

Example 6 with FileListEntry

use of org.jabref.gui.filelist.FileListEntry in project jabref by JabRef.

the class SynchronizeFileField method run.

@Override
public void run() {
    if (!goOn) {
        panel.output(Localization.lang("This operation requires one or more entries to be selected."));
        return;
    }
    entriesChangedCount = 0;
    panel.frame().setProgressBarValue(0);
    panel.frame().setProgressBarVisible(true);
    // autoSet takes 10 (?) times longer than checkExisting
    int weightAutoSet = 10;
    int progressBarMax = (autoSet ? weightAutoSet * sel.size() : 0) + (checkExisting ? sel.size() : 0);
    panel.frame().setProgressBarMaximum(progressBarMax);
    int progress = 0;
    final NamedCompound ce = new NamedCompound(Localization.lang("Automatically set file links"));
    Set<BibEntry> changedEntries = new HashSet<>();
    // First we try to autoset fields
    if (autoSet) {
        List<BibEntry> entries = new ArrayList<>(sel);
        // Start the automatically setting process:
        Runnable r = AutoSetLinks.autoSetLinks(entries, ce, changedEntries, null, panel.getBibDatabaseContext(), null, null);
        JabRefExecutorService.INSTANCE.executeAndWait(r);
    }
    progress += sel.size() * weightAutoSet;
    panel.frame().setProgressBarValue(progress);
    // The following loop checks all external links that are already set.
    if (checkExisting) {
        boolean removeAllBroken = false;
        mainLoop: for (BibEntry aSel : sel) {
            panel.frame().setProgressBarValue(progress++);
            final Optional<String> old = aSel.getField(FieldName.FILE);
            // Check if a extension is set:
            if (old.isPresent() && !(old.get().isEmpty())) {
                FileListTableModel tableModel = new FileListTableModel();
                tableModel.setContentDontGuessTypes(old.get());
                for (int j = 0; j < tableModel.getRowCount(); j++) {
                    FileListEntry flEntry = tableModel.getEntry(j);
                    LinkedFile field = flEntry.toParsedFileField();
                    // See if the link looks like an URL:
                    if (field.isOnlineLink()) {
                        // Don't check the remote file.
                        continue;
                    // TODO: should there be an option to check remote links?
                    }
                    // A variable to keep track of whether this link gets deleted:
                    boolean deleted = false;
                    // Get an absolute path representation:
                    Optional<Path> file = field.findIn(panel.getBibDatabaseContext(), Globals.prefs.getFileDirectoryPreferences());
                    if ((!file.isPresent()) || !Files.exists(file.get())) {
                        int answer;
                        if (removeAllBroken) {
                            // We should delete this link.
                            answer = 2;
                        } else {
                            answer = JOptionPane.showOptionDialog(panel.frame(), Localization.lang("<HTML>Could not find file '%0'<BR>linked from entry '%1'</HTML>", flEntry.getLink(), aSel.getCiteKeyOptional().orElse(Localization.lang("undefined"))), Localization.lang("Broken link"), JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, brokenLinkOptions, brokenLinkOptions[0]);
                        }
                        switch(answer) {
                            case 1:
                                // Assign new file.
                                FileListEntryEditor flEditor = new FileListEntryEditor(panel.frame(), flEntry, false, true, panel.getBibDatabaseContext());
                                flEditor.setVisible(true, true);
                                break;
                            case 2:
                                // Clear field:
                                tableModel.removeEntry(j);
                                // Make sure we don't investigate this link further.
                                deleted = true;
                                // Step back in the iteration, because we removed an entry.
                                j--;
                                break;
                            case 3:
                                // Clear field:
                                tableModel.removeEntry(j);
                                // Make sure we don't investigate this link further.
                                deleted = true;
                                // Step back in the iteration, because we removed an entry.
                                j--;
                                // Notify for further cases.
                                removeAllBroken = true;
                                break;
                            default:
                                // Cancel
                                break mainLoop;
                        }
                    }
                    // Unless we deleted this link, see if its file type is recognized:
                    if (!deleted && flEntry.getType().isPresent() && (flEntry.getType().get() instanceof UnknownExternalFileType)) {
                        String[] options = new String[] { Localization.lang("Define '%0'", flEntry.getType().get().getName()), Localization.lang("Change file type"), Localization.lang("Cancel") };
                        String defOption = options[0];
                        int answer = JOptionPane.showOptionDialog(panel.frame(), Localization.lang("One or more file links are of the type '%0', which is undefined. What do you want to do?", flEntry.getType().get().getName()), Localization.lang("Undefined file type"), JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, defOption);
                        if (answer == JOptionPane.CANCEL_OPTION) {
                        // User doesn't want to handle this unknown link type.
                        } else if (answer == JOptionPane.YES_OPTION) {
                            // User wants to define the new file type. Show the dialog:
                            ExternalFileType newType = new ExternalFileType(flEntry.getType().get().getName(), "", "", "", "new", IconTheme.JabRefIcon.FILE.getSmallIcon());
                            ExternalFileTypeEntryEditor editor = new ExternalFileTypeEntryEditor(panel.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);
                                panel.getMainTable().repaint();
                            }
                        } else {
                            // User wants to change the type of this link.
                            // First get a model of all file links for this entry:
                            FileListEntryEditor editor = new FileListEntryEditor(panel.frame(), flEntry, false, true, panel.getBibDatabaseContext());
                            editor.setVisible(true, false);
                        }
                    }
                }
                if (!tableModel.getStringRepresentation().equals(old.orElse(null))) {
                    // The table has been modified. Store the change:
                    String toSet = tableModel.getStringRepresentation();
                    if (toSet.isEmpty()) {
                        ce.addEdit(new UndoableFieldChange(aSel, FieldName.FILE, old.orElse(null), null));
                        aSel.clearField(FieldName.FILE);
                    } else {
                        ce.addEdit(new UndoableFieldChange(aSel, FieldName.FILE, old.orElse(null), toSet));
                        aSel.setField(FieldName.FILE, toSet);
                    }
                    changedEntries.add(aSel);
                }
            }
        }
    }
    if (!changedEntries.isEmpty()) {
        // Add the undo edit:
        ce.end();
        panel.getUndoManager().addEdit(ce);
        panel.markBaseChanged();
        entriesChangedCount = changedEntries.size();
    }
}
Also used : BibEntry(org.jabref.model.entry.BibEntry) FileListTableModel(org.jabref.gui.filelist.FileListTableModel) LinkedFile(org.jabref.model.entry.LinkedFile) ExternalFileTypeEntryEditor(org.jabref.gui.externalfiletype.ExternalFileTypeEntryEditor) Optional(java.util.Optional) ArrayList(java.util.ArrayList) FileListEntry(org.jabref.gui.filelist.FileListEntry) UnknownExternalFileType(org.jabref.gui.externalfiletype.UnknownExternalFileType) UnknownExternalFileType(org.jabref.gui.externalfiletype.UnknownExternalFileType) ExternalFileType(org.jabref.gui.externalfiletype.ExternalFileType) FileListEntryEditor(org.jabref.gui.filelist.FileListEntryEditor) NamedCompound(org.jabref.gui.undo.NamedCompound) UndoableFieldChange(org.jabref.gui.undo.UndoableFieldChange) HashSet(java.util.HashSet)

Example 7 with FileListEntry

use of org.jabref.gui.filelist.FileListEntry in project jabref by JabRef.

the class DroppedFileHandler method doLink.

/**
     * Make a extension to the file.
     *
     * @param entry    The entry to extension from.
     * @param fileType The FileType associated with the file.
     * @param filename The path to the file.
     * @param edits    An NamedCompound action this action is to be added to. If none
     *                 is given, the edit is added to the panel's undoManager.
     */
private void doLink(BibEntry entry, ExternalFileType fileType, String filename, boolean avoidDuplicate, NamedCompound edits) {
    Optional<String> oldValue = entry.getField(FieldName.FILE);
    FileListTableModel tm = new FileListTableModel();
    oldValue.ifPresent(tm::setContent);
    // If avoidDuplicate==true, we should check if this file is already linked:
    if (avoidDuplicate) {
        // For comparison, find the absolute filename:
        List<Path> dirs = panel.getBibDatabaseContext().getFileDirectoriesAsPaths(Globals.prefs.getFileDirectoryPreferences());
        String absFilename;
        if (new File(filename).isAbsolute() || dirs.isEmpty()) {
            absFilename = filename;
        } else {
            Optional<Path> file = FileHelper.expandFilenameAsPath(filename, dirs);
            if (file.isPresent()) {
                absFilename = file.get().toAbsolutePath().toString();
            } else {
                // This shouldn't happen based on the old code, so maybe one should set it something else?
                absFilename = "";
            }
        }
        LOGGER.debug("absFilename: " + absFilename);
        for (int i = 0; i < tm.getRowCount(); i++) {
            FileListEntry flEntry = tm.getEntry(i);
            // Find the absolute filename for this existing link:
            String absName = flEntry.toParsedFileField().findIn(dirs).map(Path::toAbsolutePath).map(Path::toString).orElse(null);
            LOGGER.debug("absName: " + absName);
            // If the filenames are equal, we don't need to link, so we simply return:
            if (absFilename.equals(absName)) {
                return;
            }
        }
    }
    tm.addEntry(tm.getRowCount(), new FileListEntry("", filename, fileType));
    String newValue = tm.getStringRepresentation();
    UndoableFieldChange edit = new UndoableFieldChange(entry, FieldName.FILE, oldValue.orElse(null), newValue);
    entry.setField(FieldName.FILE, newValue);
    if (edits == null) {
        panel.getUndoManager().addEdit(edit);
    } else {
        edits.addEdit(edit);
    }
}
Also used : Path(java.nio.file.Path) FileListTableModel(org.jabref.gui.filelist.FileListTableModel) FileListEntry(org.jabref.gui.filelist.FileListEntry) UndoableFieldChange(org.jabref.gui.undo.UndoableFieldChange) File(java.io.File)

Example 8 with FileListEntry

use of org.jabref.gui.filelist.FileListEntry in project jabref by JabRef.

the class EntryFromFileCreator method addFileInfo.

private void addFileInfo(BibEntry entry, File file) {
    Optional<ExternalFileType> fileType = ExternalFileTypes.getInstance().getExternalFileTypeByExt(externalFileType.getFieldName());
    List<Path> possibleFilePaths = JabRefGUI.getMainFrame().getCurrentBasePanel().getBibDatabaseContext().getFileDirectoriesAsPaths(Globals.prefs.getFileDirectoryPreferences());
    Path shortenedFileName = FileUtil.shortenFileName(file.toPath(), possibleFilePaths);
    FileListEntry fileListEntry = new FileListEntry("", shortenedFileName.toString(), fileType);
    FileListTableModel model = new FileListTableModel();
    model.addEntry(0, fileListEntry);
    entry.setField(FieldName.FILE, model.getStringRepresentation());
}
Also used : ExternalFileType(org.jabref.gui.externalfiletype.ExternalFileType) Path(java.nio.file.Path) FileListTableModel(org.jabref.gui.filelist.FileListTableModel) FileListEntry(org.jabref.gui.filelist.FileListEntry)

Example 9 with FileListEntry

use of org.jabref.gui.filelist.FileListEntry in project jabref by JabRef.

the class MainTableSelectionListener method showIconRightClickMenu.

/**
     * Process popup trigger events occurring on an icon cell in the table. Show a menu where the user can choose which
     * external resource to open for the entry. If no relevant external resources exist, let the normal popup trigger
     * handler do its thing instead.
     *
     * @param e The mouse event defining this popup trigger.
     * @param row The row where the event occurred.
     * @param column the MainTableColumn associated with this table cell.
     */
private void showIconRightClickMenu(MouseEvent e, int row, MainTableColumn column) {
    BibEntry entry = tableRows.get(row);
    JPopupMenu menu = new JPopupMenu();
    boolean showDefaultPopup = true;
    // field that can specify a list of links:
    if (!column.getBibtexFields().isEmpty()) {
        for (String field : column.getBibtexFields()) {
            if (FieldName.FILE.equals(field)) {
                // We use a FileListTableModel to parse the field content:
                FileListTableModel fileList = new FileListTableModel();
                entry.getField(field).ifPresent(fileList::setContent);
                for (int i = 0; i < fileList.getRowCount(); i++) {
                    FileListEntry flEntry = fileList.getEntry(i);
                    if (column.isFileFilter() && (!flEntry.getType().get().getName().equalsIgnoreCase(column.getColumnName()))) {
                        continue;
                    }
                    String description = flEntry.getDescription();
                    if ((description == null) || (description.trim().isEmpty())) {
                        description = flEntry.getLink();
                    }
                    menu.add(new ExternalFileMenuItem(panel.frame(), entry, description, flEntry.getLink(), flEntry.getType().get().getIcon(), panel.getBibDatabaseContext(), flEntry.getType()));
                    showDefaultPopup = false;
                }
            } else {
                if (SpecialField.isSpecialField(column.getColumnName())) {
                    // full pop should be shown as left click already shows short popup
                    showDefaultPopup = true;
                } else {
                    Optional<String> content = entry.getField(field);
                    if (content.isPresent()) {
                        Icon icon;
                        JLabel iconLabel = GUIGlobals.getTableIcon(field);
                        if (iconLabel == null) {
                            icon = IconTheme.JabRefIcon.FILE.getIcon();
                        } else {
                            icon = iconLabel.getIcon();
                        }
                        menu.add(new ExternalFileMenuItem(panel.frame(), entry, content.get(), content.get(), icon, panel.getBibDatabaseContext(), field));
                        if (field.equals(FieldName.DOI)) {
                            menu.add(new CopyDoiUrlAction(content.get()));
                        }
                        showDefaultPopup = false;
                    }
                }
            }
        }
        if (showDefaultPopup) {
            processPopupTrigger(e, row);
        } else {
            menu.show(table, e.getX(), e.getY());
        }
    }
}
Also used : BibEntry(org.jabref.model.entry.BibEntry) FileListTableModel(org.jabref.gui.filelist.FileListTableModel) ExternalFileMenuItem(org.jabref.gui.externalfiletype.ExternalFileMenuItem) FileListEntry(org.jabref.gui.filelist.FileListEntry) JLabel(javax.swing.JLabel) JPopupMenu(javax.swing.JPopupMenu) CopyDoiUrlAction(org.jabref.gui.actions.CopyDoiUrlAction) Icon(javax.swing.Icon)

Example 10 with FileListEntry

use of org.jabref.gui.filelist.FileListEntry in project jabref by JabRef.

the class PdfImporter method doXMPImport.

private void doXMPImport(String fileName, List<BibEntry> res) {
    List<BibEntry> localRes = new ArrayList<>();
    PdfXmpImporter importer = new PdfXmpImporter(Globals.prefs.getXMPPreferences());
    Path filePath = Paths.get(fileName);
    ParserResult result = importer.importDatabase(filePath, Globals.prefs.getDefaultEncoding());
    if (result.hasWarnings()) {
        frame.showMessage(result.getErrorMessage());
    }
    localRes.addAll(result.getDatabase().getEntries());
    BibEntry entry;
    if (localRes.isEmpty()) {
        // import failed -> generate default entry
        LOGGER.info("Import failed");
        createNewBlankEntry(fileName).ifPresent(res::add);
        return;
    }
    // only one entry is imported
    entry = localRes.get(0);
    // insert entry to database and link file
    panel.getDatabase().insertEntry(entry);
    panel.markBaseChanged();
    FileListTableModel tm = new FileListTableModel();
    Path toLink = Paths.get(fileName);
    // Get a list of file directories:
    List<Path> dirsS = panel.getBibDatabaseContext().getFileDirectoriesAsPaths(Globals.prefs.getFileDirectoryPreferences());
    tm.addEntry(0, new FileListEntry(toLink.getFileName().toString(), FileUtil.shortenFileName(toLink, dirsS).toString(), ExternalFileTypes.getInstance().getExternalFileTypeByName("PDF")));
    entry.setField(FieldName.FILE, tm.getStringRepresentation());
    res.add(entry);
}
Also used : Path(java.nio.file.Path) BibEntry(org.jabref.model.entry.BibEntry) ParserResult(org.jabref.logic.importer.ParserResult) FileListTableModel(org.jabref.gui.filelist.FileListTableModel) ArrayList(java.util.ArrayList) FileListEntry(org.jabref.gui.filelist.FileListEntry) PdfXmpImporter(org.jabref.logic.importer.fileformat.PdfXmpImporter)

Aggregations

FileListEntry (org.jabref.gui.filelist.FileListEntry)14 FileListTableModel (org.jabref.gui.filelist.FileListTableModel)9 ExternalFileType (org.jabref.gui.externalfiletype.ExternalFileType)7 Path (java.nio.file.Path)6 BibEntry (org.jabref.model.entry.BibEntry)5 UndoableFieldChange (org.jabref.gui.undo.UndoableFieldChange)4 IOException (java.io.IOException)3 ArrayList (java.util.ArrayList)3 List (java.util.List)3 Optional (java.util.Optional)3 JLabel (javax.swing.JLabel)3 ExternalFileMenuItem (org.jabref.gui.externalfiletype.ExternalFileMenuItem)3 UnknownExternalFileType (org.jabref.gui.externalfiletype.UnknownExternalFileType)3 FileListEntryEditor (org.jabref.gui.filelist.FileListEntryEditor)3 LinkedFile (org.jabref.model.entry.LinkedFile)3 File (java.io.File)2 Icon (javax.swing.Icon)2 JPopupMenu (javax.swing.JPopupMenu)2 CopyDoiUrlAction (org.jabref.gui.actions.CopyDoiUrlAction)2 ExternalFileTypeEntryEditor (org.jabref.gui.externalfiletype.ExternalFileTypeEntryEditor)2