From c7473e73b7c3ead034031128105fd72decd15544 Mon Sep 17 00:00:00 2001
From: "dependabot[bot]"
Date: Tue, 22 Jan 2019 08:24:58 +0100
Subject: [PATCH 01/20] Bump mysql-connector-java from 8.0.13 to 8.0.14 (#4599)
Bumps [mysql-connector-java](https://github.com/mysql/mysql-connector-j) from 8.0.13 to 8.0.14.
- [Release notes](https://github.com/mysql/mysql-connector-j/releases)
- [Changelog](https://github.com/mysql/mysql-connector-j/blob/release/8.0/CHANGES)
- [Commits](https://github.com/mysql/mysql-connector-j/compare/8.0.13...8.0.14)
Signed-off-by: dependabot[bot]
---
build.gradle | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/build.gradle b/build.gradle
index 5f902290771..94a5e380cab 100644
--- a/build.gradle
+++ b/build.gradle
@@ -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.13'
+ compile 'mysql:mysql-connector-java:8.0.14'
compile 'org.postgresql:postgresql:42.2.5'
From 701e73d545e9879163438a95ba9ceb6a33eddb48 Mon Sep 17 00:00:00 2001
From: Aleksandrs Gusevs
Date: Tue, 22 Jan 2019 13:28:24 +0200
Subject: [PATCH 02/20] Solution for submitting dialog with Ctrl + Enter
(#4496) (#4592)
* Issue#4496 Added default action invocation in dialog when pressing ctrl+enter
* Issue#4496 Added changelog regarding changes made
---
CHANGELOG.md | 1 +
.../org/jabref/gui/keyboard/KeyBinding.java | 1 +
.../java/org/jabref/gui/util/BaseDialog.java | 17 +++++++++++++++++
src/main/resources/l10n/JabRef_en.properties | 2 ++
4 files changed, 21 insertions(+)
diff --git a/CHANGELOG.md b/CHANGELOG.md
index ce2410787c6..9c29a663c2b 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -50,6 +50,7 @@ We refer to [GitHub issues](https://github.com/JabRef/jabref/issues) by using `#
- 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)
- 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/src/main/java/org/jabref/gui/keyboard/KeyBinding.java b/src/main/java/org/jabref/gui/keyboard/KeyBinding.java
index cd6f1c67613..b73fbc6b0c3 100644
--- a/src/main/java/org/jabref/gui/keyboard/KeyBinding.java
+++ b/src/main/java/org/jabref/gui/keyboard/KeyBinding.java
@@ -25,6 +25,7 @@ public enum KeyBinding {
ENTRY_EDITOR_PREVIOUS_PANEL_2("Entry editor, previous panel 2", Localization.lang("Entry editor, previous panel 2"), "ctrl+MINUS", KeyBindingCategory.VIEW),
DECREASE_TABLE_FONT_SIZE("Decrease table font size", Localization.lang("Decrease table font size"), "ctrl+MINUS", KeyBindingCategory.VIEW),
DELETE_ENTRY("Delete entry", Localization.lang("Delete entry"), "DELETE", KeyBindingCategory.BIBTEX),
+ DEFAULT_DIALOG_ACTION("Execute default action in dialog", Localization.lang("Execute default action in dialog"), "ctrl+ENTER", KeyBindingCategory.VIEW),
DOWNLOAD_FULL_TEXT("Look up full text documents", Localization.lang("Look up full text documents"), "alt+F7", KeyBindingCategory.QUALITY),
EDIT_ENTRY("Edit entry", Localization.lang("Edit entry"), "ctrl+E", KeyBindingCategory.BIBTEX),
EDIT_STRINGS("Edit strings", Localization.lang("Edit strings"), "ctrl+T", KeyBindingCategory.BIBTEX),
diff --git a/src/main/java/org/jabref/gui/util/BaseDialog.java b/src/main/java/org/jabref/gui/util/BaseDialog.java
index 59f6e034e3b..a05eb2862ce 100644
--- a/src/main/java/org/jabref/gui/util/BaseDialog.java
+++ b/src/main/java/org/jabref/gui/util/BaseDialog.java
@@ -1,5 +1,9 @@
package org.jabref.gui.util;
+import java.util.Optional;
+
+import javafx.scene.control.Button;
+import javafx.scene.control.ButtonType;
import javafx.scene.control.Dialog;
import javafx.scene.image.Image;
import javafx.stage.Stage;
@@ -16,6 +20,8 @@ protected BaseDialog() {
KeyBindingRepository keyBindingRepository = Globals.getKeyPrefs();
if (keyBindingRepository.checkKeyCombinationEquality(KeyBinding.CLOSE, event)) {
close();
+ } else if (keyBindingRepository.checkKeyCombinationEquality(KeyBinding.DEFAULT_DIALOG_ACTION, event)) {
+ getDefaultButton().ifPresent(Button::fire);
}
});
@@ -24,6 +30,17 @@ protected BaseDialog() {
Globals.getThemeLoader().installCss(getDialogPane().getScene(), Globals.prefs);
}
+ private Optional
- */
- private static class ZipFileChooserTableModel extends AbstractTableModel {
-
- private final List columnNames = Arrays.asList(Localization.lang("Name"),
- Localization.lang("Last modified"), Localization.lang("Size"));
- private final List rows;
- private final ZipFile zipFile;
-
-
- ZipFileChooserTableModel(ZipFile zipFile, List rows) {
- super();
- this.rows = rows;
- this.zipFile = zipFile;
- }
-
- /*
- * (non-Javadoc)
- * @see javax.swing.table.TableModel#getColumnCount()
- */
- @Override
- public int getColumnCount() {
- return columnNames.size();
- }
-
- /*
- * (non-Javadoc)
- * @see javax.swing.table.TableModel#getRowCount()
- */
- @Override
- public int getRowCount() {
- return this.rows.size();
- }
-
- /*
- * (non-Javadoc)
- * @see javax.swing.table.TableModel#getColumnName(int)
- */
- @Override
- public String getColumnName(int col) {
- return columnNames.get(col);
- }
-
- /**
- * ZIP-File entry at the given row index.
- *
- * @param rowIndex row index
- * @return ZIP file entry
- */
- public ZipEntry getZipEntry(int rowIndex) {
- return this.rows.get(rowIndex);
- }
-
- /**
- * ZIP file which contains all entries of this model.
- *
- * @return zip file
- */
- public ZipFile getZipFile() {
- return this.zipFile;
- }
-
- /*
- * (non-Javadoc)
- * @see javax.swing.table.TableModel#getValueAt(int, int)
- */
- @Override
- public Object getValueAt(int rowIndex, int columnIndex) {
- Object value = null;
- ZipEntry entry = getZipEntry(rowIndex);
- if (columnIndex == 0) {
- value = entry.getName();
- } else if (columnIndex == 1) {
- value = ZonedDateTime.ofInstant(new Date(entry.getTime()).toInstant(),
- ZoneId.systemDefault())
- .format(DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM));
- } else if (columnIndex == 2) {
- value = entry.getSize();
- }
- return value;
- }
- }
-
-}
diff --git a/src/main/java/org/jabref/gui/util/ViewModelTableRowFactory.java b/src/main/java/org/jabref/gui/util/ViewModelTableRowFactory.java
index 6e053fc3a40..78d50765935 100644
--- a/src/main/java/org/jabref/gui/util/ViewModelTableRowFactory.java
+++ b/src/main/java/org/jabref/gui/util/ViewModelTableRowFactory.java
@@ -8,6 +8,7 @@
import javafx.scene.control.ContextMenu;
import javafx.scene.control.TableRow;
import javafx.scene.control.TableView;
+import javafx.scene.control.Tooltip;
import javafx.scene.control.TreeTableCell;
import javafx.scene.input.DragEvent;
import javafx.scene.input.KeyCode;
@@ -16,6 +17,8 @@
import javafx.scene.input.MouseEvent;
import javafx.util.Callback;
+import org.jabref.model.strings.StringUtil;
+
import org.reactfx.util.TriConsumer;
/**
@@ -33,6 +36,7 @@ public class ViewModelTableRowFactory implements Callback, Table
private BiConsumer toOnDragExited;
private BiConsumer toOnDragOver;
private TriConsumer, S, ? super MouseDragEvent> toOnMouseDragEntered;
+ private Callback toTooltip;
public ViewModelTableRowFactory withOnMouseClickedEvent(BiConsumer onMouseClickedEvent) {
this.onMouseClickedEvent = onMouseClickedEvent;
@@ -84,10 +88,22 @@ public ViewModelTableRowFactory setOnDragOver(BiConsumer withTooltip(Callback toTooltip) {
+ this.toTooltip = toTooltip;
+ return this;
+ }
+
@Override
public TableRow call(TableView tableView) {
TableRow row = new TableRow<>();
+ if (toTooltip != null) {
+ String tooltipText = toTooltip.call(row.getItem());
+ if (StringUtil.isNotBlank(tooltipText)) {
+ row.setTooltip(new Tooltip(tooltipText));
+ }
+ }
+
if (onMouseClickedEvent != null) {
row.setOnMouseClicked(event -> {
if (!row.isEmpty()) {
diff --git a/src/main/java/org/jabref/gui/util/ZipFileChooser.java b/src/main/java/org/jabref/gui/util/ZipFileChooser.java
new file mode 100644
index 00000000000..74049324e9d
--- /dev/null
+++ b/src/main/java/org/jabref/gui/util/ZipFileChooser.java
@@ -0,0 +1,96 @@
+package org.jabref.gui.util;
+
+import java.io.IOException;
+import java.nio.file.FileSystem;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.time.ZoneId;
+import java.time.ZonedDateTime;
+import java.time.format.DateTimeFormatter;
+import java.time.format.FormatStyle;
+import java.util.stream.Collectors;
+
+import javafx.beans.property.ReadOnlyLongWrapper;
+import javafx.beans.property.ReadOnlyStringWrapper;
+import javafx.collections.FXCollections;
+import javafx.collections.ObservableList;
+import javafx.scene.control.ButtonType;
+import javafx.scene.control.SelectionMode;
+import javafx.scene.control.TableColumn;
+import javafx.scene.control.TableView;
+
+import org.jabref.logic.l10n.Localization;
+
+/**
+ * Dialog to allow users to choose a file contained in a ZIP file.
+ */
+public class ZipFileChooser extends BaseDialog {
+
+ /**
+ * New ZIP file chooser.
+ *
+ * @param zipFile ZIP-Fle to choose from, must be readable
+ */
+ public ZipFileChooser(FileSystem zipFile) throws IOException {
+ setTitle(Localization.lang("Select file from ZIP-archive"));
+
+ TableView table = new TableView<>(getSelectableZipEntries(zipFile));
+ TableColumn nameColumn = new TableColumn<>(Localization.lang("Name"));
+ TableColumn modifiedColumn = new TableColumn<>(Localization.lang("Last modified"));
+ TableColumn sizeColumn = new TableColumn<>(Localization.lang("Size"));
+ table.getColumns().add(nameColumn);
+ table.getColumns().add(modifiedColumn);
+ table.getColumns().add(sizeColumn);
+ nameColumn.setCellValueFactory(data -> new ReadOnlyStringWrapper(data.getValue().toString()));
+ modifiedColumn.setCellValueFactory(data -> {
+ try {
+ return new ReadOnlyStringWrapper(
+ ZonedDateTime.ofInstant(Files.getLastModifiedTime(data.getValue()).toInstant(),
+ ZoneId.systemDefault())
+ .format(DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM)));
+ } catch (IOException e) {
+ // Ignore
+ return new ReadOnlyStringWrapper("");
+ }
+ });
+ sizeColumn.setCellValueFactory(data -> {
+ try {
+ return new ReadOnlyLongWrapper(Files.size(data.getValue()));
+ } catch (IOException e) {
+ // Ignore
+ return new ReadOnlyLongWrapper(0);
+ }
+ });
+ table.getSelectionModel().setSelectionMode(SelectionMode.SINGLE);
+
+ getDialogPane().setContent(table);
+
+ getDialogPane().getButtonTypes().setAll(
+ ButtonType.OK,
+ ButtonType.CANCEL
+ );
+
+ setResultConverter(button -> {
+ if (button == ButtonType.OK) {
+ return table.getSelectionModel().getSelectedItem();
+ } else {
+ return null;
+ }
+ });
+ }
+
+ /**
+ * Entries that can be selected with this dialog.
+ *
+ * @param zipFile ZIP-File
+ * @return entries that can be selected
+ */
+ private static ObservableList getSelectableZipEntries(FileSystem zipFile) throws IOException {
+ Path rootDir = zipFile.getRootDirectories().iterator().next();
+
+ return FXCollections.observableArrayList(
+ Files.walk(rootDir)
+ .filter(file -> file.endsWith(".class"))
+ .collect(Collectors.toList()));
+ }
+}
diff --git a/src/main/resources/l10n/JabRef_en.properties b/src/main/resources/l10n/JabRef_en.properties
index f3a0cae326a..90fe32bdc9d 100644
--- a/src/main/resources/l10n/JabRef_en.properties
+++ b/src/main/resources/l10n/JabRef_en.properties
@@ -40,17 +40,10 @@ Add=Add
Add\ a\ (compiled)\ custom\ Importer\ class\ from\ a\ class\ path.=Add a (compiled) custom Importer class from a class path.
The\ path\ need\ not\ be\ on\ the\ classpath\ of\ JabRef.=The path need not be on the classpath of JabRef.
-Add\ a\ (compiled)\ custom\ Importer\ class\ from\ a\ ZIP-archive.=Add a (compiled) custom Importer class from a ZIP-archive.
-The\ ZIP-archive\ need\ not\ be\ on\ the\ classpath\ of\ JabRef.=The ZIP-archive need not be on the classpath of JabRef.
-
Add\ a\ regular\ expression\ for\ the\ key\ pattern.=Add a regular expression for the key pattern.
Add\ selected\ entries\ to\ this\ group=Add selected entries to this group
-Add\ from\ folder=Add from folder
-
-Add\ from\ JAR=Add from JAR
-
Add\ subgroup=Add subgroup
Add\ to\ group=Add to group
@@ -155,8 +148,6 @@ Clear=Clear
Clear\ fields=Clear fields
-Close=Close
-
Close\ entry=Close entry
Close\ dialog=Close dialog
@@ -167,7 +158,6 @@ Close\ window=Close window
Closed\ library=Closed library
-Command\ line\ id=Command line id
Comments=Comments
Contained\ in=Contained in
@@ -784,8 +774,6 @@ Please\ enter\ the\ field\ to\ search\ (e.g.\ keywords)\ and\ the\ keywor
Please\ enter\ the\ string's\ label=Please enter the string's label
-Please\ select\ an\ importer.=Please select an importer.
-
Please\ restart\ JabRef\ for\ preferences\ to\ take\ effect.=Please restart JabRef for preferences to take effect.
Possible\ duplicate\ entries=Possible duplicate entries
@@ -967,8 +955,6 @@ Show\ BibTeX\ source\ by\ default=Show BibTeX source by default
Show\ confirmation\ dialog\ when\ deleting\ entries=Show confirmation dialog when deleting entries
-Show\ description=Show description
-
Show\ file\ column=Show file column
Show\ last\ names\ only=Show last names only
From 18aba35fcf77fad95577e3213e1eb66f5256cf42 Mon Sep 17 00:00:00 2001
From: Christoph
Date: Fri, 25 Jan 2019 16:36:16 +0100
Subject: [PATCH 10/20] Convert OO/LO SidePanel to javafx (#4341)
* Convert OO/LO SidePanel to javafx
First attempt at converting the OpenOffice side panel
* rework first part of select style dialog
* add icon to delete style
add edit function
implement rest of logic
* store settings, show path
load last selected style
subscribe preview panel to changes
* update from scence builder
* fix ok button
wrap preview panel in vbox
* add title for canceable progess dialog
rework manual connect
rework settings popup
initialize oo prefs to avoid NPE
remove old style dialog
* formatting
* Create custom dialog which returns a dialog object
fix preference storage
fix manual path select
* pass keybinding repo as dependency
* add new dialog for advanced cite
todo: find out how to change the values
* reload preferences in connect
fix passing of prefs
fix advanced cite dialog
* fix checkstyle
add some dialog basics for manage citatiosn
* further implement viewModel
* implement viewModel
fix l10n parts
TODO: editing of extra info does not yet work
* remove submodule
* Display Manage citations as TextFlow in the table
Allow editing of page info directly in the table
Replace html bold with Text-Bold style
* fix checkstyle
* rework page info
remove old dialog
fix l10n
set titles
add tooltips
* use flowpane instead of textflow to prevent table row height increasing
* cleanup and fix codacy issues
* rework dialogs
rework future handling in detect OO installation
* rework constructor and rename to CitationEntryViewModel
move gui getText to view
* fix checkstyle and l10n issues
* fix order
* fix style file select layout and inline variable'
* Add Book as preview as well
* change mac default settings to LO path
* checkstyle
* fix merge error
* first part of refactoring
* refactor and remove/fix obsolete tests
put visible/managed bindings in fxml
* Fixes #4576
Store show/hide info of panel in preferences
* use progessbar from fxdialogs
TODO: Fix execution in fx thread
* Fix autodetecting open office paths in background thread
Fix saving of settings after auto connect
Add notification when connections are cleared
remove custom dialog hack
* fix checkstyle
---
.../java/org/jabref/gui/DialogService.java | 8 +-
.../java/org/jabref/gui/FXDialogService.java | 14 +-
.../java/org/jabref/gui/SidePaneManager.java | 4 +-
.../gui/openoffice/AdvancedCiteDialog.fxml | 30 +
.../gui/openoffice/AdvancedCiteDialog.java | 113 ---
.../openoffice/AdvancedCiteDialogView.java | 46 +
.../AdvancedCiteDialogViewModel.java | 25 +
.../openoffice/BibEntryNotFoundException.java | 1 -
.../openoffice/CitationEntryViewModel.java | 40 +
.../gui/openoffice/CitationManager.java | 237 ------
.../DetectOpenOfficeInstallation.java | 86 +-
.../gui/openoffice/ManageCitationsDialog.fxml | 21 +
.../openoffice/ManageCitationsDialogView.java | 95 +++
.../ManageCitationsDialogViewModel.java | 73 ++
.../gui/openoffice/ManualConnectDialog.fxml | 43 +
.../openoffice/ManualConnectDialogView.java | 90 ++
.../ManualConnectDialogViewModel.java | 79 ++
.../org/jabref/gui/openoffice/OOBibBase.java | 140 ++--
.../gui/openoffice/OpenOfficePanel.java | 786 ++++++++----------
.../gui/openoffice/OpenOfficeSidePanel.java | 24 +-
.../gui/openoffice/StyleSelectDialog.fxml | 39 +
.../gui/openoffice/StyleSelectDialog.java | 538 ------------
.../gui/openoffice/StyleSelectDialogView.java | 145 ++++
.../StyleSelectDialogViewModel.java | 137 +++
.../openoffice/StyleSelectItemViewModel.java | 59 ++
.../UndefinedCharacterFormatException.java | 1 -
.../logic/openoffice/CitationEntry.java | 27 +-
.../jabref/logic/openoffice/OOBibStyle.java | 7 +-
.../openoffice/OpenOfficePreferences.java | 39 +-
.../java/org/jabref/logic/util/TestEntry.java | 13 +
.../jabref/preferences/JabRefPreferences.java | 3 +
.../preferences/PreferencesService.java | 8 +
src/main/resources/l10n/JabRef_en.properties | 11 +-
.../logic/openoffice/CitationEntryTest.java | 32 +-
34 files changed, 1443 insertions(+), 1571 deletions(-)
create mode 100644 src/main/java/org/jabref/gui/openoffice/AdvancedCiteDialog.fxml
delete mode 100644 src/main/java/org/jabref/gui/openoffice/AdvancedCiteDialog.java
create mode 100644 src/main/java/org/jabref/gui/openoffice/AdvancedCiteDialogView.java
create mode 100644 src/main/java/org/jabref/gui/openoffice/AdvancedCiteDialogViewModel.java
create mode 100644 src/main/java/org/jabref/gui/openoffice/CitationEntryViewModel.java
delete mode 100644 src/main/java/org/jabref/gui/openoffice/CitationManager.java
create mode 100644 src/main/java/org/jabref/gui/openoffice/ManageCitationsDialog.fxml
create mode 100644 src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogView.java
create mode 100644 src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogViewModel.java
create mode 100644 src/main/java/org/jabref/gui/openoffice/ManualConnectDialog.fxml
create mode 100644 src/main/java/org/jabref/gui/openoffice/ManualConnectDialogView.java
create mode 100644 src/main/java/org/jabref/gui/openoffice/ManualConnectDialogViewModel.java
create mode 100644 src/main/java/org/jabref/gui/openoffice/StyleSelectDialog.fxml
delete mode 100644 src/main/java/org/jabref/gui/openoffice/StyleSelectDialog.java
create mode 100644 src/main/java/org/jabref/gui/openoffice/StyleSelectDialogView.java
create mode 100644 src/main/java/org/jabref/gui/openoffice/StyleSelectDialogViewModel.java
create mode 100644 src/main/java/org/jabref/gui/openoffice/StyleSelectItemViewModel.java
diff --git a/src/main/java/org/jabref/gui/DialogService.java b/src/main/java/org/jabref/gui/DialogService.java
index 947fa1c66a0..2e105481d1d 100644
--- a/src/main/java/org/jabref/gui/DialogService.java
+++ b/src/main/java/org/jabref/gui/DialogService.java
@@ -140,7 +140,7 @@ default void showErrorDialogAndWait(Exception exception) {
* @return true if the use clicked "YES" otherwise false
*/
boolean showConfirmationDialogWithOptOutAndWait(String title, String content,
- String optOutMessage, Consumer optOutAction);
+ String optOutMessage, Consumer optOutAction);
/**
* Create and display a new confirmation dialog.
@@ -152,8 +152,8 @@ boolean showConfirmationDialogWithOptOutAndWait(String title, String content,
* @return true if the use clicked "YES" otherwise false
*/
boolean showConfirmationDialogWithOptOutAndWait(String title, String content,
- String okButtonLabel, String cancelButtonLabel,
- String optOutMessage, Consumer optOutAction);
+ String okButtonLabel, String cancelButtonLabel,
+ String optOutMessage, Consumer optOutAction);
/**
* This will create and display a new dialog of the specified
@@ -163,7 +163,7 @@ boolean showConfirmationDialogWithOptOutAndWait(String title, String content,
* @return Optional with the pressed Button as ButtonType
*/
Optional showCustomButtonDialogAndWait(Alert.AlertType type, String title, String content,
- ButtonType... buttonTypes);
+ ButtonType... buttonTypes);
/**
* This will create and display a new dialog showing a custom {@link DialogPane}
diff --git a/src/main/java/org/jabref/gui/FXDialogService.java b/src/main/java/org/jabref/gui/FXDialogService.java
index 93470689c79..0d6bc1fecd0 100644
--- a/src/main/java/org/jabref/gui/FXDialogService.java
+++ b/src/main/java/org/jabref/gui/FXDialogService.java
@@ -74,7 +74,7 @@ private static FXDialog createDialog(AlertType type, String title, String conten
}
private static FXDialog createDialogWithOptOut(AlertType type, String title, String content,
- String optOutMessage, Consumer optOutAction) {
+ String optOutMessage, Consumer optOutAction) {
FXDialog alert = new FXDialog(type, title, true);
// Need to force the alert to layout in order to grab the graphic as we are replacing the dialog pane with a custom pane
alert.getDialogPane().applyCss();
@@ -180,7 +180,7 @@ public boolean showConfirmationDialogAndWait(String title, String content, Strin
@Override
public boolean showConfirmationDialogAndWait(String title, String content,
- String okButtonLabel, String cancelButtonLabel) {
+ String okButtonLabel, String cancelButtonLabel) {
FXDialog alert = createDialog(AlertType.CONFIRMATION, title, content);
ButtonType okButtonType = new ButtonType(okButtonLabel, ButtonBar.ButtonData.OK_DONE);
ButtonType cancelButtonType = new ButtonType(cancelButtonLabel, ButtonBar.ButtonData.NO);
@@ -190,7 +190,7 @@ public boolean showConfirmationDialogAndWait(String title, String content,
@Override
public boolean showConfirmationDialogWithOptOutAndWait(String title, String content,
- String optOutMessage, Consumer optOutAction) {
+ String optOutMessage, Consumer optOutAction) {
FXDialog alert = createDialogWithOptOut(AlertType.CONFIRMATION, title, content, optOutMessage, optOutAction);
alert.getButtonTypes().setAll(ButtonType.YES, ButtonType.NO);
return alert.showAndWait().filter(buttonType -> buttonType == ButtonType.YES).isPresent();
@@ -198,8 +198,8 @@ public boolean showConfirmationDialogWithOptOutAndWait(String title, String cont
@Override
public boolean showConfirmationDialogWithOptOutAndWait(String title, String content,
- String okButtonLabel, String cancelButtonLabel,
- String optOutMessage, Consumer optOutAction) {
+ String okButtonLabel, String cancelButtonLabel,
+ String optOutMessage, Consumer optOutAction) {
FXDialog alert = createDialogWithOptOut(AlertType.CONFIRMATION, title, content, optOutMessage, optOutAction);
ButtonType okButtonType = new ButtonType(okButtonLabel, ButtonBar.ButtonData.YES);
ButtonType cancelButtonType = new ButtonType(cancelButtonLabel, ButtonBar.ButtonData.NO);
@@ -209,7 +209,7 @@ public boolean showConfirmationDialogWithOptOutAndWait(String title, String cont
@Override
public Optional showCustomButtonDialogAndWait(AlertType type, String title, String content,
- ButtonType... buttonTypes) {
+ ButtonType... buttonTypes) {
FXDialog alert = createDialog(type, title, content);
alert.getButtonTypes().setAll(buttonTypes);
return alert.showAndWait();
@@ -217,7 +217,7 @@ public Optional showCustomButtonDialogAndWait(AlertType type, String
@Override
public Optional showCustomDialogAndWait(String title, DialogPane contentPane,
- ButtonType... buttonTypes) {
+ ButtonType... buttonTypes) {
FXDialog alert = new FXDialog(AlertType.NONE, title);
alert.setDialogPane(contentPane);
alert.getButtonTypes().setAll(buttonTypes);
diff --git a/src/main/java/org/jabref/gui/SidePaneManager.java b/src/main/java/org/jabref/gui/SidePaneManager.java
index 5a09bdcd1ab..eef7f01098b 100644
--- a/src/main/java/org/jabref/gui/SidePaneManager.java
+++ b/src/main/java/org/jabref/gui/SidePaneManager.java
@@ -33,8 +33,8 @@ public SidePaneManager(JabRefPreferences preferences, JabRefFrame frame) {
Stream.of(
new FileUpdatePanel(this),
new GroupSidePane(this, preferences, frame.getDialogService()),
- new WebSearchPane(this, preferences, frame),
- new OpenOfficeSidePanel(this, openOfficePreferences, frame))
+ 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/openoffice/AdvancedCiteDialog.fxml b/src/main/java/org/jabref/gui/openoffice/AdvancedCiteDialog.fxml
new file mode 100644
index 00000000000..1127c2e08d7
--- /dev/null
+++ b/src/main/java/org/jabref/gui/openoffice/AdvancedCiteDialog.fxml
@@ -0,0 +1,30 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/src/main/java/org/jabref/gui/openoffice/AdvancedCiteDialog.java b/src/main/java/org/jabref/gui/openoffice/AdvancedCiteDialog.java
deleted file mode 100644
index 2a2d48ef26e..00000000000
--- a/src/main/java/org/jabref/gui/openoffice/AdvancedCiteDialog.java
+++ /dev/null
@@ -1,113 +0,0 @@
-package org.jabref.gui.openoffice;
-
-import java.awt.BorderLayout;
-import java.awt.event.ActionEvent;
-import java.awt.event.ActionListener;
-
-import javax.swing.AbstractAction;
-import javax.swing.Action;
-import javax.swing.ButtonGroup;
-import javax.swing.JButton;
-import javax.swing.JComponent;
-import javax.swing.JDialog;
-import javax.swing.JFrame;
-import javax.swing.JRadioButton;
-import javax.swing.JTextField;
-
-import org.jabref.Globals;
-import org.jabref.gui.JabRefFrame;
-import org.jabref.gui.keyboard.KeyBinding;
-import org.jabref.logic.l10n.Localization;
-
-import com.jgoodies.forms.builder.ButtonBarBuilder;
-import com.jgoodies.forms.builder.FormBuilder;
-import com.jgoodies.forms.layout.FormLayout;
-
-/**
- * Dialog for adding citation with page number info.
- */
-class AdvancedCiteDialog {
-
- private static boolean defaultInPar = true;
- private boolean okPressed;
- private final JDialog diag;
- private final JTextField pageInfo = new JTextField(15);
-
-
- public AdvancedCiteDialog(JabRefFrame parent) {
- diag = new JDialog((JFrame) null, Localization.lang("Cite special"), true);
- ButtonGroup bg = new ButtonGroup();
- JRadioButton inPar = new JRadioButton(Localization.lang("Cite selected entries between parenthesis"));
- JRadioButton inText = new JRadioButton(Localization.lang("Cite selected entries with in-text citation"));
- bg.add(inPar);
- bg.add(inText);
- if (defaultInPar) {
- inPar.setSelected(true);
- } else {
- inText.setSelected(true);
- }
-
- inPar.addChangeListener(changeEvent -> defaultInPar = inPar.isSelected());
-
- FormBuilder builder = FormBuilder.create()
- .layout(new FormLayout("left:pref, 4dlu, fill:pref", "pref, 4dlu, pref, 4dlu, pref"));
- builder.add(inPar).xyw(1, 1, 3);
- builder.add(inText).xyw(1, 3, 3);
- builder.add(Localization.lang("Extra information (e.g. page number)") + ":").xy(1, 5);
- builder.add(pageInfo).xy(3, 5);
- builder.padding("10dlu, 10dlu, 10dlu, 10dlu");
- diag.getContentPane().add(builder.getPanel(), BorderLayout.CENTER);
-
- ButtonBarBuilder bb = new ButtonBarBuilder();
- bb.addGlue();
- JButton ok = new JButton(Localization.lang("OK"));
- JButton cancel = new JButton(Localization.lang("Cancel"));
- bb.addButton(ok);
- bb.addButton(cancel);
- bb.addGlue();
- bb.padding("5dlu, 5dlu, 5dlu, 5dlu");
- diag.getContentPane().add(bb.getPanel(), BorderLayout.SOUTH);
-
- diag.pack();
-
- ActionListener okAction = actionEvent -> {
- okPressed = true;
- diag.dispose();
- };
-
- ok.addActionListener(okAction);
- pageInfo.addActionListener(okAction);
- inPar.addActionListener(okAction);
- inText.addActionListener(okAction);
- Action cancelAction = new AbstractAction() {
-
- @Override
- public void actionPerformed(ActionEvent actionEvent) {
- okPressed = false;
- diag.dispose();
- }
- };
- cancel.addActionListener(cancelAction);
- builder.getPanel().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW)
- .put(Globals.getKeyPrefs().getKey(KeyBinding.CLOSE), "close");
- builder.getPanel().getActionMap().put("close", cancelAction);
-
- }
-
- public void showDialog() {
- diag.setLocationRelativeTo(diag.getParent());
- diag.setVisible(true);
- }
-
- public boolean canceled() {
- return !okPressed;
- }
-
- public String getPageInfo() {
- return pageInfo.getText().trim();
- }
-
- public boolean isInParenthesisCite() {
- return defaultInPar;
- }
-}
diff --git a/src/main/java/org/jabref/gui/openoffice/AdvancedCiteDialogView.java b/src/main/java/org/jabref/gui/openoffice/AdvancedCiteDialogView.java
new file mode 100644
index 00000000000..f12e34fcdbe
--- /dev/null
+++ b/src/main/java/org/jabref/gui/openoffice/AdvancedCiteDialogView.java
@@ -0,0 +1,46 @@
+package org.jabref.gui.openoffice;
+
+import javafx.fxml.FXML;
+import javafx.scene.control.ButtonType;
+import javafx.scene.control.RadioButton;
+import javafx.scene.control.TextField;
+import javafx.scene.control.ToggleGroup;
+
+import org.jabref.gui.util.BaseDialog;
+import org.jabref.logic.l10n.Localization;
+
+import com.airhacks.afterburner.views.ViewLoader;
+
+public class AdvancedCiteDialogView extends BaseDialog {
+
+ @FXML private TextField pageInfo;
+ @FXML private RadioButton inPar;
+ @FXML private RadioButton inText;
+ @FXML private ToggleGroup citeToggleGroup;
+ private AdvancedCiteDialogViewModel viewModel;
+
+ public AdvancedCiteDialogView() {
+
+ ViewLoader.view(this)
+ .load()
+ .setAsDialogPane(this);
+ setResultConverter(btn -> {
+ if (btn == ButtonType.OK) {
+ return viewModel;
+ }
+ return null;
+ });
+
+ setTitle(Localization.lang("Cite special"));
+ }
+
+ @FXML
+ private void initialize() {
+ viewModel = new AdvancedCiteDialogViewModel();
+
+ 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/AdvancedCiteDialogViewModel.java b/src/main/java/org/jabref/gui/openoffice/AdvancedCiteDialogViewModel.java
new file mode 100644
index 00000000000..c62abfeccec
--- /dev/null
+++ b/src/main/java/org/jabref/gui/openoffice/AdvancedCiteDialogViewModel.java
@@ -0,0 +1,25 @@
+package org.jabref.gui.openoffice;
+
+import javafx.beans.property.BooleanProperty;
+import javafx.beans.property.SimpleBooleanProperty;
+import javafx.beans.property.SimpleStringProperty;
+import javafx.beans.property.StringProperty;
+
+public class AdvancedCiteDialogViewModel {
+
+ private final StringProperty pageInfo = new SimpleStringProperty("");
+ private final BooleanProperty citeInPar = new SimpleBooleanProperty();
+ private final BooleanProperty citeInText = new SimpleBooleanProperty();
+
+ public StringProperty pageInfoProperty() {
+ return pageInfo;
+ }
+
+ public BooleanProperty citeInParProperty() {
+ return citeInPar;
+ }
+
+ public BooleanProperty citeInTextProperty() {
+ return citeInText;
+ }
+}
diff --git a/src/main/java/org/jabref/gui/openoffice/BibEntryNotFoundException.java b/src/main/java/org/jabref/gui/openoffice/BibEntryNotFoundException.java
index 15dde84a5fb..3a83f8c7177 100644
--- a/src/main/java/org/jabref/gui/openoffice/BibEntryNotFoundException.java
+++ b/src/main/java/org/jabref/gui/openoffice/BibEntryNotFoundException.java
@@ -4,7 +4,6 @@ class BibEntryNotFoundException extends Exception {
private final String bibtexKey;
-
public BibEntryNotFoundException(String bibtexKey, String message) {
super(message);
diff --git a/src/main/java/org/jabref/gui/openoffice/CitationEntryViewModel.java b/src/main/java/org/jabref/gui/openoffice/CitationEntryViewModel.java
new file mode 100644
index 00000000000..58ac9f04ecd
--- /dev/null
+++ b/src/main/java/org/jabref/gui/openoffice/CitationEntryViewModel.java
@@ -0,0 +1,40 @@
+package org.jabref.gui.openoffice;
+
+import javafx.beans.property.SimpleStringProperty;
+import javafx.beans.property.StringProperty;
+
+import org.jabref.logic.openoffice.CitationEntry;
+
+public class CitationEntryViewModel {
+
+ private final StringProperty citation = new SimpleStringProperty("");
+ private final StringProperty extraInformation = new SimpleStringProperty("");
+ private final String refMarkName;
+
+ public CitationEntryViewModel(String refMarkName, String citation, String extraInfo) {
+ this.refMarkName = refMarkName;
+ this.citation.setValue(citation);
+ this.extraInformation.setValue(extraInfo);
+ }
+
+ public CitationEntryViewModel(CitationEntry citationEntry) {
+ this(citationEntry.getRefMarkName(), citationEntry.getContext(), citationEntry.getPageInfo().orElse(""));
+ }
+
+ public CitationEntry toCitationEntry() {
+ return new CitationEntry(refMarkName, citation.getValue(), extraInformation.getValue());
+ }
+
+ public StringProperty citationProperty() {
+ return citation;
+ }
+
+ public StringProperty extraInformationProperty() {
+ return extraInformation;
+ }
+
+ public void setExtraInfo(String extraInfo) {
+ extraInformation.setValue(extraInfo);
+ }
+
+}
diff --git a/src/main/java/org/jabref/gui/openoffice/CitationManager.java b/src/main/java/org/jabref/gui/openoffice/CitationManager.java
deleted file mode 100644
index ae75d693d95..00000000000
--- a/src/main/java/org/jabref/gui/openoffice/CitationManager.java
+++ /dev/null
@@ -1,237 +0,0 @@
-package org.jabref.gui.openoffice;
-
-import java.awt.BorderLayout;
-import java.awt.Dimension;
-import java.awt.event.ActionEvent;
-import java.awt.event.MouseAdapter;
-import java.awt.event.MouseEvent;
-import java.util.List;
-import java.util.Optional;
-
-import javax.swing.AbstractAction;
-import javax.swing.Action;
-import javax.swing.BorderFactory;
-import javax.swing.JButton;
-import javax.swing.JComponent;
-import javax.swing.JDialog;
-import javax.swing.JFrame;
-import javax.swing.JScrollPane;
-import javax.swing.JTable;
-import javax.swing.JTextField;
-
-import org.jabref.Globals;
-import org.jabref.gui.DialogService;
-import org.jabref.gui.keyboard.KeyBinding;
-import org.jabref.logic.l10n.Localization;
-import org.jabref.logic.openoffice.CitationEntry;
-
-import ca.odell.glazedlists.BasicEventList;
-import ca.odell.glazedlists.EventList;
-import ca.odell.glazedlists.gui.TableFormat;
-import ca.odell.glazedlists.swing.DefaultEventTableModel;
-import com.jgoodies.forms.builder.ButtonBarBuilder;
-import com.jgoodies.forms.builder.FormBuilder;
-import com.jgoodies.forms.layout.FormLayout;
-import com.sun.star.beans.IllegalTypeException;
-import com.sun.star.beans.NotRemoveableException;
-import com.sun.star.beans.PropertyExistException;
-import com.sun.star.beans.UnknownPropertyException;
-import com.sun.star.container.NoSuchElementException;
-import com.sun.star.container.XNameAccess;
-import com.sun.star.lang.IllegalArgumentException;
-import com.sun.star.lang.WrappedTargetException;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * Dialog for modifying existing citations.
- */
-class CitationManager {
-
- private static final Logger LOGGER = LoggerFactory.getLogger(CitationManager.class);
- private final OOBibBase ooBase;
- private final JDialog diag;
- private final EventList list;
- private final JTable table;
-
- private final DefaultEventTableModel tableModel;
-
- public CitationManager(OOBibBase ooBase, DialogService dialogService)
- throws NoSuchElementException, WrappedTargetException, UnknownPropertyException {
- diag = new JDialog((JFrame) null, Localization.lang("Manage citations"), true);
- this.ooBase = ooBase;
-
- list = new BasicEventList<>();
- XNameAccess nameAccess = ooBase.getReferenceMarks();
- List names = ooBase.getJabRefReferenceMarks(nameAccess);
- for (String name : names) {
- list.add(new CitationEntry(name,
- "..." + ooBase.getCitationContext(nameAccess, name, 30, 30, true) + "...",
- ooBase.getCustomProperty(name)));
- }
- tableModel = new DefaultEventTableModel<>(list, new CitationEntryFormat());
- table = new JTable(tableModel);
-
- diag.add(new JScrollPane(table), BorderLayout.CENTER);
-
- ButtonBarBuilder bb = new ButtonBarBuilder();
- bb.addGlue();
- JButton ok = new JButton(Localization.lang("OK"));
- bb.addButton(ok);
- JButton cancel = new JButton(Localization.lang("Cancel"));
- bb.addButton(cancel);
- bb.addGlue();
- bb.getPanel().setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
- diag.add(bb.getPanel(), BorderLayout.SOUTH);
-
- diag.pack();
- diag.setSize(700, 400);
-
- ok.addActionListener(e -> {
- try {
- storeSettings();
- } catch (UnknownPropertyException | NotRemoveableException | PropertyExistException | IllegalTypeException |
- IllegalArgumentException ex) {
- LOGGER.warn("Problem modifying citation", ex);
- dialogService.showErrorDialogAndWait(Localization.lang("Problem modifying citation"), ex);
- }
- diag.dispose();
- });
-
- Action cancelAction = new AbstractAction() {
-
- @Override
- public void actionPerformed(ActionEvent actionEvent) {
- diag.dispose();
- }
- };
- cancel.addActionListener(cancelAction);
-
- bb.getPanel().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put
- (Globals.getKeyPrefs().getKey(KeyBinding.CLOSE), "close");
- bb.getPanel().getActionMap().put("close", cancelAction);
-
- table.getColumnModel().getColumn(0).setPreferredWidth(580);
- table.getColumnModel().getColumn(1).setPreferredWidth(110);
- table.setPreferredScrollableViewportSize(new Dimension(700, 500));
- table.addMouseListener(new TableClickListener());
- }
-
- private void storeSettings() throws UnknownPropertyException, NotRemoveableException, PropertyExistException,
- IllegalTypeException, IllegalArgumentException {
- for (CitationEntry entry : list) {
- Optional pageInfo = entry.getPageInfo();
- if (entry.pageInfoChanged() && pageInfo.isPresent()) {
- ooBase.setCustomProperty(entry.getRefMarkName(), pageInfo.get());
- }
- }
- }
-
- public void showDialog() {
- diag.setLocationRelativeTo(diag.getParent());
- diag.setVisible(true);
- }
-
- private static class CitationEntryFormat implements TableFormat {
-
- @Override
- public int getColumnCount() {
- return 2;
- }
-
- @Override
- public String getColumnName(int i) {
- if (i == 0) {
- return Localization.lang("Citation");
- } else {
- return Localization.lang("Extra information");
- }
- }
-
- @Override
- public Object getColumnValue(CitationEntry citEntry, int i) {
- if (i == 0) {
- return citEntry.getContext();
- } else {
- return citEntry.getPageInfo().orElse("");
- }
- }
- }
-
- private class TableClickListener extends MouseAdapter {
-
- @Override
- public void mouseClicked(MouseEvent e) {
- if ((e.getButton() == MouseEvent.BUTTON1) && (e.getClickCount() == 2)) {
- int row = table.rowAtPoint(e.getPoint());
- if (row >= 0) {
- SingleCitationDialog scd = new SingleCitationDialog(list.get(row));
- scd.showDialog();
- }
- }
- }
- }
-
- class SingleCitationDialog {
-
- private final JDialog singleCiteDialog;
- private final JTextField pageInfo = new JTextField(20);
- private final JButton okButton = new JButton(Localization.lang("OK"));
- private final JButton cancelButton = new JButton(Localization.lang("Cancel"));
- private final CitationEntry entry;
-
-
- public SingleCitationDialog(CitationEntry citEntry) {
- this.entry = citEntry;
- pageInfo.setText(entry.getPageInfo().orElse(""));
-
- singleCiteDialog = new JDialog(CitationManager.this.diag, Localization.lang("Citation"), true);
-
- FormBuilder builder = FormBuilder.create()
- .layout(new FormLayout("left:pref, 4dlu, fill:150dlu:grow", "pref, 4dlu, pref"));
- builder.add(entry.getContext()).xyw(1, 1, 3);
- builder.add(Localization.lang("Extra information (e.g. page number)")).xy(1, 3);
- builder.add(pageInfo).xy(3, 3);
- builder.padding("10dlu, 10dlu, 10dlu, 10dlu");
- singleCiteDialog.getContentPane().add(builder.getPanel(), BorderLayout.CENTER);
-
- ButtonBarBuilder bb = new ButtonBarBuilder();
- bb.addGlue();
- bb.addButton(okButton);
- bb.addButton(cancelButton);
- bb.addGlue();
- bb.padding("5dlu, 5dlu, 5dlu, 5dlu");
- singleCiteDialog.add(bb.getPanel(), BorderLayout.SOUTH);
-
- okButton.addActionListener(e -> {
- if (pageInfo.getText().trim().isEmpty()) {
- entry.setPageInfo(null);
- } else {
- entry.setPageInfo(pageInfo.getText().trim());
- }
- tableModel.fireTableDataChanged();
- singleCiteDialog.dispose();
- });
-
- Action cancelAction = new AbstractAction() {
-
- @Override
- public void actionPerformed(ActionEvent actionEvent) {
- singleCiteDialog.dispose();
- }
- };
- cancelButton.addActionListener(cancelAction);
-
- builder.getPanel().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put
- (Globals.getKeyPrefs().getKey(KeyBinding.CLOSE), "close");
- builder.getPanel().getActionMap().put("close", cancelAction);
-
- }
-
- public void showDialog() {
- singleCiteDialog.pack();
- singleCiteDialog.setLocationRelativeTo(singleCiteDialog.getParent());
- singleCiteDialog.setVisible(true);
- }
- }
-}
diff --git a/src/main/java/org/jabref/gui/openoffice/DetectOpenOfficeInstallation.java b/src/main/java/org/jabref/gui/openoffice/DetectOpenOfficeInstallation.java
index 55853091840..1f4a892f14a 100644
--- a/src/main/java/org/jabref/gui/openoffice/DetectOpenOfficeInstallation.java
+++ b/src/main/java/org/jabref/gui/openoffice/DetectOpenOfficeInstallation.java
@@ -1,83 +1,57 @@
package org.jabref.gui.openoffice;
-import java.awt.BorderLayout;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Optional;
-import java.util.concurrent.CompletableFuture;
-import java.util.concurrent.Future;
-import javax.swing.BorderFactory;
-import javax.swing.JDialog;
-import javax.swing.JLabel;
-import javax.swing.JProgressBar;
-import javax.swing.SwingConstants;
-import javax.swing.SwingUtilities;
-
-import org.jabref.Globals;
import org.jabref.gui.DialogService;
import org.jabref.gui.desktop.JabRefDesktop;
import org.jabref.gui.desktop.os.NativeDesktop;
-import org.jabref.gui.util.BackgroundTask;
-import org.jabref.gui.util.DefaultTaskExecutor;
import org.jabref.gui.util.DirectoryDialogConfiguration;
import org.jabref.logic.l10n.Localization;
import org.jabref.logic.openoffice.OpenOfficeFileSearch;
import org.jabref.logic.openoffice.OpenOfficePreferences;
import org.jabref.logic.util.OS;
import org.jabref.logic.util.io.FileUtil;
+import org.jabref.model.strings.StringUtil;
+import org.jabref.preferences.JabRefPreferences;
/**
* Tools for automatically detecting OpenOffice or LibreOffice installations.
*/
public class DetectOpenOfficeInstallation {
- private final OpenOfficePreferences preferences;
- private final JDialog parent;
+ private final OpenOfficePreferences ooPrefs;
private final DialogService dialogService;
+ private final JabRefPreferences preferences;
- private JDialog progressDialog;
-
- public DetectOpenOfficeInstallation(JDialog parent, OpenOfficePreferences preferences, DialogService dialogService) {
- this.parent = parent;
+ public DetectOpenOfficeInstallation(JabRefPreferences preferences, DialogService dialogService) {
this.preferences = preferences;
this.dialogService = dialogService;
+ this.ooPrefs = preferences.getOpenOfficePreferences();
}
- public Future isInstalled() {
- CompletableFuture future = new CompletableFuture<>();
- if (this.checkAutoDetectedPaths(preferences)) {
- future.complete(true);
- } else {
- init();
- BackgroundTask.wrap(() -> future.complete(autoDetectPaths()))
- .onSuccess(x -> SwingUtilities.invokeLater(progressDialog::dispose))
- .executeWith(Globals.TASK_EXECUTOR);
- }
- return future;
+ public boolean isInstalled() {
+ return autoDetectPaths();
}
- public void init() {
- progressDialog = showProgressDialog(parent, Localization.lang("Autodetecting paths..."),
- Localization.lang("Please wait..."));
+ public boolean isExecutablePathDefined() {
+ return checkAutoDetectedPaths(ooPrefs);
}
private Optional selectInstallationPath() {
final NativeDesktop nativeDesktop = JabRefDesktop.getNativeDesktop();
- Optional path = DefaultTaskExecutor.runInJavaFXThread(() -> {
- dialogService.showInformationDialogAndWait(Localization.lang("Could not find OpenOffice/LibreOffice installation"),
- Localization.lang("Unable to autodetect OpenOffice/LibreOffice installation. Please choose the installation directory manually."));
- DirectoryDialogConfiguration dirDialogConfiguration = new DirectoryDialogConfiguration.Builder()
- .withInitialDirectory(nativeDesktop.getApplicationDirectory())
- .build();
- return dialogService.showDirectorySelectionDialog(dirDialogConfiguration);
- });
+ dialogService.showInformationDialogAndWait(Localization.lang("Could not find OpenOffice/LibreOffice installation"),
+ Localization.lang("Unable to autodetect OpenOffice/LibreOffice installation. Please choose the installation directory manually."));
+ DirectoryDialogConfiguration dirDialogConfiguration = new DirectoryDialogConfiguration.Builder()
+ .withInitialDirectory(nativeDesktop.getApplicationDirectory())
+ .build();
+ return dialogService.showDirectorySelectionDialog(dirDialogConfiguration);
- return path;
}
private boolean autoDetectPaths() {
@@ -102,7 +76,7 @@ private boolean autoDetectPaths() {
*/
private boolean checkAutoDetectedPaths(OpenOfficePreferences openOfficePreferences) {
String executablePath = openOfficePreferences.getExecutablePath();
- return ((executablePath != null) && Files.exists(Paths.get(executablePath)));
+ return !StringUtil.isNullOrEmpty(executablePath) && Files.exists(Paths.get(executablePath));
}
private boolean setOpenOfficePreferences(Path installDir) {
@@ -119,9 +93,10 @@ private boolean setOpenOfficePreferences(Path installDir) {
Optional jarFilePath = FileUtil.find(OpenOfficePreferences.OO_JARS.get(0), installDir);
if (execPath.isPresent() && jarFilePath.isPresent()) {
- preferences.setInstallationPath(installDir.toString());
- preferences.setExecutablePath(execPath.get().toString());
- preferences.setJarsPath(jarFilePath.get().getParent().toString());
+ ooPrefs.setInstallationPath(installDir.toString());
+ ooPrefs.setExecutablePath(execPath.get().toString());
+ ooPrefs.setJarsPath(jarFilePath.get().getParent().toString());
+ preferences.setOpenOfficePreferences(ooPrefs);
return true;
}
@@ -138,25 +113,12 @@ 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 = DefaultTaskExecutor.runInJavaFXThread(() -> dialogService.showChoiceDialogAndWait(
- Localization.lang("Choose OpenOffice/LibreOffice executable"),
- content, Localization.lang("Use selected instance"), installDirs));
+ Optional selectedPath = dialogService.showChoiceDialogAndWait(Localization.lang("Choose OpenOffice/LibreOffice executable"),
+ content, Localization.lang("Use selected instance"), installDirs);
return selectedPath;
}
- public JDialog showProgressDialog(JDialog progressParent, String title, String message) {
- JProgressBar bar = new JProgressBar(SwingConstants.HORIZONTAL);
- final JDialog progressDialog = new JDialog(progressParent, title, false);
- bar.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
- bar.setIndeterminate(true);
- progressDialog.add(new JLabel(message), BorderLayout.NORTH);
- progressDialog.add(bar, BorderLayout.CENTER);
- progressDialog.pack();
- progressDialog.setLocationRelativeTo(null);
- progressDialog.setVisible(true);
- return progressDialog;
- }
}
diff --git a/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialog.fxml b/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialog.fxml
new file mode 100644
index 00000000000..bde42841ce5
--- /dev/null
+++ b/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialog.fxml
@@ -0,0 +1,21 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogView.java b/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogView.java
new file mode 100644
index 00000000000..1f50783e89f
--- /dev/null
+++ b/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogView.java
@@ -0,0 +1,95 @@
+package org.jabref.gui.openoffice;
+
+import javax.inject.Inject;
+
+import javafx.fxml.FXML;
+import javafx.scene.Node;
+import javafx.scene.control.ButtonType;
+import javafx.scene.control.TableColumn;
+import javafx.scene.control.TableColumn.CellEditEvent;
+import javafx.scene.control.TableView;
+import javafx.scene.control.cell.TextFieldTableCell;
+import javafx.scene.layout.FlowPane;
+import javafx.scene.text.Text;
+
+import org.jabref.gui.DialogService;
+import org.jabref.gui.util.BaseDialog;
+import org.jabref.gui.util.ValueTableCellFactory;
+import org.jabref.logic.l10n.Localization;
+import org.jabref.model.strings.StringUtil;
+
+import com.airhacks.afterburner.views.ViewLoader;
+import com.sun.star.beans.UnknownPropertyException;
+import com.sun.star.container.NoSuchElementException;
+import com.sun.star.lang.WrappedTargetException;
+
+public class ManageCitationsDialogView extends BaseDialog {
+
+ private static final String HTML_BOLD_END_TAG = "";
+ private static final String HTML_BOLD_START_TAG = "";
+
+ private final OOBibBase ooBase;
+
+ @FXML private TableView citationsTableView;
+ @FXML private TableColumn citation;
+ @FXML private TableColumn extraInfo;
+
+ @Inject private DialogService dialogService;
+
+ private ManageCitationsDialogViewModel viewModel;
+
+ public ManageCitationsDialogView(OOBibBase ooBase) {
+ this.ooBase = ooBase;
+
+
+ ViewLoader.view(this)
+ .load()
+ .setAsDialogPane(this);
+
+ setResultConverter(btn -> {
+ if (btn == ButtonType.OK) {
+ viewModel.storeSettings();
+ }
+ return null;
+ });
+
+ setTitle(Localization.lang("Manage citations"));
+ }
+
+ @FXML
+ private void initialize() throws NoSuchElementException, WrappedTargetException, UnknownPropertyException {
+
+ viewModel = new ManageCitationsDialogViewModel(ooBase, dialogService);
+
+ citation.setCellValueFactory(cellData -> cellData.getValue().citationProperty());
+ new ValueTableCellFactory().withGraphic(this::getText).install(citation);
+
+ extraInfo.setCellValueFactory(cellData -> cellData.getValue().extraInformationProperty());
+ extraInfo.setEditable(true);
+
+ citationsTableView.setEditable(true);
+
+ citationsTableView.itemsProperty().bindBidirectional(viewModel.citationsProperty());
+
+ extraInfo.setOnEditCommit((CellEditEvent cell) -> {
+ 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());
+
+ Text startText = new Text(start);
+ Text inBetweenText = new Text(inBetween);
+ inBetweenText.setStyle("-fx-font-weight: bold");
+ Text endText = new Text(end);
+
+ FlowPane flow = new FlowPane(startText, inBetweenText, endText);
+ return flow;
+ }
+}
diff --git a/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogViewModel.java b/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogViewModel.java
new file mode 100644
index 00000000000..e928f5ee673
--- /dev/null
+++ b/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogViewModel.java
@@ -0,0 +1,73 @@
+package org.jabref.gui.openoffice;
+
+import java.util.List;
+import java.util.Optional;
+import java.util.stream.Collectors;
+
+import javafx.beans.property.ListProperty;
+import javafx.beans.property.SimpleListProperty;
+import javafx.collections.FXCollections;
+
+import org.jabref.gui.DialogService;
+import org.jabref.logic.l10n.Localization;
+import org.jabref.logic.openoffice.CitationEntry;
+
+import com.sun.star.beans.IllegalTypeException;
+import com.sun.star.beans.NotRemoveableException;
+import com.sun.star.beans.PropertyExistException;
+import com.sun.star.beans.UnknownPropertyException;
+import com.sun.star.container.NoSuchElementException;
+import com.sun.star.container.XNameAccess;
+import com.sun.star.lang.IllegalArgumentException;
+import com.sun.star.lang.WrappedTargetException;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class ManageCitationsDialogViewModel {
+
+ private static final Logger LOGGER = LoggerFactory.getLogger(ManageCitationsDialogViewModel.class);
+
+ private final ListProperty citations = new SimpleListProperty<>(FXCollections.observableArrayList());
+ private final OOBibBase ooBase;
+ private final DialogService dialogService;
+
+ public ManageCitationsDialogViewModel(OOBibBase ooBase, DialogService dialogService) throws NoSuchElementException, WrappedTargetException, UnknownPropertyException {
+ this.ooBase = ooBase;
+ this.dialogService = dialogService;
+
+ XNameAccess nameAccess = ooBase.getReferenceMarks();
+ List names = ooBase.getJabRefReferenceMarks(nameAccess);
+ for (String name : names) {
+
+ CitationEntry entry = new CitationEntry(name,
+ ooBase.getCitationContext(nameAccess, name, 30, 30, true),
+ ooBase.getCustomProperty(name));
+
+ CitationEntryViewModel itemViewModelEntry = new CitationEntryViewModel(entry);
+ citations.add(itemViewModelEntry);
+ }
+
+ }
+
+ public void storeSettings() {
+ List ciationEntries = citations.stream().map(CitationEntryViewModel::toCitationEntry).collect(Collectors.toList());
+ try {
+ for (CitationEntry entry : ciationEntries) {
+ Optional pageInfo = entry.getPageInfo();
+ if (pageInfo.isPresent()) {
+ ooBase.setCustomProperty(entry.getRefMarkName(), pageInfo.get());
+ }
+ }
+ } catch (UnknownPropertyException | NotRemoveableException | PropertyExistException | IllegalTypeException |
+ IllegalArgumentException ex) {
+ LOGGER.warn("Problem modifying citation", ex);
+ dialogService.showErrorDialogAndWait(Localization.lang("Problem modifying citation"), ex);
+ }
+ }
+
+ 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
new file mode 100644
index 00000000000..751462763d6
--- /dev/null
+++ b/src/main/java/org/jabref/gui/openoffice/ManualConnectDialog.fxml
@@ -0,0 +1,43 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/src/main/java/org/jabref/gui/openoffice/ManualConnectDialogView.java b/src/main/java/org/jabref/gui/openoffice/ManualConnectDialogView.java
new file mode 100644
index 00000000000..5352cf97198
--- /dev/null
+++ b/src/main/java/org/jabref/gui/openoffice/ManualConnectDialogView.java
@@ -0,0 +1,90 @@
+package org.jabref.gui.openoffice;
+
+import javax.inject.Inject;
+
+import javafx.event.ActionEvent;
+import javafx.fxml.FXML;
+import javafx.scene.control.Button;
+import javafx.scene.control.ButtonType;
+import javafx.scene.control.Label;
+import javafx.scene.control.TextField;
+
+import org.jabref.gui.DialogService;
+import org.jabref.gui.util.BaseDialog;
+import org.jabref.logic.l10n.Localization;
+import org.jabref.logic.util.OS;
+import org.jabref.preferences.PreferencesService;
+
+import com.airhacks.afterburner.views.ViewLoader;
+
+public class ManualConnectDialogView extends BaseDialog {
+
+ @FXML private Label OOPathLabel;
+ @FXML private TextField ooPath;
+ @FXML private Button browseOOPath;
+ @FXML private Button browseOOExec;
+ @FXML private Button browseOOJars;
+ @FXML private TextField ooExec;
+ @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) {
+ this.dialogService = dialogService;
+
+ ViewLoader.view(this)
+ .load()
+ .setAsDialogPane(this);
+
+ setResultConverter(button -> {
+ if (button == ButtonType.OK) {
+ viewModel.save();
+ return true;
+ }
+ return null;
+ });
+
+ setTitle(Localization.lang("Set connection parameters"));
+ }
+
+ @FXML
+ private void initialize() {
+
+ viewModel = new ManualConnectDialogViewModel(preferencesService, dialogService);
+
+ ooPath.textProperty().bindBidirectional(viewModel.ooPathProperty());
+ ooExec.textProperty().bindBidirectional(viewModel.ooExecProperty());
+ ooJars.textProperty().bind(viewModel.ooJarsProperty());
+
+ if (OS.WINDOWS || OS.OS_X) {
+ ooPath.setVisible(true);
+ ooExec.setVisible(false);
+ ooJars.setVisible(false);
+ } else {
+ ooPath.setVisible(false);
+ ooExec.setVisible(false);
+ ooJars.setVisible(true);
+ }
+ }
+
+ @FXML
+ private void browseOOPath(ActionEvent event) {
+ viewModel.browseOOPath();
+ }
+
+ @FXML
+ private void browseOOExec(ActionEvent event) {
+ viewModel.browseOOExec();
+ }
+
+ @FXML
+ 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
new file mode 100644
index 00000000000..c628484296e
--- /dev/null
+++ b/src/main/java/org/jabref/gui/openoffice/ManualConnectDialogViewModel.java
@@ -0,0 +1,79 @@
+package org.jabref.gui.openoffice;
+
+import javafx.beans.property.SimpleStringProperty;
+import javafx.beans.property.StringProperty;
+
+import org.jabref.gui.DialogService;
+import org.jabref.gui.desktop.JabRefDesktop;
+import org.jabref.gui.desktop.os.NativeDesktop;
+import org.jabref.gui.util.DirectoryDialogConfiguration;
+import org.jabref.gui.util.FileDialogConfiguration;
+import org.jabref.logic.openoffice.OpenOfficePreferences;
+import org.jabref.logic.util.OS;
+import org.jabref.preferences.PreferencesService;
+
+public class ManualConnectDialogViewModel {
+
+ private final StringProperty ooPath = new SimpleStringProperty("");
+ private final StringProperty ooExec = new SimpleStringProperty("");
+ private final StringProperty ooJars = new SimpleStringProperty("");
+ private final DialogService dialogService;
+ private final NativeDesktop nativeDesktop = JabRefDesktop.getNativeDesktop();
+ private final FileDialogConfiguration fileDialogConfiguration;
+ private final DirectoryDialogConfiguration dirDialogConfiguration;
+ private final OpenOfficePreferences ooPreferences;
+ private final PreferencesService preferencesService;
+
+ public ManualConnectDialogViewModel(PreferencesService preferencesService, DialogService dialogService) {
+ this.dialogService = dialogService;
+ this.preferencesService = preferencesService;
+
+ ooPreferences = preferencesService.getOpenOfficePreferences();
+ ooPathProperty().setValue(ooPreferences.getInstallationPath());
+ ooExecProperty().setValue(ooPreferences.getExecutablePath());
+ ooJarsProperty().setValue(ooPreferences.getJarsPath());
+
+ dirDialogConfiguration = new DirectoryDialogConfiguration.Builder()
+ .withInitialDirectory(nativeDesktop.getApplicationDirectory())
+ .build();
+ fileDialogConfiguration = new FileDialogConfiguration.Builder()
+ .withInitialDirectory(nativeDesktop.getApplicationDirectory())
+ .build();
+ }
+
+ public void browseOOPath() {
+ dialogService.showDirectorySelectionDialog(dirDialogConfiguration).ifPresent(path -> ooPath.setValue(path.toAbsolutePath().toString()));
+ }
+
+ public void browseOOExec() {
+ dialogService.showFileOpenDialog(fileDialogConfiguration).ifPresent(f -> ooExec.setValue(f.toAbsolutePath().toString()));
+
+ }
+
+ public void browseOOJars() {
+ dialogService.showDirectorySelectionDialog(dirDialogConfiguration).ifPresent(path -> ooJars.setValue(path.toAbsolutePath().toString()));
+ }
+
+ public StringProperty ooPathProperty() {
+ return ooPath;
+ }
+
+ public StringProperty ooExecProperty() {
+ return ooExec;
+ }
+
+ public StringProperty ooJarsProperty() {
+ return ooJars;
+ }
+
+ public void save() {
+ if (OS.WINDOWS || OS.OS_X) {
+ ooPreferences.updateConnectionParams(ooPath.getValue(), ooPath.getValue(), ooPath.getValue());
+ } else {
+ ooPreferences.updateConnectionParams(ooPath.getValue(), ooExec.getValue(), ooJars.getValue());
+ }
+
+ 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 b9b9ff4f704..560eaf1fe87 100644
--- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java
+++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java
@@ -135,10 +135,9 @@ 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);
@@ -165,7 +164,7 @@ public Optional getCurrentDocumentTitle() {
} 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();
@@ -174,7 +173,7 @@ public Optional getCurrentDocumentTitle() {
}
public void selectDocument() throws UnknownPropertyException, WrappedTargetException, IndexOutOfBoundsException,
- NoSuchElementException, NoDocumentException {
+ NoSuchElementException, NoDocumentException {
List textDocumentList = getTextDocuments();
XTextDocument selected;
if (textDocumentList.isEmpty()) {
@@ -213,8 +212,8 @@ public void selectDocument() throws UnknownPropertyException, WrappedTargetExcep
}
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) {
@@ -231,7 +230,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:
@@ -272,13 +271,13 @@ private List getTextDocuments() throws NoSuchElementException, Wr
}
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));
+ new Any(Type.STRING, value));
}
}
@@ -318,11 +317,12 @@ public void updateSortedReferenceMarks() throws WrappedTargetException, NoSuchEl
* @throws UndefinedParagraphFormatException
*/
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 {
+ 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 {
try {
@@ -337,10 +337,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 +355,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 +370,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();
@@ -413,9 +413,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) {
@@ -441,9 +441,9 @@ public List getJabRefReferenceMarks(XNameAccess nameAccess) {
}
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 +550,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 +559,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 +585,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 +689,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 +715,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 +745,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();
@@ -781,8 +781,8 @@ private List getSortedReferenceMarks(final XNameAccess nameAccess)
}
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 +795,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;
@@ -821,7 +821,7 @@ private String getUniqueReferenceMarkName(String bibtexKey, int type) {
}
private Map findCitedEntries(List databases, List keys,
- Map linkSourceBase) {
+ Map linkSourceBase) {
Map entries = new LinkedHashMap<>();
for (String key : keys) {
boolean found = false;
@@ -862,7 +862,7 @@ private List findCitedKeys() throws NoSuchElementException, WrappedTarge
}
private Map getSortedEntriesFromSortedRefMarks(List names,
- Map linkSourceBase) {
+ Map linkSourceBase) {
Map newList = new LinkedHashMap<>();
for (String name : names) {
@@ -940,7 +940,8 @@ private List findCitedEntryIndex(String citRefName, List keys)
}
public String getCitationContext(XNameAccess nameAccess, String refMarkName, int charBefore, int charAfter,
- boolean htmlMarkup) throws NoSuchElementException, WrappedTargetException {
+ boolean htmlMarkup)
+ throws NoSuchElementException, WrappedTargetException {
Object referenceMark = nameAccess.getByName(refMarkName);
XTextContent bookmark = UnoRuntime.queryInterface(XTextContent.class, referenceMark);
@@ -982,8 +983,9 @@ 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 {
+ String parFormat)
+ 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()) {
@@ -1004,18 +1006,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");
@@ -1090,8 +1092,9 @@ 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 {
+ OOBibStyle style)
+ 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:
@@ -1124,7 +1127,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);
}
}
@@ -1152,7 +1155,7 @@ 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 {
+ throws UnknownPropertyException, PropertyVetoException, IllegalArgumentException, WrappedTargetException {
XTextRange range = position.getStart();
XTextCursor cursor = position.getText().createTextCursorByRange(range);
cursor.goRight((short) start, false);
@@ -1201,9 +1204,9 @@ private XNameAccess getBookmarks() {
}
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);
@@ -1214,9 +1217,9 @@ public void combineCiteMarkers(List databases, OOBibStyle style)
boolean madeModifications = false;
while (piv < (names.size() - 1)) {
XTextRange range1 = UnoRuntime.queryInterface(XTextContent.class, nameAccess.getByName(names.get(piv)))
- .getAnchor().getEnd();
+ .getAnchor().getEnd();
XTextRange range2 = UnoRuntime.queryInterface(XTextContent.class, nameAccess.getByName(names.get(piv + 1)))
- .getAnchor().getStart();
+ .getAnchor().getStart();
if (range1.getText() != range2.getText()) {
piv++;
continue;
@@ -1240,7 +1243,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);
@@ -1263,7 +1266,7 @@ public void combineCiteMarkers(List databases, OOBibStyle style)
}
Collections.sort(entries, new FieldComparator(FieldName.YEAR));
String keyString = String.join(",", entries.stream().map(entry -> entry.getCiteKeyOptional().orElse(""))
- .collect(Collectors.toList()));
+ .collect(Collectors.toList()));
// Insert bookmark:
String bName = getUniqueReferenceMarkName(keyString, OOBibBase.AUTHORYEAR_PAR);
insertReferenceMark(bName, "tmp", mxDocCursor, true, style);
@@ -1280,7 +1283,7 @@ public void combineCiteMarkers(List databases, OOBibStyle style)
}
public static XTextDocument selectComponent(List list)
- throws UnknownPropertyException, WrappedTargetException, IndexOutOfBoundsException {
+ throws UnknownPropertyException, WrappedTargetException, IndexOutOfBoundsException {
String[] values = new String[list.size()];
int ii = 0;
for (XTextDocument doc : list) {
@@ -1291,7 +1294,7 @@ public static XTextDocument selectComponent(List list)
sel.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
sel.setSelectedIndex(0);
int ans = JOptionPane.showConfirmDialog(null, new JScrollPane(sel), Localization.lang("Select document"),
- JOptionPane.OK_CANCEL_OPTION);
+ JOptionPane.OK_CANCEL_OPTION);
if (ans == JOptionPane.OK_OPTION) {
return list.get(sel.getSelectedIndex());
} else {
@@ -1304,7 +1307,6 @@ private static class ComparableMark implements Comparable {
private final String name;
private final Point position;
-
public ComparableMark(String name, Point position) {
this.name = name;
this.position = position;
@@ -1328,7 +1330,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;
}
@@ -1345,7 +1347,7 @@ public int hashCode() {
}
public BibDatabase generateDatabase(List databases)
- throws NoSuchElementException, WrappedTargetException {
+ throws NoSuchElementException, WrappedTargetException {
BibDatabase resultDatabase = new BibDatabase();
List cited = findCitedKeys();
diff --git a/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java b/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java
index f829a652172..21b12f02321 100644
--- a/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java
+++ b/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java
@@ -1,8 +1,5 @@
package org.jabref.gui.openoffice;
-import java.awt.BorderLayout;
-import java.awt.Dimension;
-import java.awt.event.ActionEvent;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
@@ -16,35 +13,34 @@
import java.util.Optional;
import java.util.stream.Collectors;
-import javax.swing.AbstractAction;
-import javax.swing.Action;
-import javax.swing.ButtonGroup;
-import javax.swing.Icon;
-import javax.swing.JButton;
-import javax.swing.JCheckBoxMenuItem;
-import javax.swing.JDialog;
-import javax.swing.JFrame;
-import javax.swing.JMenuItem;
-import javax.swing.JPanel;
-import javax.swing.JPopupMenu;
-import javax.swing.JRadioButtonMenuItem;
-import javax.swing.JTextField;
-import javax.swing.SwingUtilities;
+import javafx.concurrent.Task;
+import javafx.geometry.Side;
+import javafx.scene.Node;
+import javafx.scene.control.Button;
+import javafx.scene.control.CheckMenuItem;
+import javafx.scene.control.ContextMenu;
+import javafx.scene.control.MenuItem;
+import javafx.scene.control.ProgressBar;
+import javafx.scene.control.RadioMenuItem;
+import javafx.scene.control.SeparatorMenuItem;
+import javafx.scene.control.ToggleGroup;
+import javafx.scene.control.Tooltip;
+import javafx.scene.layout.HBox;
+import javafx.scene.layout.Priority;
+import javafx.scene.layout.VBox;
import org.jabref.Globals;
import org.jabref.gui.BasePanel;
import org.jabref.gui.DialogService;
import org.jabref.gui.JabRefFrame;
-import org.jabref.gui.desktop.JabRefDesktop;
-import org.jabref.gui.desktop.os.NativeDesktop;
+import org.jabref.gui.actions.ActionFactory;
+import org.jabref.gui.actions.StandardActions;
import org.jabref.gui.help.HelpAction;
import org.jabref.gui.icon.IconTheme;
+import org.jabref.gui.keyboard.KeyBindingRepository;
import org.jabref.gui.undo.NamedCompound;
import org.jabref.gui.undo.UndoableKeyChange;
-import org.jabref.gui.util.BackgroundTask;
-import org.jabref.gui.util.DefaultTaskExecutor;
-import org.jabref.gui.util.DirectoryDialogConfiguration;
-import org.jabref.gui.util.FileDialogConfiguration;
+import org.jabref.gui.util.TaskExecutor;
import org.jabref.logic.bibtexkeypattern.BibtexKeyGenerator;
import org.jabref.logic.bibtexkeypattern.BibtexKeyPatternPreferences;
import org.jabref.logic.help.HelpFile;
@@ -53,16 +49,13 @@
import org.jabref.logic.openoffice.OpenOfficePreferences;
import org.jabref.logic.openoffice.StyleLoader;
import org.jabref.logic.openoffice.UndefinedParagraphFormatException;
-import org.jabref.logic.util.OS;
import org.jabref.logic.util.io.FileUtil;
import org.jabref.model.Defaults;
import org.jabref.model.database.BibDatabase;
import org.jabref.model.database.BibDatabaseContext;
import org.jabref.model.entry.BibEntry;
+import org.jabref.preferences.JabRefPreferences;
-import com.jgoodies.forms.builder.ButtonBarBuilder;
-import com.jgoodies.forms.builder.FormBuilder;
-import com.jgoodies.forms.layout.FormLayout;
import com.sun.star.beans.IllegalTypeException;
import com.sun.star.beans.NotRemoveableException;
import com.sun.star.beans.PropertyExistException;
@@ -82,227 +75,211 @@ public class OpenOfficePanel {
private static final Logger LOGGER = LoggerFactory.getLogger(OpenOfficePanel.class);
private final DialogService dialogService;
- private JPanel content;
-
- private JDialog diag;
- private final JButton connect;
- private final JButton manualConnect;
- private final JButton selectDocument;
- private final JButton setStyleFile = new JButton(Localization.lang("Select style"));
- private final JButton pushEntries = new JButton(Localization.lang("Cite"));
- private final JButton pushEntriesInt = new JButton(Localization.lang("Cite in-text"));
- private final JButton pushEntriesEmpty = new JButton(Localization.lang("Insert empty citation"));
- private final JButton pushEntriesAdvanced = new JButton(Localization.lang("Cite special"));
- private final JButton update;
- private final JButton merge = new JButton(Localization.lang("Merge citations"));
- private final JButton manageCitations = new JButton(Localization.lang("Manage citations"));
- private final JButton exportCitations = new JButton(Localization.lang("Export cited"));
- private final JButton settingsB = new JButton(Localization.lang("Settings"));
- private final JButton help = new HelpAction(Localization.lang("OpenOffice/LibreOffice integration"),
- HelpFile.OPENOFFICE_LIBREOFFICE).getHelpButton();
+ private final Button connect;
+ private final Button manualConnect;
+ private final Button selectDocument;
+ private final Button setStyleFile = new Button(Localization.lang("Select style"));
+ private final Button pushEntries = new Button(Localization.lang("Cite"));
+ private final Button pushEntriesInt = new Button(Localization.lang("Cite in-text"));
+ private final Button pushEntriesEmpty = new Button(Localization.lang("Insert empty citation"));
+ private final Button pushEntriesAdvanced = new Button(Localization.lang("Cite special"));
+ private final Button update;
+ private final Button merge = new Button(Localization.lang("Merge citations"));
+ private final Button manageCitations = new Button(Localization.lang("Manage citations"));
+ private final Button exportCitations = new Button(Localization.lang("Export cited"));
+ private final Button settingsB = new Button(Localization.lang("Settings"));
+ private final Button help;
+ private final VBox vbox = new VBox();
+
private OOBibBase ooBase;
private final JabRefFrame frame;
private OOBibStyle style;
- private StyleSelectDialog styleDialog;
- private boolean dialogOkPressed;
- private final OpenOfficePreferences preferences;
+ private OpenOfficePreferences ooPrefs;
+ private final JabRefPreferences jabRefPreferences;
private final StyleLoader loader;
+ private final TaskExecutor taskExecutor;
+
+ public OpenOfficePanel(JabRefFrame frame, JabRefPreferences jabRefPreferences, OpenOfficePreferences ooPrefs, KeyBindingRepository keyBindingRepository) {
+ ActionFactory factory = new ActionFactory(keyBindingRepository);
+ this.frame = frame;
+ this.ooPrefs = ooPrefs;
+ this.jabRefPreferences = jabRefPreferences;
+ this.taskExecutor = Globals.TASK_EXECUTOR;
+ dialogService = frame.getDialogService();
+
+ connect = new Button();
+ connect.setGraphic(IconTheme.JabRefIcons.CONNECT_OPEN_OFFICE.getGraphicNode());
+ connect.setTooltip(new Tooltip(Localization.lang("Connect")));
+ connect.setMaxWidth(Double.MAX_VALUE);
+
+ manualConnect = new Button();
+ manualConnect.setGraphic(IconTheme.JabRefIcons.CONNECT_OPEN_OFFICE.getGraphicNode());
+ manualConnect.setTooltip(new Tooltip(Localization.lang("Manual connect")));
+ manualConnect.setMaxWidth(Double.MAX_VALUE);
+
+ HelpAction helpCommand = new HelpAction(HelpFile.OPENOFFICE_LIBREOFFICE);
+
+ help = factory.createIconButton(StandardActions.HELP, helpCommand.getCommand());
+ help.setMaxWidth(Double.MAX_VALUE);
+
+ selectDocument = new Button();
+ selectDocument.setGraphic(IconTheme.JabRefIcons.OPEN.getGraphicNode());
+ selectDocument.setTooltip(new Tooltip(Localization.lang("Select Writer document")));
+ selectDocument.setMaxWidth(Double.MAX_VALUE);
+
+ update = new Button();
+ update.setGraphic(IconTheme.JabRefIcons.REFRESH.getGraphicNode());
+ update.setTooltip(new Tooltip(Localization.lang("Sync OpenOffice/LibreOffice bibliography")));
+ update.setMaxWidth(Double.MAX_VALUE);
+
+ loader = new StyleLoader(ooPrefs,
+ Globals.prefs.getLayoutFormatterPreferences(Globals.journalAbbreviationLoader),
+ Globals.prefs.getDefaultEncoding());
- public OpenOfficePanel(JabRefFrame jabRefFrame) {
- Icon connectImage = IconTheme.JabRefIcons.CONNECT_OPEN_OFFICE.getSmallIcon();
-
- connect = new JButton(connectImage);
- manualConnect = new JButton(connectImage);
- connect.setToolTipText(Localization.lang("Connect"));
- manualConnect.setToolTipText(Localization.lang("Manual connect"));
- connect.setPreferredSize(new Dimension(24, 24));
- manualConnect.setPreferredSize(new Dimension(24, 24));
-
- selectDocument = new JButton(IconTheme.JabRefIcons.OPEN.getSmallIcon());
- selectDocument.setToolTipText(Localization.lang("Select Writer document"));
- selectDocument.setPreferredSize(new Dimension(24, 24));
- update = new JButton(IconTheme.JabRefIcons.REFRESH.getSmallIcon());
- update.setToolTipText(Localization.lang("Sync OpenOffice/LibreOffice bibliography"));
- update.setPreferredSize(new Dimension(24, 24));
- preferences = Globals.prefs.getOpenOfficePreferences();
- loader = new StyleLoader(preferences,
- Globals.prefs.getLayoutFormatterPreferences(Globals.journalAbbreviationLoader),
- Globals.prefs.getDefaultEncoding());
-
- this.frame = jabRefFrame;
initPanel();
- dialogService = frame.getDialogService();
}
- public JPanel getContent() {
- return content;
+ public Node getContent() {
+ return vbox;
}
private void initPanel() {
- connect.addActionListener(e -> connectAutomatically());
- manualConnect.addActionListener(e -> connectManually());
+ connect.setOnAction(e -> connectAutomatically());
+ manualConnect.setOnAction(e -> connectManually());
- selectDocument.setToolTipText(Localization.lang("Select which open Writer document to work on"));
- selectDocument.addActionListener(e -> {
+ selectDocument.setTooltip(new Tooltip(Localization.lang("Select which open Writer document to work on")));
+ selectDocument.setOnAction(e -> {
try {
ooBase.selectDocument();
- frame.output(Localization.lang("Connected to document") + ": "
- + ooBase.getCurrentDocumentTitle().orElse(""));
+ dialogService.notify(Localization.lang("Connected to document") + ": "
+ + ooBase.getCurrentDocumentTitle().orElse(""));
} catch (UnknownPropertyException | WrappedTargetException | IndexOutOfBoundsException |
- NoSuchElementException | NoDocumentException ex) {
+ NoSuchElementException | NoDocumentException ex) {
LOGGER.warn("Problem connecting", ex);
dialogService.showErrorDialogAndWait(ex);
}
});
- setStyleFile.addActionListener(event -> {
+ setStyleFile.setMaxWidth(Double.MAX_VALUE);
+ setStyleFile.setOnAction(event -> {
- if (styleDialog == null) {
- styleDialog = new StyleSelectDialog(frame, preferences, loader);
- }
- styleDialog.setVisible(true);
- styleDialog.getStyle().ifPresent(selectedStyle -> {
+ StyleSelectDialogView styleDialog = new StyleSelectDialogView(loader);
+ styleDialog.showAndWait().ifPresent(selectedStyle -> {
style = selectedStyle;
try {
style.ensureUpToDate();
} catch (IOException e) {
LOGGER.warn("Unable to reload style file '" + style.getPath() + "'", e);
}
- frame.setStatus(Localization.lang("Current style is '%0'", style.getName()));
+ dialogService.notify(Localization.lang("Current style is '%0'", style.getName()));
});
});
- pushEntries.setToolTipText(Localization.lang("Cite selected entries between parenthesis"));
- pushEntries.addActionListener(e -> pushEntries(true, true, false));
- pushEntriesInt.setToolTipText(Localization.lang("Cite selected entries with in-text citation"));
- pushEntriesInt.addActionListener(e -> pushEntries(false, true, false));
- pushEntriesEmpty.setToolTipText(
- Localization.lang("Insert a citation without text (the entry will appear in the reference list)"));
- pushEntriesEmpty.addActionListener(e -> pushEntries(false, false, false));
- pushEntriesAdvanced.setToolTipText(Localization.lang("Cite selected entries with extra information"));
- pushEntriesAdvanced.addActionListener(e -> pushEntries(false, true, true));
-
- update.setToolTipText(Localization.lang("Ensure that the bibliography is up-to-date"));
- Action updateAction = new AbstractAction() {
-
- @Override
- public void actionPerformed(ActionEvent e) {
- try {
- if (style == null) {
- style = loader.getUsedStyle();
- } else {
- style.ensureUpToDate();
- }
+ pushEntries.setTooltip(new Tooltip(Localization.lang("Cite selected entries between parenthesis")));
+ pushEntries.setOnAction(e -> pushEntries(true, true, false));
+ pushEntries.setMaxWidth(Double.MAX_VALUE);
+ pushEntriesInt.setTooltip(new Tooltip(Localization.lang("Cite selected entries with in-text citation")));
+ pushEntriesInt.setOnAction(e -> pushEntries(false, true, false));
+ pushEntriesInt.setMaxWidth(Double.MAX_VALUE);
+ pushEntriesEmpty.setTooltip(new Tooltip(Localization.lang("Insert a citation without text (the entry will appear in the reference list)")));
+ pushEntriesEmpty.setOnAction(e -> pushEntries(false, false, false));
+ pushEntriesEmpty.setMaxWidth(Double.MAX_VALUE);
+ pushEntriesAdvanced.setTooltip(new Tooltip(Localization.lang("Cite selected entries with extra information")));
+ pushEntriesAdvanced.setOnAction(e -> pushEntries(false, true, true));
+ pushEntriesAdvanced.setMaxWidth(Double.MAX_VALUE);
+
+ update.setTooltip(new Tooltip(Localization.lang("Ensure that the bibliography is up-to-date")));
+
+ update.setOnAction(event -> {
+ try {
+ if (style == null) {
+ style = loader.getUsedStyle();
+ } else {
+ style.ensureUpToDate();
+ }
- ooBase.updateSortedReferenceMarks();
+ ooBase.updateSortedReferenceMarks();
- List databases = getBaseList();
- List unresolvedKeys = ooBase.refreshCiteMarkers(databases, style);
- 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)));
+ List databases = getBaseList();
+ List unresolvedKeys = ooBase.refreshCiteMarkers(databases, style);
+ 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)));
- }
- } catch (UndefinedCharacterFormatException ex) {
- reportUndefinedCharacterFormat(ex);
- } catch (UndefinedParagraphFormatException ex) {
- reportUndefinedParagraphFormat(ex);
- } catch (ConnectionLostException ex) {
- showConnectionLostErrorMessage();
- } 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."));
-
- } 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()));
-
- } catch (com.sun.star.lang.IllegalArgumentException | PropertyVetoException | UnknownPropertyException | WrappedTargetException | NoSuchElementException |
- CreationException ex) {
- LOGGER.warn("Could not update bibliography", ex);
}
+ } catch (UndefinedCharacterFormatException ex) {
+ reportUndefinedCharacterFormat(ex);
+ } catch (UndefinedParagraphFormatException ex) {
+ reportUndefinedParagraphFormat(ex);
+ } catch (ConnectionLostException ex) {
+ showConnectionLostErrorMessage();
+ } 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."));
+
+ } 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()));
+
+ } catch (com.sun.star.lang.IllegalArgumentException | PropertyVetoException | UnknownPropertyException | WrappedTargetException | NoSuchElementException |
+ CreationException ex) {
+ LOGGER.warn("Could not update bibliography", ex);
}
- };
- update.addActionListener(updateAction);
- merge.setToolTipText(Localization.lang("Combine pairs of citations that are separated by spaces only"));
- merge.addActionListener(e -> {
+ });
+
+ merge.setMaxWidth(Double.MAX_VALUE);
+ merge.setTooltip(new Tooltip(Localization.lang("Combine pairs of citations that are separated by spaces only")));
+ merge.setOnAction(e -> {
try {
ooBase.combineCiteMarkers(getBaseList(), style);
} 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);
}
});
- settingsB.addActionListener(e -> showSettingsPopup());
- manageCitations.addActionListener(e -> {
- try {
- CitationManager cm = new CitationManager(ooBase, dialogService);
- cm.showDialog();
- } catch (NoSuchElementException | WrappedTargetException | UnknownPropertyException ex) {
- LOGGER.warn("Problem showing citation manager", ex);
- }
+ ContextMenu settingsMenu = createSettingsPopup();
+ settingsB.setMaxWidth(Double.MAX_VALUE);
+ settingsB.setContextMenu(settingsMenu);
+ settingsB.setOnAction(e -> settingsMenu.show(settingsB, Side.BOTTOM, 0, 0));
+ manageCitations.setMaxWidth(Double.MAX_VALUE);
+ manageCitations.setOnAction(e -> {
+ ManageCitationsDialogView dlg = new ManageCitationsDialogView(ooBase);
+ dlg.showAndWait();
});
- exportCitations.addActionListener(event -> exportEntries());
-
- selectDocument.setEnabled(false);
- pushEntries.setEnabled(false);
- pushEntriesInt.setEnabled(false);
- pushEntriesEmpty.setEnabled(false);
- pushEntriesAdvanced.setEnabled(false);
- update.setEnabled(false);
- merge.setEnabled(false);
- manageCitations.setEnabled(false);
- exportCitations.setEnabled(false);
- diag = new JDialog((JFrame) null, "OpenOffice/LibreOffice panel", false);
-
- FormBuilder mainBuilder = FormBuilder.create()
- .layout(new FormLayout("fill:pref:grow", "p,p,p,p,p,p,p,p,p,p,p"));
-
- FormBuilder topRowBuilder = FormBuilder.create()
- .layout(new FormLayout(
- "fill:pref:grow, 1dlu, fill:pref:grow, 1dlu, fill:pref:grow, 1dlu, fill:pref:grow, 1dlu, fill:pref",
- "pref"));
- topRowBuilder.add(connect).xy(1, 1);
- topRowBuilder.add(manualConnect).xy(3, 1);
- topRowBuilder.add(selectDocument).xy(5, 1);
- topRowBuilder.add(update).xy(7, 1);
- topRowBuilder.add(help).xy(9, 1);
- mainBuilder.add(topRowBuilder.getPanel()).xy(1, 1);
- mainBuilder.add(setStyleFile).xy(1, 2);
- mainBuilder.add(pushEntries).xy(1, 3);
- mainBuilder.add(pushEntriesInt).xy(1, 4);
- mainBuilder.add(pushEntriesAdvanced).xy(1, 5);
- mainBuilder.add(pushEntriesEmpty).xy(1, 6);
- mainBuilder.add(merge).xy(1, 7);
- mainBuilder.add(manageCitations).xy(1, 8);
- mainBuilder.add(exportCitations).xy(1, 9);
- mainBuilder.add(settingsB).xy(1, 10);
-
- content = new JPanel();
- content.setLayout(new BorderLayout());
- content.add(mainBuilder.getPanel(), BorderLayout.CENTER);
-
- /*
- frame.getTabbedPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW)
- .put(Globals.getKeyPrefs().getKey(KeyBinding.REFRESH_OO), "Refresh OO");
- frame.getTabbedPane().getActionMap().put("Refresh OO", updateAction);
- */
-
+ exportCitations.setMaxWidth(Double.MAX_VALUE);
+ exportCitations.setOnAction(event -> exportEntries());
+
+ selectDocument.setDisable(true);
+ pushEntries.setDisable(true);
+ pushEntriesInt.setDisable(true);
+ pushEntriesEmpty.setDisable(true);
+ pushEntriesAdvanced.setDisable(true);
+ update.setDisable(true);
+ merge.setDisable(true);
+ manageCitations.setDisable(true);
+ exportCitations.setDisable(true);
+
+ HBox hbox = new HBox();
+ hbox.getChildren().addAll(connect, manualConnect, selectDocument, update, help);
+ 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);
}
private void exportEntries() {
@@ -321,25 +298,24 @@ 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)));
}
- Defaults defaults = new Defaults(Globals.prefs.getDefaultBibDatabaseMode());
-
+ Defaults defaults = new Defaults(jabRefPreferences.getDefaultBibDatabaseMode());
BibDatabaseContext databaseContext = new BibDatabaseContext(newDatabase, defaults);
this.frame.addTab(databaseContext, true);
} 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);
}
@@ -347,7 +323,7 @@ private void exportEntries() {
private List getBaseList() {
List databases = new ArrayList<>();
- if (preferences.getUseAllDatabases()) {
+ if (ooPrefs.getUseAllDatabases()) {
for (BasePanel basePanel : frame.getBasePanelList()) {
databases.add(basePanel.getDatabase());
}
@@ -359,102 +335,103 @@ private List getBaseList() {
}
private void connectAutomatically() {
- BackgroundTask
- .wrap(() -> {
- DetectOpenOfficeInstallation officeInstallation = new DetectOpenOfficeInstallation(diag, preferences, dialogService);
+ DetectOpenOfficeInstallation officeInstallation = new DetectOpenOfficeInstallation(jabRefPreferences, dialogService);
+
+ if (officeInstallation.isExecutablePathDefined()) {
+ connect();
+ } else {
- Boolean installed = officeInstallation.isInstalled().get();
- if (installed == null || !installed) {
+ Task taskConnectIfInstalled = new Task() {
+
+ @Override
+ protected Void call() throws Exception {
+ updateProgress(ProgressBar.INDETERMINATE_PROGRESS, ProgressBar.INDETERMINATE_PROGRESS);
+
+ boolean installed = officeInstallation.isInstalled();
+ if (!installed) {
throw new IllegalStateException("OpenOffice Installation could not be detected.");
}
return null; // can not use BackgroundTask.wrap(Runnable) because Runnable.run() can't throw exceptions
- })
- .onSuccess(x -> connect())
- .onFailure(ex ->
- dialogService.showErrorDialogAndWait(Localization.lang("Autodetection failed"), Localization.lang("Autodetection failed"), ex))
- .executeWith(Globals.TASK_EXECUTOR);
- }
+ }
+ };
- private void connectManually() {
- showManualConnectionDialog();
- if (!dialogOkPressed) {
- return;
+ taskConnectIfInstalled.setOnSucceeded(value -> connect());
+ taskConnectIfInstalled.setOnFailed(value -> dialogService.showErrorDialogAndWait(Localization.lang("Autodetection failed"), Localization.lang("Autodetection failed"), taskConnectIfInstalled.getException()));
+
+ dialogService.showProgressDialogAndWait(Localization.lang("Autodetecting paths..."), Localization.lang("Autodetecting paths..."), taskConnectIfInstalled);
+ taskExecutor.execute(taskConnectIfInstalled);
}
+ }
- connect();
+ private void connectManually() {
+ showManualConnectionDialog().ifPresent(ok -> connect());
}
private void connect() {
- JDialog progressDialog = null;
+ ooPrefs = jabRefPreferences.getOpenOfficePreferences();
- try {
- // Add OO JARs to the classpath
- loadOpenOfficeJars(Paths.get(preferences.getInstallationPath()));
-
- // Show progress dialog:
- progressDialog = new DetectOpenOfficeInstallation(diag, preferences, dialogService)
- .showProgressDialog(diag, Localization.lang("Connecting"), Localization.lang("Please wait..."));
- JDialog finalProgressDialog = progressDialog;
- BackgroundTask
- .wrap(this::createBibBase)
- .onFinished(() -> SwingUtilities.invokeLater(() -> {
- finalProgressDialog.dispose();
- diag.dispose();
- }))
- .onSuccess(ooBase -> {
- this.ooBase = ooBase;
-
- if (ooBase.isConnectedToDocument()) {
- frame.output(Localization.lang("Connected to document") + ": " + ooBase.getCurrentDocumentTitle().orElse(""));
- }
-
- // Enable actions that depend on Connect:
- selectDocument.setEnabled(true);
- pushEntries.setEnabled(true);
- pushEntriesInt.setEnabled(true);
- pushEntriesEmpty.setEnabled(true);
- pushEntriesAdvanced.setEnabled(true);
- update.setEnabled(true);
- merge.setEnabled(true);
- manageCitations.setEnabled(true);
- exportCitations.setEnabled(true);
-
- })
- .onFailure(ex ->
- dialogService.showErrorDialogAndWait(Localization.lang("Autodetection failed"), Localization.lang("Autodetection failed"), ex))
- .executeWith(Globals.TASK_EXECUTOR);
- diag.dispose();
-
- } catch (UnsatisfiedLinkError e) {
- LOGGER.warn("Could not connect to running OpenOffice/LibreOffice", e);
-
- DefaultTaskExecutor.runInJavaFXThread(() ->
- 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.")));
-
- } catch (IOException e) {
- LOGGER.warn("Could not connect to running OpenOffice/LibreOffice", e);
-
- DefaultTaskExecutor.runInJavaFXThread(() ->
- 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:"),
- e));
-
- } finally {
- if (progressDialog != null) {
- progressDialog.dispose();
+ Task connectTask = new Task() {
+
+ @Override
+ protected OOBibBase call() throws Exception {
+ updateProgress(ProgressBar.INDETERMINATE_PROGRESS, ProgressBar.INDETERMINATE_PROGRESS);
+ loadOpenOfficeJars(Paths.get(ooPrefs.getInstallationPath()));
+
+ return createBibBase();
}
- }
+ };
+
+ connectTask.setOnSucceeded(value -> {
+ ooBase = connectTask.getValue();
+
+ if (ooBase.isConnectedToDocument()) {
+ dialogService.notify(Localization.lang("Connected to document") + ": " + ooBase.getCurrentDocumentTitle().orElse(""));
+ }
+
+ // Enable actions that depend on Connect:
+ selectDocument.setDisable(false);
+ pushEntries.setDisable(false);
+ pushEntriesInt.setDisable(false);
+ pushEntriesEmpty.setDisable(false);
+ pushEntriesAdvanced.setDisable(false);
+ update.setDisable(false);
+ merge.setDisable(false);
+ manageCitations.setDisable(false);
+ exportCitations.setDisable(false);
+
+ });
+ connectTask.setOnFailed(value -> {
+ Throwable ex = connectTask.getException();
+ if (ex instanceof UnsatisfiedLinkError) {
+ 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."));
+
+ } 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);
+ } else {
+ dialogService.showErrorDialogAndWait(Localization.lang("Autodetection failed"), Localization.lang("Autodetection failed"), ex);
+ }
+ });
+
+ dialogService.showProgressDialogAndWait(Localization.lang("Autodetecting paths..."), Localization.lang("Autodetecting paths..."), connectTask);
+ taskExecutor.execute(connectTask);
+
}
private void loadOpenOfficeJars(Path configurationPath) throws IOException {
List> filePaths = OpenOfficePreferences.OO_JARS.stream().map(jar -> FileUtil.find(jar, configurationPath)).collect(Collectors.toList());
if (!filePaths.stream().allMatch(Optional::isPresent)) {
- throw new IOException("(Not all) required Open Office Jars were found inside installation path.");
+ throw new IOException("(Not all) required Open Office Jars were found inside installation path. Searched for " + OpenOfficePreferences.OO_JARS + " in " + configurationPath);
}
List jarURLs = new ArrayList<>(OpenOfficePreferences.OO_JARS.size());
@@ -465,10 +442,10 @@ 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(preferences.getExecutablePath(), true);
+ return new OOBibBase(ooPrefs.getExecutablePath(), true);
}
private static void addURL(List jarList) throws IOException {
@@ -481,119 +458,39 @@ private static void addURL(List jarList) throws IOException {
method.invoke(sysloader, anU);
}
} catch (SecurityException | NoSuchMethodException | IllegalAccessException | IllegalArgumentException |
- InvocationTargetException e) {
+ 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 void showManualConnectionDialog() {
- dialogOkPressed = false;
- final JDialog cDiag = new JDialog((JFrame) null, Localization.lang("Set connection parameters"), true);
- final NativeDesktop nativeDesktop = JabRefDesktop.getNativeDesktop();
-
- final DialogService dialogService = this.dialogService;
- DirectoryDialogConfiguration dirDialogConfiguration = new DirectoryDialogConfiguration.Builder()
- .withInitialDirectory(nativeDesktop.getApplicationDirectory())
- .build();
-
- FileDialogConfiguration fileDialogConfiguration = new FileDialogConfiguration.Builder()
- .withInitialDirectory(nativeDesktop.getApplicationDirectory())
- .build();
-
- // Path fields
- final JTextField ooPath = new JTextField(30);
- JButton browseOOPath = new JButton(Localization.lang("Browse"));
- ooPath.setText(preferences.getInstallationPath());
- browseOOPath.addActionListener(e -> DefaultTaskExecutor.runInJavaFXThread(() -> dialogService.showDirectorySelectionDialog(dirDialogConfiguration))
- .ifPresent(f -> ooPath.setText(f.toAbsolutePath().toString())));
-
- final JTextField ooExec = new JTextField(30);
- JButton browseOOExec = new JButton(Localization.lang("Browse"));
- ooExec.setText(preferences.getExecutablePath());
- browseOOExec.addActionListener(e -> DefaultTaskExecutor.runInJavaFXThread(() -> dialogService.showFileOpenDialog(fileDialogConfiguration))
- .ifPresent(f -> ooExec.setText(f.toAbsolutePath().toString())));
-
- final JTextField ooJars = new JTextField(30);
- ooJars.setText(preferences.getJarsPath());
- JButton browseOOJars = new JButton(Localization.lang("Browse"));
- browseOOJars.addActionListener(e -> DefaultTaskExecutor.runInJavaFXThread(() -> dialogService.showDirectorySelectionDialog(dirDialogConfiguration))
- .ifPresent(f -> ooJars.setText(f.toAbsolutePath().toString())));
-
- FormBuilder builder = FormBuilder.create()
- .layout(new FormLayout("left:pref, 4dlu, fill:pref:grow, 4dlu, fill:pref", "pref"));
-
- if (OS.WINDOWS || OS.OS_X) {
- builder.add(Localization.lang("Path to OpenOffice/LibreOffice directory")).xy(1, 1);
- builder.add(ooPath).xy(3, 1);
- builder.add(browseOOPath).xy(5, 1);
- } else {
- builder.add(Localization.lang("Path to OpenOffice/LibreOffice executable")).xy(1, 1);
- builder.add(ooExec).xy(3, 1);
- builder.add(browseOOExec).xy(5, 1);
-
- builder.appendRows("4dlu, pref");
- builder.add(Localization.lang("Path to OpenOffice/LibreOffice library dir")).xy(1, 3);
- builder.add(ooJars).xy(3, 3);
- builder.add(browseOOJars).xy(5, 3);
- }
- builder.padding("5dlu, 5dlu, 5dlu, 5dlu");
-
- cDiag.getContentPane().add(builder.getPanel(), BorderLayout.CENTER);
-
- // Buttons
- JButton ok = new JButton(Localization.lang("OK"));
- JButton cancel = new JButton(Localization.lang("Cancel"));
-
- ok.addActionListener(e -> {
- if (OS.WINDOWS || OS.OS_X) {
- preferences.updateConnectionParams(ooPath.getText(), ooPath.getText(), ooPath.getText());
- } else {
- preferences.updateConnectionParams(ooPath.getText(), ooExec.getText(), ooJars.getText());
- }
- dialogOkPressed = true;
- cDiag.dispose();
- });
- cancel.addActionListener(e -> cDiag.dispose());
-
- ButtonBarBuilder bb = new ButtonBarBuilder();
- bb.addGlue();
- bb.addRelatedGap();
- bb.addButton(ok);
- bb.addButton(cancel);
- bb.addGlue();
- bb.padding("5dlu, 5dlu, 5dlu, 5dlu");
- cDiag.getContentPane().add(bb.getPanel(), BorderLayout.SOUTH);
-
- // Finish and show dirDialog
- cDiag.pack();
- cDiag.setVisible(true);
+ private Optional showManualConnectionDialog() {
+ return new ManualConnectDialogView(dialogService).showAndWait();
}
private void pushEntries(boolean inParenthesisIn, boolean withText, boolean addPageInfo) {
if (!ooBase.isConnectedToDocument()) {
-
- DefaultTaskExecutor.runInJavaFXThread(() -> dialogService.showErrorDialogAndWait(
- Localization.lang("Error pushing entries"), Localization.lang("Not connected to any Writer document. Please"
- + " make sure a document is open, and use the 'Select Writer document' button to connect to it.")));
-
+ dialogService.showErrorDialogAndWait(Localization.lang("Error pushing entries"), Localization.lang("Not connected to any Writer document. Please" + " make sure a document is open, and use the 'Select Writer document' button to connect to it."));
return;
}
Boolean inParenthesis = inParenthesisIn;
String pageInfo = null;
if (addPageInfo) {
- AdvancedCiteDialog citeDialog = new AdvancedCiteDialog(frame);
- citeDialog.showDialog();
- if (citeDialog.canceled()) {
- return;
- }
- if (!citeDialog.getPageInfo().isEmpty()) {
- pageInfo = citeDialog.getPageInfo();
- }
- inParenthesis = citeDialog.isInParenthesisCite();
+ AdvancedCiteDialogView citeDialog = new AdvancedCiteDialogView();
+ Optional citeDialogViewModel = citeDialog.showAndWait();
+
+ if (citeDialogViewModel.isPresent()) {
+
+ AdvancedCiteDialogViewModel model = citeDialogViewModel.get();
+ if (!model.pageInfoProperty().getValue().isEmpty()) {
+ pageInfo = model.pageInfoProperty().getValue();
+ }
+ inParenthesis = model.citeInParProperty().getValue();
+ }
}
BasePanel panel = frame.getCurrentBasePanel();
@@ -607,12 +504,12 @@ private void pushEntries(boolean inParenthesisIn, boolean withText, boolean addP
style = loader.getUsedStyle();
}
ooBase.insertEntry(entries, database, getBaseList(), style, inParenthesis, withText, pageInfo,
- preferences.getSyncWhenCiting());
+ ooPrefs.getSyncWhenCiting());
} catch (FileNotFoundException ex) {
- DefaultTaskExecutor.runInJavaFXThread(() -> 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.")));
+ 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."));
LOGGER.warn("Problem with style file", ex);
} catch (ConnectionLostException ex) {
@@ -622,9 +519,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);
}
}
@@ -657,21 +554,21 @@ 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)) {
// Generate keys
- BibtexKeyPatternPreferences prefs = Globals.prefs.getBibtexKeyPatternPreferences();
+ BibtexKeyPatternPreferences prefs = jabRefPreferences.getBibtexKeyPatternPreferences();
NamedCompound undoCompound = new NamedCompound(Localization.lang("Cite"));
for (BibEntry entry : 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();
@@ -686,77 +583,70 @@ private boolean checkThatEntriesHaveKeys(List entries) {
}
private void showConnectionLostErrorMessage() {
- DefaultTaskExecutor.runInJavaFXThread(() -> 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.")));
+ 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."));
}
private void reportUndefinedParagraphFormat(UndefinedParagraphFormatException ex) {
- DefaultTaskExecutor.runInJavaFXThread(() -> 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.")));
+ 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."));
}
private void reportUndefinedCharacterFormat(UndefinedCharacterFormatException ex) {
- DefaultTaskExecutor.runInJavaFXThread(() -> 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.")
-
- ));
+ 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.")
+
+ );
}
- private void showSettingsPopup() {
- JPopupMenu menu = new JPopupMenu();
- final JCheckBoxMenuItem autoSync = new JCheckBoxMenuItem(
- Localization.lang("Automatically sync bibliography when inserting citations"),
- preferences.getSyncWhenCiting());
- final JRadioButtonMenuItem useActiveBase = new JRadioButtonMenuItem(
- Localization.lang("Look up BibTeX entries in the active tab only"));
- final JRadioButtonMenuItem useAllBases = new JRadioButtonMenuItem(
- Localization.lang("Look up BibTeX entries in all open libraries"));
- final JMenuItem clearConnectionSettings = new JMenuItem(Localization.lang("Clear connection settings"));
-
- ButtonGroup lookupButtonGroup = new ButtonGroup();
- lookupButtonGroup.add(useActiveBase);
- lookupButtonGroup.add(useAllBases);
- if (preferences.getUseAllDatabases()) {
+ private ContextMenu createSettingsPopup() {
+
+ ContextMenu contextMenu = new ContextMenu();
+
+ CheckMenuItem autoSync = new CheckMenuItem(Localization.lang("Automatically sync bibliography when inserting citations"));
+ autoSync.selectedProperty().set(ooPrefs.getSyncWhenCiting());
+
+ ToggleGroup toggleGroup = new ToggleGroup();
+ RadioMenuItem useActiveBase = new RadioMenuItem(Localization.lang("Look up BibTeX entries in the active tab only"));
+ RadioMenuItem useAllBases = new RadioMenuItem(Localization.lang("Look up BibTeX entries in all open libraries"));
+ useActiveBase.setToggleGroup(toggleGroup);
+ useAllBases.setToggleGroup(toggleGroup);
+
+ MenuItem clearConnectionSettings = new MenuItem(Localization.lang("Clear connection settings"));
+
+ if (ooPrefs.getUseAllDatabases()) {
useAllBases.setSelected(true);
} else {
useActiveBase.setSelected(true);
}
- autoSync.addActionListener(e -> {
- preferences.setSyncWhenCiting(autoSync.isSelected());
- Globals.prefs.setOpenOfficePreferences(preferences);
+ autoSync.setOnAction(e -> {
+ ooPrefs.setSyncWhenCiting(autoSync.isSelected());
+ jabRefPreferences.setOpenOfficePreferences(ooPrefs);
});
- useAllBases.addActionListener(e -> {
- preferences.setUseAllDatabases(useAllBases.isSelected());
- Globals.prefs.setOpenOfficePreferences(preferences);
+ useAllBases.setOnAction(e -> {
+ ooPrefs.setUseAllDatabases(useAllBases.isSelected());
+ jabRefPreferences.setOpenOfficePreferences(ooPrefs);
});
- useActiveBase.addActionListener(e -> {
- preferences.setUseAllDatabases(!useActiveBase.isSelected());
- Globals.prefs.setOpenOfficePreferences(preferences);
+ useActiveBase.setOnAction(e -> {
+ ooPrefs.setUseAllDatabases(!useActiveBase.isSelected());
+ jabRefPreferences.setOpenOfficePreferences(ooPrefs);
});
- clearConnectionSettings.addActionListener(e -> {
- preferences.clearConnectionSettings();
- Globals.prefs.setOpenOfficePreferences(preferences);
+ clearConnectionSettings.setOnAction(e -> {
+ ooPrefs.clearConnectionSettings();
+ dialogService.notify(Localization.lang("Cleared connection settings"));
+ jabRefPreferences.setOpenOfficePreferences(ooPrefs);
});
- menu.add(autoSync);
- menu.addSeparator();
- menu.add(useActiveBase);
- menu.add(useAllBases);
- menu.addSeparator();
- menu.add(clearConnectionSettings);
- menu.show(settingsB, 0, settingsB.getHeight());
+ contextMenu.getItems().addAll(autoSync, new SeparatorMenuItem(), useActiveBase, useAllBases, new SeparatorMenuItem(), clearConnectionSettings);
+
+ return contextMenu;
+
}
}
diff --git a/src/main/java/org/jabref/gui/openoffice/OpenOfficeSidePanel.java b/src/main/java/org/jabref/gui/openoffice/OpenOfficeSidePanel.java
index c5e064715ce..d725a7d84c9 100644
--- a/src/main/java/org/jabref/gui/openoffice/OpenOfficeSidePanel.java
+++ b/src/main/java/org/jabref/gui/openoffice/OpenOfficeSidePanel.java
@@ -1,8 +1,5 @@
package org.jabref.gui.openoffice;
-import javax.swing.SwingUtilities;
-
-import javafx.embed.swing.SwingNode;
import javafx.scene.Node;
import javafx.scene.layout.Priority;
@@ -14,26 +11,31 @@
import org.jabref.gui.actions.StandardActions;
import org.jabref.gui.icon.IconTheme;
import org.jabref.logic.openoffice.OpenOfficePreferences;
+import org.jabref.preferences.JabRefPreferences;
public class OpenOfficeSidePanel extends SidePaneComponent {
- private OpenOfficePreferences preferences;
- private JabRefFrame frame;
+ private final JabRefPreferences preferences;
+ private final JabRefFrame frame;
+ private final OpenOfficePreferences ooPrefs;
- public OpenOfficeSidePanel(SidePaneManager sidePaneManager, OpenOfficePreferences preferences, JabRefFrame frame) {
+ public OpenOfficeSidePanel(SidePaneManager sidePaneManager, JabRefPreferences preferences, JabRefFrame frame) {
super(sidePaneManager, IconTheme.JabRefIcons.FILE_OPENOFFICE, "OpenOffice/LibreOffice");
- this.preferences = preferences;
this.frame = frame;
+ this.preferences = preferences;
+ this.ooPrefs = preferences.getOpenOfficePreferences();
}
@Override
public void beforeClosing() {
- preferences.setShowPanel(false);
+ ooPrefs.setShowPanel(false);
+ preferences.setOpenOfficePreferences(ooPrefs);
}
@Override
public void afterOpening() {
- preferences.setShowPanel(true);
+ ooPrefs.setShowPanel(true);
+ preferences.setOpenOfficePreferences(ooPrefs);
}
@Override
@@ -48,9 +50,7 @@ public Action getToggleAction() {
@Override
protected Node createContentPane() {
- SwingNode swingNode = new SwingNode();
- SwingUtilities.invokeLater(() -> swingNode.setContent(new OpenOfficePanel(frame).getContent()));
- return swingNode;
+ return new OpenOfficePanel(frame, preferences, ooPrefs, preferences.getKeyBindingRepository()).getContent();
}
@Override
diff --git a/src/main/java/org/jabref/gui/openoffice/StyleSelectDialog.fxml b/src/main/java/org/jabref/gui/openoffice/StyleSelectDialog.fxml
new file mode 100644
index 00000000000..f994d348787
--- /dev/null
+++ b/src/main/java/org/jabref/gui/openoffice/StyleSelectDialog.fxml
@@ -0,0 +1,39 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/src/main/java/org/jabref/gui/openoffice/StyleSelectDialog.java b/src/main/java/org/jabref/gui/openoffice/StyleSelectDialog.java
deleted file mode 100644
index 62317e1c8fd..00000000000
--- a/src/main/java/org/jabref/gui/openoffice/StyleSelectDialog.java
+++ /dev/null
@@ -1,538 +0,0 @@
-package org.jabref.gui.openoffice;
-
-import java.awt.BorderLayout;
-import java.awt.Dimension;
-import java.awt.event.ActionEvent;
-import java.awt.event.ActionListener;
-import java.awt.event.MouseAdapter;
-import java.awt.event.MouseEvent;
-import java.io.IOException;
-import java.nio.file.Path;
-import java.util.Objects;
-import java.util.Optional;
-
-import javax.swing.AbstractAction;
-import javax.swing.Action;
-import javax.swing.ActionMap;
-import javax.swing.BorderFactory;
-import javax.swing.InputMap;
-import javax.swing.JButton;
-import javax.swing.JComponent;
-import javax.swing.JDialog;
-import javax.swing.JFrame;
-import javax.swing.JMenuItem;
-import javax.swing.JPopupMenu;
-import javax.swing.JScrollPane;
-import javax.swing.JTable;
-import javax.swing.JTextArea;
-import javax.swing.JTextField;
-import javax.swing.KeyStroke;
-import javax.swing.ListSelectionModel;
-import javax.swing.table.TableColumnModel;
-
-import javafx.embed.swing.JFXPanel;
-import javafx.scene.Scene;
-
-import org.jabref.Globals;
-import org.jabref.gui.DialogService;
-import org.jabref.gui.JabRefDialog;
-import org.jabref.gui.JabRefFrame;
-import org.jabref.gui.PreviewPanel;
-import org.jabref.gui.customjfx.CustomJFXPanel;
-import org.jabref.gui.desktop.JabRefDesktop;
-import org.jabref.gui.externalfiletype.ExternalFileType;
-import org.jabref.gui.externalfiletype.ExternalFileTypes;
-import org.jabref.gui.icon.IconTheme;
-import org.jabref.gui.keyboard.KeyBinding;
-import org.jabref.gui.util.DefaultTaskExecutor;
-import org.jabref.gui.util.FileDialogConfiguration;
-import org.jabref.gui.util.WindowLocation;
-import org.jabref.logic.l10n.Localization;
-import org.jabref.logic.openoffice.OOBibStyle;
-import org.jabref.logic.openoffice.OpenOfficePreferences;
-import org.jabref.logic.openoffice.StyleLoader;
-import org.jabref.logic.util.StandardFileType;
-import org.jabref.logic.util.TestEntry;
-import org.jabref.model.database.BibDatabaseContext;
-import org.jabref.model.entry.BibEntry;
-import org.jabref.preferences.JabRefPreferences;
-
-import ca.odell.glazedlists.BasicEventList;
-import ca.odell.glazedlists.EventList;
-import ca.odell.glazedlists.SortedList;
-import ca.odell.glazedlists.event.ListEvent;
-import ca.odell.glazedlists.event.ListEventListener;
-import ca.odell.glazedlists.gui.TableFormat;
-import ca.odell.glazedlists.swing.DefaultEventSelectionModel;
-import ca.odell.glazedlists.swing.DefaultEventTableModel;
-import ca.odell.glazedlists.swing.GlazedListsSwing;
-import com.jgoodies.forms.builder.ButtonBarBuilder;
-import com.jgoodies.forms.builder.FormBuilder;
-import com.jgoodies.forms.layout.FormLayout;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * This class produces a dialog box for choosing a style file.
- */
-class StyleSelectDialog {
-
- private static final Logger LOGGER = LoggerFactory.getLogger(StyleSelectDialog.class);
-
- private final JabRefFrame frame;
- private final DialogService dialogService;
- private EventList styles;
- private JDialog diag;
- private JTable table;
- private DefaultEventTableModel tableModel;
- private DefaultEventSelectionModel selectionModel;
- private final JPopupMenu popup = new JPopupMenu();
- private final JMenuItem edit = new JMenuItem(Localization.lang("Edit"));
- private final JMenuItem show = new JMenuItem(Localization.lang("View"));
- private final JMenuItem remove = new JMenuItem(Localization.lang("Remove"));
- private final JMenuItem reload = new JMenuItem(Localization.lang("Reload"));
- private final JButton addButton = new JButton(IconTheme.JabRefIcons.ADD_NOBOX.getIcon());
- private final JButton removeButton = new JButton(IconTheme.JabRefIcons.REMOVE_NOBOX.getIcon());
- private PreviewPanel preview;
- private ActionListener removeAction;
-
- private final JButton ok = new JButton(Localization.lang("OK"));
- private final JButton cancel = new JButton(Localization.lang("Cancel"));
- private final BibEntry prevEntry;
-
- private boolean okPressed;
- private final StyleLoader loader;
- private final OpenOfficePreferences preferences;
-
- public StyleSelectDialog(JabRefFrame frame, OpenOfficePreferences preferences, StyleLoader loader) {
- this.frame = Objects.requireNonNull(frame);
- this.preferences = Objects.requireNonNull(preferences);
- this.loader = Objects.requireNonNull(loader);
- prevEntry = TestEntry.getTestEntry();
- init();
- dialogService = frame.getDialogService();
- }
-
- private void init() {
- setupPopupMenu();
-
- addButton.addActionListener(actionEvent -> {
- AddFileDialog addDialog = new AddFileDialog();
- addDialog.setDirectoryPath(preferences.getCurrentStyle());
- addDialog.setVisible(true);
- addDialog.getFileName().ifPresent(fileName -> {
- if (loader.addStyleIfValid(fileName)) {
- preferences.setCurrentStyle(fileName);
- }
- });
- updateStyles();
- });
- addButton.setToolTipText(Localization.lang("Add style file"));
-
- removeButton.addActionListener(removeAction);
- removeButton.setToolTipText(Localization.lang("Remove style"));
-
- // Create a preview panel for previewing styles
- // Must be done before creating the table to avoid NPEs
- DefaultTaskExecutor.runInJavaFXThread(() -> {
- preview = new PreviewPanel(null, new BibDatabaseContext(), Globals.getKeyPrefs(), Globals.prefs.getPreviewPreferences(), dialogService, ExternalFileTypes.getInstance());
- // Use the test entry from the Preview settings tab in Preferences:
- preview.setEntry(prevEntry);
- });
-
- setupTable();
- updateStyles();
-
- // Build dialog
- diag = new JDialog((JFrame) null, Localization.lang("Select style"), true);
-
- FormBuilder builder = FormBuilder.create();
- builder.layout(new FormLayout("fill:pref:grow, 4dlu, left:pref, 4dlu, left:pref",
- "pref, 4dlu, 100dlu:grow, 4dlu, pref, 4dlu, fill:100dlu"));
- builder.add(Localization.lang("Select one of the available styles or add a style file from disk.")).xyw(1,
- 1,
- 5);
- builder.add(new JScrollPane(table)).xyw(1, 3, 5);
- builder.add(addButton).xy(3, 5);
- builder.add(removeButton).xy(5, 5);
- JFXPanel container = CustomJFXPanel.wrap(new Scene(preview));
- builder.add(container).xyw(1, 7, 5);
- builder.padding("5dlu, 5dlu, 5dlu, 5dlu");
-
- diag.add(builder.getPanel(), BorderLayout.CENTER);
-
- AbstractAction okListener = new AbstractAction() {
-
- @Override
- public void actionPerformed(ActionEvent event) {
- if ((table.getRowCount() == 0) || (table.getSelectedRowCount() == 0)) {
- dialogService.showErrorDialogAndWait(Localization.lang("Style selection"),
- Localization.lang("You must select a valid style file."));
- return;
- }
- okPressed = true;
- storeSettings();
- diag.dispose();
- }
- };
- ok.addActionListener(okListener);
-
- Action cancelListener = new AbstractAction() {
-
- @Override
- public void actionPerformed(ActionEvent event) {
- diag.dispose();
- }
- };
- cancel.addActionListener(cancelListener);
-
- ButtonBarBuilder bb = new ButtonBarBuilder();
- bb.addGlue();
- bb.addButton(ok);
- bb.addButton(cancel);
- bb.addGlue();
- bb.getPanel().setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
- diag.add(bb.getPanel(), BorderLayout.SOUTH);
-
- ActionMap am = bb.getPanel().getActionMap();
- InputMap im = bb.getPanel().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
- im.put(Globals.getKeyPrefs().getKey(KeyBinding.CLOSE), "close");
- am.put("close", cancelListener);
- im.put(KeyStroke.getKeyStroke("ENTER"), "enterOk");
- am.put("enterOk", okListener);
-
- diag.pack();
-
- WindowLocation pw = new WindowLocation(diag, JabRefPreferences.STYLES_POS_X, JabRefPreferences.STYLES_POS_Y,
- JabRefPreferences.STYLES_SIZE_X, JabRefPreferences.STYLES_SIZE_Y);
- pw.displayWindowAtStoredLocation();
- }
-
- private void setupTable() {
- styles = new BasicEventList<>();
- EventList sortedStyles = new SortedList<>(styles);
-
- tableModel = (DefaultEventTableModel) GlazedListsSwing
- .eventTableModelWithThreadProxyList(sortedStyles, new StyleTableFormat());
- table = new JTable(tableModel);
- TableColumnModel cm = table.getColumnModel();
- cm.getColumn(0).setPreferredWidth(100);
- cm.getColumn(1).setPreferredWidth(200);
- cm.getColumn(2).setPreferredWidth(80);
-
- selectionModel = (DefaultEventSelectionModel) GlazedListsSwing
- .eventSelectionModelWithThreadProxyList(sortedStyles);
- table.setSelectionModel(selectionModel);
- table.getSelectionModel().setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
- table.addMouseListener(new MouseAdapter() {
-
- @Override
- public void mousePressed(MouseEvent mouseEvent) {
- if (mouseEvent.isPopupTrigger()) {
- tablePopup(mouseEvent);
- }
- }
-
- @Override
- public void mouseReleased(MouseEvent mouseEvent) {
- if (mouseEvent.isPopupTrigger()) {
- tablePopup(mouseEvent);
- }
- }
- });
-
- selectionModel.getSelected().addListEventListener(new EntrySelectionListener());
- }
-
- private void setupPopupMenu() {
- popup.add(edit);
- popup.add(show);
- popup.add(remove);
- popup.add(reload);
-
- // Add action listener to "Edit" menu item, which is supposed to open the style file in an external editor:
- edit.addActionListener(actionEvent -> getSelectedStyle().ifPresent(style -> {
- Optional type = ExternalFileTypes.getInstance().getExternalFileTypeByExt("jstyle");
- String link = style.getPath();
- try {
-
- JabRefDesktop.openExternalFileAnyFormat(frame.getCurrentBasePanel().getBibDatabaseContext(), link, type);
-
- } catch (IOException e) {
- LOGGER.warn("Problem open style file editor", e);
- }
- }));
-
- // Add action listener to "Show" menu item, which is supposed to open the style file in a dialog:
- show.addActionListener(actionEvent -> getSelectedStyle().ifPresent(this::displayStyle));
-
- // Create action listener for removing a style, also used for the remove button
- removeAction = actionEvent -> getSelectedStyle().ifPresent(style -> {
-
- if (!style.isFromResource() && dialogService.showConfirmationDialogAndWait(Localization.lang("Remove style"),
- Localization.lang("Are you sure you want to remove the style?"),
- Localization.lang("Remove style"),
- Localization.lang("Cancel"))) {
- if (!loader.removeStyle(style)) {
- LOGGER.info("Problem removing style");
- }
- updateStyles();
- }
- });
- // Add it to the remove menu item
- remove.addActionListener(removeAction);
-
- // Add action listener to the "Reload" menu item, which is supposed to reload an external style file
- reload.addActionListener(actionEvent ->
-
- getSelectedStyle().ifPresent(style -> {
- try {
- style.ensureUpToDate();
- } catch (IOException e) {
- LOGGER.warn("Problem with style file '" + style.getPath() + "'", e);
- }
- }));
- }
-
- public void setVisible(boolean visible) {
- okPressed = false;
- diag.setVisible(visible);
- }
-
- /**
- * Read all style files or directories of style files indicated by the current
- * settings, and add the styles to the list of styles.
- */
- private void updateStyles() {
-
- table.clearSelection();
- styles.getReadWriteLock().writeLock().lock();
- styles.clear();
- styles.addAll(loader.getStyles());
- styles.getReadWriteLock().writeLock().unlock();
-
- selectLastUsed();
- }
-
- /**
- * This method scans the current list of styles, and looks for the styles
- * that was last used. If found, that style is selected. If not found,
- * the first style is selected provided there are >0 styles.
- */
- private void selectLastUsed() {
- String usedStyleFile = preferences.getCurrentStyle();
- // Set the initial selection of the table:
- if (usedStyleFile == null) {
- if (table.getRowCount() > 0) {
- table.setRowSelectionInterval(0, 0);
- }
- } else {
- boolean found = false;
- for (int i = 0; i < table.getRowCount(); i++) {
- if (usedStyleFile.equals(tableModel.getElementAt(i).getPath())) {
- table.setRowSelectionInterval(i, i);
- found = true;
- break;
- }
- }
- if (!found && (table.getRowCount() > 0)) {
- table.setRowSelectionInterval(0, 0);
- }
- }
- }
-
- private void storeSettings() {
- getSelectedStyle().ifPresent(style -> preferences.setCurrentStyle(style.getPath()));
- }
-
- public Optional getStyle() {
- if (okPressed) {
- return getSelectedStyle();
- }
- return Optional.empty();
- }
-
- /**
- * Get the currently selected style.
- *
- * @return the selected style, or empty if no style is selected.
- */
- private Optional getSelectedStyle() {
- if (!selectionModel.getSelected().isEmpty()) {
- return Optional.of(selectionModel.getSelected().get(0));
- }
- return Optional.empty();
- }
-
- static class StyleTableFormat implements TableFormat {
-
- @Override
- public int getColumnCount() {
- return 3;
- }
-
- @Override
- public String getColumnName(int i) {
- switch (i) {
- case 0:
- return Localization.lang("Name");
- case 1:
- return Localization.lang("Journals");
- case 2:
- return Localization.lang("File");
- default:
- return "";
- }
- }
-
- @Override
- public Object getColumnValue(OOBibStyle style, int i) {
- switch (i) {
- case 0:
- return style.getName();
- case 1:
- return String.join(", ", style.getJournals());
- case 2:
- return style.isFromResource() ? Localization.lang("Internal style") : style.getFile().getName();
- default:
- return "";
- }
- }
- }
-
- public boolean isOkPressed() {
- return okPressed;
- }
-
- private void tablePopup(MouseEvent e) {
- popup.show(e.getComponent(), e.getX(), e.getY());
- }
-
- private void displayStyle(OOBibStyle style) {
- // Make a dialog box to display the contents:
- final JDialog dd = new JDialog(diag, style.getName(), true);
-
- JTextArea ta = new JTextArea(style.getLocalCopy());
- ta.setEditable(false);
- JScrollPane sp = new JScrollPane(ta);
- sp.setPreferredSize(new Dimension(700, 500));
- dd.getContentPane().add(sp, BorderLayout.CENTER);
- JButton okButton = new JButton(Localization.lang("OK"));
- ButtonBarBuilder bb = new ButtonBarBuilder();
- bb.addGlue();
- bb.addButton(okButton);
- bb.addGlue();
- bb.getPanel().setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
- dd.getContentPane().add(bb.getPanel(), BorderLayout.SOUTH);
- okButton.addActionListener(actionEvent -> dd.dispose());
- dd.pack();
- dd.setLocationRelativeTo(diag);
- dd.setVisible(true);
- }
-
- /**
- * The listener for the Glazed list monitoring the current selection.
- * When selection changes, we need to update the preview panel.
- */
- private class EntrySelectionListener implements ListEventListener {
-
- @Override
- public void listChanged(ListEvent listEvent) {
- if (listEvent.getSourceList().size() == 1) {
- OOBibStyle style = listEvent.getSourceList().get(0);
-
- // Enable/disable popup menu items and buttons
- if (style.isFromResource()) {
- remove.setEnabled(false);
- edit.setEnabled(false);
- reload.setEnabled(false);
- removeButton.setEnabled(false);
- } else {
- remove.setEnabled(true);
- edit.setEnabled(true);
- reload.setEnabled(true);
- removeButton.setEnabled(true);
- }
-
- // Set new preview layout
- preview.setLayout(style.getReferenceFormat("default"));
- }
- }
- }
-
- private class AddFileDialog extends JabRefDialog {
-
- private final JTextField newFile = new JTextField();
- private boolean addOKPressed;
-
- public AddFileDialog() {
- super(diag, Localization.lang("Add style file"), true, AddFileDialog.class);
-
- JButton browse = new JButton(Localization.lang("Browse"));
- FileDialogConfiguration fileDialogConfiguration = new FileDialogConfiguration.Builder()
- .addExtensionFilter(Localization.lang("Style file"), StandardFileType.JSTYLE)
- .withDefaultExtension(Localization.lang("Style file"), StandardFileType.JSTYLE)
- .withInitialDirectory(Globals.prefs.get(JabRefPreferences.WORKING_DIRECTORY))
- .build();
-
- browse.addActionListener(e -> {
- Optional file = DefaultTaskExecutor
- .runInJavaFXThread(() -> dialogService.showFileOpenDialog(fileDialogConfiguration));
- file.ifPresent(f -> newFile.setText(f.toAbsolutePath().toString()));
- });
-
- // Build content panel
- FormBuilder builder = FormBuilder.create();
- builder.layout(new FormLayout("left:pref, 4dlu, fill:100dlu:grow, 4dlu, pref", "p"));
- builder.add(Localization.lang("File")).xy(1, 1);
- builder.add(newFile).xy(3, 1);
- builder.add(browse).xy(5, 1);
- builder.padding("10dlu, 10dlu, 10dlu, 10dlu");
- getContentPane().add(builder.build(), BorderLayout.CENTER);
-
- // Buttons
- ButtonBarBuilder bb = new ButtonBarBuilder();
- JButton addOKButton = new JButton(Localization.lang("OK"));
- JButton addCancelButton = new JButton(Localization.lang("Cancel"));
- bb.addGlue();
- bb.addButton(addOKButton);
- bb.addButton(addCancelButton);
- bb.addGlue();
- bb.getPanel().setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
- getContentPane().add(bb.getPanel(), BorderLayout.SOUTH);
- addOKButton.addActionListener(e -> {
- addOKPressed = true;
- dispose();
- });
-
- Action cancelAction = new AbstractAction() {
-
- @Override
- public void actionPerformed(ActionEvent e) {
- addOKPressed = false;
- dispose();
- }
- };
- addCancelButton.addActionListener(cancelAction);
-
- // Key bindings:
- bb.getPanel()
- .getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW)
- .put(Globals.getKeyPrefs().getKey(KeyBinding.CLOSE), "close");
- bb.getPanel().getActionMap().put("close", cancelAction);
- pack();
- setLocationRelativeTo(diag);
- }
-
- public Optional getFileName() {
- if (addOKPressed && (newFile.getText() != null) && !newFile.getText().isEmpty()) {
- return Optional.of(newFile.getText());
- }
- return Optional.empty();
- }
-
- public void setDirectoryPath(String path) {
- this.newFile.setText(path);
- }
- }
-}
diff --git a/src/main/java/org/jabref/gui/openoffice/StyleSelectDialogView.java b/src/main/java/org/jabref/gui/openoffice/StyleSelectDialogView.java
new file mode 100644
index 00000000000..2a160c15d03
--- /dev/null
+++ b/src/main/java/org/jabref/gui/openoffice/StyleSelectDialogView.java
@@ -0,0 +1,145 @@
+package org.jabref.gui.openoffice;
+
+import javax.inject.Inject;
+
+import javafx.fxml.FXML;
+import javafx.scene.control.Button;
+import javafx.scene.control.ButtonType;
+import javafx.scene.control.ContextMenu;
+import javafx.scene.control.MenuItem;
+import javafx.scene.control.TableColumn;
+import javafx.scene.control.TableView;
+import javafx.scene.layout.VBox;
+
+import org.jabref.gui.DialogService;
+import org.jabref.gui.PreviewPanel;
+import org.jabref.gui.externalfiletype.ExternalFileTypes;
+import org.jabref.gui.icon.IconTheme;
+import org.jabref.gui.util.BaseDialog;
+import org.jabref.gui.util.ValueTableCellFactory;
+import org.jabref.gui.util.ViewModelTableRowFactory;
+import org.jabref.logic.l10n.Localization;
+import org.jabref.logic.openoffice.OOBibStyle;
+import org.jabref.logic.openoffice.StyleLoader;
+import org.jabref.logic.util.TestEntry;
+import org.jabref.model.database.BibDatabaseContext;
+import org.jabref.preferences.PreferencesService;
+
+import com.airhacks.afterburner.views.ViewLoader;
+import org.fxmisc.easybind.EasyBind;
+
+public class StyleSelectDialogView extends BaseDialog {
+
+ @FXML private TableColumn colName;
+ @FXML private TableView tvStyles;
+ @FXML private TableColumn colJournals;
+ @FXML private TableColumn colFile;
+ @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;
+
+ public StyleSelectDialogView(StyleLoader loader) {
+
+ this.loader = loader;
+
+ ViewLoader.view(this)
+ .load()
+ .setAsDialogPane(this);
+
+ setResultConverter(button -> {
+ if (button == ButtonType.OK) {
+ viewModel.storePrefs();
+ return tvStyles.getSelectionModel().getSelectedItem().getStyle();
+ }
+ return null;
+
+ });
+ setTitle(Localization.lang("Style selection"));
+ }
+
+ @FXML
+ private void initialize() {
+
+ viewModel = new StyleSelectDialogViewModel(dialogService, loader, preferencesService);
+
+ previewArticle = new PreviewPanel(null, new BibDatabaseContext(), preferencesService.getKeyBindingRepository(), preferencesService.getPreviewPreferences(), dialogService, ExternalFileTypes.getInstance());
+ previewArticle.setEntry(TestEntry.getTestEntry());
+ vbox.getChildren().add(previewArticle);
+
+ previewBook = new PreviewPanel(null, new BibDatabaseContext(), preferencesService.getKeyBindingRepository(), preferencesService.getPreviewPreferences(), dialogService, ExternalFileTypes.getInstance());
+ previewBook.setEntry(TestEntry.getTestEntryBook());
+ vbox.getChildren().add(previewBook);
+
+ colName.setCellValueFactory(cellData -> cellData.getValue().nameProperty());
+ colJournals.setCellValueFactory(cellData -> cellData.getValue().journalsProperty());
+ colFile.setCellValueFactory(cellData -> cellData.getValue().fileProperty());
+ 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);
+
+ edit.setOnAction(e -> viewModel.editStyle());
+
+ new ViewModelTableRowFactory()
+ .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) {
+ viewModel.selectedItemProperty().setValue(oldvalue);
+ } else {
+ viewModel.selectedItemProperty().setValue(newvalue);
+ }
+ });
+
+ tvStyles.setItems(viewModel.stylesProperty());
+
+ add.setGraphic(IconTheme.JabRefIcons.ADD.getGraphicNode());
+
+ EasyBind.subscribe(viewModel.selectedItemProperty(), style -> {
+ tvStyles.getSelectionModel().select(style);
+ previewArticle.setLayout(style.getStyle().getReferenceFormat("default"));
+ previewBook.setLayout(style.getStyle().getReferenceFormat("default"));
+ });
+ }
+
+ private ContextMenu createContextMenu() {
+ ContextMenu contextMenu = new ContextMenu();
+ contextMenu.getItems().addAll(edit, reload);
+ return contextMenu;
+ }
+
+ @FXML
+ 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
new file mode 100644
index 00000000000..203c495243b
--- /dev/null
+++ b/src/main/java/org/jabref/gui/openoffice/StyleSelectDialogViewModel.java
@@ -0,0 +1,137 @@
+package org.jabref.gui.openoffice;
+
+import java.io.IOException;
+import java.nio.file.Path;
+import java.util.List;
+import java.util.Optional;
+import java.util.stream.Collectors;
+
+import javafx.beans.property.ListProperty;
+import javafx.beans.property.ObjectProperty;
+import javafx.beans.property.SimpleListProperty;
+import javafx.beans.property.SimpleObjectProperty;
+import javafx.collections.FXCollections;
+import javafx.scene.control.ButtonType;
+import javafx.scene.control.DialogPane;
+import javafx.scene.control.ScrollPane;
+import javafx.scene.control.TextArea;
+
+import org.jabref.gui.DialogService;
+import org.jabref.gui.desktop.JabRefDesktop;
+import org.jabref.gui.externalfiletype.ExternalFileType;
+import org.jabref.gui.externalfiletype.ExternalFileTypes;
+import org.jabref.gui.util.FileDialogConfiguration;
+import org.jabref.logic.l10n.Localization;
+import org.jabref.logic.openoffice.OOBibStyle;
+import org.jabref.logic.openoffice.OpenOfficePreferences;
+import org.jabref.logic.openoffice.StyleLoader;
+import org.jabref.logic.util.StandardFileType;
+import org.jabref.model.database.BibDatabaseContext;
+import org.jabref.preferences.PreferencesService;
+
+public class StyleSelectDialogViewModel {
+
+ private final DialogService dialogService;
+ private final StyleLoader loader;
+ private final OpenOfficePreferences preferences;
+ private final PreferencesService preferencesService;
+ private final ListProperty styles = new SimpleListProperty<>(FXCollections.observableArrayList());
+ private final ObjectProperty selectedItem = new SimpleObjectProperty<>();
+
+ public StyleSelectDialogViewModel(DialogService dialogService, StyleLoader loader, PreferencesService preferencesService) {
+ this.dialogService = dialogService;
+ this.preferences = preferencesService.getOpenOfficePreferences();
+ this.loader = loader;
+ this.preferencesService = preferencesService;
+
+ styles.addAll(loadStyles());
+
+ String currentStyle = preferences.getCurrentStyle();
+ Optional lastUsedStyle = styles.stream().filter(style -> style.getStylePath().equals(currentStyle)).findFirst();
+
+ if (lastUsedStyle.isPresent()) {
+ selectedItem.setValue(lastUsedStyle.get());
+ } else {
+ selectedItem.setValue(styles.get(0));
+ }
+
+ }
+
+ public StyleSelectItemViewModel fromOOBibStyle(OOBibStyle style) {
+ return new StyleSelectItemViewModel(style.getName(), String.join(", ", style.getJournals()), style.isFromResource() ? Localization.lang("Internal style") : style.getPath(), style);
+ }
+
+ public OOBibStyle toOOBibStyle(StyleSelectItemViewModel item) {
+ return item.getStyle();
+ }
+
+ 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();
+ Optional path = dialogService.showFileOpenDialog(fileDialogConfiguration);
+ path.map(Path::toAbsolutePath).map(Path::toString).ifPresent(stylePath -> {
+ if (loader.addStyleIfValid(stylePath)) {
+ preferences.setCurrentStyle(stylePath);
+ styles.setAll(loadStyles());
+ } else {
+ dialogService.showErrorDialogAndWait(Localization.lang("Invalid style selected"), Localization.lang("You must select a valid style file."));
+ }
+ });
+
+ }
+
+ public List loadStyles() {
+ return loader.getStyles().stream().map(this::fromOOBibStyle).collect(Collectors.toList());
+ }
+
+ public ListProperty stylesProperty() {
+ return styles;
+ }
+
+ public void deleteStyle() {
+
+ OOBibStyle style = selectedItem.getValue().getStyle();
+ if (loader.removeStyle(style)) {
+ styles.remove(selectedItem.get());
+ }
+
+ }
+
+ public void editStyle() {
+ OOBibStyle style = selectedItem.getValue().getStyle();
+
+ Optional type = ExternalFileTypes.getInstance().getExternalFileTypeByExt("jstyle");
+
+ try {
+ JabRefDesktop.openExternalFileAnyFormat(new BibDatabaseContext(), style.getPath().toString(), type);
+ } catch (IOException e) {
+ dialogService.showErrorDialogAndWait(e);
+ }
+ }
+
+ public void viewStyle(StyleSelectItemViewModel item) {
+
+ DialogPane pane = new DialogPane();
+ ScrollPane scrollPane = new ScrollPane();
+ scrollPane.setFitToHeight(true);
+ scrollPane.setFitToWidth(true);
+ TextArea styleView = new TextArea(item.getStyle().getLocalCopy());
+ scrollPane.setContent(styleView);
+ pane.setContent(scrollPane);
+ dialogService.showCustomDialogAndWait(item.getStyle().getName(), pane, ButtonType.OK);
+
+ }
+
+ public ObjectProperty selectedItemProperty() {
+ return selectedItem;
+ }
+
+ 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
new file mode 100644
index 00000000000..1b4eebf2070
--- /dev/null
+++ b/src/main/java/org/jabref/gui/openoffice/StyleSelectItemViewModel.java
@@ -0,0 +1,59 @@
+package org.jabref.gui.openoffice;
+
+import javafx.beans.property.BooleanProperty;
+import javafx.beans.property.ObjectProperty;
+import javafx.beans.property.SimpleBooleanProperty;
+import javafx.beans.property.SimpleObjectProperty;
+import javafx.beans.property.SimpleStringProperty;
+import javafx.beans.property.StringProperty;
+import javafx.scene.Node;
+
+import org.jabref.gui.icon.IconTheme;
+import org.jabref.logic.openoffice.OOBibStyle;
+
+public class StyleSelectItemViewModel {
+
+ private final StringProperty name = new SimpleStringProperty("");
+ private final StringProperty journals = new SimpleStringProperty("");
+ private final StringProperty file = new SimpleStringProperty("");
+ private final ObjectProperty icon = new SimpleObjectProperty<>(IconTheme.JabRefIcons.DELETE_ENTRY.getGraphicNode());
+ private final OOBibStyle style;
+ private final BooleanProperty internalStyle = new SimpleBooleanProperty();
+
+ public StyleSelectItemViewModel(String name, String journals, String file, OOBibStyle style) {
+ this.name.setValue(name);
+ this.journals.setValue(journals);
+ this.file.setValue(file);
+ this.style = style;
+ this.internalStyle.set(style.isFromResource());
+ }
+
+ public StringProperty nameProperty() {
+ return name;
+ }
+
+ public StringProperty journalsProperty() {
+ return journals;
+ }
+
+ public ObjectProperty iconProperty() {
+ return icon;
+ }
+
+ public StringProperty fileProperty() {
+ return file;
+ }
+
+ public OOBibStyle getStyle() {
+ return style;
+ }
+
+ public BooleanProperty internalStyleProperty() {
+ return internalStyle;
+ }
+
+ public String getStylePath() {
+ return style.getPath();
+ }
+
+}
diff --git a/src/main/java/org/jabref/gui/openoffice/UndefinedCharacterFormatException.java b/src/main/java/org/jabref/gui/openoffice/UndefinedCharacterFormatException.java
index bf799e91d7d..4ab29ca2fa5 100644
--- a/src/main/java/org/jabref/gui/openoffice/UndefinedCharacterFormatException.java
+++ b/src/main/java/org/jabref/gui/openoffice/UndefinedCharacterFormatException.java
@@ -8,7 +8,6 @@ class UndefinedCharacterFormatException extends Exception {
private final String formatName;
-
public UndefinedCharacterFormatException(String formatName) {
super();
this.formatName = formatName;
diff --git a/src/main/java/org/jabref/logic/openoffice/CitationEntry.java b/src/main/java/org/jabref/logic/openoffice/CitationEntry.java
index b2273cd7aaa..3acbee9ed35 100644
--- a/src/main/java/org/jabref/logic/openoffice/CitationEntry.java
+++ b/src/main/java/org/jabref/logic/openoffice/CitationEntry.java
@@ -1,20 +1,18 @@
package org.jabref.logic.openoffice;
+import java.util.Objects;
import java.util.Optional;
public class CitationEntry implements Comparable {
private final String refMarkName;
- private Optional pageInfo;
+ private final Optional pageInfo;
private final String context;
- private final Optional origPageInfo;
- // Only used for testing...
public CitationEntry(String refMarkName, String context) {
this(refMarkName, context, Optional.empty());
}
- // Only used for testing...
public CitationEntry(String refMarkName, String context, String pageInfo) {
this(refMarkName, context, Optional.ofNullable(pageInfo));
}
@@ -23,7 +21,6 @@ public CitationEntry(String refMarkName, String context, Optional pageIn
this.refMarkName = refMarkName;
this.context = context;
this.pageInfo = pageInfo;
- this.origPageInfo = pageInfo;
}
public Optional getPageInfo() {
@@ -34,19 +31,6 @@ public String getRefMarkName() {
return refMarkName;
}
- public boolean pageInfoChanged() {
- if (pageInfo.isPresent() ^ origPageInfo.isPresent()) {
- return true;
- }
- if (pageInfo.isPresent()) {
- // This means that origPageInfo.isPresent is also true here
- return pageInfo.get().compareTo(origPageInfo.get()) != 0;
- } else {
- // So origPageInfo.isPresent is false here
- return false;
- }
- }
-
@Override
public int compareTo(CitationEntry other) {
return this.refMarkName.compareTo(other.refMarkName);
@@ -59,21 +43,18 @@ public boolean equals(Object o) {
}
if (o instanceof CitationEntry) {
CitationEntry other = (CitationEntry) o;
- return this.refMarkName.equals(other.refMarkName);
+ return Objects.equals(this.refMarkName, other.refMarkName);
}
return false;
}
@Override
public int hashCode() {
- return this.refMarkName.hashCode();
+ return Objects.hash(refMarkName);
}
public String getContext() {
return context;
}
- public void setPageInfo(String trim) {
- pageInfo = Optional.ofNullable(trim);
- }
}
diff --git a/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java b/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java
index b07f09c55a8..2d71b151207 100644
--- a/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java
+++ b/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java
@@ -855,6 +855,10 @@ public Object getProperty(String propName) {
return properties.get(propName);
}
+ /**
+ * Indicate if it is an internal style
+ * @return True if an internal style
+ */
public boolean isFromResource() {
return fromResource;
}
@@ -875,7 +879,8 @@ public boolean equals(Object o) {
}
if (o instanceof OOBibStyle) {
OOBibStyle otherStyle = (OOBibStyle) o;
- return Objects.equals(path, otherStyle.path) && Objects.equals(name, otherStyle.name)
+ return Objects.equals(path, otherStyle.path)
+ && Objects.equals(name, otherStyle.name)
&& Objects.equals(citProperties, otherStyle.citProperties)
&& Objects.equals(properties, otherStyle.properties);
}
diff --git a/src/main/java/org/jabref/logic/openoffice/OpenOfficePreferences.java b/src/main/java/org/jabref/logic/openoffice/OpenOfficePreferences.java
index 419377ba715..f3d6a0b29a0 100644
--- a/src/main/java/org/jabref/logic/openoffice/OpenOfficePreferences.java
+++ b/src/main/java/org/jabref/logic/openoffice/OpenOfficePreferences.java
@@ -1,5 +1,6 @@
package org.jabref.logic.openoffice;
+import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
@@ -9,8 +10,8 @@ public class OpenOfficePreferences {
public static final String DEFAULT_WIN_EXEC_PATH = "C:\\Program Files\\LibreOffice 5\\program";
public static final String WINDOWS_EXECUTABLE = "soffice.exe";
- public static final String DEFAULT_OSX_PATH = "/Applications/OpenOffice.org.app";
- public static final String DEFAULT_OSX_EXEC_PATH = "/Applications/OpenOffice.org.app/Contents/MacOS/soffice";
+ public static final String DEFAULT_OSX_PATH = "/Applications/LibreOffice.app";
+ public static final String DEFAULT_OSX_EXEC_PATH = "/Applications/LibreOffice.app/Contents/MacOS/soffice";
public static final String OSX_EXECUTABLE = "soffice";
public static final String DEFAULT_LINUX_PATH = "/usr/lib/libreoffice";
@@ -19,22 +20,22 @@ public class OpenOfficePreferences {
public static final List OO_JARS = Arrays.asList("unoil.jar", "jurt.jar", "juh.jar", "ridl.jar");
- private String executablePath;
- private String installationPath;
- private Boolean useAllDatabases;
- private Boolean syncWhenCiting;
- private Boolean showPanel;
- private List externalStyles;
- private String currentStyle;
- private String jarsPath;
+ private String executablePath = "";
+ private String installationPath = "";
+ private boolean useAllDatabases;
+ private boolean syncWhenCiting;
+ private boolean showPanel;
+ private List externalStyles = new ArrayList<>();
+ private String currentStyle = "";
+ private String jarsPath = "";
public OpenOfficePreferences(
String jarsPath,
String executablePath,
String installationPath,
- Boolean useAllDatabases,
- Boolean syncWhenCiting,
- Boolean showPanel,
+ boolean useAllDatabases,
+ boolean syncWhenCiting,
+ boolean showPanel,
List externalStyles,
String currentStyle
) {
@@ -93,18 +94,18 @@ public Boolean getSyncWhenCiting() {
return syncWhenCiting;
}
- public void setSyncWhenCiting(Boolean syncWhenCiting) {
+ public void setSyncWhenCiting(boolean syncWhenCiting) {
this.syncWhenCiting = syncWhenCiting;
}
/**
* true if the OO panel is shown on startup
*/
- public Boolean getShowPanel() {
+ public boolean getShowPanel() {
return showPanel;
}
- public void setShowPanel(Boolean showPanel) {
+ public void setShowPanel(boolean showPanel) {
this.showPanel = showPanel;
}
@@ -148,9 +149,9 @@ public void updateConnectionParams(String ooPath, String execPath, String jarsPa
}
public void clearConnectionSettings() {
- this.installationPath = null;
- this.executablePath = null;
- this.jarsPath = null;
+ this.installationPath = "";
+ this.executablePath = "";
+ this.jarsPath = "";
}
}
diff --git a/src/main/java/org/jabref/logic/util/TestEntry.java b/src/main/java/org/jabref/logic/util/TestEntry.java
index 6c98136c848..5ef00045c54 100644
--- a/src/main/java/org/jabref/logic/util/TestEntry.java
+++ b/src/main/java/org/jabref/logic/util/TestEntry.java
@@ -30,4 +30,17 @@ public static BibEntry getTestEntry() {
"This entry describes a test scenario which may be useful in JabRef. By providing a test entry it is possible to see how certain things will look in this graphical BIB-file mananger.");
return entry;
}
+
+ public static BibEntry getTestEntryBook() {
+ BibEntry entry = new BibEntry(BibtexEntryTypes.BOOK);
+ entry.setCiteKey("Harrer2018");
+ entry.setField(FieldName.AUTHOR, "Simon Harrer and Jörg Lenhard and Linus Dietz");
+ entry.setField(FieldName.EDITOR, "Andrea Steward");
+ entry.setField(FieldName.TITLE, "Java by Comparison");
+ entry.setField(FieldName.YEAR, "2018");
+ entry.setField(FieldName.MONTH, "March");
+ entry.setField(FieldName.PUBLISHER, "Pragmatic Bookshelf");
+ entry.setField(FieldName.ADDRESS, "Raleigh, NC");
+ return entry;
+ }
}
diff --git a/src/main/java/org/jabref/preferences/JabRefPreferences.java b/src/main/java/org/jabref/preferences/JabRefPreferences.java
index 5d3d38d061e..e7320ee4d95 100644
--- a/src/main/java/org/jabref/preferences/JabRefPreferences.java
+++ b/src/main/java/org/jabref/preferences/JabRefPreferences.java
@@ -1546,6 +1546,7 @@ public XmpPreferences getXMPPreferences() {
getKeywordDelimiter());
}
+ @Override
public OpenOfficePreferences getOpenOfficePreferences() {
return new OpenOfficePreferences(
this.get(JabRefPreferences.OO_JARS_PATH),
@@ -1558,6 +1559,7 @@ public OpenOfficePreferences getOpenOfficePreferences() {
this.get(JabRefPreferences.OO_BIBLIOGRAPHY_STYLE_FILE));
}
+ @Override
public void setOpenOfficePreferences(OpenOfficePreferences openOfficePreferences) {
this.put(JabRefPreferences.OO_JARS_PATH, openOfficePreferences.getJarsPath());
this.put(JabRefPreferences.OO_EXECUTABLE_PATH, openOfficePreferences.getExecutablePath());
@@ -1598,6 +1600,7 @@ public JabRefPreferences storePreviewPreferences(PreviewPreferences previewPrefe
return this;
}
+ @Override
public PreviewPreferences getPreviewPreferences() {
int cyclePos = getInt(CYCLE_PREVIEW_POS);
List cycle = getStringList(CYCLE_PREVIEW);
diff --git a/src/main/java/org/jabref/preferences/PreferencesService.java b/src/main/java/org/jabref/preferences/PreferencesService.java
index 97931addffa..46c208a12f4 100644
--- a/src/main/java/org/jabref/preferences/PreferencesService.java
+++ b/src/main/java/org/jabref/preferences/PreferencesService.java
@@ -10,9 +10,11 @@
import org.jabref.logic.journals.JournalAbbreviationLoader;
import org.jabref.logic.journals.JournalAbbreviationPreferences;
import org.jabref.logic.layout.LayoutFormatterPreferences;
+import org.jabref.logic.openoffice.OpenOfficePreferences;
import org.jabref.model.metadata.FilePreferences;
public interface PreferencesService {
+
JournalAbbreviationPreferences getJournalAbbreviationPreferences();
void storeKeyBindingRepository(KeyBindingRepository keyBindingRepository);
@@ -27,6 +29,12 @@ public interface PreferencesService {
void setWorkingDir(Path dir);
+ OpenOfficePreferences getOpenOfficePreferences();
+
+ void setOpenOfficePreferences(OpenOfficePreferences openOfficePreferences);
+
+ PreviewPreferences getPreviewPreferences();
+
Map> getEntryEditorTabList();
Boolean getEnforceLegalKeys();
diff --git a/src/main/resources/l10n/JabRef_en.properties b/src/main/resources/l10n/JabRef_en.properties
index 90fe32bdc9d..5b5e6925b1e 100644
--- a/src/main/resources/l10n/JabRef_en.properties
+++ b/src/main/resources/l10n/JabRef_en.properties
@@ -1289,7 +1289,7 @@ Extra\ information\ (e.g.\ page\ number)=Extra information (e.g. page number)
Manage\ citations=Manage citations
Problem\ modifying\ citation=Problem modifying citation
Citation=Citation
-Extra\ information=Extra information
+Connecting...=Connecting...
Could\ not\ resolve\ BibTeX\ entry\ for\ citation\ marker\ '%0'.=Could not resolve BibTeX entry for citation marker '%0'.
Select\ style=Select style
Journals=Journals
@@ -1309,7 +1309,6 @@ Your\ OpenOffice/LibreOffice\ document\ references\ the\ BibTeX\ key\ '%0',\ whi
Unable\ to\ synchronize\ bibliography=Unable to synchronize bibliography
Combine\ pairs\ of\ citations\ that\ are\ separated\ by\ spaces\ only=Combine pairs of citations that are separated by spaces only
Autodetection\ failed=Autodetection failed
-Connecting=Connecting
Please\ wait...=Please wait...
Set\ connection\ parameters=Set connection parameters
Path\ to\ OpenOffice/LibreOffice\ directory=Path to OpenOffice/LibreOffice directory
@@ -1700,11 +1699,11 @@ Run\ field\ formatter\:=Run field formatter:
Table\ font\ size\ is\ %0=Table font size is %0
Internal\ style=Internal style
Add\ style\ file=Add style file
-Are\ you\ sure\ you\ want\ to\ remove\ the\ style?=Are you sure you want to remove the style?
Current\ style\ is\ '%0'=Current style is '%0'
Remove\ style=Remove style
-Select\ one\ of\ the\ available\ styles\ or\ add\ a\ style\ file\ from\ disk.=Select one of the available styles or add a style file from disk.
You\ must\ select\ a\ valid\ style\ file.=You must select a valid style file.
+Invalid\ style\ selected=Invalid style selected
+
Reload=Reload
Capitalize=Capitalize
@@ -1819,7 +1818,6 @@ booktitle\ ends\ with\ 'conference\ on'=booktitle ends with 'conference on'
All\ external\ files=All external files
-OpenOffice/LibreOffice\ integration=OpenOffice/LibreOffice integration
incorrect\ control\ digit=incorrect control digit
incorrect\ format=incorrect format
@@ -1920,7 +1918,6 @@ Your\ issue\ was\ reported\ in\ your\ browser.=Your issue was reported in your b
The\ log\ and\ exception\ information\ was\ copied\ to\ your\ clipboard.=The log and exception information was copied to your clipboard.
Please\ paste\ this\ information\ (with\ Ctrl+V)\ in\ the\ issue\ description.=Please paste this information (with Ctrl+V) in the issue description.
-Connecting...=Connecting...
Host=Host
Port=Port
Library=Library
@@ -2217,3 +2214,5 @@ Main\ layout\ file=Main layout file
Save\ exporter=Save exporter
File\ extension\:=File extension\:
Export\ format\ name\:=Export format name\:
+
+Cleared\ connection\ settings=Cleared connection settings
diff --git a/src/test/java/org/jabref/logic/openoffice/CitationEntryTest.java b/src/test/java/org/jabref/logic/openoffice/CitationEntryTest.java
index 877109eb6ea..b1cd1d100a7 100644
--- a/src/test/java/org/jabref/logic/openoffice/CitationEntryTest.java
+++ b/src/test/java/org/jabref/logic/openoffice/CitationEntryTest.java
@@ -5,7 +5,6 @@
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
@@ -14,7 +13,6 @@ class CitationEntryTest {
@Test
void testCitationEntryInitalPageInfo() {
CitationEntry citationEntry = new CitationEntry("RefMark", "Context", "Info");
- assertFalse(citationEntry.pageInfoChanged());
assertTrue(citationEntry.getPageInfo().isPresent());
assertEquals("Info", citationEntry.getPageInfo().get());
assertEquals("RefMark", citationEntry.getRefMarkName());
@@ -24,9 +22,8 @@ void testCitationEntryInitalPageInfo() {
@Test
void testCitationEntryOptionalInitalPageInfo() {
CitationEntry citationEntry = new CitationEntry("RefMark", "Context", Optional.of("Info"));
- assertFalse(citationEntry.pageInfoChanged());
- assertTrue(citationEntry.getPageInfo().isPresent());
- assertEquals("Info", citationEntry.getPageInfo().get());
+
+ assertEquals(Optional.of("Info"), citationEntry.getPageInfo());
assertEquals("RefMark", citationEntry.getRefMarkName());
assertEquals("Context", citationEntry.getContext());
}
@@ -34,34 +31,13 @@ void testCitationEntryOptionalInitalPageInfo() {
@Test
void testCitationEntryInitalPageInfoChanged() {
CitationEntry citationEntry = new CitationEntry("RefMark", "Context", "Info");
- citationEntry.setPageInfo("Other info");
- assertTrue(citationEntry.pageInfoChanged());
- assertTrue(citationEntry.getPageInfo().isPresent());
- assertEquals("Other info", citationEntry.getPageInfo().get());
- }
-
- @Test
- void testCitationEntryInitalPageInfoRemoved() {
- CitationEntry citationEntry = new CitationEntry("RefMark", "Context", "Info");
- citationEntry.setPageInfo(null);
- assertTrue(citationEntry.pageInfoChanged());
- assertFalse(citationEntry.getPageInfo().isPresent());
+ assertEquals(Optional.of("Info"), citationEntry.getPageInfo());
}
@Test
void testCitationEntryNoInitalPageInfo() {
CitationEntry citationEntry = new CitationEntry("RefMark", "Context");
- assertFalse(citationEntry.pageInfoChanged());
- assertFalse(citationEntry.getPageInfo().isPresent());
- }
-
- @Test
- void testCitationEntryNoInitalPageInfoChanged() {
- CitationEntry citationEntry = new CitationEntry("RefMark", "Context");
- citationEntry.setPageInfo("Other info");
- assertTrue(citationEntry.pageInfoChanged());
- assertTrue(citationEntry.getPageInfo().isPresent());
- assertEquals("Other info", citationEntry.getPageInfo().get());
+ assertEquals(Optional.empty(), citationEntry.getPageInfo());
}
@Test
From aa3657cacf9697a1236969336d1bf1ff9258ef8f Mon Sep 17 00:00:00 2001
From: frasca80 <26461960+frasca80@users.noreply.github.com>
Date: Fri, 25 Jan 2019 17:42:46 +0100
Subject: [PATCH 11/20] Fix for BibTex source tab parsing issue if field
contains {} (#4581)
* Cleanup interfaces (#4553)
* improve styling of preferences side menu (#4556)
* Added extra stats to be sent with MrDLib recommendations (#4452)
* Refactor BibEntry deprecated method (#4554)
* Refactor BibEntry deprecated method
* Fixed error
* More on checkstyle fixing
* Fixed checkstyle issues
* Added custom entrytype for types not registered in the enumerator.
* Added getTypeOrDefault method refactor code to use it and fix NPE problem
* Fixing checkstyle rules
* More on checkstyle
* More on getType getTypeOrDefault replacement
* Revert Article EntryType into Electronic
* Added break line between different packages
* Refactor BibtextEntryTypes.getTypeOrDefault method
* Removed unused import
* Removed extra new line, checkstyle error fixing
* Delete the deprecated BibEntry Constructor (#4560)
* Bump xmpbox from 2.0.12 to 2.0.13 (#4561)
Bumps xmpbox from 2.0.12 to 2.0.13.
Signed-off-by: dependabot[bot]
* Bump checkstyle from 8.15 to 8.16 (#4562)
Bumps [checkstyle](https://github.com/checkstyle/checkstyle) from 8.15 to 8.16.
- [Release notes](https://github.com/checkstyle/checkstyle/releases)
- [Commits](https://github.com/checkstyle/checkstyle/compare/checkstyle-8.15...checkstyle-8.16)
Signed-off-by: dependabot[bot]
* Do not extract file ending from Urls (#4547)
* Fixes #4544 Do not extract file ending from Urls
* Add tests
* file type for any resource type
* Keep simple file name extraction for files
* checkstyle
* Converts integrity check dialog to JavaFX (#4559)
* Converts integrity check dialog to JavaFX
Moreover:
- Show entry by reference and not by id. Fixes #2181.
- Fixes a few issues that occurred when opening the entry editor by code from the integrity dialog
- Reuse gridpane in entry editor (should have a slightly superior performance)
- Improve display of progress dialog
- Invoke copy files task using central task executor
* fix l10n
fix aborting of copy files task and showing of integrity check dialog
* fix l10n
* Add uncaught exception message (#4565)
* Add error message for uncaught exceptions
Added a new view to the project. It's shown after the uncaught exception is logged.
* Add simple text to fallback error view
Added a label asking the user to look into the logfiles for more details.
* Add error message to language files
Added the error message to the german and english language files.
* Add ErrorDialogAndWait
Removed the FallbackErrorView. Added the showErrorDialogAndWait call instead.
* BibTex parser triggered on focus out of the text area instead of on value change event
* BibTex parser triggered on focus out of the text area instead of on value change event
* Added a post-parsing validation to be sure there's no relevant unconsidered content into epilog.
Added DialogService in SourceTab as current NotificationPane seems not working.
* Added a post-parsing validation to be sure there's no relevant unconsidered content into epilog.
Added DialogService in SourceTab as current NotificationPane seems not working.
* Codacy/PR Quality Review change.
* Codacy/PR Quality Review change.
---
.../jabref/gui/entryeditor/EntryEditor.java | 2 +-
.../org/jabref/gui/entryeditor/SourceTab.java | 26 +++++++++++++++----
.../importer/fileformat/BibtexParser.java | 14 +++++++++-
.../jabref/gui/entryeditor/SourceTabTest.java | 3 ++-
4 files changed, 37 insertions(+), 8 deletions(-)
diff --git a/src/main/java/org/jabref/gui/entryeditor/EntryEditor.java b/src/main/java/org/jabref/gui/entryeditor/EntryEditor.java
index c7961bff628..4289c29d1b2 100644
--- a/src/main/java/org/jabref/gui/entryeditor/EntryEditor.java
+++ b/src/main/java/org/jabref/gui/entryeditor/EntryEditor.java
@@ -300,7 +300,7 @@ private List createTabs() {
tabs.add(new RelatedArticlesTab(preferences, dialogService));
// Source tab
- sourceTab = new SourceTab(databaseContext, undoManager, preferences.getLatexFieldFormatterPreferences(), preferences.getImportFormatPreferences(), fileMonitor);
+ sourceTab = new SourceTab(databaseContext, undoManager, preferences.getLatexFieldFormatterPreferences(), preferences.getImportFormatPreferences(), fileMonitor, dialogService);
tabs.add(sourceTab);
return tabs;
}
diff --git a/src/main/java/org/jabref/gui/entryeditor/SourceTab.java b/src/main/java/org/jabref/gui/entryeditor/SourceTab.java
index f380e64e269..b96fed0bea4 100644
--- a/src/main/java/org/jabref/gui/entryeditor/SourceTab.java
+++ b/src/main/java/org/jabref/gui/entryeditor/SourceTab.java
@@ -13,6 +13,7 @@
import javafx.collections.ListChangeListener;
import javafx.scene.control.Tooltip;
+import org.jabref.gui.DialogService;
import org.jabref.gui.icon.IconTheme;
import org.jabref.gui.undo.CountingUndoManager;
import org.jabref.gui.undo.NamedCompound;
@@ -53,8 +54,9 @@ public class SourceTab extends EntryEditorTab {
private final ObservableRuleBasedValidator sourceValidator = new ObservableRuleBasedValidator(sourceIsValid);
private final ImportFormatPreferences importFormatPreferences;
private final FileUpdateMonitor fileMonitor;
+ private final DialogService dialogService;
- public SourceTab(BibDatabaseContext bibDatabaseContext, CountingUndoManager undoManager, LatexFieldFormatterPreferences fieldFormatterPreferences, ImportFormatPreferences importFormatPreferences, FileUpdateMonitor fileMonitor) {
+ public SourceTab(BibDatabaseContext bibDatabaseContext, CountingUndoManager undoManager, LatexFieldFormatterPreferences fieldFormatterPreferences, ImportFormatPreferences importFormatPreferences, FileUpdateMonitor fileMonitor, DialogService dialogService) {
this.mode = bibDatabaseContext.getMode();
this.setText(Localization.lang("%0 source", mode.getFormattedName()));
this.setTooltip(new Tooltip(Localization.lang("Show/edit %0 source", mode.getFormattedName())));
@@ -63,6 +65,7 @@ public SourceTab(BibDatabaseContext bibDatabaseContext, CountingUndoManager undo
this.fieldFormatterPreferences = fieldFormatterPreferences;
this.importFormatPreferences = importFormatPreferences;
this.fileMonitor = fileMonitor;
+ this.dialogService = dialogService;
}
@@ -95,14 +98,21 @@ protected void bindToEntry(BibEntry entry) {
if (sourceValidator.getValidationStatus().isValid()) {
notificationPane.hide();
} else {
- sourceValidator.getValidationStatus().getHighestMessage().ifPresent(validationMessage -> notificationPane.show(validationMessage.getMessage()));
+ sourceValidator.getValidationStatus().getHighestMessage().ifPresent(validationMessage -> {
+ notificationPane.show(validationMessage.getMessage());//this seems not working
+ dialogService.showErrorDialogAndWait(validationMessage.getMessage());
+ });
}
});
this.setContent(codeArea);
- // Store source for every change in the source code
+ // Store source for on focus out event in the source code (within its text area)
// and update source code for every change of entry field values
- BindingsHelper.bindContentBidirectional(entry.getFieldsObservable(), codeArea.textProperty(), this::storeSource, fields -> {
+ BindingsHelper.bindContentBidirectional(entry.getFieldsObservable(), codeArea.focusedProperty(), onFocus -> {
+ if (!onFocus) {
+ storeSource(codeArea.textProperty().getValue());
+ }
+ }, fields -> {
DefaultTaskExecutor.runAndWaitInJavaFXThread(() -> {
codeArea.clear();
try {
@@ -110,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);
}
});
@@ -141,6 +151,12 @@ private void storeSource(String text) {
}
}
+ if (parserResult.hasWarnings()) {
+ // put the warning into as exception text -> it will be displayed to the user
+
+ throw new IllegalStateException(parserResult.getErrorMessage());
+ }
+
NamedCompound compound = new NamedCompound(Localization.lang("source edit"));
BibEntry newEntry = database.getEntries().get(0);
String newKey = newEntry.getCiteKeyOptional().orElse(null);
diff --git a/src/main/java/org/jabref/logic/importer/fileformat/BibtexParser.java b/src/main/java/org/jabref/logic/importer/fileformat/BibtexParser.java
index 06accaed956..db4bffee679 100644
--- a/src/main/java/org/jabref/logic/importer/fileformat/BibtexParser.java
+++ b/src/main/java/org/jabref/logic/importer/fileformat/BibtexParser.java
@@ -16,6 +16,7 @@
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
+import java.util.regex.Pattern;
import org.jabref.logic.bibtex.FieldContentParser;
import org.jabref.logic.exporter.BibtexDatabaseWriter;
@@ -70,7 +71,7 @@ public class BibtexParser implements Parser {
private boolean eof;
private int line = 1;
private ParserResult parserResult;
- private MetaDataParser metaDataParser;
+ private final MetaDataParser metaDataParser;
public BibtexParser(ImportFormatPreferences importFormatPreferences, FileUpdateMonitor fileMonitor) {
this.importFormatPreferences = Objects.requireNonNull(importFormatPreferences);
@@ -211,9 +212,20 @@ private ParserResult parseFileContent() throws IOException {
parseRemainingContent();
+ checkEpilog();
+
return parserResult;
}
+ private void checkEpilog() {
+ // This is an incomplete and inaccurate try to verify if something went wrong with previous parsing activity even though there were no warnings so far
+ // regex looks for something like 'identifier = blabla ,'
+ if (!parserResult.hasWarnings() && Pattern.compile("\\w+\\s*=.*,").matcher(database.getEpilog()).find()) {
+ parserResult.addWarning("following BibTex fragment has not been parsed:\n" + database.getEpilog());
+ }
+
+ }
+
private void parseRemainingContent() {
database.setEpilog(dumpTextReadSoFarToString().trim());
}
diff --git a/src/test/java/org/jabref/gui/entryeditor/SourceTabTest.java b/src/test/java/org/jabref/gui/entryeditor/SourceTabTest.java
index 48bf1243fc7..df3012e67ad 100644
--- a/src/test/java/org/jabref/gui/entryeditor/SourceTabTest.java
+++ b/src/test/java/org/jabref/gui/entryeditor/SourceTabTest.java
@@ -6,6 +6,7 @@
import javafx.scene.control.TabPane;
import javafx.stage.Stage;
+import org.jabref.gui.FXDialogService;
import org.jabref.gui.undo.CountingUndoManager;
import org.jabref.logic.bibtex.LatexFieldFormatterPreferences;
import org.jabref.logic.importer.ImportFormatPreferences;
@@ -35,7 +36,7 @@ public class SourceTabTest {
public void onStart(Stage stage) {
area = new CodeArea();
area.appendText("some example\n text to go here\n across a couple of \n lines....");
- sourceTab = new SourceTab(new BibDatabaseContext(), new CountingUndoManager(), new LatexFieldFormatterPreferences(), mock(ImportFormatPreferences.class), new DummyFileUpdateMonitor());
+ sourceTab = new SourceTab(new BibDatabaseContext(), new CountingUndoManager(), new LatexFieldFormatterPreferences(), mock(ImportFormatPreferences.class), new DummyFileUpdateMonitor(), new FXDialogService());
pane = new TabPane(
new Tab("main area", area),
new Tab("other tab", new Label("some text")),
From 16a68f3ffd3b44c05c05cd6247839fecd68affc9 Mon Sep 17 00:00:00 2001
From: Christoph
Date: Sat, 26 Jan 2019 17:52:26 +0100
Subject: [PATCH 12/20] Convert DuplicateResolverDialog to javafx (#4601)
* Convert DuplicateResolverDialog to javafx
* add result
* change buttons to button types
simplify dialog
reset duplicate bibtex key search dialog for the moment
* fix help and move buttons to init
return null on default
---
.../jabref/gui/DuplicateResolverDialog.java | 174 ++++++++----------
.../java/org/jabref/gui/DuplicateSearch.java | 60 +++---
src/main/java/org/jabref/gui/JabRefFrame.java | 2 +-
.../ResolveDuplicateLabelDialog.java | 9 +-
.../gui/importer/ImportInspectionDialog.java | 36 ++--
5 files changed, 124 insertions(+), 157 deletions(-)
diff --git a/src/main/java/org/jabref/gui/DuplicateResolverDialog.java b/src/main/java/org/jabref/gui/DuplicateResolverDialog.java
index 362333ebfa0..cb34df3d202 100644
--- a/src/main/java/org/jabref/gui/DuplicateResolverDialog.java
+++ b/src/main/java/org/jabref/gui/DuplicateResolverDialog.java
@@ -1,26 +1,20 @@
package org.jabref.gui;
-import java.awt.BorderLayout;
-import java.awt.event.WindowAdapter;
-import java.awt.event.WindowEvent;
+import javafx.scene.control.Button;
+import javafx.scene.control.ButtonBar;
+import javafx.scene.control.ButtonBar.ButtonData;
+import javafx.scene.control.ButtonType;
+import javafx.scene.layout.BorderPane;
-import javax.swing.Box;
-import javax.swing.JButton;
-import javax.swing.JPanel;
-
-import javafx.scene.Scene;
-
-import org.jabref.gui.customjfx.CustomJFXPanel;
+import org.jabref.gui.DuplicateResolverDialog.DuplicateResolverResult;
import org.jabref.gui.help.HelpAction;
-import org.jabref.gui.importer.ImportInspectionDialog;
import org.jabref.gui.mergeentries.MergeEntries;
-import org.jabref.gui.util.WindowLocation;
+import org.jabref.gui.util.BaseDialog;
import org.jabref.logic.help.HelpFile;
import org.jabref.logic.l10n.Localization;
import org.jabref.model.entry.BibEntry;
-import org.jabref.preferences.JabRefPreferences;
-public class DuplicateResolverDialog extends JabRefDialog {
+public class DuplicateResolverDialog extends BaseDialog {
public enum DuplicateResolverType {
DUPLICATE_SEARCH,
@@ -30,7 +24,6 @@ public enum DuplicateResolverType {
}
public enum DuplicateResolverResult {
- NOT_CHOSEN,
KEEP_BOTH,
KEEP_LEFT,
KEEP_RIGHT,
@@ -39,108 +32,89 @@ public enum DuplicateResolverResult {
BREAK
}
- JButton helpButton = new HelpAction(Localization.lang("Help"), HelpFile.FIND_DUPLICATES).getHelpButton();
- private final JButton cancel = new JButton(Localization.lang("Cancel"));
- private final JButton merge = new JButton(Localization.lang("Keep merged entry only"));
private final JabRefFrame frame;
- private final JPanel options = new JPanel();
- private DuplicateResolverResult status = DuplicateResolverResult.NOT_CHOSEN;
private MergeEntries me;
public DuplicateResolverDialog(JabRefFrame frame, BibEntry one, BibEntry two, DuplicateResolverType type) {
- super(Localization.lang("Possible duplicate entries"), true, DuplicateResolverDialog.class);
this.frame = frame;
- init(one, two, type);
- }
-
- public DuplicateResolverDialog(ImportInspectionDialog dialog, BibEntry one, BibEntry two,
- DuplicateResolverType type) {
- super(dialog, Localization.lang("Possible duplicate entries"), true, DuplicateResolverDialog.class);
- this.frame = dialog.getFrame();
+ this.setTitle(Localization.lang("Possible duplicate entries"));
init(one, two, type);
}
private void init(BibEntry one, BibEntry two, DuplicateResolverType type) {
- JButton both;
- JButton second;
- JButton first;
- JButton removeExact = null;
- switch (type) {
- case DUPLICATE_SEARCH:
- first = new JButton(Localization.lang("Keep left"));
- second = new JButton(Localization.lang("Keep right"));
- both = new JButton(Localization.lang("Keep both"));
- me = new MergeEntries(one, two, frame.getCurrentBasePanel().getBibDatabaseContext().getMode());
- break;
- case INSPECTION:
- first = new JButton(Localization.lang("Remove old entry"));
- second = new JButton(Localization.lang("Remove entry from import"));
- both = new JButton(Localization.lang("Keep both"));
- me = new MergeEntries(one, two, Localization.lang("Old entry"),
- Localization.lang("From import"), frame.getCurrentBasePanel().getBibDatabaseContext().getMode());
- break;
- case DUPLICATE_SEARCH_WITH_EXACT:
- first = new JButton(Localization.lang("Keep left"));
- second = new JButton(Localization.lang("Keep right"));
- both = new JButton(Localization.lang("Keep both"));
- removeExact = new JButton(Localization.lang("Automatically remove exact duplicates"));
- me = new MergeEntries(one, two, frame.getCurrentBasePanel().getBibDatabaseContext().getMode());
- break;
- default:
- first = new JButton(Localization.lang("Import and remove old entry"));
- second = new JButton(Localization.lang("Do not import entry"));
- both = new JButton(Localization.lang("Import and keep old entry"));
- me = new MergeEntries(one, two, Localization.lang("Old entry"),
- Localization.lang("From import"), frame.getCurrentBasePanel().getBibDatabaseContext().getMode());
- break;
- }
- if (removeExact != null) {
- options.add(removeExact);
+ HelpAction helpCommand = new HelpAction(HelpFile.FIND_DUPLICATES);
+ ButtonType help = new ButtonType(Localization.lang("Help"), ButtonData.HELP);
+
+ ButtonType cancel = ButtonType.CANCEL;
+ ButtonType merge = new ButtonType(Localization.lang("Keep merged entry only"), ButtonData.APPLY);
+
+ ButtonBar options = new ButtonBar();
+ ButtonType both;
+ ButtonType second;
+ ButtonType first;
+ ButtonType removeExact = new ButtonType(Localization.lang("Automatically remove exact duplicates"), ButtonData.APPLY);
+ boolean removeExactVisible = false;
+
+ switch (type) {
+ case DUPLICATE_SEARCH:
+ first = new ButtonType(Localization.lang("Keep left"), ButtonData.APPLY);
+ second = new ButtonType(Localization.lang("Keep right"), ButtonData.APPLY);
+ both = new ButtonType(Localization.lang("Keep both"), ButtonData.APPLY);
+ me = new MergeEntries(one, two, frame.getCurrentBasePanel().getBibDatabaseContext().getMode());
+ break;
+ case INSPECTION:
+ first = new ButtonType(Localization.lang("Remove old entry"), ButtonData.APPLY);
+ 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());
+ break;
+ case DUPLICATE_SEARCH_WITH_EXACT:
+ first = new ButtonType(Localization.lang("Keep left"), ButtonData.APPLY);
+ second = new ButtonType(Localization.lang("Keep right"), ButtonData.APPLY);
+ both = new ButtonType(Localization.lang("Keep both"), ButtonData.APPLY);
+
+ removeExactVisible = true;
+
+ me = new MergeEntries(one, two, frame.getCurrentBasePanel().getBibDatabaseContext().getMode());
+ break;
+ default:
+ first = new ButtonType(Localization.lang("Import and remove old entry"), ButtonData.APPLY);
+ 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());
+ break;
}
- options.add(first);
- options.add(second);
- options.add(both);
- options.add(merge);
- options.add(Box.createHorizontalStrut(5));
- options.add(cancel);
- options.add(helpButton);
-
- first.addActionListener(e -> buttonPressed(DuplicateResolverResult.KEEP_LEFT));
- second.addActionListener(e -> buttonPressed(DuplicateResolverResult.KEEP_RIGHT));
- both.addActionListener(e -> buttonPressed(DuplicateResolverResult.KEEP_BOTH));
- merge.addActionListener(e -> buttonPressed(DuplicateResolverResult.KEEP_MERGE));
- if (removeExact != null) {
- removeExact.addActionListener(e -> buttonPressed(DuplicateResolverResult.AUTOREMOVE_EXACT));
+ if (removeExactVisible) {
+ this.getDialogPane().getButtonTypes().add(removeExact);
}
- cancel.addActionListener(e -> buttonPressed(DuplicateResolverResult.BREAK));
- addWindowListener(new WindowAdapter() {
- @Override
- public void windowClosing(WindowEvent e) {
- buttonPressed(DuplicateResolverResult.BREAK);
- }
- });
+ this.getDialogPane().getButtonTypes().addAll(first, second, both, merge, cancel, help);
- getContentPane().add(CustomJFXPanel.wrap(new Scene(me)));
- getContentPane().add(options, BorderLayout.SOUTH);
- pack();
+ BorderPane borderPane = new BorderPane(me);
+ borderPane.setBottom(options);
- WindowLocation pw = new WindowLocation(this, JabRefPreferences.DUPLICATES_POS_X,
- JabRefPreferences.DUPLICATES_POS_Y, JabRefPreferences.DUPLICATES_SIZE_X,
- JabRefPreferences.DUPLICATES_SIZE_Y);
- pw.displayWindowAtStoredLocation();
+ this.setResultConverter(button -> {
- both.requestFocus();
- }
-
- private void buttonPressed(DuplicateResolverResult result) {
- status = result;
- dispose();
- }
+ if (button.equals(first)) {
+ return DuplicateResolverResult.KEEP_LEFT;
+ } else if (button.equals(second)) {
+ return DuplicateResolverResult.KEEP_RIGHT;
+ } else if (button.equals(both)) {
+ return DuplicateResolverResult.KEEP_BOTH;
+ } else if (button.equals(merge)) {
+ return DuplicateResolverResult.KEEP_MERGE;
+ } else if (button.equals(removeExact)) {
+ return DuplicateResolverResult.AUTOREMOVE_EXACT;
+ }
+ return null;
+ });
- public DuplicateResolverResult getSelected() {
- return status;
+ getDialogPane().setContent(borderPane);
+ Button helpButton = (Button) this.getDialogPane().lookupButton(help);
+ helpButton.setOnAction(evt -> helpCommand.getCommand().execute());
}
public BibEntry getMergedEntry() {
diff --git a/src/main/java/org/jabref/gui/DuplicateSearch.java b/src/main/java/org/jabref/gui/DuplicateSearch.java
index 8331483d01f..476b3f70276 100644
--- a/src/main/java/org/jabref/gui/DuplicateSearch.java
+++ b/src/main/java/org/jabref/gui/DuplicateSearch.java
@@ -12,8 +12,6 @@
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
-import javax.swing.SwingUtilities;
-
import org.jabref.Globals;
import org.jabref.JabRefExecutorService;
import org.jabref.gui.DuplicateResolverDialog.DuplicateResolverResult;
@@ -37,15 +35,17 @@ public class DuplicateSearch extends SimpleCommand {
private final AtomicBoolean libraryAnalyzed = new AtomicBoolean();
private final AtomicBoolean autoRemoveExactDuplicates = new AtomicBoolean();
private final AtomicInteger duplicateCount = new AtomicInteger();
+ private final DialogService dialogService;
- public DuplicateSearch(JabRefFrame frame) {
+ public DuplicateSearch(JabRefFrame frame, DialogService dialogService) {
this.frame = frame;
+ this.dialogService = dialogService;
}
@Override
public void execute() {
BasePanel panel = frame.getCurrentBasePanel();
- panel.output(Localization.lang("Searching for duplicates..."));
+ dialogService.notify(Localization.lang("Searching for duplicates..."));
List entries = panel.getDatabase().getEntries();
duplicates.clear();
@@ -57,8 +57,7 @@ public void execute() {
return;
}
- JabRefExecutorService.INSTANCE
- .executeInterruptableTask(() -> searchPossibleDuplicates(entries, panel.getBibDatabaseContext().getMode()), "DuplicateSearcher");
+ JabRefExecutorService.INSTANCE.executeInterruptableTask(() -> searchPossibleDuplicates(entries, panel.getBibDatabaseContext().getMode()), "DuplicateSearcher");
BackgroundTask.wrap(this::verifyDuplicates)
.onSuccess(this::handleDuplicates)
.executeWith(Globals.TASK_EXECUTOR);
@@ -124,13 +123,11 @@ private DuplicateSearchResult verifyDuplicates() {
private void askResolveStrategy(DuplicateSearchResult result, BibEntry first, BibEntry second, DuplicateResolverType resolverType) {
DuplicateResolverDialog dialog = new DuplicateResolverDialog(frame, first, second, resolverType);
- dialog.setVisible(true);
- dialog.dispose();
- DuplicateResolverResult resolverResult = dialog.getSelected();
+ 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
@@ -150,31 +147,30 @@ private void handleDuplicates(DuplicateSearchResult result) {
return;
}
- SwingUtilities.invokeLater(() -> {
- BasePanel panel = frame.getCurrentBasePanel();
- final NamedCompound compoundEdit = new NamedCompound(Localization.lang("duplicate removal"));
- // Now, do the actual removal:
- if (!result.getToRemove().isEmpty()) {
- for (BibEntry entry : result.getToRemove()) {
- panel.getDatabase().removeEntry(entry);
- compoundEdit.addEdit(new UndoableRemoveEntry(panel.getDatabase(), entry, panel));
- }
- panel.markBaseChanged();
+ BasePanel panel = frame.getCurrentBasePanel();
+ final NamedCompound compoundEdit = new NamedCompound(Localization.lang("duplicate removal"));
+ // Now, do the actual removal:
+ if (!result.getToRemove().isEmpty()) {
+ for (BibEntry entry : result.getToRemove()) {
+ panel.getDatabase().removeEntry(entry);
+ compoundEdit.addEdit(new UndoableRemoveEntry(panel.getDatabase(), entry, panel));
}
- // and adding merged entries:
- if (!result.getToAdd().isEmpty()) {
- for (BibEntry entry : result.getToAdd()) {
- panel.getDatabase().insertEntry(entry);
- compoundEdit.addEdit(new UndoableInsertEntry(panel.getDatabase(), entry));
- }
- panel.markBaseChanged();
+ panel.markBaseChanged();
+ }
+ // and adding merged entries:
+ if (!result.getToAdd().isEmpty()) {
+ for (BibEntry entry : result.getToAdd()) {
+ panel.getDatabase().insertEntry(entry);
+ compoundEdit.addEdit(new UndoableInsertEntry(panel.getDatabase(), entry));
}
+ panel.markBaseChanged();
+ }
+
+ dialogService.notify(Localization.lang("Duplicates found") + ": " + duplicateCount.get() + ' '
+ + Localization.lang("pairs processed") + ": " + result.getDuplicateCount());
+ compoundEdit.end();
+ panel.getUndoManager().addEdit(compoundEdit);
- panel.output(Localization.lang("Duplicates found") + ": " + duplicateCount.get() + ' '
- + Localization.lang("pairs processed") + ": " + result.getDuplicateCount());
- compoundEdit.end();
- panel.getUndoManager().addEdit(compoundEdit);
- });
}
/**
diff --git a/src/main/java/org/jabref/gui/JabRefFrame.java b/src/main/java/org/jabref/gui/JabRefFrame.java
index d8fd07cb6f2..b1872641c36 100644
--- a/src/main/java/org/jabref/gui/JabRefFrame.java
+++ b/src/main/java/org/jabref/gui/JabRefFrame.java
@@ -858,7 +858,7 @@ private MenuBar createMenu() {
}
quality.getItems().addAll(
- factory.createMenuItem(StandardActions.FIND_DUPLICATES, new DuplicateSearch(this)),
+ factory.createMenuItem(StandardActions.FIND_DUPLICATES, new DuplicateSearch(this, dialogService)),
factory.createMenuItem(StandardActions.MERGE_ENTRIES, new MergeEntriesAction(this)),
new SeparatorMenuItem(),
diff --git a/src/main/java/org/jabref/gui/bibtexkeypattern/ResolveDuplicateLabelDialog.java b/src/main/java/org/jabref/gui/bibtexkeypattern/ResolveDuplicateLabelDialog.java
index 61434841141..68006125528 100644
--- a/src/main/java/org/jabref/gui/bibtexkeypattern/ResolveDuplicateLabelDialog.java
+++ b/src/main/java/org/jabref/gui/bibtexkeypattern/ResolveDuplicateLabelDialog.java
@@ -44,12 +44,11 @@ class ResolveDuplicateLabelDialog {
private boolean okPressed;
private boolean cancelPressed;
-
public ResolveDuplicateLabelDialog(BasePanel panel, String key, List entries) {
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));
@@ -59,7 +58,7 @@ public ResolveDuplicateLabelDialog(BasePanel panel, String key, List e
JCheckBox cb = new JCheckBox(Localization.lang("Generate BibTeX key"), !first);
b.appendRows("1dlu, p");
b.add(cb).xy(1, row);
- PreviewPanel previewPanel = new PreviewPanel(null, null, Globals.getKeyPrefs(), Globals.prefs.getPreviewPreferences(), new FXDialogService(), ExternalFileTypes.getInstance());
+ PreviewPanel previewPanel = new PreviewPanel(null, panel.getBibDatabaseContext(), Globals.getKeyPrefs(), Globals.prefs.getPreviewPreferences(), new FXDialogService(), ExternalFileTypes.getInstance());
previewPanel.setEntry(entry);
JFXPanel container = CustomJFXPanel.wrap(new Scene(previewPanel));
container.setPreferredSize(new Dimension(800, 90));
@@ -86,8 +85,8 @@ public ResolveDuplicateLabelDialog(BasePanel panel, String key, List e
diag.pack();
ok.addActionListener(e -> {
- okPressed = true;
- diag.dispose();
+ okPressed = true;
+ diag.dispose();
});
ignore.addActionListener(e -> diag.dispose());
diff --git a/src/main/java/org/jabref/gui/importer/ImportInspectionDialog.java b/src/main/java/org/jabref/gui/importer/ImportInspectionDialog.java
index ae3dc7c5b4b..2ce86d731c4 100644
--- a/src/main/java/org/jabref/gui/importer/ImportInspectionDialog.java
+++ b/src/main/java/org/jabref/gui/importer/ImportInspectionDialog.java
@@ -695,14 +695,12 @@ public void actionPerformed(ActionEvent event) {
// is indicated by the entry's group hit status:
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)));
+ 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)));
if (!continuePressed) {
return;
@@ -1053,12 +1051,13 @@ public void mousePressed(MouseEvent e) {
if (other.isPresent()) {
// This will be true if the duplicate is in the existing
// database.
- DuplicateResolverDialog diag = new DuplicateResolverDialog(ImportInspectionDialog.this, other.get(),
+ DuplicateResolverDialog diag = new DuplicateResolverDialog(getFrame(), other.get(),
first, DuplicateResolverDialog.DuplicateResolverType.INSPECTION);
- diag.setLocationRelativeTo(ImportInspectionDialog.this);
- diag.setVisible(true);
+
+ DuplicateResolverResult result = diag.showAndWait().orElse(DuplicateResolverResult.BREAK);
+
ImportInspectionDialog.this.toFront();
- if (diag.getSelected() == DuplicateResolverResult.KEEP_LEFT) {
+ if (result == DuplicateResolverResult.KEEP_LEFT) {
// Remove old entry. Or... add it to a list of entries
// to be deleted. We only delete
// it after Ok is clicked.
@@ -1074,7 +1073,7 @@ public void mousePressed(MouseEvent e) {
entries.getReadWriteLock().writeLock().unlock();
}
- } else if (diag.getSelected() == DuplicateResolverResult.KEEP_RIGHT) {
+ } else if (result == DuplicateResolverResult.KEEP_RIGHT) {
// Remove the entry from the import inspection dialog.
entries.getReadWriteLock().writeLock().lock();
try {
@@ -1082,7 +1081,7 @@ public void mousePressed(MouseEvent e) {
} finally {
entries.getReadWriteLock().writeLock().unlock();
}
- } else if (diag.getSelected() == DuplicateResolverResult.KEEP_BOTH) {
+ } else if (result == DuplicateResolverResult.KEEP_BOTH) {
// Do nothing.
entries.getReadWriteLock().writeLock().lock();
try {
@@ -1090,7 +1089,7 @@ public void mousePressed(MouseEvent e) {
} finally {
entries.getReadWriteLock().writeLock().unlock();
}
- } else if (diag.getSelected() == DuplicateResolverResult.KEEP_MERGE) {
+ } else if (result == DuplicateResolverResult.KEEP_MERGE) {
// Remove old entry. Or... add it to a list of entries
// to be deleted. We only delete
// it after Ok is clicked.
@@ -1114,12 +1113,11 @@ public void mousePressed(MouseEvent e) {
// Check if the duplicate is of another entry in the import:
other = internalDuplicate(entries, first);
if (other.isPresent()) {
- DuplicateResolverDialog diag = new DuplicateResolverDialog(ImportInspectionDialog.this, first,
+ DuplicateResolverDialog diag = new DuplicateResolverDialog(getFrame(), first,
other.get(), DuplicateResolverDialog.DuplicateResolverType.DUPLICATE_SEARCH);
- diag.setLocationRelativeTo(ImportInspectionDialog.this);
- diag.setVisible(true);
+
ImportInspectionDialog.this.toFront();
- DuplicateResolverResult answer = diag.getSelected();
+ DuplicateResolverResult answer = diag.showAndWait().get();
if (answer == DuplicateResolverResult.KEEP_LEFT) {
entries.remove(other.get());
first.setGroupHit(false);
From b3f35ec19a2f9383feab1b3faf97109214bdc780 Mon Sep 17 00:00:00 2001
From: Galileo Sartor
Date: Sat, 26 Jan 2019 17:52:37 +0100
Subject: [PATCH 13/20] Update snapcraft.yaml Move to snap folder
---
.gitignore | 12 ------
.../snapcraft => snap/gui}/jabref.desktop | 2 +-
.../gui/jabref.png | Bin
snap/snapcraft.yaml | 34 +++++++++++++++++
snapcraft.yaml | 35 ------------------
5 files changed, 35 insertions(+), 48 deletions(-)
rename {buildres/snapcraft => snap/gui}/jabref.desktop (90%)
rename buildres/snapcraft/JabRef-icon-256.png => snap/gui/jabref.png (100%)
create mode 100644 snap/snapcraft.yaml
delete mode 100644 snapcraft.yaml
diff --git a/.gitignore b/.gitignore
index eef074f6e45..7c7850841ea 100644
--- a/.gitignore
+++ b/.gitignore
@@ -23,18 +23,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/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..6873178bf86
--- /dev/null
+++ b/snap/snapcraft.yaml
@@ -0,0 +1,34 @@
+name: jabref
+version: "git"
+version-script: cat build.gradle | grep "^version =" | cut -d'"' -f2
+#icon: snap/gui/icon.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
+
+apps:
+ jabref:
+ command: desktop-launch java -jar $SNAP/jar/JabRef-$SNAP_VERSION.jar
+ environment:
+ JAVA_OPTS: "-Djava.util.prefs.systemRoot=$SNAP_USER_DATA/.java -Djava.util.prefs.userRoot=$SNAP_USER_DATA/.java/.userPrefs"
+ plugs:
+ - desktop
+ - desktop-legacy
+ - wayland
+ - unity7
+ - home
+ - network-bind
+
+parts:
+ jabref:
+ plugin: gradle
+ source: .
+ stage-packages:
+ - openjdk-8-jre
+ - openjfx
+ - x11-utils
+ gradle-options: [snapJar]
+ gradle-output-dir: 'build/releases'
+ after: [desktop-gtk3]
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]
From 69661a4a7ca4dc7f33726da3b80e2bfdcd1e0932 Mon Sep 17 00:00:00 2001
From: Christoph
Date: Sun, 27 Jan 2019 12:04:48 +0100
Subject: [PATCH 14/20] Try to fix not on FX thread for search and autocomplete
(#4618)
* Try to fix not on FX thread for search and autocomplete
* fix comment text
---
src/main/java/org/jabref/gui/BasePanel.java | 12 +++++++-----
1 file changed, 7 insertions(+), 5 deletions(-)
diff --git a/src/main/java/org/jabref/gui/BasePanel.java b/src/main/java/org/jabref/gui/BasePanel.java
index a2e7e5734b6..777c06eaf6f 100644
--- a/src/main/java/org/jabref/gui/BasePanel.java
+++ b/src/main/java/org/jabref/gui/BasePanel.java
@@ -1345,39 +1345,41 @@ public void listen(EntryRemovedEvent entryRemovedEvent) {
/**
* Ensures that the search auto completer is up to date when entries are changed AKA Let the auto completer, if any,
* harvest words from the entry
+ * Actual methods for autocomplete indexing must run in javafx thread
*/
private class SearchAutoCompleteListener {
@Subscribe
public void listen(EntryAddedEvent addedEntryEvent) {
- searchAutoCompleter.indexEntry(addedEntryEvent.getBibEntry());
+ DefaultTaskExecutor.runInJavaFXThread(() -> searchAutoCompleter.indexEntry(addedEntryEvent.getBibEntry()));
}
@Subscribe
public void listen(EntryChangedEvent entryChangedEvent) {
- searchAutoCompleter.indexEntry(entryChangedEvent.getBibEntry());
+ DefaultTaskExecutor.runInJavaFXThread(() -> searchAutoCompleter.indexEntry(entryChangedEvent.getBibEntry()));
}
}
/**
* Ensures that the results of the current search are updated when a new entry is inserted into the database
+ * Actual methods for performing search must run in javafx thread
*/
private class SearchListener {
@Subscribe
public void listen(EntryAddedEvent addedEntryEvent) {
- frame.getGlobalSearchBar().performSearch();
+ DefaultTaskExecutor.runInJavaFXThread(() -> frame.getGlobalSearchBar().performSearch());
}
@Subscribe
public void listen(EntryChangedEvent entryChangedEvent) {
- frame.getGlobalSearchBar().performSearch();
+ DefaultTaskExecutor.runInJavaFXThread(() -> frame.getGlobalSearchBar().performSearch());
}
@Subscribe
public void listen(EntryRemovedEvent removedEntryEvent) {
// IMO only used to update the status (found X entries)
- frame.getGlobalSearchBar().performSearch();
+ DefaultTaskExecutor.runInJavaFXThread(() -> frame.getGlobalSearchBar().performSearch());
}
}
From dd537702493917ca5fcdc3aeb3046c11caea06ce Mon Sep 17 00:00:00 2001
From: Galileo Sartor
Date: Sun, 27 Jan 2019 13:05:12 +0100
Subject: [PATCH 15/20] Fix preferences path: use _JAVA_OPTIONS
---
snap/snapcraft.yaml | 3 ++-
1 file changed, 2 insertions(+), 1 deletion(-)
diff --git a/snap/snapcraft.yaml b/snap/snapcraft.yaml
index 6873178bf86..cdc75820ea6 100644
--- a/snap/snapcraft.yaml
+++ b/snap/snapcraft.yaml
@@ -12,13 +12,14 @@ apps:
jabref:
command: desktop-launch java -jar $SNAP/jar/JabRef-$SNAP_VERSION.jar
environment:
- JAVA_OPTS: "-Djava.util.prefs.systemRoot=$SNAP_USER_DATA/.java -Djava.util.prefs.userRoot=$SNAP_USER_DATA/.java/.userPrefs"
+ _JAVA_OPTIONS: "-Djava.util.prefs.systemRoot=$SNAP_USER_DATA/.java/etc/.java -Djava.util.prefs.userRoot=$SNAP_USER_DATA/.java/.userPrefs"
plugs:
- desktop
- desktop-legacy
- wayland
- unity7
- home
+ - opengl
- network-bind
parts:
From 095b70b7f052a1a6929a75ba18e8b82fd38e99c8 Mon Sep 17 00:00:00 2001
From: "dependabot[bot]"
Date: Mon, 28 Jan 2019 08:38:22 +0100
Subject: [PATCH 16/20] Bump checkstyle from 8.16 to 8.17 (#4620)
Bumps [checkstyle](https://github.com/checkstyle/checkstyle) from 8.16 to 8.17.
- [Release notes](https://github.com/checkstyle/checkstyle/releases)
- [Commits](https://github.com/checkstyle/checkstyle/compare/checkstyle-8.16...checkstyle-8.17)
Signed-off-by: dependabot[bot]
---
build.gradle | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/build.gradle b/build.gradle
index 94a5e380cab..b3f68a91c8c 100644
--- a/build.gradle
+++ b/build.gradle
@@ -181,7 +181,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 {
From fbf1cc9a406da6018619887b73506a89e1535f14 Mon Sep 17 00:00:00 2001
From: Galileo Sartor
Date: Mon, 28 Jan 2019 18:13:56 +0100
Subject: [PATCH 17/20] snap: disable tests build, add removable media and
specify architectures (#4619)
* snap: disable tests build, add removable media and specify architectures
* Move to gtk2 fixes the dialogs
* Add snap ignores to .gitignore
* Add source-type: git to enable submodules
---
.gitignore | 8 ++++++++
snap/snapcraft.yaml | 14 ++++++++++----
2 files changed, 18 insertions(+), 4 deletions(-)
diff --git a/.gitignore b/.gitignore
index 7c7850841ea..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/
diff --git a/snap/snapcraft.yaml b/snap/snapcraft.yaml
index cdc75820ea6..b26f84fef0d 100644
--- a/snap/snapcraft.yaml
+++ b/snap/snapcraft.yaml
@@ -1,18 +1,22 @@
name: jabref
version: "git"
version-script: cat build.gradle | grep "^version =" | cut -d'"' -f2
-#icon: snap/gui/icon.png
+#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: "-Djava.util.prefs.systemRoot=$SNAP_USER_DATA/.java/etc/.java -Djava.util.prefs.userRoot=$SNAP_USER_DATA/.java/.userPrefs"
+ _JAVA_OPTIONS: "-Duser.home=$SNAP_USER_DATA"
plugs:
- desktop
- desktop-legacy
@@ -21,15 +25,17 @@ apps:
- 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]
+ gradle-options: [snapJar, -xtest]
gradle-output-dir: 'build/releases'
- after: [desktop-gtk3]
+ after: [desktop-gtk2]
From 33b35f7f65ef0fab14fcf866d48ce8daade7adb5 Mon Sep 17 00:00:00 2001
From: "dependabot[bot]"
Date: Thu, 31 Jan 2019 08:44:05 +0100
Subject: [PATCH 18/20] Bump wiremock from 2.20.0 to 2.21.0 (#4623)
Bumps [wiremock](https://github.com/tomakehurst/wiremock) from 2.20.0 to 2.21.0.
- [Release notes](https://github.com/tomakehurst/wiremock/releases)
- [Changelog](https://github.com/tomakehurst/wiremock/blob/master/release-settings.gradle)
- [Commits](https://github.com/tomakehurst/wiremock/compare/2.20.0...2.21.0)
Signed-off-by: dependabot[bot]
---
build.gradle | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/build.gradle b/build.gradle
index b3f68a91c8c..9d93378e772 100644
--- a/build.gradle
+++ b/build.gradle
@@ -171,7 +171,7 @@ dependencies {
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 'com.github.tomakehurst:wiremock:2.21.0'
testCompile 'org.assertj:assertj-swing-junit:3.8.0'
testCompile 'org.reflections:reflections:0.9.11'
testCompile 'org.xmlunit:xmlunit-core:2.6.2'
From 769ebd19e7ed68a511817aa2bc12c2bcdf149446 Mon Sep 17 00:00:00 2001
From: Chelsey Ong <30564248+chelseyong@users.noreply.github.com>
Date: Thu, 31 Jan 2019 16:46:20 +0700
Subject: [PATCH 19/20] Fix preview style configuration (#4613)
* Modify prefsTab to save the selected preview style in preferences
* Fix codacy by changing to equals
---
src/main/java/org/jabref/gui/PreviewPanel.java | 9 +++++++--
.../java/org/jabref/gui/preferences/PreviewPrefsTab.java | 3 +++
2 files changed, 10 insertions(+), 2 deletions(-)
diff --git a/src/main/java/org/jabref/gui/PreviewPanel.java b/src/main/java/org/jabref/gui/PreviewPanel.java
index bffcb4e2bd3..95323116271 100644
--- a/src/main/java/org/jabref/gui/PreviewPanel.java
+++ b/src/main/java/org/jabref/gui/PreviewPanel.java
@@ -62,6 +62,7 @@ public class PreviewPanel extends ScrollPane implements SearchQueryHighlightList
private final KeyBindingRepository keyBindingRepository;
private String previewStyle;
+ private CitationStyle citationStyle;
private final String defaultPreviewStyle = "Preview";
private Optional basePanel = Optional.empty();
@@ -224,13 +225,14 @@ 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);
+ .ifPresent(cs -> {
+ citationStyle = cs;
if (!init) {
basePanel.get().output(Localization.lang("Preview style changed to: %0", citationStyle.getTitle()));
}
@@ -299,6 +301,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(() -> {
diff --git a/src/main/java/org/jabref/gui/preferences/PreviewPrefsTab.java b/src/main/java/org/jabref/gui/preferences/PreviewPrefsTab.java
index 071aa23cd0a..76fc314f1b8 100644
--- a/src/main/java/org/jabref/gui/preferences/PreviewPrefsTab.java
+++ b/src/main/java/org/jabref/gui/preferences/PreviewPrefsTab.java
@@ -264,6 +264,9 @@ public void storeSettings() {
.withPreviewCycle(styles)
.withPreviewStyle(layout.getText().replace("\n", "__NEWLINE__"))
.build();
+ if (!chosen.getSelectionModel().isEmpty()) {
+ previewPreferences = previewPreferences.getBuilder().withPreviewCyclePosition(chosen.getSelectionModel().getSelectedIndex()).build();
+ }
Globals.prefs.storePreviewPreferences(previewPreferences);
// update preview
From 629fcc424f7f7dce419b7c1ab3d8984a84c902e5 Mon Sep 17 00:00:00 2001
From: Christoph
Date: Fri, 1 Feb 2019 16:08:00 +0100
Subject: [PATCH 20/20] Fix NPE and not on FX Thread in PreviewPrefs Tabs
(#4624)
* Fix NPE and not on FX Thread in PreviewPrefs Tabs
Remove obsolete swing stuff
Create proper javafx binding
Fixes #4621
Fixes #4622
Fix another issue where the Preview stlye is not set correctly
* fix checkstyle
Signed-off-by: Siedlerchr
* fix copying of entry preview
* prevent divide by zero excpetion
* Pass task executor as variable
Use Background Task
add error message
improve binding
* remove empty line
---
src/main/java/org/jabref/gui/JabRefFrame.java | 27 ++--
.../java/org/jabref/gui/PreviewPanel.java | 36 +++--
.../gui/actions/ShowPreferencesAction.java | 8 +-
.../gui/preferences/PreferencesDialog.java | 53 ++++---
.../gui/preferences/PreviewPrefsTab.java | 145 +++++++-----------
.../preferences/PreviewPreferences.java | 16 +-
src/main/resources/l10n/JabRef_en.properties | 2 +
7 files changed, 134 insertions(+), 153 deletions(-)
diff --git a/src/main/java/org/jabref/gui/JabRefFrame.java b/src/main/java/org/jabref/gui/JabRefFrame.java
index b1872641c36..76e14c8e6ce 100644
--- a/src/main/java/org/jabref/gui/JabRefFrame.java
+++ b/src/main/java/org/jabref/gui/JabRefFrame.java
@@ -923,24 +923,23 @@ 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(),
+ new SeparatorMenuItem(),
- factory.createMenuItem(StandardActions.SETUP_GENERAL_FIELDS, new SetupGeneralFieldsAction()),
- factory.createMenuItem(StandardActions.MANAGE_CUSTOM_IMPORTS, new ManageCustomImportsAction()),
- factory.createMenuItem(StandardActions.MANAGE_CUSTOM_EXPORTS, new ManageCustomExportsAction()),
- factory.createMenuItem(StandardActions.MANAGE_EXTERNAL_FILETYPES, new EditExternalFileTypesAction()),
- factory.createMenuItem(StandardActions.MANAGE_JOURNALS, new ManageJournalsAction()),
- factory.createMenuItem(StandardActions.CUSTOMIZE_KEYBINDING, new CustomizeKeyBindingAction()),
- factory.createMenuItem(StandardActions.MANAGE_PROTECTED_TERMS, new ManageProtectedTermsAction(this, Globals.protectedTermsLoader)),
+ factory.createMenuItem(StandardActions.SETUP_GENERAL_FIELDS, new SetupGeneralFieldsAction()),
+ factory.createMenuItem(StandardActions.MANAGE_CUSTOM_IMPORTS, new ManageCustomImportsAction()),
+ factory.createMenuItem(StandardActions.MANAGE_CUSTOM_EXPORTS, new ManageCustomExportsAction()),
+ factory.createMenuItem(StandardActions.MANAGE_EXTERNAL_FILETYPES, new EditExternalFileTypesAction()),
+ factory.createMenuItem(StandardActions.MANAGE_JOURNALS, new ManageJournalsAction()),
+ factory.createMenuItem(StandardActions.CUSTOMIZE_KEYBINDING, new CustomizeKeyBindingAction()),
+ factory.createMenuItem(StandardActions.MANAGE_PROTECTED_TERMS, new ManageProtectedTermsAction(this, Globals.protectedTermsLoader)),
- new SeparatorMenuItem(),
+ new SeparatorMenuItem(),
- 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_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)));
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 95323116271..ff8d6db01bd 100644
--- a/src/main/java/org/jabref/gui/PreviewPanel.java
+++ b/src/main/java/org/jabref/gui/PreviewPanel.java
@@ -94,10 +94,10 @@ public PreviewPanel(BasePanel panel, BibDatabaseContext databaseContext, KeyBind
this.keyBindingRepository = keyBindingRepository;
fileHandler = new NewDroppedFileHandler(dialogService, databaseContext, externalFileTypes,
- Globals.prefs.getFilePreferences(),
+ Globals.prefs.getFilePreferences(),
Globals.prefs.getImportFormatPreferences(),
Globals.prefs.getUpdateFieldPreferences(),
- Globals.getFileUpdateMonitor());
+ Globals.getFileUpdateMonitor());
// Set up scroll pane for preview pane
setFitToHeight(true);
@@ -231,19 +231,19 @@ private void updateLayout(PreviewPreferences previewPreferences, boolean init) {
if (CitationStyle.isCitationStyleFile(style)) {
layout = Optional.empty();
CitationStyle.createCitationStyleFromFile(style)
- .ifPresent(cs -> {
- citationStyle = cs;
- 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")));
}
}
@@ -301,7 +301,7 @@ public void update() {
.doLayout(entry, databaseContext.getDatabase())));
setPreviewLabel(sb.toString());
} else if (basePanel.isPresent() && bibEntry.isPresent()) {
- if (citationStyle != null && !previewStyle.equals(defaultPreviewStyle)) {
+ if ((citationStyle != null) && !previewStyle.equals(defaultPreviewStyle)) {
basePanel.get().getCitationStyleCache().setCitationStyle(citationStyle);
}
Future> citationStyleWorker = BackgroundTask
@@ -368,11 +368,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/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/preferences/PreferencesDialog.java b/src/main/java/org/jabref/gui/preferences/PreferencesDialog.java
index a2571e4e5fd..25837b9b62c 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));
@@ -111,8 +112,8 @@ private void construct() {
});
tabsList.getSelectionModel().selectFirst();
new ViewModelListCellFactory()
- .withText(PrefsTab::getTabName)
- .install(tabsList);
+ .withText(PrefsTab::getTabName)
+ .install(tabsList);
VBox buttonContainer = new VBox();
buttonContainer.setAlignment(Pos.BOTTOM_LEFT);
@@ -132,21 +133,19 @@ private void construct() {
resetPreferences.setOnAction(e -> resetPreferences());
resetPreferences.setMaxWidth(Double.MAX_VALUE);
buttonContainer.getChildren().addAll(
- importPreferences,
- exportPreferences,
- showPreferences,
- resetPreferences
- );
+ importPreferences,
+ exportPreferences,
+ showPreferences,
+ resetPreferences);
VBox spacer = new VBox();
spacer.setPrefHeight(10.0);
VBox.setVgrow(tabsList, Priority.ALWAYS);
VBox.setVgrow(spacer, Priority.SOMETIMES);
vBox.getChildren().addAll(
- tabsList,
- spacer,
- buttonContainer
- );
+ tabsList,
+ spacer,
+ buttonContainer);
container.setLeft(vBox);
@@ -155,16 +154,16 @@ private void construct() {
private void resetPreferences() {
boolean resetPreferencesConfirmed = dialogService.showConfirmationDialogAndWait(
- Localization.lang("Reset preferences"),
- Localization.lang("Are you sure you want to reset all settings to default values?"),
- Localization.lang("Reset preferences"),
- Localization.lang("Cancel"));
+ Localization.lang("Reset preferences"),
+ Localization.lang("Are you sure you want to reset all settings to default values?"),
+ Localization.lang("Reset preferences"),
+ Localization.lang("Cancel"));
if (resetPreferencesConfirmed) {
try {
prefs.clear();
dialogService.showWarningDialogAndWait(Localization.lang("Reset preferences"),
- Localization.lang("You must restart JabRef for this to come into effect."));
+ Localization.lang("You must restart JabRef for this to come into effect."));
} catch (BackingStoreException ex) {
LOGGER.error("Error while resetting preferences", ex);
dialogService.showErrorDialogAndWait(Localization.lang("Reset preferences"), ex);
@@ -175,9 +174,9 @@ private void resetPreferences() {
private void importPreferences() {
FileDialogConfiguration fileDialogConfiguration = new FileDialogConfiguration.Builder()
- .addExtensionFilter(StandardFileType.XML)
- .withDefaultExtension(StandardFileType.XML)
- .withInitialDirectory(prefs.setLastPreferencesExportPath()).build();
+ .addExtensionFilter(StandardFileType.XML)
+ .withDefaultExtension(StandardFileType.XML)
+ .withInitialDirectory(prefs.setLastPreferencesExportPath()).build();
dialogService.showFileOpenDialog(fileDialogConfiguration).ifPresent(file -> {
try {
@@ -185,7 +184,7 @@ private void importPreferences() {
updateAfterPreferenceChanges();
dialogService.showWarningDialogAndWait(Localization.lang("Import preferences"),
- Localization.lang("You must restart JabRef for this to come into effect."));
+ Localization.lang("You must restart JabRef for this to come into effect."));
} catch (JabRefException ex) {
LOGGER.error("Error while importing preferences", ex);
dialogService.showErrorDialogAndWait(Localization.lang("Import preferences"), ex);
@@ -230,10 +229,10 @@ public void setValues() {
private void exportPreferences() {
FileDialogConfiguration fileDialogConfiguration = new FileDialogConfiguration.Builder()
- .addExtensionFilter(StandardFileType.XML)
- .withDefaultExtension(StandardFileType.XML)
- .withInitialDirectory(prefs.setLastPreferencesExportPath())
- .build();
+ .addExtensionFilter(StandardFileType.XML)
+ .withDefaultExtension(StandardFileType.XML)
+ .withInitialDirectory(prefs.setLastPreferencesExportPath())
+ .build();
dialogService.showFileSaveDialog(fileDialogConfiguration)
.ifPresent(exportFile -> {
diff --git a/src/main/java/org/jabref/gui/preferences/PreviewPrefsTab.java b/src/main/java/org/jabref/gui/preferences/PreviewPrefsTab.java
index 76fc314f1b8..5ace5352e0a 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