Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ Note that this project **does not** adhere to [Semantic Versioning](https://semv
- We fixed an issue where back navigation selected a deleted entry instead of skipping it. [#17353](https://github.com/JabRef/jabref/issues/17353)
- We fixed the linked file tooltip showing the old file name after renaming or moving the file. [#9277](https://github.com/JabRef/jabref/issues/9277)
- We fixed an issue where citationcount, day, and dayfiled columns were sorted alphabetically instead of numerically. [#17459](https://github.com/JabRef/jabref/issues/17459)
- We fixed an issue where the generate citation keys toolbar button stopped working after canceling an overwrite. [#17748](https://github.com/JabRef/jabref/issues/17748)

## [6.0-beta.1] - 2026-09-21

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,9 +31,6 @@ public class GenerateCitationKeyAction extends SimpleCommand {
private final DialogService dialogService;
private final StateManager stateManager;

private List<BibEntry> entries;
private boolean isCanceled;

private final TaskExecutor taskExecutor;
private final CliPreferences preferences;

Expand All @@ -53,28 +50,28 @@ public GenerateCitationKeyAction(Supplier<LibraryTab> tabSupplier,

@Override
public void execute() {
entries = new ArrayList<>(stateManager.getSelectedEntries());
stateManager.getActiveDatabase().ifPresent(this::generateKeysIn);
List<BibEntry> entries = new ArrayList<>(stateManager.getSelectedEntries());
stateManager.getActiveDatabase().ifPresent(databaseContext -> generateKeysIn(databaseContext, entries));
}

private void generateKeysIn(BibDatabaseContext databaseContext) {
private void generateKeysIn(BibDatabaseContext databaseContext, List<BibEntry> entries) {
if (entries.isEmpty()) {
dialogService.showWarningDialogAndWait(Localization.lang("Autogenerate citation keys"),
Localization.lang("First select the entries you want keys to be generated for."));
return;
}
dialogService.notify(formatOutputMessage(Localization.lang("Generating citation key for"), entries.size()));

checkOverwriteKeysChosen();
if (hasUserCanceledOverwrite(entries)) {
return;
}

if (!this.isCanceled) {
BackgroundTask<Void> backgroundTask = this.generateKeysInBackground(databaseContext);
backgroundTask.showToUser(true);
backgroundTask.titleProperty().set(Localization.lang("Autogenerate citation keys"));
backgroundTask.messageProperty().set(Localization.lang("%0/%1 entries", 0, entries.size()));
BackgroundTask<Void> backgroundTask = this.generateKeysInBackground(databaseContext, entries);
backgroundTask.showToUser(true);
backgroundTask.titleProperty().set(Localization.lang("Autogenerate citation keys"));
backgroundTask.messageProperty().set(Localization.lang("%0/%1 entries", 0, entries.size()));

backgroundTask.executeWith(this.taskExecutor);
}
backgroundTask.executeWith(this.taskExecutor);
}

public static boolean confirmOverwriteKeys(DialogService dialogService, CliPreferences preferences) {
Expand All @@ -92,22 +89,22 @@ public static boolean confirmOverwriteKeys(DialogService dialogService, CliPrefe
}
}

private void checkOverwriteKeysChosen() {
private boolean hasUserCanceledOverwrite(List<BibEntry> entries) {
// We don't want to generate keys for entries which already have one thus remove the entries
if (this.preferences.getCitationKeyPatternPreferences().shouldAvoidOverwriteCiteKey()) {
entries.removeIf(BibEntry::hasCitationKey);
return false;
// if we're going to override some citation keys warn the user about it
} else if (entries.parallelStream().anyMatch(BibEntry::hasCitationKey)) {
boolean overwriteKeys = confirmOverwriteKeys(dialogService, this.preferences);

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

private BackgroundTask<Void> generateKeysInBackground(BibDatabaseContext databaseContext) {
private BackgroundTask<Void> generateKeysInBackground(BibDatabaseContext databaseContext, List<BibEntry> entries) {
UndoManager undoManager = stateManager.getUndoManager(databaseContext);
CompoundEdit compound = new CompoundEdit(StandardActions.GENERATE_CITE_KEYS.getText());
// The keys are written entry by entry in call(), which is also where they are handed over
Expand All @@ -129,9 +126,6 @@ public Void call() {
}

private Void generateKeys() {
if (isCanceled) {
return null;
}
UiTaskExecutor.runInJavaFXThread(() -> {
updateProgress(0, entries.size());
messageProperty().set(Localization.lang("%0/%1 entries", 0, entries.size()));
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,182 @@
package org.jabref.gui.citationkeypattern;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Future;

import javafx.beans.property.SimpleObjectProperty;
import javafx.collections.FXCollections;

import org.jabref.gui.DialogService;
import org.jabref.gui.StateManager;
import org.jabref.gui.testutils.JavaFxExtension;
import org.jabref.gui.undo.HeadlessGuiUndoManager;
import org.jabref.logic.citationkeypattern.CitationKeyPatternPreferences;
import org.jabref.logic.citationkeypattern.GlobalCitationKeyPatterns;
import org.jabref.logic.preferences.CliPreferences;
import org.jabref.logic.util.BackgroundTask;
import org.jabref.logic.util.CurrentThreadTaskExecutor;
import org.jabref.logic.util.TaskExecutor;
import org.jabref.model.database.BibDatabase;
import org.jabref.model.database.BibDatabaseContext;
import org.jabref.model.entry.BibEntry;
import org.jabref.model.entry.field.StandardField;

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

@ExtendWith(JavaFxExtension.class)
class GenerateCitationKeyActionTest {

private final DialogService dialogService = mock(DialogService.class);
private final StateManager stateManager = mock(StateManager.class);
private final CliPreferences preferences = mock(CliPreferences.class);

private BibEntry remainingWang;

/// "王" and "汪" both transliterate to "Wang". After "王" is removed, the base key "Wang2020" is free again,
/// so regenerating "汪" would move it from "Wang2020a" to "Wang2020".
@BeforeEach
void setUp() {
BibEntry removedWang = new BibEntry()
.withField(StandardField.AUTHOR, "王, 小明")
.withField(StandardField.YEAR, "2020")
.withCitationKey("Wang2020");
remainingWang = new BibEntry()
.withField(StandardField.AUTHOR, "汪, 小明")
.withField(StandardField.YEAR, "2020")
.withCitationKey("Wang2020a");
BibDatabaseContext databaseContext = new BibDatabaseContext(new BibDatabase(List.of(removedWang, remainingWang)));
databaseContext.getDatabase().removeEntry(removedWang);

when(stateManager.getSelectedEntries()).thenReturn(FXCollections.observableArrayList(remainingWang));
when(stateManager.getActiveDatabase()).thenReturn(Optional.of(databaseContext));
when(stateManager.getUndoManager(any())).thenReturn(new HeadlessGuiUndoManager());
when(dialogService.showConfirmationDialogWithOptOutAndWait(anyString(), anyString(), anyString(), anyString(), anyString(), any()))
.thenReturn(true);
}

private void useKeyPreferences(boolean avoidOverwrite) {
GlobalCitationKeyPatterns keyPatterns = GlobalCitationKeyPatterns.fromPattern("[auth:transliterate:camel][year]");
when(preferences.getCitationKeyPatternPreferences()).thenReturn(new CitationKeyPatternPreferences(
false,
avoidOverwrite,
true,
false,
CitationKeyPatternPreferences.KeySuffix.SECOND_WITH_A,
"",
"",
CitationKeyPatternPreferences.DEFAULT_UNWANTED_CHARACTERS,
keyPatterns,
new SimpleObjectProperty<>(',')));
}

private void generateKeysForSelectedEntries() {
JavaFxExtension.invokeAndWait(() ->
new GenerateCitationKeyAction(() -> null, dialogService, stateManager, new CurrentThreadTaskExecutor(), preferences).execute());
JavaFxExtension.awaitEvents();
}

/// Records current behaviour, not intended behaviour: confirming the overwrite renames the key, so a citation of "Wang2020a" breaks.
/// A silently changing key is considered a bug (see https://github.com/JabRef/jabref/issues/9605).
/// This is the contrast to the test with overwriting avoided, which keeps the key.
@Test
void regeneratingAfterCollidingEntryIsRemovedRenamesKeyWhenOverwriteIsConfirmed() {
useKeyPreferences(false);

generateKeysForSelectedEntries();

verify(dialogService).showConfirmationDialogWithOptOutAndWait(anyString(), anyString(), anyString(), anyString(), anyString(), any());
assertEquals(Optional.of("Wang2020"), remainingWang.getCitationKey());
}

@Test
void regeneratingAfterCollidingEntryIsRemovedKeepsKeyWhenOverwriteIsAvoided() {
useKeyPreferences(true);

generateKeysForSelectedEntries();

verify(dialogService, never()).showConfirmationDialogWithOptOutAndWait(anyString(), anyString(), anyString(), anyString(), anyString(), any());
assertEquals(Optional.of("Wang2020a"), remainingWang.getCitationKey());
}

@Test
void executeGeneratesKeyAfterPreviousExecutionWasCanceled() {
useKeyPreferences(false);
when(dialogService.showConfirmationDialogWithOptOutAndWait(anyString(), anyString(), anyString(), anyString(), anyString(), any()))
.thenReturn(false);

GenerateCitationKeyAction action = new GenerateCitationKeyAction(
() -> null, dialogService, stateManager, new CurrentThreadTaskExecutor(), preferences);

JavaFxExtension.invokeAndWait(action::execute);
JavaFxExtension.awaitEvents();

assertEquals(Optional.of("Wang2020a"), remainingWang.getCitationKey());

BibEntry entryWithoutKey = new BibEntry()
.withField(StandardField.AUTHOR, "Smith, Jane")
.withField(StandardField.YEAR, "2026");
stateManager.getActiveDatabase().get().getDatabase().insertEntry(entryWithoutKey);
when(stateManager.getSelectedEntries()).thenReturn(FXCollections.observableArrayList(entryWithoutKey));

JavaFxExtension.invokeAndWait(action::execute);
JavaFxExtension.awaitEvents();

assertEquals(Optional.of("Smith2026"), entryWithoutKey.getCitationKey());
}

@Test
void delayedTaskGeneratesKeyWhenSubsequentExecutionIsCanceled() {
useKeyPreferences(false);
when(dialogService.showConfirmationDialogWithOptOutAndWait(anyString(), anyString(), anyString(), anyString(), anyString(), any()))
.thenReturn(false);

List<Runnable> queuedTasks = new ArrayList<>();
TaskExecutor delayingTaskExecutor = new CurrentThreadTaskExecutor() {
@Override
public <V> Future<V> execute(BackgroundTask<V> task) {
queuedTasks.add(() -> super.execute(task));
return CompletableFuture.completedFuture(null);
}
};

GenerateCitationKeyAction action = new GenerateCitationKeyAction(
() -> null, dialogService, stateManager, delayingTaskExecutor, preferences);

BibEntry entryWithoutKey = new BibEntry()
.withField(StandardField.AUTHOR, "Smith, Jane")
.withField(StandardField.YEAR, "2026");
stateManager.getActiveDatabase().get().getDatabase().insertEntry(entryWithoutKey);
when(stateManager.getSelectedEntries()).thenReturn(FXCollections.observableArrayList(entryWithoutKey));

JavaFxExtension.invokeAndWait(action::execute);
JavaFxExtension.awaitEvents();

assertEquals(Optional.empty(), entryWithoutKey.getCitationKey());

when(stateManager.getSelectedEntries()).thenReturn(FXCollections.observableArrayList(remainingWang));

JavaFxExtension.invokeAndWait(action::execute);
JavaFxExtension.awaitEvents();

for (Runnable task : queuedTasks) {
JavaFxExtension.invokeAndWait(task);
}
JavaFxExtension.awaitEvents();

assertEquals(Optional.of("Smith2026"), entryWithoutKey.getCitationKey());
assertEquals(Optional.of("Wang2020a"), remainingWang.getCitationKey());
}
}
Loading