Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Properly Copy Associated PDFs Between .bib Files #12092

Closed
wants to merge 3 commits into from
Closed
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
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,8 @@ Note that this project **does not** adhere to [Semantic Versioning](https://semv
- We added an exporter and improved the importer for Endnote XML format. [#11137](https://github.com/JabRef/jabref/issues/11137)
- We added support for using BibTeX Style files (BST) in the Preview. [#11102](https://github.com/JabRef/jabref/issues/11102)
- We added support for automatically update LaTeX citations when a LaTeX file is created, removed, or modified. [#10585](https://github.com/JabRef/jabref/issues/10585)
- We Added functionality to copy associated PDF files when moving entries between `.bib` files, ensuring linked PDFs are also transferred to the destination's designated file directory. [#520](https://github.com/koppor/jabref/issues/520)


### Changed

Expand Down
37 changes: 37 additions & 0 deletions src/main/java/org/jabref/gui/LibraryTab.java
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
package org.jabref.gui;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
Expand Down Expand Up @@ -109,6 +112,8 @@
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import static com.ibm.icu.text.PluralRules.Operand.e;

/**
* Represents the ui area where the notifier pane, the library table and the entry editor are shown.
*/
Expand Down Expand Up @@ -172,6 +177,8 @@ private enum PanelMode { MAIN_TABLE, MAIN_TABLE_AND_ENTRY_EDITOR }

private final AiService aiService;

private static BibDatabaseContext copiedBibDatabaseContext;

/**
* @param isDummyContext Indicates whether the database context is a dummy. A dummy context is used to display a progress indicator while parsing the database.
* If the context is a dummy, the Lucene index should not be created, as both the dummy context and the actual context share the same index path {@link BibDatabaseContext#getFulltextIndexPath()}.
Expand Down Expand Up @@ -905,6 +912,7 @@ public void insertEntries(final List<BibEntry> entries) {
}

public void copyEntry() {
copiedBibDatabaseContext = this.bibDatabaseContext;
int entriesCopied = doCopyEntry(getSelectedEntries());
if (entriesCopied >= 0) {
dialogService.notify(Localization.lang("Copied %0 entry(ies)", entriesCopied));
Expand Down Expand Up @@ -933,6 +941,7 @@ private int doCopyEntry(List<BibEntry> selectedEntries) {
}

public void pasteEntry() {

List<BibEntry> entriesToAdd;
String content = ClipBoardManager.getContents();
entriesToAdd = importHandler.handleBibTeXData(content);
Expand All @@ -943,6 +952,34 @@ public void pasteEntry() {
return;
}

Optional<String> optionalBibFolderPath = copiedBibDatabaseContext.getMetaData().getDefaultFileDirectory();
if(optionalBibFolderPath.isEmpty()){
LOGGER.warn("can not find the file path");
return;
}

Path sourceBibFolder = Paths.get(optionalBibFolderPath.get());

for(BibEntry entry:entriesToAdd){
List<LinkedFile> linkedFiles = entry.getFiles();
for(LinkedFile linkedFile: linkedFiles){
if("pdf".equalsIgnoreCase(linkedFile.getFileType())){
List<Path> folderList = List.of(sourceBibFolder);
Optional<Path> sourcePath = linkedFile.findIn(folderList);
if(sourcePath.isPresent() && Files.exists(sourcePath.get())){
Path targetFolder = bibDatabaseContext.getMetaData().getDefaultFileDirectory().map(Paths::get).orElseThrow();
Path targetPath = targetFolder.resolve(sourcePath.get().getFileName());
try{
Files.copy(sourcePath.get(), targetPath, StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
LOGGER.error("failed to copy PDF file: {}", sourcePath.get(),e);
}
}else{
LOGGER.warn("did not find PDF: {}", linkedFile.getLink());
}
}
}
}
importHandler.importEntriesWithDuplicateCheck(bibDatabaseContext, entriesToAdd);
}

Expand Down
30 changes: 30 additions & 0 deletions src/main/java/org/jabref/gui/copyfiles/CopyFilesAction.java
Original file line number Diff line number Diff line change
@@ -1,9 +1,13 @@
package org.jabref.gui.copyfiles;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.util.List;
import java.util.Optional;

import javafx.application.Platform;
import javafx.concurrent.Task;

import org.jabref.gui.DialogService;
Expand All @@ -15,9 +19,12 @@
import org.jabref.logic.preferences.CliPreferences;
import org.jabref.model.database.BibDatabaseContext;
import org.jabref.model.entry.BibEntry;
import org.jabref.model.entry.LinkedFile;


import static org.jabref.gui.actions.ActionHelper.needsDatabase;
import static org.jabref.gui.actions.ActionHelper.needsEntriesSelected;
import static org.jabref.gui.edit.automaticfiededitor.AbstractAutomaticFieldEditorTabViewModel.LOGGER;

public class CopyFilesAction extends SimpleCommand {

Expand Down Expand Up @@ -48,6 +55,7 @@ private void showDialog(List<CopyFilesResultItemViewModel> data) {

@Override
public void execute() {

BibDatabaseContext database = stateManager.getActiveDatabase().orElseThrow(() -> new NullPointerException("Database null"));
List<BibEntry> entries = stateManager.getSelectedEntries();

Expand All @@ -63,7 +71,29 @@ public void execute() {
Localization.lang("Copy linked files to folder..."),
exportTask);

LOGGER.info("Creating CopyFilesTask with path: " + path);
for (BibEntry entry : entries) {
List<LinkedFile> linkedFiles = entry.getFiles();
for (LinkedFile file : linkedFiles) {
Optional<Path> sourcePath = file.findIn(List.of(path));
if (sourcePath.isPresent()) {
Path targetPath = path.resolve(sourcePath.get().getFileName());
try {
Files.copy(sourcePath.get(), targetPath, StandardCopyOption.REPLACE_EXISTING);
LinkedFile newLinkedFile = new LinkedFile(file.getDescription(), targetPath.toString(), file.getFileType());
entry.addFile(newLinkedFile);
LOGGER.info("Successfully copied file: " + sourcePath.get() + " to " + targetPath);
} catch (IOException e) {
LOGGER.error("Failed to copy file: " + sourcePath.get() + " to " + targetPath, e);
}
}else{
LOGGER.warn("Source file not found or doesn't exist: {}", file.getLink());
}
}
}
uiTaskExecutor.execute(exportTask);

LOGGER.info("CopyFilesTask has been executed.");
exportTask.setOnSucceeded(e -> showDialog(exportTask.getValue()));
});
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -59,3 +59,4 @@ private void setupTable() {
tvResult.setColumnResizePolicy(param -> true);
}
}

2 changes: 2 additions & 0 deletions src/main/java/org/jabref/gui/copyfiles/CopyFilesTask.java
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,7 @@ protected List<CopyFilesResultItemViewModel> call() throws InterruptedException,

if (newPath.isPresent()) {
Path newFile = newPath.get();
LOGGER.info("Calling copyFile method...");
boolean success = FileUtil.copyFile(fileToExport.get(), newFile, false);
updateProgress(totalFilesCounter++, totalFilesCount);
try {
Expand All @@ -97,6 +98,7 @@ protected List<CopyFilesResultItemViewModel> call() throws InterruptedException,
}
if (success) {
updateMessage(localizedSuccessMessage);
fileName.setLink(newFile.toString());
numberSuccessful++;
writeLogMessage(newFile, bw, localizedSuccessMessage);
addResultToList(newFile, success, localizedSuccessMessage);
Expand Down
2 changes: 2 additions & 0 deletions src/main/java/org/jabref/logic/util/io/FileUtil.java
Original file line number Diff line number Diff line change
Expand Up @@ -228,7 +228,9 @@ public static boolean copyFile(Path pathToSourceFile, Path pathToDestinationFile
}
try {
// This should also preserve Hard Links
LOGGER.info("Attempting to copy file from " + pathToSourceFile + " to " + pathToDestinationFile);
Files.copy(pathToSourceFile, pathToDestinationFile, StandardCopyOption.REPLACE_EXISTING);
LOGGER.info("File copied successfully.");
return true;
} catch (IOException e) {
LOGGER.error("Copying Files failed.", e);
Expand Down
Loading