/**
   * Corresponds to ticket #1811. Check that after a creation of a diagram with ports (on node) from
   * the model content view , the layoutConstraint of all ports is not {0, 0}.
   */
  public void testPortLocationForCreationFromModelContentView() {

    // Get the desired package
    final Model model = (Model) semanticModel;
    assertNotNull("Corrupted input data", model);
    // Get the diagram for the root of this model.
    diagram = (DDiagram) createRepresentation(NODE_REPRESENTATION_DESC_NAME, model);
    // Get the class named "Class2"
    PackageableElement element = model.getPackagedElement("Class2");
    assertTrue("Corrupted input data", element instanceof Class);
    final Class class2 = (Class) element;

    // Get the class named "Class3"
    element = model.getPackagedElement("Class3");
    assertTrue("Corrupted input data", element instanceof Class);
    final Class class3 = (Class) element;

    final Property firstProperty = class3.getOwnedAttribute("Prop3to2", class2);
    final Property secondProperty = class3.getOwnedAttribute("OtherProp3to2", class2);

    // Open the editor (and refresh it)
    final IEditorPart editorPart =
        DialectUIManager.INSTANCE.openEditor(session, diagram, new NullProgressMonitor());
    TestsUtil.synchronizationWithUIThread();

    final DDiagramElement firstPropertyDiagramElement =
        getFirstDiagramElement(diagram, firstProperty);
    assertNotNull(
        "The first property has no corresponding diagramElement", firstPropertyDiagramElement);
    final Node firstPropertyNode = getGmfNode(firstPropertyDiagramElement);
    assertNotNull("The first property has no corresponding GMF node", firstPropertyNode);
    assertTrue(
        "Bag layout constraint type", firstPropertyNode.getLayoutConstraint() instanceof Location);
    final Location firstLocation = (Location) firstPropertyNode.getLayoutConstraint();
    final DDiagramElement secondPropertyDiagramElement =
        getFirstDiagramElement(diagram, secondProperty);
    assertNotNull(
        "The second property has no corresponding diagramElement", secondPropertyDiagramElement);
    final Node secondPropertyNode = getGmfNode(secondPropertyDiagramElement);
    assertNotNull("The second property has no corresponding GMF node", secondPropertyNode);
    assertTrue(
        "Bag layout constraint type", secondPropertyNode.getLayoutConstraint() instanceof Location);
    final Location secondLocation = (Location) secondPropertyNode.getLayoutConstraint();

    assertFalse(
        "All the layout constraints of the ports should not be in {0,0}",
        firstLocation.getX() == 0
            && firstLocation.getY() == 0
            && secondLocation.getX() == 0
            && secondLocation.getY() == 0);
    assertTrue(
        "All the layout constraints of the ports should be different",
        firstLocation.getX() != secondLocation.getX()
            || firstLocation.getY() != secondLocation.getY());

    DialectUIManager.INSTANCE.closeEditor(editorPart, false);
    TestsUtil.synchronizationWithUIThread();
  }
 @Override
 protected void executeCurrentCommand() {
   FiguresHelper.AVOID_OVERLAP_ENABLE = false;
   super.executeCurrentCommand();
   FiguresHelper.AVOID_OVERLAP_ENABLE = true;
   CompoundCommand cc = new CompoundCommand("Check Overlap");
   for (IGraphicalEditPart ep : _movingShapes) {
     Location loc = (Location) ((Node) ep.getNotationView()).getLayoutConstraint();
     Point oldLoc = new Point(loc.getX(), loc.getY());
     Point newLoc =
         FiguresHelper.handleCompartmentMargin(
             ep, loc.getX(), loc.getY(), (ep.resolveSemanticElement() instanceof SubProcessEvent));
     if ((newLoc.x != 0 && newLoc.y != 0) && !newLoc.equals(oldLoc)) {
       cc.add(
           new ICommandProxy(
               new SetBoundsCommand(
                   _container.getEditingDomain(),
                   "Check Overlap",
                   new EObjectAdapter(ep.getNotationView()),
                   newLoc)));
     }
   }
   executeCommand(cc);
 }
 /** @generated */
 protected void refreshSemantic() {
   if (resolveSemanticElement() == null) {
     return;
   }
   LinkedList<IAdaptable> createdViews = new LinkedList<IAdaptable>();
   List<UMLNodeDescriptor> childDescriptors =
       UMLDiagramUpdater.getStateMachine_2000SemanticChildren((View) getHost().getModel());
   LinkedList<View> orphaned = new LinkedList<View>();
   // we care to check only views we recognize as ours
   LinkedList<View> knownViewChildren = new LinkedList<View>();
   for (View v : getViewChildren()) {
     if (isMyDiagramElement(v)) {
       knownViewChildren.add(v);
     }
   }
   // alternative to #cleanCanonicalSemanticChildren(getViewChildren(), semanticChildren)
   HashMap<UMLNodeDescriptor, LinkedList<View>> potentialViews =
       new HashMap<UMLNodeDescriptor, LinkedList<View>>();
   //
   // iteration happens over list of desired semantic elements, trying to find best matching View,
   // while original CEP
   // iterates views, potentially losing view (size/bounds) information - i.e. if there are few
   // views to reference same EObject, only last one
   // to answer isOrphaned == true will be used for the domain element representation, see
   // #cleanCanonicalSemanticChildren()
   for (Iterator<UMLNodeDescriptor> descriptorsIterator = childDescriptors.iterator();
       descriptorsIterator.hasNext(); ) {
     UMLNodeDescriptor next = descriptorsIterator.next();
     String hint = UMLVisualIDRegistry.getType(next.getVisualID());
     LinkedList<View> perfectMatch =
         new LinkedList<View>(); // both semanticElement and hint match that of NodeDescriptor
     LinkedList<View> potentialMatch =
         new LinkedList<View>(); // semanticElement matches, hint does not
     for (View childView : getViewChildren()) {
       EObject semanticElement = childView.getElement();
       if (next.getModelElement().equals(semanticElement)) {
         if (hint.equals(childView.getType())) {
           perfectMatch.add(childView);
           // actually, can stop iteration over view children here, but
           // may want to use not the first view but last one as a 'real' match (the way original
           // CEP does
           // with its trick with viewToSemanticMap inside #cleanCanonicalSemanticChildren
         } else {
           potentialMatch.add(childView);
         }
       }
     }
     if (perfectMatch.size() > 0) {
       descriptorsIterator
           .remove(); // precise match found no need to create anything for the NodeDescriptor
       // use only one view (first or last?), keep rest as orphaned for further consideration
       knownViewChildren.remove(perfectMatch.getFirst());
     } else if (potentialMatch.size() > 0) {
       potentialViews.put(next, potentialMatch);
     }
   }
   // those left in knownViewChildren are subject to removal - they are our diagram elements we
   // didn't find match to,
   // or those we have potential matches to, and thus need to be recreated, preserving
   // size/location information.
   orphaned.addAll(knownViewChildren);
   //
   CompositeTransactionalCommand boundsCommand =
       new CompositeTransactionalCommand(
           host().getEditingDomain(), DiagramUIMessages.SetLocationCommand_Label_Resize);
   ArrayList<CreateViewRequest.ViewDescriptor> viewDescriptors =
       new ArrayList<CreateViewRequest.ViewDescriptor>(childDescriptors.size());
   for (UMLNodeDescriptor next : childDescriptors) {
     String hint = UMLVisualIDRegistry.getType(next.getVisualID());
     IAdaptable elementAdapter = new CanonicalElementAdapter(next.getModelElement(), hint);
     CreateViewRequest.ViewDescriptor descriptor =
         new CreateViewRequest.ViewDescriptor(
             elementAdapter,
             Node.class,
             hint,
             ViewUtil.APPEND,
             false,
             host().getDiagramPreferencesHint());
     viewDescriptors.add(descriptor);
     LinkedList<View> possibleMatches = potentialViews.get(next);
     if (possibleMatches != null) {
       // from potential matches, leave those that were not eventually used for some other
       // NodeDescriptor (i.e. those left as orphaned)
       possibleMatches.retainAll(knownViewChildren);
     }
     if (possibleMatches != null && !possibleMatches.isEmpty()) {
       View originalView = possibleMatches.getFirst();
       knownViewChildren.remove(
           originalView); // remove not to copy properties of the same view again and again
       // add command to copy properties
       if (originalView instanceof Node) {
         if (((Node) originalView).getLayoutConstraint() instanceof Bounds) {
           Bounds b = (Bounds) ((Node) originalView).getLayoutConstraint();
           boundsCommand.add(
               new SetBoundsCommand(
                   boundsCommand.getEditingDomain(),
                   boundsCommand.getLabel(),
                   descriptor,
                   new Rectangle(b.getX(), b.getY(), b.getWidth(), b.getHeight())));
         } else if (((Node) originalView).getLayoutConstraint() instanceof Location) {
           Location l = (Location) ((Node) originalView).getLayoutConstraint();
           boundsCommand.add(
               new SetBoundsCommand(
                   boundsCommand.getEditingDomain(),
                   boundsCommand.getLabel(),
                   descriptor,
                   new Point(l.getX(), l.getY())));
         } else if (((Node) originalView).getLayoutConstraint() instanceof Size) {
           Size s = (Size) ((Node) originalView).getLayoutConstraint();
           boundsCommand.add(
               new SetBoundsCommand(
                   boundsCommand.getEditingDomain(),
                   boundsCommand.getLabel(),
                   descriptor,
                   new Dimension(s.getWidth(), s.getHeight())));
         }
       }
     }
   }
   boolean changed = deleteViews(orphaned.iterator());
   //
   CreateViewRequest request = getCreateViewRequest(viewDescriptors);
   Command cmd = getCreateViewCommand(request);
   if (cmd != null && cmd.canExecute()) {
     SetViewMutabilityCommand.makeMutable(new EObjectAdapter(host().getNotationView())).execute();
     executeCommand(cmd);
     if (boundsCommand.canExecute()) {
       executeCommand(new ICommandProxy(boundsCommand.reduce()));
     }
     @SuppressWarnings("unchecked")
     List<IAdaptable> nl = (List<IAdaptable>) request.getNewObject();
     createdViews.addAll(nl);
   }
   if (changed || createdViews.size() > 0) {
     postProcessRefreshSemantic(createdViews);
   }
   if (createdViews.size() > 1) {
     // perform a layout of the container
     DeferredLayoutCommand layoutCmd =
         new DeferredLayoutCommand(host().getEditingDomain(), createdViews, host());
     executeCommand(new ICommandProxy(layoutCmd));
   }
   makeViewsImmutable(createdViews);
 }
  /**
   * Open the diagram, modify the semantic (causing creation of new ports), check the position of
   * new ports (not the same). See VP-3095
   */
  protected void testPortLocationAfterRefresh(boolean activateCollapseFilter) {
    // Get the desired package
    final Model model = (Model) semanticModel;
    assertNotNull("Corrupted input data", model);
    // Get the diagram for the root of this model.
    diagram = (DDiagram) createRepresentation(NODE_REPRESENTATION_DESC_NAME, model);
    // Get the class named "Class2"
    PackageableElement element = model.getPackagedElement("Class2");
    assertTrue("Corrupted input data", element instanceof Class);
    final Class class2 = (Class) element;

    // Get the class named "Class3"
    element = model.getPackagedElement("Class3");
    assertTrue("Corrupted input data", element instanceof Class);
    final Class class3 = (Class) element;

    final Property firstProperty = class3.getOwnedAttribute("Prop3to2", class2);
    final Property secondProperty = class3.getOwnedAttribute("OtherProp3to2", class2);

    // Open the editor (and refresh it)
    final IEditorPart editorPart =
        DialectUIManager.INSTANCE.openEditor(session, diagram, new NullProgressMonitor());
    TestsUtil.synchronizationWithUIThread();

    if (activateCollapseFilter) {
      activateFilter(diagram, "FilterPropertyStartingWithA");
    }

    // Add 3 Property to class3 (that will cause the creation of 3
    // new ports during refresh).
    addProperties(class3, class2, "Prop3to2_", 3);
    // Refresh the diagram
    refresh(diagram);

    final DDiagramElement firstPropertyDiagramElement =
        getFirstDiagramElement(diagram, firstProperty);
    assertNotNull(
        "The first property has no corresponding diagramElement", firstPropertyDiagramElement);
    final Node firstPropertyNode = getGmfNode(firstPropertyDiagramElement);
    assertNotNull("The first property has no corresponding GMF node", firstPropertyNode);
    assertTrue(
        "Bag layout constraint type", firstPropertyNode.getLayoutConstraint() instanceof Location);
    final Location firstLocation = (Location) firstPropertyNode.getLayoutConstraint();
    final DDiagramElement secondPropertyDiagramElement =
        getFirstDiagramElement(diagram, secondProperty);
    assertNotNull(
        "The second property has no corresponding diagramElement", secondPropertyDiagramElement);
    final Node secondPropertyNode = getGmfNode(secondPropertyDiagramElement);
    assertNotNull("The second property has no corresponding GMF node", secondPropertyNode);
    assertTrue(
        "Bag layout constraint type", secondPropertyNode.getLayoutConstraint() instanceof Location);
    final Location secondLocation = (Location) secondPropertyNode.getLayoutConstraint();

    assertFalse(
        "All the layout constraints of the ports should not be in {0,0}",
        firstLocation.getX() == 0
            && firstLocation.getY() == 0
            && secondLocation.getX() == 0
            && secondLocation.getY() == 0);
    assertTrue(
        "All the layout constraints of the ports should be different",
        firstLocation.getX() != secondLocation.getX()
            || firstLocation.getY() != secondLocation.getY());

    final Property thirdProperty = class3.getOwnedAttribute("Prop3to2_1", class2);
    final Property fourthProperty = class3.getOwnedAttribute("Prop3to2_2", class2);
    final Property fifthProperty = class3.getOwnedAttribute("Prop3to2_3", class2);
    final DDiagramElement thirdPropertyDiagramElement =
        getFirstDiagramElement(diagram, thirdProperty);
    assertNotNull(
        "The third property has no corresponding diagramElement", thirdPropertyDiagramElement);
    final Node thirdPropertyNode = getGmfNode(thirdPropertyDiagramElement);
    assertNotNull("The third property has no corresponding GMF node", thirdPropertyNode);
    assertTrue(
        "Bag layout constraint type", thirdPropertyNode.getLayoutConstraint() instanceof Location);
    final Location thirdLocation = (Location) thirdPropertyNode.getLayoutConstraint();
    final DDiagramElement fourthPropertyDiagramElement =
        getFirstDiagramElement(diagram, fourthProperty);
    assertNotNull(
        "The fourth property has no corresponding diagramElement", fourthPropertyDiagramElement);
    final Node fourthPropertyNode = getGmfNode(fourthPropertyDiagramElement);
    assertNotNull("The fourth property has no corresponding GMF node", fourthPropertyNode);
    assertTrue(
        "Bag layout constraint type", fourthPropertyNode.getLayoutConstraint() instanceof Location);
    final Location fourthLocation = (Location) fourthPropertyNode.getLayoutConstraint();
    final DDiagramElement fifthPropertyDiagramElement =
        getFirstDiagramElement(diagram, fifthProperty);
    assertNotNull(
        "The fifth property has no corresponding diagramElement", fifthPropertyDiagramElement);
    final Node fifthPropertyNode = getGmfNode(fifthPropertyDiagramElement);
    assertNotNull("The fifth property has no corresponding GMF node", fifthPropertyNode);
    assertTrue(
        "Bag layout constraint type", fifthPropertyNode.getLayoutConstraint() instanceof Location);
    final Location fifthLocation = (Location) fifthPropertyNode.getLayoutConstraint();

    assertFalse(
        "All the layout constraints of the ports should not be in {0,0}",
        thirdLocation.getX() == 0
            && thirdLocation.getY() == 0
            && fourthLocation.getX() == 0
            && fourthLocation.getY() == 0
            && fifthLocation.getX() == 0
            && fifthLocation.getY() == 0);
    assertTrue(
        "All the layout constraints of the ports should be different",
        thirdLocation.getX() != fourthLocation.getX()
            || thirdLocation.getY() != fourthLocation.getY());
    assertTrue(
        "All the layout constraints of the ports should be different",
        thirdLocation.getX() != fifthLocation.getX()
            || thirdLocation.getY() != fifthLocation.getY());
    assertTrue(
        "All the layout constraints of the ports should be different",
        fifthLocation.getX() != fourthLocation.getX()
            || fifthLocation.getY() != fourthLocation.getY());

    DialectUIManager.INSTANCE.closeEditor(editorPart, false);
    TestsUtil.synchronizationWithUIThread();
  }
  /**
   * Corresponds to ticket #1811. Check that after a creation of a diagram with ports from an
   * existing diagram, the layoutConstraint of all ports is not {0, 0}.
   */
  public void testPortLocationForCreationFromNavigation() {
    // Get the desired package
    final Model model = (Model) semanticModel;
    assertNotNull("Corrupted input data", model);
    // Get the diagram for the root of this model.
    diagram = (DDiagram) createRepresentation(NODE_REPRESENTATION_DESC_NAME, model);

    // Open the editor (and refresh it)
    final IEditorPart editorPart =
        DialectUIManager.INSTANCE.openEditor(session, diagram, new NullProgressMonitor());
    TestsUtil.synchronizationWithUIThread();

    // Set the focus to the desired package
    assertTrue(
        "We should have a DiagramDocumentEditor", editorPart instanceof DiagramDocumentEditor);

    final DiagramDocumentEditor diagramEditor = (DiagramDocumentEditor) editorPart;

    // Get the package named "SubPackage"
    PackageableElement element = model.getPackagedElement("SubPackage");
    assertTrue("Corrupted input data", element instanceof Package);
    final Package packageSubPackage = (Package) element;

    IMenuManager popupMenu = new MenuManager();
    popupMenu.add(
        new MenuManager(
            IWorkbenchActionConstants.MB_ADDITIONS,
            IWorkbenchActionConstants.MB_ADDITIONS)); // $NON-NLS-1$ //$NON-NLS-2$
    popupMenu.add(new MenuManager("popup.new", "popup.new")); // $NON-NLS-1$

    // Set the focus to package SubPackage
    IGraphicalEditPart elementEditPart =
        getEditPart(getFirstDiagramElement(diagram, packageSubPackage));
    diagramEditor.getDiagramGraphicalViewer().setFocus(elementEditPart);

    DNode focusedElement =
        (DNode)
            ((GraphicalEditPart) diagramEditor.getDiagramGraphicalViewer().getFocusEditPart())
                .resolveSemanticElement();
    assertTrue(
        "This is not the good focused element", focusedElement.getTarget() instanceof Package);
    assertEquals(
        "This is not the good focused element",
        "SubPackage",
        ((Package) focusedElement.getTarget()).getName());

    ContributionItemService.getInstance().contributeToPopupMenu(popupMenu, diagramEditor);

    // Check the popup menu.
    IMenuManager newRepresentationMenu = (IMenuManager) popupMenu.find("popup.new");
    IContributionItem[] items = newRepresentationMenu.getItems();

    boolean inNewRepresentationToGroup = false;

    ActionContributionItem actionContribution = null;

    for (int i = 0; i < items.length; i++) {
      if (items[i] instanceof Separator) {
        Separator sep = (Separator) items[i];
        if ("createRepresentationGroup".equals(sep.getId())) {
          inNewRepresentationToGroup = true;
        } else {
          inNewRepresentationToGroup = false;
        }
      }
      if (inNewRepresentationToGroup && items[i] instanceof ActionContributionItem) {
        assertNull("There should be only one ActionContributionItem", actionContribution);
        actionContribution = (ActionContributionItem) items[i];
      }
    }

    assertNotNull("There should be one ActionContributionItem", actionContribution);
    final IAction action = actionContribution.getAction();

    assertEquals("Action has not the correct text", "New diagram", action.getText());

    // Disabling ui callback of diagram command factory
    final Object adapter = diagramEditor.getAdapter(IDiagramCommandFactoryProvider.class);
    final IDiagramCommandFactoryProvider diagramCmdFactoryProvider =
        (IDiagramCommandFactoryProvider) adapter;
    final IDiagramCommandFactory diagramCommandFactory =
        diagramCmdFactoryProvider.getCommandFactory(session.getTransactionalEditingDomain());
    diagramCommandFactory.setUserInterfaceCallBack(new NoUICallback());

    action.run();

    IEditorPart editor2 =
        PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getActiveEditor();
    assertTrue("We should have a DiagramDocumentEditor", editor2 instanceof DiagramDocumentEditor);

    final DiagramDocumentEditor diagramEditor2 = (DiagramDocumentEditor) editor2;
    GraphicalEditPart diagramPart = (GraphicalEditPart) diagramEditor2.getDiagramEditPart();
    final DSemanticDiagram diagram2 = (DSemanticDiagram) diagramPart.resolveSemanticElement();

    assertEquals(
        "The opened diagram is not valid", diagram2.getTarget(), focusedElement.getTarget());

    // Get the class named "SubClass1"
    element = packageSubPackage.getPackagedElement("SubClass1");
    assertTrue("Corrupted input data", element instanceof Class);
    final Class subClass1 = (Class) element;

    final Property firstProperty = subClass1.getOwnedAttribute("Prop1", subClass1);
    final Property secondProperty = subClass1.getOwnedAttribute("Prop2", subClass1);

    final DDiagramElement firstPropertyDiagramElement =
        getFirstDiagramElement(diagram2, firstProperty);
    assertNotNull(
        "The first property has no corresponding diagramElement", firstPropertyDiagramElement);
    final Node firstPropertyNode = getGmfNode(firstPropertyDiagramElement);
    assertNotNull("The first property has no corresponding GMF node", firstPropertyNode);
    assertTrue(
        "Bag layout constraint type", firstPropertyNode.getLayoutConstraint() instanceof Location);
    final Location firstLocation = (Location) firstPropertyNode.getLayoutConstraint();
    final DDiagramElement secondPropertyDiagramElement =
        getFirstDiagramElement(diagram2, secondProperty);
    assertNotNull(
        "The second property has no corresponding diagramElement", secondPropertyDiagramElement);
    final Node secondPropertyNode = getGmfNode(secondPropertyDiagramElement);
    assertNotNull("The second property has no corresponding GMF node", secondPropertyNode);
    assertTrue(
        "Bag layout constraint type", secondPropertyNode.getLayoutConstraint() instanceof Location);
    final Location secondLocation = (Location) secondPropertyNode.getLayoutConstraint();

    assertFalse(
        "All the layout constraints of the ports should not be in {0,0}",
        firstLocation.getX() == 0
            && firstLocation.getY() == 0
            && secondLocation.getX() == 0
            && secondLocation.getY() == 0);
    assertTrue(
        "All the layout constraints of the ports should be different",
        firstLocation.getX() != secondLocation.getX()
            || firstLocation.getY() != secondLocation.getY());

    DialectUIManager.INSTANCE.closeEditor(editorPart, false);
    TestsUtil.synchronizationWithUIThread();

    DialectUIManager.INSTANCE.closeEditor(editor2, false);
    TestsUtil.synchronizationWithUIThread();
  }