Search in sources :

Example 1 with EntryType

use of org.jabref.model.entry.EntryType in project jabref by JabRef.

the class BasePanel method setupActions.

private void setupActions() {
    SaveDatabaseAction saveAction = new SaveDatabaseAction(this);
    CleanupAction cleanUpAction = new CleanupAction(this, Globals.prefs);
    actions.put(Actions.UNDO, undoAction);
    actions.put(Actions.REDO, redoAction);
    actions.put(Actions.FOCUS_TABLE, (BaseAction) () -> {
        mainTable.requestFocus();
    });
    // The action for opening an entry editor.
    actions.put(Actions.EDIT, (BaseAction) selectionListener::editSignalled);
    // The action for saving a database.
    actions.put(Actions.SAVE, saveAction);
    actions.put(Actions.SAVE_AS, (BaseAction) saveAction::saveAs);
    actions.put(Actions.SAVE_SELECTED_AS, new SaveSelectedAction(SavePreferences.DatabaseSaveType.ALL));
    actions.put(Actions.SAVE_SELECTED_AS_PLAIN, new SaveSelectedAction(SavePreferences.DatabaseSaveType.PLAIN_BIBTEX));
    // The action for copying selected entries.
    actions.put(Actions.COPY, (BaseAction) () -> copy());
    actions.put(Actions.PRINT_PREVIEW, new PrintPreviewAction());
    actions.put(Actions.CUT, (BaseAction) this::cut);
    //when you modify this action be sure to adjust Actions.CUT,
    //they are the same except of the Localization, delete confirmation and Actions.COPY call
    actions.put(Actions.DELETE, (BaseAction) () -> delete(false));
    // The action for pasting entries or cell contents.
    //  - more robust detection of available content flavors (doesn't only look at first one offered)
    //  - support for parsing string-flavor clipboard contents which are bibtex entries.
    //    This allows you to (a) paste entire bibtex entries from a text editor, web browser, etc
    //                       (b) copy and paste entries between multiple instances of JabRef (since
    //         only the text representation seems to get as far as the X clipboard, at least on my system)
    actions.put(Actions.PASTE, (BaseAction) () -> paste());
    actions.put(Actions.SELECT_ALL, (BaseAction) mainTable::selectAll);
    // The action for opening the preamble editor
    actions.put(Actions.EDIT_PREAMBLE, (BaseAction) () -> {
        if (preambleEditor == null) {
            PreambleEditor form = new PreambleEditor(frame, BasePanel.this, bibDatabaseContext.getDatabase());
            form.setLocationRelativeTo(frame);
            form.setVisible(true);
            preambleEditor = form;
        } else {
            preambleEditor.setVisible(true);
        }
    });
    // The action for opening the string editor
    actions.put(Actions.EDIT_STRINGS, (BaseAction) () -> {
        if (stringDialog == null) {
            StringDialog form = new StringDialog(frame, BasePanel.this, bibDatabaseContext.getDatabase());
            form.setVisible(true);
            stringDialog = form;
        } else {
            stringDialog.setVisible(true);
        }
    });
    actions.put(FindUnlinkedFilesDialog.ACTION_COMMAND, (BaseAction) () -> {
        final FindUnlinkedFilesDialog dialog = new FindUnlinkedFilesDialog(frame, frame, BasePanel.this);
        dialog.setLocationRelativeTo(frame);
        dialog.setVisible(true);
    });
    // The action for auto-generating keys.
    actions.put(Actions.MAKE_KEY, new AbstractWorker() {

        List<BibEntry> entries;

        int numSelected;

        boolean canceled;

        // Run first, in EDT:
        @Override
        public void init() {
            entries = getSelectedEntries();
            numSelected = entries.size();
            if (entries.isEmpty()) {
                // None selected. Inform the user to select entries first.
                JOptionPane.showMessageDialog(frame, Localization.lang("First select the entries you want keys to be generated for."), Localization.lang("Autogenerate BibTeX keys"), JOptionPane.INFORMATION_MESSAGE);
                return;
            }
            frame.block();
            output(formatOutputMessage(Localization.lang("Generating BibTeX key for"), numSelected));
        }

        // Run second, on a different thread:
        @Override
        public void run() {
            // We don't want to generate keys for entries which already have one thus remove the entries
            if (Globals.prefs.getBoolean(JabRefPreferences.AVOID_OVERWRITING_KEY)) {
                entries.removeIf(BibEntry::hasCiteKey);
            // if we're going to override some cite keys warn the user about it
            } else if (Globals.prefs.getBoolean(JabRefPreferences.WARN_BEFORE_OVERWRITING_KEY)) {
                if (entries.parallelStream().anyMatch(BibEntry::hasCiteKey)) {
                    CheckBoxMessage cbm = new CheckBoxMessage(Localization.lang("One or more keys will be overwritten. Continue?"), Localization.lang("Disable this confirmation dialog"), false);
                    final int answer = JOptionPane.showConfirmDialog(frame, cbm, Localization.lang("Overwrite keys"), JOptionPane.YES_NO_OPTION);
                    Globals.prefs.putBoolean(JabRefPreferences.WARN_BEFORE_OVERWRITING_KEY, !cbm.isSelected());
                    // The user doesn't want to overide cite keys
                    if (answer == JOptionPane.NO_OPTION) {
                        canceled = true;
                        return;
                    }
                }
            }
            // generate the new cite keys for each entry
            final NamedCompound ce = new NamedCompound(Localization.lang("Autogenerate BibTeX keys"));
            AbstractBibtexKeyPattern citeKeyPattern = bibDatabaseContext.getMetaData().getCiteKeyPattern(Globals.prefs.getBibtexKeyPatternPreferences().getKeyPattern());
            for (BibEntry entry : entries) {
                String oldCiteKey = entry.getCiteKeyOptional().orElse("");
                BibtexKeyPatternUtil.makeAndSetLabel(citeKeyPattern, bibDatabaseContext.getDatabase(), entry, Globals.prefs.getBibtexKeyPatternPreferences());
                String newCiteKey = entry.getCiteKeyOptional().orElse("");
                if (!oldCiteKey.equals(newCiteKey)) {
                    ce.addEdit(new UndoableKeyChange(entry, oldCiteKey, newCiteKey));
                }
            }
            ce.end();
            // register the undo event only if new cite keys were generated
            if (ce.hasEdits()) {
                getUndoManager().addEdit(ce);
            }
        }

        // Run third, on EDT:
        @Override
        public void update() {
            if (canceled) {
                frame.unblock();
                return;
            }
            markBaseChanged();
            numSelected = entries.size();
            ////////////////////////////////////////////////////////////////////////////////
            for (final BibEntry bibEntry : entries) {
                SwingUtilities.invokeLater(() -> {
                    final int row = mainTable.findEntry(bibEntry);
                    if ((row >= 0) && (mainTable.getSelectedRowCount() < entries.size())) {
                        mainTable.addRowSelectionInterval(row, row);
                    }
                });
            }
            ////////////////////////////////////////////////////////////////////////////////
            output(formatOutputMessage(Localization.lang("Generated BibTeX key for"), numSelected));
            frame.unblock();
        }
    });
    // The action for cleaning up entry.
    actions.put(Actions.CLEANUP, cleanUpAction);
    actions.put(Actions.MERGE_ENTRIES, (BaseAction) () -> new MergeEntriesDialog(BasePanel.this));
    actions.put(Actions.SEARCH, (BaseAction) frame.getGlobalSearchBar()::focus);
    actions.put(Actions.GLOBAL_SEARCH, (BaseAction) frame.getGlobalSearchBar()::performGlobalSearch);
    // The action for copying the selected entry's key.
    actions.put(Actions.COPY_KEY, (BaseAction) () -> copyKey());
    // The action for copying the selected entry's title.
    actions.put(Actions.COPY_TITLE, (BaseAction) () -> copyTitle());
    // The action for copying a cite for the selected entry.
    actions.put(Actions.COPY_CITE_KEY, (BaseAction) () -> copyCiteKey());
    // The action for copying the BibTeX key and the title for the first selected entry
    actions.put(Actions.COPY_KEY_AND_TITLE, (BaseAction) () -> copyKeyAndTitle());
    actions.put(Actions.COPY_CITATION_ASCII_DOC, (BaseAction) () -> copyCitationToClipboard(CitationStyleOutputFormat.ASCII_DOC));
    actions.put(Actions.COPY_CITATION_XSLFO, (BaseAction) () -> copyCitationToClipboard(CitationStyleOutputFormat.XSL_FO));
    actions.put(Actions.COPY_CITATION_HTML, (BaseAction) () -> copyCitationToClipboard(CitationStyleOutputFormat.HTML));
    actions.put(Actions.COPY_CITATION_RTF, (BaseAction) () -> copyCitationToClipboard(CitationStyleOutputFormat.RTF));
    actions.put(Actions.COPY_CITATION_TEXT, (BaseAction) () -> copyCitationToClipboard(CitationStyleOutputFormat.TEXT));
    // The action for copying the BibTeX keys as hyperlinks to the urls of the selected entries
    actions.put(Actions.COPY_KEY_AND_LINK, new CopyBibTeXKeyAndLinkAction(mainTable));
    actions.put(Actions.MERGE_DATABASE, new AppendDatabaseAction(frame, this));
    actions.put(Actions.ADD_FILE_LINK, new AttachFileAction(this));
    actions.put(Actions.OPEN_EXTERNAL_FILE, (BaseAction) () -> openExternalFile());
    actions.put(Actions.OPEN_FOLDER, (BaseAction) () -> JabRefExecutorService.INSTANCE.execute(() -> {
        final List<Path> files = FileUtil.getListOfLinkedFiles(mainTable.getSelectedEntries(), bibDatabaseContext.getFileDirectoriesAsPaths(Globals.prefs.getFileDirectoryPreferences()));
        for (final Path f : files) {
            try {
                JabRefDesktop.openFolderAndSelectFile(f.toAbsolutePath());
            } catch (IOException e) {
                LOGGER.info("Could not open folder", e);
            }
        }
    }));
    actions.put(Actions.OPEN_CONSOLE, (BaseAction) () -> JabRefDesktop.openConsole(frame.getCurrentBasePanel().getBibDatabaseContext().getDatabaseFile().orElse(null)));
    actions.put(Actions.PULL_CHANGES_FROM_SHARED_DATABASE, (BaseAction) () -> {
        DBMSSynchronizer dbmsSynchronizer = frame.getCurrentBasePanel().getBibDatabaseContext().getDBMSSynchronizer();
        dbmsSynchronizer.pullChanges();
    });
    actions.put(Actions.OPEN_URL, new OpenURLAction());
    actions.put(Actions.MERGE_WITH_FETCHED_ENTRY, new MergeWithFetchedEntryAction(this));
    actions.put(Actions.REPLACE_ALL, (BaseAction) () -> {
        final ReplaceStringDialog rsd = new ReplaceStringDialog(frame);
        rsd.setVisible(true);
        if (!rsd.okPressed()) {
            return;
        }
        int counter = 0;
        final NamedCompound ce = new NamedCompound(Localization.lang("Replace string"));
        if (rsd.selOnly()) {
            for (BibEntry be : mainTable.getSelectedEntries()) {
                counter += rsd.replace(be, ce);
            }
        } else {
            for (BibEntry entry : bibDatabaseContext.getDatabase().getEntries()) {
                counter += rsd.replace(entry, ce);
            }
        }
        output(Localization.lang("Replaced") + ' ' + counter + ' ' + (counter == 1 ? Localization.lang("occurrence") : Localization.lang("occurrences")) + '.');
        if (counter > 0) {
            ce.end();
            getUndoManager().addEdit(ce);
            markBaseChanged();
        }
    });
    actions.put(Actions.DUPLI_CHECK, (BaseAction) () -> JabRefExecutorService.INSTANCE.execute(new DuplicateSearch(BasePanel.this)));
    actions.put(Actions.PLAIN_TEXT_IMPORT, (BaseAction) () -> {
        EntryTypeDialog etd = new EntryTypeDialog(frame);
        etd.setLocationRelativeTo(BasePanel.this);
        etd.setVisible(true);
        EntryType tp = etd.getChoice();
        if (tp == null) {
            return;
        }
        BibEntry bibEntry = new BibEntry(tp.getName());
        TextInputDialog tidialog = new TextInputDialog(frame, bibEntry);
        tidialog.setLocationRelativeTo(BasePanel.this);
        tidialog.setVisible(true);
        if (tidialog.okPressed()) {
            UpdateField.setAutomaticFields(Collections.singletonList(bibEntry), false, false, Globals.prefs.getUpdateFieldPreferences());
            insertEntry(bibEntry);
        }
    });
    actions.put(Actions.MARK_ENTRIES, new MarkEntriesAction(frame, 0));
    actions.put(Actions.UNMARK_ENTRIES, (BaseAction) () -> {
        try {
            List<BibEntry> bes = mainTable.getSelectedEntries();
            if (bes.isEmpty()) {
                output(Localization.lang("This operation requires one or more entries to be selected."));
                return;
            }
            NamedCompound ce = new NamedCompound(Localization.lang("Unmark entries"));
            for (BibEntry be : bes) {
                EntryMarker.unmarkEntry(be, false, bibDatabaseContext.getDatabase(), ce);
            }
            ce.end();
            getUndoManager().addEdit(ce);
            markBaseChanged();
            String outputStr;
            if (bes.size() == 1) {
                outputStr = Localization.lang("Unmarked selected entry");
            } else {
                outputStr = Localization.lang("Unmarked all %0 selected entries", Integer.toString(bes.size()));
            }
            output(outputStr);
        } catch (Throwable ex) {
            LOGGER.warn("Could not unmark", ex);
        }
    });
    actions.put(Actions.UNMARK_ALL, (BaseAction) () -> {
        NamedCompound ce = new NamedCompound(Localization.lang("Unmark all"));
        for (BibEntry be : bibDatabaseContext.getDatabase().getEntries()) {
            EntryMarker.unmarkEntry(be, false, bibDatabaseContext.getDatabase(), ce);
        }
        ce.end();
        getUndoManager().addEdit(ce);
        markBaseChanged();
        output(Localization.lang("Unmarked all entries"));
    });
    // Note that we can't put the number of entries that have been reverted into the undoText as the concrete number cannot be injected
    actions.put(new SpecialFieldValueViewModel(SpecialField.RELEVANCE.getValues().get(0)).getActionName(), new SpecialFieldViewModel(SpecialField.RELEVANCE).getSpecialFieldAction(SpecialField.RELEVANCE.getValues().get(0), frame));
    actions.put(new SpecialFieldValueViewModel(SpecialField.QUALITY.getValues().get(0)).getActionName(), new SpecialFieldViewModel(SpecialField.QUALITY).getSpecialFieldAction(SpecialField.QUALITY.getValues().get(0), frame));
    actions.put(new SpecialFieldValueViewModel(SpecialField.PRINTED.getValues().get(0)).getActionName(), new SpecialFieldViewModel(SpecialField.PRINTED).getSpecialFieldAction(SpecialField.PRINTED.getValues().get(0), frame));
    for (SpecialFieldValue prio : SpecialField.PRIORITY.getValues()) {
        actions.put(new SpecialFieldValueViewModel(prio).getActionName(), new SpecialFieldViewModel(SpecialField.PRIORITY).getSpecialFieldAction(prio, this.frame));
    }
    for (SpecialFieldValue rank : SpecialField.RANKING.getValues()) {
        actions.put(new SpecialFieldValueViewModel(rank).getActionName(), new SpecialFieldViewModel(SpecialField.RANKING).getSpecialFieldAction(rank, this.frame));
    }
    for (SpecialFieldValue status : SpecialField.READ_STATUS.getValues()) {
        actions.put(new SpecialFieldValueViewModel(status).getActionName(), new SpecialFieldViewModel(SpecialField.READ_STATUS).getSpecialFieldAction(status, this.frame));
    }
    actions.put(Actions.TOGGLE_PREVIEW, (BaseAction) () -> {
        PreviewPreferences previewPreferences = Globals.prefs.getPreviewPreferences();
        boolean enabled = !previewPreferences.isPreviewPanelEnabled();
        PreviewPreferences newPreviewPreferences = previewPreferences.getBuilder().withPreviewPanelEnabled(enabled).build();
        Globals.prefs.storePreviewPreferences(newPreviewPreferences);
        setPreviewActiveBasePanels(enabled);
        frame.setPreviewToggle(enabled);
    });
    actions.put(Actions.NEXT_PREVIEW_STYLE, (BaseAction) selectionListener::nextPreviewStyle);
    actions.put(Actions.PREVIOUS_PREVIEW_STYLE, (BaseAction) selectionListener::previousPreviewStyle);
    actions.put(Actions.MANAGE_SELECTORS, (BaseAction) () -> {
        ContentSelectorDialog csd = new ContentSelectorDialog(frame, frame, BasePanel.this, false, null);
        csd.setLocationRelativeTo(frame);
        csd.setVisible(true);
    });
    actions.put(Actions.EXPORT_TO_CLIPBOARD, new ExportToClipboardAction(frame));
    actions.put(Actions.SEND_AS_EMAIL, new SendAsEMailAction(frame));
    actions.put(Actions.WRITE_XMP, new WriteXMPAction(this));
    actions.put(Actions.ABBREVIATE_ISO, new AbbreviateAction(this, true));
    actions.put(Actions.ABBREVIATE_MEDLINE, new AbbreviateAction(this, false));
    actions.put(Actions.UNABBREVIATE, new UnabbreviateAction(this));
    actions.put(Actions.AUTO_SET_FILE, new SynchronizeFileField(this));
    actions.put(Actions.BACK, (BaseAction) BasePanel.this::back);
    actions.put(Actions.FORWARD, (BaseAction) BasePanel.this::forward);
    actions.put(Actions.RESOLVE_DUPLICATE_KEYS, new SearchFixDuplicateLabels(this));
    actions.put(Actions.ADD_TO_GROUP, new GroupAddRemoveDialog(this, true, false));
    actions.put(Actions.REMOVE_FROM_GROUP, new GroupAddRemoveDialog(this, false, false));
    actions.put(Actions.MOVE_TO_GROUP, new GroupAddRemoveDialog(this, true, true));
    actions.put(Actions.DOWNLOAD_FULL_TEXT, new FindFullTextAction(this));
}
Also used : DBMSSynchronizer(org.jabref.shared.DBMSSynchronizer) CheckBoxMessage(org.jabref.gui.util.component.CheckBoxMessage) AbstractBibtexKeyPattern(org.jabref.model.bibtexkeypattern.AbstractBibtexKeyPattern) UnabbreviateAction(org.jabref.gui.journals.UnabbreviateAction) NamedCompound(org.jabref.gui.undo.NamedCompound) ArrayList(java.util.ArrayList) List(java.util.List) PreviewPreferences(org.jabref.preferences.PreviewPreferences) FindFullTextAction(org.jabref.gui.externalfiles.FindFullTextAction) SpecialFieldValueViewModel(org.jabref.gui.specialfields.SpecialFieldValueViewModel) AbbreviateAction(org.jabref.gui.journals.AbbreviateAction) CleanupAction(org.jabref.gui.actions.CleanupAction) UndoableKeyChange(org.jabref.gui.undo.UndoableKeyChange) MergeEntriesDialog(org.jabref.gui.mergeentries.MergeEntriesDialog) MergeWithFetchedEntryAction(org.jabref.gui.mergeentries.MergeWithFetchedEntryAction) SynchronizeFileField(org.jabref.gui.externalfiles.SynchronizeFileField) ContentSelectorDialog(org.jabref.gui.contentselector.ContentSelectorDialog) AppendDatabaseAction(org.jabref.gui.importer.actions.AppendDatabaseAction) WriteXMPAction(org.jabref.gui.externalfiles.WriteXMPAction) SearchFixDuplicateLabels(org.jabref.gui.bibtexkeypattern.SearchFixDuplicateLabels) SaveDatabaseAction(org.jabref.gui.exporter.SaveDatabaseAction) MarkEntriesAction(org.jabref.gui.worker.MarkEntriesAction) AttachFileAction(org.jabref.gui.filelist.AttachFileAction) ExportToClipboardAction(org.jabref.gui.exporter.ExportToClipboardAction) AbstractWorker(org.jabref.gui.worker.AbstractWorker) Path(java.nio.file.Path) BibEntry(org.jabref.model.entry.BibEntry) GroupAddRemoveDialog(org.jabref.gui.groups.GroupAddRemoveDialog) BaseAction(org.jabref.gui.actions.BaseAction) IOException(java.io.IOException) SendAsEMailAction(org.jabref.gui.worker.SendAsEMailAction) EntryType(org.jabref.model.entry.EntryType) SpecialFieldViewModel(org.jabref.gui.specialfields.SpecialFieldViewModel) CopyBibTeXKeyAndLinkAction(org.jabref.gui.actions.CopyBibTeXKeyAndLinkAction) TextInputDialog(org.jabref.gui.plaintextimport.TextInputDialog) SpecialFieldValue(org.jabref.model.entry.specialfields.SpecialFieldValue)

Example 2 with EntryType

use of org.jabref.model.entry.EntryType in project jabref by JabRef.

the class BibtexKeyPatternPanel method buildGUI.

private void buildGUI() {
    JPanel pan = new JPanel();
    JScrollPane sp = new JScrollPane(pan);
    sp.setPreferredSize(new Dimension(100, 100));
    sp.setBorder(BorderFactory.createEmptyBorder());
    pan.setLayout(gbl);
    setLayout(gbl);
    // The header - can be removed
    JLabel lblEntryType = new JLabel(Localization.lang("Entry type"));
    Font f = new Font("plain", Font.BOLD, 12);
    lblEntryType.setFont(f);
    con.gridx = 0;
    con.gridy = 0;
    con.gridwidth = 1;
    con.gridheight = 1;
    con.fill = GridBagConstraints.VERTICAL;
    con.anchor = GridBagConstraints.WEST;
    con.insets = new Insets(5, 5, 10, 0);
    gbl.setConstraints(lblEntryType, con);
    pan.add(lblEntryType);
    JLabel lblKeyPattern = new JLabel(Localization.lang("Key pattern"));
    lblKeyPattern.setFont(f);
    con.gridx = 1;
    con.gridy = 0;
    con.gridheight = 1;
    con.fill = GridBagConstraints.HORIZONTAL;
    con.anchor = GridBagConstraints.WEST;
    con.insets = new Insets(5, 5, 10, 5);
    gbl.setConstraints(lblKeyPattern, con);
    pan.add(lblKeyPattern);
    con.gridy = 1;
    con.gridx = 0;
    JLabel lab = new JLabel(Localization.lang("Default pattern"));
    gbl.setConstraints(lab, con);
    pan.add(lab);
    con.gridx = 1;
    gbl.setConstraints(defaultPat, con);
    pan.add(defaultPat);
    con.insets = new Insets(5, 5, 10, 5);
    JButton btnDefault = new JButton(Localization.lang("Default"));
    btnDefault.addActionListener(e -> defaultPat.setText((String) Globals.prefs.defaults.get(JabRefPreferences.DEFAULT_BIBTEX_KEY_PATTERN)));
    con.gridx = 2;
    int y = 2;
    gbl.setConstraints(btnDefault, con);
    pan.add(btnDefault);
    BibDatabaseMode mode;
    // check mode of currently used DB
    if (panel != null) {
        mode = panel.getBibDatabaseContext().getMode();
    } else {
        // use preferences value if no DB is open
        mode = Globals.prefs.getDefaultBibDatabaseMode();
    }
    for (EntryType type : EntryTypes.getAllValues(mode)) {
        textFields.put(type.getName().toLowerCase(Locale.ROOT), addEntryType(pan, type, y));
        y++;
    }
    con.fill = GridBagConstraints.BOTH;
    con.gridx = 0;
    con.gridy = 1;
    con.gridwidth = 3;
    con.weightx = 1;
    con.weighty = 1;
    gbl.setConstraints(sp, con);
    add(sp);
    // A help button
    con.gridwidth = 1;
    con.gridx = 1;
    con.gridy = 2;
    con.fill = GridBagConstraints.HORIZONTAL;
    //
    con.weightx = 0;
    con.weighty = 0;
    con.anchor = GridBagConstraints.SOUTHEAST;
    con.insets = new Insets(0, 5, 0, 5);
    JButton hlb = new JButton(IconTheme.JabRefIcon.HELP.getSmallIcon());
    hlb.setToolTipText(Localization.lang("Help on key patterns"));
    gbl.setConstraints(hlb, con);
    add(hlb);
    hlb.addActionListener(help);
    // And finally a button to reset everything
    JButton btnDefaultAll = new JButton(Localization.lang("Reset all"));
    con.gridx = 2;
    con.gridy = 2;
    con.weightx = 1;
    con.weighty = 0;
    con.anchor = GridBagConstraints.SOUTHEAST;
    con.insets = new Insets(20, 5, 0, 5);
    gbl.setConstraints(btnDefaultAll, con);
    btnDefaultAll.addActionListener(e -> {
        for (JTextField field : textFields.values()) {
            field.setText("");
        }
        defaultPat.setText((String) Globals.prefs.defaults.get(JabRefPreferences.DEFAULT_BIBTEX_KEY_PATTERN));
    });
    add(btnDefaultAll);
}
Also used : JScrollPane(javax.swing.JScrollPane) JPanel(javax.swing.JPanel) Insets(java.awt.Insets) EntryType(org.jabref.model.entry.EntryType) BibDatabaseMode(org.jabref.model.database.BibDatabaseMode) JButton(javax.swing.JButton) JLabel(javax.swing.JLabel) Dimension(java.awt.Dimension) JTextField(javax.swing.JTextField) Font(java.awt.Font)

Example 3 with EntryType

use of org.jabref.model.entry.EntryType in project jabref by JabRef.

the class NewEntryAction method actionPerformed.

@Override
public void actionPerformed(ActionEvent e) {
    String thisType = type;
    if (thisType == null) {
        EntryTypeDialog etd = new EntryTypeDialog(jabRefFrame);
        etd.setLocationRelativeTo(jabRefFrame);
        etd.setVisible(true);
        EntryType tp = etd.getChoice();
        if (tp == null) {
            return;
        }
        thisType = tp.getName();
    }
    if (jabRefFrame.getBasePanelCount() > 0) {
        jabRefFrame.getCurrentBasePanel().newEntry(EntryTypes.getType(thisType, jabRefFrame.getCurrentBasePanel().getBibDatabaseContext().getMode()).get());
    } else {
        LOGGER.info("Action 'New entry' must be disabled when no database is open.");
    }
}
Also used : EntryType(org.jabref.model.entry.EntryType) EntryTypeDialog(org.jabref.gui.EntryTypeDialog)

Example 4 with EntryType

use of org.jabref.model.entry.EntryType in project jabref by JabRef.

the class BasePanel method newEntry.

/**
     * This method is called from JabRefFrame when the user wants to create a new entry. If the argument is null, the
     * user is prompted for an entry type.
     *
     * @param type The type of the entry to create.
     * @return The newly created BibEntry or null the operation was canceled by the user.
     */
public BibEntry newEntry(EntryType type) {
    EntryType actualType = type;
    if (actualType == null) {
        // Find out what type is wanted.
        final EntryTypeDialog etd = new EntryTypeDialog(frame);
        // We want to center the dialog, to make it look nicer.
        etd.setLocationRelativeTo(frame);
        etd.setVisible(true);
        actualType = etd.getChoice();
    }
    if (actualType != null) {
        // Only if the dialog was not canceled.
        final BibEntry be = new BibEntry(actualType.getName());
        try {
            bibDatabaseContext.getDatabase().insertEntry(be);
            // Set owner/timestamp if options are enabled:
            List<BibEntry> list = new ArrayList<>();
            list.add(be);
            UpdateField.setAutomaticFields(list, true, true, Globals.prefs.getUpdateFieldPreferences());
            // Create an UndoableInsertEntry object.
            getUndoManager().addEdit(new UndoableInsertEntry(bibDatabaseContext.getDatabase(), be, BasePanel.this));
            output(Localization.lang("Added new '%0' entry.", actualType.getName().toLowerCase(Locale.ROOT)));
            // and adjustment of the splitter.
            if (mode != BasePanelMode.SHOWING_EDITOR) {
                mode = BasePanelMode.WILL_SHOW_EDITOR;
            }
            highlightEntry(be);
            // The database just changed.
            markBaseChanged();
            final EntryEditor entryEditor = getEntryEditor(be);
            this.showEntryEditor(entryEditor);
            entryEditor.requestFocus();
            return be;
        } catch (KeyCollisionException ex) {
            LOGGER.info(ex.getMessage(), ex);
        }
    }
    return null;
}
Also used : KeyCollisionException(org.jabref.model.database.KeyCollisionException) BibEntry(org.jabref.model.entry.BibEntry) EntryEditor(org.jabref.gui.entryeditor.EntryEditor) EntryType(org.jabref.model.entry.EntryType) ArrayList(java.util.ArrayList) UndoableInsertEntry(org.jabref.gui.undo.UndoableInsertEntry)

Example 5 with EntryType

use of org.jabref.model.entry.EntryType in project jabref by JabRef.

the class EntryCustomizationDialog method applyChanges.

private void applyChanges() {
    valueChanged(new ListSelectionEvent(new JList<>(), 0, 0, false));
    List<String> actuallyChangedTypes = new ArrayList<>();
    // Iterate over our map of required fields, and list those types if necessary:
    List<String> types = typeComp.getFields();
    for (Map.Entry<String, List<String>> stringListEntry : reqLists.entrySet()) {
        if (!types.contains(stringListEntry.getKey())) {
            continue;
        }
        List<String> requiredFieldsList = stringListEntry.getValue();
        List<String> optionalFieldsList = optLists.get(stringListEntry.getKey());
        List<String> secondaryOptionalFieldsLists = opt2Lists.get(stringListEntry.getKey());
        if (secondaryOptionalFieldsLists == null) {
            secondaryOptionalFieldsLists = new ArrayList<>(0);
        }
        // If this type is already existing, check if any changes have
        // been made
        boolean changesMade = true;
        if (defaulted.contains(stringListEntry.getKey())) {
            // This type should be reverted to its default setup.
            EntryTypes.removeType(stringListEntry.getKey(), bibDatabaseMode);
            actuallyChangedTypes.add(stringListEntry.getKey().toLowerCase(Locale.ENGLISH));
            defaulted.remove(stringListEntry.getKey());
            continue;
        }
        Optional<EntryType> oldType = EntryTypes.getType(stringListEntry.getKey(), bibDatabaseMode);
        if (oldType.isPresent()) {
            List<String> oldRequiredFieldsList = oldType.get().getRequiredFieldsFlat();
            List<String> oldOptionalFieldsList = oldType.get().getOptionalFields();
            if (biblatexMode) {
                List<String> oldPrimaryOptionalFieldsLists = oldType.get().getPrimaryOptionalFields();
                List<String> oldSecondaryOptionalFieldsList = oldType.get().getSecondaryOptionalFields();
                if (equalLists(oldRequiredFieldsList, requiredFieldsList) && equalLists(oldPrimaryOptionalFieldsLists, optionalFieldsList) && equalLists(oldSecondaryOptionalFieldsList, secondaryOptionalFieldsLists)) {
                    changesMade = false;
                }
            } else if (equalLists(oldRequiredFieldsList, requiredFieldsList) && equalLists(oldOptionalFieldsList, optionalFieldsList)) {
                changesMade = false;
            }
        }
        if (changesMade) {
            CustomEntryType customType = biblatexMode ? new CustomEntryType(StringUtil.capitalizeFirst(stringListEntry.getKey()), requiredFieldsList, optionalFieldsList, secondaryOptionalFieldsLists) : new CustomEntryType(StringUtil.capitalizeFirst(stringListEntry.getKey()), requiredFieldsList, optionalFieldsList);
            EntryTypes.addOrModifyCustomEntryType(customType, bibDatabaseMode);
            actuallyChangedTypes.add(customType.getName().toLowerCase(Locale.ENGLISH));
        }
    }
    // update all affected entries if something has been changed
    if (!actuallyChangedTypes.isEmpty()) {
        updateEntriesForChangedTypes(actuallyChangedTypes);
    }
    Set<String> typesToRemove = new HashSet<>();
    for (String existingType : EntryTypes.getAllTypes(bibDatabaseMode)) {
        if (!types.contains(existingType)) {
            typesToRemove.add(existingType);
        }
    }
    // Remove those that should be removed:
    if (!typesToRemove.isEmpty()) {
        for (String typeToRemove : typesToRemove) {
            deleteType(typeToRemove);
        }
    }
    updateTables();
    CustomEntryTypesManager.saveCustomEntryTypes(Globals.prefs);
}
Also used : ListSelectionEvent(javax.swing.event.ListSelectionEvent) ArrayList(java.util.ArrayList) CustomEntryType(org.jabref.model.entry.CustomEntryType) CustomEntryType(org.jabref.model.entry.CustomEntryType) EntryType(org.jabref.model.entry.EntryType) ArrayList(java.util.ArrayList) JList(javax.swing.JList) List(java.util.List) HashMap(java.util.HashMap) Map(java.util.Map) ActionMap(javax.swing.ActionMap) InputMap(javax.swing.InputMap) JList(javax.swing.JList) HashSet(java.util.HashSet)

Aggregations

EntryType (org.jabref.model.entry.EntryType)22 ArrayList (java.util.ArrayList)8 BibEntry (org.jabref.model.entry.BibEntry)8 JPanel (javax.swing.JPanel)6 IOException (java.io.IOException)5 CustomEntryType (org.jabref.model.entry.CustomEntryType)5 Font (java.awt.Font)4 ParserResult (org.jabref.logic.importer.ParserResult)4 Insets (java.awt.Insets)3 JLabel (javax.swing.JLabel)3 StringReader (java.io.StringReader)2 HashMap (java.util.HashMap)2 HashSet (java.util.HashSet)2 List (java.util.List)2 Map (java.util.Map)2 ChangeEvent (javax.swing.event.ChangeEvent)2 ChangeListener (javax.swing.event.ChangeListener)2 EntryTypeDialog (org.jabref.gui.EntryTypeDialog)2 UndoableInsertEntry (org.jabref.gui.undo.UndoableInsertEntry)2 TypedBibEntry (org.jabref.logic.TypedBibEntry)2