Simplify core related to languages selection in settings tab.

This commit is contained in:
Dmitry Isaenko 2020-07-28 02:09:10 +03:00
parent f332083e27
commit 62a0b514b4
3 changed files with 218 additions and 149 deletions

View file

@ -19,8 +19,6 @@
package nsusbloader.Controllers; package nsusbloader.Controllers;
import javafx.application.HostServices; import javafx.application.HostServices;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.concurrent.Task; import javafx.concurrent.Task;
import javafx.fxml.FXML; import javafx.fxml.FXML;
import javafx.fxml.Initializable; import javafx.fxml.Initializable;
@ -30,17 +28,12 @@ import javafx.scene.layout.VBox;
import nsusbloader.AppPreferences; import nsusbloader.AppPreferences;
import nsusbloader.ServiceWindow; import nsusbloader.ServiceWindow;
import nsusbloader.ModelControllers.UpdatesChecker; import nsusbloader.ModelControllers.UpdatesChecker;
import nsusbloader.UI.LocaleUiStringHolder; import nsusbloader.UI.LocaleHolder;
import nsusbloader.UI.SettingsLanguagesSetup;
import nsusbloader.Utilities.WindowsDrivers.DriversInstall; import nsusbloader.Utilities.WindowsDrivers.DriversInstall;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URL; import java.net.URL;
import java.net.URLDecoder;
import java.util.*; import java.util.*;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
public class SettingsController implements Initializable { public class SettingsController implements Initializable {
@FXML @FXML
@ -48,69 +41,66 @@ public class SettingsController implements Initializable {
validateNSHostNameCb, validateNSHostNameCb,
expertModeCb, expertModeCb,
autoDetectIpCb, autoDetectIpCb,
randPortCb; randPortCb,
dontServeCb,
autoCheckUpdCb,
tfXciSpprtCb;
@FXML @FXML
private TextField pcIpTextField, private TextField pcIpTextField,
pcPortTextField, pcPortTextField,
pcExtraTextField; pcExtraTextField;
@FXML
private CheckBox dontServeCb;
@FXML @FXML
private VBox expertSettingsVBox; private VBox expertSettingsVBox;
@FXML
private CheckBox autoCheckUpdCb;
@FXML @FXML
private Hyperlink newVersionLink; private Hyperlink newVersionLink;
@FXML
private CheckBox tfXciSpprtCb;
@FXML @FXML
private Button langBtn, private Button langBtn,
checkForUpdBtn, checkForUpdBtn,
drvInstBtn; drvInstBtn;
@FXML @FXML
private ChoiceBox<LocaleUiStringHolder> langCB; private ChoiceBox<LocaleHolder> langCB;
@FXML @FXML
private ChoiceBox<String> glVersionChoiceBox; private ChoiceBox<String> glVersionChoiceBox;
private HostServices hs; private HostServices hostServices;
public static final String[] glSupportedVersions = {"v0.5", "v0.7.x", "v0.8"}; public static final String[] glSupportedVersions = {"v0.5", "v0.7.x", "v0.8"};
private ResourceBundle resourceBundle;
@Override @Override
public void initialize(URL url, ResourceBundle resourceBundle) { public void initialize(URL url, ResourceBundle resourceBundle) {
nspFilesFilterForGLCB.setSelected(AppPreferences.getInstance().getNspFileFilterGL()); this.resourceBundle = resourceBundle;
final AppPreferences preferences = AppPreferences.getInstance();
validateNSHostNameCb.setSelected(AppPreferences.getInstance().getNsIpValidationNeeded()); nspFilesFilterForGLCB.setSelected(preferences.getNspFileFilterGL());
validateNSHostNameCb.setSelected(preferences.getNsIpValidationNeeded());
expertSettingsVBox.setDisable(! preferences.getExpertMode());
expertModeCb.setSelected(preferences.getExpertMode());
expertModeCb.setOnAction(e-> expertSettingsVBox.setDisable(! expertModeCb.isSelected()));
expertSettingsVBox.setDisable(!AppPreferences.getInstance().getExpertMode()); autoDetectIpCb.setSelected(preferences.getAutoDetectIp());
pcIpTextField.setDisable(preferences.getAutoDetectIp());
expertModeCb.setSelected(AppPreferences.getInstance().getExpertMode());
expertModeCb.setOnAction(e-> expertSettingsVBox.setDisable(!expertModeCb.isSelected()));
autoDetectIpCb.setSelected(AppPreferences.getInstance().getAutoDetectIp());
pcIpTextField.setDisable(AppPreferences.getInstance().getAutoDetectIp());
autoDetectIpCb.setOnAction(e->{ autoDetectIpCb.setOnAction(e->{
pcIpTextField.setDisable(autoDetectIpCb.isSelected()); pcIpTextField.setDisable(autoDetectIpCb.isSelected());
if (!autoDetectIpCb.isSelected()) if (! autoDetectIpCb.isSelected())
pcIpTextField.requestFocus(); pcIpTextField.requestFocus();
}); });
randPortCb.setSelected(AppPreferences.getInstance().getRandPort()); randPortCb.setSelected(preferences.getRandPort());
pcPortTextField.setDisable(AppPreferences.getInstance().getRandPort()); pcPortTextField.setDisable(preferences.getRandPort());
randPortCb.setOnAction(e->{ randPortCb.setOnAction(e->{
pcPortTextField.setDisable(randPortCb.isSelected()); pcPortTextField.setDisable(randPortCb.isSelected());
if (!randPortCb.isSelected()) if (! randPortCb.isSelected())
pcPortTextField.requestFocus(); pcPortTextField.requestFocus();
}); });
if (AppPreferences.getInstance().getNotServeRequests()){ if (preferences.getNotServeRequests()){
dontServeCb.setSelected(true); dontServeCb.setSelected(true);
autoDetectIpCb.setSelected(false); autoDetectIpCb.setSelected(false);
@ -121,7 +111,7 @@ public class SettingsController implements Initializable {
randPortCb.setDisable(true); randPortCb.setDisable(true);
pcPortTextField.setDisable(false); pcPortTextField.setDisable(false);
} }
pcExtraTextField.setDisable(!AppPreferences.getInstance().getNotServeRequests()); pcExtraTextField.setDisable(! preferences.getNotServeRequests());
dontServeCb.setOnAction(e->{ dontServeCb.setOnAction(e->{
if (dontServeCb.isSelected()){ if (dontServeCb.isSelected()){
@ -149,9 +139,9 @@ public class SettingsController implements Initializable {
} }
}); });
pcIpTextField.setText(AppPreferences.getInstance().getHostIp()); pcIpTextField.setText(preferences.getHostIp());
pcPortTextField.setText(AppPreferences.getInstance().getHostPort()); pcPortTextField.setText(preferences.getHostPort());
pcExtraTextField.setText(AppPreferences.getInstance().getHostExtra()); pcExtraTextField.setText(preferences.getHostExtra());
pcIpTextField.setTextFormatter(new TextFormatter<>(change -> { pcIpTextField.setTextFormatter(new TextFormatter<>(change -> {
if (change.getControlNewText().contains(" ") | change.getControlNewText().contains("\t")) if (change.getControlNewText().contains(" ") | change.getControlNewText().contains("\t"))
@ -180,36 +170,59 @@ public class SettingsController implements Initializable {
})); }));
newVersionLink.setVisible(false); newVersionLink.setVisible(false);
newVersionLink.setOnAction(e-> hs.showDocument(newVersionLink.getText())); newVersionLink.setOnAction(e-> hostServices.showDocument(newVersionLink.getText()));
autoCheckUpdCb.setSelected(AppPreferences.getInstance().getAutoCheckUpdates()); autoCheckUpdCb.setSelected(preferences.getAutoCheckUpdates());
Region btnSwitchImage = new Region(); Region btnSwitchImage = new Region();
btnSwitchImage.getStyleClass().add("regionUpdatesCheck"); btnSwitchImage.getStyleClass().add("regionUpdatesCheck");
checkForUpdBtn.setGraphic(btnSwitchImage); checkForUpdBtn.setGraphic(btnSwitchImage);
checkForUpdBtn.setOnAction(e->{ checkForUpdBtn.setOnAction(e->checkForUpdatesAction());
setDriversInstallFeature();
tfXciSpprtCb.setSelected(preferences.getTfXCI());
SettingsLanguagesSetup settingsLanguagesSetup = new SettingsLanguagesSetup();
langCB.setItems(settingsLanguagesSetup.getLanguages());
langCB.getSelectionModel().select(settingsLanguagesSetup.getRecentLanguage());
configureLanguageButton();
// Set supported old versions
glVersionChoiceBox.getItems().addAll(glSupportedVersions);
String oldVer = preferences.getGlVersion(); // Overhead; Too much validation of consistency
glVersionChoiceBox.getSelectionModel().select(oldVer);
}
private void checkForUpdatesAction(){
Task<List<String>> updTask = new UpdatesChecker(); Task<List<String>> updTask = new UpdatesChecker();
updTask.setOnSucceeded(event->{ updTask.setOnSucceeded(event->{
List<String> result = updTask.getValue(); List<String> result = updTask.getValue();
if (result != null){
if (result == null){
ServiceWindow.getInfoNotification(resourceBundle.getString("windowTitleNewVersionUnknown"),
resourceBundle.getString("windowBodyNewVersionUnknown"));
return;
}
if (result.get(0).isEmpty()){ if (result.get(0).isEmpty()){
ServiceWindow.getInfoNotification(resourceBundle.getString("windowTitleNewVersionNOTAval"), resourceBundle.getString("windowBodyNewVersionNOTAval")); ServiceWindow.getInfoNotification(resourceBundle.getString("windowTitleNewVersionNOTAval"),
resourceBundle.getString("windowBodyNewVersionNOTAval"));
return;
} }
else {
setNewVersionLink(result.get(0)); setNewVersionLink(result.get(0));
ServiceWindow.getInfoNotification(resourceBundle.getString("windowTitleNewVersionAval"), resourceBundle.getString("windowTitleNewVersionAval")+": "+result.get(0) + "\n\n" + result.get(1)); ServiceWindow.getInfoNotification(resourceBundle.getString("windowTitleNewVersionAval"),
} resourceBundle.getString("windowTitleNewVersionAval")+": "+result.get(0) + "\n\n" + result.get(1));
}
else {
ServiceWindow.getInfoNotification(resourceBundle.getString("windowTitleNewVersionUnknown"), resourceBundle.getString("windowBodyNewVersionUnknown"));
}
}); });
Thread updates = new Thread(updTask); Thread updates = new Thread(updTask);
updates.setDaemon(true); updates.setDaemon(true);
updates.start(); updates.start();
}); }
private void setDriversInstallFeature(){
if (isWindows()){ if (isWindows()){
Region btnDrvImage = new Region(); Region btnDrvImage = new Region();
btnDrvImage.getStyleClass().add("regionWindows"); btnDrvImage.getStyleClass().add("regionWindows");
@ -217,89 +230,20 @@ public class SettingsController implements Initializable {
drvInstBtn.setVisible(true); drvInstBtn.setVisible(true);
drvInstBtn.setOnAction(actionEvent -> new DriversInstall(resourceBundle)); drvInstBtn.setOnAction(actionEvent -> new DriversInstall(resourceBundle));
} }
tfXciSpprtCb.setSelected(AppPreferences.getInstance().getTfXCI());
// Language settings area
ObservableList<LocaleUiStringHolder> langCBObsList = FXCollections.observableArrayList();
//langCBObsList.add(new LocaleUiStringHolder(new Locale("en", "US")));
File jarFile;
try{
String encodedJarLocation = getClass().getProtectionDomain().getCodeSource().getLocation().getPath().replace("+", "%2B");
jarFile = new File(URLDecoder.decode(encodedJarLocation, "UTF-8"));
} }
catch (UnsupportedEncodingException uee){ private boolean isWindows(){
uee.printStackTrace(); return System.getProperty("os.name").toLowerCase().replace(" ", "").contains("windows");
jarFile = null;
} }
if(jarFile != null && jarFile.isFile()) { // Run with JAR file private void configureLanguageButton(){
try { langBtn.setOnAction(e->languageButtonAction());
JarFile jar = new JarFile(jarFile);
Enumeration<JarEntry> entries = jar.entries(); //gives ALL entries in jar
while (entries.hasMoreElements()) {
String name = entries.nextElement().getName();
if (name.startsWith("locale_")){
try{
langCBObsList.add(new LocaleUiStringHolder(name));
} }
catch (Exception e){ private void languageButtonAction(){
e.printStackTrace(); LocaleHolder localeHolder = langCB.getSelectionModel().getSelectedItem();
}
}
}
jar.close();
}
catch (IOException ioe){
ioe.printStackTrace(); // TODO: think about better solution?
}
}
else { // Run within IDE
URL resourceURL = this.getClass().getResource("/");
String[] filesList = new File(resourceURL.getFile()).list(); // Screw it. This WON'T produce NullPointerException
for (String jarFileName : filesList)
if (jarFileName.startsWith("locale_")){
try{
langCBObsList.add(new LocaleUiStringHolder(jarFileName));
}
catch (Exception e){
e.printStackTrace();
}
}
}
langCBObsList.sort(Comparator.comparing(LocaleUiStringHolder::toString));
langCB.setItems(langCBObsList);
// TODO: REFACTOR THIS SHIT; INCAPSULATE AND MOVE OUT FROM HERE
Locale localeFromPrefs = AppPreferences.getInstance().getLocale();
boolean notExists = true;
for (LocaleUiStringHolder holderItem: langCBObsList){
if (holderItem.getLocale().equals(localeFromPrefs)){
langCB.getSelectionModel().select(holderItem);
notExists = false;
break;
}
}
if (notExists)
langCB.getSelectionModel().select(0);
langBtn.setOnAction(e->{
LocaleUiStringHolder localeHolder = langCB.getSelectionModel().getSelectedItem();
AppPreferences.getInstance().setLocale(localeHolder.getLocaleCode()); AppPreferences.getInstance().setLocale(localeHolder.getLocaleCode());
Locale newLocale = localeHolder.getLocale(); Locale newLocale = localeHolder.getLocale();
ServiceWindow.getInfoNotification("", ServiceWindow.getInfoNotification("",
ResourceBundle.getBundle("locale", newLocale).getString("windowBodyRestartToApplyLang")); ResourceBundle.getBundle("locale", newLocale).getString("windowBodyRestartToApplyLang"));
});
// Set supported old versions
glVersionChoiceBox.getItems().addAll(glSupportedVersions);
String oldVer = AppPreferences.getInstance().getGlVersion(); // Overhead; Too much validation of consistency
glVersionChoiceBox.getSelectionModel().select(oldVer);
}
private boolean isWindows(){
return System.getProperty("os.name").toLowerCase().replace(" ", "").contains("windows");
} }
public boolean getNSPFileFilterForGL(){return nspFilesFilterForGLCB.isSelected(); } public boolean getNSPFileFilterForGL(){return nspFilesFilterForGLCB.isSelected(); }
@ -316,7 +260,7 @@ public class SettingsController implements Initializable {
public boolean getAutoCheckForUpdates(){ return autoCheckUpdCb.isSelected(); } public boolean getAutoCheckForUpdates(){ return autoCheckUpdCb.isSelected(); }
public boolean getTfXciNszXczSupport(){ return tfXciSpprtCb.isSelected(); } // Used also for NSZ/XCZ public boolean getTfXciNszXczSupport(){ return tfXciSpprtCb.isSelected(); } // Used also for NSZ/XCZ
public void registerHostServices(HostServices hostServices){this.hs = hostServices;} public void registerHostServices(HostServices hostServices){this.hostServices = hostServices;}
public void setNewVersionLink(String newVer){ public void setNewVersionLink(String newVer){
newVersionLink.setVisible(true); newVersionLink.setVisible(true);

View file

@ -18,25 +18,21 @@
*/ */
package nsusbloader.UI; package nsusbloader.UI;
import nsusbloader.cli.IncorrectSetupException;
import java.util.Locale; import java.util.Locale;
public class LocaleUiStringHolder { public class LocaleHolder {
private final Locale locale; private final Locale locale;
private final String localeCode; private final String localeCode;
private final String languageName; private final String languageName;
public LocaleUiStringHolder(Locale locale){ public LocaleHolder(Locale locale){
this.locale = locale; this.locale = locale;
this.localeCode = locale.toString(); this.localeCode = locale.toString();
this.languageName = locale.getDisplayLanguage(locale) + " (" + locale + ")"; this.languageName = locale.getDisplayLanguage(locale) + " (" + locale + ")";
} }
public LocaleUiStringHolder(String localeFileName) throws Exception{ public LocaleHolder(String localeFileName) {
if (localeFileName.length() < 12)
throw new IncorrectSetupException("Locale filename is incorrect: "+localeFileName);
String country = localeFileName.substring(7, 9); String country = localeFileName.substring(7, 9);
String language = localeFileName.substring(10, 12); String language = localeFileName.substring(10, 12);
this.locale = new Locale(country, language); this.locale = new Locale(country, language);

View file

@ -0,0 +1,129 @@
/*
Copyright 2019-2020 Dmitry Isaenko
This file is part of NS-USBloader.
NS-USBloader is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
NS-USBloader is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with NS-USBloader. If not, see <https://www.gnu.org/licenses/>.
*/
package nsusbloader.UI;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import nsusbloader.AppPreferences;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLDecoder;
import java.util.Comparator;
import java.util.Enumeration;
import java.util.Locale;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
public class SettingsLanguagesSetup {
private final ObservableList<LocaleHolder> languages;
private File thisApplicationFile;
private LocaleHolder recentlyUsedLanguageHolder;
public SettingsLanguagesSetup() {
this.languages = FXCollections.observableArrayList();
parseFiles();
sortLanguages();
defineRecentlyUsedLanguageHolder();
}
private void parseFiles() {
if (isApplicationIsJar()) // Executed as JAR file
parseFilesInsideJar();
else // Executed within IDE
parseFilesInFilesystem();
}
private boolean isApplicationIsJar() {
getThisApplicationFile();
return thisApplicationFile != null && thisApplicationFile.isFile();
}
private void getThisApplicationFile() {
try {
String encodedJarLocation =
getClass().getProtectionDomain().getCodeSource().getLocation().getPath().replace("+", "%2B");
this.thisApplicationFile = new File(URLDecoder.decode(encodedJarLocation, "UTF-8"));
} catch (UnsupportedEncodingException uee) {
uee.printStackTrace();
this.thisApplicationFile = null;
}
}
private void parseFilesInsideJar() {
try {
JarFile jar = new JarFile(thisApplicationFile);
Enumeration<JarEntry> entries = jar.entries(); //gives ALL entries in jar
while (entries.hasMoreElements()) {
String name = entries.nextElement().getName();
if (name.startsWith("locale_")) {
languages.add(new LocaleHolder(name));
}
}
jar.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
private void parseFilesInFilesystem() {
URL resourceURL = this.getClass().getResource("/");
String[] filesList = new File(resourceURL.getFile()).list(); // Screw it. This WON'T produce NullPointerException
for (String jarFileName : filesList) {
if (jarFileName.startsWith("locale_")) {
languages.add(new LocaleHolder(jarFileName));
}
}
}
private void sortLanguages() {
languages.sort(Comparator.comparing(LocaleHolder::toString));
}
private void defineRecentlyUsedLanguageHolder() {
Locale localeFromPreferences = AppPreferences.getInstance().getLocale();
for (LocaleHolder holder : languages) {
Locale holderLocale = holder.getLocale();
if (holderLocale.equals(localeFromPreferences)) {
this.recentlyUsedLanguageHolder = holder;
return;
}
}
// Otherwise define default one that is "en_US"
for (LocaleHolder holder : languages) {
if (holder.getLocaleCode().equals("en_US")) {
this.recentlyUsedLanguageHolder = holder;
return;
}
}
}
public ObservableList<LocaleHolder> getLanguages() {
return languages;
}
public LocaleHolder getRecentLanguage() {
return recentlyUsedLanguageHolder;
}
}