Sunday, April 12, 2009

JFace databinding : implementing roundtrip

As developers, we are sometimes (often?) confronted with annoying user demands.

For example, last week, I implemented a classic form enabling the user to enter financial data. I used a ControlDecoration for each field to indicate as precisely as possible errors or warnings to application's users.

I was pretty happy with the result and proud to present it to my customer. Then comes the disillusion....

He asks me to change the behavior of each field validation. When user fills a field with bad data, we must not display a small icon indicating that the data are wrong, we must instead replace the content of the field with the last known valid data...

After googling on this demand, I finally found a bug report 238222 on the eclipse bug database that could help me implementing this functionnality.

Unfortunately, the workaround proposed doesn't work properly.

So I give here my own solution. The main element is my ValidatorRoundtrip class.

It implements IValidator so I can use it with any Validator points availbale in UpdateValueStrategy.

Basically, this class, calls IStatus doValidation(String value), check for the IStatus returned by this call :
- if the IStatus is an error or a cancel, the view is updated to reflect the model (that contains the old valid value)
- if the IStatus is an ok or warning or info IStatus, the normal flow is executed and the modle is updated with the new value.

Here is the code of ValidationRoundtrip :

import org.eclipse.core.databinding.Binding;
import org.eclipse.core.databinding.observable.Realm;
import org.eclipse.core.databinding.validation.IValidator;
import org.eclipse.core.runtime.IStatus;

/**
*
* @author sylvere richard
*
*/
public abstract class ValidatorRoundtrip implements IValidator {

private final Binding b;
private final Realm realm;

public ValidatorRoundtrip(Realm realm, Binding b) {
this.realm = realm;
this.b = b;
}

/**
* Method declared final. Validation logic must be put in method
* ValidatorRoundtrip.doValidation
*
*
* Will call doValidation.
*
* If the IStatus returned by doValidation is an error
* or a cancel, it will force a refresh of the target by calling updateModelToTarget()
* to restore the previous value on screen.
* Otherwise, the process flow is unchanged.
*/
@Override
public final IStatus validate(Object value) {
final IStatus res = doValidation(value);
if (res.matches(IStatus.INFO | IStatus.WARNING) || res.isOK()) {
return res;
}

realm.asyncExec(new Runnable() {

@Override
public void run() {
b.updateModelToTarget();
}
});
return res;
}

/**
* Puts validation logic here
* @param value
* @return
*/
public abstract IStatus doValidation(Object value);
}



So to use this class, we just have to put our business log in the doValidation method.

Here is a snippet using demonstrating the use of this class :

/*
* Snippet demonstrating the use of ValidatorRoundtrip.
* A ValidatorRoundtrip is used to restore the last valid
* value on screen after a validation error occurs.
*
* For a list of all SWT example snippets see
* http://www.eclipse.org/swt/snippets/
*/
import org.eclipse.core.databinding.Binding;
import org.eclipse.core.databinding.DataBindingContext;
import org.eclipse.core.databinding.UpdateValueStrategy;
import org.eclipse.core.databinding.beans.PojoObservables;
import org.eclipse.core.databinding.observable.Realm;
import org.eclipse.core.databinding.validation.ValidationStatus;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.jface.databinding.swt.SWTObservables;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.fieldassist.ControlDecoration;
import org.eclipse.jface.resource.JFaceResources;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;

public class SnippetRoundtrip {

/**
* the model bound to the UI.
*
*/
private static class MyModel {

private String myText;

public String getMyText() {
return myText;
}

public void setMyText(String myText) {
this.myText = myText;
}
}

/**
*
* A composite that will contains a text to validate.
*
*/
private static class MainCompo extends Composite {
private final MyModel model = new MyModel();

private Text text;
private ControlDecoration ctrlDeco;

private Button button;

/**
*
* @param parent
* @param style
*/
public MainCompo(Composite parent, int style) {
super(parent, style);
doLayout();
}

private void doLayout() {
setLayout(new FormLayout());

Label lbl = new Label(this, SWT.NONE);
lbl.setText("Enter a text without 'aa' :");

text = new Text(this, SWT.BORDER);

ctrlDeco = new ControlDecoration(text, SWT.TOP | SWT.LEFT);
ctrlDeco.hide();
ctrlDeco.setImage(JFaceResources
.getImage(Dialog.DLG_IMG_MESSAGE_WARNING));

button = new Button(this, SWT.NONE);
button.setText("Hello");

FormData data = new FormData();
data.left = new FormAttachment(0, 100, 5);
data.top = new FormAttachment(text, 0, SWT.CENTER);
lbl.setLayoutData(data);

data = new FormData();
data.left = new FormAttachment(lbl, 5+ctrlDeco.getImage().getBounds().width, SWT.RIGHT);
data.top = new FormAttachment(0, 100, 5);
data.right = new FormAttachment(100,100,-5);
text.setLayoutData(data);

data = new FormData();
data.left = new FormAttachment(lbl, 5, SWT.RIGHT);
data.top = new FormAttachment(text,5);
button.setLayoutData(data);

}

/**
* we bind text to MyModel.myText
*/
public void binding(final DataBindingContext dbc) {
// let's go binding text to MyModel.myText
// we will do validation
// In case the string typed by the user contains 'aa', we do the roundtrip to go
// back to the last correct value.
// A sequence like 'bb' is allowed but leads to a warning displayed
// to the user.

UpdateValueStrategy strgTargetToModel = new UpdateValueStrategy(
UpdateValueStrategy.POLICY_UPDATE);
UpdateValueStrategy strgModelToTarget = new UpdateValueStrategy(
UpdateValueStrategy.POLICY_UPDATE);
Binding b = dbc.bindValue(SWTObservables.observeText(text,
SWT.FocusOut), PojoObservables.observeValue(model, "myText"),
strgTargetToModel, strgModelToTarget);

strgTargetToModel.setAfterGetValidator(new ValidatorRoundtrip(dbc
.getValidationRealm(), b) {
@Override
public IStatus doValidation(Object value) {
if (value == null) {
ctrlDeco.hide();
return ValidationStatus.ok();
}
String strVal = (String) value;
//error, contains 'aa'
if (strVal.indexOf("aa") != -1) {
return ValidationStatus
.error("the value of this text must NOT contains 'aa'!!");
}
//warning, contains 'bb'
if (strVal.indexOf("bb") != -1) {
ctrlDeco.show();
ctrlDeco.setDescriptionText("be careful, the value of this text contains 'bb' !!");
return ValidationStatus
.warning(ctrlDeco.getDescriptionText());
}
ctrlDeco.hide();
return ValidationStatus.ok();
}
});

}

}

/**
* Main entry point
* @param args
*/
public static void main(String[] args) {
final Display display = new Display();

Realm.runWithDefault(SWTObservables.getRealm(display), new Runnable() {
public void run() {
Shell shell = new Shell(display);
shell.setBounds(0,0,400,200);
shell.setLayout(new FormLayout());
MainCompo compo = new MainCompo(shell, SWT.NONE);
FormData data = new FormData();
data.left = new FormAttachment(0, 100,0);
data.right = new FormAttachment(100, 100,0);
data.top = new FormAttachment(0, 100,0);
data.bottom = new FormAttachment(100, 100,0);
compo.setLayoutData(data);

final DataBindingContext dbc = new DataBindingContext();
compo.binding(dbc);
shell.open();

while (!shell.isDisposed()) {
if (!display.readAndDispatch())
display.sleep();
}
}
});
display.dispose();
}
}



Here is the list of jar we have to put in the classpath for this snippet to work :

com.ibm.icu_3.8.1.v20080530.jar
org.eclipse.core.commands_3.4.0.I20080509-2000.jar
org.eclipse.core.databinding_1.1.1.M20080827-0800b.jar
org.eclipse.core.databinding.beans_1.1.1.M20080827-0800a.jar
org.eclipse.core.databinding.source_1.1.1.M20080827-0800b.jar
org.eclipse.core.runtime_3.4.0.v20080512.jar
org.eclipse.equinox.common_3.4.0.v20080421-2006.jar
org.eclipse.jface_3.4.2.M20090107-0800.jar
org.eclipse.jface.databinding_1.2.1.M20080827-0800a.jar
org.eclipse.osgi_3.4.3.R34x_v20081215-1030.jar
org.eclipse.swt_3.4.2.v3452b.jar
org.eclipse.swt.win32.win32.x86_3.4.1.v3452b.jar


Bye !

1 comment:

Henno Vermeulen said...

Thanks for your post! I am now using this roundtrip idea to implement validation with user interaction. Sometimes I need to ask the user for confirmation on whether or not they are sure they want to make the change. I can implement this by showing a with a MessageDialog.openConfirm inside the setBeforeSetValidator and restore the old value if the user did not confirm.