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

Convert AutoLinkFilesAction to JavaFX #4822

Merged
merged 2 commits into from
Apr 1, 2019
Merged
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
12 changes: 6 additions & 6 deletions src/main/java/org/jabref/JabRefMain.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,13 @@

import java.net.Authenticator;

import javax.swing.JFrame;
import javax.swing.JOptionPane;

import javafx.application.Application;
import javafx.application.Platform;
import javafx.scene.control.Alert;
import javafx.stage.Stage;

import org.jabref.cli.ArgumentProcessor;
import org.jabref.gui.FXDialog;
import org.jabref.gui.remote.JabRefMessageHandler;
import org.jabref.logic.journals.JournalAbbreviationLoader;
import org.jabref.logic.l10n.Localization;
Expand Down Expand Up @@ -119,9 +118,10 @@ private static void ensureCorrectJavaVersion() {
versionError.append("\n");
versionError.append(Localization.lang("Note that currently, JabRef does not run with Java 9."));
}
final JFrame frame = new JFrame();
JOptionPane.showMessageDialog(null, versionError, Localization.lang("Error"), JOptionPane.ERROR_MESSAGE);
frame.dispose();

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this dialog is superflous as JabRef won't even start with java9 cause of the class/module visibility

FXDialog alert = new FXDialog(Alert.AlertType.ERROR, Localization.lang("Error"), true);
alert.setHeaderText(null);
alert.setContentText(versionError.toString());

// We exit on Java 9 error since this will definitely not work
if (java9Fail) {
Expand Down
7 changes: 5 additions & 2 deletions src/main/java/org/jabref/cli/ArgumentProcessor.java
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,9 @@

import org.jabref.Globals;
import org.jabref.JabRefException;
import org.jabref.gui.externalfiles.AutoSetLinks;
import org.jabref.gui.externalfiles.AutoSetFileLinksUtil;
import org.jabref.gui.externalfiletype.ExternalFileTypes;
import org.jabref.gui.undo.NamedCompound;
import org.jabref.logic.bibtexkeypattern.BibtexKeyGenerator;
import org.jabref.logic.exporter.AtomicFileWriter;
import org.jabref.logic.exporter.BibDatabaseWriter;
Expand Down Expand Up @@ -496,7 +498,8 @@ private void automaticallySetFileLinks(List<ParserResult> loaded) {
for (ParserResult parserResult : loaded) {
BibDatabase database = parserResult.getDatabase();
LOGGER.info(Localization.lang("Automatically setting file links"));
AutoSetLinks.autoSetLinks(database.getEntries(), parserResult.getDatabaseContext());
AutoSetFileLinksUtil util = new AutoSetFileLinksUtil(parserResult.getDatabaseContext(), Globals.prefs.getFilePreferences(), Globals.prefs.getAutoLinkPreferences(), ExternalFileTypes.getInstance());
util.linkAssociatedFiles(database.getEntries(), new NamedCompound(""));
}
}

Expand Down
24 changes: 6 additions & 18 deletions src/main/java/org/jabref/gui/JabRefFrame.java
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,6 @@
import org.jabref.JabRefExecutorService;
import org.jabref.gui.actions.ActionFactory;
import org.jabref.gui.actions.Actions;
import org.jabref.gui.actions.AutoLinkFilesAction;
import org.jabref.gui.actions.BibtexKeyPatternAction;
import org.jabref.gui.actions.ConnectToSharedDatabaseCommand;
import org.jabref.gui.actions.CopyFilesAction;
Expand Down Expand Up @@ -88,6 +87,7 @@
import org.jabref.gui.exporter.ExportToClipboardAction;
import org.jabref.gui.exporter.SaveAllAction;
import org.jabref.gui.exporter.SaveDatabaseAction;
import org.jabref.gui.externalfiles.AutoLinkFilesAction;
import org.jabref.gui.externalfiles.FindUnlinkedFilesAction;
import org.jabref.gui.externalfiletype.ExternalFileTypes;
import org.jabref.gui.help.AboutAction;
Expand All @@ -113,7 +113,6 @@
import org.jabref.logic.autosaveandbackup.BackupManager;
import org.jabref.logic.importer.IdFetcher;
import org.jabref.logic.importer.OpenDatabase;
import org.jabref.logic.importer.OutputPrinter;
import org.jabref.logic.importer.ParserResult;
import org.jabref.logic.importer.WebFetchers;
import org.jabref.logic.l10n.Localization;
Expand Down Expand Up @@ -148,7 +147,7 @@
/**
* The main window of the application.
*/
public class JabRefFrame extends BorderPane implements OutputPrinter {
public class JabRefFrame extends BorderPane {

// Frame titles.
public static final String FRAME_TITLE = "JabRef";
Expand Down Expand Up @@ -821,7 +820,7 @@ private MenuBar createMenu() {

new SeparatorMenuItem(),

factory.createMenuItem(StandardActions.SET_FILE_LINKS, new AutoLinkFilesAction())
factory.createMenuItem(StandardActions.SET_FILE_LINKS, new AutoLinkFilesAction(this, prefs))
);

PushToApplicationButton pushToExternal = new PushToApplicationButton(this, pushApplications.getApplications());
Expand Down Expand Up @@ -1251,17 +1250,6 @@ private boolean isExistURLorDOI(List<BibEntry> selectEntryList) {
return false;
}

@Override
public void showMessage(String message, String title, int msgType) {
JOptionPane.showMessageDialog(null, message, title, msgType);
}

@Override
public void setStatus(String s) {
output(s);
}

@Override
public void showMessage(String message) {
JOptionPane.showMessageDialog(null, message);
}
Expand Down Expand Up @@ -1440,15 +1428,15 @@ private void setDefaultTableFontSize() {
for (BasePanel basePanel : getBasePanelList()) {
basePanel.updateTableFont();
}
setStatus(Localization.lang("Table font size is %0", String.valueOf(GUIGlobals.currentFont.getSize())));
dialogService.notify(Localization.lang("Table font size is %0", String.valueOf(GUIGlobals.currentFont.getSize())));
}

private void increaseTableFontSize() {
GUIGlobals.setFont(GUIGlobals.currentFont.getSize() + 1);
for (BasePanel basePanel : getBasePanelList()) {
basePanel.updateTableFont();
}
setStatus(Localization.lang("Table font size is %0", String.valueOf(GUIGlobals.currentFont.getSize())));
dialogService.notify(Localization.lang("Table font size is %0", String.valueOf(GUIGlobals.currentFont.getSize())));
}

private void decreaseTableFontSize() {
Expand All @@ -1460,7 +1448,7 @@ private void decreaseTableFontSize() {
for (BasePanel basePanel : getBasePanelList()) {
basePanel.updateTableFont();
}
setStatus(Localization.lang("Table font size is %0", String.valueOf(GUIGlobals.currentFont.getSize())));
dialogService.notify(Localization.lang("Table font size is %0", String.valueOf(GUIGlobals.currentFont.getSize())));
}

private class CloseDatabaseAction extends SimpleCommand {
Expand Down
52 changes: 0 additions & 52 deletions src/main/java/org/jabref/gui/actions/AutoLinkFilesAction.java

This file was deleted.

Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
package org.jabref.gui.externalfiles;

import java.util.List;

import javafx.concurrent.Task;

import org.jabref.gui.DialogService;
import org.jabref.gui.JabRefFrame;
import org.jabref.gui.actions.SimpleCommand;
import org.jabref.gui.externalfiletype.ExternalFileTypes;
import org.jabref.gui.undo.NamedCompound;
import org.jabref.logic.l10n.Localization;
import org.jabref.model.entry.BibEntry;
import org.jabref.preferences.JabRefPreferences;

/**
* This Action may only be used in a menu or button.
* Never in the entry editor. FileListEditor and EntryEditor have other ways to update the file links
*/
public class AutoLinkFilesAction extends SimpleCommand {

private final DialogService dialogService;
private final JabRefFrame frame;
private final JabRefPreferences preferences;

public AutoLinkFilesAction(JabRefFrame frame, JabRefPreferences preferences) {
this.frame = frame;
this.dialogService = frame.getDialogService();
this.preferences = preferences;
}

@Override
public void execute() {
List<BibEntry> entries = frame.getCurrentBasePanel().getSelectedEntries();
if (entries.isEmpty()) {
dialogService.notify(Localization.lang("This operation requires one or more entries to be selected."));
return;
}

final NamedCompound nc = new NamedCompound(Localization.lang("Automatically set file links"));
AutoSetFileLinksUtil util = new AutoSetFileLinksUtil(frame.getCurrentBasePanel().getBibDatabaseContext(), preferences.getFilePreferences(), preferences.getAutoLinkPreferences(), ExternalFileTypes.getInstance());
Task<List<BibEntry>> linkFilesTask = new Task<List<BibEntry>>() {
@Override
protected List<BibEntry> call() {
return util.linkAssociatedFiles(entries, nc);
}

@Override
protected void succeeded() {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You don't have to overwrite succeeded, as a call to linkFilesTask.setOnSucceeded() has the same effect
I prefered to only overwrite call

if (!getValue().isEmpty()) {
if (nc.hasEdits()) {
nc.end();
frame.getCurrentBasePanel().getUndoManager().addEdit(nc);
}
dialogService.notify(Localization.lang("Finished automatically setting external links."));
} else {
dialogService.notify(Localization.lang("Finished automatically setting external links.") + " " + Localization.lang("No files found."));
}
}
};

dialogService.showProgressDialogAndWait(
Localization.lang("Automatically setting file links"),
Localization.lang("Searching for files"),
linkFilesTask
);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,17 @@
import org.jabref.gui.externalfiletype.ExternalFileType;
import org.jabref.gui.externalfiletype.ExternalFileTypes;
import org.jabref.gui.externalfiletype.UnknownExternalFileType;
import org.jabref.gui.undo.NamedCompound;
import org.jabref.gui.undo.UndoableFieldChange;
import org.jabref.gui.util.DefaultTaskExecutor;
import org.jabref.logic.util.io.AutoLinkPreferences;
import org.jabref.logic.util.io.FileFinder;
import org.jabref.logic.util.io.FileFinders;
import org.jabref.logic.util.io.FileUtil;
import org.jabref.model.database.BibDatabaseContext;
import org.jabref.model.entry.BibEntry;
import org.jabref.model.entry.FieldName;
import org.jabref.model.entry.FileFieldWriter;
import org.jabref.model.entry.LinkedFile;
import org.jabref.model.metadata.FilePreferences;
import org.jabref.model.util.FileHelper;
Expand All @@ -26,7 +31,7 @@

public class AutoSetFileLinksUtil {

private static final Logger LOGGER = LoggerFactory.getLogger(AutoSetLinks.class);
private static final Logger LOGGER = LoggerFactory.getLogger(AutoSetFileLinksUtil.class);
private List<Path> directories;
private AutoLinkPreferences autoLinkPreferences;
private ExternalFileTypes externalFileTypes;
Expand All @@ -35,12 +40,44 @@ public AutoSetFileLinksUtil(BibDatabaseContext databaseContext, FilePreferences
this(databaseContext.getFileDirectoriesAsPaths(filePreferences), autoLinkPreferences, externalFileTypes);
}

public AutoSetFileLinksUtil(List<Path> directories, AutoLinkPreferences autoLinkPreferences, ExternalFileTypes externalFileTypes) {
private AutoSetFileLinksUtil(List<Path> directories, AutoLinkPreferences autoLinkPreferences, ExternalFileTypes externalFileTypes) {
this.directories = directories;
this.autoLinkPreferences = autoLinkPreferences;
this.externalFileTypes = externalFileTypes;
}

public List<BibEntry> linkAssociatedFiles(List<BibEntry> entries, NamedCompound ce) {
List<BibEntry> changedEntries = new ArrayList<>();
for (BibEntry entry : entries) {

List<LinkedFile> linkedFiles = new ArrayList<>();
try {
linkedFiles = findAssociatedNotLinkedFiles(entry);
} catch (IOException e) {
LOGGER.error("Problem finding files", e);
}

if (ce != null) {
for (LinkedFile linkedFile : linkedFiles) {
// store undo information
String newVal = FileFieldWriter.getStringRepresentation(linkedFile);

String oldVal = entry.getField(FieldName.FILE).orElse(null);

UndoableFieldChange fieldChange = new UndoableFieldChange(entry, FieldName.FILE, oldVal, newVal);
ce.addEdit(fieldChange);

DefaultTaskExecutor.runInJavaFXThread(() -> {
entry.addFile(linkedFile);
});
}

changedEntries.add(entry);
}
}
return changedEntries;
}

public List<LinkedFile> findAssociatedNotLinkedFiles(BibEntry entry) throws IOException {
List<LinkedFile> linkedFiles = new ArrayList<>();

Expand All @@ -53,22 +90,23 @@ public List<LinkedFile> findAssociatedNotLinkedFiles(BibEntry entry) throws IOEx
// Collect the found files that are not yet linked
for (Path foundFile : result) {
boolean fileAlreadyLinked = entry.getFiles().stream()
.map(file -> file.findIn(directories))
.anyMatch(file -> {
try {
return file.isPresent() && Files.isSameFile(file.get(), foundFile);
} catch (IOException e) {
LOGGER.error("Problem with isSameFile", e);
}
return false;
});
.map(file -> file.findIn(directories))
.anyMatch(file -> {
try {
return file.isPresent() && Files.isSameFile(file.get(), foundFile);
} catch (IOException e) {
LOGGER.error("Problem with isSameFile", e);
}
return false;
});

if (!fileAlreadyLinked) {
Optional<ExternalFileType> type = FileHelper.getFileExtension(foundFile)
.map(externalFileTypes::getExternalFileTypeByExt)
.orElse(Optional.of(new UnknownExternalFileType("")));
.map(externalFileTypes::getExternalFileTypeByExt)
.orElse(Optional.of(new UnknownExternalFileType("")));

String strType = type.isPresent() ? type.get().getName() : "";
String relativeFilePath = FileUtil.relativize(foundFile, directories).toString();
Path relativeFilePath = FileUtil.relativize(foundFile, directories);
LinkedFile linkedFile = new LinkedFile("", relativeFilePath, strType);
linkedFiles.add(linkedFile);
}
Expand Down
Loading