Manually merged CRLF changes + additional small patch for changes that SHOULD NOT be in the changeset but that the SVN -> GIT sync script has added
--- /dev/null
- /* \r
- @VaadinApache2LicenseForJavaFiles@\r
- */\r
- package com.vaadin.data.fieldgroup;\r
- \r
- import java.lang.reflect.Method;\r
- \r
- import com.vaadin.data.Item;\r
- import com.vaadin.data.util.BeanItem;\r
- import com.vaadin.data.validator.BeanValidator;\r
- import com.vaadin.ui.Field;\r
- \r
- public class BeanFieldGroup<T> extends FieldGroup {\r
- \r
- private Class<T> beanType;\r
- \r
- private static Boolean beanValidationImplementationAvailable = null;\r
- \r
- public BeanFieldGroup(Class<T> beanType) {\r
- this.beanType = beanType;\r
- }\r
- \r
- @Override\r
- protected Class<?> getPropertyType(Object propertyId) {\r
- if (getItemDataSource() != null) {\r
- return super.getPropertyType(propertyId);\r
- } else {\r
- // Data source not set so we need to figure out the type manually\r
- /*\r
- * toString should never really be needed as propertyId should be of\r
- * form "fieldName" or "fieldName.subField[.subField2]" but the\r
- * method declaration comes from parent.\r
- */\r
- java.lang.reflect.Field f;\r
- try {\r
- f = getField(beanType, propertyId.toString());\r
- return f.getType();\r
- } catch (SecurityException e) {\r
- throw new BindException("Cannot determine type of propertyId '"\r
- + propertyId + "'.", e);\r
- } catch (NoSuchFieldException e) {\r
- throw new BindException("Cannot determine type of propertyId '"\r
- + propertyId + "'. The propertyId was not found in "\r
- + beanType.getName(), e);\r
- }\r
- }\r
- }\r
- \r
- private static java.lang.reflect.Field getField(Class<?> cls,\r
- String propertyId) throws SecurityException, NoSuchFieldException {\r
- if (propertyId.contains(".")) {\r
- String[] parts = propertyId.split("\\.", 2);\r
- // Get the type of the field in the "cls" class\r
- java.lang.reflect.Field field1 = getField(cls, parts[0]);\r
- // Find the rest from the sub type\r
- return getField(field1.getType(), parts[1]);\r
- } else {\r
- try {\r
- // Try to find the field directly in the given class\r
- java.lang.reflect.Field field1 = cls\r
- .getDeclaredField(propertyId);\r
- return field1;\r
- } catch (NoSuchFieldError e) {\r
- // Try super classes until we reach Object\r
- Class<?> superClass = cls.getSuperclass();\r
- if (superClass != Object.class) {\r
- return getField(superClass, propertyId);\r
- } else {\r
- throw e;\r
- }\r
- }\r
- }\r
- }\r
- \r
- /**\r
- * Helper method for setting the data source directly using a bean. This\r
- * method wraps the bean in a {@link BeanItem} and calls\r
- * {@link #setItemDataSource(Item)}.\r
- * \r
- * @param bean\r
- * The bean to use as data source.\r
- */\r
- public void setItemDataSource(T bean) {\r
- setItemDataSource(new BeanItem(bean));\r
- }\r
- \r
- @Override\r
- public void setItemDataSource(Item item) {\r
- if (!(item instanceof BeanItem)) {\r
- throw new RuntimeException(getClass().getSimpleName()\r
- + " only supports BeanItems as item data source");\r
- }\r
- super.setItemDataSource(item);\r
- }\r
- \r
- @Override\r
- public BeanItem<T> getItemDataSource() {\r
- return (BeanItem<T>) super.getItemDataSource();\r
- }\r
- \r
- @Override\r
- public void bind(Field field, Object propertyId) {\r
- if (getItemDataSource() != null) {\r
- // The data source is set so the property must be found in the item.\r
- // If it is not we try to add it.\r
- try {\r
- getItemProperty(propertyId);\r
- } catch (BindException e) {\r
- // Not found, try to add a nested property;\r
- // BeanItem property ids are always strings so this is safe\r
- getItemDataSource().addNestedProperty((String) propertyId);\r
- }\r
- }\r
- \r
- super.bind(field, propertyId);\r
- }\r
- \r
- @Override\r
- protected void configureField(Field<?> field) {\r
- super.configureField(field);\r
- // Add Bean validators if there are annotations\r
- if (isBeanValidationImplementationAvailable()) {\r
- BeanValidator validator = new BeanValidator(\r
- beanType, getPropertyId(field).toString());\r
- field.addValidator(validator);\r
- if (field.getLocale() != null) {\r
- validator.setLocale(field.getLocale());\r
- }\r
- }\r
- }\r
- \r
- /**\r
- * Checks whether a bean validation implementation (e.g. Hibernate Validator\r
- * or Apache Bean Validation) is available.\r
- * \r
- * TODO move this method to some more generic location\r
- * \r
- * @return true if a JSR-303 bean validation implementation is available\r
- */\r
- protected static boolean isBeanValidationImplementationAvailable() {\r
- if (beanValidationImplementationAvailable != null) {\r
- return beanValidationImplementationAvailable;\r
- }\r
- try {\r
- Class<?> validationClass = Class\r
- .forName("javax.validation.Validation");\r
- Method buildFactoryMethod = validationClass\r
- .getMethod("buildDefaultValidatorFactory");\r
- Object factory = buildFactoryMethod.invoke(null);\r
- beanValidationImplementationAvailable = (factory != null);\r
- } catch (Exception e) {\r
- // no bean validation implementation available\r
- beanValidationImplementationAvailable = false;\r
- }\r
- return beanValidationImplementationAvailable;\r
- }\r
++/*
++@VaadinApache2LicenseForJavaFiles@
++ */
++package com.vaadin.data.fieldgroup;
++
++import java.lang.reflect.Method;
++
++import com.vaadin.data.Item;
++import com.vaadin.data.util.BeanItem;
++import com.vaadin.data.validator.BeanValidator;
++import com.vaadin.ui.Field;
++
++public class BeanFieldGroup<T> extends FieldGroup {
++
++ private Class<T> beanType;
++
++ private static Boolean beanValidationImplementationAvailable = null;
++
++ public BeanFieldGroup(Class<T> beanType) {
++ this.beanType = beanType;
++ }
++
++ @Override
++ protected Class<?> getPropertyType(Object propertyId) {
++ if (getItemDataSource() != null) {
++ return super.getPropertyType(propertyId);
++ } else {
++ // Data source not set so we need to figure out the type manually
++ /*
++ * toString should never really be needed as propertyId should be of
++ * form "fieldName" or "fieldName.subField[.subField2]" but the
++ * method declaration comes from parent.
++ */
++ java.lang.reflect.Field f;
++ try {
++ f = getField(beanType, propertyId.toString());
++ return f.getType();
++ } catch (SecurityException e) {
++ throw new BindException("Cannot determine type of propertyId '"
++ + propertyId + "'.", e);
++ } catch (NoSuchFieldException e) {
++ throw new BindException("Cannot determine type of propertyId '"
++ + propertyId + "'. The propertyId was not found in "
++ + beanType.getName(), e);
++ }
++ }
++ }
++
++ private static java.lang.reflect.Field getField(Class<?> cls,
++ String propertyId) throws SecurityException, NoSuchFieldException {
++ if (propertyId.contains(".")) {
++ String[] parts = propertyId.split("\\.", 2);
++ // Get the type of the field in the "cls" class
++ java.lang.reflect.Field field1 = getField(cls, parts[0]);
++ // Find the rest from the sub type
++ return getField(field1.getType(), parts[1]);
++ } else {
++ try {
++ // Try to find the field directly in the given class
++ java.lang.reflect.Field field1 = cls
++ .getDeclaredField(propertyId);
++ return field1;
++ } catch (NoSuchFieldError e) {
++ // Try super classes until we reach Object
++ Class<?> superClass = cls.getSuperclass();
++ if (superClass != Object.class) {
++ return getField(superClass, propertyId);
++ } else {
++ throw e;
++ }
++ }
++ }
++ }
++
++ /**
++ * Helper method for setting the data source directly using a bean. This
++ * method wraps the bean in a {@link BeanItem} and calls
++ * {@link #setItemDataSource(Item)}.
++ *
++ * @param bean
++ * The bean to use as data source.
++ */
++ public void setItemDataSource(T bean) {
++ setItemDataSource(new BeanItem(bean));
++ }
++
++ @Override
++ public void setItemDataSource(Item item) {
++ if (!(item instanceof BeanItem)) {
++ throw new RuntimeException(getClass().getSimpleName()
++ + " only supports BeanItems as item data source");
++ }
++ super.setItemDataSource(item);
++ }
++
++ @Override
++ public BeanItem<T> getItemDataSource() {
++ return (BeanItem<T>) super.getItemDataSource();
++ }
++
++ @Override
++ public void bind(Field field, Object propertyId) {
++ if (getItemDataSource() != null) {
++ // The data source is set so the property must be found in the item.
++ // If it is not we try to add it.
++ try {
++ getItemProperty(propertyId);
++ } catch (BindException e) {
++ // Not found, try to add a nested property;
++ // BeanItem property ids are always strings so this is safe
++ getItemDataSource().addNestedProperty((String) propertyId);
++ }
++ }
++
++ super.bind(field, propertyId);
++ }
++
++ @Override
++ protected void configureField(Field<?> field) {
++ super.configureField(field);
++ // Add Bean validators if there are annotations
++ if (isBeanValidationImplementationAvailable()) {
++ BeanValidator validator = new BeanValidator(
++ beanType, getPropertyId(field).toString());
++ field.addValidator(validator);
++ if (field.getLocale() != null) {
++ validator.setLocale(field.getLocale());
++ }
++ }
++ }
++
++ /**
++ * Checks whether a bean validation implementation (e.g. Hibernate Validator
++ * or Apache Bean Validation) is available.
++ *
++ * TODO move this method to some more generic location
++ *
++ * @return true if a JSR-303 bean validation implementation is available
++ */
++ protected static boolean isBeanValidationImplementationAvailable() {
++ if (beanValidationImplementationAvailable != null) {
++ return beanValidationImplementationAvailable;
++ }
++ try {
++ Class<?> validationClass = Class
++ .forName("javax.validation.Validation");
++ Method buildFactoryMethod = validationClass
++ .getMethod("buildDefaultValidatorFactory");
++ Object factory = buildFactoryMethod.invoke(null);
++ beanValidationImplementationAvailable = (factory != null);
++ } catch (Exception e) {
++ // no bean validation implementation available
++ beanValidationImplementationAvailable = false;
++ }
++ return beanValidationImplementationAvailable;
++ }
+}
--- /dev/null
- /* \r
- @VaadinApache2LicenseForJavaFiles@\r
- */\r
- package com.vaadin.data.fieldgroup;\r
- \r
- import java.lang.annotation.ElementType;\r
- import java.lang.annotation.Retention;\r
- import java.lang.annotation.RetentionPolicy;\r
- import java.lang.annotation.Target;\r
- \r
- @Target({ ElementType.FIELD })\r
- @Retention(RetentionPolicy.RUNTIME)\r
- public @interface Caption {\r
- String value();\r
- }\r
++/*
++@VaadinApache2LicenseForJavaFiles@
++ */
++package com.vaadin.data.fieldgroup;
++
++import java.lang.annotation.ElementType;
++import java.lang.annotation.Retention;
++import java.lang.annotation.RetentionPolicy;
++import java.lang.annotation.Target;
++
++@Target({ ElementType.FIELD })
++@Retention(RetentionPolicy.RUNTIME)
++public @interface Caption {
++ String value();
++}
--- /dev/null
- /* \r
- @VaadinApache2LicenseForJavaFiles@\r
- */\r
- package com.vaadin.data.fieldgroup;\r
- \r
- import java.util.EnumSet;\r
- \r
- import com.vaadin.data.Item;\r
- import com.vaadin.data.fieldgroup.FieldGroup.BindException;\r
- import com.vaadin.ui.AbstractSelect;\r
- import com.vaadin.ui.AbstractTextField;\r
- import com.vaadin.ui.CheckBox;\r
- import com.vaadin.ui.ComboBox;\r
- import com.vaadin.ui.Field;\r
- import com.vaadin.ui.ListSelect;\r
- import com.vaadin.ui.NativeSelect;\r
- import com.vaadin.ui.OptionGroup;\r
- import com.vaadin.ui.RichTextArea;\r
- import com.vaadin.ui.Table;\r
- import com.vaadin.ui.TextField;\r
- \r
- public class DefaultFieldGroupFieldFactory implements FieldGroupFieldFactory {\r
- \r
- public static final Object CAPTION_PROPERTY_ID = "Caption";\r
- \r
- public <T extends Field> T createField(Class<?> type, Class<T> fieldType) {\r
- if (Enum.class.isAssignableFrom(type)) {\r
- return createEnumField(type, fieldType);\r
- } else if (Boolean.class.isAssignableFrom(type)\r
- || boolean.class.isAssignableFrom(type)) {\r
- return createBooleanField(fieldType);\r
- }\r
- if (AbstractTextField.class.isAssignableFrom(fieldType)) {\r
- return fieldType.cast(createAbstractTextField(fieldType\r
- .asSubclass(AbstractTextField.class)));\r
- } else if (fieldType == RichTextArea.class) {\r
- return fieldType.cast(createRichTextArea());\r
- }\r
- return createDefaultField(type, fieldType);\r
- }\r
- \r
- protected RichTextArea createRichTextArea() {\r
- RichTextArea rta = new RichTextArea();\r
- rta.setImmediate(true);\r
- \r
- return rta;\r
- }\r
- \r
- private <T extends Field> T createEnumField(Class<?> type,\r
- Class<T> fieldType) {\r
- if (AbstractSelect.class.isAssignableFrom(fieldType)) {\r
- AbstractSelect s = createCompatibleSelect((Class<? extends AbstractSelect>) fieldType);\r
- populateWithEnumData(s, (Class<? extends Enum>) type);\r
- return (T) s;\r
- }\r
- \r
- return null;\r
- }\r
- \r
- protected AbstractSelect createCompatibleSelect(\r
- Class<? extends AbstractSelect> fieldType) {\r
- AbstractSelect select;\r
- if (fieldType.isAssignableFrom(ListSelect.class)) {\r
- select = new ListSelect();\r
- select.setMultiSelect(false);\r
- } else if (fieldType.isAssignableFrom(NativeSelect.class)) {\r
- select = new NativeSelect();\r
- } else if (fieldType.isAssignableFrom(OptionGroup.class)) {\r
- select = new OptionGroup();\r
- select.setMultiSelect(false);\r
- } else if (fieldType.isAssignableFrom(Table.class)) {\r
- Table t = new Table();\r
- t.setSelectable(true);\r
- select = t;\r
- } else {\r
- select = new ComboBox(null);\r
- }\r
- select.setImmediate(true);\r
- select.setNullSelectionAllowed(false);\r
- \r
- return select;\r
- }\r
- \r
- protected <T extends Field> T createBooleanField(Class<T> fieldType) {\r
- if (fieldType.isAssignableFrom(CheckBox.class)) {\r
- CheckBox cb = new CheckBox(null);\r
- cb.setImmediate(true);\r
- return (T) cb;\r
- } else if (AbstractTextField.class.isAssignableFrom(fieldType)) {\r
- return (T) createAbstractTextField((Class<? extends AbstractTextField>) fieldType);\r
- }\r
- \r
- return null;\r
- }\r
- \r
- protected <T extends AbstractTextField> T createAbstractTextField(\r
- Class<T> fieldType) {\r
- if (fieldType == AbstractTextField.class) {\r
- fieldType = (Class<T>) TextField.class;\r
- }\r
- try {\r
- T field = fieldType.newInstance();\r
- field.setImmediate(true);\r
- return field;\r
- } catch (Exception e) {\r
- throw new BindException("Could not create a field of type "\r
- + fieldType, e);\r
- }\r
- }\r
- \r
- /**\r
- * Fallback when no specific field has been created. Typically returns a\r
- * TextField.\r
- * \r
- * @param <T>\r
- * The type of field to create\r
- * @param type\r
- * The type of data that should be edited\r
- * @param fieldType\r
- * The type of field to create\r
- * @return A field capable of editing the data or null if no field could be\r
- * created\r
- */\r
- protected <T extends Field> T createDefaultField(Class<?> type,\r
- Class<T> fieldType) {\r
- if (fieldType.isAssignableFrom(TextField.class)) {\r
- return fieldType.cast(createAbstractTextField(TextField.class));\r
- }\r
- return null;\r
- }\r
- \r
- /**\r
- * Populates the given select with all the enums in the given {@link Enum}\r
- * class. Uses {@link Enum}.toString() for caption.\r
- * \r
- * @param select\r
- * The select to populate\r
- * @param enumClass\r
- * The Enum class to use\r
- */\r
- protected void populateWithEnumData(AbstractSelect select,\r
- Class<? extends Enum> enumClass) {\r
- select.removeAllItems();\r
- for (Object p : select.getContainerPropertyIds()) {\r
- select.removeContainerProperty(p);\r
- }\r
- select.addContainerProperty(CAPTION_PROPERTY_ID, String.class, "");\r
- select.setItemCaptionPropertyId(CAPTION_PROPERTY_ID);\r
- @SuppressWarnings("unchecked")\r
- EnumSet<?> enumSet = EnumSet.allOf(enumClass);\r
- for (Object r : enumSet) {\r
- Item newItem = select.addItem(r);\r
- newItem.getItemProperty(CAPTION_PROPERTY_ID).setValue(r.toString());\r
- }\r
- }\r
- }\r
++/*
++@VaadinApache2LicenseForJavaFiles@
++ */
++package com.vaadin.data.fieldgroup;
++
++import java.util.EnumSet;
++
++import com.vaadin.data.Item;
++import com.vaadin.data.fieldgroup.FieldGroup.BindException;
++import com.vaadin.ui.AbstractSelect;
++import com.vaadin.ui.AbstractTextField;
++import com.vaadin.ui.CheckBox;
++import com.vaadin.ui.ComboBox;
++import com.vaadin.ui.Field;
++import com.vaadin.ui.ListSelect;
++import com.vaadin.ui.NativeSelect;
++import com.vaadin.ui.OptionGroup;
++import com.vaadin.ui.RichTextArea;
++import com.vaadin.ui.Table;
++import com.vaadin.ui.TextField;
++
++public class DefaultFieldGroupFieldFactory implements FieldGroupFieldFactory {
++
++ public static final Object CAPTION_PROPERTY_ID = "Caption";
++
++ public <T extends Field> T createField(Class<?> type, Class<T> fieldType) {
++ if (Enum.class.isAssignableFrom(type)) {
++ return createEnumField(type, fieldType);
++ } else if (Boolean.class.isAssignableFrom(type)
++ || boolean.class.isAssignableFrom(type)) {
++ return createBooleanField(fieldType);
++ }
++ if (AbstractTextField.class.isAssignableFrom(fieldType)) {
++ return fieldType.cast(createAbstractTextField(fieldType
++ .asSubclass(AbstractTextField.class)));
++ } else if (fieldType == RichTextArea.class) {
++ return fieldType.cast(createRichTextArea());
++ }
++ return createDefaultField(type, fieldType);
++ }
++
++ protected RichTextArea createRichTextArea() {
++ RichTextArea rta = new RichTextArea();
++ rta.setImmediate(true);
++
++ return rta;
++ }
++
++ private <T extends Field> T createEnumField(Class<?> type,
++ Class<T> fieldType) {
++ if (AbstractSelect.class.isAssignableFrom(fieldType)) {
++ AbstractSelect s = createCompatibleSelect((Class<? extends AbstractSelect>) fieldType);
++ populateWithEnumData(s, (Class<? extends Enum>) type);
++ return (T) s;
++ }
++
++ return null;
++ }
++
++ protected AbstractSelect createCompatibleSelect(
++ Class<? extends AbstractSelect> fieldType) {
++ AbstractSelect select;
++ if (fieldType.isAssignableFrom(ListSelect.class)) {
++ select = new ListSelect();
++ select.setMultiSelect(false);
++ } else if (fieldType.isAssignableFrom(NativeSelect.class)) {
++ select = new NativeSelect();
++ } else if (fieldType.isAssignableFrom(OptionGroup.class)) {
++ select = new OptionGroup();
++ select.setMultiSelect(false);
++ } else if (fieldType.isAssignableFrom(Table.class)) {
++ Table t = new Table();
++ t.setSelectable(true);
++ select = t;
++ } else {
++ select = new ComboBox(null);
++ }
++ select.setImmediate(true);
++ select.setNullSelectionAllowed(false);
++
++ return select;
++ }
++
++ protected <T extends Field> T createBooleanField(Class<T> fieldType) {
++ if (fieldType.isAssignableFrom(CheckBox.class)) {
++ CheckBox cb = new CheckBox(null);
++ cb.setImmediate(true);
++ return (T) cb;
++ } else if (AbstractTextField.class.isAssignableFrom(fieldType)) {
++ return (T) createAbstractTextField((Class<? extends AbstractTextField>) fieldType);
++ }
++
++ return null;
++ }
++
++ protected <T extends AbstractTextField> T createAbstractTextField(
++ Class<T> fieldType) {
++ if (fieldType == AbstractTextField.class) {
++ fieldType = (Class<T>) TextField.class;
++ }
++ try {
++ T field = fieldType.newInstance();
++ field.setImmediate(true);
++ return field;
++ } catch (Exception e) {
++ throw new BindException("Could not create a field of type "
++ + fieldType, e);
++ }
++ }
++
++ /**
++ * Fallback when no specific field has been created. Typically returns a
++ * TextField.
++ *
++ * @param <T>
++ * The type of field to create
++ * @param type
++ * The type of data that should be edited
++ * @param fieldType
++ * The type of field to create
++ * @return A field capable of editing the data or null if no field could be
++ * created
++ */
++ protected <T extends Field> T createDefaultField(Class<?> type,
++ Class<T> fieldType) {
++ if (fieldType.isAssignableFrom(TextField.class)) {
++ return fieldType.cast(createAbstractTextField(TextField.class));
++ }
++ return null;
++ }
++
++ /**
++ * Populates the given select with all the enums in the given {@link Enum}
++ * class. Uses {@link Enum}.toString() for caption.
++ *
++ * @param select
++ * The select to populate
++ * @param enumClass
++ * The Enum class to use
++ */
++ protected void populateWithEnumData(AbstractSelect select,
++ Class<? extends Enum> enumClass) {
++ select.removeAllItems();
++ for (Object p : select.getContainerPropertyIds()) {
++ select.removeContainerProperty(p);
++ }
++ select.addContainerProperty(CAPTION_PROPERTY_ID, String.class, "");
++ select.setItemCaptionPropertyId(CAPTION_PROPERTY_ID);
++ @SuppressWarnings("unchecked")
++ EnumSet<?> enumSet = EnumSet.allOf(enumClass);
++ for (Object r : enumSet) {
++ Item newItem = select.addItem(r);
++ newItem.getItemProperty(CAPTION_PROPERTY_ID).setValue(r.toString());
++ }
++ }
++}
--- /dev/null
- /* \r
- @VaadinApache2LicenseForJavaFiles@\r
- */\r
- package com.vaadin.data.fieldgroup;\r
- \r
- import java.io.Serializable;\r
- import java.lang.reflect.InvocationTargetException;\r
- import java.util.ArrayList;\r
- import java.util.Collection;\r
- import java.util.Collections;\r
- import java.util.HashMap;\r
- import java.util.LinkedHashMap;\r
- import java.util.List;\r
- import java.util.logging.Logger;\r
- \r
- import com.vaadin.data.Item;\r
- import com.vaadin.data.Property;\r
- import com.vaadin.data.Validator.InvalidValueException;\r
- import com.vaadin.data.util.TransactionalPropertyWrapper;\r
- import com.vaadin.tools.ReflectTools;\r
- import com.vaadin.ui.DefaultFieldFactory;\r
- import com.vaadin.ui.Field;\r
- import com.vaadin.ui.Form;\r
- \r
- /**\r
- * FieldGroup provides an easy way of binding fields to data and handling\r
- * commits of these fields.\r
- * <p>\r
- * The functionality of FieldGroup is similar to {@link Form} but\r
- * {@link FieldGroup} does not handle layouts in any way. The typical use case\r
- * is to create a layout outside the FieldGroup and then use FieldGroup to bind\r
- * the fields to a data source.\r
- * </p>\r
- * <p>\r
- * {@link FieldGroup} is not a UI component so it cannot be added to a layout.\r
- * Using the buildAndBind methods {@link FieldGroup} can create fields for you\r
- * using a FieldGroupFieldFactory but you still have to add them to the correct\r
- * position in your layout.\r
- * </p>\r
- * \r
- * @author Vaadin Ltd\r
- * @version @version@\r
- * @since 7.0\r
- */\r
- public class FieldGroup implements Serializable {\r
- \r
- private static final Logger logger = Logger.getLogger(FieldGroup.class\r
- .getName());\r
- \r
- private Item itemDataSource;\r
- private boolean buffered = true;\r
- \r
- private boolean enabled = true;\r
- private boolean readOnly = false;\r
- \r
- private HashMap<Object, Field<?>> propertyIdToField = new HashMap<Object, Field<?>>();\r
- private LinkedHashMap<Field<?>, Object> fieldToPropertyId = new LinkedHashMap<Field<?>, Object>();\r
- private List<CommitHandler> commitHandlers = new ArrayList<CommitHandler>();\r
- \r
- /**\r
- * The field factory used by builder methods.\r
- */\r
- private FieldGroupFieldFactory fieldFactory = new DefaultFieldGroupFieldFactory();\r
- \r
- /**\r
- * Constructs a field binder. Use {@link #setItemDataSource(Item)} to set a\r
- * data source for the field binder.\r
- * \r
- */\r
- public FieldGroup() {\r
- \r
- }\r
- \r
- /**\r
- * Constructs a field binder that uses the given data source.\r
- * \r
- * @param itemDataSource\r
- * The data source to bind the fields to\r
- */\r
- public FieldGroup(Item itemDataSource) {\r
- setItemDataSource(itemDataSource);\r
- }\r
- \r
- /**\r
- * Updates the item that is used by this FieldBinder. Rebinds all fields to\r
- * the properties in the new item.\r
- * \r
- * @param itemDataSource\r
- * The new item to use\r
- */\r
- public void setItemDataSource(Item itemDataSource) {\r
- this.itemDataSource = itemDataSource;\r
- \r
- for (Field<?> f : fieldToPropertyId.keySet()) {\r
- bind(f, fieldToPropertyId.get(f));\r
- }\r
- }\r
- \r
- /**\r
- * Gets the item used by this FieldBinder. Note that you must call\r
- * {@link #commit()} for the item to be updated unless buffered mode has\r
- * been switched off.\r
- * \r
- * @see #setBuffered(boolean)\r
- * @see #commit()\r
- * \r
- * @return The item used by this FieldBinder\r
- */\r
- public Item getItemDataSource() {\r
- return itemDataSource;\r
- }\r
- \r
- /**\r
- * Checks the buffered mode for the bound fields.\r
- * <p>\r
- * \r
- * @see #setBuffered(boolean) for more details on buffered mode\r
- * \r
- * @see Field#isBuffered()\r
- * @return true if buffered mode is on, false otherwise\r
- * \r
- */\r
- public boolean isBuffered() {\r
- return buffered;\r
- }\r
- \r
- /**\r
- * Sets the buffered mode for the bound fields.\r
- * <p>\r
- * When buffered mode is on the item will not be updated until\r
- * {@link #commit()} is called. If buffered mode is off the item will be\r
- * updated once the fields are updated.\r
- * </p>\r
- * <p>\r
- * The default is to use buffered mode.\r
- * </p>\r
- * \r
- * @see Field#setBuffered(boolean)\r
- * @param buffered\r
- * true to turn on buffered mode, false otherwise\r
- */\r
- public void setBuffered(boolean buffered) {\r
- if (buffered == this.buffered) {\r
- return;\r
- }\r
- \r
- this.buffered = buffered;\r
- for (Field<?> field : getFields()) {\r
- field.setBuffered(buffered);\r
- }\r
- }\r
- \r
- /**\r
- * Returns the enabled status for the fields.\r
- * <p>\r
- * Note that this will not accurately represent the enabled status of all\r
- * fields if you change the enabled status of the fields through some other\r
- * method than {@link #setEnabled(boolean)}.\r
- * \r
- * @return true if the fields are enabled, false otherwise\r
- */\r
- public boolean isEnabled() {\r
- return enabled;\r
- }\r
- \r
- /**\r
- * Updates the enabled state of all bound fields.\r
- * \r
- * @param fieldsEnabled\r
- * true to enable all bound fields, false to disable them\r
- */\r
- public void setEnabled(boolean fieldsEnabled) {\r
- enabled = fieldsEnabled;\r
- for (Field<?> field : getFields()) {\r
- field.setEnabled(fieldsEnabled);\r
- }\r
- }\r
- \r
- /**\r
- * Returns the read only status for the fields.\r
- * <p>\r
- * Note that this will not accurately represent the read only status of all\r
- * fields if you change the read only status of the fields through some\r
- * other method than {@link #setReadOnly(boolean)}.\r
- * \r
- * @return true if the fields are set to read only, false otherwise\r
- */\r
- public boolean isReadOnly() {\r
- return readOnly;\r
- }\r
- \r
- /**\r
- * Updates the read only state of all bound fields.\r
- * \r
- * @param fieldsReadOnly\r
- * true to set all bound fields to read only, false to set them\r
- * to read write\r
- */\r
- public void setReadOnly(boolean fieldsReadOnly) {\r
- readOnly = fieldsReadOnly;\r
- }\r
- \r
- /**\r
- * Returns a collection of all fields that have been bound.\r
- * <p>\r
- * The fields are not returned in any specific order.\r
- * </p>\r
- * \r
- * @return A collection with all bound Fields\r
- */\r
- public Collection<Field<?>> getFields() {\r
- return fieldToPropertyId.keySet();\r
- }\r
- \r
- /**\r
- * Binds the field with the given propertyId from the current item. If an\r
- * item has not been set then the binding is postponed until the item is set\r
- * using {@link #setItemDataSource(Item)}.\r
- * <p>\r
- * This method also adds validators when applicable.\r
- * </p>\r
- * \r
- * @param field\r
- * The field to bind\r
- * @param propertyId\r
- * The propertyId to bind to the field\r
- * @throws BindException\r
- * If the property id is already bound to another field by this\r
- * field binder\r
- */\r
- public void bind(Field<?> field, Object propertyId) throws BindException {\r
- if (propertyIdToField.containsKey(propertyId)\r
- && propertyIdToField.get(propertyId) != field) {\r
- throw new BindException("Property id " + propertyId\r
- + " is already bound to another field");\r
- }\r
- fieldToPropertyId.put(field, propertyId);\r
- propertyIdToField.put(propertyId, field);\r
- if (itemDataSource == null) {\r
- // Will be bound when data source is set\r
- return;\r
- }\r
- \r
- field.setPropertyDataSource(wrapInTransactionalProperty(getItemProperty(propertyId)));\r
- configureField(field);\r
- }\r
- \r
- private <T> Property.Transactional<T> wrapInTransactionalProperty(\r
- Property<T> itemProperty) {\r
- return new TransactionalPropertyWrapper<T>(itemProperty);\r
- }\r
- \r
- /**\r
- * Gets the property with the given property id from the item.\r
- * \r
- * @param propertyId\r
- * The id if the property to find\r
- * @return The property with the given id from the item\r
- * @throws BindException\r
- * If the property was not found in the item or no item has been\r
- * set\r
- */\r
- protected Property<?> getItemProperty(Object propertyId)\r
- throws BindException {\r
- Item item = getItemDataSource();\r
- if (item == null) {\r
- throw new BindException("Could not lookup property with id "\r
- + propertyId + " as no item has been set");\r
- }\r
- Property<?> p = item.getItemProperty(propertyId);\r
- if (p == null) {\r
- throw new BindException("A property with id " + propertyId\r
- + " was not found in the item");\r
- }\r
- return p;\r
- }\r
- \r
- /**\r
- * Detaches the field from its property id and removes it from this\r
- * FieldBinder.\r
- * <p>\r
- * Note that the field is not detached from its property data source if it\r
- * is no longer connected to the same property id it was bound to using this\r
- * FieldBinder.\r
- * \r
- * @param field\r
- * The field to detach\r
- * @throws BindException\r
- * If the field is not bound by this field binder or not bound\r
- * to the correct property id\r
- */\r
- public void unbind(Field<?> field) throws BindException {\r
- Object propertyId = fieldToPropertyId.get(field);\r
- if (propertyId == null) {\r
- throw new BindException(\r
- "The given field is not part of this FieldBinder");\r
- }\r
- \r
- Property fieldDataSource = field.getPropertyDataSource();\r
- if (fieldDataSource instanceof TransactionalPropertyWrapper) {\r
- fieldDataSource = ((TransactionalPropertyWrapper) fieldDataSource)\r
- .getWrappedProperty();\r
- }\r
- if (fieldDataSource == getItemProperty(propertyId)) {\r
- field.setPropertyDataSource(null);\r
- }\r
- fieldToPropertyId.remove(field);\r
- propertyIdToField.remove(propertyId);\r
- }\r
- \r
- /**\r
- * Configures a field with the settings set for this FieldBinder.\r
- * <p>\r
- * By default this updates the buffered, read only and enabled state of the\r
- * field. Also adds validators when applicable.\r
- * \r
- * @param field\r
- * The field to update\r
- */\r
- protected void configureField(Field<?> field) {\r
- field.setBuffered(isBuffered());\r
- \r
- field.setEnabled(isEnabled());\r
- field.setReadOnly(isReadOnly());\r
- }\r
- \r
- /**\r
- * Gets the type of the property with the given property id.\r
- * \r
- * @param propertyId\r
- * The propertyId. Must be find\r
- * @return The type of the property\r
- */\r
- protected Class<?> getPropertyType(Object propertyId) throws BindException {\r
- if (getItemDataSource() == null) {\r
- throw new BindException(\r
- "Property type for '"\r
- + propertyId\r
- + "' could not be determined. No item data source has been set.");\r
- }\r
- Property<?> p = getItemDataSource().getItemProperty(propertyId);\r
- if (p == null) {\r
- throw new BindException(\r
- "Property type for '"\r
- + propertyId\r
- + "' could not be determined. No property with that id was found.");\r
- }\r
- \r
- return p.getType();\r
- }\r
- \r
- /**\r
- * Returns a collection of all property ids that have been bound to fields.\r
- * <p>\r
- * Note that this will return property ids even before the item has been\r
- * set. In that case it returns the property ids that will be bound once the\r
- * item is set.\r
- * </p>\r
- * <p>\r
- * No guarantee is given for the order of the property ids\r
- * </p>\r
- * \r
- * @return A collection of bound property ids\r
- */\r
- public Collection<Object> getBoundPropertyIds() {\r
- return Collections.unmodifiableCollection(propertyIdToField.keySet());\r
- }\r
- \r
- /**\r
- * Returns a collection of all property ids that exist in the item set using\r
- * {@link #setItemDataSource(Item)} but have not been bound to fields.\r
- * <p>\r
- * Will always return an empty collection before an item has been set using\r
- * {@link #setItemDataSource(Item)}.\r
- * </p>\r
- * <p>\r
- * No guarantee is given for the order of the property ids\r
- * </p>\r
- * \r
- * @return A collection of property ids that have not been bound to fields\r
- */\r
- public Collection<Object> getUnboundPropertyIds() {\r
- if (getItemDataSource() == null) {\r
- return new ArrayList<Object>();\r
- }\r
- List<Object> unboundPropertyIds = new ArrayList<Object>();\r
- unboundPropertyIds.addAll(getItemDataSource().getItemPropertyIds());\r
- unboundPropertyIds.removeAll(propertyIdToField.keySet());\r
- return unboundPropertyIds;\r
- }\r
- \r
- /**\r
- * Commits all changes done to the bound fields.\r
- * <p>\r
- * Calls all {@link CommitHandler}s before and after committing the field\r
- * changes to the item data source. The whole commit is aborted and state is\r
- * restored to what it was before commit was called if any\r
- * {@link CommitHandler} throws a CommitException or there is a problem\r
- * committing the fields\r
- * \r
- * @throws CommitException\r
- * If the commit was aborted\r
- */\r
- public void commit() throws CommitException {\r
- if (!isBuffered()) {\r
- // Not using buffered mode, nothing to do\r
- return;\r
- }\r
- for (Field<?> f : fieldToPropertyId.keySet()) {\r
- ((Property.Transactional<?>) f.getPropertyDataSource())\r
- .startTransaction();\r
- }\r
- try {\r
- firePreCommitEvent();\r
- // Commit the field values to the properties\r
- for (Field<?> f : fieldToPropertyId.keySet()) {\r
- f.commit();\r
- }\r
- firePostCommitEvent();\r
- \r
- // Commit the properties\r
- for (Field<?> f : fieldToPropertyId.keySet()) {\r
- ((Property.Transactional<?>) f.getPropertyDataSource())\r
- .commit();\r
- }\r
- \r
- } catch (Exception e) {\r
- for (Field<?> f : fieldToPropertyId.keySet()) {\r
- try {\r
- ((Property.Transactional<?>) f.getPropertyDataSource())\r
- .rollback();\r
- } catch (Exception rollbackException) {\r
- // FIXME: What to do ?\r
- }\r
- }\r
- \r
- throw new CommitException("Commit failed", e);\r
- }\r
- \r
- }\r
- \r
- /**\r
- * Sends a preCommit event to all registered commit handlers\r
- * \r
- * @throws CommitException\r
- * If the commit should be aborted\r
- */\r
- private void firePreCommitEvent() throws CommitException {\r
- CommitHandler[] handlers = commitHandlers\r
- .toArray(new CommitHandler[commitHandlers.size()]);\r
- \r
- for (CommitHandler handler : handlers) {\r
- handler.preCommit(new CommitEvent(this));\r
- }\r
- }\r
- \r
- /**\r
- * Sends a postCommit event to all registered commit handlers\r
- * \r
- * @throws CommitException\r
- * If the commit should be aborted\r
- */\r
- private void firePostCommitEvent() throws CommitException {\r
- CommitHandler[] handlers = commitHandlers\r
- .toArray(new CommitHandler[commitHandlers.size()]);\r
- \r
- for (CommitHandler handler : handlers) {\r
- handler.postCommit(new CommitEvent(this));\r
- }\r
- }\r
- \r
- /**\r
- * Discards all changes done to the bound fields.\r
- * <p>\r
- * Only has effect if buffered mode is used.\r
- * \r
- */\r
- public void discard() {\r
- for (Field<?> f : fieldToPropertyId.keySet()) {\r
- try {\r
- f.discard();\r
- } catch (Exception e) {\r
- // TODO: handle exception\r
- // What can we do if discard fails other than try to discard all\r
- // other fields?\r
- }\r
- }\r
- }\r
- \r
- /**\r
- * Returns the field that is bound to the given property id\r
- * \r
- * @param propertyId\r
- * The property id to use to lookup the field\r
- * @return The field that is bound to the property id or null if no field is\r
- * bound to that property id\r
- */\r
- public Field<?> getField(Object propertyId) {\r
- return propertyIdToField.get(propertyId);\r
- }\r
- \r
- /**\r
- * Returns the property id that is bound to the given field\r
- * \r
- * @param field\r
- * The field to use to lookup the property id\r
- * @return The property id that is bound to the field or null if the field\r
- * is not bound to any property id by this FieldBinder\r
- */\r
- public Object getPropertyId(Field<?> field) {\r
- return fieldToPropertyId.get(field);\r
- }\r
- \r
- /**\r
- * Adds a commit handler.\r
- * <p>\r
- * The commit handler is called before the field values are committed to the\r
- * item ( {@link CommitHandler#preCommit(CommitEvent)}) and after the item\r
- * has been updated ({@link CommitHandler#postCommit(CommitEvent)}). If a\r
- * {@link CommitHandler} throws a CommitException the whole commit is\r
- * aborted and the fields retain their old values.\r
- * \r
- * @param commitHandler\r
- * The commit handler to add\r
- */\r
- public void addCommitHandler(CommitHandler commitHandler) {\r
- commitHandlers.add(commitHandler);\r
- }\r
- \r
- /**\r
- * Removes the given commit handler.\r
- * \r
- * @see #addCommitHandler(CommitHandler)\r
- * \r
- * @param commitHandler\r
- * The commit handler to remove\r
- */\r
- public void removeCommitHandler(CommitHandler commitHandler) {\r
- commitHandlers.remove(commitHandler);\r
- }\r
- \r
- /**\r
- * Returns a list of all commit handlers for this {@link FieldGroup}.\r
- * <p>\r
- * Use {@link #addCommitHandler(CommitHandler)} and\r
- * {@link #removeCommitHandler(CommitHandler)} to register or unregister a\r
- * commit handler.\r
- * \r
- * @return A collection of commit handlers\r
- */\r
- protected Collection<CommitHandler> getCommitHandlers() {\r
- return Collections.unmodifiableCollection(commitHandlers);\r
- }\r
- \r
- /**\r
- * CommitHandlers are used by {@link FieldGroup#commit()} as part of the\r
- * commit transactions. CommitHandlers can perform custom operations as part\r
- * of the commit and cause the commit to be aborted by throwing a\r
- * {@link CommitException}.\r
- */\r
- public interface CommitHandler extends Serializable {\r
- /**\r
- * Called before changes are committed to the field and the item is\r
- * updated.\r
- * <p>\r
- * Throw a {@link CommitException} to abort the commit.\r
- * \r
- * @param commitEvent\r
- * An event containing information regarding the commit\r
- * @throws CommitException\r
- * if the commit should be aborted\r
- */\r
- public void preCommit(CommitEvent commitEvent) throws CommitException;\r
- \r
- /**\r
- * Called after changes are committed to the fields and the item is\r
- * updated..\r
- * <p>\r
- * Throw a {@link CommitException} to abort the commit.\r
- * \r
- * @param commitEvent\r
- * An event containing information regarding the commit\r
- * @throws CommitException\r
- * if the commit should be aborted\r
- */\r
- public void postCommit(CommitEvent commitEvent) throws CommitException;\r
- }\r
- \r
- /**\r
- * FIXME javadoc\r
- * \r
- */\r
- public static class CommitEvent implements Serializable {\r
- private FieldGroup fieldBinder;\r
- \r
- private CommitEvent(FieldGroup fieldBinder) {\r
- this.fieldBinder = fieldBinder;\r
- }\r
- \r
- /**\r
- * Returns the field binder that this commit relates to\r
- * \r
- * @return The FieldBinder that is being committed.\r
- */\r
- public FieldGroup getFieldBinder() {\r
- return fieldBinder;\r
- }\r
- \r
- }\r
- \r
- /**\r
- * Checks the validity of the bound fields.\r
- * <p>\r
- * Call the {@link Field#validate()} for the fields to get the individual\r
- * error messages.\r
- * \r
- * @return true if all bound fields are valid, false otherwise.\r
- */\r
- public boolean isValid() {\r
- try {\r
- for (Field<?> field : getFields()) {\r
- field.validate();\r
- }\r
- return true;\r
- } catch (InvalidValueException e) {\r
- return false;\r
- }\r
- }\r
- \r
- /**\r
- * Checks if any bound field has been modified.\r
- * \r
- * @return true if at least on field has been modified, false otherwise\r
- */\r
- public boolean isModified() {\r
- for (Field<?> field : getFields()) {\r
- if (field.isModified()) {\r
- return true;\r
- }\r
- }\r
- return false;\r
- }\r
- \r
- /**\r
- * Gets the field factory for the {@link FieldGroup}. The field factory is\r
- * only used when {@link FieldGroup} creates a new field.\r
- * \r
- * @return The field factory in use\r
- * \r
- */\r
- public FieldGroupFieldFactory getFieldFactory() {\r
- return fieldFactory;\r
- }\r
- \r
- /**\r
- * Sets the field factory for the {@link FieldGroup}. The field factory is\r
- * only used when {@link FieldGroup} creates a new field.\r
- * \r
- * @param fieldFactory\r
- * The field factory to use\r
- */\r
- public void setFieldFactory(FieldGroupFieldFactory fieldFactory) {\r
- this.fieldFactory = fieldFactory;\r
- }\r
- \r
- /**\r
- * Binds member fields found in the given object.\r
- * <p>\r
- * This method processes all (Java) member fields whose type extends\r
- * {@link Field} and that can be mapped to a property id. Property id\r
- * mapping is done based on the field name or on a @{@link PropertyId}\r
- * annotation on the field. All non-null fields for which a property id can\r
- * be determined are bound to the property id.\r
- * </p>\r
- * <p>\r
- * For example:\r
- * \r
- * <pre>\r
- * public class MyForm extends VerticalLayout {\r
- * private TextField firstName = new TextField("First name");\r
- * @PropertyId("last")\r
- * private TextField lastName = new TextField("Last name"); \r
- * private TextField age = new TextField("Age"); ... }\r
- * \r
- * MyForm myForm = new MyForm(); \r
- * ... \r
- * fieldGroup.bindMemberFields(myForm);\r
- * </pre>\r
- * \r
- * </p>\r
- * This binds the firstName TextField to a "firstName" property in the item,\r
- * lastName TextField to a "last" property and the age TextField to a "age"\r
- * property.\r
- * \r
- * @param objectWithMemberFields\r
- * The object that contains (Java) member fields to bind\r
- * @throws BindException\r
- * If there is a problem binding a field\r
- */\r
- public void bindMemberFields(Object objectWithMemberFields)\r
- throws BindException {\r
- buildAndBindMemberFields(objectWithMemberFields, false);\r
- }\r
- \r
- /**\r
- * Binds member fields found in the given object and builds member fields\r
- * that have not been initialized.\r
- * <p>\r
- * This method processes all (Java) member fields whose type extends\r
- * {@link Field} and that can be mapped to a property id. Property id\r
- * mapping is done based on the field name or on a @{@link PropertyId}\r
- * annotation on the field. Fields that are not initialized (null) are built\r
- * using the field factory. All non-null fields for which a property id can\r
- * be determined are bound to the property id.\r
- * </p>\r
- * <p>\r
- * For example:\r
- * \r
- * <pre>\r
- * public class MyForm extends VerticalLayout {\r
- * private TextField firstName = new TextField("First name");\r
- * @PropertyId("last")\r
- * private TextField lastName = new TextField("Last name"); \r
- * private TextField age;\r
- * \r
- * MyForm myForm = new MyForm(); \r
- * ... \r
- * fieldGroup.buildAndBindMemberFields(myForm);\r
- * </pre>\r
- * \r
- * </p>\r
- * <p>\r
- * This binds the firstName TextField to a "firstName" property in the item,\r
- * lastName TextField to a "last" property and builds an age TextField using\r
- * the field factory and then binds it to the "age" property.\r
- * </p>\r
- * \r
- * @param objectWithMemberFields\r
- * The object that contains (Java) member fields to build and\r
- * bind\r
- * @throws BindException\r
- * If there is a problem binding or building a field\r
- */\r
- public void buildAndBindMemberFields(Object objectWithMemberFields)\r
- throws BindException {\r
- buildAndBindMemberFields(objectWithMemberFields, true);\r
- }\r
- \r
- /**\r
- * Binds member fields found in the given object and optionally builds\r
- * member fields that have not been initialized.\r
- * <p>\r
- * This method processes all (Java) member fields whose type extends\r
- * {@link Field} and that can be mapped to a property id. Property id\r
- * mapping is done based on the field name or on a @{@link PropertyId}\r
- * annotation on the field. Fields that are not initialized (null) are built\r
- * using the field factory is buildFields is true. All non-null fields for\r
- * which a property id can be determined are bound to the property id.\r
- * </p>\r
- * \r
- * @param objectWithMemberFields\r
- * The object that contains (Java) member fields to build and\r
- * bind\r
- * @throws BindException\r
- * If there is a problem binding or building a field\r
- */\r
- protected void buildAndBindMemberFields(Object objectWithMemberFields,\r
- boolean buildFields) throws BindException {\r
- Class<?> objectClass = objectWithMemberFields.getClass();\r
- \r
- for (java.lang.reflect.Field memberField : objectClass\r
- .getDeclaredFields()) {\r
- \r
- if (!Field.class.isAssignableFrom(memberField.getType())) {\r
- // Process next field\r
- continue;\r
- }\r
- \r
- PropertyId propertyIdAnnotation = memberField\r
- .getAnnotation(PropertyId.class);\r
- \r
- Class<? extends Field> fieldType = (Class<? extends Field>) memberField\r
- .getType();\r
- \r
- Object propertyId = null;\r
- if (propertyIdAnnotation != null) {\r
- // @PropertyId(propertyId) always overrides property id\r
- propertyId = propertyIdAnnotation.value();\r
- } else {\r
- propertyId = memberField.getName();\r
- }\r
- \r
- // Ensure that the property id exists\r
- Class<?> propertyType;\r
- \r
- try {\r
- propertyType = getPropertyType(propertyId);\r
- } catch (BindException e) {\r
- // Property id was not found, skip this field\r
- continue;\r
- }\r
- \r
- Field<?> field;\r
- try {\r
- // Get the field from the object\r
- field = (Field<?>) ReflectTools.getJavaFieldValue(\r
- objectWithMemberFields, memberField);\r
- } catch (Exception e) {\r
- // If we cannot determine the value, just skip the field and try\r
- // the next one\r
- continue;\r
- }\r
- \r
- if (field == null && buildFields) {\r
- Caption captionAnnotation = memberField\r
- .getAnnotation(Caption.class);\r
- String caption;\r
- if (captionAnnotation != null) {\r
- caption = captionAnnotation.value();\r
- } else {\r
- caption = DefaultFieldFactory\r
- .createCaptionByPropertyId(propertyId);\r
- }\r
- \r
- // Create the component (Field)\r
- field = build(caption, propertyType, fieldType);\r
- \r
- // Store it in the field\r
- try {\r
- ReflectTools.setJavaFieldValue(objectWithMemberFields,\r
- memberField, field);\r
- } catch (IllegalArgumentException e) {\r
- throw new BindException("Could not assign value to field '"\r
- + memberField.getName() + "'", e);\r
- } catch (IllegalAccessException e) {\r
- throw new BindException("Could not assign value to field '"\r
- + memberField.getName() + "'", e);\r
- } catch (InvocationTargetException e) {\r
- throw new BindException("Could not assign value to field '"\r
- + memberField.getName() + "'", e);\r
- }\r
- }\r
- \r
- if (field != null) {\r
- // Bind it to the property id\r
- bind(field, propertyId);\r
- }\r
- }\r
- }\r
- \r
- public static class CommitException extends Exception {\r
- \r
- public CommitException() {\r
- super();\r
- // TODO Auto-generated constructor stub\r
- }\r
- \r
- public CommitException(String message, Throwable cause) {\r
- super(message, cause);\r
- // TODO Auto-generated constructor stub\r
- }\r
- \r
- public CommitException(String message) {\r
- super(message);\r
- // TODO Auto-generated constructor stub\r
- }\r
- \r
- public CommitException(Throwable cause) {\r
- super(cause);\r
- // TODO Auto-generated constructor stub\r
- }\r
- \r
- }\r
- \r
- public static class BindException extends RuntimeException {\r
- \r
- public BindException(String message) {\r
- super(message);\r
- }\r
- \r
- public BindException(String message, Throwable t) {\r
- super(message, t);\r
- }\r
- \r
- }\r
- \r
- /**\r
- * Builds a field and binds it to the given property id using the field\r
- * binder.\r
- * \r
- * @param propertyId\r
- * The property id to bind to. Must be present in the field\r
- * finder.\r
- * @throws BindException\r
- * If there is a problem while building or binding\r
- * @return The created and bound field\r
- */\r
- public Field<?> buildAndBind(Object propertyId) throws BindException {\r
- String caption = DefaultFieldFactory\r
- .createCaptionByPropertyId(propertyId);\r
- return buildAndBind(caption, propertyId);\r
- }\r
- \r
- /**\r
- * Builds a field using the given caption and binds it to the given property\r
- * id using the field binder.\r
- * \r
- * @param caption\r
- * The caption for the field\r
- * @param propertyId\r
- * The property id to bind to. Must be present in the field\r
- * finder.\r
- * @throws BindException\r
- * If there is a problem while building or binding\r
- * @return The created and bound field. Can be any type of {@link Field}.\r
- */\r
- public Field<?> buildAndBind(String caption, Object propertyId)\r
- throws BindException {\r
- Class<?> type = getPropertyType(propertyId);\r
- return buildAndBind(caption, propertyId, Field.class);\r
- \r
- }\r
- \r
- /**\r
- * Builds a field using the given caption and binds it to the given property\r
- * id using the field binder. Ensures the new field is of the given type.\r
- * \r
- * @param caption\r
- * The caption for the field\r
- * @param propertyId\r
- * The property id to bind to. Must be present in the field\r
- * finder.\r
- * @throws BindException\r
- * If the field could not be created\r
- * @return The created and bound field. Can be any type of {@link Field}.\r
- */\r
- \r
- public <T extends Field> T buildAndBind(String caption, Object propertyId,\r
- Class<T> fieldType) throws BindException {\r
- Class<?> type = getPropertyType(propertyId);\r
- \r
- T field = build(caption, type, fieldType);\r
- bind(field, propertyId);\r
- \r
- return field;\r
- }\r
- \r
- /**\r
- * Creates a field based on the given data type.\r
- * <p>\r
- * The data type is the type that we want to edit using the field. The field\r
- * type is the type of field we want to create, can be {@link Field} if any\r
- * Field is good.\r
- * </p>\r
- * \r
- * @param caption\r
- * The caption for the new field\r
- * @param dataType\r
- * The data model type that we want to edit using the field\r
- * @param fieldType\r
- * The type of field that we want to create\r
- * @return A Field capable of editing the given type\r
- * @throws BindException\r
- * If the field could not be created\r
- */\r
- protected <T extends Field> T build(String caption, Class<?> dataType,\r
- Class<T> fieldType) throws BindException {\r
- T field = getFieldFactory().createField(dataType, fieldType);\r
- if (field == null) {\r
- throw new BindException("Unable to build a field of type "\r
- + fieldType.getName() + " for editing "\r
- + dataType.getName());\r
- }\r
- \r
- field.setCaption(caption);\r
- return field;\r
- }\r
++/*
++@VaadinApache2LicenseForJavaFiles@
++ */
++package com.vaadin.data.fieldgroup;
++
++import java.io.Serializable;
++import java.lang.reflect.InvocationTargetException;
++import java.util.ArrayList;
++import java.util.Collection;
++import java.util.Collections;
++import java.util.HashMap;
++import java.util.LinkedHashMap;
++import java.util.List;
++import java.util.logging.Logger;
++
++import com.vaadin.data.Item;
++import com.vaadin.data.Property;
++import com.vaadin.data.Validator.InvalidValueException;
++import com.vaadin.data.util.TransactionalPropertyWrapper;
++import com.vaadin.tools.ReflectTools;
++import com.vaadin.ui.DefaultFieldFactory;
++import com.vaadin.ui.Field;
++import com.vaadin.ui.Form;
++
++/**
++ * FieldGroup provides an easy way of binding fields to data and handling
++ * commits of these fields.
++ * <p>
++ * The functionality of FieldGroup is similar to {@link Form} but
++ * {@link FieldGroup} does not handle layouts in any way. The typical use case
++ * is to create a layout outside the FieldGroup and then use FieldGroup to bind
++ * the fields to a data source.
++ * </p>
++ * <p>
++ * {@link FieldGroup} is not a UI component so it cannot be added to a layout.
++ * Using the buildAndBind methods {@link FieldGroup} can create fields for you
++ * using a FieldGroupFieldFactory but you still have to add them to the correct
++ * position in your layout.
++ * </p>
++ *
++ * @author Vaadin Ltd
++ * @version @version@
++ * @since 7.0
++ */
++public class FieldGroup implements Serializable {
++
++ private static final Logger logger = Logger.getLogger(FieldGroup.class
++ .getName());
++
++ private Item itemDataSource;
++ private boolean buffered = true;
++
++ private boolean enabled = true;
++ private boolean readOnly = false;
++
++ private HashMap<Object, Field<?>> propertyIdToField = new HashMap<Object, Field<?>>();
++ private LinkedHashMap<Field<?>, Object> fieldToPropertyId = new LinkedHashMap<Field<?>, Object>();
++ private List<CommitHandler> commitHandlers = new ArrayList<CommitHandler>();
++
++ /**
++ * The field factory used by builder methods.
++ */
++ private FieldGroupFieldFactory fieldFactory = new DefaultFieldGroupFieldFactory();
++
++ /**
++ * Constructs a field binder. Use {@link #setItemDataSource(Item)} to set a
++ * data source for the field binder.
++ *
++ */
++ public FieldGroup() {
++
++ }
++
++ /**
++ * Constructs a field binder that uses the given data source.
++ *
++ * @param itemDataSource
++ * The data source to bind the fields to
++ */
++ public FieldGroup(Item itemDataSource) {
++ setItemDataSource(itemDataSource);
++ }
++
++ /**
++ * Updates the item that is used by this FieldBinder. Rebinds all fields to
++ * the properties in the new item.
++ *
++ * @param itemDataSource
++ * The new item to use
++ */
++ public void setItemDataSource(Item itemDataSource) {
++ this.itemDataSource = itemDataSource;
++
++ for (Field<?> f : fieldToPropertyId.keySet()) {
++ bind(f, fieldToPropertyId.get(f));
++ }
++ }
++
++ /**
++ * Gets the item used by this FieldBinder. Note that you must call
++ * {@link #commit()} for the item to be updated unless buffered mode has
++ * been switched off.
++ *
++ * @see #setBuffered(boolean)
++ * @see #commit()
++ *
++ * @return The item used by this FieldBinder
++ */
++ public Item getItemDataSource() {
++ return itemDataSource;
++ }
++
++ /**
++ * Checks the buffered mode for the bound fields.
++ * <p>
++ *
++ * @see #setBuffered(boolean) for more details on buffered mode
++ *
++ * @see Field#isBuffered()
++ * @return true if buffered mode is on, false otherwise
++ *
++ */
++ public boolean isBuffered() {
++ return buffered;
++ }
++
++ /**
++ * Sets the buffered mode for the bound fields.
++ * <p>
++ * When buffered mode is on the item will not be updated until
++ * {@link #commit()} is called. If buffered mode is off the item will be
++ * updated once the fields are updated.
++ * </p>
++ * <p>
++ * The default is to use buffered mode.
++ * </p>
++ *
++ * @see Field#setBuffered(boolean)
++ * @param buffered
++ * true to turn on buffered mode, false otherwise
++ */
++ public void setBuffered(boolean buffered) {
++ if (buffered == this.buffered) {
++ return;
++ }
++
++ this.buffered = buffered;
++ for (Field<?> field : getFields()) {
++ field.setBuffered(buffered);
++ }
++ }
++
++ /**
++ * Returns the enabled status for the fields.
++ * <p>
++ * Note that this will not accurately represent the enabled status of all
++ * fields if you change the enabled status of the fields through some other
++ * method than {@link #setEnabled(boolean)}.
++ *
++ * @return true if the fields are enabled, false otherwise
++ */
++ public boolean isEnabled() {
++ return enabled;
++ }
++
++ /**
++ * Updates the enabled state of all bound fields.
++ *
++ * @param fieldsEnabled
++ * true to enable all bound fields, false to disable them
++ */
++ public void setEnabled(boolean fieldsEnabled) {
++ enabled = fieldsEnabled;
++ for (Field<?> field : getFields()) {
++ field.setEnabled(fieldsEnabled);
++ }
++ }
++
++ /**
++ * Returns the read only status for the fields.
++ * <p>
++ * Note that this will not accurately represent the read only status of all
++ * fields if you change the read only status of the fields through some
++ * other method than {@link #setReadOnly(boolean)}.
++ *
++ * @return true if the fields are set to read only, false otherwise
++ */
++ public boolean isReadOnly() {
++ return readOnly;
++ }
++
++ /**
++ * Updates the read only state of all bound fields.
++ *
++ * @param fieldsReadOnly
++ * true to set all bound fields to read only, false to set them
++ * to read write
++ */
++ public void setReadOnly(boolean fieldsReadOnly) {
++ readOnly = fieldsReadOnly;
++ }
++
++ /**
++ * Returns a collection of all fields that have been bound.
++ * <p>
++ * The fields are not returned in any specific order.
++ * </p>
++ *
++ * @return A collection with all bound Fields
++ */
++ public Collection<Field<?>> getFields() {
++ return fieldToPropertyId.keySet();
++ }
++
++ /**
++ * Binds the field with the given propertyId from the current item. If an
++ * item has not been set then the binding is postponed until the item is set
++ * using {@link #setItemDataSource(Item)}.
++ * <p>
++ * This method also adds validators when applicable.
++ * </p>
++ *
++ * @param field
++ * The field to bind
++ * @param propertyId
++ * The propertyId to bind to the field
++ * @throws BindException
++ * If the property id is already bound to another field by this
++ * field binder
++ */
++ public void bind(Field<?> field, Object propertyId) throws BindException {
++ if (propertyIdToField.containsKey(propertyId)
++ && propertyIdToField.get(propertyId) != field) {
++ throw new BindException("Property id " + propertyId
++ + " is already bound to another field");
++ }
++ fieldToPropertyId.put(field, propertyId);
++ propertyIdToField.put(propertyId, field);
++ if (itemDataSource == null) {
++ // Will be bound when data source is set
++ return;
++ }
++
++ field.setPropertyDataSource(wrapInTransactionalProperty(getItemProperty(propertyId)));
++ configureField(field);
++ }
++
++ private <T> Property.Transactional<T> wrapInTransactionalProperty(
++ Property<T> itemProperty) {
++ return new TransactionalPropertyWrapper<T>(itemProperty);
++ }
++
++ /**
++ * Gets the property with the given property id from the item.
++ *
++ * @param propertyId
++ * The id if the property to find
++ * @return The property with the given id from the item
++ * @throws BindException
++ * If the property was not found in the item or no item has been
++ * set
++ */
++ protected Property<?> getItemProperty(Object propertyId)
++ throws BindException {
++ Item item = getItemDataSource();
++ if (item == null) {
++ throw new BindException("Could not lookup property with id "
++ + propertyId + " as no item has been set");
++ }
++ Property<?> p = item.getItemProperty(propertyId);
++ if (p == null) {
++ throw new BindException("A property with id " + propertyId
++ + " was not found in the item");
++ }
++ return p;
++ }
++
++ /**
++ * Detaches the field from its property id and removes it from this
++ * FieldBinder.
++ * <p>
++ * Note that the field is not detached from its property data source if it
++ * is no longer connected to the same property id it was bound to using this
++ * FieldBinder.
++ *
++ * @param field
++ * The field to detach
++ * @throws BindException
++ * If the field is not bound by this field binder or not bound
++ * to the correct property id
++ */
++ public void unbind(Field<?> field) throws BindException {
++ Object propertyId = fieldToPropertyId.get(field);
++ if (propertyId == null) {
++ throw new BindException(
++ "The given field is not part of this FieldBinder");
++ }
++
++ Property fieldDataSource = field.getPropertyDataSource();
++ if (fieldDataSource instanceof TransactionalPropertyWrapper) {
++ fieldDataSource = ((TransactionalPropertyWrapper) fieldDataSource)
++ .getWrappedProperty();
++ }
++ if (fieldDataSource == getItemProperty(propertyId)) {
++ field.setPropertyDataSource(null);
++ }
++ fieldToPropertyId.remove(field);
++ propertyIdToField.remove(propertyId);
++ }
++
++ /**
++ * Configures a field with the settings set for this FieldBinder.
++ * <p>
++ * By default this updates the buffered, read only and enabled state of the
++ * field. Also adds validators when applicable.
++ *
++ * @param field
++ * The field to update
++ */
++ protected void configureField(Field<?> field) {
++ field.setBuffered(isBuffered());
++
++ field.setEnabled(isEnabled());
++ field.setReadOnly(isReadOnly());
++ }
++
++ /**
++ * Gets the type of the property with the given property id.
++ *
++ * @param propertyId
++ * The propertyId. Must be find
++ * @return The type of the property
++ */
++ protected Class<?> getPropertyType(Object propertyId) throws BindException {
++ if (getItemDataSource() == null) {
++ throw new BindException(
++ "Property type for '"
++ + propertyId
++ + "' could not be determined. No item data source has been set.");
++ }
++ Property<?> p = getItemDataSource().getItemProperty(propertyId);
++ if (p == null) {
++ throw new BindException(
++ "Property type for '"
++ + propertyId
++ + "' could not be determined. No property with that id was found.");
++ }
++
++ return p.getType();
++ }
++
++ /**
++ * Returns a collection of all property ids that have been bound to fields.
++ * <p>
++ * Note that this will return property ids even before the item has been
++ * set. In that case it returns the property ids that will be bound once the
++ * item is set.
++ * </p>
++ * <p>
++ * No guarantee is given for the order of the property ids
++ * </p>
++ *
++ * @return A collection of bound property ids
++ */
++ public Collection<Object> getBoundPropertyIds() {
++ return Collections.unmodifiableCollection(propertyIdToField.keySet());
++ }
++
++ /**
++ * Returns a collection of all property ids that exist in the item set using
++ * {@link #setItemDataSource(Item)} but have not been bound to fields.
++ * <p>
++ * Will always return an empty collection before an item has been set using
++ * {@link #setItemDataSource(Item)}.
++ * </p>
++ * <p>
++ * No guarantee is given for the order of the property ids
++ * </p>
++ *
++ * @return A collection of property ids that have not been bound to fields
++ */
++ public Collection<Object> getUnboundPropertyIds() {
++ if (getItemDataSource() == null) {
++ return new ArrayList<Object>();
++ }
++ List<Object> unboundPropertyIds = new ArrayList<Object>();
++ unboundPropertyIds.addAll(getItemDataSource().getItemPropertyIds());
++ unboundPropertyIds.removeAll(propertyIdToField.keySet());
++ return unboundPropertyIds;
++ }
++
++ /**
++ * Commits all changes done to the bound fields.
++ * <p>
++ * Calls all {@link CommitHandler}s before and after committing the field
++ * changes to the item data source. The whole commit is aborted and state is
++ * restored to what it was before commit was called if any
++ * {@link CommitHandler} throws a CommitException or there is a problem
++ * committing the fields
++ *
++ * @throws CommitException
++ * If the commit was aborted
++ */
++ public void commit() throws CommitException {
++ if (!isBuffered()) {
++ // Not using buffered mode, nothing to do
++ return;
++ }
++ for (Field<?> f : fieldToPropertyId.keySet()) {
++ ((Property.Transactional<?>) f.getPropertyDataSource())
++ .startTransaction();
++ }
++ try {
++ firePreCommitEvent();
++ // Commit the field values to the properties
++ for (Field<?> f : fieldToPropertyId.keySet()) {
++ f.commit();
++ }
++ firePostCommitEvent();
++
++ // Commit the properties
++ for (Field<?> f : fieldToPropertyId.keySet()) {
++ ((Property.Transactional<?>) f.getPropertyDataSource())
++ .commit();
++ }
++
++ } catch (Exception e) {
++ for (Field<?> f : fieldToPropertyId.keySet()) {
++ try {
++ ((Property.Transactional<?>) f.getPropertyDataSource())
++ .rollback();
++ } catch (Exception rollbackException) {
++ // FIXME: What to do ?
++ }
++ }
++
++ throw new CommitException("Commit failed", e);
++ }
++
++ }
++
++ /**
++ * Sends a preCommit event to all registered commit handlers
++ *
++ * @throws CommitException
++ * If the commit should be aborted
++ */
++ private void firePreCommitEvent() throws CommitException {
++ CommitHandler[] handlers = commitHandlers
++ .toArray(new CommitHandler[commitHandlers.size()]);
++
++ for (CommitHandler handler : handlers) {
++ handler.preCommit(new CommitEvent(this));
++ }
++ }
++
++ /**
++ * Sends a postCommit event to all registered commit handlers
++ *
++ * @throws CommitException
++ * If the commit should be aborted
++ */
++ private void firePostCommitEvent() throws CommitException {
++ CommitHandler[] handlers = commitHandlers
++ .toArray(new CommitHandler[commitHandlers.size()]);
++
++ for (CommitHandler handler : handlers) {
++ handler.postCommit(new CommitEvent(this));
++ }
++ }
++
++ /**
++ * Discards all changes done to the bound fields.
++ * <p>
++ * Only has effect if buffered mode is used.
++ *
++ */
++ public void discard() {
++ for (Field<?> f : fieldToPropertyId.keySet()) {
++ try {
++ f.discard();
++ } catch (Exception e) {
++ // TODO: handle exception
++ // What can we do if discard fails other than try to discard all
++ // other fields?
++ }
++ }
++ }
++
++ /**
++ * Returns the field that is bound to the given property id
++ *
++ * @param propertyId
++ * The property id to use to lookup the field
++ * @return The field that is bound to the property id or null if no field is
++ * bound to that property id
++ */
++ public Field<?> getField(Object propertyId) {
++ return propertyIdToField.get(propertyId);
++ }
++
++ /**
++ * Returns the property id that is bound to the given field
++ *
++ * @param field
++ * The field to use to lookup the property id
++ * @return The property id that is bound to the field or null if the field
++ * is not bound to any property id by this FieldBinder
++ */
++ public Object getPropertyId(Field<?> field) {
++ return fieldToPropertyId.get(field);
++ }
++
++ /**
++ * Adds a commit handler.
++ * <p>
++ * The commit handler is called before the field values are committed to the
++ * item ( {@link CommitHandler#preCommit(CommitEvent)}) and after the item
++ * has been updated ({@link CommitHandler#postCommit(CommitEvent)}). If a
++ * {@link CommitHandler} throws a CommitException the whole commit is
++ * aborted and the fields retain their old values.
++ *
++ * @param commitHandler
++ * The commit handler to add
++ */
++ public void addCommitHandler(CommitHandler commitHandler) {
++ commitHandlers.add(commitHandler);
++ }
++
++ /**
++ * Removes the given commit handler.
++ *
++ * @see #addCommitHandler(CommitHandler)
++ *
++ * @param commitHandler
++ * The commit handler to remove
++ */
++ public void removeCommitHandler(CommitHandler commitHandler) {
++ commitHandlers.remove(commitHandler);
++ }
++
++ /**
++ * Returns a list of all commit handlers for this {@link FieldGroup}.
++ * <p>
++ * Use {@link #addCommitHandler(CommitHandler)} and
++ * {@link #removeCommitHandler(CommitHandler)} to register or unregister a
++ * commit handler.
++ *
++ * @return A collection of commit handlers
++ */
++ protected Collection<CommitHandler> getCommitHandlers() {
++ return Collections.unmodifiableCollection(commitHandlers);
++ }
++
++ /**
++ * CommitHandlers are used by {@link FieldGroup#commit()} as part of the
++ * commit transactions. CommitHandlers can perform custom operations as part
++ * of the commit and cause the commit to be aborted by throwing a
++ * {@link CommitException}.
++ */
++ public interface CommitHandler extends Serializable {
++ /**
++ * Called before changes are committed to the field and the item is
++ * updated.
++ * <p>
++ * Throw a {@link CommitException} to abort the commit.
++ *
++ * @param commitEvent
++ * An event containing information regarding the commit
++ * @throws CommitException
++ * if the commit should be aborted
++ */
++ public void preCommit(CommitEvent commitEvent) throws CommitException;
++
++ /**
++ * Called after changes are committed to the fields and the item is
++ * updated..
++ * <p>
++ * Throw a {@link CommitException} to abort the commit.
++ *
++ * @param commitEvent
++ * An event containing information regarding the commit
++ * @throws CommitException
++ * if the commit should be aborted
++ */
++ public void postCommit(CommitEvent commitEvent) throws CommitException;
++ }
++
++ /**
++ * FIXME javadoc
++ *
++ */
++ public static class CommitEvent implements Serializable {
++ private FieldGroup fieldBinder;
++
++ private CommitEvent(FieldGroup fieldBinder) {
++ this.fieldBinder = fieldBinder;
++ }
++
++ /**
++ * Returns the field binder that this commit relates to
++ *
++ * @return The FieldBinder that is being committed.
++ */
++ public FieldGroup getFieldBinder() {
++ return fieldBinder;
++ }
++
++ }
++
++ /**
++ * Checks the validity of the bound fields.
++ * <p>
++ * Call the {@link Field#validate()} for the fields to get the individual
++ * error messages.
++ *
++ * @return true if all bound fields are valid, false otherwise.
++ */
++ public boolean isValid() {
++ try {
++ for (Field<?> field : getFields()) {
++ field.validate();
++ }
++ return true;
++ } catch (InvalidValueException e) {
++ return false;
++ }
++ }
++
++ /**
++ * Checks if any bound field has been modified.
++ *
++ * @return true if at least on field has been modified, false otherwise
++ */
++ public boolean isModified() {
++ for (Field<?> field : getFields()) {
++ if (field.isModified()) {
++ return true;
++ }
++ }
++ return false;
++ }
++
++ /**
++ * Gets the field factory for the {@link FieldGroup}. The field factory is
++ * only used when {@link FieldGroup} creates a new field.
++ *
++ * @return The field factory in use
++ *
++ */
++ public FieldGroupFieldFactory getFieldFactory() {
++ return fieldFactory;
++ }
++
++ /**
++ * Sets the field factory for the {@link FieldGroup}. The field factory is
++ * only used when {@link FieldGroup} creates a new field.
++ *
++ * @param fieldFactory
++ * The field factory to use
++ */
++ public void setFieldFactory(FieldGroupFieldFactory fieldFactory) {
++ this.fieldFactory = fieldFactory;
++ }
++
++ /**
++ * Binds member fields found in the given object.
++ * <p>
++ * This method processes all (Java) member fields whose type extends
++ * {@link Field} and that can be mapped to a property id. Property id
++ * mapping is done based on the field name or on a @{@link PropertyId}
++ * annotation on the field. All non-null fields for which a property id can
++ * be determined are bound to the property id.
++ * </p>
++ * <p>
++ * For example:
++ *
++ * <pre>
++ * public class MyForm extends VerticalLayout {
++ * private TextField firstName = new TextField("First name");
++ * @PropertyId("last")
++ * private TextField lastName = new TextField("Last name");
++ * private TextField age = new TextField("Age"); ... }
++ *
++ * MyForm myForm = new MyForm();
++ * ...
++ * fieldGroup.bindMemberFields(myForm);
++ * </pre>
++ *
++ * </p>
++ * This binds the firstName TextField to a "firstName" property in the item,
++ * lastName TextField to a "last" property and the age TextField to a "age"
++ * property.
++ *
++ * @param objectWithMemberFields
++ * The object that contains (Java) member fields to bind
++ * @throws BindException
++ * If there is a problem binding a field
++ */
++ public void bindMemberFields(Object objectWithMemberFields)
++ throws BindException {
++ buildAndBindMemberFields(objectWithMemberFields, false);
++ }
++
++ /**
++ * Binds member fields found in the given object and builds member fields
++ * that have not been initialized.
++ * <p>
++ * This method processes all (Java) member fields whose type extends
++ * {@link Field} and that can be mapped to a property id. Property id
++ * mapping is done based on the field name or on a @{@link PropertyId}
++ * annotation on the field. Fields that are not initialized (null) are built
++ * using the field factory. All non-null fields for which a property id can
++ * be determined are bound to the property id.
++ * </p>
++ * <p>
++ * For example:
++ *
++ * <pre>
++ * public class MyForm extends VerticalLayout {
++ * private TextField firstName = new TextField("First name");
++ * @PropertyId("last")
++ * private TextField lastName = new TextField("Last name");
++ * private TextField age;
++ *
++ * MyForm myForm = new MyForm();
++ * ...
++ * fieldGroup.buildAndBindMemberFields(myForm);
++ * </pre>
++ *
++ * </p>
++ * <p>
++ * This binds the firstName TextField to a "firstName" property in the item,
++ * lastName TextField to a "last" property and builds an age TextField using
++ * the field factory and then binds it to the "age" property.
++ * </p>
++ *
++ * @param objectWithMemberFields
++ * The object that contains (Java) member fields to build and
++ * bind
++ * @throws BindException
++ * If there is a problem binding or building a field
++ */
++ public void buildAndBindMemberFields(Object objectWithMemberFields)
++ throws BindException {
++ buildAndBindMemberFields(objectWithMemberFields, true);
++ }
++
++ /**
++ * Binds member fields found in the given object and optionally builds
++ * member fields that have not been initialized.
++ * <p>
++ * This method processes all (Java) member fields whose type extends
++ * {@link Field} and that can be mapped to a property id. Property id
++ * mapping is done based on the field name or on a @{@link PropertyId}
++ * annotation on the field. Fields that are not initialized (null) are built
++ * using the field factory is buildFields is true. All non-null fields for
++ * which a property id can be determined are bound to the property id.
++ * </p>
++ *
++ * @param objectWithMemberFields
++ * The object that contains (Java) member fields to build and
++ * bind
++ * @throws BindException
++ * If there is a problem binding or building a field
++ */
++ protected void buildAndBindMemberFields(Object objectWithMemberFields,
++ boolean buildFields) throws BindException {
++ Class<?> objectClass = objectWithMemberFields.getClass();
++
++ for (java.lang.reflect.Field memberField : objectClass
++ .getDeclaredFields()) {
++
++ if (!Field.class.isAssignableFrom(memberField.getType())) {
++ // Process next field
++ continue;
++ }
++
++ PropertyId propertyIdAnnotation = memberField
++ .getAnnotation(PropertyId.class);
++
++ Class<? extends Field> fieldType = (Class<? extends Field>) memberField
++ .getType();
++
++ Object propertyId = null;
++ if (propertyIdAnnotation != null) {
++ // @PropertyId(propertyId) always overrides property id
++ propertyId = propertyIdAnnotation.value();
++ } else {
++ propertyId = memberField.getName();
++ }
++
++ // Ensure that the property id exists
++ Class<?> propertyType;
++
++ try {
++ propertyType = getPropertyType(propertyId);
++ } catch (BindException e) {
++ // Property id was not found, skip this field
++ continue;
++ }
++
++ Field<?> field;
++ try {
++ // Get the field from the object
++ field = (Field<?>) ReflectTools.getJavaFieldValue(
++ objectWithMemberFields, memberField);
++ } catch (Exception e) {
++ // If we cannot determine the value, just skip the field and try
++ // the next one
++ continue;
++ }
++
++ if (field == null && buildFields) {
++ Caption captionAnnotation = memberField
++ .getAnnotation(Caption.class);
++ String caption;
++ if (captionAnnotation != null) {
++ caption = captionAnnotation.value();
++ } else {
++ caption = DefaultFieldFactory
++ .createCaptionByPropertyId(propertyId);
++ }
++
++ // Create the component (Field)
++ field = build(caption, propertyType, fieldType);
++
++ // Store it in the field
++ try {
++ ReflectTools.setJavaFieldValue(objectWithMemberFields,
++ memberField, field);
++ } catch (IllegalArgumentException e) {
++ throw new BindException("Could not assign value to field '"
++ + memberField.getName() + "'", e);
++ } catch (IllegalAccessException e) {
++ throw new BindException("Could not assign value to field '"
++ + memberField.getName() + "'", e);
++ } catch (InvocationTargetException e) {
++ throw new BindException("Could not assign value to field '"
++ + memberField.getName() + "'", e);
++ }
++ }
++
++ if (field != null) {
++ // Bind it to the property id
++ bind(field, propertyId);
++ }
++ }
++ }
++
++ public static class CommitException extends Exception {
++
++ public CommitException() {
++ super();
++ // TODO Auto-generated constructor stub
++ }
++
++ public CommitException(String message, Throwable cause) {
++ super(message, cause);
++ // TODO Auto-generated constructor stub
++ }
++
++ public CommitException(String message) {
++ super(message);
++ // TODO Auto-generated constructor stub
++ }
++
++ public CommitException(Throwable cause) {
++ super(cause);
++ // TODO Auto-generated constructor stub
++ }
++
++ }
++
++ public static class BindException extends RuntimeException {
++
++ public BindException(String message) {
++ super(message);
++ }
++
++ public BindException(String message, Throwable t) {
++ super(message, t);
++ }
++
++ }
++
++ /**
++ * Builds a field and binds it to the given property id using the field
++ * binder.
++ *
++ * @param propertyId
++ * The property id to bind to. Must be present in the field
++ * finder.
++ * @throws BindException
++ * If there is a problem while building or binding
++ * @return The created and bound field
++ */
++ public Field<?> buildAndBind(Object propertyId) throws BindException {
++ String caption = DefaultFieldFactory
++ .createCaptionByPropertyId(propertyId);
++ return buildAndBind(caption, propertyId);
++ }
++
++ /**
++ * Builds a field using the given caption and binds it to the given property
++ * id using the field binder.
++ *
++ * @param caption
++ * The caption for the field
++ * @param propertyId
++ * The property id to bind to. Must be present in the field
++ * finder.
++ * @throws BindException
++ * If there is a problem while building or binding
++ * @return The created and bound field. Can be any type of {@link Field}.
++ */
++ public Field<?> buildAndBind(String caption, Object propertyId)
++ throws BindException {
++ Class<?> type = getPropertyType(propertyId);
++ return buildAndBind(caption, propertyId, Field.class);
++
++ }
++
++ /**
++ * Builds a field using the given caption and binds it to the given property
++ * id using the field binder. Ensures the new field is of the given type.
++ *
++ * @param caption
++ * The caption for the field
++ * @param propertyId
++ * The property id to bind to. Must be present in the field
++ * finder.
++ * @throws BindException
++ * If the field could not be created
++ * @return The created and bound field. Can be any type of {@link Field}.
++ */
++
++ public <T extends Field> T buildAndBind(String caption, Object propertyId,
++ Class<T> fieldType) throws BindException {
++ Class<?> type = getPropertyType(propertyId);
++
++ T field = build(caption, type, fieldType);
++ bind(field, propertyId);
++
++ return field;
++ }
++
++ /**
++ * Creates a field based on the given data type.
++ * <p>
++ * The data type is the type that we want to edit using the field. The field
++ * type is the type of field we want to create, can be {@link Field} if any
++ * Field is good.
++ * </p>
++ *
++ * @param caption
++ * The caption for the new field
++ * @param dataType
++ * The data model type that we want to edit using the field
++ * @param fieldType
++ * The type of field that we want to create
++ * @return A Field capable of editing the given type
++ * @throws BindException
++ * If the field could not be created
++ */
++ protected <T extends Field> T build(String caption, Class<?> dataType,
++ Class<T> fieldType) throws BindException {
++ T field = getFieldFactory().createField(dataType, fieldType);
++ if (field == null) {
++ throw new BindException("Unable to build a field of type "
++ + fieldType.getName() + " for editing "
++ + dataType.getName());
++ }
++
++ field.setCaption(caption);
++ return field;
++ }
+}
--- /dev/null
- /* \r
- @VaadinApache2LicenseForJavaFiles@\r
- */\r
- package com.vaadin.data.fieldgroup;\r
- \r
- import java.io.Serializable;\r
- \r
- import com.vaadin.ui.Field;\r
- \r
- /**\r
- * Factory interface for creating new Field-instances based on the data type\r
- * that should be edited.\r
- * \r
- * @author Vaadin Ltd.\r
- * @version @version@\r
- * @since 7.0\r
- */\r
- public interface FieldGroupFieldFactory extends Serializable {\r
- /**\r
- * Creates a field based on the data type that we want to edit\r
- * \r
- * @param dataType\r
- * The type that we want to edit using the field\r
- * @param fieldType\r
- * The type of field we want to create. If set to {@link Field}\r
- * then any type of field is accepted\r
- * @return A field that can be assigned to the given fieldType and that is\r
- * capable of editing the given type of data\r
- */\r
- <T extends Field> T createField(Class<?> dataType, Class<T> fieldType);\r
- }\r
++/*
++@VaadinApache2LicenseForJavaFiles@
++ */
++package com.vaadin.data.fieldgroup;
++
++import java.io.Serializable;
++
++import com.vaadin.ui.Field;
++
++/**
++ * Factory interface for creating new Field-instances based on the data type
++ * that should be edited.
++ *
++ * @author Vaadin Ltd.
++ * @version @version@
++ * @since 7.0
++ */
++public interface FieldGroupFieldFactory extends Serializable {
++ /**
++ * Creates a field based on the data type that we want to edit
++ *
++ * @param dataType
++ * The type that we want to edit using the field
++ * @param fieldType
++ * The type of field we want to create. If set to {@link Field}
++ * then any type of field is accepted
++ * @return A field that can be assigned to the given fieldType and that is
++ * capable of editing the given type of data
++ */
++ <T extends Field> T createField(Class<?> dataType, Class<T> fieldType);
++}
--- /dev/null
- /* \r
- @VaadinApache2LicenseForJavaFiles@\r
- */\r
- package com.vaadin.data.fieldgroup;\r
- \r
- import java.lang.annotation.ElementType;\r
- import java.lang.annotation.Retention;\r
- import java.lang.annotation.RetentionPolicy;\r
- import java.lang.annotation.Target;\r
- \r
- @Target({ ElementType.FIELD })\r
- @Retention(RetentionPolicy.RUNTIME)\r
- public @interface PropertyId {\r
- String value();\r
- }\r
++/*
++@VaadinApache2LicenseForJavaFiles@
++ */
++package com.vaadin.data.fieldgroup;
++
++import java.lang.annotation.ElementType;
++import java.lang.annotation.Retention;
++import java.lang.annotation.RetentionPolicy;
++import java.lang.annotation.Target;
++
++@Target({ ElementType.FIELD })
++@Retention(RetentionPolicy.RUNTIME)
++public @interface PropertyId {
++ String value();
++}
- /* \r
- @VaadinApache2LicenseForJavaFiles@\r
- */\r
- \r
- package com.vaadin.data.util;\r
- \r
- import java.io.BufferedReader;\r
- import java.io.BufferedWriter;\r
- import java.io.File;\r
- import java.io.FileInputStream;\r
- import java.io.FileNotFoundException;\r
- import java.io.FileOutputStream;\r
- import java.io.IOException;\r
- import java.io.InputStreamReader;\r
- import java.io.OutputStreamWriter;\r
- import java.nio.charset.Charset;\r
- \r
- /**\r
- * Property implementation for wrapping a text file.\r
- * \r
- * Supports reading and writing of a File from/to String.\r
- * \r
- * {@link ValueChangeListener}s are supported, but only fire when\r
- * setValue(Object) is explicitly called. {@link ReadOnlyStatusChangeListener}s\r
- * are supported but only fire when setReadOnly(boolean) is explicitly called.\r
- * \r
- */\r
- @SuppressWarnings("serial")\r
- public class TextFileProperty extends AbstractProperty<String> {\r
- \r
- private File file;\r
- private Charset charset = null;\r
- \r
- /**\r
- * Wrap given file with property interface.\r
- * \r
- * Setting the file to null works, but getValue() will return null.\r
- * \r
- * @param file\r
- * File to be wrapped.\r
- */\r
- public TextFileProperty(File file) {\r
- this.file = file;\r
- }\r
- \r
- /**\r
- * Wrap the given file with the property interface and specify character\r
- * set.\r
- * \r
- * Setting the file to null works, but getValue() will return null.\r
- * \r
- * @param file\r
- * File to be wrapped.\r
- * @param charset\r
- * Charset to be used for reading and writing the file.\r
- */\r
- public TextFileProperty(File file, Charset charset) {\r
- this.file = file;\r
- this.charset = charset;\r
- }\r
- \r
- /*\r
- * (non-Javadoc)\r
- * \r
- * @see com.vaadin.data.Property#getType()\r
- */\r
- public Class<String> getType() {\r
- return String.class;\r
- }\r
- \r
- /*\r
- * (non-Javadoc)\r
- * \r
- * @see com.vaadin.data.Property#getValue()\r
- */\r
- public String getValue() {\r
- if (file == null) {\r
- return null;\r
- }\r
- try {\r
- FileInputStream fis = new FileInputStream(file);\r
- InputStreamReader isr = charset == null ? new InputStreamReader(fis)\r
- : new InputStreamReader(fis, charset);\r
- BufferedReader r = new BufferedReader(isr);\r
- StringBuilder b = new StringBuilder();\r
- char buf[] = new char[8 * 1024];\r
- int len;\r
- while ((len = r.read(buf)) != -1) {\r
- b.append(buf, 0, len);\r
- }\r
- r.close();\r
- isr.close();\r
- fis.close();\r
- return b.toString();\r
- } catch (FileNotFoundException e) {\r
- return null;\r
- } catch (IOException e) {\r
- throw new RuntimeException(e);\r
- }\r
- }\r
- \r
- /*\r
- * (non-Javadoc)\r
- * \r
- * @see com.vaadin.data.Property#isReadOnly()\r
- */\r
- @Override\r
- public boolean isReadOnly() {\r
- return file == null || super.isReadOnly() || !file.canWrite();\r
- }\r
- \r
- /*\r
- * (non-Javadoc)\r
- * \r
- * @see com.vaadin.data.Property#setValue(java.lang.Object)\r
- */\r
- public void setValue(Object newValue) throws ReadOnlyException {\r
- if (isReadOnly()) {\r
- throw new ReadOnlyException();\r
- }\r
- if (file == null) {\r
- return;\r
- }\r
- \r
- try {\r
- FileOutputStream fos = new FileOutputStream(file);\r
- OutputStreamWriter osw = charset == null ? new OutputStreamWriter(\r
- fos) : new OutputStreamWriter(fos, charset);\r
- BufferedWriter w = new BufferedWriter(osw);\r
- w.append(newValue.toString());\r
- w.flush();\r
- w.close();\r
- osw.close();\r
- fos.close();\r
- fireValueChange();\r
- } catch (IOException e) {\r
- throw new RuntimeException(e);\r
- }\r
- }\r
- \r
- }\r
+ /*
+ @VaadinApache2LicenseForJavaFiles@
+ */
+
+ package com.vaadin.data.util;
+
+ import java.io.BufferedReader;
+ import java.io.BufferedWriter;
+ import java.io.File;
+ import java.io.FileInputStream;
+ import java.io.FileNotFoundException;
+ import java.io.FileOutputStream;
+ import java.io.IOException;
+ import java.io.InputStreamReader;
+ import java.io.OutputStreamWriter;
+ import java.nio.charset.Charset;
+
+ /**
+ * Property implementation for wrapping a text file.
+ *
+ * Supports reading and writing of a File from/to String.
+ *
+ * {@link ValueChangeListener}s are supported, but only fire when
+ * setValue(Object) is explicitly called. {@link ReadOnlyStatusChangeListener}s
+ * are supported but only fire when setReadOnly(boolean) is explicitly called.
+ *
+ */
+ @SuppressWarnings("serial")
-public class TextFileProperty extends AbstractProperty {
++public class TextFileProperty extends AbstractProperty<String> {
+
+ private File file;
+ private Charset charset = null;
+
+ /**
+ * Wrap given file with property interface.
+ *
+ * Setting the file to null works, but getValue() will return null.
+ *
+ * @param file
+ * File to be wrapped.
+ */
+ public TextFileProperty(File file) {
+ this.file = file;
+ }
+
+ /**
+ * Wrap the given file with the property interface and specify character
+ * set.
+ *
+ * Setting the file to null works, but getValue() will return null.
+ *
+ * @param file
+ * File to be wrapped.
+ * @param charset
+ * Charset to be used for reading and writing the file.
+ */
+ public TextFileProperty(File file, Charset charset) {
+ this.file = file;
+ this.charset = charset;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see com.vaadin.data.Property#getType()
+ */
- public Class<?> getType() {
++ public Class<String> getType() {
+ return String.class;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see com.vaadin.data.Property#getValue()
+ */
- public Object getValue() {
++ public String getValue() {
+ if (file == null) {
+ return null;
+ }
+ try {
+ FileInputStream fis = new FileInputStream(file);
+ InputStreamReader isr = charset == null ? new InputStreamReader(fis)
+ : new InputStreamReader(fis, charset);
+ BufferedReader r = new BufferedReader(isr);
+ StringBuilder b = new StringBuilder();
+ char buf[] = new char[8 * 1024];
+ int len;
+ while ((len = r.read(buf)) != -1) {
+ b.append(buf, 0, len);
+ }
+ r.close();
+ isr.close();
+ fis.close();
+ return b.toString();
+ } catch (FileNotFoundException e) {
+ return null;
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see com.vaadin.data.Property#isReadOnly()
+ */
+ @Override
+ public boolean isReadOnly() {
+ return file == null || super.isReadOnly() || !file.canWrite();
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see com.vaadin.data.Property#setValue(java.lang.Object)
+ */
+ public void setValue(Object newValue) throws ReadOnlyException {
+ if (isReadOnly()) {
+ throw new ReadOnlyException();
+ }
+ if (file == null) {
+ return;
+ }
+
+ try {
+ FileOutputStream fos = new FileOutputStream(file);
+ OutputStreamWriter osw = charset == null ? new OutputStreamWriter(
+ fos) : new OutputStreamWriter(fos, charset);
+ BufferedWriter w = new BufferedWriter(osw);
+ w.append(newValue.toString());
+ w.flush();
+ w.close();
+ osw.close();
+ fos.close();
+ fireValueChange();
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ }
--- /dev/null
- /* \r
- @VaadinApache2LicenseForJavaFiles@\r
- */\r
- package com.vaadin.data.util;\r
- \r
- import com.vaadin.data.Property;\r
- import com.vaadin.data.Property.ValueChangeEvent;\r
- import com.vaadin.data.Property.ValueChangeNotifier;\r
- \r
- /**\r
- * Wrapper class that helps implement two-phase commit for a non-transactional\r
- * property.\r
- * \r
- * When accessing the property through the wrapper, getting and setting the\r
- * property value take place immediately. However, the wrapper keeps track of\r
- * the old value of the property so that it can be set for the property in case\r
- * of a roll-back. This can result in the underlying property value changing\r
- * multiple times (first based on modifications made by the application, then\r
- * back upon roll-back).\r
- * \r
- * Value change events on the {@link TransactionalPropertyWrapper} are only\r
- * fired at the end of a successful transaction, whereas listeners attached to\r
- * the underlying property may receive multiple value change events.\r
- * \r
- * @see com.vaadin.data.Property.Transactional\r
- * \r
- * @author Vaadin Ltd\r
- * @version @version@\r
- * @since 7.0\r
- * \r
- * @param <T>\r
- */\r
- public class TransactionalPropertyWrapper<T> extends AbstractProperty<T>\r
- implements ValueChangeNotifier, Property.Transactional<T> {\r
- \r
- private Property<T> wrappedProperty;\r
- private boolean inTransaction = false;\r
- private boolean valueChangePending;\r
- private T valueBeforeTransaction;\r
- \r
- public TransactionalPropertyWrapper(Property<T> wrappedProperty) {\r
- this.wrappedProperty = wrappedProperty;\r
- if (wrappedProperty instanceof ValueChangeNotifier) {\r
- ((ValueChangeNotifier) wrappedProperty)\r
- .addListener(new ValueChangeListener() {\r
- \r
- public void valueChange(ValueChangeEvent event) {\r
- fireValueChange();\r
- }\r
- });\r
- }\r
- }\r
- \r
- public Class getType() {\r
- return wrappedProperty.getType();\r
- }\r
- \r
- public T getValue() {\r
- return wrappedProperty.getValue();\r
- }\r
- \r
- public void setValue(Object newValue) throws ReadOnlyException {\r
- // Causes a value change to be sent to this listener which in turn fires\r
- // a new value change event for this property\r
- wrappedProperty.setValue(newValue);\r
- }\r
- \r
- public void startTransaction() {\r
- inTransaction = true;\r
- valueBeforeTransaction = getValue();\r
- }\r
- \r
- public void commit() {\r
- endTransaction();\r
- }\r
- \r
- public void rollback() {\r
- try {\r
- wrappedProperty.setValue(valueBeforeTransaction);\r
- } finally {\r
- valueChangePending = false;\r
- endTransaction();\r
- }\r
- }\r
- \r
- protected void endTransaction() {\r
- inTransaction = false;\r
- valueBeforeTransaction = null;\r
- if (valueChangePending) {\r
- fireValueChange();\r
- }\r
- }\r
- \r
- @Override\r
- protected void fireValueChange() {\r
- if (inTransaction) {\r
- valueChangePending = true;\r
- } else {\r
- super.fireValueChange();\r
- }\r
- }\r
- \r
- public Property<T> getWrappedProperty() {\r
- return wrappedProperty;\r
- }\r
- \r
- }\r
++/*
++@VaadinApache2LicenseForJavaFiles@
++ */
++package com.vaadin.data.util;
++
++import com.vaadin.data.Property;
++import com.vaadin.data.Property.ValueChangeEvent;
++import com.vaadin.data.Property.ValueChangeNotifier;
++
++/**
++ * Wrapper class that helps implement two-phase commit for a non-transactional
++ * property.
++ *
++ * When accessing the property through the wrapper, getting and setting the
++ * property value take place immediately. However, the wrapper keeps track of
++ * the old value of the property so that it can be set for the property in case
++ * of a roll-back. This can result in the underlying property value changing
++ * multiple times (first based on modifications made by the application, then
++ * back upon roll-back).
++ *
++ * Value change events on the {@link TransactionalPropertyWrapper} are only
++ * fired at the end of a successful transaction, whereas listeners attached to
++ * the underlying property may receive multiple value change events.
++ *
++ * @see com.vaadin.data.Property.Transactional
++ *
++ * @author Vaadin Ltd
++ * @version @version@
++ * @since 7.0
++ *
++ * @param <T>
++ */
++public class TransactionalPropertyWrapper<T> extends AbstractProperty<T>
++ implements ValueChangeNotifier, Property.Transactional<T> {
++
++ private Property<T> wrappedProperty;
++ private boolean inTransaction = false;
++ private boolean valueChangePending;
++ private T valueBeforeTransaction;
++
++ public TransactionalPropertyWrapper(Property<T> wrappedProperty) {
++ this.wrappedProperty = wrappedProperty;
++ if (wrappedProperty instanceof ValueChangeNotifier) {
++ ((ValueChangeNotifier) wrappedProperty)
++ .addListener(new ValueChangeListener() {
++
++ public void valueChange(ValueChangeEvent event) {
++ fireValueChange();
++ }
++ });
++ }
++ }
++
++ public Class getType() {
++ return wrappedProperty.getType();
++ }
++
++ public T getValue() {
++ return wrappedProperty.getValue();
++ }
++
++ public void setValue(Object newValue) throws ReadOnlyException {
++ // Causes a value change to be sent to this listener which in turn fires
++ // a new value change event for this property
++ wrappedProperty.setValue(newValue);
++ }
++
++ public void startTransaction() {
++ inTransaction = true;
++ valueBeforeTransaction = getValue();
++ }
++
++ public void commit() {
++ endTransaction();
++ }
++
++ public void rollback() {
++ try {
++ wrappedProperty.setValue(valueBeforeTransaction);
++ } finally {
++ valueChangePending = false;
++ endTransaction();
++ }
++ }
++
++ protected void endTransaction() {
++ inTransaction = false;
++ valueBeforeTransaction = null;
++ if (valueChangePending) {
++ fireValueChange();
++ }
++ }
++
++ @Override
++ protected void fireValueChange() {
++ if (inTransaction) {
++ valueChangePending = true;
++ } else {
++ super.fireValueChange();
++ }
++ }
++
++ public Property<T> getWrappedProperty() {
++ return wrappedProperty;
++ }
++
++}
--- /dev/null
- /*\r
- @VaadinApache2LicenseForJavaFiles@\r
- */\r
- \r
- package com.vaadin.data.util.converter;\r
- \r
- import java.io.Serializable;\r
- import java.util.Locale;\r
- \r
- /**\r
- * Interface that implements conversion between a model and a presentation type.\r
- * <p>\r
- * Typically {@link #convertToPresentation(Object, Locale)} and\r
- * {@link #convertToModel(Object, Locale)} should be symmetric so that chaining\r
- * these together returns the original result for all input but this is not a\r
- * requirement.\r
- * </p>\r
- * <p>\r
- * Converters must not have any side effects (never update UI from inside a\r
- * converter).\r
- * </p>\r
- * <p>\r
- * All Converters must be stateless and thread safe.\r
- * </p>\r
- * <p>\r
- * If conversion of a value fails, a {@link ConversionException} is thrown.\r
- * </p>\r
- * \r
- * @param <MODEL>\r
- * The model type. Must be compatible with what\r
- * {@link #getModelType()} returns.\r
- * @param <PRESENTATION>\r
- * The presentation type. Must be compatible with what\r
- * {@link #getPresentationType()} returns.\r
- * @author Vaadin Ltd.\r
- * @version\r
- * @VERSION@\r
- * @since 7.0\r
- */\r
- public interface Converter<PRESENTATION, MODEL> extends Serializable {\r
- \r
- /**\r
- * Converts the given value from target type to source type.\r
- * <p>\r
- * A converter can optionally use locale to do the conversion.\r
- * </p>\r
- * A converter should in most cases be symmetric so chaining\r
- * {@link #convertToPresentation(Object, Locale)} and\r
- * {@link #convertToModel(Object, Locale)} should return the original value.\r
- * \r
- * @param value\r
- * The value to convert, compatible with the target type. Can be\r
- * null\r
- * @param locale\r
- * The locale to use for conversion. Can be null.\r
- * @return The converted value compatible with the source type\r
- * @throws ConversionException\r
- * If the value could not be converted\r
- */\r
- public MODEL convertToModel(PRESENTATION value, Locale locale)\r
- throws ConversionException;\r
- \r
- /**\r
- * Converts the given value from source type to target type.\r
- * <p>\r
- * A converter can optionally use locale to do the conversion.\r
- * </p>\r
- * A converter should in most cases be symmetric so chaining\r
- * {@link #convertToPresentation(Object, Locale)} and\r
- * {@link #convertToModel(Object, Locale)} should return the original value.\r
- * \r
- * @param value\r
- * The value to convert, compatible with the target type. Can be\r
- * null\r
- * @param locale\r
- * The locale to use for conversion. Can be null.\r
- * @return The converted value compatible with the source type\r
- * @throws ConversionException\r
- * If the value could not be converted\r
- */\r
- public PRESENTATION convertToPresentation(MODEL value, Locale locale)\r
- throws ConversionException;\r
- \r
- /**\r
- * The source type of the converter.\r
- * \r
- * Values of this type can be passed to\r
- * {@link #convertToPresentation(Object, Locale)}.\r
- * \r
- * @return The source type\r
- */\r
- public Class<MODEL> getModelType();\r
- \r
- /**\r
- * The target type of the converter.\r
- * \r
- * Values of this type can be passed to\r
- * {@link #convertToModel(Object, Locale)}.\r
- * \r
- * @return The target type\r
- */\r
- public Class<PRESENTATION> getPresentationType();\r
- \r
- /**\r
- * An exception that signals that the value passed to\r
- * {@link Converter#convertToPresentation(Object, Locale)} or\r
- * {@link Converter#convertToModel(Object, Locale)} could not be converted.\r
- * \r
- * @author Vaadin Ltd\r
- * @version\r
- * @VERSION@\r
- * @since 7.0\r
- */\r
- public static class ConversionException extends RuntimeException {\r
- \r
- /**\r
- * Constructs a new <code>ConversionException</code> without a detail\r
- * message.\r
- */\r
- public ConversionException() {\r
- }\r
- \r
- /**\r
- * Constructs a new <code>ConversionException</code> with the specified\r
- * detail message.\r
- * \r
- * @param msg\r
- * the detail message\r
- */\r
- public ConversionException(String msg) {\r
- super(msg);\r
- }\r
- \r
- /**\r
- * Constructs a new {@code ConversionException} with the specified\r
- * cause.\r
- * \r
- * @param cause\r
- * The cause of the the exception\r
- */\r
- public ConversionException(Throwable cause) {\r
- super(cause);\r
- }\r
- \r
- /**\r
- * Constructs a new <code>ConversionException</code> with the specified\r
- * detail message and cause.\r
- * \r
- * @param message\r
- * the detail message\r
- * @param cause\r
- * The cause of the the exception\r
- */\r
- public ConversionException(String message, Throwable cause) {\r
- super(message, cause);\r
- }\r
- }\r
- \r
- }\r
++/*
++@VaadinApache2LicenseForJavaFiles@
++ */
++
++package com.vaadin.data.util.converter;
++
++import java.io.Serializable;
++import java.util.Locale;
++
++/**
++ * Interface that implements conversion between a model and a presentation type.
++ * <p>
++ * Typically {@link #convertToPresentation(Object, Locale)} and
++ * {@link #convertToModel(Object, Locale)} should be symmetric so that chaining
++ * these together returns the original result for all input but this is not a
++ * requirement.
++ * </p>
++ * <p>
++ * Converters must not have any side effects (never update UI from inside a
++ * converter).
++ * </p>
++ * <p>
++ * All Converters must be stateless and thread safe.
++ * </p>
++ * <p>
++ * If conversion of a value fails, a {@link ConversionException} is thrown.
++ * </p>
++ *
++ * @param <MODEL>
++ * The model type. Must be compatible with what
++ * {@link #getModelType()} returns.
++ * @param <PRESENTATION>
++ * The presentation type. Must be compatible with what
++ * {@link #getPresentationType()} returns.
++ * @author Vaadin Ltd.
++ * @version
++ * @VERSION@
++ * @since 7.0
++ */
++public interface Converter<PRESENTATION, MODEL> extends Serializable {
++
++ /**
++ * Converts the given value from target type to source type.
++ * <p>
++ * A converter can optionally use locale to do the conversion.
++ * </p>
++ * A converter should in most cases be symmetric so chaining
++ * {@link #convertToPresentation(Object, Locale)} and
++ * {@link #convertToModel(Object, Locale)} should return the original value.
++ *
++ * @param value
++ * The value to convert, compatible with the target type. Can be
++ * null
++ * @param locale
++ * The locale to use for conversion. Can be null.
++ * @return The converted value compatible with the source type
++ * @throws ConversionException
++ * If the value could not be converted
++ */
++ public MODEL convertToModel(PRESENTATION value, Locale locale)
++ throws ConversionException;
++
++ /**
++ * Converts the given value from source type to target type.
++ * <p>
++ * A converter can optionally use locale to do the conversion.
++ * </p>
++ * A converter should in most cases be symmetric so chaining
++ * {@link #convertToPresentation(Object, Locale)} and
++ * {@link #convertToModel(Object, Locale)} should return the original value.
++ *
++ * @param value
++ * The value to convert, compatible with the target type. Can be
++ * null
++ * @param locale
++ * The locale to use for conversion. Can be null.
++ * @return The converted value compatible with the source type
++ * @throws ConversionException
++ * If the value could not be converted
++ */
++ public PRESENTATION convertToPresentation(MODEL value, Locale locale)
++ throws ConversionException;
++
++ /**
++ * The source type of the converter.
++ *
++ * Values of this type can be passed to
++ * {@link #convertToPresentation(Object, Locale)}.
++ *
++ * @return The source type
++ */
++ public Class<MODEL> getModelType();
++
++ /**
++ * The target type of the converter.
++ *
++ * Values of this type can be passed to
++ * {@link #convertToModel(Object, Locale)}.
++ *
++ * @return The target type
++ */
++ public Class<PRESENTATION> getPresentationType();
++
++ /**
++ * An exception that signals that the value passed to
++ * {@link Converter#convertToPresentation(Object, Locale)} or
++ * {@link Converter#convertToModel(Object, Locale)} could not be converted.
++ *
++ * @author Vaadin Ltd
++ * @version
++ * @VERSION@
++ * @since 7.0
++ */
++ public static class ConversionException extends RuntimeException {
++
++ /**
++ * Constructs a new <code>ConversionException</code> without a detail
++ * message.
++ */
++ public ConversionException() {
++ }
++
++ /**
++ * Constructs a new <code>ConversionException</code> with the specified
++ * detail message.
++ *
++ * @param msg
++ * the detail message
++ */
++ public ConversionException(String msg) {
++ super(msg);
++ }
++
++ /**
++ * Constructs a new {@code ConversionException} with the specified
++ * cause.
++ *
++ * @param cause
++ * The cause of the the exception
++ */
++ public ConversionException(Throwable cause) {
++ super(cause);
++ }
++
++ /**
++ * Constructs a new <code>ConversionException</code> with the specified
++ * detail message and cause.
++ *
++ * @param message
++ * the detail message
++ * @param cause
++ * The cause of the the exception
++ */
++ public ConversionException(String message, Throwable cause) {
++ super(message, cause);
++ }
++ }
++
++}
--- /dev/null
- /*\r
- @VaadinApache2LicenseForJavaFiles@\r
- */\r
- \r
- package com.vaadin.data.util.converter;\r
- \r
- import java.io.Serializable;\r
- \r
- /**\r
- * Factory interface for providing Converters based on a presentation type and a\r
- * model type.\r
- * \r
- * @author Vaadin Ltd.\r
- * @version\r
- * @VERSION@\r
- * @since 7.0\r
- * \r
- */\r
- public interface ConverterFactory extends Serializable {\r
- public <PRESENTATION, MODEL> Converter<PRESENTATION, MODEL> createConverter(\r
- Class<PRESENTATION> presentationType, Class<MODEL> modelType);\r
- \r
- }\r
++/*
++@VaadinApache2LicenseForJavaFiles@
++ */
++
++package com.vaadin.data.util.converter;
++
++import java.io.Serializable;
++
++/**
++ * Factory interface for providing Converters based on a presentation type and a
++ * model type.
++ *
++ * @author Vaadin Ltd.
++ * @version
++ * @VERSION@
++ * @since 7.0
++ *
++ */
++public interface ConverterFactory extends Serializable {
++ public <PRESENTATION, MODEL> Converter<PRESENTATION, MODEL> createConverter(
++ Class<PRESENTATION> presentationType, Class<MODEL> modelType);
++
++}
--- /dev/null
- /*\r
- @VaadinApache2LicenseForJavaFiles@\r
- */\r
- \r
- package com.vaadin.data.util.converter;\r
- \r
- import java.util.Date;\r
- import java.util.Locale;\r
- \r
- /**\r
- * A converter that converts from {@link Long} to {@link Date} and back.\r
- * \r
- * @author Vaadin Ltd\r
- * @version\r
- * @VERSION@\r
- * @since 7.0\r
- */\r
- public class DateToLongConverter implements Converter<Date, Long> {\r
- \r
- /*\r
- * (non-Javadoc)\r
- * \r
- * @see\r
- * com.vaadin.data.util.converter.Converter#convertToModel(java.lang.Object,\r
- * java.util.Locale)\r
- */\r
- public Long convertToModel(Date value, Locale locale) {\r
- if (value == null) {\r
- return null;\r
- }\r
- \r
- return value.getTime();\r
- }\r
- \r
- /*\r
- * (non-Javadoc)\r
- * \r
- * @see\r
- * com.vaadin.data.util.converter.Converter#convertToPresentation(java.lang\r
- * .Object, java.util.Locale)\r
- */\r
- public Date convertToPresentation(Long value, Locale locale) {\r
- if (value == null) {\r
- return null;\r
- }\r
- \r
- return new Date(value);\r
- }\r
- \r
- /*\r
- * (non-Javadoc)\r
- * \r
- * @see com.vaadin.data.util.converter.Converter#getModelType()\r
- */\r
- public Class<Long> getModelType() {\r
- return Long.class;\r
- }\r
- \r
- /*\r
- * (non-Javadoc)\r
- * \r
- * @see com.vaadin.data.util.converter.Converter#getPresentationType()\r
- */\r
- public Class<Date> getPresentationType() {\r
- return Date.class;\r
- }\r
- \r
- }\r
++/*
++@VaadinApache2LicenseForJavaFiles@
++ */
++
++package com.vaadin.data.util.converter;
++
++import java.util.Date;
++import java.util.Locale;
++
++/**
++ * A converter that converts from {@link Long} to {@link Date} and back.
++ *
++ * @author Vaadin Ltd
++ * @version
++ * @VERSION@
++ * @since 7.0
++ */
++public class DateToLongConverter implements Converter<Date, Long> {
++
++ /*
++ * (non-Javadoc)
++ *
++ * @see
++ * com.vaadin.data.util.converter.Converter#convertToModel(java.lang.Object,
++ * java.util.Locale)
++ */
++ public Long convertToModel(Date value, Locale locale) {
++ if (value == null) {
++ return null;
++ }
++
++ return value.getTime();
++ }
++
++ /*
++ * (non-Javadoc)
++ *
++ * @see
++ * com.vaadin.data.util.converter.Converter#convertToPresentation(java.lang
++ * .Object, java.util.Locale)
++ */
++ public Date convertToPresentation(Long value, Locale locale) {
++ if (value == null) {
++ return null;
++ }
++
++ return new Date(value);
++ }
++
++ /*
++ * (non-Javadoc)
++ *
++ * @see com.vaadin.data.util.converter.Converter#getModelType()
++ */
++ public Class<Long> getModelType() {
++ return Long.class;
++ }
++
++ /*
++ * (non-Javadoc)
++ *
++ * @see com.vaadin.data.util.converter.Converter#getPresentationType()
++ */
++ public Class<Date> getPresentationType() {
++ return Date.class;
++ }
++
++}
--- /dev/null
- /*\r
- @VaadinApache2LicenseForJavaFiles@\r
- */\r
- \r
- package com.vaadin.data.util.converter;\r
- \r
- import java.util.Date;\r
- import java.util.logging.Logger;\r
- \r
- import com.vaadin.Application;\r
- \r
- /**\r
- * Default implementation of {@link ConverterFactory}. Provides converters for\r
- * standard types like {@link String}, {@link Double} and {@link Date}. </p>\r
- * <p>\r
- * Custom converters can be provided by extending this class and using\r
- * {@link Application#setConverterFactory(ConverterFactory)}.\r
- * </p>\r
- * \r
- * @author Vaadin Ltd\r
- * @version\r
- * @VERSION@\r
- * @since 7.0\r
- */\r
- public class DefaultConverterFactory implements ConverterFactory {\r
- \r
- private final static Logger log = Logger\r
- .getLogger(DefaultConverterFactory.class.getName());\r
- \r
- public <PRESENTATION, MODEL> Converter<PRESENTATION, MODEL> createConverter(\r
- Class<PRESENTATION> presentationType, Class<MODEL> modelType) {\r
- Converter<PRESENTATION, MODEL> converter = findConverter(\r
- presentationType, modelType);\r
- if (converter != null) {\r
- log.finest(getClass().getName() + " created a "\r
- + converter.getClass());\r
- return converter;\r
- }\r
- \r
- // Try to find a reverse converter\r
- Converter<MODEL, PRESENTATION> reverseConverter = findConverter(\r
- modelType, presentationType);\r
- if (reverseConverter != null) {\r
- log.finest(getClass().getName() + " created a reverse "\r
- + reverseConverter.getClass());\r
- return new ReverseConverter<PRESENTATION, MODEL>(reverseConverter);\r
- }\r
- \r
- log.finest(getClass().getName() + " could not find a converter for "\r
- + presentationType.getName() + " to " + modelType.getName()\r
- + " conversion");\r
- return null;\r
- \r
- }\r
- \r
- protected <PRESENTATION, MODEL> Converter<PRESENTATION, MODEL> findConverter(\r
- Class<PRESENTATION> presentationType, Class<MODEL> modelType) {\r
- if (presentationType == String.class) {\r
- // TextField converters and more\r
- Converter<PRESENTATION, MODEL> converter = (Converter<PRESENTATION, MODEL>) createStringConverter(modelType);\r
- if (converter != null) {\r
- return converter;\r
- }\r
- } else if (presentationType == Date.class) {\r
- // DateField converters and more\r
- Converter<PRESENTATION, MODEL> converter = (Converter<PRESENTATION, MODEL>) createDateConverter(modelType);\r
- if (converter != null) {\r
- return converter;\r
- }\r
- }\r
- \r
- return null;\r
- \r
- }\r
- \r
- protected Converter<Date, ?> createDateConverter(Class<?> sourceType) {\r
- if (Long.class.isAssignableFrom(sourceType)) {\r
- return new DateToLongConverter();\r
- } else {\r
- return null;\r
- }\r
- }\r
- \r
- protected Converter<String, ?> createStringConverter(Class<?> sourceType) {\r
- if (Double.class.isAssignableFrom(sourceType)) {\r
- return new StringToDoubleConverter();\r
- } else if (Integer.class.isAssignableFrom(sourceType)) {\r
- return new StringToIntegerConverter();\r
- } else if (Boolean.class.isAssignableFrom(sourceType)) {\r
- return new StringToBooleanConverter();\r
- } else if (Number.class.isAssignableFrom(sourceType)) {\r
- return new StringToNumberConverter();\r
- } else if (Date.class.isAssignableFrom(sourceType)) {\r
- return new StringToDateConverter();\r
- } else {\r
- return null;\r
- }\r
- }\r
- \r
- }\r
++/*
++@VaadinApache2LicenseForJavaFiles@
++ */
++
++package com.vaadin.data.util.converter;
++
++import java.util.Date;
++import java.util.logging.Logger;
++
++import com.vaadin.Application;
++
++/**
++ * Default implementation of {@link ConverterFactory}. Provides converters for
++ * standard types like {@link String}, {@link Double} and {@link Date}. </p>
++ * <p>
++ * Custom converters can be provided by extending this class and using
++ * {@link Application#setConverterFactory(ConverterFactory)}.
++ * </p>
++ *
++ * @author Vaadin Ltd
++ * @version
++ * @VERSION@
++ * @since 7.0
++ */
++public class DefaultConverterFactory implements ConverterFactory {
++
++ private final static Logger log = Logger
++ .getLogger(DefaultConverterFactory.class.getName());
++
++ public <PRESENTATION, MODEL> Converter<PRESENTATION, MODEL> createConverter(
++ Class<PRESENTATION> presentationType, Class<MODEL> modelType) {
++ Converter<PRESENTATION, MODEL> converter = findConverter(
++ presentationType, modelType);
++ if (converter != null) {
++ log.finest(getClass().getName() + " created a "
++ + converter.getClass());
++ return converter;
++ }
++
++ // Try to find a reverse converter
++ Converter<MODEL, PRESENTATION> reverseConverter = findConverter(
++ modelType, presentationType);
++ if (reverseConverter != null) {
++ log.finest(getClass().getName() + " created a reverse "
++ + reverseConverter.getClass());
++ return new ReverseConverter<PRESENTATION, MODEL>(reverseConverter);
++ }
++
++ log.finest(getClass().getName() + " could not find a converter for "
++ + presentationType.getName() + " to " + modelType.getName()
++ + " conversion");
++ return null;
++
++ }
++
++ protected <PRESENTATION, MODEL> Converter<PRESENTATION, MODEL> findConverter(
++ Class<PRESENTATION> presentationType, Class<MODEL> modelType) {
++ if (presentationType == String.class) {
++ // TextField converters and more
++ Converter<PRESENTATION, MODEL> converter = (Converter<PRESENTATION, MODEL>) createStringConverter(modelType);
++ if (converter != null) {
++ return converter;
++ }
++ } else if (presentationType == Date.class) {
++ // DateField converters and more
++ Converter<PRESENTATION, MODEL> converter = (Converter<PRESENTATION, MODEL>) createDateConverter(modelType);
++ if (converter != null) {
++ return converter;
++ }
++ }
++
++ return null;
++
++ }
++
++ protected Converter<Date, ?> createDateConverter(Class<?> sourceType) {
++ if (Long.class.isAssignableFrom(sourceType)) {
++ return new DateToLongConverter();
++ } else {
++ return null;
++ }
++ }
++
++ protected Converter<String, ?> createStringConverter(Class<?> sourceType) {
++ if (Double.class.isAssignableFrom(sourceType)) {
++ return new StringToDoubleConverter();
++ } else if (Integer.class.isAssignableFrom(sourceType)) {
++ return new StringToIntegerConverter();
++ } else if (Boolean.class.isAssignableFrom(sourceType)) {
++ return new StringToBooleanConverter();
++ } else if (Number.class.isAssignableFrom(sourceType)) {
++ return new StringToNumberConverter();
++ } else if (Date.class.isAssignableFrom(sourceType)) {
++ return new StringToDateConverter();
++ } else {
++ return null;
++ }
++ }
++
++}
--- /dev/null
- /*\r
- @VaadinApache2LicenseForJavaFiles@\r
- */\r
- \r
- package com.vaadin.data.util.converter;\r
- \r
- import java.util.Locale;\r
- \r
- /**\r
- * A converter that wraps another {@link Converter} and reverses source and\r
- * target types.\r
- * \r
- * @param <MODEL>\r
- * The source type\r
- * @param <PRESENTATION>\r
- * The target type\r
- * \r
- * @author Vaadin Ltd\r
- * @version\r
- * @VERSION@\r
- * @since 7.0\r
- */\r
- public class ReverseConverter<PRESENTATION, MODEL> implements\r
- Converter<PRESENTATION, MODEL> {\r
- \r
- private Converter<MODEL, PRESENTATION> realConverter;\r
- \r
- /**\r
- * Creates a converter from source to target based on a converter that\r
- * converts from target to source.\r
- * \r
- * @param converter\r
- * The converter to use in a reverse fashion\r
- */\r
- public ReverseConverter(Converter<MODEL, PRESENTATION> converter) {\r
- this.realConverter = converter;\r
- }\r
- \r
- /*\r
- * (non-Javadoc)\r
- * \r
- * @see com.vaadin.data.util.converter.Converter#convertToModel(java\r
- * .lang.Object, java.util.Locale)\r
- */\r
- public MODEL convertToModel(PRESENTATION value, Locale locale)\r
- throws com.vaadin.data.util.converter.Converter.ConversionException {\r
- return realConverter.convertToPresentation(value, locale);\r
- }\r
- \r
- /*\r
- * (non-Javadoc)\r
- * \r
- * @see\r
- * com.vaadin.data.util.converter.Converter#convertToPresentation(java.lang\r
- * .Object, java.util.Locale)\r
- */\r
- public PRESENTATION convertToPresentation(MODEL value, Locale locale)\r
- throws com.vaadin.data.util.converter.Converter.ConversionException {\r
- return realConverter.convertToModel(value, locale);\r
- }\r
- \r
- /*\r
- * (non-Javadoc)\r
- * \r
- * @see com.vaadin.data.util.converter.Converter#getSourceType()\r
- */\r
- public Class<MODEL> getModelType() {\r
- return realConverter.getPresentationType();\r
- }\r
- \r
- /*\r
- * (non-Javadoc)\r
- * \r
- * @see com.vaadin.data.util.converter.Converter#getTargetType()\r
- */\r
- public Class<PRESENTATION> getPresentationType() {\r
- return realConverter.getModelType();\r
- }\r
- \r
- }\r
++/*
++@VaadinApache2LicenseForJavaFiles@
++ */
++
++package com.vaadin.data.util.converter;
++
++import java.util.Locale;
++
++/**
++ * A converter that wraps another {@link Converter} and reverses source and
++ * target types.
++ *
++ * @param <MODEL>
++ * The source type
++ * @param <PRESENTATION>
++ * The target type
++ *
++ * @author Vaadin Ltd
++ * @version
++ * @VERSION@
++ * @since 7.0
++ */
++public class ReverseConverter<PRESENTATION, MODEL> implements
++ Converter<PRESENTATION, MODEL> {
++
++ private Converter<MODEL, PRESENTATION> realConverter;
++
++ /**
++ * Creates a converter from source to target based on a converter that
++ * converts from target to source.
++ *
++ * @param converter
++ * The converter to use in a reverse fashion
++ */
++ public ReverseConverter(Converter<MODEL, PRESENTATION> converter) {
++ this.realConverter = converter;
++ }
++
++ /*
++ * (non-Javadoc)
++ *
++ * @see com.vaadin.data.util.converter.Converter#convertToModel(java
++ * .lang.Object, java.util.Locale)
++ */
++ public MODEL convertToModel(PRESENTATION value, Locale locale)
++ throws com.vaadin.data.util.converter.Converter.ConversionException {
++ return realConverter.convertToPresentation(value, locale);
++ }
++
++ /*
++ * (non-Javadoc)
++ *
++ * @see
++ * com.vaadin.data.util.converter.Converter#convertToPresentation(java.lang
++ * .Object, java.util.Locale)
++ */
++ public PRESENTATION convertToPresentation(MODEL value, Locale locale)
++ throws com.vaadin.data.util.converter.Converter.ConversionException {
++ return realConverter.convertToModel(value, locale);
++ }
++
++ /*
++ * (non-Javadoc)
++ *
++ * @see com.vaadin.data.util.converter.Converter#getSourceType()
++ */
++ public Class<MODEL> getModelType() {
++ return realConverter.getPresentationType();
++ }
++
++ /*
++ * (non-Javadoc)
++ *
++ * @see com.vaadin.data.util.converter.Converter#getTargetType()
++ */
++ public Class<PRESENTATION> getPresentationType() {
++ return realConverter.getModelType();
++ }
++
++}
--- /dev/null
- /*\r
- @VaadinApache2LicenseForJavaFiles@\r
- */\r
- \r
- package com.vaadin.data.util.converter;\r
- \r
- import java.util.Locale;\r
- \r
- /**\r
- * A converter that converts from {@link String} to {@link Boolean} and back.\r
- * The String representation is given by Boolean.toString().\r
- * <p>\r
- * Leading and trailing white spaces are ignored when converting from a String.\r
- * </p>\r
- * \r
- * @author Vaadin Ltd\r
- * @version\r
- * @VERSION@\r
- * @since 7.0\r
- */\r
- public class StringToBooleanConverter implements Converter<String, Boolean> {\r
- \r
- /*\r
- * (non-Javadoc)\r
- * \r
- * @see\r
- * com.vaadin.data.util.converter.Converter#convertToModel(java.lang.Object,\r
- * java.util.Locale)\r
- */\r
- public Boolean convertToModel(String value, Locale locale)\r
- throws ConversionException {\r
- if (value == null) {\r
- return null;\r
- }\r
- \r
- // Remove leading and trailing white space\r
- value = value.trim();\r
- \r
- if (getTrueString().equals(value)) {\r
- return true;\r
- } else if (getFalseString().equals(value)) {\r
- return false;\r
- } else {\r
- throw new ConversionException("Cannot convert " + value + " to "\r
- + getModelType().getName());\r
- }\r
- }\r
- \r
- /**\r
- * Gets the string representation for true. Default is "true".\r
- * \r
- * @return the string representation for true\r
- */\r
- protected String getTrueString() {\r
- return Boolean.TRUE.toString();\r
- }\r
- \r
- /**\r
- * Gets the string representation for false. Default is "false".\r
- * \r
- * @return the string representation for false\r
- */\r
- protected String getFalseString() {\r
- return Boolean.FALSE.toString();\r
- }\r
- \r
- /*\r
- * (non-Javadoc)\r
- * \r
- * @see\r
- * com.vaadin.data.util.converter.Converter#convertToPresentation(java.lang\r
- * .Object, java.util.Locale)\r
- */\r
- public String convertToPresentation(Boolean value, Locale locale)\r
- throws ConversionException {\r
- if (value == null) {\r
- return null;\r
- }\r
- if (value) {\r
- return getTrueString();\r
- } else {\r
- return getFalseString();\r
- }\r
- }\r
- \r
- /*\r
- * (non-Javadoc)\r
- * \r
- * @see com.vaadin.data.util.converter.Converter#getModelType()\r
- */\r
- public Class<Boolean> getModelType() {\r
- return Boolean.class;\r
- }\r
- \r
- /*\r
- * (non-Javadoc)\r
- * \r
- * @see com.vaadin.data.util.converter.Converter#getPresentationType()\r
- */\r
- public Class<String> getPresentationType() {\r
- return String.class;\r
- }\r
- \r
- }\r
++/*
++@VaadinApache2LicenseForJavaFiles@
++ */
++
++package com.vaadin.data.util.converter;
++
++import java.util.Locale;
++
++/**
++ * A converter that converts from {@link String} to {@link Boolean} and back.
++ * The String representation is given by Boolean.toString().
++ * <p>
++ * Leading and trailing white spaces are ignored when converting from a String.
++ * </p>
++ *
++ * @author Vaadin Ltd
++ * @version
++ * @VERSION@
++ * @since 7.0
++ */
++public class StringToBooleanConverter implements Converter<String, Boolean> {
++
++ /*
++ * (non-Javadoc)
++ *
++ * @see
++ * com.vaadin.data.util.converter.Converter#convertToModel(java.lang.Object,
++ * java.util.Locale)
++ */
++ public Boolean convertToModel(String value, Locale locale)
++ throws ConversionException {
++ if (value == null) {
++ return null;
++ }
++
++ // Remove leading and trailing white space
++ value = value.trim();
++
++ if (getTrueString().equals(value)) {
++ return true;
++ } else if (getFalseString().equals(value)) {
++ return false;
++ } else {
++ throw new ConversionException("Cannot convert " + value + " to "
++ + getModelType().getName());
++ }
++ }
++
++ /**
++ * Gets the string representation for true. Default is "true".
++ *
++ * @return the string representation for true
++ */
++ protected String getTrueString() {
++ return Boolean.TRUE.toString();
++ }
++
++ /**
++ * Gets the string representation for false. Default is "false".
++ *
++ * @return the string representation for false
++ */
++ protected String getFalseString() {
++ return Boolean.FALSE.toString();
++ }
++
++ /*
++ * (non-Javadoc)
++ *
++ * @see
++ * com.vaadin.data.util.converter.Converter#convertToPresentation(java.lang
++ * .Object, java.util.Locale)
++ */
++ public String convertToPresentation(Boolean value, Locale locale)
++ throws ConversionException {
++ if (value == null) {
++ return null;
++ }
++ if (value) {
++ return getTrueString();
++ } else {
++ return getFalseString();
++ }
++ }
++
++ /*
++ * (non-Javadoc)
++ *
++ * @see com.vaadin.data.util.converter.Converter#getModelType()
++ */
++ public Class<Boolean> getModelType() {
++ return Boolean.class;
++ }
++
++ /*
++ * (non-Javadoc)
++ *
++ * @see com.vaadin.data.util.converter.Converter#getPresentationType()
++ */
++ public Class<String> getPresentationType() {
++ return String.class;
++ }
++
++}
--- /dev/null
- /*\r
- @VaadinApache2LicenseForJavaFiles@\r
- */\r
- \r
- package com.vaadin.data.util.converter;\r
- \r
- import java.text.DateFormat;\r
- import java.text.ParsePosition;\r
- import java.util.Date;\r
- import java.util.Locale;\r
- \r
- /**\r
- * A converter that converts from {@link Date} to {@link String} and back. Uses\r
- * the given locale and {@link DateFormat} for formatting and parsing.\r
- * <p>\r
- * Leading and trailing white spaces are ignored when converting from a String.\r
- * </p>\r
- * <p>\r
- * Override and overwrite {@link #getFormat(Locale)} to use a different format.\r
- * </p>\r
- * \r
- * @author Vaadin Ltd\r
- * @version\r
- * @VERSION@\r
- * @since 7.0\r
- */\r
- public class StringToDateConverter implements Converter<String, Date> {\r
- \r
- /**\r
- * Returns the format used by {@link #convertToPresentation(Date, Locale)}\r
- * and {@link #convertToModel(String, Locale)}.\r
- * \r
- * @param locale\r
- * The locale to use\r
- * @return A DateFormat instance\r
- */\r
- protected DateFormat getFormat(Locale locale) {\r
- if (locale == null) {\r
- locale = Locale.getDefault();\r
- }\r
- \r
- DateFormat f = DateFormat.getDateTimeInstance(DateFormat.MEDIUM,\r
- DateFormat.MEDIUM, locale);\r
- f.setLenient(false);\r
- return f;\r
- }\r
- \r
- /*\r
- * (non-Javadoc)\r
- * \r
- * @see\r
- * com.vaadin.data.util.converter.Converter#convertToModel(java.lang.Object,\r
- * java.util.Locale)\r
- */\r
- public Date convertToModel(String value, Locale locale)\r
- throws com.vaadin.data.util.converter.Converter.ConversionException {\r
- if (value == null) {\r
- return null;\r
- }\r
- \r
- // Remove leading and trailing white space\r
- value = value.trim();\r
- \r
- ParsePosition parsePosition = new ParsePosition(0);\r
- Date parsedValue = getFormat(locale).parse(value, parsePosition);\r
- if (parsePosition.getIndex() != value.length()) {\r
- throw new ConversionException("Could not convert '" + value\r
- + "' to " + getModelType().getName());\r
- }\r
- \r
- return parsedValue;\r
- }\r
- \r
- /*\r
- * (non-Javadoc)\r
- * \r
- * @see\r
- * com.vaadin.data.util.converter.Converter#convertToPresentation(java.lang\r
- * .Object, java.util.Locale)\r
- */\r
- public String convertToPresentation(Date value, Locale locale)\r
- throws com.vaadin.data.util.converter.Converter.ConversionException {\r
- if (value == null) {\r
- return null;\r
- }\r
- \r
- return getFormat(locale).format(value);\r
- }\r
- \r
- /*\r
- * (non-Javadoc)\r
- * \r
- * @see com.vaadin.data.util.converter.Converter#getModelType()\r
- */\r
- public Class<Date> getModelType() {\r
- return Date.class;\r
- }\r
- \r
- /*\r
- * (non-Javadoc)\r
- * \r
- * @see com.vaadin.data.util.converter.Converter#getPresentationType()\r
- */\r
- public Class<String> getPresentationType() {\r
- return String.class;\r
- }\r
- \r
- }\r
++/*
++@VaadinApache2LicenseForJavaFiles@
++ */
++
++package com.vaadin.data.util.converter;
++
++import java.text.DateFormat;
++import java.text.ParsePosition;
++import java.util.Date;
++import java.util.Locale;
++
++/**
++ * A converter that converts from {@link Date} to {@link String} and back. Uses
++ * the given locale and {@link DateFormat} for formatting and parsing.
++ * <p>
++ * Leading and trailing white spaces are ignored when converting from a String.
++ * </p>
++ * <p>
++ * Override and overwrite {@link #getFormat(Locale)} to use a different format.
++ * </p>
++ *
++ * @author Vaadin Ltd
++ * @version
++ * @VERSION@
++ * @since 7.0
++ */
++public class StringToDateConverter implements Converter<String, Date> {
++
++ /**
++ * Returns the format used by {@link #convertToPresentation(Date, Locale)}
++ * and {@link #convertToModel(String, Locale)}.
++ *
++ * @param locale
++ * The locale to use
++ * @return A DateFormat instance
++ */
++ protected DateFormat getFormat(Locale locale) {
++ if (locale == null) {
++ locale = Locale.getDefault();
++ }
++
++ DateFormat f = DateFormat.getDateTimeInstance(DateFormat.MEDIUM,
++ DateFormat.MEDIUM, locale);
++ f.setLenient(false);
++ return f;
++ }
++
++ /*
++ * (non-Javadoc)
++ *
++ * @see
++ * com.vaadin.data.util.converter.Converter#convertToModel(java.lang.Object,
++ * java.util.Locale)
++ */
++ public Date convertToModel(String value, Locale locale)
++ throws com.vaadin.data.util.converter.Converter.ConversionException {
++ if (value == null) {
++ return null;
++ }
++
++ // Remove leading and trailing white space
++ value = value.trim();
++
++ ParsePosition parsePosition = new ParsePosition(0);
++ Date parsedValue = getFormat(locale).parse(value, parsePosition);
++ if (parsePosition.getIndex() != value.length()) {
++ throw new ConversionException("Could not convert '" + value
++ + "' to " + getModelType().getName());
++ }
++
++ return parsedValue;
++ }
++
++ /*
++ * (non-Javadoc)
++ *
++ * @see
++ * com.vaadin.data.util.converter.Converter#convertToPresentation(java.lang
++ * .Object, java.util.Locale)
++ */
++ public String convertToPresentation(Date value, Locale locale)
++ throws com.vaadin.data.util.converter.Converter.ConversionException {
++ if (value == null) {
++ return null;
++ }
++
++ return getFormat(locale).format(value);
++ }
++
++ /*
++ * (non-Javadoc)
++ *
++ * @see com.vaadin.data.util.converter.Converter#getModelType()
++ */
++ public Class<Date> getModelType() {
++ return Date.class;
++ }
++
++ /*
++ * (non-Javadoc)
++ *
++ * @see com.vaadin.data.util.converter.Converter#getPresentationType()
++ */
++ public Class<String> getPresentationType() {
++ return String.class;
++ }
++
++}
--- /dev/null
- /*\r
- @VaadinApache2LicenseForJavaFiles@\r
- */\r
- \r
- package com.vaadin.data.util.converter;\r
- \r
- import java.text.NumberFormat;\r
- import java.text.ParsePosition;\r
- import java.util.Locale;\r
- \r
- /**\r
- * A converter that converts from {@link String} to {@link Double} and back.\r
- * Uses the given locale and a {@link NumberFormat} instance for formatting and\r
- * parsing.\r
- * <p>\r
- * Leading and trailing white spaces are ignored when converting from a String.\r
- * </p>\r
- * <p>\r
- * Override and overwrite {@link #getFormat(Locale)} to use a different format.\r
- * </p>\r
- * \r
- * @author Vaadin Ltd\r
- * @version\r
- * @VERSION@\r
- * @since 7.0\r
- */\r
- public class StringToDoubleConverter implements Converter<String, Double> {\r
- \r
- /**\r
- * Returns the format used by {@link #convertToPresentation(Double, Locale)}\r
- * and {@link #convertToModel(String, Locale)}.\r
- * \r
- * @param locale\r
- * The locale to use\r
- * @return A NumberFormat instance\r
- */\r
- protected NumberFormat getFormat(Locale locale) {\r
- if (locale == null) {\r
- locale = Locale.getDefault();\r
- }\r
- \r
- return NumberFormat.getNumberInstance(locale);\r
- }\r
- \r
- /*\r
- * (non-Javadoc)\r
- * \r
- * @see\r
- * com.vaadin.data.util.converter.Converter#convertToModel(java.lang.Object,\r
- * java.util.Locale)\r
- */\r
- public Double convertToModel(String value, Locale locale)\r
- throws ConversionException {\r
- if (value == null) {\r
- return null;\r
- }\r
- \r
- // Remove leading and trailing white space\r
- value = value.trim();\r
- \r
- ParsePosition parsePosition = new ParsePosition(0);\r
- Number parsedValue = getFormat(locale).parse(value, parsePosition);\r
- if (parsePosition.getIndex() != value.length()) {\r
- throw new ConversionException("Could not convert '" + value\r
- + "' to " + getModelType().getName());\r
- }\r
- return parsedValue.doubleValue();\r
- }\r
- \r
- /*\r
- * (non-Javadoc)\r
- * \r
- * @see\r
- * com.vaadin.data.util.converter.Converter#convertToPresentation(java.lang\r
- * .Object, java.util.Locale)\r
- */\r
- public String convertToPresentation(Double value, Locale locale)\r
- throws ConversionException {\r
- if (value == null) {\r
- return null;\r
- }\r
- \r
- return getFormat(locale).format(value);\r
- }\r
- \r
- /*\r
- * (non-Javadoc)\r
- * \r
- * @see com.vaadin.data.util.converter.Converter#getModelType()\r
- */\r
- public Class<Double> getModelType() {\r
- return Double.class;\r
- }\r
- \r
- /*\r
- * (non-Javadoc)\r
- * \r
- * @see com.vaadin.data.util.converter.Converter#getPresentationType()\r
- */\r
- public Class<String> getPresentationType() {\r
- return String.class;\r
- }\r
- }\r
++/*
++@VaadinApache2LicenseForJavaFiles@
++ */
++
++package com.vaadin.data.util.converter;
++
++import java.text.NumberFormat;
++import java.text.ParsePosition;
++import java.util.Locale;
++
++/**
++ * A converter that converts from {@link String} to {@link Double} and back.
++ * Uses the given locale and a {@link NumberFormat} instance for formatting and
++ * parsing.
++ * <p>
++ * Leading and trailing white spaces are ignored when converting from a String.
++ * </p>
++ * <p>
++ * Override and overwrite {@link #getFormat(Locale)} to use a different format.
++ * </p>
++ *
++ * @author Vaadin Ltd
++ * @version
++ * @VERSION@
++ * @since 7.0
++ */
++public class StringToDoubleConverter implements Converter<String, Double> {
++
++ /**
++ * Returns the format used by {@link #convertToPresentation(Double, Locale)}
++ * and {@link #convertToModel(String, Locale)}.
++ *
++ * @param locale
++ * The locale to use
++ * @return A NumberFormat instance
++ */
++ protected NumberFormat getFormat(Locale locale) {
++ if (locale == null) {
++ locale = Locale.getDefault();
++ }
++
++ return NumberFormat.getNumberInstance(locale);
++ }
++
++ /*
++ * (non-Javadoc)
++ *
++ * @see
++ * com.vaadin.data.util.converter.Converter#convertToModel(java.lang.Object,
++ * java.util.Locale)
++ */
++ public Double convertToModel(String value, Locale locale)
++ throws ConversionException {
++ if (value == null) {
++ return null;
++ }
++
++ // Remove leading and trailing white space
++ value = value.trim();
++
++ ParsePosition parsePosition = new ParsePosition(0);
++ Number parsedValue = getFormat(locale).parse(value, parsePosition);
++ if (parsePosition.getIndex() != value.length()) {
++ throw new ConversionException("Could not convert '" + value
++ + "' to " + getModelType().getName());
++ }
++ return parsedValue.doubleValue();
++ }
++
++ /*
++ * (non-Javadoc)
++ *
++ * @see
++ * com.vaadin.data.util.converter.Converter#convertToPresentation(java.lang
++ * .Object, java.util.Locale)
++ */
++ public String convertToPresentation(Double value, Locale locale)
++ throws ConversionException {
++ if (value == null) {
++ return null;
++ }
++
++ return getFormat(locale).format(value);
++ }
++
++ /*
++ * (non-Javadoc)
++ *
++ * @see com.vaadin.data.util.converter.Converter#getModelType()
++ */
++ public Class<Double> getModelType() {
++ return Double.class;
++ }
++
++ /*
++ * (non-Javadoc)
++ *
++ * @see com.vaadin.data.util.converter.Converter#getPresentationType()
++ */
++ public Class<String> getPresentationType() {
++ return String.class;
++ }
++}
--- /dev/null
- /*\r
- @VaadinApache2LicenseForJavaFiles@\r
- */\r
- \r
- package com.vaadin.data.util.converter;\r
- \r
- import java.text.NumberFormat;\r
- import java.text.ParsePosition;\r
- import java.util.Locale;\r
- \r
- /**\r
- * A converter that converts from {@link String} to {@link Integer} and back.\r
- * Uses the given locale and a {@link NumberFormat} instance for formatting and\r
- * parsing.\r
- * <p>\r
- * Override and overwrite {@link #getFormat(Locale)} to use a different format.\r
- * </p>\r
- * \r
- * @author Vaadin Ltd\r
- * @version\r
- * @VERSION@\r
- * @since 7.0\r
- */\r
- public class StringToIntegerConverter implements Converter<String, Integer> {\r
- \r
- /**\r
- * Returns the format used by\r
- * {@link #convertToPresentation(Integer, Locale)} and\r
- * {@link #convertToModel(String, Locale)}.\r
- * \r
- * @param locale\r
- * The locale to use\r
- * @return A NumberFormat instance\r
- */\r
- protected NumberFormat getFormat(Locale locale) {\r
- if (locale == null) {\r
- locale = Locale.getDefault();\r
- }\r
- return NumberFormat.getIntegerInstance(locale);\r
- }\r
- \r
- public Integer convertToModel(String value, Locale locale)\r
- throws ConversionException {\r
- if (value == null) {\r
- return null;\r
- }\r
- \r
- // Remove leading and trailing white space\r
- value = value.trim();\r
- \r
- // Parse and detect errors. If the full string was not used, it is\r
- // an error.\r
- ParsePosition parsePosition = new ParsePosition(0);\r
- Number parsedValue = getFormat(locale).parse(value, parsePosition);\r
- if (parsePosition.getIndex() != value.length()) {\r
- throw new ConversionException("Could not convert '" + value\r
- + "' to " + getModelType().getName());\r
- }\r
- \r
- if (parsedValue == null) {\r
- // Convert "" to null\r
- return null;\r
- }\r
- return parsedValue.intValue();\r
- }\r
- \r
- public String convertToPresentation(Integer value, Locale locale)\r
- throws ConversionException {\r
- if (value == null) {\r
- return null;\r
- }\r
- \r
- return getFormat(locale).format(value);\r
- }\r
- \r
- public Class<Integer> getModelType() {\r
- return Integer.class;\r
- }\r
- \r
- public Class<String> getPresentationType() {\r
- return String.class;\r
- }\r
- \r
- }\r
++/*
++@VaadinApache2LicenseForJavaFiles@
++ */
++
++package com.vaadin.data.util.converter;
++
++import java.text.NumberFormat;
++import java.text.ParsePosition;
++import java.util.Locale;
++
++/**
++ * A converter that converts from {@link String} to {@link Integer} and back.
++ * Uses the given locale and a {@link NumberFormat} instance for formatting and
++ * parsing.
++ * <p>
++ * Override and overwrite {@link #getFormat(Locale)} to use a different format.
++ * </p>
++ *
++ * @author Vaadin Ltd
++ * @version
++ * @VERSION@
++ * @since 7.0
++ */
++public class StringToIntegerConverter implements Converter<String, Integer> {
++
++ /**
++ * Returns the format used by
++ * {@link #convertToPresentation(Integer, Locale)} and
++ * {@link #convertToModel(String, Locale)}.
++ *
++ * @param locale
++ * The locale to use
++ * @return A NumberFormat instance
++ */
++ protected NumberFormat getFormat(Locale locale) {
++ if (locale == null) {
++ locale = Locale.getDefault();
++ }
++ return NumberFormat.getIntegerInstance(locale);
++ }
++
++ public Integer convertToModel(String value, Locale locale)
++ throws ConversionException {
++ if (value == null) {
++ return null;
++ }
++
++ // Remove leading and trailing white space
++ value = value.trim();
++
++ // Parse and detect errors. If the full string was not used, it is
++ // an error.
++ ParsePosition parsePosition = new ParsePosition(0);
++ Number parsedValue = getFormat(locale).parse(value, parsePosition);
++ if (parsePosition.getIndex() != value.length()) {
++ throw new ConversionException("Could not convert '" + value
++ + "' to " + getModelType().getName());
++ }
++
++ if (parsedValue == null) {
++ // Convert "" to null
++ return null;
++ }
++ return parsedValue.intValue();
++ }
++
++ public String convertToPresentation(Integer value, Locale locale)
++ throws ConversionException {
++ if (value == null) {
++ return null;
++ }
++
++ return getFormat(locale).format(value);
++ }
++
++ public Class<Integer> getModelType() {
++ return Integer.class;
++ }
++
++ public Class<String> getPresentationType() {
++ return String.class;
++ }
++
++}
--- /dev/null
- /*\r
- @VaadinApache2LicenseForJavaFiles@\r
- */\r
- \r
- package com.vaadin.data.util.converter;\r
- \r
- import java.text.NumberFormat;\r
- import java.text.ParsePosition;\r
- import java.util.Locale;\r
- \r
- /**\r
- * A converter that converts from {@link Number} to {@link String} and back.\r
- * Uses the given locale and {@link NumberFormat} for formatting and parsing.\r
- * <p>\r
- * Override and overwrite {@link #getFormat(Locale)} to use a different format.\r
- * </p>\r
- * \r
- * @author Vaadin Ltd\r
- * @version\r
- * @VERSION@\r
- * @since 7.0\r
- */\r
- public class StringToNumberConverter implements Converter<String, Number> {\r
- \r
- /**\r
- * Returns the format used by {@link #convertToPresentation(Number, Locale)}\r
- * and {@link #convertToModel(String, Locale)}.\r
- * \r
- * @param locale\r
- * The locale to use\r
- * @return A NumberFormat instance\r
- */\r
- protected NumberFormat getFormat(Locale locale) {\r
- if (locale == null) {\r
- locale = Locale.getDefault();\r
- }\r
- \r
- return NumberFormat.getNumberInstance(locale);\r
- }\r
- \r
- /*\r
- * (non-Javadoc)\r
- * \r
- * @see\r
- * com.vaadin.data.util.converter.Converter#convertToModel(java.lang.Object,\r
- * java.util.Locale)\r
- */\r
- public Number convertToModel(String value, Locale locale)\r
- throws ConversionException {\r
- if (value == null) {\r
- return null;\r
- }\r
- \r
- // Remove leading and trailing white space\r
- value = value.trim();\r
- \r
- // Parse and detect errors. If the full string was not used, it is\r
- // an error.\r
- ParsePosition parsePosition = new ParsePosition(0);\r
- Number parsedValue = getFormat(locale).parse(value, parsePosition);\r
- if (parsePosition.getIndex() != value.length()) {\r
- throw new ConversionException("Could not convert '" + value\r
- + "' to " + getModelType().getName());\r
- }\r
- \r
- if (parsedValue == null) {\r
- // Convert "" to null\r
- return null;\r
- }\r
- return parsedValue;\r
- }\r
- \r
- /*\r
- * (non-Javadoc)\r
- * \r
- * @see\r
- * com.vaadin.data.util.converter.Converter#convertToPresentation(java.lang\r
- * .Object, java.util.Locale)\r
- */\r
- public String convertToPresentation(Number value, Locale locale)\r
- throws ConversionException {\r
- if (value == null) {\r
- return null;\r
- }\r
- \r
- return getFormat(locale).format(value);\r
- }\r
- \r
- /*\r
- * (non-Javadoc)\r
- * \r
- * @see com.vaadin.data.util.converter.Converter#getModelType()\r
- */\r
- public Class<Number> getModelType() {\r
- return Number.class;\r
- }\r
- \r
- /*\r
- * (non-Javadoc)\r
- * \r
- * @see com.vaadin.data.util.converter.Converter#getPresentationType()\r
- */\r
- public Class<String> getPresentationType() {\r
- return String.class;\r
- }\r
- \r
- }\r
++/*
++@VaadinApache2LicenseForJavaFiles@
++ */
++
++package com.vaadin.data.util.converter;
++
++import java.text.NumberFormat;
++import java.text.ParsePosition;
++import java.util.Locale;
++
++/**
++ * A converter that converts from {@link Number} to {@link String} and back.
++ * Uses the given locale and {@link NumberFormat} for formatting and parsing.
++ * <p>
++ * Override and overwrite {@link #getFormat(Locale)} to use a different format.
++ * </p>
++ *
++ * @author Vaadin Ltd
++ * @version
++ * @VERSION@
++ * @since 7.0
++ */
++public class StringToNumberConverter implements Converter<String, Number> {
++
++ /**
++ * Returns the format used by {@link #convertToPresentation(Number, Locale)}
++ * and {@link #convertToModel(String, Locale)}.
++ *
++ * @param locale
++ * The locale to use
++ * @return A NumberFormat instance
++ */
++ protected NumberFormat getFormat(Locale locale) {
++ if (locale == null) {
++ locale = Locale.getDefault();
++ }
++
++ return NumberFormat.getNumberInstance(locale);
++ }
++
++ /*
++ * (non-Javadoc)
++ *
++ * @see
++ * com.vaadin.data.util.converter.Converter#convertToModel(java.lang.Object,
++ * java.util.Locale)
++ */
++ public Number convertToModel(String value, Locale locale)
++ throws ConversionException {
++ if (value == null) {
++ return null;
++ }
++
++ // Remove leading and trailing white space
++ value = value.trim();
++
++ // Parse and detect errors. If the full string was not used, it is
++ // an error.
++ ParsePosition parsePosition = new ParsePosition(0);
++ Number parsedValue = getFormat(locale).parse(value, parsePosition);
++ if (parsePosition.getIndex() != value.length()) {
++ throw new ConversionException("Could not convert '" + value
++ + "' to " + getModelType().getName());
++ }
++
++ if (parsedValue == null) {
++ // Convert "" to null
++ return null;
++ }
++ return parsedValue;
++ }
++
++ /*
++ * (non-Javadoc)
++ *
++ * @see
++ * com.vaadin.data.util.converter.Converter#convertToPresentation(java.lang
++ * .Object, java.util.Locale)
++ */
++ public String convertToPresentation(Number value, Locale locale)
++ throws ConversionException {
++ if (value == null) {
++ return null;
++ }
++
++ return getFormat(locale).format(value);
++ }
++
++ /*
++ * (non-Javadoc)
++ *
++ * @see com.vaadin.data.util.converter.Converter#getModelType()
++ */
++ public Class<Number> getModelType() {
++ return Number.class;
++ }
++
++ /*
++ * (non-Javadoc)
++ *
++ * @see com.vaadin.data.util.converter.Converter#getPresentationType()
++ */
++ public Class<String> getPresentationType() {
++ return String.class;
++ }
++
++}
--- /dev/null
- /* \r
- @VaadinApache2LicenseForJavaFiles@\r
- */\r
- \r
- package com.vaadin.data.validator;\r
- \r
- import java.io.Serializable;\r
- import java.util.ArrayList;\r
- import java.util.List;\r
- import java.util.Locale;\r
- import java.util.Set;\r
- \r
- import javax.validation.ConstraintViolation;\r
- import javax.validation.MessageInterpolator.Context;\r
- import javax.validation.Validation;\r
- import javax.validation.ValidatorFactory;\r
- import javax.validation.metadata.ConstraintDescriptor;\r
- \r
- import com.vaadin.data.Validator;\r
- \r
- /**\r
- * Vaadin {@link Validator} using the JSR-303 (javax.validation)\r
- * annotation-based bean validation.\r
- * \r
- * The annotations of the fields of the beans are used to determine the\r
- * validation to perform.\r
- * \r
- * Note that a JSR-303 implementation (e.g. Hibernate Validator or Apache Bean\r
- * Validation - formerly agimatec validation) must be present on the project\r
- * classpath when using bean validation.\r
- * \r
- * @since 7.0\r
- * \r
- * @author Petri Hakala\r
- * @author Henri Sara\r
- */\r
- public class BeanValidator implements Validator {\r
- \r
- private static final long serialVersionUID = 1L;\r
- private static ValidatorFactory factory;\r
- \r
- private transient javax.validation.Validator javaxBeanValidator;\r
- private String propertyName;\r
- private Class<?> beanClass;\r
- private Locale locale;\r
- \r
- /**\r
- * Simple implementation of a message interpolator context that returns\r
- * fixed values.\r
- */\r
- protected static class SimpleContext implements Context, Serializable {\r
- \r
- private final Object value;\r
- private final ConstraintDescriptor<?> descriptor;\r
- \r
- /**\r
- * Create a simple immutable message interpolator context.\r
- * \r
- * @param value\r
- * value being validated\r
- * @param descriptor\r
- * ConstraintDescriptor corresponding to the constraint being\r
- * validated\r
- */\r
- public SimpleContext(Object value, ConstraintDescriptor<?> descriptor) {\r
- this.value = value;\r
- this.descriptor = descriptor;\r
- }\r
- \r
- public ConstraintDescriptor<?> getConstraintDescriptor() {\r
- return descriptor;\r
- }\r
- \r
- public Object getValidatedValue() {\r
- return value;\r
- }\r
- \r
- }\r
- \r
- /**\r
- * Creates a Vaadin {@link Validator} utilizing JSR-303 bean validation.\r
- * \r
- * @param beanClass\r
- * bean class based on which the validation should be performed\r
- * @param propertyName\r
- * property to validate\r
- */\r
- public BeanValidator(Class<?> beanClass, String propertyName) {\r
- this.beanClass = beanClass;\r
- this.propertyName = propertyName;\r
- locale = Locale.getDefault();\r
- }\r
- \r
- /*\r
- * (non-Javadoc)\r
- * \r
- * @see com.vaadin.data.Validator#validate(java.lang.Object)\r
- */\r
- public void validate(final Object value) throws InvalidValueException {\r
- Set<?> violations = getJavaxBeanValidator().validateValue(beanClass,\r
- propertyName, value);\r
- if (violations.size() > 0) {\r
- List<String> exceptions = new ArrayList<String>();\r
- for (Object v : violations) {\r
- final ConstraintViolation<?> violation = (ConstraintViolation<?>) v;\r
- String msg = getJavaxBeanValidatorFactory()\r
- .getMessageInterpolator().interpolate(\r
- violation.getMessageTemplate(),\r
- new SimpleContext(value, violation\r
- .getConstraintDescriptor()), locale);\r
- exceptions.add(msg);\r
- }\r
- StringBuilder b = new StringBuilder();\r
- for (int i = 0; i < exceptions.size(); i++) {\r
- if (i != 0) {\r
- b.append("<br/>");\r
- }\r
- b.append(exceptions.get(i));\r
- }\r
- throw new InvalidValueException(b.toString());\r
- }\r
- }\r
- \r
- /**\r
- * Sets the locale used for validation error messages.\r
- * \r
- * Revalidation is not automatically triggered by setting the locale.\r
- * \r
- * @param locale\r
- */\r
- public void setLocale(Locale locale) {\r
- this.locale = locale;\r
- }\r
- \r
- /**\r
- * Gets the locale used for validation error messages.\r
- * \r
- * @return locale used for validation\r
- */\r
- public Locale getLocale() {\r
- return locale;\r
- }\r
- \r
- /**\r
- * Returns the underlying JSR-303 bean validator factory used. A factory is\r
- * created using {@link Validation} if necessary.\r
- * \r
- * @return {@link ValidatorFactory} to use\r
- */\r
- protected static ValidatorFactory getJavaxBeanValidatorFactory() {\r
- if (factory == null) {\r
- factory = Validation.buildDefaultValidatorFactory();\r
- }\r
- \r
- return factory;\r
- }\r
- \r
- /**\r
- * Returns a shared Validator instance to use. An instance is created using\r
- * the validator factory if necessary and thereafter reused by the\r
- * {@link BeanValidator} instance.\r
- * \r
- * @return the JSR-303 {@link javax.validation.Validator} to use\r
- */\r
- protected javax.validation.Validator getJavaxBeanValidator() {\r
- if (javaxBeanValidator == null) {\r
- javaxBeanValidator = getJavaxBeanValidatorFactory().getValidator();\r
- }\r
- \r
- return javaxBeanValidator;\r
- }\r
- \r
++/*
++@VaadinApache2LicenseForJavaFiles@
++ */
++
++package com.vaadin.data.validator;
++
++import java.io.Serializable;
++import java.util.ArrayList;
++import java.util.List;
++import java.util.Locale;
++import java.util.Set;
++
++import javax.validation.ConstraintViolation;
++import javax.validation.MessageInterpolator.Context;
++import javax.validation.Validation;
++import javax.validation.ValidatorFactory;
++import javax.validation.metadata.ConstraintDescriptor;
++
++import com.vaadin.data.Validator;
++
++/**
++ * Vaadin {@link Validator} using the JSR-303 (javax.validation)
++ * annotation-based bean validation.
++ *
++ * The annotations of the fields of the beans are used to determine the
++ * validation to perform.
++ *
++ * Note that a JSR-303 implementation (e.g. Hibernate Validator or Apache Bean
++ * Validation - formerly agimatec validation) must be present on the project
++ * classpath when using bean validation.
++ *
++ * @since 7.0
++ *
++ * @author Petri Hakala
++ * @author Henri Sara
++ */
++public class BeanValidator implements Validator {
++
++ private static final long serialVersionUID = 1L;
++ private static ValidatorFactory factory;
++
++ private transient javax.validation.Validator javaxBeanValidator;
++ private String propertyName;
++ private Class<?> beanClass;
++ private Locale locale;
++
++ /**
++ * Simple implementation of a message interpolator context that returns
++ * fixed values.
++ */
++ protected static class SimpleContext implements Context, Serializable {
++
++ private final Object value;
++ private final ConstraintDescriptor<?> descriptor;
++
++ /**
++ * Create a simple immutable message interpolator context.
++ *
++ * @param value
++ * value being validated
++ * @param descriptor
++ * ConstraintDescriptor corresponding to the constraint being
++ * validated
++ */
++ public SimpleContext(Object value, ConstraintDescriptor<?> descriptor) {
++ this.value = value;
++ this.descriptor = descriptor;
++ }
++
++ public ConstraintDescriptor<?> getConstraintDescriptor() {
++ return descriptor;
++ }
++
++ public Object getValidatedValue() {
++ return value;
++ }
++
++ }
++
++ /**
++ * Creates a Vaadin {@link Validator} utilizing JSR-303 bean validation.
++ *
++ * @param beanClass
++ * bean class based on which the validation should be performed
++ * @param propertyName
++ * property to validate
++ */
++ public BeanValidator(Class<?> beanClass, String propertyName) {
++ this.beanClass = beanClass;
++ this.propertyName = propertyName;
++ locale = Locale.getDefault();
++ }
++
++ /*
++ * (non-Javadoc)
++ *
++ * @see com.vaadin.data.Validator#validate(java.lang.Object)
++ */
++ public void validate(final Object value) throws InvalidValueException {
++ Set<?> violations = getJavaxBeanValidator().validateValue(beanClass,
++ propertyName, value);
++ if (violations.size() > 0) {
++ List<String> exceptions = new ArrayList<String>();
++ for (Object v : violations) {
++ final ConstraintViolation<?> violation = (ConstraintViolation<?>) v;
++ String msg = getJavaxBeanValidatorFactory()
++ .getMessageInterpolator().interpolate(
++ violation.getMessageTemplate(),
++ new SimpleContext(value, violation
++ .getConstraintDescriptor()), locale);
++ exceptions.add(msg);
++ }
++ StringBuilder b = new StringBuilder();
++ for (int i = 0; i < exceptions.size(); i++) {
++ if (i != 0) {
++ b.append("<br/>");
++ }
++ b.append(exceptions.get(i));
++ }
++ throw new InvalidValueException(b.toString());
++ }
++ }
++
++ /**
++ * Sets the locale used for validation error messages.
++ *
++ * Revalidation is not automatically triggered by setting the locale.
++ *
++ * @param locale
++ */
++ public void setLocale(Locale locale) {
++ this.locale = locale;
++ }
++
++ /**
++ * Gets the locale used for validation error messages.
++ *
++ * @return locale used for validation
++ */
++ public Locale getLocale() {
++ return locale;
++ }
++
++ /**
++ * Returns the underlying JSR-303 bean validator factory used. A factory is
++ * created using {@link Validation} if necessary.
++ *
++ * @return {@link ValidatorFactory} to use
++ */
++ protected static ValidatorFactory getJavaxBeanValidatorFactory() {
++ if (factory == null) {
++ factory = Validation.buildDefaultValidatorFactory();
++ }
++
++ return factory;
++ }
++
++ /**
++ * Returns a shared Validator instance to use. An instance is created using
++ * the validator factory if necessary and thereafter reused by the
++ * {@link BeanValidator} instance.
++ *
++ * @return the JSR-303 {@link javax.validation.Validator} to use
++ */
++ protected javax.validation.Validator getJavaxBeanValidator() {
++ if (javaxBeanValidator == null) {
++ javaxBeanValidator = getJavaxBeanValidatorFactory().getValidator();
++ }
++
++ return javaxBeanValidator;
++ }
++
+}
--- /dev/null
- /* \r
- @VaadinApache2LicenseForJavaFiles@\r
- */\r
- package com.vaadin.data.validator;\r
- \r
- import java.util.Date;\r
- \r
- import com.vaadin.ui.DateField.Resolution;\r
- \r
- /**\r
- * Validator for validating that a Date is inside a given range.\r
- * \r
- * <p>\r
- * Note that the comparison is done directly on the Date object so take care\r
- * that the hours/minutes/seconds/milliseconds of the min/max values are\r
- * properly set.\r
- * </p>\r
- * \r
- * @author Vaadin Ltd.\r
- * @version\r
- * @VERSION@\r
- * @since 7.0\r
- */\r
- public class DateRangeValidator extends RangeValidator<Date> {\r
- \r
- /**\r
- * Creates a validator for checking that an Date is within a given range.\r
- * <p>\r
- * By default the range is inclusive i.e. both minValue and maxValue are\r
- * valid values. Use {@link #setMinValueIncluded(boolean)} or\r
- * {@link #setMaxValueIncluded(boolean)} to change it.\r
- * </p>\r
- * <p>\r
- * Note that the comparison is done directly on the Date object so take care\r
- * that the hours/minutes/seconds/milliseconds of the min/max values are\r
- * properly set.\r
- * </p>\r
- * \r
- * @param errorMessage\r
- * the message to display in case the value does not validate.\r
- * @param minValue\r
- * The minimum value to accept or null for no limit\r
- * @param maxValue\r
- * The maximum value to accept or null for no limit\r
- */\r
- public DateRangeValidator(String errorMessage, Date minValue,\r
- Date maxValue, Resolution resolution) {\r
- super(errorMessage, Date.class, minValue, maxValue);\r
- }\r
- \r
- }\r
++/*
++@VaadinApache2LicenseForJavaFiles@
++ */
++package com.vaadin.data.validator;
++
++import java.util.Date;
++
++import com.vaadin.ui.DateField.Resolution;
++
++/**
++ * Validator for validating that a Date is inside a given range.
++ *
++ * <p>
++ * Note that the comparison is done directly on the Date object so take care
++ * that the hours/minutes/seconds/milliseconds of the min/max values are
++ * properly set.
++ * </p>
++ *
++ * @author Vaadin Ltd.
++ * @version
++ * @VERSION@
++ * @since 7.0
++ */
++public class DateRangeValidator extends RangeValidator<Date> {
++
++ /**
++ * Creates a validator for checking that an Date is within a given range.
++ * <p>
++ * By default the range is inclusive i.e. both minValue and maxValue are
++ * valid values. Use {@link #setMinValueIncluded(boolean)} or
++ * {@link #setMaxValueIncluded(boolean)} to change it.
++ * </p>
++ * <p>
++ * Note that the comparison is done directly on the Date object so take care
++ * that the hours/minutes/seconds/milliseconds of the min/max values are
++ * properly set.
++ * </p>
++ *
++ * @param errorMessage
++ * the message to display in case the value does not validate.
++ * @param minValue
++ * The minimum value to accept or null for no limit
++ * @param maxValue
++ * The maximum value to accept or null for no limit
++ */
++ public DateRangeValidator(String errorMessage, Date minValue,
++ Date maxValue, Resolution resolution) {
++ super(errorMessage, Date.class, minValue, maxValue);
++ }
++
++}
--- /dev/null
- /* \r
- @VaadinApache2LicenseForJavaFiles@\r
- */\r
- package com.vaadin.data.validator;\r
- \r
- /**\r
- * An base implementation for validating any objects that implement\r
- * {@link Comparable}.\r
- * \r
- * Verifies that the value is of the given type and within the (optionally)\r
- * given limits. Typically you want to use a sub class of this like\r
- * {@link IntegerRangeValidator}, {@link DoubleRangeValidator} or\r
- * {@link DateRangeValidator} in applications.\r
- * <p>\r
- * Note that {@link RangeValidator} always accept null values. Make a field\r
- * required to ensure that no empty values are accepted or override\r
- * {@link #isValidValue(Comparable)}.\r
- * </p>\r
- * \r
- * @param <T>\r
- * The type of Number to validate. Must implement Comparable so that\r
- * minimum and maximum checks work.\r
- * @author Vaadin Ltd.\r
- * @version\r
- * @VERSION@\r
- * @since 7.0\r
- */\r
- public class RangeValidator<T extends Comparable> extends AbstractValidator<T> {\r
- \r
- private T minValue = null;\r
- private boolean minValueIncluded = true;\r
- private T maxValue = null;\r
- private boolean maxValueIncluded = true;\r
- private Class<T> type;\r
- \r
- /**\r
- * Creates a new range validator of the given type.\r
- * \r
- * @param errorMessage\r
- * The error message to use if validation fails\r
- * @param type\r
- * The type of object the validator can validate.\r
- * @param minValue\r
- * The minimum value that should be accepted or null for no limit\r
- * @param maxValue\r
- * The maximum value that should be accepted or null for no limit\r
- */\r
- public RangeValidator(String errorMessage, Class<T> type, T minValue,\r
- T maxValue) {\r
- super(errorMessage);\r
- this.type = type;\r
- this.minValue = minValue;\r
- this.maxValue = maxValue;\r
- }\r
- \r
- /**\r
- * Checks if the minimum value is part of the accepted range\r
- * \r
- * @return true if the minimum value is part of the range, false otherwise\r
- */\r
- public boolean isMinValueIncluded() {\r
- return minValueIncluded;\r
- }\r
- \r
- /**\r
- * Sets if the minimum value is part of the accepted range\r
- * \r
- * @param minValueIncluded\r
- * true if the minimum value should be part of the range, false\r
- * otherwise\r
- */\r
- public void setMinValueIncluded(boolean minValueIncluded) {\r
- this.minValueIncluded = minValueIncluded;\r
- }\r
- \r
- /**\r
- * Checks if the maximum value is part of the accepted range\r
- * \r
- * @return true if the maximum value is part of the range, false otherwise\r
- */\r
- public boolean isMaxValueIncluded() {\r
- return maxValueIncluded;\r
- }\r
- \r
- /**\r
- * Sets if the maximum value is part of the accepted range\r
- * \r
- * @param maxValueIncluded\r
- * true if the maximum value should be part of the range, false\r
- * otherwise\r
- */\r
- public void setMaxValueIncluded(boolean maxValueIncluded) {\r
- this.maxValueIncluded = maxValueIncluded;\r
- }\r
- \r
- /**\r
- * Gets the minimum value of the range\r
- * \r
- * @return the minimum value\r
- */\r
- public T getMinValue() {\r
- return minValue;\r
- }\r
- \r
- /**\r
- * Sets the minimum value of the range. Use\r
- * {@link #setMinValueIncluded(boolean)} to control whether this value is\r
- * part of the range or not.\r
- * \r
- * @param minValue\r
- * the minimum value\r
- */\r
- public void setMinValue(T minValue) {\r
- this.minValue = minValue;\r
- }\r
- \r
- /**\r
- * Gets the maximum value of the range\r
- * \r
- * @return the maximum value\r
- */\r
- public T getMaxValue() {\r
- return maxValue;\r
- }\r
- \r
- /**\r
- * Sets the maximum value of the range. Use\r
- * {@link #setMaxValueIncluded(boolean)} to control whether this value is\r
- * part of the range or not.\r
- * \r
- * @param maxValue\r
- * the maximum value\r
- */\r
- public void setMaxValue(T maxValue) {\r
- this.maxValue = maxValue;\r
- }\r
- \r
- /*\r
- * (non-Javadoc)\r
- * \r
- * @see\r
- * com.vaadin.data.validator.AbstractValidator#isValidValue(java.lang.Object\r
- * )\r
- */\r
- @Override\r
- protected boolean isValidValue(T value) {\r
- if (value == null) {\r
- return true;\r
- }\r
- \r
- if (getMinValue() != null) {\r
- // Ensure that the min limit is ok\r
- int result = value.compareTo(getMinValue());\r
- if (result < 0) {\r
- // value less than min value\r
- return false;\r
- } else if (result == 0 && !isMinValueIncluded()) {\r
- // values equal and min value not included\r
- return false;\r
- }\r
- }\r
- if (getMaxValue() != null) {\r
- // Ensure that the Max limit is ok\r
- int result = value.compareTo(getMaxValue());\r
- if (result > 0) {\r
- // value greater than max value\r
- return false;\r
- } else if (result == 0 && !isMaxValueIncluded()) {\r
- // values equal and max value not included\r
- return false;\r
- }\r
- }\r
- return true;\r
- }\r
- \r
- /*\r
- * (non-Javadoc)\r
- * \r
- * @see com.vaadin.data.validator.AbstractValidator#getType()\r
- */\r
- @Override\r
- public Class<T> getType() {\r
- return type;\r
- }\r
- \r
- }\r
++/*
++@VaadinApache2LicenseForJavaFiles@
++ */
++package com.vaadin.data.validator;
++
++/**
++ * An base implementation for validating any objects that implement
++ * {@link Comparable}.
++ *
++ * Verifies that the value is of the given type and within the (optionally)
++ * given limits. Typically you want to use a sub class of this like
++ * {@link IntegerRangeValidator}, {@link DoubleRangeValidator} or
++ * {@link DateRangeValidator} in applications.
++ * <p>
++ * Note that {@link RangeValidator} always accept null values. Make a field
++ * required to ensure that no empty values are accepted or override
++ * {@link #isValidValue(Comparable)}.
++ * </p>
++ *
++ * @param <T>
++ * The type of Number to validate. Must implement Comparable so that
++ * minimum and maximum checks work.
++ * @author Vaadin Ltd.
++ * @version
++ * @VERSION@
++ * @since 7.0
++ */
++public class RangeValidator<T extends Comparable> extends AbstractValidator<T> {
++
++ private T minValue = null;
++ private boolean minValueIncluded = true;
++ private T maxValue = null;
++ private boolean maxValueIncluded = true;
++ private Class<T> type;
++
++ /**
++ * Creates a new range validator of the given type.
++ *
++ * @param errorMessage
++ * The error message to use if validation fails
++ * @param type
++ * The type of object the validator can validate.
++ * @param minValue
++ * The minimum value that should be accepted or null for no limit
++ * @param maxValue
++ * The maximum value that should be accepted or null for no limit
++ */
++ public RangeValidator(String errorMessage, Class<T> type, T minValue,
++ T maxValue) {
++ super(errorMessage);
++ this.type = type;
++ this.minValue = minValue;
++ this.maxValue = maxValue;
++ }
++
++ /**
++ * Checks if the minimum value is part of the accepted range
++ *
++ * @return true if the minimum value is part of the range, false otherwise
++ */
++ public boolean isMinValueIncluded() {
++ return minValueIncluded;
++ }
++
++ /**
++ * Sets if the minimum value is part of the accepted range
++ *
++ * @param minValueIncluded
++ * true if the minimum value should be part of the range, false
++ * otherwise
++ */
++ public void setMinValueIncluded(boolean minValueIncluded) {
++ this.minValueIncluded = minValueIncluded;
++ }
++
++ /**
++ * Checks if the maximum value is part of the accepted range
++ *
++ * @return true if the maximum value is part of the range, false otherwise
++ */
++ public boolean isMaxValueIncluded() {
++ return maxValueIncluded;
++ }
++
++ /**
++ * Sets if the maximum value is part of the accepted range
++ *
++ * @param maxValueIncluded
++ * true if the maximum value should be part of the range, false
++ * otherwise
++ */
++ public void setMaxValueIncluded(boolean maxValueIncluded) {
++ this.maxValueIncluded = maxValueIncluded;
++ }
++
++ /**
++ * Gets the minimum value of the range
++ *
++ * @return the minimum value
++ */
++ public T getMinValue() {
++ return minValue;
++ }
++
++ /**
++ * Sets the minimum value of the range. Use
++ * {@link #setMinValueIncluded(boolean)} to control whether this value is
++ * part of the range or not.
++ *
++ * @param minValue
++ * the minimum value
++ */
++ public void setMinValue(T minValue) {
++ this.minValue = minValue;
++ }
++
++ /**
++ * Gets the maximum value of the range
++ *
++ * @return the maximum value
++ */
++ public T getMaxValue() {
++ return maxValue;
++ }
++
++ /**
++ * Sets the maximum value of the range. Use
++ * {@link #setMaxValueIncluded(boolean)} to control whether this value is
++ * part of the range or not.
++ *
++ * @param maxValue
++ * the maximum value
++ */
++ public void setMaxValue(T maxValue) {
++ this.maxValue = maxValue;
++ }
++
++ /*
++ * (non-Javadoc)
++ *
++ * @see
++ * com.vaadin.data.validator.AbstractValidator#isValidValue(java.lang.Object
++ * )
++ */
++ @Override
++ protected boolean isValidValue(T value) {
++ if (value == null) {
++ return true;
++ }
++
++ if (getMinValue() != null) {
++ // Ensure that the min limit is ok
++ int result = value.compareTo(getMinValue());
++ if (result < 0) {
++ // value less than min value
++ return false;
++ } else if (result == 0 && !isMinValueIncluded()) {
++ // values equal and min value not included
++ return false;
++ }
++ }
++ if (getMaxValue() != null) {
++ // Ensure that the Max limit is ok
++ int result = value.compareTo(getMaxValue());
++ if (result > 0) {
++ // value greater than max value
++ return false;
++ } else if (result == 0 && !isMaxValueIncluded()) {
++ // values equal and max value not included
++ return false;
++ }
++ }
++ return true;
++ }
++
++ /*
++ * (non-Javadoc)
++ *
++ * @see com.vaadin.data.validator.AbstractValidator#getType()
++ */
++ @Override
++ public Class<T> getType() {
++ return type;
++ }
++
++}
--- /dev/null
- package com.vaadin.external.json;\r
- \r
- /**\r
- * The JSONException is thrown by the JSON.org classes when things are amiss.\r
- * @author JSON.org\r
- * @version 2010-12-24\r
- */\r
- public class JSONException extends Exception {\r
- private static final long serialVersionUID = 0;\r
- private Throwable cause;\r
- \r
- /**\r
- * Constructs a JSONException with an explanatory message.\r
- * @param message Detail about the reason for the exception.\r
- */\r
- public JSONException(String message) {\r
- super(message);\r
- }\r
- \r
- public JSONException(Throwable cause) {\r
- super(cause.getMessage());\r
- this.cause = cause;\r
- }\r
- \r
- public Throwable getCause() {\r
- return this.cause;\r
- }\r
- }\r
++package com.vaadin.external.json;
++
++/**
++ * The JSONException is thrown by the JSON.org classes when things are amiss.
++ * @author JSON.org
++ * @version 2010-12-24
++ */
++public class JSONException extends Exception {
++ private static final long serialVersionUID = 0;
++ private Throwable cause;
++
++ /**
++ * Constructs a JSONException with an explanatory message.
++ * @param message Detail about the reason for the exception.
++ */
++ public JSONException(String message) {
++ super(message);
++ }
++
++ public JSONException(Throwable cause) {
++ super(cause.getMessage());
++ this.cause = cause;
++ }
++
++ public Throwable getCause() {
++ return this.cause;
++ }
++}
--- /dev/null
- package com.vaadin.external.json;\r
- \r
- import java.io.Serializable;\r
- \r
- /**\r
- * The <code>JSONString</code> interface allows a <code>toJSONString()</code>\r
- * method so that a class can change the behavior of\r
- * <code>JSONObject.toString()</code>, <code>JSONArray.toString()</code>, and\r
- * <code>JSONWriter.value(</code>Object<code>)</code>. The\r
- * <code>toJSONString</code> method will be used instead of the default behavior\r
- * of using the Object's <code>toString()</code> method and quoting the result.\r
- */\r
- public interface JSONString extends Serializable {\r
- /**\r
- * The <code>toJSONString</code> method allows a class to produce its own\r
- * JSON serialization.\r
- * \r
- * @return A strictly syntactically correct JSON text.\r
- */\r
- public String toJSONString();\r
- }\r
++package com.vaadin.external.json;
++
++import java.io.Serializable;
++
++/**
++ * The <code>JSONString</code> interface allows a <code>toJSONString()</code>
++ * method so that a class can change the behavior of
++ * <code>JSONObject.toString()</code>, <code>JSONArray.toString()</code>, and
++ * <code>JSONWriter.value(</code>Object<code>)</code>. The
++ * <code>toJSONString</code> method will be used instead of the default behavior
++ * of using the Object's <code>toString()</code> method and quoting the result.
++ */
++public interface JSONString extends Serializable {
++ /**
++ * The <code>toJSONString</code> method allows a class to produce its own
++ * JSON serialization.
++ *
++ * @return A strictly syntactically correct JSON text.
++ */
++ public String toJSONString();
++}
--- /dev/null
- package com.vaadin.external.json;\r
- \r
- /*\r
- Copyright (c) 2006 JSON.org\r
- \r
- Permission is hereby granted, free of charge, to any person obtaining a copy\r
- of this software and associated documentation files (the "Software"), to deal\r
- in the Software without restriction, including without limitation the rights\r
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\r
- copies of the Software, and to permit persons to whom the Software is\r
- furnished to do so, subject to the following conditions:\r
- \r
- The above copyright notice and this permission notice shall be included in all\r
- copies or substantial portions of the Software.\r
- \r
- The Software shall be used for Good, not Evil.\r
- \r
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\r
- SOFTWARE.\r
- */\r
- \r
- import java.io.StringWriter;\r
- \r
- /**\r
- * JSONStringer provides a quick and convenient way of producing JSON text.\r
- * The texts produced strictly conform to JSON syntax rules. No whitespace is\r
- * added, so the results are ready for transmission or storage. Each instance of\r
- * JSONStringer can produce one JSON text.\r
- * <p>\r
- * A JSONStringer instance provides a <code>value</code> method for appending\r
- * values to the\r
- * text, and a <code>key</code>\r
- * method for adding keys before values in objects. There are <code>array</code>\r
- * and <code>endArray</code> methods that make and bound array values, and\r
- * <code>object</code> and <code>endObject</code> methods which make and bound\r
- * object values. All of these methods return the JSONWriter instance,\r
- * permitting cascade style. For example, <pre>\r
- * myString = new JSONStringer()\r
- * .object()\r
- * .key("JSON")\r
- * .value("Hello, World!")\r
- * .endObject()\r
- * .toString();</pre> which produces the string <pre>\r
- * {"JSON":"Hello, World!"}</pre>\r
- * <p>\r
- * The first method called must be <code>array</code> or <code>object</code>.\r
- * There are no methods for adding commas or colons. JSONStringer adds them for\r
- * you. Objects and arrays can be nested up to 20 levels deep.\r
- * <p>\r
- * This can sometimes be easier than using a JSONObject to build a string.\r
- * @author JSON.org\r
- * @version 2008-09-18\r
- */\r
- public class JSONStringer extends JSONWriter {\r
- /**\r
- * Make a fresh JSONStringer. It can be used to build one JSON text.\r
- */\r
- public JSONStringer() {\r
- super(new StringWriter());\r
- }\r
- \r
- /**\r
- * Return the JSON text. This method is used to obtain the product of the\r
- * JSONStringer instance. It will return <code>null</code> if there was a\r
- * problem in the construction of the JSON text (such as the calls to\r
- * <code>array</code> were not properly balanced with calls to\r
- * <code>endArray</code>).\r
- * @return The JSON text.\r
- */\r
- public String toString() {\r
- return this.mode == 'd' ? this.writer.toString() : null;\r
- }\r
- }\r
++package com.vaadin.external.json;
++
++/*
++Copyright (c) 2006 JSON.org
++
++Permission is hereby granted, free of charge, to any person obtaining a copy
++of this software and associated documentation files (the "Software"), to deal
++in the Software without restriction, including without limitation the rights
++to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
++copies of the Software, and to permit persons to whom the Software is
++furnished to do so, subject to the following conditions:
++
++The above copyright notice and this permission notice shall be included in all
++copies or substantial portions of the Software.
++
++The Software shall be used for Good, not Evil.
++
++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
++IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
++FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
++AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
++LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
++OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
++SOFTWARE.
++*/
++
++import java.io.StringWriter;
++
++/**
++ * JSONStringer provides a quick and convenient way of producing JSON text.
++ * The texts produced strictly conform to JSON syntax rules. No whitespace is
++ * added, so the results are ready for transmission or storage. Each instance of
++ * JSONStringer can produce one JSON text.
++ * <p>
++ * A JSONStringer instance provides a <code>value</code> method for appending
++ * values to the
++ * text, and a <code>key</code>
++ * method for adding keys before values in objects. There are <code>array</code>
++ * and <code>endArray</code> methods that make and bound array values, and
++ * <code>object</code> and <code>endObject</code> methods which make and bound
++ * object values. All of these methods return the JSONWriter instance,
++ * permitting cascade style. For example, <pre>
++ * myString = new JSONStringer()
++ * .object()
++ * .key("JSON")
++ * .value("Hello, World!")
++ * .endObject()
++ * .toString();</pre> which produces the string <pre>
++ * {"JSON":"Hello, World!"}</pre>
++ * <p>
++ * The first method called must be <code>array</code> or <code>object</code>.
++ * There are no methods for adding commas or colons. JSONStringer adds them for
++ * you. Objects and arrays can be nested up to 20 levels deep.
++ * <p>
++ * This can sometimes be easier than using a JSONObject to build a string.
++ * @author JSON.org
++ * @version 2008-09-18
++ */
++public class JSONStringer extends JSONWriter {
++ /**
++ * Make a fresh JSONStringer. It can be used to build one JSON text.
++ */
++ public JSONStringer() {
++ super(new StringWriter());
++ }
++
++ /**
++ * Return the JSON text. This method is used to obtain the product of the
++ * JSONStringer instance. It will return <code>null</code> if there was a
++ * problem in the construction of the JSON text (such as the calls to
++ * <code>array</code> were not properly balanced with calls to
++ * <code>endArray</code>).
++ * @return The JSON text.
++ */
++ public String toString() {
++ return this.mode == 'd' ? this.writer.toString() : null;
++ }
++}
--- /dev/null
- package com.vaadin.external.json;\r
- \r
- import java.io.IOException;\r
- import java.io.Serializable;\r
- import java.io.Writer;\r
- \r
- /*\r
- Copyright (c) 2006 JSON.org\r
- \r
- Permission is hereby granted, free of charge, to any person obtaining a copy\r
- of this software and associated documentation files (the "Software"), to deal\r
- in the Software without restriction, including without limitation the rights\r
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\r
- copies of the Software, and to permit persons to whom the Software is\r
- furnished to do so, subject to the following conditions:\r
- \r
- The above copyright notice and this permission notice shall be included in all\r
- copies or substantial portions of the Software.\r
- \r
- The Software shall be used for Good, not Evil.\r
- \r
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\r
- SOFTWARE.\r
- */\r
- \r
- /**\r
- * JSONWriter provides a quick and convenient way of producing JSON text. The\r
- * texts produced strictly conform to JSON syntax rules. No whitespace is added,\r
- * so the results are ready for transmission or storage. Each instance of\r
- * JSONWriter can produce one JSON text.\r
- * <p>\r
- * A JSONWriter instance provides a <code>value</code> method for appending\r
- * values to the text, and a <code>key</code> method for adding keys before\r
- * values in objects. There are <code>array</code> and <code>endArray</code>\r
- * methods that make and bound array values, and <code>object</code> and\r
- * <code>endObject</code> methods which make and bound object values. All of\r
- * these methods return the JSONWriter instance, permitting a cascade style. For\r
- * example,\r
- * \r
- * <pre>\r
- * new JSONWriter(myWriter).object().key("JSON").value("Hello, World!")\r
- * .endObject();\r
- * </pre>\r
- * \r
- * which writes\r
- * \r
- * <pre>\r
- * {"JSON":"Hello, World!"}\r
- * </pre>\r
- * <p>\r
- * The first method called must be <code>array</code> or <code>object</code>.\r
- * There are no methods for adding commas or colons. JSONWriter adds them for\r
- * you. Objects and arrays can be nested up to 20 levels deep.\r
- * <p>\r
- * This can sometimes be easier than using a JSONObject to build a string.\r
- * \r
- * @author JSON.org\r
- * @version 2011-11-14\r
- */\r
- public class JSONWriter implements Serializable {\r
- private static final int maxdepth = 200;\r
- \r
- /**\r
- * The comma flag determines if a comma should be output before the next\r
- * value.\r
- */\r
- private boolean comma;\r
- \r
- /**\r
- * The current mode. Values: 'a' (array), 'd' (done), 'i' (initial), 'k'\r
- * (key), 'o' (object).\r
- */\r
- protected char mode;\r
- \r
- /**\r
- * The object/array stack.\r
- */\r
- private final JSONObject stack[];\r
- \r
- /**\r
- * The stack top index. A value of 0 indicates that the stack is empty.\r
- */\r
- private int top;\r
- \r
- /**\r
- * The writer that will receive the output.\r
- */\r
- protected Writer writer;\r
- \r
- /**\r
- * Make a fresh JSONWriter. It can be used to build one JSON text.\r
- */\r
- public JSONWriter(Writer w) {\r
- comma = false;\r
- mode = 'i';\r
- stack = new JSONObject[maxdepth];\r
- top = 0;\r
- writer = w;\r
- }\r
- \r
- /**\r
- * Append a value.\r
- * \r
- * @param string\r
- * A string value.\r
- * @return this\r
- * @throws JSONException\r
- * If the value is out of sequence.\r
- */\r
- private JSONWriter append(String string) throws JSONException {\r
- if (string == null) {\r
- throw new JSONException("Null pointer");\r
- }\r
- if (mode == 'o' || mode == 'a') {\r
- try {\r
- if (comma && mode == 'a') {\r
- writer.write(',');\r
- }\r
- writer.write(string);\r
- } catch (IOException e) {\r
- throw new JSONException(e);\r
- }\r
- if (mode == 'o') {\r
- mode = 'k';\r
- }\r
- comma = true;\r
- return this;\r
- }\r
- throw new JSONException("Value out of sequence.");\r
- }\r
- \r
- /**\r
- * Begin appending a new array. All values until the balancing\r
- * <code>endArray</code> will be appended to this array. The\r
- * <code>endArray</code> method must be called to mark the array's end.\r
- * \r
- * @return this\r
- * @throws JSONException\r
- * If the nesting is too deep, or if the object is started in\r
- * the wrong place (for example as a key or after the end of the\r
- * outermost array or object).\r
- */\r
- public JSONWriter array() throws JSONException {\r
- if (mode == 'i' || mode == 'o' || mode == 'a') {\r
- push(null);\r
- append("[");\r
- comma = false;\r
- return this;\r
- }\r
- throw new JSONException("Misplaced array.");\r
- }\r
- \r
- /**\r
- * End something.\r
- * \r
- * @param mode\r
- * Mode\r
- * @param c\r
- * Closing character\r
- * @return this\r
- * @throws JSONException\r
- * If unbalanced.\r
- */\r
- private JSONWriter end(char mode, char c) throws JSONException {\r
- if (this.mode != mode) {\r
- throw new JSONException(mode == 'a' ? "Misplaced endArray."\r
- : "Misplaced endObject.");\r
- }\r
- pop(mode);\r
- try {\r
- writer.write(c);\r
- } catch (IOException e) {\r
- throw new JSONException(e);\r
- }\r
- comma = true;\r
- return this;\r
- }\r
- \r
- /**\r
- * End an array. This method most be called to balance calls to\r
- * <code>array</code>.\r
- * \r
- * @return this\r
- * @throws JSONException\r
- * If incorrectly nested.\r
- */\r
- public JSONWriter endArray() throws JSONException {\r
- return end('a', ']');\r
- }\r
- \r
- /**\r
- * End an object. This method most be called to balance calls to\r
- * <code>object</code>.\r
- * \r
- * @return this\r
- * @throws JSONException\r
- * If incorrectly nested.\r
- */\r
- public JSONWriter endObject() throws JSONException {\r
- return end('k', '}');\r
- }\r
- \r
- /**\r
- * Append a key. The key will be associated with the next value. In an\r
- * object, every value must be preceded by a key.\r
- * \r
- * @param string\r
- * A key string.\r
- * @return this\r
- * @throws JSONException\r
- * If the key is out of place. For example, keys do not belong\r
- * in arrays or if the key is null.\r
- */\r
- public JSONWriter key(String string) throws JSONException {\r
- if (string == null) {\r
- throw new JSONException("Null key.");\r
- }\r
- if (mode == 'k') {\r
- try {\r
- stack[top - 1].putOnce(string, Boolean.TRUE);\r
- if (comma) {\r
- writer.write(',');\r
- }\r
- writer.write(JSONObject.quote(string));\r
- writer.write(':');\r
- comma = false;\r
- mode = 'o';\r
- return this;\r
- } catch (IOException e) {\r
- throw new JSONException(e);\r
- }\r
- }\r
- throw new JSONException("Misplaced key.");\r
- }\r
- \r
- /**\r
- * Begin appending a new object. All keys and values until the balancing\r
- * <code>endObject</code> will be appended to this object. The\r
- * <code>endObject</code> method must be called to mark the object's end.\r
- * \r
- * @return this\r
- * @throws JSONException\r
- * If the nesting is too deep, or if the object is started in\r
- * the wrong place (for example as a key or after the end of the\r
- * outermost array or object).\r
- */\r
- public JSONWriter object() throws JSONException {\r
- if (mode == 'i') {\r
- mode = 'o';\r
- }\r
- if (mode == 'o' || mode == 'a') {\r
- append("{");\r
- push(new JSONObject());\r
- comma = false;\r
- return this;\r
- }\r
- throw new JSONException("Misplaced object.");\r
- \r
- }\r
- \r
- /**\r
- * Pop an array or object scope.\r
- * \r
- * @param c\r
- * The scope to close.\r
- * @throws JSONException\r
- * If nesting is wrong.\r
- */\r
- private void pop(char c) throws JSONException {\r
- if (top <= 0) {\r
- throw new JSONException("Nesting error.");\r
- }\r
- char m = stack[top - 1] == null ? 'a' : 'k';\r
- if (m != c) {\r
- throw new JSONException("Nesting error.");\r
- }\r
- top -= 1;\r
- mode = top == 0 ? 'd' : stack[top - 1] == null ? 'a' : 'k';\r
- }\r
- \r
- /**\r
- * Push an array or object scope.\r
- * \r
- * @param c\r
- * The scope to open.\r
- * @throws JSONException\r
- * If nesting is too deep.\r
- */\r
- private void push(JSONObject jo) throws JSONException {\r
- if (top >= maxdepth) {\r
- throw new JSONException("Nesting too deep.");\r
- }\r
- stack[top] = jo;\r
- mode = jo == null ? 'a' : 'k';\r
- top += 1;\r
- }\r
- \r
- /**\r
- * Append either the value <code>true</code> or the value <code>false</code>\r
- * .\r
- * \r
- * @param b\r
- * A boolean.\r
- * @return this\r
- * @throws JSONException\r
- */\r
- public JSONWriter value(boolean b) throws JSONException {\r
- return append(b ? "true" : "false");\r
- }\r
- \r
- /**\r
- * Append a double value.\r
- * \r
- * @param d\r
- * A double.\r
- * @return this\r
- * @throws JSONException\r
- * If the number is not finite.\r
- */\r
- public JSONWriter value(double d) throws JSONException {\r
- return this.value(new Double(d));\r
- }\r
- \r
- /**\r
- * Append a long value.\r
- * \r
- * @param l\r
- * A long.\r
- * @return this\r
- * @throws JSONException\r
- */\r
- public JSONWriter value(long l) throws JSONException {\r
- return append(Long.toString(l));\r
- }\r
- \r
- /**\r
- * Append an object value.\r
- * \r
- * @param object\r
- * The object to append. It can be null, or a Boolean, Number,\r
- * String, JSONObject, or JSONArray, or an object that implements\r
- * JSONString.\r
- * @return this\r
- * @throws JSONException\r
- * If the value is out of sequence.\r
- */\r
- public JSONWriter value(Object object) throws JSONException {\r
- return append(JSONObject.valueToString(object));\r
- }\r
- }\r
++package com.vaadin.external.json;
++
++import java.io.IOException;
++import java.io.Serializable;
++import java.io.Writer;
++
++/*
++ Copyright (c) 2006 JSON.org
++
++ Permission is hereby granted, free of charge, to any person obtaining a copy
++ of this software and associated documentation files (the "Software"), to deal
++ in the Software without restriction, including without limitation the rights
++ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
++ copies of the Software, and to permit persons to whom the Software is
++ furnished to do so, subject to the following conditions:
++
++ The above copyright notice and this permission notice shall be included in all
++ copies or substantial portions of the Software.
++
++ The Software shall be used for Good, not Evil.
++
++ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
++ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
++ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
++ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
++ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
++ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
++ SOFTWARE.
++ */
++
++/**
++ * JSONWriter provides a quick and convenient way of producing JSON text. The
++ * texts produced strictly conform to JSON syntax rules. No whitespace is added,
++ * so the results are ready for transmission or storage. Each instance of
++ * JSONWriter can produce one JSON text.
++ * <p>
++ * A JSONWriter instance provides a <code>value</code> method for appending
++ * values to the text, and a <code>key</code> method for adding keys before
++ * values in objects. There are <code>array</code> and <code>endArray</code>
++ * methods that make and bound array values, and <code>object</code> and
++ * <code>endObject</code> methods which make and bound object values. All of
++ * these methods return the JSONWriter instance, permitting a cascade style. For
++ * example,
++ *
++ * <pre>
++ * new JSONWriter(myWriter).object().key("JSON").value("Hello, World!")
++ * .endObject();
++ * </pre>
++ *
++ * which writes
++ *
++ * <pre>
++ * {"JSON":"Hello, World!"}
++ * </pre>
++ * <p>
++ * The first method called must be <code>array</code> or <code>object</code>.
++ * There are no methods for adding commas or colons. JSONWriter adds them for
++ * you. Objects and arrays can be nested up to 20 levels deep.
++ * <p>
++ * This can sometimes be easier than using a JSONObject to build a string.
++ *
++ * @author JSON.org
++ * @version 2011-11-14
++ */
++public class JSONWriter implements Serializable {
++ private static final int maxdepth = 200;
++
++ /**
++ * The comma flag determines if a comma should be output before the next
++ * value.
++ */
++ private boolean comma;
++
++ /**
++ * The current mode. Values: 'a' (array), 'd' (done), 'i' (initial), 'k'
++ * (key), 'o' (object).
++ */
++ protected char mode;
++
++ /**
++ * The object/array stack.
++ */
++ private final JSONObject stack[];
++
++ /**
++ * The stack top index. A value of 0 indicates that the stack is empty.
++ */
++ private int top;
++
++ /**
++ * The writer that will receive the output.
++ */
++ protected Writer writer;
++
++ /**
++ * Make a fresh JSONWriter. It can be used to build one JSON text.
++ */
++ public JSONWriter(Writer w) {
++ comma = false;
++ mode = 'i';
++ stack = new JSONObject[maxdepth];
++ top = 0;
++ writer = w;
++ }
++
++ /**
++ * Append a value.
++ *
++ * @param string
++ * A string value.
++ * @return this
++ * @throws JSONException
++ * If the value is out of sequence.
++ */
++ private JSONWriter append(String string) throws JSONException {
++ if (string == null) {
++ throw new JSONException("Null pointer");
++ }
++ if (mode == 'o' || mode == 'a') {
++ try {
++ if (comma && mode == 'a') {
++ writer.write(',');
++ }
++ writer.write(string);
++ } catch (IOException e) {
++ throw new JSONException(e);
++ }
++ if (mode == 'o') {
++ mode = 'k';
++ }
++ comma = true;
++ return this;
++ }
++ throw new JSONException("Value out of sequence.");
++ }
++
++ /**
++ * Begin appending a new array. All values until the balancing
++ * <code>endArray</code> will be appended to this array. The
++ * <code>endArray</code> method must be called to mark the array's end.
++ *
++ * @return this
++ * @throws JSONException
++ * If the nesting is too deep, or if the object is started in
++ * the wrong place (for example as a key or after the end of the
++ * outermost array or object).
++ */
++ public JSONWriter array() throws JSONException {
++ if (mode == 'i' || mode == 'o' || mode == 'a') {
++ push(null);
++ append("[");
++ comma = false;
++ return this;
++ }
++ throw new JSONException("Misplaced array.");
++ }
++
++ /**
++ * End something.
++ *
++ * @param mode
++ * Mode
++ * @param c
++ * Closing character
++ * @return this
++ * @throws JSONException
++ * If unbalanced.
++ */
++ private JSONWriter end(char mode, char c) throws JSONException {
++ if (this.mode != mode) {
++ throw new JSONException(mode == 'a' ? "Misplaced endArray."
++ : "Misplaced endObject.");
++ }
++ pop(mode);
++ try {
++ writer.write(c);
++ } catch (IOException e) {
++ throw new JSONException(e);
++ }
++ comma = true;
++ return this;
++ }
++
++ /**
++ * End an array. This method most be called to balance calls to
++ * <code>array</code>.
++ *
++ * @return this
++ * @throws JSONException
++ * If incorrectly nested.
++ */
++ public JSONWriter endArray() throws JSONException {
++ return end('a', ']');
++ }
++
++ /**
++ * End an object. This method most be called to balance calls to
++ * <code>object</code>.
++ *
++ * @return this
++ * @throws JSONException
++ * If incorrectly nested.
++ */
++ public JSONWriter endObject() throws JSONException {
++ return end('k', '}');
++ }
++
++ /**
++ * Append a key. The key will be associated with the next value. In an
++ * object, every value must be preceded by a key.
++ *
++ * @param string
++ * A key string.
++ * @return this
++ * @throws JSONException
++ * If the key is out of place. For example, keys do not belong
++ * in arrays or if the key is null.
++ */
++ public JSONWriter key(String string) throws JSONException {
++ if (string == null) {
++ throw new JSONException("Null key.");
++ }
++ if (mode == 'k') {
++ try {
++ stack[top - 1].putOnce(string, Boolean.TRUE);
++ if (comma) {
++ writer.write(',');
++ }
++ writer.write(JSONObject.quote(string));
++ writer.write(':');
++ comma = false;
++ mode = 'o';
++ return this;
++ } catch (IOException e) {
++ throw new JSONException(e);
++ }
++ }
++ throw new JSONException("Misplaced key.");
++ }
++
++ /**
++ * Begin appending a new object. All keys and values until the balancing
++ * <code>endObject</code> will be appended to this object. The
++ * <code>endObject</code> method must be called to mark the object's end.
++ *
++ * @return this
++ * @throws JSONException
++ * If the nesting is too deep, or if the object is started in
++ * the wrong place (for example as a key or after the end of the
++ * outermost array or object).
++ */
++ public JSONWriter object() throws JSONException {
++ if (mode == 'i') {
++ mode = 'o';
++ }
++ if (mode == 'o' || mode == 'a') {
++ append("{");
++ push(new JSONObject());
++ comma = false;
++ return this;
++ }
++ throw new JSONException("Misplaced object.");
++
++ }
++
++ /**
++ * Pop an array or object scope.
++ *
++ * @param c
++ * The scope to close.
++ * @throws JSONException
++ * If nesting is wrong.
++ */
++ private void pop(char c) throws JSONException {
++ if (top <= 0) {
++ throw new JSONException("Nesting error.");
++ }
++ char m = stack[top - 1] == null ? 'a' : 'k';
++ if (m != c) {
++ throw new JSONException("Nesting error.");
++ }
++ top -= 1;
++ mode = top == 0 ? 'd' : stack[top - 1] == null ? 'a' : 'k';
++ }
++
++ /**
++ * Push an array or object scope.
++ *
++ * @param c
++ * The scope to open.
++ * @throws JSONException
++ * If nesting is too deep.
++ */
++ private void push(JSONObject jo) throws JSONException {
++ if (top >= maxdepth) {
++ throw new JSONException("Nesting too deep.");
++ }
++ stack[top] = jo;
++ mode = jo == null ? 'a' : 'k';
++ top += 1;
++ }
++
++ /**
++ * Append either the value <code>true</code> or the value <code>false</code>
++ * .
++ *
++ * @param b
++ * A boolean.
++ * @return this
++ * @throws JSONException
++ */
++ public JSONWriter value(boolean b) throws JSONException {
++ return append(b ? "true" : "false");
++ }
++
++ /**
++ * Append a double value.
++ *
++ * @param d
++ * A double.
++ * @return this
++ * @throws JSONException
++ * If the number is not finite.
++ */
++ public JSONWriter value(double d) throws JSONException {
++ return this.value(new Double(d));
++ }
++
++ /**
++ * Append a long value.
++ *
++ * @param l
++ * A long.
++ * @return this
++ * @throws JSONException
++ */
++ public JSONWriter value(long l) throws JSONException {
++ return append(Long.toString(l));
++ }
++
++ /**
++ * Append an object value.
++ *
++ * @param object
++ * The object to append. It can be null, or a Boolean, Number,
++ * String, JSONObject, or JSONArray, or an object that implements
++ * JSONString.
++ * @return this
++ * @throws JSONException
++ * If the value is out of sequence.
++ */
++ public JSONWriter value(Object object) throws JSONException {
++ return append(JSONObject.valueToString(object));
++ }
++}
- /*\r
- @VaadinApache2LicenseForJavaFiles@\r
- */\r
- package com.vaadin.terminal.gwt.client;\r
- \r
- import java.io.Serializable;\r
- \r
- import com.vaadin.terminal.gwt.server.WebBrowser;\r
- \r
- /**\r
- * Class that parses the user agent string from the browser and provides\r
- * information about the browser. Used internally by {@link BrowserInfo} and\r
- * {@link WebBrowser}. Should not be used directly.\r
- * \r
- * @author Vaadin Ltd.\r
- * @version @VERSION@\r
- * @since 6.3\r
- */\r
- public class VBrowserDetails implements Serializable {\r
- \r
- private boolean isGecko = false;\r
- private boolean isWebKit = false;\r
- private boolean isPresto = false;\r
- \r
- private boolean isChromeFrameCapable = false;\r
- private boolean isChromeFrame = false;\r
- \r
- private boolean isSafari = false;\r
- private boolean isChrome = false;\r
- private boolean isFirefox = false;\r
- private boolean isOpera = false;\r
- private boolean isIE = false;\r
- \r
- private boolean isWindows = false;\r
- private boolean isMacOSX = false;\r
- private boolean isLinux = false;\r
- \r
- private float browserEngineVersion = -1;\r
- private int browserMajorVersion = -1;\r
- private int browserMinorVersion = -1;\r
- \r
- /**\r
- * Create an instance based on the given user agent.\r
- * \r
- * @param userAgent\r
- * User agent as provided by the browser.\r
- */\r
- public VBrowserDetails(String userAgent) {\r
- userAgent = userAgent.toLowerCase();\r
- \r
- // browser engine name\r
- isGecko = userAgent.indexOf("gecko") != -1\r
- && userAgent.indexOf("webkit") == -1;\r
- isWebKit = userAgent.indexOf("applewebkit") != -1;\r
- isPresto = userAgent.indexOf(" presto/") != -1;\r
- \r
- // browser name\r
- isChrome = userAgent.indexOf(" chrome/") != -1;\r
- isSafari = !isChrome && userAgent.indexOf("safari") != -1;\r
- isOpera = userAgent.indexOf("opera") != -1;\r
- isIE = userAgent.indexOf("msie") != -1 && !isOpera\r
- && (userAgent.indexOf("webtv") == -1);\r
- isFirefox = userAgent.indexOf(" firefox/") != -1;\r
- \r
- // chromeframe\r
- isChromeFrameCapable = userAgent.indexOf("chromeframe") != -1;\r
- isChromeFrame = isChromeFrameCapable && !isChrome;\r
- \r
- // Rendering engine version\r
- try {\r
- if (isGecko) {\r
- int rvPos = userAgent.indexOf("rv:");\r
- if (rvPos >= 0) {\r
- String tmp = userAgent.substring(rvPos + 3);\r
- tmp = tmp.replaceFirst("(\\.[0-9]+).+", "$1");\r
- browserEngineVersion = Float.parseFloat(tmp);\r
- }\r
- } else if (isWebKit) {\r
- String tmp = userAgent\r
- .substring(userAgent.indexOf("webkit/") + 7);\r
- tmp = tmp.replaceFirst("([0-9]+)[^0-9].+", "$1");\r
- browserEngineVersion = Float.parseFloat(tmp);\r
- }\r
- } catch (Exception e) {\r
- // Browser engine version parsing failed\r
- System.err.println("Browser engine version parsing failed for: "\r
- + userAgent);\r
- }\r
- \r
- // Browser version\r
- try {\r
- if (isIE) {\r
- String ieVersionString = userAgent.substring(userAgent\r
- .indexOf("msie ") + 5);\r
- ieVersionString = safeSubstring(ieVersionString, 0,\r
- ieVersionString.indexOf(";"));\r
- parseVersionString(ieVersionString);\r
- } else if (isFirefox) {\r
- int i = userAgent.indexOf(" firefox/") + 9;\r
- parseVersionString(safeSubstring(userAgent, i, i + 5));\r
- } else if (isChrome) {\r
- int i = userAgent.indexOf(" chrome/") + 8;\r
- parseVersionString(safeSubstring(userAgent, i, i + 5));\r
- } else if (isSafari) {\r
- int i = userAgent.indexOf(" version/") + 9;\r
- parseVersionString(safeSubstring(userAgent, i, i + 5));\r
- } else if (isOpera) {\r
- int i = userAgent.indexOf(" version/");\r
- if (i != -1) {\r
- // Version present in Opera 10 and newer\r
- i += 9; // " version/".length\r
- } else {\r
- i = userAgent.indexOf("opera/") + 6;\r
- }\r
- parseVersionString(safeSubstring(userAgent, i, i + 5));\r
- }\r
- } catch (Exception e) {\r
- // Browser version parsing failed\r
- System.err.println("Browser version parsing failed for: "\r
- + userAgent);\r
- }\r
- \r
- // Operating system\r
- if (userAgent.contains("windows ")) {\r
- isWindows = true;\r
- } else if (userAgent.contains("linux")) {\r
- isLinux = true;\r
- } else if (userAgent.contains("macintosh")\r
- || userAgent.contains("mac osx")\r
- || userAgent.contains("mac os x")) {\r
- isMacOSX = true;\r
- }\r
- }\r
- \r
- private void parseVersionString(String versionString) {\r
- int idx = versionString.indexOf('.');\r
- if (idx < 0) {\r
- idx = versionString.length();\r
- }\r
- browserMajorVersion = Integer.parseInt(safeSubstring(versionString, 0,\r
- idx));\r
- \r
- int idx2 = versionString.indexOf('.', idx + 1);\r
- if (idx2 < 0) {\r
- idx2 = versionString.length();\r
- }\r
- try {\r
- browserMinorVersion = Integer.parseInt(safeSubstring(versionString,\r
- idx + 1, idx2).replaceAll("[^0-9].*", ""));\r
- } catch (NumberFormatException e) {\r
- // leave the minor version unmodified (-1 = unknown)\r
- }\r
- }\r
- \r
- private String safeSubstring(String string, int beginIndex, int endIndex) {\r
- if (beginIndex < 0) {\r
- beginIndex = 0;\r
- }\r
- if (endIndex < 0 || endIndex > string.length()) {\r
- endIndex = string.length();\r
- }\r
- return string.substring(beginIndex, endIndex);\r
- }\r
- \r
- /**\r
- * Tests if the browser is Firefox.\r
- * \r
- * @return true if it is Firefox, false otherwise\r
- */\r
- public boolean isFirefox() {\r
- return isFirefox;\r
- }\r
- \r
- /**\r
- * Tests if the browser is using the Gecko engine\r
- * \r
- * @return true if it is Gecko, false otherwise\r
- */\r
- public boolean isGecko() {\r
- return isGecko;\r
- }\r
- \r
- /**\r
- * Tests if the browser is using the WebKit engine\r
- * \r
- * @return true if it is WebKit, false otherwise\r
- */\r
- public boolean isWebKit() {\r
- return isWebKit;\r
- }\r
- \r
- /**\r
- * Tests if the browser is using the Presto engine\r
- * \r
- * @return true if it is Presto, false otherwise\r
- */\r
- public boolean isPresto() {\r
- return isPresto;\r
- }\r
- \r
- /**\r
- * Tests if the browser is Safari.\r
- * \r
- * @return true if it is Safari, false otherwise\r
- */\r
- public boolean isSafari() {\r
- return isSafari;\r
- }\r
- \r
- /**\r
- * Tests if the browser is Chrome.\r
- * \r
- * @return true if it is Chrome, false otherwise\r
- */\r
- public boolean isChrome() {\r
- return isChrome;\r
- }\r
- \r
- /**\r
- * Tests if the browser is capable of running ChromeFrame.\r
- * \r
- * @return true if it has ChromeFrame, false otherwise\r
- */\r
- public boolean isChromeFrameCapable() {\r
- return isChromeFrameCapable;\r
- }\r
- \r
- /**\r
- * Tests if the browser is running ChromeFrame.\r
- * \r
- * @return true if it is ChromeFrame, false otherwise\r
- */\r
- public boolean isChromeFrame() {\r
- return isChromeFrame;\r
- }\r
- \r
- /**\r
- * Tests if the browser is Opera.\r
- * \r
- * @return true if it is Opera, false otherwise\r
- */\r
- public boolean isOpera() {\r
- return isOpera;\r
- }\r
- \r
- /**\r
- * Tests if the browser is Internet Explorer.\r
- * \r
- * @return true if it is Internet Explorer, false otherwise\r
- */\r
- public boolean isIE() {\r
- return isIE;\r
- }\r
- \r
- /**\r
- * Returns the version of the browser engine. For WebKit this is an integer\r
- * e.g., 532.0. For gecko it is a float e.g., 1.8 or 1.9.\r
- * \r
- * @return The version of the browser engine\r
- */\r
- public float getBrowserEngineVersion() {\r
- return browserEngineVersion;\r
- }\r
- \r
- /**\r
- * Returns the browser major version e.g., 3 for Firefox 3.5, 4 for Chrome\r
- * 4, 8 for Internet Explorer 8.\r
- * <p>\r
- * Note that Internet Explorer 8 and newer will return the document mode so\r
- * IE8 rendering as IE7 will return 7.\r
- * </p>\r
- * \r
- * @return The major version of the browser.\r
- */\r
- public final int getBrowserMajorVersion() {\r
- return browserMajorVersion;\r
- }\r
- \r
- /**\r
- * Returns the browser minor version e.g., 5 for Firefox 3.5.\r
- * \r
- * @see #getBrowserMajorVersion()\r
- * \r
- * @return The minor version of the browser, or -1 if not known/parsed.\r
- */\r
- public final int getBrowserMinorVersion() {\r
- return browserMinorVersion;\r
- }\r
- \r
- /**\r
- * Sets the version for IE based on the documentMode. This is used to return\r
- * the correct the correct IE version when the version from the user agent\r
- * string and the value of the documentMode property do not match.\r
- * \r
- * @param documentMode\r
- * The current document mode\r
- */\r
- public void setIEMode(int documentMode) {\r
- browserMajorVersion = documentMode;\r
- browserMinorVersion = 0;\r
- }\r
- \r
- /**\r
- * Tests if the browser is run on Windows.\r
- * \r
- * @return true if run on Windows, false otherwise\r
- */\r
- public boolean isWindows() {\r
- return isWindows;\r
- }\r
- \r
- /**\r
- * Tests if the browser is run on Mac OSX.\r
- * \r
- * @return true if run on Mac OSX, false otherwise\r
- */\r
- public boolean isMacOSX() {\r
- return isMacOSX;\r
- }\r
- \r
- /**\r
- * Tests if the browser is run on Linux.\r
- * \r
- * @return true if run on Linux, false otherwise\r
- */\r
- public boolean isLinux() {\r
- return isLinux;\r
- }\r
- \r
- /**\r
- * Checks if the browser is so old that it simply won't work with a Vaadin\r
- * application. NOTE that the browser might still be capable of running\r
- * Crome Frame, so you might still want to check\r
- * {@link #isChromeFrameCapable()} if this returns true.\r
- * \r
- * @return true if the browser won't work, false if not the browser is\r
- * supported or might work\r
- */\r
- public boolean isTooOldToFunctionProperly() {\r
- if (isIE() && getBrowserMajorVersion() < 8) {\r
- return true;\r
- }\r
- if (isSafari() && getBrowserMajorVersion() < 5) {\r
- return true;\r
- }\r
- if (isFirefox() && getBrowserMajorVersion() < 4) {\r
- return true;\r
- }\r
- if (isOpera() && getBrowserMajorVersion() < 11) {\r
- return true;\r
- }\r
- \r
- return false;\r
- }\r
- \r
- }\r
+ /*
+ @VaadinApache2LicenseForJavaFiles@
+ */
+ package com.vaadin.terminal.gwt.client;
+
+ import java.io.Serializable;
+
+ import com.vaadin.terminal.gwt.server.WebBrowser;
+
+ /**
+ * Class that parses the user agent string from the browser and provides
+ * information about the browser. Used internally by {@link BrowserInfo} and
+ * {@link WebBrowser}. Should not be used directly.
+ *
+ * @author Vaadin Ltd.
+ * @version @VERSION@
+ * @since 6.3
+ */
+ public class VBrowserDetails implements Serializable {
+
+ private boolean isGecko = false;
+ private boolean isWebKit = false;
+ private boolean isPresto = false;
+
++ private boolean isChromeFrameCapable = false;
++ private boolean isChromeFrame = false;
++
+ private boolean isSafari = false;
+ private boolean isChrome = false;
+ private boolean isFirefox = false;
+ private boolean isOpera = false;
+ private boolean isIE = false;
+
+ private boolean isWindows = false;
+ private boolean isMacOSX = false;
+ private boolean isLinux = false;
+
+ private float browserEngineVersion = -1;
+ private int browserMajorVersion = -1;
+ private int browserMinorVersion = -1;
+
+ /**
+ * Create an instance based on the given user agent.
+ *
+ * @param userAgent
+ * User agent as provided by the browser.
+ */
+ public VBrowserDetails(String userAgent) {
+ userAgent = userAgent.toLowerCase();
+
+ // browser engine name
+ isGecko = userAgent.indexOf("gecko") != -1
+ && userAgent.indexOf("webkit") == -1;
+ isWebKit = userAgent.indexOf("applewebkit") != -1;
+ isPresto = userAgent.indexOf(" presto/") != -1;
+
+ // browser name
+ isChrome = userAgent.indexOf(" chrome/") != -1;
+ isSafari = !isChrome && userAgent.indexOf("safari") != -1;
+ isOpera = userAgent.indexOf("opera") != -1;
+ isIE = userAgent.indexOf("msie") != -1 && !isOpera
+ && (userAgent.indexOf("webtv") == -1);
+ isFirefox = userAgent.indexOf(" firefox/") != -1;
+
++ // chromeframe
++ isChromeFrameCapable = userAgent.indexOf("chromeframe") != -1;
++ isChromeFrame = isChromeFrameCapable && !isChrome;
++
+ // Rendering engine version
+ try {
+ if (isGecko) {
+ int rvPos = userAgent.indexOf("rv:");
+ if (rvPos >= 0) {
+ String tmp = userAgent.substring(rvPos + 3);
+ tmp = tmp.replaceFirst("(\\.[0-9]+).+", "$1");
+ browserEngineVersion = Float.parseFloat(tmp);
+ }
+ } else if (isWebKit) {
+ String tmp = userAgent
+ .substring(userAgent.indexOf("webkit/") + 7);
+ tmp = tmp.replaceFirst("([0-9]+)[^0-9].+", "$1");
+ browserEngineVersion = Float.parseFloat(tmp);
+ }
+ } catch (Exception e) {
+ // Browser engine version parsing failed
+ System.err.println("Browser engine version parsing failed for: "
+ + userAgent);
+ }
+
+ // Browser version
+ try {
+ if (isIE) {
+ String ieVersionString = userAgent.substring(userAgent
+ .indexOf("msie ") + 5);
+ ieVersionString = safeSubstring(ieVersionString, 0,
+ ieVersionString.indexOf(";"));
+ parseVersionString(ieVersionString);
+ } else if (isFirefox) {
+ int i = userAgent.indexOf(" firefox/") + 9;
+ parseVersionString(safeSubstring(userAgent, i, i + 5));
+ } else if (isChrome) {
+ int i = userAgent.indexOf(" chrome/") + 8;
+ parseVersionString(safeSubstring(userAgent, i, i + 5));
+ } else if (isSafari) {
+ int i = userAgent.indexOf(" version/") + 9;
+ parseVersionString(safeSubstring(userAgent, i, i + 5));
+ } else if (isOpera) {
+ int i = userAgent.indexOf(" version/");
+ if (i != -1) {
+ // Version present in Opera 10 and newer
+ i += 9; // " version/".length
+ } else {
+ i = userAgent.indexOf("opera/") + 6;
+ }
+ parseVersionString(safeSubstring(userAgent, i, i + 5));
+ }
+ } catch (Exception e) {
+ // Browser version parsing failed
+ System.err.println("Browser version parsing failed for: "
+ + userAgent);
+ }
+
+ // Operating system
+ if (userAgent.contains("windows ")) {
+ isWindows = true;
+ } else if (userAgent.contains("linux")) {
+ isLinux = true;
+ } else if (userAgent.contains("macintosh")
+ || userAgent.contains("mac osx")
+ || userAgent.contains("mac os x")) {
+ isMacOSX = true;
+ }
+ }
+
+ private void parseVersionString(String versionString) {
+ int idx = versionString.indexOf('.');
+ if (idx < 0) {
+ idx = versionString.length();
+ }
+ browserMajorVersion = Integer.parseInt(safeSubstring(versionString, 0,
+ idx));
+
+ int idx2 = versionString.indexOf('.', idx + 1);
+ if (idx2 < 0) {
+ idx2 = versionString.length();
+ }
+ try {
+ browserMinorVersion = Integer.parseInt(safeSubstring(versionString,
+ idx + 1, idx2).replaceAll("[^0-9].*", ""));
+ } catch (NumberFormatException e) {
+ // leave the minor version unmodified (-1 = unknown)
+ }
+ }
+
+ private String safeSubstring(String string, int beginIndex, int endIndex) {
+ if (beginIndex < 0) {
+ beginIndex = 0;
+ }
+ if (endIndex < 0 || endIndex > string.length()) {
+ endIndex = string.length();
+ }
+ return string.substring(beginIndex, endIndex);
+ }
+
+ /**
+ * Tests if the browser is Firefox.
+ *
+ * @return true if it is Firefox, false otherwise
+ */
+ public boolean isFirefox() {
+ return isFirefox;
+ }
+
+ /**
+ * Tests if the browser is using the Gecko engine
+ *
+ * @return true if it is Gecko, false otherwise
+ */
+ public boolean isGecko() {
+ return isGecko;
+ }
+
+ /**
+ * Tests if the browser is using the WebKit engine
+ *
+ * @return true if it is WebKit, false otherwise
+ */
+ public boolean isWebKit() {
+ return isWebKit;
+ }
+
+ /**
+ * Tests if the browser is using the Presto engine
+ *
+ * @return true if it is Presto, false otherwise
+ */
+ public boolean isPresto() {
+ return isPresto;
+ }
+
+ /**
+ * Tests if the browser is Safari.
+ *
+ * @return true if it is Safari, false otherwise
+ */
+ public boolean isSafari() {
+ return isSafari;
+ }
+
+ /**
+ * Tests if the browser is Chrome.
+ *
+ * @return true if it is Chrome, false otherwise
+ */
+ public boolean isChrome() {
+ return isChrome;
+ }
+
++ /**
++ * Tests if the browser is capable of running ChromeFrame.
++ *
++ * @return true if it has ChromeFrame, false otherwise
++ */
++ public boolean isChromeFrameCapable() {
++ return isChromeFrameCapable;
++ }
++
++ /**
++ * Tests if the browser is running ChromeFrame.
++ *
++ * @return true if it is ChromeFrame, false otherwise
++ */
++ public boolean isChromeFrame() {
++ return isChromeFrame;
++ }
++
+ /**
+ * Tests if the browser is Opera.
+ *
+ * @return true if it is Opera, false otherwise
+ */
+ public boolean isOpera() {
+ return isOpera;
+ }
+
+ /**
+ * Tests if the browser is Internet Explorer.
+ *
+ * @return true if it is Internet Explorer, false otherwise
+ */
+ public boolean isIE() {
+ return isIE;
+ }
+
+ /**
+ * Returns the version of the browser engine. For WebKit this is an integer
+ * e.g., 532.0. For gecko it is a float e.g., 1.8 or 1.9.
+ *
+ * @return The version of the browser engine
+ */
+ public float getBrowserEngineVersion() {
+ return browserEngineVersion;
+ }
+
+ /**
+ * Returns the browser major version e.g., 3 for Firefox 3.5, 4 for Chrome
+ * 4, 8 for Internet Explorer 8.
+ * <p>
+ * Note that Internet Explorer 8 and newer will return the document mode so
+ * IE8 rendering as IE7 will return 7.
+ * </p>
+ *
+ * @return The major version of the browser.
+ */
+ public final int getBrowserMajorVersion() {
+ return browserMajorVersion;
+ }
+
+ /**
+ * Returns the browser minor version e.g., 5 for Firefox 3.5.
+ *
+ * @see #getBrowserMajorVersion()
+ *
+ * @return The minor version of the browser, or -1 if not known/parsed.
+ */
+ public final int getBrowserMinorVersion() {
+ return browserMinorVersion;
+ }
+
+ /**
+ * Sets the version for IE based on the documentMode. This is used to return
+ * the correct the correct IE version when the version from the user agent
+ * string and the value of the documentMode property do not match.
+ *
+ * @param documentMode
+ * The current document mode
+ */
+ public void setIEMode(int documentMode) {
+ browserMajorVersion = documentMode;
+ browserMinorVersion = 0;
+ }
+
+ /**
+ * Tests if the browser is run on Windows.
+ *
+ * @return true if run on Windows, false otherwise
+ */
+ public boolean isWindows() {
+ return isWindows;
+ }
+
+ /**
+ * Tests if the browser is run on Mac OSX.
+ *
+ * @return true if run on Mac OSX, false otherwise
+ */
+ public boolean isMacOSX() {
+ return isMacOSX;
+ }
+
+ /**
+ * Tests if the browser is run on Linux.
+ *
+ * @return true if run on Linux, false otherwise
+ */
+ public boolean isLinux() {
+ return isLinux;
+ }
+
++ /**
++ * Checks if the browser is so old that it simply won't work with a Vaadin
++ * application. NOTE that the browser might still be capable of running
++ * Crome Frame, so you might still want to check
++ * {@link #isChromeFrameCapable()} if this returns true.
++ *
++ * @return true if the browser won't work, false if not the browser is
++ * supported or might work
++ */
++ public boolean isTooOldToFunctionProperly() {
++ if (isIE() && getBrowserMajorVersion() < 8) {
++ return true;
++ }
++ if (isSafari() && getBrowserMajorVersion() < 5) {
++ return true;
++ }
++ if (isFirefox() && getBrowserMajorVersion() < 4) {
++ return true;
++ }
++ if (isOpera() && getBrowserMajorVersion() < 11) {
++ return true;
++ }
++
++ return false;
++ }
++
+ }
--- /dev/null
- /*\r
- @VaadinApache2LicenseForJavaFiles@\r
- */\r
- package com.vaadin.terminal.gwt.client;\r
- \r
- /**\r
- * Interface implemented by all client side classes that can be communicate with\r
- * the server. Classes implementing this interface are initialized by the\r
- * framework when needed and have the ability to communicate with the server.\r
- * \r
- * @author Vaadin Ltd\r
- * @version @VERSION@\r
- * @since 7.0.0\r
- */\r
- public interface VPaintable {\r
- /**\r
- * TODO\r
- * \r
- * @param uidl\r
- * @param client\r
- */\r
- public void updateFromUIDL(UIDL uidl, ApplicationConnection client);\r
- \r
- // /**\r
- // * Returns the id for this VPaintable. This must always be what has been\r
- // set\r
- // * using {@link #setId(String)}.\r
- // *\r
- // * @return The id for the VPaintable.\r
- // */\r
- // public String getId();\r
- //\r
- // /**\r
- // * Sets the id for the VPaintable. This method is called once by the\r
- // * framework when the VPaintable is initialized and should never be called\r
- // * otherwise.\r
- // * <p>\r
- // * The VPaintable id is used to map the server and the client paintables\r
- // * together. It is unique in this root and assigned by the framework.\r
- // * </p>\r
- // *\r
- // * @param id\r
- // * The id of the paintable.\r
- // */\r
- // public void setId(String id);\r
- \r
- /**\r
- * Gets ApplicationConnection instance that created this VPaintable.\r
- * \r
- * @return The ApplicationConnection as set by\r
- * {@link #setConnection(ApplicationConnection)}\r
- */\r
- // public ApplicationConnection getConnection();\r
- \r
- /**\r
- * Sets the reference to ApplicationConnection. This method is called by the\r
- * framework when the VPaintable is created and should never be called\r
- * otherwise.\r
- * \r
- * @param connection\r
- * The ApplicationConnection that created this VPaintable\r
- */\r
- // public void setConnection(ApplicationConnection connection);\r
- \r
- /**\r
- * Tests whether the component is enabled or not. A user can not interact\r
- * with disabled components. Disabled components are rendered in a style\r
- * that indicates the status, usually in gray color. Children of a disabled\r
- * component are also disabled.\r
- * \r
- * @return true if the component is enabled, false otherwise\r
- */\r
- // public boolean isEnabled();\r
- }\r
++/*
++@VaadinApache2LicenseForJavaFiles@
++ */
++package com.vaadin.terminal.gwt.client;
++
++/**
++ * Interface implemented by all client side classes that can be communicate with
++ * the server. Classes implementing this interface are initialized by the
++ * framework when needed and have the ability to communicate with the server.
++ *
++ * @author Vaadin Ltd
++ * @version @VERSION@
++ * @since 7.0.0
++ */
++public interface VPaintable {
++ /**
++ * TODO
++ *
++ * @param uidl
++ * @param client
++ */
++ public void updateFromUIDL(UIDL uidl, ApplicationConnection client);
++
++ // /**
++ // * Returns the id for this VPaintable. This must always be what has been
++ // set
++ // * using {@link #setId(String)}.
++ // *
++ // * @return The id for the VPaintable.
++ // */
++ // public String getId();
++ //
++ // /**
++ // * Sets the id for the VPaintable. This method is called once by the
++ // * framework when the VPaintable is initialized and should never be called
++ // * otherwise.
++ // * <p>
++ // * The VPaintable id is used to map the server and the client paintables
++ // * together. It is unique in this root and assigned by the framework.
++ // * </p>
++ // *
++ // * @param id
++ // * The id of the paintable.
++ // */
++ // public void setId(String id);
++
++ /**
++ * Gets ApplicationConnection instance that created this VPaintable.
++ *
++ * @return The ApplicationConnection as set by
++ * {@link #setConnection(ApplicationConnection)}
++ */
++ // public ApplicationConnection getConnection();
++
++ /**
++ * Sets the reference to ApplicationConnection. This method is called by the
++ * framework when the VPaintable is created and should never be called
++ * otherwise.
++ *
++ * @param connection
++ * The ApplicationConnection that created this VPaintable
++ */
++ // public void setConnection(ApplicationConnection connection);
++
++ /**
++ * Tests whether the component is enabled or not. A user can not interact
++ * with disabled components. Disabled components are rendered in a style
++ * that indicates the status, usually in gray color. Children of a disabled
++ * component are also disabled.
++ *
++ * @return true if the component is enabled, false otherwise
++ */
++ // public boolean isEnabled();
++}
--- /dev/null
- /*\r
- @VaadinApache2LicenseForJavaFiles@\r
- */\r
- package com.vaadin.terminal.gwt.client;\r
- \r
- import java.util.Collection;\r
- import java.util.Collections;\r
- import java.util.HashMap;\r
- import java.util.HashSet;\r
- import java.util.Iterator;\r
- import java.util.Map;\r
- import java.util.Set;\r
- \r
- import com.google.gwt.core.client.GWT;\r
- import com.google.gwt.user.client.Element;\r
- import com.google.gwt.user.client.ui.HasWidgets;\r
- import com.google.gwt.user.client.ui.Widget;\r
- import com.vaadin.terminal.Paintable;\r
- import com.vaadin.terminal.gwt.client.RenderInformation.FloatSize;\r
- import com.vaadin.terminal.gwt.client.RenderInformation.Size;\r
- \r
- public class VPaintableMap {\r
- \r
- private Map<String, VPaintable> idToPaintable = new HashMap<String, VPaintable>();\r
- private Map<VPaintable, String> paintableToId = new HashMap<VPaintable, String>();\r
- \r
- public static VPaintableMap get(ApplicationConnection applicationConnection) {\r
- return applicationConnection.getPaintableMap();\r
- }\r
- \r
- @Deprecated\r
- private final ComponentDetailMap idToComponentDetail = ComponentDetailMap\r
- .create();\r
- \r
- private Set<String> unregistryBag = new HashSet<String>();\r
- \r
- /**\r
- * Returns a Paintable by its paintable id\r
- * \r
- * @param id\r
- * The Paintable id\r
- */\r
- public VPaintable getPaintable(String pid) {\r
- return idToPaintable.get(pid);\r
- }\r
- \r
- /**\r
- * Returns a Paintable element by its root element\r
- * \r
- * @param element\r
- * Root element of the paintable\r
- */\r
- public VPaintableWidget getPaintable(Element element) {\r
- return (VPaintableWidget) getPaintable(getPid(element));\r
- }\r
- \r
- /**\r
- * FIXME: What does this even do and why?\r
- * \r
- * @param pid\r
- * @return\r
- */\r
- public boolean isDragAndDropPaintable(String pid) {\r
- return (pid.startsWith("DD"));\r
- }\r
- \r
- /**\r
- * Checks if a paintable with the given paintable id has been registered.\r
- * \r
- * @param pid\r
- * The paintable id to check for\r
- * @return true if a paintable has been registered with the given paintable\r
- * id, false otherwise\r
- */\r
- public boolean hasPaintable(String pid) {\r
- return idToPaintable.containsKey(pid);\r
- }\r
- \r
- /**\r
- * Removes all registered paintable ids\r
- */\r
- public void clear() {\r
- idToPaintable.clear();\r
- paintableToId.clear();\r
- idToComponentDetail.clear();\r
- }\r
- \r
- @Deprecated\r
- public Widget getWidget(VPaintableWidget paintable) {\r
- return paintable.getWidgetForPaintable();\r
- }\r
- \r
- @Deprecated\r
- public VPaintableWidget getPaintable(Widget widget) {\r
- return getPaintable(widget.getElement());\r
- }\r
- \r
- public void registerPaintable(String pid, VPaintable paintable) {\r
- ComponentDetail componentDetail = GWT.create(ComponentDetail.class);\r
- idToComponentDetail.put(pid, componentDetail);\r
- idToPaintable.put(pid, paintable);\r
- paintableToId.put(paintable, pid);\r
- if (paintable instanceof VPaintableWidget) {\r
- VPaintableWidget pw = (VPaintableWidget) paintable;\r
- setPid(pw.getWidgetForPaintable().getElement(), pid);\r
- }\r
- }\r
- \r
- private native void setPid(Element el, String pid)\r
- /*-{\r
- el.tkPid = pid;\r
- }-*/;\r
- \r
- /**\r
- * Gets the paintableId for a specific paintable.\r
- * <p>\r
- * The paintableId is used in the UIDL to identify a specific widget\r
- * instance, effectively linking the widget with it's server side Component.\r
- * </p>\r
- * \r
- * @param paintable\r
- * the paintable who's id is needed\r
- * @return the id for the given paintable or null if the paintable could not\r
- * be found\r
- */\r
- public String getPid(VPaintable paintable) {\r
- if (paintable == null) {\r
- return null;\r
- }\r
- return paintableToId.get(paintable);\r
- }\r
- \r
- @Deprecated\r
- public String getPid(Widget widget) {\r
- return getPid(widget.getElement());\r
- }\r
- \r
- /**\r
- * Gets the paintableId using a DOM element - the element should be the main\r
- * element for a paintable otherwise no id will be found. Use\r
- * {@link #getPid(Paintable)} instead whenever possible.\r
- * \r
- * @see #getPid(Paintable)\r
- * @param el\r
- * element of the paintable whose pid is desired\r
- * @return the pid of the element's paintable, if it's a paintable\r
- */\r
- native String getPid(Element el)\r
- /*-{\r
- return el.tkPid;\r
- }-*/;\r
- \r
- /**\r
- * Gets the main element for the paintable with the given id. The revers of\r
- * {@link #getPid(Element)}.\r
- * \r
- * @param pid\r
- * the pid of the widget whose element is desired\r
- * @return the element for the paintable corresponding to the pid\r
- */\r
- public Element getElement(String pid) {\r
- VPaintable p = getPaintable(pid);\r
- if (p instanceof VPaintableWidget) {\r
- return ((VPaintableWidget) p).getWidgetForPaintable().getElement();\r
- }\r
- \r
- return null;\r
- }\r
- \r
- /**\r
- * Unregisters the given paintable; always use after removing a paintable.\r
- * This method does not remove the paintable from the DOM, but marks the\r
- * paintable so that ApplicationConnection may clean up its references to\r
- * it. Removing the widget from DOM is component containers responsibility.\r
- * \r
- * @param p\r
- * the paintable to remove\r
- */\r
- public void unregisterPaintable(VPaintable p) {\r
- \r
- // add to unregistry que\r
- \r
- if (p == null) {\r
- VConsole.error("WARN: Trying to unregister null paintable");\r
- return;\r
- }\r
- String id = getPid(p);\r
- Widget widget = null;\r
- if (p instanceof VPaintableWidget) {\r
- widget = ((VPaintableWidget) p).getWidgetForPaintable();\r
- }\r
- \r
- if (id == null) {\r
- /*\r
- * Uncomment the following to debug unregistring components. No\r
- * paintables with null id should end here. At least one exception\r
- * is our VScrollTableRow, that is hacked to fake it self as a\r
- * Paintable to build support for sizing easier.\r
- */\r
- // if (!(p instanceof VScrollTableRow)) {\r
- // VConsole.log("Trying to unregister Paintable not created by Application Connection.");\r
- // }\r
- } else {\r
- unregistryBag.add(id);\r
- }\r
- if (widget != null && widget instanceof HasWidgets) {\r
- unregisterChildPaintables((HasWidgets) widget);\r
- }\r
- \r
- }\r
- \r
- void purgeUnregistryBag(boolean unregisterPaintables) {\r
- if (unregisterPaintables) {\r
- for (String pid : unregistryBag) {\r
- VPaintable paintable = getPaintable(pid);\r
- if (paintable == null) {\r
- /*\r
- * this should never happen, but it does :-( See e.g.\r
- * com.vaadin.tests.components.accordion.RemoveTabs (with\r
- * test script)\r
- */\r
- VConsole.error("Tried to unregister component (id="\r
- + pid\r
- + ") that is never registered (or already unregistered)");\r
- continue;\r
- }\r
- Widget widget = null;\r
- if (paintable instanceof VPaintableWidget) {\r
- widget = ((VPaintableWidget) paintable)\r
- .getWidgetForPaintable();\r
- }\r
- \r
- // check if can be cleaned\r
- if (widget == null || !widget.isAttached()) {\r
- // clean reference to paintable\r
- idToComponentDetail.remove(pid);\r
- idToPaintable.remove(pid);\r
- paintableToId.remove(paintable);\r
- }\r
- /*\r
- * else NOP : same component has been reattached to another\r
- * parent or replaced by another component implementation.\r
- */\r
- }\r
- }\r
- \r
- unregistryBag.clear();\r
- }\r
- \r
- /**\r
- * Unregisters a paintable and all it's child paintables recursively. Use\r
- * when after removing a paintable that contains other paintables. Does not\r
- * unregister the given container itself. Does not actually remove the\r
- * paintable from the DOM.\r
- * \r
- * @see #unregisterPaintable(Paintable)\r
- * @param container\r
- */\r
- public void unregisterChildPaintables(HasWidgets container) {\r
- // FIXME: This should be based on the paintable hierarchy\r
- final Iterator<Widget> it = container.iterator();\r
- while (it.hasNext()) {\r
- final Widget w = it.next();\r
- VPaintableWidget p = getPaintable(w);\r
- if (p != null) {\r
- // This will unregister the paintable and all its children\r
- unregisterPaintable(p);\r
- } else if (w instanceof HasWidgets) {\r
- // For normal widget containers, unregister the children\r
- unregisterChildPaintables((HasWidgets) w);\r
- }\r
- }\r
- }\r
- \r
- /**\r
- * FIXME: Should not be here\r
- * \r
- * @param pid\r
- * @param uidl\r
- */\r
- @Deprecated\r
- public void registerEventListenersFromUIDL(String pid, UIDL uidl) {\r
- ComponentDetail cd = idToComponentDetail.get(pid);\r
- if (cd == null) {\r
- throw new IllegalArgumentException("Pid must not be null");\r
- }\r
- \r
- cd.registerEventListenersFromUIDL(uidl);\r
- \r
- }\r
- \r
- /**\r
- * FIXME: Should not be here\r
- * \r
- * @param paintable\r
- * @return\r
- */\r
- @Deprecated\r
- public Size getOffsetSize(VPaintableWidget paintable) {\r
- return getComponentDetail(paintable).getOffsetSize();\r
- }\r
- \r
- /**\r
- * FIXME: Should not be here\r
- * \r
- * @param paintable\r
- * @return\r
- */\r
- @Deprecated\r
- public FloatSize getRelativeSize(VPaintableWidget paintable) {\r
- return getComponentDetail(paintable).getRelativeSize();\r
- }\r
- \r
- /**\r
- * FIXME: Should not be here\r
- * \r
- * @param paintable\r
- * @return\r
- */\r
- @Deprecated\r
- public void setOffsetSize(VPaintableWidget paintable, Size newSize) {\r
- getComponentDetail(paintable).setOffsetSize(newSize);\r
- }\r
- \r
- /**\r
- * FIXME: Should not be here\r
- * \r
- * @param paintable\r
- * @return\r
- */\r
- @Deprecated\r
- public void setRelativeSize(VPaintableWidget paintable,\r
- FloatSize relativeSize) {\r
- getComponentDetail(paintable).setRelativeSize(relativeSize);\r
- \r
- }\r
- \r
- private ComponentDetail getComponentDetail(VPaintableWidget paintable) {\r
- return idToComponentDetail.get(getPid(paintable));\r
- }\r
- \r
- public int size() {\r
- return idToPaintable.size();\r
- }\r
- \r
- /**\r
- * FIXME: Should be moved to VAbstractPaintableWidget\r
- * \r
- * @param paintable\r
- * @return\r
- */\r
- @Deprecated\r
- public TooltipInfo getTooltipInfo(VPaintableWidget paintable, Object key) {\r
- return getComponentDetail(paintable).getTooltipInfo(key);\r
- }\r
- \r
- @Deprecated\r
- public TooltipInfo getWidgetTooltipInfo(Widget widget, Object key) {\r
- return getTooltipInfo(getPaintable(widget), key);\r
- }\r
- \r
- public Collection<? extends VPaintable> getPaintables() {\r
- return Collections.unmodifiableCollection(paintableToId.keySet());\r
- }\r
- \r
- /**\r
- * FIXME: Should not be here\r
- * \r
- * @param paintable\r
- * @return\r
- */\r
- @Deprecated\r
- public void registerTooltip(VPaintableWidget paintable, Object key,\r
- TooltipInfo tooltip) {\r
- getComponentDetail(paintable).putAdditionalTooltip(key, tooltip);\r
- \r
- }\r
- \r
- /**\r
- * FIXME: Should not be here\r
- * \r
- * @param paintable\r
- * @return\r
- */\r
- @Deprecated\r
- public boolean hasEventListeners(VPaintableWidget paintable,\r
- String eventIdentifier) {\r
- return getComponentDetail(paintable).hasEventListeners(eventIdentifier);\r
- }\r
- \r
- /**\r
- * Tests if the widget is the root widget of a VPaintableWidget.\r
- * \r
- * @param widget\r
- * The widget to test\r
- * @return true if the widget is the root widget of a VPaintableWidget,\r
- * false otherwise\r
- */\r
- public boolean isPaintable(Widget w) {\r
- return getPid(w) != null;\r
- }\r
- \r
- }\r
++/*
++@VaadinApache2LicenseForJavaFiles@
++ */
++package com.vaadin.terminal.gwt.client;
++
++import java.util.Collection;
++import java.util.Collections;
++import java.util.HashMap;
++import java.util.HashSet;
++import java.util.Iterator;
++import java.util.Map;
++import java.util.Set;
++
++import com.google.gwt.core.client.GWT;
++import com.google.gwt.user.client.Element;
++import com.google.gwt.user.client.ui.HasWidgets;
++import com.google.gwt.user.client.ui.Widget;
++import com.vaadin.terminal.Paintable;
++import com.vaadin.terminal.gwt.client.RenderInformation.FloatSize;
++import com.vaadin.terminal.gwt.client.RenderInformation.Size;
++
++public class VPaintableMap {
++
++ private Map<String, VPaintable> idToPaintable = new HashMap<String, VPaintable>();
++ private Map<VPaintable, String> paintableToId = new HashMap<VPaintable, String>();
++
++ public static VPaintableMap get(ApplicationConnection applicationConnection) {
++ return applicationConnection.getPaintableMap();
++ }
++
++ @Deprecated
++ private final ComponentDetailMap idToComponentDetail = ComponentDetailMap
++ .create();
++
++ private Set<String> unregistryBag = new HashSet<String>();
++
++ /**
++ * Returns a Paintable by its paintable id
++ *
++ * @param id
++ * The Paintable id
++ */
++ public VPaintable getPaintable(String pid) {
++ return idToPaintable.get(pid);
++ }
++
++ /**
++ * Returns a Paintable element by its root element
++ *
++ * @param element
++ * Root element of the paintable
++ */
++ public VPaintableWidget getPaintable(Element element) {
++ return (VPaintableWidget) getPaintable(getPid(element));
++ }
++
++ /**
++ * FIXME: What does this even do and why?
++ *
++ * @param pid
++ * @return
++ */
++ public boolean isDragAndDropPaintable(String pid) {
++ return (pid.startsWith("DD"));
++ }
++
++ /**
++ * Checks if a paintable with the given paintable id has been registered.
++ *
++ * @param pid
++ * The paintable id to check for
++ * @return true if a paintable has been registered with the given paintable
++ * id, false otherwise
++ */
++ public boolean hasPaintable(String pid) {
++ return idToPaintable.containsKey(pid);
++ }
++
++ /**
++ * Removes all registered paintable ids
++ */
++ public void clear() {
++ idToPaintable.clear();
++ paintableToId.clear();
++ idToComponentDetail.clear();
++ }
++
++ @Deprecated
++ public Widget getWidget(VPaintableWidget paintable) {
++ return paintable.getWidgetForPaintable();
++ }
++
++ @Deprecated
++ public VPaintableWidget getPaintable(Widget widget) {
++ return getPaintable(widget.getElement());
++ }
++
++ public void registerPaintable(String pid, VPaintable paintable) {
++ ComponentDetail componentDetail = GWT.create(ComponentDetail.class);
++ idToComponentDetail.put(pid, componentDetail);
++ idToPaintable.put(pid, paintable);
++ paintableToId.put(paintable, pid);
++ if (paintable instanceof VPaintableWidget) {
++ VPaintableWidget pw = (VPaintableWidget) paintable;
++ setPid(pw.getWidgetForPaintable().getElement(), pid);
++ }
++ }
++
++ private native void setPid(Element el, String pid)
++ /*-{
++ el.tkPid = pid;
++ }-*/;
++
++ /**
++ * Gets the paintableId for a specific paintable.
++ * <p>
++ * The paintableId is used in the UIDL to identify a specific widget
++ * instance, effectively linking the widget with it's server side Component.
++ * </p>
++ *
++ * @param paintable
++ * the paintable who's id is needed
++ * @return the id for the given paintable or null if the paintable could not
++ * be found
++ */
++ public String getPid(VPaintable paintable) {
++ if (paintable == null) {
++ return null;
++ }
++ return paintableToId.get(paintable);
++ }
++
++ @Deprecated
++ public String getPid(Widget widget) {
++ return getPid(widget.getElement());
++ }
++
++ /**
++ * Gets the paintableId using a DOM element - the element should be the main
++ * element for a paintable otherwise no id will be found. Use
++ * {@link #getPid(Paintable)} instead whenever possible.
++ *
++ * @see #getPid(Paintable)
++ * @param el
++ * element of the paintable whose pid is desired
++ * @return the pid of the element's paintable, if it's a paintable
++ */
++ native String getPid(Element el)
++ /*-{
++ return el.tkPid;
++ }-*/;
++
++ /**
++ * Gets the main element for the paintable with the given id. The revers of
++ * {@link #getPid(Element)}.
++ *
++ * @param pid
++ * the pid of the widget whose element is desired
++ * @return the element for the paintable corresponding to the pid
++ */
++ public Element getElement(String pid) {
++ VPaintable p = getPaintable(pid);
++ if (p instanceof VPaintableWidget) {
++ return ((VPaintableWidget) p).getWidgetForPaintable().getElement();
++ }
++
++ return null;
++ }
++
++ /**
++ * Unregisters the given paintable; always use after removing a paintable.
++ * This method does not remove the paintable from the DOM, but marks the
++ * paintable so that ApplicationConnection may clean up its references to
++ * it. Removing the widget from DOM is component containers responsibility.
++ *
++ * @param p
++ * the paintable to remove
++ */
++ public void unregisterPaintable(VPaintable p) {
++
++ // add to unregistry que
++
++ if (p == null) {
++ VConsole.error("WARN: Trying to unregister null paintable");
++ return;
++ }
++ String id = getPid(p);
++ Widget widget = null;
++ if (p instanceof VPaintableWidget) {
++ widget = ((VPaintableWidget) p).getWidgetForPaintable();
++ }
++
++ if (id == null) {
++ /*
++ * Uncomment the following to debug unregistring components. No
++ * paintables with null id should end here. At least one exception
++ * is our VScrollTableRow, that is hacked to fake it self as a
++ * Paintable to build support for sizing easier.
++ */
++ // if (!(p instanceof VScrollTableRow)) {
++ // VConsole.log("Trying to unregister Paintable not created by Application Connection.");
++ // }
++ } else {
++ unregistryBag.add(id);
++ }
++ if (widget != null && widget instanceof HasWidgets) {
++ unregisterChildPaintables((HasWidgets) widget);
++ }
++
++ }
++
++ void purgeUnregistryBag(boolean unregisterPaintables) {
++ if (unregisterPaintables) {
++ for (String pid : unregistryBag) {
++ VPaintable paintable = getPaintable(pid);
++ if (paintable == null) {
++ /*
++ * this should never happen, but it does :-( See e.g.
++ * com.vaadin.tests.components.accordion.RemoveTabs (with
++ * test script)
++ */
++ VConsole.error("Tried to unregister component (id="
++ + pid
++ + ") that is never registered (or already unregistered)");
++ continue;
++ }
++ Widget widget = null;
++ if (paintable instanceof VPaintableWidget) {
++ widget = ((VPaintableWidget) paintable)
++ .getWidgetForPaintable();
++ }
++
++ // check if can be cleaned
++ if (widget == null || !widget.isAttached()) {
++ // clean reference to paintable
++ idToComponentDetail.remove(pid);
++ idToPaintable.remove(pid);
++ paintableToId.remove(paintable);
++ }
++ /*
++ * else NOP : same component has been reattached to another
++ * parent or replaced by another component implementation.
++ */
++ }
++ }
++
++ unregistryBag.clear();
++ }
++
++ /**
++ * Unregisters a paintable and all it's child paintables recursively. Use
++ * when after removing a paintable that contains other paintables. Does not
++ * unregister the given container itself. Does not actually remove the
++ * paintable from the DOM.
++ *
++ * @see #unregisterPaintable(Paintable)
++ * @param container
++ */
++ public void unregisterChildPaintables(HasWidgets container) {
++ // FIXME: This should be based on the paintable hierarchy
++ final Iterator<Widget> it = container.iterator();
++ while (it.hasNext()) {
++ final Widget w = it.next();
++ VPaintableWidget p = getPaintable(w);
++ if (p != null) {
++ // This will unregister the paintable and all its children
++ unregisterPaintable(p);
++ } else if (w instanceof HasWidgets) {
++ // For normal widget containers, unregister the children
++ unregisterChildPaintables((HasWidgets) w);
++ }
++ }
++ }
++
++ /**
++ * FIXME: Should not be here
++ *
++ * @param pid
++ * @param uidl
++ */
++ @Deprecated
++ public void registerEventListenersFromUIDL(String pid, UIDL uidl) {
++ ComponentDetail cd = idToComponentDetail.get(pid);
++ if (cd == null) {
++ throw new IllegalArgumentException("Pid must not be null");
++ }
++
++ cd.registerEventListenersFromUIDL(uidl);
++
++ }
++
++ /**
++ * FIXME: Should not be here
++ *
++ * @param paintable
++ * @return
++ */
++ @Deprecated
++ public Size getOffsetSize(VPaintableWidget paintable) {
++ return getComponentDetail(paintable).getOffsetSize();
++ }
++
++ /**
++ * FIXME: Should not be here
++ *
++ * @param paintable
++ * @return
++ */
++ @Deprecated
++ public FloatSize getRelativeSize(VPaintableWidget paintable) {
++ return getComponentDetail(paintable).getRelativeSize();
++ }
++
++ /**
++ * FIXME: Should not be here
++ *
++ * @param paintable
++ * @return
++ */
++ @Deprecated
++ public void setOffsetSize(VPaintableWidget paintable, Size newSize) {
++ getComponentDetail(paintable).setOffsetSize(newSize);
++ }
++
++ /**
++ * FIXME: Should not be here
++ *
++ * @param paintable
++ * @return
++ */
++ @Deprecated
++ public void setRelativeSize(VPaintableWidget paintable,
++ FloatSize relativeSize) {
++ getComponentDetail(paintable).setRelativeSize(relativeSize);
++
++ }
++
++ private ComponentDetail getComponentDetail(VPaintableWidget paintable) {
++ return idToComponentDetail.get(getPid(paintable));
++ }
++
++ public int size() {
++ return idToPaintable.size();
++ }
++
++ /**
++ * FIXME: Should be moved to VAbstractPaintableWidget
++ *
++ * @param paintable
++ * @return
++ */
++ @Deprecated
++ public TooltipInfo getTooltipInfo(VPaintableWidget paintable, Object key) {
++ return getComponentDetail(paintable).getTooltipInfo(key);
++ }
++
++ @Deprecated
++ public TooltipInfo getWidgetTooltipInfo(Widget widget, Object key) {
++ return getTooltipInfo(getPaintable(widget), key);
++ }
++
++ public Collection<? extends VPaintable> getPaintables() {
++ return Collections.unmodifiableCollection(paintableToId.keySet());
++ }
++
++ /**
++ * FIXME: Should not be here
++ *
++ * @param paintable
++ * @return
++ */
++ @Deprecated
++ public void registerTooltip(VPaintableWidget paintable, Object key,
++ TooltipInfo tooltip) {
++ getComponentDetail(paintable).putAdditionalTooltip(key, tooltip);
++
++ }
++
++ /**
++ * FIXME: Should not be here
++ *
++ * @param paintable
++ * @return
++ */
++ @Deprecated
++ public boolean hasEventListeners(VPaintableWidget paintable,
++ String eventIdentifier) {
++ return getComponentDetail(paintable).hasEventListeners(eventIdentifier);
++ }
++
++ /**
++ * Tests if the widget is the root widget of a VPaintableWidget.
++ *
++ * @param widget
++ * The widget to test
++ * @return true if the widget is the root widget of a VPaintableWidget,
++ * false otherwise
++ */
++ public boolean isPaintable(Widget w) {
++ return getPid(w) != null;
++ }
++
++}
--- /dev/null
- package com.vaadin.terminal.gwt.client.ui;\r
- \r
- import java.util.HashSet;\r
- import java.util.Iterator;\r
- \r
- import com.google.gwt.core.client.GWT;\r
- import com.google.gwt.event.dom.client.DomEvent.Type;\r
- import com.google.gwt.event.shared.EventHandler;\r
- import com.google.gwt.event.shared.HandlerRegistration;\r
- import com.google.gwt.user.client.Element;\r
- import com.google.gwt.user.client.ui.Widget;\r
- import com.vaadin.terminal.gwt.client.ApplicationConnection;\r
- import com.vaadin.terminal.gwt.client.EventId;\r
- import com.vaadin.terminal.gwt.client.UIDL;\r
- import com.vaadin.terminal.gwt.client.VPaintableWidget;\r
- import com.vaadin.terminal.gwt.client.ui.VAbsoluteLayout.AbsoluteWrapper;\r
- \r
- public class VAbsoluteLayoutPaintable extends VAbstractPaintableWidgetContainer {\r
- \r
- private LayoutClickEventHandler clickEventHandler = new LayoutClickEventHandler(\r
- this, EventId.LAYOUT_CLICK) {\r
- \r
- @Override\r
- protected VPaintableWidget getChildComponent(Element element) {\r
- return getWidgetForPaintable().getComponent(element);\r
- }\r
- \r
- @Override\r
- protected <H extends EventHandler> HandlerRegistration registerHandler(\r
- H handler, Type<H> type) {\r
- return getWidgetForPaintable().addDomHandler(handler, type);\r
- }\r
- };\r
- \r
- public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {\r
- getWidgetForPaintable().rendering = true;\r
- getWidgetForPaintable().client = client;\r
- // TODO margin handling\r
- if (client.updateComponent(this, uidl, true)) {\r
- getWidgetForPaintable().rendering = false;\r
- return;\r
- }\r
- \r
- clickEventHandler.handleEventHandlerRegistration(client);\r
- \r
- HashSet<String> unrenderedPids = new HashSet<String>(\r
- getWidgetForPaintable().pidToComponentWrappper.keySet());\r
- \r
- for (Iterator<Object> childIterator = uidl.getChildIterator(); childIterator\r
- .hasNext();) {\r
- UIDL cc = (UIDL) childIterator.next();\r
- if (cc.getTag().equals("cc")) {\r
- UIDL componentUIDL = cc.getChildUIDL(0);\r
- unrenderedPids.remove(componentUIDL.getId());\r
- getWidgetForPaintable().getWrapper(client, componentUIDL)\r
- .updateFromUIDL(cc);\r
- }\r
- }\r
- \r
- for (String pid : unrenderedPids) {\r
- AbsoluteWrapper absoluteWrapper = getWidgetForPaintable().pidToComponentWrappper\r
- .get(pid);\r
- getWidgetForPaintable().pidToComponentWrappper.remove(pid);\r
- absoluteWrapper.destroy();\r
- }\r
- getWidgetForPaintable().rendering = false;\r
- }\r
- \r
- public void updateCaption(VPaintableWidget component, UIDL uidl) {\r
- AbsoluteWrapper parent2 = (AbsoluteWrapper) (component\r
- .getWidgetForPaintable()).getParent();\r
- parent2.updateCaption(uidl);\r
- }\r
- \r
- @Override\r
- protected Widget createWidget() {\r
- return GWT.create(VAbsoluteLayout.class);\r
- }\r
- \r
- @Override\r
- public VAbsoluteLayout getWidgetForPaintable() {\r
- return (VAbsoluteLayout) super.getWidgetForPaintable();\r
- }\r
- }\r
++package com.vaadin.terminal.gwt.client.ui;
++
++import java.util.HashSet;
++import java.util.Iterator;
++
++import com.google.gwt.core.client.GWT;
++import com.google.gwt.event.dom.client.DomEvent.Type;
++import com.google.gwt.event.shared.EventHandler;
++import com.google.gwt.event.shared.HandlerRegistration;
++import com.google.gwt.user.client.Element;
++import com.google.gwt.user.client.ui.Widget;
++import com.vaadin.terminal.gwt.client.ApplicationConnection;
++import com.vaadin.terminal.gwt.client.EventId;
++import com.vaadin.terminal.gwt.client.UIDL;
++import com.vaadin.terminal.gwt.client.VPaintableWidget;
++import com.vaadin.terminal.gwt.client.ui.VAbsoluteLayout.AbsoluteWrapper;
++
++public class VAbsoluteLayoutPaintable extends VAbstractPaintableWidgetContainer {
++
++ private LayoutClickEventHandler clickEventHandler = new LayoutClickEventHandler(
++ this, EventId.LAYOUT_CLICK) {
++
++ @Override
++ protected VPaintableWidget getChildComponent(Element element) {
++ return getWidgetForPaintable().getComponent(element);
++ }
++
++ @Override
++ protected <H extends EventHandler> HandlerRegistration registerHandler(
++ H handler, Type<H> type) {
++ return getWidgetForPaintable().addDomHandler(handler, type);
++ }
++ };
++
++ public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {
++ getWidgetForPaintable().rendering = true;
++ getWidgetForPaintable().client = client;
++ // TODO margin handling
++ if (client.updateComponent(this, uidl, true)) {
++ getWidgetForPaintable().rendering = false;
++ return;
++ }
++
++ clickEventHandler.handleEventHandlerRegistration(client);
++
++ HashSet<String> unrenderedPids = new HashSet<String>(
++ getWidgetForPaintable().pidToComponentWrappper.keySet());
++
++ for (Iterator<Object> childIterator = uidl.getChildIterator(); childIterator
++ .hasNext();) {
++ UIDL cc = (UIDL) childIterator.next();
++ if (cc.getTag().equals("cc")) {
++ UIDL componentUIDL = cc.getChildUIDL(0);
++ unrenderedPids.remove(componentUIDL.getId());
++ getWidgetForPaintable().getWrapper(client, componentUIDL)
++ .updateFromUIDL(cc);
++ }
++ }
++
++ for (String pid : unrenderedPids) {
++ AbsoluteWrapper absoluteWrapper = getWidgetForPaintable().pidToComponentWrappper
++ .get(pid);
++ getWidgetForPaintable().pidToComponentWrappper.remove(pid);
++ absoluteWrapper.destroy();
++ }
++ getWidgetForPaintable().rendering = false;
++ }
++
++ public void updateCaption(VPaintableWidget component, UIDL uidl) {
++ AbsoluteWrapper parent2 = (AbsoluteWrapper) (component
++ .getWidgetForPaintable()).getParent();
++ parent2.updateCaption(uidl);
++ }
++
++ @Override
++ protected Widget createWidget() {
++ return GWT.create(VAbsoluteLayout.class);
++ }
++
++ @Override
++ public VAbsoluteLayout getWidgetForPaintable() {
++ return (VAbsoluteLayout) super.getWidgetForPaintable();
++ }
++}
--- /dev/null
- /*\r
- @VaadinApache2LicenseForJavaFiles@\r
- */\r
- package com.vaadin.terminal.gwt.client.ui;\r
- \r
- import com.google.gwt.user.client.ui.Widget;\r
- import com.vaadin.terminal.gwt.client.ApplicationConnection;\r
- import com.vaadin.terminal.gwt.client.VPaintableMap;\r
- import com.vaadin.terminal.gwt.client.VPaintableWidget;\r
- import com.vaadin.terminal.gwt.client.VPaintableWidgetContainer;\r
- \r
- public abstract class VAbstractPaintableWidget implements VPaintableWidget {\r
- \r
- private Widget widget;\r
- private ApplicationConnection connection;\r
- private String id;\r
- \r
- /* State variables */\r
- private boolean enabled = true;\r
- \r
- /**\r
- * Default constructor\r
- */\r
- public VAbstractPaintableWidget() {\r
- }\r
- \r
- /**\r
- * Called after the application connection reference has been set up\r
- */\r
- public void init() {\r
- }\r
- \r
- /**\r
- * Creates and returns the widget for this VPaintableWidget. This method\r
- * should only be called once when initializing the paintable.\r
- * \r
- * @return\r
- */\r
- protected abstract Widget createWidget();\r
- \r
- /**\r
- * Returns the widget associated with this paintable. The widget returned by\r
- * this method must not changed during the life time of the paintable.\r
- * \r
- * @return The widget associated with this paintable\r
- */\r
- public Widget getWidgetForPaintable() {\r
- if (widget == null) {\r
- widget = createWidget();\r
- }\r
- \r
- return widget;\r
- }\r
- \r
- /*\r
- * (non-Javadoc)\r
- * \r
- * @see com.vaadin.terminal.gwt.client.VPaintable#getConnection()\r
- */\r
- public final ApplicationConnection getConnection() {\r
- return connection;\r
- }\r
- \r
- /*\r
- * (non-Javadoc)\r
- * \r
- * @see\r
- * com.vaadin.terminal.gwt.client.VPaintable#setConnection(com.vaadin.terminal\r
- * .gwt.client.ApplicationConnection)\r
- */\r
- public final void setConnection(ApplicationConnection connection) {\r
- this.connection = connection;\r
- }\r
- \r
- public boolean isEnabled() {\r
- return enabled;\r
- }\r
- \r
- public String getId() {\r
- return id;\r
- }\r
- \r
- public void setId(String id) {\r
- this.id = id;\r
- }\r
- \r
- public VPaintableWidgetContainer getParentPaintable() {\r
- // FIXME: Return VPaintableWidgetContainer\r
- // FIXME: Store hierarchy instead of doing lookup every time\r
- \r
- VPaintableMap paintableMap = VPaintableMap.get(getConnection());\r
- \r
- Widget w = getWidgetForPaintable();\r
- while (w != null) {\r
- w = w.getParent();\r
- if (paintableMap.isPaintable(w)) {\r
- return (VPaintableWidgetContainer) paintableMap.getPaintable(w);\r
- }\r
- }\r
- \r
- return null;\r
- }\r
- }\r
++/*
++@VaadinApache2LicenseForJavaFiles@
++ */
++package com.vaadin.terminal.gwt.client.ui;
++
++import com.google.gwt.user.client.ui.Widget;
++import com.vaadin.terminal.gwt.client.ApplicationConnection;
++import com.vaadin.terminal.gwt.client.VPaintableMap;
++import com.vaadin.terminal.gwt.client.VPaintableWidget;
++import com.vaadin.terminal.gwt.client.VPaintableWidgetContainer;
++
++public abstract class VAbstractPaintableWidget implements VPaintableWidget {
++
++ private Widget widget;
++ private ApplicationConnection connection;
++ private String id;
++
++ /* State variables */
++ private boolean enabled = true;
++
++ /**
++ * Default constructor
++ */
++ public VAbstractPaintableWidget() {
++ }
++
++ /**
++ * Called after the application connection reference has been set up
++ */
++ public void init() {
++ }
++
++ /**
++ * Creates and returns the widget for this VPaintableWidget. This method
++ * should only be called once when initializing the paintable.
++ *
++ * @return
++ */
++ protected abstract Widget createWidget();
++
++ /**
++ * Returns the widget associated with this paintable. The widget returned by
++ * this method must not changed during the life time of the paintable.
++ *
++ * @return The widget associated with this paintable
++ */
++ public Widget getWidgetForPaintable() {
++ if (widget == null) {
++ widget = createWidget();
++ }
++
++ return widget;
++ }
++
++ /*
++ * (non-Javadoc)
++ *
++ * @see com.vaadin.terminal.gwt.client.VPaintable#getConnection()
++ */
++ public final ApplicationConnection getConnection() {
++ return connection;
++ }
++
++ /*
++ * (non-Javadoc)
++ *
++ * @see
++ * com.vaadin.terminal.gwt.client.VPaintable#setConnection(com.vaadin.terminal
++ * .gwt.client.ApplicationConnection)
++ */
++ public final void setConnection(ApplicationConnection connection) {
++ this.connection = connection;
++ }
++
++ public boolean isEnabled() {
++ return enabled;
++ }
++
++ public String getId() {
++ return id;
++ }
++
++ public void setId(String id) {
++ this.id = id;
++ }
++
++ public VPaintableWidgetContainer getParentPaintable() {
++ // FIXME: Return VPaintableWidgetContainer
++ // FIXME: Store hierarchy instead of doing lookup every time
++
++ VPaintableMap paintableMap = VPaintableMap.get(getConnection());
++
++ Widget w = getWidgetForPaintable();
++ while (w != null) {
++ w = w.getParent();
++ if (paintableMap.isPaintable(w)) {
++ return (VPaintableWidgetContainer) paintableMap.getPaintable(w);
++ }
++ }
++
++ return null;
++ }
++}
--- /dev/null
- /*\r
- @VaadinApache2LicenseForJavaFiles@\r
- */\r
- package com.vaadin.terminal.gwt.client.ui;\r
- \r
- import com.vaadin.terminal.gwt.client.VPaintableWidgetContainer;\r
- \r
- public abstract class VAbstractPaintableWidgetContainer extends\r
- VAbstractPaintableWidget implements VPaintableWidgetContainer {\r
- \r
- /**\r
- * Default constructor\r
- */\r
- public VAbstractPaintableWidgetContainer() {\r
- }\r
- \r
- }\r
++/*
++@VaadinApache2LicenseForJavaFiles@
++ */
++package com.vaadin.terminal.gwt.client.ui;
++
++import com.vaadin.terminal.gwt.client.VPaintableWidgetContainer;
++
++public abstract class VAbstractPaintableWidgetContainer extends
++ VAbstractPaintableWidget implements VPaintableWidgetContainer {
++
++ /**
++ * Default constructor
++ */
++ public VAbstractPaintableWidgetContainer() {
++ }
++
++}
--- /dev/null
- package com.vaadin.terminal.gwt.client.ui;\r
- \r
- import com.google.gwt.dom.client.NativeEvent;\r
- import com.google.gwt.event.dom.client.DomEvent.Type;\r
- import com.google.gwt.event.shared.EventHandler;\r
- import com.google.gwt.event.shared.HandlerRegistration;\r
- import com.google.gwt.user.client.Element;\r
- import com.google.gwt.user.client.Event;\r
- import com.google.gwt.user.client.ui.Widget;\r
- import com.vaadin.terminal.gwt.client.ApplicationConnection;\r
- import com.vaadin.terminal.gwt.client.UIDL;\r
- import com.vaadin.terminal.gwt.client.VPaintableMap;\r
- import com.vaadin.terminal.gwt.client.VPaintableWidget;\r
- \r
- public abstract class VAbstractSplitPanelPaintable extends\r
- VAbstractPaintableWidgetContainer {\r
- \r
- public static final String SPLITTER_CLICK_EVENT_IDENTIFIER = "sp_click";\r
- \r
- public void updateCaption(VPaintableWidget component, UIDL uidl) {\r
- // TODO Implement caption handling\r
- }\r
- \r
- ClickEventHandler clickEventHandler = new ClickEventHandler(this,\r
- SPLITTER_CLICK_EVENT_IDENTIFIER) {\r
- \r
- @Override\r
- protected <H extends EventHandler> HandlerRegistration registerHandler(\r
- H handler, Type<H> type) {\r
- if ((Event.getEventsSunk(getWidgetForPaintable().splitter) & Event\r
- .getTypeInt(type.getName())) != 0) {\r
- // If we are already sinking the event for the splitter we do\r
- // not want to additionally sink it for the root element\r
- return getWidgetForPaintable().addHandler(handler, type);\r
- } else {\r
- return getWidgetForPaintable().addDomHandler(handler, type);\r
- }\r
- }\r
- \r
- @Override\r
- public void onContextMenu(\r
- com.google.gwt.event.dom.client.ContextMenuEvent event) {\r
- Element target = event.getNativeEvent().getEventTarget().cast();\r
- if (getWidgetForPaintable().splitter.isOrHasChild(target)) {\r
- super.onContextMenu(event);\r
- }\r
- };\r
- \r
- @Override\r
- protected void fireClick(NativeEvent event) {\r
- Element target = event.getEventTarget().cast();\r
- if (getWidgetForPaintable().splitter.isOrHasChild(target)) {\r
- super.fireClick(event);\r
- }\r
- }\r
- \r
- @Override\r
- protected Element getRelativeToElement() {\r
- return null;\r
- }\r
- \r
- };\r
- \r
- public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {\r
- getWidgetForPaintable().client = client;\r
- getWidgetForPaintable().id = uidl.getId();\r
- getWidgetForPaintable().rendering = true;\r
- \r
- getWidgetForPaintable().immediate = uidl.hasAttribute("immediate");\r
- \r
- if (client.updateComponent(this, uidl, true)) {\r
- getWidgetForPaintable().rendering = false;\r
- return;\r
- }\r
- getWidgetForPaintable().setEnabled(\r
- !uidl.getBooleanAttribute("disabled"));\r
- \r
- clickEventHandler.handleEventHandlerRegistration(client);\r
- if (uidl.hasAttribute("style")) {\r
- getWidgetForPaintable().componentStyleNames = uidl\r
- .getStringAttribute("style").split(" ");\r
- } else {\r
- getWidgetForPaintable().componentStyleNames = new String[0];\r
- }\r
- \r
- getWidgetForPaintable().setLocked(uidl.getBooleanAttribute("locked"));\r
- \r
- getWidgetForPaintable().setPositionReversed(\r
- uidl.getBooleanAttribute("reversed"));\r
- \r
- getWidgetForPaintable().setStylenames();\r
- \r
- getWidgetForPaintable().position = uidl.getStringAttribute("position");\r
- getWidgetForPaintable().setSplitPosition(\r
- getWidgetForPaintable().position);\r
- \r
- final VPaintableWidget newFirstChildPaintable = client\r
- .getPaintable(uidl.getChildUIDL(0));\r
- final VPaintableWidget newSecondChildPaintable = client\r
- .getPaintable(uidl.getChildUIDL(1));\r
- Widget newFirstChild = newFirstChildPaintable.getWidgetForPaintable();\r
- Widget newSecondChild = newSecondChildPaintable.getWidgetForPaintable();\r
- \r
- if (getWidgetForPaintable().firstChild != newFirstChild) {\r
- if (getWidgetForPaintable().firstChild != null) {\r
- client.unregisterPaintable(VPaintableMap.get(client)\r
- .getPaintable(getWidgetForPaintable().firstChild));\r
- }\r
- getWidgetForPaintable().setFirstWidget(newFirstChild);\r
- }\r
- if (getWidgetForPaintable().secondChild != newSecondChild) {\r
- if (getWidgetForPaintable().secondChild != null) {\r
- client.unregisterPaintable(VPaintableMap.get(client)\r
- .getPaintable(getWidgetForPaintable().secondChild));\r
- }\r
- getWidgetForPaintable().setSecondWidget(newSecondChild);\r
- }\r
- newFirstChildPaintable.updateFromUIDL(uidl.getChildUIDL(0), client);\r
- newSecondChildPaintable.updateFromUIDL(uidl.getChildUIDL(1), client);\r
- \r
- getWidgetForPaintable().renderInformation\r
- .updateSize(getWidgetForPaintable().getElement());\r
- \r
- // This is needed at least for cases like #3458 to take\r
- // appearing/disappearing scrollbars into account.\r
- client.runDescendentsLayout(getWidgetForPaintable());\r
- \r
- getWidgetForPaintable().rendering = false;\r
- \r
- }\r
- \r
- @Override\r
- public VAbstractSplitPanel getWidgetForPaintable() {\r
- return (VAbstractSplitPanel) super.getWidgetForPaintable();\r
- }\r
- \r
- @Override\r
- protected abstract VAbstractSplitPanel createWidget();\r
- \r
- }\r
++package com.vaadin.terminal.gwt.client.ui;
++
++import com.google.gwt.dom.client.NativeEvent;
++import com.google.gwt.event.dom.client.DomEvent.Type;
++import com.google.gwt.event.shared.EventHandler;
++import com.google.gwt.event.shared.HandlerRegistration;
++import com.google.gwt.user.client.Element;
++import com.google.gwt.user.client.Event;
++import com.google.gwt.user.client.ui.Widget;
++import com.vaadin.terminal.gwt.client.ApplicationConnection;
++import com.vaadin.terminal.gwt.client.UIDL;
++import com.vaadin.terminal.gwt.client.VPaintableMap;
++import com.vaadin.terminal.gwt.client.VPaintableWidget;
++
++public abstract class VAbstractSplitPanelPaintable extends
++ VAbstractPaintableWidgetContainer {
++
++ public static final String SPLITTER_CLICK_EVENT_IDENTIFIER = "sp_click";
++
++ public void updateCaption(VPaintableWidget component, UIDL uidl) {
++ // TODO Implement caption handling
++ }
++
++ ClickEventHandler clickEventHandler = new ClickEventHandler(this,
++ SPLITTER_CLICK_EVENT_IDENTIFIER) {
++
++ @Override
++ protected <H extends EventHandler> HandlerRegistration registerHandler(
++ H handler, Type<H> type) {
++ if ((Event.getEventsSunk(getWidgetForPaintable().splitter) & Event
++ .getTypeInt(type.getName())) != 0) {
++ // If we are already sinking the event for the splitter we do
++ // not want to additionally sink it for the root element
++ return getWidgetForPaintable().addHandler(handler, type);
++ } else {
++ return getWidgetForPaintable().addDomHandler(handler, type);
++ }
++ }
++
++ @Override
++ public void onContextMenu(
++ com.google.gwt.event.dom.client.ContextMenuEvent event) {
++ Element target = event.getNativeEvent().getEventTarget().cast();
++ if (getWidgetForPaintable().splitter.isOrHasChild(target)) {
++ super.onContextMenu(event);
++ }
++ };
++
++ @Override
++ protected void fireClick(NativeEvent event) {
++ Element target = event.getEventTarget().cast();
++ if (getWidgetForPaintable().splitter.isOrHasChild(target)) {
++ super.fireClick(event);
++ }
++ }
++
++ @Override
++ protected Element getRelativeToElement() {
++ return null;
++ }
++
++ };
++
++ public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {
++ getWidgetForPaintable().client = client;
++ getWidgetForPaintable().id = uidl.getId();
++ getWidgetForPaintable().rendering = true;
++
++ getWidgetForPaintable().immediate = uidl.hasAttribute("immediate");
++
++ if (client.updateComponent(this, uidl, true)) {
++ getWidgetForPaintable().rendering = false;
++ return;
++ }
++ getWidgetForPaintable().setEnabled(
++ !uidl.getBooleanAttribute("disabled"));
++
++ clickEventHandler.handleEventHandlerRegistration(client);
++ if (uidl.hasAttribute("style")) {
++ getWidgetForPaintable().componentStyleNames = uidl
++ .getStringAttribute("style").split(" ");
++ } else {
++ getWidgetForPaintable().componentStyleNames = new String[0];
++ }
++
++ getWidgetForPaintable().setLocked(uidl.getBooleanAttribute("locked"));
++
++ getWidgetForPaintable().setPositionReversed(
++ uidl.getBooleanAttribute("reversed"));
++
++ getWidgetForPaintable().setStylenames();
++
++ getWidgetForPaintable().position = uidl.getStringAttribute("position");
++ getWidgetForPaintable().setSplitPosition(
++ getWidgetForPaintable().position);
++
++ final VPaintableWidget newFirstChildPaintable = client
++ .getPaintable(uidl.getChildUIDL(0));
++ final VPaintableWidget newSecondChildPaintable = client
++ .getPaintable(uidl.getChildUIDL(1));
++ Widget newFirstChild = newFirstChildPaintable.getWidgetForPaintable();
++ Widget newSecondChild = newSecondChildPaintable.getWidgetForPaintable();
++
++ if (getWidgetForPaintable().firstChild != newFirstChild) {
++ if (getWidgetForPaintable().firstChild != null) {
++ client.unregisterPaintable(VPaintableMap.get(client)
++ .getPaintable(getWidgetForPaintable().firstChild));
++ }
++ getWidgetForPaintable().setFirstWidget(newFirstChild);
++ }
++ if (getWidgetForPaintable().secondChild != newSecondChild) {
++ if (getWidgetForPaintable().secondChild != null) {
++ client.unregisterPaintable(VPaintableMap.get(client)
++ .getPaintable(getWidgetForPaintable().secondChild));
++ }
++ getWidgetForPaintable().setSecondWidget(newSecondChild);
++ }
++ newFirstChildPaintable.updateFromUIDL(uidl.getChildUIDL(0), client);
++ newSecondChildPaintable.updateFromUIDL(uidl.getChildUIDL(1), client);
++
++ getWidgetForPaintable().renderInformation
++ .updateSize(getWidgetForPaintable().getElement());
++
++ // This is needed at least for cases like #3458 to take
++ // appearing/disappearing scrollbars into account.
++ client.runDescendentsLayout(getWidgetForPaintable());
++
++ getWidgetForPaintable().rendering = false;
++
++ }
++
++ @Override
++ public VAbstractSplitPanel getWidgetForPaintable() {
++ return (VAbstractSplitPanel) super.getWidgetForPaintable();
++ }
++
++ @Override
++ protected abstract VAbstractSplitPanel createWidget();
++
++}
--- /dev/null
- package com.vaadin.terminal.gwt.client.ui;\r
- \r
- import java.util.Iterator;\r
- \r
- import com.google.gwt.core.client.GWT;\r
- import com.google.gwt.user.client.ui.Widget;\r
- import com.vaadin.terminal.gwt.client.ApplicationConnection;\r
- import com.vaadin.terminal.gwt.client.UIDL;\r
- import com.vaadin.terminal.gwt.client.VPaintableWidget;\r
- import com.vaadin.terminal.gwt.client.ui.VAccordion.StackItem;\r
- \r
- public class VAccordionPaintable extends VTabsheetBasePaintable {\r
- \r
- @Override\r
- public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {\r
- getWidgetForPaintable().rendering = true;\r
- getWidgetForPaintable().selectedUIDLItemIndex = -1;\r
- super.updateFromUIDL(uidl, client);\r
- /*\r
- * Render content after all tabs have been created and we know how large\r
- * the content area is\r
- */\r
- if (getWidgetForPaintable().selectedUIDLItemIndex >= 0) {\r
- StackItem selectedItem = getWidgetForPaintable().getStackItem(\r
- getWidgetForPaintable().selectedUIDLItemIndex);\r
- UIDL selectedTabUIDL = getWidgetForPaintable().lazyUpdateMap\r
- .remove(selectedItem);\r
- getWidgetForPaintable().open(\r
- getWidgetForPaintable().selectedUIDLItemIndex);\r
- \r
- selectedItem.setContent(selectedTabUIDL);\r
- } else if (!uidl.getBooleanAttribute("cached")\r
- && getWidgetForPaintable().openTab != null) {\r
- getWidgetForPaintable().close(getWidgetForPaintable().openTab);\r
- }\r
- \r
- getWidgetForPaintable().iLayout();\r
- // finally render possible hidden tabs\r
- if (getWidgetForPaintable().lazyUpdateMap.size() > 0) {\r
- for (Iterator iterator = getWidgetForPaintable().lazyUpdateMap\r
- .keySet().iterator(); iterator.hasNext();) {\r
- StackItem item = (StackItem) iterator.next();\r
- item.setContent(getWidgetForPaintable().lazyUpdateMap.get(item));\r
- }\r
- getWidgetForPaintable().lazyUpdateMap.clear();\r
- }\r
- \r
- getWidgetForPaintable().renderInformation\r
- .updateSize(getWidgetForPaintable().getElement());\r
- \r
- getWidgetForPaintable().rendering = false;\r
- }\r
- \r
- @Override\r
- public VAccordion getWidgetForPaintable() {\r
- return (VAccordion) super.getWidgetForPaintable();\r
- }\r
- \r
- @Override\r
- protected Widget createWidget() {\r
- return GWT.create(VAccordion.class);\r
- }\r
- \r
- public void updateCaption(VPaintableWidget component, UIDL uidl) {\r
- /* Accordion does not render its children's captions */\r
- }\r
- \r
- }\r
++package com.vaadin.terminal.gwt.client.ui;
++
++import java.util.Iterator;
++
++import com.google.gwt.core.client.GWT;
++import com.google.gwt.user.client.ui.Widget;
++import com.vaadin.terminal.gwt.client.ApplicationConnection;
++import com.vaadin.terminal.gwt.client.UIDL;
++import com.vaadin.terminal.gwt.client.VPaintableWidget;
++import com.vaadin.terminal.gwt.client.ui.VAccordion.StackItem;
++
++public class VAccordionPaintable extends VTabsheetBasePaintable {
++
++ @Override
++ public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {
++ getWidgetForPaintable().rendering = true;
++ getWidgetForPaintable().selectedUIDLItemIndex = -1;
++ super.updateFromUIDL(uidl, client);
++ /*
++ * Render content after all tabs have been created and we know how large
++ * the content area is
++ */
++ if (getWidgetForPaintable().selectedUIDLItemIndex >= 0) {
++ StackItem selectedItem = getWidgetForPaintable().getStackItem(
++ getWidgetForPaintable().selectedUIDLItemIndex);
++ UIDL selectedTabUIDL = getWidgetForPaintable().lazyUpdateMap
++ .remove(selectedItem);
++ getWidgetForPaintable().open(
++ getWidgetForPaintable().selectedUIDLItemIndex);
++
++ selectedItem.setContent(selectedTabUIDL);
++ } else if (!uidl.getBooleanAttribute("cached")
++ && getWidgetForPaintable().openTab != null) {
++ getWidgetForPaintable().close(getWidgetForPaintable().openTab);
++ }
++
++ getWidgetForPaintable().iLayout();
++ // finally render possible hidden tabs
++ if (getWidgetForPaintable().lazyUpdateMap.size() > 0) {
++ for (Iterator iterator = getWidgetForPaintable().lazyUpdateMap
++ .keySet().iterator(); iterator.hasNext();) {
++ StackItem item = (StackItem) iterator.next();
++ item.setContent(getWidgetForPaintable().lazyUpdateMap.get(item));
++ }
++ getWidgetForPaintable().lazyUpdateMap.clear();
++ }
++
++ getWidgetForPaintable().renderInformation
++ .updateSize(getWidgetForPaintable().getElement());
++
++ getWidgetForPaintable().rendering = false;
++ }
++
++ @Override
++ public VAccordion getWidgetForPaintable() {
++ return (VAccordion) super.getWidgetForPaintable();
++ }
++
++ @Override
++ protected Widget createWidget() {
++ return GWT.create(VAccordion.class);
++ }
++
++ public void updateCaption(VPaintableWidget component, UIDL uidl) {
++ /* Accordion does not render its children's captions */
++ }
++
++}
--- /dev/null
- package com.vaadin.terminal.gwt.client.ui;\r
- \r
- import com.google.gwt.core.client.GWT;\r
- import com.google.gwt.dom.client.Style;\r
- import com.google.gwt.dom.client.Style.Unit;\r
- import com.google.gwt.user.client.ui.Widget;\r
- import com.vaadin.terminal.gwt.client.ApplicationConnection;\r
- import com.vaadin.terminal.gwt.client.BrowserInfo;\r
- import com.vaadin.terminal.gwt.client.UIDL;\r
- \r
- public class VAudioPaintable extends VMediaBasePaintable {\r
- \r
- @Override\r
- public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {\r
- if (client.updateComponent(this, uidl, true)) {\r
- return;\r
- }\r
- super.updateFromUIDL(uidl, client);\r
- Style style = getWidgetForPaintable().getElement().getStyle();\r
- \r
- // Make sure that the controls are not clipped if visible.\r
- if (shouldShowControls(uidl)\r
- && (style.getHeight() == null || "".equals(style.getHeight()))) {\r
- if (BrowserInfo.get().isChrome()) {\r
- style.setHeight(32, Unit.PX);\r
- } else {\r
- style.setHeight(25, Unit.PX);\r
- }\r
- }\r
- }\r
- \r
- @Override\r
- protected Widget createWidget() {\r
- return GWT.create(VAudio.class);\r
- }\r
- \r
- }\r
++package com.vaadin.terminal.gwt.client.ui;
++
++import com.google.gwt.core.client.GWT;
++import com.google.gwt.dom.client.Style;
++import com.google.gwt.dom.client.Style.Unit;
++import com.google.gwt.user.client.ui.Widget;
++import com.vaadin.terminal.gwt.client.ApplicationConnection;
++import com.vaadin.terminal.gwt.client.BrowserInfo;
++import com.vaadin.terminal.gwt.client.UIDL;
++
++public class VAudioPaintable extends VMediaBasePaintable {
++
++ @Override
++ public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {
++ if (client.updateComponent(this, uidl, true)) {
++ return;
++ }
++ super.updateFromUIDL(uidl, client);
++ Style style = getWidgetForPaintable().getElement().getStyle();
++
++ // Make sure that the controls are not clipped if visible.
++ if (shouldShowControls(uidl)
++ && (style.getHeight() == null || "".equals(style.getHeight()))) {
++ if (BrowserInfo.get().isChrome()) {
++ style.setHeight(32, Unit.PX);
++ } else {
++ style.setHeight(25, Unit.PX);
++ }
++ }
++ }
++
++ @Override
++ protected Widget createWidget() {
++ return GWT.create(VAudio.class);
++ }
++
++}
- /*\r
- @VaadinApache2LicenseForJavaFiles@\r
- */\r
- \r
- package com.vaadin.terminal.gwt.client.ui;\r
- \r
- import java.util.Date;\r
- import java.util.Iterator;\r
- \r
- import com.google.gwt.dom.client.Node;\r
- import com.google.gwt.event.dom.client.BlurEvent;\r
- import com.google.gwt.event.dom.client.BlurHandler;\r
- import com.google.gwt.event.dom.client.ChangeEvent;\r
- import com.google.gwt.event.dom.client.ChangeHandler;\r
- import com.google.gwt.event.dom.client.ClickEvent;\r
- import com.google.gwt.event.dom.client.ClickHandler;\r
- import com.google.gwt.event.dom.client.DomEvent;\r
- import com.google.gwt.event.dom.client.FocusEvent;\r
- import com.google.gwt.event.dom.client.FocusHandler;\r
- import com.google.gwt.event.dom.client.KeyCodes;\r
- import com.google.gwt.event.dom.client.KeyDownEvent;\r
- import com.google.gwt.event.dom.client.KeyDownHandler;\r
- import com.google.gwt.event.dom.client.KeyPressEvent;\r
- import com.google.gwt.event.dom.client.KeyPressHandler;\r
- import com.google.gwt.event.dom.client.MouseDownEvent;\r
- import com.google.gwt.event.dom.client.MouseDownHandler;\r
- import com.google.gwt.event.dom.client.MouseOutEvent;\r
- import com.google.gwt.event.dom.client.MouseOutHandler;\r
- import com.google.gwt.event.dom.client.MouseUpEvent;\r
- import com.google.gwt.event.dom.client.MouseUpHandler;\r
- import com.google.gwt.user.client.Element;\r
- import com.google.gwt.user.client.Timer;\r
- import com.google.gwt.user.client.ui.Button;\r
- import com.google.gwt.user.client.ui.FlexTable;\r
- import com.google.gwt.user.client.ui.FlowPanel;\r
- import com.google.gwt.user.client.ui.InlineHTML;\r
- import com.google.gwt.user.client.ui.ListBox;\r
- import com.google.gwt.user.client.ui.Widget;\r
- import com.vaadin.terminal.gwt.client.BrowserInfo;\r
- import com.vaadin.terminal.gwt.client.DateTimeService;\r
- import com.vaadin.terminal.gwt.client.Util;\r
- import com.vaadin.terminal.gwt.client.VConsole;\r
- import com.vaadin.terminal.gwt.client.ui.label.VLabel;\r
- \r
- @SuppressWarnings("deprecation")\r
- public class VCalendarPanel extends FocusableFlexTable implements\r
- KeyDownHandler, KeyPressHandler, MouseOutHandler, MouseDownHandler,\r
- MouseUpHandler, BlurHandler, FocusHandler, SubPartAware {\r
- \r
- public interface SubmitListener {\r
- \r
- /**\r
- * Called when calendar user triggers a submitting operation in calendar\r
- * panel. Eg. clicking on day or hitting enter.\r
- */\r
- void onSubmit();\r
- \r
- /**\r
- * On eg. ESC key.\r
- */\r
- void onCancel();\r
- }\r
- \r
- /**\r
- * Blur listener that listens to blur event from the panel\r
- */\r
- public interface FocusOutListener {\r
- /**\r
- * @return true if the calendar panel is not used after focus moves out\r
- */\r
- boolean onFocusOut(DomEvent<?> event);\r
- }\r
- \r
- /**\r
- * FocusChangeListener is notified when the panel changes its _focused_\r
- * value.\r
- */\r
- public interface FocusChangeListener {\r
- void focusChanged(Date focusedDate);\r
- }\r
- \r
- /**\r
- * Dispatches an event when the panel when time is changed\r
- */\r
- public interface TimeChangeListener {\r
- \r
- void changed(int hour, int min, int sec, int msec);\r
- }\r
- \r
- /**\r
- * Represents a Date button in the calendar\r
- */\r
- private class VEventButton extends Button {\r
- public VEventButton() {\r
- addMouseDownHandler(VCalendarPanel.this);\r
- addMouseOutHandler(VCalendarPanel.this);\r
- addMouseUpHandler(VCalendarPanel.this);\r
- }\r
- }\r
- \r
- private static final String CN_FOCUSED = "focused";\r
- \r
- private static final String CN_TODAY = "today";\r
- \r
- private static final String CN_SELECTED = "selected";\r
- \r
- private static final String CN_OFFMONTH = "offmonth";\r
- \r
- /**\r
- * Represents a click handler for when a user selects a value by using the\r
- * mouse\r
- */\r
- private ClickHandler dayClickHandler = new ClickHandler() {\r
- /*\r
- * (non-Javadoc)\r
- * \r
- * @see\r
- * com.google.gwt.event.dom.client.ClickHandler#onClick(com.google.gwt\r
- * .event.dom.client.ClickEvent)\r
- */\r
- public void onClick(ClickEvent event) {\r
- Day day = (Day) event.getSource();\r
- focusDay(day.getDate());\r
- selectFocused();\r
- onSubmit();\r
- }\r
- };\r
- \r
- private VEventButton prevYear;\r
- \r
- private VEventButton nextYear;\r
- \r
- private VEventButton prevMonth;\r
- \r
- private VEventButton nextMonth;\r
- \r
- private VTime time;\r
- \r
- private FlexTable days = new FlexTable();\r
- \r
- private int resolution = VDateField.RESOLUTION_YEAR;\r
- \r
- private int focusedRow;\r
- \r
- private Timer mouseTimer;\r
- \r
- private Date value;\r
- \r
- private boolean enabled = true;\r
- \r
- private boolean readonly = false;\r
- \r
- private DateTimeService dateTimeService;\r
- \r
- private boolean showISOWeekNumbers;\r
- \r
- private Date displayedMonth;\r
- \r
- private Date focusedDate;\r
- \r
- private Day selectedDay;\r
- \r
- private Day focusedDay;\r
- \r
- private FocusOutListener focusOutListener;\r
- \r
- private SubmitListener submitListener;\r
- \r
- private FocusChangeListener focusChangeListener;\r
- \r
- private TimeChangeListener timeChangeListener;\r
- \r
- private boolean hasFocus = false;\r
- \r
- public VCalendarPanel() {\r
- \r
- setStyleName(VDateField.CLASSNAME + "-calendarpanel");\r
- \r
- /*\r
- * Firefox auto-repeat works correctly only if we use a key press\r
- * handler, other browsers handle it correctly when using a key down\r
- * handler\r
- */\r
- if (BrowserInfo.get().isGecko()) {\r
- addKeyPressHandler(this);\r
- } else {\r
- addKeyDownHandler(this);\r
- }\r
- addFocusHandler(this);\r
- addBlurHandler(this);\r
- \r
- }\r
- \r
- /**\r
- * Sets the focus to given date in the current view. Used when moving in the\r
- * calendar with the keyboard.\r
- * \r
- * @param date\r
- * A Date representing the day of month to be focused. Must be\r
- * one of the days currently visible.\r
- */\r
- private void focusDay(Date date) {\r
- // Only used when calender body is present\r
- if (resolution > VDateField.RESOLUTION_MONTH) {\r
- if (focusedDay != null) {\r
- focusedDay.removeStyleDependentName(CN_FOCUSED);\r
- }\r
- \r
- if (date != null && focusedDate != null) {\r
- focusedDate.setTime(date.getTime());\r
- int rowCount = days.getRowCount();\r
- for (int i = 0; i < rowCount; i++) {\r
- int cellCount = days.getCellCount(i);\r
- for (int j = 0; j < cellCount; j++) {\r
- Widget widget = days.getWidget(i, j);\r
- if (widget != null && widget instanceof Day) {\r
- Day curday = (Day) widget;\r
- if (curday.getDate().equals(date)) {\r
- curday.addStyleDependentName(CN_FOCUSED);\r
- focusedDay = curday;\r
- focusedRow = i;\r
- return;\r
- }\r
- }\r
- }\r
- }\r
- }\r
- }\r
- }\r
- \r
- /**\r
- * Sets the selection highlight to a given day in the current view\r
- * \r
- * @param date\r
- * A Date representing the day of month to be selected. Must be\r
- * one of the days currently visible.\r
- * \r
- */\r
- private void selectDate(Date date) {\r
- if (selectedDay != null) {\r
- selectedDay.removeStyleDependentName(CN_SELECTED);\r
- }\r
- \r
- int rowCount = days.getRowCount();\r
- for (int i = 0; i < rowCount; i++) {\r
- int cellCount = days.getCellCount(i);\r
- for (int j = 0; j < cellCount; j++) {\r
- Widget widget = days.getWidget(i, j);\r
- if (widget != null && widget instanceof Day) {\r
- Day curday = (Day) widget;\r
- if (curday.getDate().equals(date)) {\r
- curday.addStyleDependentName(CN_SELECTED);\r
- selectedDay = curday;\r
- return;\r
- }\r
- }\r
- }\r
- }\r
- }\r
- \r
- /**\r
- * Updates year, month, day from focusedDate to value\r
- */\r
- private void selectFocused() {\r
- if (focusedDate != null) {\r
- if (value == null) {\r
- // No previously selected value (set to null on server side).\r
- // Create a new date using current date and time\r
- value = new Date();\r
- }\r
- /*\r
- * #5594 set Date (day) to 1 in order to prevent any kind of\r
- * wrapping of months when later setting the month. (e.g. 31 ->\r
- * month with 30 days -> wraps to the 1st of the following month,\r
- * e.g. 31st of May -> 31st of April = 1st of May)\r
- */\r
- value.setDate(1);\r
- if (value.getYear() != focusedDate.getYear()) {\r
- value.setYear(focusedDate.getYear());\r
- }\r
- if (value.getMonth() != focusedDate.getMonth()) {\r
- value.setMonth(focusedDate.getMonth());\r
- }\r
- if (value.getDate() != focusedDate.getDate()) {\r
- }\r
- // We always need to set the date, even if it hasn't changed, since\r
- // it was forced to 1 above.\r
- value.setDate(focusedDate.getDate());\r
- \r
- selectDate(focusedDate);\r
- } else {\r
- VConsole.log("Trying to select a the focused date which is NULL!");\r
- }\r
- }\r
- \r
- protected boolean onValueChange() {\r
- return false;\r
- }\r
- \r
- public int getResolution() {\r
- return resolution;\r
- }\r
- \r
- public void setResolution(int resolution) {\r
- this.resolution = resolution;\r
- if (time != null) {\r
- time.removeFromParent();\r
- time = null;\r
- }\r
- }\r
- \r
- private boolean isReadonly() {\r
- return readonly;\r
- }\r
- \r
- private boolean isEnabled() {\r
- return enabled;\r
- }\r
- \r
- private void clearCalendarBody(boolean remove) {\r
- if (!remove) {\r
- // Leave the cells in place but clear their contents\r
- \r
- // This has the side effect of ensuring that the calendar always\r
- // contain 7 rows.\r
- for (int row = 1; row < 7; row++) {\r
- for (int col = 0; col < 8; col++) {\r
- days.setHTML(row, col, " ");\r
- }\r
- }\r
- } else if (getRowCount() > 1) {\r
- removeRow(1);\r
- days.clear();\r
- }\r
- }\r
- \r
- /**\r
- * Builds the top buttons and current month and year header.\r
- * \r
- * @param needsMonth\r
- * Should the month buttons be visible?\r
- */\r
- private void buildCalendarHeader(boolean needsMonth) {\r
- \r
- getRowFormatter().addStyleName(0,\r
- VDateField.CLASSNAME + "-calendarpanel-header");\r
- \r
- if (prevMonth == null && needsMonth) {\r
- prevMonth = new VEventButton();\r
- prevMonth.setHTML("‹");\r
- prevMonth.setStyleName("v-button-prevmonth");\r
- prevMonth.setTabIndex(-1);\r
- nextMonth = new VEventButton();\r
- nextMonth.setHTML("›");\r
- nextMonth.setStyleName("v-button-nextmonth");\r
- nextMonth.setTabIndex(-1);\r
- getFlexCellFormatter().setStyleName(0, 3,\r
- VDateField.CLASSNAME + "-calendarpanel-nextmonth");\r
- getFlexCellFormatter().setStyleName(0, 1,\r
- VDateField.CLASSNAME + "-calendarpanel-prevmonth");\r
- \r
- setWidget(0, 3, nextMonth);\r
- setWidget(0, 1, prevMonth);\r
- } else if (prevMonth != null && !needsMonth) {\r
- // Remove month traverse buttons\r
- remove(prevMonth);\r
- remove(nextMonth);\r
- prevMonth = null;\r
- nextMonth = null;\r
- }\r
- \r
- if (prevYear == null) {\r
- prevYear = new VEventButton();\r
- prevYear.setHTML("«");\r
- prevYear.setStyleName("v-button-prevyear");\r
- prevYear.setTabIndex(-1);\r
- nextYear = new VEventButton();\r
- nextYear.setHTML("»");\r
- nextYear.setStyleName("v-button-nextyear");\r
- nextYear.setTabIndex(-1);\r
- setWidget(0, 0, prevYear);\r
- setWidget(0, 4, nextYear);\r
- getFlexCellFormatter().setStyleName(0, 0,\r
- VDateField.CLASSNAME + "-calendarpanel-prevyear");\r
- getFlexCellFormatter().setStyleName(0, 4,\r
- VDateField.CLASSNAME + "-calendarpanel-nextyear");\r
- }\r
- \r
- final String monthName = needsMonth ? getDateTimeService().getMonth(\r
- focusedDate.getMonth()) : "";\r
- final int year = focusedDate.getYear() + 1900;\r
- getFlexCellFormatter().setStyleName(0, 2,\r
- VDateField.CLASSNAME + "-calendarpanel-month");\r
- setHTML(0, 2, "<span class=\"" + VDateField.CLASSNAME\r
- + "-calendarpanel-month\">" + monthName + " " + year\r
- + "</span>");\r
- }\r
- \r
- private DateTimeService getDateTimeService() {\r
- return dateTimeService;\r
- }\r
- \r
- public void setDateTimeService(DateTimeService dateTimeService) {\r
- this.dateTimeService = dateTimeService;\r
- }\r
- \r
- /**\r
- * Returns whether ISO 8601 week numbers should be shown in the value\r
- * selector or not. ISO 8601 defines that a week always starts with a Monday\r
- * so the week numbers are only shown if this is the case.\r
- * \r
- * @return true if week number should be shown, false otherwise\r
- */\r
- public boolean isShowISOWeekNumbers() {\r
- return showISOWeekNumbers;\r
- }\r
- \r
- public void setShowISOWeekNumbers(boolean showISOWeekNumbers) {\r
- this.showISOWeekNumbers = showISOWeekNumbers;\r
- }\r
- \r
- /**\r
- * Builds the day and time selectors of the calendar.\r
- */\r
- private void buildCalendarBody() {\r
- \r
- final int weekColumn = 0;\r
- final int firstWeekdayColumn = 1;\r
- final int headerRow = 0;\r
- \r
- setWidget(1, 0, days);\r
- setCellPadding(0);\r
- setCellSpacing(0);\r
- getFlexCellFormatter().setColSpan(1, 0, 5);\r
- getFlexCellFormatter().setStyleName(1, 0,\r
- VDateField.CLASSNAME + "-calendarpanel-body");\r
- \r
- days.getFlexCellFormatter().setStyleName(headerRow, weekColumn,\r
- "v-week");\r
- days.setHTML(headerRow, weekColumn, "<strong></strong>");\r
- // Hide the week column if week numbers are not to be displayed.\r
- days.getFlexCellFormatter().setVisible(headerRow, weekColumn,\r
- isShowISOWeekNumbers());\r
- \r
- days.getRowFormatter().setStyleName(headerRow,\r
- VDateField.CLASSNAME + "-calendarpanel-weekdays");\r
- \r
- if (isShowISOWeekNumbers()) {\r
- days.getFlexCellFormatter().setStyleName(headerRow, weekColumn,\r
- "v-first");\r
- days.getFlexCellFormatter().setStyleName(headerRow,\r
- firstWeekdayColumn, "");\r
- days.getRowFormatter().addStyleName(headerRow,\r
- VDateField.CLASSNAME + "-calendarpanel-weeknumbers");\r
- } else {\r
- days.getFlexCellFormatter().setStyleName(headerRow, weekColumn, "");\r
- days.getFlexCellFormatter().setStyleName(headerRow,\r
- firstWeekdayColumn, "v-first");\r
- }\r
- \r
- days.getFlexCellFormatter().setStyleName(headerRow,\r
- firstWeekdayColumn + 6, "v-last");\r
- \r
- // Print weekday names\r
- final int firstDay = getDateTimeService().getFirstDayOfWeek();\r
- for (int i = 0; i < 7; i++) {\r
- int day = i + firstDay;\r
- if (day > 6) {\r
- day = 0;\r
- }\r
- if (getResolution() > VDateField.RESOLUTION_MONTH) {\r
- days.setHTML(headerRow, firstWeekdayColumn + i, "<strong>"\r
- + getDateTimeService().getShortDay(day) + "</strong>");\r
- } else {\r
- days.setHTML(headerRow, firstWeekdayColumn + i, "");\r
- }\r
- }\r
- \r
- // today must have zeroed hours, minutes, seconds, and milliseconds\r
- final Date tmp = new Date();\r
- final Date today = new Date(tmp.getYear(), tmp.getMonth(),\r
- tmp.getDate());\r
- \r
- final int startWeekDay = getDateTimeService().getStartWeekDay(\r
- focusedDate);\r
- final Date curr = (Date) focusedDate.clone();\r
- // Start from the first day of the week that at least partially belongs\r
- // to the current month\r
- curr.setDate(-startWeekDay);\r
- \r
- // No month has more than 6 weeks so 6 is a safe maximum for rows.\r
- for (int weekOfMonth = 1; weekOfMonth < 7; weekOfMonth++) {\r
- for (int dayOfWeek = 0; dayOfWeek < 7; dayOfWeek++) {\r
- \r
- // Actually write the day of month\r
- Day day = new Day((Date) curr.clone());\r
- \r
- if (curr.equals(value)) {\r
- day.addStyleDependentName(CN_SELECTED);\r
- selectedDay = day;\r
- }\r
- if (curr.equals(today)) {\r
- day.addStyleDependentName(CN_TODAY);\r
- }\r
- if (curr.equals(focusedDate)) {\r
- focusedDay = day;\r
- focusedRow = weekOfMonth;\r
- if (hasFocus) {\r
- day.addStyleDependentName(CN_FOCUSED);\r
- }\r
- }\r
- if (curr.getMonth() != focusedDate.getMonth()) {\r
- day.addStyleDependentName(CN_OFFMONTH);\r
- }\r
- \r
- days.setWidget(weekOfMonth, firstWeekdayColumn + dayOfWeek, day);\r
- \r
- // ISO week numbers if requested\r
- days.getCellFormatter().setVisible(weekOfMonth, weekColumn,\r
- isShowISOWeekNumbers());\r
- if (isShowISOWeekNumbers()) {\r
- final String baseCssClass = VDateField.CLASSNAME\r
- + "-calendarpanel-weeknumber";\r
- String weekCssClass = baseCssClass;\r
- \r
- int weekNumber = DateTimeService.getISOWeekNumber(curr);\r
- \r
- days.setHTML(weekOfMonth, 0, "<span class=\""\r
- + weekCssClass + "\"" + ">" + weekNumber\r
- + "</span>");\r
- }\r
- curr.setDate(curr.getDate() + 1);\r
- }\r
- }\r
- }\r
- \r
- /**\r
- * Do we need the time selector\r
- * \r
- * @return True if it is required\r
- */\r
- private boolean isTimeSelectorNeeded() {\r
- return getResolution() > VDateField.RESOLUTION_DAY;\r
- }\r
- \r
- /**\r
- * Updates the calendar and text field with the selected dates.\r
- */\r
- public void renderCalendar() {\r
- if (focusedDate == null) {\r
- focusedDate = new Date();\r
- }\r
- \r
- if (getResolution() <= VDateField.RESOLUTION_MONTH\r
- && focusChangeListener != null) {\r
- focusChangeListener.focusChanged(new Date(focusedDate.getTime()));\r
- }\r
- \r
- final boolean needsMonth = getResolution() > VDateField.RESOLUTION_YEAR;\r
- boolean needsBody = getResolution() >= VDateField.RESOLUTION_DAY;\r
- buildCalendarHeader(needsMonth);\r
- clearCalendarBody(!needsBody);\r
- if (needsBody) {\r
- buildCalendarBody();\r
- }\r
- \r
- if (isTimeSelectorNeeded() && time == null) {\r
- time = new VTime();\r
- setWidget(2, 0, time);\r
- getFlexCellFormatter().setColSpan(2, 0, 5);\r
- getFlexCellFormatter().setStyleName(2, 0,\r
- VDateField.CLASSNAME + "-calendarpanel-time");\r
- } else if (isTimeSelectorNeeded()) {\r
- time.updateTimes();\r
- } else if (time != null) {\r
- remove(time);\r
- }\r
- \r
- }\r
- \r
- /**\r
- * Selects the next month\r
- */\r
- private void focusNextMonth() {\r
- \r
- int currentMonth = focusedDate.getMonth();\r
- focusedDate.setMonth(currentMonth + 1);\r
- int requestedMonth = (currentMonth + 1) % 12;\r
- \r
- /*\r
- * If the selected value was e.g. 31.3 the new value would be 31.4 but\r
- * this value is invalid so the new value will be 1.5. This is taken\r
- * care of by decreasing the value until we have the correct month.\r
- */\r
- while (focusedDate.getMonth() != requestedMonth) {\r
- focusedDate.setDate(focusedDate.getDate() - 1);\r
- }\r
- displayedMonth.setMonth(displayedMonth.getMonth() + 1);\r
- \r
- renderCalendar();\r
- }\r
- \r
- /**\r
- * Selects the previous month\r
- */\r
- private void focusPreviousMonth() {\r
- int currentMonth = focusedDate.getMonth();\r
- focusedDate.setMonth(currentMonth - 1);\r
- \r
- /*\r
- * If the selected value was e.g. 31.12 the new value would be 31.11 but\r
- * this value is invalid so the new value will be 1.12. This is taken\r
- * care of by decreasing the value until we have the correct month.\r
- */\r
- while (focusedDate.getMonth() == currentMonth) {\r
- focusedDate.setDate(focusedDate.getDate() - 1);\r
- }\r
- displayedMonth.setMonth(displayedMonth.getMonth() - 1);\r
- \r
- renderCalendar();\r
- }\r
- \r
- /**\r
- * Selects the previous year\r
- */\r
- private void focusPreviousYear(int years) {\r
- focusedDate.setYear(focusedDate.getYear() - years);\r
- displayedMonth.setYear(displayedMonth.getYear() - years);\r
- renderCalendar();\r
- }\r
- \r
- /**\r
- * Selects the next year\r
- */\r
- private void focusNextYear(int years) {\r
- focusedDate.setYear(focusedDate.getYear() + years);\r
- displayedMonth.setYear(displayedMonth.getYear() + years);\r
- renderCalendar();\r
- }\r
- \r
- /**\r
- * Handles a user click on the component\r
- * \r
- * @param sender\r
- * The component that was clicked\r
- * @param updateVariable\r
- * Should the value field be updated\r
- * \r
- */\r
- private void processClickEvent(Widget sender) {\r
- if (!isEnabled() || isReadonly()) {\r
- return;\r
- }\r
- if (sender == prevYear) {\r
- focusPreviousYear(1);\r
- } else if (sender == nextYear) {\r
- focusNextYear(1);\r
- } else if (sender == prevMonth) {\r
- focusPreviousMonth();\r
- } else if (sender == nextMonth) {\r
- focusNextMonth();\r
- }\r
- }\r
- \r
- /*\r
- * (non-Javadoc)\r
- * \r
- * @see\r
- * com.google.gwt.event.dom.client.KeyDownHandler#onKeyDown(com.google.gwt\r
- * .event.dom.client.KeyDownEvent)\r
- */\r
- public void onKeyDown(KeyDownEvent event) {\r
- handleKeyPress(event);\r
- }\r
- \r
- /*\r
- * (non-Javadoc)\r
- * \r
- * @see\r
- * com.google.gwt.event.dom.client.KeyPressHandler#onKeyPress(com.google\r
- * .gwt.event.dom.client.KeyPressEvent)\r
- */\r
- public void onKeyPress(KeyPressEvent event) {\r
- handleKeyPress(event);\r
- }\r
- \r
- /**\r
- * Handles the keypress from both the onKeyPress event and the onKeyDown\r
- * event\r
- * \r
- * @param event\r
- * The keydown/keypress event\r
- */\r
- private void handleKeyPress(DomEvent<?> event) {\r
- if (time != null\r
- && time.getElement().isOrHasChild(\r
- (Node) event.getNativeEvent().getEventTarget().cast())) {\r
- int nativeKeyCode = event.getNativeEvent().getKeyCode();\r
- if (nativeKeyCode == getSelectKey()) {\r
- onSubmit(); // submit happens if enter key hit down on listboxes\r
- event.preventDefault();\r
- event.stopPropagation();\r
- }\r
- return;\r
- }\r
- \r
- // Check tabs\r
- int keycode = event.getNativeEvent().getKeyCode();\r
- if (keycode == KeyCodes.KEY_TAB && event.getNativeEvent().getShiftKey()) {\r
- if (onTabOut(event)) {\r
- return;\r
- }\r
- }\r
- \r
- // Handle the navigation\r
- if (handleNavigation(keycode, event.getNativeEvent().getCtrlKey()\r
- || event.getNativeEvent().getMetaKey(), event.getNativeEvent()\r
- .getShiftKey())) {\r
- event.preventDefault();\r
- }\r
- \r
- }\r
- \r
- /**\r
- * Notifies submit-listeners of a submit event\r
- */\r
- private void onSubmit() {\r
- if (getSubmitListener() != null) {\r
- getSubmitListener().onSubmit();\r
- }\r
- }\r
- \r
- /**\r
- * Notifies submit-listeners of a cancel event\r
- */\r
- private void onCancel() {\r
- if (getSubmitListener() != null) {\r
- getSubmitListener().onCancel();\r
- }\r
- }\r
- \r
- /**\r
- * Handles the keyboard navigation when the resolution is set to years.\r
- * \r
- * @param keycode\r
- * The keycode to process\r
- * @param ctrl\r
- * Is ctrl pressed?\r
- * @param shift\r
- * is shift pressed\r
- * @return Returns true if the keycode was processed, else false\r
- */\r
- protected boolean handleNavigationYearMode(int keycode, boolean ctrl,\r
- boolean shift) {\r
- \r
- // Ctrl and Shift selection not supported\r
- if (ctrl || shift) {\r
- return false;\r
- }\r
- \r
- else if (keycode == getPreviousKey()) {\r
- focusNextYear(10); // Add 10 years\r
- return true;\r
- }\r
- \r
- else if (keycode == getForwardKey()) {\r
- focusNextYear(1); // Add 1 year\r
- return true;\r
- }\r
- \r
- else if (keycode == getNextKey()) {\r
- focusPreviousYear(10); // Subtract 10 years\r
- return true;\r
- }\r
- \r
- else if (keycode == getBackwardKey()) {\r
- focusPreviousYear(1); // Subtract 1 year\r
- return true;\r
- \r
- } else if (keycode == getSelectKey()) {\r
- value = (Date) focusedDate.clone();\r
- onSubmit();\r
- return true;\r
- \r
- } else if (keycode == getResetKey()) {\r
- // Restore showing value the selected value\r
- focusedDate.setTime(value.getTime());\r
- renderCalendar();\r
- return true;\r
- \r
- } else if (keycode == getCloseKey()) {\r
- // TODO fire listener, on users responsibility??\r
- \r
- return true;\r
- }\r
- return false;\r
- }\r
- \r
- /**\r
- * Handle the keyboard navigation when the resolution is set to MONTH\r
- * \r
- * @param keycode\r
- * The keycode to handle\r
- * @param ctrl\r
- * Was the ctrl key pressed?\r
- * @param shift\r
- * Was the shift key pressed?\r
- * @return\r
- */\r
- protected boolean handleNavigationMonthMode(int keycode, boolean ctrl,\r
- boolean shift) {\r
- \r
- // Ctrl selection not supported\r
- if (ctrl) {\r
- return false;\r
- \r
- } else if (keycode == getPreviousKey()) {\r
- focusNextYear(1); // Add 1 year\r
- return true;\r
- \r
- } else if (keycode == getForwardKey()) {\r
- focusNextMonth(); // Add 1 month\r
- return true;\r
- \r
- } else if (keycode == getNextKey()) {\r
- focusPreviousYear(1); // Subtract 1 year\r
- return true;\r
- \r
- } else if (keycode == getBackwardKey()) {\r
- focusPreviousMonth(); // Subtract 1 month\r
- return true;\r
- \r
- } else if (keycode == getSelectKey()) {\r
- value = (Date) focusedDate.clone();\r
- onSubmit();\r
- return true;\r
- \r
- } else if (keycode == getResetKey()) {\r
- // Restore showing value the selected value\r
- focusedDate.setTime(value.getTime());\r
- renderCalendar();\r
- return true;\r
- \r
- } else if (keycode == getCloseKey() || keycode == KeyCodes.KEY_TAB) {\r
- \r
- // TODO fire close event\r
- \r
- return true;\r
- }\r
- \r
- return false;\r
- }\r
- \r
- /**\r
- * Handle keyboard navigation what the resolution is set to DAY\r
- * \r
- * @param keycode\r
- * The keycode to handle\r
- * @param ctrl\r
- * Was the ctrl key pressed?\r
- * @param shift\r
- * Was the shift key pressed?\r
- * @return Return true if the key press was handled by the method, else\r
- * return false.\r
- */\r
- protected boolean handleNavigationDayMode(int keycode, boolean ctrl,\r
- boolean shift) {\r
- \r
- // Ctrl key is not in use\r
- if (ctrl) {\r
- return false;\r
- }\r
- \r
- /*\r
- * Jumps to the next day.\r
- */\r
- if (keycode == getForwardKey() && !shift) {\r
- // Calculate new showing value\r
- \r
- Date newCurrentDate = (Date) focusedDate.clone();\r
- \r
- newCurrentDate.setDate(newCurrentDate.getDate() + 1);\r
- \r
- if (newCurrentDate.getMonth() == focusedDate.getMonth()) {\r
- // Month did not change, only move the selection\r
- focusDay(newCurrentDate);\r
- } else {\r
- // If the month changed we need to re-render the calendar\r
- focusedDate.setDate(focusedDate.getDate() + 1);\r
- renderCalendar();\r
- }\r
- \r
- return true;\r
- \r
- /*\r
- * Jumps to the previous day\r
- */\r
- } else if (keycode == getBackwardKey() && !shift) {\r
- // Calculate new showing value\r
- Date newCurrentDate = (Date) focusedDate.clone();\r
- newCurrentDate.setDate(newCurrentDate.getDate() - 1);\r
- \r
- if (newCurrentDate.getMonth() == focusedDate.getMonth()) {\r
- // Month did not change, only move the selection\r
- focusDay(newCurrentDate);\r
- } else {\r
- // If the month changed we need to re-render the calendar\r
- focusedDate.setDate(focusedDate.getDate() - 1);\r
- renderCalendar();\r
- }\r
- \r
- return true;\r
- \r
- /*\r
- * Jumps one week back in the calendar\r
- */\r
- } else if (keycode == getPreviousKey() && !shift) {\r
- // Calculate new showing value\r
- Date newCurrentDate = (Date) focusedDate.clone();\r
- newCurrentDate.setDate(newCurrentDate.getDate() - 7);\r
- \r
- if (newCurrentDate.getMonth() == focusedDate.getMonth()\r
- && focusedRow > 1) {\r
- // Month did not change, only move the selection\r
- focusDay(newCurrentDate);\r
- } else {\r
- // If the month changed we need to re-render the calendar\r
- focusedDate = newCurrentDate;\r
- renderCalendar();\r
- }\r
- \r
- return true;\r
- \r
- /*\r
- * Jumps one week forward in the calendar\r
- */\r
- } else if (keycode == getNextKey() && !ctrl && !shift) {\r
- // Calculate new showing value\r
- Date newCurrentDate = (Date) focusedDate.clone();\r
- newCurrentDate.setDate(newCurrentDate.getDate() + 7);\r
- \r
- if (newCurrentDate.getMonth() == focusedDate.getMonth()) {\r
- // Month did not change, only move the selection\r
- focusDay(newCurrentDate);\r
- } else {\r
- // If the month changed we need to re-render the calendar\r
- focusedDate = newCurrentDate;\r
- renderCalendar();\r
- \r
- }\r
- \r
- return true;\r
- \r
- /*\r
- * Selects the value that is chosen\r
- */\r
- } else if (keycode == getSelectKey() && !shift) {\r
- selectFocused();\r
- onSubmit(); // submit\r
- return true;\r
- } else if (keycode == getCloseKey()) {\r
- onCancel();\r
- // TODO close event\r
- \r
- return true;\r
- \r
- /*\r
- * Jumps to the next month\r
- */\r
- } else if (shift && keycode == getForwardKey()) {\r
- focusNextMonth();\r
- return true;\r
- \r
- /*\r
- * Jumps to the previous month\r
- */\r
- } else if (shift && keycode == getBackwardKey()) {\r
- focusPreviousMonth();\r
- return true;\r
- \r
- /*\r
- * Jumps to the next year\r
- */\r
- } else if (shift && keycode == getPreviousKey()) {\r
- focusNextYear(1);\r
- return true;\r
- \r
- /*\r
- * Jumps to the previous year\r
- */\r
- } else if (shift && keycode == getNextKey()) {\r
- focusPreviousYear(1);\r
- return true;\r
- \r
- /*\r
- * Resets the selection\r
- */\r
- } else if (keycode == getResetKey() && !shift) {\r
- // Restore showing value the selected value\r
- focusedDate.setTime(value.getTime());\r
- renderCalendar();\r
- return true;\r
- }\r
- \r
- return false;\r
- }\r
- \r
- /**\r
- * Handles the keyboard navigation\r
- * \r
- * @param keycode\r
- * The key code that was pressed\r
- * @param ctrl\r
- * Was the ctrl key pressed\r
- * @param shift\r
- * Was the shift key pressed\r
- * @return Return true if key press was handled by the component, else\r
- * return false\r
- */\r
- protected boolean handleNavigation(int keycode, boolean ctrl, boolean shift) {\r
- if (!isEnabled() || isReadonly()) {\r
- return false;\r
- }\r
- \r
- else if (resolution == VDateField.RESOLUTION_YEAR) {\r
- return handleNavigationYearMode(keycode, ctrl, shift);\r
- }\r
- \r
- else if (resolution == VDateField.RESOLUTION_MONTH) {\r
- return handleNavigationMonthMode(keycode, ctrl, shift);\r
- }\r
- \r
- else if (resolution == VDateField.RESOLUTION_DAY) {\r
- return handleNavigationDayMode(keycode, ctrl, shift);\r
- }\r
- \r
- else {\r
- return handleNavigationDayMode(keycode, ctrl, shift);\r
- }\r
- \r
- }\r
- \r
- /**\r
- * Returns the reset key which will reset the calendar to the previous\r
- * selection. By default this is backspace but it can be overriden to change\r
- * the key to whatever you want.\r
- * \r
- * @return\r
- */\r
- protected int getResetKey() {\r
- return KeyCodes.KEY_BACKSPACE;\r
- }\r
- \r
- /**\r
- * Returns the select key which selects the value. By default this is the\r
- * enter key but it can be changed to whatever you like by overriding this\r
- * method.\r
- * \r
- * @return\r
- */\r
- protected int getSelectKey() {\r
- return KeyCodes.KEY_ENTER;\r
- }\r
- \r
- /**\r
- * Returns the key that closes the popup window if this is a VPopopCalendar.\r
- * Else this does nothing. By default this is the Escape key but you can\r
- * change the key to whatever you want by overriding this method.\r
- * \r
- * @return\r
- */\r
- protected int getCloseKey() {\r
- return KeyCodes.KEY_ESCAPE;\r
- }\r
- \r
- /**\r
- * The key that selects the next day in the calendar. By default this is the\r
- * right arrow key but by overriding this method it can be changed to\r
- * whatever you like.\r
- * \r
- * @return\r
- */\r
- protected int getForwardKey() {\r
- return KeyCodes.KEY_RIGHT;\r
- }\r
- \r
- /**\r
- * The key that selects the previous day in the calendar. By default this is\r
- * the left arrow key but by overriding this method it can be changed to\r
- * whatever you like.\r
- * \r
- * @return\r
- */\r
- protected int getBackwardKey() {\r
- return KeyCodes.KEY_LEFT;\r
- }\r
- \r
- /**\r
- * The key that selects the next week in the calendar. By default this is\r
- * the down arrow key but by overriding this method it can be changed to\r
- * whatever you like.\r
- * \r
- * @return\r
- */\r
- protected int getNextKey() {\r
- return KeyCodes.KEY_DOWN;\r
- }\r
- \r
- /**\r
- * The key that selects the previous week in the calendar. By default this\r
- * is the up arrow key but by overriding this method it can be changed to\r
- * whatever you like.\r
- * \r
- * @return\r
- */\r
- protected int getPreviousKey() {\r
- return KeyCodes.KEY_UP;\r
- }\r
- \r
- /*\r
- * (non-Javadoc)\r
- * \r
- * @see\r
- * com.google.gwt.event.dom.client.MouseOutHandler#onMouseOut(com.google\r
- * .gwt.event.dom.client.MouseOutEvent)\r
- */\r
- public void onMouseOut(MouseOutEvent event) {\r
- if (mouseTimer != null) {\r
- mouseTimer.cancel();\r
- }\r
- }\r
- \r
- /*\r
- * (non-Javadoc)\r
- * \r
- * @see\r
- * com.google.gwt.event.dom.client.MouseDownHandler#onMouseDown(com.google\r
- * .gwt.event.dom.client.MouseDownEvent)\r
- */\r
- public void onMouseDown(MouseDownEvent event) {\r
- // Allow user to click-n-hold for fast-forward or fast-rewind.\r
- // Timer is first used for a 500ms delay after mousedown. After that has\r
- // elapsed, another timer is triggered to go off every 150ms. Both\r
- // timers are cancelled on mouseup or mouseout.\r
- if (event.getSource() instanceof VEventButton) {\r
- final VEventButton sender = (VEventButton) event.getSource();\r
- processClickEvent(sender);\r
- mouseTimer = new Timer() {\r
- @Override\r
- public void run() {\r
- mouseTimer = new Timer() {\r
- @Override\r
- public void run() {\r
- processClickEvent(sender);\r
- }\r
- };\r
- mouseTimer.scheduleRepeating(150);\r
- }\r
- };\r
- mouseTimer.schedule(500);\r
- }\r
- \r
- }\r
- \r
- /*\r
- * (non-Javadoc)\r
- * \r
- * @see\r
- * com.google.gwt.event.dom.client.MouseUpHandler#onMouseUp(com.google.gwt\r
- * .event.dom.client.MouseUpEvent)\r
- */\r
- public void onMouseUp(MouseUpEvent event) {\r
- if (mouseTimer != null) {\r
- mouseTimer.cancel();\r
- }\r
- }\r
- \r
- /**\r
- * Sets the data of the Panel.\r
- * \r
- * @param currentDate\r
- * The date to set\r
- */\r
- public void setDate(Date currentDate) {\r
- \r
- // Check that we are not re-rendering an already active date\r
- if (currentDate == value && currentDate != null) {\r
- return;\r
- }\r
- \r
- Date oldDisplayedMonth = displayedMonth;\r
- value = currentDate;\r
- \r
- if (value == null) {\r
- focusedDate = displayedMonth = null;\r
- } else {\r
- focusedDate = (Date) value.clone();\r
- displayedMonth = (Date) value.clone();\r
- }\r
- \r
- // Re-render calendar if month or year of focused date has changed\r
- if (oldDisplayedMonth == null || value == null\r
- || oldDisplayedMonth.getYear() != value.getYear()\r
- || oldDisplayedMonth.getMonth() != value.getMonth()) {\r
- renderCalendar();\r
- } else {\r
- focusDay(currentDate);\r
- selectFocused();\r
- }\r
- \r
- if (!hasFocus) {\r
- focusDay((Date) null);\r
- }\r
- }\r
- \r
- /**\r
- * TimeSelector is a widget consisting of list boxes that modifie the Date\r
- * object that is given for.\r
- * \r
- */\r
- public class VTime extends FlowPanel implements ChangeHandler {\r
- \r
- private ListBox hours;\r
- \r
- private ListBox mins;\r
- \r
- private ListBox sec;\r
- \r
- private ListBox ampm;\r
- \r
- /**\r
- * Constructor\r
- */\r
- public VTime() {\r
- super();\r
- setStyleName(VDateField.CLASSNAME + "-time");\r
- buildTime();\r
- }\r
- \r
- private ListBox createListBox() {\r
- ListBox lb = new ListBox();\r
- lb.setStyleName(VNativeSelect.CLASSNAME);\r
- lb.addChangeHandler(this);\r
- lb.addBlurHandler(VCalendarPanel.this);\r
- lb.addFocusHandler(VCalendarPanel.this);\r
- return lb;\r
- }\r
- \r
- /**\r
- * Constructs the ListBoxes and updates their value\r
- * \r
- * @param redraw\r
- * Should new instances of the listboxes be created\r
- */\r
- private void buildTime() {\r
- clear();\r
- \r
- hours = createListBox();\r
- if (getDateTimeService().isTwelveHourClock()) {\r
- hours.addItem("12");\r
- for (int i = 1; i < 12; i++) {\r
- hours.addItem((i < 10) ? "0" + i : "" + i);\r
- }\r
- } else {\r
- for (int i = 0; i < 24; i++) {\r
- hours.addItem((i < 10) ? "0" + i : "" + i);\r
- }\r
- }\r
- \r
- hours.addChangeHandler(this);\r
- if (getDateTimeService().isTwelveHourClock()) {\r
- ampm = createListBox();\r
- final String[] ampmText = getDateTimeService().getAmPmStrings();\r
- ampm.addItem(ampmText[0]);\r
- ampm.addItem(ampmText[1]);\r
- ampm.addChangeHandler(this);\r
- }\r
- \r
- if (getResolution() >= VDateField.RESOLUTION_MIN) {\r
- mins = createListBox();\r
- for (int i = 0; i < 60; i++) {\r
- mins.addItem((i < 10) ? "0" + i : "" + i);\r
- }\r
- mins.addChangeHandler(this);\r
- }\r
- if (getResolution() >= VDateField.RESOLUTION_SEC) {\r
- sec = createListBox();\r
- for (int i = 0; i < 60; i++) {\r
- sec.addItem((i < 10) ? "0" + i : "" + i);\r
- }\r
- sec.addChangeHandler(this);\r
- }\r
- \r
- final String delimiter = getDateTimeService().getClockDelimeter();\r
- if (isReadonly()) {\r
- int h = 0;\r
- if (value != null) {\r
- h = value.getHours();\r
- }\r
- if (getDateTimeService().isTwelveHourClock()) {\r
- h -= h < 12 ? 0 : 12;\r
- }\r
- add(new VLabel(h < 10 ? "0" + h : "" + h));\r
- } else {\r
- add(hours);\r
- }\r
- \r
- if (getResolution() >= VDateField.RESOLUTION_MIN) {\r
- add(new VLabel(delimiter));\r
- if (isReadonly()) {\r
- final int m = mins.getSelectedIndex();\r
- add(new VLabel(m < 10 ? "0" + m : "" + m));\r
- } else {\r
- add(mins);\r
- }\r
- }\r
- if (getResolution() >= VDateField.RESOLUTION_SEC) {\r
- add(new VLabel(delimiter));\r
- if (isReadonly()) {\r
- final int s = sec.getSelectedIndex();\r
- add(new VLabel(s < 10 ? "0" + s : "" + s));\r
- } else {\r
- add(sec);\r
- }\r
- }\r
- if (getResolution() == VDateField.RESOLUTION_HOUR) {\r
- add(new VLabel(delimiter + "00")); // o'clock\r
- }\r
- if (getDateTimeService().isTwelveHourClock()) {\r
- add(new VLabel(" "));\r
- if (isReadonly()) {\r
- int i = 0;\r
- if (value != null) {\r
- i = (value.getHours() < 12) ? 0 : 1;\r
- }\r
- add(new VLabel(ampm.getItemText(i)));\r
- } else {\r
- add(ampm);\r
- }\r
- }\r
- \r
- if (isReadonly()) {\r
- return;\r
- }\r
- \r
- // Update times\r
- updateTimes();\r
- \r
- ListBox lastDropDown = getLastDropDown();\r
- lastDropDown.addKeyDownHandler(new KeyDownHandler() {\r
- public void onKeyDown(KeyDownEvent event) {\r
- boolean shiftKey = event.getNativeEvent().getShiftKey();\r
- if (shiftKey) {\r
- return;\r
- } else {\r
- int nativeKeyCode = event.getNativeKeyCode();\r
- if (nativeKeyCode == KeyCodes.KEY_TAB) {\r
- onTabOut(event);\r
- }\r
- }\r
- }\r
- });\r
- \r
- }\r
- \r
- private ListBox getLastDropDown() {\r
- int i = getWidgetCount() - 1;\r
- while (i >= 0) {\r
- Widget widget = getWidget(i);\r
- if (widget instanceof ListBox) {\r
- return (ListBox) widget;\r
- }\r
- i--;\r
- }\r
- return null;\r
- }\r
- \r
- /**\r
- * Updates the valus to correspond to the values in value\r
- */\r
- public void updateTimes() {\r
- boolean selected = true;\r
- if (value == null) {\r
- value = new Date();\r
- selected = false;\r
- }\r
- if (getDateTimeService().isTwelveHourClock()) {\r
- int h = value.getHours();\r
- ampm.setSelectedIndex(h < 12 ? 0 : 1);\r
- h -= ampm.getSelectedIndex() * 12;\r
- hours.setSelectedIndex(h);\r
- } else {\r
- hours.setSelectedIndex(value.getHours());\r
- }\r
- if (getResolution() >= VDateField.RESOLUTION_MIN) {\r
- mins.setSelectedIndex(value.getMinutes());\r
- }\r
- if (getResolution() >= VDateField.RESOLUTION_SEC) {\r
- sec.setSelectedIndex(value.getSeconds());\r
- }\r
- if (getDateTimeService().isTwelveHourClock()) {\r
- ampm.setSelectedIndex(value.getHours() < 12 ? 0 : 1);\r
- }\r
- \r
- hours.setEnabled(isEnabled());\r
- if (mins != null) {\r
- mins.setEnabled(isEnabled());\r
- }\r
- if (sec != null) {\r
- sec.setEnabled(isEnabled());\r
- }\r
- if (ampm != null) {\r
- ampm.setEnabled(isEnabled());\r
- }\r
- \r
- }\r
- \r
- private int getMilliseconds() {\r
- return DateTimeService.getMilliseconds(value);\r
- }\r
- \r
- private DateTimeService getDateTimeService() {\r
- if (dateTimeService == null) {\r
- dateTimeService = new DateTimeService();\r
- }\r
- return dateTimeService;\r
- }\r
- \r
- /*\r
- * (non-Javadoc) VT\r
- * \r
- * @see\r
- * com.google.gwt.event.dom.client.ChangeHandler#onChange(com.google.gwt\r
- * .event.dom.client.ChangeEvent)\r
- */\r
- public void onChange(ChangeEvent event) {\r
- /*\r
- * Value from dropdowns gets always set for the value. Like year and\r
- * month when resolution is month or year.\r
- */\r
- if (event.getSource() == hours) {\r
- int h = hours.getSelectedIndex();\r
- if (getDateTimeService().isTwelveHourClock()) {\r
- h = h + ampm.getSelectedIndex() * 12;\r
- }\r
- value.setHours(h);\r
- if (timeChangeListener != null) {\r
- timeChangeListener.changed(h, value.getMinutes(),\r
- value.getSeconds(),\r
- DateTimeService.getMilliseconds(value));\r
- }\r
- event.preventDefault();\r
- event.stopPropagation();\r
- } else if (event.getSource() == mins) {\r
- final int m = mins.getSelectedIndex();\r
- value.setMinutes(m);\r
- if (timeChangeListener != null) {\r
- timeChangeListener.changed(value.getHours(), m,\r
- value.getSeconds(),\r
- DateTimeService.getMilliseconds(value));\r
- }\r
- event.preventDefault();\r
- event.stopPropagation();\r
- } else if (event.getSource() == sec) {\r
- final int s = sec.getSelectedIndex();\r
- value.setSeconds(s);\r
- if (timeChangeListener != null) {\r
- timeChangeListener.changed(value.getHours(),\r
- value.getMinutes(), s,\r
- DateTimeService.getMilliseconds(value));\r
- }\r
- event.preventDefault();\r
- event.stopPropagation();\r
- } else if (event.getSource() == ampm) {\r
- final int h = hours.getSelectedIndex()\r
- + (ampm.getSelectedIndex() * 12);\r
- value.setHours(h);\r
- if (timeChangeListener != null) {\r
- timeChangeListener.changed(h, value.getMinutes(),\r
- value.getSeconds(),\r
- DateTimeService.getMilliseconds(value));\r
- }\r
- event.preventDefault();\r
- event.stopPropagation();\r
- }\r
- }\r
- \r
- }\r
- \r
- /**\r
- * A widget representing a single day in the calendar panel.\r
- */\r
- private class Day extends InlineHTML {\r
- private static final String BASECLASS = VDateField.CLASSNAME\r
- + "-calendarpanel-day";\r
- private final Date date;\r
- \r
- Day(Date date) {\r
- super("" + date.getDate());\r
- setStyleName(BASECLASS);\r
- this.date = date;\r
- addClickHandler(dayClickHandler);\r
- }\r
- \r
- public Date getDate() {\r
- return date;\r
- }\r
- }\r
- \r
- public Date getDate() {\r
- return value;\r
- }\r
- \r
- /**\r
- * If true should be returned if the panel will not be used after this\r
- * event.\r
- * \r
- * @param event\r
- * @return\r
- */\r
- protected boolean onTabOut(DomEvent<?> event) {\r
- if (focusOutListener != null) {\r
- return focusOutListener.onFocusOut(event);\r
- }\r
- return false;\r
- }\r
- \r
- /**\r
- * A focus out listener is triggered when the panel loosed focus. This can\r
- * happen either after a user clicks outside the panel or tabs out.\r
- * \r
- * @param listener\r
- * The listener to trigger\r
- */\r
- public void setFocusOutListener(FocusOutListener listener) {\r
- focusOutListener = listener;\r
- }\r
- \r
- /**\r
- * The submit listener is called when the user selects a value from the\r
- * calender either by clicking the day or selects it by keyboard.\r
- * \r
- * @param submitListener\r
- * The listener to trigger\r
- */\r
- public void setSubmitListener(SubmitListener submitListener) {\r
- this.submitListener = submitListener;\r
- }\r
- \r
- /**\r
- * The given FocusChangeListener is notified when the focused date changes\r
- * by user either clicking on a new date or by using the keyboard.\r
- * \r
- * @param listener\r
- * The FocusChangeListener to be notified\r
- */\r
- public void setFocusChangeListener(FocusChangeListener listener) {\r
- focusChangeListener = listener;\r
- }\r
- \r
- /**\r
- * The time change listener is triggered when the user changes the time.\r
- * \r
- * @param listener\r
- */\r
- public void setTimeChangeListener(TimeChangeListener listener) {\r
- timeChangeListener = listener;\r
- }\r
- \r
- /**\r
- * Returns the submit listener that listens to selection made from the panel\r
- * \r
- * @return The listener or NULL if no listener has been set\r
- */\r
- public SubmitListener getSubmitListener() {\r
- return submitListener;\r
- }\r
- \r
- /*\r
- * (non-Javadoc)\r
- * \r
- * @see\r
- * com.google.gwt.event.dom.client.BlurHandler#onBlur(com.google.gwt.event\r
- * .dom.client.BlurEvent)\r
- */\r
- public void onBlur(final BlurEvent event) {\r
- if (event.getSource() instanceof VCalendarPanel) {\r
- hasFocus = false;\r
- focusDay(null);\r
- }\r
- }\r
- \r
- /*\r
- * (non-Javadoc)\r
- * \r
- * @see\r
- * com.google.gwt.event.dom.client.FocusHandler#onFocus(com.google.gwt.event\r
- * .dom.client.FocusEvent)\r
- */\r
- public void onFocus(FocusEvent event) {\r
- if (event.getSource() instanceof VCalendarPanel) {\r
- hasFocus = true;\r
- \r
- // Focuses the current day if the calendar shows the days\r
- if (focusedDay != null) {\r
- focusDay(focusedDate);\r
- }\r
- }\r
- }\r
- \r
- private static final String SUBPART_NEXT_MONTH = "nextmon";\r
- private static final String SUBPART_PREV_MONTH = "prevmon";\r
- \r
- private static final String SUBPART_NEXT_YEAR = "nexty";\r
- private static final String SUBPART_PREV_YEAR = "prevy";\r
- private static final String SUBPART_HOUR_SELECT = "h";\r
- private static final String SUBPART_MINUTE_SELECT = "m";\r
- private static final String SUBPART_SECS_SELECT = "s";\r
- private static final String SUBPART_MSECS_SELECT = "ms";\r
- private static final String SUBPART_AMPM_SELECT = "ampm";\r
- private static final String SUBPART_DAY = "day";\r
- private static final String SUBPART_MONTH_YEAR_HEADER = "header";\r
- \r
- public String getSubPartName(Element subElement) {\r
- if (contains(nextMonth, subElement)) {\r
- return SUBPART_NEXT_MONTH;\r
- } else if (contains(prevMonth, subElement)) {\r
- return SUBPART_PREV_MONTH;\r
- } else if (contains(nextYear, subElement)) {\r
- return SUBPART_NEXT_YEAR;\r
- } else if (contains(prevYear, subElement)) {\r
- return SUBPART_PREV_YEAR;\r
- } else if (contains(days, subElement)) {\r
- // Day, find out which dayOfMonth and use that as the identifier\r
- Day day = Util.findWidget(subElement, Day.class);\r
- if (day != null) {\r
- Date date = day.getDate();\r
- int id = date.getDate();\r
- // Zero or negative ids map to days of the preceding month,\r
- // past-the-end-of-month ids to days of the following month\r
- if (date.getMonth() < displayedMonth.getMonth()) {\r
- id -= DateTimeService.getNumberOfDaysInMonth(date);\r
- } else if (date.getMonth() > displayedMonth.getMonth()) {\r
- id += DateTimeService\r
- .getNumberOfDaysInMonth(displayedMonth);\r
- }\r
- return SUBPART_DAY + id;\r
- }\r
- } else if (time != null) {\r
- if (contains(time.hours, subElement)) {\r
- return SUBPART_HOUR_SELECT;\r
- } else if (contains(time.mins, subElement)) {\r
- return SUBPART_MINUTE_SELECT;\r
- } else if (contains(time.sec, subElement)) {\r
- return SUBPART_SECS_SELECT;\r
- } else if (contains(time.ampm, subElement)) {\r
- return SUBPART_AMPM_SELECT;\r
- \r
- }\r
- } else if (getCellFormatter().getElement(0, 2).isOrHasChild(subElement)) {\r
- return SUBPART_MONTH_YEAR_HEADER;\r
- }\r
- \r
- return null;\r
- }\r
- \r
- /**\r
- * Checks if subElement is inside the widget DOM hierarchy.\r
- * \r
- * @param w\r
- * @param subElement\r
- * @return true if {@code w} is a parent of subElement, false otherwise.\r
- */\r
- private boolean contains(Widget w, Element subElement) {\r
- if (w == null || w.getElement() == null) {\r
- return false;\r
- }\r
- \r
- return w.getElement().isOrHasChild(subElement);\r
- }\r
- \r
- public Element getSubPartElement(String subPart) {\r
- if (SUBPART_NEXT_MONTH.equals(subPart)) {\r
- return nextMonth.getElement();\r
- }\r
- if (SUBPART_PREV_MONTH.equals(subPart)) {\r
- return prevMonth.getElement();\r
- }\r
- if (SUBPART_NEXT_YEAR.equals(subPart)) {\r
- return nextYear.getElement();\r
- }\r
- if (SUBPART_PREV_YEAR.equals(subPart)) {\r
- return prevYear.getElement();\r
- }\r
- if (SUBPART_HOUR_SELECT.equals(subPart)) {\r
- return time.hours.getElement();\r
- }\r
- if (SUBPART_MINUTE_SELECT.equals(subPart)) {\r
- return time.mins.getElement();\r
- }\r
- if (SUBPART_SECS_SELECT.equals(subPart)) {\r
- return time.sec.getElement();\r
- }\r
- if (SUBPART_AMPM_SELECT.equals(subPart)) {\r
- return time.ampm.getElement();\r
- }\r
- if (subPart.startsWith(SUBPART_DAY)) {\r
- // Zero or negative ids map to days in the preceding month,\r
- // past-the-end-of-month ids to days in the following month\r
- int dayOfMonth = Integer.parseInt(subPart.substring(SUBPART_DAY\r
- .length()));\r
- Date date = new Date(displayedMonth.getYear(),\r
- displayedMonth.getMonth(), dayOfMonth);\r
- Iterator<Widget> iter = days.iterator();\r
- while (iter.hasNext()) {\r
- Widget w = iter.next();\r
- if (w instanceof Day) {\r
- Day day = (Day) w;\r
- if (day.getDate().equals(date)) {\r
- return day.getElement();\r
- }\r
- }\r
- }\r
- }\r
- \r
- if (SUBPART_MONTH_YEAR_HEADER.equals(subPart)) {\r
- return (Element) getCellFormatter().getElement(0, 2).getChild(0);\r
- }\r
- return null;\r
- }\r
- \r
- @Override\r
- protected void onDetach() {\r
- super.onDetach();\r
- if (mouseTimer != null) {\r
- mouseTimer.cancel();\r
- }\r
- }\r
- }\r
+ /*
+ @VaadinApache2LicenseForJavaFiles@
+ */
+
+ package com.vaadin.terminal.gwt.client.ui;
+
+ import java.util.Date;
+ import java.util.Iterator;
+
+ import com.google.gwt.dom.client.Node;
+ import com.google.gwt.event.dom.client.BlurEvent;
+ import com.google.gwt.event.dom.client.BlurHandler;
+ import com.google.gwt.event.dom.client.ChangeEvent;
+ import com.google.gwt.event.dom.client.ChangeHandler;
+ import com.google.gwt.event.dom.client.ClickEvent;
+ import com.google.gwt.event.dom.client.ClickHandler;
+ import com.google.gwt.event.dom.client.DomEvent;
+ import com.google.gwt.event.dom.client.FocusEvent;
+ import com.google.gwt.event.dom.client.FocusHandler;
+ import com.google.gwt.event.dom.client.KeyCodes;
+ import com.google.gwt.event.dom.client.KeyDownEvent;
+ import com.google.gwt.event.dom.client.KeyDownHandler;
+ import com.google.gwt.event.dom.client.KeyPressEvent;
+ import com.google.gwt.event.dom.client.KeyPressHandler;
+ import com.google.gwt.event.dom.client.MouseDownEvent;
+ import com.google.gwt.event.dom.client.MouseDownHandler;
+ import com.google.gwt.event.dom.client.MouseOutEvent;
+ import com.google.gwt.event.dom.client.MouseOutHandler;
+ import com.google.gwt.event.dom.client.MouseUpEvent;
+ import com.google.gwt.event.dom.client.MouseUpHandler;
+ import com.google.gwt.user.client.Element;
+ import com.google.gwt.user.client.Timer;
+ import com.google.gwt.user.client.ui.Button;
+ import com.google.gwt.user.client.ui.FlexTable;
+ import com.google.gwt.user.client.ui.FlowPanel;
+ import com.google.gwt.user.client.ui.InlineHTML;
+ import com.google.gwt.user.client.ui.ListBox;
+ import com.google.gwt.user.client.ui.Widget;
+ import com.vaadin.terminal.gwt.client.BrowserInfo;
+ import com.vaadin.terminal.gwt.client.DateTimeService;
+ import com.vaadin.terminal.gwt.client.Util;
+ import com.vaadin.terminal.gwt.client.VConsole;
++import com.vaadin.terminal.gwt.client.ui.label.VLabel;
+
+ @SuppressWarnings("deprecation")
+ public class VCalendarPanel extends FocusableFlexTable implements
+ KeyDownHandler, KeyPressHandler, MouseOutHandler, MouseDownHandler,
+ MouseUpHandler, BlurHandler, FocusHandler, SubPartAware {
+
+ public interface SubmitListener {
+
+ /**
+ * Called when calendar user triggers a submitting operation in calendar
+ * panel. Eg. clicking on day or hitting enter.
+ */
+ void onSubmit();
+
+ /**
+ * On eg. ESC key.
+ */
+ void onCancel();
+ }
+
+ /**
+ * Blur listener that listens to blur event from the panel
+ */
+ public interface FocusOutListener {
+ /**
+ * @return true if the calendar panel is not used after focus moves out
+ */
+ boolean onFocusOut(DomEvent<?> event);
+ }
+
+ /**
+ * FocusChangeListener is notified when the panel changes its _focused_
+ * value.
+ */
+ public interface FocusChangeListener {
+ void focusChanged(Date focusedDate);
+ }
+
+ /**
+ * Dispatches an event when the panel when time is changed
+ */
+ public interface TimeChangeListener {
+
+ void changed(int hour, int min, int sec, int msec);
+ }
+
+ /**
+ * Represents a Date button in the calendar
+ */
+ private class VEventButton extends Button {
+ public VEventButton() {
+ addMouseDownHandler(VCalendarPanel.this);
+ addMouseOutHandler(VCalendarPanel.this);
+ addMouseUpHandler(VCalendarPanel.this);
+ }
+ }
+
+ private static final String CN_FOCUSED = "focused";
+
+ private static final String CN_TODAY = "today";
+
+ private static final String CN_SELECTED = "selected";
+
+ private static final String CN_OFFMONTH = "offmonth";
+
+ /**
+ * Represents a click handler for when a user selects a value by using the
+ * mouse
+ */
+ private ClickHandler dayClickHandler = new ClickHandler() {
+ /*
+ * (non-Javadoc)
+ *
+ * @see
+ * com.google.gwt.event.dom.client.ClickHandler#onClick(com.google.gwt
+ * .event.dom.client.ClickEvent)
+ */
+ public void onClick(ClickEvent event) {
+ Day day = (Day) event.getSource();
+ focusDay(day.getDate());
+ selectFocused();
+ onSubmit();
+ }
+ };
+
+ private VEventButton prevYear;
+
+ private VEventButton nextYear;
+
+ private VEventButton prevMonth;
+
+ private VEventButton nextMonth;
+
+ private VTime time;
+
+ private FlexTable days = new FlexTable();
+
+ private int resolution = VDateField.RESOLUTION_YEAR;
+
+ private int focusedRow;
+
+ private Timer mouseTimer;
+
+ private Date value;
+
+ private boolean enabled = true;
+
+ private boolean readonly = false;
+
+ private DateTimeService dateTimeService;
+
+ private boolean showISOWeekNumbers;
+
+ private Date displayedMonth;
+
+ private Date focusedDate;
+
+ private Day selectedDay;
+
+ private Day focusedDay;
+
+ private FocusOutListener focusOutListener;
+
+ private SubmitListener submitListener;
+
+ private FocusChangeListener focusChangeListener;
+
+ private TimeChangeListener timeChangeListener;
+
+ private boolean hasFocus = false;
+
+ public VCalendarPanel() {
+
+ setStyleName(VDateField.CLASSNAME + "-calendarpanel");
+
+ /*
+ * Firefox auto-repeat works correctly only if we use a key press
+ * handler, other browsers handle it correctly when using a key down
+ * handler
+ */
+ if (BrowserInfo.get().isGecko()) {
+ addKeyPressHandler(this);
+ } else {
+ addKeyDownHandler(this);
+ }
+ addFocusHandler(this);
+ addBlurHandler(this);
+
+ }
+
+ /**
+ * Sets the focus to given date in the current view. Used when moving in the
+ * calendar with the keyboard.
+ *
+ * @param date
+ * A Date representing the day of month to be focused. Must be
+ * one of the days currently visible.
+ */
+ private void focusDay(Date date) {
+ // Only used when calender body is present
+ if (resolution > VDateField.RESOLUTION_MONTH) {
+ if (focusedDay != null) {
+ focusedDay.removeStyleDependentName(CN_FOCUSED);
+ }
+
+ if (date != null && focusedDate != null) {
+ focusedDate.setTime(date.getTime());
+ int rowCount = days.getRowCount();
+ for (int i = 0; i < rowCount; i++) {
+ int cellCount = days.getCellCount(i);
+ for (int j = 0; j < cellCount; j++) {
+ Widget widget = days.getWidget(i, j);
+ if (widget != null && widget instanceof Day) {
+ Day curday = (Day) widget;
+ if (curday.getDate().equals(date)) {
+ curday.addStyleDependentName(CN_FOCUSED);
+ focusedDay = curday;
+ focusedRow = i;
+ return;
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+
+ /**
+ * Sets the selection highlight to a given day in the current view
+ *
+ * @param date
+ * A Date representing the day of month to be selected. Must be
+ * one of the days currently visible.
+ *
+ */
+ private void selectDate(Date date) {
+ if (selectedDay != null) {
+ selectedDay.removeStyleDependentName(CN_SELECTED);
+ }
+
+ int rowCount = days.getRowCount();
+ for (int i = 0; i < rowCount; i++) {
+ int cellCount = days.getCellCount(i);
+ for (int j = 0; j < cellCount; j++) {
+ Widget widget = days.getWidget(i, j);
+ if (widget != null && widget instanceof Day) {
+ Day curday = (Day) widget;
+ if (curday.getDate().equals(date)) {
+ curday.addStyleDependentName(CN_SELECTED);
+ selectedDay = curday;
+ return;
+ }
+ }
+ }
+ }
+ }
+
+ /**
+ * Updates year, month, day from focusedDate to value
+ */
+ private void selectFocused() {
+ if (focusedDate != null) {
+ if (value == null) {
+ // No previously selected value (set to null on server side).
+ // Create a new date using current date and time
+ value = new Date();
+ }
+ /*
+ * #5594 set Date (day) to 1 in order to prevent any kind of
+ * wrapping of months when later setting the month. (e.g. 31 ->
+ * month with 30 days -> wraps to the 1st of the following month,
+ * e.g. 31st of May -> 31st of April = 1st of May)
+ */
+ value.setDate(1);
+ if (value.getYear() != focusedDate.getYear()) {
+ value.setYear(focusedDate.getYear());
+ }
+ if (value.getMonth() != focusedDate.getMonth()) {
+ value.setMonth(focusedDate.getMonth());
+ }
+ if (value.getDate() != focusedDate.getDate()) {
+ }
+ // We always need to set the date, even if it hasn't changed, since
+ // it was forced to 1 above.
+ value.setDate(focusedDate.getDate());
+
+ selectDate(focusedDate);
+ } else {
+ VConsole.log("Trying to select a the focused date which is NULL!");
+ }
+ }
+
+ protected boolean onValueChange() {
+ return false;
+ }
+
+ public int getResolution() {
+ return resolution;
+ }
+
+ public void setResolution(int resolution) {
+ this.resolution = resolution;
+ if (time != null) {
+ time.removeFromParent();
+ time = null;
+ }
+ }
+
+ private boolean isReadonly() {
+ return readonly;
+ }
+
+ private boolean isEnabled() {
+ return enabled;
+ }
+
+ private void clearCalendarBody(boolean remove) {
+ if (!remove) {
+ // Leave the cells in place but clear their contents
+
+ // This has the side effect of ensuring that the calendar always
+ // contain 7 rows.
+ for (int row = 1; row < 7; row++) {
+ for (int col = 0; col < 8; col++) {
+ days.setHTML(row, col, " ");
+ }
+ }
+ } else if (getRowCount() > 1) {
+ removeRow(1);
+ days.clear();
+ }
+ }
+
+ /**
+ * Builds the top buttons and current month and year header.
+ *
+ * @param needsMonth
+ * Should the month buttons be visible?
+ */
+ private void buildCalendarHeader(boolean needsMonth) {
+
+ getRowFormatter().addStyleName(0,
+ VDateField.CLASSNAME + "-calendarpanel-header");
+
+ if (prevMonth == null && needsMonth) {
+ prevMonth = new VEventButton();
+ prevMonth.setHTML("‹");
+ prevMonth.setStyleName("v-button-prevmonth");
+ prevMonth.setTabIndex(-1);
+ nextMonth = new VEventButton();
+ nextMonth.setHTML("›");
+ nextMonth.setStyleName("v-button-nextmonth");
+ nextMonth.setTabIndex(-1);
+ getFlexCellFormatter().setStyleName(0, 3,
+ VDateField.CLASSNAME + "-calendarpanel-nextmonth");
+ getFlexCellFormatter().setStyleName(0, 1,
+ VDateField.CLASSNAME + "-calendarpanel-prevmonth");
+
+ setWidget(0, 3, nextMonth);
+ setWidget(0, 1, prevMonth);
+ } else if (prevMonth != null && !needsMonth) {
+ // Remove month traverse buttons
+ remove(prevMonth);
+ remove(nextMonth);
+ prevMonth = null;
+ nextMonth = null;
+ }
+
+ if (prevYear == null) {
+ prevYear = new VEventButton();
+ prevYear.setHTML("«");
+ prevYear.setStyleName("v-button-prevyear");
+ prevYear.setTabIndex(-1);
+ nextYear = new VEventButton();
+ nextYear.setHTML("»");
+ nextYear.setStyleName("v-button-nextyear");
+ nextYear.setTabIndex(-1);
+ setWidget(0, 0, prevYear);
+ setWidget(0, 4, nextYear);
+ getFlexCellFormatter().setStyleName(0, 0,
+ VDateField.CLASSNAME + "-calendarpanel-prevyear");
+ getFlexCellFormatter().setStyleName(0, 4,
+ VDateField.CLASSNAME + "-calendarpanel-nextyear");
+ }
+
+ final String monthName = needsMonth ? getDateTimeService().getMonth(
+ focusedDate.getMonth()) : "";
+ final int year = focusedDate.getYear() + 1900;
+ getFlexCellFormatter().setStyleName(0, 2,
+ VDateField.CLASSNAME + "-calendarpanel-month");
+ setHTML(0, 2, "<span class=\"" + VDateField.CLASSNAME
+ + "-calendarpanel-month\">" + monthName + " " + year
+ + "</span>");
+ }
+
+ private DateTimeService getDateTimeService() {
+ return dateTimeService;
+ }
+
+ public void setDateTimeService(DateTimeService dateTimeService) {
+ this.dateTimeService = dateTimeService;
+ }
+
+ /**
+ * Returns whether ISO 8601 week numbers should be shown in the value
+ * selector or not. ISO 8601 defines that a week always starts with a Monday
+ * so the week numbers are only shown if this is the case.
+ *
+ * @return true if week number should be shown, false otherwise
+ */
+ public boolean isShowISOWeekNumbers() {
+ return showISOWeekNumbers;
+ }
+
+ public void setShowISOWeekNumbers(boolean showISOWeekNumbers) {
+ this.showISOWeekNumbers = showISOWeekNumbers;
+ }
+
+ /**
+ * Builds the day and time selectors of the calendar.
+ */
+ private void buildCalendarBody() {
+
+ final int weekColumn = 0;
+ final int firstWeekdayColumn = 1;
+ final int headerRow = 0;
+
+ setWidget(1, 0, days);
+ setCellPadding(0);
+ setCellSpacing(0);
+ getFlexCellFormatter().setColSpan(1, 0, 5);
+ getFlexCellFormatter().setStyleName(1, 0,
+ VDateField.CLASSNAME + "-calendarpanel-body");
+
+ days.getFlexCellFormatter().setStyleName(headerRow, weekColumn,
+ "v-week");
+ days.setHTML(headerRow, weekColumn, "<strong></strong>");
+ // Hide the week column if week numbers are not to be displayed.
+ days.getFlexCellFormatter().setVisible(headerRow, weekColumn,
+ isShowISOWeekNumbers());
+
+ days.getRowFormatter().setStyleName(headerRow,
+ VDateField.CLASSNAME + "-calendarpanel-weekdays");
+
+ if (isShowISOWeekNumbers()) {
+ days.getFlexCellFormatter().setStyleName(headerRow, weekColumn,
+ "v-first");
+ days.getFlexCellFormatter().setStyleName(headerRow,
+ firstWeekdayColumn, "");
+ days.getRowFormatter().addStyleName(headerRow,
+ VDateField.CLASSNAME + "-calendarpanel-weeknumbers");
+ } else {
+ days.getFlexCellFormatter().setStyleName(headerRow, weekColumn, "");
+ days.getFlexCellFormatter().setStyleName(headerRow,
+ firstWeekdayColumn, "v-first");
+ }
+
+ days.getFlexCellFormatter().setStyleName(headerRow,
+ firstWeekdayColumn + 6, "v-last");
+
+ // Print weekday names
+ final int firstDay = getDateTimeService().getFirstDayOfWeek();
+ for (int i = 0; i < 7; i++) {
+ int day = i + firstDay;
+ if (day > 6) {
+ day = 0;
+ }
+ if (getResolution() > VDateField.RESOLUTION_MONTH) {
+ days.setHTML(headerRow, firstWeekdayColumn + i, "<strong>"
+ + getDateTimeService().getShortDay(day) + "</strong>");
+ } else {
+ days.setHTML(headerRow, firstWeekdayColumn + i, "");
+ }
+ }
+
+ // today must have zeroed hours, minutes, seconds, and milliseconds
+ final Date tmp = new Date();
+ final Date today = new Date(tmp.getYear(), tmp.getMonth(),
+ tmp.getDate());
+
+ final int startWeekDay = getDateTimeService().getStartWeekDay(
+ focusedDate);
+ final Date curr = (Date) focusedDate.clone();
+ // Start from the first day of the week that at least partially belongs
+ // to the current month
+ curr.setDate(-startWeekDay);
+
+ // No month has more than 6 weeks so 6 is a safe maximum for rows.
+ for (int weekOfMonth = 1; weekOfMonth < 7; weekOfMonth++) {
+ for (int dayOfWeek = 0; dayOfWeek < 7; dayOfWeek++) {
+
+ // Actually write the day of month
+ Day day = new Day((Date) curr.clone());
+
+ if (curr.equals(value)) {
+ day.addStyleDependentName(CN_SELECTED);
+ selectedDay = day;
+ }
+ if (curr.equals(today)) {
+ day.addStyleDependentName(CN_TODAY);
+ }
+ if (curr.equals(focusedDate)) {
+ focusedDay = day;
+ focusedRow = weekOfMonth;
+ if (hasFocus) {
+ day.addStyleDependentName(CN_FOCUSED);
+ }
+ }
+ if (curr.getMonth() != focusedDate.getMonth()) {
+ day.addStyleDependentName(CN_OFFMONTH);
+ }
+
+ days.setWidget(weekOfMonth, firstWeekdayColumn + dayOfWeek, day);
+
+ // ISO week numbers if requested
+ days.getCellFormatter().setVisible(weekOfMonth, weekColumn,
+ isShowISOWeekNumbers());
+ if (isShowISOWeekNumbers()) {
+ final String baseCssClass = VDateField.CLASSNAME
+ + "-calendarpanel-weeknumber";
+ String weekCssClass = baseCssClass;
+
+ int weekNumber = DateTimeService.getISOWeekNumber(curr);
+
+ days.setHTML(weekOfMonth, 0, "<span class=\""
+ + weekCssClass + "\"" + ">" + weekNumber
+ + "</span>");
+ }
+ curr.setDate(curr.getDate() + 1);
+ }
+ }
+ }
+
+ /**
+ * Do we need the time selector
+ *
+ * @return True if it is required
+ */
+ private boolean isTimeSelectorNeeded() {
+ return getResolution() > VDateField.RESOLUTION_DAY;
+ }
+
+ /**
+ * Updates the calendar and text field with the selected dates.
+ */
+ public void renderCalendar() {
+ if (focusedDate == null) {
+ focusedDate = new Date();
+ }
+
+ if (getResolution() <= VDateField.RESOLUTION_MONTH
+ && focusChangeListener != null) {
+ focusChangeListener.focusChanged(new Date(focusedDate.getTime()));
+ }
+
+ final boolean needsMonth = getResolution() > VDateField.RESOLUTION_YEAR;
+ boolean needsBody = getResolution() >= VDateField.RESOLUTION_DAY;
+ buildCalendarHeader(needsMonth);
+ clearCalendarBody(!needsBody);
+ if (needsBody) {
+ buildCalendarBody();
+ }
+
+ if (isTimeSelectorNeeded() && time == null) {
+ time = new VTime();
+ setWidget(2, 0, time);
+ getFlexCellFormatter().setColSpan(2, 0, 5);
+ getFlexCellFormatter().setStyleName(2, 0,
+ VDateField.CLASSNAME + "-calendarpanel-time");
+ } else if (isTimeSelectorNeeded()) {
+ time.updateTimes();
+ } else if (time != null) {
+ remove(time);
+ }
+
+ }
+
+ /**
+ * Selects the next month
+ */
+ private void focusNextMonth() {
+
+ int currentMonth = focusedDate.getMonth();
+ focusedDate.setMonth(currentMonth + 1);
+ int requestedMonth = (currentMonth + 1) % 12;
+
+ /*
+ * If the selected value was e.g. 31.3 the new value would be 31.4 but
+ * this value is invalid so the new value will be 1.5. This is taken
+ * care of by decreasing the value until we have the correct month.
+ */
+ while (focusedDate.getMonth() != requestedMonth) {
+ focusedDate.setDate(focusedDate.getDate() - 1);
+ }
+ displayedMonth.setMonth(displayedMonth.getMonth() + 1);
+
+ renderCalendar();
+ }
+
+ /**
+ * Selects the previous month
+ */
+ private void focusPreviousMonth() {
+ int currentMonth = focusedDate.getMonth();
+ focusedDate.setMonth(currentMonth - 1);
+
+ /*
+ * If the selected value was e.g. 31.12 the new value would be 31.11 but
+ * this value is invalid so the new value will be 1.12. This is taken
+ * care of by decreasing the value until we have the correct month.
+ */
+ while (focusedDate.getMonth() == currentMonth) {
+ focusedDate.setDate(focusedDate.getDate() - 1);
+ }
+ displayedMonth.setMonth(displayedMonth.getMonth() - 1);
+
+ renderCalendar();
+ }
+
+ /**
+ * Selects the previous year
+ */
+ private void focusPreviousYear(int years) {
+ focusedDate.setYear(focusedDate.getYear() - years);
+ displayedMonth.setYear(displayedMonth.getYear() - years);
+ renderCalendar();
+ }
+
+ /**
+ * Selects the next year
+ */
+ private void focusNextYear(int years) {
+ focusedDate.setYear(focusedDate.getYear() + years);
+ displayedMonth.setYear(displayedMonth.getYear() + years);
+ renderCalendar();
+ }
+
+ /**
+ * Handles a user click on the component
+ *
+ * @param sender
+ * The component that was clicked
+ * @param updateVariable
+ * Should the value field be updated
+ *
+ */
+ private void processClickEvent(Widget sender) {
+ if (!isEnabled() || isReadonly()) {
+ return;
+ }
+ if (sender == prevYear) {
+ focusPreviousYear(1);
+ } else if (sender == nextYear) {
+ focusNextYear(1);
+ } else if (sender == prevMonth) {
+ focusPreviousMonth();
+ } else if (sender == nextMonth) {
+ focusNextMonth();
+ }
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see
+ * com.google.gwt.event.dom.client.KeyDownHandler#onKeyDown(com.google.gwt
+ * .event.dom.client.KeyDownEvent)
+ */
+ public void onKeyDown(KeyDownEvent event) {
+ handleKeyPress(event);
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see
+ * com.google.gwt.event.dom.client.KeyPressHandler#onKeyPress(com.google
+ * .gwt.event.dom.client.KeyPressEvent)
+ */
+ public void onKeyPress(KeyPressEvent event) {
+ handleKeyPress(event);
+ }
+
+ /**
+ * Handles the keypress from both the onKeyPress event and the onKeyDown
+ * event
+ *
+ * @param event
+ * The keydown/keypress event
+ */
+ private void handleKeyPress(DomEvent<?> event) {
+ if (time != null
+ && time.getElement().isOrHasChild(
+ (Node) event.getNativeEvent().getEventTarget().cast())) {
+ int nativeKeyCode = event.getNativeEvent().getKeyCode();
+ if (nativeKeyCode == getSelectKey()) {
+ onSubmit(); // submit happens if enter key hit down on listboxes
+ event.preventDefault();
+ event.stopPropagation();
+ }
+ return;
+ }
+
+ // Check tabs
+ int keycode = event.getNativeEvent().getKeyCode();
+ if (keycode == KeyCodes.KEY_TAB && event.getNativeEvent().getShiftKey()) {
+ if (onTabOut(event)) {
+ return;
+ }
+ }
+
+ // Handle the navigation
+ if (handleNavigation(keycode, event.getNativeEvent().getCtrlKey()
+ || event.getNativeEvent().getMetaKey(), event.getNativeEvent()
+ .getShiftKey())) {
+ event.preventDefault();
+ }
+
+ }
+
+ /**
+ * Notifies submit-listeners of a submit event
+ */
+ private void onSubmit() {
+ if (getSubmitListener() != null) {
+ getSubmitListener().onSubmit();
+ }
+ }
+
+ /**
+ * Notifies submit-listeners of a cancel event
+ */
+ private void onCancel() {
+ if (getSubmitListener() != null) {
+ getSubmitListener().onCancel();
+ }
+ }
+
+ /**
+ * Handles the keyboard navigation when the resolution is set to years.
+ *
+ * @param keycode
+ * The keycode to process
+ * @param ctrl
+ * Is ctrl pressed?
+ * @param shift
+ * is shift pressed
+ * @return Returns true if the keycode was processed, else false
+ */
+ protected boolean handleNavigationYearMode(int keycode, boolean ctrl,
+ boolean shift) {
+
+ // Ctrl and Shift selection not supported
+ if (ctrl || shift) {
+ return false;
+ }
+
+ else if (keycode == getPreviousKey()) {
+ focusNextYear(10); // Add 10 years
+ return true;
+ }
+
+ else if (keycode == getForwardKey()) {
+ focusNextYear(1); // Add 1 year
+ return true;
+ }
+
+ else if (keycode == getNextKey()) {
+ focusPreviousYear(10); // Subtract 10 years
+ return true;
+ }
+
+ else if (keycode == getBackwardKey()) {
+ focusPreviousYear(1); // Subtract 1 year
+ return true;
+
+ } else if (keycode == getSelectKey()) {
+ value = (Date) focusedDate.clone();
+ onSubmit();
+ return true;
+
+ } else if (keycode == getResetKey()) {
+ // Restore showing value the selected value
+ focusedDate.setTime(value.getTime());
+ renderCalendar();
+ return true;
+
+ } else if (keycode == getCloseKey()) {
+ // TODO fire listener, on users responsibility??
+
+ return true;
+ }
+ return false;
+ }
+
+ /**
+ * Handle the keyboard navigation when the resolution is set to MONTH
+ *
+ * @param keycode
+ * The keycode to handle
+ * @param ctrl
+ * Was the ctrl key pressed?
+ * @param shift
+ * Was the shift key pressed?
+ * @return
+ */
+ protected boolean handleNavigationMonthMode(int keycode, boolean ctrl,
+ boolean shift) {
+
+ // Ctrl selection not supported
+ if (ctrl) {
+ return false;
+
+ } else if (keycode == getPreviousKey()) {
+ focusNextYear(1); // Add 1 year
+ return true;
+
+ } else if (keycode == getForwardKey()) {
+ focusNextMonth(); // Add 1 month
+ return true;
+
+ } else if (keycode == getNextKey()) {
+ focusPreviousYear(1); // Subtract 1 year
+ return true;
+
+ } else if (keycode == getBackwardKey()) {
+ focusPreviousMonth(); // Subtract 1 month
+ return true;
+
+ } else if (keycode == getSelectKey()) {
+ value = (Date) focusedDate.clone();
+ onSubmit();
+ return true;
+
+ } else if (keycode == getResetKey()) {
+ // Restore showing value the selected value
+ focusedDate.setTime(value.getTime());
+ renderCalendar();
+ return true;
+
+ } else if (keycode == getCloseKey() || keycode == KeyCodes.KEY_TAB) {
+
+ // TODO fire close event
+
+ return true;
+ }
+
+ return false;
+ }
+
+ /**
+ * Handle keyboard navigation what the resolution is set to DAY
+ *
+ * @param keycode
+ * The keycode to handle
+ * @param ctrl
+ * Was the ctrl key pressed?
+ * @param shift
+ * Was the shift key pressed?
+ * @return Return true if the key press was handled by the method, else
+ * return false.
+ */
+ protected boolean handleNavigationDayMode(int keycode, boolean ctrl,
+ boolean shift) {
+
+ // Ctrl key is not in use
+ if (ctrl) {
+ return false;
+ }
+
+ /*
+ * Jumps to the next day.
+ */
+ if (keycode == getForwardKey() && !shift) {
+ // Calculate new showing value
+
+ Date newCurrentDate = (Date) focusedDate.clone();
+
+ newCurrentDate.setDate(newCurrentDate.getDate() + 1);
+
+ if (newCurrentDate.getMonth() == focusedDate.getMonth()) {
+ // Month did not change, only move the selection
+ focusDay(newCurrentDate);
+ } else {
+ // If the month changed we need to re-render the calendar
+ focusedDate.setDate(focusedDate.getDate() + 1);
+ renderCalendar();
+ }
+
+ return true;
+
+ /*
+ * Jumps to the previous day
+ */
+ } else if (keycode == getBackwardKey() && !shift) {
+ // Calculate new showing value
+ Date newCurrentDate = (Date) focusedDate.clone();
+ newCurrentDate.setDate(newCurrentDate.getDate() - 1);
+
+ if (newCurrentDate.getMonth() == focusedDate.getMonth()) {
+ // Month did not change, only move the selection
+ focusDay(newCurrentDate);
+ } else {
+ // If the month changed we need to re-render the calendar
+ focusedDate.setDate(focusedDate.getDate() - 1);
+ renderCalendar();
+ }
+
+ return true;
+
+ /*
+ * Jumps one week back in the calendar
+ */
+ } else if (keycode == getPreviousKey() && !shift) {
+ // Calculate new showing value
+ Date newCurrentDate = (Date) focusedDate.clone();
+ newCurrentDate.setDate(newCurrentDate.getDate() - 7);
+
+ if (newCurrentDate.getMonth() == focusedDate.getMonth()
+ && focusedRow > 1) {
+ // Month did not change, only move the selection
+ focusDay(newCurrentDate);
+ } else {
+ // If the month changed we need to re-render the calendar
+ focusedDate = newCurrentDate;
+ renderCalendar();
+ }
+
+ return true;
+
+ /*
+ * Jumps one week forward in the calendar
+ */
+ } else if (keycode == getNextKey() && !ctrl && !shift) {
+ // Calculate new showing value
+ Date newCurrentDate = (Date) focusedDate.clone();
+ newCurrentDate.setDate(newCurrentDate.getDate() + 7);
+
+ if (newCurrentDate.getMonth() == focusedDate.getMonth()) {
+ // Month did not change, only move the selection
+ focusDay(newCurrentDate);
+ } else {
+ // If the month changed we need to re-render the calendar
+ focusedDate = newCurrentDate;
+ renderCalendar();
+
+ }
+
+ return true;
+
+ /*
+ * Selects the value that is chosen
+ */
+ } else if (keycode == getSelectKey() && !shift) {
+ selectFocused();
+ onSubmit(); // submit
+ return true;
+ } else if (keycode == getCloseKey()) {
+ onCancel();
+ // TODO close event
+
+ return true;
+
+ /*
+ * Jumps to the next month
+ */
+ } else if (shift && keycode == getForwardKey()) {
+ focusNextMonth();
+ return true;
+
+ /*
+ * Jumps to the previous month
+ */
+ } else if (shift && keycode == getBackwardKey()) {
+ focusPreviousMonth();
+ return true;
+
+ /*
+ * Jumps to the next year
+ */
+ } else if (shift && keycode == getPreviousKey()) {
+ focusNextYear(1);
+ return true;
+
+ /*
+ * Jumps to the previous year
+ */
+ } else if (shift && keycode == getNextKey()) {
+ focusPreviousYear(1);
+ return true;
+
+ /*
+ * Resets the selection
+ */
+ } else if (keycode == getResetKey() && !shift) {
+ // Restore showing value the selected value
+ focusedDate.setTime(value.getTime());
+ renderCalendar();
+ return true;
+ }
+
+ return false;
+ }
+
+ /**
+ * Handles the keyboard navigation
+ *
+ * @param keycode
+ * The key code that was pressed
+ * @param ctrl
+ * Was the ctrl key pressed
+ * @param shift
+ * Was the shift key pressed
+ * @return Return true if key press was handled by the component, else
+ * return false
+ */
+ protected boolean handleNavigation(int keycode, boolean ctrl, boolean shift) {
+ if (!isEnabled() || isReadonly()) {
+ return false;
+ }
+
+ else if (resolution == VDateField.RESOLUTION_YEAR) {
+ return handleNavigationYearMode(keycode, ctrl, shift);
+ }
+
+ else if (resolution == VDateField.RESOLUTION_MONTH) {
+ return handleNavigationMonthMode(keycode, ctrl, shift);
+ }
+
+ else if (resolution == VDateField.RESOLUTION_DAY) {
+ return handleNavigationDayMode(keycode, ctrl, shift);
+ }
+
+ else {
+ return handleNavigationDayMode(keycode, ctrl, shift);
+ }
+
+ }
+
+ /**
+ * Returns the reset key which will reset the calendar to the previous
+ * selection. By default this is backspace but it can be overriden to change
+ * the key to whatever you want.
+ *
+ * @return
+ */
+ protected int getResetKey() {
+ return KeyCodes.KEY_BACKSPACE;
+ }
+
+ /**
+ * Returns the select key which selects the value. By default this is the
+ * enter key but it can be changed to whatever you like by overriding this
+ * method.
+ *
+ * @return
+ */
+ protected int getSelectKey() {
+ return KeyCodes.KEY_ENTER;
+ }
+
+ /**
+ * Returns the key that closes the popup window if this is a VPopopCalendar.
+ * Else this does nothing. By default this is the Escape key but you can
+ * change the key to whatever you want by overriding this method.
+ *
+ * @return
+ */
+ protected int getCloseKey() {
+ return KeyCodes.KEY_ESCAPE;
+ }
+
+ /**
+ * The key that selects the next day in the calendar. By default this is the
+ * right arrow key but by overriding this method it can be changed to
+ * whatever you like.
+ *
+ * @return
+ */
+ protected int getForwardKey() {
+ return KeyCodes.KEY_RIGHT;
+ }
+
+ /**
+ * The key that selects the previous day in the calendar. By default this is
+ * the left arrow key but by overriding this method it can be changed to
+ * whatever you like.
+ *
+ * @return
+ */
+ protected int getBackwardKey() {
+ return KeyCodes.KEY_LEFT;
+ }
+
+ /**
+ * The key that selects the next week in the calendar. By default this is
+ * the down arrow key but by overriding this method it can be changed to
+ * whatever you like.
+ *
+ * @return
+ */
+ protected int getNextKey() {
+ return KeyCodes.KEY_DOWN;
+ }
+
+ /**
+ * The key that selects the previous week in the calendar. By default this
+ * is the up arrow key but by overriding this method it can be changed to
+ * whatever you like.
+ *
+ * @return
+ */
+ protected int getPreviousKey() {
+ return KeyCodes.KEY_UP;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see
+ * com.google.gwt.event.dom.client.MouseOutHandler#onMouseOut(com.google
+ * .gwt.event.dom.client.MouseOutEvent)
+ */
+ public void onMouseOut(MouseOutEvent event) {
+ if (mouseTimer != null) {
+ mouseTimer.cancel();
+ }
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see
+ * com.google.gwt.event.dom.client.MouseDownHandler#onMouseDown(com.google
+ * .gwt.event.dom.client.MouseDownEvent)
+ */
+ public void onMouseDown(MouseDownEvent event) {
+ // Allow user to click-n-hold for fast-forward or fast-rewind.
+ // Timer is first used for a 500ms delay after mousedown. After that has
+ // elapsed, another timer is triggered to go off every 150ms. Both
+ // timers are cancelled on mouseup or mouseout.
+ if (event.getSource() instanceof VEventButton) {
- final Widget sender = (Widget) event.getSource();
++ final VEventButton sender = (VEventButton) event.getSource();
+ processClickEvent(sender);
+ mouseTimer = new Timer() {
+ @Override
+ public void run() {
+ mouseTimer = new Timer() {
+ @Override
+ public void run() {
+ processClickEvent(sender);
+ }
+ };
+ mouseTimer.scheduleRepeating(150);
+ }
+ };
+ mouseTimer.schedule(500);
+ }
+
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see
+ * com.google.gwt.event.dom.client.MouseUpHandler#onMouseUp(com.google.gwt
+ * .event.dom.client.MouseUpEvent)
+ */
+ public void onMouseUp(MouseUpEvent event) {
+ if (mouseTimer != null) {
+ mouseTimer.cancel();
+ }
+ }
+
+ /**
+ * Sets the data of the Panel.
+ *
+ * @param currentDate
+ * The date to set
+ */
+ public void setDate(Date currentDate) {
+
+ // Check that we are not re-rendering an already active date
+ if (currentDate == value && currentDate != null) {
+ return;
+ }
+
+ Date oldDisplayedMonth = displayedMonth;
+ value = currentDate;
+
+ if (value == null) {
+ focusedDate = displayedMonth = null;
+ } else {
+ focusedDate = (Date) value.clone();
+ displayedMonth = (Date) value.clone();
+ }
+
+ // Re-render calendar if month or year of focused date has changed
+ if (oldDisplayedMonth == null || value == null
+ || oldDisplayedMonth.getYear() != value.getYear()
+ || oldDisplayedMonth.getMonth() != value.getMonth()) {
+ renderCalendar();
+ } else {
+ focusDay(currentDate);
+ selectFocused();
+ }
+
+ if (!hasFocus) {
+ focusDay((Date) null);
+ }
+ }
+
+ /**
+ * TimeSelector is a widget consisting of list boxes that modifie the Date
+ * object that is given for.
+ *
+ */
+ public class VTime extends FlowPanel implements ChangeHandler {
+
+ private ListBox hours;
+
+ private ListBox mins;
+
+ private ListBox sec;
+
- private ListBox msec;
-
+ private ListBox ampm;
+
+ /**
+ * Constructor
+ */
+ public VTime() {
+ super();
+ setStyleName(VDateField.CLASSNAME + "-time");
+ buildTime();
+ }
+
+ private ListBox createListBox() {
+ ListBox lb = new ListBox();
+ lb.setStyleName(VNativeSelect.CLASSNAME);
+ lb.addChangeHandler(this);
+ lb.addBlurHandler(VCalendarPanel.this);
+ lb.addFocusHandler(VCalendarPanel.this);
+ return lb;
+ }
+
+ /**
+ * Constructs the ListBoxes and updates their value
+ *
+ * @param redraw
+ * Should new instances of the listboxes be created
+ */
+ private void buildTime() {
+ clear();
+
+ hours = createListBox();
+ if (getDateTimeService().isTwelveHourClock()) {
+ hours.addItem("12");
+ for (int i = 1; i < 12; i++) {
+ hours.addItem((i < 10) ? "0" + i : "" + i);
+ }
+ } else {
+ for (int i = 0; i < 24; i++) {
+ hours.addItem((i < 10) ? "0" + i : "" + i);
+ }
+ }
+
+ hours.addChangeHandler(this);
+ if (getDateTimeService().isTwelveHourClock()) {
+ ampm = createListBox();
+ final String[] ampmText = getDateTimeService().getAmPmStrings();
+ ampm.addItem(ampmText[0]);
+ ampm.addItem(ampmText[1]);
+ ampm.addChangeHandler(this);
+ }
+
+ if (getResolution() >= VDateField.RESOLUTION_MIN) {
+ mins = createListBox();
+ for (int i = 0; i < 60; i++) {
+ mins.addItem((i < 10) ? "0" + i : "" + i);
+ }
+ mins.addChangeHandler(this);
+ }
+ if (getResolution() >= VDateField.RESOLUTION_SEC) {
+ sec = createListBox();
+ for (int i = 0; i < 60; i++) {
+ sec.addItem((i < 10) ? "0" + i : "" + i);
+ }
+ sec.addChangeHandler(this);
+ }
- if (getResolution() == VDateField.RESOLUTION_MSEC) {
- msec = createListBox();
- for (int i = 0; i < 1000; i++) {
- if (i < 10) {
- msec.addItem("00" + i);
- } else if (i < 100) {
- msec.addItem("0" + i);
- } else {
- msec.addItem("" + i);
- }
- }
- msec.addChangeHandler(this);
- }
+
+ final String delimiter = getDateTimeService().getClockDelimeter();
+ if (isReadonly()) {
+ int h = 0;
+ if (value != null) {
+ h = value.getHours();
+ }
+ if (getDateTimeService().isTwelveHourClock()) {
+ h -= h < 12 ? 0 : 12;
+ }
+ add(new VLabel(h < 10 ? "0" + h : "" + h));
+ } else {
+ add(hours);
+ }
+
+ if (getResolution() >= VDateField.RESOLUTION_MIN) {
+ add(new VLabel(delimiter));
+ if (isReadonly()) {
+ final int m = mins.getSelectedIndex();
+ add(new VLabel(m < 10 ? "0" + m : "" + m));
+ } else {
+ add(mins);
+ }
+ }
+ if (getResolution() >= VDateField.RESOLUTION_SEC) {
+ add(new VLabel(delimiter));
+ if (isReadonly()) {
+ final int s = sec.getSelectedIndex();
+ add(new VLabel(s < 10 ? "0" + s : "" + s));
+ } else {
+ add(sec);
+ }
+ }
- if (getResolution() == VDateField.RESOLUTION_MSEC) {
- add(new VLabel("."));
- if (isReadonly()) {
- final int m = getMilliseconds();
- final String ms = m < 100 ? "0" + m : "" + m;
- add(new VLabel(m < 10 ? "0" + ms : ms));
- } else {
- add(msec);
- }
- }
+ if (getResolution() == VDateField.RESOLUTION_HOUR) {
+ add(new VLabel(delimiter + "00")); // o'clock
+ }
+ if (getDateTimeService().isTwelveHourClock()) {
+ add(new VLabel(" "));
+ if (isReadonly()) {
+ int i = 0;
+ if (value != null) {
+ i = (value.getHours() < 12) ? 0 : 1;
+ }
+ add(new VLabel(ampm.getItemText(i)));
+ } else {
+ add(ampm);
+ }
+ }
+
+ if (isReadonly()) {
+ return;
+ }
+
+ // Update times
+ updateTimes();
+
+ ListBox lastDropDown = getLastDropDown();
+ lastDropDown.addKeyDownHandler(new KeyDownHandler() {
+ public void onKeyDown(KeyDownEvent event) {
+ boolean shiftKey = event.getNativeEvent().getShiftKey();
+ if (shiftKey) {
+ return;
+ } else {
+ int nativeKeyCode = event.getNativeKeyCode();
+ if (nativeKeyCode == KeyCodes.KEY_TAB) {
+ onTabOut(event);
+ }
+ }
+ }
+ });
+
+ }
+
+ private ListBox getLastDropDown() {
+ int i = getWidgetCount() - 1;
+ while (i >= 0) {
+ Widget widget = getWidget(i);
+ if (widget instanceof ListBox) {
+ return (ListBox) widget;
+ }
+ i--;
+ }
+ return null;
+ }
+
+ /**
+ * Updates the valus to correspond to the values in value
+ */
+ public void updateTimes() {
+ boolean selected = true;
+ if (value == null) {
+ value = new Date();
+ selected = false;
+ }
+ if (getDateTimeService().isTwelveHourClock()) {
+ int h = value.getHours();
+ ampm.setSelectedIndex(h < 12 ? 0 : 1);
+ h -= ampm.getSelectedIndex() * 12;
+ hours.setSelectedIndex(h);
+ } else {
+ hours.setSelectedIndex(value.getHours());
+ }
+ if (getResolution() >= VDateField.RESOLUTION_MIN) {
+ mins.setSelectedIndex(value.getMinutes());
+ }
+ if (getResolution() >= VDateField.RESOLUTION_SEC) {
+ sec.setSelectedIndex(value.getSeconds());
+ }
- if (getResolution() == VDateField.RESOLUTION_MSEC) {
- if (selected) {
- msec.setSelectedIndex(getMilliseconds());
- } else {
- msec.setSelectedIndex(0);
- }
- }
+ if (getDateTimeService().isTwelveHourClock()) {
+ ampm.setSelectedIndex(value.getHours() < 12 ? 0 : 1);
+ }
+
+ hours.setEnabled(isEnabled());
+ if (mins != null) {
+ mins.setEnabled(isEnabled());
+ }
+ if (sec != null) {
+ sec.setEnabled(isEnabled());
+ }
- if (msec != null) {
- msec.setEnabled(isEnabled());
- }
+ if (ampm != null) {
+ ampm.setEnabled(isEnabled());
+ }
+
+ }
+
+ private int getMilliseconds() {
+ return DateTimeService.getMilliseconds(value);
+ }
+
+ private DateTimeService getDateTimeService() {
+ if (dateTimeService == null) {
+ dateTimeService = new DateTimeService();
+ }
+ return dateTimeService;
+ }
+
+ /*
+ * (non-Javadoc) VT
+ *
+ * @see
+ * com.google.gwt.event.dom.client.ChangeHandler#onChange(com.google.gwt
+ * .event.dom.client.ChangeEvent)
+ */
+ public void onChange(ChangeEvent event) {
+ /*
+ * Value from dropdowns gets always set for the value. Like year and
+ * month when resolution is month or year.
+ */
+ if (event.getSource() == hours) {
+ int h = hours.getSelectedIndex();
+ if (getDateTimeService().isTwelveHourClock()) {
+ h = h + ampm.getSelectedIndex() * 12;
+ }
+ value.setHours(h);
+ if (timeChangeListener != null) {
+ timeChangeListener.changed(h, value.getMinutes(),
+ value.getSeconds(),
+ DateTimeService.getMilliseconds(value));
+ }
+ event.preventDefault();
+ event.stopPropagation();
+ } else if (event.getSource() == mins) {
+ final int m = mins.getSelectedIndex();
+ value.setMinutes(m);
+ if (timeChangeListener != null) {
+ timeChangeListener.changed(value.getHours(), m,
+ value.getSeconds(),
+ DateTimeService.getMilliseconds(value));
+ }
+ event.preventDefault();
+ event.stopPropagation();
+ } else if (event.getSource() == sec) {
+ final int s = sec.getSelectedIndex();
+ value.setSeconds(s);
+ if (timeChangeListener != null) {
+ timeChangeListener.changed(value.getHours(),
+ value.getMinutes(), s,
+ DateTimeService.getMilliseconds(value));
+ }
+ event.preventDefault();
+ event.stopPropagation();
- } else if (event.getSource() == msec) {
- final int ms = msec.getSelectedIndex();
- DateTimeService.setMilliseconds(value, ms);
- if (timeChangeListener != null) {
- timeChangeListener.changed(value.getHours(),
- value.getMinutes(), value.getSeconds(), ms);
- }
- event.preventDefault();
- event.stopPropagation();
+ } else if (event.getSource() == ampm) {
+ final int h = hours.getSelectedIndex()
+ + (ampm.getSelectedIndex() * 12);
+ value.setHours(h);
+ if (timeChangeListener != null) {
+ timeChangeListener.changed(h, value.getMinutes(),
+ value.getSeconds(),
+ DateTimeService.getMilliseconds(value));
+ }
+ event.preventDefault();
+ event.stopPropagation();
+ }
+ }
+
+ }
+
+ /**
+ * A widget representing a single day in the calendar panel.
+ */
+ private class Day extends InlineHTML {
+ private static final String BASECLASS = VDateField.CLASSNAME
+ + "-calendarpanel-day";
+ private final Date date;
+
+ Day(Date date) {
+ super("" + date.getDate());
+ setStyleName(BASECLASS);
+ this.date = date;
+ addClickHandler(dayClickHandler);
+ }
+
+ public Date getDate() {
+ return date;
+ }
+ }
+
+ public Date getDate() {
+ return value;
+ }
+
+ /**
+ * If true should be returned if the panel will not be used after this
+ * event.
+ *
+ * @param event
+ * @return
+ */
+ protected boolean onTabOut(DomEvent<?> event) {
+ if (focusOutListener != null) {
+ return focusOutListener.onFocusOut(event);
+ }
+ return false;
+ }
+
+ /**
+ * A focus out listener is triggered when the panel loosed focus. This can
+ * happen either after a user clicks outside the panel or tabs out.
+ *
+ * @param listener
+ * The listener to trigger
+ */
+ public void setFocusOutListener(FocusOutListener listener) {
+ focusOutListener = listener;
+ }
+
+ /**
+ * The submit listener is called when the user selects a value from the
+ * calender either by clicking the day or selects it by keyboard.
+ *
+ * @param submitListener
+ * The listener to trigger
+ */
+ public void setSubmitListener(SubmitListener submitListener) {
+ this.submitListener = submitListener;
+ }
+
+ /**
+ * The given FocusChangeListener is notified when the focused date changes
+ * by user either clicking on a new date or by using the keyboard.
+ *
+ * @param listener
+ * The FocusChangeListener to be notified
+ */
+ public void setFocusChangeListener(FocusChangeListener listener) {
+ focusChangeListener = listener;
+ }
+
+ /**
+ * The time change listener is triggered when the user changes the time.
+ *
+ * @param listener
+ */
+ public void setTimeChangeListener(TimeChangeListener listener) {
+ timeChangeListener = listener;
+ }
+
+ /**
+ * Returns the submit listener that listens to selection made from the panel
+ *
+ * @return The listener or NULL if no listener has been set
+ */
+ public SubmitListener getSubmitListener() {
+ return submitListener;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see
+ * com.google.gwt.event.dom.client.BlurHandler#onBlur(com.google.gwt.event
+ * .dom.client.BlurEvent)
+ */
+ public void onBlur(final BlurEvent event) {
+ if (event.getSource() instanceof VCalendarPanel) {
+ hasFocus = false;
+ focusDay(null);
+ }
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see
+ * com.google.gwt.event.dom.client.FocusHandler#onFocus(com.google.gwt.event
+ * .dom.client.FocusEvent)
+ */
+ public void onFocus(FocusEvent event) {
+ if (event.getSource() instanceof VCalendarPanel) {
+ hasFocus = true;
+
+ // Focuses the current day if the calendar shows the days
+ if (focusedDay != null) {
+ focusDay(focusedDate);
+ }
+ }
+ }
+
+ private static final String SUBPART_NEXT_MONTH = "nextmon";
+ private static final String SUBPART_PREV_MONTH = "prevmon";
+
+ private static final String SUBPART_NEXT_YEAR = "nexty";
+ private static final String SUBPART_PREV_YEAR = "prevy";
+ private static final String SUBPART_HOUR_SELECT = "h";
+ private static final String SUBPART_MINUTE_SELECT = "m";
+ private static final String SUBPART_SECS_SELECT = "s";
+ private static final String SUBPART_MSECS_SELECT = "ms";
+ private static final String SUBPART_AMPM_SELECT = "ampm";
+ private static final String SUBPART_DAY = "day";
+ private static final String SUBPART_MONTH_YEAR_HEADER = "header";
+
+ public String getSubPartName(Element subElement) {
+ if (contains(nextMonth, subElement)) {
+ return SUBPART_NEXT_MONTH;
+ } else if (contains(prevMonth, subElement)) {
+ return SUBPART_PREV_MONTH;
+ } else if (contains(nextYear, subElement)) {
+ return SUBPART_NEXT_YEAR;
+ } else if (contains(prevYear, subElement)) {
+ return SUBPART_PREV_YEAR;
+ } else if (contains(days, subElement)) {
+ // Day, find out which dayOfMonth and use that as the identifier
+ Day day = Util.findWidget(subElement, Day.class);
+ if (day != null) {
+ Date date = day.getDate();
+ int id = date.getDate();
+ // Zero or negative ids map to days of the preceding month,
+ // past-the-end-of-month ids to days of the following month
+ if (date.getMonth() < displayedMonth.getMonth()) {
+ id -= DateTimeService.getNumberOfDaysInMonth(date);
+ } else if (date.getMonth() > displayedMonth.getMonth()) {
+ id += DateTimeService
+ .getNumberOfDaysInMonth(displayedMonth);
+ }
+ return SUBPART_DAY + id;
+ }
+ } else if (time != null) {
+ if (contains(time.hours, subElement)) {
+ return SUBPART_HOUR_SELECT;
+ } else if (contains(time.mins, subElement)) {
+ return SUBPART_MINUTE_SELECT;
+ } else if (contains(time.sec, subElement)) {
+ return SUBPART_SECS_SELECT;
- } else if (contains(time.msec, subElement)) {
- return SUBPART_MSECS_SELECT;
+ } else if (contains(time.ampm, subElement)) {
+ return SUBPART_AMPM_SELECT;
+
+ }
+ } else if (getCellFormatter().getElement(0, 2).isOrHasChild(subElement)) {
+ return SUBPART_MONTH_YEAR_HEADER;
+ }
+
+ return null;
+ }
+
+ /**
+ * Checks if subElement is inside the widget DOM hierarchy.
+ *
+ * @param w
+ * @param subElement
+ * @return true if {@code w} is a parent of subElement, false otherwise.
+ */
+ private boolean contains(Widget w, Element subElement) {
+ if (w == null || w.getElement() == null) {
+ return false;
+ }
+
+ return w.getElement().isOrHasChild(subElement);
+ }
+
+ public Element getSubPartElement(String subPart) {
+ if (SUBPART_NEXT_MONTH.equals(subPart)) {
+ return nextMonth.getElement();
+ }
+ if (SUBPART_PREV_MONTH.equals(subPart)) {
+ return prevMonth.getElement();
+ }
+ if (SUBPART_NEXT_YEAR.equals(subPart)) {
+ return nextYear.getElement();
+ }
+ if (SUBPART_PREV_YEAR.equals(subPart)) {
+ return prevYear.getElement();
+ }
+ if (SUBPART_HOUR_SELECT.equals(subPart)) {
+ return time.hours.getElement();
+ }
+ if (SUBPART_MINUTE_SELECT.equals(subPart)) {
+ return time.mins.getElement();
+ }
+ if (SUBPART_SECS_SELECT.equals(subPart)) {
+ return time.sec.getElement();
+ }
- if (SUBPART_MSECS_SELECT.equals(subPart)) {
- return time.msec.getElement();
- }
+ if (SUBPART_AMPM_SELECT.equals(subPart)) {
+ return time.ampm.getElement();
+ }
+ if (subPart.startsWith(SUBPART_DAY)) {
+ // Zero or negative ids map to days in the preceding month,
+ // past-the-end-of-month ids to days in the following month
+ int dayOfMonth = Integer.parseInt(subPart.substring(SUBPART_DAY
+ .length()));
+ Date date = new Date(displayedMonth.getYear(),
+ displayedMonth.getMonth(), dayOfMonth);
+ Iterator<Widget> iter = days.iterator();
+ while (iter.hasNext()) {
+ Widget w = iter.next();
+ if (w instanceof Day) {
+ Day day = (Day) w;
+ if (day.getDate().equals(date)) {
+ return day.getElement();
+ }
+ }
+ }
+ }
+
+ if (SUBPART_MONTH_YEAR_HEADER.equals(subPart)) {
+ return (Element) getCellFormatter().getElement(0, 2).getChild(0);
+ }
+ return null;
+ }
+
+ @Override
+ protected void onDetach() {
+ super.onDetach();
+ if (mouseTimer != null) {
+ mouseTimer.cancel();
+ }
+ }
+ }
--- /dev/null
- package com.vaadin.terminal.gwt.client.ui;\r
- \r
- import com.google.gwt.core.client.GWT;\r
- import com.google.gwt.user.client.DOM;\r
- import com.google.gwt.user.client.Event;\r
- import com.google.gwt.user.client.ui.Widget;\r
- import com.vaadin.terminal.gwt.client.ApplicationConnection;\r
- import com.vaadin.terminal.gwt.client.EventHelper;\r
- import com.vaadin.terminal.gwt.client.UIDL;\r
- import com.vaadin.terminal.gwt.client.VTooltip;\r
- \r
- public class VCheckBoxPaintable extends VAbstractPaintableWidget {\r
- \r
- public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {\r
- // Save details\r
- getWidgetForPaintable().client = client;\r
- getWidgetForPaintable().id = uidl.getId();\r
- \r
- // Ensure correct implementation\r
- if (client.updateComponent(this, uidl, false)) {\r
- return;\r
- }\r
- \r
- getWidgetForPaintable().focusHandlerRegistration = EventHelper\r
- .updateFocusHandler(this, client,\r
- getWidgetForPaintable().focusHandlerRegistration);\r
- getWidgetForPaintable().blurHandlerRegistration = EventHelper\r
- .updateBlurHandler(this, client,\r
- getWidgetForPaintable().blurHandlerRegistration);\r
- \r
- if (uidl.hasAttribute("error")) {\r
- if (getWidgetForPaintable().errorIndicatorElement == null) {\r
- getWidgetForPaintable().errorIndicatorElement = DOM\r
- .createSpan();\r
- getWidgetForPaintable().errorIndicatorElement\r
- .setInnerHTML(" ");\r
- DOM.setElementProperty(\r
- getWidgetForPaintable().errorIndicatorElement,\r
- "className", "v-errorindicator");\r
- DOM.appendChild(getWidgetForPaintable().getElement(),\r
- getWidgetForPaintable().errorIndicatorElement);\r
- DOM.sinkEvents(getWidgetForPaintable().errorIndicatorElement,\r
- VTooltip.TOOLTIP_EVENTS | Event.ONCLICK);\r
- } else {\r
- DOM.setStyleAttribute(\r
- getWidgetForPaintable().errorIndicatorElement,\r
- "display", "");\r
- }\r
- } else if (getWidgetForPaintable().errorIndicatorElement != null) {\r
- DOM.setStyleAttribute(\r
- getWidgetForPaintable().errorIndicatorElement, "display",\r
- "none");\r
- }\r
- \r
- if (uidl.hasAttribute("readonly")) {\r
- getWidgetForPaintable().setEnabled(false);\r
- }\r
- \r
- if (uidl.hasAttribute("icon")) {\r
- if (getWidgetForPaintable().icon == null) {\r
- getWidgetForPaintable().icon = new Icon(client);\r
- DOM.insertChild(getWidgetForPaintable().getElement(),\r
- getWidgetForPaintable().icon.getElement(), 1);\r
- getWidgetForPaintable().icon\r
- .sinkEvents(VTooltip.TOOLTIP_EVENTS);\r
- getWidgetForPaintable().icon.sinkEvents(Event.ONCLICK);\r
- }\r
- getWidgetForPaintable().icon\r
- .setUri(uidl.getStringAttribute("icon"));\r
- } else if (getWidgetForPaintable().icon != null) {\r
- // detach icon\r
- DOM.removeChild(getWidgetForPaintable().getElement(),\r
- getWidgetForPaintable().icon.getElement());\r
- getWidgetForPaintable().icon = null;\r
- }\r
- \r
- // Set text\r
- getWidgetForPaintable().setText(uidl.getStringAttribute("caption"));\r
- getWidgetForPaintable()\r
- .setValue(\r
- uidl.getBooleanVariable(getWidgetForPaintable().VARIABLE_STATE));\r
- getWidgetForPaintable().immediate = uidl\r
- .getBooleanAttribute("immediate");\r
- }\r
- \r
- @Override\r
- public VCheckBox getWidgetForPaintable() {\r
- return (VCheckBox) super.getWidgetForPaintable();\r
- }\r
- \r
- @Override\r
- protected Widget createWidget() {\r
- return GWT.create(VCheckBox.class);\r
- }\r
- \r
- }\r
++package com.vaadin.terminal.gwt.client.ui;
++
++import com.google.gwt.core.client.GWT;
++import com.google.gwt.user.client.DOM;
++import com.google.gwt.user.client.Event;
++import com.google.gwt.user.client.ui.Widget;
++import com.vaadin.terminal.gwt.client.ApplicationConnection;
++import com.vaadin.terminal.gwt.client.EventHelper;
++import com.vaadin.terminal.gwt.client.UIDL;
++import com.vaadin.terminal.gwt.client.VTooltip;
++
++public class VCheckBoxPaintable extends VAbstractPaintableWidget {
++
++ public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {
++ // Save details
++ getWidgetForPaintable().client = client;
++ getWidgetForPaintable().id = uidl.getId();
++
++ // Ensure correct implementation
++ if (client.updateComponent(this, uidl, false)) {
++ return;
++ }
++
++ getWidgetForPaintable().focusHandlerRegistration = EventHelper
++ .updateFocusHandler(this, client,
++ getWidgetForPaintable().focusHandlerRegistration);
++ getWidgetForPaintable().blurHandlerRegistration = EventHelper
++ .updateBlurHandler(this, client,
++ getWidgetForPaintable().blurHandlerRegistration);
++
++ if (uidl.hasAttribute("error")) {
++ if (getWidgetForPaintable().errorIndicatorElement == null) {
++ getWidgetForPaintable().errorIndicatorElement = DOM
++ .createSpan();
++ getWidgetForPaintable().errorIndicatorElement
++ .setInnerHTML(" ");
++ DOM.setElementProperty(
++ getWidgetForPaintable().errorIndicatorElement,
++ "className", "v-errorindicator");
++ DOM.appendChild(getWidgetForPaintable().getElement(),
++ getWidgetForPaintable().errorIndicatorElement);
++ DOM.sinkEvents(getWidgetForPaintable().errorIndicatorElement,
++ VTooltip.TOOLTIP_EVENTS | Event.ONCLICK);
++ } else {
++ DOM.setStyleAttribute(
++ getWidgetForPaintable().errorIndicatorElement,
++ "display", "");
++ }
++ } else if (getWidgetForPaintable().errorIndicatorElement != null) {
++ DOM.setStyleAttribute(
++ getWidgetForPaintable().errorIndicatorElement, "display",
++ "none");
++ }
++
++ if (uidl.hasAttribute("readonly")) {
++ getWidgetForPaintable().setEnabled(false);
++ }
++
++ if (uidl.hasAttribute("icon")) {
++ if (getWidgetForPaintable().icon == null) {
++ getWidgetForPaintable().icon = new Icon(client);
++ DOM.insertChild(getWidgetForPaintable().getElement(),
++ getWidgetForPaintable().icon.getElement(), 1);
++ getWidgetForPaintable().icon
++ .sinkEvents(VTooltip.TOOLTIP_EVENTS);
++ getWidgetForPaintable().icon.sinkEvents(Event.ONCLICK);
++ }
++ getWidgetForPaintable().icon
++ .setUri(uidl.getStringAttribute("icon"));
++ } else if (getWidgetForPaintable().icon != null) {
++ // detach icon
++ DOM.removeChild(getWidgetForPaintable().getElement(),
++ getWidgetForPaintable().icon.getElement());
++ getWidgetForPaintable().icon = null;
++ }
++
++ // Set text
++ getWidgetForPaintable().setText(uidl.getStringAttribute("caption"));
++ getWidgetForPaintable()
++ .setValue(
++ uidl.getBooleanVariable(getWidgetForPaintable().VARIABLE_STATE));
++ getWidgetForPaintable().immediate = uidl
++ .getBooleanAttribute("immediate");
++ }
++
++ @Override
++ public VCheckBox getWidgetForPaintable() {
++ return (VCheckBox) super.getWidgetForPaintable();
++ }
++
++ @Override
++ protected Widget createWidget() {
++ return GWT.create(VCheckBox.class);
++ }
++
++}
--- /dev/null
- package com.vaadin.terminal.gwt.client.ui;\r
- \r
- import com.google.gwt.core.client.GWT;\r
- import com.google.gwt.event.dom.client.DomEvent.Type;\r
- import com.google.gwt.event.shared.EventHandler;\r
- import com.google.gwt.event.shared.HandlerRegistration;\r
- import com.google.gwt.user.client.Element;\r
- import com.google.gwt.user.client.ui.Widget;\r
- import com.vaadin.terminal.gwt.client.ApplicationConnection;\r
- import com.vaadin.terminal.gwt.client.EventId;\r
- import com.vaadin.terminal.gwt.client.UIDL;\r
- import com.vaadin.terminal.gwt.client.VPaintableWidget;\r
- \r
- public class VCssLayoutPaintable extends VAbstractPaintableWidgetContainer {\r
- \r
- private LayoutClickEventHandler clickEventHandler = new LayoutClickEventHandler(\r
- this, EventId.LAYOUT_CLICK) {\r
- \r
- @Override\r
- protected VPaintableWidget getChildComponent(Element element) {\r
- return getWidgetForPaintable().panel.getComponent(element);\r
- }\r
- \r
- @Override\r
- protected <H extends EventHandler> HandlerRegistration registerHandler(\r
- H handler, Type<H> type) {\r
- return getWidgetForPaintable().addDomHandler(handler, type);\r
- }\r
- };\r
- \r
- public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {\r
- getWidgetForPaintable().rendering = true;\r
- \r
- if (client.updateComponent(this, uidl, true)) {\r
- getWidgetForPaintable().rendering = false;\r
- return;\r
- }\r
- clickEventHandler.handleEventHandlerRegistration(client);\r
- \r
- getWidgetForPaintable().setMarginAndSpacingStyles(\r
- new VMarginInfo(uidl.getIntAttribute("margins")),\r
- uidl.hasAttribute("spacing"));\r
- getWidgetForPaintable().panel.updateFromUIDL(uidl, client);\r
- getWidgetForPaintable().rendering = false;\r
- }\r
- \r
- @Override\r
- public VCssLayout getWidgetForPaintable() {\r
- return (VCssLayout) super.getWidgetForPaintable();\r
- }\r
- \r
- @Override\r
- protected Widget createWidget() {\r
- return GWT.create(VCssLayout.class);\r
- }\r
- \r
- public void updateCaption(VPaintableWidget component, UIDL uidl) {\r
- getWidgetForPaintable().panel.updateCaption(component, uidl);\r
- }\r
- \r
- }\r
++package com.vaadin.terminal.gwt.client.ui;
++
++import com.google.gwt.core.client.GWT;
++import com.google.gwt.event.dom.client.DomEvent.Type;
++import com.google.gwt.event.shared.EventHandler;
++import com.google.gwt.event.shared.HandlerRegistration;
++import com.google.gwt.user.client.Element;
++import com.google.gwt.user.client.ui.Widget;
++import com.vaadin.terminal.gwt.client.ApplicationConnection;
++import com.vaadin.terminal.gwt.client.EventId;
++import com.vaadin.terminal.gwt.client.UIDL;
++import com.vaadin.terminal.gwt.client.VPaintableWidget;
++
++public class VCssLayoutPaintable extends VAbstractPaintableWidgetContainer {
++
++ private LayoutClickEventHandler clickEventHandler = new LayoutClickEventHandler(
++ this, EventId.LAYOUT_CLICK) {
++
++ @Override
++ protected VPaintableWidget getChildComponent(Element element) {
++ return getWidgetForPaintable().panel.getComponent(element);
++ }
++
++ @Override
++ protected <H extends EventHandler> HandlerRegistration registerHandler(
++ H handler, Type<H> type) {
++ return getWidgetForPaintable().addDomHandler(handler, type);
++ }
++ };
++
++ public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {
++ getWidgetForPaintable().rendering = true;
++
++ if (client.updateComponent(this, uidl, true)) {
++ getWidgetForPaintable().rendering = false;
++ return;
++ }
++ clickEventHandler.handleEventHandlerRegistration(client);
++
++ getWidgetForPaintable().setMarginAndSpacingStyles(
++ new VMarginInfo(uidl.getIntAttribute("margins")),
++ uidl.hasAttribute("spacing"));
++ getWidgetForPaintable().panel.updateFromUIDL(uidl, client);
++ getWidgetForPaintable().rendering = false;
++ }
++
++ @Override
++ public VCssLayout getWidgetForPaintable() {
++ return (VCssLayout) super.getWidgetForPaintable();
++ }
++
++ @Override
++ protected Widget createWidget() {
++ return GWT.create(VCssLayout.class);
++ }
++
++ public void updateCaption(VPaintableWidget component, UIDL uidl) {
++ getWidgetForPaintable().panel.updateCaption(component, uidl);
++ }
++
++}
--- /dev/null
- package com.vaadin.terminal.gwt.client.ui;\r
- \r
- import com.google.gwt.core.client.GWT;\r
- import com.google.gwt.core.client.Scheduler;\r
- import com.google.gwt.user.client.Command;\r
- import com.google.gwt.user.client.ui.Widget;\r
- import com.vaadin.terminal.gwt.client.ApplicationConnection;\r
- import com.vaadin.terminal.gwt.client.UIDL;\r
- import com.vaadin.terminal.gwt.client.VPaintableMap;\r
- import com.vaadin.terminal.gwt.client.VPaintableWidget;\r
- \r
- public class VCustomComponentPaintable extends\r
- VAbstractPaintableWidgetContainer {\r
- \r
- public void updateFromUIDL(UIDL uidl, final ApplicationConnection client) {\r
- getWidgetForPaintable().rendering = true;\r
- if (client.updateComponent(this, uidl, true)) {\r
- getWidgetForPaintable().rendering = false;\r
- return;\r
- }\r
- getWidgetForPaintable().client = client;\r
- \r
- final UIDL child = uidl.getChildUIDL(0);\r
- if (child != null) {\r
- final VPaintableWidget paintable = client.getPaintable(child);\r
- Widget widget = paintable.getWidgetForPaintable();\r
- if (widget != getWidgetForPaintable().getWidget()) {\r
- if (getWidgetForPaintable().getWidget() != null) {\r
- client.unregisterPaintable(VPaintableMap.get(client)\r
- .getPaintable(getWidgetForPaintable().getWidget()));\r
- getWidgetForPaintable().clear();\r
- }\r
- getWidgetForPaintable().setWidget(widget);\r
- }\r
- paintable.updateFromUIDL(child, client);\r
- }\r
- \r
- boolean updateDynamicSize = getWidgetForPaintable().updateDynamicSize();\r
- if (updateDynamicSize) {\r
- Scheduler.get().scheduleDeferred(new Command() {\r
- public void execute() {\r
- // FIXME deferred relative size update needed to fix some\r
- // scrollbar issues in sampler. This must be the wrong way\r
- // to do it. Might be that some other component is broken.\r
- client.handleComponentRelativeSize(getWidgetForPaintable());\r
- \r
- }\r
- });\r
- }\r
- \r
- getWidgetForPaintable().renderSpace.setWidth(getWidgetForPaintable()\r
- .getElement().getOffsetWidth());\r
- getWidgetForPaintable().renderSpace.setHeight(getWidgetForPaintable()\r
- .getElement().getOffsetHeight());\r
- \r
- /*\r
- * Needed to update client size if the size of this component has\r
- * changed and the child uses relative size(s).\r
- */\r
- client.runDescendentsLayout(getWidgetForPaintable());\r
- \r
- getWidgetForPaintable().rendering = false;\r
- }\r
- \r
- @Override\r
- protected Widget createWidget() {\r
- return GWT.create(VCustomComponent.class);\r
- }\r
- \r
- @Override\r
- public VCustomComponent getWidgetForPaintable() {\r
- return (VCustomComponent) super.getWidgetForPaintable();\r
- }\r
- \r
- public void updateCaption(VPaintableWidget component, UIDL uidl) {\r
- // NOP, custom component dont render composition roots caption\r
- }\r
- \r
- }\r
++package com.vaadin.terminal.gwt.client.ui;
++
++import com.google.gwt.core.client.GWT;
++import com.google.gwt.core.client.Scheduler;
++import com.google.gwt.user.client.Command;
++import com.google.gwt.user.client.ui.Widget;
++import com.vaadin.terminal.gwt.client.ApplicationConnection;
++import com.vaadin.terminal.gwt.client.UIDL;
++import com.vaadin.terminal.gwt.client.VPaintableMap;
++import com.vaadin.terminal.gwt.client.VPaintableWidget;
++
++public class VCustomComponentPaintable extends
++ VAbstractPaintableWidgetContainer {
++
++ public void updateFromUIDL(UIDL uidl, final ApplicationConnection client) {
++ getWidgetForPaintable().rendering = true;
++ if (client.updateComponent(this, uidl, true)) {
++ getWidgetForPaintable().rendering = false;
++ return;
++ }
++ getWidgetForPaintable().client = client;
++
++ final UIDL child = uidl.getChildUIDL(0);
++ if (child != null) {
++ final VPaintableWidget paintable = client.getPaintable(child);
++ Widget widget = paintable.getWidgetForPaintable();
++ if (widget != getWidgetForPaintable().getWidget()) {
++ if (getWidgetForPaintable().getWidget() != null) {
++ client.unregisterPaintable(VPaintableMap.get(client)
++ .getPaintable(getWidgetForPaintable().getWidget()));
++ getWidgetForPaintable().clear();
++ }
++ getWidgetForPaintable().setWidget(widget);
++ }
++ paintable.updateFromUIDL(child, client);
++ }
++
++ boolean updateDynamicSize = getWidgetForPaintable().updateDynamicSize();
++ if (updateDynamicSize) {
++ Scheduler.get().scheduleDeferred(new Command() {
++ public void execute() {
++ // FIXME deferred relative size update needed to fix some
++ // scrollbar issues in sampler. This must be the wrong way
++ // to do it. Might be that some other component is broken.
++ client.handleComponentRelativeSize(getWidgetForPaintable());
++
++ }
++ });
++ }
++
++ getWidgetForPaintable().renderSpace.setWidth(getWidgetForPaintable()
++ .getElement().getOffsetWidth());
++ getWidgetForPaintable().renderSpace.setHeight(getWidgetForPaintable()
++ .getElement().getOffsetHeight());
++
++ /*
++ * Needed to update client size if the size of this component has
++ * changed and the child uses relative size(s).
++ */
++ client.runDescendentsLayout(getWidgetForPaintable());
++
++ getWidgetForPaintable().rendering = false;
++ }
++
++ @Override
++ protected Widget createWidget() {
++ return GWT.create(VCustomComponent.class);
++ }
++
++ @Override
++ public VCustomComponent getWidgetForPaintable() {
++ return (VCustomComponent) super.getWidgetForPaintable();
++ }
++
++ public void updateCaption(VPaintableWidget component, UIDL uidl) {
++ // NOP, custom component dont render composition roots caption
++ }
++
++}
--- /dev/null
- package com.vaadin.terminal.gwt.client.ui;\r
- \r
- import java.util.HashSet;\r
- import java.util.Iterator;\r
- import java.util.Set;\r
- \r
- import com.google.gwt.core.client.GWT;\r
- import com.google.gwt.user.client.ui.Widget;\r
- import com.vaadin.terminal.gwt.client.ApplicationConnection;\r
- import com.vaadin.terminal.gwt.client.UIDL;\r
- import com.vaadin.terminal.gwt.client.VPaintableWidget;\r
- \r
- public class VCustomLayoutPaintable extends VAbstractPaintableWidgetContainer {\r
- \r
- /** Update the layout from UIDL */\r
- public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {\r
- getWidgetForPaintable().client = client;\r
- // ApplicationConnection manages generic component features\r
- if (client.updateComponent(this, uidl, true)) {\r
- return;\r
- }\r
- \r
- getWidgetForPaintable().pid = uidl.getId();\r
- if (!getWidgetForPaintable().hasTemplate()) {\r
- // Update HTML template only once\r
- getWidgetForPaintable().initializeHTML(uidl, client);\r
- }\r
- \r
- // Evaluate scripts\r
- VCustomLayout.eval(getWidgetForPaintable().scripts);\r
- getWidgetForPaintable().scripts = null;\r
- \r
- getWidgetForPaintable().iLayout();\r
- // TODO Check if this is needed\r
- client.runDescendentsLayout(getWidgetForPaintable());\r
- \r
- Set<Widget> oldWidgets = new HashSet<Widget>();\r
- oldWidgets.addAll(getWidgetForPaintable().locationToWidget.values());\r
- \r
- // For all contained widgets\r
- for (final Iterator<?> i = uidl.getChildIterator(); i.hasNext();) {\r
- final UIDL uidlForChild = (UIDL) i.next();\r
- if (uidlForChild.getTag().equals("location")) {\r
- final String location = uidlForChild.getStringAttribute("name");\r
- UIDL childUIDL = uidlForChild.getChildUIDL(0);\r
- final VPaintableWidget childPaintable = client\r
- .getPaintable(childUIDL);\r
- Widget childWidget = childPaintable.getWidgetForPaintable();\r
- try {\r
- getWidgetForPaintable().setWidget(childWidget, location);\r
- childPaintable.updateFromUIDL(childUIDL, client);\r
- } catch (final IllegalArgumentException e) {\r
- // If no location is found, this component is not visible\r
- }\r
- oldWidgets.remove(childWidget);\r
- }\r
- }\r
- for (Iterator<Widget> iterator = oldWidgets.iterator(); iterator\r
- .hasNext();) {\r
- Widget oldWidget = iterator.next();\r
- if (oldWidget.isAttached()) {\r
- // slot of this widget is emptied, remove it\r
- getWidgetForPaintable().remove(oldWidget);\r
- }\r
- }\r
- \r
- getWidgetForPaintable().iLayout();\r
- // TODO Check if this is needed\r
- client.runDescendentsLayout(getWidgetForPaintable());\r
- \r
- }\r
- \r
- @Override\r
- public VCustomLayout getWidgetForPaintable() {\r
- return (VCustomLayout) super.getWidgetForPaintable();\r
- }\r
- \r
- @Override\r
- protected Widget createWidget() {\r
- return GWT.create(VCustomLayout.class);\r
- }\r
- \r
- public void updateCaption(VPaintableWidget paintable, UIDL uidl) {\r
- getWidgetForPaintable().updateCaption(paintable, uidl);\r
- \r
- }\r
- }\r
++package com.vaadin.terminal.gwt.client.ui;
++
++import java.util.HashSet;
++import java.util.Iterator;
++import java.util.Set;
++
++import com.google.gwt.core.client.GWT;
++import com.google.gwt.user.client.ui.Widget;
++import com.vaadin.terminal.gwt.client.ApplicationConnection;
++import com.vaadin.terminal.gwt.client.UIDL;
++import com.vaadin.terminal.gwt.client.VPaintableWidget;
++
++public class VCustomLayoutPaintable extends VAbstractPaintableWidgetContainer {
++
++ /** Update the layout from UIDL */
++ public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {
++ getWidgetForPaintable().client = client;
++ // ApplicationConnection manages generic component features
++ if (client.updateComponent(this, uidl, true)) {
++ return;
++ }
++
++ getWidgetForPaintable().pid = uidl.getId();
++ if (!getWidgetForPaintable().hasTemplate()) {
++ // Update HTML template only once
++ getWidgetForPaintable().initializeHTML(uidl, client);
++ }
++
++ // Evaluate scripts
++ VCustomLayout.eval(getWidgetForPaintable().scripts);
++ getWidgetForPaintable().scripts = null;
++
++ getWidgetForPaintable().iLayout();
++ // TODO Check if this is needed
++ client.runDescendentsLayout(getWidgetForPaintable());
++
++ Set<Widget> oldWidgets = new HashSet<Widget>();
++ oldWidgets.addAll(getWidgetForPaintable().locationToWidget.values());
++
++ // For all contained widgets
++ for (final Iterator<?> i = uidl.getChildIterator(); i.hasNext();) {
++ final UIDL uidlForChild = (UIDL) i.next();
++ if (uidlForChild.getTag().equals("location")) {
++ final String location = uidlForChild.getStringAttribute("name");
++ UIDL childUIDL = uidlForChild.getChildUIDL(0);
++ final VPaintableWidget childPaintable = client
++ .getPaintable(childUIDL);
++ Widget childWidget = childPaintable.getWidgetForPaintable();
++ try {
++ getWidgetForPaintable().setWidget(childWidget, location);
++ childPaintable.updateFromUIDL(childUIDL, client);
++ } catch (final IllegalArgumentException e) {
++ // If no location is found, this component is not visible
++ }
++ oldWidgets.remove(childWidget);
++ }
++ }
++ for (Iterator<Widget> iterator = oldWidgets.iterator(); iterator
++ .hasNext();) {
++ Widget oldWidget = iterator.next();
++ if (oldWidget.isAttached()) {
++ // slot of this widget is emptied, remove it
++ getWidgetForPaintable().remove(oldWidget);
++ }
++ }
++
++ getWidgetForPaintable().iLayout();
++ // TODO Check if this is needed
++ client.runDescendentsLayout(getWidgetForPaintable());
++
++ }
++
++ @Override
++ public VCustomLayout getWidgetForPaintable() {
++ return (VCustomLayout) super.getWidgetForPaintable();
++ }
++
++ @Override
++ protected Widget createWidget() {
++ return GWT.create(VCustomLayout.class);
++ }
++
++ public void updateCaption(VPaintableWidget paintable, UIDL uidl) {
++ getWidgetForPaintable().updateCaption(paintable, uidl);
++
++ }
++}
- /* \r
- @VaadinApache2LicenseForJavaFiles@\r
- */\r
- \r
- package com.vaadin.terminal.gwt.client.ui;\r
- \r
- import java.util.Date;\r
- \r
- import com.google.gwt.event.dom.client.DomEvent;\r
- import com.vaadin.terminal.gwt.client.DateTimeService;\r
- import com.vaadin.terminal.gwt.client.ui.VCalendarPanel.FocusOutListener;\r
- import com.vaadin.terminal.gwt.client.ui.VCalendarPanel.SubmitListener;\r
- \r
- /**\r
- * A client side implementation for InlineDateField\r
- */\r
- public class VDateFieldCalendar extends VDateField {\r
- \r
- protected final VCalendarPanel calendarPanel;\r
- \r
- public VDateFieldCalendar() {\r
- super();\r
- calendarPanel = new VCalendarPanel();\r
- add(calendarPanel);\r
- calendarPanel.setSubmitListener(new SubmitListener() {\r
- public void onSubmit() {\r
- updateValueFromPanel();\r
- }\r
- \r
- public void onCancel() {\r
- // TODO Auto-generated method stub\r
- \r
- }\r
- });\r
- calendarPanel.setFocusOutListener(new FocusOutListener() {\r
- public boolean onFocusOut(DomEvent<?> event) {\r
- updateValueFromPanel();\r
- return false;\r
- }\r
- });\r
- }\r
- \r
- /**\r
- * TODO refactor: almost same method as in VPopupCalendar.updateValue\r
- */\r
- @SuppressWarnings("deprecation")\r
- protected void updateValueFromPanel() {\r
- Date date2 = calendarPanel.getDate();\r
- Date currentDate = getCurrentDate();\r
- if (currentDate == null || date2.getTime() != currentDate.getTime()) {\r
- setCurrentDate((Date) date2.clone());\r
- getClient().updateVariable(getId(), "year", date2.getYear() + 1900,\r
- false);\r
- if (getCurrentResolution() > VDateField.RESOLUTION_YEAR) {\r
- getClient().updateVariable(getId(), "month",\r
- date2.getMonth() + 1, false);\r
- if (getCurrentResolution() > RESOLUTION_MONTH) {\r
- getClient().updateVariable(getId(), "day", date2.getDate(),\r
- false);\r
- if (getCurrentResolution() > RESOLUTION_DAY) {\r
- getClient().updateVariable(getId(), "hour",\r
- date2.getHours(), false);\r
- if (getCurrentResolution() > RESOLUTION_HOUR) {\r
- getClient().updateVariable(getId(), "min",\r
- date2.getMinutes(), false);\r
- if (getCurrentResolution() > RESOLUTION_MIN) {\r
- getClient().updateVariable(getId(), "sec",\r
- date2.getSeconds(), false);\r
- if (getCurrentResolution() > RESOLUTION_SEC) {\r
- getClient().updateVariable(\r
- getId(),\r
- "msec",\r
- DateTimeService\r
- .getMilliseconds(date2),\r
- false);\r
- }\r
- }\r
- }\r
- }\r
- }\r
- }\r
- if (isImmediate()) {\r
- getClient().sendPendingVariableChanges();\r
- }\r
- }\r
- }\r
- }\r
+ /*
+ @VaadinApache2LicenseForJavaFiles@
+ */
+
+ package com.vaadin.terminal.gwt.client.ui;
+
+ import java.util.Date;
+
+ import com.google.gwt.event.dom.client.DomEvent;
-import com.vaadin.terminal.gwt.client.ApplicationConnection;
+ import com.vaadin.terminal.gwt.client.DateTimeService;
-import com.vaadin.terminal.gwt.client.UIDL;
-import com.vaadin.terminal.gwt.client.ui.VCalendarPanel.FocusChangeListener;
+ import com.vaadin.terminal.gwt.client.ui.VCalendarPanel.FocusOutListener;
+ import com.vaadin.terminal.gwt.client.ui.VCalendarPanel.SubmitListener;
-import com.vaadin.terminal.gwt.client.ui.VCalendarPanel.TimeChangeListener;
+
+ /**
+ * A client side implementation for InlineDateField
+ */
+ public class VDateFieldCalendar extends VDateField {
+
- private final VCalendarPanel calendarPanel;
++ protected final VCalendarPanel calendarPanel;
+
+ public VDateFieldCalendar() {
+ super();
+ calendarPanel = new VCalendarPanel();
+ add(calendarPanel);
+ calendarPanel.setSubmitListener(new SubmitListener() {
+ public void onSubmit() {
+ updateValueFromPanel();
+ }
+
+ public void onCancel() {
+ // TODO Auto-generated method stub
+
+ }
+ });
+ calendarPanel.setFocusOutListener(new FocusOutListener() {
+ public boolean onFocusOut(DomEvent<?> event) {
+ updateValueFromPanel();
+ return false;
+ }
+ });
+ }
+
- @Override
- @SuppressWarnings("deprecation")
- public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {
- super.updateFromUIDL(uidl, client);
- calendarPanel.setShowISOWeekNumbers(isShowISOWeekNumbers());
- calendarPanel.setDateTimeService(getDateTimeService());
- calendarPanel.setResolution(getCurrentResolution());
- Date currentDate = getCurrentDate();
- if (currentDate != null) {
- calendarPanel.setDate(new Date(currentDate.getTime()));
- } else {
- calendarPanel.setDate(null);
- }
-
- if (currentResolution > RESOLUTION_DAY) {
- calendarPanel.setTimeChangeListener(new TimeChangeListener() {
- public void changed(int hour, int min, int sec, int msec) {
- Date d = getDate();
- if (d == null) {
- // date currently null, use the value from calendarPanel
- // (~ client time at the init of the widget)
- d = (Date) calendarPanel.getDate().clone();
- }
- d.setHours(hour);
- d.setMinutes(min);
- d.setSeconds(sec);
- DateTimeService.setMilliseconds(d, msec);
-
- // Always update time changes to the server
- calendarPanel.setDate(d);
- updateValueFromPanel();
- }
- });
- }
-
- if (currentResolution <= RESOLUTION_MONTH) {
- calendarPanel.setFocusChangeListener(new FocusChangeListener() {
- public void focusChanged(Date date) {
- Date date2 = new Date();
- if (calendarPanel.getDate() != null) {
- date2.setTime(calendarPanel.getDate().getTime());
- }
- /*
- * Update the value of calendarPanel
- */
- date2.setYear(date.getYear());
- date2.setMonth(date.getMonth());
- calendarPanel.setDate(date2);
- /*
- * Then update the value from panel to server
- */
- updateValueFromPanel();
- }
- });
- } else {
- calendarPanel.setFocusChangeListener(null);
- }
-
- // Update possible changes
- calendarPanel.renderCalendar();
- }
-
+ /**
+ * TODO refactor: almost same method as in VPopupCalendar.updateValue
+ */
+ @SuppressWarnings("deprecation")
- private void updateValueFromPanel() {
++ protected void updateValueFromPanel() {
+ Date date2 = calendarPanel.getDate();
+ Date currentDate = getCurrentDate();
+ if (currentDate == null || date2.getTime() != currentDate.getTime()) {
+ setCurrentDate((Date) date2.clone());
+ getClient().updateVariable(getId(), "year", date2.getYear() + 1900,
+ false);
+ if (getCurrentResolution() > VDateField.RESOLUTION_YEAR) {
+ getClient().updateVariable(getId(), "month",
+ date2.getMonth() + 1, false);
+ if (getCurrentResolution() > RESOLUTION_MONTH) {
+ getClient().updateVariable(getId(), "day", date2.getDate(),
+ false);
+ if (getCurrentResolution() > RESOLUTION_DAY) {
+ getClient().updateVariable(getId(), "hour",
+ date2.getHours(), false);
+ if (getCurrentResolution() > RESOLUTION_HOUR) {
+ getClient().updateVariable(getId(), "min",
+ date2.getMinutes(), false);
+ if (getCurrentResolution() > RESOLUTION_MIN) {
+ getClient().updateVariable(getId(), "sec",
+ date2.getSeconds(), false);
+ if (getCurrentResolution() > RESOLUTION_SEC) {
+ getClient().updateVariable(
+ getId(),
+ "msec",
+ DateTimeService
+ .getMilliseconds(date2),
+ false);
+ }
+ }
+ }
+ }
+ }
+ }
+ if (isImmediate()) {
+ getClient().sendPendingVariableChanges();
+ }
+ }
+ }
+ }
--- /dev/null
- package com.vaadin.terminal.gwt.client.ui;\r
- \r
- import java.util.HashMap;\r
- import java.util.Set;\r
- \r
- import com.google.gwt.core.client.GWT;\r
- import com.google.gwt.user.client.ui.Widget;\r
- import com.vaadin.terminal.gwt.client.ApplicationConnection;\r
- import com.vaadin.terminal.gwt.client.UIDL;\r
- \r
- public class VDragAndDropWrapperPaintable extends VCustomComponentPaintable {\r
- \r
- @Override\r
- public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {\r
- getWidgetForPaintable().client = client;\r
- super.updateFromUIDL(uidl, client);\r
- if (!uidl.hasAttribute("cached") && !uidl.hasAttribute("hidden")) {\r
- UIDL acceptCrit = uidl.getChildByTagName("-ac");\r
- if (acceptCrit == null) {\r
- getWidgetForPaintable().dropHandler = null;\r
- } else {\r
- if (getWidgetForPaintable().dropHandler == null) {\r
- getWidgetForPaintable().dropHandler = getWidgetForPaintable().new CustomDropHandler();\r
- }\r
- getWidgetForPaintable().dropHandler\r
- .updateAcceptRules(acceptCrit);\r
- }\r
- \r
- Set<String> variableNames = uidl.getVariableNames();\r
- for (String fileId : variableNames) {\r
- if (fileId.startsWith("rec-")) {\r
- String receiverUrl = uidl.getStringVariable(fileId);\r
- fileId = fileId.substring(4);\r
- if (getWidgetForPaintable().fileIdToReceiver == null) {\r
- getWidgetForPaintable().fileIdToReceiver = new HashMap<String, String>();\r
- }\r
- if ("".equals(receiverUrl)) {\r
- Integer id = Integer.parseInt(fileId);\r
- int indexOf = getWidgetForPaintable().fileIds\r
- .indexOf(id);\r
- if (indexOf != -1) {\r
- getWidgetForPaintable().files.remove(indexOf);\r
- getWidgetForPaintable().fileIds.remove(indexOf);\r
- }\r
- } else {\r
- getWidgetForPaintable().fileIdToReceiver.put(fileId,\r
- receiverUrl);\r
- }\r
- }\r
- }\r
- getWidgetForPaintable().startNextUpload();\r
- \r
- getWidgetForPaintable().dragStartMode = uidl\r
- .getIntAttribute(VDragAndDropWrapper.DRAG_START_MODE);\r
- getWidgetForPaintable().initDragStartMode();\r
- getWidgetForPaintable().html5DataFlavors = uidl\r
- .getMapAttribute(VDragAndDropWrapper.HTML5_DATA_FLAVORS);\r
- }\r
- }\r
- \r
- @Override\r
- protected Widget createWidget() {\r
- return GWT.create(VDragAndDropWrapper.class);\r
- }\r
- \r
- @Override\r
- public VDragAndDropWrapper getWidgetForPaintable() {\r
- return (VDragAndDropWrapper) super.getWidgetForPaintable();\r
- }\r
- \r
- }\r
++package com.vaadin.terminal.gwt.client.ui;
++
++import java.util.HashMap;
++import java.util.Set;
++
++import com.google.gwt.core.client.GWT;
++import com.google.gwt.user.client.ui.Widget;
++import com.vaadin.terminal.gwt.client.ApplicationConnection;
++import com.vaadin.terminal.gwt.client.UIDL;
++
++public class VDragAndDropWrapperPaintable extends VCustomComponentPaintable {
++
++ @Override
++ public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {
++ getWidgetForPaintable().client = client;
++ super.updateFromUIDL(uidl, client);
++ if (!uidl.hasAttribute("cached") && !uidl.hasAttribute("hidden")) {
++ UIDL acceptCrit = uidl.getChildByTagName("-ac");
++ if (acceptCrit == null) {
++ getWidgetForPaintable().dropHandler = null;
++ } else {
++ if (getWidgetForPaintable().dropHandler == null) {
++ getWidgetForPaintable().dropHandler = getWidgetForPaintable().new CustomDropHandler();
++ }
++ getWidgetForPaintable().dropHandler
++ .updateAcceptRules(acceptCrit);
++ }
++
++ Set<String> variableNames = uidl.getVariableNames();
++ for (String fileId : variableNames) {
++ if (fileId.startsWith("rec-")) {
++ String receiverUrl = uidl.getStringVariable(fileId);
++ fileId = fileId.substring(4);
++ if (getWidgetForPaintable().fileIdToReceiver == null) {
++ getWidgetForPaintable().fileIdToReceiver = new HashMap<String, String>();
++ }
++ if ("".equals(receiverUrl)) {
++ Integer id = Integer.parseInt(fileId);
++ int indexOf = getWidgetForPaintable().fileIds
++ .indexOf(id);
++ if (indexOf != -1) {
++ getWidgetForPaintable().files.remove(indexOf);
++ getWidgetForPaintable().fileIds.remove(indexOf);
++ }
++ } else {
++ getWidgetForPaintable().fileIdToReceiver.put(fileId,
++ receiverUrl);
++ }
++ }
++ }
++ getWidgetForPaintable().startNextUpload();
++
++ getWidgetForPaintable().dragStartMode = uidl
++ .getIntAttribute(VDragAndDropWrapper.DRAG_START_MODE);
++ getWidgetForPaintable().initDragStartMode();
++ getWidgetForPaintable().html5DataFlavors = uidl
++ .getMapAttribute(VDragAndDropWrapper.HTML5_DATA_FLAVORS);
++ }
++ }
++
++ @Override
++ protected Widget createWidget() {
++ return GWT.create(VDragAndDropWrapper.class);
++ }
++
++ @Override
++ public VDragAndDropWrapper getWidgetForPaintable() {
++ return (VDragAndDropWrapper) super.getWidgetForPaintable();
++ }
++
++}
--- /dev/null
- package com.vaadin.terminal.gwt.client.ui;\r
- \r
- import com.google.gwt.core.client.GWT;\r
- import com.google.gwt.user.client.ui.Widget;\r
- import com.vaadin.terminal.gwt.client.ApplicationConnection;\r
- import com.vaadin.terminal.gwt.client.UIDL;\r
- import com.vaadin.terminal.gwt.client.VPaintableWidget;\r
- \r
- public class VFormLayoutPaintable extends VAbstractPaintableWidgetContainer {\r
- public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {\r
- getWidgetForPaintable().rendering = true;\r
- \r
- getWidgetForPaintable().client = client;\r
- \r
- if (client.updateComponent(this, uidl, true)) {\r
- getWidgetForPaintable().rendering = false;\r
- return;\r
- }\r
- \r
- getWidgetForPaintable().table.updateFromUIDL(uidl, client);\r
- \r
- getWidgetForPaintable().rendering = false;\r
- }\r
- \r
- public void updateCaption(VPaintableWidget component, UIDL uidl) {\r
- getWidgetForPaintable().table.updateCaption(component, uidl);\r
- }\r
- \r
- @Override\r
- public VFormLayout getWidgetForPaintable() {\r
- return (VFormLayout) super.getWidgetForPaintable();\r
- }\r
- \r
- @Override\r
- protected Widget createWidget() {\r
- return GWT.create(VFormLayout.class);\r
- }\r
- \r
- }\r
++package com.vaadin.terminal.gwt.client.ui;
++
++import com.google.gwt.core.client.GWT;
++import com.google.gwt.user.client.ui.Widget;
++import com.vaadin.terminal.gwt.client.ApplicationConnection;
++import com.vaadin.terminal.gwt.client.UIDL;
++import com.vaadin.terminal.gwt.client.VPaintableWidget;
++
++public class VFormLayoutPaintable extends VAbstractPaintableWidgetContainer {
++ public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {
++ getWidgetForPaintable().rendering = true;
++
++ getWidgetForPaintable().client = client;
++
++ if (client.updateComponent(this, uidl, true)) {
++ getWidgetForPaintable().rendering = false;
++ return;
++ }
++
++ getWidgetForPaintable().table.updateFromUIDL(uidl, client);
++
++ getWidgetForPaintable().rendering = false;
++ }
++
++ public void updateCaption(VPaintableWidget component, UIDL uidl) {
++ getWidgetForPaintable().table.updateCaption(component, uidl);
++ }
++
++ @Override
++ public VFormLayout getWidgetForPaintable() {
++ return (VFormLayout) super.getWidgetForPaintable();
++ }
++
++ @Override
++ protected Widget createWidget() {
++ return GWT.create(VFormLayout.class);
++ }
++
++}
--- /dev/null
- package com.vaadin.terminal.gwt.client.ui;\r
- \r
- import com.google.gwt.core.client.GWT;\r
- import com.google.gwt.event.dom.client.KeyDownEvent;\r
- import com.google.gwt.user.client.ui.Widget;\r
- import com.vaadin.terminal.gwt.client.ApplicationConnection;\r
- import com.vaadin.terminal.gwt.client.UIDL;\r
- import com.vaadin.terminal.gwt.client.VPaintableMap;\r
- import com.vaadin.terminal.gwt.client.VPaintableWidget;\r
- \r
- public class VFormPaintable extends VAbstractPaintableWidgetContainer {\r
- \r
- public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {\r
- getWidgetForPaintable().rendering = true;\r
- getWidgetForPaintable().client = client;\r
- getWidgetForPaintable().id = uidl.getId();\r
- \r
- if (client.updateComponent(this, uidl, false)) {\r
- getWidgetForPaintable().rendering = false;\r
- return;\r
- }\r
- \r
- boolean legendEmpty = true;\r
- if (uidl.hasAttribute("caption")) {\r
- getWidgetForPaintable().caption.setInnerText(uidl\r
- .getStringAttribute("caption"));\r
- legendEmpty = false;\r
- } else {\r
- getWidgetForPaintable().caption.setInnerText("");\r
- }\r
- if (uidl.hasAttribute("icon")) {\r
- if (getWidgetForPaintable().icon == null) {\r
- getWidgetForPaintable().icon = new Icon(client);\r
- getWidgetForPaintable().legend\r
- .insertFirst(getWidgetForPaintable().icon.getElement());\r
- }\r
- getWidgetForPaintable().icon\r
- .setUri(uidl.getStringAttribute("icon"));\r
- legendEmpty = false;\r
- } else {\r
- if (getWidgetForPaintable().icon != null) {\r
- getWidgetForPaintable().legend\r
- .removeChild(getWidgetForPaintable().icon.getElement());\r
- }\r
- }\r
- if (legendEmpty) {\r
- getWidgetForPaintable().addStyleDependentName("nocaption");\r
- } else {\r
- getWidgetForPaintable().removeStyleDependentName("nocaption");\r
- }\r
- \r
- if (uidl.hasAttribute("error")) {\r
- final UIDL errorUidl = uidl.getErrors();\r
- getWidgetForPaintable().errorMessage.updateFromUIDL(errorUidl);\r
- getWidgetForPaintable().errorMessage.setVisible(true);\r
- } else {\r
- getWidgetForPaintable().errorMessage.setVisible(false);\r
- }\r
- \r
- if (uidl.hasAttribute("description")) {\r
- getWidgetForPaintable().desc.setInnerHTML(uidl\r
- .getStringAttribute("description"));\r
- if (getWidgetForPaintable().desc.getParentElement() == null) {\r
- getWidgetForPaintable().fieldSet.insertAfter(\r
- getWidgetForPaintable().desc,\r
- getWidgetForPaintable().legend);\r
- }\r
- } else {\r
- getWidgetForPaintable().desc.setInnerHTML("");\r
- if (getWidgetForPaintable().desc.getParentElement() != null) {\r
- getWidgetForPaintable().fieldSet\r
- .removeChild(getWidgetForPaintable().desc);\r
- }\r
- }\r
- \r
- getWidgetForPaintable().updateSize();\r
- \r
- // first render footer so it will be easier to handle relative height of\r
- // main layout\r
- if (uidl.getChildCount() > 1\r
- && !uidl.getChildUIDL(1).getTag().equals("actions")) {\r
- // render footer\r
- VPaintableWidget newFooter = client.getPaintable(uidl\r
- .getChildUIDL(1));\r
- Widget newFooterWidget = newFooter.getWidgetForPaintable();\r
- if (getWidgetForPaintable().footer == null) {\r
- getWidgetForPaintable().add(newFooter.getWidgetForPaintable(),\r
- getWidgetForPaintable().footerContainer);\r
- getWidgetForPaintable().footer = newFooterWidget;\r
- } else if (newFooter != getWidgetForPaintable().footer) {\r
- getWidgetForPaintable().remove(getWidgetForPaintable().footer);\r
- client.unregisterPaintable(VPaintableMap.get(getConnection())\r
- .getPaintable(getWidgetForPaintable().footer));\r
- getWidgetForPaintable().add(newFooter.getWidgetForPaintable(),\r
- getWidgetForPaintable().footerContainer);\r
- }\r
- getWidgetForPaintable().footer = newFooterWidget;\r
- newFooter.updateFromUIDL(uidl.getChildUIDL(1), client);\r
- // needed for the main layout to know the space it has available\r
- getWidgetForPaintable().updateSize();\r
- } else {\r
- if (getWidgetForPaintable().footer != null) {\r
- getWidgetForPaintable().remove(getWidgetForPaintable().footer);\r
- client.unregisterPaintable(VPaintableMap.get(getConnection())\r
- .getPaintable(getWidgetForPaintable().footer));\r
- // needed for the main layout to know the space it has available\r
- getWidgetForPaintable().updateSize();\r
- }\r
- }\r
- \r
- final UIDL layoutUidl = uidl.getChildUIDL(0);\r
- VPaintableWidget newLayout = client.getPaintable(layoutUidl);\r
- Widget newLayoutWidget = newLayout.getWidgetForPaintable();\r
- if (getWidgetForPaintable().lo == null) {\r
- // Layout not rendered before\r
- getWidgetForPaintable().lo = newLayoutWidget;\r
- getWidgetForPaintable().add(newLayoutWidget,\r
- getWidgetForPaintable().fieldContainer);\r
- } else if (getWidgetForPaintable().lo != newLayoutWidget) {\r
- // Layout has changed\r
- client.unregisterPaintable(VPaintableMap.get(getConnection())\r
- .getPaintable(getWidgetForPaintable().lo));\r
- getWidgetForPaintable().remove(getWidgetForPaintable().lo);\r
- getWidgetForPaintable().lo = newLayoutWidget;\r
- getWidgetForPaintable().add(newLayoutWidget,\r
- getWidgetForPaintable().fieldContainer);\r
- }\r
- newLayout.updateFromUIDL(layoutUidl, client);\r
- \r
- // also recalculates size of the footer if undefined size form - see\r
- // #3710\r
- getWidgetForPaintable().updateSize();\r
- client.runDescendentsLayout(getWidgetForPaintable());\r
- \r
- // We may have actions attached\r
- if (uidl.getChildCount() > 1) {\r
- UIDL childUidl = uidl.getChildByTagName("actions");\r
- if (childUidl != null) {\r
- if (getWidgetForPaintable().shortcutHandler == null) {\r
- getWidgetForPaintable().shortcutHandler = new ShortcutActionHandler(\r
- getId(), client);\r
- getWidgetForPaintable().keyDownRegistration = getWidgetForPaintable()\r
- .addDomHandler(getWidgetForPaintable(),\r
- KeyDownEvent.getType());\r
- }\r
- getWidgetForPaintable().shortcutHandler\r
- .updateActionMap(childUidl);\r
- }\r
- } else if (getWidgetForPaintable().shortcutHandler != null) {\r
- getWidgetForPaintable().keyDownRegistration.removeHandler();\r
- getWidgetForPaintable().shortcutHandler = null;\r
- getWidgetForPaintable().keyDownRegistration = null;\r
- }\r
- \r
- getWidgetForPaintable().rendering = false;\r
- }\r
- \r
- public void updateCaption(VPaintableWidget component, UIDL uidl) {\r
- // NOP form don't render caption for neither field layout nor footer\r
- // layout\r
- }\r
- \r
- @Override\r
- public VForm getWidgetForPaintable() {\r
- return (VForm) super.getWidgetForPaintable();\r
- }\r
- \r
- @Override\r
- protected Widget createWidget() {\r
- return GWT.create(VForm.class);\r
- }\r
- \r
- }\r
++package com.vaadin.terminal.gwt.client.ui;
++
++import com.google.gwt.core.client.GWT;
++import com.google.gwt.event.dom.client.KeyDownEvent;
++import com.google.gwt.user.client.ui.Widget;
++import com.vaadin.terminal.gwt.client.ApplicationConnection;
++import com.vaadin.terminal.gwt.client.UIDL;
++import com.vaadin.terminal.gwt.client.VPaintableMap;
++import com.vaadin.terminal.gwt.client.VPaintableWidget;
++
++public class VFormPaintable extends VAbstractPaintableWidgetContainer {
++
++ public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {
++ getWidgetForPaintable().rendering = true;
++ getWidgetForPaintable().client = client;
++ getWidgetForPaintable().id = uidl.getId();
++
++ if (client.updateComponent(this, uidl, false)) {
++ getWidgetForPaintable().rendering = false;
++ return;
++ }
++
++ boolean legendEmpty = true;
++ if (uidl.hasAttribute("caption")) {
++ getWidgetForPaintable().caption.setInnerText(uidl
++ .getStringAttribute("caption"));
++ legendEmpty = false;
++ } else {
++ getWidgetForPaintable().caption.setInnerText("");
++ }
++ if (uidl.hasAttribute("icon")) {
++ if (getWidgetForPaintable().icon == null) {
++ getWidgetForPaintable().icon = new Icon(client);
++ getWidgetForPaintable().legend
++ .insertFirst(getWidgetForPaintable().icon.getElement());
++ }
++ getWidgetForPaintable().icon
++ .setUri(uidl.getStringAttribute("icon"));
++ legendEmpty = false;
++ } else {
++ if (getWidgetForPaintable().icon != null) {
++ getWidgetForPaintable().legend
++ .removeChild(getWidgetForPaintable().icon.getElement());
++ }
++ }
++ if (legendEmpty) {
++ getWidgetForPaintable().addStyleDependentName("nocaption");
++ } else {
++ getWidgetForPaintable().removeStyleDependentName("nocaption");
++ }
++
++ if (uidl.hasAttribute("error")) {
++ final UIDL errorUidl = uidl.getErrors();
++ getWidgetForPaintable().errorMessage.updateFromUIDL(errorUidl);
++ getWidgetForPaintable().errorMessage.setVisible(true);
++ } else {
++ getWidgetForPaintable().errorMessage.setVisible(false);
++ }
++
++ if (uidl.hasAttribute("description")) {
++ getWidgetForPaintable().desc.setInnerHTML(uidl
++ .getStringAttribute("description"));
++ if (getWidgetForPaintable().desc.getParentElement() == null) {
++ getWidgetForPaintable().fieldSet.insertAfter(
++ getWidgetForPaintable().desc,
++ getWidgetForPaintable().legend);
++ }
++ } else {
++ getWidgetForPaintable().desc.setInnerHTML("");
++ if (getWidgetForPaintable().desc.getParentElement() != null) {
++ getWidgetForPaintable().fieldSet
++ .removeChild(getWidgetForPaintable().desc);
++ }
++ }
++
++ getWidgetForPaintable().updateSize();
++
++ // first render footer so it will be easier to handle relative height of
++ // main layout
++ if (uidl.getChildCount() > 1
++ && !uidl.getChildUIDL(1).getTag().equals("actions")) {
++ // render footer
++ VPaintableWidget newFooter = client.getPaintable(uidl
++ .getChildUIDL(1));
++ Widget newFooterWidget = newFooter.getWidgetForPaintable();
++ if (getWidgetForPaintable().footer == null) {
++ getWidgetForPaintable().add(newFooter.getWidgetForPaintable(),
++ getWidgetForPaintable().footerContainer);
++ getWidgetForPaintable().footer = newFooterWidget;
++ } else if (newFooter != getWidgetForPaintable().footer) {
++ getWidgetForPaintable().remove(getWidgetForPaintable().footer);
++ client.unregisterPaintable(VPaintableMap.get(getConnection())
++ .getPaintable(getWidgetForPaintable().footer));
++ getWidgetForPaintable().add(newFooter.getWidgetForPaintable(),
++ getWidgetForPaintable().footerContainer);
++ }
++ getWidgetForPaintable().footer = newFooterWidget;
++ newFooter.updateFromUIDL(uidl.getChildUIDL(1), client);
++ // needed for the main layout to know the space it has available
++ getWidgetForPaintable().updateSize();
++ } else {
++ if (getWidgetForPaintable().footer != null) {
++ getWidgetForPaintable().remove(getWidgetForPaintable().footer);
++ client.unregisterPaintable(VPaintableMap.get(getConnection())
++ .getPaintable(getWidgetForPaintable().footer));
++ // needed for the main layout to know the space it has available
++ getWidgetForPaintable().updateSize();
++ }
++ }
++
++ final UIDL layoutUidl = uidl.getChildUIDL(0);
++ VPaintableWidget newLayout = client.getPaintable(layoutUidl);
++ Widget newLayoutWidget = newLayout.getWidgetForPaintable();
++ if (getWidgetForPaintable().lo == null) {
++ // Layout not rendered before
++ getWidgetForPaintable().lo = newLayoutWidget;
++ getWidgetForPaintable().add(newLayoutWidget,
++ getWidgetForPaintable().fieldContainer);
++ } else if (getWidgetForPaintable().lo != newLayoutWidget) {
++ // Layout has changed
++ client.unregisterPaintable(VPaintableMap.get(getConnection())
++ .getPaintable(getWidgetForPaintable().lo));
++ getWidgetForPaintable().remove(getWidgetForPaintable().lo);
++ getWidgetForPaintable().lo = newLayoutWidget;
++ getWidgetForPaintable().add(newLayoutWidget,
++ getWidgetForPaintable().fieldContainer);
++ }
++ newLayout.updateFromUIDL(layoutUidl, client);
++
++ // also recalculates size of the footer if undefined size form - see
++ // #3710
++ getWidgetForPaintable().updateSize();
++ client.runDescendentsLayout(getWidgetForPaintable());
++
++ // We may have actions attached
++ if (uidl.getChildCount() > 1) {
++ UIDL childUidl = uidl.getChildByTagName("actions");
++ if (childUidl != null) {
++ if (getWidgetForPaintable().shortcutHandler == null) {
++ getWidgetForPaintable().shortcutHandler = new ShortcutActionHandler(
++ getId(), client);
++ getWidgetForPaintable().keyDownRegistration = getWidgetForPaintable()
++ .addDomHandler(getWidgetForPaintable(),
++ KeyDownEvent.getType());
++ }
++ getWidgetForPaintable().shortcutHandler
++ .updateActionMap(childUidl);
++ }
++ } else if (getWidgetForPaintable().shortcutHandler != null) {
++ getWidgetForPaintable().keyDownRegistration.removeHandler();
++ getWidgetForPaintable().shortcutHandler = null;
++ getWidgetForPaintable().keyDownRegistration = null;
++ }
++
++ getWidgetForPaintable().rendering = false;
++ }
++
++ public void updateCaption(VPaintableWidget component, UIDL uidl) {
++ // NOP form don't render caption for neither field layout nor footer
++ // layout
++ }
++
++ @Override
++ public VForm getWidgetForPaintable() {
++ return (VForm) super.getWidgetForPaintable();
++ }
++
++ @Override
++ protected Widget createWidget() {
++ return GWT.create(VForm.class);
++ }
++
++}
--- /dev/null
- package com.vaadin.terminal.gwt.client.ui;\r
- \r
- import java.util.HashMap;\r
- import java.util.Iterator;\r
- import java.util.LinkedList;\r
- \r
- import com.google.gwt.core.client.GWT;\r
- import com.google.gwt.event.dom.client.DomEvent.Type;\r
- import com.google.gwt.event.shared.EventHandler;\r
- import com.google.gwt.event.shared.HandlerRegistration;\r
- import com.google.gwt.user.client.Element;\r
- import com.google.gwt.user.client.ui.Widget;\r
- import com.vaadin.terminal.gwt.client.ApplicationConnection;\r
- import com.vaadin.terminal.gwt.client.EventId;\r
- import com.vaadin.terminal.gwt.client.UIDL;\r
- import com.vaadin.terminal.gwt.client.VPaintableMap;\r
- import com.vaadin.terminal.gwt.client.VPaintableWidget;\r
- import com.vaadin.terminal.gwt.client.ui.VGridLayout.Cell;\r
- import com.vaadin.terminal.gwt.client.ui.layout.ChildComponentContainer;\r
- \r
- public class VGridLayoutPaintable extends VAbstractPaintableWidgetContainer {\r
- private LayoutClickEventHandler clickEventHandler = new LayoutClickEventHandler(\r
- this, EventId.LAYOUT_CLICK) {\r
- \r
- @Override\r
- protected VPaintableWidget getChildComponent(Element element) {\r
- return getWidgetForPaintable().getComponent(element);\r
- }\r
- \r
- @Override\r
- protected <H extends EventHandler> HandlerRegistration registerHandler(\r
- H handler, Type<H> type) {\r
- return getWidgetForPaintable().addDomHandler(handler, type);\r
- }\r
- };\r
- \r
- @SuppressWarnings("unchecked")\r
- public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {\r
- getWidgetForPaintable().rendering = true;\r
- getWidgetForPaintable().client = client;\r
- \r
- if (client.updateComponent(this, uidl, true)) {\r
- getWidgetForPaintable().rendering = false;\r
- return;\r
- }\r
- clickEventHandler.handleEventHandlerRegistration(client);\r
- \r
- getWidgetForPaintable().canvas.setWidth("0px");\r
- \r
- getWidgetForPaintable().handleMargins(uidl);\r
- getWidgetForPaintable().detectSpacing(uidl);\r
- \r
- int cols = uidl.getIntAttribute("w");\r
- int rows = uidl.getIntAttribute("h");\r
- \r
- getWidgetForPaintable().columnWidths = new int[cols];\r
- getWidgetForPaintable().rowHeights = new int[rows];\r
- \r
- if (getWidgetForPaintable().cells == null) {\r
- getWidgetForPaintable().cells = new Cell[cols][rows];\r
- } else if (getWidgetForPaintable().cells.length != cols\r
- || getWidgetForPaintable().cells[0].length != rows) {\r
- Cell[][] newCells = new Cell[cols][rows];\r
- for (int i = 0; i < getWidgetForPaintable().cells.length; i++) {\r
- for (int j = 0; j < getWidgetForPaintable().cells[i].length; j++) {\r
- if (i < cols && j < rows) {\r
- newCells[i][j] = getWidgetForPaintable().cells[i][j];\r
- }\r
- }\r
- }\r
- getWidgetForPaintable().cells = newCells;\r
- }\r
- \r
- getWidgetForPaintable().nonRenderedWidgets = (HashMap<Widget, ChildComponentContainer>) getWidgetForPaintable().widgetToComponentContainer\r
- .clone();\r
- \r
- final int[] alignments = uidl.getIntArrayAttribute("alignments");\r
- int alignmentIndex = 0;\r
- \r
- LinkedList<Cell> pendingCells = new LinkedList<Cell>();\r
- \r
- LinkedList<Cell> relativeHeighted = new LinkedList<Cell>();\r
- \r
- for (final Iterator<?> i = uidl.getChildIterator(); i.hasNext();) {\r
- final UIDL r = (UIDL) i.next();\r
- if ("gr".equals(r.getTag())) {\r
- for (final Iterator<?> j = r.getChildIterator(); j.hasNext();) {\r
- final UIDL c = (UIDL) j.next();\r
- if ("gc".equals(c.getTag())) {\r
- Cell cell = getWidgetForPaintable().getCell(c);\r
- if (cell.hasContent()) {\r
- boolean rendered = cell.renderIfNoRelativeWidth();\r
- cell.alignment = alignments[alignmentIndex++];\r
- if (!rendered) {\r
- pendingCells.add(cell);\r
- }\r
- \r
- if (cell.colspan > 1) {\r
- getWidgetForPaintable().storeColSpannedCell(\r
- cell);\r
- } else if (rendered) {\r
- // strore non-colspanned widths to columnWidth\r
- // array\r
- if (getWidgetForPaintable().columnWidths[cell.col] < cell\r
- .getWidth()) {\r
- getWidgetForPaintable().columnWidths[cell.col] = cell\r
- .getWidth();\r
- }\r
- }\r
- if (cell.hasRelativeHeight()) {\r
- relativeHeighted.add(cell);\r
- }\r
- }\r
- }\r
- }\r
- }\r
- }\r
- \r
- getWidgetForPaintable().colExpandRatioArray = uidl\r
- .getIntArrayAttribute("colExpand");\r
- getWidgetForPaintable().rowExpandRatioArray = uidl\r
- .getIntArrayAttribute("rowExpand");\r
- getWidgetForPaintable().distributeColSpanWidths();\r
- \r
- getWidgetForPaintable().minColumnWidths = VGridLayout\r
- .cloneArray(getWidgetForPaintable().columnWidths);\r
- getWidgetForPaintable().expandColumns();\r
- \r
- getWidgetForPaintable().renderRemainingComponentsWithNoRelativeHeight(\r
- pendingCells);\r
- \r
- getWidgetForPaintable().detectRowHeights();\r
- \r
- getWidgetForPaintable().expandRows();\r
- \r
- getWidgetForPaintable().renderRemainingComponents(pendingCells);\r
- \r
- for (Cell cell : relativeHeighted) {\r
- // rendering done above so cell.cc should not be null\r
- Widget widget2 = cell.cc.getWidget();\r
- client.handleComponentRelativeSize(widget2);\r
- cell.cc.updateWidgetSize();\r
- }\r
- \r
- getWidgetForPaintable().layoutCells();\r
- \r
- // clean non rendered components\r
- for (Widget w : getWidgetForPaintable().nonRenderedWidgets.keySet()) {\r
- ChildComponentContainer childComponentContainer = getWidgetForPaintable().widgetToComponentContainer\r
- .get(w);\r
- getWidgetForPaintable().widgetToCell.remove(w);\r
- getWidgetForPaintable().widgetToComponentContainer.remove(w);\r
- childComponentContainer.removeFromParent();\r
- VPaintableMap paintableMap = VPaintableMap.get(client);\r
- paintableMap.unregisterPaintable(paintableMap.getPaintable(w));\r
- }\r
- getWidgetForPaintable().nonRenderedWidgets = null;\r
- \r
- getWidgetForPaintable().rendering = false;\r
- getWidgetForPaintable().sizeChangedDuringRendering = false;\r
- \r
- }\r
- \r
- public void updateCaption(VPaintableWidget paintable, UIDL uidl) {\r
- Widget widget = paintable.getWidgetForPaintable();\r
- ChildComponentContainer cc = getWidgetForPaintable().widgetToComponentContainer\r
- .get(widget);\r
- if (cc != null) {\r
- cc.updateCaption(uidl, getConnection());\r
- }\r
- if (!getWidgetForPaintable().rendering) {\r
- // ensure rel size details are updated\r
- getWidgetForPaintable().widgetToCell.get(widget)\r
- .updateRelSizeStatus(uidl);\r
- /*\r
- * This was a component-only update and the possible size change\r
- * must be propagated to the layout\r
- */\r
- getConnection().captionSizeUpdated(widget);\r
- }\r
- }\r
- \r
- @Override\r
- public VGridLayout getWidgetForPaintable() {\r
- return (VGridLayout) super.getWidgetForPaintable();\r
- }\r
- \r
- @Override\r
- protected Widget createWidget() {\r
- return GWT.create(VGridLayout.class);\r
- }\r
- \r
- }\r
++package com.vaadin.terminal.gwt.client.ui;
++
++import java.util.HashMap;
++import java.util.Iterator;
++import java.util.LinkedList;
++
++import com.google.gwt.core.client.GWT;
++import com.google.gwt.event.dom.client.DomEvent.Type;
++import com.google.gwt.event.shared.EventHandler;
++import com.google.gwt.event.shared.HandlerRegistration;
++import com.google.gwt.user.client.Element;
++import com.google.gwt.user.client.ui.Widget;
++import com.vaadin.terminal.gwt.client.ApplicationConnection;
++import com.vaadin.terminal.gwt.client.EventId;
++import com.vaadin.terminal.gwt.client.UIDL;
++import com.vaadin.terminal.gwt.client.VPaintableMap;
++import com.vaadin.terminal.gwt.client.VPaintableWidget;
++import com.vaadin.terminal.gwt.client.ui.VGridLayout.Cell;
++import com.vaadin.terminal.gwt.client.ui.layout.ChildComponentContainer;
++
++public class VGridLayoutPaintable extends VAbstractPaintableWidgetContainer {
++ private LayoutClickEventHandler clickEventHandler = new LayoutClickEventHandler(
++ this, EventId.LAYOUT_CLICK) {
++
++ @Override
++ protected VPaintableWidget getChildComponent(Element element) {
++ return getWidgetForPaintable().getComponent(element);
++ }
++
++ @Override
++ protected <H extends EventHandler> HandlerRegistration registerHandler(
++ H handler, Type<H> type) {
++ return getWidgetForPaintable().addDomHandler(handler, type);
++ }
++ };
++
++ @SuppressWarnings("unchecked")
++ public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {
++ getWidgetForPaintable().rendering = true;
++ getWidgetForPaintable().client = client;
++
++ if (client.updateComponent(this, uidl, true)) {
++ getWidgetForPaintable().rendering = false;
++ return;
++ }
++ clickEventHandler.handleEventHandlerRegistration(client);
++
++ getWidgetForPaintable().canvas.setWidth("0px");
++
++ getWidgetForPaintable().handleMargins(uidl);
++ getWidgetForPaintable().detectSpacing(uidl);
++
++ int cols = uidl.getIntAttribute("w");
++ int rows = uidl.getIntAttribute("h");
++
++ getWidgetForPaintable().columnWidths = new int[cols];
++ getWidgetForPaintable().rowHeights = new int[rows];
++
++ if (getWidgetForPaintable().cells == null) {
++ getWidgetForPaintable().cells = new Cell[cols][rows];
++ } else if (getWidgetForPaintable().cells.length != cols
++ || getWidgetForPaintable().cells[0].length != rows) {
++ Cell[][] newCells = new Cell[cols][rows];
++ for (int i = 0; i < getWidgetForPaintable().cells.length; i++) {
++ for (int j = 0; j < getWidgetForPaintable().cells[i].length; j++) {
++ if (i < cols && j < rows) {
++ newCells[i][j] = getWidgetForPaintable().cells[i][j];
++ }
++ }
++ }
++ getWidgetForPaintable().cells = newCells;
++ }
++
++ getWidgetForPaintable().nonRenderedWidgets = (HashMap<Widget, ChildComponentContainer>) getWidgetForPaintable().widgetToComponentContainer
++ .clone();
++
++ final int[] alignments = uidl.getIntArrayAttribute("alignments");
++ int alignmentIndex = 0;
++
++ LinkedList<Cell> pendingCells = new LinkedList<Cell>();
++
++ LinkedList<Cell> relativeHeighted = new LinkedList<Cell>();
++
++ for (final Iterator<?> i = uidl.getChildIterator(); i.hasNext();) {
++ final UIDL r = (UIDL) i.next();
++ if ("gr".equals(r.getTag())) {
++ for (final Iterator<?> j = r.getChildIterator(); j.hasNext();) {
++ final UIDL c = (UIDL) j.next();
++ if ("gc".equals(c.getTag())) {
++ Cell cell = getWidgetForPaintable().getCell(c);
++ if (cell.hasContent()) {
++ boolean rendered = cell.renderIfNoRelativeWidth();
++ cell.alignment = alignments[alignmentIndex++];
++ if (!rendered) {
++ pendingCells.add(cell);
++ }
++
++ if (cell.colspan > 1) {
++ getWidgetForPaintable().storeColSpannedCell(
++ cell);
++ } else if (rendered) {
++ // strore non-colspanned widths to columnWidth
++ // array
++ if (getWidgetForPaintable().columnWidths[cell.col] < cell
++ .getWidth()) {
++ getWidgetForPaintable().columnWidths[cell.col] = cell
++ .getWidth();
++ }
++ }
++ if (cell.hasRelativeHeight()) {
++ relativeHeighted.add(cell);
++ }
++ }
++ }
++ }
++ }
++ }
++
++ getWidgetForPaintable().colExpandRatioArray = uidl
++ .getIntArrayAttribute("colExpand");
++ getWidgetForPaintable().rowExpandRatioArray = uidl
++ .getIntArrayAttribute("rowExpand");
++ getWidgetForPaintable().distributeColSpanWidths();
++
++ getWidgetForPaintable().minColumnWidths = VGridLayout
++ .cloneArray(getWidgetForPaintable().columnWidths);
++ getWidgetForPaintable().expandColumns();
++
++ getWidgetForPaintable().renderRemainingComponentsWithNoRelativeHeight(
++ pendingCells);
++
++ getWidgetForPaintable().detectRowHeights();
++
++ getWidgetForPaintable().expandRows();
++
++ getWidgetForPaintable().renderRemainingComponents(pendingCells);
++
++ for (Cell cell : relativeHeighted) {
++ // rendering done above so cell.cc should not be null
++ Widget widget2 = cell.cc.getWidget();
++ client.handleComponentRelativeSize(widget2);
++ cell.cc.updateWidgetSize();
++ }
++
++ getWidgetForPaintable().layoutCells();
++
++ // clean non rendered components
++ for (Widget w : getWidgetForPaintable().nonRenderedWidgets.keySet()) {
++ ChildComponentContainer childComponentContainer = getWidgetForPaintable().widgetToComponentContainer
++ .get(w);
++ getWidgetForPaintable().widgetToCell.remove(w);
++ getWidgetForPaintable().widgetToComponentContainer.remove(w);
++ childComponentContainer.removeFromParent();
++ VPaintableMap paintableMap = VPaintableMap.get(client);
++ paintableMap.unregisterPaintable(paintableMap.getPaintable(w));
++ }
++ getWidgetForPaintable().nonRenderedWidgets = null;
++
++ getWidgetForPaintable().rendering = false;
++ getWidgetForPaintable().sizeChangedDuringRendering = false;
++
++ }
++
++ public void updateCaption(VPaintableWidget paintable, UIDL uidl) {
++ Widget widget = paintable.getWidgetForPaintable();
++ ChildComponentContainer cc = getWidgetForPaintable().widgetToComponentContainer
++ .get(widget);
++ if (cc != null) {
++ cc.updateCaption(uidl, getConnection());
++ }
++ if (!getWidgetForPaintable().rendering) {
++ // ensure rel size details are updated
++ getWidgetForPaintable().widgetToCell.get(widget)
++ .updateRelSizeStatus(uidl);
++ /*
++ * This was a component-only update and the possible size change
++ * must be propagated to the layout
++ */
++ getConnection().captionSizeUpdated(widget);
++ }
++ }
++
++ @Override
++ public VGridLayout getWidgetForPaintable() {
++ return (VGridLayout) super.getWidgetForPaintable();
++ }
++
++ @Override
++ protected Widget createWidget() {
++ return GWT.create(VGridLayout.class);
++ }
++
++}
--- /dev/null
- package com.vaadin.terminal.gwt.client.ui;\r
- \r
- import com.google.gwt.core.client.GWT;\r
- \r
- public class VHorizontalLayoutPaintable extends VOrderedLayoutPaintable {\r
- \r
- @Override\r
- public VHorizontalLayout getWidgetForPaintable() {\r
- return (VHorizontalLayout) super.getWidgetForPaintable();\r
- }\r
- \r
- @Override\r
- protected VHorizontalLayout createWidget() {\r
- return GWT.create(VHorizontalLayout.class);\r
- }\r
- \r
- }\r
++package com.vaadin.terminal.gwt.client.ui;
++
++import com.google.gwt.core.client.GWT;
++
++public class VHorizontalLayoutPaintable extends VOrderedLayoutPaintable {
++
++ @Override
++ public VHorizontalLayout getWidgetForPaintable() {
++ return (VHorizontalLayout) super.getWidgetForPaintable();
++ }
++
++ @Override
++ protected VHorizontalLayout createWidget() {
++ return GWT.create(VHorizontalLayout.class);
++ }
++
++}
--- /dev/null
- package com.vaadin.terminal.gwt.client.ui;\r
- \r
- import com.google.gwt.core.client.GWT;\r
- \r
- public class VHorizontalSplitPanelPaintable extends\r
- VAbstractSplitPanelPaintable {\r
- \r
- @Override\r
- protected VAbstractSplitPanel createWidget() {\r
- return GWT.create(VSplitPanelHorizontal.class);\r
- }\r
- \r
- }\r
++package com.vaadin.terminal.gwt.client.ui;
++
++import com.google.gwt.core.client.GWT;
++
++public class VHorizontalSplitPanelPaintable extends
++ VAbstractSplitPanelPaintable {
++
++ @Override
++ protected VAbstractSplitPanel createWidget() {
++ return GWT.create(VSplitPanelHorizontal.class);
++ }
++
++}
--- /dev/null
- package com.vaadin.terminal.gwt.client.ui;\r
- \r
- import com.vaadin.terminal.gwt.client.ApplicationConnection;\r
- import com.vaadin.terminal.gwt.client.UIDL;\r
- import com.vaadin.terminal.gwt.client.Util;\r
- \r
- public abstract class VMediaBasePaintable extends VAbstractPaintableWidget {\r
- \r
- public static final String TAG_SOURCE = "src";\r
- \r
- public static final String ATTR_PAUSE = "pause";\r
- public static final String ATTR_PLAY = "play";\r
- public static final String ATTR_MUTED = "muted";\r
- public static final String ATTR_CONTROLS = "ctrl";\r
- public static final String ATTR_AUTOPLAY = "auto";\r
- public static final String ATTR_RESOURCE = "res";\r
- public static final String ATTR_RESOURCE_TYPE = "type";\r
- public static final String ATTR_HTML = "html";\r
- public static final String ATTR_ALT_TEXT = "alt";\r
- \r
- public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {\r
- if (client.updateComponent(this, uidl, true)) {\r
- return;\r
- }\r
- \r
- getWidgetForPaintable().setControls(shouldShowControls(uidl));\r
- getWidgetForPaintable().setAutoplay(shouldAutoplay(uidl));\r
- getWidgetForPaintable().setMuted(isMediaMuted(uidl));\r
- \r
- // Add all sources\r
- for (int ix = 0; ix < uidl.getChildCount(); ix++) {\r
- UIDL child = uidl.getChildUIDL(ix);\r
- if (TAG_SOURCE.equals(child.getTag())) {\r
- getWidgetForPaintable().addSource(getSourceUrl(child),\r
- getSourceType(child));\r
- }\r
- }\r
- setAltText(uidl);\r
- \r
- evalPauseCommand(uidl);\r
- evalPlayCommand(uidl);\r
- }\r
- \r
- protected boolean shouldShowControls(UIDL uidl) {\r
- return uidl.getBooleanAttribute(ATTR_CONTROLS);\r
- }\r
- \r
- private boolean shouldAutoplay(UIDL uidl) {\r
- return uidl.getBooleanAttribute(ATTR_AUTOPLAY);\r
- }\r
- \r
- private boolean isMediaMuted(UIDL uidl) {\r
- return uidl.getBooleanAttribute(ATTR_MUTED);\r
- }\r
- \r
- private boolean allowHtmlContent(UIDL uidl) {\r
- return uidl.getBooleanAttribute(ATTR_HTML);\r
- }\r
- \r
- private void evalPlayCommand(UIDL uidl) {\r
- if (uidl.hasAttribute(ATTR_PLAY)) {\r
- getWidgetForPaintable().play();\r
- }\r
- }\r
- \r
- private void evalPauseCommand(UIDL uidl) {\r
- if (uidl.hasAttribute(ATTR_PAUSE)) {\r
- getWidgetForPaintable().pause();\r
- }\r
- }\r
- \r
- @Override\r
- public VMediaBase getWidgetForPaintable() {\r
- return (VMediaBase) super.getWidgetForPaintable();\r
- }\r
- \r
- /**\r
- * @param uidl\r
- * @return the URL of a resource to be used as a source for the media\r
- */\r
- private String getSourceUrl(UIDL uidl) {\r
- String url = getConnection().translateVaadinUri(\r
- uidl.getStringAttribute(VMediaBasePaintable.ATTR_RESOURCE));\r
- if (url == null) {\r
- return "";\r
- }\r
- return url;\r
- }\r
- \r
- /**\r
- * @param uidl\r
- * @return the mime type of the media\r
- */\r
- private String getSourceType(UIDL uidl) {\r
- return uidl.getStringAttribute(VMediaBasePaintable.ATTR_RESOURCE_TYPE);\r
- }\r
- \r
- private void setAltText(UIDL uidl) {\r
- String alt = uidl.getStringAttribute(VMediaBasePaintable.ATTR_ALT_TEXT);\r
- \r
- if (alt == null || "".equals(alt)) {\r
- alt = getWidgetForPaintable().getDefaultAltHtml();\r
- } else if (!allowHtmlContent(uidl)) {\r
- alt = Util.escapeHTML(alt);\r
- }\r
- getWidgetForPaintable().setAltText(alt);\r
- }\r
- \r
- }\r
++package com.vaadin.terminal.gwt.client.ui;
++
++import com.vaadin.terminal.gwt.client.ApplicationConnection;
++import com.vaadin.terminal.gwt.client.UIDL;
++import com.vaadin.terminal.gwt.client.Util;
++
++public abstract class VMediaBasePaintable extends VAbstractPaintableWidget {
++
++ public static final String TAG_SOURCE = "src";
++
++ public static final String ATTR_PAUSE = "pause";
++ public static final String ATTR_PLAY = "play";
++ public static final String ATTR_MUTED = "muted";
++ public static final String ATTR_CONTROLS = "ctrl";
++ public static final String ATTR_AUTOPLAY = "auto";
++ public static final String ATTR_RESOURCE = "res";
++ public static final String ATTR_RESOURCE_TYPE = "type";
++ public static final String ATTR_HTML = "html";
++ public static final String ATTR_ALT_TEXT = "alt";
++
++ public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {
++ if (client.updateComponent(this, uidl, true)) {
++ return;
++ }
++
++ getWidgetForPaintable().setControls(shouldShowControls(uidl));
++ getWidgetForPaintable().setAutoplay(shouldAutoplay(uidl));
++ getWidgetForPaintable().setMuted(isMediaMuted(uidl));
++
++ // Add all sources
++ for (int ix = 0; ix < uidl.getChildCount(); ix++) {
++ UIDL child = uidl.getChildUIDL(ix);
++ if (TAG_SOURCE.equals(child.getTag())) {
++ getWidgetForPaintable().addSource(getSourceUrl(child),
++ getSourceType(child));
++ }
++ }
++ setAltText(uidl);
++
++ evalPauseCommand(uidl);
++ evalPlayCommand(uidl);
++ }
++
++ protected boolean shouldShowControls(UIDL uidl) {
++ return uidl.getBooleanAttribute(ATTR_CONTROLS);
++ }
++
++ private boolean shouldAutoplay(UIDL uidl) {
++ return uidl.getBooleanAttribute(ATTR_AUTOPLAY);
++ }
++
++ private boolean isMediaMuted(UIDL uidl) {
++ return uidl.getBooleanAttribute(ATTR_MUTED);
++ }
++
++ private boolean allowHtmlContent(UIDL uidl) {
++ return uidl.getBooleanAttribute(ATTR_HTML);
++ }
++
++ private void evalPlayCommand(UIDL uidl) {
++ if (uidl.hasAttribute(ATTR_PLAY)) {
++ getWidgetForPaintable().play();
++ }
++ }
++
++ private void evalPauseCommand(UIDL uidl) {
++ if (uidl.hasAttribute(ATTR_PAUSE)) {
++ getWidgetForPaintable().pause();
++ }
++ }
++
++ @Override
++ public VMediaBase getWidgetForPaintable() {
++ return (VMediaBase) super.getWidgetForPaintable();
++ }
++
++ /**
++ * @param uidl
++ * @return the URL of a resource to be used as a source for the media
++ */
++ private String getSourceUrl(UIDL uidl) {
++ String url = getConnection().translateVaadinUri(
++ uidl.getStringAttribute(VMediaBasePaintable.ATTR_RESOURCE));
++ if (url == null) {
++ return "";
++ }
++ return url;
++ }
++
++ /**
++ * @param uidl
++ * @return the mime type of the media
++ */
++ private String getSourceType(UIDL uidl) {
++ return uidl.getStringAttribute(VMediaBasePaintable.ATTR_RESOURCE_TYPE);
++ }
++
++ private void setAltText(UIDL uidl) {
++ String alt = uidl.getStringAttribute(VMediaBasePaintable.ATTR_ALT_TEXT);
++
++ if (alt == null || "".equals(alt)) {
++ alt = getWidgetForPaintable().getDefaultAltHtml();
++ } else if (!allowHtmlContent(uidl)) {
++ alt = Util.escapeHTML(alt);
++ }
++ getWidgetForPaintable().setAltText(alt);
++ }
++
++}
--- /dev/null
- /*\r
- @VaadinApache2LicenseForJavaFiles@\r
- */\r
- package com.vaadin.terminal.gwt.client.ui;\r
- \r
- import java.util.Iterator;\r
- import java.util.Stack;\r
- \r
- import com.google.gwt.core.client.GWT;\r
- import com.google.gwt.user.client.Command;\r
- import com.google.gwt.user.client.ui.Widget;\r
- import com.vaadin.terminal.gwt.client.ApplicationConnection;\r
- import com.vaadin.terminal.gwt.client.UIDL;\r
- import com.vaadin.terminal.gwt.client.Util;\r
- import com.vaadin.terminal.gwt.client.ui.VMenuBar.CustomMenuItem;\r
- \r
- public class VMenuBarPaintable extends VAbstractPaintableWidget {\r
- /**\r
- * This method must be implemented to update the client-side component from\r
- * UIDL data received from server.\r
- * \r
- * This method is called when the page is loaded for the first time, and\r
- * every time UI changes in the component are received from the server.\r
- */\r
- public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {\r
- // This call should be made first. Ensure correct implementation,\r
- // and let the containing layout manage caption, etc.\r
- if (client.updateComponent(this, uidl, true)) {\r
- return;\r
- }\r
- \r
- getWidgetForPaintable().htmlContentAllowed = uidl\r
- .hasAttribute(VMenuBar.HTML_CONTENT_ALLOWED);\r
- \r
- getWidgetForPaintable().openRootOnHover = uidl\r
- .getBooleanAttribute(VMenuBar.OPEN_ROOT_MENU_ON_HOWER);\r
- \r
- getWidgetForPaintable().enabled = !uidl.getBooleanAttribute("disabled");\r
- \r
- // For future connections\r
- getWidgetForPaintable().client = client;\r
- getWidgetForPaintable().uidlId = uidl.getId();\r
- \r
- // Empty the menu every time it receives new information\r
- if (!getWidgetForPaintable().getItems().isEmpty()) {\r
- getWidgetForPaintable().clearItems();\r
- }\r
- \r
- UIDL options = uidl.getChildUIDL(0);\r
- \r
- if (uidl.hasAttribute("width")) {\r
- UIDL moreItemUIDL = options.getChildUIDL(0);\r
- StringBuffer itemHTML = new StringBuffer();\r
- \r
- if (moreItemUIDL.hasAttribute("icon")) {\r
- itemHTML.append("<img src=\""\r
- + Util.escapeAttribute(client\r
- .translateVaadinUri(moreItemUIDL\r
- .getStringAttribute("icon")))\r
- + "\" class=\"" + Icon.CLASSNAME + "\" alt=\"\" />");\r
- }\r
- \r
- String moreItemText = moreItemUIDL.getStringAttribute("text");\r
- if ("".equals(moreItemText)) {\r
- moreItemText = "►";\r
- }\r
- itemHTML.append(moreItemText);\r
- \r
- getWidgetForPaintable().moreItem = GWT.create(CustomMenuItem.class);\r
- getWidgetForPaintable().moreItem.setHTML(itemHTML.toString());\r
- getWidgetForPaintable().moreItem.setCommand(VMenuBar.emptyCommand);\r
- \r
- getWidgetForPaintable().collapsedRootItems = new VMenuBar(true,\r
- getWidgetForPaintable());\r
- getWidgetForPaintable().moreItem\r
- .setSubMenu(getWidgetForPaintable().collapsedRootItems);\r
- getWidgetForPaintable().moreItem.addStyleName(VMenuBar.CLASSNAME\r
- + "-more-menuitem");\r
- }\r
- \r
- UIDL uidlItems = uidl.getChildUIDL(1);\r
- Iterator<Object> itr = uidlItems.getChildIterator();\r
- Stack<Iterator<Object>> iteratorStack = new Stack<Iterator<Object>>();\r
- Stack<VMenuBar> menuStack = new Stack<VMenuBar>();\r
- VMenuBar currentMenu = getWidgetForPaintable();\r
- \r
- while (itr.hasNext()) {\r
- UIDL item = (UIDL) itr.next();\r
- CustomMenuItem currentItem = null;\r
- \r
- final int itemId = item.getIntAttribute("id");\r
- \r
- boolean itemHasCommand = item.hasAttribute("command");\r
- boolean itemIsCheckable = item\r
- .hasAttribute(VMenuBar.ATTRIBUTE_CHECKED);\r
- \r
- String itemHTML = getWidgetForPaintable().buildItemHTML(item);\r
- \r
- Command cmd = null;\r
- if (!item.hasAttribute("separator")) {\r
- if (itemHasCommand || itemIsCheckable) {\r
- // Construct a command that fires onMenuClick(int) with the\r
- // item's id-number\r
- cmd = new Command() {\r
- public void execute() {\r
- getWidgetForPaintable().hostReference\r
- .onMenuClick(itemId);\r
- }\r
- };\r
- }\r
- }\r
- \r
- currentItem = currentMenu.addItem(itemHTML.toString(), cmd);\r
- currentItem.updateFromUIDL(item, client);\r
- \r
- if (item.getChildCount() > 0) {\r
- menuStack.push(currentMenu);\r
- iteratorStack.push(itr);\r
- itr = item.getChildIterator();\r
- currentMenu = new VMenuBar(true, currentMenu);\r
- if (uidl.hasAttribute("style")) {\r
- for (String style : uidl.getStringAttribute("style").split(\r
- " ")) {\r
- currentMenu.addStyleDependentName(style);\r
- }\r
- }\r
- currentItem.setSubMenu(currentMenu);\r
- }\r
- \r
- while (!itr.hasNext() && !iteratorStack.empty()) {\r
- boolean hasCheckableItem = false;\r
- for (CustomMenuItem menuItem : currentMenu.getItems()) {\r
- hasCheckableItem = hasCheckableItem\r
- || menuItem.isCheckable();\r
- }\r
- if (hasCheckableItem) {\r
- currentMenu.addStyleDependentName("check-column");\r
- } else {\r
- currentMenu.removeStyleDependentName("check-column");\r
- }\r
- \r
- itr = iteratorStack.pop();\r
- currentMenu = menuStack.pop();\r
- }\r
- }// while\r
- \r
- getWidgetForPaintable().iLayout(false);\r
- \r
- }// updateFromUIDL\r
- \r
- @Override\r
- protected Widget createWidget() {\r
- return GWT.create(VMenuBar.class);\r
- }\r
- \r
- @Override\r
- public VMenuBar getWidgetForPaintable() {\r
- return (VMenuBar) super.getWidgetForPaintable();\r
- }\r
- \r
- }\r
++/*
++@VaadinApache2LicenseForJavaFiles@
++ */
++package com.vaadin.terminal.gwt.client.ui;
++
++import java.util.Iterator;
++import java.util.Stack;
++
++import com.google.gwt.core.client.GWT;
++import com.google.gwt.user.client.Command;
++import com.google.gwt.user.client.ui.Widget;
++import com.vaadin.terminal.gwt.client.ApplicationConnection;
++import com.vaadin.terminal.gwt.client.UIDL;
++import com.vaadin.terminal.gwt.client.Util;
++import com.vaadin.terminal.gwt.client.ui.VMenuBar.CustomMenuItem;
++
++public class VMenuBarPaintable extends VAbstractPaintableWidget {
++ /**
++ * This method must be implemented to update the client-side component from
++ * UIDL data received from server.
++ *
++ * This method is called when the page is loaded for the first time, and
++ * every time UI changes in the component are received from the server.
++ */
++ public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {
++ // This call should be made first. Ensure correct implementation,
++ // and let the containing layout manage caption, etc.
++ if (client.updateComponent(this, uidl, true)) {
++ return;
++ }
++
++ getWidgetForPaintable().htmlContentAllowed = uidl
++ .hasAttribute(VMenuBar.HTML_CONTENT_ALLOWED);
++
++ getWidgetForPaintable().openRootOnHover = uidl
++ .getBooleanAttribute(VMenuBar.OPEN_ROOT_MENU_ON_HOWER);
++
++ getWidgetForPaintable().enabled = !uidl.getBooleanAttribute("disabled");
++
++ // For future connections
++ getWidgetForPaintable().client = client;
++ getWidgetForPaintable().uidlId = uidl.getId();
++
++ // Empty the menu every time it receives new information
++ if (!getWidgetForPaintable().getItems().isEmpty()) {
++ getWidgetForPaintable().clearItems();
++ }
++
++ UIDL options = uidl.getChildUIDL(0);
++
++ if (uidl.hasAttribute("width")) {
++ UIDL moreItemUIDL = options.getChildUIDL(0);
++ StringBuffer itemHTML = new StringBuffer();
++
++ if (moreItemUIDL.hasAttribute("icon")) {
++ itemHTML.append("<img src=\""
++ + Util.escapeAttribute(client
++ .translateVaadinUri(moreItemUIDL
++ .getStringAttribute("icon")))
++ + "\" class=\"" + Icon.CLASSNAME + "\" alt=\"\" />");
++ }
++
++ String moreItemText = moreItemUIDL.getStringAttribute("text");
++ if ("".equals(moreItemText)) {
++ moreItemText = "►";
++ }
++ itemHTML.append(moreItemText);
++
++ getWidgetForPaintable().moreItem = GWT.create(CustomMenuItem.class);
++ getWidgetForPaintable().moreItem.setHTML(itemHTML.toString());
++ getWidgetForPaintable().moreItem.setCommand(VMenuBar.emptyCommand);
++
++ getWidgetForPaintable().collapsedRootItems = new VMenuBar(true,
++ getWidgetForPaintable());
++ getWidgetForPaintable().moreItem
++ .setSubMenu(getWidgetForPaintable().collapsedRootItems);
++ getWidgetForPaintable().moreItem.addStyleName(VMenuBar.CLASSNAME
++ + "-more-menuitem");
++ }
++
++ UIDL uidlItems = uidl.getChildUIDL(1);
++ Iterator<Object> itr = uidlItems.getChildIterator();
++ Stack<Iterator<Object>> iteratorStack = new Stack<Iterator<Object>>();
++ Stack<VMenuBar> menuStack = new Stack<VMenuBar>();
++ VMenuBar currentMenu = getWidgetForPaintable();
++
++ while (itr.hasNext()) {
++ UIDL item = (UIDL) itr.next();
++ CustomMenuItem currentItem = null;
++
++ final int itemId = item.getIntAttribute("id");
++
++ boolean itemHasCommand = item.hasAttribute("command");
++ boolean itemIsCheckable = item
++ .hasAttribute(VMenuBar.ATTRIBUTE_CHECKED);
++
++ String itemHTML = getWidgetForPaintable().buildItemHTML(item);
++
++ Command cmd = null;
++ if (!item.hasAttribute("separator")) {
++ if (itemHasCommand || itemIsCheckable) {
++ // Construct a command that fires onMenuClick(int) with the
++ // item's id-number
++ cmd = new Command() {
++ public void execute() {
++ getWidgetForPaintable().hostReference
++ .onMenuClick(itemId);
++ }
++ };
++ }
++ }
++
++ currentItem = currentMenu.addItem(itemHTML.toString(), cmd);
++ currentItem.updateFromUIDL(item, client);
++
++ if (item.getChildCount() > 0) {
++ menuStack.push(currentMenu);
++ iteratorStack.push(itr);
++ itr = item.getChildIterator();
++ currentMenu = new VMenuBar(true, currentMenu);
++ if (uidl.hasAttribute("style")) {
++ for (String style : uidl.getStringAttribute("style").split(
++ " ")) {
++ currentMenu.addStyleDependentName(style);
++ }
++ }
++ currentItem.setSubMenu(currentMenu);
++ }
++
++ while (!itr.hasNext() && !iteratorStack.empty()) {
++ boolean hasCheckableItem = false;
++ for (CustomMenuItem menuItem : currentMenu.getItems()) {
++ hasCheckableItem = hasCheckableItem
++ || menuItem.isCheckable();
++ }
++ if (hasCheckableItem) {
++ currentMenu.addStyleDependentName("check-column");
++ } else {
++ currentMenu.removeStyleDependentName("check-column");
++ }
++
++ itr = iteratorStack.pop();
++ currentMenu = menuStack.pop();
++ }
++ }// while
++
++ getWidgetForPaintable().iLayout(false);
++
++ }// updateFromUIDL
++
++ @Override
++ protected Widget createWidget() {
++ return GWT.create(VMenuBar.class);
++ }
++
++ @Override
++ public VMenuBar getWidgetForPaintable() {
++ return (VMenuBar) super.getWidgetForPaintable();
++ }
++
++}
--- /dev/null
- package com.vaadin.terminal.gwt.client.ui;\r
- \r
- import java.util.ArrayList;\r
- import java.util.Iterator;\r
- \r
- import com.google.gwt.event.dom.client.DomEvent.Type;\r
- import com.google.gwt.event.shared.EventHandler;\r
- import com.google.gwt.event.shared.HandlerRegistration;\r
- import com.google.gwt.user.client.Element;\r
- import com.google.gwt.user.client.ui.Widget;\r
- import com.vaadin.terminal.gwt.client.ApplicationConnection;\r
- import com.vaadin.terminal.gwt.client.BrowserInfo;\r
- import com.vaadin.terminal.gwt.client.EventId;\r
- import com.vaadin.terminal.gwt.client.RenderInformation.FloatSize;\r
- import com.vaadin.terminal.gwt.client.UIDL;\r
- import com.vaadin.terminal.gwt.client.Util;\r
- import com.vaadin.terminal.gwt.client.VPaintableWidget;\r
- import com.vaadin.terminal.gwt.client.ui.layout.CellBasedLayoutPaintable;\r
- import com.vaadin.terminal.gwt.client.ui.layout.ChildComponentContainer;\r
- \r
- public abstract class VOrderedLayoutPaintable extends CellBasedLayoutPaintable {\r
- \r
- private LayoutClickEventHandler clickEventHandler = new LayoutClickEventHandler(\r
- this, EventId.LAYOUT_CLICK) {\r
- \r
- @Override\r
- protected VPaintableWidget getChildComponent(Element element) {\r
- return getWidgetForPaintable().getComponent(element);\r
- }\r
- \r
- @Override\r
- protected <H extends EventHandler> HandlerRegistration registerHandler(\r
- H handler, Type<H> type) {\r
- return getWidgetForPaintable().addDomHandler(handler, type);\r
- }\r
- };\r
- \r
- public void updateCaption(VPaintableWidget paintable, UIDL uidl) {\r
- Widget widget = paintable.getWidgetForPaintable();\r
- ChildComponentContainer componentContainer = getWidgetForPaintable()\r
- .getComponentContainer(widget);\r
- componentContainer.updateCaption(uidl, getConnection());\r
- if (!getWidgetForPaintable().isRendering) {\r
- /*\r
- * This was a component-only update and the possible size change\r
- * must be propagated to the layout\r
- */\r
- getConnection().captionSizeUpdated(widget);\r
- }\r
- }\r
- \r
- @Override\r
- public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {\r
- getWidgetForPaintable().isRendering = true;\r
- super.updateFromUIDL(uidl, client);\r
- \r
- // Only non-cached, visible UIDL:s can introduce changes\r
- if (uidl.getBooleanAttribute("cached")\r
- || uidl.getBooleanAttribute("invisible")) {\r
- getWidgetForPaintable().isRendering = false;\r
- return;\r
- }\r
- \r
- clickEventHandler.handleEventHandlerRegistration(client);\r
- \r
- // IStopWatch w = new IStopWatch("OrderedLayout.updateFromUIDL");\r
- \r
- ArrayList<Widget> uidlWidgets = new ArrayList<Widget>(\r
- uidl.getChildCount());\r
- ArrayList<ChildComponentContainer> relativeSizeComponents = new ArrayList<ChildComponentContainer>();\r
- ArrayList<UIDL> relativeSizeComponentUIDL = new ArrayList<UIDL>();\r
- \r
- int pos = 0;\r
- for (final Iterator<Object> it = uidl.getChildIterator(); it.hasNext();) {\r
- final UIDL childUIDL = (UIDL) it.next();\r
- final VPaintableWidget childPaintable = client\r
- .getPaintable(childUIDL);\r
- Widget widget = childPaintable.getWidgetForPaintable();\r
- \r
- // Create container for component\r
- ChildComponentContainer childComponentContainer = getWidgetForPaintable()\r
- .getComponentContainer(widget);\r
- \r
- if (childComponentContainer == null) {\r
- // This is a new component\r
- childComponentContainer = getWidgetForPaintable()\r
- .createChildContainer(childPaintable);\r
- } else {\r
- /*\r
- * The widget may be null if the same paintable has been\r
- * rendered in a different component container while this has\r
- * been invisible. Ensure the childComponentContainer has the\r
- * widget attached. See e.g. #5372\r
- */\r
- childComponentContainer.setPaintable(childPaintable);\r
- }\r
- \r
- getWidgetForPaintable().addOrMoveChild(childComponentContainer,\r
- pos++);\r
- \r
- /*\r
- * Components which are to be expanded in the same orientation as\r
- * the layout are rendered later when it is clear how much space\r
- * they can use\r
- */\r
- if (!Util.isCached(childUIDL)) {\r
- FloatSize relativeSize = Util.parseRelativeSize(childUIDL);\r
- childComponentContainer.setRelativeSize(relativeSize);\r
- }\r
- \r
- if (childComponentContainer\r
- .isComponentRelativeSized(getWidgetForPaintable().orientation)) {\r
- relativeSizeComponents.add(childComponentContainer);\r
- relativeSizeComponentUIDL.add(childUIDL);\r
- } else {\r
- if (getWidgetForPaintable().isDynamicWidth()) {\r
- childComponentContainer.renderChild(childUIDL, client, -1);\r
- } else {\r
- childComponentContainer\r
- .renderChild(childUIDL, client,\r
- getWidgetForPaintable().activeLayoutSize\r
- .getWidth());\r
- }\r
- if (getWidgetForPaintable().sizeHasChangedDuringRendering\r
- && Util.isCached(childUIDL)) {\r
- // notify cached relative sized component about size\r
- // chance\r
- client.handleComponentRelativeSize(childComponentContainer\r
- .getWidget());\r
- }\r
- }\r
- \r
- uidlWidgets.add(widget);\r
- \r
- }\r
- \r
- // w.mark("Rendering of "\r
- // + (uidlWidgets.size() - relativeSizeComponents.size())\r
- // + " absolute size components done");\r
- \r
- /*\r
- * Remove any children after pos. These are the ones that previously\r
- * were in the layout but have now been removed\r
- */\r
- getWidgetForPaintable().removeChildrenAfter(pos);\r
- \r
- // w.mark("Old children removed");\r
- \r
- /* Fetch alignments and expand ratio from UIDL */\r
- getWidgetForPaintable().updateAlignmentsAndExpandRatios(uidl,\r
- uidlWidgets);\r
- // w.mark("Alignments and expand ratios updated");\r
- \r
- /* Fetch widget sizes from rendered components */\r
- getWidgetForPaintable().updateWidgetSizes();\r
- // w.mark("Widget sizes updated");\r
- \r
- getWidgetForPaintable().recalculateLayout();\r
- // w.mark("Layout size calculated (" + activeLayoutSize +\r
- // ") offsetSize: "\r
- // + getOffsetWidth() + "," + getOffsetHeight());\r
- \r
- /* Render relative size components */\r
- for (int i = 0; i < relativeSizeComponents.size(); i++) {\r
- ChildComponentContainer childComponentContainer = relativeSizeComponents\r
- .get(i);\r
- UIDL childUIDL = relativeSizeComponentUIDL.get(i);\r
- \r
- if (getWidgetForPaintable().isDynamicWidth()) {\r
- childComponentContainer.renderChild(childUIDL, client, -1);\r
- } else {\r
- childComponentContainer.renderChild(childUIDL, client,\r
- getWidgetForPaintable().activeLayoutSize.getWidth());\r
- }\r
- \r
- if (Util.isCached(childUIDL)) {\r
- /*\r
- * We must update the size of the relative sized component if\r
- * the expand ratio or something else in the layout changes\r
- * which affects the size of a relative sized component\r
- */\r
- client.handleComponentRelativeSize(childComponentContainer\r
- .getWidget());\r
- }\r
- \r
- // childComponentContainer.updateWidgetSize();\r
- }\r
- \r
- // w.mark("Rendering of " + (relativeSizeComponents.size())\r
- // + " relative size components done");\r
- \r
- /* Fetch widget sizes for relative size components */\r
- for (ChildComponentContainer childComponentContainer : getWidgetForPaintable()\r
- .getComponentContainers()) {\r
- \r
- /* Update widget size from DOM */\r
- childComponentContainer.updateWidgetSize();\r
- }\r
- \r
- // w.mark("Widget sizes updated");\r
- \r
- /*\r
- * Components with relative size in main direction may affect the layout\r
- * size in the other direction\r
- */\r
- if ((getWidgetForPaintable().isHorizontal() && getWidgetForPaintable()\r
- .isDynamicHeight())\r
- || (getWidgetForPaintable().isVertical() && getWidgetForPaintable()\r
- .isDynamicWidth())) {\r
- getWidgetForPaintable().layoutSizeMightHaveChanged();\r
- }\r
- // w.mark("Layout dimensions updated");\r
- \r
- /* Update component spacing */\r
- getWidgetForPaintable().updateContainerMargins();\r
- \r
- /*\r
- * Update component sizes for components with relative size in non-main\r
- * direction\r
- */\r
- if (getWidgetForPaintable().updateRelativeSizesInNonMainDirection()) {\r
- // Sizes updated - might affect the other dimension so we need to\r
- // recheck the widget sizes and recalculate layout dimensions\r
- getWidgetForPaintable().updateWidgetSizes();\r
- getWidgetForPaintable().layoutSizeMightHaveChanged();\r
- }\r
- getWidgetForPaintable().calculateAlignments();\r
- // w.mark("recalculateComponentSizesAndAlignments done");\r
- \r
- getWidgetForPaintable().setRootSize();\r
- \r
- if (BrowserInfo.get().isIE()) {\r
- /*\r
- * This should fix the issue with padding not always taken into\r
- * account for the containers leading to no spacing between\r
- * elements.\r
- */\r
- getWidgetForPaintable().root.getStyle().setProperty("zoom", "1");\r
- }\r
- \r
- // w.mark("runDescendentsLayout done");\r
- getWidgetForPaintable().isRendering = false;\r
- getWidgetForPaintable().sizeHasChangedDuringRendering = false;\r
- }\r
- \r
- @Override\r
- protected abstract VOrderedLayout createWidget();\r
- \r
- @Override\r
- public VOrderedLayout getWidgetForPaintable() {\r
- return (VOrderedLayout) super.getWidgetForPaintable();\r
- }\r
- \r
- }\r
++package com.vaadin.terminal.gwt.client.ui;
++
++import java.util.ArrayList;
++import java.util.Iterator;
++
++import com.google.gwt.event.dom.client.DomEvent.Type;
++import com.google.gwt.event.shared.EventHandler;
++import com.google.gwt.event.shared.HandlerRegistration;
++import com.google.gwt.user.client.Element;
++import com.google.gwt.user.client.ui.Widget;
++import com.vaadin.terminal.gwt.client.ApplicationConnection;
++import com.vaadin.terminal.gwt.client.BrowserInfo;
++import com.vaadin.terminal.gwt.client.EventId;
++import com.vaadin.terminal.gwt.client.RenderInformation.FloatSize;
++import com.vaadin.terminal.gwt.client.UIDL;
++import com.vaadin.terminal.gwt.client.Util;
++import com.vaadin.terminal.gwt.client.VPaintableWidget;
++import com.vaadin.terminal.gwt.client.ui.layout.CellBasedLayoutPaintable;
++import com.vaadin.terminal.gwt.client.ui.layout.ChildComponentContainer;
++
++public abstract class VOrderedLayoutPaintable extends CellBasedLayoutPaintable {
++
++ private LayoutClickEventHandler clickEventHandler = new LayoutClickEventHandler(
++ this, EventId.LAYOUT_CLICK) {
++
++ @Override
++ protected VPaintableWidget getChildComponent(Element element) {
++ return getWidgetForPaintable().getComponent(element);
++ }
++
++ @Override
++ protected <H extends EventHandler> HandlerRegistration registerHandler(
++ H handler, Type<H> type) {
++ return getWidgetForPaintable().addDomHandler(handler, type);
++ }
++ };
++
++ public void updateCaption(VPaintableWidget paintable, UIDL uidl) {
++ Widget widget = paintable.getWidgetForPaintable();
++ ChildComponentContainer componentContainer = getWidgetForPaintable()
++ .getComponentContainer(widget);
++ componentContainer.updateCaption(uidl, getConnection());
++ if (!getWidgetForPaintable().isRendering) {
++ /*
++ * This was a component-only update and the possible size change
++ * must be propagated to the layout
++ */
++ getConnection().captionSizeUpdated(widget);
++ }
++ }
++
++ @Override
++ public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {
++ getWidgetForPaintable().isRendering = true;
++ super.updateFromUIDL(uidl, client);
++
++ // Only non-cached, visible UIDL:s can introduce changes
++ if (uidl.getBooleanAttribute("cached")
++ || uidl.getBooleanAttribute("invisible")) {
++ getWidgetForPaintable().isRendering = false;
++ return;
++ }
++
++ clickEventHandler.handleEventHandlerRegistration(client);
++
++ // IStopWatch w = new IStopWatch("OrderedLayout.updateFromUIDL");
++
++ ArrayList<Widget> uidlWidgets = new ArrayList<Widget>(
++ uidl.getChildCount());
++ ArrayList<ChildComponentContainer> relativeSizeComponents = new ArrayList<ChildComponentContainer>();
++ ArrayList<UIDL> relativeSizeComponentUIDL = new ArrayList<UIDL>();
++
++ int pos = 0;
++ for (final Iterator<Object> it = uidl.getChildIterator(); it.hasNext();) {
++ final UIDL childUIDL = (UIDL) it.next();
++ final VPaintableWidget childPaintable = client
++ .getPaintable(childUIDL);
++ Widget widget = childPaintable.getWidgetForPaintable();
++
++ // Create container for component
++ ChildComponentContainer childComponentContainer = getWidgetForPaintable()
++ .getComponentContainer(widget);
++
++ if (childComponentContainer == null) {
++ // This is a new component
++ childComponentContainer = getWidgetForPaintable()
++ .createChildContainer(childPaintable);
++ } else {
++ /*
++ * The widget may be null if the same paintable has been
++ * rendered in a different component container while this has
++ * been invisible. Ensure the childComponentContainer has the
++ * widget attached. See e.g. #5372
++ */
++ childComponentContainer.setPaintable(childPaintable);
++ }
++
++ getWidgetForPaintable().addOrMoveChild(childComponentContainer,
++ pos++);
++
++ /*
++ * Components which are to be expanded in the same orientation as
++ * the layout are rendered later when it is clear how much space
++ * they can use
++ */
++ if (!Util.isCached(childUIDL)) {
++ FloatSize relativeSize = Util.parseRelativeSize(childUIDL);
++ childComponentContainer.setRelativeSize(relativeSize);
++ }
++
++ if (childComponentContainer
++ .isComponentRelativeSized(getWidgetForPaintable().orientation)) {
++ relativeSizeComponents.add(childComponentContainer);
++ relativeSizeComponentUIDL.add(childUIDL);
++ } else {
++ if (getWidgetForPaintable().isDynamicWidth()) {
++ childComponentContainer.renderChild(childUIDL, client, -1);
++ } else {
++ childComponentContainer
++ .renderChild(childUIDL, client,
++ getWidgetForPaintable().activeLayoutSize
++ .getWidth());
++ }
++ if (getWidgetForPaintable().sizeHasChangedDuringRendering
++ && Util.isCached(childUIDL)) {
++ // notify cached relative sized component about size
++ // chance
++ client.handleComponentRelativeSize(childComponentContainer
++ .getWidget());
++ }
++ }
++
++ uidlWidgets.add(widget);
++
++ }
++
++ // w.mark("Rendering of "
++ // + (uidlWidgets.size() - relativeSizeComponents.size())
++ // + " absolute size components done");
++
++ /*
++ * Remove any children after pos. These are the ones that previously
++ * were in the layout but have now been removed
++ */
++ getWidgetForPaintable().removeChildrenAfter(pos);
++
++ // w.mark("Old children removed");
++
++ /* Fetch alignments and expand ratio from UIDL */
++ getWidgetForPaintable().updateAlignmentsAndExpandRatios(uidl,
++ uidlWidgets);
++ // w.mark("Alignments and expand ratios updated");
++
++ /* Fetch widget sizes from rendered components */
++ getWidgetForPaintable().updateWidgetSizes();
++ // w.mark("Widget sizes updated");
++
++ getWidgetForPaintable().recalculateLayout();
++ // w.mark("Layout size calculated (" + activeLayoutSize +
++ // ") offsetSize: "
++ // + getOffsetWidth() + "," + getOffsetHeight());
++
++ /* Render relative size components */
++ for (int i = 0; i < relativeSizeComponents.size(); i++) {
++ ChildComponentContainer childComponentContainer = relativeSizeComponents
++ .get(i);
++ UIDL childUIDL = relativeSizeComponentUIDL.get(i);
++
++ if (getWidgetForPaintable().isDynamicWidth()) {
++ childComponentContainer.renderChild(childUIDL, client, -1);
++ } else {
++ childComponentContainer.renderChild(childUIDL, client,
++ getWidgetForPaintable().activeLayoutSize.getWidth());
++ }
++
++ if (Util.isCached(childUIDL)) {
++ /*
++ * We must update the size of the relative sized component if
++ * the expand ratio or something else in the layout changes
++ * which affects the size of a relative sized component
++ */
++ client.handleComponentRelativeSize(childComponentContainer
++ .getWidget());
++ }
++
++ // childComponentContainer.updateWidgetSize();
++ }
++
++ // w.mark("Rendering of " + (relativeSizeComponents.size())
++ // + " relative size components done");
++
++ /* Fetch widget sizes for relative size components */
++ for (ChildComponentContainer childComponentContainer : getWidgetForPaintable()
++ .getComponentContainers()) {
++
++ /* Update widget size from DOM */
++ childComponentContainer.updateWidgetSize();
++ }
++
++ // w.mark("Widget sizes updated");
++
++ /*
++ * Components with relative size in main direction may affect the layout
++ * size in the other direction
++ */
++ if ((getWidgetForPaintable().isHorizontal() && getWidgetForPaintable()
++ .isDynamicHeight())
++ || (getWidgetForPaintable().isVertical() && getWidgetForPaintable()
++ .isDynamicWidth())) {
++ getWidgetForPaintable().layoutSizeMightHaveChanged();
++ }
++ // w.mark("Layout dimensions updated");
++
++ /* Update component spacing */
++ getWidgetForPaintable().updateContainerMargins();
++
++ /*
++ * Update component sizes for components with relative size in non-main
++ * direction
++ */
++ if (getWidgetForPaintable().updateRelativeSizesInNonMainDirection()) {
++ // Sizes updated - might affect the other dimension so we need to
++ // recheck the widget sizes and recalculate layout dimensions
++ getWidgetForPaintable().updateWidgetSizes();
++ getWidgetForPaintable().layoutSizeMightHaveChanged();
++ }
++ getWidgetForPaintable().calculateAlignments();
++ // w.mark("recalculateComponentSizesAndAlignments done");
++
++ getWidgetForPaintable().setRootSize();
++
++ if (BrowserInfo.get().isIE()) {
++ /*
++ * This should fix the issue with padding not always taken into
++ * account for the containers leading to no spacing between
++ * elements.
++ */
++ getWidgetForPaintable().root.getStyle().setProperty("zoom", "1");
++ }
++
++ // w.mark("runDescendentsLayout done");
++ getWidgetForPaintable().isRendering = false;
++ getWidgetForPaintable().sizeHasChangedDuringRendering = false;
++ }
++
++ @Override
++ protected abstract VOrderedLayout createWidget();
++
++ @Override
++ public VOrderedLayout getWidgetForPaintable() {
++ return (VOrderedLayout) super.getWidgetForPaintable();
++ }
++
++}
--- /dev/null
- package com.vaadin.terminal.gwt.client.ui;\r
- \r
- import com.google.gwt.core.client.GWT;\r
- import com.google.gwt.event.dom.client.DomEvent.Type;\r
- import com.google.gwt.event.shared.EventHandler;\r
- import com.google.gwt.event.shared.HandlerRegistration;\r
- import com.google.gwt.user.client.ui.Widget;\r
- import com.vaadin.terminal.gwt.client.ApplicationConnection;\r
- import com.vaadin.terminal.gwt.client.UIDL;\r
- import com.vaadin.terminal.gwt.client.VPaintableWidget;\r
- \r
- public class VPanelPaintable extends VAbstractPaintableWidgetContainer {\r
- \r
- public static final String CLICK_EVENT_IDENTIFIER = "click";\r
- \r
- private ClickEventHandler clickEventHandler = new ClickEventHandler(this,\r
- CLICK_EVENT_IDENTIFIER) {\r
- \r
- @Override\r
- protected <H extends EventHandler> HandlerRegistration registerHandler(\r
- H handler, Type<H> type) {\r
- return getWidgetForPaintable().addDomHandler(handler, type);\r
- }\r
- };\r
- \r
- public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {\r
- getWidgetForPaintable().rendering = true;\r
- if (!uidl.hasAttribute("cached")) {\r
- \r
- // Handle caption displaying and style names, prior generics.\r
- // Affects size\r
- // calculations\r
- \r
- // Restore default stylenames\r
- getWidgetForPaintable().contentNode.setClassName(VPanel.CLASSNAME\r
- + "-content");\r
- getWidgetForPaintable().bottomDecoration\r
- .setClassName(VPanel.CLASSNAME + "-deco");\r
- getWidgetForPaintable().captionNode.setClassName(VPanel.CLASSNAME\r
- + "-caption");\r
- boolean hasCaption = false;\r
- if (uidl.hasAttribute("caption")\r
- && !uidl.getStringAttribute("caption").equals("")) {\r
- getWidgetForPaintable().setCaption(\r
- uidl.getStringAttribute("caption"));\r
- hasCaption = true;\r
- } else {\r
- getWidgetForPaintable().setCaption("");\r
- getWidgetForPaintable().captionNode\r
- .setClassName(VPanel.CLASSNAME + "-nocaption");\r
- }\r
- \r
- // Add proper stylenames for all elements. This way we can prevent\r
- // unwanted CSS selector inheritance.\r
- if (uidl.hasAttribute("style")) {\r
- final String[] styles = uidl.getStringAttribute("style").split(\r
- " ");\r
- final String captionBaseClass = VPanel.CLASSNAME\r
- + (hasCaption ? "-caption" : "-nocaption");\r
- final String contentBaseClass = VPanel.CLASSNAME + "-content";\r
- final String decoBaseClass = VPanel.CLASSNAME + "-deco";\r
- String captionClass = captionBaseClass;\r
- String contentClass = contentBaseClass;\r
- String decoClass = decoBaseClass;\r
- for (int i = 0; i < styles.length; i++) {\r
- captionClass += " " + captionBaseClass + "-" + styles[i];\r
- contentClass += " " + contentBaseClass + "-" + styles[i];\r
- decoClass += " " + decoBaseClass + "-" + styles[i];\r
- }\r
- getWidgetForPaintable().captionNode.setClassName(captionClass);\r
- getWidgetForPaintable().contentNode.setClassName(contentClass);\r
- getWidgetForPaintable().bottomDecoration\r
- .setClassName(decoClass);\r
- \r
- }\r
- }\r
- // Ensure correct implementation\r
- if (client.updateComponent(this, uidl, false)) {\r
- getWidgetForPaintable().rendering = false;\r
- return;\r
- }\r
- \r
- clickEventHandler.handleEventHandlerRegistration(client);\r
- \r
- getWidgetForPaintable().client = client;\r
- getWidgetForPaintable().id = uidl.getId();\r
- \r
- getWidgetForPaintable().setIconUri(uidl, client);\r
- \r
- getWidgetForPaintable().handleError(uidl);\r
- \r
- // Render content\r
- final UIDL layoutUidl = uidl.getChildUIDL(0);\r
- final VPaintableWidget newLayout = client.getPaintable(layoutUidl);\r
- if (newLayout != getWidgetForPaintable().layout) {\r
- if (getWidgetForPaintable().layout != null) {\r
- client.unregisterPaintable(getWidgetForPaintable().layout);\r
- }\r
- getWidgetForPaintable()\r
- .setWidget(newLayout.getWidgetForPaintable());\r
- getWidgetForPaintable().layout = newLayout;\r
- }\r
- getWidgetForPaintable().layout.updateFromUIDL(layoutUidl, client);\r
- \r
- // We may have actions attached to this panel\r
- if (uidl.getChildCount() > 1) {\r
- final int cnt = uidl.getChildCount();\r
- for (int i = 1; i < cnt; i++) {\r
- UIDL childUidl = uidl.getChildUIDL(i);\r
- if (childUidl.getTag().equals("actions")) {\r
- if (getWidgetForPaintable().shortcutHandler == null) {\r
- getWidgetForPaintable().shortcutHandler = new ShortcutActionHandler(\r
- getId(), client);\r
- }\r
- getWidgetForPaintable().shortcutHandler\r
- .updateActionMap(childUidl);\r
- }\r
- }\r
- }\r
- \r
- if (uidl.hasVariable("scrollTop")\r
- && uidl.getIntVariable("scrollTop") != getWidgetForPaintable().scrollTop) {\r
- getWidgetForPaintable().scrollTop = uidl\r
- .getIntVariable("scrollTop");\r
- getWidgetForPaintable().contentNode\r
- .setScrollTop(getWidgetForPaintable().scrollTop);\r
- // re-read the actual scrollTop in case invalid value was set\r
- // (scrollTop != 0 when no scrollbar exists, other values would be\r
- // caught by scroll listener), see #3784\r
- getWidgetForPaintable().scrollTop = getWidgetForPaintable().contentNode\r
- .getScrollTop();\r
- }\r
- \r
- if (uidl.hasVariable("scrollLeft")\r
- && uidl.getIntVariable("scrollLeft") != getWidgetForPaintable().scrollLeft) {\r
- getWidgetForPaintable().scrollLeft = uidl\r
- .getIntVariable("scrollLeft");\r
- getWidgetForPaintable().contentNode\r
- .setScrollLeft(getWidgetForPaintable().scrollLeft);\r
- // re-read the actual scrollTop in case invalid value was set\r
- // (scrollTop != 0 when no scrollbar exists, other values would be\r
- // caught by scroll listener), see #3784\r
- getWidgetForPaintable().scrollLeft = getWidgetForPaintable().contentNode\r
- .getScrollLeft();\r
- }\r
- \r
- // Must be run after scrollTop is set as Webkit overflow fix re-sets the\r
- // scrollTop\r
- getWidgetForPaintable().runHacks(false);\r
- \r
- // And apply tab index\r
- if (uidl.hasVariable("tabindex")) {\r
- getWidgetForPaintable().contentNode.setTabIndex(uidl\r
- .getIntVariable("tabindex"));\r
- }\r
- \r
- getWidgetForPaintable().rendering = false;\r
- \r
- }\r
- \r
- public void updateCaption(VPaintableWidget component, UIDL uidl) {\r
- // NOP: layouts caption, errors etc not rendered in Panel\r
- }\r
- \r
- @Override\r
- public VPanel getWidgetForPaintable() {\r
- return (VPanel) super.getWidgetForPaintable();\r
- }\r
- \r
- @Override\r
- protected Widget createWidget() {\r
- return GWT.create(VPanel.class);\r
- }\r
- \r
- }\r
++package com.vaadin.terminal.gwt.client.ui;
++
++import com.google.gwt.core.client.GWT;
++import com.google.gwt.event.dom.client.DomEvent.Type;
++import com.google.gwt.event.shared.EventHandler;
++import com.google.gwt.event.shared.HandlerRegistration;
++import com.google.gwt.user.client.ui.Widget;
++import com.vaadin.terminal.gwt.client.ApplicationConnection;
++import com.vaadin.terminal.gwt.client.UIDL;
++import com.vaadin.terminal.gwt.client.VPaintableWidget;
++
++public class VPanelPaintable extends VAbstractPaintableWidgetContainer {
++
++ public static final String CLICK_EVENT_IDENTIFIER = "click";
++
++ private ClickEventHandler clickEventHandler = new ClickEventHandler(this,
++ CLICK_EVENT_IDENTIFIER) {
++
++ @Override
++ protected <H extends EventHandler> HandlerRegistration registerHandler(
++ H handler, Type<H> type) {
++ return getWidgetForPaintable().addDomHandler(handler, type);
++ }
++ };
++
++ public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {
++ getWidgetForPaintable().rendering = true;
++ if (!uidl.hasAttribute("cached")) {
++
++ // Handle caption displaying and style names, prior generics.
++ // Affects size
++ // calculations
++
++ // Restore default stylenames
++ getWidgetForPaintable().contentNode.setClassName(VPanel.CLASSNAME
++ + "-content");
++ getWidgetForPaintable().bottomDecoration
++ .setClassName(VPanel.CLASSNAME + "-deco");
++ getWidgetForPaintable().captionNode.setClassName(VPanel.CLASSNAME
++ + "-caption");
++ boolean hasCaption = false;
++ if (uidl.hasAttribute("caption")
++ && !uidl.getStringAttribute("caption").equals("")) {
++ getWidgetForPaintable().setCaption(
++ uidl.getStringAttribute("caption"));
++ hasCaption = true;
++ } else {
++ getWidgetForPaintable().setCaption("");
++ getWidgetForPaintable().captionNode
++ .setClassName(VPanel.CLASSNAME + "-nocaption");
++ }
++
++ // Add proper stylenames for all elements. This way we can prevent
++ // unwanted CSS selector inheritance.
++ if (uidl.hasAttribute("style")) {
++ final String[] styles = uidl.getStringAttribute("style").split(
++ " ");
++ final String captionBaseClass = VPanel.CLASSNAME
++ + (hasCaption ? "-caption" : "-nocaption");
++ final String contentBaseClass = VPanel.CLASSNAME + "-content";
++ final String decoBaseClass = VPanel.CLASSNAME + "-deco";
++ String captionClass = captionBaseClass;
++ String contentClass = contentBaseClass;
++ String decoClass = decoBaseClass;
++ for (int i = 0; i < styles.length; i++) {
++ captionClass += " " + captionBaseClass + "-" + styles[i];
++ contentClass += " " + contentBaseClass + "-" + styles[i];
++ decoClass += " " + decoBaseClass + "-" + styles[i];
++ }
++ getWidgetForPaintable().captionNode.setClassName(captionClass);
++ getWidgetForPaintable().contentNode.setClassName(contentClass);
++ getWidgetForPaintable().bottomDecoration
++ .setClassName(decoClass);
++
++ }
++ }
++ // Ensure correct implementation
++ if (client.updateComponent(this, uidl, false)) {
++ getWidgetForPaintable().rendering = false;
++ return;
++ }
++
++ clickEventHandler.handleEventHandlerRegistration(client);
++
++ getWidgetForPaintable().client = client;
++ getWidgetForPaintable().id = uidl.getId();
++
++ getWidgetForPaintable().setIconUri(uidl, client);
++
++ getWidgetForPaintable().handleError(uidl);
++
++ // Render content
++ final UIDL layoutUidl = uidl.getChildUIDL(0);
++ final VPaintableWidget newLayout = client.getPaintable(layoutUidl);
++ if (newLayout != getWidgetForPaintable().layout) {
++ if (getWidgetForPaintable().layout != null) {
++ client.unregisterPaintable(getWidgetForPaintable().layout);
++ }
++ getWidgetForPaintable()
++ .setWidget(newLayout.getWidgetForPaintable());
++ getWidgetForPaintable().layout = newLayout;
++ }
++ getWidgetForPaintable().layout.updateFromUIDL(layoutUidl, client);
++
++ // We may have actions attached to this panel
++ if (uidl.getChildCount() > 1) {
++ final int cnt = uidl.getChildCount();
++ for (int i = 1; i < cnt; i++) {
++ UIDL childUidl = uidl.getChildUIDL(i);
++ if (childUidl.getTag().equals("actions")) {
++ if (getWidgetForPaintable().shortcutHandler == null) {
++ getWidgetForPaintable().shortcutHandler = new ShortcutActionHandler(
++ getId(), client);
++ }
++ getWidgetForPaintable().shortcutHandler
++ .updateActionMap(childUidl);
++ }
++ }
++ }
++
++ if (uidl.hasVariable("scrollTop")
++ && uidl.getIntVariable("scrollTop") != getWidgetForPaintable().scrollTop) {
++ getWidgetForPaintable().scrollTop = uidl
++ .getIntVariable("scrollTop");
++ getWidgetForPaintable().contentNode
++ .setScrollTop(getWidgetForPaintable().scrollTop);
++ // re-read the actual scrollTop in case invalid value was set
++ // (scrollTop != 0 when no scrollbar exists, other values would be
++ // caught by scroll listener), see #3784
++ getWidgetForPaintable().scrollTop = getWidgetForPaintable().contentNode
++ .getScrollTop();
++ }
++
++ if (uidl.hasVariable("scrollLeft")
++ && uidl.getIntVariable("scrollLeft") != getWidgetForPaintable().scrollLeft) {
++ getWidgetForPaintable().scrollLeft = uidl
++ .getIntVariable("scrollLeft");
++ getWidgetForPaintable().contentNode
++ .setScrollLeft(getWidgetForPaintable().scrollLeft);
++ // re-read the actual scrollTop in case invalid value was set
++ // (scrollTop != 0 when no scrollbar exists, other values would be
++ // caught by scroll listener), see #3784
++ getWidgetForPaintable().scrollLeft = getWidgetForPaintable().contentNode
++ .getScrollLeft();
++ }
++
++ // Must be run after scrollTop is set as Webkit overflow fix re-sets the
++ // scrollTop
++ getWidgetForPaintable().runHacks(false);
++
++ // And apply tab index
++ if (uidl.hasVariable("tabindex")) {
++ getWidgetForPaintable().contentNode.setTabIndex(uidl
++ .getIntVariable("tabindex"));
++ }
++
++ getWidgetForPaintable().rendering = false;
++
++ }
++
++ public void updateCaption(VPaintableWidget component, UIDL uidl) {
++ // NOP: layouts caption, errors etc not rendered in Panel
++ }
++
++ @Override
++ public VPanel getWidgetForPaintable() {
++ return (VPanel) super.getWidgetForPaintable();
++ }
++
++ @Override
++ protected Widget createWidget() {
++ return GWT.create(VPanel.class);
++ }
++
++}
- /*\r
- @VaadinApache2LicenseForJavaFiles@\r
- */\r
- \r
- package com.vaadin.terminal.gwt.client.ui;\r
- \r
- import java.util.Date;\r
- \r
- import com.google.gwt.core.client.GWT;\r
- import com.google.gwt.event.dom.client.ClickEvent;\r
- import com.google.gwt.event.dom.client.ClickHandler;\r
- import com.google.gwt.event.dom.client.DomEvent;\r
- import com.google.gwt.event.dom.client.KeyCodes;\r
- import com.google.gwt.event.logical.shared.CloseEvent;\r
- import com.google.gwt.event.logical.shared.CloseHandler;\r
- import com.google.gwt.user.client.DOM;\r
- import com.google.gwt.user.client.Element;\r
- import com.google.gwt.user.client.Event;\r
- import com.google.gwt.user.client.Timer;\r
- import com.google.gwt.user.client.Window;\r
- import com.google.gwt.user.client.ui.Button;\r
- import com.google.gwt.user.client.ui.PopupPanel;\r
- import com.google.gwt.user.client.ui.PopupPanel.PositionCallback;\r
- import com.vaadin.terminal.gwt.client.BrowserInfo;\r
- import com.vaadin.terminal.gwt.client.VConsole;\r
- import com.vaadin.terminal.gwt.client.ui.VCalendarPanel.FocusOutListener;\r
- import com.vaadin.terminal.gwt.client.ui.VCalendarPanel.SubmitListener;\r
- \r
- /**\r
- * Represents a date selection component with a text field and a popup date\r
- * selector.\r
- * \r
- * <b>Note:</b> To change the keyboard assignments used in the popup dialog you\r
- * should extend <code>com.vaadin.terminal.gwt.client.ui.VCalendarPanel</code>\r
- * and then pass set it by calling the\r
- * <code>setCalendarPanel(VCalendarPanel panel)</code> method.\r
- * \r
- */\r
- public class VPopupCalendar extends VTextualDate implements Field,\r
- ClickHandler, CloseHandler<PopupPanel>, SubPartAware {\r
- \r
- protected static final String POPUP_PRIMARY_STYLE_NAME = VDateField.CLASSNAME\r
- + "-popup";\r
- \r
- protected final Button calendarToggle;\r
- \r
- protected VCalendarPanel calendar;\r
- \r
- protected final VOverlay popup;\r
- private boolean open = false;\r
- protected boolean parsable = true;\r
- \r
- public VPopupCalendar() {\r
- super();\r
- \r
- calendarToggle = new Button();\r
- calendarToggle.setStyleName(CLASSNAME + "-button");\r
- calendarToggle.setText("");\r
- calendarToggle.addClickHandler(this);\r
- // -2 instead of -1 to avoid FocusWidget.onAttach to reset it\r
- calendarToggle.getElement().setTabIndex(-2);\r
- add(calendarToggle);\r
- \r
- calendar = GWT.create(VCalendarPanel.class);\r
- calendar.setFocusOutListener(new FocusOutListener() {\r
- public boolean onFocusOut(DomEvent<?> event) {\r
- event.preventDefault();\r
- closeCalendarPanel();\r
- return true;\r
- }\r
- });\r
- \r
- calendar.setSubmitListener(new SubmitListener() {\r
- public void onSubmit() {\r
- // Update internal value and send valuechange event if immediate\r
- updateValue(calendar.getDate());\r
- \r
- // Update text field (a must when not immediate).\r
- buildDate(true);\r
- \r
- closeCalendarPanel();\r
- }\r
- \r
- public void onCancel() {\r
- closeCalendarPanel();\r
- }\r
- });\r
- \r
- popup = new VOverlay(true, true, true);\r
- popup.setStyleName(POPUP_PRIMARY_STYLE_NAME);\r
- popup.setWidget(calendar);\r
- popup.addCloseHandler(this);\r
- \r
- DOM.setElementProperty(calendar.getElement(), "id",\r
- "PID_VAADIN_POPUPCAL");\r
- \r
- sinkEvents(Event.ONKEYDOWN);\r
- \r
- }\r
- \r
- @SuppressWarnings("deprecation")\r
- protected void updateValue(Date newDate) {\r
- Date currentDate = getCurrentDate();\r
- if (currentDate == null || newDate.getTime() != currentDate.getTime()) {\r
- setCurrentDate((Date) newDate.clone());\r
- getClient().updateVariable(getId(), "year",\r
- newDate.getYear() + 1900, false);\r
- if (getCurrentResolution() > VDateField.RESOLUTION_YEAR) {\r
- getClient().updateVariable(getId(), "month",\r
- newDate.getMonth() + 1, false);\r
- if (getCurrentResolution() > RESOLUTION_MONTH) {\r
- getClient().updateVariable(getId(), "day",\r
- newDate.getDate(), false);\r
- if (getCurrentResolution() > RESOLUTION_DAY) {\r
- getClient().updateVariable(getId(), "hour",\r
- newDate.getHours(), false);\r
- if (getCurrentResolution() > RESOLUTION_HOUR) {\r
- getClient().updateVariable(getId(), "min",\r
- newDate.getMinutes(), false);\r
- if (getCurrentResolution() > RESOLUTION_MIN) {\r
- getClient().updateVariable(getId(), "sec",\r
- newDate.getSeconds(), false);\r
- }\r
- }\r
- }\r
- }\r
- }\r
- if (isImmediate()) {\r
- getClient().sendPendingVariableChanges();\r
- }\r
- }\r
- }\r
- \r
- /*\r
- * (non-Javadoc)\r
- * \r
- * @see\r
- * com.google.gwt.user.client.ui.UIObject#setStyleName(java.lang.String)\r
- */\r
- @Override\r
- public void setStyleName(String style) {\r
- // make sure the style is there before size calculation\r
- super.setStyleName(style + " " + CLASSNAME + "-popupcalendar");\r
- }\r
- \r
- /**\r
- * Opens the calendar panel popup\r
- */\r
- public void openCalendarPanel() {\r
- \r
- if (!open && !readonly) {\r
- open = true;\r
- \r
- if (getCurrentDate() != null) {\r
- calendar.setDate((Date) getCurrentDate().clone());\r
- } else {\r
- calendar.setDate(new Date());\r
- }\r
- \r
- // clear previous values\r
- popup.setWidth("");\r
- popup.setHeight("");\r
- popup.setPopupPositionAndShow(new PositionCallback() {\r
- public void setPosition(int offsetWidth, int offsetHeight) {\r
- final int w = offsetWidth;\r
- final int h = offsetHeight;\r
- final int browserWindowWidth = Window.getClientWidth()\r
- + Window.getScrollLeft();\r
- final int browserWindowHeight = Window.getClientHeight()\r
- + Window.getScrollTop();\r
- int t = calendarToggle.getAbsoluteTop();\r
- int l = calendarToggle.getAbsoluteLeft();\r
- \r
- // Add a little extra space to the right to avoid\r
- // problems with IE7 scrollbars and to make it look\r
- // nicer.\r
- int extraSpace = 30;\r
- \r
- boolean overflowRight = false;\r
- if (l + +w + extraSpace > browserWindowWidth) {\r
- overflowRight = true;\r
- // Part of the popup is outside the browser window\r
- // (to the right)\r
- l = browserWindowWidth - w - extraSpace;\r
- }\r
- \r
- if (t + h + calendarToggle.getOffsetHeight() + 30 > browserWindowHeight) {\r
- // Part of the popup is outside the browser window\r
- // (below)\r
- t = browserWindowHeight - h\r
- - calendarToggle.getOffsetHeight() - 30;\r
- if (!overflowRight) {\r
- // Show to the right of the popup button unless we\r
- // are in the lower right corner of the screen\r
- l += calendarToggle.getOffsetWidth();\r
- }\r
- }\r
- \r
- // fix size\r
- popup.setWidth(w + "px");\r
- popup.setHeight(h + "px");\r
- \r
- popup.setPopupPosition(l,\r
- t + calendarToggle.getOffsetHeight() + 2);\r
- \r
- /*\r
- * We have to wait a while before focusing since the popup\r
- * needs to be opened before we can focus\r
- */\r
- Timer focusTimer = new Timer() {\r
- @Override\r
- public void run() {\r
- setFocus(true);\r
- }\r
- };\r
- \r
- focusTimer.schedule(100);\r
- }\r
- });\r
- } else {\r
- VConsole.error("Cannot reopen popup, it is already open!");\r
- }\r
- }\r
- \r
- /*\r
- * (non-Javadoc)\r
- * \r
- * @see\r
- * com.google.gwt.event.dom.client.ClickHandler#onClick(com.google.gwt.event\r
- * .dom.client.ClickEvent)\r
- */\r
- public void onClick(ClickEvent event) {\r
- if (event.getSource() == calendarToggle && isEnabled()) {\r
- openCalendarPanel();\r
- }\r
- }\r
- \r
- /*\r
- * (non-Javadoc)\r
- * \r
- * @see\r
- * com.google.gwt.event.logical.shared.CloseHandler#onClose(com.google.gwt\r
- * .event.logical.shared.CloseEvent)\r
- */\r
- public void onClose(CloseEvent<PopupPanel> event) {\r
- if (event.getSource() == popup) {\r
- buildDate();\r
- if (!BrowserInfo.get().isTouchDevice()) {\r
- /*\r
- * Move focus to textbox, unless on touch device (avoids opening\r
- * virtual keyboard).\r
- */\r
- focus();\r
- }\r
- \r
- // TODO resolve what the "Sigh." is all about and document it here\r
- // Sigh.\r
- Timer t = new Timer() {\r
- @Override\r
- public void run() {\r
- open = false;\r
- }\r
- };\r
- t.schedule(100);\r
- }\r
- }\r
- \r
- /**\r
- * Sets focus to Calendar panel.\r
- * \r
- * @param focus\r
- */\r
- public void setFocus(boolean focus) {\r
- calendar.setFocus(focus);\r
- }\r
- \r
- /*\r
- * (non-Javadoc)\r
- * \r
- * @see com.vaadin.terminal.gwt.client.ui.VTextualDate#getFieldExtraWidth()\r
- */\r
- @Override\r
- protected int getFieldExtraWidth() {\r
- if (fieldExtraWidth < 0) {\r
- fieldExtraWidth = super.getFieldExtraWidth();\r
- fieldExtraWidth += calendarToggle.getOffsetWidth();\r
- }\r
- return fieldExtraWidth;\r
- }\r
- \r
- /*\r
- * (non-Javadoc)\r
- * \r
- * @see com.vaadin.terminal.gwt.client.ui.VTextualDate#buildDate()\r
- */\r
- @Override\r
- protected void buildDate() {\r
- // Save previous value\r
- String previousValue = getText();\r
- super.buildDate();\r
- \r
- // Restore previous value if the input could not be parsed\r
- if (!parsable) {\r
- setText(previousValue);\r
- }\r
- }\r
- \r
- /**\r
- * Update the text field contents from the date. See {@link #buildDate()}.\r
- * \r
- * @param forceValid\r
- * true to force the text field to be updated, false to only\r
- * update if the parsable flag is true.\r
- */\r
- protected void buildDate(boolean forceValid) {\r
- if (forceValid) {\r
- parsable = true;\r
- }\r
- buildDate();\r
- }\r
- \r
- /*\r
- * (non-Javadoc)\r
- * \r
- * @see\r
- * com.vaadin.terminal.gwt.client.ui.VDateField#onBrowserEvent(com.google\r
- * .gwt.user.client.Event)\r
- */\r
- @Override\r
- public void onBrowserEvent(com.google.gwt.user.client.Event event) {\r
- super.onBrowserEvent(event);\r
- if (DOM.eventGetType(event) == Event.ONKEYDOWN\r
- && event.getKeyCode() == getOpenCalenderPanelKey()) {\r
- openCalendarPanel();\r
- event.preventDefault();\r
- }\r
- }\r
- \r
- /**\r
- * Get the key code that opens the calendar panel. By default it is the down\r
- * key but you can override this to be whatever you like\r
- * \r
- * @return\r
- */\r
- protected int getOpenCalenderPanelKey() {\r
- return KeyCodes.KEY_DOWN;\r
- }\r
- \r
- /**\r
- * Closes the open popup panel\r
- */\r
- public void closeCalendarPanel() {\r
- if (open) {\r
- popup.hide(true);\r
- }\r
- }\r
- \r
- private final String CALENDAR_TOGGLE_ID = "popupButton";\r
- \r
- @Override\r
- public Element getSubPartElement(String subPart) {\r
- if (subPart.equals(CALENDAR_TOGGLE_ID)) {\r
- return calendarToggle.getElement();\r
- }\r
- \r
- return super.getSubPartElement(subPart);\r
- }\r
- \r
- @Override\r
- public String getSubPartName(Element subElement) {\r
- if (calendarToggle.getElement().isOrHasChild(subElement)) {\r
- return CALENDAR_TOGGLE_ID;\r
- }\r
- \r
- return super.getSubPartName(subElement);\r
- }\r
- \r
- }\r
+ /*
+ @VaadinApache2LicenseForJavaFiles@
+ */
+
+ package com.vaadin.terminal.gwt.client.ui;
+
+ import java.util.Date;
+
+ import com.google.gwt.core.client.GWT;
+ import com.google.gwt.event.dom.client.ClickEvent;
+ import com.google.gwt.event.dom.client.ClickHandler;
+ import com.google.gwt.event.dom.client.DomEvent;
+ import com.google.gwt.event.dom.client.KeyCodes;
+ import com.google.gwt.event.logical.shared.CloseEvent;
+ import com.google.gwt.event.logical.shared.CloseHandler;
+ import com.google.gwt.user.client.DOM;
+ import com.google.gwt.user.client.Element;
+ import com.google.gwt.user.client.Event;
+ import com.google.gwt.user.client.Timer;
+ import com.google.gwt.user.client.Window;
+ import com.google.gwt.user.client.ui.Button;
+ import com.google.gwt.user.client.ui.PopupPanel;
+ import com.google.gwt.user.client.ui.PopupPanel.PositionCallback;
-import com.vaadin.terminal.gwt.client.ApplicationConnection;
+ import com.vaadin.terminal.gwt.client.BrowserInfo;
-import com.vaadin.terminal.gwt.client.DateTimeService;
-import com.vaadin.terminal.gwt.client.Paintable;
-import com.vaadin.terminal.gwt.client.UIDL;
+ import com.vaadin.terminal.gwt.client.VConsole;
-import com.vaadin.terminal.gwt.client.ui.VCalendarPanel.FocusChangeListener;
+ import com.vaadin.terminal.gwt.client.ui.VCalendarPanel.FocusOutListener;
+ import com.vaadin.terminal.gwt.client.ui.VCalendarPanel.SubmitListener;
-import com.vaadin.terminal.gwt.client.ui.VCalendarPanel.TimeChangeListener;
+
+ /**
+ * Represents a date selection component with a text field and a popup date
+ * selector.
+ *
+ * <b>Note:</b> To change the keyboard assignments used in the popup dialog you
+ * should extend <code>com.vaadin.terminal.gwt.client.ui.VCalendarPanel</code>
+ * and then pass set it by calling the
+ * <code>setCalendarPanel(VCalendarPanel panel)</code> method.
+ *
+ */
-public class VPopupCalendar extends VTextualDate implements Paintable, Field,
++public class VPopupCalendar extends VTextualDate implements Field,
+ ClickHandler, CloseHandler<PopupPanel>, SubPartAware {
+
- private static final String POPUP_PRIMARY_STYLE_NAME = VDateField.CLASSNAME
++ protected static final String POPUP_PRIMARY_STYLE_NAME = VDateField.CLASSNAME
+ + "-popup";
+
- private final Button calendarToggle;
++ protected final Button calendarToggle;
+
- private VCalendarPanel calendar;
++ protected VCalendarPanel calendar;
+
- private final VOverlay popup;
++ protected final VOverlay popup;
+ private boolean open = false;
- private boolean parsable = true;
++ protected boolean parsable = true;
+
+ public VPopupCalendar() {
+ super();
+
+ calendarToggle = new Button();
+ calendarToggle.setStyleName(CLASSNAME + "-button");
+ calendarToggle.setText("");
+ calendarToggle.addClickHandler(this);
+ // -2 instead of -1 to avoid FocusWidget.onAttach to reset it
+ calendarToggle.getElement().setTabIndex(-2);
+ add(calendarToggle);
+
+ calendar = GWT.create(VCalendarPanel.class);
+ calendar.setFocusOutListener(new FocusOutListener() {
+ public boolean onFocusOut(DomEvent<?> event) {
+ event.preventDefault();
+ closeCalendarPanel();
+ return true;
+ }
+ });
+
+ calendar.setSubmitListener(new SubmitListener() {
+ public void onSubmit() {
+ // Update internal value and send valuechange event if immediate
+ updateValue(calendar.getDate());
+
+ // Update text field (a must when not immediate).
+ buildDate(true);
+
+ closeCalendarPanel();
+ }
+
+ public void onCancel() {
+ closeCalendarPanel();
+ }
+ });
+
+ popup = new VOverlay(true, true, true);
+ popup.setStyleName(POPUP_PRIMARY_STYLE_NAME);
+ popup.setWidget(calendar);
+ popup.addCloseHandler(this);
+
+ DOM.setElementProperty(calendar.getElement(), "id",
+ "PID_VAADIN_POPUPCAL");
+
+ sinkEvents(Event.ONKEYDOWN);
+
+ }
+
+ @SuppressWarnings("deprecation")
- private void updateValue(Date newDate) {
++ protected void updateValue(Date newDate) {
+ Date currentDate = getCurrentDate();
+ if (currentDate == null || newDate.getTime() != currentDate.getTime()) {
+ setCurrentDate((Date) newDate.clone());
+ getClient().updateVariable(getId(), "year",
+ newDate.getYear() + 1900, false);
+ if (getCurrentResolution() > VDateField.RESOLUTION_YEAR) {
+ getClient().updateVariable(getId(), "month",
+ newDate.getMonth() + 1, false);
+ if (getCurrentResolution() > RESOLUTION_MONTH) {
+ getClient().updateVariable(getId(), "day",
+ newDate.getDate(), false);
+ if (getCurrentResolution() > RESOLUTION_DAY) {
+ getClient().updateVariable(getId(), "hour",
+ newDate.getHours(), false);
+ if (getCurrentResolution() > RESOLUTION_HOUR) {
+ getClient().updateVariable(getId(), "min",
+ newDate.getMinutes(), false);
+ if (getCurrentResolution() > RESOLUTION_MIN) {
+ getClient().updateVariable(getId(), "sec",
+ newDate.getSeconds(), false);
- if (getCurrentResolution() == RESOLUTION_MSEC) {
- getClient().updateVariable(
- getId(),
- "msec",
- DateTimeService
- .getMilliseconds(newDate),
- false);
- }
+ }
+ }
+ }
+ }
+ }
+ if (isImmediate()) {
+ getClient().sendPendingVariableChanges();
+ }
+ }
+ }
+
- /*
- * (non-Javadoc)
- *
- * @see
- * com.vaadin.terminal.gwt.client.ui.VTextualDate#updateFromUIDL(com.vaadin
- * .terminal.gwt.client.UIDL,
- * com.vaadin.terminal.gwt.client.ApplicationConnection)
- */
- @Override
- @SuppressWarnings("deprecation")
- public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {
- boolean lastReadOnlyState = readonly;
- boolean lastEnabledState = isEnabled();
-
- parsable = uidl.getBooleanAttribute("parsable");
-
- super.updateFromUIDL(uidl, client);
-
- String popupStyleNames = ApplicationConnection.getStyleName(
- POPUP_PRIMARY_STYLE_NAME, uidl, false);
- popupStyleNames += " " + VDateField.CLASSNAME + "-"
- + resolutionToString(currentResolution);
- popup.setStyleName(popupStyleNames);
-
- calendar.setDateTimeService(getDateTimeService());
- calendar.setShowISOWeekNumbers(isShowISOWeekNumbers());
- if (calendar.getResolution() != currentResolution) {
- calendar.setResolution(currentResolution);
- if (calendar.getDate() != null) {
- calendar.setDate((Date) getCurrentDate().clone());
- // force re-render when changing resolution only
- calendar.renderCalendar();
- }
- }
- calendarToggle.setEnabled(enabled);
-
- if (currentResolution <= RESOLUTION_MONTH) {
- calendar.setFocusChangeListener(new FocusChangeListener() {
- public void focusChanged(Date date) {
- updateValue(date);
- buildDate();
- Date date2 = calendar.getDate();
- date2.setYear(date.getYear());
- date2.setMonth(date.getMonth());
- }
- });
- } else {
- calendar.setFocusChangeListener(null);
- }
-
- if (currentResolution > RESOLUTION_DAY) {
- calendar.setTimeChangeListener(new TimeChangeListener() {
- public void changed(int hour, int min, int sec, int msec) {
- Date d = getDate();
- if (d == null) {
- // date currently null, use the value from calendarPanel
- // (~ client time at the init of the widget)
- d = (Date) calendar.getDate().clone();
- }
- d.setHours(hour);
- d.setMinutes(min);
- d.setSeconds(sec);
- DateTimeService.setMilliseconds(d, msec);
-
- // Always update time changes to the server
- updateValue(d);
-
- // Update text field
- buildDate();
- }
- });
- }
-
- if (readonly) {
- calendarToggle.addStyleName(CLASSNAME + "-button-readonly");
- } else {
- calendarToggle.removeStyleName(CLASSNAME + "-button-readonly");
- }
-
- if (lastReadOnlyState != readonly || lastEnabledState != isEnabled()) {
- // Enabled or readonly state changed. Differences in theming might
- // affect the width (for instance if the popup button is hidden) so
- // we have to recalculate the width (IF the width of the field is
- // fixed)
- updateWidth();
- }
-
- calendarToggle.setEnabled(true);
- }
-
+ /*
+ * (non-Javadoc)
+ *
+ * @see
+ * com.google.gwt.user.client.ui.UIObject#setStyleName(java.lang.String)
+ */
+ @Override
+ public void setStyleName(String style) {
+ // make sure the style is there before size calculation
+ super.setStyleName(style + " " + CLASSNAME + "-popupcalendar");
+ }
+
+ /**
+ * Opens the calendar panel popup
+ */
+ public void openCalendarPanel() {
+
+ if (!open && !readonly) {
+ open = true;
+
+ if (getCurrentDate() != null) {
+ calendar.setDate((Date) getCurrentDate().clone());
+ } else {
+ calendar.setDate(new Date());
+ }
+
+ // clear previous values
+ popup.setWidth("");
+ popup.setHeight("");
+ popup.setPopupPositionAndShow(new PositionCallback() {
+ public void setPosition(int offsetWidth, int offsetHeight) {
+ final int w = offsetWidth;
+ final int h = offsetHeight;
+ final int browserWindowWidth = Window.getClientWidth()
+ + Window.getScrollLeft();
+ final int browserWindowHeight = Window.getClientHeight()
+ + Window.getScrollTop();
+ int t = calendarToggle.getAbsoluteTop();
+ int l = calendarToggle.getAbsoluteLeft();
+
+ // Add a little extra space to the right to avoid
- // problems with IE6/IE7 scrollbars and to make it look
++ // problems with IE7 scrollbars and to make it look
+ // nicer.
+ int extraSpace = 30;
+
+ boolean overflowRight = false;
+ if (l + +w + extraSpace > browserWindowWidth) {
+ overflowRight = true;
+ // Part of the popup is outside the browser window
+ // (to the right)
+ l = browserWindowWidth - w - extraSpace;
+ }
+
+ if (t + h + calendarToggle.getOffsetHeight() + 30 > browserWindowHeight) {
+ // Part of the popup is outside the browser window
+ // (below)
+ t = browserWindowHeight - h
+ - calendarToggle.getOffsetHeight() - 30;
+ if (!overflowRight) {
+ // Show to the right of the popup button unless we
+ // are in the lower right corner of the screen
+ l += calendarToggle.getOffsetWidth();
+ }
+ }
+
+ // fix size
+ popup.setWidth(w + "px");
+ popup.setHeight(h + "px");
+
+ popup.setPopupPosition(l,
+ t + calendarToggle.getOffsetHeight() + 2);
+
+ /*
+ * We have to wait a while before focusing since the popup
+ * needs to be opened before we can focus
+ */
+ Timer focusTimer = new Timer() {
+ @Override
+ public void run() {
+ setFocus(true);
+ }
+ };
+
+ focusTimer.schedule(100);
+ }
+ });
+ } else {
+ VConsole.error("Cannot reopen popup, it is already open!");
+ }
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see
+ * com.google.gwt.event.dom.client.ClickHandler#onClick(com.google.gwt.event
+ * .dom.client.ClickEvent)
+ */
+ public void onClick(ClickEvent event) {
+ if (event.getSource() == calendarToggle && isEnabled()) {
+ openCalendarPanel();
+ }
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see
+ * com.google.gwt.event.logical.shared.CloseHandler#onClose(com.google.gwt
+ * .event.logical.shared.CloseEvent)
+ */
+ public void onClose(CloseEvent<PopupPanel> event) {
+ if (event.getSource() == popup) {
+ buildDate();
+ if (!BrowserInfo.get().isTouchDevice()) {
+ /*
+ * Move focus to textbox, unless on touch device (avoids opening
+ * virtual keyboard).
+ */
+ focus();
+ }
+
+ // TODO resolve what the "Sigh." is all about and document it here
+ // Sigh.
+ Timer t = new Timer() {
+ @Override
+ public void run() {
+ open = false;
+ }
+ };
+ t.schedule(100);
+ }
+ }
+
+ /**
+ * Sets focus to Calendar panel.
+ *
+ * @param focus
+ */
+ public void setFocus(boolean focus) {
+ calendar.setFocus(focus);
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see com.vaadin.terminal.gwt.client.ui.VTextualDate#getFieldExtraWidth()
+ */
+ @Override
+ protected int getFieldExtraWidth() {
+ if (fieldExtraWidth < 0) {
+ fieldExtraWidth = super.getFieldExtraWidth();
+ fieldExtraWidth += calendarToggle.getOffsetWidth();
+ }
+ return fieldExtraWidth;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see com.vaadin.terminal.gwt.client.ui.VTextualDate#buildDate()
+ */
+ @Override
+ protected void buildDate() {
+ // Save previous value
+ String previousValue = getText();
+ super.buildDate();
+
+ // Restore previous value if the input could not be parsed
+ if (!parsable) {
+ setText(previousValue);
+ }
+ }
+
+ /**
+ * Update the text field contents from the date. See {@link #buildDate()}.
+ *
+ * @param forceValid
+ * true to force the text field to be updated, false to only
+ * update if the parsable flag is true.
+ */
+ protected void buildDate(boolean forceValid) {
+ if (forceValid) {
+ parsable = true;
+ }
+ buildDate();
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see
+ * com.vaadin.terminal.gwt.client.ui.VDateField#onBrowserEvent(com.google
+ * .gwt.user.client.Event)
+ */
+ @Override
+ public void onBrowserEvent(com.google.gwt.user.client.Event event) {
+ super.onBrowserEvent(event);
+ if (DOM.eventGetType(event) == Event.ONKEYDOWN
+ && event.getKeyCode() == getOpenCalenderPanelKey()) {
+ openCalendarPanel();
+ event.preventDefault();
+ }
+ }
+
+ /**
+ * Get the key code that opens the calendar panel. By default it is the down
+ * key but you can override this to be whatever you like
+ *
+ * @return
+ */
+ protected int getOpenCalenderPanelKey() {
+ return KeyCodes.KEY_DOWN;
+ }
+
+ /**
+ * Closes the open popup panel
+ */
+ public void closeCalendarPanel() {
+ if (open) {
+ popup.hide(true);
+ }
+ }
+
+ private final String CALENDAR_TOGGLE_ID = "popupButton";
+
+ @Override
+ public Element getSubPartElement(String subPart) {
+ if (subPart.equals(CALENDAR_TOGGLE_ID)) {
+ return calendarToggle.getElement();
+ }
+
+ return super.getSubPartElement(subPart);
+ }
+
+ @Override
+ public String getSubPartName(Element subElement) {
+ if (calendarToggle.getElement().isOrHasChild(subElement)) {
+ return CALENDAR_TOGGLE_ID;
+ }
+
+ return super.getSubPartName(subElement);
+ }
+
+ }
--- /dev/null
- package com.vaadin.terminal.gwt.client.ui;\r
- \r
- import com.google.gwt.core.client.GWT;\r
- import com.google.gwt.user.client.ui.Widget;\r
- import com.vaadin.terminal.gwt.client.ApplicationConnection;\r
- import com.vaadin.terminal.gwt.client.UIDL;\r
- import com.vaadin.terminal.gwt.client.VCaption;\r
- import com.vaadin.terminal.gwt.client.VCaptionWrapper;\r
- import com.vaadin.terminal.gwt.client.VPaintableWidget;\r
- \r
- public class VPopupViewPaintable extends VAbstractPaintableWidgetContainer {\r
- \r
- /**\r
- * \r
- * \r
- * @see com.vaadin.terminal.gwt.client.VPaintableWidget#updateFromUIDL(com.vaadin.terminal.gwt.client.UIDL,\r
- * com.vaadin.terminal.gwt.client.ApplicationConnection)\r
- */\r
- public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {\r
- // This call should be made first. Ensure correct implementation,\r
- // and don't let the containing layout manage caption.\r
- if (client.updateComponent(this, uidl, false)) {\r
- return;\r
- }\r
- // These are for future server connections\r
- getWidgetForPaintable().client = client;\r
- getWidgetForPaintable().uidlId = uidl.getId();\r
- \r
- getWidgetForPaintable().hostPopupVisible = uidl\r
- .getBooleanVariable("popupVisibility");\r
- \r
- getWidgetForPaintable().setHTML(uidl.getStringAttribute("html"));\r
- \r
- if (uidl.hasAttribute("hideOnMouseOut")) {\r
- getWidgetForPaintable().popup.setHideOnMouseOut(uidl\r
- .getBooleanAttribute("hideOnMouseOut"));\r
- }\r
- \r
- // Render the popup if visible and show it.\r
- if (getWidgetForPaintable().hostPopupVisible) {\r
- UIDL popupUIDL = uidl.getChildUIDL(0);\r
- \r
- // showPopupOnTop(popup, hostReference);\r
- getWidgetForPaintable().preparePopup(getWidgetForPaintable().popup);\r
- getWidgetForPaintable().popup.updateFromUIDL(popupUIDL, client);\r
- if (uidl.hasAttribute("style")) {\r
- final String[] styles = uidl.getStringAttribute("style").split(\r
- " ");\r
- final StringBuffer styleBuf = new StringBuffer();\r
- final String primaryName = getWidgetForPaintable().popup\r
- .getStylePrimaryName();\r
- styleBuf.append(primaryName);\r
- for (int i = 0; i < styles.length; i++) {\r
- styleBuf.append(" ");\r
- styleBuf.append(primaryName);\r
- styleBuf.append("-");\r
- styleBuf.append(styles[i]);\r
- }\r
- getWidgetForPaintable().popup.setStyleName(styleBuf.toString());\r
- } else {\r
- getWidgetForPaintable().popup\r
- .setStyleName(getWidgetForPaintable().popup\r
- .getStylePrimaryName());\r
- }\r
- getWidgetForPaintable().showPopup(getWidgetForPaintable().popup);\r
- \r
- // The popup shouldn't be visible, try to hide it.\r
- } else {\r
- getWidgetForPaintable().popup.hide();\r
- }\r
- }// updateFromUIDL\r
- \r
- public void updateCaption(VPaintableWidget component, UIDL uidl) {\r
- if (VCaption.isNeeded(uidl)) {\r
- if (getWidgetForPaintable().popup.captionWrapper != null) {\r
- getWidgetForPaintable().popup.captionWrapper\r
- .updateCaption(uidl);\r
- } else {\r
- getWidgetForPaintable().popup.captionWrapper = new VCaptionWrapper(\r
- component, getConnection());\r
- getWidgetForPaintable().popup\r
- .setWidget(getWidgetForPaintable().popup.captionWrapper);\r
- getWidgetForPaintable().popup.captionWrapper\r
- .updateCaption(uidl);\r
- }\r
- } else {\r
- if (getWidgetForPaintable().popup.captionWrapper != null) {\r
- getWidgetForPaintable().popup\r
- .setWidget(getWidgetForPaintable().popup.popupComponentWidget);\r
- }\r
- }\r
- }\r
- \r
- @Override\r
- public VPopupView getWidgetForPaintable() {\r
- return (VPopupView) super.getWidgetForPaintable();\r
- }\r
- \r
- @Override\r
- protected Widget createWidget() {\r
- return GWT.create(VPopupView.class);\r
- }\r
- \r
- }\r
++package com.vaadin.terminal.gwt.client.ui;
++
++import com.google.gwt.core.client.GWT;
++import com.google.gwt.user.client.ui.Widget;
++import com.vaadin.terminal.gwt.client.ApplicationConnection;
++import com.vaadin.terminal.gwt.client.UIDL;
++import com.vaadin.terminal.gwt.client.VCaption;
++import com.vaadin.terminal.gwt.client.VCaptionWrapper;
++import com.vaadin.terminal.gwt.client.VPaintableWidget;
++
++public class VPopupViewPaintable extends VAbstractPaintableWidgetContainer {
++
++ /**
++ *
++ *
++ * @see com.vaadin.terminal.gwt.client.VPaintableWidget#updateFromUIDL(com.vaadin.terminal.gwt.client.UIDL,
++ * com.vaadin.terminal.gwt.client.ApplicationConnection)
++ */
++ public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {
++ // This call should be made first. Ensure correct implementation,
++ // and don't let the containing layout manage caption.
++ if (client.updateComponent(this, uidl, false)) {
++ return;
++ }
++ // These are for future server connections
++ getWidgetForPaintable().client = client;
++ getWidgetForPaintable().uidlId = uidl.getId();
++
++ getWidgetForPaintable().hostPopupVisible = uidl
++ .getBooleanVariable("popupVisibility");
++
++ getWidgetForPaintable().setHTML(uidl.getStringAttribute("html"));
++
++ if (uidl.hasAttribute("hideOnMouseOut")) {
++ getWidgetForPaintable().popup.setHideOnMouseOut(uidl
++ .getBooleanAttribute("hideOnMouseOut"));
++ }
++
++ // Render the popup if visible and show it.
++ if (getWidgetForPaintable().hostPopupVisible) {
++ UIDL popupUIDL = uidl.getChildUIDL(0);
++
++ // showPopupOnTop(popup, hostReference);
++ getWidgetForPaintable().preparePopup(getWidgetForPaintable().popup);
++ getWidgetForPaintable().popup.updateFromUIDL(popupUIDL, client);
++ if (uidl.hasAttribute("style")) {
++ final String[] styles = uidl.getStringAttribute("style").split(
++ " ");
++ final StringBuffer styleBuf = new StringBuffer();
++ final String primaryName = getWidgetForPaintable().popup
++ .getStylePrimaryName();
++ styleBuf.append(primaryName);
++ for (int i = 0; i < styles.length; i++) {
++ styleBuf.append(" ");
++ styleBuf.append(primaryName);
++ styleBuf.append("-");
++ styleBuf.append(styles[i]);
++ }
++ getWidgetForPaintable().popup.setStyleName(styleBuf.toString());
++ } else {
++ getWidgetForPaintable().popup
++ .setStyleName(getWidgetForPaintable().popup
++ .getStylePrimaryName());
++ }
++ getWidgetForPaintable().showPopup(getWidgetForPaintable().popup);
++
++ // The popup shouldn't be visible, try to hide it.
++ } else {
++ getWidgetForPaintable().popup.hide();
++ }
++ }// updateFromUIDL
++
++ public void updateCaption(VPaintableWidget component, UIDL uidl) {
++ if (VCaption.isNeeded(uidl)) {
++ if (getWidgetForPaintable().popup.captionWrapper != null) {
++ getWidgetForPaintable().popup.captionWrapper
++ .updateCaption(uidl);
++ } else {
++ getWidgetForPaintable().popup.captionWrapper = new VCaptionWrapper(
++ component, getConnection());
++ getWidgetForPaintable().popup
++ .setWidget(getWidgetForPaintable().popup.captionWrapper);
++ getWidgetForPaintable().popup.captionWrapper
++ .updateCaption(uidl);
++ }
++ } else {
++ if (getWidgetForPaintable().popup.captionWrapper != null) {
++ getWidgetForPaintable().popup
++ .setWidget(getWidgetForPaintable().popup.popupComponentWidget);
++ }
++ }
++ }
++
++ @Override
++ public VPopupView getWidgetForPaintable() {
++ return (VPopupView) super.getWidgetForPaintable();
++ }
++
++ @Override
++ protected Widget createWidget() {
++ return GWT.create(VPopupView.class);
++ }
++
++}
--- /dev/null
- /*\r
- @VaadinApache2LicenseForJavaFiles@\r
- */\r
- package com.vaadin.terminal.gwt.client.ui;\r
- \r
- import com.google.gwt.core.client.GWT;\r
- import com.google.gwt.core.client.Scheduler;\r
- import com.google.gwt.dom.client.Style.Position;\r
- import com.google.gwt.user.client.Command;\r
- import com.google.gwt.user.client.ui.Widget;\r
- import com.vaadin.terminal.gwt.client.ApplicationConnection;\r
- import com.vaadin.terminal.gwt.client.BrowserInfo;\r
- import com.vaadin.terminal.gwt.client.UIDL;\r
- import com.vaadin.terminal.gwt.client.Util;\r
- \r
- public class VScrollTablePaintable extends VAbstractPaintableWidget {\r
- \r
- /*\r
- * (non-Javadoc)\r
- * \r
- * @see\r
- * com.vaadin.terminal.gwt.client.Paintable#updateFromUIDL(com.vaadin.terminal\r
- * .gwt.client.UIDL, com.vaadin.terminal.gwt.client.ApplicationConnection)\r
- */\r
- public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {\r
- getWidgetForPaintable().rendering = true;\r
- \r
- if (uidl.hasAttribute(VScrollTable.ATTRIBUTE_PAGEBUFFER_FIRST)) {\r
- getWidgetForPaintable().serverCacheFirst = uidl\r
- .getIntAttribute(VScrollTable.ATTRIBUTE_PAGEBUFFER_FIRST);\r
- getWidgetForPaintable().serverCacheLast = uidl\r
- .getIntAttribute(VScrollTable.ATTRIBUTE_PAGEBUFFER_LAST);\r
- } else {\r
- getWidgetForPaintable().serverCacheFirst = -1;\r
- getWidgetForPaintable().serverCacheLast = -1;\r
- }\r
- /*\r
- * We need to do this before updateComponent since updateComponent calls\r
- * this.setHeight() which will calculate a new body height depending on\r
- * the space available.\r
- */\r
- if (uidl.hasAttribute("colfooters")) {\r
- getWidgetForPaintable().showColFooters = uidl\r
- .getBooleanAttribute("colfooters");\r
- }\r
- \r
- getWidgetForPaintable().tFoot\r
- .setVisible(getWidgetForPaintable().showColFooters);\r
- \r
- if (client.updateComponent(this, uidl, true)) {\r
- getWidgetForPaintable().rendering = false;\r
- return;\r
- }\r
- \r
- getWidgetForPaintable().enabled = !uidl.hasAttribute("disabled");\r
- \r
- if (BrowserInfo.get().isIE8() && !getWidgetForPaintable().enabled) {\r
- /*\r
- * The disabled shim will not cover the table body if it is relative\r
- * in IE8. See #7324\r
- */\r
- getWidgetForPaintable().scrollBodyPanel.getElement().getStyle()\r
- .setPosition(Position.STATIC);\r
- } else if (BrowserInfo.get().isIE8()) {\r
- getWidgetForPaintable().scrollBodyPanel.getElement().getStyle()\r
- .setPosition(Position.RELATIVE);\r
- }\r
- \r
- getWidgetForPaintable().client = client;\r
- getWidgetForPaintable().paintableId = uidl.getStringAttribute("id");\r
- getWidgetForPaintable().immediate = uidl\r
- .getBooleanAttribute("immediate");\r
- \r
- int previousTotalRows = getWidgetForPaintable().totalRows;\r
- getWidgetForPaintable().updateTotalRows(uidl);\r
- boolean totalRowsChanged = (getWidgetForPaintable().totalRows != previousTotalRows);\r
- \r
- getWidgetForPaintable().updateDragMode(uidl);\r
- \r
- getWidgetForPaintable().updateSelectionProperties(uidl);\r
- \r
- if (uidl.hasAttribute("alb")) {\r
- getWidgetForPaintable().bodyActionKeys = uidl\r
- .getStringArrayAttribute("alb");\r
- } else {\r
- // Need to clear the actions if the action handlers have been\r
- // removed\r
- getWidgetForPaintable().bodyActionKeys = null;\r
- }\r
- \r
- getWidgetForPaintable().setCacheRateFromUIDL(uidl);\r
- \r
- getWidgetForPaintable().recalcWidths = uidl\r
- .hasAttribute("recalcWidths");\r
- if (getWidgetForPaintable().recalcWidths) {\r
- getWidgetForPaintable().tHead.clear();\r
- getWidgetForPaintable().tFoot.clear();\r
- }\r
- \r
- getWidgetForPaintable().updatePageLength(uidl);\r
- \r
- getWidgetForPaintable().updateFirstVisibleAndScrollIfNeeded(uidl);\r
- \r
- getWidgetForPaintable().showRowHeaders = uidl\r
- .getBooleanAttribute("rowheaders");\r
- getWidgetForPaintable().showColHeaders = uidl\r
- .getBooleanAttribute("colheaders");\r
- \r
- getWidgetForPaintable().updateSortingProperties(uidl);\r
- \r
- boolean keyboardSelectionOverRowFetchInProgress = getWidgetForPaintable()\r
- .selectSelectedRows(uidl);\r
- \r
- getWidgetForPaintable().updateActionMap(uidl);\r
- \r
- getWidgetForPaintable().updateColumnProperties(uidl);\r
- \r
- UIDL ac = uidl.getChildByTagName("-ac");\r
- if (ac == null) {\r
- if (getWidgetForPaintable().dropHandler != null) {\r
- // remove dropHandler if not present anymore\r
- getWidgetForPaintable().dropHandler = null;\r
- }\r
- } else {\r
- if (getWidgetForPaintable().dropHandler == null) {\r
- getWidgetForPaintable().dropHandler = getWidgetForPaintable().new VScrollTableDropHandler();\r
- }\r
- getWidgetForPaintable().dropHandler.updateAcceptRules(ac);\r
- }\r
- \r
- UIDL partialRowAdditions = uidl.getChildByTagName("prows");\r
- UIDL partialRowUpdates = uidl.getChildByTagName("urows");\r
- if (partialRowUpdates != null || partialRowAdditions != null) {\r
- // we may have pending cache row fetch, cancel it. See #2136\r
- getWidgetForPaintable().rowRequestHandler.cancel();\r
- \r
- getWidgetForPaintable().updateRowsInBody(partialRowUpdates);\r
- getWidgetForPaintable().addAndRemoveRows(partialRowAdditions);\r
- } else {\r
- UIDL rowData = uidl.getChildByTagName("rows");\r
- if (rowData != null) {\r
- // we may have pending cache row fetch, cancel it. See #2136\r
- getWidgetForPaintable().rowRequestHandler.cancel();\r
- \r
- if (!getWidgetForPaintable().recalcWidths\r
- && getWidgetForPaintable().initializedAndAttached) {\r
- getWidgetForPaintable().updateBody(rowData,\r
- uidl.getIntAttribute("firstrow"),\r
- uidl.getIntAttribute("rows"));\r
- if (getWidgetForPaintable().headerChangedDuringUpdate) {\r
- getWidgetForPaintable().triggerLazyColumnAdjustment(\r
- true);\r
- } else if (!getWidgetForPaintable()\r
- .isScrollPositionVisible()\r
- || totalRowsChanged\r
- || getWidgetForPaintable().lastRenderedHeight != getWidgetForPaintable().scrollBody\r
- .getOffsetHeight()) {\r
- // webkits may still bug with their disturbing scrollbar\r
- // bug, see #3457\r
- // Run overflow fix for the scrollable area\r
- // #6698 - If there's a scroll going on, don't abort it\r
- // by changing overflows as the length of the contents\r
- // *shouldn't* have changed (unless the number of rows\r
- // or the height of the widget has also changed)\r
- Scheduler.get().scheduleDeferred(new Command() {\r
- public void execute() {\r
- Util.runWebkitOverflowAutoFix(getWidgetForPaintable().scrollBodyPanel\r
- .getElement());\r
- }\r
- });\r
- }\r
- } else {\r
- getWidgetForPaintable().initializeRows(uidl, rowData);\r
- }\r
- }\r
- }\r
- \r
- if (!getWidgetForPaintable().isSelectable()) {\r
- getWidgetForPaintable().scrollBody\r
- .addStyleName(VScrollTable.CLASSNAME + "-body-noselection");\r
- } else {\r
- getWidgetForPaintable().scrollBody\r
- .removeStyleName(VScrollTable.CLASSNAME\r
- + "-body-noselection");\r
- }\r
- \r
- getWidgetForPaintable().hideScrollPositionAnnotation();\r
- getWidgetForPaintable().purgeUnregistryBag();\r
- \r
- // selection is no in sync with server, avoid excessive server visits by\r
- // clearing to flag used during the normal operation\r
- if (!keyboardSelectionOverRowFetchInProgress) {\r
- getWidgetForPaintable().selectionChanged = false;\r
- }\r
- \r
- /*\r
- * This is called when the Home or page up button has been pressed in\r
- * selectable mode and the next selected row was not yet rendered in the\r
- * client\r
- */\r
- if (getWidgetForPaintable().selectFirstItemInNextRender\r
- || getWidgetForPaintable().focusFirstItemInNextRender) {\r
- getWidgetForPaintable().selectFirstRenderedRowInViewPort(\r
- getWidgetForPaintable().focusFirstItemInNextRender);\r
- getWidgetForPaintable().selectFirstItemInNextRender = getWidgetForPaintable().focusFirstItemInNextRender = false;\r
- }\r
- \r
- /*\r
- * This is called when the page down or end button has been pressed in\r
- * selectable mode and the next selected row was not yet rendered in the\r
- * client\r
- */\r
- if (getWidgetForPaintable().selectLastItemInNextRender\r
- || getWidgetForPaintable().focusLastItemInNextRender) {\r
- getWidgetForPaintable().selectLastRenderedRowInViewPort(\r
- getWidgetForPaintable().focusLastItemInNextRender);\r
- getWidgetForPaintable().selectLastItemInNextRender = getWidgetForPaintable().focusLastItemInNextRender = false;\r
- }\r
- getWidgetForPaintable().multiselectPending = false;\r
- \r
- if (getWidgetForPaintable().focusedRow != null) {\r
- if (!getWidgetForPaintable().focusedRow.isAttached()\r
- && !getWidgetForPaintable().rowRequestHandler.isRunning()) {\r
- // focused row has been orphaned, can't focus\r
- getWidgetForPaintable().focusRowFromBody();\r
- }\r
- }\r
- \r
- getWidgetForPaintable().tabIndex = uidl.hasAttribute("tabindex") ? uidl\r
- .getIntAttribute("tabindex") : 0;\r
- getWidgetForPaintable().setProperTabIndex();\r
- \r
- getWidgetForPaintable().resizeSortedColumnForSortIndicator();\r
- \r
- // Remember this to detect situations where overflow hack might be\r
- // needed during scrolling\r
- getWidgetForPaintable().lastRenderedHeight = getWidgetForPaintable().scrollBody\r
- .getOffsetHeight();\r
- \r
- getWidgetForPaintable().rendering = false;\r
- getWidgetForPaintable().headerChangedDuringUpdate = false;\r
- \r
- }\r
- \r
- @Override\r
- protected Widget createWidget() {\r
- return GWT.create(VScrollTable.class);\r
- }\r
- \r
- @Override\r
- public VScrollTable getWidgetForPaintable() {\r
- return (VScrollTable) super.getWidgetForPaintable();\r
- }\r
- }\r
++/*
++@VaadinApache2LicenseForJavaFiles@
++ */
++package com.vaadin.terminal.gwt.client.ui;
++
++import com.google.gwt.core.client.GWT;
++import com.google.gwt.core.client.Scheduler;
++import com.google.gwt.dom.client.Style.Position;
++import com.google.gwt.user.client.Command;
++import com.google.gwt.user.client.ui.Widget;
++import com.vaadin.terminal.gwt.client.ApplicationConnection;
++import com.vaadin.terminal.gwt.client.BrowserInfo;
++import com.vaadin.terminal.gwt.client.UIDL;
++import com.vaadin.terminal.gwt.client.Util;
++
++public class VScrollTablePaintable extends VAbstractPaintableWidget {
++
++ /*
++ * (non-Javadoc)
++ *
++ * @see
++ * com.vaadin.terminal.gwt.client.Paintable#updateFromUIDL(com.vaadin.terminal
++ * .gwt.client.UIDL, com.vaadin.terminal.gwt.client.ApplicationConnection)
++ */
++ public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {
++ getWidgetForPaintable().rendering = true;
++
++ if (uidl.hasAttribute(VScrollTable.ATTRIBUTE_PAGEBUFFER_FIRST)) {
++ getWidgetForPaintable().serverCacheFirst = uidl
++ .getIntAttribute(VScrollTable.ATTRIBUTE_PAGEBUFFER_FIRST);
++ getWidgetForPaintable().serverCacheLast = uidl
++ .getIntAttribute(VScrollTable.ATTRIBUTE_PAGEBUFFER_LAST);
++ } else {
++ getWidgetForPaintable().serverCacheFirst = -1;
++ getWidgetForPaintable().serverCacheLast = -1;
++ }
++ /*
++ * We need to do this before updateComponent since updateComponent calls
++ * this.setHeight() which will calculate a new body height depending on
++ * the space available.
++ */
++ if (uidl.hasAttribute("colfooters")) {
++ getWidgetForPaintable().showColFooters = uidl
++ .getBooleanAttribute("colfooters");
++ }
++
++ getWidgetForPaintable().tFoot
++ .setVisible(getWidgetForPaintable().showColFooters);
++
++ if (client.updateComponent(this, uidl, true)) {
++ getWidgetForPaintable().rendering = false;
++ return;
++ }
++
++ getWidgetForPaintable().enabled = !uidl.hasAttribute("disabled");
++
++ if (BrowserInfo.get().isIE8() && !getWidgetForPaintable().enabled) {
++ /*
++ * The disabled shim will not cover the table body if it is relative
++ * in IE8. See #7324
++ */
++ getWidgetForPaintable().scrollBodyPanel.getElement().getStyle()
++ .setPosition(Position.STATIC);
++ } else if (BrowserInfo.get().isIE8()) {
++ getWidgetForPaintable().scrollBodyPanel.getElement().getStyle()
++ .setPosition(Position.RELATIVE);
++ }
++
++ getWidgetForPaintable().client = client;
++ getWidgetForPaintable().paintableId = uidl.getStringAttribute("id");
++ getWidgetForPaintable().immediate = uidl
++ .getBooleanAttribute("immediate");
++
++ int previousTotalRows = getWidgetForPaintable().totalRows;
++ getWidgetForPaintable().updateTotalRows(uidl);
++ boolean totalRowsChanged = (getWidgetForPaintable().totalRows != previousTotalRows);
++
++ getWidgetForPaintable().updateDragMode(uidl);
++
++ getWidgetForPaintable().updateSelectionProperties(uidl);
++
++ if (uidl.hasAttribute("alb")) {
++ getWidgetForPaintable().bodyActionKeys = uidl
++ .getStringArrayAttribute("alb");
++ } else {
++ // Need to clear the actions if the action handlers have been
++ // removed
++ getWidgetForPaintable().bodyActionKeys = null;
++ }
++
++ getWidgetForPaintable().setCacheRateFromUIDL(uidl);
++
++ getWidgetForPaintable().recalcWidths = uidl
++ .hasAttribute("recalcWidths");
++ if (getWidgetForPaintable().recalcWidths) {
++ getWidgetForPaintable().tHead.clear();
++ getWidgetForPaintable().tFoot.clear();
++ }
++
++ getWidgetForPaintable().updatePageLength(uidl);
++
++ getWidgetForPaintable().updateFirstVisibleAndScrollIfNeeded(uidl);
++
++ getWidgetForPaintable().showRowHeaders = uidl
++ .getBooleanAttribute("rowheaders");
++ getWidgetForPaintable().showColHeaders = uidl
++ .getBooleanAttribute("colheaders");
++
++ getWidgetForPaintable().updateSortingProperties(uidl);
++
++ boolean keyboardSelectionOverRowFetchInProgress = getWidgetForPaintable()
++ .selectSelectedRows(uidl);
++
++ getWidgetForPaintable().updateActionMap(uidl);
++
++ getWidgetForPaintable().updateColumnProperties(uidl);
++
++ UIDL ac = uidl.getChildByTagName("-ac");
++ if (ac == null) {
++ if (getWidgetForPaintable().dropHandler != null) {
++ // remove dropHandler if not present anymore
++ getWidgetForPaintable().dropHandler = null;
++ }
++ } else {
++ if (getWidgetForPaintable().dropHandler == null) {
++ getWidgetForPaintable().dropHandler = getWidgetForPaintable().new VScrollTableDropHandler();
++ }
++ getWidgetForPaintable().dropHandler.updateAcceptRules(ac);
++ }
++
++ UIDL partialRowAdditions = uidl.getChildByTagName("prows");
++ UIDL partialRowUpdates = uidl.getChildByTagName("urows");
++ if (partialRowUpdates != null || partialRowAdditions != null) {
++ // we may have pending cache row fetch, cancel it. See #2136
++ getWidgetForPaintable().rowRequestHandler.cancel();
++
++ getWidgetForPaintable().updateRowsInBody(partialRowUpdates);
++ getWidgetForPaintable().addAndRemoveRows(partialRowAdditions);
++ } else {
++ UIDL rowData = uidl.getChildByTagName("rows");
++ if (rowData != null) {
++ // we may have pending cache row fetch, cancel it. See #2136
++ getWidgetForPaintable().rowRequestHandler.cancel();
++
++ if (!getWidgetForPaintable().recalcWidths
++ && getWidgetForPaintable().initializedAndAttached) {
++ getWidgetForPaintable().updateBody(rowData,
++ uidl.getIntAttribute("firstrow"),
++ uidl.getIntAttribute("rows"));
++ if (getWidgetForPaintable().headerChangedDuringUpdate) {
++ getWidgetForPaintable().triggerLazyColumnAdjustment(
++ true);
++ } else if (!getWidgetForPaintable()
++ .isScrollPositionVisible()
++ || totalRowsChanged
++ || getWidgetForPaintable().lastRenderedHeight != getWidgetForPaintable().scrollBody
++ .getOffsetHeight()) {
++ // webkits may still bug with their disturbing scrollbar
++ // bug, see #3457
++ // Run overflow fix for the scrollable area
++ // #6698 - If there's a scroll going on, don't abort it
++ // by changing overflows as the length of the contents
++ // *shouldn't* have changed (unless the number of rows
++ // or the height of the widget has also changed)
++ Scheduler.get().scheduleDeferred(new Command() {
++ public void execute() {
++ Util.runWebkitOverflowAutoFix(getWidgetForPaintable().scrollBodyPanel
++ .getElement());
++ }
++ });
++ }
++ } else {
++ getWidgetForPaintable().initializeRows(uidl, rowData);
++ }
++ }
++ }
++
++ if (!getWidgetForPaintable().isSelectable()) {
++ getWidgetForPaintable().scrollBody
++ .addStyleName(VScrollTable.CLASSNAME + "-body-noselection");
++ } else {
++ getWidgetForPaintable().scrollBody
++ .removeStyleName(VScrollTable.CLASSNAME
++ + "-body-noselection");
++ }
++
++ getWidgetForPaintable().hideScrollPositionAnnotation();
++ getWidgetForPaintable().purgeUnregistryBag();
++
++ // selection is no in sync with server, avoid excessive server visits by
++ // clearing to flag used during the normal operation
++ if (!keyboardSelectionOverRowFetchInProgress) {
++ getWidgetForPaintable().selectionChanged = false;
++ }
++
++ /*
++ * This is called when the Home or page up button has been pressed in
++ * selectable mode and the next selected row was not yet rendered in the
++ * client
++ */
++ if (getWidgetForPaintable().selectFirstItemInNextRender
++ || getWidgetForPaintable().focusFirstItemInNextRender) {
++ getWidgetForPaintable().selectFirstRenderedRowInViewPort(
++ getWidgetForPaintable().focusFirstItemInNextRender);
++ getWidgetForPaintable().selectFirstItemInNextRender = getWidgetForPaintable().focusFirstItemInNextRender = false;
++ }
++
++ /*
++ * This is called when the page down or end button has been pressed in
++ * selectable mode and the next selected row was not yet rendered in the
++ * client
++ */
++ if (getWidgetForPaintable().selectLastItemInNextRender
++ || getWidgetForPaintable().focusLastItemInNextRender) {
++ getWidgetForPaintable().selectLastRenderedRowInViewPort(
++ getWidgetForPaintable().focusLastItemInNextRender);
++ getWidgetForPaintable().selectLastItemInNextRender = getWidgetForPaintable().focusLastItemInNextRender = false;
++ }
++ getWidgetForPaintable().multiselectPending = false;
++
++ if (getWidgetForPaintable().focusedRow != null) {
++ if (!getWidgetForPaintable().focusedRow.isAttached()
++ && !getWidgetForPaintable().rowRequestHandler.isRunning()) {
++ // focused row has been orphaned, can't focus
++ getWidgetForPaintable().focusRowFromBody();
++ }
++ }
++
++ getWidgetForPaintable().tabIndex = uidl.hasAttribute("tabindex") ? uidl
++ .getIntAttribute("tabindex") : 0;
++ getWidgetForPaintable().setProperTabIndex();
++
++ getWidgetForPaintable().resizeSortedColumnForSortIndicator();
++
++ // Remember this to detect situations where overflow hack might be
++ // needed during scrolling
++ getWidgetForPaintable().lastRenderedHeight = getWidgetForPaintable().scrollBody
++ .getOffsetHeight();
++
++ getWidgetForPaintable().rendering = false;
++ getWidgetForPaintable().headerChangedDuringUpdate = false;
++
++ }
++
++ @Override
++ protected Widget createWidget() {
++ return GWT.create(VScrollTable.class);
++ }
++
++ @Override
++ public VScrollTable getWidgetForPaintable() {
++ return (VScrollTable) super.getWidgetForPaintable();
++ }
++}
- /* \r
- @VaadinApache2LicenseForJavaFiles@\r
- */\r
- // \r
- package com.vaadin.terminal.gwt.client.ui;\r
- \r
- import com.google.gwt.core.client.Scheduler;\r
- import com.google.gwt.core.client.Scheduler.ScheduledCommand;\r
- import com.google.gwt.event.dom.client.KeyCodes;\r
- import com.google.gwt.user.client.Command;\r
- import com.google.gwt.user.client.DOM;\r
- import com.google.gwt.user.client.Element;\r
- import com.google.gwt.user.client.Event;\r
- import com.google.gwt.user.client.Window;\r
- import com.google.gwt.user.client.ui.HTML;\r
- import com.google.gwt.user.client.ui.Widget;\r
- import com.vaadin.terminal.gwt.client.ApplicationConnection;\r
- import com.vaadin.terminal.gwt.client.BrowserInfo;\r
- import com.vaadin.terminal.gwt.client.ContainerResizedListener;\r
- import com.vaadin.terminal.gwt.client.Util;\r
- import com.vaadin.terminal.gwt.client.VConsole;\r
- \r
- public class VSlider extends SimpleFocusablePanel implements Field,\r
- ContainerResizedListener {\r
- \r
- public static final String CLASSNAME = "v-slider";\r
- \r
- /**\r
- * Minimum size (width or height, depending on orientation) of the slider\r
- * base.\r
- */\r
- private static final int MIN_SIZE = 50;\r
- \r
- ApplicationConnection client;\r
- \r
- String id;\r
- \r
- boolean immediate;\r
- boolean disabled;\r
- boolean readonly;\r
- \r
- private int acceleration = 1;\r
- double min;\r
- double max;\r
- int resolution;\r
- Double value;\r
- boolean vertical;\r
- \r
- private final HTML feedback = new HTML("", false);\r
- private final VOverlay feedbackPopup = new VOverlay(true, false, true) {\r
- @Override\r
- public void show() {\r
- super.show();\r
- updateFeedbackPosition();\r
- }\r
- };\r
- \r
- /* DOM element for slider's base */\r
- private final Element base;\r
- private final int BASE_BORDER_WIDTH = 1;\r
- \r
- /* DOM element for slider's handle */\r
- private final Element handle;\r
- \r
- /* DOM element for decrement arrow */\r
- private final Element smaller;\r
- \r
- /* DOM element for increment arrow */\r
- private final Element bigger;\r
- \r
- /* Temporary dragging/animation variables */\r
- private boolean dragging = false;\r
- \r
- private VLazyExecutor delayedValueUpdater = new VLazyExecutor(100,\r
- new ScheduledCommand() {\r
- \r
- public void execute() {\r
- updateValueToServer();\r
- acceleration = 1;\r
- }\r
- });\r
- \r
- public VSlider() {\r
- super();\r
- \r
- base = DOM.createDiv();\r
- handle = DOM.createDiv();\r
- smaller = DOM.createDiv();\r
- bigger = DOM.createDiv();\r
- \r
- setStyleName(CLASSNAME);\r
- DOM.setElementProperty(base, "className", CLASSNAME + "-base");\r
- DOM.setElementProperty(handle, "className", CLASSNAME + "-handle");\r
- DOM.setElementProperty(smaller, "className", CLASSNAME + "-smaller");\r
- DOM.setElementProperty(bigger, "className", CLASSNAME + "-bigger");\r
- \r
- DOM.appendChild(getElement(), bigger);\r
- DOM.appendChild(getElement(), smaller);\r
- DOM.appendChild(getElement(), base);\r
- DOM.appendChild(base, handle);\r
- \r
- // Hide initially\r
- DOM.setStyleAttribute(smaller, "display", "none");\r
- DOM.setStyleAttribute(bigger, "display", "none");\r
- DOM.setStyleAttribute(handle, "visibility", "hidden");\r
- \r
- sinkEvents(Event.MOUSEEVENTS | Event.ONMOUSEWHEEL | Event.KEYEVENTS\r
- | Event.FOCUSEVENTS | Event.TOUCHEVENTS);\r
- \r
- feedbackPopup.addStyleName(CLASSNAME + "-feedback");\r
- feedbackPopup.setWidget(feedback);\r
- }\r
- \r
- void setFeedbackValue(double value) {\r
- String currentValue = "" + value;\r
- if (resolution == 0) {\r
- currentValue = "" + new Double(value).intValue();\r
- }\r
- feedback.setText(currentValue);\r
- }\r
- \r
- private void updateFeedbackPosition() {\r
- if (vertical) {\r
- feedbackPopup.setPopupPosition(\r
- DOM.getAbsoluteLeft(handle) + handle.getOffsetWidth(),\r
- DOM.getAbsoluteTop(handle) + handle.getOffsetHeight() / 2\r
- - feedbackPopup.getOffsetHeight() / 2);\r
- } else {\r
- feedbackPopup.setPopupPosition(\r
- DOM.getAbsoluteLeft(handle) + handle.getOffsetWidth() / 2\r
- - feedbackPopup.getOffsetWidth() / 2,\r
- DOM.getAbsoluteTop(handle)\r
- - feedbackPopup.getOffsetHeight());\r
- }\r
- }\r
- \r
- void buildBase() {\r
- final String styleAttribute = vertical ? "height" : "width";\r
- final String domProperty = vertical ? "offsetHeight" : "offsetWidth";\r
- \r
- final Element p = DOM.getParent(getElement());\r
- if (DOM.getElementPropertyInt(p, domProperty) > 50) {\r
- if (vertical) {\r
- setHeight();\r
- } else {\r
- DOM.setStyleAttribute(base, styleAttribute, "");\r
- }\r
- } else {\r
- // Set minimum size and adjust after all components have\r
- // (supposedly) been drawn completely.\r
- DOM.setStyleAttribute(base, styleAttribute, MIN_SIZE + "px");\r
- Scheduler.get().scheduleDeferred(new Command() {\r
- public void execute() {\r
- final Element p = DOM.getParent(getElement());\r
- if (DOM.getElementPropertyInt(p, domProperty) > (MIN_SIZE + 5)) {\r
- if (vertical) {\r
- setHeight();\r
- } else {\r
- DOM.setStyleAttribute(base, styleAttribute, "");\r
- }\r
- // Ensure correct position\r
- setValue(value, false);\r
- }\r
- }\r
- });\r
- }\r
- \r
- // TODO attach listeners for focusing and arrow keys\r
- }\r
- \r
- void buildHandle() {\r
- final String handleAttribute = vertical ? "marginTop" : "marginLeft";\r
- \r
- DOM.setStyleAttribute(handle, handleAttribute, "0");\r
- \r
- // Restore visibility\r
- DOM.setStyleAttribute(handle, "visibility", "visible");\r
- \r
- }\r
- \r
- void setValue(Double value, boolean updateToServer) {\r
- if (value == null) {\r
- return;\r
- }\r
- \r
- if (value < min) {\r
- value = min;\r
- } else if (value > max) {\r
- value = max;\r
- }\r
- \r
- // Update handle position\r
- final String styleAttribute = vertical ? "marginTop" : "marginLeft";\r
- final String domProperty = vertical ? "offsetHeight" : "offsetWidth";\r
- final int handleSize = Integer.parseInt(DOM.getElementProperty(handle,\r
- domProperty));\r
- final int baseSize = Integer.parseInt(DOM.getElementProperty(base,\r
- domProperty)) - (2 * BASE_BORDER_WIDTH);\r
- \r
- final int range = baseSize - handleSize;\r
- double v = value.doubleValue();\r
- \r
- // Round value to resolution\r
- if (resolution > 0) {\r
- v = Math.round(v * Math.pow(10, resolution));\r
- v = v / Math.pow(10, resolution);\r
- } else {\r
- v = Math.round(v);\r
- }\r
- final double valueRange = max - min;\r
- double p = 0;\r
- if (valueRange > 0) {\r
- p = range * ((v - min) / valueRange);\r
- }\r
- if (p < 0) {\r
- p = 0;\r
- }\r
- if (vertical) {\r
- p = range - p;\r
- }\r
- final double pos = p;\r
- \r
- DOM.setStyleAttribute(handle, styleAttribute, (Math.round(pos)) + "px");\r
- \r
- // Update value\r
- this.value = new Double(v);\r
- setFeedbackValue(v);\r
- \r
- if (updateToServer) {\r
- updateValueToServer();\r
- }\r
- }\r
- \r
- @Override\r
- public void onBrowserEvent(Event event) {\r
- if (disabled || readonly) {\r
- return;\r
- }\r
- final Element targ = DOM.eventGetTarget(event);\r
- \r
- if (DOM.eventGetType(event) == Event.ONMOUSEWHEEL) {\r
- processMouseWheelEvent(event);\r
- } else if (dragging || targ == handle) {\r
- processHandleEvent(event);\r
- } else if (targ == smaller) {\r
- decreaseValue(true);\r
- } else if (targ == bigger) {\r
- increaseValue(true);\r
- } else if (DOM.eventGetType(event) == Event.MOUSEEVENTS) {\r
- processBaseEvent(event);\r
- } else if ((BrowserInfo.get().isGecko() && DOM.eventGetType(event) == Event.ONKEYPRESS)\r
- || (!BrowserInfo.get().isGecko() && DOM.eventGetType(event) == Event.ONKEYDOWN)) {\r
- \r
- if (handleNavigation(event.getKeyCode(), event.getCtrlKey(),\r
- event.getShiftKey())) {\r
- \r
- feedbackPopup.show();\r
- \r
- delayedValueUpdater.trigger();\r
- \r
- DOM.eventPreventDefault(event);\r
- DOM.eventCancelBubble(event, true);\r
- }\r
- } else if (targ.equals(getElement())\r
- && DOM.eventGetType(event) == Event.ONFOCUS) {\r
- feedbackPopup.show();\r
- } else if (targ.equals(getElement())\r
- && DOM.eventGetType(event) == Event.ONBLUR) {\r
- feedbackPopup.hide();\r
- } else if (DOM.eventGetType(event) == Event.ONMOUSEDOWN) {\r
- feedbackPopup.show();\r
- }\r
- if (Util.isTouchEvent(event)) {\r
- event.preventDefault(); // avoid simulated events\r
- event.stopPropagation();\r
- }\r
- }\r
- \r
- private void processMouseWheelEvent(final Event event) {\r
- final int dir = DOM.eventGetMouseWheelVelocityY(event);\r
- \r
- if (dir < 0) {\r
- increaseValue(false);\r
- } else {\r
- decreaseValue(false);\r
- }\r
- \r
- delayedValueUpdater.trigger();\r
- \r
- DOM.eventPreventDefault(event);\r
- DOM.eventCancelBubble(event, true);\r
- }\r
- \r
- private void processHandleEvent(Event event) {\r
- switch (DOM.eventGetType(event)) {\r
- case Event.ONMOUSEDOWN:\r
- case Event.ONTOUCHSTART:\r
- if (!disabled && !readonly) {\r
- focus();\r
- feedbackPopup.show();\r
- dragging = true;\r
- DOM.setElementProperty(handle, "className", CLASSNAME\r
- + "-handle " + CLASSNAME + "-handle-active");\r
- DOM.setCapture(getElement());\r
- DOM.eventPreventDefault(event); // prevent selecting text\r
- DOM.eventCancelBubble(event, true);\r
- event.stopPropagation();\r
- VConsole.log("Slider move start");\r
- }\r
- break;\r
- case Event.ONMOUSEMOVE:\r
- case Event.ONTOUCHMOVE:\r
- if (dragging) {\r
- VConsole.log("Slider move");\r
- setValueByEvent(event, false);\r
- updateFeedbackPosition();\r
- event.stopPropagation();\r
- }\r
- break;\r
- case Event.ONTOUCHEND:\r
- feedbackPopup.hide();\r
- case Event.ONMOUSEUP:\r
- // feedbackPopup.hide();\r
- VConsole.log("Slider move end");\r
- dragging = false;\r
- DOM.setElementProperty(handle, "className", CLASSNAME + "-handle");\r
- DOM.releaseCapture(getElement());\r
- setValueByEvent(event, true);\r
- event.stopPropagation();\r
- break;\r
- default:\r
- break;\r
- }\r
- }\r
- \r
- private void processBaseEvent(Event event) {\r
- if (DOM.eventGetType(event) == Event.ONMOUSEDOWN) {\r
- if (!disabled && !readonly && !dragging) {\r
- setValueByEvent(event, true);\r
- DOM.eventCancelBubble(event, true);\r
- }\r
- }\r
- }\r
- \r
- private void decreaseValue(boolean updateToServer) {\r
- setValue(new Double(value.doubleValue() - Math.pow(10, -resolution)),\r
- updateToServer);\r
- }\r
- \r
- private void increaseValue(boolean updateToServer) {\r
- setValue(new Double(value.doubleValue() + Math.pow(10, -resolution)),\r
- updateToServer);\r
- }\r
- \r
- private void setValueByEvent(Event event, boolean updateToServer) {\r
- double v = min; // Fallback to min\r
- \r
- final int coord = getEventPosition(event);\r
- \r
- final int handleSize, baseSize, baseOffset;\r
- if (vertical) {\r
- handleSize = handle.getOffsetHeight();\r
- baseSize = base.getOffsetHeight();\r
- baseOffset = base.getAbsoluteTop() - Window.getScrollTop()\r
- - handleSize / 2;\r
- } else {\r
- handleSize = handle.getOffsetWidth();\r
- baseSize = base.getOffsetWidth();\r
- baseOffset = base.getAbsoluteLeft() - Window.getScrollLeft()\r
- + handleSize / 2;\r
- }\r
- \r
- if (vertical) {\r
- v = ((baseSize - (coord - baseOffset)) / (double) (baseSize - handleSize))\r
- * (max - min) + min;\r
- } else {\r
- v = ((coord - baseOffset) / (double) (baseSize - handleSize))\r
- * (max - min) + min;\r
- }\r
- \r
- if (v < min) {\r
- v = min;\r
- } else if (v > max) {\r
- v = max;\r
- }\r
- \r
- setValue(v, updateToServer);\r
- }\r
- \r
- /**\r
- * TODO consider extracting touches support to an impl class specific for\r
- * webkit (only browser that really supports touches).\r
- * \r
- * @param event\r
- * @return\r
- */\r
- protected int getEventPosition(Event event) {\r
- if (vertical) {\r
- return Util.getTouchOrMouseClientY(event);\r
- } else {\r
- return Util.getTouchOrMouseClientX(event);\r
- }\r
- }\r
- \r
- public void iLayout() {\r
- if (vertical) {\r
- setHeight();\r
- }\r
- // Update handle position\r
- setValue(value, false);\r
- }\r
- \r
- private void setHeight() {\r
- // Calculate decoration size\r
- DOM.setStyleAttribute(base, "height", "0");\r
- DOM.setStyleAttribute(base, "overflow", "hidden");\r
- int h = DOM.getElementPropertyInt(getElement(), "offsetHeight");\r
- if (h < MIN_SIZE) {\r
- h = MIN_SIZE;\r
- }\r
- DOM.setStyleAttribute(base, "height", h + "px");\r
- DOM.setStyleAttribute(base, "overflow", "");\r
- }\r
- \r
- private void updateValueToServer() {\r
- client.updateVariable(id, "value", value.doubleValue(), immediate);\r
- }\r
- \r
- /**\r
- * Handles the keyboard events handled by the Slider\r
- * \r
- * @param event\r
- * The keyboard event received\r
- * @return true iff the navigation event was handled\r
- */\r
- public boolean handleNavigation(int keycode, boolean ctrl, boolean shift) {\r
- \r
- // No support for ctrl moving\r
- if (ctrl) {\r
- return false;\r
- }\r
- \r
- if ((keycode == getNavigationUpKey() && vertical)\r
- || (keycode == getNavigationRightKey() && !vertical)) {\r
- if (shift) {\r
- for (int a = 0; a < acceleration; a++) {\r
- increaseValue(false);\r
- }\r
- acceleration++;\r
- } else {\r
- increaseValue(false);\r
- }\r
- return true;\r
- } else if (keycode == getNavigationDownKey() && vertical\r
- || (keycode == getNavigationLeftKey() && !vertical)) {\r
- if (shift) {\r
- for (int a = 0; a < acceleration; a++) {\r
- decreaseValue(false);\r
- }\r
- acceleration++;\r
- } else {\r
- decreaseValue(false);\r
- }\r
- return true;\r
- }\r
- \r
- return false;\r
- }\r
- \r
- /**\r
- * Get the key that increases the vertical slider. By default it is the up\r
- * arrow key but by overriding this you can change the key to whatever you\r
- * want.\r
- * \r
- * @return The keycode of the key\r
- */\r
- protected int getNavigationUpKey() {\r
- return KeyCodes.KEY_UP;\r
- }\r
- \r
- /**\r
- * Get the key that decreases the vertical slider. By default it is the down\r
- * arrow key but by overriding this you can change the key to whatever you\r
- * want.\r
- * \r
- * @return The keycode of the key\r
- */\r
- protected int getNavigationDownKey() {\r
- return KeyCodes.KEY_DOWN;\r
- }\r
- \r
- /**\r
- * Get the key that decreases the horizontal slider. By default it is the\r
- * left arrow key but by overriding this you can change the key to whatever\r
- * you want.\r
- * \r
- * @return The keycode of the key\r
- */\r
- protected int getNavigationLeftKey() {\r
- return KeyCodes.KEY_LEFT;\r
- }\r
- \r
- /**\r
- * Get the key that increases the horizontal slider. By default it is the\r
- * right arrow key but by overriding this you can change the key to whatever\r
- * you want.\r
- * \r
- * @return The keycode of the key\r
- */\r
- protected int getNavigationRightKey() {\r
- return KeyCodes.KEY_RIGHT;\r
- }\r
- \r
- public Widget getWidgetForPaintable() {\r
- return this;\r
- }\r
- }\r
+ /*
+ @VaadinApache2LicenseForJavaFiles@
+ */
+ //
+ package com.vaadin.terminal.gwt.client.ui;
+
+ import com.google.gwt.core.client.Scheduler;
+ import com.google.gwt.core.client.Scheduler.ScheduledCommand;
+ import com.google.gwt.event.dom.client.KeyCodes;
+ import com.google.gwt.user.client.Command;
+ import com.google.gwt.user.client.DOM;
+ import com.google.gwt.user.client.Element;
+ import com.google.gwt.user.client.Event;
+ import com.google.gwt.user.client.Window;
+ import com.google.gwt.user.client.ui.HTML;
++import com.google.gwt.user.client.ui.Widget;
+ import com.vaadin.terminal.gwt.client.ApplicationConnection;
+ import com.vaadin.terminal.gwt.client.BrowserInfo;
+ import com.vaadin.terminal.gwt.client.ContainerResizedListener;
-import com.vaadin.terminal.gwt.client.Paintable;
-import com.vaadin.terminal.gwt.client.UIDL;
+ import com.vaadin.terminal.gwt.client.Util;
+ import com.vaadin.terminal.gwt.client.VConsole;
+
-public class VSlider extends SimpleFocusablePanel implements Paintable, Field,
++public class VSlider extends SimpleFocusablePanel implements Field,
+ ContainerResizedListener {
+
+ public static final String CLASSNAME = "v-slider";
+
+ /**
+ * Minimum size (width or height, depending on orientation) of the slider
+ * base.
+ */
+ private static final int MIN_SIZE = 50;
+
+ ApplicationConnection client;
+
+ String id;
+
- private boolean immediate;
- private boolean disabled;
- private boolean readonly;
- private boolean scrollbarStyle;
++ boolean immediate;
++ boolean disabled;
++ boolean readonly;
+
+ private int acceleration = 1;
- private int handleSize;
- private double min;
- private double max;
- private int resolution;
- private Double value;
- private boolean vertical;
- private boolean arrows;
++ double min;
++ double max;
++ int resolution;
++ Double value;
++ boolean vertical;
+
+ private final HTML feedback = new HTML("", false);
+ private final VOverlay feedbackPopup = new VOverlay(true, false, true) {
+ @Override
+ public void show() {
+ super.show();
+ updateFeedbackPosition();
+ }
+ };
+
+ /* DOM element for slider's base */
+ private final Element base;
+ private final int BASE_BORDER_WIDTH = 1;
+
+ /* DOM element for slider's handle */
+ private final Element handle;
+
+ /* DOM element for decrement arrow */
+ private final Element smaller;
+
+ /* DOM element for increment arrow */
+ private final Element bigger;
+
+ /* Temporary dragging/animation variables */
+ private boolean dragging = false;
+
+ private VLazyExecutor delayedValueUpdater = new VLazyExecutor(100,
+ new ScheduledCommand() {
+
+ public void execute() {
+ updateValueToServer();
+ acceleration = 1;
+ }
+ });
+
+ public VSlider() {
+ super();
+
+ base = DOM.createDiv();
+ handle = DOM.createDiv();
+ smaller = DOM.createDiv();
+ bigger = DOM.createDiv();
+
+ setStyleName(CLASSNAME);
+ DOM.setElementProperty(base, "className", CLASSNAME + "-base");
+ DOM.setElementProperty(handle, "className", CLASSNAME + "-handle");
+ DOM.setElementProperty(smaller, "className", CLASSNAME + "-smaller");
+ DOM.setElementProperty(bigger, "className", CLASSNAME + "-bigger");
+
+ DOM.appendChild(getElement(), bigger);
+ DOM.appendChild(getElement(), smaller);
+ DOM.appendChild(getElement(), base);
+ DOM.appendChild(base, handle);
+
+ // Hide initially
+ DOM.setStyleAttribute(smaller, "display", "none");
+ DOM.setStyleAttribute(bigger, "display", "none");
+ DOM.setStyleAttribute(handle, "visibility", "hidden");
+
+ sinkEvents(Event.MOUSEEVENTS | Event.ONMOUSEWHEEL | Event.KEYEVENTS
+ | Event.FOCUSEVENTS | Event.TOUCHEVENTS);
+
+ feedbackPopup.addStyleName(CLASSNAME + "-feedback");
+ feedbackPopup.setWidget(feedback);
+ }
+
- public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {
-
- this.client = client;
- id = uidl.getId();
-
- // Ensure correct implementation
- if (client.updateComponent(this, uidl, true)) {
- return;
- }
-
- immediate = uidl.getBooleanAttribute("immediate");
- disabled = uidl.getBooleanAttribute("disabled");
- readonly = uidl.getBooleanAttribute("readonly");
-
- vertical = uidl.hasAttribute("vertical");
- arrows = uidl.hasAttribute("arrows");
-
- String style = "";
- if (uidl.hasAttribute("style")) {
- style = uidl.getStringAttribute("style");
- }
-
- scrollbarStyle = style.indexOf("scrollbar") > -1;
-
- if (arrows) {
- DOM.setStyleAttribute(smaller, "display", "block");
- DOM.setStyleAttribute(bigger, "display", "block");
- }
-
- if (vertical) {
- addStyleName(CLASSNAME + "-vertical");
- } else {
- removeStyleName(CLASSNAME + "-vertical");
- }
-
- min = uidl.getDoubleAttribute("min");
- max = uidl.getDoubleAttribute("max");
- resolution = uidl.getIntAttribute("resolution");
- value = new Double(uidl.getDoubleVariable("value"));
-
- setFeedbackValue(value);
-
- handleSize = uidl.getIntAttribute("hsize");
-
- buildBase();
-
- if (!vertical) {
- // Draw handle with a delay to allow base to gain maximum width
- Scheduler.get().scheduleDeferred(new Command() {
- public void execute() {
- buildHandle();
- setValue(value, false);
- }
- });
- } else {
- buildHandle();
- setValue(value, false);
- }
- }
-
- private void setFeedbackValue(double value) {
++ void setFeedbackValue(double value) {
+ String currentValue = "" + value;
+ if (resolution == 0) {
+ currentValue = "" + new Double(value).intValue();
+ }
+ feedback.setText(currentValue);
+ }
+
+ private void updateFeedbackPosition() {
+ if (vertical) {
+ feedbackPopup.setPopupPosition(
+ DOM.getAbsoluteLeft(handle) + handle.getOffsetWidth(),
+ DOM.getAbsoluteTop(handle) + handle.getOffsetHeight() / 2
+ - feedbackPopup.getOffsetHeight() / 2);
+ } else {
+ feedbackPopup.setPopupPosition(
+ DOM.getAbsoluteLeft(handle) + handle.getOffsetWidth() / 2
+ - feedbackPopup.getOffsetWidth() / 2,
+ DOM.getAbsoluteTop(handle)
+ - feedbackPopup.getOffsetHeight());
+ }
+ }
+
- private void buildBase() {
++ void buildBase() {
+ final String styleAttribute = vertical ? "height" : "width";
+ final String domProperty = vertical ? "offsetHeight" : "offsetWidth";
+
+ final Element p = DOM.getParent(getElement());
+ if (DOM.getElementPropertyInt(p, domProperty) > 50) {
+ if (vertical) {
+ setHeight();
+ } else {
+ DOM.setStyleAttribute(base, styleAttribute, "");
+ }
+ } else {
+ // Set minimum size and adjust after all components have
+ // (supposedly) been drawn completely.
+ DOM.setStyleAttribute(base, styleAttribute, MIN_SIZE + "px");
+ Scheduler.get().scheduleDeferred(new Command() {
+ public void execute() {
+ final Element p = DOM.getParent(getElement());
+ if (DOM.getElementPropertyInt(p, domProperty) > (MIN_SIZE + 5)) {
+ if (vertical) {
+ setHeight();
+ } else {
+ DOM.setStyleAttribute(base, styleAttribute, "");
+ }
+ // Ensure correct position
+ setValue(value, false);
+ }
+ }
+ });
+ }
+
+ // TODO attach listeners for focusing and arrow keys
+ }
+
- private void buildHandle() {
- final String styleAttribute = vertical ? "height" : "width";
++ void buildHandle() {
+ final String handleAttribute = vertical ? "marginTop" : "marginLeft";
- final String domProperty = vertical ? "offsetHeight" : "offsetWidth";
+
+ DOM.setStyleAttribute(handle, handleAttribute, "0");
+
- if (scrollbarStyle) {
- // Only stretch the handle if scrollbar style is set.
- int s = (int) (Double.parseDouble(DOM.getElementProperty(base,
- domProperty)) / 100 * handleSize);
- if (handleSize == -1) {
- final int baseS = Integer.parseInt(DOM.getElementProperty(base,
- domProperty));
- final double range = (max - min) * (resolution + 1) * 3;
- s = (int) (baseS - range);
- }
- if (s < 3) {
- s = 3;
- }
- DOM.setStyleAttribute(handle, styleAttribute, s + "px");
- } else {
- DOM.setStyleAttribute(handle, styleAttribute, "");
- }
-
+ // Restore visibility
+ DOM.setStyleAttribute(handle, "visibility", "visible");
+
+ }
+
- private void setValue(Double value, boolean updateToServer) {
++ void setValue(Double value, boolean updateToServer) {
+ if (value == null) {
+ return;
+ }
+
+ if (value < min) {
+ value = min;
+ } else if (value > max) {
+ value = max;
+ }
+
+ // Update handle position
+ final String styleAttribute = vertical ? "marginTop" : "marginLeft";
+ final String domProperty = vertical ? "offsetHeight" : "offsetWidth";
+ final int handleSize = Integer.parseInt(DOM.getElementProperty(handle,
+ domProperty));
+ final int baseSize = Integer.parseInt(DOM.getElementProperty(base,
+ domProperty)) - (2 * BASE_BORDER_WIDTH);
+
+ final int range = baseSize - handleSize;
+ double v = value.doubleValue();
+
+ // Round value to resolution
+ if (resolution > 0) {
+ v = Math.round(v * Math.pow(10, resolution));
+ v = v / Math.pow(10, resolution);
+ } else {
+ v = Math.round(v);
+ }
+ final double valueRange = max - min;
+ double p = 0;
+ if (valueRange > 0) {
+ p = range * ((v - min) / valueRange);
+ }
+ if (p < 0) {
+ p = 0;
+ }
+ if (vertical) {
- // IE6 rounding behaves a little unstable, reduce one pixel so the
- // containing element (base) won't expand without limits
- p = range - p - (BrowserInfo.get().isIE6() ? 1 : 0);
++ p = range - p;
+ }
+ final double pos = p;
+
+ DOM.setStyleAttribute(handle, styleAttribute, (Math.round(pos)) + "px");
+
+ // Update value
+ this.value = new Double(v);
+ setFeedbackValue(v);
+
+ if (updateToServer) {
+ updateValueToServer();
+ }
+ }
+
+ @Override
+ public void onBrowserEvent(Event event) {
+ if (disabled || readonly) {
+ return;
+ }
+ final Element targ = DOM.eventGetTarget(event);
+
+ if (DOM.eventGetType(event) == Event.ONMOUSEWHEEL) {
+ processMouseWheelEvent(event);
+ } else if (dragging || targ == handle) {
+ processHandleEvent(event);
+ } else if (targ == smaller) {
+ decreaseValue(true);
+ } else if (targ == bigger) {
+ increaseValue(true);
+ } else if (DOM.eventGetType(event) == Event.MOUSEEVENTS) {
+ processBaseEvent(event);
+ } else if ((BrowserInfo.get().isGecko() && DOM.eventGetType(event) == Event.ONKEYPRESS)
+ || (!BrowserInfo.get().isGecko() && DOM.eventGetType(event) == Event.ONKEYDOWN)) {
+
+ if (handleNavigation(event.getKeyCode(), event.getCtrlKey(),
+ event.getShiftKey())) {
+
+ feedbackPopup.show();
+
+ delayedValueUpdater.trigger();
+
+ DOM.eventPreventDefault(event);
+ DOM.eventCancelBubble(event, true);
+ }
+ } else if (targ.equals(getElement())
+ && DOM.eventGetType(event) == Event.ONFOCUS) {
+ feedbackPopup.show();
+ } else if (targ.equals(getElement())
+ && DOM.eventGetType(event) == Event.ONBLUR) {
+ feedbackPopup.hide();
+ } else if (DOM.eventGetType(event) == Event.ONMOUSEDOWN) {
+ feedbackPopup.show();
+ }
- if(Util.isTouchEvent(event)) {
++ if (Util.isTouchEvent(event)) {
+ event.preventDefault(); // avoid simulated events
+ event.stopPropagation();
+ }
+ }
+
+ private void processMouseWheelEvent(final Event event) {
+ final int dir = DOM.eventGetMouseWheelVelocityY(event);
+
+ if (dir < 0) {
+ increaseValue(false);
+ } else {
+ decreaseValue(false);
+ }
+
+ delayedValueUpdater.trigger();
+
+ DOM.eventPreventDefault(event);
+ DOM.eventCancelBubble(event, true);
+ }
+
+ private void processHandleEvent(Event event) {
+ switch (DOM.eventGetType(event)) {
+ case Event.ONMOUSEDOWN:
+ case Event.ONTOUCHSTART:
+ if (!disabled && !readonly) {
+ focus();
+ feedbackPopup.show();
+ dragging = true;
+ DOM.setElementProperty(handle, "className", CLASSNAME
+ + "-handle " + CLASSNAME + "-handle-active");
+ DOM.setCapture(getElement());
+ DOM.eventPreventDefault(event); // prevent selecting text
+ DOM.eventCancelBubble(event, true);
+ event.stopPropagation();
+ VConsole.log("Slider move start");
+ }
+ break;
+ case Event.ONMOUSEMOVE:
+ case Event.ONTOUCHMOVE:
+ if (dragging) {
+ VConsole.log("Slider move");
+ setValueByEvent(event, false);
+ updateFeedbackPosition();
+ event.stopPropagation();
+ }
+ break;
+ case Event.ONTOUCHEND:
+ feedbackPopup.hide();
+ case Event.ONMOUSEUP:
+ // feedbackPopup.hide();
+ VConsole.log("Slider move end");
+ dragging = false;
+ DOM.setElementProperty(handle, "className", CLASSNAME + "-handle");
+ DOM.releaseCapture(getElement());
+ setValueByEvent(event, true);
+ event.stopPropagation();
+ break;
+ default:
+ break;
+ }
+ }
+
+ private void processBaseEvent(Event event) {
+ if (DOM.eventGetType(event) == Event.ONMOUSEDOWN) {
+ if (!disabled && !readonly && !dragging) {
+ setValueByEvent(event, true);
+ DOM.eventCancelBubble(event, true);
+ }
+ }
+ }
+
+ private void decreaseValue(boolean updateToServer) {
+ setValue(new Double(value.doubleValue() - Math.pow(10, -resolution)),
+ updateToServer);
+ }
+
+ private void increaseValue(boolean updateToServer) {
+ setValue(new Double(value.doubleValue() + Math.pow(10, -resolution)),
+ updateToServer);
+ }
+
+ private void setValueByEvent(Event event, boolean updateToServer) {
+ double v = min; // Fallback to min
+
+ final int coord = getEventPosition(event);
+
+ final int handleSize, baseSize, baseOffset;
+ if (vertical) {
+ handleSize = handle.getOffsetHeight();
+ baseSize = base.getOffsetHeight();
+ baseOffset = base.getAbsoluteTop() - Window.getScrollTop()
+ - handleSize / 2;
+ } else {
+ handleSize = handle.getOffsetWidth();
+ baseSize = base.getOffsetWidth();
+ baseOffset = base.getAbsoluteLeft() - Window.getScrollLeft()
+ + handleSize / 2;
+ }
+
+ if (vertical) {
+ v = ((baseSize - (coord - baseOffset)) / (double) (baseSize - handleSize))
+ * (max - min) + min;
+ } else {
+ v = ((coord - baseOffset) / (double) (baseSize - handleSize))
+ * (max - min) + min;
+ }
+
+ if (v < min) {
+ v = min;
+ } else if (v > max) {
+ v = max;
+ }
+
+ setValue(v, updateToServer);
+ }
+
+ /**
+ * TODO consider extracting touches support to an impl class specific for
+ * webkit (only browser that really supports touches).
+ *
+ * @param event
+ * @return
+ */
+ protected int getEventPosition(Event event) {
+ if (vertical) {
+ return Util.getTouchOrMouseClientY(event);
+ } else {
+ return Util.getTouchOrMouseClientX(event);
+ }
+ }
+
+ public void iLayout() {
+ if (vertical) {
+ setHeight();
+ }
+ // Update handle position
+ setValue(value, false);
+ }
+
+ private void setHeight() {
+ // Calculate decoration size
+ DOM.setStyleAttribute(base, "height", "0");
+ DOM.setStyleAttribute(base, "overflow", "hidden");
+ int h = DOM.getElementPropertyInt(getElement(), "offsetHeight");
+ if (h < MIN_SIZE) {
+ h = MIN_SIZE;
+ }
+ DOM.setStyleAttribute(base, "height", h + "px");
+ DOM.setStyleAttribute(base, "overflow", "");
+ }
+
+ private void updateValueToServer() {
+ client.updateVariable(id, "value", value.doubleValue(), immediate);
+ }
+
+ /**
+ * Handles the keyboard events handled by the Slider
+ *
+ * @param event
+ * The keyboard event received
+ * @return true iff the navigation event was handled
+ */
+ public boolean handleNavigation(int keycode, boolean ctrl, boolean shift) {
+
+ // No support for ctrl moving
+ if (ctrl) {
+ return false;
+ }
+
+ if ((keycode == getNavigationUpKey() && vertical)
+ || (keycode == getNavigationRightKey() && !vertical)) {
+ if (shift) {
+ for (int a = 0; a < acceleration; a++) {
+ increaseValue(false);
+ }
+ acceleration++;
+ } else {
+ increaseValue(false);
+ }
+ return true;
+ } else if (keycode == getNavigationDownKey() && vertical
+ || (keycode == getNavigationLeftKey() && !vertical)) {
+ if (shift) {
+ for (int a = 0; a < acceleration; a++) {
+ decreaseValue(false);
+ }
+ acceleration++;
+ } else {
+ decreaseValue(false);
+ }
+ return true;
+ }
+
+ return false;
+ }
+
+ /**
+ * Get the key that increases the vertical slider. By default it is the up
+ * arrow key but by overriding this you can change the key to whatever you
+ * want.
+ *
+ * @return The keycode of the key
+ */
+ protected int getNavigationUpKey() {
+ return KeyCodes.KEY_UP;
+ }
+
+ /**
+ * Get the key that decreases the vertical slider. By default it is the down
+ * arrow key but by overriding this you can change the key to whatever you
+ * want.
+ *
+ * @return The keycode of the key
+ */
+ protected int getNavigationDownKey() {
+ return KeyCodes.KEY_DOWN;
+ }
+
+ /**
+ * Get the key that decreases the horizontal slider. By default it is the
+ * left arrow key but by overriding this you can change the key to whatever
+ * you want.
+ *
+ * @return The keycode of the key
+ */
+ protected int getNavigationLeftKey() {
+ return KeyCodes.KEY_LEFT;
+ }
+
+ /**
+ * Get the key that increases the horizontal slider. By default it is the
+ * right arrow key but by overriding this you can change the key to whatever
+ * you want.
+ *
+ * @return The keycode of the key
+ */
+ protected int getNavigationRightKey() {
+ return KeyCodes.KEY_RIGHT;
+ }
++
++ public Widget getWidgetForPaintable() {
++ return this;
++ }
+ }
--- /dev/null
- package com.vaadin.terminal.gwt.client.ui;\r
- \r
- import com.google.gwt.core.client.GWT;\r
- import com.google.gwt.core.client.Scheduler;\r
- import com.google.gwt.user.client.Command;\r
- import com.google.gwt.user.client.ui.Widget;\r
- import com.vaadin.terminal.gwt.client.ApplicationConnection;\r
- import com.vaadin.terminal.gwt.client.UIDL;\r
- \r
- public class VSliderPaintable extends VAbstractPaintableWidget {\r
- \r
- public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {\r
- \r
- getWidgetForPaintable().client = client;\r
- getWidgetForPaintable().id = uidl.getId();\r
- \r
- // Ensure correct implementation\r
- if (client.updateComponent(this, uidl, true)) {\r
- return;\r
- }\r
- \r
- getWidgetForPaintable().immediate = uidl\r
- .getBooleanAttribute("immediate");\r
- getWidgetForPaintable().disabled = uidl.getBooleanAttribute("disabled");\r
- getWidgetForPaintable().readonly = uidl.getBooleanAttribute("readonly");\r
- \r
- getWidgetForPaintable().vertical = uidl.hasAttribute("vertical");\r
- \r
- String style = "";\r
- if (uidl.hasAttribute("style")) {\r
- style = uidl.getStringAttribute("style");\r
- }\r
- \r
- if (getWidgetForPaintable().vertical) {\r
- getWidgetForPaintable().addStyleName(\r
- VSlider.CLASSNAME + "-vertical");\r
- } else {\r
- getWidgetForPaintable().removeStyleName(\r
- VSlider.CLASSNAME + "-vertical");\r
- }\r
- \r
- getWidgetForPaintable().min = uidl.getDoubleAttribute("min");\r
- getWidgetForPaintable().max = uidl.getDoubleAttribute("max");\r
- getWidgetForPaintable().resolution = uidl.getIntAttribute("resolution");\r
- getWidgetForPaintable().value = new Double(\r
- uidl.getDoubleVariable("value"));\r
- \r
- getWidgetForPaintable().setFeedbackValue(getWidgetForPaintable().value);\r
- \r
- getWidgetForPaintable().buildBase();\r
- \r
- if (!getWidgetForPaintable().vertical) {\r
- // Draw handle with a delay to allow base to gain maximum width\r
- Scheduler.get().scheduleDeferred(new Command() {\r
- public void execute() {\r
- getWidgetForPaintable().buildHandle();\r
- getWidgetForPaintable().setValue(\r
- getWidgetForPaintable().value, false);\r
- }\r
- });\r
- } else {\r
- getWidgetForPaintable().buildHandle();\r
- getWidgetForPaintable().setValue(getWidgetForPaintable().value,\r
- false);\r
- }\r
- }\r
- \r
- @Override\r
- public VSlider getWidgetForPaintable() {\r
- return (VSlider) super.getWidgetForPaintable();\r
- }\r
- \r
- @Override\r
- protected Widget createWidget() {\r
- return GWT.create(VSlider.class);\r
- }\r
- \r
- }\r
++package com.vaadin.terminal.gwt.client.ui;
++
++import com.google.gwt.core.client.GWT;
++import com.google.gwt.core.client.Scheduler;
++import com.google.gwt.user.client.Command;
++import com.google.gwt.user.client.ui.Widget;
++import com.vaadin.terminal.gwt.client.ApplicationConnection;
++import com.vaadin.terminal.gwt.client.UIDL;
++
++public class VSliderPaintable extends VAbstractPaintableWidget {
++
++ public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {
++
++ getWidgetForPaintable().client = client;
++ getWidgetForPaintable().id = uidl.getId();
++
++ // Ensure correct implementation
++ if (client.updateComponent(this, uidl, true)) {
++ return;
++ }
++
++ getWidgetForPaintable().immediate = uidl
++ .getBooleanAttribute("immediate");
++ getWidgetForPaintable().disabled = uidl.getBooleanAttribute("disabled");
++ getWidgetForPaintable().readonly = uidl.getBooleanAttribute("readonly");
++
++ getWidgetForPaintable().vertical = uidl.hasAttribute("vertical");
++
++ String style = "";
++ if (uidl.hasAttribute("style")) {
++ style = uidl.getStringAttribute("style");
++ }
++
++ if (getWidgetForPaintable().vertical) {
++ getWidgetForPaintable().addStyleName(
++ VSlider.CLASSNAME + "-vertical");
++ } else {
++ getWidgetForPaintable().removeStyleName(
++ VSlider.CLASSNAME + "-vertical");
++ }
++
++ getWidgetForPaintable().min = uidl.getDoubleAttribute("min");
++ getWidgetForPaintable().max = uidl.getDoubleAttribute("max");
++ getWidgetForPaintable().resolution = uidl.getIntAttribute("resolution");
++ getWidgetForPaintable().value = new Double(
++ uidl.getDoubleVariable("value"));
++
++ getWidgetForPaintable().setFeedbackValue(getWidgetForPaintable().value);
++
++ getWidgetForPaintable().buildBase();
++
++ if (!getWidgetForPaintable().vertical) {
++ // Draw handle with a delay to allow base to gain maximum width
++ Scheduler.get().scheduleDeferred(new Command() {
++ public void execute() {
++ getWidgetForPaintable().buildHandle();
++ getWidgetForPaintable().setValue(
++ getWidgetForPaintable().value, false);
++ }
++ });
++ } else {
++ getWidgetForPaintable().buildHandle();
++ getWidgetForPaintable().setValue(getWidgetForPaintable().value,
++ false);
++ }
++ }
++
++ @Override
++ public VSlider getWidgetForPaintable() {
++ return (VSlider) super.getWidgetForPaintable();
++ }
++
++ @Override
++ protected Widget createWidget() {
++ return GWT.create(VSlider.class);
++ }
++
++}
--- /dev/null
- package com.vaadin.terminal.gwt.client.ui;\r
- \r
- import java.util.ArrayList;\r
- import java.util.Iterator;\r
- \r
- import com.google.gwt.user.client.ui.Widget;\r
- import com.vaadin.terminal.gwt.client.ApplicationConnection;\r
- import com.vaadin.terminal.gwt.client.UIDL;\r
- import com.vaadin.terminal.gwt.client.VPaintableMap;\r
- import com.vaadin.terminal.gwt.client.VPaintableWidget;\r
- \r
- public abstract class VTabsheetBasePaintable extends\r
- VAbstractPaintableWidgetContainer {\r
- \r
- public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {\r
- getWidgetForPaintable().client = client;\r
- \r
- // Ensure correct implementation\r
- getWidgetForPaintable().cachedUpdate = client.updateComponent(this,\r
- uidl, true);\r
- if (getWidgetForPaintable().cachedUpdate) {\r
- return;\r
- }\r
- \r
- // Update member references\r
- getWidgetForPaintable().id = uidl.getId();\r
- getWidgetForPaintable().disabled = uidl.hasAttribute("disabled");\r
- \r
- // Render content\r
- final UIDL tabs = uidl.getChildUIDL(0);\r
- \r
- // Paintables in the TabSheet before update\r
- ArrayList<Widget> oldWidgets = new ArrayList<Widget>();\r
- for (Iterator<Widget> iterator = getWidgetForPaintable()\r
- .getWidgetIterator(); iterator.hasNext();) {\r
- oldWidgets.add(iterator.next());\r
- }\r
- \r
- // Clear previous values\r
- getWidgetForPaintable().tabKeys.clear();\r
- getWidgetForPaintable().disabledTabKeys.clear();\r
- \r
- int index = 0;\r
- for (final Iterator<Object> it = tabs.getChildIterator(); it.hasNext();) {\r
- final UIDL tab = (UIDL) it.next();\r
- final String key = tab.getStringAttribute("key");\r
- final boolean selected = tab.getBooleanAttribute("selected");\r
- final boolean hidden = tab.getBooleanAttribute("hidden");\r
- \r
- if (tab.getBooleanAttribute("disabled")) {\r
- getWidgetForPaintable().disabledTabKeys.add(key);\r
- }\r
- \r
- getWidgetForPaintable().tabKeys.add(key);\r
- \r
- if (selected) {\r
- getWidgetForPaintable().activeTabIndex = index;\r
- }\r
- getWidgetForPaintable().renderTab(tab, index, selected, hidden);\r
- index++;\r
- }\r
- \r
- int tabCount = getWidgetForPaintable().getTabCount();\r
- while (tabCount-- > index) {\r
- getWidgetForPaintable().removeTab(index);\r
- }\r
- \r
- for (int i = 0; i < getWidgetForPaintable().getTabCount(); i++) {\r
- VPaintableWidget p = getWidgetForPaintable().getTab(i);\r
- // During the initial rendering the paintable might be null (this is\r
- // weird...)\r
- if (p != null) {\r
- oldWidgets.remove(p.getWidgetForPaintable());\r
- }\r
- }\r
- \r
- // Perform unregister for any paintables removed during update\r
- for (Iterator<Widget> iterator = oldWidgets.iterator(); iterator\r
- .hasNext();) {\r
- Widget oldWidget = iterator.next();\r
- VPaintableWidget oldPaintable = VPaintableMap.get(client)\r
- .getPaintable(oldWidget);\r
- if (oldWidget.isAttached()) {\r
- oldWidget.removeFromParent();\r
- }\r
- VPaintableMap.get(client).unregisterPaintable(oldPaintable);\r
- }\r
- \r
- }\r
- \r
- @Override\r
- public VTabsheetBase getWidgetForPaintable() {\r
- return (VTabsheetBase) super.getWidgetForPaintable();\r
- }\r
- \r
- }\r
++package com.vaadin.terminal.gwt.client.ui;
++
++import java.util.ArrayList;
++import java.util.Iterator;
++
++import com.google.gwt.user.client.ui.Widget;
++import com.vaadin.terminal.gwt.client.ApplicationConnection;
++import com.vaadin.terminal.gwt.client.UIDL;
++import com.vaadin.terminal.gwt.client.VPaintableMap;
++import com.vaadin.terminal.gwt.client.VPaintableWidget;
++
++public abstract class VTabsheetBasePaintable extends
++ VAbstractPaintableWidgetContainer {
++
++ public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {
++ getWidgetForPaintable().client = client;
++
++ // Ensure correct implementation
++ getWidgetForPaintable().cachedUpdate = client.updateComponent(this,
++ uidl, true);
++ if (getWidgetForPaintable().cachedUpdate) {
++ return;
++ }
++
++ // Update member references
++ getWidgetForPaintable().id = uidl.getId();
++ getWidgetForPaintable().disabled = uidl.hasAttribute("disabled");
++
++ // Render content
++ final UIDL tabs = uidl.getChildUIDL(0);
++
++ // Paintables in the TabSheet before update
++ ArrayList<Widget> oldWidgets = new ArrayList<Widget>();
++ for (Iterator<Widget> iterator = getWidgetForPaintable()
++ .getWidgetIterator(); iterator.hasNext();) {
++ oldWidgets.add(iterator.next());
++ }
++
++ // Clear previous values
++ getWidgetForPaintable().tabKeys.clear();
++ getWidgetForPaintable().disabledTabKeys.clear();
++
++ int index = 0;
++ for (final Iterator<Object> it = tabs.getChildIterator(); it.hasNext();) {
++ final UIDL tab = (UIDL) it.next();
++ final String key = tab.getStringAttribute("key");
++ final boolean selected = tab.getBooleanAttribute("selected");
++ final boolean hidden = tab.getBooleanAttribute("hidden");
++
++ if (tab.getBooleanAttribute("disabled")) {
++ getWidgetForPaintable().disabledTabKeys.add(key);
++ }
++
++ getWidgetForPaintable().tabKeys.add(key);
++
++ if (selected) {
++ getWidgetForPaintable().activeTabIndex = index;
++ }
++ getWidgetForPaintable().renderTab(tab, index, selected, hidden);
++ index++;
++ }
++
++ int tabCount = getWidgetForPaintable().getTabCount();
++ while (tabCount-- > index) {
++ getWidgetForPaintable().removeTab(index);
++ }
++
++ for (int i = 0; i < getWidgetForPaintable().getTabCount(); i++) {
++ VPaintableWidget p = getWidgetForPaintable().getTab(i);
++ // During the initial rendering the paintable might be null (this is
++ // weird...)
++ if (p != null) {
++ oldWidgets.remove(p.getWidgetForPaintable());
++ }
++ }
++
++ // Perform unregister for any paintables removed during update
++ for (Iterator<Widget> iterator = oldWidgets.iterator(); iterator
++ .hasNext();) {
++ Widget oldWidget = iterator.next();
++ VPaintableWidget oldPaintable = VPaintableMap.get(client)
++ .getPaintable(oldWidget);
++ if (oldWidget.isAttached()) {
++ oldWidget.removeFromParent();
++ }
++ VPaintableMap.get(client).unregisterPaintable(oldPaintable);
++ }
++
++ }
++
++ @Override
++ public VTabsheetBase getWidgetForPaintable() {
++ return (VTabsheetBase) super.getWidgetForPaintable();
++ }
++
++}
--- /dev/null
- package com.vaadin.terminal.gwt.client.ui;\r
- \r
- import com.google.gwt.core.client.GWT;\r
- import com.google.gwt.user.client.DOM;\r
- import com.google.gwt.user.client.ui.Widget;\r
- import com.vaadin.terminal.gwt.client.ApplicationConnection;\r
- import com.vaadin.terminal.gwt.client.UIDL;\r
- import com.vaadin.terminal.gwt.client.VPaintableWidget;\r
- \r
- public class VTabsheetPaintable extends VTabsheetBasePaintable {\r
- \r
- @Override\r
- public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {\r
- getWidgetForPaintable().rendering = true;\r
- \r
- if (!uidl.getBooleanAttribute("cached")) {\r
- // Handle stylename changes before generics (might affect size\r
- // calculations)\r
- getWidgetForPaintable().handleStyleNames(uidl);\r
- }\r
- \r
- super.updateFromUIDL(uidl, client);\r
- if (getWidgetForPaintable().cachedUpdate) {\r
- getWidgetForPaintable().rendering = false;\r
- return;\r
- }\r
- \r
- // tabs; push or not\r
- if (!getWidgetForPaintable().isDynamicWidth()) {\r
- // FIXME: This makes tab sheet tabs go to 1px width on every update\r
- // and then back to original width\r
- // update width later, in updateTabScroller();\r
- DOM.setStyleAttribute(getWidgetForPaintable().tabs, "width", "1px");\r
- DOM.setStyleAttribute(getWidgetForPaintable().tabs, "overflow",\r
- "hidden");\r
- } else {\r
- getWidgetForPaintable().showAllTabs();\r
- DOM.setStyleAttribute(getWidgetForPaintable().tabs, "width", "");\r
- DOM.setStyleAttribute(getWidgetForPaintable().tabs, "overflow",\r
- "visible");\r
- getWidgetForPaintable().updateDynamicWidth();\r
- }\r
- \r
- if (!getWidgetForPaintable().isDynamicHeight()) {\r
- // Must update height after the styles have been set\r
- getWidgetForPaintable().updateContentNodeHeight();\r
- getWidgetForPaintable().updateOpenTabSize();\r
- }\r
- \r
- getWidgetForPaintable().iLayout();\r
- \r
- // Re run relative size update to ensure optimal scrollbars\r
- // TODO isolate to situation that visible tab has undefined height\r
- try {\r
- client.handleComponentRelativeSize(getWidgetForPaintable().tp\r
- .getWidget(getWidgetForPaintable().tp.getVisibleWidget()));\r
- } catch (Exception e) {\r
- // Ignore, most likely empty tabsheet\r
- }\r
- \r
- getWidgetForPaintable().renderInformation\r
- .updateSize(getWidgetForPaintable().getElement());\r
- \r
- getWidgetForPaintable().waitingForResponse = false;\r
- getWidgetForPaintable().rendering = false;\r
- }\r
- \r
- @Override\r
- protected Widget createWidget() {\r
- return GWT.create(VTabsheet.class);\r
- }\r
- \r
- @Override\r
- public VTabsheet getWidgetForPaintable() {\r
- return (VTabsheet) super.getWidgetForPaintable();\r
- }\r
- \r
- public void updateCaption(VPaintableWidget component, UIDL uidl) {\r
- /* Tabsheet does not render its children's captions */\r
- }\r
- \r
- }\r
++package com.vaadin.terminal.gwt.client.ui;
++
++import com.google.gwt.core.client.GWT;
++import com.google.gwt.user.client.DOM;
++import com.google.gwt.user.client.ui.Widget;
++import com.vaadin.terminal.gwt.client.ApplicationConnection;
++import com.vaadin.terminal.gwt.client.UIDL;
++import com.vaadin.terminal.gwt.client.VPaintableWidget;
++
++public class VTabsheetPaintable extends VTabsheetBasePaintable {
++
++ @Override
++ public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {
++ getWidgetForPaintable().rendering = true;
++
++ if (!uidl.getBooleanAttribute("cached")) {
++ // Handle stylename changes before generics (might affect size
++ // calculations)
++ getWidgetForPaintable().handleStyleNames(uidl);
++ }
++
++ super.updateFromUIDL(uidl, client);
++ if (getWidgetForPaintable().cachedUpdate) {
++ getWidgetForPaintable().rendering = false;
++ return;
++ }
++
++ // tabs; push or not
++ if (!getWidgetForPaintable().isDynamicWidth()) {
++ // FIXME: This makes tab sheet tabs go to 1px width on every update
++ // and then back to original width
++ // update width later, in updateTabScroller();
++ DOM.setStyleAttribute(getWidgetForPaintable().tabs, "width", "1px");
++ DOM.setStyleAttribute(getWidgetForPaintable().tabs, "overflow",
++ "hidden");
++ } else {
++ getWidgetForPaintable().showAllTabs();
++ DOM.setStyleAttribute(getWidgetForPaintable().tabs, "width", "");
++ DOM.setStyleAttribute(getWidgetForPaintable().tabs, "overflow",
++ "visible");
++ getWidgetForPaintable().updateDynamicWidth();
++ }
++
++ if (!getWidgetForPaintable().isDynamicHeight()) {
++ // Must update height after the styles have been set
++ getWidgetForPaintable().updateContentNodeHeight();
++ getWidgetForPaintable().updateOpenTabSize();
++ }
++
++ getWidgetForPaintable().iLayout();
++
++ // Re run relative size update to ensure optimal scrollbars
++ // TODO isolate to situation that visible tab has undefined height
++ try {
++ client.handleComponentRelativeSize(getWidgetForPaintable().tp
++ .getWidget(getWidgetForPaintable().tp.getVisibleWidget()));
++ } catch (Exception e) {
++ // Ignore, most likely empty tabsheet
++ }
++
++ getWidgetForPaintable().renderInformation
++ .updateSize(getWidgetForPaintable().getElement());
++
++ getWidgetForPaintable().waitingForResponse = false;
++ getWidgetForPaintable().rendering = false;
++ }
++
++ @Override
++ protected Widget createWidget() {
++ return GWT.create(VTabsheet.class);
++ }
++
++ @Override
++ public VTabsheet getWidgetForPaintable() {
++ return (VTabsheet) super.getWidgetForPaintable();
++ }
++
++ public void updateCaption(VPaintableWidget component, UIDL uidl) {
++ /* Tabsheet does not render its children's captions */
++ }
++
++}
- /*\r
- @VaadinApache2LicenseForJavaFiles@\r
- */\r
- \r
- package com.vaadin.terminal.gwt.client.ui;\r
- \r
- import com.google.gwt.core.client.Scheduler;\r
- import com.google.gwt.user.client.Command;\r
- import com.google.gwt.user.client.DOM;\r
- import com.google.gwt.user.client.Element;\r
- import com.google.gwt.user.client.Event;\r
- \r
- /**\r
- * This class represents a multiline textfield (textarea).\r
- * \r
- * TODO consider replacing this with a RichTextArea based implementation. IE\r
- * does not support CSS height for textareas in Strict mode :-(\r
- * \r
- * @author Vaadin Ltd.\r
- * \r
- */\r
- public class VTextArea extends VTextField {\r
- public static final String CLASSNAME = "v-textarea";\r
- \r
- public VTextArea() {\r
- super(DOM.createTextArea());\r
- setStyleName(CLASSNAME);\r
- }\r
- \r
- public void setRows(int rows) {\r
- setRows(getElement(), rows);\r
- }\r
- \r
- private native void setRows(Element e, int r)\r
- /*-{\r
- try {\r
- if(e.tagName.toLowerCase() == "textarea")\r
- e.rows = r;\r
- } catch (e) {}\r
- }-*/;\r
- \r
- @Override\r
- public void onBrowserEvent(Event event) {\r
- if (getMaxLength() >= 0 && event.getTypeInt() == Event.ONKEYUP) {\r
- Scheduler.get().scheduleDeferred(new Command() {\r
- public void execute() {\r
- if (getText().length() > getMaxLength()) {\r
- setText(getText().substring(0, getMaxLength()));\r
- }\r
- }\r
- });\r
- }\r
- super.onBrowserEvent(event);\r
- }\r
- \r
- @Override\r
- public int getCursorPos() {\r
- // This is needed so that TextBoxImplIE6 is used to return the correct\r
- // position for old Internet Explorer versions where it has to be\r
- // detected in a different way.\r
- return getImpl().getTextAreaCursorPos(getElement());\r
- }\r
- }\r
+ /*
+ @VaadinApache2LicenseForJavaFiles@
+ */
+
+ package com.vaadin.terminal.gwt.client.ui;
+
+ import com.google.gwt.core.client.Scheduler;
+ import com.google.gwt.user.client.Command;
+ import com.google.gwt.user.client.DOM;
+ import com.google.gwt.user.client.Element;
+ import com.google.gwt.user.client.Event;
-import com.vaadin.terminal.gwt.client.ApplicationConnection;
-import com.vaadin.terminal.gwt.client.UIDL;
+
+ /**
+ * This class represents a multiline textfield (textarea).
+ *
+ * TODO consider replacing this with a RichTextArea based implementation. IE
+ * does not support CSS height for textareas in Strict mode :-(
+ *
+ * @author Vaadin Ltd.
+ *
+ */
+ public class VTextArea extends VTextField {
+ public static final String CLASSNAME = "v-textarea";
+
+ public VTextArea() {
+ super(DOM.createTextArea());
+ setStyleName(CLASSNAME);
+ }
+
- @Override
- public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {
- // Call parent renderer explicitly
- super.updateFromUIDL(uidl, client);
-
- if (uidl.hasAttribute("rows")) {
- setRows(uidl.getIntAttribute("rows"));
- }
-
- if (getMaxLength() >= 0) {
- sinkEvents(Event.ONKEYUP);
- }
- }
-
+ public void setRows(int rows) {
+ setRows(getElement(), rows);
+ }
+
+ private native void setRows(Element e, int r)
+ /*-{
+ try {
+ if(e.tagName.toLowerCase() == "textarea")
+ e.rows = r;
+ } catch (e) {}
+ }-*/;
+
+ @Override
+ public void onBrowserEvent(Event event) {
+ if (getMaxLength() >= 0 && event.getTypeInt() == Event.ONKEYUP) {
+ Scheduler.get().scheduleDeferred(new Command() {
+ public void execute() {
+ if (getText().length() > getMaxLength()) {
+ setText(getText().substring(0, getMaxLength()));
+ }
+ }
+ });
+ }
+ super.onBrowserEvent(event);
+ }
+
+ @Override
+ public int getCursorPos() {
+ // This is needed so that TextBoxImplIE6 is used to return the correct
+ // position for old Internet Explorer versions where it has to be
+ // detected in a different way.
+ return getImpl().getTextAreaCursorPos(getElement());
+ }
+ }
--- /dev/null
- package com.vaadin.terminal.gwt.client.ui;\r
- \r
- import java.util.Iterator;\r
- \r
- import com.google.gwt.core.client.GWT;\r
- import com.google.gwt.user.client.ui.Widget;\r
- import com.vaadin.terminal.gwt.client.ApplicationConnection;\r
- import com.vaadin.terminal.gwt.client.TooltipInfo;\r
- import com.vaadin.terminal.gwt.client.UIDL;\r
- import com.vaadin.terminal.gwt.client.ui.VTree.TreeNode;\r
- \r
- public class VTreePaintable extends VAbstractPaintableWidget {\r
- \r
- public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {\r
- // Ensure correct implementation and let container manage caption\r
- if (client.updateComponent(this, uidl, true)) {\r
- return;\r
- }\r
- \r
- getWidgetForPaintable().rendering = true;\r
- \r
- getWidgetForPaintable().client = client;\r
- \r
- if (uidl.hasAttribute("partialUpdate")) {\r
- handleUpdate(uidl);\r
- getWidgetForPaintable().rendering = false;\r
- return;\r
- }\r
- \r
- getWidgetForPaintable().paintableId = uidl.getId();\r
- \r
- getWidgetForPaintable().immediate = uidl.hasAttribute("immediate");\r
- \r
- getWidgetForPaintable().disabled = uidl.getBooleanAttribute("disabled");\r
- getWidgetForPaintable().readonly = uidl.getBooleanAttribute("readonly");\r
- \r
- getWidgetForPaintable().dragMode = uidl.hasAttribute("dragMode") ? uidl\r
- .getIntAttribute("dragMode") : 0;\r
- \r
- getWidgetForPaintable().isNullSelectionAllowed = uidl\r
- .getBooleanAttribute("nullselect");\r
- \r
- if (uidl.hasAttribute("alb")) {\r
- getWidgetForPaintable().bodyActionKeys = uidl\r
- .getStringArrayAttribute("alb");\r
- }\r
- \r
- getWidgetForPaintable().body.clear();\r
- // clear out any references to nodes that no longer are attached\r
- getWidgetForPaintable().clearNodeToKeyMap();\r
- TreeNode childTree = null;\r
- UIDL childUidl = null;\r
- for (final Iterator<?> i = uidl.getChildIterator(); i.hasNext();) {\r
- childUidl = (UIDL) i.next();\r
- if ("actions".equals(childUidl.getTag())) {\r
- updateActionMap(childUidl);\r
- continue;\r
- } else if ("-ac".equals(childUidl.getTag())) {\r
- getWidgetForPaintable().updateDropHandler(childUidl);\r
- continue;\r
- }\r
- childTree = getWidgetForPaintable().new TreeNode();\r
- updateNodeFromUIDL(childTree, childUidl);\r
- getWidgetForPaintable().body.add(childTree);\r
- childTree.addStyleDependentName("root");\r
- childTree.childNodeContainer.addStyleDependentName("root");\r
- }\r
- if (childTree != null && childUidl != null) {\r
- boolean leaf = !childUidl.getTag().equals("node");\r
- childTree.addStyleDependentName(leaf ? "leaf-last" : "last");\r
- childTree.childNodeContainer.addStyleDependentName("last");\r
- }\r
- final String selectMode = uidl.getStringAttribute("selectmode");\r
- getWidgetForPaintable().selectable = !"none".equals(selectMode);\r
- getWidgetForPaintable().isMultiselect = "multi".equals(selectMode);\r
- \r
- if (getWidgetForPaintable().isMultiselect) {\r
- getWidgetForPaintable().multiSelectMode = uidl\r
- .getIntAttribute("multiselectmode");\r
- }\r
- \r
- getWidgetForPaintable().selectedIds = uidl\r
- .getStringArrayVariableAsSet("selected");\r
- \r
- // Update lastSelection and focusedNode to point to *actual* nodes again\r
- // after the old ones have been cleared from the body. This fixes focus\r
- // and keyboard navigation issues as described in #7057 and other\r
- // tickets.\r
- if (getWidgetForPaintable().lastSelection != null) {\r
- getWidgetForPaintable().lastSelection = getWidgetForPaintable()\r
- .getNodeByKey(getWidgetForPaintable().lastSelection.key);\r
- }\r
- if (getWidgetForPaintable().focusedNode != null) {\r
- getWidgetForPaintable().setFocusedNode(\r
- getWidgetForPaintable().getNodeByKey(\r
- getWidgetForPaintable().focusedNode.key));\r
- }\r
- \r
- if (getWidgetForPaintable().lastSelection == null\r
- && getWidgetForPaintable().focusedNode == null\r
- && !getWidgetForPaintable().selectedIds.isEmpty()) {\r
- getWidgetForPaintable().setFocusedNode(\r
- getWidgetForPaintable().getNodeByKey(\r
- getWidgetForPaintable().selectedIds.iterator()\r
- .next()));\r
- getWidgetForPaintable().focusedNode.setFocused(false);\r
- }\r
- \r
- getWidgetForPaintable().rendering = false;\r
- \r
- }\r
- \r
- @Override\r
- protected Widget createWidget() {\r
- return GWT.create(VTree.class);\r
- }\r
- \r
- @Override\r
- public VTree getWidgetForPaintable() {\r
- return (VTree) super.getWidgetForPaintable();\r
- }\r
- \r
- private void handleUpdate(UIDL uidl) {\r
- final TreeNode rootNode = getWidgetForPaintable().getNodeByKey(\r
- uidl.getStringAttribute("rootKey"));\r
- if (rootNode != null) {\r
- if (!rootNode.getState()) {\r
- // expanding node happened server side\r
- rootNode.setState(true, false);\r
- }\r
- renderChildNodes(rootNode, (Iterator) uidl.getChildIterator());\r
- }\r
- }\r
- \r
- /**\r
- * Registers action for the root and also for individual nodes\r
- * \r
- * @param uidl\r
- */\r
- private void updateActionMap(UIDL uidl) {\r
- final Iterator<?> it = uidl.getChildIterator();\r
- while (it.hasNext()) {\r
- final UIDL action = (UIDL) it.next();\r
- final String key = action.getStringAttribute("key");\r
- final String caption = action.getStringAttribute("caption");\r
- String iconUrl = null;\r
- if (action.hasAttribute("icon")) {\r
- iconUrl = getConnection().translateVaadinUri(\r
- action.getStringAttribute("icon"));\r
- }\r
- getWidgetForPaintable().registerAction(key, caption, iconUrl);\r
- }\r
- \r
- }\r
- \r
- public void updateNodeFromUIDL(TreeNode treeNode, UIDL uidl) {\r
- String nodeKey = uidl.getStringAttribute("key");\r
- treeNode.setText(uidl.getStringAttribute("caption"));\r
- treeNode.key = nodeKey;\r
- \r
- getWidgetForPaintable().registerNode(treeNode);\r
- \r
- if (uidl.hasAttribute("al")) {\r
- treeNode.actionKeys = uidl.getStringArrayAttribute("al");\r
- }\r
- \r
- if (uidl.getTag().equals("node")) {\r
- if (uidl.getChildCount() == 0) {\r
- treeNode.childNodeContainer.setVisible(false);\r
- } else {\r
- renderChildNodes(treeNode, (Iterator) uidl.getChildIterator());\r
- treeNode.childrenLoaded = true;\r
- }\r
- } else {\r
- treeNode.addStyleName(TreeNode.CLASSNAME + "-leaf");\r
- }\r
- if (uidl.hasAttribute("style")) {\r
- treeNode.setNodeStyleName(uidl.getStringAttribute("style"));\r
- }\r
- \r
- String description = uidl.getStringAttribute("descr");\r
- if (description != null && getConnection() != null) {\r
- // Set tooltip\r
- TooltipInfo info = new TooltipInfo(description);\r
- getConnection().registerTooltip(this, nodeKey, info);\r
- } else {\r
- // Remove possible previous tooltip\r
- getConnection().registerTooltip(this, nodeKey, null);\r
- }\r
- \r
- if (uidl.getBooleanAttribute("expanded") && !treeNode.getState()) {\r
- treeNode.setState(true, false);\r
- }\r
- \r
- if (uidl.getBooleanAttribute("selected")) {\r
- treeNode.setSelected(true);\r
- // ensure that identifier is in selectedIds array (this may be a\r
- // partial update)\r
- getWidgetForPaintable().selectedIds.add(nodeKey);\r
- }\r
- \r
- treeNode.setIcon(uidl.getStringAttribute("icon"));\r
- }\r
- \r
- void renderChildNodes(TreeNode containerNode, Iterator<UIDL> i) {\r
- containerNode.childNodeContainer.clear();\r
- containerNode.childNodeContainer.setVisible(true);\r
- while (i.hasNext()) {\r
- final UIDL childUidl = i.next();\r
- // actions are in bit weird place, don't mix them with children,\r
- // but current node's actions\r
- if ("actions".equals(childUidl.getTag())) {\r
- updateActionMap(childUidl);\r
- continue;\r
- }\r
- final TreeNode childTree = getWidgetForPaintable().new TreeNode();\r
- updateNodeFromUIDL(childTree, childUidl);\r
- containerNode.add(childTree);\r
- if (!i.hasNext()) {\r
- childTree\r
- .addStyleDependentName(childTree.isLeaf() ? "leaf-last"\r
- : "last");\r
- childTree.childNodeContainer.addStyleDependentName("last");\r
- }\r
- }\r
- containerNode.childrenLoaded = true;\r
- }\r
- }\r
++package com.vaadin.terminal.gwt.client.ui;
++
++import java.util.Iterator;
++
++import com.google.gwt.core.client.GWT;
++import com.google.gwt.user.client.ui.Widget;
++import com.vaadin.terminal.gwt.client.ApplicationConnection;
++import com.vaadin.terminal.gwt.client.TooltipInfo;
++import com.vaadin.terminal.gwt.client.UIDL;
++import com.vaadin.terminal.gwt.client.ui.VTree.TreeNode;
++
++public class VTreePaintable extends VAbstractPaintableWidget {
++
++ public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {
++ // Ensure correct implementation and let container manage caption
++ if (client.updateComponent(this, uidl, true)) {
++ return;
++ }
++
++ getWidgetForPaintable().rendering = true;
++
++ getWidgetForPaintable().client = client;
++
++ if (uidl.hasAttribute("partialUpdate")) {
++ handleUpdate(uidl);
++ getWidgetForPaintable().rendering = false;
++ return;
++ }
++
++ getWidgetForPaintable().paintableId = uidl.getId();
++
++ getWidgetForPaintable().immediate = uidl.hasAttribute("immediate");
++
++ getWidgetForPaintable().disabled = uidl.getBooleanAttribute("disabled");
++ getWidgetForPaintable().readonly = uidl.getBooleanAttribute("readonly");
++
++ getWidgetForPaintable().dragMode = uidl.hasAttribute("dragMode") ? uidl
++ .getIntAttribute("dragMode") : 0;
++
++ getWidgetForPaintable().isNullSelectionAllowed = uidl
++ .getBooleanAttribute("nullselect");
++
++ if (uidl.hasAttribute("alb")) {
++ getWidgetForPaintable().bodyActionKeys = uidl
++ .getStringArrayAttribute("alb");
++ }
++
++ getWidgetForPaintable().body.clear();
++ // clear out any references to nodes that no longer are attached
++ getWidgetForPaintable().clearNodeToKeyMap();
++ TreeNode childTree = null;
++ UIDL childUidl = null;
++ for (final Iterator<?> i = uidl.getChildIterator(); i.hasNext();) {
++ childUidl = (UIDL) i.next();
++ if ("actions".equals(childUidl.getTag())) {
++ updateActionMap(childUidl);
++ continue;
++ } else if ("-ac".equals(childUidl.getTag())) {
++ getWidgetForPaintable().updateDropHandler(childUidl);
++ continue;
++ }
++ childTree = getWidgetForPaintable().new TreeNode();
++ updateNodeFromUIDL(childTree, childUidl);
++ getWidgetForPaintable().body.add(childTree);
++ childTree.addStyleDependentName("root");
++ childTree.childNodeContainer.addStyleDependentName("root");
++ }
++ if (childTree != null && childUidl != null) {
++ boolean leaf = !childUidl.getTag().equals("node");
++ childTree.addStyleDependentName(leaf ? "leaf-last" : "last");
++ childTree.childNodeContainer.addStyleDependentName("last");
++ }
++ final String selectMode = uidl.getStringAttribute("selectmode");
++ getWidgetForPaintable().selectable = !"none".equals(selectMode);
++ getWidgetForPaintable().isMultiselect = "multi".equals(selectMode);
++
++ if (getWidgetForPaintable().isMultiselect) {
++ getWidgetForPaintable().multiSelectMode = uidl
++ .getIntAttribute("multiselectmode");
++ }
++
++ getWidgetForPaintable().selectedIds = uidl
++ .getStringArrayVariableAsSet("selected");
++
++ // Update lastSelection and focusedNode to point to *actual* nodes again
++ // after the old ones have been cleared from the body. This fixes focus
++ // and keyboard navigation issues as described in #7057 and other
++ // tickets.
++ if (getWidgetForPaintable().lastSelection != null) {
++ getWidgetForPaintable().lastSelection = getWidgetForPaintable()
++ .getNodeByKey(getWidgetForPaintable().lastSelection.key);
++ }
++ if (getWidgetForPaintable().focusedNode != null) {
++ getWidgetForPaintable().setFocusedNode(
++ getWidgetForPaintable().getNodeByKey(
++ getWidgetForPaintable().focusedNode.key));
++ }
++
++ if (getWidgetForPaintable().lastSelection == null
++ && getWidgetForPaintable().focusedNode == null
++ && !getWidgetForPaintable().selectedIds.isEmpty()) {
++ getWidgetForPaintable().setFocusedNode(
++ getWidgetForPaintable().getNodeByKey(
++ getWidgetForPaintable().selectedIds.iterator()
++ .next()));
++ getWidgetForPaintable().focusedNode.setFocused(false);
++ }
++
++ getWidgetForPaintable().rendering = false;
++
++ }
++
++ @Override
++ protected Widget createWidget() {
++ return GWT.create(VTree.class);
++ }
++
++ @Override
++ public VTree getWidgetForPaintable() {
++ return (VTree) super.getWidgetForPaintable();
++ }
++
++ private void handleUpdate(UIDL uidl) {
++ final TreeNode rootNode = getWidgetForPaintable().getNodeByKey(
++ uidl.getStringAttribute("rootKey"));
++ if (rootNode != null) {
++ if (!rootNode.getState()) {
++ // expanding node happened server side
++ rootNode.setState(true, false);
++ }
++ renderChildNodes(rootNode, (Iterator) uidl.getChildIterator());
++ }
++ }
++
++ /**
++ * Registers action for the root and also for individual nodes
++ *
++ * @param uidl
++ */
++ private void updateActionMap(UIDL uidl) {
++ final Iterator<?> it = uidl.getChildIterator();
++ while (it.hasNext()) {
++ final UIDL action = (UIDL) it.next();
++ final String key = action.getStringAttribute("key");
++ final String caption = action.getStringAttribute("caption");
++ String iconUrl = null;
++ if (action.hasAttribute("icon")) {
++ iconUrl = getConnection().translateVaadinUri(
++ action.getStringAttribute("icon"));
++ }
++ getWidgetForPaintable().registerAction(key, caption, iconUrl);
++ }
++
++ }
++
++ public void updateNodeFromUIDL(TreeNode treeNode, UIDL uidl) {
++ String nodeKey = uidl.getStringAttribute("key");
++ treeNode.setText(uidl.getStringAttribute("caption"));
++ treeNode.key = nodeKey;
++
++ getWidgetForPaintable().registerNode(treeNode);
++
++ if (uidl.hasAttribute("al")) {
++ treeNode.actionKeys = uidl.getStringArrayAttribute("al");
++ }
++
++ if (uidl.getTag().equals("node")) {
++ if (uidl.getChildCount() == 0) {
++ treeNode.childNodeContainer.setVisible(false);
++ } else {
++ renderChildNodes(treeNode, (Iterator) uidl.getChildIterator());
++ treeNode.childrenLoaded = true;
++ }
++ } else {
++ treeNode.addStyleName(TreeNode.CLASSNAME + "-leaf");
++ }
++ if (uidl.hasAttribute("style")) {
++ treeNode.setNodeStyleName(uidl.getStringAttribute("style"));
++ }
++
++ String description = uidl.getStringAttribute("descr");
++ if (description != null && getConnection() != null) {
++ // Set tooltip
++ TooltipInfo info = new TooltipInfo(description);
++ getConnection().registerTooltip(this, nodeKey, info);
++ } else {
++ // Remove possible previous tooltip
++ getConnection().registerTooltip(this, nodeKey, null);
++ }
++
++ if (uidl.getBooleanAttribute("expanded") && !treeNode.getState()) {
++ treeNode.setState(true, false);
++ }
++
++ if (uidl.getBooleanAttribute("selected")) {
++ treeNode.setSelected(true);
++ // ensure that identifier is in selectedIds array (this may be a
++ // partial update)
++ getWidgetForPaintable().selectedIds.add(nodeKey);
++ }
++
++ treeNode.setIcon(uidl.getStringAttribute("icon"));
++ }
++
++ void renderChildNodes(TreeNode containerNode, Iterator<UIDL> i) {
++ containerNode.childNodeContainer.clear();
++ containerNode.childNodeContainer.setVisible(true);
++ while (i.hasNext()) {
++ final UIDL childUidl = i.next();
++ // actions are in bit weird place, don't mix them with children,
++ // but current node's actions
++ if ("actions".equals(childUidl.getTag())) {
++ updateActionMap(childUidl);
++ continue;
++ }
++ final TreeNode childTree = getWidgetForPaintable().new TreeNode();
++ updateNodeFromUIDL(childTree, childUidl);
++ containerNode.add(childTree);
++ if (!i.hasNext()) {
++ childTree
++ .addStyleDependentName(childTree.isLeaf() ? "leaf-last"
++ : "last");
++ childTree.childNodeContainer.addStyleDependentName("last");
++ }
++ }
++ containerNode.childrenLoaded = true;
++ }
++}
--- /dev/null
- /*\r
- @VaadinApache2LicenseForJavaFiles@\r
- */\r
- package com.vaadin.terminal.gwt.client.ui;\r
- \r
- import com.google.gwt.core.client.GWT;\r
- import com.google.gwt.user.client.ui.Widget;\r
- import com.vaadin.terminal.gwt.client.ApplicationConnection;\r
- import com.vaadin.terminal.gwt.client.UIDL;\r
- import com.vaadin.terminal.gwt.client.ui.VScrollTable.VScrollTableBody.VScrollTableRow;\r
- import com.vaadin.terminal.gwt.client.ui.VTreeTable.PendingNavigationEvent;\r
- \r
- public class VTreeTablePaintable extends VScrollTablePaintable {\r
- public static final String ATTRIBUTE_HIERARCHY_COLUMN_INDEX = "hci";\r
- \r
- @Override\r
- public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {\r
- FocusableScrollPanel widget = null;\r
- int scrollPosition = 0;\r
- if (getWidgetForPaintable().collapseRequest) {\r
- widget = (FocusableScrollPanel) getWidgetForPaintable()\r
- .getWidget(1);\r
- scrollPosition = widget.getScrollPosition();\r
- }\r
- getWidgetForPaintable().animationsEnabled = uidl\r
- .getBooleanAttribute("animate");\r
- getWidgetForPaintable().colIndexOfHierarchy = uidl\r
- .hasAttribute(ATTRIBUTE_HIERARCHY_COLUMN_INDEX) ? uidl\r
- .getIntAttribute(ATTRIBUTE_HIERARCHY_COLUMN_INDEX) : 0;\r
- int oldTotalRows = getWidgetForPaintable().getTotalRows();\r
- super.updateFromUIDL(uidl, client);\r
- if (getWidgetForPaintable().collapseRequest) {\r
- if (getWidgetForPaintable().collapsedRowKey != null\r
- && getWidgetForPaintable().scrollBody != null) {\r
- VScrollTableRow row = getWidgetForPaintable()\r
- .getRenderedRowByKey(\r
- getWidgetForPaintable().collapsedRowKey);\r
- if (row != null) {\r
- getWidgetForPaintable().setRowFocus(row);\r
- getWidgetForPaintable().focus();\r
- }\r
- }\r
- \r
- int scrollPosition2 = widget.getScrollPosition();\r
- if (scrollPosition != scrollPosition2) {\r
- widget.setScrollPosition(scrollPosition);\r
- }\r
- \r
- // check which rows are needed from the server and initiate a\r
- // deferred fetch\r
- getWidgetForPaintable().onScroll(null);\r
- }\r
- // Recalculate table size if collapse request, or if page length is zero\r
- // (not sent by server) and row count changes (#7908).\r
- if (getWidgetForPaintable().collapseRequest\r
- || (!uidl.hasAttribute("pagelength") && getWidgetForPaintable()\r
- .getTotalRows() != oldTotalRows)) {\r
- /*\r
- * Ensure that possibly removed/added scrollbars are considered.\r
- * Triggers row calculations, removes cached rows etc. Basically\r
- * cleans up state. Be careful if touching this, you will break\r
- * pageLength=0 if you remove this.\r
- */\r
- getWidgetForPaintable().triggerLazyColumnAdjustment(true);\r
- \r
- getWidgetForPaintable().collapseRequest = false;\r
- }\r
- if (uidl.hasAttribute("focusedRow")) {\r
- String key = uidl.getStringAttribute("focusedRow");\r
- getWidgetForPaintable().setRowFocus(\r
- getWidgetForPaintable().getRenderedRowByKey(key));\r
- getWidgetForPaintable().focusParentResponsePending = false;\r
- } else if (uidl.hasAttribute("clearFocusPending")) {\r
- // Special case to detect a response to a focusParent request that\r
- // does not return any focusedRow because the selected node has no\r
- // parent\r
- getWidgetForPaintable().focusParentResponsePending = false;\r
- }\r
- \r
- while (!getWidgetForPaintable().collapseRequest\r
- && !getWidgetForPaintable().focusParentResponsePending\r
- && !getWidgetForPaintable().pendingNavigationEvents.isEmpty()) {\r
- // Keep replaying any queued events as long as we don't have any\r
- // potential content changes pending\r
- PendingNavigationEvent event = getWidgetForPaintable().pendingNavigationEvents\r
- .removeFirst();\r
- getWidgetForPaintable().handleNavigation(event.keycode, event.ctrl,\r
- event.shift);\r
- }\r
- }\r
- \r
- @Override\r
- protected Widget createWidget() {\r
- return GWT.create(VTreeTable.class);\r
- }\r
- \r
- @Override\r
- public VTreeTable getWidgetForPaintable() {\r
- return (VTreeTable) super.getWidgetForPaintable();\r
- }\r
- }\r
++/*
++@VaadinApache2LicenseForJavaFiles@
++ */
++package com.vaadin.terminal.gwt.client.ui;
++
++import com.google.gwt.core.client.GWT;
++import com.google.gwt.user.client.ui.Widget;
++import com.vaadin.terminal.gwt.client.ApplicationConnection;
++import com.vaadin.terminal.gwt.client.UIDL;
++import com.vaadin.terminal.gwt.client.ui.VScrollTable.VScrollTableBody.VScrollTableRow;
++import com.vaadin.terminal.gwt.client.ui.VTreeTable.PendingNavigationEvent;
++
++public class VTreeTablePaintable extends VScrollTablePaintable {
++ public static final String ATTRIBUTE_HIERARCHY_COLUMN_INDEX = "hci";
++
++ @Override
++ public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {
++ FocusableScrollPanel widget = null;
++ int scrollPosition = 0;
++ if (getWidgetForPaintable().collapseRequest) {
++ widget = (FocusableScrollPanel) getWidgetForPaintable()
++ .getWidget(1);
++ scrollPosition = widget.getScrollPosition();
++ }
++ getWidgetForPaintable().animationsEnabled = uidl
++ .getBooleanAttribute("animate");
++ getWidgetForPaintable().colIndexOfHierarchy = uidl
++ .hasAttribute(ATTRIBUTE_HIERARCHY_COLUMN_INDEX) ? uidl
++ .getIntAttribute(ATTRIBUTE_HIERARCHY_COLUMN_INDEX) : 0;
++ int oldTotalRows = getWidgetForPaintable().getTotalRows();
++ super.updateFromUIDL(uidl, client);
++ if (getWidgetForPaintable().collapseRequest) {
++ if (getWidgetForPaintable().collapsedRowKey != null
++ && getWidgetForPaintable().scrollBody != null) {
++ VScrollTableRow row = getWidgetForPaintable()
++ .getRenderedRowByKey(
++ getWidgetForPaintable().collapsedRowKey);
++ if (row != null) {
++ getWidgetForPaintable().setRowFocus(row);
++ getWidgetForPaintable().focus();
++ }
++ }
++
++ int scrollPosition2 = widget.getScrollPosition();
++ if (scrollPosition != scrollPosition2) {
++ widget.setScrollPosition(scrollPosition);
++ }
++
++ // check which rows are needed from the server and initiate a
++ // deferred fetch
++ getWidgetForPaintable().onScroll(null);
++ }
++ // Recalculate table size if collapse request, or if page length is zero
++ // (not sent by server) and row count changes (#7908).
++ if (getWidgetForPaintable().collapseRequest
++ || (!uidl.hasAttribute("pagelength") && getWidgetForPaintable()
++ .getTotalRows() != oldTotalRows)) {
++ /*
++ * Ensure that possibly removed/added scrollbars are considered.
++ * Triggers row calculations, removes cached rows etc. Basically
++ * cleans up state. Be careful if touching this, you will break
++ * pageLength=0 if you remove this.
++ */
++ getWidgetForPaintable().triggerLazyColumnAdjustment(true);
++
++ getWidgetForPaintable().collapseRequest = false;
++ }
++ if (uidl.hasAttribute("focusedRow")) {
++ String key = uidl.getStringAttribute("focusedRow");
++ getWidgetForPaintable().setRowFocus(
++ getWidgetForPaintable().getRenderedRowByKey(key));
++ getWidgetForPaintable().focusParentResponsePending = false;
++ } else if (uidl.hasAttribute("clearFocusPending")) {
++ // Special case to detect a response to a focusParent request that
++ // does not return any focusedRow because the selected node has no
++ // parent
++ getWidgetForPaintable().focusParentResponsePending = false;
++ }
++
++ while (!getWidgetForPaintable().collapseRequest
++ && !getWidgetForPaintable().focusParentResponsePending
++ && !getWidgetForPaintable().pendingNavigationEvents.isEmpty()) {
++ // Keep replaying any queued events as long as we don't have any
++ // potential content changes pending
++ PendingNavigationEvent event = getWidgetForPaintable().pendingNavigationEvents
++ .removeFirst();
++ getWidgetForPaintable().handleNavigation(event.keycode, event.ctrl,
++ event.shift);
++ }
++ }
++
++ @Override
++ protected Widget createWidget() {
++ return GWT.create(VTreeTable.class);
++ }
++
++ @Override
++ public VTreeTable getWidgetForPaintable() {
++ return (VTreeTable) super.getWidgetForPaintable();
++ }
++}
--- /dev/null
- package com.vaadin.terminal.gwt.client.ui;\r
- \r
- import com.google.gwt.core.client.GWT;\r
- \r
- public class VVerticalLayoutPaintable extends VOrderedLayoutPaintable {\r
- \r
- @Override\r
- public VVerticalLayout getWidgetForPaintable() {\r
- return (VVerticalLayout) super.getWidgetForPaintable();\r
- }\r
- \r
- @Override\r
- protected VVerticalLayout createWidget() {\r
- return GWT.create(VVerticalLayout.class);\r
- }\r
- \r
- }\r
++package com.vaadin.terminal.gwt.client.ui;
++
++import com.google.gwt.core.client.GWT;
++
++public class VVerticalLayoutPaintable extends VOrderedLayoutPaintable {
++
++ @Override
++ public VVerticalLayout getWidgetForPaintable() {
++ return (VVerticalLayout) super.getWidgetForPaintable();
++ }
++
++ @Override
++ protected VVerticalLayout createWidget() {
++ return GWT.create(VVerticalLayout.class);
++ }
++
++}
--- /dev/null
- package com.vaadin.terminal.gwt.client.ui;\r
- \r
- import com.google.gwt.core.client.GWT;\r
- \r
- public class VVerticalSplitPanelPaintable extends VAbstractSplitPanelPaintable {\r
- \r
- @Override\r
- protected VAbstractSplitPanel createWidget() {\r
- return GWT.create(VSplitPanelVertical.class);\r
- }\r
- \r
- }\r
++package com.vaadin.terminal.gwt.client.ui;
++
++import com.google.gwt.core.client.GWT;
++
++public class VVerticalSplitPanelPaintable extends VAbstractSplitPanelPaintable {
++
++ @Override
++ protected VAbstractSplitPanel createWidget() {
++ return GWT.create(VSplitPanelVertical.class);
++ }
++
++}
--- /dev/null
- package com.vaadin.terminal.gwt.client.ui;\r
- \r
- import com.google.gwt.core.client.GWT;\r
- import com.google.gwt.user.client.ui.Widget;\r
- import com.vaadin.terminal.gwt.client.ApplicationConnection;\r
- import com.vaadin.terminal.gwt.client.UIDL;\r
- \r
- public class VVideoPaintable extends VMediaBasePaintable {\r
- public static final String ATTR_POSTER = "poster";\r
- \r
- @Override\r
- public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {\r
- if (client.updateComponent(this, uidl, true)) {\r
- return;\r
- }\r
- super.updateFromUIDL(uidl, client);\r
- setPosterFromUIDL(uidl);\r
- }\r
- \r
- private void setPosterFromUIDL(UIDL uidl) {\r
- if (uidl.hasAttribute(ATTR_POSTER)) {\r
- getWidgetForPaintable().setPoster(\r
- getConnection().translateVaadinUri(\r
- uidl.getStringAttribute(ATTR_POSTER)));\r
- }\r
- }\r
- \r
- @Override\r
- public VVideo getWidgetForPaintable() {\r
- return (VVideo) super.getWidgetForPaintable();\r
- }\r
- \r
- @Override\r
- protected Widget createWidget() {\r
- return GWT.create(VVideo.class);\r
- }\r
- \r
- }\r
++package com.vaadin.terminal.gwt.client.ui;
++
++import com.google.gwt.core.client.GWT;
++import com.google.gwt.user.client.ui.Widget;
++import com.vaadin.terminal.gwt.client.ApplicationConnection;
++import com.vaadin.terminal.gwt.client.UIDL;
++
++public class VVideoPaintable extends VMediaBasePaintable {
++ public static final String ATTR_POSTER = "poster";
++
++ @Override
++ public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {
++ if (client.updateComponent(this, uidl, true)) {
++ return;
++ }
++ super.updateFromUIDL(uidl, client);
++ setPosterFromUIDL(uidl);
++ }
++
++ private void setPosterFromUIDL(UIDL uidl) {
++ if (uidl.hasAttribute(ATTR_POSTER)) {
++ getWidgetForPaintable().setPoster(
++ getConnection().translateVaadinUri(
++ uidl.getStringAttribute(ATTR_POSTER)));
++ }
++ }
++
++ @Override
++ public VVideo getWidgetForPaintable() {
++ return (VVideo) super.getWidgetForPaintable();
++ }
++
++ @Override
++ protected Widget createWidget() {
++ return GWT.create(VVideo.class);
++ }
++
++}
--- /dev/null
- package com.vaadin.terminal.gwt.client.ui;\r
- \r
- import java.util.HashSet;\r
- import java.util.Iterator;\r
- \r
- import com.google.gwt.core.client.GWT;\r
- import com.google.gwt.core.client.Scheduler;\r
- import com.google.gwt.event.dom.client.DomEvent.Type;\r
- import com.google.gwt.event.shared.EventHandler;\r
- import com.google.gwt.event.shared.HandlerRegistration;\r
- import com.google.gwt.user.client.Command;\r
- import com.google.gwt.user.client.DOM;\r
- import com.google.gwt.user.client.Event;\r
- import com.google.gwt.user.client.History;\r
- import com.google.gwt.user.client.Window;\r
- import com.google.gwt.user.client.ui.RootPanel;\r
- import com.google.gwt.user.client.ui.Widget;\r
- import com.vaadin.terminal.gwt.client.ApplicationConnection;\r
- import com.vaadin.terminal.gwt.client.BrowserInfo;\r
- import com.vaadin.terminal.gwt.client.Focusable;\r
- import com.vaadin.terminal.gwt.client.UIDL;\r
- import com.vaadin.terminal.gwt.client.Util;\r
- import com.vaadin.terminal.gwt.client.VConsole;\r
- import com.vaadin.terminal.gwt.client.VPaintableMap;\r
- import com.vaadin.terminal.gwt.client.VPaintableWidget;\r
- \r
- public class VViewPaintable extends VAbstractPaintableWidgetContainer {\r
- \r
- private static final String CLICK_EVENT_IDENTIFIER = VPanelPaintable.CLICK_EVENT_IDENTIFIER;\r
- \r
- public void updateFromUIDL(final UIDL uidl, ApplicationConnection client) {\r
- getWidgetForPaintable().rendering = true;\r
- \r
- getWidgetForPaintable().id = uidl.getId();\r
- boolean firstPaint = getWidgetForPaintable().connection == null;\r
- getWidgetForPaintable().connection = client;\r
- \r
- getWidgetForPaintable().immediate = uidl.hasAttribute("immediate");\r
- getWidgetForPaintable().resizeLazy = uidl\r
- .hasAttribute(VView.RESIZE_LAZY);\r
- String newTheme = uidl.getStringAttribute("theme");\r
- if (getWidgetForPaintable().theme != null\r
- && !newTheme.equals(getWidgetForPaintable().theme)) {\r
- // Complete page refresh is needed due css can affect layout\r
- // calculations etc\r
- getWidgetForPaintable().reloadHostPage();\r
- } else {\r
- getWidgetForPaintable().theme = newTheme;\r
- }\r
- if (uidl.hasAttribute("style")) {\r
- getWidgetForPaintable().setStyleName(\r
- getWidgetForPaintable().getStylePrimaryName() + " "\r
- + uidl.getStringAttribute("style"));\r
- }\r
- \r
- clickEventHandler.handleEventHandlerRegistration(client);\r
- \r
- if (!getWidgetForPaintable().isEmbedded()\r
- && uidl.hasAttribute("caption")) {\r
- // only change window title if we're in charge of the whole page\r
- com.google.gwt.user.client.Window.setTitle(uidl\r
- .getStringAttribute("caption"));\r
- }\r
- \r
- // Process children\r
- int childIndex = 0;\r
- \r
- // Open URL:s\r
- boolean isClosed = false; // was this window closed?\r
- while (childIndex < uidl.getChildCount()\r
- && "open".equals(uidl.getChildUIDL(childIndex).getTag())) {\r
- final UIDL open = uidl.getChildUIDL(childIndex);\r
- final String url = client.translateVaadinUri(open\r
- .getStringAttribute("src"));\r
- final String target = open.getStringAttribute("name");\r
- if (target == null) {\r
- // source will be opened to this browser window, but we may have\r
- // to finish rendering this window in case this is a download\r
- // (and window stays open).\r
- Scheduler.get().scheduleDeferred(new Command() {\r
- public void execute() {\r
- VView.goTo(url);\r
- }\r
- });\r
- } else if ("_self".equals(target)) {\r
- // This window is closing (for sure). Only other opens are\r
- // relevant in this change. See #3558, #2144\r
- isClosed = true;\r
- VView.goTo(url);\r
- } else {\r
- String options;\r
- if (open.hasAttribute("border")) {\r
- if (open.getStringAttribute("border").equals("minimal")) {\r
- options = "menubar=yes,location=no,status=no";\r
- } else {\r
- options = "menubar=no,location=no,status=no";\r
- }\r
- \r
- } else {\r
- options = "resizable=yes,menubar=yes,toolbar=yes,directories=yes,location=yes,scrollbars=yes,status=yes";\r
- }\r
- \r
- if (open.hasAttribute("width")) {\r
- int w = open.getIntAttribute("width");\r
- options += ",width=" + w;\r
- }\r
- if (open.hasAttribute("height")) {\r
- int h = open.getIntAttribute("height");\r
- options += ",height=" + h;\r
- }\r
- \r
- Window.open(url, target, options);\r
- }\r
- childIndex++;\r
- }\r
- if (isClosed) {\r
- // don't render the content, something else will be opened to this\r
- // browser view\r
- getWidgetForPaintable().rendering = false;\r
- return;\r
- }\r
- \r
- // Draw this application level window\r
- UIDL childUidl = uidl.getChildUIDL(childIndex);\r
- final VPaintableWidget lo = client.getPaintable(childUidl);\r
- \r
- if (getWidgetForPaintable().layout != null) {\r
- if (getWidgetForPaintable().layout != lo) {\r
- // remove old\r
- client.unregisterPaintable(getWidgetForPaintable().layout);\r
- // add new\r
- getWidgetForPaintable().setWidget(lo.getWidgetForPaintable());\r
- getWidgetForPaintable().layout = lo;\r
- }\r
- } else {\r
- getWidgetForPaintable().setWidget(lo.getWidgetForPaintable());\r
- getWidgetForPaintable().layout = lo;\r
- }\r
- \r
- getWidgetForPaintable().layout.updateFromUIDL(childUidl, client);\r
- if (!childUidl.getBooleanAttribute("cached")) {\r
- getWidgetForPaintable().updateParentFrameSize();\r
- }\r
- \r
- // Save currently open subwindows to track which will need to be closed\r
- final HashSet<VWindow> removedSubWindows = new HashSet<VWindow>(\r
- getWidgetForPaintable().subWindows);\r
- \r
- // Handle other UIDL children\r
- while ((childUidl = uidl.getChildUIDL(++childIndex)) != null) {\r
- String tag = childUidl.getTag().intern();\r
- if (tag == "actions") {\r
- if (getWidgetForPaintable().actionHandler == null) {\r
- getWidgetForPaintable().actionHandler = new ShortcutActionHandler(\r
- getWidgetForPaintable().id, client);\r
- }\r
- getWidgetForPaintable().actionHandler\r
- .updateActionMap(childUidl);\r
- } else if (tag == "execJS") {\r
- String script = childUidl.getStringAttribute("script");\r
- VView.eval(script);\r
- } else if (tag == "notifications") {\r
- for (final Iterator<?> it = childUidl.getChildIterator(); it\r
- .hasNext();) {\r
- final UIDL notification = (UIDL) it.next();\r
- VNotification.showNotification(client, notification);\r
- }\r
- } else {\r
- // subwindows\r
- final VPaintableWidget w = client.getPaintable(childUidl);\r
- if (getWidgetForPaintable().subWindows.contains(w)) {\r
- removedSubWindows.remove(w);\r
- } else {\r
- getWidgetForPaintable().subWindows.add((VWindow) w);\r
- }\r
- w.updateFromUIDL(childUidl, client);\r
- }\r
- }\r
- \r
- // Close old windows which where not in UIDL anymore\r
- for (final Iterator<VWindow> rem = removedSubWindows.iterator(); rem\r
- .hasNext();) {\r
- final VWindow w = rem.next();\r
- client.unregisterPaintable(VPaintableMap.get(getConnection())\r
- .getPaintable(w));\r
- getWidgetForPaintable().subWindows.remove(w);\r
- w.hide();\r
- }\r
- \r
- if (uidl.hasAttribute("focused")) {\r
- // set focused component when render phase is finished\r
- Scheduler.get().scheduleDeferred(new Command() {\r
- public void execute() {\r
- VPaintableWidget paintable = (VPaintableWidget) uidl\r
- .getPaintableAttribute("focused", getConnection());\r
- \r
- final Widget toBeFocused = paintable\r
- .getWidgetForPaintable();\r
- /*\r
- * Two types of Widgets can be focused, either implementing\r
- * GWT HasFocus of a thinner Vaadin specific Focusable\r
- * interface.\r
- */\r
- if (toBeFocused instanceof com.google.gwt.user.client.ui.Focusable) {\r
- final com.google.gwt.user.client.ui.Focusable toBeFocusedWidget = (com.google.gwt.user.client.ui.Focusable) toBeFocused;\r
- toBeFocusedWidget.setFocus(true);\r
- } else if (toBeFocused instanceof Focusable) {\r
- ((Focusable) toBeFocused).focus();\r
- } else {\r
- VConsole.log("Could not focus component");\r
- }\r
- }\r
- });\r
- }\r
- \r
- // Add window listeners on first paint, to prevent premature\r
- // variablechanges\r
- if (firstPaint) {\r
- Window.addWindowClosingHandler(getWidgetForPaintable());\r
- Window.addResizeHandler(getWidgetForPaintable());\r
- }\r
- \r
- getWidgetForPaintable().onResize();\r
- \r
- // finally set scroll position from UIDL\r
- if (uidl.hasVariable("scrollTop")) {\r
- getWidgetForPaintable().scrollable = true;\r
- getWidgetForPaintable().scrollTop = uidl\r
- .getIntVariable("scrollTop");\r
- DOM.setElementPropertyInt(getWidgetForPaintable().getElement(),\r
- "scrollTop", getWidgetForPaintable().scrollTop);\r
- getWidgetForPaintable().scrollLeft = uidl\r
- .getIntVariable("scrollLeft");\r
- DOM.setElementPropertyInt(getWidgetForPaintable().getElement(),\r
- "scrollLeft", getWidgetForPaintable().scrollLeft);\r
- } else {\r
- getWidgetForPaintable().scrollable = false;\r
- }\r
- \r
- // Safari workaround must be run after scrollTop is updated as it sets\r
- // scrollTop using a deferred command.\r
- if (BrowserInfo.get().isSafari()) {\r
- Util.runWebkitOverflowAutoFix(getWidgetForPaintable().getElement());\r
- }\r
- \r
- getWidgetForPaintable().scrollIntoView(uidl);\r
- \r
- if (uidl.hasAttribute(VView.FRAGMENT_VARIABLE)) {\r
- getWidgetForPaintable().currentFragment = uidl\r
- .getStringAttribute(VView.FRAGMENT_VARIABLE);\r
- if (!getWidgetForPaintable().currentFragment.equals(History\r
- .getToken())) {\r
- History.newItem(getWidgetForPaintable().currentFragment, true);\r
- }\r
- } else {\r
- // Initial request for which the server doesn't yet have a fragment\r
- // (and haven't shown any interest in getting one)\r
- getWidgetForPaintable().currentFragment = History.getToken();\r
- \r
- // Include current fragment in the next request\r
- client.updateVariable(getWidgetForPaintable().id,\r
- VView.FRAGMENT_VARIABLE,\r
- getWidgetForPaintable().currentFragment, false);\r
- }\r
- \r
- getWidgetForPaintable().rendering = false;\r
- }\r
- \r
- public void init(String rootPanelId,\r
- ApplicationConnection applicationConnection) {\r
- DOM.sinkEvents(getWidgetForPaintable().getElement(), Event.ONKEYDOWN\r
- | Event.ONSCROLL);\r
- \r
- // iview is focused when created so element needs tabIndex\r
- // 1 due 0 is at the end of natural tabbing order\r
- DOM.setElementProperty(getWidgetForPaintable().getElement(),\r
- "tabIndex", "1");\r
- \r
- RootPanel root = RootPanel.get(rootPanelId);\r
- \r
- // Remove the v-app-loading or any splash screen added inside the div by\r
- // the user\r
- root.getElement().setInnerHTML("");\r
- // For backwards compatibility with static index pages only.\r
- // No longer added by AbstractApplicationServlet/Portlet\r
- root.removeStyleName("v-app-loading");\r
- \r
- String themeUri = applicationConnection.getConfiguration()\r
- .getThemeUri();\r
- String themeName = themeUri.substring(themeUri.lastIndexOf('/'));\r
- themeName = themeName.replaceAll("[^a-zA-Z0-9]", "");\r
- root.addStyleName("v-theme-" + themeName);\r
- \r
- root.add(getWidgetForPaintable());\r
- \r
- if (applicationConnection.getConfiguration().isStandalone()) {\r
- // set focus to iview element by default to listen possible keyboard\r
- // shortcuts. For embedded applications this is unacceptable as we\r
- // don't want to steal focus from the main page nor we don't want\r
- // side-effects from focusing (scrollIntoView).\r
- getWidgetForPaintable().getElement().focus();\r
- }\r
- \r
- getWidgetForPaintable().parentFrame = VView.getParentFrame();\r
- }\r
- \r
- private ClickEventHandler clickEventHandler = new ClickEventHandler(this,\r
- CLICK_EVENT_IDENTIFIER) {\r
- \r
- @Override\r
- protected <H extends EventHandler> HandlerRegistration registerHandler(\r
- H handler, Type<H> type) {\r
- return getWidgetForPaintable().addDomHandler(handler, type);\r
- }\r
- };\r
- \r
- public void updateCaption(VPaintableWidget component, UIDL uidl) {\r
- // NOP The main view never draws caption for its layout\r
- }\r
- \r
- @Override\r
- public VView getWidgetForPaintable() {\r
- return (VView) super.getWidgetForPaintable();\r
- }\r
- \r
- @Override\r
- protected Widget createWidget() {\r
- return GWT.create(VView.class);\r
- }\r
- \r
- }\r
++package com.vaadin.terminal.gwt.client.ui;
++
++import java.util.HashSet;
++import java.util.Iterator;
++
++import com.google.gwt.core.client.GWT;
++import com.google.gwt.core.client.Scheduler;
++import com.google.gwt.event.dom.client.DomEvent.Type;
++import com.google.gwt.event.shared.EventHandler;
++import com.google.gwt.event.shared.HandlerRegistration;
++import com.google.gwt.user.client.Command;
++import com.google.gwt.user.client.DOM;
++import com.google.gwt.user.client.Event;
++import com.google.gwt.user.client.History;
++import com.google.gwt.user.client.Window;
++import com.google.gwt.user.client.ui.RootPanel;
++import com.google.gwt.user.client.ui.Widget;
++import com.vaadin.terminal.gwt.client.ApplicationConnection;
++import com.vaadin.terminal.gwt.client.BrowserInfo;
++import com.vaadin.terminal.gwt.client.Focusable;
++import com.vaadin.terminal.gwt.client.UIDL;
++import com.vaadin.terminal.gwt.client.Util;
++import com.vaadin.terminal.gwt.client.VConsole;
++import com.vaadin.terminal.gwt.client.VPaintableMap;
++import com.vaadin.terminal.gwt.client.VPaintableWidget;
++
++public class VViewPaintable extends VAbstractPaintableWidgetContainer {
++
++ private static final String CLICK_EVENT_IDENTIFIER = VPanelPaintable.CLICK_EVENT_IDENTIFIER;
++
++ public void updateFromUIDL(final UIDL uidl, ApplicationConnection client) {
++ getWidgetForPaintable().rendering = true;
++
++ getWidgetForPaintable().id = uidl.getId();
++ boolean firstPaint = getWidgetForPaintable().connection == null;
++ getWidgetForPaintable().connection = client;
++
++ getWidgetForPaintable().immediate = uidl.hasAttribute("immediate");
++ getWidgetForPaintable().resizeLazy = uidl
++ .hasAttribute(VView.RESIZE_LAZY);
++ String newTheme = uidl.getStringAttribute("theme");
++ if (getWidgetForPaintable().theme != null
++ && !newTheme.equals(getWidgetForPaintable().theme)) {
++ // Complete page refresh is needed due css can affect layout
++ // calculations etc
++ getWidgetForPaintable().reloadHostPage();
++ } else {
++ getWidgetForPaintable().theme = newTheme;
++ }
++ if (uidl.hasAttribute("style")) {
++ getWidgetForPaintable().setStyleName(
++ getWidgetForPaintable().getStylePrimaryName() + " "
++ + uidl.getStringAttribute("style"));
++ }
++
++ clickEventHandler.handleEventHandlerRegistration(client);
++
++ if (!getWidgetForPaintable().isEmbedded()
++ && uidl.hasAttribute("caption")) {
++ // only change window title if we're in charge of the whole page
++ com.google.gwt.user.client.Window.setTitle(uidl
++ .getStringAttribute("caption"));
++ }
++
++ // Process children
++ int childIndex = 0;
++
++ // Open URL:s
++ boolean isClosed = false; // was this window closed?
++ while (childIndex < uidl.getChildCount()
++ && "open".equals(uidl.getChildUIDL(childIndex).getTag())) {
++ final UIDL open = uidl.getChildUIDL(childIndex);
++ final String url = client.translateVaadinUri(open
++ .getStringAttribute("src"));
++ final String target = open.getStringAttribute("name");
++ if (target == null) {
++ // source will be opened to this browser window, but we may have
++ // to finish rendering this window in case this is a download
++ // (and window stays open).
++ Scheduler.get().scheduleDeferred(new Command() {
++ public void execute() {
++ VView.goTo(url);
++ }
++ });
++ } else if ("_self".equals(target)) {
++ // This window is closing (for sure). Only other opens are
++ // relevant in this change. See #3558, #2144
++ isClosed = true;
++ VView.goTo(url);
++ } else {
++ String options;
++ if (open.hasAttribute("border")) {
++ if (open.getStringAttribute("border").equals("minimal")) {
++ options = "menubar=yes,location=no,status=no";
++ } else {
++ options = "menubar=no,location=no,status=no";
++ }
++
++ } else {
++ options = "resizable=yes,menubar=yes,toolbar=yes,directories=yes,location=yes,scrollbars=yes,status=yes";
++ }
++
++ if (open.hasAttribute("width")) {
++ int w = open.getIntAttribute("width");
++ options += ",width=" + w;
++ }
++ if (open.hasAttribute("height")) {
++ int h = open.getIntAttribute("height");
++ options += ",height=" + h;
++ }
++
++ Window.open(url, target, options);
++ }
++ childIndex++;
++ }
++ if (isClosed) {
++ // don't render the content, something else will be opened to this
++ // browser view
++ getWidgetForPaintable().rendering = false;
++ return;
++ }
++
++ // Draw this application level window
++ UIDL childUidl = uidl.getChildUIDL(childIndex);
++ final VPaintableWidget lo = client.getPaintable(childUidl);
++
++ if (getWidgetForPaintable().layout != null) {
++ if (getWidgetForPaintable().layout != lo) {
++ // remove old
++ client.unregisterPaintable(getWidgetForPaintable().layout);
++ // add new
++ getWidgetForPaintable().setWidget(lo.getWidgetForPaintable());
++ getWidgetForPaintable().layout = lo;
++ }
++ } else {
++ getWidgetForPaintable().setWidget(lo.getWidgetForPaintable());
++ getWidgetForPaintable().layout = lo;
++ }
++
++ getWidgetForPaintable().layout.updateFromUIDL(childUidl, client);
++ if (!childUidl.getBooleanAttribute("cached")) {
++ getWidgetForPaintable().updateParentFrameSize();
++ }
++
++ // Save currently open subwindows to track which will need to be closed
++ final HashSet<VWindow> removedSubWindows = new HashSet<VWindow>(
++ getWidgetForPaintable().subWindows);
++
++ // Handle other UIDL children
++ while ((childUidl = uidl.getChildUIDL(++childIndex)) != null) {
++ String tag = childUidl.getTag().intern();
++ if (tag == "actions") {
++ if (getWidgetForPaintable().actionHandler == null) {
++ getWidgetForPaintable().actionHandler = new ShortcutActionHandler(
++ getWidgetForPaintable().id, client);
++ }
++ getWidgetForPaintable().actionHandler
++ .updateActionMap(childUidl);
++ } else if (tag == "execJS") {
++ String script = childUidl.getStringAttribute("script");
++ VView.eval(script);
++ } else if (tag == "notifications") {
++ for (final Iterator<?> it = childUidl.getChildIterator(); it
++ .hasNext();) {
++ final UIDL notification = (UIDL) it.next();
++ VNotification.showNotification(client, notification);
++ }
++ } else {
++ // subwindows
++ final VPaintableWidget w = client.getPaintable(childUidl);
++ if (getWidgetForPaintable().subWindows.contains(w)) {
++ removedSubWindows.remove(w);
++ } else {
++ getWidgetForPaintable().subWindows.add((VWindow) w);
++ }
++ w.updateFromUIDL(childUidl, client);
++ }
++ }
++
++ // Close old windows which where not in UIDL anymore
++ for (final Iterator<VWindow> rem = removedSubWindows.iterator(); rem
++ .hasNext();) {
++ final VWindow w = rem.next();
++ client.unregisterPaintable(VPaintableMap.get(getConnection())
++ .getPaintable(w));
++ getWidgetForPaintable().subWindows.remove(w);
++ w.hide();
++ }
++
++ if (uidl.hasAttribute("focused")) {
++ // set focused component when render phase is finished
++ Scheduler.get().scheduleDeferred(new Command() {
++ public void execute() {
++ VPaintableWidget paintable = (VPaintableWidget) uidl
++ .getPaintableAttribute("focused", getConnection());
++
++ final Widget toBeFocused = paintable
++ .getWidgetForPaintable();
++ /*
++ * Two types of Widgets can be focused, either implementing
++ * GWT HasFocus of a thinner Vaadin specific Focusable
++ * interface.
++ */
++ if (toBeFocused instanceof com.google.gwt.user.client.ui.Focusable) {
++ final com.google.gwt.user.client.ui.Focusable toBeFocusedWidget = (com.google.gwt.user.client.ui.Focusable) toBeFocused;
++ toBeFocusedWidget.setFocus(true);
++ } else if (toBeFocused instanceof Focusable) {
++ ((Focusable) toBeFocused).focus();
++ } else {
++ VConsole.log("Could not focus component");
++ }
++ }
++ });
++ }
++
++ // Add window listeners on first paint, to prevent premature
++ // variablechanges
++ if (firstPaint) {
++ Window.addWindowClosingHandler(getWidgetForPaintable());
++ Window.addResizeHandler(getWidgetForPaintable());
++ }
++
++ getWidgetForPaintable().onResize();
++
++ // finally set scroll position from UIDL
++ if (uidl.hasVariable("scrollTop")) {
++ getWidgetForPaintable().scrollable = true;
++ getWidgetForPaintable().scrollTop = uidl
++ .getIntVariable("scrollTop");
++ DOM.setElementPropertyInt(getWidgetForPaintable().getElement(),
++ "scrollTop", getWidgetForPaintable().scrollTop);
++ getWidgetForPaintable().scrollLeft = uidl
++ .getIntVariable("scrollLeft");
++ DOM.setElementPropertyInt(getWidgetForPaintable().getElement(),
++ "scrollLeft", getWidgetForPaintable().scrollLeft);
++ } else {
++ getWidgetForPaintable().scrollable = false;
++ }
++
++ // Safari workaround must be run after scrollTop is updated as it sets
++ // scrollTop using a deferred command.
++ if (BrowserInfo.get().isSafari()) {
++ Util.runWebkitOverflowAutoFix(getWidgetForPaintable().getElement());
++ }
++
++ getWidgetForPaintable().scrollIntoView(uidl);
++
++ if (uidl.hasAttribute(VView.FRAGMENT_VARIABLE)) {
++ getWidgetForPaintable().currentFragment = uidl
++ .getStringAttribute(VView.FRAGMENT_VARIABLE);
++ if (!getWidgetForPaintable().currentFragment.equals(History
++ .getToken())) {
++ History.newItem(getWidgetForPaintable().currentFragment, true);
++ }
++ } else {
++ // Initial request for which the server doesn't yet have a fragment
++ // (and haven't shown any interest in getting one)
++ getWidgetForPaintable().currentFragment = History.getToken();
++
++ // Include current fragment in the next request
++ client.updateVariable(getWidgetForPaintable().id,
++ VView.FRAGMENT_VARIABLE,
++ getWidgetForPaintable().currentFragment, false);
++ }
++
++ getWidgetForPaintable().rendering = false;
++ }
++
++ public void init(String rootPanelId,
++ ApplicationConnection applicationConnection) {
++ DOM.sinkEvents(getWidgetForPaintable().getElement(), Event.ONKEYDOWN
++ | Event.ONSCROLL);
++
++ // iview is focused when created so element needs tabIndex
++ // 1 due 0 is at the end of natural tabbing order
++ DOM.setElementProperty(getWidgetForPaintable().getElement(),
++ "tabIndex", "1");
++
++ RootPanel root = RootPanel.get(rootPanelId);
++
++ // Remove the v-app-loading or any splash screen added inside the div by
++ // the user
++ root.getElement().setInnerHTML("");
++ // For backwards compatibility with static index pages only.
++ // No longer added by AbstractApplicationServlet/Portlet
++ root.removeStyleName("v-app-loading");
++
++ String themeUri = applicationConnection.getConfiguration()
++ .getThemeUri();
++ String themeName = themeUri.substring(themeUri.lastIndexOf('/'));
++ themeName = themeName.replaceAll("[^a-zA-Z0-9]", "");
++ root.addStyleName("v-theme-" + themeName);
++
++ root.add(getWidgetForPaintable());
++
++ if (applicationConnection.getConfiguration().isStandalone()) {
++ // set focus to iview element by default to listen possible keyboard
++ // shortcuts. For embedded applications this is unacceptable as we
++ // don't want to steal focus from the main page nor we don't want
++ // side-effects from focusing (scrollIntoView).
++ getWidgetForPaintable().getElement().focus();
++ }
++
++ getWidgetForPaintable().parentFrame = VView.getParentFrame();
++ }
++
++ private ClickEventHandler clickEventHandler = new ClickEventHandler(this,
++ CLICK_EVENT_IDENTIFIER) {
++
++ @Override
++ protected <H extends EventHandler> HandlerRegistration registerHandler(
++ H handler, Type<H> type) {
++ return getWidgetForPaintable().addDomHandler(handler, type);
++ }
++ };
++
++ public void updateCaption(VPaintableWidget component, UIDL uidl) {
++ // NOP The main view never draws caption for its layout
++ }
++
++ @Override
++ public VView getWidgetForPaintable() {
++ return (VView) super.getWidgetForPaintable();
++ }
++
++ @Override
++ protected Widget createWidget() {
++ return GWT.create(VView.class);
++ }
++
++}
--- /dev/null
- package com.vaadin.terminal.gwt.client.ui;\r
- \r
- import com.google.gwt.core.client.GWT;\r
- import com.google.gwt.event.dom.client.DomEvent.Type;\r
- import com.google.gwt.event.shared.EventHandler;\r
- import com.google.gwt.event.shared.HandlerRegistration;\r
- import com.google.gwt.user.client.DOM;\r
- import com.google.gwt.user.client.Event;\r
- import com.google.gwt.user.client.Window;\r
- import com.google.gwt.user.client.ui.Frame;\r
- import com.google.gwt.user.client.ui.Widget;\r
- import com.vaadin.terminal.gwt.client.ApplicationConnection;\r
- import com.vaadin.terminal.gwt.client.UIDL;\r
- import com.vaadin.terminal.gwt.client.Util;\r
- import com.vaadin.terminal.gwt.client.VPaintableWidget;\r
- import com.vaadin.terminal.gwt.client.ui.ShortcutActionHandler.BeforeShortcutActionListener;\r
- \r
- public class VWindowPaintable extends VAbstractPaintableWidgetContainer\r
- implements BeforeShortcutActionListener {\r
- \r
- private static final String CLICK_EVENT_IDENTIFIER = VPanelPaintable.CLICK_EVENT_IDENTIFIER;\r
- \r
- private ClickEventHandler clickEventHandler = new ClickEventHandler(this,\r
- CLICK_EVENT_IDENTIFIER) {\r
- \r
- @Override\r
- protected <H extends EventHandler> HandlerRegistration registerHandler(\r
- H handler, Type<H> type) {\r
- return getWidgetForPaintable().addDomHandler(handler, type);\r
- }\r
- };\r
- \r
- public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {\r
- getWidgetForPaintable().id = uidl.getId();\r
- getWidgetForPaintable().client = client;\r
- \r
- // Workaround needed for Testing Tools (GWT generates window DOM\r
- // slightly different in different browsers).\r
- DOM.setElementProperty(getWidgetForPaintable().closeBox, "id",\r
- getWidgetForPaintable().id + "_window_close");\r
- \r
- if (uidl.hasAttribute("invisible")) {\r
- getWidgetForPaintable().hide();\r
- return;\r
- }\r
- \r
- if (!uidl.hasAttribute("cached")) {\r
- if (uidl.getBooleanAttribute("modal") != getWidgetForPaintable().vaadinModality) {\r
- getWidgetForPaintable().setVaadinModality(\r
- !getWidgetForPaintable().vaadinModality);\r
- }\r
- if (!getWidgetForPaintable().isAttached()) {\r
- getWidgetForPaintable().setVisible(false); // hide until\r
- // possible centering\r
- getWidgetForPaintable().show();\r
- }\r
- if (uidl.getBooleanAttribute("resizable") != getWidgetForPaintable().resizable) {\r
- getWidgetForPaintable().setResizable(\r
- !getWidgetForPaintable().resizable);\r
- }\r
- getWidgetForPaintable().resizeLazy = uidl\r
- .hasAttribute(VView.RESIZE_LAZY);\r
- \r
- getWidgetForPaintable().setDraggable(\r
- !uidl.hasAttribute("fixedposition"));\r
- \r
- // Caption must be set before required header size is measured. If\r
- // the caption attribute is missing the caption should be cleared.\r
- getWidgetForPaintable().setCaption(\r
- uidl.getStringAttribute("caption"),\r
- uidl.getStringAttribute("icon"));\r
- }\r
- \r
- getWidgetForPaintable().visibilityChangesDisabled = true;\r
- if (client.updateComponent(this, uidl, false)) {\r
- return;\r
- }\r
- getWidgetForPaintable().visibilityChangesDisabled = false;\r
- \r
- clickEventHandler.handleEventHandlerRegistration(client);\r
- \r
- getWidgetForPaintable().immediate = uidl.hasAttribute("immediate");\r
- \r
- getWidgetForPaintable().setClosable(\r
- !uidl.getBooleanAttribute("readonly"));\r
- \r
- // Initialize the position form UIDL\r
- int positionx = uidl.getIntVariable("positionx");\r
- int positiony = uidl.getIntVariable("positiony");\r
- if (positionx >= 0 || positiony >= 0) {\r
- if (positionx < 0) {\r
- positionx = 0;\r
- }\r
- if (positiony < 0) {\r
- positiony = 0;\r
- }\r
- getWidgetForPaintable().setPopupPosition(positionx, positiony);\r
- }\r
- \r
- boolean showingUrl = false;\r
- int childIndex = 0;\r
- UIDL childUidl = uidl.getChildUIDL(childIndex++);\r
- while ("open".equals(childUidl.getTag())) {\r
- // TODO multiple opens with the same target will in practice just\r
- // open the last one - should we fix that somehow?\r
- final String parsedUri = client.translateVaadinUri(childUidl\r
- .getStringAttribute("src"));\r
- if (!childUidl.hasAttribute("name")) {\r
- final Frame frame = new Frame();\r
- DOM.setStyleAttribute(frame.getElement(), "width", "100%");\r
- DOM.setStyleAttribute(frame.getElement(), "height", "100%");\r
- DOM.setStyleAttribute(frame.getElement(), "border", "0px");\r
- frame.setUrl(parsedUri);\r
- getWidgetForPaintable().contentPanel.setWidget(frame);\r
- showingUrl = true;\r
- } else {\r
- final String target = childUidl.getStringAttribute("name");\r
- Window.open(parsedUri, target, "");\r
- }\r
- childUidl = uidl.getChildUIDL(childIndex++);\r
- }\r
- \r
- final VPaintableWidget lo = client.getPaintable(childUidl);\r
- if (getWidgetForPaintable().layout != null) {\r
- if (getWidgetForPaintable().layout != lo) {\r
- // remove old\r
- client.unregisterPaintable(getWidgetForPaintable().layout);\r
- getWidgetForPaintable().contentPanel\r
- .remove(getWidgetForPaintable().layout\r
- .getWidgetForPaintable());\r
- // add new\r
- if (!showingUrl) {\r
- getWidgetForPaintable().contentPanel.setWidget(lo\r
- .getWidgetForPaintable());\r
- }\r
- getWidgetForPaintable().layout = lo;\r
- }\r
- } else if (!showingUrl) {\r
- getWidgetForPaintable().contentPanel.setWidget(lo\r
- .getWidgetForPaintable());\r
- getWidgetForPaintable().layout = lo;\r
- }\r
- \r
- getWidgetForPaintable().dynamicWidth = !uidl.hasAttribute("width");\r
- getWidgetForPaintable().dynamicHeight = !uidl.hasAttribute("height");\r
- \r
- getWidgetForPaintable().layoutRelativeWidth = uidl\r
- .hasAttribute("layoutRelativeWidth");\r
- getWidgetForPaintable().layoutRelativeHeight = uidl\r
- .hasAttribute("layoutRelativeHeight");\r
- \r
- if (getWidgetForPaintable().dynamicWidth\r
- && getWidgetForPaintable().layoutRelativeWidth) {\r
- /*\r
- * Relative layout width, fix window width before rendering (width\r
- * according to caption)\r
- */\r
- getWidgetForPaintable().setNaturalWidth();\r
- }\r
- \r
- getWidgetForPaintable().layout.updateFromUIDL(childUidl, client);\r
- if (!getWidgetForPaintable().dynamicHeight\r
- && getWidgetForPaintable().layoutRelativeWidth) {\r
- /*\r
- * Relative layout width, and fixed height. Must update the size to\r
- * be able to take scrollbars into account (layout gets narrower\r
- * space if it is higher than the window) -> only vertical scrollbar\r
- */\r
- client.runDescendentsLayout(getWidgetForPaintable());\r
- }\r
- \r
- /*\r
- * No explicit width is set and the layout does not have relative width\r
- * so fix the size according to the layout.\r
- */\r
- if (getWidgetForPaintable().dynamicWidth\r
- && !getWidgetForPaintable().layoutRelativeWidth) {\r
- getWidgetForPaintable().setNaturalWidth();\r
- }\r
- \r
- if (getWidgetForPaintable().dynamicHeight\r
- && getWidgetForPaintable().layoutRelativeHeight) {\r
- // Prevent resizing until height has been fixed\r
- getWidgetForPaintable().resizable = false;\r
- }\r
- \r
- // we may have actions and notifications\r
- if (uidl.getChildCount() > 1) {\r
- final int cnt = uidl.getChildCount();\r
- for (int i = 1; i < cnt; i++) {\r
- childUidl = uidl.getChildUIDL(i);\r
- if (childUidl.getTag().equals("actions")) {\r
- if (getWidgetForPaintable().shortcutHandler == null) {\r
- getWidgetForPaintable().shortcutHandler = new ShortcutActionHandler(\r
- getId(), client);\r
- }\r
- getWidgetForPaintable().shortcutHandler\r
- .updateActionMap(childUidl);\r
- }\r
- }\r
- \r
- }\r
- \r
- // setting scrollposition must happen after children is rendered\r
- getWidgetForPaintable().contentPanel.setScrollPosition(uidl\r
- .getIntVariable("scrollTop"));\r
- getWidgetForPaintable().contentPanel.setHorizontalScrollPosition(uidl\r
- .getIntVariable("scrollLeft"));\r
- \r
- // Center this window on screen if requested\r
- // This has to be here because we might not know the content size before\r
- // everything is painted into the window\r
- if (uidl.getBooleanAttribute("center")) {\r
- // mark as centered - this is unset on move/resize\r
- getWidgetForPaintable().centered = true;\r
- getWidgetForPaintable().center();\r
- } else {\r
- // don't try to center the window anymore\r
- getWidgetForPaintable().centered = false;\r
- }\r
- getWidgetForPaintable().updateShadowSizeAndPosition();\r
- getWidgetForPaintable().setVisible(true);\r
- \r
- boolean sizeReduced = false;\r
- // ensure window is not larger than browser window\r
- if (getWidgetForPaintable().getOffsetWidth() > Window.getClientWidth()) {\r
- getWidgetForPaintable().setWidth(Window.getClientWidth() + "px");\r
- sizeReduced = true;\r
- }\r
- if (getWidgetForPaintable().getOffsetHeight() > Window\r
- .getClientHeight()) {\r
- getWidgetForPaintable().setHeight(Window.getClientHeight() + "px");\r
- sizeReduced = true;\r
- }\r
- \r
- if (getWidgetForPaintable().dynamicHeight\r
- && getWidgetForPaintable().layoutRelativeHeight) {\r
- /*\r
- * Window height is undefined, layout is 100% high so the layout\r
- * should define the initial window height but on resize the layout\r
- * should be as high as the window. We fix the height to deal with\r
- * this.\r
- */\r
- \r
- int h = getWidgetForPaintable().contents.getOffsetHeight()\r
- + getWidgetForPaintable().getExtraHeight();\r
- int w = getWidgetForPaintable().getElement().getOffsetWidth();\r
- \r
- client.updateVariable(getId(), "height", h, false);\r
- client.updateVariable(getId(), "width", w, true);\r
- }\r
- \r
- if (sizeReduced) {\r
- // If we changed the size we need to update the size of the child\r
- // component if it is relative (#3407)\r
- client.runDescendentsLayout(getWidgetForPaintable());\r
- }\r
- \r
- Util.runWebkitOverflowAutoFix(getWidgetForPaintable().contentPanel\r
- .getElement());\r
- \r
- client.getView().getWidgetForPaintable().scrollIntoView(uidl);\r
- \r
- if (uidl.hasAttribute("bringToFront")) {\r
- /*\r
- * Focus as a side-efect. Will be overridden by\r
- * ApplicationConnection if another component was focused by the\r
- * server side.\r
- */\r
- getWidgetForPaintable().contentPanel.focus();\r
- getWidgetForPaintable().bringToFrontSequence = uidl\r
- .getIntAttribute("bringToFront");\r
- VWindow.deferOrdering();\r
- }\r
- }\r
- \r
- public void updateCaption(VPaintableWidget component, UIDL uidl) {\r
- // NOP, window has own caption, layout captio not rendered\r
- }\r
- \r
- public void onBeforeShortcutAction(Event e) {\r
- // NOP, nothing to update just avoid workaround ( causes excess\r
- // blur/focus )\r
- }\r
- \r
- @Override\r
- public VWindow getWidgetForPaintable() {\r
- return (VWindow) super.getWidgetForPaintable();\r
- }\r
- \r
- @Override\r
- protected Widget createWidget() {\r
- return GWT.create(VWindow.class);\r
- }\r
- \r
- }\r
++package com.vaadin.terminal.gwt.client.ui;
++
++import com.google.gwt.core.client.GWT;
++import com.google.gwt.event.dom.client.DomEvent.Type;
++import com.google.gwt.event.shared.EventHandler;
++import com.google.gwt.event.shared.HandlerRegistration;
++import com.google.gwt.user.client.DOM;
++import com.google.gwt.user.client.Event;
++import com.google.gwt.user.client.Window;
++import com.google.gwt.user.client.ui.Frame;
++import com.google.gwt.user.client.ui.Widget;
++import com.vaadin.terminal.gwt.client.ApplicationConnection;
++import com.vaadin.terminal.gwt.client.UIDL;
++import com.vaadin.terminal.gwt.client.Util;
++import com.vaadin.terminal.gwt.client.VPaintableWidget;
++import com.vaadin.terminal.gwt.client.ui.ShortcutActionHandler.BeforeShortcutActionListener;
++
++public class VWindowPaintable extends VAbstractPaintableWidgetContainer
++ implements BeforeShortcutActionListener {
++
++ private static final String CLICK_EVENT_IDENTIFIER = VPanelPaintable.CLICK_EVENT_IDENTIFIER;
++
++ private ClickEventHandler clickEventHandler = new ClickEventHandler(this,
++ CLICK_EVENT_IDENTIFIER) {
++
++ @Override
++ protected <H extends EventHandler> HandlerRegistration registerHandler(
++ H handler, Type<H> type) {
++ return getWidgetForPaintable().addDomHandler(handler, type);
++ }
++ };
++
++ public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {
++ getWidgetForPaintable().id = uidl.getId();
++ getWidgetForPaintable().client = client;
++
++ // Workaround needed for Testing Tools (GWT generates window DOM
++ // slightly different in different browsers).
++ DOM.setElementProperty(getWidgetForPaintable().closeBox, "id",
++ getWidgetForPaintable().id + "_window_close");
++
++ if (uidl.hasAttribute("invisible")) {
++ getWidgetForPaintable().hide();
++ return;
++ }
++
++ if (!uidl.hasAttribute("cached")) {
++ if (uidl.getBooleanAttribute("modal") != getWidgetForPaintable().vaadinModality) {
++ getWidgetForPaintable().setVaadinModality(
++ !getWidgetForPaintable().vaadinModality);
++ }
++ if (!getWidgetForPaintable().isAttached()) {
++ getWidgetForPaintable().setVisible(false); // hide until
++ // possible centering
++ getWidgetForPaintable().show();
++ }
++ if (uidl.getBooleanAttribute("resizable") != getWidgetForPaintable().resizable) {
++ getWidgetForPaintable().setResizable(
++ !getWidgetForPaintable().resizable);
++ }
++ getWidgetForPaintable().resizeLazy = uidl
++ .hasAttribute(VView.RESIZE_LAZY);
++
++ getWidgetForPaintable().setDraggable(
++ !uidl.hasAttribute("fixedposition"));
++
++ // Caption must be set before required header size is measured. If
++ // the caption attribute is missing the caption should be cleared.
++ getWidgetForPaintable().setCaption(
++ uidl.getStringAttribute("caption"),
++ uidl.getStringAttribute("icon"));
++ }
++
++ getWidgetForPaintable().visibilityChangesDisabled = true;
++ if (client.updateComponent(this, uidl, false)) {
++ return;
++ }
++ getWidgetForPaintable().visibilityChangesDisabled = false;
++
++ clickEventHandler.handleEventHandlerRegistration(client);
++
++ getWidgetForPaintable().immediate = uidl.hasAttribute("immediate");
++
++ getWidgetForPaintable().setClosable(
++ !uidl.getBooleanAttribute("readonly"));
++
++ // Initialize the position form UIDL
++ int positionx = uidl.getIntVariable("positionx");
++ int positiony = uidl.getIntVariable("positiony");
++ if (positionx >= 0 || positiony >= 0) {
++ if (positionx < 0) {
++ positionx = 0;
++ }
++ if (positiony < 0) {
++ positiony = 0;
++ }
++ getWidgetForPaintable().setPopupPosition(positionx, positiony);
++ }
++
++ boolean showingUrl = false;
++ int childIndex = 0;
++ UIDL childUidl = uidl.getChildUIDL(childIndex++);
++ while ("open".equals(childUidl.getTag())) {
++ // TODO multiple opens with the same target will in practice just
++ // open the last one - should we fix that somehow?
++ final String parsedUri = client.translateVaadinUri(childUidl
++ .getStringAttribute("src"));
++ if (!childUidl.hasAttribute("name")) {
++ final Frame frame = new Frame();
++ DOM.setStyleAttribute(frame.getElement(), "width", "100%");
++ DOM.setStyleAttribute(frame.getElement(), "height", "100%");
++ DOM.setStyleAttribute(frame.getElement(), "border", "0px");
++ frame.setUrl(parsedUri);
++ getWidgetForPaintable().contentPanel.setWidget(frame);
++ showingUrl = true;
++ } else {
++ final String target = childUidl.getStringAttribute("name");
++ Window.open(parsedUri, target, "");
++ }
++ childUidl = uidl.getChildUIDL(childIndex++);
++ }
++
++ final VPaintableWidget lo = client.getPaintable(childUidl);
++ if (getWidgetForPaintable().layout != null) {
++ if (getWidgetForPaintable().layout != lo) {
++ // remove old
++ client.unregisterPaintable(getWidgetForPaintable().layout);
++ getWidgetForPaintable().contentPanel
++ .remove(getWidgetForPaintable().layout
++ .getWidgetForPaintable());
++ // add new
++ if (!showingUrl) {
++ getWidgetForPaintable().contentPanel.setWidget(lo
++ .getWidgetForPaintable());
++ }
++ getWidgetForPaintable().layout = lo;
++ }
++ } else if (!showingUrl) {
++ getWidgetForPaintable().contentPanel.setWidget(lo
++ .getWidgetForPaintable());
++ getWidgetForPaintable().layout = lo;
++ }
++
++ getWidgetForPaintable().dynamicWidth = !uidl.hasAttribute("width");
++ getWidgetForPaintable().dynamicHeight = !uidl.hasAttribute("height");
++
++ getWidgetForPaintable().layoutRelativeWidth = uidl
++ .hasAttribute("layoutRelativeWidth");
++ getWidgetForPaintable().layoutRelativeHeight = uidl
++ .hasAttribute("layoutRelativeHeight");
++
++ if (getWidgetForPaintable().dynamicWidth
++ && getWidgetForPaintable().layoutRelativeWidth) {
++ /*
++ * Relative layout width, fix window width before rendering (width
++ * according to caption)
++ */
++ getWidgetForPaintable().setNaturalWidth();
++ }
++
++ getWidgetForPaintable().layout.updateFromUIDL(childUidl, client);
++ if (!getWidgetForPaintable().dynamicHeight
++ && getWidgetForPaintable().layoutRelativeWidth) {
++ /*
++ * Relative layout width, and fixed height. Must update the size to
++ * be able to take scrollbars into account (layout gets narrower
++ * space if it is higher than the window) -> only vertical scrollbar
++ */
++ client.runDescendentsLayout(getWidgetForPaintable());
++ }
++
++ /*
++ * No explicit width is set and the layout does not have relative width
++ * so fix the size according to the layout.
++ */
++ if (getWidgetForPaintable().dynamicWidth
++ && !getWidgetForPaintable().layoutRelativeWidth) {
++ getWidgetForPaintable().setNaturalWidth();
++ }
++
++ if (getWidgetForPaintable().dynamicHeight
++ && getWidgetForPaintable().layoutRelativeHeight) {
++ // Prevent resizing until height has been fixed
++ getWidgetForPaintable().resizable = false;
++ }
++
++ // we may have actions and notifications
++ if (uidl.getChildCount() > 1) {
++ final int cnt = uidl.getChildCount();
++ for (int i = 1; i < cnt; i++) {
++ childUidl = uidl.getChildUIDL(i);
++ if (childUidl.getTag().equals("actions")) {
++ if (getWidgetForPaintable().shortcutHandler == null) {
++ getWidgetForPaintable().shortcutHandler = new ShortcutActionHandler(
++ getId(), client);
++ }
++ getWidgetForPaintable().shortcutHandler
++ .updateActionMap(childUidl);
++ }
++ }
++
++ }
++
++ // setting scrollposition must happen after children is rendered
++ getWidgetForPaintable().contentPanel.setScrollPosition(uidl
++ .getIntVariable("scrollTop"));
++ getWidgetForPaintable().contentPanel.setHorizontalScrollPosition(uidl
++ .getIntVariable("scrollLeft"));
++
++ // Center this window on screen if requested
++ // This has to be here because we might not know the content size before
++ // everything is painted into the window
++ if (uidl.getBooleanAttribute("center")) {
++ // mark as centered - this is unset on move/resize
++ getWidgetForPaintable().centered = true;
++ getWidgetForPaintable().center();
++ } else {
++ // don't try to center the window anymore
++ getWidgetForPaintable().centered = false;
++ }
++ getWidgetForPaintable().updateShadowSizeAndPosition();
++ getWidgetForPaintable().setVisible(true);
++
++ boolean sizeReduced = false;
++ // ensure window is not larger than browser window
++ if (getWidgetForPaintable().getOffsetWidth() > Window.getClientWidth()) {
++ getWidgetForPaintable().setWidth(Window.getClientWidth() + "px");
++ sizeReduced = true;
++ }
++ if (getWidgetForPaintable().getOffsetHeight() > Window
++ .getClientHeight()) {
++ getWidgetForPaintable().setHeight(Window.getClientHeight() + "px");
++ sizeReduced = true;
++ }
++
++ if (getWidgetForPaintable().dynamicHeight
++ && getWidgetForPaintable().layoutRelativeHeight) {
++ /*
++ * Window height is undefined, layout is 100% high so the layout
++ * should define the initial window height but on resize the layout
++ * should be as high as the window. We fix the height to deal with
++ * this.
++ */
++
++ int h = getWidgetForPaintable().contents.getOffsetHeight()
++ + getWidgetForPaintable().getExtraHeight();
++ int w = getWidgetForPaintable().getElement().getOffsetWidth();
++
++ client.updateVariable(getId(), "height", h, false);
++ client.updateVariable(getId(), "width", w, true);
++ }
++
++ if (sizeReduced) {
++ // If we changed the size we need to update the size of the child
++ // component if it is relative (#3407)
++ client.runDescendentsLayout(getWidgetForPaintable());
++ }
++
++ Util.runWebkitOverflowAutoFix(getWidgetForPaintable().contentPanel
++ .getElement());
++
++ client.getView().getWidgetForPaintable().scrollIntoView(uidl);
++
++ if (uidl.hasAttribute("bringToFront")) {
++ /*
++ * Focus as a side-efect. Will be overridden by
++ * ApplicationConnection if another component was focused by the
++ * server side.
++ */
++ getWidgetForPaintable().contentPanel.focus();
++ getWidgetForPaintable().bringToFrontSequence = uidl
++ .getIntAttribute("bringToFront");
++ VWindow.deferOrdering();
++ }
++ }
++
++ public void updateCaption(VPaintableWidget component, UIDL uidl) {
++ // NOP, window has own caption, layout captio not rendered
++ }
++
++ public void onBeforeShortcutAction(Event e) {
++ // NOP, nothing to update just avoid workaround ( causes excess
++ // blur/focus )
++ }
++
++ @Override
++ public VWindow getWidgetForPaintable() {
++ return (VWindow) super.getWidgetForPaintable();
++ }
++
++ @Override
++ protected Widget createWidget() {
++ return GWT.create(VWindow.class);
++ }
++
++}
--- /dev/null
- /*\r
- @VaadinApache2LicenseForJavaFiles@\r
- */\r
- package com.vaadin.terminal.gwt.client.ui.label;\r
- \r
- import com.google.gwt.core.client.GWT;\r
- import com.google.gwt.dom.client.Document;\r
- import com.google.gwt.dom.client.PreElement;\r
- import com.google.gwt.user.client.ui.Widget;\r
- import com.vaadin.terminal.gwt.client.ApplicationConnection;\r
- import com.vaadin.terminal.gwt.client.UIDL;\r
- import com.vaadin.terminal.gwt.client.Util;\r
- import com.vaadin.terminal.gwt.client.ui.VAbstractPaintableWidget;\r
- \r
- public class VLabelPaintable extends VAbstractPaintableWidget {\r
- public VLabelPaintable() {\r
- }\r
- \r
- public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {\r
- if (client.updateComponent(this, uidl, true)) {\r
- return;\r
- }\r
- \r
- boolean sinkOnloads = false;\r
- \r
- final String mode = uidl.getStringAttribute("mode");\r
- if (mode == null || "text".equals(mode)) {\r
- getWidgetForPaintable().setText(uidl.getChildString(0));\r
- } else if ("pre".equals(mode)) {\r
- PreElement preElement = Document.get().createPreElement();\r
- preElement.setInnerText(uidl.getChildUIDL(0).getChildString(0));\r
- // clear existing content\r
- getWidgetForPaintable().setHTML("");\r
- // add preformatted text to dom\r
- getWidgetForPaintable().getElement().appendChild(preElement);\r
- } else if ("uidl".equals(mode)) {\r
- getWidgetForPaintable().setHTML(uidl.getChildrenAsXML());\r
- } else if ("xhtml".equals(mode)) {\r
- UIDL content = uidl.getChildUIDL(0).getChildUIDL(0);\r
- if (content.getChildCount() > 0) {\r
- getWidgetForPaintable().setHTML(content.getChildString(0));\r
- } else {\r
- getWidgetForPaintable().setHTML("");\r
- }\r
- sinkOnloads = true;\r
- } else if ("xml".equals(mode)) {\r
- getWidgetForPaintable().setHTML(\r
- uidl.getChildUIDL(0).getChildString(0));\r
- } else if ("raw".equals(mode)) {\r
- getWidgetForPaintable().setHTML(\r
- uidl.getChildUIDL(0).getChildString(0));\r
- sinkOnloads = true;\r
- } else {\r
- getWidgetForPaintable().setText("");\r
- }\r
- if (sinkOnloads) {\r
- Util.sinkOnloadForImages(getWidgetForPaintable().getElement());\r
- }\r
- }\r
- \r
- @Override\r
- protected Widget createWidget() {\r
- return GWT.create(VLabel.class);\r
- }\r
- \r
- @Override\r
- public VLabel getWidgetForPaintable() {\r
- return (VLabel) super.getWidgetForPaintable();\r
- }\r
- \r
- }\r
++/*
++@VaadinApache2LicenseForJavaFiles@
++ */
++package com.vaadin.terminal.gwt.client.ui.label;
++
++import com.google.gwt.core.client.GWT;
++import com.google.gwt.dom.client.Document;
++import com.google.gwt.dom.client.PreElement;
++import com.google.gwt.user.client.ui.Widget;
++import com.vaadin.terminal.gwt.client.ApplicationConnection;
++import com.vaadin.terminal.gwt.client.UIDL;
++import com.vaadin.terminal.gwt.client.Util;
++import com.vaadin.terminal.gwt.client.ui.VAbstractPaintableWidget;
++
++public class VLabelPaintable extends VAbstractPaintableWidget {
++ public VLabelPaintable() {
++ }
++
++ public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {
++ if (client.updateComponent(this, uidl, true)) {
++ return;
++ }
++
++ boolean sinkOnloads = false;
++
++ final String mode = uidl.getStringAttribute("mode");
++ if (mode == null || "text".equals(mode)) {
++ getWidgetForPaintable().setText(uidl.getChildString(0));
++ } else if ("pre".equals(mode)) {
++ PreElement preElement = Document.get().createPreElement();
++ preElement.setInnerText(uidl.getChildUIDL(0).getChildString(0));
++ // clear existing content
++ getWidgetForPaintable().setHTML("");
++ // add preformatted text to dom
++ getWidgetForPaintable().getElement().appendChild(preElement);
++ } else if ("uidl".equals(mode)) {
++ getWidgetForPaintable().setHTML(uidl.getChildrenAsXML());
++ } else if ("xhtml".equals(mode)) {
++ UIDL content = uidl.getChildUIDL(0).getChildUIDL(0);
++ if (content.getChildCount() > 0) {
++ getWidgetForPaintable().setHTML(content.getChildString(0));
++ } else {
++ getWidgetForPaintable().setHTML("");
++ }
++ sinkOnloads = true;
++ } else if ("xml".equals(mode)) {
++ getWidgetForPaintable().setHTML(
++ uidl.getChildUIDL(0).getChildString(0));
++ } else if ("raw".equals(mode)) {
++ getWidgetForPaintable().setHTML(
++ uidl.getChildUIDL(0).getChildString(0));
++ sinkOnloads = true;
++ } else {
++ getWidgetForPaintable().setText("");
++ }
++ if (sinkOnloads) {
++ Util.sinkOnloadForImages(getWidgetForPaintable().getElement());
++ }
++ }
++
++ @Override
++ protected Widget createWidget() {
++ return GWT.create(VLabel.class);
++ }
++
++ @Override
++ public VLabel getWidgetForPaintable() {
++ return (VLabel) super.getWidgetForPaintable();
++ }
++
++}
--- /dev/null
- package com.vaadin.terminal.gwt.client.ui.layout;\r
- \r
- import com.vaadin.terminal.gwt.client.ApplicationConnection;\r
- import com.vaadin.terminal.gwt.client.UIDL;\r
- import com.vaadin.terminal.gwt.client.ui.VAbstractPaintableWidgetContainer;\r
- import com.vaadin.terminal.gwt.client.ui.VMarginInfo;\r
- \r
- public abstract class CellBasedLayoutPaintable extends\r
- VAbstractPaintableWidgetContainer {\r
- \r
- public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {\r
- getWidgetForPaintable().client = client;\r
- \r
- // Only non-cached UIDL:s can introduce changes\r
- if (uidl.getBooleanAttribute("cached")) {\r
- return;\r
- }\r
- \r
- /**\r
- * Margin and spacind detection depends on classNames and must be set\r
- * before setting size. Here just update the details from UIDL and from\r
- * overridden setStyleName run actual margin detections.\r
- */\r
- updateMarginAndSpacingInfo(uidl);\r
- \r
- /*\r
- * This call should be made first. Ensure correct implementation, handle\r
- * size etc.\r
- */\r
- if (client.updateComponent(this, uidl, true)) {\r
- return;\r
- }\r
- \r
- handleDynamicDimensions(uidl);\r
- }\r
- \r
- private void handleDynamicDimensions(UIDL uidl) {\r
- String w = uidl.hasAttribute("width") ? uidl\r
- .getStringAttribute("width") : "";\r
- \r
- String h = uidl.hasAttribute("height") ? uidl\r
- .getStringAttribute("height") : "";\r
- \r
- if (w.equals("")) {\r
- getWidgetForPaintable().dynamicWidth = true;\r
- } else {\r
- getWidgetForPaintable().dynamicWidth = false;\r
- }\r
- \r
- if (h.equals("")) {\r
- getWidgetForPaintable().dynamicHeight = true;\r
- } else {\r
- getWidgetForPaintable().dynamicHeight = false;\r
- }\r
- \r
- }\r
- \r
- void updateMarginAndSpacingInfo(UIDL uidl) {\r
- if (!uidl.hasAttribute("invisible")) {\r
- int bitMask = uidl.getIntAttribute("margins");\r
- if (getWidgetForPaintable().activeMarginsInfo.getBitMask() != bitMask) {\r
- getWidgetForPaintable().activeMarginsInfo = new VMarginInfo(\r
- bitMask);\r
- getWidgetForPaintable().marginsNeedsRecalculation = true;\r
- }\r
- boolean spacing = uidl.getBooleanAttribute("spacing");\r
- if (spacing != getWidgetForPaintable().spacingEnabled) {\r
- getWidgetForPaintable().marginsNeedsRecalculation = true;\r
- getWidgetForPaintable().spacingEnabled = spacing;\r
- }\r
- }\r
- }\r
- \r
- @Override\r
- protected abstract CellBasedLayout createWidget();\r
- \r
- @Override\r
- public CellBasedLayout getWidgetForPaintable() {\r
- return (CellBasedLayout) super.getWidgetForPaintable();\r
- }\r
- }\r
++package com.vaadin.terminal.gwt.client.ui.layout;
++
++import com.vaadin.terminal.gwt.client.ApplicationConnection;
++import com.vaadin.terminal.gwt.client.UIDL;
++import com.vaadin.terminal.gwt.client.ui.VAbstractPaintableWidgetContainer;
++import com.vaadin.terminal.gwt.client.ui.VMarginInfo;
++
++public abstract class CellBasedLayoutPaintable extends
++ VAbstractPaintableWidgetContainer {
++
++ public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {
++ getWidgetForPaintable().client = client;
++
++ // Only non-cached UIDL:s can introduce changes
++ if (uidl.getBooleanAttribute("cached")) {
++ return;
++ }
++
++ /**
++ * Margin and spacind detection depends on classNames and must be set
++ * before setting size. Here just update the details from UIDL and from
++ * overridden setStyleName run actual margin detections.
++ */
++ updateMarginAndSpacingInfo(uidl);
++
++ /*
++ * This call should be made first. Ensure correct implementation, handle
++ * size etc.
++ */
++ if (client.updateComponent(this, uidl, true)) {
++ return;
++ }
++
++ handleDynamicDimensions(uidl);
++ }
++
++ private void handleDynamicDimensions(UIDL uidl) {
++ String w = uidl.hasAttribute("width") ? uidl
++ .getStringAttribute("width") : "";
++
++ String h = uidl.hasAttribute("height") ? uidl
++ .getStringAttribute("height") : "";
++
++ if (w.equals("")) {
++ getWidgetForPaintable().dynamicWidth = true;
++ } else {
++ getWidgetForPaintable().dynamicWidth = false;
++ }
++
++ if (h.equals("")) {
++ getWidgetForPaintable().dynamicHeight = true;
++ } else {
++ getWidgetForPaintable().dynamicHeight = false;
++ }
++
++ }
++
++ void updateMarginAndSpacingInfo(UIDL uidl) {
++ if (!uidl.hasAttribute("invisible")) {
++ int bitMask = uidl.getIntAttribute("margins");
++ if (getWidgetForPaintable().activeMarginsInfo.getBitMask() != bitMask) {
++ getWidgetForPaintable().activeMarginsInfo = new VMarginInfo(
++ bitMask);
++ getWidgetForPaintable().marginsNeedsRecalculation = true;
++ }
++ boolean spacing = uidl.getBooleanAttribute("spacing");
++ if (spacing != getWidgetForPaintable().spacingEnabled) {
++ getWidgetForPaintable().marginsNeedsRecalculation = true;
++ getWidgetForPaintable().spacingEnabled = spacing;
++ }
++ }
++ }
++
++ @Override
++ protected abstract CellBasedLayout createWidget();
++
++ @Override
++ public CellBasedLayout getWidgetForPaintable() {
++ return (CellBasedLayout) super.getWidgetForPaintable();
++ }
++}
--- /dev/null
- package com.vaadin.terminal.gwt.client.ui.richtextarea;\r
- \r
- import com.google.gwt.core.client.GWT;\r
- import com.google.gwt.user.client.Event;\r
- import com.google.gwt.user.client.ui.Widget;\r
- import com.vaadin.terminal.gwt.client.ApplicationConnection;\r
- import com.vaadin.terminal.gwt.client.UIDL;\r
- import com.vaadin.terminal.gwt.client.ui.ShortcutActionHandler.BeforeShortcutActionListener;\r
- import com.vaadin.terminal.gwt.client.ui.VAbstractPaintableWidget;\r
- \r
- public class VRichTextAreaPaintable extends VAbstractPaintableWidget implements\r
- BeforeShortcutActionListener {\r
- \r
- public void updateFromUIDL(final UIDL uidl, ApplicationConnection client) {\r
- getWidgetForPaintable().client = client;\r
- getWidgetForPaintable().id = uidl.getId();\r
- \r
- if (uidl.hasVariable("text")) {\r
- getWidgetForPaintable().currentValue = uidl\r
- .getStringVariable("text");\r
- if (getWidgetForPaintable().rta.isAttached()) {\r
- getWidgetForPaintable().rta\r
- .setHTML(getWidgetForPaintable().currentValue);\r
- } else {\r
- getWidgetForPaintable().html\r
- .setHTML(getWidgetForPaintable().currentValue);\r
- }\r
- }\r
- if (!uidl.hasAttribute("cached")) {\r
- getWidgetForPaintable().setEnabled(\r
- !uidl.getBooleanAttribute("disabled"));\r
- }\r
- \r
- if (client.updateComponent(this, uidl, true)) {\r
- return;\r
- }\r
- \r
- getWidgetForPaintable().setReadOnly(\r
- uidl.getBooleanAttribute("readonly"));\r
- getWidgetForPaintable().immediate = uidl\r
- .getBooleanAttribute("immediate");\r
- int newMaxLength = uidl.hasAttribute("maxLength") ? uidl\r
- .getIntAttribute("maxLength") : -1;\r
- if (newMaxLength >= 0) {\r
- if (getWidgetForPaintable().maxLength == -1) {\r
- getWidgetForPaintable().keyPressHandler = getWidgetForPaintable().rta\r
- .addKeyPressHandler(getWidgetForPaintable());\r
- }\r
- getWidgetForPaintable().maxLength = newMaxLength;\r
- } else if (getWidgetForPaintable().maxLength != -1) {\r
- getWidgetForPaintable().getElement().setAttribute("maxlength", "");\r
- getWidgetForPaintable().maxLength = -1;\r
- getWidgetForPaintable().keyPressHandler.removeHandler();\r
- }\r
- \r
- if (uidl.hasAttribute("selectAll")) {\r
- getWidgetForPaintable().selectAll();\r
- }\r
- \r
- }\r
- \r
- public void onBeforeShortcutAction(Event e) {\r
- getWidgetForPaintable().synchronizeContentToServer();\r
- }\r
- \r
- @Override\r
- public VRichTextArea getWidgetForPaintable() {\r
- return (VRichTextArea) super.getWidgetForPaintable();\r
- };\r
- \r
- @Override\r
- protected Widget createWidget() {\r
- return GWT.create(VRichTextArea.class);\r
- }\r
- \r
- }\r
++package com.vaadin.terminal.gwt.client.ui.richtextarea;
++
++import com.google.gwt.core.client.GWT;
++import com.google.gwt.user.client.Event;
++import com.google.gwt.user.client.ui.Widget;
++import com.vaadin.terminal.gwt.client.ApplicationConnection;
++import com.vaadin.terminal.gwt.client.UIDL;
++import com.vaadin.terminal.gwt.client.ui.ShortcutActionHandler.BeforeShortcutActionListener;
++import com.vaadin.terminal.gwt.client.ui.VAbstractPaintableWidget;
++
++public class VRichTextAreaPaintable extends VAbstractPaintableWidget implements
++ BeforeShortcutActionListener {
++
++ public void updateFromUIDL(final UIDL uidl, ApplicationConnection client) {
++ getWidgetForPaintable().client = client;
++ getWidgetForPaintable().id = uidl.getId();
++
++ if (uidl.hasVariable("text")) {
++ getWidgetForPaintable().currentValue = uidl
++ .getStringVariable("text");
++ if (getWidgetForPaintable().rta.isAttached()) {
++ getWidgetForPaintable().rta
++ .setHTML(getWidgetForPaintable().currentValue);
++ } else {
++ getWidgetForPaintable().html
++ .setHTML(getWidgetForPaintable().currentValue);
++ }
++ }
++ if (!uidl.hasAttribute("cached")) {
++ getWidgetForPaintable().setEnabled(
++ !uidl.getBooleanAttribute("disabled"));
++ }
++
++ if (client.updateComponent(this, uidl, true)) {
++ return;
++ }
++
++ getWidgetForPaintable().setReadOnly(
++ uidl.getBooleanAttribute("readonly"));
++ getWidgetForPaintable().immediate = uidl
++ .getBooleanAttribute("immediate");
++ int newMaxLength = uidl.hasAttribute("maxLength") ? uidl
++ .getIntAttribute("maxLength") : -1;
++ if (newMaxLength >= 0) {
++ if (getWidgetForPaintable().maxLength == -1) {
++ getWidgetForPaintable().keyPressHandler = getWidgetForPaintable().rta
++ .addKeyPressHandler(getWidgetForPaintable());
++ }
++ getWidgetForPaintable().maxLength = newMaxLength;
++ } else if (getWidgetForPaintable().maxLength != -1) {
++ getWidgetForPaintable().getElement().setAttribute("maxlength", "");
++ getWidgetForPaintable().maxLength = -1;
++ getWidgetForPaintable().keyPressHandler.removeHandler();
++ }
++
++ if (uidl.hasAttribute("selectAll")) {
++ getWidgetForPaintable().selectAll();
++ }
++
++ }
++
++ public void onBeforeShortcutAction(Event e) {
++ getWidgetForPaintable().synchronizeContentToServer();
++ }
++
++ @Override
++ public VRichTextArea getWidgetForPaintable() {
++ return (VRichTextArea) super.getWidgetForPaintable();
++ };
++
++ @Override
++ protected Widget createWidget() {
++ return GWT.create(VRichTextArea.class);
++ }
++
++}
--- /dev/null
- /*\r
- @VaadinApache2LicenseForJavaFiles@\r
- */\r
- \r
- package com.vaadin.terminal.gwt.server;\r
- \r
- import java.io.IOException;\r
- import java.io.InputStream;\r
- import java.util.Locale;\r
- import java.util.Map;\r
- \r
- import javax.portlet.ClientDataRequest;\r
- import javax.portlet.PortletRequest;\r
- import javax.portlet.ResourceRequest;\r
- \r
- import com.vaadin.terminal.CombinedRequest;\r
- import com.vaadin.terminal.DeploymentConfiguration;\r
- import com.vaadin.terminal.WrappedRequest;\r
- \r
- /**\r
- * Wrapper for {@link PortletRequest} and its subclasses.\r
- * \r
- * @author Vaadin Ltd.\r
- * @since 7.0\r
- * \r
- * @see WrappedRequest\r
- * @see WrappedPortletResponse\r
- */\r
- public class WrappedPortletRequest implements WrappedRequest {\r
- \r
- private final PortletRequest request;\r
- private final DeploymentConfiguration deploymentConfiguration;\r
- \r
- /**\r
- * Wraps a portlet request and an associated deployment configuration\r
- * \r
- * @param request\r
- * the portlet request to wrap\r
- * @param deploymentConfiguration\r
- * the associated deployment configuration\r
- */\r
- public WrappedPortletRequest(PortletRequest request,\r
- DeploymentConfiguration deploymentConfiguration) {\r
- this.request = request;\r
- this.deploymentConfiguration = deploymentConfiguration;\r
- }\r
- \r
- public Object getAttribute(String name) {\r
- return request.getAttribute(name);\r
- }\r
- \r
- public int getContentLength() {\r
- try {\r
- return ((ClientDataRequest) request).getContentLength();\r
- } catch (ClassCastException e) {\r
- throw new IllegalStateException(\r
- "Content lenght only available for ClientDataRequests");\r
- }\r
- }\r
- \r
- public InputStream getInputStream() throws IOException {\r
- try {\r
- return ((ClientDataRequest) request).getPortletInputStream();\r
- } catch (ClassCastException e) {\r
- throw new IllegalStateException(\r
- "Input data only available for ClientDataRequests");\r
- }\r
- }\r
- \r
- public String getParameter(String name) {\r
- return request.getParameter(name);\r
- }\r
- \r
- public Map<String, String[]> getParameterMap() {\r
- return request.getParameterMap();\r
- }\r
- \r
- public void setAttribute(String name, Object o) {\r
- request.setAttribute(name, o);\r
- }\r
- \r
- public String getRequestPathInfo() {\r
- if (request instanceof ResourceRequest) {\r
- return ((ResourceRequest) request).getResourceID();\r
- } else {\r
- return null;\r
- }\r
- }\r
- \r
- public int getSessionMaxInactiveInterval() {\r
- return request.getPortletSession().getMaxInactiveInterval();\r
- }\r
- \r
- public Object getSessionAttribute(String name) {\r
- return request.getPortletSession().getAttribute(name);\r
- }\r
- \r
- public void setSessionAttribute(String name, Object attribute) {\r
- request.getPortletSession().setAttribute(name, attribute);\r
- }\r
- \r
- /**\r
- * Gets the original, unwrapped portlet request.\r
- * \r
- * @return the unwrapped portlet request\r
- */\r
- public PortletRequest getPortletRequest() {\r
- return request;\r
- }\r
- \r
- public String getContentType() {\r
- try {\r
- return ((ResourceRequest) request).getContentType();\r
- } catch (ClassCastException e) {\r
- throw new IllegalStateException(\r
- "Content type only available for ResourceRequests");\r
- }\r
- }\r
- \r
- public BrowserDetails getBrowserDetails() {\r
- // No browserDetails available for normal requests\r
- return null;\r
- }\r
- \r
- public Locale getLocale() {\r
- return request.getLocale();\r
- }\r
- \r
- public String getRemoteAddr() {\r
- return null;\r
- }\r
- \r
- public boolean isSecure() {\r
- return request.isSecure();\r
- }\r
- \r
- public String getHeader(String string) {\r
- return null;\r
- }\r
- \r
- /**\r
- * Reads a portal property from the portal context of the wrapped request.\r
- * \r
- * @param name\r
- * a string with the name of the portal property to get\r
- * @return a string with the value of the property, or <code>null</code> if\r
- * the property is not defined\r
- */\r
- public String getPortalProperty(String name) {\r
- return request.getPortalContext().getProperty(name);\r
- }\r
- \r
- public DeploymentConfiguration getDeploymentConfiguration() {\r
- return deploymentConfiguration;\r
- }\r
- \r
- /**\r
- * Helper method to get a <code>WrappedPortlettRequest</code> from a\r
- * <code>WrappedRequest</code>. Aside from casting, this method also takes\r
- * care of situations where there's another level of wrapping.\r
- * \r
- * @param request\r
- * a wrapped request\r
- * @return a wrapped portlet request\r
- * @throws ClassCastException\r
- * if the wrapped request doesn't wrap a portlet request\r
- */\r
- public static WrappedPortletRequest cast(WrappedRequest request) {\r
- if (request instanceof CombinedRequest) {\r
- CombinedRequest combinedRequest = (CombinedRequest) request;\r
- request = combinedRequest.getSecondRequest();\r
- }\r
- return (WrappedPortletRequest) request;\r
- }\r
- }\r
++/*
++@VaadinApache2LicenseForJavaFiles@
++ */
++
++package com.vaadin.terminal.gwt.server;
++
++import java.io.IOException;
++import java.io.InputStream;
++import java.util.Locale;
++import java.util.Map;
++
++import javax.portlet.ClientDataRequest;
++import javax.portlet.PortletRequest;
++import javax.portlet.ResourceRequest;
++
++import com.vaadin.terminal.CombinedRequest;
++import com.vaadin.terminal.DeploymentConfiguration;
++import com.vaadin.terminal.WrappedRequest;
++
++/**
++ * Wrapper for {@link PortletRequest} and its subclasses.
++ *
++ * @author Vaadin Ltd.
++ * @since 7.0
++ *
++ * @see WrappedRequest
++ * @see WrappedPortletResponse
++ */
++public class WrappedPortletRequest implements WrappedRequest {
++
++ private final PortletRequest request;
++ private final DeploymentConfiguration deploymentConfiguration;
++
++ /**
++ * Wraps a portlet request and an associated deployment configuration
++ *
++ * @param request
++ * the portlet request to wrap
++ * @param deploymentConfiguration
++ * the associated deployment configuration
++ */
++ public WrappedPortletRequest(PortletRequest request,
++ DeploymentConfiguration deploymentConfiguration) {
++ this.request = request;
++ this.deploymentConfiguration = deploymentConfiguration;
++ }
++
++ public Object getAttribute(String name) {
++ return request.getAttribute(name);
++ }
++
++ public int getContentLength() {
++ try {
++ return ((ClientDataRequest) request).getContentLength();
++ } catch (ClassCastException e) {
++ throw new IllegalStateException(
++ "Content lenght only available for ClientDataRequests");
++ }
++ }
++
++ public InputStream getInputStream() throws IOException {
++ try {
++ return ((ClientDataRequest) request).getPortletInputStream();
++ } catch (ClassCastException e) {
++ throw new IllegalStateException(
++ "Input data only available for ClientDataRequests");
++ }
++ }
++
++ public String getParameter(String name) {
++ return request.getParameter(name);
++ }
++
++ public Map<String, String[]> getParameterMap() {
++ return request.getParameterMap();
++ }
++
++ public void setAttribute(String name, Object o) {
++ request.setAttribute(name, o);
++ }
++
++ public String getRequestPathInfo() {
++ if (request instanceof ResourceRequest) {
++ return ((ResourceRequest) request).getResourceID();
++ } else {
++ return null;
++ }
++ }
++
++ public int getSessionMaxInactiveInterval() {
++ return request.getPortletSession().getMaxInactiveInterval();
++ }
++
++ public Object getSessionAttribute(String name) {
++ return request.getPortletSession().getAttribute(name);
++ }
++
++ public void setSessionAttribute(String name, Object attribute) {
++ request.getPortletSession().setAttribute(name, attribute);
++ }
++
++ /**
++ * Gets the original, unwrapped portlet request.
++ *
++ * @return the unwrapped portlet request
++ */
++ public PortletRequest getPortletRequest() {
++ return request;
++ }
++
++ public String getContentType() {
++ try {
++ return ((ResourceRequest) request).getContentType();
++ } catch (ClassCastException e) {
++ throw new IllegalStateException(
++ "Content type only available for ResourceRequests");
++ }
++ }
++
++ public BrowserDetails getBrowserDetails() {
++ // No browserDetails available for normal requests
++ return null;
++ }
++
++ public Locale getLocale() {
++ return request.getLocale();
++ }
++
++ public String getRemoteAddr() {
++ return null;
++ }
++
++ public boolean isSecure() {
++ return request.isSecure();
++ }
++
++ public String getHeader(String string) {
++ return null;
++ }
++
++ /**
++ * Reads a portal property from the portal context of the wrapped request.
++ *
++ * @param name
++ * a string with the name of the portal property to get
++ * @return a string with the value of the property, or <code>null</code> if
++ * the property is not defined
++ */
++ public String getPortalProperty(String name) {
++ return request.getPortalContext().getProperty(name);
++ }
++
++ public DeploymentConfiguration getDeploymentConfiguration() {
++ return deploymentConfiguration;
++ }
++
++ /**
++ * Helper method to get a <code>WrappedPortlettRequest</code> from a
++ * <code>WrappedRequest</code>. Aside from casting, this method also takes
++ * care of situations where there's another level of wrapping.
++ *
++ * @param request
++ * a wrapped request
++ * @return a wrapped portlet request
++ * @throws ClassCastException
++ * if the wrapped request doesn't wrap a portlet request
++ */
++ public static WrappedPortletRequest cast(WrappedRequest request) {
++ if (request instanceof CombinedRequest) {
++ CombinedRequest combinedRequest = (CombinedRequest) request;
++ request = combinedRequest.getSecondRequest();
++ }
++ return (WrappedPortletRequest) request;
++ }
++}
- /* \r
- @VaadinApache2LicenseForJavaFiles@\r
- */\r
- \r
- package com.vaadin.ui;\r
- \r
- import java.util.Collection;\r
- \r
- import com.vaadin.data.Container;\r
- import com.vaadin.terminal.PaintException;\r
- import com.vaadin.terminal.PaintTarget;\r
- import com.vaadin.terminal.gwt.client.ui.VFilterSelect;\r
- import com.vaadin.terminal.gwt.client.ui.VFilterSelectPaintable;\r
- \r
- /**\r
- * A filtering dropdown single-select. Suitable for newItemsAllowed, but it's\r
- * turned of by default to avoid mistakes. Items are filtered based on user\r
- * input, and loaded dynamically ("lazy-loading") from the server. You can turn\r
- * on newItemsAllowed and change filtering mode (and also turn it off), but you\r
- * can not turn on multi-select mode.\r
- * \r
- */\r
- @SuppressWarnings("serial")\r
- @ClientWidget(VFilterSelectPaintable.class)\r
- public class ComboBox extends Select {\r
- \r
- private String inputPrompt = null;\r
- \r
- /**\r
- * If text input is not allowed, the ComboBox behaves like a pretty\r
- * NativeSelect - the user can not enter any text and clicking the text\r
- * field opens the drop down with options\r
- */\r
- private boolean textInputAllowed = true;\r
- \r
- public ComboBox() {\r
- setMultiSelect(false);\r
- setNewItemsAllowed(false);\r
- }\r
- \r
- public ComboBox(String caption, Collection<?> options) {\r
- super(caption, options);\r
- setMultiSelect(false);\r
- setNewItemsAllowed(false);\r
- }\r
- \r
- public ComboBox(String caption, Container dataSource) {\r
- super(caption, dataSource);\r
- setMultiSelect(false);\r
- setNewItemsAllowed(false);\r
- }\r
- \r
- public ComboBox(String caption) {\r
- super(caption);\r
- setMultiSelect(false);\r
- setNewItemsAllowed(false);\r
- }\r
- \r
- @Override\r
- public void setMultiSelect(boolean multiSelect) {\r
- if (multiSelect && !isMultiSelect()) {\r
- throw new UnsupportedOperationException("Multiselect not supported");\r
- }\r
- super.setMultiSelect(multiSelect);\r
- }\r
- \r
- /**\r
- * Gets the current input prompt.\r
- * \r
- * @see #setInputPrompt(String)\r
- * @return the current input prompt, or null if not enabled\r
- */\r
- public String getInputPrompt() {\r
- return inputPrompt;\r
- }\r
- \r
- /**\r
- * Sets the input prompt - a textual prompt that is displayed when the\r
- * select would otherwise be empty, to prompt the user for input.\r
- * \r
- * @param inputPrompt\r
- * the desired input prompt, or null to disable\r
- */\r
- public void setInputPrompt(String inputPrompt) {\r
- this.inputPrompt = inputPrompt;\r
- requestRepaint();\r
- }\r
- \r
- @Override\r
- public void paintContent(PaintTarget target) throws PaintException {\r
- if (inputPrompt != null) {\r
- target.addAttribute("prompt", inputPrompt);\r
- }\r
- super.paintContent(target);\r
- \r
- if (!textInputAllowed) {\r
- target.addAttribute(VFilterSelect.ATTR_NO_TEXT_INPUT, true);\r
- }\r
- }\r
- \r
- /**\r
- * Sets whether it is possible to input text into the field or whether the\r
- * field area of the component is just used to show what is selected. By\r
- * disabling text input, the comboBox will work in the same way as a\r
- * {@link NativeSelect}\r
- * \r
- * @see #isTextInputAllowed()\r
- * \r
- * @param textInputAllowed\r
- * true to allow entering text, false to just show the current\r
- * selection\r
- */\r
- public void setTextInputAllowed(boolean textInputAllowed) {\r
- this.textInputAllowed = textInputAllowed;\r
- requestRepaint();\r
- }\r
- \r
- /**\r
- * Returns true if the user can enter text into the field to either filter\r
- * the selections or enter a new value if {@link #isNewItemsAllowed()}\r
- * returns true. If text input is disabled, the comboBox will work in the\r
- * same way as a {@link NativeSelect}\r
- * \r
- * @return\r
- */\r
- public boolean isTextInputAllowed() {\r
- return textInputAllowed;\r
- }\r
- \r
- }\r
+ /*
+ @VaadinApache2LicenseForJavaFiles@
+ */
+
+ package com.vaadin.ui;
+
+ import java.util.Collection;
+
+ import com.vaadin.data.Container;
+ import com.vaadin.terminal.PaintException;
+ import com.vaadin.terminal.PaintTarget;
+ import com.vaadin.terminal.gwt.client.ui.VFilterSelect;
++import com.vaadin.terminal.gwt.client.ui.VFilterSelectPaintable;
+
+ /**
+ * A filtering dropdown single-select. Suitable for newItemsAllowed, but it's
+ * turned of by default to avoid mistakes. Items are filtered based on user
+ * input, and loaded dynamically ("lazy-loading") from the server. You can turn
+ * on newItemsAllowed and change filtering mode (and also turn it off), but you
+ * can not turn on multi-select mode.
+ *
+ */
+ @SuppressWarnings("serial")
-@ClientWidget(VFilterSelect.class)
++@ClientWidget(VFilterSelectPaintable.class)
+ public class ComboBox extends Select {
+
+ private String inputPrompt = null;
+
+ /**
+ * If text input is not allowed, the ComboBox behaves like a pretty
+ * NativeSelect - the user can not enter any text and clicking the text
+ * field opens the drop down with options
+ */
+ private boolean textInputAllowed = true;
+
+ public ComboBox() {
+ setMultiSelect(false);
+ setNewItemsAllowed(false);
+ }
+
+ public ComboBox(String caption, Collection<?> options) {
+ super(caption, options);
+ setMultiSelect(false);
+ setNewItemsAllowed(false);
+ }
+
+ public ComboBox(String caption, Container dataSource) {
+ super(caption, dataSource);
+ setMultiSelect(false);
+ setNewItemsAllowed(false);
+ }
+
+ public ComboBox(String caption) {
+ super(caption);
+ setMultiSelect(false);
+ setNewItemsAllowed(false);
+ }
+
+ @Override
+ public void setMultiSelect(boolean multiSelect) {
+ if (multiSelect && !isMultiSelect()) {
+ throw new UnsupportedOperationException("Multiselect not supported");
+ }
+ super.setMultiSelect(multiSelect);
+ }
+
+ /**
+ * Gets the current input prompt.
+ *
+ * @see #setInputPrompt(String)
+ * @return the current input prompt, or null if not enabled
+ */
+ public String getInputPrompt() {
+ return inputPrompt;
+ }
+
+ /**
+ * Sets the input prompt - a textual prompt that is displayed when the
+ * select would otherwise be empty, to prompt the user for input.
+ *
+ * @param inputPrompt
+ * the desired input prompt, or null to disable
+ */
+ public void setInputPrompt(String inputPrompt) {
+ this.inputPrompt = inputPrompt;
+ requestRepaint();
+ }
+
+ @Override
+ public void paintContent(PaintTarget target) throws PaintException {
+ if (inputPrompt != null) {
+ target.addAttribute("prompt", inputPrompt);
+ }
+ super.paintContent(target);
+
+ if (!textInputAllowed) {
+ target.addAttribute(VFilterSelect.ATTR_NO_TEXT_INPUT, true);
+ }
+ }
+
+ /**
+ * Sets whether it is possible to input text into the field or whether the
+ * field area of the component is just used to show what is selected. By
+ * disabling text input, the comboBox will work in the same way as a
+ * {@link NativeSelect}
+ *
+ * @see #isTextInputAllowed()
+ *
+ * @param textInputAllowed
+ * true to allow entering text, false to just show the current
+ * selection
+ */
+ public void setTextInputAllowed(boolean textInputAllowed) {
+ this.textInputAllowed = textInputAllowed;
+ requestRepaint();
+ }
+
+ /**
+ * Returns true if the user can enter text into the field to either filter
+ * the selections or enter a new value if {@link #isNewItemsAllowed()}
+ * returns true. If text input is disabled, the comboBox will work in the
+ * same way as a {@link NativeSelect}
+ *
+ * @return
+ */
+ public boolean isTextInputAllowed() {
+ return textInputAllowed;
+ }
+
+ }
- /* \r
- @VaadinApache2LicenseForJavaFiles@\r
- */\r
- \r
- package com.vaadin.ui;\r
- \r
- import java.util.Date;\r
- \r
- import com.vaadin.data.Property;\r
- import com.vaadin.terminal.gwt.client.ui.VDateFieldCalendarPaintable;\r
- \r
- /**\r
- * <p>\r
- * A date entry component, which displays the actual date selector inline.\r
- * \r
- * </p>\r
- * \r
- * @see DateField\r
- * @see PopupDateField\r
- * @author Vaadin Ltd.\r
- * @version\r
- * @VERSION@\r
- * @since 5.0\r
- */\r
- @ClientWidget(VDateFieldCalendarPaintable.class)\r
- public class InlineDateField extends DateField {\r
- \r
- public InlineDateField() {\r
- super();\r
- }\r
- \r
- public InlineDateField(Property dataSource) throws IllegalArgumentException {\r
- super(dataSource);\r
- }\r
- \r
- public InlineDateField(String caption, Date value) {\r
- super(caption, value);\r
- }\r
- \r
- public InlineDateField(String caption, Property dataSource) {\r
- super(caption, dataSource);\r
- }\r
- \r
- public InlineDateField(String caption) {\r
- super(caption);\r
- }\r
- \r
- }\r
+ /*
+ @VaadinApache2LicenseForJavaFiles@
+ */
+
+ package com.vaadin.ui;
+
+ import java.util.Date;
+
+ import com.vaadin.data.Property;
-import com.vaadin.terminal.gwt.client.ui.VDateFieldCalendar;
++import com.vaadin.terminal.gwt.client.ui.VDateFieldCalendarPaintable;
+
+ /**
+ * <p>
+ * A date entry component, which displays the actual date selector inline.
+ *
+ * </p>
+ *
+ * @see DateField
+ * @see PopupDateField
+ * @author Vaadin Ltd.
+ * @version
+ * @VERSION@
+ * @since 5.0
+ */
-@ClientWidget(VDateFieldCalendar.class)
++@ClientWidget(VDateFieldCalendarPaintable.class)
+ public class InlineDateField extends DateField {
+
+ public InlineDateField() {
+ super();
+ }
+
+ public InlineDateField(Property dataSource) throws IllegalArgumentException {
+ super(dataSource);
+ }
+
+ public InlineDateField(String caption, Date value) {
+ super(caption, value);
+ }
+
+ public InlineDateField(String caption, Property dataSource) {
+ super(caption, dataSource);
+ }
+
+ public InlineDateField(String caption) {
+ super(caption);
+ }
+
+ }
- package com.vaadin.data.util;\r
- \r
- import junit.framework.TestCase;\r
- \r
- import org.junit.Assert;\r
- \r
- public class ObjectPropertyTest extends TestCase {\r
- \r
- public static class TestSuperClass {\r
- private String name;\r
- \r
- public TestSuperClass(String name) {\r
- this.name = name;\r
- }\r
- \r
- public String getName() {\r
- return name;\r
- }\r
- \r
- @Override\r
- public String toString() {\r
- return getName();\r
- }\r
- }\r
- \r
- public static class TestSubClass extends TestSuperClass {\r
- public TestSubClass(String name) {\r
- super("Subclass: " + name);\r
- }\r
- }\r
- \r
- private TestSuperClass super1 = new TestSuperClass("super1");\r
- private TestSubClass sub1 = new TestSubClass("sub1");\r
- \r
- public void testSimple() {\r
- ObjectProperty<TestSuperClass> prop1 = new ObjectProperty<TestSuperClass>(\r
- super1, TestSuperClass.class);\r
- Assert.assertEquals("super1", prop1.getValue().getName());\r
- prop1 = new ObjectProperty<TestSuperClass>(super1);\r
- Assert.assertEquals("super1", prop1.getValue().getName());\r
- \r
- ObjectProperty<TestSubClass> prop2 = new ObjectProperty<TestSubClass>(\r
- sub1, TestSubClass.class);\r
- Assert.assertEquals("Subclass: sub1", prop2.getValue().getName());\r
- prop2 = new ObjectProperty<TestSubClass>(sub1);\r
- Assert.assertEquals("Subclass: sub1", prop2.getValue().getName());\r
- }\r
- \r
- public void testSetValueObjectSuper() {\r
- ObjectProperty<TestSuperClass> prop = new ObjectProperty<TestSuperClass>(\r
- super1, TestSuperClass.class);\r
- Assert.assertEquals("super1", prop.getValue().getName());\r
- prop.setValue(new TestSuperClass("super2"));\r
- Assert.assertEquals("super1", super1.getName());\r
- Assert.assertEquals("super2", prop.getValue().getName());\r
- }\r
- \r
- public void testSetValueObjectSub() {\r
- ObjectProperty<TestSubClass> prop = new ObjectProperty<TestSubClass>(\r
- sub1, TestSubClass.class);\r
- Assert.assertEquals("Subclass: sub1", prop.getValue().getName());\r
- prop.setValue(new TestSubClass("sub2"));\r
- Assert.assertEquals("Subclass: sub1", sub1.getName());\r
- Assert.assertEquals("Subclass: sub2", prop.getValue().getName());\r
- }\r
- \r
- public void testSetValueStringSuper() {\r
- ObjectProperty<TestSuperClass> prop = new ObjectProperty<TestSuperClass>(\r
- super1, TestSuperClass.class);\r
- Assert.assertEquals("super1", prop.getValue().getName());\r
- prop.setValue(new TestSuperClass("super2"));\r
- Assert.assertEquals("super1", super1.getName());\r
- Assert.assertEquals("super2", prop.getValue().getName());\r
- }\r
- \r
- public void testSetValueStringSub() {\r
- ObjectProperty<TestSubClass> prop = new ObjectProperty<TestSubClass>(\r
- sub1, TestSubClass.class);\r
- Assert.assertEquals("Subclass: sub1", prop.getValue().getName());\r
- prop.setValue(new TestSubClass("sub2"));\r
- Assert.assertEquals("Subclass: sub1", sub1.getName());\r
- Assert.assertEquals("Subclass: sub2", prop.getValue().getName());\r
- }\r
- \r
- public void testMixedGenerics() {\r
- ObjectProperty<TestSuperClass> prop = new ObjectProperty<TestSuperClass>(\r
- sub1);\r
- Assert.assertEquals("Subclass: sub1", prop.getValue().getName());\r
- Assert.assertEquals(prop.getType(), TestSubClass.class);\r
- // create correct subclass based on the runtime type of the instance\r
- // given to ObjectProperty constructor, which is a subclass of the type\r
- // parameter\r
- prop.setValue(new TestSubClass("sub2"));\r
- Assert.assertEquals("Subclass: sub2", prop.getValue().getName());\r
- }\r
- \r
- }\r
+ package com.vaadin.data.util;
+
+ import junit.framework.TestCase;
+
+ import org.junit.Assert;
+
-import com.vaadin.data.util.ObjectProperty;
-
+ public class ObjectPropertyTest extends TestCase {
+
+ public static class TestSuperClass {
+ private String name;
+
+ public TestSuperClass(String name) {
+ this.name = name;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ @Override
+ public String toString() {
+ return getName();
+ }
+ }
+
+ public static class TestSubClass extends TestSuperClass {
+ public TestSubClass(String name) {
+ super("Subclass: " + name);
+ }
+ }
+
+ private TestSuperClass super1 = new TestSuperClass("super1");
+ private TestSubClass sub1 = new TestSubClass("sub1");
+
+ public void testSimple() {
+ ObjectProperty<TestSuperClass> prop1 = new ObjectProperty<TestSuperClass>(
+ super1, TestSuperClass.class);
+ Assert.assertEquals("super1", prop1.getValue().getName());
+ prop1 = new ObjectProperty<TestSuperClass>(super1);
+ Assert.assertEquals("super1", prop1.getValue().getName());
+
+ ObjectProperty<TestSubClass> prop2 = new ObjectProperty<TestSubClass>(
+ sub1, TestSubClass.class);
+ Assert.assertEquals("Subclass: sub1", prop2.getValue().getName());
+ prop2 = new ObjectProperty<TestSubClass>(sub1);
+ Assert.assertEquals("Subclass: sub1", prop2.getValue().getName());
+ }
+
+ public void testSetValueObjectSuper() {
+ ObjectProperty<TestSuperClass> prop = new ObjectProperty<TestSuperClass>(
+ super1, TestSuperClass.class);
+ Assert.assertEquals("super1", prop.getValue().getName());
+ prop.setValue(new TestSuperClass("super2"));
+ Assert.assertEquals("super1", super1.getName());
+ Assert.assertEquals("super2", prop.getValue().getName());
+ }
+
+ public void testSetValueObjectSub() {
+ ObjectProperty<TestSubClass> prop = new ObjectProperty<TestSubClass>(
+ sub1, TestSubClass.class);
+ Assert.assertEquals("Subclass: sub1", prop.getValue().getName());
+ prop.setValue(new TestSubClass("sub2"));
+ Assert.assertEquals("Subclass: sub1", sub1.getName());
+ Assert.assertEquals("Subclass: sub2", prop.getValue().getName());
+ }
+
+ public void testSetValueStringSuper() {
+ ObjectProperty<TestSuperClass> prop = new ObjectProperty<TestSuperClass>(
+ super1, TestSuperClass.class);
+ Assert.assertEquals("super1", prop.getValue().getName());
- prop.setValue("super2");
++ prop.setValue(new TestSuperClass("super2"));
+ Assert.assertEquals("super1", super1.getName());
+ Assert.assertEquals("super2", prop.getValue().getName());
+ }
+
+ public void testSetValueStringSub() {
+ ObjectProperty<TestSubClass> prop = new ObjectProperty<TestSubClass>(
+ sub1, TestSubClass.class);
+ Assert.assertEquals("Subclass: sub1", prop.getValue().getName());
- prop.setValue("sub2");
++ prop.setValue(new TestSubClass("sub2"));
+ Assert.assertEquals("Subclass: sub1", sub1.getName());
+ Assert.assertEquals("Subclass: sub2", prop.getValue().getName());
+ }
+
+ public void testMixedGenerics() {
+ ObjectProperty<TestSuperClass> prop = new ObjectProperty<TestSuperClass>(
+ sub1);
+ Assert.assertEquals("Subclass: sub1", prop.getValue().getName());
+ Assert.assertEquals(prop.getType(), TestSubClass.class);
+ // create correct subclass based on the runtime type of the instance
+ // given to ObjectProperty constructor, which is a subclass of the type
+ // parameter
- prop.setValue("sub2");
++ prop.setValue(new TestSubClass("sub2"));
+ Assert.assertEquals("Subclass: sub2", prop.getValue().getName());
+ }
+
+ }
- package com.vaadin.data.util;\r
- \r
- import java.util.HashMap;\r
- import java.util.Iterator;\r
- import java.util.Map;\r
- \r
- import junit.framework.TestCase;\r
- \r
- import com.vaadin.data.Container;\r
- import com.vaadin.data.Item;\r
- import com.vaadin.tests.util.TestUtil;\r
- \r
- public class TestContainerSorting extends TestCase {\r
- \r
- private static final String ITEM_DATA_MINUS2_NULL = "Data -2 null";\r
- private static final String ITEM_DATA_MINUS2 = "Data -2";\r
- private static final String ITEM_DATA_MINUS1 = "Data -1";\r
- private static final String ITEM_DATA_MINUS1_NULL = "Data -1 null";\r
- private static final String ITEM_ANOTHER_NULL = "Another null";\r
- private static final String ITEM_STRING_2 = "String 2";\r
- private static final String ITEM_STRING_NULL2 = "String null";\r
- private static final String ITEM_STRING_1 = "String 1";\r
- \r
- private static final String PROPERTY_INTEGER_NULL2 = "integer-null";\r
- private static final String PROPERTY_INTEGER_NOT_NULL = "integer-not-null";\r
- private static final String PROPERTY_STRING_NULL = "string-null";\r
- private static final String PROPERTY_STRING_ID = "string-not-null";\r
- \r
- @Override\r
- protected void setUp() throws Exception {\r
- super.setUp();\r
- }\r
- \r
- public void testEmptyFilteredIndexedContainer() {\r
- IndexedContainer ic = new IndexedContainer();\r
- \r
- addProperties(ic);\r
- populate(ic);\r
- \r
- ic.addContainerFilter(PROPERTY_STRING_ID, "aasdfasdfasdf", true, false);\r
- ic.sort(new Object[] { PROPERTY_STRING_ID }, new boolean[] { true });\r
- \r
- }\r
- \r
- public void testFilteredIndexedContainer() {\r
- IndexedContainer ic = new IndexedContainer();\r
- \r
- addProperties(ic);\r
- populate(ic);\r
- \r
- ic.addContainerFilter(PROPERTY_STRING_ID, "a", true, false);\r
- ic.sort(new Object[] { PROPERTY_STRING_ID }, new boolean[] { true });\r
- verifyOrder(ic,\r
- new String[] { ITEM_ANOTHER_NULL, ITEM_DATA_MINUS1,\r
- ITEM_DATA_MINUS1_NULL, ITEM_DATA_MINUS2,\r
- ITEM_DATA_MINUS2_NULL, });\r
- }\r
- \r
- public void testIndexedContainer() {\r
- IndexedContainer ic = new IndexedContainer();\r
- \r
- addProperties(ic);\r
- populate(ic);\r
- \r
- ic.sort(new Object[] { PROPERTY_STRING_ID }, new boolean[] { true });\r
- verifyOrder(ic, new String[] { ITEM_ANOTHER_NULL, ITEM_DATA_MINUS1,\r
- ITEM_DATA_MINUS1_NULL, ITEM_DATA_MINUS2, ITEM_DATA_MINUS2_NULL,\r
- ITEM_STRING_1, ITEM_STRING_2, ITEM_STRING_NULL2 });\r
- \r
- ic.sort(new Object[] { PROPERTY_INTEGER_NOT_NULL,\r
- PROPERTY_INTEGER_NULL2, PROPERTY_STRING_ID }, new boolean[] {\r
- true, false, true });\r
- verifyOrder(ic, new String[] { ITEM_DATA_MINUS2, ITEM_DATA_MINUS2_NULL,\r
- ITEM_DATA_MINUS1, ITEM_DATA_MINUS1_NULL, ITEM_ANOTHER_NULL,\r
- ITEM_STRING_NULL2, ITEM_STRING_1, ITEM_STRING_2 });\r
- \r
- ic.sort(new Object[] { PROPERTY_INTEGER_NOT_NULL,\r
- PROPERTY_INTEGER_NULL2, PROPERTY_STRING_ID }, new boolean[] {\r
- true, true, true });\r
- verifyOrder(ic, new String[] { ITEM_DATA_MINUS2_NULL, ITEM_DATA_MINUS2,\r
- ITEM_DATA_MINUS1_NULL, ITEM_DATA_MINUS1, ITEM_ANOTHER_NULL,\r
- ITEM_STRING_NULL2, ITEM_STRING_1, ITEM_STRING_2 });\r
- \r
- }\r
- \r
- public void testHierarchicalContainer() {\r
- HierarchicalContainer hc = new HierarchicalContainer();\r
- populateContainer(hc);\r
- hc.sort(new Object[] { "name" }, new boolean[] { true });\r
- verifyOrder(hc, new String[] { "Audi", "C++", "Call of Duty", "Cars",\r
- "English", "Fallout", "Finnish", "Ford", "Games", "Java",\r
- "Might and Magic", "Natural languages", "PHP",\r
- "Programming languages", "Python", "Red Alert", "Swedish",\r
- "Toyota", "Volvo" });\r
- TestUtil.assertArrays(\r
- hc.rootItemIds().toArray(),\r
- new Integer[] { nameToId.get("Cars"), nameToId.get("Games"),\r
- nameToId.get("Natural languages"),\r
- nameToId.get("Programming languages") });\r
- TestUtil.assertArrays(\r
- hc.getChildren(nameToId.get("Games")).toArray(),\r
- new Integer[] { nameToId.get("Call of Duty"),\r
- nameToId.get("Fallout"),\r
- nameToId.get("Might and Magic"),\r
- nameToId.get("Red Alert") });\r
- }\r
- \r
- private static void populateContainer(HierarchicalContainer container) {\r
- container.addContainerProperty("name", String.class, null);\r
- \r
- addItem(container, "Games", null);\r
- addItem(container, "Call of Duty", "Games");\r
- addItem(container, "Might and Magic", "Games");\r
- addItem(container, "Fallout", "Games");\r
- addItem(container, "Red Alert", "Games");\r
- \r
- addItem(container, "Cars", null);\r
- addItem(container, "Toyota", "Cars");\r
- addItem(container, "Volvo", "Cars");\r
- addItem(container, "Audi", "Cars");\r
- addItem(container, "Ford", "Cars");\r
- \r
- addItem(container, "Natural languages", null);\r
- addItem(container, "Swedish", "Natural languages");\r
- addItem(container, "English", "Natural languages");\r
- addItem(container, "Finnish", "Natural languages");\r
- \r
- addItem(container, "Programming languages", null);\r
- addItem(container, "C++", "Programming languages");\r
- addItem(container, "PHP", "Programming languages");\r
- addItem(container, "Java", "Programming languages");\r
- addItem(container, "Python", "Programming languages");\r
- \r
- }\r
- \r
- private static int index = 0;\r
- private static Map<String, Integer> nameToId = new HashMap<String, Integer>();\r
- private static Map<Integer, String> idToName = new HashMap<Integer, String>();\r
- \r
- public static void addItem(IndexedContainer container, String string,\r
- String parent) {\r
- nameToId.put(string, index);\r
- idToName.put(index, string);\r
- \r
- Item item = container.addItem(index);\r
- item.getItemProperty("name").setValue(string);\r
- \r
- if (parent != null && container instanceof HierarchicalContainer) {\r
- ((HierarchicalContainer) container).setParent(index,\r
- nameToId.get(parent));\r
- }\r
- \r
- index++;\r
- }\r
- \r
- private void verifyOrder(Container.Sortable ic, Object[] idOrder) {\r
- int size = ic.size();\r
- Object[] actual = new Object[size];\r
- Iterator<?> i = ic.getItemIds().iterator();\r
- int index = 0;\r
- while (i.hasNext()) {\r
- Object o = i.next();\r
- if (o.getClass() == Integer.class\r
- && idOrder[index].getClass() == String.class) {\r
- o = idToName.get(o);\r
- }\r
- actual[index++] = o;\r
- }\r
- \r
- TestUtil.assertArrays(actual, idOrder);\r
- \r
- }\r
- \r
- private void populate(IndexedContainer ic) {\r
- addItem(ic, ITEM_STRING_1, ITEM_STRING_1, 1, 1);\r
- addItem(ic, ITEM_STRING_NULL2, null, 0, null);\r
- addItem(ic, ITEM_STRING_2, ITEM_STRING_2, 2, 2);\r
- addItem(ic, ITEM_ANOTHER_NULL, null, 0, null);\r
- addItem(ic, ITEM_DATA_MINUS1, ITEM_DATA_MINUS1, -1, -1);\r
- addItem(ic, ITEM_DATA_MINUS1_NULL, null, -1, null);\r
- addItem(ic, ITEM_DATA_MINUS2, ITEM_DATA_MINUS2, -2, -2);\r
- addItem(ic, ITEM_DATA_MINUS2_NULL, null, -2, null);\r
- }\r
- \r
- private Item addItem(Container ic, String id, String string_null,\r
- int integer, Integer integer_null) {\r
- Item i = ic.addItem(id);\r
- i.getItemProperty(PROPERTY_STRING_ID).setValue(id);\r
- i.getItemProperty(PROPERTY_STRING_NULL).setValue(string_null);\r
- i.getItemProperty(PROPERTY_INTEGER_NOT_NULL).setValue(integer);\r
- i.getItemProperty(PROPERTY_INTEGER_NULL2).setValue(integer_null);\r
- \r
- return i;\r
- }\r
- \r
- private void addProperties(IndexedContainer ic) {\r
- ic.addContainerProperty("id", String.class, null);\r
- ic.addContainerProperty(PROPERTY_STRING_ID, String.class, "");\r
- ic.addContainerProperty(PROPERTY_STRING_NULL, String.class, null);\r
- ic.addContainerProperty(PROPERTY_INTEGER_NULL2, Integer.class, null);\r
- ic.addContainerProperty(PROPERTY_INTEGER_NOT_NULL, Integer.class, 0);\r
- ic.addContainerProperty("comparable-null", Integer.class, 0);\r
- }\r
- \r
- public class MyObject implements Comparable<MyObject> {\r
- private String data;\r
- \r
- public int compareTo(MyObject o) {\r
- if (o == null) {\r
- return 1;\r
- }\r
- \r
- if (o.data == null) {\r
- return data == null ? 0 : 1;\r
- } else if (data == null) {\r
- return -1;\r
- } else {\r
- return data.compareTo(o.data);\r
- }\r
- }\r
- }\r
- \r
- }\r
+ package com.vaadin.data.util;
+
+ import java.util.HashMap;
+ import java.util.Iterator;
+ import java.util.Map;
+
+ import junit.framework.TestCase;
+
+ import com.vaadin.data.Container;
+ import com.vaadin.data.Item;
-import com.vaadin.data.util.HierarchicalContainer;
-import com.vaadin.data.util.IndexedContainer;
++import com.vaadin.tests.util.TestUtil;
+
+ public class TestContainerSorting extends TestCase {
+
+ private static final String ITEM_DATA_MINUS2_NULL = "Data -2 null";
+ private static final String ITEM_DATA_MINUS2 = "Data -2";
+ private static final String ITEM_DATA_MINUS1 = "Data -1";
+ private static final String ITEM_DATA_MINUS1_NULL = "Data -1 null";
+ private static final String ITEM_ANOTHER_NULL = "Another null";
+ private static final String ITEM_STRING_2 = "String 2";
+ private static final String ITEM_STRING_NULL2 = "String null";
+ private static final String ITEM_STRING_1 = "String 1";
+
+ private static final String PROPERTY_INTEGER_NULL2 = "integer-null";
+ private static final String PROPERTY_INTEGER_NOT_NULL = "integer-not-null";
+ private static final String PROPERTY_STRING_NULL = "string-null";
+ private static final String PROPERTY_STRING_ID = "string-not-null";
+
+ @Override
+ protected void setUp() throws Exception {
+ super.setUp();
+ }
+
+ public void testEmptyFilteredIndexedContainer() {
+ IndexedContainer ic = new IndexedContainer();
+
+ addProperties(ic);
+ populate(ic);
+
+ ic.addContainerFilter(PROPERTY_STRING_ID, "aasdfasdfasdf", true, false);
+ ic.sort(new Object[] { PROPERTY_STRING_ID }, new boolean[] { true });
+
+ }
+
+ public void testFilteredIndexedContainer() {
+ IndexedContainer ic = new IndexedContainer();
+
+ addProperties(ic);
+ populate(ic);
+
+ ic.addContainerFilter(PROPERTY_STRING_ID, "a", true, false);
+ ic.sort(new Object[] { PROPERTY_STRING_ID }, new boolean[] { true });
+ verifyOrder(ic,
+ new String[] { ITEM_ANOTHER_NULL, ITEM_DATA_MINUS1,
+ ITEM_DATA_MINUS1_NULL, ITEM_DATA_MINUS2,
+ ITEM_DATA_MINUS2_NULL, });
+ }
+
+ public void testIndexedContainer() {
+ IndexedContainer ic = new IndexedContainer();
+
+ addProperties(ic);
+ populate(ic);
+
+ ic.sort(new Object[] { PROPERTY_STRING_ID }, new boolean[] { true });
+ verifyOrder(ic, new String[] { ITEM_ANOTHER_NULL, ITEM_DATA_MINUS1,
+ ITEM_DATA_MINUS1_NULL, ITEM_DATA_MINUS2, ITEM_DATA_MINUS2_NULL,
+ ITEM_STRING_1, ITEM_STRING_2, ITEM_STRING_NULL2 });
+
+ ic.sort(new Object[] { PROPERTY_INTEGER_NOT_NULL,
+ PROPERTY_INTEGER_NULL2, PROPERTY_STRING_ID }, new boolean[] {
+ true, false, true });
+ verifyOrder(ic, new String[] { ITEM_DATA_MINUS2, ITEM_DATA_MINUS2_NULL,
+ ITEM_DATA_MINUS1, ITEM_DATA_MINUS1_NULL, ITEM_ANOTHER_NULL,
+ ITEM_STRING_NULL2, ITEM_STRING_1, ITEM_STRING_2 });
+
+ ic.sort(new Object[] { PROPERTY_INTEGER_NOT_NULL,
+ PROPERTY_INTEGER_NULL2, PROPERTY_STRING_ID }, new boolean[] {
+ true, true, true });
+ verifyOrder(ic, new String[] { ITEM_DATA_MINUS2_NULL, ITEM_DATA_MINUS2,
+ ITEM_DATA_MINUS1_NULL, ITEM_DATA_MINUS1, ITEM_ANOTHER_NULL,
+ ITEM_STRING_NULL2, ITEM_STRING_1, ITEM_STRING_2 });
+
+ }
+
+ public void testHierarchicalContainer() {
+ HierarchicalContainer hc = new HierarchicalContainer();
+ populateContainer(hc);
+ hc.sort(new Object[] { "name" }, new boolean[] { true });
+ verifyOrder(hc, new String[] { "Audi", "C++", "Call of Duty", "Cars",
+ "English", "Fallout", "Finnish", "Ford", "Games", "Java",
+ "Might and Magic", "Natural languages", "PHP",
+ "Programming languages", "Python", "Red Alert", "Swedish",
+ "Toyota", "Volvo" });
- assertArrays(
++ TestUtil.assertArrays(
+ hc.rootItemIds().toArray(),
+ new Integer[] { nameToId.get("Cars"), nameToId.get("Games"),
+ nameToId.get("Natural languages"),
+ nameToId.get("Programming languages") });
- assertArrays(
++ TestUtil.assertArrays(
+ hc.getChildren(nameToId.get("Games")).toArray(),
+ new Integer[] { nameToId.get("Call of Duty"),
+ nameToId.get("Fallout"),
+ nameToId.get("Might and Magic"),
+ nameToId.get("Red Alert") });
+ }
+
+ private static void populateContainer(HierarchicalContainer container) {
+ container.addContainerProperty("name", String.class, null);
+
+ addItem(container, "Games", null);
+ addItem(container, "Call of Duty", "Games");
+ addItem(container, "Might and Magic", "Games");
+ addItem(container, "Fallout", "Games");
+ addItem(container, "Red Alert", "Games");
+
+ addItem(container, "Cars", null);
+ addItem(container, "Toyota", "Cars");
+ addItem(container, "Volvo", "Cars");
+ addItem(container, "Audi", "Cars");
+ addItem(container, "Ford", "Cars");
+
+ addItem(container, "Natural languages", null);
+ addItem(container, "Swedish", "Natural languages");
+ addItem(container, "English", "Natural languages");
+ addItem(container, "Finnish", "Natural languages");
+
+ addItem(container, "Programming languages", null);
+ addItem(container, "C++", "Programming languages");
+ addItem(container, "PHP", "Programming languages");
+ addItem(container, "Java", "Programming languages");
+ addItem(container, "Python", "Programming languages");
+
+ }
+
+ private static int index = 0;
+ private static Map<String, Integer> nameToId = new HashMap<String, Integer>();
+ private static Map<Integer, String> idToName = new HashMap<Integer, String>();
+
+ public static void addItem(IndexedContainer container, String string,
+ String parent) {
+ nameToId.put(string, index);
+ idToName.put(index, string);
+
+ Item item = container.addItem(index);
+ item.getItemProperty("name").setValue(string);
+
+ if (parent != null && container instanceof HierarchicalContainer) {
+ ((HierarchicalContainer) container).setParent(index,
+ nameToId.get(parent));
+ }
+
+ index++;
+ }
+
+ private void verifyOrder(Container.Sortable ic, Object[] idOrder) {
+ int size = ic.size();
+ Object[] actual = new Object[size];
+ Iterator<?> i = ic.getItemIds().iterator();
+ int index = 0;
+ while (i.hasNext()) {
+ Object o = i.next();
+ if (o.getClass() == Integer.class
+ && idOrder[index].getClass() == String.class) {
+ o = idToName.get(o);
+ }
+ actual[index++] = o;
+ }
+
- assertArrays(actual, idOrder);
-
- }
-
- private void assertArrays(Object[] actualObjects, Object[] expectedObjects) {
- assertEquals(
- "Actual contains a different number of values than was expected",
- expectedObjects.length, actualObjects.length);
-
- for (int i = 0; i < actualObjects.length; i++) {
- Object actual = actualObjects[i];
- Object expected = expectedObjects[i];
-
- assertEquals("Item[" + i + "] does not match", expected, actual);
- }
++ TestUtil.assertArrays(actual, idOrder);
+
+ }
+
+ private void populate(IndexedContainer ic) {
+ addItem(ic, ITEM_STRING_1, ITEM_STRING_1, 1, 1);
+ addItem(ic, ITEM_STRING_NULL2, null, 0, null);
+ addItem(ic, ITEM_STRING_2, ITEM_STRING_2, 2, 2);
+ addItem(ic, ITEM_ANOTHER_NULL, null, 0, null);
+ addItem(ic, ITEM_DATA_MINUS1, ITEM_DATA_MINUS1, -1, -1);
+ addItem(ic, ITEM_DATA_MINUS1_NULL, null, -1, null);
+ addItem(ic, ITEM_DATA_MINUS2, ITEM_DATA_MINUS2, -2, -2);
+ addItem(ic, ITEM_DATA_MINUS2_NULL, null, -2, null);
+ }
+
+ private Item addItem(Container ic, String id, String string_null,
+ int integer, Integer integer_null) {
+ Item i = ic.addItem(id);
+ i.getItemProperty(PROPERTY_STRING_ID).setValue(id);
+ i.getItemProperty(PROPERTY_STRING_NULL).setValue(string_null);
+ i.getItemProperty(PROPERTY_INTEGER_NOT_NULL).setValue(integer);
+ i.getItemProperty(PROPERTY_INTEGER_NULL2).setValue(integer_null);
+
+ return i;
+ }
+
+ private void addProperties(IndexedContainer ic) {
+ ic.addContainerProperty("id", String.class, null);
+ ic.addContainerProperty(PROPERTY_STRING_ID, String.class, "");
+ ic.addContainerProperty(PROPERTY_STRING_NULL, String.class, null);
+ ic.addContainerProperty(PROPERTY_INTEGER_NULL2, Integer.class, null);
+ ic.addContainerProperty(PROPERTY_INTEGER_NOT_NULL, Integer.class, 0);
+ ic.addContainerProperty("comparable-null", Integer.class, 0);
+ }
+
+ public class MyObject implements Comparable<MyObject> {
+ private String data;
+
+ public int compareTo(MyObject o) {
+ if (o == null) {
+ return 1;
+ }
+
+ if (o.data == null) {
+ return data == null ? 0 : 1;
+ } else if (data == null) {
+ return -1;
+ } else {
+ return data.compareTo(o.data);
+ }
+ }
+ }
+
+ }
--- /dev/null
- package com.vaadin.tests.data.bean;\r
- \r
- import java.io.Serializable;\r
- \r
- @SuppressWarnings("serial")\r
- public class Address implements Serializable {\r
- \r
- private String streetAddress = "";\r
- private Integer postalCode = null;\r
- private String city = "";\r
- private Country country = null;\r
- \r
- public Address() {\r
- \r
- }\r
- \r
- public Address(String streetAddress, int postalCode, String city,\r
- Country country) {\r
- setStreetAddress(streetAddress);\r
- setPostalCode(postalCode);\r
- setCity(city);\r
- setCountry(country);\r
- }\r
- \r
- @Override\r
- public String toString() {\r
- return "Address [streetAddress=" + streetAddress + ", postalCode="\r
- + postalCode + ", city=" + city + ", country=" + country + "]";\r
- }\r
- \r
- public String getStreetAddress() {\r
- return streetAddress;\r
- }\r
- \r
- public void setStreetAddress(String streetAddress) {\r
- this.streetAddress = streetAddress;\r
- }\r
- \r
- public Integer getPostalCode() {\r
- return postalCode;\r
- }\r
- \r
- public void setPostalCode(Integer postalCode) {\r
- this.postalCode = postalCode;\r
- }\r
- \r
- public String getCity() {\r
- return city;\r
- }\r
- \r
- public void setCity(String city) {\r
- this.city = city;\r
- }\r
- \r
- public Country getCountry() {\r
- return country;\r
- }\r
- \r
- public void setCountry(Country country) {\r
- this.country = country;\r
- }\r
- \r
- }\r
++package com.vaadin.tests.data.bean;
++
++import java.io.Serializable;
++
++@SuppressWarnings("serial")
++public class Address implements Serializable {
++
++ private String streetAddress = "";
++ private Integer postalCode = null;
++ private String city = "";
++ private Country country = null;
++
++ public Address() {
++
++ }
++
++ public Address(String streetAddress, int postalCode, String city,
++ Country country) {
++ setStreetAddress(streetAddress);
++ setPostalCode(postalCode);
++ setCity(city);
++ setCountry(country);
++ }
++
++ @Override
++ public String toString() {
++ return "Address [streetAddress=" + streetAddress + ", postalCode="
++ + postalCode + ", city=" + city + ", country=" + country + "]";
++ }
++
++ public String getStreetAddress() {
++ return streetAddress;
++ }
++
++ public void setStreetAddress(String streetAddress) {
++ this.streetAddress = streetAddress;
++ }
++
++ public Integer getPostalCode() {
++ return postalCode;
++ }
++
++ public void setPostalCode(Integer postalCode) {
++ this.postalCode = postalCode;
++ }
++
++ public String getCity() {
++ return city;
++ }
++
++ public void setCity(String city) {
++ this.city = city;
++ }
++
++ public Country getCountry() {
++ return country;
++ }
++
++ public void setCountry(Country country) {
++ this.country = country;
++ }
++
++}
--- /dev/null
- package com.vaadin.tests.data.bean;\r
- \r
- import javax.validation.constraints.Digits;\r
- import javax.validation.constraints.Max;\r
- import javax.validation.constraints.Min;\r
- import javax.validation.constraints.NotNull;\r
- import javax.validation.constraints.Size;\r
- \r
- public class BeanToValidate {\r
- @NotNull\r
- @Size(min = 3, max = 16)\r
- private String firstname;\r
- \r
- @NotNull(message = "Last name must not be empty")\r
- private String lastname;\r
- \r
- @Min(value = 18, message = "Must be 18 or above")\r
- @Max(150)\r
- private int age;\r
- \r
- @Digits(integer = 3, fraction = 2)\r
- private String decimals;\r
- \r
- public String getFirstname() {\r
- return firstname;\r
- }\r
- \r
- public void setFirstname(String firstname) {\r
- this.firstname = firstname;\r
- }\r
- \r
- public String getLastname() {\r
- return lastname;\r
- }\r
- \r
- public void setLastname(String lastname) {\r
- this.lastname = lastname;\r
- }\r
- \r
- public int getAge() {\r
- return age;\r
- }\r
- \r
- public void setAge(int age) {\r
- this.age = age;\r
- }\r
- \r
- public String getDecimals() {\r
- return decimals;\r
- }\r
- \r
- public void setDecimals(String decimals) {\r
- this.decimals = decimals;\r
- }\r
- \r
- }\r
++package com.vaadin.tests.data.bean;
++
++import javax.validation.constraints.Digits;
++import javax.validation.constraints.Max;
++import javax.validation.constraints.Min;
++import javax.validation.constraints.NotNull;
++import javax.validation.constraints.Size;
++
++public class BeanToValidate {
++ @NotNull
++ @Size(min = 3, max = 16)
++ private String firstname;
++
++ @NotNull(message = "Last name must not be empty")
++ private String lastname;
++
++ @Min(value = 18, message = "Must be 18 or above")
++ @Max(150)
++ private int age;
++
++ @Digits(integer = 3, fraction = 2)
++ private String decimals;
++
++ public String getFirstname() {
++ return firstname;
++ }
++
++ public void setFirstname(String firstname) {
++ this.firstname = firstname;
++ }
++
++ public String getLastname() {
++ return lastname;
++ }
++
++ public void setLastname(String lastname) {
++ this.lastname = lastname;
++ }
++
++ public int getAge() {
++ return age;
++ }
++
++ public void setAge(int age) {
++ this.age = age;
++ }
++
++ public String getDecimals() {
++ return decimals;
++ }
++
++ public void setDecimals(String decimals) {
++ this.decimals = decimals;
++ }
++
++}
--- /dev/null
- package com.vaadin.tests.data.bean;\r
- \r
- public enum Country {\r
- \r
- FINLAND("Finland"), SWEDEN("Sweden"), USA("USA"), RUSSIA("Russia"), NETHERLANDS(\r
- "Netherlands"), SOUTH_AFRICA("South Africa");\r
- \r
- private String name;\r
- \r
- private Country(String name) {\r
- this.name = name;\r
- }\r
- \r
- @Override\r
- public String toString() {\r
- return name;\r
- }\r
- }\r
++package com.vaadin.tests.data.bean;
++
++public enum Country {
++
++ FINLAND("Finland"), SWEDEN("Sweden"), USA("USA"), RUSSIA("Russia"), NETHERLANDS(
++ "Netherlands"), SOUTH_AFRICA("South Africa");
++
++ private String name;
++
++ private Country(String name) {
++ this.name = name;
++ }
++
++ @Override
++ public String toString() {
++ return name;
++ }
++}
--- /dev/null
- package com.vaadin.tests.data.bean;\r
- \r
- import java.math.BigDecimal;\r
- import java.util.Date;\r
- \r
- public class Person {\r
- private String firstName;\r
- private String lastName;\r
- private String email;\r
- private int age;\r
- private Sex sex;\r
- private Address address;\r
- private boolean deceased;\r
- private Date birthDate;\r
- \r
- private Integer salary; // null if unknown\r
- private Double salaryDouble; // null if unknown\r
- \r
- private BigDecimal rent;\r
- \r
- public Person() {\r
- \r
- }\r
- \r
- @Override\r
- public String toString() {\r
- return "Person [firstName=" + firstName + ", lastName=" + lastName\r
- + ", email=" + email + ", age=" + age + ", sex=" + sex\r
- + ", address=" + address + ", deceased=" + deceased\r
- + ", salary=" + salary + ", salaryDouble=" + salaryDouble\r
- + ", rent=" + rent + "]";\r
- }\r
- \r
- public Person(String firstName, String lastName, String email, int age,\r
- Sex sex, Address address) {\r
- super();\r
- this.firstName = firstName;\r
- this.lastName = lastName;\r
- this.email = email;\r
- this.age = age;\r
- this.sex = sex;\r
- this.address = address;\r
- }\r
- \r
- public String getFirstName() {\r
- return firstName;\r
- }\r
- \r
- public void setFirstName(String firstName) {\r
- this.firstName = firstName;\r
- }\r
- \r
- public String getLastName() {\r
- return lastName;\r
- }\r
- \r
- public void setLastName(String lastName) {\r
- this.lastName = lastName;\r
- }\r
- \r
- public int getAge() {\r
- return age;\r
- }\r
- \r
- public void setAge(int age) {\r
- this.age = age;\r
- }\r
- \r
- public Address getAddress() {\r
- return address;\r
- }\r
- \r
- public void setAddress(Address address) {\r
- this.address = address;\r
- }\r
- \r
- public Sex getSex() {\r
- return sex;\r
- }\r
- \r
- public void setSex(Sex sex) {\r
- this.sex = sex;\r
- }\r
- \r
- public String getEmail() {\r
- return email;\r
- }\r
- \r
- public void setEmail(String email) {\r
- this.email = email;\r
- }\r
- \r
- public boolean getDeceased() {\r
- return deceased;\r
- }\r
- \r
- public void setDeceased(boolean deceased) {\r
- this.deceased = deceased;\r
- }\r
- \r
- public Integer getSalary() {\r
- return salary;\r
- }\r
- \r
- public void setSalary(Integer salary) {\r
- this.salary = salary;\r
- }\r
- \r
- public BigDecimal getRent() {\r
- return rent;\r
- }\r
- \r
- public void setRent(BigDecimal rent) {\r
- this.rent = rent;\r
- }\r
- \r
- public Double getSalaryDouble() {\r
- return salaryDouble;\r
- }\r
- \r
- public void setSalaryDouble(Double salaryDouble) {\r
- this.salaryDouble = salaryDouble;\r
- }\r
- \r
- public Date getBirthDate() {\r
- return birthDate;\r
- }\r
- \r
- public void setBirthDate(Date birthDate) {\r
- this.birthDate = birthDate;\r
- }\r
- \r
- }\r
++package com.vaadin.tests.data.bean;
++
++import java.math.BigDecimal;
++import java.util.Date;
++
++public class Person {
++ private String firstName;
++ private String lastName;
++ private String email;
++ private int age;
++ private Sex sex;
++ private Address address;
++ private boolean deceased;
++ private Date birthDate;
++
++ private Integer salary; // null if unknown
++ private Double salaryDouble; // null if unknown
++
++ private BigDecimal rent;
++
++ public Person() {
++
++ }
++
++ @Override
++ public String toString() {
++ return "Person [firstName=" + firstName + ", lastName=" + lastName
++ + ", email=" + email + ", age=" + age + ", sex=" + sex
++ + ", address=" + address + ", deceased=" + deceased
++ + ", salary=" + salary + ", salaryDouble=" + salaryDouble
++ + ", rent=" + rent + "]";
++ }
++
++ public Person(String firstName, String lastName, String email, int age,
++ Sex sex, Address address) {
++ super();
++ this.firstName = firstName;
++ this.lastName = lastName;
++ this.email = email;
++ this.age = age;
++ this.sex = sex;
++ this.address = address;
++ }
++
++ public String getFirstName() {
++ return firstName;
++ }
++
++ public void setFirstName(String firstName) {
++ this.firstName = firstName;
++ }
++
++ public String getLastName() {
++ return lastName;
++ }
++
++ public void setLastName(String lastName) {
++ this.lastName = lastName;
++ }
++
++ public int getAge() {
++ return age;
++ }
++
++ public void setAge(int age) {
++ this.age = age;
++ }
++
++ public Address getAddress() {
++ return address;
++ }
++
++ public void setAddress(Address address) {
++ this.address = address;
++ }
++
++ public Sex getSex() {
++ return sex;
++ }
++
++ public void setSex(Sex sex) {
++ this.sex = sex;
++ }
++
++ public String getEmail() {
++ return email;
++ }
++
++ public void setEmail(String email) {
++ this.email = email;
++ }
++
++ public boolean getDeceased() {
++ return deceased;
++ }
++
++ public void setDeceased(boolean deceased) {
++ this.deceased = deceased;
++ }
++
++ public Integer getSalary() {
++ return salary;
++ }
++
++ public void setSalary(Integer salary) {
++ this.salary = salary;
++ }
++
++ public BigDecimal getRent() {
++ return rent;
++ }
++
++ public void setRent(BigDecimal rent) {
++ this.rent = rent;
++ }
++
++ public Double getSalaryDouble() {
++ return salaryDouble;
++ }
++
++ public void setSalaryDouble(Double salaryDouble) {
++ this.salaryDouble = salaryDouble;
++ }
++
++ public Date getBirthDate() {
++ return birthDate;
++ }
++
++ public void setBirthDate(Date birthDate) {
++ this.birthDate = birthDate;
++ }
++
++}
--- /dev/null
- package com.vaadin.tests.data.bean;\r
- \r
- import java.math.BigDecimal;\r
- import java.util.Date;\r
- \r
- import javax.validation.constraints.Digits;\r
- import javax.validation.constraints.Max;\r
- import javax.validation.constraints.Min;\r
- import javax.validation.constraints.NotNull;\r
- import javax.validation.constraints.Past;\r
- import javax.validation.constraints.Size;\r
- \r
- public class PersonWithBeanValidationAnnotations {\r
- @NotNull\r
- @Size(min = 5, max = 20)\r
- private String firstName;\r
- @NotNull\r
- private String lastName;\r
- \r
- private String email;\r
- \r
- @Min(0)\r
- @Max(100)\r
- private int age;\r
- \r
- @NotNull\r
- private Sex sex;\r
- \r
- private Address address;\r
- private boolean deceased;\r
- \r
- @NotNull\r
- @Past\r
- private Date birthDate;\r
- \r
- @Min(0)\r
- private Integer salary; // null if unknown\r
- \r
- @Digits(integer = 6, fraction = 2)\r
- private Double salaryDouble; // null if unknown\r
- \r
- private BigDecimal rent;\r
- \r
- public PersonWithBeanValidationAnnotations() {\r
- \r
- }\r
- \r
- @Override\r
- public String toString() {\r
- return "Person [firstName=" + firstName + ", lastName=" + lastName\r
- + ", email=" + email + ", age=" + age + ", sex=" + sex\r
- + ", address=" + address + ", deceased=" + deceased\r
- + ", salary=" + salary + ", salaryDouble=" + salaryDouble\r
- + ", rent=" + rent + "]";\r
- }\r
- \r
- public PersonWithBeanValidationAnnotations(String firstName,\r
- String lastName, String email, int age, Sex sex, Address address) {\r
- super();\r
- this.firstName = firstName;\r
- this.lastName = lastName;\r
- this.email = email;\r
- this.age = age;\r
- this.sex = sex;\r
- this.address = address;\r
- }\r
- \r
- public String getFirstName() {\r
- return firstName;\r
- }\r
- \r
- public void setFirstName(String firstName) {\r
- this.firstName = firstName;\r
- }\r
- \r
- public String getLastName() {\r
- return lastName;\r
- }\r
- \r
- public void setLastName(String lastName) {\r
- this.lastName = lastName;\r
- }\r
- \r
- public int getAge() {\r
- return age;\r
- }\r
- \r
- public void setAge(int age) {\r
- this.age = age;\r
- }\r
- \r
- public Address getAddress() {\r
- return address;\r
- }\r
- \r
- public void setAddress(Address address) {\r
- this.address = address;\r
- }\r
- \r
- public Sex getSex() {\r
- return sex;\r
- }\r
- \r
- public void setSex(Sex sex) {\r
- this.sex = sex;\r
- }\r
- \r
- public String getEmail() {\r
- return email;\r
- }\r
- \r
- public void setEmail(String email) {\r
- this.email = email;\r
- }\r
- \r
- public boolean getDeceased() {\r
- return deceased;\r
- }\r
- \r
- public void setDeceased(boolean deceased) {\r
- this.deceased = deceased;\r
- }\r
- \r
- public Integer getSalary() {\r
- return salary;\r
- }\r
- \r
- public void setSalary(Integer salary) {\r
- this.salary = salary;\r
- }\r
- \r
- public BigDecimal getRent() {\r
- return rent;\r
- }\r
- \r
- public void setRent(BigDecimal rent) {\r
- this.rent = rent;\r
- }\r
- \r
- public Double getSalaryDouble() {\r
- return salaryDouble;\r
- }\r
- \r
- public void setSalaryDouble(Double salaryDouble) {\r
- this.salaryDouble = salaryDouble;\r
- }\r
- \r
- public Date getBirthDate() {\r
- return birthDate;\r
- }\r
- \r
- public void setBirthDate(Date birthDate) {\r
- this.birthDate = birthDate;\r
- }\r
- \r
- }\r
++package com.vaadin.tests.data.bean;
++
++import java.math.BigDecimal;
++import java.util.Date;
++
++import javax.validation.constraints.Digits;
++import javax.validation.constraints.Max;
++import javax.validation.constraints.Min;
++import javax.validation.constraints.NotNull;
++import javax.validation.constraints.Past;
++import javax.validation.constraints.Size;
++
++public class PersonWithBeanValidationAnnotations {
++ @NotNull
++ @Size(min = 5, max = 20)
++ private String firstName;
++ @NotNull
++ private String lastName;
++
++ private String email;
++
++ @Min(0)
++ @Max(100)
++ private int age;
++
++ @NotNull
++ private Sex sex;
++
++ private Address address;
++ private boolean deceased;
++
++ @NotNull
++ @Past
++ private Date birthDate;
++
++ @Min(0)
++ private Integer salary; // null if unknown
++
++ @Digits(integer = 6, fraction = 2)
++ private Double salaryDouble; // null if unknown
++
++ private BigDecimal rent;
++
++ public PersonWithBeanValidationAnnotations() {
++
++ }
++
++ @Override
++ public String toString() {
++ return "Person [firstName=" + firstName + ", lastName=" + lastName
++ + ", email=" + email + ", age=" + age + ", sex=" + sex
++ + ", address=" + address + ", deceased=" + deceased
++ + ", salary=" + salary + ", salaryDouble=" + salaryDouble
++ + ", rent=" + rent + "]";
++ }
++
++ public PersonWithBeanValidationAnnotations(String firstName,
++ String lastName, String email, int age, Sex sex, Address address) {
++ super();
++ this.firstName = firstName;
++ this.lastName = lastName;
++ this.email = email;
++ this.age = age;
++ this.sex = sex;
++ this.address = address;
++ }
++
++ public String getFirstName() {
++ return firstName;
++ }
++
++ public void setFirstName(String firstName) {
++ this.firstName = firstName;
++ }
++
++ public String getLastName() {
++ return lastName;
++ }
++
++ public void setLastName(String lastName) {
++ this.lastName = lastName;
++ }
++
++ public int getAge() {
++ return age;
++ }
++
++ public void setAge(int age) {
++ this.age = age;
++ }
++
++ public Address getAddress() {
++ return address;
++ }
++
++ public void setAddress(Address address) {
++ this.address = address;
++ }
++
++ public Sex getSex() {
++ return sex;
++ }
++
++ public void setSex(Sex sex) {
++ this.sex = sex;
++ }
++
++ public String getEmail() {
++ return email;
++ }
++
++ public void setEmail(String email) {
++ this.email = email;
++ }
++
++ public boolean getDeceased() {
++ return deceased;
++ }
++
++ public void setDeceased(boolean deceased) {
++ this.deceased = deceased;
++ }
++
++ public Integer getSalary() {
++ return salary;
++ }
++
++ public void setSalary(Integer salary) {
++ this.salary = salary;
++ }
++
++ public BigDecimal getRent() {
++ return rent;
++ }
++
++ public void setRent(BigDecimal rent) {
++ this.rent = rent;
++ }
++
++ public Double getSalaryDouble() {
++ return salaryDouble;
++ }
++
++ public void setSalaryDouble(Double salaryDouble) {
++ this.salaryDouble = salaryDouble;
++ }
++
++ public Date getBirthDate() {
++ return birthDate;
++ }
++
++ public void setBirthDate(Date birthDate) {
++ this.birthDate = birthDate;
++ }
++
++}
--- /dev/null
- package com.vaadin.tests.data.bean;\r
- \r
- public enum Sex {\r
- MALE("Male"), FEMALE("Female"), UNKNOWN("Unknown");\r
- \r
- private String stringRepresentation;\r
- \r
- private Sex(String stringRepresentation) {\r
- this.stringRepresentation = stringRepresentation;\r
- }\r
- \r
- public String getStringRepresentation() {\r
- return stringRepresentation;\r
- }\r
- \r
- @Override\r
- public String toString() {\r
- return getStringRepresentation();\r
- }\r
- }\r
++package com.vaadin.tests.data.bean;
++
++public enum Sex {
++ MALE("Male"), FEMALE("Female"), UNKNOWN("Unknown");
++
++ private String stringRepresentation;
++
++ private Sex(String stringRepresentation) {
++ this.stringRepresentation = stringRepresentation;
++ }
++
++ public String getStringRepresentation() {
++ return stringRepresentation;
++ }
++
++ @Override
++ public String toString() {
++ return getStringRepresentation();
++ }
++}
- package com.vaadin.tests.server;\r
- \r
- import static org.easymock.EasyMock.createMock;\r
- \r
- import java.lang.Thread.UncaughtExceptionHandler;\r
- import java.lang.reflect.InvocationTargetException;\r
- import java.lang.reflect.Method;\r
- import java.net.MalformedURLException;\r
- import java.net.URL;\r
- import java.util.ArrayList;\r
- import java.util.Iterator;\r
- import java.util.List;\r
- import java.util.Properties;\r
- import java.util.Random;\r
- \r
- import javax.servlet.http.HttpSession;\r
- \r
- import junit.framework.TestCase;\r
- \r
- import org.easymock.EasyMock;\r
- \r
- import com.vaadin.Application;\r
- import com.vaadin.service.ApplicationContext.TransactionListener;\r
- import com.vaadin.terminal.gwt.server.AbstractWebApplicationContext;\r
- import com.vaadin.terminal.gwt.server.WebApplicationContext;\r
- \r
- public class TransactionListenersConcurrency extends TestCase {\r
- \r
- /**\r
- * This test starts N threads concurrently. Each thread creates an\r
- * application which adds a transaction listener to the context. A\r
- * transaction is then started for each application. Some semi-random delays\r
- * are included so that calls to addTransactionListener and\r
- * WebApplicationContext.startTransaction are mixed.\r
- * \r
- */\r
- public void testTransactionListeners() throws Exception {\r
- final List<Throwable> exceptions = new ArrayList<Throwable>();\r
- \r
- HttpSession session = createSession();\r
- final WebApplicationContext context = WebApplicationContext\r
- .getApplicationContext(session);\r
- List<Thread> threads = new ArrayList<Thread>();\r
- \r
- for (int i = 0; i < 5; i++) {\r
- Thread t = new Thread(new Runnable() {\r
- \r
- public void run() {\r
- Application app = new Application() {\r
- \r
- @Override\r
- public void init() {\r
- // Sleep 0-1000ms so another transaction has time to\r
- // start before we add the transaction listener.\r
- try {\r
- Thread.sleep((long) (1000 * new Random()\r
- .nextDouble()));\r
- } catch (InterruptedException e) {\r
- // TODO Auto-generated catch block\r
- e.printStackTrace();\r
- }\r
- \r
- getContext().addTransactionListener(\r
- new DelayTransactionListener(2000));\r
- }\r
- \r
- };\r
- \r
- // Start the application so the transaction listener is\r
- // called later on.\r
- try {\r
- \r
- app.start(new URL("http://localhost/"),\r
- new Properties(), context, true);\r
- } catch (MalformedURLException e) {\r
- // TODO Auto-generated catch block\r
- e.printStackTrace();\r
- }\r
- \r
- try {\r
- // Call the transaction listener using reflection as\r
- // startTransaction is protected.\r
- \r
- Method m = AbstractWebApplicationContext.class\r
- .getDeclaredMethod("startTransaction",\r
- Application.class, Object.class);\r
- m.setAccessible(true);\r
- m.invoke(context, app, null);\r
- } catch (Exception e) {\r
- throw new RuntimeException(e);\r
- }\r
- }\r
- \r
- });\r
- \r
- threads.add(t);\r
- t.setUncaughtExceptionHandler(new UncaughtExceptionHandler() {\r
- \r
- public void uncaughtException(Thread t, Throwable e) {\r
- e = e.getCause();\r
- exceptions.add(e);\r
- }\r
- });\r
- }\r
- \r
- // Start the threads and wait for all of them to finish\r
- for (Thread t : threads) {\r
- t.start();\r
- }\r
- int running = threads.size();\r
- \r
- while (running > 0) {\r
- for (Iterator<Thread> i = threads.iterator(); i.hasNext();) {\r
- Thread t = i.next();\r
- if (!t.isAlive()) {\r
- running--;\r
- i.remove();\r
- }\r
- }\r
- }\r
- \r
- for (Throwable t : exceptions) {\r
- if (t instanceof InvocationTargetException) {\r
- t = t.getCause();\r
- }\r
- t.printStackTrace(System.err);\r
- fail(t.getClass().getName());\r
- }\r
- \r
- System.out.println("Done, all ok");\r
- \r
- }\r
- \r
- /**\r
- * Creates a HttpSession mock\r
- * \r
- */\r
- private static HttpSession createSession() {\r
- HttpSession session = createMock(HttpSession.class);\r
- EasyMock.expect(\r
- session.getAttribute(WebApplicationContext.class.getName()))\r
- .andReturn(null).anyTimes();\r
- session.setAttribute(\r
- EasyMock.eq(WebApplicationContext.class.getName()),\r
- EasyMock.anyObject());\r
- \r
- EasyMock.replay(session);\r
- return session;\r
- }\r
- \r
- /**\r
- * A transaction listener that just sleeps for the given amount of time in\r
- * transactionStart and transactionEnd.\r
- * \r
- */\r
- public static class DelayTransactionListener implements TransactionListener {\r
- \r
- private int delay;\r
- \r
- public DelayTransactionListener(int delay) {\r
- this.delay = delay;\r
- }\r
- \r
- public void transactionStart(Application application,\r
- Object transactionData) {\r
- try {\r
- Thread.sleep(delay);\r
- } catch (InterruptedException e) {\r
- e.printStackTrace();\r
- }\r
- \r
- }\r
- \r
- public void transactionEnd(Application application,\r
- Object transactionData) {\r
- try {\r
- Thread.sleep(delay);\r
- } catch (InterruptedException e) {\r
- e.printStackTrace();\r
- }\r
- \r
- }\r
- }\r
- \r
- }\r
+ package com.vaadin.tests.server;
+
+ import static org.easymock.EasyMock.createMock;
+
+ import java.lang.Thread.UncaughtExceptionHandler;
+ import java.lang.reflect.InvocationTargetException;
+ import java.lang.reflect.Method;
+ import java.net.MalformedURLException;
+ import java.net.URL;
+ import java.util.ArrayList;
+ import java.util.Iterator;
+ import java.util.List;
+ import java.util.Properties;
+ import java.util.Random;
+
+ import javax.servlet.http.HttpSession;
+
+ import junit.framework.TestCase;
+
+ import org.easymock.EasyMock;
+
+ import com.vaadin.Application;
+ import com.vaadin.service.ApplicationContext.TransactionListener;
+ import com.vaadin.terminal.gwt.server.AbstractWebApplicationContext;
+ import com.vaadin.terminal.gwt.server.WebApplicationContext;
+
+ public class TransactionListenersConcurrency extends TestCase {
+
+ /**
+ * This test starts N threads concurrently. Each thread creates an
+ * application which adds a transaction listener to the context. A
+ * transaction is then started for each application. Some semi-random delays
+ * are included so that calls to addTransactionListener and
+ * WebApplicationContext.startTransaction are mixed.
+ *
+ */
+ public void testTransactionListeners() throws Exception {
+ final List<Throwable> exceptions = new ArrayList<Throwable>();
+
+ HttpSession session = createSession();
+ final WebApplicationContext context = WebApplicationContext
+ .getApplicationContext(session);
+ List<Thread> threads = new ArrayList<Thread>();
+
+ for (int i = 0; i < 5; i++) {
+ Thread t = new Thread(new Runnable() {
+
+ public void run() {
+ Application app = new Application() {
+
+ @Override
+ public void init() {
+ // Sleep 0-1000ms so another transaction has time to
+ // start before we add the transaction listener.
+ try {
+ Thread.sleep((long) (1000 * new Random()
+ .nextDouble()));
+ } catch (InterruptedException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+
+ getContext().addTransactionListener(
+ new DelayTransactionListener(2000));
+ }
+
+ };
+
+ // Start the application so the transaction listener is
+ // called later on.
+ try {
+
+ app.start(new URL("http://localhost/"),
- new Properties(), context);
++ new Properties(), context, true);
+ } catch (MalformedURLException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+
+ try {
+ // Call the transaction listener using reflection as
+ // startTransaction is protected.
+
+ Method m = AbstractWebApplicationContext.class
+ .getDeclaredMethod("startTransaction",
+ Application.class, Object.class);
+ m.setAccessible(true);
+ m.invoke(context, app, null);
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ });
+
+ threads.add(t);
+ t.setUncaughtExceptionHandler(new UncaughtExceptionHandler() {
+
+ public void uncaughtException(Thread t, Throwable e) {
+ e = e.getCause();
+ exceptions.add(e);
+ }
+ });
+ }
+
+ // Start the threads and wait for all of them to finish
+ for (Thread t : threads) {
+ t.start();
+ }
+ int running = threads.size();
+
+ while (running > 0) {
+ for (Iterator<Thread> i = threads.iterator(); i.hasNext();) {
+ Thread t = i.next();
+ if (!t.isAlive()) {
+ running--;
+ i.remove();
+ }
+ }
+ }
+
+ for (Throwable t : exceptions) {
+ if (t instanceof InvocationTargetException) {
+ t = t.getCause();
+ }
+ t.printStackTrace(System.err);
+ fail(t.getClass().getName());
+ }
+
+ System.out.println("Done, all ok");
+
+ }
+
+ /**
+ * Creates a HttpSession mock
+ *
+ */
+ private static HttpSession createSession() {
+ HttpSession session = createMock(HttpSession.class);
+ EasyMock.expect(
+ session.getAttribute(WebApplicationContext.class.getName()))
+ .andReturn(null).anyTimes();
+ session.setAttribute(
+ EasyMock.eq(WebApplicationContext.class.getName()),
+ EasyMock.anyObject());
+
+ EasyMock.replay(session);
+ return session;
+ }
+
+ /**
+ * A transaction listener that just sleeps for the given amount of time in
+ * transactionStart and transactionEnd.
+ *
+ */
+ public static class DelayTransactionListener implements TransactionListener {
+
+ private int delay;
+
+ public DelayTransactionListener(int delay) {
+ this.delay = delay;
+ }
+
+ public void transactionStart(Application application,
+ Object transactionData) {
+ try {
+ Thread.sleep(delay);
+ } catch (InterruptedException e) {
+ e.printStackTrace();
+ }
+
+ }
+
+ public void transactionEnd(Application application,
+ Object transactionData) {
+ try {
+ Thread.sleep(delay);
+ } catch (InterruptedException e) {
+ e.printStackTrace();
+ }
+
+ }
+ }
+
+ }
- package com.vaadin.tests.server.component.absolutelayout;\r
- \r
- import junit.framework.TestCase;\r
- \r
- import com.vaadin.terminal.Sizeable;\r
- import com.vaadin.terminal.Sizeable.Unit;\r
- import com.vaadin.ui.AbsoluteLayout;\r
- import com.vaadin.ui.Button;\r
- \r
- public class ComponentPosition extends TestCase {\r
- \r
- private static final String CSS = "top:7.0px;right:7.0%;bottom:7.0pc;left:7.0em;z-index:7;";\r
- private static final String PARTIAL_CSS = "top:7.0px;left:7.0em;";\r
- private static final Float CSS_VALUE = Float.valueOf(7);\r
- \r
- private static final Unit UNIT_UNSET = Sizeable.Unit.PIXELS;\r
- \r
- /**\r
- * Add component w/o giving positions, assert that everything is unset\r
- */\r
- public void testNoPosition() {\r
- AbsoluteLayout layout = new AbsoluteLayout();\r
- Button b = new Button();\r
- layout.addComponent(b);\r
- \r
- assertNull(layout.getPosition(b).getTopValue());\r
- assertNull(layout.getPosition(b).getBottomValue());\r
- assertNull(layout.getPosition(b).getLeftValue());\r
- assertNull(layout.getPosition(b).getRightValue());\r
- \r
- assertEquals(UNIT_UNSET, layout.getPosition(b).getTopUnits());\r
- assertEquals(UNIT_UNSET, layout.getPosition(b).getBottomUnits());\r
- assertEquals(UNIT_UNSET, layout.getPosition(b).getLeftUnits());\r
- assertEquals(UNIT_UNSET, layout.getPosition(b).getRightUnits());\r
- \r
- assertEquals(-1, layout.getPosition(b).getZIndex());\r
- \r
- assertEquals("", layout.getPosition(b).getCSSString());\r
- \r
- }\r
- \r
- /**\r
- * Add component, setting all attributes using CSS, assert getter agree\r
- */\r
- public void testFullCss() {\r
- AbsoluteLayout layout = new AbsoluteLayout();\r
- Button b = new Button();\r
- layout.addComponent(b, CSS);\r
- \r
- assertEquals(CSS_VALUE, layout.getPosition(b).getTopValue());\r
- assertEquals(CSS_VALUE, layout.getPosition(b).getBottomValue());\r
- assertEquals(CSS_VALUE, layout.getPosition(b).getLeftValue());\r
- assertEquals(CSS_VALUE, layout.getPosition(b).getRightValue());\r
- \r
- assertEquals(Sizeable.Unit.PIXELS, layout.getPosition(b).getTopUnits());\r
- assertEquals(Sizeable.Unit.PICAS, layout.getPosition(b)\r
- .getBottomUnits());\r
- assertEquals(Sizeable.Unit.EM, layout.getPosition(b).getLeftUnits());\r
- assertEquals(Sizeable.Unit.PERCENTAGE, layout.getPosition(b)\r
- .getRightUnits());\r
- \r
- assertEquals(7, layout.getPosition(b).getZIndex());\r
- \r
- assertEquals(CSS, layout.getPosition(b).getCSSString());\r
- \r
- }\r
- \r
- /**\r
- * Add component, setting some attributes using CSS, assert getters agree\r
- */\r
- public void testPartialCss() {\r
- AbsoluteLayout layout = new AbsoluteLayout();\r
- Button b = new Button();\r
- layout.addComponent(b, PARTIAL_CSS);\r
- \r
- assertEquals(CSS_VALUE, layout.getPosition(b).getTopValue());\r
- assertNull(layout.getPosition(b).getBottomValue());\r
- assertEquals(CSS_VALUE, layout.getPosition(b).getLeftValue());\r
- assertNull(layout.getPosition(b).getRightValue());\r
- \r
- assertEquals(Sizeable.Unit.PIXELS, layout.getPosition(b).getTopUnits());\r
- assertEquals(UNIT_UNSET, layout.getPosition(b).getBottomUnits());\r
- assertEquals(Sizeable.Unit.EM, layout.getPosition(b).getLeftUnits());\r
- assertEquals(UNIT_UNSET, layout.getPosition(b).getRightUnits());\r
- \r
- assertEquals(-1, layout.getPosition(b).getZIndex());\r
- \r
- assertEquals(PARTIAL_CSS, layout.getPosition(b).getCSSString());\r
- \r
- }\r
- \r
- /**\r
- * Add component setting all attributes using CSS, then reset using partial\r
- * CSS; assert getters agree and the appropriate attributes are unset.\r
- */\r
- public void testPartialCssReset() {\r
- AbsoluteLayout layout = new AbsoluteLayout();\r
- Button b = new Button();\r
- layout.addComponent(b, CSS);\r
- \r
- layout.getPosition(b).setCSSString(PARTIAL_CSS);\r
- \r
- assertEquals(CSS_VALUE, layout.getPosition(b).getTopValue());\r
- assertNull(layout.getPosition(b).getBottomValue());\r
- assertEquals(CSS_VALUE, layout.getPosition(b).getLeftValue());\r
- assertNull(layout.getPosition(b).getRightValue());\r
- \r
- assertEquals(Sizeable.Unit.PIXELS, layout.getPosition(b).getTopUnits());\r
- assertEquals(UNIT_UNSET, layout.getPosition(b).getBottomUnits());\r
- assertEquals(Sizeable.Unit.EM, layout.getPosition(b).getLeftUnits());\r
- assertEquals(UNIT_UNSET, layout.getPosition(b).getRightUnits());\r
- \r
- assertEquals(-1, layout.getPosition(b).getZIndex());\r
- \r
- assertEquals(PARTIAL_CSS, layout.getPosition(b).getCSSString());\r
- \r
- }\r
- \r
- /**\r
- * Add component, then set all position attributes with individual setters\r
- * for value and units; assert getters agree.\r
- */\r
- public void testSetPosition() {\r
- final Float SIZE = Float.valueOf(12);\r
- \r
- AbsoluteLayout layout = new AbsoluteLayout();\r
- Button b = new Button();\r
- layout.addComponent(b);\r
- \r
- layout.getPosition(b).setTopValue(SIZE);\r
- layout.getPosition(b).setRightValue(SIZE);\r
- layout.getPosition(b).setBottomValue(SIZE);\r
- layout.getPosition(b).setLeftValue(SIZE);\r
- \r
- layout.getPosition(b).setTopUnits(Sizeable.Unit.CM);\r
- layout.getPosition(b).setRightUnits(Sizeable.Unit.EX);\r
- layout.getPosition(b).setBottomUnits(Sizeable.Unit.INCH);\r
- layout.getPosition(b).setLeftUnits(Sizeable.Unit.MM);\r
- \r
- assertEquals(SIZE, layout.getPosition(b).getTopValue());\r
- assertEquals(SIZE, layout.getPosition(b).getRightValue());\r
- assertEquals(SIZE, layout.getPosition(b).getBottomValue());\r
- assertEquals(SIZE, layout.getPosition(b).getLeftValue());\r
- \r
- assertEquals(Sizeable.Unit.CM, layout.getPosition(b).getTopUnits());\r
- assertEquals(Sizeable.Unit.EX, layout.getPosition(b).getRightUnits());\r
- assertEquals(Sizeable.Unit.INCH, layout.getPosition(b).getBottomUnits());\r
- assertEquals(Sizeable.Unit.MM, layout.getPosition(b).getLeftUnits());\r
- \r
- }\r
- \r
- /**\r
- * Add component, then set all position attributes with combined setters for\r
- * value and units; assert getters agree.\r
- */\r
- public void testSetPosition2() {\r
- final Float SIZE = Float.valueOf(12);\r
- AbsoluteLayout layout = new AbsoluteLayout();\r
- Button b = new Button();\r
- layout.addComponent(b);\r
- \r
- layout.getPosition(b).setTop(SIZE, Sizeable.Unit.CM);\r
- layout.getPosition(b).setRight(SIZE, Sizeable.Unit.EX);\r
- layout.getPosition(b).setBottom(SIZE, Sizeable.Unit.INCH);\r
- layout.getPosition(b).setLeft(SIZE, Sizeable.Unit.MM);\r
- \r
- assertEquals(SIZE, layout.getPosition(b).getTopValue());\r
- assertEquals(SIZE, layout.getPosition(b).getRightValue());\r
- assertEquals(SIZE, layout.getPosition(b).getBottomValue());\r
- assertEquals(SIZE, layout.getPosition(b).getLeftValue());\r
- \r
- assertEquals(Sizeable.Unit.CM, layout.getPosition(b).getTopUnits());\r
- assertEquals(Sizeable.Unit.EX, layout.getPosition(b).getRightUnits());\r
- assertEquals(Sizeable.Unit.INCH, layout.getPosition(b).getBottomUnits());\r
- assertEquals(Sizeable.Unit.MM, layout.getPosition(b).getLeftUnits());\r
- \r
- }\r
- \r
- /**\r
- * Add component, set all attributes using CSS, unset some using method\r
- * calls, assert getters agree.\r
- */\r
- public void testUnsetPosition() {\r
- AbsoluteLayout layout = new AbsoluteLayout();\r
- Button b = new Button();\r
- layout.addComponent(b, CSS);\r
- \r
- layout.getPosition(b).setTopValue(null);\r
- layout.getPosition(b).setRightValue(null);\r
- layout.getPosition(b).setBottomValue(null);\r
- layout.getPosition(b).setLeftValue(null);\r
- \r
- layout.getPosition(b).setZIndex(-1);\r
- \r
- assertNull(layout.getPosition(b).getTopValue());\r
- assertNull(layout.getPosition(b).getBottomValue());\r
- assertNull(layout.getPosition(b).getLeftValue());\r
- assertNull(layout.getPosition(b).getRightValue());\r
- \r
- assertEquals("", layout.getPosition(b).getCSSString());\r
- \r
- }\r
- \r
- }\r
+ package com.vaadin.tests.server.component.absolutelayout;
+
+ import junit.framework.TestCase;
+
+ import com.vaadin.terminal.Sizeable;
++import com.vaadin.terminal.Sizeable.Unit;
+ import com.vaadin.ui.AbsoluteLayout;
+ import com.vaadin.ui.Button;
+
+ public class ComponentPosition extends TestCase {
+
+ private static final String CSS = "top:7.0px;right:7.0%;bottom:7.0pc;left:7.0em;z-index:7;";
+ private static final String PARTIAL_CSS = "top:7.0px;left:7.0em;";
+ private static final Float CSS_VALUE = Float.valueOf(7);
+
- private static final int UNIT_UNSET = Sizeable.UNITS_PIXELS;
++ private static final Unit UNIT_UNSET = Sizeable.Unit.PIXELS;
+
+ /**
+ * Add component w/o giving positions, assert that everything is unset
+ */
+ public void testNoPosition() {
+ AbsoluteLayout layout = new AbsoluteLayout();
+ Button b = new Button();
+ layout.addComponent(b);
+
+ assertNull(layout.getPosition(b).getTopValue());
+ assertNull(layout.getPosition(b).getBottomValue());
+ assertNull(layout.getPosition(b).getLeftValue());
+ assertNull(layout.getPosition(b).getRightValue());
+
+ assertEquals(UNIT_UNSET, layout.getPosition(b).getTopUnits());
+ assertEquals(UNIT_UNSET, layout.getPosition(b).getBottomUnits());
+ assertEquals(UNIT_UNSET, layout.getPosition(b).getLeftUnits());
+ assertEquals(UNIT_UNSET, layout.getPosition(b).getRightUnits());
+
+ assertEquals(-1, layout.getPosition(b).getZIndex());
+
+ assertEquals("", layout.getPosition(b).getCSSString());
+
+ }
+
+ /**
+ * Add component, setting all attributes using CSS, assert getter agree
+ */
+ public void testFullCss() {
+ AbsoluteLayout layout = new AbsoluteLayout();
+ Button b = new Button();
+ layout.addComponent(b, CSS);
+
+ assertEquals(CSS_VALUE, layout.getPosition(b).getTopValue());
+ assertEquals(CSS_VALUE, layout.getPosition(b).getBottomValue());
+ assertEquals(CSS_VALUE, layout.getPosition(b).getLeftValue());
+ assertEquals(CSS_VALUE, layout.getPosition(b).getRightValue());
+
- assertEquals(Sizeable.UNITS_PIXELS, layout.getPosition(b).getTopUnits());
- assertEquals(Sizeable.UNITS_PICAS, layout.getPosition(b)
++ assertEquals(Sizeable.Unit.PIXELS, layout.getPosition(b).getTopUnits());
++ assertEquals(Sizeable.Unit.PICAS, layout.getPosition(b)
+ .getBottomUnits());
- assertEquals(Sizeable.UNITS_EM, layout.getPosition(b).getLeftUnits());
- assertEquals(Sizeable.UNITS_PERCENTAGE, layout.getPosition(b)
++ assertEquals(Sizeable.Unit.EM, layout.getPosition(b).getLeftUnits());
++ assertEquals(Sizeable.Unit.PERCENTAGE, layout.getPosition(b)
+ .getRightUnits());
+
+ assertEquals(7, layout.getPosition(b).getZIndex());
+
+ assertEquals(CSS, layout.getPosition(b).getCSSString());
+
+ }
+
+ /**
+ * Add component, setting some attributes using CSS, assert getters agree
+ */
+ public void testPartialCss() {
+ AbsoluteLayout layout = new AbsoluteLayout();
+ Button b = new Button();
+ layout.addComponent(b, PARTIAL_CSS);
+
+ assertEquals(CSS_VALUE, layout.getPosition(b).getTopValue());
+ assertNull(layout.getPosition(b).getBottomValue());
+ assertEquals(CSS_VALUE, layout.getPosition(b).getLeftValue());
+ assertNull(layout.getPosition(b).getRightValue());
+
- assertEquals(Sizeable.UNITS_PIXELS, layout.getPosition(b).getTopUnits());
++ assertEquals(Sizeable.Unit.PIXELS, layout.getPosition(b).getTopUnits());
+ assertEquals(UNIT_UNSET, layout.getPosition(b).getBottomUnits());
- assertEquals(Sizeable.UNITS_EM, layout.getPosition(b).getLeftUnits());
++ assertEquals(Sizeable.Unit.EM, layout.getPosition(b).getLeftUnits());
+ assertEquals(UNIT_UNSET, layout.getPosition(b).getRightUnits());
+
+ assertEquals(-1, layout.getPosition(b).getZIndex());
+
+ assertEquals(PARTIAL_CSS, layout.getPosition(b).getCSSString());
+
+ }
+
+ /**
+ * Add component setting all attributes using CSS, then reset using partial
+ * CSS; assert getters agree and the appropriate attributes are unset.
+ */
+ public void testPartialCssReset() {
+ AbsoluteLayout layout = new AbsoluteLayout();
+ Button b = new Button();
+ layout.addComponent(b, CSS);
+
+ layout.getPosition(b).setCSSString(PARTIAL_CSS);
+
+ assertEquals(CSS_VALUE, layout.getPosition(b).getTopValue());
+ assertNull(layout.getPosition(b).getBottomValue());
+ assertEquals(CSS_VALUE, layout.getPosition(b).getLeftValue());
+ assertNull(layout.getPosition(b).getRightValue());
+
- assertEquals(Sizeable.UNITS_PIXELS, layout.getPosition(b).getTopUnits());
++ assertEquals(Sizeable.Unit.PIXELS, layout.getPosition(b).getTopUnits());
+ assertEquals(UNIT_UNSET, layout.getPosition(b).getBottomUnits());
- assertEquals(Sizeable.UNITS_EM, layout.getPosition(b).getLeftUnits());
++ assertEquals(Sizeable.Unit.EM, layout.getPosition(b).getLeftUnits());
+ assertEquals(UNIT_UNSET, layout.getPosition(b).getRightUnits());
+
+ assertEquals(-1, layout.getPosition(b).getZIndex());
+
+ assertEquals(PARTIAL_CSS, layout.getPosition(b).getCSSString());
+
+ }
+
+ /**
+ * Add component, then set all position attributes with individual setters
+ * for value and units; assert getters agree.
+ */
+ public void testSetPosition() {
+ final Float SIZE = Float.valueOf(12);
+
+ AbsoluteLayout layout = new AbsoluteLayout();
+ Button b = new Button();
+ layout.addComponent(b);
+
+ layout.getPosition(b).setTopValue(SIZE);
+ layout.getPosition(b).setRightValue(SIZE);
+ layout.getPosition(b).setBottomValue(SIZE);
+ layout.getPosition(b).setLeftValue(SIZE);
+
- layout.getPosition(b).setTopUnits(Sizeable.UNITS_CM);
- layout.getPosition(b).setRightUnits(Sizeable.UNITS_EX);
- layout.getPosition(b).setBottomUnits(Sizeable.UNITS_INCH);
- layout.getPosition(b).setLeftUnits(Sizeable.UNITS_MM);
++ layout.getPosition(b).setTopUnits(Sizeable.Unit.CM);
++ layout.getPosition(b).setRightUnits(Sizeable.Unit.EX);
++ layout.getPosition(b).setBottomUnits(Sizeable.Unit.INCH);
++ layout.getPosition(b).setLeftUnits(Sizeable.Unit.MM);
+
+ assertEquals(SIZE, layout.getPosition(b).getTopValue());
+ assertEquals(SIZE, layout.getPosition(b).getRightValue());
+ assertEquals(SIZE, layout.getPosition(b).getBottomValue());
+ assertEquals(SIZE, layout.getPosition(b).getLeftValue());
+
- assertEquals(Sizeable.UNITS_CM, layout.getPosition(b).getTopUnits());
- assertEquals(Sizeable.UNITS_EX, layout.getPosition(b).getRightUnits());
- assertEquals(Sizeable.UNITS_INCH, layout.getPosition(b)
- .getBottomUnits());
- assertEquals(Sizeable.UNITS_MM, layout.getPosition(b).getLeftUnits());
++ assertEquals(Sizeable.Unit.CM, layout.getPosition(b).getTopUnits());
++ assertEquals(Sizeable.Unit.EX, layout.getPosition(b).getRightUnits());
++ assertEquals(Sizeable.Unit.INCH, layout.getPosition(b).getBottomUnits());
++ assertEquals(Sizeable.Unit.MM, layout.getPosition(b).getLeftUnits());
+
+ }
+
+ /**
+ * Add component, then set all position attributes with combined setters for
+ * value and units; assert getters agree.
+ */
+ public void testSetPosition2() {
+ final Float SIZE = Float.valueOf(12);
+ AbsoluteLayout layout = new AbsoluteLayout();
+ Button b = new Button();
+ layout.addComponent(b);
+
- layout.getPosition(b).setTop(SIZE, Sizeable.UNITS_CM);
- layout.getPosition(b).setRight(SIZE, Sizeable.UNITS_EX);
- layout.getPosition(b).setBottom(SIZE, Sizeable.UNITS_INCH);
- layout.getPosition(b).setLeft(SIZE, Sizeable.UNITS_MM);
++ layout.getPosition(b).setTop(SIZE, Sizeable.Unit.CM);
++ layout.getPosition(b).setRight(SIZE, Sizeable.Unit.EX);
++ layout.getPosition(b).setBottom(SIZE, Sizeable.Unit.INCH);
++ layout.getPosition(b).setLeft(SIZE, Sizeable.Unit.MM);
+
+ assertEquals(SIZE, layout.getPosition(b).getTopValue());
+ assertEquals(SIZE, layout.getPosition(b).getRightValue());
+ assertEquals(SIZE, layout.getPosition(b).getBottomValue());
+ assertEquals(SIZE, layout.getPosition(b).getLeftValue());
+
- assertEquals(Sizeable.UNITS_CM, layout.getPosition(b).getTopUnits());
- assertEquals(Sizeable.UNITS_EX, layout.getPosition(b).getRightUnits());
- assertEquals(Sizeable.UNITS_INCH, layout.getPosition(b)
- .getBottomUnits());
- assertEquals(Sizeable.UNITS_MM, layout.getPosition(b).getLeftUnits());
++ assertEquals(Sizeable.Unit.CM, layout.getPosition(b).getTopUnits());
++ assertEquals(Sizeable.Unit.EX, layout.getPosition(b).getRightUnits());
++ assertEquals(Sizeable.Unit.INCH, layout.getPosition(b).getBottomUnits());
++ assertEquals(Sizeable.Unit.MM, layout.getPosition(b).getLeftUnits());
+
+ }
+
+ /**
+ * Add component, set all attributes using CSS, unset some using method
+ * calls, assert getters agree.
+ */
+ public void testUnsetPosition() {
+ AbsoluteLayout layout = new AbsoluteLayout();
+ Button b = new Button();
+ layout.addComponent(b, CSS);
+
+ layout.getPosition(b).setTopValue(null);
+ layout.getPosition(b).setRightValue(null);
+ layout.getPosition(b).setBottomValue(null);
+ layout.getPosition(b).setLeftValue(null);
+
+ layout.getPosition(b).setZIndex(-1);
+
+ assertNull(layout.getPosition(b).getTopValue());
+ assertNull(layout.getPosition(b).getBottomValue());
+ assertNull(layout.getPosition(b).getLeftValue());
+ assertNull(layout.getPosition(b).getRightValue());
+
+ assertEquals("", layout.getPosition(b).getCSSString());
+
+ }
+
+ }
--- /dev/null
- package com.vaadin.tests.server.component.abstractfield;\r
- \r
- import java.util.Locale;\r
- \r
- import junit.framework.TestCase;\r
- \r
- import com.vaadin.data.util.MethodProperty;\r
- import com.vaadin.data.util.converter.Converter;\r
- import com.vaadin.data.util.converter.StringToIntegerConverter;\r
- import com.vaadin.tests.data.bean.Address;\r
- import com.vaadin.tests.data.bean.Country;\r
- import com.vaadin.tests.data.bean.Person;\r
- import com.vaadin.tests.data.bean.Sex;\r
- import com.vaadin.ui.CheckBox;\r
- import com.vaadin.ui.TextField;\r
- \r
- public class AbstractFieldValueConversions extends TestCase {\r
- \r
- Person paulaBean = new Person("Paula", "Brilliant", "paula@brilliant.com",\r
- 34, Sex.FEMALE, new Address("Paula street 1", 12345, "P-town",\r
- Country.FINLAND));\r
- \r
- public void testWithoutConversion() {\r
- TextField tf = new TextField();\r
- tf.setPropertyDataSource(new MethodProperty<String>(paulaBean,\r
- "firstName"));\r
- assertEquals("Paula", tf.getValue());\r
- assertEquals("Paula", tf.getPropertyDataSource().getValue());\r
- tf.setValue("abc");\r
- assertEquals("abc", tf.getValue());\r
- assertEquals("abc", tf.getPropertyDataSource().getValue());\r
- assertEquals("abc", paulaBean.getFirstName());\r
- }\r
- \r
- public void testStringIdentityConversion() {\r
- TextField tf = new TextField();\r
- tf.setConverter(new Converter<String, String>() {\r
- \r
- public String convertToModel(String value, Locale locale) {\r
- return value;\r
- }\r
- \r
- public String convertToPresentation(String value, Locale locale) {\r
- return value;\r
- }\r
- \r
- public Class<String> getModelType() {\r
- return String.class;\r
- }\r
- \r
- public Class<String> getPresentationType() {\r
- return String.class;\r
- }\r
- });\r
- tf.setPropertyDataSource(new MethodProperty<String>(paulaBean,\r
- "firstName"));\r
- assertEquals("Paula", tf.getValue());\r
- assertEquals("Paula", tf.getPropertyDataSource().getValue());\r
- tf.setValue("abc");\r
- assertEquals("abc", tf.getValue());\r
- assertEquals("abc", tf.getPropertyDataSource().getValue());\r
- assertEquals("abc", paulaBean.getFirstName());\r
- }\r
- \r
- public void testFailingConversion() {\r
- TextField tf = new TextField();\r
- tf.setConverter(new Converter<String, Integer>() {\r
- \r
- public Integer convertToModel(String value, Locale locale) {\r
- throw new ConversionException("Failed");\r
- }\r
- \r
- public String convertToPresentation(Integer value, Locale locale) {\r
- throw new ConversionException("Failed");\r
- }\r
- \r
- public Class<Integer> getModelType() {\r
- // TODO Auto-generated method stub\r
- return null;\r
- }\r
- \r
- public Class<String> getPresentationType() {\r
- // TODO Auto-generated method stub\r
- return null;\r
- }\r
- });\r
- try {\r
- tf.setValue(1);\r
- fail("setValue(Integer) should throw an exception");\r
- } catch (Converter.ConversionException e) {\r
- // OK, expected\r
- }\r
- }\r
- \r
- public void testIntegerStringConversion() {\r
- TextField tf = new TextField();\r
- \r
- tf.setConverter(new StringToIntegerConverter());\r
- tf.setPropertyDataSource(new MethodProperty<Integer>(paulaBean, "age"));\r
- assertEquals(34, tf.getPropertyDataSource().getValue());\r
- assertEquals("34", tf.getValue());\r
- tf.setValue("12");\r
- assertEquals(12, tf.getPropertyDataSource().getValue());\r
- assertEquals("12", tf.getValue());\r
- tf.getPropertyDataSource().setValue(42);\r
- assertEquals(42, tf.getPropertyDataSource().getValue());\r
- assertEquals("42", tf.getValue());\r
- }\r
- \r
- public void testBooleanNullConversion() {\r
- CheckBox cb = new CheckBox();\r
- cb.setConverter(new Converter<Boolean, Boolean>() {\r
- \r
- public Boolean convertToModel(Boolean value, Locale locale) {\r
- // value from a CheckBox should never be null as long as it is\r
- // not set to null (handled by conversion below).\r
- assertNotNull(value);\r
- return value;\r
- }\r
- \r
- public Boolean convertToPresentation(Boolean value, Locale locale) {\r
- // Datamodel -> field\r
- if (value == null) {\r
- return false;\r
- }\r
- \r
- return value;\r
- }\r
- \r
- public Class<Boolean> getModelType() {\r
- return Boolean.class;\r
- }\r
- \r
- public Class<Boolean> getPresentationType() {\r
- return Boolean.class;\r
- }\r
- \r
- });\r
- MethodProperty<Boolean> property = new MethodProperty<Boolean>(\r
- paulaBean, "deceased");\r
- cb.setPropertyDataSource(property);\r
- assertEquals(Boolean.FALSE, property.getValue());\r
- assertEquals(Boolean.FALSE, cb.getValue());\r
- Boolean newDmValue = cb.getConverter().convertToPresentation(\r
- cb.getValue(), new Locale("fi", "FI"));\r
- assertEquals(Boolean.FALSE, newDmValue);\r
- \r
- // FIXME: Should be able to set to false here to cause datamodel to be\r
- // set to false but the change will not be propagated to the Property\r
- // (field value is already false)\r
- \r
- cb.setValue(true);\r
- assertEquals(Boolean.TRUE, cb.getValue());\r
- assertEquals(Boolean.TRUE, property.getValue());\r
- \r
- cb.setValue(false);\r
- assertEquals(Boolean.FALSE, cb.getValue());\r
- assertEquals(Boolean.FALSE, property.getValue());\r
- \r
- }\r
- \r
- }\r
++package com.vaadin.tests.server.component.abstractfield;
++
++import java.util.Locale;
++
++import junit.framework.TestCase;
++
++import com.vaadin.data.util.MethodProperty;
++import com.vaadin.data.util.converter.Converter;
++import com.vaadin.data.util.converter.StringToIntegerConverter;
++import com.vaadin.tests.data.bean.Address;
++import com.vaadin.tests.data.bean.Country;
++import com.vaadin.tests.data.bean.Person;
++import com.vaadin.tests.data.bean.Sex;
++import com.vaadin.ui.CheckBox;
++import com.vaadin.ui.TextField;
++
++public class AbstractFieldValueConversions extends TestCase {
++
++ Person paulaBean = new Person("Paula", "Brilliant", "paula@brilliant.com",
++ 34, Sex.FEMALE, new Address("Paula street 1", 12345, "P-town",
++ Country.FINLAND));
++
++ public void testWithoutConversion() {
++ TextField tf = new TextField();
++ tf.setPropertyDataSource(new MethodProperty<String>(paulaBean,
++ "firstName"));
++ assertEquals("Paula", tf.getValue());
++ assertEquals("Paula", tf.getPropertyDataSource().getValue());
++ tf.setValue("abc");
++ assertEquals("abc", tf.getValue());
++ assertEquals("abc", tf.getPropertyDataSource().getValue());
++ assertEquals("abc", paulaBean.getFirstName());
++ }
++
++ public void testStringIdentityConversion() {
++ TextField tf = new TextField();
++ tf.setConverter(new Converter<String, String>() {
++
++ public String convertToModel(String value, Locale locale) {
++ return value;
++ }
++
++ public String convertToPresentation(String value, Locale locale) {
++ return value;
++ }
++
++ public Class<String> getModelType() {
++ return String.class;
++ }
++
++ public Class<String> getPresentationType() {
++ return String.class;
++ }
++ });
++ tf.setPropertyDataSource(new MethodProperty<String>(paulaBean,
++ "firstName"));
++ assertEquals("Paula", tf.getValue());
++ assertEquals("Paula", tf.getPropertyDataSource().getValue());
++ tf.setValue("abc");
++ assertEquals("abc", tf.getValue());
++ assertEquals("abc", tf.getPropertyDataSource().getValue());
++ assertEquals("abc", paulaBean.getFirstName());
++ }
++
++ public void testFailingConversion() {
++ TextField tf = new TextField();
++ tf.setConverter(new Converter<String, Integer>() {
++
++ public Integer convertToModel(String value, Locale locale) {
++ throw new ConversionException("Failed");
++ }
++
++ public String convertToPresentation(Integer value, Locale locale) {
++ throw new ConversionException("Failed");
++ }
++
++ public Class<Integer> getModelType() {
++ // TODO Auto-generated method stub
++ return null;
++ }
++
++ public Class<String> getPresentationType() {
++ // TODO Auto-generated method stub
++ return null;
++ }
++ });
++ try {
++ tf.setValue(1);
++ fail("setValue(Integer) should throw an exception");
++ } catch (Converter.ConversionException e) {
++ // OK, expected
++ }
++ }
++
++ public void testIntegerStringConversion() {
++ TextField tf = new TextField();
++
++ tf.setConverter(new StringToIntegerConverter());
++ tf.setPropertyDataSource(new MethodProperty<Integer>(paulaBean, "age"));
++ assertEquals(34, tf.getPropertyDataSource().getValue());
++ assertEquals("34", tf.getValue());
++ tf.setValue("12");
++ assertEquals(12, tf.getPropertyDataSource().getValue());
++ assertEquals("12", tf.getValue());
++ tf.getPropertyDataSource().setValue(42);
++ assertEquals(42, tf.getPropertyDataSource().getValue());
++ assertEquals("42", tf.getValue());
++ }
++
++ public void testBooleanNullConversion() {
++ CheckBox cb = new CheckBox();
++ cb.setConverter(new Converter<Boolean, Boolean>() {
++
++ public Boolean convertToModel(Boolean value, Locale locale) {
++ // value from a CheckBox should never be null as long as it is
++ // not set to null (handled by conversion below).
++ assertNotNull(value);
++ return value;
++ }
++
++ public Boolean convertToPresentation(Boolean value, Locale locale) {
++ // Datamodel -> field
++ if (value == null) {
++ return false;
++ }
++
++ return value;
++ }
++
++ public Class<Boolean> getModelType() {
++ return Boolean.class;
++ }
++
++ public Class<Boolean> getPresentationType() {
++ return Boolean.class;
++ }
++
++ });
++ MethodProperty<Boolean> property = new MethodProperty<Boolean>(
++ paulaBean, "deceased");
++ cb.setPropertyDataSource(property);
++ assertEquals(Boolean.FALSE, property.getValue());
++ assertEquals(Boolean.FALSE, cb.getValue());
++ Boolean newDmValue = cb.getConverter().convertToPresentation(
++ cb.getValue(), new Locale("fi", "FI"));
++ assertEquals(Boolean.FALSE, newDmValue);
++
++ // FIXME: Should be able to set to false here to cause datamodel to be
++ // set to false but the change will not be propagated to the Property
++ // (field value is already false)
++
++ cb.setValue(true);
++ assertEquals(Boolean.TRUE, cb.getValue());
++ assertEquals(Boolean.TRUE, property.getValue());
++
++ cb.setValue(false);
++ assertEquals(Boolean.FALSE, cb.getValue());
++ assertEquals(Boolean.FALSE, property.getValue());
++
++ }
++
++}
--- /dev/null
- package com.vaadin.tests.server.component.abstractfield;\r
- \r
- import java.math.BigDecimal;\r
- import java.util.Locale;\r
- \r
- import junit.framework.TestCase;\r
- \r
- import com.vaadin.Application;\r
- import com.vaadin.data.util.MethodProperty;\r
- import com.vaadin.tests.data.bean.Address;\r
- import com.vaadin.tests.data.bean.Country;\r
- import com.vaadin.tests.data.bean.Person;\r
- import com.vaadin.tests.data.bean.Sex;\r
- import com.vaadin.ui.TextField;\r
- \r
- public class DefaultConverterFactory extends TestCase {\r
- \r
- Person paulaBean = new Person("Paula", "Brilliant", "paula@brilliant.com",\r
- 34, Sex.FEMALE, new Address("Paula street 1", 12345, "P-town",\r
- Country.FINLAND));\r
- {\r
- paulaBean.setSalary(49000);\r
- BigDecimal rent = new BigDecimal(57223);\r
- rent = rent.scaleByPowerOfTen(-2);\r
- paulaBean.setRent(rent);\r
- }\r
- \r
- public void testDefaultNumberConversion() {\r
- Application app = new Application();\r
- Application.setCurrentApplication(app);\r
- TextField tf = new TextField();\r
- tf.setLocale(new Locale("en", "US"));\r
- tf.setPropertyDataSource(new MethodProperty<Integer>(paulaBean,\r
- "salary"));\r
- assertEquals("49,000", tf.getValue());\r
- \r
- tf.setLocale(new Locale("fi", "FI"));\r
- // FIXME: The following line should not be necessary and should be\r
- // removed\r
- tf.setPropertyDataSource(new MethodProperty<Integer>(paulaBean,\r
- "salary"));\r
- String value = tf.getValue();\r
- // Java uses a non-breaking space (ascii 160) instead of space when\r
- // formatting\r
- String expected = "49" + (char) 160 + "000";\r
- assertEquals(expected, value);\r
- }\r
- }\r
++package com.vaadin.tests.server.component.abstractfield;
++
++import java.math.BigDecimal;
++import java.util.Locale;
++
++import junit.framework.TestCase;
++
++import com.vaadin.Application;
++import com.vaadin.data.util.MethodProperty;
++import com.vaadin.tests.data.bean.Address;
++import com.vaadin.tests.data.bean.Country;
++import com.vaadin.tests.data.bean.Person;
++import com.vaadin.tests.data.bean.Sex;
++import com.vaadin.ui.TextField;
++
++public class DefaultConverterFactory extends TestCase {
++
++ Person paulaBean = new Person("Paula", "Brilliant", "paula@brilliant.com",
++ 34, Sex.FEMALE, new Address("Paula street 1", 12345, "P-town",
++ Country.FINLAND));
++ {
++ paulaBean.setSalary(49000);
++ BigDecimal rent = new BigDecimal(57223);
++ rent = rent.scaleByPowerOfTen(-2);
++ paulaBean.setRent(rent);
++ }
++
++ public void testDefaultNumberConversion() {
++ Application app = new Application();
++ Application.setCurrentApplication(app);
++ TextField tf = new TextField();
++ tf.setLocale(new Locale("en", "US"));
++ tf.setPropertyDataSource(new MethodProperty<Integer>(paulaBean,
++ "salary"));
++ assertEquals("49,000", tf.getValue());
++
++ tf.setLocale(new Locale("fi", "FI"));
++ // FIXME: The following line should not be necessary and should be
++ // removed
++ tf.setPropertyDataSource(new MethodProperty<Integer>(paulaBean,
++ "salary"));
++ String value = tf.getValue();
++ // Java uses a non-breaking space (ascii 160) instead of space when
++ // formatting
++ String expected = "49" + (char) 160 + "000";
++ assertEquals(expected, value);
++ }
++}
- package com.vaadin.tests.server.component.abstractfield;\r
- \r
- import com.vaadin.data.Property.ReadOnlyStatusChangeEvent;\r
- import com.vaadin.data.Property.ReadOnlyStatusChangeListener;\r
- import com.vaadin.data.Property.ValueChangeEvent;\r
- import com.vaadin.data.Property.ValueChangeListener;\r
- import com.vaadin.tests.server.component.AbstractListenerMethodsTest;\r
- import com.vaadin.ui.CheckBox;\r
- \r
- public class TestAbstractFieldListeners extends AbstractListenerMethodsTest {\r
- public void testReadOnlyStatusChangeListenerAddGetRemove() throws Exception {\r
- testListenerAddGetRemove(CheckBox.class,\r
- ReadOnlyStatusChangeEvent.class,\r
- ReadOnlyStatusChangeListener.class);\r
- }\r
- \r
- public void testValueChangeListenerAddGetRemove() throws Exception {\r
- testListenerAddGetRemove(CheckBox.class, ValueChangeEvent.class,\r
- ValueChangeListener.class);\r
- }\r
- }\r
+ package com.vaadin.tests.server.component.abstractfield;
+
+ import com.vaadin.data.Property.ReadOnlyStatusChangeEvent;
+ import com.vaadin.data.Property.ReadOnlyStatusChangeListener;
+ import com.vaadin.data.Property.ValueChangeEvent;
+ import com.vaadin.data.Property.ValueChangeListener;
+ import com.vaadin.tests.server.component.AbstractListenerMethodsTest;
-import com.vaadin.ui.Button;
++import com.vaadin.ui.CheckBox;
+
+ public class TestAbstractFieldListeners extends AbstractListenerMethodsTest {
+ public void testReadOnlyStatusChangeListenerAddGetRemove() throws Exception {
- testListenerAddGetRemove(Button.class, ReadOnlyStatusChangeEvent.class,
++ testListenerAddGetRemove(CheckBox.class,
++ ReadOnlyStatusChangeEvent.class,
+ ReadOnlyStatusChangeListener.class);
+ }
+
+ public void testValueChangeListenerAddGetRemove() throws Exception {
- testListenerAddGetRemove(Button.class, ValueChangeEvent.class,
++ testListenerAddGetRemove(CheckBox.class, ValueChangeEvent.class,
+ ValueChangeListener.class);
+ }
+ }
--- /dev/null
- package com.vaadin.tests.server.component.datefield;\r
- \r
- import java.util.ArrayList;\r
- \r
- import junit.framework.TestCase;\r
- \r
- import com.vaadin.tests.util.TestUtil;\r
- import com.vaadin.ui.DateField.Resolution;\r
- \r
- public class ResolutionTest extends TestCase {\r
- \r
- public void testResolutionHigherOrEqualToYear() {\r
- Iterable<Resolution> higherOrEqual = Resolution\r
- .getResolutionsHigherOrEqualTo(Resolution.YEAR);\r
- ArrayList<Resolution> expected = new ArrayList<Resolution>();\r
- expected.add(Resolution.YEAR);\r
- TestUtil.assertIterableEquals(expected, higherOrEqual);\r
- }\r
- \r
- public void testResolutionHigherOrEqualToDay() {\r
- Iterable<Resolution> higherOrEqual = Resolution\r
- .getResolutionsHigherOrEqualTo(Resolution.DAY);\r
- ArrayList<Resolution> expected = new ArrayList<Resolution>();\r
- expected.add(Resolution.DAY);\r
- expected.add(Resolution.MONTH);\r
- expected.add(Resolution.YEAR);\r
- TestUtil.assertIterableEquals(expected, higherOrEqual);\r
- \r
- }\r
- \r
- public void testResolutionLowerThanDay() {\r
- Iterable<Resolution> higherOrEqual = Resolution\r
- .getResolutionsLowerThan(Resolution.DAY);\r
- ArrayList<Resolution> expected = new ArrayList<Resolution>();\r
- expected.add(Resolution.HOUR);\r
- expected.add(Resolution.MINUTE);\r
- expected.add(Resolution.SECOND);\r
- TestUtil.assertIterableEquals(expected, higherOrEqual);\r
- \r
- }\r
- \r
- public void testResolutionLowerThanSecond() {\r
- Iterable<Resolution> higherOrEqual = Resolution\r
- .getResolutionsLowerThan(Resolution.SECOND);\r
- ArrayList<Resolution> expected = new ArrayList<Resolution>();\r
- TestUtil.assertIterableEquals(expected, higherOrEqual);\r
- }\r
- \r
- public void testResolutionLowerThanYear() {\r
- Iterable<Resolution> higherOrEqual = Resolution\r
- .getResolutionsLowerThan(Resolution.YEAR);\r
- ArrayList<Resolution> expected = new ArrayList<Resolution>();\r
- expected.add(Resolution.MONTH);\r
- expected.add(Resolution.DAY);\r
- expected.add(Resolution.HOUR);\r
- expected.add(Resolution.MINUTE);\r
- expected.add(Resolution.SECOND);\r
- TestUtil.assertIterableEquals(expected, higherOrEqual);\r
- \r
- }\r
- }\r
++package com.vaadin.tests.server.component.datefield;
++
++import java.util.ArrayList;
++
++import junit.framework.TestCase;
++
++import com.vaadin.tests.util.TestUtil;
++import com.vaadin.ui.DateField.Resolution;
++
++public class ResolutionTest extends TestCase {
++
++ public void testResolutionHigherOrEqualToYear() {
++ Iterable<Resolution> higherOrEqual = Resolution
++ .getResolutionsHigherOrEqualTo(Resolution.YEAR);
++ ArrayList<Resolution> expected = new ArrayList<Resolution>();
++ expected.add(Resolution.YEAR);
++ TestUtil.assertIterableEquals(expected, higherOrEqual);
++ }
++
++ public void testResolutionHigherOrEqualToDay() {
++ Iterable<Resolution> higherOrEqual = Resolution
++ .getResolutionsHigherOrEqualTo(Resolution.DAY);
++ ArrayList<Resolution> expected = new ArrayList<Resolution>();
++ expected.add(Resolution.DAY);
++ expected.add(Resolution.MONTH);
++ expected.add(Resolution.YEAR);
++ TestUtil.assertIterableEquals(expected, higherOrEqual);
++
++ }
++
++ public void testResolutionLowerThanDay() {
++ Iterable<Resolution> higherOrEqual = Resolution
++ .getResolutionsLowerThan(Resolution.DAY);
++ ArrayList<Resolution> expected = new ArrayList<Resolution>();
++ expected.add(Resolution.HOUR);
++ expected.add(Resolution.MINUTE);
++ expected.add(Resolution.SECOND);
++ TestUtil.assertIterableEquals(expected, higherOrEqual);
++
++ }
++
++ public void testResolutionLowerThanSecond() {
++ Iterable<Resolution> higherOrEqual = Resolution
++ .getResolutionsLowerThan(Resolution.SECOND);
++ ArrayList<Resolution> expected = new ArrayList<Resolution>();
++ TestUtil.assertIterableEquals(expected, higherOrEqual);
++ }
++
++ public void testResolutionLowerThanYear() {
++ Iterable<Resolution> higherOrEqual = Resolution
++ .getResolutionsLowerThan(Resolution.YEAR);
++ ArrayList<Resolution> expected = new ArrayList<Resolution>();
++ expected.add(Resolution.MONTH);
++ expected.add(Resolution.DAY);
++ expected.add(Resolution.HOUR);
++ expected.add(Resolution.MINUTE);
++ expected.add(Resolution.SECOND);
++ TestUtil.assertIterableEquals(expected, higherOrEqual);
++
++ }
++}
--- /dev/null
- package com.vaadin.tests.server.component.slider;\r
- \r
- import junit.framework.Assert;\r
- import junit.framework.TestCase;\r
- \r
- import com.vaadin.ui.Slider;\r
- import com.vaadin.ui.Slider.ValueOutOfBoundsException;\r
- \r
- public class SliderTest extends TestCase {\r
- \r
- public void testOutOfBounds() {\r
- Slider s = new Slider(0, 10);\r
- s.setValue(0);\r
- Assert.assertEquals(0.0, s.getValue());\r
- s.setValue(10);\r
- Assert.assertEquals(10.0, s.getValue());\r
- try {\r
- s.setValue(20);\r
- fail("Should throw out of bounds exception");\r
- } catch (ValueOutOfBoundsException e) {\r
- // TODO: handle exception\r
- }\r
- \r
- }\r
- }\r
++package com.vaadin.tests.server.component.slider;
++
++import junit.framework.Assert;
++import junit.framework.TestCase;
++
++import com.vaadin.ui.Slider;
++import com.vaadin.ui.Slider.ValueOutOfBoundsException;
++
++public class SliderTest extends TestCase {
++
++ public void testOutOfBounds() {
++ Slider s = new Slider(0, 10);
++ s.setValue(0);
++ Assert.assertEquals(0.0, s.getValue());
++ s.setValue(10);
++ Assert.assertEquals(10.0, s.getValue());
++ try {
++ s.setValue(20);
++ fail("Should throw out of bounds exception");
++ } catch (ValueOutOfBoundsException e) {
++ // TODO: handle exception
++ }
++
++ }
++}
- package com.vaadin.tests.server.component.window;\r
- \r
- import static org.junit.Assert.assertEquals;\r
- import static org.junit.Assert.assertNull;\r
- import static org.junit.Assert.assertTrue;\r
- \r
- import org.junit.Test;\r
- \r
- import com.vaadin.Application;\r
- import com.vaadin.ui.Root;\r
- import com.vaadin.ui.Root.LegacyWindow;\r
- import com.vaadin.ui.Window;\r
- \r
- public class AddRemoveSubWindow {\r
- \r
- public class TestApp extends Application.LegacyApplication {\r
- \r
- @Override\r
- public void init() {\r
- LegacyWindow w = new LegacyWindow("Main window");\r
- setMainWindow(w);\r
- }\r
- }\r
- \r
- @Test\r
- public void addSubWindow() {\r
- TestApp app = new TestApp();\r
- app.init();\r
- Window subWindow = new Window("Sub window");\r
- Root mainWindow = app.getMainWindow();\r
- \r
- mainWindow.addWindow(subWindow);\r
- // Added to main window so the parent of the sub window should be the\r
- // main window\r
- assertEquals(subWindow.getParent(), mainWindow);\r
- \r
- try {\r
- mainWindow.addWindow(subWindow);\r
- assertTrue("Window.addWindow did not throw the expected exception",\r
- false);\r
- } catch (IllegalArgumentException e) {\r
- // Should throw an exception as it has already been added to the\r
- // main window\r
- }\r
- \r
- // Try to add the same sub window to another window\r
- try {\r
- LegacyWindow w = new LegacyWindow();\r
- w.addWindow(subWindow);\r
- assertTrue("Window.addWindow did not throw the expected exception",\r
- false);\r
- } catch (IllegalArgumentException e) {\r
- // Should throw an exception as it has already been added to the\r
- // main window\r
- }\r
- \r
- }\r
- \r
- @Test\r
- public void removeSubWindow() {\r
- TestApp app = new TestApp();\r
- app.init();\r
- Window subWindow = new Window("Sub window");\r
- Root mainWindow = app.getMainWindow();\r
- mainWindow.addWindow(subWindow);\r
- \r
- // Added to main window so the parent of the sub window should be the\r
- // main window\r
- assertEquals(subWindow.getParent(), mainWindow);\r
- \r
- // Parent should still be set\r
- assertEquals(subWindow.getParent(), mainWindow);\r
- \r
- // Remove from the main window and assert it has been removed\r
- boolean removed = mainWindow.removeWindow(subWindow);\r
- assertTrue("Window was not removed correctly", removed);\r
- assertNull(subWindow.getParent());\r
- }\r
- }\r
+ package com.vaadin.tests.server.component.window;
+
+ import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
+ import static org.junit.Assert.assertNull;
+ import static org.junit.Assert.assertTrue;
+
+ import org.junit.Test;
+
+ import com.vaadin.Application;
++import com.vaadin.ui.Root;
++import com.vaadin.ui.Root.LegacyWindow;
+ import com.vaadin.ui.Window;
+
+ public class AddRemoveSubWindow {
+
- public class TestApp extends Application {
++ public class TestApp extends Application.LegacyApplication {
+
+ @Override
+ public void init() {
- Window w = new Window("Main window");
++ LegacyWindow w = new LegacyWindow("Main window");
+ setMainWindow(w);
+ }
+ }
+
+ @Test
+ public void addSubWindow() {
+ TestApp app = new TestApp();
+ app.init();
+ Window subWindow = new Window("Sub window");
- Window mainWindow = app.getMainWindow();
++ Root mainWindow = app.getMainWindow();
+
+ mainWindow.addWindow(subWindow);
+ // Added to main window so the parent of the sub window should be the
+ // main window
+ assertEquals(subWindow.getParent(), mainWindow);
+
+ try {
+ mainWindow.addWindow(subWindow);
+ assertTrue("Window.addWindow did not throw the expected exception",
+ false);
+ } catch (IllegalArgumentException e) {
+ // Should throw an exception as it has already been added to the
+ // main window
+ }
+
+ // Try to add the same sub window to another window
+ try {
- Window w = new Window();
++ LegacyWindow w = new LegacyWindow();
+ w.addWindow(subWindow);
+ assertTrue("Window.addWindow did not throw the expected exception",
+ false);
+ } catch (IllegalArgumentException e) {
+ // Should throw an exception as it has already been added to the
+ // main window
+ }
+
+ }
+
+ @Test
+ public void removeSubWindow() {
+ TestApp app = new TestApp();
+ app.init();
+ Window subWindow = new Window("Sub window");
- Window mainWindow = app.getMainWindow();
++ Root mainWindow = app.getMainWindow();
+ mainWindow.addWindow(subWindow);
+
+ // Added to main window so the parent of the sub window should be the
+ // main window
+ assertEquals(subWindow.getParent(), mainWindow);
+
- // Remove from the wrong window, should result in an exception
- boolean removed = subWindow.removeWindow(subWindow);
- assertFalse("Window was removed even though it should not have been",
- removed);
-
+ // Parent should still be set
+ assertEquals(subWindow.getParent(), mainWindow);
+
+ // Remove from the main window and assert it has been removed
- removed = mainWindow.removeWindow(subWindow);
++ boolean removed = mainWindow.removeWindow(subWindow);
+ assertTrue("Window was not removed correctly", removed);
+ assertNull(subWindow.getParent());
+ }
+ }
- package com.vaadin.tests.server.component.window;\r
- \r
- import static org.junit.Assert.assertSame;\r
- import static org.junit.Assert.assertTrue;\r
- \r
- import org.junit.Test;\r
- \r
- import com.vaadin.Application;\r
- import com.vaadin.terminal.WrappedRequest;\r
- import com.vaadin.ui.Label;\r
- import com.vaadin.ui.Root;\r
- import com.vaadin.ui.VerticalLayout;\r
- import com.vaadin.ui.Window;\r
- \r
- public class AttachDetachWindow {\r
- \r
- private Application testApp = new Application();\r
- \r
- private interface TestContainer {\r
- public boolean attachCalled();\r
- \r
- public boolean detachCalled();\r
- \r
- public TestContent getTestContent();\r
- \r
- public Application getApplication();\r
- }\r
- \r
- private class TestWindow extends Window implements TestContainer {\r
- boolean windowAttachCalled = false;\r
- boolean windowDetachCalled = false;\r
- private TestContent testContent = new TestContent();;\r
- \r
- TestWindow() {\r
- setContent(testContent);\r
- }\r
- \r
- @Override\r
- public void attach() {\r
- super.attach();\r
- windowAttachCalled = true;\r
- }\r
- \r
- @Override\r
- public void detach() {\r
- super.detach();\r
- windowDetachCalled = true;\r
- }\r
- \r
- public boolean attachCalled() {\r
- return windowAttachCalled;\r
- }\r
- \r
- public boolean detachCalled() {\r
- return windowDetachCalled;\r
- }\r
- \r
- public TestContent getTestContent() {\r
- return testContent;\r
- }\r
- }\r
- \r
- private class TestContent extends VerticalLayout {\r
- boolean contentDetachCalled = false;\r
- boolean childDetachCalled = false;\r
- boolean contentAttachCalled = false;\r
- boolean childAttachCalled = false;\r
- \r
- private Label child = new Label() {\r
- @Override\r
- public void attach() {\r
- super.attach();\r
- childAttachCalled = true;\r
- }\r
- \r
- @Override\r
- public void detach() {\r
- super.detach();\r
- childDetachCalled = true;\r
- }\r
- };\r
- \r
- public TestContent() {\r
- addComponent(child);\r
- }\r
- \r
- @Override\r
- public void attach() {\r
- super.attach();\r
- contentAttachCalled = true;\r
- }\r
- \r
- @Override\r
- public void detach() {\r
- super.detach();\r
- contentDetachCalled = true;\r
- }\r
- }\r
- \r
- private class TestRoot extends Root implements TestContainer {\r
- boolean rootAttachCalled = false;\r
- boolean rootDetachCalled = false;\r
- private TestContent testContent = new TestContent();;\r
- \r
- public TestRoot() {\r
- setContent(testContent);\r
- }\r
- \r
- @Override\r
- protected void init(WrappedRequest request) {\r
- // Do nothing\r
- }\r
- \r
- public boolean attachCalled() {\r
- return rootAttachCalled;\r
- }\r
- \r
- public boolean detachCalled() {\r
- return rootDetachCalled;\r
- }\r
- \r
- public TestContent getTestContent() {\r
- return testContent;\r
- }\r
- \r
- @Override\r
- public void attach() {\r
- super.attach();\r
- rootAttachCalled = true;\r
- }\r
- \r
- @Override\r
- public void detach() {\r
- super.detach();\r
- rootDetachCalled = true;\r
- }\r
- }\r
- \r
- TestRoot main = new TestRoot();\r
- TestWindow sub = new TestWindow();\r
- \r
- @Test\r
- public void addSubWindowBeforeAttachingMainWindow() {\r
- assertUnattached(main);\r
- assertUnattached(sub);\r
- \r
- main.addWindow(sub);\r
- assertUnattached(main);\r
- assertUnattached(sub);\r
- \r
- // attaching main should recurse to sub\r
- main.setApplication(testApp);\r
- assertAttached(main);\r
- assertAttached(sub);\r
- }\r
- \r
- @Test\r
- public void addSubWindowAfterAttachingMainWindow() {\r
- assertUnattached(main);\r
- assertUnattached(sub);\r
- \r
- main.setApplication(testApp);\r
- assertAttached(main);\r
- assertUnattached(sub);\r
- \r
- // main is already attached, so attach should be called for sub\r
- main.addWindow(sub);\r
- assertAttached(main);\r
- assertAttached(sub);\r
- }\r
- \r
- @Test\r
- public void removeSubWindowBeforeDetachingMainWindow() {\r
- main.setApplication(testApp);\r
- main.addWindow(sub);\r
- \r
- // sub should be detached when removing from attached main\r
- main.removeWindow(sub);\r
- assertAttached(main);\r
- assertDetached(sub);\r
- \r
- // main detach should recurse to sub\r
- main.setApplication(null);\r
- assertDetached(main);\r
- assertDetached(sub);\r
- }\r
- \r
- @Test\r
- public void removeSubWindowAfterDetachingMainWindow() {\r
- main.setApplication(testApp);\r
- main.addWindow(sub);\r
- \r
- // main detach should recurse to sub\r
- main.setApplication(null);\r
- assertDetached(main);\r
- assertDetached(sub);\r
- \r
- main.removeWindow(sub);\r
- assertDetached(main);\r
- assertDetached(sub);\r
- }\r
- \r
- /**\r
- * Asserts that win and its children are attached to testApp and their\r
- * attach() methods have been called.\r
- */\r
- private void assertAttached(TestContainer win) {\r
- TestContent testContent = win.getTestContent();\r
- \r
- assertTrue("window attach not called", win.attachCalled());\r
- assertTrue("window content attach not called",\r
- testContent.contentAttachCalled);\r
- assertTrue("window child attach not called",\r
- testContent.childAttachCalled);\r
- \r
- assertSame("window not attached", win.getApplication(), testApp);\r
- assertSame("window content not attached", testContent.getApplication(),\r
- testApp);\r
- assertSame("window children not attached",\r
- testContent.child.getApplication(), testApp);\r
- }\r
- \r
- /**\r
- * Asserts that win and its children are not attached.\r
- */\r
- private void assertUnattached(TestContainer win) {\r
- assertSame("window not detached", win.getApplication(), null);\r
- assertSame("window content not detached", win.getTestContent()\r
- .getApplication(), null);\r
- assertSame("window children not detached",\r
- win.getTestContent().child.getApplication(), null);\r
- }\r
- \r
- /**\r
- * Asserts that win and its children are unattached and their detach()\r
- * methods have been been called.\r
- * \r
- * @param win\r
- */\r
- private void assertDetached(TestContainer win) {\r
- assertUnattached(win);\r
- assertTrue("window detach not called", win.detachCalled());\r
- assertTrue("window content detach not called",\r
- win.getTestContent().contentDetachCalled);\r
- assertTrue("window child detach not called",\r
- win.getTestContent().childDetachCalled);\r
- }\r
- }\r
+ package com.vaadin.tests.server.component.window;
+
+ import static org.junit.Assert.assertSame;
+ import static org.junit.Assert.assertTrue;
+
++import org.junit.Test;
++
+ import com.vaadin.Application;
-import com.vaadin.ui.Component;
++import com.vaadin.terminal.WrappedRequest;
+ import com.vaadin.ui.Label;
++import com.vaadin.ui.Root;
+ import com.vaadin.ui.VerticalLayout;
+ import com.vaadin.ui.Window;
+
-import org.junit.Test;
-
+ public class AttachDetachWindow {
+
- private Application testApp = new Application() {
- @Override
- public void init() {
- }
- };
++ private Application testApp = new Application();
++
++ private interface TestContainer {
++ public boolean attachCalled();
++
++ public boolean detachCalled();
+
- private class TestWindow extends Window {
++ public TestContent getTestContent();
++
++ public Application getApplication();
++ }
++
++ private class TestWindow extends Window implements TestContainer {
+ boolean windowAttachCalled = false;
- boolean contentAttachCalled = false;
- boolean childAttachCalled = false;
+ boolean windowDetachCalled = false;
- boolean contentDetachCalled = false;
- boolean childDetachCalled = false;
++ private TestContent testContent = new TestContent();;
+
+ TestWindow() {
- setContent(new VerticalLayout() {
- @Override
- public void attach() {
- super.attach();
- contentAttachCalled = true;
- }
-
- @Override
- public void detach() {
- super.detach();
- contentDetachCalled = true;
- }
- });
- addComponent(new Label() {
- @Override
- public void attach() {
- super.attach();
- childAttachCalled = true;
- }
-
- @Override
- public void detach() {
- super.detach();
- childDetachCalled = true;
- }
- });
- }
-
- Component getChild() {
- return getComponentIterator().next();
++ setContent(testContent);
+ }
+
+ @Override
+ public void attach() {
+ super.attach();
+ windowAttachCalled = true;
+ }
+
+ @Override
+ public void detach() {
+ super.detach();
+ windowDetachCalled = true;
+ }
++
++ public boolean attachCalled() {
++ return windowAttachCalled;
++ }
++
++ public boolean detachCalled() {
++ return windowDetachCalled;
++ }
++
++ public TestContent getTestContent() {
++ return testContent;
++ }
+ }
+
- TestWindow main = new TestWindow();
++ private class TestContent extends VerticalLayout {
++ boolean contentDetachCalled = false;
++ boolean childDetachCalled = false;
++ boolean contentAttachCalled = false;
++ boolean childAttachCalled = false;
++
++ private Label child = new Label() {
++ @Override
++ public void attach() {
++ super.attach();
++ childAttachCalled = true;
++ }
++
++ @Override
++ public void detach() {
++ super.detach();
++ childDetachCalled = true;
++ }
++ };
++
++ public TestContent() {
++ addComponent(child);
++ }
++
++ @Override
++ public void attach() {
++ super.attach();
++ contentAttachCalled = true;
++ }
++
++ @Override
++ public void detach() {
++ super.detach();
++ contentDetachCalled = true;
++ }
++ }
++
++ private class TestRoot extends Root implements TestContainer {
++ boolean rootAttachCalled = false;
++ boolean rootDetachCalled = false;
++ private TestContent testContent = new TestContent();;
++
++ public TestRoot() {
++ setContent(testContent);
++ }
++
++ @Override
++ protected void init(WrappedRequest request) {
++ // Do nothing
++ }
++
++ public boolean attachCalled() {
++ return rootAttachCalled;
++ }
++
++ public boolean detachCalled() {
++ return rootDetachCalled;
++ }
++
++ public TestContent getTestContent() {
++ return testContent;
++ }
++
++ @Override
++ public void attach() {
++ super.attach();
++ rootAttachCalled = true;
++ }
++
++ @Override
++ public void detach() {
++ super.detach();
++ rootDetachCalled = true;
++ }
++ }
++
++ TestRoot main = new TestRoot();
+ TestWindow sub = new TestWindow();
+
+ @Test
+ public void addSubWindowBeforeAttachingMainWindow() {
+ assertUnattached(main);
+ assertUnattached(sub);
+
+ main.addWindow(sub);
+ assertUnattached(main);
+ assertUnattached(sub);
+
+ // attaching main should recurse to sub
- testApp.setMainWindow(main);
++ main.setApplication(testApp);
+ assertAttached(main);
+ assertAttached(sub);
+ }
+
+ @Test
+ public void addSubWindowAfterAttachingMainWindow() {
+ assertUnattached(main);
+ assertUnattached(sub);
+
- testApp.setMainWindow(main);
++ main.setApplication(testApp);
+ assertAttached(main);
+ assertUnattached(sub);
+
+ // main is already attached, so attach should be called for sub
+ main.addWindow(sub);
+ assertAttached(main);
+ assertAttached(sub);
+ }
+
+ @Test
+ public void removeSubWindowBeforeDetachingMainWindow() {
- testApp.addWindow(main);
++ main.setApplication(testApp);
+ main.addWindow(sub);
+
+ // sub should be detached when removing from attached main
+ main.removeWindow(sub);
+ assertAttached(main);
+ assertDetached(sub);
+
+ // main detach should recurse to sub
- testApp.removeWindow(main);
++ main.setApplication(null);
+ assertDetached(main);
+ assertDetached(sub);
+ }
+
+ @Test
+ public void removeSubWindowAfterDetachingMainWindow() {
- testApp.addWindow(main);
++ main.setApplication(testApp);
+ main.addWindow(sub);
+
+ // main detach should recurse to sub
- testApp.removeWindow(main);
++ main.setApplication(null);
+ assertDetached(main);
+ assertDetached(sub);
+
+ main.removeWindow(sub);
+ assertDetached(main);
+ assertDetached(sub);
+ }
+
+ /**
+ * Asserts that win and its children are attached to testApp and their
+ * attach() methods have been called.
+ */
- private void assertAttached(TestWindow win) {
- assertTrue("window attach not called", win.windowAttachCalled);
- assertTrue("window content attach not called", win.contentAttachCalled);
- assertTrue("window child attach not called", win.childAttachCalled);
++ private void assertAttached(TestContainer win) {
++ TestContent testContent = win.getTestContent();
++
++ assertTrue("window attach not called", win.attachCalled());
++ assertTrue("window content attach not called",
++ testContent.contentAttachCalled);
++ assertTrue("window child attach not called",
++ testContent.childAttachCalled);
+
+ assertSame("window not attached", win.getApplication(), testApp);
- assertSame("window content not attached", win.getContent()
- .getApplication(), testApp);
- assertSame("window children not attached", win.getChild()
- .getApplication(), testApp);
++ assertSame("window content not attached", testContent.getApplication(),
++ testApp);
++ assertSame("window children not attached",
++ testContent.child.getApplication(), testApp);
+ }
+
+ /**
+ * Asserts that win and its children are not attached.
+ */
- private void assertUnattached(TestWindow win) {
++ private void assertUnattached(TestContainer win) {
+ assertSame("window not detached", win.getApplication(), null);
- assertSame("window content not detached", win.getContent()
- .getApplication(), null);
- assertSame("window children not detached", win.getChild()
++ assertSame("window content not detached", win.getTestContent()
+ .getApplication(), null);
++ assertSame("window children not detached",
++ win.getTestContent().child.getApplication(), null);
+ }
+
+ /**
+ * Asserts that win and its children are unattached and their detach()
+ * methods have been been called.
+ *
+ * @param win
+ */
- private void assertDetached(TestWindow win) {
++ private void assertDetached(TestContainer win) {
+ assertUnattached(win);
- assertTrue("window detach not called", win.windowDetachCalled);
- assertTrue("window content detach not called", win.contentDetachCalled);
- assertTrue("window child detach not called", win.childDetachCalled);
++ assertTrue("window detach not called", win.detachCalled());
++ assertTrue("window content detach not called",
++ win.getTestContent().contentDetachCalled);
++ assertTrue("window child detach not called",
++ win.getTestContent().childDetachCalled);
+ }
+ }
- package com.vaadin.tests.server.components;\r
- \r
- import junit.framework.TestCase;\r
- \r
- import org.easymock.EasyMock;\r
- \r
- import com.vaadin.data.Property.ValueChangeEvent;\r
- import com.vaadin.data.Property.ValueChangeListener;\r
- import com.vaadin.data.Property.ValueChangeNotifier;\r
- import com.vaadin.data.util.ObjectProperty;\r
- import com.vaadin.ui.AbstractField;\r
- \r
- /**\r
- * Base class for tests for checking that value change listeners for fields are\r
- * not called exactly once when they should be, and not at other times.\r
- * \r
- * Does not check all cases (e.g. properties that do not implement\r
- * {@link ValueChangeNotifier}).\r
- * \r
- * Subclasses should implement {@link #setValue()} and call\r
- * <code>super.setValue(AbstractField)</code>. Also, subclasses should typically\r
- * override {@link #setValue(AbstractField)} to set the field value via\r
- * <code>changeVariables()</code>.\r
- */\r
- public abstract class AbstractTestFieldValueChange<T> extends TestCase {\r
- \r
- private AbstractField<T> field;\r
- private ValueChangeListener listener;\r
- \r
- protected void setUp(AbstractField<T> field) throws Exception {\r
- this.field = field;\r
- listener = EasyMock.createStrictMock(ValueChangeListener.class);\r
- \r
- }\r
- \r
- protected ValueChangeListener getListener() {\r
- return listener;\r
- }\r
- \r
- /**\r
- * Test that listeners are not called when they have been unregistered.\r
- */\r
- public void testRemoveListener() {\r
- getField().setPropertyDataSource(new ObjectProperty<String>(""));\r
- getField().setWriteThrough(true);\r
- getField().setReadThrough(true);\r
- \r
- // Expectations and start test\r
- listener.valueChange(EasyMock.isA(ValueChangeEvent.class));\r
- EasyMock.replay(listener);\r
- \r
- // Add listener and set the value -> should end up in listener once\r
- getField().addListener(listener);\r
- setValue(getField());\r
- \r
- // Ensure listener was called once\r
- EasyMock.verify(listener);\r
- \r
- // Remove the listener and set the value -> should not end up in\r
- // listener\r
- getField().removeListener(listener);\r
- setValue(getField());\r
- \r
- // Ensure listener still has been called only once\r
- EasyMock.verify(listener);\r
- }\r
- \r
- /**\r
- * Common unbuffered case: both writeThrough (auto-commit) and readThrough\r
- * are on. Calling commit() should not cause notifications.\r
- * \r
- * Using the readThrough mode allows changes made to the property value to\r
- * be seen in some cases also when there is no notification of value change\r
- * from the property.\r
- * \r
- * Field value change notifications closely mirror value changes of the data\r
- * source behind the field.\r
- */\r
- public void testWriteThroughReadThrough() {\r
- getField().setPropertyDataSource(new ObjectProperty<String>(""));\r
- getField().setWriteThrough(true);\r
- getField().setReadThrough(true);\r
- \r
- expectValueChangeFromSetValueNotCommit();\r
- }\r
- \r
- /**\r
- * Fully buffered use where the data source is neither read nor modified\r
- * during editing, and is updated at commit().\r
- * \r
- * Field value change notifications reflect the buffered value in the field,\r
- * not the original data source value changes.\r
- */\r
- public void testNoWriteThroughNoReadThrough() {\r
- getField().setPropertyDataSource(new ObjectProperty<String>(""));\r
- getField().setWriteThrough(false);\r
- getField().setReadThrough(false);\r
- \r
- expectValueChangeFromSetValueNotCommit();\r
- }\r
- \r
- /**\r
- * Less common partly buffered case: writeThrough (auto-commit) is on and\r
- * readThrough is off. Calling commit() should not cause notifications.\r
- * \r
- * Without readThrough activated, changes to the data source that do not\r
- * cause notifications are not reflected by the field value.\r
- * \r
- * Field value change notifications correspond to changes made to the data\r
- * source value through the text field or the (notifying) property.\r
- */\r
- public void testWriteThroughNoReadThrough() {\r
- getField().setPropertyDataSource(new ObjectProperty<String>(""));\r
- getField().setWriteThrough(true);\r
- getField().setReadThrough(false);\r
- \r
- expectValueChangeFromSetValueNotCommit();\r
- }\r
- \r
- /**\r
- * Partly buffered use where the data source is read but not nor modified\r
- * during editing, and is updated at commit().\r
- * \r
- * When used like this, a field is updated from the data source if necessary\r
- * when its value is requested and the property value has changed but the\r
- * field has not been modified in its buffer.\r
- * \r
- * Field value change notifications reflect the buffered value in the field,\r
- * not the original data source value changes.\r
- */\r
- public void testNoWriteThroughReadThrough() {\r
- getField().setPropertyDataSource(new ObjectProperty<String>(""));\r
- getField().setWriteThrough(false);\r
- getField().setReadThrough(true);\r
- \r
- expectValueChangeFromSetValueNotCommit();\r
- }\r
- \r
- protected void expectValueChangeFromSetValueNotCommit() {\r
- // Expectations and start test\r
- listener.valueChange(EasyMock.isA(ValueChangeEvent.class));\r
- EasyMock.replay(listener);\r
- \r
- // Add listener and set the value -> should end up in listener once\r
- getField().addListener(listener);\r
- setValue(getField());\r
- \r
- // Ensure listener was called once\r
- EasyMock.verify(listener);\r
- \r
- // commit\r
- getField().commit();\r
- \r
- // Ensure listener was not called again\r
- EasyMock.verify(listener);\r
- }\r
- \r
- protected AbstractField<T> getField() {\r
- return field;\r
- }\r
- \r
- /**\r
- * Override in subclasses to set value with changeVariables().\r
- */\r
- protected void setValue(AbstractField<T> field) {\r
- field.setValue("newValue");\r
- }\r
- \r
- }\r
+ package com.vaadin.tests.server.components;
+
+ import junit.framework.TestCase;
+
+ import org.easymock.EasyMock;
+
+ import com.vaadin.data.Property.ValueChangeEvent;
+ import com.vaadin.data.Property.ValueChangeListener;
+ import com.vaadin.data.Property.ValueChangeNotifier;
+ import com.vaadin.data.util.ObjectProperty;
+ import com.vaadin.ui.AbstractField;
+
+ /**
+ * Base class for tests for checking that value change listeners for fields are
+ * not called exactly once when they should be, and not at other times.
+ *
+ * Does not check all cases (e.g. properties that do not implement
+ * {@link ValueChangeNotifier}).
+ *
+ * Subclasses should implement {@link #setValue()} and call
+ * <code>super.setValue(AbstractField)</code>. Also, subclasses should typically
+ * override {@link #setValue(AbstractField)} to set the field value via
+ * <code>changeVariables()</code>.
+ */
-public abstract class AbstractTestFieldValueChange extends TestCase {
++public abstract class AbstractTestFieldValueChange<T> extends TestCase {
+
- private AbstractField field;
++ private AbstractField<T> field;
+ private ValueChangeListener listener;
+
- protected void setUp(AbstractField field) throws Exception {
++ protected void setUp(AbstractField<T> field) throws Exception {
+ this.field = field;
+ listener = EasyMock.createStrictMock(ValueChangeListener.class);
+
+ }
+
+ protected ValueChangeListener getListener() {
+ return listener;
+ }
+
+ /**
+ * Test that listeners are not called when they have been unregistered.
+ */
+ public void testRemoveListener() {
+ getField().setPropertyDataSource(new ObjectProperty<String>(""));
+ getField().setWriteThrough(true);
+ getField().setReadThrough(true);
+
+ // Expectations and start test
+ listener.valueChange(EasyMock.isA(ValueChangeEvent.class));
+ EasyMock.replay(listener);
+
+ // Add listener and set the value -> should end up in listener once
+ getField().addListener(listener);
+ setValue(getField());
+
+ // Ensure listener was called once
+ EasyMock.verify(listener);
+
+ // Remove the listener and set the value -> should not end up in
+ // listener
+ getField().removeListener(listener);
+ setValue(getField());
+
+ // Ensure listener still has been called only once
+ EasyMock.verify(listener);
+ }
+
+ /**
+ * Common unbuffered case: both writeThrough (auto-commit) and readThrough
+ * are on. Calling commit() should not cause notifications.
+ *
+ * Using the readThrough mode allows changes made to the property value to
+ * be seen in some cases also when there is no notification of value change
+ * from the property.
+ *
+ * Field value change notifications closely mirror value changes of the data
+ * source behind the field.
+ */
+ public void testWriteThroughReadThrough() {
+ getField().setPropertyDataSource(new ObjectProperty<String>(""));
+ getField().setWriteThrough(true);
+ getField().setReadThrough(true);
+
+ expectValueChangeFromSetValueNotCommit();
+ }
+
+ /**
+ * Fully buffered use where the data source is neither read nor modified
+ * during editing, and is updated at commit().
+ *
+ * Field value change notifications reflect the buffered value in the field,
+ * not the original data source value changes.
+ */
+ public void testNoWriteThroughNoReadThrough() {
+ getField().setPropertyDataSource(new ObjectProperty<String>(""));
+ getField().setWriteThrough(false);
+ getField().setReadThrough(false);
+
+ expectValueChangeFromSetValueNotCommit();
+ }
+
+ /**
+ * Less common partly buffered case: writeThrough (auto-commit) is on and
+ * readThrough is off. Calling commit() should not cause notifications.
+ *
+ * Without readThrough activated, changes to the data source that do not
+ * cause notifications are not reflected by the field value.
+ *
+ * Field value change notifications correspond to changes made to the data
+ * source value through the text field or the (notifying) property.
+ */
+ public void testWriteThroughNoReadThrough() {
+ getField().setPropertyDataSource(new ObjectProperty<String>(""));
+ getField().setWriteThrough(true);
+ getField().setReadThrough(false);
+
+ expectValueChangeFromSetValueNotCommit();
+ }
+
+ /**
+ * Partly buffered use where the data source is read but not nor modified
+ * during editing, and is updated at commit().
+ *
+ * When used like this, a field is updated from the data source if necessary
+ * when its value is requested and the property value has changed but the
+ * field has not been modified in its buffer.
+ *
+ * Field value change notifications reflect the buffered value in the field,
+ * not the original data source value changes.
+ */
+ public void testNoWriteThroughReadThrough() {
+ getField().setPropertyDataSource(new ObjectProperty<String>(""));
+ getField().setWriteThrough(false);
+ getField().setReadThrough(true);
+
+ expectValueChangeFromSetValueNotCommit();
+ }
+
+ protected void expectValueChangeFromSetValueNotCommit() {
+ // Expectations and start test
+ listener.valueChange(EasyMock.isA(ValueChangeEvent.class));
+ EasyMock.replay(listener);
+
+ // Add listener and set the value -> should end up in listener once
+ getField().addListener(listener);
+ setValue(getField());
+
+ // Ensure listener was called once
+ EasyMock.verify(listener);
+
+ // commit
+ getField().commit();
+
+ // Ensure listener was not called again
+ EasyMock.verify(listener);
+ }
+
- protected AbstractField getField() {
++ protected AbstractField<T> getField() {
+ return field;
+ }
+
+ /**
+ * Override in subclasses to set value with changeVariables().
+ */
- protected void setValue(AbstractField field) {
++ protected void setValue(AbstractField<T> field) {
+ field.setValue("newValue");
+ }
+
+ }
- package com.vaadin.tests.server.components;\r
- \r
- import java.util.HashMap;\r
- import java.util.Map;\r
- \r
- import com.vaadin.ui.AbstractField;\r
- import com.vaadin.ui.ComboBox;\r
- \r
- /**\r
- * Check that the value change listener for a combo box is triggered exactly\r
- * once when setting the value, at the correct time.\r
- * \r
- * See <a href="http://dev.vaadin.com/ticket/4394">Ticket 4394</a>.\r
- */\r
- public class TestComboBoxValueChange extends\r
- AbstractTestFieldValueChange<Object> {\r
- @Override\r
- protected void setUp() throws Exception {\r
- ComboBox combo = new ComboBox();\r
- combo.addItem("myvalue");\r
- super.setUp(combo);\r
- }\r
- \r
- @Override\r
- protected void setValue(AbstractField<Object> field) {\r
- Map<String, Object> variables = new HashMap<String, Object>();\r
- variables.put("selected", new String[] { "myvalue" });\r
- field.changeVariables(field, variables);\r
- }\r
- \r
- }\r
+ package com.vaadin.tests.server.components;
+
+ import java.util.HashMap;
+ import java.util.Map;
+
+ import com.vaadin.ui.AbstractField;
+ import com.vaadin.ui.ComboBox;
+
+ /**
+ * Check that the value change listener for a combo box is triggered exactly
+ * once when setting the value, at the correct time.
+ *
+ * See <a href="http://dev.vaadin.com/ticket/4394">Ticket 4394</a>.
+ */
-public class TestComboBoxValueChange extends AbstractTestFieldValueChange {
++public class TestComboBoxValueChange extends
++ AbstractTestFieldValueChange<Object> {
+ @Override
+ protected void setUp() throws Exception {
+ ComboBox combo = new ComboBox();
+ combo.addItem("myvalue");
+ super.setUp(combo);
+ }
+
+ @Override
- protected void setValue(AbstractField field) {
++ protected void setValue(AbstractField<Object> field) {
+ Map<String, Object> variables = new HashMap<String, Object>();
+ variables.put("selected", new String[] { "myvalue" });
+ field.changeVariables(field, variables);
+ }
+
+ }
- package com.vaadin.tests.server.components;\r
- \r
- import java.util.HashMap;\r
- import java.util.Map;\r
- \r
- import junit.framework.Assert;\r
- \r
- import org.easymock.EasyMock;\r
- \r
- import com.vaadin.data.Property.ValueChangeEvent;\r
- import com.vaadin.data.util.ObjectProperty;\r
- import com.vaadin.ui.AbstractField;\r
- import com.vaadin.ui.TextField;\r
- \r
- /**\r
- * Check that the value change listener for a text field is triggered exactly\r
- * once when setting the value, at the correct time.\r
- * \r
- * See <a href="http://dev.vaadin.com/ticket/4394">Ticket 4394</a>.\r
- */\r
- public class TestTextFieldValueChange extends\r
- AbstractTestFieldValueChange<String> {\r
- \r
- @Override\r
- protected void setUp() throws Exception {\r
- super.setUp(new TextField());\r
- }\r
- \r
- /**\r
- * Case where the text field only uses its internal buffer, no external\r
- * property data source.\r
- */\r
- public void testNoDataSource() {\r
- getField().setPropertyDataSource(null);\r
- \r
- expectValueChangeFromSetValueNotCommit();\r
- }\r
- \r
- @Override\r
- protected void setValue(AbstractField<String> field) {\r
- Map<String, Object> variables = new HashMap<String, Object>();\r
- variables.put("text", "newValue");\r
- field.changeVariables(field, variables);\r
- }\r
- \r
- /**\r
- * Test that field propagates value change events originating from property,\r
- * but don't fire value change events twice if value has only changed once.\r
- * \r
- * \r
- * TODO make test field type agnostic (eg. combobox)\r
- */\r
- public void testValueChangeEventPropagationWithReadThrough() {\r
- ObjectProperty<String> property = new ObjectProperty<String>("");\r
- getField().setPropertyDataSource(property);\r
- \r
- // defaults, buffering off\r
- getField().setBuffered(false);\r
- \r
- // Expectations and start test\r
- getListener().valueChange(EasyMock.isA(ValueChangeEvent.class));\r
- EasyMock.replay(getListener());\r
- \r
- // Add listener and set the value -> should end up in listener once\r
- getField().addListener(getListener());\r
- \r
- property.setValue("Foo");\r
- \r
- // Ensure listener was called once\r
- EasyMock.verify(getListener());\r
- \r
- // get value should not fire value change again\r
- Object value = getField().getValue();\r
- Assert.assertEquals("Foo", value);\r
- \r
- // Ensure listener still has been called only once\r
- EasyMock.verify(getListener());\r
- }\r
- \r
- /**\r
- * If read through is on and value has been modified, but not committed, the\r
- * value should not propagate similar to\r
- * {@link #testValueChangeEventPropagationWithReadThrough()}\r
- * \r
- * TODO make test field type agnostic (eg. combobox)\r
- */\r
- public void testValueChangePropagationWithReadThroughWithModifiedValue() {\r
- final String initialValue = "initial";\r
- ObjectProperty<String> property = new ObjectProperty<String>(\r
- initialValue);\r
- getField().setPropertyDataSource(property);\r
- \r
- // write buffering on, read buffering off\r
- getField().setWriteThrough(false);\r
- getField().setReadThrough(true);\r
- \r
- // Expect no value changes calls to listener\r
- EasyMock.replay(getListener());\r
- \r
- // first set the value (note, write through false -> not forwarded to\r
- // property)\r
- setValue(getField());\r
- \r
- Assert.assertTrue(getField().isModified());\r
- \r
- // Add listener and set the value -> should end up in listener once\r
- getField().addListener(getListener());\r
- \r
- // modify property value, should not fire value change in field as the\r
- // field has uncommitted value (aka isModified() == true)\r
- property.setValue("Foo");\r
- \r
- // Ensure listener was called once\r
- EasyMock.verify(getListener());\r
- \r
- // get value should not fire value change again\r
- Object value = getField().getValue();\r
- // Ensure listener still has been called only once\r
- EasyMock.verify(getListener());\r
- \r
- // field value should be different from the original value and current\r
- // proeprty value\r
- boolean isValueEqualToInitial = value.equals(initialValue);\r
- Assert.assertFalse(isValueEqualToInitial);\r
- boolean isValueEqualToPropertyValue = value.equals(property.getValue());\r
- Assert.assertFalse(isValueEqualToPropertyValue);\r
- \r
- // Ensure listener has not been called\r
- EasyMock.verify(getListener());\r
- \r
- }\r
- \r
- /**\r
- * Value change events from property should not propagate if read through is\r
- * false. Execpt when the property is being set.\r
- * \r
- * TODO make test field type agnostic (eg. combobox)\r
- */\r
- public void testValueChangePropagationWithReadThroughOff() {\r
- final String initialValue = "initial";\r
- ObjectProperty<String> property = new ObjectProperty<String>(\r
- initialValue);\r
- \r
- // set buffering\r
- getField().setBuffered(true);\r
- \r
- // Value change should only happen once, when setting the property,\r
- // further changes via property should not cause value change listener\r
- // in field to be notified\r
- getListener().valueChange(EasyMock.isA(ValueChangeEvent.class));\r
- EasyMock.replay(getListener());\r
- \r
- getField().addListener(getListener());\r
- getField().setPropertyDataSource(property);\r
- \r
- // Ensure listener was called once\r
- EasyMock.verify(getListener());\r
- \r
- // modify property value, should not fire value change in field as the\r
- // read buffering is on (read through == false)\r
- property.setValue("Foo");\r
- \r
- // Ensure listener still has been called only once\r
- EasyMock.verify(getListener());\r
- \r
- // get value should not fire value change again\r
- Object value = getField().getValue();\r
- \r
- // field value should be different from the original value and current\r
- // proeprty value\r
- boolean isValueEqualToInitial = value.equals(initialValue);\r
- Assert.assertTrue(isValueEqualToInitial);\r
- \r
- // Ensure listener still has been called only once\r
- EasyMock.verify(getListener());\r
- \r
- }\r
- \r
- }\r
+ package com.vaadin.tests.server.components;
+
+ import java.util.HashMap;
+ import java.util.Map;
+
+ import junit.framework.Assert;
+
+ import org.easymock.EasyMock;
+
+ import com.vaadin.data.Property.ValueChangeEvent;
+ import com.vaadin.data.util.ObjectProperty;
+ import com.vaadin.ui.AbstractField;
+ import com.vaadin.ui.TextField;
+
+ /**
+ * Check that the value change listener for a text field is triggered exactly
+ * once when setting the value, at the correct time.
+ *
+ * See <a href="http://dev.vaadin.com/ticket/4394">Ticket 4394</a>.
+ */
-public class TestTextFieldValueChange extends AbstractTestFieldValueChange {
++public class TestTextFieldValueChange extends
++ AbstractTestFieldValueChange<String> {
+
+ @Override
+ protected void setUp() throws Exception {
+ super.setUp(new TextField());
+ }
+
+ /**
+ * Case where the text field only uses its internal buffer, no external
+ * property data source.
+ */
+ public void testNoDataSource() {
+ getField().setPropertyDataSource(null);
+
+ expectValueChangeFromSetValueNotCommit();
+ }
+
+ @Override
- protected void setValue(AbstractField field) {
++ protected void setValue(AbstractField<String> field) {
+ Map<String, Object> variables = new HashMap<String, Object>();
+ variables.put("text", "newValue");
+ field.changeVariables(field, variables);
+ }
+
+ /**
+ * Test that field propagates value change events originating from property,
+ * but don't fire value change events twice if value has only changed once.
+ *
+ *
+ * TODO make test field type agnostic (eg. combobox)
+ */
+ public void testValueChangeEventPropagationWithReadThrough() {
+ ObjectProperty<String> property = new ObjectProperty<String>("");
+ getField().setPropertyDataSource(property);
+
+ // defaults, buffering off
- getField().setWriteThrough(true);
- getField().setReadThrough(true);
++ getField().setBuffered(false);
+
+ // Expectations and start test
+ getListener().valueChange(EasyMock.isA(ValueChangeEvent.class));
+ EasyMock.replay(getListener());
+
+ // Add listener and set the value -> should end up in listener once
+ getField().addListener(getListener());
+
+ property.setValue("Foo");
+
+ // Ensure listener was called once
+ EasyMock.verify(getListener());
+
+ // get value should not fire value change again
+ Object value = getField().getValue();
+ Assert.assertEquals("Foo", value);
+
+ // Ensure listener still has been called only once
+ EasyMock.verify(getListener());
+ }
+
+ /**
+ * If read through is on and value has been modified, but not committed, the
+ * value should not propagate similar to
+ * {@link #testValueChangeEventPropagationWithReadThrough()}
+ *
+ * TODO make test field type agnostic (eg. combobox)
+ */
+ public void testValueChangePropagationWithReadThroughWithModifiedValue() {
+ final String initialValue = "initial";
+ ObjectProperty<String> property = new ObjectProperty<String>(
+ initialValue);
+ getField().setPropertyDataSource(property);
+
+ // write buffering on, read buffering off
+ getField().setWriteThrough(false);
+ getField().setReadThrough(true);
+
+ // Expect no value changes calls to listener
+ EasyMock.replay(getListener());
+
+ // first set the value (note, write through false -> not forwarded to
+ // property)
+ setValue(getField());
+
+ Assert.assertTrue(getField().isModified());
+
+ // Add listener and set the value -> should end up in listener once
+ getField().addListener(getListener());
+
+ // modify property value, should not fire value change in field as the
+ // field has uncommitted value (aka isModified() == true)
+ property.setValue("Foo");
+
+ // Ensure listener was called once
+ EasyMock.verify(getListener());
+
+ // get value should not fire value change again
+ Object value = getField().getValue();
+ // Ensure listener still has been called only once
+ EasyMock.verify(getListener());
+
+ // field value should be different from the original value and current
+ // proeprty value
+ boolean isValueEqualToInitial = value.equals(initialValue);
+ Assert.assertFalse(isValueEqualToInitial);
+ boolean isValueEqualToPropertyValue = value.equals(property.getValue());
+ Assert.assertFalse(isValueEqualToPropertyValue);
+
+ // Ensure listener has not been called
+ EasyMock.verify(getListener());
+
+ }
+
+ /**
+ * Value change events from property should not propagate if read through is
+ * false. Execpt when the property is being set.
+ *
+ * TODO make test field type agnostic (eg. combobox)
+ */
+ public void testValueChangePropagationWithReadThroughOff() {
+ final String initialValue = "initial";
+ ObjectProperty<String> property = new ObjectProperty<String>(
+ initialValue);
+
+ // set buffering
- getField().setWriteThrough(false);
- getField().setReadThrough(false);
++ getField().setBuffered(true);
+
+ // Value change should only happen once, when setting the property,
+ // further changes via property should not cause value change listener
+ // in field to be notified
+ getListener().valueChange(EasyMock.isA(ValueChangeEvent.class));
+ EasyMock.replay(getListener());
+
+ getField().addListener(getListener());
+ getField().setPropertyDataSource(property);
+
+ // Ensure listener was called once
+ EasyMock.verify(getListener());
+
+ // modify property value, should not fire value change in field as the
+ // read buffering is on (read through == false)
+ property.setValue("Foo");
+
+ // Ensure listener still has been called only once
+ EasyMock.verify(getListener());
+
+ // get value should not fire value change again
+ Object value = getField().getValue();
+
+ // field value should be different from the original value and current
+ // proeprty value
+ boolean isValueEqualToInitial = value.equals(initialValue);
+ Assert.assertTrue(isValueEqualToInitial);
+
+ // Ensure listener still has been called only once
+ EasyMock.verify(getListener());
+
+ }
+
+ }
- package com.vaadin.tests.server.components;\r
- \r
- import java.util.HashMap;\r
- import java.util.Map;\r
- \r
- import junit.framework.TestCase;\r
- \r
- import org.easymock.EasyMock;\r
- \r
- import com.vaadin.ui.Root.LegacyWindow;\r
- import com.vaadin.ui.Window;\r
- import com.vaadin.ui.Window.CloseEvent;\r
- import com.vaadin.ui.Window.CloseListener;\r
- import com.vaadin.ui.Window.ResizeEvent;\r
- import com.vaadin.ui.Window.ResizeListener;\r
- \r
- public class TestWindow extends TestCase {\r
- \r
- private Window window;\r
- \r
- @Override\r
- protected void setUp() throws Exception {\r
- window = new Window();\r
- new LegacyWindow().addWindow(window);\r
- }\r
- \r
- public void testCloseListener() {\r
- CloseListener cl = EasyMock.createMock(Window.CloseListener.class);\r
- \r
- // Expectations\r
- cl.windowClose(EasyMock.isA(CloseEvent.class));\r
- \r
- // Start actual test\r
- EasyMock.replay(cl);\r
- \r
- // Add listener and send a close event -> should end up in listener once\r
- window.addListener(cl);\r
- sendClose(window);\r
- \r
- // Ensure listener was called once\r
- EasyMock.verify(cl);\r
- \r
- // Remove the listener and send close event -> should not end up in\r
- // listener\r
- window.removeListener(cl);\r
- sendClose(window);\r
- \r
- // Ensure listener still has been called only once\r
- EasyMock.verify(cl);\r
- \r
- }\r
- \r
- public void testResizeListener() {\r
- ResizeListener rl = EasyMock.createMock(Window.ResizeListener.class);\r
- \r
- // Expectations\r
- rl.windowResized(EasyMock.isA(ResizeEvent.class));\r
- \r
- // Start actual test\r
- EasyMock.replay(rl);\r
- \r
- // Add listener and send a resize event -> should end up in listener\r
- // once\r
- window.addListener(rl);\r
- sendResize(window);\r
- \r
- // Ensure listener was called once\r
- EasyMock.verify(rl);\r
- \r
- // Remove the listener and send close event -> should not end up in\r
- // listener\r
- window.removeListener(rl);\r
- sendResize(window);\r
- \r
- // Ensure listener still has been called only once\r
- EasyMock.verify(rl);\r
- \r
- }\r
- \r
- private void sendResize(Window window2) {\r
- Map<String, Object> variables = new HashMap<String, Object>();\r
- variables.put("height", 1234);\r
- window.changeVariables(window, variables);\r
- \r
- }\r
- \r
- private static void sendClose(Window window) {\r
- Map<String, Object> variables = new HashMap<String, Object>();\r
- variables.put("close", true);\r
- window.changeVariables(window, variables);\r
- }\r
- }\r
+ package com.vaadin.tests.server.components;
+
+ import java.util.HashMap;
+ import java.util.Map;
+
+ import junit.framework.TestCase;
+
+ import org.easymock.EasyMock;
+
++import com.vaadin.ui.Root.LegacyWindow;
+ import com.vaadin.ui.Window;
+ import com.vaadin.ui.Window.CloseEvent;
+ import com.vaadin.ui.Window.CloseListener;
+ import com.vaadin.ui.Window.ResizeEvent;
+ import com.vaadin.ui.Window.ResizeListener;
+
+ public class TestWindow extends TestCase {
+
+ private Window window;
+
+ @Override
+ protected void setUp() throws Exception {
+ window = new Window();
++ new LegacyWindow().addWindow(window);
+ }
+
+ public void testCloseListener() {
+ CloseListener cl = EasyMock.createMock(Window.CloseListener.class);
+
+ // Expectations
+ cl.windowClose(EasyMock.isA(CloseEvent.class));
+
+ // Start actual test
+ EasyMock.replay(cl);
+
+ // Add listener and send a close event -> should end up in listener once
+ window.addListener(cl);
+ sendClose(window);
+
+ // Ensure listener was called once
+ EasyMock.verify(cl);
+
+ // Remove the listener and send close event -> should not end up in
+ // listener
+ window.removeListener(cl);
+ sendClose(window);
+
+ // Ensure listener still has been called only once
+ EasyMock.verify(cl);
+
+ }
+
+ public void testResizeListener() {
+ ResizeListener rl = EasyMock.createMock(Window.ResizeListener.class);
+
+ // Expectations
+ rl.windowResized(EasyMock.isA(ResizeEvent.class));
+
+ // Start actual test
+ EasyMock.replay(rl);
+
+ // Add listener and send a resize event -> should end up in listener
+ // once
+ window.addListener(rl);
+ sendResize(window);
+
+ // Ensure listener was called once
+ EasyMock.verify(rl);
+
+ // Remove the listener and send close event -> should not end up in
+ // listener
+ window.removeListener(rl);
+ sendResize(window);
+
+ // Ensure listener still has been called only once
+ EasyMock.verify(rl);
+
+ }
+
+ private void sendResize(Window window2) {
+ Map<String, Object> variables = new HashMap<String, Object>();
+ variables.put("height", 1234);
+ window.changeVariables(window, variables);
+
+ }
+
+ private static void sendClose(Window window) {
+ Map<String, Object> variables = new HashMap<String, Object>();
+ variables.put("close", true);
+ window.changeVariables(window, variables);
+ }
+ }
--- /dev/null
- package com.vaadin.tests.server.validation;\r
- \r
- import junit.framework.TestCase;\r
- \r
- import com.vaadin.data.validator.IntegerRangeValidator;\r
- \r
- public class RangeValidatorTest extends TestCase {\r
- \r
- // This test uses IntegerRangeValidator for simplicity.\r
- // IntegerRangeValidator contains no code so we really are testing\r
- // RangeValidator\r
- public void testMinValueNonInclusive() {\r
- IntegerRangeValidator iv = new IntegerRangeValidator("Failed", 0, 10);\r
- iv.setMinValueIncluded(false);\r
- assertFalse(iv.isValid(0));\r
- assertTrue(iv.isValid(10));\r
- assertFalse(iv.isValid(11));\r
- assertFalse(iv.isValid(-1));\r
- }\r
- \r
- public void testMinMaxValuesInclusive() {\r
- IntegerRangeValidator iv = new IntegerRangeValidator("Failed", 0, 10);\r
- assertTrue(iv.isValid(0));\r
- assertTrue(iv.isValid(1));\r
- assertTrue(iv.isValid(10));\r
- assertFalse(iv.isValid(11));\r
- assertFalse(iv.isValid(-1));\r
- }\r
- \r
- public void testMaxValueNonInclusive() {\r
- IntegerRangeValidator iv = new IntegerRangeValidator("Failed", 0, 10);\r
- iv.setMaxValueIncluded(false);\r
- assertTrue(iv.isValid(0));\r
- assertTrue(iv.isValid(9));\r
- assertFalse(iv.isValid(10));\r
- assertFalse(iv.isValid(11));\r
- assertFalse(iv.isValid(-1));\r
- }\r
- \r
- public void testMinMaxValuesNonInclusive() {\r
- IntegerRangeValidator iv = new IntegerRangeValidator("Failed", 0, 10);\r
- iv.setMinValueIncluded(false);\r
- iv.setMaxValueIncluded(false);\r
- \r
- assertFalse(iv.isValid(0));\r
- assertTrue(iv.isValid(1));\r
- assertTrue(iv.isValid(9));\r
- assertFalse(iv.isValid(10));\r
- assertFalse(iv.isValid(11));\r
- assertFalse(iv.isValid(-1));\r
- }\r
- }\r
++package com.vaadin.tests.server.validation;
++
++import junit.framework.TestCase;
++
++import com.vaadin.data.validator.IntegerRangeValidator;
++
++public class RangeValidatorTest extends TestCase {
++
++ // This test uses IntegerRangeValidator for simplicity.
++ // IntegerRangeValidator contains no code so we really are testing
++ // RangeValidator
++ public void testMinValueNonInclusive() {
++ IntegerRangeValidator iv = new IntegerRangeValidator("Failed", 0, 10);
++ iv.setMinValueIncluded(false);
++ assertFalse(iv.isValid(0));
++ assertTrue(iv.isValid(10));
++ assertFalse(iv.isValid(11));
++ assertFalse(iv.isValid(-1));
++ }
++
++ public void testMinMaxValuesInclusive() {
++ IntegerRangeValidator iv = new IntegerRangeValidator("Failed", 0, 10);
++ assertTrue(iv.isValid(0));
++ assertTrue(iv.isValid(1));
++ assertTrue(iv.isValid(10));
++ assertFalse(iv.isValid(11));
++ assertFalse(iv.isValid(-1));
++ }
++
++ public void testMaxValueNonInclusive() {
++ IntegerRangeValidator iv = new IntegerRangeValidator("Failed", 0, 10);
++ iv.setMaxValueIncluded(false);
++ assertTrue(iv.isValid(0));
++ assertTrue(iv.isValid(9));
++ assertFalse(iv.isValid(10));
++ assertFalse(iv.isValid(11));
++ assertFalse(iv.isValid(-1));
++ }
++
++ public void testMinMaxValuesNonInclusive() {
++ IntegerRangeValidator iv = new IntegerRangeValidator("Failed", 0, 10);
++ iv.setMinValueIncluded(false);
++ iv.setMaxValueIncluded(false);
++
++ assertFalse(iv.isValid(0));
++ assertTrue(iv.isValid(1));
++ assertTrue(iv.isValid(9));
++ assertFalse(iv.isValid(10));
++ assertFalse(iv.isValid(11));
++ assertFalse(iv.isValid(-1));
++ }
++}
- package com.vaadin.tests.server.validation;\r
- \r
- import org.junit.Test;\r
- \r
- import com.vaadin.data.validator.IntegerValidator;\r
- import com.vaadin.ui.TextField;\r
- \r
- public class TestReadOnlyValidation {\r
- \r
- @Test\r
- public void testIntegerValidation() {\r
- TextField field = new TextField();\r
- field.addValidator(new IntegerValidator("Enter a Valid Number"));\r
- field.setValue(String.valueOf(10));\r
- field.validate();\r
- }\r
- }\r
+ package com.vaadin.tests.server.validation;
+
+ import org.junit.Test;
+
+ import com.vaadin.data.validator.IntegerValidator;
+ import com.vaadin.ui.TextField;
+
+ public class TestReadOnlyValidation {
+
+ @Test
+ public void testIntegerValidation() {
+ TextField field = new TextField();
+ field.addValidator(new IntegerValidator("Enter a Valid Number"));
- field.setValue(Integer.valueOf(10));
++ field.setValue(String.valueOf(10));
+ field.validate();
+ }
+ }
--- /dev/null
- package com.vaadin.tests.util;\r
- \r
- import java.lang.reflect.Modifier;\r
- import java.util.HashSet;\r
- import java.util.List;\r
- import java.util.Set;\r
- \r
- import com.vaadin.tests.VaadinClasses;\r
- \r
- public class GraphVizClassHierarchyCreator {\r
- \r
- public static void main(String[] args) {\r
- String gv = getGraphVizHierarchy((List) VaadinClasses.getComponents(),\r
- "com.vaadin");\r
- System.out.println(gv);\r
- }\r
- \r
- private static String getGraphVizHierarchy(List<Class> classes,\r
- String packageToInclude) {\r
- boolean includeInterfaces = false;\r
- \r
- StringBuilder header = new StringBuilder();\r
- header.append("digraph finite_state_machine {\n"\r
- + " rankdir=BT;\n" + " dpi=\"150\";\n"\r
- + " ratio=\"0.25\";\n");\r
- \r
- StringBuilder sb = new StringBuilder();\r
- \r
- Set<Class> classesAndParents = new HashSet<Class>();\r
- for (Class<?> cls : classes) {\r
- addClassAndParents(classesAndParents, cls, packageToInclude);\r
- }\r
- \r
- Set<Class> interfaces = new HashSet<Class>();\r
- for (Object cls : classesAndParents.toArray()) {\r
- for (Class<?> c : ((Class) cls).getInterfaces()) {\r
- addClassAndParentInterfaces(classesAndParents, c,\r
- packageToInclude);\r
- }\r
- }\r
- \r
- for (Class<?> c : classesAndParents) {\r
- appendClass(sb, c, c.getSuperclass(), packageToInclude,\r
- includeInterfaces);\r
- for (Class ci : c.getInterfaces()) {\r
- appendClass(sb, c, ci, packageToInclude, includeInterfaces);\r
- }\r
- }\r
- \r
- header.append(" node [shape = ellipse, style=\"dotted\"] ");\r
- for (Class c : classesAndParents) {\r
- if (!c.isInterface() && Modifier.isAbstract(c.getModifiers())) {\r
- header.append(c.getSimpleName() + " ");\r
- }\r
- }\r
- if (includeInterfaces) {\r
- System.out.print(" node [shape = ellipse, style=\"solid\"] ");\r
- for (Class c : classesAndParents) {\r
- if (c.isInterface()) {\r
- header.append(c.getSimpleName() + " ");\r
- }\r
- }\r
- header.append(";\n");\r
- }\r
- header.append(";\n");\r
- header.append(" node [shape = rectangle, style=\"solid\"];\n");\r
- return header.toString() + sb.toString() + "}";\r
- }\r
- \r
- private static void addClassAndParents(Set<Class> classesAndParents,\r
- Class<?> cls, String packageToInclude) {\r
- \r
- if (cls == null) {\r
- return;\r
- }\r
- \r
- if (classesAndParents.contains(cls)) {\r
- return;\r
- }\r
- \r
- if (!cls.getPackage().getName().startsWith(packageToInclude)) {\r
- return;\r
- }\r
- \r
- classesAndParents.add(cls);\r
- addClassAndParents(classesAndParents, cls.getSuperclass(),\r
- packageToInclude);\r
- \r
- }\r
- \r
- private static void addClassAndParentInterfaces(\r
- Set<Class> classesAndParents, Class<?> cls, String packageToInclude) {\r
- \r
- if (cls == null) {\r
- return;\r
- }\r
- \r
- if (classesAndParents.contains(cls)) {\r
- return;\r
- }\r
- \r
- if (!cls.getPackage().getName().startsWith(packageToInclude)) {\r
- return;\r
- }\r
- \r
- classesAndParents.add(cls);\r
- for (Class iClass : cls.getInterfaces()) {\r
- addClassAndParentInterfaces(classesAndParents, iClass,\r
- packageToInclude);\r
- }\r
- \r
- }\r
- \r
- private static void appendClass(StringBuilder sb, Class<?> c,\r
- Class<?> superClass, String packageToInclude,\r
- boolean includeInterfaces) {\r
- if (superClass == null) {\r
- return;\r
- }\r
- if (!c.getPackage().getName().startsWith(packageToInclude)) {\r
- return;\r
- }\r
- if (!superClass.getPackage().getName().startsWith(packageToInclude)) {\r
- return;\r
- }\r
- if (!includeInterfaces && (c.isInterface() || superClass.isInterface())) {\r
- return;\r
- }\r
- \r
- sb.append(c.getSimpleName()).append(" -> ")\r
- .append(superClass.getSimpleName()).append("\n");\r
- \r
- }\r
- \r
- private static void addInterfaces(Set<Class> interfaces, Class<?> cls) {\r
- if (interfaces.contains(cls)) {\r
- return;\r
- }\r
- \r
- if (cls.isInterface()) {\r
- interfaces.add(cls);\r
- }\r
- \r
- for (Class c : cls.getInterfaces()) {\r
- addInterfaces(interfaces, c);\r
- }\r
- }\r
- \r
- }\r
++package com.vaadin.tests.util;
++
++import java.lang.reflect.Modifier;
++import java.util.HashSet;
++import java.util.List;
++import java.util.Set;
++
++import com.vaadin.tests.VaadinClasses;
++
++public class GraphVizClassHierarchyCreator {
++
++ public static void main(String[] args) {
++ String gv = getGraphVizHierarchy((List) VaadinClasses.getComponents(),
++ "com.vaadin");
++ System.out.println(gv);
++ }
++
++ private static String getGraphVizHierarchy(List<Class> classes,
++ String packageToInclude) {
++ boolean includeInterfaces = false;
++
++ StringBuilder header = new StringBuilder();
++ header.append("digraph finite_state_machine {\n"
++ + " rankdir=BT;\n" + " dpi=\"150\";\n"
++ + " ratio=\"0.25\";\n");
++
++ StringBuilder sb = new StringBuilder();
++
++ Set<Class> classesAndParents = new HashSet<Class>();
++ for (Class<?> cls : classes) {
++ addClassAndParents(classesAndParents, cls, packageToInclude);
++ }
++
++ Set<Class> interfaces = new HashSet<Class>();
++ for (Object cls : classesAndParents.toArray()) {
++ for (Class<?> c : ((Class) cls).getInterfaces()) {
++ addClassAndParentInterfaces(classesAndParents, c,
++ packageToInclude);
++ }
++ }
++
++ for (Class<?> c : classesAndParents) {
++ appendClass(sb, c, c.getSuperclass(), packageToInclude,
++ includeInterfaces);
++ for (Class ci : c.getInterfaces()) {
++ appendClass(sb, c, ci, packageToInclude, includeInterfaces);
++ }
++ }
++
++ header.append(" node [shape = ellipse, style=\"dotted\"] ");
++ for (Class c : classesAndParents) {
++ if (!c.isInterface() && Modifier.isAbstract(c.getModifiers())) {
++ header.append(c.getSimpleName() + " ");
++ }
++ }
++ if (includeInterfaces) {
++ System.out.print(" node [shape = ellipse, style=\"solid\"] ");
++ for (Class c : classesAndParents) {
++ if (c.isInterface()) {
++ header.append(c.getSimpleName() + " ");
++ }
++ }
++ header.append(";\n");
++ }
++ header.append(";\n");
++ header.append(" node [shape = rectangle, style=\"solid\"];\n");
++ return header.toString() + sb.toString() + "}";
++ }
++
++ private static void addClassAndParents(Set<Class> classesAndParents,
++ Class<?> cls, String packageToInclude) {
++
++ if (cls == null) {
++ return;
++ }
++
++ if (classesAndParents.contains(cls)) {
++ return;
++ }
++
++ if (!cls.getPackage().getName().startsWith(packageToInclude)) {
++ return;
++ }
++
++ classesAndParents.add(cls);
++ addClassAndParents(classesAndParents, cls.getSuperclass(),
++ packageToInclude);
++
++ }
++
++ private static void addClassAndParentInterfaces(
++ Set<Class> classesAndParents, Class<?> cls, String packageToInclude) {
++
++ if (cls == null) {
++ return;
++ }
++
++ if (classesAndParents.contains(cls)) {
++ return;
++ }
++
++ if (!cls.getPackage().getName().startsWith(packageToInclude)) {
++ return;
++ }
++
++ classesAndParents.add(cls);
++ for (Class iClass : cls.getInterfaces()) {
++ addClassAndParentInterfaces(classesAndParents, iClass,
++ packageToInclude);
++ }
++
++ }
++
++ private static void appendClass(StringBuilder sb, Class<?> c,
++ Class<?> superClass, String packageToInclude,
++ boolean includeInterfaces) {
++ if (superClass == null) {
++ return;
++ }
++ if (!c.getPackage().getName().startsWith(packageToInclude)) {
++ return;
++ }
++ if (!superClass.getPackage().getName().startsWith(packageToInclude)) {
++ return;
++ }
++ if (!includeInterfaces && (c.isInterface() || superClass.isInterface())) {
++ return;
++ }
++
++ sb.append(c.getSimpleName()).append(" -> ")
++ .append(superClass.getSimpleName()).append("\n");
++
++ }
++
++ private static void addInterfaces(Set<Class> interfaces, Class<?> cls) {
++ if (interfaces.contains(cls)) {
++ return;
++ }
++
++ if (cls.isInterface()) {
++ interfaces.add(cls);
++ }
++
++ for (Class c : cls.getInterfaces()) {
++ addInterfaces(interfaces, c);
++ }
++ }
++
++}
--- /dev/null
- package com.vaadin.tests.util;\r
- \r
- import java.util.Iterator;\r
- \r
- import junit.framework.Assert;\r
- \r
- public class TestUtil {\r
- public static void assertArrays(Object[] actualObjects,\r
- Object[] expectedObjects) {\r
- Assert.assertEquals(\r
- "Actual contains a different number of values than was expected",\r
- expectedObjects.length, actualObjects.length);\r
- \r
- for (int i = 0; i < actualObjects.length; i++) {\r
- Object actual = actualObjects[i];\r
- Object expected = expectedObjects[i];\r
- \r
- Assert.assertEquals("Item[" + i + "] does not match", expected,\r
- actual);\r
- }\r
- \r
- }\r
- \r
- public static void assertIterableEquals(Iterable<?> iterable1,\r
- Iterable<?> iterable2) {\r
- Iterator<?> i1 = iterable1.iterator();\r
- Iterator<?> i2 = iterable2.iterator();\r
- \r
- while (i1.hasNext()) {\r
- Object o1 = i1.next();\r
- if (!i2.hasNext()) {\r
- Assert.fail("The second iterable contains fewer items than the first. The object "\r
- + o1 + " has no match in the second iterable.");\r
- }\r
- Object o2 = i2.next();\r
- Assert.assertEquals(o1, o2);\r
- }\r
- if (i2.hasNext()) {\r
- Assert.fail("The second iterable contains more items than the first. The object "\r
- + i2.next() + " has no match in the first iterable.");\r
- }\r
- }\r
- }\r
++package com.vaadin.tests.util;
++
++import java.util.Iterator;
++
++import junit.framework.Assert;
++
++public class TestUtil {
++ public static void assertArrays(Object[] actualObjects,
++ Object[] expectedObjects) {
++ Assert.assertEquals(
++ "Actual contains a different number of values than was expected",
++ expectedObjects.length, actualObjects.length);
++
++ for (int i = 0; i < actualObjects.length; i++) {
++ Object actual = actualObjects[i];
++ Object expected = expectedObjects[i];
++
++ Assert.assertEquals("Item[" + i + "] does not match", expected,
++ actual);
++ }
++
++ }
++
++ public static void assertIterableEquals(Iterable<?> iterable1,
++ Iterable<?> iterable2) {
++ Iterator<?> i1 = iterable1.iterator();
++ Iterator<?> i2 = iterable2.iterator();
++
++ while (i1.hasNext()) {
++ Object o1 = i1.next();
++ if (!i2.hasNext()) {
++ Assert.fail("The second iterable contains fewer items than the first. The object "
++ + o1 + " has no match in the second iterable.");
++ }
++ Object o2 = i2.next();
++ Assert.assertEquals(o1, o2);
++ }
++ if (i2.hasNext()) {
++ Assert.fail("The second iterable contains more items than the first. The object "
++ + i2.next() + " has no match in the first iterable.");
++ }
++ }
++}
- package com.vaadin.tests;\r
- \r
- import java.lang.reflect.Modifier;\r
- import java.util.ArrayList;\r
- import java.util.Collection;\r
- import java.util.HashMap;\r
- import java.util.HashSet;\r
- import java.util.List;\r
- import java.util.Map;\r
- import java.util.Set;\r
- \r
- import com.vaadin.Application;\r
- import com.vaadin.data.Item;\r
- import com.vaadin.data.util.DefaultItemSorter;\r
- import com.vaadin.data.util.HierarchicalContainer;\r
- import com.vaadin.event.ItemClickEvent;\r
- import com.vaadin.event.ItemClickEvent.ItemClickListener;\r
- import com.vaadin.terminal.ExternalResource;\r
- import com.vaadin.terminal.Sizeable;\r
- import com.vaadin.tests.components.AbstractComponentTest;\r
- import com.vaadin.ui.AbstractComponent;\r
- import com.vaadin.ui.Component;\r
- import com.vaadin.ui.ComponentContainer;\r
- import com.vaadin.ui.Embedded;\r
- import com.vaadin.ui.HorizontalSplitPanel;\r
- import com.vaadin.ui.Label;\r
- import com.vaadin.ui.Label.ContentMode;\r
- import com.vaadin.ui.Root.LegacyWindow;\r
- import com.vaadin.ui.Tree;\r
- import com.vaadin.ui.Tree.ItemStyleGenerator;\r
- import com.vaadin.ui.VerticalLayout;\r
- \r
- public class Components extends Application.LegacyApplication {\r
- \r
- private static final Object CAPTION = "c";\r
- private Map<Class<? extends AbstractComponentTest>, String> tests = new HashMap<Class<? extends AbstractComponentTest>, String>();\r
- private Tree naviTree;\r
- private HorizontalSplitPanel sp;\r
- private LegacyWindow mainWindow;\r
- private final Embedded applicationEmbedder = new Embedded();\r
- private String baseUrl;\r
- private List<Class<? extends Component>> componentsWithoutTests = new ArrayList<Class<? extends Component>>();\r
- \r
- {\r
- for (Class<?> c : VaadinClasses.getBasicComponentTests()) {\r
- String testClass = c.getSimpleName();\r
- tests.put((Class<? extends AbstractComponentTest>) c, testClass);\r
- }\r
- \r
- List<Class<? extends Component>> componentsWithoutTest = VaadinClasses\r
- .getComponents();\r
- Set<String> availableTests = new HashSet<String>();\r
- for (String testName : tests.values()) {\r
- availableTests.add(testName);\r
- }\r
- \r
- for (Class<? extends Component> component : componentsWithoutTest) {\r
- String baseName = component.getSimpleName();\r
- if (availableTests.contains(baseName + "es")) {\r
- continue;\r
- }\r
- if (availableTests.contains(baseName + "es2")) {\r
- continue;\r
- }\r
- if (availableTests.contains(baseName + "s2")) {\r
- continue;\r
- }\r
- if (availableTests.contains(baseName + "s")) {\r
- continue;\r
- }\r
- if (availableTests.contains(baseName + "Test")) {\r
- continue;\r
- }\r
- \r
- componentsWithoutTests.add(component);\r
- }\r
- \r
- }\r
- \r
- class MissingTest extends AbstractComponentTest<AbstractComponent> {\r
- @Override\r
- protected Class<AbstractComponent> getTestClass() {\r
- return null;\r
- }\r
- }\r
- \r
- @Override\r
- public void init() {\r
- mainWindow = new LegacyWindow();\r
- setTheme("tests-components");\r
- mainWindow.getContent().setSizeFull();\r
- setMainWindow(mainWindow);\r
- sp = new HorizontalSplitPanel();\r
- sp.setSizeFull();\r
- VerticalLayout naviLayout = new VerticalLayout();\r
- naviLayout\r
- .addComponent(new Label(\r
- "Click to open a test case.<br/>Right click to open test in a new window<br/><br/>",\r
- ContentMode.XHTML));\r
- naviLayout.addComponent(createMenu());\r
- naviLayout.addComponent(createMissingTestsList());\r
- \r
- sp.setFirstComponent(naviLayout);\r
- sp.setSplitPosition(250, Sizeable.UNITS_PIXELS);\r
- VerticalLayout embeddingLayout = new VerticalLayout();\r
- embeddingLayout.setSizeFull();\r
- embeddingLayout\r
- .addComponent(new Label(\r
- "<b>Do not use the embedded version for creating automated tests. Open the test in a new window before recording.</b><br/>",\r
- ContentMode.XHTML));\r
- applicationEmbedder.setSizeFull();\r
- embeddingLayout.addComponent(applicationEmbedder);\r
- embeddingLayout.setExpandRatio(applicationEmbedder, 1);\r
- sp.setSecondComponent(embeddingLayout);\r
- mainWindow.addComponent(sp);\r
- \r
- applicationEmbedder.setType(Embedded.TYPE_BROWSER);\r
- baseUrl = getURL().toString().replace(getClass().getName(), "")\r
- .replaceAll("//$", "/");\r
- }\r
- \r
- private Component createMissingTestsList() {\r
- String missingTests = "";\r
- for (Class<? extends Component> component : componentsWithoutTests) {\r
- String cls = "missing";\r
- if (component.getAnnotation(Deprecated.class) != null) {\r
- cls = "missing-deprecated";\r
- }\r
- missingTests += "<font class=\"" + cls + "\">"\r
- + component.getSimpleName() + "</font><br/>";\r
- }\r
- return new Label("<b>Components without a test:</B><br/>"\r
- + missingTests, ContentMode.XHTML);\r
- }\r
- \r
- private Component createMenu() {\r
- naviTree = new Tree();\r
- naviTree.setItemStyleGenerator(new ItemStyleGenerator() {\r
- \r
- public String getStyle(Object itemId) {\r
- Class<?> cls = (Class<?>) itemId;\r
- if (!isAbstract(cls)) {\r
- return "blue";\r
- }\r
- return null;\r
- }\r
- });\r
- HierarchicalContainer hc = new HierarchicalContainer();\r
- naviTree.setContainerDataSource(hc);\r
- DefaultItemSorter sorter = new DefaultItemSorter() {\r
- @SuppressWarnings("rawtypes")\r
- @Override\r
- public int compare(Object o1, Object o2) {\r
- if (o1 instanceof Class && o2 instanceof Class && o1 != null\r
- && o2 != null) {\r
- Class<?> c1 = (Class) o1;\r
- Class<?> c2 = (Class) o2;\r
- boolean a1 = isAbstract(c1);\r
- boolean a2 = isAbstract(c2);\r
- \r
- if (a1 && !a2) {\r
- return 1;\r
- } else if (!a1 && a2) {\r
- return -1;\r
- }\r
- \r
- }\r
- return super.compare(o1, o2);\r
- }\r
- };\r
- hc.setItemSorter(sorter);\r
- naviTree.addContainerProperty(CAPTION, String.class, "");\r
- naviTree.setItemCaptionPropertyId(CAPTION);\r
- for (Class<? extends AbstractComponentTest> cls : tests.keySet()) {\r
- addTreeItem(cls);\r
- }\r
- hc.sort(new Object[] { CAPTION }, new boolean[] { true });\r
- naviTree.setSelectable(false);\r
- for (Object o : naviTree.rootItemIds()) {\r
- expandAndSetChildrenAllowed(o);\r
- }\r
- \r
- naviTree.addListener(new ItemClickListener() {\r
- \r
- public void itemClick(ItemClickEvent event) {\r
- Class<?> cls = (Class<?>) event.getItemId();\r
- if (!isAbstract(cls)) {\r
- String url = baseUrl + cls.getName()\r
- + "?restartApplication";\r
- if (event.getButton() == ItemClickEvent.BUTTON_LEFT) {\r
- openEmbedded(url);\r
- naviTree.setValue(event.getItemId());\r
- } else if (event.getButton() == ItemClickEvent.BUTTON_RIGHT) {\r
- openInNewTab(url);\r
- }\r
- }\r
- }\r
- \r
- });\r
- return naviTree;\r
- }\r
- \r
- protected void openInNewTab(String url) {\r
- getMainWindow().open(new ExternalResource(url), "_blank");\r
- }\r
- \r
- protected void openEmbedded(String url) {\r
- applicationEmbedder.setSource(new ExternalResource(url));\r
- }\r
- \r
- private void expandAndSetChildrenAllowed(Object o) {\r
- Collection<?> children = naviTree.getChildren(o);\r
- if (children == null || children.size() == 0) {\r
- naviTree.setChildrenAllowed(o, false);\r
- } else {\r
- naviTree.expandItem(o);\r
- for (Object c : children) {\r
- expandAndSetChildrenAllowed(c);\r
- }\r
- }\r
- \r
- }\r
- \r
- protected boolean isAbstract(Class<?> cls) {\r
- return Modifier.isAbstract(cls.getModifiers());\r
- }\r
- \r
- @SuppressWarnings("unchecked")\r
- private void addTreeItem(Class<? extends AbstractComponentTest> cls) {\r
- String name = tests.get(cls);\r
- if (name == null) {\r
- name = cls.getSimpleName();\r
- }\r
- \r
- Class<? extends AbstractComponentTest> superClass = (Class<? extends AbstractComponentTest>) cls\r
- .getSuperclass();\r
- \r
- // This cast is needed only to make compilation through Ant work ..\r
- if (((Class<?>) cls) != AbstractComponentTest.class) {\r
- addTreeItem(superClass);\r
- }\r
- if (naviTree.containsId(cls)) {\r
- return;\r
- }\r
- \r
- Item i = naviTree.addItem(cls);\r
- i.getItemProperty(CAPTION).setValue(name);\r
- naviTree.setParent(cls, superClass);\r
- }\r
- \r
- protected Component createTestComponent(\r
- Class<? extends AbstractComponentTest> cls) {\r
- try {\r
- AbstractComponentTest t = cls.newInstance();\r
- t.init();\r
- ComponentContainer c = t.getMainWindow().getContent();\r
- t.getMainWindow().setContent(null);\r
- return c;\r
- } catch (InstantiationException e) {\r
- // TODO Auto-generated catch block\r
- e.printStackTrace();\r
- } catch (IllegalAccessException e) {\r
- // TODO Auto-generated catch block\r
- e.printStackTrace();\r
- }\r
- return null;\r
- }\r
- \r
- }\r
+ package com.vaadin.tests;
+
+ import java.lang.reflect.Modifier;
+ import java.util.ArrayList;
+ import java.util.Collection;
+ import java.util.HashMap;
+ import java.util.HashSet;
+ import java.util.List;
+ import java.util.Map;
+ import java.util.Set;
+
+ import com.vaadin.Application;
+ import com.vaadin.data.Item;
+ import com.vaadin.data.util.DefaultItemSorter;
+ import com.vaadin.data.util.HierarchicalContainer;
+ import com.vaadin.event.ItemClickEvent;
+ import com.vaadin.event.ItemClickEvent.ItemClickListener;
+ import com.vaadin.terminal.ExternalResource;
+ import com.vaadin.terminal.Sizeable;
+ import com.vaadin.tests.components.AbstractComponentTest;
+ import com.vaadin.ui.AbstractComponent;
+ import com.vaadin.ui.Component;
+ import com.vaadin.ui.ComponentContainer;
+ import com.vaadin.ui.Embedded;
+ import com.vaadin.ui.HorizontalSplitPanel;
+ import com.vaadin.ui.Label;
++import com.vaadin.ui.Label.ContentMode;
++import com.vaadin.ui.Root.LegacyWindow;
+ import com.vaadin.ui.Tree;
+ import com.vaadin.ui.Tree.ItemStyleGenerator;
+ import com.vaadin.ui.VerticalLayout;
-import com.vaadin.ui.Window;
+
-public class Components extends Application {
++public class Components extends Application.LegacyApplication {
+
+ private static final Object CAPTION = "c";
+ private Map<Class<? extends AbstractComponentTest>, String> tests = new HashMap<Class<? extends AbstractComponentTest>, String>();
+ private Tree naviTree;
+ private HorizontalSplitPanel sp;
- private Window mainWindow;
++ private LegacyWindow mainWindow;
+ private final Embedded applicationEmbedder = new Embedded();
+ private String baseUrl;
+ private List<Class<? extends Component>> componentsWithoutTests = new ArrayList<Class<? extends Component>>();
+
+ {
+ for (Class<?> c : VaadinClasses.getBasicComponentTests()) {
+ String testClass = c.getSimpleName();
+ tests.put((Class<? extends AbstractComponentTest>) c, testClass);
+ }
+
+ List<Class<? extends Component>> componentsWithoutTest = VaadinClasses
+ .getComponents();
+ Set<String> availableTests = new HashSet<String>();
+ for (String testName : tests.values()) {
+ availableTests.add(testName);
+ }
+
+ for (Class<? extends Component> component : componentsWithoutTest) {
+ String baseName = component.getSimpleName();
+ if (availableTests.contains(baseName + "es")) {
+ continue;
+ }
+ if (availableTests.contains(baseName + "es2")) {
+ continue;
+ }
+ if (availableTests.contains(baseName + "s2")) {
+ continue;
+ }
+ if (availableTests.contains(baseName + "s")) {
+ continue;
+ }
+ if (availableTests.contains(baseName + "Test")) {
+ continue;
+ }
+
+ componentsWithoutTests.add(component);
+ }
+
+ }
+
+ class MissingTest extends AbstractComponentTest<AbstractComponent> {
+ @Override
+ protected Class<AbstractComponent> getTestClass() {
+ return null;
+ }
+ }
+
+ @Override
+ public void init() {
- mainWindow = new Window();
++ mainWindow = new LegacyWindow();
+ setTheme("tests-components");
+ mainWindow.getContent().setSizeFull();
+ setMainWindow(mainWindow);
+ sp = new HorizontalSplitPanel();
+ sp.setSizeFull();
+ VerticalLayout naviLayout = new VerticalLayout();
+ naviLayout
+ .addComponent(new Label(
+ "Click to open a test case.<br/>Right click to open test in a new window<br/><br/>",
- Label.CONTENT_XHTML));
++ ContentMode.XHTML));
+ naviLayout.addComponent(createMenu());
+ naviLayout.addComponent(createMissingTestsList());
+
+ sp.setFirstComponent(naviLayout);
+ sp.setSplitPosition(250, Sizeable.UNITS_PIXELS);
+ VerticalLayout embeddingLayout = new VerticalLayout();
+ embeddingLayout.setSizeFull();
+ embeddingLayout
+ .addComponent(new Label(
+ "<b>Do not use the embedded version for creating automated tests. Open the test in a new window before recording.</b><br/>",
- Label.CONTENT_XHTML));
++ ContentMode.XHTML));
+ applicationEmbedder.setSizeFull();
+ embeddingLayout.addComponent(applicationEmbedder);
+ embeddingLayout.setExpandRatio(applicationEmbedder, 1);
+ sp.setSecondComponent(embeddingLayout);
+ mainWindow.addComponent(sp);
+
+ applicationEmbedder.setType(Embedded.TYPE_BROWSER);
+ baseUrl = getURL().toString().replace(getClass().getName(), "")
+ .replaceAll("//$", "/");
+ }
+
+ private Component createMissingTestsList() {
+ String missingTests = "";
+ for (Class<? extends Component> component : componentsWithoutTests) {
+ String cls = "missing";
+ if (component.getAnnotation(Deprecated.class) != null) {
+ cls = "missing-deprecated";
+ }
+ missingTests += "<font class=\"" + cls + "\">"
+ + component.getSimpleName() + "</font><br/>";
+ }
+ return new Label("<b>Components without a test:</B><br/>"
- + missingTests, Label.CONTENT_XHTML);
++ + missingTests, ContentMode.XHTML);
+ }
+
+ private Component createMenu() {
+ naviTree = new Tree();
+ naviTree.setItemStyleGenerator(new ItemStyleGenerator() {
+
+ public String getStyle(Object itemId) {
+ Class<?> cls = (Class<?>) itemId;
+ if (!isAbstract(cls)) {
+ return "blue";
+ }
+ return null;
+ }
+ });
+ HierarchicalContainer hc = new HierarchicalContainer();
+ naviTree.setContainerDataSource(hc);
+ DefaultItemSorter sorter = new DefaultItemSorter() {
+ @SuppressWarnings("rawtypes")
+ @Override
+ public int compare(Object o1, Object o2) {
+ if (o1 instanceof Class && o2 instanceof Class && o1 != null
+ && o2 != null) {
+ Class<?> c1 = (Class) o1;
+ Class<?> c2 = (Class) o2;
+ boolean a1 = isAbstract(c1);
+ boolean a2 = isAbstract(c2);
+
+ if (a1 && !a2) {
+ return 1;
+ } else if (!a1 && a2) {
+ return -1;
+ }
+
+ }
+ return super.compare(o1, o2);
+ }
+ };
+ hc.setItemSorter(sorter);
+ naviTree.addContainerProperty(CAPTION, String.class, "");
+ naviTree.setItemCaptionPropertyId(CAPTION);
+ for (Class<? extends AbstractComponentTest> cls : tests.keySet()) {
+ addTreeItem(cls);
+ }
+ hc.sort(new Object[] { CAPTION }, new boolean[] { true });
+ naviTree.setSelectable(false);
+ for (Object o : naviTree.rootItemIds()) {
+ expandAndSetChildrenAllowed(o);
+ }
+
+ naviTree.addListener(new ItemClickListener() {
+
+ public void itemClick(ItemClickEvent event) {
+ Class<?> cls = (Class<?>) event.getItemId();
+ if (!isAbstract(cls)) {
+ String url = baseUrl + cls.getName()
+ + "?restartApplication";
+ if (event.getButton() == ItemClickEvent.BUTTON_LEFT) {
+ openEmbedded(url);
+ naviTree.setValue(event.getItemId());
+ } else if (event.getButton() == ItemClickEvent.BUTTON_RIGHT) {
+ openInNewTab(url);
+ }
+ }
+ }
+
+ });
+ return naviTree;
+ }
+
+ protected void openInNewTab(String url) {
+ getMainWindow().open(new ExternalResource(url), "_blank");
+ }
+
+ protected void openEmbedded(String url) {
+ applicationEmbedder.setSource(new ExternalResource(url));
+ }
+
+ private void expandAndSetChildrenAllowed(Object o) {
+ Collection<?> children = naviTree.getChildren(o);
+ if (children == null || children.size() == 0) {
+ naviTree.setChildrenAllowed(o, false);
+ } else {
+ naviTree.expandItem(o);
+ for (Object c : children) {
+ expandAndSetChildrenAllowed(c);
+ }
+ }
+
+ }
+
+ protected boolean isAbstract(Class<?> cls) {
+ return Modifier.isAbstract(cls.getModifiers());
+ }
+
+ @SuppressWarnings("unchecked")
+ private void addTreeItem(Class<? extends AbstractComponentTest> cls) {
+ String name = tests.get(cls);
+ if (name == null) {
+ name = cls.getSimpleName();
+ }
+
+ Class<? extends AbstractComponentTest> superClass = (Class<? extends AbstractComponentTest>) cls
+ .getSuperclass();
+
+ // This cast is needed only to make compilation through Ant work ..
+ if (((Class<?>) cls) != AbstractComponentTest.class) {
+ addTreeItem(superClass);
+ }
+ if (naviTree.containsId(cls)) {
+ return;
+ }
+
+ Item i = naviTree.addItem(cls);
+ i.getItemProperty(CAPTION).setValue(name);
+ naviTree.setParent(cls, superClass);
+ }
+
+ protected Component createTestComponent(
+ Class<? extends AbstractComponentTest> cls) {
+ try {
+ AbstractComponentTest t = cls.newInstance();
+ t.init();
+ ComponentContainer c = t.getMainWindow().getContent();
+ t.getMainWindow().setContent(null);
+ return c;
+ } catch (InstantiationException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ } catch (IllegalAccessException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+ return null;
+ }
+
+ }
- /**\r
- * \r
- */\r
- package com.vaadin.tests;\r
- \r
- import com.vaadin.ui.Button;\r
- import com.vaadin.ui.Button.ClickEvent;\r
- import com.vaadin.ui.CustomComponent;\r
- import com.vaadin.ui.GridLayout;\r
- import com.vaadin.ui.Label;\r
- import com.vaadin.ui.Notification;\r
- import com.vaadin.ui.Panel;\r
- import com.vaadin.ui.Root;\r
- import com.vaadin.ui.VerticalLayout;\r
- \r
- /**\r
- * @author marc\r
- * \r
- */\r
- public class TestComponentAddAndRecursion extends CustomComponent {\r
- Panel p;\r
- Panel p2;\r
- Label l;\r
- Label l2;\r
- Panel p3;\r
- \r
- public TestComponentAddAndRecursion() {\r
- \r
- VerticalLayout main = new VerticalLayout();\r
- setCompositionRoot(main);\r
- \r
- l = new Label("A");\r
- l2 = new Label("B");\r
- p = new Panel("p");\r
- p.addComponent(l);\r
- p.addComponent(l2);\r
- main.addComponent(p);\r
- p2 = new Panel("p2");\r
- p2.addComponent(l);\r
- main.addComponent(p2);\r
- p3 = new Panel("p3");\r
- p2.addComponent(p3);\r
- \r
- Button b = new Button("use gridlayout", new Button.ClickListener() {\r
- \r
- public void buttonClick(ClickEvent event) {\r
- p.setContent(new GridLayout());\r
- p2.setContent(new GridLayout());\r
- p3.setContent(new GridLayout());\r
- }\r
- \r
- });\r
- main.addComponent(b);\r
- b = new Button("use orderedlayout", new Button.ClickListener() {\r
- \r
- public void buttonClick(ClickEvent event) {\r
- p.setContent(new VerticalLayout());\r
- p2.setContent(new VerticalLayout());\r
- p3.setContent(new VerticalLayout());\r
- }\r
- \r
- });\r
- main.addComponent(b);\r
- b = new Button("move B", new Button.ClickListener() {\r
- \r
- public void buttonClick(ClickEvent event) {\r
- p2.addComponent(l2);\r
- }\r
- \r
- });\r
- main.addComponent(b);\r
- b = new Button("move p", new Button.ClickListener() {\r
- \r
- public void buttonClick(ClickEvent event) {\r
- p3.addComponent(p);\r
- }\r
- \r
- });\r
- main.addComponent(b);\r
- b = new Button("add to both", new Button.ClickListener() {\r
- \r
- public void buttonClick(ClickEvent event) {\r
- Label l = new Label("both");\r
- p.addComponent(l);\r
- p2.addComponent(l);\r
- }\r
- \r
- });\r
- main.addComponent(b);\r
- b = new Button("recurse", new Button.ClickListener() {\r
- \r
- public void buttonClick(ClickEvent event) {\r
- try {\r
- p3.addComponent(p2);\r
- Root.getCurrentRoot().showNotification("ERROR",\r
- "This should have failed",\r
- Notification.TYPE_ERROR_MESSAGE);\r
- } catch (Exception e) {\r
- Root.getCurrentRoot().showNotification("OK",\r
- "threw, as expected",\r
- Notification.TYPE_ERROR_MESSAGE);\r
- }\r
- }\r
- \r
- });\r
- main.addComponent(b);\r
- b = new Button("recurse2", new Button.ClickListener() {\r
- \r
- public void buttonClick(ClickEvent event) {\r
- Panel p = new Panel("dynamic");\r
- p.addComponent(p2);\r
- try {\r
- p3.addComponent(p);\r
- Root.getCurrentRoot().showNotification("ERROR",\r
- "This should have failed",\r
- Notification.TYPE_ERROR_MESSAGE);\r
- } catch (Exception e) {\r
- Root.getCurrentRoot().showNotification("OK",\r
- "threw, as expected",\r
- Notification.TYPE_ERROR_MESSAGE);\r
- }\r
- }\r
- \r
- });\r
- main.addComponent(b);\r
- /*\r
- * And that's it! The framework will display the main window and its\r
- * contents when the application is accessed with the terminal.\r
- */\r
- }\r
- }\r
+ /**
+ *
+ */
+ package com.vaadin.tests;
+
+ import com.vaadin.ui.Button;
+ import com.vaadin.ui.Button.ClickEvent;
+ import com.vaadin.ui.CustomComponent;
+ import com.vaadin.ui.GridLayout;
+ import com.vaadin.ui.Label;
++import com.vaadin.ui.Notification;
+ import com.vaadin.ui.Panel;
++import com.vaadin.ui.Root;
+ import com.vaadin.ui.VerticalLayout;
-import com.vaadin.ui.Window;
+
+ /**
+ * @author marc
+ *
+ */
+ public class TestComponentAddAndRecursion extends CustomComponent {
+ Panel p;
+ Panel p2;
+ Label l;
+ Label l2;
+ Panel p3;
+
+ public TestComponentAddAndRecursion() {
+
+ VerticalLayout main = new VerticalLayout();
+ setCompositionRoot(main);
+
+ l = new Label("A");
+ l2 = new Label("B");
+ p = new Panel("p");
+ p.addComponent(l);
+ p.addComponent(l2);
+ main.addComponent(p);
+ p2 = new Panel("p2");
+ p2.addComponent(l);
+ main.addComponent(p2);
+ p3 = new Panel("p3");
+ p2.addComponent(p3);
+
+ Button b = new Button("use gridlayout", new Button.ClickListener() {
+
+ public void buttonClick(ClickEvent event) {
+ p.setContent(new GridLayout());
+ p2.setContent(new GridLayout());
+ p3.setContent(new GridLayout());
+ }
+
+ });
+ main.addComponent(b);
+ b = new Button("use orderedlayout", new Button.ClickListener() {
+
+ public void buttonClick(ClickEvent event) {
+ p.setContent(new VerticalLayout());
+ p2.setContent(new VerticalLayout());
+ p3.setContent(new VerticalLayout());
+ }
+
+ });
+ main.addComponent(b);
+ b = new Button("move B", new Button.ClickListener() {
+
+ public void buttonClick(ClickEvent event) {
+ p2.addComponent(l2);
+ }
+
+ });
+ main.addComponent(b);
+ b = new Button("move p", new Button.ClickListener() {
+
+ public void buttonClick(ClickEvent event) {
+ p3.addComponent(p);
+ }
+
+ });
+ main.addComponent(b);
+ b = new Button("add to both", new Button.ClickListener() {
+
+ public void buttonClick(ClickEvent event) {
+ Label l = new Label("both");
+ p.addComponent(l);
+ p2.addComponent(l);
+ }
+
+ });
+ main.addComponent(b);
+ b = new Button("recurse", new Button.ClickListener() {
+
+ public void buttonClick(ClickEvent event) {
+ try {
+ p3.addComponent(p2);
- getWindow().showNotification("ERROR",
++ Root.getCurrentRoot().showNotification("ERROR",
+ "This should have failed",
- Window.Notification.TYPE_ERROR_MESSAGE);
++ Notification.TYPE_ERROR_MESSAGE);
+ } catch (Exception e) {
- getWindow().showNotification("OK", "threw, as expected",
- Window.Notification.TYPE_ERROR_MESSAGE);
++ Root.getCurrentRoot().showNotification("OK",
++ "threw, as expected",
++ Notification.TYPE_ERROR_MESSAGE);
+ }
+ }
+
+ });
+ main.addComponent(b);
+ b = new Button("recurse2", new Button.ClickListener() {
+
+ public void buttonClick(ClickEvent event) {
+ Panel p = new Panel("dynamic");
+ p.addComponent(p2);
+ try {
+ p3.addComponent(p);
- getWindow().showNotification("ERROR",
++ Root.getCurrentRoot().showNotification("ERROR",
+ "This should have failed",
- Window.Notification.TYPE_ERROR_MESSAGE);
++ Notification.TYPE_ERROR_MESSAGE);
+ } catch (Exception e) {
- getWindow().showNotification("OK", "threw, as expected",
- Window.Notification.TYPE_ERROR_MESSAGE);
++ Root.getCurrentRoot().showNotification("OK",
++ "threw, as expected",
++ Notification.TYPE_ERROR_MESSAGE);
+ }
+ }
+
+ });
+ main.addComponent(b);
+ /*
+ * And that's it! The framework will display the main window and its
+ * contents when the application is accessed with the terminal.
+ */
+ }
+ }
- package com.vaadin.tests.application;\r
- \r
- import com.vaadin.Application;\r
- import com.vaadin.terminal.gwt.server.WebApplicationContext;\r
- import com.vaadin.tests.components.TestBase;\r
- import com.vaadin.ui.Button;\r
- import com.vaadin.ui.Button.ClickEvent;\r
- import com.vaadin.ui.Label;\r
- import com.vaadin.ui.Label.ContentMode;\r
- \r
- public class ApplicationCloseTest extends TestBase {\r
- \r
- private String memoryConsumer;\r
- \r
- @Override\r
- protected void setup() {\r
- Label applications = new Label("Applications in session: <br/>",\r
- ContentMode.XHTML);\r
- for (Application a : ((WebApplicationContext) getContext())\r
- .getApplications()) {\r
- applications.setValue(applications.getValue() + "App: " + a\r
- + "<br/>");\r
- }\r
- applications.setValue(applications.getValue() + "<br/><br/>");\r
- \r
- addComponent(applications);\r
- Label thisApp = new Label("This applications: " + this);\r
- Button close = new Button("Close this", new Button.ClickListener() {\r
- \r
- public void buttonClick(ClickEvent event) {\r
- event.getButton().getApplication().close();\r
- }\r
- });\r
- \r
- StringBuilder sb = new StringBuilder();\r
- \r
- // 100 bytes\r
- String str = "0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789";\r
- \r
- int MB = 5;\r
- for (int i = 0; i < MB * 10000; i++) {\r
- sb.append(str);\r
- }\r
- \r
- memoryConsumer = sb.toString();\r
- long totalUsage = Runtime.getRuntime().totalMemory();\r
- String totalUsageString = totalUsage / 1000 / 1000 + "MiB";\r
- Label memoryUsage = new Label(\r
- "Using about "\r
- + memoryConsumer.length()\r
- / 1000\r
- / 1000\r
- + "MiB memory for this application.<br/>Total memory usage reported as "\r
- + totalUsageString + "<br/>", ContentMode.XHTML);\r
- \r
- addComponent(thisApp);\r
- addComponent(memoryUsage);\r
- addComponent(close);\r
- }\r
- \r
- @Override\r
- protected String getDescription() {\r
- return "Click close to close the application and open a new one";\r
- }\r
- \r
- @Override\r
- protected Integer getTicketNumber() {\r
- return 3732;\r
- }\r
- \r
- }\r
+ package com.vaadin.tests.application;
+
+ import com.vaadin.Application;
+ import com.vaadin.terminal.gwt.server.WebApplicationContext;
+ import com.vaadin.tests.components.TestBase;
+ import com.vaadin.ui.Button;
+ import com.vaadin.ui.Button.ClickEvent;
+ import com.vaadin.ui.Label;
++import com.vaadin.ui.Label.ContentMode;
+
+ public class ApplicationCloseTest extends TestBase {
+
+ private String memoryConsumer;
+
+ @Override
+ protected void setup() {
+ Label applications = new Label("Applications in session: <br/>",
- Label.CONTENT_XHTML);
++ ContentMode.XHTML);
+ for (Application a : ((WebApplicationContext) getContext())
+ .getApplications()) {
+ applications.setValue(applications.getValue() + "App: " + a
+ + "<br/>");
+ }
+ applications.setValue(applications.getValue() + "<br/><br/>");
+
+ addComponent(applications);
+ Label thisApp = new Label("This applications: " + this);
+ Button close = new Button("Close this", new Button.ClickListener() {
+
+ public void buttonClick(ClickEvent event) {
+ event.getButton().getApplication().close();
+ }
+ });
+
+ StringBuilder sb = new StringBuilder();
+
+ // 100 bytes
+ String str = "0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789";
+
+ int MB = 5;
+ for (int i = 0; i < MB * 10000; i++) {
+ sb.append(str);
+ }
+
+ memoryConsumer = sb.toString();
+ long totalUsage = Runtime.getRuntime().totalMemory();
+ String totalUsageString = totalUsage / 1000 / 1000 + "MiB";
+ Label memoryUsage = new Label(
+ "Using about "
+ + memoryConsumer.length()
+ / 1000
+ / 1000
+ + "MiB memory for this application.<br/>Total memory usage reported as "
- + totalUsageString + "<br/>", Label.CONTENT_XHTML);
++ + totalUsageString + "<br/>", ContentMode.XHTML);
+
+ addComponent(thisApp);
+ addComponent(memoryUsage);
+ addComponent(close);
+ }
+
+ @Override
+ protected String getDescription() {
+ return "Click close to close the application and open a new one";
+ }
+
+ @Override
+ protected Integer getTicketNumber() {
+ return 3732;
+ }
+
+ }
- package com.vaadin.tests.applicationcontext;\r
- \r
- import com.vaadin.terminal.gwt.server.WebApplicationContext;\r
- import com.vaadin.tests.components.AbstractTestCase;\r
- import com.vaadin.tests.util.Log;\r
- import com.vaadin.ui.Button;\r
- import com.vaadin.ui.Button.ClickEvent;\r
- import com.vaadin.ui.Button.ClickListener;\r
- import com.vaadin.ui.Root.LegacyWindow;\r
- \r
- public class ChangeSessionId extends AbstractTestCase {\r
- \r
- private Log log = new Log(5);\r
- Button loginButton = new Button("Change session");\r
- boolean requestSessionSwitch = false;\r
- \r
- @Override\r
- public void init() {\r
- LegacyWindow mainWindow = new LegacyWindow("Sestest Application");\r
- mainWindow.addComponent(log);\r
- mainWindow.addComponent(loginButton);\r
- mainWindow.addComponent(new Button("Show session id",\r
- new Button.ClickListener() {\r
- \r
- public void buttonClick(ClickEvent event) {\r
- logSessionId();\r
- }\r
- }));\r
- setMainWindow(mainWindow);\r
- \r
- loginButton.addListener(new ClickListener() {\r
- public void buttonClick(ClickEvent event) {\r
- WebApplicationContext context = ((WebApplicationContext) getContext());\r
- \r
- String oldSessionId = context.getHttpSession().getId();\r
- context.reinitializeSession();\r
- String newSessionId = context.getHttpSession().getId();\r
- if (oldSessionId.equals(newSessionId)) {\r
- log.log("FAILED! Both old and new session id is "\r
- + newSessionId);\r
- } else {\r
- log.log("Session id changed successfully from "\r
- + oldSessionId + " to " + newSessionId);\r
- }\r
- \r
- }\r
- });\r
- logSessionId();\r
- }\r
- \r
- private void logSessionId() {\r
- log.log("Session id: " + getSessionId());\r
- }\r
- \r
- protected String getSessionId() {\r
- return ((WebApplicationContext) getContext()).getHttpSession().getId();\r
- }\r
- \r
- @Override\r
- protected String getDescription() {\r
- return "Tests that the session id can be changed to prevent session fixation attacks";\r
- }\r
- \r
- @Override\r
- protected Integer getTicketNumber() {\r
- return 6094;\r
- }\r
- \r
+ package com.vaadin.tests.applicationcontext;
+
+ import com.vaadin.terminal.gwt.server.WebApplicationContext;
+ import com.vaadin.tests.components.AbstractTestCase;
+ import com.vaadin.tests.util.Log;
+ import com.vaadin.ui.Button;
+ import com.vaadin.ui.Button.ClickEvent;
+ import com.vaadin.ui.Button.ClickListener;
-import com.vaadin.ui.Window;
++import com.vaadin.ui.Root.LegacyWindow;
+
+ public class ChangeSessionId extends AbstractTestCase {
+
+ private Log log = new Log(5);
+ Button loginButton = new Button("Change session");
+ boolean requestSessionSwitch = false;
+
+ @Override
+ public void init() {
- Window mainWindow = new Window("Sestest Application");
++ LegacyWindow mainWindow = new LegacyWindow("Sestest Application");
+ mainWindow.addComponent(log);
+ mainWindow.addComponent(loginButton);
+ mainWindow.addComponent(new Button("Show session id",
+ new Button.ClickListener() {
+
+ public void buttonClick(ClickEvent event) {
+ logSessionId();
+ }
+ }));
+ setMainWindow(mainWindow);
+
+ loginButton.addListener(new ClickListener() {
+ public void buttonClick(ClickEvent event) {
+ WebApplicationContext context = ((WebApplicationContext) getContext());
+
+ String oldSessionId = context.getHttpSession().getId();
+ context.reinitializeSession();
+ String newSessionId = context.getHttpSession().getId();
+ if (oldSessionId.equals(newSessionId)) {
+ log.log("FAILED! Both old and new session id is "
+ + newSessionId);
+ } else {
+ log.log("Session id changed successfully from "
+ + oldSessionId + " to " + newSessionId);
+ }
+
+ }
+ });
+ logSessionId();
+ }
+
+ private void logSessionId() {
+ log.log("Session id: " + getSessionId());
+ }
+
+ protected String getSessionId() {
+ return ((WebApplicationContext) getContext()).getHttpSession().getId();
+ }
+
+ @Override
+ protected String getDescription() {
+ return "Tests that the session id can be changed to prevent session fixation attacks";
+ }
+
+ @Override
+ protected Integer getTicketNumber() {
+ return 6094;
+ }
+
}
- package com.vaadin.tests.components;\r
- \r
- import java.util.HashSet;\r
- import java.util.Iterator;\r
- import java.util.LinkedHashMap;\r
- \r
- import com.vaadin.ui.AbstractComponentContainer;\r
- import com.vaadin.ui.Button;\r
- import com.vaadin.ui.Component;\r
- import com.vaadin.ui.ComponentContainer.ComponentAttachEvent;\r
- import com.vaadin.ui.ComponentContainer.ComponentAttachListener;\r
- import com.vaadin.ui.ComponentContainer.ComponentDetachEvent;\r
- import com.vaadin.ui.ComponentContainer.ComponentDetachListener;\r
- import com.vaadin.ui.HorizontalSplitPanel;\r
- import com.vaadin.ui.InlineDateField;\r
- import com.vaadin.ui.NativeButton;\r
- import com.vaadin.ui.PopupDateField;\r
- import com.vaadin.ui.RichTextArea;\r
- import com.vaadin.ui.TabSheet;\r
- import com.vaadin.ui.Table;\r
- import com.vaadin.ui.TextArea;\r
- import com.vaadin.ui.TextField;\r
- import com.vaadin.ui.VerticalSplitPanel;\r
- \r
- public abstract class AbstractComponentContainerTest<T extends AbstractComponentContainer>\r
- extends AbstractComponentTest<T> implements ComponentAttachListener,\r
- ComponentDetachListener {\r
- \r
- private String CATEGORY_COMPONENT_CONTAINER_FEATURES = "Component container features";\r
- private Command<T, ComponentSize> addButtonCommand = new Command<T, ComponentSize>() {\r
- \r
- public void execute(T c, ComponentSize size, Object data) {\r
- Button b = new Button("A button");\r
- c.addComponent(b);\r
- size.apply(b);\r
- }\r
- };\r
- \r
- private Command<T, ComponentSize> addNativeButtonCommand = new Command<T, ComponentSize>() {\r
- \r
- public void execute(T c, ComponentSize size, Object data) {\r
- NativeButton b = new NativeButton("Native button");\r
- c.addComponent(b);\r
- size.apply(b);\r
- }\r
- };\r
- \r
- private Command<T, ComponentSize> addTextAreaCommand = new Command<T, ComponentSize>() {\r
- public void execute(T c, ComponentSize size, Object data) {\r
- TextArea ta = new TextArea();\r
- c.addComponent(ta);\r
- size.apply(ta);\r
- }\r
- };\r
- \r
- private Command<T, ComponentSize> addRichTextAreaCommand = new Command<T, ComponentSize>() {\r
- public void execute(T c, ComponentSize size, Object data) {\r
- RichTextArea ta = new RichTextArea();\r
- c.addComponent(ta);\r
- size.apply(ta);\r
- }\r
- };\r
- \r
- private Command<T, ComponentSize> addTextFieldCommand = new Command<T, ComponentSize>() {\r
- public void execute(T c, ComponentSize size, Object data) {\r
- TextField tf = new TextField();\r
- c.addComponent(tf);\r
- size.apply(tf);\r
- }\r
- };\r
- \r
- private Command<T, ComponentSize> addInlineDateFieldCommand = new Command<T, ComponentSize>() {\r
- public void execute(T c, ComponentSize size, Object data) {\r
- InlineDateField tf = new InlineDateField();\r
- c.addComponent(tf);\r
- size.apply(tf);\r
- }\r
- };\r
- private Command<T, ComponentSize> addPopupDateFieldCommand = new Command<T, ComponentSize>() {\r
- public void execute(T c, ComponentSize size, Object data) {\r
- PopupDateField tf = new PopupDateField();\r
- c.addComponent(tf);\r
- size.apply(tf);\r
- }\r
- };\r
- \r
- private Command<T, ComponentSize> addVerticalSplitPanelCommand = new Command<T, ComponentSize>() {\r
- public void execute(T c, ComponentSize size, Object data) {\r
- VerticalSplitPanel vsp = new VerticalSplitPanel();\r
- c.addComponent(vsp);\r
- size.apply(vsp);\r
- }\r
- };\r
- \r
- private Command<T, ComponentSize> addHorizontalSplitPanelCommand = new Command<T, ComponentSize>() {\r
- public void execute(T c, ComponentSize size, Object data) {\r
- HorizontalSplitPanel vsp = new HorizontalSplitPanel();\r
- c.addComponent(vsp);\r
- size.apply(vsp);\r
- }\r
- };\r
- \r
- private Command<T, ComponentSize> addTabSheetCommand = new Command<T, ComponentSize>() {\r
- public void execute(T c, ComponentSize size, Object data) {\r
- TabSheet ts = createTabSheet();\r
- c.addComponent(ts);\r
- size.apply(ts);\r
- }\r
- };\r
- \r
- private Command<T, ComponentSize> addTableCommand = new Command<T, ComponentSize>() {\r
- \r
- public void execute(T c, ComponentSize size, Object data) {\r
- Table t = createTable();\r
- c.addComponent(t);\r
- size.apply(t);\r
- }\r
- };\r
- private Command<T, Object> removeAllComponentsCommand = new Command<T, Object>() {\r
- public void execute(T c, Object value, Object data) {\r
- c.removeAllComponents();\r
- }\r
- };\r
- private Command<T, Integer> removeComponentByIndexCommand = new Command<T, Integer>() {\r
- \r
- public void execute(T c, Integer value, Object data) {\r
- Component child = getComponentAtIndex(c, value);\r
- c.removeComponent(child);\r
- \r
- }\r
- };\r
- private Command<T, Boolean> componentAttachListenerCommand = new Command<T, Boolean>() {\r
- \r
- public void execute(T c, Boolean value, Object data) {\r
- if (value) {\r
- c.addListener((ComponentAttachListener) AbstractComponentContainerTest.this);\r
- } else {\r
- c.removeListener((ComponentAttachListener) AbstractComponentContainerTest.this);\r
- }\r
- }\r
- };\r
- \r
- private Command<T, Boolean> componentDetachListenerCommand = new Command<T, Boolean>() {\r
- \r
- public void execute(T c, Boolean value, Object data) {\r
- if (value) {\r
- c.addListener((ComponentDetachListener) AbstractComponentContainerTest.this);\r
- } else {\r
- c.removeListener((ComponentDetachListener) AbstractComponentContainerTest.this);\r
- }\r
- }\r
- };\r
- \r
- private Command<T, Integer> setComponentHeight = new Command<T, Integer>() {\r
- \r
- public void execute(T c, Integer value, Object data) {\r
- Component child = getComponentAtIndex(c, value);\r
- child.setHeight((String) data);\r
- \r
- }\r
- };\r
- \r
- private Command<T, Integer> setComponentWidth = new Command<T, Integer>() {\r
- \r
- public void execute(T c, Integer value, Object data) {\r
- Component child = getComponentAtIndex(c, value);\r
- child.setWidth((String) data);\r
- \r
- }\r
- };\r
- \r
- protected static class ComponentSize {\r
- private String width, height;\r
- \r
- public ComponentSize(String width, String height) {\r
- this.width = width;\r
- this.height = height;\r
- }\r
- \r
- public void apply(Component target) {\r
- target.setWidth(width);\r
- target.setHeight(height);\r
- }\r
- \r
- public String getWidth() {\r
- return width;\r
- }\r
- \r
- public String getHeight() {\r
- return height;\r
- }\r
- \r
- @Override\r
- public String toString() {\r
- String s = "";\r
- s += width == null ? "auto" : width;\r
- s += " x ";\r
- s += height == null ? "auto" : height;\r
- return s;\r
- }\r
- }\r
- \r
- @Override\r
- protected void createActions() {\r
- super.createActions();\r
- \r
- createAddComponentActions(CATEGORY_COMPONENT_CONTAINER_FEATURES);\r
- createRemoveComponentActions(CATEGORY_COMPONENT_CONTAINER_FEATURES);\r
- createChangeComponentSizeActions(CATEGORY_COMPONENT_CONTAINER_FEATURES);\r
- createComponentAttachListener(CATEGORY_LISTENERS);\r
- createComponentDetachListener(CATEGORY_LISTENERS);\r
- }\r
- \r
- protected Component getComponentAtIndex(T container, int value) {\r
- Iterator<Component> iter = container.getComponentIterator();\r
- for (int i = 0; i < value; i++) {\r
- iter.next();\r
- }\r
- \r
- return iter.next();\r
- }\r
- \r
- protected Table createTable() {\r
- Table t = new Table();\r
- t.addContainerProperty("property 1", String.class, "");\r
- t.addContainerProperty("property 2", String.class, "");\r
- t.addContainerProperty("property 3", String.class, "");\r
- for (int i = 1; i < 10; i++) {\r
- t.addItem(new Object[] { "row/col " + i + "/1",\r
- "row/col " + i + "/2", "row/col " + i + "/3" },\r
- String.valueOf(i));\r
- }\r
- return t;\r
- }\r
- \r
- protected TabSheet createTabSheet() {\r
- TabSheet ts = new TabSheet();\r
- Table t = createTable();\r
- t.setSizeFull();\r
- ts.addTab(t, "Size full Table", ICON_16_USER_PNG_UNCACHEABLE);\r
- ts.addTab(new Button("A button"), "Button", null);\r
- return ts;\r
- }\r
- \r
- private void createComponentAttachListener(String category) {\r
- createBooleanAction("Component attach listener", category, false,\r
- componentAttachListenerCommand);\r
- \r
- }\r
- \r
- private void createComponentDetachListener(String category) {\r
- createBooleanAction("Component detach listener", category, false,\r
- componentDetachListenerCommand);\r
- \r
- }\r
- \r
- private void createRemoveComponentActions(String category) {\r
- String subCategory = "Remove component";\r
- String byIndexCategory = "By index";\r
- \r
- createCategory(subCategory, category);\r
- createCategory(byIndexCategory, subCategory);\r
- createClickAction("Remove all components", subCategory,\r
- removeAllComponentsCommand, null);\r
- for (int i = 0; i < 20; i++) {\r
- createClickAction("Remove component " + i, byIndexCategory,\r
- removeComponentByIndexCommand, Integer.valueOf(i));\r
- }\r
- \r
- }\r
- \r
- private void createAddComponentActions(String category) {\r
- String subCategory = "Add component";\r
- createCategory(subCategory, category);\r
- \r
- LinkedHashMap<String, Command<T, ComponentSize>> addCommands = new LinkedHashMap<String, AbstractComponentTestCase.Command<T, ComponentSize>>();\r
- addCommands.put("Button", addButtonCommand);\r
- addCommands.put("NativeButton", addNativeButtonCommand);\r
- addCommands.put("TextField", addTextFieldCommand);\r
- addCommands.put("TextArea", addTextAreaCommand);\r
- addCommands.put("RichTextArea", addRichTextAreaCommand);\r
- addCommands.put("TabSheet", addTabSheetCommand);\r
- addCommands.put("Table", addTableCommand);\r
- addCommands.put("InlineDateField", addInlineDateFieldCommand);\r
- addCommands.put("PopupDateField", addPopupDateFieldCommand);\r
- addCommands.put("VerticalSplitPanel", addVerticalSplitPanelCommand);\r
- addCommands.put("HorizontalSplitPanel", addHorizontalSplitPanelCommand);\r
- \r
- HashSet<String> noVerticalSize = new HashSet<String>();\r
- noVerticalSize.add("TextField");\r
- noVerticalSize.add("Button");\r
- \r
- // addCommands.put("AbsoluteLayout", addAbsoluteLayoutCommand);\r
- // addCommands.put("HorizontalLayout", addHorizontalLayoutCommand);\r
- // addCommands.put("VerticalLayout", addVerticalLayoutCommand);\r
- \r
- ComponentSize[] sizes = new ComponentSize[] {\r
- new ComponentSize(null, null),\r
- new ComponentSize("200px", null),\r
- new ComponentSize("100%", null),\r
- new ComponentSize(null, "200px"),\r
- new ComponentSize(null, "100%"),\r
- new ComponentSize("300px", "300px"),\r
- new ComponentSize("100%", "100%"),\r
- \r
- };\r
- \r
- for (String componentCategory : addCommands.keySet()) {\r
- createCategory(componentCategory, subCategory);\r
- \r
- for (ComponentSize size : sizes) {\r
- if (size.getHeight() != null\r
- && noVerticalSize.contains(componentCategory)) {\r
- continue;\r
- }\r
- createClickAction(size.toString(), componentCategory,\r
- addCommands.get(componentCategory), size);\r
- }\r
- }\r
- \r
- }\r
- \r
- private void createChangeComponentSizeActions(String category) {\r
- String widthCategory = "Change component width";\r
- createCategory(widthCategory, category);\r
- String heightCategory = "Change component height";\r
- createCategory(heightCategory, category);\r
- \r
- String[] options = new String[] { "100px", "200px", "50%", "100%" };\r
- for (int i = 0; i < 20; i++) {\r
- String componentWidthCategory = "Component " + i + " width";\r
- String componentHeightCategory = "Component " + i + " height";\r
- createCategory(componentWidthCategory, widthCategory);\r
- createCategory(componentHeightCategory, heightCategory);\r
- \r
- createClickAction("auto", componentHeightCategory,\r
- setComponentHeight, Integer.valueOf(i), null);\r
- createClickAction("auto", componentWidthCategory,\r
- setComponentWidth, Integer.valueOf(i), null);\r
- for (String option : options) {\r
- createClickAction(option, componentHeightCategory,\r
- setComponentHeight, Integer.valueOf(i), option);\r
- createClickAction(option, componentWidthCategory,\r
- setComponentWidth, Integer.valueOf(i), option);\r
- }\r
- \r
- }\r
- \r
- }\r
- \r
- public void componentDetachedFromContainer(ComponentDetachEvent event) {\r
- log(event.getClass().getSimpleName() + ": "\r
- + event.getDetachedComponent().getClass().getSimpleName()\r
- + " detached from "\r
- + event.getContainer().getClass().getSimpleName());\r
- }\r
- \r
- public void componentAttachedToContainer(ComponentAttachEvent event) {\r
- log(event.getClass().getSimpleName() + ": "\r
- + event.getAttachedComponent().getClass().getSimpleName()\r
- + " attached to "\r
- + event.getContainer().getClass().getSimpleName());\r
- \r
- }\r
- \r
- }\r
+ package com.vaadin.tests.components;
+
++import java.util.HashSet;
+ import java.util.Iterator;
+ import java.util.LinkedHashMap;
+
+ import com.vaadin.ui.AbstractComponentContainer;
+ import com.vaadin.ui.Button;
+ import com.vaadin.ui.Component;
+ import com.vaadin.ui.ComponentContainer.ComponentAttachEvent;
+ import com.vaadin.ui.ComponentContainer.ComponentAttachListener;
+ import com.vaadin.ui.ComponentContainer.ComponentDetachEvent;
+ import com.vaadin.ui.ComponentContainer.ComponentDetachListener;
+ import com.vaadin.ui.HorizontalSplitPanel;
+ import com.vaadin.ui.InlineDateField;
+ import com.vaadin.ui.NativeButton;
+ import com.vaadin.ui.PopupDateField;
+ import com.vaadin.ui.RichTextArea;
+ import com.vaadin.ui.TabSheet;
+ import com.vaadin.ui.Table;
+ import com.vaadin.ui.TextArea;
+ import com.vaadin.ui.TextField;
+ import com.vaadin.ui.VerticalSplitPanel;
+
+ public abstract class AbstractComponentContainerTest<T extends AbstractComponentContainer>
+ extends AbstractComponentTest<T> implements ComponentAttachListener,
+ ComponentDetachListener {
+
+ private String CATEGORY_COMPONENT_CONTAINER_FEATURES = "Component container features";
+ private Command<T, ComponentSize> addButtonCommand = new Command<T, ComponentSize>() {
+
+ public void execute(T c, ComponentSize size, Object data) {
+ Button b = new Button("A button");
+ c.addComponent(b);
+ size.apply(b);
+ }
+ };
+
+ private Command<T, ComponentSize> addNativeButtonCommand = new Command<T, ComponentSize>() {
+
+ public void execute(T c, ComponentSize size, Object data) {
+ NativeButton b = new NativeButton("Native button");
+ c.addComponent(b);
+ size.apply(b);
+ }
+ };
+
+ private Command<T, ComponentSize> addTextAreaCommand = new Command<T, ComponentSize>() {
+ public void execute(T c, ComponentSize size, Object data) {
+ TextArea ta = new TextArea();
+ c.addComponent(ta);
+ size.apply(ta);
+ }
+ };
+
+ private Command<T, ComponentSize> addRichTextAreaCommand = new Command<T, ComponentSize>() {
+ public void execute(T c, ComponentSize size, Object data) {
+ RichTextArea ta = new RichTextArea();
+ c.addComponent(ta);
+ size.apply(ta);
+ }
+ };
+
+ private Command<T, ComponentSize> addTextFieldCommand = new Command<T, ComponentSize>() {
+ public void execute(T c, ComponentSize size, Object data) {
+ TextField tf = new TextField();
+ c.addComponent(tf);
+ size.apply(tf);
+ }
+ };
+
+ private Command<T, ComponentSize> addInlineDateFieldCommand = new Command<T, ComponentSize>() {
+ public void execute(T c, ComponentSize size, Object data) {
+ InlineDateField tf = new InlineDateField();
+ c.addComponent(tf);
+ size.apply(tf);
+ }
+ };
+ private Command<T, ComponentSize> addPopupDateFieldCommand = new Command<T, ComponentSize>() {
+ public void execute(T c, ComponentSize size, Object data) {
+ PopupDateField tf = new PopupDateField();
+ c.addComponent(tf);
+ size.apply(tf);
+ }
+ };
+
+ private Command<T, ComponentSize> addVerticalSplitPanelCommand = new Command<T, ComponentSize>() {
+ public void execute(T c, ComponentSize size, Object data) {
+ VerticalSplitPanel vsp = new VerticalSplitPanel();
+ c.addComponent(vsp);
+ size.apply(vsp);
+ }
+ };
+
+ private Command<T, ComponentSize> addHorizontalSplitPanelCommand = new Command<T, ComponentSize>() {
+ public void execute(T c, ComponentSize size, Object data) {
+ HorizontalSplitPanel vsp = new HorizontalSplitPanel();
+ c.addComponent(vsp);
+ size.apply(vsp);
+ }
+ };
+
+ private Command<T, ComponentSize> addTabSheetCommand = new Command<T, ComponentSize>() {
+ public void execute(T c, ComponentSize size, Object data) {
+ TabSheet ts = createTabSheet();
+ c.addComponent(ts);
+ size.apply(ts);
+ }
+ };
+
+ private Command<T, ComponentSize> addTableCommand = new Command<T, ComponentSize>() {
+
+ public void execute(T c, ComponentSize size, Object data) {
+ Table t = createTable();
+ c.addComponent(t);
+ size.apply(t);
+ }
+ };
+ private Command<T, Object> removeAllComponentsCommand = new Command<T, Object>() {
+ public void execute(T c, Object value, Object data) {
+ c.removeAllComponents();
+ }
+ };
+ private Command<T, Integer> removeComponentByIndexCommand = new Command<T, Integer>() {
+
+ public void execute(T c, Integer value, Object data) {
+ Component child = getComponentAtIndex(c, value);
+ c.removeComponent(child);
+
+ }
+ };
+ private Command<T, Boolean> componentAttachListenerCommand = new Command<T, Boolean>() {
+
+ public void execute(T c, Boolean value, Object data) {
+ if (value) {
+ c.addListener((ComponentAttachListener) AbstractComponentContainerTest.this);
+ } else {
+ c.removeListener((ComponentAttachListener) AbstractComponentContainerTest.this);
+ }
+ }
+ };
+
+ private Command<T, Boolean> componentDetachListenerCommand = new Command<T, Boolean>() {
+
+ public void execute(T c, Boolean value, Object data) {
+ if (value) {
+ c.addListener((ComponentDetachListener) AbstractComponentContainerTest.this);
+ } else {
+ c.removeListener((ComponentDetachListener) AbstractComponentContainerTest.this);
+ }
+ }
+ };
+
+ private Command<T, Integer> setComponentHeight = new Command<T, Integer>() {
+
+ public void execute(T c, Integer value, Object data) {
+ Component child = getComponentAtIndex(c, value);
+ child.setHeight((String) data);
+
+ }
+ };
+
+ private Command<T, Integer> setComponentWidth = new Command<T, Integer>() {
+
+ public void execute(T c, Integer value, Object data) {
+ Component child = getComponentAtIndex(c, value);
+ child.setWidth((String) data);
+
+ }
+ };
+
+ protected static class ComponentSize {
+ private String width, height;
+
+ public ComponentSize(String width, String height) {
+ this.width = width;
+ this.height = height;
+ }
+
+ public void apply(Component target) {
+ target.setWidth(width);
+ target.setHeight(height);
+ }
+
+ public String getWidth() {
+ return width;
+ }
+
+ public String getHeight() {
+ return height;
+ }
+
+ @Override
+ public String toString() {
+ String s = "";
+ s += width == null ? "auto" : width;
+ s += " x ";
+ s += height == null ? "auto" : height;
+ return s;
+ }
+ }
+
+ @Override
+ protected void createActions() {
+ super.createActions();
+
+ createAddComponentActions(CATEGORY_COMPONENT_CONTAINER_FEATURES);
+ createRemoveComponentActions(CATEGORY_COMPONENT_CONTAINER_FEATURES);
+ createChangeComponentSizeActions(CATEGORY_COMPONENT_CONTAINER_FEATURES);
+ createComponentAttachListener(CATEGORY_LISTENERS);
+ createComponentDetachListener(CATEGORY_LISTENERS);
+ }
+
+ protected Component getComponentAtIndex(T container, int value) {
+ Iterator<Component> iter = container.getComponentIterator();
+ for (int i = 0; i < value; i++) {
+ iter.next();
+ }
+
+ return iter.next();
+ }
+
+ protected Table createTable() {
+ Table t = new Table();
+ t.addContainerProperty("property 1", String.class, "");
+ t.addContainerProperty("property 2", String.class, "");
+ t.addContainerProperty("property 3", String.class, "");
+ for (int i = 1; i < 10; i++) {
+ t.addItem(new Object[] { "row/col " + i + "/1",
+ "row/col " + i + "/2", "row/col " + i + "/3" },
+ String.valueOf(i));
+ }
+ return t;
+ }
+
+ protected TabSheet createTabSheet() {
+ TabSheet ts = new TabSheet();
+ Table t = createTable();
+ t.setSizeFull();
+ ts.addTab(t, "Size full Table", ICON_16_USER_PNG_UNCACHEABLE);
+ ts.addTab(new Button("A button"), "Button", null);
+ return ts;
+ }
+
+ private void createComponentAttachListener(String category) {
+ createBooleanAction("Component attach listener", category, false,
+ componentAttachListenerCommand);
+
+ }
+
+ private void createComponentDetachListener(String category) {
+ createBooleanAction("Component detach listener", category, false,
+ componentDetachListenerCommand);
+
+ }
+
+ private void createRemoveComponentActions(String category) {
+ String subCategory = "Remove component";
+ String byIndexCategory = "By index";
+
+ createCategory(subCategory, category);
+ createCategory(byIndexCategory, subCategory);
+ createClickAction("Remove all components", subCategory,
+ removeAllComponentsCommand, null);
+ for (int i = 0; i < 20; i++) {
+ createClickAction("Remove component " + i, byIndexCategory,
+ removeComponentByIndexCommand, Integer.valueOf(i));
+ }
+
+ }
+
+ private void createAddComponentActions(String category) {
+ String subCategory = "Add component";
+ createCategory(subCategory, category);
+
+ LinkedHashMap<String, Command<T, ComponentSize>> addCommands = new LinkedHashMap<String, AbstractComponentTestCase.Command<T, ComponentSize>>();
+ addCommands.put("Button", addButtonCommand);
+ addCommands.put("NativeButton", addNativeButtonCommand);
+ addCommands.put("TextField", addTextFieldCommand);
+ addCommands.put("TextArea", addTextAreaCommand);
+ addCommands.put("RichTextArea", addRichTextAreaCommand);
+ addCommands.put("TabSheet", addTabSheetCommand);
+ addCommands.put("Table", addTableCommand);
+ addCommands.put("InlineDateField", addInlineDateFieldCommand);
+ addCommands.put("PopupDateField", addPopupDateFieldCommand);
+ addCommands.put("VerticalSplitPanel", addVerticalSplitPanelCommand);
+ addCommands.put("HorizontalSplitPanel", addHorizontalSplitPanelCommand);
++
++ HashSet<String> noVerticalSize = new HashSet<String>();
++ noVerticalSize.add("TextField");
++ noVerticalSize.add("Button");
++
+ // addCommands.put("AbsoluteLayout", addAbsoluteLayoutCommand);
+ // addCommands.put("HorizontalLayout", addHorizontalLayoutCommand);
+ // addCommands.put("VerticalLayout", addVerticalLayoutCommand);
+
+ ComponentSize[] sizes = new ComponentSize[] {
+ new ComponentSize(null, null),
+ new ComponentSize("200px", null),
+ new ComponentSize("100%", null),
+ new ComponentSize(null, "200px"),
+ new ComponentSize(null, "100%"),
+ new ComponentSize("300px", "300px"),
+ new ComponentSize("100%", "100%"),
+
+ };
+
+ for (String componentCategory : addCommands.keySet()) {
+ createCategory(componentCategory, subCategory);
+
+ for (ComponentSize size : sizes) {
++ if (size.getHeight() != null
++ && noVerticalSize.contains(componentCategory)) {
++ continue;
++ }
+ createClickAction(size.toString(), componentCategory,
+ addCommands.get(componentCategory), size);
+ }
+ }
+
+ }
+
+ private void createChangeComponentSizeActions(String category) {
+ String widthCategory = "Change component width";
+ createCategory(widthCategory, category);
+ String heightCategory = "Change component height";
+ createCategory(heightCategory, category);
+
+ String[] options = new String[] { "100px", "200px", "50%", "100%" };
+ for (int i = 0; i < 20; i++) {
+ String componentWidthCategory = "Component " + i + " width";
+ String componentHeightCategory = "Component " + i + " height";
+ createCategory(componentWidthCategory, widthCategory);
+ createCategory(componentHeightCategory, heightCategory);
+
+ createClickAction("auto", componentHeightCategory,
+ setComponentHeight, Integer.valueOf(i), null);
+ createClickAction("auto", componentWidthCategory,
+ setComponentWidth, Integer.valueOf(i), null);
+ for (String option : options) {
+ createClickAction(option, componentHeightCategory,
+ setComponentHeight, Integer.valueOf(i), option);
+ createClickAction(option, componentWidthCategory,
+ setComponentWidth, Integer.valueOf(i), option);
+ }
+
+ }
+
+ }
+
+ public void componentDetachedFromContainer(ComponentDetachEvent event) {
+ log(event.getClass().getSimpleName() + ": "
+ + event.getDetachedComponent().getClass().getSimpleName()
+ + " detached from "
+ + event.getContainer().getClass().getSimpleName());
+ }
+
+ public void componentAttachedToContainer(ComponentAttachEvent event) {
+ log(event.getClass().getSimpleName() + ": "
+ + event.getAttachedComponent().getClass().getSimpleName()
+ + " attached to "
+ + event.getContainer().getClass().getSimpleName());
+
+ }
+
+ }
- package com.vaadin.tests.components;\r
- \r
- import java.util.HashMap;\r
- import java.util.HashSet;\r
- import java.util.LinkedHashMap;\r
- import java.util.List;\r
- import java.util.Locale;\r
- import java.util.Map;\r
- import java.util.Set;\r
- \r
- import com.vaadin.event.FieldEvents.BlurEvent;\r
- import com.vaadin.event.FieldEvents.BlurListener;\r
- import com.vaadin.event.FieldEvents.BlurNotifier;\r
- import com.vaadin.event.FieldEvents.FocusEvent;\r
- import com.vaadin.event.FieldEvents.FocusListener;\r
- import com.vaadin.event.FieldEvents.FocusNotifier;\r
- import com.vaadin.terminal.Resource;\r
- import com.vaadin.terminal.ThemeResource;\r
- import com.vaadin.tests.util.Log;\r
- import com.vaadin.tests.util.LoremIpsum;\r
- import com.vaadin.ui.AbstractComponent;\r
- import com.vaadin.ui.MenuBar;\r
- import com.vaadin.ui.MenuBar.MenuItem;\r
- \r
- public abstract class AbstractComponentTest<T extends AbstractComponent>\r
- extends AbstractComponentTestCase<T> implements FocusListener,\r
- BlurListener {\r
- \r
- protected static final String TEXT_SHORT = "Short";\r
- protected static final String TEXT_MEDIUM = "This is a semi-long text that might wrap.";\r
- protected static final String TEXT_LONG = "This is a long text. "\r
- + LoremIpsum.get(500);\r
- protected static final String TEXT_VERY_LONG = "This is a very, very long text. "\r
- + LoremIpsum.get(5000);\r
- \r
- private static final Resource SELECTED_ICON = new ThemeResource(\r
- "../runo/icons/16/ok.png");\r
- \r
- private static final LinkedHashMap<String, String> sizeOptions = new LinkedHashMap<String, String>();\r
- static {\r
- sizeOptions.put("auto", null);\r
- sizeOptions.put("50%", "50%");\r
- sizeOptions.put("100%", "100%");\r
- for (int w = 200; w < 1000; w += 100) {\r
- sizeOptions.put(w + "px", w + "px");\r
- }\r
- }\r
- \r
- // Menu related\r
- \r
- private MenuItem mainMenu;\r
- \r
- private MenuBar menu;\r
- \r
- private MenuItem settingsMenu;\r
- \r
- private T component;\r
- \r
- // Used to determine if a menuItem should be selected and the other\r
- // unselected on click\r
- private Set<MenuItem> parentOfSelectableMenuItem = new HashSet<MenuItem>();\r
- \r
- /**\r
- * Maps the category name to a menu item\r
- */\r
- private Map<String, MenuItem> categoryToMenuItem = new HashMap<String, MenuItem>();\r
- private Map<MenuItem, String> menuItemToCategory = new HashMap<MenuItem, String>();\r
- \r
- // Logging\r
- private Log log;\r
- \r
- protected static final String CATEGORY_STATE = "State";\r
- protected static final String CATEGORY_SIZE = "Size";\r
- protected static final String CATEGORY_SELECTION = "Selection";\r
- protected static final String CATEGORY_LISTENERS = "Listeners";\r
- protected static final String CATEGORY_FEATURES = "Features";\r
- protected static final String CATEGORY_ACTIONS = "Actions";\r
- protected static final String CATEGORY_DECORATIONS = "Decorations";\r
- \r
- @Override\r
- protected final void setup() {\r
- setTheme("tests-components");\r
- \r
- // Create menu here so it appears before the components\r
- addComponent(createMainMenu());\r
- \r
- getLayout().setSizeFull();\r
- createLog();\r
- super.setup();\r
- \r
- // Create menu actions and trigger default actions\r
- createActions();\r
- \r
- // Clear initialization log messages\r
- log.clear();\r
- }\r
- \r
- private MenuBar createMainMenu() {\r
- menu = new MenuBar();\r
- menu.setDebugId("menu");\r
- mainMenu = menu.addItem("Component", null);\r
- settingsMenu = menu.addItem("Settings", null);\r
- populateSettingsMenu(settingsMenu);\r
- \r
- return menu;\r
- }\r
- \r
- /**\r
- * Override to add items to the "settings" menu.\r
- * \r
- * NOTE, Call super class first to preserve current order. If you override\r
- * this in a class and another class overrides it you might break tests\r
- * because the wrong items will be selected.\r
- * \r
- * @param settingsMenu\r
- */\r
- protected void populateSettingsMenu(MenuItem settingsMenu) {\r
- \r
- MenuItem showEventLog = settingsMenu.addItem("Show event log",\r
- new MenuBar.Command() {\r
- \r
- public void menuSelected(MenuItem selectedItem) {\r
- boolean selected = !isSelected(selectedItem);\r
- setLogVisible(selected);\r
- setSelected(selectedItem, selected);\r
- }\r
- \r
- });\r
- setSelected(showEventLog, true);\r
- \r
- settingsMenu.addItem("Clear log", new MenuBar.Command() {\r
- \r
- public void menuSelected(MenuItem selectedItem) {\r
- log.clear();\r
- }\r
- });\r
- MenuItem layoutSize = settingsMenu.addItem("Parent layout size", null);\r
- MenuItem layoutWidth = layoutSize.addItem("Width", null);\r
- MenuItem layoutHeight = layoutSize.addItem("Height", null);\r
- for (final String name : sizeOptions.keySet()) {\r
- layoutWidth.addItem(name, new MenuBar.Command() {\r
- public void menuSelected(MenuItem selectedItem) {\r
- getTestComponents().get(0).getParent()\r
- .setWidth(sizeOptions.get(name));\r
- log("Parent layout width set to " + name);\r
- }\r
- });\r
- layoutHeight.addItem(name, new MenuBar.Command() {\r
- public void menuSelected(MenuItem selectedItem) {\r
- getTestComponents().get(0).getParent()\r
- .setHeight(sizeOptions.get(name));\r
- log("Parent layout height set to " + name);\r
- }\r
- });\r
- }\r
- \r
- }\r
- \r
- protected void setLogVisible(boolean visible) {\r
- log.setVisible(visible);\r
- }\r
- \r
- private void createLog() {\r
- log = new Log(5).setNumberLogRows(true);\r
- getLayout().addComponent(log, 1);\r
- }\r
- \r
- /**\r
- * By default initializes just one instance of {@link #getTestClass()} using\r
- * {@link #constructComponent()}.\r
- */\r
- @Override\r
- protected void initializeComponents() {\r
- component = constructComponent();\r
- component.setDebugId("testComponent");\r
- addTestComponent(component);\r
- }\r
- \r
- public T getComponent() {\r
- return component;\r
- }\r
- \r
- @Override\r
- protected void addTestComponent(T c) {\r
- super.addTestComponent(c);\r
- getLayout().setExpandRatio(c, 1);\r
- \r
- };\r
- \r
- /**\r
- * Construct the component that is to be tested. This method uses a no-arg\r
- * constructor by default. Override to customize.\r
- * \r
- * @return Instance of the component that is to be tested.\r
- * @throws IllegalAccessException\r
- * @throws InstantiationException\r
- */\r
- protected T constructComponent() {\r
- try {\r
- return getTestClass().newInstance();\r
- } catch (Exception e) {\r
- throw new RuntimeException("Failed to instantiate "\r
- + getTestClass(), e);\r
- }\r
- }\r
- \r
- /**\r
- * Create actions for the component. Remember to call super.createActions()\r
- * when overriding.\r
- */\r
- protected void createActions() {\r
- createBooleanAction("Immediate", CATEGORY_STATE, true, immediateCommand);\r
- createBooleanAction("Enabled", CATEGORY_STATE, true, enabledCommand);\r
- createBooleanAction("Readonly", CATEGORY_STATE, false, readonlyCommand);\r
- createBooleanAction("Visible", CATEGORY_STATE, true, visibleCommand);\r
- createBooleanAction("Error indicator", CATEGORY_STATE, false,\r
- errorIndicatorCommand);\r
- createLocaleSelect(CATEGORY_STATE);\r
- createErrorMessageSelect(CATEGORY_DECORATIONS);\r
- \r
- createDescriptionSelect(CATEGORY_DECORATIONS);\r
- createCaptionSelect(CATEGORY_DECORATIONS);\r
- createIconSelect(CATEGORY_DECORATIONS);\r
- \r
- createWidthAndHeightActions(CATEGORY_SIZE);\r
- \r
- createStyleNameSelect(CATEGORY_DECORATIONS);\r
- \r
- }\r
- \r
- protected Command<T, Boolean> focusListenerCommand = new Command<T, Boolean>() {\r
- \r
- public void execute(T c, Boolean value, Object data) {\r
- if (value) {\r
- ((FocusNotifier) c).addListener(AbstractComponentTest.this);\r
- } else {\r
- ((FocusNotifier) c).removeListener(AbstractComponentTest.this);\r
- }\r
- }\r
- };\r
- protected Command<T, Boolean> blurListenerCommand = new Command<T, Boolean>() {\r
- \r
- public void execute(T c, Boolean value, Object data) {\r
- if (value) {\r
- ((BlurNotifier) c).addListener(AbstractComponentTest.this);\r
- } else {\r
- ((BlurNotifier) c).removeListener(AbstractComponentTest.this);\r
- }\r
- }\r
- };\r
- \r
- protected void createFocusListener(String category) {\r
- createBooleanAction("Focus listener", category, false,\r
- focusListenerCommand);\r
- \r
- }\r
- \r
- protected void createBlurListener(String category) {\r
- createBooleanAction("Blur listener", category, false,\r
- blurListenerCommand);\r
- \r
- }\r
- \r
- private void createStyleNameSelect(String category) {\r
- LinkedHashMap<String, String> options = new LinkedHashMap<String, String>();\r
- options.put("-", null);\r
- options.put("Light blue background (background-lightblue)",\r
- "background-lightblue");\r
- options.put("1px red border (border-red-1px)", "border-red-1px");\r
- options.put("2px blue border (border-blue-2px)", "border-blue-2px");\r
- createComponentStyleNames(options);\r
- createSelectAction("Style name", category, options, "-",\r
- styleNameCommand);\r
- \r
- }\r
- \r
- protected void createComponentStyleNames(\r
- LinkedHashMap<String, String> options) {\r
- \r
- }\r
- \r
- private void createErrorMessageSelect(String category) {\r
- LinkedHashMap<String, String> options = new LinkedHashMap<String, String>();\r
- options.put("-", null);\r
- options.put(TEXT_SHORT, TEXT_SHORT);\r
- options.put("Medium", TEXT_MEDIUM);\r
- options.put("Long", TEXT_LONG);\r
- options.put("Very long", TEXT_VERY_LONG);\r
- createSelectAction("Error message", category, options, "-",\r
- errorMessageCommand);\r
- \r
- }\r
- \r
- private void createDescriptionSelect(String category) {\r
- LinkedHashMap<String, String> options = new LinkedHashMap<String, String>();\r
- options.put("-", null);\r
- options.put(TEXT_SHORT, TEXT_SHORT);\r
- options.put("Medium", TEXT_MEDIUM);\r
- options.put("Long", TEXT_LONG);\r
- options.put("Very long", TEXT_VERY_LONG);\r
- createSelectAction("Description / tooltip", category, options, "-",\r
- descriptionCommand);\r
- \r
- }\r
- \r
- private void createCaptionSelect(String category) {\r
- createSelectAction("Caption", category, createCaptionOptions(),\r
- "Short", captionCommand);\r
- \r
- }\r
- \r
- protected LinkedHashMap<String, String> createCaptionOptions() {\r
- LinkedHashMap<String, String> options = new LinkedHashMap<String, String>();\r
- options.put("-", null);\r
- options.put("Short", TEXT_SHORT);\r
- options.put("Medium", TEXT_MEDIUM);\r
- options.put("Long", TEXT_LONG);\r
- options.put("Very long", TEXT_VERY_LONG);\r
- return options;\r
- }\r
- \r
- private void createWidthAndHeightActions(String category) {\r
- String widthCategory = "Width";\r
- String heightCategory = "Height";\r
- \r
- createCategory(widthCategory, category);\r
- createCategory(heightCategory, category);\r
- \r
- for (String name : sizeOptions.keySet()) {\r
- createClickAction(name, widthCategory, widthCommand,\r
- sizeOptions.get(name));\r
- createClickAction(name, heightCategory, heightCommand,\r
- sizeOptions.get(name));\r
- }\r
- \r
- // Default to undefined size\r
- for (T c : getTestComponents()) {\r
- c.setWidth(null);\r
- c.setHeight(null);\r
- }\r
- }\r
- \r
- private void createIconSelect(String category) {\r
- LinkedHashMap<String, Resource> options = new LinkedHashMap<String, Resource>();\r
- options.put("-", null);\r
- options.put("16x16", ICON_16_USER_PNG_CACHEABLE);\r
- options.put("32x32", ICON_32_ATTENTION_PNG_CACHEABLE);\r
- options.put("64x64", ICON_64_EMAIL_REPLY_PNG_CACHEABLE);\r
- \r
- createSelectAction("Icon", category, options, "-", iconCommand, null);\r
- }\r
- \r
- private void createLocaleSelect(String category) {\r
- LinkedHashMap<String, Locale> options = new LinkedHashMap<String, Locale>();\r
- options.put("-", null);\r
- options.put("fi_FI", new Locale("fi", "FI"));\r
- options.put("en_US", Locale.US);\r
- options.put("zh_CN", Locale.SIMPLIFIED_CHINESE);\r
- options.put("fr_FR", Locale.FRANCE);\r
- \r
- createSelectAction("Locale", category, options, "en_US", localeCommand,\r
- null);\r
- }\r
- \r
- protected void createBooleanAction(String caption, String category,\r
- boolean initialState, final Command<T, Boolean> command) {\r
- createBooleanAction(caption, category, initialState, command, null);\r
- }\r
- \r
- protected <DATATYPE> void createBooleanAction(String caption,\r
- String category, boolean initialState,\r
- final Command<T, Boolean> command, Object data) {\r
- MenuItem categoryItem = getCategoryMenuItem(category);\r
- MenuItem item = categoryItem.addItem(caption,\r
- menuBooleanCommand(command, data));\r
- setSelected(item, initialState);\r
- doCommand(caption, command, initialState, data);\r
- }\r
- \r
- protected <DATATYPE> void createClickAction(String caption,\r
- String category, final Command<T, DATATYPE> command, DATATYPE value) {\r
- createClickAction(caption, category, command, value, null);\r
- }\r
- \r
- protected <DATATYPE> void createClickAction(String caption,\r
- String category, final Command<T, DATATYPE> command,\r
- DATATYPE value, Object data) {\r
- MenuItem categoryItem = getCategoryMenuItem(category);\r
- categoryItem.addItem(caption, menuClickCommand(command, value, data));\r
- }\r
- \r
- private MenuItem getCategoryMenuItem(String category) {\r
- if (category == null) {\r
- return getCategoryMenuItem("Misc");\r
- }\r
- \r
- MenuItem item = categoryToMenuItem.get(category);\r
- if (item != null) {\r
- return item;\r
- }\r
- \r
- return createCategory(category, null);\r
- }\r
- \r
- /**\r
- * Creates category named "category" with id "categoryId" in parent category\r
- * "parentCategory". Each categoryId must be globally unique.\r
- * \r
- * @param category\r
- * @param categoryId\r
- * @param parentCategory\r
- * @return\r
- */\r
- protected MenuItem createCategory(String category, String parentCategory) {\r
- if (hasCategory(category)) {\r
- return categoryToMenuItem.get(category);\r
- }\r
- MenuItem item;\r
- if (parentCategory == null) {\r
- item = mainMenu.addItem(category, null);\r
- } else {\r
- item = getCategoryMenuItem(parentCategory).addItem(category, null);\r
- }\r
- categoryToMenuItem.put(category, item);\r
- menuItemToCategory.put(item, category);\r
- return item;\r
- }\r
- \r
- protected boolean hasCategory(String categoryId) {\r
- return categoryToMenuItem.containsKey(categoryId);\r
- }\r
- \r
- protected void removeCategory(String categoryId) {\r
- if (!hasCategory(categoryId)) {\r
- throw new IllegalArgumentException("Category '" + categoryId\r
- + "' does not exist");\r
- }\r
- \r
- MenuItem item = getCategoryMenuItem(categoryId);\r
- Object[] children = item.getChildren().toArray();\r
- for (Object child : children) {\r
- if (menuItemToCategory.containsKey(child)) {\r
- removeCategory(menuItemToCategory.get(child));\r
- }\r
- }\r
- // Detach from parent\r
- item.getParent().removeChild(item);\r
- // Clean mappings\r
- categoryToMenuItem.remove(categoryId);\r
- menuItemToCategory.remove(item);\r
- \r
- }\r
- \r
- private MenuBar.Command menuBooleanCommand(\r
- final com.vaadin.tests.components.ComponentTestCase.Command<T, Boolean> booleanCommand,\r
- final Object data) {\r
- \r
- return new MenuBar.Command() {\r
- public void menuSelected(MenuItem selectedItem) {\r
- boolean selected = !isSelected(selectedItem);\r
- doCommand(getText(selectedItem), booleanCommand, selected, data);\r
- setSelected(selectedItem, selected);\r
- }\r
- \r
- };\r
- }\r
- \r
- private <DATATYPE> MenuBar.Command menuClickCommand(\r
- final com.vaadin.tests.components.ComponentTestCase.Command<T, DATATYPE> command,\r
- final DATATYPE value, final Object data) {\r
- \r
- return new MenuBar.Command() {\r
- public void menuSelected(MenuItem selectedItem) {\r
- doCommand(getText(selectedItem), command, value, data);\r
- }\r
- \r
- };\r
- }\r
- \r
- protected void setSelected(MenuItem item, boolean selected) {\r
- if (selected) {\r
- item.setIcon(SELECTED_ICON);\r
- } else {\r
- item.setIcon(null);\r
- }\r
- }\r
- \r
- protected boolean isSelected(MenuItem item) {\r
- return (item.getIcon() != null);\r
- }\r
- \r
- private <VALUETYPE> MenuBar.Command singleSelectMenuCommand(\r
- final com.vaadin.tests.components.ComponentTestCase.Command<T, VALUETYPE> cmd,\r
- final VALUETYPE object, final Object data) {\r
- return new MenuBar.Command() {\r
- public void menuSelected(MenuItem selectedItem) {\r
- doCommand(getText(selectedItem), cmd, object, data);\r
- \r
- if (parentOfSelectableMenuItem.contains(selectedItem\r
- .getParent())) {\r
- unselectChildren(selectedItem.getParent());\r
- setSelected(selectedItem, true);\r
- }\r
- }\r
- \r
- };\r
- \r
- }\r
- \r
- /**\r
- * Unselect all child menu items\r
- * \r
- * @param parent\r
- */\r
- protected void unselectChildren(MenuItem parent) {\r
- List<MenuItem> children = parent.getChildren();\r
- if (children == null) {\r
- return;\r
- }\r
- \r
- for (MenuItem child : children) {\r
- setSelected(child, false);\r
- }\r
- }\r
- \r
- protected String getText(MenuItem item) {\r
- String path = "";\r
- MenuItem parent = item.getParent();\r
- while (!isCategory(parent)) {\r
- path = parent.getText() + "/" + path;\r
- parent = parent.getParent();\r
- }\r
- \r
- return path + "/" + item.getText();\r
- }\r
- \r
- private boolean isCategory(MenuItem item) {\r
- return item.getParent() == mainMenu;\r
- }\r
- \r
- protected <TYPE> void createSelectAction(\r
- String caption,\r
- String category,\r
- LinkedHashMap<String, TYPE> options,\r
- String initialValue,\r
- com.vaadin.tests.components.ComponentTestCase.Command<T, TYPE> command) {\r
- createSelectAction(caption, category, options, initialValue, command,\r
- null);\r
- \r
- }\r
- \r
- protected <TYPE> void createMultiClickAction(\r
- String caption,\r
- String category,\r
- LinkedHashMap<String, TYPE> options,\r
- com.vaadin.tests.components.ComponentTestCase.Command<T, TYPE> command,\r
- Object data) {\r
- \r
- MenuItem categoryItem = getCategoryMenuItem(category);\r
- MenuItem mainItem = categoryItem.addItem(caption, null);\r
- \r
- for (String option : options.keySet()) {\r
- MenuBar.Command cmd = menuClickCommand(command,\r
- options.get(option), data);\r
- mainItem.addItem(option, cmd);\r
- }\r
- }\r
- \r
- protected <TYPE> void createMultiToggleAction(\r
- String caption,\r
- String category,\r
- LinkedHashMap<String, TYPE> options,\r
- com.vaadin.tests.components.ComponentTestCase.Command<T, Boolean> command,\r
- boolean defaultValue) {\r
- \r
- LinkedHashMap<String, Boolean> defaultValues = new LinkedHashMap<String, Boolean>();\r
- \r
- for (String option : options.keySet()) {\r
- defaultValues.put(option, defaultValue);\r
- }\r
- \r
- createMultiToggleAction(caption, category, options, command,\r
- defaultValues);\r
- }\r
- \r
- protected <TYPE> void createMultiToggleAction(\r
- String caption,\r
- String category,\r
- LinkedHashMap<String, TYPE> options,\r
- com.vaadin.tests.components.ComponentTestCase.Command<T, Boolean> command,\r
- LinkedHashMap<String, Boolean> defaultValues) {\r
- \r
- createCategory(caption, category);\r
- \r
- for (String option : options.keySet()) {\r
- createBooleanAction(option, caption, defaultValues.get(option),\r
- command, options.get(option));\r
- \r
- }\r
- }\r
- \r
- protected <TYPE> void createSelectAction(\r
- String caption,\r
- String category,\r
- LinkedHashMap<String, TYPE> options,\r
- String initialValue,\r
- com.vaadin.tests.components.ComponentTestCase.Command<T, TYPE> command,\r
- Object data) {\r
- \r
- MenuItem parentItem = getCategoryMenuItem(category);\r
- MenuItem mainItem = parentItem.addItem(caption, null);\r
- \r
- parentOfSelectableMenuItem.add(mainItem);\r
- for (String option : options.keySet()) {\r
- MenuBar.Command cmd = singleSelectMenuCommand(command,\r
- options.get(option), data);\r
- MenuItem item = mainItem.addItem(option, cmd);\r
- if (option.equals(initialValue)) {\r
- cmd.menuSelected(item);\r
- }\r
- }\r
- }\r
- \r
- protected LinkedHashMap<String, Integer> createIntegerOptions(int max) {\r
- LinkedHashMap<String, Integer> options = new LinkedHashMap<String, Integer>();\r
- for (int i = 0; i <= 9 && i <= max; i++) {\r
- options.put(String.valueOf(i), i);\r
- }\r
- for (int i = 10; i <= max; i *= 10) {\r
- options.put(String.valueOf(i), i);\r
- if (2 * i <= max) {\r
- options.put(String.valueOf(2 * i), 2 * i);\r
- }\r
- if (5 * i <= max) {\r
- options.put(String.valueOf(5 * i), 5 * i);\r
- }\r
- }\r
- \r
- return options;\r
- }\r
- \r
- protected LinkedHashMap<String, Double> createDoubleOptions(double max) {\r
- LinkedHashMap<String, Double> options = new LinkedHashMap<String, Double>();\r
- for (double d = 0; d <= max && d < 10; d += 0.5) {\r
- options.put(String.valueOf(d), d);\r
- }\r
- for (double d = 10; d <= max; d *= 10) {\r
- options.put(String.valueOf(d), d);\r
- if (2.5 * d <= max) {\r
- options.put(String.valueOf(2 * d), 2 * d);\r
- }\r
- if (5 * d <= max) {\r
- options.put(String.valueOf(5 * d), 5 * d);\r
- }\r
- }\r
- \r
- return options;\r
- }\r
- \r
- protected LinkedHashMap<String, Resource> createIconOptions(\r
- boolean cacheable) {\r
- LinkedHashMap<String, Resource> options = new LinkedHashMap<String, Resource>();\r
- options.put("-", null);\r
- if (cacheable) {\r
- options.put("16x16", ICON_16_USER_PNG_CACHEABLE);\r
- options.put("32x32", ICON_32_ATTENTION_PNG_CACHEABLE);\r
- options.put("64x64", ICON_64_EMAIL_REPLY_PNG_CACHEABLE);\r
- } else {\r
- options.put("16x16", ICON_16_USER_PNG_UNCACHEABLE);\r
- options.put("32x32", ICON_32_ATTENTION_PNG_UNCACHEABLE);\r
- options.put("64x64", ICON_64_EMAIL_REPLY_PNG_UNCACHEABLE);\r
- \r
- }\r
- return options;\r
- }\r
- \r
- protected void log(String msg) {\r
- log.log(msg);\r
- }\r
- \r
- protected boolean hasLog() {\r
- return log != null;\r
- }\r
- \r
- @Override\r
- protected <VALUET> void doCommand(String commandName,\r
- AbstractComponentTestCase.Command<T, VALUET> command, VALUET value,\r
- Object data) {\r
- if (hasLog()) {\r
- log("Command: " + commandName + "(" + value + ")");\r
- }\r
- super.doCommand(commandName, command, value, data);\r
- }\r
- \r
- @Override\r
- public void terminalError(com.vaadin.terminal.Terminal.ErrorEvent event) {\r
- String logMsg = "Exception occured, "\r
- + event.getThrowable().getClass().getName();\r
- \r
- String exceptionMsg = event.getThrowable().getMessage();\r
- if (exceptionMsg != null && exceptionMsg.length() > 0) {\r
- logMsg += exceptionMsg;\r
- }\r
- log.log(logMsg);\r
- final Throwable t = event.getThrowable();\r
- if (t != null) {\r
- t.printStackTrace();\r
- }\r
- \r
- }\r
- \r
- public void focus(FocusEvent event) {\r
- log(event.getClass().getSimpleName());\r
- }\r
- \r
- public void blur(BlurEvent event) {\r
- log(event.getClass().getSimpleName());\r
- }\r
- \r
- }\r
+ package com.vaadin.tests.components;
+
+ import java.util.HashMap;
+ import java.util.HashSet;
+ import java.util.LinkedHashMap;
+ import java.util.List;
+ import java.util.Locale;
+ import java.util.Map;
+ import java.util.Set;
+
++import com.vaadin.event.FieldEvents.BlurEvent;
++import com.vaadin.event.FieldEvents.BlurListener;
++import com.vaadin.event.FieldEvents.BlurNotifier;
++import com.vaadin.event.FieldEvents.FocusEvent;
++import com.vaadin.event.FieldEvents.FocusListener;
++import com.vaadin.event.FieldEvents.FocusNotifier;
+ import com.vaadin.terminal.Resource;
+ import com.vaadin.terminal.ThemeResource;
+ import com.vaadin.tests.util.Log;
+ import com.vaadin.tests.util.LoremIpsum;
+ import com.vaadin.ui.AbstractComponent;
+ import com.vaadin.ui.MenuBar;
+ import com.vaadin.ui.MenuBar.MenuItem;
+
+ public abstract class AbstractComponentTest<T extends AbstractComponent>
- extends AbstractComponentTestCase<T> {
++ extends AbstractComponentTestCase<T> implements FocusListener,
++ BlurListener {
+
+ protected static final String TEXT_SHORT = "Short";
+ protected static final String TEXT_MEDIUM = "This is a semi-long text that might wrap.";
+ protected static final String TEXT_LONG = "This is a long text. "
+ + LoremIpsum.get(500);
+ protected static final String TEXT_VERY_LONG = "This is a very, very long text. "
+ + LoremIpsum.get(5000);
+
+ private static final Resource SELECTED_ICON = new ThemeResource(
+ "../runo/icons/16/ok.png");
+
+ private static final LinkedHashMap<String, String> sizeOptions = new LinkedHashMap<String, String>();
+ static {
+ sizeOptions.put("auto", null);
+ sizeOptions.put("50%", "50%");
+ sizeOptions.put("100%", "100%");
+ for (int w = 200; w < 1000; w += 100) {
+ sizeOptions.put(w + "px", w + "px");
+ }
+ }
+
+ // Menu related
+
+ private MenuItem mainMenu;
+
+ private MenuBar menu;
+
+ private MenuItem settingsMenu;
+
+ private T component;
+
+ // Used to determine if a menuItem should be selected and the other
+ // unselected on click
+ private Set<MenuItem> parentOfSelectableMenuItem = new HashSet<MenuItem>();
+
+ /**
+ * Maps the category name to a menu item
+ */
+ private Map<String, MenuItem> categoryToMenuItem = new HashMap<String, MenuItem>();
+ private Map<MenuItem, String> menuItemToCategory = new HashMap<MenuItem, String>();
+
+ // Logging
+ private Log log;
+
+ protected static final String CATEGORY_STATE = "State";
+ protected static final String CATEGORY_SIZE = "Size";
+ protected static final String CATEGORY_SELECTION = "Selection";
+ protected static final String CATEGORY_LISTENERS = "Listeners";
+ protected static final String CATEGORY_FEATURES = "Features";
+ protected static final String CATEGORY_ACTIONS = "Actions";
+ protected static final String CATEGORY_DECORATIONS = "Decorations";
+
+ @Override
+ protected final void setup() {
+ setTheme("tests-components");
+
+ // Create menu here so it appears before the components
+ addComponent(createMainMenu());
+
+ getLayout().setSizeFull();
+ createLog();
+ super.setup();
+
+ // Create menu actions and trigger default actions
+ createActions();
+
+ // Clear initialization log messages
+ log.clear();
+ }
+
+ private MenuBar createMainMenu() {
+ menu = new MenuBar();
+ menu.setDebugId("menu");
+ mainMenu = menu.addItem("Component", null);
+ settingsMenu = menu.addItem("Settings", null);
+ populateSettingsMenu(settingsMenu);
+
+ return menu;
+ }
+
+ /**
+ * Override to add items to the "settings" menu.
+ *
+ * NOTE, Call super class first to preserve current order. If you override
+ * this in a class and another class overrides it you might break tests
+ * because the wrong items will be selected.
+ *
+ * @param settingsMenu
+ */
+ protected void populateSettingsMenu(MenuItem settingsMenu) {
+
+ MenuItem showEventLog = settingsMenu.addItem("Show event log",
+ new MenuBar.Command() {
+
+ public void menuSelected(MenuItem selectedItem) {
+ boolean selected = !isSelected(selectedItem);
+ setLogVisible(selected);
+ setSelected(selectedItem, selected);
+ }
+
+ });
+ setSelected(showEventLog, true);
+
+ settingsMenu.addItem("Clear log", new MenuBar.Command() {
+
+ public void menuSelected(MenuItem selectedItem) {
+ log.clear();
+ }
+ });
+ MenuItem layoutSize = settingsMenu.addItem("Parent layout size", null);
+ MenuItem layoutWidth = layoutSize.addItem("Width", null);
+ MenuItem layoutHeight = layoutSize.addItem("Height", null);
+ for (final String name : sizeOptions.keySet()) {
+ layoutWidth.addItem(name, new MenuBar.Command() {
+ public void menuSelected(MenuItem selectedItem) {
+ getTestComponents().get(0).getParent()
+ .setWidth(sizeOptions.get(name));
+ log("Parent layout width set to " + name);
+ }
+ });
+ layoutHeight.addItem(name, new MenuBar.Command() {
+ public void menuSelected(MenuItem selectedItem) {
+ getTestComponents().get(0).getParent()
+ .setHeight(sizeOptions.get(name));
+ log("Parent layout height set to " + name);
+ }
+ });
+ }
+
+ }
+
+ protected void setLogVisible(boolean visible) {
+ log.setVisible(visible);
+ }
+
+ private void createLog() {
+ log = new Log(5).setNumberLogRows(true);
+ getLayout().addComponent(log, 1);
+ }
+
+ /**
+ * By default initializes just one instance of {@link #getTestClass()} using
+ * {@link #constructComponent()}.
+ */
+ @Override
+ protected void initializeComponents() {
+ component = constructComponent();
+ component.setDebugId("testComponent");
+ addTestComponent(component);
+ }
+
+ public T getComponent() {
+ return component;
+ }
+
+ @Override
+ protected void addTestComponent(T c) {
+ super.addTestComponent(c);
+ getLayout().setExpandRatio(c, 1);
+
+ };
+
+ /**
+ * Construct the component that is to be tested. This method uses a no-arg
+ * constructor by default. Override to customize.
+ *
+ * @return Instance of the component that is to be tested.
+ * @throws IllegalAccessException
+ * @throws InstantiationException
+ */
+ protected T constructComponent() {
+ try {
+ return getTestClass().newInstance();
+ } catch (Exception e) {
+ throw new RuntimeException("Failed to instantiate "
+ + getTestClass(), e);
+ }
+ }
+
+ /**
+ * Create actions for the component. Remember to call super.createActions()
+ * when overriding.
+ */
+ protected void createActions() {
+ createBooleanAction("Immediate", CATEGORY_STATE, true, immediateCommand);
+ createBooleanAction("Enabled", CATEGORY_STATE, true, enabledCommand);
+ createBooleanAction("Readonly", CATEGORY_STATE, false, readonlyCommand);
+ createBooleanAction("Visible", CATEGORY_STATE, true, visibleCommand);
+ createBooleanAction("Error indicator", CATEGORY_STATE, false,
+ errorIndicatorCommand);
+ createLocaleSelect(CATEGORY_STATE);
+ createErrorMessageSelect(CATEGORY_DECORATIONS);
+
+ createDescriptionSelect(CATEGORY_DECORATIONS);
+ createCaptionSelect(CATEGORY_DECORATIONS);
+ createIconSelect(CATEGORY_DECORATIONS);
+
+ createWidthAndHeightActions(CATEGORY_SIZE);
+
+ createStyleNameSelect(CATEGORY_DECORATIONS);
+
+ }
+
++ protected Command<T, Boolean> focusListenerCommand = new Command<T, Boolean>() {
++
++ public void execute(T c, Boolean value, Object data) {
++ if (value) {
++ ((FocusNotifier) c).addListener(AbstractComponentTest.this);
++ } else {
++ ((FocusNotifier) c).removeListener(AbstractComponentTest.this);
++ }
++ }
++ };
++ protected Command<T, Boolean> blurListenerCommand = new Command<T, Boolean>() {
++
++ public void execute(T c, Boolean value, Object data) {
++ if (value) {
++ ((BlurNotifier) c).addListener(AbstractComponentTest.this);
++ } else {
++ ((BlurNotifier) c).removeListener(AbstractComponentTest.this);
++ }
++ }
++ };
++
++ protected void createFocusListener(String category) {
++ createBooleanAction("Focus listener", category, false,
++ focusListenerCommand);
++
++ }
++
++ protected void createBlurListener(String category) {
++ createBooleanAction("Blur listener", category, false,
++ blurListenerCommand);
++
++ }
++
+ private void createStyleNameSelect(String category) {
+ LinkedHashMap<String, String> options = new LinkedHashMap<String, String>();
+ options.put("-", null);
+ options.put("Light blue background (background-lightblue)",
+ "background-lightblue");
+ options.put("1px red border (border-red-1px)", "border-red-1px");
+ options.put("2px blue border (border-blue-2px)", "border-blue-2px");
+ createComponentStyleNames(options);
+ createSelectAction("Style name", category, options, "-",
+ styleNameCommand);
+
+ }
+
+ protected void createComponentStyleNames(
+ LinkedHashMap<String, String> options) {
+
+ }
+
+ private void createErrorMessageSelect(String category) {
+ LinkedHashMap<String, String> options = new LinkedHashMap<String, String>();
+ options.put("-", null);
+ options.put(TEXT_SHORT, TEXT_SHORT);
+ options.put("Medium", TEXT_MEDIUM);
+ options.put("Long", TEXT_LONG);
+ options.put("Very long", TEXT_VERY_LONG);
+ createSelectAction("Error message", category, options, "-",
+ errorMessageCommand);
+
+ }
+
+ private void createDescriptionSelect(String category) {
+ LinkedHashMap<String, String> options = new LinkedHashMap<String, String>();
+ options.put("-", null);
+ options.put(TEXT_SHORT, TEXT_SHORT);
+ options.put("Medium", TEXT_MEDIUM);
+ options.put("Long", TEXT_LONG);
+ options.put("Very long", TEXT_VERY_LONG);
+ createSelectAction("Description / tooltip", category, options, "-",
+ descriptionCommand);
+
+ }
+
+ private void createCaptionSelect(String category) {
+ createSelectAction("Caption", category, createCaptionOptions(),
+ "Short", captionCommand);
+
+ }
+
+ protected LinkedHashMap<String, String> createCaptionOptions() {
+ LinkedHashMap<String, String> options = new LinkedHashMap<String, String>();
+ options.put("-", null);
+ options.put("Short", TEXT_SHORT);
+ options.put("Medium", TEXT_MEDIUM);
+ options.put("Long", TEXT_LONG);
+ options.put("Very long", TEXT_VERY_LONG);
+ return options;
+ }
+
+ private void createWidthAndHeightActions(String category) {
+ String widthCategory = "Width";
+ String heightCategory = "Height";
+
+ createCategory(widthCategory, category);
+ createCategory(heightCategory, category);
+
+ for (String name : sizeOptions.keySet()) {
+ createClickAction(name, widthCategory, widthCommand,
+ sizeOptions.get(name));
+ createClickAction(name, heightCategory, heightCommand,
+ sizeOptions.get(name));
+ }
+
+ // Default to undefined size
+ for (T c : getTestComponents()) {
+ c.setWidth(null);
+ c.setHeight(null);
+ }
+ }
+
+ private void createIconSelect(String category) {
+ LinkedHashMap<String, Resource> options = new LinkedHashMap<String, Resource>();
+ options.put("-", null);
+ options.put("16x16", ICON_16_USER_PNG_CACHEABLE);
+ options.put("32x32", ICON_32_ATTENTION_PNG_CACHEABLE);
+ options.put("64x64", ICON_64_EMAIL_REPLY_PNG_CACHEABLE);
+
+ createSelectAction("Icon", category, options, "-", iconCommand, null);
+ }
+
+ private void createLocaleSelect(String category) {
+ LinkedHashMap<String, Locale> options = new LinkedHashMap<String, Locale>();
+ options.put("-", null);
+ options.put("fi_FI", new Locale("fi", "FI"));
+ options.put("en_US", Locale.US);
+ options.put("zh_CN", Locale.SIMPLIFIED_CHINESE);
+ options.put("fr_FR", Locale.FRANCE);
+
+ createSelectAction("Locale", category, options, "en_US", localeCommand,
+ null);
+ }
+
+ protected void createBooleanAction(String caption, String category,
+ boolean initialState, final Command<T, Boolean> command) {
+ createBooleanAction(caption, category, initialState, command, null);
+ }
+
+ protected <DATATYPE> void createBooleanAction(String caption,
+ String category, boolean initialState,
+ final Command<T, Boolean> command, Object data) {
+ MenuItem categoryItem = getCategoryMenuItem(category);
+ MenuItem item = categoryItem.addItem(caption,
+ menuBooleanCommand(command, data));
+ setSelected(item, initialState);
+ doCommand(caption, command, initialState, data);
+ }
+
+ protected <DATATYPE> void createClickAction(String caption,
+ String category, final Command<T, DATATYPE> command, DATATYPE value) {
+ createClickAction(caption, category, command, value, null);
+ }
+
+ protected <DATATYPE> void createClickAction(String caption,
+ String category, final Command<T, DATATYPE> command,
+ DATATYPE value, Object data) {
+ MenuItem categoryItem = getCategoryMenuItem(category);
+ categoryItem.addItem(caption, menuClickCommand(command, value, data));
+ }
+
+ private MenuItem getCategoryMenuItem(String category) {
+ if (category == null) {
+ return getCategoryMenuItem("Misc");
+ }
+
+ MenuItem item = categoryToMenuItem.get(category);
+ if (item != null) {
+ return item;
+ }
+
+ return createCategory(category, null);
+ }
+
+ /**
+ * Creates category named "category" with id "categoryId" in parent category
+ * "parentCategory". Each categoryId must be globally unique.
+ *
+ * @param category
+ * @param categoryId
+ * @param parentCategory
+ * @return
+ */
+ protected MenuItem createCategory(String category, String parentCategory) {
+ if (hasCategory(category)) {
+ return categoryToMenuItem.get(category);
+ }
+ MenuItem item;
+ if (parentCategory == null) {
+ item = mainMenu.addItem(category, null);
+ } else {
+ item = getCategoryMenuItem(parentCategory).addItem(category, null);
+ }
+ categoryToMenuItem.put(category, item);
+ menuItemToCategory.put(item, category);
+ return item;
+ }
+
+ protected boolean hasCategory(String categoryId) {
+ return categoryToMenuItem.containsKey(categoryId);
+ }
+
+ protected void removeCategory(String categoryId) {
+ if (!hasCategory(categoryId)) {
+ throw new IllegalArgumentException("Category '" + categoryId
+ + "' does not exist");
+ }
+
+ MenuItem item = getCategoryMenuItem(categoryId);
+ Object[] children = item.getChildren().toArray();
+ for (Object child : children) {
+ if (menuItemToCategory.containsKey(child)) {
+ removeCategory(menuItemToCategory.get(child));
+ }
+ }
+ // Detach from parent
+ item.getParent().removeChild(item);
+ // Clean mappings
+ categoryToMenuItem.remove(categoryId);
+ menuItemToCategory.remove(item);
+
+ }
+
+ private MenuBar.Command menuBooleanCommand(
+ final com.vaadin.tests.components.ComponentTestCase.Command<T, Boolean> booleanCommand,
+ final Object data) {
+
+ return new MenuBar.Command() {
+ public void menuSelected(MenuItem selectedItem) {
+ boolean selected = !isSelected(selectedItem);
+ doCommand(getText(selectedItem), booleanCommand, selected, data);
+ setSelected(selectedItem, selected);
+ }
+
+ };
+ }
+
+ private <DATATYPE> MenuBar.Command menuClickCommand(
+ final com.vaadin.tests.components.ComponentTestCase.Command<T, DATATYPE> command,
+ final DATATYPE value, final Object data) {
+
+ return new MenuBar.Command() {
+ public void menuSelected(MenuItem selectedItem) {
+ doCommand(getText(selectedItem), command, value, data);
+ }
+
+ };
+ }
+
+ protected void setSelected(MenuItem item, boolean selected) {
+ if (selected) {
+ item.setIcon(SELECTED_ICON);
+ } else {
+ item.setIcon(null);
+ }
+ }
+
+ protected boolean isSelected(MenuItem item) {
+ return (item.getIcon() != null);
+ }
+
+ private <VALUETYPE> MenuBar.Command singleSelectMenuCommand(
+ final com.vaadin.tests.components.ComponentTestCase.Command<T, VALUETYPE> cmd,
+ final VALUETYPE object, final Object data) {
+ return new MenuBar.Command() {
+ public void menuSelected(MenuItem selectedItem) {
+ doCommand(getText(selectedItem), cmd, object, data);
+
+ if (parentOfSelectableMenuItem.contains(selectedItem
+ .getParent())) {
+ unselectChildren(selectedItem.getParent());
+ setSelected(selectedItem, true);
+ }
+ }
+
+ };
+
+ }
+
+ /**
+ * Unselect all child menu items
+ *
+ * @param parent
+ */
+ protected void unselectChildren(MenuItem parent) {
+ List<MenuItem> children = parent.getChildren();
+ if (children == null) {
+ return;
+ }
+
+ for (MenuItem child : children) {
+ setSelected(child, false);
+ }
+ }
+
+ protected String getText(MenuItem item) {
+ String path = "";
+ MenuItem parent = item.getParent();
+ while (!isCategory(parent)) {
+ path = parent.getText() + "/" + path;
+ parent = parent.getParent();
+ }
+
+ return path + "/" + item.getText();
+ }
+
+ private boolean isCategory(MenuItem item) {
+ return item.getParent() == mainMenu;
+ }
+
+ protected <TYPE> void createSelectAction(
+ String caption,
+ String category,
+ LinkedHashMap<String, TYPE> options,
+ String initialValue,
+ com.vaadin.tests.components.ComponentTestCase.Command<T, TYPE> command) {
+ createSelectAction(caption, category, options, initialValue, command,
+ null);
+
+ }
+
+ protected <TYPE> void createMultiClickAction(
+ String caption,
+ String category,
+ LinkedHashMap<String, TYPE> options,
+ com.vaadin.tests.components.ComponentTestCase.Command<T, TYPE> command,
+ Object data) {
+
+ MenuItem categoryItem = getCategoryMenuItem(category);
+ MenuItem mainItem = categoryItem.addItem(caption, null);
+
+ for (String option : options.keySet()) {
+ MenuBar.Command cmd = menuClickCommand(command,
+ options.get(option), data);
+ mainItem.addItem(option, cmd);
+ }
+ }
+
+ protected <TYPE> void createMultiToggleAction(
+ String caption,
+ String category,
+ LinkedHashMap<String, TYPE> options,
+ com.vaadin.tests.components.ComponentTestCase.Command<T, Boolean> command,
+ boolean defaultValue) {
+
+ LinkedHashMap<String, Boolean> defaultValues = new LinkedHashMap<String, Boolean>();
+
+ for (String option : options.keySet()) {
+ defaultValues.put(option, defaultValue);
+ }
+
+ createMultiToggleAction(caption, category, options, command,
+ defaultValues);
+ }
+
+ protected <TYPE> void createMultiToggleAction(
+ String caption,
+ String category,
+ LinkedHashMap<String, TYPE> options,
+ com.vaadin.tests.components.ComponentTestCase.Command<T, Boolean> command,
+ LinkedHashMap<String, Boolean> defaultValues) {
+
+ createCategory(caption, category);
+
+ for (String option : options.keySet()) {
+ createBooleanAction(option, caption, defaultValues.get(option),
+ command, options.get(option));
+
+ }
+ }
+
+ protected <TYPE> void createSelectAction(
+ String caption,
+ String category,
+ LinkedHashMap<String, TYPE> options,
+ String initialValue,
+ com.vaadin.tests.components.ComponentTestCase.Command<T, TYPE> command,
+ Object data) {
+
+ MenuItem parentItem = getCategoryMenuItem(category);
+ MenuItem mainItem = parentItem.addItem(caption, null);
+
+ parentOfSelectableMenuItem.add(mainItem);
+ for (String option : options.keySet()) {
+ MenuBar.Command cmd = singleSelectMenuCommand(command,
+ options.get(option), data);
+ MenuItem item = mainItem.addItem(option, cmd);
+ if (option.equals(initialValue)) {
+ cmd.menuSelected(item);
+ }
+ }
+ }
+
+ protected LinkedHashMap<String, Integer> createIntegerOptions(int max) {
+ LinkedHashMap<String, Integer> options = new LinkedHashMap<String, Integer>();
+ for (int i = 0; i <= 9 && i <= max; i++) {
+ options.put(String.valueOf(i), i);
+ }
+ for (int i = 10; i <= max; i *= 10) {
+ options.put(String.valueOf(i), i);
+ if (2 * i <= max) {
+ options.put(String.valueOf(2 * i), 2 * i);
+ }
+ if (5 * i <= max) {
+ options.put(String.valueOf(5 * i), 5 * i);
+ }
+ }
+
+ return options;
+ }
+
+ protected LinkedHashMap<String, Double> createDoubleOptions(double max) {
+ LinkedHashMap<String, Double> options = new LinkedHashMap<String, Double>();
+ for (double d = 0; d <= max && d < 10; d += 0.5) {
+ options.put(String.valueOf(d), d);
+ }
+ for (double d = 10; d <= max; d *= 10) {
+ options.put(String.valueOf(d), d);
+ if (2.5 * d <= max) {
+ options.put(String.valueOf(2 * d), 2 * d);
+ }
+ if (5 * d <= max) {
+ options.put(String.valueOf(5 * d), 5 * d);
+ }
+ }
+
+ return options;
+ }
+
+ protected LinkedHashMap<String, Resource> createIconOptions(
+ boolean cacheable) {
+ LinkedHashMap<String, Resource> options = new LinkedHashMap<String, Resource>();
+ options.put("-", null);
+ if (cacheable) {
+ options.put("16x16", ICON_16_USER_PNG_CACHEABLE);
+ options.put("32x32", ICON_32_ATTENTION_PNG_CACHEABLE);
+ options.put("64x64", ICON_64_EMAIL_REPLY_PNG_CACHEABLE);
+ } else {
+ options.put("16x16", ICON_16_USER_PNG_UNCACHEABLE);
+ options.put("32x32", ICON_32_ATTENTION_PNG_UNCACHEABLE);
+ options.put("64x64", ICON_64_EMAIL_REPLY_PNG_UNCACHEABLE);
+
+ }
+ return options;
+ }
+
+ protected void log(String msg) {
+ log.log(msg);
+ }
+
+ protected boolean hasLog() {
+ return log != null;
+ }
+
+ @Override
+ protected <VALUET> void doCommand(String commandName,
+ AbstractComponentTestCase.Command<T, VALUET> command, VALUET value,
+ Object data) {
+ if (hasLog()) {
+ log("Command: " + commandName + "(" + value + ")");
+ }
+ super.doCommand(commandName, command, value, data);
+ }
+
+ @Override
+ public void terminalError(com.vaadin.terminal.Terminal.ErrorEvent event) {
+ String logMsg = "Exception occured, "
+ + event.getThrowable().getClass().getName();
+
+ String exceptionMsg = event.getThrowable().getMessage();
+ if (exceptionMsg != null && exceptionMsg.length() > 0) {
+ logMsg += exceptionMsg;
+ }
+ log.log(logMsg);
+ final Throwable t = event.getThrowable();
+ if (t != null) {
+ t.printStackTrace();
+ }
+
+ }
++
++ public void focus(FocusEvent event) {
++ log(event.getClass().getSimpleName());
++ }
++
++ public void blur(BlurEvent event) {
++ log(event.getClass().getSimpleName());
++ }
++
+ }
- package com.vaadin.tests.components;\r
- \r
- import com.vaadin.Application;\r
- import com.vaadin.service.ApplicationContext;\r
- import com.vaadin.terminal.gwt.server.AbstractWebApplicationContext;\r
- import com.vaadin.terminal.gwt.server.WebBrowser;\r
- \r
- public abstract class AbstractTestCase extends Application.LegacyApplication {\r
- \r
- protected abstract String getDescription();\r
- \r
- protected abstract Integer getTicketNumber();\r
- \r
- protected WebBrowser getBrowser() {\r
- ApplicationContext context = getContext();\r
- if (context instanceof AbstractWebApplicationContext) {\r
- WebBrowser webBrowser = ((AbstractWebApplicationContext) context)\r
- .getBrowser();\r
- return webBrowser;\r
- }\r
- \r
- return null;\r
- }\r
- }\r
+ package com.vaadin.tests.components;
+
+ import com.vaadin.Application;
+ import com.vaadin.service.ApplicationContext;
+ import com.vaadin.terminal.gwt.server.AbstractWebApplicationContext;
+ import com.vaadin.terminal.gwt.server.WebBrowser;
+
-public abstract class AbstractTestCase extends Application {
++public abstract class AbstractTestCase extends Application.LegacyApplication {
+
+ protected abstract String getDescription();
+
+ protected abstract Integer getTicketNumber();
+
+ protected WebBrowser getBrowser() {
+ ApplicationContext context = getContext();
+ if (context instanceof AbstractWebApplicationContext) {
+ WebBrowser webBrowser = ((AbstractWebApplicationContext) context)
+ .getBrowser();
+ return webBrowser;
+ }
+
+ return null;
+ }
+ }
- package com.vaadin.tests.components;\r
- \r
- import com.vaadin.ui.Component;\r
- import com.vaadin.ui.Label;\r
- import com.vaadin.ui.Label.ContentMode;\r
- import com.vaadin.ui.Root.LegacyWindow;\r
- import com.vaadin.ui.VerticalLayout;\r
- \r
- public abstract class TestBase extends AbstractTestCase {\r
- \r
- @Override\r
- public final void init() {\r
- window = new LegacyWindow(getClass().getName());\r
- setMainWindow(window);\r
- window.getContent().setSizeFull();\r
- \r
- Label label = new Label(getDescription(), ContentMode.XHTML);\r
- label.setWidth("100%");\r
- window.getContent().addComponent(label);\r
- \r
- layout = new VerticalLayout();\r
- window.getContent().addComponent(layout);\r
- ((VerticalLayout) window.getContent()).setExpandRatio(layout, 1);\r
- \r
- setup();\r
- }\r
- \r
- private LegacyWindow window;\r
- private VerticalLayout layout;\r
- \r
- public TestBase() {\r
- \r
- }\r
- \r
- protected VerticalLayout getLayout() {\r
- return layout;\r
- }\r
- \r
- protected abstract void setup();\r
- \r
- protected void addComponent(Component c) {\r
- getLayout().addComponent(c);\r
- }\r
- \r
- protected void removeComponent(Component c) {\r
- getLayout().removeComponent(c);\r
- }\r
- \r
- protected void replaceComponent(Component oldComponent,\r
- Component newComponent) {\r
- getLayout().replaceComponent(oldComponent, newComponent);\r
- }\r
- \r
- }\r
+ package com.vaadin.tests.components;
+
+ import com.vaadin.ui.Component;
+ import com.vaadin.ui.Label;
++import com.vaadin.ui.Label.ContentMode;
++import com.vaadin.ui.Root.LegacyWindow;
+ import com.vaadin.ui.VerticalLayout;
-import com.vaadin.ui.Window;
+
+ public abstract class TestBase extends AbstractTestCase {
+
+ @Override
+ public final void init() {
- window = new Window(getClass().getName());
++ window = new LegacyWindow(getClass().getName());
+ setMainWindow(window);
+ window.getContent().setSizeFull();
+
- Label label = new Label(getDescription(), Label.CONTENT_XHTML);
++ Label label = new Label(getDescription(), ContentMode.XHTML);
+ label.setWidth("100%");
+ window.getContent().addComponent(label);
+
+ layout = new VerticalLayout();
+ window.getContent().addComponent(layout);
+ ((VerticalLayout) window.getContent()).setExpandRatio(layout, 1);
+
+ setup();
+ }
+
- private Window window;
++ private LegacyWindow window;
+ private VerticalLayout layout;
+
+ public TestBase() {
+
+ }
+
+ protected VerticalLayout getLayout() {
+ return layout;
+ }
+
+ protected abstract void setup();
+
+ protected void addComponent(Component c) {
+ getLayout().addComponent(c);
+ }
+
+ protected void removeComponent(Component c) {
+ getLayout().removeComponent(c);
+ }
+
+ protected void replaceComponent(Component oldComponent,
+ Component newComponent) {
+ getLayout().replaceComponent(oldComponent, newComponent);
+ }
+
+ }
- package com.vaadin.tests.components.abstractcomponent;\r
- \r
- import com.vaadin.data.Property;\r
- import com.vaadin.data.Property.ValueChangeEvent;\r
- import com.vaadin.tests.components.AbstractTestCase;\r
- import com.vaadin.ui.Button;\r
- import com.vaadin.ui.CheckBox;\r
- import com.vaadin.ui.Panel;\r
- import com.vaadin.ui.Root.LegacyWindow;\r
- \r
- public class EnableState extends AbstractTestCase {\r
- @Override\r
- public void init() {\r
- LegacyWindow mainWindow = new LegacyWindow("Helloworld Application");\r
- \r
- final Panel panel = new Panel("Test");\r
- final Button button = new Button("ablebutton");\r
- panel.addComponent(button);\r
- \r
- CheckBox enable = new CheckBox("Toggle button enabled", true);\r
- enable.addListener(new Property.ValueChangeListener() {\r
- \r
- public void valueChange(ValueChangeEvent event) {\r
- boolean enabled = (Boolean) event.getProperty().getValue();\r
- button.setEnabled(enabled);\r
- // button.requestRepaint();\r
- }\r
- });\r
- enable.setImmediate(true);\r
- \r
- CheckBox caption = new CheckBox("Toggle button caption", true);\r
- caption.addListener(new Property.ValueChangeListener() {\r
- \r
- public void valueChange(ValueChangeEvent event) {\r
- button.setCaption(button.getCaption() + "+");\r
- }\r
- });\r
- caption.setImmediate(true);\r
- \r
- CheckBox visible = new CheckBox("Toggle panel visibility", true);\r
- visible.addListener(new Property.ValueChangeListener() {\r
- \r
- public void valueChange(ValueChangeEvent event) {\r
- boolean visible = (Boolean) event.getProperty().getValue();\r
- \r
- panel.setVisible(visible);\r
- }\r
- });\r
- visible.setImmediate(true);\r
- \r
- CheckBox panelEnable = new CheckBox("Toggle panel enabled", true);\r
- panelEnable.addListener(new Property.ValueChangeListener() {\r
- \r
- public void valueChange(ValueChangeEvent event) {\r
- boolean enabled = (Boolean) event.getProperty().getValue();\r
- panel.setEnabled(enabled);\r
- }\r
- });\r
- panelEnable.setImmediate(true);\r
- \r
- mainWindow.addComponent(enable);\r
- mainWindow.addComponent(caption);\r
- mainWindow.addComponent(visible);\r
- mainWindow.addComponent(panelEnable);\r
- mainWindow.addComponent(panel);\r
- \r
- setMainWindow(mainWindow);\r
- }\r
- \r
- @Override\r
- protected String getDescription() {\r
- return "This tests the enabled/disabled propagation and that enabled/disabled state is updated"\r
- + " properly even when the parent is invisible. Disabling the Button while the panel is"\r
- + " invisible should be reflected on the screen when the panel is set visible"\r
- + " again.";\r
- }\r
- \r
- @Override\r
- protected Integer getTicketNumber() {\r
- return 3609;\r
- }\r
- }\r
+ package com.vaadin.tests.components.abstractcomponent;
+
++import com.vaadin.data.Property;
++import com.vaadin.data.Property.ValueChangeEvent;
+ import com.vaadin.tests.components.AbstractTestCase;
+ import com.vaadin.ui.Button;
-import com.vaadin.ui.Button.ClickEvent;
+ import com.vaadin.ui.CheckBox;
+ import com.vaadin.ui.Panel;
-import com.vaadin.ui.Window;
++import com.vaadin.ui.Root.LegacyWindow;
+
+ public class EnableState extends AbstractTestCase {
+ @Override
+ public void init() {
- Window mainWindow = new Window("Helloworld Application");
++ LegacyWindow mainWindow = new LegacyWindow("Helloworld Application");
+
+ final Panel panel = new Panel("Test");
+ final Button button = new Button("ablebutton");
+ panel.addComponent(button);
+
+ CheckBox enable = new CheckBox("Toggle button enabled", true);
- enable.addListener(new Button.ClickListener() {
- public void buttonClick(ClickEvent event) {
- boolean enabled = (Boolean) event.getButton().getValue();
++ enable.addListener(new Property.ValueChangeListener() {
++
++ public void valueChange(ValueChangeEvent event) {
++ boolean enabled = (Boolean) event.getProperty().getValue();
+ button.setEnabled(enabled);
+ // button.requestRepaint();
+ }
+ });
+ enable.setImmediate(true);
+
+ CheckBox caption = new CheckBox("Toggle button caption", true);
- caption.addListener(new Button.ClickListener() {
- public void buttonClick(ClickEvent event) {
++ caption.addListener(new Property.ValueChangeListener() {
++
++ public void valueChange(ValueChangeEvent event) {
+ button.setCaption(button.getCaption() + "+");
+ }
+ });
+ caption.setImmediate(true);
+
+ CheckBox visible = new CheckBox("Toggle panel visibility", true);
- visible.addListener(new Button.ClickListener() {
- public void buttonClick(ClickEvent event) {
- boolean visible = (Boolean) event.getButton().getValue();
++ visible.addListener(new Property.ValueChangeListener() {
++
++ public void valueChange(ValueChangeEvent event) {
++ boolean visible = (Boolean) event.getProperty().getValue();
+
+ panel.setVisible(visible);
+ }
+ });
+ visible.setImmediate(true);
+
+ CheckBox panelEnable = new CheckBox("Toggle panel enabled", true);
- panelEnable.addListener(new Button.ClickListener() {
- public void buttonClick(ClickEvent event) {
- boolean enabled = (Boolean) event.getButton().getValue();
++ panelEnable.addListener(new Property.ValueChangeListener() {
++
++ public void valueChange(ValueChangeEvent event) {
++ boolean enabled = (Boolean) event.getProperty().getValue();
+ panel.setEnabled(enabled);
+ }
+ });
+ panelEnable.setImmediate(true);
+
+ mainWindow.addComponent(enable);
+ mainWindow.addComponent(caption);
+ mainWindow.addComponent(visible);
+ mainWindow.addComponent(panelEnable);
+ mainWindow.addComponent(panel);
+
+ setMainWindow(mainWindow);
+ }
+
+ @Override
+ protected String getDescription() {
+ return "This tests the enabled/disabled propagation and that enabled/disabled state is updated"
+ + " properly even when the parent is invisible. Disabling the Button while the panel is"
+ + " invisible should be reflected on the screen when the panel is set visible"
+ + " again.";
+ }
+
+ @Override
+ protected Integer getTicketNumber() {
+ return 3609;
+ }
+ }
--- /dev/null
- package com.vaadin.tests.components.abstractfield;\r
- \r
- import java.util.HashSet;\r
- import java.util.Locale;\r
- import java.util.Set;\r
- \r
- import com.vaadin.data.Container;\r
- import com.vaadin.data.Item;\r
- import com.vaadin.data.Property.ValueChangeEvent;\r
- import com.vaadin.data.Property.ValueChangeListener;\r
- import com.vaadin.tests.components.TestBase;\r
- import com.vaadin.tests.util.Log;\r
- import com.vaadin.ui.AbstractField;\r
- import com.vaadin.ui.ComboBox;\r
- import com.vaadin.ui.Component;\r
- \r
- public abstract class AbstractComponentDataBindingTest extends TestBase\r
- implements ValueChangeListener {\r
- private static final Object CAPTION = "CAPTION";\r
- private Log log = new Log(5);\r
- private ComboBox localeSelect;\r
- \r
- @Override\r
- protected void setup() {\r
- addComponent(log);\r
- localeSelect = createLocaleSelect();\r
- addComponent(localeSelect);\r
- \r
- // Causes fields to be created\r
- localeSelect.setValue(Locale.US);\r
- }\r
- \r
- private ComboBox createLocaleSelect() {\r
- ComboBox cb = new ComboBox("Locale");\r
- cb.addContainerProperty(CAPTION, String.class, "");\r
- cb.setItemCaptionPropertyId(CAPTION);\r
- cb.setNullSelectionAllowed(false);\r
- for (Locale l : Locale.getAvailableLocales()) {\r
- Item i = cb.addItem(l);\r
- i.getItemProperty(CAPTION).setValue(\r
- l.getDisplayName(Locale.ENGLISH));\r
- }\r
- ((Container.Sortable) cb.getContainerDataSource()).sort(\r
- new Object[] { CAPTION }, new boolean[] { true });\r
- cb.setImmediate(true);\r
- cb.addListener(new ValueChangeListener() {\r
- \r
- public void valueChange(ValueChangeEvent event) {\r
- updateLocale((Locale) localeSelect.getValue());\r
- }\r
- });\r
- return cb;\r
- }\r
- \r
- protected void updateLocale(Locale locale) {\r
- setLocale(locale);\r
- for (Component c : fields) {\r
- removeComponent(c);\r
- }\r
- fields.clear();\r
- createFields();\r
- }\r
- \r
- protected abstract void createFields();\r
- \r
- private Set<Component> fields = new HashSet<Component>();\r
- \r
- @Override\r
- protected void addComponent(Component c) {\r
- super.addComponent(c);\r
- if (c instanceof AbstractField) {\r
- configureField((AbstractField<?>) c);\r
- if (c != localeSelect) {\r
- fields.add(c);\r
- }\r
- }\r
- }\r
- \r
- protected void configureField(AbstractField<?> field) {\r
- field.setImmediate(true);\r
- field.addListener(this);\r
- }\r
- \r
- @Override\r
- protected String getDescription() {\r
- return "";\r
- }\r
- \r
- @Override\r
- protected Integer getTicketNumber() {\r
- return null;\r
- }\r
- \r
- public void valueChange(ValueChangeEvent event) {\r
- AbstractField field = (AbstractField) event.getProperty();\r
- // if (field == localeSelect) {\r
- // return;\r
- // }\r
- \r
- Object newValue = field.getValue();\r
- if (newValue != null) {\r
- newValue = newValue + " (" + newValue.getClass().getName() + ")";\r
- }\r
- \r
- String message = "Value of " + field.getCaption() + " changed to "\r
- + newValue + ".";\r
- if (field.getPropertyDataSource() != null) {\r
- Object dataSourceValue = field.getPropertyDataSource().getValue();\r
- message += "Data model value is " + dataSourceValue;\r
- message += " (" + field.getPropertyDataSource().getType().getName()\r
- + ")";\r
- }\r
- log.log(message);\r
- \r
- }\r
- \r
- }\r
++package com.vaadin.tests.components.abstractfield;
++
++import java.util.HashSet;
++import java.util.Locale;
++import java.util.Set;
++
++import com.vaadin.data.Container;
++import com.vaadin.data.Item;
++import com.vaadin.data.Property.ValueChangeEvent;
++import com.vaadin.data.Property.ValueChangeListener;
++import com.vaadin.tests.components.TestBase;
++import com.vaadin.tests.util.Log;
++import com.vaadin.ui.AbstractField;
++import com.vaadin.ui.ComboBox;
++import com.vaadin.ui.Component;
++
++public abstract class AbstractComponentDataBindingTest extends TestBase
++ implements ValueChangeListener {
++ private static final Object CAPTION = "CAPTION";
++ private Log log = new Log(5);
++ private ComboBox localeSelect;
++
++ @Override
++ protected void setup() {
++ addComponent(log);
++ localeSelect = createLocaleSelect();
++ addComponent(localeSelect);
++
++ // Causes fields to be created
++ localeSelect.setValue(Locale.US);
++ }
++
++ private ComboBox createLocaleSelect() {
++ ComboBox cb = new ComboBox("Locale");
++ cb.addContainerProperty(CAPTION, String.class, "");
++ cb.setItemCaptionPropertyId(CAPTION);
++ cb.setNullSelectionAllowed(false);
++ for (Locale l : Locale.getAvailableLocales()) {
++ Item i = cb.addItem(l);
++ i.getItemProperty(CAPTION).setValue(
++ l.getDisplayName(Locale.ENGLISH));
++ }
++ ((Container.Sortable) cb.getContainerDataSource()).sort(
++ new Object[] { CAPTION }, new boolean[] { true });
++ cb.setImmediate(true);
++ cb.addListener(new ValueChangeListener() {
++
++ public void valueChange(ValueChangeEvent event) {
++ updateLocale((Locale) localeSelect.getValue());
++ }
++ });
++ return cb;
++ }
++
++ protected void updateLocale(Locale locale) {
++ setLocale(locale);
++ for (Component c : fields) {
++ removeComponent(c);
++ }
++ fields.clear();
++ createFields();
++ }
++
++ protected abstract void createFields();
++
++ private Set<Component> fields = new HashSet<Component>();
++
++ @Override
++ protected void addComponent(Component c) {
++ super.addComponent(c);
++ if (c instanceof AbstractField) {
++ configureField((AbstractField<?>) c);
++ if (c != localeSelect) {
++ fields.add(c);
++ }
++ }
++ }
++
++ protected void configureField(AbstractField<?> field) {
++ field.setImmediate(true);
++ field.addListener(this);
++ }
++
++ @Override
++ protected String getDescription() {
++ return "";
++ }
++
++ @Override
++ protected Integer getTicketNumber() {
++ return null;
++ }
++
++ public void valueChange(ValueChangeEvent event) {
++ AbstractField field = (AbstractField) event.getProperty();
++ // if (field == localeSelect) {
++ // return;
++ // }
++
++ Object newValue = field.getValue();
++ if (newValue != null) {
++ newValue = newValue + " (" + newValue.getClass().getName() + ")";
++ }
++
++ String message = "Value of " + field.getCaption() + " changed to "
++ + newValue + ".";
++ if (field.getPropertyDataSource() != null) {
++ Object dataSourceValue = field.getPropertyDataSource().getValue();
++ message += "Data model value is " + dataSourceValue;
++ message += " (" + field.getPropertyDataSource().getType().getName()
++ + ")";
++ }
++ log.log(message);
++
++ }
++
++}
- package com.vaadin.tests.components.abstractfield;\r
- \r
- import java.text.SimpleDateFormat;\r
- import java.util.ArrayList;\r
- import java.util.Collection;\r
- import java.util.Collections;\r
- import java.util.Date;\r
- import java.util.LinkedHashMap;\r
- import java.util.List;\r
- import java.util.Locale;\r
- \r
- import com.vaadin.data.Property;\r
- import com.vaadin.data.Property.ReadOnlyStatusChangeEvent;\r
- import com.vaadin.data.Property.ReadOnlyStatusChangeListener;\r
- import com.vaadin.data.Property.ValueChangeListener;\r
- import com.vaadin.event.FieldEvents.BlurNotifier;\r
- import com.vaadin.event.FieldEvents.FocusNotifier;\r
- import com.vaadin.tests.components.AbstractComponentTest;\r
- import com.vaadin.ui.AbstractField;\r
- import com.vaadin.ui.MenuBar;\r
- import com.vaadin.ui.MenuBar.MenuItem;\r
- \r
- public abstract class AbstractFieldTest<T extends AbstractField<?>> extends\r
- AbstractComponentTest<T> implements ValueChangeListener,\r
- ReadOnlyStatusChangeListener {\r
- \r
- @Override\r
- protected void createActions() {\r
- super.createActions();\r
- createBooleanAction("Required", CATEGORY_STATE, false, requiredCommand);\r
- createRequiredErrorSelect(CATEGORY_DECORATIONS);\r
- if (FocusNotifier.class.isAssignableFrom(getTestClass())) {\r
- createFocusListener(CATEGORY_LISTENERS);\r
- }\r
- \r
- if (BlurNotifier.class.isAssignableFrom(getTestClass())) {\r
- createBlurListener(CATEGORY_LISTENERS);\r
- }\r
- \r
- createValueChangeListener(CATEGORY_LISTENERS);\r
- createReadOnlyStatusChangeListener(CATEGORY_LISTENERS);\r
- \r
- // * invalidcommitted\r
- // * commit()\r
- // * discard()\r
- // * writethrough\r
- // * readthrough\r
- // * addvalidator\r
- // * isvalid\r
- // * invalidallowed\r
- // * error indicator\r
- //\r
- // * tabindex\r
- // * validation visible\r
- // * ShortcutListener\r
- \r
- }\r
- \r
- @Override\r
- protected void populateSettingsMenu(MenuItem settingsMenu) {\r
- super.populateSettingsMenu(settingsMenu);\r
- \r
- if (AbstractField.class.isAssignableFrom(getTestClass())) {\r
- MenuItem abstractField = settingsMenu\r
- .addItem("AbstractField", null);\r
- abstractField.addItem("Show value", new MenuBar.Command() {\r
- \r
- public void menuSelected(MenuItem selectedItem) {\r
- for (T a : getTestComponents()) {\r
- log(a.getClass().getSimpleName() + " value: "\r
- + getValue(a));\r
- }\r
- }\r
- });\r
- }\r
- }\r
- \r
- private void createRequiredErrorSelect(String category) {\r
- LinkedHashMap<String, String> options = new LinkedHashMap<String, String>();\r
- options.put("-", null);\r
- options.put(TEXT_SHORT, TEXT_SHORT);\r
- options.put("Medium", TEXT_MEDIUM);\r
- options.put("Long", TEXT_LONG);\r
- options.put("Very long", TEXT_VERY_LONG);\r
- createSelectAction("Required error message", category, options, "-",\r
- requiredErrorMessageCommand);\r
- \r
- }\r
- \r
- private void createValueChangeListener(String category) {\r
- \r
- createBooleanAction("Value change listener", category, false,\r
- valueChangeListenerCommand);\r
- }\r
- \r
- private void createReadOnlyStatusChangeListener(String category) {\r
- \r
- createBooleanAction("Read only status change listener", category,\r
- false, readonlyStatusChangeListenerCommand);\r
- }\r
- \r
- protected Command<T, Boolean> valueChangeListenerCommand = new Command<T, Boolean>() {\r
- \r
- public void execute(T c, Boolean value, Object data) {\r
- if (value) {\r
- c.addListener((ValueChangeListener) AbstractFieldTest.this);\r
- } else {\r
- c.removeListener((ValueChangeListener) AbstractFieldTest.this);\r
- }\r
- }\r
- };\r
- protected Command<T, Boolean> readonlyStatusChangeListenerCommand = new Command<T, Boolean>() {\r
- \r
- public void execute(T c, Boolean value, Object data) {\r
- if (value) {\r
- c.addListener((ReadOnlyStatusChangeListener) AbstractFieldTest.this);\r
- } else {\r
- c.removeListener((ReadOnlyStatusChangeListener) AbstractFieldTest.this);\r
- }\r
- }\r
- };\r
- \r
- protected Command<T, Object> setValueCommand = new Command<T, Object>() {\r
- \r
- public void execute(T c, Object value, Object data) {\r
- c.setValue(value);\r
- }\r
- };\r
- \r
- public void valueChange(com.vaadin.data.Property.ValueChangeEvent event) {\r
- log(event.getClass().getSimpleName() + ", new value: "\r
- + getValue(event.getProperty()));\r
- };\r
- \r
- @SuppressWarnings({ "rawtypes", "unchecked" })\r
- private String getValue(Property property) {\r
- Object o = property.getValue();\r
- if (o instanceof Collection) {\r
- // Sort collections to avoid problems with values printed in\r
- // different order\r
- try {\r
- ArrayList<Comparable> c = new ArrayList<Comparable>(\r
- (Collection) o);\r
- Collections.sort(c);\r
- o = c;\r
- } catch (Exception e) {\r
- // continue with unsorted if sorting fails for some reason\r
- log("Exception while sorting value: " + e.getMessage());\r
- }\r
- }\r
- \r
- // Distinguish between null and 'null'\r
- String value = "null";\r
- if (o != null) {\r
- if (o instanceof Date) {\r
- Date d = (Date) o;\r
- // Dec 31, 2068 23:09:26.531\r
- String pattern = "MMM d, yyyy HH:mm:ss.SSS";\r
- SimpleDateFormat format = new SimpleDateFormat(pattern,\r
- new Locale("en", "US"));\r
- value = format.format(d);\r
- } else {\r
- value = "'" + o.toString() + "'";\r
- }\r
- }\r
- \r
- return value;\r
- \r
- }\r
- \r
- public void readOnlyStatusChange(ReadOnlyStatusChangeEvent event) {\r
- log(event.getClass().getSimpleName());\r
- }\r
- \r
- protected void createSetTextValueAction(String category) {\r
- String subCategory = "Set text value";\r
- createCategory(subCategory, category);\r
- List<String> values = new ArrayList<String>();\r
- values.add("Test");\r
- values.add("A little longer value");\r
- values.add("A very long value with very much text. All in all it is 74 characters long");\r
- \r
- createClickAction("(empty string)", subCategory, setValueCommand, "");\r
- createClickAction("(null)", subCategory, setValueCommand, null);\r
- for (String value : values) {\r
- createClickAction(value, subCategory, setValueCommand, value);\r
- }\r
- }\r
- \r
- }\r
+ package com.vaadin.tests.components.abstractfield;
+
+ import java.text.SimpleDateFormat;
+ import java.util.ArrayList;
+ import java.util.Collection;
+ import java.util.Collections;
+ import java.util.Date;
+ import java.util.LinkedHashMap;
+ import java.util.List;
+ import java.util.Locale;
+
+ import com.vaadin.data.Property;
+ import com.vaadin.data.Property.ReadOnlyStatusChangeEvent;
+ import com.vaadin.data.Property.ReadOnlyStatusChangeListener;
+ import com.vaadin.data.Property.ValueChangeListener;
-import com.vaadin.event.FieldEvents.BlurEvent;
-import com.vaadin.event.FieldEvents.BlurListener;
+ import com.vaadin.event.FieldEvents.BlurNotifier;
-import com.vaadin.event.FieldEvents.FocusEvent;
-import com.vaadin.event.FieldEvents.FocusListener;
+ import com.vaadin.event.FieldEvents.FocusNotifier;
+ import com.vaadin.tests.components.AbstractComponentTest;
+ import com.vaadin.ui.AbstractField;
+ import com.vaadin.ui.MenuBar;
+ import com.vaadin.ui.MenuBar.MenuItem;
+
-public abstract class AbstractFieldTest<T extends AbstractField> extends
++public abstract class AbstractFieldTest<T extends AbstractField<?>> extends
+ AbstractComponentTest<T> implements ValueChangeListener,
- ReadOnlyStatusChangeListener, FocusListener, BlurListener {
++ ReadOnlyStatusChangeListener {
+
+ @Override
+ protected void createActions() {
+ super.createActions();
+ createBooleanAction("Required", CATEGORY_STATE, false, requiredCommand);
+ createRequiredErrorSelect(CATEGORY_DECORATIONS);
++ if (FocusNotifier.class.isAssignableFrom(getTestClass())) {
++ createFocusListener(CATEGORY_LISTENERS);
++ }
++
++ if (BlurNotifier.class.isAssignableFrom(getTestClass())) {
++ createBlurListener(CATEGORY_LISTENERS);
++ }
+
+ createValueChangeListener(CATEGORY_LISTENERS);
+ createReadOnlyStatusChangeListener(CATEGORY_LISTENERS);
+
+ // * invalidcommitted
+ // * commit()
+ // * discard()
+ // * writethrough
+ // * readthrough
+ // * addvalidator
+ // * isvalid
+ // * invalidallowed
+ // * error indicator
+ //
+ // * tabindex
+ // * validation visible
+ // * ShortcutListener
+
+ }
+
+ @Override
+ protected void populateSettingsMenu(MenuItem settingsMenu) {
+ super.populateSettingsMenu(settingsMenu);
+
+ if (AbstractField.class.isAssignableFrom(getTestClass())) {
+ MenuItem abstractField = settingsMenu
+ .addItem("AbstractField", null);
+ abstractField.addItem("Show value", new MenuBar.Command() {
+
+ public void menuSelected(MenuItem selectedItem) {
+ for (T a : getTestComponents()) {
+ log(a.getClass().getSimpleName() + " value: "
+ + getValue(a));
+ }
+ }
+ });
+ }
+ }
+
+ private void createRequiredErrorSelect(String category) {
+ LinkedHashMap<String, String> options = new LinkedHashMap<String, String>();
+ options.put("-", null);
+ options.put(TEXT_SHORT, TEXT_SHORT);
+ options.put("Medium", TEXT_MEDIUM);
+ options.put("Long", TEXT_LONG);
+ options.put("Very long", TEXT_VERY_LONG);
+ createSelectAction("Required error message", category, options, "-",
+ requiredErrorMessageCommand);
+
- if (FocusNotifier.class.isAssignableFrom(getTestClass())) {
- createFocusListener(CATEGORY_LISTENERS);
- }
-
- if (BlurNotifier.class.isAssignableFrom(getTestClass())) {
- createBlurListener(CATEGORY_LISTENERS);
- }
-
+ }
+
+ private void createValueChangeListener(String category) {
+
+ createBooleanAction("Value change listener", category, false,
+ valueChangeListenerCommand);
+ }
+
+ private void createReadOnlyStatusChangeListener(String category) {
+
+ createBooleanAction("Read only status change listener", category,
+ false, readonlyStatusChangeListenerCommand);
+ }
+
- private void createFocusListener(String category) {
- createBooleanAction("Focus listener", category, false,
- focusListenerCommand);
-
- }
-
- private void createBlurListener(String category) {
- createBooleanAction("Blur listener", category, false,
- blurListenerCommand);
-
- }
-
+ protected Command<T, Boolean> valueChangeListenerCommand = new Command<T, Boolean>() {
+
+ public void execute(T c, Boolean value, Object data) {
+ if (value) {
+ c.addListener((ValueChangeListener) AbstractFieldTest.this);
+ } else {
+ c.removeListener((ValueChangeListener) AbstractFieldTest.this);
+ }
+ }
+ };
+ protected Command<T, Boolean> readonlyStatusChangeListenerCommand = new Command<T, Boolean>() {
+
+ public void execute(T c, Boolean value, Object data) {
+ if (value) {
+ c.addListener((ReadOnlyStatusChangeListener) AbstractFieldTest.this);
+ } else {
+ c.removeListener((ReadOnlyStatusChangeListener) AbstractFieldTest.this);
+ }
+ }
+ };
- protected Command<T, Boolean> focusListenerCommand = new Command<T, Boolean>() {
-
- public void execute(T c, Boolean value, Object data) {
- if (value) {
- ((FocusNotifier) c).addListener(AbstractFieldTest.this);
- } else {
- ((FocusNotifier) c).removeListener(AbstractFieldTest.this);
- }
- }
- };
- protected Command<T, Boolean> blurListenerCommand = new Command<T, Boolean>() {
+
- public void execute(T c, Boolean value, Object data) {
- if (value) {
- ((BlurNotifier) c).addListener(AbstractFieldTest.this);
- } else {
- ((BlurNotifier) c).removeListener(AbstractFieldTest.this);
- }
- }
- };
+ protected Command<T, Object> setValueCommand = new Command<T, Object>() {
+
+ public void execute(T c, Object value, Object data) {
+ c.setValue(value);
+ }
+ };
+
+ public void valueChange(com.vaadin.data.Property.ValueChangeEvent event) {
+ log(event.getClass().getSimpleName() + ", new value: "
+ + getValue(event.getProperty()));
+ };
+
+ @SuppressWarnings({ "rawtypes", "unchecked" })
+ private String getValue(Property property) {
+ Object o = property.getValue();
+ if (o instanceof Collection) {
+ // Sort collections to avoid problems with values printed in
+ // different order
+ try {
+ ArrayList<Comparable> c = new ArrayList<Comparable>(
+ (Collection) o);
+ Collections.sort(c);
+ o = c;
+ } catch (Exception e) {
+ // continue with unsorted if sorting fails for some reason
+ log("Exception while sorting value: " + e.getMessage());
+ }
+ }
+
+ // Distinguish between null and 'null'
+ String value = "null";
+ if (o != null) {
+ if (o instanceof Date) {
+ Date d = (Date) o;
+ // Dec 31, 2068 23:09:26.531
+ String pattern = "MMM d, yyyy HH:mm:ss.SSS";
+ SimpleDateFormat format = new SimpleDateFormat(pattern,
+ new Locale("en", "US"));
+ value = format.format(d);
+ } else {
+ value = "'" + o.toString() + "'";
+ }
+ }
+
+ return value;
+
+ }
+
+ public void readOnlyStatusChange(ReadOnlyStatusChangeEvent event) {
+ log(event.getClass().getSimpleName());
+ }
+
- public void focus(FocusEvent event) {
- log(event.getClass().getSimpleName());
- }
-
- public void blur(BlurEvent event) {
- log(event.getClass().getSimpleName());
- }
-
+ protected void createSetTextValueAction(String category) {
+ String subCategory = "Set text value";
+ createCategory(subCategory, category);
+ List<String> values = new ArrayList<String>();
+ values.add("Test");
+ values.add("A little longer value");
+ values.add("A very long value with very much text. All in all it is 74 characters long");
+
+ createClickAction("(empty string)", subCategory, setValueCommand, "");
+ createClickAction("(null)", subCategory, setValueCommand, null);
+ for (String value : values) {
+ createClickAction(value, subCategory, setValueCommand, value);
+ }
+ }
+
+ }
--- /dev/null
- package com.vaadin.tests.components.abstractfield;\r
- \r
- import com.vaadin.ui.DateField;\r
- \r
- public class DateFieldBackedByString extends AbstractComponentDataBindingTest {\r
- \r
- private String s = null;\r
- \r
- @Override\r
- protected void createFields() {\r
- DateField df = new DateField("Date field");\r
- addComponent(df);\r
- df.setPropertyDataSource(new com.vaadin.data.util.ObjectProperty<String>(\r
- s, String.class));\r
- \r
- }\r
- }\r
++package com.vaadin.tests.components.abstractfield;
++
++import com.vaadin.ui.DateField;
++
++public class DateFieldBackedByString extends AbstractComponentDataBindingTest {
++
++ private String s = null;
++
++ @Override
++ protected void createFields() {
++ DateField df = new DateField("Date field");
++ addComponent(df);
++ df.setPropertyDataSource(new com.vaadin.data.util.ObjectProperty<String>(
++ s, String.class));
++
++ }
++}
--- /dev/null
- package com.vaadin.tests.components.abstractfield;\r
- \r
- import java.util.Date;\r
- \r
- import com.vaadin.data.util.ObjectProperty;\r
- import com.vaadin.ui.Button;\r
- import com.vaadin.ui.Button.ClickEvent;\r
- import com.vaadin.ui.PopupDateField;\r
- \r
- public class DateFieldBasedOnLong extends AbstractComponentDataBindingTest {\r
- \r
- private Long l = null;\r
- private ObjectProperty<Long> property;\r
- \r
- @Override\r
- protected void createFields() {\r
- PopupDateField pdf = new PopupDateField("DateField");\r
- addComponent(pdf);\r
- property = new ObjectProperty<Long>(l, Long.class);\r
- pdf.setPropertyDataSource(property);\r
- \r
- property.setValue(new Date(2011 - 1900, 4, 6).getTime());\r
- \r
- addComponent(new Button("Set property value to 10000L",\r
- new Button.ClickListener() {\r
- \r
- public void buttonClick(ClickEvent event) {\r
- property.setValue(10000L);\r
- \r
- }\r
- }));\r
- }\r
- \r
- }\r
++package com.vaadin.tests.components.abstractfield;
++
++import java.util.Date;
++
++import com.vaadin.data.util.ObjectProperty;
++import com.vaadin.ui.Button;
++import com.vaadin.ui.Button.ClickEvent;
++import com.vaadin.ui.PopupDateField;
++
++public class DateFieldBasedOnLong extends AbstractComponentDataBindingTest {
++
++ private Long l = null;
++ private ObjectProperty<Long> property;
++
++ @Override
++ protected void createFields() {
++ PopupDateField pdf = new PopupDateField("DateField");
++ addComponent(pdf);
++ property = new ObjectProperty<Long>(l, Long.class);
++ pdf.setPropertyDataSource(property);
++
++ property.setValue(new Date(2011 - 1900, 4, 6).getTime());
++
++ addComponent(new Button("Set property value to 10000L",
++ new Button.ClickListener() {
++
++ public void buttonClick(ClickEvent event) {
++ property.setValue(10000L);
++
++ }
++ }));
++ }
++
++}
--- /dev/null
- package com.vaadin.tests.components.abstractfield;\r
- \r
- import com.vaadin.data.util.MethodProperty;\r
- import com.vaadin.tests.data.bean.Address;\r
- import com.vaadin.tests.data.bean.Country;\r
- import com.vaadin.tests.data.bean.Person;\r
- import com.vaadin.tests.data.bean.Sex;\r
- import com.vaadin.ui.TextField;\r
- \r
- public class DoubleInTextField extends AbstractComponentDataBindingTest {\r
- \r
- @Override\r
- protected void createFields() {\r
- Person person = new Person("John", "Doe", "john@doe.com", 78, Sex.MALE,\r
- new Address("Dovestreet 12", 12233, "Johnston",\r
- Country.SOUTH_AFRICA));\r
- \r
- TextField salary = new TextField("Vaadin 7 - TextField with Double");\r
- addComponent(salary);\r
- salary.setPropertyDataSource(new MethodProperty<Double>(person,\r
- "salaryDouble"));\r
- \r
- TextField salary6 = new TextField("Vaadin 6 - TextField with Double");\r
- addComponent(salary6);\r
- salary6.setPropertyDataSource(new MethodProperty<Double>(person,\r
- "salaryDouble"));\r
- salary6.setConverter(new Vaadin6ImplicitDoubleConverter());\r
- \r
- }\r
- \r
- }\r
++package com.vaadin.tests.components.abstractfield;
++
++import com.vaadin.data.util.MethodProperty;
++import com.vaadin.tests.data.bean.Address;
++import com.vaadin.tests.data.bean.Country;
++import com.vaadin.tests.data.bean.Person;
++import com.vaadin.tests.data.bean.Sex;
++import com.vaadin.ui.TextField;
++
++public class DoubleInTextField extends AbstractComponentDataBindingTest {
++
++ @Override
++ protected void createFields() {
++ Person person = new Person("John", "Doe", "john@doe.com", 78, Sex.MALE,
++ new Address("Dovestreet 12", 12233, "Johnston",
++ Country.SOUTH_AFRICA));
++
++ TextField salary = new TextField("Vaadin 7 - TextField with Double");
++ addComponent(salary);
++ salary.setPropertyDataSource(new MethodProperty<Double>(person,
++ "salaryDouble"));
++
++ TextField salary6 = new TextField("Vaadin 6 - TextField with Double");
++ addComponent(salary6);
++ salary6.setPropertyDataSource(new MethodProperty<Double>(person,
++ "salaryDouble"));
++ salary6.setConverter(new Vaadin6ImplicitDoubleConverter());
++
++ }
++
++}
--- /dev/null
- package com.vaadin.tests.components.abstractfield;\r
- \r
- import com.vaadin.data.Property.ValueChangeEvent;\r
- import com.vaadin.data.Property.ValueChangeListener;\r
- import com.vaadin.data.util.ObjectProperty;\r
- import com.vaadin.data.validator.DoubleValidator;\r
- import com.vaadin.data.validator.IntegerValidator;\r
- import com.vaadin.tests.components.TestBase;\r
- import com.vaadin.tests.util.Log;\r
- import com.vaadin.ui.TextField;\r
- \r
- public class IntegerDoubleFieldsWithDataSource extends TestBase {\r
- \r
- private Log log = new Log(5);\r
- \r
- @Override\r
- protected void setup() {\r
- addComponent(log);\r
- \r
- TextField tf = createIntegerTextField();\r
- tf.addValidator(new IntegerValidator("Must be an Integer"));\r
- addComponent(tf);\r
- \r
- tf = createIntegerTextField();\r
- tf.setCaption("Enter a double");\r
- tf.setPropertyDataSource(new ObjectProperty<Double>(2.1));\r
- tf.addValidator(new DoubleValidator("Must be a Double"));\r
- addComponent(tf);\r
- }\r
- \r
- private TextField createIntegerTextField() {\r
- final TextField tf = new TextField("Enter an integer");\r
- tf.setPropertyDataSource(new ObjectProperty<Integer>(new Integer(2)));\r
- tf.setImmediate(true);\r
- tf.addListener(new ValueChangeListener() {\r
- \r
- public void valueChange(ValueChangeEvent event) {\r
- try {\r
- log.log("Value for " + tf.getCaption() + " changed to "\r
- + tf.getValue());\r
- log.log("Converted value is " + tf.getConvertedValue());\r
- } catch (Exception e) {\r
- // TODO: handle exception\r
- e.printStackTrace();\r
- }\r
- }\r
- });\r
- \r
- return tf;\r
- }\r
- \r
- @Override\r
- protected String getDescription() {\r
- // TODO Auto-generated method stub\r
- return null;\r
- }\r
- \r
- @Override\r
- protected Integer getTicketNumber() {\r
- // TODO Auto-generated method stub\r
- return null;\r
- }\r
- \r
- }\r
++package com.vaadin.tests.components.abstractfield;
++
++import com.vaadin.data.Property.ValueChangeEvent;
++import com.vaadin.data.Property.ValueChangeListener;
++import com.vaadin.data.util.ObjectProperty;
++import com.vaadin.data.validator.DoubleValidator;
++import com.vaadin.data.validator.IntegerValidator;
++import com.vaadin.tests.components.TestBase;
++import com.vaadin.tests.util.Log;
++import com.vaadin.ui.TextField;
++
++public class IntegerDoubleFieldsWithDataSource extends TestBase {
++
++ private Log log = new Log(5);
++
++ @Override
++ protected void setup() {
++ addComponent(log);
++
++ TextField tf = createIntegerTextField();
++ tf.addValidator(new IntegerValidator("Must be an Integer"));
++ addComponent(tf);
++
++ tf = createIntegerTextField();
++ tf.setCaption("Enter a double");
++ tf.setPropertyDataSource(new ObjectProperty<Double>(2.1));
++ tf.addValidator(new DoubleValidator("Must be a Double"));
++ addComponent(tf);
++ }
++
++ private TextField createIntegerTextField() {
++ final TextField tf = new TextField("Enter an integer");
++ tf.setPropertyDataSource(new ObjectProperty<Integer>(new Integer(2)));
++ tf.setImmediate(true);
++ tf.addListener(new ValueChangeListener() {
++
++ public void valueChange(ValueChangeEvent event) {
++ try {
++ log.log("Value for " + tf.getCaption() + " changed to "
++ + tf.getValue());
++ log.log("Converted value is " + tf.getConvertedValue());
++ } catch (Exception e) {
++ // TODO: handle exception
++ e.printStackTrace();
++ }
++ }
++ });
++
++ return tf;
++ }
++
++ @Override
++ protected String getDescription() {
++ // TODO Auto-generated method stub
++ return null;
++ }
++
++ @Override
++ protected Integer getTicketNumber() {
++ // TODO Auto-generated method stub
++ return null;
++ }
++
++}
--- /dev/null
- package com.vaadin.tests.components.abstractfield;\r
- \r
- import com.vaadin.data.Property.ValueChangeEvent;\r
- import com.vaadin.data.Property.ValueChangeListener;\r
- import com.vaadin.tests.components.TestBase;\r
- import com.vaadin.tests.util.Log;\r
- import com.vaadin.ui.TextField;\r
- \r
- public class IntegerFieldWithoutDataSource extends TestBase {\r
- \r
- private Log log = new Log(5);\r
- \r
- @Override\r
- protected void setup() {\r
- addComponent(log);\r
- \r
- TextField tf = createIntegerTextField();\r
- tf.setCaption(tf.getCaption() + "(invalid allowed)");\r
- addComponent(tf);\r
- tf = createIntegerTextField();\r
- tf.setInvalidAllowed(false);\r
- tf.setCaption(tf.getCaption() + "(invalid not allowed)");\r
- addComponent(tf);\r
- }\r
- \r
- private TextField createIntegerTextField() {\r
- final TextField tf = new TextField("Enter an integer");\r
- tf.setConverter(Integer.class);\r
- tf.setImmediate(true);\r
- tf.addListener(new ValueChangeListener() {\r
- \r
- public void valueChange(ValueChangeEvent event) {\r
- try {\r
- log.log("Value for " + tf.getCaption() + " changed to "\r
- + tf.getValue());\r
- log.log("Converted value is " + tf.getConvertedValue());\r
- } catch (Exception e) {\r
- // TODO: handle exception\r
- e.printStackTrace();\r
- }\r
- }\r
- });\r
- \r
- return tf;\r
- }\r
- \r
- @Override\r
- protected String getDescription() {\r
- // TODO Auto-generated method stub\r
- return null;\r
- }\r
- \r
- @Override\r
- protected Integer getTicketNumber() {\r
- // TODO Auto-generated method stub\r
- return null;\r
- }\r
- \r
- }\r
++package com.vaadin.tests.components.abstractfield;
++
++import com.vaadin.data.Property.ValueChangeEvent;
++import com.vaadin.data.Property.ValueChangeListener;
++import com.vaadin.tests.components.TestBase;
++import com.vaadin.tests.util.Log;
++import com.vaadin.ui.TextField;
++
++public class IntegerFieldWithoutDataSource extends TestBase {
++
++ private Log log = new Log(5);
++
++ @Override
++ protected void setup() {
++ addComponent(log);
++
++ TextField tf = createIntegerTextField();
++ tf.setCaption(tf.getCaption() + "(invalid allowed)");
++ addComponent(tf);
++ tf = createIntegerTextField();
++ tf.setInvalidAllowed(false);
++ tf.setCaption(tf.getCaption() + "(invalid not allowed)");
++ addComponent(tf);
++ }
++
++ private TextField createIntegerTextField() {
++ final TextField tf = new TextField("Enter an integer");
++ tf.setConverter(Integer.class);
++ tf.setImmediate(true);
++ tf.addListener(new ValueChangeListener() {
++
++ public void valueChange(ValueChangeEvent event) {
++ try {
++ log.log("Value for " + tf.getCaption() + " changed to "
++ + tf.getValue());
++ log.log("Converted value is " + tf.getConvertedValue());
++ } catch (Exception e) {
++ // TODO: handle exception
++ e.printStackTrace();
++ }
++ }
++ });
++
++ return tf;
++ }
++
++ @Override
++ protected String getDescription() {
++ // TODO Auto-generated method stub
++ return null;
++ }
++
++ @Override
++ protected Integer getTicketNumber() {
++ // TODO Auto-generated method stub
++ return null;
++ }
++
++}
--- /dev/null
- package com.vaadin.tests.components.abstractfield;\r
- \r
- import java.util.Date;\r
- \r
- import com.vaadin.data.Property.ValueChangeEvent;\r
- import com.vaadin.data.Property.ValueChangeListener;\r
- import com.vaadin.data.util.ObjectProperty;\r
- import com.vaadin.terminal.UserError;\r
- import com.vaadin.ui.AbstractComponent.ComponentErrorEvent;\r
- import com.vaadin.ui.AbstractComponent.ComponentErrorHandler;\r
- import com.vaadin.ui.ComboBox;\r
- import com.vaadin.ui.TextField;\r
- \r
- public class TextFieldConversions extends AbstractComponentDataBindingTest {\r
- \r
- private TextField tf;\r
- \r
- private Object o;\r
- \r
- private ComboBox dataType;\r
- \r
- @Override\r
- protected void createFields() {\r
- dataType = new ComboBox("Data type");\r
- dataType.setImmediate(true);\r
- dataType.addItem(Long.class);\r
- dataType.addItem(Integer.class);\r
- dataType.addItem(Double.class);\r
- dataType.addItem(Date.class);\r
- dataType.addItem(String.class);\r
- \r
- dataType.addListener(new ValueChangeListener() {\r
- \r
- public void valueChange(ValueChangeEvent event) {\r
- tf.setPropertyDataSource(new ObjectProperty<Object>(o,\r
- (Class<Object>) dataType.getValue()));\r
- }\r
- });\r
- addComponent(dataType);\r
- \r
- tf = new TextField("TextField");\r
- addComponent(tf);\r
- tf.setErrorHandler(new ComponentErrorHandler() {\r
- \r
- public boolean handleComponentError(ComponentErrorEvent event) {\r
- tf.setComponentError(new UserError("Invalid value"));\r
- return true;\r
- }\r
- });\r
- }\r
- }\r
++package com.vaadin.tests.components.abstractfield;
++
++import java.util.Date;
++
++import com.vaadin.data.Property.ValueChangeEvent;
++import com.vaadin.data.Property.ValueChangeListener;
++import com.vaadin.data.util.ObjectProperty;
++import com.vaadin.terminal.UserError;
++import com.vaadin.ui.AbstractComponent.ComponentErrorEvent;
++import com.vaadin.ui.AbstractComponent.ComponentErrorHandler;
++import com.vaadin.ui.ComboBox;
++import com.vaadin.ui.TextField;
++
++public class TextFieldConversions extends AbstractComponentDataBindingTest {
++
++ private TextField tf;
++
++ private Object o;
++
++ private ComboBox dataType;
++
++ @Override
++ protected void createFields() {
++ dataType = new ComboBox("Data type");
++ dataType.setImmediate(true);
++ dataType.addItem(Long.class);
++ dataType.addItem(Integer.class);
++ dataType.addItem(Double.class);
++ dataType.addItem(Date.class);
++ dataType.addItem(String.class);
++
++ dataType.addListener(new ValueChangeListener() {
++
++ public void valueChange(ValueChangeEvent event) {
++ tf.setPropertyDataSource(new ObjectProperty<Object>(o,
++ (Class<Object>) dataType.getValue()));
++ }
++ });
++ addComponent(dataType);
++
++ tf = new TextField("TextField");
++ addComponent(tf);
++ tf.setErrorHandler(new ComponentErrorHandler() {
++
++ public boolean handleComponentError(ComponentErrorEvent event) {
++ tf.setComponentError(new UserError("Invalid value"));
++ return true;
++ }
++ });
++ }
++}
--- /dev/null
- package com.vaadin.tests.components.abstractfield;\r
- \r
- import java.util.Locale;\r
- \r
- import com.vaadin.data.util.converter.Converter;\r
- \r
- public class Vaadin6ImplicitDoubleConverter implements\r
- Converter<String, Double> {\r
- \r
- public Double convertToModel(String value, Locale locale)\r
- throws com.vaadin.data.util.converter.Converter.ConversionException {\r
- if (null == value) {\r
- return null;\r
- }\r
- return new Double(value.toString());\r
- }\r
- \r
- public String convertToPresentation(Double value, Locale locale)\r
- throws com.vaadin.data.util.converter.Converter.ConversionException {\r
- if (value == null) {\r
- return null;\r
- }\r
- return value.toString();\r
- \r
- }\r
- \r
- public Class<Double> getModelType() {\r
- return Double.class;\r
- }\r
- \r
- public Class<String> getPresentationType() {\r
- return String.class;\r
- }\r
- \r
- }\r
++package com.vaadin.tests.components.abstractfield;
++
++import java.util.Locale;
++
++import com.vaadin.data.util.converter.Converter;
++
++public class Vaadin6ImplicitDoubleConverter implements
++ Converter<String, Double> {
++
++ public Double convertToModel(String value, Locale locale)
++ throws com.vaadin.data.util.converter.Converter.ConversionException {
++ if (null == value) {
++ return null;
++ }
++ return new Double(value.toString());
++ }
++
++ public String convertToPresentation(Double value, Locale locale)
++ throws com.vaadin.data.util.converter.Converter.ConversionException {
++ if (value == null) {
++ return null;
++ }
++ return value.toString();
++
++ }
++
++ public Class<Double> getModelType() {
++ return Double.class;
++ }
++
++ public Class<String> getPresentationType() {
++ return String.class;
++ }
++
++}
- package com.vaadin.tests.components.button;\r
- \r
- import java.util.LinkedHashMap;\r
- \r
- import com.vaadin.tests.components.AbstractComponentTest;\r
- import com.vaadin.ui.Button;\r
- import com.vaadin.ui.Button.ClickEvent;\r
- import com.vaadin.ui.Button.ClickListener;\r
- import com.vaadin.ui.themes.Reindeer;\r
- \r
- public class Buttons2<T extends Button> extends AbstractComponentTest<T>\r
- implements ClickListener {\r
- \r
- private Command<T, Boolean> disableOnClickCommand = new Command<T, Boolean>() {\r
- \r
- public void execute(T c, Boolean value, Object data) {\r
- c.setDisableOnClick(value);\r
- }\r
- };\r
- \r
- private Command<T, Boolean> clickListenerCommand = new Command<T, Boolean>() {\r
- \r
- public void execute(T c, Boolean value, Object data) {\r
- if (value) {\r
- c.addListener((Button.ClickListener) Buttons2.this);\r
- } else {\r
- c.removeListener((Button.ClickListener) Buttons2.this);\r
- }\r
- \r
- }\r
- };\r
- \r
- @SuppressWarnings("unchecked")\r
- @Override\r
- protected Class<T> getTestClass() {\r
- return (Class<T>) Button.class;\r
- }\r
- \r
- @Override\r
- protected void createActions() {\r
- super.createActions();\r
- \r
- createFocusListener(CATEGORY_LISTENERS);\r
- createBlurListener(CATEGORY_LISTENERS);\r
- \r
- createBooleanAction("Disable on click", CATEGORY_FEATURES, false,\r
- disableOnClickCommand);\r
- addClickListener(CATEGORY_LISTENERS);\r
- }\r
- \r
- @Override\r
- protected void createComponentStyleNames(\r
- LinkedHashMap<String, String> options) {\r
- options.put("Reindeer default", Reindeer.BUTTON_DEFAULT);\r
- options.put("Reindeer small", Reindeer.BUTTON_SMALL);\r
- options.put("Reindeer link", Reindeer.BUTTON_LINK);\r
- }\r
- \r
- private void addClickListener(String category) {\r
- createBooleanAction("Click listener", category, false,\r
- clickListenerCommand);\r
- \r
- }\r
- \r
- public void buttonClick(ClickEvent event) {\r
- log(event.getClass().getSimpleName());\r
- }\r
- }\r
+ package com.vaadin.tests.components.button;
+
+ import java.util.LinkedHashMap;
+
-import com.vaadin.tests.components.abstractfield.AbstractFieldTest;
++import com.vaadin.tests.components.AbstractComponentTest;
+ import com.vaadin.ui.Button;
+ import com.vaadin.ui.Button.ClickEvent;
+ import com.vaadin.ui.Button.ClickListener;
+ import com.vaadin.ui.themes.Reindeer;
+
-public class Buttons2<T extends Button> extends AbstractFieldTest<T> implements
- ClickListener {
-
- private Command<T, Boolean> switchModeCommand = new Command<T, Boolean>() {
-
- @SuppressWarnings("deprecation")
- public void execute(T c, Boolean value, Object data) {
- c.setSwitchMode(value);
- }
- };
++public class Buttons2<T extends Button> extends AbstractComponentTest<T>
++ implements ClickListener {
+
+ private Command<T, Boolean> disableOnClickCommand = new Command<T, Boolean>() {
+
+ public void execute(T c, Boolean value, Object data) {
+ c.setDisableOnClick(value);
+ }
+ };
+
+ private Command<T, Boolean> clickListenerCommand = new Command<T, Boolean>() {
+
+ public void execute(T c, Boolean value, Object data) {
+ if (value) {
+ c.addListener((Button.ClickListener) Buttons2.this);
+ } else {
+ c.removeListener((Button.ClickListener) Buttons2.this);
+ }
+
+ }
+ };
+
++ @SuppressWarnings("unchecked")
+ @Override
+ protected Class<T> getTestClass() {
+ return (Class<T>) Button.class;
+ }
+
+ @Override
+ protected void createActions() {
+ super.createActions();
+
- createBooleanAction("Switch mode", CATEGORY_FEATURES, false,
- switchModeCommand);
++ createFocusListener(CATEGORY_LISTENERS);
++ createBlurListener(CATEGORY_LISTENERS);
++
+ createBooleanAction("Disable on click", CATEGORY_FEATURES, false,
+ disableOnClickCommand);
+ addClickListener(CATEGORY_LISTENERS);
+ }
+
+ @Override
+ protected void createComponentStyleNames(
+ LinkedHashMap<String, String> options) {
+ options.put("Reindeer default", Reindeer.BUTTON_DEFAULT);
+ options.put("Reindeer small", Reindeer.BUTTON_SMALL);
+ options.put("Reindeer link", Reindeer.BUTTON_LINK);
+ }
+
+ private void addClickListener(String category) {
+ createBooleanAction("Click listener", category, false,
+ clickListenerCommand);
+
+ }
+
+ public void buttonClick(ClickEvent event) {
+ log(event.getClass().getSimpleName());
+ }
+ }
- package com.vaadin.tests.components.button;\r
- \r
- import com.vaadin.tests.components.AbstractTestCase;\r
- import com.vaadin.ui.Button;\r
- import com.vaadin.ui.HorizontalLayout;\r
- import com.vaadin.ui.Root.LegacyWindow;\r
- import com.vaadin.ui.VerticalLayout;\r
- import com.vaadin.ui.themes.BaseTheme;\r
- \r
- public class ButtonsInHorizontalLayout extends AbstractTestCase {\r
- \r
- @Override\r
- public void init() {\r
- VerticalLayout content = new VerticalLayout();\r
- content.setMargin(true);\r
- content.setSpacing(true);\r
- \r
- content.addComponent(createButtonLayout(null));\r
- content.addComponent(createButtonLayout(BaseTheme.BUTTON_LINK));\r
- \r
- setMainWindow(new LegacyWindow("", content));\r
- }\r
- \r
- private HorizontalLayout createButtonLayout(String style) {\r
- HorizontalLayout layout = new HorizontalLayout();\r
- layout.setSpacing(true);\r
- layout.addComponent(createButton(style));\r
- layout.addComponent(createButton(style));\r
- layout.addComponent(createButton(style));\r
- return layout;\r
- }\r
- \r
- private Button createButton(String style) {\r
- Button button = new Button(\r
- "Look at me in IE7 or IE8 in compatibility mode");\r
- if (style != null && style.length() != 0) {\r
- button.setStyleName(style);\r
- }\r
- return button;\r
- }\r
- \r
- @Override\r
- protected String getDescription() {\r
- return "Tests for rendering of buttons in a HorizontalLayout";\r
- }\r
- \r
- @Override\r
- protected Integer getTicketNumber() {\r
- return 7978;\r
- }\r
- \r
- }\r
+ package com.vaadin.tests.components.button;
+
+ import com.vaadin.tests.components.AbstractTestCase;
+ import com.vaadin.ui.Button;
+ import com.vaadin.ui.HorizontalLayout;
++import com.vaadin.ui.Root.LegacyWindow;
+ import com.vaadin.ui.VerticalLayout;
-import com.vaadin.ui.Window;
+ import com.vaadin.ui.themes.BaseTheme;
+
+ public class ButtonsInHorizontalLayout extends AbstractTestCase {
+
+ @Override
+ public void init() {
+ VerticalLayout content = new VerticalLayout();
+ content.setMargin(true);
+ content.setSpacing(true);
+
+ content.addComponent(createButtonLayout(null));
+ content.addComponent(createButtonLayout(BaseTheme.BUTTON_LINK));
+
- setMainWindow(new Window("", content));
++ setMainWindow(new LegacyWindow("", content));
+ }
+
+ private HorizontalLayout createButtonLayout(String style) {
+ HorizontalLayout layout = new HorizontalLayout();
+ layout.setSpacing(true);
+ layout.addComponent(createButton(style));
+ layout.addComponent(createButton(style));
+ layout.addComponent(createButton(style));
+ return layout;
+ }
+
+ private Button createButton(String style) {
+ Button button = new Button(
+ "Look at me in IE7 or IE8 in compatibility mode");
+ if (style != null && style.length() != 0) {
+ button.setStyleName(style);
+ }
+ return button;
+ }
+
+ @Override
+ protected String getDescription() {
+ return "Tests for rendering of buttons in a HorizontalLayout";
+ }
+
+ @Override
+ protected Integer getTicketNumber() {
+ return 7978;
+ }
+
+ }
- package com.vaadin.tests.components.checkbox;\r
- \r
- import com.vaadin.tests.components.abstractfield.AbstractFieldTest;\r
- import com.vaadin.ui.Button.ClickEvent;\r
- import com.vaadin.ui.Button.ClickListener;\r
- import com.vaadin.ui.CheckBox;\r
- \r
- public class CheckBoxes2 extends AbstractFieldTest<CheckBox> implements\r
- ClickListener {\r
- \r
- @Override\r
- protected Class<CheckBox> getTestClass() {\r
- return CheckBox.class;\r
- }\r
- \r
- @Override\r
- protected void createActions() {\r
- super.createActions();\r
- \r
- }\r
- \r
- public void buttonClick(ClickEvent event) {\r
- log(event.getClass().getSimpleName());\r
- }\r
- }\r
+ package com.vaadin.tests.components.checkbox;
+
+ import com.vaadin.tests.components.abstractfield.AbstractFieldTest;
+ import com.vaadin.ui.Button.ClickEvent;
+ import com.vaadin.ui.Button.ClickListener;
+ import com.vaadin.ui.CheckBox;
+
+ public class CheckBoxes2 extends AbstractFieldTest<CheckBox> implements
+ ClickListener {
+
- // cannot extend Buttons2 because of Switch mode problems
-
+ @Override
+ protected Class<CheckBox> getTestClass() {
+ return CheckBox.class;
+ }
+
- private Command<CheckBox, Boolean> switchModeCommand = new Command<CheckBox, Boolean>() {
-
- @SuppressWarnings("deprecation")
- public void execute(CheckBox c, Boolean value, Object data) {
- c.setSwitchMode(value);
- }
- };
-
- private Command<CheckBox, Boolean> clickListenerCommand = new Command<CheckBox, Boolean>() {
-
- public void execute(CheckBox c, Boolean value, Object data) {
- if (value) {
- c.addListener((ClickListener) CheckBoxes2.this);
- } else {
- c.removeListener((ClickListener) CheckBoxes2.this);
- }
-
- }
- };
-
+ @Override
+ protected void createActions() {
+ super.createActions();
+
- createBooleanAction("Switch mode", CATEGORY_FEATURES, true,
- switchModeCommand);
- addClickListener(CATEGORY_LISTENERS);
- }
-
- private void addClickListener(String category) {
- createBooleanAction("Click listener", category, false,
- clickListenerCommand);
-
+ }
+
+ public void buttonClick(ClickEvent event) {
+ log(event.getClass().getSimpleName());
+ }
+ }
- package com.vaadin.tests.components.customcomponent;\r
- \r
- import com.vaadin.data.Property.ValueChangeEvent;\r
- import com.vaadin.tests.components.TestBase;\r
- import com.vaadin.ui.Button;\r
- import com.vaadin.ui.CustomComponent;\r
- import com.vaadin.ui.Label;\r
- import com.vaadin.ui.Label.ContentMode;\r
- import com.vaadin.ui.TextField;\r
- \r
- public class ClipContent extends TestBase {\r
- \r
- @Override\r
- protected void setup() {\r
- \r
- Label text = new Label(\r
- "1_long_line_that_should_be_clipped<br/>2_long_line_that_should_be_clipped<br/>3_long_line_that_should_be_clipped<br/>4_long_line_that_should_be_clipped<br/>",\r
- ContentMode.XHTML);\r
- \r
- final CustomComponent cc = new CustomComponent(text);\r
- cc.setWidth("20px");\r
- cc.setHeight("20px");\r
- \r
- final TextField w = new TextField("Width");\r
- w.setValue("20px");\r
- w.addListener(new TextField.ValueChangeListener() {\r
- public void valueChange(ValueChangeEvent event) {\r
- cc.setWidth(w.getValue());\r
- }\r
- });\r
- addComponent(w);\r
- final TextField h = new TextField("Height");\r
- h.setValue("20px");\r
- h.addListener(new TextField.ValueChangeListener() {\r
- public void valueChange(ValueChangeEvent event) {\r
- cc.setHeight(h.getValue());\r
- }\r
- });\r
- addComponent(h);\r
- Button b = new Button("apply");\r
- addComponent(b);\r
- \r
- addComponent(cc);\r
- \r
- }\r
- \r
- @Override\r
- protected String getDescription() {\r
- return "The text in CustomComponent should be clipped if it has size defined.";\r
- }\r
- \r
- @Override\r
- protected Integer getTicketNumber() {\r
- return null;\r
- }\r
- \r
- }\r
+ package com.vaadin.tests.components.customcomponent;
+
+ import com.vaadin.data.Property.ValueChangeEvent;
+ import com.vaadin.tests.components.TestBase;
+ import com.vaadin.ui.Button;
+ import com.vaadin.ui.CustomComponent;
+ import com.vaadin.ui.Label;
++import com.vaadin.ui.Label.ContentMode;
+ import com.vaadin.ui.TextField;
+
+ public class ClipContent extends TestBase {
+
+ @Override
+ protected void setup() {
+
+ Label text = new Label(
+ "1_long_line_that_should_be_clipped<br/>2_long_line_that_should_be_clipped<br/>3_long_line_that_should_be_clipped<br/>4_long_line_that_should_be_clipped<br/>",
- Label.CONTENT_XHTML);
++ ContentMode.XHTML);
+
+ final CustomComponent cc = new CustomComponent(text);
+ cc.setWidth("20px");
+ cc.setHeight("20px");
+
+ final TextField w = new TextField("Width");
+ w.setValue("20px");
+ w.addListener(new TextField.ValueChangeListener() {
+ public void valueChange(ValueChangeEvent event) {
- cc.setWidth((String) w.getValue());
++ cc.setWidth(w.getValue());
+ }
+ });
+ addComponent(w);
+ final TextField h = new TextField("Height");
+ h.setValue("20px");
+ h.addListener(new TextField.ValueChangeListener() {
+ public void valueChange(ValueChangeEvent event) {
- cc.setHeight((String) h.getValue());
++ cc.setHeight(h.getValue());
+ }
+ });
+ addComponent(h);
+ Button b = new Button("apply");
+ addComponent(b);
+
+ addComponent(cc);
+
+ }
+
+ @Override
+ protected String getDescription() {
+ return "The text in CustomComponent should be clipped if it has size defined.";
+ }
+
+ @Override
+ protected Integer getTicketNumber() {
+ return null;
+ }
+
+ }
--- /dev/null
- package com.vaadin.tests.components.customfield;\r
- \r
- import com.vaadin.data.Item;\r
- import com.vaadin.data.Property;\r
- import com.vaadin.data.Property.ValueChangeEvent;\r
- import com.vaadin.tests.components.TestBase;\r
- import com.vaadin.tests.util.Person;\r
- import com.vaadin.ui.Table;\r
- \r
- /**\r
- * Demonstrate the use of a form as a custom field within another form.\r
- */\r
- public abstract class AbstractNestedFormExample extends TestBase {\r
- private NestedPersonForm personForm;\r
- private boolean embeddedAddress;\r
- \r
- public void setup(boolean embeddedAddress) {\r
- this.embeddedAddress = embeddedAddress;\r
- \r
- addComponent(getPersonTable());\r
- }\r
- \r
- /**\r
- * Creates a table with two person objects\r
- */\r
- public Table getPersonTable() {\r
- Table table = new Table();\r
- table.setPageLength(5);\r
- table.setSelectable(true);\r
- table.setImmediate(true);\r
- table.setNullSelectionAllowed(true);\r
- table.addContainerProperty("Name", String.class, null);\r
- table.addListener(getTableValueChangeListener());\r
- Person person = new Person("Teppo", "Testaaja",\r
- "teppo.testaaja@example.com", "", "Ruukinkatu 2–4", 20540,\r
- "Turku");\r
- Person person2 = new Person("Taina", "Testaaja",\r
- "taina.testaaja@example.com", "", "Ruukinkatu 2–4", 20540,\r
- "Turku");\r
- Item item = table.addItem(person);\r
- item.getItemProperty("Name").setValue(\r
- person.getFirstName() + " " + person.getLastName());\r
- item = table.addItem(person2);\r
- item.getItemProperty("Name").setValue(\r
- person2.getFirstName() + " " + person2.getLastName());\r
- return table;\r
- }\r
- \r
- /**\r
- * Creates value change listener for the table\r
- */\r
- private Property.ValueChangeListener getTableValueChangeListener() {\r
- return new Property.ValueChangeListener() {\r
- \r
- public void valueChange(ValueChangeEvent event) {\r
- if (personForm != null) {\r
- removeComponent(personForm);\r
- }\r
- if (event.getProperty().getValue() != null) {\r
- personForm = new NestedPersonForm((Person) event\r
- .getProperty().getValue(), embeddedAddress);\r
- personForm.setWidth("350px");\r
- addComponent(personForm);\r
- }\r
- }\r
- \r
- };\r
- }\r
- \r
- @Override\r
- protected Integer getTicketNumber() {\r
- return null;\r
- }\r
- \r
- }\r
++package com.vaadin.tests.components.customfield;
++
++import com.vaadin.data.Item;
++import com.vaadin.data.Property;
++import com.vaadin.data.Property.ValueChangeEvent;
++import com.vaadin.tests.components.TestBase;
++import com.vaadin.tests.util.Person;
++import com.vaadin.ui.Table;
++
++/**
++ * Demonstrate the use of a form as a custom field within another form.
++ */
++public abstract class AbstractNestedFormExample extends TestBase {
++ private NestedPersonForm personForm;
++ private boolean embeddedAddress;
++
++ public void setup(boolean embeddedAddress) {
++ this.embeddedAddress = embeddedAddress;
++
++ addComponent(getPersonTable());
++ }
++
++ /**
++ * Creates a table with two person objects
++ */
++ public Table getPersonTable() {
++ Table table = new Table();
++ table.setPageLength(5);
++ table.setSelectable(true);
++ table.setImmediate(true);
++ table.setNullSelectionAllowed(true);
++ table.addContainerProperty("Name", String.class, null);
++ table.addListener(getTableValueChangeListener());
++ Person person = new Person("Teppo", "Testaaja",
++ "teppo.testaaja@example.com", "", "Ruukinkatu 2–4", 20540,
++ "Turku");
++ Person person2 = new Person("Taina", "Testaaja",
++ "taina.testaaja@example.com", "", "Ruukinkatu 2–4", 20540,
++ "Turku");
++ Item item = table.addItem(person);
++ item.getItemProperty("Name").setValue(
++ person.getFirstName() + " " + person.getLastName());
++ item = table.addItem(person2);
++ item.getItemProperty("Name").setValue(
++ person2.getFirstName() + " " + person2.getLastName());
++ return table;
++ }
++
++ /**
++ * Creates value change listener for the table
++ */
++ private Property.ValueChangeListener getTableValueChangeListener() {
++ return new Property.ValueChangeListener() {
++
++ public void valueChange(ValueChangeEvent event) {
++ if (personForm != null) {
++ removeComponent(personForm);
++ }
++ if (event.getProperty().getValue() != null) {
++ personForm = new NestedPersonForm((Person) event
++ .getProperty().getValue(), embeddedAddress);
++ personForm.setWidth("350px");
++ addComponent(personForm);
++ }
++ }
++
++ };
++ }
++
++ @Override
++ protected Integer getTicketNumber() {
++ return null;
++ }
++
++}
--- /dev/null
- package com.vaadin.tests.components.customfield;\r
- \r
- import java.util.Arrays;\r
- import java.util.List;\r
- \r
- import com.vaadin.data.Buffered;\r
- import com.vaadin.data.Validator.InvalidValueException;\r
- import com.vaadin.data.util.BeanItem;\r
- import com.vaadin.tests.util.Address;\r
- import com.vaadin.ui.Component;\r
- import com.vaadin.ui.CustomField;\r
- import com.vaadin.ui.Form;\r
- \r
- /**\r
- * Nested form for the Address object of the Person object\r
- */\r
- public class AddressField extends CustomField<Address> {\r
- private Form addressForm;\r
- private final Form parentForm;\r
- \r
- public AddressField() {\r
- this(null);\r
- }\r
- \r
- public AddressField(Form parentForm) {\r
- this.parentForm = parentForm;\r
- }\r
- \r
- @Override\r
- protected Component initContent() {\r
- if (parentForm != null) {\r
- addressForm = new EmbeddedForm(parentForm);\r
- } else {\r
- addressForm = new Form();\r
- }\r
- addressForm.setCaption("Address");\r
- addressForm.setWriteThrough(false);\r
- \r
- // make sure field changes are sent early\r
- addressForm.setImmediate(true);\r
- \r
- return addressForm;\r
- }\r
- \r
- @Override\r
- protected Form getContent() {\r
- return (Form) super.getContent();\r
- }\r
- \r
- @Override\r
- public void setInternalValue(Address address) throws ReadOnlyException {\r
- // create the address if not given\r
- if (null == address) {\r
- address = new Address();\r
- }\r
- \r
- super.setInternalValue(address);\r
- \r
- // set item data source and visible properties in a single operation to\r
- // avoid creating fields multiple times\r
- List<String> visibleProperties = Arrays.asList("streetAddress",\r
- "postalCode", "city");\r
- getContent().setItemDataSource(new BeanItem<Address>(address),\r
- visibleProperties);\r
- }\r
- \r
- /**\r
- * commit changes of the address form\r
- */\r
- @Override\r
- public void commit() throws Buffered.SourceException, InvalidValueException {\r
- addressForm.commit();\r
- super.commit();\r
- }\r
- \r
- /**\r
- * discard changes of the address form\r
- */\r
- @Override\r
- public void discard() throws Buffered.SourceException {\r
- // Do not discard the top-level value\r
- // super.discard();\r
- addressForm.discard();\r
- }\r
- \r
- @Override\r
- public boolean isReadOnly() {\r
- // In this application, the address is modified implicitly by\r
- // addressForm.commit(), not by setting the Address object for a Person.\r
- return false;\r
- }\r
- \r
- @Override\r
- public Class<Address> getType() {\r
- return Address.class;\r
- }\r
++package com.vaadin.tests.components.customfield;
++
++import java.util.Arrays;
++import java.util.List;
++
++import com.vaadin.data.Buffered;
++import com.vaadin.data.Validator.InvalidValueException;
++import com.vaadin.data.util.BeanItem;
++import com.vaadin.tests.util.Address;
++import com.vaadin.ui.Component;
++import com.vaadin.ui.CustomField;
++import com.vaadin.ui.Form;
++
++/**
++ * Nested form for the Address object of the Person object
++ */
++public class AddressField extends CustomField<Address> {
++ private Form addressForm;
++ private final Form parentForm;
++
++ public AddressField() {
++ this(null);
++ }
++
++ public AddressField(Form parentForm) {
++ this.parentForm = parentForm;
++ }
++
++ @Override
++ protected Component initContent() {
++ if (parentForm != null) {
++ addressForm = new EmbeddedForm(parentForm);
++ } else {
++ addressForm = new Form();
++ }
++ addressForm.setCaption("Address");
++ addressForm.setWriteThrough(false);
++
++ // make sure field changes are sent early
++ addressForm.setImmediate(true);
++
++ return addressForm;
++ }
++
++ @Override
++ protected Form getContent() {
++ return (Form) super.getContent();
++ }
++
++ @Override
++ public void setInternalValue(Address address) throws ReadOnlyException {
++ // create the address if not given
++ if (null == address) {
++ address = new Address();
++ }
++
++ super.setInternalValue(address);
++
++ // set item data source and visible properties in a single operation to
++ // avoid creating fields multiple times
++ List<String> visibleProperties = Arrays.asList("streetAddress",
++ "postalCode", "city");
++ getContent().setItemDataSource(new BeanItem<Address>(address),
++ visibleProperties);
++ }
++
++ /**
++ * commit changes of the address form
++ */
++ @Override
++ public void commit() throws Buffered.SourceException, InvalidValueException {
++ addressForm.commit();
++ super.commit();
++ }
++
++ /**
++ * discard changes of the address form
++ */
++ @Override
++ public void discard() throws Buffered.SourceException {
++ // Do not discard the top-level value
++ // super.discard();
++ addressForm.discard();
++ }
++
++ @Override
++ public boolean isReadOnly() {
++ // In this application, the address is modified implicitly by
++ // addressForm.commit(), not by setting the Address object for a Person.
++ return false;
++ }
++
++ @Override
++ public Class<Address> getType() {
++ return Address.class;
++ }
+}
--- /dev/null
- package com.vaadin.tests.components.customfield;\r
- \r
- import com.vaadin.tests.components.TestBase;\r
- import com.vaadin.tests.util.Address;\r
- import com.vaadin.ui.Button;\r
- import com.vaadin.ui.Button.ClickEvent;\r
- \r
- /**\r
- * Demonstrate a custom field which is a form, and contains another custom field\r
- * for the selection of a city.\r
- */\r
- public class AddressFormExample extends TestBase {\r
- \r
- @Override\r
- protected void setup() {\r
- Address address = new Address("Ruukinkatu 2-4", 20540, "Turku");\r
- final AddressField field = new AddressField();\r
- field.setValue(address);\r
- \r
- addComponent(field);\r
- \r
- Button commitButton = new Button("Save", new Button.ClickListener() {\r
- public void buttonClick(ClickEvent event) {\r
- field.commit();\r
- Address address = field.getValue();\r
- field.getRoot().showNotification(\r
- "Address saved: " + address.getStreetAddress() + ", "\r
- + address.getPostalCode() + ", "\r
- + address.getCity());\r
- }\r
- });\r
- addComponent(commitButton);\r
- }\r
- \r
- @Override\r
- protected String getDescription() {\r
- return "Custom field for editing an Address";\r
- }\r
- \r
- @Override\r
- protected Integer getTicketNumber() {\r
- return null;\r
- }\r
- \r
- }\r
++package com.vaadin.tests.components.customfield;
++
++import com.vaadin.tests.components.TestBase;
++import com.vaadin.tests.util.Address;
++import com.vaadin.ui.Button;
++import com.vaadin.ui.Button.ClickEvent;
++
++/**
++ * Demonstrate a custom field which is a form, and contains another custom field
++ * for the selection of a city.
++ */
++public class AddressFormExample extends TestBase {
++
++ @Override
++ protected void setup() {
++ Address address = new Address("Ruukinkatu 2-4", 20540, "Turku");
++ final AddressField field = new AddressField();
++ field.setValue(address);
++
++ addComponent(field);
++
++ Button commitButton = new Button("Save", new Button.ClickListener() {
++ public void buttonClick(ClickEvent event) {
++ field.commit();
++ Address address = field.getValue();
++ field.getRoot().showNotification(
++ "Address saved: " + address.getStreetAddress() + ", "
++ + address.getPostalCode() + ", "
++ + address.getCity());
++ }
++ });
++ addComponent(commitButton);
++ }
++
++ @Override
++ protected String getDescription() {
++ return "Custom field for editing an Address";
++ }
++
++ @Override
++ protected Integer getTicketNumber() {
++ return null;
++ }
++
++}
--- /dev/null
- package com.vaadin.tests.components.customfield;\r
- \r
- import com.vaadin.ui.Button;\r
- import com.vaadin.ui.Button.ClickEvent;\r
- import com.vaadin.ui.Button.ClickListener;\r
- import com.vaadin.ui.Component;\r
- import com.vaadin.ui.CustomField;\r
- import com.vaadin.ui.Label;\r
- import com.vaadin.ui.VerticalLayout;\r
- \r
- /**\r
- * An example of a custom field for editing a boolean value. The field is\r
- * composed of multiple components, and could also edit a more complex data\r
- * structures. Here, the commit etc. logic is not overridden.\r
- */\r
- public class BooleanField extends CustomField {\r
- \r
- @Override\r
- protected Component initContent() {\r
- VerticalLayout layout = new VerticalLayout();\r
- \r
- layout.addComponent(new Label("Please click the button"));\r
- \r
- final Button button = new Button("Click me");\r
- button.addListener(new ClickListener() {\r
- public void buttonClick(ClickEvent event) {\r
- Object value = getValue();\r
- boolean newValue = true;\r
- if ((value instanceof Boolean) && ((Boolean) value)) {\r
- newValue = false;\r
- }\r
- setValue(newValue);\r
- button.setCaption(newValue ? "On" : "Off");\r
- }\r
- });\r
- layout.addComponent(button);\r
- \r
- return layout;\r
- }\r
- \r
- @Override\r
- public Class<?> getType() {\r
- return Boolean.class;\r
- }\r
++package com.vaadin.tests.components.customfield;
++
++import com.vaadin.ui.Button;
++import com.vaadin.ui.Button.ClickEvent;
++import com.vaadin.ui.Button.ClickListener;
++import com.vaadin.ui.Component;
++import com.vaadin.ui.CustomField;
++import com.vaadin.ui.Label;
++import com.vaadin.ui.VerticalLayout;
++
++/**
++ * An example of a custom field for editing a boolean value. The field is
++ * composed of multiple components, and could also edit a more complex data
++ * structures. Here, the commit etc. logic is not overridden.
++ */
++public class BooleanField extends CustomField {
++
++ @Override
++ protected Component initContent() {
++ VerticalLayout layout = new VerticalLayout();
++
++ layout.addComponent(new Label("Please click the button"));
++
++ final Button button = new Button("Click me");
++ button.addListener(new ClickListener() {
++ public void buttonClick(ClickEvent event) {
++ Object value = getValue();
++ boolean newValue = true;
++ if ((value instanceof Boolean) && ((Boolean) value)) {
++ newValue = false;
++ }
++ setValue(newValue);
++ button.setCaption(newValue ? "On" : "Off");
++ }
++ });
++ layout.addComponent(button);
++
++ return layout;
++ }
++
++ @Override
++ public Class<?> getType() {
++ return Boolean.class;
++ }
+}
--- /dev/null
- package com.vaadin.tests.components.customfield;\r
- \r
- import com.vaadin.data.Item;\r
- import com.vaadin.data.util.BeanItem;\r
- import com.vaadin.tests.components.TestBase;\r
- import com.vaadin.ui.Button;\r
- import com.vaadin.ui.Button.ClickEvent;\r
- import com.vaadin.ui.Button.ClickListener;\r
- import com.vaadin.ui.Component;\r
- import com.vaadin.ui.DefaultFieldFactory;\r
- import com.vaadin.ui.Field;\r
- import com.vaadin.ui.Form;\r
- import com.vaadin.ui.VerticalLayout;\r
- \r
- public class BooleanFieldExample extends TestBase {\r
- \r
- /**\r
- * Data model class with two boolean fields.\r
- */\r
- public static class TwoBooleans {\r
- private boolean normal;\r
- private boolean custom;\r
- \r
- public void setNormal(boolean normal) {\r
- this.normal = normal;\r
- }\r
- \r
- public boolean isNormal() {\r
- return normal;\r
- }\r
- \r
- public void setCustom(boolean custom) {\r
- this.custom = custom;\r
- }\r
- \r
- public boolean isCustom() {\r
- return custom;\r
- }\r
- }\r
- \r
- @Override\r
- protected void setup() {\r
- final VerticalLayout layout = new VerticalLayout();\r
- layout.setMargin(true);\r
- \r
- final Form form = new Form();\r
- form.setFormFieldFactory(new DefaultFieldFactory() {\r
- @Override\r
- public Field createField(Item item, Object propertyId,\r
- Component uiContext) {\r
- if ("custom".equals(propertyId)) {\r
- return new BooleanField();\r
- }\r
- return super.createField(item, propertyId, uiContext);\r
- }\r
- });\r
- final TwoBooleans data = new TwoBooleans();\r
- form.setItemDataSource(new BeanItem<TwoBooleans>(data));\r
- \r
- layout.addComponent(form);\r
- \r
- Button submit = new Button("Submit", new ClickListener() {\r
- public void buttonClick(ClickEvent event) {\r
- form.commit();\r
- layout.getRoot()\r
- .showNotification(\r
- "The custom boolean field value is "\r
- + data.isCustom()\r
- + ".<br>"\r
- + "The checkbox (default boolean field) value is "\r
- + data.isNormal() + ".");\r
- }\r
- });\r
- layout.addComponent(submit);\r
- \r
- addComponent(layout);\r
- }\r
- \r
- @Override\r
- protected String getDescription() {\r
- return "A customized field (a two-state button) for editing a boolean value.";\r
- }\r
- \r
- @Override\r
- protected Integer getTicketNumber() {\r
- return null;\r
- }\r
- \r
- }\r
++package com.vaadin.tests.components.customfield;
++
++import com.vaadin.data.Item;
++import com.vaadin.data.util.BeanItem;
++import com.vaadin.tests.components.TestBase;
++import com.vaadin.ui.Button;
++import com.vaadin.ui.Button.ClickEvent;
++import com.vaadin.ui.Button.ClickListener;
++import com.vaadin.ui.Component;
++import com.vaadin.ui.DefaultFieldFactory;
++import com.vaadin.ui.Field;
++import com.vaadin.ui.Form;
++import com.vaadin.ui.VerticalLayout;
++
++public class BooleanFieldExample extends TestBase {
++
++ /**
++ * Data model class with two boolean fields.
++ */
++ public static class TwoBooleans {
++ private boolean normal;
++ private boolean custom;
++
++ public void setNormal(boolean normal) {
++ this.normal = normal;
++ }
++
++ public boolean isNormal() {
++ return normal;
++ }
++
++ public void setCustom(boolean custom) {
++ this.custom = custom;
++ }
++
++ public boolean isCustom() {
++ return custom;
++ }
++ }
++
++ @Override
++ protected void setup() {
++ final VerticalLayout layout = new VerticalLayout();
++ layout.setMargin(true);
++
++ final Form form = new Form();
++ form.setFormFieldFactory(new DefaultFieldFactory() {
++ @Override
++ public Field createField(Item item, Object propertyId,
++ Component uiContext) {
++ if ("custom".equals(propertyId)) {
++ return new BooleanField();
++ }
++ return super.createField(item, propertyId, uiContext);
++ }
++ });
++ final TwoBooleans data = new TwoBooleans();
++ form.setItemDataSource(new BeanItem<TwoBooleans>(data));
++
++ layout.addComponent(form);
++
++ Button submit = new Button("Submit", new ClickListener() {
++ public void buttonClick(ClickEvent event) {
++ form.commit();
++ layout.getRoot()
++ .showNotification(
++ "The custom boolean field value is "
++ + data.isCustom()
++ + ".<br>"
++ + "The checkbox (default boolean field) value is "
++ + data.isNormal() + ".");
++ }
++ });
++ layout.addComponent(submit);
++
++ addComponent(layout);
++ }
++
++ @Override
++ protected String getDescription() {
++ return "A customized field (a two-state button) for editing a boolean value.";
++ }
++
++ @Override
++ protected Integer getTicketNumber() {
++ return null;
++ }
++
++}
--- /dev/null
- package com.vaadin.tests.components.customfield;\r
- \r
- import java.util.HashMap;\r
- import java.util.Map;\r
- \r
- import com.vaadin.ui.CustomLayout;\r
- import com.vaadin.ui.Field;\r
- import com.vaadin.ui.Form;\r
- import com.vaadin.ui.Layout;\r
- \r
- /**\r
- * Form that displays its fields in the layout of another form.\r
- * \r
- * The fields are still logically part of this form even though they are in the\r
- * layout of the parent form. The embedded form itself is automatically hidden.\r
- * \r
- * TODO Known issue: any field factory creating an {@link EmbeddedForm}\r
- * (directly or indirectly) should re-use the field once it has been created to\r
- * avoid the creation of duplicate fields when e.g. setting the visible item\r
- * properties.\r
- */\r
- public class EmbeddedForm extends Form {\r
- private Form parentForm;\r
- private Map<Object, Field> fields = new HashMap<Object, Field>();\r
- \r
- /**\r
- * Create a form that places its fields in another {@link Form}.\r
- * \r
- * @param parentForm\r
- * form to which to embed the fields, not null\r
- */\r
- public EmbeddedForm(Form parentForm) {\r
- this.parentForm = parentForm;\r
- setVisible(false);\r
- }\r
- \r
- @Override\r
- protected void attachField(Object propertyId, Field field) {\r
- if (propertyId == null || field == null) {\r
- return;\r
- }\r
- \r
- Layout layout = parentForm.getLayout();\r
- \r
- Field oldField = fields.get(propertyId);\r
- if (oldField != null) {\r
- layout.removeComponent(oldField);\r
- }\r
- \r
- fields.put(propertyId, field);\r
- \r
- if (layout instanceof CustomLayout) {\r
- ((CustomLayout) layout).addComponent(field, propertyId.toString());\r
- } else {\r
- layout.addComponent(field);\r
- }\r
- }\r
- \r
- @Override\r
- public boolean removeItemProperty(Object id) {\r
- // remove the field from the parent layout if already added there\r
- parentForm.getLayout().removeComponent(fields.get(id));\r
- fields.remove(id);\r
- \r
- return super.removeItemProperty(id);\r
- }\r
++package com.vaadin.tests.components.customfield;
++
++import java.util.HashMap;
++import java.util.Map;
++
++import com.vaadin.ui.CustomLayout;
++import com.vaadin.ui.Field;
++import com.vaadin.ui.Form;
++import com.vaadin.ui.Layout;
++
++/**
++ * Form that displays its fields in the layout of another form.
++ *
++ * The fields are still logically part of this form even though they are in the
++ * layout of the parent form. The embedded form itself is automatically hidden.
++ *
++ * TODO Known issue: any field factory creating an {@link EmbeddedForm}
++ * (directly or indirectly) should re-use the field once it has been created to
++ * avoid the creation of duplicate fields when e.g. setting the visible item
++ * properties.
++ */
++public class EmbeddedForm extends Form {
++ private Form parentForm;
++ private Map<Object, Field> fields = new HashMap<Object, Field>();
++
++ /**
++ * Create a form that places its fields in another {@link Form}.
++ *
++ * @param parentForm
++ * form to which to embed the fields, not null
++ */
++ public EmbeddedForm(Form parentForm) {
++ this.parentForm = parentForm;
++ setVisible(false);
++ }
++
++ @Override
++ protected void attachField(Object propertyId, Field field) {
++ if (propertyId == null || field == null) {
++ return;
++ }
++
++ Layout layout = parentForm.getLayout();
++
++ Field oldField = fields.get(propertyId);
++ if (oldField != null) {
++ layout.removeComponent(oldField);
++ }
++
++ fields.put(propertyId, field);
++
++ if (layout instanceof CustomLayout) {
++ ((CustomLayout) layout).addComponent(field, propertyId.toString());
++ } else {
++ layout.addComponent(field);
++ }
++ }
++
++ @Override
++ public boolean removeItemProperty(Object id) {
++ // remove the field from the parent layout if already added there
++ parentForm.getLayout().removeComponent(fields.get(id));
++ fields.remove(id);
++
++ return super.removeItemProperty(id);
++ }
+}
- package com.vaadin.tests.components.datefield;\r
- \r
- import java.text.SimpleDateFormat;\r
- import java.util.Date;\r
- import java.util.Locale;\r
- \r
- import com.vaadin.data.Property.ValueChangeEvent;\r
- import com.vaadin.data.Property.ValueChangeListener;\r
- import com.vaadin.data.util.ObjectProperty;\r
- import com.vaadin.tests.components.TestBase;\r
- import com.vaadin.tests.util.Log;\r
- import com.vaadin.ui.Button;\r
- import com.vaadin.ui.Button.ClickEvent;\r
- import com.vaadin.ui.Button.ClickListener;\r
- import com.vaadin.ui.DateField;\r
- import com.vaadin.ui.Label;\r
- import com.vaadin.ui.Label.ContentMode;\r
- import com.vaadin.ui.PopupDateField;\r
- \r
- @SuppressWarnings("serial")\r
- public class DateFieldEmptyValid extends TestBase {\r
- \r
- private Log log;\r
- \r
- private MyDateField df;\r
- \r
- private SimpleDateFormat formatter = new SimpleDateFormat(\r
- "MMMM d, yyyy hh:mm:ss aaa", Locale.US);\r
- \r
- public class MyDateField extends PopupDateField {\r
- @Override\r
- public boolean isEmpty() {\r
- return super.isEmpty();\r
- }\r
- \r
- }\r
- \r
- @Override\r
- protected void setup() {\r
- addComponent(new Label("<br/><br/>", ContentMode.XHTML));\r
- log = new Log(8);\r
- addComponent(log);\r
- df = new MyDateField();\r
- df.setDebugId("DateField");\r
- df.setRequired(true);\r
- df.setLocale(new Locale("fi", "FI"));\r
- df.setValue(new Date(100000000000L));\r
- df.setImmediate(true);\r
- df.setResolution(DateField.RESOLUTION_DAY);\r
- df.addListener(new ValueChangeListener() {\r
- public void valueChange(ValueChangeEvent event) {\r
- log.log("Value changeEvent");\r
- checkEmpty();\r
- }\r
- });\r
- addComponent(df);\r
- checkEmpty();\r
- Button b = new Button("Clear date");\r
- b.setDebugId("clear");\r
- b.addListener(new ClickListener() {\r
- \r
- public void buttonClick(ClickEvent event) {\r
- log.log("Clearing date aka setValue(null)");\r
- df.setValue(null);\r
- }\r
- });\r
- addComponent(b);\r
- \r
- b = new Button("Set date to 4.5.1990");\r
- b.setDebugId("set4.5.1990");\r
- b.addListener(new ClickListener() {\r
- \r
- @SuppressWarnings("deprecation")\r
- public void buttonClick(ClickEvent event) {\r
- log.log("Setting new value to datefield (4.5.1990)");\r
- df.setValue(new Date(1990 - 1900, 5 - 1, 4));\r
- }\r
- });\r
- addComponent(b);\r
- \r
- b = new Button("Set date to 5.6.2000 using a property data source");\r
- b.addListener(new ClickListener() {\r
- \r
- @SuppressWarnings("deprecation")\r
- public void buttonClick(ClickEvent event) {\r
- log.log("Setting new object property (5.6.2000) to datefield");\r
- ObjectProperty<Date> dfProp = new ObjectProperty<Date>(\r
- new Date(2000 - 1900, 6 - 1, 5), Date.class);\r
- df.setPropertyDataSource(dfProp);\r
- }\r
- });\r
- b.setDebugId("set-by-ds");\r
- addComponent(b);\r
- \r
- b = new Button(\r
- "Set date to 27.8.2005 by changing a new property data source from null, ds attached before value setting.");\r
- b.setDebugId("set-via-ds");\r
- b.addListener(new ClickListener() {\r
- \r
- @SuppressWarnings("deprecation")\r
- public void buttonClick(ClickEvent event) {\r
- log.log("Setting object property (with value null) to datefield and set value of property to 27.8.2005");\r
- ObjectProperty<Date> dfProp = new ObjectProperty<Date>(null,\r
- Date.class);\r
- df.setPropertyDataSource(dfProp);\r
- dfProp.setValue(new Date(2005 - 1900, 8 - 1, 27));\r
- }\r
- });\r
- addComponent(b);\r
- \r
- b = new Button("Check value");\r
- b.setDebugId("check-value");\r
- b.addListener(new ClickListener() {\r
- public void buttonClick(ClickEvent event) {\r
- log.log("Checking state");\r
- checkEmpty();\r
- }\r
- });\r
- addComponent(b);\r
- }\r
- \r
- private void checkEmpty() {\r
- Object value = df.getValue();\r
- if (value instanceof Date) {\r
- value = formatter.format(df.getValue());\r
- }\r
- \r
- log.log("DateField value is now " + value);\r
- // log.log("DateField value is now " + df.getValue());\r
- log.log("isEmpty: " + df.isEmpty() + ", isValid: " + df.isValid());\r
- }\r
- \r
- @Override\r
- protected String getDescription() {\r
- return "Tests the isEmpty() and isValid() functionality of a DateField. The field is required and has no other validators."\r
- + "IsEmpty() should return true when the field is truly empty i.e. contains no text, no matter how the field has been made empty. If the field contains any text, isEmpty() should return false."\r
- + "IsValid() should in this case return true if the field is not empty and vice versa.";\r
- }\r
- \r
- @Override\r
- protected Integer getTicketNumber() {\r
- return 5277;\r
- }\r
- \r
- }\r
+ package com.vaadin.tests.components.datefield;
+
+ import java.text.SimpleDateFormat;
+ import java.util.Date;
+ import java.util.Locale;
+
+ import com.vaadin.data.Property.ValueChangeEvent;
+ import com.vaadin.data.Property.ValueChangeListener;
+ import com.vaadin.data.util.ObjectProperty;
+ import com.vaadin.tests.components.TestBase;
+ import com.vaadin.tests.util.Log;
+ import com.vaadin.ui.Button;
+ import com.vaadin.ui.Button.ClickEvent;
+ import com.vaadin.ui.Button.ClickListener;
+ import com.vaadin.ui.DateField;
+ import com.vaadin.ui.Label;
++import com.vaadin.ui.Label.ContentMode;
+ import com.vaadin.ui.PopupDateField;
+
+ @SuppressWarnings("serial")
+ public class DateFieldEmptyValid extends TestBase {
+
+ private Log log;
+
+ private MyDateField df;
+
+ private SimpleDateFormat formatter = new SimpleDateFormat(
+ "MMMM d, yyyy hh:mm:ss aaa", Locale.US);
+
+ public class MyDateField extends PopupDateField {
+ @Override
+ public boolean isEmpty() {
+ return super.isEmpty();
+ }
+
+ }
+
+ @Override
+ protected void setup() {
- addComponent(new Label("<br/><br/>", Label.CONTENT_XHTML));
++ addComponent(new Label("<br/><br/>", ContentMode.XHTML));
+ log = new Log(8);
+ addComponent(log);
+ df = new MyDateField();
+ df.setDebugId("DateField");
+ df.setRequired(true);
+ df.setLocale(new Locale("fi", "FI"));
+ df.setValue(new Date(100000000000L));
+ df.setImmediate(true);
+ df.setResolution(DateField.RESOLUTION_DAY);
+ df.addListener(new ValueChangeListener() {
+ public void valueChange(ValueChangeEvent event) {
+ log.log("Value changeEvent");
+ checkEmpty();
+ }
+ });
+ addComponent(df);
+ checkEmpty();
+ Button b = new Button("Clear date");
+ b.setDebugId("clear");
+ b.addListener(new ClickListener() {
+
+ public void buttonClick(ClickEvent event) {
+ log.log("Clearing date aka setValue(null)");
+ df.setValue(null);
+ }
+ });
+ addComponent(b);
+
+ b = new Button("Set date to 4.5.1990");
+ b.setDebugId("set4.5.1990");
+ b.addListener(new ClickListener() {
+
+ @SuppressWarnings("deprecation")
+ public void buttonClick(ClickEvent event) {
+ log.log("Setting new value to datefield (4.5.1990)");
+ df.setValue(new Date(1990 - 1900, 5 - 1, 4));
+ }
+ });
+ addComponent(b);
+
+ b = new Button("Set date to 5.6.2000 using a property data source");
+ b.addListener(new ClickListener() {
+
+ @SuppressWarnings("deprecation")
+ public void buttonClick(ClickEvent event) {
+ log.log("Setting new object property (5.6.2000) to datefield");
+ ObjectProperty<Date> dfProp = new ObjectProperty<Date>(
+ new Date(2000 - 1900, 6 - 1, 5), Date.class);
+ df.setPropertyDataSource(dfProp);
+ }
+ });
+ b.setDebugId("set-by-ds");
+ addComponent(b);
+
+ b = new Button(
+ "Set date to 27.8.2005 by changing a new property data source from null, ds attached before value setting.");
+ b.setDebugId("set-via-ds");
+ b.addListener(new ClickListener() {
+
+ @SuppressWarnings("deprecation")
+ public void buttonClick(ClickEvent event) {
+ log.log("Setting object property (with value null) to datefield and set value of property to 27.8.2005");
+ ObjectProperty<Date> dfProp = new ObjectProperty<Date>(null,
+ Date.class);
+ df.setPropertyDataSource(dfProp);
+ dfProp.setValue(new Date(2005 - 1900, 8 - 1, 27));
+ }
+ });
+ addComponent(b);
+
+ b = new Button("Check value");
+ b.setDebugId("check-value");
+ b.addListener(new ClickListener() {
+ public void buttonClick(ClickEvent event) {
+ log.log("Checking state");
+ checkEmpty();
+ }
+ });
+ addComponent(b);
+ }
+
+ private void checkEmpty() {
+ Object value = df.getValue();
+ if (value instanceof Date) {
+ value = formatter.format(df.getValue());
+ }
+
+ log.log("DateField value is now " + value);
+ // log.log("DateField value is now " + df.getValue());
+ log.log("isEmpty: " + df.isEmpty() + ", isValid: " + df.isValid());
+ }
+
+ @Override
+ protected String getDescription() {
+ return "Tests the isEmpty() and isValid() functionality of a DateField. The field is required and has no other validators."
+ + "IsEmpty() should return true when the field is truly empty i.e. contains no text, no matter how the field has been made empty. If the field contains any text, isEmpty() should return false."
+ + "IsValid() should in this case return true if the field is not empty and vice versa.";
+ }
+
+ @Override
+ protected Integer getTicketNumber() {
+ return 5277;
+ }
+
+ }
- package com.vaadin.tests.components.datefield;\r
- \r
- import java.sql.Date;\r
- \r
- import com.vaadin.tests.components.AbstractTestCase;\r
- import com.vaadin.ui.Alignment;\r
- import com.vaadin.ui.DateField;\r
- import com.vaadin.ui.DateField.Resolution;\r
- import com.vaadin.ui.GridLayout;\r
- import com.vaadin.ui.Root.LegacyWindow;\r
- \r
- public class DateFieldPopupOffScreen extends AbstractTestCase {\r
- \r
- @Override\r
- protected String getDescription() {\r
- return "Test for the popup position from a DateField. The popup should always be on-screen even if the DateField is close the the edge of the browser.";\r
- }\r
- \r
- @Override\r
- protected Integer getTicketNumber() {\r
- return 3639;\r
- }\r
- \r
- @Override\r
- public void init() {\r
- LegacyWindow mainWindow = new LegacyWindow(getClass().getName());\r
- \r
- GridLayout mainLayout = new GridLayout(3, 3);\r
- mainLayout.setSizeFull();\r
- \r
- DateField df;\r
- \r
- df = createDateField();\r
- mainLayout.addComponent(df, 2, 0);\r
- mainLayout.setComponentAlignment(df, Alignment.TOP_RIGHT);\r
- \r
- df = createDateField();\r
- mainLayout.addComponent(df, 2, 1);\r
- mainLayout.setComponentAlignment(df, Alignment.MIDDLE_RIGHT);\r
- \r
- df = createDateField();\r
- mainLayout.addComponent(df, 2, 2);\r
- mainLayout.setComponentAlignment(df, Alignment.BOTTOM_RIGHT);\r
- \r
- df = createDateField();\r
- mainLayout.addComponent(df, 0, 2);\r
- mainLayout.setComponentAlignment(df, Alignment.BOTTOM_LEFT);\r
- \r
- df = createDateField();\r
- mainLayout.addComponent(df, 1, 2);\r
- mainLayout.setComponentAlignment(df, Alignment.BOTTOM_CENTER);\r
- \r
- mainWindow.setContent(mainLayout);\r
- setMainWindow(mainWindow);\r
- }\r
- \r
- private DateField createDateField() {\r
- DateField df = new DateField();\r
- df.setResolution(Resolution.SECOND);\r
- df.setDescription("This is a long, multiline tooltip.<br/>It should always be on screen so it can be read.");\r
- df.setValue(new Date(1000000L));\r
- return df;\r
- }\r
- }\r
+ package com.vaadin.tests.components.datefield;
+
+ import java.sql.Date;
+
+ import com.vaadin.tests.components.AbstractTestCase;
+ import com.vaadin.ui.Alignment;
+ import com.vaadin.ui.DateField;
++import com.vaadin.ui.DateField.Resolution;
+ import com.vaadin.ui.GridLayout;
-import com.vaadin.ui.Window;
++import com.vaadin.ui.Root.LegacyWindow;
+
+ public class DateFieldPopupOffScreen extends AbstractTestCase {
+
+ @Override
+ protected String getDescription() {
+ return "Test for the popup position from a DateField. The popup should always be on-screen even if the DateField is close the the edge of the browser.";
+ }
+
+ @Override
+ protected Integer getTicketNumber() {
+ return 3639;
+ }
+
+ @Override
+ public void init() {
- Window mainWindow = new Window(getClass().getName());
++ LegacyWindow mainWindow = new LegacyWindow(getClass().getName());
+
+ GridLayout mainLayout = new GridLayout(3, 3);
+ mainLayout.setSizeFull();
+
+ DateField df;
+
+ df = createDateField();
+ mainLayout.addComponent(df, 2, 0);
+ mainLayout.setComponentAlignment(df, Alignment.TOP_RIGHT);
+
+ df = createDateField();
+ mainLayout.addComponent(df, 2, 1);
+ mainLayout.setComponentAlignment(df, Alignment.MIDDLE_RIGHT);
+
+ df = createDateField();
+ mainLayout.addComponent(df, 2, 2);
+ mainLayout.setComponentAlignment(df, Alignment.BOTTOM_RIGHT);
+
+ df = createDateField();
+ mainLayout.addComponent(df, 0, 2);
+ mainLayout.setComponentAlignment(df, Alignment.BOTTOM_LEFT);
+
+ df = createDateField();
+ mainLayout.addComponent(df, 1, 2);
+ mainLayout.setComponentAlignment(df, Alignment.BOTTOM_CENTER);
+
+ mainWindow.setContent(mainLayout);
+ setMainWindow(mainWindow);
+ }
+
+ private DateField createDateField() {
+ DateField df = new DateField();
++ df.setResolution(Resolution.SECOND);
+ df.setDescription("This is a long, multiline tooltip.<br/>It should always be on screen so it can be read.");
+ df.setValue(new Date(1000000L));
+ return df;
+ }
+ }
--- /dev/null
- package com.vaadin.tests.components.datefield;\r
- \r
- import java.util.Date;\r
- import java.util.Locale;\r
- \r
- import com.vaadin.data.Property.ValueChangeEvent;\r
- import com.vaadin.data.Property.ValueChangeListener;\r
- import com.vaadin.data.util.BeanItem;\r
- import com.vaadin.data.validator.RangeValidator;\r
- import com.vaadin.tests.components.TestBase;\r
- import com.vaadin.ui.CheckBox;\r
- import com.vaadin.ui.DateField.Resolution;\r
- import com.vaadin.ui.PopupDateField;\r
- \r
- public class DateFieldRangeValidation extends TestBase {\r
- \r
- public class Range {\r
- private Date from, to;\r
- private boolean fromInclusive = true;\r
- private boolean toInclusive = true;\r
- \r
- public boolean isFromInclusive() {\r
- return fromInclusive;\r
- }\r
- \r
- public void setFromInclusive(boolean fromInclusive) {\r
- this.fromInclusive = fromInclusive;\r
- }\r
- \r
- public boolean isToInclusive() {\r
- return toInclusive;\r
- }\r
- \r
- public void setToInclusive(boolean toInclusive) {\r
- this.toInclusive = toInclusive;\r
- }\r
- \r
- public Date getFrom() {\r
- return from;\r
- }\r
- \r
- public void setFrom(Date from) {\r
- this.from = from;\r
- }\r
- \r
- public Date getTo() {\r
- return to;\r
- }\r
- \r
- public void setTo(Date to) {\r
- this.to = to;\r
- }\r
- \r
- }\r
- \r
- private Range range = new Range();\r
- private ValueChangeListener refreshField = new ValueChangeListener() {\r
- \r
- public void valueChange(ValueChangeEvent event) {\r
- actualDateField.requestRepaint();\r
- }\r
- };\r
- \r
- private PopupDateField actualDateField;\r
- \r
- @Override\r
- protected void setup() {\r
- BeanItem<Range> bi = new BeanItem<Range>(range);\r
- range.setFrom(new Date(2011 - 1900, 12 - 1, 4));\r
- range.setTo(new Date(2011 - 1900, 12 - 1, 15));\r
- \r
- PopupDateField fromField = createDateField();\r
- fromField.setPropertyDataSource(bi.getItemProperty("from"));\r
- CheckBox fromInclusive = new CheckBox("From inclusive",\r
- bi.getItemProperty("fromInclusive"));\r
- CheckBox toInclusive = new CheckBox("To inclusive",\r
- bi.getItemProperty("toInclusive"));\r
- fromInclusive.setImmediate(true);\r
- fromInclusive.addListener(refreshField);\r
- toInclusive.setImmediate(true);\r
- toInclusive.addListener(refreshField);\r
- \r
- PopupDateField toField = createDateField();\r
- toField.setPropertyDataSource(bi.getItemProperty("to"));\r
- \r
- actualDateField = createDateField();\r
- actualDateField.setValue(new Date(2011 - 1900, 12 - 1, 1));\r
- actualDateField.addValidator(new RangeValidator<Date>("", Date.class,\r
- null, null) {\r
- @Override\r
- public boolean isMinValueIncluded() {\r
- return range.isFromInclusive();\r
- }\r
- \r
- @Override\r
- public boolean isMaxValueIncluded() {\r
- return range.isToInclusive();\r
- }\r
- \r
- @Override\r
- public Date getMaxValue() {\r
- return range.getTo();\r
- }\r
- \r
- @Override\r
- public Date getMinValue() {\r
- return range.getFrom();\r
- }\r
- \r
- @Override\r
- public String getErrorMessage() {\r
- return "Date must be in range " + getMinValue() + " - "\r
- + getMaxValue();\r
- }\r
- });\r
- addComponent(fromField);\r
- addComponent(fromInclusive);\r
- addComponent(toField);\r
- addComponent(toInclusive);\r
- addComponent(actualDateField);\r
- }\r
- \r
- private PopupDateField createDateField() {\r
- PopupDateField df = new PopupDateField();\r
- df.setLocale(new Locale("en", "US"));\r
- df.setResolution(Resolution.DAY);\r
- df.setWriteThrough(true);\r
- df.setReadThrough(true);\r
- df.setImmediate(true);\r
- return df;\r
- }\r
- \r
- @Override\r
- protected String getDescription() {\r
- return "Tests the DateField range validator. The first field sets the minimum date, the second the maximum. Checkboxes control if the selected date is ok or not.";\r
- }\r
- \r
- @Override\r
- protected Integer getTicketNumber() {\r
- // TODO Auto-generated method stub\r
- return null;\r
- }\r
- \r
- }\r
++package com.vaadin.tests.components.datefield;
++
++import java.util.Date;
++import java.util.Locale;
++
++import com.vaadin.data.Property.ValueChangeEvent;
++import com.vaadin.data.Property.ValueChangeListener;
++import com.vaadin.data.util.BeanItem;
++import com.vaadin.data.validator.RangeValidator;
++import com.vaadin.tests.components.TestBase;
++import com.vaadin.ui.CheckBox;
++import com.vaadin.ui.DateField.Resolution;
++import com.vaadin.ui.PopupDateField;
++
++public class DateFieldRangeValidation extends TestBase {
++
++ public class Range {
++ private Date from, to;
++ private boolean fromInclusive = true;
++ private boolean toInclusive = true;
++
++ public boolean isFromInclusive() {
++ return fromInclusive;
++ }
++
++ public void setFromInclusive(boolean fromInclusive) {
++ this.fromInclusive = fromInclusive;
++ }
++
++ public boolean isToInclusive() {
++ return toInclusive;
++ }
++
++ public void setToInclusive(boolean toInclusive) {
++ this.toInclusive = toInclusive;
++ }
++
++ public Date getFrom() {
++ return from;
++ }
++
++ public void setFrom(Date from) {
++ this.from = from;
++ }
++
++ public Date getTo() {
++ return to;
++ }
++
++ public void setTo(Date to) {
++ this.to = to;
++ }
++
++ }
++
++ private Range range = new Range();
++ private ValueChangeListener refreshField = new ValueChangeListener() {
++
++ public void valueChange(ValueChangeEvent event) {
++ actualDateField.requestRepaint();
++ }
++ };
++
++ private PopupDateField actualDateField;
++
++ @Override
++ protected void setup() {
++ BeanItem<Range> bi = new BeanItem<Range>(range);
++ range.setFrom(new Date(2011 - 1900, 12 - 1, 4));
++ range.setTo(new Date(2011 - 1900, 12 - 1, 15));
++
++ PopupDateField fromField = createDateField();
++ fromField.setPropertyDataSource(bi.getItemProperty("from"));
++ CheckBox fromInclusive = new CheckBox("From inclusive",
++ bi.getItemProperty("fromInclusive"));
++ CheckBox toInclusive = new CheckBox("To inclusive",
++ bi.getItemProperty("toInclusive"));
++ fromInclusive.setImmediate(true);
++ fromInclusive.addListener(refreshField);
++ toInclusive.setImmediate(true);
++ toInclusive.addListener(refreshField);
++
++ PopupDateField toField = createDateField();
++ toField.setPropertyDataSource(bi.getItemProperty("to"));
++
++ actualDateField = createDateField();
++ actualDateField.setValue(new Date(2011 - 1900, 12 - 1, 1));
++ actualDateField.addValidator(new RangeValidator<Date>("", Date.class,
++ null, null) {
++ @Override
++ public boolean isMinValueIncluded() {
++ return range.isFromInclusive();
++ }
++
++ @Override
++ public boolean isMaxValueIncluded() {
++ return range.isToInclusive();
++ }
++
++ @Override
++ public Date getMaxValue() {
++ return range.getTo();
++ }
++
++ @Override
++ public Date getMinValue() {
++ return range.getFrom();
++ }
++
++ @Override
++ public String getErrorMessage() {
++ return "Date must be in range " + getMinValue() + " - "
++ + getMaxValue();
++ }
++ });
++ addComponent(fromField);
++ addComponent(fromInclusive);
++ addComponent(toField);
++ addComponent(toInclusive);
++ addComponent(actualDateField);
++ }
++
++ private PopupDateField createDateField() {
++ PopupDateField df = new PopupDateField();
++ df.setLocale(new Locale("en", "US"));
++ df.setResolution(Resolution.DAY);
++ df.setWriteThrough(true);
++ df.setReadThrough(true);
++ df.setImmediate(true);
++ return df;
++ }
++
++ @Override
++ protected String getDescription() {
++ return "Tests the DateField range validator. The first field sets the minimum date, the second the maximum. Checkboxes control if the selected date is ok or not.";
++ }
++
++ @Override
++ protected Integer getTicketNumber() {
++ // TODO Auto-generated method stub
++ return null;
++ }
++
++}
- package com.vaadin.tests.components.datefield;\r
- \r
- import java.text.DateFormat;\r
- import java.text.SimpleDateFormat;\r
- import java.util.Calendar;\r
- import java.util.Date;\r
- import java.util.LinkedHashMap;\r
- import java.util.Locale;\r
- \r
- import com.vaadin.tests.components.abstractfield.AbstractFieldTest;\r
- import com.vaadin.ui.DateField;\r
- import com.vaadin.ui.DateField.Resolution;\r
- \r
- public class DateFieldTest<T extends DateField> extends AbstractFieldTest<T> {\r
- \r
- @SuppressWarnings("unchecked")\r
- @Override\r
- protected Class<T> getTestClass() {\r
- return (Class<T>) DateField.class;\r
- }\r
- \r
- private Command<T, Date> setValue = new Command<T, Date>() {\r
- \r
- public void execute(T c, Date value, Object data) {\r
- c.setValue(value);\r
- }\r
- };\r
- \r
- @Override\r
- protected void createActions() {\r
- super.createActions();\r
- createResolutionSelectAction(CATEGORY_FEATURES);\r
- createBooleanAction("Lenient", CATEGORY_FEATURES, false, lenientCommand);\r
- createBooleanAction("Show week numbers", CATEGORY_FEATURES, false,\r
- weekNumberCommand);\r
- createDateFormatSelectAction(CATEGORY_FEATURES);\r
- createSetValueAction(CATEGORY_FEATURES);\r
- \r
- };\r
- \r
- private void createSetValueAction(String category) {\r
- LinkedHashMap<String, Date> options = new LinkedHashMap<String, Date>();\r
- options.put("(null)", null);\r
- options.put("(current time)", new Date());\r
- Calendar c = Calendar.getInstance(new Locale("fi", "FI"));\r
- c.clear();\r
- c.set(2010, 12 - 1, 12, 12, 0, 0);\r
- c.set(Calendar.MILLISECOND, 0);\r
- options.put("2010-12-12 12:00:00.000", c.getTime());\r
- c.clear();\r
- c.set(2000, 1 - 1, 2, 3, 4, 5);\r
- c.set(Calendar.MILLISECOND, 6);\r
- options.put("2000-01-02 03:04:05.006", c.getTime());\r
- createMultiClickAction("Set value", category, options, setValue, null);\r
- }\r
- \r
- private void createDateFormatSelectAction(String category) {\r
- LinkedHashMap<String, String> options = new LinkedHashMap<String, String>();\r
- \r
- options.put("-", null);\r
- options.put("d M yyyy", "d M yyyy");\r
- options.put("d MM yyyy", "d MM yyyy");\r
- options.put("d MMM yyyy", "d MMM yyyy");\r
- options.put("d MMMM yyyy", "d MMMM yyyy");\r
- options.put("dd M yyyy", "dd M yyyy");\r
- options.put("ddd M yyyy", "ddd M yyyy");\r
- options.put("d M y", "d M y");\r
- options.put("d M yy", "d M yy");\r
- options.put("d M yyy", "d M yyy");\r
- options.put("d M yyyy", "d M yyyy");\r
- options.put("d M 'custom text' yyyy", "d M 'custom text' yyyy");\r
- options.put("'day:'d', month:'M', year: 'yyyy",\r
- "'day:'d', month:'M', year: 'yyyy");\r
- options.put(getDatePattern(new Locale("fi", "FI"), DateFormat.LONG),\r
- getDatePattern(new Locale("fi", "FI"), DateFormat.LONG));\r
- options.put(getDatePattern(new Locale("fi", "FI"), DateFormat.MEDIUM),\r
- getDatePattern(new Locale("fi", "FI"), DateFormat.MEDIUM));\r
- options.put(getDatePattern(new Locale("fi", "FI"), DateFormat.SHORT),\r
- getDatePattern(new Locale("fi", "FI"), DateFormat.SHORT));\r
- \r
- createSelectAction("Date format", category, options, "-",\r
- dateFormatCommand);\r
- \r
- }\r
- \r
- private String getDatePattern(Locale locale, int dateStyle) {\r
- DateFormat dateFormat = DateFormat.getDateInstance(dateStyle, locale);\r
- \r
- if (dateFormat instanceof SimpleDateFormat) {\r
- String pattern = ((SimpleDateFormat) dateFormat).toPattern();\r
- return pattern;\r
- }\r
- return null;\r
- \r
- }\r
- \r
- private void createResolutionSelectAction(String category) {\r
- LinkedHashMap<String, Resolution> options = new LinkedHashMap<String, Resolution>();\r
- options.put("Year", DateField.Resolution.YEAR);\r
- options.put("Month", DateField.Resolution.MONTH);\r
- options.put("Day", DateField.Resolution.DAY);\r
- options.put("Hour", DateField.Resolution.HOUR);\r
- options.put("Min", DateField.Resolution.MINUTE);\r
- options.put("Sec", DateField.Resolution.SECOND);\r
- \r
- createSelectAction("Resolution", category, options, "Year",\r
- resolutionCommand);\r
- }\r
- \r
- private Command<T, Resolution> resolutionCommand = new Command<T, Resolution>() {\r
- \r
- public void execute(T c, Resolution value, Object data) {\r
- c.setResolution(value);\r
- \r
- }\r
- };\r
- private Command<T, Boolean> lenientCommand = new Command<T, Boolean>() {\r
- \r
- public void execute(T c, Boolean value, Object data) {\r
- c.setLenient(false);\r
- \r
- }\r
- };\r
- private Command<T, Boolean> weekNumberCommand = new Command<T, Boolean>() {\r
- \r
- public void execute(T c, Boolean value, Object data) {\r
- c.setShowISOWeekNumbers(value);\r
- \r
- }\r
- };\r
- private Command<T, String> dateFormatCommand = new Command<T, String>() {\r
- \r
- public void execute(T c, String value, Object data) {\r
- c.setDateFormat(value);\r
- }\r
- };\r
- \r
- }\r
+ package com.vaadin.tests.components.datefield;
+
+ import java.text.DateFormat;
+ import java.text.SimpleDateFormat;
+ import java.util.Calendar;
+ import java.util.Date;
+ import java.util.LinkedHashMap;
+ import java.util.Locale;
+
+ import com.vaadin.tests.components.abstractfield.AbstractFieldTest;
+ import com.vaadin.ui.DateField;
++import com.vaadin.ui.DateField.Resolution;
+
+ public class DateFieldTest<T extends DateField> extends AbstractFieldTest<T> {
+
++ @SuppressWarnings("unchecked")
+ @Override
+ protected Class<T> getTestClass() {
+ return (Class<T>) DateField.class;
+ }
+
+ private Command<T, Date> setValue = new Command<T, Date>() {
+
+ public void execute(T c, Date value, Object data) {
+ c.setValue(value);
+ }
+ };
+
+ @Override
+ protected void createActions() {
+ super.createActions();
+ createResolutionSelectAction(CATEGORY_FEATURES);
+ createBooleanAction("Lenient", CATEGORY_FEATURES, false, lenientCommand);
+ createBooleanAction("Show week numbers", CATEGORY_FEATURES, false,
+ weekNumberCommand);
+ createDateFormatSelectAction(CATEGORY_FEATURES);
+ createSetValueAction(CATEGORY_FEATURES);
+
+ };
+
+ private void createSetValueAction(String category) {
+ LinkedHashMap<String, Date> options = new LinkedHashMap<String, Date>();
+ options.put("(null)", null);
+ options.put("(current time)", new Date());
+ Calendar c = Calendar.getInstance(new Locale("fi", "FI"));
+ c.clear();
+ c.set(2010, 12 - 1, 12, 12, 0, 0);
+ c.set(Calendar.MILLISECOND, 0);
+ options.put("2010-12-12 12:00:00.000", c.getTime());
+ c.clear();
+ c.set(2000, 1 - 1, 2, 3, 4, 5);
+ c.set(Calendar.MILLISECOND, 6);
+ options.put("2000-01-02 03:04:05.006", c.getTime());
+ createMultiClickAction("Set value", category, options, setValue, null);
+ }
+
+ private void createDateFormatSelectAction(String category) {
+ LinkedHashMap<String, String> options = new LinkedHashMap<String, String>();
+
+ options.put("-", null);
+ options.put("d M yyyy", "d M yyyy");
+ options.put("d MM yyyy", "d MM yyyy");
+ options.put("d MMM yyyy", "d MMM yyyy");
+ options.put("d MMMM yyyy", "d MMMM yyyy");
+ options.put("dd M yyyy", "dd M yyyy");
+ options.put("ddd M yyyy", "ddd M yyyy");
+ options.put("d M y", "d M y");
+ options.put("d M yy", "d M yy");
+ options.put("d M yyy", "d M yyy");
+ options.put("d M yyyy", "d M yyyy");
+ options.put("d M 'custom text' yyyy", "d M 'custom text' yyyy");
+ options.put("'day:'d', month:'M', year: 'yyyy",
+ "'day:'d', month:'M', year: 'yyyy");
+ options.put(getDatePattern(new Locale("fi", "FI"), DateFormat.LONG),
+ getDatePattern(new Locale("fi", "FI"), DateFormat.LONG));
+ options.put(getDatePattern(new Locale("fi", "FI"), DateFormat.MEDIUM),
+ getDatePattern(new Locale("fi", "FI"), DateFormat.MEDIUM));
+ options.put(getDatePattern(new Locale("fi", "FI"), DateFormat.SHORT),
+ getDatePattern(new Locale("fi", "FI"), DateFormat.SHORT));
+
+ createSelectAction("Date format", category, options, "-",
+ dateFormatCommand);
+
+ }
+
+ private String getDatePattern(Locale locale, int dateStyle) {
+ DateFormat dateFormat = DateFormat.getDateInstance(dateStyle, locale);
+
+ if (dateFormat instanceof SimpleDateFormat) {
+ String pattern = ((SimpleDateFormat) dateFormat).toPattern();
+ return pattern;
+ }
+ return null;
+
+ }
+
+ private void createResolutionSelectAction(String category) {
- LinkedHashMap<String, Integer> options = new LinkedHashMap<String, Integer>();
- options.put("Year", DateField.RESOLUTION_YEAR);
- options.put("Month", DateField.RESOLUTION_MONTH);
- options.put("Day", DateField.RESOLUTION_DAY);
- options.put("Hour", DateField.RESOLUTION_HOUR);
- options.put("Min", DateField.RESOLUTION_MIN);
- options.put("Sec", DateField.RESOLUTION_SEC);
- options.put("Msec", DateField.RESOLUTION_MSEC);
++ LinkedHashMap<String, Resolution> options = new LinkedHashMap<String, Resolution>();
++ options.put("Year", DateField.Resolution.YEAR);
++ options.put("Month", DateField.Resolution.MONTH);
++ options.put("Day", DateField.Resolution.DAY);
++ options.put("Hour", DateField.Resolution.HOUR);
++ options.put("Min", DateField.Resolution.MINUTE);
++ options.put("Sec", DateField.Resolution.SECOND);
+
+ createSelectAction("Resolution", category, options, "Year",
+ resolutionCommand);
+ }
+
- private Command<T, Integer> resolutionCommand = new Command<T, Integer>() {
++ private Command<T, Resolution> resolutionCommand = new Command<T, Resolution>() {
+
- public void execute(T c, Integer value, Object data) {
++ public void execute(T c, Resolution value, Object data) {
+ c.setResolution(value);
+
+ }
+ };
+ private Command<T, Boolean> lenientCommand = new Command<T, Boolean>() {
+
+ public void execute(T c, Boolean value, Object data) {
+ c.setLenient(false);
+
+ }
+ };
+ private Command<T, Boolean> weekNumberCommand = new Command<T, Boolean>() {
+
+ public void execute(T c, Boolean value, Object data) {
+ c.setShowISOWeekNumbers(value);
+
+ }
+ };
+ private Command<T, String> dateFormatCommand = new Command<T, String>() {
+
+ public void execute(T c, String value, Object data) {
+ c.setDateFormat(value);
+ }
+ };
+
+ }
- package com.vaadin.tests.components.datefield;\r
- \r
- import java.util.Date;\r
- \r
- import com.vaadin.data.Property;\r
- import com.vaadin.data.util.converter.Converter;\r
- import com.vaadin.tests.components.TestBase;\r
- import com.vaadin.ui.DateField;\r
- \r
- public class DateFieldUnparsableDate extends TestBase {\r
- \r
- public class MyDateField extends DateField {\r
- Date oldDate = null;\r
- \r
- public MyDateField(String caption) {\r
- super(caption);\r
- addListener(new Property.ValueChangeListener() {\r
- public void valueChange(\r
- com.vaadin.data.Property.ValueChangeEvent event) {\r
- oldDate = getValue();\r
- }\r
- });\r
- }\r
- \r
- @Override\r
- protected Date handleUnparsableDateString(String dateString)\r
- throws Converter.ConversionException {\r
- return oldDate;\r
- }\r
- }\r
- \r
- public class MyDateField2 extends DateField {\r
- public MyDateField2(String caption) {\r
- super(caption);\r
- }\r
- \r
- @Override\r
- protected Date handleUnparsableDateString(String dateString)\r
- throws Converter.ConversionException {\r
- return null;\r
- }\r
- }\r
- \r
- public class MyDateField3 extends DateField {\r
- public MyDateField3(String caption) {\r
- super(caption);\r
- }\r
- \r
- @Override\r
- protected Date handleUnparsableDateString(String dateString)\r
- throws Converter.ConversionException {\r
- throw new Converter.ConversionException(\r
- "You should not enter invalid dates!");\r
- }\r
- }\r
- \r
- public class MyDateField4 extends DateField {\r
- public MyDateField4(String caption) {\r
- super(caption);\r
- }\r
- \r
- @Override\r
- protected Date handleUnparsableDateString(String dateString)\r
- throws Converter.ConversionException {\r
- if (dateString != null && dateString.equals("today")) {\r
- return new Date();\r
- }\r
- throw new Converter.ConversionException(\r
- "You should not enter invalid dates!");\r
- }\r
- }\r
- \r
- @Override\r
- protected void setup() {\r
- MyDateField df = new MyDateField(\r
- "Returns the old value for invalid dates");\r
- df.setImmediate(true);\r
- addComponent(df);\r
- \r
- MyDateField2 df2 = new MyDateField2("Returns empty for invalid dates");\r
- df2.setImmediate(true);\r
- addComponent(df2);\r
- \r
- MyDateField3 df3 = new MyDateField3(\r
- "Throws an exception for invalid dates");\r
- df3.setImmediate(true);\r
- addComponent(df3);\r
- \r
- MyDateField4 df4 = new MyDateField4("Can convert 'today'");\r
- df4.setImmediate(true);\r
- addComponent(df4);\r
- \r
- }\r
- \r
- @Override\r
- protected String getDescription() {\r
- return "DateFields in various configurations (according to caption). All handle unparsable dates differently";\r
- }\r
- \r
- @Override\r
- protected Integer getTicketNumber() {\r
- return 4236;\r
- }\r
- }\r
+ package com.vaadin.tests.components.datefield;
+
+ import java.util.Date;
+
+ import com.vaadin.data.Property;
++import com.vaadin.data.util.converter.Converter;
+ import com.vaadin.tests.components.TestBase;
+ import com.vaadin.ui.DateField;
+
+ public class DateFieldUnparsableDate extends TestBase {
+
+ public class MyDateField extends DateField {
+ Date oldDate = null;
+
+ public MyDateField(String caption) {
+ super(caption);
+ addListener(new Property.ValueChangeListener() {
+ public void valueChange(
+ com.vaadin.data.Property.ValueChangeEvent event) {
- oldDate = (Date) getValue();
++ oldDate = getValue();
+ }
+ });
+ }
+
+ @Override
+ protected Date handleUnparsableDateString(String dateString)
- throws ConversionException {
++ throws Converter.ConversionException {
+ return oldDate;
+ }
+ }
+
+ public class MyDateField2 extends DateField {
+ public MyDateField2(String caption) {
+ super(caption);
+ }
+
+ @Override
+ protected Date handleUnparsableDateString(String dateString)
- throws ConversionException {
++ throws Converter.ConversionException {
+ return null;
+ }
+ }
+
+ public class MyDateField3 extends DateField {
+ public MyDateField3(String caption) {
+ super(caption);
+ }
+
+ @Override
+ protected Date handleUnparsableDateString(String dateString)
- throws ConversionException {
- throw new ConversionException("You should not enter invalid dates!");
++ throws Converter.ConversionException {
++ throw new Converter.ConversionException(
++ "You should not enter invalid dates!");
+ }
+ }
+
+ public class MyDateField4 extends DateField {
+ public MyDateField4(String caption) {
+ super(caption);
+ }
+
+ @Override
+ protected Date handleUnparsableDateString(String dateString)
- throws ConversionException {
++ throws Converter.ConversionException {
+ if (dateString != null && dateString.equals("today")) {
+ return new Date();
+ }
- throw new ConversionException("You should not enter invalid dates!");
++ throw new Converter.ConversionException(
++ "You should not enter invalid dates!");
+ }
+ }
+
+ @Override
+ protected void setup() {
+ MyDateField df = new MyDateField(
+ "Returns the old value for invalid dates");
+ df.setImmediate(true);
+ addComponent(df);
+
+ MyDateField2 df2 = new MyDateField2("Returns empty for invalid dates");
+ df2.setImmediate(true);
+ addComponent(df2);
+
+ MyDateField3 df3 = new MyDateField3(
+ "Throws an exception for invalid dates");
+ df3.setImmediate(true);
+ addComponent(df3);
+
+ MyDateField4 df4 = new MyDateField4("Can convert 'today'");
+ df4.setImmediate(true);
+ addComponent(df4);
+
+ }
+
+ @Override
+ protected String getDescription() {
+ return "DateFields in various configurations (according to caption). All handle unparsable dates differently";
+ }
+
+ @Override
+ protected Integer getTicketNumber() {
+ return 4236;
+ }
+ }
- package com.vaadin.tests.components.datefield;\r
- \r
- import java.sql.Date;\r
- import java.util.LinkedHashMap;\r
- import java.util.List;\r
- import java.util.Locale;\r
- \r
- import com.vaadin.tests.components.ComponentTestCase;\r
- import com.vaadin.ui.Component;\r
- import com.vaadin.ui.DateField;\r
- import com.vaadin.ui.DateField.Resolution;\r
- import com.vaadin.ui.InlineDateField;\r
- \r
- @SuppressWarnings("serial")\r
- public class InlineDateFields extends ComponentTestCase<InlineDateField> {\r
- \r
- private static final Locale[] LOCALES = new Locale[] { Locale.US,\r
- Locale.TAIWAN, new Locale("fi", "FI") };\r
- \r
- @Override\r
- protected Class<InlineDateField> getTestClass() {\r
- return InlineDateField.class;\r
- }\r
- \r
- @Override\r
- protected void initializeComponents() {\r
- \r
- Locale locale = LOCALES[0];\r
- \r
- InlineDateField pd = createInlineDateField("Undefined width", "-1",\r
- locale);\r
- pd.setDebugId("Locale-" + locale.toString() + "-undefined-wide");\r
- addTestComponent(pd);\r
- pd = createInlineDateField("300px width", "300px", locale);\r
- pd.setDebugId("Locale-" + locale.toString() + "-300px-wide");\r
- addTestComponent(pd);\r
- pd = createInlineDateField("Initially empty", "", locale);\r
- pd.setValue(null);\r
- pd.setDebugId("Locale-" + locale.toString() + "-initially-empty");\r
- addTestComponent(pd);\r
- \r
- }\r
- \r
- private InlineDateField createInlineDateField(String caption, String width,\r
- Locale locale) {\r
- InlineDateField pd = new InlineDateField(caption + "("\r
- + locale.toString() + ")");\r
- pd.setWidth(width);\r
- pd.setValue(new Date(12312312313L));\r
- pd.setLocale(locale);\r
- pd.setResolution(DateField.Resolution.YEAR);\r
- \r
- return pd;\r
- }\r
- \r
- @Override\r
- protected String getDescription() {\r
- return "A generic test for InlineDateFields in different configurations";\r
- }\r
- \r
- @Override\r
- protected List<Component> createActions() {\r
- List<Component> actions = super.createActions();\r
- actions.add(createResolutionSelectAction());\r
- actions.add(createLocaleSelectAction());\r
- return actions;\r
- }\r
- \r
- private Component createResolutionSelectAction() {\r
- LinkedHashMap<String, Resolution> options = new LinkedHashMap<String, Resolution>();\r
- options.put("Year", DateField.Resolution.YEAR);\r
- options.put("Month", DateField.Resolution.MONTH);\r
- options.put("Day", DateField.Resolution.DAY);\r
- options.put("Hour", DateField.Resolution.HOUR);\r
- options.put("Min", DateField.Resolution.MINUTE);\r
- options.put("Sec", DateField.Resolution.SECOND);\r
- return createSelectAction("Resolution", options, "Year",\r
- new Command<InlineDateField, Resolution>() {\r
- \r
- public void execute(InlineDateField c, Resolution value,\r
- Object data) {\r
- c.setResolution(value);\r
- \r
- }\r
- });\r
- }\r
- \r
- private Component createLocaleSelectAction() {\r
- LinkedHashMap<String, Locale> options = new LinkedHashMap<String, Locale>();\r
- for (Locale locale : LOCALES) {\r
- options.put(locale.toString(), locale);\r
- }\r
- return createSelectAction("Locale", options, LOCALES[0].toString(),\r
- new Command<InlineDateField, Locale>() {\r
- \r
- public void execute(InlineDateField c, Locale value,\r
- Object data) {\r
- c.setCaption(c.getCaption().replaceAll(\r
- c.getLocale().toString(), value.toString()));\r
- c.setLocale(value);\r
- \r
- }\r
- });\r
- }\r
- \r
- }\r
+ package com.vaadin.tests.components.datefield;
+
+ import java.sql.Date;
+ import java.util.LinkedHashMap;
+ import java.util.List;
+ import java.util.Locale;
+
+ import com.vaadin.tests.components.ComponentTestCase;
+ import com.vaadin.ui.Component;
+ import com.vaadin.ui.DateField;
++import com.vaadin.ui.DateField.Resolution;
+ import com.vaadin.ui.InlineDateField;
+
+ @SuppressWarnings("serial")
+ public class InlineDateFields extends ComponentTestCase<InlineDateField> {
+
+ private static final Locale[] LOCALES = new Locale[] { Locale.US,
+ Locale.TAIWAN, new Locale("fi", "FI") };
+
+ @Override
+ protected Class<InlineDateField> getTestClass() {
+ return InlineDateField.class;
+ }
+
+ @Override
+ protected void initializeComponents() {
+
+ Locale locale = LOCALES[0];
+
+ InlineDateField pd = createInlineDateField("Undefined width", "-1",
+ locale);
+ pd.setDebugId("Locale-" + locale.toString() + "-undefined-wide");
+ addTestComponent(pd);
+ pd = createInlineDateField("300px width", "300px", locale);
+ pd.setDebugId("Locale-" + locale.toString() + "-300px-wide");
+ addTestComponent(pd);
+ pd = createInlineDateField("Initially empty", "", locale);
+ pd.setValue(null);
+ pd.setDebugId("Locale-" + locale.toString() + "-initially-empty");
+ addTestComponent(pd);
+
+ }
+
+ private InlineDateField createInlineDateField(String caption, String width,
+ Locale locale) {
+ InlineDateField pd = new InlineDateField(caption + "("
+ + locale.toString() + ")");
+ pd.setWidth(width);
+ pd.setValue(new Date(12312312313L));
+ pd.setLocale(locale);
- pd.setResolution(DateField.RESOLUTION_YEAR);
++ pd.setResolution(DateField.Resolution.YEAR);
+
+ return pd;
+ }
+
+ @Override
+ protected String getDescription() {
+ return "A generic test for InlineDateFields in different configurations";
+ }
+
+ @Override
+ protected List<Component> createActions() {
+ List<Component> actions = super.createActions();
+ actions.add(createResolutionSelectAction());
+ actions.add(createLocaleSelectAction());
+ return actions;
+ }
+
+ private Component createResolutionSelectAction() {
- LinkedHashMap<String, Integer> options = new LinkedHashMap<String, Integer>();
- options.put("Year", DateField.RESOLUTION_YEAR);
- options.put("Month", DateField.RESOLUTION_MONTH);
- options.put("Day", DateField.RESOLUTION_DAY);
- options.put("Hour", DateField.RESOLUTION_HOUR);
- options.put("Min", DateField.RESOLUTION_MIN);
- options.put("Sec", DateField.RESOLUTION_SEC);
- options.put("Msec", DateField.RESOLUTION_MSEC);
++ LinkedHashMap<String, Resolution> options = new LinkedHashMap<String, Resolution>();
++ options.put("Year", DateField.Resolution.YEAR);
++ options.put("Month", DateField.Resolution.MONTH);
++ options.put("Day", DateField.Resolution.DAY);
++ options.put("Hour", DateField.Resolution.HOUR);
++ options.put("Min", DateField.Resolution.MINUTE);
++ options.put("Sec", DateField.Resolution.SECOND);
+ return createSelectAction("Resolution", options, "Year",
- new Command<InlineDateField, Integer>() {
++ new Command<InlineDateField, Resolution>() {
+
- public void execute(InlineDateField c, Integer value,
++ public void execute(InlineDateField c, Resolution value,
+ Object data) {
+ c.setResolution(value);
+
+ }
+ });
+ }
+
+ private Component createLocaleSelectAction() {
+ LinkedHashMap<String, Locale> options = new LinkedHashMap<String, Locale>();
+ for (Locale locale : LOCALES) {
+ options.put(locale.toString(), locale);
+ }
+ return createSelectAction("Locale", options, LOCALES[0].toString(),
+ new Command<InlineDateField, Locale>() {
+
+ public void execute(InlineDateField c, Locale value,
+ Object data) {
+ c.setCaption(c.getCaption().replaceAll(
+ c.getLocale().toString(), value.toString()));
+ c.setLocale(value);
+
+ }
+ });
+ }
+
+ }
- package com.vaadin.tests.components.datefield;\r
- \r
- import java.sql.Date;\r
- import java.util.LinkedHashMap;\r
- import java.util.List;\r
- import java.util.Locale;\r
- \r
- import com.vaadin.tests.components.ComponentTestCase;\r
- import com.vaadin.ui.Component;\r
- import com.vaadin.ui.DateField;\r
- import com.vaadin.ui.DateField.Resolution;\r
- import com.vaadin.ui.PopupDateField;\r
- \r
- @SuppressWarnings("serial")\r
- public class PopupDateFields extends ComponentTestCase<PopupDateField> {\r
- \r
- private static final Locale[] LOCALES = new Locale[] { Locale.US,\r
- Locale.TAIWAN, new Locale("fi", "FI") };\r
- \r
- @Override\r
- protected Class<PopupDateField> getTestClass() {\r
- return PopupDateField.class;\r
- }\r
- \r
- @Override\r
- protected void initializeComponents() {\r
- \r
- for (Locale locale : LOCALES) {\r
- PopupDateField pd = createPopupDateField("Undefined width", "-1",\r
- locale);\r
- pd.setDebugId("Locale-" + locale.toString() + "-undefined-wide");\r
- addTestComponent(pd);\r
- pd = createPopupDateField("500px width", "500px", locale);\r
- pd.setDebugId("Locale-" + locale.toString() + "-500px-wide");\r
- addTestComponent(pd);\r
- pd = createPopupDateField("Initially empty", "", locale);\r
- pd.setValue(null);\r
- pd.setDebugId("Locale-" + locale.toString() + "-initially-empty");\r
- addTestComponent(pd);\r
- }\r
- \r
- }\r
- \r
- private PopupDateField createPopupDateField(String caption, String width,\r
- Locale locale) {\r
- PopupDateField pd = new PopupDateField(caption + "("\r
- + locale.toString() + ")");\r
- pd.setWidth(width);\r
- pd.setValue(new Date(12312312313L));\r
- pd.setLocale(locale);\r
- pd.setResolution(DateField.Resolution.YEAR);\r
- \r
- return pd;\r
- }\r
- \r
- @Override\r
- protected String getDescription() {\r
- return "A generic test for PopupDateFields in different configurations";\r
- }\r
- \r
- @Override\r
- protected List<Component> createActions() {\r
- List<Component> actions = super.createActions();\r
- actions.add(createResolutionSelectAction());\r
- actions.add(createInputPromptSelectAction());\r
- return actions;\r
- }\r
- \r
- private Component createResolutionSelectAction() {\r
- LinkedHashMap<String, Resolution> options = new LinkedHashMap<String, Resolution>();\r
- options.put("Year", DateField.Resolution.YEAR);\r
- options.put("Month", DateField.Resolution.MONTH);\r
- options.put("Day", DateField.Resolution.DAY);\r
- options.put("Hour", DateField.Resolution.HOUR);\r
- options.put("Min", DateField.Resolution.MINUTE);\r
- options.put("Sec", DateField.Resolution.SECOND);\r
- return createSelectAction("Resolution", options, "Year",\r
- new Command<PopupDateField, Resolution>() {\r
- \r
- public void execute(PopupDateField c, Resolution value,\r
- Object data) {\r
- c.setResolution(value);\r
- \r
- }\r
- });\r
- }\r
- \r
- private Component createInputPromptSelectAction() {\r
- LinkedHashMap<String, String> options = new LinkedHashMap<String, String>();\r
- options.put("<none>", null);\r
- options.put("Please enter date", "Please enter date");\r
- options.put("åäöÅÄÖ", "åäöÅÄÖ");\r
- \r
- return createSelectAction("Input prompt", options, "<none>",\r
- new Command<PopupDateField, String>() {\r
- \r
- public void execute(PopupDateField c, String value,\r
- Object data) {\r
- c.setInputPrompt(value);\r
- \r
- }\r
- });\r
- }\r
- \r
- }\r
+ package com.vaadin.tests.components.datefield;
+
+ import java.sql.Date;
+ import java.util.LinkedHashMap;
+ import java.util.List;
+ import java.util.Locale;
+
+ import com.vaadin.tests.components.ComponentTestCase;
+ import com.vaadin.ui.Component;
+ import com.vaadin.ui.DateField;
++import com.vaadin.ui.DateField.Resolution;
+ import com.vaadin.ui.PopupDateField;
+
+ @SuppressWarnings("serial")
+ public class PopupDateFields extends ComponentTestCase<PopupDateField> {
+
+ private static final Locale[] LOCALES = new Locale[] { Locale.US,
+ Locale.TAIWAN, new Locale("fi", "FI") };
+
+ @Override
+ protected Class<PopupDateField> getTestClass() {
+ return PopupDateField.class;
+ }
+
+ @Override
+ protected void initializeComponents() {
+
+ for (Locale locale : LOCALES) {
+ PopupDateField pd = createPopupDateField("Undefined width", "-1",
+ locale);
+ pd.setDebugId("Locale-" + locale.toString() + "-undefined-wide");
+ addTestComponent(pd);
+ pd = createPopupDateField("500px width", "500px", locale);
+ pd.setDebugId("Locale-" + locale.toString() + "-500px-wide");
+ addTestComponent(pd);
+ pd = createPopupDateField("Initially empty", "", locale);
+ pd.setValue(null);
+ pd.setDebugId("Locale-" + locale.toString() + "-initially-empty");
+ addTestComponent(pd);
+ }
+
+ }
+
+ private PopupDateField createPopupDateField(String caption, String width,
+ Locale locale) {
+ PopupDateField pd = new PopupDateField(caption + "("
+ + locale.toString() + ")");
+ pd.setWidth(width);
+ pd.setValue(new Date(12312312313L));
+ pd.setLocale(locale);
- pd.setResolution(DateField.RESOLUTION_YEAR);
++ pd.setResolution(DateField.Resolution.YEAR);
+
+ return pd;
+ }
+
+ @Override
+ protected String getDescription() {
+ return "A generic test for PopupDateFields in different configurations";
+ }
+
+ @Override
+ protected List<Component> createActions() {
+ List<Component> actions = super.createActions();
+ actions.add(createResolutionSelectAction());
+ actions.add(createInputPromptSelectAction());
+ return actions;
+ }
+
+ private Component createResolutionSelectAction() {
- LinkedHashMap<String, Integer> options = new LinkedHashMap<String, Integer>();
- options.put("Year", DateField.RESOLUTION_YEAR);
- options.put("Month", DateField.RESOLUTION_MONTH);
- options.put("Day", DateField.RESOLUTION_DAY);
- options.put("Hour", DateField.RESOLUTION_HOUR);
- options.put("Min", DateField.RESOLUTION_MIN);
- options.put("Sec", DateField.RESOLUTION_SEC);
- options.put("Msec", DateField.RESOLUTION_MSEC);
++ LinkedHashMap<String, Resolution> options = new LinkedHashMap<String, Resolution>();
++ options.put("Year", DateField.Resolution.YEAR);
++ options.put("Month", DateField.Resolution.MONTH);
++ options.put("Day", DateField.Resolution.DAY);
++ options.put("Hour", DateField.Resolution.HOUR);
++ options.put("Min", DateField.Resolution.MINUTE);
++ options.put("Sec", DateField.Resolution.SECOND);
+ return createSelectAction("Resolution", options, "Year",
- new Command<PopupDateField, Integer>() {
++ new Command<PopupDateField, Resolution>() {
+
- public void execute(PopupDateField c, Integer value,
++ public void execute(PopupDateField c, Resolution value,
+ Object data) {
+ c.setResolution(value);
+
+ }
+ });
+ }
+
+ private Component createInputPromptSelectAction() {
+ LinkedHashMap<String, String> options = new LinkedHashMap<String, String>();
+ options.put("<none>", null);
+ options.put("Please enter date", "Please enter date");
+ options.put("åäöÅÄÖ", "åäöÅÄÖ");
+
+ return createSelectAction("Input prompt", options, "<none>",
+ new Command<PopupDateField, String>() {
+
+ public void execute(PopupDateField c, String value,
+ Object data) {
+ c.setInputPrompt(value);
+
+ }
+ });
+ }
+
+ }
- package com.vaadin.tests.components.embedded;\r
- \r
- import com.vaadin.terminal.ClassResource;\r
- import com.vaadin.tests.components.TestBase;\r
- import com.vaadin.ui.Embedded;\r
- import com.vaadin.ui.Window;\r
- \r
- public class EmbeddedPdf extends TestBase {\r
- \r
- @Override\r
- protected String getDescription() {\r
- return "The embedded flash should have the movie parameter set to \"someRandomValue\" and an allowFullScreen parameter set to \"true\".";\r
- }\r
- \r
- @Override\r
- protected Integer getTicketNumber() {\r
- return 3367;\r
- }\r
- \r
- @Override\r
- public void setup() {\r
- Embedded player = new Embedded();\r
- player.setType(Embedded.TYPE_BROWSER);\r
- player.setWidth("400px");\r
- player.setHeight("300px");\r
- player.setSource(new ClassResource(getClass(), "test.pdf", this));\r
- addComponent(player);\r
- \r
- player.getRoot().addWindow(new Window("Testwindow"));\r
- }\r
- \r
- }\r
+ package com.vaadin.tests.components.embedded;
+
+ import com.vaadin.terminal.ClassResource;
+ import com.vaadin.tests.components.TestBase;
+ import com.vaadin.ui.Embedded;
+ import com.vaadin.ui.Window;
+
+ public class EmbeddedPdf extends TestBase {
+
+ @Override
+ protected String getDescription() {
+ return "The embedded flash should have the movie parameter set to \"someRandomValue\" and an allowFullScreen parameter set to \"true\".";
+ }
+
+ @Override
+ protected Integer getTicketNumber() {
+ return 3367;
+ }
+
+ @Override
+ public void setup() {
+ Embedded player = new Embedded();
+ player.setType(Embedded.TYPE_BROWSER);
+ player.setWidth("400px");
+ player.setHeight("300px");
+ player.setSource(new ClassResource(getClass(), "test.pdf", this));
+ addComponent(player);
+
- player.getWindow().addWindow(new Window("Testwindow"));
++ player.getRoot().addWindow(new Window("Testwindow"));
+ }
+
+ }
- package com.vaadin.tests.components.form;\r
- \r
- import com.vaadin.event.ShortcutAction.KeyCode;\r
- import com.vaadin.tests.components.TestBase;\r
- import com.vaadin.tests.util.Log;\r
- import com.vaadin.ui.Button;\r
- import com.vaadin.ui.Button.ClickEvent;\r
- import com.vaadin.ui.Form;\r
- import com.vaadin.ui.TextField;\r
- \r
- public class FormWithEnterShortCut extends TestBase {\r
- private Log log = new Log(2);\r
- \r
- @Override\r
- protected void setup() {\r
- \r
- final Form form = new Form();\r
- final TextField tf = new TextField("Search");\r
- form.addField("searchfield", tf);\r
- \r
- Button button = new Button("Go");\r
- button.addListener(new Button.ClickListener() {\r
- public void buttonClick(ClickEvent event) {\r
- log.log("search: " + tf.getValue());\r
- }\r
- });\r
- button.setClickShortcut(KeyCode.ENTER);\r
- button.setStyleName("primary");\r
- \r
- form.getFooter().addComponent(button);\r
- \r
- addComponent(log);\r
- addComponent(form);\r
- \r
- }\r
- \r
- @Override\r
- protected String getDescription() {\r
- return "Focusing a button and pressing enter (which is a shortcut for button click) should only produce one click event";\r
- }\r
- \r
- @Override\r
- protected Integer getTicketNumber() {\r
- return 5433;\r
- }\r
- }\r
+ package com.vaadin.tests.components.form;
+
+ import com.vaadin.event.ShortcutAction.KeyCode;
+ import com.vaadin.tests.components.TestBase;
+ import com.vaadin.tests.util.Log;
+ import com.vaadin.ui.Button;
+ import com.vaadin.ui.Button.ClickEvent;
-import com.vaadin.ui.Field;
+ import com.vaadin.ui.Form;
+ import com.vaadin.ui.TextField;
+
+ public class FormWithEnterShortCut extends TestBase {
+ private Log log = new Log(2);
+
+ @Override
+ protected void setup() {
+
+ final Form form = new Form();
- final Field tf = new TextField("Search");
++ final TextField tf = new TextField("Search");
+ form.addField("searchfield", tf);
+
+ Button button = new Button("Go");
+ button.addListener(new Button.ClickListener() {
+ public void buttonClick(ClickEvent event) {
+ log.log("search: " + tf.getValue());
+ }
+ });
+ button.setClickShortcut(KeyCode.ENTER);
+ button.setStyleName("primary");
+
+ form.getFooter().addComponent(button);
+
+ addComponent(log);
+ addComponent(form);
+
+ }
+
+ @Override
+ protected String getDescription() {
+ return "Focusing a button and pressing enter (which is a shortcut for button click) should only produce one click event";
+ }
+
+ @Override
+ protected Integer getTicketNumber() {
+ return 5433;
+ }
+ }
- package com.vaadin.tests.components.formlayout;\r
- \r
- import com.vaadin.tests.components.AbstractTestCase;\r
- import com.vaadin.ui.FormLayout;\r
- import com.vaadin.ui.Root.LegacyWindow;\r
- import com.vaadin.ui.Table;\r
- import com.vaadin.ui.TextField;\r
- \r
- public class TableInFormLayoutCausesScrolling extends AbstractTestCase {\r
- \r
- @Override\r
- public void init() {\r
- // Window Initialization.\r
- final LegacyWindow window = new LegacyWindow("Main Window");\r
- setMainWindow(window);\r
- \r
- // FormLayout creation\r
- final FormLayout fl = new FormLayout();\r
- window.setContent(fl);\r
- \r
- // Add 20 TextField\r
- for (int i = 20; i-- > 0;) {\r
- fl.addComponent(new TextField());\r
- }\r
- \r
- // Add 1 selectable table with some items\r
- final Table table = new Table();\r
- table.setSelectable(true);\r
- table.addContainerProperty("item", String.class, "");\r
- for (int i = 50; i-- > 0;) {\r
- table.addItem(new String[] { "item" + i }, i);\r
- }\r
- window.addComponent(table);\r
- }\r
- \r
- @Override\r
- protected String getDescription() {\r
- return "Clicking in the Table should not cause the page to scroll";\r
- }\r
- \r
- @Override\r
- protected Integer getTicketNumber() {\r
- return 7309;\r
- }\r
+ package com.vaadin.tests.components.formlayout;
+
+ import com.vaadin.tests.components.AbstractTestCase;
+ import com.vaadin.ui.FormLayout;
++import com.vaadin.ui.Root.LegacyWindow;
+ import com.vaadin.ui.Table;
+ import com.vaadin.ui.TextField;
-import com.vaadin.ui.Window;
+
+ public class TableInFormLayoutCausesScrolling extends AbstractTestCase {
+
+ @Override
+ public void init() {
+ // Window Initialization.
- final Window window = new Window("Main Window");
++ final LegacyWindow window = new LegacyWindow("Main Window");
+ setMainWindow(window);
+
+ // FormLayout creation
+ final FormLayout fl = new FormLayout();
+ window.setContent(fl);
+
+ // Add 20 TextField
+ for (int i = 20; i-- > 0;) {
+ fl.addComponent(new TextField());
+ }
+
+ // Add 1 selectable table with some items
+ final Table table = new Table();
+ table.setSelectable(true);
+ table.addContainerProperty("item", String.class, "");
+ for (int i = 50; i-- > 0;) {
+ table.addItem(new String[] { "item" + i }, i);
+ }
+ window.addComponent(table);
+ }
+
+ @Override
+ protected String getDescription() {
+ return "Clicking in the Table should not cause the page to scroll";
+ }
+
+ @Override
+ protected Integer getTicketNumber() {
+ return 7309;
+ }
}
- package com.vaadin.tests.components.label;\r
- \r
- import java.util.ArrayList;\r
- import java.util.LinkedHashMap;\r
- import java.util.List;\r
- \r
- import com.vaadin.data.Property.ValueChangeListener;\r
- import com.vaadin.tests.components.AbstractComponentTest;\r
- import com.vaadin.ui.Label;\r
- import com.vaadin.ui.Label.ContentMode;\r
- \r
- public class LabelTest extends AbstractComponentTest<Label> implements\r
- ValueChangeListener {\r
- \r
- private Command<Label, Object> setValueCommand = new Command<Label, Object>() {\r
- \r
- public void execute(Label c, Object value, Object data) {\r
- c.setValue(value);\r
- }\r
- };\r
- \r
- private Command<Label, Boolean> valueChangeListenerCommand = new Command<Label, Boolean>() {\r
- public void execute(Label c, Boolean value, Object data) {\r
- if (value) {\r
- c.addListener(LabelTest.this);\r
- } else {\r
- c.removeListener(LabelTest.this);\r
- \r
- }\r
- }\r
- };\r
- \r
- private Command<Label, ContentMode> contentModeCommand = new Command<Label, ContentMode>() {\r
- public void execute(Label c, ContentMode value, Object data) {\r
- c.setContentMode(value);\r
- }\r
- };\r
- \r
- @Override\r
- protected Class<Label> getTestClass() {\r
- return Label.class;\r
- }\r
- \r
- @Override\r
- protected void createActions() {\r
- super.createActions();\r
- \r
- createContentModeSelect(CATEGORY_FEATURES);\r
- createValueSelect(CATEGORY_FEATURES);\r
- createValueChangeListener(CATEGORY_LISTENERS);\r
- }\r
- \r
- private void createValueSelect(String category) {\r
- String subCategory = "Set text value";\r
- createCategory(subCategory, category);\r
- List<String> values = new ArrayList<String>();\r
- values.add("Test");\r
- values.add("A little longer value");\r
- values.add("A very long value with very much text. All in all it is 74 characters long");\r
- values.add("<b>Bold</b>");\r
- values.add("<div style=\"height: 70px; width: 15px; border: 1px dashed red\">With border</div>");\r
- \r
- createClickAction("(empty string)", subCategory, setValueCommand, "");\r
- createClickAction("(null)", subCategory, setValueCommand, null);\r
- for (String value : values) {\r
- createClickAction(value, subCategory, setValueCommand, value);\r
- }\r
- }\r
- \r
- @SuppressWarnings("deprecation")\r
- private void createContentModeSelect(String category) {\r
- LinkedHashMap<String, ContentMode> options = new LinkedHashMap<String, ContentMode>();\r
- options.put("Text", ContentMode.TEXT);\r
- options.put("Preformatted", ContentMode.PREFORMATTED);\r
- options.put("Raw", ContentMode.RAW);\r
- options.put("UIDL", ContentMode.XML); // Deprecated UIDL mode still used\r
- // to avoid breaking old tests\r
- options.put("XHTML", ContentMode.XHTML);\r
- options.put("XML", ContentMode.XML);\r
- \r
- createSelectAction("Content mode", category, options, "Text",\r
- contentModeCommand);\r
- }\r
- \r
- private void createValueChangeListener(String category) {\r
- createBooleanAction("Value change listener", category, false,\r
- valueChangeListenerCommand);\r
- }\r
- \r
- public void valueChange(com.vaadin.data.Property.ValueChangeEvent event) {\r
- Object o = event.getProperty().getValue();\r
- \r
- // Distinguish between null and 'null'\r
- String value = "null";\r
- if (o != null) {\r
- value = "'" + o.toString() + "'";\r
- }\r
- \r
- log(event.getClass().getSimpleName() + ", new value: " + value);\r
- };\r
- \r
- }\r
+ package com.vaadin.tests.components.label;
+
+ import java.util.ArrayList;
+ import java.util.LinkedHashMap;
+ import java.util.List;
+
+ import com.vaadin.data.Property.ValueChangeListener;
+ import com.vaadin.tests.components.AbstractComponentTest;
+ import com.vaadin.ui.Label;
++import com.vaadin.ui.Label.ContentMode;
+
+ public class LabelTest extends AbstractComponentTest<Label> implements
+ ValueChangeListener {
+
+ private Command<Label, Object> setValueCommand = new Command<Label, Object>() {
+
+ public void execute(Label c, Object value, Object data) {
+ c.setValue(value);
+ }
+ };
+
+ private Command<Label, Boolean> valueChangeListenerCommand = new Command<Label, Boolean>() {
+ public void execute(Label c, Boolean value, Object data) {
+ if (value) {
+ c.addListener(LabelTest.this);
+ } else {
+ c.removeListener(LabelTest.this);
+
+ }
+ }
+ };
+
- private Command<Label, Integer> contentModeCommand = new Command<Label, Integer>() {
- public void execute(Label c, Integer value, Object data) {
++ private Command<Label, ContentMode> contentModeCommand = new Command<Label, ContentMode>() {
++ public void execute(Label c, ContentMode value, Object data) {
+ c.setContentMode(value);
+ }
+ };
+
+ @Override
+ protected Class<Label> getTestClass() {
+ return Label.class;
+ }
+
+ @Override
+ protected void createActions() {
+ super.createActions();
+
+ createContentModeSelect(CATEGORY_FEATURES);
+ createValueSelect(CATEGORY_FEATURES);
+ createValueChangeListener(CATEGORY_LISTENERS);
+ }
+
+ private void createValueSelect(String category) {
+ String subCategory = "Set text value";
+ createCategory(subCategory, category);
+ List<String> values = new ArrayList<String>();
+ values.add("Test");
+ values.add("A little longer value");
+ values.add("A very long value with very much text. All in all it is 74 characters long");
+ values.add("<b>Bold</b>");
+ values.add("<div style=\"height: 70px; width: 15px; border: 1px dashed red\">With border</div>");
+
+ createClickAction("(empty string)", subCategory, setValueCommand, "");
+ createClickAction("(null)", subCategory, setValueCommand, null);
+ for (String value : values) {
+ createClickAction(value, subCategory, setValueCommand, value);
+ }
+ }
+
+ @SuppressWarnings("deprecation")
+ private void createContentModeSelect(String category) {
- LinkedHashMap<String, Integer> options = new LinkedHashMap<String, Integer>();
- options.put("Text", Label.CONTENT_TEXT);
- options.put("Preformatted", Label.CONTENT_PREFORMATTED);
- options.put("Raw", Label.CONTENT_RAW);
- options.put("UIDL", Label.CONTENT_UIDL);
- options.put("XHTML", Label.CONTENT_XHTML);
- options.put("XML", Label.CONTENT_XML);
++ LinkedHashMap<String, ContentMode> options = new LinkedHashMap<String, ContentMode>();
++ options.put("Text", ContentMode.TEXT);
++ options.put("Preformatted", ContentMode.PREFORMATTED);
++ options.put("Raw", ContentMode.RAW);
++ options.put("UIDL", ContentMode.XML); // Deprecated UIDL mode still used
++ // to avoid breaking old tests
++ options.put("XHTML", ContentMode.XHTML);
++ options.put("XML", ContentMode.XML);
+
+ createSelectAction("Content mode", category, options, "Text",
+ contentModeCommand);
+ }
+
+ private void createValueChangeListener(String category) {
+ createBooleanAction("Value change listener", category, false,
+ valueChangeListenerCommand);
+ }
+
+ public void valueChange(com.vaadin.data.Property.ValueChangeEvent event) {
+ Object o = event.getProperty().getValue();
+
+ // Distinguish between null and 'null'
+ String value = "null";
+ if (o != null) {
+ value = "'" + o.toString() + "'";
+ }
+
+ log(event.getClass().getSimpleName() + ", new value: " + value);
+ };
+
+ }
- package com.vaadin.tests.components.menubar;\r
- \r
- import com.vaadin.terminal.ThemeResource;\r
- import com.vaadin.tests.components.AbstractTestCase;\r
- import com.vaadin.ui.Alignment;\r
- import com.vaadin.ui.MenuBar;\r
- import com.vaadin.ui.Root.LegacyWindow;\r
- import com.vaadin.ui.VerticalLayout;\r
- \r
- public class MenuBarRunsOutOfBrowser extends AbstractTestCase {\r
- \r
- @Override\r
- public void init() {\r
- setTheme("runo");\r
- LegacyWindow main = new LegacyWindow("Test");\r
- main.setSizeFull();\r
- setMainWindow(main);\r
- main.getContent().setSizeFull();\r
- \r
- MenuBar menuBar = new MenuBar();\r
- menuBar.addItem("Test", new ThemeResource("icons/16/calendar.png"),\r
- null);\r
- menuBar.addItem("ABC", new ThemeResource("icons/16/document.png"), null);\r
- menuBar.addItem("123", new ThemeResource("icons/16/help.png"), null);\r
- \r
- main.getContent().addComponent(menuBar);\r
- ((VerticalLayout) main.getContent()).setComponentAlignment(menuBar,\r
- Alignment.TOP_RIGHT);\r
- \r
- }\r
- \r
- @Override\r
- protected String getDescription() {\r
- return "The menubar should be right aligned but not run out of the browser";\r
- }\r
- \r
- @Override\r
- protected Integer getTicketNumber() {\r
- return 5894;\r
- }\r
- \r
- }\r
+ package com.vaadin.tests.components.menubar;
+
+ import com.vaadin.terminal.ThemeResource;
+ import com.vaadin.tests.components.AbstractTestCase;
+ import com.vaadin.ui.Alignment;
+ import com.vaadin.ui.MenuBar;
++import com.vaadin.ui.Root.LegacyWindow;
+ import com.vaadin.ui.VerticalLayout;
-import com.vaadin.ui.Window;
+
+ public class MenuBarRunsOutOfBrowser extends AbstractTestCase {
+
+ @Override
+ public void init() {
+ setTheme("runo");
- Window main = new Window("Test");
++ LegacyWindow main = new LegacyWindow("Test");
+ main.setSizeFull();
+ setMainWindow(main);
+ main.getContent().setSizeFull();
+
+ MenuBar menuBar = new MenuBar();
+ menuBar.addItem("Test", new ThemeResource("icons/16/calendar.png"),
+ null);
+ menuBar.addItem("ABC", new ThemeResource("icons/16/document.png"), null);
+ menuBar.addItem("123", new ThemeResource("icons/16/help.png"), null);
+
+ main.getContent().addComponent(menuBar);
+ ((VerticalLayout) main.getContent()).setComponentAlignment(menuBar,
+ Alignment.TOP_RIGHT);
+
+ }
+
+ @Override
+ protected String getDescription() {
+ return "The menubar should be right aligned but not run out of the browser";
+ }
+
+ @Override
+ protected Integer getTicketNumber() {
+ return 5894;
+ }
+
+ }
- package com.vaadin.tests.components.notification;\r
- \r
- import com.vaadin.tests.components.TestBase;\r
- import com.vaadin.ui.Button;\r
- import com.vaadin.ui.Button.ClickEvent;\r
- import com.vaadin.ui.Button.ClickListener;\r
- import com.vaadin.ui.NativeSelect;\r
- import com.vaadin.ui.Notification;\r
- import com.vaadin.ui.Root;\r
- import com.vaadin.ui.TextArea;\r
- \r
- public class Notifications extends TestBase implements ClickListener {\r
- \r
- private static final String CAPTION = "CAPTION";\r
- private TextArea tf;\r
- private NativeSelect type;\r
- \r
- @SuppressWarnings("deprecation")\r
- @Override\r
- protected void setup() {\r
- tf = new TextArea("Text", "Hello world");\r
- tf.setRows(10);\r
- addComponent(tf);\r
- type = new NativeSelect();\r
- type.setNullSelectionAllowed(false);\r
- type.addContainerProperty(CAPTION, String.class, "");\r
- type.setItemCaptionPropertyId(CAPTION);\r
- type.addItem(Notification.TYPE_HUMANIZED_MESSAGE)\r
- .getItemProperty(CAPTION).setValue("Humanized");\r
- type.addItem(Notification.TYPE_ERROR_MESSAGE).getItemProperty(CAPTION)\r
- .setValue("Error");\r
- type.addItem(Notification.TYPE_WARNING_MESSAGE)\r
- .getItemProperty(CAPTION).setValue("Warning");\r
- type.addItem(Notification.TYPE_TRAY_NOTIFICATION)\r
- .getItemProperty(CAPTION).setValue("Tray");\r
- type.setValue(type.getItemIds().iterator().next());\r
- addComponent(type);\r
- Button showNotification = new Button("Show notification", this);\r
- addComponent(showNotification);\r
- }\r
- \r
- @Override\r
- protected String getDescription() {\r
- return "Generic test case for notifications";\r
- }\r
- \r
- @Override\r
- protected Integer getTicketNumber() {\r
- // TODO Auto-generated method stub\r
- return null;\r
- }\r
- \r
- public void buttonClick(ClickEvent event) {\r
- Notification n = new Notification(tf.getValue(),\r
- (Integer) type.getValue());\r
- Root.getCurrentRoot().showNotification(n);\r
- \r
- }\r
- }\r
+ package com.vaadin.tests.components.notification;
+
+ import com.vaadin.tests.components.TestBase;
+ import com.vaadin.ui.Button;
+ import com.vaadin.ui.Button.ClickEvent;
+ import com.vaadin.ui.Button.ClickListener;
+ import com.vaadin.ui.NativeSelect;
-import com.vaadin.ui.TextField;
-import com.vaadin.ui.Window.Notification;
++import com.vaadin.ui.Notification;
++import com.vaadin.ui.Root;
++import com.vaadin.ui.TextArea;
+
+ public class Notifications extends TestBase implements ClickListener {
+
+ private static final String CAPTION = "CAPTION";
- private TextField tf;
++ private TextArea tf;
+ private NativeSelect type;
+
+ @SuppressWarnings("deprecation")
+ @Override
+ protected void setup() {
- tf = new TextField("Text", "Hello world");
++ tf = new TextArea("Text", "Hello world");
+ tf.setRows(10);
+ addComponent(tf);
+ type = new NativeSelect();
+ type.setNullSelectionAllowed(false);
+ type.addContainerProperty(CAPTION, String.class, "");
+ type.setItemCaptionPropertyId(CAPTION);
+ type.addItem(Notification.TYPE_HUMANIZED_MESSAGE)
+ .getItemProperty(CAPTION).setValue("Humanized");
+ type.addItem(Notification.TYPE_ERROR_MESSAGE).getItemProperty(CAPTION)
+ .setValue("Error");
+ type.addItem(Notification.TYPE_WARNING_MESSAGE)
+ .getItemProperty(CAPTION).setValue("Warning");
+ type.addItem(Notification.TYPE_TRAY_NOTIFICATION)
+ .getItemProperty(CAPTION).setValue("Tray");
+ type.setValue(type.getItemIds().iterator().next());
+ addComponent(type);
+ Button showNotification = new Button("Show notification", this);
+ addComponent(showNotification);
+ }
+
+ @Override
+ protected String getDescription() {
+ return "Generic test case for notifications";
+ }
+
+ @Override
+ protected Integer getTicketNumber() {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ public void buttonClick(ClickEvent event) {
- Notification n = new Notification((String) tf.getValue(),
++ Notification n = new Notification(tf.getValue(),
+ (Integer) type.getValue());
- event.getButton().getWindow().showNotification(n);
++ Root.getCurrentRoot().showNotification(n);
+
+ }
+ }
- package com.vaadin.tests.components.notification;\r
- \r
- import com.vaadin.tests.components.TestBase;\r
- import com.vaadin.ui.Button;\r
- import com.vaadin.ui.Button.ClickEvent;\r
- import com.vaadin.ui.Button.ClickListener;\r
- import com.vaadin.ui.CheckBox;\r
- import com.vaadin.ui.Notification;\r
- import com.vaadin.ui.Root;\r
- import com.vaadin.ui.TextArea;\r
- import com.vaadin.ui.TextField;\r
- \r
- public class NotificationsHtmlAllowed extends TestBase implements ClickListener {\r
- \r
- private TextArea messageField;\r
- private CheckBox htmlAllowedBox;\r
- private TextField captionField;\r
- \r
- @Override\r
- protected void setup() {\r
- captionField = new TextField("Caption", "Hello <u>world</u>");\r
- addComponent(captionField);\r
- captionField.focus();\r
- \r
- messageField = new TextArea("Message",\r
- "Hello <i>world</i>\nWith a newline <br/>And a html line break");\r
- messageField.setRows(10);\r
- addComponent(messageField);\r
- \r
- htmlAllowedBox = new CheckBox("Html content allowed", true);\r
- addComponent(htmlAllowedBox);\r
- \r
- Button showNotification = new Button("Show notification", this);\r
- addComponent(showNotification);\r
- }\r
- \r
- @Override\r
- protected String getDescription() {\r
- return "Test case for htmlAllowed in notifications";\r
- }\r
- \r
- @Override\r
- protected Integer getTicketNumber() {\r
- return 6097;\r
- }\r
- \r
- public void buttonClick(ClickEvent event) {\r
- Notification n = makeNotification();\r
- Root.getCurrentRoot().showNotification(n);\r
- \r
- }\r
- \r
- private Notification makeNotification() {\r
- Notification n = new Notification((String) captionField.getValue(),\r
- (String) messageField.getValue(),\r
- Notification.TYPE_HUMANIZED_MESSAGE,\r
- (Boolean) htmlAllowedBox.getValue());\r
- return n;\r
- }\r
- }\r
+ package com.vaadin.tests.components.notification;
+
+ import com.vaadin.tests.components.TestBase;
+ import com.vaadin.ui.Button;
+ import com.vaadin.ui.Button.ClickEvent;
+ import com.vaadin.ui.Button.ClickListener;
+ import com.vaadin.ui.CheckBox;
++import com.vaadin.ui.Notification;
++import com.vaadin.ui.Root;
+ import com.vaadin.ui.TextArea;
+ import com.vaadin.ui.TextField;
-import com.vaadin.ui.Window;
-import com.vaadin.ui.Window.Notification;
+
+ public class NotificationsHtmlAllowed extends TestBase implements ClickListener {
+
+ private TextArea messageField;
+ private CheckBox htmlAllowedBox;
+ private TextField captionField;
- private Window subwindow;
- private CheckBox showInSubwindow;
+
+ @Override
+ protected void setup() {
+ captionField = new TextField("Caption", "Hello <u>world</u>");
+ addComponent(captionField);
+ captionField.focus();
+
+ messageField = new TextArea("Message",
+ "Hello <i>world</i>\nWith a newline <br/>And a html line break");
+ messageField.setRows(10);
+ addComponent(messageField);
+
+ htmlAllowedBox = new CheckBox("Html content allowed", true);
+ addComponent(htmlAllowedBox);
+
- showInSubwindow = new CheckBox("Show in subwindow", false);
- addComponent(showInSubwindow);
-
+ Button showNotification = new Button("Show notification", this);
+ addComponent(showNotification);
-
- subwindow = new Window("Sub window");
- subwindow.setPositionX(400);
- subwindow.setPositionY(0);
- getMainWindow().addWindow(subwindow);
+ }
+
+ @Override
+ protected String getDescription() {
+ return "Test case for htmlAllowed in notifications";
+ }
+
+ @Override
+ protected Integer getTicketNumber() {
+ return 6097;
+ }
+
+ public void buttonClick(ClickEvent event) {
+ Notification n = makeNotification();
- Window window;
- if (showInSubwindow.booleanValue()) {
- window = subwindow;
- } else {
- window = event.getButton().getWindow();
- }
- window.showNotification(n);
++ Root.getCurrentRoot().showNotification(n);
+
+ }
+
+ private Notification makeNotification() {
+ Notification n = new Notification((String) captionField.getValue(),
+ (String) messageField.getValue(),
+ Notification.TYPE_HUMANIZED_MESSAGE,
- htmlAllowedBox.booleanValue());
++ (Boolean) htmlAllowedBox.getValue());
+ return n;
+ }
+ }
- package com.vaadin.tests.components.popupview;\r
- \r
- import com.vaadin.tests.components.TestBase;\r
- import com.vaadin.ui.Button;\r
- import com.vaadin.ui.Button.ClickEvent;\r
- import com.vaadin.ui.Button.ClickListener;\r
- import com.vaadin.ui.Notification;\r
- import com.vaadin.ui.PopupView;\r
- import com.vaadin.ui.TextField;\r
- \r
- public class PopupViewNullValues extends TestBase {\r
- \r
- private PopupView pv[] = new PopupView[4];\r
- private Button b[] = new Button[4];\r
- \r
- @Override\r
- protected void setup() {\r
- try {\r
- pv[0] = new PopupView("Popupview 1 - no component", null);\r
- addComponent(pv[0]);\r
- b[0] = new Button("Open popupview 1", new ClickListener() {\r
- \r
- public void buttonClick(ClickEvent event) {\r
- pv[0].setPopupVisible(true);\r
- }\r
- \r
- });\r
- } catch (Exception e) {\r
- getMainWindow()\r
- .showNotification(\r
- "Error, 'null content' should not throw an exception at this point",\r
- Notification.TYPE_ERROR_MESSAGE);\r
- }\r
- \r
- try {\r
- pv[1] = new PopupView(null, new TextField(\r
- "Empty html, contains component"));\r
- addComponent(pv[1]);\r
- b[1] = new Button("Open popupview 2", new ClickListener() {\r
- \r
- public void buttonClick(ClickEvent event) {\r
- pv[1].setPopupVisible(true);\r
- }\r
- \r
- });\r
- } catch (Exception e) {\r
- getMainWindow()\r
- .showNotification(\r
- "Error, 'null html', should not throw an exception at this point",\r
- Notification.TYPE_ERROR_MESSAGE);\r
- }\r
- \r
- try {\r
- pv[2] = new PopupView(null, null);\r
- addComponent(pv[2]);\r
- b[2] = new Button("Open popupview 3", new ClickListener() {\r
- \r
- public void buttonClick(ClickEvent event) {\r
- pv[2].setPopupVisible(true);\r
- }\r
- \r
- });\r
- } catch (Exception e) {\r
- getMainWindow()\r
- .showNotification(\r
- "Error, 'null html, null content', should not throw an exception at this point",\r
- Notification.TYPE_ERROR_MESSAGE);\r
- }\r
- try {\r
- pv[3] = new PopupView("Popupview 4 - has component", new TextField(\r
- "This is the content of popupview 4"));\r
- addComponent(pv[3]);\r
- b[3] = new Button("Open popupview 4", new ClickListener() {\r
- \r
- public void buttonClick(ClickEvent event) {\r
- pv[3].setPopupVisible(true);\r
- }\r
- \r
- });\r
- } catch (Exception e) {\r
- getMainWindow()\r
- .showNotification(\r
- "Error, 'null html, null content', should not throw an exception at this point",\r
- Notification.TYPE_ERROR_MESSAGE);\r
- }\r
- \r
- addComponent(b[0]);\r
- addComponent(b[1]);\r
- addComponent(b[2]);\r
- addComponent(b[3]);\r
- }\r
- \r
- @Override\r
- protected String getDescription() {\r
- return "This test case contains 3 popupviews. Only the second and the forth popup views have non-null components and can be opened. 1 and 3 will produce an exception if you try to open them.";\r
- }\r
- \r
- @Override\r
- protected Integer getTicketNumber() {\r
- return 3248;\r
- }\r
- \r
- }\r
+ package com.vaadin.tests.components.popupview;
+
+ import com.vaadin.tests.components.TestBase;
+ import com.vaadin.ui.Button;
+ import com.vaadin.ui.Button.ClickEvent;
+ import com.vaadin.ui.Button.ClickListener;
++import com.vaadin.ui.Notification;
+ import com.vaadin.ui.PopupView;
+ import com.vaadin.ui.TextField;
-import com.vaadin.ui.Window.Notification;
+
+ public class PopupViewNullValues extends TestBase {
+
+ private PopupView pv[] = new PopupView[4];
+ private Button b[] = new Button[4];
+
+ @Override
+ protected void setup() {
+ try {
+ pv[0] = new PopupView("Popupview 1 - no component", null);
+ addComponent(pv[0]);
+ b[0] = new Button("Open popupview 1", new ClickListener() {
+
+ public void buttonClick(ClickEvent event) {
+ pv[0].setPopupVisible(true);
+ }
+
+ });
+ } catch (Exception e) {
+ getMainWindow()
+ .showNotification(
+ "Error, 'null content' should not throw an exception at this point",
+ Notification.TYPE_ERROR_MESSAGE);
+ }
+
+ try {
+ pv[1] = new PopupView(null, new TextField(
+ "Empty html, contains component"));
+ addComponent(pv[1]);
+ b[1] = new Button("Open popupview 2", new ClickListener() {
+
+ public void buttonClick(ClickEvent event) {
+ pv[1].setPopupVisible(true);
+ }
+
+ });
+ } catch (Exception e) {
+ getMainWindow()
+ .showNotification(
+ "Error, 'null html', should not throw an exception at this point",
+ Notification.TYPE_ERROR_MESSAGE);
+ }
+
+ try {
+ pv[2] = new PopupView(null, null);
+ addComponent(pv[2]);
+ b[2] = new Button("Open popupview 3", new ClickListener() {
+
+ public void buttonClick(ClickEvent event) {
+ pv[2].setPopupVisible(true);
+ }
+
+ });
+ } catch (Exception e) {
+ getMainWindow()
+ .showNotification(
+ "Error, 'null html, null content', should not throw an exception at this point",
+ Notification.TYPE_ERROR_MESSAGE);
+ }
+ try {
+ pv[3] = new PopupView("Popupview 4 - has component", new TextField(
+ "This is the content of popupview 4"));
+ addComponent(pv[3]);
+ b[3] = new Button("Open popupview 4", new ClickListener() {
+
+ public void buttonClick(ClickEvent event) {
+ pv[3].setPopupVisible(true);
+ }
+
+ });
+ } catch (Exception e) {
+ getMainWindow()
+ .showNotification(
+ "Error, 'null html, null content', should not throw an exception at this point",
+ Notification.TYPE_ERROR_MESSAGE);
+ }
+
+ addComponent(b[0]);
+ addComponent(b[1]);
+ addComponent(b[2]);
+ addComponent(b[3]);
+ }
+
+ @Override
+ protected String getDescription() {
+ return "This test case contains 3 popupviews. Only the second and the forth popup views have non-null components and can be opened. 1 and 3 will produce an exception if you try to open them.";
+ }
+
+ @Override
+ protected Integer getTicketNumber() {
+ return 3248;
+ }
+
+ }
- package com.vaadin.tests.components.popupview;\r
- \r
- import com.vaadin.tests.components.TestBase;\r
- import com.vaadin.ui.Component;\r
- import com.vaadin.ui.PopupView;\r
- import com.vaadin.ui.PopupView.Content;\r
- import com.vaadin.ui.RichTextArea;\r
- import com.vaadin.ui.VerticalLayout;\r
- \r
- public class PopupViewWithRTE extends TestBase {\r
- \r
- @Override\r
- protected String getDescription() {\r
- return "Rich text editor should work properly in popupview. Try to edit text below.";\r
- }\r
- \r
- @Override\r
- protected Integer getTicketNumber() {\r
- return 3043;\r
- }\r
- \r
- @Override\r
- protected void setup() {\r
- PopupView pv = new PopupView(new Content() {\r
- \r
- RichTextArea rte = new RichTextArea();\r
- \r
- VerticalLayout vl = new VerticalLayout();\r
- \r
- public String getMinimizedValueAsHTML() {\r
- String value = rte.getValue();\r
- if (value == null || "".equals(value)) {\r
- value = "Initial <b>content</b> for <h3>rte</h3>.";\r
- rte.setValue(value);\r
- rte.setHeight("150px");\r
- rte.setWidth("100%");\r
- vl.addComponent(rte);\r
- vl.setWidth("600px");\r
- }\r
- return value.toString();\r
- }\r
- \r
- public Component getPopupComponent() {\r
- return vl;\r
- }\r
- });\r
- getLayout().addComponent(pv);\r
- }\r
- \r
- }\r
+ package com.vaadin.tests.components.popupview;
+
+ import com.vaadin.tests.components.TestBase;
+ import com.vaadin.ui.Component;
+ import com.vaadin.ui.PopupView;
+ import com.vaadin.ui.PopupView.Content;
+ import com.vaadin.ui.RichTextArea;
+ import com.vaadin.ui.VerticalLayout;
+
+ public class PopupViewWithRTE extends TestBase {
+
+ @Override
+ protected String getDescription() {
+ return "Rich text editor should work properly in popupview. Try to edit text below.";
+ }
+
+ @Override
+ protected Integer getTicketNumber() {
+ return 3043;
+ }
+
+ @Override
+ protected void setup() {
+ PopupView pv = new PopupView(new Content() {
+
+ RichTextArea rte = new RichTextArea();
+
+ VerticalLayout vl = new VerticalLayout();
+
+ public String getMinimizedValueAsHTML() {
- Object value = rte.getValue();
++ String value = rte.getValue();
+ if (value == null || "".equals(value)) {
+ value = "Initial <b>content</b> for <h3>rte</h3>.";
+ rte.setValue(value);
+ rte.setHeight("150px");
+ rte.setWidth("100%");
+ vl.addComponent(rte);
+ vl.setWidth("600px");
+ }
+ return value.toString();
+ }
+
+ public Component getPopupComponent() {
+ return vl;
+ }
+ });
+ getLayout().addComponent(pv);
+ }
+
+ }
- package com.vaadin.tests.components.splitpanel;\r
- \r
- import com.vaadin.terminal.Sizeable;\r
- import com.vaadin.terminal.Sizeable.Unit;\r
- import com.vaadin.tests.components.AbstractLayoutTest;\r
- import com.vaadin.ui.AbstractSplitPanel;\r
- import com.vaadin.ui.AbstractSplitPanel.SplitterClickEvent;\r
- import com.vaadin.ui.AbstractSplitPanel.SplitterClickListener;\r
- \r
- public abstract class AbstractSplitPanelTest<T extends AbstractSplitPanel>\r
- extends AbstractLayoutTest<T> implements SplitterClickListener {\r
- \r
- private Command<T, Boolean> splitterClickListenerCommand = new Command<T, Boolean>() {\r
- \r
- public void execute(T c, Boolean value, Object data) {\r
- if (value) {\r
- c.addListener((SplitterClickListener) AbstractSplitPanelTest.this);\r
- } else {\r
- c.removeListener((SplitterClickListener) AbstractSplitPanelTest.this);\r
- }\r
- \r
- }\r
- };\r
- private Command<T, SplitPosition> setSplitPositionCommand = new Command<T, AbstractSplitPanelTest.SplitPosition>() {\r
- public void execute(T c, SplitPosition value, Object data) {\r
- value.apply(c);\r
- }\r
- };\r
- private Command<T, Boolean> splitterLockCommand = new Command<T, Boolean>() {\r
- \r
- public void execute(T c, Boolean value, Object data) {\r
- c.setLocked(value);\r
- }\r
- };\r
- \r
- @Override\r
- protected void createActions() {\r
- super.createActions();\r
- createSetSplitPositionAction(CATEGORY_FEATURES);\r
- createSplitterClickListenerAction(CATEGORY_LISTENERS);\r
- createSplitterLockAction(CATEGORY_FEATURES);\r
- \r
- // Default to 100% x 100% as SplitPanel does not work as undefined\r
- for (T c : getTestComponents()) {\r
- c.setSizeFull();\r
- }\r
- }\r
- \r
- private void createSplitterLockAction(String categoryFeatures) {\r
- createBooleanAction("Splitter locked", categoryFeatures, false,\r
- splitterLockCommand);\r
- \r
- }\r
- \r
- public static class SplitPosition {\r
- \r
- private boolean reverse = false;\r
- private int position;\r
- private Unit unit;\r
- private String posString;\r
- \r
- public SplitPosition(String pos) {\r
- this.posString = pos;\r
- if (pos.startsWith("-")) {\r
- reverse = true;\r
- pos = pos.substring(1);\r
- }\r
- \r
- if (pos.endsWith("px")) {\r
- position = Integer.parseInt(pos.substring(0, pos.length() - 2));\r
- unit = Sizeable.Unit.PIXELS;\r
- } else if (pos.endsWith("%")) {\r
- position = Integer.parseInt(pos.substring(0, pos.length() - 1));\r
- unit = Sizeable.Unit.PERCENTAGE;\r
- } else {\r
- throw new RuntimeException("Could not parse " + pos);\r
- }\r
- }\r
- \r
- public void apply(AbstractSplitPanel sp) {\r
- sp.setSplitPosition(position, unit, reverse);\r
- }\r
- \r
- @Override\r
- public String toString() {\r
- return posString;\r
- }\r
- }\r
- \r
- private void createSetSplitPositionAction(String categoryFeatures) {\r
- String subCategory = "Set splitter position";\r
- createCategory(subCategory, categoryFeatures);\r
- \r
- createClickAction("0px from left/top", subCategory,\r
- setSplitPositionCommand, new SplitPosition("0px"));\r
- createClickAction("200px from left/top", subCategory,\r
- setSplitPositionCommand, new SplitPosition("200px"));\r
- createClickAction("0px from right/bottom", subCategory,\r
- setSplitPositionCommand, new SplitPosition("-0px"));\r
- createClickAction("200px from right/bottom", subCategory,\r
- setSplitPositionCommand, new SplitPosition("-200px"));\r
- \r
- createClickAction("0% from left/top", subCategory,\r
- setSplitPositionCommand, new SplitPosition("0%"));\r
- createClickAction("0% from right/bottom", subCategory,\r
- setSplitPositionCommand, new SplitPosition("-0%"));\r
- createClickAction("50% from left/top", subCategory,\r
- setSplitPositionCommand, new SplitPosition("50%"));\r
- createClickAction("50% from right/bottom", subCategory,\r
- setSplitPositionCommand, new SplitPosition("-50%"));\r
- createClickAction("100% from left/top", subCategory,\r
- setSplitPositionCommand, new SplitPosition("100%"));\r
- createClickAction("100% from right/bottom", subCategory,\r
- setSplitPositionCommand, new SplitPosition("-100%"));\r
- \r
- }\r
- \r
- private void createSplitterClickListenerAction(String category) {\r
- createBooleanAction("SplitterClickListener", category, false,\r
- splitterClickListenerCommand);\r
- \r
- }\r
- \r
- public void splitterClick(SplitterClickEvent event) {\r
- log(event.getClass().getSimpleName() + ": " + event.getButtonName()\r
- + " at " + event.getRelativeX() + "," + event.getRelativeY());\r
- }\r
- }\r
+ package com.vaadin.tests.components.splitpanel;
+
+ import com.vaadin.terminal.Sizeable;
++import com.vaadin.terminal.Sizeable.Unit;
+ import com.vaadin.tests.components.AbstractLayoutTest;
+ import com.vaadin.ui.AbstractSplitPanel;
+ import com.vaadin.ui.AbstractSplitPanel.SplitterClickEvent;
+ import com.vaadin.ui.AbstractSplitPanel.SplitterClickListener;
+
+ public abstract class AbstractSplitPanelTest<T extends AbstractSplitPanel>
+ extends AbstractLayoutTest<T> implements SplitterClickListener {
+
+ private Command<T, Boolean> splitterClickListenerCommand = new Command<T, Boolean>() {
+
+ public void execute(T c, Boolean value, Object data) {
+ if (value) {
+ c.addListener((SplitterClickListener) AbstractSplitPanelTest.this);
+ } else {
+ c.removeListener((SplitterClickListener) AbstractSplitPanelTest.this);
+ }
+
+ }
+ };
+ private Command<T, SplitPosition> setSplitPositionCommand = new Command<T, AbstractSplitPanelTest.SplitPosition>() {
+ public void execute(T c, SplitPosition value, Object data) {
+ value.apply(c);
+ }
+ };
+ private Command<T, Boolean> splitterLockCommand = new Command<T, Boolean>() {
+
+ public void execute(T c, Boolean value, Object data) {
+ c.setLocked(value);
+ }
+ };
+
+ @Override
+ protected void createActions() {
+ super.createActions();
+ createSetSplitPositionAction(CATEGORY_FEATURES);
+ createSplitterClickListenerAction(CATEGORY_LISTENERS);
+ createSplitterLockAction(CATEGORY_FEATURES);
+
+ // Default to 100% x 100% as SplitPanel does not work as undefined
+ for (T c : getTestComponents()) {
+ c.setSizeFull();
+ }
+ }
+
+ private void createSplitterLockAction(String categoryFeatures) {
+ createBooleanAction("Splitter locked", categoryFeatures, false,
+ splitterLockCommand);
+
+ }
+
+ public static class SplitPosition {
+
+ private boolean reverse = false;
+ private int position;
- private int unit;
++ private Unit unit;
+ private String posString;
+
+ public SplitPosition(String pos) {
+ this.posString = pos;
+ if (pos.startsWith("-")) {
+ reverse = true;
+ pos = pos.substring(1);
+ }
+
+ if (pos.endsWith("px")) {
+ position = Integer.parseInt(pos.substring(0, pos.length() - 2));
- unit = Sizeable.UNITS_PIXELS;
++ unit = Sizeable.Unit.PIXELS;
+ } else if (pos.endsWith("%")) {
+ position = Integer.parseInt(pos.substring(0, pos.length() - 1));
- unit = Sizeable.UNITS_PERCENTAGE;
++ unit = Sizeable.Unit.PERCENTAGE;
+ } else {
+ throw new RuntimeException("Could not parse " + pos);
+ }
+ }
+
+ public void apply(AbstractSplitPanel sp) {
+ sp.setSplitPosition(position, unit, reverse);
+ }
+
+ @Override
+ public String toString() {
+ return posString;
+ }
+ }
+
+ private void createSetSplitPositionAction(String categoryFeatures) {
+ String subCategory = "Set splitter position";
+ createCategory(subCategory, categoryFeatures);
+
+ createClickAction("0px from left/top", subCategory,
+ setSplitPositionCommand, new SplitPosition("0px"));
+ createClickAction("200px from left/top", subCategory,
+ setSplitPositionCommand, new SplitPosition("200px"));
+ createClickAction("0px from right/bottom", subCategory,
+ setSplitPositionCommand, new SplitPosition("-0px"));
+ createClickAction("200px from right/bottom", subCategory,
+ setSplitPositionCommand, new SplitPosition("-200px"));
+
+ createClickAction("0% from left/top", subCategory,
+ setSplitPositionCommand, new SplitPosition("0%"));
+ createClickAction("0% from right/bottom", subCategory,
+ setSplitPositionCommand, new SplitPosition("-0%"));
+ createClickAction("50% from left/top", subCategory,
+ setSplitPositionCommand, new SplitPosition("50%"));
+ createClickAction("50% from right/bottom", subCategory,
+ setSplitPositionCommand, new SplitPosition("-50%"));
+ createClickAction("100% from left/top", subCategory,
+ setSplitPositionCommand, new SplitPosition("100%"));
+ createClickAction("100% from right/bottom", subCategory,
+ setSplitPositionCommand, new SplitPosition("-100%"));
+
+ }
+
+ private void createSplitterClickListenerAction(String category) {
+ createBooleanAction("SplitterClickListener", category, false,
+ splitterClickListenerCommand);
+
+ }
+
+ public void splitterClick(SplitterClickEvent event) {
+ log(event.getClass().getSimpleName() + ": " + event.getButtonName()
+ + " at " + event.getRelativeX() + "," + event.getRelativeY());
+ }
+ }
- package com.vaadin.tests.components.splitpanel;\r
- \r
- import com.vaadin.terminal.Sizeable;\r
- import com.vaadin.tests.components.AbstractTestCase;\r
- import com.vaadin.ui.Button;\r
- import com.vaadin.ui.Button.ClickEvent;\r
- import com.vaadin.ui.Button.ClickListener;\r
- import com.vaadin.ui.HorizontalLayout;\r
- import com.vaadin.ui.HorizontalSplitPanel;\r
- import com.vaadin.ui.NativeButton;\r
- import com.vaadin.ui.Root.LegacyWindow;\r
- \r
- public class SplitPanelExtraScrollbars extends AbstractTestCase implements\r
- ClickListener {\r
- \r
- private HorizontalSplitPanel sp;\r
- private HorizontalLayout hl;\r
- private Button b;\r
- \r
- @Override\r
- public void init() {\r
- sp = new HorizontalSplitPanel();\r
- sp.setSizeFull();\r
- sp.setSplitPosition(0, Sizeable.UNITS_PIXELS);\r
- \r
- hl = new HorizontalLayout();\r
- hl.setMargin(true);\r
- hl.setWidth("100%");\r
- hl.setHeight(null);\r
- \r
- b = createButton("200px");\r
- sp.setSecondComponent(hl);\r
- hl.addComponent(b);\r
- \r
- LegacyWindow w = new LegacyWindow("Test", sp);\r
- setMainWindow(w);\r
- }\r
- \r
- private Button createButton(String height) {\r
- Button b = new NativeButton("A BIG button");\r
- b.setHeight(height);\r
- b.addListener(this);\r
- return b;\r
- }\r
- \r
- @Override\r
- protected String getDescription() {\r
- return "Click the button to change its height. Making the button higher than the browser should not cause vertical but not horizontal scrollbars to appear.";\r
- }\r
- \r
- @Override\r
- protected Integer getTicketNumber() {\r
- return 3458;\r
- }\r
- \r
- public void buttonClick(ClickEvent event) {\r
- if (b.getHeight() == 200) {\r
- b.setHeight("1200px");\r
- } else {\r
- b.setHeight("200px");\r
- }\r
- \r
- // Sending all changes in one repaint triggers the bug\r
- hl.requestRepaint();\r
- sp.requestRepaint();\r
- }\r
- \r
- }\r
+ package com.vaadin.tests.components.splitpanel;
+
+ import com.vaadin.terminal.Sizeable;
+ import com.vaadin.tests.components.AbstractTestCase;
+ import com.vaadin.ui.Button;
+ import com.vaadin.ui.Button.ClickEvent;
+ import com.vaadin.ui.Button.ClickListener;
+ import com.vaadin.ui.HorizontalLayout;
+ import com.vaadin.ui.HorizontalSplitPanel;
+ import com.vaadin.ui.NativeButton;
-import com.vaadin.ui.Window;
++import com.vaadin.ui.Root.LegacyWindow;
+
+ public class SplitPanelExtraScrollbars extends AbstractTestCase implements
+ ClickListener {
+
+ private HorizontalSplitPanel sp;
+ private HorizontalLayout hl;
+ private Button b;
+
+ @Override
+ public void init() {
+ sp = new HorizontalSplitPanel();
+ sp.setSizeFull();
+ sp.setSplitPosition(0, Sizeable.UNITS_PIXELS);
+
+ hl = new HorizontalLayout();
+ hl.setMargin(true);
+ hl.setWidth("100%");
+ hl.setHeight(null);
+
+ b = createButton("200px");
+ sp.setSecondComponent(hl);
+ hl.addComponent(b);
+
- Window w = new Window("Test", sp);
++ LegacyWindow w = new LegacyWindow("Test", sp);
+ setMainWindow(w);
+ }
+
+ private Button createButton(String height) {
+ Button b = new NativeButton("A BIG button");
+ b.setHeight(height);
+ b.addListener(this);
+ return b;
+ }
+
+ @Override
+ protected String getDescription() {
+ return "Click the button to change its height. Making the button higher than the browser should not cause vertical but not horizontal scrollbars to appear.";
+ }
+
+ @Override
+ protected Integer getTicketNumber() {
+ return 3458;
+ }
+
+ public void buttonClick(ClickEvent event) {
+ if (b.getHeight() == 200) {
+ b.setHeight("1200px");
+ } else {
+ b.setHeight("200px");
+ }
+
+ // Sending all changes in one repaint triggers the bug
+ hl.requestRepaint();
+ sp.requestRepaint();
+ }
+
+ }
- package com.vaadin.tests.components.splitpanel;\r
- \r
- import com.vaadin.terminal.Sizeable;\r
- import com.vaadin.tests.components.AbstractTestCase;\r
- import com.vaadin.ui.Button;\r
- import com.vaadin.ui.HorizontalSplitPanel;\r
- import com.vaadin.ui.NativeButton;\r
- import com.vaadin.ui.Root.LegacyWindow;\r
- import com.vaadin.ui.TextField;\r
- import com.vaadin.ui.VerticalLayout;\r
- \r
- public class SplitPanelWidthOnResize extends AbstractTestCase {\r
- \r
- @Override\r
- public void init() {\r
- VerticalLayout layout = new VerticalLayout();\r
- layout.setSizeFull();\r
- LegacyWindow w = new LegacyWindow("", layout);\r
- setMainWindow(w);\r
- HorizontalSplitPanel splitPanel = new HorizontalSplitPanel();\r
- Button button = new NativeButton("A huge button");\r
- button.setSizeFull();\r
- TextField textField = new TextField("A small textfield");\r
- \r
- splitPanel.setFirstComponent(button);\r
- splitPanel.setSecondComponent(textField);\r
- splitPanel.setSizeFull();\r
- splitPanel.setSplitPosition(100, Sizeable.UNITS_PERCENTAGE);\r
- \r
- layout.addComponent(splitPanel);\r
- }\r
- \r
- @Override\r
- protected String getDescription() {\r
- return "Make the browser window smaller and then larger again. The huge button should always stay visible and the TextField should never be shown.";\r
- }\r
- \r
- @Override\r
- protected Integer getTicketNumber() {\r
- return 3322;\r
- }\r
- \r
- }\r
+ package com.vaadin.tests.components.splitpanel;
+
+ import com.vaadin.terminal.Sizeable;
+ import com.vaadin.tests.components.AbstractTestCase;
+ import com.vaadin.ui.Button;
+ import com.vaadin.ui.HorizontalSplitPanel;
+ import com.vaadin.ui.NativeButton;
++import com.vaadin.ui.Root.LegacyWindow;
+ import com.vaadin.ui.TextField;
+ import com.vaadin.ui.VerticalLayout;
-import com.vaadin.ui.Window;
+
+ public class SplitPanelWidthOnResize extends AbstractTestCase {
+
+ @Override
+ public void init() {
+ VerticalLayout layout = new VerticalLayout();
+ layout.setSizeFull();
- Window w = new Window("", layout);
++ LegacyWindow w = new LegacyWindow("", layout);
+ setMainWindow(w);
+ HorizontalSplitPanel splitPanel = new HorizontalSplitPanel();
+ Button button = new NativeButton("A huge button");
+ button.setSizeFull();
+ TextField textField = new TextField("A small textfield");
+
+ splitPanel.setFirstComponent(button);
+ splitPanel.setSecondComponent(textField);
+ splitPanel.setSizeFull();
+ splitPanel.setSplitPosition(100, Sizeable.UNITS_PERCENTAGE);
+
+ layout.addComponent(splitPanel);
+ }
+
+ @Override
+ protected String getDescription() {
+ return "Make the browser window smaller and then larger again. The huge button should always stay visible and the TextField should never be shown.";
+ }
+
+ @Override
+ protected Integer getTicketNumber() {
+ return 3322;
+ }
+
+ }
--- /dev/null
- package com.vaadin.tests.components.table;\r
- \r
- import java.math.BigDecimal;\r
- import java.text.NumberFormat;\r
- import java.util.Date;\r
- import java.util.Locale;\r
- \r
- import com.vaadin.data.Property.ValueChangeEvent;\r
- import com.vaadin.data.Property.ValueChangeListener;\r
- import com.vaadin.data.util.BeanItemContainer;\r
- import com.vaadin.data.util.converter.Converter;\r
- import com.vaadin.data.util.converter.StringToNumberConverter;\r
- import com.vaadin.tests.components.TestBase;\r
- import com.vaadin.tests.data.bean.Address;\r
- import com.vaadin.tests.data.bean.Country;\r
- import com.vaadin.tests.data.bean.Person;\r
- import com.vaadin.tests.data.bean.Sex;\r
- import com.vaadin.tests.util.Log;\r
- import com.vaadin.ui.CheckBox;\r
- import com.vaadin.ui.ComboBox;\r
- import com.vaadin.ui.Table;\r
- \r
- public class DoublesInTable extends TestBase {\r
- BeanItemContainer<Person> personBeanItemContainer = new BeanItemContainer<Person>(\r
- Person.class);\r
- \r
- private Table table;\r
- \r
- private Log log = new Log(5);\r
- \r
- private ComboBox localeSelect;\r
- \r
- private CheckBox useCustomConverters;\r
- \r
- private CheckBox editMode;\r
- \r
- @Override\r
- protected void setup() {\r
- editMode = new CheckBox("Edit mode");\r
- editMode.setImmediate(true);\r
- editMode.addListener(new ValueChangeListener() {\r
- \r
- public void valueChange(ValueChangeEvent event) {\r
- table.setEditable(editMode.getValue());\r
- \r
- }\r
- });\r
- \r
- useCustomConverters = new CheckBox("Use custom converters");\r
- useCustomConverters.setImmediate(true);\r
- useCustomConverters.addListener(new ValueChangeListener() {\r
- \r
- public void valueChange(ValueChangeEvent event) {\r
- recreateTable();\r
- }\r
- });\r
- \r
- localeSelect = createLocaleSelect();\r
- personBeanItemContainer = createContainer(100);\r
- addComponent(log);\r
- addComponent(localeSelect);\r
- addComponent(useCustomConverters);\r
- addComponent(editMode);\r
- recreateTable();\r
- \r
- }\r
- \r
- private ComboBox createLocaleSelect() {\r
- ComboBox cb = new ComboBox();\r
- cb.setNullSelectionAllowed(false);\r
- for (Locale l : Locale.getAvailableLocales()) {\r
- cb.addItem(l);\r
- }\r
- cb.setImmediate(true);\r
- cb.setValue(Locale.US);\r
- cb.addListener(new ValueChangeListener() {\r
- \r
- public void valueChange(ValueChangeEvent event) {\r
- recreateTable();\r
- }\r
- });\r
- return cb;\r
- }\r
- \r
- protected void recreateTable() {\r
- Table newTable = createTable(useCustomConverters.getValue(),\r
- (Locale) localeSelect.getValue());\r
- newTable.setEditable(editMode.getValue());\r
- if (table == null) {\r
- addComponent(newTable);\r
- } else {\r
- replaceComponent(table, newTable);\r
- }\r
- table = newTable;\r
- }\r
- \r
- private static BeanItemContainer<Person> createContainer(int nr) {\r
- BeanItemContainer<Person> bic = new BeanItemContainer<Person>(\r
- Person.class);\r
- for (int i = 1; i <= nr; i++) {\r
- Person p = new Person();\r
- p.setFirstName("First " + i);\r
- p.setLastName("Last " + i);\r
- p.setAge(i);\r
- p.setDeceased((i % 5 - 2) == 0);\r
- p.setEmail("person" + i + "@mail.com");\r
- p.setRent(new BigDecimal(i * 1250.25));\r
- p.setSalary(3000 + i);\r
- p.setSex((i % 4) == 0 ? Sex.MALE : Sex.FEMALE);\r
- p.setBirthDate(new Date(2011 - 1900 - p.getAge(), 11 - 1, 24));\r
- if (i % 42 == 0) {\r
- p.setSex(Sex.UNKNOWN);\r
- }\r
- String city = "City " + (i / 10);\r
- Country country = Country.FINLAND;\r
- Address address = new Address("Street " + i, 12345 + i * 2, city,\r
- country);\r
- p.setAddress(address);\r
- bic.addBean(p);\r
- }\r
- \r
- return bic;\r
- }\r
- \r
- protected Table createTable(boolean useCustomConverters, Locale locale) {\r
- Table t = new Table("Persons");\r
- t.setLocale(locale);\r
- t.setContainerDataSource(personBeanItemContainer);\r
- t.setSortDisabled(false);\r
- if (useCustomConverters) {\r
- addConverters(t);\r
- }\r
- t.setSelectable(true);\r
- t.setImmediate(true);\r
- t.addListener(new ValueChangeListener() {\r
- \r
- public void valueChange(ValueChangeEvent event) {\r
- log.log("Value is now: " + event.getProperty().getValue());\r
- \r
- }\r
- });\r
- return t;\r
- }\r
- \r
- private void addConverters(Table t) {\r
- t.setConverter("sex", new Converter<String, Sex>() {\r
- \r
- public Sex convertToModel(String value, Locale locale)\r
- throws com.vaadin.data.util.converter.Converter.ConversionException {\r
- // not used in this test - Table only converts to presentation\r
- return null;\r
- }\r
- \r
- public String convertToPresentation(Sex value, Locale locale)\r
- throws com.vaadin.data.util.converter.Converter.ConversionException {\r
- if (value == null) {\r
- value = Sex.UNKNOWN;\r
- }\r
- return value.getStringRepresentation();\r
- }\r
- \r
- public Class<Sex> getModelType() {\r
- return Sex.class;\r
- }\r
- \r
- public Class<String> getPresentationType() {\r
- return String.class;\r
- }\r
- });\r
- t.setConverter("deceased", new Converter<String, Boolean>() {\r
- \r
- public Boolean convertToModel(String value, Locale locale) {\r
- // not used in this test - Table only converts from source to\r
- // target\r
- return null;\r
- }\r
- \r
- public String convertToPresentation(Boolean value, Locale locale) {\r
- if (value == null || value) {\r
- return "YES, DEAD!";\r
- } else {\r
- return "-";\r
- }\r
- }\r
- \r
- public Class<Boolean> getModelType() {\r
- return Boolean.class;\r
- }\r
- \r
- public Class<String> getPresentationType() {\r
- return String.class;\r
- }\r
- });\r
- t.setConverter("age", new Converter<String, Integer>() {\r
- \r
- public Integer convertToModel(String value, Locale locale)\r
- throws com.vaadin.data.util.converter.Converter.ConversionException {\r
- // not used in this test - Table only converts from source to\r
- // target\r
- return null;\r
- }\r
- \r
- public String convertToPresentation(Integer value, Locale locale)\r
- throws com.vaadin.data.util.converter.Converter.ConversionException {\r
- if (value == null) {\r
- return null;\r
- }\r
- if (value < 3) {\r
- return value + " (baby)";\r
- } else if (value < 7) {\r
- return value + " (kid)";\r
- } else if (value < 18) {\r
- return value + " (young)";\r
- } else {\r
- return value + "";\r
- }\r
- }\r
- \r
- public Class<Integer> getModelType() {\r
- return Integer.class;\r
- }\r
- \r
- public Class<String> getPresentationType() {\r
- return String.class;\r
- }\r
- });\r
- t.setConverter("address", new Converter<String, Address>() {\r
- \r
- public Address convertToModel(String value, Locale locale)\r
- throws ConversionException {\r
- // not used in this test - Table only converts to presentation\r
- return null;\r
- }\r
- \r
- public String convertToPresentation(Address value, Locale locale)\r
- throws ConversionException {\r
- return value.getStreetAddress() + ", " + value.getCity() + " ("\r
- + value.getCountry() + ")";\r
- }\r
- \r
- public Class<Address> getModelType() {\r
- return Address.class;\r
- }\r
- \r
- public Class<String> getPresentationType() {\r
- return String.class;\r
- }\r
- \r
- });\r
- \r
- t.setConverter("rent", new StringToNumberConverter() {\r
- @Override\r
- protected NumberFormat getFormat(Locale locale) {\r
- return NumberFormat.getCurrencyInstance(locale);\r
- // DecimalFormat df = new DecimalFormat();\r
- // df.setDecimalSeparatorAlwaysShown(true);\r
- // df.setGroupingUsed(true);\r
- // df.setMinimumFractionDigits(2);\r
- // df.setMaximumFractionDigits(2);\r
- // return df;\r
- }\r
- });\r
- }\r
- \r
- @Override\r
- protected String getDescription() {\r
- // TODO Auto-generated method stub\r
- return null;\r
- }\r
- \r
- @Override\r
- protected Integer getTicketNumber() {\r
- // TODO Auto-generated method stub\r
- return null;\r
- }\r
- \r
- }\r
++package com.vaadin.tests.components.table;
++
++import java.math.BigDecimal;
++import java.text.NumberFormat;
++import java.util.Date;
++import java.util.Locale;
++
++import com.vaadin.data.Property.ValueChangeEvent;
++import com.vaadin.data.Property.ValueChangeListener;
++import com.vaadin.data.util.BeanItemContainer;
++import com.vaadin.data.util.converter.Converter;
++import com.vaadin.data.util.converter.StringToNumberConverter;
++import com.vaadin.tests.components.TestBase;
++import com.vaadin.tests.data.bean.Address;
++import com.vaadin.tests.data.bean.Country;
++import com.vaadin.tests.data.bean.Person;
++import com.vaadin.tests.data.bean.Sex;
++import com.vaadin.tests.util.Log;
++import com.vaadin.ui.CheckBox;
++import com.vaadin.ui.ComboBox;
++import com.vaadin.ui.Table;
++
++public class DoublesInTable extends TestBase {
++ BeanItemContainer<Person> personBeanItemContainer = new BeanItemContainer<Person>(
++ Person.class);
++
++ private Table table;
++
++ private Log log = new Log(5);
++
++ private ComboBox localeSelect;
++
++ private CheckBox useCustomConverters;
++
++ private CheckBox editMode;
++
++ @Override
++ protected void setup() {
++ editMode = new CheckBox("Edit mode");
++ editMode.setImmediate(true);
++ editMode.addListener(new ValueChangeListener() {
++
++ public void valueChange(ValueChangeEvent event) {
++ table.setEditable(editMode.getValue());
++
++ }
++ });
++
++ useCustomConverters = new CheckBox("Use custom converters");
++ useCustomConverters.setImmediate(true);
++ useCustomConverters.addListener(new ValueChangeListener() {
++
++ public void valueChange(ValueChangeEvent event) {
++ recreateTable();
++ }
++ });
++
++ localeSelect = createLocaleSelect();
++ personBeanItemContainer = createContainer(100);
++ addComponent(log);
++ addComponent(localeSelect);
++ addComponent(useCustomConverters);
++ addComponent(editMode);
++ recreateTable();
++
++ }
++
++ private ComboBox createLocaleSelect() {
++ ComboBox cb = new ComboBox();
++ cb.setNullSelectionAllowed(false);
++ for (Locale l : Locale.getAvailableLocales()) {
++ cb.addItem(l);
++ }
++ cb.setImmediate(true);
++ cb.setValue(Locale.US);
++ cb.addListener(new ValueChangeListener() {
++
++ public void valueChange(ValueChangeEvent event) {
++ recreateTable();
++ }
++ });
++ return cb;
++ }
++
++ protected void recreateTable() {
++ Table newTable = createTable(useCustomConverters.getValue(),
++ (Locale) localeSelect.getValue());
++ newTable.setEditable(editMode.getValue());
++ if (table == null) {
++ addComponent(newTable);
++ } else {
++ replaceComponent(table, newTable);
++ }
++ table = newTable;
++ }
++
++ private static BeanItemContainer<Person> createContainer(int nr) {
++ BeanItemContainer<Person> bic = new BeanItemContainer<Person>(
++ Person.class);
++ for (int i = 1; i <= nr; i++) {
++ Person p = new Person();
++ p.setFirstName("First " + i);
++ p.setLastName("Last " + i);
++ p.setAge(i);
++ p.setDeceased((i % 5 - 2) == 0);
++ p.setEmail("person" + i + "@mail.com");
++ p.setRent(new BigDecimal(i * 1250.25));
++ p.setSalary(3000 + i);
++ p.setSex((i % 4) == 0 ? Sex.MALE : Sex.FEMALE);
++ p.setBirthDate(new Date(2011 - 1900 - p.getAge(), 11 - 1, 24));
++ if (i % 42 == 0) {
++ p.setSex(Sex.UNKNOWN);
++ }
++ String city = "City " + (i / 10);
++ Country country = Country.FINLAND;
++ Address address = new Address("Street " + i, 12345 + i * 2, city,
++ country);
++ p.setAddress(address);
++ bic.addBean(p);
++ }
++
++ return bic;
++ }
++
++ protected Table createTable(boolean useCustomConverters, Locale locale) {
++ Table t = new Table("Persons");
++ t.setLocale(locale);
++ t.setContainerDataSource(personBeanItemContainer);
++ t.setSortDisabled(false);
++ if (useCustomConverters) {
++ addConverters(t);
++ }
++ t.setSelectable(true);
++ t.setImmediate(true);
++ t.addListener(new ValueChangeListener() {
++
++ public void valueChange(ValueChangeEvent event) {
++ log.log("Value is now: " + event.getProperty().getValue());
++
++ }
++ });
++ return t;
++ }
++
++ private void addConverters(Table t) {
++ t.setConverter("sex", new Converter<String, Sex>() {
++
++ public Sex convertToModel(String value, Locale locale)
++ throws com.vaadin.data.util.converter.Converter.ConversionException {
++ // not used in this test - Table only converts to presentation
++ return null;
++ }
++
++ public String convertToPresentation(Sex value, Locale locale)
++ throws com.vaadin.data.util.converter.Converter.ConversionException {
++ if (value == null) {
++ value = Sex.UNKNOWN;
++ }
++ return value.getStringRepresentation();
++ }
++
++ public Class<Sex> getModelType() {
++ return Sex.class;
++ }
++
++ public Class<String> getPresentationType() {
++ return String.class;
++ }
++ });
++ t.setConverter("deceased", new Converter<String, Boolean>() {
++
++ public Boolean convertToModel(String value, Locale locale) {
++ // not used in this test - Table only converts from source to
++ // target
++ return null;
++ }
++
++ public String convertToPresentation(Boolean value, Locale locale) {
++ if (value == null || value) {
++ return "YES, DEAD!";
++ } else {
++ return "-";
++ }
++ }
++
++ public Class<Boolean> getModelType() {
++ return Boolean.class;
++ }
++
++ public Class<String> getPresentationType() {
++ return String.class;
++ }
++ });
++ t.setConverter("age", new Converter<String, Integer>() {
++
++ public Integer convertToModel(String value, Locale locale)
++ throws com.vaadin.data.util.converter.Converter.ConversionException {
++ // not used in this test - Table only converts from source to
++ // target
++ return null;
++ }
++
++ public String convertToPresentation(Integer value, Locale locale)
++ throws com.vaadin.data.util.converter.Converter.ConversionException {
++ if (value == null) {
++ return null;
++ }
++ if (value < 3) {
++ return value + " (baby)";
++ } else if (value < 7) {
++ return value + " (kid)";
++ } else if (value < 18) {
++ return value + " (young)";
++ } else {
++ return value + "";
++ }
++ }
++
++ public Class<Integer> getModelType() {
++ return Integer.class;
++ }
++
++ public Class<String> getPresentationType() {
++ return String.class;
++ }
++ });
++ t.setConverter("address", new Converter<String, Address>() {
++
++ public Address convertToModel(String value, Locale locale)
++ throws ConversionException {
++ // not used in this test - Table only converts to presentation
++ return null;
++ }
++
++ public String convertToPresentation(Address value, Locale locale)
++ throws ConversionException {
++ return value.getStreetAddress() + ", " + value.getCity() + " ("
++ + value.getCountry() + ")";
++ }
++
++ public Class<Address> getModelType() {
++ return Address.class;
++ }
++
++ public Class<String> getPresentationType() {
++ return String.class;
++ }
++
++ });
++
++ t.setConverter("rent", new StringToNumberConverter() {
++ @Override
++ protected NumberFormat getFormat(Locale locale) {
++ return NumberFormat.getCurrencyInstance(locale);
++ // DecimalFormat df = new DecimalFormat();
++ // df.setDecimalSeparatorAlwaysShown(true);
++ // df.setGroupingUsed(true);
++ // df.setMinimumFractionDigits(2);
++ // df.setMaximumFractionDigits(2);
++ // return df;
++ }
++ });
++ }
++
++ @Override
++ protected String getDescription() {
++ // TODO Auto-generated method stub
++ return null;
++ }
++
++ @Override
++ protected Integer getTicketNumber() {
++ // TODO Auto-generated method stub
++ return null;
++ }
++
++}
- package com.vaadin.tests.components.table;\r
- \r
- import java.text.DateFormat;\r
- import java.util.Calendar;\r
- import java.util.Date;\r
- import java.util.Locale;\r
- \r
- import com.vaadin.data.Container;\r
- import com.vaadin.event.ItemClickEvent;\r
- import com.vaadin.tests.components.TestBase;\r
- import com.vaadin.ui.Component;\r
- import com.vaadin.ui.DefaultFieldFactory;\r
- import com.vaadin.ui.Field;\r
- import com.vaadin.ui.Table;\r
- import com.vaadin.ui.TableFieldFactory;\r
- \r
- public class EditableModeChange extends TestBase {\r
- \r
- private ItemClickEvent selectionEvent;\r
- \r
- private final String[] names = { "Teemu", "Teppo", "Seppo", "Matti",\r
- "Pekka" };\r
- \r
- @Override\r
- public void setup() {\r
- \r
- final Table items = new Table("Items - double-click to edit");\r
- items.setSelectable(true);\r
- items.addContainerProperty("name", String.class, "");\r
- items.addContainerProperty("birthday", Date.class, "");\r
- \r
- final TableFieldFactory fieldFactory = new ItemFieldFactory();\r
- items.setTableFieldFactory(fieldFactory);\r
- \r
- Calendar cal = Calendar.getInstance();\r
- cal.set(2010, 7, 12, 12, 7, 54);\r
- \r
- for (String name : names) {\r
- items.addItem(name);\r
- items.getItem(name).getItemProperty("name").setValue(name);\r
- items.getItem(name).getItemProperty("birthday")\r
- .setValue(new FormattedDate(cal.getTime().getTime()));\r
- }\r
- \r
- items.addListener(new ItemClickEvent.ItemClickListener() {\r
- \r
- public void itemClick(ItemClickEvent event) {\r
- if (event.isDoubleClick()) {\r
- selectionEvent = event;\r
- items.setEditable(true);\r
- } else if (items.isEditable()) {\r
- items.setEditable(false);\r
- }\r
- }\r
- });\r
- \r
- addComponent(items);\r
- }\r
- \r
- private class FormattedDate extends Date {\r
- \r
- private DateFormat formatter = DateFormat.getDateTimeInstance(\r
- DateFormat.MEDIUM, DateFormat.MEDIUM, new Locale("en", "US"));\r
- \r
- public FormattedDate(long time) {\r
- super(time);\r
- }\r
- \r
- @Override\r
- public String toString() {\r
- return formatter.format(this);\r
- }\r
- }\r
- \r
- private class ItemFieldFactory extends DefaultFieldFactory {\r
- @Override\r
- public Field<?> createField(Container container, Object itemId,\r
- Object propertyId, Component uiContext) {\r
- if (selectionEvent != null) {\r
- if ((selectionEvent.getItemId().equals(itemId))\r
- && (selectionEvent.getPropertyId().equals(propertyId))) {\r
- return super.createField(container, itemId, propertyId,\r
- uiContext);\r
- }\r
- }\r
- return null;\r
- }\r
- }\r
- \r
- @Override\r
- protected String getDescription() {\r
- return "Double click a cell to edit, then click on another row to select it (editmode is set to false). The clicked row should now be selected without any flickering.";\r
- }\r
- \r
- @Override\r
- protected Integer getTicketNumber() {\r
- return 5427;\r
- }\r
+ package com.vaadin.tests.components.table;
+
+ import java.text.DateFormat;
+ import java.util.Calendar;
+ import java.util.Date;
+ import java.util.Locale;
+
+ import com.vaadin.data.Container;
+ import com.vaadin.event.ItemClickEvent;
+ import com.vaadin.tests.components.TestBase;
+ import com.vaadin.ui.Component;
+ import com.vaadin.ui.DefaultFieldFactory;
+ import com.vaadin.ui.Field;
+ import com.vaadin.ui.Table;
+ import com.vaadin.ui.TableFieldFactory;
+
+ public class EditableModeChange extends TestBase {
+
+ private ItemClickEvent selectionEvent;
+
+ private final String[] names = { "Teemu", "Teppo", "Seppo", "Matti",
+ "Pekka" };
+
+ @Override
+ public void setup() {
+
+ final Table items = new Table("Items - double-click to edit");
+ items.setSelectable(true);
+ items.addContainerProperty("name", String.class, "");
+ items.addContainerProperty("birthday", Date.class, "");
+
+ final TableFieldFactory fieldFactory = new ItemFieldFactory();
+ items.setTableFieldFactory(fieldFactory);
+
+ Calendar cal = Calendar.getInstance();
+ cal.set(2010, 7, 12, 12, 7, 54);
+
+ for (String name : names) {
+ items.addItem(name);
+ items.getItem(name).getItemProperty("name").setValue(name);
+ items.getItem(name).getItemProperty("birthday")
+ .setValue(new FormattedDate(cal.getTime().getTime()));
+ }
+
+ items.addListener(new ItemClickEvent.ItemClickListener() {
+
+ public void itemClick(ItemClickEvent event) {
+ if (event.isDoubleClick()) {
+ selectionEvent = event;
+ items.setEditable(true);
+ } else if (items.isEditable()) {
+ items.setEditable(false);
+ }
+ }
+ });
+
+ addComponent(items);
+ }
+
+ private class FormattedDate extends Date {
+
+ private DateFormat formatter = DateFormat.getDateTimeInstance(
+ DateFormat.MEDIUM, DateFormat.MEDIUM, new Locale("en", "US"));
+
+ public FormattedDate(long time) {
+ super(time);
+ }
+
+ @Override
+ public String toString() {
+ return formatter.format(this);
+ }
+ }
+
+ private class ItemFieldFactory extends DefaultFieldFactory {
+ @Override
- public Field createField(Container container, Object itemId,
++ public Field<?> createField(Container container, Object itemId,
+ Object propertyId, Component uiContext) {
+ if (selectionEvent != null) {
+ if ((selectionEvent.getItemId().equals(itemId))
+ && (selectionEvent.getPropertyId().equals(propertyId))) {
+ return super.createField(container, itemId, propertyId,
+ uiContext);
+ }
+ }
+ return null;
+ }
+ }
+
+ @Override
+ protected String getDescription() {
+ return "Double click a cell to edit, then click on another row to select it (editmode is set to false). The clicked row should now be selected without any flickering.";
+ }
+
+ @Override
+ protected Integer getTicketNumber() {
+ return 5427;
+ }
}
- package com.vaadin.tests.components.table;\r
- \r
- import java.util.ArrayList;\r
- import java.util.List;\r
- \r
- import com.vaadin.data.util.BeanItemContainer;\r
- import com.vaadin.tests.components.TestBase;\r
- import com.vaadin.tests.util.Person;\r
- import com.vaadin.ui.HorizontalLayout;\r
- import com.vaadin.ui.Root.LegacyWindow;\r
- import com.vaadin.ui.Table;\r
- \r
- public class ScrollCausesRequestLoop extends TestBase {\r
- \r
- @Override\r
- protected void setup() {\r
- setMainWindow(new LegacyWindow("", new TestView()));\r
- }\r
- \r
- @Override\r
- protected String getDescription() {\r
- return "Scrolling a table causes an infinite loop of UIDL requests in some cases";\r
- }\r
- \r
- @Override\r
- protected Integer getTicketNumber() {\r
- return 8040;\r
- }\r
- \r
- private static class TestView extends HorizontalLayout {\r
- \r
- TestView() {\r
- Table table = new Table();\r
- List<Person> data = createData();\r
- BeanItemContainer<Person> container = new BeanItemContainer<Person>(\r
- Person.class, data) {\r
- \r
- @Override\r
- public Person getIdByIndex(int index) {\r
- try {\r
- // Simulate some loading delay with some exaggeration\r
- // to make easier to reproduce\r
- Thread.sleep(50);\r
- } catch (InterruptedException e) {\r
- Thread.currentThread().interrupt();\r
- throw new RuntimeException(e);\r
- }\r
- return super.getIdByIndex(index);\r
- }\r
- };\r
- table.setContainerDataSource(container);\r
- addComponent(table);\r
- }\r
- }\r
- \r
- private static List<Person> createData() {\r
- int count = 500;\r
- List<Person> data = new ArrayList<Person>(count);\r
- for (int i = 0; i < count; i++) {\r
- data.add(new Person("Person", "" + i, "Email", "Phone", "Street",\r
- 12345, "City"));\r
- }\r
- return data;\r
- }\r
- }\r
+ package com.vaadin.tests.components.table;
+
+ import java.util.ArrayList;
+ import java.util.List;
+
+ import com.vaadin.data.util.BeanItemContainer;
+ import com.vaadin.tests.components.TestBase;
+ import com.vaadin.tests.util.Person;
+ import com.vaadin.ui.HorizontalLayout;
++import com.vaadin.ui.Root.LegacyWindow;
+ import com.vaadin.ui.Table;
-import com.vaadin.ui.Window;
+
+ public class ScrollCausesRequestLoop extends TestBase {
+
+ @Override
+ protected void setup() {
- setMainWindow(new Window("", new TestView()));
++ setMainWindow(new LegacyWindow("", new TestView()));
+ }
+
+ @Override
+ protected String getDescription() {
+ return "Scrolling a table causes an infinite loop of UIDL requests in some cases";
+ }
+
+ @Override
+ protected Integer getTicketNumber() {
+ return 8040;
+ }
+
+ private static class TestView extends HorizontalLayout {
+
+ TestView() {
+ Table table = new Table();
+ List<Person> data = createData();
+ BeanItemContainer<Person> container = new BeanItemContainer<Person>(
+ Person.class, data) {
+
+ @Override
+ public Person getIdByIndex(int index) {
+ try {
+ // Simulate some loading delay with some exaggeration
+ // to make easier to reproduce
+ Thread.sleep(50);
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ throw new RuntimeException(e);
+ }
+ return super.getIdByIndex(index);
+ }
+ };
+ table.setContainerDataSource(container);
+ addComponent(table);
+ }
+ }
+
+ private static List<Person> createData() {
+ int count = 500;
+ List<Person> data = new ArrayList<Person>(count);
+ for (int i = 0; i < count; i++) {
+ data.add(new Person("Person", "" + i, "Email", "Phone", "Street",
+ 12345, "City"));
+ }
+ return data;
+ }
+ }
- package com.vaadin.tests.components.table;\r
- \r
- import com.vaadin.data.Property.ValueChangeEvent;\r
- import com.vaadin.data.Property.ValueChangeListener;\r
- import com.vaadin.event.ItemClickEvent;\r
- import com.vaadin.event.ItemClickEvent.ItemClickListener;\r
- import com.vaadin.tests.components.TestBase;\r
- import com.vaadin.ui.Component;\r
- import com.vaadin.ui.GridLayout;\r
- import com.vaadin.ui.Label;\r
- import com.vaadin.ui.Layout;\r
- import com.vaadin.ui.Table;\r
- import com.vaadin.ui.VerticalLayout;\r
- \r
- public class TableClickValueChangeInteraction extends TestBase {\r
- \r
- @Override\r
- public void setup() {\r
- GridLayout grid = new GridLayout(4, 4);\r
- grid.setSpacing(true);\r
- grid.setMargin(true);\r
- \r
- getLayout().removeAllComponents();\r
- getLayout().addComponent(grid);\r
- \r
- for (int i = 0; i < 16; ++i) {\r
- grid.addComponent(makeTable((i & 8) > 0, (i & 4) > 0, (i & 2) > 0,\r
- (i & 1) > 0));\r
- }\r
- \r
- }\r
- \r
- @Override\r
- protected String getDescription() {\r
- return "Table selection breaks if ItemClickListener requests repaint";\r
- }\r
- \r
- @Override\r
- protected Integer getTicketNumber() {\r
- return 7127;\r
- }\r
- \r
- private Component makeTable(boolean immediate, boolean selectable,\r
- boolean listenClicks, boolean listenValueChanges) {\r
- \r
- final Table table = new Table((immediate ? "I" : "i")\r
- + (selectable ? "S" : "s") + (listenClicks ? "C" : "c")\r
- + (listenValueChanges ? "V" : "v"));\r
- final Label clickLabel = new Label("Click?");\r
- final Label valueChangeLabel = new Label("Value?");\r
- \r
- table.addContainerProperty("foo", String.class, null);\r
- for (int i = 0; i < 3; i++) {\r
- table.addItem("item" + i).getItemProperty("foo")\r
- .setValue("An item " + i);\r
- }\r
- table.setImmediate(immediate);\r
- table.setSelectable(selectable);\r
- table.setWidth("100px");\r
- table.setHeight("100px");\r
- if (listenClicks) {\r
- table.addListener(new ItemClickListener() {\r
- public void itemClick(ItemClickEvent event) {\r
- table.requestRepaint();\r
- clickLabel.setValue("Click " + event.getItemId());\r
- }\r
- });\r
- }\r
- if (listenValueChanges) {\r
- table.addListener(new ValueChangeListener() {\r
- public void valueChange(ValueChangeEvent event) {\r
- valueChangeLabel.setValue("Value "\r
- + event.getProperty().getValue());\r
- }\r
- });\r
- }\r
- \r
- Layout result = new VerticalLayout();\r
- result.addComponent(table);\r
- result.addComponent(clickLabel);\r
- result.addComponent(valueChangeLabel);\r
- return result;\r
- }\r
+ package com.vaadin.tests.components.table;
+
+ import com.vaadin.data.Property.ValueChangeEvent;
+ import com.vaadin.data.Property.ValueChangeListener;
+ import com.vaadin.event.ItemClickEvent;
+ import com.vaadin.event.ItemClickEvent.ItemClickListener;
+ import com.vaadin.tests.components.TestBase;
+ import com.vaadin.ui.Component;
+ import com.vaadin.ui.GridLayout;
+ import com.vaadin.ui.Label;
+ import com.vaadin.ui.Layout;
+ import com.vaadin.ui.Table;
+ import com.vaadin.ui.VerticalLayout;
-import com.vaadin.ui.Window;
+
+ public class TableClickValueChangeInteraction extends TestBase {
+
- final Window mainWindow = new Window();
-
+ @Override
+ public void setup() {
- setMainWindow(mainWindow);
++ GridLayout grid = new GridLayout(4, 4);
++ grid.setSpacing(true);
++ grid.setMargin(true);
+
- GridLayout layout = new GridLayout(4, 4);
- layout.setSpacing(true);
- layout.setMargin(true);
- mainWindow.setContent(layout);
++ getLayout().removeAllComponents();
++ getLayout().addComponent(grid);
+
+ for (int i = 0; i < 16; ++i) {
- mainWindow.addComponent(makeTable((i & 8) > 0, (i & 4) > 0,
- (i & 2) > 0, (i & 1) > 0));
++ grid.addComponent(makeTable((i & 8) > 0, (i & 4) > 0, (i & 2) > 0,
++ (i & 1) > 0));
+ }
+
+ }
+
+ @Override
+ protected String getDescription() {
+ return "Table selection breaks if ItemClickListener requests repaint";
+ }
+
+ @Override
+ protected Integer getTicketNumber() {
+ return 7127;
+ }
+
+ private Component makeTable(boolean immediate, boolean selectable,
+ boolean listenClicks, boolean listenValueChanges) {
+
+ final Table table = new Table((immediate ? "I" : "i")
+ + (selectable ? "S" : "s") + (listenClicks ? "C" : "c")
+ + (listenValueChanges ? "V" : "v"));
+ final Label clickLabel = new Label("Click?");
+ final Label valueChangeLabel = new Label("Value?");
+
+ table.addContainerProperty("foo", String.class, null);
+ for (int i = 0; i < 3; i++) {
+ table.addItem("item" + i).getItemProperty("foo")
+ .setValue("An item " + i);
+ }
+ table.setImmediate(immediate);
+ table.setSelectable(selectable);
+ table.setWidth("100px");
+ table.setHeight("100px");
+ if (listenClicks) {
+ table.addListener(new ItemClickListener() {
+ public void itemClick(ItemClickEvent event) {
+ table.requestRepaint();
+ clickLabel.setValue("Click " + event.getItemId());
+ }
+ });
+ }
+ if (listenValueChanges) {
+ table.addListener(new ValueChangeListener() {
+ public void valueChange(ValueChangeEvent event) {
- valueChangeLabel.setValue("Value " + event.getProperty());
++ valueChangeLabel.setValue("Value "
++ + event.getProperty().getValue());
+ }
+ });
+ }
+
+ Layout result = new VerticalLayout();
+ result.addComponent(table);
+ result.addComponent(clickLabel);
+ result.addComponent(valueChangeLabel);
+ return result;
+ }
}
- package com.vaadin.tests.components.table;\r
- \r
- import com.vaadin.data.Container;\r
- import com.vaadin.data.Item;\r
- import com.vaadin.data.util.IndexedContainer;\r
- import com.vaadin.tests.components.AbstractTestCase;\r
- import com.vaadin.ui.Root.LegacyWindow;\r
- import com.vaadin.ui.Table;\r
- import com.vaadin.ui.VerticalLayout;\r
- \r
- public class TableExtraScrollbars extends AbstractTestCase {\r
- \r
- private static int PROPS = 15;\r
- private static int ROWS = 1000;\r
- \r
- @Override\r
- public void init() {\r
- setTheme("runo");\r
- LegacyWindow w = new LegacyWindow("Table scrollbars bug example");\r
- setMainWindow(w);\r
- \r
- VerticalLayout vl = new VerticalLayout();\r
- vl.setSizeFull();\r
- vl.addComponent(createTable());\r
- w.setContent(vl);\r
- }\r
- \r
- protected Table createTable() {\r
- Table table = new Table(null, createContainer());\r
- table.setSizeFull();\r
- table.setPageLength(50);\r
- table.setColumnReorderingAllowed(true);\r
- table.setSelectable(true);\r
- return table;\r
- }\r
- \r
- protected Container createContainer() {\r
- Container container = new IndexedContainer();\r
- for (int i = 0; i < PROPS; ++i) {\r
- container.addContainerProperty("prop" + i, String.class, null);\r
- }\r
- for (int i = 0; i < ROWS; ++i) {\r
- Item item = container.addItem(i);\r
- for (int p = 0; p < PROPS; ++p) {\r
- item.getItemProperty("prop" + p).setValue(\r
- "property value 1234567890");\r
- }\r
- }\r
- return container;\r
- }\r
- \r
- @Override\r
- protected String getDescription() {\r
- return "Scrolling down in the table should not add extra scrollbars";\r
- }\r
- \r
- @Override\r
- protected Integer getTicketNumber() {\r
- return 4489;\r
- }\r
+ package com.vaadin.tests.components.table;
+
+ import com.vaadin.data.Container;
+ import com.vaadin.data.Item;
+ import com.vaadin.data.util.IndexedContainer;
+ import com.vaadin.tests.components.AbstractTestCase;
++import com.vaadin.ui.Root.LegacyWindow;
+ import com.vaadin.ui.Table;
+ import com.vaadin.ui.VerticalLayout;
-import com.vaadin.ui.Window;
+
+ public class TableExtraScrollbars extends AbstractTestCase {
+
+ private static int PROPS = 15;
+ private static int ROWS = 1000;
+
+ @Override
+ public void init() {
+ setTheme("runo");
- Window w = new Window("Table scrollbars bug example");
++ LegacyWindow w = new LegacyWindow("Table scrollbars bug example");
+ setMainWindow(w);
+
+ VerticalLayout vl = new VerticalLayout();
+ vl.setSizeFull();
+ vl.addComponent(createTable());
+ w.setContent(vl);
+ }
+
+ protected Table createTable() {
+ Table table = new Table(null, createContainer());
+ table.setSizeFull();
+ table.setPageLength(50);
+ table.setColumnReorderingAllowed(true);
+ table.setSelectable(true);
+ return table;
+ }
+
+ protected Container createContainer() {
+ Container container = new IndexedContainer();
+ for (int i = 0; i < PROPS; ++i) {
+ container.addContainerProperty("prop" + i, String.class, null);
+ }
+ for (int i = 0; i < ROWS; ++i) {
+ Item item = container.addItem(i);
+ for (int p = 0; p < PROPS; ++p) {
+ item.getItemProperty("prop" + p).setValue(
+ "property value 1234567890");
+ }
+ }
+ return container;
+ }
+
+ @Override
+ protected String getDescription() {
+ return "Scrolling down in the table should not add extra scrollbars";
+ }
+
+ @Override
+ protected Integer getTicketNumber() {
+ return 4489;
+ }
}
- package com.vaadin.tests.components.table;\r
- \r
- import com.vaadin.data.Property.ValueChangeEvent;\r
- import com.vaadin.data.Property.ValueChangeListener;\r
- import com.vaadin.tests.components.TestBase;\r
- import com.vaadin.ui.CheckBox;\r
- import com.vaadin.ui.Table;\r
- \r
- public class TableScrollOnFocus extends TestBase {\r
- @Override\r
- protected void setup() {\r
- final Table table = new Table();\r
- final CheckBox chkSelectable = new CheckBox("selectable");\r
- \r
- chkSelectable.setImmediate(true);\r
- chkSelectable.addListener(new ValueChangeListener() {\r
- public void valueChange(ValueChangeEvent event) {\r
- table.setSelectable((Boolean) chkSelectable.getValue());\r
- }\r
- });\r
- \r
- table.addContainerProperty("row #", String.class, "-");\r
- table.setColumnWidth("row #", 150);\r
- for (int i = 1; i < 200; i++) {\r
- table.addItem(new String[] { "" + i }, null);\r
- }\r
- table.setSortDisabled(true);\r
- \r
- chkSelectable.setValue(true);\r
- \r
- addComponent(chkSelectable);\r
- addComponent(table);\r
- }\r
- \r
- @Override\r
- protected String getDescription() {\r
- return "The table scrolls up 2 pages after loosing and regaining the focus!</b><p>"\r
- + "Drag scrollbar to top then to the bottom of the table.<br>"\r
- + "Click somewhere beside the table to take away the focus,<br>"\r
- + "then click back on the table (header or scrollbar) to give back the focus<br>"\r
- + "(Pressing Tab and Shift-Tab does the same job).<p>"\r
- + "If the table is set to non-selectable-mode, no self-scrolling occurs.";\r
- }\r
- \r
- @Override\r
- protected Integer getTicketNumber() {\r
- return 6774;\r
- }\r
+ package com.vaadin.tests.components.table;
+
+ import com.vaadin.data.Property.ValueChangeEvent;
+ import com.vaadin.data.Property.ValueChangeListener;
+ import com.vaadin.tests.components.TestBase;
+ import com.vaadin.ui.CheckBox;
+ import com.vaadin.ui.Table;
+
+ public class TableScrollOnFocus extends TestBase {
+ @Override
+ protected void setup() {
+ final Table table = new Table();
+ final CheckBox chkSelectable = new CheckBox("selectable");
+
+ chkSelectable.setImmediate(true);
+ chkSelectable.addListener(new ValueChangeListener() {
+ public void valueChange(ValueChangeEvent event) {
- table.setSelectable(chkSelectable.booleanValue());
++ table.setSelectable((Boolean) chkSelectable.getValue());
+ }
+ });
+
+ table.addContainerProperty("row #", String.class, "-");
+ table.setColumnWidth("row #", 150);
+ for (int i = 1; i < 200; i++) {
+ table.addItem(new String[] { "" + i }, null);
+ }
+ table.setSortDisabled(true);
+
+ chkSelectable.setValue(true);
+
+ addComponent(chkSelectable);
+ addComponent(table);
+ }
+
+ @Override
+ protected String getDescription() {
+ return "The table scrolls up 2 pages after loosing and regaining the focus!</b><p>"
+ + "Drag scrollbar to top then to the bottom of the table.<br>"
+ + "Click somewhere beside the table to take away the focus,<br>"
+ + "then click back on the table (header or scrollbar) to give back the focus<br>"
+ + "(Pressing Tab and Shift-Tab does the same job).<p>"
+ + "If the table is set to non-selectable-mode, no self-scrolling occurs.";
+ }
+
+ @Override
+ protected Integer getTicketNumber() {
+ return 6774;
+ }
}
- package com.vaadin.tests.components.table;\r
- \r
- import com.vaadin.data.Property.ValueChangeEvent;\r
- import com.vaadin.data.Property.ValueChangeListener;\r
- import com.vaadin.tests.components.TestBase;\r
- import com.vaadin.tests.util.Log;\r
- import com.vaadin.ui.Button;\r
- import com.vaadin.ui.Component;\r
- import com.vaadin.ui.Table;\r
- \r
- public class TableSingleSelect extends TestBase {\r
- Log log = new Log(3);\r
- \r
- @Override\r
- protected void setup() {\r
- log.setDebugId("eventlog");\r
- \r
- Table t = new Table();\r
- \r
- t.setSelectable(true);\r
- t.setNullSelectionAllowed(true);\r
- t.setImmediate(true);\r
- t.addListener(new ValueChangeListener() {\r
- \r
- public void valueChange(ValueChangeEvent event) {\r
- log.log("Selected value: " + event.getProperty().getValue());\r
- }\r
- });\r
- \r
- t.addContainerProperty("string", String.class, null);\r
- t.addContainerProperty("button", Component.class, null);\r
- \r
- for (int i = 0; i < 10; i++) {\r
- t.addItem(i);\r
- t.getContainerProperty(i, "string").setValue(String.valueOf(i));\r
- t.getContainerProperty(i, "button")\r
- .setValue(new Button("Click me"));\r
- }\r
- \r
- addComponent(log);\r
- addComponent(t);\r
- }\r
- \r
- @Override\r
- protected String getDescription() {\r
- return "Table in single-select mode with null selection allowed. Tests that single select does not select multiple items, selects and deselects properly.";\r
- }\r
- \r
- @Override\r
- protected Integer getTicketNumber() {\r
- return 5431;\r
- }\r
- \r
- }\r
+ package com.vaadin.tests.components.table;
+
+ import com.vaadin.data.Property.ValueChangeEvent;
+ import com.vaadin.data.Property.ValueChangeListener;
+ import com.vaadin.tests.components.TestBase;
+ import com.vaadin.tests.util.Log;
+ import com.vaadin.ui.Button;
+ import com.vaadin.ui.Component;
+ import com.vaadin.ui.Table;
+
+ public class TableSingleSelect extends TestBase {
+ Log log = new Log(3);
+
+ @Override
+ protected void setup() {
+ log.setDebugId("eventlog");
+
+ Table t = new Table();
+
+ t.setSelectable(true);
+ t.setNullSelectionAllowed(true);
+ t.setImmediate(true);
+ t.addListener(new ValueChangeListener() {
+
+ public void valueChange(ValueChangeEvent event) {
+ log.log("Selected value: " + event.getProperty().getValue());
+ }
+ });
+
+ t.addContainerProperty("string", String.class, null);
+ t.addContainerProperty("button", Component.class, null);
+
+ for (int i = 0; i < 10; i++) {
+ t.addItem(i);
- t.getContainerProperty(i, "string").setValue(i);
++ t.getContainerProperty(i, "string").setValue(String.valueOf(i));
+ t.getContainerProperty(i, "button")
+ .setValue(new Button("Click me"));
+ }
+
+ addComponent(log);
+ addComponent(t);
+ }
+
+ @Override
+ protected String getDescription() {
+ return "Table in single-select mode with null selection allowed. Tests that single select does not select multiple items, selects and deselects properly.";
+ }
+
+ @Override
+ protected Integer getTicketNumber() {
+ return 5431;
+ }
+
+ }
- package com.vaadin.tests.components.table;\r
- \r
- import java.text.DecimalFormat;\r
- \r
- import com.vaadin.tests.components.AbstractTestCase;\r
- import com.vaadin.ui.Button;\r
- import com.vaadin.ui.HorizontalLayout;\r
- import com.vaadin.ui.HorizontalSplitPanel;\r
- import com.vaadin.ui.Label;\r
- import com.vaadin.ui.Root.LegacyWindow;\r
- import com.vaadin.ui.Table;\r
- import com.vaadin.ui.VerticalLayout;\r
- \r
- public class TableToggleVisibility extends AbstractTestCase {\r
- \r
- private static final int[] LENGTHS = new int[] { 20, 22, 10 };\r
- \r
- @Override\r
- public void init() {\r
- \r
- DecimalFormat format = new DecimalFormat("000");\r
- Table[] tables = new Table[3];\r
- Button[] buttons = new Button[3];\r
- \r
- VerticalLayout leftComponent = new VerticalLayout();\r
- leftComponent.setMargin(true);\r
- leftComponent.setSpacing(true);\r
- \r
- // Toolbar with buttons to hide or show lists\r
- \r
- HorizontalLayout toolBar = new HorizontalLayout();\r
- toolBar.setSpacing(true);\r
- toolBar.setMargin(true);\r
- \r
- leftComponent.addComponent(toolBar);\r
- leftComponent.setExpandRatio(toolBar, 0.0f);\r
- \r
- // List of trucks -----------------------\r
- \r
- tables[0] = new Table("Trucks");\r
- tables[0].addContainerProperty("Brand", String.class, null);\r
- tables[0].addContainerProperty("Model", String.class, null);\r
- tables[0].addContainerProperty("License Plate", String.class, null);\r
- \r
- for (int i = 1; i < LENGTHS[0]; i++) {\r
- tables[0].addItem(\r
- new Object[] { "MAN", "XYZ", "1-ABC-" + format.format(i) },\r
- Integer.valueOf(i));\r
- }\r
- tables[0].setPageLength(LENGTHS[0]);\r
- \r
- tables[0].setWidth("100%");\r
- tables[0].setHeight("100%");\r
- tables[0].setSelectable(true);\r
- \r
- leftComponent.addComponent(tables[0]);\r
- leftComponent.setExpandRatio(tables[0], 1.0f);\r
- \r
- // List of trailers ----------------------\r
- \r
- tables[1] = new Table("Trailers");\r
- tables[1].addContainerProperty("Type", String.class, null);\r
- tables[1].addContainerProperty("License Plate", String.class, null);\r
- for (int i = 1; i < LENGTHS[1]; i++) {\r
- tables[1].addItem(\r
- new Object[] { "Cooler", "1-QQQ-" + format.format(i) },\r
- Integer.valueOf(i));\r
- }\r
- tables[1].setPageLength(LENGTHS[1]);\r
- \r
- tables[1].setWidth("100%");\r
- tables[1].setHeight("100%");\r
- tables[1].setSelectable(true);\r
- \r
- leftComponent.addComponent(tables[1]);\r
- leftComponent.setExpandRatio(tables[1], 1.0f);\r
- \r
- // List of drivers ------------------------\r
- \r
- tables[2] = new Table("Drivers");\r
- tables[2].addContainerProperty("First Name", String.class, null);\r
- tables[2].addContainerProperty("Last Name", String.class, null);\r
- tables[2].addContainerProperty("HR ID", String.class, null);\r
- for (int i = 1; i < LENGTHS[2]; i++) {\r
- tables[2].addItem(\r
- new Object[] { "King", "Vabis", "HR-" + format.format(i) },\r
- Integer.valueOf(i));\r
- }\r
- tables[2].setPageLength(LENGTHS[2]);\r
- \r
- tables[2].setWidth("100%");\r
- tables[2].setHeight("100%");\r
- tables[2].setSelectable(true);\r
- \r
- leftComponent.addComponent(tables[2]);\r
- leftComponent.setExpandRatio(tables[2], 1.0f);\r
- \r
- leftComponent.setWidth("100%");\r
- \r
- HorizontalSplitPanel split = new HorizontalSplitPanel();\r
- split.setFirstComponent(leftComponent);\r
- \r
- VerticalLayout rightComponent = new VerticalLayout();\r
- rightComponent.setMargin(true);\r
- rightComponent.addComponent(new Label("Left blank!"));\r
- split.setSecondComponent(rightComponent);\r
- \r
- split.setSizeFull();\r
- \r
- VerticalLayout mainLayout = new VerticalLayout();\r
- mainLayout.setSizeFull();\r
- mainLayout.addComponent(split);\r
- mainLayout.setExpandRatio(split, 1.0f);\r
- \r
- LegacyWindow mainWindow = new LegacyWindow("Visibilitybug Application",\r
- mainLayout);\r
- mainWindow.setSizeFull();\r
- \r
- setMainWindow(mainWindow);\r
- \r
- // complete toolbar\r
- \r
- for (int i = 0; i < buttons.length; i++) {\r
- buttons[i] = new ToggleButton(tables[i]);\r
- toolBar.addComponent(buttons[i]);\r
- }\r
- \r
- }\r
- \r
- // Button to switch the visibility of a table.\r
- \r
- private static class ToggleButton extends Button {\r
- \r
- private Table table;\r
- \r
- private ToggleButton(Table table) {\r
- this.table = table;\r
- \r
- setCaption("- " + table.getCaption());\r
- \r
- addListener(new ClickListener() {\r
- \r
- public void buttonClick(ClickEvent event) {\r
- \r
- boolean wasVisible = ToggleButton.this.table.isVisible();\r
- \r
- ToggleButton.this.table.setVisible(!wasVisible);\r
- setCaption((wasVisible ? "+ " : "- ")\r
- + ToggleButton.this.table.getCaption());\r
- setDescription((wasVisible ? "Show " : "Hide ")\r
- + "the list with "\r
- + ToggleButton.this.table.getCaption());\r
- \r
- }\r
- });\r
- }\r
- \r
- }\r
- \r
- @Override\r
- protected String getDescription() {\r
- return "Test for hiding and showing tables. Click a button to show/hide one of the tables. The tables are all 100% wide and should be rendered the same way after being hidden and shown again.";\r
- }\r
- \r
- @Override\r
- protected Integer getTicketNumber() {\r
- return 6494;\r
- }\r
- \r
+ package com.vaadin.tests.components.table;
+
+ import java.text.DecimalFormat;
+
+ import com.vaadin.tests.components.AbstractTestCase;
+ import com.vaadin.ui.Button;
+ import com.vaadin.ui.HorizontalLayout;
+ import com.vaadin.ui.HorizontalSplitPanel;
+ import com.vaadin.ui.Label;
++import com.vaadin.ui.Root.LegacyWindow;
+ import com.vaadin.ui.Table;
+ import com.vaadin.ui.VerticalLayout;
-import com.vaadin.ui.Window;
+
+ public class TableToggleVisibility extends AbstractTestCase {
+
+ private static final int[] LENGTHS = new int[] { 20, 22, 10 };
+
+ @Override
+ public void init() {
+
+ DecimalFormat format = new DecimalFormat("000");
+ Table[] tables = new Table[3];
+ Button[] buttons = new Button[3];
+
+ VerticalLayout leftComponent = new VerticalLayout();
+ leftComponent.setMargin(true);
+ leftComponent.setSpacing(true);
+
+ // Toolbar with buttons to hide or show lists
+
+ HorizontalLayout toolBar = new HorizontalLayout();
+ toolBar.setSpacing(true);
+ toolBar.setMargin(true);
+
+ leftComponent.addComponent(toolBar);
+ leftComponent.setExpandRatio(toolBar, 0.0f);
+
+ // List of trucks -----------------------
+
+ tables[0] = new Table("Trucks");
+ tables[0].addContainerProperty("Brand", String.class, null);
+ tables[0].addContainerProperty("Model", String.class, null);
+ tables[0].addContainerProperty("License Plate", String.class, null);
+
+ for (int i = 1; i < LENGTHS[0]; i++) {
+ tables[0].addItem(
+ new Object[] { "MAN", "XYZ", "1-ABC-" + format.format(i) },
+ Integer.valueOf(i));
+ }
+ tables[0].setPageLength(LENGTHS[0]);
+
+ tables[0].setWidth("100%");
+ tables[0].setHeight("100%");
+ tables[0].setSelectable(true);
+
+ leftComponent.addComponent(tables[0]);
+ leftComponent.setExpandRatio(tables[0], 1.0f);
+
+ // List of trailers ----------------------
+
+ tables[1] = new Table("Trailers");
+ tables[1].addContainerProperty("Type", String.class, null);
+ tables[1].addContainerProperty("License Plate", String.class, null);
+ for (int i = 1; i < LENGTHS[1]; i++) {
+ tables[1].addItem(
+ new Object[] { "Cooler", "1-QQQ-" + format.format(i) },
+ Integer.valueOf(i));
+ }
+ tables[1].setPageLength(LENGTHS[1]);
+
+ tables[1].setWidth("100%");
+ tables[1].setHeight("100%");
+ tables[1].setSelectable(true);
+
+ leftComponent.addComponent(tables[1]);
+ leftComponent.setExpandRatio(tables[1], 1.0f);
+
+ // List of drivers ------------------------
+
+ tables[2] = new Table("Drivers");
+ tables[2].addContainerProperty("First Name", String.class, null);
+ tables[2].addContainerProperty("Last Name", String.class, null);
+ tables[2].addContainerProperty("HR ID", String.class, null);
+ for (int i = 1; i < LENGTHS[2]; i++) {
+ tables[2].addItem(
+ new Object[] { "King", "Vabis", "HR-" + format.format(i) },
+ Integer.valueOf(i));
+ }
+ tables[2].setPageLength(LENGTHS[2]);
+
+ tables[2].setWidth("100%");
+ tables[2].setHeight("100%");
+ tables[2].setSelectable(true);
+
+ leftComponent.addComponent(tables[2]);
+ leftComponent.setExpandRatio(tables[2], 1.0f);
+
+ leftComponent.setWidth("100%");
+
+ HorizontalSplitPanel split = new HorizontalSplitPanel();
+ split.setFirstComponent(leftComponent);
+
+ VerticalLayout rightComponent = new VerticalLayout();
+ rightComponent.setMargin(true);
+ rightComponent.addComponent(new Label("Left blank!"));
+ split.setSecondComponent(rightComponent);
+
+ split.setSizeFull();
+
+ VerticalLayout mainLayout = new VerticalLayout();
+ mainLayout.setSizeFull();
+ mainLayout.addComponent(split);
+ mainLayout.setExpandRatio(split, 1.0f);
+
- Window mainWindow = new Window("Visibilitybug Application", mainLayout);
++ LegacyWindow mainWindow = new LegacyWindow("Visibilitybug Application",
++ mainLayout);
+ mainWindow.setSizeFull();
+
+ setMainWindow(mainWindow);
+
+ // complete toolbar
+
+ for (int i = 0; i < buttons.length; i++) {
+ buttons[i] = new ToggleButton(tables[i]);
+ toolBar.addComponent(buttons[i]);
+ }
+
+ }
+
+ // Button to switch the visibility of a table.
+
+ private static class ToggleButton extends Button {
+
+ private Table table;
+
+ private ToggleButton(Table table) {
+ this.table = table;
+
+ setCaption("- " + table.getCaption());
+
+ addListener(new ClickListener() {
+
+ public void buttonClick(ClickEvent event) {
+
+ boolean wasVisible = ToggleButton.this.table.isVisible();
+
+ ToggleButton.this.table.setVisible(!wasVisible);
+ setCaption((wasVisible ? "+ " : "- ")
+ + ToggleButton.this.table.getCaption());
+ setDescription((wasVisible ? "Show " : "Hide ")
+ + "the list with "
+ + ToggleButton.this.table.getCaption());
+
+ }
+ });
+ }
+
+ }
+
+ @Override
+ protected String getDescription() {
+ return "Test for hiding and showing tables. Click a button to show/hide one of the tables. The tables are all 100% wide and should be rendered the same way after being hidden and shown again.";
+ }
+
+ @Override
+ protected Integer getTicketNumber() {
+ return 6494;
+ }
+
}
- package com.vaadin.tests.components.table;\r
- \r
- import com.vaadin.data.Item;\r
- import com.vaadin.data.Property;\r
- import com.vaadin.tests.components.TestBase;\r
- import com.vaadin.ui.Table;\r
- \r
- public class TableWithManyColumns extends TestBase {\r
- \r
- private static final int ROWS = 20;\r
- private static final int COLS = 100;\r
- \r
- @Override\r
- protected void setup() {\r
- Table t = new Table();\r
- \r
- for (int i = 0; i < COLS; i++) {\r
- t.addContainerProperty("COLUMN_" + i, String.class, "");\r
- }\r
- for (int row = 0; row < ROWS; row++) {\r
- Item i = t.addItem(String.valueOf(row));\r
- for (int col = 0; col < COLS; col++) {\r
- Property<?> p = i.getItemProperty("COLUMN_" + col);\r
- p.setValue("item " + row + "/" + col);\r
- }\r
- }\r
- t.setFooterVisible(true);\r
- t.setSizeFull();\r
- addComponent(t);\r
- }\r
- \r
- @Override\r
- protected String getDescription() {\r
- return "The footer, header and content cells should be as wide, even when the Table contains many columns";\r
- }\r
- \r
- @Override\r
- protected Integer getTicketNumber() {\r
- return 5185;\r
- }\r
- \r
- }\r
+ package com.vaadin.tests.components.table;
+
+ import com.vaadin.data.Item;
+ import com.vaadin.data.Property;
+ import com.vaadin.tests.components.TestBase;
+ import com.vaadin.ui.Table;
+
+ public class TableWithManyColumns extends TestBase {
+
+ private static final int ROWS = 20;
+ private static final int COLS = 100;
+
+ @Override
+ protected void setup() {
+ Table t = new Table();
+
+ for (int i = 0; i < COLS; i++) {
+ t.addContainerProperty("COLUMN_" + i, String.class, "");
+ }
+ for (int row = 0; row < ROWS; row++) {
+ Item i = t.addItem(String.valueOf(row));
+ for (int col = 0; col < COLS; col++) {
- Property p = i.getItemProperty("COLUMN_" + col);
++ Property<?> p = i.getItemProperty("COLUMN_" + col);
+ p.setValue("item " + row + "/" + col);
+ }
+ }
+ t.setFooterVisible(true);
+ t.setSizeFull();
+ addComponent(t);
+ }
+
+ @Override
+ protected String getDescription() {
+ return "The footer, header and content cells should be as wide, even when the Table contains many columns";
+ }
+
+ @Override
+ protected Integer getTicketNumber() {
+ return 5185;
+ }
+
+ }
- package com.vaadin.tests.components.table;\r
- \r
- import java.util.ArrayList;\r
- import java.util.Arrays;\r
- import java.util.LinkedHashMap;\r
- import java.util.List;\r
- \r
- import com.vaadin.event.Action;\r
- import com.vaadin.event.Action.Handler;\r
- import com.vaadin.event.ItemClickEvent.ItemClickListener;\r
- import com.vaadin.terminal.Resource;\r
- import com.vaadin.tests.components.select.AbstractSelectTestCase;\r
- import com.vaadin.ui.AbstractSelect.MultiSelectMode;\r
- import com.vaadin.ui.Button;\r
- import com.vaadin.ui.Label;\r
- import com.vaadin.ui.Label.ContentMode;\r
- import com.vaadin.ui.Table;\r
- import com.vaadin.ui.Table.Align;\r
- import com.vaadin.ui.Table.CellStyleGenerator;\r
- import com.vaadin.ui.Table.ColumnGenerator;\r
- import com.vaadin.ui.Table.ColumnHeaderMode;\r
- import com.vaadin.ui.Table.ColumnResizeEvent;\r
- import com.vaadin.ui.Table.ColumnResizeListener;\r
- import com.vaadin.ui.Table.FooterClickEvent;\r
- import com.vaadin.ui.Table.FooterClickListener;\r
- import com.vaadin.ui.Table.GeneratedRow;\r
- import com.vaadin.ui.Table.HeaderClickEvent;\r
- import com.vaadin.ui.Table.HeaderClickListener;\r
- import com.vaadin.ui.Table.RowGenerator;\r
- import com.vaadin.ui.Table.RowHeaderMode;\r
- \r
- public class Tables<T extends Table> extends AbstractSelectTestCase<T>\r
- implements ItemClickListener, HeaderClickListener, FooterClickListener,\r
- ColumnResizeListener {\r
- \r
- protected static final String CATEGORY_ROWS = "Rows";\r
- private static final String CATEGORY_HEADER = "Header";\r
- private static final String CATEGORY_FOOTER = "Footer";\r
- private static final String CATEGORY_COLUMNS = "Columns";\r
- \r
- @SuppressWarnings("unchecked")\r
- @Override\r
- protected Class<T> getTestClass() {\r
- return (Class<T>) Table.class;\r
- }\r
- \r
- /* COMMANDS */\r
- private Command<T, Align> columnAlignmentCommand = new Command<T, Align>() {\r
- \r
- public void execute(T c, Align alignment, Object propertyId) {\r
- c.setColumnAlignment(propertyId, alignment);\r
- }\r
- \r
- };\r
- \r
- private Command<T, Boolean> columnVisibleCommand = new Command<T, Boolean>() {\r
- public void execute(Table c, Boolean visible, Object propertyId) {\r
- List<Object> visibleColumns = new ArrayList<Object>(Arrays.asList(c\r
- .getVisibleColumns()));\r
- if (visible) {\r
- // Table should really check this... Completely fails without\r
- // the check (#\r
- if (!visibleColumns.contains(propertyId)) {\r
- visibleColumns.add(propertyId);\r
- }\r
- } else {\r
- visibleColumns.remove(propertyId);\r
- }\r
- c.setVisibleColumns(visibleColumns.toArray());\r
- }\r
- };\r
- \r
- private Command<T, Boolean> columnCollapsed = new Command<T, Boolean>() {\r
- \r
- public void execute(T c, Boolean collapsed, Object propertyId) {\r
- c.setColumnCollapsed(propertyId, collapsed);\r
- \r
- }\r
- };\r
- \r
- protected Command<T, Boolean> columnResizeListenerCommand = new Command<T, Boolean>() {\r
- \r
- public void execute(Table c, Boolean value, Object data) {\r
- if (value) {\r
- c.addListener((ColumnResizeListener) Tables.this);\r
- } else {\r
- c.removeListener((ColumnResizeListener) Tables.this);\r
- }\r
- }\r
- };\r
- \r
- protected Command<T, Boolean> headerClickListenerCommand = new Command<T, Boolean>() {\r
- \r
- public void execute(T c, Boolean value, Object data) {\r
- if (value) {\r
- c.addListener((HeaderClickListener) Tables.this);\r
- } else {\r
- c.removeListener((HeaderClickListener) Tables.this);\r
- }\r
- }\r
- };\r
- \r
- protected Command<T, Boolean> footerClickListenerCommand = new Command<T, Boolean>() {\r
- \r
- public void execute(Table c, Boolean value, Object data) {\r
- if (value) {\r
- c.addListener((FooterClickListener) Tables.this);\r
- } else {\r
- c.removeListener((FooterClickListener) Tables.this);\r
- }\r
- }\r
- };\r
- \r
- protected Command<T, RowHeaderMode> rowHeaderModeCommand = new Command<T, RowHeaderMode>() {\r
- \r
- public void execute(Table c, RowHeaderMode value, Object data) {\r
- if (value == RowHeaderMode.PROPERTY) {\r
- c.setItemCaptionPropertyId("Property 3");\r
- }\r
- c.setRowHeaderMode(value);\r
- }\r
- };\r
- \r
- protected Command<T, String> footerTextCommand = new Command<T, String>() {\r
- \r
- public void execute(Table c, String value, Object data) {\r
- for (Object propertyId : c.getContainerPropertyIds()) {\r
- if (value != null) {\r
- c.setColumnFooter(propertyId,\r
- value.replace("{id}", propertyId.toString()));\r
- } else {\r
- c.setColumnFooter(propertyId, null);\r
- }\r
- }\r
- }\r
- };\r
- \r
- protected Command<T, Object> alignColumnLeftCommand = new Command<T, Object>() {\r
- \r
- public void execute(T c, Object propertyId, Object data) {\r
- c.setColumnAlignment(propertyId, (Align) data);\r
- }\r
- };\r
- \r
- private Command<T, ContextMenu> contextMenuCommand = new Command<T, ContextMenu>() {\r
- \r
- public void execute(T c, final ContextMenu value, Object data) {\r
- c.removeAllActionHandlers();\r
- if (value != null) {\r
- c.addActionHandler(new Handler() {\r
- \r
- public void handleAction(Action action, Object sender,\r
- Object target) {\r
- log("Action " + action.getCaption() + " performed on "\r
- + target);\r
- }\r
- \r
- public Action[] getActions(Object target, Object sender) {\r
- return value.getActions(target, sender);\r
- }\r
- });\r
- }\r
- }\r
- };\r
- private Command<T, Integer> columnWidthCommand = new Command<T, Integer>() {\r
- \r
- public void execute(T c, Integer width, Object propertyId) {\r
- c.setColumnWidth(propertyId, width);\r
- \r
- }\r
- };\r
- \r
- private Command<T, Resource> columnIconCommand = new Command<T, Resource>() {\r
- \r
- public void execute(T c, Resource icon, Object propertyId) {\r
- c.setColumnIcon(propertyId, icon);\r
- \r
- }\r
- };\r
- private Command<T, ColumnHeaderMode> columnHeaderModeCommand = new Command<T, ColumnHeaderMode>() {\r
- \r
- public void execute(T c, ColumnHeaderMode columnHeaderMode, Object data) {\r
- c.setColumnHeaderMode(columnHeaderMode);\r
- \r
- }\r
- };\r
- private Command<T, String> columnHeaderCommand = new Command<T, String>() {\r
- \r
- public void execute(T c, String header, Object propertyId) {\r
- c.setColumnHeader(propertyId, header);\r
- \r
- }\r
- };\r
- private Command<T, Float> columnExpandRatioCommand = new Command<T, Float>() {\r
- \r
- public void execute(T c, Float expandRatio, Object propertyId) {\r
- c.setColumnExpandRatio(propertyId, expandRatio);\r
- }\r
- };\r
- \r
- private class GeneratedColumn {\r
- private Class<?> type;\r
- private String width;\r
- private boolean html;\r
- \r
- public GeneratedColumn(Class<?> type, String width, boolean html) {\r
- super();\r
- this.type = type;\r
- this.width = width;\r
- this.html = html;\r
- }\r
- }\r
- \r
- String generatedColumnId = "Generated ";\r
- int generatedColumnNextNr = 1;\r
- \r
- private Command<T, GeneratedColumn> addGeneratedColumnCommand = new Command<T, GeneratedColumn>() {\r
- \r
- public void execute(T c, final GeneratedColumn col, Object data) {\r
- while (c.getColumnGenerator(generatedColumnId\r
- + generatedColumnNextNr) != null) {\r
- generatedColumnNextNr++;\r
- }\r
- \r
- c.addGeneratedColumn(generatedColumnId + generatedColumnNextNr,\r
- new ColumnGenerator() {\r
- \r
- public Object generateCell(Table source, Object itemId,\r
- Object columnId) {\r
- String value = "";\r
- if (col.html) {\r
- value = "<i>" + itemId + "</i>" + "/" + "<b>"\r
- + columnId + "</b>";\r
- } else {\r
- value = itemId + "/" + columnId;\r
- }\r
- if (col.type == Button.class) {\r
- Button b = new Button();\r
- b.setCaption(value);\r
- b.setWidth(col.width);\r
- return b;\r
- } else if (col.type == Label.class) {\r
- Label l = new Label();\r
- l.setWidth(col.width);\r
- if (col.html) {\r
- l.setValue(value);\r
- l.setContentMode(ContentMode.XHTML);\r
- } else {\r
- l.setValue(value);\r
- }\r
- return l;\r
- } else if (col.type == String.class) {\r
- return value;\r
- } else if (col.type == Object.class) {\r
- return new Object();\r
- }\r
- \r
- return null;\r
- }\r
- });\r
- generatedColumnNextNr++;\r
- createColumnOptions(false);\r
- \r
- }\r
- };\r
- private Command<T, Object> removeGeneratedColumnsCommand = new Command<T, Object>() {\r
- \r
- public void execute(T c, Object value, Object data) {\r
- for (int i = 0; i < generatedColumnNextNr; i++) {\r
- String columnId = generatedColumnId + i;\r
- if (c.getColumnGenerator(columnId) != null) {\r
- c.removeGeneratedColumn(columnId);\r
- }\r
- \r
- }\r
- createColumnOptions(false);\r
- \r
- }\r
- };\r
- \r
- private class CellStyleInfo {\r
- private final String styleName;\r
- private final Object itemId;\r
- private final Object propertyId;\r
- \r
- public CellStyleInfo(String styleName, Object itemId, Object propertyId) {\r
- this.styleName = styleName;\r
- this.itemId = itemId;\r
- this.propertyId = propertyId;\r
- }\r
- \r
- public boolean appliesTo(Object itemId, Object propertyId) {\r
- return (this.itemId != null && this.itemId.equals(itemId))\r
- && (this.propertyId == propertyId || (this.propertyId != null && this.propertyId\r
- .equals(propertyId)));\r
- }\r
- }\r
- \r
- private Command<T, CellStyleInfo> cellStyleCommand = new Command<T, CellStyleInfo>() {\r
- \r
- public void execute(T c, final CellStyleInfo cellStyleInfo, Object data) {\r
- if (cellStyleInfo == null) {\r
- c.setCellStyleGenerator(null);\r
- } else {\r
- c.setCellStyleGenerator(new CellStyleGenerator() {\r
- \r
- public String getStyle(Object itemId, Object propertyId) {\r
- if (cellStyleInfo.appliesTo(itemId, propertyId)) {\r
- return cellStyleInfo.styleName;\r
- }\r
- return null;\r
- }\r
- });\r
- }\r
- }\r
- };\r
- \r
- private class GeneratedRowInfo {\r
- \r
- private final int nth;\r
- private final String[] text;\r
- private final boolean isHtml;\r
- \r
- public GeneratedRowInfo(int nth, boolean isHtml, String... text) {\r
- this.nth = nth;\r
- this.isHtml = isHtml;\r
- this.text = text;\r
- }\r
- \r
- public boolean appliesTo(Object itemId) {\r
- int ix = Integer.valueOf(itemId.toString().substring(5));\r
- return ix % nth == 0;\r
- }\r
- \r
- @Override\r
- public String toString() {\r
- return String.format("%d, %s, %s", nth, isHtml ? "true" : "false",\r
- Arrays.toString(text));\r
- }\r
- }\r
- \r
- private Command<T, GeneratedRowInfo> rowGeneratorCommand = new Command<T, GeneratedRowInfo>() {\r
- \r
- public void execute(T c, final GeneratedRowInfo generatedRowInfo,\r
- Object data) {\r
- if (generatedRowInfo == null) {\r
- c.setRowGenerator(null);\r
- } else {\r
- c.setRowGenerator(new RowGenerator() {\r
- \r
- public GeneratedRow generateRow(Table table, Object itemId) {\r
- if (generatedRowInfo.appliesTo(itemId)) {\r
- GeneratedRow generatedRow = new GeneratedRow(\r
- generatedRowInfo.text);\r
- generatedRow\r
- .setHtmlContentAllowed(generatedRowInfo.isHtml);\r
- return generatedRow;\r
- }\r
- return null;\r
- }\r
- });\r
- }\r
- }\r
- };\r
- \r
- private Command<T, Boolean> setSortEnabledCommand = new Command<T, Boolean>() {\r
- \r
- public void execute(T c, Boolean value, Object data) {\r
- c.setSortDisabled(!value);\r
- \r
- }\r
- };\r
- \r
- /* COMMANDS END */\r
- \r
- @Override\r
- protected void createActions() {\r
- super.createActions();\r
- \r
- createPageLengthSelect(CATEGORY_SIZE);\r
- \r
- createSelectionModeSelect(CATEGORY_SELECTION);\r
- createValueSelection(CATEGORY_SELECTION);\r
- \r
- createItemClickListener(CATEGORY_LISTENERS);\r
- createColumnResizeListenerCheckbox(CATEGORY_LISTENERS);\r
- createHeaderClickListenerCheckbox(CATEGORY_LISTENERS);\r
- createFooterClickListenerCheckbox(CATEGORY_LISTENERS);\r
- \r
- createRowHeaderModeSelect(CATEGORY_DATA_SOURCE);\r
- \r
- createHeaderVisibilitySelect(CATEGORY_HEADER);\r
- createHeaderTextCheckbox(CATEGORY_HEADER);\r
- \r
- createFooterVisibilityCheckbox(CATEGORY_FOOTER);\r
- createFooterTextSelect(CATEGORY_FOOTER);\r
- \r
- createColumnReorderingAllowedCheckbox(CATEGORY_FEATURES);\r
- createColumnCollapsingAllowedCheckbox(CATEGORY_FEATURES);\r
- \r
- createContextMenuAction(CATEGORY_FEATURES);\r
- \r
- createColumnHeaderMode(CATEGORY_FEATURES);\r
- createAddGeneratedColumnAction(CATEGORY_FEATURES);\r
- createCellStyleAction(CATEGORY_FEATURES);\r
- createGeneratedRowAction(CATEGORY_FEATURES);\r
- \r
- createBooleanAction("Sort enabled", CATEGORY_FEATURES, true,\r
- setSortEnabledCommand);\r
- createColumnOptions(true);\r
- }\r
- \r
- private void createAddGeneratedColumnAction(String categoryFeatures) {\r
- String category = "Generated columns";\r
- createCategory(category, categoryFeatures);\r
- createClickAction("Add Button", category, addGeneratedColumnCommand,\r
- new GeneratedColumn(Button.class, null, false));\r
- createClickAction("Add 200px wide Button", category,\r
- addGeneratedColumnCommand, new GeneratedColumn(Button.class,\r
- "200px", false));\r
- createClickAction("Add 100% wide Button", category,\r
- addGeneratedColumnCommand, new GeneratedColumn(Button.class,\r
- "100%", false));\r
- createClickAction("Add Label", category, addGeneratedColumnCommand,\r
- new GeneratedColumn(Label.class, null, false));\r
- createClickAction("Add 100px Label", category,\r
- addGeneratedColumnCommand, new GeneratedColumn(Label.class,\r
- "100px", false));\r
- createClickAction("Add 100% wide Label", category,\r
- addGeneratedColumnCommand, new GeneratedColumn(Label.class,\r
- "100%", false));\r
- \r
- createClickAction("Remove generated columns", category,\r
- removeGeneratedColumnsCommand, null);\r
- createClickAction("Add string as generated column", category,\r
- addGeneratedColumnCommand, new GeneratedColumn(String.class,\r
- "", false));\r
- createClickAction("Add HTML string as generated column", category,\r
- addGeneratedColumnCommand, new GeneratedColumn(String.class,\r
- "", true));\r
- createClickAction("Add 100px HTML Label", category,\r
- addGeneratedColumnCommand, new GeneratedColumn(Label.class,\r
- "100px", true));\r
- createClickAction("Add Object as generated column", category,\r
- addGeneratedColumnCommand, new GeneratedColumn(Object.class,\r
- "", false));\r
- }\r
- \r
- private void createCellStyleAction(String categoryFeatures) {\r
- LinkedHashMap<String, CellStyleInfo> options = new LinkedHashMap<String, CellStyleInfo>();\r
- options.put("None", null);\r
- options.put("Red row", new CellStyleInfo(\r
- "tables-test-cell-style-red-row", "Item 2", null));\r
- options.put("Red cell", new CellStyleInfo(\r
- "tables-test-cell-style-red-row", "Item 2", "Property 2"));\r
- createSelectAction("Cell style generator", categoryFeatures, options,\r
- "None", cellStyleCommand, true);\r
- }\r
- \r
- private void createGeneratedRowAction(String categoryFeatures) {\r
- LinkedHashMap<String, GeneratedRowInfo> options = new LinkedHashMap<String, GeneratedRowInfo>();\r
- options.put("None", null);\r
- options.put("Every fifth row, spanned", new GeneratedRowInfo(5, false,\r
- "foobarbaz this is a long one that should span."));\r
- int props = getComponent().getContainerPropertyIds().size();\r
- String[] text = new String[props];\r
- for (int ix = 0; ix < props; ix++) {\r
- text[ix] = "foo" + ix;\r
- }\r
- options.put("Every tenth row, no spanning", new GeneratedRowInfo(10,\r
- false, text));\r
- options.put(\r
- "Every eight row, spanned, html formatted",\r
- new GeneratedRowInfo(8, true,\r
- "<b>foo</b> <i>bar</i> <span style='color:red;text-size:0.5em;'>baz</span>"));\r
- options.put("Every row, spanned", new GeneratedRowInfo(1, false,\r
- "spanned"));\r
- createSelectAction("Row generator", categoryFeatures, options, "None",\r
- rowGeneratorCommand, true);\r
- }\r
- \r
- private void createColumnHeaderMode(String category) {\r
- LinkedHashMap<String, ColumnHeaderMode> columnHeaderModeOptions = new LinkedHashMap<String, ColumnHeaderMode>();\r
- columnHeaderModeOptions.put("Hidden", ColumnHeaderMode.HIDDEN);\r
- columnHeaderModeOptions.put("Id", ColumnHeaderMode.ID);\r
- columnHeaderModeOptions.put("Explicit", ColumnHeaderMode.EXPLICIT);\r
- columnHeaderModeOptions.put("Explicit defaults id",\r
- ColumnHeaderMode.EXPLICIT_DEFAULTS_ID);\r
- \r
- createSelectAction("Column header mode", category,\r
- columnHeaderModeOptions, "Explicit defaults id",\r
- columnHeaderModeCommand);\r
- }\r
- \r
- private void createValueSelection(String categorySelection) {\r
- LinkedHashMap<String, Object> options = new LinkedHashMap<String, Object>();\r
- options.put("null", null);\r
- for (int i = 1; i <= 10; i++) {\r
- options.put("Item " + i, "Item " + i);\r
- }\r
- createSelectAction("Value", categorySelection, options, null,\r
- setValueCommand);\r
- }\r
- \r
- private void createContextMenuAction(String category) {\r
- LinkedHashMap<String, ContextMenu> options = new LinkedHashMap<String, ContextMenu>();\r
- options.put("None", null);\r
- options.put("Item without icon", new ContextMenu("No icon", null));\r
- ContextMenu cm = new ContextMenu();\r
- cm.addItem("Caption only", null);\r
- cm.addItem("Has icon", ICON_16_USER_PNG_UNCACHEABLE);\r
- options.put("With and without icon", cm);\r
- options.put("Only one large icon", new ContextMenu("Icon",\r
- ICON_64_EMAIL_REPLY_PNG_UNCACHEABLE));\r
- options.put("Empty", new ContextMenu() {\r
- @Override\r
- public Action[] getActions(Object target, Object sender) {\r
- return null;\r
- }\r
- });\r
- options.put("Edit/New", new ContextMenu() {\r
- @Override\r
- public Action[] getActions(Object itemId, Object component) {\r
- if (itemId == null) {\r
- return new Action[] { new Action("New..."),\r
- new Action("Common action") };\r
- } else {\r
- return new Action[] { new Action("Edit " + itemId),\r
- new Action("Common action") };\r
- }\r
- }\r
- });\r
- \r
- createSelectAction("Context menu", category, options, "None",\r
- contextMenuCommand, true);\r
- }\r
- \r
- private void createColumnReorderingAllowedCheckbox(String category) {\r
- createBooleanAction("Column reordering allowed", category, true,\r
- new Command<T, Boolean>() {\r
- public void execute(Table c, Boolean value, Object data) {\r
- c.setColumnReorderingAllowed(value);\r
- }\r
- });\r
- }\r
- \r
- private void createColumnCollapsingAllowedCheckbox(String category) {\r
- createBooleanAction("Column collapsing allowed", category, true,\r
- new Command<T, Boolean>() {\r
- public void execute(T c, Boolean value, Object data) {\r
- c.setColumnCollapsingAllowed(value);\r
- }\r
- });\r
- }\r
- \r
- private void createColumnOptions(boolean init) {\r
- if (!init && !hasCategory(CATEGORY_COLUMNS)) {\r
- return;\r
- }\r
- \r
- long start = System.currentTimeMillis();\r
- if (!init) {\r
- removeCategory(CATEGORY_COLUMNS);\r
- }\r
- \r
- for (Object id : getComponent().getContainerPropertyIds()) {\r
- String name = id.toString();\r
- createCategory(name, CATEGORY_COLUMNS);\r
- createColumnOption(name, id);\r
- }\r
- for (int i = 0; i < generatedColumnNextNr; i++) {\r
- String id = generatedColumnId + i;\r
- String name = id;\r
- if (getTestComponents().get(0).getColumnGenerator(id) != null) {\r
- createCategory(name, CATEGORY_COLUMNS);\r
- createColumnOption(name, id);\r
- }\r
- }\r
- \r
- long end = System.currentTimeMillis();\r
- System.err.println("Create options took " + (end - start) + "ms");\r
- }\r
- \r
- private class Timer {\r
- private long start, last;\r
- \r
- private Timer() {\r
- start = System.currentTimeMillis();\r
- last = System.currentTimeMillis();\r
- }\r
- \r
- public void log(String msg) {\r
- long now = System.currentTimeMillis();\r
- System.err.println("[This: " + (now - last) + "ms, total: "\r
- + (now - start) + "ms]: " + msg);\r
- last = now;\r
- }\r
- }\r
- \r
- private void createColumnOption(String category, Object propertyId) {\r
- Timer t = new Timer();\r
- createBooleanAction("Visible", category, true, columnVisibleCommand,\r
- propertyId);\r
- t.log("Visible");\r
- createBooleanAction("Collapsed", category, false, columnCollapsed,\r
- propertyId);\r
- t.log("Collapsed");\r
- LinkedHashMap<String, Align> options = new LinkedHashMap<String, Align>();\r
- options.put("Left", Align.LEFT);\r
- options.put("Center", Align.CENTER);\r
- options.put("Right", Align.RIGHT);\r
- \r
- createSelectAction("Alignment", category, options, "Left",\r
- columnAlignmentCommand, propertyId);\r
- t.log("Alignment");\r
- LinkedHashMap<String, Integer> widthOptions = new LinkedHashMap<String, Integer>();\r
- widthOptions.put("- remove -", -1);\r
- for (int i : new int[] { 0, 1, 10, 100, 200, 400 }) {\r
- widthOptions.put(i + "px", i);\r
- }\r
- createSelectAction("Width", category, widthOptions, "- remove -",\r
- columnWidthCommand, propertyId);\r
- t.log("Width");\r
- \r
- LinkedHashMap<String, Resource> iconOptions = new LinkedHashMap<String, Resource>();\r
- iconOptions.put("- none -", null);\r
- iconOptions.put("ok 16x16", ICON_16_USER_PNG_CACHEABLE);\r
- iconOptions.put("help 16x16", ICON_16_HELP_PNG_CACHEABLE);\r
- iconOptions.put("folder 16x16", ICON_16_FOLDER_PNG_CACHEABLE);\r
- iconOptions.put("attention 32x32", ICON_32_ATTENTION_PNG_CACHEABLE);\r
- createSelectAction("Icon", category, iconOptions, "- none -",\r
- columnIconCommand, propertyId);\r
- \r
- t.log("Icon");\r
- LinkedHashMap<String, String> columnHeaderOptions = new LinkedHashMap<String, String>();\r
- columnHeaderOptions.put("- none -", null);\r
- columnHeaderOptions.put("A", "A");\r
- columnHeaderOptions.put("A nice column", "A nice column");\r
- \r
- createSelectAction("Column header", category, columnHeaderOptions,\r
- "- none -", columnHeaderCommand, propertyId);\r
- t.log("Header");\r
- LinkedHashMap<String, Float> expandOptions = new LinkedHashMap<String, Float>();\r
- expandOptions.put("- remove -", -1f);\r
- for (float i : new float[] { 0, 1, 2, 3, 4, 5 }) {\r
- expandOptions.put(i + "", i);\r
- }\r
- createSelectAction("Expand ratio", category, expandOptions,\r
- "- remove -", columnExpandRatioCommand, propertyId);\r
- t.log("Expand");\r
- // Footer text (move)\r
- // Header text (move)\r
- \r
- }\r
- \r
- private void createRowHeaderModeSelect(String category) {\r
- LinkedHashMap<String, RowHeaderMode> options = new LinkedHashMap<String, RowHeaderMode>();\r
- options.put("Explicit", RowHeaderMode.EXPLICIT);\r
- options.put("Explicit defaults id", RowHeaderMode.EXPLICIT_DEFAULTS_ID);\r
- options.put("Hidden", RowHeaderMode.HIDDEN);\r
- options.put("Icon only", RowHeaderMode.ICON_ONLY);\r
- options.put("Id", RowHeaderMode.ID);\r
- options.put("Index", RowHeaderMode.INDEX);\r
- options.put("Item", RowHeaderMode.ITEM);\r
- options.put("'Property 3' property", RowHeaderMode.PROPERTY);\r
- \r
- createSelectAction("Row header mode", category, options, "Hidden",\r
- rowHeaderModeCommand);\r
- }\r
- \r
- private void createFooterTextSelect(String category) {\r
- LinkedHashMap<String, String> options = new LinkedHashMap<String, String>();\r
- options.put("None", null);\r
- options.put("Footer X", "Footer {id}");\r
- options.put("X", "{id}");\r
- \r
- createSelectAction("Texts in footer", category, options, "None",\r
- footerTextCommand);\r
- }\r
- \r
- private void createHeaderTextCheckbox(String category) {\r
- LinkedHashMap<String, String> options = new LinkedHashMap<String, String>();\r
- options.put("None", null);\r
- options.put("Col: {id}", "Col: {id}");\r
- options.put("Header {id} - every second", "Header {id}");\r
- \r
- createSelectAction("Texts in header", category, options, "None",\r
- new Command<T, String>() {\r
- public void execute(T c, String value, Object data) {\r
- int nr = 0;\r
- for (Object propertyId : c.getContainerPropertyIds()) {\r
- nr++;\r
- if (value != null && value.equals("Header {id}")\r
- && nr % 2 == 0) {\r
- c.setColumnHeader(propertyId, null);\r
- } else if (value != null) {\r
- c.setColumnHeader(\r
- propertyId,\r
- value.replace("{id}",\r
- propertyId.toString()));\r
- } else {\r
- c.setColumnHeader(propertyId, null);\r
- }\r
- }\r
- \r
- }\r
- });\r
- }\r
- \r
- private void createHeaderClickListenerCheckbox(String category) {\r
- \r
- createBooleanAction("Header click listener", category, false,\r
- headerClickListenerCommand);\r
- }\r
- \r
- private void createFooterClickListenerCheckbox(String category) {\r
- \r
- createBooleanAction("Footer click listener", category, false,\r
- footerClickListenerCommand);\r
- }\r
- \r
- private void createColumnResizeListenerCheckbox(String category) {\r
- \r
- createBooleanAction("Column resize listener", category, false,\r
- columnResizeListenerCommand);\r
- }\r
- \r
- // TODO:\r
- // setCurrentPageFirstItemIndex()\r
- // Editable\r
- // Cache rate\r
- // CurrentPageFirstItemId\r
- \r
- protected void createFooterVisibilityCheckbox(String category) {\r
- createBooleanAction("Footer visible", category, true,\r
- new Command<T, Boolean>() {\r
- \r
- public void execute(T c, Boolean value, Object data) {\r
- c.setFooterVisible(value);\r
- }\r
- });\r
- }\r
- \r
- protected void createHeaderVisibilitySelect(String category) {\r
- LinkedHashMap<String, ColumnHeaderMode> options = new LinkedHashMap<String, ColumnHeaderMode>();\r
- options.put("Explicit", ColumnHeaderMode.EXPLICIT);\r
- options.put("Explicit defaults id",\r
- ColumnHeaderMode.EXPLICIT_DEFAULTS_ID);\r
- options.put("Id", ColumnHeaderMode.ID);\r
- options.put("Hidden", ColumnHeaderMode.HIDDEN);\r
- \r
- createSelectAction("Header mode", category, options,\r
- "Explicit defaults id", new Command<T, ColumnHeaderMode>() {\r
- \r
- public void execute(T c, ColumnHeaderMode value, Object data) {\r
- c.setColumnHeaderMode(value);\r
- \r
- }\r
- });\r
- }\r
- \r
- protected void createPageLengthSelect(String category) {\r
- LinkedHashMap<String, Integer> options = new LinkedHashMap<String, Integer>();\r
- options.put("0", 0);\r
- options.put("5", 5);\r
- options.put("10", 10);\r
- options.put("20", 20);\r
- options.put("50", 50);\r
- \r
- createSelectAction("PageLength", category, options, "10",\r
- new Command<T, Integer>() {\r
- \r
- public void execute(Table t, Integer value, Object data) {\r
- t.setPageLength(value);\r
- }\r
- });\r
- }\r
- \r
- private enum SelectMode {\r
- NONE, SINGLE, MULTI_SIMPLE, MULTI;\r
- }\r
- \r
- protected void createSelectionModeSelect(String category) {\r
- LinkedHashMap<String, SelectMode> options = new LinkedHashMap<String, SelectMode>();\r
- options.put("None", SelectMode.NONE);\r
- options.put("Single", SelectMode.SINGLE);\r
- options.put("Multi - simple", SelectMode.MULTI_SIMPLE);\r
- options.put("Multi - ctrl/shift", SelectMode.MULTI);\r
- \r
- createSelectAction("Selection Mode", category, options,\r
- "Multi - ctrl/shift", new Command<T, SelectMode>() {\r
- \r
- public void execute(Table t, SelectMode value, Object data) {\r
- switch (value) {\r
- case NONE:\r
- t.setSelectable(false);\r
- break;\r
- case SINGLE:\r
- t.setMultiSelect(false);\r
- t.setSelectable(true);\r
- break;\r
- case MULTI_SIMPLE:\r
- t.setSelectable(true);\r
- t.setMultiSelect(true);\r
- t.setMultiSelectMode(MultiSelectMode.SIMPLE);\r
- break;\r
- case MULTI:\r
- t.setSelectable(true);\r
- t.setMultiSelect(true);\r
- t.setMultiSelectMode(MultiSelectMode.DEFAULT);\r
- break;\r
- }\r
- }\r
- });\r
- }\r
- \r
- public void columnResize(ColumnResizeEvent event) {\r
- log("ColumnResize on " + event.getPropertyId() + " from "\r
- + event.getPreviousWidth() + " to " + event.getCurrentWidth());\r
- }\r
- \r
- public void footerClick(FooterClickEvent event) {\r
- log("FooterClick on " + event.getPropertyId() + " using "\r
- + event.getButtonName());\r
- }\r
- \r
- public void headerClick(HeaderClickEvent event) {\r
- log("HeaderClick on " + event.getPropertyId() + " using "\r
- + event.getButtonName());\r
- }\r
- \r
- @Override\r
- protected void updateContainer() {\r
- super.updateContainer();\r
- \r
- // Recreate for the new properties\r
- createColumnOptions(false);\r
- \r
- }\r
- \r
- }\r
+ package com.vaadin.tests.components.table;
+
+ import java.util.ArrayList;
+ import java.util.Arrays;
+ import java.util.LinkedHashMap;
+ import java.util.List;
+
+ import com.vaadin.event.Action;
+ import com.vaadin.event.Action.Handler;
+ import com.vaadin.event.ItemClickEvent.ItemClickListener;
+ import com.vaadin.terminal.Resource;
+ import com.vaadin.tests.components.select.AbstractSelectTestCase;
+ import com.vaadin.ui.AbstractSelect.MultiSelectMode;
+ import com.vaadin.ui.Button;
+ import com.vaadin.ui.Label;
++import com.vaadin.ui.Label.ContentMode;
+ import com.vaadin.ui.Table;
++import com.vaadin.ui.Table.Align;
+ import com.vaadin.ui.Table.CellStyleGenerator;
+ import com.vaadin.ui.Table.ColumnGenerator;
++import com.vaadin.ui.Table.ColumnHeaderMode;
+ import com.vaadin.ui.Table.ColumnResizeEvent;
+ import com.vaadin.ui.Table.ColumnResizeListener;
+ import com.vaadin.ui.Table.FooterClickEvent;
+ import com.vaadin.ui.Table.FooterClickListener;
+ import com.vaadin.ui.Table.GeneratedRow;
+ import com.vaadin.ui.Table.HeaderClickEvent;
+ import com.vaadin.ui.Table.HeaderClickListener;
+ import com.vaadin.ui.Table.RowGenerator;
++import com.vaadin.ui.Table.RowHeaderMode;
+
+ public class Tables<T extends Table> extends AbstractSelectTestCase<T>
+ implements ItemClickListener, HeaderClickListener, FooterClickListener,
+ ColumnResizeListener {
+
+ protected static final String CATEGORY_ROWS = "Rows";
+ private static final String CATEGORY_HEADER = "Header";
+ private static final String CATEGORY_FOOTER = "Footer";
+ private static final String CATEGORY_COLUMNS = "Columns";
+
++ @SuppressWarnings("unchecked")
+ @Override
+ protected Class<T> getTestClass() {
- return (Class) Table.class;
++ return (Class<T>) Table.class;
+ }
+
+ /* COMMANDS */
- private Command<T, String> columnAlignmentCommand = new Command<T, String>() {
++ private Command<T, Align> columnAlignmentCommand = new Command<T, Align>() {
+
- public void execute(T c, String alignment, Object propertyId) {
++ public void execute(T c, Align alignment, Object propertyId) {
+ c.setColumnAlignment(propertyId, alignment);
+ }
+
+ };
+
+ private Command<T, Boolean> columnVisibleCommand = new Command<T, Boolean>() {
+ public void execute(Table c, Boolean visible, Object propertyId) {
+ List<Object> visibleColumns = new ArrayList<Object>(Arrays.asList(c
+ .getVisibleColumns()));
+ if (visible) {
+ // Table should really check this... Completely fails without
+ // the check (#
+ if (!visibleColumns.contains(propertyId)) {
+ visibleColumns.add(propertyId);
+ }
+ } else {
+ visibleColumns.remove(propertyId);
+ }
+ c.setVisibleColumns(visibleColumns.toArray());
+ }
+ };
+
+ private Command<T, Boolean> columnCollapsed = new Command<T, Boolean>() {
+
+ public void execute(T c, Boolean collapsed, Object propertyId) {
+ c.setColumnCollapsed(propertyId, collapsed);
+
+ }
+ };
+
+ protected Command<T, Boolean> columnResizeListenerCommand = new Command<T, Boolean>() {
+
+ public void execute(Table c, Boolean value, Object data) {
+ if (value) {
+ c.addListener((ColumnResizeListener) Tables.this);
+ } else {
+ c.removeListener((ColumnResizeListener) Tables.this);
+ }
+ }
+ };
+
+ protected Command<T, Boolean> headerClickListenerCommand = new Command<T, Boolean>() {
+
+ public void execute(T c, Boolean value, Object data) {
+ if (value) {
+ c.addListener((HeaderClickListener) Tables.this);
+ } else {
+ c.removeListener((HeaderClickListener) Tables.this);
+ }
+ }
+ };
+
+ protected Command<T, Boolean> footerClickListenerCommand = new Command<T, Boolean>() {
+
+ public void execute(Table c, Boolean value, Object data) {
+ if (value) {
+ c.addListener((FooterClickListener) Tables.this);
+ } else {
+ c.removeListener((FooterClickListener) Tables.this);
+ }
+ }
+ };
+
- protected Command<T, Integer> rowHeaderModeCommand = new Command<T, Integer>() {
++ protected Command<T, RowHeaderMode> rowHeaderModeCommand = new Command<T, RowHeaderMode>() {
+
- public void execute(Table c, Integer value, Object data) {
- if (value == Table.ROW_HEADER_MODE_PROPERTY) {
++ public void execute(Table c, RowHeaderMode value, Object data) {
++ if (value == RowHeaderMode.PROPERTY) {
+ c.setItemCaptionPropertyId("Property 3");
+ }
+ c.setRowHeaderMode(value);
+ }
+ };
+
+ protected Command<T, String> footerTextCommand = new Command<T, String>() {
+
+ public void execute(Table c, String value, Object data) {
+ for (Object propertyId : c.getContainerPropertyIds()) {
+ if (value != null) {
+ c.setColumnFooter(propertyId,
+ value.replace("{id}", propertyId.toString()));
+ } else {
+ c.setColumnFooter(propertyId, null);
+ }
+ }
+ }
+ };
+
+ protected Command<T, Object> alignColumnLeftCommand = new Command<T, Object>() {
+
+ public void execute(T c, Object propertyId, Object data) {
- c.setColumnAlignment(propertyId, (String) data);
++ c.setColumnAlignment(propertyId, (Align) data);
+ }
+ };
+
+ private Command<T, ContextMenu> contextMenuCommand = new Command<T, ContextMenu>() {
+
+ public void execute(T c, final ContextMenu value, Object data) {
+ c.removeAllActionHandlers();
+ if (value != null) {
+ c.addActionHandler(new Handler() {
+
+ public void handleAction(Action action, Object sender,
+ Object target) {
+ log("Action " + action.getCaption() + " performed on "
+ + target);
+ }
+
+ public Action[] getActions(Object target, Object sender) {
+ return value.getActions(target, sender);
+ }
+ });
+ }
+ }
+ };
+ private Command<T, Integer> columnWidthCommand = new Command<T, Integer>() {
+
+ public void execute(T c, Integer width, Object propertyId) {
+ c.setColumnWidth(propertyId, width);
+
+ }
+ };
+
+ private Command<T, Resource> columnIconCommand = new Command<T, Resource>() {
+
+ public void execute(T c, Resource icon, Object propertyId) {
+ c.setColumnIcon(propertyId, icon);
+
+ }
+ };
- private Command<T, Integer> columnHeaderModeCommand = new Command<T, Integer>() {
++ private Command<T, ColumnHeaderMode> columnHeaderModeCommand = new Command<T, ColumnHeaderMode>() {
+
- public void execute(T c, Integer columnHeaderMode, Object data) {
++ public void execute(T c, ColumnHeaderMode columnHeaderMode, Object data) {
+ c.setColumnHeaderMode(columnHeaderMode);
+
+ }
+ };
+ private Command<T, String> columnHeaderCommand = new Command<T, String>() {
+
+ public void execute(T c, String header, Object propertyId) {
+ c.setColumnHeader(propertyId, header);
+
+ }
+ };
+ private Command<T, Float> columnExpandRatioCommand = new Command<T, Float>() {
+
+ public void execute(T c, Float expandRatio, Object propertyId) {
+ c.setColumnExpandRatio(propertyId, expandRatio);
+ }
+ };
+
+ private class GeneratedColumn {
+ private Class<?> type;
+ private String width;
+ private boolean html;
+
+ public GeneratedColumn(Class<?> type, String width, boolean html) {
+ super();
+ this.type = type;
+ this.width = width;
+ this.html = html;
+ }
+ }
+
+ String generatedColumnId = "Generated ";
+ int generatedColumnNextNr = 1;
+
+ private Command<T, GeneratedColumn> addGeneratedColumnCommand = new Command<T, GeneratedColumn>() {
+
+ public void execute(T c, final GeneratedColumn col, Object data) {
+ while (c.getColumnGenerator(generatedColumnId
+ + generatedColumnNextNr) != null) {
+ generatedColumnNextNr++;
+ }
+
+ c.addGeneratedColumn(generatedColumnId + generatedColumnNextNr,
+ new ColumnGenerator() {
+
+ public Object generateCell(Table source, Object itemId,
+ Object columnId) {
+ String value = "";
+ if (col.html) {
+ value = "<i>" + itemId + "</i>" + "/" + "<b>"
+ + columnId + "</b>";
+ } else {
+ value = itemId + "/" + columnId;
+ }
+ if (col.type == Button.class) {
+ Button b = new Button();
+ b.setCaption(value);
+ b.setWidth(col.width);
+ return b;
+ } else if (col.type == Label.class) {
+ Label l = new Label();
+ l.setWidth(col.width);
+ if (col.html) {
+ l.setValue(value);
- l.setContentMode(Label.CONTENT_XHTML);
++ l.setContentMode(ContentMode.XHTML);
+ } else {
+ l.setValue(value);
+ }
+ return l;
+ } else if (col.type == String.class) {
+ return value;
+ } else if (col.type == Object.class) {
+ return new Object();
+ }
+
+ return null;
+ }
+ });
+ generatedColumnNextNr++;
+ createColumnOptions(false);
+
+ }
+ };
+ private Command<T, Object> removeGeneratedColumnsCommand = new Command<T, Object>() {
+
+ public void execute(T c, Object value, Object data) {
+ for (int i = 0; i < generatedColumnNextNr; i++) {
+ String columnId = generatedColumnId + i;
+ if (c.getColumnGenerator(columnId) != null) {
+ c.removeGeneratedColumn(columnId);
+ }
+
+ }
+ createColumnOptions(false);
+
+ }
+ };
+
+ private class CellStyleInfo {
+ private final String styleName;
+ private final Object itemId;
+ private final Object propertyId;
+
+ public CellStyleInfo(String styleName, Object itemId, Object propertyId) {
+ this.styleName = styleName;
+ this.itemId = itemId;
+ this.propertyId = propertyId;
+ }
+
+ public boolean appliesTo(Object itemId, Object propertyId) {
+ return (this.itemId != null && this.itemId.equals(itemId))
+ && (this.propertyId == propertyId || (this.propertyId != null && this.propertyId
+ .equals(propertyId)));
+ }
+ }
+
+ private Command<T, CellStyleInfo> cellStyleCommand = new Command<T, CellStyleInfo>() {
+
+ public void execute(T c, final CellStyleInfo cellStyleInfo, Object data) {
+ if (cellStyleInfo == null) {
+ c.setCellStyleGenerator(null);
+ } else {
+ c.setCellStyleGenerator(new CellStyleGenerator() {
+
+ public String getStyle(Object itemId, Object propertyId) {
+ if (cellStyleInfo.appliesTo(itemId, propertyId)) {
+ return cellStyleInfo.styleName;
+ }
+ return null;
+ }
+ });
+ }
+ }
+ };
+
+ private class GeneratedRowInfo {
+
+ private final int nth;
+ private final String[] text;
+ private final boolean isHtml;
+
+ public GeneratedRowInfo(int nth, boolean isHtml, String... text) {
+ this.nth = nth;
+ this.isHtml = isHtml;
+ this.text = text;
+ }
+
+ public boolean appliesTo(Object itemId) {
+ int ix = Integer.valueOf(itemId.toString().substring(5));
+ return ix % nth == 0;
+ }
+
+ @Override
+ public String toString() {
+ return String.format("%d, %s, %s", nth, isHtml ? "true" : "false",
+ Arrays.toString(text));
+ }
+ }
+
+ private Command<T, GeneratedRowInfo> rowGeneratorCommand = new Command<T, GeneratedRowInfo>() {
+
+ public void execute(T c, final GeneratedRowInfo generatedRowInfo,
+ Object data) {
+ if (generatedRowInfo == null) {
+ c.setRowGenerator(null);
+ } else {
+ c.setRowGenerator(new RowGenerator() {
+
+ public GeneratedRow generateRow(Table table, Object itemId) {
+ if (generatedRowInfo.appliesTo(itemId)) {
+ GeneratedRow generatedRow = new GeneratedRow(
+ generatedRowInfo.text);
+ generatedRow
+ .setHtmlContentAllowed(generatedRowInfo.isHtml);
+ return generatedRow;
+ }
+ return null;
+ }
+ });
+ }
+ }
+ };
+
+ private Command<T, Boolean> setSortEnabledCommand = new Command<T, Boolean>() {
+
+ public void execute(T c, Boolean value, Object data) {
+ c.setSortDisabled(!value);
+
+ }
+ };
+
+ /* COMMANDS END */
+
+ @Override
+ protected void createActions() {
+ super.createActions();
+
+ createPageLengthSelect(CATEGORY_SIZE);
+
+ createSelectionModeSelect(CATEGORY_SELECTION);
+ createValueSelection(CATEGORY_SELECTION);
+
+ createItemClickListener(CATEGORY_LISTENERS);
+ createColumnResizeListenerCheckbox(CATEGORY_LISTENERS);
+ createHeaderClickListenerCheckbox(CATEGORY_LISTENERS);
+ createFooterClickListenerCheckbox(CATEGORY_LISTENERS);
+
+ createRowHeaderModeSelect(CATEGORY_DATA_SOURCE);
+
+ createHeaderVisibilitySelect(CATEGORY_HEADER);
+ createHeaderTextCheckbox(CATEGORY_HEADER);
+
+ createFooterVisibilityCheckbox(CATEGORY_FOOTER);
+ createFooterTextSelect(CATEGORY_FOOTER);
+
+ createColumnReorderingAllowedCheckbox(CATEGORY_FEATURES);
+ createColumnCollapsingAllowedCheckbox(CATEGORY_FEATURES);
+
+ createContextMenuAction(CATEGORY_FEATURES);
+
+ createColumnHeaderMode(CATEGORY_FEATURES);
+ createAddGeneratedColumnAction(CATEGORY_FEATURES);
+ createCellStyleAction(CATEGORY_FEATURES);
+ createGeneratedRowAction(CATEGORY_FEATURES);
+
+ createBooleanAction("Sort enabled", CATEGORY_FEATURES, true,
+ setSortEnabledCommand);
+ createColumnOptions(true);
+ }
+
+ private void createAddGeneratedColumnAction(String categoryFeatures) {
+ String category = "Generated columns";
+ createCategory(category, categoryFeatures);
+ createClickAction("Add Button", category, addGeneratedColumnCommand,
+ new GeneratedColumn(Button.class, null, false));
+ createClickAction("Add 200px wide Button", category,
+ addGeneratedColumnCommand, new GeneratedColumn(Button.class,
+ "200px", false));
+ createClickAction("Add 100% wide Button", category,
+ addGeneratedColumnCommand, new GeneratedColumn(Button.class,
+ "100%", false));
+ createClickAction("Add Label", category, addGeneratedColumnCommand,
+ new GeneratedColumn(Label.class, null, false));
+ createClickAction("Add 100px Label", category,
+ addGeneratedColumnCommand, new GeneratedColumn(Label.class,
+ "100px", false));
+ createClickAction("Add 100% wide Label", category,
+ addGeneratedColumnCommand, new GeneratedColumn(Label.class,
+ "100%", false));
+
+ createClickAction("Remove generated columns", category,
+ removeGeneratedColumnsCommand, null);
+ createClickAction("Add string as generated column", category,
+ addGeneratedColumnCommand, new GeneratedColumn(String.class,
+ "", false));
+ createClickAction("Add HTML string as generated column", category,
+ addGeneratedColumnCommand, new GeneratedColumn(String.class,
+ "", true));
+ createClickAction("Add 100px HTML Label", category,
+ addGeneratedColumnCommand, new GeneratedColumn(Label.class,
+ "100px", true));
+ createClickAction("Add Object as generated column", category,
+ addGeneratedColumnCommand, new GeneratedColumn(Object.class,
+ "", false));
+ }
+
+ private void createCellStyleAction(String categoryFeatures) {
+ LinkedHashMap<String, CellStyleInfo> options = new LinkedHashMap<String, CellStyleInfo>();
+ options.put("None", null);
+ options.put("Red row", new CellStyleInfo(
+ "tables-test-cell-style-red-row", "Item 2", null));
+ options.put("Red cell", new CellStyleInfo(
+ "tables-test-cell-style-red-row", "Item 2", "Property 2"));
+ createSelectAction("Cell style generator", categoryFeatures, options,
+ "None", cellStyleCommand, true);
+ }
+
+ private void createGeneratedRowAction(String categoryFeatures) {
+ LinkedHashMap<String, GeneratedRowInfo> options = new LinkedHashMap<String, GeneratedRowInfo>();
+ options.put("None", null);
+ options.put("Every fifth row, spanned", new GeneratedRowInfo(5, false,
+ "foobarbaz this is a long one that should span."));
+ int props = getComponent().getContainerPropertyIds().size();
+ String[] text = new String[props];
+ for (int ix = 0; ix < props; ix++) {
+ text[ix] = "foo" + ix;
+ }
+ options.put("Every tenth row, no spanning", new GeneratedRowInfo(10,
+ false, text));
+ options.put(
+ "Every eight row, spanned, html formatted",
+ new GeneratedRowInfo(8, true,
+ "<b>foo</b> <i>bar</i> <span style='color:red;text-size:0.5em;'>baz</span>"));
+ options.put("Every row, spanned", new GeneratedRowInfo(1, false,
+ "spanned"));
+ createSelectAction("Row generator", categoryFeatures, options, "None",
+ rowGeneratorCommand, true);
+ }
+
+ private void createColumnHeaderMode(String category) {
- LinkedHashMap<String, Integer> columnHeaderModeOptions = new LinkedHashMap<String, Integer>();
- columnHeaderModeOptions.put("Hidden", Table.COLUMN_HEADER_MODE_HIDDEN);
- columnHeaderModeOptions.put("Id", Table.COLUMN_HEADER_MODE_ID);
- columnHeaderModeOptions.put("Explicit",
- Table.COLUMN_HEADER_MODE_EXPLICIT);
++ LinkedHashMap<String, ColumnHeaderMode> columnHeaderModeOptions = new LinkedHashMap<String, ColumnHeaderMode>();
++ columnHeaderModeOptions.put("Hidden", ColumnHeaderMode.HIDDEN);
++ columnHeaderModeOptions.put("Id", ColumnHeaderMode.ID);
++ columnHeaderModeOptions.put("Explicit", ColumnHeaderMode.EXPLICIT);
+ columnHeaderModeOptions.put("Explicit defaults id",
- Table.COLUMN_HEADER_MODE_EXPLICIT_DEFAULTS_ID);
++ ColumnHeaderMode.EXPLICIT_DEFAULTS_ID);
+
+ createSelectAction("Column header mode", category,
+ columnHeaderModeOptions, "Explicit defaults id",
+ columnHeaderModeCommand);
+ }
+
+ private void createValueSelection(String categorySelection) {
+ LinkedHashMap<String, Object> options = new LinkedHashMap<String, Object>();
+ options.put("null", null);
+ for (int i = 1; i <= 10; i++) {
+ options.put("Item " + i, "Item " + i);
+ }
+ createSelectAction("Value", categorySelection, options, null,
+ setValueCommand);
+ }
+
+ private void createContextMenuAction(String category) {
+ LinkedHashMap<String, ContextMenu> options = new LinkedHashMap<String, ContextMenu>();
+ options.put("None", null);
+ options.put("Item without icon", new ContextMenu("No icon", null));
+ ContextMenu cm = new ContextMenu();
+ cm.addItem("Caption only", null);
+ cm.addItem("Has icon", ICON_16_USER_PNG_UNCACHEABLE);
+ options.put("With and without icon", cm);
+ options.put("Only one large icon", new ContextMenu("Icon",
+ ICON_64_EMAIL_REPLY_PNG_UNCACHEABLE));
+ options.put("Empty", new ContextMenu() {
+ @Override
+ public Action[] getActions(Object target, Object sender) {
+ return null;
+ }
+ });
+ options.put("Edit/New", new ContextMenu() {
+ @Override
+ public Action[] getActions(Object itemId, Object component) {
+ if (itemId == null) {
+ return new Action[] { new Action("New..."),
+ new Action("Common action") };
+ } else {
+ return new Action[] { new Action("Edit " + itemId),
+ new Action("Common action") };
+ }
+ }
+ });
+
+ createSelectAction("Context menu", category, options, "None",
+ contextMenuCommand, true);
+ }
+
+ private void createColumnReorderingAllowedCheckbox(String category) {
+ createBooleanAction("Column reordering allowed", category, true,
+ new Command<T, Boolean>() {
+ public void execute(Table c, Boolean value, Object data) {
+ c.setColumnReorderingAllowed(value);
+ }
+ });
+ }
+
+ private void createColumnCollapsingAllowedCheckbox(String category) {
+ createBooleanAction("Column collapsing allowed", category, true,
+ new Command<T, Boolean>() {
+ public void execute(T c, Boolean value, Object data) {
+ c.setColumnCollapsingAllowed(value);
+ }
+ });
+ }
+
+ private void createColumnOptions(boolean init) {
+ if (!init && !hasCategory(CATEGORY_COLUMNS)) {
+ return;
+ }
+
+ long start = System.currentTimeMillis();
+ if (!init) {
+ removeCategory(CATEGORY_COLUMNS);
+ }
+
+ for (Object id : getComponent().getContainerPropertyIds()) {
+ String name = id.toString();
+ createCategory(name, CATEGORY_COLUMNS);
+ createColumnOption(name, id);
+ }
+ for (int i = 0; i < generatedColumnNextNr; i++) {
+ String id = generatedColumnId + i;
+ String name = id;
+ if (getTestComponents().get(0).getColumnGenerator(id) != null) {
+ createCategory(name, CATEGORY_COLUMNS);
+ createColumnOption(name, id);
+ }
+ }
+
+ long end = System.currentTimeMillis();
+ System.err.println("Create options took " + (end - start) + "ms");
+ }
+
+ private class Timer {
+ private long start, last;
+
+ private Timer() {
+ start = System.currentTimeMillis();
+ last = System.currentTimeMillis();
+ }
+
+ public void log(String msg) {
+ long now = System.currentTimeMillis();
+ System.err.println("[This: " + (now - last) + "ms, total: "
+ + (now - start) + "ms]: " + msg);
+ last = now;
+ }
+ }
+
+ private void createColumnOption(String category, Object propertyId) {
+ Timer t = new Timer();
+ createBooleanAction("Visible", category, true, columnVisibleCommand,
+ propertyId);
+ t.log("Visible");
+ createBooleanAction("Collapsed", category, false, columnCollapsed,
+ propertyId);
+ t.log("Collapsed");
- LinkedHashMap<String, String> options = new LinkedHashMap<String, String>();
- options.put("Left", Table.ALIGN_LEFT);
- options.put("Center", Table.ALIGN_CENTER);
- options.put("Right", Table.ALIGN_RIGHT);
++ LinkedHashMap<String, Align> options = new LinkedHashMap<String, Align>();
++ options.put("Left", Align.LEFT);
++ options.put("Center", Align.CENTER);
++ options.put("Right", Align.RIGHT);
+
+ createSelectAction("Alignment", category, options, "Left",
+ columnAlignmentCommand, propertyId);
+ t.log("Alignment");
+ LinkedHashMap<String, Integer> widthOptions = new LinkedHashMap<String, Integer>();
+ widthOptions.put("- remove -", -1);
+ for (int i : new int[] { 0, 1, 10, 100, 200, 400 }) {
+ widthOptions.put(i + "px", i);
+ }
+ createSelectAction("Width", category, widthOptions, "- remove -",
+ columnWidthCommand, propertyId);
+ t.log("Width");
+
+ LinkedHashMap<String, Resource> iconOptions = new LinkedHashMap<String, Resource>();
+ iconOptions.put("- none -", null);
+ iconOptions.put("ok 16x16", ICON_16_USER_PNG_CACHEABLE);
+ iconOptions.put("help 16x16", ICON_16_HELP_PNG_CACHEABLE);
+ iconOptions.put("folder 16x16", ICON_16_FOLDER_PNG_CACHEABLE);
+ iconOptions.put("attention 32x32", ICON_32_ATTENTION_PNG_CACHEABLE);
+ createSelectAction("Icon", category, iconOptions, "- none -",
+ columnIconCommand, propertyId);
+
+ t.log("Icon");
+ LinkedHashMap<String, String> columnHeaderOptions = new LinkedHashMap<String, String>();
+ columnHeaderOptions.put("- none -", null);
+ columnHeaderOptions.put("A", "A");
+ columnHeaderOptions.put("A nice column", "A nice column");
+
+ createSelectAction("Column header", category, columnHeaderOptions,
+ "- none -", columnHeaderCommand, propertyId);
+ t.log("Header");
+ LinkedHashMap<String, Float> expandOptions = new LinkedHashMap<String, Float>();
+ expandOptions.put("- remove -", -1f);
+ for (float i : new float[] { 0, 1, 2, 3, 4, 5 }) {
+ expandOptions.put(i + "", i);
+ }
+ createSelectAction("Expand ratio", category, expandOptions,
+ "- remove -", columnExpandRatioCommand, propertyId);
+ t.log("Expand");
+ // Footer text (move)
+ // Header text (move)
+
+ }
+
+ private void createRowHeaderModeSelect(String category) {
- LinkedHashMap<String, Integer> options = new LinkedHashMap<String, Integer>();
- options.put("Explicit", Table.ROW_HEADER_MODE_EXPLICIT);
- options.put("Explicit defaults id",
- Table.ROW_HEADER_MODE_EXPLICIT_DEFAULTS_ID);
- options.put("Hidden", Table.ROW_HEADER_MODE_HIDDEN);
- options.put("Icon only", Table.ROW_HEADER_MODE_ICON_ONLY);
- options.put("Id", Table.ROW_HEADER_MODE_ID);
- options.put("Index", Table.ROW_HEADER_MODE_INDEX);
- options.put("Item", Table.ROW_HEADER_MODE_ITEM);
- options.put("'Property 3' property", Table.ROW_HEADER_MODE_PROPERTY);
++ LinkedHashMap<String, RowHeaderMode> options = new LinkedHashMap<String, RowHeaderMode>();
++ options.put("Explicit", RowHeaderMode.EXPLICIT);
++ options.put("Explicit defaults id", RowHeaderMode.EXPLICIT_DEFAULTS_ID);
++ options.put("Hidden", RowHeaderMode.HIDDEN);
++ options.put("Icon only", RowHeaderMode.ICON_ONLY);
++ options.put("Id", RowHeaderMode.ID);
++ options.put("Index", RowHeaderMode.INDEX);
++ options.put("Item", RowHeaderMode.ITEM);
++ options.put("'Property 3' property", RowHeaderMode.PROPERTY);
+
+ createSelectAction("Row header mode", category, options, "Hidden",
+ rowHeaderModeCommand);
+ }
+
+ private void createFooterTextSelect(String category) {
+ LinkedHashMap<String, String> options = new LinkedHashMap<String, String>();
+ options.put("None", null);
+ options.put("Footer X", "Footer {id}");
+ options.put("X", "{id}");
+
+ createSelectAction("Texts in footer", category, options, "None",
+ footerTextCommand);
+ }
+
+ private void createHeaderTextCheckbox(String category) {
+ LinkedHashMap<String, String> options = new LinkedHashMap<String, String>();
+ options.put("None", null);
+ options.put("Col: {id}", "Col: {id}");
+ options.put("Header {id} - every second", "Header {id}");
+
+ createSelectAction("Texts in header", category, options, "None",
+ new Command<T, String>() {
+ public void execute(T c, String value, Object data) {
+ int nr = 0;
+ for (Object propertyId : c.getContainerPropertyIds()) {
+ nr++;
+ if (value != null && value.equals("Header {id}")
+ && nr % 2 == 0) {
+ c.setColumnHeader(propertyId, null);
+ } else if (value != null) {
+ c.setColumnHeader(
+ propertyId,
+ value.replace("{id}",
+ propertyId.toString()));
+ } else {
+ c.setColumnHeader(propertyId, null);
+ }
+ }
+
+ }
+ });
+ }
+
+ private void createHeaderClickListenerCheckbox(String category) {
+
+ createBooleanAction("Header click listener", category, false,
+ headerClickListenerCommand);
+ }
+
+ private void createFooterClickListenerCheckbox(String category) {
+
+ createBooleanAction("Footer click listener", category, false,
+ footerClickListenerCommand);
+ }
+
+ private void createColumnResizeListenerCheckbox(String category) {
+
+ createBooleanAction("Column resize listener", category, false,
+ columnResizeListenerCommand);
+ }
+
+ // TODO:
+ // setCurrentPageFirstItemIndex()
+ // Editable
+ // Cache rate
+ // CurrentPageFirstItemId
+
+ protected void createFooterVisibilityCheckbox(String category) {
+ createBooleanAction("Footer visible", category, true,
+ new Command<T, Boolean>() {
+
+ public void execute(T c, Boolean value, Object data) {
+ c.setFooterVisible(value);
+ }
+ });
+ }
+
+ protected void createHeaderVisibilitySelect(String category) {
- LinkedHashMap<String, Integer> options = new LinkedHashMap<String, Integer>();
- options.put("Explicit", Table.COLUMN_HEADER_MODE_EXPLICIT);
++ LinkedHashMap<String, ColumnHeaderMode> options = new LinkedHashMap<String, ColumnHeaderMode>();
++ options.put("Explicit", ColumnHeaderMode.EXPLICIT);
+ options.put("Explicit defaults id",
- Table.COLUMN_HEADER_MODE_EXPLICIT_DEFAULTS_ID);
- options.put("Id", Table.COLUMN_HEADER_MODE_ID);
- options.put("Hidden", Table.COLUMN_HEADER_MODE_HIDDEN);
++ ColumnHeaderMode.EXPLICIT_DEFAULTS_ID);
++ options.put("Id", ColumnHeaderMode.ID);
++ options.put("Hidden", ColumnHeaderMode.HIDDEN);
+
+ createSelectAction("Header mode", category, options,
- "Explicit defaults id", new Command<T, Integer>() {
++ "Explicit defaults id", new Command<T, ColumnHeaderMode>() {
+
- public void execute(T c, Integer value, Object data) {
++ public void execute(T c, ColumnHeaderMode value, Object data) {
+ c.setColumnHeaderMode(value);
+
+ }
+ });
+ }
+
+ protected void createPageLengthSelect(String category) {
+ LinkedHashMap<String, Integer> options = new LinkedHashMap<String, Integer>();
+ options.put("0", 0);
+ options.put("5", 5);
+ options.put("10", 10);
+ options.put("20", 20);
+ options.put("50", 50);
+
+ createSelectAction("PageLength", category, options, "10",
+ new Command<T, Integer>() {
+
+ public void execute(Table t, Integer value, Object data) {
+ t.setPageLength(value);
+ }
+ });
+ }
+
+ private enum SelectMode {
+ NONE, SINGLE, MULTI_SIMPLE, MULTI;
+ }
+
+ protected void createSelectionModeSelect(String category) {
+ LinkedHashMap<String, SelectMode> options = new LinkedHashMap<String, SelectMode>();
+ options.put("None", SelectMode.NONE);
+ options.put("Single", SelectMode.SINGLE);
+ options.put("Multi - simple", SelectMode.MULTI_SIMPLE);
+ options.put("Multi - ctrl/shift", SelectMode.MULTI);
+
+ createSelectAction("Selection Mode", category, options,
+ "Multi - ctrl/shift", new Command<T, SelectMode>() {
+
+ public void execute(Table t, SelectMode value, Object data) {
+ switch (value) {
+ case NONE:
+ t.setSelectable(false);
+ break;
+ case SINGLE:
+ t.setMultiSelect(false);
+ t.setSelectable(true);
+ break;
+ case MULTI_SIMPLE:
+ t.setSelectable(true);
+ t.setMultiSelect(true);
+ t.setMultiSelectMode(MultiSelectMode.SIMPLE);
+ break;
+ case MULTI:
+ t.setSelectable(true);
+ t.setMultiSelect(true);
+ t.setMultiSelectMode(MultiSelectMode.DEFAULT);
+ break;
+ }
+ }
+ });
+ }
+
+ public void columnResize(ColumnResizeEvent event) {
+ log("ColumnResize on " + event.getPropertyId() + " from "
+ + event.getPreviousWidth() + " to " + event.getCurrentWidth());
+ }
+
+ public void footerClick(FooterClickEvent event) {
+ log("FooterClick on " + event.getPropertyId() + " using "
+ + event.getButtonName());
+ }
+
+ public void headerClick(HeaderClickEvent event) {
+ log("HeaderClick on " + event.getPropertyId() + " using "
+ + event.getButtonName());
+ }
+
+ @Override
+ protected void updateContainer() {
+ super.updateContainer();
+
+ // Recreate for the new properties
+ createColumnOptions(false);
+
+ }
+
+ }
- package com.vaadin.tests.components.table;\r
- \r
- import com.vaadin.Application;\r
- import com.vaadin.data.Container;\r
- import com.vaadin.data.Item;\r
- import com.vaadin.data.util.IndexedContainer;\r
- import com.vaadin.ui.Button;\r
- import com.vaadin.ui.Button.ClickEvent;\r
- import com.vaadin.ui.Button.ClickListener;\r
- import com.vaadin.ui.Root.LegacyWindow;\r
- import com.vaadin.ui.Table;\r
- import com.vaadin.ui.VerticalLayout;\r
- \r
- public class TestCurrentPageFirstItem extends Application.LegacyApplication\r
- implements ClickListener {\r
- \r
- private Button buttonIndex;\r
- private Button buttonItem;\r
- private Table table;\r
- private int counter = 0;\r
- IndexedContainer container = new IndexedContainer();\r
- \r
- @Override\r
- public void init() {\r
- try {\r
- LegacyWindow main = new LegacyWindow("Table header Test");\r
- setMainWindow(main);\r
- main.setSizeFull();\r
- // setTheme("testtheme");\r
- VerticalLayout baseLayout = new VerticalLayout();\r
- main.setContent(baseLayout);\r
- \r
- table = new Table();\r
- container.addContainerProperty("row", String.class, "");\r
- table.setContainerDataSource(container);\r
- table.setWidth("100%");\r
- table.setPageLength(3);\r
- buttonIndex = new Button("Add row and select last index", this);\r
- buttonItem = new Button("Add row and select last item", this);\r
- \r
- baseLayout.addComponent(table);\r
- baseLayout.addComponent(buttonIndex);\r
- baseLayout.addComponent(buttonItem);\r
- } catch (Exception e) {\r
- e.printStackTrace();\r
- }\r
- }\r
- \r
- public void buttonClick(ClickEvent event) {\r
- Item item = container.addItem(++counter);\r
- item.getItemProperty("row").setValue(counter + "");\r
- table.select(counter);\r
- if (event.getButton() == buttonIndex) {\r
- table.setCurrentPageFirstItemIndex(((Container.Indexed) table\r
- .getContainerDataSource()).indexOfId(counter));\r
- } else {\r
- table.setCurrentPageFirstItemId(counter);\r
- }\r
- }\r
- }\r
+ package com.vaadin.tests.components.table;
+
+ import com.vaadin.Application;
+ import com.vaadin.data.Container;
+ import com.vaadin.data.Item;
+ import com.vaadin.data.util.IndexedContainer;
+ import com.vaadin.ui.Button;
+ import com.vaadin.ui.Button.ClickEvent;
+ import com.vaadin.ui.Button.ClickListener;
++import com.vaadin.ui.Root.LegacyWindow;
+ import com.vaadin.ui.Table;
+ import com.vaadin.ui.VerticalLayout;
-import com.vaadin.ui.Window;
+
-public class TestCurrentPageFirstItem extends Application implements
- ClickListener {
++public class TestCurrentPageFirstItem extends Application.LegacyApplication
++ implements ClickListener {
+
+ private Button buttonIndex;
+ private Button buttonItem;
+ private Table table;
+ private int counter = 0;
+ IndexedContainer container = new IndexedContainer();
+
+ @Override
+ public void init() {
+ try {
- Window main = new Window("Table header Test");
++ LegacyWindow main = new LegacyWindow("Table header Test");
+ setMainWindow(main);
+ main.setSizeFull();
+ // setTheme("testtheme");
+ VerticalLayout baseLayout = new VerticalLayout();
+ main.setContent(baseLayout);
+
+ table = new Table();
+ container.addContainerProperty("row", String.class, "");
+ table.setContainerDataSource(container);
+ table.setWidth("100%");
+ table.setPageLength(3);
+ buttonIndex = new Button("Add row and select last index", this);
+ buttonItem = new Button("Add row and select last item", this);
+
+ baseLayout.addComponent(table);
+ baseLayout.addComponent(buttonIndex);
+ baseLayout.addComponent(buttonItem);
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ }
+
+ public void buttonClick(ClickEvent event) {
+ Item item = container.addItem(++counter);
+ item.getItemProperty("row").setValue(counter + "");
+ table.select(counter);
+ if (event.getButton() == buttonIndex) {
+ table.setCurrentPageFirstItemIndex(((Container.Indexed) table
+ .getContainerDataSource()).indexOfId(counter));
+ } else {
+ table.setCurrentPageFirstItemId(counter);
+ }
+ }
+ }
- package com.vaadin.tests.components.tabsheet;\r
- \r
- import java.util.LinkedHashMap;\r
- \r
- import com.vaadin.terminal.Resource;\r
- import com.vaadin.tests.components.AbstractComponentContainerTest;\r
- import com.vaadin.ui.Component;\r
- import com.vaadin.ui.TabSheet;\r
- import com.vaadin.ui.TabSheet.CloseHandler;\r
- import com.vaadin.ui.TabSheet.SelectedTabChangeEvent;\r
- import com.vaadin.ui.TabSheet.SelectedTabChangeListener;\r
- import com.vaadin.ui.TabSheet.Tab;\r
- \r
- public class TabSheetTest<T extends TabSheet> extends\r
- AbstractComponentContainerTest<T> implements SelectedTabChangeListener {\r
- \r
- private Command<T, Integer> setTabCaption = new Command<T, Integer>() {\r
- \r
- public void execute(T c, Integer value, Object data) {\r
- c.getTab(value).setCaption((String) data);\r
- \r
- }\r
- };\r
- private Command<T, Integer> setTabIcon = new Command<T, Integer>() {\r
- \r
- public void execute(T c, Integer value, Object data) {\r
- c.getTab(value).setIcon((Resource) data);\r
- \r
- }\r
- };\r
- private Command<T, Integer> setTabClosable = new Command<T, Integer>() {\r
- \r
- public void execute(T c, Integer value, Object data) {\r
- c.getTab(value).setClosable((Boolean) data);\r
- }\r
- };\r
- private Command<T, Boolean> setCloseHandlerListener = new Command<T, Boolean>() {\r
- \r
- public void execute(T c, Boolean value, Object data) {\r
- if (value) {\r
- c.setCloseHandler(new CloseHandler() {\r
- public void onTabClose(TabSheet tabsheet, Component c) {\r
- tabClosed(tabsheet, tabsheet.getTab(c));\r
- tabsheet.removeComponent(c);\r
- }\r
- \r
- });\r
- } else {\r
- c.setCloseHandler(new CloseHandler() {\r
- public void onTabClose(TabSheet tabsheet, Component c) {\r
- tabsheet.removeComponent(c);\r
- }\r
- });\r
- }\r
- \r
- }\r
- };\r
- private Command<T, Boolean> setSelectedTabListener = new Command<T, Boolean>() {\r
- \r
- public void execute(T c, Boolean value, Object data) {\r
- if (value) {\r
- c.addListener((SelectedTabChangeListener) TabSheetTest.this);\r
- } else {\r
- c.removeListener((SelectedTabChangeListener) TabSheetTest.this);\r
- }\r
- \r
- }\r
- };\r
- \r
- private Command<T, Integer> selectTab = new Command<T, Integer>() {\r
- public void execute(T c, Integer index, Object data) {\r
- c.setSelectedTab(c.getTab(index).getComponent());\r
- }\r
- };\r
- private Command<T, Boolean> hideTabs = new Command<T, Boolean>() {\r
- \r
- public void execute(T c, Boolean value, Object data) {\r
- c.hideTabs(value);\r
- \r
- }\r
- };\r
- \r
- @SuppressWarnings("unchecked")\r
- @Override\r
- protected Class<T> getTestClass() {\r
- return (Class<T>) TabSheet.class;\r
- }\r
- \r
- @Override\r
- protected void createActions() {\r
- super.createActions();\r
- createSetTabCaptionIcon(CATEGORY_FEATURES);\r
- createSelectTab(CATEGORY_FEATURES);\r
- createClosableToggle(CATEGORY_FEATURES);\r
- createCloseHandlerToggle(CATEGORY_LISTENERS);\r
- createSelectListenerToggle(CATEGORY_LISTENERS);\r
- createHideTabsToggle(CATEGORY_FEATURES);\r
- \r
- // TODO\r
- // Insert tab at x\r
- \r
- }\r
- \r
- private void createHideTabsToggle(String category) {\r
- createBooleanAction("Hide tabs", category, false, hideTabs);\r
- \r
- }\r
- \r
- private void createSelectListenerToggle(String category) {\r
- createBooleanAction("Selected tab listener", category, false,\r
- setSelectedTabListener);\r
- \r
- }\r
- \r
- private void createCloseHandlerToggle(String category) {\r
- createBooleanAction("Close event listener (handler)", category, false,\r
- setCloseHandlerListener);\r
- \r
- }\r
- \r
- private void createClosableToggle(String category) {\r
- String closableCategory = "Set tab closable";\r
- createCategory(closableCategory, category);\r
- for (int i = 0; i < 20; i++) {\r
- String tabClosableCategory = "Tab " + i + " closable";\r
- \r
- createCategory(tabClosableCategory, closableCategory);\r
- createClickAction("true", tabClosableCategory, setTabClosable, i,\r
- true);\r
- createClickAction("false", tabClosableCategory, setTabClosable, i,\r
- false);\r
- \r
- }\r
- }\r
- \r
- private void createSelectTab(String category) {\r
- String selectTabCategory = "Select tab";\r
- createCategory(selectTabCategory, category);\r
- for (int i = 0; i < 20; i++) {\r
- createClickAction("Select tab " + i, selectTabCategory, selectTab,\r
- i);\r
- \r
- }\r
- }\r
- \r
- private void createSetTabCaptionIcon(String category) {\r
- String captionCategory = "Set tab caption";\r
- String iconCategory = "Set tab icon";\r
- createCategory(captionCategory, category);\r
- createCategory(iconCategory, category);\r
- \r
- String captionOptions[] = new String[] { "", "{id}", "Tab {id}",\r
- "A long caption for tab {id}" };\r
- LinkedHashMap<String, Resource> iconOptions = new LinkedHashMap<String, Resource>();\r
- iconOptions.put("-", null);\r
- iconOptions.put("16x16 (cachable)", ICON_16_USER_PNG_CACHEABLE);\r
- iconOptions.put("16x16 (uncachable)", ICON_16_USER_PNG_UNCACHEABLE);\r
- iconOptions.put("32x32 (cachable)", ICON_32_ATTENTION_PNG_CACHEABLE);\r
- iconOptions\r
- .put("32x32 (uncachable)", ICON_32_ATTENTION_PNG_UNCACHEABLE);\r
- iconOptions.put("64x64 (cachable)", ICON_64_EMAIL_REPLY_PNG_CACHEABLE);\r
- iconOptions.put("64x64 (uncachable)",\r
- ICON_64_EMAIL_REPLY_PNG_UNCACHEABLE);\r
- \r
- for (int i = 0; i < 20; i++) {\r
- String tabCaptionCategory = "Tab " + i + " caption";\r
- String tabIconCategory = "Tab " + i + " icon";\r
- \r
- createCategory(tabCaptionCategory, captionCategory);\r
- createCategory(tabIconCategory, iconCategory);\r
- \r
- createClickAction("(null)", tabCaptionCategory, setTabCaption,\r
- Integer.valueOf(i), null);\r
- createClickAction("(null)", tabIconCategory, setTabIcon,\r
- Integer.valueOf(i), null);\r
- \r
- for (String option : captionOptions) {\r
- option = option.replace("{id}", String.valueOf(i));\r
- createClickAction(option, tabCaptionCategory, setTabCaption,\r
- Integer.valueOf(i), option);\r
- }\r
- \r
- for (String option : iconOptions.keySet()) {\r
- Resource icon = iconOptions.get(option);\r
- createClickAction(option, tabIconCategory, setTabIcon,\r
- Integer.valueOf(i), icon);\r
- }\r
- \r
- }\r
- \r
- }\r
- \r
- private void tabClosed(TabSheet tabSheet, Tab tab) {\r
- log("Tab " + tabSheet.getTabPosition(tab) + " closed");\r
- }\r
- \r
- public void selectedTabChange(SelectedTabChangeEvent event) {\r
- TabSheet ts = event.getTabSheet();\r
- log("Tab " + ts.getTabPosition(ts.getTab(ts.getSelectedTab()))\r
- + " selected");\r
- \r
- }\r
- }\r
+ package com.vaadin.tests.components.tabsheet;
+
+ import java.util.LinkedHashMap;
+
+ import com.vaadin.terminal.Resource;
+ import com.vaadin.tests.components.AbstractComponentContainerTest;
+ import com.vaadin.ui.Component;
+ import com.vaadin.ui.TabSheet;
+ import com.vaadin.ui.TabSheet.CloseHandler;
+ import com.vaadin.ui.TabSheet.SelectedTabChangeEvent;
+ import com.vaadin.ui.TabSheet.SelectedTabChangeListener;
+ import com.vaadin.ui.TabSheet.Tab;
+
+ public class TabSheetTest<T extends TabSheet> extends
+ AbstractComponentContainerTest<T> implements SelectedTabChangeListener {
+
+ private Command<T, Integer> setTabCaption = new Command<T, Integer>() {
+
+ public void execute(T c, Integer value, Object data) {
+ c.getTab(value).setCaption((String) data);
+
+ }
+ };
+ private Command<T, Integer> setTabIcon = new Command<T, Integer>() {
+
+ public void execute(T c, Integer value, Object data) {
+ c.getTab(value).setIcon((Resource) data);
+
+ }
+ };
+ private Command<T, Integer> setTabClosable = new Command<T, Integer>() {
+
+ public void execute(T c, Integer value, Object data) {
+ c.getTab(value).setClosable((Boolean) data);
+ }
+ };
+ private Command<T, Boolean> setCloseHandlerListener = new Command<T, Boolean>() {
+
+ public void execute(T c, Boolean value, Object data) {
+ if (value) {
+ c.setCloseHandler(new CloseHandler() {
+ public void onTabClose(TabSheet tabsheet, Component c) {
+ tabClosed(tabsheet, tabsheet.getTab(c));
+ tabsheet.removeComponent(c);
+ }
+
+ });
+ } else {
+ c.setCloseHandler(new CloseHandler() {
+ public void onTabClose(TabSheet tabsheet, Component c) {
+ tabsheet.removeComponent(c);
+ }
+ });
+ }
+
+ }
+ };
+ private Command<T, Boolean> setSelectedTabListener = new Command<T, Boolean>() {
+
+ public void execute(T c, Boolean value, Object data) {
+ if (value) {
+ c.addListener((SelectedTabChangeListener) TabSheetTest.this);
+ } else {
+ c.removeListener((SelectedTabChangeListener) TabSheetTest.this);
+ }
+
+ }
+ };
+
+ private Command<T, Integer> selectTab = new Command<T, Integer>() {
+ public void execute(T c, Integer index, Object data) {
+ c.setSelectedTab(c.getTab(index).getComponent());
+ }
+ };
+ private Command<T, Boolean> hideTabs = new Command<T, Boolean>() {
+
+ public void execute(T c, Boolean value, Object data) {
+ c.hideTabs(value);
+
+ }
+ };
+
++ @SuppressWarnings("unchecked")
+ @Override
+ protected Class<T> getTestClass() {
+ return (Class<T>) TabSheet.class;
+ }
+
+ @Override
+ protected void createActions() {
+ super.createActions();
+ createSetTabCaptionIcon(CATEGORY_FEATURES);
+ createSelectTab(CATEGORY_FEATURES);
+ createClosableToggle(CATEGORY_FEATURES);
+ createCloseHandlerToggle(CATEGORY_LISTENERS);
+ createSelectListenerToggle(CATEGORY_LISTENERS);
+ createHideTabsToggle(CATEGORY_FEATURES);
+
+ // TODO
+ // Insert tab at x
+
+ }
+
+ private void createHideTabsToggle(String category) {
+ createBooleanAction("Hide tabs", category, false, hideTabs);
+
+ }
+
+ private void createSelectListenerToggle(String category) {
+ createBooleanAction("Selected tab listener", category, false,
+ setSelectedTabListener);
+
+ }
+
+ private void createCloseHandlerToggle(String category) {
+ createBooleanAction("Close event listener (handler)", category, false,
+ setCloseHandlerListener);
+
+ }
+
+ private void createClosableToggle(String category) {
+ String closableCategory = "Set tab closable";
+ createCategory(closableCategory, category);
+ for (int i = 0; i < 20; i++) {
+ String tabClosableCategory = "Tab " + i + " closable";
+
+ createCategory(tabClosableCategory, closableCategory);
+ createClickAction("true", tabClosableCategory, setTabClosable, i,
+ true);
+ createClickAction("false", tabClosableCategory, setTabClosable, i,
+ false);
+
+ }
+ }
+
+ private void createSelectTab(String category) {
+ String selectTabCategory = "Select tab";
+ createCategory(selectTabCategory, category);
+ for (int i = 0; i < 20; i++) {
+ createClickAction("Select tab " + i, selectTabCategory, selectTab,
+ i);
+
+ }
+ }
+
+ private void createSetTabCaptionIcon(String category) {
+ String captionCategory = "Set tab caption";
+ String iconCategory = "Set tab icon";
+ createCategory(captionCategory, category);
+ createCategory(iconCategory, category);
+
+ String captionOptions[] = new String[] { "", "{id}", "Tab {id}",
+ "A long caption for tab {id}" };
+ LinkedHashMap<String, Resource> iconOptions = new LinkedHashMap<String, Resource>();
+ iconOptions.put("-", null);
+ iconOptions.put("16x16 (cachable)", ICON_16_USER_PNG_CACHEABLE);
+ iconOptions.put("16x16 (uncachable)", ICON_16_USER_PNG_UNCACHEABLE);
+ iconOptions.put("32x32 (cachable)", ICON_32_ATTENTION_PNG_CACHEABLE);
+ iconOptions
+ .put("32x32 (uncachable)", ICON_32_ATTENTION_PNG_UNCACHEABLE);
+ iconOptions.put("64x64 (cachable)", ICON_64_EMAIL_REPLY_PNG_CACHEABLE);
+ iconOptions.put("64x64 (uncachable)",
+ ICON_64_EMAIL_REPLY_PNG_UNCACHEABLE);
+
+ for (int i = 0; i < 20; i++) {
+ String tabCaptionCategory = "Tab " + i + " caption";
+ String tabIconCategory = "Tab " + i + " icon";
+
+ createCategory(tabCaptionCategory, captionCategory);
+ createCategory(tabIconCategory, iconCategory);
+
+ createClickAction("(null)", tabCaptionCategory, setTabCaption,
+ Integer.valueOf(i), null);
+ createClickAction("(null)", tabIconCategory, setTabIcon,
+ Integer.valueOf(i), null);
+
+ for (String option : captionOptions) {
+ option = option.replace("{id}", String.valueOf(i));
+ createClickAction(option, tabCaptionCategory, setTabCaption,
+ Integer.valueOf(i), option);
+ }
+
+ for (String option : iconOptions.keySet()) {
+ Resource icon = iconOptions.get(option);
+ createClickAction(option, tabIconCategory, setTabIcon,
+ Integer.valueOf(i), icon);
+ }
+
+ }
+
+ }
+
+ private void tabClosed(TabSheet tabSheet, Tab tab) {
+ log("Tab " + tabSheet.getTabPosition(tab) + " closed");
+ }
+
+ public void selectedTabChange(SelectedTabChangeEvent event) {
+ TabSheet ts = event.getTabSheet();
+ log("Tab " + ts.getTabPosition(ts.getTab(ts.getSelectedTab()))
+ + " selected");
+
+ }
+ }
- package com.vaadin.tests.components.tabsheet;\r
- \r
- import com.vaadin.tests.components.AbstractTestCase;\r
- import com.vaadin.ui.Button;\r
- import com.vaadin.ui.Button.ClickEvent;\r
- import com.vaadin.ui.Button.ClickListener;\r
- import com.vaadin.ui.Label;\r
- import com.vaadin.ui.Root.LegacyWindow;\r
- import com.vaadin.ui.TabSheet;\r
- import com.vaadin.ui.TabSheet.Tab;\r
- import com.vaadin.ui.VerticalLayout;\r
- \r
- public class TabsheetNPE extends AbstractTestCase implements ClickListener {\r
- \r
- @Override\r
- protected String getDescription() {\r
- return "Enable and activate tab should enable and activate the first tab.";\r
- }\r
- \r
- @Override\r
- protected Integer getTicketNumber() {\r
- return 3292;\r
- }\r
- \r
- private static final int TABS_COUNT = 3;\r
- private TabSheet tabSheet;\r
- private Label[] label = new Label[TABS_COUNT];\r
- private Tab[] tab = new Tab[TABS_COUNT];\r
- \r
- @Override\r
- public void init() {\r
- setMainWindow(new LegacyWindow("TabSheet Demo", createMainLayout()));\r
- }\r
- \r
- private VerticalLayout createMainLayout() {\r
- VerticalLayout layout = new VerticalLayout();\r
- \r
- tabSheet = new TabSheet();\r
- for (int i = 1; i <= TABS_COUNT; i++) {\r
- label[i - 1] = new Label("Tab " + i);\r
- tab[i - 1] = tabSheet.addTab(label[i - 1], "Tab " + i, null);\r
- tab[i - 1].setEnabled(false);\r
- }\r
- \r
- layout.addComponent(tabSheet);\r
- Button btn = new Button("Enable and activate tab");\r
- btn.addListener(this);\r
- layout.addComponent(btn);\r
- return layout;\r
- }\r
- \r
- public void buttonClick(ClickEvent event) {\r
- for (int i = 0; i < TABS_COUNT; i++) {\r
- tab[i].setEnabled(true);\r
- }\r
- tabSheet.setSelectedTab(label[0]);\r
- }\r
- \r
- }\r
+ package com.vaadin.tests.components.tabsheet;
+
+ import com.vaadin.tests.components.AbstractTestCase;
+ import com.vaadin.ui.Button;
+ import com.vaadin.ui.Button.ClickEvent;
+ import com.vaadin.ui.Button.ClickListener;
+ import com.vaadin.ui.Label;
++import com.vaadin.ui.Root.LegacyWindow;
+ import com.vaadin.ui.TabSheet;
+ import com.vaadin.ui.TabSheet.Tab;
+ import com.vaadin.ui.VerticalLayout;
-import com.vaadin.ui.Window;
+
+ public class TabsheetNPE extends AbstractTestCase implements ClickListener {
+
+ @Override
+ protected String getDescription() {
+ return "Enable and activate tab should enable and activate the first tab.";
+ }
+
+ @Override
+ protected Integer getTicketNumber() {
+ return 3292;
+ }
+
+ private static final int TABS_COUNT = 3;
+ private TabSheet tabSheet;
+ private Label[] label = new Label[TABS_COUNT];
+ private Tab[] tab = new Tab[TABS_COUNT];
+
+ @Override
+ public void init() {
- setMainWindow(new Window("TabSheet Demo", createMainLayout()));
++ setMainWindow(new LegacyWindow("TabSheet Demo", createMainLayout()));
+ }
+
+ private VerticalLayout createMainLayout() {
+ VerticalLayout layout = new VerticalLayout();
+
+ tabSheet = new TabSheet();
+ for (int i = 1; i <= TABS_COUNT; i++) {
+ label[i - 1] = new Label("Tab " + i);
+ tab[i - 1] = tabSheet.addTab(label[i - 1], "Tab " + i, null);
+ tab[i - 1].setEnabled(false);
+ }
+
+ layout.addComponent(tabSheet);
+ Button btn = new Button("Enable and activate tab");
+ btn.addListener(this);
+ layout.addComponent(btn);
+ return layout;
+ }
+
+ public void buttonClick(ClickEvent event) {
+ for (int i = 0; i < TABS_COUNT; i++) {
+ tab[i].setEnabled(true);
+ }
+ tabSheet.setSelectedTab(label[0]);
+ }
+
+ }
- package com.vaadin.tests.components.tabsheet;\r
- \r
- import com.vaadin.tests.components.TestBase;\r
- import com.vaadin.ui.TabSheet;\r
- import com.vaadin.ui.TextArea;\r
- \r
- public class VerticalScrollbarPosition extends TestBase {\r
- \r
- @Override\r
- protected String getDescription() {\r
- return "A vertical scrollbar in a TabSheet should always be placed at the right edge";\r
- }\r
- \r
- @Override\r
- protected Integer getTicketNumber() {\r
- return 2473;\r
- }\r
- \r
- @Override\r
- protected void setup() {\r
- TabSheet tabsheet = new TabSheet();\r
- tabsheet.setWidth(null);\r
- tabsheet.setHeight("200px");\r
- TextArea tf = new TextArea();\r
- tf.setRows(2);\r
- tf.setHeight("300px");\r
- tf.setWidth("200px");\r
- tabsheet.addTab(\r
- tf,\r
- "A text area that is 200px wide, the tab bar for the tabsheet is wider",\r
- null);\r
- TextArea tf2 = new TextArea("Another tab", "b");\r
- tf2.setWidth("1000px");\r
- tf2.setHeight("50px");\r
- tabsheet.addTab(tf2);\r
- addComponent(tabsheet);\r
- }\r
- \r
- }\r
+ package com.vaadin.tests.components.tabsheet;
+
+ import com.vaadin.tests.components.TestBase;
+ import com.vaadin.ui.TabSheet;
+ import com.vaadin.ui.TextArea;
-import com.vaadin.ui.TextField;
+
+ public class VerticalScrollbarPosition extends TestBase {
+
+ @Override
+ protected String getDescription() {
+ return "A vertical scrollbar in a TabSheet should always be placed at the right edge";
+ }
+
+ @Override
+ protected Integer getTicketNumber() {
+ return 2473;
+ }
+
+ @Override
+ protected void setup() {
+ TabSheet tabsheet = new TabSheet();
+ tabsheet.setWidth(null);
+ tabsheet.setHeight("200px");
+ TextArea tf = new TextArea();
+ tf.setRows(2);
+ tf.setHeight("300px");
+ tf.setWidth("200px");
+ tabsheet.addTab(
+ tf,
- "A text field that is 200px wide, the tab bar for the tabsheet is wider",
++ "A text area that is 200px wide, the tab bar for the tabsheet is wider",
+ null);
- TextField tf2 = new TextField("Another tab", "b");
++ TextArea tf2 = new TextArea("Another tab", "b");
+ tf2.setWidth("1000px");
+ tf2.setHeight("50px");
+ tabsheet.addTab(tf2);
+ addComponent(tabsheet);
+ }
+
+ }
- package com.vaadin.tests.components.textfield;\r
- \r
- import com.vaadin.Application;\r
- import com.vaadin.ui.Component;\r
- import com.vaadin.ui.Panel;\r
- import com.vaadin.ui.Root.LegacyWindow;\r
- import com.vaadin.ui.Table;\r
- import com.vaadin.ui.TextField;\r
- import com.vaadin.ui.VerticalLayout;\r
- \r
- public class TextFieldInLayoutInTable extends Application.LegacyApplication {\r
- \r
- @Override\r
- public void init() {\r
- \r
- final LegacyWindow mainWindow = new LegacyWindow(this.getClass()\r
- .getName());\r
- setMainWindow(mainWindow);\r
- \r
- final Table table = new Table();\r
- table.addContainerProperty("column1", Component.class, null);\r
- final Panel panel = new Panel("Panel");\r
- ((VerticalLayout) panel.getContent()).setMargin(false);\r
- VerticalLayout vl = new VerticalLayout();\r
- final TextField textField = new TextField();\r
- vl.addComponent(textField);\r
- \r
- table.addItem(new Object[] { vl }, 1);\r
- \r
- table.setSizeFull();\r
- mainWindow.addComponent(table);\r
- }\r
- \r
- }\r
+ package com.vaadin.tests.components.textfield;
+
+ import com.vaadin.Application;
+ import com.vaadin.ui.Component;
+ import com.vaadin.ui.Panel;
++import com.vaadin.ui.Root.LegacyWindow;
+ import com.vaadin.ui.Table;
+ import com.vaadin.ui.TextField;
+ import com.vaadin.ui.VerticalLayout;
-import com.vaadin.ui.Window;
+
-@SuppressWarnings("serial")
-public class TextFieldInLayoutInTable extends Application {
++public class TextFieldInLayoutInTable extends Application.LegacyApplication {
+
+ @Override
+ public void init() {
+
- final Window mainWindow = new Window(this.getClass().getName());
++ final LegacyWindow mainWindow = new LegacyWindow(this.getClass()
++ .getName());
+ setMainWindow(mainWindow);
+
+ final Table table = new Table();
+ table.addContainerProperty("column1", Component.class, null);
+ final Panel panel = new Panel("Panel");
+ ((VerticalLayout) panel.getContent()).setMargin(false);
+ VerticalLayout vl = new VerticalLayout();
+ final TextField textField = new TextField();
+ vl.addComponent(textField);
+
+ table.addItem(new Object[] { vl }, 1);
+
+ table.setSizeFull();
+ mainWindow.addComponent(table);
+ }
+
+ }
- package com.vaadin.tests.components.textfield;\r
- \r
- import com.vaadin.event.FieldEvents.TextChangeListener;\r
- import com.vaadin.tests.components.abstractfield.AbstractTextFieldTest;\r
- import com.vaadin.ui.TextField;\r
- \r
- public class TextFieldTest extends AbstractTextFieldTest<TextField> implements\r
- TextChangeListener {\r
- \r
- @Override\r
- protected Class<TextField> getTestClass() {\r
- return TextField.class;\r
- }\r
- \r
- @Override\r
- protected void createActions() {\r
- super.createActions();\r
- }\r
- \r
- }\r
+ package com.vaadin.tests.components.textfield;
+
-import java.util.LinkedHashMap;
-
+ import com.vaadin.event.FieldEvents.TextChangeListener;
+ import com.vaadin.tests.components.abstractfield.AbstractTextFieldTest;
+ import com.vaadin.ui.TextField;
+
+ public class TextFieldTest extends AbstractTextFieldTest<TextField> implements
+ TextChangeListener {
+
- private Command<TextField, Boolean> secretCommand = new Command<TextField, Boolean>() {
- @SuppressWarnings("deprecation")
- public void execute(TextField c, Boolean value, Object data) {
- c.setSecret(value);
- }
- };
-
- private Command<TextField, Boolean> wordwrapCommand = new Command<TextField, Boolean>() {
- @SuppressWarnings("deprecation")
- public void execute(TextField c, Boolean value, Object data) {
- c.setWordwrap(value);
- }
- };
-
- private Command<TextField, Integer> rowsCommand = new Command<TextField, Integer>() {
- @SuppressWarnings("deprecation")
- public void execute(TextField c, Integer value, Object data) {
- c.setRows(value);
- }
- };
-
+ @Override
+ protected Class<TextField> getTestClass() {
+ return TextField.class;
+ }
+
+ @Override
+ protected void createActions() {
+ super.createActions();
- createSecretAction(CATEGORY_FEATURES);
- createWordwrapAction(CATEGORY_FEATURES);
- createRowsAction(CATEGORY_FEATURES);
- }
-
- private void createRowsAction(String category) {
- LinkedHashMap<String, Integer> options = createIntegerOptions(20);
- createSelectAction("Rows", category, options, "0", rowsCommand);
- }
-
- private void createSecretAction(String category) {
- createBooleanAction("Secret", category, false, secretCommand);
- }
-
- private void createWordwrapAction(String category) {
- createBooleanAction("Wordwrap", category, false, wordwrapCommand);
+ }
+
+ }
- package com.vaadin.tests.components.tree;\r
- \r
- import com.vaadin.data.Item;\r
- import com.vaadin.data.Property.ValueChangeEvent;\r
- import com.vaadin.data.Property.ValueChangeListener;\r
- import com.vaadin.data.util.HierarchicalContainer;\r
- import com.vaadin.tests.components.TestBase;\r
- import com.vaadin.ui.Button;\r
- import com.vaadin.ui.Button.ClickEvent;\r
- import com.vaadin.ui.Button.ClickListener;\r
- import com.vaadin.ui.CheckBox;\r
- import com.vaadin.ui.Tree;\r
- \r
- public class TreeFiltering extends TestBase {\r
- \r
- @Override\r
- public void setup() {\r
- \r
- final Tree ccTree = new Tree();\r
- addComponent(ccTree);\r
- final HierarchicalContainer cont = new HierarchicalContainer();\r
- cont.addContainerProperty("caption", String.class, "");\r
- \r
- Item item;\r
- for (int i = 0; i < 5; i++) {\r
- item = cont.addItem(i);\r
- item.getItemProperty("caption").setValue("Number " + i);\r
- cont.setParent(i, i - 1);\r
- }\r
- \r
- for (int i = 0; i < 5; i++) {\r
- Object id = cont.addItem();\r
- item = cont.getItem(id);\r
- item.getItemProperty("caption").setValue("0-" + i);\r
- cont.setParent(id, 0);\r
- }\r
- \r
- ccTree.setContainerDataSource(cont);\r
- ccTree.setItemCaptionPropertyId("caption");\r
- \r
- for (final Object o : ccTree.getItemIds()) {\r
- ccTree.expandItem(o);\r
- }\r
- \r
- final CheckBox filterType = new CheckBox(\r
- "Include parent when filtering", true);\r
- filterType.setImmediate(true);\r
- filterType.addListener(new ValueChangeListener() {\r
- \r
- public void valueChange(ValueChangeEvent event) {\r
- cont.setIncludeParentsWhenFiltering((Boolean) ((CheckBox) event\r
- .getProperty()).getValue());\r
- ccTree.requestRepaint();\r
- }\r
- });\r
- addComponent(filterType);\r
- \r
- final Button b = new Button("Add filter 'foo'", new ClickListener() {\r
- public void buttonClick(final ClickEvent event) {\r
- cont.addContainerFilter("caption", "foo", true, false);\r
- \r
- }\r
- });\r
- addComponent(b);\r
- final Button b2 = new Button("Add filter 'Num'", new ClickListener() {\r
- public void buttonClick(final ClickEvent event) {\r
- cont.addContainerFilter("caption", "Num", true, false);\r
- \r
- }\r
- });\r
- \r
- addComponent(b2);\r
- final Button num = new Button("Add filter '0'", new ClickListener() {\r
- public void buttonClick(final ClickEvent event) {\r
- cont.addContainerFilter("caption", "0", true, false);\r
- \r
- }\r
- });\r
- \r
- addComponent(num);\r
- final Button num2 = new Button("Add filter '0-'", new ClickListener() {\r
- public void buttonClick(final ClickEvent event) {\r
- cont.addContainerFilter("caption", "0-", true, false);\r
- \r
- }\r
- });\r
- \r
- addComponent(num2);\r
- final Button num3 = new Button("Add filter 'Number 4'",\r
- new ClickListener() {\r
- public void buttonClick(final ClickEvent event) {\r
- cont.addContainerFilter("caption", "Number 4", true,\r
- false);\r
- \r
- }\r
- });\r
- \r
- addComponent(num3);\r
- final Button p1 = new Button("Set Number 3 parent to Number 0",\r
- new ClickListener() {\r
- public void buttonClick(final ClickEvent event) {\r
- cont.setParent(3, 0);\r
- \r
- }\r
- });\r
- addComponent(p1);\r
- final Button r = new Button("Remove filters", new ClickListener() {\r
- public void buttonClick(final ClickEvent event) {\r
- cont.removeAllContainerFilters();\r
- \r
- }\r
- });\r
- addComponent(r);\r
- }\r
- \r
- @Override\r
- protected String getDescription() {\r
- return "Filtering in a tree should work as expected. Roots and their children which match the filter should be shown. Other nodes should be hidden";\r
- }\r
- \r
- @Override\r
- protected Integer getTicketNumber() {\r
- return 4192;\r
- }\r
- \r
+ package com.vaadin.tests.components.tree;
+
+ import com.vaadin.data.Item;
+ import com.vaadin.data.Property.ValueChangeEvent;
+ import com.vaadin.data.Property.ValueChangeListener;
+ import com.vaadin.data.util.HierarchicalContainer;
+ import com.vaadin.tests.components.TestBase;
+ import com.vaadin.ui.Button;
+ import com.vaadin.ui.Button.ClickEvent;
+ import com.vaadin.ui.Button.ClickListener;
+ import com.vaadin.ui.CheckBox;
+ import com.vaadin.ui.Tree;
+
+ public class TreeFiltering extends TestBase {
+
+ @Override
+ public void setup() {
+
+ final Tree ccTree = new Tree();
+ addComponent(ccTree);
+ final HierarchicalContainer cont = new HierarchicalContainer();
+ cont.addContainerProperty("caption", String.class, "");
+
+ Item item;
+ for (int i = 0; i < 5; i++) {
+ item = cont.addItem(i);
+ item.getItemProperty("caption").setValue("Number " + i);
+ cont.setParent(i, i - 1);
+ }
+
+ for (int i = 0; i < 5; i++) {
+ Object id = cont.addItem();
+ item = cont.getItem(id);
+ item.getItemProperty("caption").setValue("0-" + i);
+ cont.setParent(id, 0);
+ }
+
+ ccTree.setContainerDataSource(cont);
+ ccTree.setItemCaptionPropertyId("caption");
+
+ for (final Object o : ccTree.getItemIds()) {
+ ccTree.expandItem(o);
+ }
+
+ final CheckBox filterType = new CheckBox(
+ "Include parent when filtering", true);
+ filterType.setImmediate(true);
+ filterType.addListener(new ValueChangeListener() {
+
+ public void valueChange(ValueChangeEvent event) {
- cont.setIncludeParentsWhenFiltering(((CheckBox) event
- .getProperty()).booleanValue());
++ cont.setIncludeParentsWhenFiltering((Boolean) ((CheckBox) event
++ .getProperty()).getValue());
+ ccTree.requestRepaint();
+ }
+ });
+ addComponent(filterType);
+
+ final Button b = new Button("Add filter 'foo'", new ClickListener() {
+ public void buttonClick(final ClickEvent event) {
+ cont.addContainerFilter("caption", "foo", true, false);
+
+ }
+ });
+ addComponent(b);
+ final Button b2 = new Button("Add filter 'Num'", new ClickListener() {
+ public void buttonClick(final ClickEvent event) {
+ cont.addContainerFilter("caption", "Num", true, false);
+
+ }
+ });
+
+ addComponent(b2);
+ final Button num = new Button("Add filter '0'", new ClickListener() {
+ public void buttonClick(final ClickEvent event) {
+ cont.addContainerFilter("caption", "0", true, false);
+
+ }
+ });
+
+ addComponent(num);
+ final Button num2 = new Button("Add filter '0-'", new ClickListener() {
+ public void buttonClick(final ClickEvent event) {
+ cont.addContainerFilter("caption", "0-", true, false);
+
+ }
+ });
+
+ addComponent(num2);
+ final Button num3 = new Button("Add filter 'Number 4'",
+ new ClickListener() {
+ public void buttonClick(final ClickEvent event) {
+ cont.addContainerFilter("caption", "Number 4", true,
+ false);
+
+ }
+ });
+
+ addComponent(num3);
+ final Button p1 = new Button("Set Number 3 parent to Number 0",
+ new ClickListener() {
+ public void buttonClick(final ClickEvent event) {
+ cont.setParent(3, 0);
+
+ }
+ });
+ addComponent(p1);
+ final Button r = new Button("Remove filters", new ClickListener() {
+ public void buttonClick(final ClickEvent event) {
+ cont.removeAllContainerFilters();
+
+ }
+ });
+ addComponent(r);
+ }
+
+ @Override
+ protected String getDescription() {
+ return "Filtering in a tree should work as expected. Roots and their children which match the filter should be shown. Other nodes should be hidden";
+ }
+
+ @Override
+ protected Integer getTicketNumber() {
+ return 4192;
+ }
+
}
- package com.vaadin.tests.components.tree;\r
- \r
- import com.vaadin.tests.components.AbstractTestCase;\r
- import com.vaadin.ui.RichTextArea;\r
- import com.vaadin.ui.Root.LegacyWindow;\r
- import com.vaadin.ui.TextField;\r
- import com.vaadin.ui.Tree;\r
- import com.vaadin.ui.VerticalLayout;\r
- \r
- public class TreeScrolling extends AbstractTestCase {\r
- \r
- @Override\r
- public void init() {\r
- VerticalLayout layout = new VerticalLayout();\r
- layout.setSizeUndefined();\r
- LegacyWindow w = new LegacyWindow("", layout);\r
- setMainWindow(w);\r
- \r
- TextField filler1 = new TextField();\r
- RichTextArea filler2 = new RichTextArea();\r
- Tree tree = new Tree();\r
- for (int i = 0; i < 20; i++) {\r
- String parentId = "Item " + i;\r
- // Item parentItem =\r
- tree.addItem(parentId);\r
- for (int j = 0; j < 20; j++) {\r
- String subId = "Item " + i + " - " + j;\r
- // Item subItem =\r
- tree.addItem(subId);\r
- tree.setParent(subId, parentId);\r
- }\r
- \r
- }\r
- \r
- for (Object id : tree.rootItemIds()) {\r
- tree.expandItemsRecursively(id);\r
- }\r
- \r
- layout.addComponent(filler1);\r
- layout.addComponent(filler2);\r
- layout.addComponent(tree);\r
- }\r
- \r
- @Override\r
- protected String getDescription() {\r
- return "Tests what happens when a tree is partly out of view when an item is selected";\r
- }\r
- \r
- @Override\r
- protected Integer getTicketNumber() {\r
- return 5400;\r
- }\r
- \r
- }\r
+ package com.vaadin.tests.components.tree;
+
+ import com.vaadin.tests.components.AbstractTestCase;
+ import com.vaadin.ui.RichTextArea;
++import com.vaadin.ui.Root.LegacyWindow;
+ import com.vaadin.ui.TextField;
+ import com.vaadin.ui.Tree;
+ import com.vaadin.ui.VerticalLayout;
-import com.vaadin.ui.Window;
+
+ public class TreeScrolling extends AbstractTestCase {
+
+ @Override
+ public void init() {
+ VerticalLayout layout = new VerticalLayout();
+ layout.setSizeUndefined();
- Window w = new Window("", layout);
++ LegacyWindow w = new LegacyWindow("", layout);
+ setMainWindow(w);
+
+ TextField filler1 = new TextField();
+ RichTextArea filler2 = new RichTextArea();
+ Tree tree = new Tree();
+ for (int i = 0; i < 20; i++) {
+ String parentId = "Item " + i;
+ // Item parentItem =
+ tree.addItem(parentId);
+ for (int j = 0; j < 20; j++) {
+ String subId = "Item " + i + " - " + j;
+ // Item subItem =
+ tree.addItem(subId);
+ tree.setParent(subId, parentId);
+ }
+
+ }
+
+ for (Object id : tree.rootItemIds()) {
+ tree.expandItemsRecursively(id);
+ }
+
+ layout.addComponent(filler1);
+ layout.addComponent(filler2);
+ layout.addComponent(tree);
+ }
+
+ @Override
+ protected String getDescription() {
+ return "Tests what happens when a tree is partly out of view when an item is selected";
+ }
+
+ @Override
+ protected Integer getTicketNumber() {
+ return 5400;
+ }
+
+ }
- package com.vaadin.tests.components.window;\r
- \r
- import javax.servlet.http.HttpServletRequest;\r
- import javax.servlet.http.HttpServletResponse;\r
- \r
- import com.vaadin.event.ShortcutAction.KeyCode;\r
- import com.vaadin.terminal.gwt.server.HttpServletRequestListener;\r
- import com.vaadin.tests.components.AbstractTestCase;\r
- import com.vaadin.tests.util.Log;\r
- import com.vaadin.ui.Button;\r
- import com.vaadin.ui.Button.ClickEvent;\r
- import com.vaadin.ui.Button.ClickListener;\r
- import com.vaadin.ui.Component;\r
- import com.vaadin.ui.Label;\r
- import com.vaadin.ui.Root;\r
- import com.vaadin.ui.Window;\r
- \r
- public class AttachShouldBeCalledForSubWindows extends AbstractTestCase\r
- implements HttpServletRequestListener {\r
- private static final long serialVersionUID = 1L;\r
- \r
- private Log log = new Log(20);\r
- \r
- boolean addSubWindowBeforeMainWindow = true;\r
- \r
- @Override\r
- public void init() {\r
- \r
- Root.LegacyWindow mainWindow = new Root.LegacyWindow() {\r
- @Override\r
- public void attach() {\r
- log(this);\r
- super.attach();\r
- }\r
- \r
- @Override\r
- public void addWindow(Window w) {\r
- log.log("Adding sub window");\r
- super.addWindow(w);\r
- log.log("Sub window added");\r
- \r
- }\r
- };\r
- mainWindow.setCaption("Main window");\r
- mainWindow.addComponent(log);\r
- mainWindow.getContent().setSizeFull();\r
- Label label = new Label("This is the main app") {\r
- @Override\r
- public void attach() {\r
- log(this);\r
- super.attach();\r
- }\r
- };\r
- \r
- mainWindow.addComponent(label);\r
- Window loginWindow = createSubWindow();\r
- if (addSubWindowBeforeMainWindow) {\r
- mainWindow.addWindow(loginWindow);\r
- }\r
- \r
- log.log("Setting main window");\r
- setMainWindow(mainWindow); // At this point\r
- log.log("Main window set");\r
- \r
- if (!addSubWindowBeforeMainWindow) {\r
- mainWindow.addWindow(loginWindow);\r
- }\r
- }\r
- \r
- private Window createSubWindow() {\r
- Window w = new Window("Sub window") {\r
- @Override\r
- public void attach() {\r
- log(this);\r
- super.attach();\r
- }\r
- };\r
- Button okButton = new Button("OK") {\r
- @Override\r
- public void attach() {\r
- super.attach();\r
- log(this);\r
- }\r
- };\r
- okButton.addListener(new ClickListener() {\r
- \r
- public void buttonClick(ClickEvent event) {\r
- log.log("Button clicked");\r
- \r
- }\r
- });\r
- okButton.setClickShortcut(KeyCode.ENTER);\r
- w.addComponent(okButton);\r
- w.center();\r
- return w;\r
- }\r
- \r
- public void log(Component c) {\r
- Class<?> cls = c.getClass();\r
- if (cls.isAnonymousClass()) {\r
- cls = cls.getSuperclass();\r
- }\r
- log.log(cls.getName() + " '" + c.getCaption()\r
- + "' attached to application");\r
- }\r
- \r
- @Override\r
- protected String getDescription() {\r
- return "By default attaches a sub window with a button to the main window and then set the main window to the application. Use ?attachMainFirst to reverse the order. In both cases attach events should be sent for the components in the sub window";\r
- }\r
- \r
- @Override\r
- protected Integer getTicketNumber() {\r
- return 8170;\r
- }\r
- \r
- public void onRequestStart(HttpServletRequest request,\r
- HttpServletResponse response) {\r
- if (request.getParameter("attachMainFirst") != null) {\r
- addSubWindowBeforeMainWindow = false;\r
- }\r
- \r
- }\r
- \r
- public void onRequestEnd(HttpServletRequest request,\r
- HttpServletResponse response) {\r
- // TODO Auto-generated method stub\r
- \r
- }\r
- }\r
+ package com.vaadin.tests.components.window;
+
+ import javax.servlet.http.HttpServletRequest;
+ import javax.servlet.http.HttpServletResponse;
+
+ import com.vaadin.event.ShortcutAction.KeyCode;
+ import com.vaadin.terminal.gwt.server.HttpServletRequestListener;
+ import com.vaadin.tests.components.AbstractTestCase;
+ import com.vaadin.tests.util.Log;
+ import com.vaadin.ui.Button;
+ import com.vaadin.ui.Button.ClickEvent;
+ import com.vaadin.ui.Button.ClickListener;
+ import com.vaadin.ui.Component;
+ import com.vaadin.ui.Label;
++import com.vaadin.ui.Root;
+ import com.vaadin.ui.Window;
+
+ public class AttachShouldBeCalledForSubWindows extends AbstractTestCase
+ implements HttpServletRequestListener {
+ private static final long serialVersionUID = 1L;
+
+ private Log log = new Log(20);
+
+ boolean addSubWindowBeforeMainWindow = true;
+
+ @Override
+ public void init() {
+
- Window mainWindow = new Window() {
++ Root.LegacyWindow mainWindow = new Root.LegacyWindow() {
+ @Override
+ public void attach() {
+ log(this);
+ super.attach();
+ }
+
+ @Override
+ public void addWindow(Window w) {
+ log.log("Adding sub window");
+ super.addWindow(w);
+ log.log("Sub window added");
+
+ }
+ };
+ mainWindow.setCaption("Main window");
+ mainWindow.addComponent(log);
+ mainWindow.getContent().setSizeFull();
+ Label label = new Label("This is the main app") {
+ @Override
+ public void attach() {
+ log(this);
+ super.attach();
+ }
+ };
+
+ mainWindow.addComponent(label);
+ Window loginWindow = createSubWindow();
+ if (addSubWindowBeforeMainWindow) {
+ mainWindow.addWindow(loginWindow);
+ }
+
+ log.log("Setting main window");
+ setMainWindow(mainWindow); // At this point
+ log.log("Main window set");
+
+ if (!addSubWindowBeforeMainWindow) {
+ mainWindow.addWindow(loginWindow);
+ }
+ }
+
+ private Window createSubWindow() {
+ Window w = new Window("Sub window") {
+ @Override
+ public void attach() {
+ log(this);
+ super.attach();
+ }
+ };
+ Button okButton = new Button("OK") {
+ @Override
+ public void attach() {
+ super.attach();
+ log(this);
+ }
+ };
+ okButton.addListener(new ClickListener() {
+
+ public void buttonClick(ClickEvent event) {
+ log.log("Button clicked");
+
+ }
+ });
+ okButton.setClickShortcut(KeyCode.ENTER);
+ w.addComponent(okButton);
+ w.center();
+ return w;
+ }
+
+ public void log(Component c) {
+ Class<?> cls = c.getClass();
+ if (cls.isAnonymousClass()) {
+ cls = cls.getSuperclass();
+ }
+ log.log(cls.getName() + " '" + c.getCaption()
+ + "' attached to application");
+ }
+
+ @Override
+ protected String getDescription() {
+ return "By default attaches a sub window with a button to the main window and then set the main window to the application. Use ?attachMainFirst to reverse the order. In both cases attach events should be sent for the components in the sub window";
+ }
+
+ @Override
+ protected Integer getTicketNumber() {
+ return 8170;
+ }
+
+ public void onRequestStart(HttpServletRequest request,
+ HttpServletResponse response) {
+ if (request.getParameter("attachMainFirst") != null) {
+ addSubWindowBeforeMainWindow = false;
+ }
+
+ }
+
+ public void onRequestEnd(HttpServletRequest request,
+ HttpServletResponse response) {
+ // TODO Auto-generated method stub
+
+ }
+ }
- package com.vaadin.tests.components.window;\r
- \r
- import com.vaadin.tests.components.TestBase;\r
- import com.vaadin.tests.util.Log;\r
- import com.vaadin.ui.Button;\r
- import com.vaadin.ui.Button.ClickEvent;\r
- import com.vaadin.ui.Button.ClickListener;\r
- import com.vaadin.ui.Window;\r
- import com.vaadin.ui.Window.CloseEvent;\r
- import com.vaadin.ui.Window.CloseListener;\r
- \r
- public class CloseSubWindow extends TestBase {\r
- \r
- private Log log = new Log(5);\r
- \r
- @Override\r
- protected void setup() {\r
- Button openWindowButton = new Button("Open sub-window");\r
- openWindowButton.setDebugId("opensub");\r
- openWindowButton.addListener(new ClickListener() {\r
- public void buttonClick(ClickEvent event) {\r
- Window sub = createClosableSubWindow("Sub-window");\r
- getMainWindow().addWindow(sub);\r
- }\r
- });\r
- \r
- addComponent(log);\r
- addComponent(openWindowButton);\r
- }\r
- \r
- private Window createClosableSubWindow(final String title) {\r
- final Window window = new Window(title);\r
- window.setSizeUndefined();\r
- window.getContent().setSizeFull();\r
- window.setClosable(true);\r
- \r
- Button closeButton = new Button("Close");\r
- closeButton.addListener(new ClickListener() {\r
- public void buttonClick(ClickEvent event) {\r
- window.close();\r
- }\r
- });\r
- window.addComponent(closeButton);\r
- \r
- Button removeButton = new Button("Remove from parent");\r
- removeButton.addListener(new ClickListener() {\r
- public void buttonClick(ClickEvent event) {\r
- window.close();\r
- }\r
- });\r
- window.addComponent(closeButton);\r
- \r
- window.addListener(new CloseListener() {\r
- public void windowClose(CloseEvent e) {\r
- log.log("Window '" + title + "' closed");\r
- }\r
- });\r
- \r
- return window;\r
- }\r
- \r
- @Override\r
- protected String getDescription() {\r
- return "Close sub-windows both from code and with the close button in the window title bar, and check for close events. Contains an ugly workaround for the Opera bug (Opera does not send close events)";\r
- }\r
- \r
- @Override\r
- protected Integer getTicketNumber() {\r
- return 3865;\r
- }\r
- }\r
+ package com.vaadin.tests.components.window;
+
-import java.net.URL;
-
-import com.vaadin.terminal.ExternalResource;
+ import com.vaadin.tests.components.TestBase;
+ import com.vaadin.tests.util.Log;
+ import com.vaadin.ui.Button;
+ import com.vaadin.ui.Button.ClickEvent;
+ import com.vaadin.ui.Button.ClickListener;
+ import com.vaadin.ui.Window;
+ import com.vaadin.ui.Window.CloseEvent;
+ import com.vaadin.ui.Window.CloseListener;
+
+ public class CloseSubWindow extends TestBase {
+
- private Window browserWindow;
+ private Log log = new Log(5);
+
+ @Override
+ protected void setup() {
+ Button openWindowButton = new Button("Open sub-window");
+ openWindowButton.setDebugId("opensub");
+ openWindowButton.addListener(new ClickListener() {
+ public void buttonClick(ClickEvent event) {
+ Window sub = createClosableSubWindow("Sub-window");
+ getMainWindow().addWindow(sub);
+ }
+ });
+
+ addComponent(log);
+ addComponent(openWindowButton);
-
- Button openBrowserWindowButton = new Button("Open browser window");
- openWindowButton.setDebugId("opennative");
- openBrowserWindowButton.addListener(new ClickListener() {
- public void buttonClick(ClickEvent event) {
- browserWindow = new Window("Window");
- Button closeButton = new Button("Close this window",
- new ClickListener() {
-
- public void buttonClick(ClickEvent event) {
- event.getButton().getWindow()
- .executeJavaScript("window.close();");
-
- }
- });
- browserWindow.addComponent(closeButton);
-
- browserWindow.addListener(new CloseListener() {
- public void windowClose(CloseEvent e) {
- logBrowserWindowClosed();
- // there is no push, so the user needs to click a button
- // to see the notification
-
- // Opera does not send a notification about the window
- // having been closed
- }
-
- });
-
- addWindow(browserWindow);
- URL windowUrl = browserWindow.getURL();
- // named for easier access by test tools
- getMainWindow().open(new ExternalResource(windowUrl),
- "nativewindow");
- if (getBrowser().isOpera()) {
- // Immediately log a close event in Opera so this test can
- // be run for all browsers. Vaadin ticket #5687.
- logBrowserWindowClosed();
- }
- }
- });
-
- addComponent(openBrowserWindowButton);
-
- Button pollButton = new Button("Poll server");
- pollButton.setDebugId("poll");
- addComponent(pollButton);
-
+ }
+
+ private Window createClosableSubWindow(final String title) {
+ final Window window = new Window(title);
+ window.setSizeUndefined();
+ window.getContent().setSizeFull();
+ window.setClosable(true);
+
+ Button closeButton = new Button("Close");
+ closeButton.addListener(new ClickListener() {
+ public void buttonClick(ClickEvent event) {
- window.getParent().removeWindow(window);
++ window.close();
+ }
+ });
+ window.addComponent(closeButton);
+
+ Button removeButton = new Button("Remove from parent");
+ removeButton.addListener(new ClickListener() {
+ public void buttonClick(ClickEvent event) {
- window.getParent().removeWindow(window);
++ window.close();
+ }
+ });
+ window.addComponent(closeButton);
+
+ window.addListener(new CloseListener() {
+ public void windowClose(CloseEvent e) {
+ log.log("Window '" + title + "' closed");
+ }
+ });
+
+ return window;
+ }
+
+ @Override
+ protected String getDescription() {
+ return "Close sub-windows both from code and with the close button in the window title bar, and check for close events. Contains an ugly workaround for the Opera bug (Opera does not send close events)";
+ }
+
+ @Override
+ protected Integer getTicketNumber() {
+ return 3865;
+ }
-
- private void logBrowserWindowClosed() {
- log.log("Browser window closed");
-
- }
-
+ }
- package com.vaadin.tests.components.window;\r
- \r
- import com.vaadin.terminal.ThemeResource;\r
- import com.vaadin.tests.components.TestBase;\r
- import com.vaadin.ui.Alignment;\r
- import com.vaadin.ui.Button;\r
- import com.vaadin.ui.Button.ClickEvent;\r
- import com.vaadin.ui.Window;\r
- \r
- public class ExtraWindowShown extends TestBase {\r
- \r
- @Override\r
- protected void setup() {\r
- Button b = new Button("Open window", new Button.ClickListener() {\r
- \r
- public void buttonClick(ClickEvent event) {\r
- \r
- final Window w = new Window("Sub window");\r
- w.center();\r
- w.addComponent(new Button("Close", new Button.ClickListener() {\r
- \r
- public void buttonClick(ClickEvent event) {\r
- w.close();\r
- }\r
- }));\r
- Button iconButton = new Button("A button with icon");\r
- iconButton\r
- .setIcon(new ThemeResource("../runo/icons/16/ok.png"));\r
- w.addComponent(iconButton);\r
- event.getButton().getRoot().addWindow(w);\r
- }\r
- \r
- });\r
- getLayout().setHeight("100%");\r
- getLayout().addComponent(b);\r
- getLayout().setComponentAlignment(b, Alignment.MIDDLE_CENTER);\r
- }\r
- \r
- @Override\r
- protected String getDescription() {\r
- // TODO Auto-generated method stub\r
- return null;\r
- }\r
- \r
- @Override\r
- protected Integer getTicketNumber() {\r
- // TODO Auto-generated method stub\r
- return null;\r
- }\r
- \r
- }\r
+ package com.vaadin.tests.components.window;
+
+ import com.vaadin.terminal.ThemeResource;
+ import com.vaadin.tests.components.TestBase;
+ import com.vaadin.ui.Alignment;
+ import com.vaadin.ui.Button;
+ import com.vaadin.ui.Button.ClickEvent;
+ import com.vaadin.ui.Window;
+
+ public class ExtraWindowShown extends TestBase {
+
+ @Override
+ protected void setup() {
+ Button b = new Button("Open window", new Button.ClickListener() {
+
+ public void buttonClick(ClickEvent event) {
+
+ final Window w = new Window("Sub window");
+ w.center();
+ w.addComponent(new Button("Close", new Button.ClickListener() {
+
+ public void buttonClick(ClickEvent event) {
- Window main = w.getParent();
- // main = w.getWindow();
- main.removeWindow(w);
++ w.close();
+ }
+ }));
+ Button iconButton = new Button("A button with icon");
+ iconButton
+ .setIcon(new ThemeResource("../runo/icons/16/ok.png"));
+ w.addComponent(iconButton);
- event.getButton().getWindow().addWindow(w);
++ event.getButton().getRoot().addWindow(w);
+ }
+
+ });
+ getLayout().setHeight("100%");
+ getLayout().addComponent(b);
+ getLayout().setComponentAlignment(b, Alignment.MIDDLE_CENTER);
+ }
+
+ @Override
+ protected String getDescription() {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ protected Integer getTicketNumber() {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ }
- package com.vaadin.tests.components.window;\r
- \r
- import com.vaadin.tests.components.AbstractTestCase;\r
- import com.vaadin.ui.Button;\r
- import com.vaadin.ui.Button.ClickEvent;\r
- import com.vaadin.ui.Button.ClickListener;\r
- import com.vaadin.ui.Component;\r
- import com.vaadin.ui.HorizontalLayout;\r
- import com.vaadin.ui.Label;\r
- import com.vaadin.ui.Panel;\r
- import com.vaadin.ui.Root.LegacyWindow;\r
- import com.vaadin.ui.Table;\r
- import com.vaadin.ui.VerticalLayout;\r
- import com.vaadin.ui.Window;\r
- \r
- public class WindowScrollingComponentIntoView extends AbstractTestCase {\r
- \r
- @Override\r
- protected String getDescription() {\r
- return "Scroll down, click 'up' and the view should scroll to the top";\r
- }\r
- \r
- @Override\r
- protected Integer getTicketNumber() {\r
- return 4206;\r
- }\r
- \r
- @Override\r
- public void init() {\r
- Table table = new Table();\r
- table.setPageLength(50);\r
- \r
- setMainWindow(new LegacyWindow(""));\r
- getMainWindow().getContent().setSizeUndefined();\r
- \r
- Component l2 = null;\r
- for (int i = 0; i < 10; i++) {\r
- l2 = l("X" + i);\r
- getMainWindow().addComponent(l2);\r
- }\r
- \r
- final Component x9 = l2;\r
- \r
- HorizontalLayout horizontalLayout = new HorizontalLayout();\r
- \r
- Component l = null;\r
- for (int i = 0; i < 10; i++) {\r
- l = l("Y" + i);\r
- horizontalLayout.addComponent(l);\r
- }\r
- \r
- getMainWindow().addComponent(horizontalLayout);\r
- final Component y9 = l;\r
- \r
- final Window window = new Window();\r
- window.setHeight("500px");\r
- window.setWidth("500px");\r
- window.setPositionX(200);\r
- window.setPositionY(200);\r
- \r
- window.addComponent(new Button("Scroll mainwin to X9",\r
- new ClickListener() {\r
- public void buttonClick(ClickEvent event) {\r
- getMainWindow().scrollIntoView(x9);\r
- \r
- }\r
- }));\r
- window.addComponent(new Button("Scroll mainwin to Y9",\r
- new ClickListener() {\r
- public void buttonClick(ClickEvent event) {\r
- getMainWindow().scrollIntoView(y9);\r
- \r
- }\r
- }));\r
- \r
- Panel panel = new Panel("scrollable panel");\r
- panel.setHeight(400, Panel.UNITS_PIXELS);\r
- panel.setScrollable(true);\r
- panel.setScrollLeft(50);\r
- panel.setScrollTop(50);\r
- panel.getContent().setSizeUndefined();\r
- window.addComponent(l("Spacer", 500, 500));\r
- \r
- l2 = null;\r
- for (int i = 0; i < 10; i++) {\r
- l2 = l("X" + i);\r
- panel.addComponent(l2);\r
- }\r
- \r
- final Component x29 = l2;\r
- \r
- horizontalLayout = new HorizontalLayout();\r
- \r
- l = null;\r
- for (int i = 0; i < 10; i++) {\r
- l = l("Y" + i);\r
- horizontalLayout.addComponent(l);\r
- }\r
- panel.addComponent(horizontalLayout);\r
- final Component y29 = l;\r
- \r
- ((VerticalLayout) getMainWindow().getContent()).addComponent(\r
- new Button("Scroll win to X9", new ClickListener() {\r
- public void buttonClick(ClickEvent event) {\r
- throw new RuntimeException("Currently not implemented");\r
- // window.scrollIntoView(x29);\r
- }\r
- }), 0);\r
- ((VerticalLayout) getMainWindow().getContent()).addComponent(\r
- new Button("Scroll win to Y9", new ClickListener() {\r
- public void buttonClick(ClickEvent event) {\r
- throw new RuntimeException("Currently not implemented");\r
- // window.scrollIntoView(y29);\r
- }\r
- }), 0);\r
- \r
- window.addComponent(panel);\r
- getMainWindow().addWindow(window);\r
- \r
- }\r
- \r
- private Component l(String string) {\r
- return l(string, 200, 350);\r
- }\r
- \r
- private Component l(String string, int h, int w) {\r
- Label label = new Label(string);\r
- label.setHeight(h, Label.UNITS_PIXELS);\r
- label.setWidth(w, Label.UNITS_PIXELS);\r
- return label;\r
- }\r
- }\r
+ package com.vaadin.tests.components.window;
+
+ import com.vaadin.tests.components.AbstractTestCase;
+ import com.vaadin.ui.Button;
+ import com.vaadin.ui.Button.ClickEvent;
+ import com.vaadin.ui.Button.ClickListener;
+ import com.vaadin.ui.Component;
+ import com.vaadin.ui.HorizontalLayout;
+ import com.vaadin.ui.Label;
+ import com.vaadin.ui.Panel;
++import com.vaadin.ui.Root.LegacyWindow;
+ import com.vaadin.ui.Table;
+ import com.vaadin.ui.VerticalLayout;
+ import com.vaadin.ui.Window;
+
+ public class WindowScrollingComponentIntoView extends AbstractTestCase {
+
+ @Override
+ protected String getDescription() {
+ return "Scroll down, click 'up' and the view should scroll to the top";
+ }
+
+ @Override
+ protected Integer getTicketNumber() {
+ return 4206;
+ }
+
+ @Override
+ public void init() {
+ Table table = new Table();
+ table.setPageLength(50);
+
- final Button up = new Button("up");
- up.addListener(new Button.ClickListener() {
-
- public void buttonClick(ClickEvent event) {
- up.getWindow().setScrollTop(0);
- }
- });
-
- setMainWindow(new Window(""));
++ setMainWindow(new LegacyWindow(""));
+ getMainWindow().getContent().setSizeUndefined();
+
+ Component l2 = null;
+ for (int i = 0; i < 10; i++) {
+ l2 = l("X" + i);
+ getMainWindow().addComponent(l2);
+ }
+
+ final Component x9 = l2;
+
+ HorizontalLayout horizontalLayout = new HorizontalLayout();
+
+ Component l = null;
+ for (int i = 0; i < 10; i++) {
+ l = l("Y" + i);
+ horizontalLayout.addComponent(l);
+ }
+
+ getMainWindow().addComponent(horizontalLayout);
+ final Component y9 = l;
+
+ final Window window = new Window();
+ window.setHeight("500px");
+ window.setWidth("500px");
+ window.setPositionX(200);
+ window.setPositionY(200);
+
+ window.addComponent(new Button("Scroll mainwin to X9",
+ new ClickListener() {
+ public void buttonClick(ClickEvent event) {
+ getMainWindow().scrollIntoView(x9);
+
+ }
+ }));
+ window.addComponent(new Button("Scroll mainwin to Y9",
+ new ClickListener() {
+ public void buttonClick(ClickEvent event) {
+ getMainWindow().scrollIntoView(y9);
+
+ }
+ }));
+
+ Panel panel = new Panel("scrollable panel");
+ panel.setHeight(400, Panel.UNITS_PIXELS);
+ panel.setScrollable(true);
+ panel.setScrollLeft(50);
+ panel.setScrollTop(50);
+ panel.getContent().setSizeUndefined();
+ window.addComponent(l("Spacer", 500, 500));
+
+ l2 = null;
+ for (int i = 0; i < 10; i++) {
+ l2 = l("X" + i);
+ panel.addComponent(l2);
+ }
+
+ final Component x29 = l2;
+
+ horizontalLayout = new HorizontalLayout();
+
+ l = null;
+ for (int i = 0; i < 10; i++) {
+ l = l("Y" + i);
+ horizontalLayout.addComponent(l);
+ }
+ panel.addComponent(horizontalLayout);
+ final Component y29 = l;
+
+ ((VerticalLayout) getMainWindow().getContent()).addComponent(
+ new Button("Scroll win to X9", new ClickListener() {
+ public void buttonClick(ClickEvent event) {
- window.scrollIntoView(x29);
++ throw new RuntimeException("Currently not implemented");
++ // window.scrollIntoView(x29);
+ }
+ }), 0);
+ ((VerticalLayout) getMainWindow().getContent()).addComponent(
+ new Button("Scroll win to Y9", new ClickListener() {
+ public void buttonClick(ClickEvent event) {
- window.scrollIntoView(y29);
++ throw new RuntimeException("Currently not implemented");
++ // window.scrollIntoView(y29);
+ }
+ }), 0);
+
+ window.addComponent(panel);
+ getMainWindow().addWindow(window);
+
+ }
+
+ private Component l(String string) {
+ return l(string, 200, 350);
+ }
+
+ private Component l(String string, int h, int w) {
+ Label label = new Label(string);
+ label.setHeight(h, Label.UNITS_PIXELS);
+ label.setWidth(w, Label.UNITS_PIXELS);
+ return label;
+ }
+ }
- package com.vaadin.tests.components.window;\r
- \r
- import com.vaadin.tests.components.AbstractTestCase;\r
- import com.vaadin.ui.Button;\r
- import com.vaadin.ui.Button.ClickEvent;\r
- import com.vaadin.ui.Root.LegacyWindow;\r
- import com.vaadin.ui.Table;\r
- \r
- public class WindowScrollingUp extends AbstractTestCase {\r
- \r
- @Override\r
- protected String getDescription() {\r
- return "Scroll down, click 'up' and the view should scroll to the top";\r
- }\r
- \r
- @Override\r
- protected Integer getTicketNumber() {\r
- return 4206;\r
- }\r
- \r
- @Override\r
- public void init() {\r
- Table table = new Table();\r
- table.setPageLength(50);\r
- \r
- final Button up = new Button("up");\r
- up.addListener(new Button.ClickListener() {\r
- \r
- public void buttonClick(ClickEvent event) {\r
- up.getRoot().setScrollTop(0);\r
- }\r
- });\r
- \r
- setMainWindow(new LegacyWindow(""));\r
- getMainWindow().addComponent(table);\r
- getMainWindow().addComponent(up);\r
- \r
- }\r
- }\r
+ package com.vaadin.tests.components.window;
+
+ import com.vaadin.tests.components.AbstractTestCase;
+ import com.vaadin.ui.Button;
+ import com.vaadin.ui.Button.ClickEvent;
++import com.vaadin.ui.Root.LegacyWindow;
+ import com.vaadin.ui.Table;
-import com.vaadin.ui.Window;
+
+ public class WindowScrollingUp extends AbstractTestCase {
+
+ @Override
+ protected String getDescription() {
+ return "Scroll down, click 'up' and the view should scroll to the top";
+ }
+
+ @Override
+ protected Integer getTicketNumber() {
+ return 4206;
+ }
+
+ @Override
+ public void init() {
+ Table table = new Table();
+ table.setPageLength(50);
+
+ final Button up = new Button("up");
+ up.addListener(new Button.ClickListener() {
+
+ public void buttonClick(ClickEvent event) {
- up.getWindow().setScrollTop(0);
++ up.getRoot().setScrollTop(0);
+ }
+ });
+
- setMainWindow(new Window(""));
++ setMainWindow(new LegacyWindow(""));
+ getMainWindow().addComponent(table);
+ getMainWindow().addComponent(up);
+
+ }
+ }
- package com.vaadin.tests.containers;\r
- \r
- import com.vaadin.data.Item;\r
- import com.vaadin.data.Property.ValueChangeEvent;\r
- import com.vaadin.data.Property.ValueChangeListener;\r
- import com.vaadin.data.util.BeanItemContainer;\r
- import com.vaadin.terminal.Sizeable;\r
- import com.vaadin.tests.components.TestBase;\r
- import com.vaadin.ui.Button;\r
- import com.vaadin.ui.Button.ClickEvent;\r
- import com.vaadin.ui.CheckBox;\r
- import com.vaadin.ui.Label;\r
- import com.vaadin.ui.Table;\r
- import com.vaadin.ui.TextField;\r
- import com.vaadin.ui.VerticalLayout;\r
- \r
- public class BeanItemContainerFilteringTest extends TestBase {\r
- \r
- private Table table;\r
- private BeanItemContainer<TestBean> container;\r
- private TextField filterString;\r
- private TextField position;\r
- private int nextToAdd = 1;\r
- private Label nextLabel;\r
- \r
- protected static class TestBean {\r
- private String id;\r
- private String value;\r
- \r
- public TestBean() {\r
- }\r
- \r
- public TestBean(String id, String value) {\r
- setId(id);\r
- setValue(value);\r
- }\r
- \r
- public void setId(String id) {\r
- this.id = id;\r
- }\r
- \r
- public String getId() {\r
- return id;\r
- }\r
- \r
- public void setValue(String value) {\r
- this.value = value;\r
- }\r
- \r
- public String getValue() {\r
- return value;\r
- }\r
- }\r
- \r
- @Override\r
- protected String getDescription() {\r
- return "Test adding items in a filtered BeanItemContainer.";\r
- }\r
- \r
- @Override\r
- protected Integer getTicketNumber() {\r
- return new Integer(1061);\r
- }\r
- \r
- @Override\r
- protected void setup() {\r
- table = new Table();\r
- try {\r
- container = new BeanItemContainer<TestBean>(TestBean.class);\r
- table.setContainerDataSource(container);\r
- \r
- table.setWidth(300, Sizeable.UNITS_PIXELS);\r
- table.setSelectable(true);\r
- table.setMultiSelect(false);\r
- table.setEditable(true);\r
- table.setImmediate(true);\r
- // table.addContainerProperty("column1", String.class, "test");\r
- \r
- for (int i = 0; i < 25; ++i) {\r
- container.addItem(new TestBean("Item " + i, "Value for " + i));\r
- }\r
- \r
- VerticalLayout vl = new VerticalLayout();\r
- \r
- // activate & deactivate filtering\r
- filterString = new TextField("Filter string:", "1");\r
- vl.addComponent(filterString);\r
- \r
- final CheckBox cb = new CheckBox("Filter on value");\r
- cb.addListener(new ValueChangeListener() {\r
- \r
- public void valueChange(ValueChangeEvent event) {\r
- container.removeAllContainerFilters();\r
- if (((CheckBox) event.getProperty()).getValue()) {\r
- container.addContainerFilter("value", filterString\r
- .getValue().toString(), false, false);\r
- }\r
- }\r
- });\r
- cb.setImmediate(true);\r
- vl.addComponent(cb);\r
- \r
- nextLabel = new Label();\r
- nextLabel.setCaption("Next id: " + nextToAdd);\r
- vl.addComponent(nextLabel);\r
- \r
- // addItemAt(idx), addItemAfter(selection), addItem()\r
- \r
- final Button addItemButton = new Button("addItem()",\r
- new Button.ClickListener() {\r
- public void buttonClick(ClickEvent event) {\r
- container.addItem(new TestBean("addItem() "\r
- + nextToAdd, "value " + nextToAdd));\r
- nextToAdd++;\r
- nextLabel.setCaption("Next id: " + nextToAdd);\r
- }\r
- });\r
- addItemButton.setImmediate(true);\r
- vl.addComponent(addItemButton);\r
- \r
- final Button addItemAfterButton = new Button("addItemAfter()",\r
- new Button.ClickListener() {\r
- public void buttonClick(ClickEvent event) {\r
- Object selection = table.getValue();\r
- if (selection == null) {\r
- return;\r
- }\r
- TestBean bean = new TestBean("addItemAfter() "\r
- + nextToAdd, "value " + nextToAdd);\r
- Item item = container.addItemAfter(selection, bean);\r
- if (item == null) {\r
- getMainWindow().showNotification(\r
- "Adding item after " + selection\r
- + " failed");\r
- }\r
- nextToAdd++;\r
- nextLabel.setCaption("Next id: " + nextToAdd);\r
- }\r
- });\r
- addItemAfterButton.setImmediate(true);\r
- vl.addComponent(addItemAfterButton);\r
- \r
- position = new TextField("Position:", "0");\r
- vl.addComponent(position);\r
- \r
- final Button addItemAtButton = new Button("addItemAt()",\r
- new Button.ClickListener() {\r
- public void buttonClick(ClickEvent event) {\r
- int index = Integer.parseInt(position.getValue()\r
- .toString());\r
- TestBean bean = new TestBean("addItemAt() "\r
- + nextToAdd, "value " + nextToAdd);\r
- Item item = container.addItemAt(index, bean);\r
- if (item == null) {\r
- getMainWindow().showNotification(\r
- "Adding item at index "\r
- + position.getValue()\r
- + " failed");\r
- }\r
- nextToAdd++;\r
- nextLabel.setCaption("Next id: " + nextToAdd);\r
- }\r
- });\r
- addItemAtButton.setImmediate(true);\r
- vl.addComponent(addItemAtButton);\r
- \r
- getLayout().addComponent(table);\r
- getLayout().addComponent(vl);\r
- } catch (Exception ex) {\r
- ex.printStackTrace();\r
- }\r
- }\r
- \r
- }\r
+ package com.vaadin.tests.containers;
+
+ import com.vaadin.data.Item;
++import com.vaadin.data.Property.ValueChangeEvent;
++import com.vaadin.data.Property.ValueChangeListener;
+ import com.vaadin.data.util.BeanItemContainer;
+ import com.vaadin.terminal.Sizeable;
+ import com.vaadin.tests.components.TestBase;
+ import com.vaadin.ui.Button;
+ import com.vaadin.ui.Button.ClickEvent;
+ import com.vaadin.ui.CheckBox;
+ import com.vaadin.ui.Label;
+ import com.vaadin.ui.Table;
+ import com.vaadin.ui.TextField;
+ import com.vaadin.ui.VerticalLayout;
+
+ public class BeanItemContainerFilteringTest extends TestBase {
+
+ private Table table;
+ private BeanItemContainer<TestBean> container;
+ private TextField filterString;
+ private TextField position;
+ private int nextToAdd = 1;
+ private Label nextLabel;
+
+ protected static class TestBean {
+ private String id;
+ private String value;
+
+ public TestBean() {
+ }
+
+ public TestBean(String id, String value) {
+ setId(id);
+ setValue(value);
+ }
+
+ public void setId(String id) {
+ this.id = id;
+ }
+
+ public String getId() {
+ return id;
+ }
+
+ public void setValue(String value) {
+ this.value = value;
+ }
+
+ public String getValue() {
+ return value;
+ }
+ }
+
+ @Override
+ protected String getDescription() {
+ return "Test adding items in a filtered BeanItemContainer.";
+ }
+
+ @Override
+ protected Integer getTicketNumber() {
+ return new Integer(1061);
+ }
+
+ @Override
+ protected void setup() {
+ table = new Table();
+ try {
+ container = new BeanItemContainer<TestBean>(TestBean.class);
+ table.setContainerDataSource(container);
+
+ table.setWidth(300, Sizeable.UNITS_PIXELS);
+ table.setSelectable(true);
+ table.setMultiSelect(false);
+ table.setEditable(true);
+ table.setImmediate(true);
+ // table.addContainerProperty("column1", String.class, "test");
+
+ for (int i = 0; i < 25; ++i) {
+ container.addItem(new TestBean("Item " + i, "Value for " + i));
+ }
+
+ VerticalLayout vl = new VerticalLayout();
+
+ // activate & deactivate filtering
+ filterString = new TextField("Filter string:", "1");
+ vl.addComponent(filterString);
+
- final CheckBox cb = new CheckBox("Filter on value",
- new Button.ClickListener() {
- public void buttonClick(ClickEvent event) {
- container.removeAllContainerFilters();
- if (((CheckBox) event.getSource()).booleanValue()) {
- container.addContainerFilter("value",
- filterString.getValue().toString(),
- false, false);
- }
- }
- });
++ final CheckBox cb = new CheckBox("Filter on value");
++ cb.addListener(new ValueChangeListener() {
++
++ public void valueChange(ValueChangeEvent event) {
++ container.removeAllContainerFilters();
++ if (((CheckBox) event.getProperty()).getValue()) {
++ container.addContainerFilter("value", filterString
++ .getValue().toString(), false, false);
++ }
++ }
++ });
+ cb.setImmediate(true);
+ vl.addComponent(cb);
+
+ nextLabel = new Label();
+ nextLabel.setCaption("Next id: " + nextToAdd);
+ vl.addComponent(nextLabel);
+
+ // addItemAt(idx), addItemAfter(selection), addItem()
+
+ final Button addItemButton = new Button("addItem()",
+ new Button.ClickListener() {
+ public void buttonClick(ClickEvent event) {
+ container.addItem(new TestBean("addItem() "
+ + nextToAdd, "value " + nextToAdd));
+ nextToAdd++;
+ nextLabel.setCaption("Next id: " + nextToAdd);
+ }
+ });
+ addItemButton.setImmediate(true);
+ vl.addComponent(addItemButton);
+
+ final Button addItemAfterButton = new Button("addItemAfter()",
+ new Button.ClickListener() {
+ public void buttonClick(ClickEvent event) {
+ Object selection = table.getValue();
+ if (selection == null) {
+ return;
+ }
+ TestBean bean = new TestBean("addItemAfter() "
+ + nextToAdd, "value " + nextToAdd);
+ Item item = container.addItemAfter(selection, bean);
+ if (item == null) {
+ getMainWindow().showNotification(
+ "Adding item after " + selection
+ + " failed");
+ }
+ nextToAdd++;
+ nextLabel.setCaption("Next id: " + nextToAdd);
+ }
+ });
+ addItemAfterButton.setImmediate(true);
+ vl.addComponent(addItemAfterButton);
+
+ position = new TextField("Position:", "0");
+ vl.addComponent(position);
+
+ final Button addItemAtButton = new Button("addItemAt()",
+ new Button.ClickListener() {
+ public void buttonClick(ClickEvent event) {
+ int index = Integer.parseInt(position.getValue()
+ .toString());
+ TestBean bean = new TestBean("addItemAt() "
+ + nextToAdd, "value " + nextToAdd);
+ Item item = container.addItemAt(index, bean);
+ if (item == null) {
+ getMainWindow().showNotification(
+ "Adding item at index "
+ + position.getValue()
+ + " failed");
+ }
+ nextToAdd++;
+ nextLabel.setCaption("Next id: " + nextToAdd);
+ }
+ });
+ addItemAtButton.setImmediate(true);
+ vl.addComponent(addItemAtButton);
+
+ getLayout().addComponent(table);
+ getLayout().addComponent(vl);
+ } catch (Exception ex) {
+ ex.printStackTrace();
+ }
+ }
+
+ }
- package com.vaadin.tests.containers;\r
- \r
- import com.vaadin.data.Item;\r
- import com.vaadin.data.Property.ValueChangeEvent;\r
- import com.vaadin.data.Property.ValueChangeListener;\r
- import com.vaadin.data.util.IndexedContainer;\r
- import com.vaadin.terminal.Sizeable;\r
- import com.vaadin.tests.components.TestBase;\r
- import com.vaadin.ui.Button;\r
- import com.vaadin.ui.Button.ClickEvent;\r
- import com.vaadin.ui.CheckBox;\r
- import com.vaadin.ui.Label;\r
- import com.vaadin.ui.Table;\r
- import com.vaadin.ui.TextField;\r
- import com.vaadin.ui.VerticalLayout;\r
- \r
- public class IndexedContainerFilteringTest extends TestBase {\r
- \r
- private Table table;\r
- private IndexedContainer container;\r
- private TextField filterString;\r
- private TextField position;\r
- private int nextToAdd = 1;\r
- private Label nextLabel;\r
- \r
- @Override\r
- protected String getDescription() {\r
- return "Adding items to a filtered IndexedContainer inserts the items at the wrong location.";\r
- }\r
- \r
- @Override\r
- protected Integer getTicketNumber() {\r
- return new Integer(2809);\r
- }\r
- \r
- @Override\r
- protected void setup() {\r
- table = new Table();\r
- container = (IndexedContainer) table.getContainerDataSource();\r
- \r
- table.setWidth(300, Sizeable.UNITS_PIXELS);\r
- table.setSelectable(true);\r
- table.setMultiSelect(false);\r
- table.addContainerProperty("column1", String.class, "test");\r
- \r
- for (int i = 0; i < 25; ++i) {\r
- table.addItem(new Object[] { "Item " + i }, "Item " + i);\r
- }\r
- \r
- VerticalLayout vl = new VerticalLayout();\r
- \r
- // activate & deactivate filtering\r
- filterString = new TextField("Filter string:", "1");\r
- vl.addComponent(filterString);\r
- \r
- final CheckBox cb = new CheckBox("Filter");\r
- cb.addListener(new ValueChangeListener() {\r
- \r
- public void valueChange(ValueChangeEvent event) {\r
- container.removeAllContainerFilters();\r
- if (((CheckBox) event.getProperty()).getValue()) {\r
- container.addContainerFilter("column1", filterString\r
- .getValue().toString(), false, false);\r
- }\r
- }\r
- });\r
- cb.setImmediate(true);\r
- vl.addComponent(cb);\r
- \r
- nextLabel = new Label();\r
- nextLabel.setCaption("Next id: " + nextToAdd);\r
- vl.addComponent(nextLabel);\r
- \r
- // addItemAt(idx), addItemAfter(selection), addItem()\r
- \r
- final Button addItemButton = new Button("addItem()",\r
- new Button.ClickListener() {\r
- public void buttonClick(ClickEvent event) {\r
- Item item = container.addItem("addItem() " + nextToAdd);\r
- if (item != null) {\r
- item.getItemProperty("column1").setValue(\r
- "addItem() " + nextToAdd);\r
- }\r
- nextToAdd++;\r
- nextLabel.setCaption("Next id: " + nextToAdd);\r
- }\r
- });\r
- addItemButton.setImmediate(true);\r
- vl.addComponent(addItemButton);\r
- \r
- final Button addItemAfterButton = new Button("addItemAfter()",\r
- new Button.ClickListener() {\r
- public void buttonClick(ClickEvent event) {\r
- Object selection = table.getValue();\r
- if (selection == null) {\r
- return;\r
- }\r
- String id = "addItemAfter() " + nextToAdd;\r
- Item item = container.addItemAfter(selection, id);\r
- if (item != null) {\r
- item.getItemProperty("column1").setValue(id);\r
- table.setValue(id);\r
- } else {\r
- getMainWindow().showNotification(\r
- "Adding item after " + selection\r
- + " failed");\r
- }\r
- nextToAdd++;\r
- nextLabel.setCaption("Next id: " + nextToAdd);\r
- }\r
- });\r
- addItemAfterButton.setImmediate(true);\r
- vl.addComponent(addItemAfterButton);\r
- \r
- position = new TextField("Position:", "0");\r
- vl.addComponent(position);\r
- \r
- final Button addItemAtButton = new Button("addItemAt()",\r
- new Button.ClickListener() {\r
- public void buttonClick(ClickEvent event) {\r
- int index = Integer.parseInt(position.getValue()\r
- .toString());\r
- String id = "addItemAt() " + nextToAdd;\r
- Item item = container.addItemAt(index, id);\r
- if (item != null) {\r
- item.getItemProperty("column1").setValue(id);\r
- table.setValue(id);\r
- } else {\r
- getMainWindow().showNotification(\r
- "Adding item at index "\r
- + position.getValue() + " failed");\r
- }\r
- nextToAdd++;\r
- nextLabel.setCaption("Next id: " + nextToAdd);\r
- }\r
- });\r
- addItemAtButton.setImmediate(true);\r
- vl.addComponent(addItemAtButton);\r
- \r
- getLayout().addComponent(table);\r
- getLayout().addComponent(vl);\r
- }\r
- }\r
+ package com.vaadin.tests.containers;
+
+ import com.vaadin.data.Item;
++import com.vaadin.data.Property.ValueChangeEvent;
++import com.vaadin.data.Property.ValueChangeListener;
+ import com.vaadin.data.util.IndexedContainer;
+ import com.vaadin.terminal.Sizeable;
+ import com.vaadin.tests.components.TestBase;
+ import com.vaadin.ui.Button;
+ import com.vaadin.ui.Button.ClickEvent;
+ import com.vaadin.ui.CheckBox;
+ import com.vaadin.ui.Label;
+ import com.vaadin.ui.Table;
+ import com.vaadin.ui.TextField;
+ import com.vaadin.ui.VerticalLayout;
+
+ public class IndexedContainerFilteringTest extends TestBase {
+
+ private Table table;
+ private IndexedContainer container;
+ private TextField filterString;
+ private TextField position;
+ private int nextToAdd = 1;
+ private Label nextLabel;
+
+ @Override
+ protected String getDescription() {
+ return "Adding items to a filtered IndexedContainer inserts the items at the wrong location.";
+ }
+
+ @Override
+ protected Integer getTicketNumber() {
+ return new Integer(2809);
+ }
+
+ @Override
+ protected void setup() {
+ table = new Table();
+ container = (IndexedContainer) table.getContainerDataSource();
+
+ table.setWidth(300, Sizeable.UNITS_PIXELS);
+ table.setSelectable(true);
+ table.setMultiSelect(false);
+ table.addContainerProperty("column1", String.class, "test");
+
+ for (int i = 0; i < 25; ++i) {
+ table.addItem(new Object[] { "Item " + i }, "Item " + i);
+ }
+
+ VerticalLayout vl = new VerticalLayout();
+
+ // activate & deactivate filtering
+ filterString = new TextField("Filter string:", "1");
+ vl.addComponent(filterString);
+
- final CheckBox cb = new CheckBox("Filter", new Button.ClickListener() {
- public void buttonClick(ClickEvent event) {
++ final CheckBox cb = new CheckBox("Filter");
++ cb.addListener(new ValueChangeListener() {
++
++ public void valueChange(ValueChangeEvent event) {
+ container.removeAllContainerFilters();
- if (((CheckBox) event.getSource()).booleanValue()) {
++ if (((CheckBox) event.getProperty()).getValue()) {
+ container.addContainerFilter("column1", filterString
+ .getValue().toString(), false, false);
+ }
+ }
+ });
+ cb.setImmediate(true);
+ vl.addComponent(cb);
+
+ nextLabel = new Label();
+ nextLabel.setCaption("Next id: " + nextToAdd);
+ vl.addComponent(nextLabel);
+
+ // addItemAt(idx), addItemAfter(selection), addItem()
+
+ final Button addItemButton = new Button("addItem()",
+ new Button.ClickListener() {
+ public void buttonClick(ClickEvent event) {
+ Item item = container.addItem("addItem() " + nextToAdd);
+ if (item != null) {
+ item.getItemProperty("column1").setValue(
+ "addItem() " + nextToAdd);
+ }
+ nextToAdd++;
+ nextLabel.setCaption("Next id: " + nextToAdd);
+ }
+ });
+ addItemButton.setImmediate(true);
+ vl.addComponent(addItemButton);
+
+ final Button addItemAfterButton = new Button("addItemAfter()",
+ new Button.ClickListener() {
+ public void buttonClick(ClickEvent event) {
+ Object selection = table.getValue();
+ if (selection == null) {
+ return;
+ }
+ String id = "addItemAfter() " + nextToAdd;
+ Item item = container.addItemAfter(selection, id);
+ if (item != null) {
+ item.getItemProperty("column1").setValue(id);
+ table.setValue(id);
+ } else {
+ getMainWindow().showNotification(
+ "Adding item after " + selection
+ + " failed");
+ }
+ nextToAdd++;
+ nextLabel.setCaption("Next id: " + nextToAdd);
+ }
+ });
+ addItemAfterButton.setImmediate(true);
+ vl.addComponent(addItemAfterButton);
+
+ position = new TextField("Position:", "0");
+ vl.addComponent(position);
+
+ final Button addItemAtButton = new Button("addItemAt()",
+ new Button.ClickListener() {
+ public void buttonClick(ClickEvent event) {
+ int index = Integer.parseInt(position.getValue()
+ .toString());
+ String id = "addItemAt() " + nextToAdd;
+ Item item = container.addItemAt(index, id);
+ if (item != null) {
+ item.getItemProperty("column1").setValue(id);
+ table.setValue(id);
+ } else {
+ getMainWindow().showNotification(
+ "Adding item at index "
+ + position.getValue() + " failed");
+ }
+ nextToAdd++;
+ nextLabel.setCaption("Next id: " + nextToAdd);
+ }
+ });
+ addItemAtButton.setImmediate(true);
+ vl.addComponent(addItemAtButton);
+
+ getLayout().addComponent(table);
+ getLayout().addComponent(vl);
+ }
+ }
--- /dev/null
- package com.vaadin.tests.converter;\r
- \r
- import com.vaadin.data.Property.ValueChangeEvent;\r
- import com.vaadin.data.Property.ValueChangeListener;\r
- import com.vaadin.tests.components.TestBase;\r
- import com.vaadin.tests.util.Log;\r
- import com.vaadin.ui.TextField;\r
- \r
- public class ConverterThatEnforcesAFormat extends TestBase {\r
- \r
- private Log log = new Log(5);\r
- \r
- @Override\r
- protected void setup() {\r
- final TextField tf = new TextField(\r
- "This field should always be formatted with 3 digits");\r
- tf.setConverter(new StringToDoubleConverterWithThreeFractionDigits());\r
- tf.addListener(new ValueChangeListener() {\r
- public void valueChange(ValueChangeEvent event) {\r
- log.log("Value changed to "\r
- + event.getProperty().getValue()\r
- + "(converted value is "\r
- + tf.getConvertedValue()\r
- + "). Two-way conversion gives: "\r
- + tf.getConverter().convertToPresentation(\r
- tf.getConverter().convertToModel(tf.getValue(),\r
- tf.getLocale()), tf.getLocale()) + ")");\r
- }\r
- });\r
- tf.setImmediate(true);\r
- addComponent(log);\r
- addComponent(tf);\r
- tf.setConvertedValue(50.0);\r
- }\r
- \r
- @Override\r
- protected String getDescription() {\r
- return "Entering a valid double in the field should always cause the field contents to be formatted to contain 3 digits after the decimal point";\r
- }\r
- \r
- @Override\r
- protected Integer getTicketNumber() {\r
- return 8191;\r
- }\r
- \r
- }\r
++package com.vaadin.tests.converter;
++
++import com.vaadin.data.Property.ValueChangeEvent;
++import com.vaadin.data.Property.ValueChangeListener;
++import com.vaadin.tests.components.TestBase;
++import com.vaadin.tests.util.Log;
++import com.vaadin.ui.TextField;
++
++public class ConverterThatEnforcesAFormat extends TestBase {
++
++ private Log log = new Log(5);
++
++ @Override
++ protected void setup() {
++ final TextField tf = new TextField(
++ "This field should always be formatted with 3 digits");
++ tf.setConverter(new StringToDoubleConverterWithThreeFractionDigits());
++ tf.addListener(new ValueChangeListener() {
++ public void valueChange(ValueChangeEvent event) {
++ log.log("Value changed to "
++ + event.getProperty().getValue()
++ + "(converted value is "
++ + tf.getConvertedValue()
++ + "). Two-way conversion gives: "
++ + tf.getConverter().convertToPresentation(
++ tf.getConverter().convertToModel(tf.getValue(),
++ tf.getLocale()), tf.getLocale()) + ")");
++ }
++ });
++ tf.setImmediate(true);
++ addComponent(log);
++ addComponent(tf);
++ tf.setConvertedValue(50.0);
++ }
++
++ @Override
++ protected String getDescription() {
++ return "Entering a valid double in the field should always cause the field contents to be formatted to contain 3 digits after the decimal point";
++ }
++
++ @Override
++ protected Integer getTicketNumber() {
++ return 8191;
++ }
++
++}
--- /dev/null
- package com.vaadin.tests.converter;\r
- \r
- import java.text.NumberFormat;\r
- import java.util.Locale;\r
- \r
- import com.vaadin.data.util.converter.StringToDoubleConverter;\r
- \r
- public class StringToDoubleConverterWithThreeFractionDigits extends StringToDoubleConverter {\r
- \r
- @Override\r
- protected NumberFormat getFormat(Locale locale) {\r
- NumberFormat format = super.getFormat(locale);\r
- format.setGroupingUsed(false);\r
- format.setMaximumFractionDigits(3);\r
- format.setMinimumFractionDigits(3);\r
- return format;\r
- }\r
- }\r
++package com.vaadin.tests.converter;
++
++import java.text.NumberFormat;
++import java.util.Locale;
++
++import com.vaadin.data.util.converter.StringToDoubleConverter;
++
++public class StringToDoubleConverterWithThreeFractionDigits extends StringToDoubleConverter {
++
++ @Override
++ protected NumberFormat getFormat(Locale locale) {
++ NumberFormat format = super.getFormat(locale);
++ format.setGroupingUsed(false);
++ format.setMaximumFractionDigits(3);
++ format.setMinimumFractionDigits(3);
++ return format;
++ }
++}
--- /dev/null
- package com.vaadin.tests.dd;\r
- \r
- import com.google.gwt.core.client.GWT;\r
- import com.google.gwt.user.client.ui.Widget;\r
- import com.vaadin.terminal.gwt.client.ApplicationConnection;\r
- import com.vaadin.terminal.gwt.client.UIDL;\r
- import com.vaadin.terminal.gwt.client.ui.VAbstractPaintableWidget;\r
- \r
- public class VMyDragSourcePaintable extends VAbstractPaintableWidget {\r
- \r
- public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {\r
- if (client.updateComponent(this, uidl, true)) {\r
- return;\r
- }\r
- }\r
- \r
- @Override\r
- protected Widget createWidget() {\r
- return GWT.create(VMyDragSource.class);\r
- }\r
- \r
- }\r
++package com.vaadin.tests.dd;
++
++import com.google.gwt.core.client.GWT;
++import com.google.gwt.user.client.ui.Widget;
++import com.vaadin.terminal.gwt.client.ApplicationConnection;
++import com.vaadin.terminal.gwt.client.UIDL;
++import com.vaadin.terminal.gwt.client.ui.VAbstractPaintableWidget;
++
++public class VMyDragSourcePaintable extends VAbstractPaintableWidget {
++
++ public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {
++ if (client.updateComponent(this, uidl, true)) {
++ return;
++ }
++ }
++
++ @Override
++ protected Widget createWidget() {
++ return GWT.create(VMyDragSource.class);
++ }
++
++}
--- /dev/null
- package com.vaadin.tests.dd;\r
- \r
- import com.google.gwt.core.client.GWT;\r
- import com.google.gwt.user.client.ui.Widget;\r
- import com.vaadin.terminal.gwt.client.ApplicationConnection;\r
- import com.vaadin.terminal.gwt.client.UIDL;\r
- import com.vaadin.terminal.gwt.client.ui.VAbstractPaintableWidget;\r
- \r
- public class VMyDropTargetPaintable extends VAbstractPaintableWidget {\r
- \r
- public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {\r
- if (client.updateComponent(this, uidl, true)) {\r
- return;\r
- }\r
- getWidgetForPaintable().client = client;\r
- }\r
- \r
- @Override\r
- public VMyDropTarget getWidgetForPaintable() {\r
- return (VMyDropTarget) super.getWidgetForPaintable();\r
- }\r
- \r
- @Override\r
- protected Widget createWidget() {\r
- return GWT.create(VMyDropTarget.class);\r
- }\r
- \r
- }\r
++package com.vaadin.tests.dd;
++
++import com.google.gwt.core.client.GWT;
++import com.google.gwt.user.client.ui.Widget;
++import com.vaadin.terminal.gwt.client.ApplicationConnection;
++import com.vaadin.terminal.gwt.client.UIDL;
++import com.vaadin.terminal.gwt.client.ui.VAbstractPaintableWidget;
++
++public class VMyDropTargetPaintable extends VAbstractPaintableWidget {
++
++ public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {
++ if (client.updateComponent(this, uidl, true)) {
++ return;
++ }
++ getWidgetForPaintable().client = client;
++ }
++
++ @Override
++ public VMyDropTarget getWidgetForPaintable() {
++ return (VMyDropTarget) super.getWidgetForPaintable();
++ }
++
++ @Override
++ protected Widget createWidget() {
++ return GWT.create(VMyDropTarget.class);
++ }
++
++}
--- /dev/null
- package com.vaadin.tests.fieldgroup;\r
- \r
- import com.vaadin.data.fieldgroup.BeanFieldGroup;\r
- import com.vaadin.data.fieldgroup.FieldGroup.CommitException;\r
- import com.vaadin.tests.components.TestBase;\r
- import com.vaadin.tests.util.Log;\r
- import com.vaadin.ui.Button;\r
- import com.vaadin.ui.Button.ClickEvent;\r
- import com.vaadin.ui.Button.ClickListener;\r
- import com.vaadin.ui.Root;\r
- \r
- public abstract class AbstractBeanFieldGroupTest extends TestBase {\r
- \r
- private Button commitButton;\r
- protected Log log = new Log(5);\r
- \r
- private Button discardButton;\r
- private Button showBeanButton;\r
- private BeanFieldGroup fieldBinder;\r
- \r
- @Override\r
- protected void setup() {\r
- addComponent(log);\r
- }\r
- \r
- protected Button getDiscardButton() {\r
- if (discardButton == null) {\r
- discardButton = new Button("Discard", new Button.ClickListener() {\r
- \r
- public void buttonClick(ClickEvent event) {\r
- getFieldBinder().discard();\r
- log.log("Discarded changes");\r
- \r
- }\r
- });\r
- }\r
- return discardButton;\r
- }\r
- \r
- protected Button getShowBeanButton() {\r
- if (showBeanButton == null) {\r
- showBeanButton = new Button("Show bean values",\r
- new Button.ClickListener() {\r
- \r
- public void buttonClick(ClickEvent event) {\r
- log.log(getFieldBinder().getItemDataSource()\r
- .getBean().toString());\r
- \r
- }\r
- });\r
- }\r
- return showBeanButton;\r
- }\r
- \r
- protected Button getCommitButton() {\r
- if (commitButton == null) {\r
- commitButton = new Button("Commit");\r
- commitButton.addListener(new ClickListener() {\r
- \r
- public void buttonClick(ClickEvent event) {\r
- String msg = "Commit succesful";\r
- try {\r
- getFieldBinder().commit();\r
- } catch (CommitException e) {\r
- msg = "Commit failed: " + e.getMessage();\r
- }\r
- Root.getCurrentRoot().showNotification(msg);\r
- log.log(msg);\r
- \r
- }\r
- });\r
- }\r
- return commitButton;\r
- }\r
- \r
- protected BeanFieldGroup getFieldBinder() {\r
- return fieldBinder;\r
- }\r
- \r
- protected void setFieldBinder(BeanFieldGroup beanFieldBinder) {\r
- fieldBinder = beanFieldBinder;\r
- }\r
- \r
- @Override\r
- protected String getDescription() {\r
- // TODO Auto-generated method stub\r
- return null;\r
- }\r
- \r
- @Override\r
- protected Integer getTicketNumber() {\r
- // TODO Auto-generated method stub\r
- return null;\r
- }\r
- \r
- }\r
++package com.vaadin.tests.fieldgroup;
++
++import com.vaadin.data.fieldgroup.BeanFieldGroup;
++import com.vaadin.data.fieldgroup.FieldGroup.CommitException;
++import com.vaadin.tests.components.TestBase;
++import com.vaadin.tests.util.Log;
++import com.vaadin.ui.Button;
++import com.vaadin.ui.Button.ClickEvent;
++import com.vaadin.ui.Button.ClickListener;
++import com.vaadin.ui.Root;
++
++public abstract class AbstractBeanFieldGroupTest extends TestBase {
++
++ private Button commitButton;
++ protected Log log = new Log(5);
++
++ private Button discardButton;
++ private Button showBeanButton;
++ private BeanFieldGroup fieldBinder;
++
++ @Override
++ protected void setup() {
++ addComponent(log);
++ }
++
++ protected Button getDiscardButton() {
++ if (discardButton == null) {
++ discardButton = new Button("Discard", new Button.ClickListener() {
++
++ public void buttonClick(ClickEvent event) {
++ getFieldBinder().discard();
++ log.log("Discarded changes");
++
++ }
++ });
++ }
++ return discardButton;
++ }
++
++ protected Button getShowBeanButton() {
++ if (showBeanButton == null) {
++ showBeanButton = new Button("Show bean values",
++ new Button.ClickListener() {
++
++ public void buttonClick(ClickEvent event) {
++ log.log(getFieldBinder().getItemDataSource()
++ .getBean().toString());
++
++ }
++ });
++ }
++ return showBeanButton;
++ }
++
++ protected Button getCommitButton() {
++ if (commitButton == null) {
++ commitButton = new Button("Commit");
++ commitButton.addListener(new ClickListener() {
++
++ public void buttonClick(ClickEvent event) {
++ String msg = "Commit succesful";
++ try {
++ getFieldBinder().commit();
++ } catch (CommitException e) {
++ msg = "Commit failed: " + e.getMessage();
++ }
++ Root.getCurrentRoot().showNotification(msg);
++ log.log(msg);
++
++ }
++ });
++ }
++ return commitButton;
++ }
++
++ protected BeanFieldGroup getFieldBinder() {
++ return fieldBinder;
++ }
++
++ protected void setFieldBinder(BeanFieldGroup beanFieldBinder) {
++ fieldBinder = beanFieldBinder;
++ }
++
++ @Override
++ protected String getDescription() {
++ // TODO Auto-generated method stub
++ return null;
++ }
++
++ @Override
++ protected Integer getTicketNumber() {
++ // TODO Auto-generated method stub
++ return null;
++ }
++
++}
--- /dev/null
- package com.vaadin.tests.fieldgroup;\r
- \r
- import com.vaadin.data.fieldgroup.BeanFieldGroup;\r
- import com.vaadin.data.fieldgroup.FieldGroup;\r
- import com.vaadin.data.fieldgroup.FieldGroup.CommitEvent;\r
- import com.vaadin.data.fieldgroup.FieldGroup.CommitException;\r
- import com.vaadin.data.fieldgroup.FieldGroup.CommitHandler;\r
- import com.vaadin.data.util.BeanItem;\r
- import com.vaadin.data.util.converter.StringToBooleanConverter;\r
- import com.vaadin.data.validator.EmailValidator;\r
- import com.vaadin.data.validator.IntegerRangeValidator;\r
- import com.vaadin.data.validator.StringLengthValidator;\r
- import com.vaadin.tests.components.TestBase;\r
- import com.vaadin.tests.data.bean.Address;\r
- import com.vaadin.tests.data.bean.Country;\r
- import com.vaadin.tests.data.bean.Person;\r
- import com.vaadin.tests.data.bean.Sex;\r
- import com.vaadin.tests.util.Log;\r
- import com.vaadin.ui.Button;\r
- import com.vaadin.ui.Button.ClickEvent;\r
- import com.vaadin.ui.Panel;\r
- import com.vaadin.ui.Root;\r
- import com.vaadin.ui.Table;\r
- import com.vaadin.ui.TextArea;\r
- import com.vaadin.ui.TextField;\r
- \r
- public class BasicPersonForm extends TestBase {\r
- \r
- private Log log = new Log(5);\r
- private TextField firstName;\r
- private TextArea lastName;\r
- private TextField email;\r
- private TextField age;\r
- private Table sex;\r
- private TextField deceased;\r
- \r
- public class Configuration {\r
- public boolean preCommitFails = false;\r
- public boolean postCommitFails = false;\r
- \r
- public boolean isPreCommitFails() {\r
- return preCommitFails;\r
- }\r
- \r
- public void setPreCommitFails(boolean preCommitFails) {\r
- this.preCommitFails = preCommitFails;\r
- }\r
- \r
- public boolean isPostCommitFails() {\r
- return postCommitFails;\r
- }\r
- \r
- public void setPostCommitFails(boolean postCommitFails) {\r
- this.postCommitFails = postCommitFails;\r
- }\r
- \r
- }\r
- \r
- private Configuration configuration = new Configuration();\r
- \r
- private class ConfigurationPanel extends Panel {\r
- \r
- public ConfigurationPanel() {\r
- super("Configuration");\r
- BeanItem<Configuration> bi = new BeanItem<BasicPersonForm.Configuration>(\r
- configuration);\r
- FieldGroup confFieldGroup = new FieldGroup(bi);\r
- confFieldGroup.setItemDataSource(bi);\r
- confFieldGroup.setBuffered(false);\r
- \r
- for (Object propertyId : bi.getItemPropertyIds()) {\r
- addComponent(confFieldGroup.buildAndBind(propertyId));\r
- }\r
- \r
- }\r
- }\r
- \r
- @Override\r
- protected void setup() {\r
- addComponent(log);\r
- Panel confPanel = new ConfigurationPanel();\r
- addComponent(confPanel);\r
- \r
- final FieldGroup fieldGroup = new BeanFieldGroup<Person>(Person.class);\r
- fieldGroup.addCommitHandler(new CommitHandler() {\r
- \r
- public void preCommit(CommitEvent commitEvent)\r
- throws CommitException {\r
- if (configuration.preCommitFails) {\r
- throw new CommitException(\r
- "Error in preCommit because first name is "\r
- + getPerson(commitEvent.getFieldBinder())\r
- .getFirstName());\r
- }\r
- \r
- }\r
- \r
- public void postCommit(CommitEvent commitEvent)\r
- throws CommitException {\r
- if (configuration.postCommitFails) {\r
- throw new CommitException(\r
- "Error in postCommit because first name is "\r
- + getPerson(commitEvent.getFieldBinder())\r
- .getFirstName());\r
- }\r
- }\r
- });\r
- \r
- fieldGroup.setBuffered(true);\r
- \r
- fieldGroup.buildAndBindMemberFields(this);\r
- addComponent(firstName);\r
- addComponent(lastName);\r
- addComponent(email);\r
- addComponent(age);\r
- addComponent(sex);\r
- addComponent(deceased);\r
- \r
- Button commitButton = new Button("Commit", new Button.ClickListener() {\r
- \r
- public void buttonClick(ClickEvent event) {\r
- String msg = "Commit succesful";\r
- try {\r
- fieldGroup.commit();\r
- } catch (CommitException e) {\r
- msg = "Commit failed: " + e.getMessage();\r
- }\r
- Root.getCurrentRoot().showNotification(msg);\r
- log.log(msg);\r
- \r
- }\r
- });\r
- Button discardButton = new Button("Discard",\r
- new Button.ClickListener() {\r
- \r
- public void buttonClick(ClickEvent event) {\r
- fieldGroup.discard();\r
- log.log("Discarded changes");\r
- \r
- }\r
- });\r
- Button showBean = new Button("Show bean values",\r
- new Button.ClickListener() {\r
- \r
- public void buttonClick(ClickEvent event) {\r
- log.log(getPerson(fieldGroup).toString());\r
- \r
- }\r
- });\r
- addComponent(commitButton);\r
- addComponent(discardButton);\r
- addComponent(showBean);\r
- email.addValidator(new EmailValidator("Must be a valid address"));\r
- lastName.addValidator(new StringLengthValidator("Must be min 5 chars",\r
- 5, null, true));\r
- \r
- age.addValidator(new IntegerRangeValidator(\r
- "Must be between 0 and 150, {0} is not", 0, 150));\r
- sex.setPageLength(0);\r
- deceased.setConverter(new StringToBooleanConverter() {\r
- @Override\r
- protected String getTrueString() {\r
- return "YAY!";\r
- }\r
- \r
- @Override\r
- protected String getFalseString() {\r
- return "NAAAAAH";\r
- }\r
- });\r
- Person p = new Person("John", "Doe", "john@doe.com", 64, Sex.MALE,\r
- new Address("John street", 11223, "John's town", Country.USA));\r
- fieldGroup.setItemDataSource(new BeanItem<Person>(p));\r
- }\r
- \r
- public static Person getPerson(FieldGroup binder) {\r
- return ((BeanItem<Person>) binder.getItemDataSource()).getBean();\r
- }\r
- \r
- @Override\r
- protected String getDescription() {\r
- // TODO Auto-generated method stub\r
- return null;\r
- }\r
- \r
- @Override\r
- protected Integer getTicketNumber() {\r
- // TODO Auto-generated method stub\r
- return null;\r
- }\r
- \r
- }\r
++package com.vaadin.tests.fieldgroup;
++
++import com.vaadin.data.fieldgroup.BeanFieldGroup;
++import com.vaadin.data.fieldgroup.FieldGroup;
++import com.vaadin.data.fieldgroup.FieldGroup.CommitEvent;
++import com.vaadin.data.fieldgroup.FieldGroup.CommitException;
++import com.vaadin.data.fieldgroup.FieldGroup.CommitHandler;
++import com.vaadin.data.util.BeanItem;
++import com.vaadin.data.util.converter.StringToBooleanConverter;
++import com.vaadin.data.validator.EmailValidator;
++import com.vaadin.data.validator.IntegerRangeValidator;
++import com.vaadin.data.validator.StringLengthValidator;
++import com.vaadin.tests.components.TestBase;
++import com.vaadin.tests.data.bean.Address;
++import com.vaadin.tests.data.bean.Country;
++import com.vaadin.tests.data.bean.Person;
++import com.vaadin.tests.data.bean.Sex;
++import com.vaadin.tests.util.Log;
++import com.vaadin.ui.Button;
++import com.vaadin.ui.Button.ClickEvent;
++import com.vaadin.ui.Panel;
++import com.vaadin.ui.Root;
++import com.vaadin.ui.Table;
++import com.vaadin.ui.TextArea;
++import com.vaadin.ui.TextField;
++
++public class BasicPersonForm extends TestBase {
++
++ private Log log = new Log(5);
++ private TextField firstName;
++ private TextArea lastName;
++ private TextField email;
++ private TextField age;
++ private Table sex;
++ private TextField deceased;
++
++ public class Configuration {
++ public boolean preCommitFails = false;
++ public boolean postCommitFails = false;
++
++ public boolean isPreCommitFails() {
++ return preCommitFails;
++ }
++
++ public void setPreCommitFails(boolean preCommitFails) {
++ this.preCommitFails = preCommitFails;
++ }
++
++ public boolean isPostCommitFails() {
++ return postCommitFails;
++ }
++
++ public void setPostCommitFails(boolean postCommitFails) {
++ this.postCommitFails = postCommitFails;
++ }
++
++ }
++
++ private Configuration configuration = new Configuration();
++
++ private class ConfigurationPanel extends Panel {
++
++ public ConfigurationPanel() {
++ super("Configuration");
++ BeanItem<Configuration> bi = new BeanItem<BasicPersonForm.Configuration>(
++ configuration);
++ FieldGroup confFieldGroup = new FieldGroup(bi);
++ confFieldGroup.setItemDataSource(bi);
++ confFieldGroup.setBuffered(false);
++
++ for (Object propertyId : bi.getItemPropertyIds()) {
++ addComponent(confFieldGroup.buildAndBind(propertyId));
++ }
++
++ }
++ }
++
++ @Override
++ protected void setup() {
++ addComponent(log);
++ Panel confPanel = new ConfigurationPanel();
++ addComponent(confPanel);
++
++ final FieldGroup fieldGroup = new BeanFieldGroup<Person>(Person.class);
++ fieldGroup.addCommitHandler(new CommitHandler() {
++
++ public void preCommit(CommitEvent commitEvent)
++ throws CommitException {
++ if (configuration.preCommitFails) {
++ throw new CommitException(
++ "Error in preCommit because first name is "
++ + getPerson(commitEvent.getFieldBinder())
++ .getFirstName());
++ }
++
++ }
++
++ public void postCommit(CommitEvent commitEvent)
++ throws CommitException {
++ if (configuration.postCommitFails) {
++ throw new CommitException(
++ "Error in postCommit because first name is "
++ + getPerson(commitEvent.getFieldBinder())
++ .getFirstName());
++ }
++ }
++ });
++
++ fieldGroup.setBuffered(true);
++
++ fieldGroup.buildAndBindMemberFields(this);
++ addComponent(firstName);
++ addComponent(lastName);
++ addComponent(email);
++ addComponent(age);
++ addComponent(sex);
++ addComponent(deceased);
++
++ Button commitButton = new Button("Commit", new Button.ClickListener() {
++
++ public void buttonClick(ClickEvent event) {
++ String msg = "Commit succesful";
++ try {
++ fieldGroup.commit();
++ } catch (CommitException e) {
++ msg = "Commit failed: " + e.getMessage();
++ }
++ Root.getCurrentRoot().showNotification(msg);
++ log.log(msg);
++
++ }
++ });
++ Button discardButton = new Button("Discard",
++ new Button.ClickListener() {
++
++ public void buttonClick(ClickEvent event) {
++ fieldGroup.discard();
++ log.log("Discarded changes");
++
++ }
++ });
++ Button showBean = new Button("Show bean values",
++ new Button.ClickListener() {
++
++ public void buttonClick(ClickEvent event) {
++ log.log(getPerson(fieldGroup).toString());
++
++ }
++ });
++ addComponent(commitButton);
++ addComponent(discardButton);
++ addComponent(showBean);
++ email.addValidator(new EmailValidator("Must be a valid address"));
++ lastName.addValidator(new StringLengthValidator("Must be min 5 chars",
++ 5, null, true));
++
++ age.addValidator(new IntegerRangeValidator(
++ "Must be between 0 and 150, {0} is not", 0, 150));
++ sex.setPageLength(0);
++ deceased.setConverter(new StringToBooleanConverter() {
++ @Override
++ protected String getTrueString() {
++ return "YAY!";
++ }
++
++ @Override
++ protected String getFalseString() {
++ return "NAAAAAH";
++ }
++ });
++ Person p = new Person("John", "Doe", "john@doe.com", 64, Sex.MALE,
++ new Address("John street", 11223, "John's town", Country.USA));
++ fieldGroup.setItemDataSource(new BeanItem<Person>(p));
++ }
++
++ public static Person getPerson(FieldGroup binder) {
++ return ((BeanItem<Person>) binder.getItemDataSource()).getBean();
++ }
++
++ @Override
++ protected String getDescription() {
++ // TODO Auto-generated method stub
++ return null;
++ }
++
++ @Override
++ protected Integer getTicketNumber() {
++ // TODO Auto-generated method stub
++ return null;
++ }
++
++}
--- /dev/null
- package com.vaadin.tests.fieldgroup;\r
- \r
- import com.vaadin.data.fieldgroup.BeanFieldGroup;\r
- import com.vaadin.data.fieldgroup.FieldGroup;\r
- import com.vaadin.data.fieldgroup.FieldGroup.CommitException;\r
- import com.vaadin.data.util.BeanItem;\r
- import com.vaadin.tests.components.TestBase;\r
- import com.vaadin.tests.data.bean.Address;\r
- import com.vaadin.tests.data.bean.Country;\r
- import com.vaadin.tests.data.bean.Person;\r
- import com.vaadin.tests.data.bean.PersonWithBeanValidationAnnotations;\r
- import com.vaadin.tests.data.bean.Sex;\r
- import com.vaadin.tests.util.Log;\r
- import com.vaadin.ui.Button;\r
- import com.vaadin.ui.Button.ClickEvent;\r
- import com.vaadin.ui.Root;\r
- import com.vaadin.ui.Table;\r
- import com.vaadin.ui.TextArea;\r
- import com.vaadin.ui.TextField;\r
- \r
- public class FieldBinderWithBeanValidation extends TestBase {\r
- \r
- private Log log = new Log(5);\r
- private TextField firstName;\r
- private TextArea lastName;\r
- private TextField email;\r
- private TextField age;\r
- private Table sex;\r
- private TextField deceased;\r
- \r
- @Override\r
- protected void setup() {\r
- addComponent(log);\r
- \r
- final BeanFieldGroup<PersonWithBeanValidationAnnotations> fieldGroup = new BeanFieldGroup<PersonWithBeanValidationAnnotations>(\r
- PersonWithBeanValidationAnnotations.class);\r
- \r
- fieldGroup.buildAndBindMemberFields(this);\r
- addComponent(firstName);\r
- addComponent(lastName);\r
- addComponent(email);\r
- addComponent(age);\r
- addComponent(sex);\r
- addComponent(deceased);\r
- \r
- Button commitButton = new Button("Commit", new Button.ClickListener() {\r
- \r
- public void buttonClick(ClickEvent event) {\r
- String msg = "Commit succesful";\r
- try {\r
- fieldGroup.commit();\r
- } catch (CommitException e) {\r
- msg = "Commit failed: " + e.getMessage();\r
- }\r
- Root.getCurrentRoot().showNotification(msg);\r
- log.log(msg);\r
- \r
- }\r
- });\r
- Button discardButton = new Button("Discard",\r
- new Button.ClickListener() {\r
- \r
- public void buttonClick(ClickEvent event) {\r
- fieldGroup.discard();\r
- log.log("Discarded changes");\r
- \r
- }\r
- });\r
- Button showBean = new Button("Show bean values",\r
- new Button.ClickListener() {\r
- \r
- public void buttonClick(ClickEvent event) {\r
- log.log(getPerson(fieldGroup).toString());\r
- \r
- }\r
- });\r
- addComponent(commitButton);\r
- addComponent(discardButton);\r
- addComponent(showBean);\r
- sex.setPageLength(0);\r
- \r
- PersonWithBeanValidationAnnotations p = new PersonWithBeanValidationAnnotations(\r
- "John", "Doe", "john@doe.com", 64, Sex.MALE, new Address(\r
- "John street", 11223, "John's town", Country.USA));\r
- fieldGroup\r
- .setItemDataSource(new BeanItem<PersonWithBeanValidationAnnotations>(\r
- p));\r
- }\r
- \r
- public static Person getPerson(FieldGroup binder) {\r
- return ((BeanItem<Person>) binder.getItemDataSource()).getBean();\r
- }\r
- \r
- @Override\r
- protected String getDescription() {\r
- // TODO Auto-generated method stub\r
- return null;\r
- }\r
- \r
- @Override\r
- protected Integer getTicketNumber() {\r
- // TODO Auto-generated method stub\r
- return null;\r
- }\r
- \r
- }\r
++package com.vaadin.tests.fieldgroup;
++
++import com.vaadin.data.fieldgroup.BeanFieldGroup;
++import com.vaadin.data.fieldgroup.FieldGroup;
++import com.vaadin.data.fieldgroup.FieldGroup.CommitException;
++import com.vaadin.data.util.BeanItem;
++import com.vaadin.tests.components.TestBase;
++import com.vaadin.tests.data.bean.Address;
++import com.vaadin.tests.data.bean.Country;
++import com.vaadin.tests.data.bean.Person;
++import com.vaadin.tests.data.bean.PersonWithBeanValidationAnnotations;
++import com.vaadin.tests.data.bean.Sex;
++import com.vaadin.tests.util.Log;
++import com.vaadin.ui.Button;
++import com.vaadin.ui.Button.ClickEvent;
++import com.vaadin.ui.Root;
++import com.vaadin.ui.Table;
++import com.vaadin.ui.TextArea;
++import com.vaadin.ui.TextField;
++
++public class FieldBinderWithBeanValidation extends TestBase {
++
++ private Log log = new Log(5);
++ private TextField firstName;
++ private TextArea lastName;
++ private TextField email;
++ private TextField age;
++ private Table sex;
++ private TextField deceased;
++
++ @Override
++ protected void setup() {
++ addComponent(log);
++
++ final BeanFieldGroup<PersonWithBeanValidationAnnotations> fieldGroup = new BeanFieldGroup<PersonWithBeanValidationAnnotations>(
++ PersonWithBeanValidationAnnotations.class);
++
++ fieldGroup.buildAndBindMemberFields(this);
++ addComponent(firstName);
++ addComponent(lastName);
++ addComponent(email);
++ addComponent(age);
++ addComponent(sex);
++ addComponent(deceased);
++
++ Button commitButton = new Button("Commit", new Button.ClickListener() {
++
++ public void buttonClick(ClickEvent event) {
++ String msg = "Commit succesful";
++ try {
++ fieldGroup.commit();
++ } catch (CommitException e) {
++ msg = "Commit failed: " + e.getMessage();
++ }
++ Root.getCurrentRoot().showNotification(msg);
++ log.log(msg);
++
++ }
++ });
++ Button discardButton = new Button("Discard",
++ new Button.ClickListener() {
++
++ public void buttonClick(ClickEvent event) {
++ fieldGroup.discard();
++ log.log("Discarded changes");
++
++ }
++ });
++ Button showBean = new Button("Show bean values",
++ new Button.ClickListener() {
++
++ public void buttonClick(ClickEvent event) {
++ log.log(getPerson(fieldGroup).toString());
++
++ }
++ });
++ addComponent(commitButton);
++ addComponent(discardButton);
++ addComponent(showBean);
++ sex.setPageLength(0);
++
++ PersonWithBeanValidationAnnotations p = new PersonWithBeanValidationAnnotations(
++ "John", "Doe", "john@doe.com", 64, Sex.MALE, new Address(
++ "John street", 11223, "John's town", Country.USA));
++ fieldGroup
++ .setItemDataSource(new BeanItem<PersonWithBeanValidationAnnotations>(
++ p));
++ }
++
++ public static Person getPerson(FieldGroup binder) {
++ return ((BeanItem<Person>) binder.getItemDataSource()).getBean();
++ }
++
++ @Override
++ protected String getDescription() {
++ // TODO Auto-generated method stub
++ return null;
++ }
++
++ @Override
++ protected Integer getTicketNumber() {
++ // TODO Auto-generated method stub
++ return null;
++ }
++
++}
--- /dev/null
- package com.vaadin.tests.fieldgroup;\r
- \r
- import com.vaadin.data.fieldgroup.BeanFieldGroup;\r
- import com.vaadin.data.fieldgroup.FieldGroup;\r
- import com.vaadin.data.fieldgroup.PropertyId;\r
- import com.vaadin.data.util.BeanItem;\r
- import com.vaadin.tests.components.TestBase;\r
- import com.vaadin.tests.data.bean.Address;\r
- import com.vaadin.tests.data.bean.Country;\r
- import com.vaadin.tests.data.bean.Person;\r
- import com.vaadin.tests.data.bean.Sex;\r
- import com.vaadin.ui.TextField;\r
- \r
- public class FormBuilderWithNestedProperties extends TestBase {\r
- \r
- private TextField firstName;\r
- private TextField lastName;\r
- @PropertyId("address.streetAddress")\r
- private TextField streetAddress;\r
- \r
- @Override\r
- protected void setup() {\r
- FieldGroup fieldGroup = new BeanFieldGroup<Person>(Person.class);\r
- fieldGroup.buildAndBindMemberFields(this);\r
- \r
- addComponent(firstName);\r
- addComponent(lastName);\r
- addComponent(streetAddress);\r
- \r
- fieldGroup.setItemDataSource(new BeanItem<Person>(new Person("Who",\r
- "me?", "email", 1, Sex.MALE, new Address("street name", 202020,\r
- "City", Country.FINLAND))));\r
- }\r
- \r
- @Override\r
- protected String getDescription() {\r
- // TODO Auto-generated method stub\r
- return null;\r
- }\r
- \r
- @Override\r
- protected Integer getTicketNumber() {\r
- // TODO Auto-generated method stub\r
- return null;\r
- }\r
- \r
- }\r
++package com.vaadin.tests.fieldgroup;
++
++import com.vaadin.data.fieldgroup.BeanFieldGroup;
++import com.vaadin.data.fieldgroup.FieldGroup;
++import com.vaadin.data.fieldgroup.PropertyId;
++import com.vaadin.data.util.BeanItem;
++import com.vaadin.tests.components.TestBase;
++import com.vaadin.tests.data.bean.Address;
++import com.vaadin.tests.data.bean.Country;
++import com.vaadin.tests.data.bean.Person;
++import com.vaadin.tests.data.bean.Sex;
++import com.vaadin.ui.TextField;
++
++public class FormBuilderWithNestedProperties extends TestBase {
++
++ private TextField firstName;
++ private TextField lastName;
++ @PropertyId("address.streetAddress")
++ private TextField streetAddress;
++
++ @Override
++ protected void setup() {
++ FieldGroup fieldGroup = new BeanFieldGroup<Person>(Person.class);
++ fieldGroup.buildAndBindMemberFields(this);
++
++ addComponent(firstName);
++ addComponent(lastName);
++ addComponent(streetAddress);
++
++ fieldGroup.setItemDataSource(new BeanItem<Person>(new Person("Who",
++ "me?", "email", 1, Sex.MALE, new Address("street name", 202020,
++ "City", Country.FINLAND))));
++ }
++
++ @Override
++ protected String getDescription() {
++ // TODO Auto-generated method stub
++ return null;
++ }
++
++ @Override
++ protected Integer getTicketNumber() {
++ // TODO Auto-generated method stub
++ return null;
++ }
++
++}
--- /dev/null
- package com.vaadin.tests.fieldgroup;\r
- \r
- import com.vaadin.data.fieldgroup.BeanFieldGroup;\r
- import com.vaadin.data.fieldgroup.PropertyId;\r
- import com.vaadin.tests.data.bean.Address;\r
- import com.vaadin.tests.data.bean.Country;\r
- import com.vaadin.tests.data.bean.Person;\r
- import com.vaadin.tests.data.bean.Sex;\r
- import com.vaadin.tests.util.Log;\r
- import com.vaadin.ui.CheckBox;\r
- import com.vaadin.ui.NativeSelect;\r
- import com.vaadin.ui.TextField;\r
- \r
- public class FormWithNestedProperties extends AbstractBeanFieldGroupTest {\r
- \r
- private Log log = new Log(5);\r
- \r
- private TextField firstName = new TextField("First name");\r
- private TextField lastName = new TextField("Last name");\r
- private TextField email = new TextField("Email");\r
- private TextField age = new TextField("Age");\r
- \r
- @PropertyId("address.streetAddress")\r
- private TextField streetAddress = new TextField("Street address");\r
- private NativeSelect country;\r
- \r
- private CheckBox deceased = new CheckBox("Deceased");\r
- \r
- @Override\r
- protected void setup() {\r
- super.setup();\r
- \r
- setFieldBinder(new BeanFieldGroup<Person>(Person.class));\r
- country = getFieldBinder().buildAndBind("country", "address.country",\r
- NativeSelect.class);\r
- getFieldBinder().bindMemberFields(this);\r
- addComponent(firstName);\r
- addComponent(lastName);\r
- addComponent(streetAddress);\r
- addComponent(country);\r
- addComponent(email);\r
- addComponent(age);\r
- addComponent(deceased);\r
- addComponent(getCommitButton());\r
- addComponent(getDiscardButton());\r
- addComponent(getShowBeanButton());\r
- \r
- getFieldBinder().setItemDataSource(\r
- new Person("First", "Last", "Email", 52, Sex.FEMALE,\r
- new Address("street address", 01234, "City",\r
- Country.FINLAND)));\r
- \r
- }\r
- \r
- @Override\r
- protected String getDescription() {\r
- // TODO Auto-generated method stub\r
- return null;\r
- }\r
- \r
- @Override\r
- protected Integer getTicketNumber() {\r
- // TODO Auto-generated method stub\r
- return null;\r
- }\r
- \r
- }\r
++package com.vaadin.tests.fieldgroup;
++
++import com.vaadin.data.fieldgroup.BeanFieldGroup;
++import com.vaadin.data.fieldgroup.PropertyId;
++import com.vaadin.tests.data.bean.Address;
++import com.vaadin.tests.data.bean.Country;
++import com.vaadin.tests.data.bean.Person;
++import com.vaadin.tests.data.bean.Sex;
++import com.vaadin.tests.util.Log;
++import com.vaadin.ui.CheckBox;
++import com.vaadin.ui.NativeSelect;
++import com.vaadin.ui.TextField;
++
++public class FormWithNestedProperties extends AbstractBeanFieldGroupTest {
++
++ private Log log = new Log(5);
++
++ private TextField firstName = new TextField("First name");
++ private TextField lastName = new TextField("Last name");
++ private TextField email = new TextField("Email");
++ private TextField age = new TextField("Age");
++
++ @PropertyId("address.streetAddress")
++ private TextField streetAddress = new TextField("Street address");
++ private NativeSelect country;
++
++ private CheckBox deceased = new CheckBox("Deceased");
++
++ @Override
++ protected void setup() {
++ super.setup();
++
++ setFieldBinder(new BeanFieldGroup<Person>(Person.class));
++ country = getFieldBinder().buildAndBind("country", "address.country",
++ NativeSelect.class);
++ getFieldBinder().bindMemberFields(this);
++ addComponent(firstName);
++ addComponent(lastName);
++ addComponent(streetAddress);
++ addComponent(country);
++ addComponent(email);
++ addComponent(age);
++ addComponent(deceased);
++ addComponent(getCommitButton());
++ addComponent(getDiscardButton());
++ addComponent(getShowBeanButton());
++
++ getFieldBinder().setItemDataSource(
++ new Person("First", "Last", "Email", 52, Sex.FEMALE,
++ new Address("street address", 01234, "City",
++ Country.FINLAND)));
++
++ }
++
++ @Override
++ protected String getDescription() {
++ // TODO Auto-generated method stub
++ return null;
++ }
++
++ @Override
++ protected Integer getTicketNumber() {
++ // TODO Auto-generated method stub
++ return null;
++ }
++
++}
- package com.vaadin.tests.layouts;\r
- \r
- import java.util.ArrayList;\r
- import java.util.List;\r
- \r
- import com.vaadin.data.Item;\r
- import com.vaadin.data.Property.ValueChangeEvent;\r
- import com.vaadin.data.Property.ValueChangeListener;\r
- import com.vaadin.terminal.ThemeResource;\r
- import com.vaadin.terminal.UserError;\r
- import com.vaadin.tests.components.TestBase;\r
- import com.vaadin.ui.AbstractField;\r
- import com.vaadin.ui.Button;\r
- import com.vaadin.ui.Button.ClickEvent;\r
- import com.vaadin.ui.Button.ClickListener;\r
- import com.vaadin.ui.CheckBox;\r
- import com.vaadin.ui.Component;\r
- import com.vaadin.ui.CssLayout;\r
- import com.vaadin.ui.FormLayout;\r
- import com.vaadin.ui.GridLayout;\r
- import com.vaadin.ui.HorizontalLayout;\r
- import com.vaadin.ui.Layout;\r
- import com.vaadin.ui.NativeButton;\r
- import com.vaadin.ui.NativeSelect;\r
- import com.vaadin.ui.TextField;\r
- import com.vaadin.ui.VerticalLayout;\r
- \r
- public class CaptionsInLayouts extends TestBase {\r
- \r
- private static final Object CAPTION = "CAPTION";\r
- private static final Object CLASS = "C";\r
- private static final Object WIDTH = "W";\r
- \r
- private NativeSelect layoutSelect;\r
- private Layout layout;\r
- private VerticalLayout verticalLayout;\r
- private HorizontalLayout horizontalLayout;\r
- private GridLayout gridLayout;\r
- private FormLayout formLayout;\r
- private List<AbstractField<?>> components = new ArrayList<AbstractField<?>>();\r
- private CssLayout cssLayout;\r
- private HorizontalLayout layoutParent = new HorizontalLayout();\r
- \r
- @Override\r
- protected void setup() {\r
- // setTheme("tests-tickets");\r
- addComponent(createLayoutSelect());\r
- addComponent(toggleRequired());\r
- // addComponent(toggleCaptions());\r
- addComponent(toggleError());\r
- addComponent(toggleIcon());\r
- addComponent(addCaptionText());\r
- layoutParent.addComponent(new NativeButton("Button right of layout"));\r
- addComponent(layoutParent);\r
- addComponent(new NativeButton("Button below layout"));\r
- createComponents();\r
- layoutSelect.setValue(layoutSelect.getItemIds().iterator().next());\r
- }\r
- \r
- private Component addCaptionText() {\r
- Button b = new Button("Add caption text");\r
- b.addListener(new ClickListener() {\r
- \r
- public void buttonClick(ClickEvent event) {\r
- prependCaptions("a");\r
- }\r
- });\r
- return b;\r
- }\r
- \r
- protected void prependCaptions(String prepend) {\r
- for (AbstractField<?> c : components) {\r
- c.setCaption(prepend + c.getCaption());\r
- }\r
- \r
- }\r
- \r
- private Component toggleRequired() {\r
- CheckBox requiredToggle = new CheckBox();\r
- requiredToggle.setImmediate(true);\r
- requiredToggle.setCaption("Required");\r
- requiredToggle.addListener(new ValueChangeListener() {\r
- \r
- public void valueChange(ValueChangeEvent event) {\r
- setRequired((Boolean) event.getProperty().getValue());\r
- }\r
- });\r
- return requiredToggle;\r
- }\r
- \r
- private Component toggleIcon() {\r
- CheckBox iconToggle = new CheckBox();\r
- iconToggle.setImmediate(true);\r
- iconToggle.setCaption("Icons");\r
- iconToggle.addListener(new ValueChangeListener() {\r
- \r
- public void valueChange(ValueChangeEvent event) {\r
- setIcon((Boolean) event.getProperty().getValue());\r
- }\r
- });\r
- return iconToggle;\r
- }\r
- \r
- protected void setRequired(boolean value) {\r
- for (AbstractField<?> c : components) {\r
- c.setRequired(value);\r
- }\r
- \r
- }\r
- \r
- protected void setIcon(boolean value) {\r
- for (AbstractField<?> c : components) {\r
- if (!value) {\r
- c.setIcon(null);\r
- } else {\r
- c.setIcon(new ThemeResource("../runo/icons/16/ok.png"));\r
- }\r
- }\r
- \r
- }\r
- \r
- private Component toggleError() {\r
- CheckBox errorToggle = new CheckBox();\r
- errorToggle.setImmediate(true);\r
- errorToggle.setCaption("Error");\r
- errorToggle.addListener(new ValueChangeListener() {\r
- \r
- public void valueChange(ValueChangeEvent event) {\r
- setError((Boolean) event.getProperty().getValue());\r
- }\r
- });\r
- return errorToggle;\r
- }\r
- \r
- protected void setError(boolean value) {\r
- for (AbstractField<?> c : components) {\r
- if (value) {\r
- c.setComponentError(new UserError("error"));\r
- } else {\r
- c.setComponentError(null);\r
- \r
- }\r
- }\r
- \r
- }\r
- \r
- private void createComponents() {\r
- TextField tfUndefWide = new TextField(\r
- "Undefined wide text field with a very long caption, longer than the field and the layout. Lorem ipsum dolor sit amet.");\r
- TextField tf100pxWide = new TextField(\r
- "100 px wide text field with a very long caption, longer than 100px.");\r
- tf100pxWide.setWidth("100px");\r
- \r
- TextField tf500pxWide = new TextField(\r
- "500 px wide text field with a very long caption, longer than 500px. Lorem ipsum dolor sit amet, consectetur adipiscing elit.");\r
- tf500pxWide.setWidth("500px");\r
- \r
- components.add(tfUndefWide);\r
- components.add(tf100pxWide);\r
- components.add(tf500pxWide);\r
- \r
- }\r
- \r
- private void setLayout(Layout newLayout) {\r
- if (layout == null) {\r
- layoutParent.addComponent(newLayout, 0);\r
- } else {\r
- layoutParent.replaceComponent(layout, newLayout);\r
- }\r
- layout = newLayout;\r
- \r
- for (Component c : components) {\r
- if (c.getParent() != layout) {\r
- layout.addComponent(c);\r
- }\r
- }\r
- \r
- }\r
- \r
- private Layout getLayout(String caption,\r
- Class<? extends Layout> layoutClass, String width) {\r
- Layout l;\r
- if (layoutClass == VerticalLayout.class) {\r
- if (verticalLayout == null) {\r
- verticalLayout = new VerticalLayout();\r
- verticalLayout.setStyleName("borders");\r
- }\r
- l = verticalLayout;\r
- } else if (layoutClass == HorizontalLayout.class) {\r
- if (horizontalLayout == null) {\r
- horizontalLayout = new HorizontalLayout();\r
- horizontalLayout.setStyleName("borders");\r
- }\r
- l = horizontalLayout;\r
- } else if (layoutClass == GridLayout.class) {\r
- if (gridLayout == null) {\r
- gridLayout = new GridLayout();\r
- gridLayout.setStyleName("borders");\r
- }\r
- l = gridLayout;\r
- } else if (layoutClass == CssLayout.class) {\r
- if (cssLayout == null) {\r
- cssLayout = new CssLayout();\r
- cssLayout.setStyleName("borders");\r
- }\r
- l = cssLayout;\r
- } else if (layoutClass == FormLayout.class) {\r
- if (formLayout == null) {\r
- formLayout = new FormLayout();\r
- formLayout.setStyleName("borders");\r
- }\r
- l = formLayout;\r
- } else {\r
- return null;\r
- }\r
- \r
- l.setCaption(caption);\r
- if (width.equals("auto")) {\r
- width = null;\r
- }\r
- \r
- l.setWidth(width);\r
- \r
- // addComponent(l);\r
- \r
- return l;\r
- }\r
- \r
- private Component createLayoutSelect() {\r
- layoutSelect = new NativeSelect("Layout");\r
- layoutSelect.addContainerProperty(CAPTION, String.class, "");\r
- layoutSelect.addContainerProperty(CLASS, Class.class, "");\r
- layoutSelect.addContainerProperty(WIDTH, String.class, "");\r
- layoutSelect.setItemCaptionPropertyId(CAPTION);\r
- layoutSelect.setNullSelectionAllowed(false);\r
- \r
- for (Class<?> cls : new Class[] { HorizontalLayout.class,\r
- VerticalLayout.class, GridLayout.class, CssLayout.class,\r
- FormLayout.class }) {\r
- for (String width : new String[] { "400px", "auto" }) {\r
- Object id = layoutSelect.addItem();\r
- Item i = layoutSelect.getItem(id);\r
- i.getItemProperty(CAPTION).setValue(\r
- cls.getSimpleName() + ", " + width);\r
- i.getItemProperty(CLASS).setValue(cls);\r
- i.getItemProperty(WIDTH).setValue(width);\r
- }\r
- \r
- }\r
- layoutSelect.setImmediate(true);\r
- layoutSelect.addListener(new ValueChangeListener() {\r
- \r
- @SuppressWarnings("unchecked")\r
- public void valueChange(ValueChangeEvent event) {\r
- Item i = layoutSelect.getItem(event.getProperty().getValue());\r
- \r
- setLayout(getLayout((String) i.getItemProperty(CAPTION)\r
- .getValue(), (Class<? extends Layout>) i\r
- .getItemProperty(CLASS).getValue(), (String) i\r
- .getItemProperty(WIDTH).getValue()));\r
- }\r
- });\r
- \r
- return layoutSelect;\r
- }\r
- \r
- @Override\r
- protected String getDescription() {\r
- return "Tests what happens when the caption changes in various layouts. Behavior should be consistent.";\r
- }\r
- \r
- @Override\r
- protected Integer getTicketNumber() {\r
- return 5424;\r
- }\r
- \r
- }\r
+ package com.vaadin.tests.layouts;
+
+ import java.util.ArrayList;
+ import java.util.List;
+
+ import com.vaadin.data.Item;
+ import com.vaadin.data.Property.ValueChangeEvent;
+ import com.vaadin.data.Property.ValueChangeListener;
+ import com.vaadin.terminal.ThemeResource;
+ import com.vaadin.terminal.UserError;
+ import com.vaadin.tests.components.TestBase;
+ import com.vaadin.ui.AbstractField;
+ import com.vaadin.ui.Button;
+ import com.vaadin.ui.Button.ClickEvent;
+ import com.vaadin.ui.Button.ClickListener;
+ import com.vaadin.ui.CheckBox;
+ import com.vaadin.ui.Component;
+ import com.vaadin.ui.CssLayout;
+ import com.vaadin.ui.FormLayout;
+ import com.vaadin.ui.GridLayout;
+ import com.vaadin.ui.HorizontalLayout;
+ import com.vaadin.ui.Layout;
+ import com.vaadin.ui.NativeButton;
+ import com.vaadin.ui.NativeSelect;
+ import com.vaadin.ui.TextField;
+ import com.vaadin.ui.VerticalLayout;
+
+ public class CaptionsInLayouts extends TestBase {
+
+ private static final Object CAPTION = "CAPTION";
+ private static final Object CLASS = "C";
+ private static final Object WIDTH = "W";
+
+ private NativeSelect layoutSelect;
+ private Layout layout;
+ private VerticalLayout verticalLayout;
+ private HorizontalLayout horizontalLayout;
+ private GridLayout gridLayout;
+ private FormLayout formLayout;
- private List<AbstractField> components = new ArrayList<AbstractField>();
++ private List<AbstractField<?>> components = new ArrayList<AbstractField<?>>();
+ private CssLayout cssLayout;
+ private HorizontalLayout layoutParent = new HorizontalLayout();
+
+ @Override
+ protected void setup() {
+ // setTheme("tests-tickets");
+ addComponent(createLayoutSelect());
+ addComponent(toggleRequired());
+ // addComponent(toggleCaptions());
+ addComponent(toggleError());
+ addComponent(toggleIcon());
+ addComponent(addCaptionText());
+ layoutParent.addComponent(new NativeButton("Button right of layout"));
+ addComponent(layoutParent);
+ addComponent(new NativeButton("Button below layout"));
+ createComponents();
+ layoutSelect.setValue(layoutSelect.getItemIds().iterator().next());
+ }
+
+ private Component addCaptionText() {
+ Button b = new Button("Add caption text");
+ b.addListener(new ClickListener() {
+
+ public void buttonClick(ClickEvent event) {
+ prependCaptions("a");
+ }
+ });
+ return b;
+ }
+
+ protected void prependCaptions(String prepend) {
- for (AbstractField c : components) {
++ for (AbstractField<?> c : components) {
+ c.setCaption(prepend + c.getCaption());
+ }
+
+ }
+
+ private Component toggleRequired() {
+ CheckBox requiredToggle = new CheckBox();
+ requiredToggle.setImmediate(true);
+ requiredToggle.setCaption("Required");
+ requiredToggle.addListener(new ValueChangeListener() {
+
+ public void valueChange(ValueChangeEvent event) {
+ setRequired((Boolean) event.getProperty().getValue());
+ }
+ });
+ return requiredToggle;
+ }
+
+ private Component toggleIcon() {
+ CheckBox iconToggle = new CheckBox();
+ iconToggle.setImmediate(true);
+ iconToggle.setCaption("Icons");
+ iconToggle.addListener(new ValueChangeListener() {
+
+ public void valueChange(ValueChangeEvent event) {
+ setIcon((Boolean) event.getProperty().getValue());
+ }
+ });
+ return iconToggle;
+ }
+
+ protected void setRequired(boolean value) {
- for (AbstractField c : components) {
++ for (AbstractField<?> c : components) {
+ c.setRequired(value);
+ }
+
+ }
+
+ protected void setIcon(boolean value) {
- for (AbstractField c : components) {
++ for (AbstractField<?> c : components) {
+ if (!value) {
+ c.setIcon(null);
+ } else {
+ c.setIcon(new ThemeResource("../runo/icons/16/ok.png"));
+ }
+ }
+
+ }
+
+ private Component toggleError() {
+ CheckBox errorToggle = new CheckBox();
+ errorToggle.setImmediate(true);
+ errorToggle.setCaption("Error");
+ errorToggle.addListener(new ValueChangeListener() {
+
+ public void valueChange(ValueChangeEvent event) {
+ setError((Boolean) event.getProperty().getValue());
+ }
+ });
+ return errorToggle;
+ }
+
+ protected void setError(boolean value) {
- for (AbstractField c : components) {
++ for (AbstractField<?> c : components) {
+ if (value) {
+ c.setComponentError(new UserError("error"));
+ } else {
+ c.setComponentError(null);
+
+ }
+ }
+
+ }
+
+ private void createComponents() {
+ TextField tfUndefWide = new TextField(
+ "Undefined wide text field with a very long caption, longer than the field and the layout. Lorem ipsum dolor sit amet.");
+ TextField tf100pxWide = new TextField(
+ "100 px wide text field with a very long caption, longer than 100px.");
+ tf100pxWide.setWidth("100px");
+
+ TextField tf500pxWide = new TextField(
+ "500 px wide text field with a very long caption, longer than 500px. Lorem ipsum dolor sit amet, consectetur adipiscing elit.");
+ tf500pxWide.setWidth("500px");
+
+ components.add(tfUndefWide);
+ components.add(tf100pxWide);
+ components.add(tf500pxWide);
+
+ }
+
+ private void setLayout(Layout newLayout) {
+ if (layout == null) {
+ layoutParent.addComponent(newLayout, 0);
+ } else {
+ layoutParent.replaceComponent(layout, newLayout);
+ }
+ layout = newLayout;
+
+ for (Component c : components) {
+ if (c.getParent() != layout) {
+ layout.addComponent(c);
+ }
+ }
+
+ }
+
+ private Layout getLayout(String caption,
+ Class<? extends Layout> layoutClass, String width) {
+ Layout l;
+ if (layoutClass == VerticalLayout.class) {
+ if (verticalLayout == null) {
+ verticalLayout = new VerticalLayout();
+ verticalLayout.setStyleName("borders");
+ }
+ l = verticalLayout;
+ } else if (layoutClass == HorizontalLayout.class) {
+ if (horizontalLayout == null) {
+ horizontalLayout = new HorizontalLayout();
+ horizontalLayout.setStyleName("borders");
+ }
+ l = horizontalLayout;
+ } else if (layoutClass == GridLayout.class) {
+ if (gridLayout == null) {
+ gridLayout = new GridLayout();
+ gridLayout.setStyleName("borders");
+ }
+ l = gridLayout;
+ } else if (layoutClass == CssLayout.class) {
+ if (cssLayout == null) {
+ cssLayout = new CssLayout();
+ cssLayout.setStyleName("borders");
+ }
+ l = cssLayout;
+ } else if (layoutClass == FormLayout.class) {
+ if (formLayout == null) {
+ formLayout = new FormLayout();
+ formLayout.setStyleName("borders");
+ }
+ l = formLayout;
+ } else {
+ return null;
+ }
+
+ l.setCaption(caption);
+ if (width.equals("auto")) {
+ width = null;
+ }
+
+ l.setWidth(width);
+
+ // addComponent(l);
+
+ return l;
+ }
+
+ private Component createLayoutSelect() {
+ layoutSelect = new NativeSelect("Layout");
+ layoutSelect.addContainerProperty(CAPTION, String.class, "");
+ layoutSelect.addContainerProperty(CLASS, Class.class, "");
+ layoutSelect.addContainerProperty(WIDTH, String.class, "");
+ layoutSelect.setItemCaptionPropertyId(CAPTION);
+ layoutSelect.setNullSelectionAllowed(false);
+
+ for (Class<?> cls : new Class[] { HorizontalLayout.class,
+ VerticalLayout.class, GridLayout.class, CssLayout.class,
+ FormLayout.class }) {
+ for (String width : new String[] { "400px", "auto" }) {
+ Object id = layoutSelect.addItem();
+ Item i = layoutSelect.getItem(id);
+ i.getItemProperty(CAPTION).setValue(
+ cls.getSimpleName() + ", " + width);
+ i.getItemProperty(CLASS).setValue(cls);
+ i.getItemProperty(WIDTH).setValue(width);
+ }
+
+ }
+ layoutSelect.setImmediate(true);
+ layoutSelect.addListener(new ValueChangeListener() {
+
+ @SuppressWarnings("unchecked")
+ public void valueChange(ValueChangeEvent event) {
+ Item i = layoutSelect.getItem(event.getProperty().getValue());
+
+ setLayout(getLayout((String) i.getItemProperty(CAPTION)
+ .getValue(), (Class<? extends Layout>) i
+ .getItemProperty(CLASS).getValue(), (String) i
+ .getItemProperty(WIDTH).getValue()));
+ }
+ });
+
+ return layoutSelect;
+ }
+
+ @Override
+ protected String getDescription() {
+ return "Tests what happens when the caption changes in various layouts. Behavior should be consistent.";
+ }
+
+ @Override
+ protected Integer getTicketNumber() {
+ return 5424;
+ }
+
+ }
- package com.vaadin.tests.layouts;\r
- \r
- import com.vaadin.tests.components.TestBase;\r
- import com.vaadin.ui.Button;\r
- import com.vaadin.ui.Button.ClickEvent;\r
- import com.vaadin.ui.HorizontalLayout;\r
- import com.vaadin.ui.Label;\r
- import com.vaadin.ui.Label.ContentMode;\r
- import com.vaadin.ui.VerticalLayout;\r
- \r
- public class HiddenHorizontalLayout extends TestBase {\r
- \r
- @Override\r
- protected String getDescription() {\r
- return "Test to verify that toggling layout visibility works properly.";\r
- }\r
- \r
- @Override\r
- protected Integer getTicketNumber() {\r
- return 3183;\r
- }\r
- \r
- @Override\r
- public void setup() {\r
- \r
- VerticalLayout vl = new VerticalLayout();\r
- vl.setSizeFull();\r
- getLayout().addComponent(vl);\r
- \r
- final HorizontalLayout hl = new HorizontalLayout();\r
- hl.setWidth("100%");\r
- hl.setHeight("30px");\r
- hl.addComponent(new Label("label1"));\r
- hl.addComponent(new Label("label2"));\r
- hl.addComponent(new Label("label3"));\r
- hl.addComponent(new Label("label4"));\r
- vl.addComponent(hl);\r
- \r
- Label l = new Label("Steps to reproduce with Vaadin 6.0.1:<br/>"\r
- + "1. set browser size smaller than fullscreen<br/>"\r
- + "2. Refresh page with browser<br/>"\r
- + "3. Click \"toggle layout visibility\"<br>"\r
- + "4. Resize browser window to full <br/>"\r
- + "5. Click \"toggle layout visibility\"<br/>",\r
- ContentMode.XHTML);\r
- vl.addComponent(l);\r
- Button b = new Button("toggle layout visibility",\r
- new Button.ClickListener() {\r
- \r
- public void buttonClick(ClickEvent event) {\r
- hl.setVisible(!hl.isVisible());\r
- }\r
- \r
- });\r
- vl.addComponent(b);\r
- }\r
- \r
+ package com.vaadin.tests.layouts;
+
+ import com.vaadin.tests.components.TestBase;
+ import com.vaadin.ui.Button;
+ import com.vaadin.ui.Button.ClickEvent;
+ import com.vaadin.ui.HorizontalLayout;
+ import com.vaadin.ui.Label;
++import com.vaadin.ui.Label.ContentMode;
+ import com.vaadin.ui.VerticalLayout;
+
+ public class HiddenHorizontalLayout extends TestBase {
+
+ @Override
+ protected String getDescription() {
+ return "Test to verify that toggling layout visibility works properly.";
+ }
+
+ @Override
+ protected Integer getTicketNumber() {
+ return 3183;
+ }
+
+ @Override
+ public void setup() {
+
+ VerticalLayout vl = new VerticalLayout();
+ vl.setSizeFull();
+ getLayout().addComponent(vl);
+
+ final HorizontalLayout hl = new HorizontalLayout();
+ hl.setWidth("100%");
+ hl.setHeight("30px");
+ hl.addComponent(new Label("label1"));
+ hl.addComponent(new Label("label2"));
+ hl.addComponent(new Label("label3"));
+ hl.addComponent(new Label("label4"));
+ vl.addComponent(hl);
+
+ Label l = new Label("Steps to reproduce with Vaadin 6.0.1:<br/>"
+ + "1. set browser size smaller than fullscreen<br/>"
+ + "2. Refresh page with browser<br/>"
+ + "3. Click \"toggle layout visibility\"<br>"
+ + "4. Resize browser window to full <br/>"
+ + "5. Click \"toggle layout visibility\"<br/>",
- Label.CONTENT_XHTML);
++ ContentMode.XHTML);
+ vl.addComponent(l);
+ Button b = new Button("toggle layout visibility",
+ new Button.ClickListener() {
+
+ public void buttonClick(ClickEvent event) {
+ hl.setVisible(!hl.isVisible());
+ }
+
+ });
+ vl.addComponent(b);
+ }
+
}
- package com.vaadin.tests.layouts;\r
- \r
- import java.io.File;\r
- import java.net.URL;\r
- import java.util.ArrayList;\r
- import java.util.Arrays;\r
- import java.util.Iterator;\r
- \r
- import com.vaadin.data.Item;\r
- import com.vaadin.data.Property;\r
- import com.vaadin.data.Property.ValueChangeEvent;\r
- import com.vaadin.data.Property.ValueChangeListener;\r
- import com.vaadin.data.util.BeanItem;\r
- import com.vaadin.data.util.IndexedContainer;\r
- import com.vaadin.tests.components.TestBase;\r
- import com.vaadin.ui.AbsoluteLayout;\r
- import com.vaadin.ui.AbsoluteLayout.ComponentPosition;\r
- import com.vaadin.ui.AbstractComponent;\r
- import com.vaadin.ui.Button;\r
- import com.vaadin.ui.Button.ClickEvent;\r
- import com.vaadin.ui.Component;\r
- import com.vaadin.ui.DefaultFieldFactory;\r
- import com.vaadin.ui.Field;\r
- import com.vaadin.ui.Form;\r
- import com.vaadin.ui.Label;\r
- import com.vaadin.ui.Layout;\r
- import com.vaadin.ui.NativeSelect;\r
- import com.vaadin.ui.TextArea;\r
- import com.vaadin.ui.Window;\r
- \r
- public class TestAbsoluteLayout extends TestBase {\r
- \r
- private static class MFieldFactory extends DefaultFieldFactory {\r
- \r
- @Override\r
- public Field<?> createField(Item item, Object propertyId,\r
- Component uiContext) {\r
- if (propertyId.equals("CSSString")) {\r
- TextArea f = new TextArea();\r
- f.setRows(5);\r
- f.setHeight("8em");\r
- f.setCaption("CSS string");\r
- return f;\r
- } else if (((String) propertyId).contains("Units")) {\r
- NativeSelect s = new NativeSelect() {\r
- };\r
- s.addContainerProperty("caption", String.class, "");\r
- s.setItemCaptionPropertyId("caption");\r
- s.setNullSelectionAllowed(false);\r
- for (int i = 0; i < Layout.Unit.values().length; i++) {\r
- Item unitItem = s.addItem(i);\r
- unitItem.getItemProperty("caption").setValue(\r
- Layout.Unit.values()[i]);\r
- }\r
- return s;\r
- }\r
- \r
- return super.createField(item, propertyId, uiContext);\r
- }\r
- \r
- private static MFieldFactory instance;\r
- \r
- public static DefaultFieldFactory get() {\r
- if (instance == null) {\r
- instance = new MFieldFactory();\r
- }\r
- return instance;\r
- }\r
- };\r
- \r
- @Override\r
- protected String getDescription() {\r
- return "This is absolute layout tester.";\r
- }\r
- \r
- @Override\r
- protected Integer getTicketNumber() {\r
- return null;\r
- }\r
- \r
- @Override\r
- protected void setup() {\r
- AbsoluteLayout layout = new AbsoluteLayout();\r
- setTheme("tests-tickets");\r
- layout.setStyleName("cyan");\r
- layout.setWidth("1000px");\r
- layout.setHeight("500px");\r
- \r
- layout.addComponent(new Label("Hello World"));\r
- \r
- Button button = new Button("Centered button,z-index:10;");\r
- button.setSizeFull();\r
- layout.addComponent(button,\r
- "top:40%;bottom:40%;right:20%;left:20%;z-index:10;");\r
- \r
- Label label = new Label(\r
- "Exotic positioned label. Fullsize, top:100px; left:2cm; right: 3.5in; bottom:12.12mm ");\r
- label.setStyleName("yellow");\r
- label.setSizeFull();\r
- layout.addComponent(label,\r
- "top:100px; left:2cm; right: 3.5in; bottom:12.12mm");\r
- \r
- label = new Label("fullize, bottom:80%;left:80%;");\r
- label.setStyleName("green");\r
- label.setSizeFull();\r
- layout.addComponent(label, "bottom:80%;left:80%;");\r
- \r
- label = new Label("bottomright");\r
- label.setSizeUndefined();\r
- label.setStyleName("green");\r
- layout.addComponent(label, "bottom:0px; right:0px;");\r
- \r
- getLayout().setSizeFull();\r
- getLayout().addComponent(layout);\r
- \r
- getMainWindow().addWindow(new EditorWindow(layout));\r
- \r
- }\r
- \r
- public class EditorWindow extends Window {\r
- private final AbsoluteLayout l;\r
- private Form componentEditor;\r
- private Form positionEditor;\r
- \r
- public EditorWindow(AbsoluteLayout lo) {\r
- super("AbsoluteLayout editor aka köyhän miehen wysiwyg");\r
- l = lo;\r
- \r
- setHeight("600px");\r
- \r
- Button componentChooser = new Button("choose component to edit");\r
- componentChooser.addListener(new Button.ClickListener() {\r
- public void buttonClick(ClickEvent event) {\r
- final Window chooser = new Window("Choose component");\r
- chooser.getContent().setSizeUndefined();\r
- chooser.setModal(true);\r
- \r
- NativeSelect select = new NativeSelect(\r
- "Choose component to edit");\r
- \r
- select.setNullSelectionAllowed(false);\r
- \r
- IndexedContainer container = new IndexedContainer();\r
- container.addContainerProperty("caption", String.class, "");\r
- Iterator<Component> componentIterator = l\r
- .getComponentIterator();\r
- while (componentIterator.hasNext()) {\r
- AbstractComponent next = (AbstractComponent) componentIterator\r
- .next();\r
- Item item = container.addItem(next);\r
- \r
- String caption = next.getClass().getSimpleName();\r
- \r
- caption += "; cap: " + next.getCaption() + "; debugid"\r
- + getDebugId();\r
- \r
- if (next instanceof Property) {\r
- caption += " value:"\r
- + ((Property<?>) next).getValue();\r
- }\r
- \r
- item.getItemProperty("caption").setValue(caption);\r
- }\r
- select.setContainerDataSource(container);\r
- select.setItemCaptionPropertyId("caption");\r
- select.setImmediate(true);\r
- \r
- select.addListener(new ValueChangeListener() {\r
- public void valueChange(ValueChangeEvent event) {\r
- editcomponent((Component) event.getProperty()\r
- .getValue());\r
- getMainWindow().removeWindow(chooser);\r
- }\r
- \r
- });\r
- \r
- chooser.addComponent(select);\r
- \r
- getMainWindow().addWindow(chooser);\r
- \r
- }\r
- });\r
- \r
- addComponent(componentChooser);\r
- \r
- Button addComp = new Button("add component");\r
- addComp.addListener(new Button.ClickListener() {\r
- public void buttonClick(ClickEvent event) {\r
- final Window chooser = new Window(\r
- "Choose component type to add");\r
- chooser.getContent().setSizeUndefined();\r
- chooser.setModal(true);\r
- \r
- NativeSelect select = new NativeSelect(\r
- "Choose component to edit");\r
- \r
- select.setNullSelectionAllowed(false);\r
- \r
- IndexedContainer container = new IndexedContainer();\r
- \r
- URL resource = AbstractComponent.class.getResource(".");\r
- File directory = new File(resource.getFile());\r
- if (directory.exists()) {\r
- // Get the list of the files contained in the\r
- // package\r
- final String[] files = directory.list();\r
- for (int j = 0; j < files.length; j++) {\r
- // we are only interested in .class files\r
- if (files[j].endsWith(".class")) {\r
- // removes the .class extension\r
- String p = resource.toString()\r
- + files[j].substring(0,\r
- files[j].length() - 6);\r
- p = p.replaceAll(".*classes/", "");\r
- p = p.replaceAll("/", ".");\r
- Class<?> c;\r
- try {\r
- c = Class.forName(p);\r
- if (AbstractComponent.class\r
- .isAssignableFrom(c)\r
- && !p.toLowerCase().contains(\r
- "layout")\r
- && !p.toLowerCase().contains(\r
- "abstract")) {\r
- container.addItem(c);\r
- }\r
- } catch (ClassNotFoundException e) {\r
- // TODO Auto-generated catch block\r
- e.printStackTrace();\r
- }\r
- }\r
- }\r
- }\r
- select.setContainerDataSource(container);\r
- select.setImmediate(true);\r
- \r
- select.addListener(new ValueChangeListener() {\r
- public void valueChange(ValueChangeEvent event) {\r
- Class<?> c = (Class<?>) event.getProperty()\r
- .getValue();\r
- \r
- try {\r
- Component newInstance = (Component) c\r
- .newInstance();\r
- l.addComponent(newInstance);\r
- editcomponent(newInstance);\r
- getMainWindow().removeWindow(chooser);\r
- } catch (InstantiationException e) {\r
- // TODO Auto-generated catch block\r
- e.printStackTrace();\r
- } catch (IllegalAccessException e) {\r
- // TODO Auto-generated catch block\r
- e.printStackTrace();\r
- }\r
- \r
- }\r
- \r
- });\r
- \r
- chooser.addComponent(select);\r
- \r
- getMainWindow().addWindow(chooser);\r
- \r
- }\r
- });\r
- \r
- addComponent(addComp);\r
- \r
- componentEditor = new Form();\r
- componentEditor.setWriteThrough(false);\r
- componentEditor.setCaption("Component properties:");\r
- componentEditor.setFormFieldFactory(MFieldFactory.get());\r
- addComponent(componentEditor);\r
- \r
- positionEditor = new Form();\r
- positionEditor.setCaption("Component position");\r
- positionEditor.setWriteThrough(false);\r
- positionEditor.setFormFieldFactory(MFieldFactory.get());\r
- addComponent(positionEditor);\r
- \r
- Button b = new Button("Commit changes", new Button.ClickListener() {\r
- public void buttonClick(ClickEvent event) {\r
- positionEditor.commit();\r
- componentEditor.commit();\r
- }\r
- });\r
- addComponent(b);\r
- \r
- }\r
- \r
- private void editcomponent(Component value) {\r
- \r
- BeanItem<Component> beanItem = new BeanItem<Component>(value);\r
- String c = "Component properties for "\r
- + value.getClass().getSimpleName();\r
- ArrayList<String> fields = new ArrayList<String>(\r
- Arrays.asList(new String[] { "width", "widthUnits",\r
- "height", "heightUnits", "caption", "styleName" }));\r
- if (value instanceof Label) {\r
- c += "(" + ((Label) value).getValue() + ")";\r
- fields.add("value");\r
- }\r
- \r
- componentEditor.setItemDataSource(beanItem, fields);\r
- \r
- BeanItem<ComponentPosition> positionItem = new BeanItem<ComponentPosition>(\r
- l.getPosition(value));\r
- componentEditor.setCaption(c);\r
- \r
- positionEditor.setItemDataSource(positionItem);\r
- \r
- }\r
- }\r
- \r
- }\r
+ package com.vaadin.tests.layouts;
+
+ import java.io.File;
+ import java.net.URL;
+ import java.util.ArrayList;
+ import java.util.Arrays;
+ import java.util.Iterator;
+
+ import com.vaadin.data.Item;
+ import com.vaadin.data.Property;
+ import com.vaadin.data.Property.ValueChangeEvent;
+ import com.vaadin.data.Property.ValueChangeListener;
+ import com.vaadin.data.util.BeanItem;
+ import com.vaadin.data.util.IndexedContainer;
+ import com.vaadin.tests.components.TestBase;
+ import com.vaadin.ui.AbsoluteLayout;
+ import com.vaadin.ui.AbsoluteLayout.ComponentPosition;
+ import com.vaadin.ui.AbstractComponent;
+ import com.vaadin.ui.Button;
+ import com.vaadin.ui.Button.ClickEvent;
+ import com.vaadin.ui.Component;
+ import com.vaadin.ui.DefaultFieldFactory;
+ import com.vaadin.ui.Field;
+ import com.vaadin.ui.Form;
+ import com.vaadin.ui.Label;
+ import com.vaadin.ui.Layout;
+ import com.vaadin.ui.NativeSelect;
+ import com.vaadin.ui.TextArea;
+ import com.vaadin.ui.Window;
+
+ public class TestAbsoluteLayout extends TestBase {
+
+ private static class MFieldFactory extends DefaultFieldFactory {
+
+ @Override
- public Field createField(Item item, Object propertyId,
++ public Field<?> createField(Item item, Object propertyId,
+ Component uiContext) {
+ if (propertyId.equals("CSSString")) {
+ TextArea f = new TextArea();
+ f.setRows(5);
+ f.setHeight("8em");
+ f.setCaption("CSS string");
+ return f;
+ } else if (((String) propertyId).contains("Units")) {
+ NativeSelect s = new NativeSelect() {
+ };
+ s.addContainerProperty("caption", String.class, "");
+ s.setItemCaptionPropertyId("caption");
+ s.setNullSelectionAllowed(false);
- for (int i = 0; i < Layout.UNIT_SYMBOLS.length; i++) {
++ for (int i = 0; i < Layout.Unit.values().length; i++) {
+ Item unitItem = s.addItem(i);
+ unitItem.getItemProperty("caption").setValue(
- Layout.UNIT_SYMBOLS[i]);
++ Layout.Unit.values()[i]);
+ }
+ return s;
+ }
+
+ return super.createField(item, propertyId, uiContext);
+ }
+
+ private static MFieldFactory instance;
+
+ public static DefaultFieldFactory get() {
+ if (instance == null) {
+ instance = new MFieldFactory();
+ }
+ return instance;
+ }
+ };
+
+ @Override
+ protected String getDescription() {
+ return "This is absolute layout tester.";
+ }
+
+ @Override
+ protected Integer getTicketNumber() {
+ return null;
+ }
+
+ @Override
+ protected void setup() {
+ AbsoluteLayout layout = new AbsoluteLayout();
+ setTheme("tests-tickets");
+ layout.setStyleName("cyan");
+ layout.setWidth("1000px");
+ layout.setHeight("500px");
+
+ layout.addComponent(new Label("Hello World"));
+
+ Button button = new Button("Centered button,z-index:10;");
+ button.setSizeFull();
+ layout.addComponent(button,
+ "top:40%;bottom:40%;right:20%;left:20%;z-index:10;");
+
+ Label label = new Label(
+ "Exotic positioned label. Fullsize, top:100px; left:2cm; right: 3.5in; bottom:12.12mm ");
+ label.setStyleName("yellow");
+ label.setSizeFull();
+ layout.addComponent(label,
+ "top:100px; left:2cm; right: 3.5in; bottom:12.12mm");
+
+ label = new Label("fullize, bottom:80%;left:80%;");
+ label.setStyleName("green");
+ label.setSizeFull();
+ layout.addComponent(label, "bottom:80%;left:80%;");
+
+ label = new Label("bottomright");
+ label.setSizeUndefined();
+ label.setStyleName("green");
+ layout.addComponent(label, "bottom:0px; right:0px;");
+
+ getLayout().setSizeFull();
+ getLayout().addComponent(layout);
+
+ getMainWindow().addWindow(new EditorWindow(layout));
+
+ }
+
+ public class EditorWindow extends Window {
+ private final AbsoluteLayout l;
+ private Form componentEditor;
+ private Form positionEditor;
+
+ public EditorWindow(AbsoluteLayout lo) {
+ super("AbsoluteLayout editor aka köyhän miehen wysiwyg");
+ l = lo;
+
+ setHeight("600px");
+
+ Button componentChooser = new Button("choose component to edit");
+ componentChooser.addListener(new Button.ClickListener() {
+ public void buttonClick(ClickEvent event) {
+ final Window chooser = new Window("Choose component");
+ chooser.getContent().setSizeUndefined();
+ chooser.setModal(true);
+
+ NativeSelect select = new NativeSelect(
+ "Choose component to edit");
+
+ select.setNullSelectionAllowed(false);
+
+ IndexedContainer container = new IndexedContainer();
+ container.addContainerProperty("caption", String.class, "");
+ Iterator<Component> componentIterator = l
+ .getComponentIterator();
+ while (componentIterator.hasNext()) {
+ AbstractComponent next = (AbstractComponent) componentIterator
+ .next();
+ Item item = container.addItem(next);
+
+ String caption = next.getClass().getSimpleName();
+
+ caption += "; cap: " + next.getCaption() + "; debugid"
+ + getDebugId();
+
+ if (next instanceof Property) {
- caption += " value:" + ((Property) next).getValue();
++ caption += " value:"
++ + ((Property<?>) next).getValue();
+ }
+
+ item.getItemProperty("caption").setValue(caption);
+ }
+ select.setContainerDataSource(container);
+ select.setItemCaptionPropertyId("caption");
+ select.setImmediate(true);
+
+ select.addListener(new ValueChangeListener() {
+ public void valueChange(ValueChangeEvent event) {
+ editcomponent((Component) event.getProperty()
+ .getValue());
+ getMainWindow().removeWindow(chooser);
+ }
+
+ });
+
+ chooser.addComponent(select);
+
+ getMainWindow().addWindow(chooser);
+
+ }
+ });
+
+ addComponent(componentChooser);
+
+ Button addComp = new Button("add component");
+ addComp.addListener(new Button.ClickListener() {
+ public void buttonClick(ClickEvent event) {
+ final Window chooser = new Window(
+ "Choose component type to add");
+ chooser.getContent().setSizeUndefined();
+ chooser.setModal(true);
+
+ NativeSelect select = new NativeSelect(
+ "Choose component to edit");
+
+ select.setNullSelectionAllowed(false);
+
+ IndexedContainer container = new IndexedContainer();
+
+ URL resource = AbstractComponent.class.getResource(".");
+ File directory = new File(resource.getFile());
+ if (directory.exists()) {
+ // Get the list of the files contained in the
+ // package
+ final String[] files = directory.list();
+ for (int j = 0; j < files.length; j++) {
+ // we are only interested in .class files
+ if (files[j].endsWith(".class")) {
+ // removes the .class extension
+ String p = resource.toString()
+ + files[j].substring(0,
+ files[j].length() - 6);
+ p = p.replaceAll(".*classes/", "");
+ p = p.replaceAll("/", ".");
+ Class<?> c;
+ try {
+ c = Class.forName(p);
+ if (AbstractComponent.class
+ .isAssignableFrom(c)
+ && !p.toLowerCase().contains(
+ "layout")
+ && !p.toLowerCase().contains(
+ "abstract")) {
+ container.addItem(c);
+ }
+ } catch (ClassNotFoundException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+ }
+ }
+ }
+ select.setContainerDataSource(container);
+ select.setImmediate(true);
+
+ select.addListener(new ValueChangeListener() {
+ public void valueChange(ValueChangeEvent event) {
+ Class<?> c = (Class<?>) event.getProperty()
+ .getValue();
+
+ try {
+ Component newInstance = (Component) c
+ .newInstance();
+ l.addComponent(newInstance);
+ editcomponent(newInstance);
+ getMainWindow().removeWindow(chooser);
+ } catch (InstantiationException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ } catch (IllegalAccessException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+
+ }
+
+ });
+
+ chooser.addComponent(select);
+
+ getMainWindow().addWindow(chooser);
+
+ }
+ });
+
+ addComponent(addComp);
+
+ componentEditor = new Form();
+ componentEditor.setWriteThrough(false);
+ componentEditor.setCaption("Component properties:");
+ componentEditor.setFormFieldFactory(MFieldFactory.get());
+ addComponent(componentEditor);
+
+ positionEditor = new Form();
+ positionEditor.setCaption("Component position");
+ positionEditor.setWriteThrough(false);
+ positionEditor.setFormFieldFactory(MFieldFactory.get());
+ addComponent(positionEditor);
+
+ Button b = new Button("Commit changes", new Button.ClickListener() {
+ public void buttonClick(ClickEvent event) {
+ positionEditor.commit();
+ componentEditor.commit();
+ }
+ });
+ addComponent(b);
+
+ }
+
+ private void editcomponent(Component value) {
+
+ BeanItem<Component> beanItem = new BeanItem<Component>(value);
+ String c = "Component properties for "
+ + value.getClass().getSimpleName();
+ ArrayList<String> fields = new ArrayList<String>(
+ Arrays.asList(new String[] { "width", "widthUnits",
+ "height", "heightUnits", "caption", "styleName" }));
+ if (value instanceof Label) {
+ c += "(" + ((Label) value).getValue() + ")";
+ fields.add("value");
+ }
+
+ componentEditor.setItemDataSource(beanItem, fields);
+
+ BeanItem<ComponentPosition> positionItem = new BeanItem<ComponentPosition>(
+ l.getPosition(value));
+ componentEditor.setCaption(c);
+
+ positionEditor.setItemDataSource(positionItem);
+
+ }
+ }
+
+ }
- package com.vaadin.tests.layouts;\r
- \r
- import com.vaadin.tests.components.TestBase;\r
- import com.vaadin.ui.AbstractComponent;\r
- import com.vaadin.ui.Button;\r
- import com.vaadin.ui.Button.ClickEvent;\r
- import com.vaadin.ui.CheckBox;\r
- import com.vaadin.ui.Component;\r
- import com.vaadin.ui.CssLayout;\r
- import com.vaadin.ui.GridLayout;\r
- import com.vaadin.ui.Label;\r
- import com.vaadin.ui.Label.ContentMode;\r
- import com.vaadin.ui.Layout;\r
- import com.vaadin.ui.NativeSelect;\r
- import com.vaadin.ui.TextField;\r
- import com.vaadin.ui.VerticalLayout;\r
- \r
- public class TestLayoutPerformance extends TestBase {\r
- private NativeSelect ns;\r
- private int i;\r
- private NativeSelect ns2;\r
- private VerticalLayout testarea = new VerticalLayout();\r
- \r
- @Override\r
- protected String getDescription() {\r
- return "Test app to test simple rendering to various layouts.";\r
- }\r
- \r
- @Override\r
- protected Integer getTicketNumber() {\r
- return null;\r
- }\r
- \r
- @Override\r
- protected void setup() {\r
- Label label = new Label("<h1>CssLayout performance test.</h1>",\r
- ContentMode.XHTML);\r
- getLayout().addComponent(label);\r
- \r
- label = new Label(\r
- "<em>Hint</em>. Use debug dialog to measure rendering times TODO: extend with size settings (to both layout and content).",\r
- ContentMode.XHTML);\r
- getLayout().addComponent(label);\r
- \r
- ns = new NativeSelect("Select component to test");\r
- ns.addItem(CssLayout.class);\r
- ns.addItem(GridLayout.class);\r
- ns.addItem(VerticalLayout.class);\r
- ns.setNullSelectionAllowed(false);\r
- ns.setValue(CssLayout.class);\r
- \r
- ns2 = new NativeSelect("Select component to render inside layout.");\r
- ns2.addItem(Label.class);\r
- ns2.addItem(Button.class);\r
- ns2.setNullSelectionAllowed(false);\r
- ns2.setValue(Label.class);\r
- \r
- final TextField n = new TextField("Number of components");\r
- \r
- n.setValue("1000");\r
- \r
- final CheckBox cb = new CheckBox("Generate captions", false);\r
- \r
- Button b = new Button("Render component");\r
- \r
- b.addListener(new Button.ClickListener() {\r
- \r
- public void buttonClick(ClickEvent event) {\r
- int components = Integer.parseInt(n.getValue());\r
- Layout layout = getCurrentLayout();\r
- for (int i = 0; i < components; i++) {\r
- Component component = newTestComponent();\r
- if (cb.getValue()) {\r
- component.setCaption("caption " + i);\r
- }\r
- layout.addComponent(component);\r
- }\r
- \r
- testarea.removeAllComponents();\r
- testarea.addComponent(layout);\r
- }\r
- \r
- });\r
- \r
- getLayout().addComponent(ns);\r
- getLayout().addComponent(ns2);\r
- getLayout().addComponent(n);\r
- getLayout().addComponent(cb);\r
- getLayout().addComponent(b);\r
- getLayout().addComponent(testarea);\r
- \r
- }\r
- \r
- private Layout getCurrentLayout() {\r
- Class<?> value = (Class<?>) ns.getValue();\r
- if (value == GridLayout.class) {\r
- return new GridLayout(10, 1);\r
- }\r
- \r
- try {\r
- return (Layout) value.newInstance();\r
- } catch (InstantiationException e) {\r
- // TODO Auto-generated catch block\r
- e.printStackTrace();\r
- } catch (IllegalAccessException e) {\r
- // TODO Auto-generated catch block\r
- e.printStackTrace();\r
- }\r
- return null;\r
- \r
- }\r
- \r
- private Component newTestComponent() {\r
- Class<?> componentClass = (Class<?>) ns2.getValue();\r
- AbstractComponent newInstance = null;\r
- try {\r
- newInstance = (AbstractComponent) componentClass.newInstance();\r
- } catch (InstantiationException e) {\r
- // TODO Auto-generated catch block\r
- e.printStackTrace();\r
- } catch (IllegalAccessException e) {\r
- // TODO Auto-generated catch block\r
- e.printStackTrace();\r
- }\r
- if (componentClass == Label.class) {\r
- ((Label) newInstance).setValue("Test l " + (i++));\r
- ((Label) newInstance).setSizeUndefined();\r
- } else {\r
- newInstance.setCaption("Test l " + (i++));\r
- }\r
- return newInstance;\r
- }\r
- \r
- }\r
+ package com.vaadin.tests.layouts;
+
+ import com.vaadin.tests.components.TestBase;
+ import com.vaadin.ui.AbstractComponent;
+ import com.vaadin.ui.Button;
+ import com.vaadin.ui.Button.ClickEvent;
+ import com.vaadin.ui.CheckBox;
+ import com.vaadin.ui.Component;
+ import com.vaadin.ui.CssLayout;
+ import com.vaadin.ui.GridLayout;
+ import com.vaadin.ui.Label;
++import com.vaadin.ui.Label.ContentMode;
+ import com.vaadin.ui.Layout;
+ import com.vaadin.ui.NativeSelect;
+ import com.vaadin.ui.TextField;
+ import com.vaadin.ui.VerticalLayout;
+
+ public class TestLayoutPerformance extends TestBase {
+ private NativeSelect ns;
+ private int i;
+ private NativeSelect ns2;
+ private VerticalLayout testarea = new VerticalLayout();
+
+ @Override
+ protected String getDescription() {
+ return "Test app to test simple rendering to various layouts.";
+ }
+
+ @Override
+ protected Integer getTicketNumber() {
+ return null;
+ }
+
+ @Override
+ protected void setup() {
+ Label label = new Label("<h1>CssLayout performance test.</h1>",
- Label.CONTENT_XHTML);
++ ContentMode.XHTML);
+ getLayout().addComponent(label);
+
+ label = new Label(
+ "<em>Hint</em>. Use debug dialog to measure rendering times TODO: extend with size settings (to both layout and content).",
- Label.CONTENT_XHTML);
++ ContentMode.XHTML);
+ getLayout().addComponent(label);
+
+ ns = new NativeSelect("Select component to test");
+ ns.addItem(CssLayout.class);
+ ns.addItem(GridLayout.class);
+ ns.addItem(VerticalLayout.class);
+ ns.setNullSelectionAllowed(false);
+ ns.setValue(CssLayout.class);
+
+ ns2 = new NativeSelect("Select component to render inside layout.");
+ ns2.addItem(Label.class);
+ ns2.addItem(Button.class);
+ ns2.setNullSelectionAllowed(false);
+ ns2.setValue(Label.class);
+
+ final TextField n = new TextField("Number of components");
+
+ n.setValue("1000");
+
+ final CheckBox cb = new CheckBox("Generate captions", false);
+
+ Button b = new Button("Render component");
+
+ b.addListener(new Button.ClickListener() {
+
+ public void buttonClick(ClickEvent event) {
- int components = Integer.parseInt((String) n.getValue());
++ int components = Integer.parseInt(n.getValue());
+ Layout layout = getCurrentLayout();
+ for (int i = 0; i < components; i++) {
+ Component component = newTestComponent();
- if (cb.booleanValue()) {
++ if (cb.getValue()) {
+ component.setCaption("caption " + i);
+ }
+ layout.addComponent(component);
+ }
+
+ testarea.removeAllComponents();
+ testarea.addComponent(layout);
+ }
+
+ });
+
+ getLayout().addComponent(ns);
+ getLayout().addComponent(ns2);
+ getLayout().addComponent(n);
+ getLayout().addComponent(cb);
+ getLayout().addComponent(b);
+ getLayout().addComponent(testarea);
+
+ }
+
+ private Layout getCurrentLayout() {
+ Class<?> value = (Class<?>) ns.getValue();
+ if (value == GridLayout.class) {
+ return new GridLayout(10, 1);
+ }
+
+ try {
+ return (Layout) value.newInstance();
+ } catch (InstantiationException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ } catch (IllegalAccessException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+ return null;
+
+ }
+
+ private Component newTestComponent() {
+ Class<?> componentClass = (Class<?>) ns2.getValue();
+ AbstractComponent newInstance = null;
+ try {
+ newInstance = (AbstractComponent) componentClass.newInstance();
+ } catch (InstantiationException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ } catch (IllegalAccessException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+ if (componentClass == Label.class) {
+ ((Label) newInstance).setValue("Test l " + (i++));
+ ((Label) newInstance).setSizeUndefined();
+ } else {
+ newInstance.setCaption("Test l " + (i++));
+ }
+ return newInstance;
+ }
+
+ }
- package com.vaadin.tests.layouts;\r
- \r
- import com.vaadin.tests.components.AbstractTestCase;\r
- import com.vaadin.ui.Layout;\r
- import com.vaadin.ui.Root.LegacyWindow;\r
- import com.vaadin.ui.Tree;\r
- import com.vaadin.ui.VerticalLayout;\r
- \r
- public class TreeWithBordersInLayout extends AbstractTestCase {\r
- \r
- private static final Object CAPTION = "caption";\r
- \r
- @Override\r
- public void init() {\r
- Layout mainLayout = new VerticalLayout();\r
- mainLayout.setSizeUndefined();\r
- setMainWindow(new LegacyWindow("main window", mainLayout));\r
- \r
- setTheme("tests-tickets");\r
- \r
- Tree t = new Tree();\r
- t.addContainerProperty(CAPTION, String.class, "");\r
- t.setItemCaptionPropertyId(CAPTION);\r
- t.addItem("Item 1").getItemProperty(CAPTION).setValue("Item 1");\r
- \r
- t.setSizeUndefined();\r
- t.setStyleName("redblueborders");\r
- mainLayout.addComponent(t);\r
- \r
- }\r
- \r
- @Override\r
- protected String getDescription() {\r
- return "The tree consists of one node and has a 10px blue red border and a 10px red right border. The tree node should be visible between the borders.";\r
- }\r
- \r
- @Override\r
- protected Integer getTicketNumber() {\r
- return 3915;\r
- }\r
- \r
- }\r
+ package com.vaadin.tests.layouts;
+
+ import com.vaadin.tests.components.AbstractTestCase;
+ import com.vaadin.ui.Layout;
++import com.vaadin.ui.Root.LegacyWindow;
+ import com.vaadin.ui.Tree;
+ import com.vaadin.ui.VerticalLayout;
-import com.vaadin.ui.Window;
+
+ public class TreeWithBordersInLayout extends AbstractTestCase {
+
+ private static final Object CAPTION = "caption";
+
+ @Override
+ public void init() {
+ Layout mainLayout = new VerticalLayout();
+ mainLayout.setSizeUndefined();
- setMainWindow(new Window("main window", mainLayout));
++ setMainWindow(new LegacyWindow("main window", mainLayout));
+
+ setTheme("tests-tickets");
+
+ Tree t = new Tree();
+ t.addContainerProperty(CAPTION, String.class, "");
+ t.setItemCaptionPropertyId(CAPTION);
+ t.addItem("Item 1").getItemProperty(CAPTION).setValue("Item 1");
+
+ t.setSizeUndefined();
+ t.setStyleName("redblueborders");
+ mainLayout.addComponent(t);
+
+ }
+
+ @Override
+ protected String getDescription() {
+ return "The tree consists of one node and has a 10px blue red border and a 10px red right border. The tree node should be visible between the borders.";
+ }
+
+ @Override
+ protected Integer getTicketNumber() {
+ return 3915;
+ }
+
+ }
- package com.vaadin.tests.layouts;\r
- \r
- import com.vaadin.tests.components.TestBase;\r
- import com.vaadin.ui.Button;\r
- import com.vaadin.ui.Button.ClickEvent;\r
- import com.vaadin.ui.Button.ClickListener;\r
- import com.vaadin.ui.Label;\r
- import com.vaadin.ui.Root.LegacyWindow;\r
- import com.vaadin.ui.TextField;\r
- import com.vaadin.ui.VerticalLayout;\r
- \r
- public class VerticalLayoutExpandRatioModification extends TestBase implements\r
- ClickListener {\r
- \r
- private boolean isVisible = false;\r
- private VerticalLayout mainLayout;\r
- private VerticalLayout vl1;\r
- private VerticalLayout vl2;\r
- private Button button;\r
- \r
- @Override\r
- public void setup() {\r
- LegacyWindow main = new LegacyWindow("The Main Window");\r
- mainLayout = new VerticalLayout();\r
- main.setContent(mainLayout);\r
- setMainWindow(main);\r
- \r
- // The upper layout\r
- vl1 = new VerticalLayout();\r
- Label label1 = new Label("The upper layout");\r
- vl1.addComponent(label1);\r
- \r
- // Button that hides or shows the bottom part\r
- button = new Button("show / hide", this);\r
- \r
- // The bottom layout\r
- vl2 = new VerticalLayout();\r
- TextField tf = new TextField("The bottom field");\r
- tf.setHeight("100%");\r
- vl2.addComponent(tf);\r
- \r
- // Add everything to the view\r
- mainLayout.addComponent(vl1);\r
- mainLayout.addComponent(button);\r
- mainLayout.addComponent(vl2);\r
- \r
- // Set expand ratios, hide lower\r
- mainLayout.setExpandRatio(vl1, 1);\r
- mainLayout.setExpandRatio(vl2, 0);\r
- \r
- // Maximize everything\r
- main.setSizeFull();\r
- mainLayout.setSizeFull();\r
- vl1.setSizeFull();\r
- vl2.setSizeFull();\r
- }\r
- \r
- public void buttonClick(ClickEvent event) {\r
- if (isVisible) {\r
- mainLayout.setExpandRatio(vl2, 0);\r
- isVisible = false;\r
- } else {\r
- mainLayout.setExpandRatio(vl2, 1);\r
- isVisible = true;\r
- }\r
- }\r
- \r
- @Override\r
- protected String getDescription() {\r
- return "Changing the expand ratio should repaint the layout correctly. Changing from 0 to something else should render the previously invisible component";\r
- }\r
- \r
- @Override\r
- protected Integer getTicketNumber() {\r
- return 2454;\r
- }\r
- }\r
+ package com.vaadin.tests.layouts;
+
+ import com.vaadin.tests.components.TestBase;
+ import com.vaadin.ui.Button;
+ import com.vaadin.ui.Button.ClickEvent;
+ import com.vaadin.ui.Button.ClickListener;
+ import com.vaadin.ui.Label;
++import com.vaadin.ui.Root.LegacyWindow;
+ import com.vaadin.ui.TextField;
+ import com.vaadin.ui.VerticalLayout;
-import com.vaadin.ui.Window;
+
+ public class VerticalLayoutExpandRatioModification extends TestBase implements
+ ClickListener {
+
+ private boolean isVisible = false;
+ private VerticalLayout mainLayout;
+ private VerticalLayout vl1;
+ private VerticalLayout vl2;
+ private Button button;
+
+ @Override
+ public void setup() {
- Window main = new Window("The Main Window");
++ LegacyWindow main = new LegacyWindow("The Main Window");
+ mainLayout = new VerticalLayout();
+ main.setContent(mainLayout);
+ setMainWindow(main);
+
+ // The upper layout
+ vl1 = new VerticalLayout();
+ Label label1 = new Label("The upper layout");
+ vl1.addComponent(label1);
+
+ // Button that hides or shows the bottom part
+ button = new Button("show / hide", this);
+
+ // The bottom layout
+ vl2 = new VerticalLayout();
+ TextField tf = new TextField("The bottom field");
+ tf.setHeight("100%");
+ vl2.addComponent(tf);
+
+ // Add everything to the view
+ mainLayout.addComponent(vl1);
+ mainLayout.addComponent(button);
+ mainLayout.addComponent(vl2);
+
+ // Set expand ratios, hide lower
+ mainLayout.setExpandRatio(vl1, 1);
+ mainLayout.setExpandRatio(vl2, 0);
+
+ // Maximize everything
+ main.setSizeFull();
+ mainLayout.setSizeFull();
+ vl1.setSizeFull();
+ vl2.setSizeFull();
+ }
+
+ public void buttonClick(ClickEvent event) {
+ if (isVisible) {
+ mainLayout.setExpandRatio(vl2, 0);
+ isVisible = false;
+ } else {
+ mainLayout.setExpandRatio(vl2, 1);
+ isVisible = true;
+ }
+ }
+
+ @Override
+ protected String getDescription() {
+ return "Changing the expand ratio should repaint the layout correctly. Changing from 0 to something else should render the previously invisible component";
+ }
+
+ @Override
+ protected Integer getTicketNumber() {
+ return 2454;
+ }
+ }
- package com.vaadin.tests.layouts.layouttester;\r
- \r
- import java.util.Date;\r
- \r
- import com.vaadin.Application;\r
- import com.vaadin.terminal.Resource;\r
- import com.vaadin.terminal.SystemError;\r
- import com.vaadin.terminal.ThemeResource;\r
- import com.vaadin.terminal.UserError;\r
- import com.vaadin.ui.AbstractComponent;\r
- import com.vaadin.ui.AbstractField;\r
- import com.vaadin.ui.Alignment;\r
- import com.vaadin.ui.Button;\r
- import com.vaadin.ui.Button.ClickEvent;\r
- import com.vaadin.ui.CheckBox;\r
- import com.vaadin.ui.DateField;\r
- import com.vaadin.ui.GridLayout;\r
- import com.vaadin.ui.HorizontalLayout;\r
- import com.vaadin.ui.InlineDateField;\r
- import com.vaadin.ui.Label;\r
- import com.vaadin.ui.Layout;\r
- import com.vaadin.ui.Link;\r
- import com.vaadin.ui.NativeSelect;\r
- import com.vaadin.ui.Panel;\r
- import com.vaadin.ui.TabSheet;\r
- import com.vaadin.ui.Table;\r
- import com.vaadin.ui.TextField;\r
- import com.vaadin.ui.VerticalLayout;\r
- import com.vaadin.ui.themes.Reindeer;\r
- \r
- public class GridLayoutTests extends AbstractLayoutTests {\r
- \r
- private AbstractComponent rc1, col1, col2, col3, row1, row2, row3, x3, x22;\r
- \r
- public GridLayoutTests(Application application) {\r
- super();\r
- }\r
- \r
- @Override\r
- protected Layout getAlignmentTests() {\r
- HorizontalLayout hlo = new HorizontalLayout();\r
- hlo.setSpacing(true);\r
- GridLayout glo = getTestGrid();\r
- glo.addStyleName(Reindeer.LAYOUT_WHITE);\r
- Alignment[] alignments = new Alignment[] { Alignment.BOTTOM_LEFT,\r
- Alignment.BOTTOM_CENTER, Alignment.BOTTOM_RIGHT,\r
- Alignment.MIDDLE_LEFT, Alignment.MIDDLE_CENTER,\r
- Alignment.MIDDLE_RIGHT, Alignment.TOP_LEFT,\r
- Alignment.TOP_CENTER, Alignment.TOP_RIGHT };\r
- \r
- glo.replaceComponent(col1, col1 = new TextField());\r
- glo.replaceComponent(col2, col2 = new TextField());\r
- glo.replaceComponent(col3, col3 = new TextField());\r
- ((TextField) col1).setValue("BOTTOM_RIGHT");\r
- ((TextField) col2).setValue("BOTTOM_LEFT");\r
- ((TextField) col3).setValue("BOTTOM_CENTER");\r
- glo.setComponentAlignment(col2, alignments[0]);\r
- glo.setComponentAlignment(col3, alignments[1]);\r
- glo.setComponentAlignment(col1, alignments[2]);\r
- \r
- glo.setComponentAlignment(row1, alignments[3]);\r
- glo.setComponentAlignment(row2, alignments[4]);\r
- glo.setComponentAlignment(row3, alignments[5]);\r
- hlo.addComponent(glo);\r
- glo = getTestGrid();\r
- glo.replaceComponent(row1, row1 = new DateField());\r
- glo.replaceComponent(row2, row2 = new DateField());\r
- glo.replaceComponent(row3, row3 = new DateField());\r
- glo.setComponentAlignment(col2, alignments[6]);\r
- glo.setComponentAlignment(col3, alignments[7]);\r
- glo.setComponentAlignment(col1, alignments[8]);\r
- hlo.addComponent(glo);\r
- return hlo;\r
- }\r
- \r
- @Override\r
- protected Layout getCaptionsTests() {\r
- GridLayout glo = getTestGrid();\r
- glo.setWidth("600px");\r
- String[] captions = new String[] {\r
- "",\r
- "abcdefghijklmnopq",\r
- "abc def hij klm nop qrs tuv xyz qaz wsx edc rfv tgb yhn ujm mko nji bhu vgy cft cde" };\r
- glo.replaceComponent(col1, col1 = new TextField());\r
- glo.replaceComponent(col2, col2 = new TextField());\r
- glo.replaceComponent(col3, col3 = new TextField());\r
- \r
- col1.setCaption(captions[0]);\r
- col2.setCaption(captions[1]);\r
- col3.setCaption(captions[2]);\r
- col3.setIcon(new ThemeResource(LOCK_16_PNG));\r
- \r
- glo.replaceComponent(row1, row1 = new Label());\r
- glo.replaceComponent(row2, row2 = new Label());\r
- glo.replaceComponent(row3, row3 = new Label());\r
- \r
- row1.setCaption(captions[0]);\r
- row2.setCaption(captions[1]);\r
- row3.setCaption(captions[2]);\r
- \r
- glo.replaceComponent(x3, x3 = getTestTabsheet());\r
- glo.replaceComponent(x22, x22 = getTestTable());\r
- x22.setComponentError(new UserError("component error, user error"));\r
- \r
- x3.setCaption(captions[1]);\r
- x22.setCaption(captions[2]);\r
- \r
- return glo;\r
- }\r
- \r
- @Override\r
- protected Layout getComponentAddReplaceMoveTests() {\r
- final GridLayout glo = getTestGrid();\r
- glo.setHeight("350px");\r
- Layout baseLayout = getBaseLayout();\r
- final Button button1 = new Button("Test add");\r
- final Button button2 = new Button("Test replace");\r
- final Button button3 = new Button("Test move");\r
- final Button button4 = new Button("Test remove comp 1,1");\r
- final Button button5 = new Button("Test remove row 0");\r
- final Button button6 = new Button("Test remove comp row3");\r
- \r
- baseLayout.addComponent(button1);\r
- baseLayout.addComponent(button2);\r
- baseLayout.addComponent(button3);\r
- baseLayout.addComponent(button4);\r
- baseLayout.addComponent(button5);\r
- baseLayout.addComponent(button6);\r
- baseLayout.addComponent(glo);\r
- button1.setEnabled(true);\r
- button2.setEnabled(false);\r
- button3.setEnabled(false);\r
- button4.setEnabled(false);\r
- button5.setEnabled(false);\r
- button6.setEnabled(false);\r
- \r
- final HorizontalLayout source = new HorizontalLayout();\r
- source.addComponent(new Label("MOVE LABEL 1"));\r
- source.addComponent(new Label("MOVE LABEL 2"));\r
- \r
- final AbstractComponent cc1 = getTestTabsheet();\r
- cc1.setCaption("ADDED COMPONENT");\r
- \r
- final AbstractComponent cc2 = getTestTabsheet();\r
- cc2.setCaption("REPLACEMENT COMPONENT");\r
- \r
- button1.addListener(new Button.ClickListener() {\r
- private static final long serialVersionUID = 7716267156088629379L;\r
- \r
- public void buttonClick(ClickEvent event) {\r
- glo.addComponent(cc1);\r
- button1.setEnabled(false);\r
- button2.setEnabled(true);\r
- }\r
- });\r
- button2.addListener(new Button.ClickListener() {\r
- private static final long serialVersionUID = 7716267156088629379L;\r
- \r
- public void buttonClick(ClickEvent event) {\r
- glo.replaceComponent(x22, cc2);\r
- button2.setEnabled(false);\r
- button3.setEnabled(true);\r
- }\r
- });\r
- button3.addListener(new Button.ClickListener() {\r
- private static final long serialVersionUID = 7716267156088629379L;\r
- \r
- public void buttonClick(ClickEvent event) {\r
- glo.moveComponentsFrom(source);\r
- button3.setEnabled(false);\r
- button4.setEnabled(true);\r
- }\r
- });\r
- button4.addListener(new Button.ClickListener() {\r
- private static final long serialVersionUID = 7716267156088629379L;\r
- \r
- public void buttonClick(ClickEvent event) {\r
- glo.removeComponent(1, 1);\r
- button4.setEnabled(false);\r
- button5.setEnabled(true);\r
- }\r
- });\r
- \r
- button5.addListener(new Button.ClickListener() {\r
- private static final long serialVersionUID = 7716267156088629379L;\r
- \r
- public void buttonClick(ClickEvent event) {\r
- glo.removeRow(0);\r
- button5.setEnabled(false);\r
- button6.setEnabled(true);\r
- }\r
- });\r
- button6.addListener(new Button.ClickListener() {\r
- private static final long serialVersionUID = 7716267156088629379L;\r
- \r
- public void buttonClick(ClickEvent event) {\r
- glo.removeComponent(row3);\r
- button6.setEnabled(false);\r
- }\r
- });\r
- \r
- return baseLayout;\r
- }\r
- \r
- @Override\r
- protected Layout getComponentSizingTests() {\r
- final GridLayout glo = getTestGrid();\r
- glo.setHeight("350px");\r
- Layout baseLayout = getBaseLayout();\r
- final Button button1 = new Button("full size, 3x1");\r
- final Button button2 = new Button("200 px width, 3x1");\r
- final Button button3 = new Button("200 px width, table");\r
- final Button button4 = new Button("undefined size+add, table");\r
- \r
- glo.replaceComponent(x22, x22 = getTestTable());\r
- \r
- baseLayout.addComponent(button1);\r
- baseLayout.addComponent(button2);\r
- baseLayout.addComponent(button3);\r
- baseLayout.addComponent(button4);\r
- baseLayout.addComponent(glo);\r
- button1.setEnabled(true);\r
- button2.setEnabled(false);\r
- button3.setEnabled(false);\r
- button4.setEnabled(false);\r
- \r
- button1.addListener(new Button.ClickListener() {\r
- private static final long serialVersionUID = 7716267156088629379L;\r
- \r
- public void buttonClick(ClickEvent event) {\r
- x3.setSizeFull();\r
- button1.setEnabled(false);\r
- button2.setEnabled(true);\r
- }\r
- });\r
- button2.addListener(new Button.ClickListener() {\r
- private static final long serialVersionUID = 7716267156088629379L;\r
- \r
- public void buttonClick(ClickEvent event) {\r
- x3.setWidth("200px");\r
- button2.setEnabled(false);\r
- button3.setEnabled(true);\r
- }\r
- });\r
- button3.addListener(new Button.ClickListener() {\r
- private static final long serialVersionUID = 7716267156088629379L;\r
- \r
- public void buttonClick(ClickEvent event) {\r
- x22.setWidth("200px");\r
- button3.setEnabled(false);\r
- button4.setEnabled(true);\r
- }\r
- });\r
- button4.addListener(new Button.ClickListener() {\r
- private static final long serialVersionUID = 7716267156088629379L;\r
- \r
- public void buttonClick(ClickEvent event) {\r
- x22.setSizeUndefined();\r
- ((Table) x22).addItem(new Object[] { "NEW ROW1" }, 3);\r
- ((Table) x22).addItem(new Object[] { "NEW ROW2" }, 4);\r
- button4.setEnabled(false);\r
- }\r
- });\r
- \r
- return baseLayout;\r
- }\r
- \r
- @Override\r
- protected Layout getExpandRatiosTests() {\r
- final GridLayout glo = getTestGrid();\r
- Layout baseLayout = getBaseLayout();\r
- final Button button1 = new Button("set col 3 expand 1");\r
- final Button button2 = new Button("set all cols expand 0.25");\r
- final Button button3 = new Button("set row 0 expand 0.5");\r
- final Button button4 = new Button("set row 3 expand 0.2");\r
- glo.setHeight("400px");\r
- glo.replaceComponent(x22, x22 = getTestTable());\r
- \r
- baseLayout.addComponent(button1);\r
- baseLayout.addComponent(button2);\r
- baseLayout.addComponent(button3);\r
- baseLayout.addComponent(button4);\r
- baseLayout.addComponent(glo);\r
- button1.setEnabled(true);\r
- button2.setEnabled(false);\r
- button3.setEnabled(false);\r
- button4.setEnabled(false);\r
- \r
- button1.addListener(new Button.ClickListener() {\r
- private static final long serialVersionUID = 7716267156088629379L;\r
- \r
- public void buttonClick(ClickEvent event) {\r
- glo.setColumnExpandRatio(3, 1);\r
- button1.setEnabled(false);\r
- button2.setEnabled(true);\r
- }\r
- });\r
- button2.addListener(new Button.ClickListener() {\r
- private static final long serialVersionUID = 7716267156088629379L;\r
- \r
- public void buttonClick(ClickEvent event) {\r
- glo.setColumnExpandRatio(0, 0.25f);\r
- glo.setColumnExpandRatio(1, 0.25f);\r
- glo.setColumnExpandRatio(2, 0.25f);\r
- glo.setColumnExpandRatio(3, 0.25f);\r
- button2.setEnabled(false);\r
- button3.setEnabled(true);\r
- }\r
- });\r
- button3.addListener(new Button.ClickListener() {\r
- private static final long serialVersionUID = 7716267156088629379L;\r
- \r
- public void buttonClick(ClickEvent event) {\r
- glo.setRowExpandRatio(0, 0.5f);\r
- button3.setEnabled(false);\r
- button4.setEnabled(true);\r
- }\r
- });\r
- button4.addListener(new Button.ClickListener() {\r
- private static final long serialVersionUID = 7716267156088629379L;\r
- \r
- public void buttonClick(ClickEvent event) {\r
- glo.setRowExpandRatio(3, 0.3f);\r
- button4.setEnabled(false);\r
- }\r
- });\r
- \r
- return baseLayout;\r
- }\r
- \r
- @Override\r
- protected Layout getIconsTests() {\r
- GridLayout glo = getTestGrid();\r
- glo.setWidth("600px");\r
- Resource[] icons = new Resource[] { new ThemeResource(CALENDAR_32_PNG),\r
- new ThemeResource(LOCK_16_PNG) };\r
- \r
- glo.replaceComponent(col1, col1 = new TextField("TEXTFIELD"));\r
- glo.replaceComponent(col2, col2 = new Label("LABEL"));\r
- glo.replaceComponent(col3, col3 = new Link("LINK", null));\r
- \r
- col1.setIcon(icons[0]);\r
- col2.setIcon(icons[1]);\r
- col3.setIcon(icons[0]);\r
- rc1.setIcon(icons[1]);\r
- col3.setCaption("long test caption bewucbwuebco or bmort b cbwecubw wbeucwe asdasd asdasda asdasd");\r
- col3.setComponentError(new UserError("component error, user error"));\r
- \r
- glo.replaceComponent(row1, row1 = new DateField());\r
- glo.replaceComponent(row2, row2 = new NativeSelect());\r
- glo.replaceComponent(row3, row3 = getTestTabsheet());\r
- \r
- row1.setIcon(icons[1]);\r
- row2.setIcon(icons[0]);\r
- row3.setIcon(icons[1]);\r
- \r
- glo.replaceComponent(x3, x3 = new CheckBox("CHECKBOX"));\r
- glo.replaceComponent(x22, x22 = new Panel("PANEL"));\r
- x22.setIcon(new ThemeResource(CALENDAR_32_PNG));\r
- \r
- x3.setIcon(icons[0]);\r
- x22.setIcon(icons[1]);\r
- \r
- return glo;\r
- }\r
- \r
- @Override\r
- protected Layout getLayoutSizingTests() {\r
- final GridLayout glo = getTestGrid();\r
- Layout baseLayout = getBaseLayout();\r
- baseLayout.setWidth("500px");\r
- baseLayout.setHeight("500px");\r
- final Button button1 = new Button("Set fixed height 350px");\r
- final Button button2 = new Button(\r
- "Set undefined size and add component");\r
- final Button button3 = new Button("Set fixed width and height 75%");\r
- final Button button4 = new Button("Set size full");\r
- \r
- glo.replaceComponent(x22, x22 = getTestTable());\r
- \r
- baseLayout.addComponent(button1);\r
- baseLayout.addComponent(button2);\r
- baseLayout.addComponent(button3);\r
- baseLayout.addComponent(button4);\r
- baseLayout.addComponent(glo);\r
- button1.setEnabled(true);\r
- button2.setEnabled(false);\r
- button3.setEnabled(false);\r
- button4.setEnabled(false);\r
- \r
- button1.addListener(new Button.ClickListener() {\r
- private static final long serialVersionUID = 7716267156088629379L;\r
- \r
- public void buttonClick(ClickEvent event) {\r
- glo.setHeight("350px");\r
- button1.setEnabled(false);\r
- button2.setEnabled(true);\r
- }\r
- });\r
- button2.addListener(new Button.ClickListener() {\r
- private static final long serialVersionUID = 7716267156088629379L;\r
- \r
- public void buttonClick(ClickEvent event) {\r
- glo.setSizeUndefined();\r
- glo.addComponent(new Label("--- NEW LABEL ---"));\r
- button2.setEnabled(false);\r
- button3.setEnabled(true);\r
- }\r
- });\r
- button3.addListener(new Button.ClickListener() {\r
- private static final long serialVersionUID = 7716267156088629379L;\r
- \r
- public void buttonClick(ClickEvent event) {\r
- glo.setWidth("75%");\r
- glo.setHeight("75%");\r
- button3.setEnabled(false);\r
- button4.setEnabled(true);\r
- }\r
- });\r
- button4.addListener(new Button.ClickListener() {\r
- private static final long serialVersionUID = 7716267156088629379L;\r
- \r
- public void buttonClick(ClickEvent event) {\r
- glo.setSizeFull();\r
- button4.setEnabled(false);\r
- }\r
- });\r
- \r
- return baseLayout;\r
- }\r
- \r
- @Override\r
- protected Layout getMarginSpacingTests() {\r
- final GridLayout glo = getTestGrid();\r
- Layout baseLayout = getBaseLayout();\r
- baseLayout.setWidth("500px");\r
- baseLayout.setHeight("500px");\r
- final Button button1 = new Button("Set margin on");\r
- final Button button2 = new Button("Set spacing on");\r
- final Button button3 = new Button("Set margin off");\r
- final Button button4 = new Button("Set spacing off");\r
- \r
- baseLayout.addComponent(button1);\r
- baseLayout.addComponent(button2);\r
- baseLayout.addComponent(button3);\r
- baseLayout.addComponent(button4);\r
- button1.setEnabled(true);\r
- button2.setEnabled(false);\r
- button3.setEnabled(false);\r
- button4.setEnabled(false);\r
- \r
- baseLayout.addComponent(glo);\r
- \r
- button1.addListener(new Button.ClickListener() {\r
- private static final long serialVersionUID = 7716267156088629379L;\r
- \r
- public void buttonClick(ClickEvent event) {\r
- glo.setMargin(true);\r
- button1.setEnabled(false);\r
- button2.setEnabled(true);\r
- }\r
- });\r
- button2.addListener(new Button.ClickListener() {\r
- private static final long serialVersionUID = 7716267156088629379L;\r
- \r
- public void buttonClick(ClickEvent event) {\r
- glo.setSpacing(true);\r
- button2.setEnabled(false);\r
- button3.setEnabled(true);\r
- }\r
- });\r
- button3.addListener(new Button.ClickListener() {\r
- private static final long serialVersionUID = 7716267156088629379L;\r
- \r
- public void buttonClick(ClickEvent event) {\r
- glo.setMargin(false);\r
- button3.setEnabled(false);\r
- button4.setEnabled(true);\r
- }\r
- });\r
- button4.addListener(new Button.ClickListener() {\r
- private static final long serialVersionUID = 7716267156088629379L;\r
- \r
- public void buttonClick(ClickEvent event) {\r
- glo.setSpacing(false);\r
- button4.setEnabled(false);\r
- }\r
- });\r
- \r
- return baseLayout;\r
- }\r
- \r
- @Override\r
- protected Layout getRequiredErrorIndicatorsTests() {\r
- GridLayout glo = getTestGrid();\r
- glo.setWidth("600px");\r
- Resource[] icons = new Resource[] { new ThemeResource(CALENDAR_32_PNG),\r
- new ThemeResource(LOCK_16_PNG) };\r
- \r
- glo.replaceComponent(col1, col1 = new TextField("TEXTFIELD"));\r
- glo.replaceComponent(col2, col2 = new Label("LABEL"));\r
- glo.replaceComponent(col3, col3 = new Link("LINK", null));\r
- \r
- col1.setIcon(icons[0]);\r
- col1.setComponentError(new UserError("component error, user error"));\r
- col2.setComponentError(new SystemError("component error, system error"));\r
- col3.setComponentError(new UserError("component error, user error"));\r
- \r
- glo.replaceComponent(row1, row1 = new DateField());\r
- glo.replaceComponent(row2, row2 = new NativeSelect());\r
- glo.replaceComponent(row3, row3 = getTestTabsheet());\r
- \r
- ((AbstractField<?>) col1).setRequired(true);\r
- ((AbstractField<?>) col1).setValidationVisible(true);\r
- ((AbstractField<?>) col1).setRequiredError("required error");\r
- \r
- ((AbstractField<?>) row1).setRequired(true);\r
- ((AbstractField<?>) row1).setValidationVisible(true);\r
- ((AbstractField<?>) row1).setRequiredError("required error");\r
- \r
- ((AbstractField<?>) row2).setRequired(true);\r
- ((AbstractField<?>) row2).setValidationVisible(true);\r
- ((AbstractField<?>) row2).setRequiredError("required error");\r
- row2.setComponentError(new UserError("component error, user error"));\r
- \r
- row3.setComponentError(new UserError("component error, user error"));\r
- row3.setIcon(icons[1]);\r
- row3.setCaption("long test caption bewucbwuebco or bmort b cbwecubw wbeucwe asdasd asdasda asdasd");\r
- \r
- glo.replaceComponent(x3, x3 = new CheckBox("CHECKBOX"));\r
- glo.replaceComponent(x22, x22 = new Panel("PANEL"));\r
- \r
- x3.setComponentError(new UserError("component error, user error"));\r
- x22.setComponentError(new UserError("component error, user error"));\r
- x22.setIcon(icons[0]);\r
- \r
- return glo;\r
- }\r
- \r
- private GridLayout getTestGrid() {\r
- // Create a 4 by 4 grid layout.\r
- GridLayout grid = new GridLayout(4, 4);\r
- // Fill out the first row using the cursor.\r
- grid.addComponent(rc1 = new Button("R/C 1"));\r
- \r
- grid.addComponent(col1 = new Button("Col " + (grid.getCursorX() + 1)));\r
- grid.addComponent(col2 = new Button("Col " + (grid.getCursorX() + 1)));\r
- grid.addComponent(col3 = new Button("Col " + (grid.getCursorX() + 1)));\r
- \r
- // Fill out the first column using coordinates.\r
- \r
- grid.addComponent(row1 = new Button("Row " + 1), 0, 1);\r
- grid.addComponent(row2 = new Button("Row " + 2), 0, 2);\r
- grid.addComponent(row3 = new Button("Row " + 3), 0, 3);\r
- \r
- // Add some components of various shapes.\r
- grid.addComponent(x3 = new Button("3x1 button"), 1, 1, 3, 1);\r
- grid.addComponent(new Label("1x2 cell"), 1, 2, 1, 3);\r
- x22 = new InlineDateField("A 2x2 date field");\r
- ((InlineDateField) x22).setResolution(DateField.RESOLUTION_DAY);\r
- ((InlineDateField) x22).setValue(new Date(128028960000l));\r
- grid.addComponent(x22, 2, 2, 3, 3);\r
- grid.setWidth("450px");\r
- grid.setHeight("450px");\r
- return grid;\r
- }\r
- \r
- private VerticalLayout getBaseLayout() {\r
- VerticalLayout vlo = new VerticalLayout();\r
- vlo.setSizeUndefined();\r
- return vlo;\r
- }\r
- \r
- private AbstractComponent getTestTabsheet() {\r
- TabSheet tabsheet = new TabSheet();\r
- tabsheet.setSizeUndefined();\r
- tabsheet.addTab(new UndefWideLabel("TAB1"), "TAB1", new ThemeResource(\r
- GLOBE_16_PNG));\r
- tabsheet.addTab(new UndefWideLabel("TAB2"), "TAB2", null);\r
- return tabsheet;\r
- }\r
- \r
- private Table getTestTable() {\r
- Table t = new Table();\r
- t.setSizeUndefined();\r
- t.setPageLength(5);\r
- t.addContainerProperty("test", String.class, null);\r
- t.addItem(new Object[] { "qwertyuiop asdfghjklzxccvbnm,m,." }, 1);\r
- t.addItem(new Object[] { "YGVYTCTCTRXRXRXRX" }, 2);\r
- return t;\r
- }\r
- \r
- }\r
+ package com.vaadin.tests.layouts.layouttester;
+
+ import java.util.Date;
+
+ import com.vaadin.Application;
+ import com.vaadin.terminal.Resource;
+ import com.vaadin.terminal.SystemError;
+ import com.vaadin.terminal.ThemeResource;
+ import com.vaadin.terminal.UserError;
+ import com.vaadin.ui.AbstractComponent;
+ import com.vaadin.ui.AbstractField;
+ import com.vaadin.ui.Alignment;
+ import com.vaadin.ui.Button;
+ import com.vaadin.ui.Button.ClickEvent;
+ import com.vaadin.ui.CheckBox;
+ import com.vaadin.ui.DateField;
+ import com.vaadin.ui.GridLayout;
+ import com.vaadin.ui.HorizontalLayout;
+ import com.vaadin.ui.InlineDateField;
+ import com.vaadin.ui.Label;
+ import com.vaadin.ui.Layout;
+ import com.vaadin.ui.Link;
+ import com.vaadin.ui.NativeSelect;
+ import com.vaadin.ui.Panel;
+ import com.vaadin.ui.TabSheet;
+ import com.vaadin.ui.Table;
+ import com.vaadin.ui.TextField;
+ import com.vaadin.ui.VerticalLayout;
+ import com.vaadin.ui.themes.Reindeer;
+
+ public class GridLayoutTests extends AbstractLayoutTests {
+
+ private AbstractComponent rc1, col1, col2, col3, row1, row2, row3, x3, x22;
+
+ public GridLayoutTests(Application application) {
+ super();
+ }
+
+ @Override
+ protected Layout getAlignmentTests() {
+ HorizontalLayout hlo = new HorizontalLayout();
+ hlo.setSpacing(true);
+ GridLayout glo = getTestGrid();
+ glo.addStyleName(Reindeer.LAYOUT_WHITE);
+ Alignment[] alignments = new Alignment[] { Alignment.BOTTOM_LEFT,
+ Alignment.BOTTOM_CENTER, Alignment.BOTTOM_RIGHT,
+ Alignment.MIDDLE_LEFT, Alignment.MIDDLE_CENTER,
+ Alignment.MIDDLE_RIGHT, Alignment.TOP_LEFT,
+ Alignment.TOP_CENTER, Alignment.TOP_RIGHT };
+
+ glo.replaceComponent(col1, col1 = new TextField());
+ glo.replaceComponent(col2, col2 = new TextField());
+ glo.replaceComponent(col3, col3 = new TextField());
+ ((TextField) col1).setValue("BOTTOM_RIGHT");
+ ((TextField) col2).setValue("BOTTOM_LEFT");
+ ((TextField) col3).setValue("BOTTOM_CENTER");
+ glo.setComponentAlignment(col2, alignments[0]);
+ glo.setComponentAlignment(col3, alignments[1]);
+ glo.setComponentAlignment(col1, alignments[2]);
+
+ glo.setComponentAlignment(row1, alignments[3]);
+ glo.setComponentAlignment(row2, alignments[4]);
+ glo.setComponentAlignment(row3, alignments[5]);
+ hlo.addComponent(glo);
+ glo = getTestGrid();
+ glo.replaceComponent(row1, row1 = new DateField());
+ glo.replaceComponent(row2, row2 = new DateField());
+ glo.replaceComponent(row3, row3 = new DateField());
+ glo.setComponentAlignment(col2, alignments[6]);
+ glo.setComponentAlignment(col3, alignments[7]);
+ glo.setComponentAlignment(col1, alignments[8]);
+ hlo.addComponent(glo);
+ return hlo;
+ }
+
+ @Override
+ protected Layout getCaptionsTests() {
+ GridLayout glo = getTestGrid();
+ glo.setWidth("600px");
+ String[] captions = new String[] {
+ "",
+ "abcdefghijklmnopq",
+ "abc def hij klm nop qrs tuv xyz qaz wsx edc rfv tgb yhn ujm mko nji bhu vgy cft cde" };
+ glo.replaceComponent(col1, col1 = new TextField());
+ glo.replaceComponent(col2, col2 = new TextField());
+ glo.replaceComponent(col3, col3 = new TextField());
+
+ col1.setCaption(captions[0]);
+ col2.setCaption(captions[1]);
+ col3.setCaption(captions[2]);
+ col3.setIcon(new ThemeResource(LOCK_16_PNG));
+
+ glo.replaceComponent(row1, row1 = new Label());
+ glo.replaceComponent(row2, row2 = new Label());
+ glo.replaceComponent(row3, row3 = new Label());
+
+ row1.setCaption(captions[0]);
+ row2.setCaption(captions[1]);
+ row3.setCaption(captions[2]);
+
+ glo.replaceComponent(x3, x3 = getTestTabsheet());
+ glo.replaceComponent(x22, x22 = getTestTable());
+ x22.setComponentError(new UserError("component error, user error"));
+
+ x3.setCaption(captions[1]);
+ x22.setCaption(captions[2]);
+
+ return glo;
+ }
+
+ @Override
+ protected Layout getComponentAddReplaceMoveTests() {
+ final GridLayout glo = getTestGrid();
+ glo.setHeight("350px");
+ Layout baseLayout = getBaseLayout();
+ final Button button1 = new Button("Test add");
+ final Button button2 = new Button("Test replace");
+ final Button button3 = new Button("Test move");
+ final Button button4 = new Button("Test remove comp 1,1");
+ final Button button5 = new Button("Test remove row 0");
+ final Button button6 = new Button("Test remove comp row3");
+
+ baseLayout.addComponent(button1);
+ baseLayout.addComponent(button2);
+ baseLayout.addComponent(button3);
+ baseLayout.addComponent(button4);
+ baseLayout.addComponent(button5);
+ baseLayout.addComponent(button6);
+ baseLayout.addComponent(glo);
+ button1.setEnabled(true);
+ button2.setEnabled(false);
+ button3.setEnabled(false);
+ button4.setEnabled(false);
+ button5.setEnabled(false);
+ button6.setEnabled(false);
+
+ final HorizontalLayout source = new HorizontalLayout();
+ source.addComponent(new Label("MOVE LABEL 1"));
+ source.addComponent(new Label("MOVE LABEL 2"));
+
+ final AbstractComponent cc1 = getTestTabsheet();
+ cc1.setCaption("ADDED COMPONENT");
+
+ final AbstractComponent cc2 = getTestTabsheet();
+ cc2.setCaption("REPLACEMENT COMPONENT");
+
+ button1.addListener(new Button.ClickListener() {
+ private static final long serialVersionUID = 7716267156088629379L;
+
+ public void buttonClick(ClickEvent event) {
+ glo.addComponent(cc1);
+ button1.setEnabled(false);
+ button2.setEnabled(true);
+ }
+ });
+ button2.addListener(new Button.ClickListener() {
+ private static final long serialVersionUID = 7716267156088629379L;
+
+ public void buttonClick(ClickEvent event) {
+ glo.replaceComponent(x22, cc2);
+ button2.setEnabled(false);
+ button3.setEnabled(true);
+ }
+ });
+ button3.addListener(new Button.ClickListener() {
+ private static final long serialVersionUID = 7716267156088629379L;
+
+ public void buttonClick(ClickEvent event) {
+ glo.moveComponentsFrom(source);
+ button3.setEnabled(false);
+ button4.setEnabled(true);
+ }
+ });
+ button4.addListener(new Button.ClickListener() {
+ private static final long serialVersionUID = 7716267156088629379L;
+
+ public void buttonClick(ClickEvent event) {
+ glo.removeComponent(1, 1);
+ button4.setEnabled(false);
+ button5.setEnabled(true);
+ }
+ });
+
+ button5.addListener(new Button.ClickListener() {
+ private static final long serialVersionUID = 7716267156088629379L;
+
+ public void buttonClick(ClickEvent event) {
+ glo.removeRow(0);
+ button5.setEnabled(false);
+ button6.setEnabled(true);
+ }
+ });
+ button6.addListener(new Button.ClickListener() {
+ private static final long serialVersionUID = 7716267156088629379L;
+
+ public void buttonClick(ClickEvent event) {
+ glo.removeComponent(row3);
+ button6.setEnabled(false);
+ }
+ });
+
+ return baseLayout;
+ }
+
+ @Override
+ protected Layout getComponentSizingTests() {
+ final GridLayout glo = getTestGrid();
+ glo.setHeight("350px");
+ Layout baseLayout = getBaseLayout();
+ final Button button1 = new Button("full size, 3x1");
+ final Button button2 = new Button("200 px width, 3x1");
+ final Button button3 = new Button("200 px width, table");
+ final Button button4 = new Button("undefined size+add, table");
+
+ glo.replaceComponent(x22, x22 = getTestTable());
+
+ baseLayout.addComponent(button1);
+ baseLayout.addComponent(button2);
+ baseLayout.addComponent(button3);
+ baseLayout.addComponent(button4);
+ baseLayout.addComponent(glo);
+ button1.setEnabled(true);
+ button2.setEnabled(false);
+ button3.setEnabled(false);
+ button4.setEnabled(false);
+
+ button1.addListener(new Button.ClickListener() {
+ private static final long serialVersionUID = 7716267156088629379L;
+
+ public void buttonClick(ClickEvent event) {
+ x3.setSizeFull();
+ button1.setEnabled(false);
+ button2.setEnabled(true);
+ }
+ });
+ button2.addListener(new Button.ClickListener() {
+ private static final long serialVersionUID = 7716267156088629379L;
+
+ public void buttonClick(ClickEvent event) {
+ x3.setWidth("200px");
+ button2.setEnabled(false);
+ button3.setEnabled(true);
+ }
+ });
+ button3.addListener(new Button.ClickListener() {
+ private static final long serialVersionUID = 7716267156088629379L;
+
+ public void buttonClick(ClickEvent event) {
+ x22.setWidth("200px");
+ button3.setEnabled(false);
+ button4.setEnabled(true);
+ }
+ });
+ button4.addListener(new Button.ClickListener() {
+ private static final long serialVersionUID = 7716267156088629379L;
+
+ public void buttonClick(ClickEvent event) {
+ x22.setSizeUndefined();
+ ((Table) x22).addItem(new Object[] { "NEW ROW1" }, 3);
+ ((Table) x22).addItem(new Object[] { "NEW ROW2" }, 4);
+ button4.setEnabled(false);
+ }
+ });
+
+ return baseLayout;
+ }
+
+ @Override
+ protected Layout getExpandRatiosTests() {
+ final GridLayout glo = getTestGrid();
+ Layout baseLayout = getBaseLayout();
+ final Button button1 = new Button("set col 3 expand 1");
+ final Button button2 = new Button("set all cols expand 0.25");
+ final Button button3 = new Button("set row 0 expand 0.5");
+ final Button button4 = new Button("set row 3 expand 0.2");
+ glo.setHeight("400px");
+ glo.replaceComponent(x22, x22 = getTestTable());
+
+ baseLayout.addComponent(button1);
+ baseLayout.addComponent(button2);
+ baseLayout.addComponent(button3);
+ baseLayout.addComponent(button4);
+ baseLayout.addComponent(glo);
+ button1.setEnabled(true);
+ button2.setEnabled(false);
+ button3.setEnabled(false);
+ button4.setEnabled(false);
+
+ button1.addListener(new Button.ClickListener() {
+ private static final long serialVersionUID = 7716267156088629379L;
+
+ public void buttonClick(ClickEvent event) {
+ glo.setColumnExpandRatio(3, 1);
+ button1.setEnabled(false);
+ button2.setEnabled(true);
+ }
+ });
+ button2.addListener(new Button.ClickListener() {
+ private static final long serialVersionUID = 7716267156088629379L;
+
+ public void buttonClick(ClickEvent event) {
+ glo.setColumnExpandRatio(0, 0.25f);
+ glo.setColumnExpandRatio(1, 0.25f);
+ glo.setColumnExpandRatio(2, 0.25f);
+ glo.setColumnExpandRatio(3, 0.25f);
+ button2.setEnabled(false);
+ button3.setEnabled(true);
+ }
+ });
+ button3.addListener(new Button.ClickListener() {
+ private static final long serialVersionUID = 7716267156088629379L;
+
+ public void buttonClick(ClickEvent event) {
+ glo.setRowExpandRatio(0, 0.5f);
+ button3.setEnabled(false);
+ button4.setEnabled(true);
+ }
+ });
+ button4.addListener(new Button.ClickListener() {
+ private static final long serialVersionUID = 7716267156088629379L;
+
+ public void buttonClick(ClickEvent event) {
+ glo.setRowExpandRatio(3, 0.3f);
+ button4.setEnabled(false);
+ }
+ });
+
+ return baseLayout;
+ }
+
+ @Override
+ protected Layout getIconsTests() {
+ GridLayout glo = getTestGrid();
+ glo.setWidth("600px");
+ Resource[] icons = new Resource[] { new ThemeResource(CALENDAR_32_PNG),
+ new ThemeResource(LOCK_16_PNG) };
+
+ glo.replaceComponent(col1, col1 = new TextField("TEXTFIELD"));
+ glo.replaceComponent(col2, col2 = new Label("LABEL"));
+ glo.replaceComponent(col3, col3 = new Link("LINK", null));
+
+ col1.setIcon(icons[0]);
+ col2.setIcon(icons[1]);
+ col3.setIcon(icons[0]);
+ rc1.setIcon(icons[1]);
+ col3.setCaption("long test caption bewucbwuebco or bmort b cbwecubw wbeucwe asdasd asdasda asdasd");
+ col3.setComponentError(new UserError("component error, user error"));
+
+ glo.replaceComponent(row1, row1 = new DateField());
+ glo.replaceComponent(row2, row2 = new NativeSelect());
+ glo.replaceComponent(row3, row3 = getTestTabsheet());
+
+ row1.setIcon(icons[1]);
+ row2.setIcon(icons[0]);
+ row3.setIcon(icons[1]);
+
+ glo.replaceComponent(x3, x3 = new CheckBox("CHECKBOX"));
+ glo.replaceComponent(x22, x22 = new Panel("PANEL"));
+ x22.setIcon(new ThemeResource(CALENDAR_32_PNG));
+
+ x3.setIcon(icons[0]);
+ x22.setIcon(icons[1]);
+
+ return glo;
+ }
+
+ @Override
+ protected Layout getLayoutSizingTests() {
+ final GridLayout glo = getTestGrid();
+ Layout baseLayout = getBaseLayout();
+ baseLayout.setWidth("500px");
+ baseLayout.setHeight("500px");
+ final Button button1 = new Button("Set fixed height 350px");
+ final Button button2 = new Button(
+ "Set undefined size and add component");
+ final Button button3 = new Button("Set fixed width and height 75%");
+ final Button button4 = new Button("Set size full");
+
+ glo.replaceComponent(x22, x22 = getTestTable());
+
+ baseLayout.addComponent(button1);
+ baseLayout.addComponent(button2);
+ baseLayout.addComponent(button3);
+ baseLayout.addComponent(button4);
+ baseLayout.addComponent(glo);
+ button1.setEnabled(true);
+ button2.setEnabled(false);
+ button3.setEnabled(false);
+ button4.setEnabled(false);
+
+ button1.addListener(new Button.ClickListener() {
+ private static final long serialVersionUID = 7716267156088629379L;
+
+ public void buttonClick(ClickEvent event) {
+ glo.setHeight("350px");
+ button1.setEnabled(false);
+ button2.setEnabled(true);
+ }
+ });
+ button2.addListener(new Button.ClickListener() {
+ private static final long serialVersionUID = 7716267156088629379L;
+
+ public void buttonClick(ClickEvent event) {
+ glo.setSizeUndefined();
+ glo.addComponent(new Label("--- NEW LABEL ---"));
+ button2.setEnabled(false);
+ button3.setEnabled(true);
+ }
+ });
+ button3.addListener(new Button.ClickListener() {
+ private static final long serialVersionUID = 7716267156088629379L;
+
+ public void buttonClick(ClickEvent event) {
+ glo.setWidth("75%");
+ glo.setHeight("75%");
+ button3.setEnabled(false);
+ button4.setEnabled(true);
+ }
+ });
+ button4.addListener(new Button.ClickListener() {
+ private static final long serialVersionUID = 7716267156088629379L;
+
+ public void buttonClick(ClickEvent event) {
+ glo.setSizeFull();
+ button4.setEnabled(false);
+ }
+ });
+
+ return baseLayout;
+ }
+
+ @Override
+ protected Layout getMarginSpacingTests() {
+ final GridLayout glo = getTestGrid();
+ Layout baseLayout = getBaseLayout();
+ baseLayout.setWidth("500px");
+ baseLayout.setHeight("500px");
+ final Button button1 = new Button("Set margin on");
+ final Button button2 = new Button("Set spacing on");
+ final Button button3 = new Button("Set margin off");
+ final Button button4 = new Button("Set spacing off");
+
+ baseLayout.addComponent(button1);
+ baseLayout.addComponent(button2);
+ baseLayout.addComponent(button3);
+ baseLayout.addComponent(button4);
+ button1.setEnabled(true);
+ button2.setEnabled(false);
+ button3.setEnabled(false);
+ button4.setEnabled(false);
+
+ baseLayout.addComponent(glo);
+
+ button1.addListener(new Button.ClickListener() {
+ private static final long serialVersionUID = 7716267156088629379L;
+
+ public void buttonClick(ClickEvent event) {
+ glo.setMargin(true);
+ button1.setEnabled(false);
+ button2.setEnabled(true);
+ }
+ });
+ button2.addListener(new Button.ClickListener() {
+ private static final long serialVersionUID = 7716267156088629379L;
+
+ public void buttonClick(ClickEvent event) {
+ glo.setSpacing(true);
+ button2.setEnabled(false);
+ button3.setEnabled(true);
+ }
+ });
+ button3.addListener(new Button.ClickListener() {
+ private static final long serialVersionUID = 7716267156088629379L;
+
+ public void buttonClick(ClickEvent event) {
+ glo.setMargin(false);
+ button3.setEnabled(false);
+ button4.setEnabled(true);
+ }
+ });
+ button4.addListener(new Button.ClickListener() {
+ private static final long serialVersionUID = 7716267156088629379L;
+
+ public void buttonClick(ClickEvent event) {
+ glo.setSpacing(false);
+ button4.setEnabled(false);
+ }
+ });
+
+ return baseLayout;
+ }
+
+ @Override
+ protected Layout getRequiredErrorIndicatorsTests() {
+ GridLayout glo = getTestGrid();
+ glo.setWidth("600px");
+ Resource[] icons = new Resource[] { new ThemeResource(CALENDAR_32_PNG),
+ new ThemeResource(LOCK_16_PNG) };
+
+ glo.replaceComponent(col1, col1 = new TextField("TEXTFIELD"));
+ glo.replaceComponent(col2, col2 = new Label("LABEL"));
+ glo.replaceComponent(col3, col3 = new Link("LINK", null));
+
+ col1.setIcon(icons[0]);
+ col1.setComponentError(new UserError("component error, user error"));
+ col2.setComponentError(new SystemError("component error, system error"));
+ col3.setComponentError(new UserError("component error, user error"));
+
+ glo.replaceComponent(row1, row1 = new DateField());
+ glo.replaceComponent(row2, row2 = new NativeSelect());
+ glo.replaceComponent(row3, row3 = getTestTabsheet());
+
- ((AbstractField) col1).setRequired(true);
- ((AbstractField) col1).setValidationVisible(true);
- ((AbstractField) col1).setRequiredError("required error");
++ ((AbstractField<?>) col1).setRequired(true);
++ ((AbstractField<?>) col1).setValidationVisible(true);
++ ((AbstractField<?>) col1).setRequiredError("required error");
+
- ((AbstractField) row1).setRequired(true);
- ((AbstractField) row1).setValidationVisible(true);
- ((AbstractField) row1).setRequiredError("required error");
++ ((AbstractField<?>) row1).setRequired(true);
++ ((AbstractField<?>) row1).setValidationVisible(true);
++ ((AbstractField<?>) row1).setRequiredError("required error");
+
- ((AbstractField) row2).setRequired(true);
- ((AbstractField) row2).setValidationVisible(true);
- ((AbstractField) row2).setRequiredError("required error");
++ ((AbstractField<?>) row2).setRequired(true);
++ ((AbstractField<?>) row2).setValidationVisible(true);
++ ((AbstractField<?>) row2).setRequiredError("required error");
+ row2.setComponentError(new UserError("component error, user error"));
+
+ row3.setComponentError(new UserError("component error, user error"));
+ row3.setIcon(icons[1]);
+ row3.setCaption("long test caption bewucbwuebco or bmort b cbwecubw wbeucwe asdasd asdasda asdasd");
+
+ glo.replaceComponent(x3, x3 = new CheckBox("CHECKBOX"));
+ glo.replaceComponent(x22, x22 = new Panel("PANEL"));
+
+ x3.setComponentError(new UserError("component error, user error"));
+ x22.setComponentError(new UserError("component error, user error"));
+ x22.setIcon(icons[0]);
+
+ return glo;
+ }
+
+ private GridLayout getTestGrid() {
+ // Create a 4 by 4 grid layout.
+ GridLayout grid = new GridLayout(4, 4);
+ // Fill out the first row using the cursor.
+ grid.addComponent(rc1 = new Button("R/C 1"));
+
+ grid.addComponent(col1 = new Button("Col " + (grid.getCursorX() + 1)));
+ grid.addComponent(col2 = new Button("Col " + (grid.getCursorX() + 1)));
+ grid.addComponent(col3 = new Button("Col " + (grid.getCursorX() + 1)));
+
+ // Fill out the first column using coordinates.
+
+ grid.addComponent(row1 = new Button("Row " + 1), 0, 1);
+ grid.addComponent(row2 = new Button("Row " + 2), 0, 2);
+ grid.addComponent(row3 = new Button("Row " + 3), 0, 3);
+
+ // Add some components of various shapes.
+ grid.addComponent(x3 = new Button("3x1 button"), 1, 1, 3, 1);
+ grid.addComponent(new Label("1x2 cell"), 1, 2, 1, 3);
+ x22 = new InlineDateField("A 2x2 date field");
+ ((InlineDateField) x22).setResolution(DateField.RESOLUTION_DAY);
+ ((InlineDateField) x22).setValue(new Date(128028960000l));
+ grid.addComponent(x22, 2, 2, 3, 3);
+ grid.setWidth("450px");
+ grid.setHeight("450px");
+ return grid;
+ }
+
+ private VerticalLayout getBaseLayout() {
+ VerticalLayout vlo = new VerticalLayout();
+ vlo.setSizeUndefined();
+ return vlo;
+ }
+
+ private AbstractComponent getTestTabsheet() {
+ TabSheet tabsheet = new TabSheet();
+ tabsheet.setSizeUndefined();
+ tabsheet.addTab(new UndefWideLabel("TAB1"), "TAB1", new ThemeResource(
+ GLOBE_16_PNG));
+ tabsheet.addTab(new UndefWideLabel("TAB2"), "TAB2", null);
+ return tabsheet;
+ }
+
+ private Table getTestTable() {
+ Table t = new Table();
+ t.setSizeUndefined();
+ t.setPageLength(5);
+ t.addContainerProperty("test", String.class, null);
+ t.addItem(new Object[] { "qwertyuiop asdfghjklzxccvbnm,m,." }, 1);
+ t.addItem(new Object[] { "YGVYTCTCTRXRXRXRX" }, 2);
+ return t;
+ }
+
+ }
- package com.vaadin.tests.layouts.layouttester;\r
- \r
- import com.vaadin.Application;\r
- import com.vaadin.terminal.Resource;\r
- import com.vaadin.terminal.SystemError;\r
- import com.vaadin.terminal.ThemeResource;\r
- import com.vaadin.terminal.UserError;\r
- import com.vaadin.ui.AbstractComponent;\r
- import com.vaadin.ui.AbstractField;\r
- import com.vaadin.ui.Alignment;\r
- import com.vaadin.ui.Button;\r
- import com.vaadin.ui.Button.ClickEvent;\r
- import com.vaadin.ui.CheckBox;\r
- import com.vaadin.ui.DateField;\r
- import com.vaadin.ui.HorizontalLayout;\r
- import com.vaadin.ui.Label;\r
- import com.vaadin.ui.Label.ContentMode;\r
- import com.vaadin.ui.Layout;\r
- import com.vaadin.ui.Link;\r
- import com.vaadin.ui.Select;\r
- import com.vaadin.ui.TabSheet;\r
- import com.vaadin.ui.Table;\r
- import com.vaadin.ui.TextField;\r
- import com.vaadin.ui.VerticalLayout;\r
- import com.vaadin.ui.themes.Reindeer;\r
- \r
- public class HorizontalLayoutTests extends AbstractLayoutTests {\r
- \r
- public HorizontalLayoutTests(Application application) {\r
- super();\r
- }\r
- \r
- @Override\r
- protected Layout getAlignmentTests() {\r
- Layout baseLayout = getBaseLayout();\r
- HorizontalLayout vlo = getTestLaytout();\r
- AbstractComponent[] components = new AbstractComponent[9];\r
- String[] styles = { Reindeer.LAYOUT_BLUE, Reindeer.LAYOUT_WHITE };\r
- Alignment[] alignments = new Alignment[] { Alignment.BOTTOM_LEFT,\r
- Alignment.BOTTOM_CENTER, Alignment.BOTTOM_RIGHT,\r
- Alignment.MIDDLE_LEFT, Alignment.MIDDLE_CENTER,\r
- Alignment.MIDDLE_RIGHT, Alignment.TOP_LEFT,\r
- Alignment.TOP_CENTER, Alignment.TOP_RIGHT };\r
- \r
- vlo.addStyleName(Reindeer.LAYOUT_WHITE);\r
- baseLayout.addComponent(vlo);\r
- int index = 0;\r
- for (int i = 0; i < components.length; i++) {\r
- if (i > 0 && i % 3 == 0) {\r
- vlo = getTestLaytout();\r
- vlo.addStyleName(styles[index++]);\r
- baseLayout.addComponent(vlo);\r
- }\r
- components[i] = new TextField();\r
- ((TextField) components[i]).setValue("FIELD " + i);\r
- vlo.addComponent(components[i]);\r
- vlo.setComponentAlignment(components[i], alignments[i]);\r
- }\r
- return baseLayout;\r
- }\r
- \r
- @Override\r
- protected Layout getCaptionsTests() {\r
- Layout baseLayout = getBaseLayout();\r
- AbstractComponent component = null;\r
- \r
- String[] captions = new String[] {\r
- "",\r
- "abcdefghijklmnopq",\r
- "abc def hij klm nop qrs tuv xyz qaz wsx edc rfv tgb yhn ujm mko nji bhu vgy cft cde" };\r
- \r
- HorizontalLayout vlo = getTestLaytout();\r
- for (int i = 0; i < captions.length; i++) {\r
- component = new TextField();\r
- ((TextField) component).setValue("FIELD " + i);\r
- component.setCaption(captions[i]);\r
- vlo.addComponent(component);\r
- }\r
- baseLayout.addComponent(vlo);\r
- vlo = getTestLaytout();\r
- for (int i = 0; i < captions.length; i++) {\r
- component = new Label();\r
- ((Label) component).setValue("Label " + i);\r
- component.setCaption(captions[i]);\r
- vlo.addComponent(component);\r
- }\r
- baseLayout.addComponent(vlo);\r
- vlo = getTestLaytout();\r
- for (int i = 0; i < captions.length; i++) {\r
- component = new Select();\r
- component.setCaption(captions[i]);\r
- component.setIcon(new ThemeResource(LOCK_16_PNG));\r
- vlo.addComponent(component);\r
- }\r
- baseLayout.addComponent(vlo);\r
- vlo = getTestLaytout();\r
- for (int i = 0; i < captions.length; i++) {\r
- component = getTestTabsheet();\r
- component.setCaption(captions[i]);\r
- component.setComponentError(new UserError(\r
- "component error, user error"));\r
- vlo.addComponent(component);\r
- }\r
- baseLayout.addComponent(vlo);\r
- return baseLayout;\r
- }\r
- \r
- @Override\r
- protected Layout getComponentAddReplaceMoveTests() {\r
- final HorizontalLayout vlo = getTestLaytout();\r
- Layout baseLayout = getBaseLayout();\r
- final HorizontalLayout source = new HorizontalLayout();\r
- source.addComponent(new Label("OTHER LABEL 1"));\r
- source.addComponent(new Label("OTHER LABEL 2"));\r
- \r
- final AbstractComponent c1 = new Button("BUTTON");\r
- final AbstractComponent c2 = new Label("<b>LABEL</b>",\r
- ContentMode.XHTML);\r
- final AbstractComponent c3 = new Table("TABLE");\r
- c3.setHeight("100px");\r
- c3.setWidth("100%");\r
- \r
- final Button addButton = new Button("Test add");\r
- final Button replaceButton = new Button("Test replace");\r
- final Button moveButton = new Button("Test move");\r
- final Button removeButton = new Button("Test remove");\r
- \r
- replaceButton.setEnabled(false);\r
- moveButton.setEnabled(false);\r
- removeButton.setEnabled(false);\r
- \r
- addButton.addListener(new Button.ClickListener() {\r
- private static final long serialVersionUID = 7716267156088629379L;\r
- \r
- public void buttonClick(ClickEvent event) {\r
- vlo.addComponent(new TextField());\r
- addButton.setEnabled(false);\r
- replaceButton.setEnabled(true);\r
- }\r
- });\r
- replaceButton.addListener(new Button.ClickListener() {\r
- private static final long serialVersionUID = 7716267156088629379L;\r
- \r
- public void buttonClick(ClickEvent event) {\r
- vlo.replaceComponent(c1, c3);\r
- replaceButton.setEnabled(false);\r
- moveButton.setEnabled(true);\r
- }\r
- });\r
- moveButton.addListener(new Button.ClickListener() {\r
- private static final long serialVersionUID = 7716267156088629379L;\r
- \r
- public void buttonClick(ClickEvent event) {\r
- vlo.moveComponentsFrom(source);\r
- moveButton.setEnabled(false);\r
- removeButton.setEnabled(true);\r
- }\r
- });\r
- removeButton.addListener(new Button.ClickListener() {\r
- private static final long serialVersionUID = 7716267156088629379L;\r
- \r
- public void buttonClick(ClickEvent event) {\r
- vlo.removeComponent(c1);\r
- vlo.removeComponent(c2);\r
- removeButton.setEnabled(false);\r
- }\r
- });\r
- \r
- baseLayout.addComponent(addButton);\r
- baseLayout.addComponent(replaceButton);\r
- baseLayout.addComponent(moveButton);\r
- baseLayout.addComponent(removeButton);\r
- \r
- vlo.addComponent(c1);\r
- vlo.addComponent(c2);\r
- vlo.addComponent(c3);\r
- baseLayout.addComponent(vlo);\r
- \r
- return baseLayout;\r
- }\r
- \r
- @Override\r
- protected Layout getComponentSizingTests() {\r
- final HorizontalLayout vlo = getTestLaytout();\r
- Layout baseLayout = getBaseLayout();\r
- \r
- final AbstractComponent c = getTestTable();\r
- \r
- final Button biggerButton = new Button("full size");\r
- final Button smallerButton = new Button("200 px width");\r
- final Button originalButton = new Button("undefined size+add");\r
- \r
- baseLayout.addComponent(biggerButton);\r
- baseLayout.addComponent(smallerButton);\r
- baseLayout.addComponent(originalButton);\r
- vlo.addComponent(c);\r
- baseLayout.addComponent(vlo);\r
- \r
- biggerButton.setEnabled(true);\r
- smallerButton.setEnabled(false);\r
- originalButton.setEnabled(false);\r
- \r
- biggerButton.addListener(new Button.ClickListener() {\r
- private static final long serialVersionUID = 7716267156088629379L;\r
- \r
- public void buttonClick(ClickEvent event) {\r
- c.setSizeFull();\r
- biggerButton.setEnabled(false);\r
- smallerButton.setEnabled(true);\r
- }\r
- });\r
- smallerButton.addListener(new Button.ClickListener() {\r
- private static final long serialVersionUID = 7716267156088629379L;\r
- \r
- public void buttonClick(ClickEvent event) {\r
- c.setWidth("200px");\r
- smallerButton.setEnabled(false);\r
- originalButton.setEnabled(true);\r
- }\r
- });\r
- originalButton.addListener(new Button.ClickListener() {\r
- private static final long serialVersionUID = 7716267156088629379L;\r
- \r
- public void buttonClick(ClickEvent event) {\r
- originalButton.setEnabled(false);\r
- c.setSizeUndefined();\r
- ((Table) c)\r
- .addItem(\r
- new Object[] { "VYVTCTC VYVYV ECECCE NIDSD SDMPOM" },\r
- 3);\r
- }\r
- });\r
- \r
- return baseLayout;\r
- }\r
- \r
- @Override\r
- protected Layout getLayoutSizingTests() {\r
- final HorizontalLayout vlo = getTestLaytout();\r
- vlo.setSpacing(false);\r
- vlo.setMargin(false);\r
- Layout baseLayout = getBaseLayout();\r
- final AbstractComponent c1 = getTestTable();\r
- c1.setSizeFull();\r
- final AbstractComponent c2 = getTestTable();\r
- c2.setSizeFull();\r
- \r
- final Button button1 = new Button("Set fixed height 350px");\r
- final Button button2 = new Button(\r
- "Set undefined size and add component");\r
- final Button button3 = new Button("Set fixed width and height 75%");\r
- final Button button4 = new Button("Set size full");\r
- \r
- baseLayout.addComponent(button1);\r
- baseLayout.addComponent(button2);\r
- baseLayout.addComponent(button3);\r
- baseLayout.addComponent(button4);\r
- button1.setEnabled(true);\r
- button2.setEnabled(false);\r
- button3.setEnabled(false);\r
- button4.setEnabled(false);\r
- \r
- vlo.addComponent(c1);\r
- vlo.addComponent(c2);\r
- vlo.setExpandRatio(c1, 0.5f);\r
- vlo.setExpandRatio(c2, 0.5f);\r
- \r
- baseLayout.addComponent(vlo);\r
- \r
- button1.addListener(new Button.ClickListener() {\r
- private static final long serialVersionUID = 7716267156088629379L;\r
- \r
- public void buttonClick(ClickEvent event) {\r
- vlo.setHeight("350px");\r
- button1.setEnabled(false);\r
- button2.setEnabled(true);\r
- }\r
- });\r
- button2.addListener(new Button.ClickListener() {\r
- private static final long serialVersionUID = 7716267156088629379L;\r
- \r
- public void buttonClick(ClickEvent event) {\r
- vlo.setSizeUndefined();\r
- vlo.addComponent(new Label("--- NEW LABEL ---"));\r
- button2.setEnabled(false);\r
- button3.setEnabled(true);\r
- }\r
- });\r
- button3.addListener(new Button.ClickListener() {\r
- private static final long serialVersionUID = 7716267156088629379L;\r
- \r
- public void buttonClick(ClickEvent event) {\r
- vlo.setWidth("75%");\r
- vlo.setHeight("75%");\r
- button3.setEnabled(false);\r
- button4.setEnabled(true);\r
- }\r
- });\r
- button4.addListener(new Button.ClickListener() {\r
- private static final long serialVersionUID = 7716267156088629379L;\r
- \r
- public void buttonClick(ClickEvent event) {\r
- vlo.setSizeFull();\r
- button4.setEnabled(false);\r
- }\r
- });\r
- \r
- return baseLayout;\r
- }\r
- \r
- @Override\r
- protected Layout getExpandRatiosTests() {\r
- final HorizontalLayout vlo = getTestLaytout();\r
- Layout baseLayout = getBaseLayout();\r
- final AbstractComponent c1 = getTestTable();\r
- c1.setSizeFull();\r
- final AbstractComponent c2 = getTestTable();\r
- c2.setSizeFull();\r
- \r
- final Button button1 = new Button("Expand to 1/undefined");\r
- final Button button2 = new Button("Expand to 0.5/0.5");\r
- final Button button3 = new Button("Expand to 0.75/0.25");\r
- \r
- baseLayout.addComponent(button1);\r
- baseLayout.addComponent(button2);\r
- baseLayout.addComponent(button3);\r
- button1.setEnabled(true);\r
- button2.setEnabled(false);\r
- button3.setEnabled(false);\r
- \r
- vlo.addComponent(c1);\r
- vlo.addComponent(c2);\r
- baseLayout.addComponent(vlo);\r
- \r
- button1.addListener(new Button.ClickListener() {\r
- private static final long serialVersionUID = 7716267156088629379L;\r
- \r
- public void buttonClick(ClickEvent event) {\r
- vlo.setExpandRatio(c1, 1.0f);\r
- button1.setEnabled(false);\r
- button2.setEnabled(true);\r
- }\r
- });\r
- button2.addListener(new Button.ClickListener() {\r
- private static final long serialVersionUID = 7716267156088629379L;\r
- \r
- public void buttonClick(ClickEvent event) {\r
- vlo.setExpandRatio(c1, 0.5f);\r
- vlo.setExpandRatio(c2, 0.5f);\r
- button2.setEnabled(false);\r
- button3.setEnabled(true);\r
- }\r
- });\r
- button3.addListener(new Button.ClickListener() {\r
- private static final long serialVersionUID = 7716267156088629379L;\r
- \r
- public void buttonClick(ClickEvent event) {\r
- vlo.setExpandRatio(c1, 0.75f);\r
- vlo.setExpandRatio(c2, 0.25f);\r
- button3.setEnabled(false);\r
- }\r
- });\r
- return baseLayout;\r
- }\r
- \r
- @Override\r
- protected Layout getIconsTests() {\r
- HorizontalLayout vlo = getTestLaytout();\r
- AbstractComponent[] components = new AbstractComponent[2];\r
- Layout baseLayout = getBaseLayout();\r
- Resource[] icons = new Resource[] { new ThemeResource(CALENDAR_32_PNG),\r
- new ThemeResource(LOCK_16_PNG) };\r
- \r
- for (int i = 0; i < components.length; i++) {\r
- components[i] = new TextField();\r
- ((TextField) components[i]).setValue("FIELD " + i);\r
- components[i].setIcon(icons[i]);\r
- components[i]\r
- .setCaption("long test caption bewucbwuebco or bmort b cbwecubw wbeucwe asdasd asdasda asdasd");\r
- vlo.addComponent(components[i]);\r
- }\r
- for (int i = 0; i < components.length; i++) {\r
- components[i] = new Label();\r
- ((Label) components[i]).setValue("Label " + i);\r
- components[i].setIcon(icons[i]);\r
- vlo.addComponent(components[i]);\r
- }\r
- baseLayout.addComponent(vlo);\r
- vlo = getTestLaytout();\r
- for (int i = 0; i < components.length; i++) {\r
- components[i] = new Select();\r
- components[i].setIcon(icons[i]);\r
- vlo.addComponent(components[i]);\r
- }\r
- for (int i = 0; i < components.length; i++) {\r
- components[i] = new Button();\r
- components[i].setComponentError(new UserError(\r
- "component error, user error"));\r
- components[i].setIcon(icons[i]);\r
- vlo.addComponent(components[i]);\r
- }\r
- for (int i = 0; i < components.length; i++) {\r
- components[i] = new Link("Link", null);\r
- components[i].setIcon(icons[i]);\r
- vlo.addComponent(components[i]);\r
- }\r
- baseLayout.addComponent(vlo);\r
- return baseLayout;\r
- }\r
- \r
- @Override\r
- protected Layout getMarginSpacingTests() {\r
- final HorizontalLayout vlo = getTestLaytout();\r
- vlo.setSpacing(false);\r
- vlo.setMargin(false);\r
- Layout baseLayout = getBaseLayout();\r
- final AbstractComponent c1 = getTestTable();\r
- c1.setSizeFull();\r
- final AbstractComponent c2 = getTestTable();\r
- c2.setSizeFull();\r
- \r
- final Button button1 = new Button("Set margin on");\r
- final Button button2 = new Button("Set spacing on");\r
- final Button button3 = new Button("Set margin off");\r
- final Button button4 = new Button("Set spacing off");\r
- \r
- baseLayout.addComponent(button1);\r
- baseLayout.addComponent(button2);\r
- baseLayout.addComponent(button3);\r
- baseLayout.addComponent(button4);\r
- button1.setEnabled(true);\r
- button2.setEnabled(false);\r
- button3.setEnabled(false);\r
- button4.setEnabled(false);\r
- \r
- vlo.addComponent(c1);\r
- vlo.addComponent(c2);\r
- vlo.setExpandRatio(c1, 0.5f);\r
- vlo.setExpandRatio(c2, 0.5f);\r
- baseLayout.addComponent(vlo);\r
- \r
- button1.addListener(new Button.ClickListener() {\r
- private static final long serialVersionUID = 7716267156088629379L;\r
- \r
- public void buttonClick(ClickEvent event) {\r
- vlo.setMargin(true);\r
- button1.setEnabled(false);\r
- button2.setEnabled(true);\r
- }\r
- });\r
- button2.addListener(new Button.ClickListener() {\r
- private static final long serialVersionUID = 7716267156088629379L;\r
- \r
- public void buttonClick(ClickEvent event) {\r
- vlo.setSpacing(true);\r
- button2.setEnabled(false);\r
- button3.setEnabled(true);\r
- }\r
- });\r
- button3.addListener(new Button.ClickListener() {\r
- private static final long serialVersionUID = 7716267156088629379L;\r
- \r
- public void buttonClick(ClickEvent event) {\r
- vlo.setMargin(false);\r
- button3.setEnabled(false);\r
- button4.setEnabled(true);\r
- }\r
- });\r
- button4.addListener(new Button.ClickListener() {\r
- private static final long serialVersionUID = 7716267156088629379L;\r
- \r
- public void buttonClick(ClickEvent event) {\r
- vlo.setSpacing(false);\r
- button4.setEnabled(false);\r
- }\r
- });\r
- \r
- return baseLayout;\r
- }\r
- \r
- @Override\r
- protected Layout getRequiredErrorIndicatorsTests() {\r
- HorizontalLayout vlo = getTestLaytout();\r
- Layout baseLayout = getBaseLayout();\r
- AbstractComponent[] components = new AbstractComponent[4];\r
- components[0] = new Label("LABEL");\r
- components[0].setSizeUndefined();\r
- components[1] = new Button("BUTTON");\r
- components[2] = getTestTable();\r
- components[3] = getTestTabsheet();\r
- components[3].setIcon(new ThemeResource(LOCK_16_PNG));\r
- \r
- AbstractField<?>[] fields = new AbstractField<?>[5];\r
- fields[0] = new TextField();\r
- fields[0].setRequired(true);\r
- fields[0].setValidationVisible(true);\r
- fields[0].setRequiredError("required error");\r
- \r
- fields[1] = new TextField();\r
- fields[1].setValue("TEXTFIELD2");\r
- fields[1]\r
- .setComponentError(new UserError("component error, user error"));\r
- \r
- fields[2] = new Select();\r
- fields[2].setComponentError(new SystemError(\r
- "component error, system error"));\r
- fields[3] = new DateField();\r
- fields[3].setComponentError(new SystemError(\r
- "component error, system error"));\r
- \r
- fields[4] = new CheckBox();\r
- fields[4]\r
- .setComponentError(new UserError("component error, user error"));\r
- \r
- for (int i = 0; i < components.length; i++) {\r
- components[i].setComponentError(new UserError(\r
- "component error, user error"));\r
- vlo.addComponent(components[i]);\r
- }\r
- baseLayout.addComponent(vlo);\r
- vlo = getTestLaytout();\r
- for (int i = 0; i < fields.length; i++) {\r
- vlo.addComponent(fields[i]);\r
- }\r
- baseLayout.addComponent(vlo);\r
- return baseLayout;\r
- }\r
- \r
- private VerticalLayout getBaseLayout() {\r
- VerticalLayout vlo = new VerticalLayout();\r
- vlo.setSizeUndefined();\r
- return vlo;\r
- }\r
- \r
- private HorizontalLayout getTestLaytout() {\r
- HorizontalLayout vlo = new HorizontalLayout();\r
- vlo.setHeight("100px");\r
- vlo.setWidth("750px");\r
- return vlo;\r
- }\r
- \r
- private AbstractComponent getTestTabsheet() {\r
- TabSheet tabsheet = new TabSheet();\r
- tabsheet.setSizeUndefined();\r
- tabsheet.addTab(new UndefWideLabel("TAB1"), "TAB1", new ThemeResource(\r
- GLOBE_16_PNG));\r
- tabsheet.addTab(new UndefWideLabel("TAB2"), "TAB2", null);\r
- return tabsheet;\r
- }\r
- \r
- private Table getTestTable() {\r
- Table t = new Table();\r
- t.setSizeUndefined();\r
- t.setPageLength(5);\r
- t.addContainerProperty("test", String.class, null);\r
- t.addItem(new Object[] { "qwertyuiop asdfghjkl zxccvbnm,m,." }, 1);\r
- t.addItem(new Object[] { "YGVYTCTCTRXRXRXRX" }, 2);\r
- return t;\r
- }\r
- }\r
+ package com.vaadin.tests.layouts.layouttester;
+
+ import com.vaadin.Application;
+ import com.vaadin.terminal.Resource;
+ import com.vaadin.terminal.SystemError;
+ import com.vaadin.terminal.ThemeResource;
+ import com.vaadin.terminal.UserError;
+ import com.vaadin.ui.AbstractComponent;
+ import com.vaadin.ui.AbstractField;
+ import com.vaadin.ui.Alignment;
+ import com.vaadin.ui.Button;
+ import com.vaadin.ui.Button.ClickEvent;
+ import com.vaadin.ui.CheckBox;
+ import com.vaadin.ui.DateField;
+ import com.vaadin.ui.HorizontalLayout;
+ import com.vaadin.ui.Label;
++import com.vaadin.ui.Label.ContentMode;
+ import com.vaadin.ui.Layout;
+ import com.vaadin.ui.Link;
+ import com.vaadin.ui.Select;
+ import com.vaadin.ui.TabSheet;
+ import com.vaadin.ui.Table;
+ import com.vaadin.ui.TextField;
+ import com.vaadin.ui.VerticalLayout;
+ import com.vaadin.ui.themes.Reindeer;
+
+ public class HorizontalLayoutTests extends AbstractLayoutTests {
+
+ public HorizontalLayoutTests(Application application) {
+ super();
+ }
+
+ @Override
+ protected Layout getAlignmentTests() {
+ Layout baseLayout = getBaseLayout();
+ HorizontalLayout vlo = getTestLaytout();
+ AbstractComponent[] components = new AbstractComponent[9];
+ String[] styles = { Reindeer.LAYOUT_BLUE, Reindeer.LAYOUT_WHITE };
+ Alignment[] alignments = new Alignment[] { Alignment.BOTTOM_LEFT,
+ Alignment.BOTTOM_CENTER, Alignment.BOTTOM_RIGHT,
+ Alignment.MIDDLE_LEFT, Alignment.MIDDLE_CENTER,
+ Alignment.MIDDLE_RIGHT, Alignment.TOP_LEFT,
+ Alignment.TOP_CENTER, Alignment.TOP_RIGHT };
+
+ vlo.addStyleName(Reindeer.LAYOUT_WHITE);
+ baseLayout.addComponent(vlo);
+ int index = 0;
+ for (int i = 0; i < components.length; i++) {
+ if (i > 0 && i % 3 == 0) {
+ vlo = getTestLaytout();
+ vlo.addStyleName(styles[index++]);
+ baseLayout.addComponent(vlo);
+ }
+ components[i] = new TextField();
+ ((TextField) components[i]).setValue("FIELD " + i);
+ vlo.addComponent(components[i]);
+ vlo.setComponentAlignment(components[i], alignments[i]);
+ }
+ return baseLayout;
+ }
+
+ @Override
+ protected Layout getCaptionsTests() {
+ Layout baseLayout = getBaseLayout();
+ AbstractComponent component = null;
+
+ String[] captions = new String[] {
+ "",
+ "abcdefghijklmnopq",
+ "abc def hij klm nop qrs tuv xyz qaz wsx edc rfv tgb yhn ujm mko nji bhu vgy cft cde" };
+
+ HorizontalLayout vlo = getTestLaytout();
+ for (int i = 0; i < captions.length; i++) {
+ component = new TextField();
+ ((TextField) component).setValue("FIELD " + i);
+ component.setCaption(captions[i]);
+ vlo.addComponent(component);
+ }
+ baseLayout.addComponent(vlo);
+ vlo = getTestLaytout();
+ for (int i = 0; i < captions.length; i++) {
+ component = new Label();
+ ((Label) component).setValue("Label " + i);
+ component.setCaption(captions[i]);
+ vlo.addComponent(component);
+ }
+ baseLayout.addComponent(vlo);
+ vlo = getTestLaytout();
+ for (int i = 0; i < captions.length; i++) {
+ component = new Select();
+ component.setCaption(captions[i]);
+ component.setIcon(new ThemeResource(LOCK_16_PNG));
+ vlo.addComponent(component);
+ }
+ baseLayout.addComponent(vlo);
+ vlo = getTestLaytout();
+ for (int i = 0; i < captions.length; i++) {
+ component = getTestTabsheet();
+ component.setCaption(captions[i]);
+ component.setComponentError(new UserError(
+ "component error, user error"));
+ vlo.addComponent(component);
+ }
+ baseLayout.addComponent(vlo);
+ return baseLayout;
+ }
+
+ @Override
+ protected Layout getComponentAddReplaceMoveTests() {
+ final HorizontalLayout vlo = getTestLaytout();
+ Layout baseLayout = getBaseLayout();
+ final HorizontalLayout source = new HorizontalLayout();
+ source.addComponent(new Label("OTHER LABEL 1"));
+ source.addComponent(new Label("OTHER LABEL 2"));
+
+ final AbstractComponent c1 = new Button("BUTTON");
+ final AbstractComponent c2 = new Label("<b>LABEL</b>",
- Label.CONTENT_XHTML);
++ ContentMode.XHTML);
+ final AbstractComponent c3 = new Table("TABLE");
+ c3.setHeight("100px");
+ c3.setWidth("100%");
+
+ final Button addButton = new Button("Test add");
+ final Button replaceButton = new Button("Test replace");
+ final Button moveButton = new Button("Test move");
+ final Button removeButton = new Button("Test remove");
+
+ replaceButton.setEnabled(false);
+ moveButton.setEnabled(false);
+ removeButton.setEnabled(false);
+
+ addButton.addListener(new Button.ClickListener() {
+ private static final long serialVersionUID = 7716267156088629379L;
+
+ public void buttonClick(ClickEvent event) {
+ vlo.addComponent(new TextField());
+ addButton.setEnabled(false);
+ replaceButton.setEnabled(true);
+ }
+ });
+ replaceButton.addListener(new Button.ClickListener() {
+ private static final long serialVersionUID = 7716267156088629379L;
+
+ public void buttonClick(ClickEvent event) {
+ vlo.replaceComponent(c1, c3);
+ replaceButton.setEnabled(false);
+ moveButton.setEnabled(true);
+ }
+ });
+ moveButton.addListener(new Button.ClickListener() {
+ private static final long serialVersionUID = 7716267156088629379L;
+
+ public void buttonClick(ClickEvent event) {
+ vlo.moveComponentsFrom(source);
+ moveButton.setEnabled(false);
+ removeButton.setEnabled(true);
+ }
+ });
+ removeButton.addListener(new Button.ClickListener() {
+ private static final long serialVersionUID = 7716267156088629379L;
+
+ public void buttonClick(ClickEvent event) {
+ vlo.removeComponent(c1);
+ vlo.removeComponent(c2);
+ removeButton.setEnabled(false);
+ }
+ });
+
+ baseLayout.addComponent(addButton);
+ baseLayout.addComponent(replaceButton);
+ baseLayout.addComponent(moveButton);
+ baseLayout.addComponent(removeButton);
+
+ vlo.addComponent(c1);
+ vlo.addComponent(c2);
+ vlo.addComponent(c3);
+ baseLayout.addComponent(vlo);
+
+ return baseLayout;
+ }
+
+ @Override
+ protected Layout getComponentSizingTests() {
+ final HorizontalLayout vlo = getTestLaytout();
+ Layout baseLayout = getBaseLayout();
+
+ final AbstractComponent c = getTestTable();
+
+ final Button biggerButton = new Button("full size");
+ final Button smallerButton = new Button("200 px width");
+ final Button originalButton = new Button("undefined size+add");
+
+ baseLayout.addComponent(biggerButton);
+ baseLayout.addComponent(smallerButton);
+ baseLayout.addComponent(originalButton);
+ vlo.addComponent(c);
+ baseLayout.addComponent(vlo);
+
+ biggerButton.setEnabled(true);
+ smallerButton.setEnabled(false);
+ originalButton.setEnabled(false);
+
+ biggerButton.addListener(new Button.ClickListener() {
+ private static final long serialVersionUID = 7716267156088629379L;
+
+ public void buttonClick(ClickEvent event) {
+ c.setSizeFull();
+ biggerButton.setEnabled(false);
+ smallerButton.setEnabled(true);
+ }
+ });
+ smallerButton.addListener(new Button.ClickListener() {
+ private static final long serialVersionUID = 7716267156088629379L;
+
+ public void buttonClick(ClickEvent event) {
+ c.setWidth("200px");
+ smallerButton.setEnabled(false);
+ originalButton.setEnabled(true);
+ }
+ });
+ originalButton.addListener(new Button.ClickListener() {
+ private static final long serialVersionUID = 7716267156088629379L;
+
+ public void buttonClick(ClickEvent event) {
+ originalButton.setEnabled(false);
+ c.setSizeUndefined();
+ ((Table) c)
+ .addItem(
+ new Object[] { "VYVTCTC VYVYV ECECCE NIDSD SDMPOM" },
+ 3);
+ }
+ });
+
+ return baseLayout;
+ }
+
+ @Override
+ protected Layout getLayoutSizingTests() {
+ final HorizontalLayout vlo = getTestLaytout();
+ vlo.setSpacing(false);
+ vlo.setMargin(false);
+ Layout baseLayout = getBaseLayout();
+ final AbstractComponent c1 = getTestTable();
+ c1.setSizeFull();
+ final AbstractComponent c2 = getTestTable();
+ c2.setSizeFull();
+
+ final Button button1 = new Button("Set fixed height 350px");
+ final Button button2 = new Button(
+ "Set undefined size and add component");
+ final Button button3 = new Button("Set fixed width and height 75%");
+ final Button button4 = new Button("Set size full");
+
+ baseLayout.addComponent(button1);
+ baseLayout.addComponent(button2);
+ baseLayout.addComponent(button3);
+ baseLayout.addComponent(button4);
+ button1.setEnabled(true);
+ button2.setEnabled(false);
+ button3.setEnabled(false);
+ button4.setEnabled(false);
+
+ vlo.addComponent(c1);
+ vlo.addComponent(c2);
+ vlo.setExpandRatio(c1, 0.5f);
+ vlo.setExpandRatio(c2, 0.5f);
+
+ baseLayout.addComponent(vlo);
+
+ button1.addListener(new Button.ClickListener() {
+ private static final long serialVersionUID = 7716267156088629379L;
+
+ public void buttonClick(ClickEvent event) {
+ vlo.setHeight("350px");
+ button1.setEnabled(false);
+ button2.setEnabled(true);
+ }
+ });
+ button2.addListener(new Button.ClickListener() {
+ private static final long serialVersionUID = 7716267156088629379L;
+
+ public void buttonClick(ClickEvent event) {
+ vlo.setSizeUndefined();
+ vlo.addComponent(new Label("--- NEW LABEL ---"));
+ button2.setEnabled(false);
+ button3.setEnabled(true);
+ }
+ });
+ button3.addListener(new Button.ClickListener() {
+ private static final long serialVersionUID = 7716267156088629379L;
+
+ public void buttonClick(ClickEvent event) {
+ vlo.setWidth("75%");
+ vlo.setHeight("75%");
+ button3.setEnabled(false);
+ button4.setEnabled(true);
+ }
+ });
+ button4.addListener(new Button.ClickListener() {
+ private static final long serialVersionUID = 7716267156088629379L;
+
+ public void buttonClick(ClickEvent event) {
+ vlo.setSizeFull();
+ button4.setEnabled(false);
+ }
+ });
+
+ return baseLayout;
+ }
+
+ @Override
+ protected Layout getExpandRatiosTests() {
+ final HorizontalLayout vlo = getTestLaytout();
+ Layout baseLayout = getBaseLayout();
+ final AbstractComponent c1 = getTestTable();
+ c1.setSizeFull();
+ final AbstractComponent c2 = getTestTable();
+ c2.setSizeFull();
+
+ final Button button1 = new Button("Expand to 1/undefined");
+ final Button button2 = new Button("Expand to 0.5/0.5");
+ final Button button3 = new Button("Expand to 0.75/0.25");
+
+ baseLayout.addComponent(button1);
+ baseLayout.addComponent(button2);
+ baseLayout.addComponent(button3);
+ button1.setEnabled(true);
+ button2.setEnabled(false);
+ button3.setEnabled(false);
+
+ vlo.addComponent(c1);
+ vlo.addComponent(c2);
+ baseLayout.addComponent(vlo);
+
+ button1.addListener(new Button.ClickListener() {
+ private static final long serialVersionUID = 7716267156088629379L;
+
+ public void buttonClick(ClickEvent event) {
+ vlo.setExpandRatio(c1, 1.0f);
+ button1.setEnabled(false);
+ button2.setEnabled(true);
+ }
+ });
+ button2.addListener(new Button.ClickListener() {
+ private static final long serialVersionUID = 7716267156088629379L;
+
+ public void buttonClick(ClickEvent event) {
+ vlo.setExpandRatio(c1, 0.5f);
+ vlo.setExpandRatio(c2, 0.5f);
+ button2.setEnabled(false);
+ button3.setEnabled(true);
+ }
+ });
+ button3.addListener(new Button.ClickListener() {
+ private static final long serialVersionUID = 7716267156088629379L;
+
+ public void buttonClick(ClickEvent event) {
+ vlo.setExpandRatio(c1, 0.75f);
+ vlo.setExpandRatio(c2, 0.25f);
+ button3.setEnabled(false);
+ }
+ });
+ return baseLayout;
+ }
+
+ @Override
+ protected Layout getIconsTests() {
+ HorizontalLayout vlo = getTestLaytout();
+ AbstractComponent[] components = new AbstractComponent[2];
+ Layout baseLayout = getBaseLayout();
+ Resource[] icons = new Resource[] { new ThemeResource(CALENDAR_32_PNG),
+ new ThemeResource(LOCK_16_PNG) };
+
+ for (int i = 0; i < components.length; i++) {
+ components[i] = new TextField();
+ ((TextField) components[i]).setValue("FIELD " + i);
+ components[i].setIcon(icons[i]);
+ components[i]
+ .setCaption("long test caption bewucbwuebco or bmort b cbwecubw wbeucwe asdasd asdasda asdasd");
+ vlo.addComponent(components[i]);
+ }
+ for (int i = 0; i < components.length; i++) {
+ components[i] = new Label();
+ ((Label) components[i]).setValue("Label " + i);
+ components[i].setIcon(icons[i]);
+ vlo.addComponent(components[i]);
+ }
+ baseLayout.addComponent(vlo);
+ vlo = getTestLaytout();
+ for (int i = 0; i < components.length; i++) {
+ components[i] = new Select();
+ components[i].setIcon(icons[i]);
+ vlo.addComponent(components[i]);
+ }
+ for (int i = 0; i < components.length; i++) {
+ components[i] = new Button();
+ components[i].setComponentError(new UserError(
+ "component error, user error"));
+ components[i].setIcon(icons[i]);
+ vlo.addComponent(components[i]);
+ }
+ for (int i = 0; i < components.length; i++) {
+ components[i] = new Link("Link", null);
+ components[i].setIcon(icons[i]);
+ vlo.addComponent(components[i]);
+ }
+ baseLayout.addComponent(vlo);
+ return baseLayout;
+ }
+
+ @Override
+ protected Layout getMarginSpacingTests() {
+ final HorizontalLayout vlo = getTestLaytout();
+ vlo.setSpacing(false);
+ vlo.setMargin(false);
+ Layout baseLayout = getBaseLayout();
+ final AbstractComponent c1 = getTestTable();
+ c1.setSizeFull();
+ final AbstractComponent c2 = getTestTable();
+ c2.setSizeFull();
+
+ final Button button1 = new Button("Set margin on");
+ final Button button2 = new Button("Set spacing on");
+ final Button button3 = new Button("Set margin off");
+ final Button button4 = new Button("Set spacing off");
+
+ baseLayout.addComponent(button1);
+ baseLayout.addComponent(button2);
+ baseLayout.addComponent(button3);
+ baseLayout.addComponent(button4);
+ button1.setEnabled(true);
+ button2.setEnabled(false);
+ button3.setEnabled(false);
+ button4.setEnabled(false);
+
+ vlo.addComponent(c1);
+ vlo.addComponent(c2);
+ vlo.setExpandRatio(c1, 0.5f);
+ vlo.setExpandRatio(c2, 0.5f);
+ baseLayout.addComponent(vlo);
+
+ button1.addListener(new Button.ClickListener() {
+ private static final long serialVersionUID = 7716267156088629379L;
+
+ public void buttonClick(ClickEvent event) {
+ vlo.setMargin(true);
+ button1.setEnabled(false);
+ button2.setEnabled(true);
+ }
+ });
+ button2.addListener(new Button.ClickListener() {
+ private static final long serialVersionUID = 7716267156088629379L;
+
+ public void buttonClick(ClickEvent event) {
+ vlo.setSpacing(true);
+ button2.setEnabled(false);
+ button3.setEnabled(true);
+ }
+ });
+ button3.addListener(new Button.ClickListener() {
+ private static final long serialVersionUID = 7716267156088629379L;
+
+ public void buttonClick(ClickEvent event) {
+ vlo.setMargin(false);
+ button3.setEnabled(false);
+ button4.setEnabled(true);
+ }
+ });
+ button4.addListener(new Button.ClickListener() {
+ private static final long serialVersionUID = 7716267156088629379L;
+
+ public void buttonClick(ClickEvent event) {
+ vlo.setSpacing(false);
+ button4.setEnabled(false);
+ }
+ });
+
+ return baseLayout;
+ }
+
+ @Override
+ protected Layout getRequiredErrorIndicatorsTests() {
+ HorizontalLayout vlo = getTestLaytout();
+ Layout baseLayout = getBaseLayout();
+ AbstractComponent[] components = new AbstractComponent[4];
+ components[0] = new Label("LABEL");
+ components[0].setSizeUndefined();
+ components[1] = new Button("BUTTON");
+ components[2] = getTestTable();
+ components[3] = getTestTabsheet();
+ components[3].setIcon(new ThemeResource(LOCK_16_PNG));
+
- AbstractField[] fields = new AbstractField[5];
++ AbstractField<?>[] fields = new AbstractField<?>[5];
+ fields[0] = new TextField();
+ fields[0].setRequired(true);
+ fields[0].setValidationVisible(true);
+ fields[0].setRequiredError("required error");
+
+ fields[1] = new TextField();
+ fields[1].setValue("TEXTFIELD2");
+ fields[1]
+ .setComponentError(new UserError("component error, user error"));
+
+ fields[2] = new Select();
+ fields[2].setComponentError(new SystemError(
+ "component error, system error"));
+ fields[3] = new DateField();
+ fields[3].setComponentError(new SystemError(
+ "component error, system error"));
+
+ fields[4] = new CheckBox();
+ fields[4]
+ .setComponentError(new UserError("component error, user error"));
+
+ for (int i = 0; i < components.length; i++) {
+ components[i].setComponentError(new UserError(
+ "component error, user error"));
+ vlo.addComponent(components[i]);
+ }
+ baseLayout.addComponent(vlo);
+ vlo = getTestLaytout();
+ for (int i = 0; i < fields.length; i++) {
+ vlo.addComponent(fields[i]);
+ }
+ baseLayout.addComponent(vlo);
+ return baseLayout;
+ }
+
+ private VerticalLayout getBaseLayout() {
+ VerticalLayout vlo = new VerticalLayout();
+ vlo.setSizeUndefined();
+ return vlo;
+ }
+
+ private HorizontalLayout getTestLaytout() {
+ HorizontalLayout vlo = new HorizontalLayout();
+ vlo.setHeight("100px");
+ vlo.setWidth("750px");
+ return vlo;
+ }
+
+ private AbstractComponent getTestTabsheet() {
+ TabSheet tabsheet = new TabSheet();
+ tabsheet.setSizeUndefined();
+ tabsheet.addTab(new UndefWideLabel("TAB1"), "TAB1", new ThemeResource(
+ GLOBE_16_PNG));
+ tabsheet.addTab(new UndefWideLabel("TAB2"), "TAB2", null);
+ return tabsheet;
+ }
+
+ private Table getTestTable() {
+ Table t = new Table();
+ t.setSizeUndefined();
+ t.setPageLength(5);
+ t.addContainerProperty("test", String.class, null);
+ t.addItem(new Object[] { "qwertyuiop asdfghjkl zxccvbnm,m,." }, 1);
+ t.addItem(new Object[] { "YGVYTCTCTRXRXRXRX" }, 2);
+ return t;
+ }
+ }
- package com.vaadin.tests.layouts.layouttester;\r
- \r
- import com.vaadin.Application;\r
- import com.vaadin.terminal.Resource;\r
- import com.vaadin.terminal.SystemError;\r
- import com.vaadin.terminal.ThemeResource;\r
- import com.vaadin.terminal.UserError;\r
- import com.vaadin.ui.AbstractComponent;\r
- import com.vaadin.ui.AbstractField;\r
- import com.vaadin.ui.Alignment;\r
- import com.vaadin.ui.Button;\r
- import com.vaadin.ui.Button.ClickEvent;\r
- import com.vaadin.ui.CheckBox;\r
- import com.vaadin.ui.DateField;\r
- import com.vaadin.ui.HorizontalLayout;\r
- import com.vaadin.ui.Label;\r
- import com.vaadin.ui.Label.ContentMode;\r
- import com.vaadin.ui.Layout;\r
- import com.vaadin.ui.Link;\r
- import com.vaadin.ui.NativeSelect;\r
- import com.vaadin.ui.Select;\r
- import com.vaadin.ui.TabSheet;\r
- import com.vaadin.ui.Table;\r
- import com.vaadin.ui.TextField;\r
- import com.vaadin.ui.VerticalLayout;\r
- \r
- public class VerticalLayoutTests extends AbstractLayoutTests {\r
- \r
- public VerticalLayoutTests(Application application) {\r
- super();\r
- }\r
- \r
- @Override\r
- protected Layout getAlignmentTests() {\r
- Layout baseLayout = getBaseLayout();\r
- ((HorizontalLayout) baseLayout).setSpacing(true);\r
- VerticalLayout vlo = getTestLaytout();\r
- AbstractComponent[] components = new AbstractComponent[9];\r
- Alignment[] alignments = new Alignment[] { Alignment.BOTTOM_CENTER,\r
- Alignment.BOTTOM_LEFT, Alignment.BOTTOM_RIGHT,\r
- Alignment.MIDDLE_CENTER, Alignment.MIDDLE_LEFT,\r
- Alignment.MIDDLE_RIGHT, Alignment.TOP_CENTER,\r
- Alignment.TOP_LEFT, Alignment.TOP_RIGHT };\r
- \r
- for (int i = 0; i < components.length / 2; i++) {\r
- components[i] = new TextField();\r
- ((TextField) components[i]).setValue("FIELD " + i);\r
- vlo.addComponent(components[i]);\r
- vlo.setComponentAlignment(components[i], alignments[i]);\r
- vlo.addComponent(new Label("<hr />", ContentMode.XHTML));\r
- }\r
- baseLayout.addComponent(vlo);\r
- vlo = getTestLaytout();\r
- for (int i = components.length / 2; i < components.length; i++) {\r
- components[i] = new TextField();\r
- ((TextField) components[i]).setValue("FIELD " + i);\r
- vlo.addComponent(components[i]);\r
- vlo.setComponentAlignment(components[i], alignments[i]);\r
- vlo.addComponent(new Label("<hr />", ContentMode.XHTML));\r
- }\r
- baseLayout.addComponent(vlo);\r
- return baseLayout;\r
- }\r
- \r
- @Override\r
- protected Layout getCaptionsTests() {\r
- Layout baseLayout = getBaseLayout();\r
- VerticalLayout vlo = getTestLaytout();\r
- AbstractComponent component = null;\r
- \r
- String[] captions = new String[] {\r
- "",\r
- "abcdefghijklmnopq",\r
- "abc def hij klm nop qrs tuv xyz qaz wsx edc rfv tgb yhn ujm mko nji bhu vgy cft cde" };\r
- \r
- for (int i = 0; i < captions.length; i++) {\r
- component = new TextField();\r
- ((TextField) component).setValue("FIELD " + i);\r
- component.setCaption(captions[i]);\r
- vlo.addComponent(component);\r
- }\r
- for (int i = 0; i < captions.length; i++) {\r
- component = new Label();\r
- ((Label) component).setValue("Label " + i);\r
- component.setCaption(captions[i]);\r
- vlo.addComponent(component);\r
- }\r
- baseLayout.addComponent(vlo);\r
- vlo = getTestLaytout();\r
- for (int i = 0; i < captions.length; i++) {\r
- component = new Select();\r
- component.setCaption(captions[i]);\r
- component.setIcon(new ThemeResource(LOCK_16_PNG));\r
- vlo.addComponent(component);\r
- }\r
- for (int i = 0; i < captions.length; i++) {\r
- component = getTestTabsheet();\r
- component.setCaption(captions[i]);\r
- component.setComponentError(new UserError(\r
- "component error, user error"));\r
- vlo.addComponent(component);\r
- }\r
- baseLayout.addComponent(vlo);\r
- return baseLayout;\r
- }\r
- \r
- @Override\r
- protected Layout getComponentAddReplaceMoveTests() {\r
- Layout baseLayout = getBaseLayout();\r
- final VerticalLayout vlo = getTestLaytout();\r
- final VerticalLayout vlo2 = getTestLaytout();\r
- \r
- final HorizontalLayout source = new HorizontalLayout();\r
- source.addComponent(new Label("OTHER LABEL 1"));\r
- source.addComponent(new Label("OTHER LABEL 2"));\r
- \r
- final AbstractComponent c1 = new Button("BUTTON");\r
- final AbstractComponent c2 = new Label("<b>LABEL</b>",\r
- ContentMode.XHTML);\r
- final AbstractComponent c3 = new Table("TABLE");\r
- c3.setHeight("100px");\r
- c3.setWidth("100%");\r
- \r
- final Button addButton = new Button("Test add");\r
- final Button replaceButton = new Button("Test replace");\r
- final Button moveButton = new Button("Test move");\r
- final Button removeButton = new Button("Test remove");\r
- \r
- replaceButton.setEnabled(false);\r
- moveButton.setEnabled(false);\r
- removeButton.setEnabled(false);\r
- \r
- addButton.addListener(new Button.ClickListener() {\r
- private static final long serialVersionUID = 7716267156088629379L;\r
- \r
- public void buttonClick(ClickEvent event) {\r
- vlo2.addComponent(new TextField());\r
- addButton.setEnabled(false);\r
- replaceButton.setEnabled(true);\r
- }\r
- });\r
- replaceButton.addListener(new Button.ClickListener() {\r
- private static final long serialVersionUID = 7716267156088629379L;\r
- \r
- public void buttonClick(ClickEvent event) {\r
- vlo2.replaceComponent(c1, c3);\r
- replaceButton.setEnabled(false);\r
- moveButton.setEnabled(true);\r
- }\r
- });\r
- moveButton.addListener(new Button.ClickListener() {\r
- private static final long serialVersionUID = 7716267156088629379L;\r
- \r
- public void buttonClick(ClickEvent event) {\r
- vlo2.moveComponentsFrom(source);\r
- moveButton.setEnabled(false);\r
- removeButton.setEnabled(true);\r
- }\r
- });\r
- removeButton.addListener(new Button.ClickListener() {\r
- private static final long serialVersionUID = 7716267156088629379L;\r
- \r
- public void buttonClick(ClickEvent event) {\r
- vlo2.removeComponent(c1);\r
- vlo2.removeComponent(c2);\r
- removeButton.setEnabled(false);\r
- }\r
- });\r
- \r
- vlo.addComponent(addButton);\r
- vlo.addComponent(replaceButton);\r
- vlo.addComponent(moveButton);\r
- vlo.addComponent(removeButton);\r
- \r
- baseLayout.addComponent(vlo);\r
- vlo2.addComponent(c1);\r
- vlo2.addComponent(c2);\r
- vlo2.addComponent(c3);\r
- baseLayout.addComponent(vlo2);\r
- return baseLayout;\r
- }\r
- \r
- @Override\r
- protected Layout getComponentSizingTests() {\r
- Layout baseLayout = getBaseLayout();\r
- final VerticalLayout vlo = getTestLaytout();\r
- \r
- final AbstractComponent c = getTestTable();\r
- \r
- final Button biggerButton = new Button("full size");\r
- final Button smallerButton = new Button("200 px width");\r
- final Button originalButton = new Button("undefined size and add");\r
- \r
- vlo.addComponent(biggerButton);\r
- vlo.addComponent(smallerButton);\r
- vlo.addComponent(originalButton);\r
- baseLayout.addComponent(vlo);\r
- final VerticalLayout vlo2 = getTestLaytout();\r
- vlo2.addComponent(c);\r
- baseLayout.addComponent(vlo2);\r
- \r
- biggerButton.setEnabled(true);\r
- smallerButton.setEnabled(false);\r
- originalButton.setEnabled(false);\r
- \r
- biggerButton.addListener(new Button.ClickListener() {\r
- private static final long serialVersionUID = 7716267156088629379L;\r
- \r
- public void buttonClick(ClickEvent event) {\r
- c.setSizeFull();\r
- biggerButton.setEnabled(false);\r
- smallerButton.setEnabled(true);\r
- }\r
- });\r
- smallerButton.addListener(new Button.ClickListener() {\r
- private static final long serialVersionUID = 7716267156088629379L;\r
- \r
- public void buttonClick(ClickEvent event) {\r
- c.setWidth("200px");\r
- smallerButton.setEnabled(false);\r
- originalButton.setEnabled(true);\r
- }\r
- });\r
- originalButton.addListener(new Button.ClickListener() {\r
- private static final long serialVersionUID = 7716267156088629379L;\r
- \r
- public void buttonClick(ClickEvent event) {\r
- originalButton.setEnabled(false);\r
- c.setSizeUndefined();\r
- ((Table) c)\r
- .addItem(\r
- new Object[] { "VYVTCTC VYVYV ECECCE NIDSD SDMPOM" },\r
- 3);\r
- }\r
- });\r
- \r
- return baseLayout;\r
- }\r
- \r
- @Override\r
- protected Layout getLayoutSizingTests() {\r
- Layout baseLayout = getBaseLayout();\r
- final VerticalLayout vlo = getTestLaytout();\r
- \r
- vlo.setSpacing(false);\r
- vlo.setMargin(false);\r
- \r
- final AbstractComponent c1 = getTestTable();\r
- c1.setSizeFull();\r
- final AbstractComponent c2 = getTestTable();\r
- c2.setSizeFull();\r
- \r
- final Button button1 = new Button("Set fixed height 350px");\r
- final Button button2 = new Button(\r
- "Set undefined size and add component");\r
- final Button button3 = new Button("Set fixed width and height 75%");\r
- final Button button4 = new Button("Set size full");\r
- \r
- vlo.addComponent(button1);\r
- vlo.addComponent(button2);\r
- vlo.addComponent(button3);\r
- vlo.addComponent(button4);\r
- baseLayout.addComponent(vlo);\r
- final VerticalLayout vlo2 = getTestLaytout();\r
- \r
- button1.setEnabled(true);\r
- button2.setEnabled(false);\r
- button3.setEnabled(false);\r
- button4.setEnabled(false);\r
- \r
- vlo2.addComponent(c1);\r
- vlo2.addComponent(new Label("<hr />", ContentMode.XHTML));\r
- vlo2.addComponent(c2);\r
- vlo2.setExpandRatio(c1, 0.5f);\r
- vlo2.setExpandRatio(c2, 0.5f);\r
- baseLayout.addComponent(vlo2);\r
- \r
- button1.addListener(new Button.ClickListener() {\r
- private static final long serialVersionUID = 7716267156088629379L;\r
- \r
- public void buttonClick(ClickEvent event) {\r
- vlo2.setHeight("350px");\r
- button1.setEnabled(false);\r
- button2.setEnabled(true);\r
- }\r
- });\r
- button2.addListener(new Button.ClickListener() {\r
- private static final long serialVersionUID = 7716267156088629379L;\r
- \r
- public void buttonClick(ClickEvent event) {\r
- vlo2.setSizeUndefined();\r
- vlo2.addComponent(new Label("--- NEW LABEL ---"));\r
- button2.setEnabled(false);\r
- button3.setEnabled(true);\r
- }\r
- });\r
- button3.addListener(new Button.ClickListener() {\r
- private static final long serialVersionUID = 7716267156088629379L;\r
- \r
- public void buttonClick(ClickEvent event) {\r
- vlo2.setWidth("75%");\r
- vlo2.setHeight("75%");\r
- button3.setEnabled(false);\r
- button4.setEnabled(true);\r
- }\r
- });\r
- button4.addListener(new Button.ClickListener() {\r
- private static final long serialVersionUID = 7716267156088629379L;\r
- \r
- public void buttonClick(ClickEvent event) {\r
- vlo2.setSizeFull();\r
- button4.setEnabled(false);\r
- }\r
- });\r
- \r
- return baseLayout;\r
- }\r
- \r
- @Override\r
- protected Layout getExpandRatiosTests() {\r
- Layout baseLayout = getBaseLayout();\r
- final VerticalLayout vlo = getTestLaytout();\r
- \r
- final AbstractComponent c1 = getTestTable();\r
- c1.setSizeFull();\r
- final AbstractComponent c2 = getTestTable();\r
- c2.setSizeFull();\r
- \r
- final Button button1 = new Button("Expand to 1/undefined");\r
- final Button button2 = new Button("Expand to 0.5/0.5");\r
- final Button button3 = new Button("Expand to 0.75/0.25");\r
- \r
- vlo.addComponent(button1);\r
- vlo.addComponent(button2);\r
- vlo.addComponent(button3);\r
- button1.setEnabled(true);\r
- button2.setEnabled(false);\r
- button3.setEnabled(false);\r
- \r
- baseLayout.addComponent(vlo);\r
- final VerticalLayout vlo2 = getTestLaytout();\r
- \r
- vlo2.addComponent(c1);\r
- vlo2.addComponent(c2);\r
- baseLayout.addComponent(vlo2);\r
- \r
- button1.addListener(new Button.ClickListener() {\r
- private static final long serialVersionUID = 7716267156088629379L;\r
- \r
- public void buttonClick(ClickEvent event) {\r
- vlo2.setExpandRatio(c1, 1.0f);\r
- button1.setEnabled(false);\r
- button2.setEnabled(true);\r
- }\r
- });\r
- button2.addListener(new Button.ClickListener() {\r
- private static final long serialVersionUID = 7716267156088629379L;\r
- \r
- public void buttonClick(ClickEvent event) {\r
- vlo2.setExpandRatio(c1, 0.5f);\r
- vlo2.setExpandRatio(c2, 0.5f);\r
- button2.setEnabled(false);\r
- button3.setEnabled(true);\r
- }\r
- });\r
- button3.addListener(new Button.ClickListener() {\r
- private static final long serialVersionUID = 7716267156088629379L;\r
- \r
- public void buttonClick(ClickEvent event) {\r
- vlo2.setExpandRatio(c1, 0.75f);\r
- vlo2.setExpandRatio(c2, 0.25f);\r
- button3.setEnabled(false);\r
- }\r
- });\r
- return baseLayout;\r
- }\r
- \r
- @Override\r
- protected Layout getIconsTests() {\r
- Layout baseLayout = getBaseLayout();\r
- VerticalLayout vlo = getTestLaytout();\r
- AbstractComponent[] components = new AbstractComponent[2];\r
- \r
- Resource[] icons = new Resource[] { new ThemeResource(CALENDAR_32_PNG),\r
- new ThemeResource(LOCK_16_PNG) };\r
- \r
- for (int i = 0; i < components.length; i++) {\r
- components[i] = new TextField();\r
- ((TextField) components[i]).setValue("FIELD " + i);\r
- components[i].setIcon(icons[i]);\r
- components[i]\r
- .setCaption("long test caption bewucbwuebco or bmort b cbwecubw wbeucwe asdasd asdasda asdasd");\r
- vlo.addComponent(components[i]);\r
- }\r
- \r
- for (int i = 0; i < components.length; i++) {\r
- components[i] = new Label();\r
- ((Label) components[i]).setValue("Label " + i);\r
- components[i].setIcon(icons[i]);\r
- vlo.addComponent(components[i]);\r
- }\r
- \r
- for (int i = 0; i < components.length; i++) {\r
- components[i] = new Select();\r
- components[i].setIcon(icons[i]);\r
- vlo.addComponent(components[i]);\r
- }\r
- baseLayout.addComponent(vlo);\r
- final VerticalLayout vlo2 = getTestLaytout();\r
- for (int i = 0; i < components.length; i++) {\r
- components[i] = new Button();\r
- components[i].setComponentError(new UserError(\r
- "component error, user error"));\r
- components[i].setIcon(icons[i]);\r
- vlo2.addComponent(components[i]);\r
- }\r
- \r
- for (int i = 0; i < components.length; i++) {\r
- components[i] = new Link("Link", null);\r
- components[i].setIcon(icons[i]);\r
- vlo2.addComponent(components[i]);\r
- }\r
- baseLayout.addComponent(vlo2);\r
- return baseLayout;\r
- }\r
- \r
- @Override\r
- protected Layout getMarginSpacingTests() {\r
- Layout baseLayout = getBaseLayout();\r
- final VerticalLayout vlo = getTestLaytout();\r
- vlo.setSpacing(false);\r
- vlo.setMargin(false);\r
- \r
- final AbstractComponent c1 = getTestTable();\r
- c1.setSizeFull();\r
- final AbstractComponent c2 = getTestTable();\r
- c2.setSizeFull();\r
- \r
- final Button button1 = new Button("Set margin on");\r
- final Button button2 = new Button("Set spacing on");\r
- final Button button3 = new Button("Set margin off");\r
- final Button button4 = new Button("Set spacing off");\r
- \r
- vlo.addComponent(button1);\r
- vlo.addComponent(button2);\r
- vlo.addComponent(button3);\r
- vlo.addComponent(button4);\r
- button1.setEnabled(true);\r
- button2.setEnabled(false);\r
- button3.setEnabled(false);\r
- button4.setEnabled(false);\r
- \r
- baseLayout.addComponent(vlo);\r
- final VerticalLayout vlo2 = getTestLaytout();\r
- \r
- vlo2.addComponent(c1);\r
- vlo2.addComponent(new Label("<hr />", ContentMode.XHTML));\r
- vlo2.addComponent(c2);\r
- vlo2.setExpandRatio(c1, 0.5f);\r
- vlo2.setExpandRatio(c2, 0.5f);\r
- baseLayout.addComponent(vlo2);\r
- \r
- button1.addListener(new Button.ClickListener() {\r
- private static final long serialVersionUID = 7716267156088629379L;\r
- \r
- public void buttonClick(ClickEvent event) {\r
- vlo2.setMargin(true);\r
- button1.setEnabled(false);\r
- button2.setEnabled(true);\r
- }\r
- });\r
- button2.addListener(new Button.ClickListener() {\r
- private static final long serialVersionUID = 7716267156088629379L;\r
- \r
- public void buttonClick(ClickEvent event) {\r
- vlo2.setSpacing(true);\r
- button2.setEnabled(false);\r
- button3.setEnabled(true);\r
- }\r
- });\r
- button3.addListener(new Button.ClickListener() {\r
- private static final long serialVersionUID = 7716267156088629379L;\r
- \r
- public void buttonClick(ClickEvent event) {\r
- vlo2.setMargin(false);\r
- button3.setEnabled(false);\r
- button4.setEnabled(true);\r
- }\r
- });\r
- button4.addListener(new Button.ClickListener() {\r
- private static final long serialVersionUID = 7716267156088629379L;\r
- \r
- public void buttonClick(ClickEvent event) {\r
- vlo2.setSpacing(false);\r
- button4.setEnabled(false);\r
- }\r
- });\r
- \r
- return baseLayout;\r
- }\r
- \r
- @Override\r
- protected Layout getRequiredErrorIndicatorsTests() {\r
- Layout baseLayout = getBaseLayout();\r
- VerticalLayout vlo = getTestLaytout();\r
- AbstractComponent[] components = new AbstractComponent[4];\r
- components[0] = new Label("LABEL");\r
- components[0].setSizeUndefined();\r
- components[1] = new Button("BUTTON");\r
- components[2] = getTestTable();\r
- components[3] = getTestTabsheet();\r
- components[3].setIcon(new ThemeResource(LOCK_16_PNG));\r
- \r
- AbstractField<?>[] fields = new AbstractField<?>[6];\r
- fields[0] = new TextField();\r
- fields[0].setRequired(true);\r
- fields[0].setValidationVisible(true);\r
- fields[0].setRequiredError("required error");\r
- \r
- fields[1] = new TextField();\r
- fields[1].setValue("TEXTFIELD2");\r
- fields[1]\r
- .setComponentError(new UserError("component error, user error"));\r
- \r
- fields[2] = new Select();\r
- fields[2].setComponentError(new SystemError(\r
- "component error, system error"));\r
- fields[3] = new DateField();\r
- fields[3].setComponentError(new SystemError(\r
- "component error, system error"));\r
- \r
- fields[4] = new CheckBox();\r
- fields[4]\r
- .setComponentError(new UserError("component error, user error"));\r
- \r
- fields[5] = new NativeSelect();\r
- fields[5].setRequired(true);\r
- fields[5].setValidationVisible(true);\r
- fields[5].setRequiredError("required error");\r
- fields[5]\r
- .setComponentError(new UserError("component error, user error"));\r
- fields[5].setIcon(new ThemeResource(CALENDAR_32_PNG));\r
- \r
- for (int i = 0; i < components.length; i++) {\r
- components[i].setComponentError(new UserError(\r
- "component error, user error"));\r
- vlo.addComponent(components[i]);\r
- }\r
- baseLayout.addComponent(vlo);\r
- final VerticalLayout vlo2 = getTestLaytout();\r
- for (int i = 0; i < fields.length; i++) {\r
- vlo2.addComponent(fields[i]);\r
- }\r
- \r
- baseLayout.addComponent(vlo2);\r
- return baseLayout;\r
- }\r
- \r
- private HorizontalLayout getBaseLayout() {\r
- HorizontalLayout hlo = new HorizontalLayout();\r
- hlo.setSizeUndefined();\r
- return hlo;\r
- }\r
- \r
- private VerticalLayout getTestLaytout() {\r
- VerticalLayout vlo = new VerticalLayout();\r
- vlo.setHeight("500px");\r
- vlo.setWidth("400px");\r
- return vlo;\r
- }\r
- \r
- private AbstractComponent getTestTabsheet() {\r
- TabSheet tabsheet = new TabSheet();\r
- tabsheet.setSizeUndefined();\r
- tabsheet.addTab(new UndefWideLabel("TAB1"), "TAB1", new ThemeResource(\r
- GLOBE_16_PNG));\r
- tabsheet.addTab(new UndefWideLabel("TAB2"), "TAB2", null);\r
- return tabsheet;\r
- }\r
- \r
- private Table getTestTable() {\r
- Table t = new Table();\r
- t.setSizeUndefined();\r
- t.setPageLength(5);\r
- t.addContainerProperty("test", String.class, null);\r
- t.addItem(new Object[] { "qwertyuiop asdfghjköäxccvbnm,m,." }, 1);\r
- t.addItem(new Object[] { "YGVYTCTCTRXRXRXRX" }, 2);\r
- return t;\r
- }\r
- }\r
+ package com.vaadin.tests.layouts.layouttester;
+
+ import com.vaadin.Application;
+ import com.vaadin.terminal.Resource;
+ import com.vaadin.terminal.SystemError;
+ import com.vaadin.terminal.ThemeResource;
+ import com.vaadin.terminal.UserError;
+ import com.vaadin.ui.AbstractComponent;
+ import com.vaadin.ui.AbstractField;
+ import com.vaadin.ui.Alignment;
+ import com.vaadin.ui.Button;
+ import com.vaadin.ui.Button.ClickEvent;
+ import com.vaadin.ui.CheckBox;
+ import com.vaadin.ui.DateField;
+ import com.vaadin.ui.HorizontalLayout;
+ import com.vaadin.ui.Label;
++import com.vaadin.ui.Label.ContentMode;
+ import com.vaadin.ui.Layout;
+ import com.vaadin.ui.Link;
+ import com.vaadin.ui.NativeSelect;
+ import com.vaadin.ui.Select;
+ import com.vaadin.ui.TabSheet;
+ import com.vaadin.ui.Table;
+ import com.vaadin.ui.TextField;
+ import com.vaadin.ui.VerticalLayout;
+
+ public class VerticalLayoutTests extends AbstractLayoutTests {
+
+ public VerticalLayoutTests(Application application) {
+ super();
+ }
+
+ @Override
+ protected Layout getAlignmentTests() {
+ Layout baseLayout = getBaseLayout();
+ ((HorizontalLayout) baseLayout).setSpacing(true);
+ VerticalLayout vlo = getTestLaytout();
+ AbstractComponent[] components = new AbstractComponent[9];
+ Alignment[] alignments = new Alignment[] { Alignment.BOTTOM_CENTER,
+ Alignment.BOTTOM_LEFT, Alignment.BOTTOM_RIGHT,
+ Alignment.MIDDLE_CENTER, Alignment.MIDDLE_LEFT,
+ Alignment.MIDDLE_RIGHT, Alignment.TOP_CENTER,
+ Alignment.TOP_LEFT, Alignment.TOP_RIGHT };
+
+ for (int i = 0; i < components.length / 2; i++) {
+ components[i] = new TextField();
+ ((TextField) components[i]).setValue("FIELD " + i);
+ vlo.addComponent(components[i]);
+ vlo.setComponentAlignment(components[i], alignments[i]);
- vlo.addComponent(new Label("<hr />", Label.CONTENT_XHTML));
++ vlo.addComponent(new Label("<hr />", ContentMode.XHTML));
+ }
+ baseLayout.addComponent(vlo);
+ vlo = getTestLaytout();
+ for (int i = components.length / 2; i < components.length; i++) {
+ components[i] = new TextField();
+ ((TextField) components[i]).setValue("FIELD " + i);
+ vlo.addComponent(components[i]);
+ vlo.setComponentAlignment(components[i], alignments[i]);
- vlo.addComponent(new Label("<hr />", Label.CONTENT_XHTML));
++ vlo.addComponent(new Label("<hr />", ContentMode.XHTML));
+ }
+ baseLayout.addComponent(vlo);
+ return baseLayout;
+ }
+
+ @Override
+ protected Layout getCaptionsTests() {
+ Layout baseLayout = getBaseLayout();
+ VerticalLayout vlo = getTestLaytout();
+ AbstractComponent component = null;
+
+ String[] captions = new String[] {
+ "",
+ "abcdefghijklmnopq",
+ "abc def hij klm nop qrs tuv xyz qaz wsx edc rfv tgb yhn ujm mko nji bhu vgy cft cde" };
+
+ for (int i = 0; i < captions.length; i++) {
+ component = new TextField();
+ ((TextField) component).setValue("FIELD " + i);
+ component.setCaption(captions[i]);
+ vlo.addComponent(component);
+ }
+ for (int i = 0; i < captions.length; i++) {
+ component = new Label();
+ ((Label) component).setValue("Label " + i);
+ component.setCaption(captions[i]);
+ vlo.addComponent(component);
+ }
+ baseLayout.addComponent(vlo);
+ vlo = getTestLaytout();
+ for (int i = 0; i < captions.length; i++) {
+ component = new Select();
+ component.setCaption(captions[i]);
+ component.setIcon(new ThemeResource(LOCK_16_PNG));
+ vlo.addComponent(component);
+ }
+ for (int i = 0; i < captions.length; i++) {
+ component = getTestTabsheet();
+ component.setCaption(captions[i]);
+ component.setComponentError(new UserError(
+ "component error, user error"));
+ vlo.addComponent(component);
+ }
+ baseLayout.addComponent(vlo);
+ return baseLayout;
+ }
+
+ @Override
+ protected Layout getComponentAddReplaceMoveTests() {
+ Layout baseLayout = getBaseLayout();
+ final VerticalLayout vlo = getTestLaytout();
+ final VerticalLayout vlo2 = getTestLaytout();
+
+ final HorizontalLayout source = new HorizontalLayout();
+ source.addComponent(new Label("OTHER LABEL 1"));
+ source.addComponent(new Label("OTHER LABEL 2"));
+
+ final AbstractComponent c1 = new Button("BUTTON");
+ final AbstractComponent c2 = new Label("<b>LABEL</b>",
- Label.CONTENT_XHTML);
++ ContentMode.XHTML);
+ final AbstractComponent c3 = new Table("TABLE");
+ c3.setHeight("100px");
+ c3.setWidth("100%");
+
+ final Button addButton = new Button("Test add");
+ final Button replaceButton = new Button("Test replace");
+ final Button moveButton = new Button("Test move");
+ final Button removeButton = new Button("Test remove");
+
+ replaceButton.setEnabled(false);
+ moveButton.setEnabled(false);
+ removeButton.setEnabled(false);
+
+ addButton.addListener(new Button.ClickListener() {
+ private static final long serialVersionUID = 7716267156088629379L;
+
+ public void buttonClick(ClickEvent event) {
+ vlo2.addComponent(new TextField());
+ addButton.setEnabled(false);
+ replaceButton.setEnabled(true);
+ }
+ });
+ replaceButton.addListener(new Button.ClickListener() {
+ private static final long serialVersionUID = 7716267156088629379L;
+
+ public void buttonClick(ClickEvent event) {
+ vlo2.replaceComponent(c1, c3);
+ replaceButton.setEnabled(false);
+ moveButton.setEnabled(true);
+ }
+ });
+ moveButton.addListener(new Button.ClickListener() {
+ private static final long serialVersionUID = 7716267156088629379L;
+
+ public void buttonClick(ClickEvent event) {
+ vlo2.moveComponentsFrom(source);
+ moveButton.setEnabled(false);
+ removeButton.setEnabled(true);
+ }
+ });
+ removeButton.addListener(new Button.ClickListener() {
+ private static final long serialVersionUID = 7716267156088629379L;
+
+ public void buttonClick(ClickEvent event) {
+ vlo2.removeComponent(c1);
+ vlo2.removeComponent(c2);
+ removeButton.setEnabled(false);
+ }
+ });
+
+ vlo.addComponent(addButton);
+ vlo.addComponent(replaceButton);
+ vlo.addComponent(moveButton);
+ vlo.addComponent(removeButton);
+
+ baseLayout.addComponent(vlo);
+ vlo2.addComponent(c1);
+ vlo2.addComponent(c2);
+ vlo2.addComponent(c3);
+ baseLayout.addComponent(vlo2);
+ return baseLayout;
+ }
+
+ @Override
+ protected Layout getComponentSizingTests() {
+ Layout baseLayout = getBaseLayout();
+ final VerticalLayout vlo = getTestLaytout();
+
+ final AbstractComponent c = getTestTable();
+
+ final Button biggerButton = new Button("full size");
+ final Button smallerButton = new Button("200 px width");
+ final Button originalButton = new Button("undefined size and add");
+
+ vlo.addComponent(biggerButton);
+ vlo.addComponent(smallerButton);
+ vlo.addComponent(originalButton);
+ baseLayout.addComponent(vlo);
+ final VerticalLayout vlo2 = getTestLaytout();
+ vlo2.addComponent(c);
+ baseLayout.addComponent(vlo2);
+
+ biggerButton.setEnabled(true);
+ smallerButton.setEnabled(false);
+ originalButton.setEnabled(false);
+
+ biggerButton.addListener(new Button.ClickListener() {
+ private static final long serialVersionUID = 7716267156088629379L;
+
+ public void buttonClick(ClickEvent event) {
+ c.setSizeFull();
+ biggerButton.setEnabled(false);
+ smallerButton.setEnabled(true);
+ }
+ });
+ smallerButton.addListener(new Button.ClickListener() {
+ private static final long serialVersionUID = 7716267156088629379L;
+
+ public void buttonClick(ClickEvent event) {
+ c.setWidth("200px");
+ smallerButton.setEnabled(false);
+ originalButton.setEnabled(true);
+ }
+ });
+ originalButton.addListener(new Button.ClickListener() {
+ private static final long serialVersionUID = 7716267156088629379L;
+
+ public void buttonClick(ClickEvent event) {
+ originalButton.setEnabled(false);
+ c.setSizeUndefined();
+ ((Table) c)
+ .addItem(
+ new Object[] { "VYVTCTC VYVYV ECECCE NIDSD SDMPOM" },
+ 3);
+ }
+ });
+
+ return baseLayout;
+ }
+
+ @Override
+ protected Layout getLayoutSizingTests() {
+ Layout baseLayout = getBaseLayout();
+ final VerticalLayout vlo = getTestLaytout();
+
+ vlo.setSpacing(false);
+ vlo.setMargin(false);
+
+ final AbstractComponent c1 = getTestTable();
+ c1.setSizeFull();
+ final AbstractComponent c2 = getTestTable();
+ c2.setSizeFull();
+
+ final Button button1 = new Button("Set fixed height 350px");
+ final Button button2 = new Button(
+ "Set undefined size and add component");
+ final Button button3 = new Button("Set fixed width and height 75%");
+ final Button button4 = new Button("Set size full");
+
+ vlo.addComponent(button1);
+ vlo.addComponent(button2);
+ vlo.addComponent(button3);
+ vlo.addComponent(button4);
+ baseLayout.addComponent(vlo);
+ final VerticalLayout vlo2 = getTestLaytout();
+
+ button1.setEnabled(true);
+ button2.setEnabled(false);
+ button3.setEnabled(false);
+ button4.setEnabled(false);
+
+ vlo2.addComponent(c1);
- vlo2.addComponent(new Label("<hr />", Label.CONTENT_XHTML));
++ vlo2.addComponent(new Label("<hr />", ContentMode.XHTML));
+ vlo2.addComponent(c2);
+ vlo2.setExpandRatio(c1, 0.5f);
+ vlo2.setExpandRatio(c2, 0.5f);
+ baseLayout.addComponent(vlo2);
+
+ button1.addListener(new Button.ClickListener() {
+ private static final long serialVersionUID = 7716267156088629379L;
+
+ public void buttonClick(ClickEvent event) {
+ vlo2.setHeight("350px");
+ button1.setEnabled(false);
+ button2.setEnabled(true);
+ }
+ });
+ button2.addListener(new Button.ClickListener() {
+ private static final long serialVersionUID = 7716267156088629379L;
+
+ public void buttonClick(ClickEvent event) {
+ vlo2.setSizeUndefined();
+ vlo2.addComponent(new Label("--- NEW LABEL ---"));
+ button2.setEnabled(false);
+ button3.setEnabled(true);
+ }
+ });
+ button3.addListener(new Button.ClickListener() {
+ private static final long serialVersionUID = 7716267156088629379L;
+
+ public void buttonClick(ClickEvent event) {
+ vlo2.setWidth("75%");
+ vlo2.setHeight("75%");
+ button3.setEnabled(false);
+ button4.setEnabled(true);
+ }
+ });
+ button4.addListener(new Button.ClickListener() {
+ private static final long serialVersionUID = 7716267156088629379L;
+
+ public void buttonClick(ClickEvent event) {
+ vlo2.setSizeFull();
+ button4.setEnabled(false);
+ }
+ });
+
+ return baseLayout;
+ }
+
+ @Override
+ protected Layout getExpandRatiosTests() {
+ Layout baseLayout = getBaseLayout();
+ final VerticalLayout vlo = getTestLaytout();
+
+ final AbstractComponent c1 = getTestTable();
+ c1.setSizeFull();
+ final AbstractComponent c2 = getTestTable();
+ c2.setSizeFull();
+
+ final Button button1 = new Button("Expand to 1/undefined");
+ final Button button2 = new Button("Expand to 0.5/0.5");
+ final Button button3 = new Button("Expand to 0.75/0.25");
+
+ vlo.addComponent(button1);
+ vlo.addComponent(button2);
+ vlo.addComponent(button3);
+ button1.setEnabled(true);
+ button2.setEnabled(false);
+ button3.setEnabled(false);
+
+ baseLayout.addComponent(vlo);
+ final VerticalLayout vlo2 = getTestLaytout();
+
+ vlo2.addComponent(c1);
+ vlo2.addComponent(c2);
+ baseLayout.addComponent(vlo2);
+
+ button1.addListener(new Button.ClickListener() {
+ private static final long serialVersionUID = 7716267156088629379L;
+
+ public void buttonClick(ClickEvent event) {
+ vlo2.setExpandRatio(c1, 1.0f);
+ button1.setEnabled(false);
+ button2.setEnabled(true);
+ }
+ });
+ button2.addListener(new Button.ClickListener() {
+ private static final long serialVersionUID = 7716267156088629379L;
+
+ public void buttonClick(ClickEvent event) {
+ vlo2.setExpandRatio(c1, 0.5f);
+ vlo2.setExpandRatio(c2, 0.5f);
+ button2.setEnabled(false);
+ button3.setEnabled(true);
+ }
+ });
+ button3.addListener(new Button.ClickListener() {
+ private static final long serialVersionUID = 7716267156088629379L;
+
+ public void buttonClick(ClickEvent event) {
+ vlo2.setExpandRatio(c1, 0.75f);
+ vlo2.setExpandRatio(c2, 0.25f);
+ button3.setEnabled(false);
+ }
+ });
+ return baseLayout;
+ }
+
+ @Override
+ protected Layout getIconsTests() {
+ Layout baseLayout = getBaseLayout();
+ VerticalLayout vlo = getTestLaytout();
+ AbstractComponent[] components = new AbstractComponent[2];
+
+ Resource[] icons = new Resource[] { new ThemeResource(CALENDAR_32_PNG),
+ new ThemeResource(LOCK_16_PNG) };
+
+ for (int i = 0; i < components.length; i++) {
+ components[i] = new TextField();
+ ((TextField) components[i]).setValue("FIELD " + i);
+ components[i].setIcon(icons[i]);
+ components[i]
+ .setCaption("long test caption bewucbwuebco or bmort b cbwecubw wbeucwe asdasd asdasda asdasd");
+ vlo.addComponent(components[i]);
+ }
+
+ for (int i = 0; i < components.length; i++) {
+ components[i] = new Label();
+ ((Label) components[i]).setValue("Label " + i);
+ components[i].setIcon(icons[i]);
+ vlo.addComponent(components[i]);
+ }
+
+ for (int i = 0; i < components.length; i++) {
+ components[i] = new Select();
+ components[i].setIcon(icons[i]);
+ vlo.addComponent(components[i]);
+ }
+ baseLayout.addComponent(vlo);
+ final VerticalLayout vlo2 = getTestLaytout();
+ for (int i = 0; i < components.length; i++) {
+ components[i] = new Button();
+ components[i].setComponentError(new UserError(
+ "component error, user error"));
+ components[i].setIcon(icons[i]);
+ vlo2.addComponent(components[i]);
+ }
+
+ for (int i = 0; i < components.length; i++) {
+ components[i] = new Link("Link", null);
+ components[i].setIcon(icons[i]);
+ vlo2.addComponent(components[i]);
+ }
+ baseLayout.addComponent(vlo2);
+ return baseLayout;
+ }
+
+ @Override
+ protected Layout getMarginSpacingTests() {
+ Layout baseLayout = getBaseLayout();
+ final VerticalLayout vlo = getTestLaytout();
+ vlo.setSpacing(false);
+ vlo.setMargin(false);
+
+ final AbstractComponent c1 = getTestTable();
+ c1.setSizeFull();
+ final AbstractComponent c2 = getTestTable();
+ c2.setSizeFull();
+
+ final Button button1 = new Button("Set margin on");
+ final Button button2 = new Button("Set spacing on");
+ final Button button3 = new Button("Set margin off");
+ final Button button4 = new Button("Set spacing off");
+
+ vlo.addComponent(button1);
+ vlo.addComponent(button2);
+ vlo.addComponent(button3);
+ vlo.addComponent(button4);
+ button1.setEnabled(true);
+ button2.setEnabled(false);
+ button3.setEnabled(false);
+ button4.setEnabled(false);
+
+ baseLayout.addComponent(vlo);
+ final VerticalLayout vlo2 = getTestLaytout();
+
+ vlo2.addComponent(c1);
- vlo2.addComponent(new Label("<hr />", Label.CONTENT_XHTML));
++ vlo2.addComponent(new Label("<hr />", ContentMode.XHTML));
+ vlo2.addComponent(c2);
+ vlo2.setExpandRatio(c1, 0.5f);
+ vlo2.setExpandRatio(c2, 0.5f);
+ baseLayout.addComponent(vlo2);
+
+ button1.addListener(new Button.ClickListener() {
+ private static final long serialVersionUID = 7716267156088629379L;
+
+ public void buttonClick(ClickEvent event) {
+ vlo2.setMargin(true);
+ button1.setEnabled(false);
+ button2.setEnabled(true);
+ }
+ });
+ button2.addListener(new Button.ClickListener() {
+ private static final long serialVersionUID = 7716267156088629379L;
+
+ public void buttonClick(ClickEvent event) {
+ vlo2.setSpacing(true);
+ button2.setEnabled(false);
+ button3.setEnabled(true);
+ }
+ });
+ button3.addListener(new Button.ClickListener() {
+ private static final long serialVersionUID = 7716267156088629379L;
+
+ public void buttonClick(ClickEvent event) {
+ vlo2.setMargin(false);
+ button3.setEnabled(false);
+ button4.setEnabled(true);
+ }
+ });
+ button4.addListener(new Button.ClickListener() {
+ private static final long serialVersionUID = 7716267156088629379L;
+
+ public void buttonClick(ClickEvent event) {
+ vlo2.setSpacing(false);
+ button4.setEnabled(false);
+ }
+ });
+
+ return baseLayout;
+ }
+
+ @Override
+ protected Layout getRequiredErrorIndicatorsTests() {
+ Layout baseLayout = getBaseLayout();
+ VerticalLayout vlo = getTestLaytout();
+ AbstractComponent[] components = new AbstractComponent[4];
+ components[0] = new Label("LABEL");
+ components[0].setSizeUndefined();
+ components[1] = new Button("BUTTON");
+ components[2] = getTestTable();
+ components[3] = getTestTabsheet();
+ components[3].setIcon(new ThemeResource(LOCK_16_PNG));
+
- AbstractField[] fields = new AbstractField[6];
++ AbstractField<?>[] fields = new AbstractField<?>[6];
+ fields[0] = new TextField();
+ fields[0].setRequired(true);
+ fields[0].setValidationVisible(true);
+ fields[0].setRequiredError("required error");
+
+ fields[1] = new TextField();
+ fields[1].setValue("TEXTFIELD2");
+ fields[1]
+ .setComponentError(new UserError("component error, user error"));
+
+ fields[2] = new Select();
+ fields[2].setComponentError(new SystemError(
+ "component error, system error"));
+ fields[3] = new DateField();
+ fields[3].setComponentError(new SystemError(
+ "component error, system error"));
+
+ fields[4] = new CheckBox();
+ fields[4]
+ .setComponentError(new UserError("component error, user error"));
+
+ fields[5] = new NativeSelect();
+ fields[5].setRequired(true);
+ fields[5].setValidationVisible(true);
+ fields[5].setRequiredError("required error");
+ fields[5]
+ .setComponentError(new UserError("component error, user error"));
+ fields[5].setIcon(new ThemeResource(CALENDAR_32_PNG));
+
+ for (int i = 0; i < components.length; i++) {
+ components[i].setComponentError(new UserError(
+ "component error, user error"));
+ vlo.addComponent(components[i]);
+ }
+ baseLayout.addComponent(vlo);
+ final VerticalLayout vlo2 = getTestLaytout();
+ for (int i = 0; i < fields.length; i++) {
+ vlo2.addComponent(fields[i]);
+ }
+
+ baseLayout.addComponent(vlo2);
+ return baseLayout;
+ }
+
+ private HorizontalLayout getBaseLayout() {
+ HorizontalLayout hlo = new HorizontalLayout();
+ hlo.setSizeUndefined();
+ return hlo;
+ }
+
+ private VerticalLayout getTestLaytout() {
+ VerticalLayout vlo = new VerticalLayout();
+ vlo.setHeight("500px");
+ vlo.setWidth("400px");
+ return vlo;
+ }
+
+ private AbstractComponent getTestTabsheet() {
+ TabSheet tabsheet = new TabSheet();
+ tabsheet.setSizeUndefined();
+ tabsheet.addTab(new UndefWideLabel("TAB1"), "TAB1", new ThemeResource(
+ GLOBE_16_PNG));
+ tabsheet.addTab(new UndefWideLabel("TAB2"), "TAB2", null);
+ return tabsheet;
+ }
+
+ private Table getTestTable() {
+ Table t = new Table();
+ t.setSizeUndefined();
+ t.setPageLength(5);
+ t.addContainerProperty("test", String.class, null);
+ t.addItem(new Object[] { "qwertyuiop asdfghjköäxccvbnm,m,." }, 1);
+ t.addItem(new Object[] { "YGVYTCTCTRXRXRXRX" }, 2);
+ return t;
+ }
+ }
--- /dev/null
- package com.vaadin.tests.minitutorials;\r
- \r
- import com.vaadin.terminal.WrappedRequest;\r
- import com.vaadin.tests.components.AbstractTestRoot;\r
- import com.vaadin.ui.TextField;\r
- \r
- public class CustomConverterFactoryRoot extends AbstractTestRoot {\r
- @Override\r
- public void setup(WrappedRequest request) {\r
- getApplication().setConverterFactory(new MyConverterFactory());\r
- \r
- TextField tf = new TextField("This is my double field");\r
- tf.setImmediate(true);\r
- tf.setConverter(Double.class);\r
- addComponent(tf);\r
- \r
- // As we do not set the locale explicitly for the field we set the value\r
- // after the field has been attached so it uses the application locale\r
- // for conversion\r
- tf.setConvertedValue(50.1);\r
- \r
- }\r
- \r
- @Override\r
- protected String getTestDescription() {\r
- return "Mini tutorial for https://vaadin.com/wiki/-/wiki/Main/Changing%20the%20default%20converters%20for%20an%20application";\r
- }\r
- \r
- @Override\r
- protected Integer getTicketNumber() {\r
- return null;\r
- }\r
- }\r
++package com.vaadin.tests.minitutorials;
++
++import com.vaadin.terminal.WrappedRequest;
++import com.vaadin.tests.components.AbstractTestRoot;
++import com.vaadin.ui.TextField;
++
++public class CustomConverterFactoryRoot extends AbstractTestRoot {
++ @Override
++ public void setup(WrappedRequest request) {
++ getApplication().setConverterFactory(new MyConverterFactory());
++
++ TextField tf = new TextField("This is my double field");
++ tf.setImmediate(true);
++ tf.setConverter(Double.class);
++ addComponent(tf);
++
++ // As we do not set the locale explicitly for the field we set the value
++ // after the field has been attached so it uses the application locale
++ // for conversion
++ tf.setConvertedValue(50.1);
++
++ }
++
++ @Override
++ protected String getTestDescription() {
++ return "Mini tutorial for https://vaadin.com/wiki/-/wiki/Main/Changing%20the%20default%20converters%20for%20an%20application";
++ }
++
++ @Override
++ protected Integer getTicketNumber() {
++ return null;
++ }
++}
--- /dev/null
- package com.vaadin.tests.minitutorials;\r
- \r
- import com.vaadin.data.util.converter.Converter;\r
- import com.vaadin.data.util.converter.DefaultConverterFactory;\r
- \r
- public class MyConverterFactory extends DefaultConverterFactory {\r
- @Override\r
- protected <PRESENTATION, MODEL> Converter<PRESENTATION, MODEL> findConverter(\r
- Class<PRESENTATION> presentationType, Class<MODEL> modelType) {\r
- // Handle String <-> Double\r
- if (presentationType == String.class && modelType == Double.class) {\r
- return (Converter<PRESENTATION, MODEL>) new MyStringToDoubleConverter();\r
- }\r
- // Let default factory handle the rest\r
- return super.findConverter(presentationType, modelType);\r
- }\r
- }\r
++package com.vaadin.tests.minitutorials;
++
++import com.vaadin.data.util.converter.Converter;
++import com.vaadin.data.util.converter.DefaultConverterFactory;
++
++public class MyConverterFactory extends DefaultConverterFactory {
++ @Override
++ protected <PRESENTATION, MODEL> Converter<PRESENTATION, MODEL> findConverter(
++ Class<PRESENTATION> presentationType, Class<MODEL> modelType) {
++ // Handle String <-> Double
++ if (presentationType == String.class && modelType == Double.class) {
++ return (Converter<PRESENTATION, MODEL>) new MyStringToDoubleConverter();
++ }
++ // Let default factory handle the rest
++ return super.findConverter(presentationType, modelType);
++ }
++}
--- /dev/null
- package com.vaadin.tests.minitutorials;\r
- \r
- import java.text.NumberFormat;\r
- import java.util.Locale;\r
- \r
- import com.vaadin.data.util.converter.StringToDoubleConverter;\r
- \r
- public class MyStringToDoubleConverter extends StringToDoubleConverter {\r
- \r
- @Override\r
- protected NumberFormat getFormat(Locale locale) {\r
- NumberFormat format = super.getFormat(locale);\r
- format.setGroupingUsed(false);\r
- format.setMaximumFractionDigits(3);\r
- format.setMinimumFractionDigits(3);\r
- return format;\r
- }\r
- }\r
++package com.vaadin.tests.minitutorials;
++
++import java.text.NumberFormat;
++import java.util.Locale;
++
++import com.vaadin.data.util.converter.StringToDoubleConverter;
++
++public class MyStringToDoubleConverter extends StringToDoubleConverter {
++
++ @Override
++ protected NumberFormat getFormat(Locale locale) {
++ NumberFormat format = super.getFormat(locale);
++ format.setGroupingUsed(false);
++ format.setMaximumFractionDigits(3);
++ format.setMinimumFractionDigits(3);
++ return format;
++ }
++}
- package com.vaadin.tests.tickets;\r
- \r
- import com.vaadin.Application;\r
- import com.vaadin.ui.Button;\r
- import com.vaadin.ui.Button.ClickEvent;\r
- import com.vaadin.ui.Button.ClickListener;\r
- import com.vaadin.ui.GridLayout;\r
- import com.vaadin.ui.Label;\r
- import com.vaadin.ui.Label.ContentMode;\r
- import com.vaadin.ui.Root.LegacyWindow;\r
- import com.vaadin.ui.TextField;\r
- \r
- public class Ticket124 extends Application.LegacyApplication {\r
- \r
- private TextField tf;\r
- private GridLayout gl;\r
- \r
- @Override\r
- public void init() {\r
- LegacyWindow w = new LegacyWindow(\r
- "#124: Insert & remove row for GridLayout");\r
- setMainWindow(w);\r
- setTheme("tests-tickets");\r
- // gl = new GridLayout(4, 4);\r
- gl = new GridLayout(2, 2);\r
- \r
- tf = new TextField("Row nr");\r
- Button insert = new Button("Insert row", new ClickListener() {\r
- \r
- public void buttonClick(ClickEvent event) {\r
- insertRow();\r
- \r
- }\r
- });\r
- Button delete = new Button("Delete row", new ClickListener() {\r
- \r
- public void buttonClick(ClickEvent event) {\r
- deleteRow();\r
- \r
- }\r
- });\r
- \r
- // gl.addComponent(new Label("0-0"), 0, 0);\r
- // gl.addComponent(new Label("0-1"), 1, 0);\r
- gl.addComponent(new Label("1-0"), 1, 0);\r
- gl.addComponent(new Label("1-1"), 1, 1);\r
- gl.addComponent(new Label("0,0-1,0"), 0, 0, 1, 0);\r
- gl.addComponent(new Label("2,0-3,0"), 2, 0, 3, 0);\r
- Label l = new Label("Large cell 0,1-2,2<br/>yadayada<br/>lorem ipsum");\r
- l.setContentMode(ContentMode.XHTML);\r
- gl.addComponent(l, 0, 1, 2, 2);\r
- gl.addComponent(new Label("3-1"), 3, 1);\r
- gl.addComponent(new Label("3,2-3,3"), 3, 2, 3, 3);\r
- gl.addComponent(tf, 0, 3);\r
- gl.addComponent(insert, 1, 3);\r
- gl.addComponent(delete, 2, 3);\r
- \r
- gl.setStyleName("border");\r
- w.addComponent(gl);\r
- }\r
- \r
- protected void deleteRow() {\r
- int pos = Integer.parseInt(tf.getValue().toString());\r
- gl.removeRow(pos);\r
- \r
- }\r
- \r
- protected void clearRow() {\r
- int pos = Integer.parseInt(tf.getValue().toString());\r
- for (int col = 0; col < gl.getColumns(); col++) {\r
- try {\r
- gl.removeComponent(col, pos);\r
- } catch (Exception e) {\r
- e.printStackTrace();\r
- }\r
- }\r
- \r
- }\r
- \r
- protected void insertRow() {\r
- int pos = Integer.parseInt(tf.getValue().toString());\r
- gl.insertRow(pos);\r
- try {\r
- TextField t = new TextField("", "Newly added row");\r
- t.setWidth("100%");\r
- gl.addComponent(t, 0, pos, 3, pos);\r
- } catch (Exception e) {\r
- // TODO: handle exception\r
- }\r
- }\r
- \r
- }\r
+ package com.vaadin.tests.tickets;
+
+ import com.vaadin.Application;
+ import com.vaadin.ui.Button;
+ import com.vaadin.ui.Button.ClickEvent;
+ import com.vaadin.ui.Button.ClickListener;
+ import com.vaadin.ui.GridLayout;
+ import com.vaadin.ui.Label;
++import com.vaadin.ui.Label.ContentMode;
++import com.vaadin.ui.Root.LegacyWindow;
+ import com.vaadin.ui.TextField;
-import com.vaadin.ui.Window;
+
-public class Ticket124 extends Application {
++public class Ticket124 extends Application.LegacyApplication {
+
+ private TextField tf;
+ private GridLayout gl;
+
+ @Override
+ public void init() {
- Window w = new Window("#124: Insert & remove row for GridLayout");
++ LegacyWindow w = new LegacyWindow(
++ "#124: Insert & remove row for GridLayout");
+ setMainWindow(w);
+ setTheme("tests-tickets");
+ // gl = new GridLayout(4, 4);
+ gl = new GridLayout(2, 2);
+
+ tf = new TextField("Row nr");
+ Button insert = new Button("Insert row", new ClickListener() {
+
+ public void buttonClick(ClickEvent event) {
+ insertRow();
+
+ }
+ });
+ Button delete = new Button("Delete row", new ClickListener() {
+
+ public void buttonClick(ClickEvent event) {
+ deleteRow();
+
+ }
+ });
+
+ // gl.addComponent(new Label("0-0"), 0, 0);
+ // gl.addComponent(new Label("0-1"), 1, 0);
+ gl.addComponent(new Label("1-0"), 1, 0);
+ gl.addComponent(new Label("1-1"), 1, 1);
+ gl.addComponent(new Label("0,0-1,0"), 0, 0, 1, 0);
+ gl.addComponent(new Label("2,0-3,0"), 2, 0, 3, 0);
+ Label l = new Label("Large cell 0,1-2,2<br/>yadayada<br/>lorem ipsum");
- l.setContentMode(Label.CONTENT_XHTML);
++ l.setContentMode(ContentMode.XHTML);
+ gl.addComponent(l, 0, 1, 2, 2);
+ gl.addComponent(new Label("3-1"), 3, 1);
+ gl.addComponent(new Label("3,2-3,3"), 3, 2, 3, 3);
+ gl.addComponent(tf, 0, 3);
+ gl.addComponent(insert, 1, 3);
+ gl.addComponent(delete, 2, 3);
+
+ gl.setStyleName("border");
+ w.addComponent(gl);
+ }
+
+ protected void deleteRow() {
+ int pos = Integer.parseInt(tf.getValue().toString());
+ gl.removeRow(pos);
+
+ }
+
+ protected void clearRow() {
+ int pos = Integer.parseInt(tf.getValue().toString());
+ for (int col = 0; col < gl.getColumns(); col++) {
+ try {
+ gl.removeComponent(col, pos);
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ }
+
+ }
+
+ protected void insertRow() {
+ int pos = Integer.parseInt(tf.getValue().toString());
+ gl.insertRow(pos);
+ try {
+ TextField t = new TextField("", "Newly added row");
+ t.setWidth("100%");
+ gl.addComponent(t, 0, pos, 3, pos);
+ } catch (Exception e) {
+ // TODO: handle exception
+ }
+ }
+
+ }
- package com.vaadin.tests.tickets;\r
- \r
- import com.vaadin.data.Item;\r
- import com.vaadin.data.Property;\r
- import com.vaadin.ui.AbstractSelect;\r
- import com.vaadin.ui.CustomComponent;\r
- import com.vaadin.ui.Label;\r
- import com.vaadin.ui.Root.LegacyWindow;\r
- import com.vaadin.ui.TextField;\r
- import com.vaadin.ui.Tree;\r
- import com.vaadin.ui.VerticalLayout;\r
- import com.vaadin.ui.themes.Reindeer;\r
- \r
- public class Ticket1245 extends com.vaadin.Application.LegacyApplication {\r
- \r
- TextField f = new TextField();\r
- \r
- @Override\r
- public void init() {\r
- final LegacyWindow main = new LegacyWindow(getClass().getName()\r
- .substring(getClass().getName().lastIndexOf(".") + 1));\r
- setMainWindow(main);\r
- \r
- main.addComponent(new TreeExample());\r
- }\r
- }\r
- \r
- class TreeExample extends CustomComponent {\r
- \r
- // Id for the caption property\r
- private static final Object CAPTION_PROPERTY = "caption";\r
- \r
- private static final String desc = "non-first tree in non-sized orderedlayout seems to be the problem";\r
- \r
- Tree tree;\r
- \r
- public TreeExample() {\r
- final VerticalLayout main = new VerticalLayout();\r
- setCompositionRoot(main);\r
- \r
- // Panel w/ Tree\r
- main.setStyleName(Reindeer.PANEL_LIGHT);\r
- main.setWidth("200px");\r
- // // Description, this is needed. Works in first slot\r
- main.addComponent(new Label(desc));\r
- \r
- // setting either width or height fixes the issue\r
- // p.setWidth(500);\r
- // p.setHeight(800);\r
- \r
- // Tree with a few items\r
- tree = new Tree();\r
- tree.setImmediate(true);\r
- // we'll use a property for caption instead of the item id ("value"),\r
- // so that multiple items can have the same caption\r
- tree.addContainerProperty(CAPTION_PROPERTY, String.class, "");\r
- tree.setItemCaptionMode(AbstractSelect.ITEM_CAPTION_MODE_PROPERTY);\r
- tree.setItemCaptionPropertyId(CAPTION_PROPERTY);\r
- for (int i = 1; i <= 3; i++) {\r
- final Object id = addCaptionedItem("Section " + i, null);\r
- tree.expandItem(id);\r
- addCaptionedItem("Team A", id);\r
- addCaptionedItem("Team B", id);\r
- }\r
- main.addComponent(tree);\r
- }\r
- \r
- /**\r
- * Helper to add an item with specified caption and (optional) parent.\r
- * \r
- * @param caption\r
- * The item caption\r
- * @param parent\r
- * The (optional) parent item id\r
- * @return the created item's id\r
- */\r
- private Object addCaptionedItem(String caption, Object parent) {\r
- // add item, let tree decide id\r
- final Object id = tree.addItem();\r
- // get the created item\r
- final Item item = tree.getItem(id);\r
- // set our "caption" property\r
- @SuppressWarnings("unchecked")\r
- final Property<String> p = (Property<String>) item\r
- .getItemProperty(CAPTION_PROPERTY);\r
- p.setValue(caption);\r
- if (parent != null) {\r
- tree.setChildrenAllowed(parent, true);\r
- tree.setParent(id, parent);\r
- tree.setChildrenAllowed(id, false);\r
- }\r
- return id;\r
- }\r
- \r
+ package com.vaadin.tests.tickets;
+
+ import com.vaadin.data.Item;
+ import com.vaadin.data.Property;
+ import com.vaadin.ui.AbstractSelect;
+ import com.vaadin.ui.CustomComponent;
+ import com.vaadin.ui.Label;
++import com.vaadin.ui.Root.LegacyWindow;
+ import com.vaadin.ui.TextField;
+ import com.vaadin.ui.Tree;
+ import com.vaadin.ui.VerticalLayout;
-import com.vaadin.ui.Window;
+ import com.vaadin.ui.themes.Reindeer;
+
-public class Ticket1245 extends com.vaadin.Application {
++public class Ticket1245 extends com.vaadin.Application.LegacyApplication {
+
+ TextField f = new TextField();
+
+ @Override
+ public void init() {
- final Window main = new Window(getClass().getName().substring(
- getClass().getName().lastIndexOf(".") + 1));
++ final LegacyWindow main = new LegacyWindow(getClass().getName()
++ .substring(getClass().getName().lastIndexOf(".") + 1));
+ setMainWindow(main);
+
+ main.addComponent(new TreeExample());
+ }
+ }
+
+ class TreeExample extends CustomComponent {
+
+ // Id for the caption property
+ private static final Object CAPTION_PROPERTY = "caption";
+
+ private static final String desc = "non-first tree in non-sized orderedlayout seems to be the problem";
+
+ Tree tree;
+
+ public TreeExample() {
+ final VerticalLayout main = new VerticalLayout();
+ setCompositionRoot(main);
+
+ // Panel w/ Tree
+ main.setStyleName(Reindeer.PANEL_LIGHT);
+ main.setWidth("200px");
+ // // Description, this is needed. Works in first slot
+ main.addComponent(new Label(desc));
+
+ // setting either width or height fixes the issue
+ // p.setWidth(500);
+ // p.setHeight(800);
+
+ // Tree with a few items
+ tree = new Tree();
+ tree.setImmediate(true);
+ // we'll use a property for caption instead of the item id ("value"),
+ // so that multiple items can have the same caption
+ tree.addContainerProperty(CAPTION_PROPERTY, String.class, "");
+ tree.setItemCaptionMode(AbstractSelect.ITEM_CAPTION_MODE_PROPERTY);
+ tree.setItemCaptionPropertyId(CAPTION_PROPERTY);
+ for (int i = 1; i <= 3; i++) {
+ final Object id = addCaptionedItem("Section " + i, null);
+ tree.expandItem(id);
+ addCaptionedItem("Team A", id);
+ addCaptionedItem("Team B", id);
+ }
+ main.addComponent(tree);
+ }
+
+ /**
+ * Helper to add an item with specified caption and (optional) parent.
+ *
+ * @param caption
+ * The item caption
+ * @param parent
+ * The (optional) parent item id
+ * @return the created item's id
+ */
+ private Object addCaptionedItem(String caption, Object parent) {
+ // add item, let tree decide id
+ final Object id = tree.addItem();
+ // get the created item
+ final Item item = tree.getItem(id);
+ // set our "caption" property
- final Property p = item.getItemProperty(CAPTION_PROPERTY);
++ @SuppressWarnings("unchecked")
++ final Property<String> p = (Property<String>) item
++ .getItemProperty(CAPTION_PROPERTY);
+ p.setValue(caption);
+ if (parent != null) {
+ tree.setChildrenAllowed(parent, true);
+ tree.setParent(id, parent);
+ tree.setChildrenAllowed(id, false);
+ }
+ return id;
+ }
+
-}
+}
- package com.vaadin.tests.tickets;\r
- \r
- import com.vaadin.event.Action;\r
- import com.vaadin.event.Action.Handler;\r
- import com.vaadin.event.ShortcutAction;\r
- import com.vaadin.ui.Label;\r
- import com.vaadin.ui.Root.LegacyWindow;\r
- import com.vaadin.ui.TextField;\r
- \r
- public class Ticket1365 extends com.vaadin.Application.LegacyApplication\r
- implements Handler {\r
- \r
- TextField f = new TextField();\r
- \r
- Label status = new Label("ENTER and CTRL-S fires shortcut action.");\r
- \r
- @Override\r
- public void init() {\r
- final LegacyWindow main = new LegacyWindow(getClass().getName()\r
- .substring(getClass().getName().lastIndexOf(".") + 1));\r
- setMainWindow(main);\r
- \r
- main.addComponent(f);\r
- main.addComponent(status);\r
- main.addActionHandler(this);\r
- f.focus();\r
- \r
- }\r
- \r
- final static private Action[] actions = new Action[] {\r
- new ShortcutAction("Enter", ShortcutAction.KeyCode.ENTER,\r
- new int[] {}),\r
- new ShortcutAction("CTRL-S", ShortcutAction.KeyCode.S,\r
- new int[] { ShortcutAction.ModifierKey.CTRL }), };\r
- \r
- public Action[] getActions(Object target, Object sender) {\r
- return actions;\r
- }\r
- \r
- public void handleAction(Action action, Object sender, Object target) {\r
- status.setValue("Pressed " + action.getCaption()\r
- + " to fire shortcut. Texfield value: " + f.getValue());\r
- f.focus();\r
- }\r
- \r
+ package com.vaadin.tests.tickets;
+
+ import com.vaadin.event.Action;
+ import com.vaadin.event.Action.Handler;
+ import com.vaadin.event.ShortcutAction;
+ import com.vaadin.ui.Label;
++import com.vaadin.ui.Root.LegacyWindow;
+ import com.vaadin.ui.TextField;
-import com.vaadin.ui.Window;
+
-public class Ticket1365 extends com.vaadin.Application implements Handler {
++public class Ticket1365 extends com.vaadin.Application.LegacyApplication
++ implements Handler {
+
+ TextField f = new TextField();
+
+ Label status = new Label("ENTER and CTRL-S fires shortcut action.");
+
+ @Override
+ public void init() {
- final Window main = new Window(getClass().getName().substring(
- getClass().getName().lastIndexOf(".") + 1));
++ final LegacyWindow main = new LegacyWindow(getClass().getName()
++ .substring(getClass().getName().lastIndexOf(".") + 1));
+ setMainWindow(main);
+
+ main.addComponent(f);
+ main.addComponent(status);
+ main.addActionHandler(this);
+ f.focus();
+
+ }
+
+ final static private Action[] actions = new Action[] {
+ new ShortcutAction("Enter", ShortcutAction.KeyCode.ENTER,
+ new int[] {}),
+ new ShortcutAction("CTRL-S", ShortcutAction.KeyCode.S,
+ new int[] { ShortcutAction.ModifierKey.CTRL }), };
+
+ public Action[] getActions(Object target, Object sender) {
+ return actions;
+ }
+
+ public void handleAction(Action action, Object sender, Object target) {
+ status.setValue("Pressed " + action.getCaption()
+ + " to fire shortcut. Texfield value: " + f.getValue());
+ f.focus();
+ }
+
}
- package com.vaadin.tests.tickets;\r
- \r
- import java.util.ArrayList;\r
- import java.util.Collection;\r
- import java.util.HashMap;\r
- import java.util.Map;\r
- \r
- import com.vaadin.data.Container;\r
- import com.vaadin.data.Item;\r
- import com.vaadin.data.Property;\r
- import com.vaadin.data.util.ObjectProperty;\r
- import com.vaadin.data.util.PropertysetItem;\r
- \r
- /**\r
- * @author Efecte R&D\r
- * @version $Revision$, $Date$\r
- */\r
- public class Ticket1506_TestContainer implements Container {\r
- private Map<String, PropertysetItem> items = new HashMap<String, PropertysetItem>();\r
- public static final String ITEM_1_ID = "1";\r
- public static final String ITEM_2_ID = "2";\r
- public static final String PROPERTY_1_ID = "property 1";\r
- public static final String PROPERTY_2_ID = "property 2";\r
- \r
- private void loadItems() {\r
- final PropertysetItem item1 = new PropertysetItem();\r
- item1.addItemProperty(PROPERTY_1_ID, new ObjectProperty<String>(\r
- "value 1", String.class));\r
- item1.addItemProperty(PROPERTY_2_ID, new ObjectProperty<String>(\r
- "name 1", String.class));\r
- items.put(ITEM_1_ID, item1);\r
- \r
- final PropertysetItem item2 = new PropertysetItem();\r
- item2.addItemProperty(PROPERTY_1_ID, new ObjectProperty<String>(\r
- "value 2", String.class));\r
- item2.addItemProperty(PROPERTY_2_ID, new ObjectProperty<String>(\r
- "name 2", String.class));\r
- items.put(ITEM_2_ID, item2);\r
- }\r
- \r
- public Item getItem(Object itemId) {\r
- if (items.isEmpty()) {\r
- loadItems();\r
- }\r
- return items.get(itemId);\r
- }\r
- \r
- public Collection<String> getContainerPropertyIds() {\r
- if (items.isEmpty()) {\r
- loadItems();\r
- }\r
- ArrayList<String> a = new ArrayList<String>();\r
- a.add(PROPERTY_1_ID);\r
- a.add(PROPERTY_2_ID);\r
- return a;\r
- }\r
- \r
- public Collection<String> getItemIds() {\r
- if (items.isEmpty()) {\r
- loadItems();\r
- }\r
- ArrayList<String> a = new ArrayList<String>();\r
- a.add(ITEM_1_ID);\r
- a.add(ITEM_2_ID);\r
- return a;\r
- }\r
- \r
- public Property<?> getContainerProperty(Object itemId, Object propertyId) {\r
- if (items.isEmpty()) {\r
- loadItems();\r
- }\r
- Item item = items.get(itemId);\r
- if (item != null) {\r
- return item.getItemProperty(propertyId);\r
- }\r
- return null;\r
- }\r
- \r
- public Class<String> getType(Object propertyId) {\r
- if (items.isEmpty()) {\r
- loadItems();\r
- }\r
- return String.class;\r
- }\r
- \r
- public int size() {\r
- if (items.isEmpty()) {\r
- loadItems();\r
- }\r
- return items.size();\r
- }\r
- \r
- public boolean containsId(Object itemId) {\r
- if (items.isEmpty()) {\r
- loadItems();\r
- }\r
- return items.containsKey(itemId);\r
- }\r
- \r
- public Item addItem(Object itemId) throws UnsupportedOperationException {\r
- throw new UnsupportedOperationException("Not implemented");\r
- }\r
- \r
- public Object addItem() throws UnsupportedOperationException {\r
- throw new UnsupportedOperationException("Not implemented");\r
- }\r
- \r
- public boolean removeItem(Object itemId)\r
- throws UnsupportedOperationException {\r
- throw new UnsupportedOperationException("Not implemented");\r
- }\r
- \r
- public boolean addContainerProperty(Object propertyId, Class<?> type,\r
- Object defaultValue) throws UnsupportedOperationException {\r
- throw new UnsupportedOperationException("Not implemented");\r
- }\r
- \r
- public boolean removeContainerProperty(Object propertyId)\r
- throws UnsupportedOperationException {\r
- throw new UnsupportedOperationException("Not implemented");\r
- }\r
- \r
- public boolean removeAllItems() throws UnsupportedOperationException {\r
- throw new UnsupportedOperationException("Not implemented");\r
- }\r
- }\r
+ package com.vaadin.tests.tickets;
+
+ import java.util.ArrayList;
+ import java.util.Collection;
+ import java.util.HashMap;
+ import java.util.Map;
+
+ import com.vaadin.data.Container;
+ import com.vaadin.data.Item;
+ import com.vaadin.data.Property;
+ import com.vaadin.data.util.ObjectProperty;
+ import com.vaadin.data.util.PropertysetItem;
+
+ /**
+ * @author Efecte R&D
+ * @version $Revision$, $Date$
+ */
+ public class Ticket1506_TestContainer implements Container {
+ private Map<String, PropertysetItem> items = new HashMap<String, PropertysetItem>();
+ public static final String ITEM_1_ID = "1";
+ public static final String ITEM_2_ID = "2";
+ public static final String PROPERTY_1_ID = "property 1";
+ public static final String PROPERTY_2_ID = "property 2";
+
+ private void loadItems() {
+ final PropertysetItem item1 = new PropertysetItem();
+ item1.addItemProperty(PROPERTY_1_ID, new ObjectProperty<String>(
+ "value 1", String.class));
+ item1.addItemProperty(PROPERTY_2_ID, new ObjectProperty<String>(
+ "name 1", String.class));
+ items.put(ITEM_1_ID, item1);
+
+ final PropertysetItem item2 = new PropertysetItem();
+ item2.addItemProperty(PROPERTY_1_ID, new ObjectProperty<String>(
+ "value 2", String.class));
+ item2.addItemProperty(PROPERTY_2_ID, new ObjectProperty<String>(
+ "name 2", String.class));
+ items.put(ITEM_2_ID, item2);
+ }
+
+ public Item getItem(Object itemId) {
+ if (items.isEmpty()) {
+ loadItems();
+ }
+ return items.get(itemId);
+ }
+
+ public Collection<String> getContainerPropertyIds() {
+ if (items.isEmpty()) {
+ loadItems();
+ }
+ ArrayList<String> a = new ArrayList<String>();
+ a.add(PROPERTY_1_ID);
+ a.add(PROPERTY_2_ID);
+ return a;
+ }
+
+ public Collection<String> getItemIds() {
+ if (items.isEmpty()) {
+ loadItems();
+ }
+ ArrayList<String> a = new ArrayList<String>();
+ a.add(ITEM_1_ID);
+ a.add(ITEM_2_ID);
+ return a;
+ }
+
- public Property getContainerProperty(Object itemId, Object propertyId) {
++ public Property<?> getContainerProperty(Object itemId, Object propertyId) {
+ if (items.isEmpty()) {
+ loadItems();
+ }
+ Item item = items.get(itemId);
+ if (item != null) {
+ return item.getItemProperty(propertyId);
+ }
+ return null;
+ }
+
+ public Class<String> getType(Object propertyId) {
+ if (items.isEmpty()) {
+ loadItems();
+ }
+ return String.class;
+ }
+
+ public int size() {
+ if (items.isEmpty()) {
+ loadItems();
+ }
+ return items.size();
+ }
+
+ public boolean containsId(Object itemId) {
+ if (items.isEmpty()) {
+ loadItems();
+ }
+ return items.containsKey(itemId);
+ }
+
+ public Item addItem(Object itemId) throws UnsupportedOperationException {
+ throw new UnsupportedOperationException("Not implemented");
+ }
+
+ public Object addItem() throws UnsupportedOperationException {
+ throw new UnsupportedOperationException("Not implemented");
+ }
+
+ public boolean removeItem(Object itemId)
+ throws UnsupportedOperationException {
+ throw new UnsupportedOperationException("Not implemented");
+ }
+
+ public boolean addContainerProperty(Object propertyId, Class<?> type,
+ Object defaultValue) throws UnsupportedOperationException {
+ throw new UnsupportedOperationException("Not implemented");
+ }
+
+ public boolean removeContainerProperty(Object propertyId)
+ throws UnsupportedOperationException {
+ throw new UnsupportedOperationException("Not implemented");
+ }
+
+ public boolean removeAllItems() throws UnsupportedOperationException {
+ throw new UnsupportedOperationException("Not implemented");
+ }
+ }
- package com.vaadin.tests.tickets;\r
- \r
- import java.util.ArrayList;\r
- import java.util.Collection;\r
- import java.util.HashMap;\r
- import java.util.Map;\r
- \r
- import com.vaadin.data.Container;\r
- import com.vaadin.data.Item;\r
- import com.vaadin.data.Property;\r
- import com.vaadin.data.util.ObjectProperty;\r
- import com.vaadin.data.util.PropertysetItem;\r
- \r
- /**\r
- * @author Efecte R&D\r
- * @version $Revision$, $Date$\r
- */\r
- public class Ticket1506_TestContainer2 implements Container {\r
- private Map<String, PropertysetItem> items = new HashMap<String, PropertysetItem>();\r
- public static final String ITEM_1_ID = "1";\r
- public static final String ITEM_2_ID = "2";\r
- public static final String PROPERTY_1_ID = "property 1";\r
- public static final String PROPERTY_2_ID = "property 2";\r
- \r
- private void loadItems() {\r
- for (int i = 1; i < 15; i++) {\r
- final PropertysetItem item = new PropertysetItem();\r
- item.addItemProperty(PROPERTY_1_ID, new ObjectProperty<String>(\r
- "value " + i, String.class));\r
- item.addItemProperty(PROPERTY_2_ID, new ObjectProperty<String>(\r
- "name " + i, String.class));\r
- items.put(String.valueOf(i), item);\r
- }\r
- }\r
- \r
- public Item getItem(Object itemId) {\r
- if (items.isEmpty()) {\r
- loadItems();\r
- }\r
- return items.get(itemId);\r
- }\r
- \r
- public Collection<String> getContainerPropertyIds() {\r
- if (items.isEmpty()) {\r
- loadItems();\r
- }\r
- ArrayList<String> a = new ArrayList<String>();\r
- a.add(PROPERTY_1_ID);\r
- a.add(PROPERTY_2_ID);\r
- return a;\r
- }\r
- \r
- public Collection<String> getItemIds() {\r
- if (items.isEmpty()) {\r
- loadItems();\r
- }\r
- return items.keySet();\r
- }\r
- \r
- public Property<?> getContainerProperty(Object itemId, Object propertyId) {\r
- if (items.isEmpty()) {\r
- loadItems();\r
- }\r
- Item item = items.get(itemId);\r
- if (item != null) {\r
- return item.getItemProperty(propertyId);\r
- }\r
- return null;\r
- }\r
- \r
- public Class<String> getType(Object propertyId) {\r
- if (items.isEmpty()) {\r
- loadItems();\r
- }\r
- return String.class;\r
- }\r
- \r
- public int size() {\r
- if (items.isEmpty()) {\r
- loadItems();\r
- }\r
- return items.size();\r
- }\r
- \r
- public boolean containsId(Object itemId) {\r
- if (items.isEmpty()) {\r
- loadItems();\r
- }\r
- return items.containsKey(itemId);\r
- }\r
- \r
- public Item addItem(Object itemId) throws UnsupportedOperationException {\r
- throw new UnsupportedOperationException("Not implemented");\r
- }\r
- \r
- public Object addItem() throws UnsupportedOperationException {\r
- throw new UnsupportedOperationException("Not implemented");\r
- }\r
- \r
- public boolean removeItem(Object itemId)\r
- throws UnsupportedOperationException {\r
- throw new UnsupportedOperationException("Not implemented");\r
- }\r
- \r
- public boolean addContainerProperty(Object propertyId, Class<?> type,\r
- Object defaultValue) throws UnsupportedOperationException {\r
- throw new UnsupportedOperationException("Not implemented");\r
- }\r
- \r
- public boolean removeContainerProperty(Object propertyId)\r
- throws UnsupportedOperationException {\r
- throw new UnsupportedOperationException("Not implemented");\r
- }\r
- \r
- public boolean removeAllItems() throws UnsupportedOperationException {\r
- throw new UnsupportedOperationException("Not implemented");\r
- }\r
+ package com.vaadin.tests.tickets;
+
+ import java.util.ArrayList;
+ import java.util.Collection;
+ import java.util.HashMap;
+ import java.util.Map;
+
+ import com.vaadin.data.Container;
+ import com.vaadin.data.Item;
+ import com.vaadin.data.Property;
+ import com.vaadin.data.util.ObjectProperty;
+ import com.vaadin.data.util.PropertysetItem;
+
+ /**
+ * @author Efecte R&D
+ * @version $Revision$, $Date$
+ */
+ public class Ticket1506_TestContainer2 implements Container {
+ private Map<String, PropertysetItem> items = new HashMap<String, PropertysetItem>();
+ public static final String ITEM_1_ID = "1";
+ public static final String ITEM_2_ID = "2";
+ public static final String PROPERTY_1_ID = "property 1";
+ public static final String PROPERTY_2_ID = "property 2";
+
+ private void loadItems() {
+ for (int i = 1; i < 15; i++) {
+ final PropertysetItem item = new PropertysetItem();
+ item.addItemProperty(PROPERTY_1_ID, new ObjectProperty<String>(
+ "value " + i, String.class));
+ item.addItemProperty(PROPERTY_2_ID, new ObjectProperty<String>(
+ "name " + i, String.class));
+ items.put(String.valueOf(i), item);
+ }
+ }
+
+ public Item getItem(Object itemId) {
+ if (items.isEmpty()) {
+ loadItems();
+ }
+ return items.get(itemId);
+ }
+
+ public Collection<String> getContainerPropertyIds() {
+ if (items.isEmpty()) {
+ loadItems();
+ }
+ ArrayList<String> a = new ArrayList<String>();
+ a.add(PROPERTY_1_ID);
+ a.add(PROPERTY_2_ID);
+ return a;
+ }
+
+ public Collection<String> getItemIds() {
+ if (items.isEmpty()) {
+ loadItems();
+ }
+ return items.keySet();
+ }
+
- public Property getContainerProperty(Object itemId, Object propertyId) {
++ public Property<?> getContainerProperty(Object itemId, Object propertyId) {
+ if (items.isEmpty()) {
+ loadItems();
+ }
+ Item item = items.get(itemId);
+ if (item != null) {
+ return item.getItemProperty(propertyId);
+ }
+ return null;
+ }
+
+ public Class<String> getType(Object propertyId) {
+ if (items.isEmpty()) {
+ loadItems();
+ }
+ return String.class;
+ }
+
+ public int size() {
+ if (items.isEmpty()) {
+ loadItems();
+ }
+ return items.size();
+ }
+
+ public boolean containsId(Object itemId) {
+ if (items.isEmpty()) {
+ loadItems();
+ }
+ return items.containsKey(itemId);
+ }
+
+ public Item addItem(Object itemId) throws UnsupportedOperationException {
+ throw new UnsupportedOperationException("Not implemented");
+ }
+
+ public Object addItem() throws UnsupportedOperationException {
+ throw new UnsupportedOperationException("Not implemented");
+ }
+
+ public boolean removeItem(Object itemId)
+ throws UnsupportedOperationException {
+ throw new UnsupportedOperationException("Not implemented");
+ }
+
+ public boolean addContainerProperty(Object propertyId, Class<?> type,
+ Object defaultValue) throws UnsupportedOperationException {
+ throw new UnsupportedOperationException("Not implemented");
+ }
+
+ public boolean removeContainerProperty(Object propertyId)
+ throws UnsupportedOperationException {
+ throw new UnsupportedOperationException("Not implemented");
+ }
+
+ public boolean removeAllItems() throws UnsupportedOperationException {
+ throw new UnsupportedOperationException("Not implemented");
+ }
}
- package com.vaadin.tests.tickets;\r
- \r
- import com.vaadin.ui.Button;\r
- import com.vaadin.ui.Button.ClickEvent;\r
- import com.vaadin.ui.GridLayout;\r
- import com.vaadin.ui.HorizontalLayout;\r
- import com.vaadin.ui.Label;\r
- import com.vaadin.ui.Panel;\r
- import com.vaadin.ui.Root.LegacyWindow;\r
- \r
- public class Ticket1572 extends com.vaadin.Application.LegacyApplication {\r
- \r
- private Label state;\r
- private GridLayout gl;\r
- private Label spacingstate;\r
- \r
- @Override\r
- public void init() {\r
- \r
- final LegacyWindow main = new LegacyWindow(getClass().getName()\r
- .substring(getClass().getName().lastIndexOf(".") + 1));\r
- setMainWindow(main);\r
- \r
- Panel p = new Panel("Test wrapper for gridlayout margin/spacing");\r
- \r
- p.setContent(new HorizontalLayout());\r
- \r
- gl = new GridLayout(3, 3);\r
- gl.setMargin(true);\r
- for (int i = 0; i < 3 * 3; i++) {\r
- gl.addComponent(new Button("test"));\r
- }\r
- p.addComponent(gl);\r
- p.addComponent(new Label("| next component"));\r
- \r
- Button b = new Button("next margin state");\r
- b.addListener(new Button.ClickListener() {\r
- public void buttonClick(ClickEvent event) {\r
- nextMarginState();\r
- }\r
- \r
- });\r
- \r
- state = new Label();\r
- state.setCaption("Current margin state:");\r
- main.addComponent(state);\r
- main.addComponent(b);\r
- \r
- Button b2 = new Button("next spacing state");\r
- b2.addListener(new Button.ClickListener() {\r
- public void buttonClick(ClickEvent event) {\r
- nextSpacingState();\r
- }\r
- \r
- });\r
- \r
- spacingstate = new Label();\r
- spacingstate.setCaption("Current Spacing State:");\r
- main.addComponent(spacingstate);\r
- main.addComponent(b2);\r
- \r
- main.addComponent(p);\r
- \r
- nextMarginState();\r
- nextSpacingState();\r
- \r
- }\r
- \r
- private int stateCounter = -1;\r
- \r
- private void nextMarginState() {\r
- stateCounter++;\r
- switch (stateCounter) {\r
- case 0:\r
- gl.setMargin(false);\r
- state.setValue("Margin off");\r
- break;\r
- case 1:\r
- gl.setMargin(true);\r
- state.setValue("Margin on");\r
- break;\r
- case 2:\r
- gl.setMargin(true, false, false, false);\r
- state.setValue("Margin top");\r
- break;\r
- case 3:\r
- gl.setMargin(false, true, false, false);\r
- state.setValue("Margin right");\r
- break;\r
- case 4:\r
- gl.setMargin(false, false, true, false);\r
- state.setValue("Margin bottom");\r
- break;\r
- case 5:\r
- gl.setMargin(false, false, false, true);\r
- state.setValue("Margin left");\r
- break;\r
- default:\r
- stateCounter = -1;\r
- nextMarginState();\r
- break;\r
- }\r
- }\r
- \r
- private boolean spacing = true;\r
- \r
- private void nextSpacingState() {\r
- spacing = !spacing;\r
- if (spacing) {\r
- gl.setSpacing(true);\r
- spacingstate.setValue("Spacing on");\r
- } else {\r
- gl.setSpacing(false);\r
- spacingstate.setValue("Spacing off");\r
- }\r
- }\r
- \r
- }\r
+ package com.vaadin.tests.tickets;
+
+ import com.vaadin.ui.Button;
+ import com.vaadin.ui.Button.ClickEvent;
+ import com.vaadin.ui.GridLayout;
+ import com.vaadin.ui.HorizontalLayout;
+ import com.vaadin.ui.Label;
+ import com.vaadin.ui.Panel;
-import com.vaadin.ui.Window;
++import com.vaadin.ui.Root.LegacyWindow;
+
-public class Ticket1572 extends com.vaadin.Application {
++public class Ticket1572 extends com.vaadin.Application.LegacyApplication {
+
+ private Label state;
+ private GridLayout gl;
+ private Label spacingstate;
+
+ @Override
+ public void init() {
+
- final Window main = new Window(getClass().getName().substring(
- getClass().getName().lastIndexOf(".") + 1));
++ final LegacyWindow main = new LegacyWindow(getClass().getName()
++ .substring(getClass().getName().lastIndexOf(".") + 1));
+ setMainWindow(main);
+
+ Panel p = new Panel("Test wrapper for gridlayout margin/spacing");
+
+ p.setContent(new HorizontalLayout());
+
+ gl = new GridLayout(3, 3);
+ gl.setMargin(true);
+ for (int i = 0; i < 3 * 3; i++) {
+ gl.addComponent(new Button("test"));
+ }
+ p.addComponent(gl);
+ p.addComponent(new Label("| next component"));
+
+ Button b = new Button("next margin state");
+ b.addListener(new Button.ClickListener() {
+ public void buttonClick(ClickEvent event) {
+ nextMarginState();
+ }
+
+ });
+
+ state = new Label();
+ state.setCaption("Current margin state:");
+ main.addComponent(state);
+ main.addComponent(b);
+
+ Button b2 = new Button("next spacing state");
+ b2.addListener(new Button.ClickListener() {
+ public void buttonClick(ClickEvent event) {
+ nextSpacingState();
+ }
+
+ });
+
+ spacingstate = new Label();
+ spacingstate.setCaption("Current Spacing State:");
+ main.addComponent(spacingstate);
+ main.addComponent(b2);
+
+ main.addComponent(p);
+
+ nextMarginState();
+ nextSpacingState();
+
+ }
+
+ private int stateCounter = -1;
+
+ private void nextMarginState() {
+ stateCounter++;
+ switch (stateCounter) {
+ case 0:
+ gl.setMargin(false);
+ state.setValue("Margin off");
+ break;
+ case 1:
+ gl.setMargin(true);
+ state.setValue("Margin on");
+ break;
+ case 2:
+ gl.setMargin(true, false, false, false);
+ state.setValue("Margin top");
+ break;
+ case 3:
+ gl.setMargin(false, true, false, false);
+ state.setValue("Margin right");
+ break;
+ case 4:
+ gl.setMargin(false, false, true, false);
+ state.setValue("Margin bottom");
+ break;
+ case 5:
+ gl.setMargin(false, false, false, true);
+ state.setValue("Margin left");
+ break;
+ default:
+ stateCounter = -1;
+ nextMarginState();
+ break;
+ }
+ }
+
+ private boolean spacing = true;
+
+ private void nextSpacingState() {
+ spacing = !spacing;
+ if (spacing) {
+ gl.setSpacing(true);
+ spacingstate.setValue("Spacing on");
+ } else {
+ gl.setSpacing(false);
+ spacingstate.setValue("Spacing off");
+ }
+ }
+
+ }
- package com.vaadin.tests.tickets;\r
- \r
- import java.util.Date;\r
- \r
- import com.vaadin.ui.Button;\r
- import com.vaadin.ui.Button.ClickEvent;\r
- import com.vaadin.ui.Button.ClickListener;\r
- import com.vaadin.ui.Label;\r
- import com.vaadin.ui.ProgressIndicator;\r
- import com.vaadin.ui.Root.LegacyWindow;\r
- \r
- public class Ticket1581 extends com.vaadin.Application.LegacyApplication {\r
- \r
- private Label time;\r
- private ProgressIndicator poller;\r
- private Thread thread;\r
- \r
- @Override\r
- public void init() {\r
- final LegacyWindow main = new LegacyWindow(getClass().getName()\r
- .substring(getClass().getName().lastIndexOf(".") + 1));\r
- setMainWindow(main);\r
- \r
- main.addComponent(new Label("Test the second issue in ticket #1581"));\r
- \r
- time = new Label();\r
- poller = new ProgressIndicator();\r
- poller.setPollingInterval(200);\r
- main.addComponent(time);\r
- main.addComponent(poller);\r
- \r
- thread = new Thread() {\r
- \r
- @Override\r
- public void run() {\r
- super.run();\r
- while (true) {\r
- time.setValue(new Date());\r
- try {\r
- sleep(200);\r
- } catch (InterruptedException e) {\r
- // TODO Auto-generated catch block\r
- e.printStackTrace();\r
- }\r
- }\r
- }\r
- \r
- };\r
- \r
- thread.start();\r
- \r
- final Button stop = new Button("Stop updating", new ClickListener() {\r
- boolean active = true;\r
- \r
- public void buttonClick(ClickEvent event) {\r
- \r
- if (active) {\r
- main.removeComponent(poller);\r
- event.getButton().setCaption("Resume");\r
- } else {\r
- main.addComponent(poller);\r
- event.getButton().setCaption("Stop updating");\r
- }\r
- active = !active;\r
- }\r
- });\r
- \r
- main.addComponent(stop);\r
- }\r
- \r
- }\r
+ package com.vaadin.tests.tickets;
+
+ import java.util.Date;
+
+ import com.vaadin.ui.Button;
+ import com.vaadin.ui.Button.ClickEvent;
+ import com.vaadin.ui.Button.ClickListener;
+ import com.vaadin.ui.Label;
+ import com.vaadin.ui.ProgressIndicator;
-import com.vaadin.ui.Window;
++import com.vaadin.ui.Root.LegacyWindow;
+
-public class Ticket1581 extends com.vaadin.Application {
++public class Ticket1581 extends com.vaadin.Application.LegacyApplication {
+
+ private Label time;
+ private ProgressIndicator poller;
+ private Thread thread;
+
+ @Override
+ public void init() {
- final Window main = new Window(getClass().getName().substring(
- getClass().getName().lastIndexOf(".") + 1));
++ final LegacyWindow main = new LegacyWindow(getClass().getName()
++ .substring(getClass().getName().lastIndexOf(".") + 1));
+ setMainWindow(main);
+
+ main.addComponent(new Label("Test the second issue in ticket #1581"));
+
+ time = new Label();
+ poller = new ProgressIndicator();
+ poller.setPollingInterval(200);
+ main.addComponent(time);
+ main.addComponent(poller);
+
+ thread = new Thread() {
+
+ @Override
+ public void run() {
+ super.run();
+ while (true) {
+ time.setValue(new Date());
+ try {
+ sleep(200);
+ } catch (InterruptedException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+ }
+ }
+
+ };
+
+ thread.start();
+
+ final Button stop = new Button("Stop updating", new ClickListener() {
+ boolean active = true;
+
+ public void buttonClick(ClickEvent event) {
+
+ if (active) {
+ main.removeComponent(poller);
+ event.getButton().setCaption("Resume");
+ } else {
+ main.addComponent(poller);
+ event.getButton().setCaption("Stop updating");
+ }
+ active = !active;
+ }
+ });
+
+ main.addComponent(stop);
+ }
+
+ }
- package com.vaadin.tests.tickets;\r
- \r
- import java.awt.Color;\r
- import java.awt.Graphics;\r
- import java.awt.image.BufferedImage;\r
- import java.io.ByteArrayInputStream;\r
- import java.io.ByteArrayOutputStream;\r
- import java.io.IOException;\r
- import java.util.Date;\r
- \r
- import javax.imageio.ImageIO;\r
- \r
- import com.vaadin.Application;\r
- import com.vaadin.terminal.DownloadStream;\r
- import com.vaadin.terminal.ExternalResource;\r
- import com.vaadin.terminal.RequestHandler;\r
- import com.vaadin.terminal.WrappedRequest;\r
- import com.vaadin.terminal.WrappedResponse;\r
- import com.vaadin.ui.Link;\r
- import com.vaadin.ui.Root.LegacyWindow;\r
- \r
- public class Ticket1589 extends Application.LegacyApplication {\r
- \r
- @Override\r
- public void init() {\r
- LegacyWindow w = new LegacyWindow(getClass().getSimpleName());\r
- setMainWindow(w);\r
- \r
- MyDynamicResource res = new MyDynamicResource();\r
- \r
- addRequestHandler(res);\r
- \r
- w.addComponent(new Link(\r
- "Test (without Content-Disposition, should suggest generatedFile.png when saving, browser default for actual disposition)",\r
- new ExternalResource("myresource")));\r
- \r
- w.addComponent(new Link(\r
- "Test (with Content-Disposition, should popup download dialog that suggests filename downloadedPNG.png)",\r
- new ExternalResource("myresource_download")));\r
- }\r
- }\r
- \r
- class MyDynamicResource implements RequestHandler {\r
- String textToDisplay = (new Date()).toString();\r
- \r
- /**\r
- * Provides the dynamic resource if the URI matches the resource URI. The\r
- * matching URI is "/myresource" under the application URI context.\r
- * \r
- * Returns null if the URI does not match. Otherwise returns a download\r
- * stream that contains the response from the server.\r
- */\r
- public boolean handleRequest(Application application,\r
- WrappedRequest request, WrappedResponse response)\r
- throws IOException {\r
- String relativeUri = request.getRequestPathInfo();\r
- // Catch the given URI that identifies the resource, otherwise let other\r
- // URI handlers or the Application to handle the response.\r
- if (!relativeUri.startsWith("myresource")) {\r
- return false;\r
- }\r
- \r
- // Create an image and draw some background on it.\r
- BufferedImage image = new BufferedImage(200, 200,\r
- BufferedImage.TYPE_INT_RGB);\r
- Graphics drawable = image.getGraphics();\r
- drawable.setColor(Color.lightGray);\r
- drawable.fillRect(0, 0, 200, 200);\r
- drawable.setColor(Color.yellow);\r
- drawable.fillOval(25, 25, 150, 150);\r
- drawable.setColor(Color.blue);\r
- drawable.drawRect(0, 0, 199, 199);\r
- \r
- // Use the parameter to create dynamic content.\r
- drawable.setColor(Color.black);\r
- drawable.drawString("Time: " + textToDisplay, 75, 100);\r
- \r
- try {\r
- // Write the image to a buffer.\r
- ByteArrayOutputStream imagebuffer = new ByteArrayOutputStream();\r
- ImageIO.write(image, "png", imagebuffer);\r
- \r
- // Return a stream from the buffer.\r
- ByteArrayInputStream istream = new ByteArrayInputStream(\r
- imagebuffer.toByteArray());\r
- DownloadStream downloadStream = new DownloadStream(istream,\r
- "image/png", "generatedFile.png");\r
- \r
- if (relativeUri.startsWith("myresource_download")) {\r
- downloadStream.setParameter("Content-Disposition",\r
- "attachment; filename=\"downloadedPNG.png\"");\r
- }\r
- downloadStream.writeTo(response);\r
- return true;\r
- } catch (IOException e) {\r
- return false;\r
- }\r
- }\r
+ package com.vaadin.tests.tickets;
+
+ import java.awt.Color;
+ import java.awt.Graphics;
+ import java.awt.image.BufferedImage;
+ import java.io.ByteArrayInputStream;
+ import java.io.ByteArrayOutputStream;
+ import java.io.IOException;
-import java.net.URL;
+ import java.util.Date;
+
+ import javax.imageio.ImageIO;
+
+ import com.vaadin.Application;
+ import com.vaadin.terminal.DownloadStream;
+ import com.vaadin.terminal.ExternalResource;
-import com.vaadin.terminal.URIHandler;
++import com.vaadin.terminal.RequestHandler;
++import com.vaadin.terminal.WrappedRequest;
++import com.vaadin.terminal.WrappedResponse;
+ import com.vaadin.ui.Link;
-import com.vaadin.ui.Window;
++import com.vaadin.ui.Root.LegacyWindow;
+
-public class Ticket1589 extends Application {
++public class Ticket1589 extends Application.LegacyApplication {
+
+ @Override
+ public void init() {
- Window w = new Window(getClass().getSimpleName());
++ LegacyWindow w = new LegacyWindow(getClass().getSimpleName());
+ setMainWindow(w);
+
+ MyDynamicResource res = new MyDynamicResource();
+
- w.addURIHandler(res);
++ addRequestHandler(res);
+
+ w.addComponent(new Link(
+ "Test (without Content-Disposition, should suggest generatedFile.png when saving, browser default for actual disposition)",
+ new ExternalResource("myresource")));
+
+ w.addComponent(new Link(
+ "Test (with Content-Disposition, should popup download dialog that suggests filename downloadedPNG.png)",
+ new ExternalResource("myresource_download")));
+ }
+ }
+
-class MyDynamicResource implements URIHandler {
++class MyDynamicResource implements RequestHandler {
+ String textToDisplay = (new Date()).toString();
+
+ /**
+ * Provides the dynamic resource if the URI matches the resource URI. The
+ * matching URI is "/myresource" under the application URI context.
+ *
+ * Returns null if the URI does not match. Otherwise returns a download
+ * stream that contains the response from the server.
+ */
- public DownloadStream handleURI(URL context, String relativeUri) {
++ public boolean handleRequest(Application application,
++ WrappedRequest request, WrappedResponse response)
++ throws IOException {
++ String relativeUri = request.getRequestPathInfo();
+ // Catch the given URI that identifies the resource, otherwise let other
+ // URI handlers or the Application to handle the response.
+ if (!relativeUri.startsWith("myresource")) {
- return null;
++ return false;
+ }
+
+ // Create an image and draw some background on it.
+ BufferedImage image = new BufferedImage(200, 200,
+ BufferedImage.TYPE_INT_RGB);
+ Graphics drawable = image.getGraphics();
+ drawable.setColor(Color.lightGray);
+ drawable.fillRect(0, 0, 200, 200);
+ drawable.setColor(Color.yellow);
+ drawable.fillOval(25, 25, 150, 150);
+ drawable.setColor(Color.blue);
+ drawable.drawRect(0, 0, 199, 199);
+
+ // Use the parameter to create dynamic content.
+ drawable.setColor(Color.black);
+ drawable.drawString("Time: " + textToDisplay, 75, 100);
+
+ try {
+ // Write the image to a buffer.
+ ByteArrayOutputStream imagebuffer = new ByteArrayOutputStream();
+ ImageIO.write(image, "png", imagebuffer);
+
+ // Return a stream from the buffer.
+ ByteArrayInputStream istream = new ByteArrayInputStream(
+ imagebuffer.toByteArray());
+ DownloadStream downloadStream = new DownloadStream(istream,
+ "image/png", "generatedFile.png");
+
+ if (relativeUri.startsWith("myresource_download")) {
+ downloadStream.setParameter("Content-Disposition",
+ "attachment; filename=\"downloadedPNG.png\"");
+ }
- return downloadStream;
++ downloadStream.writeTo(response);
++ return true;
+ } catch (IOException e) {
- return null;
++ return false;
+ }
+ }
}
- package com.vaadin.tests.tickets;\r
- \r
- import com.vaadin.terminal.SystemError;\r
- import com.vaadin.ui.Root.LegacyWindow;\r
- import com.vaadin.ui.TextField;\r
- \r
- public class Ticket1663 extends com.vaadin.Application.LegacyApplication {\r
- \r
- @Override\r
- public void init() {\r
- \r
- LegacyWindow main = new LegacyWindow("#1663");\r
- setMainWindow(main);\r
- \r
- TextField tf = new TextField("First name");\r
- tf.setDescription("The first name is used for the administration user interfaces only.");\r
- tf.setComponentError(new SystemError(\r
- "You must enter only one first name."));\r
- \r
- main.addComponent(tf);\r
- }\r
- }\r
+ package com.vaadin.tests.tickets;
+
+ import com.vaadin.terminal.SystemError;
++import com.vaadin.ui.Root.LegacyWindow;
+ import com.vaadin.ui.TextField;
-import com.vaadin.ui.Window;
+
-public class Ticket1663 extends com.vaadin.Application {
++public class Ticket1663 extends com.vaadin.Application.LegacyApplication {
+
+ @Override
+ public void init() {
+
- Window main = new Window("#1663");
++ LegacyWindow main = new LegacyWindow("#1663");
+ setMainWindow(main);
+
+ TextField tf = new TextField("First name");
+ tf.setDescription("The first name is used for the administration user interfaces only.");
+ tf.setComponentError(new SystemError(
+ "You must enter only one first name."));
+
+ main.addComponent(tf);
+ }
+ }
- package com.vaadin.tests.tickets;\r
- \r
- import com.vaadin.Application;\r
- import com.vaadin.ui.Button;\r
- import com.vaadin.ui.Button.ClickEvent;\r
- import com.vaadin.ui.Root.LegacyWindow;\r
- \r
- public class Ticket1673 extends com.vaadin.Application.LegacyApplication {\r
- \r
- @Override\r
- public void init() {\r
- \r
- final LegacyWindow main = new LegacyWindow("#1673");\r
- setMainWindow(main);\r
- \r
- main.addComponent(new Button("close", new Button.ClickListener() {\r
- public void buttonClick(ClickEvent event) {\r
- close();\r
- }\r
- }));\r
- \r
- }\r
- \r
- public static Application.SystemMessages getSystemMessages() {\r
- Application.CustomizedSystemMessages msgs = new Application.CustomizedSystemMessages();\r
- \r
- msgs.setSessionExpiredURL("http://www.vaadin.com/");\r
- msgs.setSessionExpiredCaption("Foo");\r
- msgs.setSessionExpiredMessage("Bar");\r
- \r
- return msgs;\r
- }\r
- }\r
+ package com.vaadin.tests.tickets;
+
+ import com.vaadin.Application;
+ import com.vaadin.ui.Button;
-import com.vaadin.ui.Window;
++import com.vaadin.ui.Button.ClickEvent;
++import com.vaadin.ui.Root.LegacyWindow;
+
-public class Ticket1673 extends com.vaadin.Application {
++public class Ticket1673 extends com.vaadin.Application.LegacyApplication {
+
+ @Override
+ public void init() {
+
- final Window main = new Window("#1673");
++ final LegacyWindow main = new LegacyWindow("#1673");
+ setMainWindow(main);
+
- main.addComponent(new Button("close", this, "close"));
++ main.addComponent(new Button("close", new Button.ClickListener() {
++ public void buttonClick(ClickEvent event) {
++ close();
++ }
++ }));
+
+ }
+
+ public static Application.SystemMessages getSystemMessages() {
+ Application.CustomizedSystemMessages msgs = new Application.CustomizedSystemMessages();
+
+ msgs.setSessionExpiredURL("http://www.vaadin.com/");
+ msgs.setSessionExpiredCaption("Foo");
+ msgs.setSessionExpiredMessage("Bar");
+
+ return msgs;
+ }
+ }
- package com.vaadin.tests.tickets;\r
- \r
- import java.util.Iterator;\r
- \r
- import com.vaadin.data.Property;\r
- import com.vaadin.data.Property.ValueChangeEvent;\r
- import com.vaadin.data.util.MethodProperty;\r
- import com.vaadin.terminal.SystemError;\r
- import com.vaadin.terminal.ThemeResource;\r
- import com.vaadin.ui.AbstractComponent;\r
- import com.vaadin.ui.Button;\r
- import com.vaadin.ui.CheckBox;\r
- import com.vaadin.ui.Component;\r
- import com.vaadin.ui.ComponentContainer;\r
- import com.vaadin.ui.DateField;\r
- import com.vaadin.ui.Form;\r
- import com.vaadin.ui.GridLayout;\r
- import com.vaadin.ui.HorizontalLayout;\r
- import com.vaadin.ui.Label;\r
- import com.vaadin.ui.Layout;\r
- import com.vaadin.ui.Layout.AlignmentHandler;\r
- import com.vaadin.ui.NativeSelect;\r
- import com.vaadin.ui.Panel;\r
- import com.vaadin.ui.Root.LegacyWindow;\r
- import com.vaadin.ui.TextField;\r
- import com.vaadin.ui.VerticalLayout;\r
- \r
- public class Ticket1710 extends com.vaadin.Application.LegacyApplication {\r
- \r
- @Override\r
- public void init() {\r
- \r
- setTheme("tests-tickets");\r
- \r
- VerticalLayout lo = new VerticalLayout();\r
- setMainWindow(new LegacyWindow("#1710", lo));\r
- lo.setMargin(true);\r
- lo.setSpacing(true);\r
- lo.setWidth("100%");\r
- \r
- // Hiding controls\r
- HorizontalLayout hidingControls = new HorizontalLayout();\r
- lo.addComponent(hidingControls);\r
- \r
- // OrderedLayout\r
- final VerticalLayout orderedLayout = new VerticalLayout();\r
- LayoutTestingPanel oltp = new LayoutTestingPanel("OrderedLayout",\r
- orderedLayout);\r
- CheckBox cb = new CheckBox("OrderedLayout",\r
- new MethodProperty<Boolean>(oltp, "visible"));\r
- cb.setImmediate(true);\r
- hidingControls.addComponent(cb);\r
- lo.addComponent(oltp);\r
- orderedLayout.setSpacing(false);\r
- addFields(orderedLayout);\r
- \r
- // GridLayout\r
- GridLayout grid = new GridLayout(1, 1);\r
- Panel g1tp = new LayoutTestingPanel("Gridlayout with 1 column", grid);\r
- cb = new CheckBox("GridLayout (1col)", new MethodProperty<Boolean>(\r
- g1tp, "visible"));\r
- cb.setImmediate(true);\r
- hidingControls.addComponent(cb);\r
- g1tp.setVisible(false);\r
- lo.addComponent(g1tp);\r
- grid.setSpacing(true);\r
- addFields(grid);\r
- GridLayout grid2 = new GridLayout(2, 1);\r
- Panel g2tp = new LayoutTestingPanel("Gridlayout with 2 columns", grid2);\r
- cb = new CheckBox("GridLayout (2cols)", new MethodProperty<Boolean>(\r
- g2tp, "visible"));\r
- cb.setImmediate(true);\r
- hidingControls.addComponent(cb);\r
- g2tp.setVisible(false);\r
- lo.addComponent(g2tp);\r
- grid2.setSpacing(true);\r
- addFields(grid2);\r
- \r
- // ExpandLayout\r
- VerticalLayout el = new VerticalLayout();\r
- Panel elp = new LayoutTestingPanel(\r
- "ExpandLayout width first component expanded", el);\r
- cb = new CheckBox("ExpandLayout (vertical)",\r
- new MethodProperty<Boolean>(elp, "visible"));\r
- cb.setImmediate(true);\r
- hidingControls.addComponent(cb);\r
- elp.setVisible(false);\r
- el.setHeight("700px");\r
- addFields(el);\r
- Component firstComponent = el.getComponentIterator().next();\r
- firstComponent.setSizeFull();\r
- el.setExpandRatio(firstComponent, 1);\r
- lo.addComponent(elp);\r
- HorizontalLayout elh = new HorizontalLayout();\r
- Panel elhp = new LayoutTestingPanel(\r
- "ExpandLayout width first component expanded; horizontal", elh);\r
- cb = new CheckBox("ExpandLayout (horizontal)",\r
- new MethodProperty<Boolean>(elhp, "visible"));\r
- cb.setImmediate(true);\r
- hidingControls.addComponent(cb);\r
- elhp.setVisible(false);\r
- elhp.setScrollable(true);\r
- elh.setWidth("2000px");\r
- elh.setHeight("100px");\r
- addFields(elh);\r
- Component firstComponentElh = elh.getComponentIterator().next();\r
- firstComponentElh.setSizeFull();\r
- elh.setExpandRatio(firstComponentElh, 1);\r
- lo.addComponent(elhp);\r
- \r
- // CustomLayout\r
- VerticalLayout cl = new VerticalLayout();\r
- Panel clp = new LayoutTestingPanel("CustomLayout", cl);\r
- cb = new CheckBox("CustomLayout", new MethodProperty<Boolean>(clp,\r
- "visible"));\r
- cb.setImmediate(true);\r
- hidingControls.addComponent(cb);\r
- clp.setVisible(false);\r
- lo.addComponent(clp);\r
- cl.addComponent(new Label("<<< Add customlayout testcase here >>>"));\r
- \r
- // Form\r
- Panel formPanel = new Panel("Form");\r
- cb = new CheckBox("Form", new MethodProperty<Boolean>(formPanel,\r
- "visible"));\r
- cb.setImmediate(true);\r
- hidingControls.addComponent(cb);\r
- formPanel.setVisible(false);\r
- formPanel.addComponent(getFormPanelExample());\r
- lo.addComponent(formPanel);\r
- \r
- for (Iterator<Component> i = hidingControls.getComponentIterator(); i\r
- .hasNext();) {\r
- ((AbstractComponent) i.next()).setImmediate(true);\r
- }\r
- \r
- }\r
- \r
- private Form getFormPanelExample() {\r
- Form f = new Form();\r
- f.setCaption("Test form");\r
- CheckBox fb2 = new CheckBox("Test button", true);\r
- fb2.setComponentError(new SystemError("Test error"));\r
- f.addField("fb2", fb2);\r
- TextField ft1 = new TextField("With caption");\r
- ft1.setComponentError(new SystemError("Error"));\r
- f.addField("ft1", ft1);\r
- TextField ft2 = new TextField();\r
- ft2.setComponentError(new SystemError("Error"));\r
- ft2.setValue("Without caption");\r
- f.addField("ft2", ft2);\r
- TextField ft3 = new TextField("With caption and required");\r
- ft3.setComponentError(new SystemError("Error"));\r
- ft3.setRequired(true);\r
- f.addField("ft3", ft3);\r
- return f;\r
- }\r
- \r
- private void addFields(ComponentContainer lo) {\r
- Button button = new Button("Test button");\r
- button.setComponentError(new SystemError("Test error"));\r
- lo.addComponent(button);\r
- \r
- CheckBox b2 = new CheckBox("Test button");\r
- b2.setComponentError(new SystemError("Test error"));\r
- lo.addComponent(b2);\r
- \r
- TextField t1 = new TextField("With caption");\r
- t1.setComponentError(new SystemError("Error"));\r
- lo.addComponent(t1);\r
- \r
- TextField t2 = new TextField("With caption and required");\r
- t2.setComponentError(new SystemError("Error"));\r
- t2.setRequired(true);\r
- lo.addComponent(t2);\r
- \r
- TextField t3 = new TextField();\r
- t3.setValue("Without caption");\r
- t3.setComponentError(new SystemError("Error"));\r
- lo.addComponent(t3);\r
- \r
- lo.addComponent(new TextField("Textfield with no error in it"));\r
- \r
- TextField tt1 = new TextField("100% wide Textfield with no error in it");\r
- tt1.setWidth("100%");\r
- lo.addComponent(tt1);\r
- \r
- TextField tt2 = new TextField();\r
- tt2.setWidth("100%");\r
- tt2.setValue("100% wide Textfield with no error in it and no caption");\r
- lo.addComponent(tt2);\r
- \r
- TextField t4 = new TextField();\r
- t4.setValue("Without caption, With required");\r
- t4.setComponentError(new SystemError("Error"));\r
- t4.setRequired(true);\r
- lo.addComponent(t4);\r
- \r
- TextField t5 = new TextField();\r
- t5.setValue("Without caption, WIDE");\r
- t5.setComponentError(new SystemError("Error"));\r
- t5.setWidth("100%");\r
- lo.addComponent(t5);\r
- \r
- TextField t6 = new TextField();\r
- t6.setValue("Without caption, With required, WIDE");\r
- t6.setComponentError(new SystemError("Error"));\r
- t6.setRequired(true);\r
- t6.setWidth("100%");\r
- lo.addComponent(t6);\r
- \r
- TextField t7 = new TextField();\r
- t7.setValue("With icon and required and icon");\r
- t7.setComponentError(new SystemError("Error"));\r
- t7.setRequired(true);\r
- t7.setIcon(new ThemeResource("../runo/icons/16/ok.png"));\r
- lo.addComponent(t7);\r
- \r
- DateField d1 = new DateField(\r
- "Datefield with caption and icon, next one without caption");\r
- d1.setComponentError(new SystemError("Error"));\r
- d1.setRequired(true);\r
- d1.setIcon(new ThemeResource("../runo/icons/16/ok.png"));\r
- lo.addComponent(d1);\r
- \r
- DateField d2 = new DateField();\r
- d2.setComponentError(new SystemError("Error"));\r
- d2.setRequired(true);\r
- lo.addComponent(d2);\r
- }\r
- \r
- public class LayoutTestingPanel extends Panel {\r
- \r
- Layout testedLayout;\r
- \r
- HorizontalLayout controls = new HorizontalLayout();\r
- CheckBox marginLeft = new CheckBox("m-left", false);\r
- CheckBox marginRight = new CheckBox("m-right", false);\r
- CheckBox marginTop = new CheckBox("m-top", false);\r
- CheckBox marginBottom = new CheckBox("m-bottom", false);\r
- CheckBox spacing = new CheckBox("spacing", false);\r
- VerticalLayout testPanelLayout = new VerticalLayout();\r
- \r
- LayoutTestingPanel(String caption, Layout layout) {\r
- super(caption);\r
- VerticalLayout internalLayout = new VerticalLayout();\r
- internalLayout.setWidth("100%");\r
- setContent(internalLayout);\r
- testedLayout = layout;\r
- testPanelLayout.setWidth("100%");\r
- Panel controlWrapper = new Panel();\r
- controlWrapper.addComponent(controls);\r
- controlWrapper.setWidth("100%");\r
- controlWrapper.setScrollable(true);\r
- controlWrapper.setStyleName("controls");\r
- internalLayout.addComponent(controlWrapper);\r
- Panel testPanel = new Panel(testPanelLayout);\r
- testPanel.setStyleName("testarea");\r
- testPanelLayout.addComponent(testedLayout);\r
- internalLayout.addComponent(testPanel);\r
- internalLayout.setMargin(true);\r
- internalLayout.setSpacing(true);\r
- controls.setSpacing(true);\r
- controls.setMargin(false);\r
- controls.addComponent(new Label("width"));\r
- controls.addComponent(new TextField(new MethodProperty<Float>(\r
- testedLayout, "width")));\r
- controls.addComponent(new CheckBox("%",\r
- new MethodProperty<Boolean>(this, "widthPercents")));\r
- controls.addComponent(new Label("height"));\r
- controls.addComponent(new TextField(new MethodProperty<Float>(\r
- testedLayout, "height")));\r
- controls.addComponent(new CheckBox("%",\r
- new MethodProperty<Boolean>(this, "heightPercents")));\r
- controls.addComponent(marginLeft);\r
- controls.addComponent(marginRight);\r
- controls.addComponent(marginTop);\r
- controls.addComponent(marginBottom);\r
- if (testedLayout instanceof Layout.SpacingHandler) {\r
- controls.addComponent(spacing);\r
- }\r
- \r
- Property.ValueChangeListener marginSpacingListener = new Property.ValueChangeListener() {\r
- public void valueChange(ValueChangeEvent event) {\r
- updateMarginsAndSpacing();\r
- }\r
- };\r
- \r
- marginBottom.addListener(marginSpacingListener);\r
- marginTop.addListener(marginSpacingListener);\r
- marginLeft.addListener(marginSpacingListener);\r
- marginRight.addListener(marginSpacingListener);\r
- spacing.addListener(marginSpacingListener);\r
- updateMarginsAndSpacing();\r
- \r
- addAlignmentControls();\r
- \r
- testedLayout.setStyleName("tested-layout");\r
- setStyleName("layout-testing-panel");\r
- \r
- for (Iterator<Component> i = controls.getComponentIterator(); i\r
- .hasNext();) {\r
- ((AbstractComponent) i.next()).setImmediate(true);\r
- }\r
- }\r
- \r
- @SuppressWarnings("deprecation")\r
- private void addAlignmentControls() {\r
- if (!(testedLayout instanceof Layout.AlignmentHandler)) {\r
- return;\r
- }\r
- @SuppressWarnings("unused")\r
- final Layout.AlignmentHandler ah = (AlignmentHandler) testedLayout;\r
- \r
- final NativeSelect vAlign = new NativeSelect();\r
- final NativeSelect hAlign = new NativeSelect();\r
- controls.addComponent(new Label("component alignment"));\r
- controls.addComponent(hAlign);\r
- controls.addComponent(vAlign);\r
- hAlign.setNullSelectionAllowed(false);\r
- vAlign.setNullSelectionAllowed(false);\r
- \r
- vAlign.addItem(new Integer(Layout.AlignmentHandler.ALIGNMENT_TOP));\r
- vAlign.setItemCaption(new Integer(\r
- Layout.AlignmentHandler.ALIGNMENT_TOP), "top");\r
- vAlign.addItem(new Integer(\r
- Layout.AlignmentHandler.ALIGNMENT_VERTICAL_CENTER));\r
- vAlign.setItemCaption(new Integer(\r
- Layout.AlignmentHandler.ALIGNMENT_VERTICAL_CENTER),\r
- "center");\r
- vAlign.addItem(new Integer(Layout.AlignmentHandler.ALIGNMENT_BOTTOM));\r
- vAlign.setItemCaption(new Integer(\r
- Layout.AlignmentHandler.ALIGNMENT_BOTTOM), "bottom");\r
- \r
- hAlign.addItem(new Integer(Layout.AlignmentHandler.ALIGNMENT_LEFT));\r
- hAlign.setItemCaption(new Integer(\r
- Layout.AlignmentHandler.ALIGNMENT_LEFT), "left");\r
- hAlign.addItem(new Integer(\r
- Layout.AlignmentHandler.ALIGNMENT_HORIZONTAL_CENTER));\r
- hAlign.setItemCaption(new Integer(\r
- Layout.AlignmentHandler.ALIGNMENT_HORIZONTAL_CENTER),\r
- "center");\r
- hAlign.addItem(new Integer(Layout.AlignmentHandler.ALIGNMENT_RIGHT));\r
- hAlign.setItemCaption(new Integer(\r
- Layout.AlignmentHandler.ALIGNMENT_RIGHT), "right");\r
- \r
- Property.ValueChangeListener alignmentChangeListener = new Property.ValueChangeListener() {\r
- public void valueChange(ValueChangeEvent event) {\r
- updateAlignments(((Integer) hAlign.getValue()).intValue(),\r
- ((Integer) vAlign.getValue()).intValue());\r
- }\r
- \r
- };\r
- \r
- hAlign.setValue(new Integer(Layout.AlignmentHandler.ALIGNMENT_LEFT));\r
- vAlign.addListener(alignmentChangeListener);\r
- hAlign.addListener(alignmentChangeListener);\r
- vAlign.setValue(new Integer(Layout.AlignmentHandler.ALIGNMENT_TOP));\r
- \r
- controls.addComponent(new Label("layout alignment"));\r
- final NativeSelect lAlign = new NativeSelect();\r
- controls.addComponent(lAlign);\r
- lAlign.setNullSelectionAllowed(false);\r
- lAlign.addItem(new Integer(Layout.AlignmentHandler.ALIGNMENT_LEFT));\r
- lAlign.setItemCaption(new Integer(\r
- Layout.AlignmentHandler.ALIGNMENT_LEFT), "left");\r
- lAlign.addItem(new Integer(\r
- Layout.AlignmentHandler.ALIGNMENT_HORIZONTAL_CENTER));\r
- lAlign.setItemCaption(new Integer(\r
- Layout.AlignmentHandler.ALIGNMENT_HORIZONTAL_CENTER),\r
- "center");\r
- lAlign.addItem(new Integer(Layout.AlignmentHandler.ALIGNMENT_RIGHT));\r
- lAlign.setItemCaption(new Integer(\r
- Layout.AlignmentHandler.ALIGNMENT_RIGHT), "right");\r
- \r
- lAlign.addListener(new Property.ValueChangeListener() {\r
- public void valueChange(ValueChangeEvent event) {\r
- testPanelLayout.setComponentAlignment(testedLayout,\r
- ((Integer) lAlign.getValue()).intValue(),\r
- VerticalLayout.ALIGNMENT_TOP);\r
- }\r
- });\r
- }\r
- \r
- @SuppressWarnings("deprecation")\r
- private void updateAlignments(int h, int v) {\r
- for (Iterator<Component> i = testedLayout.getComponentIterator(); i\r
- .hasNext();) {\r
- ((Layout.AlignmentHandler) testedLayout).setComponentAlignment(\r
- i.next(), h, v);\r
- }\r
- }\r
- \r
- private void updateMarginsAndSpacing() {\r
- testedLayout.setMargin(\r
- ((Boolean) marginTop.getValue()).booleanValue(),\r
- ((Boolean) marginRight.getValue()).booleanValue(),\r
- ((Boolean) marginBottom.getValue()).booleanValue(),\r
- ((Boolean) marginLeft.getValue()).booleanValue());\r
- if (testedLayout instanceof Layout.SpacingHandler) {\r
- ((Layout.SpacingHandler) testedLayout)\r
- .setSpacing(((Boolean) spacing.getValue())\r
- .booleanValue());\r
- }\r
- }\r
- \r
- }\r
- }\r
+ package com.vaadin.tests.tickets;
+
+ import java.util.Iterator;
+
+ import com.vaadin.data.Property;
+ import com.vaadin.data.Property.ValueChangeEvent;
+ import com.vaadin.data.util.MethodProperty;
+ import com.vaadin.terminal.SystemError;
+ import com.vaadin.terminal.ThemeResource;
+ import com.vaadin.ui.AbstractComponent;
+ import com.vaadin.ui.Button;
+ import com.vaadin.ui.CheckBox;
+ import com.vaadin.ui.Component;
+ import com.vaadin.ui.ComponentContainer;
+ import com.vaadin.ui.DateField;
+ import com.vaadin.ui.Form;
+ import com.vaadin.ui.GridLayout;
+ import com.vaadin.ui.HorizontalLayout;
+ import com.vaadin.ui.Label;
+ import com.vaadin.ui.Layout;
+ import com.vaadin.ui.Layout.AlignmentHandler;
+ import com.vaadin.ui.NativeSelect;
+ import com.vaadin.ui.Panel;
++import com.vaadin.ui.Root.LegacyWindow;
+ import com.vaadin.ui.TextField;
+ import com.vaadin.ui.VerticalLayout;
-import com.vaadin.ui.Window;
+
-public class Ticket1710 extends com.vaadin.Application {
++public class Ticket1710 extends com.vaadin.Application.LegacyApplication {
+
+ @Override
+ public void init() {
+
+ setTheme("tests-tickets");
+
+ VerticalLayout lo = new VerticalLayout();
- setMainWindow(new Window("#1710", lo));
++ setMainWindow(new LegacyWindow("#1710", lo));
+ lo.setMargin(true);
+ lo.setSpacing(true);
+ lo.setWidth("100%");
+
+ // Hiding controls
+ HorizontalLayout hidingControls = new HorizontalLayout();
+ lo.addComponent(hidingControls);
+
+ // OrderedLayout
+ final VerticalLayout orderedLayout = new VerticalLayout();
+ LayoutTestingPanel oltp = new LayoutTestingPanel("OrderedLayout",
+ orderedLayout);
+ CheckBox cb = new CheckBox("OrderedLayout",
+ new MethodProperty<Boolean>(oltp, "visible"));
+ cb.setImmediate(true);
+ hidingControls.addComponent(cb);
+ lo.addComponent(oltp);
+ orderedLayout.setSpacing(false);
+ addFields(orderedLayout);
+
+ // GridLayout
+ GridLayout grid = new GridLayout(1, 1);
+ Panel g1tp = new LayoutTestingPanel("Gridlayout with 1 column", grid);
+ cb = new CheckBox("GridLayout (1col)", new MethodProperty<Boolean>(
+ g1tp, "visible"));
+ cb.setImmediate(true);
+ hidingControls.addComponent(cb);
+ g1tp.setVisible(false);
+ lo.addComponent(g1tp);
+ grid.setSpacing(true);
+ addFields(grid);
+ GridLayout grid2 = new GridLayout(2, 1);
+ Panel g2tp = new LayoutTestingPanel("Gridlayout with 2 columns", grid2);
+ cb = new CheckBox("GridLayout (2cols)", new MethodProperty<Boolean>(
+ g2tp, "visible"));
+ cb.setImmediate(true);
+ hidingControls.addComponent(cb);
+ g2tp.setVisible(false);
+ lo.addComponent(g2tp);
+ grid2.setSpacing(true);
+ addFields(grid2);
+
+ // ExpandLayout
+ VerticalLayout el = new VerticalLayout();
+ Panel elp = new LayoutTestingPanel(
+ "ExpandLayout width first component expanded", el);
+ cb = new CheckBox("ExpandLayout (vertical)",
+ new MethodProperty<Boolean>(elp, "visible"));
+ cb.setImmediate(true);
+ hidingControls.addComponent(cb);
+ elp.setVisible(false);
+ el.setHeight("700px");
+ addFields(el);
+ Component firstComponent = el.getComponentIterator().next();
+ firstComponent.setSizeFull();
+ el.setExpandRatio(firstComponent, 1);
+ lo.addComponent(elp);
+ HorizontalLayout elh = new HorizontalLayout();
+ Panel elhp = new LayoutTestingPanel(
+ "ExpandLayout width first component expanded; horizontal", elh);
+ cb = new CheckBox("ExpandLayout (horizontal)",
+ new MethodProperty<Boolean>(elhp, "visible"));
+ cb.setImmediate(true);
+ hidingControls.addComponent(cb);
+ elhp.setVisible(false);
+ elhp.setScrollable(true);
+ elh.setWidth("2000px");
+ elh.setHeight("100px");
+ addFields(elh);
+ Component firstComponentElh = elh.getComponentIterator().next();
+ firstComponentElh.setSizeFull();
+ elh.setExpandRatio(firstComponentElh, 1);
+ lo.addComponent(elhp);
+
+ // CustomLayout
+ VerticalLayout cl = new VerticalLayout();
+ Panel clp = new LayoutTestingPanel("CustomLayout", cl);
+ cb = new CheckBox("CustomLayout", new MethodProperty<Boolean>(clp,
+ "visible"));
+ cb.setImmediate(true);
+ hidingControls.addComponent(cb);
+ clp.setVisible(false);
+ lo.addComponent(clp);
+ cl.addComponent(new Label("<<< Add customlayout testcase here >>>"));
+
+ // Form
+ Panel formPanel = new Panel("Form");
+ cb = new CheckBox("Form", new MethodProperty<Boolean>(formPanel,
+ "visible"));
+ cb.setImmediate(true);
+ hidingControls.addComponent(cb);
+ formPanel.setVisible(false);
+ formPanel.addComponent(getFormPanelExample());
+ lo.addComponent(formPanel);
+
+ for (Iterator<Component> i = hidingControls.getComponentIterator(); i
+ .hasNext();) {
+ ((AbstractComponent) i.next()).setImmediate(true);
+ }
+
+ }
+
+ private Form getFormPanelExample() {
+ Form f = new Form();
+ f.setCaption("Test form");
- Button fb1 = new Button("Test button");
- fb1.setComponentError(new SystemError("Test error"));
- f.addField("fb1", fb1);
+ CheckBox fb2 = new CheckBox("Test button", true);
+ fb2.setComponentError(new SystemError("Test error"));
+ f.addField("fb2", fb2);
+ TextField ft1 = new TextField("With caption");
+ ft1.setComponentError(new SystemError("Error"));
+ f.addField("ft1", ft1);
+ TextField ft2 = new TextField();
+ ft2.setComponentError(new SystemError("Error"));
+ ft2.setValue("Without caption");
+ f.addField("ft2", ft2);
+ TextField ft3 = new TextField("With caption and required");
+ ft3.setComponentError(new SystemError("Error"));
+ ft3.setRequired(true);
+ f.addField("ft3", ft3);
+ return f;
+ }
+
+ private void addFields(ComponentContainer lo) {
+ Button button = new Button("Test button");
+ button.setComponentError(new SystemError("Test error"));
+ lo.addComponent(button);
+
+ CheckBox b2 = new CheckBox("Test button");
+ b2.setComponentError(new SystemError("Test error"));
+ lo.addComponent(b2);
+
+ TextField t1 = new TextField("With caption");
+ t1.setComponentError(new SystemError("Error"));
+ lo.addComponent(t1);
+
+ TextField t2 = new TextField("With caption and required");
+ t2.setComponentError(new SystemError("Error"));
+ t2.setRequired(true);
+ lo.addComponent(t2);
+
+ TextField t3 = new TextField();
+ t3.setValue("Without caption");
+ t3.setComponentError(new SystemError("Error"));
+ lo.addComponent(t3);
+
+ lo.addComponent(new TextField("Textfield with no error in it"));
+
+ TextField tt1 = new TextField("100% wide Textfield with no error in it");
+ tt1.setWidth("100%");
+ lo.addComponent(tt1);
+
+ TextField tt2 = new TextField();
+ tt2.setWidth("100%");
+ tt2.setValue("100% wide Textfield with no error in it and no caption");
+ lo.addComponent(tt2);
+
+ TextField t4 = new TextField();
+ t4.setValue("Without caption, With required");
+ t4.setComponentError(new SystemError("Error"));
+ t4.setRequired(true);
+ lo.addComponent(t4);
+
+ TextField t5 = new TextField();
+ t5.setValue("Without caption, WIDE");
+ t5.setComponentError(new SystemError("Error"));
+ t5.setWidth("100%");
+ lo.addComponent(t5);
+
+ TextField t6 = new TextField();
+ t6.setValue("Without caption, With required, WIDE");
+ t6.setComponentError(new SystemError("Error"));
+ t6.setRequired(true);
+ t6.setWidth("100%");
+ lo.addComponent(t6);
+
+ TextField t7 = new TextField();
+ t7.setValue("With icon and required and icon");
+ t7.setComponentError(new SystemError("Error"));
+ t7.setRequired(true);
+ t7.setIcon(new ThemeResource("../runo/icons/16/ok.png"));
+ lo.addComponent(t7);
+
+ DateField d1 = new DateField(
+ "Datefield with caption and icon, next one without caption");
+ d1.setComponentError(new SystemError("Error"));
+ d1.setRequired(true);
+ d1.setIcon(new ThemeResource("../runo/icons/16/ok.png"));
+ lo.addComponent(d1);
+
+ DateField d2 = new DateField();
+ d2.setComponentError(new SystemError("Error"));
+ d2.setRequired(true);
+ lo.addComponent(d2);
+ }
+
+ public class LayoutTestingPanel extends Panel {
+
+ Layout testedLayout;
+
+ HorizontalLayout controls = new HorizontalLayout();
+ CheckBox marginLeft = new CheckBox("m-left", false);
+ CheckBox marginRight = new CheckBox("m-right", false);
+ CheckBox marginTop = new CheckBox("m-top", false);
+ CheckBox marginBottom = new CheckBox("m-bottom", false);
+ CheckBox spacing = new CheckBox("spacing", false);
+ VerticalLayout testPanelLayout = new VerticalLayout();
+
+ LayoutTestingPanel(String caption, Layout layout) {
+ super(caption);
+ VerticalLayout internalLayout = new VerticalLayout();
+ internalLayout.setWidth("100%");
+ setContent(internalLayout);
+ testedLayout = layout;
+ testPanelLayout.setWidth("100%");
+ Panel controlWrapper = new Panel();
+ controlWrapper.addComponent(controls);
+ controlWrapper.setWidth("100%");
+ controlWrapper.setScrollable(true);
+ controlWrapper.setStyleName("controls");
+ internalLayout.addComponent(controlWrapper);
+ Panel testPanel = new Panel(testPanelLayout);
+ testPanel.setStyleName("testarea");
+ testPanelLayout.addComponent(testedLayout);
+ internalLayout.addComponent(testPanel);
+ internalLayout.setMargin(true);
+ internalLayout.setSpacing(true);
+ controls.setSpacing(true);
+ controls.setMargin(false);
+ controls.addComponent(new Label("width"));
+ controls.addComponent(new TextField(new MethodProperty<Float>(
+ testedLayout, "width")));
+ controls.addComponent(new CheckBox("%",
+ new MethodProperty<Boolean>(this, "widthPercents")));
+ controls.addComponent(new Label("height"));
+ controls.addComponent(new TextField(new MethodProperty<Float>(
+ testedLayout, "height")));
+ controls.addComponent(new CheckBox("%",
+ new MethodProperty<Boolean>(this, "heightPercents")));
+ controls.addComponent(marginLeft);
+ controls.addComponent(marginRight);
+ controls.addComponent(marginTop);
+ controls.addComponent(marginBottom);
+ if (testedLayout instanceof Layout.SpacingHandler) {
+ controls.addComponent(spacing);
+ }
+
+ Property.ValueChangeListener marginSpacingListener = new Property.ValueChangeListener() {
+ public void valueChange(ValueChangeEvent event) {
+ updateMarginsAndSpacing();
+ }
+ };
+
+ marginBottom.addListener(marginSpacingListener);
+ marginTop.addListener(marginSpacingListener);
+ marginLeft.addListener(marginSpacingListener);
+ marginRight.addListener(marginSpacingListener);
+ spacing.addListener(marginSpacingListener);
+ updateMarginsAndSpacing();
+
+ addAlignmentControls();
+
+ testedLayout.setStyleName("tested-layout");
+ setStyleName("layout-testing-panel");
+
+ for (Iterator<Component> i = controls.getComponentIterator(); i
+ .hasNext();) {
+ ((AbstractComponent) i.next()).setImmediate(true);
+ }
+ }
+
+ @SuppressWarnings("deprecation")
+ private void addAlignmentControls() {
+ if (!(testedLayout instanceof Layout.AlignmentHandler)) {
+ return;
+ }
+ @SuppressWarnings("unused")
+ final Layout.AlignmentHandler ah = (AlignmentHandler) testedLayout;
+
+ final NativeSelect vAlign = new NativeSelect();
+ final NativeSelect hAlign = new NativeSelect();
+ controls.addComponent(new Label("component alignment"));
+ controls.addComponent(hAlign);
+ controls.addComponent(vAlign);
+ hAlign.setNullSelectionAllowed(false);
+ vAlign.setNullSelectionAllowed(false);
+
+ vAlign.addItem(new Integer(Layout.AlignmentHandler.ALIGNMENT_TOP));
+ vAlign.setItemCaption(new Integer(
+ Layout.AlignmentHandler.ALIGNMENT_TOP), "top");
+ vAlign.addItem(new Integer(
+ Layout.AlignmentHandler.ALIGNMENT_VERTICAL_CENTER));
+ vAlign.setItemCaption(new Integer(
+ Layout.AlignmentHandler.ALIGNMENT_VERTICAL_CENTER),
+ "center");
+ vAlign.addItem(new Integer(Layout.AlignmentHandler.ALIGNMENT_BOTTOM));
+ vAlign.setItemCaption(new Integer(
+ Layout.AlignmentHandler.ALIGNMENT_BOTTOM), "bottom");
+
+ hAlign.addItem(new Integer(Layout.AlignmentHandler.ALIGNMENT_LEFT));
+ hAlign.setItemCaption(new Integer(
+ Layout.AlignmentHandler.ALIGNMENT_LEFT), "left");
+ hAlign.addItem(new Integer(
+ Layout.AlignmentHandler.ALIGNMENT_HORIZONTAL_CENTER));
+ hAlign.setItemCaption(new Integer(
+ Layout.AlignmentHandler.ALIGNMENT_HORIZONTAL_CENTER),
+ "center");
+ hAlign.addItem(new Integer(Layout.AlignmentHandler.ALIGNMENT_RIGHT));
+ hAlign.setItemCaption(new Integer(
+ Layout.AlignmentHandler.ALIGNMENT_RIGHT), "right");
+
+ Property.ValueChangeListener alignmentChangeListener = new Property.ValueChangeListener() {
+ public void valueChange(ValueChangeEvent event) {
+ updateAlignments(((Integer) hAlign.getValue()).intValue(),
+ ((Integer) vAlign.getValue()).intValue());
+ }
+
+ };
+
+ hAlign.setValue(new Integer(Layout.AlignmentHandler.ALIGNMENT_LEFT));
+ vAlign.addListener(alignmentChangeListener);
+ hAlign.addListener(alignmentChangeListener);
+ vAlign.setValue(new Integer(Layout.AlignmentHandler.ALIGNMENT_TOP));
+
+ controls.addComponent(new Label("layout alignment"));
+ final NativeSelect lAlign = new NativeSelect();
+ controls.addComponent(lAlign);
+ lAlign.setNullSelectionAllowed(false);
+ lAlign.addItem(new Integer(Layout.AlignmentHandler.ALIGNMENT_LEFT));
+ lAlign.setItemCaption(new Integer(
+ Layout.AlignmentHandler.ALIGNMENT_LEFT), "left");
+ lAlign.addItem(new Integer(
+ Layout.AlignmentHandler.ALIGNMENT_HORIZONTAL_CENTER));
+ lAlign.setItemCaption(new Integer(
+ Layout.AlignmentHandler.ALIGNMENT_HORIZONTAL_CENTER),
+ "center");
+ lAlign.addItem(new Integer(Layout.AlignmentHandler.ALIGNMENT_RIGHT));
+ lAlign.setItemCaption(new Integer(
+ Layout.AlignmentHandler.ALIGNMENT_RIGHT), "right");
+
+ lAlign.addListener(new Property.ValueChangeListener() {
+ public void valueChange(ValueChangeEvent event) {
+ testPanelLayout.setComponentAlignment(testedLayout,
+ ((Integer) lAlign.getValue()).intValue(),
+ VerticalLayout.ALIGNMENT_TOP);
+ }
+ });
+ }
+
+ @SuppressWarnings("deprecation")
+ private void updateAlignments(int h, int v) {
+ for (Iterator<Component> i = testedLayout.getComponentIterator(); i
+ .hasNext();) {
+ ((Layout.AlignmentHandler) testedLayout).setComponentAlignment(
+ i.next(), h, v);
+ }
+ }
+
+ private void updateMarginsAndSpacing() {
+ testedLayout.setMargin(
+ ((Boolean) marginTop.getValue()).booleanValue(),
+ ((Boolean) marginRight.getValue()).booleanValue(),
+ ((Boolean) marginBottom.getValue()).booleanValue(),
+ ((Boolean) marginLeft.getValue()).booleanValue());
+ if (testedLayout instanceof Layout.SpacingHandler) {
+ ((Layout.SpacingHandler) testedLayout)
+ .setSpacing(((Boolean) spacing.getValue())
+ .booleanValue());
+ }
+ }
+
+ }
+ }
- package com.vaadin.tests.tickets;\r
- \r
- import com.vaadin.ui.ComboBox;\r
- import com.vaadin.ui.Root.LegacyWindow;\r
- \r
- public class Ticket1767 extends com.vaadin.Application.LegacyApplication {\r
- \r
- @Override\r
- public void init() {\r
- \r
- final LegacyWindow main = new LegacyWindow(getClass().getName()\r
- .substring(getClass().getName().lastIndexOf(".") + 1));\r
- setMainWindow(main);\r
- \r
- ComboBox cb = new ComboBox(" '<' item is not seen in populist?");\r
- cb.addItem("Te<strong>st</strong> < jep >");\r
- cb.addItem("<");\r
- cb.addItem(">");\r
- \r
- cb.addItem("< dsf");\r
- cb.addItem("> sdf");\r
- \r
- cb.addItem("dsfs <");\r
- cb.addItem("sdfsd >");\r
- \r
- main.addComponent(cb);\r
- \r
- }\r
- \r
- }\r
+ package com.vaadin.tests.tickets;
+
+ import com.vaadin.ui.ComboBox;
-import com.vaadin.ui.Window;
++import com.vaadin.ui.Root.LegacyWindow;
+
-public class Ticket1767 extends com.vaadin.Application {
++public class Ticket1767 extends com.vaadin.Application.LegacyApplication {
+
+ @Override
+ public void init() {
+
- final Window main = new Window(getClass().getName().substring(
- getClass().getName().lastIndexOf(".") + 1));
++ final LegacyWindow main = new LegacyWindow(getClass().getName()
++ .substring(getClass().getName().lastIndexOf(".") + 1));
+ setMainWindow(main);
+
+ ComboBox cb = new ComboBox(" '<' item is not seen in populist?");
+ cb.addItem("Te<strong>st</strong> < jep >");
+ cb.addItem("<");
+ cb.addItem(">");
+
+ cb.addItem("< dsf");
+ cb.addItem("> sdf");
+
+ cb.addItem("dsfs <");
+ cb.addItem("sdfsd >");
+
+ main.addComponent(cb);
+
+ }
+
+ }
- package com.vaadin.tests.tickets;\r
- \r
- import com.vaadin.ui.Button;\r
- import com.vaadin.ui.Button.ClickEvent;\r
- import com.vaadin.ui.GridLayout;\r
- import com.vaadin.ui.Root.LegacyWindow;\r
- import com.vaadin.ui.TextField;\r
- \r
- public class Ticket1772 extends com.vaadin.Application.LegacyApplication {\r
- \r
- @Override\r
- public void init() {\r
- \r
- final LegacyWindow main = new LegacyWindow(getClass().getName()\r
- .substring(getClass().getName().lastIndexOf(".") + 1));\r
- setMainWindow(main);\r
- \r
- Button b = new Button("Add content");\r
- main.addComponent(b);\r
- \r
- final GridLayout gridLayout = new GridLayout(2, 2);\r
- main.addComponent(gridLayout);\r
- \r
- b.addListener(new Button.ClickListener() {\r
- int counter = 0;\r
- \r
- public void buttonClick(ClickEvent event) {\r
- \r
- gridLayout\r
- .addComponent(new TextField("Content " + (++counter)));\r
- \r
- }\r
- });\r
- \r
- }\r
- \r
- }\r
+ package com.vaadin.tests.tickets;
+
+ import com.vaadin.ui.Button;
+ import com.vaadin.ui.Button.ClickEvent;
+ import com.vaadin.ui.GridLayout;
++import com.vaadin.ui.Root.LegacyWindow;
+ import com.vaadin.ui.TextField;
-import com.vaadin.ui.Window;
+
-public class Ticket1772 extends com.vaadin.Application {
++public class Ticket1772 extends com.vaadin.Application.LegacyApplication {
+
+ @Override
+ public void init() {
+
- final Window main = new Window(getClass().getName().substring(
- getClass().getName().lastIndexOf(".") + 1));
++ final LegacyWindow main = new LegacyWindow(getClass().getName()
++ .substring(getClass().getName().lastIndexOf(".") + 1));
+ setMainWindow(main);
+
+ Button b = new Button("Add content");
+ main.addComponent(b);
+
+ final GridLayout gridLayout = new GridLayout(2, 2);
+ main.addComponent(gridLayout);
+
+ b.addListener(new Button.ClickListener() {
+ int counter = 0;
+
+ public void buttonClick(ClickEvent event) {
+
+ gridLayout
+ .addComponent(new TextField("Content " + (++counter)));
+
+ }
+ });
+
+ }
+
+ }
- package com.vaadin.tests.tickets;\r
- \r
- import com.vaadin.ui.Button;\r
- import com.vaadin.ui.Button.ClickEvent;\r
- import com.vaadin.ui.CustomLayout;\r
- import com.vaadin.ui.Label;\r
- import com.vaadin.ui.Root.LegacyWindow;\r
- \r
- public class Ticket1775 extends com.vaadin.Application.LegacyApplication {\r
- \r
- @Override\r
- public void init() {\r
- \r
- final LegacyWindow main = new LegacyWindow("#1775");\r
- setMainWindow(main);\r
- setTheme("tests-tickets");\r
- String layoutName = "Ticket1775";\r
- final CustomLayout layout = new CustomLayout(layoutName);\r
- \r
- main.addComponent(layout);\r
- \r
- Button button2 = new Button("Populate content");\r
- main.addComponent(button2);\r
- \r
- final Button button = new Button("Change content");\r
- main.addComponent(button);\r
- \r
- button2.addListener(new Button.ClickListener() {\r
- \r
- public void buttonClick(ClickEvent event) {\r
- Label mainComponent = new Label("Main");\r
- Label header = new Label("Header");\r
- final Label anotherComponent = new Label("another");\r
- layout.addComponent(mainComponent, "body");\r
- layout.addComponent(header, "loginUser");\r
- button.addListener(new Button.ClickListener() {\r
- public void buttonClick(Button.ClickEvent event) {\r
- layout.addComponent(anotherComponent, "body");\r
- layout.removeComponent("loginUser");\r
- }\r
- });\r
- \r
- }\r
- });\r
- \r
- }\r
- \r
- }\r
+ package com.vaadin.tests.tickets;
+
+ import com.vaadin.ui.Button;
+ import com.vaadin.ui.Button.ClickEvent;
+ import com.vaadin.ui.CustomLayout;
+ import com.vaadin.ui.Label;
-import com.vaadin.ui.Window;
++import com.vaadin.ui.Root.LegacyWindow;
+
-public class Ticket1775 extends com.vaadin.Application {
++public class Ticket1775 extends com.vaadin.Application.LegacyApplication {
+
+ @Override
+ public void init() {
+
- final Window main = new Window("#1775");
++ final LegacyWindow main = new LegacyWindow("#1775");
+ setMainWindow(main);
- main.setTheme("tests-tickets");
++ setTheme("tests-tickets");
+ String layoutName = "Ticket1775";
+ final CustomLayout layout = new CustomLayout(layoutName);
+
+ main.addComponent(layout);
+
+ Button button2 = new Button("Populate content");
+ main.addComponent(button2);
+
+ final Button button = new Button("Change content");
+ main.addComponent(button);
+
+ button2.addListener(new Button.ClickListener() {
+
+ public void buttonClick(ClickEvent event) {
+ Label mainComponent = new Label("Main");
+ Label header = new Label("Header");
+ final Label anotherComponent = new Label("another");
+ layout.addComponent(mainComponent, "body");
+ layout.addComponent(header, "loginUser");
+ button.addListener(new Button.ClickListener() {
+ public void buttonClick(Button.ClickEvent event) {
+ layout.addComponent(anotherComponent, "body");
+ layout.removeComponent("loginUser");
+ }
+ });
+
+ }
+ });
+
+ }
+
+ }
- package com.vaadin.tests.tickets;\r
- \r
- import java.util.Iterator;\r
- import java.util.LinkedList;\r
- \r
- import com.vaadin.data.Validator;\r
- import com.vaadin.data.util.MethodProperty;\r
- import com.vaadin.terminal.SystemError;\r
- import com.vaadin.ui.AbstractField;\r
- import com.vaadin.ui.Button;\r
- import com.vaadin.ui.Button.ClickEvent;\r
- import com.vaadin.ui.Label;\r
- import com.vaadin.ui.Label.ContentMode;\r
- import com.vaadin.ui.Root.LegacyWindow;\r
- import com.vaadin.ui.Select;\r
- import com.vaadin.ui.Window;\r
- \r
- public class Ticket1804 extends com.vaadin.Application.LegacyApplication {\r
- \r
- LinkedList<Select> listOfAllFields = new LinkedList<Select>();\r
- \r
- @Override\r
- public void init() {\r
- \r
- final LegacyWindow main = new LegacyWindow("#1804");\r
- setMainWindow(main);\r
- \r
- com.vaadin.ui.Select s;\r
- \r
- s = new Select("Select with null selection allowed; required=true");\r
- s.setNullSelectionAllowed(true);\r
- s.setRequired(true);\r
- listOfAllFields.add(s);\r
- \r
- s = new Select("Select with null selection NOT allowed; required=true");\r
- s.setNullSelectionAllowed(false);\r
- s.setRequired(true);\r
- listOfAllFields.add(s);\r
- \r
- s = new Select("Testcase from the ticket #1804");\r
- s.setNullSelectionAllowed(false);\r
- s.setPropertyDataSource(new MethodProperty<String>(new TestPojo(), "id"));\r
- s.addValidator(new EmptyStringValidator(\r
- "Selection required for test-field"));\r
- s.setRequired(true);\r
- listOfAllFields.add(s);\r
- \r
- s = new Select("Testcase from the ticket #1804, but without validator");\r
- s.setNullSelectionAllowed(false);\r
- s.setPropertyDataSource(new MethodProperty<String>(new TestPojo(), "id"));\r
- s.setRequired(true);\r
- listOfAllFields.add(s);\r
- \r
- s = new Select(\r
- "Testcase from the ticket #1804, but with required=false");\r
- s.setNullSelectionAllowed(false);\r
- s.setPropertyDataSource(new MethodProperty<String>(new TestPojo(), "id"));\r
- s.addValidator(new EmptyStringValidator(\r
- "Selection required for test-field"));\r
- listOfAllFields.add(s);\r
- \r
- s = new Select(\r
- "Testcase from the ticket #1804, but without validator and with required=false");\r
- s.setNullSelectionAllowed(false);\r
- s.setPropertyDataSource(new MethodProperty<String>(new TestPojo(), "id"));\r
- listOfAllFields.add(s);\r
- \r
- s = new Select(\r
- "Required=true, custom error message, null selection not allowed");\r
- s.setRequired(true);\r
- s.setNullSelectionAllowed(false);\r
- s.setPropertyDataSource(new MethodProperty<String>(new TestPojo(), "id"));\r
- s.setValue(null);\r
- s.setComponentError(new SystemError("Test error message"));\r
- listOfAllFields.add(s);\r
- \r
- for (Iterator<Select> i = listOfAllFields.iterator(); i.hasNext();) {\r
- s = i.next();\r
- main.addComponent(s);\r
- s.addItem("foo");\r
- s.addItem("");\r
- s.addItem("bar");\r
- if (s.isNullSelectionAllowed()) {\r
- s.addItem("<null>");\r
- s.setNullSelectionItemId("<null>");\r
- }\r
- s.setImmediate(true);\r
- }\r
- \r
- Button checkValidity = new Button("Check validity of the fields");\r
- main.addComponent(checkValidity);\r
- checkValidity.addListener(new Button.ClickListener() {\r
- \r
- public void buttonClick(ClickEvent event) {\r
- StringBuffer msg = new StringBuffer();\r
- for (Iterator<Select> i = listOfAllFields.iterator(); i\r
- .hasNext();) {\r
- AbstractField<?> af = i.next();\r
- msg.append("<h1>" + af.getCaption() + "</h1>\n");\r
- msg.append("Value=" + af.getValue() + "<br/>\n");\r
- if (af.isValid()) {\r
- msg.append("VALID\n<hr/>");\r
- } else {\r
- msg.append("INVALID<br/><i>" + af.getErrorMessage()\r
- + "</i><hr/>");\r
- }\r
- }\r
- Window w = new Window("Status of the fields");\r
- w.setModal(true);\r
- w.setScrollable(true);\r
- w.setHeight("80%");\r
- w.addComponent(new Label(msg.toString(), ContentMode.XHTML));\r
- main.addWindow(w);\r
- }\r
- });\r
- }\r
- \r
- public class TestPojo {\r
- String id = "";\r
- \r
- public String getId() {\r
- return id;\r
- }\r
- \r
- public void setId(String id) {\r
- this.id = id;\r
- }\r
- \r
- }\r
- \r
- /** Throws an exception when the string is empty or null. */\r
- static class EmptyStringValidator implements Validator {\r
- \r
- String msg;\r
- \r
- EmptyStringValidator(String msg) {\r
- this.msg = msg;\r
- }\r
- \r
- public void validate(Object value) throws InvalidValueException {\r
- if (value == null || value.toString().length() == 0) {\r
- throw new InvalidValueException(msg);\r
- }\r
- }\r
- \r
- }\r
- \r
- }\r
+ package com.vaadin.tests.tickets;
+
+ import java.util.Iterator;
+ import java.util.LinkedList;
+
+ import com.vaadin.data.Validator;
+ import com.vaadin.data.util.MethodProperty;
+ import com.vaadin.terminal.SystemError;
+ import com.vaadin.ui.AbstractField;
+ import com.vaadin.ui.Button;
+ import com.vaadin.ui.Button.ClickEvent;
+ import com.vaadin.ui.Label;
++import com.vaadin.ui.Label.ContentMode;
++import com.vaadin.ui.Root.LegacyWindow;
+ import com.vaadin.ui.Select;
+ import com.vaadin.ui.Window;
+
-public class Ticket1804 extends com.vaadin.Application {
++public class Ticket1804 extends com.vaadin.Application.LegacyApplication {
+
+ LinkedList<Select> listOfAllFields = new LinkedList<Select>();
+
+ @Override
+ public void init() {
+
- final Window main = new Window("#1804");
++ final LegacyWindow main = new LegacyWindow("#1804");
+ setMainWindow(main);
+
+ com.vaadin.ui.Select s;
+
+ s = new Select("Select with null selection allowed; required=true");
+ s.setNullSelectionAllowed(true);
+ s.setRequired(true);
+ listOfAllFields.add(s);
+
+ s = new Select("Select with null selection NOT allowed; required=true");
+ s.setNullSelectionAllowed(false);
+ s.setRequired(true);
+ listOfAllFields.add(s);
+
+ s = new Select("Testcase from the ticket #1804");
+ s.setNullSelectionAllowed(false);
+ s.setPropertyDataSource(new MethodProperty<String>(new TestPojo(), "id"));
+ s.addValidator(new EmptyStringValidator(
+ "Selection required for test-field"));
+ s.setRequired(true);
+ listOfAllFields.add(s);
+
+ s = new Select("Testcase from the ticket #1804, but without validator");
+ s.setNullSelectionAllowed(false);
+ s.setPropertyDataSource(new MethodProperty<String>(new TestPojo(), "id"));
+ s.setRequired(true);
+ listOfAllFields.add(s);
+
+ s = new Select(
+ "Testcase from the ticket #1804, but with required=false");
+ s.setNullSelectionAllowed(false);
+ s.setPropertyDataSource(new MethodProperty<String>(new TestPojo(), "id"));
+ s.addValidator(new EmptyStringValidator(
+ "Selection required for test-field"));
+ listOfAllFields.add(s);
+
+ s = new Select(
+ "Testcase from the ticket #1804, but without validator and with required=false");
+ s.setNullSelectionAllowed(false);
+ s.setPropertyDataSource(new MethodProperty<String>(new TestPojo(), "id"));
+ listOfAllFields.add(s);
+
+ s = new Select(
+ "Required=true, custom error message, null selection not allowed");
+ s.setRequired(true);
+ s.setNullSelectionAllowed(false);
+ s.setPropertyDataSource(new MethodProperty<String>(new TestPojo(), "id"));
+ s.setValue(null);
+ s.setComponentError(new SystemError("Test error message"));
+ listOfAllFields.add(s);
+
+ for (Iterator<Select> i = listOfAllFields.iterator(); i.hasNext();) {
+ s = i.next();
+ main.addComponent(s);
+ s.addItem("foo");
+ s.addItem("");
+ s.addItem("bar");
+ if (s.isNullSelectionAllowed()) {
+ s.addItem("<null>");
+ s.setNullSelectionItemId("<null>");
+ }
+ s.setImmediate(true);
+ }
+
+ Button checkValidity = new Button("Check validity of the fields");
+ main.addComponent(checkValidity);
+ checkValidity.addListener(new Button.ClickListener() {
+
+ public void buttonClick(ClickEvent event) {
+ StringBuffer msg = new StringBuffer();
+ for (Iterator<Select> i = listOfAllFields.iterator(); i
+ .hasNext();) {
- AbstractField af = i.next();
++ AbstractField<?> af = i.next();
+ msg.append("<h1>" + af.getCaption() + "</h1>\n");
+ msg.append("Value=" + af.getValue() + "<br/>\n");
+ if (af.isValid()) {
+ msg.append("VALID\n<hr/>");
+ } else {
+ msg.append("INVALID<br/><i>" + af.getErrorMessage()
+ + "</i><hr/>");
+ }
+ }
+ Window w = new Window("Status of the fields");
+ w.setModal(true);
+ w.setScrollable(true);
+ w.setHeight("80%");
- w.addComponent(new Label(msg.toString(), Label.CONTENT_XHTML));
++ w.addComponent(new Label(msg.toString(), ContentMode.XHTML));
+ main.addWindow(w);
+ }
+ });
+ }
+
+ public class TestPojo {
+ String id = "";
+
+ public String getId() {
+ return id;
+ }
+
+ public void setId(String id) {
+ this.id = id;
+ }
+
+ }
+
+ /** Throws an exception when the string is empty or null. */
- class EmptyStringValidator implements Validator {
++ static class EmptyStringValidator implements Validator {
+
+ String msg;
+
+ EmptyStringValidator(String msg) {
+ this.msg = msg;
+ }
+
- public boolean isValid(Object value) {
- return !(value == null || value.toString().length() == 0);
- }
-
+ public void validate(Object value) throws InvalidValueException {
- if (!isValid(value)) {
++ if (value == null || value.toString().length() == 0) {
+ throw new InvalidValueException(msg);
+ }
+ }
+
+ }
+
+ }
- package com.vaadin.tests.tickets;\r
- \r
- import com.vaadin.data.Property.ValueChangeEvent;\r
- import com.vaadin.data.Property.ValueChangeListener;\r
- import com.vaadin.ui.Alignment;\r
- import com.vaadin.ui.Button;\r
- import com.vaadin.ui.GridLayout;\r
- import com.vaadin.ui.Label;\r
- import com.vaadin.ui.Layout;\r
- import com.vaadin.ui.Root.LegacyWindow;\r
- import com.vaadin.ui.TextField;\r
- \r
- public class Ticket1805 extends com.vaadin.Application.LegacyApplication {\r
- \r
- @Override\r
- public void init() {\r
- final LegacyWindow main = new LegacyWindow(getClass().getName()\r
- .substring(getClass().getName().lastIndexOf(".") + 1));\r
- setMainWindow(main);\r
- ((Layout) main.getContent()).setMargin(false);\r
- \r
- Label description = new Label(\r
- "GridLayout with 100% (no height), is wanted to "\r
- + "share all available width with columns "\r
- + "relatively to their natural width. And it "\r
- + "should still work with margins and spacings");\r
- main.addComponent(description);\r
- \r
- final GridLayout grid = new GridLayout(4, 1);\r
- \r
- final TextField size = new TextField("Grid width in css unit");\r
- size.addListener(new ValueChangeListener() {\r
- public void valueChange(ValueChangeEvent event) {\r
- String width = size.getValue().toString();\r
- if (width == null || width.equals("")) {\r
- grid.setSizeUndefined();\r
- } else {\r
- grid.setWidth(width);\r
- }\r
- }\r
- });\r
- main.addComponent(size);\r
- main.addComponent(new Button("set size"));\r
- \r
- grid.setMargin(true);\r
- grid.setSpacing(true);\r
- \r
- grid.addComponent(new Label("WIDE"));\r
- grid.addComponent(new Label("_I_"));\r
- grid.addComponent(new Label("VEEEEEEEEEEERY_WIDE"));\r
- Label label = new Label("|");\r
- grid.addComponent(label);\r
- grid.setComponentAlignment(label, Alignment.TOP_RIGHT);\r
- main.addComponent(grid);\r
- }\r
- \r
- }\r
+ package com.vaadin.tests.tickets;
+
+ import com.vaadin.data.Property.ValueChangeEvent;
+ import com.vaadin.data.Property.ValueChangeListener;
+ import com.vaadin.ui.Alignment;
+ import com.vaadin.ui.Button;
+ import com.vaadin.ui.GridLayout;
+ import com.vaadin.ui.Label;
+ import com.vaadin.ui.Layout;
++import com.vaadin.ui.Root.LegacyWindow;
+ import com.vaadin.ui.TextField;
-import com.vaadin.ui.Window;
+
-public class Ticket1805 extends com.vaadin.Application {
++public class Ticket1805 extends com.vaadin.Application.LegacyApplication {
+
+ @Override
+ public void init() {
- final Window main = new Window(getClass().getName().substring(
- getClass().getName().lastIndexOf(".") + 1));
++ final LegacyWindow main = new LegacyWindow(getClass().getName()
++ .substring(getClass().getName().lastIndexOf(".") + 1));
+ setMainWindow(main);
+ ((Layout) main.getContent()).setMargin(false);
+
+ Label description = new Label(
+ "GridLayout with 100% (no height), is wanted to "
+ + "share all available width with columns "
+ + "relatively to their natural width. And it "
+ + "should still work with margins and spacings");
+ main.addComponent(description);
+
+ final GridLayout grid = new GridLayout(4, 1);
+
+ final TextField size = new TextField("Grid width in css unit");
+ size.addListener(new ValueChangeListener() {
+ public void valueChange(ValueChangeEvent event) {
+ String width = size.getValue().toString();
+ if (width == null || width.equals("")) {
+ grid.setSizeUndefined();
+ } else {
+ grid.setWidth(width);
+ }
+ }
+ });
+ main.addComponent(size);
+ main.addComponent(new Button("set size"));
+
+ grid.setMargin(true);
+ grid.setSpacing(true);
+
+ grid.addComponent(new Label("WIDE"));
+ grid.addComponent(new Label("_I_"));
+ grid.addComponent(new Label("VEEEEEEEEEEERY_WIDE"));
+ Label label = new Label("|");
+ grid.addComponent(label);
+ grid.setComponentAlignment(label, Alignment.TOP_RIGHT);
+ main.addComponent(grid);
+ }
+
+ }
- package com.vaadin.tests.tickets;\r
- \r
- import com.vaadin.data.util.ObjectProperty;\r
- import com.vaadin.ui.Button;\r
- import com.vaadin.ui.Button.ClickEvent;\r
- import com.vaadin.ui.Root.LegacyWindow;\r
- import com.vaadin.ui.TextField;\r
- \r
- public class Ticket1806 extends com.vaadin.Application.LegacyApplication {\r
- \r
- @Override\r
- public void init() {\r
- final LegacyWindow main = new LegacyWindow(getClass().getName()\r
- .substring(getClass().getName().lastIndexOf(".") + 1));\r
- setMainWindow(main);\r
- \r
- final ObjectProperty<String> prop = new ObjectProperty<String>("");\r
- final TextField tf1 = new TextField(\r
- "Buffered TextField bound to ObjectProperty");\r
- tf1.setWriteThrough(false);\r
- tf1.setReadThrough(false);\r
- tf1.setPropertyDataSource(prop);\r
- main.addComponent(tf1);\r
- main.addComponent(new Button(\r
- "This button does nothing (but flushes queued variable changes)"));\r
- main.addComponent(new Button("Commit the field to property",\r
- new Button.ClickListener() {\r
- public void buttonClick(ClickEvent event) {\r
- tf1.commit();\r
- }\r
- }));\r
- main.addComponent(new Button("Show property value",\r
- new Button.ClickListener() {\r
- public void buttonClick(ClickEvent event) {\r
- main.showNotification("'" + prop.getValue() + "'");\r
- }\r
- }));\r
- main.addComponent(new Button("Show field value",\r
- new Button.ClickListener() {\r
- public void buttonClick(ClickEvent event) {\r
- main.showNotification("'" + tf1.getValue() + "'");\r
- }\r
- }));\r
- }\r
+ package com.vaadin.tests.tickets;
+
+ import com.vaadin.data.util.ObjectProperty;
+ import com.vaadin.ui.Button;
+ import com.vaadin.ui.Button.ClickEvent;
++import com.vaadin.ui.Root.LegacyWindow;
+ import com.vaadin.ui.TextField;
-import com.vaadin.ui.Window;
+
-public class Ticket1806 extends com.vaadin.Application {
++public class Ticket1806 extends com.vaadin.Application.LegacyApplication {
+
+ @Override
+ public void init() {
- final Window main = new Window(getClass().getName().substring(
- getClass().getName().lastIndexOf(".") + 1));
++ final LegacyWindow main = new LegacyWindow(getClass().getName()
++ .substring(getClass().getName().lastIndexOf(".") + 1));
+ setMainWindow(main);
+
+ final ObjectProperty<String> prop = new ObjectProperty<String>("");
+ final TextField tf1 = new TextField(
+ "Buffered TextField bound to ObjectProperty");
+ tf1.setWriteThrough(false);
+ tf1.setReadThrough(false);
+ tf1.setPropertyDataSource(prop);
+ main.addComponent(tf1);
+ main.addComponent(new Button(
+ "This button does nothing (but flushes queued variable changes)"));
+ main.addComponent(new Button("Commit the field to property",
+ new Button.ClickListener() {
+ public void buttonClick(ClickEvent event) {
+ tf1.commit();
+ }
+ }));
+ main.addComponent(new Button("Show property value",
+ new Button.ClickListener() {
+ public void buttonClick(ClickEvent event) {
+ main.showNotification("'" + prop.getValue() + "'");
+ }
+ }));
+ main.addComponent(new Button("Show field value",
+ new Button.ClickListener() {
+ public void buttonClick(ClickEvent event) {
+ main.showNotification("'" + tf1.getValue() + "'");
+ }
+ }));
+ }
}
- package com.vaadin.tests.tickets;\r
- \r
- import java.util.Iterator;\r
- import java.util.LinkedList;\r
- \r
- import com.vaadin.data.Validator;\r
- import com.vaadin.data.validator.StringLengthValidator;\r
- import com.vaadin.ui.Button;\r
- import com.vaadin.ui.Button.ClickEvent;\r
- import com.vaadin.ui.Label;\r
- import com.vaadin.ui.Label.ContentMode;\r
- import com.vaadin.ui.Root.LegacyWindow;\r
- import com.vaadin.ui.TextField;\r
- import com.vaadin.ui.Window;\r
- \r
- public class Ticket1811 extends com.vaadin.Application.LegacyApplication {\r
- \r
- LinkedList<TextField> listOfAllFields = new LinkedList<TextField>();\r
- \r
- @Override\r
- public void init() {\r
- \r
- final LegacyWindow main = new LegacyWindow("#1811");\r
- setMainWindow(main);\r
- \r
- Validator strLenValidator = new StringLengthValidator(\r
- "String must be at least 3 chars long and non-null", 3, -1,\r
- false);\r
- \r
- TextField tf1 = new TextField(\r
- "Text field with default settings (required=false)");\r
- listOfAllFields.add(tf1);\r
- \r
- TextField tf2 = new TextField("Text field with required=true");\r
- tf2.setRequired(true);\r
- listOfAllFields.add(tf2);\r
- \r
- TextField tf3 = new TextField(\r
- "Text field with required=true and strlen >= 3");\r
- tf3.setRequired(true);\r
- tf3.addValidator(strLenValidator);\r
- listOfAllFields.add(tf3);\r
- \r
- TextField tf4 = new TextField(\r
- "Text field with required=false (default) and strlen >= 3");\r
- tf4.addValidator(strLenValidator);\r
- listOfAllFields.add(tf4);\r
- \r
- for (Iterator<TextField> i = listOfAllFields.iterator(); i.hasNext();) {\r
- TextField tf = i.next();\r
- main.addComponent(tf);\r
- tf.setImmediate(true);\r
- }\r
- \r
- Button checkValidity = new Button("Check validity of the fields");\r
- main.addComponent(checkValidity);\r
- checkValidity.addListener(new Button.ClickListener() {\r
- \r
- public void buttonClick(ClickEvent event) {\r
- StringBuffer msg = new StringBuffer();\r
- for (Iterator<TextField> i = listOfAllFields.iterator(); i\r
- .hasNext();) {\r
- TextField tf = i.next();\r
- msg.append("<h1>" + tf.getCaption() + "</h1>\n");\r
- if (tf.isValid()) {\r
- msg.append("VALID\n<hr/>");\r
- } else {\r
- msg.append("INVALID<br/><i>" + tf.getErrorMessage()\r
- + "</i><hr/>");\r
- }\r
- }\r
- Window w = new Window("Status of the fields");\r
- w.setModal(true);\r
- w.addComponent(new Label(msg.toString(), ContentMode.XHTML));\r
- main.addWindow(w);\r
- }\r
- });\r
- }\r
- \r
- }\r
+ package com.vaadin.tests.tickets;
+
+ import java.util.Iterator;
+ import java.util.LinkedList;
+
+ import com.vaadin.data.Validator;
+ import com.vaadin.data.validator.StringLengthValidator;
+ import com.vaadin.ui.Button;
+ import com.vaadin.ui.Button.ClickEvent;
+ import com.vaadin.ui.Label;
++import com.vaadin.ui.Label.ContentMode;
++import com.vaadin.ui.Root.LegacyWindow;
+ import com.vaadin.ui.TextField;
+ import com.vaadin.ui.Window;
+
-public class Ticket1811 extends com.vaadin.Application {
++public class Ticket1811 extends com.vaadin.Application.LegacyApplication {
+
+ LinkedList<TextField> listOfAllFields = new LinkedList<TextField>();
+
+ @Override
+ public void init() {
+
- final Window main = new Window("#1811");
++ final LegacyWindow main = new LegacyWindow("#1811");
+ setMainWindow(main);
+
+ Validator strLenValidator = new StringLengthValidator(
+ "String must be at least 3 chars long and non-null", 3, -1,
+ false);
+
+ TextField tf1 = new TextField(
+ "Text field with default settings (required=false)");
+ listOfAllFields.add(tf1);
+
+ TextField tf2 = new TextField("Text field with required=true");
+ tf2.setRequired(true);
+ listOfAllFields.add(tf2);
+
+ TextField tf3 = new TextField(
+ "Text field with required=true and strlen >= 3");
+ tf3.setRequired(true);
+ tf3.addValidator(strLenValidator);
+ listOfAllFields.add(tf3);
+
+ TextField tf4 = new TextField(
+ "Text field with required=false (default) and strlen >= 3");
+ tf4.addValidator(strLenValidator);
+ listOfAllFields.add(tf4);
+
+ for (Iterator<TextField> i = listOfAllFields.iterator(); i.hasNext();) {
+ TextField tf = i.next();
+ main.addComponent(tf);
+ tf.setImmediate(true);
+ }
+
+ Button checkValidity = new Button("Check validity of the fields");
+ main.addComponent(checkValidity);
+ checkValidity.addListener(new Button.ClickListener() {
+
+ public void buttonClick(ClickEvent event) {
+ StringBuffer msg = new StringBuffer();
+ for (Iterator<TextField> i = listOfAllFields.iterator(); i
+ .hasNext();) {
+ TextField tf = i.next();
+ msg.append("<h1>" + tf.getCaption() + "</h1>\n");
+ if (tf.isValid()) {
+ msg.append("VALID\n<hr/>");
+ } else {
+ msg.append("INVALID<br/><i>" + tf.getErrorMessage()
+ + "</i><hr/>");
+ }
+ }
+ Window w = new Window("Status of the fields");
+ w.setModal(true);
- w.addComponent(new Label(msg.toString(), Label.CONTENT_XHTML));
++ w.addComponent(new Label(msg.toString(), ContentMode.XHTML));
+ main.addWindow(w);
+ }
+ });
+ }
+
+ }
- package com.vaadin.tests.tickets;\r
- \r
- import java.util.Iterator;\r
- import java.util.LinkedList;\r
- \r
- import com.vaadin.ui.AbstractField;\r
- import com.vaadin.ui.Button;\r
- import com.vaadin.ui.Button.ClickEvent;\r
- import com.vaadin.ui.Label;\r
- import com.vaadin.ui.Label.ContentMode;\r
- import com.vaadin.ui.Root.LegacyWindow;\r
- import com.vaadin.ui.Select;\r
- import com.vaadin.ui.Window;\r
- \r
- public class Ticket1819 extends com.vaadin.Application.LegacyApplication {\r
- \r
- LinkedList<Select> listOfAllFields = new LinkedList<Select>();\r
- \r
- @Override\r
- public void init() {\r
- \r
- final LegacyWindow main = new LegacyWindow("#1819");\r
- setMainWindow(main);\r
- \r
- com.vaadin.ui.Select s;\r
- \r
- s = new Select("Select with null selection allowed");\r
- s.setNullSelectionAllowed(true);\r
- listOfAllFields.add(s);\r
- \r
- s = new Select("Select with null selection NOT allowed");\r
- s.setNullSelectionAllowed(false);\r
- listOfAllFields.add(s);\r
- \r
- for (Iterator<Select> i = listOfAllFields.iterator(); i.hasNext();) {\r
- s = i.next();\r
- main.addComponent(s);\r
- s.addItem("-null-");\r
- s.addItem("");\r
- s.addItem("foo");\r
- s.addItem("bar");\r
- s.setNullSelectionItemId("-null-");\r
- s.setImmediate(true);\r
- }\r
- \r
- Button checkValidity = new Button("Check validity of the fields");\r
- main.addComponent(checkValidity);\r
- checkValidity.addListener(new Button.ClickListener() {\r
- \r
- public void buttonClick(ClickEvent event) {\r
- StringBuffer msg = new StringBuffer();\r
- for (Iterator<Select> i = listOfAllFields.iterator(); i\r
- .hasNext();) {\r
- AbstractField<?> af = i.next();\r
- msg.append("<h1>" + af.getCaption() + "</h1>\n");\r
- msg.append("Value=" + af.getValue() + "<br/>\n");\r
- }\r
- Window w = new Window("Status of the fields");\r
- w.setModal(true);\r
- w.addComponent(new Label(msg.toString(), ContentMode.XHTML));\r
- main.addWindow(w);\r
- }\r
- });\r
- }\r
- \r
- }\r
+ package com.vaadin.tests.tickets;
+
+ import java.util.Iterator;
+ import java.util.LinkedList;
+
+ import com.vaadin.ui.AbstractField;
+ import com.vaadin.ui.Button;
+ import com.vaadin.ui.Button.ClickEvent;
+ import com.vaadin.ui.Label;
++import com.vaadin.ui.Label.ContentMode;
++import com.vaadin.ui.Root.LegacyWindow;
+ import com.vaadin.ui.Select;
+ import com.vaadin.ui.Window;
+
-public class Ticket1819 extends com.vaadin.Application {
++public class Ticket1819 extends com.vaadin.Application.LegacyApplication {
+
+ LinkedList<Select> listOfAllFields = new LinkedList<Select>();
+
+ @Override
+ public void init() {
+
- final Window main = new Window("#1819");
++ final LegacyWindow main = new LegacyWindow("#1819");
+ setMainWindow(main);
+
+ com.vaadin.ui.Select s;
+
+ s = new Select("Select with null selection allowed");
+ s.setNullSelectionAllowed(true);
+ listOfAllFields.add(s);
+
+ s = new Select("Select with null selection NOT allowed");
+ s.setNullSelectionAllowed(false);
+ listOfAllFields.add(s);
+
+ for (Iterator<Select> i = listOfAllFields.iterator(); i.hasNext();) {
+ s = i.next();
+ main.addComponent(s);
+ s.addItem("-null-");
+ s.addItem("");
+ s.addItem("foo");
+ s.addItem("bar");
+ s.setNullSelectionItemId("-null-");
+ s.setImmediate(true);
+ }
+
+ Button checkValidity = new Button("Check validity of the fields");
+ main.addComponent(checkValidity);
+ checkValidity.addListener(new Button.ClickListener() {
+
+ public void buttonClick(ClickEvent event) {
+ StringBuffer msg = new StringBuffer();
+ for (Iterator<Select> i = listOfAllFields.iterator(); i
+ .hasNext();) {
- AbstractField af = i.next();
++ AbstractField<?> af = i.next();
+ msg.append("<h1>" + af.getCaption() + "</h1>\n");
+ msg.append("Value=" + af.getValue() + "<br/>\n");
+ }
+ Window w = new Window("Status of the fields");
+ w.setModal(true);
- w.addComponent(new Label(msg.toString(), Label.CONTENT_XHTML));
++ w.addComponent(new Label(msg.toString(), ContentMode.XHTML));
+ main.addWindow(w);
+ }
+ });
+ }
+
+ }
- package com.vaadin.tests.tickets;\r
- \r
- import com.vaadin.ui.Button;\r
- import com.vaadin.ui.Button.ClickEvent;\r
- import com.vaadin.ui.Button.ClickListener;\r
- import com.vaadin.ui.HorizontalLayout;\r
- import com.vaadin.ui.Label;\r
- import com.vaadin.ui.Panel;\r
- import com.vaadin.ui.Root.LegacyWindow;\r
- \r
- public class Ticket1834PanelScrolling extends\r
- com.vaadin.Application.LegacyApplication {\r
- \r
- private static final int ROWS = 50;\r
- \r
- private Label state = new Label("State");\r
- \r
- private Panel p;\r
- \r
- @Override\r
- public void init() {\r
- final LegacyWindow main = new LegacyWindow(getClass().getName()\r
- .substring(getClass().getName().lastIndexOf(".") + 1));\r
- setMainWindow(main);\r
- \r
- HorizontalLayout currentState = new HorizontalLayout();\r
- \r
- currentState.addComponent(state);\r
- Button b = new Button("update");\r
- currentState.addComponent(b);\r
- b.addListener(new ClickListener() {\r
- public void buttonClick(ClickEvent event) {\r
- state.setValue("ScrollTop: " + p.getScrollTop()\r
- + " ScrollLeft: " + p.getScrollLeft());\r
- }\r
- });\r
- main.addComponent(currentState);\r
- \r
- b = new Button("ScrollBy 50px");\r
- b.addListener(new ClickListener() {\r
- public void buttonClick(ClickEvent event) {\r
- p.setScrollLeft(p.getScrollLeft() + 50);\r
- p.setScrollTop(p.getScrollTop() + 50);\r
- state.setValue("ScrollTop: " + p.getScrollTop()\r
- + " ScrollLeft: " + p.getScrollLeft());\r
- }\r
- });\r
- \r
- main.addComponent(b);\r
- \r
- b = new Button("Add row");\r
- b.addListener(new ClickListener() {\r
- int i = 0;\r
- \r
- public void buttonClick(ClickEvent event) {\r
- p.addComponent(new Label("new Row" + ++i));\r
- }\r
- });\r
- \r
- main.addComponent(b);\r
- \r
- b = new Button("Repaint Panel");\r
- b.addListener(new ClickListener() {\r
- public void buttonClick(ClickEvent event) {\r
- p.requestRepaint();\r
- }\r
- });\r
- \r
- main.addComponent(b);\r
- \r
- p = new Panel("TestPanel");\r
- p.setScrollable(true);\r
- \r
- for (int i = 0; i < ROWS; i++) {\r
- p.addComponent(new Label(\r
- "Label"\r
- + i\r
- + "................................................................................................................."));\r
- }\r
- \r
- p.setHeight("300px");\r
- p.setWidth("250px");\r
- \r
- p.setScrollTop(100);\r
- p.setScrollLeft(100);\r
- \r
- main.addComponent(p);\r
- \r
- }\r
+ package com.vaadin.tests.tickets;
+
+ import com.vaadin.ui.Button;
+ import com.vaadin.ui.Button.ClickEvent;
+ import com.vaadin.ui.Button.ClickListener;
+ import com.vaadin.ui.HorizontalLayout;
+ import com.vaadin.ui.Label;
+ import com.vaadin.ui.Panel;
-import com.vaadin.ui.Window;
++import com.vaadin.ui.Root.LegacyWindow;
+
-public class Ticket1834PanelScrolling extends com.vaadin.Application {
++public class Ticket1834PanelScrolling extends
++ com.vaadin.Application.LegacyApplication {
+
+ private static final int ROWS = 50;
+
+ private Label state = new Label("State");
+
+ private Panel p;
+
+ @Override
+ public void init() {
- final Window main = new Window(getClass().getName().substring(
- getClass().getName().lastIndexOf(".") + 1));
++ final LegacyWindow main = new LegacyWindow(getClass().getName()
++ .substring(getClass().getName().lastIndexOf(".") + 1));
+ setMainWindow(main);
+
+ HorizontalLayout currentState = new HorizontalLayout();
+
+ currentState.addComponent(state);
+ Button b = new Button("update");
+ currentState.addComponent(b);
+ b.addListener(new ClickListener() {
+ public void buttonClick(ClickEvent event) {
+ state.setValue("ScrollTop: " + p.getScrollTop()
+ + " ScrollLeft: " + p.getScrollLeft());
+ }
+ });
+ main.addComponent(currentState);
+
+ b = new Button("ScrollBy 50px");
+ b.addListener(new ClickListener() {
+ public void buttonClick(ClickEvent event) {
+ p.setScrollLeft(p.getScrollLeft() + 50);
+ p.setScrollTop(p.getScrollTop() + 50);
+ state.setValue("ScrollTop: " + p.getScrollTop()
+ + " ScrollLeft: " + p.getScrollLeft());
+ }
+ });
+
+ main.addComponent(b);
+
+ b = new Button("Add row");
+ b.addListener(new ClickListener() {
+ int i = 0;
+
+ public void buttonClick(ClickEvent event) {
+ p.addComponent(new Label("new Row" + ++i));
+ }
+ });
+
+ main.addComponent(b);
+
+ b = new Button("Repaint Panel");
+ b.addListener(new ClickListener() {
+ public void buttonClick(ClickEvent event) {
+ p.requestRepaint();
+ }
+ });
+
+ main.addComponent(b);
+
+ p = new Panel("TestPanel");
+ p.setScrollable(true);
+
+ for (int i = 0; i < ROWS; i++) {
+ p.addComponent(new Label(
+ "Label"
+ + i
+ + "................................................................................................................."));
+ }
+
+ p.setHeight("300px");
+ p.setWidth("250px");
+
+ p.setScrollTop(100);
+ p.setScrollLeft(100);
+
+ main.addComponent(p);
+
+ }
}
- package com.vaadin.tests.tickets;\r
- \r
- import com.vaadin.ui.Panel;\r
- import com.vaadin.ui.Root.LegacyWindow;\r
- \r
- public class Ticket1868 extends com.vaadin.Application.LegacyApplication {\r
- \r
- @Override\r
- public void init() {\r
- \r
- setMainWindow(new LegacyWindow("#1868"));\r
- \r
- Panel p = new Panel(\r
- "This is a really long caption for the panel, too long in fact!");\r
- p.setWidth("300px");\r
- p.setHeight("300px");\r
- \r
- getMainWindow().addComponent(p);\r
- }\r
+ package com.vaadin.tests.tickets;
+
+ import com.vaadin.ui.Panel;
-import com.vaadin.ui.Window;
++import com.vaadin.ui.Root.LegacyWindow;
+
-public class Ticket1868 extends com.vaadin.Application {
++public class Ticket1868 extends com.vaadin.Application.LegacyApplication {
+
+ @Override
+ public void init() {
+
- setMainWindow(new Window("#1868"));
++ setMainWindow(new LegacyWindow("#1868"));
+
+ Panel p = new Panel(
+ "This is a really long caption for the panel, too long in fact!");
+ p.setWidth("300px");
+ p.setHeight("300px");
+
+ getMainWindow().addComponent(p);
+ }
}
- package com.vaadin.tests.tickets;\r
- \r
- import com.vaadin.ui.Button;\r
- import com.vaadin.ui.GridLayout;\r
- import com.vaadin.ui.HorizontalLayout;\r
- import com.vaadin.ui.Panel;\r
- import com.vaadin.ui.Root.LegacyWindow;\r
- import com.vaadin.ui.VerticalLayout;\r
- \r
- public class Ticket1869 extends com.vaadin.Application.LegacyApplication {\r
- \r
- @Override\r
- public void init() {\r
- \r
- GridLayout lo = new GridLayout(2, 1);\r
- setMainWindow(new LegacyWindow("#1869", lo));\r
- lo.setMargin(true);\r
- lo.setSpacing(true);\r
- \r
- VerticalLayout el = new VerticalLayout();\r
- Panel elp = new Panel(\r
- "Vertical ExpandLayout /w first component expanded", el);\r
- el.setHeight("1000px");\r
- for (int i = 0; i < 3; i++) {\r
- Button b = new Button("x");\r
- el.addComponent(b);\r
- if (i == 0) {\r
- b.setSizeFull();\r
- el.setExpandRatio(b, 1);\r
- }\r
- }\r
- lo.addComponent(elp);\r
- elp.setWidth("300px");\r
- elp.setHeight("300px");\r
- elp.setScrollable(true);\r
- \r
- HorizontalLayout elh = new HorizontalLayout();\r
- Panel elph = new Panel(\r
- "Horizontal ExpandLayout /w first component expanded", elh);\r
- elh.setWidth("1000px");\r
- for (int i = 0; i < 3; i++) {\r
- Button b = new Button("x");\r
- elh.addComponent(b);\r
- if (i == 0) {\r
- b.setSizeFull();\r
- elh.setExpandRatio(b, 1);\r
- }\r
- }\r
- lo.addComponent(elph);\r
- elph.setWidth("300px");\r
- elph.setHeight("300px");\r
- elph.setScrollable(true);\r
- \r
- }\r
- }\r
+ package com.vaadin.tests.tickets;
+
+ import com.vaadin.ui.Button;
+ import com.vaadin.ui.GridLayout;
+ import com.vaadin.ui.HorizontalLayout;
+ import com.vaadin.ui.Panel;
++import com.vaadin.ui.Root.LegacyWindow;
+ import com.vaadin.ui.VerticalLayout;
-import com.vaadin.ui.Window;
+
-public class Ticket1869 extends com.vaadin.Application {
++public class Ticket1869 extends com.vaadin.Application.LegacyApplication {
+
+ @Override
+ public void init() {
+
+ GridLayout lo = new GridLayout(2, 1);
- setMainWindow(new Window("#1869", lo));
++ setMainWindow(new LegacyWindow("#1869", lo));
+ lo.setMargin(true);
+ lo.setSpacing(true);
+
+ VerticalLayout el = new VerticalLayout();
+ Panel elp = new Panel(
+ "Vertical ExpandLayout /w first component expanded", el);
+ el.setHeight("1000px");
+ for (int i = 0; i < 3; i++) {
+ Button b = new Button("x");
+ el.addComponent(b);
+ if (i == 0) {
+ b.setSizeFull();
+ el.setExpandRatio(b, 1);
+ }
+ }
+ lo.addComponent(elp);
+ elp.setWidth("300px");
+ elp.setHeight("300px");
+ elp.setScrollable(true);
+
+ HorizontalLayout elh = new HorizontalLayout();
+ Panel elph = new Panel(
+ "Horizontal ExpandLayout /w first component expanded", elh);
+ elh.setWidth("1000px");
+ for (int i = 0; i < 3; i++) {
+ Button b = new Button("x");
+ elh.addComponent(b);
+ if (i == 0) {
+ b.setSizeFull();
+ elh.setExpandRatio(b, 1);
+ }
+ }
+ lo.addComponent(elph);
+ elph.setWidth("300px");
+ elph.setHeight("300px");
+ elph.setScrollable(true);
+
+ }
+ }
- package com.vaadin.tests.tickets;\r
- \r
- import java.util.Date;\r
- import java.util.Iterator;\r
- import java.util.Random;\r
- \r
- import com.vaadin.Application;\r
- import com.vaadin.data.util.BeanItem;\r
- import com.vaadin.data.validator.StringLengthValidator;\r
- import com.vaadin.terminal.Resource;\r
- import com.vaadin.terminal.ThemeResource;\r
- import com.vaadin.terminal.UserError;\r
- import com.vaadin.ui.Alignment;\r
- import com.vaadin.ui.Button;\r
- import com.vaadin.ui.Button.ClickEvent;\r
- import com.vaadin.ui.Button.ClickListener;\r
- import com.vaadin.ui.Component;\r
- import com.vaadin.ui.Field;\r
- import com.vaadin.ui.Form;\r
- import com.vaadin.ui.FormLayout;\r
- import com.vaadin.ui.GridLayout;\r
- import com.vaadin.ui.HorizontalLayout;\r
- import com.vaadin.ui.Layout;\r
- import com.vaadin.ui.Layout.AlignmentHandler;\r
- import com.vaadin.ui.Panel;\r
- import com.vaadin.ui.Root.LegacyWindow;\r
- import com.vaadin.ui.TextField;\r
- import com.vaadin.ui.VerticalLayout;\r
- \r
- public class Ticket1878 extends Application.LegacyApplication {\r
- \r
- private Layout orderedLayout;\r
- private Layout gridLayout;\r
- private Layout formLayout;\r
- private GridLayout mainLayout;\r
- private Button switchToGridButton;\r
- private Button switchToOrderedButton;\r
- private Button switchToFormsButton;\r
- \r
- @Override\r
- public void init() {\r
- LegacyWindow w = new LegacyWindow(getClass().getSimpleName());\r
- setMainWindow(w);\r
- // setTheme("tests-tickets");\r
- \r
- mainLayout = new GridLayout(1, 2);\r
- w.setContent(mainLayout);\r
- orderedLayout = createOL();\r
- gridLayout = createGL();\r
- formLayout = createForms();\r
- \r
- switchToGridButton = new Button("Switch to GridLayout",\r
- new ClickListener() {\r
- \r
- public void buttonClick(ClickEvent event) {\r
- changeLayout(switchToGridButton, gridLayout);\r
- }\r
- \r
- });\r
- switchToOrderedButton = new Button("Switch to OrderedLayout",\r
- new ClickListener() {\r
- \r
- public void buttonClick(ClickEvent event) {\r
- changeLayout(switchToOrderedButton, orderedLayout);\r
- }\r
- \r
- });\r
- switchToOrderedButton.setEnabled(false);\r
- \r
- switchToFormsButton = new Button("Switch to Form", new ClickListener() {\r
- \r
- public void buttonClick(ClickEvent event) {\r
- changeLayout(switchToFormsButton, formLayout);\r
- }\r
- \r
- });\r
- \r
- HorizontalLayout buttonLayout = new HorizontalLayout();\r
- buttonLayout.addComponent(switchToOrderedButton);\r
- buttonLayout.addComponent(switchToGridButton);\r
- buttonLayout.addComponent(switchToFormsButton);\r
- \r
- mainLayout.addComponent(buttonLayout);\r
- mainLayout.addComponent(orderedLayout);\r
- // w.setContent(orderedLayout);\r
- }\r
- \r
- private static Layout createOL() {\r
- GridLayout layout = new GridLayout(1, 5);\r
- \r
- GridLayout l1 = new GridLayout(1, 3);\r
- createLayout(l1, new HorizontalLayout(), "1000px", "150px", "100%",\r
- null, true);\r
- createLayout(l1, new HorizontalLayout(), "1000px", "150px", "50px",\r
- null, false);\r
- GridLayout l2 = new GridLayout(6, 1);\r
- createLayout(l2, new VerticalLayout(), "200px", "500px", true);\r
- createLayout(l2, new VerticalLayout(), "200px", "500px", "100%", null,\r
- true);\r
- createLayout(l2, new VerticalLayout(), "150px", "500px", true);\r
- createLayout(l2, new VerticalLayout(), "150px", "500px", "100%", null,\r
- true);\r
- createLayout(l2, new VerticalLayout(), "100px", "500px", true);\r
- createLayout(l2, new VerticalLayout(), "100px", "500px", "100%", null,\r
- true);\r
- layout.addComponent(l1);\r
- layout.addComponent(l2);\r
- \r
- return layout;\r
- }\r
- \r
- private static Layout createGL() {\r
- GridLayout layout = new GridLayout(1, 5);\r
- \r
- GridLayout l1 = new GridLayout(1, 3);\r
- createLayout(l1, new GridLayout(8, 1), "1000px", "150px", "100%", null,\r
- true);\r
- createLayout(l1, new GridLayout(8, 1), "1000px", "150px", "50px", null,\r
- false);\r
- GridLayout l2 = new GridLayout(6, 1);\r
- createLayout(l2, new GridLayout(1, 8), "200px", "500px", true);\r
- createLayout(l2, new GridLayout(1, 8), "200px", "500px", "100%", null,\r
- true);\r
- createLayout(l2, new GridLayout(1, 8), "150px", "500px", true);\r
- createLayout(l2, new GridLayout(1, 8), "150px", "500px", "100%", null,\r
- true);\r
- createLayout(l2, new GridLayout(1, 8), "100px", "500px", true);\r
- createLayout(l2, new GridLayout(1, 8), "100px", "500px", "100%", null,\r
- true);\r
- layout.addComponent(l1);\r
- layout.addComponent(l2);\r
- \r
- return layout;\r
- }\r
- \r
- public class FormObject {\r
- private String stringValue = "abc";\r
- private int intValue = 1;\r
- private long longValue = 2L;\r
- private Date dateValue = new Date(34587034750L);\r
- \r
- public String getStringValue() {\r
- return stringValue;\r
- }\r
- \r
- public void setStringValue(String stringValue) {\r
- this.stringValue = stringValue;\r
- }\r
- \r
- public int getIntValue() {\r
- return intValue;\r
- }\r
- \r
- public void setIntValue(int intValue) {\r
- this.intValue = intValue;\r
- }\r
- \r
- public long getLongValue() {\r
- return longValue;\r
- }\r
- \r
- public void setLongValue(long longValue) {\r
- this.longValue = longValue;\r
- }\r
- \r
- public Date getDateValue() {\r
- return dateValue;\r
- }\r
- \r
- public void setDateValue(Date dateValue) {\r
- this.dateValue = dateValue;\r
- }\r
- \r
- }\r
- \r
- private Layout createForms() {\r
- GridLayout layout = new GridLayout(1, 5);\r
- Form form;\r
- \r
- Random r = new Random();\r
- GridLayout l1 = new GridLayout(1, 3);\r
- form = createForm(l1, "200px", "500px");\r
- BeanItem<FormObject> item = new BeanItem<FormObject>(new FormObject());\r
- form.setItemDataSource(item);\r
- for (Iterator<?> i = item.getItemPropertyIds().iterator(); i.hasNext();) {\r
- Object property = i.next();\r
- Field<?> f = form.getField(property);\r
- \r
- f.setRequired(r.nextBoolean());\r
- if (r.nextBoolean()) {\r
- f.setIcon(new ThemeResource("icons/16/document-add.png"));\r
- }\r
- if (r.nextBoolean()) {\r
- f.setCaption(null);\r
- }\r
- \r
- f.addValidator(new StringLengthValidator("Error", 10, 8, false));\r
- }\r
- // createLayout(l1, new\r
- // ExpandLayout(ExpandLayout.ORIENTATION_HORIZONTAL),\r
- // "1000px", "150px", "50px", null, false);\r
- \r
- // GridLayout l2 = new GridLayout(6, 1);\r
- // createLayout(l2, new ExpandLayout(ExpandLayout.ORIENTATION_VERTICAL),\r
- // "200px", "500px", true);\r
- // createLayout(l2, new ExpandLayout(ExpandLayout.ORIENTATION_VERTICAL),\r
- // "200px", "500px", "100%", null, true);\r
- // createLayout(l2, new ExpandLayout(ExpandLayout.ORIENTATION_VERTICAL),\r
- // "150px", "500px", true);\r
- // createLayout(l2, new ExpandLayout(ExpandLayout.ORIENTATION_VERTICAL),\r
- // "150px", "500px", "100%", null, true);\r
- // createLayout(l2, new ExpandLayout(ExpandLayout.ORIENTATION_VERTICAL),\r
- // "100px", "500px", true);\r
- // createLayout(l2, new ExpandLayout(ExpandLayout.ORIENTATION_VERTICAL),\r
- // "100px", "500px", "100%", null, true);\r
- layout.addComponent(l1);\r
- // layout.addComponent(l2);\r
- \r
- return layout;\r
- }\r
- \r
- private Form createForm(GridLayout parentLayout, String w, String h) {\r
- FormLayout formLayout = new FormLayout();\r
- Form form = new Form(formLayout);\r
- \r
- Panel p = new Panel("Form " + w + "x" + h);\r
- \r
- p.setWidth(w);\r
- p.setHeight(h);\r
- \r
- p.getContent().setSizeFull();\r
- \r
- parentLayout.addComponent(p);\r
- p.addComponent(form);\r
- formLayout.setSizeFull();\r
- \r
- return form;\r
- }\r
- \r
- protected void changeLayout(Button b, Layout newLayout) {\r
- switchToOrderedButton.setEnabled(true);\r
- switchToGridButton.setEnabled(true);\r
- switchToFormsButton.setEnabled(true);\r
- \r
- b.setEnabled(false);\r
- Iterator<Component> i = mainLayout.getComponentIterator();\r
- i.next();\r
- Layout l = (Layout) i.next();\r
- \r
- mainLayout.replaceComponent(l, newLayout);\r
- }\r
- \r
- private static void createLayout(GridLayout parentLayout, Layout newLayout,\r
- String w, String h, boolean align) {\r
- createLayout(parentLayout, newLayout, w, h, null, null, align);\r
- }\r
- \r
- private static void createLayout(GridLayout parentLayout, Layout newLayout,\r
- String w, String h, String componentWidth, String componentHeight,\r
- boolean align) {\r
- String dirText = "V";\r
- String type;\r
- if (newLayout instanceof VerticalLayout) {\r
- type = "OL";\r
- } else if (newLayout instanceof HorizontalLayout) {\r
- dirText = "H";\r
- type = "OL";\r
- } else {\r
- if (((GridLayout) newLayout).getColumns() != 1) {\r
- dirText = "H";\r
- }\r
- type = "GL";\r
- }\r
- String alignText = align ? "-A" : "";\r
- String cWidth = componentWidth == null ? "" : " - " + componentWidth;\r
- Panel p = new Panel(type + "/" + dirText + alignText + " " + w + "x"\r
- + h + cWidth, newLayout);\r
- \r
- p.setWidth(w);\r
- p.setHeight(h);\r
- \r
- newLayout.setSizeFull();\r
- \r
- String captions[] = new String[] { "TextField with caption", null };\r
- Resource icons[] = new Resource[] {\r
- new ThemeResource("icons/16/document-delete.png"), null };\r
- boolean required[] = new boolean[] { true, false };\r
- TextField fields[][] = new TextField[captions.length][icons.length];\r
- for (int caption = 0; caption < captions.length; caption++) {\r
- for (int icon = 0; icon < icons.length; icon++) {\r
- for (int req = 0; req < required.length; req++) {\r
- TextField tf = createTextFieldWithError(captions[caption],\r
- icons[icon], required[req]);\r
- \r
- fields[caption][icon] = tf;\r
- if (componentWidth != null) {\r
- tf.setWidth(componentWidth);\r
- tf.setValue(tf.getValue() + " w:" + componentWidth);\r
- }\r
- \r
- if (componentHeight != null) {\r
- tf.setHeight(componentWidth);\r
- tf.setValue(tf.getValue() + " h:" + componentHeight);\r
- }\r
- \r
- p.addComponent(tf);\r
- \r
- if (align) {\r
- ((AlignmentHandler) newLayout).setComponentAlignment(\r
- tf, Alignment.BOTTOM_RIGHT);\r
- }\r
- }\r
- }\r
- }\r
- \r
- parentLayout.addComponent(p);\r
- \r
- }\r
- \r
- // private static void createGridLayout(GridLayout parentLayout, int dir,\r
- // String w, String h) {\r
- // createGridLayout(parentLayout, dir, w, h, null, null);\r
- // }\r
- \r
- // private static void createGridLayout(GridLayout parentLayout, int dir,\r
- // String w, String h, String componentWidth, String componentHeight) {\r
- // GridLayout gl;\r
- // if (dir == OrderedLayout.ORIENTATION_HORIZONTAL) {\r
- // gl = new GridLayout(8, 1);\r
- // } else {\r
- // gl = new GridLayout(1, 8);\r
- // }\r
- //\r
- // String dirText = (dir == OrderedLayout.ORIENTATION_HORIZONTAL ? "H"\r
- // : "V");\r
- // String cWidth = componentWidth == null ? "" : " - " + componentWidth;\r
- // Panel p = new Panel("GL/" + dirText + " " + w + "x" + h + cWidth, gl);\r
- //\r
- // p.setWidth(w);\r
- // p.setHeight(h);\r
- //\r
- // gl.setSizeFull();\r
- //\r
- // String captions[] = new String[] { "TextField with caption", null };\r
- // Resource icons[] = new Resource[] {\r
- // new ThemeResource("icons/16/document-delete.png"), null };\r
- // boolean required[] = new boolean[] { true, false };\r
- // TextField fields[][] = new TextField[captions.length][icons.length];\r
- // for (int caption = 0; caption < captions.length; caption++) {\r
- // for (int icon = 0; icon < icons.length; icon++) {\r
- // for (int req = 0; req < required.length; req++) {\r
- // TextField tf = createTextFieldWithError(captions[caption],\r
- // icons[icon], required[req]);\r
- //\r
- // fields[caption][icon] = tf;\r
- // if (componentWidth != null) {\r
- // tf.setWidth(componentWidth);\r
- // }\r
- //\r
- // if (componentHeight != null) {\r
- // tf.setHeight(componentWidth);\r
- // }\r
- //\r
- // p.addComponent(tf);\r
- // gl.setComponentAlignment(tf, OrderedLayout.ALIGNMENT_LEFT,\r
- // OrderedLayout.ALIGNMENT_BOTTOM);\r
- // }\r
- // }\r
- // }\r
- //\r
- // parentLayout.addComponent(p);\r
- //\r
- // }\r
- \r
- private static TextField createTextFieldWithError(String caption,\r
- Resource icon, boolean required) {\r
- TextField tf = new TextField();\r
- tf.setCaption(caption);\r
- tf.setIcon(icon);\r
- tf.setRequired(required);\r
- tf.setComponentError(new UserError("Test error message"));\r
- return tf;\r
- }\r
- }\r
+ package com.vaadin.tests.tickets;
+
+ import java.util.Date;
+ import java.util.Iterator;
+ import java.util.Random;
+
+ import com.vaadin.Application;
+ import com.vaadin.data.util.BeanItem;
+ import com.vaadin.data.validator.StringLengthValidator;
+ import com.vaadin.terminal.Resource;
+ import com.vaadin.terminal.ThemeResource;
+ import com.vaadin.terminal.UserError;
+ import com.vaadin.ui.Alignment;
+ import com.vaadin.ui.Button;
+ import com.vaadin.ui.Button.ClickEvent;
+ import com.vaadin.ui.Button.ClickListener;
+ import com.vaadin.ui.Component;
+ import com.vaadin.ui.Field;
+ import com.vaadin.ui.Form;
+ import com.vaadin.ui.FormLayout;
+ import com.vaadin.ui.GridLayout;
+ import com.vaadin.ui.HorizontalLayout;
+ import com.vaadin.ui.Layout;
+ import com.vaadin.ui.Layout.AlignmentHandler;
+ import com.vaadin.ui.Panel;
++import com.vaadin.ui.Root.LegacyWindow;
+ import com.vaadin.ui.TextField;
+ import com.vaadin.ui.VerticalLayout;
-import com.vaadin.ui.Window;
+
-public class Ticket1878 extends Application {
++public class Ticket1878 extends Application.LegacyApplication {
+
+ private Layout orderedLayout;
+ private Layout gridLayout;
+ private Layout formLayout;
+ private GridLayout mainLayout;
+ private Button switchToGridButton;
+ private Button switchToOrderedButton;
+ private Button switchToFormsButton;
+
+ @Override
+ public void init() {
- Window w = new Window(getClass().getSimpleName());
++ LegacyWindow w = new LegacyWindow(getClass().getSimpleName());
+ setMainWindow(w);
+ // setTheme("tests-tickets");
+
+ mainLayout = new GridLayout(1, 2);
+ w.setContent(mainLayout);
+ orderedLayout = createOL();
+ gridLayout = createGL();
+ formLayout = createForms();
+
+ switchToGridButton = new Button("Switch to GridLayout",
+ new ClickListener() {
+
+ public void buttonClick(ClickEvent event) {
+ changeLayout(switchToGridButton, gridLayout);
+ }
+
+ });
+ switchToOrderedButton = new Button("Switch to OrderedLayout",
+ new ClickListener() {
+
+ public void buttonClick(ClickEvent event) {
+ changeLayout(switchToOrderedButton, orderedLayout);
+ }
+
+ });
+ switchToOrderedButton.setEnabled(false);
+
+ switchToFormsButton = new Button("Switch to Form", new ClickListener() {
+
+ public void buttonClick(ClickEvent event) {
+ changeLayout(switchToFormsButton, formLayout);
+ }
+
+ });
+
+ HorizontalLayout buttonLayout = new HorizontalLayout();
+ buttonLayout.addComponent(switchToOrderedButton);
+ buttonLayout.addComponent(switchToGridButton);
+ buttonLayout.addComponent(switchToFormsButton);
+
+ mainLayout.addComponent(buttonLayout);
+ mainLayout.addComponent(orderedLayout);
+ // w.setContent(orderedLayout);
+ }
+
+ private static Layout createOL() {
+ GridLayout layout = new GridLayout(1, 5);
+
+ GridLayout l1 = new GridLayout(1, 3);
+ createLayout(l1, new HorizontalLayout(), "1000px", "150px", "100%",
+ null, true);
+ createLayout(l1, new HorizontalLayout(), "1000px", "150px", "50px",
+ null, false);
+ GridLayout l2 = new GridLayout(6, 1);
+ createLayout(l2, new VerticalLayout(), "200px", "500px", true);
+ createLayout(l2, new VerticalLayout(), "200px", "500px", "100%", null,
+ true);
+ createLayout(l2, new VerticalLayout(), "150px", "500px", true);
+ createLayout(l2, new VerticalLayout(), "150px", "500px", "100%", null,
+ true);
+ createLayout(l2, new VerticalLayout(), "100px", "500px", true);
+ createLayout(l2, new VerticalLayout(), "100px", "500px", "100%", null,
+ true);
+ layout.addComponent(l1);
+ layout.addComponent(l2);
+
+ return layout;
+ }
+
+ private static Layout createGL() {
+ GridLayout layout = new GridLayout(1, 5);
+
+ GridLayout l1 = new GridLayout(1, 3);
+ createLayout(l1, new GridLayout(8, 1), "1000px", "150px", "100%", null,
+ true);
+ createLayout(l1, new GridLayout(8, 1), "1000px", "150px", "50px", null,
+ false);
+ GridLayout l2 = new GridLayout(6, 1);
+ createLayout(l2, new GridLayout(1, 8), "200px", "500px", true);
+ createLayout(l2, new GridLayout(1, 8), "200px", "500px", "100%", null,
+ true);
+ createLayout(l2, new GridLayout(1, 8), "150px", "500px", true);
+ createLayout(l2, new GridLayout(1, 8), "150px", "500px", "100%", null,
+ true);
+ createLayout(l2, new GridLayout(1, 8), "100px", "500px", true);
+ createLayout(l2, new GridLayout(1, 8), "100px", "500px", "100%", null,
+ true);
+ layout.addComponent(l1);
+ layout.addComponent(l2);
+
+ return layout;
+ }
+
+ public class FormObject {
+ private String stringValue = "abc";
+ private int intValue = 1;
+ private long longValue = 2L;
+ private Date dateValue = new Date(34587034750L);
+
+ public String getStringValue() {
+ return stringValue;
+ }
+
+ public void setStringValue(String stringValue) {
+ this.stringValue = stringValue;
+ }
+
+ public int getIntValue() {
+ return intValue;
+ }
+
+ public void setIntValue(int intValue) {
+ this.intValue = intValue;
+ }
+
+ public long getLongValue() {
+ return longValue;
+ }
+
+ public void setLongValue(long longValue) {
+ this.longValue = longValue;
+ }
+
+ public Date getDateValue() {
+ return dateValue;
+ }
+
+ public void setDateValue(Date dateValue) {
+ this.dateValue = dateValue;
+ }
+
+ }
+
+ private Layout createForms() {
+ GridLayout layout = new GridLayout(1, 5);
+ Form form;
+
+ Random r = new Random();
+ GridLayout l1 = new GridLayout(1, 3);
+ form = createForm(l1, "200px", "500px");
+ BeanItem<FormObject> item = new BeanItem<FormObject>(new FormObject());
+ form.setItemDataSource(item);
+ for (Iterator<?> i = item.getItemPropertyIds().iterator(); i.hasNext();) {
+ Object property = i.next();
- Field f = form.getField(property);
++ Field<?> f = form.getField(property);
+
+ f.setRequired(r.nextBoolean());
+ if (r.nextBoolean()) {
+ f.setIcon(new ThemeResource("icons/16/document-add.png"));
+ }
+ if (r.nextBoolean()) {
+ f.setCaption(null);
+ }
+
+ f.addValidator(new StringLengthValidator("Error", 10, 8, false));
+ }
+ // createLayout(l1, new
+ // ExpandLayout(ExpandLayout.ORIENTATION_HORIZONTAL),
+ // "1000px", "150px", "50px", null, false);
+
+ // GridLayout l2 = new GridLayout(6, 1);
+ // createLayout(l2, new ExpandLayout(ExpandLayout.ORIENTATION_VERTICAL),
+ // "200px", "500px", true);
+ // createLayout(l2, new ExpandLayout(ExpandLayout.ORIENTATION_VERTICAL),
+ // "200px", "500px", "100%", null, true);
+ // createLayout(l2, new ExpandLayout(ExpandLayout.ORIENTATION_VERTICAL),
+ // "150px", "500px", true);
+ // createLayout(l2, new ExpandLayout(ExpandLayout.ORIENTATION_VERTICAL),
+ // "150px", "500px", "100%", null, true);
+ // createLayout(l2, new ExpandLayout(ExpandLayout.ORIENTATION_VERTICAL),
+ // "100px", "500px", true);
+ // createLayout(l2, new ExpandLayout(ExpandLayout.ORIENTATION_VERTICAL),
+ // "100px", "500px", "100%", null, true);
+ layout.addComponent(l1);
+ // layout.addComponent(l2);
+
+ return layout;
+ }
+
+ private Form createForm(GridLayout parentLayout, String w, String h) {
+ FormLayout formLayout = new FormLayout();
+ Form form = new Form(formLayout);
+
+ Panel p = new Panel("Form " + w + "x" + h);
+
+ p.setWidth(w);
+ p.setHeight(h);
+
+ p.getContent().setSizeFull();
+
+ parentLayout.addComponent(p);
+ p.addComponent(form);
+ formLayout.setSizeFull();
+
+ return form;
+ }
+
+ protected void changeLayout(Button b, Layout newLayout) {
+ switchToOrderedButton.setEnabled(true);
+ switchToGridButton.setEnabled(true);
+ switchToFormsButton.setEnabled(true);
+
+ b.setEnabled(false);
+ Iterator<Component> i = mainLayout.getComponentIterator();
+ i.next();
+ Layout l = (Layout) i.next();
+
+ mainLayout.replaceComponent(l, newLayout);
+ }
+
+ private static void createLayout(GridLayout parentLayout, Layout newLayout,
+ String w, String h, boolean align) {
+ createLayout(parentLayout, newLayout, w, h, null, null, align);
+ }
+
+ private static void createLayout(GridLayout parentLayout, Layout newLayout,
+ String w, String h, String componentWidth, String componentHeight,
+ boolean align) {
+ String dirText = "V";
+ String type;
+ if (newLayout instanceof VerticalLayout) {
+ type = "OL";
+ } else if (newLayout instanceof HorizontalLayout) {
+ dirText = "H";
+ type = "OL";
+ } else {
+ if (((GridLayout) newLayout).getColumns() != 1) {
+ dirText = "H";
+ }
+ type = "GL";
+ }
+ String alignText = align ? "-A" : "";
+ String cWidth = componentWidth == null ? "" : " - " + componentWidth;
+ Panel p = new Panel(type + "/" + dirText + alignText + " " + w + "x"
+ + h + cWidth, newLayout);
+
+ p.setWidth(w);
+ p.setHeight(h);
+
+ newLayout.setSizeFull();
+
+ String captions[] = new String[] { "TextField with caption", null };
+ Resource icons[] = new Resource[] {
+ new ThemeResource("icons/16/document-delete.png"), null };
+ boolean required[] = new boolean[] { true, false };
+ TextField fields[][] = new TextField[captions.length][icons.length];
+ for (int caption = 0; caption < captions.length; caption++) {
+ for (int icon = 0; icon < icons.length; icon++) {
+ for (int req = 0; req < required.length; req++) {
+ TextField tf = createTextFieldWithError(captions[caption],
+ icons[icon], required[req]);
+
+ fields[caption][icon] = tf;
+ if (componentWidth != null) {
+ tf.setWidth(componentWidth);
+ tf.setValue(tf.getValue() + " w:" + componentWidth);
+ }
+
+ if (componentHeight != null) {
+ tf.setHeight(componentWidth);
+ tf.setValue(tf.getValue() + " h:" + componentHeight);
+ }
+
+ p.addComponent(tf);
+
+ if (align) {
+ ((AlignmentHandler) newLayout).setComponentAlignment(
+ tf, Alignment.BOTTOM_RIGHT);
+ }
+ }
+ }
+ }
+
+ parentLayout.addComponent(p);
+
+ }
+
+ // private static void createGridLayout(GridLayout parentLayout, int dir,
+ // String w, String h) {
+ // createGridLayout(parentLayout, dir, w, h, null, null);
+ // }
+
+ // private static void createGridLayout(GridLayout parentLayout, int dir,
+ // String w, String h, String componentWidth, String componentHeight) {
+ // GridLayout gl;
+ // if (dir == OrderedLayout.ORIENTATION_HORIZONTAL) {
+ // gl = new GridLayout(8, 1);
+ // } else {
+ // gl = new GridLayout(1, 8);
+ // }
+ //
+ // String dirText = (dir == OrderedLayout.ORIENTATION_HORIZONTAL ? "H"
+ // : "V");
+ // String cWidth = componentWidth == null ? "" : " - " + componentWidth;
+ // Panel p = new Panel("GL/" + dirText + " " + w + "x" + h + cWidth, gl);
+ //
+ // p.setWidth(w);
+ // p.setHeight(h);
+ //
+ // gl.setSizeFull();
+ //
+ // String captions[] = new String[] { "TextField with caption", null };
+ // Resource icons[] = new Resource[] {
+ // new ThemeResource("icons/16/document-delete.png"), null };
+ // boolean required[] = new boolean[] { true, false };
+ // TextField fields[][] = new TextField[captions.length][icons.length];
+ // for (int caption = 0; caption < captions.length; caption++) {
+ // for (int icon = 0; icon < icons.length; icon++) {
+ // for (int req = 0; req < required.length; req++) {
+ // TextField tf = createTextFieldWithError(captions[caption],
+ // icons[icon], required[req]);
+ //
+ // fields[caption][icon] = tf;
+ // if (componentWidth != null) {
+ // tf.setWidth(componentWidth);
+ // }
+ //
+ // if (componentHeight != null) {
+ // tf.setHeight(componentWidth);
+ // }
+ //
+ // p.addComponent(tf);
+ // gl.setComponentAlignment(tf, OrderedLayout.ALIGNMENT_LEFT,
+ // OrderedLayout.ALIGNMENT_BOTTOM);
+ // }
+ // }
+ // }
+ //
+ // parentLayout.addComponent(p);
+ //
+ // }
+
+ private static TextField createTextFieldWithError(String caption,
+ Resource icon, boolean required) {
+ TextField tf = new TextField();
+ tf.setCaption(caption);
+ tf.setIcon(icon);
+ tf.setRequired(required);
+ tf.setComponentError(new UserError("Test error message"));
+ return tf;
+ }
+ }
- package com.vaadin.tests.tickets;\r
- \r
- import com.vaadin.ui.Button;\r
- import com.vaadin.ui.Button.ClickEvent;\r
- import com.vaadin.ui.Component;\r
- import com.vaadin.ui.GridLayout;\r
- import com.vaadin.ui.Panel;\r
- import com.vaadin.ui.Root.LegacyWindow;\r
- \r
- public class Ticket1919 extends com.vaadin.Application.LegacyApplication {\r
- \r
- private GridLayout lo;\r
- private boolean on = true;\r
- \r
- @Override\r
- public void init() {\r
- final LegacyWindow main = new LegacyWindow(getClass().getName()\r
- .substring(getClass().getName().lastIndexOf(".") + 1));\r
- setMainWindow(main);\r
- \r
- setTheme("tests-tickets");\r
- \r
- lo = new GridLayout(2, 2);\r
- lo.setSizeFull();\r
- lo.setMargin(true);\r
- lo.setSpacing(true);\r
- \r
- lo.addComponent(getTestComponent());\r
- lo.addComponent(getTestComponent());\r
- lo.addComponent(getTestComponent());\r
- lo.addComponent(getTestComponent());\r
- \r
- main.setContent(lo);\r
- \r
- }\r
- \r
- public void toggleStyleName() {\r
- if (on) {\r
- lo.setStyleName("test");\r
- } else {\r
- lo.setStyleName("");\r
- }\r
- on = !on;\r
- }\r
- \r
- private Component getTestComponent() {\r
- Panel p = new Panel();\r
- p.setSizeFull();\r
- \r
- Button b = new Button("toggle Values", new Button.ClickListener() {\r
- public void buttonClick(ClickEvent event) {\r
- toggleStyleName();\r
- }\r
- });\r
- p.addComponent(b);\r
- return p;\r
- }\r
+ package com.vaadin.tests.tickets;
+
+ import com.vaadin.ui.Button;
++import com.vaadin.ui.Button.ClickEvent;
+ import com.vaadin.ui.Component;
+ import com.vaadin.ui.GridLayout;
+ import com.vaadin.ui.Panel;
-import com.vaadin.ui.Window;
++import com.vaadin.ui.Root.LegacyWindow;
+
-public class Ticket1919 extends com.vaadin.Application {
++public class Ticket1919 extends com.vaadin.Application.LegacyApplication {
+
+ private GridLayout lo;
+ private boolean on = true;
+
+ @Override
+ public void init() {
- final Window main = new Window(getClass().getName().substring(
- getClass().getName().lastIndexOf(".") + 1));
++ final LegacyWindow main = new LegacyWindow(getClass().getName()
++ .substring(getClass().getName().lastIndexOf(".") + 1));
+ setMainWindow(main);
+
- main.setTheme("tests-tickets");
++ setTheme("tests-tickets");
+
+ lo = new GridLayout(2, 2);
+ lo.setSizeFull();
+ lo.setMargin(true);
+ lo.setSpacing(true);
+
+ lo.addComponent(getTestComponent());
+ lo.addComponent(getTestComponent());
+ lo.addComponent(getTestComponent());
+ lo.addComponent(getTestComponent());
+
+ main.setContent(lo);
+
+ }
+
+ public void toggleStyleName() {
+ if (on) {
+ lo.setStyleName("test");
+ } else {
+ lo.setStyleName("");
+ }
+ on = !on;
+ }
+
+ private Component getTestComponent() {
+ Panel p = new Panel();
+ p.setSizeFull();
+
- Button b = new Button("toggle Values", this, "toggleStyleName");
++ Button b = new Button("toggle Values", new Button.ClickListener() {
++ public void buttonClick(ClickEvent event) {
++ toggleStyleName();
++ }
++ });
+ p.addComponent(b);
+ return p;
+ }
-}
+}
- package com.vaadin.tests.tickets;\r
- \r
- import com.vaadin.ui.Label;\r
- import com.vaadin.ui.Panel;\r
- import com.vaadin.ui.Root.LegacyWindow;\r
- import com.vaadin.ui.VerticalLayout;\r
- \r
- public class Ticket1923 extends com.vaadin.Application.LegacyApplication {\r
- \r
- private static final int ROWS = 50;\r
- \r
- private Panel p;\r
- \r
- @Override\r
- public void init() {\r
- final LegacyWindow main = new LegacyWindow(getClass().getName()\r
- .substring(getClass().getName().lastIndexOf(".") + 1));\r
- setMainWindow(main);\r
- \r
- p = new Panel("TestPanel 250x300");\r
- // p.getLayout().setWidth("100%");\r
- p.setScrollable(true);\r
- // p.setContent(new GridLayout(1, 100));\r
- for (int i = 0; i < ROWS; i++) {\r
- p.addComponent(new Label(\r
- "Label"\r
- + i\r
- + " 5067w09adsfasdjfahlsdfjhalfjhaldjfhalsjdfhlajdhflajhdfljahdslfjahldsjfhaljdfhaljfdhlajsdhflajshdflkajhsdlfkjahsldfkjahsldfhalskjfdhlksjfdh857idifhaljsdfhlajsdhflajhdflajhdfljahldfjhaljdfhalsjdfhalkjdhflkajhdfljahsdlfjahlsdjfhaldjfhaljfdhlajdhflajshdfljahsdlfjhalsjdfhalskjhfdlhusfglksuhdflgjshflgjhslfghslfjghsljfglsjhfglsjhfgljshfgljshflgjhslfghsljfgsljdfglsdjhfglsjhflgkjshfldjgh"));\r
- }\r
- // main.getLayout().setSizeFull();\r
- \r
- p.setHeight("300px");\r
- p.setWidth("250px");\r
- // p.setWidth("50%");\r
- \r
- p.setScrollTop(100);\r
- p.setScrollLeft(100);\r
- \r
- main.addComponent(p);\r
- \r
- VerticalLayout ol = new VerticalLayout();\r
- p = new Panel("a");\r
- p.addComponent(new Label("Longer than caption"));\r
- ol.addComponent(p);\r
- \r
- main.addComponent(ol);\r
- \r
- ol = new VerticalLayout();\r
- p = new Panel("captionasdfjahsdjfh this should be clipped god damn it");\r
- // p.getLayout().setSizeFull();\r
- p.setWidth("50px");\r
- p.setHeight("100px");\r
- p.addComponent(new Label(\r
- "aasdfaasdfja dslkfj lakfdj lakjdf lkaj dflkaj ldfkj alsdfj laksdj flkajs dflkj sdfsadfasdfasd"));\r
- ol.addComponent(p);\r
- \r
- main.addComponent(ol);\r
- \r
- ol = new VerticalLayout();\r
- p = new Panel("300x-1");\r
- // p.getLayout().setSizeFull();\r
- p.setWidth("300px");\r
- p.addComponent(new Label("Short"));\r
- p.addComponent(new Label("Short"));\r
- p.addComponent(new Label("Short"));\r
- p.addComponent(new Label("Short"));\r
- p.addComponent(new Label("Short"));\r
- p.addComponent(new Label("Short"));\r
- p.addComponent(new Label("Short"));\r
- p.addComponent(new Label("Short"));\r
- p.addComponent(new Label("Short"));\r
- p.addComponent(new Label("Short"));\r
- p.addComponent(new Label("Short"));\r
- p.addComponent(new Label("Short"));\r
- p.addComponent(new Label("Short"));\r
- ol.addComponent(p);\r
- \r
- main.addComponent(ol);\r
- }\r
+ package com.vaadin.tests.tickets;
+
+ import com.vaadin.ui.Label;
+ import com.vaadin.ui.Panel;
++import com.vaadin.ui.Root.LegacyWindow;
+ import com.vaadin.ui.VerticalLayout;
-import com.vaadin.ui.Window;
+
-public class Ticket1923 extends com.vaadin.Application {
++public class Ticket1923 extends com.vaadin.Application.LegacyApplication {
+
+ private static final int ROWS = 50;
+
+ private Panel p;
+
+ @Override
+ public void init() {
- final Window main = new Window(getClass().getName().substring(
- getClass().getName().lastIndexOf(".") + 1));
++ final LegacyWindow main = new LegacyWindow(getClass().getName()
++ .substring(getClass().getName().lastIndexOf(".") + 1));
+ setMainWindow(main);
+
+ p = new Panel("TestPanel 250x300");
+ // p.getLayout().setWidth("100%");
+ p.setScrollable(true);
+ // p.setContent(new GridLayout(1, 100));
+ for (int i = 0; i < ROWS; i++) {
+ p.addComponent(new Label(
+ "Label"
+ + i
+ + " 5067w09adsfasdjfahlsdfjhalfjhaldjfhalsjdfhlajdhflajhdfljahdslfjahldsjfhaljdfhaljfdhlajsdhflajshdflkajhsdlfkjahsldfkjahsldfhalskjfdhlksjfdh857idifhaljsdfhlajsdhflajhdflajhdfljahldfjhaljdfhalsjdfhalkjdhflkajhdfljahsdlfjahlsdjfhaldjfhaljfdhlajdhflajshdfljahsdlfjhalsjdfhalskjhfdlhusfglksuhdflgjshflgjhslfghslfjghsljfglsjhfglsjhfgljshfgljshflgjhslfghsljfgsljdfglsdjhfglsjhflgkjshfldjgh"));
+ }
+ // main.getLayout().setSizeFull();
+
+ p.setHeight("300px");
+ p.setWidth("250px");
+ // p.setWidth("50%");
+
+ p.setScrollTop(100);
+ p.setScrollLeft(100);
+
+ main.addComponent(p);
+
+ VerticalLayout ol = new VerticalLayout();
+ p = new Panel("a");
+ p.addComponent(new Label("Longer than caption"));
+ ol.addComponent(p);
+
+ main.addComponent(ol);
+
+ ol = new VerticalLayout();
+ p = new Panel("captionasdfjahsdjfh this should be clipped god damn it");
+ // p.getLayout().setSizeFull();
+ p.setWidth("50px");
+ p.setHeight("100px");
+ p.addComponent(new Label(
+ "aasdfaasdfja dslkfj lakfdj lakjdf lkaj dflkaj ldfkj alsdfj laksdj flkajs dflkj sdfsadfasdfasd"));
+ ol.addComponent(p);
+
+ main.addComponent(ol);
+
+ ol = new VerticalLayout();
+ p = new Panel("300x-1");
+ // p.getLayout().setSizeFull();
+ p.setWidth("300px");
+ p.addComponent(new Label("Short"));
+ p.addComponent(new Label("Short"));
+ p.addComponent(new Label("Short"));
+ p.addComponent(new Label("Short"));
+ p.addComponent(new Label("Short"));
+ p.addComponent(new Label("Short"));
+ p.addComponent(new Label("Short"));
+ p.addComponent(new Label("Short"));
+ p.addComponent(new Label("Short"));
+ p.addComponent(new Label("Short"));
+ p.addComponent(new Label("Short"));
+ p.addComponent(new Label("Short"));
+ p.addComponent(new Label("Short"));
+ ol.addComponent(p);
+
+ main.addComponent(ol);
+ }
}
- package com.vaadin.tests.tickets;\r
- \r
- import com.vaadin.Application;\r
- import com.vaadin.ui.Root.LegacyWindow;\r
- \r
- public class Ticket1925 extends Application.LegacyApplication {\r
- \r
- @Override\r
- public void init() {\r
- LegacyWindow mainWindow = new LegacyWindow("Test åäö");\r
- setMainWindow(mainWindow);\r
- \r
- }\r
- \r
- }\r
+ package com.vaadin.tests.tickets;
+
+ import com.vaadin.Application;
-import com.vaadin.ui.Window;
++import com.vaadin.ui.Root.LegacyWindow;
+
-public class Ticket1925 extends Application {
++public class Ticket1925 extends Application.LegacyApplication {
+
+ @Override
+ public void init() {
- Window mainWindow = new Window("Test åäö");
++ LegacyWindow mainWindow = new LegacyWindow("Test åäö");
+ setMainWindow(mainWindow);
+
+ }
+
+ }
- package com.vaadin.tests.tickets;\r
- \r
- import com.vaadin.Application;\r
- import com.vaadin.ui.AbstractOrderedLayout;\r
- import com.vaadin.ui.Alignment;\r
- import com.vaadin.ui.Button;\r
- import com.vaadin.ui.GridLayout;\r
- import com.vaadin.ui.HorizontalLayout;\r
- import com.vaadin.ui.Layout;\r
- import com.vaadin.ui.Layout.AlignmentHandler;\r
- import com.vaadin.ui.Panel;\r
- import com.vaadin.ui.Root.LegacyWindow;\r
- import com.vaadin.ui.VerticalLayout;\r
- \r
- public class Ticket1966 extends Application.LegacyApplication {\r
- \r
- @Override\r
- public void init() {\r
- LegacyWindow w = new LegacyWindow(getClass().getName());\r
- setMainWindow(w);\r
- // setTheme("tests-tickets");\r
- w.setContent(new GridLayout(2, 2));\r
- // w.getLayout().setSizeFull();\r
- createUI((Layout) w.getContent());\r
- }\r
- \r
- private void createUI(Layout layout) {\r
- orderedLayout(layout);\r
- gridLayout(layout);\r
- }\r
- \r
- private void gridLayout(Layout layout) {\r
- Panel p = new Panel("GridLayout");\r
- layout.addComponent(p);\r
- \r
- GridLayout gl = new GridLayout(1, 4);\r
- gl.setCaption("Horizontal");\r
- Button b;\r
- \r
- b = new Button("Wide button");\r
- b.setWidth("500px");\r
- gl.addComponent(b);\r
- \r
- addButtons(gl);\r
- \r
- p.addComponent(gl);\r
- \r
- /* VERTICAL */\r
- \r
- gl = new GridLayout(4, 1);\r
- gl.setCaption("Vertical");\r
- \r
- addButtons(gl);\r
- \r
- b = new Button("High button");\r
- b.setHeight("200px");\r
- gl.addComponent(b);\r
- \r
- p.addComponent(gl);\r
- \r
- }\r
- \r
- private void orderedLayout(Layout layout) {\r
- Panel p = new Panel("OrderedLayout");\r
- layout.addComponent(p);\r
- \r
- AbstractOrderedLayout ol = new VerticalLayout();\r
- ol.setCaption("Horizontal");\r
- // ol.setWidth("100%");\r
- \r
- Button b;\r
- \r
- b = new Button("Wide button");\r
- b.setWidth("500px");\r
- ol.addComponent(b);\r
- \r
- addButtons(ol);\r
- p.addComponent(ol);\r
- \r
- /* VERTICAL */\r
- \r
- ol = new HorizontalLayout();\r
- ol.setCaption("Vertical");\r
- \r
- addButtons(ol);\r
- b = new Button("High button");\r
- b.setHeight("200px");\r
- ol.addComponent(b);\r
- \r
- p.addComponent(ol);\r
- \r
- }\r
- \r
- private void addButtons(Layout ol) {\r
- ol.addComponent(getButton(ol, Alignment.TOP_LEFT));\r
- ol.addComponent(getButton(ol, Alignment.MIDDLE_CENTER));\r
- ol.addComponent(getButton(ol, Alignment.BOTTOM_RIGHT));\r
- \r
- }\r
- \r
- private Button getButton(Layout l, Alignment align) {\r
- Button b = new Button("Narrow Button - "\r
- + align.getHorizontalAlignment() + " - "\r
- + align.getVerticalAlignment());\r
- b.setWidth("100px");\r
- ((AlignmentHandler) l).setComponentAlignment(b, align);\r
- \r
- return b;\r
- \r
- }\r
- }\r
+ package com.vaadin.tests.tickets;
+
+ import com.vaadin.Application;
+ import com.vaadin.ui.AbstractOrderedLayout;
+ import com.vaadin.ui.Alignment;
+ import com.vaadin.ui.Button;
+ import com.vaadin.ui.GridLayout;
+ import com.vaadin.ui.HorizontalLayout;
+ import com.vaadin.ui.Layout;
+ import com.vaadin.ui.Layout.AlignmentHandler;
+ import com.vaadin.ui.Panel;
++import com.vaadin.ui.Root.LegacyWindow;
+ import com.vaadin.ui.VerticalLayout;
-import com.vaadin.ui.Window;
+
-public class Ticket1966 extends Application {
++public class Ticket1966 extends Application.LegacyApplication {
+
+ @Override
+ public void init() {
- Window w = new Window(getClass().getName());
++ LegacyWindow w = new LegacyWindow(getClass().getName());
+ setMainWindow(w);
+ // setTheme("tests-tickets");
+ w.setContent(new GridLayout(2, 2));
+ // w.getLayout().setSizeFull();
+ createUI((Layout) w.getContent());
+ }
+
+ private void createUI(Layout layout) {
+ orderedLayout(layout);
+ gridLayout(layout);
+ }
+
+ private void gridLayout(Layout layout) {
+ Panel p = new Panel("GridLayout");
+ layout.addComponent(p);
+
+ GridLayout gl = new GridLayout(1, 4);
+ gl.setCaption("Horizontal");
+ Button b;
+
+ b = new Button("Wide button");
+ b.setWidth("500px");
+ gl.addComponent(b);
+
+ addButtons(gl);
+
+ p.addComponent(gl);
+
+ /* VERTICAL */
+
+ gl = new GridLayout(4, 1);
+ gl.setCaption("Vertical");
+
+ addButtons(gl);
+
+ b = new Button("High button");
+ b.setHeight("200px");
+ gl.addComponent(b);
+
+ p.addComponent(gl);
+
+ }
+
+ private void orderedLayout(Layout layout) {
+ Panel p = new Panel("OrderedLayout");
+ layout.addComponent(p);
+
+ AbstractOrderedLayout ol = new VerticalLayout();
+ ol.setCaption("Horizontal");
+ // ol.setWidth("100%");
+
+ Button b;
+
+ b = new Button("Wide button");
+ b.setWidth("500px");
+ ol.addComponent(b);
+
+ addButtons(ol);
+ p.addComponent(ol);
+
+ /* VERTICAL */
+
+ ol = new HorizontalLayout();
+ ol.setCaption("Vertical");
+
+ addButtons(ol);
+ b = new Button("High button");
+ b.setHeight("200px");
+ ol.addComponent(b);
+
+ p.addComponent(ol);
+
+ }
+
+ private void addButtons(Layout ol) {
+ ol.addComponent(getButton(ol, Alignment.TOP_LEFT));
+ ol.addComponent(getButton(ol, Alignment.MIDDLE_CENTER));
+ ol.addComponent(getButton(ol, Alignment.BOTTOM_RIGHT));
+
+ }
+
+ private Button getButton(Layout l, Alignment align) {
+ Button b = new Button("Narrow Button - "
+ + align.getHorizontalAlignment() + " - "
+ + align.getVerticalAlignment());
+ b.setWidth("100px");
+ ((AlignmentHandler) l).setComponentAlignment(b, align);
+
+ return b;
+
+ }
+ }
- package com.vaadin.tests.tickets;\r
- \r
- import com.vaadin.Application;\r
- import com.vaadin.ui.AbstractOrderedLayout;\r
- import com.vaadin.ui.Alignment;\r
- import com.vaadin.ui.Button;\r
- import com.vaadin.ui.GridLayout;\r
- import com.vaadin.ui.HorizontalLayout;\r
- import com.vaadin.ui.Layout;\r
- import com.vaadin.ui.Layout.AlignmentHandler;\r
- import com.vaadin.ui.Panel;\r
- import com.vaadin.ui.Root.LegacyWindow;\r
- import com.vaadin.ui.VerticalLayout;\r
- \r
- public class Ticket1966_2 extends Application.LegacyApplication {\r
- \r
- @Override\r
- public void init() {\r
- LegacyWindow w = new LegacyWindow(getClass().getName());\r
- setMainWindow(w);\r
- w.setContent(new GridLayout(2, 2));\r
- \r
- // Panel p = new Panel("test");\r
- // p.setWidth(500);\r
- // p.setHeight(500);\r
- // p.setContent(new GridLayout(1, 2));\r
- // p.getLayout().setSizeFull();\r
- //\r
- // p.addComponent(new Button("asjkdfhakshdf"));\r
- // p.addComponent(new Button("öalijgto8aq5"));\r
- \r
- // GridLayout gl = new GridLayout(4, 1);\r
- // // gl.setCaption("Vertical");\r
- // gl.setWidth("100%");\r
- // gl.setHeight(500);\r
- \r
- // addButtons(gl);\r
- // gl.addComponent(new Label("abc"));\r
- // p.addComponent(gl);\r
- \r
- // w.getLayout().addComponent(p);\r
- createUI((Layout) w.getContent());\r
- }\r
- \r
- private void createUI(Layout layout) {\r
- orderedLayout(layout);\r
- gridLayout(layout);\r
- expandLayout(layout);\r
- }\r
- \r
- private void gridLayout(Layout layout) {\r
- Panel p = new Panel("GridLayout");\r
- p.setWidth("500px");\r
- p.setHeight("500px");\r
- p.getContent().setSizeFull();\r
- layout.addComponent(p);\r
- \r
- GridLayout gl = new GridLayout(1, 4);\r
- gl.setCaption("Horizontal");\r
- gl.setWidth("100%");\r
- \r
- // Button b;\r
- \r
- // b = new Button("Wide button");\r
- // b.setWidth("500");\r
- // gl.addComponent(b);\r
- \r
- addButtons(gl);\r
- \r
- p.addComponent(gl);\r
- \r
- /* VERTICAL */\r
- \r
- gl = new GridLayout(4, 1);\r
- // gl.setCaption("Vertical");\r
- gl.setHeight("100%");\r
- addButtons(gl);\r
- \r
- // Button b = new Button("High button");\r
- // b.setHeight(200);\r
- // gl.addComponent(b);\r
- \r
- p.addComponent(gl);\r
- \r
- }\r
- \r
- private void orderedLayout(Layout layout) {\r
- Panel p = new Panel("OrderedLayout");\r
- p.setWidth("500px");\r
- p.setHeight("500px");\r
- p.getContent().setWidth("100%");\r
- layout.addComponent(p);\r
- \r
- AbstractOrderedLayout ol = new VerticalLayout();\r
- // ol.setCaption("Horizontal");\r
- ol.setWidth("100%");\r
- addButtons(ol);\r
- p.addComponent(ol);\r
- \r
- /* VERTICAL */\r
- \r
- ol = new HorizontalLayout();\r
- // ol.setCaption("Vertical");\r
- ol.setHeight("200px");\r
- addButtons(ol);\r
- // Button b = new Button("High button");\r
- // b.setHeight(200);\r
- // ol.addComponent(b);\r
- p.addComponent(ol);\r
- \r
- }\r
- \r
- private void expandLayout(Layout layout) {\r
- Panel p = new Panel("ExpandLayout");\r
- layout.addComponent(p);\r
- p.getContent().setWidth("500");\r
- p.getContent().setHeight("400");\r
- \r
- AbstractOrderedLayout el = new VerticalLayout();\r
- // el.setCaption("Horizontal");\r
- // el.setSizeUndefined();\r
- // el.setWidth("100%");\r
- // ol.setWidth("100%");\r
- Button b;\r
- \r
- b = new Button("Wide button");\r
- b.setWidth("100%");\r
- // b.setHeight(200);\r
- // el.setExpandRatio(b,1);\r
- // el.addComponent(b);\r
- \r
- addButtons(el);\r
- p.addComponent(el);\r
- \r
- /* VERTICAL */\r
- \r
- el = new HorizontalLayout();\r
- // el.setHeight(400);\r
- // el.setWidth("100%");\r
- // el.setCaption("Vertical");\r
- \r
- addButtons(el);\r
- // b = new Button("High button");\r
- // el.setExpandRatio(b,1);\r
- // b.setHeight(100);\r
- // el.addComponent(b);\r
- \r
- p.addComponent(el);\r
- \r
- }\r
- \r
- private void addButtons(Layout ol) {\r
- ol.addComponent(getButton(ol, Alignment.TOP_LEFT));\r
- ol.addComponent(getButton(ol, Alignment.MIDDLE_CENTER));\r
- ol.addComponent(getButton(ol, Alignment.BOTTOM_RIGHT));\r
- \r
- }\r
- \r
- private Button getButton(Layout l, Alignment align) {\r
- Button b = new Button(align.getHorizontalAlignment() + " - "\r
- + align.getVerticalAlignment());\r
- // b.setWidth("100");\r
- ((AlignmentHandler) l).setComponentAlignment(b, align);\r
- \r
- return b;\r
- \r
- }\r
- }\r
+ package com.vaadin.tests.tickets;
+
+ import com.vaadin.Application;
+ import com.vaadin.ui.AbstractOrderedLayout;
+ import com.vaadin.ui.Alignment;
+ import com.vaadin.ui.Button;
+ import com.vaadin.ui.GridLayout;
+ import com.vaadin.ui.HorizontalLayout;
+ import com.vaadin.ui.Layout;
+ import com.vaadin.ui.Layout.AlignmentHandler;
+ import com.vaadin.ui.Panel;
++import com.vaadin.ui.Root.LegacyWindow;
+ import com.vaadin.ui.VerticalLayout;
-import com.vaadin.ui.Window;
+
-public class Ticket1966_2 extends Application {
++public class Ticket1966_2 extends Application.LegacyApplication {
+
+ @Override
+ public void init() {
- Window w = new Window(getClass().getName());
++ LegacyWindow w = new LegacyWindow(getClass().getName());
+ setMainWindow(w);
+ w.setContent(new GridLayout(2, 2));
+
+ // Panel p = new Panel("test");
+ // p.setWidth(500);
+ // p.setHeight(500);
+ // p.setContent(new GridLayout(1, 2));
+ // p.getLayout().setSizeFull();
+ //
+ // p.addComponent(new Button("asjkdfhakshdf"));
+ // p.addComponent(new Button("öalijgto8aq5"));
+
+ // GridLayout gl = new GridLayout(4, 1);
+ // // gl.setCaption("Vertical");
+ // gl.setWidth("100%");
+ // gl.setHeight(500);
+
+ // addButtons(gl);
+ // gl.addComponent(new Label("abc"));
+ // p.addComponent(gl);
+
+ // w.getLayout().addComponent(p);
+ createUI((Layout) w.getContent());
+ }
+
+ private void createUI(Layout layout) {
+ orderedLayout(layout);
+ gridLayout(layout);
+ expandLayout(layout);
+ }
+
+ private void gridLayout(Layout layout) {
+ Panel p = new Panel("GridLayout");
+ p.setWidth("500px");
+ p.setHeight("500px");
+ p.getContent().setSizeFull();
+ layout.addComponent(p);
+
+ GridLayout gl = new GridLayout(1, 4);
+ gl.setCaption("Horizontal");
+ gl.setWidth("100%");
+
+ // Button b;
+
+ // b = new Button("Wide button");
+ // b.setWidth("500");
+ // gl.addComponent(b);
+
+ addButtons(gl);
+
+ p.addComponent(gl);
+
+ /* VERTICAL */
+
+ gl = new GridLayout(4, 1);
+ // gl.setCaption("Vertical");
+ gl.setHeight("100%");
+ addButtons(gl);
+
+ // Button b = new Button("High button");
+ // b.setHeight(200);
+ // gl.addComponent(b);
+
+ p.addComponent(gl);
+
+ }
+
+ private void orderedLayout(Layout layout) {
+ Panel p = new Panel("OrderedLayout");
+ p.setWidth("500px");
+ p.setHeight("500px");
+ p.getContent().setWidth("100%");
+ layout.addComponent(p);
+
+ AbstractOrderedLayout ol = new VerticalLayout();
+ // ol.setCaption("Horizontal");
+ ol.setWidth("100%");
+ addButtons(ol);
+ p.addComponent(ol);
+
+ /* VERTICAL */
+
+ ol = new HorizontalLayout();
+ // ol.setCaption("Vertical");
+ ol.setHeight("200px");
+ addButtons(ol);
+ // Button b = new Button("High button");
+ // b.setHeight(200);
+ // ol.addComponent(b);
+ p.addComponent(ol);
+
+ }
+
+ private void expandLayout(Layout layout) {
+ Panel p = new Panel("ExpandLayout");
+ layout.addComponent(p);
+ p.getContent().setWidth("500");
+ p.getContent().setHeight("400");
+
+ AbstractOrderedLayout el = new VerticalLayout();
+ // el.setCaption("Horizontal");
+ // el.setSizeUndefined();
+ // el.setWidth("100%");
+ // ol.setWidth("100%");
+ Button b;
+
+ b = new Button("Wide button");
+ b.setWidth("100%");
+ // b.setHeight(200);
+ // el.setExpandRatio(b,1);
+ // el.addComponent(b);
+
+ addButtons(el);
+ p.addComponent(el);
+
+ /* VERTICAL */
+
+ el = new HorizontalLayout();
+ // el.setHeight(400);
+ // el.setWidth("100%");
+ // el.setCaption("Vertical");
+
+ addButtons(el);
+ // b = new Button("High button");
+ // el.setExpandRatio(b,1);
+ // b.setHeight(100);
+ // el.addComponent(b);
+
+ p.addComponent(el);
+
+ }
+
+ private void addButtons(Layout ol) {
+ ol.addComponent(getButton(ol, Alignment.TOP_LEFT));
+ ol.addComponent(getButton(ol, Alignment.MIDDLE_CENTER));
+ ol.addComponent(getButton(ol, Alignment.BOTTOM_RIGHT));
+
+ }
+
+ private Button getButton(Layout l, Alignment align) {
+ Button b = new Button(align.getHorizontalAlignment() + " - "
+ + align.getVerticalAlignment());
+ // b.setWidth("100");
+ ((AlignmentHandler) l).setComponentAlignment(b, align);
+
+ return b;
+
+ }
+ }
- package com.vaadin.tests.tickets;\r
- \r
- import com.vaadin.Application;\r
- import com.vaadin.terminal.ThemeResource;\r
- import com.vaadin.terminal.UserError;\r
- import com.vaadin.ui.Alignment;\r
- import com.vaadin.ui.GridLayout;\r
- import com.vaadin.ui.Panel;\r
- import com.vaadin.ui.Root.LegacyWindow;\r
- import com.vaadin.ui.TextField;\r
- import com.vaadin.ui.VerticalLayout;\r
- \r
- public class Ticket1966_3 extends Application.LegacyApplication {\r
- \r
- @Override\r
- public void init() {\r
- LegacyWindow w = new LegacyWindow(getClass().getSimpleName());\r
- setMainWindow(w);\r
- // setTheme("tests-tickets");\r
- GridLayout layout = new GridLayout(10, 10);\r
- w.setContent(layout);\r
- createUI(layout);\r
- }\r
- \r
- private void createUI(GridLayout layout) {\r
- VerticalLayout ol = new VerticalLayout();\r
- Panel p = new Panel(ol);\r
- p.setWidth("300px");\r
- p.setHeight("300px");\r
- p.getContent().setSizeFull();\r
- \r
- TextField tf = new TextField("Long caption, longer than 100 pixels");\r
- tf.setWidth("100px");\r
- \r
- ol.addComponent(tf);\r
- ol.setComponentAlignment(tf, Alignment.TOP_RIGHT);\r
- \r
- tf = new TextField("Short caption");\r
- tf.setWidth("100px");\r
- \r
- tf.setComponentError(new UserError("error message"));\r
- ol.addComponent(tf);\r
- ol.setComponentAlignment(tf, Alignment.TOP_RIGHT);\r
- \r
- tf = new TextField("Short caption");\r
- tf.setComponentError(new UserError("error message"));\r
- tf.setIcon(new ThemeResource("icons/16/calendar.png"));\r
- tf.setWidth("100px");\r
- \r
- tf.setComponentError(new UserError("error message"));\r
- ol.addComponent(tf);\r
- ol.setComponentAlignment(tf, Alignment.TOP_RIGHT);\r
- \r
- tf = new TextField();\r
- tf.setValue("No caption");\r
- tf.setWidth("100px");\r
- \r
- ol.addComponent(tf);\r
- ol.setComponentAlignment(tf, Alignment.TOP_RIGHT);\r
- \r
- layout.addComponent(p);\r
- }\r
- }\r
+ package com.vaadin.tests.tickets;
+
+ import com.vaadin.Application;
+ import com.vaadin.terminal.ThemeResource;
+ import com.vaadin.terminal.UserError;
+ import com.vaadin.ui.Alignment;
+ import com.vaadin.ui.GridLayout;
+ import com.vaadin.ui.Panel;
++import com.vaadin.ui.Root.LegacyWindow;
+ import com.vaadin.ui.TextField;
+ import com.vaadin.ui.VerticalLayout;
-import com.vaadin.ui.Window;
+
-public class Ticket1966_3 extends Application {
++public class Ticket1966_3 extends Application.LegacyApplication {
+
+ @Override
+ public void init() {
- Window w = new Window(getClass().getSimpleName());
++ LegacyWindow w = new LegacyWindow(getClass().getSimpleName());
+ setMainWindow(w);
+ // setTheme("tests-tickets");
+ GridLayout layout = new GridLayout(10, 10);
+ w.setContent(layout);
+ createUI(layout);
+ }
+
+ private void createUI(GridLayout layout) {
+ VerticalLayout ol = new VerticalLayout();
+ Panel p = new Panel(ol);
+ p.setWidth("300px");
+ p.setHeight("300px");
+ p.getContent().setSizeFull();
+
+ TextField tf = new TextField("Long caption, longer than 100 pixels");
+ tf.setWidth("100px");
+
+ ol.addComponent(tf);
+ ol.setComponentAlignment(tf, Alignment.TOP_RIGHT);
+
+ tf = new TextField("Short caption");
+ tf.setWidth("100px");
+
+ tf.setComponentError(new UserError("error message"));
+ ol.addComponent(tf);
+ ol.setComponentAlignment(tf, Alignment.TOP_RIGHT);
+
+ tf = new TextField("Short caption");
+ tf.setComponentError(new UserError("error message"));
+ tf.setIcon(new ThemeResource("icons/16/calendar.png"));
+ tf.setWidth("100px");
+
+ tf.setComponentError(new UserError("error message"));
+ ol.addComponent(tf);
+ ol.setComponentAlignment(tf, Alignment.TOP_RIGHT);
+
+ tf = new TextField();
+ tf.setValue("No caption");
+ tf.setWidth("100px");
+
+ ol.addComponent(tf);
+ ol.setComponentAlignment(tf, Alignment.TOP_RIGHT);
+
+ layout.addComponent(p);
+ }
+ }
- package com.vaadin.tests.tickets;\r
- \r
- import com.vaadin.terminal.UserError;\r
- import com.vaadin.tests.TestForTablesInitialColumnWidthLogicRendering;\r
- import com.vaadin.ui.Button;\r
- import com.vaadin.ui.Button.ClickEvent;\r
- import com.vaadin.ui.Label;\r
- import com.vaadin.ui.Root.LegacyWindow;\r
- import com.vaadin.ui.TabSheet;\r
- import com.vaadin.ui.Table;\r
- import com.vaadin.ui.VerticalLayout;\r
- \r
- public class Ticket1969 extends com.vaadin.Application.LegacyApplication {\r
- \r
- @Override\r
- public void init() {\r
- final LegacyWindow main = new LegacyWindow(getClass().getName()\r
- .substring(getClass().getName().lastIndexOf(".") + 1));\r
- setMainWindow(main);\r
- \r
- main.getContent().setSizeFull();\r
- \r
- TabSheet ts = new TabSheet();\r
- ts.setSizeFull();\r
- \r
- final Table t = TestForTablesInitialColumnWidthLogicRendering\r
- .getTestTable(7, 2000);\r
- t.setSizeFull();\r
- ts.addTab(t, "Table, scrollins should not flash", null);\r
- \r
- final Label testContent = new Label(\r
- "TabSheet by default uses caption, icon, errors etc. from Components. ");\r
- \r
- testContent.setCaption("Introduction to test");\r
- \r
- ts.addTab(testContent);\r
- \r
- final VerticalLayout actions = new VerticalLayout();\r
- \r
- actions.setCaption("Test actions");\r
- \r
- ts.addTab(actions);\r
- \r
- Button b;\r
- \r
- b = new Button(\r
- "change introduction caption (should add * to tab name)",\r
- new Button.ClickListener() {\r
- public void buttonClick(ClickEvent event) {\r
- testContent.setCaption(testContent.getCaption() + "*");\r
- }\r
- });\r
- actions.addComponent(b);\r
- \r
- b = new Button("change tab caption (should add * to tab name)",\r
- new Button.ClickListener() {\r
- public void buttonClick(ClickEvent event) {\r
- actions.setCaption(actions.getCaption() + "*");\r
- }\r
- });\r
- \r
- actions.addComponent(b);\r
- \r
- final UserError e = new UserError("Test error");\r
- \r
- b = new Button("Toggle error", new Button.ClickListener() {\r
- public void buttonClick(ClickEvent event) {\r
- if (testContent.getComponentError() == null) {\r
- testContent.setComponentError(e);\r
- } else {\r
- testContent.setComponentError(null);\r
- }\r
- }\r
- });\r
- actions.addComponent(b);\r
- \r
- b = new Button("Change table caption", new Button.ClickListener() {\r
- public void buttonClick(ClickEvent event) {\r
- t.setCaption(t.getCaption() + "*");\r
- }\r
- });\r
- actions.addComponent(b);\r
- \r
- b = new Button("Toggle Table error", new Button.ClickListener() {\r
- public void buttonClick(ClickEvent event) {\r
- if (t.getComponentError() == null) {\r
- t.setComponentError(e);\r
- } else {\r
- t.setComponentError(null);\r
- }\r
- }\r
- });\r
- \r
- actions.addComponent(b);\r
- \r
- for (int i = 0; i < 20; i++) {\r
- Label l = new Label("Test Content");\r
- l.setCaption("Extra tab " + i);\r
- ts.addComponent(l);\r
- }\r
- \r
- main.addComponent(ts);\r
- \r
- }\r
+ package com.vaadin.tests.tickets;
+
+ import com.vaadin.terminal.UserError;
+ import com.vaadin.tests.TestForTablesInitialColumnWidthLogicRendering;
+ import com.vaadin.ui.Button;
+ import com.vaadin.ui.Button.ClickEvent;
+ import com.vaadin.ui.Label;
++import com.vaadin.ui.Root.LegacyWindow;
+ import com.vaadin.ui.TabSheet;
+ import com.vaadin.ui.Table;
+ import com.vaadin.ui.VerticalLayout;
-import com.vaadin.ui.Window;
+
-public class Ticket1969 extends com.vaadin.Application {
++public class Ticket1969 extends com.vaadin.Application.LegacyApplication {
+
+ @Override
+ public void init() {
- final Window main = new Window(getClass().getName().substring(
- getClass().getName().lastIndexOf(".") + 1));
++ final LegacyWindow main = new LegacyWindow(getClass().getName()
++ .substring(getClass().getName().lastIndexOf(".") + 1));
+ setMainWindow(main);
+
+ main.getContent().setSizeFull();
+
+ TabSheet ts = new TabSheet();
+ ts.setSizeFull();
+
+ final Table t = TestForTablesInitialColumnWidthLogicRendering
+ .getTestTable(7, 2000);
+ t.setSizeFull();
+ ts.addTab(t, "Table, scrollins should not flash", null);
+
+ final Label testContent = new Label(
+ "TabSheet by default uses caption, icon, errors etc. from Components. ");
+
+ testContent.setCaption("Introduction to test");
+
+ ts.addTab(testContent);
+
+ final VerticalLayout actions = new VerticalLayout();
+
+ actions.setCaption("Test actions");
+
+ ts.addTab(actions);
+
+ Button b;
+
+ b = new Button(
+ "change introduction caption (should add * to tab name)",
+ new Button.ClickListener() {
+ public void buttonClick(ClickEvent event) {
+ testContent.setCaption(testContent.getCaption() + "*");
+ }
+ });
+ actions.addComponent(b);
+
+ b = new Button("change tab caption (should add * to tab name)",
+ new Button.ClickListener() {
+ public void buttonClick(ClickEvent event) {
+ actions.setCaption(actions.getCaption() + "*");
+ }
+ });
+
+ actions.addComponent(b);
+
+ final UserError e = new UserError("Test error");
+
+ b = new Button("Toggle error", new Button.ClickListener() {
+ public void buttonClick(ClickEvent event) {
+ if (testContent.getComponentError() == null) {
+ testContent.setComponentError(e);
+ } else {
+ testContent.setComponentError(null);
+ }
+ }
+ });
+ actions.addComponent(b);
+
+ b = new Button("Change table caption", new Button.ClickListener() {
+ public void buttonClick(ClickEvent event) {
+ t.setCaption(t.getCaption() + "*");
+ }
+ });
+ actions.addComponent(b);
+
+ b = new Button("Toggle Table error", new Button.ClickListener() {
+ public void buttonClick(ClickEvent event) {
+ if (t.getComponentError() == null) {
+ t.setComponentError(e);
+ } else {
+ t.setComponentError(null);
+ }
+ }
+ });
+
+ actions.addComponent(b);
+
+ for (int i = 0; i < 20; i++) {
+ Label l = new Label("Test Content");
+ l.setCaption("Extra tab " + i);
+ ts.addComponent(l);
+ }
+
+ main.addComponent(ts);
+
+ }
}
- package com.vaadin.tests.tickets;\r
- \r
- import com.vaadin.Application;\r
- import com.vaadin.ui.GridLayout;\r
- import com.vaadin.ui.Label;\r
- import com.vaadin.ui.Root.LegacyWindow;\r
- \r
- public class Ticket1972 extends Application.LegacyApplication {\r
- \r
- @Override\r
- public void init() {\r
- LegacyWindow w = new LegacyWindow(getClass().getName());\r
- setMainWindow(w);\r
- setTheme("tests-ticket");\r
- GridLayout layout = new GridLayout(3, 3);\r
- layout.setStyleName("borders");\r
- layout.addComponent(new Label("1-1"));\r
- layout.space();\r
- layout.space();\r
- layout.addComponent(new Label("2-1"));\r
- layout.space();\r
- layout.space();\r
- layout.addComponent(new Label("3-1"));\r
- layout.space();\r
- layout.addComponent(new Label("3-3"));\r
- \r
- w.setContent(layout);\r
- }\r
- \r
- }\r
+ package com.vaadin.tests.tickets;
+
+ import com.vaadin.Application;
+ import com.vaadin.ui.GridLayout;
+ import com.vaadin.ui.Label;
-import com.vaadin.ui.Window;
++import com.vaadin.ui.Root.LegacyWindow;
+
-public class Ticket1972 extends Application {
++public class Ticket1972 extends Application.LegacyApplication {
+
+ @Override
+ public void init() {
- Window w = new Window(getClass().getName());
++ LegacyWindow w = new LegacyWindow(getClass().getName());
+ setMainWindow(w);
+ setTheme("tests-ticket");
+ GridLayout layout = new GridLayout(3, 3);
+ layout.setStyleName("borders");
+ layout.addComponent(new Label("1-1"));
+ layout.space();
+ layout.space();
+ layout.addComponent(new Label("2-1"));
+ layout.space();
+ layout.space();
+ layout.addComponent(new Label("3-1"));
+ layout.space();
+ layout.addComponent(new Label("3-3"));
+
+ w.setContent(layout);
+ }
+
+ }
- package com.vaadin.tests.tickets;\r
- \r
- import com.vaadin.data.Item;\r
- import com.vaadin.data.util.IndexedContainer;\r
- import com.vaadin.ui.Button;\r
- import com.vaadin.ui.Component;\r
- import com.vaadin.ui.Root.LegacyWindow;\r
- import com.vaadin.ui.Table;\r
- import com.vaadin.ui.VerticalLayout;\r
- \r
- public class Ticket1973 extends com.vaadin.Application.LegacyApplication {\r
- \r
- LegacyWindow main = new LegacyWindow();\r
- Table table = new Table();\r
- \r
- @Override\r
- public void init() {\r
- setMainWindow(main);\r
- \r
- final IndexedContainer container1 = new IndexedContainer();\r
- container1.addContainerProperty("layout", Component.class, null);\r
- \r
- final IndexedContainer container2 = new IndexedContainer();\r
- container2.addContainerProperty("layout", Component.class, null);\r
- \r
- fill(container1, 100, "Testi 1 :");\r
- fill(container2, 100, "Testi 2 :");\r
- \r
- table.setContainerDataSource(container1);\r
- \r
- Button refreshTable = new Button("Change table container");\r
- refreshTable.addListener(new Button.ClickListener() {\r
- public void buttonClick(Button.ClickEvent e) {\r
- table.setContainerDataSource(container2);\r
- table.setContainerDataSource(container1);\r
- }\r
- });\r
- \r
- main.addComponent(table);\r
- main.addComponent(refreshTable);\r
- }\r
- \r
- public void fill(IndexedContainer container, int size, String prefix) {\r
- for (int i = 0; i < size; i++) {\r
- Item item = container.addItem(new Integer(i));\r
- VerticalLayout layout = new VerticalLayout();\r
- layout.addComponent(new Button(prefix + i));\r
- item.getItemProperty("layout").setValue(layout);\r
- }\r
- }\r
+ package com.vaadin.tests.tickets;
+
+ import com.vaadin.data.Item;
+ import com.vaadin.data.util.IndexedContainer;
+ import com.vaadin.ui.Button;
+ import com.vaadin.ui.Component;
++import com.vaadin.ui.Root.LegacyWindow;
+ import com.vaadin.ui.Table;
+ import com.vaadin.ui.VerticalLayout;
-import com.vaadin.ui.Window;
+
-public class Ticket1973 extends com.vaadin.Application {
++public class Ticket1973 extends com.vaadin.Application.LegacyApplication {
+
- Window main = new Window();
++ LegacyWindow main = new LegacyWindow();
+ Table table = new Table();
+
+ @Override
+ public void init() {
+ setMainWindow(main);
+
+ final IndexedContainer container1 = new IndexedContainer();
+ container1.addContainerProperty("layout", Component.class, null);
+
+ final IndexedContainer container2 = new IndexedContainer();
+ container2.addContainerProperty("layout", Component.class, null);
+
+ fill(container1, 100, "Testi 1 :");
+ fill(container2, 100, "Testi 2 :");
+
+ table.setContainerDataSource(container1);
+
+ Button refreshTable = new Button("Change table container");
+ refreshTable.addListener(new Button.ClickListener() {
+ public void buttonClick(Button.ClickEvent e) {
+ table.setContainerDataSource(container2);
+ table.setContainerDataSource(container1);
+ }
+ });
+
+ main.addComponent(table);
+ main.addComponent(refreshTable);
+ }
+
+ public void fill(IndexedContainer container, int size, String prefix) {
+ for (int i = 0; i < size; i++) {
+ Item item = container.addItem(new Integer(i));
+ VerticalLayout layout = new VerticalLayout();
+ layout.addComponent(new Button(prefix + i));
+ item.getItemProperty("layout").setValue(layout);
+ }
+ }
}
- package com.vaadin.tests.tickets;\r
- \r
- import java.io.ByteArrayInputStream;\r
- import java.io.File;\r
- import java.io.FileInputStream;\r
- \r
- import com.vaadin.Application;\r
- import com.vaadin.terminal.gwt.server.WebApplicationContext;\r
- import com.vaadin.ui.Button;\r
- import com.vaadin.ui.Button.ClickEvent;\r
- import com.vaadin.ui.Button.ClickListener;\r
- import com.vaadin.ui.CustomLayout;\r
- import com.vaadin.ui.GridLayout;\r
- import com.vaadin.ui.Root.LegacyWindow;\r
- \r
- public class Ticket1975 extends Application.LegacyApplication {\r
- \r
- private CustomLayout cl1;\r
- private CustomLayout cl2;\r
- \r
- @Override\r
- public void init() {\r
- LegacyWindow w = new LegacyWindow(getClass().getName());\r
- setMainWindow(w);\r
- setTheme("tests-tickets");\r
- GridLayout layout = new GridLayout(1, 10);\r
- w.setContent(layout);\r
- createUI(layout);\r
- }\r
- \r
- private void createUI(GridLayout layout) {\r
- String s = "<b>Blah</b><input type=\"text\" value='Lorem\" ipsum'/>";\r
- try {\r
- cl1 = new CustomLayout(new ByteArrayInputStream(s.getBytes()));\r
- layout.addComponent(cl1);\r
- WebApplicationContext wc = ((WebApplicationContext) getContext());\r
- \r
- layout.addComponent(new Button("Disable/Enable",\r
- new ClickListener() {\r
- \r
- public void buttonClick(ClickEvent event) {\r
- boolean e = cl1.isEnabled();\r
- \r
- cl1.setEnabled(!e);\r
- cl2.setEnabled(!e);\r
- }\r
- \r
- }));\r
- File f = new File(wc.getBaseDirectory().getAbsoluteFile()\r
- + "/VAADIN/themes/" + getTheme()\r
- + "/layouts/Ticket1975.html");\r
- \r
- cl2 = new CustomLayout(new FileInputStream(f));\r
- layout.addComponent(cl2);\r
- \r
- } catch (Exception e) {\r
- // TODO Auto-generated catch block\r
- e.printStackTrace();\r
- }\r
- \r
- }\r
- }\r
+ package com.vaadin.tests.tickets;
+
+ import java.io.ByteArrayInputStream;
+ import java.io.File;
+ import java.io.FileInputStream;
+
+ import com.vaadin.Application;
+ import com.vaadin.terminal.gwt.server.WebApplicationContext;
+ import com.vaadin.ui.Button;
+ import com.vaadin.ui.Button.ClickEvent;
+ import com.vaadin.ui.Button.ClickListener;
+ import com.vaadin.ui.CustomLayout;
+ import com.vaadin.ui.GridLayout;
-import com.vaadin.ui.Window;
++import com.vaadin.ui.Root.LegacyWindow;
+
-public class Ticket1975 extends Application {
++public class Ticket1975 extends Application.LegacyApplication {
+
+ private CustomLayout cl1;
+ private CustomLayout cl2;
+
+ @Override
+ public void init() {
- Window w = new Window(getClass().getName());
++ LegacyWindow w = new LegacyWindow(getClass().getName());
+ setMainWindow(w);
+ setTheme("tests-tickets");
+ GridLayout layout = new GridLayout(1, 10);
+ w.setContent(layout);
+ createUI(layout);
+ }
+
+ private void createUI(GridLayout layout) {
+ String s = "<b>Blah</b><input type=\"text\" value='Lorem\" ipsum'/>";
+ try {
+ cl1 = new CustomLayout(new ByteArrayInputStream(s.getBytes()));
+ layout.addComponent(cl1);
+ WebApplicationContext wc = ((WebApplicationContext) getContext());
+
+ layout.addComponent(new Button("Disable/Enable",
+ new ClickListener() {
+
+ public void buttonClick(ClickEvent event) {
+ boolean e = cl1.isEnabled();
+
+ cl1.setEnabled(!e);
+ cl2.setEnabled(!e);
+ }
+
+ }));
+ File f = new File(wc.getBaseDirectory().getAbsoluteFile()
+ + "/VAADIN/themes/" + getTheme()
+ + "/layouts/Ticket1975.html");
+
+ cl2 = new CustomLayout(new FileInputStream(f));
+ layout.addComponent(cl2);
+
+ } catch (Exception e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+
+ }
+ }
- package com.vaadin.tests.tickets;\r
- \r
- import com.vaadin.Application;\r
- import com.vaadin.ui.Button;\r
- import com.vaadin.ui.ComboBox;\r
- import com.vaadin.ui.DateField;\r
- import com.vaadin.ui.GridLayout;\r
- import com.vaadin.ui.ListSelect;\r
- import com.vaadin.ui.NativeSelect;\r
- import com.vaadin.ui.OptionGroup;\r
- import com.vaadin.ui.Root.LegacyWindow;\r
- import com.vaadin.ui.TextField;\r
- import com.vaadin.ui.TwinColSelect;\r
- \r
- public class Ticket1986 extends Application.LegacyApplication {\r
- \r
- @Override\r
- public void init() {\r
- LegacyWindow w = new LegacyWindow(getClass().getName());\r
- setMainWindow(w);\r
- \r
- int index = 1;\r
- \r
- GridLayout layout = new GridLayout(2, 2);\r
- TextField f1 = new TextField("1");\r
- f1.setTabIndex(index++);\r
- TextField f2 = new TextField("2");\r
- f2.setTabIndex(index++);\r
- \r
- DateField f3 = new DateField("3");\r
- f3.setTabIndex(index++);\r
- ComboBox cb = new ComboBox("4");\r
- cb.setTabIndex(index++);\r
- \r
- ListSelect lss = new ListSelect("5");\r
- lss.addItem("foo");\r
- lss.addItem("Bar");\r
- lss.setTabIndex(index++);\r
- \r
- NativeSelect ns = new NativeSelect("6");\r
- ns.addItem("foo");\r
- ns.addItem("bar");\r
- ns.setTabIndex(index++);\r
- \r
- OptionGroup og = new OptionGroup("7");\r
- og.addItem("foo");\r
- og.addItem("bar");\r
- og.setTabIndex(index++);\r
- \r
- OptionGroup ogm = new OptionGroup("7");\r
- ogm.setMultiSelect(true);\r
- ogm.addItem("foo");\r
- ogm.addItem("bar");\r
- ogm.setTabIndex(index++);\r
- \r
- TwinColSelect ts = new TwinColSelect("8");\r
- ts.addItem("Foo");\r
- ts.addItem("Bar");\r
- ts.setTabIndex(index++);\r
- \r
- Button b = new Button("9");\r
- b.setTabIndex(index++);\r
- \r
- layout.addComponent(b);\r
- layout.addComponent(ts);\r
- layout.addComponent(ogm);\r
- layout.addComponent(og);\r
- layout.addComponent(ns);\r
- layout.addComponent(lss);\r
- layout.addComponent(cb);\r
- layout.addComponent(f3);\r
- layout.addComponent(f2);\r
- layout.addComponent(f1);\r
- \r
- w.setContent(layout);\r
- \r
- }\r
- \r
- }\r
+ package com.vaadin.tests.tickets;
+
+ import com.vaadin.Application;
+ import com.vaadin.ui.Button;
+ import com.vaadin.ui.ComboBox;
+ import com.vaadin.ui.DateField;
+ import com.vaadin.ui.GridLayout;
+ import com.vaadin.ui.ListSelect;
+ import com.vaadin.ui.NativeSelect;
+ import com.vaadin.ui.OptionGroup;
++import com.vaadin.ui.Root.LegacyWindow;
+ import com.vaadin.ui.TextField;
+ import com.vaadin.ui.TwinColSelect;
-import com.vaadin.ui.Window;
+
-public class Ticket1986 extends Application {
++public class Ticket1986 extends Application.LegacyApplication {
+
+ @Override
+ public void init() {
- Window w = new Window(getClass().getName());
++ LegacyWindow w = new LegacyWindow(getClass().getName());
+ setMainWindow(w);
+
+ int index = 1;
+
+ GridLayout layout = new GridLayout(2, 2);
+ TextField f1 = new TextField("1");
+ f1.setTabIndex(index++);
+ TextField f2 = new TextField("2");
+ f2.setTabIndex(index++);
+
+ DateField f3 = new DateField("3");
+ f3.setTabIndex(index++);
+ ComboBox cb = new ComboBox("4");
+ cb.setTabIndex(index++);
+
+ ListSelect lss = new ListSelect("5");
+ lss.addItem("foo");
+ lss.addItem("Bar");
+ lss.setTabIndex(index++);
+
+ NativeSelect ns = new NativeSelect("6");
+ ns.addItem("foo");
+ ns.addItem("bar");
+ ns.setTabIndex(index++);
+
+ OptionGroup og = new OptionGroup("7");
+ og.addItem("foo");
+ og.addItem("bar");
+ og.setTabIndex(index++);
+
+ OptionGroup ogm = new OptionGroup("7");
+ ogm.setMultiSelect(true);
+ ogm.addItem("foo");
+ ogm.addItem("bar");
+ ogm.setTabIndex(index++);
+
+ TwinColSelect ts = new TwinColSelect("8");
+ ts.addItem("Foo");
+ ts.addItem("Bar");
+ ts.setTabIndex(index++);
+
+ Button b = new Button("9");
+ b.setTabIndex(index++);
+
+ layout.addComponent(b);
+ layout.addComponent(ts);
+ layout.addComponent(ogm);
+ layout.addComponent(og);
+ layout.addComponent(ns);
+ layout.addComponent(lss);
+ layout.addComponent(cb);
+ layout.addComponent(f3);
+ layout.addComponent(f2);
+ layout.addComponent(f1);
+
+ w.setContent(layout);
+
+ }
+
+ }
- package com.vaadin.tests.tickets;\r
- \r
- import com.vaadin.ui.CheckBox;\r
- import com.vaadin.ui.Root.LegacyWindow;\r
- import com.vaadin.ui.Table;\r
- \r
- public class Ticket1991 extends com.vaadin.Application.LegacyApplication {\r
- \r
- @Override\r
- public void init() {\r
- final LegacyWindow main = new LegacyWindow(getClass().getName()\r
- .substring(getClass().getName().lastIndexOf(".") + 1));\r
- setMainWindow(main);\r
- \r
- Table t = new Table("Test table");\r
- \r
- t.addContainerProperty(" ", CheckBox.class, "");\r
- t.addContainerProperty("Col1", String.class, "");\r
- t.addContainerProperty("Col2", String.class, "");\r
- \r
- t.setPageLength(5);\r
- \r
- t.addItem(new Object[] { new CheckBox(), "Foo", "Bar" }, "1");\r
- t.addItem(new Object[] { new CheckBox(), "Foo", "Bar" }, "2");\r
- \r
- main.addComponent(t);\r
- }\r
+ package com.vaadin.tests.tickets;
+
+ import com.vaadin.ui.CheckBox;
++import com.vaadin.ui.Root.LegacyWindow;
+ import com.vaadin.ui.Table;
-import com.vaadin.ui.Window;
+
-public class Ticket1991 extends com.vaadin.Application {
++public class Ticket1991 extends com.vaadin.Application.LegacyApplication {
+
+ @Override
+ public void init() {
- final Window main = new Window(getClass().getName().substring(
- getClass().getName().lastIndexOf(".") + 1));
++ final LegacyWindow main = new LegacyWindow(getClass().getName()
++ .substring(getClass().getName().lastIndexOf(".") + 1));
+ setMainWindow(main);
+
+ Table t = new Table("Test table");
+
+ t.addContainerProperty(" ", CheckBox.class, "");
+ t.addContainerProperty("Col1", String.class, "");
+ t.addContainerProperty("Col2", String.class, "");
+
+ t.setPageLength(5);
+
+ t.addItem(new Object[] { new CheckBox(), "Foo", "Bar" }, "1");
+ t.addItem(new Object[] { new CheckBox(), "Foo", "Bar" }, "2");
+
+ main.addComponent(t);
+ }
}
- package com.vaadin.tests.tickets;\r
- \r
- import com.vaadin.Application;\r
- import com.vaadin.data.Container;\r
- import com.vaadin.data.Container.Filterable;\r
- import com.vaadin.data.Item;\r
- import com.vaadin.data.util.filter.SimpleStringFilter;\r
- import com.vaadin.ui.Button;\r
- import com.vaadin.ui.Button.ClickEvent;\r
- import com.vaadin.ui.Root.LegacyWindow;\r
- import com.vaadin.ui.Table;\r
- \r
- public class Ticket1995 extends Application.LegacyApplication {\r
- \r
- private static final Object PROPERTY_1 = "Test";\r
- private Table table;\r
- \r
- @Override\r
- public void init() {\r
- final LegacyWindow mainWin = new LegacyWindow(getClass().getName());\r
- setMainWindow(mainWin);\r
- \r
- table = new Table();\r
- table.addContainerProperty(PROPERTY_1, String.class, "");\r
- table.setPageLength(4);\r
- \r
- Item item = table.addItem("1");\r
- item.getItemProperty(PROPERTY_1).setValue("Row 1");\r
- item = table.addItem("2");\r
- item.getItemProperty(PROPERTY_1).setValue("Row 2");\r
- \r
- Filterable filterable = (Container.Filterable) table\r
- .getContainerDataSource();\r
- filterable.addContainerFilter(new SimpleStringFilter(PROPERTY_1, "Row",\r
- true, false));\r
- \r
- table.setColumnHeader(PROPERTY_1, "Test (filter: Row)");\r
- \r
- mainWin.addComponent(table);\r
- mainWin.addComponent(new Button("Add item",\r
- new com.vaadin.ui.Button.ClickListener() {\r
- \r
- public void buttonClick(ClickEvent event) {\r
- addItem();\r
- }\r
- }));\r
- }\r
- \r
- protected void addItem() {\r
- Filterable filterable = (Container.Filterable) table\r
- .getContainerDataSource();\r
- \r
- Item i = table.addItem("abc");\r
- String res = "";\r
- if (i == null) {\r
- res = "FAILED";\r
- } else {\r
- res = "OK!";\r
- }\r
- \r
- getMainWindow().showNotification("Tried to add item 'abc', " + res);\r
- \r
- filterable.addContainerFilter(new SimpleStringFilter(PROPERTY_1, "Row",\r
- true, false));\r
- \r
- }\r
- }\r
+ package com.vaadin.tests.tickets;
+
+ import com.vaadin.Application;
+ import com.vaadin.data.Container;
+ import com.vaadin.data.Container.Filterable;
+ import com.vaadin.data.Item;
+ import com.vaadin.data.util.filter.SimpleStringFilter;
+ import com.vaadin.ui.Button;
+ import com.vaadin.ui.Button.ClickEvent;
++import com.vaadin.ui.Root.LegacyWindow;
+ import com.vaadin.ui.Table;
-import com.vaadin.ui.Window;
+
-public class Ticket1995 extends Application {
++public class Ticket1995 extends Application.LegacyApplication {
+
+ private static final Object PROPERTY_1 = "Test";
+ private Table table;
+
+ @Override
+ public void init() {
- final Window mainWin = new Window(getClass().getName());
++ final LegacyWindow mainWin = new LegacyWindow(getClass().getName());
+ setMainWindow(mainWin);
+
+ table = new Table();
+ table.addContainerProperty(PROPERTY_1, String.class, "");
+ table.setPageLength(4);
+
+ Item item = table.addItem("1");
+ item.getItemProperty(PROPERTY_1).setValue("Row 1");
+ item = table.addItem("2");
+ item.getItemProperty(PROPERTY_1).setValue("Row 2");
+
+ Filterable filterable = (Container.Filterable) table
+ .getContainerDataSource();
+ filterable.addContainerFilter(new SimpleStringFilter(PROPERTY_1, "Row",
+ true, false));
+
+ table.setColumnHeader(PROPERTY_1, "Test (filter: Row)");
+
+ mainWin.addComponent(table);
+ mainWin.addComponent(new Button("Add item",
+ new com.vaadin.ui.Button.ClickListener() {
+
+ public void buttonClick(ClickEvent event) {
+ addItem();
+ }
+ }));
+ }
+
+ protected void addItem() {
+ Filterable filterable = (Container.Filterable) table
+ .getContainerDataSource();
+
+ Item i = table.addItem("abc");
+ String res = "";
+ if (i == null) {
+ res = "FAILED";
+ } else {
+ res = "OK!";
+ }
+
+ getMainWindow().showNotification("Tried to add item 'abc', " + res);
+
+ filterable.addContainerFilter(new SimpleStringFilter(PROPERTY_1, "Row",
+ true, false));
+
+ }
+ }
- package com.vaadin.tests.tickets;\r
- \r
- import com.vaadin.Application;\r
- import com.vaadin.data.util.MethodProperty;\r
- import com.vaadin.ui.GridLayout;\r
- import com.vaadin.ui.Root.LegacyWindow;\r
- import com.vaadin.ui.TextField;\r
- \r
- public class Ticket2002 extends Application.LegacyApplication {\r
- private Long long1 = new Long(1L);\r
- private Long long2 = new Long(2L);\r
- \r
- public Long getLong1() {\r
- return long1;\r
- }\r
- \r
- public void setLong1(Long long1) {\r
- this.long1 = long1;\r
- }\r
- \r
- public Long getLong2() {\r
- return long2;\r
- }\r
- \r
- public void setLong2(Long long2) {\r
- this.long2 = long2;\r
- }\r
- \r
- @Override\r
- public void init() {\r
- LegacyWindow w = new LegacyWindow(getClass().getName());\r
- setMainWindow(w);\r
- \r
- GridLayout layout = new GridLayout(2, 2);\r
- layout.setSpacing(true);\r
- \r
- TextField f1 = new TextField("Non-immediate/Long text field",\r
- new MethodProperty<Long>(this, "long1"));\r
- f1.setImmediate(false);\r
- f1.setNullSettingAllowed(true);\r
- TextField f2 = new TextField("Immediate/Long text field",\r
- new MethodProperty<Long>(this, "long2"));\r
- f2.setImmediate(true);\r
- f2.setNullSettingAllowed(true);\r
- \r
- layout.addComponent(f1);\r
- layout.addComponent(f2);\r
- \r
- w.setContent(layout);\r
- }\r
- }\r
+ package com.vaadin.tests.tickets;
+
+ import com.vaadin.Application;
+ import com.vaadin.data.util.MethodProperty;
+ import com.vaadin.ui.GridLayout;
++import com.vaadin.ui.Root.LegacyWindow;
+ import com.vaadin.ui.TextField;
-import com.vaadin.ui.Window;
+
-public class Ticket2002 extends Application {
++public class Ticket2002 extends Application.LegacyApplication {
+ private Long long1 = new Long(1L);
+ private Long long2 = new Long(2L);
+
+ public Long getLong1() {
+ return long1;
+ }
+
+ public void setLong1(Long long1) {
+ this.long1 = long1;
+ }
+
+ public Long getLong2() {
+ return long2;
+ }
+
+ public void setLong2(Long long2) {
+ this.long2 = long2;
+ }
+
+ @Override
+ public void init() {
- Window w = new Window(getClass().getName());
++ LegacyWindow w = new LegacyWindow(getClass().getName());
+ setMainWindow(w);
+
+ GridLayout layout = new GridLayout(2, 2);
+ layout.setSpacing(true);
+
+ TextField f1 = new TextField("Non-immediate/Long text field",
+ new MethodProperty<Long>(this, "long1"));
+ f1.setImmediate(false);
+ f1.setNullSettingAllowed(true);
+ TextField f2 = new TextField("Immediate/Long text field",
+ new MethodProperty<Long>(this, "long2"));
+ f2.setImmediate(true);
+ f2.setNullSettingAllowed(true);
+
+ layout.addComponent(f1);
+ layout.addComponent(f2);
+
+ w.setContent(layout);
+ }
+ }
- package com.vaadin.tests.tickets;\r
- \r
- import com.vaadin.data.Container;\r
- import com.vaadin.event.ItemClickEvent;\r
- import com.vaadin.tests.TestForTablesInitialColumnWidthLogicRendering;\r
- import com.vaadin.ui.Button;\r
- import com.vaadin.ui.Button.ClickEvent;\r
- import com.vaadin.ui.HorizontalLayout;\r
- import com.vaadin.ui.Label;\r
- import com.vaadin.ui.Panel;\r
- import com.vaadin.ui.Root.LegacyWindow;\r
- import com.vaadin.ui.Table;\r
- import com.vaadin.ui.TextField;\r
- import com.vaadin.ui.Tree;\r
- import com.vaadin.ui.VerticalLayout;\r
- import com.vaadin.ui.Window;\r
- \r
- public class Ticket2009 extends com.vaadin.Application.LegacyApplication {\r
- \r
- TextField f = new TextField();\r
- \r
- @Override\r
- public void init() {\r
- final LegacyWindow main = new LegacyWindow(getClass().getName()\r
- .substring(getClass().getName().lastIndexOf(".") + 1));\r
- setMainWindow(main);\r
- \r
- HorizontalLayout ol = new HorizontalLayout();\r
- main.setContent(ol);\r
- ol.setSizeFull();\r
- \r
- Panel p = new Panel("Tree test");\r
- p.setSizeFull();\r
- \r
- Tree t = new Tree();\r
- \r
- t.addItem("Foo");\r
- t.addItem("Bar");\r
- \r
- final VerticalLayout events = new VerticalLayout();\r
- \r
- t.addListener(new ItemClickEvent.ItemClickListener() {\r
- public void itemClick(ItemClickEvent event) {\r
- events.addComponent(new Label(new Label("Click:"\r
- + (event.isDoubleClick() ? "double" : "single")\r
- + " button:" + event.getButton() + " propertyId:"\r
- + event.getPropertyId() + " itemID:"\r
- + event.getItemId() + " item:" + event.getItem())));\r
- \r
- }\r
- });\r
- \r
- main.addComponent(p);\r
- p.addComponent(t);\r
- p.addComponent(events);\r
- \r
- Panel p2 = new Panel("Table test (try dbl click also)");\r
- p2.setSizeFull();\r
- \r
- final VerticalLayout events2 = new VerticalLayout();\r
- Table table = TestForTablesInitialColumnWidthLogicRendering\r
- .getTestTable(5, 100);\r
- table.setRowHeaderMode(Table.ROW_HEADER_MODE_ID);\r
- table.addListener(new ItemClickEvent.ItemClickListener() {\r
- public void itemClick(ItemClickEvent event) {\r
- events2.addComponent(new Label("Click:"\r
- + (event.isDoubleClick() ? "double" : "single")\r
- + " button:" + event.getButton() + " propertyId:"\r
- + event.getPropertyId() + " itemID:"\r
- + event.getItemId() + " item:" + event.getItem()));\r
- if (event.isDoubleClick()) {\r
- new PropertyEditor(event);\r
- }\r
- \r
- }\r
- });\r
- p2.addComponent(table);\r
- p2.addComponent(events2);\r
- \r
- main.addComponent(p2);\r
- \r
- }\r
- \r
- class PropertyEditor extends Window {\r
- \r
- private static final int W = 300;\r
- private static final int H = 150;\r
- \r
- private Container c;\r
- private Object itemid;\r
- private Object propertyid;\r
- \r
- TextField editor = new TextField();\r
- Button done = new Button("Done");\r
- \r
- PropertyEditor(ItemClickEvent event) {\r
- c = (Container) event.getSource();\r
- \r
- propertyid = event.getPropertyId();\r
- itemid = event.getItemId();\r
- \r
- setCaption("Editing " + itemid + " : " + propertyid);\r
- \r
- editor.setPropertyDataSource(c.getContainerProperty(itemid,\r
- propertyid));\r
- addComponent(editor);\r
- addComponent(done);\r
- \r
- setWidth(W + "px");\r
- setHeight(H + "px");\r
- \r
- setPositionX(event.getClientX() - W / 2);\r
- setPositionY(event.getClientY() - H / 2);\r
- \r
- getMainWindow().addWindow(this);\r
- \r
- done.addListener(new Button.ClickListener() {\r
- public void buttonClick(ClickEvent event) {\r
- getMainWindow().removeWindow(PropertyEditor.this);\r
- }\r
- });\r
- \r
- }\r
- \r
- }\r
- \r
+ package com.vaadin.tests.tickets;
+
+ import com.vaadin.data.Container;
+ import com.vaadin.event.ItemClickEvent;
+ import com.vaadin.tests.TestForTablesInitialColumnWidthLogicRendering;
+ import com.vaadin.ui.Button;
+ import com.vaadin.ui.Button.ClickEvent;
+ import com.vaadin.ui.HorizontalLayout;
+ import com.vaadin.ui.Label;
+ import com.vaadin.ui.Panel;
++import com.vaadin.ui.Root.LegacyWindow;
+ import com.vaadin.ui.Table;
+ import com.vaadin.ui.TextField;
+ import com.vaadin.ui.Tree;
+ import com.vaadin.ui.VerticalLayout;
+ import com.vaadin.ui.Window;
+
-public class Ticket2009 extends com.vaadin.Application {
++public class Ticket2009 extends com.vaadin.Application.LegacyApplication {
+
+ TextField f = new TextField();
+
+ @Override
+ public void init() {
- final Window main = new Window(getClass().getName().substring(
- getClass().getName().lastIndexOf(".") + 1));
++ final LegacyWindow main = new LegacyWindow(getClass().getName()
++ .substring(getClass().getName().lastIndexOf(".") + 1));
+ setMainWindow(main);
+
+ HorizontalLayout ol = new HorizontalLayout();
+ main.setContent(ol);
+ ol.setSizeFull();
+
+ Panel p = new Panel("Tree test");
+ p.setSizeFull();
+
+ Tree t = new Tree();
+
+ t.addItem("Foo");
+ t.addItem("Bar");
+
+ final VerticalLayout events = new VerticalLayout();
+
+ t.addListener(new ItemClickEvent.ItemClickListener() {
+ public void itemClick(ItemClickEvent event) {
+ events.addComponent(new Label(new Label("Click:"
+ + (event.isDoubleClick() ? "double" : "single")
+ + " button:" + event.getButton() + " propertyId:"
+ + event.getPropertyId() + " itemID:"
+ + event.getItemId() + " item:" + event.getItem())));
+
+ }
+ });
+
+ main.addComponent(p);
+ p.addComponent(t);
+ p.addComponent(events);
+
+ Panel p2 = new Panel("Table test (try dbl click also)");
+ p2.setSizeFull();
+
+ final VerticalLayout events2 = new VerticalLayout();
+ Table table = TestForTablesInitialColumnWidthLogicRendering
+ .getTestTable(5, 100);
+ table.setRowHeaderMode(Table.ROW_HEADER_MODE_ID);
+ table.addListener(new ItemClickEvent.ItemClickListener() {
+ public void itemClick(ItemClickEvent event) {
+ events2.addComponent(new Label("Click:"
+ + (event.isDoubleClick() ? "double" : "single")
+ + " button:" + event.getButton() + " propertyId:"
+ + event.getPropertyId() + " itemID:"
+ + event.getItemId() + " item:" + event.getItem()));
+ if (event.isDoubleClick()) {
+ new PropertyEditor(event);
+ }
+
+ }
+ });
+ p2.addComponent(table);
+ p2.addComponent(events2);
+
+ main.addComponent(p2);
+
+ }
+
+ class PropertyEditor extends Window {
+
+ private static final int W = 300;
+ private static final int H = 150;
+
+ private Container c;
+ private Object itemid;
+ private Object propertyid;
+
+ TextField editor = new TextField();
+ Button done = new Button("Done");
+
+ PropertyEditor(ItemClickEvent event) {
+ c = (Container) event.getSource();
+
+ propertyid = event.getPropertyId();
+ itemid = event.getItemId();
+
+ setCaption("Editing " + itemid + " : " + propertyid);
+
+ editor.setPropertyDataSource(c.getContainerProperty(itemid,
+ propertyid));
+ addComponent(editor);
+ addComponent(done);
+
+ setWidth(W + "px");
+ setHeight(H + "px");
+
+ setPositionX(event.getClientX() - W / 2);
+ setPositionY(event.getClientY() - H / 2);
+
+ getMainWindow().addWindow(this);
+
+ done.addListener(new Button.ClickListener() {
+ public void buttonClick(ClickEvent event) {
+ getMainWindow().removeWindow(PropertyEditor.this);
+ }
+ });
+
+ }
+
+ }
+
}
- package com.vaadin.tests.tickets;\r
- \r
- import com.vaadin.Application;\r
- import com.vaadin.ui.GridLayout;\r
- import com.vaadin.ui.Root.LegacyWindow;\r
- import com.vaadin.ui.Select;\r
- \r
- public class Ticket2011 extends Application.LegacyApplication {\r
- \r
- @Override\r
- public void init() {\r
- LegacyWindow w = new LegacyWindow(getClass().getName());\r
- setMainWindow(w);\r
- // setTheme("tests-ticket");\r
- GridLayout layout = new GridLayout(10, 10);\r
- w.setContent(layout);\r
- createUI(layout);\r
- }\r
- \r
- private void createUI(GridLayout layout) {\r
- Select s = new Select("Select");\r
- s.addItem("Item 1");\r
- s.addItem("Item 2");\r
- layout.addComponent(s);\r
- }\r
- }\r
+ package com.vaadin.tests.tickets;
+
+ import com.vaadin.Application;
+ import com.vaadin.ui.GridLayout;
++import com.vaadin.ui.Root.LegacyWindow;
+ import com.vaadin.ui.Select;
-import com.vaadin.ui.Window;
+
-public class Ticket2011 extends Application {
++public class Ticket2011 extends Application.LegacyApplication {
+
+ @Override
+ public void init() {
- Window w = new Window(getClass().getName());
++ LegacyWindow w = new LegacyWindow(getClass().getName());
+ setMainWindow(w);
+ // setTheme("tests-ticket");
+ GridLayout layout = new GridLayout(10, 10);
+ w.setContent(layout);
+ createUI(layout);
+ }
+
+ private void createUI(GridLayout layout) {
+ Select s = new Select("Select");
+ s.addItem("Item 1");
+ s.addItem("Item 2");
+ layout.addComponent(s);
+ }
+ }
- package com.vaadin.tests.tickets;\r
- \r
- import java.util.UUID;\r
- \r
- import com.vaadin.Application;\r
- import com.vaadin.ui.Button;\r
- import com.vaadin.ui.Button.ClickEvent;\r
- import com.vaadin.ui.Button.ClickListener;\r
- import com.vaadin.ui.GridLayout;\r
- import com.vaadin.ui.HorizontalLayout;\r
- import com.vaadin.ui.Panel;\r
- import com.vaadin.ui.Root.LegacyWindow;\r
- \r
- public class Ticket2014 extends Application.LegacyApplication {\r
- \r
- private HorizontalLayout innerLayout1;\r
- private Button b1;\r
- private Panel panel;\r
- \r
- @Override\r
- public void init() {\r
- LegacyWindow w = new LegacyWindow(getClass().getName());\r
- setMainWindow(w);\r
- // setTheme("tests-ticket");\r
- GridLayout layout = new GridLayout(10, 10);\r
- w.setContent(layout);\r
- createUI(layout);\r
- }\r
- \r
- private void createUI(GridLayout layout) {\r
- createPanel(layout);\r
- \r
- layout.addComponent(new Button("Change class name",\r
- new ClickListener() {\r
- \r
- public void buttonClick(ClickEvent event) {\r
- b1.setStyleName(UUID.randomUUID().toString());\r
- }\r
- \r
- }));\r
- \r
- }\r
- \r
- private void createPanel(GridLayout layout) {\r
- panel = new Panel("panel caption");\r
- layout.addComponent(panel);\r
- \r
- innerLayout1 = new HorizontalLayout();\r
- innerLayout1.setSpacing(true);\r
- panel.addComponent(innerLayout1);\r
- \r
- b1 = new Button("Button inside orderedLayout", new ClickListener() {\r
- \r
- public void buttonClick(ClickEvent event) {\r
- System.out.println("Clicked " + event.getButton().getCaption());\r
- }\r
- \r
- });\r
- \r
- innerLayout1.addComponent(b1);\r
- \r
- }\r
- }\r
+ package com.vaadin.tests.tickets;
+
+ import java.util.UUID;
+
+ import com.vaadin.Application;
+ import com.vaadin.ui.Button;
+ import com.vaadin.ui.Button.ClickEvent;
+ import com.vaadin.ui.Button.ClickListener;
+ import com.vaadin.ui.GridLayout;
+ import com.vaadin.ui.HorizontalLayout;
+ import com.vaadin.ui.Panel;
-import com.vaadin.ui.Window;
++import com.vaadin.ui.Root.LegacyWindow;
+
-public class Ticket2014 extends Application {
++public class Ticket2014 extends Application.LegacyApplication {
+
+ private HorizontalLayout innerLayout1;
+ private Button b1;
+ private Panel panel;
+
+ @Override
+ public void init() {
- Window w = new Window(getClass().getName());
++ LegacyWindow w = new LegacyWindow(getClass().getName());
+ setMainWindow(w);
+ // setTheme("tests-ticket");
+ GridLayout layout = new GridLayout(10, 10);
+ w.setContent(layout);
+ createUI(layout);
+ }
+
+ private void createUI(GridLayout layout) {
+ createPanel(layout);
+
+ layout.addComponent(new Button("Change class name",
+ new ClickListener() {
+
+ public void buttonClick(ClickEvent event) {
+ b1.setStyleName(UUID.randomUUID().toString());
+ }
+
+ }));
+
+ }
+
+ private void createPanel(GridLayout layout) {
+ panel = new Panel("panel caption");
+ layout.addComponent(panel);
+
+ innerLayout1 = new HorizontalLayout();
+ innerLayout1.setSpacing(true);
+ panel.addComponent(innerLayout1);
+
+ b1 = new Button("Button inside orderedLayout", new ClickListener() {
+
+ public void buttonClick(ClickEvent event) {
+ System.out.println("Clicked " + event.getButton().getCaption());
+ }
+
+ });
+
+ innerLayout1.addComponent(b1);
+
+ }
+ }
- package com.vaadin.tests.tickets;\r
- \r
- import com.vaadin.Application;\r
- import com.vaadin.ui.AbstractComponent;\r
- import com.vaadin.ui.AbstractOrderedLayout;\r
- import com.vaadin.ui.Button;\r
- import com.vaadin.ui.Button.ClickEvent;\r
- import com.vaadin.ui.Button.ClickListener;\r
- import com.vaadin.ui.GridLayout;\r
- import com.vaadin.ui.Label;\r
- import com.vaadin.ui.Layout;\r
- import com.vaadin.ui.Panel;\r
- import com.vaadin.ui.Root.LegacyWindow;\r
- import com.vaadin.ui.TextArea;\r
- import com.vaadin.ui.VerticalLayout;\r
- \r
- public class Ticket2021 extends Application.LegacyApplication {\r
- \r
- private TextArea tf1, tf2, tf3;\r
- \r
- private String contents = "This TextField SHOULD FILL the panel and NOT CAUSE any scrollbars to appear in the Panel. Scrollbars SHOULD appear in the TextField AND the whole scrollbars (includinc arrow down) SHOULD be visible.\n\n"\r
- + ""\r
- + "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Praesent quis justo. Vivamus nec mi eu libero convallis auctor. Mauris et arcu. Nunc luctus justo. Aenean convallis, odio in vehicula scelerisque, est magna condimentum pede, a aliquam elit eros vitae diam. Phasellus porttitor convallis tellus. Nullam elementum, ligula nec viverra malesuada, risus tortor bibendum dui, eget hendrerit sem enim at massa. Nam eu pede sed nulla congue fermentum. Vestibulum malesuada libero non nunc. Proin rutrum. Fusce erat pede, volutpat vitae, aliquam ut, sagittis vel, augue. Fusce dui pede, convallis nec, accumsan tincidunt, consectetuer ac, purus. Nulla facilisi. Ut nisi. Sed orci risus, lacinia eu, sodales molestie, gravida quis, neque. Vestibulum pharetra ornare elit. Nulla porttitor molestie mauris. Morbi fringilla tellus sed risus. Curabitur varius massa."\r
- + "Nulla nisi. Sed blandit, ante vitae sagittis volutpat, arcu mauris vehicula risus, vitae posuere felis lectus sit amet purus. Donec nec magna et leo eleifend scelerisque. Suspendisse condimentum pharetra ligula. Curabitur lorem. Pellentesque a augue sit amet enim fermentum placerat. Phasellus ante risus, molestie at, iaculis at, pellentesque non, tellus. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Phasellus non urna eget risus tempus imperdiet. Integer est diam, sagittis sit amet, posuere sit amet, bibendum sed, lacus. Aenean adipiscing cursus ipsum. Quisque at elit. Vestibulum vitae nunc. Praesent placerat metus viverra lorem. Cras nec elit congue nisi faucibus feugiat. Nam eget mi. Vestibulum condimentum. Nunc nisl ante, cursus in, dictum ac, lobortis rutrum, mi. Nulla eu nisi. In ultricies vehicula magna."\r
- + "Nunc eros dui, elementum at, ullamcorper eget, varius at, velit. Ut dictum. Cras ullamcorper ante vel tortor. Quisque viverra mauris vulputate quam. Nulla dui. Suspendisse non eros at ipsum faucibus hendrerit. Morbi dignissim pharetra tortor. Etiam malesuada. Mauris lacinia elementum erat. Duis mollis placerat metus. Nunc risus felis, cursus ac, cursus vel, convallis vel, metus. Ut vehicula nibh et nulla. Vivamus id pede. Quisque egestas arcu a ligula. Maecenas vehicula. Quisque sed ligula quis tellus tempus rutrum. Curabitur vel augue sed orci egestas pharetra. Duis pharetra.";\r
- \r
- @Override\r
- public void init() {\r
- LegacyWindow w = new LegacyWindow(getClass().getSimpleName());\r
- w.setContent(new GridLayout(2, 2));\r
- setMainWindow(w);\r
- \r
- Panel p = new Panel();\r
- p.setCaption("ExpandLayout");\r
- p.setWidth("500px");\r
- p.setHeight("500px");\r
- p.setContent(new VerticalLayout());\r
- p.getContent().setSizeFull();\r
- \r
- w.getContent().addComponent(p);\r
- \r
- tf1 = new TextArea();\r
- tf1.setRows(5);\r
- tf1.setSizeFull();\r
- tf1.setValue(contents);\r
- tf1.setCaption("TextField caption");\r
- p.getContent().addComponent(tf1);\r
- \r
- /*\r
- * \r
- * OrderedLayout\r
- */\r
- \r
- Panel p2 = new Panel();\r
- p2.setCaption("OrderedLayout");\r
- p2.setWidth("500px");\r
- p2.setHeight("500px");\r
- p2.setContent(new VerticalLayout());\r
- p2.getContent().setSizeFull();\r
- \r
- w.getContent().addComponent(p2);\r
- \r
- tf2 = new TextArea();\r
- tf2.setRows(5);\r
- tf2.setSizeFull();\r
- tf2.setValue(contents);\r
- tf2.setCaption("TextField caption");\r
- p2.getContent().addComponent(tf2);\r
- \r
- /*\r
- * \r
- * GridLayout\r
- */\r
- \r
- Panel p3 = new Panel();\r
- p3.setCaption("GridLayout");\r
- p3.setWidth("500px");\r
- p3.setHeight("500px");\r
- // p3.setContent(new GridLayout());\r
- p3.getContent().setSizeFull();\r
- ((Layout) p3.getContent()).setMargin(false);\r
- \r
- GridLayout gl = new GridLayout();\r
- gl.setSizeFull();\r
- gl.setMargin(false);\r
- p3.getContent().addComponent(gl);\r
- w.getContent().addComponent(p3);\r
- \r
- tf3 = new TextArea();\r
- tf3.setRows(5);\r
- tf3.setSizeFull();\r
- tf3.setValue(contents);\r
- tf3.setCaption("TextField caption");\r
- // p3.getContent().addComponent(tf3);\r
- gl.addComponent(tf3);\r
- \r
- // Panel pp = new Panel();\r
- // pp.setCaption("OrderedLayout");\r
- // pp.setWidth("500px");\r
- // pp.setHeight("500px");\r
- // pp.getContent().setSizeFull();\r
- // orderedLayout = new VerticalLayout();\r
- // pp.getContent().addComponent(orderedLayout);\r
- // w.getContent().addComponent(pp);\r
- // createUI(orderedLayout);\r
- }\r
- \r
- @SuppressWarnings("unused")\r
- private void createUI(Layout layout) {\r
- Label l = new Label("Label");\r
- Button b = new Button("Enable/disable caption and watch button move",\r
- new ClickListener() {\r
- \r
- public void buttonClick(ClickEvent event) {\r
- System.out.println("Enable/disable caption");\r
- for (AbstractComponent l : new AbstractComponent[] {\r
- tf1, tf2, tf3 }) {\r
- // AbstractComponent l = tf2;\r
- // Layout l = (Layout) event.getButton().getData();\r
- if (l.getCaption() == null) {\r
- l.setCaption("Expand layout caption");\r
- } else {\r
- l.setCaption(null);\r
- }\r
- }\r
- }\r
- \r
- });\r
- b.setData(layout);\r
- Label l2 = new Label("This should always be visible");\r
- \r
- layout.addComponent(l);\r
- layout.addComponent(b);\r
- layout.addComponent(l2);\r
- \r
- if (layout instanceof AbstractOrderedLayout) {\r
- ((AbstractOrderedLayout) layout).setExpandRatio(l, 1);\r
- \r
- }\r
- }\r
- }\r
+ package com.vaadin.tests.tickets;
+
+ import com.vaadin.Application;
+ import com.vaadin.ui.AbstractComponent;
+ import com.vaadin.ui.AbstractOrderedLayout;
+ import com.vaadin.ui.Button;
+ import com.vaadin.ui.Button.ClickEvent;
+ import com.vaadin.ui.Button.ClickListener;
+ import com.vaadin.ui.GridLayout;
+ import com.vaadin.ui.Label;
+ import com.vaadin.ui.Layout;
+ import com.vaadin.ui.Panel;
++import com.vaadin.ui.Root.LegacyWindow;
+ import com.vaadin.ui.TextArea;
+ import com.vaadin.ui.VerticalLayout;
-import com.vaadin.ui.Window;
+
-public class Ticket2021 extends Application {
++public class Ticket2021 extends Application.LegacyApplication {
+
+ private TextArea tf1, tf2, tf3;
+
+ private String contents = "This TextField SHOULD FILL the panel and NOT CAUSE any scrollbars to appear in the Panel. Scrollbars SHOULD appear in the TextField AND the whole scrollbars (includinc arrow down) SHOULD be visible.\n\n"
+ + ""
+ + "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Praesent quis justo. Vivamus nec mi eu libero convallis auctor. Mauris et arcu. Nunc luctus justo. Aenean convallis, odio in vehicula scelerisque, est magna condimentum pede, a aliquam elit eros vitae diam. Phasellus porttitor convallis tellus. Nullam elementum, ligula nec viverra malesuada, risus tortor bibendum dui, eget hendrerit sem enim at massa. Nam eu pede sed nulla congue fermentum. Vestibulum malesuada libero non nunc. Proin rutrum. Fusce erat pede, volutpat vitae, aliquam ut, sagittis vel, augue. Fusce dui pede, convallis nec, accumsan tincidunt, consectetuer ac, purus. Nulla facilisi. Ut nisi. Sed orci risus, lacinia eu, sodales molestie, gravida quis, neque. Vestibulum pharetra ornare elit. Nulla porttitor molestie mauris. Morbi fringilla tellus sed risus. Curabitur varius massa."
+ + "Nulla nisi. Sed blandit, ante vitae sagittis volutpat, arcu mauris vehicula risus, vitae posuere felis lectus sit amet purus. Donec nec magna et leo eleifend scelerisque. Suspendisse condimentum pharetra ligula. Curabitur lorem. Pellentesque a augue sit amet enim fermentum placerat. Phasellus ante risus, molestie at, iaculis at, pellentesque non, tellus. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Phasellus non urna eget risus tempus imperdiet. Integer est diam, sagittis sit amet, posuere sit amet, bibendum sed, lacus. Aenean adipiscing cursus ipsum. Quisque at elit. Vestibulum vitae nunc. Praesent placerat metus viverra lorem. Cras nec elit congue nisi faucibus feugiat. Nam eget mi. Vestibulum condimentum. Nunc nisl ante, cursus in, dictum ac, lobortis rutrum, mi. Nulla eu nisi. In ultricies vehicula magna."
+ + "Nunc eros dui, elementum at, ullamcorper eget, varius at, velit. Ut dictum. Cras ullamcorper ante vel tortor. Quisque viverra mauris vulputate quam. Nulla dui. Suspendisse non eros at ipsum faucibus hendrerit. Morbi dignissim pharetra tortor. Etiam malesuada. Mauris lacinia elementum erat. Duis mollis placerat metus. Nunc risus felis, cursus ac, cursus vel, convallis vel, metus. Ut vehicula nibh et nulla. Vivamus id pede. Quisque egestas arcu a ligula. Maecenas vehicula. Quisque sed ligula quis tellus tempus rutrum. Curabitur vel augue sed orci egestas pharetra. Duis pharetra.";
+
+ @Override
+ public void init() {
- Window w = new Window(getClass().getSimpleName());
++ LegacyWindow w = new LegacyWindow(getClass().getSimpleName());
+ w.setContent(new GridLayout(2, 2));
+ setMainWindow(w);
+
+ Panel p = new Panel();
+ p.setCaption("ExpandLayout");
+ p.setWidth("500px");
+ p.setHeight("500px");
+ p.setContent(new VerticalLayout());
+ p.getContent().setSizeFull();
+
+ w.getContent().addComponent(p);
+
+ tf1 = new TextArea();
+ tf1.setRows(5);
+ tf1.setSizeFull();
+ tf1.setValue(contents);
+ tf1.setCaption("TextField caption");
+ p.getContent().addComponent(tf1);
+
+ /*
+ *
+ * OrderedLayout
+ */
+
+ Panel p2 = new Panel();
+ p2.setCaption("OrderedLayout");
+ p2.setWidth("500px");
+ p2.setHeight("500px");
+ p2.setContent(new VerticalLayout());
+ p2.getContent().setSizeFull();
+
+ w.getContent().addComponent(p2);
+
+ tf2 = new TextArea();
+ tf2.setRows(5);
+ tf2.setSizeFull();
+ tf2.setValue(contents);
+ tf2.setCaption("TextField caption");
+ p2.getContent().addComponent(tf2);
+
+ /*
+ *
+ * GridLayout
+ */
+
+ Panel p3 = new Panel();
+ p3.setCaption("GridLayout");
+ p3.setWidth("500px");
+ p3.setHeight("500px");
+ // p3.setContent(new GridLayout());
+ p3.getContent().setSizeFull();
+ ((Layout) p3.getContent()).setMargin(false);
+
+ GridLayout gl = new GridLayout();
+ gl.setSizeFull();
+ gl.setMargin(false);
+ p3.getContent().addComponent(gl);
+ w.getContent().addComponent(p3);
+
+ tf3 = new TextArea();
+ tf3.setRows(5);
+ tf3.setSizeFull();
+ tf3.setValue(contents);
+ tf3.setCaption("TextField caption");
+ // p3.getContent().addComponent(tf3);
+ gl.addComponent(tf3);
+
+ // Panel pp = new Panel();
+ // pp.setCaption("OrderedLayout");
+ // pp.setWidth("500px");
+ // pp.setHeight("500px");
+ // pp.getContent().setSizeFull();
+ // orderedLayout = new VerticalLayout();
+ // pp.getContent().addComponent(orderedLayout);
+ // w.getContent().addComponent(pp);
+ // createUI(orderedLayout);
+ }
+
+ @SuppressWarnings("unused")
+ private void createUI(Layout layout) {
+ Label l = new Label("Label");
+ Button b = new Button("Enable/disable caption and watch button move",
+ new ClickListener() {
+
+ public void buttonClick(ClickEvent event) {
+ System.out.println("Enable/disable caption");
+ for (AbstractComponent l : new AbstractComponent[] {
+ tf1, tf2, tf3 }) {
+ // AbstractComponent l = tf2;
+ // Layout l = (Layout) event.getButton().getData();
+ if (l.getCaption() == null) {
+ l.setCaption("Expand layout caption");
+ } else {
+ l.setCaption(null);
+ }
+ }
+ }
+
+ });
+ b.setData(layout);
+ Label l2 = new Label("This should always be visible");
+
+ layout.addComponent(l);
+ layout.addComponent(b);
+ layout.addComponent(l2);
+
+ if (layout instanceof AbstractOrderedLayout) {
+ ((AbstractOrderedLayout) layout).setExpandRatio(l, 1);
+
+ }
+ }
+ }
- package com.vaadin.tests.tickets;\r
- \r
- import com.vaadin.Application;\r
- import com.vaadin.ui.CustomLayout;\r
- import com.vaadin.ui.Root.LegacyWindow;\r
- \r
- public class Ticket2022 extends Application.LegacyApplication {\r
- \r
- @Override\r
- public void init() {\r
- LegacyWindow w = new LegacyWindow(getClass().getSimpleName());\r
- setMainWindow(w);\r
- setTheme("tests-tickets");\r
- CustomLayout l;\r
- \r
- // WebApplicationContext wac = ((WebApplicationContext) getContext());\r
- // File f = new File(wac.getBaseDirectory().getAbsoluteFile()\r
- // + "/VAADIN/themes/" + getTheme() + "/layouts/Ticket2022.html");\r
- \r
- l = new CustomLayout("Ticket2022");\r
- // try {\r
- // l = new CustomLayout(new FileInputStream(f));\r
- w.setContent(l);\r
- // } catch (FileNotFoundException e) {\r
- // // TODO Auto-generated catch block\r
- // e.printStackTrace();\r
- // } catch (IOException e) {\r
- // // TODO Auto-generated catch block\r
- // e.printStackTrace();\r
- // }\r
- }\r
- }\r
+ package com.vaadin.tests.tickets;
+
+ import com.vaadin.Application;
+ import com.vaadin.ui.CustomLayout;
-import com.vaadin.ui.Window;
++import com.vaadin.ui.Root.LegacyWindow;
+
-public class Ticket2022 extends Application {
++public class Ticket2022 extends Application.LegacyApplication {
+
+ @Override
+ public void init() {
- Window w = new Window(getClass().getSimpleName());
++ LegacyWindow w = new LegacyWindow(getClass().getSimpleName());
+ setMainWindow(w);
+ setTheme("tests-tickets");
+ CustomLayout l;
+
+ // WebApplicationContext wac = ((WebApplicationContext) getContext());
+ // File f = new File(wac.getBaseDirectory().getAbsoluteFile()
+ // + "/VAADIN/themes/" + getTheme() + "/layouts/Ticket2022.html");
+
+ l = new CustomLayout("Ticket2022");
+ // try {
+ // l = new CustomLayout(new FileInputStream(f));
+ w.setContent(l);
+ // } catch (FileNotFoundException e) {
+ // // TODO Auto-generated catch block
+ // e.printStackTrace();
+ // } catch (IOException e) {
+ // // TODO Auto-generated catch block
+ // e.printStackTrace();
+ // }
+ }
+ }
- package com.vaadin.tests.tickets;\r
- \r
- import com.vaadin.Application;\r
- import com.vaadin.ui.GridLayout;\r
- import com.vaadin.ui.Label;\r
- import com.vaadin.ui.Root.LegacyWindow;\r
- import com.vaadin.ui.TextField;\r
- import com.vaadin.ui.VerticalLayout;\r
- \r
- public class Ticket2024 extends Application.LegacyApplication {\r
- \r
- @Override\r
- public void init() {\r
- LegacyWindow w = new LegacyWindow(getClass().getSimpleName());\r
- setMainWindow(w);\r
- // setTheme("tests-tickets");\r
- GridLayout layout = new GridLayout(2, 2);\r
- layout.setHeight("100%");\r
- layout.setWidth("700");\r
- w.getContent().setSizeFull();\r
- w.getContent().setHeight("2000");\r
- w.getContent().addComponent(layout);\r
- \r
- layout.addComponent(new Label(\r
- "This should NOT get stuck when scrolling down"));\r
- layout.addComponent(new TextField("This should not get stuck either..."));\r
- \r
- VerticalLayout ol = new VerticalLayout();\r
- ol.setHeight("1000");\r
- ol.setWidth("200");\r
- w.getContent().addComponent(ol);\r
- ol.addComponent(new Label("Just a label to enable the scrollbar"));\r
- \r
- }\r
- }\r
+ package com.vaadin.tests.tickets;
+
+ import com.vaadin.Application;
+ import com.vaadin.ui.GridLayout;
+ import com.vaadin.ui.Label;
++import com.vaadin.ui.Root.LegacyWindow;
+ import com.vaadin.ui.TextField;
+ import com.vaadin.ui.VerticalLayout;
-import com.vaadin.ui.Window;
+
-public class Ticket2024 extends Application {
++public class Ticket2024 extends Application.LegacyApplication {
+
+ @Override
+ public void init() {
- Window w = new Window(getClass().getSimpleName());
++ LegacyWindow w = new LegacyWindow(getClass().getSimpleName());
+ setMainWindow(w);
+ // setTheme("tests-tickets");
+ GridLayout layout = new GridLayout(2, 2);
+ layout.setHeight("100%");
+ layout.setWidth("700");
+ w.getContent().setSizeFull();
+ w.getContent().setHeight("2000");
+ w.getContent().addComponent(layout);
+
+ layout.addComponent(new Label(
+ "This should NOT get stuck when scrolling down"));
+ layout.addComponent(new TextField("This should not get stuck either..."));
+
+ VerticalLayout ol = new VerticalLayout();
+ ol.setHeight("1000");
+ ol.setWidth("200");
+ w.getContent().addComponent(ol);
+ ol.addComponent(new Label("Just a label to enable the scrollbar"));
+
+ }
+ }
- package com.vaadin.tests.tickets;\r
- \r
- import com.vaadin.Application;\r
- import com.vaadin.ui.GridLayout;\r
- import com.vaadin.ui.Root.LegacyWindow;\r
- import com.vaadin.ui.TextField;\r
- \r
- public class Ticket2026 extends Application.LegacyApplication {\r
- \r
- @Override\r
- public void init() {\r
- LegacyWindow w = new LegacyWindow(getClass().getSimpleName());\r
- setMainWindow(w);\r
- \r
- GridLayout layout = new GridLayout(2, 2);\r
- layout.setSpacing(true);\r
- \r
- @SuppressWarnings("unused")\r
- int nr = 5;\r
- TextField tf;\r
- tf = new TextField("TextField (tabIndex 1)");\r
- tf.setTabIndex(1);\r
- tf.focus();\r
- layout.addComponent(tf);\r
- layout.addComponent(new TextField("TextField without tab index"));\r
- layout.addComponent(new TextField("TextField without tab index"));\r
- layout.addComponent(new TextField("TextField without tab index"));\r
- layout.addComponent(new TextField("TextField without tab index"));\r
- tf = new TextField("TextField (tabIndex 2)");\r
- tf.setTabIndex(2);\r
- layout.addComponent(tf);\r
- \r
- w.setContent(layout);\r
- }\r
- }\r
+ package com.vaadin.tests.tickets;
+
+ import com.vaadin.Application;
+ import com.vaadin.ui.GridLayout;
++import com.vaadin.ui.Root.LegacyWindow;
+ import com.vaadin.ui.TextField;
-import com.vaadin.ui.Window;
+
-public class Ticket2026 extends Application {
++public class Ticket2026 extends Application.LegacyApplication {
+
+ @Override
+ public void init() {
- Window w = new Window(getClass().getSimpleName());
++ LegacyWindow w = new LegacyWindow(getClass().getSimpleName());
+ setMainWindow(w);
+
+ GridLayout layout = new GridLayout(2, 2);
+ layout.setSpacing(true);
+
+ @SuppressWarnings("unused")
+ int nr = 5;
+ TextField tf;
+ tf = new TextField("TextField (tabIndex 1)");
+ tf.setTabIndex(1);
+ tf.focus();
+ layout.addComponent(tf);
+ layout.addComponent(new TextField("TextField without tab index"));
+ layout.addComponent(new TextField("TextField without tab index"));
+ layout.addComponent(new TextField("TextField without tab index"));
+ layout.addComponent(new TextField("TextField without tab index"));
+ tf = new TextField("TextField (tabIndex 2)");
+ tf.setTabIndex(2);
+ layout.addComponent(tf);
+
+ w.setContent(layout);
+ }
+ }
- package com.vaadin.tests.tickets;\r
- \r
- import java.util.Random;\r
- \r
- import com.vaadin.Application;\r
- import com.vaadin.data.Property.ValueChangeEvent;\r
- import com.vaadin.data.Property.ValueChangeListener;\r
- import com.vaadin.terminal.UserError;\r
- import com.vaadin.ui.Alignment;\r
- import com.vaadin.ui.Component;\r
- import com.vaadin.ui.GridLayout;\r
- import com.vaadin.ui.HorizontalLayout;\r
- import com.vaadin.ui.Panel;\r
- import com.vaadin.ui.Root.LegacyWindow;\r
- import com.vaadin.ui.TextArea;\r
- import com.vaadin.ui.TextField;\r
- import com.vaadin.ui.VerticalLayout;\r
- \r
- public class Ticket2029 extends Application.LegacyApplication {\r
- \r
- int COMPONENTS;\r
- int DIM1, DIM2;\r
- Random r = new Random();\r
- \r
- @Override\r
- public void init() {\r
- COMPONENTS = 5;\r
- DIM1 = 504;\r
- DIM2 = 100;\r
- \r
- LegacyWindow w = new LegacyWindow(getClass().getSimpleName());\r
- setMainWindow(w);\r
- // setTheme("tests-tickets");\r
- Panel p = createPanel();\r
- w.getContent().addComponent(p);\r
- // w.getLayout().addComponent(createGLPanel());\r
- w.getContent().addComponent(createPanelV());\r
- }\r
- \r
- private Panel createPanel() {\r
- Panel p = new Panel(DIM1 + "x" + DIM2 + " OrderedLayout");\r
- p.setWidth(DIM1 + "px");\r
- p.setHeight(DIM2 + "px");\r
- \r
- HorizontalLayout layout = new HorizontalLayout();\r
- p.setContent(layout);\r
- p.getContent().setSizeFull();\r
- \r
- for (int i = 0; i < COMPONENTS; i++) {\r
- TextField tf = new TextField();\r
- if (r.nextBoolean()) {\r
- tf.setCaption("Caption");\r
- }\r
- if (r.nextBoolean()) {\r
- tf.setRequired(true);\r
- }\r
- if (r.nextBoolean()) {\r
- tf.setComponentError(new UserError("Error"));\r
- }\r
- tf.setWidth("100%");\r
- layout.setComponentAlignment(tf, Alignment.BOTTOM_LEFT);\r
- p.addComponent(tf);\r
- \r
- }\r
- \r
- return p;\r
- }\r
- \r
- @SuppressWarnings("unused")\r
- private Panel createGLPanel() {\r
- Panel p = new Panel("" + DIM1 + "x" + DIM2 + " GridLayout");\r
- p.setWidth("" + DIM1 + "px");\r
- p.setHeight("" + DIM2 + "px");\r
- \r
- GridLayout layout = new GridLayout(COMPONENTS, 1);\r
- p.setContent(layout);\r
- p.getContent().setSizeFull();\r
- \r
- for (int i = 0; i < COMPONENTS; i++) {\r
- TextField tf = new TextField();\r
- tf.setImmediate(true);\r
- tf.addListener(new ValueChangeListener() {\r
- \r
- public void valueChange(ValueChangeEvent event) {\r
- Component c = ((Component) event.getProperty());\r
- c.setCaption("askfdj");\r
- \r
- }\r
- });\r
- if (r.nextBoolean()) {\r
- tf.setCaption("Caption");\r
- }\r
- if (r.nextBoolean()) {\r
- tf.setRequired(true);\r
- }\r
- if (r.nextBoolean()) {\r
- tf.setComponentError(new UserError("Error"));\r
- }\r
- tf.setWidth("100%");\r
- layout.setComponentAlignment(tf, Alignment.MIDDLE_LEFT);\r
- p.addComponent(tf);\r
- \r
- }\r
- \r
- return p;\r
- }\r
- \r
- private Panel createPanelV() {\r
- Panel p = new Panel("" + DIM1 + "x" + DIM2 + " OrderedLayout");\r
- p.setWidth("" + DIM2 + "px");\r
- p.setHeight("" + DIM1 + "px");\r
- \r
- VerticalLayout layout = new VerticalLayout();\r
- p.setContent(layout);\r
- p.getContent().setSizeFull();\r
- \r
- for (int i = 0; i < COMPONENTS; i++) {\r
- TextArea tf = new TextArea();\r
- if (r.nextBoolean()) {\r
- tf.setCaption("Caption");\r
- }\r
- if (r.nextBoolean()) {\r
- tf.setRequired(true);\r
- }\r
- if (r.nextBoolean()) {\r
- tf.setComponentError(new UserError("Error"));\r
- }\r
- \r
- tf.setRows(2);\r
- tf.setSizeFull();\r
- \r
- layout.setComponentAlignment(tf, Alignment.BOTTOM_LEFT);\r
- p.addComponent(tf);\r
- \r
- }\r
- \r
- return p;\r
- }\r
- }\r
+ package com.vaadin.tests.tickets;
+
+ import java.util.Random;
+
+ import com.vaadin.Application;
+ import com.vaadin.data.Property.ValueChangeEvent;
+ import com.vaadin.data.Property.ValueChangeListener;
+ import com.vaadin.terminal.UserError;
+ import com.vaadin.ui.Alignment;
+ import com.vaadin.ui.Component;
+ import com.vaadin.ui.GridLayout;
+ import com.vaadin.ui.HorizontalLayout;
+ import com.vaadin.ui.Panel;
++import com.vaadin.ui.Root.LegacyWindow;
+ import com.vaadin.ui.TextArea;
+ import com.vaadin.ui.TextField;
+ import com.vaadin.ui.VerticalLayout;
-import com.vaadin.ui.Window;
+
-public class Ticket2029 extends Application {
++public class Ticket2029 extends Application.LegacyApplication {
+
+ int COMPONENTS;
+ int DIM1, DIM2;
+ Random r = new Random();
+
+ @Override
+ public void init() {
+ COMPONENTS = 5;
+ DIM1 = 504;
+ DIM2 = 100;
+
- Window w = new Window(getClass().getSimpleName());
++ LegacyWindow w = new LegacyWindow(getClass().getSimpleName());
+ setMainWindow(w);
+ // setTheme("tests-tickets");
+ Panel p = createPanel();
+ w.getContent().addComponent(p);
+ // w.getLayout().addComponent(createGLPanel());
+ w.getContent().addComponent(createPanelV());
+ }
+
+ private Panel createPanel() {
+ Panel p = new Panel(DIM1 + "x" + DIM2 + " OrderedLayout");
+ p.setWidth(DIM1 + "px");
+ p.setHeight(DIM2 + "px");
+
+ HorizontalLayout layout = new HorizontalLayout();
+ p.setContent(layout);
+ p.getContent().setSizeFull();
+
+ for (int i = 0; i < COMPONENTS; i++) {
+ TextField tf = new TextField();
+ if (r.nextBoolean()) {
+ tf.setCaption("Caption");
+ }
+ if (r.nextBoolean()) {
+ tf.setRequired(true);
+ }
+ if (r.nextBoolean()) {
+ tf.setComponentError(new UserError("Error"));
+ }
+ tf.setWidth("100%");
+ layout.setComponentAlignment(tf, Alignment.BOTTOM_LEFT);
+ p.addComponent(tf);
+
+ }
+
+ return p;
+ }
+
+ @SuppressWarnings("unused")
+ private Panel createGLPanel() {
+ Panel p = new Panel("" + DIM1 + "x" + DIM2 + " GridLayout");
+ p.setWidth("" + DIM1 + "px");
+ p.setHeight("" + DIM2 + "px");
+
+ GridLayout layout = new GridLayout(COMPONENTS, 1);
+ p.setContent(layout);
+ p.getContent().setSizeFull();
+
+ for (int i = 0; i < COMPONENTS; i++) {
+ TextField tf = new TextField();
+ tf.setImmediate(true);
+ tf.addListener(new ValueChangeListener() {
+
+ public void valueChange(ValueChangeEvent event) {
+ Component c = ((Component) event.getProperty());
+ c.setCaption("askfdj");
+
+ }
+ });
+ if (r.nextBoolean()) {
+ tf.setCaption("Caption");
+ }
+ if (r.nextBoolean()) {
+ tf.setRequired(true);
+ }
+ if (r.nextBoolean()) {
+ tf.setComponentError(new UserError("Error"));
+ }
+ tf.setWidth("100%");
+ layout.setComponentAlignment(tf, Alignment.MIDDLE_LEFT);
+ p.addComponent(tf);
+
+ }
+
+ return p;
+ }
+
+ private Panel createPanelV() {
+ Panel p = new Panel("" + DIM1 + "x" + DIM2 + " OrderedLayout");
+ p.setWidth("" + DIM2 + "px");
+ p.setHeight("" + DIM1 + "px");
+
+ VerticalLayout layout = new VerticalLayout();
+ p.setContent(layout);
+ p.getContent().setSizeFull();
+
+ for (int i = 0; i < COMPONENTS; i++) {
+ TextArea tf = new TextArea();
+ if (r.nextBoolean()) {
+ tf.setCaption("Caption");
+ }
+ if (r.nextBoolean()) {
+ tf.setRequired(true);
+ }
+ if (r.nextBoolean()) {
+ tf.setComponentError(new UserError("Error"));
+ }
+
+ tf.setRows(2);
+ tf.setSizeFull();
+
+ layout.setComponentAlignment(tf, Alignment.BOTTOM_LEFT);
+ p.addComponent(tf);
+
+ }
+
+ return p;
+ }
+ }
- package com.vaadin.tests.tickets;\r
- \r
- import com.vaadin.ui.Button;\r
- import com.vaadin.ui.Button.ClickEvent;\r
- import com.vaadin.ui.Label;\r
- import com.vaadin.ui.Layout;\r
- import com.vaadin.ui.Root.LegacyWindow;\r
- import com.vaadin.ui.VerticalLayout;\r
- \r
- public class Ticket2037 extends com.vaadin.Application.LegacyApplication {\r
- \r
- @Override\r
- public void init() {\r
- LegacyWindow main = new LegacyWindow();\r
- setMainWindow(main);\r
- \r
- main.addComponent(new Label(\r
- "Use debug dialog and trac number of registered paintables. It should not grow on subsequant b clicks."));\r
- \r
- final Layout lo = new VerticalLayout();\r
- \r
- Button b = new Button("b");\r
- \r
- main.addComponent(b);\r
- main.addComponent(lo);\r
- b.addListener(new Button.ClickListener() {\r
- \r
- public void buttonClick(ClickEvent event) {\r
- \r
- repopupate(lo);\r
- \r
- }\r
- });\r
- \r
- }\r
- \r
- int counter = 0;\r
- \r
- protected void repopupate(Layout lo) {\r
- lo.removeAllComponents();\r
- \r
- for (int i = 0; i < 20; i++) {\r
- lo.addComponent(new Label("tc" + (counter++)));\r
- }\r
- \r
- }\r
- \r
+ package com.vaadin.tests.tickets;
+
+ import com.vaadin.ui.Button;
+ import com.vaadin.ui.Button.ClickEvent;
+ import com.vaadin.ui.Label;
+ import com.vaadin.ui.Layout;
++import com.vaadin.ui.Root.LegacyWindow;
+ import com.vaadin.ui.VerticalLayout;
-import com.vaadin.ui.Window;
+
-public class Ticket2037 extends com.vaadin.Application {
++public class Ticket2037 extends com.vaadin.Application.LegacyApplication {
+
+ @Override
+ public void init() {
- Window main = new Window();
++ LegacyWindow main = new LegacyWindow();
+ setMainWindow(main);
+
+ main.addComponent(new Label(
+ "Use debug dialog and trac number of registered paintables. It should not grow on subsequant b clicks."));
+
+ final Layout lo = new VerticalLayout();
+
+ Button b = new Button("b");
+
+ main.addComponent(b);
+ main.addComponent(lo);
+ b.addListener(new Button.ClickListener() {
+
+ public void buttonClick(ClickEvent event) {
+
+ repopupate(lo);
+
+ }
+ });
+
+ }
+
+ int counter = 0;
+
+ protected void repopupate(Layout lo) {
+ lo.removeAllComponents();
+
+ for (int i = 0; i < 20; i++) {
+ lo.addComponent(new Label("tc" + (counter++)));
+ }
+
+ }
+
}
- package com.vaadin.tests.tickets;\r
- \r
- import com.vaadin.ui.Accordion;\r
- import com.vaadin.ui.Label;\r
- import com.vaadin.ui.Layout;\r
- import com.vaadin.ui.Root.LegacyWindow;\r
- import com.vaadin.ui.TextArea;\r
- import com.vaadin.ui.TextField;\r
- \r
- public class Ticket2040 extends com.vaadin.Application.LegacyApplication {\r
- \r
- TextField f = new TextField();\r
- \r
- @Override\r
- public void init() {\r
- LegacyWindow main = new LegacyWindow();\r
- setMainWindow(main);\r
- \r
- main.getContent().setSizeFull();\r
- ((Layout) main.getContent()).setMargin(true);\r
- \r
- setTheme("tests-tickets");\r
- \r
- Accordion ts;\r
- \r
- ts = new Accordion();\r
- ts.setSizeFull();\r
- ts.setWidth("300px");\r
- \r
- TextArea l = new TextArea("DSFS");\r
- l.setRows(2);\r
- l.setStyleName("red");\r
- l.setSizeFull();\r
- ts.addTab(l, "100% h component", null);\r
- \r
- Label testContent = new Label(\r
- "TabSheet by default uses caption, icon, errors etc. from Components. ");\r
- \r
- testContent.setCaption("Introduction to test");\r
- \r
- ts.addTab(testContent);\r
- \r
- // main.addComponent(ts);\r
- \r
- ts = new Accordion();\r
- ts.setSizeFull();\r
- ts.setHeight("200px");\r
- ts.setWidth("300px");\r
- \r
- l = new TextArea("DSFS");\r
- l.setRows(2);\r
- l.setStyleName("red");\r
- l.setSizeFull();\r
- ts.addTab(l, "200px h component", null);\r
- \r
- testContent = new Label(\r
- "TabSheet by default uses caption, icon, errors etc. from Components. ");\r
- \r
- testContent.setCaption("Introduction to test");\r
- \r
- ts.addTab(testContent);\r
- \r
- main.addComponent(ts);\r
- \r
- ts = new Accordion();\r
- ts.setSizeFull();\r
- ts.setHeight("50%");\r
- ts.setWidth("300px");\r
- \r
- l = new TextArea("DSFS");\r
- l.setRows(2);\r
- l.setStyleName("red");\r
- l.setSizeFull();\r
- ts.addTab(l, "50% h component", null);\r
- \r
- testContent = new Label(\r
- "TabSheet by default uses caption, icon, errors etc. from Components. ");\r
- \r
- testContent.setCaption("Introduction to test");\r
- \r
- ts.addTab(testContent);\r
- \r
- // main.addComponent(ts);\r
- \r
- }\r
- \r
+ package com.vaadin.tests.tickets;
+
+ import com.vaadin.ui.Accordion;
+ import com.vaadin.ui.Label;
+ import com.vaadin.ui.Layout;
++import com.vaadin.ui.Root.LegacyWindow;
+ import com.vaadin.ui.TextArea;
+ import com.vaadin.ui.TextField;
-import com.vaadin.ui.Window;
+
-public class Ticket2040 extends com.vaadin.Application {
++public class Ticket2040 extends com.vaadin.Application.LegacyApplication {
+
+ TextField f = new TextField();
+
+ @Override
+ public void init() {
- Window main = new Window();
++ LegacyWindow main = new LegacyWindow();
+ setMainWindow(main);
+
+ main.getContent().setSizeFull();
+ ((Layout) main.getContent()).setMargin(true);
+
+ setTheme("tests-tickets");
+
+ Accordion ts;
+
+ ts = new Accordion();
+ ts.setSizeFull();
+ ts.setWidth("300px");
+
+ TextArea l = new TextArea("DSFS");
+ l.setRows(2);
+ l.setStyleName("red");
+ l.setSizeFull();
+ ts.addTab(l, "100% h component", null);
+
+ Label testContent = new Label(
+ "TabSheet by default uses caption, icon, errors etc. from Components. ");
+
+ testContent.setCaption("Introduction to test");
+
+ ts.addTab(testContent);
+
+ // main.addComponent(ts);
+
+ ts = new Accordion();
+ ts.setSizeFull();
+ ts.setHeight("200px");
+ ts.setWidth("300px");
+
+ l = new TextArea("DSFS");
+ l.setRows(2);
+ l.setStyleName("red");
+ l.setSizeFull();
+ ts.addTab(l, "200px h component", null);
+
+ testContent = new Label(
+ "TabSheet by default uses caption, icon, errors etc. from Components. ");
+
+ testContent.setCaption("Introduction to test");
+
+ ts.addTab(testContent);
+
+ main.addComponent(ts);
+
+ ts = new Accordion();
+ ts.setSizeFull();
+ ts.setHeight("50%");
+ ts.setWidth("300px");
+
+ l = new TextArea("DSFS");
+ l.setRows(2);
+ l.setStyleName("red");
+ l.setSizeFull();
+ ts.addTab(l, "50% h component", null);
+
+ testContent = new Label(
+ "TabSheet by default uses caption, icon, errors etc. from Components. ");
+
+ testContent.setCaption("Introduction to test");
+
+ ts.addTab(testContent);
+
+ // main.addComponent(ts);
+
+ }
+
}
- package com.vaadin.tests.tickets;\r
- \r
- import com.vaadin.Application;\r
- import com.vaadin.ui.Button;\r
- import com.vaadin.ui.Button.ClickEvent;\r
- import com.vaadin.ui.Button.ClickListener;\r
- import com.vaadin.ui.GridLayout;\r
- import com.vaadin.ui.Label;\r
- import com.vaadin.ui.Notification;\r
- import com.vaadin.ui.Root.LegacyWindow;\r
- \r
- public class Ticket2042 extends Application.LegacyApplication {\r
- \r
- @Override\r
- public void init() {\r
- LegacyWindow w = new LegacyWindow(getClass().getSimpleName());\r
- setMainWindow(w);\r
- // setTheme("tests-tickets");\r
- GridLayout layout = new GridLayout(1, 2);\r
- layout.setHeight("2000px");\r
- w.setContent(layout);\r
- createUI(layout);\r
- }\r
- \r
- private void createUI(GridLayout layout) {\r
- layout.addComponent(new Label("abc"));\r
- layout.addComponent(new Button("B", new ClickListener() {\r
- \r
- public void buttonClick(ClickEvent event) {\r
- Notification n = new Notification("Test");\r
- getMainWindow().showNotification(n);\r
- }\r
- \r
- }));\r
- \r
- layout.addComponent(new Label("abc"));\r
- }\r
- }\r
+ package com.vaadin.tests.tickets;
+
+ import com.vaadin.Application;
+ import com.vaadin.ui.Button;
+ import com.vaadin.ui.Button.ClickEvent;
+ import com.vaadin.ui.Button.ClickListener;
+ import com.vaadin.ui.GridLayout;
+ import com.vaadin.ui.Label;
-import com.vaadin.ui.Window;
-import com.vaadin.ui.Window.Notification;
++import com.vaadin.ui.Notification;
++import com.vaadin.ui.Root.LegacyWindow;
+
-public class Ticket2042 extends Application {
++public class Ticket2042 extends Application.LegacyApplication {
+
+ @Override
+ public void init() {
- Window w = new Window(getClass().getSimpleName());
++ LegacyWindow w = new LegacyWindow(getClass().getSimpleName());
+ setMainWindow(w);
+ // setTheme("tests-tickets");
+ GridLayout layout = new GridLayout(1, 2);
+ layout.setHeight("2000px");
+ w.setContent(layout);
+ createUI(layout);
+ }
+
+ private void createUI(GridLayout layout) {
+ layout.addComponent(new Label("abc"));
+ layout.addComponent(new Button("B", new ClickListener() {
+
+ public void buttonClick(ClickEvent event) {
+ Notification n = new Notification("Test");
+ getMainWindow().showNotification(n);
+ }
+
+ }));
+
+ layout.addComponent(new Label("abc"));
+ }
+ }
- package com.vaadin.tests.tickets;\r
- \r
- import com.vaadin.Application;\r
- import com.vaadin.terminal.ExternalResource;\r
- import com.vaadin.ui.GridLayout;\r
- import com.vaadin.ui.Link;\r
- import com.vaadin.ui.Root.LegacyWindow;\r
- \r
- public class Ticket2043 extends Application.LegacyApplication {\r
- \r
- @Override\r
- public void init() {\r
- LegacyWindow w = new LegacyWindow(getClass().getSimpleName());\r
- setMainWindow(w);\r
- // setTheme("tests-tickets");\r
- GridLayout layout = new GridLayout(10, 10);\r
- w.setContent(layout);\r
- createUI(layout);\r
- }\r
- \r
- private void createUI(GridLayout layout) {\r
- Link l = new Link("Vaadin home (new 200x200 window, no decor, icon)",\r
- new ExternalResource("http://www.vaadin.com"), "_blank", 200,\r
- 200, Link.TARGET_BORDER_NONE);\r
- \r
- layout.addComponent(l);\r
- }\r
- }\r
+ package com.vaadin.tests.tickets;
+
+ import com.vaadin.Application;
+ import com.vaadin.terminal.ExternalResource;
+ import com.vaadin.ui.GridLayout;
+ import com.vaadin.ui.Link;
-import com.vaadin.ui.Window;
++import com.vaadin.ui.Root.LegacyWindow;
+
-public class Ticket2043 extends Application {
++public class Ticket2043 extends Application.LegacyApplication {
+
+ @Override
+ public void init() {
- Window w = new Window(getClass().getSimpleName());
++ LegacyWindow w = new LegacyWindow(getClass().getSimpleName());
+ setMainWindow(w);
+ // setTheme("tests-tickets");
+ GridLayout layout = new GridLayout(10, 10);
+ w.setContent(layout);
+ createUI(layout);
+ }
+
+ private void createUI(GridLayout layout) {
+ Link l = new Link("Vaadin home (new 200x200 window, no decor, icon)",
+ new ExternalResource("http://www.vaadin.com"), "_blank", 200,
+ 200, Link.TARGET_BORDER_NONE);
+
+ layout.addComponent(l);
+ }
+ }
- package com.vaadin.tests.tickets;\r
- \r
- import com.vaadin.Application;\r
- import com.vaadin.terminal.ThemeResource;\r
- import com.vaadin.ui.Button;\r
- import com.vaadin.ui.Button.ClickEvent;\r
- import com.vaadin.ui.Button.ClickListener;\r
- import com.vaadin.ui.Embedded;\r
- import com.vaadin.ui.GridLayout;\r
- import com.vaadin.ui.Label;\r
- import com.vaadin.ui.Layout;\r
- import com.vaadin.ui.Panel;\r
- import com.vaadin.ui.Root.LegacyWindow;\r
- import com.vaadin.ui.VerticalLayout;\r
- \r
- public class Ticket2048 extends Application.LegacyApplication {\r
- \r
- private Embedded embedded;\r
- private Panel p;\r
- private VerticalLayout orderedLayout;\r
- \r
- @Override\r
- public void init() {\r
- LegacyWindow w = new LegacyWindow(getClass().getSimpleName());\r
- setMainWindow(w);\r
- // setTheme("tests-tickets");\r
- // splitPanel = new SplitPanel(SplitPanel.ORIENTATION_HORIZONTAL);\r
- // getMainWindow().setContent(splitPanel);\r
- \r
- // GridLayout layout = new GridLayout(10, 10);\r
- // w.setContent(layout);\r
- // gridLayout = new GridLayout(1, 1);\r
- orderedLayout = new VerticalLayout();\r
- \r
- getMainWindow().setContent(orderedLayout);\r
- // getMainWindow().setContent(new GridLayout(1, 1));\r
- getMainWindow().setSizeFull();\r
- getMainWindow().getContent().setSizeFull();\r
- \r
- createUI(orderedLayout);\r
- // createUI(gridLayout);\r
- \r
- }\r
- \r
- private void createUI(Layout layout) {\r
- // Button sw = new Button("Switch", new ClickListener() {\r
- //\r
- // public void buttonClick(ClickEvent event) {\r
- // Layout l = getMainWindow().getLayout();\r
- // if (l == orderedLayout) {\r
- // getMainWindow().setContent(gridLayout);\r
- // } else {\r
- // getMainWindow().setContent(orderedLayout);\r
- // }\r
- //\r
- // }\r
- // });\r
- // layout.addComponent(sw);\r
- \r
- Layout ol = new GridLayout(1, 2);\r
- p = new Panel("Panel", ol);\r
- p.setSizeFull();\r
- Label l = new Label("Spacer");\r
- l.setHeight("400px");\r
- p.addComponent(l);\r
- \r
- embedded = new Embedded(null, new ThemeResource(\r
- "icons/64/folder-add.png"));\r
- layout.addComponent(embedded);\r
- Button b = new Button(\r
- "Replace image with new embedded component (flashes)",\r
- new ClickListener() {\r
- \r
- public void buttonClick(ClickEvent event) {\r
- Embedded newEmbedded = new Embedded(null,\r
- new ThemeResource("icons/64/folder-add.png"));\r
- getMainWindow().getContent().replaceComponent(embedded,\r
- newEmbedded);\r
- embedded = newEmbedded;\r
- \r
- }\r
- \r
- });\r
- p.addComponent(b);\r
- \r
- b = new Button("Change image source (is fine)", new ClickListener() {\r
- \r
- public void buttonClick(ClickEvent event) {\r
- String img = "folder-add";\r
- if (((ThemeResource) embedded.getSource()).getResourceId()\r
- .contains("folder-add")) {\r
- img = "folder-delete";\r
- }\r
- embedded.setSource(new ThemeResource("icons/64/" + img + ".png"));\r
- \r
- }\r
- \r
- });\r
- \r
- p.addComponent(b);\r
- layout.addComponent(p);\r
- }\r
- }\r
+ package com.vaadin.tests.tickets;
+
+ import com.vaadin.Application;
+ import com.vaadin.terminal.ThemeResource;
+ import com.vaadin.ui.Button;
+ import com.vaadin.ui.Button.ClickEvent;
+ import com.vaadin.ui.Button.ClickListener;
+ import com.vaadin.ui.Embedded;
+ import com.vaadin.ui.GridLayout;
+ import com.vaadin.ui.Label;
+ import com.vaadin.ui.Layout;
+ import com.vaadin.ui.Panel;
++import com.vaadin.ui.Root.LegacyWindow;
+ import com.vaadin.ui.VerticalLayout;
-import com.vaadin.ui.Window;
+
-public class Ticket2048 extends Application {
++public class Ticket2048 extends Application.LegacyApplication {
+
+ private Embedded embedded;
+ private Panel p;
+ private VerticalLayout orderedLayout;
+
+ @Override
+ public void init() {
- Window w = new Window(getClass().getSimpleName());
++ LegacyWindow w = new LegacyWindow(getClass().getSimpleName());
+ setMainWindow(w);
+ // setTheme("tests-tickets");
+ // splitPanel = new SplitPanel(SplitPanel.ORIENTATION_HORIZONTAL);
+ // getMainWindow().setContent(splitPanel);
+
+ // GridLayout layout = new GridLayout(10, 10);
+ // w.setContent(layout);
+ // gridLayout = new GridLayout(1, 1);
+ orderedLayout = new VerticalLayout();
+
+ getMainWindow().setContent(orderedLayout);
+ // getMainWindow().setContent(new GridLayout(1, 1));
+ getMainWindow().setSizeFull();
+ getMainWindow().getContent().setSizeFull();
+
+ createUI(orderedLayout);
+ // createUI(gridLayout);
+
+ }
+
+ private void createUI(Layout layout) {
+ // Button sw = new Button("Switch", new ClickListener() {
+ //
+ // public void buttonClick(ClickEvent event) {
+ // Layout l = getMainWindow().getLayout();
+ // if (l == orderedLayout) {
+ // getMainWindow().setContent(gridLayout);
+ // } else {
+ // getMainWindow().setContent(orderedLayout);
+ // }
+ //
+ // }
+ // });
+ // layout.addComponent(sw);
+
+ Layout ol = new GridLayout(1, 2);
+ p = new Panel("Panel", ol);
+ p.setSizeFull();
+ Label l = new Label("Spacer");
+ l.setHeight("400px");
+ p.addComponent(l);
+
+ embedded = new Embedded(null, new ThemeResource(
+ "icons/64/folder-add.png"));
+ layout.addComponent(embedded);
+ Button b = new Button(
+ "Replace image with new embedded component (flashes)",
+ new ClickListener() {
+
+ public void buttonClick(ClickEvent event) {
+ Embedded newEmbedded = new Embedded(null,
+ new ThemeResource("icons/64/folder-add.png"));
+ getMainWindow().getContent().replaceComponent(embedded,
+ newEmbedded);
+ embedded = newEmbedded;
+
+ }
+
+ });
+ p.addComponent(b);
+
+ b = new Button("Change image source (is fine)", new ClickListener() {
+
+ public void buttonClick(ClickEvent event) {
+ String img = "folder-add";
+ if (((ThemeResource) embedded.getSource()).getResourceId()
+ .contains("folder-add")) {
+ img = "folder-delete";
+ }
+ embedded.setSource(new ThemeResource("icons/64/" + img + ".png"));
+
+ }
+
+ });
+
+ p.addComponent(b);
+ layout.addComponent(p);
+ }
+ }
- package com.vaadin.tests.tickets;\r
- \r
- import com.vaadin.Application;\r
- import com.vaadin.data.Item;\r
- import com.vaadin.ui.Button;\r
- import com.vaadin.ui.Component;\r
- import com.vaadin.ui.DateField;\r
- import com.vaadin.ui.GridLayout;\r
- import com.vaadin.ui.Label;\r
- import com.vaadin.ui.Root.LegacyWindow;\r
- import com.vaadin.ui.Table;\r
- import com.vaadin.ui.TextField;\r
- \r
- public class Ticket2051 extends Application.LegacyApplication {\r
- \r
- private static final Object P1 = new Object();\r
- private static final Object P2 = new Object();\r
- \r
- @Override\r
- public void init() {\r
- LegacyWindow w = new LegacyWindow(getClass().getSimpleName());\r
- setMainWindow(w);\r
- // setTheme("tests-tickets");\r
- GridLayout layout = new GridLayout(10, 10);\r
- w.setContent(layout);\r
- createUI(layout);\r
- }\r
- \r
- private void createUI(GridLayout layout) {\r
- Table t = new Table("This is a table");\r
- t.addContainerProperty(P1, Component.class, null);\r
- t.addContainerProperty(P2, Component.class, null);\r
- t.setColumnHeaders(new String[] { "Col1", "Col2" });\r
- \r
- Item i = t.addItem("1");\r
- i.getItemProperty(P1).setValue(new TextField("abc"));\r
- i.getItemProperty(P2).setValue(new Label("label"));\r
- Item i2 = t.addItem("2");\r
- i2.getItemProperty(P1).setValue(new Button("def"));\r
- i2.getItemProperty(P2).setValue(new DateField());\r
- \r
- layout.addComponent(t);\r
- }\r
- }\r
+ package com.vaadin.tests.tickets;
+
+ import com.vaadin.Application;
+ import com.vaadin.data.Item;
+ import com.vaadin.ui.Button;
+ import com.vaadin.ui.Component;
+ import com.vaadin.ui.DateField;
+ import com.vaadin.ui.GridLayout;
+ import com.vaadin.ui.Label;
++import com.vaadin.ui.Root.LegacyWindow;
+ import com.vaadin.ui.Table;
+ import com.vaadin.ui.TextField;
-import com.vaadin.ui.Window;
+
-public class Ticket2051 extends Application {
++public class Ticket2051 extends Application.LegacyApplication {
+
+ private static final Object P1 = new Object();
+ private static final Object P2 = new Object();
+
+ @Override
+ public void init() {
- Window w = new Window(getClass().getSimpleName());
++ LegacyWindow w = new LegacyWindow(getClass().getSimpleName());
+ setMainWindow(w);
+ // setTheme("tests-tickets");
+ GridLayout layout = new GridLayout(10, 10);
+ w.setContent(layout);
+ createUI(layout);
+ }
+
+ private void createUI(GridLayout layout) {
+ Table t = new Table("This is a table");
+ t.addContainerProperty(P1, Component.class, null);
+ t.addContainerProperty(P2, Component.class, null);
+ t.setColumnHeaders(new String[] { "Col1", "Col2" });
+
+ Item i = t.addItem("1");
+ i.getItemProperty(P1).setValue(new TextField("abc"));
+ i.getItemProperty(P2).setValue(new Label("label"));
+ Item i2 = t.addItem("2");
+ i2.getItemProperty(P1).setValue(new Button("def"));
+ i2.getItemProperty(P2).setValue(new DateField());
+
+ layout.addComponent(t);
+ }
+ }
- package com.vaadin.tests.tickets;\r
- \r
- import com.vaadin.Application;\r
- import com.vaadin.ui.Button;\r
- import com.vaadin.ui.Button.ClickEvent;\r
- import com.vaadin.ui.Button.ClickListener;\r
- import com.vaadin.ui.GridLayout;\r
- import com.vaadin.ui.HorizontalLayout;\r
- import com.vaadin.ui.Root.LegacyWindow;\r
- \r
- public class Ticket2060 extends Application.LegacyApplication {\r
- \r
- private Button button1;\r
- private Button button2;\r
- private Button button3;\r
- \r
- @Override\r
- public void init() {\r
- LegacyWindow w = new LegacyWindow(getClass().getSimpleName());\r
- setMainWindow(w);\r
- // setTheme("tests-tickets");\r
- GridLayout layout = new GridLayout(10, 10);\r
- w.setContent(layout);\r
- createUI(layout);\r
- }\r
- \r
- private void createUI(GridLayout layout) {\r
- HorizontalLayout buttonLayout = new HorizontalLayout();\r
- button1 = new Button("Button which is 50px wide");\r
- button1.setWidth("50px");\r
- button2 = new Button("Button without width");\r
- button3 = new Button("Click to repaint buttons", new ClickListener() {\r
- \r
- public void buttonClick(ClickEvent event) {\r
- button1.requestRepaint();\r
- button2.requestRepaint();\r
- button3.requestRepaint();\r
- \r
- }\r
- \r
- });\r
- \r
- buttonLayout.addComponent(button1);\r
- buttonLayout.addComponent(button2);\r
- buttonLayout.addComponent(button3);\r
- \r
- layout.addComponent(buttonLayout);\r
- \r
- }\r
- }\r
+ package com.vaadin.tests.tickets;
+
+ import com.vaadin.Application;
+ import com.vaadin.ui.Button;
+ import com.vaadin.ui.Button.ClickEvent;
+ import com.vaadin.ui.Button.ClickListener;
+ import com.vaadin.ui.GridLayout;
+ import com.vaadin.ui.HorizontalLayout;
-import com.vaadin.ui.Window;
++import com.vaadin.ui.Root.LegacyWindow;
+
-public class Ticket2060 extends Application {
++public class Ticket2060 extends Application.LegacyApplication {
+
+ private Button button1;
+ private Button button2;
+ private Button button3;
+
+ @Override
+ public void init() {
- Window w = new Window(getClass().getSimpleName());
++ LegacyWindow w = new LegacyWindow(getClass().getSimpleName());
+ setMainWindow(w);
+ // setTheme("tests-tickets");
+ GridLayout layout = new GridLayout(10, 10);
+ w.setContent(layout);
+ createUI(layout);
+ }
+
+ private void createUI(GridLayout layout) {
+ HorizontalLayout buttonLayout = new HorizontalLayout();
+ button1 = new Button("Button which is 50px wide");
+ button1.setWidth("50px");
+ button2 = new Button("Button without width");
+ button3 = new Button("Click to repaint buttons", new ClickListener() {
+
+ public void buttonClick(ClickEvent event) {
+ button1.requestRepaint();
+ button2.requestRepaint();
+ button3.requestRepaint();
+
+ }
+
+ });
+
+ buttonLayout.addComponent(button1);
+ buttonLayout.addComponent(button2);
+ buttonLayout.addComponent(button3);
+
+ layout.addComponent(buttonLayout);
+
+ }
+ }
- package com.vaadin.tests.tickets;\r
- \r
- import com.vaadin.Application;\r
- import com.vaadin.ui.HorizontalSplitPanel;\r
- import com.vaadin.ui.Root.LegacyWindow;\r
- import com.vaadin.ui.TabSheet;\r
- import com.vaadin.ui.Table;\r
- import com.vaadin.ui.TextField;\r
- \r
- public class Ticket2062 extends Application.LegacyApplication {\r
- private static final Object P1 = new Object();\r
- \r
- @Override\r
- public void init() {\r
- setMainWindow(new LegacyWindow("Ticket2062"));\r
- getMainWindow().setSizeFull();\r
- \r
- HorizontalSplitPanel p = new HorizontalSplitPanel();\r
- p.setSizeFull();\r
- getMainWindow().setContent(p);\r
- \r
- TextField tf1 = new TextField("Tab 1");\r
- tf1.setValue("Field 1");\r
- tf1.setSizeFull();\r
- \r
- Table t = new Table("Table");\r
- t.addContainerProperty(P1, String.class, "");\r
- t.setSizeFull();\r
- \r
- TabSheet tabSheet = new TabSheet();\r
- tabSheet.setWidth("300px");\r
- tabSheet.setHeight("300px");\r
- \r
- tabSheet.addComponent(tf1);\r
- tabSheet.addComponent(t);\r
- \r
- getMainWindow().addComponent(tabSheet);\r
- \r
- }\r
- \r
+ package com.vaadin.tests.tickets;
+
+ import com.vaadin.Application;
+ import com.vaadin.ui.HorizontalSplitPanel;
++import com.vaadin.ui.Root.LegacyWindow;
+ import com.vaadin.ui.TabSheet;
+ import com.vaadin.ui.Table;
+ import com.vaadin.ui.TextField;
-import com.vaadin.ui.Window;
+
-public class Ticket2062 extends Application {
++public class Ticket2062 extends Application.LegacyApplication {
+ private static final Object P1 = new Object();
+
+ @Override
+ public void init() {
- setMainWindow(new Window("Ticket2062"));
++ setMainWindow(new LegacyWindow("Ticket2062"));
+ getMainWindow().setSizeFull();
+
+ HorizontalSplitPanel p = new HorizontalSplitPanel();
+ p.setSizeFull();
+ getMainWindow().setContent(p);
+
+ TextField tf1 = new TextField("Tab 1");
+ tf1.setValue("Field 1");
+ tf1.setSizeFull();
+
+ Table t = new Table("Table");
+ t.addContainerProperty(P1, String.class, "");
+ t.setSizeFull();
+
+ TabSheet tabSheet = new TabSheet();
+ tabSheet.setWidth("300px");
+ tabSheet.setHeight("300px");
+
+ tabSheet.addComponent(tf1);
+ tabSheet.addComponent(t);
+
+ getMainWindow().addComponent(tabSheet);
+
+ }
+
}
- package com.vaadin.tests.tickets;\r
- \r
- import com.vaadin.Application;\r
- import com.vaadin.ui.GridLayout;\r
- import com.vaadin.ui.Label;\r
- import com.vaadin.ui.Panel;\r
- import com.vaadin.ui.Root.LegacyWindow;\r
- \r
- public class Ticket2083 extends Application.LegacyApplication {\r
- \r
- @Override\r
- public void init() {\r
- LegacyWindow w = new LegacyWindow(getClass().getSimpleName());\r
- setMainWindow(w);\r
- // setTheme("tests-tickets");\r
- GridLayout layout = new GridLayout(10, 10);\r
- w.setContent(layout);\r
- createUI(layout);\r
- }\r
- \r
- private void createUI(GridLayout layout) {\r
- Panel p = new Panel(\r
- "This is a panel with a longer caption than it should have");\r
- p.setWidth("100px");\r
- p.getContent().addComponent(new Label("Contents"));\r
- layout.addComponent(p);\r
- }\r
- }\r
+ package com.vaadin.tests.tickets;
+
+ import com.vaadin.Application;
+ import com.vaadin.ui.GridLayout;
+ import com.vaadin.ui.Label;
+ import com.vaadin.ui.Panel;
-import com.vaadin.ui.Window;
++import com.vaadin.ui.Root.LegacyWindow;
+
-public class Ticket2083 extends Application {
++public class Ticket2083 extends Application.LegacyApplication {
+
+ @Override
+ public void init() {
- Window w = new Window(getClass().getSimpleName());
++ LegacyWindow w = new LegacyWindow(getClass().getSimpleName());
+ setMainWindow(w);
+ // setTheme("tests-tickets");
+ GridLayout layout = new GridLayout(10, 10);
+ w.setContent(layout);
+ createUI(layout);
+ }
+
+ private void createUI(GridLayout layout) {
+ Panel p = new Panel(
+ "This is a panel with a longer caption than it should have");
+ p.setWidth("100px");
+ p.getContent().addComponent(new Label("Contents"));
+ layout.addComponent(p);
+ }
+ }
- package com.vaadin.tests.tickets;\r
- \r
- import com.vaadin.Application;\r
- import com.vaadin.terminal.ExternalResource;\r
- import com.vaadin.ui.Embedded;\r
- import com.vaadin.ui.Root.LegacyWindow;\r
- \r
- public class Ticket2095 extends Application.LegacyApplication {\r
- \r
- @Override\r
- public void init() {\r
- LegacyWindow w = new LegacyWindow(getClass().getSimpleName());\r
- setMainWindow(w);\r
- \r
- // uncomment to workaround iorderedlayout bug in current trunk\r
- // w.setContent(new ExpandLayout());\r
- w.getContent().setSizeFull();\r
- \r
- Embedded em = new Embedded();\r
- em.setType(Embedded.TYPE_BROWSER);\r
- em.setSource(new ExternalResource("../statictestfiles/ticket2095.html"));\r
- em.setDebugId("MYIFRAME");\r
- \r
- em.setSizeFull();\r
- \r
- w.addComponent(em);\r
- \r
- }\r
- }\r
+ package com.vaadin.tests.tickets;
+
+ import com.vaadin.Application;
+ import com.vaadin.terminal.ExternalResource;
+ import com.vaadin.ui.Embedded;
-import com.vaadin.ui.Window;
++import com.vaadin.ui.Root.LegacyWindow;
+
-public class Ticket2095 extends Application {
++public class Ticket2095 extends Application.LegacyApplication {
+
+ @Override
+ public void init() {
- Window w = new Window(getClass().getSimpleName());
++ LegacyWindow w = new LegacyWindow(getClass().getSimpleName());
+ setMainWindow(w);
+
+ // uncomment to workaround iorderedlayout bug in current trunk
+ // w.setContent(new ExpandLayout());
+ w.getContent().setSizeFull();
+
+ Embedded em = new Embedded();
+ em.setType(Embedded.TYPE_BROWSER);
+ em.setSource(new ExternalResource("../statictestfiles/ticket2095.html"));
+ em.setDebugId("MYIFRAME");
+
+ em.setSizeFull();
+
+ w.addComponent(em);
+
+ }
+ }
- package com.vaadin.tests.tickets;\r
- \r
- import com.vaadin.Application;\r
- import com.vaadin.ui.Label;\r
- import com.vaadin.ui.Root.LegacyWindow;\r
- import com.vaadin.ui.TabSheet;\r
- \r
- public class Ticket2098 extends Application.LegacyApplication {\r
- \r
- private static final String info = "First tab hidden, second should initially be selected";\r
- \r
- @Override\r
- public void init() {\r
- LegacyWindow w = new LegacyWindow(getClass().getSimpleName());\r
- setMainWindow(w);\r
- // setTheme("tests-tickets");\r
- w.addComponent(new Label(info));\r
- createUI(w);\r
- }\r
- \r
- private void createUI(LegacyWindow w) {\r
- TabSheet ts = new TabSheet();\r
- Label l1 = new Label("111");\r
- Label l2 = new Label("222");\r
- Label l3 = new Label("333");\r
- Label l4 = new Label("444");\r
- \r
- ts.addTab(l1, "1", null);\r
- ts.addTab(l2, "2", null);\r
- ts.addTab(l3, "3", null);\r
- ts.addTab(l4, "4", null);\r
- \r
- l1.setVisible(false);\r
- \r
- w.addComponent(ts);\r
- }\r
- }\r
+ package com.vaadin.tests.tickets;
+
+ import com.vaadin.Application;
+ import com.vaadin.ui.Label;
++import com.vaadin.ui.Root.LegacyWindow;
+ import com.vaadin.ui.TabSheet;
-import com.vaadin.ui.Window;
+
-public class Ticket2098 extends Application {
++public class Ticket2098 extends Application.LegacyApplication {
+
+ private static final String info = "First tab hidden, second should initially be selected";
+
+ @Override
+ public void init() {
- Window w = new Window(getClass().getSimpleName());
++ LegacyWindow w = new LegacyWindow(getClass().getSimpleName());
+ setMainWindow(w);
+ // setTheme("tests-tickets");
+ w.addComponent(new Label(info));
+ createUI(w);
+ }
+
- private void createUI(Window w) {
++ private void createUI(LegacyWindow w) {
+ TabSheet ts = new TabSheet();
+ Label l1 = new Label("111");
+ Label l2 = new Label("222");
+ Label l3 = new Label("333");
+ Label l4 = new Label("444");
+
+ ts.addTab(l1, "1", null);
+ ts.addTab(l2, "2", null);
+ ts.addTab(l3, "3", null);
+ ts.addTab(l4, "4", null);
+
+ l1.setVisible(false);
+
+ w.addComponent(ts);
+ }
+ }
- package com.vaadin.tests.tickets;\r
- \r
- import com.vaadin.Application;\r
- import com.vaadin.ui.Button;\r
- import com.vaadin.ui.Button.ClickEvent;\r
- import com.vaadin.ui.Button.ClickListener;\r
- import com.vaadin.ui.GridLayout;\r
- import com.vaadin.ui.Label;\r
- import com.vaadin.ui.Root.LegacyWindow;\r
- import com.vaadin.ui.TabSheet;\r
- import com.vaadin.ui.VerticalLayout;\r
- import com.vaadin.ui.Window;\r
- \r
- public class Ticket2099 extends Application.LegacyApplication {\r
- \r
- private Label l1, l2, l3;\r
- private VerticalLayout ol1, ol2, ol3;\r
- private Window popup;\r
- \r
- @Override\r
- public void init() {\r
- LegacyWindow w = new LegacyWindow(getClass().getSimpleName());\r
- setMainWindow(w);\r
- // setTheme("tests-tickets");\r
- GridLayout layout = new GridLayout(10, 10);\r
- w.setContent(layout);\r
- createUI(layout);\r
- }\r
- \r
- private void createUI(GridLayout layout) {\r
- Button b = new Button("Show popup", new ClickListener() {\r
- \r
- public void buttonClick(ClickEvent event) {\r
- getMainWindow().addWindow(popup);\r
- // popup.setVisible(true);\r
- }\r
- \r
- });\r
- popup = createPopup();\r
- getMainWindow().addWindow(popup);\r
- \r
- layout.addComponent(b);\r
- layout.addComponent(new Button("Hide label '222'", new ClickListener() {\r
- \r
- public void buttonClick(ClickEvent event) {\r
- l2.setVisible(!l2.isVisible());\r
- }\r
- \r
- }));\r
- \r
- }\r
- \r
- private Window createPopup() {\r
- Window w = new Window("Popup");\r
- TabSheet ts = new TabSheet();\r
- ol1 = new VerticalLayout();\r
- ol2 = new VerticalLayout();\r
- ol3 = new VerticalLayout();\r
- l1 = new Label("111");\r
- l2 = new Label("222");\r
- l3 = new Label("333");\r
- \r
- ol1.addComponent(l1);\r
- ol2.addComponent(l2);\r
- ol3.addComponent(l3);\r
- \r
- ts.addTab(ol1, "1", null);\r
- ts.addTab(ol2, "2", null);\r
- ts.addTab(ol3, "3", null);\r
- \r
- // l1.setVisible(false);\r
- // ts.setSelectedTab(l3);\r
- \r
- w.addComponent(ts);\r
- \r
- return w;\r
- }\r
- }\r
+ package com.vaadin.tests.tickets;
+
+ import com.vaadin.Application;
+ import com.vaadin.ui.Button;
+ import com.vaadin.ui.Button.ClickEvent;
+ import com.vaadin.ui.Button.ClickListener;
+ import com.vaadin.ui.GridLayout;
+ import com.vaadin.ui.Label;
++import com.vaadin.ui.Root.LegacyWindow;
+ import com.vaadin.ui.TabSheet;
+ import com.vaadin.ui.VerticalLayout;
+ import com.vaadin.ui.Window;
+
-public class Ticket2099 extends Application {
++public class Ticket2099 extends Application.LegacyApplication {
+
+ private Label l1, l2, l3;
+ private VerticalLayout ol1, ol2, ol3;
+ private Window popup;
+
+ @Override
+ public void init() {
- Window w = new Window(getClass().getSimpleName());
++ LegacyWindow w = new LegacyWindow(getClass().getSimpleName());
+ setMainWindow(w);
+ // setTheme("tests-tickets");
+ GridLayout layout = new GridLayout(10, 10);
+ w.setContent(layout);
+ createUI(layout);
+ }
+
+ private void createUI(GridLayout layout) {
+ Button b = new Button("Show popup", new ClickListener() {
+
+ public void buttonClick(ClickEvent event) {
+ getMainWindow().addWindow(popup);
+ // popup.setVisible(true);
+ }
+
+ });
+ popup = createPopup();
- addWindow(popup);
++ getMainWindow().addWindow(popup);
+
+ layout.addComponent(b);
+ layout.addComponent(new Button("Hide label '222'", new ClickListener() {
+
+ public void buttonClick(ClickEvent event) {
+ l2.setVisible(!l2.isVisible());
+ }
+
+ }));
+
+ }
+
+ private Window createPopup() {
+ Window w = new Window("Popup");
+ TabSheet ts = new TabSheet();
+ ol1 = new VerticalLayout();
+ ol2 = new VerticalLayout();
+ ol3 = new VerticalLayout();
+ l1 = new Label("111");
+ l2 = new Label("222");
+ l3 = new Label("333");
+
+ ol1.addComponent(l1);
+ ol2.addComponent(l2);
+ ol3.addComponent(l3);
+
+ ts.addTab(ol1, "1", null);
+ ts.addTab(ol2, "2", null);
+ ts.addTab(ol3, "3", null);
+
+ // l1.setVisible(false);
+ // ts.setSelectedTab(l3);
+
+ w.addComponent(ts);
+
+ return w;
+ }
+ }
- package com.vaadin.tests.tickets;\r
- \r
- import com.vaadin.Application;\r
- import com.vaadin.ui.Button;\r
- import com.vaadin.ui.Root.LegacyWindow;\r
- \r
- public class Ticket2101 extends Application.LegacyApplication {\r
- \r
- @Override\r
- public void init() {\r
- LegacyWindow w = new LegacyWindow(getClass().getSimpleName());\r
- setMainWindow(w);\r
- \r
- Button b = new Button(\r
- "Button with a long text which will not fit on 50 pixels");\r
- b.setWidth("50px");\r
- \r
- w.getContent().addComponent(b);\r
- }\r
- \r
- }\r
+ package com.vaadin.tests.tickets;
+
+ import com.vaadin.Application;
+ import com.vaadin.ui.Button;
-import com.vaadin.ui.Window;
++import com.vaadin.ui.Root.LegacyWindow;
+
-public class Ticket2101 extends Application {
++public class Ticket2101 extends Application.LegacyApplication {
+
+ @Override
+ public void init() {
- Window w = new Window(getClass().getSimpleName());
++ LegacyWindow w = new LegacyWindow(getClass().getSimpleName());
+ setMainWindow(w);
+
+ Button b = new Button(
+ "Button with a long text which will not fit on 50 pixels");
+ b.setWidth("50px");
+
+ w.getContent().addComponent(b);
+ }
+
+ }
- package com.vaadin.tests.tickets;\r
- \r
- import com.vaadin.data.Item;\r
- import com.vaadin.data.util.IndexedContainer;\r
- import com.vaadin.ui.Button;\r
- import com.vaadin.ui.Component;\r
- import com.vaadin.ui.Label;\r
- import com.vaadin.ui.Root.LegacyWindow;\r
- import com.vaadin.ui.Table;\r
- \r
- /**\r
- * \r
- * Toggling container with an empty one may result duplicate header cell in\r
- * client.\r
- * \r
- */\r
- public class Ticket2126 extends com.vaadin.Application.LegacyApplication {\r
- \r
- LegacyWindow main = new LegacyWindow();\r
- Table table = new Table();\r
- \r
- @Override\r
- public void init() {\r
- setMainWindow(main);\r
- \r
- final IndexedContainer container1 = new IndexedContainer();\r
- container1.addContainerProperty("text", Component.class, null);\r
- final IndexedContainer container2 = new IndexedContainer();\r
- \r
- // Case #2 Try to comment the following line for another type of strange\r
- // behaviour\r
- container2.addContainerProperty("text", Component.class, null);\r
- \r
- for (int i = 0; i < 100; i++) {\r
- Item item = container1.addItem(i);\r
- item.getItemProperty("text").setValue(new Label("Test " + i));\r
- }\r
- \r
- table.setContainerDataSource(container1);\r
- \r
- // workaround for case #2\r
- // table.setWidth("300px");\r
- // table.setHeight("300px");\r
- \r
- Button refreshTable = new Button("Switch table container");\r
- refreshTable.addListener(new Button.ClickListener() {\r
- boolean full = true;\r
- \r
- public void buttonClick(Button.ClickEvent e) {\r
- if (full) {\r
- table.setContainerDataSource(container2);\r
- } else {\r
- table.setContainerDataSource(container1);\r
- }\r
- full = !full;\r
- }\r
- });\r
- \r
- main.addComponent(table);\r
- main.addComponent(refreshTable);\r
- }\r
+ package com.vaadin.tests.tickets;
+
+ import com.vaadin.data.Item;
+ import com.vaadin.data.util.IndexedContainer;
+ import com.vaadin.ui.Button;
+ import com.vaadin.ui.Component;
+ import com.vaadin.ui.Label;
++import com.vaadin.ui.Root.LegacyWindow;
+ import com.vaadin.ui.Table;
-import com.vaadin.ui.Window;
+
+ /**
+ *
+ * Toggling container with an empty one may result duplicate header cell in
+ * client.
+ *
+ */
-public class Ticket2126 extends com.vaadin.Application {
++public class Ticket2126 extends com.vaadin.Application.LegacyApplication {
+
- Window main = new Window();
++ LegacyWindow main = new LegacyWindow();
+ Table table = new Table();
+
+ @Override
+ public void init() {
+ setMainWindow(main);
+
+ final IndexedContainer container1 = new IndexedContainer();
+ container1.addContainerProperty("text", Component.class, null);
+ final IndexedContainer container2 = new IndexedContainer();
+
+ // Case #2 Try to comment the following line for another type of strange
+ // behaviour
+ container2.addContainerProperty("text", Component.class, null);
+
+ for (int i = 0; i < 100; i++) {
+ Item item = container1.addItem(i);
+ item.getItemProperty("text").setValue(new Label("Test " + i));
+ }
+
+ table.setContainerDataSource(container1);
+
+ // workaround for case #2
+ // table.setWidth("300px");
+ // table.setHeight("300px");
+
+ Button refreshTable = new Button("Switch table container");
+ refreshTable.addListener(new Button.ClickListener() {
+ boolean full = true;
+
+ public void buttonClick(Button.ClickEvent e) {
+ if (full) {
+ table.setContainerDataSource(container2);
+ } else {
+ table.setContainerDataSource(container1);
+ }
+ full = !full;
+ }
+ });
+
+ main.addComponent(table);
+ main.addComponent(refreshTable);
+ }
}
- package com.vaadin.tests.tickets;\r
- \r
- import com.vaadin.Application;\r
- import com.vaadin.data.Item;\r
- import com.vaadin.ui.Component;\r
- import com.vaadin.ui.Label;\r
- import com.vaadin.ui.Root.LegacyWindow;\r
- import com.vaadin.ui.Table;\r
- import com.vaadin.ui.Table.CellStyleGenerator;\r
- import com.vaadin.ui.Table.ColumnGenerator;\r
- \r
- public class Ticket2208 extends Application.LegacyApplication {\r
- \r
- private Table t;\r
- \r
- @Override\r
- public void init() {\r
- LegacyWindow mainWindow = new LegacyWindow();\r
- setMainWindow(mainWindow);\r
- \r
- t = new Table("A table");\r
- t.addContainerProperty("col 1 (red)", String.class, "");\r
- t.addContainerProperty("col 2", String.class, "");\r
- \r
- t.setHeight("150px");\r
- t.addGeneratedColumn("col 3 (green)", new ColumnGenerator() {\r
- \r
- public Component generateCell(Table source, Object itemId,\r
- Object columnId) {\r
- Item item = source.getItem(itemId);\r
- String col1 = (String) item.getItemProperty("col 1 (red)")\r
- .getValue();\r
- String col2 = (String) item.getItemProperty("col 2").getValue();\r
- return new Label(col1 + "-" + col2);\r
- }\r
- });\r
- \r
- t.addContainerProperty("col 4", String.class, "");\r
- t.setCellStyleGenerator(new CellStyleGenerator() {\r
- \r
- public String getStyle(Object itemId, Object propertyId) {\r
- if ("col 1 (red)".equals(propertyId)) {\r
- return "red";\r
- }\r
- \r
- if ("col 3 (green)".equals(propertyId)) {\r
- return "green";\r
- }\r
- \r
- return null;\r
- }\r
- });\r
- \r
- t.addItem(new Object[] { "Col 1-1", "Col 2-1", "Col 4-1" },\r
- new Object());\r
- t.addItem(new Object[] { "Col 1-2", "Col 2-2", "Col 4-2" },\r
- new Object());\r
- t.addItem(new Object[] { "Col 1-3", "Col 2-3", "Col 4-3" },\r
- new Object());\r
- \r
- t.setColumnReorderingAllowed(true);\r
- t.setColumnCollapsingAllowed(true);\r
- setTheme("tests-tickets");\r
- mainWindow.addComponent(t);\r
- \r
- }\r
- \r
- }\r
+ package com.vaadin.tests.tickets;
+
+ import com.vaadin.Application;
+ import com.vaadin.data.Item;
+ import com.vaadin.ui.Component;
+ import com.vaadin.ui.Label;
++import com.vaadin.ui.Root.LegacyWindow;
+ import com.vaadin.ui.Table;
+ import com.vaadin.ui.Table.CellStyleGenerator;
+ import com.vaadin.ui.Table.ColumnGenerator;
-import com.vaadin.ui.Window;
+
-public class Ticket2208 extends Application {
++public class Ticket2208 extends Application.LegacyApplication {
+
+ private Table t;
+
+ @Override
+ public void init() {
- Window mainWindow = new Window();
++ LegacyWindow mainWindow = new LegacyWindow();
+ setMainWindow(mainWindow);
+
+ t = new Table("A table");
+ t.addContainerProperty("col 1 (red)", String.class, "");
+ t.addContainerProperty("col 2", String.class, "");
+
+ t.setHeight("150px");
+ t.addGeneratedColumn("col 3 (green)", new ColumnGenerator() {
+
+ public Component generateCell(Table source, Object itemId,
+ Object columnId) {
+ Item item = source.getItem(itemId);
+ String col1 = (String) item.getItemProperty("col 1 (red)")
+ .getValue();
+ String col2 = (String) item.getItemProperty("col 2").getValue();
+ return new Label(col1 + "-" + col2);
+ }
+ });
+
+ t.addContainerProperty("col 4", String.class, "");
+ t.setCellStyleGenerator(new CellStyleGenerator() {
+
+ public String getStyle(Object itemId, Object propertyId) {
+ if ("col 1 (red)".equals(propertyId)) {
+ return "red";
+ }
+
+ if ("col 3 (green)".equals(propertyId)) {
+ return "green";
+ }
+
+ return null;
+ }
+ });
+
+ t.addItem(new Object[] { "Col 1-1", "Col 2-1", "Col 4-1" },
+ new Object());
+ t.addItem(new Object[] { "Col 1-2", "Col 2-2", "Col 4-2" },
+ new Object());
+ t.addItem(new Object[] { "Col 1-3", "Col 2-3", "Col 4-3" },
+ new Object());
+
+ t.setColumnReorderingAllowed(true);
+ t.setColumnCollapsingAllowed(true);
+ setTheme("tests-tickets");
+ mainWindow.addComponent(t);
+
+ }
+
+ }
- package com.vaadin.tests.tickets;\r
- \r
- import com.vaadin.Application;\r
- import com.vaadin.ui.Button;\r
- import com.vaadin.ui.Button.ClickEvent;\r
- import com.vaadin.ui.Button.ClickListener;\r
- import com.vaadin.ui.ComboBox;\r
- import com.vaadin.ui.GridLayout;\r
- import com.vaadin.ui.Label;\r
- import com.vaadin.ui.Root.LegacyWindow;\r
- \r
- public class Ticket2209 extends Application.LegacyApplication {\r
- \r
- private GridLayout gl;\r
- private ComboBox combo;\r
- private Label labelLong;\r
- \r
- @Override\r
- public void init() {\r
- setMainWindow(new LegacyWindow());\r
- \r
- gl = new GridLayout(1, 2);\r
- gl.setStyleName("borders");\r
- getMainWindow().addComponent(gl);\r
- setTheme("tests-tickets");\r
- combo = new ComboBox("Combo caption");\r
- labelLong = new Label(\r
- "A long label, longer than the combo box. Why doesn't it affect the width? And why is the gridlayout so high?");\r
- gl.addComponent(combo);\r
- gl.addComponent(labelLong);\r
- \r
- Button b = new Button("Add label text", new ClickListener() {\r
- \r
- public void buttonClick(ClickEvent event) {\r
- labelLong.setValue(labelLong.getValue() + "-12345");\r
- }\r
- \r
- });\r
- getMainWindow().addComponent(b);\r
- }\r
- \r
- }\r
+ package com.vaadin.tests.tickets;
+
+ import com.vaadin.Application;
+ import com.vaadin.ui.Button;
+ import com.vaadin.ui.Button.ClickEvent;
+ import com.vaadin.ui.Button.ClickListener;
+ import com.vaadin.ui.ComboBox;
+ import com.vaadin.ui.GridLayout;
+ import com.vaadin.ui.Label;
-import com.vaadin.ui.Window;
++import com.vaadin.ui.Root.LegacyWindow;
+
-public class Ticket2209 extends Application {
++public class Ticket2209 extends Application.LegacyApplication {
+
+ private GridLayout gl;
+ private ComboBox combo;
+ private Label labelLong;
+
+ @Override
+ public void init() {
- setMainWindow(new Window());
++ setMainWindow(new LegacyWindow());
+
+ gl = new GridLayout(1, 2);
+ gl.setStyleName("borders");
+ getMainWindow().addComponent(gl);
+ setTheme("tests-tickets");
+ combo = new ComboBox("Combo caption");
+ labelLong = new Label(
+ "A long label, longer than the combo box. Why doesn't it affect the width? And why is the gridlayout so high?");
+ gl.addComponent(combo);
+ gl.addComponent(labelLong);
+
+ Button b = new Button("Add label text", new ClickListener() {
+
+ public void buttonClick(ClickEvent event) {
+ labelLong.setValue(labelLong.getValue() + "-12345");
+ }
+
+ });
+ getMainWindow().addComponent(b);
+ }
+
+ }
- package com.vaadin.tests.tickets;\r
- \r
- import com.vaadin.Application;\r
- import com.vaadin.ui.Button;\r
- import com.vaadin.ui.Button.ClickEvent;\r
- import com.vaadin.ui.Button.ClickListener;\r
- import com.vaadin.ui.ComboBox;\r
- import com.vaadin.ui.Label;\r
- import com.vaadin.ui.Root.LegacyWindow;\r
- import com.vaadin.ui.VerticalLayout;\r
- \r
- public class Ticket2209OL extends Application.LegacyApplication {\r
- \r
- private VerticalLayout gl;\r
- private ComboBox combo;\r
- private Label labelLong;\r
- \r
- @Override\r
- public void init() {\r
- setMainWindow(new LegacyWindow());\r
- getMainWindow().getContent().setWidth("250px");\r
- gl = new VerticalLayout();\r
- gl.setStyleName("borders");\r
- getMainWindow().addComponent(gl);\r
- setTheme("tests-tickets");\r
- combo = new ComboBox("Combo caption");\r
- labelLong = new Label(\r
- "This should stay on one line or to wrap to multiple lines? At leas it should display all the text?. "\r
- + "A long label, longer than the combo box. Why doesn't it affect the width? And why is the gridlayout so high?"\r
- + "A long label, longer than the combo box. Why doesn't it affect the width? And why is the gridlayout so high?"\r
- + "A long label, longer than the combo box. Why doesn't it affect the width? And why is the gridlayout so high?"\r
- + "A long label, longer than the combo box. Why doesn't it affect the width? And why is the gridlayout so high?"\r
- + "A long label, longer than the combo box. Why doesn't it affect the width? And why is the gridlayout so high?"\r
- + "A long label, longer than the combo box. Why doesn't it affect the width? And why is the gridlayout so high?"\r
- + "A long label, longer than the combo box. Why doesn't it affect the width? And why is the gridlayout so high?");\r
- gl.addComponent(combo);\r
- gl.addComponent(labelLong);\r
- \r
- Button b = new Button("Add label text", new ClickListener() {\r
- \r
- public void buttonClick(ClickEvent event) {\r
- labelLong.setValue(labelLong.getValue() + "-12345");\r
- }\r
- \r
- });\r
- getMainWindow().addComponent(b);\r
- }\r
- \r
- }\r
+ package com.vaadin.tests.tickets;
+
+ import com.vaadin.Application;
+ import com.vaadin.ui.Button;
+ import com.vaadin.ui.Button.ClickEvent;
+ import com.vaadin.ui.Button.ClickListener;
+ import com.vaadin.ui.ComboBox;
+ import com.vaadin.ui.Label;
++import com.vaadin.ui.Root.LegacyWindow;
+ import com.vaadin.ui.VerticalLayout;
-import com.vaadin.ui.Window;
+
-public class Ticket2209OL extends Application {
++public class Ticket2209OL extends Application.LegacyApplication {
+
+ private VerticalLayout gl;
+ private ComboBox combo;
+ private Label labelLong;
+
+ @Override
+ public void init() {
- setMainWindow(new Window());
++ setMainWindow(new LegacyWindow());
+ getMainWindow().getContent().setWidth("250px");
+ gl = new VerticalLayout();
+ gl.setStyleName("borders");
+ getMainWindow().addComponent(gl);
+ setTheme("tests-tickets");
+ combo = new ComboBox("Combo caption");
+ labelLong = new Label(
+ "This should stay on one line or to wrap to multiple lines? At leas it should display all the text?. "
+ + "A long label, longer than the combo box. Why doesn't it affect the width? And why is the gridlayout so high?"
+ + "A long label, longer than the combo box. Why doesn't it affect the width? And why is the gridlayout so high?"
+ + "A long label, longer than the combo box. Why doesn't it affect the width? And why is the gridlayout so high?"
+ + "A long label, longer than the combo box. Why doesn't it affect the width? And why is the gridlayout so high?"
+ + "A long label, longer than the combo box. Why doesn't it affect the width? And why is the gridlayout so high?"
+ + "A long label, longer than the combo box. Why doesn't it affect the width? And why is the gridlayout so high?"
+ + "A long label, longer than the combo box. Why doesn't it affect the width? And why is the gridlayout so high?");
+ gl.addComponent(combo);
+ gl.addComponent(labelLong);
+
+ Button b = new Button("Add label text", new ClickListener() {
+
+ public void buttonClick(ClickEvent event) {
+ labelLong.setValue(labelLong.getValue() + "-12345");
+ }
+
+ });
+ getMainWindow().addComponent(b);
+ }
+
+ }
- package com.vaadin.tests.tickets;\r
- \r
- import com.vaadin.Application;\r
- import com.vaadin.ui.Button;\r
- import com.vaadin.ui.Button.ClickEvent;\r
- import com.vaadin.ui.Button.ClickListener;\r
- import com.vaadin.ui.ComboBox;\r
- import com.vaadin.ui.Label;\r
- import com.vaadin.ui.Root.LegacyWindow;\r
- import com.vaadin.ui.VerticalLayout;\r
- \r
- public class Ticket2209OL2 extends Application.LegacyApplication {\r
- \r
- private VerticalLayout gl;\r
- private ComboBox combo;\r
- private Label labelLong;\r
- \r
- @Override\r
- public void init() {\r
- setMainWindow(new LegacyWindow());\r
- getMainWindow().getContent().setWidth("250px");\r
- gl = new VerticalLayout();\r
- gl.setSizeUndefined();\r
- gl.setStyleName("borders");\r
- getMainWindow().addComponent(gl);\r
- setTheme("tests-tickets");\r
- combo = new ComboBox("Combo caption");\r
- labelLong = new Label(\r
- "This should stay on one line or to wrap to multiple lines? At leas it should display all the text?. "\r
- + "A long label, longer than the combo box. Why doesn't it affect the width? And why is the gridlayout so high?"\r
- + "A long label, longer than the combo box. Why doesn't it affect the width? And why is the gridlayout so high?"\r
- + "A long label, longer than the combo box. Why doesn't it affect the width? And why is the gridlayout so high?"\r
- + "A long label, longer than the combo box. Why doesn't it affect the width? And why is the gridlayout so high?"\r
- + "A long label, longer than the combo box. Why doesn't it affect the width? And why is the gridlayout so high?"\r
- + "A long label, longer than the combo box. Why doesn't it affect the width? And why is the gridlayout so high?"\r
- + "A long label, longer than the combo box. Why doesn't it affect the width? And why is the gridlayout so high?"\r
- + "A long label, longer than the combo box. Why doesn't it affect the width? And why is the gridlayout so high?"\r
- + "A long label, longer than the combo box. Why doesn't it affect the width? And why is the gridlayout so high?"\r
- + "A long label, longer than the combo box. Why doesn't it affect the width? And why is the gridlayout so high?"\r
- + "A long label, longer than the combo box. Why doesn't it affect the width? And why is the gridlayout so high?"\r
- + "A long label, longer than the combo box. Why doesn't it affect the width? And why is the gridlayout so high?");\r
- gl.addComponent(combo);\r
- gl.addComponent(labelLong);\r
- \r
- Button b = new Button("Add label text", new ClickListener() {\r
- \r
- public void buttonClick(ClickEvent event) {\r
- labelLong.setValue(labelLong.getValue() + "-12345");\r
- }\r
- \r
- });\r
- getMainWindow().addComponent(b);\r
- }\r
- \r
- }\r
+ package com.vaadin.tests.tickets;
+
+ import com.vaadin.Application;
+ import com.vaadin.ui.Button;
+ import com.vaadin.ui.Button.ClickEvent;
+ import com.vaadin.ui.Button.ClickListener;
+ import com.vaadin.ui.ComboBox;
+ import com.vaadin.ui.Label;
++import com.vaadin.ui.Root.LegacyWindow;
+ import com.vaadin.ui.VerticalLayout;
-import com.vaadin.ui.Window;
+
-public class Ticket2209OL2 extends Application {
++public class Ticket2209OL2 extends Application.LegacyApplication {
+
+ private VerticalLayout gl;
+ private ComboBox combo;
+ private Label labelLong;
+
+ @Override
+ public void init() {
- setMainWindow(new Window());
++ setMainWindow(new LegacyWindow());
+ getMainWindow().getContent().setWidth("250px");
+ gl = new VerticalLayout();
+ gl.setSizeUndefined();
+ gl.setStyleName("borders");
+ getMainWindow().addComponent(gl);
+ setTheme("tests-tickets");
+ combo = new ComboBox("Combo caption");
+ labelLong = new Label(
+ "This should stay on one line or to wrap to multiple lines? At leas it should display all the text?. "
+ + "A long label, longer than the combo box. Why doesn't it affect the width? And why is the gridlayout so high?"
+ + "A long label, longer than the combo box. Why doesn't it affect the width? And why is the gridlayout so high?"
+ + "A long label, longer than the combo box. Why doesn't it affect the width? And why is the gridlayout so high?"
+ + "A long label, longer than the combo box. Why doesn't it affect the width? And why is the gridlayout so high?"
+ + "A long label, longer than the combo box. Why doesn't it affect the width? And why is the gridlayout so high?"
+ + "A long label, longer than the combo box. Why doesn't it affect the width? And why is the gridlayout so high?"
+ + "A long label, longer than the combo box. Why doesn't it affect the width? And why is the gridlayout so high?"
+ + "A long label, longer than the combo box. Why doesn't it affect the width? And why is the gridlayout so high?"
+ + "A long label, longer than the combo box. Why doesn't it affect the width? And why is the gridlayout so high?"
+ + "A long label, longer than the combo box. Why doesn't it affect the width? And why is the gridlayout so high?"
+ + "A long label, longer than the combo box. Why doesn't it affect the width? And why is the gridlayout so high?"
+ + "A long label, longer than the combo box. Why doesn't it affect the width? And why is the gridlayout so high?");
+ gl.addComponent(combo);
+ gl.addComponent(labelLong);
+
+ Button b = new Button("Add label text", new ClickListener() {
+
+ public void buttonClick(ClickEvent event) {
+ labelLong.setValue(labelLong.getValue() + "-12345");
+ }
+
+ });
+ getMainWindow().addComponent(b);
+ }
+
+ }
- package com.vaadin.tests.tickets;\r
- \r
- import com.vaadin.Application;\r
- import com.vaadin.ui.Label;\r
- import com.vaadin.ui.Panel;\r
- import com.vaadin.ui.Root.LegacyWindow;\r
- import com.vaadin.ui.VerticalLayout;\r
- import com.vaadin.ui.themes.Reindeer;\r
- \r
- public class Ticket2215 extends Application.LegacyApplication {\r
- \r
- @Override\r
- public void init() {\r
- setMainWindow(new LegacyWindow());\r
- \r
- VerticalLayout ol = new VerticalLayout();\r
- Panel p = new Panel("Test");\r
- p.addComponent(new Label("Panel1"));\r
- p.setHeight("500px");\r
- p.setWidth("500px");\r
- p.setStyleName(Reindeer.PANEL_LIGHT);\r
- ol.addComponent(p);\r
- ol.addComponent(new Label("NextComponent"));\r
- \r
- getMainWindow().addComponent(ol);\r
- \r
- }\r
- \r
- }\r
+ package com.vaadin.tests.tickets;
+
+ import com.vaadin.Application;
+ import com.vaadin.ui.Label;
+ import com.vaadin.ui.Panel;
++import com.vaadin.ui.Root.LegacyWindow;
+ import com.vaadin.ui.VerticalLayout;
-import com.vaadin.ui.Window;
+ import com.vaadin.ui.themes.Reindeer;
+
-public class Ticket2215 extends Application {
++public class Ticket2215 extends Application.LegacyApplication {
+
+ @Override
+ public void init() {
- setMainWindow(new Window());
++ setMainWindow(new LegacyWindow());
+
+ VerticalLayout ol = new VerticalLayout();
+ Panel p = new Panel("Test");
+ p.addComponent(new Label("Panel1"));
+ p.setHeight("500px");
+ p.setWidth("500px");
+ p.setStyleName(Reindeer.PANEL_LIGHT);
+ ol.addComponent(p);
+ ol.addComponent(new Label("NextComponent"));
+
+ getMainWindow().addComponent(ol);
+
+ }
+
+ }
- package com.vaadin.tests.tickets;\r
- \r
- import com.vaadin.Application;\r
- import com.vaadin.ui.Button;\r
- import com.vaadin.ui.GridLayout;\r
- import com.vaadin.ui.Label;\r
- import com.vaadin.ui.Layout;\r
- import com.vaadin.ui.Layout.SpacingHandler;\r
- import com.vaadin.ui.Root.LegacyWindow;\r
- import com.vaadin.ui.VerticalLayout;\r
- \r
- public class Ticket2232 extends Application.LegacyApplication {\r
- \r
- @Override\r
- public void init() {\r
- setMainWindow(new LegacyWindow());\r
- setTheme("tests-tickets");\r
- \r
- getMainWindow()\r
- .addComponent(\r
- new Label(\r
- "Defining spacing must be possible also with pure CSS"));\r
- \r
- Layout gl;\r
- gl = new VerticalLayout();\r
- gl.setWidth("100%");\r
- gl.setHeight("200px");\r
- gl.setStyleName("t2232");\r
- fillAndAdd(gl);\r
- \r
- gl = new GridLayout();\r
- gl.setWidth("100%");\r
- gl.setHeight("200px");\r
- gl.setStyleName("t2232");\r
- fillAndAdd(gl);\r
- \r
- gl = new VerticalLayout();\r
- gl.setWidth("100%");\r
- gl.setHeight("200px");\r
- ((SpacingHandler) gl).setSpacing(true);\r
- fillAndAdd(gl);\r
- \r
- gl = new GridLayout();\r
- gl.setWidth("100%");\r
- gl.setHeight("200px");\r
- ((SpacingHandler) gl).setSpacing(true);\r
- fillAndAdd(gl);\r
- \r
- gl = new VerticalLayout();\r
- gl.setWidth("100%");\r
- gl.setHeight("200px");\r
- fillAndAdd(gl);\r
- \r
- gl = new GridLayout();\r
- gl.setWidth("100%");\r
- gl.setHeight("200px");\r
- fillAndAdd(gl);\r
- \r
- }\r
- \r
- private void fillAndAdd(Layout gl) {\r
- for (int i = 0; i < 4; i++) {\r
- Button b = new Button("B");\r
- b.setSizeFull();\r
- gl.addComponent(b);\r
- }\r
- String caption = gl.getClass().getSimpleName();\r
- caption += " style: " + gl.getStyleName() + ", spacingFromServer:"\r
- + ((SpacingHandler) gl).isSpacing();\r
- gl.setCaption(caption);\r
- getMainWindow().addComponent(gl);\r
- }\r
- \r
- }\r
+ package com.vaadin.tests.tickets;
+
+ import com.vaadin.Application;
+ import com.vaadin.ui.Button;
+ import com.vaadin.ui.GridLayout;
+ import com.vaadin.ui.Label;
+ import com.vaadin.ui.Layout;
+ import com.vaadin.ui.Layout.SpacingHandler;
++import com.vaadin.ui.Root.LegacyWindow;
+ import com.vaadin.ui.VerticalLayout;
-import com.vaadin.ui.Window;
+
-public class Ticket2232 extends Application {
++public class Ticket2232 extends Application.LegacyApplication {
+
+ @Override
+ public void init() {
- setMainWindow(new Window());
++ setMainWindow(new LegacyWindow());
+ setTheme("tests-tickets");
+
+ getMainWindow()
+ .addComponent(
+ new Label(
+ "Defining spacing must be possible also with pure CSS"));
+
+ Layout gl;
+ gl = new VerticalLayout();
+ gl.setWidth("100%");
+ gl.setHeight("200px");
+ gl.setStyleName("t2232");
+ fillAndAdd(gl);
+
+ gl = new GridLayout();
+ gl.setWidth("100%");
+ gl.setHeight("200px");
+ gl.setStyleName("t2232");
+ fillAndAdd(gl);
+
+ gl = new VerticalLayout();
+ gl.setWidth("100%");
+ gl.setHeight("200px");
+ ((SpacingHandler) gl).setSpacing(true);
+ fillAndAdd(gl);
+
+ gl = new GridLayout();
+ gl.setWidth("100%");
+ gl.setHeight("200px");
+ ((SpacingHandler) gl).setSpacing(true);
+ fillAndAdd(gl);
+
+ gl = new VerticalLayout();
+ gl.setWidth("100%");
+ gl.setHeight("200px");
+ fillAndAdd(gl);
+
+ gl = new GridLayout();
+ gl.setWidth("100%");
+ gl.setHeight("200px");
+ fillAndAdd(gl);
+
+ }
+
+ private void fillAndAdd(Layout gl) {
+ for (int i = 0; i < 4; i++) {
+ Button b = new Button("B");
+ b.setSizeFull();
+ gl.addComponent(b);
+ }
+ String caption = gl.getClass().getSimpleName();
+ caption += " style: " + gl.getStyleName() + ", spacingFromServer:"
+ + ((SpacingHandler) gl).isSpacing();
+ gl.setCaption(caption);
+ getMainWindow().addComponent(gl);
+ }
+
+ }
- package com.vaadin.tests.tickets;\r
- \r
- import java.net.URL;\r
- \r
- import com.vaadin.ui.Label;\r
- import com.vaadin.ui.Label.ContentMode;\r
- import com.vaadin.ui.Root.LegacyWindow;\r
- \r
- public class Ticket2287 extends Ticket2292 {\r
- \r
- @Override\r
- public void init() {\r
- final LegacyWindow main = new LegacyWindow(getClass().getName()\r
- .substring(getClass().getName().lastIndexOf(".") + 1));\r
- setMainWindow(main);\r
- URL url = getURL();\r
- main.addComponent(new Label(\r
- "Icon is built by servlet with a slow method, so it will show the bug (components not firing requestLayout)."));\r
- \r
- Label l = new Label();\r
- l.setContentMode(ContentMode.XHTML);\r
- l.setValue("This is a label with as slow image. <img src=\"" + url\r
- + "/icon.png\" />");\r
- main.addComponent(l);\r
- \r
- l = new Label();\r
- l.setContentMode(ContentMode.XHTML);\r
- l.setValue("This is a label with as slow image. <img src=\"" + url\r
- + "/icon.png\" />");\r
- main.addComponent(l);\r
- \r
- }\r
+ package com.vaadin.tests.tickets;
+
+ import java.net.URL;
+
+ import com.vaadin.ui.Label;
-import com.vaadin.ui.Window;
++import com.vaadin.ui.Label.ContentMode;
++import com.vaadin.ui.Root.LegacyWindow;
+
+ public class Ticket2287 extends Ticket2292 {
+
+ @Override
+ public void init() {
- final Window main = new Window(getClass().getName().substring(
- getClass().getName().lastIndexOf(".") + 1));
++ final LegacyWindow main = new LegacyWindow(getClass().getName()
++ .substring(getClass().getName().lastIndexOf(".") + 1));
+ setMainWindow(main);
+ URL url = getURL();
+ main.addComponent(new Label(
+ "Icon is built by servlet with a slow method, so it will show the bug (components not firing requestLayout)."));
+
+ Label l = new Label();
- l.setContentMode(Label.CONTENT_XHTML);
++ l.setContentMode(ContentMode.XHTML);
+ l.setValue("This is a label with as slow image. <img src=\"" + url
+ + "/icon.png\" />");
+ main.addComponent(l);
+
+ l = new Label();
- l.setContentMode(Label.CONTENT_XHTML);
++ l.setContentMode(ContentMode.XHTML);
+ l.setValue("This is a label with as slow image. <img src=\"" + url
+ + "/icon.png\" />");
+ main.addComponent(l);
+
+ }
}
- package com.vaadin.tests.tickets;\r
- \r
- import java.awt.Color;\r
- import java.awt.Graphics;\r
- import java.awt.image.BufferedImage;\r
- import java.io.ByteArrayInputStream;\r
- import java.io.ByteArrayOutputStream;\r
- import java.io.IOException;\r
- \r
- import javax.imageio.ImageIO;\r
- \r
- import com.vaadin.Application;\r
- import com.vaadin.terminal.DownloadStream;\r
- import com.vaadin.terminal.ExternalResource;\r
- import com.vaadin.terminal.RequestHandler;\r
- import com.vaadin.terminal.WrappedRequest;\r
- import com.vaadin.terminal.WrappedResponse;\r
- import com.vaadin.ui.Button;\r
- import com.vaadin.ui.CheckBox;\r
- import com.vaadin.ui.Label;\r
- import com.vaadin.ui.Link;\r
- import com.vaadin.ui.Root.LegacyWindow;\r
- \r
- public class Ticket2292 extends com.vaadin.Application.LegacyApplication\r
- implements RequestHandler {\r
- \r
- @Override\r
- public void init() {\r
- final LegacyWindow main = new LegacyWindow(getClass().getName()\r
- .substring(getClass().getName().lastIndexOf(".") + 1));\r
- setMainWindow(main);\r
- \r
- ExternalResource icon = new ExternalResource("./icon.png");\r
- main.addComponent(new Label(\r
- "Note, run with trailing slash in url to have a working icon. Icon is built by servlet with a slow method, so it will show the bug (components not firing requestLayout)"));\r
- Button b = new Button();\r
- main.addComponent(b);\r
- b.setIcon(icon);\r
- \r
- CheckBox checkBox = new CheckBox();\r
- main.addComponent(checkBox);\r
- checkBox.setIcon(icon);\r
- \r
- Link l = new Link("l", icon);\r
- main.addComponent(l);\r
- \r
- addRequestHandler(this);\r
- }\r
- \r
- public boolean handleRequest(Application application,\r
- WrappedRequest request, WrappedResponse response)\r
- throws IOException {\r
- String relativeUri = request.getRequestPathInfo();\r
- \r
- if (!relativeUri.contains("icon.png")) {\r
- return false;\r
- }\r
- \r
- // be slow to show bug\r
- try {\r
- Thread.sleep(2000);\r
- } catch (InterruptedException e1) {\r
- // TODO Auto-generated catch block\r
- e1.printStackTrace();\r
- }\r
- \r
- BufferedImage image = new BufferedImage(200, 200,\r
- BufferedImage.TYPE_INT_RGB);\r
- Graphics drawable = image.getGraphics();\r
- drawable.setColor(Color.lightGray);\r
- drawable.fillRect(0, 0, 200, 200);\r
- drawable.setColor(Color.yellow);\r
- drawable.fillOval(25, 25, 150, 150);\r
- drawable.setColor(Color.blue);\r
- drawable.drawRect(0, 0, 199, 199);\r
- \r
- // Use the parameter to create dynamic content.\r
- drawable.setColor(Color.black);\r
- drawable.drawString("Tex", 75, 100);\r
- \r
- try {\r
- // Write the image to a buffer.\r
- ByteArrayOutputStream imagebuffer = new ByteArrayOutputStream();\r
- ImageIO.write(image, "png", imagebuffer);\r
- \r
- // Return a stream from the buffer.\r
- ByteArrayInputStream istream = new ByteArrayInputStream(\r
- imagebuffer.toByteArray());\r
- new DownloadStream(istream, null, null).writeTo(response);\r
- return true;\r
- } catch (IOException e) {\r
- return false;\r
- }\r
- }\r
- \r
- }\r
+ package com.vaadin.tests.tickets;
+
+ import java.awt.Color;
+ import java.awt.Graphics;
+ import java.awt.image.BufferedImage;
+ import java.io.ByteArrayInputStream;
+ import java.io.ByteArrayOutputStream;
+ import java.io.IOException;
-import java.net.URL;
+
+ import javax.imageio.ImageIO;
+
++import com.vaadin.Application;
+ import com.vaadin.terminal.DownloadStream;
+ import com.vaadin.terminal.ExternalResource;
++import com.vaadin.terminal.RequestHandler;
++import com.vaadin.terminal.WrappedRequest;
++import com.vaadin.terminal.WrappedResponse;
+ import com.vaadin.ui.Button;
+ import com.vaadin.ui.CheckBox;
+ import com.vaadin.ui.Label;
+ import com.vaadin.ui.Link;
-import com.vaadin.ui.Window;
++import com.vaadin.ui.Root.LegacyWindow;
+
-public class Ticket2292 extends com.vaadin.Application {
++public class Ticket2292 extends com.vaadin.Application.LegacyApplication
++ implements RequestHandler {
+
+ @Override
+ public void init() {
- final Window main = new Window(getClass().getName().substring(
- getClass().getName().lastIndexOf(".") + 1));
++ final LegacyWindow main = new LegacyWindow(getClass().getName()
++ .substring(getClass().getName().lastIndexOf(".") + 1));
+ setMainWindow(main);
+
+ ExternalResource icon = new ExternalResource("./icon.png");
+ main.addComponent(new Label(
+ "Note, run with trailing slash in url to have a working icon. Icon is built by servlet with a slow method, so it will show the bug (components not firing requestLayout)"));
+ Button b = new Button();
+ main.addComponent(b);
+ b.setIcon(icon);
+
+ CheckBox checkBox = new CheckBox();
+ main.addComponent(checkBox);
+ checkBox.setIcon(icon);
+
+ Link l = new Link("l", icon);
+ main.addComponent(l);
+
++ addRequestHandler(this);
+ }
+
- @Override
- public DownloadStream handleURI(URL context, String relativeUri) {
++ public boolean handleRequest(Application application,
++ WrappedRequest request, WrappedResponse response)
++ throws IOException {
++ String relativeUri = request.getRequestPathInfo();
++
+ if (!relativeUri.contains("icon.png")) {
- return null;
++ return false;
+ }
+
+ // be slow to show bug
+ try {
+ Thread.sleep(2000);
+ } catch (InterruptedException e1) {
+ // TODO Auto-generated catch block
+ e1.printStackTrace();
+ }
+
+ BufferedImage image = new BufferedImage(200, 200,
+ BufferedImage.TYPE_INT_RGB);
+ Graphics drawable = image.getGraphics();
+ drawable.setColor(Color.lightGray);
+ drawable.fillRect(0, 0, 200, 200);
+ drawable.setColor(Color.yellow);
+ drawable.fillOval(25, 25, 150, 150);
+ drawable.setColor(Color.blue);
+ drawable.drawRect(0, 0, 199, 199);
+
+ // Use the parameter to create dynamic content.
+ drawable.setColor(Color.black);
+ drawable.drawString("Tex", 75, 100);
+
+ try {
+ // Write the image to a buffer.
+ ByteArrayOutputStream imagebuffer = new ByteArrayOutputStream();
+ ImageIO.write(image, "png", imagebuffer);
+
+ // Return a stream from the buffer.
+ ByteArrayInputStream istream = new ByteArrayInputStream(
+ imagebuffer.toByteArray());
- return new DownloadStream(istream, null, null);
++ new DownloadStream(istream, null, null).writeTo(response);
++ return true;
+ } catch (IOException e) {
- return null;
++ return false;
+ }
+ }
+
+ }
- package com.vaadin.tests.tickets;\r
- \r
- import java.io.ByteArrayInputStream;\r
- import java.io.IOException;\r
- import java.net.URL;\r
- \r
- import com.vaadin.ui.CustomLayout;\r
- import com.vaadin.ui.Label;\r
- import com.vaadin.ui.Root.LegacyWindow;\r
- \r
- public class Ticket2297 extends Ticket2292 {\r
- \r
- @Override\r
- public void init() {\r
- final LegacyWindow main = new LegacyWindow(getClass().getName()\r
- .substring(getClass().getName().lastIndexOf(".") + 1));\r
- setMainWindow(main);\r
- URL url = getURL();\r
- main.addComponent(new Label(\r
- "Icon is built by servlet with a slow method, so it will show the bug (components not firing requestLayout)."));\r
- \r
- try {\r
- CustomLayout cl = new CustomLayout(\r
- new ByteArrayInputStream(\r
- ("This is an empty CustomLayout with as slow image. <img src=\""\r
- + url.toString() + "/icon.png\" />")\r
- .getBytes()));\r
- main.addComponent(cl);\r
- \r
- cl = new CustomLayout(\r
- new ByteArrayInputStream(\r
- ("This is an empty CustomLayout with as slow image. <img src=\""\r
- + url.toString() + "/icon.png\" />")\r
- .getBytes()));\r
- main.addComponent(cl);\r
- } catch (IOException e) {\r
- // TODO Auto-generated catch block\r
- e.printStackTrace();\r
- }\r
- }\r
+ package com.vaadin.tests.tickets;
+
+ import java.io.ByteArrayInputStream;
+ import java.io.IOException;
+ import java.net.URL;
+
+ import com.vaadin.ui.CustomLayout;
+ import com.vaadin.ui.Label;
-import com.vaadin.ui.Window;
++import com.vaadin.ui.Root.LegacyWindow;
+
+ public class Ticket2297 extends Ticket2292 {
+
+ @Override
+ public void init() {
- final Window main = new Window(getClass().getName().substring(
- getClass().getName().lastIndexOf(".") + 1));
++ final LegacyWindow main = new LegacyWindow(getClass().getName()
++ .substring(getClass().getName().lastIndexOf(".") + 1));
+ setMainWindow(main);
+ URL url = getURL();
+ main.addComponent(new Label(
+ "Icon is built by servlet with a slow method, so it will show the bug (components not firing requestLayout)."));
+
+ try {
+ CustomLayout cl = new CustomLayout(
+ new ByteArrayInputStream(
+ ("This is an empty CustomLayout with as slow image. <img src=\""
+ + url.toString() + "/icon.png\" />")
+ .getBytes()));
+ main.addComponent(cl);
+
+ cl = new CustomLayout(
+ new ByteArrayInputStream(
+ ("This is an empty CustomLayout with as slow image. <img src=\""
+ + url.toString() + "/icon.png\" />")
+ .getBytes()));
+ main.addComponent(cl);
+ } catch (IOException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+ }
}
- package com.vaadin.tests.tickets;\r
- \r
- import java.io.ByteArrayInputStream;\r
- import java.io.IOException;\r
- \r
- import com.vaadin.Application;\r
- import com.vaadin.ui.CustomLayout;\r
- import com.vaadin.ui.Label;\r
- import com.vaadin.ui.Root.LegacyWindow;\r
- import com.vaadin.ui.VerticalLayout;\r
- \r
- public class Ticket2303 extends Application.LegacyApplication {\r
- \r
- @Override\r
- public void init() {\r
- LegacyWindow w = new LegacyWindow("main window");\r
- \r
- String customlayout = "<div location=\"test\"></div>";\r
- CustomLayout cl = null;\r
- try {\r
- cl = new CustomLayout(new ByteArrayInputStream(\r
- customlayout.getBytes()));\r
- } catch (IOException e) {\r
- // TODO Auto-generated catch block\r
- e.printStackTrace();\r
- }\r
- cl.setWidth("100%");\r
- w.setContent(cl);\r
- \r
- // VerticalLayout ol = new VerticalLayout();\r
- // w.setContent(ol);\r
- VerticalLayout hugeLayout = new VerticalLayout();\r
- hugeLayout.setMargin(true);\r
- hugeLayout.setSpacing(true);\r
- for (int i = 0; i < 30; i++) {\r
- hugeLayout.addComponent(new Label("huge " + i));\r
- }\r
- cl.addComponent(hugeLayout, "test");\r
- // ol.addComponent(hugeLayout);\r
- setMainWindow(w);\r
- }\r
- \r
- }\r
+ package com.vaadin.tests.tickets;
+
+ import java.io.ByteArrayInputStream;
+ import java.io.IOException;
+
+ import com.vaadin.Application;
+ import com.vaadin.ui.CustomLayout;
+ import com.vaadin.ui.Label;
++import com.vaadin.ui.Root.LegacyWindow;
+ import com.vaadin.ui.VerticalLayout;
-import com.vaadin.ui.Window;
+
-public class Ticket2303 extends Application {
++public class Ticket2303 extends Application.LegacyApplication {
+
+ @Override
+ public void init() {
- Window w = new Window("main window");
++ LegacyWindow w = new LegacyWindow("main window");
+
+ String customlayout = "<div location=\"test\"></div>";
+ CustomLayout cl = null;
+ try {
+ cl = new CustomLayout(new ByteArrayInputStream(
+ customlayout.getBytes()));
+ } catch (IOException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+ cl.setWidth("100%");
+ w.setContent(cl);
+
+ // VerticalLayout ol = new VerticalLayout();
+ // w.setContent(ol);
+ VerticalLayout hugeLayout = new VerticalLayout();
+ hugeLayout.setMargin(true);
+ hugeLayout.setSpacing(true);
+ for (int i = 0; i < 30; i++) {
+ hugeLayout.addComponent(new Label("huge " + i));
+ }
+ cl.addComponent(hugeLayout, "test");
+ // ol.addComponent(hugeLayout);
+ setMainWindow(w);
+ }
+
+ }
- package com.vaadin.tests.tickets;\r
- \r
- import com.vaadin.ui.Form;\r
- import com.vaadin.ui.Root.LegacyWindow;\r
- import com.vaadin.ui.TextField;\r
- import com.vaadin.ui.VerticalLayout;\r
- \r
- public class Ticket2407 extends com.vaadin.Application.LegacyApplication {\r
- \r
- @Override\r
- public void init() {\r
- final LegacyWindow main = new LegacyWindow("Ticket2407");\r
- setMainWindow(main);\r
- \r
- Form form = new Form(new VerticalLayout());\r
- TextField text = new TextField("This caption shall be visible");\r
- text.setRequired(true);\r
- form.addField("test", text);\r
- main.addComponent(form);\r
- }\r
- }\r
+ package com.vaadin.tests.tickets;
+
+ import com.vaadin.ui.Form;
++import com.vaadin.ui.Root.LegacyWindow;
+ import com.vaadin.ui.TextField;
+ import com.vaadin.ui.VerticalLayout;
-import com.vaadin.ui.Window;
+
-public class Ticket2407 extends com.vaadin.Application {
++public class Ticket2407 extends com.vaadin.Application.LegacyApplication {
+
+ @Override
+ public void init() {
- final Window main = new Window("Ticket2407");
++ final LegacyWindow main = new LegacyWindow("Ticket2407");
+ setMainWindow(main);
+
+ Form form = new Form(new VerticalLayout());
+ TextField text = new TextField("This caption shall be visible");
+ text.setRequired(true);
+ form.addField("test", text);
+ main.addComponent(form);
+ }
+ }
- package com.vaadin.tests.tickets;\r
- \r
- import com.vaadin.Application;\r
- import com.vaadin.ui.Button;\r
- import com.vaadin.ui.GridLayout;\r
- import com.vaadin.ui.Root.LegacyWindow;\r
- \r
- public class Ticket2411 extends Application.LegacyApplication {\r
- \r
- @Override\r
- public void init() {\r
- LegacyWindow w = new LegacyWindow(getClass().getSimpleName());\r
- setMainWindow(w);\r
- \r
- // VerticalLayout l = new VerticalLayout();\r
- GridLayout l = new GridLayout();\r
- w.setContent(l);\r
- \r
- l.setHeight("504px");\r
- \r
- for (int i = 1; i <= 5; i++) {\r
- Button b = new Button("Button " + i\r
- + " should be 100px or 101px high");\r
- b.setHeight("100%");\r
- l.addComponent(b);\r
- }\r
- }\r
- \r
- }\r
+ package com.vaadin.tests.tickets;
+
+ import com.vaadin.Application;
+ import com.vaadin.ui.Button;
+ import com.vaadin.ui.GridLayout;
-import com.vaadin.ui.Window;
++import com.vaadin.ui.Root.LegacyWindow;
+
-public class Ticket2411 extends Application {
++public class Ticket2411 extends Application.LegacyApplication {
+
+ @Override
+ public void init() {
- Window w = new Window(getClass().getSimpleName());
++ LegacyWindow w = new LegacyWindow(getClass().getSimpleName());
+ setMainWindow(w);
+
+ // VerticalLayout l = new VerticalLayout();
+ GridLayout l = new GridLayout();
+ w.setContent(l);
+
+ l.setHeight("504px");
+
+ for (int i = 1; i <= 5; i++) {
+ Button b = new Button("Button " + i
+ + " should be 100px or 101px high");
+ b.setHeight("100%");
+ l.addComponent(b);
+ }
+ }
+
+ }
- package com.vaadin.tests.tickets;\r
- \r
- import java.io.Serializable;\r
- import java.util.Calendar;\r
- import java.util.Date;\r
- import java.util.HashMap;\r
- import java.util.Map;\r
- import java.util.Random;\r
- import java.util.Set;\r
- \r
- import com.vaadin.Application;\r
- import com.vaadin.data.Container;\r
- import com.vaadin.data.Validator;\r
- import com.vaadin.data.util.BeanItemContainer;\r
- import com.vaadin.ui.ComboBox;\r
- import com.vaadin.ui.Component;\r
- import com.vaadin.ui.DateField;\r
- import com.vaadin.ui.DefaultFieldFactory;\r
- import com.vaadin.ui.Field;\r
- import com.vaadin.ui.FormLayout;\r
- import com.vaadin.ui.Layout;\r
- import com.vaadin.ui.ListSelect;\r
- import com.vaadin.ui.Panel;\r
- import com.vaadin.ui.Root.LegacyWindow;\r
- import com.vaadin.ui.Table;\r
- import com.vaadin.ui.TextField;\r
- import com.vaadin.ui.VerticalLayout;\r
- import com.vaadin.ui.Window;\r
- import com.vaadin.ui.themes.Reindeer;\r
- \r
- /**\r
- * Table layout is very slow in Firefox 3.0.10 when the table contains\r
- * components.\r
- * \r
- * This is adapted from the HbnContainer example application WorkoutLog.\r
- * \r
- * Other browsers are much faster.\r
- */\r
- public class Ticket2998 extends Application.LegacyApplication {\r
- private Table table;\r
- private VerticalLayout mainLayout;\r
- \r
- public class Workout implements Serializable {\r
- private Long id;\r
- private Date date = new Date();\r
- private String title = " -- new workout -- ";\r
- private float kilometers;\r
- \r
- private String trainingType;\r
- \r
- private Set<String> secondaryTypes;\r
- \r
- public Workout() {\r
- }\r
- \r
- public Long getId() {\r
- return id;\r
- }\r
- \r
- public Date getDate() {\r
- return date;\r
- }\r
- \r
- public void setDate(Date date) {\r
- this.date = date;\r
- }\r
- \r
- public String getTitle() {\r
- return title;\r
- }\r
- \r
- public void setTitle(String title) {\r
- this.title = title;\r
- }\r
- \r
- public float getKilometers() {\r
- return kilometers;\r
- }\r
- \r
- public void setKilometers(float kilometers) {\r
- this.kilometers = kilometers;\r
- }\r
- \r
- public String getTrainingType() {\r
- return trainingType;\r
- }\r
- \r
- public void setTrainingType(String trainingType) {\r
- this.trainingType = trainingType;\r
- }\r
- \r
- public void setSecondaryTypes(Set<String> secondaryTypes) {\r
- this.secondaryTypes = secondaryTypes;\r
- }\r
- \r
- public Set<String> getSecondaryTypes() {\r
- return secondaryTypes;\r
- }\r
- \r
- }\r
- \r
- public class WorkoutEditor extends Window {\r
- \r
- private DateField date = new DateField("Date");\r
- private TextField kilomiters = new TextField("Kilometers");\r
- private TextField title = new TextField("Title/note");\r
- \r
- private Ticket2998 workoutLog;\r
- \r
- public WorkoutEditor(Ticket2998 app) {\r
- super("Edit workout");\r
- workoutLog = app;\r
- Layout main = new VerticalLayout();\r
- setContent(main);\r
- main.setSizeUndefined();\r
- main.setStyleName(Reindeer.PANEL_LIGHT);\r
- \r
- FormLayout form = new FormLayout();\r
- form.setSizeUndefined();\r
- date.setResolution(DateField.RESOLUTION_MIN);\r
- form.addComponent(date);\r
- form.addComponent(kilomiters);\r
- form.addComponent(title);\r
- main.addComponent(form);\r
- \r
- }\r
- \r
- public void loadRun(Workout run) {\r
- if (run == null) {\r
- close();\r
- } else {\r
- date.setValue(run.getDate());\r
- kilomiters.setValue(String.valueOf(run.getKilometers()));\r
- title.setValue(run.getTitle());\r
- if (getParent() == null) {\r
- workoutLog.getMainWindow().addWindow(this);\r
- }\r
- kilomiters.focus();\r
- }\r
- }\r
- }\r
- \r
- public class MyFieldFactory extends DefaultFieldFactory {\r
- \r
- public MyFieldFactory(Ticket2998 app) {\r
- }\r
- \r
- @Override\r
- public Field<?> createField(Container container, Object itemId,\r
- Object propertyId, Component uiContext) {\r
- \r
- /*\r
- * trainingType is manyToOne relation, give it a combobox\r
- */\r
- if (propertyId.equals("trainingType")) {\r
- return getTrainingTypeComboboxFor(itemId);\r
- }\r
- \r
- /*\r
- * Secondarytypes is manyToMany relation, give it a multiselect list\r
- */\r
- if (propertyId.equals("secondaryTypes")) {\r
- return getSecondaryTypesList(itemId);\r
- }\r
- \r
- final Field<?> f = super.createField(container, itemId, propertyId,\r
- uiContext);\r
- if (f != null) {\r
- if (f instanceof TextField) {\r
- TextField tf = (TextField) f;\r
- tf.setWidth("100%");\r
- }\r
- if (propertyId.equals("kilometers")) {\r
- f.setWidth("4em");\r
- f.addValidator(new Validator() {\r
- public void validate(Object value)\r
- throws InvalidValueException {\r
- // FIXME this does not follow the standard pattern\r
- // for validators and has side effects!\r
- try {\r
- @SuppressWarnings("unused")\r
- float f = Float.parseFloat((String) value);\r
- } catch (Exception e) {\r
- f.getRoot()\r
- .showNotification("Bad number value");\r
- f.setValue(0);\r
- }\r
- }\r
- });\r
- }\r
- if (propertyId.equals("date")) {\r
- ((DateField) f).setResolution(DateField.RESOLUTION_MIN);\r
- }\r
- }\r
- return f;\r
- \r
- }\r
- \r
- private Map<Object, ListSelect> workoutIdToList = new HashMap<Object, ListSelect>();\r
- \r
- private Field<?> getSecondaryTypesList(Object itemId) {\r
- ListSelect list = workoutIdToList.get(itemId);\r
- if (list == null) {\r
- list = new ListSelect();\r
- list.setMultiSelect(true);\r
- list.addItem("Item1");\r
- list.addItem("Item2");\r
- list.addItem("Item3");\r
- list.addItem("Item4");\r
- list.addItem("Item5");\r
- // list.setContainerDataSource(trainingTypes);\r
- list.setRows(4);\r
- workoutIdToList.put(itemId, list);\r
- }\r
- return list;\r
- }\r
- \r
- private Map<Object, ComboBox> workoutIdToCombobox = new HashMap<Object, ComboBox>();\r
- \r
- private Field<?> getTrainingTypeComboboxFor(Object itemId) {\r
- ComboBox cb = workoutIdToCombobox.get(itemId);\r
- if (cb == null) {\r
- final ComboBox cb2 = new ComboBox();\r
- cb2.addItem("value1");\r
- cb2.addItem("value2");\r
- cb2.addItem("value3");\r
- cb2.addItem("value4");\r
- cb2.setNewItemsAllowed(true);\r
- \r
- workoutIdToCombobox.put(itemId, cb2);\r
- cb = cb2;\r
- }\r
- return cb;\r
- }\r
- }\r
- \r
- @Override\r
- public void init() {\r
- buildView();\r
- setTheme("reindeer");\r
- }\r
- \r
- /**\r
- * Builds a simple view for application with Table and a row of buttons\r
- * below it.\r
- */\r
- private void buildView() {\r
- \r
- final LegacyWindow w = new LegacyWindow("Workout Log");\r
- \r
- // set theme and some layout stuff\r
- setMainWindow(w);\r
- w.getContent().setSizeFull();\r
- ((Layout) w.getContent()).setMargin(false);\r
- \r
- Panel p = new Panel("Workout Log");\r
- p.setStyleName(Reindeer.PANEL_LIGHT);\r
- w.addComponent(p);\r
- mainLayout = new VerticalLayout();\r
- p.setContent(mainLayout);\r
- \r
- populateAndConfigureTable();\r
- \r
- mainLayout.addComponent(table);\r
- \r
- // make table consume all extra space\r
- p.setSizeFull();\r
- mainLayout.setSizeFull();\r
- mainLayout.setExpandRatio(table, 1);\r
- table.setSizeFull();\r
- }\r
- \r
- protected void populateAndConfigureTable() {\r
- table = new Table();\r
- \r
- table.setWidth("100%");\r
- table.setSelectable(true);\r
- table.setImmediate(true);\r
- table.setColumnCollapsingAllowed(true);\r
- table.setColumnWidth("date", 200);\r
- table.setColumnWidth("kilometers", 100);\r
- // table.addListener(this);\r
- table.setTableFieldFactory(new MyFieldFactory(this));\r
- \r
- loadWorkouts();\r
- \r
- table.setEditable(true);\r
- }\r
- \r
- /**\r
- * Loads container to Table\r
- */\r
- protected void loadWorkouts() {\r
- final BeanItemContainer<Workout> cont;\r
- // Use plain HbnContainer\r
- cont = new BeanItemContainer<Workout>(Workout.class);\r
- table.setContainerDataSource(cont);\r
- \r
- // insert some sample data\r
- Calendar c = Calendar.getInstance();\r
- c.set(Calendar.MILLISECOND, 0);\r
- c.set(Calendar.SECOND, 0);\r
- c.set(Calendar.MINUTE, 0);\r
- \r
- String[] titles = new String[] { "A short easy one", "intervals",\r
- "very long", "just shaking legs after work",\r
- "long one with Paul", "test run" };\r
- \r
- c.add(Calendar.DATE, -1000);\r
- \r
- Random rnd = new Random();\r
- \r
- Workout r;\r
- \r
- for (int i = 0; i < 1000; i++) {\r
- r = new Workout();\r
- c.set(Calendar.HOUR_OF_DAY,\r
- 12 + (rnd.nextInt(11) - rnd.nextInt(11)));\r
- r.setDate(c.getTime());\r
- r.setTitle(titles[rnd.nextInt(titles.length)]);\r
- r.setKilometers(Math.round(rnd.nextFloat() * 30));\r
- r.setTrainingType("tt");\r
- c.add(Calendar.DATE, 1);\r
- cont.addBean(r);\r
- }\r
- }\r
- \r
- }\r
+ package com.vaadin.tests.tickets;
+
+ import java.io.Serializable;
+ import java.util.Calendar;
+ import java.util.Date;
+ import java.util.HashMap;
+ import java.util.Map;
+ import java.util.Random;
+ import java.util.Set;
+
+ import com.vaadin.Application;
+ import com.vaadin.data.Container;
+ import com.vaadin.data.Validator;
+ import com.vaadin.data.util.BeanItemContainer;
+ import com.vaadin.ui.ComboBox;
+ import com.vaadin.ui.Component;
+ import com.vaadin.ui.DateField;
+ import com.vaadin.ui.DefaultFieldFactory;
+ import com.vaadin.ui.Field;
+ import com.vaadin.ui.FormLayout;
+ import com.vaadin.ui.Layout;
+ import com.vaadin.ui.ListSelect;
+ import com.vaadin.ui.Panel;
++import com.vaadin.ui.Root.LegacyWindow;
+ import com.vaadin.ui.Table;
+ import com.vaadin.ui.TextField;
+ import com.vaadin.ui.VerticalLayout;
+ import com.vaadin.ui.Window;
+ import com.vaadin.ui.themes.Reindeer;
+
+ /**
+ * Table layout is very slow in Firefox 3.0.10 when the table contains
+ * components.
+ *
+ * This is adapted from the HbnContainer example application WorkoutLog.
+ *
+ * Other browsers are much faster.
+ */
-public class Ticket2998 extends Application {
++public class Ticket2998 extends Application.LegacyApplication {
+ private Table table;
+ private VerticalLayout mainLayout;
+
+ public class Workout implements Serializable {
+ private Long id;
+ private Date date = new Date();
+ private String title = " -- new workout -- ";
+ private float kilometers;
+
+ private String trainingType;
+
+ private Set<String> secondaryTypes;
+
+ public Workout() {
+ }
+
+ public Long getId() {
+ return id;
+ }
+
+ public Date getDate() {
+ return date;
+ }
+
+ public void setDate(Date date) {
+ this.date = date;
+ }
+
+ public String getTitle() {
+ return title;
+ }
+
+ public void setTitle(String title) {
+ this.title = title;
+ }
+
+ public float getKilometers() {
+ return kilometers;
+ }
+
+ public void setKilometers(float kilometers) {
+ this.kilometers = kilometers;
+ }
+
+ public String getTrainingType() {
+ return trainingType;
+ }
+
+ public void setTrainingType(String trainingType) {
+ this.trainingType = trainingType;
+ }
+
+ public void setSecondaryTypes(Set<String> secondaryTypes) {
+ this.secondaryTypes = secondaryTypes;
+ }
+
+ public Set<String> getSecondaryTypes() {
+ return secondaryTypes;
+ }
+
+ }
+
+ public class WorkoutEditor extends Window {
+
+ private DateField date = new DateField("Date");
+ private TextField kilomiters = new TextField("Kilometers");
+ private TextField title = new TextField("Title/note");
+
+ private Ticket2998 workoutLog;
+
+ public WorkoutEditor(Ticket2998 app) {
+ super("Edit workout");
+ workoutLog = app;
+ Layout main = new VerticalLayout();
+ setContent(main);
+ main.setSizeUndefined();
+ main.setStyleName(Reindeer.PANEL_LIGHT);
+
+ FormLayout form = new FormLayout();
+ form.setSizeUndefined();
+ date.setResolution(DateField.RESOLUTION_MIN);
+ form.addComponent(date);
+ form.addComponent(kilomiters);
+ form.addComponent(title);
+ main.addComponent(form);
+
+ }
+
+ public void loadRun(Workout run) {
+ if (run == null) {
+ close();
+ } else {
+ date.setValue(run.getDate());
- kilomiters.setValue(run.getKilometers());
++ kilomiters.setValue(String.valueOf(run.getKilometers()));
+ title.setValue(run.getTitle());
+ if (getParent() == null) {
+ workoutLog.getMainWindow().addWindow(this);
+ }
+ kilomiters.focus();
+ }
+ }
+ }
+
+ public class MyFieldFactory extends DefaultFieldFactory {
+
+ public MyFieldFactory(Ticket2998 app) {
+ }
+
+ @Override
- public Field createField(Container container, Object itemId,
++ public Field<?> createField(Container container, Object itemId,
+ Object propertyId, Component uiContext) {
+
+ /*
+ * trainingType is manyToOne relation, give it a combobox
+ */
+ if (propertyId.equals("trainingType")) {
+ return getTrainingTypeComboboxFor(itemId);
+ }
+
+ /*
+ * Secondarytypes is manyToMany relation, give it a multiselect list
+ */
+ if (propertyId.equals("secondaryTypes")) {
+ return getSecondaryTypesList(itemId);
+ }
+
- final Field f = super.createField(container, itemId, propertyId,
++ final Field<?> f = super.createField(container, itemId, propertyId,
+ uiContext);
+ if (f != null) {
+ if (f instanceof TextField) {
+ TextField tf = (TextField) f;
+ tf.setWidth("100%");
+ }
+ if (propertyId.equals("kilometers")) {
+ f.setWidth("4em");
+ f.addValidator(new Validator() {
- public boolean isValid(Object value) {
++ public void validate(Object value)
++ throws InvalidValueException {
++ // FIXME this does not follow the standard pattern
++ // for validators and has side effects!
+ try {
+ @SuppressWarnings("unused")
+ float f = Float.parseFloat((String) value);
- return true;
+ } catch (Exception e) {
- f.getWindow().showNotification(
- "Bad number value");
++ f.getRoot()
++ .showNotification("Bad number value");
+ f.setValue(0);
- return false;
+ }
+ }
-
- public void validate(Object value)
- throws InvalidValueException {
- // TODO Auto-generated method stub
-
- }
+ });
+ }
+ if (propertyId.equals("date")) {
+ ((DateField) f).setResolution(DateField.RESOLUTION_MIN);
+ }
+ }
+ return f;
+
+ }
+
+ private Map<Object, ListSelect> workoutIdToList = new HashMap<Object, ListSelect>();
+
- private Field getSecondaryTypesList(Object itemId) {
++ private Field<?> getSecondaryTypesList(Object itemId) {
+ ListSelect list = workoutIdToList.get(itemId);
+ if (list == null) {
+ list = new ListSelect();
+ list.setMultiSelect(true);
+ list.addItem("Item1");
+ list.addItem("Item2");
+ list.addItem("Item3");
+ list.addItem("Item4");
+ list.addItem("Item5");
+ // list.setContainerDataSource(trainingTypes);
+ list.setRows(4);
+ workoutIdToList.put(itemId, list);
+ }
+ return list;
+ }
+
+ private Map<Object, ComboBox> workoutIdToCombobox = new HashMap<Object, ComboBox>();
+
- private Field getTrainingTypeComboboxFor(Object itemId) {
++ private Field<?> getTrainingTypeComboboxFor(Object itemId) {
+ ComboBox cb = workoutIdToCombobox.get(itemId);
+ if (cb == null) {
+ final ComboBox cb2 = new ComboBox();
+ cb2.addItem("value1");
+ cb2.addItem("value2");
+ cb2.addItem("value3");
+ cb2.addItem("value4");
+ cb2.setNewItemsAllowed(true);
+
+ workoutIdToCombobox.put(itemId, cb2);
+ cb = cb2;
+ }
+ return cb;
+ }
+ }
+
+ @Override
+ public void init() {
+ buildView();
+ setTheme("reindeer");
+ }
+
+ /**
+ * Builds a simple view for application with Table and a row of buttons
+ * below it.
+ */
+ private void buildView() {
+
- final Window w = new Window("Workout Log");
++ final LegacyWindow w = new LegacyWindow("Workout Log");
+
+ // set theme and some layout stuff
+ setMainWindow(w);
+ w.getContent().setSizeFull();
+ ((Layout) w.getContent()).setMargin(false);
+
+ Panel p = new Panel("Workout Log");
+ p.setStyleName(Reindeer.PANEL_LIGHT);
+ w.addComponent(p);
+ mainLayout = new VerticalLayout();
+ p.setContent(mainLayout);
+
+ populateAndConfigureTable();
+
+ mainLayout.addComponent(table);
+
+ // make table consume all extra space
+ p.setSizeFull();
+ mainLayout.setSizeFull();
+ mainLayout.setExpandRatio(table, 1);
+ table.setSizeFull();
+ }
+
+ protected void populateAndConfigureTable() {
+ table = new Table();
+
+ table.setWidth("100%");
+ table.setSelectable(true);
+ table.setImmediate(true);
+ table.setColumnCollapsingAllowed(true);
+ table.setColumnWidth("date", 200);
+ table.setColumnWidth("kilometers", 100);
+ // table.addListener(this);
+ table.setTableFieldFactory(new MyFieldFactory(this));
+
+ loadWorkouts();
+
+ table.setEditable(true);
+ }
+
+ /**
+ * Loads container to Table
+ */
+ protected void loadWorkouts() {
+ final BeanItemContainer<Workout> cont;
+ // Use plain HbnContainer
+ cont = new BeanItemContainer<Workout>(Workout.class);
+ table.setContainerDataSource(cont);
+
+ // insert some sample data
+ Calendar c = Calendar.getInstance();
+ c.set(Calendar.MILLISECOND, 0);
+ c.set(Calendar.SECOND, 0);
+ c.set(Calendar.MINUTE, 0);
+
+ String[] titles = new String[] { "A short easy one", "intervals",
+ "very long", "just shaking legs after work",
+ "long one with Paul", "test run" };
+
+ c.add(Calendar.DATE, -1000);
+
+ Random rnd = new Random();
+
+ Workout r;
+
+ for (int i = 0; i < 1000; i++) {
+ r = new Workout();
+ c.set(Calendar.HOUR_OF_DAY,
+ 12 + (rnd.nextInt(11) - rnd.nextInt(11)));
+ r.setDate(c.getTime());
+ r.setTitle(titles[rnd.nextInt(titles.length)]);
+ r.setKilometers(Math.round(rnd.nextFloat() * 30));
+ r.setTrainingType("tt");
+ c.add(Calendar.DATE, 1);
+ cont.addBean(r);
+ }
+ }
+
+ }
- package com.vaadin.tests.tickets;\r
- \r
- import java.util.Collection;\r
- import java.util.HashSet;\r
- \r
- import com.vaadin.Application;\r
- import com.vaadin.ui.Button;\r
- import com.vaadin.ui.Button.ClickEvent;\r
- import com.vaadin.ui.Root.LegacyWindow;\r
- import com.vaadin.ui.Table;\r
- import com.vaadin.ui.TextField;\r
- \r
- public class Ticket3146 extends Application.LegacyApplication {\r
- \r
- Table table;\r
- TextField result;\r
- \r
- @Override\r
- public void init() {\r
- LegacyWindow mainWindow = new LegacyWindow("Test");\r
- \r
- table = new Table();\r
- table.addContainerProperty("Items", String.class, null);\r
- table.addItem(new String[] { "a" }, "a");\r
- table.addItem(new String[] { "b" }, "b");\r
- table.addItem(new String[] { "c" }, "c");\r
- for (int i = 1; i < 100; ++i) {\r
- table.addItem(new String[] { "Item " + i }, "Item " + i);\r
- }\r
- table.setMultiSelect(true);\r
- table.setSelectable(true);\r
- table.setImmediate(true);\r
- table.setHeight("200px");\r
- table.setWidth("200px");\r
- mainWindow.addComponent(table);\r
- \r
- Button clearButton = new Button("Clear selection",\r
- new Button.ClickListener() {\r
- public void buttonClick(ClickEvent event) {\r
- clearSelection();\r
- }\r
- });\r
- mainWindow.addComponent(clearButton);\r
- Button clearButton2 = new Button("Clear selection 2",\r
- new Button.ClickListener() {\r
- public void buttonClick(ClickEvent event) {\r
- clearSelection2();\r
- }\r
- });\r
- mainWindow.addComponent(clearButton2);\r
- Button clearButton3 = new Button("Clear selection 3",\r
- new Button.ClickListener() {\r
- public void buttonClick(ClickEvent event) {\r
- clearSelection3();\r
- }\r
- });\r
- mainWindow.addComponent(clearButton3);\r
- Button printButton = new Button("Print selection",\r
- new Button.ClickListener() {\r
- public void buttonClick(ClickEvent event) {\r
- printSelection();\r
- }\r
- });\r
- mainWindow.addComponent(printButton);\r
- \r
- result = new TextField();\r
- result.setHeight("200px");\r
- result.setWidth("200px");\r
- mainWindow.addComponent(result);\r
- \r
- setMainWindow(mainWindow);\r
- }\r
- \r
- void clearSelection() {\r
- table.setValue(null);\r
- }\r
- \r
- void clearSelection2() {\r
- table.setValue(new HashSet<Object>());\r
- }\r
- \r
- void clearSelection3() {\r
- table.unselect("a");\r
- table.unselect("b");\r
- table.unselect("c");\r
- }\r
- \r
- void printSelection() {\r
- String selection = "";\r
- for (Object item : (Collection<?>) table.getValue()) {\r
- selection = selection + item + ' ';\r
- }\r
- result.setValue(selection);\r
- }\r
- \r
- }\r
+ package com.vaadin.tests.tickets;
+
+ import java.util.Collection;
+ import java.util.HashSet;
+
+ import com.vaadin.Application;
+ import com.vaadin.ui.Button;
+ import com.vaadin.ui.Button.ClickEvent;
++import com.vaadin.ui.Root.LegacyWindow;
+ import com.vaadin.ui.Table;
+ import com.vaadin.ui.TextField;
-import com.vaadin.ui.Window;
+
-public class Ticket3146 extends Application {
++public class Ticket3146 extends Application.LegacyApplication {
+
+ Table table;
+ TextField result;
+
+ @Override
+ public void init() {
- Window mainWindow = new Window("Test");
++ LegacyWindow mainWindow = new LegacyWindow("Test");
+
+ table = new Table();
+ table.addContainerProperty("Items", String.class, null);
+ table.addItem(new String[] { "a" }, "a");
+ table.addItem(new String[] { "b" }, "b");
+ table.addItem(new String[] { "c" }, "c");
+ for (int i = 1; i < 100; ++i) {
+ table.addItem(new String[] { "Item " + i }, "Item " + i);
+ }
+ table.setMultiSelect(true);
+ table.setSelectable(true);
+ table.setImmediate(true);
+ table.setHeight("200px");
+ table.setWidth("200px");
+ mainWindow.addComponent(table);
+
+ Button clearButton = new Button("Clear selection",
+ new Button.ClickListener() {
+ public void buttonClick(ClickEvent event) {
+ clearSelection();
+ }
+ });
+ mainWindow.addComponent(clearButton);
+ Button clearButton2 = new Button("Clear selection 2",
+ new Button.ClickListener() {
+ public void buttonClick(ClickEvent event) {
+ clearSelection2();
+ }
+ });
+ mainWindow.addComponent(clearButton2);
+ Button clearButton3 = new Button("Clear selection 3",
+ new Button.ClickListener() {
+ public void buttonClick(ClickEvent event) {
+ clearSelection3();
+ }
+ });
+ mainWindow.addComponent(clearButton3);
+ Button printButton = new Button("Print selection",
+ new Button.ClickListener() {
+ public void buttonClick(ClickEvent event) {
+ printSelection();
+ }
+ });
+ mainWindow.addComponent(printButton);
+
+ result = new TextField();
+ result.setHeight("200px");
+ result.setWidth("200px");
+ mainWindow.addComponent(result);
+
+ setMainWindow(mainWindow);
+ }
+
+ void clearSelection() {
+ table.setValue(null);
+ }
+
+ void clearSelection2() {
+ table.setValue(new HashSet<Object>());
+ }
+
+ void clearSelection3() {
+ table.unselect("a");
+ table.unselect("b");
+ table.unselect("c");
+ }
+
+ void printSelection() {
+ String selection = "";
+ for (Object item : (Collection<?>) table.getValue()) {
+ selection = selection + item + ' ';
+ }
+ result.setValue(selection);
+ }
+
+ }
- package com.vaadin.tests.tickets;\r
- \r
- import com.vaadin.Application;\r
- import com.vaadin.ui.ComboBox;\r
- import com.vaadin.ui.Root.LegacyWindow;\r
- \r
- /**\r
- * #5053: Last ComboBox item may not be shown if null selection enabled\r
- */\r
- public class Ticket5053 extends Application.LegacyApplication {\r
- \r
- @Override\r
- public void init() {\r
- LegacyWindow main = new LegacyWindow();\r
- setMainWindow(main);\r
- \r
- ComboBox combobox = new ComboBox("My ComboBox");\r
- \r
- // Enable null selection\r
- combobox.setNullSelectionAllowed(true);\r
- // Add the item that marks 'null' value\r
- String nullitem = "-- none --";\r
- combobox.addItem(nullitem);\r
- // Designate it was the 'null' value marker\r
- combobox.setNullSelectionItemId(nullitem);\r
- \r
- // Add some other items\r
- for (int i = 0; i < 10; i++) {\r
- combobox.addItem("Item " + i);\r
- }\r
- \r
- main.addComponent(combobox);\r
- }\r
- \r
- }\r
+ package com.vaadin.tests.tickets;
+
+ import com.vaadin.Application;
+ import com.vaadin.ui.ComboBox;
-import com.vaadin.ui.Window;
++import com.vaadin.ui.Root.LegacyWindow;
+
+ /**
+ * #5053: Last ComboBox item may not be shown if null selection enabled
+ */
-public class Ticket5053 extends Application {
++public class Ticket5053 extends Application.LegacyApplication {
+
+ @Override
+ public void init() {
- Window main = new Window();
++ LegacyWindow main = new LegacyWindow();
+ setMainWindow(main);
+
+ ComboBox combobox = new ComboBox("My ComboBox");
+
+ // Enable null selection
+ combobox.setNullSelectionAllowed(true);
+ // Add the item that marks 'null' value
+ String nullitem = "-- none --";
+ combobox.addItem(nullitem);
+ // Designate it was the 'null' value marker
+ combobox.setNullSelectionItemId(nullitem);
+
+ // Add some other items
+ for (int i = 0; i < 10; i++) {
+ combobox.addItem("Item " + i);
+ }
+
+ main.addComponent(combobox);
+ }
+
+ }
- package com.vaadin.tests.tickets;\r
- \r
- import com.vaadin.Application;\r
- import com.vaadin.event.ShortcutAction.KeyCode;\r
- import com.vaadin.event.ShortcutListener;\r
- import com.vaadin.ui.Label;\r
- import com.vaadin.ui.Panel;\r
- import com.vaadin.ui.Root.LegacyWindow;\r
- import com.vaadin.ui.TextField;\r
- \r
- /**\r
- * Key codes were converted to lower case on the server (overlapping special key\r
- * codes for function keys etc.) and then back to upper case on the client.\r
- * Therefore, registering e.g. F8 as a key code resulted in "w" being used as\r
- * the trigger and F8 being ignored.\r
- */\r
- public class Ticket5157 extends Application.LegacyApplication {\r
- \r
- @Override\r
- public void init() {\r
- final LegacyWindow mainWindow = new LegacyWindow(\r
- "Forumtests Application");\r
- setMainWindow(mainWindow);\r
- \r
- Panel p = new Panel();\r
- mainWindow.addComponent(p);\r
- \r
- Label l = new Label("Panel with F8 bound");\r
- p.addComponent(l);\r
- \r
- TextField f = new TextField();\r
- p.addComponent(f);\r
- \r
- p.addAction(new ShortcutListener("F8", KeyCode.F8, null) {\r
- \r
- @Override\r
- public void handleAction(Object sender, Object target) {\r
- mainWindow.showNotification(getCaption());\r
- \r
- }\r
- });\r
- \r
- p.addAction(new ShortcutListener("a", KeyCode.A, null) {\r
- \r
- @Override\r
- public void handleAction(Object sender, Object target) {\r
- mainWindow.showNotification(getCaption());\r
- \r
- }\r
- });\r
- }\r
- \r
- }\r
+ package com.vaadin.tests.tickets;
+
+ import com.vaadin.Application;
+ import com.vaadin.event.ShortcutAction.KeyCode;
+ import com.vaadin.event.ShortcutListener;
+ import com.vaadin.ui.Label;
+ import com.vaadin.ui.Panel;
++import com.vaadin.ui.Root.LegacyWindow;
+ import com.vaadin.ui.TextField;
-import com.vaadin.ui.Window;
+
+ /**
+ * Key codes were converted to lower case on the server (overlapping special key
+ * codes for function keys etc.) and then back to upper case on the client.
+ * Therefore, registering e.g. F8 as a key code resulted in "w" being used as
+ * the trigger and F8 being ignored.
+ */
-public class Ticket5157 extends Application {
++public class Ticket5157 extends Application.LegacyApplication {
+
+ @Override
+ public void init() {
- final Window mainWindow = new Window("Forumtests Application");
++ final LegacyWindow mainWindow = new LegacyWindow(
++ "Forumtests Application");
+ setMainWindow(mainWindow);
+
+ Panel p = new Panel();
+ mainWindow.addComponent(p);
+
+ Label l = new Label("Panel with F8 bound");
+ p.addComponent(l);
+
+ TextField f = new TextField();
+ p.addComponent(f);
+
+ p.addAction(new ShortcutListener("F8", KeyCode.F8, null) {
+
+ @Override
+ public void handleAction(Object sender, Object target) {
+ mainWindow.showNotification(getCaption());
+
+ }
+ });
+
+ p.addAction(new ShortcutListener("a", KeyCode.A, null) {
+
+ @Override
+ public void handleAction(Object sender, Object target) {
+ mainWindow.showNotification(getCaption());
+
+ }
+ });
+ }
+
+ }
- package com.vaadin.tests.tickets;\r
- \r
- import com.vaadin.Application;\r
- import com.vaadin.ui.Label;\r
- import com.vaadin.ui.Label.ContentMode;\r
- import com.vaadin.ui.Root.LegacyWindow;\r
- \r
- public class Ticket5952 extends Application.LegacyApplication {\r
- \r
- @Override\r
- public void init() {\r
- final LegacyWindow mainWindow = new LegacyWindow(\r
- "Forumtests Application");\r
- setMainWindow(mainWindow);\r
- \r
- String mathml = "<math mode='display' xmlns='http://www.w3.org/1998/Math/MathML'>"\r
- + "<mrow>"\r
- + " <msup>"\r
- + " <mi>x</mi>"\r
- + " <mn>2</mn>"\r
- + " </msup>"\r
- + " <msup>"\r
- + " <mi>c</mi>"\r
- + " <mn>2</mn>"\r
- + " </msup>"\r
- + " </mrow>" + "</math>";\r
- Label mathLabel = new Label(mathml, ContentMode.XML);\r
- mainWindow.addComponent(mathLabel);\r
- }\r
- }\r
+ package com.vaadin.tests.tickets;
+
+ import com.vaadin.Application;
+ import com.vaadin.ui.Label;
-import com.vaadin.ui.Window;
++import com.vaadin.ui.Label.ContentMode;
++import com.vaadin.ui.Root.LegacyWindow;
+
-public class Ticket5952 extends Application {
++public class Ticket5952 extends Application.LegacyApplication {
+
+ @Override
+ public void init() {
- final Window mainWindow = new Window("Forumtests Application");
++ final LegacyWindow mainWindow = new LegacyWindow(
++ "Forumtests Application");
+ setMainWindow(mainWindow);
-
- String mathml =
- "<math mode='display' xmlns='http://www.w3.org/1998/Math/MathML'>"+
- "<mrow>"+
- " <msup>"+
- " <mi>x</mi>"+
- " <mn>2</mn>"+
- " </msup>"+
- " <msup>"+
- " <mi>c</mi>"+
- " <mn>2</mn>"+
- " </msup>"+
- " </mrow>"+
- "</math>";
- Label mathLabel = new Label(mathml, Label.CONTENT_XML);
++
++ String mathml = "<math mode='display' xmlns='http://www.w3.org/1998/Math/MathML'>"
++ + "<mrow>"
++ + " <msup>"
++ + " <mi>x</mi>"
++ + " <mn>2</mn>"
++ + " </msup>"
++ + " <msup>"
++ + " <mi>c</mi>"
++ + " <mn>2</mn>"
++ + " </msup>"
++ + " </mrow>" + "</math>";
++ Label mathLabel = new Label(mathml, ContentMode.XML);
+ mainWindow.addComponent(mathLabel);
+ }
+ }
- package com.vaadin.tests.tickets;\r
- \r
- import com.vaadin.data.Property;\r
- import com.vaadin.data.Property.ValueChangeEvent;\r
- import com.vaadin.data.util.ObjectProperty;\r
- import com.vaadin.tests.components.TestBase;\r
- import com.vaadin.ui.Label;\r
- import com.vaadin.ui.Root.LegacyWindow;\r
- import com.vaadin.ui.TextField;\r
- import com.vaadin.ui.VerticalLayout;\r
- \r
- public class Ticket6002 extends TestBase {\r
- \r
- @Override\r
- public void setup() {\r
- LegacyWindow main = new LegacyWindow("The Main Window");\r
- setMainWindow(main);\r
- \r
- final VerticalLayout mainLayout = new VerticalLayout();\r
- main.setContent(mainLayout);\r
- \r
- mainLayout.addComponent(new Label(\r
- "Replace the floating-point values with an integer"));\r
- \r
- // ///////////////////////////////////////////////////\r
- // Better working case\r
- \r
- final ObjectProperty<Double> property1 = new ObjectProperty<Double>(\r
- new Double(42.0));\r
- \r
- // A text field that changes its caption\r
- final TextField tf1 = new TextField(\r
- "Changing this field modifies only the textfield", property1);\r
- tf1.addListener(new Property.ValueChangeListener() {\r
- public void valueChange(ValueChangeEvent event) {\r
- // This value change event is called twice if the new\r
- // input value is an integer. The second time is during\r
- // paint() of AbstractOrderedLayout.\r
- \r
- System.out.println("Value 2 is: " + property1.getValue());\r
- \r
- tf1.setCaption("With caption " + property1.getValue());\r
- }\r
- });\r
- tf1.setImmediate(true);\r
- mainLayout.addComponent(tf1);\r
- \r
- // ///////////////////////////////////////////////////\r
- // Totally failing case\r
- \r
- final ObjectProperty<Double> property2 = new ObjectProperty<Double>(\r
- new Double(42.0));\r
- \r
- // A text field that adds new components\r
- final TextField tf2 = new TextField(\r
- "Changing this field modifies the layout - do it twice",\r
- property2);\r
- tf2.addListener(new Property.ValueChangeListener() {\r
- public void valueChange(ValueChangeEvent event) {\r
- // This value change event is called twice if the new\r
- // input value is an integer. The second time is during\r
- // paint() of AbstractOrderedLayout.\r
- \r
- System.out.println("Value 1 is: " + property2.getValue());\r
- \r
- // When this listener is called the second time in paint(), the\r
- // add operation causes a ConcurrentModificationException\r
- mainLayout.addComponent(new Label(\r
- "Added a component, value is " + property2.getValue()));\r
- }\r
- });\r
- tf2.setImmediate(true);\r
- mainLayout.addComponent(tf2);\r
- \r
- mainLayout.setSpacing(true);\r
- }\r
- \r
- @Override\r
- protected String getDescription() {\r
- return "Change the numbers to integer value or add 0 in the decimal representation. "\r
- + "This causes a secondary call during paint() to reformat the value, which causes ConcurrentModificationException in the second case.";\r
- }\r
- \r
- @Override\r
- protected Integer getTicketNumber() {\r
- return 6002;\r
- }\r
- }\r
+ package com.vaadin.tests.tickets;
+
+ import com.vaadin.data.Property;
+ import com.vaadin.data.Property.ValueChangeEvent;
+ import com.vaadin.data.util.ObjectProperty;
+ import com.vaadin.tests.components.TestBase;
+ import com.vaadin.ui.Label;
++import com.vaadin.ui.Root.LegacyWindow;
+ import com.vaadin.ui.TextField;
+ import com.vaadin.ui.VerticalLayout;
-import com.vaadin.ui.Window;
+
+ public class Ticket6002 extends TestBase {
+
+ @Override
+ public void setup() {
- Window main = new Window("The Main Window");
++ LegacyWindow main = new LegacyWindow("The Main Window");
+ setMainWindow(main);
+
+ final VerticalLayout mainLayout = new VerticalLayout();
+ main.setContent(mainLayout);
+
+ mainLayout.addComponent(new Label(
+ "Replace the floating-point values with an integer"));
+
+ // ///////////////////////////////////////////////////
+ // Better working case
+
+ final ObjectProperty<Double> property1 = new ObjectProperty<Double>(
+ new Double(42.0));
+
+ // A text field that changes its caption
+ final TextField tf1 = new TextField(
+ "Changing this field modifies only the textfield", property1);
+ tf1.addListener(new Property.ValueChangeListener() {
+ public void valueChange(ValueChangeEvent event) {
+ // This value change event is called twice if the new
+ // input value is an integer. The second time is during
+ // paint() of AbstractOrderedLayout.
+
+ System.out.println("Value 2 is: " + property1.getValue());
+
+ tf1.setCaption("With caption " + property1.getValue());
+ }
+ });
+ tf1.setImmediate(true);
+ mainLayout.addComponent(tf1);
+
+ // ///////////////////////////////////////////////////
+ // Totally failing case
+
+ final ObjectProperty<Double> property2 = new ObjectProperty<Double>(
+ new Double(42.0));
+
+ // A text field that adds new components
+ final TextField tf2 = new TextField(
+ "Changing this field modifies the layout - do it twice",
+ property2);
+ tf2.addListener(new Property.ValueChangeListener() {
+ public void valueChange(ValueChangeEvent event) {
+ // This value change event is called twice if the new
+ // input value is an integer. The second time is during
+ // paint() of AbstractOrderedLayout.
+
+ System.out.println("Value 1 is: " + property2.getValue());
+
+ // When this listener is called the second time in paint(), the
+ // add operation causes a ConcurrentModificationException
+ mainLayout.addComponent(new Label(
+ "Added a component, value is " + property2.getValue()));
+ }
+ });
+ tf2.setImmediate(true);
+ mainLayout.addComponent(tf2);
+
+ mainLayout.setSpacing(true);
+ }
+
+ @Override
+ protected String getDescription() {
+ return "Change the numbers to integer value or add 0 in the decimal representation. "
+ + "This causes a secondary call during paint() to reformat the value, which causes ConcurrentModificationException in the second case.";
+ }
+
+ @Override
+ protected Integer getTicketNumber() {
+ return 6002;
+ }
+ }
- package com.vaadin.tests.tickets;\r
- \r
- import com.vaadin.Application;\r
- import com.vaadin.data.Container;\r
- import com.vaadin.data.Item;\r
- import com.vaadin.data.Property;\r
- import com.vaadin.data.util.BeanItem;\r
- import com.vaadin.ui.Button;\r
- import com.vaadin.ui.Button.ClickEvent;\r
- import com.vaadin.ui.Component;\r
- import com.vaadin.ui.ComponentContainer;\r
- import com.vaadin.ui.DefaultFieldFactory;\r
- import com.vaadin.ui.Field;\r
- import com.vaadin.ui.Form;\r
- import com.vaadin.ui.GridLayout;\r
- import com.vaadin.ui.HorizontalLayout;\r
- import com.vaadin.ui.Label;\r
- import com.vaadin.ui.Label.ContentMode;\r
- import com.vaadin.ui.Panel;\r
- import com.vaadin.ui.Root.LegacyWindow;\r
- import com.vaadin.ui.Table;\r
- import com.vaadin.ui.TextField;\r
- \r
- public class Ticket677 extends Application.LegacyApplication {\r
- \r
- private static final Label info = new Label(\r
- "<li> keep debug window open to see variable changes"\r
- + "<li> disable root panel w/ toggle button"\r
- + "<li> toggle one of the subpanels"\r
- + "<li> we attempt to focus the subpanels first textfield"\r
- + "<li> focusing should fail (try tabbing as well) [worked previousy]"\r
- + "<li> no variable changes should be sent from disabled fields [changed sent previously]"\r
- + "<li> try further toggling and tabbing around",\r
- ContentMode.RAW);\r
- \r
- Panel root = new Panel("Enabled");\r
- Panel one = new Panel("Enabled");\r
- Panel two = new Panel("Enabled");\r
- Form form;\r
- Table table;\r
- \r
- @Override\r
- public void init() {\r
- LegacyWindow main = new LegacyWindow();\r
- setMainWindow(main);\r
- \r
- main.addComponent(info);\r
- \r
- HorizontalLayout l = new HorizontalLayout();\r
- main.addComponent(l);\r
- \r
- l.addComponent(new Button("Toggle root panel",\r
- new Button.ClickListener() {\r
- public void buttonClick(ClickEvent event) {\r
- toggle(root);\r
- }\r
- }));\r
- l.addComponent(new Button("Toggle panel one",\r
- new Button.ClickListener() {\r
- public void buttonClick(ClickEvent event) {\r
- toggle(one);\r
- }\r
- }));\r
- l.addComponent(new Button("Toggle panel two",\r
- new Button.ClickListener() {\r
- public void buttonClick(ClickEvent event) {\r
- toggle(two);\r
- }\r
- }));\r
- l.addComponent(new Button("Toggle form", new Button.ClickListener() {\r
- public void buttonClick(ClickEvent event) {\r
- toggle(form);\r
- }\r
- }));\r
- l.addComponent(new Button("Toggle table", new Button.ClickListener() {\r
- public void buttonClick(ClickEvent event) {\r
- toggle(table);\r
- }\r
- }));\r
- \r
- root.setContent(new GridLayout(2, 3));\r
- main.addComponent(root);\r
- \r
- TextField tf = new TextField("Enabled");\r
- tf.setImmediate(true);\r
- root.addComponent(tf);\r
- tf = new TextField("Disabled");\r
- tf.setImmediate(true);\r
- tf.setEnabled(false);\r
- root.addComponent(tf);\r
- \r
- root.addComponent(one);\r
- tf = new TextField("Enabled");\r
- tf.setImmediate(true);\r
- one.addComponent(tf);\r
- tf = new TextField("Disabled");\r
- tf.setImmediate(true);\r
- tf.setEnabled(false);\r
- one.addComponent(tf);\r
- \r
- root.addComponent(two);\r
- tf = new TextField("Enabled");\r
- tf.setImmediate(true);\r
- two.addComponent(tf);\r
- tf = new TextField("Disabled");\r
- tf.setImmediate(true);\r
- tf.setEnabled(false);\r
- two.addComponent(tf);\r
- \r
- form = new Form();\r
- form.setCaption("Enabled");\r
- form.setFormFieldFactory(new DefaultFieldFactory() {\r
- \r
- @Override\r
- public Field<?> createField(Item item, Object propertyId,\r
- Component uiContext) {\r
- Field<?> f = super.createField(item, propertyId, uiContext);\r
- f.setEnabled(!"disabled".equals(propertyId));\r
- return f;\r
- }\r
- \r
- });\r
- form.setItemDataSource(new BeanItem<MyBean>(new MyBean()));\r
- root.addComponent(form);\r
- \r
- table = new Table("Enabled");\r
- table.setPageLength(7);\r
- table.addContainerProperty("Text", String.class, null);\r
- for (int i = 0; i < 150; i++) {\r
- Item item = table.addItem("Item" + i);\r
- Property<?> p = item.getItemProperty("Text");\r
- p.setValue(i % 5 == 0 ? "enabled" : "disabled");\r
- }\r
- \r
- table.setTableFieldFactory(new DefaultFieldFactory() {\r
- \r
- @Override\r
- public Field<?> createField(Container container, Object itemId,\r
- Object propertyId, Component uiContext) {\r
- Field<?> f = super.createField(container, itemId, propertyId,\r
- uiContext);\r
- Item item = container.getItem(itemId);\r
- Property<?> p = item.getItemProperty(propertyId);\r
- if ("disabled".equals(p.getValue())) {\r
- f.setEnabled(false);\r
- }\r
- return f;\r
- }\r
- \r
- });\r
- table.setEditable(true);\r
- root.addComponent(table);\r
- \r
- }\r
- \r
- private void toggle(Component c) {\r
- boolean enable = "Disabled".equals(c.getCaption());\r
- c.setEnabled(enable);\r
- c.setCaption((enable ? "Enabled" : "Disabled"));\r
- if (c instanceof ComponentContainer) {\r
- TextField tf = (TextField) ((ComponentContainer) c)\r
- .getComponentIterator().next();\r
- tf.focus();\r
- }\r
- }\r
- \r
- class MyBean {\r
- boolean on = false;\r
- int number = 1;\r
- String rw = "read/write";\r
- String r = "read";\r
- String disabled = "disabled";\r
- \r
- public boolean isOn() {\r
- return on;\r
- }\r
- \r
- public void setOn(boolean on) {\r
- this.on = on;\r
- }\r
- \r
- public int getNumber() {\r
- return number;\r
- }\r
- \r
- public void setNumber(int number) {\r
- this.number = number;\r
- }\r
- \r
- public String getRw() {\r
- return rw;\r
- }\r
- \r
- public void setRw(String rw) {\r
- this.rw = rw;\r
- }\r
- \r
- public String getDisabled() {\r
- return disabled;\r
- }\r
- \r
- public void setDisabled(String disabled) {\r
- this.disabled = disabled;\r
- }\r
- \r
- public String getR() {\r
- return r;\r
- }\r
- \r
- }\r
- }\r
+ package com.vaadin.tests.tickets;
+
+ import com.vaadin.Application;
+ import com.vaadin.data.Container;
+ import com.vaadin.data.Item;
+ import com.vaadin.data.Property;
+ import com.vaadin.data.util.BeanItem;
+ import com.vaadin.ui.Button;
+ import com.vaadin.ui.Button.ClickEvent;
+ import com.vaadin.ui.Component;
+ import com.vaadin.ui.ComponentContainer;
+ import com.vaadin.ui.DefaultFieldFactory;
+ import com.vaadin.ui.Field;
+ import com.vaadin.ui.Form;
+ import com.vaadin.ui.GridLayout;
+ import com.vaadin.ui.HorizontalLayout;
+ import com.vaadin.ui.Label;
++import com.vaadin.ui.Label.ContentMode;
+ import com.vaadin.ui.Panel;
++import com.vaadin.ui.Root.LegacyWindow;
+ import com.vaadin.ui.Table;
+ import com.vaadin.ui.TextField;
-import com.vaadin.ui.Window;
+
-public class Ticket677 extends Application {
++public class Ticket677 extends Application.LegacyApplication {
+
+ private static final Label info = new Label(
+ "<li> keep debug window open to see variable changes"
+ + "<li> disable root panel w/ toggle button"
+ + "<li> toggle one of the subpanels"
+ + "<li> we attempt to focus the subpanels first textfield"
+ + "<li> focusing should fail (try tabbing as well) [worked previousy]"
+ + "<li> no variable changes should be sent from disabled fields [changed sent previously]"
+ + "<li> try further toggling and tabbing around",
- Label.CONTENT_RAW);
++ ContentMode.RAW);
+
+ Panel root = new Panel("Enabled");
+ Panel one = new Panel("Enabled");
+ Panel two = new Panel("Enabled");
+ Form form;
+ Table table;
+
+ @Override
+ public void init() {
- Window main = new Window();
++ LegacyWindow main = new LegacyWindow();
+ setMainWindow(main);
+
+ main.addComponent(info);
+
+ HorizontalLayout l = new HorizontalLayout();
+ main.addComponent(l);
+
+ l.addComponent(new Button("Toggle root panel",
+ new Button.ClickListener() {
+ public void buttonClick(ClickEvent event) {
+ toggle(root);
+ }
+ }));
+ l.addComponent(new Button("Toggle panel one",
+ new Button.ClickListener() {
+ public void buttonClick(ClickEvent event) {
+ toggle(one);
+ }
+ }));
+ l.addComponent(new Button("Toggle panel two",
+ new Button.ClickListener() {
+ public void buttonClick(ClickEvent event) {
+ toggle(two);
+ }
+ }));
+ l.addComponent(new Button("Toggle form", new Button.ClickListener() {
+ public void buttonClick(ClickEvent event) {
+ toggle(form);
+ }
+ }));
+ l.addComponent(new Button("Toggle table", new Button.ClickListener() {
+ public void buttonClick(ClickEvent event) {
+ toggle(table);
+ }
+ }));
+
+ root.setContent(new GridLayout(2, 3));
+ main.addComponent(root);
+
+ TextField tf = new TextField("Enabled");
+ tf.setImmediate(true);
+ root.addComponent(tf);
+ tf = new TextField("Disabled");
+ tf.setImmediate(true);
+ tf.setEnabled(false);
+ root.addComponent(tf);
+
+ root.addComponent(one);
+ tf = new TextField("Enabled");
+ tf.setImmediate(true);
+ one.addComponent(tf);
+ tf = new TextField("Disabled");
+ tf.setImmediate(true);
+ tf.setEnabled(false);
+ one.addComponent(tf);
+
+ root.addComponent(two);
+ tf = new TextField("Enabled");
+ tf.setImmediate(true);
+ two.addComponent(tf);
+ tf = new TextField("Disabled");
+ tf.setImmediate(true);
+ tf.setEnabled(false);
+ two.addComponent(tf);
+
+ form = new Form();
+ form.setCaption("Enabled");
+ form.setFormFieldFactory(new DefaultFieldFactory() {
+
+ @Override
- public Field createField(Item item, Object propertyId,
++ public Field<?> createField(Item item, Object propertyId,
+ Component uiContext) {
- Field f = super.createField(item, propertyId, uiContext);
++ Field<?> f = super.createField(item, propertyId, uiContext);
+ f.setEnabled(!"disabled".equals(propertyId));
+ return f;
+ }
+
+ });
+ form.setItemDataSource(new BeanItem<MyBean>(new MyBean()));
+ root.addComponent(form);
+
+ table = new Table("Enabled");
+ table.setPageLength(7);
+ table.addContainerProperty("Text", String.class, null);
+ for (int i = 0; i < 150; i++) {
+ Item item = table.addItem("Item" + i);
- Property p = item.getItemProperty("Text");
++ Property<?> p = item.getItemProperty("Text");
+ p.setValue(i % 5 == 0 ? "enabled" : "disabled");
+ }
+
+ table.setTableFieldFactory(new DefaultFieldFactory() {
+
+ @Override
- public Field createField(Container container, Object itemId,
++ public Field<?> createField(Container container, Object itemId,
+ Object propertyId, Component uiContext) {
- Field f = super.createField(container, itemId, propertyId,
++ Field<?> f = super.createField(container, itemId, propertyId,
+ uiContext);
+ Item item = container.getItem(itemId);
- Property p = item.getItemProperty(propertyId);
++ Property<?> p = item.getItemProperty(propertyId);
+ if ("disabled".equals(p.getValue())) {
+ f.setEnabled(false);
+ }
+ return f;
+ }
+
+ });
+ table.setEditable(true);
+ root.addComponent(table);
+
+ }
+
+ private void toggle(Component c) {
+ boolean enable = "Disabled".equals(c.getCaption());
+ c.setEnabled(enable);
+ c.setCaption((enable ? "Enabled" : "Disabled"));
+ if (c instanceof ComponentContainer) {
+ TextField tf = (TextField) ((ComponentContainer) c)
+ .getComponentIterator().next();
+ tf.focus();
+ }
+ }
+
+ class MyBean {
+ boolean on = false;
+ int number = 1;
+ String rw = "read/write";
+ String r = "read";
+ String disabled = "disabled";
+
+ public boolean isOn() {
+ return on;
+ }
+
+ public void setOn(boolean on) {
+ this.on = on;
+ }
+
+ public int getNumber() {
+ return number;
+ }
+
+ public void setNumber(int number) {
+ this.number = number;
+ }
+
+ public String getRw() {
+ return rw;
+ }
+
+ public void setRw(String rw) {
+ this.rw = rw;
+ }
+
+ public String getDisabled() {
+ return disabled;
+ }
+
+ public void setDisabled(String disabled) {
+ this.disabled = disabled;
+ }
+
+ public String getR() {
+ return r;
+ }
+
+ }
+ }
- package com.vaadin.tests.util;\r
- \r
- import java.util.ArrayList;\r
- import java.util.List;\r
- \r
- import com.vaadin.ui.Label;\r
- import com.vaadin.ui.Label.ContentMode;\r
- import com.vaadin.ui.VerticalLayout;\r
- \r
- public class Log extends VerticalLayout {\r
- List<Label> eventLabels = new ArrayList<Label>();\r
- private boolean numberLogRows = true;\r
- private int nextLogNr = 1;\r
- \r
- public Log(int nr) {\r
- for (int i = 0; i < nr; i++) {\r
- Label l = createEventLabel();\r
- l.setDebugId("Log_row_" + i);\r
- eventLabels.add(l);\r
- addComponent(l);\r
- }\r
- setDebugId("Log");\r
- setCaption("Events:");\r
- }\r
- \r
- /**\r
- * Clears the rows and reset the row number to zero.\r
- */\r
- public Log clear() {\r
- for (Label l : eventLabels) {\r
- l.setValue(" ");\r
- }\r
- nextLogNr = 0;\r
- return this;\r
- }\r
- \r
- public Log log(String event) {\r
- int nr = eventLabels.size();\r
- for (int i = nr - 1; i > 0; i--) {\r
- eventLabels.get(i).setValue(eventLabels.get(i - 1).getValue());\r
- }\r
- String msg = event;\r
- if (numberLogRows) {\r
- msg = nextLogNr + ". " + msg;\r
- nextLogNr++;\r
- }\r
- eventLabels.get(0).setValue(msg);\r
- System.out.println(event);\r
- return this;\r
- }\r
- \r
- private Label createEventLabel() {\r
- Label l = new Label(" ", ContentMode.XHTML);\r
- l.setWidth(null);\r
- return l;\r
- }\r
- \r
- public Log setNumberLogRows(boolean numberLogRows) {\r
- this.numberLogRows = numberLogRows;\r
- return this;\r
- }\r
- \r
- }\r
+ package com.vaadin.tests.util;
+
+ import java.util.ArrayList;
+ import java.util.List;
+
+ import com.vaadin.ui.Label;
++import com.vaadin.ui.Label.ContentMode;
+ import com.vaadin.ui.VerticalLayout;
+
+ public class Log extends VerticalLayout {
+ List<Label> eventLabels = new ArrayList<Label>();
+ private boolean numberLogRows = true;
+ private int nextLogNr = 1;
+
+ public Log(int nr) {
+ for (int i = 0; i < nr; i++) {
+ Label l = createEventLabel();
+ l.setDebugId("Log_row_" + i);
+ eventLabels.add(l);
+ addComponent(l);
+ }
+ setDebugId("Log");
+ setCaption("Events:");
+ }
+
+ /**
+ * Clears the rows and reset the row number to zero.
+ */
+ public Log clear() {
+ for (Label l : eventLabels) {
+ l.setValue(" ");
+ }
+ nextLogNr = 0;
+ return this;
+ }
+
+ public Log log(String event) {
+ int nr = eventLabels.size();
+ for (int i = nr - 1; i > 0; i--) {
+ eventLabels.get(i).setValue(eventLabels.get(i - 1).getValue());
+ }
+ String msg = event;
+ if (numberLogRows) {
+ msg = nextLogNr + ". " + msg;
+ nextLogNr++;
+ }
+ eventLabels.get(0).setValue(msg);
+ System.out.println(event);
+ return this;
+ }
+
+ private Label createEventLabel() {
- Label l = new Label(" ", Label.CONTENT_XHTML);
++ Label l = new Label(" ", ContentMode.XHTML);
+ l.setWidth(null);
+ return l;
+ }
+
+ public Log setNumberLogRows(boolean numberLogRows) {
+ this.numberLogRows = numberLogRows;
+ return this;
+ }
+
+ }
- package com.vaadin.tests.validation;\r
- \r
- import java.util.Date;\r
- \r
- import com.vaadin.data.Validator.InvalidValueException;\r
- import com.vaadin.tests.components.TestBase;\r
- import com.vaadin.tests.util.AlwaysFailValidator;\r
- import com.vaadin.ui.Button;\r
- import com.vaadin.ui.Button.ClickEvent;\r
- import com.vaadin.ui.Button.ClickListener;\r
- import com.vaadin.ui.ComponentContainer;\r
- import com.vaadin.ui.DateField;\r
- import com.vaadin.ui.Field;\r
- import com.vaadin.ui.Form;\r
- import com.vaadin.ui.HorizontalLayout;\r
- import com.vaadin.ui.NativeSelect;\r
- import com.vaadin.ui.OptionGroup;\r
- import com.vaadin.ui.Panel;\r
- import com.vaadin.ui.Select;\r
- import com.vaadin.ui.TextField;\r
- import com.vaadin.ui.VerticalLayout;\r
- import com.vaadin.ui.themes.Reindeer;\r
- \r
- public class EmptyFieldErrorIndicators extends TestBase {\r
- \r
- @Override\r
- protected void setup() {\r
- getLayout().setSizeFull();\r
- \r
- HorizontalLayout hl = new HorizontalLayout();\r
- hl.setSizeFull();\r
- hl.setSpacing(true);\r
- \r
- ComponentContainer part1 = createPart(\r
- "Empty required fields validation", true, false);\r
- part1.setDebugId("emptyFieldPart");\r
- hl.addComponent(part1);\r
- \r
- ComponentContainer part2 = createPart(\r
- "Empty required fields with failing validator", true, true);\r
- part1.setDebugId("validatedFieldPart");\r
- hl.addComponent(part2);\r
- \r
- Panel panel = new Panel();\r
- panel.setSizeFull();\r
- panel.setStyleName(Reindeer.PANEL_LIGHT);\r
- panel.addComponent(hl);\r
- panel.setScrollable(true);\r
- addComponent(panel);\r
- }\r
- \r
- private ComponentContainer createPart(String caption, boolean required,\r
- boolean failValidator) {\r
- VerticalLayout part = new VerticalLayout();\r
- part.setMargin(true);\r
- \r
- final Form form = createForm(required, failValidator);\r
- part.addComponent(form);\r
- \r
- Button validate = new Button("Validate fields");\r
- validate.addListener(new ClickListener() {\r
- public void buttonClick(ClickEvent event) {\r
- try {\r
- form.validate();\r
- } catch (InvalidValueException e) {\r
- }\r
- }\r
- });\r
- part.addComponent(validate);\r
- \r
- Panel panel = new Panel(caption, part);\r
- panel.setHeight("100%");\r
- return panel;\r
- }\r
- \r
- private Form createForm(final boolean required, final boolean failValidator) {\r
- // hand-crafted form, not using form field factory\r
- final Form form = new Form() {\r
- @Override\r
- public void addField(Object propertyId, Field<?> field) {\r
- super.addField(propertyId, field);\r
- field.setRequired(required);\r
- field.setRequiredError("Missing required value!");\r
- if (failValidator && !(field instanceof Button)) {\r
- field.addValidator(new AlwaysFailValidator());\r
- }\r
- }\r
- };\r
- \r
- form.addField("Field", new TextField("Text"));\r
- form.addField("Date", new DateField("Date"));\r
- // not good for automated testing with screenshots when null\r
- // form.addField("Inline Date", new InlineDateField("Date"));\r
- // same as basic DateField\r
- // form.addField("Popup Date", new PopupDateField("Date"));\r
- Button setDateButton = new Button("Set date");\r
- form.getLayout().addComponent(setDateButton);\r
- // form.addField("Set Date", setDateButton);\r
- setDateButton.addListener(new ClickListener() {\r
- public void buttonClick(ClickEvent event) {\r
- form.getField("Date").setValue(new Date(0));\r
- }\r
- });\r
- \r
- NativeSelect nativeSelect = new NativeSelect("NativeSelect");\r
- form.addField("Native Select", nativeSelect);\r
- nativeSelect.addItem("Value 1");\r
- \r
- // in #4103, the Select component was behaving differently from others\r
- form.addField("Select", new Select("Select"));\r
- \r
- Select select2 = new Select("Select 2");\r
- select2.addItem("Value 1");\r
- form.addField("Select 2", select2);\r
- \r
- OptionGroup optionGroup = new OptionGroup("OptionGroup");\r
- optionGroup.setMultiSelect(false);\r
- optionGroup.addItem("Option 1");\r
- optionGroup.addItem("Option 2");\r
- form.addField("Option Group 1", optionGroup);\r
- \r
- OptionGroup optionGroup2 = new OptionGroup("OptionGroup");\r
- optionGroup2.setMultiSelect(true);\r
- optionGroup2.addItem("Option 1");\r
- optionGroup2.addItem("Option 2");\r
- form.addField("Option Group 2", optionGroup2);\r
- \r
- // TODO could add more different fields\r
- \r
- return form;\r
- }\r
- \r
- @Override\r
- protected String getDescription() {\r
- return "Fields on a form should not show the error indicator if required and empty";\r
- }\r
- \r
- @Override\r
- protected Integer getTicketNumber() {\r
- return 4013;\r
- }\r
- \r
- }\r
+ package com.vaadin.tests.validation;
+
+ import java.util.Date;
+
+ import com.vaadin.data.Validator.InvalidValueException;
-import com.vaadin.data.validator.AbstractValidator;
+ import com.vaadin.tests.components.TestBase;
++import com.vaadin.tests.util.AlwaysFailValidator;
+ import com.vaadin.ui.Button;
+ import com.vaadin.ui.Button.ClickEvent;
+ import com.vaadin.ui.Button.ClickListener;
+ import com.vaadin.ui.ComponentContainer;
+ import com.vaadin.ui.DateField;
+ import com.vaadin.ui.Field;
+ import com.vaadin.ui.Form;
+ import com.vaadin.ui.HorizontalLayout;
+ import com.vaadin.ui.NativeSelect;
+ import com.vaadin.ui.OptionGroup;
+ import com.vaadin.ui.Panel;
+ import com.vaadin.ui.Select;
+ import com.vaadin.ui.TextField;
+ import com.vaadin.ui.VerticalLayout;
+ import com.vaadin.ui.themes.Reindeer;
+
+ public class EmptyFieldErrorIndicators extends TestBase {
+
+ @Override
+ protected void setup() {
+ getLayout().setSizeFull();
+
+ HorizontalLayout hl = new HorizontalLayout();
+ hl.setSizeFull();
+ hl.setSpacing(true);
+
+ ComponentContainer part1 = createPart(
+ "Empty required fields validation", true, false);
+ part1.setDebugId("emptyFieldPart");
+ hl.addComponent(part1);
+
+ ComponentContainer part2 = createPart(
+ "Empty required fields with failing validator", true, true);
+ part1.setDebugId("validatedFieldPart");
+ hl.addComponent(part2);
+
+ Panel panel = new Panel();
+ panel.setSizeFull();
+ panel.setStyleName(Reindeer.PANEL_LIGHT);
+ panel.addComponent(hl);
+ panel.setScrollable(true);
+ addComponent(panel);
+ }
+
+ private ComponentContainer createPart(String caption, boolean required,
+ boolean failValidator) {
+ VerticalLayout part = new VerticalLayout();
+ part.setMargin(true);
+
+ final Form form = createForm(required, failValidator);
+ part.addComponent(form);
+
+ Button validate = new Button("Validate fields");
+ validate.addListener(new ClickListener() {
+ public void buttonClick(ClickEvent event) {
+ try {
+ form.validate();
+ } catch (InvalidValueException e) {
+ }
+ }
+ });
+ part.addComponent(validate);
+
+ Panel panel = new Panel(caption, part);
+ panel.setHeight("100%");
+ return panel;
+ }
+
+ private Form createForm(final boolean required, final boolean failValidator) {
+ // hand-crafted form, not using form field factory
+ final Form form = new Form() {
+ @Override
- public void addField(Object propertyId, Field field) {
++ public void addField(Object propertyId, Field<?> field) {
+ super.addField(propertyId, field);
+ field.setRequired(required);
+ field.setRequiredError("Missing required value!");
+ if (failValidator && !(field instanceof Button)) {
- field.addValidator(new AbstractValidator("Validation error") {
- public boolean isValid(Object value) {
- return false;
- }
- });
++ field.addValidator(new AlwaysFailValidator());
+ }
+ }
+ };
+
+ form.addField("Field", new TextField("Text"));
+ form.addField("Date", new DateField("Date"));
+ // not good for automated testing with screenshots when null
+ // form.addField("Inline Date", new InlineDateField("Date"));
+ // same as basic DateField
+ // form.addField("Popup Date", new PopupDateField("Date"));
+ Button setDateButton = new Button("Set date");
- form.addField("Set Date", setDateButton);
++ form.getLayout().addComponent(setDateButton);
++ // form.addField("Set Date", setDateButton);
+ setDateButton.addListener(new ClickListener() {
+ public void buttonClick(ClickEvent event) {
+ form.getField("Date").setValue(new Date(0));
+ }
+ });
+
+ NativeSelect nativeSelect = new NativeSelect("NativeSelect");
+ form.addField("Native Select", nativeSelect);
+ nativeSelect.addItem("Value 1");
+
+ // in #4103, the Select component was behaving differently from others
+ form.addField("Select", new Select("Select"));
+
+ Select select2 = new Select("Select 2");
+ select2.addItem("Value 1");
+ form.addField("Select 2", select2);
+
+ OptionGroup optionGroup = new OptionGroup("OptionGroup");
+ optionGroup.setMultiSelect(false);
+ optionGroup.addItem("Option 1");
+ optionGroup.addItem("Option 2");
+ form.addField("Option Group 1", optionGroup);
+
+ OptionGroup optionGroup2 = new OptionGroup("OptionGroup");
+ optionGroup2.setMultiSelect(true);
+ optionGroup2.addItem("Option 1");
+ optionGroup2.addItem("Option 2");
+ form.addField("Option Group 2", optionGroup2);
+
+ // TODO could add more different fields
+
+ return form;
+ }
+
+ @Override
+ protected String getDescription() {
+ return "Fields on a form should not show the error indicator if required and empty";
+ }
+
+ @Override
+ protected Integer getTicketNumber() {
+ return 4013;
+ }
+
+ }