Change themes in Vaadin 7 via code - themes

I am doing a project in Vaadin 7. In that I need to change the theme of a page.
In Vaadin 6, there is a function called 'setTheme()'. so that I can change the theme using that function wherever I want in my code.
But, In Vaadin 7, I couldn't find any like that.
I know there will be a way to do it.
And also how to apply changes on the UI when I change a theme?
Will it be changed automatically? (or)
ICEPush gonna help me?

In Vaadin 7 the method 'setTheme()' has been replaced with the new Annotation #Theme. The "on the fly theme change" is not possible in Vaadin 7.
There is a disucssion in this Vaadin Forum Thread about the on fly theme change in Vaadin 7. You should have a look on it.

setTheme functionality has been introduced in Vaadin 7.3.0: https://vaadin.com/wiki/-/wiki/Main/Changing+theme+on+the+fly

you can try this for Vaadin 7:
Create your own UIProvider
Register your UIProvider in root UI
Switch theme in UIProvider and trigger page reload
DynamicThemeUIProvider.java
public class DynamicThemeUIProvider extends UIProvider {
private String currentTheme = "reindeer";
#Override
public Class<? extends UI> getUIClass(UIClassSelectionEvent event) {
return DemoUI.class;
}
public void setTheme(String theme) {
currentTheme = theme;
}
public String getTheme(UICreateEvent event) {
return currentTheme;
}
}
DemoUI.java
public class DemoUI extends UI {
private DynamicThemeUIProvider provider;
#Override
protected void init(VaadinRequest request) {
provider = new DynamicThemeUIProvider();
getSession().addUIProvider(provider);
}
public DynamicThemeUIProvider getDynamicThemeUIProvider() {
return provider;
}
}
Then on a component which switches the theme:
#Override
public void valueChange(ValueChangeEvent event) {
DemoUI ui = (DemoUI) getUI();
DynamicThemeUIProvider uiProvider = ui.getDynamicThemeUIProvider();
if (uiProvider == null) {
return;
}
uiProvider.setTheme("reindeer");
try {
String value = (String) event.getProperty().getValue();
uiProvider.setTheme(value.toLowerCase());
} catch (Exception e) {
e.printStackTrace();
}
ui.getPage().getJavaScript().execute("document.location.reload(true)"); // page refresh
}

Since I used custom themes, I have made it pretty simple. I used a toggle button and executed the required piece of code every time.
JavaScript.getCurrent().execute("document.body.className = document.body.className.replace(\"theme1\",\"theme2\"); ");
JavaScript.getCurrent().execute("document.body.className = document.body.className.replace(\"theme2\",\"theme1\"); ");
My css file will be like this.
.theme1 .v-button {
/* some css attribute */
}
.theme2 .v-button {
/* some css attribute */
}
Believe me; the theme switch is very very fast since the browser itself do the trick to switch the theme rather than asking the Vaadin server to do the switch.

Regarding themes for charts:
simply have a switch somewhere inside a listener of either a ComboBox or an OptionGroup (for radio buttons) to make a the following ChartOptions static method call, e.g.:
ChartOptions.get().setTheme(new VaadinTheme())
then
ChartOptions.get().setTheme(new SkiesTheme())
etc.
there's also GridTheme(); GrayTheme() and HighChartsDefaultTheme(); you can even extend the base theme to create your own theme (look that up in the Book of Vaadin).

Since Vaadin 7.3 you can use UI#setTheme()

In Vaadin 7 and higher Versions we have an Annotation called #Theme(yourThemeName)
based on the Theme name which you give here it will redirect to that specific .scss Style.This annotation is called before the Init method is called.

Related

Automatic horizontal scroll on javafx TableView

If I scroll on my table to the right it will automatically scroll back to the left. I have no own implementation for scrolling, all is done by the TableView. Has anyone seen this before? If I test it on windows I have no issue.
compile "org.javafxports:jfxdvk:8.60.13"
javafxportsVersion = '8.60.13'
This issue is more related to javafx. If the "IS_TOUCH_SUPPORTED" flag is set the scroll bar is set to visible false after use (VirtualFlow). A change listener onVisible does then a updateHbar(). And because of hbar.isVisible() the scroll var value is set to 0.
I did not want to change "IS_TOUCH_SUPPORTED". That's why I create a own skin which only creates a custom virtual flow. The custom virtual flow is also very simple I only set the tempVisibility to true via reflection. And I also overwrite the startSBReleasedAnimation() method and do nothing inside.
public class CustomVirtualFlow<T extends IndexedCell<?>> extends VirtualFlow<T> {
public CustomVirtualFlow() {
super();
try {
final Field field = VirtualFlow.class.getDeclaredField("tempVisibility");
field.setAccessible(true);
field.setBoolean(this, true);
} catch (final Exception e) {
}
}
/*
* (non-Javadoc)
*
* #see com.sun.javafx.scene.control.skin.VirtualFlow#startSBReleasedAnimation()
*/
#Override
protected void startSBReleasedAnimation() {
// do not call the super.startSBReleasedAnimation()
}

How to log in to Facebook in Xamarin.Forms

I want to make a Xamarin.Forms project, targeting iOS, Android and Windows Phone.
My app needs to authenticate users using Facebook.
Should I implement login for each platform independently, or use a manual flow?
https://developers.facebook.com/docs/facebook-login/manually-build-a-login-flow/v2.0
I prefer to have a single implementation of the login flow, and use it on all platforms.
How can I get a single implementaion of the Facebook login flow?
UPDATE (10/24/17): While this way of doing things was okay a few years ago, I now strongly advocate for using native UI for doing authentication, as opposed to the webview method shown here. Auth0 is a great way to accomplish native UI login for your apps, using a wide variety of identity providers:
https://auth0.com/docs/quickstart/native/xamarin
EDIT: I finally put a sample for this on Gihub
I posted an answer on the Xamarin Forums. I'll repeat it here.
Let's start with the core of the app, the Xamarin.Forms PCL project. Your App class will look something like this:
namespace OAuth2Demo.XForms
{
public class App
{
static NavigationPage _NavPage;
public static Page GetMainPage ()
{
var profilePage = new ProfilePage();
_NavPage = new NavigationPage(profilePage);
return _NavPage;
}
public static bool IsLoggedIn {
get { return !string.IsNullOrWhiteSpace(_Token); }
}
static string _Token;
public static string Token {
get { return _Token; }
}
public static void SaveToken(string token)
{
_Token = token;
}
public static Action SuccessfulLoginAction
{
get {
return new Action (() => {
_NavPage.Navigation.PopModalAsync();
});
}
}
}
}
The first thing to notice is the GetMainPage() method. This tells the app which screen it should load first upon launching.
We also have a simple property and method for storing the Token that is returned from the auth service, as well as a simple IsLoggedIn property.
There's an Action property as well; something I stuck in here in order to have a way for the platform implementations to perform a Xamarin.Forms navigation action. More on this later.
You'll also notice some red in your IDE because we haven't created the ProfilePage class yet. So, let's do that.
Create a very simple ProfilePage class in the Xamarin.Forms PCL project. We're not even going to do anything fancy with it because that will depend on your particular need. For the sake of simplicity in this sample, it will contain a single label:
namespace OAuth2Demo.XForms
{
public class ProfilePage : BaseContentPage
{
public ProfilePage ()
{
Content = new Label () {
Text = "Profile Page",
VerticalOptions = LayoutOptions.CenterAndExpand,
HorizontalOptions = LayoutOptions.CenterAndExpand,
};
}
}
}
Again, you'll probably have some red in your IDE because we seem to be missing the BaseContentPage class. The sole purpose of the BaseContentPage class is to ensure that none of the app's screens can be displayed until the user has logged in. (In this simplified demo, we're just persisting the user info to memory, so you'll need to re-login every time the app is run. In a real-world app, you'd be storing the authenticated user info to the device's keychain, which would eliminate the need to login at each app start.)
Create a BaseContentPage class in the Xamarin.Forms PCL project:
namespace OAuth2Demo.XForms
{
public class BaseContentPage : ContentPage
{
protected override void OnAppearing ()
{
base.OnAppearing ();
if (!App.IsLoggedIn) {
Navigation.PushModalAsync(new LoginPage());
}
}
}
}
There's a few interesting things going on here:
We're overriding the OnAppearing() method, which is similar to the ViewWillAppear method in an iOS UIViewController. You can execute any code here that you'd like to have run immediately before the screen appears.
The only thing we're doing in this method is checking to see if the user is logged in. If they're not, then we perform a modal push to a class called LoginPage. If you're unfamiliar with the concept of a modal, it's simply a view that takes the user out of the normal application flow in order to perform some special task; in our case, to perform a login.
So, let's create the LoginPage class in the Xamarin.Forms PCL project:
namespace OAuth2Demo.XForms
{
public class LoginPage : ContentPage
{
}
}
Wait...why doesn't this class have a body???
Since we're using the Xamatin.Auth component (which does the job of building and presenting a web view that works with the provided OAuth2 info), we actually don't want any kind of implementation in our LoginPage class. I know that seems weird, but bear with me.
The LoginPageRenderer for iOS
Up until this point, we've been working solely in the Xamarin.Forms PCL project. But now we need to provide the platform-specific implementation of our LoginPage in the iOS project. This is where the concept of a Renderer comes in.
In Xamarin.Forms, when you want to provide platform-specific screens and controls (i.e. screens that do not derive their content from the abstract pages in the Xamarin.Forms PCL project), you do so with Renderers.
Create a LoginPageRenderer class in your iOS platform project:
[assembly: ExportRenderer (typeof (LoginPage), typeof (LoginPageRenderer))]
namespace OAuth2Demo.XForms.iOS
{
public class LoginPageRenderer : PageRenderer
{
public override void ViewDidAppear (bool animated)
{
base.ViewDidAppear (animated);
var auth = new OAuth2Authenticator (
clientId: "", // your OAuth2 client id
scope: "", // the scopes for the particular API you're accessing, delimited by "+" symbols
authorizeUrl: new Uri (""), // the auth URL for the service
redirectUrl: new Uri ("")); // the redirect URL for the service
auth.Completed += (sender, eventArgs) => {
// We presented the UI, so it's up to us to dimiss it on iOS.
App.SuccessfulLoginAction.Invoke();
if (eventArgs.IsAuthenticated) {
// Use eventArgs.Account to do wonderful things
App.SaveToken(eventArgs.Account.Properties["access_token"]);
} else {
// The user cancelled
}
};
PresentViewController (auth.GetUI (), true, null);
}
}
}
}
There are important things to note:
The [assembly: ExportRenderer (typeof (LoginPage), typeof (LoginPageRenderer))] line at the top (and importantly before the namespace declaration) is using the Xamarin.Forms DependencyService. It's not the most beautiful thing in the world because it's not IoC/DI, but whatever...it works. This is the mechanism that "maps" our LoginPageRenderer to the LoginPage.
This is the class in which we're actually using the Xamarin.Auth component. That's where the OAuth2Authenticator reference comes from.
Once the login is successful, we fire off a Xamarin.Forms navigation via App.SuccessfulLoginAction.Invoke();. This gets us back to the ProfilePage.
Since we're on iOS, we're doing all of our logic sinde of the ViewDidAppear() method.
The LoginPageRenderer for Android
Create a LoginPageRenderer class in your Android platform project. (Note that class name you're creating is identical to the one in the iOS project, but here in the Android project the PageRenderer inherits from Android classes instead of iOS classes.)
[assembly: ExportRenderer (typeof (LoginPage), typeof (LoginPageRenderer))]
namespace OAuth2Demo.XForms.Android
{
public class LoginPageRenderer : PageRenderer
{
protected override void OnModelChanged (VisualElement oldModel, VisualElement newModel)
{
base.OnModelChanged (oldModel, newModel);
// this is a ViewGroup - so should be able to load an AXML file and FindView<>
var activity = this.Context as Activity;
var auth = new OAuth2Authenticator (
clientId: "", // your OAuth2 client id
scope: "", // the scopes for the particular API you're accessing, delimited by "+" symbols
authorizeUrl: new Uri (""), // the auth URL for the service
redirectUrl: new Uri ("")); // the redirect URL for the service
auth.Completed += (sender, eventArgs) => {
if (eventArgs.IsAuthenticated) {
App.SuccessfulLoginAction.Invoke();
// Use eventArgs.Account to do wonderful things
App.SaveToken(eventArgs.Account.Properties["access_token"]);
} else {
// The user cancelled
}
};
activity.StartActivity (auth.GetUI(activity));
}
}
}
Again, let's take a look at some interesting things:
The [assembly: ExportRenderer (typeof (LoginPage), typeof (LoginPageRenderer))] line at the top (and importantly before the namespace declaration) is using the Xamarin.Forms DependencyService. No difference here from the iOS version of LoginPageRenderer.
Again, this is where we're actually using the Xamarin.Auth component. That's where the OAuth2Authenticator reference comes from.
Just as with the iOS version, once the login is successful, we fire off a Xamarin.Forms navigation via App.SuccessfulLoginAction.Invoke();. This gets us back to the ProfilePage.
Unlike the iOS version, we're doing all of the logic inside of the OnModelChanged() method instead of the ViewDidAppear().
Here it is on iOS:
...and Android:
UPDATE:
I've also provided a detailed sample at my blog: http://www.joesauve.com/using-xamarin-auth-with-xamarin-forms/
You could consume either Xamarin.Social or Xamarin.Auth for that. It allows using the same api whatever the platform is.
As of now, those libs aren't PCL yet, but you still can consume them from a Shared Assets Project, or abstract the API you need in an interface and inject in with DependencyService or any other DI container.
I've created a sample project to show how to create a Facebook login using native Facebook component, not through a webview like the solutions suggested here.
You can check it out in this address:
https://github.com/IdoTene/XamarinFormsNativeFacebook
IOS 8: For those who are using #NovaJoe code and are stuck on view, add the code bellow to workaround:
bool hasShown;
public override void ViewDidAppear(bool animated)
{
if (!hasShown)
{
hasShown = true;
// the rest of #novaJoe code
}
}
Here's a good Xamarin.Forms authentication sample. The documentation in the code is nice. It uses a webview to render the login screen, but you can select what login type you want. It also saves a users token so he doesn't have to keep re-logging in.
https://github.com/rlingineni/Xamarin.Forms_Authentication
Another addition to #NovaJoe's code, on iOS8 with Facebook, you'd need to modify the Renderer class as below to close the View after successful authentication.
auth.Completed += (sender, eventArgs) => {
// We presented the UI, so it's up to us to dimiss it on iOS.
/*Importand to add this line */
DismissViewController (true, null);
/* */
if (eventArgs.IsAuthenticated) {
App.Instance.SuccessfulLoginAction.Invoke ();
// Use eventArgs.Account to do wonderful things
App.Instance.SaveToken (eventArgs.Account.Properties ["access_token"]);
} else {
// The user cancelled
}
};
The correct implementation for the Androids PageRenderer is:
using System;
using Android.App;
using Android.Content;
using OAuth2Demo.XForms.Android;
using Xamarin.Auth;
using Xamarin.Forms;
using Xamarin.Forms.Platform.Android;
using XamarinAuth;
[assembly: ExportRenderer(typeof(LoginPage), typeof(LoginPageRenderer))]
namespace OAuth2Demo.XForms.Android
{
public class LoginPageRenderer : PageRenderer
{
public LoginPageRenderer(Context context) : base(context) { }
protected override void OnElementChanged(ElementChangedEventArgs<Page> e)
{
base.OnElementChanged(e);
// this is a ViewGroup - so should be able to load an AXML file and FindView<>
var activity = this.Context as Activity;
var auth = new OAuth2Authenticator(
clientId: "<Constants.clientId>", // your OAuth2 client id
scope: "<Constants.scope>", // the scopes for the particular API you're accessing, delimited by "+" symbols
authorizeUrl: new Uri("<Constants.authorizeUrl>"), // the auth URL for the service
redirectUrl: new Uri("<Constants.redirectUrl>")); // the redirect URL for the service
auth.Completed += (sender, eventArgs) =>
{
if (eventArgs.IsAuthenticated)
{
App.SuccessfulLoginAction.Invoke();
// Use eventArgs.Account to do wonderful things
App.SaveToken(eventArgs.Account.Properties["access_token"]);
}
else
{
// The user cancelled
}
};
activity.StartActivity(auth.GetUI(activity));
}
}
}

How to add DropListener to drop text in a draw2d Label

I am Trying to add a dropListener so I can Drop and text into a draw2d Label ,in GEf Editor , Can anyone help how Can I do that. An example will be great.
To respond to drop events on a GEF edit part viewer you have to install on the viewer itself an implementation of org.eclipse.jface.util.TransferDropTargetListener that understands transfers of type org.eclipse.swt.dnd.TextTransfer and that creates some kind of org.eclipse.gef.Request that can be handled by an org.eclipse.gef.EditPolicy installed on the target org.eclipse.gef.EditPart.
You have to understand that both the Request and the EditPolicy allow you to customize the drop behavior on a EditPart basis. As a consequence, I can show you an example that is actually fully functional, but feel free to customize it to your real needs.
First create the TransferDropTargetListener:
public class TextTransferDropTargetListener extends AbstractTransferDropTargetListener {
public TextTransferDropTargetListener(EditPartViewer viewer) {
super(viewer, TextTransfer.getInstance());
}
#Override
protected void handleDragOver() {
getCurrentEvent().feedback = DND.FEEDBACK_SCROLL | DND.FEEDBACK_EXPAND;
super.handleDragOver();
}
#Override
protected Request createTargetRequest() {
return new ChangeBoundsRequest(REQ_ADD);
}
#Override
protected void updateTargetRequest() {
ChangeBoundsRequest request = (ChangeBoundsRequest) getTargetRequest();
request.setEditParts(Collections.EMPTY_LIST);
request.setLocation(getDropLocation());
}
#Override
protected void handleDrop() {
super.handleDrop();
if (getCurrentEvent().detail != DND.DROP_NONE) {
getViewer().setSelection(StructuredSelection.EMPTY);
getViewer().getControl().setFocus();
}
}
#Override
protected Command getCommand() {
String text = (String) getCurrentEvent().data;
List<IEntityPart> editParts = new ArrayList<IEntityPart>();
//
// using the 'text' variable you have to create
// a new EditPart that would eventually replace the old one.
//
editParts.add(createNewLabelPart());
ChangeBoundsRequest request = (ChangeBoundsRequest) getTargetRequest();
request.setEditParts(editParts);
return super.getCommand();
}
}
then install the listener in the graphical viewer constructor using the following statement:
addDropTargetListener(new TextTransferDropTargetListener(this));
finally ensure that an EditPolicy that understands requests of type REQ_ADD (maybe you already added one that extends LayoutEditPolicy or ContainerEditPolicy) is installed on the target EditPart, which is usually done in the AbstractEditPart.createEditPolicies().
To better understand the chain of responsibilities, I suggest you to have a look at the super implementation of the TransferDropTargetListener.getCommand() method.

lwuit change UI language

I use codenameone to develop my mobile application. In this application I implement some classes and codes manually for instance create all forms by hard coding not using codenameone designer for some reason.
By the way I wanted to navigate in forms like what codenameone use, so I use one variable from type of Form called it prevForm and when I want to open a form I set it to current form and then I show new form.
Ok, that is main scenario. In this application I wanna implement internationalization too, so I create my own hashtable (Farsi and English) for this application.
This is my problem:
How can I set or change language and apply it to forms that I opened?
Is my method for navigate between forms are good?
Here is my code:
public class BaseForm extends Form implements ActionListener {
public BaseForm(){
this.setLayout(new BoxLayout(BoxLayout.Y_AXIS));
}
Command exit, ok, back;
Form prevForm;
protected void initForm(){
}
protected void showForm(){
}
protected void showForm(final Form prevForm){
//String name = this.getName();
//if("Reminder".equals(name) || "3Transaction".equals(name))
{
this.prevForm = prevForm;
Form f = this;
back = new Command("Back");
//ok = new Command("Ok");
//delete = new Command("Delete");;
Button button = new Button("Button");
f.addCommand(back);
//f.addCommand(ok);
//f.addCommand(delete);
//f.addComponent(button);
f.addCommandListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
if (ae.getCommand().equals(back)) {
//Do Exit command code
System.out.println("Back pressed");
prevForm.showBack();
} else if (ae.getCommand().equals(ok)) {
//Do Start command code
System.out.println("Ok pressed");
}
}
});
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
//Do button code
System.out.println("Action performed");
}
});
}
showForm();
}}
for open nested form I use this code:
LanguageUI lang = new LanguageUI();
lang.showForm(this);
change language [form]:
protected boolean onBtnSave() {
if(isRbFarsiSelected()){
UIManager.getInstance().setResourceBundle(new CommonSettings().getFarsi());
}
else {
UIManager.getInstance().setResourceBundle(new CommonSettings().getEnglish());
}
return false;
}
I also hard code my UI on lwuit, and i have a variable parentForm on every class so i can easily show previous form. For language change i know there is Localization in the resource editor that you can make use of. Below is how you can access it. I guess the trick is how to set the content of the L10N in the res file in code? On the other hand you can create your own helper classes that mirror the methods below.
Resources theme = Resources.open("/theme.res");
theme.getL10N(id, locale);
theme.getL10NResourceNames();
theme.isL10N(name);
theme.listL10NLocales(id)

How do I mask the current page behind a modal dialog box in vanilla GWT?

I've built a log-in composite that I am displaying in my application entry-point to the user. Upon entry of the username and password, I am sending the username and password to the server via a RemoteService and will receive back an object containing the ClientSession. If the ClientSession is a valid object (recognised username and password), I wish to display the main application panel otherwise I want to display the login dialog again (with an error message).
My question is, that during the async call to the server, how to I mask the screen so that the user cannot click anything whilst the Session is obtained from the server?
I know that the login should be fast, but the Session object contains a lot of Client Side cached values for the current user that is used to generate the main panel. This may take a fraction of a second or up to 5 seconds (I can't control the speed of the underlying infrastructure unfortunately) so I want to mask the screen until a timeout is reached then allow the user to try again.
I have done this exact operation before using GWT Ext, but vanilla GWT seems to have a lot less samples unfortunately.
Thanks
Chris
The GWT class PopupPanel has an optional "glass panel" that blocks interaction with the page underneath.
final PopupPanel popup = new PopupPanel(false, true); // Create a modal dialog box that will not auto-hide
popup.add(new Label("Please wait"));
popup.setGlassEnabled(true); // Enable the glass panel
popup.center(); // Center the popup and make it visible
You might want to check out GlassPanel from the GWT Incubator project. AFAICT it's not perfect, but should be of some help nevertheless ;)
You can also use a dialog box for this purpose.
Here is the code how to use it.
public class NTMaskAlert extends DialogBox {
private String displayText;
private String message;
private static NTMaskAlert alert;
Label lable;
private NTMaskAlert(String text) {
setText(text);
setWidget(new Image(GWT.getModuleBaseURL()
+ "/images/ajax-loader_1.gif"));
setGlassEnabled(true);
setAnimationEnabled(true);
super.show();
super.center();
WorkFlowSessionFactory.putValue(WorkFlowSesisonKey.MASKING_PANEL, this);
}
public static void mask(String text) {
if (text != null)
new NTMaskAlert(text);
else
new NTMaskAlert("Processing");
}
public static void unMask() {
NTMaskAlert alert = (NTMaskAlert) WorkFlowSessionFactory
.getValue(WorkFlowSesisonKey.MASKING_PANEL);
if (alert != null) {
alert.hide();
alert = null;
}
}
public void setDisplayText(String displayText) {
this.displayText = displayText;
alert.setText(displayText);
}
public String getDisplayText() {
return displayText;
}
public void setMessage(String message) {
this.message = message;
lable.setText(message);
}
public String getMessage() {
return message;
}
}
Use static mask and unmask method for operations.
This is my solution:
public class CustomPopupPanel extends PopupPanel {
private Label label = new Label();
public CustomPopupPanel() {
super(false, true); // Create a modal dialog box that will not auto-hide
super.setGlassEnabled(true); // Enable the glass panel
super.add(label); // Add the widget label into the panel
}
public CustomPopupPanel(String text) {
this();
this.mask(text);
}
public final void mask(String text) {
label.setText(text);
super.center(); // Center the popup and make it visible
}
public void unmask() {
super.hide(); // Hide the popup
}
}

Resources