diff --git a/.gitignore b/.gitignore
index eef074f6e45..39f4c1f4ac2 100644
--- a/.gitignore
+++ b/.gitignore
@@ -10,6 +10,14 @@ status.md
# Install4J
install4j6/
+# Snap
+parts/
+stage/
+prime/
+*.snap
+jabref_source.tar.bz2
+snap/.snapcraft/
+
# Gradle
# generated when `gradlew --gui` is called
ui/
@@ -23,18 +31,6 @@ ui/
jabref.xml
*.sonargraph
-# Snapcraft - JabRef places the files into buildres/snapcraft
-snap/
-
-
-
-
-
-
-
-
-
-
# Created by https://www.gitignore.io/api/gradle,java,jabref,intellij,eclipse,netbeans,windows,linux,macos,node,snapcraft
### Eclipse ###
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 9c29a663c2b..26e4ebbf307 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -48,6 +48,7 @@ We refer to [GitHub issues](https://github.com/JabRef/jabref/issues) by using `#
- We updated updated the Related Articles tab to accept JSON from the new version of the Mr. DLib service
- We added an option in the preference dialog box that allows user to choose behavior after dragging and dropping files in Entry Editor. [#4356](https://github.com/JabRef/jabref/issues/4356)
- We added the ability to have an export preference where previously "File"-->"Export"/"Export selected entries" would not save the user's preference[#4495](https://github.com/JabRef/jabref/issues/4495)
+- For automatically created groups, added ability to filter groups by entry type. [#4539](https://github.com/JabRef/jabref/issues/4539)
- We added the ability to add field names from the Preferences Dialog [#4546](https://github.com/JabRef/jabref/issues/4546)
- We added the ability change the column widths directly in the main table. [#4546](https://github.com/JabRef/jabref/issues/4546)
- We added the ability to execute default action in dialog by using with Ctrl + Enter combination [#4496](https://github.com/JabRef/jabref/issues/4496)
diff --git a/build.gradle b/build.gradle
index 94a5e380cab..1e55cfe71cc 100644
--- a/build.gradle
+++ b/build.gradle
@@ -102,7 +102,7 @@ dependencies {
compile group: 'org.apache.tika', name: 'tika-core', version: '1.20'
// required for reading write-protected PDFs - see https://github.com/JabRef/jabref/pull/942#issuecomment-209252635
- compile 'org.bouncycastle:bcprov-jdk15on:1.60'
+ compile 'org.bouncycastle:bcprov-jdk15on:1.61'
compile 'commons-cli:commons-cli:1.4'
@@ -120,7 +120,7 @@ dependencies {
antlr4 'org.antlr:antlr4:4.7.2'
compile 'org.antlr:antlr4-runtime:4.7.2'
- compile 'mysql:mysql-connector-java:8.0.14'
+ compile 'mysql:mysql-connector-java:8.0.15'
compile 'org.postgresql:postgresql:42.2.5'
@@ -147,10 +147,10 @@ dependencies {
// >1.8.0-beta is required for java 9 compatibility
compile 'org.slf4j:slf4j-api:1.8.0-beta2'
- compile 'org.apache.logging.log4j:log4j-slf4j18-impl:2.11.1'
- compile 'org.apache.logging.log4j:log4j-jcl:2.11.1'
- compile 'org.apache.logging.log4j:log4j-api:2.11.1'
- compile 'org.apache.logging.log4j:log4j-core:2.11.1'
+ compile 'org.apache.logging.log4j:log4j-slf4j18-impl:2.11.2'
+ compile 'org.apache.logging.log4j:log4j-jcl:2.11.2'
+ compile 'org.apache.logging.log4j:log4j-api:2.11.2'
+ compile 'org.apache.logging.log4j:log4j-core:2.11.2'
compile 'de.undercouch:citeproc-java:1.0.1'
@@ -158,21 +158,18 @@ dependencies {
errorproneJavac 'com.google.errorprone:javac:1.8.0-u20'
- compile group: 'com.microsoft.azure', name: 'applicationinsights-core', version: '2.3.0'
- compile group: 'com.microsoft.azure', name: 'applicationinsights-logging-log4j2', version: '2.3.0'
+ compile group: 'com.microsoft.azure', name: 'applicationinsights-core', version: '2.3.1'
+ compile group: 'com.microsoft.azure', name: 'applicationinsights-logging-log4j2', version: '2.3.1'
- testImplementation 'org.junit.jupiter:junit-jupiter-api:5.3.2'
- testCompile 'org.junit.jupiter:junit-jupiter-params:5.3.2'
- testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.3.2'
- testRuntimeOnly 'org.junit.vintage:junit-vintage-engine:5.3.2'
- testCompile 'org.junit.platform:junit-platform-launcher:1.3.2'
+ testImplementation 'org.junit.jupiter:junit-jupiter:5.4.0'
+ testRuntimeOnly 'org.junit.vintage:junit-vintage-engine:5.4.0'
+ testCompile 'org.junit.platform:junit-platform-launcher:1.4.0'
- testCompile 'org.junit-pioneer:junit-pioneer:0.3.0'
testRuntime 'org.apache.logging.log4j:log4j-core:2.11.1'
- testRuntime 'org.apache.logging.log4j:log4j-jul:2.11.1'
- testCompile 'org.mockito:mockito-core:2.23.4'
- testCompile 'com.github.tomakehurst:wiremock:2.20.0'
- testCompile 'org.assertj:assertj-swing-junit:3.8.0'
+ testRuntime 'org.apache.logging.log4j:log4j-jul:2.11.2'
+ testCompile 'org.mockito:mockito-core:2.24.0'
+ testCompile 'com.github.tomakehurst:wiremock:2.21.0'
+ testCompile 'org.assertj:assertj-swing-junit:3.9.2'
testCompile 'org.reflections:reflections:0.9.11'
testCompile 'org.xmlunit:xmlunit-core:2.6.2'
testCompile 'org.xmlunit:xmlunit-matchers:2.6.2'
@@ -181,7 +178,7 @@ dependencies {
testCompile "org.testfx:testfx-core:4.0.+"
testCompile "org.testfx:testfx-junit5:4.0.+"
- checkstyle 'com.puppycrawl.tools:checkstyle:8.16'
+ checkstyle 'com.puppycrawl.tools:checkstyle:8.17'
}
jacoco {
@@ -192,9 +189,6 @@ dependencyUpdates {
outputFormatter = "json"
}
-//We have to use this as long as junit-pioneer has no official release
-dependencyUpdates.revision = 'integration'
-
// We have some dependencies which cannot be updated due to various reasons.
dependencyUpdates.resolutionStrategy = {
componentSelection { rules ->
diff --git a/buildres/snapcraft/jabref.desktop b/snap/gui/jabref.desktop
similarity index 90%
rename from buildres/snapcraft/jabref.desktop
rename to snap/gui/jabref.desktop
index ef63a896d2d..3444b73fc8a 100644
--- a/buildres/snapcraft/jabref.desktop
+++ b/snap/gui/jabref.desktop
@@ -4,7 +4,7 @@ GenericName=BibTeX Editor
Comment=JabRef is an open source bibliography reference manager. The native file format used by JabRef is BibTeX, the standard LaTeX bibliography format.
Type=Application
Terminal=false
-Icon=${SNAP}/meta/gui/JabRef-icon-256.png
+Icon=${SNAP}/meta/gui/jabref.png
Exec=jabref %U
Keywords=bibtex;biblatex;latex;bibliography
Categories=Office;
diff --git a/buildres/snapcraft/JabRef-icon-256.png b/snap/gui/jabref.png
similarity index 100%
rename from buildres/snapcraft/JabRef-icon-256.png
rename to snap/gui/jabref.png
diff --git a/snap/snapcraft.yaml b/snap/snapcraft.yaml
new file mode 100644
index 00000000000..b26f84fef0d
--- /dev/null
+++ b/snap/snapcraft.yaml
@@ -0,0 +1,41 @@
+name: jabref
+version: "git"
+version-script: cat build.gradle | grep "^version =" | cut -d'"' -f2
+#icon: snap/gui/jabref.png
+summary: Bibliography manager
+description: JabRef is an open source bibliography reference manager. The native file format used by JabRef is BibTeX, the standard LaTeX bibliography format.
+
+grade: devel
+confinement: strict
+
+architectures:
+ - build-on: amd64
+ - build-on: i386
+
+apps:
+ jabref:
+ command: desktop-launch java -jar $SNAP/jar/JabRef-$SNAP_VERSION.jar
+ environment:
+ _JAVA_OPTIONS: "-Duser.home=$SNAP_USER_DATA"
+ plugs:
+ - desktop
+ - desktop-legacy
+ - wayland
+ - unity7
+ - home
+ - opengl
+ - network-bind
+ - removable-media
+
+parts:
+ jabref:
+ plugin: gradle
+ source: .
+ source-type: git
+ stage-packages:
+ - openjdk-8-jre
+ - openjfx
+ - x11-utils
+ gradle-options: [snapJar, -xtest]
+ gradle-output-dir: 'build/releases'
+ after: [desktop-gtk2]
diff --git a/snapcraft.yaml b/snapcraft.yaml
deleted file mode 100644
index 0daa48c83c4..00000000000
--- a/snapcraft.yaml
+++ /dev/null
@@ -1,35 +0,0 @@
-# based on https://github.com/snapcore/snapcraft/blob/master/demos/gradle/snap/snapcraft.yaml
-
-name: jabref
-
-# the version string 4.2-dev is replaced by scripts/run-snapcraft.sh with the current version provided in build.gradle
-version: '4.2-dev'
-
-summary: Bibliography manager
-icon: buildres/snapcraft/JabRef-icon-256.png
-description: JabRef is an open source bibliography reference manager. The native file format used by JabRef is BibTeX, the standard LaTeX bibliography format.
-
-# only with the following set to stable + strict, we can do a full release
-
-# see https://snapcraft.io/docs/reference/channels
-# stable | devel
-grade: devel
-
-# see https://snapcraft.io/docs/reference/confinement
-# strict | devmode
-confinement: strict
-
-apps:
- jabref:
- command: desktop-launch java -jar $SNAP/jar/JabRef-4.2-dev.jar
- plugs: [desktop, desktop-legacy, wayland, unity7, home, network-bind]
- desktop: ../buildres/snapcraft/jabref.desktop
-
-parts:
- jabref:
- plugin: gradle
- source: .
- stage-packages: [default-jre, openjfx, x11-utils]
- gradle-options: [snapJar]
- gradle-output-dir: 'build/releases'
- after: [desktop-gtk3]
diff --git a/src/main/java/org/jabref/gui/DuplicateResolverDialog.java b/src/main/java/org/jabref/gui/DuplicateResolverDialog.java
index cb34df3d202..0be0d823c83 100644
--- a/src/main/java/org/jabref/gui/DuplicateResolverDialog.java
+++ b/src/main/java/org/jabref/gui/DuplicateResolverDialog.java
@@ -68,7 +68,7 @@ private void init(BibEntry one, BibEntry two, DuplicateResolverType type) {
second = new ButtonType(Localization.lang("Remove entry from import"), ButtonData.APPLY);
both = new ButtonType(Localization.lang("Keep both"), ButtonData.APPLY);
me = new MergeEntries(one, two, Localization.lang("Old entry"),
- Localization.lang("From import"), frame.getCurrentBasePanel().getBibDatabaseContext().getMode());
+ Localization.lang("From import"), frame.getCurrentBasePanel().getBibDatabaseContext().getMode());
break;
case DUPLICATE_SEARCH_WITH_EXACT:
first = new ButtonType(Localization.lang("Keep left"), ButtonData.APPLY);
@@ -84,7 +84,7 @@ private void init(BibEntry one, BibEntry two, DuplicateResolverType type) {
second = new ButtonType(Localization.lang("Do not import entry"), ButtonData.APPLY);
both = new ButtonType(Localization.lang("Import and keep old entry"), ButtonData.APPLY);
me = new MergeEntries(one, two, Localization.lang("Old entry"),
- Localization.lang("From import"), frame.getCurrentBasePanel().getBibDatabaseContext().getMode());
+ Localization.lang("From import"), frame.getCurrentBasePanel().getBibDatabaseContext().getMode());
break;
}
if (removeExactVisible) {
diff --git a/src/main/java/org/jabref/gui/DuplicateSearch.java b/src/main/java/org/jabref/gui/DuplicateSearch.java
index 476b3f70276..9e9921f741a 100644
--- a/src/main/java/org/jabref/gui/DuplicateSearch.java
+++ b/src/main/java/org/jabref/gui/DuplicateSearch.java
@@ -127,7 +127,7 @@ private void askResolveStrategy(DuplicateSearchResult result, BibEntry first, Bi
DuplicateResolverResult resolverResult = dialog.showAndWait().orElse(DuplicateResolverResult.BREAK);
if ((resolverResult == DuplicateResolverResult.KEEP_LEFT)
- || (resolverResult == DuplicateResolverResult.AUTOREMOVE_EXACT)) {
+ || (resolverResult == DuplicateResolverResult.AUTOREMOVE_EXACT)) {
result.remove(second);
if (resolverResult == DuplicateResolverResult.AUTOREMOVE_EXACT) {
autoRemoveExactDuplicates.set(true); // Remember choice
@@ -167,7 +167,7 @@ private void handleDuplicates(DuplicateSearchResult result) {
}
dialogService.notify(Localization.lang("Duplicates found") + ": " + duplicateCount.get() + ' '
- + Localization.lang("pairs processed") + ": " + result.getDuplicateCount());
+ + Localization.lang("pairs processed") + ": " + result.getDuplicateCount());
compoundEdit.end();
panel.getUndoManager().addEdit(compoundEdit);
diff --git a/src/main/java/org/jabref/gui/EntryType.fxml b/src/main/java/org/jabref/gui/EntryType.fxml
index 7fb864fdf78..0ed5f37b502 100644
--- a/src/main/java/org/jabref/gui/EntryType.fxml
+++ b/src/main/java/org/jabref/gui/EntryType.fxml
@@ -12,41 +12,43 @@
-
-
-
-
-
-
+
+
+
+
+
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
-
-
-
-
+
+
+
+
@@ -56,11 +58,11 @@
-
-
+
+
-
-
+
+
diff --git a/src/main/java/org/jabref/gui/JabRefFrame.java b/src/main/java/org/jabref/gui/JabRefFrame.java
index 82ef76ff085..354c2830a35 100644
--- a/src/main/java/org/jabref/gui/JabRefFrame.java
+++ b/src/main/java/org/jabref/gui/JabRefFrame.java
@@ -923,7 +923,7 @@ private MenuBar createMenu() {
);
options.getItems().addAll(
- factory.createMenuItem(StandardActions.SHOW_PREFS, new ShowPreferencesAction(this)),
+ factory.createMenuItem(StandardActions.SHOW_PREFS, new ShowPreferencesAction(this, Globals.TASK_EXECUTOR)),
new SeparatorMenuItem(),
@@ -939,8 +939,7 @@ private MenuBar createMenu() {
factory.createMenuItem(StandardActions.MANAGE_CONTENT_SELECTORS, new OldDatabaseCommandWrapper(Actions.MANAGE_SELECTORS, this, Globals.stateManager)),
factory.createMenuItem(StandardActions.CUSTOMIZE_ENTRY_TYPES, new CustomizeEntryAction(this)),
- factory.createMenuItem(StandardActions.MANAGE_CITE_KEY_PATTERNS, new BibtexKeyPatternAction(this))
- );
+ factory.createMenuItem(StandardActions.MANAGE_CITE_KEY_PATTERNS, new BibtexKeyPatternAction(this)));
help.getItems().addAll(
factory.createMenuItem(StandardActions.HELP, HelpAction.getMainHelpPageCommand()),
diff --git a/src/main/java/org/jabref/gui/PreviewPanel.java b/src/main/java/org/jabref/gui/PreviewPanel.java
index bffcb4e2bd3..796fafdd016 100644
--- a/src/main/java/org/jabref/gui/PreviewPanel.java
+++ b/src/main/java/org/jabref/gui/PreviewPanel.java
@@ -24,7 +24,7 @@
import javafx.scene.web.WebView;
import org.jabref.Globals;
-import org.jabref.gui.externalfiles.NewDroppedFileHandler;
+import org.jabref.gui.externalfiles.ExternalFilesEntryLinker;
import org.jabref.gui.externalfiletype.ExternalFileTypes;
import org.jabref.gui.icon.IconTheme;
import org.jabref.gui.keyboard.KeyBinding;
@@ -61,8 +61,9 @@ public class PreviewPanel extends ScrollPane implements SearchQueryHighlightList
private final DialogService dialogService;
private final KeyBindingRepository keyBindingRepository;
- private String previewStyle;
private final String defaultPreviewStyle = "Preview";
+ private String previewStyle;
+ private CitationStyle citationStyle;
private Optional basePanel = Optional.empty();
private boolean fixedLayout;
@@ -79,7 +80,7 @@ public class PreviewPanel extends ScrollPane implements SearchQueryHighlightList
private final WebView previewView;
private Optional> citationStyleFuture = Optional.empty();
- private final NewDroppedFileHandler fileHandler;
+ private final ExternalFilesEntryLinker fileLinker;
/**
* @param panel (may be null) Only set this if the preview is associated to the main window.
@@ -92,11 +93,7 @@ public PreviewPanel(BasePanel panel, BibDatabaseContext databaseContext, KeyBind
this.clipBoardManager = Globals.clipboardManager;
this.keyBindingRepository = keyBindingRepository;
- fileHandler = new NewDroppedFileHandler(dialogService, databaseContext, externalFileTypes,
- Globals.prefs.getFilePreferences(),
- Globals.prefs.getImportFormatPreferences(),
- Globals.prefs.getUpdateFieldPreferences(),
- Globals.getFileUpdateMonitor());
+ fileLinker = new ExternalFilesEntryLinker(externalFileTypes, Globals.prefs.getFilePreferences(), databaseContext);
// Set up scroll pane for preview pane
setFitToHeight(true);
@@ -134,19 +131,18 @@ public PreviewPanel(BasePanel panel, BibDatabaseContext databaseContext, KeyBind
List files = event.getDragboard().getFiles().stream().map(File::toPath).collect(Collectors.toList());
if (event.getTransferMode() == TransferMode.MOVE) {
-
LOGGER.debug("Mode MOVE"); //shift on win or no modifier
- fileHandler.addToEntryRenameAndMoveToFileDir(entry, files);
+ fileLinker.moveFilesToFileDirAndAddToEntry(entry, files);
}
if (event.getTransferMode() == TransferMode.LINK) {
LOGGER.debug("Node LINK"); //alt on win
- fileHandler.addToEntry(entry, files);
-
+ fileLinker.addFilesToEntry(entry, files);
}
if (event.getTransferMode() == TransferMode.COPY) {
LOGGER.debug("Mode Copy"); //ctrl on win, no modifier on Xubuntu
- fileHandler.copyFilesToFileDirAndAddToEntry(entry, files);
+ fileLinker.copyFilesToFileDirAndAddToEntry(entry, files);
}
+ success = true;
}
event.setDropCompleted(success);
@@ -224,24 +220,25 @@ private void updateLayout(PreviewPreferences previewPreferences, boolean init) {
String style = previewPreferences.getCurrentPreviewStyle();
if (previewStyle == null) {
previewStyle = style;
+ CitationStyle.createCitationStyleFromFile(style).ifPresent(cs -> citationStyle = cs);
}
if (basePanel.isPresent() && !previewStyle.equals(style)) {
if (CitationStyle.isCitationStyleFile(style)) {
layout = Optional.empty();
CitationStyle.createCitationStyleFromFile(style)
- .ifPresent(citationStyle -> {
- basePanel.get().getCitationStyleCache().setCitationStyle(citationStyle);
- if (!init) {
- basePanel.get().output(Localization.lang("Preview style changed to: %0", citationStyle.getTitle()));
- }
- });
+ .ifPresent(cs -> {
+ citationStyle = cs;
+ if (!init) {
+ basePanel.get().output(Localization.lang("Preview style changed to: %0", citationStyle.getTitle()));
+ }
+ });
previewStyle = style;
- } else {
- previewStyle = defaultPreviewStyle;
- updatePreviewLayout(previewPreferences.getPreviewStyle(), previewPreferences.getLayoutFormatterPreferences());
- if (!init) {
- basePanel.get().output(Localization.lang("Preview style changed to: %0", Localization.lang("Preview")));
- }
+ }
+ } else {
+ previewStyle = defaultPreviewStyle;
+ updatePreviewLayout(previewPreferences.getPreviewStyle(), previewPreferences.getLayoutFormatterPreferences());
+ if (!init) {
+ basePanel.get().output(Localization.lang("Preview style changed to: %0", Localization.lang("Preview")));
}
}
@@ -299,6 +296,9 @@ public void update() {
.doLayout(entry, databaseContext.getDatabase())));
setPreviewLabel(sb.toString());
} else if (basePanel.isPresent() && bibEntry.isPresent()) {
+ if ((citationStyle != null) && !previewStyle.equals(defaultPreviewStyle)) {
+ basePanel.get().getCitationStyleCache().setCitationStyle(citationStyle);
+ }
Future> citationStyleWorker = BackgroundTask
.wrap(() -> basePanel.get().getCitationStyleCache().getCitationFor(bibEntry.get()))
.onRunning(() -> {
@@ -363,11 +363,13 @@ public void close() {
private void copyPreviewToClipBoard() {
StringBuilder previewStringContent = new StringBuilder();
Document document = previewView.getEngine().getDocument();
- NodeList nodeList = document.getElementsByTagName("*");
+ NodeList nodeList = document.getElementsByTagName("html");
+
+ //Nodelist does not implement iterable
for (int i = 0; i < nodeList.getLength(); i++) {
Element element = (Element) nodeList.item(i);
- previewStringContent.append(element.getNodeValue()).append("\n");
+ previewStringContent.append(element.getTextContent());
}
ClipboardContent content = new ClipboardContent();
diff --git a/src/main/java/org/jabref/gui/SidePaneManager.java b/src/main/java/org/jabref/gui/SidePaneManager.java
index eef7f01098b..173a11a07c3 100644
--- a/src/main/java/org/jabref/gui/SidePaneManager.java
+++ b/src/main/java/org/jabref/gui/SidePaneManager.java
@@ -31,10 +31,10 @@ public SidePaneManager(JabRefPreferences preferences, JabRefFrame frame) {
OpenOfficePreferences openOfficePreferences = preferences.getOpenOfficePreferences();
Stream.of(
- new FileUpdatePanel(this),
- new GroupSidePane(this, preferences, frame.getDialogService()),
- new WebSearchPane(this, preferences, frame),
- new OpenOfficeSidePanel(this, preferences, frame))
+ new FileUpdatePanel(this),
+ new GroupSidePane(this, preferences, frame.getDialogService()),
+ new WebSearchPane(this, preferences, frame),
+ new OpenOfficeSidePanel(this, preferences, frame))
.forEach(pane -> components.put(pane.getType(), pane));
if (preferences.getBoolean(JabRefPreferences.GROUP_SIDEPANE_VISIBLE)) {
diff --git a/src/main/java/org/jabref/gui/actions/ShowPreferencesAction.java b/src/main/java/org/jabref/gui/actions/ShowPreferencesAction.java
index 7c13cbcc250..e6c0a29684c 100644
--- a/src/main/java/org/jabref/gui/actions/ShowPreferencesAction.java
+++ b/src/main/java/org/jabref/gui/actions/ShowPreferencesAction.java
@@ -2,17 +2,21 @@
import org.jabref.gui.JabRefFrame;
import org.jabref.gui.preferences.PreferencesDialog;
+import org.jabref.gui.util.TaskExecutor;
public class ShowPreferencesAction extends SimpleCommand {
private final JabRefFrame jabRefFrame;
- public ShowPreferencesAction(JabRefFrame jabRefFrame) {
+ private final TaskExecutor taskExecutor;
+
+ public ShowPreferencesAction(JabRefFrame jabRefFrame, TaskExecutor taskExecutor) {
this.jabRefFrame = jabRefFrame;
+ this.taskExecutor = taskExecutor;
}
@Override
public void execute() {
- PreferencesDialog preferencesDialog = new PreferencesDialog(jabRefFrame);
+ PreferencesDialog preferencesDialog = new PreferencesDialog(jabRefFrame, taskExecutor);
preferencesDialog.showAndWait();
}
}
diff --git a/src/main/java/org/jabref/gui/bibtexkeypattern/ResolveDuplicateLabelDialog.java b/src/main/java/org/jabref/gui/bibtexkeypattern/ResolveDuplicateLabelDialog.java
index 68006125528..f6c6aa5544c 100644
--- a/src/main/java/org/jabref/gui/bibtexkeypattern/ResolveDuplicateLabelDialog.java
+++ b/src/main/java/org/jabref/gui/bibtexkeypattern/ResolveDuplicateLabelDialog.java
@@ -48,7 +48,7 @@ public ResolveDuplicateLabelDialog(BasePanel panel, String key, List e
diag = new JDialog((JFrame) null, Localization.lang("Duplicate BibTeX key"), true);
FormBuilder b = FormBuilder.create().layout(new FormLayout(
- "left:pref, 4dlu, fill:pref", "p"));
+ "left:pref, 4dlu, fill:pref", "p"));
b.add(new JLabel(Localization.lang("Duplicate BibTeX key") + ": " + key)).xyw(1, 1, 3);
b.getPanel().setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
diff --git a/src/main/java/org/jabref/gui/copyfiles/CopyFilesTask.java b/src/main/java/org/jabref/gui/copyfiles/CopyFilesTask.java
index ee562c53401..0938f717905 100644
--- a/src/main/java/org/jabref/gui/copyfiles/CopyFilesTask.java
+++ b/src/main/java/org/jabref/gui/copyfiles/CopyFilesTask.java
@@ -112,7 +112,6 @@ protected List call() throws InterruptedException,
writeLogMessage(newFile, bw, localizedErrorMessage);
addResultToList(newFile, success, localizedErrorMessage);
}
-
}
}
diff --git a/src/main/java/org/jabref/gui/entryeditor/EntryEditor.java b/src/main/java/org/jabref/gui/entryeditor/EntryEditor.java
index 4289c29d1b2..450da9e98d9 100644
--- a/src/main/java/org/jabref/gui/entryeditor/EntryEditor.java
+++ b/src/main/java/org/jabref/gui/entryeditor/EntryEditor.java
@@ -31,7 +31,7 @@
import org.jabref.gui.actions.GenerateBibtexKeySingleAction;
import org.jabref.gui.actions.StandardActions;
import org.jabref.gui.entryeditor.fileannotationtab.FileAnnotationTab;
-import org.jabref.gui.externalfiles.NewDroppedFileHandler;
+import org.jabref.gui.externalfiles.ExternalFilesEntryLinker;
import org.jabref.gui.externalfiletype.ExternalFileTypes;
import org.jabref.gui.help.HelpAction;
import org.jabref.gui.keyboard.KeyBinding;
@@ -91,7 +91,7 @@ public class EntryEditor extends BorderPane {
private final EntryEditorPreferences preferences;
private final DialogService dialogService;
- private final NewDroppedFileHandler fileHandler;
+ private final ExternalFilesEntryLinker fileLinker;
private final TaskExecutor taskExecutor;
public EntryEditor(BasePanel panel, EntryEditorPreferences preferences, FileUpdateMonitor fileMonitor, DialogService dialogService, ExternalFileTypes externalFileTypes, TaskExecutor taskExecutor) {
@@ -103,11 +103,7 @@ public EntryEditor(BasePanel panel, EntryEditorPreferences preferences, FileUpda
this.dialogService = dialogService;
this.taskExecutor = taskExecutor;
- fileHandler = new NewDroppedFileHandler(dialogService, databaseContext, externalFileTypes,
- Globals.prefs.getFilePreferences(),
- Globals.prefs.getImportFormatPreferences(),
- Globals.prefs.getUpdateFieldPreferences(),
- Globals.getFileUpdateMonitor());
+ fileLinker = new ExternalFilesEntryLinker(externalFileTypes, Globals.prefs.getFilePreferences(), databaseContext);
ViewLoader.view(this)
.root(this)
@@ -151,17 +147,17 @@ public EntryEditor(BasePanel panel, EntryEditorPreferences preferences, FileUpda
if (event.getTransferMode() == TransferMode.LINK) //alt on win
{
LOGGER.debug("Mode LINK");
- fileHandler.addToEntry(entry, files);
+ fileLinker.addFilesToEntry(entry, files);
}
else if (event.getTransferMode() == TransferMode.COPY) //ctrl on win, no modifier on Xubuntu
{
LOGGER.debug("Mode COPY");
- fileHandler.copyFilesToFileDirAndAddToEntry(entry, files);
+ fileLinker.copyFilesToFileDirAndAddToEntry(entry, files);
}
else
{
LOGGER.debug("Mode MOVE"); //shift on win or no modifier
- fileHandler.addToEntryRenameAndMoveToFileDir(entry, files);
+ fileLinker.moveFilesToFileDirAndAddToEntry(entry, files);
}
}
@@ -170,17 +166,17 @@ else if (event.getTransferMode() == TransferMode.COPY) //ctrl on win, no modifie
if (event.getTransferMode() == TransferMode.COPY) //ctrl on win, no modifier on Xubuntu
{
LOGGER.debug("Mode MOVE");
- fileHandler.addToEntryRenameAndMoveToFileDir(entry, files);
+ fileLinker.moveFilesToFileDirAndAddToEntry(entry, files);
}
else if (event.getTransferMode() == TransferMode.LINK) //alt on win
{
LOGGER.debug("Mode LINK");
- fileHandler.addToEntry(entry, files);
+ fileLinker.addFilesToEntry(entry, files);
}
else
{
LOGGER.debug("Mode COPY"); //shift on win or no modifier
- fileHandler.copyFilesToFileDirAndAddToEntry(entry, files);
+ fileLinker.copyFilesToFileDirAndAddToEntry(entry, files);
}
}
@@ -189,17 +185,17 @@ else if (event.getTransferMode() == TransferMode.LINK) //alt on win
if (event.getTransferMode() == TransferMode.COPY) //ctrl on win, no modifier on Xubuntu
{
LOGGER.debug("Mode COPY");
- fileHandler.copyFilesToFileDirAndAddToEntry(entry, files);
+ fileLinker.copyFilesToFileDirAndAddToEntry(entry, files);
}
else if (event.getTransferMode() == TransferMode.LINK) //alt on win
{
LOGGER.debug("Mode MOVE");
- fileHandler.addToEntryRenameAndMoveToFileDir(entry, files);
+ fileLinker.moveFilesToFileDirAndAddToEntry(entry, files);
}
else
{
LOGGER.debug("Mode LINK"); //shift on win or no modifier
- fileHandler.addToEntry(entry, files);
+ fileLinker.addFilesToEntry(entry, files);
}
}
}
diff --git a/src/main/java/org/jabref/gui/entryeditor/SourceTab.java b/src/main/java/org/jabref/gui/entryeditor/SourceTab.java
index b96fed0bea4..397e3abd921 100644
--- a/src/main/java/org/jabref/gui/entryeditor/SourceTab.java
+++ b/src/main/java/org/jabref/gui/entryeditor/SourceTab.java
@@ -120,7 +120,7 @@ protected void bindToEntry(BibEntry entry) {
} catch (IOException ex) {
codeArea.setEditable(false);
codeArea.appendText(ex.getMessage() + "\n\n" +
- Localization.lang("Correct the entry, and reopen editor to display/edit source."));
+ Localization.lang("Correct the entry, and reopen editor to display/edit source."));
LOGGER.debug("Incorrect entry", ex);
}
});
diff --git a/src/main/java/org/jabref/gui/exporter/CreateModifyExporterDialog.fxml b/src/main/java/org/jabref/gui/exporter/CreateModifyExporterDialog.fxml
index 1c63d7e8008..64a4beed541 100644
--- a/src/main/java/org/jabref/gui/exporter/CreateModifyExporterDialog.fxml
+++ b/src/main/java/org/jabref/gui/exporter/CreateModifyExporterDialog.fxml
@@ -10,43 +10,45 @@
-
-
+
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
-
-
+
+
diff --git a/src/main/java/org/jabref/gui/exporter/CreateModifyExporterDialogView.java b/src/main/java/org/jabref/gui/exporter/CreateModifyExporterDialogView.java
index c3464567625..4e942a48c14 100644
--- a/src/main/java/org/jabref/gui/exporter/CreateModifyExporterDialogView.java
+++ b/src/main/java/org/jabref/gui/exporter/CreateModifyExporterDialogView.java
@@ -18,19 +18,17 @@
public class CreateModifyExporterDialogView extends BaseDialog {
+ @Inject private final JournalAbbreviationLoader loader;
+ private final ExporterViewModel exporter;
@FXML private Button browseButton;
@FXML private TextField name;
@FXML private TextField fileName;
@FXML private TextField extension;
@FXML private ButtonType saveExporter;
-
@Inject private DialogService dialogService;
@Inject private PreferencesService preferences;
- @Inject private final JournalAbbreviationLoader loader;
private CreateModifyExporterDialogViewModel viewModel;
- private final ExporterViewModel exporter;
-
public CreateModifyExporterDialogView(ExporterViewModel exporter, DialogService dialogService,
PreferencesService preferences, JournalAbbreviationLoader loader) {
this.setTitle(Localization.lang("Customize Export Formats"));
@@ -64,4 +62,4 @@ private void initialize() {
private void browse(ActionEvent event) {
viewModel.browse();
}
-}
\ No newline at end of file
+}
diff --git a/src/main/java/org/jabref/gui/exporter/CreateModifyExporterDialogViewModel.java b/src/main/java/org/jabref/gui/exporter/CreateModifyExporterDialogViewModel.java
index 96331a29842..4fd067f02ae 100644
--- a/src/main/java/org/jabref/gui/exporter/CreateModifyExporterDialogViewModel.java
+++ b/src/main/java/org/jabref/gui/exporter/CreateModifyExporterDialogViewModel.java
@@ -21,12 +21,10 @@
import org.slf4j.LoggerFactory;
/**
- *
* This view model can be used both for "add exporter" and "modify exporter" functionalities.
* It takes an optional exporter which is empty for "add exporter," and takes the selected exporter
* for "modify exporter." It returns an optional exporter which empty if an invalid or no exporter is
* created, and otherwise contains the exporter to be added or that is modified.
- *
*/
public class CreateModifyExporterDialogViewModel extends AbstractViewModel {
@@ -65,7 +63,7 @@ public ExporterViewModel saveExporter() {
// Check that there are no empty strings.
if (layoutFile.get().isEmpty() || name.get().isEmpty() || extension.get().isEmpty()
- || !layoutFile.get().endsWith(".layout")) {
+ || !layoutFile.get().endsWith(".layout")) {
LOGGER.info("One of the fields is empty or invalid!");
return null;
@@ -75,7 +73,7 @@ public ExporterViewModel saveExporter() {
LayoutFormatterPreferences layoutPreferences = preferences.getLayoutFormatterPreferences(loader);
SavePreferences savePreferences = preferences.loadForExportFromPreferences();
TemplateExporter format = new TemplateExporter(name.get(), layoutFile.get(), extension.get(),
- layoutPreferences, savePreferences);
+ layoutPreferences, savePreferences);
format.setCustomExport(true);
return new ExporterViewModel(format);
}
@@ -86,9 +84,9 @@ public String getExportWorkingDirectory() {
public void browse() {
FileDialogConfiguration fileDialogConfiguration = new FileDialogConfiguration.Builder()
- .addExtensionFilter(Localization.lang("Custom layout file"), StandardFileType.LAYOUT)
- .withDefaultExtension(Localization.lang("Custom layout file"), StandardFileType.LAYOUT)
- .withInitialDirectory(getExportWorkingDirectory()).build();
+ .addExtensionFilter(Localization.lang("Custom layout file"), StandardFileType.LAYOUT)
+ .withDefaultExtension(Localization.lang("Custom layout file"), StandardFileType.LAYOUT)
+ .withInitialDirectory(getExportWorkingDirectory()).build();
dialogService.showFileOpenDialog(fileDialogConfiguration).ifPresent(f -> layoutFile.set(f.toAbsolutePath().toString()));
}
@@ -103,5 +101,4 @@ public StringProperty getLayoutFileName() {
public StringProperty getExtension() {
return extension;
}
-
}
diff --git a/src/main/java/org/jabref/gui/exporter/ExportCommand.java b/src/main/java/org/jabref/gui/exporter/ExportCommand.java
index 004c7597b5b..36bb095a027 100644
--- a/src/main/java/org/jabref/gui/exporter/ExportCommand.java
+++ b/src/main/java/org/jabref/gui/exporter/ExportCommand.java
@@ -58,8 +58,8 @@ public void execute() {
//Get list of exporters and sort before adding to file dialog
List exporters = Globals.exportFactory.getExporters().stream()
- .sorted(Comparator.comparing(Exporter::getName))
- .collect(Collectors.toList());
+ .sorted(Comparator.comparing(Exporter::getName))
+ .collect(Collectors.toList());
Globals.exportFactory = ExporterFactory.create(customExporters, layoutPreferences, savePreferences, xmpPreferences);
FileDialogConfiguration fileDialogConfiguration = new FileDialogConfiguration.Builder()
diff --git a/src/main/java/org/jabref/gui/exporter/ExportCustomizationDialog.fxml b/src/main/java/org/jabref/gui/exporter/ExportCustomizationDialog.fxml
index d25e272ed38..9a2749a10ca 100644
--- a/src/main/java/org/jabref/gui/exporter/ExportCustomizationDialog.fxml
+++ b/src/main/java/org/jabref/gui/exporter/ExportCustomizationDialog.fxml
@@ -5,25 +5,24 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/src/main/java/org/jabref/gui/exporter/ExportCustomizationDialogViewModel.java b/src/main/java/org/jabref/gui/exporter/ExportCustomizationDialogViewModel.java
index 76bbecce5dc..fc3d3f878cd 100644
--- a/src/main/java/org/jabref/gui/exporter/ExportCustomizationDialogViewModel.java
+++ b/src/main/java/org/jabref/gui/exporter/ExportCustomizationDialogViewModel.java
@@ -39,7 +39,7 @@ private void loadExporters() {
public void addExporter() {
CreateModifyExporterDialogView dialog = new CreateModifyExporterDialogView(null, dialogService, preferences,
- loader);
+ loader);
Optional exporter = dialogService.showCustomDialogAndWait(dialog);
if ((exporter != null) && exporter.isPresent()) {
exporters.add(exporter.get());
@@ -68,7 +68,6 @@ public void removeExporters() {
public void saveToPrefs() {
List exportersLogic = exporters.stream().map(ExporterViewModel::getLogic).collect(Collectors.toList());
preferences.storeCustomExportFormats(exportersLogic);
-
}
public ListProperty selectedExportersProperty() {
diff --git a/src/main/java/org/jabref/gui/exporter/ExportToClipboardAction.java b/src/main/java/org/jabref/gui/exporter/ExportToClipboardAction.java
index ce48b9bfebe..2148a0146c0 100644
--- a/src/main/java/org/jabref/gui/exporter/ExportToClipboardAction.java
+++ b/src/main/java/org/jabref/gui/exporter/ExportToClipboardAction.java
@@ -63,16 +63,16 @@ public void execute() {
//Find default choice, if any
Exporter defaultChoice = exporters.stream()
- .filter(exporter -> exporter.getName().equals(Globals.prefs.get(JabRefPreferences.LAST_USED_EXPORT)))
- .findAny()
- .orElse(null);
+ .filter(exporter -> exporter.getName().equals(Globals.prefs.get(JabRefPreferences.LAST_USED_EXPORT)))
+ .findAny()
+ .orElse(null);
Optional selectedExporter = dialogService.showChoiceDialogAndWait(Localization.lang("Export"), Localization.lang("Select export format"),
- Localization.lang("Export"), defaultChoice, exporters);
+ Localization.lang("Export"), defaultChoice, exporters);
selectedExporter.ifPresent(exporter -> BackgroundTask.wrap(() -> exportToClipboard(exporter))
- .onSuccess(this::setContentToClipboard)
- .executeWith(Globals.TASK_EXECUTOR));
+ .onSuccess(this::setContentToClipboard)
+ .executeWith(Globals.TASK_EXECUTOR));
}
diff --git a/src/main/java/org/jabref/gui/exporter/ExporterViewModel.java b/src/main/java/org/jabref/gui/exporter/ExporterViewModel.java
index 1b4b838ea69..4bd807881f8 100644
--- a/src/main/java/org/jabref/gui/exporter/ExporterViewModel.java
+++ b/src/main/java/org/jabref/gui/exporter/ExporterViewModel.java
@@ -8,8 +8,6 @@
/**
* ExporterViewModel wraps a TemplateExporter from logic and is used in the exporter customization dialog view
* and ViewModel.
- *
- *
*/
public class ExporterViewModel {
@@ -34,7 +32,6 @@ public TemplateExporter getLogic() {
public StringProperty name() {
return this.name;
-
}
public StringProperty layoutFileName() {
diff --git a/src/main/java/org/jabref/gui/exporter/SaveDatabaseAction.java b/src/main/java/org/jabref/gui/exporter/SaveDatabaseAction.java
index 3a4fc68ffd2..681cf946275 100644
--- a/src/main/java/org/jabref/gui/exporter/SaveDatabaseAction.java
+++ b/src/main/java/org/jabref/gui/exporter/SaveDatabaseAction.java
@@ -64,8 +64,8 @@ public SaveDatabaseAction(BasePanel panel, JabRefPreferences prefs) {
private boolean saveDatabase(Path file, boolean selectedOnly, Charset encoding, SavePreferences.DatabaseSaveType saveType) throws SaveException {
try {
SavePreferences preferences = prefs.loadForSaveFromPreferences()
- .withEncoding(encoding)
- .withSaveType(saveType);
+ .withEncoding(encoding)
+ .withSaveType(saveType);
AtomicFileWriter fileWriter = new AtomicFileWriter(file, preferences.getEncoding(), preferences.makeBackup());
BibtexDatabaseWriter databaseWriter = new BibtexDatabaseWriter(fileWriter, preferences);
diff --git a/src/main/java/org/jabref/gui/externalfiles/DroppedFileHandler.java b/src/main/java/org/jabref/gui/externalfiles/DroppedFileHandler.java
deleted file mode 100644
index b4cc4e2e9bf..00000000000
--- a/src/main/java/org/jabref/gui/externalfiles/DroppedFileHandler.java
+++ /dev/null
@@ -1,568 +0,0 @@
-package org.jabref.gui.externalfiles;
-
-import java.awt.BorderLayout;
-import java.io.File;
-import java.io.IOException;
-import java.nio.file.Files;
-import java.nio.file.Path;
-import java.nio.file.Paths;
-import java.util.List;
-import java.util.Optional;
-
-import javax.swing.BoxLayout;
-import javax.swing.ButtonGroup;
-import javax.swing.JCheckBox;
-import javax.swing.JLabel;
-import javax.swing.JOptionPane;
-import javax.swing.JPanel;
-import javax.swing.JRadioButton;
-import javax.swing.JTextArea;
-import javax.swing.JTextField;
-import javax.swing.event.ChangeEvent;
-import javax.swing.event.ChangeListener;
-
-import org.jabref.Globals;
-import org.jabref.gui.BasePanel;
-import org.jabref.gui.DialogService;
-import org.jabref.gui.JabRefFrame;
-import org.jabref.gui.externalfiletype.ExternalFileType;
-import org.jabref.gui.externalfiletype.ExternalFileTypes;
-import org.jabref.gui.filelist.FileListEntry;
-import org.jabref.gui.filelist.FileListTableModel;
-import org.jabref.gui.maintable.MainTable;
-import org.jabref.gui.undo.NamedCompound;
-import org.jabref.gui.undo.UndoableFieldChange;
-import org.jabref.gui.undo.UndoableInsertEntry;
-import org.jabref.gui.util.DefaultTaskExecutor;
-import org.jabref.logic.l10n.Localization;
-import org.jabref.logic.util.io.FileUtil;
-import org.jabref.logic.xmp.XmpUtilReader;
-import org.jabref.model.database.BibDatabase;
-import org.jabref.model.entry.BibEntry;
-import org.jabref.model.entry.FieldName;
-import org.jabref.model.entry.IdGenerator;
-import org.jabref.model.util.FileHelper;
-import org.jabref.preferences.JabRefPreferences;
-
-import com.jgoodies.forms.builder.FormBuilder;
-import com.jgoodies.forms.layout.FormLayout;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * This class holds the functionality of autolinking to a file that's dropped
- * onto an entry.
- *
- * Options for handling the files are:
- *
- * 1) Link to the file in its current position (disabled if the file is remote)
- *
- * 2) Copy the file to ??? directory, rename after bibtex key, and extension
- *
- * 3) Move the file to ??? directory, rename after bibtex key, and extension
- */
-public class DroppedFileHandler {
-
- private static final Logger LOGGER = LoggerFactory.getLogger(DroppedFileHandler.class);
-
- private final BasePanel panel;
-
- private final JRadioButton linkInPlace = new JRadioButton();
- private final JRadioButton copyRadioButton = new JRadioButton();
- private final JRadioButton moveRadioButton = new JRadioButton();
-
- private final JLabel destDirLabel = new JLabel();
-
- private final JCheckBox renameCheckBox = new JCheckBox();
-
- private final JTextField renameToTextBox = new JTextField(50);
-
- private final JPanel optionsPanel = new JPanel();
- private final DialogService dialogService;
- private JabRefPreferences preferences;
-
- public DroppedFileHandler(JabRefFrame frame, BasePanel panel) {
- this.dialogService = frame.getDialogService();
- this.preferences = frame.prefs();
- this.panel = panel;
-
- ButtonGroup grp = new ButtonGroup();
- grp.add(linkInPlace);
- grp.add(copyRadioButton);
- grp.add(moveRadioButton);
-
- FormLayout layout = new FormLayout("left:15dlu,pref,pref,pref", "bottom:14pt,pref,pref,pref,pref");
- layout.setRowGroups(new int[][] {{1, 2, 3, 4, 5}});
- FormBuilder builder = FormBuilder.create().layout(layout);
-
- builder.add(linkInPlace).xyw(1, 1, 4);
- builder.add(destDirLabel).xyw(1, 2, 4);
- builder.add(copyRadioButton).xyw(2, 3, 3);
- builder.add(moveRadioButton).xyw(2, 4, 3);
- builder.add(renameCheckBox).xyw(2, 5, 1);
- builder.add(renameToTextBox).xyw(4, 5, 1);
- optionsPanel.add(builder.getPanel());
- }
-
- /**
- * Offer copy/move/linking options for a dragged external file. Perform the
- * chosen operation, if any.
- *
- * @param fileName The name of the dragged file.
- * @param fileType The FileType associated with the file.
- * @param mainTable The MainTable the file was dragged to.
- * @param dropRow The row where the file was dropped.
- */
- public void handleDroppedfile(String fileName, ExternalFileType fileType, MainTable mainTable, int dropRow) {
-
- BibEntry entry = mainTable.getEntryAt(dropRow);
- handleDroppedfile(fileName, fileType, entry);
- }
-
- /**
- * @param fileName The name of the dragged file.
- * @param fileType The FileType associated with the file.
- * @param entry The target entry for the drop.
- */
- public void handleDroppedfile(String fileName, ExternalFileType fileType, BibEntry entry) {
- NamedCompound edits = new NamedCompound(Localization.lang("Drop %0", fileType.getExtension()));
-
- if (tryXmpImport(fileName, fileType, edits)) {
- edits.end();
- panel.getUndoManager().addEdit(edits);
- return;
- }
-
- // Show dialog
- if (!showLinkMoveCopyRenameDialog(fileName, fileType, entry, panel.getDatabase())) {
- return;
- }
-
- /*
- * Ok, we're ready to go. See first if we need to do a file copy before
- * linking:
- */
-
- boolean success = true;
- String destFilename;
-
- if (linkInPlace.isSelected()) {
- destFilename = FileUtil.relativize(Paths.get(fileName),
- panel.getBibDatabaseContext().getFileDirectoriesAsPaths(Globals.prefs.getFilePreferences()))
- .toString();
- } else {
- destFilename = renameCheckBox.isSelected() ? renameToTextBox.getText() : Paths.get(fileName).toString();
- if (copyRadioButton.isSelected()) {
- success = doCopy(fileName, destFilename, edits);
- } else if (moveRadioButton.isSelected()) {
- success = doMove(fileName, destFilename, edits);
- }
- }
-
- if (success) {
- doLink(entry, fileType, destFilename, false, edits);
- panel.markBaseChanged();
- panel.updateEntryEditorIfShowing();
- }
- edits.end();
- panel.getUndoManager().addEdit(edits);
-
- }
-
- // Done by MrDlib
- public void linkPdfToEntry(String fileName, MainTable entryTable, int dropRow) {
- BibEntry entry = entryTable.getEntryAt(dropRow);
- linkPdfToEntry(fileName, entry);
- }
-
- public void linkPdfToEntry(String fileName, BibEntry entry) {
- Optional optFileType = ExternalFileTypes.getInstance().getExternalFileTypeByExt("pdf");
-
- if (!optFileType.isPresent()) {
- LOGGER.warn("No file type with extension 'pdf' registered.");
- return;
- }
-
- ExternalFileType fileType = optFileType.get();
- // Show dialog
- if (!showLinkMoveCopyRenameDialog(fileName, fileType, entry, panel.getDatabase())) {
- return;
- }
-
- /*
- * Ok, we're ready to go. See first if we need to do a file copy before
- * linking:
- */
-
- boolean success = true;
- String destFilename;
- NamedCompound edits = new NamedCompound(Localization.lang("Drop %0", fileType.getExtension()));
-
- if (linkInPlace.isSelected()) {
- destFilename = FileUtil.relativize(Paths.get(fileName),
- panel.getBibDatabaseContext().getFileDirectoriesAsPaths(Globals.prefs.getFilePreferences()))
- .toString();
- } else {
- destFilename = renameCheckBox.isSelected() ? renameToTextBox.getText() : new File(fileName).getName();
- if (copyRadioButton.isSelected()) {
- success = doCopy(fileName, destFilename, edits);
- } else if (moveRadioButton.isSelected()) {
- success = doMove(fileName, destFilename, edits);
- }
- }
-
- if (success) {
- doLink(entry, fileType, destFilename, false, edits);
- panel.markBaseChanged();
- }
- edits.end();
- panel.getUndoManager().addEdit(edits);
- }
-
- // Done by MrDlib
-
- private boolean tryXmpImport(String fileName, ExternalFileType fileType, NamedCompound edits) {
-
- if (!"pdf".equals(fileType.getExtension())) {
- return false;
- }
-
- List xmpEntriesInFile;
- try {
- xmpEntriesInFile = XmpUtilReader.readXmp(fileName, Globals.prefs.getXMPPreferences());
- } catch (IOException e) {
- LOGGER.warn("Problem reading XMP", e);
- return false;
- }
-
- if ((xmpEntriesInFile == null) || xmpEntriesInFile.isEmpty()) {
- return false;
- }
-
- JLabel confirmationMessage = new JLabel(Localization.lang("The PDF contains one or several BibTeX-records.")
- + "\n" + Localization.lang("Do you want to import these as new entries into the current library?"));
- JPanel entriesPanel = new JPanel();
- entriesPanel.setLayout(new BoxLayout(entriesPanel, BoxLayout.Y_AXIS));
- xmpEntriesInFile.forEach(entry -> {
- JTextArea entryArea = new JTextArea(entry.toString());
- entryArea.setEditable(false);
- entriesPanel.add(entryArea);
- });
-
- JPanel contentPanel = new JPanel(new BorderLayout());
- contentPanel.add(confirmationMessage, BorderLayout.NORTH);
- contentPanel.add(entriesPanel, BorderLayout.CENTER);
-
- int reply = JOptionPane.showConfirmDialog(null, contentPanel,
- Localization.lang("XMP-metadata found in PDF: %0", fileName), JOptionPane.YES_NO_CANCEL_OPTION,
- JOptionPane.QUESTION_MESSAGE);
-
- if (reply == JOptionPane.CANCEL_OPTION) {
- return true; // The user canceled thus that we are done.
- }
- if (reply == JOptionPane.NO_OPTION) {
- return false;
- }
-
- // reply == JOptionPane.YES_OPTION)
-
- /*
- * TODO Extract Import functionality from ImportAction then we could
- * do:
- *
- * ImportAction importer = new ImportAction(frame, (mainTable ==
- * null), new PdfXmpImporter());
- *
- * importer.automatedImport(new String[] { fileName });
- */
-
- boolean isSingle = xmpEntriesInFile.size() == 1;
- BibEntry single = isSingle ? xmpEntriesInFile.get(0) : null;
-
- boolean success = true;
-
- String destFilename;
-
- if (linkInPlace.isSelected()) {
- destFilename = FileUtil.relativize(Paths.get(fileName),
- panel.getBibDatabaseContext().getFileDirectoriesAsPaths(Globals.prefs.getFilePreferences()))
- .toString();
- } else {
- if (renameCheckBox.isSelected() || (single == null)) {
- destFilename = fileName;
- } else {
- destFilename = single.getCiteKey() + "." + fileType.getExtension();
- }
-
- if (copyRadioButton.isSelected()) {
- success = doCopy(fileName, destFilename, edits);
- } else if (moveRadioButton.isSelected()) {
- success = doMove(fileName, destFilename, edits);
- }
- }
- if (success) {
-
- for (BibEntry aXmpEntriesInFile : xmpEntriesInFile) {
-
- aXmpEntriesInFile.setId(IdGenerator.next());
- edits.addEdit(new UndoableInsertEntry(panel.getDatabase(), aXmpEntriesInFile));
- panel.getDatabase().insertEntry(aXmpEntriesInFile);
- doLink(aXmpEntriesInFile, fileType, destFilename, true, edits);
-
- }
- panel.markBaseChanged();
- panel.updateEntryEditorIfShowing();
- }
- return true;
- }
-
- //
- // @return true if user pushed "OK", false otherwise
- //
- private boolean showLinkMoveCopyRenameDialog(String linkFileName, ExternalFileType fileType, BibEntry entry,
- BibDatabase database) {
-
- String dialogTitle = Localization.lang("Link to file %0", linkFileName);
-
- Optional dir = panel.getBibDatabaseContext()
- .getFirstExistingFileDir(Globals.prefs.getFilePreferences());
-
- if (!dir.isPresent()) {
- destDirLabel.setText(Localization.lang("File directory is not set or does not exist!"));
- copyRadioButton.setEnabled(false);
- moveRadioButton.setEnabled(false);
- renameToTextBox.setEnabled(false);
- renameCheckBox.setEnabled(false);
- linkInPlace.setSelected(true);
- } else {
- destDirLabel.setText(Localization.lang("File directory is '%0':", dir.get().toString()));
- copyRadioButton.setEnabled(true);
- moveRadioButton.setEnabled(true);
- renameToTextBox.setEnabled(true);
- renameCheckBox.setEnabled(true);
- }
-
- ChangeListener cl = arg0 -> {
- renameCheckBox.setEnabled(!linkInPlace.isSelected());
- renameToTextBox.setEnabled(!linkInPlace.isSelected());
- };
-
- linkInPlace.setText(Localization.lang("Leave file in its current directory"));
- copyRadioButton.setText(Localization.lang("Copy file to file directory"));
- moveRadioButton.setText(Localization.lang("Move file to file directory"));
- renameCheckBox.setText(Localization.lang("Rename file to").concat(": "));
-
- // Determine which name to suggest:
- String targetName = FileUtil.createFileNameFromPattern(database, entry,
- Globals.prefs.get(JabRefPreferences.IMPORT_FILENAMEPATTERN));
-
- String fileDirPattern = Globals.prefs.get(JabRefPreferences.IMPORT_FILEDIRPATTERN);
-
- String targetDirName = "";
- if (!fileDirPattern.isEmpty()) {
- targetDirName = FileUtil.createDirNameFromPattern(database, entry, fileDirPattern);
- }
-
- if (targetDirName.isEmpty()) {
- renameToTextBox.setText(targetName.concat(".").concat(fileType.getExtension()));
- } else {
- renameToTextBox
- .setText(targetDirName.concat("/").concat(targetName.concat(".").concat(fileType.getExtension())));
- }
- linkInPlace.setSelected(preferences.getBoolean(JabRefPreferences.DROPPEDFILEHANDLER_LEAVE));
- copyRadioButton.setSelected(preferences.getBoolean(JabRefPreferences.DROPPEDFILEHANDLER_COPY));
- moveRadioButton.setSelected(preferences.getBoolean(JabRefPreferences.DROPPEDFILEHANDLER_MOVE));
- renameCheckBox.setSelected(preferences.getBoolean(JabRefPreferences.DROPPEDFILEHANDLER_RENAME));
-
- linkInPlace.addChangeListener(cl);
- cl.stateChanged(new ChangeEvent(linkInPlace));
-
- try {
- Object[] messages = {Localization.lang("How would you like to link to '%0'?", linkFileName), optionsPanel};
- int reply = JOptionPane.showConfirmDialog(null, messages, dialogTitle, JOptionPane.OK_CANCEL_OPTION,
- JOptionPane.QUESTION_MESSAGE);
- if (reply == JOptionPane.OK_OPTION) {
- // store user's choice
- preferences.putBoolean(JabRefPreferences.DROPPEDFILEHANDLER_LEAVE, linkInPlace.isSelected());
- preferences.putBoolean(JabRefPreferences.DROPPEDFILEHANDLER_COPY, copyRadioButton.isSelected());
- preferences.putBoolean(JabRefPreferences.DROPPEDFILEHANDLER_MOVE, moveRadioButton.isSelected());
- preferences.putBoolean(JabRefPreferences.DROPPEDFILEHANDLER_RENAME, renameCheckBox.isSelected());
- return true;
- } else {
- return false;
- }
- } finally {
- linkInPlace.removeChangeListener(cl);
- }
- }
-
- /**
- * Make a extension to the file.
- *
- * @param entry The entry to extension from.
- * @param fileType The FileType associated with the file.
- * @param filename The path to the file.
- * @param edits An NamedCompound action this action is to be added to. If none
- * is given, the edit is added to the panel's undoManager.
- */
- private void doLink(BibEntry entry, ExternalFileType fileType, String filename, boolean avoidDuplicate,
- NamedCompound edits) {
-
- Optional oldValue = entry.getField(FieldName.FILE);
- FileListTableModel tm = new FileListTableModel();
- oldValue.ifPresent(tm::setContent);
-
- // If avoidDuplicate==true, we should check if this file is already linked:
- if (avoidDuplicate) {
- // For comparison, find the absolute filename:
- List dirs = panel.getBibDatabaseContext()
- .getFileDirectoriesAsPaths(Globals.prefs.getFilePreferences());
- String absFilename;
- if (new File(filename).isAbsolute() || dirs.isEmpty()) {
- absFilename = filename;
- } else {
- Optional file = FileHelper.expandFilenameAsPath(filename, dirs);
- if (file.isPresent()) {
- absFilename = file.get().toAbsolutePath().toString();
- } else {
- absFilename = ""; // This shouldn't happen based on the old code, so maybe one should set it something else?
- }
- }
-
- LOGGER.debug("absFilename: " + absFilename);
-
- for (int i = 0; i < tm.getRowCount(); i++) {
- FileListEntry flEntry = tm.getEntry(i);
- // Find the absolute filename for this existing link:
- String absName = flEntry.toParsedFileField()
- .findIn(dirs)
- .map(Path::toAbsolutePath)
- .map(Path::toString)
- .orElse(null);
-
- LOGGER.debug("absName: " + absName);
- // If the filenames are equal, we don't need to link, so we simply return:
- if (absFilename.equals(absName)) {
- return;
- }
- }
- }
-
- tm.addEntry(tm.getRowCount(), new FileListEntry("", filename, fileType));
- String newValue = tm.getStringRepresentation();
- UndoableFieldChange edit = new UndoableFieldChange(entry, FieldName.FILE, oldValue.orElse(null), newValue);
-
- // make sure that the update runs in the Java FX thread to avoid exception in listeners
- DefaultTaskExecutor.runInJavaFXThread(() -> {
- entry.setField(FieldName.FILE, newValue);
- });
-
- if (edits == null) {
- panel.getUndoManager().addEdit(edit);
- } else {
- edits.addEdit(edit);
- }
- }
-
- /**
- * Move the given file to the base directory for its file type, and rename
- * it to the given filename.
- *
- * @param fileName The name of the source file.
- * @param destFilename The destination filename.
- * @param edits TODO we should be able to undo this action
- * @return true if the operation succeeded.
- */
- private boolean doMove(String fileName, String destFilename, NamedCompound edits) {
- Optional dir = panel.getBibDatabaseContext()
- .getFirstExistingFileDir(Globals.prefs.getFilePreferences());
-
- if (dir.isPresent()) {
- Path destFile = dir.get().resolve(destFilename);
-
- if (Files.exists(destFile)) {
- int answer = JOptionPane.showConfirmDialog(null,
- Localization.lang("'%0' exists. Overwrite file?", destFile.toString()),
- Localization.lang("Overwrite file?"), JOptionPane.YES_NO_OPTION);
- if (answer == JOptionPane.NO_OPTION) {
- return false;
- }
- }
-
- Path fromFile = Paths.get(fileName);
- try {
- if (!Files.exists(destFile)) {
- Files.createDirectories(destFile);
- }
- } catch (IOException e) {
- LOGGER.error("Problem creating target directories", e);
- }
- if (FileUtil.renameFile(fromFile, destFile, true)) {
- return true;
- } else {
- dialogService.showErrorDialogAndWait(
- Localization.lang("Move file failed"),
- Localization.lang("Could not move file '%0'.", destFile.toString())
- + Localization.lang("Please move the file manually and link in place."));
- return false;
- }
- }
- return false;
- }
-
- /**
- * Copy the given file to the base directory for its file type, and give it
- * the given name.
- *
- * @param fileName The name of the source file.
- * @param toFile The destination filename. An existing path-component will be removed.
- * @param edits TODO we should be able to undo this!
- * @return true if the operation succeeded.
- */
- private boolean doCopy(String fileName, String toFile, NamedCompound edits) {
-
- List dirs = panel.getBibDatabaseContext()
- .getFileDirectories(Globals.prefs.getFilePreferences());
- int found = -1;
- for (int i = 0; i < dirs.size(); i++) {
- if (new File(dirs.get(i)).exists()) {
- found = i;
- break;
- }
- }
- if (found < 0) {
- // OOps, we don't know which directory to put it in, or the given
- // dir doesn't exist....
- // This should not happen!!
- LOGGER.warn("Cannot determine destination directory or destination directory does not exist");
- return false;
- }
-
- Path destFile = Paths.get(dirs.get(found)).resolve(toFile);
- if (destFile.toString().equals(fileName)) {
- // File is already in the correct position. Don't override!
- return true;
- }
-
- if (Files.exists(destFile)) {
- int answer = JOptionPane.showConfirmDialog(null,
- Localization.lang("'%0' exists. Overwrite file?", destFile.toString()),
- Localization.lang("File exists"), JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
- if (answer == JOptionPane.NO_OPTION) {
- return false;
- }
- }
- try {
- //copy does not create directories, therefore we have to create them manually
- if (!Files.exists(destFile)) {
- Files.createDirectories(destFile);
- }
- FileUtil.copyFile(Paths.get(fileName), destFile, true);
- } catch (IOException e) {
- LOGGER.error("Problem copying file", e);
- return false;
- }
- return true;
- }
-
-}
diff --git a/src/main/java/org/jabref/gui/externalfiles/ExternalFilesEntryLinker.java b/src/main/java/org/jabref/gui/externalfiles/ExternalFilesEntryLinker.java
index 98640b3a377..ab2b1e9c819 100644
--- a/src/main/java/org/jabref/gui/externalfiles/ExternalFilesEntryLinker.java
+++ b/src/main/java/org/jabref/gui/externalfiles/ExternalFilesEntryLinker.java
@@ -1,7 +1,6 @@
package org.jabref.gui.externalfiles;
import java.nio.file.Path;
-import java.util.Arrays;
import java.util.List;
import java.util.Optional;
@@ -51,22 +50,29 @@ public void moveLinkedFilesToFileDir(BibEntry entry) {
moveFilesCleanup.cleanup(entry);
}
- public void addFileToEntry(BibEntry entry, Path file) {
- addFilesToEntry(entry, Arrays.asList(file));
- }
-
public void addFilesToEntry(BibEntry entry, List files) {
for (Path file : files) {
FileUtil.getFileExtension(file).ifPresent(ext -> {
-
ExternalFileType type = externalFileTypes.getExternalFileTypeByExt(ext)
.orElse(new UnknownExternalFileType(ext));
Path relativePath = FileUtil.relativize(file, bibDatabaseContext.getFileDirectoriesAsPaths(filePreferences));
LinkedFile linkedfile = new LinkedFile("", relativePath.toString(), type.getName());
entry.addFile(linkedfile);
});
-
}
+ }
+ public void moveFilesToFileDirAndAddToEntry(BibEntry entry, List files) {
+ addFilesToEntry(entry, files);
+ moveLinkedFilesToFileDir(entry);
+ renameLinkedFilesToPattern(entry);
+ }
+
+ public void copyFilesToFileDirAndAddToEntry(BibEntry entry, List files) {
+ for (Path file : files) {
+ copyFileToFileDir(file)
+ .ifPresent(copiedFile -> addFilesToEntry(entry, files));
+ }
+ renameLinkedFilesToPattern(entry);
}
}
diff --git a/src/main/java/org/jabref/gui/externalfiles/FindFullTextAction.java b/src/main/java/org/jabref/gui/externalfiles/FindFullTextAction.java
index f706e4b692e..3874a503d16 100644
--- a/src/main/java/org/jabref/gui/externalfiles/FindFullTextAction.java
+++ b/src/main/java/org/jabref/gui/externalfiles/FindFullTextAction.java
@@ -43,8 +43,8 @@ public FindFullTextAction(BasePanel basePanel) {
@Override
public void execute() {
BackgroundTask.wrap(this::findFullTexts)
- .onSuccess(this::downloadFullTexts)
- .executeWith(Globals.TASK_EXECUTOR);
+ .onSuccess(this::downloadFullTexts)
+ .executeWith(Globals.TASK_EXECUTOR);
}
private Map, BibEntry> findFullTexts() {
@@ -100,8 +100,7 @@ private void downloadFullTexts(Map, BibEntry> downloads) {
//Download full text
addLinkedFileFromURL(result.get(), entry);
-
- } else {
+ } else {
dialogService.notify(Localization.lang("No full text document found for entry %0.",
entry.getCiteKeyOptional().orElse(Localization.lang("undefined"))));
}
@@ -115,7 +114,8 @@ private void downloadFullTexts(Map, BibEntry> downloads) {
/**
* This method attaches a linked file from a URL (if not already linked) to an entry using the key and value pair
* from the findFullTexts map
- * @param url the url "key"
+ *
+ * @param url the url "key"
* @param entry the entry "value"
*/
private void addLinkedFileFromURL(URL url, BibEntry entry) {
diff --git a/src/main/java/org/jabref/gui/externalfiles/FindUnlinkedFilesDialog.java b/src/main/java/org/jabref/gui/externalfiles/FindUnlinkedFilesDialog.java
index 5a8b0e8c5a8..f9e0e8a689c 100644
--- a/src/main/java/org/jabref/gui/externalfiles/FindUnlinkedFilesDialog.java
+++ b/src/main/java/org/jabref/gui/externalfiles/FindUnlinkedFilesDialog.java
@@ -9,9 +9,10 @@
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.ArrayList;
-import java.util.Collection;
+import java.util.Arrays;
import java.util.List;
import java.util.Optional;
+import java.util.stream.Collectors;
import javafx.collections.FXCollections;
import javafx.geometry.Insets;
@@ -19,7 +20,6 @@
import javafx.scene.control.Button;
import javafx.scene.control.ButtonBar;
import javafx.scene.control.ButtonType;
-import javafx.scene.control.CheckBox;
import javafx.scene.control.CheckBoxTreeItem;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
@@ -34,24 +34,24 @@
import javafx.scene.layout.Priority;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
+import javafx.stage.FileChooser;
import org.jabref.Globals;
import org.jabref.gui.DialogService;
import org.jabref.gui.JabRefFrame;
+import org.jabref.gui.externalfiletype.ExternalFileType;
import org.jabref.gui.externalfiletype.ExternalFileTypes;
-import org.jabref.gui.importer.EntryFromFileCreator;
-import org.jabref.gui.importer.EntryFromFileCreatorManager;
import org.jabref.gui.importer.UnlinkedFilesCrawler;
import org.jabref.gui.util.BackgroundTask;
import org.jabref.gui.util.BaseDialog;
import org.jabref.gui.util.DirectoryDialogConfiguration;
import org.jabref.gui.util.FileDialogConfiguration;
+import org.jabref.gui.util.FileFilterConverter;
import org.jabref.gui.util.ViewModelListCellFactory;
import org.jabref.gui.util.ViewModelTreeCellFactory;
import org.jabref.logic.l10n.Localization;
-import org.jabref.model.EntryTypes;
+import org.jabref.logic.util.StandardFileType;
import org.jabref.model.database.BibDatabaseContext;
-import org.jabref.model.entry.EntryType;
import org.jabref.preferences.JabRefPreferences;
import org.slf4j.Logger;
@@ -65,17 +65,15 @@ public class FindUnlinkedFilesDialog extends BaseDialog {
private static final Logger LOGGER = LoggerFactory.getLogger(FindUnlinkedFilesDialog.class);
private final JabRefFrame frame;
private final BibDatabaseContext databaseContext;
- private final EntryFromFileCreatorManager creatorManager;
+ private final ImportHandler importHandler;
private final JabRefPreferences preferences = Globals.prefs;
private final DialogService dialogService;
private Button buttonScan;
private Button buttonExport;
private Button buttonApply;
- private CheckBox checkboxCreateKeywords;
private TextField textfieldDirectoryPath;
private TreeView tree;
- private ComboBox comboBoxFileTypeSelection;
- private ComboBox comboBoxEntryTypeSelection;
+ private ComboBox comboBoxFileTypeSelection;
private VBox panelSearchProgress;
private BackgroundTask findUnlinkedFilesTask;
@@ -86,7 +84,16 @@ public FindUnlinkedFilesDialog(JabRefFrame frame) {
dialogService = frame.getDialogService();
databaseContext = frame.getCurrentBasePanel().getBibDatabaseContext();
- creatorManager = new EntryFromFileCreatorManager(ExternalFileTypes.getInstance());
+ importHandler = new ImportHandler(
+ dialogService,
+ databaseContext,
+ ExternalFileTypes.getInstance(),
+ Globals.prefs.getFilePreferences(),
+ Globals.prefs.getImportFormatPreferences(),
+ Globals.prefs.getUpdateFieldPreferences(),
+ Globals.getFileUpdateMonitor(),
+ frame.getUndoManager()
+ );
initialize();
}
@@ -166,9 +173,6 @@ private void initialize() {
root.setExpanded(true);
});
- checkboxCreateKeywords = new CheckBox(Localization.lang("Create directory based keywords"));
- checkboxCreateKeywords.setTooltip(new Tooltip((Localization.lang("Creates keywords in created entrys with directory pathnames"))));
-
textfieldDirectoryPath = new TextField();
Path initialPath = databaseContext.getFirstExistingFileDir(preferences.getFilePreferences())
.orElse(preferences.getWorkingDir());
@@ -177,7 +181,6 @@ private void initialize() {
Label labelDirectoryDescription = new Label(Localization.lang("Select a directory where the search shall start."));
Label labelFileTypesDescription = new Label(Localization.lang("Select file type:"));
Label labelFilesDescription = new Label(Localization.lang("These files are not linked in the active library."));
- Label labelEntryTypeDescription = new Label(Localization.lang("Entry type to be created:"));
Label labelSearchingDirectoryInfo = new Label(Localization.lang("Searching file system..."));
tree = new TreeView<>();
@@ -211,29 +214,21 @@ private void initialize() {
}
})
.install(tree);
- List fileFilterList = creatorManager.getFileFilterList();
+ List fileFilterList = Arrays.asList(
+ FileFilterConverter.ANY_FILE,
+ FileFilterConverter.toExtensionFilter(StandardFileType.PDF),
+ FileFilterConverter.toExtensionFilter(StandardFileType.BIBTEX_DB)
+ );
+
comboBoxFileTypeSelection = new ComboBox<>(FXCollections.observableArrayList(fileFilterList));
comboBoxFileTypeSelection.getSelectionModel().selectFirst();
- new ViewModelListCellFactory()
- .withText(Object::toString)
- .withIcon(fileFilter -> {
- if (fileFilter instanceof EntryFromFileCreator) {
- EntryFromFileCreator creator = (EntryFromFileCreator) fileFilter;
- if (creator.getExternalFileType() != null) {
- return creator.getExternalFileType().getIcon();
- }
- }
- return null;
- })
+ new ViewModelListCellFactory()
+ .withText(fileFilter -> fileFilter.getDescription() + fileFilter.getExtensions().stream().collect(Collectors.joining(", ", " (", ")")))
+ .withIcon(fileFilter -> ExternalFileTypes.getInstance().getExternalFileTypeByExt(fileFilter.getExtensions().get(0))
+ .map(ExternalFileType::getIcon)
+ .orElse(null))
.install(comboBoxFileTypeSelection);
- Collection entryTypes = EntryTypes.getAllValues(frame.getCurrentBasePanel().getBibDatabaseContext().getMode());
- comboBoxEntryTypeSelection = new ComboBox<>(FXCollections.observableArrayList(entryTypes));
- comboBoxEntryTypeSelection.getSelectionModel().selectFirst();
- new ViewModelListCellFactory()
- .withText(EntryType::getName)
- .install(comboBoxEntryTypeSelection);
-
panelSearchProgress = new VBox(5, labelSearchingDirectoryInfo, progressBarSearching);
panelSearchProgress.toFront();
panelSearchProgress.setVisible(false);
@@ -261,17 +256,10 @@ private void initialize() {
panelFiles.setCenter(stackPaneTree);
panelFiles.setBottom(new HBox(5, buttonOptionSelectAll, buttonOptionDeselectAll, buttonOptionExpandAll, buttonOptionCollapseAll, buttonExport));
- VBox panelEntryTypesSelection = new VBox(5);
- panelEntryTypesSelection.getChildren().setAll(
- new HBox(15, labelEntryTypeDescription, comboBoxEntryTypeSelection),
- checkboxCreateKeywords
- );
-
VBox container = new VBox(20);
container.getChildren().addAll(
panelDirectory,
- panelFiles,
- panelEntryTypesSelection
+ panelFiles
);
container.setPrefWidth(600);
getDialogPane().setContent(container);
@@ -295,7 +283,7 @@ private void expandTree(TreeItem> item, boolean expand) {
*/
private void startSearch() {
Path directory = getSearchDirectory();
- FileFilter selectedFileFilter = comboBoxFileTypeSelection.getValue();
+ FileFilter selectedFileFilter = FileFilterConverter.toFileFilter(comboBoxFileTypeSelection.getValue());
findUnlinkedFilesTask = new UnlinkedFilesCrawler(directory, selectedFileFilter, databaseContext)
.onRunning(() -> {
@@ -343,27 +331,7 @@ private void startImport() {
return;
}
- final EntryType entryType = comboBoxEntryTypeSelection.getValue();
-
- List errors = creatorManager.addEntriesFromFiles(
- fileList,
- databaseContext.getDatabase(),
- frame.getCurrentBasePanel(),
- entryType,
- checkboxCreateKeywords.isSelected());
-
- if (!errors.isEmpty()) {
- String message;
- if (errors.size() == 1) {
- message = Localization.lang("There was one file that could not be imported.");
- } else {
- message = Localization.lang("There were %0 files which could not be imported.",
- Integer.toString(errors.size()));
- }
- dialogService.showWarningDialogAndWait(
- Localization.lang("Warning"),
- Localization.lang("The import finished with warnings:") + "\n" + message);
- }
+ importHandler.importAsNewEntries(fileList);
}
/**
diff --git a/src/main/java/org/jabref/gui/externalfiles/ImportHandler.java b/src/main/java/org/jabref/gui/externalfiles/ImportHandler.java
new file mode 100644
index 00000000000..6d0860f53f0
--- /dev/null
+++ b/src/main/java/org/jabref/gui/externalfiles/ImportHandler.java
@@ -0,0 +1,113 @@
+package org.jabref.gui.externalfiles;
+
+import java.nio.file.Path;
+import java.util.Collections;
+import java.util.List;
+
+import javax.swing.undo.CompoundEdit;
+import javax.swing.undo.UndoManager;
+
+import org.jabref.Globals;
+import org.jabref.gui.DialogService;
+import org.jabref.gui.externalfiletype.ExternalFileTypes;
+import org.jabref.gui.undo.UndoableInsertEntry;
+import org.jabref.logic.externalfiles.ExternalFilesContentImporter;
+import org.jabref.logic.importer.ImportFormatPreferences;
+import org.jabref.logic.util.UpdateField;
+import org.jabref.logic.util.UpdateFieldPreferences;
+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.metadata.FilePreferences;
+import org.jabref.model.util.FileUpdateMonitor;
+import org.jabref.preferences.JabRefPreferences;
+
+public class ImportHandler {
+
+ private final BibDatabaseContext database;
+ private final UpdateFieldPreferences updateFieldPreferences;
+ private final DialogService dialogService;
+ private final FileUpdateMonitor fileUpdateMonitor;
+ private final ExternalFilesEntryLinker linker;
+ private final ExternalFilesContentImporter contentImporter;
+ private final UndoManager undoManager;
+
+ public ImportHandler(DialogService dialogService,
+ BibDatabaseContext database,
+ ExternalFileTypes externalFileTypes,
+ FilePreferences filePreferences,
+ ImportFormatPreferences importFormatPreferences,
+ UpdateFieldPreferences updateFieldPreferences,
+ FileUpdateMonitor fileupdateMonitor,
+ UndoManager undoManager) {
+
+ this.dialogService = dialogService;
+ this.database = database;
+ this.updateFieldPreferences = updateFieldPreferences;
+ this.fileUpdateMonitor = fileupdateMonitor;
+
+ this.linker = new ExternalFilesEntryLinker(externalFileTypes, filePreferences, database);
+ this.contentImporter = new ExternalFilesContentImporter(importFormatPreferences);
+ this.undoManager = undoManager;
+ }
+
+ public ExternalFilesEntryLinker getLinker() {
+ return linker;
+ }
+
+ public void importAsNewEntries(List files) {
+ CompoundEdit ce = new CompoundEdit();
+ for (Path file : files) {
+ List entriesToAdd;
+ if (FileUtil.getFileExtension(file).filter("pdf"::equals).isPresent()) {
+ List pdfResult = contentImporter.importPDFContent(file);
+ List xmpEntriesInFile = contentImporter.importXMPContent(file);
+
+ // First try xmp import, if empty try pdf import, otherwise create empty entry
+ if (!xmpEntriesInFile.isEmpty()) {
+ if (!pdfResult.isEmpty()) {
+ //FIXME: Show merge dialog?
+ entriesToAdd = xmpEntriesInFile;
+ } else {
+ entriesToAdd = xmpEntriesInFile;
+ }
+ } else {
+ if (!pdfResult.isEmpty()) {
+ entriesToAdd = pdfResult;
+ } else {
+ entriesToAdd = Collections.singletonList(createEmptyEntryWithLink(file));
+ }
+ }
+ } else {
+ entriesToAdd = Collections.singletonList(createEmptyEntryWithLink(file));
+ }
+
+ insertEntries(entriesToAdd);
+ entriesToAdd.forEach(entry -> ce.addEdit(new UndoableInsertEntry(database.getDatabase(), entry)));
+ }
+ ce.end();
+ undoManager.addEdit(ce);
+ }
+
+ private BibEntry createEmptyEntryWithLink(Path file) {
+ BibEntry entry = new BibEntry();
+ entry.setField(FieldName.TITLE, file.getFileName().toString());
+ linker.addFilesToEntry(entry, Collections.singletonList(file));
+ return entry;
+ }
+
+ public void importEntriesFromBibFiles(Path bibFile) {
+ List entriesToImport = contentImporter.importFromBibFile(bibFile, fileUpdateMonitor);
+ insertEntries(entriesToImport);
+ }
+
+ private void insertEntries(List entries) {
+ database.getDatabase().insertEntries(entries);
+
+ if (Globals.prefs.getBoolean(JabRefPreferences.USE_OWNER)) {
+ // Set owner field to default value
+ UpdateField.setAutomaticFields(entries, true, true, updateFieldPreferences);
+ }
+ }
+}
diff --git a/src/main/java/org/jabref/gui/externalfiles/NewDroppedFileHandler.java b/src/main/java/org/jabref/gui/externalfiles/NewDroppedFileHandler.java
deleted file mode 100644
index 77cfd682642..00000000000
--- a/src/main/java/org/jabref/gui/externalfiles/NewDroppedFileHandler.java
+++ /dev/null
@@ -1,152 +0,0 @@
-package org.jabref.gui.externalfiles;
-
-import java.io.IOException;
-import java.nio.file.Path;
-import java.util.Arrays;
-import java.util.List;
-import java.util.Optional;
-
-import javafx.scene.control.ButtonBar.ButtonData;
-import javafx.scene.control.ButtonType;
-import javafx.scene.control.DialogPane;
-import javafx.scene.control.TextArea;
-import javafx.scene.layout.VBox;
-import javafx.scene.text.Text;
-
-import org.jabref.Globals;
-import org.jabref.gui.DialogService;
-import org.jabref.gui.externalfiletype.ExternalFileTypes;
-import org.jabref.logic.externalfiles.ExternalFilesContentImporter;
-import org.jabref.logic.importer.ImportFormatPreferences;
-import org.jabref.logic.l10n.Localization;
-import org.jabref.logic.util.UpdateField;
-import org.jabref.logic.util.UpdateFieldPreferences;
-import org.jabref.logic.util.io.FileUtil;
-import org.jabref.model.database.BibDatabaseContext;
-import org.jabref.model.entry.BibEntry;
-import org.jabref.model.metadata.FilePreferences;
-import org.jabref.model.util.FileUpdateMonitor;
-import org.jabref.preferences.JabRefPreferences;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class NewDroppedFileHandler {
-
- private static final Logger LOGGER = LoggerFactory.getLogger(NewDroppedFileHandler.class);
-
- private final BibDatabaseContext bibDatabaseContext;
- private final UpdateFieldPreferences updateFieldPreferences;
- private final DialogService dialogService;
- private final FileUpdateMonitor fileUpdateMonitor;
- private final ExternalFilesEntryLinker linker;
- private final ExternalFilesContentImporter contentImporter;
-
- public NewDroppedFileHandler(DialogService dialogService,
- BibDatabaseContext bibDatabaseContext,
- ExternalFileTypes externalFileTypes,
- FilePreferences filePreferences,
- ImportFormatPreferences importFormatPreferences,
- UpdateFieldPreferences updateFieldPreferences,
- FileUpdateMonitor fileupdateMonitor) {
-
- this.dialogService = dialogService;
- this.bibDatabaseContext = bibDatabaseContext;
- this.updateFieldPreferences = updateFieldPreferences;
- this.fileUpdateMonitor = fileupdateMonitor;
-
- this.linker = new ExternalFilesEntryLinker(externalFileTypes, filePreferences, bibDatabaseContext);
- this.contentImporter = new ExternalFilesContentImporter(importFormatPreferences);
- }
-
- public void addNewEntryFromXMPorPDFContent(BibEntry entry, List files) {
-
- for (Path file : files) {
-
- if (FileUtil.getFileExtension(file).filter(ext -> "pdf".equals(ext)).isPresent()) {
-
- try {
- List pdfResult = contentImporter.importPDFContent(file);
- //FIXME: Show merge dialog if working again properly
- List xmpEntriesInFile = contentImporter.importXMPContent(file);
-
- //First try xmp import, if empty try pdf import, otherwise show dialog
- if (xmpEntriesInFile.isEmpty()) {
- if (pdfResult.isEmpty()) {
- addToEntryRenameAndMoveToFileDir(entry, files);
- } else {
- showImportOrLinkFileDialog(pdfResult, file, entry);
- }
- } else {
- showImportOrLinkFileDialog(xmpEntriesInFile, file, entry);
- }
-
- } catch (IOException e) {
- LOGGER.warn("Problem reading XMP", e);
- }
-
- } else {
- addToEntryRenameAndMoveToFileDir(entry, files);
- }
- }
- }
-
- public void importEntriesFromDroppedBibFiles(Path bibFile) {
-
- List entriesToImport = contentImporter.importFromBibFile(bibFile, fileUpdateMonitor);
- bibDatabaseContext.getDatabase().insertEntries(entriesToImport);
-
- if (Globals.prefs.getBoolean(JabRefPreferences.USE_OWNER)) {
- // Set owner field to default value
- UpdateField.setAutomaticFields(entriesToImport, true, true, updateFieldPreferences);
- }
- }
-
- private void showImportOrLinkFileDialog(List entriesToImport, Path fileName, BibEntry entryToLink) {
-
- DialogPane pane = new DialogPane();
-
- VBox vbox = new VBox();
- Text text = new Text(Localization.lang("The PDF contains one or several BibTeX-records.")
- + "\n" + Localization.lang("Do you want to import these as new entries into the current library or do you want to link the file to the entry?"));
- vbox.getChildren().add(text);
-
- entriesToImport.forEach(entry -> {
- TextArea textArea = new TextArea(entry.toString());
- textArea.setEditable(false);
- vbox.getChildren().add(textArea);
- });
- pane.setContent(vbox);
-
- ButtonType importButton = new ButtonType("Import into library", ButtonData.OK_DONE);
- ButtonType linkToEntry = new ButtonType("Link file to entry", ButtonData.OTHER);
-
- Optional buttonPressed = dialogService.showCustomDialogAndWait(Localization.lang("XMP-metadata found in PDF: %0", fileName.getFileName().toString()), pane, importButton, linkToEntry, ButtonType.CANCEL);
-
- if (buttonPressed.equals(Optional.of(importButton))) {
- bibDatabaseContext.getDatabase().insertEntries(entriesToImport);
- }
- if (buttonPressed.equals(Optional.of(linkToEntry))) {
- addToEntryRenameAndMoveToFileDir(entryToLink, Arrays.asList(fileName));
- }
- }
-
- public void addToEntryRenameAndMoveToFileDir(BibEntry entry, List files) {
- linker.addFilesToEntry(entry, files);
- linker.moveLinkedFilesToFileDir(entry);
- linker.renameLinkedFilesToPattern(entry);
- }
-
- public void copyFilesToFileDirAndAddToEntry(BibEntry entry, List files) {
- for (Path file : files) {
- linker.copyFileToFileDir(file).ifPresent(copiedFile -> {
- linker.addFilesToEntry(entry, files);
- });
- }
- }
-
- public void addToEntry(BibEntry entry, List files) {
- linker.addFilesToEntry(entry, files);
- }
-
-}
diff --git a/src/main/java/org/jabref/gui/externalfiletype/ExternalFileTypes.java b/src/main/java/org/jabref/gui/externalfiletype/ExternalFileTypes.java
index 1a2d2fda146..7e7d2836f1b 100644
--- a/src/main/java/org/jabref/gui/externalfiletype/ExternalFileTypes.java
+++ b/src/main/java/org/jabref/gui/externalfiletype/ExternalFileTypes.java
@@ -71,7 +71,8 @@ public Optional getExternalFileTypeByName(String name) {
* @return The ExternalFileType registered, or null if none.
*/
public Optional getExternalFileTypeByExt(String extension) {
- return externalFileTypes.stream().filter(type -> type.getExtension().equalsIgnoreCase(extension)).findFirst();
+ String extensionCleaned = extension.replace(".", "").replace("*", "");
+ return externalFileTypes.stream().filter(type -> type.getExtension().equalsIgnoreCase(extensionCleaned)).findFirst();
}
/**
diff --git a/src/main/java/org/jabref/gui/importer/EntryFromExternalFileCreator.java b/src/main/java/org/jabref/gui/importer/EntryFromExternalFileCreator.java
deleted file mode 100644
index 931dcb2bb00..00000000000
--- a/src/main/java/org/jabref/gui/importer/EntryFromExternalFileCreator.java
+++ /dev/null
@@ -1,36 +0,0 @@
-package org.jabref.gui.importer;
-
-import java.io.File;
-import java.util.Optional;
-
-import org.jabref.gui.externalfiletype.ExternalFileType;
-import org.jabref.model.entry.BibEntry;
-
-/** EntryCreator for any predefined ExternalFileType.
- * This Creator accepts all files with the extension defined in the ExternalFileType.
- */
-public class EntryFromExternalFileCreator extends EntryFromFileCreator {
-
- public EntryFromExternalFileCreator(ExternalFileType externalFileType) {
- super(externalFileType);
- }
-
- @Override
- public boolean accept(File f) {
- return f.getName().endsWith("." + externalFileType.getExtension());
- }
-
- @Override
- protected Optional createBibtexEntry(File file) {
- if (!accept(file)) {
- return Optional.empty();
- }
-
- return Optional.of(new BibEntry());
- }
-
- @Override
- public String getFormatName() {
- return externalFileType.getName();
- }
-}
diff --git a/src/main/java/org/jabref/gui/importer/EntryFromFileCreator.java b/src/main/java/org/jabref/gui/importer/EntryFromFileCreator.java
deleted file mode 100644
index 80264c77c00..00000000000
--- a/src/main/java/org/jabref/gui/importer/EntryFromFileCreator.java
+++ /dev/null
@@ -1,186 +0,0 @@
-package org.jabref.gui.importer;
-
-import java.io.File;
-import java.io.FileFilter;
-import java.nio.file.Path;
-import java.util.List;
-import java.util.Optional;
-import java.util.StringTokenizer;
-
-import org.jabref.Globals;
-import org.jabref.JabRefGUI;
-import org.jabref.gui.externalfiletype.ExternalFileType;
-import org.jabref.gui.externalfiletype.ExternalFileTypes;
-import org.jabref.gui.filelist.FileListEntry;
-import org.jabref.gui.filelist.FileListTableModel;
-import org.jabref.logic.util.io.FileUtil;
-import org.jabref.model.entry.BibEntry;
-import org.jabref.model.entry.FieldName;
-
-/**
- * The interface EntryFromFileCreator does twice:
- * On the one hand, it defines a set of files, which it can deal with, on the
- * other hand it provides the functionality to create a Bibtex entry out of a
- * file. The interface extends the java.io.FileFilter to inherit a common way of
- * defining file sets.
- */
-public abstract class EntryFromFileCreator implements FileFilter {
-
- private static final int MIN_PATH_TOKEN_LENGTH = 4;
-
- protected final ExternalFileType externalFileType;
-
- /**
- * Constructor.
- * Forces subclasses to provide an {@link ExternalFileType} instance, which
- * they build on.
- *
- * @param externalFileType
- */
- EntryFromFileCreator(ExternalFileType externalFileType) {
- this.externalFileType = externalFileType;
- }
-
- /**
- * Splits the path to the file and builds a keywords String in the format
- * that is used by Jabref.
- */
- private static String extractPathesToKeyWordsfield(String absolutePath) {
- StringBuilder sb = new StringBuilder();
- StringTokenizer st = new StringTokenizer(absolutePath, String.valueOf(File.separatorChar));
- while (st.hasMoreTokens()) {
- String token = st.nextToken();
- if (!st.hasMoreTokens()) {
- // ignore last token. The filename ist not wanted as keyword.
- break;
- }
- if (token.length() >= MIN_PATH_TOKEN_LENGTH) {
- if (sb.length() > 0) {
- // TODO: find Jabref constant for delimter
- sb.append(',');
- }
- sb.append(token);
- }
- }
- return sb.toString();
- }
-
- protected abstract Optional createBibtexEntry(File f);
-
- /**
- *
- * To support platform independence, a creator must define what types of
- * files it accepts on it's own.
- *
- *
- * Basically, accepting files which end with the file extension that is
- * described in the nested {@link #externalFileType} would work on windows
- * systems. This is also the recommended criterion, on which files should be
- * accepted.
- *
- *
- * However, defining what types of files this creator accepts, is a property
- * of entry creators, that is left to the user.
- *
- */
- @Override
- public abstract boolean accept(File f);
-
- /**
- * Name of this import format.
- *
- *
- * The name must be unique.
- *
- *
- * @return format name, must be unique and not null
- */
- public abstract String getFormatName();
-
- /**
- * Create one BibEntry containing information regarding the given File.
- *
- * @param f
- * @param addPathTokensAsKeywords
- * @return
- */
- public Optional createEntry(File f, boolean addPathTokensAsKeywords) {
- if ((f == null) || !f.exists()) {
- return Optional.empty();
- }
- Optional newEntry = createBibtexEntry(f);
-
- if (!(newEntry.isPresent())) {
- return newEntry;
- }
-
- if (addPathTokensAsKeywords) {
- appendToField(newEntry.get(), FieldName.KEYWORDS, extractPathesToKeyWordsfield(f.getAbsolutePath()));
- }
-
- if (!newEntry.get().hasField(FieldName.TITLE)) {
- newEntry.get().setField(FieldName.TITLE, f.getName());
- }
-
- addFileInfo(newEntry.get(), f);
- return newEntry;
- }
-
- /** Returns the ExternalFileType that is imported here */
- public ExternalFileType getExternalFileType() {
- return externalFileType;
- }
-
- private void addFileInfo(BibEntry entry, File file) {
- Optional fileType = ExternalFileTypes.getInstance()
- .getExternalFileTypeByExt(externalFileType.getFieldName());
-
- List possibleFilePaths = JabRefGUI.getMainFrame().getCurrentBasePanel().getBibDatabaseContext()
- .getFileDirectoriesAsPaths(Globals.prefs.getFilePreferences());
- Path shortenedFileName = FileUtil.relativize(file.toPath(), possibleFilePaths);
- FileListEntry fileListEntry = new FileListEntry("", shortenedFileName.toString(), fileType);
-
- FileListTableModel model = new FileListTableModel();
- model.addEntry(0, fileListEntry);
-
- entry.setField(FieldName.FILE, model.getStringRepresentation());
- }
-
- protected void appendToField(BibEntry entry, String field, String value) {
- if ((value == null) || value.isEmpty()) {
- return;
- }
- Optional oVal = entry.getField(field);
- if (oVal.isPresent()) {
- // TODO: find Jabref constant for delimter
- if (!oVal.get().contains(value)) {
- entry.setField(field, oVal.get() + "," + value);
- }
- } else {
- entry.setField(field, value);
- }
- }
-
- protected void addEntrysToEntry(BibEntry entry, List entrys) {
- if (entrys != null) {
- for (BibEntry e : entrys) {
- addEntryDataToEntry(entry, e);
- }
- }
- }
-
- protected void addEntryDataToEntry(BibEntry entry, BibEntry e) {
- for (String field : e.getFieldNames()) {
- e.getField(field).ifPresent(fieldContent -> appendToField(entry, field, fieldContent));
- }
- }
-
- @Override
- public String toString() {
- if (externalFileType == null) {
- return "(undefined)";
- }
- return externalFileType.getName() + " (." + externalFileType.getExtension() + ")";
- }
-
-}
diff --git a/src/main/java/org/jabref/gui/importer/EntryFromFileCreatorManager.java b/src/main/java/org/jabref/gui/importer/EntryFromFileCreatorManager.java
deleted file mode 100644
index 79b1d93f582..00000000000
--- a/src/main/java/org/jabref/gui/importer/EntryFromFileCreatorManager.java
+++ /dev/null
@@ -1,202 +0,0 @@
-package org.jabref.gui.importer;
-
-import java.io.File;
-import java.io.FileFilter;
-import java.nio.file.Files;
-import java.nio.file.Path;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.List;
-import java.util.Optional;
-
-import javax.swing.undo.CompoundEdit;
-
-import org.jabref.gui.BasePanel;
-import org.jabref.gui.externalfiletype.ExternalFileType;
-import org.jabref.gui.externalfiletype.ExternalFileTypes;
-import org.jabref.gui.undo.UndoableInsertEntry;
-import org.jabref.logic.l10n.Localization;
-import org.jabref.model.database.BibDatabase;
-import org.jabref.model.entry.BibEntry;
-import org.jabref.model.entry.EntryType;
-import org.jabref.model.entry.IdGenerator;
-
-/**
- * The class EntryFromFileCreatorManager manages entry creators.
- * The manager knows all existing implementations of the interface EntryFromFileCreator.
- * Given a file, the manager can then provide a creator, which is able to create a Bibtex entry for his file.
- * Knowing all implementations of the interface, the manager also knows the set of all files, of which Bibtex entries can be created.
- * The GUI uses this capability for offering the user only such files, of which entries could actually be created.
- *
- */
-public final class EntryFromFileCreatorManager {
-
- private final List entryCreators;
-
-
- public EntryFromFileCreatorManager(ExternalFileTypes externalFilesTypes) {
-
- entryCreators = new ArrayList<>(10);
- entryCreators.add(new EntryFromPDFCreator(externalFilesTypes));
-
- // add a creator for each ExternalFileType if there is no specialized
- // creator existing.
- Collection fileTypes = externalFilesTypes.getExternalFileTypeSelection();
-
- for (ExternalFileType exFileType : fileTypes) {
- if (!hasSpecialisedCreatorForExternalFileType(exFileType)) {
- entryCreators.add(new EntryFromExternalFileCreator(exFileType));
- }
- }
- }
-
- private boolean hasSpecialisedCreatorForExternalFileType(
- ExternalFileType externalFileType) {
- for (EntryFromFileCreator entryCreator : entryCreators) {
- if ((entryCreator.getExternalFileType() == null)
- || (entryCreator.getExternalFileType().getExtension().isEmpty())) {
- continue;
- }
- if (entryCreator.getExternalFileType().getExtension().equals(
- externalFileType.getExtension())) {
- return true;
- }
- }
- return false;
- }
-
- /**
- * Returns a {@link EntryFromFileCreator} object that is capable of creating a entry for the given file.
- *
- * @param file the external file
- * @return an empty optional if there is no EntryFromFileCreator for this file.
- */
- public Optional getEntryCreator(Path file) {
- if (!Files.exists(file)) {
- return Optional.empty();
- }
- for (EntryFromFileCreator creator : entryCreators) {
- if (creator.accept(file.toFile())) {
- return Optional.of(creator);
- }
- }
- return Optional.empty();
- }
-
- /**
- * Tries to add a entry for each file in the List.
- *
- * @param files
- * @param database
- * @param entryType
- * @return List of unexpected import event messages including failures.
- */
- public List addEntrysFromFiles(List files,
- BibDatabase database, EntryType entryType,
- boolean generateKeywordsFromPathToFile) {
- return addEntriesFromFiles(files, database, null, entryType, generateKeywordsFromPathToFile);
- }
-
- /**
- * Tries to add a entry for each file in the List.
- *
- * @return Returns a list of unexpected failures while importing
- */
- public List addEntriesFromFiles(List files,
- BibDatabase database, BasePanel panel, EntryType entryType,
- boolean generateKeywordsFromPathToFile) {
-
- List importGUIMessages = new ArrayList<>();
- int count = 0;
- CompoundEdit ce = new CompoundEdit();
- for (Path f : files) {
- Optional creator = getEntryCreator(f);
- if (!creator.isPresent()) {
- importGUIMessages.add("Problem importing " + f.toAbsolutePath() + ": Unknown filetype.");
- } else {
- Optional entry = creator.get().createEntry(f.toFile(), generateKeywordsFromPathToFile);
- if (!entry.isPresent()) {
- importGUIMessages.add("Problem importing " + f.toAbsolutePath() + ": Entry could not be created.");
- continue;
- }
- if (entryType != null) {
- entry.get().setType(entryType);
- }
- if (entry.get().getId() == null) {
- entry.get().setId(IdGenerator.next());
- }
- /*
- * TODO: database.insertEntry(BibEntry) is not sensible. Why
- * does 'true' mean "There were duplicates", while 'false' means
- * "Everything alright"?
- */
- if (!database.containsEntryWithId(entry.get().getId())) {
- // Work around SIDE EFFECT of creator.createEntry. The EntryFromPDFCreator also creates the entry in the table
- // Therefore, we only insert the entry if it is not already present
- if (database.insertEntry(entry.get())) {
- importGUIMessages.add("Problem importing " + f.toAbsolutePath() + ": Insert into BibDatabase failed.");
- } else {
- count++;
- if (panel != null) {
- ce.addEdit(new UndoableInsertEntry(database, entry.get()));
- }
- }
- }
- }
- }
-
- if ((count > 0) && (panel != null)) {
- ce.end();
- panel.getUndoManager().addEdit(ce);
- }
- return importGUIMessages;
-
- }
-
- /**
- * Returns a {@link FileFilter} instance which will accept all files, for
- * which a {@link EntryFromFileCreator} exists, that accepts the files.
- *
- * This {@link FileFilter} will be displayed in the GUI as
- * "All supported files".
- *
- * @return A {@link FileFilter} that accepts all files for which creators
- * exist.
- */
- private FileFilter getFileFilter() {
- return new FileFilter() {
-
- /**
- * Accepts all files, which are accepted by any known creator.
- */
- @Override
- public boolean accept(File file) {
- for (EntryFromFileCreator creator : entryCreators) {
- if (creator.accept(file)) {
- return true;
- }
- }
- return false;
- }
-
- @Override
- public String toString() {
- return Localization.lang("All external files");
- }
- };
- }
-
- /**
- * Returns a list of all {@link FileFilter} instances (i.e.
- * {@link EntryFromFileCreator}, plus the file filter that comes with the
- * {@link #getFileFilter()} method.
- *
- * @return A List of all known possible file filters.
- */
- public List getFileFilterList() {
- List filters = new ArrayList<>();
- filters.add(getFileFilter());
- filters.addAll(entryCreators);
- return filters;
- }
-}
diff --git a/src/main/java/org/jabref/gui/importer/EntryFromPDFCreator.java b/src/main/java/org/jabref/gui/importer/EntryFromPDFCreator.java
deleted file mode 100644
index 3c50b6823e6..00000000000
--- a/src/main/java/org/jabref/gui/importer/EntryFromPDFCreator.java
+++ /dev/null
@@ -1,62 +0,0 @@
-package org.jabref.gui.importer;
-
-import java.io.File;
-import java.util.Collections;
-import java.util.Locale;
-import java.util.Optional;
-
-import org.jabref.JabRefGUI;
-import org.jabref.gui.externalfiletype.ExternalFileType;
-import org.jabref.gui.externalfiletype.ExternalFileTypes;
-import org.jabref.gui.externalfiletype.StandardExternalFileType;
-import org.jabref.model.entry.BibEntry;
-import org.jabref.pdfimport.PdfImporter;
-import org.jabref.pdfimport.PdfImporter.ImportPdfFilesResult;
-
-/**
- * Uses XMPUtils to get one BibEntry for a PDF-File.
- * Also imports the non-XMP Data (PDDocument-Information) using XMPUtil.getBibtexEntryFromDocumentInformation.
- * If data from more than one entry is read by XMPUtil then this entys are merged into one.
- */
-public class EntryFromPDFCreator extends EntryFromFileCreator {
-
- public EntryFromPDFCreator(ExternalFileTypes externalFileTypes) {
- super(EntryFromPDFCreator.getPDFExternalFileType(externalFileTypes));
- }
-
- private static ExternalFileType getPDFExternalFileType(ExternalFileTypes externalFileTypes) {
- return externalFileTypes.getExternalFileTypeByExt("pdf")
- .orElse(StandardExternalFileType.PDF);
- }
-
- /**
- * Accepts all Files having as suffix ".PDF" (in ignore case mode).
- */
- @Override
- public boolean accept(File f) {
- return (f != null) && f.getName().toUpperCase(Locale.ROOT).endsWith(".PDF");
- }
-
- @Override
- protected Optional createBibtexEntry(File pdfFile) {
-
- if (!accept(pdfFile)) {
- return Optional.empty();
- }
-
- PdfImporter pi = new PdfImporter(JabRefGUI.getMainFrame(), JabRefGUI.getMainFrame().getCurrentBasePanel(), JabRefGUI.getMainFrame().getCurrentBasePanel().getMainTable(), -1);
- ImportPdfFilesResult res = pi.importPdfFiles(Collections.singletonList(pdfFile.toString()));
- if (res.getEntries().size() == 1) {
- return Optional.of(res.getEntries().get(0));
- } else {
- return Optional.empty();
- }
-
- }
-
- @Override
- public String getFormatName() {
- return "PDF";
- }
-
-}
diff --git a/src/main/java/org/jabref/gui/importer/ImportInspectionDialog.java b/src/main/java/org/jabref/gui/importer/ImportInspectionDialog.java
index 2ce86d731c4..6906a6e36cc 100644
--- a/src/main/java/org/jabref/gui/importer/ImportInspectionDialog.java
+++ b/src/main/java/org/jabref/gui/importer/ImportInspectionDialog.java
@@ -696,11 +696,11 @@ public void actionPerformed(ActionEvent event) {
if (entry.isGroupHit()) {
boolean continuePressed = DefaultTaskExecutor.runInJavaFXThread(() -> frame.getDialogService().showConfirmationDialogWithOptOutAndWait(Localization.lang("Duplicates found"),
- Localization.lang("There are possible duplicates (marked with an icon) that haven't been resolved. Continue?"),
- Localization.lang("Continue"),
- Localization.lang("Cancel"),
- Localization.lang("Disable this confirmation dialog"),
- optOut -> Globals.prefs.putBoolean(JabRefPreferences.WARN_ABOUT_DUPLICATES_IN_INSPECTION, !optOut)));
+ Localization.lang("There are possible duplicates (marked with an icon) that haven't been resolved. Continue?"),
+ Localization.lang("Continue"),
+ Localization.lang("Cancel"),
+ Localization.lang("Disable this confirmation dialog"),
+ optOut -> Globals.prefs.putBoolean(JabRefPreferences.WARN_ABOUT_DUPLICATES_IN_INSPECTION, !optOut)));
if (!continuePressed) {
return;
@@ -1072,7 +1072,6 @@ public void mousePressed(MouseEvent e) {
} finally {
entries.getReadWriteLock().writeLock().unlock();
}
-
} else if (result == DuplicateResolverResult.KEEP_RIGHT) {
// Remove the entry from the import inspection dialog.
entries.getReadWriteLock().writeLock().lock();
diff --git a/src/main/java/org/jabref/gui/importer/UnlinkedFilesCrawler.java b/src/main/java/org/jabref/gui/importer/UnlinkedFilesCrawler.java
index 77e57a12ab9..492656bb540 100644
--- a/src/main/java/org/jabref/gui/importer/UnlinkedFilesCrawler.java
+++ b/src/main/java/org/jabref/gui/importer/UnlinkedFilesCrawler.java
@@ -32,7 +32,7 @@ public UnlinkedFilesCrawler(Path directory, FileFilter fileFilter, BibDatabaseCo
}
@Override
- protected CheckBoxTreeItem call() throws Exception {
+ protected CheckBoxTreeItem call() {
UnlinkedPDFFileFilter unlinkedPDFFileFilter = new UnlinkedPDFFileFilter(fileFilter, databaseContext);
return searchDirectory(directory.toFile(), unlinkedPDFFileFilter);
}
@@ -40,8 +40,7 @@ protected CheckBoxTreeItem call() throws Exception {
/**
* Searches recursively all files in the specified directory.
*
- * All {@link File}s, which match the {@link FileFilter} that comes with the
- * {@link EntryFromFileCreatorManager}, are taken into the resulting tree.
+ * All files matched by the given {@link UnlinkedPDFFileFilter} are taken into the resulting tree.
*
* The result will be a tree structure of nodes of the type
* {@link CheckBoxTreeItem}.
diff --git a/src/main/java/org/jabref/gui/maintable/MainTable.java b/src/main/java/org/jabref/gui/maintable/MainTable.java
index 156370ec1c3..7ff9de40304 100644
--- a/src/main/java/org/jabref/gui/maintable/MainTable.java
+++ b/src/main/java/org/jabref/gui/maintable/MainTable.java
@@ -30,7 +30,7 @@
import org.jabref.gui.DragAndDropDataFormats;
import org.jabref.gui.GUIGlobals;
import org.jabref.gui.JabRefFrame;
-import org.jabref.gui.externalfiles.NewDroppedFileHandler;
+import org.jabref.gui.externalfiles.ImportHandler;
import org.jabref.gui.externalfiletype.ExternalFileTypes;
import org.jabref.gui.keyboard.KeyBinding;
import org.jabref.gui.keyboard.KeyBindingRepository;
@@ -59,7 +59,7 @@ public class MainTable extends TableView {
private final UndoManager undoManager;
private final MainTableDataModel model;
- private final NewDroppedFileHandler fileHandler;
+ private final ImportHandler importHandler;
private final CustomLocalDragboard localDragboard = GUIGlobals.localDragboard;
public MainTable(MainTableDataModel model, JabRefFrame frame,
@@ -71,13 +71,13 @@ public MainTable(MainTableDataModel model, JabRefFrame frame,
this.database = Objects.requireNonNull(database);
this.undoManager = panel.getUndoManager();
- fileHandler = new NewDroppedFileHandler(frame.getDialogService(), database, externalFileTypes,
- Globals.prefs.getFilePreferences(),
- Globals.prefs.getImportFormatPreferences(),
- Globals.prefs.getUpdateFieldPreferences(),
- Globals.getFileUpdateMonitor()
-
- );
+ importHandler = new ImportHandler(
+ frame.getDialogService(), database, externalFileTypes,
+ Globals.prefs.getFilePreferences(),
+ Globals.prefs.getImportFormatPreferences(),
+ Globals.prefs.getUpdateFieldPreferences(),
+ Globals.getFileUpdateMonitor(),
+ undoManager);
this.getColumns().addAll(new MainTableColumnFactory(database, preferences.getColumnPreferences(), externalFileTypes, panel.getUndoManager(), frame.getDialogService()).createColumns());
@@ -279,42 +279,37 @@ private void handleOnDragDetected(TableRow row, BibEntry
}
private void handleOnDragDropped(BibEntryTableViewModel originalItem, DragEvent event) {
-
boolean success = false;
if (event.getDragboard().hasContent(DataFormat.FILES)) {
-
List files = event.getDragboard().getFiles().stream().map(File::toPath).collect(Collectors.toList());
-
List bibFiles = files.stream().filter(FileUtil::isBibFile).collect(Collectors.toList());
if (!bibFiles.isEmpty()) {
+ // Import all bibtex entries contained in the dropped bib files
for (Path file : bibFiles) {
- fileHandler.importEntriesFromDroppedBibFiles(file);
+ importHandler.importEntriesFromBibFiles(file);
}
success = true;
-
}
if (event.getGestureTarget() instanceof TableRow) {
-
+ // Depending on the pressed modifier, import as new entries or link to drop target
BibEntry entry = originalItem.getEntry();
-
if ((event.getTransferMode() == TransferMode.MOVE)) {
-
LOGGER.debug("Mode MOVE"); //shift on win or no modifier
- fileHandler.addNewEntryFromXMPorPDFContent(entry, files);
+ importHandler.importAsNewEntries(files);
success = true;
}
if (event.getTransferMode() == TransferMode.LINK) {
LOGGER.debug("LINK"); //alt on win
- fileHandler.addToEntryRenameAndMoveToFileDir(entry, files);
+ importHandler.getLinker().moveFilesToFileDirAndAddToEntry(entry, files);
success = true;
-
}
+
if (event.getTransferMode() == TransferMode.COPY) {
LOGGER.debug("Mode Copy"); //ctrl on win
- fileHandler.copyFilesToFileDirAndAddToEntry(entry, files);
+ importHandler.getLinker().copyFilesToFileDirAndAddToEntry(entry, files);
success = true;
}
}
@@ -322,7 +317,6 @@ private void handleOnDragDropped(BibEntryTableViewModel originalItem, DragEvent
event.setDropCompleted(success);
event.consume();
-
}
public void addSelectionListener(ListChangeListener super BibEntryTableViewModel> listener) {
diff --git a/src/main/java/org/jabref/gui/maintable/PersistenceVisualStateTable.java b/src/main/java/org/jabref/gui/maintable/PersistenceVisualStateTable.java
index eb25588f568..8ee6bd949d1 100644
--- a/src/main/java/org/jabref/gui/maintable/PersistenceVisualStateTable.java
+++ b/src/main/java/org/jabref/gui/maintable/PersistenceVisualStateTable.java
@@ -66,7 +66,7 @@ private void updateColumnPreferences() {
}
if (columnNames.size() == columnsWidths.size() &&
- columnNames.size() == preferences.getStringList(preferences.COLUMN_NAMES).size()) {
+ columnNames.size() == preferences.getStringList(JabRefPreferences.COLUMN_NAMES).size()) {
preferences.putStringList(JabRefPreferences.COLUMN_NAMES, columnNames);
preferences.putStringList(JabRefPreferences.COLUMN_WIDTHS, columnsWidths);
}
diff --git a/src/main/java/org/jabref/gui/openoffice/AdvancedCiteDialog.fxml b/src/main/java/org/jabref/gui/openoffice/AdvancedCiteDialog.fxml
index 1127c2e08d7..582431c5913 100644
--- a/src/main/java/org/jabref/gui/openoffice/AdvancedCiteDialog.fxml
+++ b/src/main/java/org/jabref/gui/openoffice/AdvancedCiteDialog.fxml
@@ -6,25 +6,26 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/src/main/java/org/jabref/gui/openoffice/AdvancedCiteDialogView.java b/src/main/java/org/jabref/gui/openoffice/AdvancedCiteDialogView.java
index f12e34fcdbe..f11e8ab90ae 100644
--- a/src/main/java/org/jabref/gui/openoffice/AdvancedCiteDialogView.java
+++ b/src/main/java/org/jabref/gui/openoffice/AdvancedCiteDialogView.java
@@ -41,6 +41,5 @@ private void initialize() {
inPar.selectedProperty().bindBidirectional(viewModel.citeInParProperty());
inText.selectedProperty().bindBidirectional(viewModel.citeInTextProperty());
pageInfo.textProperty().bindBidirectional(viewModel.pageInfoProperty());
-
}
}
diff --git a/src/main/java/org/jabref/gui/openoffice/CitationEntryViewModel.java b/src/main/java/org/jabref/gui/openoffice/CitationEntryViewModel.java
index 58ac9f04ecd..028990a6bc8 100644
--- a/src/main/java/org/jabref/gui/openoffice/CitationEntryViewModel.java
+++ b/src/main/java/org/jabref/gui/openoffice/CitationEntryViewModel.java
@@ -36,5 +36,4 @@ public StringProperty extraInformationProperty() {
public void setExtraInfo(String extraInfo) {
extraInformation.setValue(extraInfo);
}
-
}
diff --git a/src/main/java/org/jabref/gui/openoffice/DetectOpenOfficeInstallation.java b/src/main/java/org/jabref/gui/openoffice/DetectOpenOfficeInstallation.java
index 1f4a892f14a..c4e8e47885a 100644
--- a/src/main/java/org/jabref/gui/openoffice/DetectOpenOfficeInstallation.java
+++ b/src/main/java/org/jabref/gui/openoffice/DetectOpenOfficeInstallation.java
@@ -46,10 +46,10 @@ private Optional selectInstallationPath() {
final NativeDesktop nativeDesktop = JabRefDesktop.getNativeDesktop();
dialogService.showInformationDialogAndWait(Localization.lang("Could not find OpenOffice/LibreOffice installation"),
- Localization.lang("Unable to autodetect OpenOffice/LibreOffice installation. Please choose the installation directory manually."));
+ Localization.lang("Unable to autodetect OpenOffice/LibreOffice installation. Please choose the installation directory manually."));
DirectoryDialogConfiguration dirDialogConfiguration = new DirectoryDialogConfiguration.Builder()
- .withInitialDirectory(nativeDesktop.getApplicationDirectory())
- .build();
+ .withInitialDirectory(nativeDesktop.getApplicationDirectory())
+ .build();
return dialogService.showDirectorySelectionDialog(dirDialogConfiguration);
}
@@ -113,10 +113,10 @@ private Optional chooseAmongInstallations(List installDirs) {
}
String content = Localization.lang("Found more than one OpenOffice/LibreOffice executable.")
- + "\n" + Localization.lang("Please choose which one to connect to:");
+ + "\n" + Localization.lang("Please choose which one to connect to:");
Optional selectedPath = dialogService.showChoiceDialogAndWait(Localization.lang("Choose OpenOffice/LibreOffice executable"),
- content, Localization.lang("Use selected instance"), installDirs);
+ content, Localization.lang("Use selected instance"), installDirs);
return selectedPath;
}
diff --git a/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialog.fxml b/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialog.fxml
index bde42841ce5..b76aabee96e 100644
--- a/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialog.fxml
+++ b/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialog.fxml
@@ -4,18 +4,19 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogView.java b/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogView.java
index 1f50783e89f..a312a4ef375 100644
--- a/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogView.java
+++ b/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogView.java
@@ -41,7 +41,6 @@ public class ManageCitationsDialogView extends BaseDialog {
public ManageCitationsDialogView(OOBibBase ooBase) {
this.ooBase = ooBase;
-
ViewLoader.view(this)
.load()
.setAsDialogPane(this);
@@ -75,14 +74,13 @@ private void initialize() throws NoSuchElementException, WrappedTargetException,
cell.getRowValue().setExtraInfo(cell.getNewValue());
});
extraInfo.setCellFactory(TextFieldTableCell.forTableColumn());
-
}
private Node getText(String citationContext) {
String inBetween = StringUtil.substringBetween(citationContext, HTML_BOLD_START_TAG, HTML_BOLD_END_TAG);
String start = citationContext.substring(0, citationContext.indexOf(HTML_BOLD_START_TAG));
- String end = citationContext.substring(citationContext.lastIndexOf(HTML_BOLD_END_TAG) + HTML_BOLD_END_TAG.length(), citationContext.length());
+ String end = citationContext.substring(citationContext.lastIndexOf(HTML_BOLD_END_TAG) + HTML_BOLD_END_TAG.length());
Text startText = new Text(start);
Text inBetweenText = new Text(inBetween);
diff --git a/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogViewModel.java b/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogViewModel.java
index e928f5ee673..55d532caa62 100644
--- a/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogViewModel.java
+++ b/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogViewModel.java
@@ -40,13 +40,12 @@ public ManageCitationsDialogViewModel(OOBibBase ooBase, DialogService dialogServ
for (String name : names) {
CitationEntry entry = new CitationEntry(name,
- ooBase.getCitationContext(nameAccess, name, 30, 30, true),
- ooBase.getCustomProperty(name));
+ ooBase.getCitationContext(nameAccess, name, 30, 30, true),
+ ooBase.getCustomProperty(name));
CitationEntryViewModel itemViewModelEntry = new CitationEntryViewModel(entry);
citations.add(itemViewModelEntry);
}
-
}
public void storeSettings() {
@@ -59,7 +58,7 @@ public void storeSettings() {
}
}
} catch (UnknownPropertyException | NotRemoveableException | PropertyExistException | IllegalTypeException |
- IllegalArgumentException ex) {
+ IllegalArgumentException ex) {
LOGGER.warn("Problem modifying citation", ex);
dialogService.showErrorDialogAndWait(Localization.lang("Problem modifying citation"), ex);
}
@@ -68,6 +67,5 @@ public void storeSettings() {
public ListProperty citationsProperty() {
return citations;
}
-
}
diff --git a/src/main/java/org/jabref/gui/openoffice/ManualConnectDialog.fxml b/src/main/java/org/jabref/gui/openoffice/ManualConnectDialog.fxml
index 751462763d6..34c8b060fdb 100644
--- a/src/main/java/org/jabref/gui/openoffice/ManualConnectDialog.fxml
+++ b/src/main/java/org/jabref/gui/openoffice/ManualConnectDialog.fxml
@@ -1,5 +1,6 @@
+
@@ -8,36 +9,41 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
-
+
diff --git a/src/main/java/org/jabref/gui/openoffice/ManualConnectDialogView.java b/src/main/java/org/jabref/gui/openoffice/ManualConnectDialogView.java
index 5352cf97198..5e7a2e7649a 100644
--- a/src/main/java/org/jabref/gui/openoffice/ManualConnectDialogView.java
+++ b/src/main/java/org/jabref/gui/openoffice/ManualConnectDialogView.java
@@ -19,6 +19,7 @@
public class ManualConnectDialogView extends BaseDialog {
+ @Inject private final DialogService dialogService;
@FXML private Label OOPathLabel;
@FXML private TextField ooPath;
@FXML private Button browseOOPath;
@@ -28,10 +29,7 @@ public class ManualConnectDialogView extends BaseDialog {
@FXML private TextField ooJars;
@FXML private Label ooExecLabel;
@FXML private Label ooJarsLabel;
-
@Inject private PreferencesService preferencesService;
- @Inject private final DialogService dialogService;
-
private ManualConnectDialogViewModel viewModel;
public ManualConnectDialogView(DialogService dialogService) {
@@ -86,5 +84,4 @@ private void browseOOExec(ActionEvent event) {
private void browseOOJars(ActionEvent event) {
viewModel.browseOOJars();
}
-
}
diff --git a/src/main/java/org/jabref/gui/openoffice/ManualConnectDialogViewModel.java b/src/main/java/org/jabref/gui/openoffice/ManualConnectDialogViewModel.java
index c628484296e..9789b717978 100644
--- a/src/main/java/org/jabref/gui/openoffice/ManualConnectDialogViewModel.java
+++ b/src/main/java/org/jabref/gui/openoffice/ManualConnectDialogViewModel.java
@@ -34,11 +34,11 @@ public ManualConnectDialogViewModel(PreferencesService preferencesService, Dialo
ooJarsProperty().setValue(ooPreferences.getJarsPath());
dirDialogConfiguration = new DirectoryDialogConfiguration.Builder()
- .withInitialDirectory(nativeDesktop.getApplicationDirectory())
- .build();
+ .withInitialDirectory(nativeDesktop.getApplicationDirectory())
+ .build();
fileDialogConfiguration = new FileDialogConfiguration.Builder()
- .withInitialDirectory(nativeDesktop.getApplicationDirectory())
- .build();
+ .withInitialDirectory(nativeDesktop.getApplicationDirectory())
+ .build();
}
public void browseOOPath() {
@@ -47,7 +47,6 @@ public void browseOOPath() {
public void browseOOExec() {
dialogService.showFileOpenDialog(fileDialogConfiguration).ifPresent(f -> ooExec.setValue(f.toAbsolutePath().toString()));
-
}
public void browseOOJars() {
@@ -75,5 +74,4 @@ public void save() {
preferencesService.setOpenOfficePreferences(ooPreferences);
}
-
}
diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java
index 560eaf1fe87..39f99b03e9c 100644
--- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java
+++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java
@@ -136,8 +136,8 @@ class OOBibBase {
private List sortedReferenceMarks;
public OOBibBase(String pathToOO, boolean atEnd) throws IOException, IllegalAccessException,
- InvocationTargetException, BootstrapException, CreationException, UnknownPropertyException,
- WrappedTargetException, IndexOutOfBoundsException, NoSuchElementException, NoDocumentException {
+ InvocationTargetException, BootstrapException, CreationException, UnknownPropertyException,
+ WrappedTargetException, IndexOutOfBoundsException, NoSuchElementException, NoDocumentException {
authorYearTitleList.add(authComp);
authorYearTitleList.add(yearComp);
authorYearTitleList.add(titleComp);
@@ -158,13 +158,33 @@ public boolean isConnectedToDocument() {
return xCurrentComponent != null;
}
+ public static XTextDocument selectComponent(List list)
+ throws UnknownPropertyException, WrappedTargetException, IndexOutOfBoundsException {
+ String[] values = new String[list.size()];
+ int ii = 0;
+ for (XTextDocument doc : list) {
+ values[ii] = String.valueOf(OOUtil.getProperty(doc.getCurrentController().getFrame(), "Title"));
+ ii++;
+ }
+ JList sel = new JList<>(values);
+ sel.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
+ sel.setSelectedIndex(0);
+ int ans = JOptionPane.showConfirmDialog(null, new JScrollPane(sel), Localization.lang("Select document"),
+ JOptionPane.OK_CANCEL_OPTION);
+ if (ans == JOptionPane.OK_OPTION) {
+ return list.get(sel.getSelectedIndex());
+ } else {
+ return null;
+ }
+ }
+
public Optional getCurrentDocumentTitle() {
if (mxDoc == null) {
return Optional.empty();
} else {
try {
return Optional
- .of(String.valueOf(OOUtil.getProperty(mxDoc.getCurrentController().getFrame(), "Title")));
+ .of(String.valueOf(OOUtil.getProperty(mxDoc.getCurrentController().getFrame(), "Title")));
} catch (UnknownPropertyException | WrappedTargetException e) {
LOGGER.warn("Could not get document title", e);
return Optional.empty();
@@ -173,7 +193,7 @@ public Optional getCurrentDocumentTitle() {
}
public void selectDocument() throws UnknownPropertyException, WrappedTargetException, IndexOutOfBoundsException,
- NoSuchElementException, NoDocumentException {
+ NoSuchElementException, NoDocumentException {
List textDocumentList = getTextDocuments();
XTextDocument selected;
if (textDocumentList.isEmpty()) {
@@ -211,9 +231,27 @@ public void selectDocument() throws UnknownPropertyException, WrappedTargetExcep
}
+ private List getTextDocuments() throws NoSuchElementException, WrappedTargetException {
+ List result = new ArrayList<>();
+ XEnumerationAccess enumAccess = xDesktop.getComponents();
+ XEnumeration componentEnumeration = enumAccess.createEnumeration();
+
+ // TODO: http://api.openoffice.org/docs/DevelopersGuide/OfficeDev/OfficeDev.xhtml#1_1_3_2_1_2_Frame_Hierarchies
+
+ while (componentEnumeration.hasMoreElements()) {
+ Object nextElement = componentEnumeration.nextElement();
+ XComponent component = UnoRuntime.queryInterface(XComponent.class, nextElement);
+ XTextDocument document = UnoRuntime.queryInterface(XTextDocument.class, component);
+ if (document != null) {
+ result.add(document);
+ }
+ }
+ return result;
+ }
+
private XDesktop simpleBootstrap(String pathToExecutable)
- throws IllegalAccessException, InvocationTargetException, BootstrapException,
- CreationException, IOException {
+ throws IllegalAccessException, InvocationTargetException, BootstrapException,
+ CreationException, IOException {
ClassLoader loader = ClassLoader.getSystemClassLoader();
if (loader instanceof URLClassLoader) {
@@ -230,7 +268,7 @@ private XDesktop simpleBootstrap(String pathToExecutable)
}
} else {
LOGGER.error("Error occured, URLClassLoader expected but " + loader.getClass()
- + " received. Could not continue.");
+ + " received. Could not continue.");
}
//Get the office component context:
@@ -252,44 +290,26 @@ private XDesktop simpleBootstrap(String pathToExecutable)
return resultDesktop;
}
- private List getTextDocuments() throws NoSuchElementException, WrappedTargetException {
- List result = new ArrayList<>();
- XEnumerationAccess enumAccess = xDesktop.getComponents();
- XEnumeration componentEnumeration = enumAccess.createEnumeration();
-
- // TODO: http://api.openoffice.org/docs/DevelopersGuide/OfficeDev/OfficeDev.xhtml#1_1_3_2_1_2_Frame_Hierarchies
-
- while (componentEnumeration.hasMoreElements()) {
- Object nextElement = componentEnumeration.nextElement();
- XComponent component = UnoRuntime.queryInterface(XComponent.class, nextElement);
- XTextDocument document = UnoRuntime.queryInterface(XTextDocument.class, component);
- if (document != null) {
- result.add(document);
- }
+ public Optional getCustomProperty(String property) throws UnknownPropertyException, WrappedTargetException {
+ if (propertySet.getPropertySetInfo().hasPropertyByName(property)) {
+ return Optional.ofNullable(propertySet.getPropertyValue(property).toString());
}
- return result;
+ return Optional.empty();
+ }
+
+ public void updateSortedReferenceMarks() throws WrappedTargetException, NoSuchElementException {
+ sortedReferenceMarks = getSortedReferenceMarks(getReferenceMarks());
}
public void setCustomProperty(String property, String value) throws UnknownPropertyException,
- NotRemoveableException, PropertyExistException, IllegalTypeException, IllegalArgumentException {
+ NotRemoveableException, PropertyExistException, IllegalTypeException, IllegalArgumentException {
if (propertySet.getPropertySetInfo().hasPropertyByName(property)) {
userProperties.removeProperty(property);
}
if (value != null) {
userProperties.addProperty(property, com.sun.star.beans.PropertyAttribute.REMOVEABLE,
- new Any(Type.STRING, value));
- }
- }
-
- public Optional getCustomProperty(String property) throws UnknownPropertyException, WrappedTargetException {
- if (propertySet.getPropertySetInfo().hasPropertyByName(property)) {
- return Optional.ofNullable(propertySet.getPropertyValue(property).toString());
+ new Any(Type.STRING, value));
}
- return Optional.empty();
- }
-
- public void updateSortedReferenceMarks() throws WrappedTargetException, NoSuchElementException {
- sortedReferenceMarks = getSortedReferenceMarks(getReferenceMarks());
}
/**
@@ -319,10 +339,10 @@ public void updateSortedReferenceMarks() throws WrappedTargetException, NoSuchEl
public void insertEntry(List entries, BibDatabase database,
List allBases, OOBibStyle style,
boolean inParenthesis, boolean withText, String pageInfo, boolean sync)
- throws IllegalArgumentException,
- UnknownPropertyException, NotRemoveableException, PropertyExistException, IllegalTypeException,
- UndefinedCharacterFormatException, WrappedTargetException, NoSuchElementException, PropertyVetoException,
- IOException, CreationException, BibEntryNotFoundException, UndefinedParagraphFormatException {
+ throws IllegalArgumentException,
+ UnknownPropertyException, NotRemoveableException, PropertyExistException, IllegalTypeException,
+ UndefinedCharacterFormatException, WrappedTargetException, NoSuchElementException, PropertyVetoException,
+ IOException, CreationException, BibEntryNotFoundException, UndefinedParagraphFormatException {
try {
@@ -337,10 +357,10 @@ public void insertEntry(List entries, BibDatabase database,
}
String keyString = String.join(",",
- entries.stream().map(entry -> entry.getCiteKeyOptional().orElse("")).collect(Collectors.toList()));
+ entries.stream().map(entry -> entry.getCiteKeyOptional().orElse("")).collect(Collectors.toList()));
// Insert bookmark:
String bName = getUniqueReferenceMarkName(keyString,
- withText ? inParenthesis ? OOBibBase.AUTHORYEAR_PAR : OOBibBase.AUTHORYEAR_INTEXT : OOBibBase.INVISIBLE_CIT);
+ withText ? inParenthesis ? OOBibBase.AUTHORYEAR_PAR : OOBibBase.AUTHORYEAR_INTEXT : OOBibBase.INVISIBLE_CIT);
// If we should store metadata for page info, do that now:
if (pageInfo != null) {
@@ -355,7 +375,7 @@ public void insertEntry(List entries, BibDatabase database,
try {
xCursorProps.setPropertyValue(CHAR_STYLE_NAME, charStyle);
} catch (UnknownPropertyException | PropertyVetoException | IllegalArgumentException |
- WrappedTargetException ex) {
+ WrappedTargetException ex) {
// Setting the character format failed, so we throw an exception that
// will result in an error message for the user. Before that,
// delete the space we inserted:
@@ -370,7 +390,7 @@ public void insertEntry(List entries, BibDatabase database,
databaseMap.put(entry, database);
}
String citeText = style.isNumberEntries() ? "-" : style.getCitationMarker(entries, databaseMap,
- inParenthesis, null, null);
+ inParenthesis, null, null);
insertReferenceMark(bName, citeText, xViewCursor, withText, style);
xViewCursor.collapseToEnd();
@@ -397,6 +417,20 @@ public void insertEntry(List entries, BibDatabase database,
}
}
+ public List getJabRefReferenceMarks(XNameAccess nameAccess) {
+ String[] names = nameAccess.getElementNames();
+ // Remove all reference marks that don't look like JabRef citations:
+ List result = new ArrayList<>();
+ if (names != null) {
+ for (String name : names) {
+ if (CITE_PATTERN.matcher(name).find()) {
+ result.add(name);
+ }
+ }
+ }
+ return result;
+ }
+
/**
* Refresh all cite markers in the document.
* @param databases The databases to get entries from.
@@ -413,9 +447,9 @@ public void insertEntry(List entries, BibDatabase database,
* @throws UnknownPropertyException
*/
public List refreshCiteMarkers(List databases, OOBibStyle style)
- throws WrappedTargetException, IllegalArgumentException, NoSuchElementException,
- UndefinedCharacterFormatException, UnknownPropertyException, PropertyVetoException, IOException,
- CreationException, BibEntryNotFoundException {
+ throws WrappedTargetException, IllegalArgumentException, NoSuchElementException,
+ UndefinedCharacterFormatException, UnknownPropertyException, PropertyVetoException, IOException,
+ CreationException, BibEntryNotFoundException {
try {
return refreshCiteMarkersInternal(databases, style);
} catch (DisposedException ex) {
@@ -426,24 +460,10 @@ public List refreshCiteMarkers(List databases, OOBibStyle s
}
}
- public List getJabRefReferenceMarks(XNameAccess nameAccess) {
- String[] names = nameAccess.getElementNames();
- // Remove all reference marks that don't look like JabRef citations:
- List result = new ArrayList<>();
- if (names != null) {
- for (String name : names) {
- if (CITE_PATTERN.matcher(name).find()) {
- result.add(name);
- }
- }
- }
- return result;
- }
-
private List refreshCiteMarkersInternal(List databases, OOBibStyle style)
- throws WrappedTargetException, IllegalArgumentException, NoSuchElementException,
- UndefinedCharacterFormatException, UnknownPropertyException, PropertyVetoException,
- CreationException, BibEntryNotFoundException {
+ throws WrappedTargetException, IllegalArgumentException, NoSuchElementException,
+ UndefinedCharacterFormatException, UnknownPropertyException, PropertyVetoException,
+ CreationException, BibEntryNotFoundException {
List cited = findCitedKeys();
Map linkSourceBase = new HashMap<>();
@@ -550,7 +570,7 @@ private List refreshCiteMarkersInternal(List databases, OOB
citationMarker = style.getNumCitationMarker(num, minGroupingCount, false);
for (int j = 0; j < keys.length; j++) {
normCitMarker[j] = style.getNumCitationMarker(Collections.singletonList(num.get(j)),
- minGroupingCount, false);
+ minGroupingCount, false);
}
} else {
// We need to find the number of the cited entry in the bibliography,
@@ -559,7 +579,7 @@ private List refreshCiteMarkersInternal(List databases, OOB
if (num.isEmpty()) {
throw new BibEntryNotFoundException(names.get(i), Localization
- .lang("Could not resolve BibTeX entry for citation marker '%0'.", names.get(i)));
+ .lang("Could not resolve BibTeX entry for citation marker '%0'.", names.get(i)));
} else {
citationMarker = style.getNumCitationMarker(num, minGroupingCount, false);
}
@@ -585,11 +605,11 @@ private List refreshCiteMarkersInternal(List databases, OOB
}
citationMarker = style.getCitationMarker(Arrays.asList(cEntries), entries,
- type == OOBibBase.AUTHORYEAR_PAR, null, null);
+ type == OOBibBase.AUTHORYEAR_PAR, null, null);
// We need "normalized" (in parenthesis) markers for uniqueness checking purposes:
for (int j = 0; j < cEntries.length; j++) {
normCitMarker[j] = style.getCitationMarker(Collections.singletonList(cEntries[j]), entries,
- true, null, new int[] {-1});
+ true, null, new int[]{-1});
}
}
citMarkers[i] = citationMarker;
@@ -689,7 +709,7 @@ private List refreshCiteMarkersInternal(List databases, OOB
}
if (needsChange) {
citMarkers[j] = style.getCitationMarker(Arrays.asList(cEntries), entries,
- types[j] == OOBibBase.AUTHORYEAR_PAR, uniquif, firstLimAuthors);
+ types[j] == OOBibBase.AUTHORYEAR_PAR, uniquif, firstLimAuthors);
}
}
}
@@ -715,7 +735,7 @@ private List refreshCiteMarkersInternal(List databases, OOB
try {
xCursorProps.setPropertyValue(CHAR_STYLE_NAME, charStyle);
} catch (UnknownPropertyException | PropertyVetoException | IllegalArgumentException |
- WrappedTargetException ex) {
+ WrappedTargetException ex) {
throw new UndefinedCharacterFormatException(charStyle);
}
}
@@ -745,9 +765,9 @@ private List refreshCiteMarkersInternal(List databases, OOB
}
private List getSortedReferenceMarks(final XNameAccess nameAccess)
- throws WrappedTargetException, NoSuchElementException {
+ throws WrappedTargetException, NoSuchElementException {
XTextViewCursorSupplier cursorSupplier = UnoRuntime.queryInterface(XTextViewCursorSupplier.class,
- mxDoc.getCurrentController());
+ mxDoc.getCurrentController());
XTextViewCursor viewCursor = cursorSupplier.getViewCursor();
XTextRange initialPos = viewCursor.getStart();
@@ -780,9 +800,25 @@ private List getSortedReferenceMarks(final XNameAccess nameAccess)
return result;
}
+ public XNameAccess getReferenceMarks() {
+ XReferenceMarksSupplier supplier = UnoRuntime.queryInterface(XReferenceMarksSupplier.class, xCurrentComponent);
+ return supplier.getReferenceMarks();
+ }
+
+ private String getUniqueReferenceMarkName(String bibtexKey, int type) {
+ XNameAccess xNamedRefMarks = getReferenceMarks();
+ int i = 0;
+ String name = OOBibBase.BIB_CITATION + '_' + type + '_' + bibtexKey;
+ while (xNamedRefMarks.hasByName(name)) {
+ name = OOBibBase.BIB_CITATION + i + '_' + type + '_' + bibtexKey;
+ i++;
+ }
+ return name;
+ }
+
public void rebuildBibTextSection(List databases, OOBibStyle style)
- throws NoSuchElementException, WrappedTargetException, IllegalArgumentException,
- CreationException, PropertyVetoException, UnknownPropertyException, UndefinedParagraphFormatException {
+ throws NoSuchElementException, WrappedTargetException, IllegalArgumentException,
+ CreationException, PropertyVetoException, UnknownPropertyException, UndefinedParagraphFormatException {
List cited = findCitedKeys();
Map linkSourceBase = new HashMap<>();
Map entries = findCitedEntries(databases, cited, linkSourceBase); // Although entries are redefined without use, this also updates linkSourceBase
@@ -795,7 +831,7 @@ public void rebuildBibTextSection(List databases, OOBibStyle style)
} else {
SortedMap newMap = new TreeMap<>(entryComparator);
for (Map.Entry bibtexEntryBibtexDatabaseEntry : findCitedEntries(databases, cited,
- linkSourceBase).entrySet()) {
+ linkSourceBase).entrySet()) {
newMap.put(bibtexEntryBibtexDatabaseEntry.getKey(), bibtexEntryBibtexDatabaseEntry.getValue());
}
entries = newMap;
@@ -804,20 +840,23 @@ public void rebuildBibTextSection(List databases, OOBibStyle style)
populateBibTextSection(entries, style);
}
- public XNameAccess getReferenceMarks() {
- XReferenceMarksSupplier supplier = UnoRuntime.queryInterface(XReferenceMarksSupplier.class, xCurrentComponent);
- return supplier.getReferenceMarks();
- }
+ private List findCitedKeys() throws NoSuchElementException, WrappedTargetException {
+ XNameAccess xNamedMarks = getReferenceMarks();
+ String[] names = xNamedMarks.getElementNames();
+ List keys = new ArrayList<>();
+ for (String name1 : names) {
+ Object bookmark = xNamedMarks.getByName(name1);
+ UnoRuntime.queryInterface(XTextContent.class, bookmark);
- private String getUniqueReferenceMarkName(String bibtexKey, int type) {
- XNameAccess xNamedRefMarks = getReferenceMarks();
- int i = 0;
- String name = OOBibBase.BIB_CITATION + '_' + type + '_' + bibtexKey;
- while (xNamedRefMarks.hasByName(name)) {
- name = OOBibBase.BIB_CITATION + i + '_' + type + '_' + bibtexKey;
- i++;
+ List newKeys = parseRefMarkName(name1);
+ for (String key : newKeys) {
+ if (!keys.contains(key)) {
+ keys.add(key);
+ }
+ }
}
- return name;
+
+ return keys;
}
private Map findCitedEntries(List databases, List keys,
@@ -842,55 +881,6 @@ private Map findCitedEntries(List databases,
return entries;
}
- private List findCitedKeys() throws NoSuchElementException, WrappedTargetException {
- XNameAccess xNamedMarks = getReferenceMarks();
- String[] names = xNamedMarks.getElementNames();
- List keys = new ArrayList<>();
- for (String name1 : names) {
- Object bookmark = xNamedMarks.getByName(name1);
- UnoRuntime.queryInterface(XTextContent.class, bookmark);
-
- List newKeys = parseRefMarkName(name1);
- for (String key : newKeys) {
- if (!keys.contains(key)) {
- keys.add(key);
- }
- }
- }
-
- return keys;
- }
-
- private Map getSortedEntriesFromSortedRefMarks(List names,
- Map linkSourceBase) {
-
- Map newList = new LinkedHashMap<>();
- for (String name : names) {
- Matcher citeMatcher = CITE_PATTERN.matcher(name);
- if (citeMatcher.find()) {
- String[] keys = citeMatcher.group(2).split(",");
- for (String key : keys) {
- BibDatabase database = linkSourceBase.get(key);
- Optional origEntry = Optional.empty();
- if (database != null) {
- origEntry = database.getEntryByKey(key);
- }
- if (origEntry.isPresent()) {
- if (!newList.containsKey(origEntry.get())) {
- newList.put(origEntry.get(), database);
- }
- } else {
- LOGGER.info("BibTeX key not found: '" + key + "'");
- LOGGER.info("Problem with reference mark: '" + name + "'");
- newList.put(new UndefinedBibtexEntry(key), null);
- }
- }
- }
- }
-
- return newList;
- }
-
private Point findPosition(XTextViewCursor cursor, XTextRange range) {
cursor.gotoRange(range, false);
return cursor.getPosition();
@@ -939,9 +929,39 @@ private List findCitedEntryIndex(String citRefName, List keys)
}
}
+ private Map getSortedEntriesFromSortedRefMarks(List names,
+ Map linkSourceBase) {
+
+ Map newList = new LinkedHashMap<>();
+ for (String name : names) {
+ Matcher citeMatcher = CITE_PATTERN.matcher(name);
+ if (citeMatcher.find()) {
+ String[] keys = citeMatcher.group(2).split(",");
+ for (String key : keys) {
+ BibDatabase database = linkSourceBase.get(key);
+ Optional origEntry = Optional.empty();
+ if (database != null) {
+ origEntry = database.getEntryByKey(key);
+ }
+ if (origEntry.isPresent()) {
+ if (!newList.containsKey(origEntry.get())) {
+ newList.put(origEntry.get(), database);
+ }
+ } else {
+ LOGGER.info("BibTeX key not found: '" + key + "'");
+ LOGGER.info("Problem with reference mark: '" + name + "'");
+ newList.put(new UndefinedBibtexEntry(key), null);
+ }
+ }
+ }
+ }
+
+ return newList;
+ }
+
public String getCitationContext(XNameAccess nameAccess, String refMarkName, int charBefore, int charAfter,
boolean htmlMarkup)
- throws NoSuchElementException, WrappedTargetException {
+ throws NoSuchElementException, WrappedTargetException {
Object referenceMark = nameAccess.getByName(refMarkName);
XTextContent bookmark = UnoRuntime.queryInterface(XTextContent.class, referenceMark);
@@ -984,8 +1004,8 @@ public String getCitationContext(XNameAccess nameAccess, String refMarkName, int
private void insertFullReferenceAtCursor(XTextCursor cursor, Map entries, OOBibStyle style,
String parFormat)
- throws UndefinedParagraphFormatException, IllegalArgumentException,
- UnknownPropertyException, PropertyVetoException, WrappedTargetException {
+ throws UndefinedParagraphFormatException, IllegalArgumentException,
+ UnknownPropertyException, PropertyVetoException, WrappedTargetException {
Map correctEntries;
// If we don't have numbered entries, we need to sort the entries before adding them:
if (style.isSortByPosition()) {
@@ -1006,18 +1026,18 @@ private void insertFullReferenceAtCursor(XTextCursor cursor, Map entries, OOBibStyle style)
- throws NoSuchElementException, WrappedTargetException, PropertyVetoException,
- UnknownPropertyException, UndefinedParagraphFormatException, IllegalArgumentException, CreationException {
+ throws NoSuchElementException, WrappedTargetException, PropertyVetoException,
+ UnknownPropertyException, UndefinedParagraphFormatException, IllegalArgumentException, CreationException {
XTextSectionsSupplier supplier = UnoRuntime.queryInterface(XTextSectionsSupplier.class, mxDoc);
XTextSection section = (XTextSection) ((Any) supplier.getTextSections().getByName(OOBibBase.BIB_SECTION_NAME))
- .getObject();
+ .getObject();
XTextCursor cursor = text.createTextCursorByRange(section.getAnchor());
OOUtil.insertTextAtCurrentLocation(text, cursor, (String) style.getProperty(OOBibStyle.TITLE),
- (String) style.getProperty(OOBibStyle.REFERENCE_HEADER_PARAGRAPH_FORMAT));
+ (String) style.getProperty(OOBibStyle.REFERENCE_HEADER_PARAGRAPH_FORMAT));
insertFullReferenceAtCursor(cursor, entries, style,
- (String) style.getProperty(OOBibStyle.REFERENCE_PARAGRAPH_FORMAT));
+ (String) style.getProperty(OOBibStyle.REFERENCE_PARAGRAPH_FORMAT));
insertBookMark(OOBibBase.BIB_SECTION_END_NAME, cursor);
}
private XTextContent insertBookMark(String name, XTextCursor position)
- throws IllegalArgumentException, CreationException {
+ throws IllegalArgumentException, CreationException {
Object bookmark;
try {
bookmark = mxDocFactory.createInstance("com.sun.star.text.Bookmark");
@@ -1093,8 +1113,8 @@ private XTextContent insertBookMark(String name, XTextCursor position)
private void insertReferenceMark(String name, String citationText, XTextCursor position, boolean withText,
OOBibStyle style)
- throws UnknownPropertyException, WrappedTargetException,
- PropertyVetoException, IllegalArgumentException, UndefinedCharacterFormatException, CreationException {
+ throws UnknownPropertyException, WrappedTargetException,
+ PropertyVetoException, IllegalArgumentException, UndefinedCharacterFormatException, CreationException {
// Check if there is "page info" stored for this citation. If so, insert it into
// the citation text before inserting the citation:
@@ -1127,7 +1147,7 @@ private void insertReferenceMark(String name, String citationText, XTextCursor p
try {
xCursorProps.setPropertyValue(CHAR_STYLE_NAME, charStyle);
} catch (UnknownPropertyException | PropertyVetoException | IllegalArgumentException |
- WrappedTargetException ex) {
+ WrappedTargetException ex) {
throw new UndefinedCharacterFormatException(charStyle);
}
}
@@ -1154,20 +1174,6 @@ private void insertReferenceMark(String name, String citationText, XTextCursor p
}
- private void italicizeOrBold(XTextCursor position, boolean italicize, int start, int end)
- throws UnknownPropertyException, PropertyVetoException, IllegalArgumentException, WrappedTargetException {
- XTextRange range = position.getStart();
- XTextCursor cursor = position.getText().createTextCursorByRange(range);
- cursor.goRight((short) start, false);
- cursor.goRight((short) (end - start), true);
- XPropertySet xcp = UnoRuntime.queryInterface(XPropertySet.class, cursor);
- if (italicize) {
- xcp.setPropertyValue("CharPosture", com.sun.star.awt.FontSlant.ITALIC);
- } else {
- xcp.setPropertyValue("CharWeight", com.sun.star.awt.FontWeight.BOLD);
- }
- }
-
private void removeReferenceMark(String name) throws NoSuchElementException, WrappedTargetException {
XNameAccess xReferenceMarks = getReferenceMarks();
if (xReferenceMarks.hasByName(name)) {
@@ -1203,10 +1209,24 @@ private XNameAccess getBookmarks() {
return xNamedBookmarks;
}
+ private void italicizeOrBold(XTextCursor position, boolean italicize, int start, int end)
+ throws UnknownPropertyException, PropertyVetoException, IllegalArgumentException, WrappedTargetException {
+ XTextRange range = position.getStart();
+ XTextCursor cursor = position.getText().createTextCursorByRange(range);
+ cursor.goRight((short) start, false);
+ cursor.goRight((short) (end - start), true);
+ XPropertySet xcp = UnoRuntime.queryInterface(XPropertySet.class, cursor);
+ if (italicize) {
+ xcp.setPropertyValue("CharPosture", com.sun.star.awt.FontSlant.ITALIC);
+ } else {
+ xcp.setPropertyValue("CharWeight", com.sun.star.awt.FontWeight.BOLD);
+ }
+ }
+
public void combineCiteMarkers(List databases, OOBibStyle style)
- throws IOException, WrappedTargetException, NoSuchElementException, IllegalArgumentException,
- UndefinedCharacterFormatException, UnknownPropertyException, PropertyVetoException, CreationException,
- BibEntryNotFoundException {
+ throws IOException, WrappedTargetException, NoSuchElementException, IllegalArgumentException,
+ UndefinedCharacterFormatException, UnknownPropertyException, PropertyVetoException, CreationException,
+ BibEntryNotFoundException {
XNameAccess nameAccess = getReferenceMarks();
// TODO: doesn't work for citations in footnotes/tables
List names = getSortedReferenceMarks(nameAccess);
@@ -1243,7 +1263,7 @@ public void combineCiteMarkers(List databases, OOBibStyle style)
try {
xCursorProps.setPropertyValue(CHAR_STYLE_NAME, charStyle);
} catch (UnknownPropertyException | PropertyVetoException | IllegalArgumentException |
- WrappedTargetException ex) {
+ WrappedTargetException ex) {
// Setting the character format failed, so we throw an exception that
// will result in an error message for the user:
throw new UndefinedCharacterFormatException(charStyle);
@@ -1282,24 +1302,37 @@ public void combineCiteMarkers(List databases, OOBibStyle style)
}
- public static XTextDocument selectComponent(List list)
- throws UnknownPropertyException, WrappedTargetException, IndexOutOfBoundsException {
- String[] values = new String[list.size()];
- int ii = 0;
- for (XTextDocument doc : list) {
- values[ii] = String.valueOf(OOUtil.getProperty(doc.getCurrentController().getFrame(), "Title"));
- ii++;
- }
- JList sel = new JList<>(values);
- sel.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
- sel.setSelectedIndex(0);
- int ans = JOptionPane.showConfirmDialog(null, new JScrollPane(sel), Localization.lang("Select document"),
- JOptionPane.OK_CANCEL_OPTION);
- if (ans == JOptionPane.OK_OPTION) {
- return list.get(sel.getSelectedIndex());
- } else {
- return null;
+ public BibDatabase generateDatabase(List databases)
+ throws NoSuchElementException, WrappedTargetException {
+ BibDatabase resultDatabase = new BibDatabase();
+ List cited = findCitedKeys();
+
+ // For each cited key
+ for (String key : cited) {
+ // Loop through the available databases
+ for (BibDatabase loopDatabase : databases) {
+ Optional entry = loopDatabase.getEntryByKey(key);
+ // If entry found
+ if (entry.isPresent()) {
+ BibEntry clonedEntry = (BibEntry) entry.get().clone();
+ // Insert a copy of the entry
+ resultDatabase.insertEntry(clonedEntry);
+ // Check if the cloned entry has a crossref field
+ clonedEntry.getField(FieldName.CROSSREF).ifPresent(crossref -> {
+ // If the crossref entry is not already in the database
+ if (!resultDatabase.getEntryByKey(crossref).isPresent()) {
+ // Add it if it is in the current library
+ loopDatabase.getEntryByKey(crossref).ifPresent(resultDatabase::insertEntry);
+ }
+ });
+
+ // Be happy with the first found BibEntry and move on to next key
+ break;
+ }
+ }
}
+
+ return resultDatabase;
}
private static class ComparableMark implements Comparable {
@@ -1330,7 +1363,7 @@ public boolean equals(Object o) {
if (o instanceof ComparableMark) {
ComparableMark other = (ComparableMark) o;
return (this.position.X == other.position.X) && (this.position.Y == other.position.Y)
- && Objects.equals(this.name, other.name);
+ && Objects.equals(this.name, other.name);
}
return false;
}
@@ -1346,37 +1379,4 @@ public int hashCode() {
}
- public BibDatabase generateDatabase(List databases)
- throws NoSuchElementException, WrappedTargetException {
- BibDatabase resultDatabase = new BibDatabase();
- List cited = findCitedKeys();
-
- // For each cited key
- for (String key : cited) {
- // Loop through the available databases
- for (BibDatabase loopDatabase : databases) {
- Optional entry = loopDatabase.getEntryByKey(key);
- // If entry found
- if (entry.isPresent()) {
- BibEntry clonedEntry = (BibEntry) entry.get().clone();
- // Insert a copy of the entry
- resultDatabase.insertEntry(clonedEntry);
- // Check if the cloned entry has a crossref field
- clonedEntry.getField(FieldName.CROSSREF).ifPresent(crossref -> {
- // If the crossref entry is not already in the database
- if (!resultDatabase.getEntryByKey(crossref).isPresent()) {
- // Add it if it is in the current library
- loopDatabase.getEntryByKey(crossref).ifPresent(resultDatabase::insertEntry);
- }
- });
-
- // Be happy with the first found BibEntry and move on to next key
- break;
- }
- }
- }
-
- return resultDatabase;
- }
-
}
diff --git a/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java b/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java
index 21b12f02321..9f31cc17a8b 100644
--- a/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java
+++ b/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java
@@ -94,10 +94,10 @@ public class OpenOfficePanel {
private OOBibBase ooBase;
private final JabRefFrame frame;
private OOBibStyle style;
- private OpenOfficePreferences ooPrefs;
private final JabRefPreferences jabRefPreferences;
- private final StyleLoader loader;
private final TaskExecutor taskExecutor;
+ private final StyleLoader loader;
+ private OpenOfficePreferences ooPrefs;
public OpenOfficePanel(JabRefFrame frame, JabRefPreferences jabRefPreferences, OpenOfficePreferences ooPrefs, KeyBindingRepository keyBindingRepository) {
ActionFactory factory = new ActionFactory(keyBindingRepository);
@@ -133,12 +133,29 @@ public OpenOfficePanel(JabRefFrame frame, JabRefPreferences jabRefPreferences, O
update.setMaxWidth(Double.MAX_VALUE);
loader = new StyleLoader(ooPrefs,
- Globals.prefs.getLayoutFormatterPreferences(Globals.journalAbbreviationLoader),
- Globals.prefs.getDefaultEncoding());
+ Globals.prefs.getLayoutFormatterPreferences(Globals.journalAbbreviationLoader),
+ Globals.prefs.getDefaultEncoding());
initPanel();
}
+ private static void addURL(List jarList) throws IOException {
+ URLClassLoader sysloader = (URLClassLoader) ClassLoader.getSystemClassLoader();
+ Class sysclass = URLClassLoader.class;
+ try {
+ Method method = sysclass.getDeclaredMethod("addURL", URL.class);
+ method.setAccessible(true);
+ for (URL anU : jarList) {
+ method.invoke(sysloader, anU);
+ }
+ } catch (SecurityException | NoSuchMethodException | IllegalAccessException | IllegalArgumentException |
+ InvocationTargetException e) {
+ LOGGER.error("Could not add URL to system classloader", e);
+ sysloader.close();
+ throw new IOException("Error, could not add URL to system classloader", e);
+ }
+ }
+
public Node getContent() {
return vbox;
}
@@ -154,9 +171,9 @@ private void initPanel() {
try {
ooBase.selectDocument();
dialogService.notify(Localization.lang("Connected to document") + ": "
- + ooBase.getCurrentDocumentTitle().orElse(""));
+ + ooBase.getCurrentDocumentTitle().orElse(""));
} catch (UnknownPropertyException | WrappedTargetException | IndexOutOfBoundsException |
- NoSuchElementException | NoDocumentException ex) {
+ NoSuchElementException | NoDocumentException ex) {
LOGGER.warn("Problem connecting", ex);
dialogService.showErrorDialogAndWait(ex);
}
@@ -209,9 +226,8 @@ private void initPanel() {
ooBase.rebuildBibTextSection(databases, style);
if (!unresolvedKeys.isEmpty()) {
dialogService.showErrorDialogAndWait(Localization.lang("Unable to synchronize bibliography"),
- Localization.lang("Your OpenOffice/LibreOffice document references the BibTeX key '%0', which could not be found in your current library.",
- unresolvedKeys.get(0)));
-
+ Localization.lang("Your OpenOffice/LibreOffice document references the BibTeX key '%0', which could not be found in your current library.",
+ unresolvedKeys.get(0)));
}
} catch (UndefinedCharacterFormatException ex) {
reportUndefinedCharacterFormat(ex);
@@ -222,19 +238,16 @@ private void initPanel() {
} catch (IOException ex) {
LOGGER.warn("Problem with style file", ex);
dialogService.showErrorDialogAndWait(Localization.lang("No valid style file defined"),
- Localization.lang("You must select either a valid style file, or use one of the default styles."));
-
+ Localization.lang("You must select either a valid style file, or use one of the default styles."));
} catch (BibEntryNotFoundException ex) {
LOGGER.debug("BibEntry not found", ex);
dialogService.showErrorDialogAndWait(Localization.lang("Unable to synchronize bibliography"), Localization.lang(
- "Your OpenOffice/LibreOffice document references the BibTeX key '%0', which could not be found in your current library.",
- ex.getBibtexKey()));
-
+ "Your OpenOffice/LibreOffice document references the BibTeX key '%0', which could not be found in your current library.",
+ ex.getBibtexKey()));
} catch (com.sun.star.lang.IllegalArgumentException | PropertyVetoException | UnknownPropertyException | WrappedTargetException | NoSuchElementException |
- CreationException ex) {
+ CreationException ex) {
LOGGER.warn("Could not update bibliography", ex);
}
-
});
merge.setMaxWidth(Double.MAX_VALUE);
@@ -245,8 +258,8 @@ private void initPanel() {
} catch (UndefinedCharacterFormatException ex) {
reportUndefinedCharacterFormat(ex);
} catch (com.sun.star.lang.IllegalArgumentException | UnknownPropertyException | PropertyVetoException |
- CreationException | NoSuchElementException | WrappedTargetException | IOException |
- BibEntryNotFoundException ex) {
+ CreationException | NoSuchElementException | WrappedTargetException | IOException |
+ BibEntryNotFoundException ex) {
LOGGER.warn("Problem combining cite markers", ex);
}
@@ -276,7 +289,7 @@ private void initPanel() {
HBox hbox = new HBox();
hbox.getChildren().addAll(connect, manualConnect, selectDocument, update, help);
- hbox.getChildren().forEach(btn -> hbox.setHgrow(btn, Priority.ALWAYS));
+ hbox.getChildren().forEach(btn -> HBox.setHgrow(btn, Priority.ALWAYS));
vbox.setFillWidth(true);
vbox.getChildren().addAll(hbox, setStyleFile, pushEntries, pushEntriesInt, pushEntriesAdvanced, pushEntriesEmpty, merge, manageCitations, exportCitations, settingsB);
@@ -298,8 +311,8 @@ private void exportEntries() {
if (!unresolvedKeys.isEmpty()) {
dialogService.showErrorDialogAndWait(Localization.lang("Unable to generate new library"),
- Localization.lang("Your OpenOffice/LibreOffice document references the BibTeX key '%0', which could not be found in your current library.",
- unresolvedKeys.get(0)));
+ Localization.lang("Your OpenOffice/LibreOffice document references the BibTeX key '%0', which could not be found in your current library.",
+ unresolvedKeys.get(0)));
}
@@ -310,12 +323,12 @@ private void exportEntries() {
} catch (BibEntryNotFoundException ex) {
LOGGER.debug("BibEntry not found", ex);
dialogService.showErrorDialogAndWait(Localization.lang("Unable to synchronize bibliography"),
- Localization.lang("Your OpenOffice/LibreOffice document references the BibTeX key '%0', which could not be found in your current library.",
- ex.getBibtexKey()));
+ Localization.lang("Your OpenOffice/LibreOffice document references the BibTeX key '%0', which could not be found in your current library.",
+ ex.getBibtexKey()));
} catch (com.sun.star.lang.IllegalArgumentException | UnknownPropertyException | PropertyVetoException |
- UndefinedCharacterFormatException | NoSuchElementException | WrappedTargetException | IOException |
- CreationException e) {
+ UndefinedCharacterFormatException | NoSuchElementException | WrappedTargetException | IOException |
+ CreationException e) {
LOGGER.warn("Problem generating new database.", e);
}
@@ -398,7 +411,6 @@ protected OOBibBase call() throws Exception {
merge.setDisable(false);
manageCitations.setDisable(false);
exportCitations.setDisable(false);
-
});
connectTask.setOnFailed(value -> {
Throwable ex = connectTask.getException();
@@ -406,17 +418,16 @@ protected OOBibBase call() throws Exception {
LOGGER.warn("Could not connect to running OpenOffice/LibreOffice", ex);
dialogService.showErrorDialogAndWait(Localization.lang("Unable to connect. One possible reason is that JabRef "
- + "and OpenOffice/LibreOffice are not both running in either 32 bit mode or 64 bit mode."));
-
+ + "and OpenOffice/LibreOffice are not both running in either 32 bit mode or 64 bit mode."));
} else if (ex instanceof IOException) {
LOGGER.warn("Could not connect to running OpenOffice/LibreOffice", ex);
dialogService.showErrorDialogAndWait(Localization.lang("Could not connect to running OpenOffice/LibreOffice."),
- Localization.lang("Could not connect to running OpenOffice/LibreOffice.")
- + "\n"
- + Localization.lang("Make sure you have installed OpenOffice/LibreOffice with Java support.") + "\n"
- + Localization.lang("If connecting manually, please verify program and library paths.") + "\n" + "\n" + Localization.lang("Error message:"),
- ex);
+ Localization.lang("Could not connect to running OpenOffice/LibreOffice.")
+ + "\n"
+ + Localization.lang("Make sure you have installed OpenOffice/LibreOffice with Java support.") + "\n"
+ + Localization.lang("If connecting manually, please verify program and library paths.") + "\n" + "\n" + Localization.lang("Error message:"),
+ ex);
} else {
dialogService.showErrorDialogAndWait(Localization.lang("Autodetection failed"), Localization.lang("Autodetection failed"), ex);
}
@@ -442,30 +453,12 @@ private void loadOpenOfficeJars(Path configurationPath) throws IOException {
}
private OOBibBase createBibBase() throws IOException, InvocationTargetException, IllegalAccessException,
- WrappedTargetException, BootstrapException, UnknownPropertyException, NoDocumentException,
- NoSuchElementException, CreationException {
+ WrappedTargetException, BootstrapException, UnknownPropertyException, NoDocumentException,
+ NoSuchElementException, CreationException {
// Connect
return new OOBibBase(ooPrefs.getExecutablePath(), true);
}
- private static void addURL(List jarList) throws IOException {
- URLClassLoader sysloader = (URLClassLoader) ClassLoader.getSystemClassLoader();
- Class sysclass = URLClassLoader.class;
- try {
- Method method = sysclass.getDeclaredMethod("addURL", URL.class);
- method.setAccessible(true);
- for (URL anU : jarList) {
- method.invoke(sysloader, anU);
- }
- } catch (SecurityException | NoSuchMethodException | IllegalAccessException | IllegalArgumentException |
- InvocationTargetException e) {
- LOGGER.error("Could not add URL to system classloader", e);
- sysloader.close();
- throw new IOException("Error, could not add URL to system classloader", e);
-
- }
- }
-
private Optional showManualConnectionDialog() {
return new ManualConnectDialogView(dialogService).showAndWait();
}
@@ -504,12 +497,12 @@ private void pushEntries(boolean inParenthesisIn, boolean withText, boolean addP
style = loader.getUsedStyle();
}
ooBase.insertEntry(entries, database, getBaseList(), style, inParenthesis, withText, pageInfo,
- ooPrefs.getSyncWhenCiting());
+ ooPrefs.getSyncWhenCiting());
} catch (FileNotFoundException ex) {
dialogService.showErrorDialogAndWait(
- Localization.lang("No valid style file defined"),
- Localization.lang("You must select either a valid style file, or use one of the default styles."));
+ Localization.lang("No valid style file defined"),
+ Localization.lang("You must select either a valid style file, or use one of the default styles."));
LOGGER.warn("Problem with style file", ex);
} catch (ConnectionLostException ex) {
@@ -519,9 +512,9 @@ private void pushEntries(boolean inParenthesisIn, boolean withText, boolean addP
} catch (UndefinedParagraphFormatException ex) {
reportUndefinedParagraphFormat(ex);
} catch (com.sun.star.lang.IllegalArgumentException | UnknownPropertyException | PropertyVetoException |
- CreationException | NoSuchElementException | WrappedTargetException | IOException |
- BibEntryNotFoundException | IllegalTypeException | PropertyExistException |
- NotRemoveableException ex) {
+ CreationException | NoSuchElementException | WrappedTargetException | IOException |
+ BibEntryNotFoundException | IllegalTypeException | PropertyExistException |
+ NotRemoveableException ex) {
LOGGER.warn("Could not insert entry", ex);
}
}
@@ -554,9 +547,9 @@ private boolean checkThatEntriesHaveKeys(List entries) {
// Ask if keys should be generated
boolean citePressed = dialogService.showConfirmationDialogAndWait(Localization.lang("Cite"),
- Localization.lang("Cannot cite entries without BibTeX keys. Generate keys now?"),
- Localization.lang("Generate keys"),
- Localization.lang("Cancel"));
+ Localization.lang("Cannot cite entries without BibTeX keys. Generate keys now?"),
+ Localization.lang("Generate keys"),
+ Localization.lang("Cancel"));
BasePanel panel = frame.getCurrentBasePanel();
if (citePressed && (panel != null)) {
@@ -567,8 +560,8 @@ private boolean checkThatEntriesHaveKeys(List entries) {
if (!entry.getCiteKeyOptional().isPresent()) {
// Generate key
new BibtexKeyGenerator(panel.getBibDatabaseContext(), prefs)
- .generateAndSetKey(entry)
- .ifPresent(change -> undoCompound.addEdit(new UndoableKeyChange(change)));
+ .generateAndSetKey(entry)
+ .ifPresent(change -> undoCompound.addEdit(new UndoableKeyChange(change)));
}
}
undoCompound.end();
@@ -584,23 +577,23 @@ private boolean checkThatEntriesHaveKeys(List entries) {
private void showConnectionLostErrorMessage() {
dialogService.showErrorDialogAndWait(Localization.lang("Connection lost"),
- Localization.lang("Connection to OpenOffice/LibreOffice has been lost. " + "Please make sure OpenOffice/LibreOffice is running, and try to reconnect."));
+ Localization.lang("Connection to OpenOffice/LibreOffice has been lost. " + "Please make sure OpenOffice/LibreOffice is running, and try to reconnect."));
}
private void reportUndefinedParagraphFormat(UndefinedParagraphFormatException ex) {
dialogService.showErrorDialogAndWait(Localization.lang("Undefined paragraph format"),
- Localization.lang("Your style file specifies the paragraph format '%0', "
- + "which is undefined in your current OpenOffice/LibreOffice document.",
- ex.getFormatName()) + "\n" + Localization.lang("The paragraph format is controlled by the property 'ReferenceParagraphFormat' or 'ReferenceHeaderParagraphFormat' in the style file."));
+ Localization.lang("Your style file specifies the paragraph format '%0', "
+ + "which is undefined in your current OpenOffice/LibreOffice document.",
+ ex.getFormatName()) + "\n" + Localization.lang("The paragraph format is controlled by the property 'ReferenceParagraphFormat' or 'ReferenceHeaderParagraphFormat' in the style file."));
}
private void reportUndefinedCharacterFormat(UndefinedCharacterFormatException ex) {
dialogService.showErrorDialogAndWait(Localization.lang("Undefined character format"),
- Localization.lang("Your style file specifies the character format '%0', "
- + "which is undefined in your current OpenOffice/LibreOffice document.",
- ex.getFormatName()) + "\n" + Localization.lang("The character format is controlled by the citation property 'CitationCharacterFormat' in the style file.")
+ Localization.lang("Your style file specifies the character format '%0', "
+ + "which is undefined in your current OpenOffice/LibreOffice document.",
+ ex.getFormatName()) + "\n" + Localization.lang("The character format is controlled by the citation property 'CitationCharacterFormat' in the style file.")
);
}
diff --git a/src/main/java/org/jabref/gui/openoffice/StyleSelectDialog.fxml b/src/main/java/org/jabref/gui/openoffice/StyleSelectDialog.fxml
index f994d348787..89d9f67ce04 100644
--- a/src/main/java/org/jabref/gui/openoffice/StyleSelectDialog.fxml
+++ b/src/main/java/org/jabref/gui/openoffice/StyleSelectDialog.fxml
@@ -7,33 +7,35 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/src/main/java/org/jabref/gui/openoffice/StyleSelectDialogView.java b/src/main/java/org/jabref/gui/openoffice/StyleSelectDialogView.java
index 2a160c15d03..7e5e6a89020 100644
--- a/src/main/java/org/jabref/gui/openoffice/StyleSelectDialogView.java
+++ b/src/main/java/org/jabref/gui/openoffice/StyleSelectDialogView.java
@@ -30,6 +30,9 @@
public class StyleSelectDialogView extends BaseDialog {
+ private final MenuItem edit = new MenuItem(Localization.lang("Edit"));
+ private final MenuItem reload = new MenuItem(Localization.lang("Reload"));
+ private final StyleLoader loader;
@FXML private TableColumn colName;
@FXML private TableView tvStyles;
@FXML private TableColumn colJournals;
@@ -37,14 +40,8 @@ public class StyleSelectDialogView extends BaseDialog {
@FXML private TableColumn colDeleteIcon;
@FXML private Button add;
@FXML private VBox vbox;
-
@Inject private PreferencesService preferencesService;
@Inject private DialogService dialogService;
-
- private final MenuItem edit = new MenuItem(Localization.lang("Edit"));
- private final MenuItem reload = new MenuItem(Localization.lang("Reload"));
- private final StyleLoader loader;
-
private StyleSelectDialogViewModel viewModel;
private PreviewPanel previewArticle;
private PreviewPanel previewBook;
@@ -63,7 +60,6 @@ public StyleSelectDialogView(StyleLoader loader) {
return tvStyles.getSelectionModel().getSelectedItem().getStyle();
}
return null;
-
});
setTitle(Localization.lang("Style selection"));
}
@@ -87,30 +83,30 @@ private void initialize() {
colDeleteIcon.setCellValueFactory(cellData -> cellData.getValue().internalStyleProperty());
new ValueTableCellFactory()
- .withGraphic(internalStyle -> {
- if (!internalStyle) {
- return IconTheme.JabRefIcons.DELETE_ENTRY.getGraphicNode();
- }
- return null;
- })
- .withOnMouseClickedEvent(item -> {
- return evt -> viewModel.deleteStyle();
- })
- .withTooltip(item -> {
- return Localization.lang("Remove style");
- })
- .install(colDeleteIcon);
+ .withGraphic(internalStyle -> {
+ if (!internalStyle) {
+ return IconTheme.JabRefIcons.DELETE_ENTRY.getGraphicNode();
+ }
+ return null;
+ })
+ .withOnMouseClickedEvent(item -> {
+ return evt -> viewModel.deleteStyle();
+ })
+ .withTooltip(item -> {
+ return Localization.lang("Remove style");
+ })
+ .install(colDeleteIcon);
edit.setOnAction(e -> viewModel.editStyle());
new ViewModelTableRowFactory()
- .withOnMouseClickedEvent((item, event) -> {
- if (event.getClickCount() == 2) {
- viewModel.viewStyle(item);
- }
- })
- .withContextMenu(item -> createContextMenu())
- .install(tvStyles);
+ .withOnMouseClickedEvent((item, event) -> {
+ if (event.getClickCount() == 2) {
+ viewModel.viewStyle(item);
+ }
+ })
+ .withContextMenu(item -> createContextMenu())
+ .install(tvStyles);
tvStyles.getSelectionModel().selectedItemProperty().addListener((observable, oldvalue, newvalue) -> {
if (newvalue == null) {
@@ -141,5 +137,4 @@ private ContextMenu createContextMenu() {
private void addStyleFile() {
viewModel.addStyleFile();
}
-
}
diff --git a/src/main/java/org/jabref/gui/openoffice/StyleSelectDialogViewModel.java b/src/main/java/org/jabref/gui/openoffice/StyleSelectDialogViewModel.java
index 203c495243b..ded9dd93b79 100644
--- a/src/main/java/org/jabref/gui/openoffice/StyleSelectDialogViewModel.java
+++ b/src/main/java/org/jabref/gui/openoffice/StyleSelectDialogViewModel.java
@@ -54,7 +54,6 @@ public StyleSelectDialogViewModel(DialogService dialogService, StyleLoader loade
} else {
selectedItem.setValue(styles.get(0));
}
-
}
public StyleSelectItemViewModel fromOOBibStyle(OOBibStyle style) {
@@ -67,10 +66,10 @@ public OOBibStyle toOOBibStyle(StyleSelectItemViewModel item) {
public void addStyleFile() {
FileDialogConfiguration fileDialogConfiguration = new FileDialogConfiguration.Builder()
- .addExtensionFilter(Localization.lang("Style file"), StandardFileType.JSTYLE)
- .withDefaultExtension(Localization.lang("Style file"), StandardFileType.JSTYLE)
- .withInitialDirectory(preferencesService.getWorkingDir())
- .build();
+ .addExtensionFilter(Localization.lang("Style file"), StandardFileType.JSTYLE)
+ .withDefaultExtension(Localization.lang("Style file"), StandardFileType.JSTYLE)
+ .withInitialDirectory(preferencesService.getWorkingDir())
+ .build();
Optional path = dialogService.showFileOpenDialog(fileDialogConfiguration);
path.map(Path::toAbsolutePath).map(Path::toString).ifPresent(stylePath -> {
if (loader.addStyleIfValid(stylePath)) {
@@ -80,7 +79,6 @@ public void addStyleFile() {
dialogService.showErrorDialogAndWait(Localization.lang("Invalid style selected"), Localization.lang("You must select a valid style file."));
}
});
-
}
public List loadStyles() {
@@ -97,7 +95,6 @@ public void deleteStyle() {
if (loader.removeStyle(style)) {
styles.remove(selectedItem.get());
}
-
}
public void editStyle() {
@@ -106,7 +103,7 @@ public void editStyle() {
Optional type = ExternalFileTypes.getInstance().getExternalFileTypeByExt("jstyle");
try {
- JabRefDesktop.openExternalFileAnyFormat(new BibDatabaseContext(), style.getPath().toString(), type);
+ JabRefDesktop.openExternalFileAnyFormat(new BibDatabaseContext(), style.getPath(), type);
} catch (IOException e) {
dialogService.showErrorDialogAndWait(e);
}
@@ -122,7 +119,6 @@ public void viewStyle(StyleSelectItemViewModel item) {
scrollPane.setContent(styleView);
pane.setContent(scrollPane);
dialogService.showCustomDialogAndWait(item.getStyle().getName(), pane, ButtonType.OK);
-
}
public ObjectProperty selectedItemProperty() {
@@ -133,5 +129,4 @@ public void storePrefs() {
preferences.setCurrentStyle(selectedItem.getValue().getStylePath());
preferencesService.setOpenOfficePreferences(preferences);
}
-
}
diff --git a/src/main/java/org/jabref/gui/openoffice/StyleSelectItemViewModel.java b/src/main/java/org/jabref/gui/openoffice/StyleSelectItemViewModel.java
index 1b4eebf2070..4f5dc9216d9 100644
--- a/src/main/java/org/jabref/gui/openoffice/StyleSelectItemViewModel.java
+++ b/src/main/java/org/jabref/gui/openoffice/StyleSelectItemViewModel.java
@@ -55,5 +55,4 @@ public BooleanProperty internalStyleProperty() {
public String getStylePath() {
return style.getPath();
}
-
}
diff --git a/src/main/java/org/jabref/gui/preferences/ImportSettingsTab.java b/src/main/java/org/jabref/gui/preferences/ImportSettingsTab.java
index d2dd0896a7e..3067882b2c2 100644
--- a/src/main/java/org/jabref/gui/preferences/ImportSettingsTab.java
+++ b/src/main/java/org/jabref/gui/preferences/ImportSettingsTab.java
@@ -4,18 +4,14 @@
import javafx.collections.FXCollections;
import javafx.scene.Node;
-import javafx.scene.control.CheckBox;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
-import javafx.scene.control.RadioButton;
import javafx.scene.control.Separator;
import javafx.scene.control.TextField;
-import javafx.scene.control.ToggleGroup;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.Pane;
import org.jabref.logic.l10n.Localization;
-import org.jabref.pdfimport.ImportDialog;
import org.jabref.preferences.JabRefPreferences;
public class ImportSettingsTab extends Pane implements PrefsTab {
@@ -23,15 +19,9 @@ public class ImportSettingsTab extends Pane implements PrefsTab {
public static final String[] DEFAULT_FILENAMEPATTERNS = new String[] {"[bibtexkey]",
"[bibtexkey] - [title]"};
- public static final int DEFAULT_STYLE = ImportDialog.CONTENT;
private static final String[] DEFAULT_FILENAMEPATTERNS_DISPLAY = new String[] {"bibtexkey", "bibtexkey - title",};
private final JabRefPreferences prefs;
- private final RadioButton radioButtonXmp;
- private final RadioButton radioButtonPDFcontent;
- private final RadioButton radioButtonNoMeta;
- private final RadioButton radioButtononlyAttachPDF;
- private final CheckBox useDefaultPDFImportStyle;
private final GridPane builder = new GridPane();
private final TextField fileNamePattern;
private final ComboBox selectFileNamePattern;
@@ -41,13 +31,6 @@ public class ImportSettingsTab extends Pane implements PrefsTab {
public ImportSettingsTab(JabRefPreferences prefs) {
this.prefs = Objects.requireNonNull(prefs);
- radioButtonNoMeta = new RadioButton(Localization.lang("Create blank entry linking the PDF"));
- radioButtonXmp = new RadioButton(Localization.lang("Create entry based on XMP-metadata"));
- radioButtonPDFcontent = new RadioButton(Localization.lang("Create entry based on content"));
- radioButtononlyAttachPDF = new RadioButton(Localization.lang("Only attach PDF"));
-
- useDefaultPDFImportStyle = new CheckBox(
- Localization.lang("Always use this PDF import style (and do not ask for each import)"));
fileNamePattern = new TextField();
fileDirPattern = new TextField();
@@ -61,17 +44,7 @@ public ImportSettingsTab(JabRefPreferences prefs) {
Label defaultImportStyle = new Label(Localization.lang("Default import style for drag and drop of PDFs"));
defaultImportStyle.getStyleClass().add("sectionHeader");
builder.add(defaultImportStyle, 1, 1);
- final ToggleGroup defaultImportStyleDragDropPdfs = new ToggleGroup();
builder.add(new Separator(), 2, 1);
- builder.add(radioButtonNoMeta, 2, 2);
- builder.add(radioButtonXmp, 2, 3);
- builder.add(radioButtonPDFcontent, 2, 4);
- builder.add(radioButtononlyAttachPDF, 2, 5);
- radioButtonNoMeta.setToggleGroup(defaultImportStyleDragDropPdfs);
- radioButtonXmp.setToggleGroup(defaultImportStyleDragDropPdfs);
- radioButtonPDFcontent.setToggleGroup(defaultImportStyleDragDropPdfs);
- radioButtononlyAttachPDF.setToggleGroup(defaultImportStyleDragDropPdfs);
- builder.add(useDefaultPDFImportStyle, 2, 6);
builder.add(new Label(""), 1, 7);
Label defaultPdfFileLinkAction = new Label(Localization.lang("Default PDF file link action"));
@@ -93,45 +66,12 @@ public Node getBuilder() {
@Override
public void setValues() {
-
- useDefaultPDFImportStyle.setSelected(prefs.getBoolean(JabRefPreferences.IMPORT_ALWAYSUSE));
- int style = prefs.getInt(JabRefPreferences.IMPORT_DEFAULT_PDF_IMPORT_STYLE);
- switch (style) {
- case ImportDialog.NOMETA:
- radioButtonNoMeta.setSelected(true);
- break;
- case ImportDialog.XMP:
- radioButtonXmp.setSelected(true);
- break;
- case ImportDialog.CONTENT:
- radioButtonPDFcontent.setSelected(true);
- break;
- case ImportDialog.ONLYATTACH:
- radioButtononlyAttachPDF.setSelected(true);
- break;
- default:
- // fallback
- radioButtonPDFcontent.setSelected(true);
- break;
- }
fileNamePattern.setText(prefs.get(JabRefPreferences.IMPORT_FILENAMEPATTERN));
fileDirPattern.setText(prefs.get(JabRefPreferences.IMPORT_FILEDIRPATTERN));
}
@Override
public void storeSettings() {
- prefs.putBoolean(JabRefPreferences.IMPORT_ALWAYSUSE, useDefaultPDFImportStyle.isSelected());
- int style = ImportSettingsTab.DEFAULT_STYLE;
- if (radioButtonNoMeta.isSelected()) {
- style = ImportDialog.NOMETA;
- } else if (radioButtonXmp.isSelected()) {
- style = ImportDialog.XMP;
- } else if (radioButtonPDFcontent.isSelected()) {
- style = ImportDialog.CONTENT;
- } else if (radioButtononlyAttachPDF.isSelected()) {
- style = ImportDialog.ONLYATTACH;
- }
- prefs.putInt(JabRefPreferences.IMPORT_DEFAULT_PDF_IMPORT_STYLE, style);
prefs.put(JabRefPreferences.IMPORT_FILENAMEPATTERN, fileNamePattern.getText());
prefs.put(JabRefPreferences.IMPORT_FILEDIRPATTERN, fileDirPattern.getText());
}
diff --git a/src/main/java/org/jabref/gui/preferences/PreferencesDialog.java b/src/main/java/org/jabref/gui/preferences/PreferencesDialog.java
index a2571e4e5fd..8881f6af654 100644
--- a/src/main/java/org/jabref/gui/preferences/PreferencesDialog.java
+++ b/src/main/java/org/jabref/gui/preferences/PreferencesDialog.java
@@ -25,6 +25,7 @@
import org.jabref.gui.util.BaseDialog;
import org.jabref.gui.util.ControlHelper;
import org.jabref.gui.util.FileDialogConfiguration;
+import org.jabref.gui.util.TaskExecutor;
import org.jabref.gui.util.ViewModelListCellFactory;
import org.jabref.logic.exporter.ExporterFactory;
import org.jabref.logic.exporter.SavePreferences;
@@ -57,7 +58,7 @@ public class PreferencesDialog extends BaseDialog {
private final JabRefPreferences prefs;
private final ObservableList preferenceTabs;
- public PreferencesDialog(JabRefFrame parent) {
+ public PreferencesDialog(JabRefFrame parent, TaskExecutor taskExecutor) {
setTitle(Localization.lang("JabRef preferences"));
getDialogPane().getScene().getStylesheets().add(this.getClass().getResource("PreferencesDialog.css").toExternalForm());
@@ -68,7 +69,7 @@ public PreferencesDialog(JabRefFrame parent) {
close();
});
- prefs = JabRefPreferences.getInstance();
+ prefs = Globals.prefs;
frame = parent;
dialogService = frame.getDialogService();
@@ -77,7 +78,7 @@ public PreferencesDialog(JabRefFrame parent) {
preferenceTabs.add(new FileTab(dialogService, prefs));
preferenceTabs.add(new TablePrefsTab(prefs));
preferenceTabs.add(new TableColumnsTab(prefs, frame));
- preferenceTabs.add(new PreviewPrefsTab(dialogService, ExternalFileTypes.getInstance()));
+ preferenceTabs.add(new PreviewPrefsTab(dialogService, ExternalFileTypes.getInstance(), taskExecutor));
preferenceTabs.add(new ExternalTab(frame, this, prefs));
preferenceTabs.add(new GroupsPrefsTab(prefs));
preferenceTabs.add(new EntryEditorPrefsTab(prefs));
@@ -135,8 +136,7 @@ private void construct() {
importPreferences,
exportPreferences,
showPreferences,
- resetPreferences
- );
+ resetPreferences);
VBox spacer = new VBox();
spacer.setPrefHeight(10.0);
@@ -145,8 +145,7 @@ private void construct() {
vBox.getChildren().addAll(
tabsList,
spacer,
- buttonContainer
- );
+ buttonContainer);
container.setLeft(vBox);
diff --git a/src/main/java/org/jabref/gui/preferences/PreviewPrefsTab.java b/src/main/java/org/jabref/gui/preferences/PreviewPrefsTab.java
index 071aa23cd0a..07dedf198b0 100644
--- a/src/main/java/org/jabref/gui/preferences/PreviewPrefsTab.java
+++ b/src/main/java/org/jabref/gui/preferences/PreviewPrefsTab.java
@@ -4,11 +4,9 @@
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
-import java.util.concurrent.ExecutionException;
-
-import javax.swing.JPanel;
-import javax.swing.SwingWorker;
+import javafx.beans.binding.Bindings;
+import javafx.beans.binding.BooleanBinding;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.Node;
@@ -28,7 +26,8 @@
import org.jabref.gui.DialogService;
import org.jabref.gui.PreviewPanel;
import org.jabref.gui.externalfiletype.ExternalFileTypes;
-import org.jabref.gui.util.DefaultTaskExecutor;
+import org.jabref.gui.util.BackgroundTask;
+import org.jabref.gui.util.TaskExecutor;
import org.jabref.logic.citationstyle.CitationStyle;
import org.jabref.logic.l10n.Localization;
import org.jabref.logic.util.TestEntry;
@@ -38,12 +37,10 @@
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-public class PreviewPrefsTab extends JPanel implements PrefsTab {
+public class PreviewPrefsTab implements PrefsTab {
private static final Logger LOGGER = LoggerFactory.getLogger(PreviewPrefsTab.class);
- private SwingWorker, Void> discoverCitationStyleWorker;
-
private final ObservableList