diff --git a/src/main/java/org/jabref/JabRefGUI.java b/src/main/java/org/jabref/JabRefGUI.java index e1e55ea0fe8..7a3acdedecf 100644 --- a/src/main/java/org/jabref/JabRefGUI.java +++ b/src/main/java/org/jabref/JabRefGUI.java @@ -20,6 +20,7 @@ import org.jabref.gui.AbstractView; import org.jabref.gui.BasePanel; +import org.jabref.gui.DialogService; import org.jabref.gui.FXDialogService; import org.jabref.gui.GUIGlobals; import org.jabref.gui.IconTheme; @@ -51,12 +52,14 @@ public class JabRefGUI { private final boolean isBlank; private final List failed = new ArrayList<>(); private final List toOpenTab = new ArrayList<>(); + private final DialogService dialogService; private final String focusedFile; public JabRefGUI(Stage mainStage, List argsDatabases, boolean isBlank) { this.bibDatabases = argsDatabases; this.isBlank = isBlank; + this.dialogService = new FXDialogService(mainStage); // passed file (we take the first one) should be focused focusedFile = argsDatabases.stream().findFirst().flatMap(ParserResult::getFile).map(File::getAbsolutePath) @@ -87,7 +90,7 @@ private void openWindow(Stage mainStage) { // If the option is enabled, open the last edited libraries, if any. if (!isBlank && Globals.prefs.getBoolean(JabRefPreferences.OPEN_LAST_EDITED)) { - openLastEditedDatabases(mainStage); + openLastEditedDatabases(); } GUIGlobals.init(); @@ -159,12 +162,11 @@ private void openWindow(Stage mainStage) { }); for (ParserResult pr : failed) { - String message = "" + Localization.lang("Error opening file '%0'.", pr.getFile().get().getName()) - + "

" - + pr.getErrorMessage() + ""; + String message = Localization.lang("Error opening file '%0'.", pr.getFile().get().getName()) + "\n" + + pr.getErrorMessage(); + + dialogService.showErrorDialogAndWait(Localization.lang("Error opening file"), message); - JOptionPane.showMessageDialog(null, message, Localization.lang("Error opening file"), - JOptionPane.ERROR_MESSAGE); } // Display warnings, if any @@ -191,7 +193,7 @@ private void openWindow(Stage mainStage) { LOGGER.debug("Finished adding panels"); } - private void openLastEditedDatabases(Stage mainStage) { + private void openLastEditedDatabases() { if (Globals.prefs.get(JabRefPreferences.LAST_EDITED) == null) { return; } @@ -206,7 +208,7 @@ private void openLastEditedDatabases(Stage mainStage) { } if (BackupManager.checkForBackupFile(dbFile.toPath())) { - BackupUIManager.showRestoreBackupDialog(new FXDialogService(mainStage), dbFile.toPath()); + BackupUIManager.showRestoreBackupDialog(dialogService, dbFile.toPath()); } ParserResult parsedDatabase = OpenDatabase.loadDatabase(fileName, @@ -264,11 +266,11 @@ private void setLookAndFeel() { // also set system l&f as default Globals.prefs.put(JabRefPreferences.WIN_LOOK_AND_FEEL, systemLookFeel); // notify the user - JOptionPane.showMessageDialog(null, - Localization - .lang("Unable to find the requested look and feel and thus the default one is used."), - Localization.lang("Warning"), JOptionPane.WARNING_MESSAGE); + LOGGER.warn("Unable to find requested look and feel", e); + dialogService.showWarningDialogAndWait(Localization.lang("Warning"), + Localization.lang("Unable to find the requested look and feel and thus the default one is used.")); + } } diff --git a/src/main/java/org/jabref/gui/BasePanel.java b/src/main/java/org/jabref/gui/BasePanel.java index 4af3c52fca1..8d63b8f60fe 100644 --- a/src/main/java/org/jabref/gui/BasePanel.java +++ b/src/main/java/org/jabref/gui/BasePanel.java @@ -84,7 +84,6 @@ import org.jabref.gui.undo.UndoableRemoveEntry; import org.jabref.gui.util.DefaultTaskExecutor; import org.jabref.gui.util.FileDialogConfiguration; -import org.jabref.gui.util.component.CheckBoxMessage; import org.jabref.gui.worker.AbstractWorker; import org.jabref.gui.worker.CallBack; import org.jabref.gui.worker.CitationStyleToClipboardWorker; @@ -420,15 +419,16 @@ public void run() { // if we're going to override some cite keys warn the user about it } else if (Globals.prefs.getBoolean(JabRefPreferences.WARN_BEFORE_OVERWRITING_KEY)) { if (entries.parallelStream().anyMatch(BibEntry::hasCiteKey)) { - CheckBoxMessage cbm = new CheckBoxMessage( + + boolean overwriteKeysPressed = dialogService.showConfirmationDialogWithOptOutAndWait(Localization.lang("Overwrite keys"), Localization.lang("One or more keys will be overwritten. Continue?"), - Localization.lang("Disable this confirmation dialog"), false); - final int answer = JOptionPane.showConfirmDialog(null, cbm, - Localization.lang("Overwrite keys"), JOptionPane.YES_NO_OPTION); - Globals.prefs.putBoolean(JabRefPreferences.WARN_BEFORE_OVERWRITING_KEY, !cbm.isSelected()); + Localization.lang("Overwrite keys"), + Localization.lang("Cancel"), + Localization.lang("Disable this confirmation dialog"), + optOut -> Globals.prefs.putBoolean(JabRefPreferences.WARN_BEFORE_OVERWRITING_KEY, !optOut)); // The user doesn't want to overide cite keys - if (answer == JOptionPane.NO_OPTION) { + if (!overwriteKeysPressed) { canceled = true; return; } @@ -525,7 +525,7 @@ public void update() { actions.put(Actions.OPEN_URL, new OpenURLAction()); - actions.put(Actions.MERGE_WITH_FETCHED_ENTRY, new MergeWithFetchedEntryAction(this)); + actions.put(Actions.MERGE_WITH_FETCHED_ENTRY, new MergeWithFetchedEntryAction(this, frame.getDialogService())); actions.put(Actions.REPLACE_ALL, (BaseAction) () -> { final ReplaceStringDialog rsd = new ReplaceStringDialog(frame); @@ -616,7 +616,7 @@ public void update() { actions.put(Actions.REMOVE_FROM_GROUP, new GroupAddRemoveDialog(this, false, false)); actions.put(Actions.MOVE_TO_GROUP, new GroupAddRemoveDialog(this, true, true)); - actions.put(Actions.DOWNLOAD_FULL_TEXT, new FindFullTextAction(this)); + actions.put(Actions.DOWNLOAD_FULL_TEXT, new FindFullTextAction(frame.getDialogService(), this)); } /** @@ -925,6 +925,7 @@ private boolean saveDatabase(File file, boolean selectedOnly, Charset enc, new String[] {Localization.lang("Save"), tryDiff, Localization.lang("Cancel")}, tryDiff); if (answer == JOptionPane.NO_OPTION) { + // The user wants to use another encoding. Object choice = JOptionPane.showInputDialog(null, Localization.lang("Select encoding"), SAVE_DATABASE, JOptionPane.QUESTION_MESSAGE, null, Encodings.ENCODINGS_DISPLAYNAMES, enc); diff --git a/src/main/java/org/jabref/gui/DialogService.java b/src/main/java/org/jabref/gui/DialogService.java index 1c177988d08..5900555e656 100644 --- a/src/main/java/org/jabref/gui/DialogService.java +++ b/src/main/java/org/jabref/gui/DialogService.java @@ -1,6 +1,7 @@ package org.jabref.gui; import java.nio.file.Path; +import java.util.Collection; import java.util.List; import java.util.Optional; import java.util.function.Consumer; @@ -9,7 +10,9 @@ import javafx.print.PrinterJob; import javafx.scene.control.Alert; import javafx.scene.control.ButtonType; +import javafx.scene.control.ChoiceDialog; import javafx.scene.control.DialogPane; +import javafx.scene.control.TextInputDialog; import org.jabref.gui.util.DirectoryDialogConfiguration; import org.jabref.gui.util.FileDialogConfiguration; @@ -22,6 +25,14 @@ */ public interface DialogService { + /** + * This will create and display new {@link ChoiceDialog} of type T with a default choice and a collection of possible choices + */ + Optional showChoiceDialogAndWait(String title, String content, String okButtonLabel, T defaultChoice, Collection choices); + + /** + * This will create and display new {@link TextInputDialog} with a text fields to enter data + */ Optional showInputDialogAndWait(String title, String content); /** @@ -119,7 +130,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. @@ -131,8 +142,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 @@ -142,7 +153,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} @@ -224,4 +235,5 @@ Optional showCustomButtonDialogAndWait(Alert.AlertType type, String * @return false if the user opts to cancel printing */ boolean showPrintDialog(PrinterJob job); + } diff --git a/src/main/java/org/jabref/gui/EntryTypeDialog.java b/src/main/java/org/jabref/gui/EntryTypeDialog.java index 133da8b8d11..5a0f7eb7b8a 100644 --- a/src/main/java/org/jabref/gui/EntryTypeDialog.java +++ b/src/main/java/org/jabref/gui/EntryTypeDialog.java @@ -20,7 +20,6 @@ import javax.swing.JComboBox; import javax.swing.JComponent; import javax.swing.JLabel; -import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JTextField; import javax.swing.SwingUtilities; @@ -331,13 +330,13 @@ protected void done() { dispose(); } else if (searchID.trim().isEmpty()) { - JOptionPane.showMessageDialog(null, Localization.lang("The given search ID was empty."), Localization.lang("Empty search ID"), JOptionPane.WARNING_MESSAGE); + frame.getDialogService().showWarningDialogAndWait(Localization.lang("Empty search ID"), + Localization.lang("The given search ID was empty.")); } else if (!fetcherException) { - JOptionPane.showMessageDialog(null, Localization.lang("Fetcher '%0' did not find an entry for id '%1'.", fetcher.getName(), searchID) + "\n" + fetcherExceptionMessage, Localization.lang("No files found."), JOptionPane.WARNING_MESSAGE); + frame.getDialogService().showErrorDialogAndWait(Localization.lang("No files found.", + Localization.lang("Fetcher '%0' did not find an entry for id '%1'.", fetcher.getName(), searchID) + "\n" + fetcherExceptionMessage)); } else { - JOptionPane.showMessageDialog(null, - Localization.lang("Error while fetching from %0", fetcher.getName()) + "." + "\n" + fetcherExceptionMessage, - Localization.lang("Error"), JOptionPane.ERROR_MESSAGE); + frame.getDialogService().showErrorDialogAndWait(Localization.lang("Error"), Localization.lang("Error while fetching from %0", fetcher.getName()) + "." + "\n" + fetcherExceptionMessage); } fetcherWorker = new FetcherWorker(); SwingUtilities.invokeLater(() -> { diff --git a/src/main/java/org/jabref/gui/FXDialogService.java b/src/main/java/org/jabref/gui/FXDialogService.java index 41d5ba1aa3e..db753727612 100644 --- a/src/main/java/org/jabref/gui/FXDialogService.java +++ b/src/main/java/org/jabref/gui/FXDialogService.java @@ -2,6 +2,7 @@ import java.io.File; import java.nio.file.Path; +import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Optional; @@ -17,6 +18,7 @@ import javafx.scene.control.ButtonBar; import javafx.scene.control.ButtonType; import javafx.scene.control.CheckBox; +import javafx.scene.control.ChoiceDialog; import javafx.scene.control.DialogPane; import javafx.scene.control.TextInputDialog; import javafx.scene.layout.Region; @@ -66,7 +68,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(); @@ -75,6 +77,7 @@ private static FXDialog createDialogWithOptOut(AlertType type, String title, Str // Create a new dialog pane that has a checkbox instead of the hide/show details button // Use the supplied callback for the action of the checkbox alert.setDialogPane(new DialogPane() { + @Override protected Node createDetailsButton() { CheckBox optOut = new CheckBox(); @@ -97,6 +100,17 @@ protected Node createDetailsButton() { return alert; } + @Override + public Optional showChoiceDialogAndWait(String title, String content, String okButtonLabel, T defaultChoice, Collection choices) { + ChoiceDialog choiceDialog = new ChoiceDialog<>(defaultChoice, choices); + ButtonType okButtonType = new ButtonType(okButtonLabel, ButtonBar.ButtonData.OK_DONE); + choiceDialog.getDialogPane().getButtonTypes().setAll(ButtonType.CANCEL, okButtonType); + choiceDialog.setHeaderText(title); + choiceDialog.setContentText(content); + return choiceDialog.showAndWait(); + + } + @Override public Optional showInputDialogAndWait(String title, String content) { TextInputDialog inputDialog = new TextInputDialog(); @@ -160,7 +174,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); @@ -170,7 +184,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(); @@ -178,8 +192,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); diff --git a/src/main/java/org/jabref/gui/JabRefFrame.java b/src/main/java/org/jabref/gui/JabRefFrame.java index 709b695e075..491ec9fb98e 100644 --- a/src/main/java/org/jabref/gui/JabRefFrame.java +++ b/src/main/java/org/jabref/gui/JabRefFrame.java @@ -570,7 +570,7 @@ public boolean quit() { private void initLayout() { setProgressBarVisible(false); - pushApplications = new PushToApplications(); + pushApplications = new PushToApplications(this.getDialogService()); BorderPane head = new BorderPane(); head.setTop(createMenu()); @@ -670,7 +670,7 @@ private Node createToolbar() { HBox rightSide = new HBox ( factory.createIconButton(StandardActions.NEW_ENTRY, new NewEntryAction(this, BiblatexEntryTypes.ARTICLE)), factory.createIconButton(StandardActions.DELETE_ENTRY, new EditAction(Actions.DELETE)), - + factory.createIconButton(StandardActions.UNDO, new OldDatabaseCommandWrapper(Actions.UNDO, this, Globals.stateManager)), factory.createIconButton(StandardActions.REDO, new OldDatabaseCommandWrapper(Actions.REDO, this, Globals.stateManager)), factory.createIconButton(StandardActions.CUT, new EditAction(Actions.CUT)), diff --git a/src/main/java/org/jabref/gui/actions/ActionFactory.java b/src/main/java/org/jabref/gui/actions/ActionFactory.java index 915bb9b3ee4..38a7f99ddee 100644 --- a/src/main/java/org/jabref/gui/actions/ActionFactory.java +++ b/src/main/java/org/jabref/gui/actions/ActionFactory.java @@ -16,7 +16,7 @@ */ public class ActionFactory { - private KeyBindingRepository keyBindingRepository; + private final KeyBindingRepository keyBindingRepository; public ActionFactory(KeyBindingRepository keyBindingRepository) { this.keyBindingRepository = Objects.requireNonNull(keyBindingRepository); diff --git a/src/main/java/org/jabref/gui/actions/CleanupAction.java b/src/main/java/org/jabref/gui/actions/CleanupAction.java index 0c23296cd6b..7382d4d076e 100644 --- a/src/main/java/org/jabref/gui/actions/CleanupAction.java +++ b/src/main/java/org/jabref/gui/actions/CleanupAction.java @@ -12,7 +12,6 @@ import org.jabref.gui.undo.NamedCompound; import org.jabref.gui.undo.UndoableFieldChange; import org.jabref.gui.util.DefaultTaskExecutor; -import org.jabref.gui.util.component.CheckBoxMessage; import org.jabref.gui.worker.AbstractWorker; import org.jabref.logic.cleanup.CleanupPreset; import org.jabref.logic.cleanup.CleanupWorker; @@ -73,15 +72,15 @@ public void run() { cleanupPreset.storeInPreferences(preferences); if (cleanupPreset.isRenamePDF() && Globals.prefs.getBoolean(JabRefPreferences.ASK_AUTO_NAMING_PDFS_AGAIN)) { - CheckBoxMessage cbm = new CheckBoxMessage( + + boolean autogeneratePressed = dialogService.showConfirmationDialogWithOptOutAndWait(Localization.lang("Autogenerate PDF Names"), Localization.lang("Auto-generating PDF-Names does not support undo. Continue?"), - Localization.lang("Disable this confirmation dialog"), false); - int answer = JOptionPane.showConfirmDialog(null, cbm, Localization.lang("Autogenerate PDF Names"), - JOptionPane.YES_NO_OPTION); - if (cbm.isSelected()) { - Globals.prefs.putBoolean(JabRefPreferences.ASK_AUTO_NAMING_PDFS_AGAIN, false); - } - if (answer == JOptionPane.NO_OPTION) { + Localization.lang("Autogenerate PDF Names"), + Localization.lang("Cancel"), + Localization.lang("Disable this confirmation dialog"), + optOut -> Globals.prefs.putBoolean(JabRefPreferences.ASK_AUTO_NAMING_PDFS_AGAIN, !optOut)); + + if (!autogeneratePressed) { canceled = true; return; } @@ -117,15 +116,15 @@ public void update() { } String message; switch (modifiedEntriesCount) { - case 0: - message = Localization.lang("No entry needed a clean up"); - break; - case 1: - message = Localization.lang("One entry needed a clean up"); - break; - default: - message = Localization.lang("%0 entries needed a clean up", Integer.toString(modifiedEntriesCount)); - break; + case 0: + message = Localization.lang("No entry needed a clean up"); + break; + case 1: + message = Localization.lang("One entry needed a clean up"); + break; + default: + message = Localization.lang("%0 entries needed a clean up", Integer.toString(modifiedEntriesCount)); + break; } panel.output(message); } diff --git a/src/main/java/org/jabref/gui/actions/JabRefAction.java b/src/main/java/org/jabref/gui/actions/JabRefAction.java index 78793e9a206..d000f716040 100644 --- a/src/main/java/org/jabref/gui/actions/JabRefAction.java +++ b/src/main/java/org/jabref/gui/actions/JabRefAction.java @@ -10,13 +10,16 @@ */ class JabRefAction extends org.controlsfx.control.action.Action { + public JabRefAction(Action action, KeyBindingRepository keyBindingRepository) { super(action.getText()); action.getIcon() .ifPresent(icon -> setGraphic(icon.getGraphicNode())); action.getKeyBinding() .ifPresent(keyBinding -> setAccelerator(keyBindingRepository.getKeyCombination(keyBinding))); + setLongText(action.getDescription()); + } public JabRefAction(Action action, Command command, KeyBindingRepository keyBindingRepository) { diff --git a/src/main/java/org/jabref/gui/actions/MassSetFieldAction.java b/src/main/java/org/jabref/gui/actions/MassSetFieldAction.java index 24ca4064ff7..2d6e2a907db 100644 --- a/src/main/java/org/jabref/gui/actions/MassSetFieldAction.java +++ b/src/main/java/org/jabref/gui/actions/MassSetFieldAction.java @@ -20,7 +20,6 @@ import javax.swing.JComponent; import javax.swing.JDialog; import javax.swing.JFrame; -import javax.swing.JOptionPane; import javax.swing.JRadioButton; import javax.swing.JTextField; import javax.swing.undo.UndoableEdit; @@ -63,7 +62,6 @@ public class MassSetFieldAction extends SimpleCommand { private boolean canceled = true; private JCheckBox overwrite; - public MassSetFieldAction(JabRefFrame frame) { this.frame = frame; } @@ -98,8 +96,8 @@ private void createDialog() { } set.addChangeListener(e -> - // Entering a setText is only relevant if we are setting, not clearing: - textFieldSet.setEnabled(set.isSelected())); + // Entering a setText is only relevant if we are setting, not clearing: + textFieldSet.setEnabled(set.isSelected())); append.addChangeListener(e -> { // Text to append is only required if we are appending: @@ -109,12 +107,12 @@ private void createDialog() { }); clear.addChangeListener(e -> - // Overwrite protection makes no sense if we are clearing the field: - overwrite.setEnabled(!clear.isSelected() && !append.isSelected())); + // Overwrite protection makes no sense if we are clearing the field: + overwrite.setEnabled(!clear.isSelected() && !append.isSelected())); rename.addChangeListener(e -> - // Entering a setText is only relevant if we are renaming - textFieldRename.setEnabled(rename.isSelected())); + // Entering a setText is only relevant if we are renaming + textFieldRename.setEnabled(rename.isSelected())); overwrite = new JCheckBox(Localization.lang("Overwrite existing field values"), true); ButtonGroup bg = new ButtonGroup(); @@ -158,8 +156,9 @@ private void createDialog() { // Check that any field name is set String fieldText = (String) field.getSelectedItem(); if ((fieldText == null) || fieldText.trim().isEmpty()) { - JOptionPane.showMessageDialog(diag, Localization.lang("You must enter at least one field name"), "", - JOptionPane.ERROR_MESSAGE); + + frame.getDialogService().showErrorDialogAndWait(Localization.lang("You must enter at least one field name")); + return; // Do not close the dialog. } @@ -167,8 +166,9 @@ private void createDialog() { if (rename.isSelected()) { String[] fields = getFieldNames(fieldText); if (fields.length > 1) { - JOptionPane.showMessageDialog(diag, Localization.lang("You can only rename one field at a time"), - "", JOptionPane.ERROR_MESSAGE); + + frame.getDialogService().showErrorDialogAndWait(Localization.lang("You can only rename one field at a time")); + return; // Do not close the dialog. } } @@ -243,8 +243,7 @@ public void execute() { NamedCompound compoundEdit = new NamedCompound(Localization.lang("Set field")); if (rename.isSelected()) { if (fields.length > 1) { - JOptionPane.showMessageDialog(diag, Localization.lang("You can only rename one field at a time"), "", - JOptionPane.ERROR_MESSAGE); + frame.getDialogService().showErrorDialogAndWait(Localization.lang("You can only rename one field at a time")); return; // Do not close the dialog. } else { compoundEdit.addEdit(MassSetFieldAction.massRenameField(entryList, fields[0], textFieldRename.getText(), @@ -258,7 +257,7 @@ public void execute() { for (String field : fields) { compoundEdit.addEdit(MassSetFieldAction.massSetField(entryList, field, set.isSelected() ? toSet : null, - overwrite.isSelected())); + overwrite.isSelected())); } } compoundEdit.end(); diff --git a/src/main/java/org/jabref/gui/collab/ChangeScanner.java b/src/main/java/org/jabref/gui/collab/ChangeScanner.java index ae1b1355832..3ee754dae4d 100644 --- a/src/main/java/org/jabref/gui/collab/ChangeScanner.java +++ b/src/main/java/org/jabref/gui/collab/ChangeScanner.java @@ -7,7 +7,6 @@ import java.util.List; import java.util.Optional; -import javax.swing.JOptionPane; import javax.swing.SwingUtilities; import javax.swing.tree.DefaultMutableTreeNode; @@ -38,6 +37,7 @@ import org.slf4j.LoggerFactory; public class ChangeScanner implements Runnable { + private static final Logger LOGGER = LoggerFactory.getLogger(ChangeScanner.class); private final File file; @@ -94,8 +94,9 @@ public void displayResult(final DisplayResultCallback fup) { }); } else { - JOptionPane.showMessageDialog(null, Localization.lang("No actual changes found."), - Localization.lang("External changes"), JOptionPane.INFORMATION_MESSAGE); + frame.getDialogService().showInformationDialogAndWait(Localization.lang("External changes"), + Localization.lang("No actual changes found.")); + fup.scanResultsResolved(true); } } @@ -103,8 +104,11 @@ public void displayResult(final DisplayResultCallback fup) { private void storeTempDatabase() { JabRefExecutorService.INSTANCE.execute(() -> { try { - SavePreferences prefs = SavePreferences.loadForSaveFromPreferences(Globals.prefs).withMakeBackup(false) - .withEncoding(panel.getBibDatabaseContext().getMetaData().getEncoding() + SavePreferences prefs = SavePreferences.loadForSaveFromPreferences(Globals.prefs) + .withMakeBackup(false) + .withEncoding(panel.getBibDatabaseContext() + .getMetaData() + .getEncoding() .orElse(Globals.prefs.getDefaultEncoding())); BibDatabaseWriter databaseWriter = new BibtexDatabaseWriter<>(FileSaveSession::new); @@ -176,6 +180,7 @@ private ChangeViewModel createBibEntryDiff(BibEntryDiff diff) { @FunctionalInterface public interface DisplayResultCallback { + void scanResultsResolved(boolean resolved); } } diff --git a/src/main/java/org/jabref/gui/customentrytypes/EntryCustomizationDialog.java b/src/main/java/org/jabref/gui/customentrytypes/EntryCustomizationDialog.java index d8ef951c9f8..6fa48081af5 100644 --- a/src/main/java/org/jabref/gui/customentrytypes/EntryCustomizationDialog.java +++ b/src/main/java/org/jabref/gui/customentrytypes/EntryCustomizationDialog.java @@ -26,7 +26,6 @@ import javax.swing.JComponent; import javax.swing.JFrame; import javax.swing.JList; -import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.ListSelectionModel; import javax.swing.event.ListDataEvent; @@ -101,7 +100,7 @@ private void initGui() { List entryTypes = new ArrayList<>(); entryTypes.addAll(EntryTypes.getAllTypes(bibDatabaseMode)); - typeComp = new EntryTypeList(entryTypes, bibDatabaseMode); + typeComp = new EntryTypeList(frame.getDialogService(), entryTypes, bibDatabaseMode); typeComp.addListSelectionListener(this); typeComp.addAdditionActionListener(e -> typeComp.selectField(e.getActionCommand())); typeComp.addDefaultActionListener(new DefaultListener()); @@ -323,14 +322,14 @@ private void deleteType(String name) { if (type.isPresent() && (type.get() instanceof CustomEntryType)) { if (!EntryTypes.getStandardType(name, bibDatabaseMode).isPresent()) { - int reply = JOptionPane.showConfirmDialog - (null, Localization.lang("All entries of this " - + "type will be declared " - + "typeless. Continue?"), - Localization.lang("Delete custom format") + - " '" + StringUtil.capitalizeFirst(name) + '\'', JOptionPane.YES_NO_OPTION, - JOptionPane.WARNING_MESSAGE); - if (reply != JOptionPane.YES_OPTION) { + + boolean deleteCustomClicked = frame.getDialogService().showConfirmationDialogAndWait(Localization.lang("Delete custom format") + + " '" + StringUtil.capitalizeFirst(name) + '\'', Localization.lang("All entries of this " + + "type will be declared " + + "typeless. Continue?"), + Localization.lang("Delete custom format"), Localization.lang("Cancel")); + + if (!deleteCustomClicked) { return; } } diff --git a/src/main/java/org/jabref/gui/customentrytypes/EntryTypeList.java b/src/main/java/org/jabref/gui/customentrytypes/EntryTypeList.java index 5f27c6a14e8..e4550b529f1 100644 --- a/src/main/java/org/jabref/gui/customentrytypes/EntryTypeList.java +++ b/src/main/java/org/jabref/gui/customentrytypes/EntryTypeList.java @@ -7,11 +7,11 @@ import java.util.Optional; import javax.swing.JButton; -import javax.swing.JOptionPane; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import org.jabref.Globals; +import org.jabref.gui.DialogService; import org.jabref.logic.bibtexkeypattern.BibtexKeyGenerator; import org.jabref.logic.l10n.Localization; import org.jabref.model.EntryTypes; @@ -29,11 +29,14 @@ public class EntryTypeList extends FieldSetComponent implements ListSelectionLis private final JButton def = new JButton(Localization.lang("Default")); private final BibDatabaseMode mode; + private final DialogService dialogService; - /** Creates a new instance of EntryTypeList */ - public EntryTypeList(List fields, BibDatabaseMode mode) { - super(Localization.lang("Entry types"), fields, false, true); + /** Creates a new instance of EntryTypeList + * @param frame */ + public EntryTypeList(DialogService dialogService, List fields, BibDatabaseMode mode) { + super(Localization.lang("Entry types"), fields, fields, false, true); this.mode = mode; + this.dialogService = dialogService; con.gridx = 0; con.gridy = 2; @@ -61,15 +64,17 @@ protected void addField(String str) { Globals.prefs.getBoolean(JabRefPreferences.ENFORCE_LEGAL_BIBTEX_KEY)); if (!testString.equals(s) || (s.indexOf('&') >= 0)) { // Report error and exit. - JOptionPane.showMessageDialog(this, Localization.lang("Entry type names are not allowed to contain white space or the following " - + "characters") + ": # { } ~ , ^ &", - Localization.lang("Error"), JOptionPane.ERROR_MESSAGE); + + dialogService.showErrorDialogAndWait(Localization.lang("Error"), + Localization.lang("Entry type names are not allowed to contain white space or the following " + + "characters") + ": # { } ~ , ^ &"); + return; - } - else if ("comment".equalsIgnoreCase(s)) { + } else if ("comment".equalsIgnoreCase(s)) { // Report error and exit. - JOptionPane.showMessageDialog(this, Localization.lang("The name 'comment' cannot be used as an entry type name."), - Localization.lang("Error"), JOptionPane.ERROR_MESSAGE); + dialogService.showErrorDialogAndWait(Localization.lang("Error"), + Localization.lang("The name 'comment' cannot be used as an entry type name.")); + return; } addFieldUncritically(s); @@ -93,8 +98,8 @@ protected void removeSelected() { listModel.removeElementAt(selected[selected.length - 1 - i]); } else { // This shouldn't happen, since the Remove button should be disabled. - JOptionPane.showMessageDialog(null, Localization.lang("This entry type cannot be removed."), - Localization.lang("Remove entry type"), JOptionPane.ERROR_MESSAGE); + dialogService.showErrorDialogAndWait(Localization.lang("Remove entry type"), + Localization.lang("This entry type cannot be removed.")); } } } diff --git a/src/main/java/org/jabref/gui/exporter/ExportCommand.java b/src/main/java/org/jabref/gui/exporter/ExportCommand.java index c503960a631..22134072914 100644 --- a/src/main/java/org/jabref/gui/exporter/ExportCommand.java +++ b/src/main/java/org/jabref/gui/exporter/ExportCommand.java @@ -5,8 +5,6 @@ import java.util.List; import java.util.stream.Collectors; -import javax.swing.JOptionPane; - import javafx.stage.FileChooser; import org.jabref.Globals; @@ -50,9 +48,8 @@ public void execute() { Globals.exportFactory = ExporterFactory.create(Globals.prefs, Globals.journalAbbreviationLoader); FileDialogConfiguration fileDialogConfiguration = createExportFileChooser(Globals.exportFactory, Globals.prefs.get(JabRefPreferences.EXPORT_WORKING_DIRECTORY)); DialogService dialogService = frame.getDialogService(); - DefaultTaskExecutor.runInJavaFXThread(() -> - dialogService.showFileSaveDialog(fileDialogConfiguration) - .ifPresent(path -> export(path, fileDialogConfiguration.getSelectedExtensionFilter(), Globals.exportFactory.getExporters()))); + DefaultTaskExecutor.runInJavaFXThread(() -> dialogService.showFileSaveDialog(fileDialogConfiguration) + .ifPresent(path -> export(path, fileDialogConfiguration.getSelectedExtensionFilter(), Globals.exportFactory.getExporters()))); } private void export(Path file, FileChooser.ExtensionFilter selectedExtensionFilter, List exporters) { @@ -63,9 +60,13 @@ private void export(Path file, FileChooser.ExtensionFilter selectedExtensionFilt if (Files.exists(file)) { // Warn that the file exists: - if (JOptionPane.showConfirmDialog(null, + + boolean overwriteFilePressed = frame.getDialogService().showConfirmationDialogAndWait(Localization.lang("Export"), Localization.lang("'%0' exists. Overwrite file?", file.getFileName().toString()), - Localization.lang("Export"), JOptionPane.OK_CANCEL_OPTION) != JOptionPane.OK_OPTION) { + Localization.lang("Overwrite file"), + Localization.lang("Cancel")); + + if (!overwriteFilePressed) { return; } } @@ -82,8 +83,9 @@ private void export(Path file, FileChooser.ExtensionFilter selectedExtensionFilt // Set the global variable for this database's file directory before exporting, // so formatters can resolve linked files correctly. // (This is an ugly hack!) - Globals.prefs.fileDirForDatabase = frame.getCurrentBasePanel().getBibDatabaseContext() - .getFileDirectories(Globals.prefs.getFileDirectoryPreferences()); + Globals.prefs.fileDirForDatabase = frame.getCurrentBasePanel() + .getBibDatabaseContext() + .getFileDirectories(Globals.prefs.getFileDirectoryPreferences()); // Make sure we remember which filter was used, to set // the default for next time: @@ -100,8 +102,11 @@ public void run() { try { format.export(frame.getCurrentBasePanel().getBibDatabaseContext(), file, - frame.getCurrentBasePanel().getBibDatabaseContext().getMetaData().getEncoding() - .orElse(Globals.prefs.getDefaultEncoding()), + frame.getCurrentBasePanel() + .getBibDatabaseContext() + .getMetaData() + .getEncoding() + .orElse(Globals.prefs.getDefaultEncoding()), finEntries); } catch (Exception ex) { LOGGER.warn("Problem exporting", ex); @@ -123,9 +128,8 @@ public void update() { else { frame.output(Localization.lang("Could not save file.") + " - " + errorMessage); // Need to warn the user that saving failed! - JOptionPane.showMessageDialog(null, - Localization.lang("Could not save file.") + "\n" + errorMessage, - Localization.lang("Save library"), JOptionPane.ERROR_MESSAGE); + frame.getDialogService().showErrorDialogAndWait(Localization.lang("Save library"), Localization.lang("Could not save file.") + "\n" + errorMessage); + } } }; diff --git a/src/main/java/org/jabref/gui/exporter/SaveDatabaseAction.java b/src/main/java/org/jabref/gui/exporter/SaveDatabaseAction.java index 39434593f4b..06efe18baa9 100644 --- a/src/main/java/org/jabref/gui/exporter/SaveDatabaseAction.java +++ b/src/main/java/org/jabref/gui/exporter/SaveDatabaseAction.java @@ -9,6 +9,9 @@ import javax.swing.JOptionPane; import javax.swing.JTextArea; +import javafx.scene.control.Alert.AlertType; +import javafx.scene.control.ButtonType; + import org.jabref.Globals; import org.jabref.JabRefExecutorService; import org.jabref.gui.BasePanel; @@ -140,7 +143,9 @@ public void run() { // Save the database success = saveDatabase(panel.getBibDatabaseContext().getDatabaseFile().get(), false, - panel.getBibDatabaseContext().getMetaData().getEncoding() + panel.getBibDatabaseContext() + .getMetaData() + .getEncoding() .orElse(Globals.prefs.getDefaultEncoding())); panel.updateTimeStamp(); @@ -188,12 +193,10 @@ private boolean saveDatabase(File file, boolean selectedOnly, Charset encoding) panel.registerUndoableChanges(session); } catch (UnsupportedCharsetException ex) { - JOptionPane.showMessageDialog(null, - Localization.lang("Could not save file.") - + Localization.lang("Character encoding '%0' is not supported.", encoding.displayName()), - Localization.lang("Save library"), JOptionPane.ERROR_MESSAGE); - // FIXME: rethrow anti-pattern - throw new SaveException("rt"); + + frame.getDialogService().showErrorDialogAndWait(Localization.lang("Save library"), Localization.lang("Could not save file.") + + Localization.lang("Character encoding '%0' is not supported.", encoding.displayName())); + throw ex; } catch (SaveException ex) { if (ex == SaveException.FILE_LOCKED) { throw ex; @@ -208,8 +211,7 @@ private boolean saveDatabase(File file, boolean selectedOnly, Charset encoding) JOptionPane.showMessageDialog(null, Localization.lang("Could not save file.") + ".\n" + ex.getMessage(), Localization.lang("Save library"), JOptionPane.ERROR_MESSAGE); - // FIXME: rethrow anti-pattern - throw new SaveException("rt"); + throw ex; } // handle encoding problems @@ -224,46 +226,48 @@ private boolean saveDatabase(File file, boolean selectedOnly, Charset encoding) builder.add(ta).xy(3, 1); builder.add(Localization.lang("What do you want to do?")).xy(1, 3); String tryDiff = Localization.lang("Try different encoding"); + + //TODO: Old Swing panel int answer = JOptionPane.showOptionDialog(null, builder.getPanel(), Localization.lang("Save library"), JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE, null, new String[] {Localization.lang("Save"), tryDiff, Localization.lang("Cancel")}, tryDiff); if (answer == JOptionPane.NO_OPTION) { // The user wants to use another encoding. - Object choice = JOptionPane.showInputDialog(null, Localization.lang("Select encoding"), - Localization.lang("Save library"), JOptionPane.QUESTION_MESSAGE, null, - Encodings.ENCODINGS_DISPLAYNAMES, encoding); - if (choice == null) { - success = false; - } else { - Charset newEncoding = Charset.forName((String) choice); + Optional selectedCharSet = frame.getDialogService().showChoiceDialogAndWait(Localization.lang("Save library"), Localization.lang("Select encoding"), Localization.lang("Save library"), encoding, Encodings.getCharsets()); + + if (selectedCharSet.isPresent()) { + + Charset newEncoding = selectedCharSet.get(); return saveDatabase(file, selectedOnly, newEncoding); + } else { + success = false; } - } else if (answer == JOptionPane.CANCEL_OPTION) { - success = false; } - } - // backup file? - try { - if (success) { - session.commit(file.toPath()); - // Make sure to remember which encoding we used. - panel.getBibDatabaseContext().getMetaData().setEncoding(encoding, ChangePropagation.DO_NOT_POST_EVENT); - } else { - session.cancel(); - } - } catch (SaveException e) { - int ans = JOptionPane.showConfirmDialog(null, - Localization.lang("Save failed during backup creation") + ". " - + Localization.lang("Save without backup?"), - Localization.lang("Unable to create backup"), JOptionPane.YES_NO_OPTION); - if (ans == JOptionPane.YES_OPTION) { - session.setUseBackup(false); - session.commit(file.toPath()); - panel.getBibDatabaseContext().getMetaData().setEncoding(encoding, ChangePropagation.DO_NOT_POST_EVENT); - } else { - success = false; + // backup file? + try { + if (success) { + session.commit(file.toPath()); + // Make sure to remember which encoding we used. + panel.getBibDatabaseContext().getMetaData().setEncoding(encoding, ChangePropagation.DO_NOT_POST_EVENT); + } else { + session.cancel(); + } + } catch (SaveException e) { + LOGGER.debug("Problems saving during backup creationg", e); + boolean saveWithoutBackupClicked = frame.getDialogService().showConfirmationDialogAndWait(Localization.lang("Unable to create backup"), + Localization.lang("Save failed during backup creation") + ". " + Localization.lang("Save without backup?"), + Localization.lang("Save without backup"), Localization.lang("Cancel")); + + if (saveWithoutBackupClicked) { + session.setUseBackup(false); + + session.commit(file.toPath()); + panel.getBibDatabaseContext().getMetaData().setEncoding(encoding, ChangePropagation.DO_NOT_POST_EVENT); + } else { + success = false; + } } } @@ -288,7 +292,8 @@ public void saveAs() throws Exception { FileDialogConfiguration fileDialogConfiguration = new FileDialogConfiguration.Builder() .addExtensionFilter(FileType.BIBTEX_DB) .withDefaultExtension(FileType.BIBTEX_DB) - .withInitialDirectory(Globals.prefs.get(JabRefPreferences.WORKING_DIRECTORY)).build(); + .withInitialDirectory(Globals.prefs.get(JabRefPreferences.WORKING_DIRECTORY)) + .build(); DialogService dialogService = frame.getDialogService(); Optional path = dialogService.showFileSaveDialog(fileDialogConfiguration); if (path.isPresent()) { @@ -389,53 +394,56 @@ public boolean isCanceled() { private boolean checkExternalModification() { // Check for external modifications: if (panel.isUpdatedExternally()) { - String[] opts = new String[] {Localization.lang("Review changes"), Localization.lang("Save"), - Localization.lang("Cancel")}; - int answer = JOptionPane.showOptionDialog(null, - Localization.lang("File has been updated externally. " + "What do you want to do?"), - Localization.lang("File updated externally"), JOptionPane.YES_NO_CANCEL_OPTION, - JOptionPane.QUESTION_MESSAGE, null, opts, opts[0]); - - if (answer == JOptionPane.CANCEL_OPTION) { - canceled = true; - return true; - } else if (answer == JOptionPane.YES_OPTION) { - canceled = true; - - JabRefExecutorService.INSTANCE.execute(() -> { - - if (!FileBasedLock - .waitForFileLock(panel.getBibDatabaseContext().getDatabaseFile().get().toPath())) { - // TODO: GUI handling of the situation when the externally modified file keeps being locked. - LOGGER.error("File locked, this will be trouble."); - } - ChangeScanner scanner = new ChangeScanner(panel.frame(), panel, - panel.getBibDatabaseContext().getDatabaseFile().get(), panel.getTempFile()); - JabRefExecutorService.INSTANCE.executeInterruptableTaskAndWait(scanner); - if (scanner.changesFound()) { - scanner.displayResult(resolved -> { - if (resolved) { - panel.markExternalChangesAsResolved(); - DefaultTaskExecutor.runInJavaFXThread(() -> panel.getSidePaneManager().hide(SidePaneType.FILE_UPDATE_NOTIFICATION)); - } else { - canceled = true; - } - }); - } - }); - - return true; - } else { // User indicated to store anyway. - if (panel.getBibDatabaseContext().getMetaData().isProtected()) { - JOptionPane.showMessageDialog(null, - Localization - .lang("Library is protected. Cannot save until external changes have been reviewed."), - Localization.lang("Protected library"), JOptionPane.ERROR_MESSAGE); + ButtonType save = new ButtonType(Localization.lang("Save")); + ButtonType reviewChanges = new ButtonType(Localization.lang("Review changes")); + + Optional buttonPressed = frame.getDialogService().showCustomButtonDialogAndWait(AlertType.CONFIRMATION, Localization.lang("File updated externally"), + Localization.lang("File has been updated externally. " + "What do you want to do?"), reviewChanges, save, ButtonType.CANCEL); + + if (buttonPressed.isPresent()) { + if (buttonPressed.get() == ButtonType.CANCEL) { canceled = true; - } else { - panel.markExternalChangesAsResolved(); - panel.getSidePaneManager().hide(SidePaneType.FILE_UPDATE_NOTIFICATION); + return true; + } + if (buttonPressed.get().equals(reviewChanges)) { + canceled = true; + + JabRefExecutorService.INSTANCE.execute(() -> { + + if (!FileBasedLock + .waitForFileLock(panel.getBibDatabaseContext().getDatabaseFile().get().toPath())) { + // TODO: GUI handling of the situation when the externally modified file keeps being locked. + LOGGER.error("File locked, this will be trouble."); + } + + ChangeScanner scanner = new ChangeScanner(panel.frame(), panel, + panel.getBibDatabaseContext().getDatabaseFile().get(), panel.getTempFile()); + JabRefExecutorService.INSTANCE.executeInterruptableTaskAndWait(scanner); + if (scanner.changesFound()) { + scanner.displayResult(resolved -> { + if (resolved) { + panel.markExternalChangesAsResolved(); + DefaultTaskExecutor.runInJavaFXThread(() -> panel.getSidePaneManager().hide(SidePaneType.FILE_UPDATE_NOTIFICATION)); + } else { + canceled = true; + } + }); + } + }); + + return true; + } else { // User indicated to store anyway. + if (panel.getBibDatabaseContext().getMetaData().isProtected()) { + + frame.getDialogService().showErrorDialogAndWait(Localization.lang("Protected library"), + Localization.lang("Library is protected. Cannot save until external changes have been reviewed.")); + + canceled = true; + } else { + panel.markExternalChangesAsResolved(); + panel.getSidePaneManager().hide(SidePaneType.FILE_UPDATE_NOTIFICATION); + } } } } diff --git a/src/main/java/org/jabref/gui/externalfiles/DownloadExternalFile.java b/src/main/java/org/jabref/gui/externalfiles/DownloadExternalFile.java index 8985ccd4f02..e556332e59d 100644 --- a/src/main/java/org/jabref/gui/externalfiles/DownloadExternalFile.java +++ b/src/main/java/org/jabref/gui/externalfiles/DownloadExternalFile.java @@ -8,12 +8,11 @@ import java.util.List; import java.util.Optional; -import javax.swing.JOptionPane; import javax.swing.SwingUtilities; import org.jabref.Globals; import org.jabref.JabRefExecutorService; -import org.jabref.gui.JabRefFrame; +import org.jabref.gui.DialogService; import org.jabref.gui.externalfiletype.ExternalFileType; import org.jabref.gui.externalfiletype.ExternalFileTypes; import org.jabref.gui.filelist.FileListEntryEditor; @@ -45,16 +44,16 @@ public class DownloadExternalFile { private static final Logger LOGGER = LoggerFactory.getLogger(DownloadExternalFile.class); - private final JabRefFrame frame; private final BibDatabaseContext databaseContext; private final BibEntry entry; + private final DialogService dialogService; + private FileListEntryEditor editor; private boolean downloadFinished; private boolean dontShowDialog; - - public DownloadExternalFile(JabRefFrame frame, BibDatabaseContext databaseContext, BibEntry entry) { - this.frame = frame; + public DownloadExternalFile(DialogService dialogService, BibDatabaseContext databaseContext, BibEntry entry) { + this.dialogService = dialogService; this.databaseContext = databaseContext; this.entry = entry; } @@ -121,22 +120,21 @@ public static String getSuffix(final String link) { */ public void download(final DownloadCallback callback) throws IOException { dontShowDialog = false; - final String res = JOptionPane.showInputDialog(frame, Localization.lang("Enter URL to download")); - if ((res == null) || res.trim().isEmpty()) { - return; - } + Optional res = dialogService.showInputDialogAndWait(Localization.lang("Download file"), Localization.lang("Enter URL to download")); - URL url; - try { - url = new URL(res); - } catch (MalformedURLException ex1) { - JOptionPane.showMessageDialog(null, Localization.lang("Invalid URL"), Localization.lang("Download file"), - JOptionPane.ERROR_MESSAGE); - return; - } + if (res.isPresent()) { + URL url; + try { + url = new URL(res.get()); + } catch (MalformedURLException ex1) { + dialogService.showErrorDialogAndWait(Localization.lang("Download file"), + Localization.lang("Invalid URL")); - download(url, callback); + return; + } + download(url, callback); + } } /** @@ -160,9 +158,8 @@ public void download(URL url, final DownloadCallback callback) throws IOExceptio // TODO: stop editor dialog if this results in an error: mimeType = udl.getMimeType(); // Read MIME type } catch (IOException ex) { - JOptionPane.showMessageDialog(null, Localization.lang("Invalid URL") + ": " + ex.getMessage(), - Localization.lang("Download file"), JOptionPane.ERROR_MESSAGE); LOGGER.info("Error while downloading " + "'" + res + "'", ex); + dialogService.showErrorDialogAndWait(Localization.lang("Download file"), Localization.lang("Invalid URL") + ": " + ex.getMessage(), ex); return; } final URL urlF = url; @@ -176,9 +173,11 @@ public void download(URL url, final DownloadCallback callback) throws IOExceptio if ((editor != null) && editor.isVisible()) { editor.setVisible(false, false); } - JOptionPane.showMessageDialog(null, Localization.lang("Invalid URL") + ": " + e2.getMessage(), - Localization.lang("Download file"), JOptionPane.ERROR_MESSAGE); + LOGGER.info("Error while downloading " + "'" + urlF + "'", e2); + + dialogService.showErrorDialogAndWait(Localization.lang("Download file"), Localization.lang("Invalid URL") + ": " + e2.getMessage()); + return; } // Download finished: call the method that stops the progress bar etc.: @@ -220,14 +219,16 @@ public void download(URL url, final DownloadCallback callback) throws IOExceptio editor.setExternalConfirm(closeEntry -> { File f = directory == null ? new File(closeEntry.getLink()) : expandFilename(directory, closeEntry.getLink()); if (f.isDirectory()) { - JOptionPane.showMessageDialog(null, Localization.lang("Target file cannot be a directory."), - Localization.lang("Download file"), JOptionPane.ERROR_MESSAGE); + dialogService.showErrorDialogAndWait(Localization.lang("Download file"), + Localization.lang("Target file cannot be a directory.")); + return false; } if (f.exists()) { - return JOptionPane.showConfirmDialog(null, - Localization.lang("'%0' exists. Overwrite file?", f.getName()), - Localization.lang("Download file"), JOptionPane.OK_CANCEL_OPTION) == JOptionPane.OK_OPTION; + return dialogService.showConfirmationDialogAndWait(Localization.lang("Download file"), + Localization.lang("'%0' exists. Overwrite file?", f.getName()), Localization.lang("Overwrite file"), + Localization.lang("Cancel")); + } else { return true; } @@ -334,13 +335,13 @@ private String getSuggestedFileName(String suffix) { return plannedName; } - /** * Callback interface that users of this class must implement in order to receive * notification when download is complete. */ @FunctionalInterface public interface DownloadCallback { + void downloadComplete(LinkedFile file); } } diff --git a/src/main/java/org/jabref/gui/externalfiles/FindFullTextAction.java b/src/main/java/org/jabref/gui/externalfiles/FindFullTextAction.java index a743d05a00d..549efc6fec4 100644 --- a/src/main/java/org/jabref/gui/externalfiles/FindFullTextAction.java +++ b/src/main/java/org/jabref/gui/externalfiles/FindFullTextAction.java @@ -9,10 +9,9 @@ import java.util.Optional; import java.util.concurrent.ConcurrentHashMap; -import javax.swing.JOptionPane; - import org.jabref.Globals; import org.jabref.gui.BasePanel; +import org.jabref.gui.DialogService; import org.jabref.gui.undo.UndoableFieldChange; import org.jabref.gui.util.DefaultTaskExecutor; import org.jabref.gui.worker.AbstractWorker; @@ -36,9 +35,11 @@ public class FindFullTextAction extends AbstractWorker { private final BasePanel basePanel; private final Map, BibEntry> downloads = new ConcurrentHashMap<>(); + private final DialogService dialogService; - public FindFullTextAction(BasePanel basePanel) { + public FindFullTextAction(DialogService dialogService, BasePanel basePanel) { this.basePanel = basePanel; + this.dialogService = dialogService; } @Override @@ -55,16 +56,16 @@ public void run() { if (basePanel.getSelectedEntries().size() >= WARNING_LIMIT) { String[] options = new String[] {Localization.lang("Look up full text documents"), Localization.lang("Cancel")}; - int answer = JOptionPane.showOptionDialog(null, - Localization.lang( - "You are about to look up full text documents for %0 entries.", - String.valueOf(basePanel.getSelectedEntries().size())) + "\n" - + Localization.lang("JabRef will send at least one request per entry to a publisher.") - + "\n" - + Localization.lang("Do you still want to continue?"), - Localization.lang("Look up full text documents"), JOptionPane.OK_CANCEL_OPTION, - JOptionPane.WARNING_MESSAGE, null, options, options[0]); - if (answer != JOptionPane.OK_OPTION) { + + boolean getFullTextForAllCliecked = dialogService.showConfirmationDialogAndWait(Localization.lang("Look up full text documents"), Localization.lang( + "You are about to look up full text documents for %0 entries.", + String.valueOf(basePanel.getSelectedEntries().size())) + "\n" + + Localization.lang("JabRef will send at least one request per entry to a publisher.") + + "\n" + + Localization.lang("Do you still want to continue?"), Localization.lang("Look up full text documents"), + Localization.lang("Cancel")); + + if (!getFullTextForAllCliecked) { basePanel.output(Localization.lang("Operation canceled.")); return; } @@ -85,13 +86,14 @@ public void update() { Optional dir = basePanel.getBibDatabaseContext().getFirstExistingFileDir(Globals.prefs.getFileDirectoryPreferences()); if (!dir.isPresent()) { - JOptionPane.showMessageDialog(null, + + dialogService.showErrorDialogAndWait(Localization.lang("Directory not found"), Localization.lang("Main file directory not set!") + " " + Localization.lang("Preferences") - + " -> " + Localization.lang("File"), - Localization.lang("Directory not found"), JOptionPane.ERROR_MESSAGE); + + " -> " + Localization.lang("File")); + return; } - DownloadExternalFile def = new DownloadExternalFile(basePanel.frame(), + DownloadExternalFile def = new DownloadExternalFile(dialogService, basePanel.getBibDatabaseContext(), entry); try { def.download(result.get(), file -> { @@ -117,7 +119,7 @@ public void update() { entry.getCiteKeyOptional().orElse(Localization.lang("undefined"))); basePanel.output(message); - JOptionPane.showMessageDialog(null, message, title, JOptionPane.ERROR_MESSAGE); + dialogService.showErrorDialogAndWait(title, message); } remove.add(result); } diff --git a/src/main/java/org/jabref/gui/fieldeditors/contextmenu/ProtectedTermsMenu.java b/src/main/java/org/jabref/gui/fieldeditors/contextmenu/ProtectedTermsMenu.java index 33a09471a67..3ede64f1fea 100644 --- a/src/main/java/org/jabref/gui/fieldeditors/contextmenu/ProtectedTermsMenu.java +++ b/src/main/java/org/jabref/gui/fieldeditors/contextmenu/ProtectedTermsMenu.java @@ -67,7 +67,7 @@ private void updateFiles() { externalFiles.getItems().add(new SeparatorMenuItem()); MenuItem addToNewFileItem = new MenuItem(Localization.lang("New") + "..."); addToNewFileItem.setOnAction(event -> { - NewProtectedTermsFileDialog dialog = new NewProtectedTermsFileDialog(JabRefGUI.getMainFrame(), + NewProtectedTermsFileDialog dialog = new NewProtectedTermsFileDialog(JabRefGUI.getMainFrame().getDialogService(), loader); SwingUtilities.invokeLater(() -> { diff --git a/src/main/java/org/jabref/gui/importer/ImportCommand.java b/src/main/java/org/jabref/gui/importer/ImportCommand.java index 5059c771b87..4849fce65ec 100644 --- a/src/main/java/org/jabref/gui/importer/ImportCommand.java +++ b/src/main/java/org/jabref/gui/importer/ImportCommand.java @@ -8,8 +8,6 @@ import java.util.SortedSet; import java.util.stream.Collectors; -import javax.swing.JOptionPane; - import javafx.stage.FileChooser; import org.jabref.Globals; @@ -61,9 +59,9 @@ public void execute() { private void doImport(Path file, SortedSet importers, FileChooser.ExtensionFilter selectedExtensionFilter) { if (!Files.exists(file)) { - JOptionPane.showMessageDialog(null, - Localization.lang("File not found") + ": '" + file.getFileName() + "'.", - Localization.lang("Import"), JOptionPane.ERROR_MESSAGE); + frame.getDialogService().showErrorDialogAndWait(Localization.lang("Import"), + Localization.lang("File not found") + ": '" + file.getFileName() + "'."); + return; } Optional format = FileFilterConverter.getImporter(selectedExtensionFilter, importers); diff --git a/src/main/java/org/jabref/gui/importer/ImportInspectionDialog.java b/src/main/java/org/jabref/gui/importer/ImportInspectionDialog.java index e4425f8e171..34293fc8dca 100644 --- a/src/main/java/org/jabref/gui/importer/ImportInspectionDialog.java +++ b/src/main/java/org/jabref/gui/importer/ImportInspectionDialog.java @@ -80,7 +80,6 @@ import org.jabref.gui.undo.UndoableRemoveEntry; import org.jabref.gui.util.DefaultTaskExecutor; import org.jabref.gui.util.comparator.IconComparator; -import org.jabref.gui.util.component.CheckBoxMessage; import org.jabref.logic.bibtex.DuplicateCheck; import org.jabref.logic.bibtex.comparator.FieldComparator; import org.jabref.logic.bibtexkeypattern.BibtexKeyGenerator; @@ -185,7 +184,6 @@ public class ImportInspectionDialog extends JabRefDialog implements ImportInspec private boolean generatedKeys; // Set to true after keys have been generated. private boolean defaultSelected = true; - /** * Creates a dialog that displays the given list of fields in the table. The * dialog allows another process to add entries dynamically while the dialog @@ -651,8 +649,8 @@ public void showMessage(String message) { */ public void showErrorMessage(String fetcherTitle, String localizedException) { showMessage(Localization.lang("Error while fetching from %0", fetcherTitle) + "\n" + - Localization.lang("Please try again later and/or check your network connection.") + "\n" + - localizedException, + Localization.lang("Please try again later and/or check your network connection.") + "\n" + + localizedException, Localization.lang("Search %0", fetcherTitle), JOptionPane.ERROR_MESSAGE); } @@ -681,7 +679,6 @@ class AddToGroupAction extends AbstractAction { private final GroupTreeNode node; - public AddToGroupAction(GroupTreeNode node) { super(node.getName()); this.node = node; @@ -732,16 +729,15 @@ public void actionPerformed(ActionEvent event) { // This status // is indicated by the entry's group hit status: if (entry.isGroupHit()) { - CheckBoxMessage cbm = new CheckBoxMessage( - Localization - .lang("There are possible duplicates (marked with an icon) that haven't been resolved. Continue?"), - Localization.lang("Disable this confirmation dialog"), false); - int answer = JOptionPane.showConfirmDialog(ImportInspectionDialog.this, cbm, - Localization.lang("Duplicates found"), JOptionPane.YES_NO_OPTION); - if (cbm.isSelected()) { - Globals.prefs.putBoolean(JabRefPreferences.WARN_ABOUT_DUPLICATES_IN_INSPECTION, false); - } - if (answer == JOptionPane.NO_OPTION) { + + boolean continuePressed = 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; } break; @@ -836,10 +832,13 @@ private boolean addToGroups(NamedCompound ce, BibEntry entry, Set // The best course of action is probably to ask the // user if a key should be generated // immediately. - int answer = JOptionPane.showConfirmDialog(ImportInspectionDialog.this, + + boolean generateKeysPressed = frame.getDialogService().showConfirmationDialogAndWait(Localization.lang("Add to group"), Localization.lang("Cannot add entries to group without generating keys. Generate keys now?"), - Localization.lang("Add to group"), JOptionPane.YES_NO_OPTION); - if (answer == JOptionPane.YES_OPTION) { + Localization.lang("Generate keys"), + Localization.lang("Cancel")); + + if (generateKeysPressed) { generateKeys(); } else { groupingCanceled = true; @@ -851,7 +850,7 @@ private boolean addToGroups(NamedCompound ce, BibEntry entry, Set for (GroupTreeNode node : groups) { if (node.getGroup() instanceof GroupEntryChanger) { // Add the entry: - GroupEntryChanger entryChanger = (GroupEntryChanger)node.getGroup(); + GroupEntryChanger entryChanger = (GroupEntryChanger) node.getGroup(); List undo = entryChanger.add(Collections.singletonList(entry)); if (!undo.isEmpty()) { ce.addEdit(UndoableChangeEntriesOfGroup.getUndoableEdit(new GroupTreeNodeViewModel(node), @@ -922,7 +921,6 @@ private class SelectionButton implements ActionListener { private final Boolean enable; - public SelectionButton(boolean enable) { this.enable = enable; } @@ -1188,15 +1186,16 @@ public void actionPerformed(ActionEvent event) { return; } BibEntry entry = selectionModel.getSelected().get(0); - String result = JOptionPane.showInputDialog(ImportInspectionDialog.this, Localization.lang("Enter URL"), - entry.getField(FieldName.URL).orElse("")); + + Optional result = frame.getDialogService().showInputDialogAndWait(Localization.lang("Enter URL"), Localization.lang("Enter URL")); + entries.getReadWriteLock().writeLock().lock(); try { - if (result != null) { - if (result.isEmpty()) { + if (result.isPresent()) { + if (result.get().isEmpty()) { entry.clearField(FieldName.URL); } else { - entry.setField(FieldName.URL, result); + entry.setField(FieldName.URL, result.get()); } } } finally { @@ -1210,7 +1209,6 @@ class DownloadFile extends JMenuItem implements ActionListener, DownloadExternal private BibEntry entry; - public DownloadFile() { super(Localization.lang("Download file")); addActionListener(this); @@ -1223,14 +1221,17 @@ public void actionPerformed(ActionEvent actionEvent) { } entry = selectionModel.getSelected().get(0); if (!entry.getCiteKeyOptional().isPresent()) { - int answer = JOptionPane.showConfirmDialog(null, + + boolean generateKeyPressed = frame.getDialogService().showConfirmationDialogAndWait(Localization.lang("Download file"), Localization.lang("This entry has no BibTeX key. Generate key now?"), - Localization.lang("Download file"), JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE); - if (answer == JOptionPane.OK_OPTION) { + Localization.lang("Generate key"), + Localization.lang("Cancel")); + + if (generateKeyPressed) { generateKeyForEntry(entry); } } - DownloadExternalFile def = new DownloadExternalFile(frame, bibDatabaseContext, entry); + DownloadExternalFile def = new DownloadExternalFile(frame.getDialogService(), bibDatabaseContext, entry); try { def.download(this); } catch (IOException ex) { @@ -1265,10 +1266,13 @@ public void actionPerformed(ActionEvent actionEvent) { } final BibEntry entry = selectionModel.getSelected().get(0); if (!entry.hasCiteKey()) { - int answer = JOptionPane.showConfirmDialog(null, + + boolean generateKeyPressed = frame.getDialogService().showConfirmationDialogAndWait(Localization.lang("Download file"), Localization.lang("This entry has no BibTeX key. Generate key now?"), - Localization.lang("Download file"), JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE); - if (answer == JOptionPane.OK_OPTION) { + Localization.lang("Generate key"), + Localization.lang("Cancel")); + + if (generateKeyPressed) { generateKeyForEntry(entry); } else { return; // Can't go on without the bibtex key. @@ -1291,7 +1295,7 @@ public void actionPerformed(ActionEvent actionEvent) { } glTable.repaint(); } - } , diag)); + }, diag)); } } @@ -1300,7 +1304,6 @@ private class LinkLocalFile extends JMenuItem implements ActionListener, Downloa private BibEntry entry; - public LinkLocalFile() { super(Localization.lang("Link local file")); addActionListener(this); @@ -1343,7 +1346,6 @@ class EntryTable extends JTable { private final GeneralRenderer renderer = new GeneralRenderer(Color.white); - public EntryTable(TableModel model) { super(model); getTableHeader().setReorderingAllowed(false); @@ -1408,29 +1410,29 @@ public Object getColumnValue(BibEntry entry, int i) { return entry.isSearchHit() ? Boolean.TRUE : Boolean.FALSE; } else if (i < PAD) { switch (i) { - case DUPL_COL: - return entry.isGroupHit() ? duplLabel : null; - case FILE_COL: - if (entry.hasField(FieldName.FILE)) { - FileListTableModel model = new FileListTableModel(); - entry.getField(FieldName.FILE).ifPresent(model::setContent); - fileLabel.setToolTipText(model.getToolTipHTMLRepresentation()); - if ((model.getRowCount() > 0) && model.getEntry(0).getType().isPresent()) { - fileLabel.setIcon(model.getEntry(0).getType().get().getIcon().getSmallIcon()); + case DUPL_COL: + return entry.isGroupHit() ? duplLabel : null; + case FILE_COL: + if (entry.hasField(FieldName.FILE)) { + FileListTableModel model = new FileListTableModel(); + entry.getField(FieldName.FILE).ifPresent(model::setContent); + fileLabel.setToolTipText(model.getToolTipHTMLRepresentation()); + if ((model.getRowCount() > 0) && model.getEntry(0).getType().isPresent()) { + fileLabel.setIcon(model.getEntry(0).getType().get().getIcon().getSmallIcon()); + } + return fileLabel; + } else { + return null; } - return fileLabel; - } else { - return null; - } - case URL_COL: - if (entry.hasField(FieldName.URL)) { - urlLabel.setToolTipText(entry.getField(FieldName.URL).orElse("")); - return urlLabel; - } else { + case URL_COL: + if (entry.hasField(FieldName.URL)) { + urlLabel.setToolTipText(entry.getField(FieldName.URL).orElse("")); + return urlLabel; + } else { + return null; + } + default: return null; - } - default: - return null; } } else { String field = INSPECTION_FIELDS.get(i - PAD); diff --git a/src/main/java/org/jabref/gui/importer/actions/OpenDatabaseAction.java b/src/main/java/org/jabref/gui/importer/actions/OpenDatabaseAction.java index 7c6aad61d90..ed00f2e30af 100644 --- a/src/main/java/org/jabref/gui/importer/actions/OpenDatabaseAction.java +++ b/src/main/java/org/jabref/gui/importer/actions/OpenDatabaseAction.java @@ -14,7 +14,6 @@ import java.util.Optional; import java.util.stream.Collectors; -import javax.swing.JOptionPane; import javax.swing.SwingUtilities; import org.jabref.Globals; @@ -191,21 +190,25 @@ private void openTheFile(Path file, boolean raisePanel) { if ((modificationTime.isPresent()) && ((System.currentTimeMillis() - modificationTime.get().toMillis()) > FileBasedLock.LOCKFILE_CRITICAL_AGE)) { // The lock file is fairly old, so we can offer to "steal" the file: - int answer = JOptionPane.showConfirmDialog(null, - "" + Localization.lang("Error opening file") + " '" + fileName + "'. " - + Localization.lang("File is locked by another JabRef instance.") + "

" + + boolean overWriteFileLockPressed = frame.getDialogService().showConfirmationDialogAndWait(Localization.lang("File locked"), + Localization.lang("Error opening file") + " '" + fileName + "'. " + + Localization.lang("File is locked by another JabRef instance.") + "\n" + Localization.lang("Do you want to override the file lock?"), - Localization.lang("File locked"), JOptionPane.YES_NO_OPTION); - if (answer == JOptionPane.YES_OPTION) { + Localization.lang("Overwrite file lock"), + Localization.lang("Cancel")); + + if (overWriteFileLockPressed) { FileBasedLock.deleteLockFile(file); } else { return; } } else if (!FileBasedLock.waitForFileLock(file)) { - JOptionPane.showMessageDialog(null, + + frame.getDialogService().showErrorDialogAndWait(Localization.lang("Error"), Localization.lang("Error opening file") + " '" + fileName + "'. " - + Localization.lang("File is locked by another JabRef instance."), - Localization.lang("Error"), JOptionPane.ERROR_MESSAGE); + + Localization.lang("File is locked by another JabRef instance.")); + return; } } @@ -226,9 +229,10 @@ private void openTheFile(Path file, boolean raisePanel) { result.getDatabaseContext().clearDatabaseFile(); // do not open the original file result.getDatabase().clearSharedDatabaseID(); LOGGER.error("Connection error", e); - JOptionPane.showMessageDialog(null, - e.getMessage() + "\n\n" + Localization.lang("A local copy will be opened."), - Localization.lang("Connection error"), JOptionPane.WARNING_MESSAGE); + + frame.getDialogService().showErrorDialogAndWait(Localization.lang("Connection error"), + e.getMessage() + "\n\n" + Localization.lang("A local copy will be opened.")); + } } diff --git a/src/main/java/org/jabref/gui/mergeentries/MergeWithFetchedEntryAction.java b/src/main/java/org/jabref/gui/mergeentries/MergeWithFetchedEntryAction.java index 28015717f25..5d0d016e3d1 100644 --- a/src/main/java/org/jabref/gui/mergeentries/MergeWithFetchedEntryAction.java +++ b/src/main/java/org/jabref/gui/mergeentries/MergeWithFetchedEntryAction.java @@ -1,8 +1,7 @@ package org.jabref.gui.mergeentries; -import javax.swing.JOptionPane; - import org.jabref.gui.BasePanel; +import org.jabref.gui.DialogService; import org.jabref.gui.actions.BaseAction; import org.jabref.logic.l10n.Localization; import org.jabref.model.entry.BibEntry; @@ -11,9 +10,11 @@ public class MergeWithFetchedEntryAction implements BaseAction { private final BasePanel basePanel; + private final DialogService dialogService; - public MergeWithFetchedEntryAction(BasePanel basePanel) { + public MergeWithFetchedEntryAction(BasePanel basePanel, DialogService dialogService) { this.basePanel = basePanel; + this.dialogService = dialogService; } @Override @@ -22,13 +23,12 @@ public void action() { BibEntry originalEntry = basePanel.getMainTable().getSelectedEntries().get(0); new FetchAndMergeEntry(originalEntry, basePanel, FetchAndMergeEntry.SUPPORTED_FIELDS); } else { - JOptionPane.showMessageDialog(null, - Localization.lang("This operation requires exactly one item to be selected."), - Localization.lang("Merge entry with %0 information", - FieldName.orFields(FieldName.getDisplayName(FieldName.DOI), - FieldName.getDisplayName(FieldName.ISBN), - FieldName.getDisplayName(FieldName.EPRINT))), - JOptionPane.INFORMATION_MESSAGE); + dialogService.showInformationDialogAndWait(Localization.lang("Merge entry with %0 information", + FieldName.orFields(FieldName.getDisplayName(FieldName.DOI), + FieldName.getDisplayName(FieldName.ISBN), + FieldName.getDisplayName(FieldName.EPRINT))), + Localization.lang("This operation requires exactly one item to be selected.")); + } } } diff --git a/src/main/java/org/jabref/gui/openoffice/DetectOpenOfficeInstallation.java b/src/main/java/org/jabref/gui/openoffice/DetectOpenOfficeInstallation.java index 14501f74f0a..0348b1a672e 100644 --- a/src/main/java/org/jabref/gui/openoffice/DetectOpenOfficeInstallation.java +++ b/src/main/java/org/jabref/gui/openoffice/DetectOpenOfficeInstallation.java @@ -153,6 +153,7 @@ private Optional chooseAmongInstallations(List installDirs) { builder.add(Localization.lang("Found more than one OpenOffice/LibreOffice executable.")).xy(1, 1); builder.add(Localization.lang("Please choose which one to connect to:")).xy(1, 3); builder.add(fileList).xy(1, 5); + int answer = JOptionPane.showConfirmDialog(null, builder.getPanel(), Localization.lang("Choose OpenOffice/LibreOffice executable"), JOptionPane.OK_CANCEL_OPTION); if (answer == JOptionPane.CANCEL_OPTION) { diff --git a/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java b/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java index 3d6a95f28da..981d7bc8723 100644 --- a/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java +++ b/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java @@ -78,6 +78,7 @@ * Pane to manage the interaction between JabRef and OpenOffice. */ public class OpenOfficePanel extends AbstractWorker { + private static final Logger LOGGER = LoggerFactory.getLogger(OpenOfficePanel.class); private JPanel content; @@ -99,7 +100,7 @@ public class OpenOfficePanel extends AbstractWorker { private final JButton help = new HelpAction(Localization.lang("OpenOffice/LibreOffice integration"), HelpFile.OPENOFFICE_LIBREOFFICE).getHelpButton(); private OOBibBase ooBase; - private JabRefFrame frame; + private final JabRefFrame frame; private OOBibStyle style; private StyleSelectDialog styleDialog; private boolean dialogOkPressed; @@ -150,9 +151,8 @@ private void initPanel() { + ooBase.getCurrentDocumentTitle().orElse("")); } catch (UnknownPropertyException | WrappedTargetException | IndexOutOfBoundsException | NoSuchElementException | NoDocumentException ex) { - JOptionPane.showMessageDialog(null, ex.getMessage(), Localization.lang("Error"), - JOptionPane.ERROR_MESSAGE); LOGGER.warn("Problem connecting", ex); + frame.getDialogService().showErrorDialogAndWait(ex); } }); @@ -203,11 +203,10 @@ public void actionPerformed(ActionEvent e) { List unresolvedKeys = ooBase.refreshCiteMarkers(databases, style); ooBase.rebuildBibTextSection(databases, style); if (!unresolvedKeys.isEmpty()) { - JOptionPane.showMessageDialog(null, - 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("Unable to synchronize bibliography"), JOptionPane.ERROR_MESSAGE); + frame.getDialogService().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); @@ -216,18 +215,16 @@ public void actionPerformed(ActionEvent e) { } catch (ConnectionLostException ex) { showConnectionLostErrorMessage(); } catch (IOException ex) { - JOptionPane.showMessageDialog(null, - Localization - .lang("You must select either a valid style file, or use one of the default styles."), - Localization.lang("No valid style file defined"), JOptionPane.ERROR_MESSAGE); LOGGER.warn("Problem with style file", ex); + frame.getDialogService().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) { - JOptionPane.showMessageDialog(null, - Localization.lang( - "Your OpenOffice/LibreOffice document references the BibTeX key '%0', which could not be found in your current library.", - ex.getBibtexKey()), - Localization.lang("Unable to synchronize bibliography"), JOptionPane.ERROR_MESSAGE); LOGGER.debug("BibEntry not found", ex); + frame.getDialogService().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); @@ -321,11 +318,11 @@ private void exportEntries() { List unresolvedKeys = ooBase.refreshCiteMarkers(databases, style); BibDatabase newDatabase = ooBase.generateDatabase(databases); if (!unresolvedKeys.isEmpty()) { - JOptionPane.showMessageDialog(null, - 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("Unable to generate new library"), JOptionPane.ERROR_MESSAGE); + + frame.getDialogService().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))); + } Defaults defaults = new Defaults(Globals.prefs.getDefaultBibDatabaseMode()); @@ -334,12 +331,11 @@ private void exportEntries() { this.frame.addTab(databaseContext, true); } catch (BibEntryNotFoundException ex) { - JOptionPane.showMessageDialog(null, - Localization.lang( - "Your OpenOffice/LibreOffice document references the BibTeX key '%0', which could not be found in your current library.", - ex.getBibtexKey()), - Localization.lang("Unable to synchronize bibliography"), JOptionPane.ERROR_MESSAGE); LOGGER.debug("BibEntry not found", ex); + frame.getDialogService().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 | UnknownPropertyException | PropertyVetoException | UndefinedCharacterFormatException | NoSuchElementException | WrappedTargetException | IOException | CreationException e) { @@ -366,8 +362,7 @@ private void connect(boolean autoDetect) { DetectOpenOfficeInstallation officeInstallation = new DetectOpenOfficeInstallation(diag, preferences); if (!officeInstallation.isInstalled()) { - JOptionPane.showMessageDialog(diag, Localization.lang("Autodetection failed"), - Localization.lang("Autodetection failed"), JOptionPane.ERROR_MESSAGE); + frame.getDialogService().showErrorDialogAndWait(Localization.lang("Autodetection failed"), Localization.lang("Autodetection failed")); return; } diag.dispose(); @@ -411,16 +406,20 @@ private void connect(boolean autoDetect) { } catch (UnsatisfiedLinkError e) { LOGGER.warn("Could not connect to running OpenOffice/LibreOffice", e); - JOptionPane.showMessageDialog(null, - 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.")); + + frame.getDialogService().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); - JOptionPane.showMessageDialog(null, + + frame.getDialogService().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.getMessage()); + + "\n" + "\n" + Localization.lang("Error message:"), + e); + } finally { if (progressDialog != null) { progressDialog.dispose(); @@ -459,7 +458,7 @@ private static void addURL(List jarList) throws IOException { URLClassLoader sysloader = (URLClassLoader) ClassLoader.getSystemClassLoader(); Class sysclass = URLClassLoader.class; try { - Method method = sysclass.getDeclaredMethod("addURL", (Class[]) new Class[] {URL.class}); + Method method = sysclass.getDeclaredMethod("addURL", new Class[] {URL.class}); method.setAccessible(true); for (URL anU : jarList) { method.invoke(sysloader, anU); @@ -479,35 +478,31 @@ private void showManualConnectionDialog() { final DialogService dialogService = frame.getDialogService(); DirectoryDialogConfiguration dirDialogConfiguration = new DirectoryDialogConfiguration.Builder() - .withInitialDirectory(nativeDesktop.getApplicationDirectory()).build(); + .withInitialDirectory(nativeDesktop.getApplicationDirectory()) + .build(); FileDialogConfiguration fileDialogConfiguration = new FileDialogConfiguration.Builder() - .withInitialDirectory(nativeDesktop.getApplicationDirectory()).build(); + .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())) - ); + 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())) - ); + 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())) - ); + 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")); @@ -642,13 +637,13 @@ private boolean checkThatEntriesHaveKeys(List entries) { } // Ask if keys should be generated - String[] options = {Localization.lang("Generate keys"), Localization.lang("Cancel")}; - int answer = JOptionPane.showOptionDialog(null, + boolean citePressed = frame.getDialogService().showConfirmationDialogAndWait(Localization.lang("Cite"), Localization.lang("Cannot cite entries without BibTeX keys. Generate keys now?"), - Localization.lang("Cite"), JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, - null); + Localization.lang("Generate keys"), + Localization.lang("Cancel")); + BasePanel panel = frame.getCurrentBasePanel(); - if ((answer == JOptionPane.OK_OPTION) && (panel != null)) { + if (citePressed && (panel != null)) { // Generate keys BibtexKeyPatternPreferences prefs = Globals.prefs.getBibtexKeyPatternPreferences(); NamedCompound undoCompound = new NamedCompound(Localization.lang("Cite")); @@ -672,40 +667,32 @@ private boolean checkThatEntriesHaveKeys(List entries) { } private void showConnectionLostErrorMessage() { - JOptionPane.showMessageDialog(null, + frame.getDialogService().showErrorDialogAndWait(Localization.lang("Connection lost"), Localization.lang("Connection to OpenOffice/LibreOffice has been lost. " - + "Please make sure OpenOffice/LibreOffice is running, and try to reconnect."), - Localization.lang("Connection lost"), JOptionPane.ERROR_MESSAGE); + + "Please make sure OpenOffice/LibreOffice is running, and try to reconnect.")); + } private void reportUndefinedParagraphFormat(UndefinedParagraphFormatException ex) { - JOptionPane - .showMessageDialog( - null, "" - + Localization.lang( - "Your style file specifies the paragraph format '%0', " - + "which is undefined in your current OpenOffice/LibreOffice document.", - ex.getFormatName()) - + "
" - + Localization - .lang("The paragraph format is controlled by the property 'ReferenceParagraphFormat' or 'ReferenceHeaderParagraphFormat' in the style file.") - + "", - "", JOptionPane.ERROR_MESSAGE); + frame.getDialogService().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) { - JOptionPane - .showMessageDialog( - null, "" - + Localization.lang( - "Your style file specifies the character format '%0', " - + "which is undefined in your current OpenOffice/LibreOffice document.", - ex.getFormatName()) - + "
" - + Localization - .lang("The character format is controlled by the citation property 'CitationCharacterFormat' in the style file.") - + "", - "", JOptionPane.ERROR_MESSAGE); + frame.getDialogService().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() { diff --git a/src/main/java/org/jabref/gui/openoffice/StyleSelectDialog.java b/src/main/java/org/jabref/gui/openoffice/StyleSelectDialog.java index 61fc21d3d8f..38496ae4108 100644 --- a/src/main/java/org/jabref/gui/openoffice/StyleSelectDialog.java +++ b/src/main/java/org/jabref/gui/openoffice/StyleSelectDialog.java @@ -22,7 +22,6 @@ import javax.swing.JDialog; import javax.swing.JFrame; import javax.swing.JMenuItem; -import javax.swing.JOptionPane; import javax.swing.JPopupMenu; import javax.swing.JScrollPane; import javax.swing.JTable; @@ -167,8 +166,8 @@ private void init() { @Override public void actionPerformed(ActionEvent event) { if ((table.getRowCount() == 0) || (table.getSelectedRowCount() == 0)) { - JOptionPane.showMessageDialog(diag, Localization.lang("You must select a valid style file."), - Localization.lang("Style selection"), JOptionPane.ERROR_MESSAGE); + frame.getDialogService().showErrorDialogAndWait(Localization.lang("Style selection"), + Localization.lang("You must select a valid style file.")); return; } okPressed = true; @@ -272,9 +271,11 @@ private void setupPopupMenu() { // Create action listener for removing a style, also used for the remove button removeAction = actionEvent -> getSelectedStyle().ifPresent(style -> { - if (!style.isFromResource() && (JOptionPane.showConfirmDialog(diag, - Localization.lang("Are you sure you want to remove the style?"), Localization.lang("Remove style"), - JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION)) { + + if (!style.isFromResource() && frame.getDialogService().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"); } @@ -285,7 +286,9 @@ private void setupPopupMenu() { 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 -> { + reload.addActionListener(actionEvent -> + + getSelectedStyle().ifPresent(style -> { try { style.ensureUpToDate(); } catch (IOException e) { @@ -374,28 +377,28 @@ public int getColumnCount() { @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 ""; + 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 ""; + 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 ""; } } } @@ -472,7 +475,8 @@ public AddFileDialog() { FileDialogConfiguration fileDialogConfiguration = new FileDialogConfiguration.Builder() .addExtensionFilter(FileType.JSTYLE) .withDefaultExtension(FileType.JSTYLE) - .withInitialDirectory(Globals.prefs.get(JabRefPreferences.WORKING_DIRECTORY)).build(); + .withInitialDirectory(Globals.prefs.get(JabRefPreferences.WORKING_DIRECTORY)) + .build(); browse.addActionListener(e -> { Optional file = DefaultTaskExecutor @@ -515,7 +519,8 @@ public void actionPerformed(ActionEvent e) { addCancelButton.addActionListener(cancelAction); // Key bindings: - bb.getPanel().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW) + bb.getPanel() + .getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW) .put(Globals.getKeyPrefs().getKey(KeyBinding.CLOSE_DIALOG), "close"); bb.getPanel().getActionMap().put("close", cancelAction); pack(); diff --git a/src/main/java/org/jabref/gui/preftabs/AdvancedTab.java b/src/main/java/org/jabref/gui/preftabs/AdvancedTab.java index d83cdcc85b5..523b3ba741b 100644 --- a/src/main/java/org/jabref/gui/preftabs/AdvancedTab.java +++ b/src/main/java/org/jabref/gui/preftabs/AdvancedTab.java @@ -6,11 +6,11 @@ import javax.swing.BorderFactory; import javax.swing.JCheckBox; import javax.swing.JLabel; -import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JTextField; import org.jabref.Globals; +import org.jabref.gui.DialogService; import org.jabref.gui.help.HelpAction; import org.jabref.gui.remote.JabRefMessageHandler; import org.jabref.logic.help.HelpFile; @@ -33,9 +33,10 @@ class AdvancedTab extends JPanel implements PrefsTab { private final JCheckBox useCaseKeeperOnSearch; private final JCheckBox useUnitFormatterOnSearch; private final RemotePreferences remotePreferences; + private final DialogService dialogService; - - public AdvancedTab(JabRefPreferences prefs) { + public AdvancedTab(DialogService dialogService, JabRefPreferences prefs) { + this.dialogService = dialogService; preferences = prefs; remotePreferences = prefs.getRemotePreferences(); @@ -45,9 +46,8 @@ public AdvancedTab(JabRefPreferences prefs) { useCaseKeeperOnSearch = new JCheckBox(Localization.lang("Add {} to specified title words on search to keep the correct case")); useUnitFormatterOnSearch = new JCheckBox(Localization.lang("Format units by adding non-breaking separators and keeping the correct case on search")); - FormLayout layout = new FormLayout - ("1dlu, 8dlu, left:pref, 4dlu, fill:3dlu",//, 4dlu, fill:pref",// 4dlu, left:pref, 4dlu", - ""); + FormLayout layout = new FormLayout("1dlu, 8dlu, left:pref, 4dlu, fill:3dlu", //, 4dlu, fill:pref",// 4dlu, left:pref, 4dlu", + ""); DefaultFormBuilder builder = new DefaultFormBuilder(layout); JPanel pan = new JPanel(); @@ -121,10 +121,12 @@ private void storeRemoteSettings() { remotePreferences.setPort(newPort); if (remotePreferences.useRemoteServer()) { - JOptionPane.showMessageDialog(null, - Localization.lang("Remote server port").concat(" ") - .concat(Localization.lang("You must restart JabRef for this to come into effect.")), - Localization.lang("Remote server port"), JOptionPane.WARNING_MESSAGE); + + dialogService.showWarningDialogAndWait(Localization.lang("Remote server port"), + Localization.lang("Remote server port") + .concat(" ") + .concat(Localization.lang("You must restart JabRef for this to come into effect."))); + } } }); @@ -156,10 +158,11 @@ public boolean validateSettings() { throw new NumberFormatException(); } } catch (NumberFormatException ex) { - JOptionPane.showMessageDialog(null, + + dialogService.showErrorDialogAndWait(Localization.lang("Remote server port"), Localization.lang("You must enter an integer value in the interval 1025-65535 in the text field for") - + " '" + Localization.lang("Remote server port") + '\'', - Localization.lang("Remote server port"), JOptionPane.ERROR_MESSAGE); + + " '" + Localization.lang("Remote server port") + '\''); + return false; } } diff --git a/src/main/java/org/jabref/gui/preftabs/AppearancePrefsTab.java b/src/main/java/org/jabref/gui/preftabs/AppearancePrefsTab.java index 0972a46ab15..c884fd07f1a 100644 --- a/src/main/java/org/jabref/gui/preftabs/AppearancePrefsTab.java +++ b/src/main/java/org/jabref/gui/preftabs/AppearancePrefsTab.java @@ -12,12 +12,12 @@ import javax.swing.JCheckBox; import javax.swing.JComboBox; import javax.swing.JLabel; -import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JTextField; import javax.swing.UIManager; import javax.swing.UIManager.LookAndFeelInfo; +import org.jabref.gui.DialogService; import org.jabref.gui.GUIGlobals; import org.jabref.logic.l10n.Localization; import org.jabref.logic.util.OS; @@ -56,6 +56,8 @@ class AppearancePrefsTab extends JPanel implements PrefsTab { private final JCheckBox customLAF; private final JCheckBox fxFontTweaksLAF; + private final DialogService dialogService; + static class LookAndFeel { public static Set getAvailableLookAndFeels() { @@ -68,7 +70,8 @@ public static Set getAvailableLookAndFeels() { * * @param prefs a JabRefPreferences value */ - public AppearancePrefsTab(JabRefPreferences prefs) { + public AppearancePrefsTab(DialogService dialogService, JabRefPreferences prefs) { + this.dialogService = dialogService; this.prefs = prefs; setLayout(new BorderLayout()); @@ -283,10 +286,8 @@ public void storeSettings() { } if (isRestartRequired) { - JOptionPane.showMessageDialog( - null, - Localization.lang("Some appearance settings you changed require to restart JabRef to come into effect."), - Localization.lang("Settings"), JOptionPane.WARNING_MESSAGE); + dialogService.showWarningDialogAndWait(Localization.lang("Settings"), + Localization.lang("Some appearance settings you changed require to restart JabRef to come into effect.")); } prefs.putInt(JabRefPreferences.TABLE_ROW_PADDING, padding); @@ -301,9 +302,8 @@ private boolean validateIntegerField(String fieldName, String fieldValue, String // Test if the field value is a number: Integer.parseInt(fieldValue); } catch (NumberFormatException ex) { - JOptionPane.showMessageDialog(null, - Localization.lang("You must enter an integer value in the text field for") + " '" + fieldName + "'", - errorTitle, JOptionPane.ERROR_MESSAGE); + + dialogService.showErrorDialogAndWait(errorTitle, Localization.lang("You must enter an integer value in the text field for") + " '" + fieldName + "'"); return false; } return true; diff --git a/src/main/java/org/jabref/gui/preftabs/ExternalTab.java b/src/main/java/org/jabref/gui/preftabs/ExternalTab.java index e3f3a50378f..83999f529ea 100644 --- a/src/main/java/org/jabref/gui/preftabs/ExternalTab.java +++ b/src/main/java/org/jabref/gui/preftabs/ExternalTab.java @@ -29,9 +29,8 @@ import com.jgoodies.forms.layout.FormLayout; class ExternalTab extends JPanel implements PrefsTab { - private final JabRefPreferences prefs; - private final JabRefFrame frame; + private final JabRefPreferences prefs; private final JTextField emailSubject; private final JTextField citeCommand; @@ -51,14 +50,13 @@ class ExternalTab extends JPanel implements PrefsTab { public ExternalTab(JabRefFrame frame, PreferencesDialog prefsDiag, JabRefPreferences prefs) { this.prefs = prefs; - this.frame = frame; + setLayout(new BorderLayout()); JButton editFileTypes = new JButton(Localization.lang("Manage external file types")); citeCommand = new JTextField(25); editFileTypes.addActionListener(ExternalFileTypeEditor.getAction(prefsDiag)); - defaultConsole = new JRadioButton(Localization.lang("Use default terminal emulator")); executeConsole = new JRadioButton(Localization.lang("Execute command") + ":"); consoleCommand = new JTextField(); @@ -72,15 +70,13 @@ public ExternalTab(JabRefFrame frame, PreferencesDialog prefsDiag, JabRefPrefere sumatraReaderPath = new JTextField(); browseSumatraReader = new JButton(Localization.lang("Browse")); - - JLabel commandDescription = new JLabel(Localization.lang( - "Note: Use the placeholder %0 for the location of the opened library file.", "%DIR")); + JLabel commandDescription = new JLabel(Localization.lang("Note: Use the placeholder %0 for the location of the opened library file.", "%DIR")); ButtonGroup consoleOptions = new ButtonGroup(); consoleOptions.add(defaultConsole); consoleOptions.add(executeConsole); - ButtonGroup readerOptions = new ButtonGroup(); + ButtonGroup readerOptions = new ButtonGroup(); readerOptions.add(adobeAcrobatReader); JPanel pdfOptionPanel = new JPanel(new GridBagLayout()); @@ -124,7 +120,7 @@ public ExternalTab(JabRefFrame frame, PreferencesDialog prefsDiag, JabRefPrefere pdfOptionPanel.add(adobeAcrobatReader, pdfLayoutConstrains); pdfLayoutConstrains.gridx = 1; - pdfOptionPanel.add(adobeAcrobatReaderPath,pdfLayoutConstrains); + pdfOptionPanel.add(adobeAcrobatReaderPath, pdfLayoutConstrains); pdfLayoutConstrains.gridx = 2; pdfOptionPanel.add(browseAdobeAcrobatReader, pdfLayoutConstrains); @@ -134,7 +130,7 @@ public ExternalTab(JabRefFrame frame, PreferencesDialog prefsDiag, JabRefPrefere browseSumatraReader.addActionListener(e -> showSumatraChooser()); pdfLayoutConstrains.gridy = 1; pdfLayoutConstrains.gridx = 0; - pdfOptionPanel.add(sumatraReader,pdfLayoutConstrains); + pdfOptionPanel.add(sumatraReader, pdfLayoutConstrains); pdfLayoutConstrains.gridx = 1; pdfOptionPanel.add(sumatraReaderPath, pdfLayoutConstrains); @@ -289,8 +285,7 @@ private void showSumatraChooser() { private void readerSelected() { if (adobeAcrobatReader.isSelected()) { prefs.put(JabRefPreferences.USE_PDF_READER, adobeAcrobatReaderPath.getText()); - } - else if (sumatraReader.isSelected()) { + } else if (sumatraReader.isSelected()) { prefs.put(JabRefPreferences.USE_PDF_READER, sumatraReaderPath.getText()); } } diff --git a/src/main/java/org/jabref/gui/preftabs/FileTab.java b/src/main/java/org/jabref/gui/preftabs/FileTab.java index 76d74bf8ba5..5e6f34dcea4 100644 --- a/src/main/java/org/jabref/gui/preftabs/FileTab.java +++ b/src/main/java/org/jabref/gui/preftabs/FileTab.java @@ -18,7 +18,7 @@ import javax.swing.JRadioButton; import javax.swing.JTextField; -import org.jabref.gui.JabRefFrame; +import org.jabref.gui.DialogService; import org.jabref.gui.help.HelpAction; import org.jabref.gui.util.DefaultTaskExecutor; import org.jabref.gui.util.DirectoryDialogConfiguration; @@ -39,7 +39,6 @@ class FileTab extends JPanel implements PrefsTab { private final JabRefPreferences prefs; - private final JabRefFrame frame; private final JCheckBox backup; private final JCheckBox localAutoSave; @@ -62,9 +61,8 @@ class FileTab extends JPanel implements PrefsTab { Localization.lang("Autolink files with names starting with the BibTeX key")); private final JTextField regExpTextField; - public FileTab(JabRefFrame frame, JabRefPreferences prefs) { + public FileTab(DialogService dialogService, JabRefPreferences prefs) { this.prefs = prefs; - this.frame = frame; fileDir = new JTextField(25); bibLocAsPrimaryDir = new JCheckBox(Localization.lang("Use the BIB file location as primary file directory")); @@ -140,8 +138,8 @@ public FileTab(JabRefFrame frame, JabRefPreferences prefs) { DirectoryDialogConfiguration dirDialogConfiguration = new DirectoryDialogConfiguration.Builder() .withInitialDirectory(Paths.get(fileDir.getText())).build(); - DefaultTaskExecutor.runInJavaFXThread(() -> frame.getDialogService().showDirectorySelectionDialog(dirDialogConfiguration)) - .ifPresent(f -> fileDir.setText(f.toString())); + DefaultTaskExecutor.runInJavaFXThread(() -> dialogService.showDirectorySelectionDialog(dirDialogConfiguration)) + .ifPresent(f -> fileDir.setText(f.toString())); }); builder.append(browse); @@ -232,15 +230,15 @@ public void storeSettings() { String newline; switch (newlineSeparator.getSelectedIndex()) { - case 0: - newline = "\r"; - break; - case 2: - newline = "\n"; - break; - default: - newline = "\r\n"; - break; + case 0: + newline = "\r"; + break; + case 2: + newline = "\n"; + break; + default: + newline = "\r\n"; + break; } prefs.put(JabRefPreferences.NEWLINE, newline); // we also have to change Globals variable as globals is not a getter, but a constant diff --git a/src/main/java/org/jabref/gui/preftabs/GeneralTab.java b/src/main/java/org/jabref/gui/preftabs/GeneralTab.java index 3764acf1ca7..0494758071d 100644 --- a/src/main/java/org/jabref/gui/preftabs/GeneralTab.java +++ b/src/main/java/org/jabref/gui/preftabs/GeneralTab.java @@ -13,11 +13,11 @@ import javax.swing.JComboBox; import javax.swing.JLabel; import javax.swing.JList; -import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JTextField; import org.jabref.Globals; +import org.jabref.gui.DialogService; import org.jabref.gui.help.HelpAction; import org.jabref.logic.help.HelpFile; import org.jabref.logic.l10n.Encodings; @@ -51,8 +51,10 @@ class GeneralTab extends JPanel implements PrefsTab { private final JComboBox language = new JComboBox<>(LANGUAGES.keySet().toArray(new String[LANGUAGES.keySet().size()])); private final JComboBox encodings; private final JComboBox biblatexMode; + private final DialogService dialogService; public class DefaultBibModeRenderer extends DefaultListCellRenderer { + @Override public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { @@ -62,9 +64,9 @@ public Component getListCellRendererComponent(JList list, Object value, int i } } - - public GeneralTab(JabRefPreferences prefs) { + public GeneralTab(DialogService dialogService, JabRefPreferences prefs) { this.prefs = prefs; + this.dialogService = dialogService; setLayout(new BorderLayout()); biblatexMode = new JComboBox<>(BibDatabaseMode.values()); @@ -204,10 +206,10 @@ public void storeSettings() { prefs.putBoolean(JabRefPreferences.ENFORCE_LEGAL_BIBTEX_KEY, enforceLegalKeys.isSelected()); prefs.setShouldCollectTelemetry(shouldCollectTelemetry.isSelected()); if (prefs.getBoolean(JabRefPreferences.MEMORY_STICK_MODE) && !memoryStick.isSelected()) { - JOptionPane.showMessageDialog(null, Localization.lang("To disable the memory stick mode" - + " rename or remove the jabref.xml file in the same folder as JabRef."), - Localization.lang("Memory stick mode"), - JOptionPane.INFORMATION_MESSAGE); + + dialogService.showInformationDialogAndWait(Localization.lang("Memory stick mode"), + Localization.lang("To disable the memory stick mode" + + " rename or remove the jabref.xml file in the same folder as JabRef.")); } prefs.putBoolean(JabRefPreferences.MEMORY_STICK_MODE, memoryStick.isSelected()); prefs.putBoolean(JabRefPreferences.CONFIRM_DELETE, confirmDelete.isSelected()); @@ -227,12 +229,11 @@ public void storeSettings() { // Update any defaults that might be language dependent: Globals.prefs.setLanguageDependentDefaultValues(); // Warn about restart needed: - JOptionPane.showMessageDialog(null, + + dialogService.showWarningDialogAndWait(Localization.lang("Changed language settings"), Localization.lang("You have changed the language setting.") .concat(" ") - .concat(Localization.lang("You must restart JabRef for this to come into effect.")), - Localization.lang("Changed language settings"), - JOptionPane.WARNING_MESSAGE); + .concat(Localization.lang("You must restart JabRef for this to come into effect."))); } } @@ -243,10 +244,9 @@ public boolean validateSettings() { DateTimeFormatter.ofPattern(timeStampFormat.getText()); } catch (IllegalArgumentException ex2) { - JOptionPane.showMessageDialog - (null, Localization.lang("The chosen date format for new entries is not valid"), - Localization.lang("Invalid date format"), - JOptionPane.ERROR_MESSAGE); + dialogService.showErrorDialogAndWait(Localization.lang("Invalid date format"), + Localization.lang("The chosen date format for new entries is not valid")); + return false; } return true; diff --git a/src/main/java/org/jabref/gui/preftabs/NetworkTab.java b/src/main/java/org/jabref/gui/preftabs/NetworkTab.java index 37fd48116aa..8db58a1e39e 100644 --- a/src/main/java/org/jabref/gui/preftabs/NetworkTab.java +++ b/src/main/java/org/jabref/gui/preftabs/NetworkTab.java @@ -7,11 +7,11 @@ import javax.swing.BorderFactory; import javax.swing.JCheckBox; import javax.swing.JLabel; -import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JPasswordField; import javax.swing.JTextField; +import org.jabref.gui.DialogService; import org.jabref.logic.l10n.Localization; import org.jabref.logic.net.ProxyPreferences; import org.jabref.logic.net.ProxyRegisterer; @@ -30,8 +30,10 @@ public class NetworkTab extends JPanel implements PrefsTab { private final JPasswordField passwordTextField; private final JabRefPreferences preferences; private ProxyPreferences oldProxyPreferences; + private final DialogService dialogService; - public NetworkTab(JabRefPreferences preferences) { + public NetworkTab(DialogService dialogService, JabRefPreferences preferences) { + this.dialogService = dialogService; this.preferences = preferences; setLayout(new BorderLayout()); @@ -158,11 +160,13 @@ public boolean validateSettings() { } if (!validSetting) { if (validAuthenticationSetting) { - JOptionPane.showMessageDialog(null, Localization.lang("Please specify both hostname and port"), - Localization.lang("Invalid setting"), JOptionPane.ERROR_MESSAGE); + + dialogService.showErrorDialogAndWait(Localization.lang("Invalid setting"), + Localization.lang("Please specify both hostname and port")); } else { - JOptionPane.showMessageDialog(null, Localization.lang("Please specify both username and password"), - Localization.lang("Invalid setting"), JOptionPane.ERROR_MESSAGE); + dialogService.showErrorDialogAndWait(Localization.lang("Invalid setting"), + Localization.lang("Please specify both username and password")); + } } return validSetting; diff --git a/src/main/java/org/jabref/gui/preftabs/PreferencesDialog.java b/src/main/java/org/jabref/gui/preftabs/PreferencesDialog.java index 1e4f6e7837c..75098d4a599 100644 --- a/src/main/java/org/jabref/gui/preftabs/PreferencesDialog.java +++ b/src/main/java/org/jabref/gui/preftabs/PreferencesDialog.java @@ -16,7 +16,6 @@ import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JList; -import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.ListSelectionModel; @@ -81,11 +80,11 @@ public PreferencesDialog(JabRefFrame parent) { main.setLayout(cardLayout); List tabs = new ArrayList<>(); - tabs.add(new GeneralTab(prefs)); - tabs.add(new FileTab(frame, prefs)); + tabs.add(new GeneralTab(frame.getDialogService(), prefs)); + tabs.add(new FileTab(frame.getDialogService(), prefs)); tabs.add(new TablePrefsTab(prefs)); tabs.add(new TableColumnsTab(prefs, parent)); - tabs.add(new PreviewPrefsTab()); + tabs.add(new PreviewPrefsTab(frame.getDialogService())); tabs.add(new ExternalTab(frame, this, prefs)); tabs.add(new GroupsPrefsTab(prefs)); tabs.add(new EntryEditorPrefsTab(prefs)); @@ -94,9 +93,9 @@ public PreferencesDialog(JabRefFrame parent) { tabs.add(new ExportSortingPrefsTab(prefs)); tabs.add(new NameFormatterTab(prefs)); tabs.add(new XmpPrefsTab(prefs)); - tabs.add(new NetworkTab(prefs)); - tabs.add(new AdvancedTab(prefs)); - tabs.add(new AppearancePrefsTab(prefs)); + tabs.add(new NetworkTab(frame.getDialogService(), prefs)); + tabs.add(new AdvancedTab(frame.getDialogService(), prefs)); + tabs.add(new AppearancePrefsTab(frame.getDialogService(), prefs)); // add all tabs tabs.forEach(tab -> main.add((Component) tab, tab.getTabName())); @@ -161,7 +160,8 @@ public PreferencesDialog(JabRefFrame parent) { FileDialogConfiguration fileDialogConfiguration = new FileDialogConfiguration.Builder() .addExtensionFilter(FileType.XML) .withDefaultExtension(FileType.XML) - .withInitialDirectory(getPrefsExportPath()).build(); + .withInitialDirectory(getPrefsExportPath()) + .build(); DialogService ds = frame.getDialogService(); Optional fileName = DefaultTaskExecutor @@ -171,14 +171,14 @@ public PreferencesDialog(JabRefFrame parent) { try { prefs.importPreferences(fileName.get().toString()); updateAfterPreferenceChanges(); - JOptionPane.showMessageDialog(PreferencesDialog.this, - Localization.lang("You must restart JabRef for this to come into effect."), - Localization.lang("Import preferences"), JOptionPane.WARNING_MESSAGE); + + frame.getDialogService().showWarningDialogAndWait(Localization.lang("Import preferences"), + Localization.lang("You must restart JabRef for this to come into effect.")); + this.dispose(); } catch (JabRefException ex) { LOGGER.warn(ex.getMessage(), ex); - JOptionPane.showMessageDialog(PreferencesDialog.this, ex.getLocalizedMessage(), - Localization.lang("Import preferences"), JOptionPane.ERROR_MESSAGE); + frame.getDialogService().showErrorDialogAndWait(Localization.lang("Import preferences"), ex); } } }); @@ -186,19 +186,22 @@ public PreferencesDialog(JabRefFrame parent) { showPreferences.addActionListener( e -> new PreferencesFilterDialog(new JabRefPreferencesFilter(prefs), null).setVisible(true)); resetPreferences.addActionListener(e -> { - if (JOptionPane.showConfirmDialog(PreferencesDialog.this, + + boolean resetPreferencesClicked = frame.getDialogService().showConfirmationDialogAndWait(Localization.lang("Reset preferences"), Localization.lang("Are you sure you want to reset all settings to default values?"), - Localization.lang("Reset preferences"), JOptionPane.OK_CANCEL_OPTION) == JOptionPane.OK_OPTION) { + Localization.lang("Reset preferences"), Localization.lang("Cancel")); + + if (resetPreferencesClicked) { try { prefs.clear(); new SharedDatabasePreferences().clear(); - JOptionPane.showMessageDialog(PreferencesDialog.this, - Localization.lang("You must restart JabRef for this to come into effect."), - Localization.lang("Reset preferences"), JOptionPane.WARNING_MESSAGE); + + frame.getDialogService().showWarningDialogAndWait(Localization.lang("Reset preferences"), + Localization.lang("You must restart JabRef for this to come into effect.")); + } catch (BackingStoreException ex) { LOGGER.warn(ex.getMessage(), ex); - JOptionPane.showMessageDialog(PreferencesDialog.this, ex.getLocalizedMessage(), - Localization.lang("Reset preferences"), JOptionPane.ERROR_MESSAGE); + frame.getDialogService().showErrorDialogAndWait(Localization.lang("Reset preferences"), ex); } updateAfterPreferenceChanges(); } @@ -284,7 +287,8 @@ public void actionPerformed(ActionEvent e) { FileDialogConfiguration fileDialogConfiguration = new FileDialogConfiguration.Builder() .addExtensionFilter(FileType.XML) .withDefaultExtension(FileType.XML) - .withInitialDirectory(Globals.prefs.get(JabRefPreferences.WORKING_DIRECTORY)).build(); + .withInitialDirectory(Globals.prefs.get(JabRefPreferences.WORKING_DIRECTORY)) + .build(); DialogService ds = frame.getDialogService(); Optional path = DefaultTaskExecutor .runInJavaFXThread(() -> ds.showFileSaveDialog(fileDialogConfiguration)); @@ -296,8 +300,8 @@ public void actionPerformed(ActionEvent e) { Globals.prefs.put(JabRefPreferences.PREFS_EXPORT_PATH, exportFile.toString()); } catch (JabRefException ex) { LOGGER.warn(ex.getMessage(), ex); - JOptionPane.showMessageDialog(PreferencesDialog.this, ex.getLocalizedMessage(), - Localization.lang("Export preferences"), JOptionPane.WARNING_MESSAGE); + frame.getDialogService().showErrorDialogAndWait(Localization.lang("Export preferences"), ex); + } }); } diff --git a/src/main/java/org/jabref/gui/preftabs/PreviewPrefsTab.java b/src/main/java/org/jabref/gui/preftabs/PreviewPrefsTab.java index a4888a5131c..5eab6420a78 100644 --- a/src/main/java/org/jabref/gui/preftabs/PreviewPrefsTab.java +++ b/src/main/java/org/jabref/gui/preftabs/PreviewPrefsTab.java @@ -1,7 +1,6 @@ package org.jabref.gui.preftabs; import java.awt.BorderLayout; -import java.awt.Dimension; import java.util.ArrayList; import java.util.Comparator; import java.util.Enumeration; @@ -12,22 +11,22 @@ import javax.swing.DefaultListModel; import javax.swing.JButton; import javax.swing.JList; -import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.ListSelectionModel; import javax.swing.SwingWorker; -import javafx.embed.swing.JFXPanel; -import javafx.scene.Scene; +import javafx.scene.control.ButtonType; +import javafx.scene.control.DialogPane; import org.jabref.Globals; import org.jabref.JabRefGUI; import org.jabref.gui.BasePanel; +import org.jabref.gui.DialogService; import org.jabref.gui.FXDialogService; import org.jabref.gui.PreviewPanel; -import org.jabref.gui.customjfx.CustomJFXPanel; +import org.jabref.gui.util.DefaultTaskExecutor; import org.jabref.logic.citationstyle.CitationStyle; import org.jabref.logic.l10n.Localization; import org.jabref.logic.util.TestEntry; @@ -56,14 +55,15 @@ public class PreviewPrefsTab extends JPanel implements PrefsTab { private final JButton btnUp = new JButton(Localization.lang("Up")); private final JButton btnDown = new JButton(Localization.lang("Down")); - private final JTextArea layout = new JTextArea("", 1, 1); private final JButton btnTest = new JButton(Localization.lang("Test")); private final JButton btnDefault = new JButton(Localization.lang("Default")); private final JScrollPane scrollPane = new JScrollPane(layout); + private final DialogService dialogService; - public PreviewPrefsTab() { + public PreviewPrefsTab(DialogService dialogService) { + this.dialogService = dialogService; setupLogic(); setupGui(); } @@ -97,7 +97,7 @@ private void setupLogic() { List newSelectedIndices = new ArrayList<>(); for (int oldIndex : chosen.getSelectedIndices()) { boolean alreadyTaken = newSelectedIndices.contains(oldIndex - 1); - int newIndex = (oldIndex > 0 && !alreadyTaken) ? oldIndex - 1 : oldIndex; + int newIndex = ((oldIndex > 0) && !alreadyTaken) ? oldIndex - 1 : oldIndex; chosenModel.add(newIndex, chosenModel.remove(oldIndex)); newSelectedIndices.add(newIndex); } @@ -110,7 +110,7 @@ private void setupLogic() { for (int i = selectedIndices.length - 1; i >= 0; i--) { int oldIndex = selectedIndices[i]; boolean alreadyTaken = newSelectedIndices.contains(oldIndex + 1); - int newIndex = (oldIndex < chosenModel.getSize() - 1 && !alreadyTaken) ? oldIndex + 1 : oldIndex; + int newIndex = ((oldIndex < (chosenModel.getSize() - 1)) && !alreadyTaken) ? oldIndex + 1 : oldIndex; chosenModel.add(newIndex, chosenModel.remove(oldIndex)); newSelectedIndices.add(newIndex); } @@ -118,22 +118,31 @@ private void setupLogic() { }); btnDefault.addActionListener(event -> layout.setText(Globals.prefs.getPreviewPreferences() - .getPreviewStyleDefault().replace("__NEWLINE__", "\n"))); + .getPreviewStyleDefault() + .replace("__NEWLINE__", "\n"))); btnTest.addActionListener(event -> { try { - PreviewPanel testPane = new PreviewPanel(null, null, Globals.getKeyPrefs(), Globals.prefs.getPreviewPreferences(), new FXDialogService()); - testPane.setFixedLayout(layout.getText()); - testPane.setEntry(TestEntry.getTestEntry()); - JFXPanel container = CustomJFXPanel.wrap(new Scene(testPane)); - container.setPreferredSize(new Dimension(800, 350)); - JOptionPane.showMessageDialog(PreviewPrefsTab.this, container, Localization.lang("Preview"), JOptionPane.PLAIN_MESSAGE); + DefaultTaskExecutor.runInJavaFXThread(() -> { + + PreviewPanel testPane = new PreviewPanel(null, null, Globals.getKeyPrefs(), Globals.prefs.getPreviewPreferences(), new FXDialogService()); + testPane.setFixedLayout(layout.getText()); + testPane.setEntry(TestEntry.getTestEntry()); + + DialogPane pane = new DialogPane(); + pane.setContent(testPane); + + dialogService.showCustomDialogAndWait(Localization.lang("Preview"), pane, ButtonType.OK); + + }); + } catch (StringIndexOutOfBoundsException exception) { LOGGER.warn("Parsing error.", exception); - JOptionPane.showMessageDialog(null, - Localization.lang("Parsing error") + ": " + Localization.lang("illegal backslash expression") - + ".\n" + exception.getMessage(), - Localization.lang("Parsing error"), JOptionPane.ERROR_MESSAGE); + + dialogService.showErrorDialogAndWait(Localization.lang("Parsing error"), + Localization.lang("Parsing error") + ": " + Localization.lang("illegal backslash expression"), + exception); + } }); } @@ -144,14 +153,21 @@ private void setupGui() { .rows("pref, $lg, fill:pref:grow, $lg, pref:grow, $lg, pref:grow, $lg, pref:grow") .padding(Paddings.DIALOG) - .addSeparator(Localization.lang("Current Preview")).xyw(1, 1, 5) - .add(available).xywh(1, 3, 1, 7) - .add(chosen).xywh(5, 3, 1, 7) - - .add(btnRight).xy(3, 3, "fill, bottom") - .add(btnLeft).xy(3, 5, "fill, top") - .add(btnUp).xy(3, 7, "fill, bottom") - .add(btnDown).xy(3, 9, "fill, top") + .addSeparator(Localization.lang("Current Preview")) + .xyw(1, 1, 5) + .add(available) + .xywh(1, 3, 1, 7) + .add(chosen) + .xywh(5, 3, 1, 7) + + .add(btnRight) + .xy(3, 3, "fill, bottom") + .add(btnLeft) + .xy(3, 5, "fill, top") + .add(btnUp) + .xy(3, 7, "fill, bottom") + .add(btnDown) + .xy(3, 9, "fill, top") .build(); JPanel preview = FormBuilder.create() @@ -159,10 +175,14 @@ private void setupGui() { .rows("pref, $lg, fill:pref:grow") .padding(Paddings.DIALOG) - .addSeparator(Localization.lang("Preview")).xy(1, 1) - .add(btnTest).xy(3, 1) - .add(btnDefault).xy(5, 1) - .add(scrollPane).xyw(1, 3, 5) + .addSeparator(Localization.lang("Preview")) + .xy(1, 1) + .add(btnTest) + .xy(3, 1) + .add(btnDefault) + .xy(5, 1) + .add(scrollPane) + .xyw(1, 3, 5) .build(); setLayout(new BoxLayout(this, BoxLayout.Y_AXIS)); @@ -204,6 +224,7 @@ public void setValues() { } discoverCitationStyleWorker = new SwingWorker, Void>() { + @Override protected List doInBackground() throws Exception { return CitationStyle.discoverCitationStyles(); diff --git a/src/main/java/org/jabref/gui/preftabs/TableColumnsTab.java b/src/main/java/org/jabref/gui/preftabs/TableColumnsTab.java index d47fb04aff6..02aecc34061 100644 --- a/src/main/java/org/jabref/gui/preftabs/TableColumnsTab.java +++ b/src/main/java/org/jabref/gui/preftabs/TableColumnsTab.java @@ -19,7 +19,6 @@ import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JList; -import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JRadioButton; import javax.swing.JScrollPane; @@ -90,7 +89,6 @@ class TableColumnsTab extends JPanel implements PrefsTab { private boolean oldSyncKeyWords; private boolean oldWriteSpecialFields; - /** * Customization of external program paths. * @@ -117,9 +115,10 @@ public int getColumnCount() { public Object getValueAt(int row, int column) { int internalRow = row; internalRow--; - if (internalRow >= tableRows.size()) { + if ((internalRow == -1) || (internalRow >= tableRows.size())) { return ""; } + TableRow rowContent = tableRows.get(internalRow); if (rowContent == null) { return ""; @@ -134,8 +133,7 @@ public Object getValueAt(int row, int column) { @Override public String getColumnName(int col) { - return col == 0 ? Localization.lang("Field name") : - Localization.lang("Column width"); + return col == 0 ? Localization.lang("Field name") : Localization.lang("Column width"); } @Override @@ -166,8 +164,7 @@ public void setValueAt(Object value, int row, int col) { if ("".equals(getValueAt(row, 1))) { setValueAt(String.valueOf(BibtexSingleField.DEFAULT_FIELD_LENGTH), row, 1); } - } - else { + } else { if (value == null) { rowContent.setLength(-1); } else { @@ -183,15 +180,13 @@ public void setValueAt(Object value, int row, int col) { cm.getColumn(0).setPreferredWidth(140); cm.getColumn(1).setPreferredWidth(80); - FormLayout layout = new FormLayout - ("1dlu, 8dlu, left:pref, 4dlu, fill:pref",""); + FormLayout layout = new FormLayout("1dlu, 8dlu, left:pref, 4dlu, fill:pref", ""); DefaultFormBuilder builder = new DefaultFormBuilder(layout); JPanel pan = new JPanel(); JPanel tabPanel = new JPanel(); tabPanel.setLayout(new BorderLayout()); - JScrollPane sp = new JScrollPane - (colSetup, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, - ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); + JScrollPane sp = new JScrollPane(colSetup, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, + ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); colSetup.setPreferredScrollableViewportSize(new Dimension(250, 200)); sp.setMinimumSize(new Dimension(250, 300)); tabPanel.add(sp, BorderLayout.CENTER); @@ -346,8 +341,7 @@ public void setValues() { } } listOfFileColumns.setSelectedIndices(indicesToSelect); - } - else { + } else { listOfFileColumns.setSelectedIndices(new int[] {}); } @@ -663,7 +657,6 @@ public void actionPerformed(ActionEvent e) { } } - /** * Store changes to table preferences. This method is called when * the user clicks Ok. @@ -711,12 +704,11 @@ public void storeSettings() { (oldSyncKeyWords != newSyncKeyWords) || (oldWriteSpecialFields != newWriteSpecialFields); if (restartRequired) { - JOptionPane.showMessageDialog(null, + frame.getDialogService().showWarningDialogAndWait(Localization.lang("Changed special field settings"), Localization.lang("You have changed settings for special fields.") - .concat(" ") - .concat(Localization.lang("You must restart JabRef for this to come into effect.")), - Localization.lang("Changed special field settings"), - JOptionPane.WARNING_MESSAGE); + .concat(" ") + .concat(Localization.lang("You must restart JabRef for this to come into effect."))); + } // restart required implies that the settings have been changed diff --git a/src/main/java/org/jabref/gui/protectedterms/NewProtectedTermsFileDialog.java b/src/main/java/org/jabref/gui/protectedterms/NewProtectedTermsFileDialog.java index d10f203fba4..c546df15777 100644 --- a/src/main/java/org/jabref/gui/protectedterms/NewProtectedTermsFileDialog.java +++ b/src/main/java/org/jabref/gui/protectedterms/NewProtectedTermsFileDialog.java @@ -17,9 +17,7 @@ import org.jabref.Globals; import org.jabref.gui.DialogService; -import org.jabref.gui.FXDialogService; import org.jabref.gui.JabRefDialog; -import org.jabref.gui.JabRefFrame; import org.jabref.gui.keyboard.KeyBinding; import org.jabref.gui.util.DefaultTaskExecutor; import org.jabref.gui.util.FileDialogConfiguration; @@ -39,18 +37,21 @@ public class NewProtectedTermsFileDialog extends JabRefDialog { private final JCheckBox enabled = new JCheckBox(Localization.lang("Enabled")); private boolean addOKPressed; private final ProtectedTermsLoader loader; - private JFrame parent; + private final DialogService dialogService; - public NewProtectedTermsFileDialog(JDialog parent, ProtectedTermsLoader loader) { + public NewProtectedTermsFileDialog(JDialog parent, ProtectedTermsLoader loader, DialogService dialogService) { super(parent, Localization.lang("New protected terms file"), true, NewProtectedTermsFileDialog.class); this.loader = loader; + this.dialogService = dialogService; + setupDialog(); setLocationRelativeTo(parent); } - public NewProtectedTermsFileDialog(JabRefFrame mainFrame, ProtectedTermsLoader loader) { + public NewProtectedTermsFileDialog(DialogService dialogService, ProtectedTermsLoader loader) { super((JFrame) null, Localization.lang("New protected terms file"), true, NewProtectedTermsFileDialog.class); this.loader = loader; + this.dialogService = dialogService; setupDialog(); } @@ -61,11 +62,10 @@ private void setupDialog() { .addExtensionFilter(FileType.TERMS) .withDefaultExtension(FileType.TERMS) .withInitialDirectory(Globals.prefs.get(JabRefPreferences.WORKING_DIRECTORY)).build(); - DialogService ds = new FXDialogService(); browse.addActionListener(e -> { Optional file = DefaultTaskExecutor - .runInJavaFXThread(() -> ds.showFileSaveDialog(fileDialogConfiguration)); + .runInJavaFXThread(() -> dialogService.showFileSaveDialog(fileDialogConfiguration)); file.ifPresent(f -> newFile.setText(f.toAbsolutePath().toString())); }); diff --git a/src/main/java/org/jabref/gui/protectedterms/ProtectedTermsDialog.java b/src/main/java/org/jabref/gui/protectedterms/ProtectedTermsDialog.java index 15e67700fa8..8936805bd96 100644 --- a/src/main/java/org/jabref/gui/protectedterms/ProtectedTermsDialog.java +++ b/src/main/java/org/jabref/gui/protectedterms/ProtectedTermsDialog.java @@ -22,7 +22,6 @@ import javax.swing.JDialog; import javax.swing.JFrame; import javax.swing.JMenuItem; -import javax.swing.JOptionPane; import javax.swing.JPopupMenu; import javax.swing.JScrollPane; import javax.swing.JTable; @@ -113,7 +112,7 @@ private void init() { removeButton.setToolTipText(Localization.lang("Remove protected terms file")); newButton.addActionListener(actionEvent -> { - NewProtectedTermsFileDialog newDialog = new NewProtectedTermsFileDialog(diag, loader); + NewProtectedTermsFileDialog newDialog = new NewProtectedTermsFileDialog(diag, loader, frame.getDialogService()); newDialog.setVisible(true); tableModel.fireTableDataChanged(); }); @@ -254,10 +253,10 @@ private void setupPopupMenu() { // Create action listener for removing a term file, also used for the remove button removeAction = actionEvent -> getSelectedTermsList().ifPresent(list -> { - if (!list.isInternalList() && (JOptionPane.showConfirmDialog(diag, + if (!list.isInternalList() && frame.getDialogService().showConfirmationDialogAndWait(Localization.lang("Remove protected terms file"), Localization.lang("Are you sure you want to remove the protected terms file?"), Localization.lang("Remove protected terms file"), - JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION)) { + Localization.lang("Cancel"))) { if (!loader.removeProtectedTermsList(list)) { LOGGER.info("Problem removing protected terms file"); } @@ -309,30 +308,30 @@ public int getRowCount() { @Override public String getColumnName(int i) { switch (i) { - case 0: - return Localization.lang("Enabled"); - case 1: - return Localization.lang("Description"); - case 2: - return Localization.lang("File"); - default: - return ""; + case 0: + return Localization.lang("Enabled"); + case 1: + return Localization.lang("Description"); + case 2: + return Localization.lang("File"); + default: + return ""; } } @Override public Object getValueAt(int row, int column) { switch (column) { - case 0: - return loader.getProtectedTermsLists().get(row).isEnabled(); - case 1: - return loader.getProtectedTermsLists().get(row).getDescription(); - case 2: - ProtectedTermsList list = loader.getProtectedTermsLists().get(row); - return list.isInternalList() ? Localization.lang("Internal list") + " - " + list.getLocation() : list - .getLocation(); - default: - return ""; + case 0: + return loader.getProtectedTermsLists().get(row).isEnabled(); + case 1: + return loader.getProtectedTermsLists().get(row).getDescription(); + case 2: + ProtectedTermsList list = loader.getProtectedTermsLists().get(row); + return list.isInternalList() ? Localization.lang("Internal list") + " - " + list.getLocation() : list + .getLocation(); + default: + return ""; } } @@ -344,14 +343,14 @@ public boolean isCellEditable(int row, int column) { @Override public Class getColumnClass(int column) { switch (column) { - case 0: - return Boolean.class; - case 1: - return String.class; - case 2: - return String.class; - default: - return String.class; + case 0: + return Boolean.class; + case 1: + return String.class; + case 2: + return String.class; + default: + return String.class; } } diff --git a/src/main/java/org/jabref/gui/push/AbstractPushToApplication.java b/src/main/java/org/jabref/gui/push/AbstractPushToApplication.java index b901293c849..fcd5332ae6c 100644 --- a/src/main/java/org/jabref/gui/push/AbstractPushToApplication.java +++ b/src/main/java/org/jabref/gui/push/AbstractPushToApplication.java @@ -10,7 +10,6 @@ import org.jabref.Globals; import org.jabref.gui.BasePanel; import org.jabref.gui.DialogService; -import org.jabref.gui.FXDialogService; import org.jabref.gui.util.DefaultTaskExecutor; import org.jabref.gui.util.FileDialogConfiguration; import org.jabref.logic.l10n.Localization; @@ -40,6 +39,11 @@ public abstract class AbstractPushToApplication implements PushToApplication { protected String commandPath; protected String commandPathPreferenceKey; protected FormBuilder builder; + protected DialogService dialogService; + + public AbstractPushToApplication(DialogService dialogService) { + this.dialogService = dialogService; + } @Override public String getName() { @@ -164,10 +168,9 @@ protected void initSettingsPanel() { FileDialogConfiguration fileDialogConfiguration = new FileDialogConfiguration.Builder() .withInitialDirectory(Globals.prefs.get(JabRefPreferences.WORKING_DIRECTORY)).build(); - DialogService ds = new FXDialogService(); browse.addActionListener( - e -> DefaultTaskExecutor.runInJavaFXThread(() -> ds.showFileOpenDialog(fileDialogConfiguration)) + e -> DefaultTaskExecutor.runInJavaFXThread(() -> dialogService.showFileOpenDialog(fileDialogConfiguration)) .ifPresent(f -> path.setText(f.toAbsolutePath().toString()))); builder.add(browse).xy(5, 1); settings = builder.build(); diff --git a/src/main/java/org/jabref/gui/push/PushToApplicationAction.java b/src/main/java/org/jabref/gui/push/PushToApplicationAction.java index 41b9dbf1243..468fb8b57dc 100644 --- a/src/main/java/org/jabref/gui/push/PushToApplicationAction.java +++ b/src/main/java/org/jabref/gui/push/PushToApplicationAction.java @@ -6,7 +6,6 @@ import javax.swing.AbstractAction; import javax.swing.Action; -import javax.swing.JOptionPane; import javax.swing.SwingUtilities; import org.jabref.JabRefExecutorService; @@ -19,12 +18,12 @@ * An Action class representing the process of invoking a PushToApplication operation. */ class PushToApplicationAction extends AbstractAction implements Runnable { + private final PushToApplication operation; private final JabRefFrame frame; private BasePanel panel; private List entries; - public PushToApplicationAction(JabRefFrame frame, PushToApplication operation) { this.frame = frame; putValue(Action.SMALL_ICON, operation.getIcon()); @@ -45,7 +44,9 @@ public void actionPerformed(ActionEvent e) { // Check if any entries are selected: entries = panel.getSelectedEntries(); if (entries.isEmpty()) { - JOptionPane.showMessageDialog(null, Localization.lang("This operation requires one or more entries to be selected."), (String) getValue(Action.NAME), JOptionPane.ERROR_MESSAGE); + frame.getDialogService().showErrorDialogAndWait((String) getValue(Action.NAME), + Localization.lang("This operation requires one or more entries to be selected.")); + return; } @@ -53,10 +54,9 @@ public void actionPerformed(ActionEvent e) { if (operation.requiresBibtexKeys()) { for (BibEntry entry : entries) { if (!(entry.getCiteKeyOptional().isPresent()) || entry.getCiteKeyOptional().get().trim().isEmpty()) { - JOptionPane.showMessageDialog(null, - Localization - .lang("This operation requires all selected entries to have BibTeX keys defined."), - (String) getValue(Action.NAME), JOptionPane.ERROR_MESSAGE); + frame.getDialogService().showErrorDialogAndWait((String) getValue(Action.NAME), + Localization.lang("This operation requires all selected entries to have BibTeX keys defined.")); + return; } } diff --git a/src/main/java/org/jabref/gui/push/PushToApplications.java b/src/main/java/org/jabref/gui/push/PushToApplications.java index 4f295459a3d..558f1ff5381 100644 --- a/src/main/java/org/jabref/gui/push/PushToApplications.java +++ b/src/main/java/org/jabref/gui/push/PushToApplications.java @@ -3,24 +3,25 @@ import java.util.ArrayList; import java.util.List; +import org.jabref.gui.DialogService; + public class PushToApplications { private final List applications; - - public PushToApplications() { - /** - * Set up the current available choices: - */ + public PushToApplications(DialogService dialogService) { + /** + * Set up the current available hoices: + */ applications = new ArrayList<>(); - applications.add(new PushToEmacs()); - applications.add(new PushToLyx()); - applications.add(new PushToTexmaker()); - applications.add(new PushToTeXstudio()); - applications.add(new PushToVim()); - applications.add(new PushToWinEdt()); + applications.add(new PushToEmacs(dialogService)); + applications.add(new PushToLyx(dialogService)); + applications.add(new PushToTexmaker(dialogService)); + applications.add(new PushToTeXstudio(dialogService)); + applications.add(new PushToVim(dialogService)); + applications.add(new PushToWinEdt(dialogService)); } public List getApplications() { diff --git a/src/main/java/org/jabref/gui/push/PushToEmacs.java b/src/main/java/org/jabref/gui/push/PushToEmacs.java index 624bb1a2995..0f7648e20c6 100644 --- a/src/main/java/org/jabref/gui/push/PushToEmacs.java +++ b/src/main/java/org/jabref/gui/push/PushToEmacs.java @@ -4,13 +4,13 @@ import java.io.InputStream; import java.util.List; -import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JTextField; import org.jabref.Globals; import org.jabref.JabRefExecutorService; import org.jabref.gui.BasePanel; +import org.jabref.gui.DialogService; import org.jabref.gui.IconTheme; import org.jabref.gui.JabRefIcon; import org.jabref.logic.l10n.Localization; @@ -26,9 +26,12 @@ public class PushToEmacs extends AbstractPushToApplication implements PushToApplication { private static final Logger LOGGER = LoggerFactory.getLogger(PushToEmacs.class); - private final JTextField additionalParams = new JTextField(30); + public PushToEmacs(DialogService dialogService) { + super(dialogService); + } + @Override public String getApplicationName() { return "Emacs"; @@ -91,12 +94,12 @@ public void pushEntries(BibDatabase database, List entries, String key // java string: "(insert \\\"\\\\cite{Blah2001}\\\")"; // so cmd receives: (insert \"\\cite{Blah2001}\") // so emacs receives: (insert "\cite{Blah2001}") - prefix.concat("\\\"\\" + getCiteCommand().replaceAll("\\\\", "\\\\\\\\") + "{" + keys + "}\\\"").concat(suffix) : - // Linux gnuclient/emacslient escaping: - // java string: "(insert \"\\\\cite{Blah2001}\")" - // so sh receives: (insert "\\cite{Blah2001}") - // so emacs receives: (insert "\cite{Blah2001}") - prefix.concat("\"" + getCiteCommand().replaceAll("\\\\", "\\\\\\\\") + "{" + keys + "}\"").concat(suffix); + prefix.concat("\\\"\\" + getCiteCommand().replaceAll("\\\\", "\\\\\\\\") + "{" + keys + "}\\\"").concat(suffix) : + // Linux gnuclient/emacslient escaping: + // java string: "(insert \"\\\\cite{Blah2001}\")" + // so sh receives: (insert "\\cite{Blah2001}") + // so emacs receives: (insert "\cite{Blah2001}") + prefix.concat("\"" + getCiteCommand().replaceAll("\\\\", "\\\\\\\\") + "{" + keys + "}\"").concat(suffix); final Process p = Runtime.getRuntime().exec(com); @@ -129,16 +132,17 @@ public void pushEntries(BibDatabase database, List entries, String key @Override public void operationCompleted(BasePanel panel) { if (couldNotConnect) { - JOptionPane.showMessageDialog(null, "" + + + dialogService.showErrorDialogAndWait(Localization.lang("Error pushing entries"), Localization.lang("Could not connect to a running gnuserv process. Make sure that " - + "Emacs or XEmacs is running,
and that the server has been started " - + "(by running the command 'server-start'/'gnuserv-start').") + "", - Localization.lang("Error"), JOptionPane.ERROR_MESSAGE); + + "Emacs or XEmacs is running, and that the server has been started " + + "(by running the command 'server-start'/'gnuserv-start').")); + } else if (couldNotCall) { - JOptionPane.showMessageDialog(null, + dialogService.showErrorDialogAndWait(Localization.lang("Error pushing entries"), Localization.lang("Could not run the gnuclient/emacsclient program. Make sure you have " - + "the emacsclient/gnuclient program installed and available in the PATH."), - Localization.lang("Error"), JOptionPane.ERROR_MESSAGE); + + "the emacsclient/gnuclient program installed and available in the PATH.")); + } else { super.operationCompleted(panel); } diff --git a/src/main/java/org/jabref/gui/push/PushToLyx.java b/src/main/java/org/jabref/gui/push/PushToLyx.java index c78064f140b..9d84a81380c 100644 --- a/src/main/java/org/jabref/gui/push/PushToLyx.java +++ b/src/main/java/org/jabref/gui/push/PushToLyx.java @@ -12,6 +12,7 @@ import org.jabref.Globals; import org.jabref.JabRefExecutorService; import org.jabref.gui.BasePanel; +import org.jabref.gui.DialogService; import org.jabref.gui.IconTheme; import org.jabref.gui.JabRefIcon; import org.jabref.logic.l10n.Localization; @@ -27,6 +28,10 @@ public class PushToLyx extends AbstractPushToApplication implements PushToApplic private static final Logger LOGGER = LoggerFactory.getLogger(PushToLyx.class); + public PushToLyx(DialogService dialogService) { + super(dialogService); + } + @Override public String getApplicationName() { return "LyX/Kile"; @@ -66,8 +71,7 @@ protected void initSettingsPanel() { } @Override - public void pushEntries(BibDatabase database, final List entries, final String keyString, - MetaData metaData) { + public void pushEntries(BibDatabase database, final List entries, final String keyString, MetaData metaData) { couldNotConnect = false; couldNotCall = false; diff --git a/src/main/java/org/jabref/gui/push/PushToTeXstudio.java b/src/main/java/org/jabref/gui/push/PushToTeXstudio.java index 7082bad60df..366fd579ab9 100644 --- a/src/main/java/org/jabref/gui/push/PushToTeXstudio.java +++ b/src/main/java/org/jabref/gui/push/PushToTeXstudio.java @@ -1,11 +1,16 @@ package org.jabref.gui.push; +import org.jabref.gui.DialogService; import org.jabref.gui.IconTheme; import org.jabref.gui.JabRefIcon; import org.jabref.preferences.JabRefPreferences; public class PushToTeXstudio extends AbstractPushToApplication implements PushToApplication { + public PushToTeXstudio(DialogService dialogService) { + super(dialogService); + } + @Override public String getApplicationName() { return "TeXstudio"; diff --git a/src/main/java/org/jabref/gui/push/PushToTexmaker.java b/src/main/java/org/jabref/gui/push/PushToTexmaker.java index 2f6ec7bedaa..38a32d952c2 100644 --- a/src/main/java/org/jabref/gui/push/PushToTexmaker.java +++ b/src/main/java/org/jabref/gui/push/PushToTexmaker.java @@ -1,5 +1,6 @@ package org.jabref.gui.push; +import org.jabref.gui.DialogService; import org.jabref.gui.IconTheme; import org.jabref.gui.JabRefIcon; import org.jabref.preferences.JabRefPreferences; @@ -9,6 +10,10 @@ */ public class PushToTexmaker extends AbstractPushToApplication implements PushToApplication { + public PushToTexmaker(DialogService dialogService) { + super(dialogService); + } + @Override public String getApplicationName() { return "Texmaker"; diff --git a/src/main/java/org/jabref/gui/push/PushToVim.java b/src/main/java/org/jabref/gui/push/PushToVim.java index a3c1b692464..bf702b2abdf 100644 --- a/src/main/java/org/jabref/gui/push/PushToVim.java +++ b/src/main/java/org/jabref/gui/push/PushToVim.java @@ -4,13 +4,13 @@ import java.io.InputStream; import java.util.List; -import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JTextField; import org.jabref.Globals; import org.jabref.JabRefExecutorService; import org.jabref.gui.BasePanel; +import org.jabref.gui.DialogService; import org.jabref.gui.IconTheme; import org.jabref.gui.JabRefIcon; import org.jabref.logic.l10n.Localization; @@ -25,9 +25,12 @@ public class PushToVim extends AbstractPushToApplication implements PushToApplication { private static final Logger LOGGER = LoggerFactory.getLogger(PushToVim.class); - private final JTextField vimServer = new JTextField(30); + public PushToVim(DialogService dialogService) { + super(dialogService); + } + @Override public String getApplicationName() { return "Vim"; @@ -78,7 +81,7 @@ public void pushEntries(BibDatabase database, List entries, String key String[] com = new String[] {commandPath, "--servername", Globals.prefs.get(JabRefPreferences.VIM_SERVER), "--remote-send", "a" + getCiteCommand() + - "{" + keys + "}"}; + "{" + keys + "}"}; final Process p = Runtime.getRuntime().exec(com); @@ -112,18 +115,14 @@ public void pushEntries(BibDatabase database, List entries, String key @Override public void operationCompleted(BasePanel panel) { if (couldNotConnect) { - JOptionPane.showMessageDialog( - null, - "" + - Localization.lang("Could not connect to Vim server. Make sure that " - + "Vim is running
with correct server name.") - + "", - Localization.lang("Error"), JOptionPane.ERROR_MESSAGE); + + dialogService.showErrorDialogAndWait(Localization.lang("Error pushing entries"), + Localization.lang("Could not connect to Vim server. Make sure that Vim is running with correct server name.")); + } else if (couldNotCall) { - JOptionPane.showMessageDialog( - null, - Localization.lang("Could not run the 'vim' program."), - Localization.lang("Error"), JOptionPane.ERROR_MESSAGE); + dialogService.showErrorDialogAndWait(Localization.lang("Error pushing entries"), + Localization.lang("Could not run the 'vim' program.")); + } else { super.operationCompleted(panel); } diff --git a/src/main/java/org/jabref/gui/push/PushToWinEdt.java b/src/main/java/org/jabref/gui/push/PushToWinEdt.java index 3adf22a12c5..629a8484866 100644 --- a/src/main/java/org/jabref/gui/push/PushToWinEdt.java +++ b/src/main/java/org/jabref/gui/push/PushToWinEdt.java @@ -1,11 +1,16 @@ package org.jabref.gui.push; +import org.jabref.gui.DialogService; import org.jabref.gui.IconTheme; import org.jabref.gui.JabRefIcon; import org.jabref.preferences.JabRefPreferences; public class PushToWinEdt extends AbstractPushToApplication implements PushToApplication { + public PushToWinEdt(DialogService dialogService) { + super(dialogService); + } + @Override public String getApplicationName() { return "WinEdt"; diff --git a/src/main/java/org/jabref/gui/shared/ConnectToSharedDatabaseDialog.java b/src/main/java/org/jabref/gui/shared/ConnectToSharedDatabaseDialog.java index 1c936e5df81..607b7423c16 100644 --- a/src/main/java/org/jabref/gui/shared/ConnectToSharedDatabaseDialog.java +++ b/src/main/java/org/jabref/gui/shared/ConnectToSharedDatabaseDialog.java @@ -115,9 +115,10 @@ public ConnectToSharedDatabaseDialog(JabRefFrame frame) { public void openSharedDatabase() { if (isSharedDatabaseAlreadyPresent()) { - JOptionPane.showMessageDialog(ConnectToSharedDatabaseDialog.this, - Localization.lang("You are already connected to a database using entered connection details."), - Localization.lang("Warning"), JOptionPane.WARNING_MESSAGE); + + frame.getDialogService().showWarningDialogAndWait(Localization.lang("Shared database connection"), + Localization.lang("You are already connected to a database using entered connection details.")); + return; } @@ -126,10 +127,13 @@ public void openSharedDatabase() { Path localFilePath = Paths.get(fileLocationField.getText()); if (Files.exists(localFilePath) && !Files.isDirectory(localFilePath)) { - int answer = JOptionPane.showConfirmDialog(this, + + boolean overwriteFilePressed = frame.getDialogService().showConfirmationDialogAndWait(Localization.lang("Existing file"), Localization.lang("'%0' exists. Overwrite file?", localFilePath.getFileName().toString()), - Localization.lang("Existing file"), JOptionPane.YES_NO_OPTION); - if (answer == JOptionPane.NO_OPTION) { + Localization.lang("Overwrite file"), + Localization.lang("Cancel")); + + if (!overwriteFilePressed) { fileLocationField.requestFocus(); return; } @@ -183,8 +187,8 @@ public void actionPerformed(ActionEvent e) { openSharedDatabase(); } catch (JabRefException exception) { - JOptionPane.showMessageDialog(ConnectToSharedDatabaseDialog.this, exception.getMessage(), - Localization.lang("Warning"), JOptionPane.WARNING_MESSAGE); + frame.getDialogService().showErrorDialogAndWait(Localization.lang("Warning"), exception); + } } }; @@ -471,7 +475,8 @@ private void showFileChooser() { FileDialogConfiguration fileDialogConfiguration = new FileDialogConfiguration.Builder() .addExtensionFilter(FileType.BIBTEX_DB) .withDefaultExtension(FileType.BIBTEX_DB) - .withInitialDirectory(Globals.prefs.get(JabRefPreferences.WORKING_DIRECTORY)).build(); + .withInitialDirectory(Globals.prefs.get(JabRefPreferences.WORKING_DIRECTORY)) + .build(); DialogService ds = frame.getDialogService(); Optional path = DefaultTaskExecutor diff --git a/src/main/java/org/jabref/logic/l10n/Encodings.java b/src/main/java/org/jabref/logic/l10n/Encodings.java index 76d57972745..c67d80684f1 100644 --- a/src/main/java/org/jabref/logic/l10n/Encodings.java +++ b/src/main/java/org/jabref/logic/l10n/Encodings.java @@ -8,16 +8,21 @@ public class Encodings { public static final Charset[] ENCODINGS; public static final String[] ENCODINGS_DISPLAYNAMES; + private static List encodingsList = Charset.availableCharsets().values().stream().distinct() + .collect(Collectors.toList()); + + private Encodings() { + } static { - List encodingsList = Charset.availableCharsets().values().stream().distinct() - .collect(Collectors.toList()); List encodingsStringList = encodingsList.stream().map(Charset::displayName).distinct() .collect(Collectors.toList()); ENCODINGS = encodingsList.toArray(new Charset[encodingsList.size()]); ENCODINGS_DISPLAYNAMES = encodingsStringList.toArray(new String[encodingsStringList.size()]); } - private Encodings() { + public static List getCharsets() { + return encodingsList; } + } diff --git a/src/main/resources/l10n/JabRef_en.properties b/src/main/resources/l10n/JabRef_en.properties index 22ac6ea2d49..c9c844d61f9 100644 --- a/src/main/resources/l10n/JabRef_en.properties +++ b/src/main/resources/l10n/JabRef_en.properties @@ -2339,3 +2339,17 @@ Keep\ entries=Keep entries Keep\ entry=Keep entry Ignore\ backup=Ignore backup Restore\ from\ backup=Restore from backup + +Continue=Continue +Generate\ key=Generate key +Overwrite\ file=Overwrite file +Overwrite\ file\ lock=Overwrite file lock +Save\ without\ backup=Save without backup +Shared\ database\ connection=Shared database connection + +Could\ not\ connect\ to\ Vim\ server.\ Make\ sure\ that\ Vim\ is\ running\ with\ correct\ server\ name.=Could not connect to Vim server. Make sure that Vim is running with correct server name. +Could\ not\ connect\ to\ a\ running\ gnuserv\ process.\ Make\ sure\ that\ Emacs\ or\ XEmacs\ is\ running,\ and\ that\ the\ server\ has\ been\ started\ (by\ running\ the\ command\ 'server-start'/'gnuserv-start').=Could not connect to a running gnuserv process. Make sure that Emacs or XEmacs is running, and that the server has been started (by running the command 'server-start'/'gnuserv-start'). +Error\ pushing\ entries=Error pushing entries + +Undefined\ character\ format=Undefined character format +Undefined\ paragraph\ format=Undefined paragraph format