From: Artur Signell Date: Tue, 31 Jan 2012 16:49:57 +0000 (+0200) Subject: Merge commit '116cd1f29a432fe5ca64f3023a9fec1ca130f078' (origin/6.8) X-Git-Tag: 7.0.0.alpha2~484 X-Git-Url: https://source.dussan.org/?a=commitdiff_plain;h=94a7e95d37925e8784fc00d4b4f800f6bf7c1ee8;p=vaadin-framework.git Merge commit '116cd1f29a432fe5ca64f3023a9fec1ca130f078' (origin/6.8) 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 --- 94a7e95d37925e8784fc00d4b4f800f6bf7c1ee8 diff --cc src/com/vaadin/data/fieldgroup/BeanFieldGroup.java index 8ca6c95069,0000000000..2584a4770b mode 100644,000000..100644 --- a/src/com/vaadin/data/fieldgroup/BeanFieldGroup.java +++ b/src/com/vaadin/data/fieldgroup/BeanFieldGroup.java @@@ -1,157 -1,0 +1,157 @@@ - /* - @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 extends FieldGroup { - - private Class beanType; - - private static Boolean beanValidationImplementationAvailable = null; - - public BeanFieldGroup(Class 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 getItemDataSource() { - return (BeanItem) 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; - } ++/* ++@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 extends FieldGroup { ++ ++ private Class beanType; ++ ++ private static Boolean beanValidationImplementationAvailable = null; ++ ++ public BeanFieldGroup(Class 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 getItemDataSource() { ++ return (BeanItem) 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; ++ } +} diff --cc src/com/vaadin/data/fieldgroup/Caption.java index e9ae01a2d2,0000000000..b990b720cd mode 100644,000000..100644 --- a/src/com/vaadin/data/fieldgroup/Caption.java +++ b/src/com/vaadin/data/fieldgroup/Caption.java @@@ -1,15 -1,0 +1,15 @@@ - /* - @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(); - } ++/* ++@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(); ++} diff --cc src/com/vaadin/data/fieldgroup/DefaultFieldGroupFieldFactory.java index 2fc7bc6b7e,0000000000..569f643998 mode 100644,000000..100644 --- a/src/com/vaadin/data/fieldgroup/DefaultFieldGroupFieldFactory.java +++ b/src/com/vaadin/data/fieldgroup/DefaultFieldGroupFieldFactory.java @@@ -1,156 -1,0 +1,156 @@@ - /* - @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 createField(Class type, Class 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 createEnumField(Class type, - Class fieldType) { - if (AbstractSelect.class.isAssignableFrom(fieldType)) { - AbstractSelect s = createCompatibleSelect((Class) fieldType); - populateWithEnumData(s, (Class) type); - return (T) s; - } - - return null; - } - - protected AbstractSelect createCompatibleSelect( - Class 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 createBooleanField(Class 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) fieldType); - } - - return null; - } - - protected T createAbstractTextField( - Class fieldType) { - if (fieldType == AbstractTextField.class) { - fieldType = (Class) 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 - * 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 createDefaultField(Class type, - Class 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 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()); - } - } - } ++/* ++@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 createField(Class type, Class 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 createEnumField(Class type, ++ Class fieldType) { ++ if (AbstractSelect.class.isAssignableFrom(fieldType)) { ++ AbstractSelect s = createCompatibleSelect((Class) fieldType); ++ populateWithEnumData(s, (Class) type); ++ return (T) s; ++ } ++ ++ return null; ++ } ++ ++ protected AbstractSelect createCompatibleSelect( ++ Class 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 createBooleanField(Class 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) fieldType); ++ } ++ ++ return null; ++ } ++ ++ protected T createAbstractTextField( ++ Class fieldType) { ++ if (fieldType == AbstractTextField.class) { ++ fieldType = (Class) 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 ++ * 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 createDefaultField(Class type, ++ Class 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 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()); ++ } ++ } ++} diff --cc src/com/vaadin/data/fieldgroup/FieldGroup.java index 381f4fef3f,0000000000..3df19f5bc9 mode 100644,000000..100644 --- a/src/com/vaadin/data/fieldgroup/FieldGroup.java +++ b/src/com/vaadin/data/fieldgroup/FieldGroup.java @@@ -1,978 -1,0 +1,978 @@@ - /* - @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. - *

- * 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. - *

- *

- * {@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. - *

- * - * @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> propertyIdToField = new HashMap>(); - private LinkedHashMap, Object> fieldToPropertyId = new LinkedHashMap, Object>(); - private List commitHandlers = new ArrayList(); - - /** - * 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. - *

- * - * @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. - *

- * 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. - *

- *

- * The default is to use buffered mode. - *

- * - * @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. - *

- * 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. - *

- * 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. - *

- * The fields are not returned in any specific order. - *

- * - * @return A collection with all bound Fields - */ - public Collection> 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)}. - *

- * This method also adds validators when applicable. - *

- * - * @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 Property.Transactional wrapInTransactionalProperty( - Property itemProperty) { - return new TransactionalPropertyWrapper(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. - *

- * 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. - *

- * 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. - *

- * 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. - *

- *

- * No guarantee is given for the order of the property ids - *

- * - * @return A collection of bound property ids - */ - public Collection 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. - *

- * Will always return an empty collection before an item has been set using - * {@link #setItemDataSource(Item)}. - *

- *

- * No guarantee is given for the order of the property ids - *

- * - * @return A collection of property ids that have not been bound to fields - */ - public Collection getUnboundPropertyIds() { - if (getItemDataSource() == null) { - return new ArrayList(); - } - List unboundPropertyIds = new ArrayList(); - unboundPropertyIds.addAll(getItemDataSource().getItemPropertyIds()); - unboundPropertyIds.removeAll(propertyIdToField.keySet()); - return unboundPropertyIds; - } - - /** - * Commits all changes done to the bound fields. - *

- * 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. - *

- * 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. - *

- * 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}. - *

- * Use {@link #addCommitHandler(CommitHandler)} and - * {@link #removeCommitHandler(CommitHandler)} to register or unregister a - * commit handler. - * - * @return A collection of commit handlers - */ - protected Collection 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. - *

- * 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.. - *

- * 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. - *

- * 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. - *

- * 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. - *

- *

- * For example: - * - *

-      * 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);
-      * 
- * - *

- * 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. - *

- * 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. - *

- *

- * For example: - * - *

-      * 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);
-      * 
- * - *

- *

- * 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. - *

- * - * @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. - *

- * 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. - *

- * - * @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 fieldType = (Class) 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 buildAndBind(String caption, Object propertyId, - Class 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. - *

- * 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. - *

- * - * @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 build(String caption, Class dataType, - Class 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; - } ++/* ++@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. ++ *

++ * 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. ++ *

++ *

++ * {@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. ++ *

++ * ++ * @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> propertyIdToField = new HashMap>(); ++ private LinkedHashMap, Object> fieldToPropertyId = new LinkedHashMap, Object>(); ++ private List commitHandlers = new ArrayList(); ++ ++ /** ++ * 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. ++ *

++ * ++ * @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. ++ *

++ * 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. ++ *

++ *

++ * The default is to use buffered mode. ++ *

++ * ++ * @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. ++ *

++ * 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. ++ *

++ * 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. ++ *

++ * The fields are not returned in any specific order. ++ *

++ * ++ * @return A collection with all bound Fields ++ */ ++ public Collection> 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)}. ++ *

++ * This method also adds validators when applicable. ++ *

++ * ++ * @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 Property.Transactional wrapInTransactionalProperty( ++ Property itemProperty) { ++ return new TransactionalPropertyWrapper(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. ++ *

++ * 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. ++ *

++ * 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. ++ *

++ * 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. ++ *

++ *

++ * No guarantee is given for the order of the property ids ++ *

++ * ++ * @return A collection of bound property ids ++ */ ++ public Collection 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. ++ *

++ * Will always return an empty collection before an item has been set using ++ * {@link #setItemDataSource(Item)}. ++ *

++ *

++ * No guarantee is given for the order of the property ids ++ *

++ * ++ * @return A collection of property ids that have not been bound to fields ++ */ ++ public Collection getUnboundPropertyIds() { ++ if (getItemDataSource() == null) { ++ return new ArrayList(); ++ } ++ List unboundPropertyIds = new ArrayList(); ++ unboundPropertyIds.addAll(getItemDataSource().getItemPropertyIds()); ++ unboundPropertyIds.removeAll(propertyIdToField.keySet()); ++ return unboundPropertyIds; ++ } ++ ++ /** ++ * Commits all changes done to the bound fields. ++ *

++ * 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. ++ *

++ * 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. ++ *

++ * 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}. ++ *

++ * Use {@link #addCommitHandler(CommitHandler)} and ++ * {@link #removeCommitHandler(CommitHandler)} to register or unregister a ++ * commit handler. ++ * ++ * @return A collection of commit handlers ++ */ ++ protected Collection 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. ++ *

++ * 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.. ++ *

++ * 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. ++ *

++ * 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. ++ *

++ * 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. ++ *

++ *

++ * For example: ++ * ++ *

++     * 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);
++     * 
++ * ++ *

++ * 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. ++ *

++ * 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. ++ *

++ *

++ * For example: ++ * ++ *

++     * 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);
++     * 
++ * ++ *

++ *

++ * 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. ++ *

++ * ++ * @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. ++ *

++ * 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. ++ *

++ * ++ * @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 fieldType = (Class) 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 buildAndBind(String caption, Object propertyId, ++ Class 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. ++ *

++ * 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. ++ *

++ * ++ * @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 build(String caption, Class dataType, ++ Class 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; ++ } +} diff --cc src/com/vaadin/data/fieldgroup/FieldGroupFieldFactory.java index 6945a492bd,0000000000..80c012cbdc mode 100644,000000..100644 --- a/src/com/vaadin/data/fieldgroup/FieldGroupFieldFactory.java +++ b/src/com/vaadin/data/fieldgroup/FieldGroupFieldFactory.java @@@ -1,31 -1,0 +1,31 @@@ - /* - @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 createField(Class dataType, Class fieldType); - } ++/* ++@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 createField(Class dataType, Class fieldType); ++} diff --cc src/com/vaadin/data/fieldgroup/PropertyId.java index 588fdc3020,0000000000..268047401d mode 100644,000000..100644 --- a/src/com/vaadin/data/fieldgroup/PropertyId.java +++ b/src/com/vaadin/data/fieldgroup/PropertyId.java @@@ -1,15 -1,0 +1,15 @@@ - /* - @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(); - } ++/* ++@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(); ++} diff --cc src/com/vaadin/data/util/TextFileProperty.java index 77325e141d,cfa8d4fabf..5ebba98062 --- a/src/com/vaadin/data/util/TextFileProperty.java +++ b/src/com/vaadin/data/util/TextFileProperty.java @@@ -1,141 -1,141 +1,141 @@@ - /* - @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 { - - 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() { - return String.class; - } - - /* - * (non-Javadoc) - * - * @see com.vaadin.data.Property#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); - } - } - - } + /* + @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 { + + 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 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); + } + } + + } diff --cc src/com/vaadin/data/util/TransactionalPropertyWrapper.java index de44dbe544,0000000000..06ec0935c3 mode 100644,000000..100644 --- a/src/com/vaadin/data/util/TransactionalPropertyWrapper.java +++ b/src/com/vaadin/data/util/TransactionalPropertyWrapper.java @@@ -1,107 -1,0 +1,107 @@@ - /* - @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 - */ - public class TransactionalPropertyWrapper extends AbstractProperty - implements ValueChangeNotifier, Property.Transactional { - - private Property wrappedProperty; - private boolean inTransaction = false; - private boolean valueChangePending; - private T valueBeforeTransaction; - - public TransactionalPropertyWrapper(Property 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 getWrappedProperty() { - return wrappedProperty; - } - - } ++/* ++@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 ++ */ ++public class TransactionalPropertyWrapper extends AbstractProperty ++ implements ValueChangeNotifier, Property.Transactional { ++ ++ private Property wrappedProperty; ++ private boolean inTransaction = false; ++ private boolean valueChangePending; ++ private T valueBeforeTransaction; ++ ++ public TransactionalPropertyWrapper(Property 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 getWrappedProperty() { ++ return wrappedProperty; ++ } ++ ++} diff --cc src/com/vaadin/data/util/converter/Converter.java index 065d06b071,0000000000..b8c15e8cdc mode 100644,000000..100644 --- a/src/com/vaadin/data/util/converter/Converter.java +++ b/src/com/vaadin/data/util/converter/Converter.java @@@ -1,159 -1,0 +1,159 @@@ - /* - @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. - *

- * 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. - *

- *

- * Converters must not have any side effects (never update UI from inside a - * converter). - *

- *

- * All Converters must be stateless and thread safe. - *

- *

- * If conversion of a value fails, a {@link ConversionException} is thrown. - *

- * - * @param - * The model type. Must be compatible with what - * {@link #getModelType()} returns. - * @param - * The presentation type. Must be compatible with what - * {@link #getPresentationType()} returns. - * @author Vaadin Ltd. - * @version - * @VERSION@ - * @since 7.0 - */ - public interface Converter extends Serializable { - - /** - * Converts the given value from target type to source type. - *

- * A converter can optionally use locale to do the conversion. - *

- * 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. - *

- * A converter can optionally use locale to do the conversion. - *

- * 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 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 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 ConversionException without a detail - * message. - */ - public ConversionException() { - } - - /** - * Constructs a new ConversionException 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 ConversionException 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); - } - } - - } ++/* ++@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. ++ *

++ * 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. ++ *

++ *

++ * Converters must not have any side effects (never update UI from inside a ++ * converter). ++ *

++ *

++ * All Converters must be stateless and thread safe. ++ *

++ *

++ * If conversion of a value fails, a {@link ConversionException} is thrown. ++ *

++ * ++ * @param ++ * The model type. Must be compatible with what ++ * {@link #getModelType()} returns. ++ * @param ++ * The presentation type. Must be compatible with what ++ * {@link #getPresentationType()} returns. ++ * @author Vaadin Ltd. ++ * @version ++ * @VERSION@ ++ * @since 7.0 ++ */ ++public interface Converter extends Serializable { ++ ++ /** ++ * Converts the given value from target type to source type. ++ *

++ * A converter can optionally use locale to do the conversion. ++ *

++ * 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. ++ *

++ * A converter can optionally use locale to do the conversion. ++ *

++ * 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 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 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 ConversionException without a detail ++ * message. ++ */ ++ public ConversionException() { ++ } ++ ++ /** ++ * Constructs a new ConversionException 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 ConversionException 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); ++ } ++ } ++ ++} diff --cc src/com/vaadin/data/util/converter/ConverterFactory.java index 451f84185d,0000000000..ed4ab41ac0 mode 100644,000000..100644 --- a/src/com/vaadin/data/util/converter/ConverterFactory.java +++ b/src/com/vaadin/data/util/converter/ConverterFactory.java @@@ -1,23 -1,0 +1,23 @@@ - /* - @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 Converter createConverter( - Class presentationType, Class modelType); - - } ++/* ++@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 Converter createConverter( ++ Class presentationType, Class modelType); ++ ++} diff --cc src/com/vaadin/data/util/converter/DateToLongConverter.java index d66adece06,0000000000..537800f617 mode 100644,000000..100644 --- a/src/com/vaadin/data/util/converter/DateToLongConverter.java +++ b/src/com/vaadin/data/util/converter/DateToLongConverter.java @@@ -1,68 -1,0 +1,68 @@@ - /* - @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 { - - /* - * (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 getModelType() { - return Long.class; - } - - /* - * (non-Javadoc) - * - * @see com.vaadin.data.util.converter.Converter#getPresentationType() - */ - public Class getPresentationType() { - return Date.class; - } - - } ++/* ++@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 { ++ ++ /* ++ * (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 getModelType() { ++ return Long.class; ++ } ++ ++ /* ++ * (non-Javadoc) ++ * ++ * @see com.vaadin.data.util.converter.Converter#getPresentationType() ++ */ ++ public Class getPresentationType() { ++ return Date.class; ++ } ++ ++} diff --cc src/com/vaadin/data/util/converter/DefaultConverterFactory.java index 9233624819,0000000000..3ad7b6a85b mode 100644,000000..100644 --- a/src/com/vaadin/data/util/converter/DefaultConverterFactory.java +++ b/src/com/vaadin/data/util/converter/DefaultConverterFactory.java @@@ -1,100 -1,0 +1,100 @@@ - /* - @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}.

- *

- * Custom converters can be provided by extending this class and using - * {@link Application#setConverterFactory(ConverterFactory)}. - *

- * - * @author Vaadin Ltd - * @version - * @VERSION@ - * @since 7.0 - */ - public class DefaultConverterFactory implements ConverterFactory { - - private final static Logger log = Logger - .getLogger(DefaultConverterFactory.class.getName()); - - public Converter createConverter( - Class presentationType, Class modelType) { - Converter converter = findConverter( - presentationType, modelType); - if (converter != null) { - log.finest(getClass().getName() + " created a " - + converter.getClass()); - return converter; - } - - // Try to find a reverse converter - Converter reverseConverter = findConverter( - modelType, presentationType); - if (reverseConverter != null) { - log.finest(getClass().getName() + " created a reverse " - + reverseConverter.getClass()); - return new ReverseConverter(reverseConverter); - } - - log.finest(getClass().getName() + " could not find a converter for " - + presentationType.getName() + " to " + modelType.getName() - + " conversion"); - return null; - - } - - protected Converter findConverter( - Class presentationType, Class modelType) { - if (presentationType == String.class) { - // TextField converters and more - Converter converter = (Converter) createStringConverter(modelType); - if (converter != null) { - return converter; - } - } else if (presentationType == Date.class) { - // DateField converters and more - Converter converter = (Converter) createDateConverter(modelType); - if (converter != null) { - return converter; - } - } - - return null; - - } - - protected Converter createDateConverter(Class sourceType) { - if (Long.class.isAssignableFrom(sourceType)) { - return new DateToLongConverter(); - } else { - return null; - } - } - - protected Converter 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; - } - } - - } ++/* ++@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}.

++ *

++ * Custom converters can be provided by extending this class and using ++ * {@link Application#setConverterFactory(ConverterFactory)}. ++ *

++ * ++ * @author Vaadin Ltd ++ * @version ++ * @VERSION@ ++ * @since 7.0 ++ */ ++public class DefaultConverterFactory implements ConverterFactory { ++ ++ private final static Logger log = Logger ++ .getLogger(DefaultConverterFactory.class.getName()); ++ ++ public Converter createConverter( ++ Class presentationType, Class modelType) { ++ Converter converter = findConverter( ++ presentationType, modelType); ++ if (converter != null) { ++ log.finest(getClass().getName() + " created a " ++ + converter.getClass()); ++ return converter; ++ } ++ ++ // Try to find a reverse converter ++ Converter reverseConverter = findConverter( ++ modelType, presentationType); ++ if (reverseConverter != null) { ++ log.finest(getClass().getName() + " created a reverse " ++ + reverseConverter.getClass()); ++ return new ReverseConverter(reverseConverter); ++ } ++ ++ log.finest(getClass().getName() + " could not find a converter for " ++ + presentationType.getName() + " to " + modelType.getName() ++ + " conversion"); ++ return null; ++ ++ } ++ ++ protected Converter findConverter( ++ Class presentationType, Class modelType) { ++ if (presentationType == String.class) { ++ // TextField converters and more ++ Converter converter = (Converter) createStringConverter(modelType); ++ if (converter != null) { ++ return converter; ++ } ++ } else if (presentationType == Date.class) { ++ // DateField converters and more ++ Converter converter = (Converter) createDateConverter(modelType); ++ if (converter != null) { ++ return converter; ++ } ++ } ++ ++ return null; ++ ++ } ++ ++ protected Converter createDateConverter(Class sourceType) { ++ if (Long.class.isAssignableFrom(sourceType)) { ++ return new DateToLongConverter(); ++ } else { ++ return null; ++ } ++ } ++ ++ protected Converter 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; ++ } ++ } ++ ++} diff --cc src/com/vaadin/data/util/converter/ReverseConverter.java index b191d1ca0b,0000000000..1c561f29e8 mode 100644,000000..100644 --- a/src/com/vaadin/data/util/converter/ReverseConverter.java +++ b/src/com/vaadin/data/util/converter/ReverseConverter.java @@@ -1,80 -1,0 +1,80 @@@ - /* - @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 - * The source type - * @param - * The target type - * - * @author Vaadin Ltd - * @version - * @VERSION@ - * @since 7.0 - */ - public class ReverseConverter implements - Converter { - - private Converter 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 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 getModelType() { - return realConverter.getPresentationType(); - } - - /* - * (non-Javadoc) - * - * @see com.vaadin.data.util.converter.Converter#getTargetType() - */ - public Class getPresentationType() { - return realConverter.getModelType(); - } - - } ++/* ++@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 ++ * The source type ++ * @param ++ * The target type ++ * ++ * @author Vaadin Ltd ++ * @version ++ * @VERSION@ ++ * @since 7.0 ++ */ ++public class ReverseConverter implements ++ Converter { ++ ++ private Converter 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 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 getModelType() { ++ return realConverter.getPresentationType(); ++ } ++ ++ /* ++ * (non-Javadoc) ++ * ++ * @see com.vaadin.data.util.converter.Converter#getTargetType() ++ */ ++ public Class getPresentationType() { ++ return realConverter.getModelType(); ++ } ++ ++} diff --cc src/com/vaadin/data/util/converter/StringToBooleanConverter.java index 3b2034a361,0000000000..96a3a3d071 mode 100644,000000..100644 --- a/src/com/vaadin/data/util/converter/StringToBooleanConverter.java +++ b/src/com/vaadin/data/util/converter/StringToBooleanConverter.java @@@ -1,104 -1,0 +1,104 @@@ - /* - @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(). - *

- * Leading and trailing white spaces are ignored when converting from a String. - *

- * - * @author Vaadin Ltd - * @version - * @VERSION@ - * @since 7.0 - */ - public class StringToBooleanConverter implements Converter { - - /* - * (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 getModelType() { - return Boolean.class; - } - - /* - * (non-Javadoc) - * - * @see com.vaadin.data.util.converter.Converter#getPresentationType() - */ - public Class getPresentationType() { - return String.class; - } - - } ++/* ++@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(). ++ *

++ * Leading and trailing white spaces are ignored when converting from a String. ++ *

++ * ++ * @author Vaadin Ltd ++ * @version ++ * @VERSION@ ++ * @since 7.0 ++ */ ++public class StringToBooleanConverter implements Converter { ++ ++ /* ++ * (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 getModelType() { ++ return Boolean.class; ++ } ++ ++ /* ++ * (non-Javadoc) ++ * ++ * @see com.vaadin.data.util.converter.Converter#getPresentationType() ++ */ ++ public Class getPresentationType() { ++ return String.class; ++ } ++ ++} diff --cc src/com/vaadin/data/util/converter/StringToDateConverter.java index 2aa9395532,0000000000..6f3c2e47f6 mode 100644,000000..100644 --- a/src/com/vaadin/data/util/converter/StringToDateConverter.java +++ b/src/com/vaadin/data/util/converter/StringToDateConverter.java @@@ -1,108 -1,0 +1,108 @@@ - /* - @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. - *

- * Leading and trailing white spaces are ignored when converting from a String. - *

- *

- * Override and overwrite {@link #getFormat(Locale)} to use a different format. - *

- * - * @author Vaadin Ltd - * @version - * @VERSION@ - * @since 7.0 - */ - public class StringToDateConverter implements Converter { - - /** - * 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 getModelType() { - return Date.class; - } - - /* - * (non-Javadoc) - * - * @see com.vaadin.data.util.converter.Converter#getPresentationType() - */ - public Class getPresentationType() { - return String.class; - } - - } ++/* ++@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. ++ *

++ * Leading and trailing white spaces are ignored when converting from a String. ++ *

++ *

++ * Override and overwrite {@link #getFormat(Locale)} to use a different format. ++ *

++ * ++ * @author Vaadin Ltd ++ * @version ++ * @VERSION@ ++ * @since 7.0 ++ */ ++public class StringToDateConverter implements Converter { ++ ++ /** ++ * 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 getModelType() { ++ return Date.class; ++ } ++ ++ /* ++ * (non-Javadoc) ++ * ++ * @see com.vaadin.data.util.converter.Converter#getPresentationType() ++ */ ++ public Class getPresentationType() { ++ return String.class; ++ } ++ ++} diff --cc src/com/vaadin/data/util/converter/StringToDoubleConverter.java index 29c6329451,0000000000..60a38f4127 mode 100644,000000..100644 --- a/src/com/vaadin/data/util/converter/StringToDoubleConverter.java +++ b/src/com/vaadin/data/util/converter/StringToDoubleConverter.java @@@ -1,103 -1,0 +1,103 @@@ - /* - @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. - *

- * Leading and trailing white spaces are ignored when converting from a String. - *

- *

- * Override and overwrite {@link #getFormat(Locale)} to use a different format. - *

- * - * @author Vaadin Ltd - * @version - * @VERSION@ - * @since 7.0 - */ - public class StringToDoubleConverter implements Converter { - - /** - * 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 getModelType() { - return Double.class; - } - - /* - * (non-Javadoc) - * - * @see com.vaadin.data.util.converter.Converter#getPresentationType() - */ - public Class getPresentationType() { - return String.class; - } - } ++/* ++@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. ++ *

++ * Leading and trailing white spaces are ignored when converting from a String. ++ *

++ *

++ * Override and overwrite {@link #getFormat(Locale)} to use a different format. ++ *

++ * ++ * @author Vaadin Ltd ++ * @version ++ * @VERSION@ ++ * @since 7.0 ++ */ ++public class StringToDoubleConverter implements Converter { ++ ++ /** ++ * 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 getModelType() { ++ return Double.class; ++ } ++ ++ /* ++ * (non-Javadoc) ++ * ++ * @see com.vaadin.data.util.converter.Converter#getPresentationType() ++ */ ++ public Class getPresentationType() { ++ return String.class; ++ } ++} diff --cc src/com/vaadin/data/util/converter/StringToIntegerConverter.java index 7fa4458c51,0000000000..e55feec3b6 mode 100644,000000..100644 --- a/src/com/vaadin/data/util/converter/StringToIntegerConverter.java +++ b/src/com/vaadin/data/util/converter/StringToIntegerConverter.java @@@ -1,84 -1,0 +1,84 @@@ - /* - @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. - *

- * Override and overwrite {@link #getFormat(Locale)} to use a different format. - *

- * - * @author Vaadin Ltd - * @version - * @VERSION@ - * @since 7.0 - */ - public class StringToIntegerConverter implements Converter { - - /** - * 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 getModelType() { - return Integer.class; - } - - public Class getPresentationType() { - return String.class; - } - - } ++/* ++@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. ++ *

++ * Override and overwrite {@link #getFormat(Locale)} to use a different format. ++ *

++ * ++ * @author Vaadin Ltd ++ * @version ++ * @VERSION@ ++ * @since 7.0 ++ */ ++public class StringToIntegerConverter implements Converter { ++ ++ /** ++ * 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 getModelType() { ++ return Integer.class; ++ } ++ ++ public Class getPresentationType() { ++ return String.class; ++ } ++ ++} diff --cc src/com/vaadin/data/util/converter/StringToNumberConverter.java index 64944a434c,0000000000..d1816007e7 mode 100644,000000..100644 --- a/src/com/vaadin/data/util/converter/StringToNumberConverter.java +++ b/src/com/vaadin/data/util/converter/StringToNumberConverter.java @@@ -1,107 -1,0 +1,107 @@@ - /* - @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. - *

- * Override and overwrite {@link #getFormat(Locale)} to use a different format. - *

- * - * @author Vaadin Ltd - * @version - * @VERSION@ - * @since 7.0 - */ - public class StringToNumberConverter implements Converter { - - /** - * 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 getModelType() { - return Number.class; - } - - /* - * (non-Javadoc) - * - * @see com.vaadin.data.util.converter.Converter#getPresentationType() - */ - public Class getPresentationType() { - return String.class; - } - - } ++/* ++@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. ++ *

++ * Override and overwrite {@link #getFormat(Locale)} to use a different format. ++ *

++ * ++ * @author Vaadin Ltd ++ * @version ++ * @VERSION@ ++ * @since 7.0 ++ */ ++public class StringToNumberConverter implements Converter { ++ ++ /** ++ * 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 getModelType() { ++ return Number.class; ++ } ++ ++ /* ++ * (non-Javadoc) ++ * ++ * @see com.vaadin.data.util.converter.Converter#getPresentationType() ++ */ ++ public Class getPresentationType() { ++ return String.class; ++ } ++ ++} diff --cc src/com/vaadin/data/validator/BeanValidator.java index 939fd2e9c4,0000000000..817df85248 mode 100644,000000..100644 --- a/src/com/vaadin/data/validator/BeanValidator.java +++ b/src/com/vaadin/data/validator/BeanValidator.java @@@ -1,173 -1,0 +1,173 @@@ - /* - @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 exceptions = new ArrayList(); - 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("
"); - } - 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; - } - ++/* ++@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 exceptions = new ArrayList(); ++ 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("
"); ++ } ++ 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; ++ } ++ +} diff --cc src/com/vaadin/data/validator/DateRangeValidator.java index 42f5a224ed,0000000000..24f3d3ce10 mode 100644,000000..100644 --- a/src/com/vaadin/data/validator/DateRangeValidator.java +++ b/src/com/vaadin/data/validator/DateRangeValidator.java @@@ -1,51 -1,0 +1,51 @@@ - /* - @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. - * - *

- * 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. - *

- * - * @author Vaadin Ltd. - * @version - * @VERSION@ - * @since 7.0 - */ - public class DateRangeValidator extends RangeValidator { - - /** - * Creates a validator for checking that an Date is within a given range. - *

- * 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. - *

- *

- * 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. - *

- * - * @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); - } - - } ++/* ++@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. ++ * ++ *

++ * 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. ++ *

++ * ++ * @author Vaadin Ltd. ++ * @version ++ * @VERSION@ ++ * @since 7.0 ++ */ ++public class DateRangeValidator extends RangeValidator { ++ ++ /** ++ * Creates a validator for checking that an Date is within a given range. ++ *

++ * 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. ++ *

++ *

++ * 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. ++ *

++ * ++ * @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); ++ } ++ ++} diff --cc src/com/vaadin/data/validator/RangeValidator.java index 457f046360,0000000000..433271274f mode 100644,000000..100644 --- a/src/com/vaadin/data/validator/RangeValidator.java +++ b/src/com/vaadin/data/validator/RangeValidator.java @@@ -1,186 -1,0 +1,186 @@@ - /* - @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. - *

- * 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)}. - *

- * - * @param - * 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 extends AbstractValidator { - - private T minValue = null; - private boolean minValueIncluded = true; - private T maxValue = null; - private boolean maxValueIncluded = true; - private Class 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 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 getType() { - return type; - } - - } ++/* ++@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. ++ *

++ * 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)}. ++ *

++ * ++ * @param ++ * 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 extends AbstractValidator { ++ ++ private T minValue = null; ++ private boolean minValueIncluded = true; ++ private T maxValue = null; ++ private boolean maxValueIncluded = true; ++ private Class 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 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 getType() { ++ return type; ++ } ++ ++} diff --cc src/com/vaadin/external/json/JSONException.java index 9d97a32d7d,0000000000..d799021506 mode 100644,000000..100644 --- a/src/com/vaadin/external/json/JSONException.java +++ b/src/com/vaadin/external/json/JSONException.java @@@ -1,28 -1,0 +1,28 @@@ - 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; - } - } ++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; ++ } ++} diff --cc src/com/vaadin/external/json/JSONString.java index 7b574d1915,0000000000..cc7e4d8c07 mode 100644,000000..100644 --- a/src/com/vaadin/external/json/JSONString.java +++ b/src/com/vaadin/external/json/JSONString.java @@@ -1,21 -1,0 +1,21 @@@ - package com.vaadin.external.json; - - import java.io.Serializable; - - /** - * The JSONString interface allows a toJSONString() - * method so that a class can change the behavior of - * JSONObject.toString(), JSONArray.toString(), and - * JSONWriter.value(Object). The - * toJSONString method will be used instead of the default behavior - * of using the Object's toString() method and quoting the result. - */ - public interface JSONString extends Serializable { - /** - * The toJSONString method allows a class to produce its own - * JSON serialization. - * - * @return A strictly syntactically correct JSON text. - */ - public String toJSONString(); - } ++package com.vaadin.external.json; ++ ++import java.io.Serializable; ++ ++/** ++ * The JSONString interface allows a toJSONString() ++ * method so that a class can change the behavior of ++ * JSONObject.toString(), JSONArray.toString(), and ++ * JSONWriter.value(Object). The ++ * toJSONString method will be used instead of the default behavior ++ * of using the Object's toString() method and quoting the result. ++ */ ++public interface JSONString extends Serializable { ++ /** ++ * The toJSONString method allows a class to produce its own ++ * JSON serialization. ++ * ++ * @return A strictly syntactically correct JSON text. ++ */ ++ public String toJSONString(); ++} diff --cc src/com/vaadin/external/json/JSONStringer.java index c4a1af600a,0000000000..465f27aaab mode 100644,000000..100644 --- a/src/com/vaadin/external/json/JSONStringer.java +++ b/src/com/vaadin/external/json/JSONStringer.java @@@ -1,78 -1,0 +1,78 @@@ - 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. - *

- * A JSONStringer instance provides a value method for appending - * values to the - * text, and a key - * method for adding keys before values in objects. There are array - * and endArray methods that make and bound array values, and - * object and endObject methods which make and bound - * object values. All of these methods return the JSONWriter instance, - * permitting cascade style. For example,

-  * myString = new JSONStringer()
-  *     .object()
-  *         .key("JSON")
-  *         .value("Hello, World!")
-  *     .endObject()
-  *     .toString();
which produces the string
-  * {"JSON":"Hello, World!"}
- *

- * The first method called must be array or object. - * 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. - *

- * 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 null if there was a - * problem in the construction of the JSON text (such as the calls to - * array were not properly balanced with calls to - * endArray). - * @return The JSON text. - */ - public String toString() { - return this.mode == 'd' ? this.writer.toString() : null; - } - } ++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. ++ *

++ * A JSONStringer instance provides a value method for appending ++ * values to the ++ * text, and a key ++ * method for adding keys before values in objects. There are array ++ * and endArray methods that make and bound array values, and ++ * object and endObject methods which make and bound ++ * object values. All of these methods return the JSONWriter instance, ++ * permitting cascade style. For example,

++ * myString = new JSONStringer()
++ *     .object()
++ *         .key("JSON")
++ *         .value("Hello, World!")
++ *     .endObject()
++ *     .toString();
which produces the string
++ * {"JSON":"Hello, World!"}
++ *

++ * The first method called must be array or object. ++ * 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. ++ *

++ * 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 null if there was a ++ * problem in the construction of the JSON text (such as the calls to ++ * array were not properly balanced with calls to ++ * endArray). ++ * @return The JSON text. ++ */ ++ public String toString() { ++ return this.mode == 'd' ? this.writer.toString() : null; ++ } ++} diff --cc src/com/vaadin/external/json/JSONWriter.java index 438721b7b2,0000000000..5f9ddeeae2 mode 100644,000000..100644 --- a/src/com/vaadin/external/json/JSONWriter.java +++ b/src/com/vaadin/external/json/JSONWriter.java @@@ -1,355 -1,0 +1,355 @@@ - 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. - *

- * A JSONWriter instance provides a value method for appending - * values to the text, and a key method for adding keys before - * values in objects. There are array and endArray - * methods that make and bound array values, and object and - * endObject methods which make and bound object values. All of - * these methods return the JSONWriter instance, permitting a cascade style. For - * example, - * - *

-  * new JSONWriter(myWriter).object().key("JSON").value("Hello, World!")
-  *         .endObject();
-  * 
- * - * which writes - * - *
-  * {"JSON":"Hello, World!"}
-  * 
- *

- * The first method called must be array or object. - * 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. - *

- * 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 - * endArray will be appended to this array. The - * endArray 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 - * array. - * - * @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 - * object. - * - * @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 - * endObject will be appended to this object. The - * endObject 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 true or the value false - * . - * - * @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)); - } - } ++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. ++ *

++ * A JSONWriter instance provides a value method for appending ++ * values to the text, and a key method for adding keys before ++ * values in objects. There are array and endArray ++ * methods that make and bound array values, and object and ++ * endObject methods which make and bound object values. All of ++ * these methods return the JSONWriter instance, permitting a cascade style. For ++ * example, ++ * ++ *

++ * new JSONWriter(myWriter).object().key("JSON").value("Hello, World!")
++ *         .endObject();
++ * 
++ * ++ * which writes ++ * ++ *
++ * {"JSON":"Hello, World!"}
++ * 
++ *

++ * The first method called must be array or object. ++ * 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. ++ *

++ * 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 ++ * endArray will be appended to this array. The ++ * endArray 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 ++ * array. ++ * ++ * @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 ++ * object. ++ * ++ * @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 ++ * endObject will be appended to this object. The ++ * endObject 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 true or the value false ++ * . ++ * ++ * @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)); ++ } ++} diff --cc src/com/vaadin/terminal/gwt/client/VBrowserDetails.java index d9ca56be05,aaef981bab..89e106f063 --- a/src/com/vaadin/terminal/gwt/client/VBrowserDetails.java +++ b/src/com/vaadin/terminal/gwt/client/VBrowserDetails.java @@@ -1,356 -1,305 +1,356 @@@ - /* - @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. - *

- * Note that Internet Explorer 8 and newer will return the document mode so - * IE8 rendering as IE7 will return 7. - *

- * - * @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; - } - - } + /* + @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. + *

+ * Note that Internet Explorer 8 and newer will return the document mode so + * IE8 rendering as IE7 will return 7. + *

+ * + * @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; ++ } ++ + } diff --cc src/com/vaadin/terminal/gwt/client/VPaintable.java index d85c6d33e2,0000000000..f7b7eaba83 mode 100644,000000..100644 --- a/src/com/vaadin/terminal/gwt/client/VPaintable.java +++ b/src/com/vaadin/terminal/gwt/client/VPaintable.java @@@ -1,74 -1,0 +1,74 @@@ - /* - @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. - // *

- // * 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. - // *

- // * - // * @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(); - } ++/* ++@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. ++ // *

++ // * 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. ++ // *

++ // * ++ // * @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(); ++} diff --cc src/com/vaadin/terminal/gwt/client/VPaintableMap.java index f21d85558c,0000000000..aa3e8e3cb8 mode 100644,000000..100644 --- a/src/com/vaadin/terminal/gwt/client/VPaintableMap.java +++ b/src/com/vaadin/terminal/gwt/client/VPaintableMap.java @@@ -1,403 -1,0 +1,403 @@@ - /* - @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 idToPaintable = new HashMap(); - private Map paintableToId = new HashMap(); - - public static VPaintableMap get(ApplicationConnection applicationConnection) { - return applicationConnection.getPaintableMap(); - } - - @Deprecated - private final ComponentDetailMap idToComponentDetail = ComponentDetailMap - .create(); - - private Set unregistryBag = new HashSet(); - - /** - * 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. - *

- * The paintableId is used in the UIDL to identify a specific widget - * instance, effectively linking the widget with it's server side Component. - *

- * - * @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 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 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; - } - - } ++/* ++@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 idToPaintable = new HashMap(); ++ private Map paintableToId = new HashMap(); ++ ++ public static VPaintableMap get(ApplicationConnection applicationConnection) { ++ return applicationConnection.getPaintableMap(); ++ } ++ ++ @Deprecated ++ private final ComponentDetailMap idToComponentDetail = ComponentDetailMap ++ .create(); ++ ++ private Set unregistryBag = new HashSet(); ++ ++ /** ++ * 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. ++ *

++ * The paintableId is used in the UIDL to identify a specific widget ++ * instance, effectively linking the widget with it's server side Component. ++ *

++ * ++ * @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 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 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; ++ } ++ ++} diff --cc src/com/vaadin/terminal/gwt/client/ui/VAbsoluteLayoutPaintable.java index 27535806c1,0000000000..9a0b6eacf6 mode 100644,000000..100644 --- a/src/com/vaadin/terminal/gwt/client/ui/VAbsoluteLayoutPaintable.java +++ b/src/com/vaadin/terminal/gwt/client/ui/VAbsoluteLayoutPaintable.java @@@ -1,84 -1,0 +1,84 @@@ - 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 HandlerRegistration registerHandler( - H handler, Type 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 unrenderedPids = new HashSet( - getWidgetForPaintable().pidToComponentWrappper.keySet()); - - for (Iterator 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(); - } - } ++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 HandlerRegistration registerHandler( ++ H handler, Type 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 unrenderedPids = new HashSet( ++ getWidgetForPaintable().pidToComponentWrappper.keySet()); ++ ++ for (Iterator 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(); ++ } ++} diff --cc src/com/vaadin/terminal/gwt/client/ui/VAbstractPaintableWidget.java index 90da0ef4ac,0000000000..09bf02ec43 mode 100644,000000..100644 --- a/src/com/vaadin/terminal/gwt/client/ui/VAbstractPaintableWidget.java +++ b/src/com/vaadin/terminal/gwt/client/ui/VAbstractPaintableWidget.java @@@ -1,103 -1,0 +1,103 @@@ - /* - @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; - } - } ++/* ++@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; ++ } ++} diff --cc src/com/vaadin/terminal/gwt/client/ui/VAbstractPaintableWidgetContainer.java index b3e19f037a,0000000000..1f78c02f58 mode 100644,000000..100644 --- a/src/com/vaadin/terminal/gwt/client/ui/VAbstractPaintableWidgetContainer.java +++ b/src/com/vaadin/terminal/gwt/client/ui/VAbstractPaintableWidgetContainer.java @@@ -1,17 -1,0 +1,17 @@@ - /* - @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() { - } - - } ++/* ++@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() { ++ } ++ ++} diff --cc src/com/vaadin/terminal/gwt/client/ui/VAbstractSplitPanelPaintable.java index 1ff066d004,0000000000..84c3ab5221 mode 100644,000000..100644 --- a/src/com/vaadin/terminal/gwt/client/ui/VAbstractSplitPanelPaintable.java +++ b/src/com/vaadin/terminal/gwt/client/ui/VAbstractSplitPanelPaintable.java @@@ -1,140 -1,0 +1,140 @@@ - 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 HandlerRegistration registerHandler( - H handler, Type 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(); - - } ++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 HandlerRegistration registerHandler( ++ H handler, Type 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(); ++ ++} diff --cc src/com/vaadin/terminal/gwt/client/ui/VAccordionPaintable.java index 3f28818073,0000000000..4136d02c30 mode 100644,000000..100644 --- a/src/com/vaadin/terminal/gwt/client/ui/VAccordionPaintable.java +++ b/src/com/vaadin/terminal/gwt/client/ui/VAccordionPaintable.java @@@ -1,68 -1,0 +1,68 @@@ - 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 */ - } - - } ++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 */ ++ } ++ ++} diff --cc src/com/vaadin/terminal/gwt/client/ui/VAudioPaintable.java index e949d95104,0000000000..dae602a668 mode 100644,000000..100644 --- a/src/com/vaadin/terminal/gwt/client/ui/VAudioPaintable.java +++ b/src/com/vaadin/terminal/gwt/client/ui/VAudioPaintable.java @@@ -1,37 -1,0 +1,37 @@@ - 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); - } - - } ++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); ++ } ++ ++} diff --cc src/com/vaadin/terminal/gwt/client/ui/VCalendarPanel.java index 99eadc9558,a2f03d6176..b5c07ca278 --- a/src/com/vaadin/terminal/gwt/client/ui/VCalendarPanel.java +++ b/src/com/vaadin/terminal/gwt/client/ui/VCalendarPanel.java @@@ -1,1739 -1,1787 +1,1739 @@@ - /* - @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, "" + monthName + " " + year - + ""); - } - - 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, ""); - // 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, "" - + getDateTimeService().getShortDay(day) + ""); - } 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, "" + weekNumber - + ""); - } - 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 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 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); - } - - 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_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 (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 (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() == 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.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_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 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(); - } - } - } + /* + @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, "" + monthName + " " + year + + ""); + } + + 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, ""); + // 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, "" + + getDateTimeService().getShortDay(day) + ""); + } 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, "" + weekNumber + + ""); + } + 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 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(); + } + } + } diff --cc src/com/vaadin/terminal/gwt/client/ui/VCheckBoxPaintable.java index 03233c6e27,0000000000..06ef54c13a mode 100644,000000..100644 --- a/src/com/vaadin/terminal/gwt/client/ui/VCheckBoxPaintable.java +++ b/src/com/vaadin/terminal/gwt/client/ui/VCheckBoxPaintable.java @@@ -1,96 -1,0 +1,96 @@@ - 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); - } - - } ++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); ++ } ++ ++} diff --cc src/com/vaadin/terminal/gwt/client/ui/VCssLayoutPaintable.java index d8640e3fe5,0000000000..1b4db40962 mode 100644,000000..100644 --- a/src/com/vaadin/terminal/gwt/client/ui/VCssLayoutPaintable.java +++ b/src/com/vaadin/terminal/gwt/client/ui/VCssLayoutPaintable.java @@@ -1,61 -1,0 +1,61 @@@ - 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 HandlerRegistration registerHandler( - H handler, Type 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); - } - - } ++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 HandlerRegistration registerHandler( ++ H handler, Type 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); ++ } ++ ++} diff --cc src/com/vaadin/terminal/gwt/client/ui/VCustomComponentPaintable.java index 3abcd9cd75,0000000000..7c0568e28e mode 100644,000000..100644 --- a/src/com/vaadin/terminal/gwt/client/ui/VCustomComponentPaintable.java +++ b/src/com/vaadin/terminal/gwt/client/ui/VCustomComponentPaintable.java @@@ -1,79 -1,0 +1,79 @@@ - 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 - } - - } ++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 ++ } ++ ++} diff --cc src/com/vaadin/terminal/gwt/client/ui/VCustomLayoutPaintable.java index 7997355136,0000000000..01190b39be mode 100644,000000..100644 --- a/src/com/vaadin/terminal/gwt/client/ui/VCustomLayoutPaintable.java +++ b/src/com/vaadin/terminal/gwt/client/ui/VCustomLayoutPaintable.java @@@ -1,87 -1,0 +1,87 @@@ - 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 oldWidgets = new HashSet(); - 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 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); - - } - } ++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 oldWidgets = new HashSet(); ++ 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 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); ++ ++ } ++} diff --cc src/com/vaadin/terminal/gwt/client/ui/VDateFieldCalendar.java index 6fb8456258,91388edcaf..6bf1d4a3a7 --- a/src/com/vaadin/terminal/gwt/client/ui/VDateFieldCalendar.java +++ b/src/com/vaadin/terminal/gwt/client/ui/VDateFieldCalendar.java @@@ -1,87 -1,153 +1,87 @@@ - /* - @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.DateTimeService; - import com.vaadin.terminal.gwt.client.ui.VCalendarPanel.FocusOutListener; - import com.vaadin.terminal.gwt.client.ui.VCalendarPanel.SubmitListener; - - /** - * A client side implementation for InlineDateField - */ - public class VDateFieldCalendar extends VDateField { - - 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; - } - }); - } - - /** - * TODO refactor: almost same method as in VPopupCalendar.updateValue - */ - @SuppressWarnings("deprecation") - 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(); - } - } - } - } + /* + @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(); + } + } + } + } diff --cc src/com/vaadin/terminal/gwt/client/ui/VDragAndDropWrapperPaintable.java index 1deb155001,0000000000..2a3189d9ba mode 100644,000000..100644 --- a/src/com/vaadin/terminal/gwt/client/ui/VDragAndDropWrapperPaintable.java +++ b/src/com/vaadin/terminal/gwt/client/ui/VDragAndDropWrapperPaintable.java @@@ -1,71 -1,0 +1,71 @@@ - 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 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(); - } - 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(); - } - - } ++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 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(); ++ } ++ 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(); ++ } ++ ++} diff --cc src/com/vaadin/terminal/gwt/client/ui/VFormLayoutPaintable.java index c4590a71c9,0000000000..1efdcfc722 mode 100644,000000..100644 --- a/src/com/vaadin/terminal/gwt/client/ui/VFormLayoutPaintable.java +++ b/src/com/vaadin/terminal/gwt/client/ui/VFormLayoutPaintable.java @@@ -1,39 -1,0 +1,39 @@@ - 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); - } - - } ++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); ++ } ++ ++} diff --cc src/com/vaadin/terminal/gwt/client/ui/VFormPaintable.java index 5f519c09d4,0000000000..4b59d64a71 mode 100644,000000..100644 --- a/src/com/vaadin/terminal/gwt/client/ui/VFormPaintable.java +++ b/src/com/vaadin/terminal/gwt/client/ui/VFormPaintable.java @@@ -1,173 -1,0 +1,173 @@@ - 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); - } - - } ++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); ++ } ++ ++} diff --cc src/com/vaadin/terminal/gwt/client/ui/VGridLayoutPaintable.java index 1ef958183b,0000000000..639ac1f8de mode 100644,000000..100644 --- a/src/com/vaadin/terminal/gwt/client/ui/VGridLayoutPaintable.java +++ b/src/com/vaadin/terminal/gwt/client/ui/VGridLayoutPaintable.java @@@ -1,193 -1,0 +1,193 @@@ - 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 HandlerRegistration registerHandler( - H handler, Type 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) getWidgetForPaintable().widgetToComponentContainer - .clone(); - - final int[] alignments = uidl.getIntArrayAttribute("alignments"); - int alignmentIndex = 0; - - LinkedList pendingCells = new LinkedList(); - - LinkedList relativeHeighted = new LinkedList(); - - 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); - } - - } ++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 HandlerRegistration registerHandler( ++ H handler, Type 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) getWidgetForPaintable().widgetToComponentContainer ++ .clone(); ++ ++ final int[] alignments = uidl.getIntArrayAttribute("alignments"); ++ int alignmentIndex = 0; ++ ++ LinkedList pendingCells = new LinkedList(); ++ ++ LinkedList relativeHeighted = new LinkedList(); ++ ++ 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); ++ } ++ ++} diff --cc src/com/vaadin/terminal/gwt/client/ui/VHorizontalLayoutPaintable.java index b72f5222cc,0000000000..e5fb4e138b mode 100644,000000..100644 --- a/src/com/vaadin/terminal/gwt/client/ui/VHorizontalLayoutPaintable.java +++ b/src/com/vaadin/terminal/gwt/client/ui/VHorizontalLayoutPaintable.java @@@ -1,17 -1,0 +1,17 @@@ - 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); - } - - } ++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); ++ } ++ ++} diff --cc src/com/vaadin/terminal/gwt/client/ui/VHorizontalSplitPanelPaintable.java index 2340ceb0b6,0000000000..ebc8a5e523 mode 100644,000000..100644 --- a/src/com/vaadin/terminal/gwt/client/ui/VHorizontalSplitPanelPaintable.java +++ b/src/com/vaadin/terminal/gwt/client/ui/VHorizontalSplitPanelPaintable.java @@@ -1,13 -1,0 +1,13 @@@ - 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); - } - - } ++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); ++ } ++ ++} diff --cc src/com/vaadin/terminal/gwt/client/ui/VMediaBasePaintable.java index fc709d56b3,0000000000..bef770f38b mode 100644,000000..100644 --- a/src/com/vaadin/terminal/gwt/client/ui/VMediaBasePaintable.java +++ b/src/com/vaadin/terminal/gwt/client/ui/VMediaBasePaintable.java @@@ -1,109 -1,0 +1,109 @@@ - 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); - } - - } ++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); ++ } ++ ++} diff --cc src/com/vaadin/terminal/gwt/client/ui/VMenuBarPaintable.java index fabc77bced,0000000000..ef2a49b9d0 mode 100644,000000..100644 --- a/src/com/vaadin/terminal/gwt/client/ui/VMenuBarPaintable.java +++ b/src/com/vaadin/terminal/gwt/client/ui/VMenuBarPaintable.java @@@ -1,161 -1,0 +1,161 @@@ - /* - @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("\"\""); - } - - 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 itr = uidlItems.getChildIterator(); - Stack> iteratorStack = new Stack>(); - Stack menuStack = new Stack(); - 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(); - } - - } ++/* ++@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("\"\""); ++ } ++ ++ 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 itr = uidlItems.getChildIterator(); ++ Stack> iteratorStack = new Stack>(); ++ Stack menuStack = new Stack(); ++ 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(); ++ } ++ ++} diff --cc src/com/vaadin/terminal/gwt/client/ui/VOrderedLayoutPaintable.java index 4720e07099,0000000000..5fa4f18efe mode 100644,000000..100644 --- a/src/com/vaadin/terminal/gwt/client/ui/VOrderedLayoutPaintable.java +++ b/src/com/vaadin/terminal/gwt/client/ui/VOrderedLayoutPaintable.java @@@ -1,254 -1,0 +1,254 @@@ - 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 HandlerRegistration registerHandler( - H handler, Type 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 uidlWidgets = new ArrayList( - uidl.getChildCount()); - ArrayList relativeSizeComponents = new ArrayList(); - ArrayList relativeSizeComponentUIDL = new ArrayList(); - - int pos = 0; - for (final Iterator 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(); - } - - } ++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 HandlerRegistration registerHandler( ++ H handler, Type 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 uidlWidgets = new ArrayList( ++ uidl.getChildCount()); ++ ArrayList relativeSizeComponents = new ArrayList(); ++ ArrayList relativeSizeComponentUIDL = new ArrayList(); ++ ++ int pos = 0; ++ for (final Iterator 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(); ++ } ++ ++} diff --cc src/com/vaadin/terminal/gwt/client/ui/VPanelPaintable.java index 198d7f4020,0000000000..c401c6db84 mode 100644,000000..100644 --- a/src/com/vaadin/terminal/gwt/client/ui/VPanelPaintable.java +++ b/src/com/vaadin/terminal/gwt/client/ui/VPanelPaintable.java @@@ -1,175 -1,0 +1,175 @@@ - 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 HandlerRegistration registerHandler( - H handler, Type 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); - } - - } ++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 HandlerRegistration registerHandler( ++ H handler, Type 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); ++ } ++ ++} diff --cc src/com/vaadin/terminal/gwt/client/ui/VPopupCalendar.java index 223e13c8d7,8bf2f6bfbf..1c0b937e05 --- a/src/com/vaadin/terminal/gwt/client/ui/VPopupCalendar.java +++ b/src/com/vaadin/terminal/gwt/client/ui/VPopupCalendar.java @@@ -1,378 -1,482 +1,378 @@@ - /* - @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.BrowserInfo; - import com.vaadin.terminal.gwt.client.VConsole; - import com.vaadin.terminal.gwt.client.ui.VCalendarPanel.FocusOutListener; - import com.vaadin.terminal.gwt.client.ui.VCalendarPanel.SubmitListener; - - /** - * Represents a date selection component with a text field and a popup date - * selector. - * - * Note: To change the keyboard assignments used in the popup dialog you - * should extend com.vaadin.terminal.gwt.client.ui.VCalendarPanel - * and then pass set it by calling the - * setCalendarPanel(VCalendarPanel panel) method. - * - */ - public class VPopupCalendar extends VTextualDate implements Field, - ClickHandler, CloseHandler, SubPartAware { - - protected static final String POPUP_PRIMARY_STYLE_NAME = VDateField.CLASSNAME - + "-popup"; - - protected final Button calendarToggle; - - protected VCalendarPanel calendar; - - protected final VOverlay popup; - private boolean open = false; - 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") - 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 (isImmediate()) { - getClient().sendPendingVariableChanges(); - } - } - } - - /* - * (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 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 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); - } - - } + /* + @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. + * + * Note: To change the keyboard assignments used in the popup dialog you + * should extend com.vaadin.terminal.gwt.client.ui.VCalendarPanel + * and then pass set it by calling the + * setCalendarPanel(VCalendarPanel panel) method. + * + */ -public class VPopupCalendar extends VTextualDate implements Paintable, Field, ++public class VPopupCalendar extends VTextualDate implements Field, + ClickHandler, CloseHandler, 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 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); + } + + } diff --cc src/com/vaadin/terminal/gwt/client/ui/VPopupViewPaintable.java index 627f925d77,0000000000..e2399bafed mode 100644,000000..100644 --- a/src/com/vaadin/terminal/gwt/client/ui/VPopupViewPaintable.java +++ b/src/com/vaadin/terminal/gwt/client/ui/VPopupViewPaintable.java @@@ -1,104 -1,0 +1,104 @@@ - 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); - } - - } ++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); ++ } ++ ++} diff --cc src/com/vaadin/terminal/gwt/client/ui/VScrollTablePaintable.java index fa7cc3d4ec,0000000000..0c41ed1aa3 mode 100644,000000..100644 --- a/src/com/vaadin/terminal/gwt/client/ui/VScrollTablePaintable.java +++ b/src/com/vaadin/terminal/gwt/client/ui/VScrollTablePaintable.java @@@ -1,254 -1,0 +1,254 @@@ - /* - @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(); - } - } ++/* ++@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(); ++ } ++} diff --cc src/com/vaadin/terminal/gwt/client/ui/VSlider.java index 9fbbeb7181,4a46346613..6e2ff0930e --- a/src/com/vaadin/terminal/gwt/client/ui/VSlider.java +++ b/src/com/vaadin/terminal/gwt/client/ui/VSlider.java @@@ -1,517 -1,599 +1,517 @@@ - /* - @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.Util; - import com.vaadin.terminal.gwt.client.VConsole; - - 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; - - boolean immediate; - boolean disabled; - boolean readonly; - - private int acceleration = 1; - 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); - } - - 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()); - } - } - - 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 - } - - void buildHandle() { - final String handleAttribute = vertical ? "marginTop" : "marginLeft"; - - DOM.setStyleAttribute(handle, handleAttribute, "0"); - - // Restore visibility - DOM.setStyleAttribute(handle, "visibility", "visible"); - - } - - 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) { - 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)) { - 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; - } - } + /* + @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; ++ } + } diff --cc src/com/vaadin/terminal/gwt/client/ui/VSliderPaintable.java index f5b8c8a45e,0000000000..c4e484a76b mode 100644,000000..100644 --- a/src/com/vaadin/terminal/gwt/client/ui/VSliderPaintable.java +++ b/src/com/vaadin/terminal/gwt/client/ui/VSliderPaintable.java @@@ -1,78 -1,0 +1,78 @@@ - 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); - } - - } ++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); ++ } ++ ++} diff --cc src/com/vaadin/terminal/gwt/client/ui/VTabsheetBasePaintable.java index 3fbc52c2ca,0000000000..ec3b02de97 mode 100644,000000..100644 --- a/src/com/vaadin/terminal/gwt/client/ui/VTabsheetBasePaintable.java +++ b/src/com/vaadin/terminal/gwt/client/ui/VTabsheetBasePaintable.java @@@ -1,96 -1,0 +1,96 @@@ - 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 oldWidgets = new ArrayList(); - for (Iterator iterator = getWidgetForPaintable() - .getWidgetIterator(); iterator.hasNext();) { - oldWidgets.add(iterator.next()); - } - - // Clear previous values - getWidgetForPaintable().tabKeys.clear(); - getWidgetForPaintable().disabledTabKeys.clear(); - - int index = 0; - for (final Iterator 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 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(); - } - - } ++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 oldWidgets = new ArrayList(); ++ for (Iterator iterator = getWidgetForPaintable() ++ .getWidgetIterator(); iterator.hasNext();) { ++ oldWidgets.add(iterator.next()); ++ } ++ ++ // Clear previous values ++ getWidgetForPaintable().tabKeys.clear(); ++ getWidgetForPaintable().disabledTabKeys.clear(); ++ ++ int index = 0; ++ for (final Iterator 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 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(); ++ } ++ ++} diff --cc src/com/vaadin/terminal/gwt/client/ui/VTabsheetPaintable.java index e8d6da757e,0000000000..4bd91683d6 mode 100644,000000..100644 --- a/src/com/vaadin/terminal/gwt/client/ui/VTabsheetPaintable.java +++ b/src/com/vaadin/terminal/gwt/client/ui/VTabsheetPaintable.java @@@ -1,82 -1,0 +1,82 @@@ - 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 */ - } - - } ++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 */ ++ } ++ ++} diff --cc src/com/vaadin/terminal/gwt/client/ui/VTextArea.java index bd58c38829,c6107e3b0e..2c8ed24693 --- a/src/com/vaadin/terminal/gwt/client/ui/VTextArea.java +++ b/src/com/vaadin/terminal/gwt/client/ui/VTextArea.java @@@ -1,63 -1,79 +1,63 @@@ - /* - @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; - - /** - * 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); - } - - 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()); - } - } + /* + @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()); + } + } diff --cc src/com/vaadin/terminal/gwt/client/ui/VTreePaintable.java index c058a15376,0000000000..d7f8fffbd7 mode 100644,000000..100644 --- a/src/com/vaadin/terminal/gwt/client/ui/VTreePaintable.java +++ b/src/com/vaadin/terminal/gwt/client/ui/VTreePaintable.java @@@ -1,228 -1,0 +1,228 @@@ - 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 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; - } - } ++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 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; ++ } ++} diff --cc src/com/vaadin/terminal/gwt/client/ui/VTreeTablePaintable.java index 9b6f03f612,0000000000..8c159f43de mode 100644,000000..100644 --- a/src/com/vaadin/terminal/gwt/client/ui/VTreeTablePaintable.java +++ b/src/com/vaadin/terminal/gwt/client/ui/VTreeTablePaintable.java @@@ -1,101 -1,0 +1,101 @@@ - /* - @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(); - } - } ++/* ++@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(); ++ } ++} diff --cc src/com/vaadin/terminal/gwt/client/ui/VVerticalLayoutPaintable.java index 5378218ece,0000000000..b911d0f013 mode 100644,000000..100644 --- a/src/com/vaadin/terminal/gwt/client/ui/VVerticalLayoutPaintable.java +++ b/src/com/vaadin/terminal/gwt/client/ui/VVerticalLayoutPaintable.java @@@ -1,17 -1,0 +1,17 @@@ - 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); - } - - } ++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); ++ } ++ ++} diff --cc src/com/vaadin/terminal/gwt/client/ui/VVerticalSplitPanelPaintable.java index d60a3185af,0000000000..5b8f978b28 mode 100644,000000..100644 --- a/src/com/vaadin/terminal/gwt/client/ui/VVerticalSplitPanelPaintable.java +++ b/src/com/vaadin/terminal/gwt/client/ui/VVerticalSplitPanelPaintable.java @@@ -1,12 -1,0 +1,12 @@@ - 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); - } - - } ++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); ++ } ++ ++} diff --cc src/com/vaadin/terminal/gwt/client/ui/VVideoPaintable.java index a9a46671be,0000000000..ac4b735cae mode 100644,000000..100644 --- a/src/com/vaadin/terminal/gwt/client/ui/VVideoPaintable.java +++ b/src/com/vaadin/terminal/gwt/client/ui/VVideoPaintable.java @@@ -1,38 -1,0 +1,38 @@@ - 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); - } - - } ++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); ++ } ++ ++} diff --cc src/com/vaadin/terminal/gwt/client/ui/VViewPaintable.java index ebec292ecb,0000000000..ccf7185c14 mode 100644,000000..100644 --- a/src/com/vaadin/terminal/gwt/client/ui/VViewPaintable.java +++ b/src/com/vaadin/terminal/gwt/client/ui/VViewPaintable.java @@@ -1,331 -1,0 +1,331 @@@ - 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 removedSubWindows = new HashSet( - 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 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 HandlerRegistration registerHandler( - H handler, Type 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); - } - - } ++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 removedSubWindows = new HashSet( ++ 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 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 HandlerRegistration registerHandler( ++ H handler, Type 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); ++ } ++ ++} diff --cc src/com/vaadin/terminal/gwt/client/ui/VWindowPaintable.java index 25fd951dd9,0000000000..65ce4a672a mode 100644,000000..100644 --- a/src/com/vaadin/terminal/gwt/client/ui/VWindowPaintable.java +++ b/src/com/vaadin/terminal/gwt/client/ui/VWindowPaintable.java @@@ -1,296 -1,0 +1,296 @@@ - 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 HandlerRegistration registerHandler( - H handler, Type 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); - } - - } ++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 HandlerRegistration registerHandler( ++ H handler, Type 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); ++ } ++ ++} diff --cc src/com/vaadin/terminal/gwt/client/ui/label/VLabelPaintable.java index 269afde25d,0000000000..c57f705c75 mode 100644,000000..100644 --- a/src/com/vaadin/terminal/gwt/client/ui/label/VLabelPaintable.java +++ b/src/com/vaadin/terminal/gwt/client/ui/label/VLabelPaintable.java @@@ -1,71 -1,0 +1,71 @@@ - /* - @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(); - } - - } ++/* ++@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(); ++ } ++ ++} diff --cc src/com/vaadin/terminal/gwt/client/ui/layout/CellBasedLayoutPaintable.java index e99425311b,0000000000..5fc74c056e mode 100644,000000..100644 --- a/src/com/vaadin/terminal/gwt/client/ui/layout/CellBasedLayoutPaintable.java +++ b/src/com/vaadin/terminal/gwt/client/ui/layout/CellBasedLayoutPaintable.java @@@ -1,81 -1,0 +1,81 @@@ - 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(); - } - } ++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(); ++ } ++} diff --cc src/com/vaadin/terminal/gwt/client/ui/richtextarea/VRichTextAreaPaintable.java index 477cd13dd5,0000000000..1dadf8cc17 mode 100644,000000..100644 --- a/src/com/vaadin/terminal/gwt/client/ui/richtextarea/VRichTextAreaPaintable.java +++ b/src/com/vaadin/terminal/gwt/client/ui/richtextarea/VRichTextAreaPaintable.java @@@ -1,76 -1,0 +1,76 @@@ - 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); - } - - } ++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); ++ } ++ ++} diff --cc src/com/vaadin/terminal/gwt/server/WrappedPortletRequest.java index 93627c1ff1,0000000000..2c9828b66b mode 100644,000000..100644 --- a/src/com/vaadin/terminal/gwt/server/WrappedPortletRequest.java +++ b/src/com/vaadin/terminal/gwt/server/WrappedPortletRequest.java @@@ -1,175 -1,0 +1,175 @@@ - /* - @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 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 null 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 WrappedPortlettRequest from a - * WrappedRequest. 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; - } - } ++/* ++@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 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 null 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 WrappedPortlettRequest from a ++ * WrappedRequest. 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; ++ } ++} diff --cc src/com/vaadin/ui/ComboBox.java index b4307188a7,bc7ab6f994..013fe6ab85 --- a/src/com/vaadin/ui/ComboBox.java +++ b/src/com/vaadin/ui/ComboBox.java @@@ -1,130 -1,129 +1,130 @@@ - /* - @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(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; - } - - } + /* + @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; + } + + } diff --cc src/com/vaadin/ui/InlineDateField.java index b0e830a75a,50e16d803b..b4160604ff --- a/src/com/vaadin/ui/InlineDateField.java +++ b/src/com/vaadin/ui/InlineDateField.java @@@ -1,48 -1,48 +1,48 @@@ - /* - @VaadinApache2LicenseForJavaFiles@ - */ - - package com.vaadin.ui; - - import java.util.Date; - - import com.vaadin.data.Property; - import com.vaadin.terminal.gwt.client.ui.VDateFieldCalendarPaintable; - - /** - *

- * A date entry component, which displays the actual date selector inline. - * - *

- * - * @see DateField - * @see PopupDateField - * @author Vaadin Ltd. - * @version - * @VERSION@ - * @since 5.0 - */ - @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); - } - - } + /* + @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; + + /** + *

+ * A date entry component, which displays the actual date selector inline. + * + *

+ * + * @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); + } + + } diff --cc tests/server-side/com/vaadin/data/util/ObjectPropertyTest.java index 0ed554a1a0,11676099e6..99ca58ba42 --- a/tests/server-side/com/vaadin/data/util/ObjectPropertyTest.java +++ b/tests/server-side/com/vaadin/data/util/ObjectPropertyTest.java @@@ -1,97 -1,99 +1,97 @@@ - package com.vaadin.data.util; - - import junit.framework.TestCase; - - import org.junit.Assert; - - 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 prop1 = new ObjectProperty( - super1, TestSuperClass.class); - Assert.assertEquals("super1", prop1.getValue().getName()); - prop1 = new ObjectProperty(super1); - Assert.assertEquals("super1", prop1.getValue().getName()); - - ObjectProperty prop2 = new ObjectProperty( - sub1, TestSubClass.class); - Assert.assertEquals("Subclass: sub1", prop2.getValue().getName()); - prop2 = new ObjectProperty(sub1); - Assert.assertEquals("Subclass: sub1", prop2.getValue().getName()); - } - - public void testSetValueObjectSuper() { - ObjectProperty prop = new ObjectProperty( - 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 prop = new ObjectProperty( - 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 prop = new ObjectProperty( - 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 testSetValueStringSub() { - ObjectProperty prop = new ObjectProperty( - 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 testMixedGenerics() { - ObjectProperty prop = new ObjectProperty( - 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(new TestSubClass("sub2")); - Assert.assertEquals("Subclass: sub2", prop.getValue().getName()); - } - - } + 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 prop1 = new ObjectProperty( + super1, TestSuperClass.class); + Assert.assertEquals("super1", prop1.getValue().getName()); + prop1 = new ObjectProperty(super1); + Assert.assertEquals("super1", prop1.getValue().getName()); + + ObjectProperty prop2 = new ObjectProperty( + sub1, TestSubClass.class); + Assert.assertEquals("Subclass: sub1", prop2.getValue().getName()); + prop2 = new ObjectProperty(sub1); + Assert.assertEquals("Subclass: sub1", prop2.getValue().getName()); + } + + public void testSetValueObjectSuper() { + ObjectProperty prop = new ObjectProperty( + 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 prop = new ObjectProperty( + 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 prop = new ObjectProperty( + 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 prop = new ObjectProperty( + 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 prop = new ObjectProperty( + 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()); + } + + } diff --cc tests/server-side/com/vaadin/data/util/TestContainerSorting.java index 8f078199f5,d9a8e6e51c..9e69b94fbb --- a/tests/server-side/com/vaadin/data/util/TestContainerSorting.java +++ b/tests/server-side/com/vaadin/data/util/TestContainerSorting.java @@@ -1,223 -1,238 +1,223 @@@ - 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.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" }); - TestUtil.assertArrays( - hc.rootItemIds().toArray(), - new Integer[] { nameToId.get("Cars"), nameToId.get("Games"), - nameToId.get("Natural languages"), - nameToId.get("Programming languages") }); - 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 nameToId = new HashMap(); - private static Map idToName = new HashMap(); - - 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; - } - - 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 { - 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); - } - } - } - - } + 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 nameToId = new HashMap(); + private static Map idToName = new HashMap(); + + 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 { + 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); + } + } + } + + } diff --cc tests/server-side/com/vaadin/tests/data/bean/Address.java index 73e0bd20fb,0000000000..15cdf34ae5 mode 100644,000000..100644 --- a/tests/server-side/com/vaadin/tests/data/bean/Address.java +++ b/tests/server-side/com/vaadin/tests/data/bean/Address.java @@@ -1,63 -1,0 +1,63 @@@ - 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; - } - - } ++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; ++ } ++ ++} diff --cc tests/server-side/com/vaadin/tests/data/bean/BeanToValidate.java index be8e40a118,0000000000..416563baba mode 100644,000000..100644 --- a/tests/server-side/com/vaadin/tests/data/bean/BeanToValidate.java +++ b/tests/server-side/com/vaadin/tests/data/bean/BeanToValidate.java @@@ -1,56 -1,0 +1,56 @@@ - 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; - } - - } ++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; ++ } ++ ++} diff --cc tests/server-side/com/vaadin/tests/data/bean/Country.java index 77192e3057,0000000000..afdf8dcfa1 mode 100644,000000..100644 --- a/tests/server-side/com/vaadin/tests/data/bean/Country.java +++ b/tests/server-side/com/vaadin/tests/data/bean/Country.java @@@ -1,18 -1,0 +1,18 @@@ - 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; - } - } ++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; ++ } ++} diff --cc tests/server-side/com/vaadin/tests/data/bean/Person.java index c9ef8e9d70,0000000000..2cb3a29368 mode 100644,000000..100644 --- a/tests/server-side/com/vaadin/tests/data/bean/Person.java +++ b/tests/server-side/com/vaadin/tests/data/bean/Person.java @@@ -1,133 -1,0 +1,133 @@@ - 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; - } - - } ++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; ++ } ++ ++} diff --cc tests/server-side/com/vaadin/tests/data/bean/PersonWithBeanValidationAnnotations.java index 4a7d5a5c2e,0000000000..93b2273263 mode 100644,000000..100644 --- a/tests/server-side/com/vaadin/tests/data/bean/PersonWithBeanValidationAnnotations.java +++ b/tests/server-side/com/vaadin/tests/data/bean/PersonWithBeanValidationAnnotations.java @@@ -1,156 -1,0 +1,156 @@@ - 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; - } - - } ++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; ++ } ++ ++} diff --cc tests/server-side/com/vaadin/tests/data/bean/Sex.java index cce0dfad53,0000000000..a4e3f20a11 mode 100644,000000..100644 --- a/tests/server-side/com/vaadin/tests/data/bean/Sex.java +++ b/tests/server-side/com/vaadin/tests/data/bean/Sex.java @@@ -1,20 -1,0 +1,20 @@@ - 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.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(); ++ } ++} diff --cc tests/server-side/com/vaadin/tests/server/TransactionListenersConcurrency.java index 2eed8c846a,224c9f5964..6c762c666d --- a/tests/server-side/com/vaadin/tests/server/TransactionListenersConcurrency.java +++ b/tests/server-side/com/vaadin/tests/server/TransactionListenersConcurrency.java @@@ -1,185 -1,185 +1,185 @@@ - 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 exceptions = new ArrayList(); - - HttpSession session = createSession(); - final WebApplicationContext context = WebApplicationContext - .getApplicationContext(session); - List threads = new ArrayList(); - - 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, 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 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; + + 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 exceptions = new ArrayList(); + + HttpSession session = createSession(); + final WebApplicationContext context = WebApplicationContext + .getApplicationContext(session); + List threads = new ArrayList(); + + 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 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(); + } + + } + } + + } diff --cc tests/server-side/com/vaadin/tests/server/component/absolutelayout/ComponentPosition.java index ba45448213,ee8ef6bfbc..4458872c79 --- a/tests/server-side/com/vaadin/tests/server/component/absolutelayout/ComponentPosition.java +++ b/tests/server-side/com/vaadin/tests/server/component/absolutelayout/ComponentPosition.java @@@ -1,204 -1,205 +1,204 @@@ - 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 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.Unit.PIXELS, layout.getPosition(b).getTopUnits()); - assertEquals(Sizeable.Unit.PICAS, layout.getPosition(b) - .getBottomUnits()); - 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.Unit.PIXELS, layout.getPosition(b).getTopUnits()); - assertEquals(UNIT_UNSET, layout.getPosition(b).getBottomUnits()); - 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.Unit.PIXELS, layout.getPosition(b).getTopUnits()); - assertEquals(UNIT_UNSET, layout.getPosition(b).getBottomUnits()); - 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.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.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.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.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()); - - } - - } + 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()); + + } + + } diff --cc tests/server-side/com/vaadin/tests/server/component/abstractfield/AbstractFieldValueConversions.java index 753afbdd06,0000000000..050ab282a6 mode 100644,000000..100644 --- a/tests/server-side/com/vaadin/tests/server/component/abstractfield/AbstractFieldValueConversions.java +++ b/tests/server-side/com/vaadin/tests/server/component/abstractfield/AbstractFieldValueConversions.java @@@ -1,162 -1,0 +1,162 @@@ - 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(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() { - - public String convertToModel(String value, Locale locale) { - return value; - } - - public String convertToPresentation(String value, Locale locale) { - return value; - } - - public Class getModelType() { - return String.class; - } - - public Class getPresentationType() { - return String.class; - } - }); - tf.setPropertyDataSource(new MethodProperty(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() { - - public Integer convertToModel(String value, Locale locale) { - throw new ConversionException("Failed"); - } - - public String convertToPresentation(Integer value, Locale locale) { - throw new ConversionException("Failed"); - } - - public Class getModelType() { - // TODO Auto-generated method stub - return null; - } - - public Class 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(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() { - - 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 getModelType() { - return Boolean.class; - } - - public Class getPresentationType() { - return Boolean.class; - } - - }); - MethodProperty property = new MethodProperty( - 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()); - - } - - } ++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(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() { ++ ++ public String convertToModel(String value, Locale locale) { ++ return value; ++ } ++ ++ public String convertToPresentation(String value, Locale locale) { ++ return value; ++ } ++ ++ public Class getModelType() { ++ return String.class; ++ } ++ ++ public Class getPresentationType() { ++ return String.class; ++ } ++ }); ++ tf.setPropertyDataSource(new MethodProperty(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() { ++ ++ public Integer convertToModel(String value, Locale locale) { ++ throw new ConversionException("Failed"); ++ } ++ ++ public String convertToPresentation(Integer value, Locale locale) { ++ throw new ConversionException("Failed"); ++ } ++ ++ public Class getModelType() { ++ // TODO Auto-generated method stub ++ return null; ++ } ++ ++ public Class 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(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() { ++ ++ 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 getModelType() { ++ return Boolean.class; ++ } ++ ++ public Class getPresentationType() { ++ return Boolean.class; ++ } ++ ++ }); ++ MethodProperty property = new MethodProperty( ++ 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()); ++ ++ } ++ ++} diff --cc tests/server-side/com/vaadin/tests/server/component/abstractfield/DefaultConverterFactory.java index 8a6bcf2e01,0000000000..e39b5d6629 mode 100644,000000..100644 --- a/tests/server-side/com/vaadin/tests/server/component/abstractfield/DefaultConverterFactory.java +++ b/tests/server-side/com/vaadin/tests/server/component/abstractfield/DefaultConverterFactory.java @@@ -1,48 -1,0 +1,48 @@@ - 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(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(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; ++ ++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(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(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); ++ } ++} diff --cc tests/server-side/com/vaadin/tests/server/component/abstractfield/TestAbstractFieldListeners.java index 2a5b50f4bb,7ee70bde13..9937bf92d5 --- a/tests/server-side/com/vaadin/tests/server/component/abstractfield/TestAbstractFieldListeners.java +++ b/tests/server-side/com/vaadin/tests/server/component/abstractfield/TestAbstractFieldListeners.java @@@ -1,21 -1,20 +1,21 @@@ - 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.CheckBox; - - public class TestAbstractFieldListeners extends AbstractListenerMethodsTest { - public void testReadOnlyStatusChangeListenerAddGetRemove() throws Exception { - testListenerAddGetRemove(CheckBox.class, - ReadOnlyStatusChangeEvent.class, - ReadOnlyStatusChangeListener.class); - } - - public void testValueChangeListenerAddGetRemove() throws Exception { - testListenerAddGetRemove(CheckBox.class, ValueChangeEvent.class, - ValueChangeListener.class); - } - } + 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); + } + } diff --cc tests/server-side/com/vaadin/tests/server/component/datefield/ResolutionTest.java index 88dceca9e7,0000000000..00b5c60dad mode 100644,000000..100644 --- a/tests/server-side/com/vaadin/tests/server/component/datefield/ResolutionTest.java +++ b/tests/server-side/com/vaadin/tests/server/component/datefield/ResolutionTest.java @@@ -1,61 -1,0 +1,61 @@@ - 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 higherOrEqual = Resolution - .getResolutionsHigherOrEqualTo(Resolution.YEAR); - ArrayList expected = new ArrayList(); - expected.add(Resolution.YEAR); - TestUtil.assertIterableEquals(expected, higherOrEqual); - } - - public void testResolutionHigherOrEqualToDay() { - Iterable higherOrEqual = Resolution - .getResolutionsHigherOrEqualTo(Resolution.DAY); - ArrayList expected = new ArrayList(); - expected.add(Resolution.DAY); - expected.add(Resolution.MONTH); - expected.add(Resolution.YEAR); - TestUtil.assertIterableEquals(expected, higherOrEqual); - - } - - public void testResolutionLowerThanDay() { - Iterable higherOrEqual = Resolution - .getResolutionsLowerThan(Resolution.DAY); - ArrayList expected = new ArrayList(); - expected.add(Resolution.HOUR); - expected.add(Resolution.MINUTE); - expected.add(Resolution.SECOND); - TestUtil.assertIterableEquals(expected, higherOrEqual); - - } - - public void testResolutionLowerThanSecond() { - Iterable higherOrEqual = Resolution - .getResolutionsLowerThan(Resolution.SECOND); - ArrayList expected = new ArrayList(); - TestUtil.assertIterableEquals(expected, higherOrEqual); - } - - public void testResolutionLowerThanYear() { - Iterable higherOrEqual = Resolution - .getResolutionsLowerThan(Resolution.YEAR); - ArrayList expected = new ArrayList(); - expected.add(Resolution.MONTH); - expected.add(Resolution.DAY); - expected.add(Resolution.HOUR); - expected.add(Resolution.MINUTE); - expected.add(Resolution.SECOND); - TestUtil.assertIterableEquals(expected, higherOrEqual); - - } - } ++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 higherOrEqual = Resolution ++ .getResolutionsHigherOrEqualTo(Resolution.YEAR); ++ ArrayList expected = new ArrayList(); ++ expected.add(Resolution.YEAR); ++ TestUtil.assertIterableEquals(expected, higherOrEqual); ++ } ++ ++ public void testResolutionHigherOrEqualToDay() { ++ Iterable higherOrEqual = Resolution ++ .getResolutionsHigherOrEqualTo(Resolution.DAY); ++ ArrayList expected = new ArrayList(); ++ expected.add(Resolution.DAY); ++ expected.add(Resolution.MONTH); ++ expected.add(Resolution.YEAR); ++ TestUtil.assertIterableEquals(expected, higherOrEqual); ++ ++ } ++ ++ public void testResolutionLowerThanDay() { ++ Iterable higherOrEqual = Resolution ++ .getResolutionsLowerThan(Resolution.DAY); ++ ArrayList expected = new ArrayList(); ++ expected.add(Resolution.HOUR); ++ expected.add(Resolution.MINUTE); ++ expected.add(Resolution.SECOND); ++ TestUtil.assertIterableEquals(expected, higherOrEqual); ++ ++ } ++ ++ public void testResolutionLowerThanSecond() { ++ Iterable higherOrEqual = Resolution ++ .getResolutionsLowerThan(Resolution.SECOND); ++ ArrayList expected = new ArrayList(); ++ TestUtil.assertIterableEquals(expected, higherOrEqual); ++ } ++ ++ public void testResolutionLowerThanYear() { ++ Iterable higherOrEqual = Resolution ++ .getResolutionsLowerThan(Resolution.YEAR); ++ ArrayList expected = new ArrayList(); ++ expected.add(Resolution.MONTH); ++ expected.add(Resolution.DAY); ++ expected.add(Resolution.HOUR); ++ expected.add(Resolution.MINUTE); ++ expected.add(Resolution.SECOND); ++ TestUtil.assertIterableEquals(expected, higherOrEqual); ++ ++ } ++} diff --cc tests/server-side/com/vaadin/tests/server/component/slider/SliderTest.java index ab527b3d06,0000000000..b969bf5e53 mode 100644,000000..100644 --- a/tests/server-side/com/vaadin/tests/server/component/slider/SliderTest.java +++ b/tests/server-side/com/vaadin/tests/server/component/slider/SliderTest.java @@@ -1,25 -1,0 +1,25 @@@ - 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.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 ++ } ++ ++ } ++} diff --cc tests/server-side/com/vaadin/tests/server/component/window/AddRemoveSubWindow.java index ed01e07e06,50de91e2af..f8901803c3 --- a/tests/server-side/com/vaadin/tests/server/component/window/AddRemoveSubWindow.java +++ b/tests/server-side/com/vaadin/tests/server/component/window/AddRemoveSubWindow.java @@@ -1,79 -1,83 +1,79 @@@ - package com.vaadin.tests.server.component.window; - - import static org.junit.Assert.assertEquals; - 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.LegacyApplication { - - @Override - public void init() { - LegacyWindow w = new LegacyWindow("Main window"); - setMainWindow(w); - } - } - - @Test - public void addSubWindow() { - TestApp app = new TestApp(); - app.init(); - Window subWindow = new Window("Sub window"); - 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 { - 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"); - 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); - - // Parent should still be set - assertEquals(subWindow.getParent(), mainWindow); - - // Remove from the main window and assert it has been removed - boolean removed = mainWindow.removeWindow(subWindow); - assertTrue("Window was not removed correctly", removed); - assertNull(subWindow.getParent()); - } - } + 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()); + } + } diff --cc tests/server-side/com/vaadin/tests/server/component/window/AttachDetachWindow.java index db97c7e6f2,5fabe40bb7..a67c7bb387 --- a/tests/server-side/com/vaadin/tests/server/component/window/AttachDetachWindow.java +++ b/tests/server-side/com/vaadin/tests/server/component/window/AttachDetachWindow.java @@@ -1,248 -1,179 +1,248 @@@ - 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.terminal.WrappedRequest; - import com.vaadin.ui.Label; - import com.vaadin.ui.Root; - import com.vaadin.ui.VerticalLayout; - import com.vaadin.ui.Window; - - public class AttachDetachWindow { - - private Application testApp = new Application(); - - private interface TestContainer { - public boolean attachCalled(); - - public boolean detachCalled(); - - public TestContent getTestContent(); - - public Application getApplication(); - } - - private class TestWindow extends Window implements TestContainer { - boolean windowAttachCalled = false; - boolean windowDetachCalled = false; - private TestContent testContent = new TestContent();; - - TestWindow() { - 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; - } - } - - 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 - main.setApplication(testApp); - assertAttached(main); - assertAttached(sub); - } - - @Test - public void addSubWindowAfterAttachingMainWindow() { - assertUnattached(main); - assertUnattached(sub); - - 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() { - 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 - main.setApplication(null); - assertDetached(main); - assertDetached(sub); - } - - @Test - public void removeSubWindowAfterDetachingMainWindow() { - main.setApplication(testApp); - main.addWindow(sub); - - // main detach should recurse to sub - 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(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", testContent.getApplication(), - testApp); - assertSame("window children not attached", - testContent.child.getApplication(), testApp); - } - - /** - * Asserts that win and its children are not attached. - */ - private void assertUnattached(TestContainer win) { - assertSame("window not detached", win.getApplication(), null); - 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(TestContainer win) { - assertUnattached(win); - 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.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); + } + } diff --cc tests/server-side/com/vaadin/tests/server/components/AbstractTestFieldValueChange.java index bcdce383f8,fcea309e84..3512f555c9 --- a/tests/server-side/com/vaadin/tests/server/components/AbstractTestFieldValueChange.java +++ b/tests/server-side/com/vaadin/tests/server/components/AbstractTestFieldValueChange.java @@@ -1,169 -1,169 +1,169 @@@ - 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 - * super.setValue(AbstractField). Also, subclasses should typically - * override {@link #setValue(AbstractField)} to set the field value via - * changeVariables(). - */ - public abstract class AbstractTestFieldValueChange extends TestCase { - - private AbstractField field; - private ValueChangeListener listener; - - protected void setUp(AbstractField 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("")); - 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("")); - 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("")); - 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("")); - 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("")); - 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() { - return field; - } - - /** - * Override in subclasses to set value with changeVariables(). - */ - protected void setValue(AbstractField field) { - field.setValue("newValue"); - } - - } + 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 + * super.setValue(AbstractField). Also, subclasses should typically + * override {@link #setValue(AbstractField)} to set the field value via + * changeVariables(). + */ -public abstract class AbstractTestFieldValueChange extends TestCase { ++public abstract class AbstractTestFieldValueChange extends TestCase { + - private AbstractField field; ++ private AbstractField field; + private ValueChangeListener listener; + - protected void setUp(AbstractField field) throws Exception { ++ protected void setUp(AbstractField 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("")); + 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("")); + 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("")); + 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("")); + 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("")); + 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 getField() { + return field; + } + + /** + * Override in subclasses to set value with changeVariables(). + */ - protected void setValue(AbstractField field) { ++ protected void setValue(AbstractField field) { + field.setValue("newValue"); + } + + } diff --cc tests/server-side/com/vaadin/tests/server/components/TestComboBoxValueChange.java index 75066c8d4a,3fbe1406f2..1ca06a86aa --- a/tests/server-side/com/vaadin/tests/server/components/TestComboBoxValueChange.java +++ b/tests/server-side/com/vaadin/tests/server/components/TestComboBoxValueChange.java @@@ -1,31 -1,30 +1,31 @@@ - 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 Ticket 4394. - */ - public class TestComboBoxValueChange extends - AbstractTestFieldValueChange { - @Override - protected void setUp() throws Exception { - ComboBox combo = new ComboBox(); - combo.addItem("myvalue"); - super.setUp(combo); - } - - @Override - protected void setValue(AbstractField field) { - Map variables = new HashMap(); - variables.put("selected", new String[] { "myvalue" }); - field.changeVariables(field, variables); - } - - } + 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 Ticket 4394. + */ -public class TestComboBoxValueChange extends AbstractTestFieldValueChange { ++public class TestComboBoxValueChange extends ++ AbstractTestFieldValueChange { + @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 field) { + Map variables = new HashMap(); + variables.put("selected", new String[] { "myvalue" }); + field.changeVariables(field, variables); + } + + } diff --cc tests/server-side/com/vaadin/tests/server/components/TestTextFieldValueChange.java index d5cb02b477,2c911d5f3f..758c09d66e --- a/tests/server-side/com/vaadin/tests/server/components/TestTextFieldValueChange.java +++ b/tests/server-side/com/vaadin/tests/server/components/TestTextFieldValueChange.java @@@ -1,179 -1,180 +1,179 @@@ - 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 Ticket 4394. - */ - public class TestTextFieldValueChange extends - AbstractTestFieldValueChange { - - @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) { - Map variables = new HashMap(); - 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 property = new ObjectProperty(""); - getField().setPropertyDataSource(property); - - // defaults, buffering off - 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 property = new ObjectProperty( - 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 property = new ObjectProperty( - initialValue); - - // set buffering - 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; + + 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 Ticket 4394. + */ -public class TestTextFieldValueChange extends AbstractTestFieldValueChange { ++public class TestTextFieldValueChange extends ++ AbstractTestFieldValueChange { + + @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 field) { + Map variables = new HashMap(); + 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 property = new ObjectProperty(""); + 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 property = new ObjectProperty( + 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 property = new ObjectProperty( + 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()); + + } + + } diff --cc tests/server-side/com/vaadin/tests/server/components/TestWindow.java index 11462b8328,89d018c8a5..7713f69f68 --- a/tests/server-side/com/vaadin/tests/server/components/TestWindow.java +++ b/tests/server-side/com/vaadin/tests/server/components/TestWindow.java @@@ -1,92 -1,90 +1,92 @@@ - 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 variables = new HashMap(); - variables.put("height", 1234); - window.changeVariables(window, variables); - - } - - private static void sendClose(Window window) { - Map variables = new HashMap(); - variables.put("close", true); - window.changeVariables(window, variables); - } - } + 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 variables = new HashMap(); + variables.put("height", 1234); + window.changeVariables(window, variables); + + } + + private static void sendClose(Window window) { + Map variables = new HashMap(); + variables.put("close", true); + window.changeVariables(window, variables); + } + } diff --cc tests/server-side/com/vaadin/tests/server/validation/RangeValidatorTest.java index 2cb2c6a509,0000000000..e3320b8699 mode 100644,000000..100644 --- a/tests/server-side/com/vaadin/tests/server/validation/RangeValidatorTest.java +++ b/tests/server-side/com/vaadin/tests/server/validation/RangeValidatorTest.java @@@ -1,52 -1,0 +1,52 @@@ - 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; ++ ++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)); ++ } ++} diff --cc tests/server-side/com/vaadin/tests/server/validation/TestReadOnlyValidation.java index fdf1586a44,c4052c2db8..e37b97e02c --- a/tests/server-side/com/vaadin/tests/server/validation/TestReadOnlyValidation.java +++ b/tests/server-side/com/vaadin/tests/server/validation/TestReadOnlyValidation.java @@@ -1,17 -1,17 +1,17 @@@ - 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(String.valueOf(10)); - field.validate(); - } - } + 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(); + } + } diff --cc tests/server-side/com/vaadin/tests/util/GraphVizClassHierarchyCreator.java index 2399879ac8,0000000000..9e791500b0 mode 100644,000000..100644 --- a/tests/server-side/com/vaadin/tests/util/GraphVizClassHierarchyCreator.java +++ b/tests/server-side/com/vaadin/tests/util/GraphVizClassHierarchyCreator.java @@@ -1,149 -1,0 +1,149 @@@ - 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 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 classesAndParents = new HashSet(); - for (Class cls : classes) { - addClassAndParents(classesAndParents, cls, packageToInclude); - } - - Set interfaces = new HashSet(); - 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 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 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 interfaces, Class cls) { - if (interfaces.contains(cls)) { - return; - } - - if (cls.isInterface()) { - interfaces.add(cls); - } - - for (Class c : cls.getInterfaces()) { - addInterfaces(interfaces, c); - } - } - - } ++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 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 classesAndParents = new HashSet(); ++ for (Class cls : classes) { ++ addClassAndParents(classesAndParents, cls, packageToInclude); ++ } ++ ++ Set interfaces = new HashSet(); ++ 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 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 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 interfaces, Class cls) { ++ if (interfaces.contains(cls)) { ++ return; ++ } ++ ++ if (cls.isInterface()) { ++ interfaces.add(cls); ++ } ++ ++ for (Class c : cls.getInterfaces()) { ++ addInterfaces(interfaces, c); ++ } ++ } ++ ++} diff --cc tests/server-side/com/vaadin/tests/util/TestUtil.java index 864d0e0822,0000000000..e84f9dd8b9 mode 100644,000000..100644 --- a/tests/server-side/com/vaadin/tests/util/TestUtil.java +++ b/tests/server-side/com/vaadin/tests/util/TestUtil.java @@@ -1,43 -1,0 +1,43 @@@ - 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.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."); ++ } ++ } ++} diff --cc tests/testbench/com/vaadin/tests/Components.java index 6bc6860607,3366f6db43..fa82948e2b --- a/tests/testbench/com/vaadin/tests/Components.java +++ b/tests/testbench/com/vaadin/tests/Components.java @@@ -1,269 -1,268 +1,269 @@@ - 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; - - public class Components extends Application.LegacyApplication { - - private static final Object CAPTION = "c"; - private Map, String> tests = new HashMap, String>(); - private Tree naviTree; - private HorizontalSplitPanel sp; - private LegacyWindow mainWindow; - private final Embedded applicationEmbedder = new Embedded(); - private String baseUrl; - private List> componentsWithoutTests = new ArrayList>(); - - { - for (Class c : VaadinClasses.getBasicComponentTests()) { - String testClass = c.getSimpleName(); - tests.put((Class) c, testClass); - } - - List> componentsWithoutTest = VaadinClasses - .getComponents(); - Set availableTests = new HashSet(); - for (String testName : tests.values()) { - availableTests.add(testName); - } - - for (Class 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 { - @Override - protected Class getTestClass() { - return null; - } - } - - @Override - public void init() { - 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.
Right click to open test in a new window

", - 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( - "Do not use the embedded version for creating automated tests. Open the test in a new window before recording.
", - 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 component : componentsWithoutTests) { - String cls = "missing"; - if (component.getAnnotation(Deprecated.class) != null) { - cls = "missing-deprecated"; - } - missingTests += "" - + component.getSimpleName() + "
"; - } - return new Label("Components without a test:
" - + 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 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 cls) { - String name = tests.get(cls); - if (name == null) { - name = cls.getSimpleName(); - } - - Class superClass = (Class) 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 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; - } - - } + 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, String> tests = new HashMap, String>(); + private Tree naviTree; + private HorizontalSplitPanel sp; - private Window mainWindow; ++ private LegacyWindow mainWindow; + private final Embedded applicationEmbedder = new Embedded(); + private String baseUrl; + private List> componentsWithoutTests = new ArrayList>(); + + { + for (Class c : VaadinClasses.getBasicComponentTests()) { + String testClass = c.getSimpleName(); + tests.put((Class) c, testClass); + } + + List> componentsWithoutTest = VaadinClasses + .getComponents(); + Set availableTests = new HashSet(); + for (String testName : tests.values()) { + availableTests.add(testName); + } + + for (Class 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 { + @Override + protected Class 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.
Right click to open test in a new window

", - 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( + "Do not use the embedded version for creating automated tests. Open the test in a new window before recording.
", - 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 component : componentsWithoutTests) { + String cls = "missing"; + if (component.getAnnotation(Deprecated.class) != null) { + cls = "missing-deprecated"; + } + missingTests += "" + + component.getSimpleName() + "
"; + } + return new Label("Components without a test:
" - + 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 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 cls) { + String name = tests.get(cls); + if (name == null) { + name = cls.getSimpleName(); + } + + Class superClass = (Class) 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 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; + } + + } diff --cc tests/testbench/com/vaadin/tests/TestComponentAddAndRecursion.java index e88ad4442b,62a67cb747..48eff0336e --- a/tests/testbench/com/vaadin/tests/TestComponentAddAndRecursion.java +++ b/tests/testbench/com/vaadin/tests/TestComponentAddAndRecursion.java @@@ -1,131 -1,128 +1,131 @@@ - /** - * - */ - 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; - - /** - * @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); - Root.getCurrentRoot().showNotification("ERROR", - "This should have failed", - Notification.TYPE_ERROR_MESSAGE); - } catch (Exception e) { - 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); - Root.getCurrentRoot().showNotification("ERROR", - "This should have failed", - Notification.TYPE_ERROR_MESSAGE); - } catch (Exception e) { - 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; + + 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. + */ + } + } diff --cc tests/testbench/com/vaadin/tests/application/ApplicationCloseTest.java index 159ba1c3e6,3d767eb016..2706134c27 --- a/tests/testbench/com/vaadin/tests/application/ApplicationCloseTest.java +++ b/tests/testbench/com/vaadin/tests/application/ApplicationCloseTest.java @@@ -1,71 -1,70 +1,71 @@@ - 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:
", - ContentMode.XHTML); - for (Application a : ((WebApplicationContext) getContext()) - .getApplications()) { - applications.setValue(applications.getValue() + "App: " + a - + "
"); - } - applications.setValue(applications.getValue() + "

"); - - 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.
Total memory usage reported as " - + totalUsageString + "
", 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.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:
", - Label.CONTENT_XHTML); ++ ContentMode.XHTML); + for (Application a : ((WebApplicationContext) getContext()) + .getApplications()) { + applications.setValue(applications.getValue() + "App: " + a + + "
"); + } + applications.setValue(applications.getValue() + "

"); + + 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.
Total memory usage reported as " - + totalUsageString + "
", Label.CONTENT_XHTML); ++ + totalUsageString + "
", 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; + } + + } diff --cc tests/testbench/com/vaadin/tests/applicationcontext/ChangeSessionId.java index d1447cb091,c0141a72d5..17ac74e5a3 --- a/tests/testbench/com/vaadin/tests/applicationcontext/ChangeSessionId.java +++ b/tests/testbench/com/vaadin/tests/applicationcontext/ChangeSessionId.java @@@ -1,69 -1,69 +1,69 @@@ - 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.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() { - 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.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; + } + } diff --cc tests/testbench/com/vaadin/tests/components/AbstractComponentContainerTest.java index 2fef794928,2a98988487..6e9e4e8930 --- a/tests/testbench/com/vaadin/tests/components/AbstractComponentContainerTest.java +++ b/tests/testbench/com/vaadin/tests/components/AbstractComponentContainerTest.java @@@ -1,366 -1,356 +1,366 @@@ - 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 - extends AbstractComponentTest implements ComponentAttachListener, - ComponentDetachListener { - - private String CATEGORY_COMPONENT_CONTAINER_FEATURES = "Component container features"; - private Command addButtonCommand = new Command() { - - public void execute(T c, ComponentSize size, Object data) { - Button b = new Button("A button"); - c.addComponent(b); - size.apply(b); - } - }; - - private Command addNativeButtonCommand = new Command() { - - public void execute(T c, ComponentSize size, Object data) { - NativeButton b = new NativeButton("Native button"); - c.addComponent(b); - size.apply(b); - } - }; - - private Command addTextAreaCommand = new Command() { - public void execute(T c, ComponentSize size, Object data) { - TextArea ta = new TextArea(); - c.addComponent(ta); - size.apply(ta); - } - }; - - private Command addRichTextAreaCommand = new Command() { - public void execute(T c, ComponentSize size, Object data) { - RichTextArea ta = new RichTextArea(); - c.addComponent(ta); - size.apply(ta); - } - }; - - private Command addTextFieldCommand = new Command() { - public void execute(T c, ComponentSize size, Object data) { - TextField tf = new TextField(); - c.addComponent(tf); - size.apply(tf); - } - }; - - private Command addInlineDateFieldCommand = new Command() { - public void execute(T c, ComponentSize size, Object data) { - InlineDateField tf = new InlineDateField(); - c.addComponent(tf); - size.apply(tf); - } - }; - private Command addPopupDateFieldCommand = new Command() { - public void execute(T c, ComponentSize size, Object data) { - PopupDateField tf = new PopupDateField(); - c.addComponent(tf); - size.apply(tf); - } - }; - - private Command addVerticalSplitPanelCommand = new Command() { - public void execute(T c, ComponentSize size, Object data) { - VerticalSplitPanel vsp = new VerticalSplitPanel(); - c.addComponent(vsp); - size.apply(vsp); - } - }; - - private Command addHorizontalSplitPanelCommand = new Command() { - public void execute(T c, ComponentSize size, Object data) { - HorizontalSplitPanel vsp = new HorizontalSplitPanel(); - c.addComponent(vsp); - size.apply(vsp); - } - }; - - private Command addTabSheetCommand = new Command() { - public void execute(T c, ComponentSize size, Object data) { - TabSheet ts = createTabSheet(); - c.addComponent(ts); - size.apply(ts); - } - }; - - private Command addTableCommand = new Command() { - - public void execute(T c, ComponentSize size, Object data) { - Table t = createTable(); - c.addComponent(t); - size.apply(t); - } - }; - private Command removeAllComponentsCommand = new Command() { - public void execute(T c, Object value, Object data) { - c.removeAllComponents(); - } - }; - private Command removeComponentByIndexCommand = new Command() { - - public void execute(T c, Integer value, Object data) { - Component child = getComponentAtIndex(c, value); - c.removeComponent(child); - - } - }; - private Command componentAttachListenerCommand = new Command() { - - public void execute(T c, Boolean value, Object data) { - if (value) { - c.addListener((ComponentAttachListener) AbstractComponentContainerTest.this); - } else { - c.removeListener((ComponentAttachListener) AbstractComponentContainerTest.this); - } - } - }; - - private Command componentDetachListenerCommand = new Command() { - - public void execute(T c, Boolean value, Object data) { - if (value) { - c.addListener((ComponentDetachListener) AbstractComponentContainerTest.this); - } else { - c.removeListener((ComponentDetachListener) AbstractComponentContainerTest.this); - } - } - }; - - private Command setComponentHeight = new Command() { - - public void execute(T c, Integer value, Object data) { - Component child = getComponentAtIndex(c, value); - child.setHeight((String) data); - - } - }; - - private Command setComponentWidth = new Command() { - - 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 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> addCommands = new LinkedHashMap>(); - 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 noVerticalSize = new HashSet(); - 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; + ++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 + extends AbstractComponentTest implements ComponentAttachListener, + ComponentDetachListener { + + private String CATEGORY_COMPONENT_CONTAINER_FEATURES = "Component container features"; + private Command addButtonCommand = new Command() { + + public void execute(T c, ComponentSize size, Object data) { + Button b = new Button("A button"); + c.addComponent(b); + size.apply(b); + } + }; + + private Command addNativeButtonCommand = new Command() { + + public void execute(T c, ComponentSize size, Object data) { + NativeButton b = new NativeButton("Native button"); + c.addComponent(b); + size.apply(b); + } + }; + + private Command addTextAreaCommand = new Command() { + public void execute(T c, ComponentSize size, Object data) { + TextArea ta = new TextArea(); + c.addComponent(ta); + size.apply(ta); + } + }; + + private Command addRichTextAreaCommand = new Command() { + public void execute(T c, ComponentSize size, Object data) { + RichTextArea ta = new RichTextArea(); + c.addComponent(ta); + size.apply(ta); + } + }; + + private Command addTextFieldCommand = new Command() { + public void execute(T c, ComponentSize size, Object data) { + TextField tf = new TextField(); + c.addComponent(tf); + size.apply(tf); + } + }; + + private Command addInlineDateFieldCommand = new Command() { + public void execute(T c, ComponentSize size, Object data) { + InlineDateField tf = new InlineDateField(); + c.addComponent(tf); + size.apply(tf); + } + }; + private Command addPopupDateFieldCommand = new Command() { + public void execute(T c, ComponentSize size, Object data) { + PopupDateField tf = new PopupDateField(); + c.addComponent(tf); + size.apply(tf); + } + }; + + private Command addVerticalSplitPanelCommand = new Command() { + public void execute(T c, ComponentSize size, Object data) { + VerticalSplitPanel vsp = new VerticalSplitPanel(); + c.addComponent(vsp); + size.apply(vsp); + } + }; + + private Command addHorizontalSplitPanelCommand = new Command() { + public void execute(T c, ComponentSize size, Object data) { + HorizontalSplitPanel vsp = new HorizontalSplitPanel(); + c.addComponent(vsp); + size.apply(vsp); + } + }; + + private Command addTabSheetCommand = new Command() { + public void execute(T c, ComponentSize size, Object data) { + TabSheet ts = createTabSheet(); + c.addComponent(ts); + size.apply(ts); + } + }; + + private Command addTableCommand = new Command() { + + public void execute(T c, ComponentSize size, Object data) { + Table t = createTable(); + c.addComponent(t); + size.apply(t); + } + }; + private Command removeAllComponentsCommand = new Command() { + public void execute(T c, Object value, Object data) { + c.removeAllComponents(); + } + }; + private Command removeComponentByIndexCommand = new Command() { + + public void execute(T c, Integer value, Object data) { + Component child = getComponentAtIndex(c, value); + c.removeComponent(child); + + } + }; + private Command componentAttachListenerCommand = new Command() { + + public void execute(T c, Boolean value, Object data) { + if (value) { + c.addListener((ComponentAttachListener) AbstractComponentContainerTest.this); + } else { + c.removeListener((ComponentAttachListener) AbstractComponentContainerTest.this); + } + } + }; + + private Command componentDetachListenerCommand = new Command() { + + public void execute(T c, Boolean value, Object data) { + if (value) { + c.addListener((ComponentDetachListener) AbstractComponentContainerTest.this); + } else { + c.removeListener((ComponentDetachListener) AbstractComponentContainerTest.this); + } + } + }; + + private Command setComponentHeight = new Command() { + + public void execute(T c, Integer value, Object data) { + Component child = getComponentAtIndex(c, value); + child.setHeight((String) data); + + } + }; + + private Command setComponentWidth = new Command() { + + 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 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> addCommands = new LinkedHashMap>(); + 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 noVerticalSize = new HashSet(); ++ 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()); + + } + + } diff --cc tests/testbench/com/vaadin/tests/components/AbstractComponentTest.java index 14a7a85adb,fe61df8913..e8ac213049 --- a/tests/testbench/com/vaadin/tests/components/AbstractComponentTest.java +++ b/tests/testbench/com/vaadin/tests/components/AbstractComponentTest.java @@@ -1,720 -1,671 +1,720 @@@ - 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 - extends AbstractComponentTestCase 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 sizeOptions = new LinkedHashMap(); - 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 parentOfSelectableMenuItem = new HashSet(); - - /** - * Maps the category name to a menu item - */ - private Map categoryToMenuItem = new HashMap(); - private Map menuItemToCategory = new HashMap(); - - // 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 focusListenerCommand = new Command() { - - public void execute(T c, Boolean value, Object data) { - if (value) { - ((FocusNotifier) c).addListener(AbstractComponentTest.this); - } else { - ((FocusNotifier) c).removeListener(AbstractComponentTest.this); - } - } - }; - protected Command blurListenerCommand = new Command() { - - 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 options = new LinkedHashMap(); - 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 options) { - - } - - private void createErrorMessageSelect(String category) { - LinkedHashMap options = new LinkedHashMap(); - 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 options = new LinkedHashMap(); - 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 createCaptionOptions() { - LinkedHashMap options = new LinkedHashMap(); - 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 options = new LinkedHashMap(); - 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 options = new LinkedHashMap(); - 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 command) { - createBooleanAction(caption, category, initialState, command, null); - } - - protected void createBooleanAction(String caption, - String category, boolean initialState, - final Command command, Object data) { - MenuItem categoryItem = getCategoryMenuItem(category); - MenuItem item = categoryItem.addItem(caption, - menuBooleanCommand(command, data)); - setSelected(item, initialState); - doCommand(caption, command, initialState, data); - } - - protected void createClickAction(String caption, - String category, final Command command, DATATYPE value) { - createClickAction(caption, category, command, value, null); - } - - protected void createClickAction(String caption, - String category, final Command 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 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 MenuBar.Command menuClickCommand( - final com.vaadin.tests.components.ComponentTestCase.Command 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 MenuBar.Command singleSelectMenuCommand( - final com.vaadin.tests.components.ComponentTestCase.Command 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 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 void createSelectAction( - String caption, - String category, - LinkedHashMap options, - String initialValue, - com.vaadin.tests.components.ComponentTestCase.Command command) { - createSelectAction(caption, category, options, initialValue, command, - null); - - } - - protected void createMultiClickAction( - String caption, - String category, - LinkedHashMap options, - com.vaadin.tests.components.ComponentTestCase.Command 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 void createMultiToggleAction( - String caption, - String category, - LinkedHashMap options, - com.vaadin.tests.components.ComponentTestCase.Command command, - boolean defaultValue) { - - LinkedHashMap defaultValues = new LinkedHashMap(); - - for (String option : options.keySet()) { - defaultValues.put(option, defaultValue); - } - - createMultiToggleAction(caption, category, options, command, - defaultValues); - } - - protected void createMultiToggleAction( - String caption, - String category, - LinkedHashMap options, - com.vaadin.tests.components.ComponentTestCase.Command command, - LinkedHashMap defaultValues) { - - createCategory(caption, category); - - for (String option : options.keySet()) { - createBooleanAction(option, caption, defaultValues.get(option), - command, options.get(option)); - - } - } - - protected void createSelectAction( - String caption, - String category, - LinkedHashMap options, - String initialValue, - com.vaadin.tests.components.ComponentTestCase.Command 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 createIntegerOptions(int max) { - LinkedHashMap options = new LinkedHashMap(); - 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 createDoubleOptions(double max) { - LinkedHashMap options = new LinkedHashMap(); - 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 createIconOptions( - boolean cacheable) { - LinkedHashMap options = new LinkedHashMap(); - 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 void doCommand(String commandName, - AbstractComponentTestCase.Command 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; + + 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 - extends AbstractComponentTestCase { ++ extends AbstractComponentTestCase 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 sizeOptions = new LinkedHashMap(); + 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 parentOfSelectableMenuItem = new HashSet(); + + /** + * Maps the category name to a menu item + */ + private Map categoryToMenuItem = new HashMap(); + private Map menuItemToCategory = new HashMap(); + + // 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 focusListenerCommand = new Command() { ++ ++ public void execute(T c, Boolean value, Object data) { ++ if (value) { ++ ((FocusNotifier) c).addListener(AbstractComponentTest.this); ++ } else { ++ ((FocusNotifier) c).removeListener(AbstractComponentTest.this); ++ } ++ } ++ }; ++ protected Command blurListenerCommand = new Command() { ++ ++ 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 options = new LinkedHashMap(); + 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 options) { + + } + + private void createErrorMessageSelect(String category) { + LinkedHashMap options = new LinkedHashMap(); + 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 options = new LinkedHashMap(); + 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 createCaptionOptions() { + LinkedHashMap options = new LinkedHashMap(); + 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 options = new LinkedHashMap(); + 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 options = new LinkedHashMap(); + 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 command) { + createBooleanAction(caption, category, initialState, command, null); + } + + protected void createBooleanAction(String caption, + String category, boolean initialState, + final Command command, Object data) { + MenuItem categoryItem = getCategoryMenuItem(category); + MenuItem item = categoryItem.addItem(caption, + menuBooleanCommand(command, data)); + setSelected(item, initialState); + doCommand(caption, command, initialState, data); + } + + protected void createClickAction(String caption, + String category, final Command command, DATATYPE value) { + createClickAction(caption, category, command, value, null); + } + + protected void createClickAction(String caption, + String category, final Command 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 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 MenuBar.Command menuClickCommand( + final com.vaadin.tests.components.ComponentTestCase.Command 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 MenuBar.Command singleSelectMenuCommand( + final com.vaadin.tests.components.ComponentTestCase.Command 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 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 void createSelectAction( + String caption, + String category, + LinkedHashMap options, + String initialValue, + com.vaadin.tests.components.ComponentTestCase.Command command) { + createSelectAction(caption, category, options, initialValue, command, + null); + + } + + protected void createMultiClickAction( + String caption, + String category, + LinkedHashMap options, + com.vaadin.tests.components.ComponentTestCase.Command 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 void createMultiToggleAction( + String caption, + String category, + LinkedHashMap options, + com.vaadin.tests.components.ComponentTestCase.Command command, + boolean defaultValue) { + + LinkedHashMap defaultValues = new LinkedHashMap(); + + for (String option : options.keySet()) { + defaultValues.put(option, defaultValue); + } + + createMultiToggleAction(caption, category, options, command, + defaultValues); + } + + protected void createMultiToggleAction( + String caption, + String category, + LinkedHashMap options, + com.vaadin.tests.components.ComponentTestCase.Command command, + LinkedHashMap defaultValues) { + + createCategory(caption, category); + + for (String option : options.keySet()) { + createBooleanAction(option, caption, defaultValues.get(option), + command, options.get(option)); + + } + } + + protected void createSelectAction( + String caption, + String category, + LinkedHashMap options, + String initialValue, + com.vaadin.tests.components.ComponentTestCase.Command 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 createIntegerOptions(int max) { + LinkedHashMap options = new LinkedHashMap(); + 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 createDoubleOptions(double max) { + LinkedHashMap options = new LinkedHashMap(); + 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 createIconOptions( + boolean cacheable) { + LinkedHashMap options = new LinkedHashMap(); + 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 void doCommand(String commandName, + AbstractComponentTestCase.Command 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()); ++ } ++ + } diff --cc tests/testbench/com/vaadin/tests/components/AbstractTestCase.java index 8f3abe90f9,e2b3ad0fe1..11d960e143 --- a/tests/testbench/com/vaadin/tests/components/AbstractTestCase.java +++ b/tests/testbench/com/vaadin/tests/components/AbstractTestCase.java @@@ -1,24 -1,24 +1,24 @@@ - 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.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; + + 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; + } + } diff --cc tests/testbench/com/vaadin/tests/components/TestBase.java index da85fc579b,c7380d3d7c..4825e09404 --- a/tests/testbench/com/vaadin/tests/components/TestBase.java +++ b/tests/testbench/com/vaadin/tests/components/TestBase.java @@@ -1,54 -1,53 +1,54 @@@ - 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; - - public abstract class TestBase extends AbstractTestCase { - - @Override - public final void init() { - window = new LegacyWindow(getClass().getName()); - setMainWindow(window); - window.getContent().setSizeFull(); - - 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 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; + + 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); + } + + } diff --cc tests/testbench/com/vaadin/tests/components/abstractcomponent/EnableState.java index 946246d59a,a5498660be..9261962b0d --- a/tests/testbench/com/vaadin/tests/components/abstractcomponent/EnableState.java +++ b/tests/testbench/com/vaadin/tests/components/abstractcomponent/EnableState.java @@@ -1,82 -1,77 +1,82 @@@ - 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.CheckBox; - import com.vaadin.ui.Panel; - import com.vaadin.ui.Root.LegacyWindow; - - public class EnableState extends AbstractTestCase { - @Override - public void init() { - 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 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 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 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 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; - } - } + 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; + } + } diff --cc tests/testbench/com/vaadin/tests/components/abstractfield/AbstractComponentDataBindingTest.java index 4bd97262ed,0000000000..93ba858e37 mode 100644,000000..100644 --- a/tests/testbench/com/vaadin/tests/components/abstractfield/AbstractComponentDataBindingTest.java +++ b/tests/testbench/com/vaadin/tests/components/abstractfield/AbstractComponentDataBindingTest.java @@@ -1,117 -1,0 +1,117 @@@ - 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 fields = new HashSet(); - - @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; ++ ++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 fields = new HashSet(); ++ ++ @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); ++ ++ } ++ ++} diff --cc tests/testbench/com/vaadin/tests/components/abstractfield/AbstractFieldTest.java index d9bc1c3108,40cc2948ee..716f80e23f --- a/tests/testbench/com/vaadin/tests/components/abstractfield/AbstractFieldTest.java +++ b/tests/testbench/com/vaadin/tests/components/abstractfield/AbstractFieldTest.java @@@ -1,190 -1,234 +1,190 @@@ - 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.BlurNotifier; - 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> extends - AbstractComponentTest implements ValueChangeListener, - 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 options = new LinkedHashMap(); - 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); - - } - - 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); - } - - protected Command valueChangeListenerCommand = new Command() { - - public void execute(T c, Boolean value, Object data) { - if (value) { - c.addListener((ValueChangeListener) AbstractFieldTest.this); - } else { - c.removeListener((ValueChangeListener) AbstractFieldTest.this); - } - } - }; - protected Command readonlyStatusChangeListenerCommand = new Command() { - - public void execute(T c, Boolean value, Object data) { - if (value) { - c.addListener((ReadOnlyStatusChangeListener) AbstractFieldTest.this); - } else { - c.removeListener((ReadOnlyStatusChangeListener) AbstractFieldTest.this); - } - } - }; - - protected Command setValueCommand = new Command() { - - 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 c = new ArrayList( - (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()); - } - - protected void createSetTextValueAction(String category) { - String subCategory = "Set text value"; - createCategory(subCategory, category); - List values = new ArrayList(); - 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); - } - } - - } + 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 extends ++public abstract class AbstractFieldTest> extends + AbstractComponentTest 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 options = new LinkedHashMap(); + 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 valueChangeListenerCommand = new Command() { + + public void execute(T c, Boolean value, Object data) { + if (value) { + c.addListener((ValueChangeListener) AbstractFieldTest.this); + } else { + c.removeListener((ValueChangeListener) AbstractFieldTest.this); + } + } + }; + protected Command readonlyStatusChangeListenerCommand = new Command() { + + public void execute(T c, Boolean value, Object data) { + if (value) { + c.addListener((ReadOnlyStatusChangeListener) AbstractFieldTest.this); + } else { + c.removeListener((ReadOnlyStatusChangeListener) AbstractFieldTest.this); + } + } + }; - protected Command focusListenerCommand = new Command() { - - public void execute(T c, Boolean value, Object data) { - if (value) { - ((FocusNotifier) c).addListener(AbstractFieldTest.this); - } else { - ((FocusNotifier) c).removeListener(AbstractFieldTest.this); - } - } - }; - protected Command blurListenerCommand = new Command() { + - public void execute(T c, Boolean value, Object data) { - if (value) { - ((BlurNotifier) c).addListener(AbstractFieldTest.this); - } else { - ((BlurNotifier) c).removeListener(AbstractFieldTest.this); - } - } - }; + protected Command setValueCommand = new Command() { + + 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 c = new ArrayList( + (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 values = new ArrayList(); + 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); + } + } + + } diff --cc tests/testbench/com/vaadin/tests/components/abstractfield/DateFieldBackedByString.java index ea51dc881f,0000000000..d4b2f89522 mode 100644,000000..100644 --- a/tests/testbench/com/vaadin/tests/components/abstractfield/DateFieldBackedByString.java +++ b/tests/testbench/com/vaadin/tests/components/abstractfield/DateFieldBackedByString.java @@@ -1,17 -1,0 +1,17 @@@ - 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( - s, String.class)); - - } - } ++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( ++ s, String.class)); ++ ++ } ++} diff --cc tests/testbench/com/vaadin/tests/components/abstractfield/DateFieldBasedOnLong.java index 4e262acb69,0000000000..deea0fbe0a mode 100644,000000..100644 --- a/tests/testbench/com/vaadin/tests/components/abstractfield/DateFieldBasedOnLong.java +++ b/tests/testbench/com/vaadin/tests/components/abstractfield/DateFieldBasedOnLong.java @@@ -1,34 -1,0 +1,34 @@@ - 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 property; - - @Override - protected void createFields() { - PopupDateField pdf = new PopupDateField("DateField"); - addComponent(pdf); - property = new ObjectProperty(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); - - } - })); - } - - } ++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 property; ++ ++ @Override ++ protected void createFields() { ++ PopupDateField pdf = new PopupDateField("DateField"); ++ addComponent(pdf); ++ property = new ObjectProperty(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); ++ ++ } ++ })); ++ } ++ ++} diff --cc tests/testbench/com/vaadin/tests/components/abstractfield/DoubleInTextField.java index b7077dba80,0000000000..4fd81081ea mode 100644,000000..100644 --- a/tests/testbench/com/vaadin/tests/components/abstractfield/DoubleInTextField.java +++ b/tests/testbench/com/vaadin/tests/components/abstractfield/DoubleInTextField.java @@@ -1,31 -1,0 +1,31 @@@ - 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(person, - "salaryDouble")); - - TextField salary6 = new TextField("Vaadin 6 - TextField with Double"); - addComponent(salary6); - salary6.setPropertyDataSource(new MethodProperty(person, - "salaryDouble")); - salary6.setConverter(new Vaadin6ImplicitDoubleConverter()); - - } - - } ++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(person, ++ "salaryDouble")); ++ ++ TextField salary6 = new TextField("Vaadin 6 - TextField with Double"); ++ addComponent(salary6); ++ salary6.setPropertyDataSource(new MethodProperty(person, ++ "salaryDouble")); ++ salary6.setConverter(new Vaadin6ImplicitDoubleConverter()); ++ ++ } ++ ++} diff --cc tests/testbench/com/vaadin/tests/components/abstractfield/IntegerDoubleFieldsWithDataSource.java index d10b7140e1,0000000000..c13aadd895 mode 100644,000000..100644 --- a/tests/testbench/com/vaadin/tests/components/abstractfield/IntegerDoubleFieldsWithDataSource.java +++ b/tests/testbench/com/vaadin/tests/components/abstractfield/IntegerDoubleFieldsWithDataSource.java @@@ -1,64 -1,0 +1,64 @@@ - 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(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(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; - } - - } ++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(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(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; ++ } ++ ++} diff --cc tests/testbench/com/vaadin/tests/components/abstractfield/IntegerFieldWithoutDataSource.java index 9d7edd3822,0000000000..b25dc9d953 mode 100644,000000..100644 --- a/tests/testbench/com/vaadin/tests/components/abstractfield/IntegerFieldWithoutDataSource.java +++ b/tests/testbench/com/vaadin/tests/components/abstractfield/IntegerFieldWithoutDataSource.java @@@ -1,59 -1,0 +1,59 @@@ - 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; - } - - } ++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; ++ } ++ ++} diff --cc tests/testbench/com/vaadin/tests/components/abstractfield/TextFieldConversions.java index 313bd721d9,0000000000..8ce214918d mode 100644,000000..100644 --- a/tests/testbench/com/vaadin/tests/components/abstractfield/TextFieldConversions.java +++ b/tests/testbench/com/vaadin/tests/components/abstractfield/TextFieldConversions.java @@@ -1,51 -1,0 +1,51 @@@ - 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(o, - (Class) 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; - } - }); - } - } ++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(o, ++ (Class) 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; ++ } ++ }); ++ } ++} diff --cc tests/testbench/com/vaadin/tests/components/abstractfield/Vaadin6ImplicitDoubleConverter.java index 274ac64b44,0000000000..0228a59f06 mode 100644,000000..100644 --- a/tests/testbench/com/vaadin/tests/components/abstractfield/Vaadin6ImplicitDoubleConverter.java +++ b/tests/testbench/com/vaadin/tests/components/abstractfield/Vaadin6ImplicitDoubleConverter.java @@@ -1,35 -1,0 +1,35 @@@ - package com.vaadin.tests.components.abstractfield; - - import java.util.Locale; - - import com.vaadin.data.util.converter.Converter; - - public class Vaadin6ImplicitDoubleConverter implements - Converter { - - 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 getModelType() { - return Double.class; - } - - public Class getPresentationType() { - return String.class; - } - - } ++package com.vaadin.tests.components.abstractfield; ++ ++import java.util.Locale; ++ ++import com.vaadin.data.util.converter.Converter; ++ ++public class Vaadin6ImplicitDoubleConverter implements ++ Converter { ++ ++ 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 getModelType() { ++ return Double.class; ++ } ++ ++ public Class getPresentationType() { ++ return String.class; ++ } ++ ++} diff --cc tests/testbench/com/vaadin/tests/components/button/Buttons2.java index e8a71dac1d,b65a9fc0cd..e04d50bddb --- a/tests/testbench/com/vaadin/tests/components/button/Buttons2.java +++ b/tests/testbench/com/vaadin/tests/components/button/Buttons2.java @@@ -1,68 -1,74 +1,68 @@@ - package com.vaadin.tests.components.button; - - import java.util.LinkedHashMap; - - 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 extends AbstractComponentTest - implements ClickListener { - - private Command disableOnClickCommand = new Command() { - - public void execute(T c, Boolean value, Object data) { - c.setDisableOnClick(value); - } - }; - - private Command clickListenerCommand = new Command() { - - 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 getTestClass() { - return (Class) Button.class; - } - - @Override - protected void createActions() { - super.createActions(); - - createFocusListener(CATEGORY_LISTENERS); - createBlurListener(CATEGORY_LISTENERS); - - createBooleanAction("Disable on click", CATEGORY_FEATURES, false, - disableOnClickCommand); - addClickListener(CATEGORY_LISTENERS); - } - - @Override - protected void createComponentStyleNames( - LinkedHashMap 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; + + 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 extends AbstractFieldTest implements - ClickListener { - - private Command switchModeCommand = new Command() { - - @SuppressWarnings("deprecation") - public void execute(T c, Boolean value, Object data) { - c.setSwitchMode(value); - } - }; ++public class Buttons2 extends AbstractComponentTest ++ implements ClickListener { + + private Command disableOnClickCommand = new Command() { + + public void execute(T c, Boolean value, Object data) { + c.setDisableOnClick(value); + } + }; + + private Command clickListenerCommand = new Command() { + + 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 getTestClass() { + return (Class) 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 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()); + } + } diff --cc tests/testbench/com/vaadin/tests/components/button/ButtonsInHorizontalLayout.java index b9a2307aff,46d92c3a03..bdabed3032 --- a/tests/testbench/com/vaadin/tests/components/button/ButtonsInHorizontalLayout.java +++ b/tests/testbench/com/vaadin/tests/components/button/ButtonsInHorizontalLayout.java @@@ -1,52 -1,52 +1,52 @@@ - 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.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 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.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; + } + + } diff --cc tests/testbench/com/vaadin/tests/components/checkbox/CheckBoxes2.java index 4a98f09808,2af1e41867..4f9cd10ecc --- a/tests/testbench/com/vaadin/tests/components/checkbox/CheckBoxes2.java +++ b/tests/testbench/com/vaadin/tests/components/checkbox/CheckBoxes2.java @@@ -1,25 -1,56 +1,25 @@@ - 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 implements - ClickListener { - - @Override - protected Class getTestClass() { - return CheckBox.class; - } - - @Override - protected void createActions() { - super.createActions(); - - } - - public void buttonClick(ClickEvent event) { - log(event.getClass().getSimpleName()); - } - } + 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 implements + ClickListener { + - // cannot extend Buttons2 because of Switch mode problems - + @Override + protected Class getTestClass() { + return CheckBox.class; + } + - private Command switchModeCommand = new Command() { - - @SuppressWarnings("deprecation") - public void execute(CheckBox c, Boolean value, Object data) { - c.setSwitchMode(value); - } - }; - - private Command clickListenerCommand = new Command() { - - 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()); + } + } diff --cc tests/testbench/com/vaadin/tests/components/customcomponent/ClipContent.java index 27a3b7a4f7,8bc464f176..7ba26e54a9 --- a/tests/testbench/com/vaadin/tests/components/customcomponent/ClipContent.java +++ b/tests/testbench/com/vaadin/tests/components/customcomponent/ClipContent.java @@@ -1,57 -1,56 +1,57 @@@ - 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
2_long_line_that_should_be_clipped
3_long_line_that_should_be_clipped
4_long_line_that_should_be_clipped
", - 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(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(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; - } - - } + 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
2_long_line_that_should_be_clipped
3_long_line_that_should_be_clipped
4_long_line_that_should_be_clipped
", - 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; + } + + } diff --cc tests/testbench/com/vaadin/tests/components/customfield/AbstractNestedFormExample.java index d8c962f1e3,0000000000..c15ca1916a mode 100644,000000..100644 --- a/tests/testbench/com/vaadin/tests/components/customfield/AbstractNestedFormExample.java +++ b/tests/testbench/com/vaadin/tests/components/customfield/AbstractNestedFormExample.java @@@ -1,75 -1,0 +1,75 @@@ - 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; - } - - } ++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; ++ } ++ ++} diff --cc tests/testbench/com/vaadin/tests/components/customfield/AddressField.java index 654b4920ad,0000000000..a3ee89b3ee mode 100644,000000..100644 --- a/tests/testbench/com/vaadin/tests/components/customfield/AddressField.java +++ b/tests/testbench/com/vaadin/tests/components/customfield/AddressField.java @@@ -1,97 -1,0 +1,97 @@@ - 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
{ - 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 visibleProperties = Arrays.asList("streetAddress", - "postalCode", "city"); - getContent().setItemDataSource(new BeanItem
(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
getType() { - return Address.class; - } ++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
{ ++ 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 visibleProperties = Arrays.asList("streetAddress", ++ "postalCode", "city"); ++ getContent().setItemDataSource(new BeanItem
(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
getType() { ++ return Address.class; ++ } +} diff --cc tests/testbench/com/vaadin/tests/components/customfield/AddressFormExample.java index f3f31d6d5d,0000000000..55e61e3980 mode 100644,000000..100644 --- a/tests/testbench/com/vaadin/tests/components/customfield/AddressFormExample.java +++ b/tests/testbench/com/vaadin/tests/components/customfield/AddressFormExample.java @@@ -1,45 -1,0 +1,45 @@@ - 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; - } - - } ++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; ++ } ++ ++} diff --cc tests/testbench/com/vaadin/tests/components/customfield/BooleanField.java index 94d25eb10e,0000000000..dc60d7e517 mode 100644,000000..100644 --- a/tests/testbench/com/vaadin/tests/components/customfield/BooleanField.java +++ b/tests/testbench/com/vaadin/tests/components/customfield/BooleanField.java @@@ -1,45 -1,0 +1,45 @@@ - 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; - } ++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; ++ } +} diff --cc tests/testbench/com/vaadin/tests/components/customfield/BooleanFieldExample.java index aaaeeeb64f,0000000000..2f9720a1c1 mode 100644,000000..100644 --- a/tests/testbench/com/vaadin/tests/components/customfield/BooleanFieldExample.java +++ b/tests/testbench/com/vaadin/tests/components/customfield/BooleanFieldExample.java @@@ -1,89 -1,0 +1,89 @@@ - 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(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() - + ".
" - + "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; - } - - } ++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(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() ++ + ".
" ++ + "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; ++ } ++ ++} diff --cc tests/testbench/com/vaadin/tests/components/customfield/EmbeddedForm.java index ceaea1f53e,0000000000..d305afde1d mode 100644,000000..100644 --- a/tests/testbench/com/vaadin/tests/components/customfield/EmbeddedForm.java +++ b/tests/testbench/com/vaadin/tests/components/customfield/EmbeddedForm.java @@@ -1,67 -1,0 +1,67 @@@ - 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 fields = new HashMap(); - - /** - * 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.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 fields = new HashMap(); ++ ++ /** ++ * 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); ++ } +} diff --cc tests/testbench/com/vaadin/tests/components/datefield/DateFieldEmptyValid.java index daecb41ae9,440f004531..37fb09ab29 --- a/tests/testbench/com/vaadin/tests/components/datefield/DateFieldEmptyValid.java +++ b/tests/testbench/com/vaadin/tests/components/datefield/DateFieldEmptyValid.java @@@ -1,145 -1,144 +1,145 @@@ - 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("

", 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 dfProp = new ObjectProperty( - 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 dfProp = new ObjectProperty(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; + + 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("

", Label.CONTENT_XHTML)); ++ addComponent(new Label("

", 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 dfProp = new ObjectProperty( + 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 dfProp = new ObjectProperty(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; + } + + } diff --cc tests/testbench/com/vaadin/tests/components/datefield/DateFieldPopupOffScreen.java index 5ea909b687,122fd4347f..6d64898e28 --- a/tests/testbench/com/vaadin/tests/components/datefield/DateFieldPopupOffScreen.java +++ b/tests/testbench/com/vaadin/tests/components/datefield/DateFieldPopupOffScreen.java @@@ -1,64 -1,62 +1,64 @@@ - 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.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() { - 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.
It should always be on screen so it can be read."); - df.setValue(new Date(1000000L)); - return df; - } - } + 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.
It should always be on screen so it can be read."); + df.setValue(new Date(1000000L)); + return df; + } + } diff --cc tests/testbench/com/vaadin/tests/components/datefield/DateFieldRangeValidation.java index 8b87f57a42,0000000000..bf93d8c8b9 mode 100644,000000..100644 --- a/tests/testbench/com/vaadin/tests/components/datefield/DateFieldRangeValidation.java +++ b/tests/testbench/com/vaadin/tests/components/datefield/DateFieldRangeValidation.java @@@ -1,144 -1,0 +1,144 @@@ - 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 bi = new BeanItem(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.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; ++ ++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 bi = new BeanItem(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.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; ++ } ++ ++} diff --cc tests/testbench/com/vaadin/tests/components/datefield/DateFieldTest.java index 15cbc858a5,7d1bdfc2c8..e8c8b69f9f --- a/tests/testbench/com/vaadin/tests/components/datefield/DateFieldTest.java +++ b/tests/testbench/com/vaadin/tests/components/datefield/DateFieldTest.java @@@ -1,138 -1,137 +1,138 @@@ - 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 extends AbstractFieldTest { - - @SuppressWarnings("unchecked") - @Override - protected Class getTestClass() { - return (Class) DateField.class; - } - - private Command setValue = new Command() { - - 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 options = new LinkedHashMap(); - 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 options = new LinkedHashMap(); - - 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 options = new LinkedHashMap(); - 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 resolutionCommand = new Command() { - - public void execute(T c, Resolution value, Object data) { - c.setResolution(value); - - } - }; - private Command lenientCommand = new Command() { - - public void execute(T c, Boolean value, Object data) { - c.setLenient(false); - - } - }; - private Command weekNumberCommand = new Command() { - - public void execute(T c, Boolean value, Object data) { - c.setShowISOWeekNumbers(value); - - } - }; - private Command dateFormatCommand = new Command() { - - public void execute(T c, String value, Object data) { - c.setDateFormat(value); - } - }; - - } + 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 extends AbstractFieldTest { + ++ @SuppressWarnings("unchecked") + @Override + protected Class getTestClass() { + return (Class) DateField.class; + } + + private Command setValue = new Command() { + + 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 options = new LinkedHashMap(); + 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 options = new LinkedHashMap(); + + 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 options = new LinkedHashMap(); - 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 options = new LinkedHashMap(); ++ 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 resolutionCommand = new Command() { ++ private Command resolutionCommand = new Command() { + - public void execute(T c, Integer value, Object data) { ++ public void execute(T c, Resolution value, Object data) { + c.setResolution(value); + + } + }; + private Command lenientCommand = new Command() { + + public void execute(T c, Boolean value, Object data) { + c.setLenient(false); + + } + }; + private Command weekNumberCommand = new Command() { + + public void execute(T c, Boolean value, Object data) { + c.setShowISOWeekNumbers(value); + + } + }; + private Command dateFormatCommand = new Command() { + + public void execute(T c, String value, Object data) { + c.setDateFormat(value); + } + }; + + } diff --cc tests/testbench/com/vaadin/tests/components/datefield/DateFieldUnparsableDate.java index 3eb6e020b0,4f83575b39..9b4a3c3383 --- a/tests/testbench/com/vaadin/tests/components/datefield/DateFieldUnparsableDate.java +++ b/tests/testbench/com/vaadin/tests/components/datefield/DateFieldUnparsableDate.java @@@ -1,104 -1,101 +1,104 @@@ - 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 = getValue(); - } - }); - } - - @Override - protected Date handleUnparsableDateString(String dateString) - throws Converter.ConversionException { - return oldDate; - } - } - - public class MyDateField2 extends DateField { - public MyDateField2(String caption) { - super(caption); - } - - @Override - protected Date handleUnparsableDateString(String dateString) - throws Converter.ConversionException { - return null; - } - } - - public class MyDateField3 extends DateField { - public MyDateField3(String caption) { - super(caption); - } - - @Override - protected Date handleUnparsableDateString(String dateString) - 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 Converter.ConversionException { - if (dateString != null && dateString.equals("today")) { - return new Date(); - } - 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; + + 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; + } + } diff --cc tests/testbench/com/vaadin/tests/components/datefield/InlineDateFields.java index 095baba1fe,56f3641043..de08477dd3 --- a/tests/testbench/com/vaadin/tests/components/datefield/InlineDateFields.java +++ b/tests/testbench/com/vaadin/tests/components/datefield/InlineDateFields.java @@@ -1,106 -1,106 +1,106 @@@ - 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 { - - private static final Locale[] LOCALES = new Locale[] { Locale.US, - Locale.TAIWAN, new Locale("fi", "FI") }; - - @Override - protected Class 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); - - return pd; - } - - @Override - protected String getDescription() { - return "A generic test for InlineDateFields in different configurations"; - } - - @Override - protected List createActions() { - List actions = super.createActions(); - actions.add(createResolutionSelectAction()); - actions.add(createLocaleSelectAction()); - return actions; - } - - private Component createResolutionSelectAction() { - LinkedHashMap options = new LinkedHashMap(); - 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() { - - public void execute(InlineDateField c, Resolution value, - Object data) { - c.setResolution(value); - - } - }); - } - - private Component createLocaleSelectAction() { - LinkedHashMap options = new LinkedHashMap(); - for (Locale locale : LOCALES) { - options.put(locale.toString(), locale); - } - return createSelectAction("Locale", options, LOCALES[0].toString(), - new Command() { - - 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; + + 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 { + + private static final Locale[] LOCALES = new Locale[] { Locale.US, + Locale.TAIWAN, new Locale("fi", "FI") }; + + @Override + protected Class 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 createActions() { + List actions = super.createActions(); + actions.add(createResolutionSelectAction()); + actions.add(createLocaleSelectAction()); + return actions; + } + + private Component createResolutionSelectAction() { - LinkedHashMap options = new LinkedHashMap(); - 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 options = new LinkedHashMap(); ++ 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() { ++ new Command() { + - public void execute(InlineDateField c, Integer value, ++ public void execute(InlineDateField c, Resolution value, + Object data) { + c.setResolution(value); + + } + }); + } + + private Component createLocaleSelectAction() { + LinkedHashMap options = new LinkedHashMap(); + for (Locale locale : LOCALES) { + options.put(locale.toString(), locale); + } + return createSelectAction("Locale", options, LOCALES[0].toString(), + new Command() { + + public void execute(InlineDateField c, Locale value, + Object data) { + c.setCaption(c.getCaption().replaceAll( + c.getLocale().toString(), value.toString())); + c.setLocale(value); + + } + }); + } + + } diff --cc tests/testbench/com/vaadin/tests/components/datefield/PopupDateFields.java index fa3659d38b,7e8b19b2a1..ad961ee7a6 --- a/tests/testbench/com/vaadin/tests/components/datefield/PopupDateFields.java +++ b/tests/testbench/com/vaadin/tests/components/datefield/PopupDateFields.java @@@ -1,105 -1,105 +1,105 @@@ - 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 { - - private static final Locale[] LOCALES = new Locale[] { Locale.US, - Locale.TAIWAN, new Locale("fi", "FI") }; - - @Override - protected Class 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); - - return pd; - } - - @Override - protected String getDescription() { - return "A generic test for PopupDateFields in different configurations"; - } - - @Override - protected List createActions() { - List actions = super.createActions(); - actions.add(createResolutionSelectAction()); - actions.add(createInputPromptSelectAction()); - return actions; - } - - private Component createResolutionSelectAction() { - LinkedHashMap options = new LinkedHashMap(); - 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() { - - public void execute(PopupDateField c, Resolution value, - Object data) { - c.setResolution(value); - - } - }); - } - - private Component createInputPromptSelectAction() { - LinkedHashMap options = new LinkedHashMap(); - options.put("", null); - options.put("Please enter date", "Please enter date"); - options.put("åäöÅÄÖ", "åäöÅÄÖ"); - - return createSelectAction("Input prompt", options, "", - new Command() { - - public void execute(PopupDateField c, String value, - Object data) { - c.setInputPrompt(value); - - } - }); - } - - } + 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 { + + private static final Locale[] LOCALES = new Locale[] { Locale.US, + Locale.TAIWAN, new Locale("fi", "FI") }; + + @Override + protected Class 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 createActions() { + List actions = super.createActions(); + actions.add(createResolutionSelectAction()); + actions.add(createInputPromptSelectAction()); + return actions; + } + + private Component createResolutionSelectAction() { - LinkedHashMap options = new LinkedHashMap(); - 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 options = new LinkedHashMap(); ++ 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() { ++ new Command() { + - public void execute(PopupDateField c, Integer value, ++ public void execute(PopupDateField c, Resolution value, + Object data) { + c.setResolution(value); + + } + }); + } + + private Component createInputPromptSelectAction() { + LinkedHashMap options = new LinkedHashMap(); + options.put("", null); + options.put("Please enter date", "Please enter date"); + options.put("åäöÅÄÖ", "åäöÅÄÖ"); + + return createSelectAction("Input prompt", options, "", + new Command() { + + public void execute(PopupDateField c, String value, + Object data) { + c.setInputPrompt(value); + + } + }); + } + + } diff --cc tests/testbench/com/vaadin/tests/components/embedded/EmbeddedPdf.java index ade23bd460,0fb8b27b75..e551e153db --- a/tests/testbench/com/vaadin/tests/components/embedded/EmbeddedPdf.java +++ b/tests/testbench/com/vaadin/tests/components/embedded/EmbeddedPdf.java @@@ -1,32 -1,32 +1,32 @@@ - 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.getRoot().addWindow(new Window("Testwindow")); - } - - } + 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")); + } + + } diff --cc tests/testbench/com/vaadin/tests/components/form/FormWithEnterShortCut.java index 7f750c9e24,a3baab921f..689ba7ea83 --- a/tests/testbench/com/vaadin/tests/components/form/FormWithEnterShortCut.java +++ b/tests/testbench/com/vaadin/tests/components/form/FormWithEnterShortCut.java @@@ -1,46 -1,47 +1,46 @@@ - 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.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 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.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; + } + } diff --cc tests/testbench/com/vaadin/tests/components/formlayout/TableInFormLayoutCausesScrolling.java index 2919cfcb44,c8eb1483b4..bbe88b1770 --- a/tests/testbench/com/vaadin/tests/components/formlayout/TableInFormLayoutCausesScrolling.java +++ b/tests/testbench/com/vaadin/tests/components/formlayout/TableInFormLayoutCausesScrolling.java @@@ -1,45 -1,45 +1,45 @@@ - 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; - - public class TableInFormLayoutCausesScrolling extends AbstractTestCase { - - @Override - public void init() { - // Window Initialization. - 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.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; + } } diff --cc tests/testbench/com/vaadin/tests/components/label/LabelTest.java index daaf4c0b98,5c71046404..130aaeca78 --- a/tests/testbench/com/vaadin/tests/components/label/LabelTest.java +++ b/tests/testbench/com/vaadin/tests/components/label/LabelTest.java @@@ -1,102 -1,100 +1,102 @@@ - 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