Search in sources :

Example 1 with FileListEntry

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

the class BasePanel method openExternalFile.

private void openExternalFile() {
    JabRefExecutorService.INSTANCE.execute(() -> {
        final List<BibEntry> bes = mainTable.getSelectedEntries();
        if (bes.size() != 1) {
            output(Localization.lang("This operation requires exactly one item to be selected."));
            return;
        }
        final BibEntry entry = bes.get(0);
        if (!entry.hasField(FieldName.FILE)) {
            // no bibtex field
            new SearchAndOpenFile(entry, BasePanel.this).searchAndOpen();
            return;
        }
        FileListTableModel fileListTableModel = new FileListTableModel();
        entry.getField(FieldName.FILE).ifPresent(fileListTableModel::setContent);
        if (fileListTableModel.getRowCount() == 0) {
            // content in BibTeX field is not readable
            new SearchAndOpenFile(entry, BasePanel.this).searchAndOpen();
            return;
        }
        FileListEntry flEntry = fileListTableModel.getEntry(0);
        ExternalFileMenuItem item = new ExternalFileMenuItem(frame(), entry, "", flEntry.getLink(), flEntry.getType().get().getIcon(), bibDatabaseContext, flEntry.getType());
        item.doClick();
    });
}
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)

Example 2 with FileListEntry

use of org.jabref.gui.filelist.FileListEntry 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 3 with FileListEntry

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

the class AutoSetLinks method autoSetLinks.

/**
     * Automatically add links for this set of entries, based on the globally stored list of external file types. The
     * entries are modified, and corresponding UndoEdit elements added to the NamedCompound given as argument.
     * Furthermore, all entries which are modified are added to the Set of entries given as an argument.
     * <p>
     * The entries' bibtex keys must have been set - entries lacking key are ignored. The operation is done in a new
     * thread, which is returned for the caller to wait for if needed.
     *
     * @param entries          A collection of BibEntry objects to find links for.
     * @param ce               A NamedCompound to add UndoEdit elements to.
     * @param changedEntries   MODIFIED, optional. A Set of BibEntry objects to which all modified entries is added.
     *                         This is used for status output and debugging
     * @param singleTableModel UGLY HACK. The table model to insert links into. Already existing links are not
     *                         duplicated or removed. This parameter has to be null if entries.count() != 1. The hack has been
     *                         introduced as a bibtexentry does not (yet) support the function getListTableModel() and the
     *                         FileListEntryEditor editor holds an instance of that table model and does not reconstruct it after the
     *                         search has succeeded.
     * @param databaseContext  The database providing the relevant file directory, if any.
     * @param callback         An ActionListener that is notified (on the event dispatch thread) when the search is finished.
     *                         The ActionEvent has id=0 if no new links were added, and id=1 if one or more links were added. This
     *                         parameter can be null, which means that no callback will be notified.
     * @param diag             An instantiated modal JDialog which will be used to display the progress of the automatically setting. This
     *                         parameter can be null, which means that no progress update will be shown.
     * @return the thread performing the automatically setting
     */
public static Runnable autoSetLinks(final List<BibEntry> entries, final NamedCompound ce, final Set<BibEntry> changedEntries, final FileListTableModel singleTableModel, final BibDatabaseContext databaseContext, final ActionListener callback, final JDialog diag) {
    final Collection<ExternalFileType> types = ExternalFileTypes.getInstance().getExternalFileTypeSelection();
    if (diag != null) {
        final JProgressBar prog = new JProgressBar(SwingConstants.HORIZONTAL, 0, types.size() - 1);
        final JLabel label = new JLabel(Localization.lang("Searching for files"));
        prog.setIndeterminate(true);
        prog.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
        diag.setTitle(Localization.lang("Automatically setting file links"));
        diag.getContentPane().add(prog, BorderLayout.CENTER);
        diag.getContentPane().add(label, BorderLayout.SOUTH);
        diag.pack();
        diag.setLocationRelativeTo(diag.getParent());
    }
    Runnable r = new Runnable() {

        @Override
        public void run() {
            // determine directories to search in
            final List<Path> dirs = databaseContext.getFileDirectoriesAsPaths(Globals.prefs.getFileDirectoryPreferences());
            // determine extensions
            final List<String> extensions = types.stream().map(ExternalFileType::getExtension).collect(Collectors.toList());
            // Run the search operation:
            FileFinder fileFinder = FileFinders.constructFromConfiguration(Globals.prefs.getAutoLinkPreferences());
            Map<BibEntry, List<Path>> result = fileFinder.findAssociatedFiles(entries, dirs, extensions);
            boolean foundAny = false;
            // Iterate over the entries:
            for (Entry<BibEntry, List<Path>> entryFilePair : result.entrySet()) {
                FileListTableModel tableModel;
                Optional<String> oldVal = entryFilePair.getKey().getField(FieldName.FILE);
                if (singleTableModel == null) {
                    tableModel = new FileListTableModel();
                    oldVal.ifPresent(tableModel::setContent);
                } else {
                    assert entries.size() == 1;
                    tableModel = singleTableModel;
                }
                List<Path> files = entryFilePair.getValue();
                for (Path f : files) {
                    f = FileUtil.shortenFileName(f, dirs);
                    boolean alreadyHas = false;
                    //System.out.println("File: "+f.getPath());
                    for (int j = 0; j < tableModel.getRowCount(); j++) {
                        FileListEntry existingEntry = tableModel.getEntry(j);
                        //System.out.println("Comp: "+existingEntry.getLink());
                        if (Paths.get(existingEntry.getLink()).equals(f)) {
                            alreadyHas = true;
                            foundAny = true;
                            break;
                        }
                    }
                    if (!alreadyHas) {
                        foundAny = true;
                        Optional<ExternalFileType> type;
                        Optional<String> extension = FileHelper.getFileExtension(f);
                        if (extension.isPresent()) {
                            type = ExternalFileTypes.getInstance().getExternalFileTypeByExt(extension.get());
                        } else {
                            type = Optional.of(new UnknownExternalFileType(""));
                        }
                        FileListEntry flEntry = new FileListEntry(f.getFileName().toString(), f.toString(), type);
                        tableModel.addEntry(tableModel.getRowCount(), flEntry);
                        String newVal = tableModel.getStringRepresentation();
                        if (newVal.isEmpty()) {
                            newVal = null;
                        }
                        if (ce != null) {
                            // store undo information
                            UndoableFieldChange change = new UndoableFieldChange(entryFilePair.getKey(), FieldName.FILE, oldVal.orElse(null), newVal);
                            ce.addEdit(change);
                        }
                        // hack: if table model is given, do NOT modify entry
                        if (singleTableModel == null) {
                            entryFilePair.getKey().setField(FieldName.FILE, newVal);
                        }
                        if (changedEntries != null) {
                            changedEntries.add(entryFilePair.getKey());
                        }
                    }
                }
            }
            // handle callbacks and dialog
            // FIXME: The ID signals if action was successful :/
            final int id = foundAny ? 1 : 0;
            SwingUtilities.invokeLater(new Runnable() {

                @Override
                public void run() {
                    if (diag != null) {
                        diag.dispose();
                    }
                    if (callback != null) {
                        callback.actionPerformed(new ActionEvent(this, id, ""));
                    }
                }
            });
        }
    };
    SwingUtilities.invokeLater(() -> {
        // show dialog which will be hidden when the task is done
        if (diag != null) {
            diag.setVisible(true);
        }
    });
    return r;
}
Also used : ActionEvent(java.awt.event.ActionEvent) JProgressBar(javax.swing.JProgressBar) FileListEntry(org.jabref.gui.filelist.FileListEntry) FileFinder(org.jabref.logic.util.io.FileFinder) UnknownExternalFileType(org.jabref.gui.externalfiletype.UnknownExternalFileType) UnknownExternalFileType(org.jabref.gui.externalfiletype.UnknownExternalFileType) ExternalFileType(org.jabref.gui.externalfiletype.ExternalFileType) UndoableFieldChange(org.jabref.gui.undo.UndoableFieldChange) List(java.util.List) Path(java.nio.file.Path) BibEntry(org.jabref.model.entry.BibEntry) FileListTableModel(org.jabref.gui.filelist.FileListTableModel) JLabel(javax.swing.JLabel)

Example 4 with FileListEntry

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

the class MoveFileAction method actionPerformed.

@Override
public void actionPerformed(ActionEvent event) {
    int selected = editor.getSelectedRow();
    if (selected == -1) {
        return;
    }
    FileListEntry entry = editor.getTableModel().getEntry(selected);
    LinkedFile field = entry.toParsedFileField();
    if (field.isOnlineLink()) {
        // TODO: notify that this operation cannot be done on remote links
        return;
    }
    // Get an absolute path representation:
    Optional<Path> fileDir = frame.getCurrentBasePanel().getBibDatabaseContext().getFirstExistingFileDir(Globals.prefs.getFileDirectoryPreferences());
    if (!fileDir.isPresent()) {
        JOptionPane.showMessageDialog(frame, Localization.lang("File directory is not set or does not exist!"), Localization.lang("Move file"), JOptionPane.ERROR_MESSAGE);
        return;
    }
    // Check if the current file exists:
    Optional<Path> file = field.findIn(frame.getCurrentBasePanel().getBibDatabaseContext(), Globals.prefs.getFileDirectoryPreferences());
    if ((file.isPresent()) && Files.exists(file.get())) {
        MoveFilesCleanup moveFiles = new MoveFilesCleanup(frame.getCurrentBasePanel().getBibDatabaseContext(), Globals.prefs.getCleanupPreferences(Globals.journalAbbreviationLoader).getFileDirPattern(), Globals.prefs.getFileDirectoryPreferences(), Globals.prefs.getLayoutFormatterPreferences(Globals.journalAbbreviationLoader), field);
        String[] options = { Localization.lang("Move file"), Localization.lang("Cancel") };
        int dialogResult = JOptionPane.showOptionDialog(frame, Localization.lang("Move file to file directory?") + " " + fileDir.get(), Localization.lang("Move file"), JOptionPane.INFORMATION_MESSAGE, JOptionPane.YES_NO_CANCEL_OPTION, null, options, options[0]);
        if (dialogResult == JOptionPane.YES_OPTION) {
            moveFiles.cleanup((eEditor.getEntry()));
        }
    } else {
        // File doesn't exist, so we can't move it.
        JOptionPane.showMessageDialog(frame, Localization.lang("Could not find file '%0'.", entry.getLink()), Localization.lang("File not found"), JOptionPane.ERROR_MESSAGE);
    }
}
Also used : Path(java.nio.file.Path) LinkedFile(org.jabref.model.entry.LinkedFile) MoveFilesCleanup(org.jabref.logic.cleanup.MoveFilesCleanup) FileListEntry(org.jabref.gui.filelist.FileListEntry)

Example 5 with FileListEntry

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

the class RenameFileAction method actionPerformed.

@Override
public void actionPerformed(ActionEvent e) {
    int selected = editor.getSelectedRow();
    if (selected == -1) {
        return;
    }
    FileListEntry entry = editor.getTableModel().getEntry(selected);
    LinkedFile field = entry.toParsedFileField();
    // Check if the current file exists:
    if (field.isOnlineLink()) {
        // TODO: notify that this operation cannot be done on remote links
        return;
    }
    Optional<Path> fileDir = frame.getCurrentBasePanel().getBibDatabaseContext().getFirstExistingFileDir(Globals.prefs.getFileDirectoryPreferences());
    if (!fileDir.isPresent()) {
        JOptionPane.showMessageDialog(frame, Localization.lang("File directory is not set or does not exist!"), Localization.lang("Rename file"), JOptionPane.ERROR_MESSAGE);
        return;
    }
    Optional<Path> file = field.findIn(frame.getCurrentBasePanel().getBibDatabaseContext(), Globals.prefs.getFileDirectoryPreferences());
    if ((file.isPresent()) && Files.exists(file.get())) {
        RenamePdfCleanup pdfCleanup = new RenamePdfCleanup(false, frame.getCurrentBasePanel().getBibDatabaseContext(), Globals.prefs.getCleanupPreferences(Globals.journalAbbreviationLoader).getFileNamePattern(), Globals.prefs.getLayoutFormatterPreferences(Globals.journalAbbreviationLoader), Globals.prefs.getFileDirectoryPreferences(), field);
        String targetFileName = pdfCleanup.getTargetFileName(field, eEditor.getEntry());
        String[] options = { Localization.lang("Rename file"), Localization.lang("Cancel") };
        int dialogResult = JOptionPane.showOptionDialog(frame, Localization.lang("Rename file to") + " " + targetFileName, Localization.lang("Rename file"), JOptionPane.INFORMATION_MESSAGE, JOptionPane.YES_NO_CANCEL_OPTION, null, options, options[0]);
        //indicates Rename pressed
        if (dialogResult == JOptionPane.YES_OPTION) {
            pdfCleanup.cleanup(eEditor.getEntry());
        }
    }
}
Also used : Path(java.nio.file.Path) LinkedFile(org.jabref.model.entry.LinkedFile) FileListEntry(org.jabref.gui.filelist.FileListEntry) RenamePdfCleanup(org.jabref.logic.cleanup.RenamePdfCleanup)

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