Skip to content

Commit

Permalink
Extract old Bibtex key generation action (#4056)
Browse files Browse the repository at this point in the history
* Extract old Bibtex key generation action

* Add Todos

* Imports

* Merge properly

* Unify key generation code

* Hide text from icon button

* Fix build

Co-authored-by: Tobias Diez <[email protected]>
  • Loading branch information
stefan-kolb and tobiasdiez committed Jul 2, 2018
1 parent cf9fbb0 commit b411cfb
Show file tree
Hide file tree
Showing 20 changed files with 268 additions and 156 deletions.
76 changes: 2 additions & 74 deletions src/main/java/org/jabref/gui/BasePanel.java
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@
import org.jabref.gui.actions.BaseAction;
import org.jabref.gui.actions.CleanupAction;
import org.jabref.gui.actions.CopyBibTeXKeyAndLinkAction;
import org.jabref.gui.actions.GenerateBibtexKeyAction;
import org.jabref.gui.autocompleter.AutoCompletePreferences;
import org.jabref.gui.autocompleter.AutoCompleteUpdater;
import org.jabref.gui.autocompleter.PersonNameSuggestionProvider;
Expand Down Expand Up @@ -135,7 +136,6 @@
import org.slf4j.LoggerFactory;

public class BasePanel extends StackPane implements ClipboardOwner {

private static final Logger LOGGER = LoggerFactory.getLogger(BasePanel.class);

private final BibDatabaseContext bibDatabaseContext;
Expand Down Expand Up @@ -360,79 +360,7 @@ private void setupActions() {
});

// 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.
dialogService.showWarningDialogAndWait(Localization.lang("Autogenerate BibTeX keys"),
Localization.lang("First select the entries you want keys to be generated for."));
return;
}
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)) {

boolean overwriteKeysPressed = dialogService.showConfirmationDialogWithOptOutAndWait(
Localization.lang("Overwrite keys"),
Localization.lang("One or more keys will be overwritten. Continue?"),
Localization.lang("Overwrite keys"),
Localization.lang("Cancel"),
Localization.lang("Disable this confirmation dialog"),
optOut -> Globals.prefs.putBoolean(JabRefPreferences.WARN_BEFORE_OVERWRITING_KEY, !optOut));

// The user doesn't want to overide cite keys
if (!overwriteKeysPressed) {
canceled = true;
return;
}
}
}

// generate the new cite keys for each entry
final NamedCompound ce = new NamedCompound(Localization.lang("Autogenerate BibTeX keys"));
BibtexKeyGenerator keyGenerator = new BibtexKeyGenerator(bibDatabaseContext, Globals.prefs.getBibtexKeyPatternPreferences());
for (BibEntry entry : entries) {
Optional<FieldChange> change = keyGenerator.generateAndSetKey(entry);
change.ifPresent(fieldChange -> ce.addEdit(new UndoableKeyChange(fieldChange)));
}
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) {
return;
}
markBaseChanged();
numSelected = entries.size();
output(formatOutputMessage(Localization.lang("Generated BibTeX key for"), numSelected));
}
});
actions.put(Actions.MAKE_KEY, new GenerateBibtexKeyAction(this, frame.getDialogService()));

// The action for cleaning up entry.
actions.put(Actions.CLEANUP, cleanUpAction);
Expand Down
2 changes: 1 addition & 1 deletion src/main/java/org/jabref/gui/BasePanelPreferences.java
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ public static BasePanelPreferences from(JabRefPreferences preferences) {
BasePanelPreferences basePanelPreferences = new BasePanelPreferences(
preferences.getMainTablePreferences(),
preferences.getAutoCompletePreferences(),
EntryEditorPreferences.from(preferences),
preferences.getEntryEditorPreferences(),
Globals.getKeyPrefs(),
preferences.getPreviewPreferences(),
preferences.getDouble(JabRefPreferences.ENTRY_EDITOR_HEIGHT));
Expand Down
2 changes: 1 addition & 1 deletion src/main/java/org/jabref/gui/JabRefFrame.java
Original file line number Diff line number Diff line change
Expand Up @@ -841,7 +841,7 @@ private MenuBar createMenu() {
factory.createMenuItem(StandardActions.RESOLVE_DUPLICATE_KEYS, new OldDatabaseCommandWrapper(Actions.RESOLVE_DUPLICATE_KEYS, this, Globals.stateManager)),
factory.createMenuItem(StandardActions.CHECK_INTEGRITY, new IntegrityCheckAction(this)),
factory.createMenuItem(StandardActions.CLEANUP_ENTRIES, new OldDatabaseCommandWrapper(Actions.CLEANUP, this, Globals.stateManager)),
factory.createMenuItem(StandardActions.GENERATE_CITE_KEY, new OldDatabaseCommandWrapper(Actions.MAKE_KEY, this, Globals.stateManager)),
factory.createMenuItem(StandardActions.GENERATE_CITE_KEYS, new OldDatabaseCommandWrapper(Actions.MAKE_KEY, this, Globals.stateManager)),

new SeparatorMenuItem(),

Expand Down
23 changes: 23 additions & 0 deletions src/main/java/org/jabref/gui/actions/ActionFactory.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@

import java.util.Objects;

import javafx.scene.Node;
import javafx.scene.control.Button;
import javafx.scene.control.ButtonBase;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuItem;

Expand Down Expand Up @@ -57,6 +59,7 @@ public Menu createSubMenu(Action action, MenuItem... children) {

public Button createIconButton(Action action, Command command) {
Button button = ActionUtils.createButton(new JabRefAction(action, command, keyBindingRepository), ActionUtils.ActionTextBehavior.HIDE);

button.getStyleClass().setAll("flatButton");

// For some reason the graphic is not set correctly, so let's fix this
Expand All @@ -65,4 +68,24 @@ public Button createIconButton(Action action, Command command) {

return button;
}

public ButtonBase configureIconButton(Action action, Command command, ButtonBase button) {
ActionUtils.configureButton(
new JabRefAction(action, command, keyBindingRepository),
button,
ActionUtils.ActionTextBehavior.HIDE);

button.getStyleClass().add("flatButton");

// For some reason the graphic is not set correctly, so let's fix this
button.graphicProperty().unbind();
action.getIcon().ifPresent(icon -> {
// ToDO: Find a way to reuse JabRefIconView
Node graphicNode = icon.getGraphicNode();
graphicNode.setStyle(String.format("-fx-font-family: %s; -fx-font-size: %s;", icon.fontFamily(), "1em"));
button.setGraphic(graphicNode);
});

return button;
}
}
98 changes: 98 additions & 0 deletions src/main/java/org/jabref/gui/actions/GenerateBibtexKeyAction.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
package org.jabref.gui.actions;

import java.util.List;

import org.jabref.Globals;
import org.jabref.gui.BasePanel;
import org.jabref.gui.DialogService;
import org.jabref.gui.undo.NamedCompound;
import org.jabref.gui.undo.UndoableKeyChange;
import org.jabref.gui.worker.AbstractWorker;
import org.jabref.logic.bibtexkeypattern.BibtexKeyGenerator;
import org.jabref.logic.l10n.Localization;
import org.jabref.model.entry.BibEntry;
import org.jabref.preferences.JabRefPreferences;

public class GenerateBibtexKeyAction extends AbstractWorker {
private final DialogService dialogService;
private BasePanel basePanel;
private List<BibEntry> entries;
private boolean canceled;

public GenerateBibtexKeyAction(BasePanel basePanel, DialogService dialogService) {
this.basePanel = basePanel;
this.dialogService = dialogService;
}

@Override
public void init() {
entries = basePanel.getSelectedEntries();

if (entries.isEmpty()) {
dialogService.showWarningDialogAndWait(Localization.lang("Autogenerate BibTeX keys"),
Localization.lang("First select the entries you want keys to be generated for."));
return;
}
basePanel.output(formatOutputMessage(Localization.lang("Generating BibTeX key for"), entries.size()));
}

public static boolean confirmOverwriteKeys(DialogService dialogService) {
if (Globals.prefs.getBoolean(JabRefPreferences.WARN_BEFORE_OVERWRITING_KEY)) {
return dialogService.showConfirmationDialogWithOptOutAndWait(
Localization.lang("Overwrite keys"),
Localization.lang("One or more keys will be overwritten. Continue?"),
Localization.lang("Overwrite keys"),
Localization.lang("Cancel"),
Localization.lang("Disable this confirmation dialog"),
optOut -> Globals.prefs.putBoolean(JabRefPreferences.WARN_BEFORE_OVERWRITING_KEY, !optOut));
} else {
// Always overwrite keys by default
return true;
}
}

@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 (entries.parallelStream().anyMatch(BibEntry::hasCiteKey)) {
boolean overwriteKeys = confirmOverwriteKeys(dialogService);

// The user doesn't want to override cite keys
if (!overwriteKeys) {
canceled = true;
return;
}
}

// generate the new cite keys for each entry
final NamedCompound compound = new NamedCompound(Localization.lang("Autogenerate BibTeX keys"));
BibtexKeyGenerator keyGenerator = new BibtexKeyGenerator(basePanel.getBibDatabaseContext(), Globals.prefs.getBibtexKeyPatternPreferences());
for (BibEntry entry : entries) {
keyGenerator.generateAndSetKey(entry)
.ifPresent(fieldChange -> compound.addEdit(new UndoableKeyChange(fieldChange)));
}
compound.end();

// register the undo event only if new cite keys were generated
if (compound.hasEdits()) {
basePanel.getUndoManager().addEdit(compound);
}
}

@Override
public void update() {
if (canceled) {
return;
}
basePanel.markBaseChanged();
basePanel.output(formatOutputMessage(Localization.lang("Generated BibTeX key for"), entries.size()));
}

private String formatOutputMessage(String start, int count) {
return String.format("%s %d %s.", start, count,
(count > 1 ? Localization.lang("entries") : Localization.lang("entry")));
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
package org.jabref.gui.actions;

import javax.swing.undo.UndoManager;

import org.jabref.gui.DialogService;
import org.jabref.gui.entryeditor.EntryEditorPreferences;
import org.jabref.gui.undo.UndoableKeyChange;
import org.jabref.logic.bibtexkeypattern.BibtexKeyGenerator;
import org.jabref.model.database.BibDatabaseContext;
import org.jabref.model.entry.BibEntry;

public class GenerateBibtexKeySingleAction extends SimpleCommand {

private DialogService dialogService;
private BibDatabaseContext databaseContext;
private EntryEditorPreferences preferences;
private BibEntry entry;
private UndoManager undoManager;

public GenerateBibtexKeySingleAction(BibEntry entry, BibDatabaseContext databaseContext, DialogService dialogService, EntryEditorPreferences preferences, UndoManager undoManager) {
this.entry = entry;
this.databaseContext = databaseContext;
this.dialogService = dialogService;
this.preferences = preferences;
this.undoManager = undoManager;

if (preferences.avoidOverwritingCiteKey()) {
// Only make command executable if cite key is empty
this.executable.bind(entry.getCiteKeyBinding().isNull());
}
}

@Override
public void execute() {
if (!entry.hasCiteKey() || GenerateBibtexKeyAction.confirmOverwriteKeys(dialogService)) {
new BibtexKeyGenerator(databaseContext, preferences.getBibtexKeyPatternPreferences())
.generateAndSetKey(entry)
.ifPresent(change -> undoManager.addEdit(new UndoableKeyChange(change)));
}
}
}
3 changes: 3 additions & 0 deletions src/main/java/org/jabref/gui/actions/JabRefAction.java
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,13 @@ public JabRefAction(Action action, KeyBindingRepository keyBindingRepository) {

public JabRefAction(Action action, Command command, KeyBindingRepository keyBindingRepository) {
this(action, keyBindingRepository);

setEventHandler(event -> {
command.execute();
trackExecute();
});

disabledProperty().bind(command.executableProperty().not());
}

private void trackExecute() {
Expand Down
5 changes: 2 additions & 3 deletions src/main/java/org/jabref/gui/actions/StandardActions.java
Original file line number Diff line number Diff line change
Expand Up @@ -127,13 +127,12 @@ public enum StandardActions implements Action {
MERGE_ENTRIES(Localization.lang("Merge entries"), IconTheme.JabRefIcons.MERGE_ENTRIES),
RESOLVE_DUPLICATE_KEYS(Localization.lang("Resolve duplicate BibTeX keys"), Localization.lang("Find and remove duplicate BibTeX keys"), KeyBinding.RESOLVE_DUPLICATE_BIBTEX_KEYS),
CHECK_INTEGRITY(Localization.lang("Check integrity"), KeyBinding.CHECK_INTEGRITY),
AUTOGENERATE_KEYS(Localization.lang("Autogenerate BibTeX keys"), IconTheme.JabRefIcons.MAKE_KEY, KeyBinding.AUTOGENERATE_BIBTEX_KEYS),
FIND_UNLINKED_FILES(Localization.lang("Find unlinked files"), Localization.lang("Searches for unlinked PDF files on the file system"), KeyBinding.FIND_UNLINKED_FILES),
AUTO_LINK_FILES(Localization.lang("Automatically set file links"), IconTheme.JabRefIcons.AUTO_FILE_LINK, KeyBinding.AUTOMATICALLY_LINK_FILES),
LOOKUP_DOC_IDENTIFIER(Localization.lang("Look up document identifier")),
LOOKUP_FULLTEXT(Localization.lang("Look up full text documents"), KeyBinding.DOWNLOAD_FULL_TEXT),

GENERATE_CITE_KEY(Localization.lang("Autogenerate BibTeX keys"), IconTheme.JabRefIcons.MAKE_KEY, KeyBinding.AUTOGENERATE_BIBTEX_KEYS),
GENERATE_CITE_KEY(Localization.lang("Generate BibTeX key"), IconTheme.JabRefIcons.MAKE_KEY, KeyBinding.AUTOGENERATE_BIBTEX_KEYS),
GENERATE_CITE_KEYS(Localization.lang("Autogenerate BibTeX keys"), IconTheme.JabRefIcons.MAKE_KEY, KeyBinding.AUTOGENERATE_BIBTEX_KEYS),
DOWNLOAD_FULL_TEXT(Localization.lang("Look up full text documents"), KeyBinding.DOWNLOAD_FULL_TEXT),
CLEANUP_ENTRIES(Localization.lang("Cleanup entries"), IconTheme.JabRefIcons.CLEANUP_ENTRIES, KeyBinding.CLEANUP),
SET_FILE_LINKS(Localization.lang("Automatically set file links"), IconTheme.JabRefIcons.AUTO_FILE_LINK, KeyBinding.AUTOMATICALLY_LINK_FILES),
Expand Down
9 changes: 1 addition & 8 deletions src/main/java/org/jabref/gui/entryeditor/EntryEditor.fxml
Original file line number Diff line number Diff line change
Expand Up @@ -40,14 +40,7 @@
<Tooltip text="%Change entry type"/>
</tooltip>
</Button>
<Button styleClass="flatButton,narrow" onAction="#generateKey">
<graphic>
<JabRefIconView glyphName="MAKE_KEY"/>
</graphic>
<tooltip>
<Tooltip text="%Generate BibTeX key"/>
</tooltip>
</Button>
<Button fx:id="generateCiteKeyButton" styleClass="narrow"/>
<Button fx:id="fetcherButton" styleClass="flatButton,narrow">
<graphic>
<JabRefIconView glyph="REFRESH"/>
Expand Down
Loading

0 comments on commit b411cfb

Please sign in to comment.