/**
   * Computes actual grid specification (origin + single cell width and height) in the coordinates
   * relative to the diagram content pane.
   *
   * <p>This specification depends only on the grid-relative properties stored in the {@link
   * EditPartViewer}, so client may cache it and rely on {@link
   * EditPartViewer#addPropertyChangeListener(PropertyChangeListener)}
   *
   * @param viewer
   * @return grid specification in the coordinate system relative to diagram content pane, or <code>
   *     null</code> if grid is not enabled
   */
  private static PrecisionRectangle getRelativeGridSpec(EditPartViewer viewer) {
    Boolean enabled = (Boolean) viewer.getProperty(SnapToGrid.PROPERTY_GRID_ENABLED);
    if (enabled == null || !enabled) {
      return null;
    }
    double gridX = 0;
    double gridY = 0;
    Dimension spacing = (Dimension) viewer.getProperty(SnapToGrid.PROPERTY_GRID_SPACING);
    if (spacing != null) {
      gridX = spacing.preciseWidth();
      gridY = spacing.preciseHeight();
    }
    if (gridX <= 0) {
      gridX = SnapToGrid.DEFAULT_GRID_SIZE;
    }
    if (gridY <= 0) {
      gridY = SnapToGrid.DEFAULT_GRID_SIZE;
    }
    Point origin = (Point) viewer.getProperty(SnapToGrid.PROPERTY_GRID_ORIGIN);
    PrecisionRectangle result =
        new PrecisionRectangle( //
            origin == null ? 0 : origin.preciseX(),
            origin == null ? 0 : origin.preciseY(),
            gridX,
            gridY);

    return result;
  }
  public void testCopyToImageActionEnablement() throws Exception {

    getTestFixture().openDiagram();

    List children = getTestFixture().getDiagramEditPart().getChildren();

    CircuitEditPart circuitEP = null;
    ListIterator li = children.listIterator();
    while (li.hasNext()) {
      Object ep = li.next();
      if (ep instanceof CircuitEditPart) {
        circuitEP = (CircuitEditPart) ep;
      }
    }

    assertNotNull(circuitEP);

    CopyToImageAction action = new CopyToImageAction(getWorkbenchPage());
    action.init();
    EditPartViewer viewer = getDiagramEditPart().getRoot().getViewer();
    viewer.deselectAll();
    viewer.select(getDiagramEditPart());
    flushEventQueue();
    assertTrue(action.isEnabled());

    viewer.deselectAll();
    viewer.select(circuitEP);
    flushEventQueue();
    assertTrue(action.isEnabled());
  }
  protected void configureEditPartViewer(EditPartViewer viewer) {
    ScalableFreeformRootEditPart rootEditPart = new ScalableFreeformRootEditPart();
    viewer.setRootEditPart(rootEditPart);
    getGraphicalViewer()
        .setContextMenu(
            new ProcessContextMenuProvider(
                getParentEditor().getActionRegistry(), getGraphicalViewer()));

    ((FigureCanvas) viewer.getControl()).setScrollBarVisibility(FigureCanvas.ALWAYS);
  }
  @Override
  public void mouseDown(MouseEvent e, EditPartViewer viewer) {
    if (viewer.getContents() instanceof ERDiagramEditPart) {
      ERDiagramEditPart editPart = (ERDiagramEditPart) viewer.getContents();
      ERDiagram diagram = (ERDiagram) editPart.getModel();

      diagram.mousePoint = new Point(e.x, e.y);

      editPart.getFigure().translateToRelative(diagram.mousePoint);
    }

    super.mouseDown(e, viewer);
  }
  /** Tests the CTRL-D keystroke which initiates a delete from model action. See Bugzilla 115108. */
  public void testDeleteFromModel() throws Exception {

    getTestFixture().openDiagram();

    LEDEditPart editPartToDelete =
        (LEDEditPart)
            getLogicTestFixture()
                .createShapeUsingTool(LogicSemanticType.LED, new Point(0, 0), getDiagramEditPart());

    List primaryEditParts = getDiagramEditPart().getPrimaryEditParts();

    assertTrue(primaryEditParts.contains(editPartToDelete));

    EObject semanticElement = (EObject) editPartToDelete.getAdapter(EObject.class);
    EObject semanticContainer = semanticElement.eContainer();

    // Select the edit part to be deleted.
    EditPartViewer rootViewer = getDiagramEditPart().getRoot().getViewer();
    rootViewer.deselectAll();
    rootViewer.select(editPartToDelete);

    // Set the preference to not confirm the element deletion.
    ((IPreferenceStore) getDiagramEditPart().getDiagramPreferencesHint().getPreferenceStore())
        .setValue(IPreferenceConstants.PREF_PROMPT_ON_DEL_FROM_MODEL, false);

    // Create the CTRL-D event
    Event e = new Event();
    e.character = (char) 0x4;
    e.keyCode = 100;
    e.stateMask = SWT.CTRL;
    e.widget = editPartToDelete.getViewer().getControl();

    // Simulate the CTRL-D keystroke
    SelectionTool tool = new SelectionTool();
    tool.setEditDomain((EditDomain) getDiagramWorkbenchPart().getDiagramEditDomain());
    tool.activate();
    tool.keyDown(new KeyEvent(e), rootViewer);

    // Verify that the edit part and the semantic element have been deleted.
    primaryEditParts = getDiagramEditPart().getPrimaryEditParts();

    assertFalse(
        "Primary edit part not deleted.",
        primaryEditParts.contains(editPartToDelete)); // $NON-NLS-1$

    assertFalse(
        "Semantic element not deleted.",
        semanticContainer.eContents().contains(semanticElement)); // $NON-NLS-1$
  }
  /** Configure outline viewer. */
  protected void configureOutlineViewer() {
    final EditPartViewer viewer = getViewer();
    viewer.setEditDomain(editor.getEditDomain());
    viewer.setEditPartFactory(getEditPartFactory());
    ContextMenuProvider provider = getMenuContentProvider();
    viewer.setContextMenu(provider);

    viewer.addDropTargetListener(new JSSTemplateTransferDropTargetListener(viewer));
    viewer.addDragSourceListener(
        new TemplateTransferDragSourceListener(viewer) {
          @Override
          protected Object getTemplate() {
            List<Object> models = new ArrayList<Object>();
            Object obj = super.getTemplate();
            if (obj == null) {
              List<?> selection = getViewer().getSelectedEditParts();
              for (Object it : selection) {
                if (it instanceof EditPart) {
                  Object model = ((EditPart) it).getModel();
                  if (model instanceof IDragable) {
                    models.add(model);
                  }
                  if (model instanceof MBand) {
                    BandTypeEnum bandType = ((MBand) model).getBandType();
                    if (BandTypeEnum.DETAIL.equals(bandType)
                        || BandTypeEnum.GROUP_FOOTER.equals(bandType)
                        || BandTypeEnum.GROUP_HEADER.equals(bandType)) {
                      models.add(model);
                    }
                  }
                }
              }
            }
            return models;
          }
        });
    // Add images drop listeners
    viewer.addDropTargetListener(
        new ImageResourceDropTargetListener(viewer, ResourceTransfer.getInstance()));
    viewer.addDropTargetListener(
        new ImageResourceDropTargetListener(viewer, FileTransfer.getInstance()));
    viewer.addDropTargetListener(
        new ImageResourceDropTargetListener(viewer, ImageURLTransfer.getInstance()));

    IPageSite site = getSite();
    site.registerContextMenu(provider.getId(), provider, site.getSelectionProvider());

    IToolBarManager tbm = site.getActionBars().getToolBarManager();
    registerToolbarAction(tbm);

    showPage(ID_ACTION_OUTLINE);
  }
 /**
  * Computes actual grid specification (origin + single cell width and height) in the absolute
  * coordinate system. Note, in contrast to {@link #getRelativeGridSpec(EditPartViewer)} this
  * specification depends on the active zoom or scroll and can't be cached by clients.
  *
  * @param viewer
  * @return absolute grid specification, or <code>null</code> if grid is not enabled
  */
 public static PrecisionRectangle getAbsoluteGridSpec(EditPartViewer viewer) {
   PrecisionRectangle spec = getRelativeGridSpec(viewer);
   if (spec != null) {
     GraphicalEditPart diagramEP = (GraphicalEditPart) viewer.getContents();
     diagramEP.getContentPane().translateToAbsolute(spec);
   }
   return spec;
 }
 /** {@inheritDoc} */
 public List getAffectedFiles() {
   if (viewer != null) {
     EditPart editpart = viewer.getRootEditPart().getContents();
     if (editpart instanceof IGraphicalEditPart) {
       View view = (View) ((IGraphicalEditPart) editpart).getModel();
       if (view != null) {
         IFile f = WorkspaceSynchronizer.getFile(view.eResource());
         return f != null ? Collections.singletonList(f) : Collections.EMPTY_LIST;
       }
     }
   }
   return super.getAffectedFiles();
 }
  public DiagramGridSpec(EditPartViewer viewer) {
    myViewer = viewer;
    myGridListener =
        new GridSpecListener() {

          @Override
          public void gridSpecChanged() {
            myRelativeGridSpec = null;
            myAbsoluteGridSpec = null;
          }
        };
    myViewer.addPropertyChangeListener(myGridListener);
  }
  /**
   * Always returns the same instance to avoid endless creation
   *
   * @return active grid specification in absolute coordinates or <code>null</code> if not enabled
   */
  public PrecisionRectangle getAbsoluteGridSpec() {
    PrecisionRectangle result = getRelativeGridSpec();
    if (result == null) {
      return null;
    }

    if (myAbsoluteGridSpec == null) {
      myAbsoluteGridSpec = new PrecisionRectangle();
    }
    myAbsoluteGridSpec.setPreciseBounds(
        result.preciseX(), result.preciseY(), result.preciseWidth(), result.preciseHeight());
    GraphicalEditPart diagramEP = (GraphicalEditPart) myViewer.getContents();
    diagramEP.getContentPane().translateToAbsolute(myAbsoluteGridSpec);

    return myAbsoluteGridSpec;
  }
  /**
   * Returns the bytes of an encoded image for the specified IFigure in the specified format.
   *
   * @param figure the Figure to create an image for.
   * @param format one of SWT.IMAGE_BMP, SWT.IMAGE_BMP_RLE, SWT.IMAGE_GIF SWT.IMAGE_ICO,
   *     SWT.IMAGE_JPEG, or SWT.IMAGE_PNG
   * @return the bytes of an encoded image for the specified Figure
   */
  private byte[] createImage(final IFigure figure, final int format) {

    final Device device = viewer.getControl().getDisplay();

    final Rectangle r = figure.getBounds();

    final ByteArrayOutputStream result = new ByteArrayOutputStream();

    Image image = null;
    GC gc = null;
    Graphics g = null;
    try {
      image = new Image(device, r.width, r.height);
      gc = new GC(image);
      g = new SWTGraphics(gc);
      g.translate(r.x * -1, r.y * -1);

      figure.paint(g);

      final ImageLoader imageLoader = new ImageLoader();
      imageLoader.data = new ImageData[] {image.getImageData()};
      imageLoader.save(result, format);

    } catch (Exception e) {
      // the image size may not exceed 16M, svg requires less space for graphs than png and jpeg
      e.printStackTrace();
    } finally {
      if (g != null) {
        g.dispose();
      }
      if (gc != null) {
        gc.dispose();
      }
      if (image != null) {
        image.dispose();
      }
    }
    return result.toByteArray();
  }
 public void dispose() {
   myViewer.removePropertyChangeListener(myGridListener);
   myRelativeGridSpec = null;
   myAbsoluteGridSpec = null;
 }
Exemplo n.º 13
0
  public Command dropMutliAssociation(
      Association association,
      EditPartViewer viewer,
      PreferencesHint diagramPreferencesHint,
      Point location,
      View containerView) {
    Command command = new CompoundCommand();
    // 0. Obtain list of property to display
    ArrayList<Property> endToDisplay = new ArrayList(association.getMemberEnds());

    // 1. creatiuon of the diamon of association
    AssociationDiamonViewCreateCommand nodeCreation =
        new AssociationDiamonViewCreateCommand(
            getEditingDomain(),
            containerView,
            viewer,
            diagramPreferencesHint,
            location,
            new SemanticAdapter(association, null));
    ((CompoundCommand) command).add(new ICommandProxy(nodeCreation));

    // 2. for each element create a graphical representation of the type and
    // finally the branch
    Iterator<Property> iteratorProp = endToDisplay.iterator();
    int index = 0;
    while (iteratorProp.hasNext()) {
      index += 1;
      // source editPart
      EditPart sourceEditPart = null;
      // end of the association end
      Property currentEnd = iteratorProp.next();

      // look for if an editpart exist for this element
      Collection<EditPart> editPartSet = viewer.getEditPartRegistry().values();
      Iterator<EditPart> editPartIterator = editPartSet.iterator();

      while (editPartIterator.hasNext() && sourceEditPart == null) {

        EditPart currentEditPart = editPartIterator.next();

        if ((!(currentEditPart instanceof CompartmentEditPart))
            && currentEditPart instanceof GraphicalEditPart
            && currentEnd
                .getType()
                .equals(((GraphicalEditPart) currentEditPart).resolveSemanticElement())) {
          sourceEditPart = currentEditPart;
        }
      }
      // descriptor for the branch
      ConnectionViewDescriptor viewBranchDescriptor =
          new ConnectionViewDescriptor(
              UMLElementTypes.Association_4019,
              ((IHintedType) UMLElementTypes.Association_4019).getSemanticHint(),
              diagramPreferencesHint);

      // the editpart exist -> only creation of the branch
      if (sourceEditPart != null) {

        GraphicalAssociationBranchViewCommand aBranchCommand =
            new GraphicalAssociationBranchViewCommand(
                getEditingDomain(),
                (IAdaptable) nodeCreation.getCommandResult().getReturnValue(),
                new SemanticAdapter(null, sourceEditPart.getModel()),
                sourceEditPart.getViewer(),
                ((IGraphicalEditPart) sourceEditPart).getDiagramPreferencesHint(),
                viewBranchDescriptor,
                currentEnd);

        // CustomDeferredCreateConnectionViewCommand aBranchCommand = new
        // CustomDeferredCreateConnectionViewCommand(getEditingDomain(),
        // ((IHintedType)UMLElementTypes.Association_4019).getSemanticHint(),
        // (IAdaptable)nodeCreation.getCommandResult().getReturnValue(), new SemanticAdapter(null,
        // sourceEditPart.getModel()), sourceEditPart.getViewer(),
        // ((IGraphicalEditPart)sourceEditPart).getDiagramPreferencesHint(), viewBranchDescriptor,
        // null);

        aBranchCommand.setElement(association);
        ((CompoundCommand) command).add(new ICommandProxy(aBranchCommand));
      } else { // the editpart does not exist

        // creation of the node
        IAdaptable elementAdapter = new EObjectAdapter(currentEnd.getType());
        ViewDescriptor descriptor =
            new ViewDescriptor(
                elementAdapter, Node.class, null, ViewUtil.APPEND, false, diagramPreferencesHint);

        // get the command and execute it.
        CreateCommand nodeCreationCommand =
            new CreateCommand(getEditingDomain(), descriptor, containerView);
        ((CompoundCommand) command).add(new ICommandProxy(nodeCreationCommand));
        SetBoundsCommand setBoundsCommand =
            new SetBoundsCommand(
                getEditingDomain(),
                "move",
                (IAdaptable) nodeCreationCommand.getCommandResult().getReturnValue(),
                new Point(location.x + 200, location.y + index * 100));
        ((CompoundCommand) command).add(new ICommandProxy(setBoundsCommand));
        // Creation of the branch
        GraphicalAssociationBranchViewCommand aBranchCommand =
            new GraphicalAssociationBranchViewCommand(
                getEditingDomain(),
                (IAdaptable) nodeCreation.getCommandResult().getReturnValue(),
                (IAdaptable) nodeCreationCommand.getCommandResult().getReturnValue(),
                viewer,
                diagramPreferencesHint,
                viewBranchDescriptor,
                currentEnd);

        // CustomDeferredCreateConnectionViewCommand aBranchCommand = new
        // CustomDeferredCreateConnectionViewCommand(getEditingDomain(),
        // ((IHintedType)UMLElementTypes.Association_4019).getSemanticHint(),
        // (IAdaptable)nodeCreation.getCommandResult().getReturnValue(),
        // (IAdaptable)nodeCreationCommand.getCommandResult().getReturnValue(), viewer,
        // diagramPreferencesHint, viewBranchDescriptor, null);

        aBranchCommand.setElement(association);
        ((CompoundCommand) command).add(new ICommandProxy(aBranchCommand));
        // creation of the link
      }
    }
    return command;
  }
  /**
   * Ask for a file name and save the viewer containing the currently selected GraphicalEditPart to
   * a image file.
   */
  @Override
  public void run() {
    final IEditorInput editorInput =
        (IEditorInput) getWorkbenchPart().getAdapter(IEditorInput.class);
    final SaveAsDialog dialog = new SaveAsDialog(new Shell(Display.getDefault()));
    dialog.setBlockOnOpen(true);
    if (editorInput == null) {
      dialog.setOriginalName("viewerImage" + counter + ".png");
    } else {
      final String fileName = editorInput.getName();
      final int extensionPos = fileName.lastIndexOf(".");
      dialog.setOriginalName(fileName.substring(0, extensionPos) + ".png");
    }
    dialog.create();
    dialog.setMessage(
        "If you don't choose an extension png will be used a default. "
            + "\n"
            + "Export is limited to file size of 15MByte -> you may use file ..(read more) "
            + "\n"
            + "type svg for very large graphs."
            + "\n"
            + "After export the workspace needs a manual refresh to show new image file.");
    dialog.setTitle("Specify file to export viewer image (png, jpeg, bmp, svg)");
    dialog.open();
    if (Window.CANCEL == dialog.getReturnCode()) {
      return;
    }

    final IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
    final IPath path = root.getLocation().append(dialog.getResult());

    int format;
    final String ext = path.getFileExtension();
    if (ext.equals("png")) {
      format = SWT.IMAGE_PNG;
      // GIFs work only with 8Bit and not with 32 Bits color depth
      //		} else if (ext.equals("gif")) {
      //			format = SWT.IMAGE_GIF;
    } else if (ext.equals("jpeg")) {
      format = SWT.IMAGE_JPEG;
    } else if (ext.equals("bmp")) {
      format = SWT.IMAGE_BMP;
      // } else if (ext.equals("ico")) {
      // format = SWT.IMAGE_ICO;
    } else if (ext.equalsIgnoreCase("svg")) {
      format = SWT.IMAGE_UNDEFINED; // TODO: find a more appropriate constant for representing SVGs
    } else {
      MessageDialog.openError(
          null,
          "Invalid file extension!",
          "The specified extension ("
              + ext
              + ") is not a valid image format extension.\nPlease use png, jpeg, bmp or svg!");
      return;
    }

    IFigure figure = ((SimpleRootEditPart) viewer.getRootEditPart()).getFigure();
    if (figure instanceof Viewport) {
      // This seems to trim the figure to the smallest rectangle containing all child figures
      ((Viewport) figure).setSize(1, 1);
      ((Viewport) figure).validate();
      figure = ((Viewport) figure).getContents();
    }
    if (format == SWT.IMAGE_UNDEFINED) {
      try {
        final File file = path.toFile();
        this.exportToSVG(file, figure);
      } catch (final IOException e) {
        e.printStackTrace();
      }
    } else {
      final byte[] imageCode = createImage(figure, format);
      try {
        final File file = path.toFile();
        final FileOutputStream fos = new FileOutputStream(file);
        fos.write(imageCode);
        fos.flush();
        fos.close();
        counter++;
      } catch (final IOException e) {
        e.printStackTrace();
      }
    }
  }