Skip to content

Commit

Permalink
Fix exceptions when trying to change settings (#4284)
Browse files Browse the repository at this point in the history
I also took the opportunity to improve a few things around our localization code (mainly converting Languages to enum).
  • Loading branch information
tobiasdiez authored Aug 23, 2018
1 parent 835bb47 commit 4dc1008
Show file tree
Hide file tree
Showing 11 changed files with 177 additions and 196 deletions.
9 changes: 4 additions & 5 deletions src/main/java/org/jabref/gui/preferences/FileTab.java
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@

import org.jabref.gui.DialogService;
import org.jabref.gui.help.HelpAction;
import org.jabref.gui.util.DefaultTaskExecutor;
import org.jabref.gui.util.DirectoryDialogConfiguration;
import org.jabref.logic.help.HelpFile;
import org.jabref.logic.l10n.Localization;
Expand All @@ -38,7 +37,7 @@ class FileTab extends Pane implements PrefsTab {
private final CheckBox backup;
private final CheckBox localAutoSave;
private final CheckBox openLast;
private final ComboBox newlineSeparator;
private final ComboBox<String> newlineSeparator;
private final CheckBox reformatFileOnSaveAndExport;
private final RadioButton resolveStringsStandard;
private final RadioButton resolveStringsAll;
Expand Down Expand Up @@ -121,8 +120,8 @@ public FileTab(DialogService dialogService, JabRefPreferences prefs) {
browse.setOnAction(e -> {
DirectoryDialogConfiguration dirDialogConfiguration = new DirectoryDialogConfiguration.Builder()
.withInitialDirectory(Paths.get(fileDir.getText())).build();
DefaultTaskExecutor.runInJavaFXThread(() -> dialogService.showDirectorySelectionDialog(dirDialogConfiguration))
.ifPresent(f -> fileDir.setText(f.toString()));
dialogService.showDirectorySelectionDialog(dirDialogConfiguration)
.ifPresent(f -> fileDir.setText(f.toString()));
});
builder.add(browse, 3, 12);
builder.add(bibLocAsPrimaryDir, 1, 13);
Expand Down Expand Up @@ -153,7 +152,7 @@ public FileTab(DialogService dialogService, JabRefPreferences prefs) {

@Override
public void setValues() {
fileDir.setText(prefs.get(FieldName.FILE + FileDirectoryPreferences.DIR_SUFFIX));
fileDir.setText(prefs.getAsOptional(FieldName.FILE + FileDirectoryPreferences.DIR_SUFFIX).orElse(""));
bibLocAsPrimaryDir.setSelected(prefs.getBoolean(JabRefPreferences.BIB_LOC_AS_PRIMARY_DIR));
runAutoFileSearch.setSelected(prefs.getBoolean(JabRefPreferences.RUN_AUTOMATIC_FILE_SEARCH));
allowFileAutoOpenBrowse.setSelected(prefs.getBoolean(JabRefPreferences.ALLOW_FILE_AUTO_OPEN_BROWSE));
Expand Down
57 changes: 21 additions & 36 deletions src/main/java/org/jabref/gui/preferences/GeneralTab.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
import java.time.format.DateTimeFormatter;

import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.Node;
import javafx.scene.control.Button;
import javafx.scene.control.CheckBox;
Expand All @@ -15,19 +14,18 @@
import javafx.scene.layout.Pane;
import javafx.scene.shape.Line;

import org.jabref.Globals;
import org.jabref.gui.DialogService;
import org.jabref.gui.help.HelpAction;
import org.jabref.gui.util.DefaultTaskExecutor;
import org.jabref.gui.util.ViewModelListCellFactory;
import org.jabref.logic.help.HelpFile;
import org.jabref.logic.l10n.Encodings;
import org.jabref.logic.l10n.Language;
import org.jabref.logic.l10n.Localization;
import org.jabref.model.database.BibDatabaseMode;
import org.jabref.model.entry.InternalBibtexFields;
import org.jabref.preferences.JabRefPreferences;

import static org.jabref.logic.l10n.Languages.LANGUAGES;

class GeneralTab extends Pane implements PrefsTab {

private final CheckBox useOwner;
Expand All @@ -47,8 +45,7 @@ class GeneralTab extends Pane implements PrefsTab {
private final TextField timeStampField;
private final JabRefPreferences prefs;

private final ObservableList<String> options = FXCollections.observableArrayList(LANGUAGES.keySet().toArray(new String[LANGUAGES.keySet().size()]));
private final ComboBox<String> language = new ComboBox<>(options);
private final ComboBox<Language> languageSelection = new ComboBox<>();
private final ComboBox<Charset> encodings;
private final ComboBox<BibDatabaseMode> biblatexMode;
private final DialogService dialogService;
Expand Down Expand Up @@ -121,7 +118,11 @@ public GeneralTab(DialogService dialogService, JabRefPreferences prefs) {
builder.add(new Line(), 1, 16);
Label languageLabel = new Label(Localization.lang("Language") + ':');
builder.add(languageLabel, 1, 17);
builder.add(language, 2, 17);
languageSelection.setItems(FXCollections.observableArrayList(Language.values()));
new ViewModelListCellFactory<Language>()
.withText(Language::getDisplayName)
.install(languageSelection);
builder.add(languageSelection, 2, 17);
builder.add(new Line(), 2, 18);
Label defaultEncoding = new Label(Localization.lang("Default encoding") + ':');
builder.add(defaultEncoding, 1, 19);
Expand Down Expand Up @@ -151,26 +152,13 @@ public void setValues() {
timeStampFormat.setText(prefs.get(JabRefPreferences.TIME_STAMP_FORMAT));
timeStampField.setText(prefs.get(JabRefPreferences.TIME_STAMP_FIELD));
inspectionWarnDupli.setSelected(prefs.getBoolean(JabRefPreferences.WARN_ABOUT_DUPLICATES_IN_INSPECTION));
if (Globals.prefs.getBoolean(JabRefPreferences.BIBLATEX_DEFAULT_MODE)) {
if (prefs.getBoolean(JabRefPreferences.BIBLATEX_DEFAULT_MODE)) {
biblatexMode.setValue(BibDatabaseMode.BIBLATEX);
} else {
biblatexMode.setValue(BibDatabaseMode.BIBTEX);
}

Charset enc = Globals.prefs.getDefaultEncoding();
encodings.setValue(enc);

String oldLan = prefs.get(JabRefPreferences.LANGUAGE);

// Language choice
int ilk = 0;
for (String lan : LANGUAGES.values()) {
if (lan.equals(oldLan)) {
language.setVisibleRowCount(ilk);
}
ilk++;
}

encodings.setValue(prefs.getDefaultEncoding());
languageSelection.setValue(prefs.getLanguage());
}

@Override
Expand All @@ -183,10 +171,9 @@ 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()) {

DefaultTaskExecutor.runInJavaFXThread(()->dialogService.showInformationDialogAndWait(Localization.lang("Memory stick mode"),
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.")));
+ " 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());
Expand All @@ -196,21 +183,19 @@ public void storeSettings() {
prefs.put(JabRefPreferences.TIME_STAMP_FORMAT, timeStampFormat.getText().trim());
prefs.put(JabRefPreferences.TIME_STAMP_FIELD, timeStampField.getText().trim());
// Update name of the time stamp field based on preferences
InternalBibtexFields.updateTimeStampField(Globals.prefs.get(JabRefPreferences.TIME_STAMP_FIELD));
InternalBibtexFields.updateTimeStampField(prefs.get(JabRefPreferences.TIME_STAMP_FIELD));
prefs.setDefaultEncoding(encodings.getValue());
prefs.putBoolean(JabRefPreferences.BIBLATEX_DEFAULT_MODE, biblatexMode.getValue().equals(BibDatabaseMode.BIBLATEX));

if (!LANGUAGES.get(language.getValue()).equals(prefs.get(JabRefPreferences.LANGUAGE))) {
prefs.put(JabRefPreferences.LANGUAGE, LANGUAGES.get(language.getValue()));
Localization.setLanguage(LANGUAGES.get(language.getValue()));
// Update any defaults that might be language dependent:
Globals.prefs.setLanguageDependentDefaultValues();
// Warn about restart needed:
if (!languageSelection.getValue().equals(prefs.getLanguage())) {
prefs.setLanguage(languageSelection.getValue());
Localization.setLanguage(languageSelection.getValue());

DefaultTaskExecutor.runInJavaFXThread(() -> dialogService.showWarningDialogAndWait(Localization.lang("Changed language settings"),
// Warn about restart needed:
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."))));
.concat(" ")
.concat(Localization.lang("You must restart JabRef for this to come into effect.")));
}
}

Expand Down
65 changes: 65 additions & 0 deletions src/main/java/org/jabref/logic/l10n/Language.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
package org.jabref.logic.l10n;

import java.util.Locale;
import java.util.Objects;
import java.util.Optional;

/**
* Contains all supported languages.
*/
public enum Language {

BahasaIndonesia("Bahasa Indonesia", "in"),
BrazilianPortuguese("Brazilian Portuguese", "pt_BR"),
Danish("Dansk", "da"),
German("Deutsch", "de"),
English("English", "en"),
Spanish("Español", "es"),
French("Français", "fr"),
Italian("Italiano", "it"),
Japanese("Japanese", "ja"),
Dutch("Nederlands", "nl"),
Norwegian("Norsk", "no"),
Persian("Persian (فارسی)", "fa"),
Russian("Russian", "ru"),
SimplifiedChinese("Simplified Chinese", "zh"),
Svenska("Svenska", "sv"),
Turkish("Turkish", "tr"),
Vietnamese("Vietnamese", "vi"),
Greek("ελληνικά", "el"),
Tagalog("Tagalog/Filipino", "tl");

private final String displayName;
private final String id;

Language(String displayName, String id) {
this.displayName = displayName;
this.id = id;
}

public static Optional<Locale> convertToSupportedLocale(Language language) {
Objects.requireNonNull(language);

//Very important to split languages like pt_BR into two parts, because otherwise the country would be treated lowercase and create problems in loading
String[] languageParts = language.getId().split("_");
Locale locale;
if (languageParts.length == 1) {
locale = new Locale(languageParts[0]);
} else if (languageParts.length == 2) {
locale = new Locale(languageParts[0], languageParts[1]);
} else {
locale = Locale.ENGLISH;
}

return Optional.of(locale);

}

public String getDisplayName() {
return displayName;
}

public String getId() {
return id;
}
}
63 changes: 0 additions & 63 deletions src/main/java/org/jabref/logic/l10n/Languages.java

This file was deleted.

12 changes: 6 additions & 6 deletions src/main/java/org/jabref/logic/l10n/Localization.java
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ public static String lang(String key, String... params) {
if (localizedMessages == null) {
// I'm logging this because it should never happen
LOGGER.error("Messages are not initialized before accessing key: " + key);
setLanguage("en");
setLanguage(Language.English);
}
return lookup(localizedMessages, key, params);
}
Expand All @@ -64,12 +64,12 @@ public static String lang(String key, String... params) {
*
* @param language Language identifier like "en", "de", etc.
*/
public static void setLanguage(String language) {
Optional<Locale> knownLanguage = Languages.convertToSupportedLocale(language);
public static void setLanguage(Language language) {
Optional<Locale> knownLanguage = Language.convertToSupportedLocale(language);
final Locale defaultLocale = Locale.getDefault();
if (!knownLanguage.isPresent()) {
LOGGER.warn("Language " + language + " is not supported by JabRef (Default:" + defaultLocale + ")");
setLanguage("en");
setLanguage(Language.English);
return;
}
// avoid reinitialization of the language bundles
Expand All @@ -86,7 +86,7 @@ public static void setLanguage(String language) {
} catch (MissingResourceException ex) {
// should not happen as we have scripts to enforce this
LOGGER.warn("Could not find bundles for language " + locale + ", switching to full english language", ex);
setLanguage("en");
setLanguage(Language.English);
}
}

Expand All @@ -98,7 +98,7 @@ public static void setLanguage(String language) {
public static LocalizationBundle getMessages() {
// avoid situations where this function is called before any language was set
if (locale == null) {
setLanguage("en");
setLanguage(Language.English);
}
return localizedMessages;
}
Expand Down
21 changes: 20 additions & 1 deletion src/main/java/org/jabref/preferences/JabRefPreferences.java
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
import java.util.prefs.InvalidPreferencesFormatException;
import java.util.prefs.Preferences;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import org.jabref.Globals;
import org.jabref.JabRefException;
Expand Down Expand Up @@ -61,6 +62,7 @@
import org.jabref.logic.importer.fetcher.DoiFetcher;
import org.jabref.logic.journals.JournalAbbreviationLoader;
import org.jabref.logic.journals.JournalAbbreviationPreferences;
import org.jabref.logic.l10n.Language;
import org.jabref.logic.l10n.Localization;
import org.jabref.logic.layout.LayoutFormatterPreferences;
import org.jabref.logic.layout.format.FileLinkPreferences;
Expand Down Expand Up @@ -444,7 +446,7 @@ private JabRefPreferences() {
// the initialization of the preferences in main
// Otherwise that language framework will be instantiated and more importantly, statically initialized preferences
// like the SearchDisplayMode will never be translated.
Localization.setLanguage(prefs.get(LANGUAGE, "en"));
Localization.setLanguage(getLanguage());

SearchPreferences.putDefaults(defaults);

Expand Down Expand Up @@ -1928,4 +1930,21 @@ public String setLastPreferencesExportPath() {
public void setLastPreferencesExportPath(Path exportFile) {
put(PREFS_EXPORT_PATH, exportFile.toString());
}

public Language getLanguage() {
String languageId = get(LANGUAGE);
return Stream.of(Language.values())
.filter(language -> language.getId().equalsIgnoreCase(languageId))
.findFirst()
.orElse(Language.English);
}

public void setLanguage(Language language) {
Language oldLanguage = getLanguage();
put(LANGUAGE, language.getId());
if (language != oldLanguage) {
// Update any defaults that might be language dependent:
setLanguageDependentDefaultValues();
}
}
}
Loading

0 comments on commit 4dc1008

Please sign in to comment.