Search in sources :

Example 11 with ExternalFileType

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

the class GUIGlobals method init.

/**
     * Perform initializations that are only used in graphical mode. This is to prevent
     * the "Xlib: connection to ":0.0" refused by server" error when access to the X server
     * on Un*x is unavailable.
     */
public static void init() {
    JLabel label;
    label = new JLabel(IconTheme.JabRefIcon.PDF_FILE.getSmallIcon());
    label.setToolTipText(Localization.lang("Open") + " PDF");
    GUIGlobals.TABLE_ICONS.put(FieldName.PDF, label);
    label = new JLabel(IconTheme.JabRefIcon.WWW.getSmallIcon());
    label.setToolTipText(Localization.lang("Open") + " URL");
    GUIGlobals.TABLE_ICONS.put(FieldName.URL, label);
    label = new JLabel(IconTheme.JabRefIcon.WWW.getSmallIcon());
    label.setToolTipText(Localization.lang("Open") + " CiteSeer URL");
    GUIGlobals.TABLE_ICONS.put("citeseerurl", label);
    label = new JLabel(IconTheme.JabRefIcon.WWW.getSmallIcon());
    label.setToolTipText(Localization.lang("Open") + " ArXiv URL");
    GUIGlobals.TABLE_ICONS.put(FieldName.EPRINT, label);
    label = new JLabel(IconTheme.JabRefIcon.DOI.getSmallIcon());
    label.setToolTipText(Localization.lang("Open") + " DOI " + Localization.lang("web link"));
    GUIGlobals.TABLE_ICONS.put(FieldName.DOI, label);
    label = new JLabel(IconTheme.JabRefIcon.FILE.getSmallIcon());
    label.setToolTipText(Localization.lang("Open") + " PS");
    GUIGlobals.TABLE_ICONS.put(FieldName.PS, label);
    label = new JLabel(IconTheme.JabRefIcon.FOLDER.getSmallIcon());
    label.setToolTipText(Localization.lang("Open folder"));
    GUIGlobals.TABLE_ICONS.put(FieldName.FOLDER, label);
    label = new JLabel(IconTheme.JabRefIcon.FILE.getSmallIcon());
    label.setToolTipText(Localization.lang("Open file"));
    GUIGlobals.TABLE_ICONS.put(FieldName.FILE, label);
    for (ExternalFileType fileType : ExternalFileTypes.getInstance().getExternalFileTypeSelection()) {
        label = new JLabel(fileType.getIcon());
        label.setToolTipText(Localization.lang("Open %0 file", fileType.getName()));
        GUIGlobals.TABLE_ICONS.put(fileType.getName(), label);
    }
    SpecialFieldViewModel relevanceViewModel = new SpecialFieldViewModel(SpecialField.RELEVANCE);
    label = new JLabel(relevanceViewModel.getRepresentingIcon());
    label.setToolTipText(relevanceViewModel.getLocalization());
    GUIGlobals.TABLE_ICONS.put(SpecialField.RELEVANCE.getFieldName(), label);
    SpecialFieldViewModel qualityViewModel = new SpecialFieldViewModel(SpecialField.QUALITY);
    label = new JLabel(qualityViewModel.getRepresentingIcon());
    label.setToolTipText(qualityViewModel.getLocalization());
    GUIGlobals.TABLE_ICONS.put(SpecialField.QUALITY.getFieldName(), label);
    // Ranking item in the menu uses one star
    SpecialFieldViewModel rankViewModel = new SpecialFieldViewModel(SpecialField.RANKING);
    label = new JLabel(rankViewModel.getRepresentingIcon());
    label.setToolTipText(rankViewModel.getLocalization());
    GUIGlobals.TABLE_ICONS.put(SpecialField.RANKING.getFieldName(), label);
    // Priority icon used for the menu
    SpecialFieldViewModel priorityViewModel = new SpecialFieldViewModel(SpecialField.PRIORITY);
    label = new JLabel(priorityViewModel.getRepresentingIcon());
    label.setToolTipText(priorityViewModel.getLocalization());
    GUIGlobals.TABLE_ICONS.put(SpecialField.PRIORITY.getFieldName(), label);
    // Read icon used for menu
    SpecialFieldViewModel readViewModel = new SpecialFieldViewModel(SpecialField.READ_STATUS);
    label = new JLabel(readViewModel.getRepresentingIcon());
    label.setToolTipText(readViewModel.getLocalization());
    GUIGlobals.TABLE_ICONS.put(SpecialField.READ_STATUS.getFieldName(), label);
    // Print icon used for menu
    SpecialFieldViewModel printedViewModel = new SpecialFieldViewModel(SpecialField.PRINTED);
    label = new JLabel(printedViewModel.getRepresentingIcon());
    label.setToolTipText(printedViewModel.getLocalization());
    GUIGlobals.TABLE_ICONS.put(SpecialField.PRINTED.getFieldName(), label);
    if (Globals.prefs.getBoolean(JabRefPreferences.EDITOR_EMACS_KEYBINDINGS)) {
        EmacsKeyBindings.load();
    }
    // Set up entry editor colors, first time:
    GUIGlobals.updateEntryEditorColors();
    GUIGlobals.currentFont = new Font(Globals.prefs.get(JabRefPreferences.FONT_FAMILY), Globals.prefs.getInt(JabRefPreferences.FONT_STYLE), Globals.prefs.getInt(JabRefPreferences.FONT_SIZE));
}
Also used : ExternalFileType(org.jabref.gui.externalfiletype.ExternalFileType) JLabel(javax.swing.JLabel) SpecialFieldViewModel(org.jabref.gui.specialfields.SpecialFieldViewModel) Font(java.awt.Font)

Example 12 with ExternalFileType

use of org.jabref.gui.externalfiletype.ExternalFileType 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 13 with ExternalFileType

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

the class LinkedFilesEditorViewModel method addFromURL.

private void addFromURL(URL url) {
    URLDownload urlDownload = new URLDownload(url);
    Optional<ExternalFileType> suggestedType = inferFileType(urlDownload);
    String suggestedTypeName = suggestedType.map(ExternalFileType::getName).orElse("");
    List<Path> fileDirectories = databaseContext.getFileDirectoriesAsPaths(Globals.prefs.getFileDirectoryPreferences());
    Path destination = constructSuggestedPath(suggestedType, fileDirectories);
    LinkedFileViewModel temporaryDownloadFile = new LinkedFileViewModel(new LinkedFile("", url, suggestedTypeName));
    files.add(temporaryDownloadFile);
    FileDownloadTask downloadTask = new FileDownloadTask(url, destination);
    temporaryDownloadFile.downloadProgressProperty().bind(downloadTask.progressProperty());
    downloadTask.setOnSucceeded(event -> {
        files.remove(temporaryDownloadFile);
        LinkedFile newLinkedFile = fromFile(destination, fileDirectories);
        files.add(new LinkedFileViewModel(newLinkedFile));
    });
    downloadTask.setOnFailed(event -> dialogService.showErrorDialogAndWait("", downloadTask.getException()));
    taskExecutor.execute(downloadTask);
}
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) FileDownloadTask(org.jabref.gui.externalfiles.FileDownloadTask) URLDownload(org.jabref.logic.net.URLDownload)

Example 14 with ExternalFileType

use of org.jabref.gui.externalfiletype.ExternalFileType 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 15 with ExternalFileType

use of org.jabref.gui.externalfiletype.ExternalFileType 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

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