Persist dark theme setting and apply in vaadin 14 - java

Hello I want to apply the dark theme at the login of the user in Vaadin 14. But it does not work when i call the toggle function programmatically. I was following this example:
https://vaadin.com/learn/tutorials/toggle-dark-theme
The setting is already persisted, but how can i apply the theme setting? It works only when the trigger comes from a request thread. Here is my code:
/**
* Changes the theme from dark to light and vice versa
*/
private static void toogleTheme() {
boolean darkThemeEnabled = ConfigManager.isLightThemeEnabled();
ThemeList themeList = UI.getCurrent().getElement().getThemeList(); //
if (themeList.contains(Lumo.DARK)) { //
themeList.remove(Lumo.DARK);
themeList.add(Lumo.LIGHT);
} else {
themeList.remove(Lumo.LIGHT);
themeList.add(Lumo.DARK);
}
ConfigManager.setLightThemeEnabled(!darkThemeEnabled);
}
The method gets called from the change theme button.

You can read the value in the onAttach method. Here is a full example class which uses a cookie for storage:
public class HelloWorldView extends HorizontalLayout {
private static final String LIGHTMODE = "lightmode";
private Button toggleTheme;
public HelloWorldView() {
setMargin(true);
toggleTheme = new Button("Toggle theme between light and dark");
add(toggleTheme);
toggleTheme.addClickListener(e -> {
toggleTheme();
});
}
private void setThemeFromCookie() {
ThemeList themeList = UI.getCurrent().getElement().getThemeList();
if (isLightThemeOn()) {
if (themeList.contains(Lumo.DARK)) {
themeList.remove(Lumo.DARK);
}
themeList.add(Lumo.LIGHT);
} else {
if (themeList.contains(Lumo.LIGHT)) {
themeList.remove(Lumo.LIGHT);
}
themeList.add(Lumo.DARK);
}
}
private void toggleTheme() {
boolean saveLightTheme = true;
ThemeList themeList = UI.getCurrent().getElement().getThemeList();
if (themeList.contains(Lumo.DARK)) {
themeList.remove(Lumo.DARK);
themeList.add(Lumo.LIGHT);
} else {
themeList.remove(Lumo.LIGHT);
themeList.add(Lumo.DARK);
saveLightTheme = false;
}
setLightThemeInCookie(saveLightTheme);
}
private void setLightThemeInCookie(boolean b) {
Cookie myCookie = new Cookie(LIGHTMODE, b ? "true" : "false");
// Make cookie expire in 2 minutes
myCookie.setMaxAge(120);
myCookie.setPath(VaadinService.getCurrentRequest().getContextPath());
VaadinService.getCurrentResponse().addCookie(myCookie);
}
private String getLightModeCookieValue() {
for (Cookie c : VaadinService.getCurrentRequest().getCookies()) {
if ("lightmode".equals(c.getName())) {
String value = c.getValue();
return value;
}
}
return null;
}
private boolean isLightThemeOn() {
String value = getLightModeCookieValue();
if (value == null) {
setLightThemeInCookie(true);
return true;
}
return "true".equals(value);
}
#Override
protected void onAttach(AttachEvent attachEvent) {
setThemeFromCookie();
super.onAttach(attachEvent);
}
}

Related

Midi Device Retrieve the pressed notes

I'm trying to create a plugin in java for Unity, I have already succeeded to fetch and get all connected midi devices, but now I'm stuck to get the pressed notes.
On java side I have theses classes :
public class UnityMidiAndroid {
private static UnityMidiAndroid _instance = new UnityMidiAndroid();
private static final String LOGTAG = "UnityMidiAndroid";
private MidiManager manager = null;
private MidiDeviceInfo[] midiDeviceInfos;
private MidiOutputPort midiOutputPort;
private final UnityMidiAndroidReceiver midiReceiver;
private MidiCallback midiCallback = null;
private UnityMidiAndroid()
{
Log.i(LOGTAG, "Ctor Created new UnityMidiAndroid");
midiReceiver = new UnityMidiAndroidReceiver();
}
public static UnityMidiAndroid getInstance()
{
return (_instance);
}
public void ctor(MidiCallback callback, Activity activity)
{
Context context = activity.getApplicationContext();
manager = (MidiManager) context.getSystemService(MIDI_SERVICE);
midiCallback = callback;
}
public String[] fetchDevices()
{
midiDeviceInfos = manager.getDevices();
String[] availableDevices = new String[midiDeviceInfos.length];
for (int i = 0; i < midiDeviceInfos.length; i++) {
Bundle property = midiDeviceInfos[i].getProperties();
String deviceName = property.getString(MidiDeviceInfo.PROPERTY_PRODUCT);
if (deviceName != null)
availableDevices[i] = deviceName;
}
return (availableDevices);
}
public void openDeviceAtIndex(int index)
{
if (midiDeviceInfos == null || midiDeviceInfos.length == 0)
midiDeviceInfos = manager.getDevices();
if (midiDeviceInfos.length == 0)
return;
openDevice(midiDeviceInfos[0]);
}
private void openDevice(MidiDeviceInfo deviceInfo)
{
if (deviceInfo == null)
return;
manager.openDevice(deviceInfo, device -> {
if (device == null)
Log.e(LOGTAG, "couldn't open " + deviceInfo.toString());
else {
midiOutputPort = device.openOutputPort(0);
if (midiOutputPort == null)
Log.e(LOGTAG, "couln't open input port on " + device);
midiOutputPort.connect(midiReceiver);
}
}, null);
}
private class UnityMidiAndroidReceiver extends MidiReceiver {
#Override
public void onSend(byte[] msg, int offset, int count, long timestamp) throws IOException {
if (midiCallback == null)
throw new IOException("midiCallback = null");
midiCallback.MidiMessage(0, msg);
midiReceiver.send(msg, offset, count);
}
}
public interface MidiCallback {
void MidiMessage(int index, byte[] data);
}
On Unity side I have these classes :
public class UnityMidiAndroidCallBack : AndroidJavaProxy
{
public UnityMidiAndroidCallBack() : base("com.test.unitymidianrdoid.MidiCallback")
{
}
public void MidiMessage(int index, byte[] data)
{
UnityMidiAndroidInputs.str += "NewNote__"; //static property for debug when new note is pressed
}
}
public class UnityMidiAndroid
{
private const string PluginName = "com.test.unitymidianrdoid.UnityMidiAndroid";
private const string UnityPlayer = "com.unity3d.player.UnityPlayer";
private static AndroidJavaClass _pluginClass;
private static AndroidJavaObject _pluginInstance;
private static UnityMidiAndroidCallBack _callBack;
public UnityMidiAndroid()
{
_callBack = new UnityMidiAndroidCallBack();
AndroidJavaClass unityPlayer = new AndroidJavaClass(UnityPlayer);
AndroidJavaObject activity = unityPlayer.GetStatic<AndroidJavaObject>("currentActivity");
PluginInstance.Call("ctor", _callBack, activity);
PluginInstance.Call("openDeviceAtIndex", 0);
}
private static AndroidJavaClass PluginClass
{
get { return _pluginClass ??= new AndroidJavaClass(PluginName); }
}
private static AndroidJavaObject PluginInstance
{
get { return _pluginInstance ??= PluginClass.CallStatic<AndroidJavaObject>("getInstance"); }
}
public string[] GetAvailableDevices()
{
return (PluginInstance.Call<string[]>("fetchDevices"));
}
}
The problem is (I think) the callback function is never triggered, but I don't know why..
For the moment I don't want to know which note is pressed, I just want to trigger the callback when a note is pressed
PS: Sorry for my bad english

Button icon that changes according to the row of a TableView javafx

I wanted to add a column if the line wasn't empty. In this one I wanted to put buttons with different ImageView to be able to go to an add or view page.
I'm trying to change the icon of a button according to the content of my row in a TableView (here if dateR (string) is null)
I manage to move it to such and such a page depending on the dateR value, but I can't change the imageView...
Thanks
TableColumn<ModelTab4, Void> visualiserAjouter = new TableColumn<ModelTab4, Void>("Visualiser/Ajouter");
Callback<TableColumn<ModelTab4, Void>, TableCell<ModelTab4, Void>> cellFactory1 = (final TableColumn<ModelTab4, Void> param) -> {
final TableCell<ModelTab4, Void> cell = new TableCell<ModelTab4, Void>() {
private String dateR;
private final Button btn1 = new Button();
{
btn1.setOnAction(click -> {
try {
ModelTab4 analyse = getTableView().getItems().get(getIndex());
dateR = analyse.getDateR();
setDate(dateR);
idAnalyse = analyse.getNum1();
if (dateR!=null){
mainApp.goConsultResult(idPerso, idPatient, idAnalyse);
}
else {
mainApp.goAjoutResult(idPerso, idPatient, idAnalyse);
}
} catch (Exception e) {
e.printStackTrace();
}
});
}
public void setDate(String date) {
this.dateR = date;
}
public String getDate() {
return dateR;
}
public void updateItem(Void item, boolean empty) {
super.updateItem(item, empty);
if (empty) {
setGraphic(null);
}
else {
if (getDate()!=null){
setGraphic(btn1);
ImageView icone1 = new ImageView("consult.png");
icone1.setFitHeight(20);
icone1.setFitWidth(20);
btn1.setGraphic(icone1);
setStyle("-fx-alignment : CENTER;");
}
else if (getDate()==null){
setGraphic(btn1);
ImageView icone2 = new ImageView("ajout.png");
icone2.setFitHeight(20);
icone2.setFitWidth(20);
btn1.setGraphic(icone2);
setStyle("-fx-alignment : CENTER;");
}
}
}
};
return cell;
};
Assuming your ModelTab4 class includes the following:
public class ModelTab4 {
private final StringProperty dateR = new SimpleStringProperty() ;
public StringProperty dateRProperty() {
return dateR ;
}
public final String getDateR() {
return dateRProperty().get();
}
public final void setDateR(String dateR) {
dateRProperty().set(dateR);
}
// other properties ...
}
you should make the value in the visualiserAjouter column the dateR property:
TableColumn<ModelTab4, String> visualiserAjouter = new TableColumn<>("Visualiser/Ajouter");
visualiserAjouter.setCellValueFactory(cellData -> cellData.getValue().dateRProperty());
Now the item in the cell implementation is the dateR property. The issue with the code the way you had it, is that the only way the property changes is after the button is pressed, and there is no notification back to the cell that the value has changed. So in updateItem() you're checking the value of dateR before is has had a chance to change. With the setup above, you can now do:
final TableCell<ModelTab4, Void> cell = new TableCell<ModelTab4, Void>() {
private final Button btn1 = new Button();
{
btn1.setOnAction(click -> {
try {
ModelTab4 analyse = getTableView().getItems().get(getIndex());
idAnalyse = analyse.getNum1();
if (getItem()!=null){
mainApp.goConsultResult(idPerso, idPatient, idAnalyse);
}
else {
mainApp.goAjoutResult(idPerso, idPatient, idAnalyse);
}
} catch (Exception e) {
e.printStackTrace();
}
});
}
public void updateItem(String dateR, boolean empty) {
super.updateItem(item, empty);
if (empty) {
setGraphic(null);
}
else {
if (dateR!=null){
setGraphic(btn1);
ImageView icone1 = new ImageView("consult.png");
icone1.setFitHeight(20);
icone1.setFitWidth(20);
btn1.setGraphic(icone1);
setStyle("-fx-alignment : CENTER;");
}
else if (dateR==null){
setGraphic(btn1);
ImageView icone2 = new ImageView("ajout.png");
icone2.setFitHeight(20);
icone2.setFitWidth(20);
btn1.setGraphic(icone2);
setStyle("-fx-alignment : CENTER;");
}
}
}
};

MaterialEditText RegexpValidator

How do I get this code to check if the input is valid and set z2 = true, if the input in valid instead of the charSequence.length?
I am using this lib:
https://github.com/rengwuxian/MaterialEditText
this.inputDisplayName.addValidator(new RegexpValidator("You can only use Laters and Numbers", "^[a-zA-Z0-9]*$"){
public boolean isValid(CharSequence charSequence, boolean z) {
boolean z2 = false;
if (TextUtils.isEmpty(charSequence)) {
RegisterActivity.this.displaynameVerified = false;
} else {
RegisterActivity registerActivity = RegisterActivity.this;
if (charSequence.length() >= 8) {
z2 = true;
}
registerActivity.displaynameVerified = z2;
}
RegisterActivity.this.validateInput();
return true;
}
});
You're overriding the RegexValidation entirely to do nothing with the regex given.
Personally, I would suggest you extend it and add a callback using an interface.
/*
* Add these inside the class
*/
private static interface ValidCallback {
public void isValid(Boolean valid);
}
private static class NumberLetterValidator extends RegexpValidator {
private ValidCallback c;
public NumberLetterValidator(ValidCallback c) {
super("You can only use Laters and Numbers", "^[a-zA-Z0-9]*$");
this.c = c;
}
#Override
public boolean isValid(CharSequence charSequence, boolean isEmpty) {
boolean valid = super.isValid(charSequence, isEmpty);
if (c != null) c.isValid(valid);
return valid;
}
}
Then, you can pass your custom logic through there.
ValidCallback cb = new ValidCallback() {
#Override
public void isValid(Boolean b) {
displaynameVerified = b;
validateInput();
}
};
this.inputDisplayName.addValidator(new NumberLetterValidator(cb));

How to set Root checkbox selected when every child is selected(GWT)

I am building GWT app where I have Tree and TreeItems with CheckBoxes. I have one root CheckBox called allCheckBox and his child elements rootCheckBox(this checkBoxes also have theirs children but that is not matter for this). I want that, when user opens dialog with checkBoxes, this checkBox is selected if every childCheckBox is selected. I have done that when tihs root checkBox is selected that child checkBoxes also are selected.
This is my piece of code:
enter cod GWT_DOMAIN_SERVICE.findAll(new AsyncCallback<List<GwtDomain>>() {
#Override
public void onFailure(Throwable caught) {
exitMessage = MSGS.dialogAddPermissionErrorDomains(caught.getLocalizedMessage());
exitStatus = false;
hide();
}
#Override
public void onSuccess(List<GwtDomain> result) {
for (final GwtDomain gwtDomain : result) {
GWT_DOMAIN_SERVICE.findActionsByDomainName(gwtDomain.name(), new AsyncCallback<List<GwtAction>>() {
#Override
public void onFailure(Throwable caught) {
exitMessage = MSGS.dialogAddPermissionErrorActions(caught.getLocalizedMessage());
exitStatus = false;
hide();
}
#Override
public void onSuccess(List<GwtAction> result) {
checkedItems = new GwtCheckedItems();
checkedItems.setName(gwtDomain);
rootCheckBox = new CheckBox();
rootCheckBox.setBoxLabel(gwtDomain.toString());
listCheckBoxes.add(rootCheckBox);
rootTreeItem = new TreeItem(rootCheckBox);
childCheckBoxMapList = new HashMap<GwtAction, CheckBox>();
checkedItems.setMap(childCheckBoxMapList);
for (GwtAccessPermission gwtAccessPermission : checkedPermissionsList) {
if (gwtAccessPermission.getPermissionDomain().toString().equals(checkedItems.getName().toString())) {
if (gwtAccessPermission.getPermissionAction().toString().equals(GwtAction.ALL.toString())) {
rootCheckBox.setValue(true);
}
}
}
if (listOfNewClass.size() == checkedPermissionsList.size()) {
allCheckBox.setValue(true);
}
for (final GwtAction gwtAction : result) {
final CheckBox childTreeItemCheckox = new CheckBox();
treeItem = new TreeItem(childTreeItemCheckox);
childTreeItemCheckox.setBoxLabel(gwtAction.toString());
rootTreeItem.addItem(treeItem);
childListOfNewClass.add(gwtAction);
allTreeItem.addItem(rootTreeItem);
childCheckBoxMapList.put(gwtAction, childTreeItemCheckox);
for (GwtAccessPermission gwtAccessPermission : checkedPermissionsList) {
if (gwtAccessPermission.getPermissionDomain().toString().equals(gwtDomain.toString())) {
if (gwtAccessPermission.getPermissionAction().toString().equals(gwtAction.toString())) {
childTreeItemCheckox.setValue(true);
}
}
}
}
listOfNewClass.put(checkedItems, rootCheckBox);
}
});
}
allCheckBox.addListener(Events.OnClick, new Listener<BaseEvent>() {
#Override
public void handleEvent(BaseEvent be) {
if (allCheckBox.getValue()) {
for (CheckBox checkBox : listCheckBoxes) {
if (!checkBox.getValue()) {
checkBox.setValue(true);
}
}
} else {
for (CheckBox checkBox : listCheckBoxes) {
checkBox.setValue(false);
}
}
}
});
How to set that when all rootCheckBoxes are checked then allCheckBox become also checked?
EDIT: This checkedPermissionsList is List of rootCheckBox which are checked.
Well the listener would have to iterate the child boxes and see if they are all selected, and set the parent box accordingly
Listener<BaseEvent> listener = new Listener<>() {
public void handleEvent(BaseEvent be) {
boolean allSet = listCheckBoxes.stream().allMatch(CheckBox::getValue);
allCheckBox.setValue(allSet); // this will also unselect if appropriate
}
}
It's the same listener for all boxes, so add it to each
listCheckBoxes.forEach(box -> box.addListener(Event.OnClick, listener));
In the pre-Java 8 version:
Listener<BaseEvent> listener = new Listener<>() {
public void handleEvent(BaseEvent be) {
boolean allSet = true;
for (CheckBox child : listCheckBoxes) {
if (!child.getValue()) {
allSet = false; // found a non-checked box
break;
}
}
allCheckBox.setValue(allSet); // this will also unselect if appropriate
}
// and set the listener to the children with
for (CheckBox box : listCheckBoxes) {
box.addListener(Event.Clicked, listener);
}

RxJava: how to turn a complicated if statement into a reactive stream?

I am implementing an app introduction and waiver that should appear before the user can access the MainActivity of my Android app. If the user has not accepted the waiver or gone through the app introduction, then my IntroNavigator kicks them back to those activities.
How can I rxify my redirectIfNecessary() method in a more functional manner, instead of the imperative approach I implemented below.
IntroNavigatorImpl.java
public class IntroNavigatorImpl implements IntroNavigator {
WeakReference<Activity> activityWeakReference;
CloudPrefsRepo cloudPrefsRepo;
public IntroNavigatorImpl(Activity activity, CloudPrefsRepo cloudPrefsRepo) {
this.activityWeakReference = new WeakReference<>(activity);
this.cloudPrefsRepo = cloudPrefsRepo;
}
#Override
public void redirectIfNecessary() {
final boolean shouldShowAppIntro = cloudPrefsRepo.shouldShowAppIntro()
.toObservable().toBlocking().first();
final boolean shouldShowWaiver = cloudPrefsRepo.shouldShowWaiver()
.toObservable().toBlocking().first();
if (shouldShowAppIntro) {
showAppIntro();
finishActivity();
} else if (shouldShowWaiver) {
showWaiver();
finishActivity();
} else {
//do nothing
}
}
#Override
public void showWaiver() {
//launch waiver activity
}
#Override
public void showAppIntro() {
//launch app intro activity
}
public void finishActivity() {
if (activityWeakReference.get() != null) {
activityWeakReference.get().finish();
}
}
}
CloudPrefsRepo.java
public interface
/**
* Whether to show the app intro.
*/
Single<Boolean> shouldShowAppIntro();
/**
* Whether to show the waiver. If the user has already
* accepted this waiver, then it shouldn't be shown.
*/
Single<Boolean> shouldShowWaiver();
Edit Based on comment:
It's not the prettiest (I'm leaning towards there not being a good reactive way to do this)
final Action0 showInfoAction = new Action0() {
#Override
public void call() {
showAppIntro();
finishActivity();
}
};
final Action0 showWaiverAction = new Action0() {
#Override
public void call() {
showWaiver();
finishActivity();
}
};
final Action0 blankAction = new Action0() {
#Override
public void call() {
}
};
Observable.zip(shouldShowInfo, shouldShowWaiver, new Func2<Boolean, Boolean, Action0>() {
#Override
public Action0 call(Boolean shoudlShowInfo, Boolean shouldShowWaiver) {
if (shoudlShowInfo) {
return showInfoAction;
} else if (shouldShowWaiver) {
return showWaiverAction;
} else {
return blankAction;
}
}
}).subscribe(new Action1<Action0>() {
#Override
public void call(Action0 action0) {
action0.call();
}
});

Categories