diff --git a/CHANGELOG.md b/CHANGELOG.md index 6d4fb5ff2867..7a59ddf41a11 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 diff --git a/jabgui/src/main/java/org/jabref/gui/citationkeypattern/GenerateCitationKeyAction.java b/jabgui/src/main/java/org/jabref/gui/citationkeypattern/GenerateCitationKeyAction.java index bd7a18c62c86..600def5565c1 100644 --- a/jabgui/src/main/java/org/jabref/gui/citationkeypattern/GenerateCitationKeyAction.java +++ b/jabgui/src/main/java/org/jabref/gui/citationkeypattern/GenerateCitationKeyAction.java @@ -31,9 +31,6 @@ public class GenerateCitationKeyAction extends SimpleCommand { private final DialogService dialogService; private final StateManager stateManager; - private List entries; - private boolean isCanceled; - private final TaskExecutor taskExecutor; private final CliPreferences preferences; @@ -53,11 +50,11 @@ public GenerateCitationKeyAction(Supplier tabSupplier, @Override public void execute() { - entries = new ArrayList<>(stateManager.getSelectedEntries()); - stateManager.getActiveDatabase().ifPresent(this::generateKeysIn); + List entries = new ArrayList<>(stateManager.getSelectedEntries()); + stateManager.getActiveDatabase().ifPresent(databaseContext -> generateKeysIn(databaseContext, entries)); } - private void generateKeysIn(BibDatabaseContext databaseContext) { + private void generateKeysIn(BibDatabaseContext databaseContext, List entries) { if (entries.isEmpty()) { dialogService.showWarningDialogAndWait(Localization.lang("Autogenerate citation keys"), Localization.lang("First select the entries you want keys to be generated for.")); @@ -65,16 +62,16 @@ private void generateKeysIn(BibDatabaseContext databaseContext) { } dialogService.notify(formatOutputMessage(Localization.lang("Generating citation key for"), entries.size())); - checkOverwriteKeysChosen(); + if (hasUserCanceledOverwrite(entries)) { + return; + } - if (!this.isCanceled) { - BackgroundTask 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 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) { @@ -92,22 +89,22 @@ public static boolean confirmOverwriteKeys(DialogService dialogService, CliPrefe } } - private void checkOverwriteKeysChosen() { + private boolean hasUserCanceledOverwrite(List 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 generateKeysInBackground(BibDatabaseContext databaseContext) { + private BackgroundTask generateKeysInBackground(BibDatabaseContext databaseContext, List 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 @@ -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())); diff --git a/jabgui/src/test/java/org/jabref/gui/citationkeypattern/GenerateCitationKeyActionTest.java b/jabgui/src/test/java/org/jabref/gui/citationkeypattern/GenerateCitationKeyActionTest.java new file mode 100644 index 000000000000..4c864f5e4737 --- /dev/null +++ b/jabgui/src/test/java/org/jabref/gui/citationkeypattern/GenerateCitationKeyActionTest.java @@ -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 queuedTasks = new ArrayList<>(); + TaskExecutor delayingTaskExecutor = new CurrentThreadTaskExecutor() { + @Override + public Future execute(BackgroundTask 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()); + } +}