Search in sources :

Example 11 with FileListEntry

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

the class DownloadExternalFile method download.

/**
     * Start a download.
     *
     * @param callback The object to which the filename should be reported when download
     *                 is complete.
     */
public void download(URL url, final DownloadCallback callback) throws IOException {
    String res = url.toString();
    String mimeType;
    // First of all, start the download itself in the background to a temporary file:
    final File tmp = File.createTempFile("jabref_download", "tmp");
    tmp.deleteOnExit();
    URLDownload udl = new URLDownload(url);
    try {
        // TODO: what if this takes long time?
        // TODO: stop editor dialog if this results in an error:
        // Read MIME type
        mimeType = udl.getMimeType();
    } catch (IOException ex) {
        JOptionPane.showMessageDialog(frame, Localization.lang("Invalid URL") + ": " + ex.getMessage(), Localization.lang("Download file"), JOptionPane.ERROR_MESSAGE);
        LOGGER.info("Error while downloading " + "'" + res + "'", ex);
        return;
    }
    final URL urlF = url;
    final URLDownload udlF = udl;
    JabRefExecutorService.INSTANCE.execute(() -> {
        try {
            udlF.toFile(tmp.toPath());
        } catch (IOException e2) {
            dontShowDialog = true;
            if ((editor != null) && editor.isVisible()) {
                editor.setVisible(false, false);
            }
            JOptionPane.showMessageDialog(frame, Localization.lang("Invalid URL") + ": " + e2.getMessage(), Localization.lang("Download file"), JOptionPane.ERROR_MESSAGE);
            LOGGER.info("Error while downloading " + "'" + urlF + "'", e2);
            return;
        }
        // Download finished: call the method that stops the progress bar etc.:
        SwingUtilities.invokeLater(DownloadExternalFile.this::downloadFinished);
    });
    Optional<ExternalFileType> suggestedType = Optional.empty();
    if (mimeType != null) {
        LOGGER.debug("MIME Type suggested: " + mimeType);
        suggestedType = ExternalFileTypes.getInstance().getExternalFileTypeByMimeType(mimeType);
    }
    // Then, while the download is proceeding, let the user choose the details of the file:
    String suffix;
    if (suggestedType.isPresent()) {
        suffix = suggestedType.get().getExtension();
    } else {
        // If we did not find a file type from the MIME type, try based on extension:
        suffix = getSuffix(res);
        if (suffix == null) {
            suffix = "";
        }
        suggestedType = ExternalFileTypes.getInstance().getExternalFileTypeByExt(suffix);
    }
    String suggestedName = getSuggestedFileName(suffix);
    List<String> fDirectory = databaseContext.getFileDirectories(Globals.prefs.getFileDirectoryPreferences());
    String directory;
    if (fDirectory.isEmpty()) {
        directory = null;
    } else {
        directory = fDirectory.get(0);
    }
    final String suggestDir = directory == null ? System.getProperty("user.home") : directory;
    File file = new File(new File(suggestDir), suggestedName);
    FileListEntry fileListEntry = new FileListEntry("", file.getCanonicalPath(), suggestedType);
    editor = new FileListEntryEditor(frame, fileListEntry, true, false, databaseContext, true);
    editor.getProgressBar().setIndeterminate(true);
    editor.setOkEnabled(false);
    editor.setExternalConfirm(closeEntry -> {
        File f = directory == null ? new File(closeEntry.getLink()) : expandFilename(directory, closeEntry.getLink());
        if (f.isDirectory()) {
            JOptionPane.showMessageDialog(frame, Localization.lang("Target file cannot be a directory."), Localization.lang("Download file"), JOptionPane.ERROR_MESSAGE);
            return false;
        }
        if (f.exists()) {
            return JOptionPane.showConfirmDialog(frame, Localization.lang("'%0' exists. Overwrite file?", f.getName()), Localization.lang("Download file"), JOptionPane.OK_CANCEL_OPTION) == JOptionPane.OK_OPTION;
        } else {
            return true;
        }
    });
    if (dontShowDialog) {
        return;
    } else {
        editor.setVisible(true, false);
    }
    // Editor closed. Go on:
    if (editor.okPressed()) {
        File toFile = directory == null ? new File(fileListEntry.getLink()) : expandFilename(directory, fileListEntry.getLink());
        String dirPrefix;
        if (directory == null) {
            dirPrefix = null;
        } else {
            if (directory.endsWith(OS.FILE_SEPARATOR)) {
                dirPrefix = directory;
            } else {
                dirPrefix = directory + OS.FILE_SEPARATOR;
            }
        }
        boolean success = FileUtil.copyFile(Paths.get(tmp.toURI()), Paths.get(toFile.toURI()), true);
        if (!success) {
            // OOps, the file exists!
            LOGGER.error("File already exists! DownloadExternalFile.download()");
        }
        // path to relative:
        if ((dirPrefix != null) && fileListEntry.getLink().startsWith(directory) && (fileListEntry.getLink().length() > dirPrefix.length())) {
            fileListEntry = new FileListEntry(fileListEntry.getDescription(), fileListEntry.getLink().substring(dirPrefix.length()), fileListEntry.getType());
        }
        callback.downloadComplete(fileListEntry);
        if (!tmp.delete()) {
            LOGGER.info("Cannot delete temporary file");
        }
    } else {
        // Canceled. Just delete the temp file:
        if (downloadFinished && !tmp.delete()) {
            LOGGER.info("Cannot delete temporary file");
        }
    }
}
Also used : ExternalFileType(org.jabref.gui.externalfiletype.ExternalFileType) FileListEntryEditor(org.jabref.gui.filelist.FileListEntryEditor) FileListEntry(org.jabref.gui.filelist.FileListEntry) IOException(java.io.IOException) URLDownload(org.jabref.logic.net.URLDownload) File(java.io.File) URL(java.net.URL)

Example 12 with FileListEntry

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

the class FileListEditor method openSelectedFile.

private void openSelectedFile() {
    int row = getSelectedRow();
    if (row >= 0) {
        FileListEntry entry = tableModel.getEntry(row);
        try {
            Optional<ExternalFileType> type = ExternalFileTypes.getInstance().getExternalFileTypeByName(entry.getType().get().getName());
            JabRefDesktop.openExternalFileAnyFormat(databaseContext, entry.getLink(), type.isPresent() ? type : entry.getType());
        } catch (IOException e) {
            LOGGER.warn("Cannot open selected file.", e);
        }
    }
}
Also used : ExternalFileType(org.jabref.gui.externalfiletype.ExternalFileType) FileListEntry(org.jabref.gui.filelist.FileListEntry) IOException(java.io.IOException)

Example 13 with FileListEntry

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

the class FileListEditor method moveEntry.

private void moveEntry(int i) {
    int[] sel = getSelectedRows();
    if ((sel.length != 1) || (tableModel.getRowCount() < 2)) {
        return;
    }
    int toIdx = sel[0] + i;
    if (toIdx >= tableModel.getRowCount()) {
        toIdx -= tableModel.getRowCount();
    }
    if (toIdx < 0) {
        toIdx += tableModel.getRowCount();
    }
    FileListEntry entry = tableModel.getEntry(sel[0]);
    tableModel.removeEntry(sel[0]);
    tableModel.addEntry(toIdx, entry);
    entryEditor.updateField(this);
    setRowSelectionInterval(toIdx, toIdx);
    adjustColumnWidth();
}
Also used : FileListEntry(org.jabref.gui.filelist.FileListEntry)

Example 14 with FileListEntry

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

the class MainTableSelectionListener method mouseClicked.

@Override
public void mouseClicked(MouseEvent e) {
    // First find the column on which the user has clicked.
    final int row = table.rowAtPoint(e.getPoint());
    // A double click on an entry should open the entry's editor.
    if (e.getClickCount() == 2) {
        BibEntry toShow = tableRows.get(row);
        editSignalled(toShow);
        return;
    }
    final int col = table.columnAtPoint(e.getPoint());
    // get the MainTableColumn which is currently visible at col
    int modelIndex = table.getColumnModel().getColumn(col).getModelIndex();
    MainTableColumn modelColumn = table.getMainTableColumn(modelIndex);
    // action will be taken when the button is released:
    if (OS.WINDOWS && (modelColumn.isIconColumn()) && (e.getButton() != MouseEvent.BUTTON1)) {
        return;
    }
    // Check if the clicked colum is a specialfield column
    if (modelColumn.isIconColumn() && (SpecialField.isSpecialField(modelColumn.getColumnName()))) {
        // handle specialfield
        handleSpecialFieldLeftClick(e, modelColumn.getColumnName());
    } else if (modelColumn.isIconColumn()) {
        // left click on icon field
        Object value = table.getValueAt(row, col);
        if (value == null) {
            // No icon here, so we do nothing.
            return;
        }
        final BibEntry entry = tableRows.get(row);
        final List<String> fieldNames = modelColumn.getBibtexFields();
        // Open it now. We do this in a thread, so the program won't freeze during the wait.
        JabRefExecutorService.INSTANCE.execute(() -> {
            panel.output(Localization.lang("External viewer called") + '.');
            // (is relevant for combinations such as "url/doi")
            for (String fieldName : fieldNames) {
                // Check if field is present, if not skip this field
                if (entry.hasField(fieldName)) {
                    String link = entry.getField(fieldName).get();
                    // field that can specify a list of links:
                    if (fieldName.equals(FieldName.FILE)) {
                        // We use a FileListTableModel to parse the field content:
                        FileListTableModel fileList = new FileListTableModel();
                        fileList.setContent(link);
                        FileListEntry flEntry = null;
                        // If there are one or more links of the correct type, open the first one:
                        if (modelColumn.isFileFilter()) {
                            for (int i = 0; i < fileList.getRowCount(); i++) {
                                if (fileList.getEntry(i).getType().toString().equals(modelColumn.getColumnName())) {
                                    flEntry = fileList.getEntry(i);
                                    break;
                                }
                            }
                        } else if (fileList.getRowCount() > 0) {
                            //If there are no file types specified open the first file
                            flEntry = fileList.getEntry(0);
                        }
                        if (flEntry != null) {
                            ExternalFileMenuItem item = new ExternalFileMenuItem(panel.frame(), entry, "", flEntry.getLink(), flEntry.getType().map(ExternalFileType::getIcon).orElse(null), panel.getBibDatabaseContext(), flEntry.getType());
                            item.doClick();
                        }
                    } else {
                        try {
                            JabRefDesktop.openExternalViewer(panel.getBibDatabaseContext(), link, fieldName);
                        } catch (IOException ex) {
                            panel.output(Localization.lang("Unable to open link."));
                            LOGGER.info("Unable to open link", ex);
                        }
                    }
                    // only open the first link
                    break;
                }
            }
        });
    } else if (modelColumn.getBibtexFields().contains(FieldName.CROSSREF)) {
        // Clicking on crossref column
        tableRows.get(row).getField(FieldName.CROSSREF).ifPresent(crossref -> panel.getDatabase().getEntryByKey(crossref).ifPresent(entry -> panel.highlightEntry(entry)));
    }
    panel.frame().updateEnabledState();
}
Also used : FocusListener(java.awt.event.FocusListener) KeyListener(java.awt.event.KeyListener) PreviewPanel(org.jabref.gui.PreviewPanel) FieldName(org.jabref.model.entry.FieldName) JabRefDesktop(org.jabref.gui.desktop.JabRefDesktop) IconTheme(org.jabref.gui.IconTheme) SpecialField(org.jabref.model.entry.specialfields.SpecialField) BasePanel(org.jabref.gui.BasePanel) SpecialFieldValue(org.jabref.model.entry.specialfields.SpecialFieldValue) SwingUtilities(javax.swing.SwingUtilities) SpecialFieldViewModel(org.jabref.gui.specialfields.SpecialFieldViewModel) Locale(java.util.Locale) SpecialFieldValueViewModel(org.jabref.gui.specialfields.SpecialFieldValueViewModel) Localization(org.jabref.logic.l10n.Localization) CopyDoiUrlAction(org.jabref.gui.actions.CopyDoiUrlAction) SpecialFieldMenuAction(org.jabref.gui.specialfields.SpecialFieldMenuAction) MouseListener(java.awt.event.MouseListener) Timer(javax.swing.Timer) ExternalFileType(org.jabref.gui.externalfiletype.ExternalFileType) BasePanelMode(org.jabref.gui.BasePanelMode) EventList(ca.odell.glazedlists.EventList) JPopupMenu(javax.swing.JPopupMenu) BibEntry(org.jabref.model.entry.BibEntry) FileListTableModel(org.jabref.gui.filelist.FileListTableModel) IOException(java.io.IOException) Icon(javax.swing.Icon) JabRefGUI(org.jabref.JabRefGUI) EntryEditor(org.jabref.gui.entryeditor.EntryEditor) KeyEvent(java.awt.event.KeyEvent) MouseEvent(java.awt.event.MouseEvent) Globals(org.jabref.Globals) FileListEntry(org.jabref.gui.filelist.FileListEntry) RightClickMenu(org.jabref.gui.menus.RightClickMenu) ListEvent(ca.odell.glazedlists.event.ListEvent) Objects(java.util.Objects) List(java.util.List) GUIGlobals(org.jabref.gui.GUIGlobals) ListEventListener(ca.odell.glazedlists.event.ListEventListener) FocusEvent(java.awt.event.FocusEvent) JLabel(javax.swing.JLabel) OS(org.jabref.logic.util.OS) Optional(java.util.Optional) Log(org.apache.commons.logging.Log) LogFactory(org.apache.commons.logging.LogFactory) JabRefExecutorService(org.jabref.JabRefExecutorService) ExternalFileMenuItem(org.jabref.gui.externalfiletype.ExternalFileMenuItem) PreviewPreferences(org.jabref.preferences.PreviewPreferences) BibEntry(org.jabref.model.entry.BibEntry) FileListTableModel(org.jabref.gui.filelist.FileListTableModel) ExternalFileMenuItem(org.jabref.gui.externalfiletype.ExternalFileMenuItem) FileListEntry(org.jabref.gui.filelist.FileListEntry) EventList(ca.odell.glazedlists.EventList) List(java.util.List) IOException(java.io.IOException)

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