/**
  * Constructor.
  *
  * @param source The EObject (Property) which the ownership is being edited
  * @param domain The Editing Domain on which the commands will be executed
  */
 public OwnerObservableValue(EObject source, EditingDomain domain) {
   this.memberEnd = (Property) source;
   this.domain = domain;
   navigableEndsObservableList =
       EMFProperties.list(UMLPackage.eINSTANCE.getAssociation_NavigableOwnedEnd())
           .observe(memberEnd.getAssociation());
   navigableEndsObservableList.addChangeListener(this);
 }
  protected void init() {
    prefs = ConfigurationScope.INSTANCE.getNode("org.bbaw.bts.ui.corpus");
    IEclipsePreferences defaultpref = DefaultScope.INSTANCE.getNode("org.bbaw.bts.ui.corpus");

    default_visibility = prefs.get(BTSCorpusConstants.PREF_LEMMA_DEFAULT_VISIBILITY, null);
    default_reviewState = prefs.get(BTSCorpusConstants.PREF_LEMMA_DEFAULT_REVIEWSTATE, null);

    object = BtsCorpusModelFactory.eINSTANCE.createBTSTCObject();
    object.setVisibility(default_visibility);
    object.setRevisionState(default_reviewState);

    DataBindingContext bindingContext = new DataBindingContext();

    // visibility
    EMFUpdateValueStrategy targetToModel_vis = new EMFUpdateValueStrategy();
    targetToModel_vis.setConverter(new BTSConfigItemToStringConverter());
    EMFUpdateValueStrategy modelToTarget_vis = new EMFUpdateValueStrategy();
    modelToTarget_vis.setConverter(new BTSStringToConfigItemConverter(visibility_viewer));
    IObservableValue target_vis_viewer =
        ViewersObservables.observeSingleSelection(visibility_viewer);
    Binding binding_vis =
        bindingContext.bindValue(
            target_vis_viewer,
            EMFProperties.value(BtsmodelPackage.Literals.ADMINISTRATIV_DATA_OBJECT__VISIBILITY)
                .observe(object),
            targetToModel_vis,
            modelToTarget_vis);

    // review status
    EMFUpdateValueStrategy targetToModel_rev = new EMFUpdateValueStrategy();
    targetToModel_rev.setConverter(new BTSConfigItemToStringConverter());
    EMFUpdateValueStrategy modelToTarget_rev = new EMFUpdateValueStrategy();
    modelToTarget_rev.setConverter(new BTSStringToConfigItemConverter(reviewState_viewer));
    IObservableValue target_rev_viewer =
        ViewersObservables.observeSingleSelection(reviewState_viewer);
    Binding binding_rev =
        bindingContext.bindValue(
            target_rev_viewer,
            EMFProperties.value(BtsmodelPackage.Literals.ADMINISTRATIV_DATA_OBJECT__REVISION_STATE)
                .observe(object),
            targetToModel_rev,
            modelToTarget_rev);
    super.initialize();
  }
  @Override
  public void initialize(URL location, ResourceBundle resources) {
    bindingContextsView.setCellFactory(
        new Callback<ListView<MBindingContext>, ListCell<MBindingContext>>() {

          @Override
          public ListCell<MBindingContext> call(ListView<MBindingContext> param) {
            return new BindingCell();
          }
        });

    EMFDataBindingContext dbc = new EMFDataBindingContext();

    {
      IJFXBeanValueProperty uiProp = JFXBeanProperties.value("text");
      IEMFValueProperty mProp =
          EMFProperties.value(ApplicationPackageImpl.Literals.APPLICATION_ELEMENT__ELEMENT_ID);
      dbc.bindValue(uiProp.observe(idField), mProp.observeDetail(master));
    }

    {
      IJFXBeanValueProperty uiProp = JFXBeanProperties.value("selected");
      IEMFValueProperty mProp =
          EMFProperties.value(UiPackageImpl.Literals.UI_ELEMENT__TO_BE_RENDERED);
      dbc.bindValue(uiProp.observe(renderField), mProp.observeDetail(master));
    }

    {
      IJFXBeanValueProperty uiProp = JFXBeanProperties.value("selected");
      IEMFValueProperty mProp = EMFProperties.value(UiPackageImpl.Literals.UI_ELEMENT__VISIBLE);
      dbc.bindValue(uiProp.observe(visibleField), mProp.observeDetail(master));
    }

    {
      IEMFListProperty mProp =
          EMFProperties.list(CommandsPackageImpl.Literals.BINDINGS__BINDING_CONTEXTS);
      IObservableList mList = mProp.observeDetail(master);
      ObservableList<MBindingContext> l = AdapterFactory.adapt(mList);
      bindingContextsView.setItems(l);
    }
  }
  protected DataBindingContext initDataBindings() {
    DataBindingContext bindingContext = new DataBindingContext();
    //
    ObservableListContentProvider listContentProvider = new ObservableListContentProvider();

    IObservableMap observeMap =
        PojoObservables.observeMap(
            listContentProvider.getKnownElements(), SettingNote.class, "name");
    checkboxTableViewer.setLabelProvider(new ObservableMapLabelProvider(observeMap));
    checkboxTableViewer.setContentProvider(listContentProvider);

    //
    IObservableList categoryNotesObserveList =
        EMFProperties.list(StorynotesPackage.Literals.CATEGORY__NOTES).observe(category);
    checkboxTableViewer.setInput(categoryNotesObserveList);
    //
    return bindingContext;
  }
  public List<T> filterDate(List<T> inputRecords, Date startDate, Date endDate) {
    final List<T> objs = new ArrayList<T>();
    if (inputRecords == null || inputRecords.isEmpty()) {
      return objs;
    }
    final Calendar start = startDate == null ? null : new GregorianCalendar();
    if (start != null) {
      start.setTime(startDate);
    }
    final Calendar startC = startDate == null ? null : Calendar.getInstance();
    if (startC != null) {
      startC.set(
          start.get(Calendar.YEAR), start.get(Calendar.MONTH), start.get(Calendar.DAY_OF_MONTH));
    }

    final Calendar end = endDate == null ? null : new GregorianCalendar();
    if (endDate != null) {
      end.setTime(endDate);
    }
    final Calendar endC = endDate == null ? null : Calendar.getInstance();
    if (endC != null) {
      endC.set(end.get(Calendar.YEAR), end.get(Calendar.MONTH), end.get(Calendar.DAY_OF_MONTH));
    }

    for (final T line : inputRecords) {
      final Date testDate = (Date) EMFProperties.value(dateFeature).getValue(line);
      final Calendar test = new GregorianCalendar();
      test.setTime(testDate);
      final Calendar testC = Calendar.getInstance();
      testC.set(test.get(Calendar.YEAR), test.get(Calendar.MONTH), test.get(Calendar.DAY_OF_MONTH));
      if ((startDate == null || !startC.after(testC)) && (endDate == null || !endC.before(testC))) {
        objs.add(line);
      }
    }
    return objs;
  }
public class PerspectiveStackEditor extends AbstractComponentEditor {
  private Composite composite;
  private EMFDataBindingContext context;

  private IListProperty ELEMENT_CONTAINER__CHILDREN =
      EMFProperties.list(UiPackageImpl.Literals.ELEMENT_CONTAINER__CHILDREN);
  private EStackLayout stackLayout;
  private List<Action> actions = new ArrayList<Action>();
  private List<Action> actionsImport = new ArrayList<Action>();

  @Inject @Optional private IProject project;

  @Inject
  public PerspectiveStackEditor() {
    super();
  }

  @Inject Shell shell;

  @PostConstruct
  void init() {
    actions.add(
        new Action(
            Messages.PerspectiveStackEditor_AddPerspective,
            createImageDescriptor(ResourceProvider.IMG_Perspective)) {
          @Override
          public void run() {
            handleAddPerspective();
          }
        });

    // --- import ---
    actionsImport.add(
        new Action(
            Messages.PerspectiveStackEditor_AddPerspective,
            createImageDescriptor(ResourceProvider.IMG_Perspective)) {
          @Override
          public void run() {
            handleImportPerspective();
          }
        });
  }

  @Override
  public Image getImage(Object element, Display display) {
    if (element instanceof MUIElement) {
      MUIElement uiElement = (MUIElement) element;
      if (uiElement.isToBeRendered() && uiElement.isVisible()) {
        return createImage(ResourceProvider.IMG_PerspectiveStack);
      } else {
        return createImage(ResourceProvider.IMG_Tbr_PerspectiveStack);
      }
    }

    return null;
  }

  @Override
  public String getLabel(Object element) {
    return Messages.PerspectiveStackEditor_Label;
  }

  @Override
  public String getDetailLabel(Object element) {
    return null;
  }

  @Override
  public String getDescription(Object element) {
    return Messages.PerspectiveStackEditor_Description;
  }

  @Override
  public Composite doGetEditor(Composite parent, Object object) {
    if (composite == null) {
      context = new EMFDataBindingContext();
      if (getEditor().isModelFragment()) {
        composite = new Composite(parent, SWT.NONE);
        stackLayout = new EStackLayout();
        composite.setLayout(stackLayout);
        createForm(composite, context, getMaster(), false);
        createForm(composite, context, getMaster(), true);
      } else {
        composite = createForm(parent, context, getMaster(), false);
      }
    }

    if (getEditor().isModelFragment()) {
      Control topControl;
      if (Util.isImport((EObject) object)) {
        topControl = composite.getChildren()[1];
      } else {
        topControl = composite.getChildren()[0];
      }

      if (stackLayout.topControl != topControl) {
        stackLayout.topControl = topControl;
        composite.layout(true, true);
      }
    }

    getMaster().setValue(object);
    return composite;
  }

  private Composite createForm(
      Composite parent,
      final EMFDataBindingContext context,
      WritableValue master,
      boolean isImport) {
    CTabFolder folder = new CTabFolder(parent, SWT.BOTTOM);

    CTabItem item = new CTabItem(folder, SWT.NONE);
    item.setText(Messages.ModelTooling_Common_TabDefault);

    parent = createScrollableContainer(folder);
    item.setControl(parent.getParent());

    if (getEditor().isShowXMIId() || getEditor().isLiveModel()) {
      ControlFactory.createXMIId(parent, this);
    }

    IWidgetValueProperty textProp = WidgetProperties.text(SWT.Modify);

    if (isImport) {
      ControlFactory.createFindImport(parent, Messages, this, context);
      folder.setSelection(0);
      return folder;
    }

    ControlFactory.createTextField(
        parent,
        Messages.ModelTooling_Common_Id,
        master,
        context,
        textProp,
        EMFEditProperties.value(
            getEditingDomain(), ApplicationPackageImpl.Literals.APPLICATION_ELEMENT__ELEMENT_ID));
    ControlFactory.createTextField(
        parent,
        Messages.ModelTooling_UIElement_AccessibilityPhrase,
        getMaster(),
        context,
        textProp,
        EMFEditProperties.value(
            getEditingDomain(), UiPackageImpl.Literals.UI_ELEMENT__ACCESSIBILITY_PHRASE));
    ControlFactory.createSelectedElement(
        parent, this, context, Messages.PerspectiveStackEditor_SelectedElement);

    // ------------------------------------------------------------
    {
      Label l = new Label(parent, SWT.NONE);
      l.setText(Messages.PerspectiveStackEditor_Perspectives);
      l.setLayoutData(new GridData(GridData.END, GridData.BEGINNING, false, false));

      final TableViewer viewer = new TableViewer(parent);
      viewer.setContentProvider(new ObservableListContentProvider());
      viewer.setLabelProvider(new ComponentLabelProvider(getEditor(), Messages));
      GridData gd = new GridData(GridData.FILL_BOTH);
      viewer.getControl().setLayoutData(gd);

      IEMFListProperty prop =
          EMFProperties.list(UiPackageImpl.Literals.ELEMENT_CONTAINER__CHILDREN);
      viewer.setInput(prop.observeDetail(getMaster()));

      Composite buttonComp = new Composite(parent, SWT.NONE);
      buttonComp.setLayoutData(new GridData(GridData.FILL, GridData.END, false, false));
      GridLayout gl = new GridLayout();
      gl.marginLeft = 0;
      gl.marginRight = 0;
      gl.marginWidth = 0;
      gl.marginHeight = 0;
      buttonComp.setLayout(gl);

      Button b = new Button(buttonComp, SWT.PUSH | SWT.FLAT);
      b.setText(Messages.ModelTooling_Common_Up);
      b.setImage(createImage(ResourceProvider.IMG_Obj16_arrow_up));
      b.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true, false));
      b.addSelectionListener(
          new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent e) {
              if (!viewer.getSelection().isEmpty()) {
                IStructuredSelection s = (IStructuredSelection) viewer.getSelection();
                if (s.size() == 1) {
                  Object obj = s.getFirstElement();
                  MElementContainer<?> container = (MElementContainer<?>) getMaster().getValue();
                  int idx = container.getChildren().indexOf(obj) - 1;
                  if (idx >= 0) {
                    if (Util.moveElementByIndex(
                        getEditingDomain(), (MUIElement) obj, getEditor().isLiveModel(), idx)) {
                      viewer.setSelection(new StructuredSelection(obj));
                    }
                  }
                }
              }
            }
          });

      b = new Button(buttonComp, SWT.PUSH | SWT.FLAT);
      b.setText(Messages.ModelTooling_Common_Down);
      b.setImage(createImage(ResourceProvider.IMG_Obj16_arrow_down));
      b.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true, false));
      b.addSelectionListener(
          new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent e) {
              if (!viewer.getSelection().isEmpty()) {
                IStructuredSelection s = (IStructuredSelection) viewer.getSelection();
                if (s.size() == 1) {
                  Object obj = s.getFirstElement();
                  MElementContainer<?> container = (MElementContainer<?>) getMaster().getValue();
                  int idx = container.getChildren().indexOf(obj) + 1;
                  if (idx < container.getChildren().size()) {
                    if (Util.moveElementByIndex(
                        getEditingDomain(), (MUIElement) obj, getEditor().isLiveModel(), idx)) {
                      viewer.setSelection(new StructuredSelection(obj));
                    }
                  }
                }
              }
            }
          });

      b = new Button(buttonComp, SWT.PUSH | SWT.FLAT);
      b.setImage(createImage(ResourceProvider.IMG_Obj16_table_add));
      b.setText(Messages.ModelTooling_Common_AddEllipsis);
      b.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true, false));
      b.addSelectionListener(
          new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent e) {
              handleAddPerspective();
            }
          });

      b = new Button(buttonComp, SWT.PUSH | SWT.FLAT);
      b.setText(Messages.ModelTooling_Common_Remove);
      b.setImage(createImage(ResourceProvider.IMG_Obj16_table_delete));
      b.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true, false));
      b.addSelectionListener(
          new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent e) {
              if (!viewer.getSelection().isEmpty()) {
                List<?> elements = ((IStructuredSelection) viewer.getSelection()).toList();

                Command cmd =
                    RemoveCommand.create(
                        getEditingDomain(),
                        getMaster().getValue(),
                        UiPackageImpl.Literals.ELEMENT_CONTAINER__CHILDREN,
                        elements);
                if (cmd.canExecute()) {
                  getEditingDomain().getCommandStack().execute(cmd);
                }
              }
            }
          });
    }

    ControlFactory.createCheckBox(
        parent,
        Messages.ModelTooling_UIElement_ToBeRendered,
        getMaster(),
        context,
        WidgetProperties.selection(),
        EMFEditProperties.value(
            getEditingDomain(), UiPackageImpl.Literals.UI_ELEMENT__TO_BE_RENDERED));
    ControlFactory.createCheckBox(
        parent,
        Messages.ModelTooling_UIElement_Visible,
        getMaster(),
        context,
        WidgetProperties.selection(),
        EMFEditProperties.value(getEditingDomain(), UiPackageImpl.Literals.UI_ELEMENT__VISIBLE));

    item = new CTabItem(folder, SWT.NONE);
    item.setText(Messages.ModelTooling_Common_TabSupplementary);

    parent = createScrollableContainer(folder);
    item.setControl(parent.getParent());

    ControlFactory.createStringListWidget(
        parent,
        Messages,
        this,
        Messages.CategoryEditor_Tags,
        ApplicationPackageImpl.Literals.APPLICATION_ELEMENT__TAGS,
        VERTICAL_LIST_WIDGET_INDENT);
    ControlFactory.createMapProperties(
        parent,
        Messages,
        this,
        Messages.ModelTooling_Contribution_PersistedState,
        ApplicationPackageImpl.Literals.APPLICATION_ELEMENT__PERSISTED_STATE,
        VERTICAL_LIST_WIDGET_INDENT);

    if (project == null) {
      createUITreeInspection(folder);
    }

    folder.setSelection(0);

    return folder;
  }

  private void createUITreeInspection(CTabFolder folder) {
    CTabItem item = new CTabItem(folder, SWT.NONE);
    item.setText(Messages.ModelTooling_Common_RuntimeWidgetTree);
    Composite container = new Composite(folder, SWT.NONE);
    container.setLayout(new GridLayout());
    item.setControl(container);

    UIViewer objectViewer = new UIViewer();
    TreeViewer viewer =
        objectViewer.createViewer(
            container,
            UiPackageImpl.Literals.UI_ELEMENT__WIDGET,
            getMaster(),
            resourcePool,
            Messages);
    viewer.getControl().setLayoutData(new GridData(GridData.FILL_BOTH));
  }

  @Override
  public IObservableList getChildList(Object element) {
    return ELEMENT_CONTAINER__CHILDREN.observe(element);
  }

  @Override
  public FeaturePath[] getLabelProperties() {
    return new FeaturePath[] {
      FeaturePath.fromList(UiPackageImpl.Literals.UI_ELEMENT__TO_BE_RENDERED)
    };
  }

  protected void handleAddPerspective() {
    MPerspective eObject = MAdvancedFactory.INSTANCE.createPerspective();
    addToModel(eObject);
  }

  protected void handleImportPerspective() {
    ModelImportWizard wizard = new ModelImportWizard(MPerspective.class, this);
    WizardDialog wizardDialog = new WizardDialog(shell, wizard);
    if (wizardDialog.open() == Window.OK) {
      MPerspective[] elements = (MPerspective[]) wizard.getElements(MPerspective.class);
      for (MPerspective category : elements) {
        addToModel(category);
      }
    }
  }

  private void addToModel(MPerspective perspective) {
    setElementId(perspective);
    Command cmd =
        AddCommand.create(
            getEditingDomain(),
            getMaster().getValue(),
            UiPackageImpl.Literals.ELEMENT_CONTAINER__CHILDREN,
            perspective);
    if (cmd.canExecute()) {
      getEditingDomain().getCommandStack().execute(cmd);
      getEditor().setSelection(perspective);
    }
  }

  @Override
  public List<Action> getActions(Object element) {
    ArrayList<Action> l = new ArrayList<Action>(super.getActions(element));
    l.addAll(actions);
    return l;
  }

  @Override
  public List<Action> getActionsImport(Object element) {
    ArrayList<Action> l = new ArrayList<Action>(super.getActionsImport(element));
    l.addAll(actionsImport);
    return l;
  }
}
  private Composite createForm(
      Composite parent,
      final EMFDataBindingContext context,
      WritableValue master,
      boolean isImport) {
    CTabFolder folder = new CTabFolder(parent, SWT.BOTTOM);

    CTabItem item = new CTabItem(folder, SWT.NONE);
    item.setText(Messages.ModelTooling_Common_TabDefault);

    parent = createScrollableContainer(folder);
    item.setControl(parent.getParent());

    if (getEditor().isShowXMIId() || getEditor().isLiveModel()) {
      ControlFactory.createXMIId(parent, this);
    }

    IWidgetValueProperty textProp = WidgetProperties.text(SWT.Modify);

    if (isImport) {
      ControlFactory.createFindImport(parent, Messages, this, context);
      folder.setSelection(0);
      return folder;
    }

    ControlFactory.createTextField(
        parent,
        Messages.ModelTooling_Common_Id,
        master,
        context,
        textProp,
        EMFEditProperties.value(
            getEditingDomain(), ApplicationPackageImpl.Literals.APPLICATION_ELEMENT__ELEMENT_ID));
    ControlFactory.createTextField(
        parent,
        Messages.ModelTooling_UIElement_AccessibilityPhrase,
        getMaster(),
        context,
        textProp,
        EMFEditProperties.value(
            getEditingDomain(), UiPackageImpl.Literals.UI_ELEMENT__ACCESSIBILITY_PHRASE));
    ControlFactory.createSelectedElement(
        parent, this, context, Messages.PerspectiveStackEditor_SelectedElement);

    // ------------------------------------------------------------
    {
      Label l = new Label(parent, SWT.NONE);
      l.setText(Messages.PerspectiveStackEditor_Perspectives);
      l.setLayoutData(new GridData(GridData.END, GridData.BEGINNING, false, false));

      final TableViewer viewer = new TableViewer(parent);
      viewer.setContentProvider(new ObservableListContentProvider());
      viewer.setLabelProvider(new ComponentLabelProvider(getEditor(), Messages));
      GridData gd = new GridData(GridData.FILL_BOTH);
      viewer.getControl().setLayoutData(gd);

      IEMFListProperty prop =
          EMFProperties.list(UiPackageImpl.Literals.ELEMENT_CONTAINER__CHILDREN);
      viewer.setInput(prop.observeDetail(getMaster()));

      Composite buttonComp = new Composite(parent, SWT.NONE);
      buttonComp.setLayoutData(new GridData(GridData.FILL, GridData.END, false, false));
      GridLayout gl = new GridLayout();
      gl.marginLeft = 0;
      gl.marginRight = 0;
      gl.marginWidth = 0;
      gl.marginHeight = 0;
      buttonComp.setLayout(gl);

      Button b = new Button(buttonComp, SWT.PUSH | SWT.FLAT);
      b.setText(Messages.ModelTooling_Common_Up);
      b.setImage(createImage(ResourceProvider.IMG_Obj16_arrow_up));
      b.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true, false));
      b.addSelectionListener(
          new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent e) {
              if (!viewer.getSelection().isEmpty()) {
                IStructuredSelection s = (IStructuredSelection) viewer.getSelection();
                if (s.size() == 1) {
                  Object obj = s.getFirstElement();
                  MElementContainer<?> container = (MElementContainer<?>) getMaster().getValue();
                  int idx = container.getChildren().indexOf(obj) - 1;
                  if (idx >= 0) {
                    if (Util.moveElementByIndex(
                        getEditingDomain(), (MUIElement) obj, getEditor().isLiveModel(), idx)) {
                      viewer.setSelection(new StructuredSelection(obj));
                    }
                  }
                }
              }
            }
          });

      b = new Button(buttonComp, SWT.PUSH | SWT.FLAT);
      b.setText(Messages.ModelTooling_Common_Down);
      b.setImage(createImage(ResourceProvider.IMG_Obj16_arrow_down));
      b.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true, false));
      b.addSelectionListener(
          new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent e) {
              if (!viewer.getSelection().isEmpty()) {
                IStructuredSelection s = (IStructuredSelection) viewer.getSelection();
                if (s.size() == 1) {
                  Object obj = s.getFirstElement();
                  MElementContainer<?> container = (MElementContainer<?>) getMaster().getValue();
                  int idx = container.getChildren().indexOf(obj) + 1;
                  if (idx < container.getChildren().size()) {
                    if (Util.moveElementByIndex(
                        getEditingDomain(), (MUIElement) obj, getEditor().isLiveModel(), idx)) {
                      viewer.setSelection(new StructuredSelection(obj));
                    }
                  }
                }
              }
            }
          });

      b = new Button(buttonComp, SWT.PUSH | SWT.FLAT);
      b.setImage(createImage(ResourceProvider.IMG_Obj16_table_add));
      b.setText(Messages.ModelTooling_Common_AddEllipsis);
      b.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true, false));
      b.addSelectionListener(
          new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent e) {
              handleAddPerspective();
            }
          });

      b = new Button(buttonComp, SWT.PUSH | SWT.FLAT);
      b.setText(Messages.ModelTooling_Common_Remove);
      b.setImage(createImage(ResourceProvider.IMG_Obj16_table_delete));
      b.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true, false));
      b.addSelectionListener(
          new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent e) {
              if (!viewer.getSelection().isEmpty()) {
                List<?> elements = ((IStructuredSelection) viewer.getSelection()).toList();

                Command cmd =
                    RemoveCommand.create(
                        getEditingDomain(),
                        getMaster().getValue(),
                        UiPackageImpl.Literals.ELEMENT_CONTAINER__CHILDREN,
                        elements);
                if (cmd.canExecute()) {
                  getEditingDomain().getCommandStack().execute(cmd);
                }
              }
            }
          });
    }

    ControlFactory.createCheckBox(
        parent,
        Messages.ModelTooling_UIElement_ToBeRendered,
        getMaster(),
        context,
        WidgetProperties.selection(),
        EMFEditProperties.value(
            getEditingDomain(), UiPackageImpl.Literals.UI_ELEMENT__TO_BE_RENDERED));
    ControlFactory.createCheckBox(
        parent,
        Messages.ModelTooling_UIElement_Visible,
        getMaster(),
        context,
        WidgetProperties.selection(),
        EMFEditProperties.value(getEditingDomain(), UiPackageImpl.Literals.UI_ELEMENT__VISIBLE));

    item = new CTabItem(folder, SWT.NONE);
    item.setText(Messages.ModelTooling_Common_TabSupplementary);

    parent = createScrollableContainer(folder);
    item.setControl(parent.getParent());

    ControlFactory.createStringListWidget(
        parent,
        Messages,
        this,
        Messages.CategoryEditor_Tags,
        ApplicationPackageImpl.Literals.APPLICATION_ELEMENT__TAGS,
        VERTICAL_LIST_WIDGET_INDENT);
    ControlFactory.createMapProperties(
        parent,
        Messages,
        this,
        Messages.ModelTooling_Contribution_PersistedState,
        ApplicationPackageImpl.Literals.APPLICATION_ELEMENT__PERSISTED_STATE,
        VERTICAL_LIST_WIDGET_INDENT);

    if (project == null) {
      createUITreeInspection(folder);
    }

    folder.setSelection(0);

    return folder;
  }
public class TrimContributionEditor extends AbstractComponentEditor {
  private Composite composite;
  private EMFDataBindingContext context;

  private IListProperty ELEMENT_CONTAINER__CHILDREN =
      EMFProperties.list(UiPackageImpl.Literals.ELEMENT_CONTAINER__CHILDREN);
  private EStackLayout stackLayout;

  @Inject @Optional protected IProject project;

  @Inject
  public TrimContributionEditor() {
    super();
  }

  @Override
  public Image getImage(Object element, Display display) {
    if (element instanceof MUIElement) {
      MUIElement uiElement = (MUIElement) element;
      if (uiElement.isToBeRendered() && uiElement.isVisible()) {
        return createImage(ResourceProvider.IMG_TrimContribution);
      } else {
        return createImage(ResourceProvider.IMG_Tbr_TrimContribution);
      }
    }

    return null;
  }

  @Override
  public String getLabel(Object element) {
    return Messages.TrimContributionEditor_TreeLabel;
  }

  @Override
  public String getDetailLabel(Object element) {
    return null;
  }

  @Override
  public String getDescription(Object element) {
    return Messages.TrimContributionEditor_TreeLabelDescription;
  }

  @Override
  public Composite doGetEditor(Composite parent, Object object) {
    if (composite == null) {
      context = new EMFDataBindingContext();
      if (getEditor().isModelFragment()) {
        composite = new Composite(parent, SWT.NONE);
        stackLayout = new EStackLayout();
        composite.setLayout(stackLayout);
        createForm(composite, context, getMaster(), false);
        createForm(composite, context, getMaster(), true);
      } else {
        composite = createForm(parent, context, getMaster(), false);
      }
    }

    if (getEditor().isModelFragment()) {
      Control topControl;
      if (Util.isImport((EObject) object)) {
        topControl = composite.getChildren()[1];
      } else {
        topControl = composite.getChildren()[0];
      }

      if (stackLayout.topControl != topControl) {
        stackLayout.topControl = topControl;
        composite.layout(true, true);
      }
    }

    getMaster().setValue(object);
    return composite;
  }

  private Composite createForm(
      Composite parent, EMFDataBindingContext context, WritableValue master, boolean isImport) {
    CTabFolder folder = new CTabFolder(parent, SWT.BOTTOM);

    CTabItem item = new CTabItem(folder, SWT.NONE);
    item.setText(Messages.ModelTooling_Common_TabDefault);

    parent = createScrollableContainer(folder);
    item.setControl(parent.getParent());

    if (getEditor().isShowXMIId() || getEditor().isLiveModel()) {
      ControlFactory.createXMIId(parent, this);
    }

    IWidgetValueProperty textProp = WidgetProperties.text(SWT.Modify);

    if (isImport) {
      ControlFactory.createFindImport(parent, Messages, this, context);
      return folder;
    }

    ControlFactory.createTextField(
        parent,
        Messages.ModelTooling_Common_Id,
        master,
        context,
        textProp,
        EMFEditProperties.value(
            getEditingDomain(), ApplicationPackageImpl.Literals.APPLICATION_ELEMENT__ELEMENT_ID));
    ControlFactory.createTextField(
        parent,
        Messages.ModelTooling_UIElement_AccessibilityPhrase,
        getMaster(),
        context,
        textProp,
        EMFEditProperties.value(
            getEditingDomain(), UiPackageImpl.Literals.UI_ELEMENT__ACCESSIBILITY_PHRASE));
    ControlFactory.createTextField(
        parent,
        Messages.TrimContributionEditor_ParentId,
        master,
        context,
        textProp,
        EMFEditProperties.value(
            getEditingDomain(), MenuPackageImpl.Literals.TRIM_CONTRIBUTION__PARENT_ID));
    ControlFactory.createTextField(
        parent,
        Messages.TrimContributionEditor_Position,
        master,
        context,
        textProp,
        EMFEditProperties.value(
            getEditingDomain(), MenuPackageImpl.Literals.TRIM_CONTRIBUTION__POSITION_IN_PARENT));

    // ------------------------------------------------------------
    {
      Label l = new Label(parent, SWT.NONE);
      l.setText(Messages.TrimContributionEditor_Controls);
      l.setLayoutData(new GridData(GridData.END, GridData.BEGINNING, false, false));

      final TableViewer viewer = new TableViewer(parent);
      viewer.setLabelProvider(new ComponentLabelProvider(getEditor(), Messages));
      viewer.setContentProvider(new ObservableListContentProvider());
      GridData gd = new GridData(GridData.FILL_BOTH);
      viewer.getControl().setLayoutData(gd);

      IEMFListProperty prop =
          EMFProperties.list(UiPackageImpl.Literals.ELEMENT_CONTAINER__CHILDREN);
      viewer.setInput(prop.observeDetail(getMaster()));

      Composite buttonComp = new Composite(parent, SWT.NONE);
      buttonComp.setLayoutData(new GridData(GridData.FILL, GridData.END, false, false));
      GridLayout gl = new GridLayout(2, false);
      gl.marginLeft = 0;
      gl.marginRight = 0;
      gl.marginWidth = 0;
      gl.marginHeight = 0;
      buttonComp.setLayout(gl);

      Button b = new Button(buttonComp, SWT.PUSH | SWT.FLAT);
      b.setText(Messages.ModelTooling_Common_Up);
      b.setImage(createImage(ResourceProvider.IMG_Obj16_arrow_up));
      b.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true, false, 2, 1));
      b.addSelectionListener(
          new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent e) {
              if (!viewer.getSelection().isEmpty()) {
                IStructuredSelection s = (IStructuredSelection) viewer.getSelection();
                if (s.size() == 1) {
                  Object obj = s.getFirstElement();
                  MElementContainer<?> container = (MElementContainer<?>) getMaster().getValue();
                  int idx = container.getChildren().indexOf(obj) - 1;
                  if (idx >= 0) {
                    if (Util.moveElementByIndex(
                        getEditingDomain(), (MUIElement) obj, getEditor().isLiveModel(), idx)) {
                      viewer.setSelection(new StructuredSelection(obj));
                    }
                  }
                }
              }
            }
          });

      b = new Button(buttonComp, SWT.PUSH | SWT.FLAT);
      b.setText(Messages.ModelTooling_Common_Down);
      b.setImage(createImage(ResourceProvider.IMG_Obj16_arrow_down));
      b.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true, false, 2, 1));
      b.addSelectionListener(
          new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent e) {
              if (!viewer.getSelection().isEmpty()) {
                IStructuredSelection s = (IStructuredSelection) viewer.getSelection();
                if (s.size() == 1) {
                  Object obj = s.getFirstElement();
                  MElementContainer<?> container = (MElementContainer<?>) getMaster().getValue();
                  int idx = container.getChildren().indexOf(obj) + 1;
                  if (idx < container.getChildren().size()) {
                    if (Util.moveElementByIndex(
                        getEditingDomain(), (MUIElement) obj, getEditor().isLiveModel(), idx)) {
                      viewer.setSelection(new StructuredSelection(obj));
                    }
                  }
                }
              }
            }
          });

      final ComboViewer typeViewer = new ComboViewer(buttonComp, SWT.READ_ONLY);
      typeViewer.setContentProvider(new ArrayContentProvider());
      typeViewer.setLabelProvider(
          new LabelProvider() {
            @Override
            public String getText(Object element) {
              return ((EClass) element).getName();
            }
          });
      typeViewer.setInput(
          new Object[] {MenuPackageImpl.Literals.TOOL_BAR, MenuPackageImpl.Literals.TOOL_CONTROL});
      typeViewer.setSelection(new StructuredSelection(MenuPackageImpl.Literals.TOOL_BAR));

      b = new Button(buttonComp, SWT.PUSH | SWT.FLAT);
      b.setImage(createImage(ResourceProvider.IMG_Obj16_table_add));
      b.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true, false));
      b.addSelectionListener(
          new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent e) {
              EObject toolbar =
                  EcoreUtil.create(
                      (EClass)
                          ((IStructuredSelection) typeViewer.getSelection()).getFirstElement());
              setElementId(toolbar);

              Command cmd =
                  AddCommand.create(
                      getEditingDomain(),
                      getMaster().getValue(),
                      UiPackageImpl.Literals.ELEMENT_CONTAINER__CHILDREN,
                      toolbar);

              if (cmd.canExecute()) {
                getEditingDomain().getCommandStack().execute(cmd);
                getEditor().setSelection(toolbar);
              }
            }
          });

      b = new Button(buttonComp, SWT.PUSH | SWT.FLAT);
      b.setText(Messages.ModelTooling_Common_Remove);
      b.setImage(createImage(ResourceProvider.IMG_Obj16_table_delete));
      b.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true, false, 2, 1));
      b.addSelectionListener(
          new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent e) {
              if (!viewer.getSelection().isEmpty()) {
                List<?> elements = ((IStructuredSelection) viewer.getSelection()).toList();

                Command cmd =
                    RemoveCommand.create(
                        getEditingDomain(),
                        getMaster().getValue(),
                        UiPackageImpl.Literals.ELEMENT_CONTAINER__CHILDREN,
                        elements);
                if (cmd.canExecute()) {
                  getEditingDomain().getCommandStack().execute(cmd);
                }
              }
            }
          });
    }

    ControlFactory.createCheckBox(
        parent,
        Messages.ModelTooling_UIElement_ToBeRendered,
        getMaster(),
        context,
        WidgetProperties.selection(),
        EMFEditProperties.value(
            getEditingDomain(), UiPackageImpl.Literals.UI_ELEMENT__TO_BE_RENDERED));
    ControlFactory.createCheckBox(
        parent,
        Messages.ModelTooling_UIElement_Visible,
        getMaster(),
        context,
        WidgetProperties.selection(),
        EMFEditProperties.value(getEditingDomain(), UiPackageImpl.Literals.UI_ELEMENT__VISIBLE));

    item = new CTabItem(folder, SWT.NONE);
    item.setText(Messages.ModelTooling_Common_TabSupplementary);

    parent = createScrollableContainer(folder);
    item.setControl(parent.getParent());

    ControlFactory.createStringListWidget(
        parent,
        Messages,
        this,
        Messages.CategoryEditor_Tags,
        ApplicationPackageImpl.Literals.APPLICATION_ELEMENT__TAGS,
        VERTICAL_LIST_WIDGET_INDENT);

    if (project == null) {
      createUITreeInspection(folder);
    }

    folder.setSelection(0);

    return folder;
  }

  private void createUITreeInspection(CTabFolder folder) {
    CTabItem item = new CTabItem(folder, SWT.NONE);
    item.setText(Messages.ModelTooling_Common_RuntimeWidgetTree);
    Composite container = new Composite(folder, SWT.NONE);
    container.setLayout(new GridLayout());
    item.setControl(container);

    UIViewer objectViewer = new UIViewer();
    TreeViewer viewer =
        objectViewer.createViewer(
            container,
            UiPackageImpl.Literals.UI_ELEMENT__WIDGET,
            getMaster(),
            resourcePool,
            Messages);
    viewer.getControl().setLayoutData(new GridData(GridData.FILL_BOTH));
  }

  @Override
  public IObservableList getChildList(Object element) {
    return ELEMENT_CONTAINER__CHILDREN.observe(element);
  }

  @Override
  public FeaturePath[] getLabelProperties() {
    return new FeaturePath[] {
      FeaturePath.fromList(UiPackageImpl.Literals.UI_ELEMENT__TO_BE_RENDERED)
    };
  }
}
public class VItemParametersEditor extends AbstractComponentEditor {
  private Composite composite;
  private EMFDataBindingContext context;
  private TableViewer viewer;
  private List<Action> actions = new ArrayList<Action>();

  private IEMFListProperty HANDLED_ITEM__PARAMETERS =
      EMFProperties.list(MenuPackageImpl.Literals.HANDLED_ITEM__PARAMETERS);

  @Inject
  public VItemParametersEditor() {
    super();
  }

  @PostConstruct
  void init() {
    actions.add(
        new Action(
            Messages.VItemParametersEditor_AddParameter,
            createImageDescriptor(ResourceProvider.IMG_Parameter)) {
          @Override
          public void run() {
            handleAdd();
          }
        });
  }

  @Override
  public Image getImage(Object element, Display display) {
    return null;
  }

  @Override
  public String getLabel(Object element) {
    return Messages.VItemParametersEditor_TreeLabel;
  }

  @Override
  public String getDetailLabel(Object element) {
    return null;
  }

  @Override
  public String getDescription(Object element) {
    return Messages.VItemParametersEditor_TreeLabelDescription;
  }

  @Override
  public Composite doGetEditor(Composite parent, Object object) {
    if (composite == null) {
      context = new EMFDataBindingContext();
      composite = createForm(parent, context, getMaster());
    }
    VirtualEntry<?> o = (VirtualEntry<?>) object;
    viewer.setInput(o.getList());
    getMaster().setValue(o.getOriginalParent());
    return composite;
  }

  private Composite createForm(
      Composite parent, EMFDataBindingContext context, WritableValue master) {
    CTabFolder folder = new CTabFolder(parent, SWT.BOTTOM);

    CTabItem item = new CTabItem(folder, SWT.NONE);
    item.setText(Messages.ModelTooling_Common_TabDefault);

    parent = createScrollableContainer(folder);
    item.setControl(parent.getParent());

    {
      viewer = new TableViewer(parent);
      ObservableListContentProvider cp = new ObservableListContentProvider();
      viewer.setContentProvider(cp);
      GridData gd = new GridData(GridData.FILL_BOTH);
      viewer.getControl().setLayoutData(gd);
      viewer.setLabelProvider(new ComponentLabelProvider(getEditor(), Messages));

      Composite buttonComp = new Composite(parent, SWT.NONE);
      buttonComp.setLayoutData(new GridData(GridData.FILL, GridData.END, false, false));
      GridLayout gl = new GridLayout();
      gl.marginLeft = 0;
      gl.marginRight = 0;
      gl.marginWidth = 0;
      gl.marginHeight = 0;
      buttonComp.setLayout(gl);

      Button b = new Button(buttonComp, SWT.PUSH | SWT.FLAT);
      b.setText(Messages.ModelTooling_Common_Up);
      b.setImage(createImage(ResourceProvider.IMG_Obj16_arrow_up));
      b.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true, false));
      b.addSelectionListener(
          new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent e) {
              if (!viewer.getSelection().isEmpty()) {
                IStructuredSelection s = (IStructuredSelection) viewer.getSelection();
                if (s.size() == 1) {
                  Object obj = s.getFirstElement();
                  MHandledItem container = (MHandledItem) getMaster().getValue();
                  int idx = container.getParameters().indexOf(obj) - 1;
                  if (idx >= 0) {
                    Command cmd =
                        MoveCommand.create(
                            getEditingDomain(),
                            getMaster().getValue(),
                            MenuPackageImpl.Literals.HANDLED_ITEM__PARAMETERS,
                            obj,
                            idx);

                    if (cmd.canExecute()) {
                      getEditingDomain().getCommandStack().execute(cmd);
                      viewer.setSelection(new StructuredSelection(obj));
                    }
                  }
                }
              }
            }
          });

      b = new Button(buttonComp, SWT.PUSH | SWT.FLAT);
      b.setText(Messages.ModelTooling_Common_Down);
      b.setImage(createImage(ResourceProvider.IMG_Obj16_arrow_down));
      b.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true, false));
      b.addSelectionListener(
          new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent e) {
              if (!viewer.getSelection().isEmpty()) {
                IStructuredSelection s = (IStructuredSelection) viewer.getSelection();
                if (s.size() == 1) {
                  Object obj = s.getFirstElement();
                  MHandledItem container = (MHandledItem) getMaster().getValue();
                  int idx = container.getParameters().indexOf(obj) + 1;
                  if (idx < container.getParameters().size()) {
                    Command cmd =
                        MoveCommand.create(
                            getEditingDomain(),
                            getMaster().getValue(),
                            MenuPackageImpl.Literals.HANDLED_ITEM__PARAMETERS,
                            obj,
                            idx);

                    if (cmd.canExecute()) {
                      getEditingDomain().getCommandStack().execute(cmd);
                      viewer.setSelection(new StructuredSelection(obj));
                    }
                  }
                }
              }
            }
          });

      b = new Button(buttonComp, SWT.PUSH | SWT.FLAT);
      b.setText(Messages.ModelTooling_Common_AddEllipsis);
      b.setImage(createImage(ResourceProvider.IMG_Obj16_table_add));
      b.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true, false));
      b.addSelectionListener(
          new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent e) {
              handleAdd();
            }
          });

      b = new Button(buttonComp, SWT.PUSH | SWT.FLAT);
      b.setText(Messages.ModelTooling_Common_Remove);
      b.setImage(createImage(ResourceProvider.IMG_Obj16_table_delete));
      b.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true, false));
      b.addSelectionListener(
          new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent e) {
              if (!viewer.getSelection().isEmpty()) {
                List<?> handlers = ((IStructuredSelection) viewer.getSelection()).toList();
                Command cmd =
                    RemoveCommand.create(
                        getEditingDomain(),
                        getMaster().getValue(),
                        MenuPackageImpl.Literals.HANDLED_ITEM__PARAMETERS,
                        handlers);
                if (cmd.canExecute()) {
                  getEditingDomain().getCommandStack().execute(cmd);
                }
              }
            }
          });
    }

    folder.setSelection(0);

    return folder;
  }

  @Override
  public IObservableList getChildList(Object element) {
    return HANDLED_ITEM__PARAMETERS.observe(element);
  }

  protected void handleAdd() {
    MParameter handler = MCommandsFactory.INSTANCE.createParameter();
    setElementId(handler);

    Command cmd =
        AddCommand.create(
            getEditingDomain(),
            getMaster().getValue(),
            MenuPackageImpl.Literals.HANDLED_ITEM__PARAMETERS,
            handler);

    if (cmd.canExecute()) {
      getEditingDomain().getCommandStack().execute(cmd);
      getEditor().setSelection(handler);
    }
  }

  @Override
  public List<Action> getActions(Object element) {
    ArrayList<Action> l = new ArrayList<Action>(super.getActions(element));
    l.addAll(actions);
    return l;
  }
}
public class StringModelFragment extends AbstractComponentEditor {
  private Composite composite;
  private Image image;
  private EMFDataBindingContext context;

  private IListProperty MODEL_FRAGMENT__ELEMENTS =
      EMFProperties.list(FragmentPackageImpl.Literals.MODEL_FRAGMENT__ELEMENTS);

  public StringModelFragment(EditingDomain editingDomain, ModelEditor editor) {
    super(editingDomain, editor);
  }

  @Override
  public Image getImage(Object element, Display display) {
    if (image == null) {
      try {
        image =
            loadSharedImage(
                display,
                new URL(
                    "platform:/plugin/org.eclipse.e4.tools.emf.ui/icons/full/modelelements/StringModelFragment.png")); //$NON-NLS-1$
      } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }
    return image;
  }

  @Override
  public String getLabel(Object element) {
    return Messages.StringModelFragment_Label;
  }

  @Override
  public String getDetailLabel(Object element) {
    return null;
  }

  @Override
  public String getDescription(Object element) {
    return Messages.StringModelFragment_Description;
  }

  @Override
  public Composite getEditor(Composite parent, Object object) {
    if (composite == null) {
      context = new EMFDataBindingContext();
      composite = createForm(parent);
    }
    getMaster().setValue(object);
    return composite;
  }

  private Composite createForm(Composite parent) {
    parent = new Composite(parent, SWT.NONE);
    GridLayout gl = new GridLayout(3, false);
    gl.horizontalSpacing = 10;
    parent.setLayout(gl);

    if (getEditor().isShowXMIId() || getEditor().isLiveModel()) {
      ControlFactory.createXMIId(parent, this);
    }

    IWidgetValueProperty textProp = WidgetProperties.text(SWT.Modify);
    {
      Label l = new Label(parent, SWT.NONE);
      l.setText(Messages.StringModelFragment_ParentId);
      l.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_END));

      Composite comp = new Composite(parent, SWT.NONE);
      GridData gd = new GridData(GridData.FILL_HORIZONTAL);
      gd.horizontalSpan = 2;
      comp.setLayoutData(gd);
      gl = new GridLayout(2, false);
      gl.marginWidth = gl.marginHeight = 0;
      gl.verticalSpacing = 0;
      gl.marginLeft = gl.marginBottom = gl.marginRight = gl.marginTop = 0;
      comp.setLayout(gl);

      Text t = new Text(comp, SWT.BORDER);
      t.setEditable(false);
      gd = new GridData(GridData.FILL_HORIZONTAL);
      t.setLayoutData(gd);
      context.bindValue(
          textProp.observeDelayed(200, t),
          EMFEditProperties.value(
                  getEditingDomain(),
                  FragmentPackageImpl.Literals.STRING_MODEL_FRAGMENT__PARENT_ELEMENT_ID)
              .observeDetail(getMaster()));

      final Button b = new Button(comp, SWT.PUSH | SWT.FLAT);
      b.setText(Messages.ModelTooling_Common_FindEllipsis);
      b.addSelectionListener(
          new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent e) {
              FindParentReferenceElementDialog dialog =
                  new FindParentReferenceElementDialog(
                      b.getShell(),
                      StringModelFragment.this,
                      (MStringModelFragment) getMaster().getValue());
              dialog.open();
            }
          });
    }

    {
      Label l = new Label(parent, SWT.NONE);
      l.setText(Messages.StringModelFragment_Featurename);
      l.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_END));

      Composite comp = new Composite(parent, SWT.NONE);
      GridData gd = new GridData(GridData.FILL_HORIZONTAL);
      gd.horizontalSpan = 2;
      comp.setLayoutData(gd);
      gl = new GridLayout(2, false);
      gl.marginWidth = gl.marginHeight = 0;
      gl.verticalSpacing = 0;
      gl.marginLeft = gl.marginBottom = gl.marginRight = gl.marginTop = 0;
      comp.setLayout(gl);

      Text t = new Text(comp, SWT.BORDER);
      gd = new GridData(GridData.FILL_HORIZONTAL);
      t.setLayoutData(gd);
      context.bindValue(
          textProp.observeDelayed(200, t),
          EMFEditProperties.value(
                  getEditingDomain(),
                  FragmentPackageImpl.Literals.STRING_MODEL_FRAGMENT__FEATURENAME)
              .observeDetail(getMaster()));

      final Button button = new Button(comp, SWT.PUSH | SWT.FLAT);
      button.setText(Messages.ModelTooling_Common_FindEllipsis);
      button.addSelectionListener(
          new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent e) {
              FeatureSelectionDialog dialog =
                  new FeatureSelectionDialog(
                      button.getShell(),
                      getEditingDomain(),
                      (MStringModelFragment) getMaster().getValue());
              dialog.open();
            }
          });
    }

    {
      Label l = new Label(parent, SWT.NONE);
      l.setText(Messages.StringModelFragment_PositionInList);
      l.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_END));

      Text t = new Text(parent, SWT.BORDER);
      GridData gd = new GridData(GridData.FILL_HORIZONTAL);
      gd.horizontalSpan = 2;
      t.setLayoutData(gd);
      context.bindValue(
          textProp.observeDelayed(200, t),
          EMFEditProperties.value(
                  getEditingDomain(),
                  FragmentPackageImpl.Literals.STRING_MODEL_FRAGMENT__POSITION_IN_LIST)
              .observeDetail(getMaster()));
    }

    // ------------------------------------------------------------
    {
      Label l = new Label(parent, SWT.NONE);
      l.setText(Messages.StringModelFragment_Elements);
      l.setLayoutData(new GridData(GridData.END, GridData.BEGINNING, false, false));

      final TableViewer viewer = new TableViewer(parent);
      viewer.setContentProvider(new ObservableListContentProvider());
      viewer.setLabelProvider(new ComponentLabelProvider(getEditor()));
      GridData gd = new GridData(GridData.FILL_HORIZONTAL);
      gd.heightHint = 300;
      viewer.getControl().setLayoutData(gd);

      IEMFListProperty prop =
          EMFProperties.list(FragmentPackageImpl.Literals.MODEL_FRAGMENT__ELEMENTS);
      viewer.setInput(prop.observeDetail(getMaster()));

      Composite buttonComp = new Composite(parent, SWT.NONE);
      buttonComp.setLayoutData(new GridData(GridData.FILL, GridData.END, false, false));
      gl = new GridLayout(2, false);
      gl.marginLeft = 0;
      gl.marginRight = 0;
      gl.marginWidth = 0;
      gl.marginHeight = 0;
      buttonComp.setLayout(gl);

      Button b = new Button(buttonComp, SWT.PUSH | SWT.FLAT);
      b.setText(Messages.ModelTooling_Common_Up);
      b.setImage(getImage(b.getDisplay(), ARROW_UP));
      b.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true, false, 2, 1));
      b.addSelectionListener(
          new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent e) {
              if (!viewer.getSelection().isEmpty()) {
                IStructuredSelection s = (IStructuredSelection) viewer.getSelection();
                if (s.size() == 1) {
                  Object obj = s.getFirstElement();
                  MModelFragment container = (MModelFragment) getMaster().getValue();
                  int idx = container.getElements().indexOf(obj) - 1;
                  if (idx >= 0) {
                    Command cmd =
                        MoveCommand.create(
                            getEditingDomain(),
                            getMaster().getValue(),
                            FragmentPackageImpl.Literals.MODEL_FRAGMENT__ELEMENTS,
                            obj,
                            idx);

                    if (cmd.canExecute()) {
                      getEditingDomain().getCommandStack().execute(cmd);
                      viewer.setSelection(new StructuredSelection(obj));
                    }
                  }
                }
              }
            }
          });

      b = new Button(buttonComp, SWT.PUSH | SWT.FLAT);
      b.setText(Messages.ModelTooling_Common_Down);
      b.setImage(getImage(b.getDisplay(), ARROW_DOWN));
      b.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true, false, 2, 1));
      b.addSelectionListener(
          new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent e) {
              if (!viewer.getSelection().isEmpty()) {
                IStructuredSelection s = (IStructuredSelection) viewer.getSelection();
                if (s.size() == 1) {
                  Object obj = s.getFirstElement();
                  MModelFragment container = (MModelFragment) getMaster().getValue();
                  int idx = container.getElements().indexOf(obj) + 1;
                  if (idx < container.getElements().size()) {
                    Command cmd =
                        MoveCommand.create(
                            getEditingDomain(),
                            getMaster().getValue(),
                            FragmentPackageImpl.Literals.MODEL_FRAGMENT__ELEMENTS,
                            obj,
                            idx);

                    if (cmd.canExecute()) {
                      getEditingDomain().getCommandStack().execute(cmd);
                      viewer.setSelection(new StructuredSelection(obj));
                    }
                  }
                }
              }
            }
          });

      final ComboViewer childrenDropDown = new ComboViewer(buttonComp);
      childrenDropDown
          .getControl()
          .setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true, false));
      childrenDropDown.setContentProvider(new ArrayContentProvider());
      childrenDropDown.setLabelProvider(
          new LabelProvider() {
            @Override
            public String getText(Object element) {
              FeatureClass eclass = (FeatureClass) element;
              return eclass.label;
            }
          });
      childrenDropDown.setComparator(
          new ViewerComparator() {
            @Override
            public int compare(Viewer viewer, Object e1, Object e2) {
              FeatureClass eClass1 = (FeatureClass) e1;
              FeatureClass eClass2 = (FeatureClass) e2;
              return eClass1.label.compareTo(eClass2.label);
            }
          });

      List<FeatureClass> list = new ArrayList<FeatureClass>();
      Util.addClasses(ApplicationPackageImpl.eINSTANCE, list);
      list.addAll(
          getEditor()
              .getFeatureClasses(
                  FragmentPackageImpl.Literals.MODEL_FRAGMENT,
                  FragmentPackageImpl.Literals.MODEL_FRAGMENT__ELEMENTS));

      childrenDropDown.setInput(list);
      childrenDropDown.getCombo().select(0);

      b = new Button(buttonComp, SWT.PUSH | SWT.FLAT);
      b.setImage(getImage(b.getDisplay(), TABLE_ADD_IMAGE));
      b.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true, false));
      b.addSelectionListener(
          new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent e) {
              EClass eClass =
                  ((FeatureClass)
                          ((IStructuredSelection) childrenDropDown.getSelection())
                              .getFirstElement())
                      .eClass;
              EObject eObject = EcoreUtil.create(eClass);

              Command cmd =
                  AddCommand.create(
                      getEditingDomain(),
                      getMaster().getValue(),
                      FragmentPackageImpl.Literals.MODEL_FRAGMENT__ELEMENTS,
                      eObject);

              if (cmd.canExecute()) {
                getEditingDomain().getCommandStack().execute(cmd);
                getEditor().setSelection(eObject);
              }
            }
          });

      b = new Button(buttonComp, SWT.PUSH | SWT.FLAT);
      b.setText(Messages.ModelTooling_Common_Remove);
      b.setImage(getImage(b.getDisplay(), TABLE_DELETE_IMAGE));
      b.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true, false, 2, 1));
      b.addSelectionListener(
          new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent e) {
              if (!viewer.getSelection().isEmpty()) {
                List<?> elements = ((IStructuredSelection) viewer.getSelection()).toList();

                Command cmd =
                    RemoveCommand.create(
                        getEditingDomain(),
                        getMaster().getValue(),
                        FragmentPackageImpl.Literals.MODEL_FRAGMENT__ELEMENTS,
                        elements);
                if (cmd.canExecute()) {
                  getEditingDomain().getCommandStack().execute(cmd);
                }
              }
            }
          });
    }

    return parent;
  }

  public void dispose() {
    if (image != null) {
      image.dispose();
      image = null;
    }

    if (composite != null) {
      composite.dispose();
      composite = null;
    }

    if (context != null) {
      context.dispose();
      context = null;
    }
  }

  @Override
  public IObservableList getChildList(Object element) {
    return MODEL_FRAGMENT__ELEMENTS.observe(element);
  }
}
public class ApplicationEditor extends AbstractComponentEditor {

  private Composite composite;
  private EMFDataBindingContext context;

  private IListProperty HANDLER_CONTAINER__HANDLERS =
      EMFProperties.list(CommandsPackageImpl.Literals.HANDLER_CONTAINER__HANDLERS);
  private IListProperty BINDING_CONTAINER__BINDINGS =
      EMFProperties.list(CommandsPackageImpl.Literals.BINDING_TABLE_CONTAINER__BINDING_TABLES);
  private IListProperty APPLICATION__COMMANDS =
      EMFProperties.list(ApplicationPackageImpl.Literals.APPLICATION__COMMANDS);
  private IListProperty PART_DESCRIPTOR_CONTAINER__DESCRIPTORS =
      EMFProperties.list(BasicPackageImpl.Literals.PART_DESCRIPTOR_CONTAINER__DESCRIPTORS);
  private IListProperty ELEMENT_CONTAINER__CHILDREN =
      EMFProperties.list(UiPackageImpl.Literals.ELEMENT_CONTAINER__CHILDREN);
  private IListProperty APPLICATION__ADDONS =
      EMFProperties.list(ApplicationPackageImpl.Literals.APPLICATION__ADDONS);
  private IListProperty MENU_CONTRIBUTIONS =
      EMFProperties.list(MenuPackageImpl.Literals.MENU_CONTRIBUTIONS__MENU_CONTRIBUTIONS);
  private IListProperty TOOLBAR_CONTRIBUTIONS =
      EMFProperties.list(MenuPackageImpl.Literals.TOOL_BAR_CONTRIBUTIONS__TOOL_BAR_CONTRIBUTIONS);
  private IListProperty TRIM_CONTRIBUTIONS =
      EMFProperties.list(MenuPackageImpl.Literals.TRIM_CONTRIBUTIONS__TRIM_CONTRIBUTIONS);
  private IListProperty APPLICATION__SNIPPETS =
      EMFProperties.list(UiPackageImpl.Literals.SNIPPET_CONTAINER__SNIPPETS);
  private IListProperty APPLICATION__CATEGORIES =
      EMFProperties.list(ApplicationPackageImpl.Literals.APPLICATION__CATEGORIES);

  private IListProperty BINDING_TABLE_CONTAINER__ROOT_CONTEXT =
      EMFProperties.list(CommandsPackageImpl.Literals.BINDING_TABLE_CONTAINER__ROOT_CONTEXT);

  @Inject @Optional private IProject project;

  private List<Action> actions = new ArrayList<Action>();

  @Inject
  public ApplicationEditor() {
    super();
  }

  @PostConstruct
  void init() {
    // actions.add(new Action("Command Wizard ...") {
    // @Override
    // public void run() {
    // doCreateCommandWizard();
    // }
    // });
  }

  @Override
  public List<Action> getActions(Object element) {
    return actions;
  }

  void doCreateCommandWizard() {
    WizardDialog dialog =
        new WizardDialog(
            composite.getShell(), new CommandWizard((MApplication) getMaster().getValue()));
    dialog.open();
  }

  @Override
  public Image getImage(Object element, Display display) {
    if (element instanceof MUIElement) {
      if (((MUIElement) element).isToBeRendered()) {
        return createImage(ResourceProvider.IMG_Application);
      } else {
        return createImage(ResourceProvider.IMG_Tbr_Application);
      }
    }
    return null;
  }

  @Override
  public String getLabel(Object element) {
    return Messages.ApplicationEditor_Label;
  }

  @Override
  public String getDescription(Object element) {
    return Messages.ApplicationEditor_Description;
  }

  @Override
  public Composite doGetEditor(Composite parent, Object object) {
    if (composite == null) {
      context = new EMFDataBindingContext();
      composite = createForm(parent, context);
    }
    getMaster().setValue(object);

    return composite;
  }

  protected Composite createForm(Composite parent, EMFDataBindingContext context) {
    CTabFolder folder = new CTabFolder(parent, SWT.BOTTOM);

    CTabItem item = new CTabItem(folder, SWT.NONE);
    item.setText(Messages.ModelTooling_Common_TabDefault);

    parent = createScrollableContainer(folder);
    item.setControl(parent.getParent());

    IWidgetValueProperty textProp = WidgetProperties.text(SWT.Modify);

    if (getEditor().isShowXMIId() || getEditor().isLiveModel()) {
      ControlFactory.createXMIId(parent, this);
    }

    ControlFactory.createTextField(
        parent,
        Messages.ModelTooling_Common_Id,
        getMaster(),
        context,
        textProp,
        EMFEditProperties.value(
            getEditingDomain(), ApplicationPackageImpl.Literals.APPLICATION_ELEMENT__ELEMENT_ID));

    ControlFactory.createBindingContextWiget(
        parent, Messages, this, Messages.ApplicationEditor_BindingContexts);

    ControlFactory.createCheckBox(
        parent,
        Messages.ModelTooling_UIElement_ToBeRendered,
        getMaster(),
        context,
        WidgetProperties.selection(),
        EMFEditProperties.value(
            getEditingDomain(), UiPackageImpl.Literals.UI_ELEMENT__TO_BE_RENDERED));
    ControlFactory.createCheckBox(
        parent,
        Messages.ModelTooling_UIElement_Visible,
        getMaster(),
        context,
        WidgetProperties.selection(),
        EMFEditProperties.value(getEditingDomain(), UiPackageImpl.Literals.UI_ELEMENT__VISIBLE));

    item = new CTabItem(folder, SWT.NONE);
    item.setText(Messages.ModelTooling_Common_TabSupplementary);

    parent = createScrollableContainer(folder);
    item.setControl(parent.getParent());

    ControlFactory.createTextField(
        parent,
        Messages.ModelTooling_UIElement_AccessibilityPhrase,
        getMaster(),
        context,
        textProp,
        EMFEditProperties.value(
            getEditingDomain(), UiPackageImpl.Literals.UI_ELEMENT__ACCESSIBILITY_PHRASE));
    ControlFactory.createStringListWidget(
        parent,
        Messages,
        this,
        Messages.ModelTooling_Context_Variables,
        UiPackageImpl.Literals.CONTEXT__VARIABLES,
        VERTICAL_LIST_WIDGET_INDENT);
    ControlFactory.createStringListWidget(
        parent,
        Messages,
        this,
        Messages.AddonsEditor_Tags,
        ApplicationPackageImpl.Literals.APPLICATION_ELEMENT__TAGS,
        VERTICAL_LIST_WIDGET_INDENT);
    ControlFactory.createMapProperties(
        parent,
        Messages,
        this,
        Messages.ModelTooling_Contribution_PersistedState,
        ApplicationPackageImpl.Literals.APPLICATION_ELEMENT__PERSISTED_STATE,
        VERTICAL_LIST_WIDGET_INDENT);

    if (project == null) {
      createUITreeInspection(folder);
    }

    folder.setSelection(0);

    return folder;
  }

  private void createUITreeInspection(CTabFolder folder) {
    CTabItem item = new CTabItem(folder, SWT.NONE);
    item.setText(Messages.ModelTooling_Common_RuntimeWidgetTree);
    Composite container = new Composite(folder, SWT.NONE);
    container.setLayout(new GridLayout());
    item.setControl(container);

    UIViewer objectViewer = new UIViewer();
    TreeViewer viewer =
        objectViewer.createViewer(
            container,
            UiPackageImpl.Literals.UI_ELEMENT__WIDGET,
            getMaster(),
            resourcePool,
            Messages);
    viewer.getControl().setLayoutData(new GridData(GridData.FILL_BOTH));
  }

  @Override
  public IObservableList getChildList(final Object element) {
    final WritableList list = new WritableList();
    list.add(
        new VirtualEntry<Object>(
            ModelEditor.VIRTUAL_ADDONS,
            APPLICATION__ADDONS,
            element,
            Messages.ApplicationEditor_Addons) {

          @Override
          protected boolean accepted(Object o) {
            return true;
          }
        });

    list.add(
        new VirtualEntry<Object>(
            ModelEditor.VIRTUAL_ROOT_CONTEXTS,
            BINDING_TABLE_CONTAINER__ROOT_CONTEXT,
            element,
            Messages.ApplicationEditor_RootContexts) {

          @Override
          protected boolean accepted(Object o) {
            return true;
          }
        });

    list.add(
        new VirtualEntry<Object>(
            ModelEditor.VIRTUAL_BINDING_TABLE,
            BINDING_CONTAINER__BINDINGS,
            element,
            Messages.ApplicationEditor_BindingTables) {

          @Override
          protected boolean accepted(Object o) {
            return true;
          }
        });

    list.add(
        new VirtualEntry<Object>(
            ModelEditor.VIRTUAL_HANDLER,
            HANDLER_CONTAINER__HANDLERS,
            element,
            Messages.ApplicationEditor_Handlers) {

          @Override
          protected boolean accepted(Object o) {
            return true;
          }
        });

    list.add(
        new VirtualEntry<Object>(
            ModelEditor.VIRTUAL_COMMAND,
            APPLICATION__COMMANDS,
            element,
            Messages.ApplicationEditor_Commands) {

          @Override
          protected boolean accepted(Object o) {
            return true;
          }
        });

    list.add(
        new VirtualEntry<Object>(
            ModelEditor.VIRTUAL_CATEGORIES,
            APPLICATION__CATEGORIES,
            element,
            Messages.ApplicationEditor_Categories) {

          @Override
          protected boolean accepted(Object o) {
            return true;
          }
        });

    list.add(
        new VirtualEntry<Object>(
            ModelEditor.VIRTUAL_APPLICATION_WINDOWS,
            ELEMENT_CONTAINER__CHILDREN,
            element,
            Messages.ApplicationEditor_Windows) {

          @Override
          protected boolean accepted(Object o) {
            return true;
          }
        });

    list.add(
        new VirtualEntry<Object>(
            ModelEditor.VIRTUAL_PART_DESCRIPTORS,
            PART_DESCRIPTOR_CONTAINER__DESCRIPTORS,
            element,
            Messages.ApplicationEditor_PartDescriptors) {

          @Override
          protected boolean accepted(Object o) {
            return true;
          }
        });

    list.add(
        new VirtualEntry<Object>(
            ModelEditor.VIRTUAL_MENU_CONTRIBUTIONS,
            MENU_CONTRIBUTIONS,
            element,
            Messages.ApplicationEditor_MenuContributions) {
          @Override
          protected boolean accepted(Object o) {
            return true;
          }
        });

    list.add(
        new VirtualEntry<Object>(
            ModelEditor.VIRTUAL_TOOLBAR_CONTRIBUTIONS,
            TOOLBAR_CONTRIBUTIONS,
            element,
            Messages.ApplicationEditor_ToolBarContributions) {
          @Override
          protected boolean accepted(Object o) {
            return true;
          }
        });

    list.add(
        new VirtualEntry<Object>(
            ModelEditor.VIRTUAL_TRIM_CONTRIBUTIONS,
            TRIM_CONTRIBUTIONS,
            element,
            Messages.ApplicationEditor_TrimContributions) {
          @Override
          protected boolean accepted(Object o) {
            return true;
          }
        });
    list.add(
        new VirtualEntry<Object>(
            ModelEditor.VIRTUAL_SNIPPETS,
            APPLICATION__SNIPPETS,
            element,
            Messages.ApplicationEditor_Snippets) {
          @Override
          protected boolean accepted(Object o) {
            return true;
          }
        });
    //
    // MApplication application = (MApplication) element;
    // if (application.getRootContext() != null) {
    // list.add(0, application.getRootContext());
    // }

    // BINDING_TABLE_CONTAINER__ROOT_CONTEXT.observe(element).addValueChangeListener(new
    // IValueChangeListener() {
    //
    // public void handleValueChange(ValueChangeEvent event) {
    // if (event.diff.getOldValue() != null) {
    // list.remove(event.diff.getOldValue());
    // if (getMaster().getValue() == element) {
    // createRemoveRootContext.setSelection(false);
    // }
    // }
    //
    // if (event.diff.getNewValue() != null) {
    // list.add(0, event.diff.getNewValue());
    // if (getMaster().getValue() == element) {
    // createRemoveRootContext.setSelection(true);
    // }
    // }
    // }
    // });

    return list;
  }

  @Override
  public String getDetailLabel(Object element) {
    return null;
  }

  @Override
  public FeaturePath[] getLabelProperties() {
    return new FeaturePath[] {
      FeaturePath.fromList(UiPackageImpl.Literals.UI_ELEMENT__TO_BE_RENDERED)
    };
  }

  class CommandWizard extends Wizard {
    private MApplication application;

    private HandlerCommandPage handlerPage;
    private KeybindingPage keyPage;
    private MenuWizardPage menuPage;
    private ToolbarWizardPage toolbarPage;

    public CommandWizard(MApplication application) {
      this.application = application;
    }

    @Override
    public void addPages() {
      getShell().setText(Messages.CommandWizard_ShellTitle);
      setDefaultPageImageDescriptor(
          ImageDescriptor.createFromImage(
              resourcePool.getImageUnchecked(ResourceProvider.IMG_Wizban16_newexp_wiz)));
      handlerPage = new HandlerCommandPage("Handler and Command");
      addPage(handlerPage);

      keyPage = new KeybindingPage("Keybinding", application);
      addPage(keyPage);

      menuPage = new MenuWizardPage("Menu", application);
      addPage(menuPage);

      toolbarPage = new ToolbarWizardPage("Toolbar", application);
      addPage(toolbarPage);
    }

    @Override
    public boolean performFinish() {

      MCommand command = CommandsFactoryImpl.eINSTANCE.createCommand();
      MHandler handler = CommandsFactoryImpl.eINSTANCE.createHandler();
      MKeyBinding keyBinding = null;

      String parentId = application.getElementId();

      String prefix =
          parentId != null && parentId.trim().length() > 0
              ? parentId + "."
              : ""; //$NON-NLS-1$ //$NON-NLS-2$

      if (handlerPage.idField.getText().trim().length() > 0) {
        command.setElementId(
            prefix + "commands." + handlerPage.idField.getText().trim()); // $NON-NLS-1$
        handler.setElementId(
            prefix + "handlers." + handlerPage.idField.getText().trim()); // $NON-NLS-1$
      }

      if (application.getBindingTables().size() != 0) {
        if (keyPage.keyField.getText().trim().length() > 0
            && !keyPage.bindtableViewer.getSelection().isEmpty()) {
          keyBinding = CommandsFactoryImpl.eINSTANCE.createKeyBinding();
          keyBinding.setKeySequence(keyPage.keyField.getText().trim());
          keyBinding.setCommand(command);
        }
      }

      command.setCommandName(handlerPage.nameField.getText());
      handler.setCommand(command);

      CompoundCommand cmd = new CompoundCommand();
      cmd.append(
          AddCommand.create(
              getEditingDomain(),
              application,
              ApplicationPackageImpl.Literals.APPLICATION__COMMANDS,
              command));
      cmd.append(
          AddCommand.create(
              getEditingDomain(),
              application,
              CommandsPackageImpl.Literals.HANDLER_CONTAINER__HANDLERS,
              handler));

      if (keyBinding != null) {
        cmd.append(
            AddCommand.create(
                getEditingDomain(),
                ((IStructuredSelection) keyPage.bindtableViewer.getSelection()).getFirstElement(),
                CommandsPackageImpl.Literals.BINDING_TABLE__BINDINGS,
                keyBinding));
      }

      if (cmd.canExecute()) {
        getEditingDomain().getCommandStack().execute(cmd);
        return true;
      }

      return false;
    }
  }

  class HandlerCommandPage extends WizardPage {
    public Text idField;
    public Text nameField;

    public HandlerCommandPage(String pageName) {
      super(pageName);
    }

    public void createControl(Composite parent) {
      setTitle("Command/Handler");
      setMessage("Insert informations for Command and Handler");

      Composite group = new Composite(parent, SWT.NONE);
      group.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
      group.setLayout(new GridLayout(3, false));

      {
        Label l = new Label(group, SWT.NONE);
        l.setText("Id");

        idField = new Text(group, SWT.BORDER);
        idField.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true, false, 2, 1));
      }

      {
        Label l = new Label(group, SWT.NONE);
        l.setText("Name" + "*");

        nameField = new Text(group, SWT.BORDER);
        nameField.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true, false, 2, 1));
        nameField.addModifyListener(
            new ModifyListener() {

              public void modifyText(ModifyEvent e) {
                setPageComplete(nameField.getText().trim().length() > 0);
              }
            });
      }

      {
        Label l = new Label(group, SWT.NONE);
        l.setText("Class");

        Text t = new Text(group, SWT.BORDER);
        t.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));

        Button b = new Button(group, SWT.PUSH | SWT.FLAT);
        b.setText(Messages.ModelTooling_Common_FindEllipsis);
      }

      setControl(group);
    }

    @Override
    public boolean isPageComplete() {
      return nameField.getText().trim().length() > 0;
    }
  }

  class KeybindingPage extends WizardPage {

    private Text keyField;
    private TableViewer bindtableViewer;
    private MApplication application;

    public KeybindingPage(String pageName, MApplication application) {
      super(pageName);
      this.application = application;
    }

    public void createControl(Composite parent) {
      setTitle("Keybinding");
      setMessage("Insert informations for a keybinding");

      Composite group = new Composite(parent, SWT.NONE);
      group.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
      group.setLayout(new GridLayout(2, false));

      {
        Label l = new Label(group, SWT.NONE);
        l.setText("Sequence");

        keyField = new Text(group, SWT.BORDER);
        keyField.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
        keyField.addModifyListener(
            new ModifyListener() {

              public void modifyText(ModifyEvent e) {
                bindtableViewer.getControl().setEnabled(isPageComplete());
                setPageComplete(isPageComplete());
              }
            });
      }

      {
        Label l = new Label(group, SWT.NONE);
        l.setText("Binding Table");
        l.setLayoutData(new GridData(GridData.VERTICAL_ALIGN_BEGINNING));

        bindtableViewer = new TableViewer(group);
        bindtableViewer.setLabelProvider(new ComponentLabelProvider(getEditor(), Messages));
        bindtableViewer.setContentProvider(new ArrayContentProvider());
        bindtableViewer.setInput(application.getBindingTables());
        bindtableViewer.addSelectionChangedListener(
            new ISelectionChangedListener() {

              public void selectionChanged(SelectionChangedEvent event) {
                setPageComplete(isPageComplete());
              }
            });
        bindtableViewer.setSelection(
            new StructuredSelection(application.getBindingTables().get(0)));
        GridData gd = new GridData(GridData.FILL_BOTH);
        gd.heightHint = bindtableViewer.getTable().getItemHeight() * 5;
        bindtableViewer.getControl().setLayoutData(gd);
        bindtableViewer.getControl().setEnabled(false);
      }

      setControl(group);
    }

    @Override
    public boolean isPageComplete() {
      if (keyField.getText().trim().length() == 0) {
        return true;
      } else {
        return !bindtableViewer.getSelection().isEmpty();
      }
    }
  }

  class MenuWizardPage extends WizardPage {
    private MApplication application;
    private Text labelField;
    private Text iconField;
    private ComboViewer typeViewer;
    private TableViewer menuViewer;

    public MenuWizardPage(String pageName, MApplication application) {
      super(pageName);
      this.application = application;
    }

    public void createControl(Composite parent) {
      setTitle("Handled Menu Item");
      setMessage("Insert informations for a Handled Menu Item");

      Composite group = new Composite(parent, SWT.NONE);
      group.setLayout(new GridLayout(2, false));
      group.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));

      {
        Label l = new Label(group, SWT.NONE);
        l.setText("Label");

        labelField = new Text(group, SWT.BORDER);
        labelField.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
      }

      {
        Label l = new Label(group, SWT.NONE);
        l.setText("Icon");

        iconField = new Text(group, SWT.BORDER);
        iconField.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
      }

      {
        Label l = new Label(group, SWT.NONE);
        l.setText("Type");

        typeViewer = new ComboViewer(group, SWT.READ_ONLY);
        typeViewer.setContentProvider(new ArrayContentProvider());
        typeViewer.setInput(ItemType.values());
        typeViewer.setSelection(new StructuredSelection(ItemType.PUSH));
      }

      {
        Label l = new Label(group, SWT.NONE);
        l.setText("Parent");
        l.setLayoutData(new GridData(GridData.VERTICAL_ALIGN_BEGINNING));

        menuViewer = new TableViewer(group);
        menuViewer.setLabelProvider(new HiearchyLabelProvider());
        menuViewer.setContentProvider(new ArrayContentProvider());

        List<MMenu> menuList = new ArrayList<MMenu>();
        Iterator<EObject> it = EcoreUtil.getAllContents(Collections.singleton(application));
        while (it.hasNext()) {
          EObject o = it.next();
          if (MenuPackageImpl.Literals.MENU.isSuperTypeOf(o.eClass())) {
            menuList.add((MMenu) o);
          }
        }
        menuViewer.setInput(menuList);
        menuViewer.addSelectionChangedListener(
            new ISelectionChangedListener() {

              public void selectionChanged(SelectionChangedEvent event) {
                setPageComplete(isPageComplete());
              }
            });
        GridData gd = new GridData(GridData.FILL_BOTH);
        gd.heightHint = menuViewer.getTable().getItemHeight() * 5;
        menuViewer.getControl().setLayoutData(gd);
        menuViewer.setSelection(new StructuredSelection(menuList.get(0)));
      }

      setControl(group);
    }

    @Override
    public boolean isPageComplete() {
      if (labelField.getText().trim().length() == 0 && iconField.getText().trim().length() == 0) {
        return true;
      } else {
        return !menuViewer.getSelection().isEmpty();
      }
    }
  }

  class ToolbarWizardPage extends WizardPage {
    private MApplication application;
    private Text labelField;
    private Text iconField;
    private ComboViewer typeViewer;
    private TableViewer toolbarViewer;

    public ToolbarWizardPage(String pageName, MApplication application) {
      super(pageName);
      this.application = application;
    }

    public void createControl(Composite parent) {
      setTitle("Handled Toolbar Item");
      setMessage("Insert informations for a Toolbar Item");

      Composite group = new Composite(parent, SWT.NONE);
      group.setLayoutData(new GridData(GridData.FILL, GridData.BEGINNING, true, false, 2, 1));
      group.setLayout(new GridLayout(2, false));

      {
        Label l = new Label(group, SWT.NONE);
        l.setText("Label");

        labelField = new Text(group, SWT.BORDER);
        labelField.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
      }

      {
        Label l = new Label(group, SWT.NONE);
        l.setText("Icon");

        iconField = new Text(group, SWT.BORDER);
        iconField.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
      }

      {
        Label l = new Label(group, SWT.NONE);
        l.setText("Type");

        typeViewer = new ComboViewer(group, SWT.READ_ONLY);
        // viewer.setLabelProvider(labelProvider)
        typeViewer.setContentProvider(new ArrayContentProvider());
        typeViewer.setInput(ItemType.values());
      }

      {
        Label l = new Label(group, SWT.NONE);
        l.setText("Parent");
        l.setLayoutData(new GridData(GridData.VERTICAL_ALIGN_BEGINNING));

        toolbarViewer = new TableViewer(group);
        toolbarViewer.setLabelProvider(new HiearchyLabelProvider());
        toolbarViewer.setContentProvider(new ArrayContentProvider());

        List<MToolBar> toolbarList = new ArrayList<MToolBar>();
        Iterator<EObject> it = EcoreUtil.getAllContents(Collections.singleton(application));
        while (it.hasNext()) {
          EObject o = it.next();
          if (MenuPackageImpl.Literals.TOOL_BAR.isSuperTypeOf(o.eClass())) {
            toolbarList.add((MToolBar) o);
          }
        }
        toolbarViewer.setInput(toolbarList);
        toolbarViewer.addSelectionChangedListener(
            new ISelectionChangedListener() {

              public void selectionChanged(SelectionChangedEvent event) {
                setPageComplete(isPageComplete());
              }
            });
        GridData gd = new GridData(GridData.FILL_BOTH);
        gd.heightHint = toolbarViewer.getTable().getItemHeight() * 5;
        toolbarViewer.getControl().setLayoutData(gd);
        toolbarViewer.setSelection(new StructuredSelection(toolbarList.get(0)));
      }

      setControl(group);
    }

    @Override
    public boolean isPageComplete() {
      if (labelField.getText().trim().length() == 0 && iconField.getText().trim().length() == 0) {
        return true;
      } else {
        return !toolbarViewer.getSelection().isEmpty();
      }
    }
  }

  class HiearchyLabelProvider extends StyledCellLabelProvider {

    @Override
    public void update(ViewerCell cell) {
      EObject o = (EObject) cell.getElement();

      String label = ""; // $NON-NLS-1$
      Image img = null;
      AbstractComponentEditor elementEditor = getEditor().getEditor(o.eClass());
      if (elementEditor != null) {
        label = elementEditor.getDetailLabel(o);
        label = label == null ? elementEditor.getLabel(o) : label;
        img = elementEditor.getImage(o, composite.getDisplay());
      }

      List<String> parentPath = new ArrayList<String>();
      while (o.eContainer() != null) {
        o = o.eContainer();
        elementEditor = getEditor().getEditor(o.eClass());
        if (elementEditor != null) {
          parentPath.add(0, elementEditor.getLabel(o));
        }
      }

      String parentString = ""; // $NON-NLS-1$
      for (String p : parentPath) {
        parentString += "/" + p; // $NON-NLS-1$
      }

      StyledString s = new StyledString(label);
      s.append(" - " + parentString, StyledString.DECORATIONS_STYLER); // $NON-NLS-1$
      cell.setStyleRanges(s.getStyleRanges());
      cell.setText(s.getString());
      cell.setImage(img);
    }
  }
}