From 3f9922e62e3a294bd19928227776f327b66158a3 Mon Sep 17 00:00:00 2001 From: Stefan Kolb Date: Sun, 15 Mar 2020 18:56:50 +0100 Subject: [PATCH] More refactorings --- src/main/java/org/jabref/gui/JabRefFrame.java | 6 +- ...eUIManager.java => AutosaveUiManager.java} | 13 +- .../org/jabref/gui/exporter/SaveAction.java | 5 +- .../jabref/gui/exporter/SaveAllAction.java | 6 +- .../gui/exporter/SaveDatabaseAction.java | 302 +++++++++--------- 5 files changed, 166 insertions(+), 166 deletions(-) rename src/main/java/org/jabref/gui/dialogs/{AutosaveUIManager.java => AutosaveUiManager.java} (72%) diff --git a/src/main/java/org/jabref/gui/JabRefFrame.java b/src/main/java/org/jabref/gui/JabRefFrame.java index 8f65312114e..f904f291fb5 100644 --- a/src/main/java/org/jabref/gui/JabRefFrame.java +++ b/src/main/java/org/jabref/gui/JabRefFrame.java @@ -57,7 +57,7 @@ import org.jabref.gui.copyfiles.CopyFilesAction; import org.jabref.gui.customentrytypes.CustomizeEntryAction; import org.jabref.gui.customizefields.SetupGeneralFieldsAction; -import org.jabref.gui.dialogs.AutosaveUIManager; +import org.jabref.gui.dialogs.AutosaveUiManager; import org.jabref.gui.documentviewer.ShowDocumentViewerAction; import org.jabref.gui.duplicationFinder.DuplicateSearch; import org.jabref.gui.edit.CopyMoreAction; @@ -1018,7 +1018,7 @@ public void addTab(BasePanel basePanel, boolean raisePanel) { if (readyForAutosave(context)) { AutosaveManager autosaver = AutosaveManager.start(context); - autosaver.registerListener(new AutosaveUIManager(basePanel)); + autosaver.registerListener(new AutosaveUiManager(basePanel)); } BackupManager.start(context, Globals.entryTypesManager, prefs); @@ -1137,7 +1137,7 @@ private boolean confirmClose(BasePanel panel) { // The user wants to save. try { SaveDatabaseAction saveAction = new SaveDatabaseAction(panel, Globals.prefs, Globals.entryTypesManager); - if (saveAction.save(panel.getBibDatabaseContext())) { + if (saveAction.save()) { return true; } // The action was either canceled or unsuccessful. diff --git a/src/main/java/org/jabref/gui/dialogs/AutosaveUIManager.java b/src/main/java/org/jabref/gui/dialogs/AutosaveUiManager.java similarity index 72% rename from src/main/java/org/jabref/gui/dialogs/AutosaveUIManager.java rename to src/main/java/org/jabref/gui/dialogs/AutosaveUiManager.java index 612a4d6092a..a1d6da59753 100644 --- a/src/main/java/org/jabref/gui/dialogs/AutosaveUIManager.java +++ b/src/main/java/org/jabref/gui/dialogs/AutosaveUiManager.java @@ -10,23 +10,22 @@ import org.slf4j.LoggerFactory; /** - * This class has an abstract UI role as it listens for an {@link AutosaveEvent} - * and saves the bib file associated with the given {@link BasePanel}. + * This class has an abstract UI role as it listens for an {@link AutosaveEvent} and saves the bib file associated with + * the given {@link BasePanel}. */ -public class AutosaveUIManager { +public class AutosaveUiManager { + private static final Logger LOGGER = LoggerFactory.getLogger(AutosaveUiManager.class); - private static final Logger LOGGER = LoggerFactory.getLogger(AutosaveUIManager.class); private final BasePanel panel; - - public AutosaveUIManager(BasePanel panel) { + public AutosaveUiManager(BasePanel panel) { this.panel = panel; } @Subscribe public void listen(@SuppressWarnings("unused") AutosaveEvent event) { try { - new SaveDatabaseAction(panel, Globals.prefs, Globals.entryTypesManager).save(panel.getBibDatabaseContext(), SaveDatabaseAction.SaveDatabaseMode.SILENT); + new SaveDatabaseAction(panel, Globals.prefs, Globals.entryTypesManager).save(SaveDatabaseAction.SaveDatabaseMode.SILENT); } catch (Throwable e) { LOGGER.error("Problem occurred while saving.", e); } diff --git a/src/main/java/org/jabref/gui/exporter/SaveAction.java b/src/main/java/org/jabref/gui/exporter/SaveAction.java index acbb8a2e602..3c2a4f4b824 100644 --- a/src/main/java/org/jabref/gui/exporter/SaveAction.java +++ b/src/main/java/org/jabref/gui/exporter/SaveAction.java @@ -11,7 +11,7 @@ */ public class SaveAction extends SimpleCommand { - public enum SaveMethod { SAVE, SAVE_AS, SAVE_SELECTED } + public enum SaveMethod {SAVE, SAVE_AS, SAVE_SELECTED} private final SaveMethod saveMethod; private final JabRefFrame frame; @@ -20,7 +20,6 @@ public SaveAction(SaveMethod saveMethod, JabRefFrame frame, StateManager stateMa this.saveMethod = saveMethod; this.frame = frame; - if (saveMethod == SaveMethod.SAVE_SELECTED) { this.executable.bind(ActionHelper.needsEntriesSelected(stateManager)); } else { @@ -37,7 +36,7 @@ public void execute() { switch (saveMethod) { case SAVE: - saveDatabaseAction.save(frame.getCurrentBasePanel().getBibDatabaseContext()); + saveDatabaseAction.save(); break; case SAVE_AS: saveDatabaseAction.saveAs(); diff --git a/src/main/java/org/jabref/gui/exporter/SaveAllAction.java b/src/main/java/org/jabref/gui/exporter/SaveAllAction.java index 0b72650d806..0e9770c034f 100644 --- a/src/main/java/org/jabref/gui/exporter/SaveAllAction.java +++ b/src/main/java/org/jabref/gui/exporter/SaveAllAction.java @@ -23,10 +23,10 @@ public void execute() { for (BasePanel panel : frame.getBasePanelList()) { SaveDatabaseAction saveDatabaseAction = new SaveDatabaseAction(panel, Globals.prefs, Globals.entryTypesManager); - boolean saveResult = saveDatabaseAction.save(panel.getBibDatabaseContext()); + boolean saveResult = saveDatabaseAction.save(); if (!saveResult) { - dialogService.notify(Localization.lang("Could not save file.")); - } + dialogService.notify(Localization.lang("Could not save file.")); + } } dialogService.notify(Localization.lang("Save all finished.")); diff --git a/src/main/java/org/jabref/gui/exporter/SaveDatabaseAction.java b/src/main/java/org/jabref/gui/exporter/SaveDatabaseAction.java index b2ea69c642c..41d1588eee9 100644 --- a/src/main/java/org/jabref/gui/exporter/SaveDatabaseAction.java +++ b/src/main/java/org/jabref/gui/exporter/SaveDatabaseAction.java @@ -17,7 +17,7 @@ import org.jabref.gui.BasePanel; import org.jabref.gui.DialogService; import org.jabref.gui.JabRefFrame; -import org.jabref.gui.dialogs.AutosaveUIManager; +import org.jabref.gui.dialogs.AutosaveUiManager; import org.jabref.gui.util.BackgroundTask; import org.jabref.gui.util.FileDialogConfiguration; import org.jabref.logic.autosaveandbackup.AutosaveManager; @@ -47,84 +47,138 @@ * operation was canceled, or whether it was successful. */ public class SaveDatabaseAction { - - public enum SaveDatabaseMode { - SILENT, NORMAL - } - private static final Logger LOGGER = LoggerFactory.getLogger(SaveDatabaseAction.class); private final BasePanel panel; private final JabRefFrame frame; private final DialogService dialogService; - private final JabRefPreferences prefs; + private final JabRefPreferences preferences; private final BibEntryTypesManager entryTypesManager; - public SaveDatabaseAction(BasePanel panel, JabRefPreferences prefs, BibEntryTypesManager entryTypesManager) { + public enum SaveDatabaseMode { + SILENT, NORMAL + } + + public SaveDatabaseAction(BasePanel panel, JabRefPreferences preferences, BibEntryTypesManager entryTypesManager) { this.panel = panel; this.frame = panel.frame(); this.dialogService = frame.getDialogService(); - this.prefs = prefs; + this.preferences = preferences; this.entryTypesManager = entryTypesManager; } - private boolean saveDatabase(Path file, boolean selectedOnly, Charset encoding, SavePreferences.DatabaseSaveType saveType) throws SaveException { - SavePreferences preferences = prefs.loadForSaveFromPreferences() - .withEncoding(encoding) - .withSaveType(saveType); - try (AtomicFileWriter fileWriter = new AtomicFileWriter(file, preferences.getEncoding(), preferences.makeBackup())) { - BibtexDatabaseWriter databaseWriter = new BibtexDatabaseWriter(fileWriter, preferences, entryTypesManager); + public boolean save() { + return save(panel.getBibDatabaseContext(), SaveDatabaseMode.NORMAL); + } - if (selectedOnly) { - databaseWriter.savePartOfDatabase(panel.getBibDatabaseContext(), panel.getSelectedEntries()); - } else { - databaseWriter.saveDatabase(panel.getBibDatabaseContext()); + public boolean save(SaveDatabaseMode mode) { + return save(panel.getBibDatabaseContext(), mode); + } + + /** + * Asks the user for the path and saves afterwards + */ + public void saveAs() { + askForSavePath().ifPresent(this::saveAs); + } + + public boolean saveAs(Path file) { + return this.saveAs(file, SaveDatabaseMode.NORMAL); + } + + public void saveSelectedAsPlain() { + askForSavePath().ifPresent(path -> { + try { + saveDatabase(path, true, preferences.getDefaultEncoding(), SavePreferences.DatabaseSaveType.PLAIN_BIBTEX); + frame.getFileHistory().newFile(path); + dialogService.notify(Localization.lang("Saved selected to '%0'.", path.toString())); + } catch (SaveException ex) { + LOGGER.error("A problem occurred when trying to save the file", ex); + dialogService.showErrorDialogAndWait(Localization.lang("Save library"), Localization.lang("Could not save file."), ex); } + }); + } - panel.registerUndoableChanges(databaseWriter.getSaveActionsFieldChanges()); + /** + * @param file the new file name to save the data base to. This is stored in the database context of the panel upon + * successful save. + * @return true on successful save + */ + private boolean saveAs(Path file, SaveDatabaseMode mode) { + BibDatabaseContext context = panel.getBibDatabaseContext(); - if (fileWriter.hasEncodingProblems()) { - saveWithDifferentEncoding(file, selectedOnly, preferences.getEncoding(), fileWriter.getEncodingProblems(), saveType); + // Close AutosaveManager and BackupManager for original library + Optional databasePath = context.getDatabasePath(); + if (databasePath.isPresent()) { + final Path oldFile = databasePath.get(); + context.setDatabasePath(oldFile); + AutosaveManager.shutdown(context); + BackupManager.shutdown(context); + } + + // Set new location + if (context.getLocation() == DatabaseLocation.SHARED) { + // Save all properties dependent on the ID. This makes it possible to restore them. + new SharedDatabasePreferences(context.getDatabase().generateSharedDatabaseID()) + .putAllDBMSConnectionProperties(context.getDBMSSynchronizer().getConnectionProperties()); + } + + boolean saveResult = save(file, mode); + + if (saveResult) { + // we managed to successfully save the file + // thus, we can store the store the path into the context + context.setDatabasePath(file); + + // Reinstall AutosaveManager and BackupManager for the new file name + panel.resetChangeMonitorAndChangePane(); + if (readyForAutosave(context)) { + AutosaveManager autosaver = AutosaveManager.start(context); + autosaver.registerListener(new AutosaveUiManager(panel)); } - } catch (UnsupportedCharsetException ex) { - throw new SaveException(Localization.lang("Character encoding '%0' is not supported.", encoding.displayName()), ex); - } catch (IOException ex) { - throw new SaveException("Problems saving:", ex); + if (readyForBackup(context)) { + BackupManager.start(context, entryTypesManager, preferences); + } + + frame.getFileHistory().newFile(file); } - return true; + return saveResult; } - private void saveWithDifferentEncoding(Path file, boolean selectedOnly, Charset encoding, Set encodingProblems, SavePreferences.DatabaseSaveType saveType) throws SaveException { - DialogPane pane = new DialogPane(); - VBox vbox = new VBox(); - vbox.getChildren().addAll( - new Text(Localization.lang("The chosen encoding '%0' could not encode the following characters:", encoding.displayName())), - new Text(encodingProblems.stream().map(Object::toString).collect(Collectors.joining("."))), - new Text(Localization.lang("What do you want to do?")) - ); - pane.setContent(vbox); - - ButtonType tryDifferentEncoding = new ButtonType(Localization.lang("Try different encoding"), ButtonBar.ButtonData.OTHER); - ButtonType ignore = new ButtonType(Localization.lang("Ignore"), ButtonBar.ButtonData.APPLY); - boolean saveWithDifferentEncoding = frame.getDialogService() - .showCustomDialogAndWait(Localization.lang("Save library"), pane, ignore, tryDifferentEncoding) - .filter(buttonType -> buttonType.equals(tryDifferentEncoding)) - .isPresent(); - if (saveWithDifferentEncoding) { - Optional newEncoding = frame.getDialogService().showChoiceDialogAndWait(Localization.lang("Save library"), Localization.lang("Select new encoding"), Localization.lang("Save library"), encoding, Encodings.getCharsets()); - if (newEncoding.isPresent()) { - // Make sure to remember which encoding we used. - panel.getBibDatabaseContext().getMetaData().setEncoding(newEncoding.get(), ChangePropagation.DO_NOT_POST_EVENT); + /** + * Asks the user for the path to save to. Stores the directory to the preferences, which is used next time when + * opening the dialog. + * + * @return the path set by the user + */ + private Optional askForSavePath() { + FileDialogConfiguration fileDialogConfiguration = new FileDialogConfiguration.Builder() + .addExtensionFilter(StandardFileType.BIBTEX_DB) + .withDefaultExtension(StandardFileType.BIBTEX_DB) + .withInitialDirectory(preferences.get(JabRefPreferences.WORKING_DIRECTORY)) + .build(); + Optional selectedPath = dialogService.showFileSaveDialog(fileDialogConfiguration); + selectedPath.ifPresent(path -> preferences.setWorkingDir(path.getParent())); + return selectedPath; + } - saveDatabase(file, selectedOnly, newEncoding.get(), saveType); + private boolean save(BibDatabaseContext bibDatabaseContext, SaveDatabaseMode mode) { + Optional databasePath = bibDatabaseContext.getDatabasePath(); + if (!databasePath.isPresent()) { + Optional savePath = askForSavePath(); + if (!savePath.isPresent()) { + return false; } + return saveAs(savePath.get(), mode); } + + return save(databasePath.get(), mode); } - public boolean save(Path targetPath, SaveDatabaseMode mode) { + private boolean save(Path targetPath, SaveDatabaseMode mode) { if (mode == SaveDatabaseMode.NORMAL) { - panel.frame().getDialogService().notify(Localization.lang("Saving library") + "..."); + dialogService.notify(String.format("%s...", Localization.lang("Saving library"))); } panel.setSaving(true); @@ -132,7 +186,7 @@ public boolean save(Path targetPath, SaveDatabaseMode mode) { Charset encoding = panel.getBibDatabaseContext() .getMetaData() .getEncoding() - .orElse(prefs.getDefaultEncoding()); + .orElse(preferences.getDefaultEncoding()); // Make sure to remember which encoding we used. panel.getBibDatabaseContext().getMetaData().setEncoding(encoding, ChangePropagation.DO_NOT_POST_EVENT); @@ -141,21 +195,18 @@ public boolean save(Path targetPath, SaveDatabaseMode mode) { if (success) { panel.getUndoManager().markUnchanged(); - // (Only) after a successful save the following - // statement marks that the base is unchanged - // since last save: + // After a successful save the following statement marks that the base is unchanged since last save panel.setNonUndoableChange(false); panel.setBaseChanged(false); - frame.setTabTitle(panel, panel.getTabTitle(), - targetPath.toAbsolutePath().toString()); + frame.setTabTitle(panel, panel.getTabTitle(), targetPath.toAbsolutePath().toString()); frame.setWindowTitle(); frame.updateAllTabTitles(); } return success; } catch (SaveException ex) { - LOGGER.error("A problem occurred when trying to save the file " + targetPath, ex); - frame.getDialogService().showErrorDialogAndWait(Localization.lang("Save library"), Localization.lang("Could not save file."), ex); + LOGGER.error(String.format("A problem occurred when trying to save the file %s", targetPath), ex); + dialogService.showErrorDialogAndWait(Localization.lang("Save library"), Localization.lang("Could not save file."), ex); return false; } finally { // release panel from save status @@ -163,100 +214,64 @@ public boolean save(Path targetPath, SaveDatabaseMode mode) { } } - public boolean save(BibDatabaseContext bibDatabaseContext) { - return save(bibDatabaseContext, SaveDatabaseMode.NORMAL); - } + private boolean saveDatabase(Path file, boolean selectedOnly, Charset encoding, SavePreferences.DatabaseSaveType saveType) throws SaveException { + SavePreferences preferences = this.preferences.loadForSaveFromPreferences() + .withEncoding(encoding) + .withSaveType(saveType); + try (AtomicFileWriter fileWriter = new AtomicFileWriter(file, preferences.getEncoding(), preferences.makeBackup())) { + BibtexDatabaseWriter databaseWriter = new BibtexDatabaseWriter(fileWriter, preferences, entryTypesManager); - public boolean save(BibDatabaseContext bibDatabaseContext, SaveDatabaseMode mode) { - Optional databasePath = bibDatabaseContext.getDatabasePath(); - if (!databasePath.isPresent()) { - Optional savePath = askForSavePath(); - if (!savePath.isPresent()) { - return false; + if (selectedOnly) { + databaseWriter.savePartOfDatabase(panel.getBibDatabaseContext(), panel.getSelectedEntries()); + } else { + databaseWriter.saveDatabase(panel.getBibDatabaseContext()); } - return saveAs(savePath.get(), mode); - } - - return save(databasePath.get(), mode); - } - - /** - * Asks the user for the path and saves afterwards - */ - public void saveAs() { - askForSavePath().ifPresent(this::saveAs); - } - /** - * Asks the user for the path to save to. Stores the directory to the preferences, which is used next time when opening the dialog. - * - * @return the path set by the user - */ - public Optional askForSavePath() { - FileDialogConfiguration fileDialogConfiguration = new FileDialogConfiguration.Builder() - .addExtensionFilter(StandardFileType.BIBTEX_DB) - .withDefaultExtension(StandardFileType.BIBTEX_DB) - .withInitialDirectory(prefs.get(JabRefPreferences.WORKING_DIRECTORY)) - .build(); - Optional selectedPath = dialogService.showFileSaveDialog(fileDialogConfiguration); - selectedPath.ifPresent(path -> prefs.setWorkingDir(path.getParent())); - return selectedPath; - } - - public boolean saveAs(Path file) { - return this.saveAs(file, SaveDatabaseMode.NORMAL); - } - - /** - * @param file the new file name to save the data base to. This is stored in the database context of the panel upon successful save. - * @return true on successful save - */ - public boolean saveAs(Path file, SaveDatabaseMode mode) { - BibDatabaseContext context = panel.getBibDatabaseContext(); + panel.registerUndoableChanges(databaseWriter.getSaveActionsFieldChanges()); - // Close AutosaveManager and BackupManager for original library - Optional databasePath = context.getDatabasePath(); - if (databasePath.isPresent()) { - final Path oldFile = databasePath.get(); - context.setDatabasePath(oldFile); - AutosaveManager.shutdown(context); - BackupManager.shutdown(context); + if (fileWriter.hasEncodingProblems()) { + saveWithDifferentEncoding(file, selectedOnly, preferences.getEncoding(), fileWriter.getEncodingProblems(), saveType); + } + } catch (UnsupportedCharsetException ex) { + throw new SaveException(Localization.lang("Character encoding '%0' is not supported.", encoding.displayName()), ex); + } catch (IOException ex) { + throw new SaveException("Problems saving:", ex); } - // Set new location - if (context.getLocation() == DatabaseLocation.SHARED) { - // Save all properties dependent on the ID. This makes it possible to restore them. - new SharedDatabasePreferences(context.getDatabase().generateSharedDatabaseID()) - .putAllDBMSConnectionProperties(context.getDBMSSynchronizer().getConnectionProperties()); - } + return true; + } - boolean saveResult = save(file, mode); + private void saveWithDifferentEncoding(Path file, boolean selectedOnly, Charset encoding, Set encodingProblems, SavePreferences.DatabaseSaveType saveType) throws SaveException { + DialogPane pane = new DialogPane(); + VBox vbox = new VBox(); + vbox.getChildren().addAll( + new Text(Localization.lang("The chosen encoding '%0' could not encode the following characters:", encoding.displayName())), + new Text(encodingProblems.stream().map(Object::toString).collect(Collectors.joining("."))), + new Text(Localization.lang("What do you want to do?")) + ); + pane.setContent(vbox); - if (saveResult) { - // we managed to successfully save the file - // thus, we can store the store the path into the context - context.setDatabasePath(file); + ButtonType tryDifferentEncoding = new ButtonType(Localization.lang("Try different encoding"), ButtonBar.ButtonData.OTHER); + ButtonType ignore = new ButtonType(Localization.lang("Ignore"), ButtonBar.ButtonData.APPLY); + boolean saveWithDifferentEncoding = dialogService + .showCustomDialogAndWait(Localization.lang("Save library"), pane, ignore, tryDifferentEncoding) + .filter(buttonType -> buttonType.equals(tryDifferentEncoding)) + .isPresent(); + if (saveWithDifferentEncoding) { + Optional newEncoding = dialogService.showChoiceDialogAndWait(Localization.lang("Save library"), Localization.lang("Select new encoding"), Localization.lang("Save library"), encoding, Encodings.getCharsets()); + if (newEncoding.isPresent()) { + // Make sure to remember which encoding we used. + panel.getBibDatabaseContext().getMetaData().setEncoding(newEncoding.get(), ChangePropagation.DO_NOT_POST_EVENT); - // Reinstall AutosaveManager and BackupManager for the new file name - panel.resetChangeMonitorAndChangePane(); - if (readyForAutosave(context)) { - AutosaveManager autosaver = AutosaveManager.start(context); - autosaver.registerListener(new AutosaveUIManager(panel)); - } - if (readyForBackup(context)) { - BackupManager.start(context, entryTypesManager, prefs); + saveDatabase(file, selectedOnly, newEncoding.get(), saveType); } - - frame.getFileHistory().newFile(file); } - - return saveResult; } private boolean readyForAutosave(BibDatabaseContext context) { return ((context.getLocation() == DatabaseLocation.SHARED) || ((context.getLocation() == DatabaseLocation.LOCAL) - && prefs.getBoolean(JabRefPreferences.LOCAL_AUTO_SAVE))) + && preferences.getBoolean(JabRefPreferences.LOCAL_AUTO_SAVE))) && context.getDatabasePath().isPresent(); } @@ -264,17 +279,4 @@ private boolean readyForAutosave(BibDatabaseContext context) { private boolean readyForBackup(BibDatabaseContext context) { return (context.getLocation() == DatabaseLocation.LOCAL) && context.getDatabasePath().isPresent(); } - - public void saveSelectedAsPlain() { - askForSavePath().ifPresent(path -> { - try { - saveDatabase(path, true, prefs.getDefaultEncoding(), SavePreferences.DatabaseSaveType.PLAIN_BIBTEX); - frame.getFileHistory().newFile(path); - frame.getDialogService().notify(Localization.lang("Saved selected to '%0'.", path.toString())); - } catch (SaveException ex) { - LOGGER.error("A problem occurred when trying to save the file", ex); - frame.getDialogService().showErrorDialogAndWait(Localization.lang("Save library"), Localization.lang("Could not save file."), ex); - } - }); - } }