Package com.onpositive.gae.baseviewer

Source Code of com.onpositive.gae.baseviewer.EditorUtility$IUpdateList

package com.onpositive.gae.baseviewer;

import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.el.MapELResolver;

import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.ToolBarManager;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.layout.GridDataFactory;
import org.eclipse.jface.viewers.IContentProvider;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.viewers.StructuredViewer;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerRow;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.DisposeEvent;
import org.eclipse.swt.events.DisposeListener;
import org.eclipse.swt.events.PaintEvent;
import org.eclipse.swt.events.PaintListener;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Spinner;
import org.eclipse.swt.widgets.ToolBar;
import org.eclipse.ui.forms.events.HyperlinkEvent;
import org.eclipse.ui.forms.events.IHyperlinkListener;
import org.eclipse.ui.plugin.AbstractUIPlugin;

import com.google.appengine.api.datastore.Blob;
import com.google.appengine.api.datastore.Category;
import com.google.appengine.api.datastore.Email;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.GeoPt;
import com.google.appengine.api.datastore.IMHandle;
import com.google.appengine.api.datastore.IMHandle.Scheme;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.Link;
import com.google.appengine.api.datastore.PhoneNumber;
import com.google.appengine.api.datastore.PostalAddress;
import com.google.appengine.api.datastore.Rating;
import com.google.appengine.api.datastore.ShortBlob;
import com.google.appengine.api.datastore.Text;
import com.google.appengine.api.users.User;
import com.google.apphosting.api.ApiProxy;
import com.onpositive.commons.elements.AbstractUIElement;
import com.onpositive.commons.elements.CTabFolderElement;
import com.onpositive.commons.elements.Container;
import com.onpositive.commons.elements.ICompositeElement;
import com.onpositive.commons.elements.IDataListener;
import com.onpositive.commons.elements.IElementListener;
import com.onpositive.commons.elements.LinkElement;
import com.onpositive.commons.elements.SWTEventListener;
import com.onpositive.commons.elements.UniversalUIElement;
import com.onpositive.commons.ui.appearance.HorizontalLayouter;
import com.onpositive.commons.ui.appearance.OneElementOnLineLayouter;
import com.onpositive.commons.ui.dialogs.InputElementDialog;
import com.onpositive.commons.ui.dialogs.TitledDialog;
import com.onpositive.commons.ui.tableeditor.Field;
import com.onpositive.commons.ui.tableeditor.OperationCallback;
import com.onpositive.gae.baseviewer.BaseDataFacade.CGAEField;
import com.onpositive.gae.baseviewer.BaseDataFacade.GAEField;
import com.onpositive.gae.baseviewer.BaseDataFacade.PGAEField;
import com.onpositive.gae.baseviewer.DataStoreTableUI.EditingBinding;
import com.onpositive.gae.baseviewer.ProjectMiner.FieldInfo;
import com.onpositive.gae.baseviewer.SerializableBlobVisualizer.IUpdateBlob;
import com.onpositive.semantic.model.api.property.IValueListener;
import com.onpositive.semantic.model.api.property.PropertyProviderLookup;
import com.onpositive.semantic.model.api.property.adapters.ILabelLookup;
import com.onpositive.semantic.model.api.property.adapters.IRealmProvider;
import com.onpositive.semantic.model.api.property.adapters.ITextLabelProvider;
import com.onpositive.semantic.model.api.property.adapters.TextProviderAdapter;
import com.onpositive.semantic.model.api.property.java.ClassAdapterFactory;
import com.onpositive.semantic.model.binding.Binding;
import com.onpositive.semantic.model.binding.IBinding;
import com.onpositive.semantic.model.binding.IBindingChangeListener;
import com.onpositive.semantic.model.realm.CodeAndMessage;
import com.onpositive.semantic.model.realm.IFactory;
import com.onpositive.semantic.model.realm.IRealm;
import com.onpositive.semantic.model.realm.ISetDelta;
import com.onpositive.semantic.model.realm.IValidator;
import com.onpositive.semantic.model.realm.OrderedRealm;
import com.onpositive.semantic.model.realm.Realm;
import com.onpositive.semantic.model.realm.ValidatorAdapter;
import com.onpositive.semantic.model.ui.property.editors.ButtonSelector;
import com.onpositive.semantic.model.ui.property.editors.CompositeEditor;
import com.onpositive.semantic.model.ui.property.editors.DateTimeEditor;
import com.onpositive.semantic.model.ui.property.editors.DisposeBindingListener;
import com.onpositive.semantic.model.ui.property.editors.OneLineTextElement;
import com.onpositive.semantic.model.ui.property.editors.SpinnerEditor;
import com.onpositive.semantic.model.ui.property.editors.ViewerTextElement;
import com.onpositive.semantic.model.ui.property.editors.structured.ComboEnumeratedValueSelector;
import com.onpositive.semantic.model.ui.property.editors.structured.ListEnumeratedValueSelector;
import com.onpositive.semantic.model.ui.viewer.structured.RealmLazyContentProvider;

public class EditorUtility {

  public static final Class<?>[] SUPPORTED_TYPES = new Class[] {
      String.class, Long.class, Double.class, Boolean.class, Date.class,
      Text.class, ShortBlob.class, Blob.class, Link.class,
      Category.class, Email.class, PostalAddress.class,
      PhoneNumber.class, IMHandle.class, GeoPt.class, User.class,
      Key.class /* , int.class, long.class, double.class */};

  public static void createBindingsForType(Class parentType, Binding bnd,
      CompositeEditor editor, IJavaProject project) {
    java.lang.reflect.Field[] fs = parentType.getDeclaredFields();
    if (editor.getLayoutManager() == null) {
      editor.setLayoutManager(new OneElementOnLineLayouter());
    }

    Container text = (Container) editor.getData("text");

    for (java.lang.reflect.Field f : fs) {
      String chId = f.getName();
      Class type = f.getType();

      Binding binding = bnd.getBinding(chId);
      binding.setName(chId);
      Object adapter = new ClassAdapterFactory().getAdapter(type,
          IValidator.class);
      if (adapter != null) {
        binding.setAdapter(IValidator.class, (IValidator) adapter);
      }
      binding.setAutoCommit(false);

      if (type == String.class) {
        OneLineTextElement<String> t = new OneLineTextElement<String>();
        t.setBinding(binding);
        editor.add(t);
      } else if (Number.class.isAssignableFrom(type)
          || type.isPrimitive()) {
        OneLineTextElement<Number> t = new OneLineTextElement<Number>();
        final Class tt = type;
        binding.addValidator(new ValidatorAdapter() {

          public CodeAndMessage isValid(IBinding context,
              Object object) {
            if (object == null) {
              return CodeAndMessage.OK_MESSAGE;
            }
            try {
              if (object instanceof String) {
                if (tt == Double.class) {
                  Double.parseDouble((String) object);
                } else if (tt == Long.class) {
                  Long.parseLong((String) object);
                } else if (tt == Float.class) {
                  Float.parseFloat((String) object);
                } else if (tt == Integer.class) {
                  Integer.parseInt((String) object);
                }
              } else {
                if (!Number.class.isAssignableFrom(object
                    .getClass())) {
                  return CodeAndMessage
                      .errorMessage("The number should be in this place");
                }
              }
              return CodeAndMessage.OK_MESSAGE;
            } catch (NumberFormatException e) {
              return CodeAndMessage
                  .errorMessage("The number should be in this place");
            }
            // return super.isValid(context, object);
          }

        });
        t.setBinding(binding);
        editor.add(t);

      } else if (type == Boolean.class) {
        ComboEnumeratedValueSelector<Boolean> t = new ComboEnumeratedValueSelector<Boolean>();
        t.setBinding(binding);
        editor.add(t);
      } else if (type == Text.class) {
        if (text == null) {
          text = new CTabFolderElement();
          text.setBordered(true);
          editor.setData("text", text);
          editor.add(text);
        }
        createText(editor, text, binding, false);
      } else if (type == Link.class) {
        createLink(editor, binding);
      } else if (type == Category.class) {
        createCategory(editor, binding);
      } else if (type == Email.class) {
        createEmail(editor, binding);
      } else if (type == PostalAddress.class) {
        createPostalAddress(editor, binding);
      } else if (type == PhoneNumber.class) {
        createPhoneNumber(editor, binding);
      } else if (type == Date.class) {
        createDate(editor, binding);
      } else if (type == IMHandle.class) {
        createIMHandle(editor, binding);
      } else if (type == GeoPt.class) {
        createGeoPt(editor, binding);
      } else if (type == User.class) {
        createUser(editor, binding);
      } else if (type == Blob.class || type == ShortBlob.class) {
        createBlob(editor, type, binding, project);
      } else if (type == Rating.class) {
        createRating(editor, binding);
      } else if (type == Key.class) {
        OneLineTextElement<String> t = new OneLineTextElement<String>();
        t.setBinding(binding);
        editor.add(t);
        // GAEField ff = f.new GAEField(chId, false);
        // createKey(editor, binding, ff);
      } else {
        if (!binding.allowsMultiValues()) {
          OneLineTextElement<String> t = new OneLineTextElement<String>();
          t.setBinding(binding);
          binding.allowsMultiValues();
          binding.setReadOnly(true);
          editor.add(t);
        } else {
          if (text == null) {
            text = new CTabFolderElement();
            text.setBordered(true);
            editor.setData("text", text);
            editor.add(text);
          }
          Container m = new Container();
          m.setLayout(new GridLayout(1, false));
          m.setCaption(binding.getName());
          final ListEnumeratedValueSelector<Object> v = new ListEnumeratedValueSelector<Object>();
          binding.addValueListener(new IValueListener<Object>() {

            public void valueChanged(Object oldValue,
                Object newValue) {
              return;

            }
          });
          v.setBinding(binding);
          v.setLayoutData(GridDataFactory.fillDefaults()
              .grab(true, true).create());
          m.add(v);
          text.add(m);
        }
      }
    }
  }

  public static void createBindings(
      final com.google.appengine.api.datastore.Entity e,
      CompositeEditor editor, final Binding bnd, Field[] fields,
      final BaseDataFacade facade) {
    Container text = (Container) editor.getData("text");
    for (final Field f : fields) {
      final GAEField fm = (GAEField) f;
      if (fm.multiplicity) {
        if (text == null) {
          text = new CTabFolderElement();
          text.setBordered(true);
          editor.setData("text", text);
          editor.add(text);
        }
        createMultiEdit(e, bnd, facade, text, f, fm);
        continue;
      }
      if (f.isKey()) {
        continue;
      } else {
        Class<?> type = f.getType();
        if (type != null) {
          final Binding binding = bnd.getBinding(f.name);
          binding.setValue(e.getProperty(f.name), null);
          Object adapter = new ClassAdapterFactory().getAdapter(type,
              IValidator.class);
          if (adapter != null) {
            binding.setAdapter(IValidator.class,
                (IValidator) adapter);
          }
          adapter = new ClassAdapterFactory().getAdapter(type,
              ILabelLookup.class);
          if (adapter != null) {
            binding.setAdapter(ILabelLookup.class,
                (ILabelLookup) adapter);
          }
          adapter = new ClassAdapterFactory().getAdapter(type,
              IRealmProvider.class);
          if (adapter != null) {

            binding.setAdapter(IRealmProvider.class,
                (IRealmProvider) adapter);
          } else {
            IRealm<?> c = facade.getRealm(f);
            if (c != null) {
              binding.setRealm(c);
            }
          }
          binding.setReadOnly(false);
          binding.setName(f.getTitle());

          if (type == String.class) {
            OneLineTextElement<String> t = new OneLineTextElement<String>();
            t.setBinding(binding);
            editor.add(t);
          } else if (Number.class.isAssignableFrom(type)) {
            OneLineTextElement<String> t = new OneLineTextElement<String>();
            t.setBinding(binding);
            editor.add(t);

          } else if (type == Boolean.class) {
            ComboEnumeratedValueSelector<Boolean> t = new ComboEnumeratedValueSelector<Boolean>();
            t.setBinding(binding);
            editor.add(t);
          } else if (type == Text.class) {
            if (text == null) {
              text = new CTabFolderElement();
              text.setBordered(true);
              editor.setData("text", text);
              editor.add(text);
            }
            createText(editor, text, binding, false);
          } else if (type == Link.class) {
            createLink(editor, binding);
          } else if (type == Category.class) {
            createCategory(editor, binding);
          } else if (type == Email.class) {
            createEmail(editor, binding);
          } else if (type == PostalAddress.class) {
            createPostalAddress(editor, binding);
          } else if (type == PhoneNumber.class) {
            createPhoneNumber(editor, binding);
          } else if (type == Date.class) {
            createDate(editor, binding);
          } else if (type == IMHandle.class) {
            createIMHandle(editor, binding);
          } else if (type == GeoPt.class) {
            createGeoPt(editor, binding);
          } else if (type == User.class) {
            createUser(editor, binding);
          } else if (type == Blob.class || type == ShortBlob.class) {
            createBlob(editor, type, binding, facade.getProject());
          } else if (type == Rating.class) {
            createRating(editor, binding);
          } else if (type == Key.class) {
            createKey(editor, binding, f);
          }
        }
      }
    }
    if (text != null) {
      text.getLayoutHints().setHint(new Point(400, 200));
      text.getLayoutHints().setGridy(true);
    }
  }

  public static void createBindingsWithButton(
      final com.google.appengine.api.datastore.Entity e,
      CompositeEditor editor, final Binding bnd, Field[] fields,
      final BaseDataFacade facade, boolean needIndexable) {
    ApiProxy.setEnvironmentForCurrentThread(new FakeEnvironment(facade
        .getAppId(), facade.namespace));

    Container text = (Container) editor.getData("text");
    Map<String, Collection<Field>> sorted = sortFields(fields, facade);
    Collection<Field> ownFields = sorted.get(facade.getKind());
    if (editor.getLayoutManager() == null) {
      editor.setLayoutManager(new OneElementOnLineLayouter());
    }
    if (ownFields == null) {
      ownFields = new HashSet<Field>();
    }
    for (Field f : ownFields) {
      text = createAppropriateControl(e, editor, bnd, facade, text, f,
          needIndexable);
    }
    if (sorted.keySet().size() > 1) {
      Container ctab = new CTabFolderElement();
      ctab.setText("Embedded");
      ctab.setBordered(true);

      text = null;
      for (String group : sorted.keySet()) {
        if (group.equals(facade.getKind())) {
          continue;
        }
        CompositeEditor container = new CompositeEditor();
        container.setText(group);
        Collection<Field> fs = sorted.get(group);
        for (final Field f : fs) {
          text = createAppropriateControl(e, container, bnd, facade,
              text, f, needIndexable);
        }
        ctab.add(container);
      }
      editor.add(ctab);
    }
    if (text != null) {
      text.getLayoutHints().setHint(new Point(400, 200));
      text.getLayoutHints().setGridy(true);
    }
  }

  private static Container createAppropriateControl(
      final com.google.appengine.api.datastore.Entity e,
      final CompositeEditor editor, final Binding bnd,
      final BaseDataFacade facade, Container text, final Field f,
      final boolean needIndexable) {
    final GAEField fm = (GAEField) f;
    final CompositeEditor ed = new CompositeEditor();
    ed.setLayout(new GridLayout());
    ed.setLayoutManager(new HorizontalLayouter());
    if (fm.multiplicity) {
      if (text == null) {
        text = new CTabFolderElement();
        text.setBordered(true);
        ed.setData("text", text);
        ed.add(text);
      }
      IBinding bb = createSpecialMultiEdit(e, bnd, facade, text, f, fm,
          needIndexable);
      // addButtonSelector(bb, ed,null);
      ed.setId(bnd.getId());
      editor.add(ed);
      return text;
    }
    if (f.isKey()) {
      return text;
    } else {
      final Class<?> type = f.getType();
      if (type != null) {
        final Binding binding = bnd.getBinding(f.name);
        binding.setValue(e.getProperty(f.name), null);
        Object adapter = new ClassAdapterFactory().getAdapter(type,
            IValidator.class);
        if (adapter != null) {
          binding.setAdapter(IValidator.class, (IValidator) adapter);
        }
        adapter = new ClassAdapterFactory().getAdapter(type,
            ILabelLookup.class);
        if (adapter != null) {
          binding.setAdapter(ILabelLookup.class,
              (ILabelLookup) adapter);
        }
        adapter = new ClassAdapterFactory().getAdapter(type,
            IRealmProvider.class);
        if (adapter != null) {

          binding.setAdapter(IRealmProvider.class,
              (IRealmProvider) adapter);
        } else {
          IRealm<?> c = facade.getRealm(f);
          if (c != null) {
            binding.setRealm(c);
          }
        }
        binding.setReadOnly(false);
        binding.setName(f.getTitle());

        if (type == String.class) {
          OneLineTextElement<String> t = new OneLineTextElement<String>();
          t.setBinding(binding);
          ed.add(t);

          addIsNullButtonSelector(binding, ed, null);
          if (needIndexable) {
            addNotIndexableButton(binding, ed, f);
          }
        } else if (Number.class.isAssignableFrom(type)
            || type.isPrimitive()) {
         
          binding.setSubjectClass(type);
          OneLineTextElement<Number> t = new OneLineTextElement<Number>();
          binding.addValidator(new ValidatorAdapter() {

            public CodeAndMessage isValid(IBinding context,
                Object object) {
              if (object == null) {
                return CodeAndMessage.OK_MESSAGE;
              }
              try {
                if (object instanceof String) {
                  if (type == Double.class) {
                    Double.parseDouble((String) object);
                  } else if (type == Long.class) {
                    Long.parseLong((String) object);
                  } else if (type == Float.class) {
                    Float.parseFloat((String) object);
                  } else if (type == Integer.class) {
                    Integer.parseInt((String) object);
                  }
                } else {
                  if (!Number.class.isAssignableFrom(object
                      .getClass())) {
                    return CodeAndMessage
                        .errorMessage("The number should be in this place");
                  }
                }
                return CodeAndMessage.OK_MESSAGE;
              } catch (NumberFormatException e) {
                return CodeAndMessage
                    .errorMessage("The number should be in this place");
              }
              // return super.isValid(context, object);
            }

          });
          t.setBinding(binding);
          ed.add(t);

          addIsNullButtonSelector(binding, ed, null);
          if (needIndexable) {
            addNotIndexableButton(binding, ed, f);
          }
        } else if (type == Boolean.class) {
          binding.setSubjectClass(type);
          ComboEnumeratedValueSelector<Boolean> t = new ComboEnumeratedValueSelector<Boolean>();
          t.setBinding(binding);
          ed.add(t);

          addIsNullButtonSelector(binding, ed, null);
          if (needIndexable) {
            addNotIndexableButton(binding, ed, f);
          }
        } else if (type == Text.class) {
          if (text == null) {
            text = new CTabFolderElement();
            text.setBordered(true);
            ed.setData("text", text);
            ed.add(text);
          }
          createText(ed, text, binding, true);

          // addIsNullButtonSelector(binding, ed, null);
          if (needIndexable) {
            addNotIndexableButton(binding, ed, f);
          }
        } else if (type == Link.class) {
          createLink(ed, binding);

          addIsNullButtonSelector(binding, ed, null);
          if (needIndexable) {
            addNotIndexableButton(binding, ed, f);
          }
        } else if (type == Category.class) {
          createCategory(ed, binding);

          addIsNullButtonSelector(binding, ed, null);
          if (needIndexable) {
            addNotIndexableButton(binding, ed, f);
          }
        } else if (type == Email.class) {
          createEmail(ed, binding);

          addIsNullButtonSelector(binding, ed, null);
          if (needIndexable) {
            addNotIndexableButton(binding, ed, f);
          }
        } else if (type == PostalAddress.class) {
          createPostalAddress(ed, binding);

          addIsNullButtonSelector(binding, ed, null);
          if (needIndexable) {
            addNotIndexableButton(binding, ed, f);
          }
        } else if (type == PhoneNumber.class) {
          createPhoneNumber(ed, binding);

          addIsNullButtonSelector(binding, ed, null);
          if (needIndexable) {
            addNotIndexableButton(binding, ed, f);
          }
        } else if (type == Date.class) {
          createDate(ed, binding);

          addIsNullButtonSelector(binding, ed, null);
          if (needIndexable) {
            addNotIndexableButton(binding, ed, f);
          }
        } else if (type == IMHandle.class) {
          createIMHandle(ed, binding);

          addIsNullButtonSelector(binding, ed, null);
          if (needIndexable) {
            addNotIndexableButton(binding, ed, f);
          }
        } else if (type == GeoPt.class) {
          createGeoPt(ed, binding);

          addIsNullButtonSelector(binding, ed, null);
          if (needIndexable) {
            addNotIndexableButton(binding, ed, f);
          }
        } else if (type == User.class) {
          createUser(ed, binding);

          addIsNullButtonSelector(binding, ed, null);
          if (needIndexable) {
            addNotIndexableButton(binding, ed, f);
          }
        } else if (type == Blob.class || type == ShortBlob.class) {
          createBlob(ed, type, binding, facade.getProject());

          addIsNullButtonSelector(binding, ed, null);
          if (needIndexable) {
            addNotIndexableButton(binding, ed, f);
          }
        } else if (type == Rating.class) {
          createRating(ed, binding);

          addIsNullButtonSelector(binding, ed, null);
          if (needIndexable) {
            addNotIndexableButton(binding, ed, f);
          }
        } else if (type == Key.class) {
          createKey(ed, binding, f);

          addIsNullButtonSelector(binding, ed, null);
          if (needIndexable) {
            addNotIndexableButton(binding, ed, f);
          }
        }
        // editor.setId(binding.getId());
      } else {
        final Binding binding = bnd.getBinding(f.name);
        final Container txt = text;

        binding.setReadOnly(false);
        binding.setName(f.getTitle());

        final LinkElement bs = new LinkElement();
        bs.setId(binding.getId());
        ed.setId(binding.getId());
        bs.getLayoutHints().setGrabVertical(false);
        bs.setText("Specify type");
        bs.setCaption(f.getTitle());
        bs.addHyperLinkListener(new IHyperlinkListener() {

          public void linkExited(HyperlinkEvent e) {
            // TODO Auto-generated method stub

          }

          public void linkEntered(HyperlinkEvent e) {
            return;

          }

          public void linkActivated(HyperlinkEvent event) {
            final Binding tmpBinding = new Binding("");
            tmpBinding.setName("Specify type for property");

            final Binding type = tmpBinding.getBinding("type");
            type.setReadOnly(false);
            type.setRequired(true);
            type.setName("Select type");
            type.setAdapter(ITextLabelProvider.class,
                new TextProviderAdapter() {

                  public String getText(Object object) {
                    Class<?> c = (Class<?>) object;
                    return c.getSimpleName();
                  }
                });
            type.setValue(String.class, null);
            type.setRealm(new Realm<Class<?>>(
                EditorUtility.SUPPORTED_TYPES));

            final ComboEnumeratedValueSelector ce = new ComboEnumeratedValueSelector(
                type);

            final CompositeEditor c1 = new CompositeEditor();
            c1.setLayoutManager(new OneElementOnLineLayouter());
            c1.add(ce);

            final Binding multi = tmpBinding.getBinding("multi");
            multi.setReadOnly(false);
            multi.setName("Multivalue");
            multi.setValue(false, null);

            ButtonSelector multiB = new ButtonSelector(multi,
                SWT.CHECK);
            c1.add(multiB);

            final Binding kk = tmpBinding.getBinding("KeyKind");
            kk.setName("Kind");
            kk.setValue(e.getKind(), null);
            kk.setReadOnly(false);
            kk.setRequired(false);

            final OneLineTextElement<String> keyKind = new OneLineTextElement<String>(
                kk);

            type.addValueListener(new IValueListener<Class<?>>() {

              public void valueChanged(Class<?> oldValue,
                  Class<?> newValue) {
                if (newValue == Key.class) {
                  c1.add(1, keyKind);
                  c1.getControl().getShell().pack(true);
                } else if (oldValue == Key.class) {
                  c1.remove(keyKind);
                  c1.getControl().getShell().pack(true);
                }

              }

            });

            CompositeEditor c2 = new CompositeEditor();
            c2.setLayoutManager(new HorizontalLayouter());
            ButtonSelector ok = new ButtonSelector();
            ok.setText("submit");
            ButtonSelector canc = new ButtonSelector();
            canc.setText("cancel");

            c2.add(ok);
            c2.add(canc);

            CompositeEditor finall = new CompositeEditor(tmpBinding);
            finall.setLayoutManager(new OneElementOnLineLayouter());
            finall.add(c1);
            finall.add(c2);

            final InputElementDialog ied = new InputElementDialog(
                finall);

            ok.setValue(new Runnable() {

              public void run() {
                IStructuredSelection iss = ce.getSelection();
                if (!iss.isEmpty()) {
                  Object fe = iss.getFirstElement();
                  Class choosen = (Class) fe;
                  ied.close();
                  ed.getParent().remove(ed);// remove(bs);

                  // ed.setLayoutManager(new
                  // HorizontalLayouter());
                  // ed.setBordered(true);
                  f.setType(choosen);
                  Object val = multi.getValue();
                  Object kind = kk.getValue();
                  if (val != null && f instanceof GAEField) {
                    ((GAEField) f).multiplicity = (Boolean) val;
                  }
                  if (kind != null) {
                    ((GAEField) f)
                        .setKeyKind((String) kind);
                  }
                  createAppropriateControl(e, editor,
                      binding, facade, txt, f,
                      needIndexable);
                  // ed.recreate();

                  editor.getControl().getShell()
                      .layout(true, true);
                  editor.getControl().getShell().pack(true);

                  // tmpBinding.dispose();
                  return;
                }
              }
            });

            canc.setValue(new Runnable() {

              public void run() {
                tmpBinding.dispose();
                ied.close();
              }
            });
            ied.open();

            return;

          }
        });

        ed.add(bs);
      }
    }
    editor.add(ed);
    return text;
  }

  private static IBinding createSpecialMultiEdit(
      final com.google.appengine.api.datastore.Entity e,
      final Binding bnd, final BaseDataFacade facade, Container text,
      final Field f, final GAEField fm, final boolean needIndexable) {
    Container m = new Container();
    m.setLayout(new GridLayout(1, false));
    m.setCaption(f.getTitle());
    final ListEnumeratedValueSelector<Object> v = new ListEnumeratedValueSelector<Object>() {
      @Override
      protected IRealm<Object> getRealm(Object value2) {

        if (this.oldRealm != null) {
          return (IRealm<Object>) this.oldRealm;
        }

        if (value2 instanceof IRealm<?>) {
          return (IRealm<Object>) value2;
        }
        if (value2 instanceof Collection) {
          final Collection<?> es = (Collection<?>) value2;

          if (value2 instanceof List) {
            return new OrderedRealm<Object>((Collection<Object>) es);
          }

          return new Realm<Object>((Collection<Object>) es);
        }
        final OrderedRealm<Object> realm = new OrderedRealm<Object>();
        if (value2 != null) {
          realm.add(value2);
        }
        this.oldRealm = realm;
        return realm;
      }

      @Override
      protected void initContentProviderFromParent() {
        if (uprovider != null) {
          this.viewer.setContentProvider(uprovider);
          this.provider = uprovider;
        } else {
          final RealmLazyContentProvider realmLazyContentProvider = new RealmLazyContentProvider() {
            @Override
            protected void enableSorting() {
              return;
            }

            @Override
            public void updateElement(int index) {
              // inverse == true means no inverse
              setInverse(true);
              super.updateElement(index);
            }
          };
          // realmLazyContentProvider.setComparator(null, true);
          this.viewer.setContentProvider(realmLazyContentProvider);
          this.registerProvider(realmLazyContentProvider);
          this.provider = realmLazyContentProvider;
        }
      }
    };
    m.add(new UniversalUIElement<ToolBar>(ToolBar.class, SWT.NONE) {

      protected ToolBar createControl(Composite conComposite) {
        ToolBarManager manager = new ToolBarManager();
        manager.add(new Action("New value") {
          {
            setImageDescriptor(AbstractUIPlugin
                .imageDescriptorFromPlugin(Activator.PLUGIN_ID,
                    "/icons/add_exc.gif"));
          }

          public void run() {
            Key parent = e.getKey();
            if (f instanceof CGAEField) {
              CGAEField cgf = (CGAEField) f;
              BaseDataFacade fac = new BaseDataFacade(
                  cgf.keyKind, facade.getProject(), facade
                      .isDebug());
              fac.setNamespace(facade.getNamespace());
              DataStoreTableUI dstui = new DataStoreTableUI();
              dstui.setFacade(fac);
              ApiProxy.setEnvironmentForCurrentThread(new FakeEnvironment(
                  facade.getAppId(), facade.namespace));
              // parent =
              // StringInputOutput.dublicateKey(parent,facade.namespace);

              Entity ent = new Entity(cgf.keyKind, parent);
              Map childrenMP = fac.getChildren(); // facade
              Object cMap = childrenMP.get(cgf.getKeyKind());
              Collection coll = null;
              if (cMap != null) {
                coll = ((Collection) ((HashMap) cMap)
                    .get(parent));
              }
              if (coll != null && coll.size() != 0) {
                Entity old = (Entity) coll
                    .toArray(new Object[coll.size()])[coll
                    .size() - 1];
                for (Iterator<String> it = old.getProperties()
                    .keySet().iterator(); it.hasNext();) {
                  ent.setProperty(it.next(), "");
                }
              }
              ArrayList<Entity> select = new ArrayList();
              select.add(ent);
              fac.determineFields(select);
              // v.addValue(ent);
              dstui.open(ent, false, false, new IUpdateList() {

                public void update(Entity e) {
                  v.addValue(e);
                }
              });// ((Collection)((HashMap)facade.getChildren().get(cgf.getKeyKind())).get(e.getKey()));

            } else {
              Object firstElement = null;
              Binding bnd = new Binding(firstElement);
              bnd.setName("Edit");
              CompositeEditor m = new CompositeEditor(bnd);
              TitledDialog dlg = new TitledDialog(m);
              GAEField singleField = fm.getSingleField();
              ApiProxy.setEnvironmentForCurrentThread(new FakeEnvironment(
                  e.getAppId()));
              Entity c = new Entity("A");

              if (fm instanceof CGAEField) {
                c = new Entity(fm.getKeyKind(), parent);
                // Entity example =
              } else {
                c.setProperty(f.name, firstElement);
              }
              createBindingsWithButton(c, m, bnd,
                  new Field[] { singleField }, facade, false);

              int open = dlg.open();
              if (open == Dialog.OK) {
                Binding bb = bnd.getBinding(f.name);
                Object value = bb.getValue();
                if (value == null || bb.isReadOnly()) {
                  value = new NullValue();
                }
                v.addValue(value);
              }
              bnd.dispose();

            }
          }
        });
        manager.add(new Action("Edit selected") {
          {
            setImageDescriptor(AbstractUIPlugin
                .imageDescriptorFromPlugin(Activator.PLUGIN_ID,
                    "/icons/text_edit.gif"));
          }

          public void run() {
            if (f instanceof CGAEField) {
              CGAEField cgf = (CGAEField) f;

              Object[] selected = v.getSelection().toArray();
              if (selected.length == 1) {
                BaseDataFacade fac = new BaseDataFacade(
                    cgf.keyKind, facade.getProject(),
                    facade.isDebug());
                fac.setNamespace(facade.getNamespace());
                DataStoreTableUI dstui = new DataStoreTableUI();
                Object selecttedd = selected[0];
                if (selecttedd instanceof Entity) {
                  final Entity sel = (Entity) selecttedd;
                  ArrayList<Entity> select = new ArrayList();
                  select.add(sel);
                  fac.determineFields(select);
                  dstui.setFacade(fac);
                  dstui.open(sel, false, true,
                      new IUpdateList() {

                        public void update(Entity e) {
                          v.removeValue(sel);
                          v.addValue(e);
                        }
                      });
                }
              }
              return;
            } else {
              Object firstElement = v.getSelection()
                  .getFirstElement();
              Binding bnd = new Binding(firstElement);
              bnd.setName("Edit");
              CompositeEditor m = new CompositeEditor(bnd);
              TitledDialog dlg = new TitledDialog(m);
              GAEField singleField = fm.getSingleField();
              ApiProxy.setEnvironmentForCurrentThread(new FakeEnvironment(
                  e.getAppId()));
              Entity c = new Entity("A");
              if (firstElement instanceof NullValue) {
                c.setProperty(f.name, null);
              } else {
                c.setProperty(f.name, firstElement);
              }
              createBindingsWithButton(c, m, bnd,
                  new Field[] { singleField }, facade, false);
              int open = dlg.open();
              if (open == Dialog.OK) {
                StructuredViewer viewer = v.getViewer();
                if (viewer instanceof TableViewer) {
                  Binding bb = bnd.getBinding(f.name);
                  Object value = bb.getValue();
                  if (value == null || bb.isReadOnly()) {
                    value = new NullValue();
                  }
                 
                  TableViewer tv = (TableViewer)viewer;
                  int index = tv.getTable().getSelectionIndex();                 
                  v.editValue(value, index);                 
                  //tv.get
                 
                } else {
                  v.removeValue(firstElement);
                  Binding bb = bnd.getBinding(f.name);
                  Object value = bb.getValue();
                  if (value == null || bb.isReadOnly()) {
                    value = new NullValue();
                  }
                  v.addValue(value);
                }
              }
              bnd.dispose();
            }
          }
        });
        manager.add(new Action("Delete selected") {
          {
            setImageDescriptor(AbstractUIPlugin
                .imageDescriptorFromPlugin(Activator.PLUGIN_ID,
                    "/icons/delete.gif"));
          }

          @SuppressWarnings("unchecked")
          public void run() {
            final List selected = v.getSelection().toList();

            if (f instanceof CGAEField) {
              final CGAEField cgf = (CGAEField) f;
              BaseDataFacade fac = new BaseDataFacade(
                  cgf.keyKind, facade.getProject(), facade
                      .isDebug());
              fac.setNamespace(facade.getNamespace());
              fac.delete(selected.toArray(new Entity[selected
                  .size()]), new OperationCallback() {

                public void passed(Object object) {
                  Collection coll = (Collection) ((HashMap) facade
                      .getChildren()
                      .get(cgf.getKeyKind())).get(e
                      .getKey());
                  coll.removeAll(selected);
                  facade.updateChildren(e);
                  v.removeValues(selected);
                }

                public void failed(Exception exception) {
                  return;
                }
              });
              // facade.updateChildren(e);
            } else {
              v.removeValues(selected);
            }
          }
        });
        return manager.createControl(conComposite);
      }

    });

    v.setValueAsSelection(false);
    Binding binding = bnd.getBinding(f.name);
    binding.setReadOnly(false);
    Object property = null;
    if (f instanceof CGAEField) {

      HashMap hashMap = (HashMap) facade.getChildren().get(
          ((CGAEField) f).keyKind);
      if (hashMap != null) {
        Collection col = (Collection) (hashMap).get(e.getKey());
        if (col != null) {
          property = new ArrayList<Object>();
          for (Iterator i = col.iterator(); i.hasNext();) {
            Entity ent = (Entity) i.next();
            ((ArrayList<Object>) property).add(ent);
            v.setLabelProvider(new LabelProvider() {

              public String getText(Object element) {
                Entity e = (Entity) element;
                String res = "";

                String[] details = ((CGAEField) f)
                    .getKeyKindDetails();
                if (details != null && details.length != 0) {
                  StringBuilder sb = new StringBuilder();
                  int ch = 0;
                  for (String det : details) {
                    Object prop = e.getProperty(det);
                    String toStr = ((CGAEField) f)
                        .getObjectText2(e, prop);
                    sb.append(toStr);
                    if (ch != details.length - 1) {
                      sb.append(":");
                    }
                    ch++;
                  }
                  res = sb.toString();
                } else {
                  res = e.getKey().toString();
                }
                return res;
              }
            });
          }
        } else {
          property = "";// <empty>
        }
      } else {
        property = "";// <empty>
      }

    } else if (f instanceof PGAEField) {
      property = e.getProperty(f.name);
    } else {
      property = e.getProperty(f.name);
    }
    if (property instanceof Collection<?>) {
      Collection c = (Collection) property;
      boolean remove = c.remove(null);
      if (remove) {
        c.add(new NullValue());
      }
    }
    binding.setValue(property, null);
    v.setBinding(binding);
    v.setLayoutData(GridDataFactory.fillDefaults().grab(true, true)
        .create());
    m.add(v);
    if (needIndexable) {
      addNotIndexableButton(binding, m, fm);
    }
    text.add(m);
    return binding;
  }

  private static IBinding createMultiEdit(
      final com.google.appengine.api.datastore.Entity e,
      final Binding bnd, final BaseDataFacade facade, Container text,
      final Field f, final GAEField fm) {
    Container m = new Container();
    m.setLayout(new GridLayout(1, false));
    m.setCaption(f.getTitle());
    final ListEnumeratedValueSelector<Object> v = new ListEnumeratedValueSelector<Object>();
    m.add(new UniversalUIElement<ToolBar>(ToolBar.class, SWT.NONE) {

      protected ToolBar createControl(Composite conComposite) {
        ToolBarManager manager = new ToolBarManager();
        manager.add(new Action("New value") {
          {
            setImageDescriptor(AbstractUIPlugin
                .imageDescriptorFromPlugin(Activator.PLUGIN_ID,
                    "/icons/add_exc.gif"));
          }

          public void run() {
            if (f instanceof CGAEField) {
              CGAEField cgf = (CGAEField) f;
              BaseDataFacade fac = new BaseDataFacade(
                  cgf.keyKind, facade.getProject(), facade
                      .isDebug());
              fac.setNamespace(facade.getNamespace());
              DataStoreTableUI dstui = new DataStoreTableUI();
              dstui.setFacade(fac);
              Entity ent = new Entity(cgf.keyKind, e.getKey());
              Collection coll = ((Collection) ((HashMap) facade
                  .getChildren().get(cgf.getKeyKind())).get(e
                  .getKey()));
              if (coll != null && coll.size() != 0) {
                Entity old = (Entity) coll
                    .toArray(new Object[coll.size()])[coll
                    .size() - 1];
                for (Iterator<String> it = old.getProperties()
                    .keySet().iterator(); it.hasNext();) {
                  ent.setProperty(it.next(), "");
                }
              }
              ArrayList<Entity> select = new ArrayList();
              select.add(ent);
              fac.determineFields(select);
              // v.addValue(ent);
              dstui.open(ent, false, new IUpdateList() {

                public void update(Entity e) {
                  v.addValue(e);
                }
              });// ((Collection)((HashMap)facade.getChildren().get(cgf.getKeyKind())).get(e.getKey()));

            } else {
              Object firstElement = null;
              Binding bnd = new Binding(firstElement);
              bnd.setName("Edit");
              CompositeEditor m = new CompositeEditor(bnd);
              m.setLayoutManager(new HorizontalLayouter());
              TitledDialog dlg = new TitledDialog(m);
              GAEField singleField = fm.getSingleField();
              ApiProxy.setEnvironmentForCurrentThread(new FakeEnvironment(
                  e.getAppId()));
              Entity c = new Entity("A");

              if (fm instanceof CGAEField) {
                c = new Entity(fm.getKeyKind(), e.getKey());
                // Entity example =
              } else {
                c.setProperty(f.name, firstElement);
              }
              createBindings(c, m, bnd,
                  new Field[] { singleField }, facade);

              int open = dlg.open();
              if (open == Dialog.OK) {
                Object value = bnd.getBinding(f.name)
                    .getValue();
                if (value == null) {
                  value = new NullValue();
                }
                v.addValue(value);
              }
              bnd.dispose();

            }
          }
        });
        manager.add(new Action("Edit selected") {
          {
            setImageDescriptor(AbstractUIPlugin
                .imageDescriptorFromPlugin(Activator.PLUGIN_ID,
                    "/icons/text_edit.gif"));
          }

          public void run() {
            if (f instanceof CGAEField) {
              CGAEField cgf = (CGAEField) f;

              Object[] selected = v.getSelection().toArray();
              if (selected.length == 1) {
                BaseDataFacade fac = new BaseDataFacade(
                    cgf.keyKind, facade.getProject(),
                    facade.isDebug());
                fac.setNamespace(facade.getNamespace());
                DataStoreTableUI dstui = new DataStoreTableUI();
                final Entity sel = (Entity) selected[0];
                ArrayList<Entity> select = new ArrayList();
                select.add(sel);
                fac.determineFields(select);
                dstui.setFacade(fac);
                dstui.open(sel, false, new IUpdateList() {

                  public void update(Entity e) {
                    v.removeValue(sel);
                    v.addValue(e);
                  }
                });
              }
              return;
            } else {
              Object firstElement = v.getSelection()
                  .getFirstElement();
              Binding bnd = new Binding(firstElement);
              bnd.setName("Edit");
              CompositeEditor m = new CompositeEditor(bnd);
              TitledDialog dlg = new TitledDialog(m);
              GAEField singleField = fm.getSingleField();
              ApiProxy.setEnvironmentForCurrentThread(new FakeEnvironment(
                  e.getAppId()));
              Entity c = new Entity("A");
              if (firstElement instanceof NullValue) {
                c.setProperty(f.name, null);
              } else {
                c.setProperty(f.name, firstElement);
              }
              createBindings(c, m, bnd,
                  new Field[] { singleField }, facade);
              int open = dlg.open();
              if (open == Dialog.OK) {
                v.removeValue(firstElement);
                Object value = bnd.getBinding(f.name)
                    .getValue();
                if (value == null) {
                  value = new NullValue();
                }
                v.addValue(value);
              }
              bnd.dispose();
            }
          }
        });
        manager.add(new Action("Delete selected") {
          {
            setImageDescriptor(AbstractUIPlugin
                .imageDescriptorFromPlugin(Activator.PLUGIN_ID,
                    "/icons/delete.gif"));
          }

          @SuppressWarnings("unchecked")
          public void run() {
            final List selected = v.getSelection().toList();

            if (f instanceof CGAEField) {
              final CGAEField cgf = (CGAEField) f;
              BaseDataFacade fac = new BaseDataFacade(
                  cgf.keyKind, facade.getProject(), facade
                      .isDebug());
              fac.setNamespace(facade.getNamespace());
              fac.delete(selected.toArray(new Entity[selected
                  .size()]), new OperationCallback() {

                public void passed(Object object) {
                  Collection coll = (Collection) ((HashMap) facade
                      .getChildren()
                      .get(cgf.getKeyKind())).get(e
                      .getKey());
                  coll.removeAll(selected);
                  facade.updateChildren(e);
                  v.removeValues(selected);
                }

                public void failed(Exception exception) {
                  return;
                }
              });
              // facade.updateChildren(e);
            } else {
              v.removeValues(selected);
            }
          }
        });
        return manager.createControl(conComposite);
      }

    });

    v.setValueAsSelection(false);
    Binding binding = bnd.getBinding(f.name);
    binding.setReadOnly(false);
    Object property = null;
    if (f instanceof CGAEField) {

      HashMap hashMap = (HashMap) facade.getChildren().get(
          ((CGAEField) f).keyKind);
      if (hashMap != null) {
        Collection col = (Collection) (hashMap).get(e.getKey());
        if (col != null) {
          property = new ArrayList<Object>();
          for (Iterator i = col.iterator(); i.hasNext();) {
            Entity ent = (Entity) i.next();
            ((ArrayList<Object>) property).add(ent);
            v.setLabelProvider(new LabelProvider() {

              public String getText(Object element) {
                Entity e = (Entity) element;
                String res = "";

                String[] details = ((CGAEField) f)
                    .getKeyKindDetails();
                if (details != null && details.length != 0) {
                  StringBuilder sb = new StringBuilder();
                  int ch = 0;
                  for (String det : details) {
                    Object prop = e.getProperty(det);
                    String toStr = ((CGAEField) f)
                        .getObjectText2(e, prop);
                    sb.append(toStr);
                    if (ch != details.length - 1) {
                      sb.append(":");
                    }
                    ch++;
                  }
                  res = sb.toString();
                } else {
                  res = e.getKey().toString();
                }
                return res;
              }
            });
          }
        } else {
          property = new NullValue();// "<empty>";
        }
      } else {
        property = new NullValue();// "<empty>";
      }

    } else if (f instanceof PGAEField) {
      property = e.getProperty(f.name);
    } else {
      property = e.getProperty(f.name);
    }
    if (property instanceof Collection<?>) {
      Collection c = (Collection) property;
      boolean remove = c.remove(null);
      if (remove) {
        c.add(new NullValue());
      }
    }
    binding.setValue(property, null);
    v.setBinding(binding);
    v.setLayoutData(GridDataFactory.fillDefaults().grab(true, true)
        .create());
    m.add(v);
    text.add(m);
    return binding;
  }

  private static void createKey(CompositeEditor editor,
      final Binding binding, final Field f) {
    binding.setFactory(new IFactory() {

      public Object getValue(Object context) {
        GAEField d = (GAEField) f;

        if (d.keyKind == null) {
          final String[] kinds = new String[1];
          kindCheck(kinds);
          if (kinds[0] == null || kinds[0].length() == 0) {
            return null;
          }
          d.keyKind = kinds[0];
        }

        final CompositeEditor rd = new CompositeEditor();
        rd.setLayout(new GridLayout());
        rd.setBinding(binding);
        binding.setAutoCommit(false);
        final TitledDialog titledDialog = new TitledDialog(rd) {

          protected void okPressed() {
            binding.commit();
            super.okPressed();
          }

        };
        binding.setDescription("Select entity to refer on");
        UniversalUIElement<Composite> element = new UniversalUIElement<Composite>(
            Composite.class, SWT.BORDER) {

          protected Composite createControl(Composite conComposite) {
            Composite c = new Composite(conComposite, SWT.NONE);

            DataStoreTableUI ui = new DataStoreTableUI() {

              public void open(Object selection) {
                binding.commit();
                titledDialog.close();
              }

            };
            c.setLayout(new GridLayout(1, false));
            ToolBarManager man = new ToolBarManager();
            Action action = ui.createActions(man, false);
            man.createControl(c);

            GAEField d = (GAEField) f;
            if (d.keyKind == null) {
              final String[] kinds = new String[1];
              Binding bnd = new Binding("");
              final Binding kind = bnd.getBinding("Kind");

              CompositeEditor bb = new CompositeEditor(bnd);

              final InputElementDialog dlg = new InputElementDialog(
                  bb);

              bb.setLayoutManager(new OneElementOnLineLayouter());
              CompositeEditor pe = new CompositeEditor();
              pe.setLayout(new FillLayout());
              OneLineTextElement<String> keyKind = new OneLineTextElement<String>(
                  kind);
              pe.add(keyKind);
              bb.add(pe);

              CompositeEditor buttons = new CompositeEditor();
              buttons.setLayoutManager(new HorizontalLayouter());

              ButtonSelector ok = new ButtonSelector();
              ok.setText("submit");
              ok.setValue(new Runnable() {

                public void run() {
                  kinds[0] = (String) kind.getValue();
                  dlg.close();
                }
              });
              buttons.add(ok);
              bb.add(buttons);
              DisposeBindingListener
                  .linkBindingLifeCycle(bnd, bb);
              dlg.open();
              d.keyKind = kinds[0];
            }
            BaseViewer bv = new BaseViewer(action, ui, d
                .getProject(), d.keyKind) {

              public void selectionChanged(
                  IStructuredSelection selection) {
                if (!selection.isEmpty()) {
                  Entity firstElement = (Entity) selection
                      .getFirstElement();
                  rd.getBinding().setValue(
                      firstElement.getKey(), null);
                }
              }

            };

            bv.createControl(c);
            BaseDataFacade createFacade = d.createFacade(d.keyKind,
                bv.getRefreshCallback(), bv.getSingleCallback());
            String namespace = d.getFacade().getNamespace();
            createFacade.setNamespace(namespace);
            ui.setFacade(createFacade);
            bv.getControl().setLayoutData(
                GridDataFactory.fillDefaults().grab(true, true)
                    .create());
            bv.kind = createFacade.getKind();
            bv.setDataFacade(createFacade);
            return c;
          }

        };
        element.getLayoutHints().setGrabHorizontal(true);
        element.getLayoutHints().setGrabVertical(true);
        rd.add(element);
        rd.getLayoutHints().setGrabHorizontal(true);
        rd.getLayoutHints().setGrabVertical(true);

        titledDialog.setResizable(true);
        titledDialog.open();
        return null;
      }

      public void kindCheck(final String[] kinds) {
        Binding bnd = new Binding("Parameters");
        final Binding kind = bnd.getBinding("Kind");
        kind.addValidator(new ValidatorAdapter<String>() {

          public CodeAndMessage isValid(IBinding context,
              String object) {
            if (object == null || object.length() == 0) {
              return CodeAndMessage
                  .errorMessage("Kind should not be empty");
            }
            return CodeAndMessage.OK_MESSAGE;
          }
        });
        kind.setReadOnly(false);
        kind.setName("Kind for key:");
        CompositeEditor bb = new CompositeEditor(bnd);

        final TitledDialog dlg = new TitledDialog(bb) {

          protected void okPressed() {
            kinds[0] = (String) kind.getValue();
            super.okPressed();
          }
          //
          // protected void cancelPressed() {
          // close();
          // kindCheck(kinds);
          // }
        };

        bb.setLayoutManager(new OneElementOnLineLayouter());
        CompositeEditor pe = new CompositeEditor();
        pe.setLayout(new FillLayout());
        OneLineTextElement<String> keyKind = new OneLineTextElement<String>(
            kind);
        pe.add(keyKind);
        bb.add(pe);
        dlg.create();

        dlg.setMessage("Please specify kind for key.");

        dlg.open();
      }

      public String getName() {
        return "Choose";
      }

      public String getDescription() {
        return "";
      }
    });
    binding.setAdapter(ILabelLookup.class, new KeyParser());
    OneLineTextElement<Object> m = new OneLineTextElement<Object>(binding) {

      protected void onValue(Object value) {
        commitToBinding(value);
      }

      protected void doCommit(final IBinding binding2) {

        super.doCommit(binding2);
      }

    };
    m.setReadOnly(false);
    editor.add(m);
  }

  private static void createText(CompositeEditor editor, Container owner,
      final Binding binding, boolean needNullButton) {
    Container gr = new Container();
    gr.setText(binding.getName());
    gr.setCaption(binding.getName());
    gr.setLayoutManager(new OneElementOnLineLayouter());

    // CompositeEditor ce = new CompositeEditor();
    // ce.setLayoutManager(new OneElementOnLineLayouter());

    final ViewerTextElement tm = new ViewerTextElement() {
      protected void setValue(IBinding binding, Object value) {
        if (value instanceof Text) {
          Text c = (Text) value;
          super.setValue(binding, c.getValue());
        }
      }

      protected void doCommit(final IBinding binding2) {
        commitToBinding(new Text(getText()));
      }

    };
    tm.setWrapText(false);
    // ce.add(tm);
    gr.add(tm);

    if (needNullButton) {
      addIsNullButtonSelector(binding, gr, null);
    }

    owner.add(gr);
    gr.getLayoutHints().setGrabVertical(true);
    gr.getLayoutHints().setMinimumSize(new Point(200, 200));
    tm.setBinding(binding);
  }

  private static void createRating(CompositeEditor editor,
      final Binding binding) {
    SpinnerEditor ed = new SpinnerEditor() {

      protected void configure(IBinding binding, Spinner control) {
        control.setMinimum(0);
        control.setMaximum(100);
        Rating c = (Rating) binding.getValue();
        if (c != null) {
          initValue(control, c.getRating());
        }
      }

      protected void commitToBinding(Object newValue) {
        Number m = (Number) newValue;
        super.commitToBinding(new Rating(m.intValue()));
      }
    };

    ed.setBinding(binding);
    editor.add(ed);
  }

  private static void createBlob(CompositeEditor editor, Class<?> type,
      final Binding binding, final IJavaProject project) {
    final boolean isShort = type == ShortBlob.class;

    binding.setFactory(new IFactory() {

      public Object getValue(Object context) {
        Display current = Display.getCurrent();
        FileDialog fileDialog = new FileDialog(
            current.getActiveShell(), SWT.OPEN);
        fileDialog.setText("Select file");
        String open = fileDialog.open();
        if (open != null) {
          try {
            FileInputStream fs = new FileInputStream(open);
            BufferedInputStream bs = new BufferedInputStream(fs);
            ByteArrayOutputStream s = new ByteArrayOutputStream();
            while (bs.available() >= 0) {
              int k = bs.read();
              if (k == -1) {
                break;
              }
              s.write(k);
            }
            return isShort ? new ShortBlob(s.toByteArray())
                : new Blob(s.toByteArray());
          } catch (IOException e) {
            Activator.log(e);
            return null;
          }
        }
        return null;
      }

      public String getName() {
        return "Set from file";
      }

      public String getDescription() {
        return "";
      }
    });
    OneLineTextElement<Object> m = new OneLineTextElement<Object>(binding) {

      private org.eclipse.swt.widgets.Text txt;

      private Composite newComposite;
      private GridLayout layout;
      private boolean packFlg = false;

      private AbstractBlobVisualizer[] viewers = new AbstractBlobVisualizer[] {
          new ImageBlobVisualizer(),
          new SerializableBlobVisualizer(new IUpdateBlob() {

            public void updateBlob(byte[] data) {
              Blob blob = new Blob(data);
              onValue(blob);
            }

          }, project) };
      private AbstractBlobVisualizer last;

      protected void onValue(Object value) {
        commitToBinding(value);
        initBlobViewer(value);
      }

      public void initBlobViewer(Object value) {
        if (value != null) {
          if (value instanceof Blob) {
            Blob blob = (Blob) value;
            if (last == null || !last.isSupported(blob)) {
              boolean flg = false;
              for (AbstractBlobVisualizer handler : viewers) {
                if (last != null) {
                  last.dispose();
                  last = null;
                }
                if (handler.isSupported(blob)) {
                  last = handler;
                  last.init(newComposite);
                  last.handleBlob(blob);
                  // if (packFlg ) {
                  // newComposite.getShell().pack(true);
                  // } else {
                  // packFlg = true;
                  // }
                  Display.getCurrent().asyncExec(
                      new Runnable() {

                        public void run() {
                          newComposite.getShell()
                              .pack(true);
                          newComposite.getShell()
                              .layout(true, true);
                        }
                      });

                  // newComposite.getShell().layout(true,
                  // true);
                  flg = true;
                  break;

                }
              }
              if (!flg) {
                // if (packFlg) {
                // newComposite.getShell().pack(true);
                // } else {
                // packFlg = true;
                // }
                // newComposite.getShell().layout(true, true);
                Display.getCurrent().asyncExec(new Runnable() {

                  public void run() {
                    newComposite.getShell().pack(true);
                    newComposite.getShell().layout(true,
                        true);
                  }
                });
              }
            } else {
              last.handleBlob(blob);
              // newComposite.getShell().pack(true);
              // newComposite.getShell().layout(true, true);
              Display.getCurrent().asyncExec(new Runnable() {

                public void run() {
                  newComposite.getShell().pack(true);
                  newComposite.getShell().layout(true, true);
                }
              });

            }
          }
        }
      }

      protected void doCommit(final IBinding binding2) {
        // commitToBinding(this.getgetValue());
      }

      protected org.eclipse.swt.widgets.Text internalCreateControl(
          Composite conComposite) {
        newComposite = new Composite(conComposite, SWT.INHERIT_FORCE);
        layout = new GridLayout(1, false);
        layout.horizontalSpacing = 0;
        layout.verticalSpacing = 2;
        layout.marginWidth = 0;
        layout.marginHeight = 0;
        newComposite.setLayout(layout);
        txt = super.internalCreateControl(newComposite);
        Object value = binding.getValue();
        if (value instanceof Blob) {
          initBlobViewer(value);
        }

        // txt.setVisible(false);

        return txt;
      }

      protected void installSelector(Composite conComposite) {
        super.installSelector(conComposite);
        Button button = new Button(conComposite, SWT.NONE);
        button.setText("Store to File");
        this.registerPart(button);
        button.addListener(SWT.Selection, new Listener() {

          public void handleEvent(Event event) {
            FileDialog dlg = new FileDialog(Display.getCurrent()
                .getActiveShell(), SWT.SAVE);
            dlg.setText("Export blob to file:");
            String open = dlg.open();
            if (open != null) {
              try {
                FileOutputStream fs = new FileOutputStream(open);
                try {
                  Object value = binding.getValue();
                  if (value instanceof Blob) {
                    Blob b = (Blob) value;
                    fs.write(b.getBytes());
                  }
                  if (value instanceof ShortBlob) {
                    ShortBlob b = (ShortBlob) value;
                    fs.write(b.getBytes());
                  }
                } finally {
                  fs.close();
                }

              } catch (IOException e) {
                MessageDialog.openError(Display.getCurrent()
                    .getActiveShell(), "Error", e
                    .getMessage());
              }
            }
            binding.getValue();
          }
        });
      }

    };
    m.setReadOnly(true);
    editor.add(m);
  }

  private static void createUser(CompositeEditor editor, final Binding binding) {
    CompositeEditor tr = new CompositeEditor(binding, Container.GROUP);

    tr.setCaption(binding.getName());
    tr.setLayoutManager(new HorizontalLayouter());

    tr.setLayoutManager(new HorizontalLayouter());
    if (binding.getValue() == null) {
      binding.setValue(new User("", "", ""), null);// setValueSilent
    }
    binding.addBindingChangeListener(new IBindingChangeListener<Object>() {

      public void valueChanged(ISetDelta<Object> valueElements) {
        // TODO Auto-generated method stub

      }

      public void enablementChanged(boolean isEnabled) {
        Collection<String> childs = binding.getKnownChilds();
        for (String ch : childs) {
          Binding b = binding.getBinding(ch);
          b.setReadOnly(!isEnabled);
        }
      }

      public void changed() {
        // TODO Auto-generated method stub

      }
    });
    final Binding binding2 = new Binding(binding, "userId"); // binding.getBinding("userId");
    binding2.setName("userId");
    binding2.setAutoCommit(true);

    tr.add(new OneLineTextElement<String>(binding2));
    final Binding binding3 = new Binding(binding, "email"); // binding.getBinding("email");
    binding3.setName("email");
    binding3.setAutoCommit(true);

    tr.add(new OneLineTextElement<String>(binding3));
    final Binding binding4 = new Binding(binding, "authDomain"); // binding.getBinding("authDomain");
    binding4.setName("authDomain");
    binding4.setAutoCommit(true);

    tr.add(new OneLineTextElement<String>(binding4));
    // binding.setReadOnly(false);
    editor.add(tr);
  }

  private static void createGeoPt(CompositeEditor editor,
      final Binding binding) {
    CompositeEditor tr = new CompositeEditor(binding, Container.GROUP);

    tr.setCaption(binding.getName());
    tr.setLayoutManager(new HorizontalLayouter());
    if (binding.getValue() == null) {
      binding.setValue(new GeoPt(0f, 0f), null); // Silent
    }

    binding.addBindingChangeListener(new IBindingChangeListener<Object>() {

      public void valueChanged(ISetDelta<Object> valueElements) {
        // TODO Auto-generated method stub
        return;
      }

      public void enablementChanged(boolean isEnabled) {
        Collection<String> childs = binding.getKnownChilds();
        for (String ch : childs) {
          Binding b = binding.getBinding(ch);
          b.setReadOnly(!isEnabled);
        }
      }

      public void changed() {
        // TODO Auto-generated method stub
        return;
      }
    });

    final Binding binding2 = new Binding(binding, "Latitude");
    final Binding binding3 = new Binding(binding, "Longitude");

    // binding2.refresh();
    // binding3.refresh();
    IBindingChangeListener<Object> l = new IBindingChangeListener<Object>() {

      public void changed() {

      }

      public void enablementChanged(boolean isEnabled) {

      }

      public void valueChanged(ISetDelta<Object> valueElements) {
        Object val1 = binding2.getValue();
        Object val2 = binding3.getValue();

        if (val1 instanceof GeoPt) {
          val1 = ((GeoPt) val1).getLatitude();
        }

        if (val2 instanceof GeoPt) {
          val2 = ((GeoPt) val2).getLongitude();
        }

        if (val1 instanceof Number && val2 instanceof Number) {
          Number value = (Number) val1;
          Number value2 = (Number) val2;
          GeoPt pt = new GeoPt((value.floatValue()/* / 1000000 */),
              value2.floatValue()/* / 1000000 */);

          binding.setValueSilent(pt);
        }
      }
    };

    binding2.setAutoCommit(true);
    binding2.addBindingChangeListener(l);
    binding2.setReadOnly(false);
    binding2.setName("Latitude");
    // binding2.setValue(vv.getLatitude(),null);
    SpinnerEditor sp2 = new SpinnerEditor() {
      protected void configure(IBinding binding, Spinner control) {
        // super.configure(binding,control);
        control.setMinimum(-90000000);
        control.setMaximum(90000000);
        control.setDigits(6);
        this.scale = 1000000;
        isFloat = true;
        control.setIncrement(1);
        Object value = binding.getValue();
        if (value == null) {
          value = 0f;
        }

        initValue(control, ((Float) value)/* * 1000000 */);

      }
    };
    sp2.setBinding(binding2);

    tr.add(sp2);
    binding3.setName("Longitude");
    // binding3.setValue(vv.getLongitude(),null);
    binding3.setReadOnly(false);
    binding3.setRequired(true);
    binding3.setAutoCommit(true);
    binding3.addBindingChangeListener(l);

    SpinnerEditor sp = new SpinnerEditor() {
      protected void configure(IBinding binding, Spinner control) {
        control.setMinimum(-180000000);
        control.setMaximum(180000000);
        control.setDigits(6);
        control.setIncrement(1);
        isFloat = true;
        // super.configure(binding3, control);
        this.scale = 1000000;
        Object value = binding.getValue();
        if (value == null) {
          value = 0f;
        }
        initValue(control, (Float) value/* * 1000000 */);

      }
    };
    sp.setBinding(binding3);
    tr.add(sp);
    editor.add(tr);
  }

  private static void createIMHandle(CompositeEditor editor,
      final Binding binding) {
    CompositeEditor tr = new CompositeEditor(binding, Container.GROUP);

    tr.setCaption(binding.getName());
    tr.setLayoutManager(new HorizontalLayouter());
    final Binding binding2 = binding.getBinding("Address");
    final Binding binding3 = binding.getBinding("Protocol");
    IBindingChangeListener<Object> l = new IBindingChangeListener<Object>() {

      public void changed() {

      }

      public void enablementChanged(boolean isEnabled) {

      }

      public void valueChanged(ISetDelta<Object> valueElements) {
        IMHandle value = new IMHandle((Scheme) binding3.getValue(),
            (String) binding2.getValue());
        binding.setValueSilent(value);
      }
    };

    binding2.setAutoCommit(true);
    binding2.addBindingChangeListener(l);
    binding2.setReadOnly(false);
    binding2.setName("Address");
    tr.add(new OneLineTextElement<Object>(binding2));
    binding3.setName("Protocol");
    binding3.setReadOnly(false);
    binding3.setRequired(true);
    binding3.setAutoCommit(true);
    Object value = binding3.getValue();
    binding3.setValue(
        Scheme.valueOf((String) (value != null ? value : "xmpp")), null);
    binding3.addBindingChangeListener(l);
    Scheme[] values = IMHandle.Scheme.values();
    binding3.setRealm(new Realm<IMHandle.Scheme>(values));
    tr.add(new ComboEnumeratedValueSelector<Object>(binding3));
    editor.add(tr);
  }

  private static void createDate(CompositeEditor editor, final Binding binding) {
    DateTimeEditor ed = new DateTimeEditor();
    ed.setStyle(SWT.DATE | SWT.TIME);
    ed.setBinding(binding);
    Object vv = ed.getValue();

    if (vv instanceof Date) {
      binding.setValue(vv, null);
    }

    editor.add(ed);
  }

  private static void createPhoneNumber(CompositeEditor editor,
      final Binding binding) {
    OneLineTextElement<String> t = new OneLineTextElement<String>() {
      protected void setValue(IBinding binding, Object value) {
        if (value instanceof PhoneNumber) {
          PhoneNumber c = (PhoneNumber) value;
          super.setValue(binding, c.getNumber());
        }
      }

      protected void doCommit(final IBinding binding2) {
        commitToBinding(new PhoneNumber(getText()));
      }
    };
    t.setContentAssistLabelProvider(new LabelProvider() {

      public String getText(Object element) {
        if (element == null) {
          return "";
        }
        if (element instanceof PhoneNumber) {
          PhoneNumber m = (PhoneNumber) element;
          return m.getNumber();
        }
        return element.toString();
      }

    });
    t.setBinding(binding);
    editor.add(t);
  }

  private static void createPostalAddress(CompositeEditor editor,
      final Binding binding) {
    OneLineTextElement<String> t = new OneLineTextElement<String>() {
      protected void setValue(IBinding binding, Object value) {
        if (value instanceof PostalAddress) {
          PostalAddress c = (PostalAddress) value;
          super.setValue(binding, c.getAddress());
        }
      }

      protected void doCommit(final IBinding binding2) {
        commitToBinding(new PostalAddress(getText()));
      }
    };
    t.setContentAssistLabelProvider(new LabelProvider() {

      public String getText(Object element) {
        if (element == null) {
          return "";
        }
        if (element instanceof PostalAddress) {
          PostalAddress m = (PostalAddress) element;
          return m.getAddress();
        }
        return element.toString();
      }

    });
    t.setBinding(binding);
    editor.add(t);
  }

  private static void createEmail(CompositeEditor editor,
      final Binding binding) {
    OneLineTextElement<String> t = new OneLineTextElement<String>() {
      protected void setValue(IBinding binding, Object value) {
        if (value instanceof Email) {
          Email c = (Email) value;
          super.setValue(binding, c.getEmail());
        }
      }

      protected void doCommit(final IBinding binding2) {
        commitToBinding(new Email(getText()));
      }
    };
    t.setContentAssistLabelProvider(new LabelProvider() {

      public String getText(Object element) {
        if (element == null) {
          return "";
        }
        if (element instanceof Email) {
          Email m = (Email) element;
          return m.getEmail();
        }
        return element.toString();
      }

    });
    t.setBinding(binding);
    editor.add(t);
  }

  private static void createCategory(CompositeEditor editor,
      final Binding binding) {
    OneLineTextElement<String> t = new OneLineTextElement<String>() {
      protected void setValue(IBinding binding, Object value) {
        if (value instanceof Category) {
          Category c = (Category) value;
          super.setValue(binding, c.getCategory());
        }
      }

      protected void doCommit(final IBinding binding2) {
        commitToBinding(new Category(getText()));
      }
    };
    t.setContentAssistLabelProvider(new LabelProvider() {

      public String getText(Object element) {
        if (element == null) {
          return "";
        }
        if (element instanceof Category) {
          Category m = (Category) element;
          return m.getCategory();
        }
        return element.toString();
      }

    });
    t.setBinding(binding);
    editor.add(t);
  }

  private static void createLink(CompositeEditor editor, final Binding binding) {
    OneLineTextElement<String> t = new OneLineTextElement<String>() {
      protected void setValue(IBinding binding, Object value) {
        if (value instanceof Link) {
          Link c = (Link) value;
          super.setValue(binding, c.getValue());
        }
      }

      protected void doCommit(final IBinding binding2) {
        commitToBinding(new Link(getText()));
      }
    };
    t.setContentAssistLabelProvider(new LabelProvider() {

      public String getText(Object element) {
        if (element == null) {
          return "";
        }
        if (element instanceof Link) {
          Link m = (Link) element;
          return m.getValue();
        }
        return element.toString();
      }

    });
    t.setBinding(binding);
    editor.add(t);
  }

  public interface IUpdateList {
    void update(Entity e);
  }

  private static void addIsNullButtonSelector(final IBinding bnd,
      Container editor, String rId) {
    ButtonSelector bs = new ButtonSelector(SWT.CHECK);
    bs.setText("is null");
    bs.addListener(SWT.Selection, new SWTEventListener() {

      public void handleEvent(AbstractUIElement element, Event event) {
        Binding b = (Binding) bnd;
        boolean readOnly = b.isReadOnly();
        b.setReadOnly(!readOnly);
        if (b instanceof EditingBinding) {
          ((EditingBinding) b).setResetToNull(!readOnly);
        }
        return;
      }
    });

    if (bnd instanceof EditingBinding) {
      EditingBinding ebd = (EditingBinding) bnd;
      Entity e = ebd.getE();
      String id = bnd.getId();
      if (e.hasProperty(id) && e.getProperty(id) == null) {
        Binding b = (Binding) bnd;
        ebd.setResetToNull(true);
        b.setReadOnly(true);
        bs.setValue(true);
      }
    }

    String ids = bnd.getId();
    if (rId != null) {
      ids = rId;
    }

    // editor.setBordered(true);
    editor.setId(ids);
    editor.add(bs);
  }

  private static void addNotIndexableButton(final IBinding bnd,
      Container editor, Field f) {
    Class fType = f.getType();

    if (fType == Blob.class || fType == Text.class) {
      return;
    }

    ButtonSelector bsNotIndexable = new ButtonSelector(SWT.CHECK);
    bsNotIndexable.setText("not indexed");
    bsNotIndexable.addListener(SWT.Selection, new SWTEventListener() {

      public void handleEvent(AbstractUIElement element, Event event) {
        Binding b = (Binding) bnd;
        if (b instanceof EditingBinding) {
          boolean flg = ((EditingBinding) b).isNotIndexable();
          ((EditingBinding) b).setNotIndexable(!flg);
        }
        return;
      }
    });
    if (bnd instanceof EditingBinding) {
      EditingBinding ebd = (EditingBinding) bnd;
      Entity e = ebd.getE();
      String id = bnd.getId();
      if (e.isUnindexedProperty(id)) {
        if (bnd instanceof EditingBinding) {
          ((EditingBinding) bnd).setNotIndexable(true);
        }
        bsNotIndexable.setValue(true);
      }
    }
    editor.add(bsNotIndexable);
  }

  private static Map<String, Collection<Field>> sortFields(Field[] fields,
      BaseDataFacade facade) {

    HashMap<String, FieldInfo> info = facade.getEmbeddedFields();
    HashMap<String, Collection<Field>> res = new HashMap();
    Set<String> set = info.keySet();
    for (Field f : fields) {
      String embK = facade.getKind();

      String fName = f.name;
      if (set.contains(fName)) {
        FieldInfo fi = info.get(fName);
        embK = fi.getEnclosingType();
      }

      Collection<Field> tmp = null;
      if (res.containsKey(embK)) {
        tmp = res.get(embK);
      } else {
        tmp = new ArrayList<Field>();
        res.put(embK, tmp);
      }
      tmp.add(f);

    }
    return res;
  }

}
TOP

Related Classes of com.onpositive.gae.baseviewer.EditorUtility$IUpdateList

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.