/** configure geometry */
  private void configureGeometry() {
    GraphicalViewer viewer = getGraphicalViewer();
    viewer.setProperty(SnapToGeometry.PROPERTY_SNAP_ENABLED, true);

    IAction action = new ToggleSnapToGeometryAction(viewer);
    getActionRegistry().registerAction(action);
  }
 @Override
 protected void doExecute() {
   if (designEditor != null) {
     GraphicalViewer graphicalViewer = designEditor.getGraphicalViewer();
     if (graphicalViewer != null && graphicalViewer.getEditPartRegistry() != null) {
       ScalableFreeformRootEditPart rootEditPart =
           (ScalableFreeformRootEditPart)
               graphicalViewer.getEditPartRegistry().get(LayerManager.ID);
       IFigure gridFigure = ((LayerManager) rootEditPart).getLayer(LayerConstants.GRID_LAYER);
       IColorConstant cc =
           StyleUtil.getColorConstant(
               PreferenceManager.getInstance()
                   .loadPreferenceAsString(PreferencesConstants.EDITOR_GRID_COLOR));
       Diagram diagram = designEditor.getDiagramTypeProvider().getDiagram();
       if (cc != null && diagram != null) {
         GraphicsAlgorithm ga = diagram.getGraphicsAlgorithm();
         if (ga != null) {
           ga.setForeground(GraphitiUi.getGaService().manageColor(diagram, cc));
           gridFigure.repaint();
           gridFigure.revalidate();
           designEditor.getDiagramBehavior().refreshContent();
         }
       }
     }
   }
 }
  private void setRuler(RulerProvider provider, int orientation) {
    Object ruler = null;
    if (isRulerVisible && provider != null)
      // provider.getRuler() might return null (at least the API does not
      // prevent that)
      ruler = provider.getRuler();

    if (ruler == null) {
      // Ruler is not visible or is not present
      setRulerContainer(null, orientation);
      // Layout right-away to prevent an empty control from showing
      layout(true);
      return;
    }

    GraphicalViewer container = getRulerContainer(orientation);
    if (container == null) {
      container = createRulerContainer(orientation);
      setRulerContainer(container, orientation);
    }
    if (container.getContents() != ruler) {
      container.setContents(ruler);
      needToLayout = true;
      Display.getCurrent().asyncExec(runnable);
    }
  }
Esempio n. 4
0
  private void refreshGraphicalViewer() {
    IEditorInput input = getEditorInput();
    if (input instanceof IFileEditorInput) {
      try {
        IFile file = ((IFileEditorInput) input).getFile();
        GraphicalViewer viewer = getGraphicalViewer();

        // desirialize
        RootModel newRoot = null;
        try {
          newRoot = DiagramSerializer.deserialize(file.getContents());
        } catch (Exception ex) {
          UMLPlugin.logException(ex);
          return;
        }

        // copy to editing model
        RootModel root = (RootModel) viewer.getContents().getModel();
        root.copyFrom(newRoot);

      } catch (Exception ex) {
        UMLPlugin.logException(ex);
      }
    }
  }
  /** configure key handler */
  private void configureKeyHandler() {
    GraphicalViewer viewer = getGraphicalViewer();

    keyHandler = new KeyHandler();
    //		keyHandler.put(KeyStroke.getPressed('a', 0x61, SWT.COMMAND),
    //	getActionRegistry().getAction(ActionFactory.SELECT_ALL.getId()));
    keyHandler.put(
        KeyStroke.getPressed('s', 0x61, SWT.CTRL),
        getActionRegistry().getAction(ActionFactory.SAVE.getId()));

    keyHandler.put(
        KeyStroke.getPressed('z', 0x7a, SWT.CTRL),
        getActionRegistry().getAction(ActionFactory.UNDO.getId()));
    keyHandler.put(
        KeyStroke.getPressed('z', 0x7a, SWT.CTRL | SWT.SHIFT),
        getActionRegistry().getAction(ActionFactory.REDO.getId()));
    keyHandler.put(
        KeyStroke.getPressed('a', 0x61, SWT.CTRL),
        getActionRegistry().getAction(ActionFactory.SELECT_ALL.getId()));

    keyHandler.put(
        KeyStroke.getPressed(SWT.DEL, 127, 0),
        getActionRegistry().getAction(ActionFactory.DELETE.getId()));
    keyHandler.put(
        KeyStroke.getPressed('+', SWT.KEYPAD_ADD, 0),
        getActionRegistry().getAction(GEFActionConstants.ZOOM_IN));
    keyHandler.put(
        KeyStroke.getPressed('-', SWT.KEYPAD_SUBTRACT, 0),
        getActionRegistry().getAction(GEFActionConstants.ZOOM_IN));

    viewer.setProperty(
        MouseWheelHandler.KeyGenerator.getKey(SWT.NONE), MouseWheelZoomHandler.SINGLETON);
    viewer.setKeyHandler(keyHandler);
  }
  /** configure grid */
  private void configureGrid() {
    GraphicalViewer viewer = getGraphicalViewer();
    viewer.setProperty(SnapToGrid.PROPERTY_GRID_ENABLED, true);
    viewer.setProperty(SnapToGrid.PROPERTY_GRID_VISIBLE, true);

    IAction action = new ToggleGridAction(viewer);
    getActionRegistry().registerAction(action);
  }
 protected GFFigureCanvas getGFCanvas() {
   IEditorReference reference = getGefEditor().getReference();
   final IEditorPart editor = reference.getEditor(true);
   GraphicalViewer graphicalViewer = (GraphicalViewer) editor.getAdapter(GraphicalViewer.class);
   final Control control = graphicalViewer.getControl();
   if (control instanceof GFFigureCanvas) {
     GFFigureCanvas c = (GFFigureCanvas) control;
     return c;
   }
   return null;
 }
 private void setRulerVisibility(boolean isVisible) {
   if (isRulerVisible != isVisible) {
     isRulerVisible = isVisible;
     if (diagramViewer != null) {
       setRuler(
           (RulerProvider) diagramViewer.getProperty(RulerProvider.PROPERTY_HORIZONTAL_RULER),
           PositionConstants.NORTH);
       setRuler(
           (RulerProvider) diagramViewer.getProperty(RulerProvider.PROPERTY_VERTICAL_RULER),
           PositionConstants.WEST);
     }
   }
 }
  @Override
  protected void configureGraphicalViewer() {
    super.configureGraphicalViewer();
    ScalableFreeformRootEditPart rootEditPart = new ScalableFreeformRootEditPart();

    GraphicalViewer viewer = getGraphicalViewer();
    viewer.setRootEditPart(rootEditPart);
    getGraphicalViewer().setEditPartFactory(new WorkDesignerEditPartFactory(getParentEditor()));
    configureEditPartViewer(viewer);
    ((FigureCanvas) viewer.getControl()).setScrollBarVisibility(FigureCanvas.ALWAYS);
    getActionRegistry().registerAction(new ToggleGridAction(getGraphicalViewer()));
    getActionRegistry().registerAction(new ToggleSnapToGeometryAction(getGraphicalViewer()));
  }
  /** {@inheritDoc} */
  @Override
  public void doTask(ERDiagram diagram) throws Exception {
    this.outputDir = getAbsolutePath(this.outputDir);
    this.outputDir = this.outputDir + "/dbdocs/";

    this.log("Output to : " + this.outputDir);

    // 出力ディレクトリの削除
    File dir = new File(outputDir);
    FileUtils.deleteDirectory(dir);

    dir = new File(outputDir + "image");
    dir.mkdirs();

    String outputImageFilePath = this.outputDir + "image/er.png";

    this.log("Output image to : " + outputImageFilePath);

    Image img = null;
    GraphicalViewer viewer = null;

    try {
      viewer = Activator.createGraphicalViewer(diagram);

      int format = ExportToImageAction.getFormatType(outputImageFilePath);

      img = Activator.createImage(viewer);

      ExportToImageManager exportToImageManager =
          new ExportToImageManager(img, format, outputImageFilePath);
      exportToImageManager.doProcess();

      Map<TableView, Location> tableLocationMap =
          ExportToHtmlAction.getTableLocationMap(viewer, diagram);

      ExportToHtmlManager reportManager =
          new ExportToHtmlManager(this.outputDir, diagram, tableLocationMap);

      this.log("Output html beginning...");

      reportManager.doProcess();

    } finally {
      if (viewer != null) {
        viewer.getContents().deactivate();
      }
      if (img != null) {
        img.dispose();
      }
    }
  }
 private void disposeRulerViewer(GraphicalViewer viewer) {
   if (viewer == null) return;
   /*
    * There's a tie from the editor's range model to the RulerViewport (via
    * a listener) to the RulerRootEditPart to the RulerViewer. Break this
    * tie so that the viewer doesn't leak and can be garbage collected.
    */
   RangeModel rModel = new DefaultRangeModel();
   Viewport port = ((FigureCanvas) viewer.getControl()).getViewport();
   port.setHorizontalRangeModel(rModel);
   port.setVerticalRangeModel(rModel);
   rulerEditDomain.removeViewer(viewer);
   viewer.getControl().dispose();
 }
 private void disposeResources() {
   if (diagramViewer != null) diagramViewer.removePropertyChangeListener(propertyListener);
   if (font != null) font.dispose();
   // layoutListener is not being removed from the scroll bars because they
   // are already
   // disposed at this point.
 }
Esempio n. 13
0
 /** @param viewer */
 private void addDndSupport(GraphicalViewer viewer, String type) {
   IExtensionPoint point =
       Platform.getExtensionRegistry().getExtensionPoint(UMLPlugin.PLUGIN_ID, "dnd");
   IExtension[] extensions = point.getExtensions();
   for (int i = 0; i < extensions.length; i++) {
     IExtension extension = extensions[i];
     IConfigurationElement[] elements = extension.getConfigurationElements();
     for (int j = 0; j < elements.length; j++) {
       IConfigurationElement element = elements[j];
       try {
         Object object = element.createExecutableExtension("class");
         if (object instanceof UMLDropTargetListenerFactory) {
           UMLDropTargetListenerFactory factory = (UMLDropTargetListenerFactory) object;
           if (factory.accept(type)) {
             TransferDropTargetListener targetListener = factory.getDropTargetListener(viewer);
             viewer.addDropTargetListener(targetListener);
           }
         }
       } catch (CoreException e) {
         e.printStackTrace();
       } finally {
       }
     }
   }
 }
Esempio n. 14
0
  public PasteAction(IWorkbenchPart part, GraphicalViewer viewer) {
    super(part);

    fGraphicalViewer = viewer;

    setText(Messages.PasteAction_0);
    setId(ActionFactory.PASTE.getId());
    ISharedImages sharedImages = PlatformUI.getWorkbench().getSharedImages();
    setImageDescriptor(sharedImages.getImageDescriptor(ISharedImages.IMG_TOOL_PASTE));
    setDisabledImageDescriptor(
        sharedImages.getImageDescriptor(ISharedImages.IMG_TOOL_PASTE_DISABLED));
    setEnabled(false);

    /** Listen to window activation to udpate Paste Action if clipboard contents has changed */
    getWorkbenchPart()
        .getSite()
        .getWorkbenchWindow()
        .getWorkbench()
        .addWindowListener(windowListener);

    /** Listen to mouse click position so that the Paste Action can paste objects at that point */
    ((GraphicalEditPart) fGraphicalViewer.getRootEditPart())
        .getFigure()
        .addMouseListener(mouseListener);
  }
Esempio n. 15
0
  /** @generated */
  public void activateEditor(IWorkbenchPage aPage, IStructuredSelection aSelection) {
    if (aSelection == null || aSelection.isEmpty()) {
      return;
    }
    if (false == aSelection.getFirstElement() instanceof MIDAbstractNavigatorItem) {
      return;
    }

    MIDAbstractNavigatorItem abstractNavigatorItem =
        (MIDAbstractNavigatorItem) aSelection.getFirstElement();
    View navigatorView = null;
    if (abstractNavigatorItem instanceof MIDNavigatorItem) {
      navigatorView = ((MIDNavigatorItem) abstractNavigatorItem).getView();
    } else if (abstractNavigatorItem instanceof MIDNavigatorGroup) {
      MIDNavigatorGroup navigatorGroup = (MIDNavigatorGroup) abstractNavigatorItem;
      if (navigatorGroup.getParent() instanceof MIDNavigatorItem) {
        navigatorView = ((MIDNavigatorItem) navigatorGroup.getParent()).getView();
      } else if (navigatorGroup.getParent() instanceof IAdaptable) {
        navigatorView = (View) ((IAdaptable) navigatorGroup.getParent()).getAdapter(View.class);
      }
    }
    if (navigatorView == null) {
      return;
    }
    IEditorInput editorInput = getEditorInput(navigatorView.getDiagram());
    IEditorPart editor = aPage.findEditor(editorInput);
    if (editor == null) {
      return;
    }
    aPage.bringToTop(editor);
    if (editor instanceof DiagramEditor) {
      DiagramEditor diagramEditor = (DiagramEditor) editor;
      ResourceSet diagramEditorResourceSet = diagramEditor.getEditingDomain().getResourceSet();
      EObject selectedView =
          diagramEditorResourceSet.getEObject(EcoreUtil.getURI(navigatorView), true);
      if (selectedView == null) {
        return;
      }
      GraphicalViewer graphicalViewer =
          (GraphicalViewer) diagramEditor.getAdapter(GraphicalViewer.class);
      EditPart selectedEditPart =
          (EditPart) graphicalViewer.getEditPartRegistry().get(selectedView);
      if (selectedEditPart != null) {
        graphicalViewer.select(selectedEditPart);
      }
    }
  }
Esempio n. 16
0
 /**
  * In order for the right-click menu to work, this shell must be registered with a view. Register
  * the context menu against the view. Make the view the default.
  *
  * @param view
  */
 public void registerWithView(IViewPart view) {
   this.view = view;
   actionRegistry.registerAction(new RefreshOPIAction(this));
   SingleSourceHelper.registerRCPRuntimeActions(actionRegistry, this);
   OPIRunnerContextMenuProvider contextMenuProvider =
       new OPIRunnerContextMenuProvider(viewer, this);
   getSite().registerContextMenu(contextMenuProvider, viewer);
   viewer.setContextMenu(contextMenuProvider);
 }
Esempio n. 17
0
 protected void initializeGraphicalViewer() {
   GraphicalViewer viewer = getGraphicalViewer();
   IFile file = ((IFileEditorInput) getEditorInput()).getFile();
   RootModel root = null;
   if (file.exists()) {
     try {
       root = DiagramSerializer.deserialize(file.getContents());
       validateModel(root);
     } catch (Exception ex) {
       UMLPlugin.logException(ex);
     }
   }
   if (root == null) {
     root = createInitializeModel();
   }
   viewer.setContents(root);
   addDndSupport(viewer, getDiagramType());
   applyPreferences();
 }
Esempio n. 18
0
 private DisplayModel createDisplayModel() throws Exception {
   displayModel = new DisplayModel(path);
   XMLUtil.fillDisplayModelFromInputStream(ResourceUtil.pathToInputStream(path), displayModel);
   if (macrosInput != null) {
     macrosInput = macrosInput.getCopy();
     macrosInput.getMacrosMap().putAll(displayModel.getMacrosInput().getMacrosMap());
     displayModel.setPropertyValue(AbstractContainerModel.PROP_MACROS, macrosInput);
   }
   viewer.setContents(displayModel);
   displayModel.setViewer(viewer);
   displayModel.setOpiRuntime(this);
   return displayModel;
 }
Esempio n. 19
0
  @Override
  public void dispose() {
    super.dispose();

    getWorkbenchPart()
        .getSite()
        .getWorkbenchWindow()
        .getWorkbench()
        .removeWindowListener(windowListener);
    ((GraphicalEditPart) fGraphicalViewer.getRootEditPart())
        .getFigure()
        .removeMouseListener(mouseListener);

    fGraphicalViewer = null;
  }
  @Override
  protected void configureGraphicalViewer() {
    super.configureGraphicalViewer();

    GraphicalViewer viewer = getGraphicalViewer();
    viewer.setEditPartFactory(new TadpoleEditPartFactory());

    // zoom menu
    zoomContribution(viewer);

    // layout action
    createDiagramAction(viewer);

    // context menu
    ContextMenuProvider provider = new TadpoleERDContextMenuProvider(viewer, getActionRegistry());
    viewer.setContextMenu(provider);

    // key handler
    configureKeyHandler();

    // grid and geometry
    configureGeometry();
    configureGrid();
  }
  /**
   * Perform the ruler layout.
   *
   * @since 3.6
   */
  public void doLayout() {
    if (left == null && top == null) {
      Rectangle area = getClientArea();
      if (!editor.getBounds().equals(area)) editor.setBounds(area);
      return;
    }

    int leftWidth = 0, topHeight = 0;
    Rectangle leftTrim = null, topTrim = null;
    if (left != null) {
      leftTrim = calculateRulerTrim((Canvas) left.getControl());
      // Adding the trim width here because FigureCanvas#computeSize()
      // does not
      leftWidth = left.getControl().computeSize(SWT.DEFAULT, SWT.DEFAULT).x + leftTrim.width;
    }
    if (top != null) {
      topTrim = calculateRulerTrim((Canvas) top.getControl());
      topHeight = top.getControl().computeSize(SWT.DEFAULT, SWT.DEFAULT).y + topTrim.height;
    }

    Rectangle editorSize = getClientArea();
    editorSize.x = leftWidth;
    editorSize.y = topHeight;
    editorSize.width -= leftWidth;
    editorSize.height -= topHeight;
    editor.setBounds(editorSize);

    /*
     * Fix for Bug# 67554 Take trim into account. Some platforms (such as
     * MacOS and Motif) leave some trimming around some canvasses.
     */
    Rectangle trim = calculateEditorTrim(editor);
    if (left != null) {
      // The - 1 and + 1 are to compensate for the RulerBorder
      left.getControl()
          .setBounds(
              0,
              topHeight - trim.x + leftTrim.x - 1,
              leftWidth,
              editorSize.height - trim.height + leftTrim.height + 1);
    }
    if (top != null) {
      top.getControl()
          .setBounds(
              leftWidth - trim.y + topTrim.y - 1,
              0,
              editorSize.width - trim.width + topTrim.width + 1,
              topHeight);
    }
  }
  private void zoomContribution(GraphicalViewer viewer) {
    double[] zoomLevels;
    List<String> zoomContributions;

    ScalableRootEditPart rootEditPart = new ScalableRootEditPart();
    viewer.setRootEditPart(rootEditPart);

    ZoomManager manager = rootEditPart.getZoomManager();
    getActionRegistry().registerAction(new ZoomInAction(manager));
    getActionRegistry().registerAction(new ZoomOutAction(manager));

    zoomLevels = new double[] {0.25, 0.5, 0.75, 1.0, 1.5, 2.0, 2.5, 3.0, 5.0, 10.0, 20.0};
    manager.setZoomLevels(zoomLevels);

    zoomContributions = new ArrayList<String>();
    //		zoomContributions.add(ZoomManager.FIT_ALL);
    //		zoomContributions.add(ZoomManager.FIT_HEIGHT);
    //		zoomContributions.add(ZoomManager.FIT_WIDTH);
    manager.setZoomLevelContributions(zoomContributions);
  }
  private GraphicalViewer createRulerContainer(int orientation) {
    ScrollingGraphicalViewer viewer = new RulerViewer();
    final boolean isHorizontal =
        orientation == PositionConstants.NORTH || orientation == PositionConstants.SOUTH;

    // Finish initializing the viewer
    viewer.setRootEditPart(new RulerRootEditPart(isHorizontal));
    viewer.setEditPartFactory(new RulerEditPartFactory(diagramViewer));
    viewer.createControl(this);
    ((GraphicalEditPart) viewer.getRootEditPart())
        .getFigure()
        .setBorder(new RulerBorder(isHorizontal));
    viewer.setProperty(GraphicalViewer.class.toString(), diagramViewer);

    // Configure the viewer's control
    FigureCanvas canvas = (FigureCanvas) viewer.getControl();
    canvas.setScrollBarVisibility(FigureCanvas.NEVER);
    if (font == null) {
      FontData[] data = canvas.getFont().getFontData();
      for (int i = 0; i < data.length; i++) {
        data[i].setHeight(data[i].getHeight() - 1);
      }
      font = new Font(Display.getCurrent(), data);
    }
    canvas.setFont(font);
    if (isHorizontal) {
      canvas.getViewport().setHorizontalRangeModel(editor.getViewport().getHorizontalRangeModel());
    } else {
      canvas.getViewport().setVerticalRangeModel(editor.getViewport().getVerticalRangeModel());
    }

    // Add the viewer to the rulerEditDomain
    if (rulerEditDomain == null) {
      rulerEditDomain = new EditDomain();
      rulerEditDomain.setCommandStack(diagramViewer.getEditDomain().getCommandStack());
    }
    rulerEditDomain.addViewer(viewer);

    return viewer;
  }
Esempio n. 24
0
  protected void configureGraphicalViewer() {
    super.configureGraphicalViewer();
    GraphicalViewer viewer = getGraphicalViewer();
    viewer.setEditPartFactory(createEditPartFactory());

    ScalableRootEditPart rootEditPart = new ScalableRootEditPart();
    viewer.setRootEditPart(rootEditPart);

    // ZoomManagerの取得
    ZoomManager manager = rootEditPart.getZoomManager();

    // ズームレベルの設定
    double[] zoomLevels =
        new double[] {0.25, 0.5, 0.75, 1.0, 1.5, 2.0, 2.5, 3.0, 4.0, 5.0, 10.0, 20.0};
    manager.setZoomLevels(zoomLevels);

    // ズーム レベル コントリビューションの設定
    ArrayList<String> zoomContributions = new ArrayList<String>();
    zoomContributions.add(ZoomManager.FIT_ALL);
    zoomContributions.add(ZoomManager.FIT_HEIGHT);
    zoomContributions.add(ZoomManager.FIT_WIDTH);
    manager.setZoomLevelContributions(zoomContributions);
    // 拡大アクションの作成と登録
    getActionRegistry().registerAction(new ZoomInAction(manager));
    // 縮小アクションの作成と登録
    getActionRegistry().registerAction(new ZoomOutAction(manager));

    getGraphicalViewer().setKeyHandler(new GraphicalViewerKeyHandler(getGraphicalViewer()));

    // コンテクストメニューの作成
    String menuId = this.getClass().getName() + ".EditorContext";

    MenuManager menuMgr = new MenuManager(menuId, menuId);
    openPropertyAction = new OpenPropertyViewAction(viewer);
    openOutlineAction = new OpenOutlineViewAction(viewer);
    saveAsImageAction = new SaveAsImageAction(viewer);
    copyAsImageAction = new CopyAsImageAction(viewer);
    createDiagramAction(viewer);

    getSite().registerContextMenu(menuId, menuMgr, viewer);

    PrintAction printAction = new PrintAction(this);
    printAction.setImageDescriptor(UMLPlugin.getImageDescriptor("icons/print.gif"));
    getActionRegistry().registerAction(printAction);

    final DeleteAction deleteAction = new DeleteAction((IWorkbenchPart) this);
    deleteAction.setSelectionProvider(getGraphicalViewer());
    getActionRegistry().registerAction(deleteAction);
    viewer.addSelectionChangedListener(
        new ISelectionChangedListener() {
          public void selectionChanged(SelectionChangedEvent event) {
            deleteAction.update();
          }
        });

    // Actions
    //		IAction showRulers = new ToggleRulerVisibilityAction(getGraphicalViewer());
    //		getActionRegistry().registerAction(showRulers);
    //
    //		IAction snapAction = new ToggleSnapToGeometryAction(getGraphicalViewer());
    //		getActionRegistry().registerAction(snapAction);
    //
    //		IAction showGrid = new ToggleGridAction(getGraphicalViewer());
    //		getActionRegistry().registerAction(showGrid);

    menuMgr.add(new Separator("edit"));
    menuMgr.add(getActionRegistry().getAction(ActionFactory.DELETE.getId()));
    menuMgr.add(getActionRegistry().getAction(ActionFactory.UNDO.getId()));
    menuMgr.add(getActionRegistry().getAction(ActionFactory.REDO.getId()));
    //		menuMgr.add(getActionRegistry().getAction(ActionFactory.COPY.getId()));
    //		menuMgr.add(getActionRegistry().getAction(ActionFactory.PASTE.getId()));
    menuMgr.add(new Separator("zoom"));
    menuMgr.add(getActionRegistry().getAction(GEFActionConstants.ZOOM_IN));
    menuMgr.add(getActionRegistry().getAction(GEFActionConstants.ZOOM_OUT));
    fillDiagramPopupMenu(menuMgr);
    menuMgr.add(new Separator("print"));
    menuMgr.add(saveAsImageAction);
    menuMgr.add(copyAsImageAction);
    menuMgr.add(printAction);
    menuMgr.add(new Separator("views"));
    menuMgr.add(openPropertyAction);
    menuMgr.add(openOutlineAction);
    menuMgr.add(new Separator("generate"));
    menuMgr.add(new Separator("additions"));
    viewer.setContextMenu(menuMgr);
    viewer.setKeyHandler(new GraphicalViewerKeyHandler(viewer).setParent(getCommonKeyHandler()));
  }
  /**
   * Creates rulers for the given graphical viewer.
   *
   * <p>The primaryViewer or its Control cannot be <code>null</code>. The primaryViewer's Control
   * should be a FigureCanvas and a child of this Composite. This method should only be invoked
   * once.
   *
   * <p>To create ruler(s), simply add the RulerProvider(s) (with the right key:
   * RulerProvider.PROPERTY_HORIZONTAL_RULER or RulerProvider.PROPERTY_VERTICAL_RULER) as a property
   * on the given viewer. It can be done after this method is invoked.
   * RulerProvider.PROPERTY_RULER_VISIBILITY can be used to show/hide the rulers.
   *
   * @param primaryViewer The graphical viewer for which the rulers have to be created
   */
  public void setGraphicalViewer(ScrollingGraphicalViewer primaryViewer) {
    // pre-conditions
    Assert.isNotNull(primaryViewer);
    Assert.isNotNull(primaryViewer.getControl());
    Assert.isTrue(diagramViewer == null);

    diagramViewer = primaryViewer;
    editor = (FigureCanvas) diagramViewer.getControl();

    // layout whenever the scrollbars are shown or hidden, and whenever the
    // RulerComposite
    // is resized
    layoutListener =
        new Listener() {
          public void handleEvent(Event event) {
            // @TODO:Pratik If you use Display.asyncExec(runnable) here,
            // some flashing
            // occurs. You can see it when the palette is in the editor, and
            // you hit
            // the button to show/hide it.
            layout(true);
          }
        };
    addListener(SWT.Resize, layoutListener);
    ScrollBar horizontalBar = editor.getHorizontalBar();
    if (horizontalBar != null) {
      horizontalBar.addListener(SWT.Show, layoutListener);
      horizontalBar.addListener(SWT.Hide, layoutListener);
    }
    ScrollBar verticalBar = editor.getVerticalBar();
    if (verticalBar != null) {
      verticalBar.addListener(SWT.Show, layoutListener);
      verticalBar.addListener(SWT.Hide, layoutListener);
    }

    propertyListener =
        new PropertyChangeListener() {
          public void propertyChange(PropertyChangeEvent evt) {
            String property = evt.getPropertyName();
            if (RulerProvider.PROPERTY_HORIZONTAL_RULER.equals(property)) {
              setRuler(
                  (RulerProvider)
                      diagramViewer.getProperty(RulerProvider.PROPERTY_HORIZONTAL_RULER),
                  PositionConstants.NORTH);
            } else if (RulerProvider.PROPERTY_VERTICAL_RULER.equals(property)) {
              setRuler(
                  (RulerProvider) diagramViewer.getProperty(RulerProvider.PROPERTY_VERTICAL_RULER),
                  PositionConstants.WEST);
            } else if (RulerProvider.PROPERTY_RULER_VISIBILITY.equals(property))
              setRulerVisibility(
                  ((Boolean) diagramViewer.getProperty(RulerProvider.PROPERTY_RULER_VISIBILITY))
                      .booleanValue());
          }
        };
    diagramViewer.addPropertyChangeListener(propertyListener);
    Boolean rulerVisibility =
        (Boolean) diagramViewer.getProperty(RulerProvider.PROPERTY_RULER_VISIBILITY);
    if (rulerVisibility != null) setRulerVisibility(rulerVisibility.booleanValue());
    setRuler(
        (RulerProvider) diagramViewer.getProperty(RulerProvider.PROPERTY_HORIZONTAL_RULER),
        PositionConstants.NORTH);
    setRuler(
        (RulerProvider) diagramViewer.getProperty(RulerProvider.PROPERTY_VERTICAL_RULER),
        PositionConstants.WEST);
  }
  private void marshallImage(BpmnMemoryModel model, String modelFileName) {
    try {
      final GraphicalViewer graphicalViewer =
          (GraphicalViewer)
              ((DiagramEditor)
                      model.getFeatureProvider().getDiagramTypeProvider().getDiagramEditor())
                  .getAdapter(GraphicalViewer.class);

      if (graphicalViewer == null || graphicalViewer.getEditPartRegistry() == null) {
        return;
      }
      final ScalableFreeformRootEditPart rootEditPart =
          (ScalableFreeformRootEditPart) graphicalViewer.getEditPartRegistry().get(LayerManager.ID);
      final IFigure rootFigure =
          ((LayerManager) rootEditPart).getLayer(LayerConstants.PRINTABLE_LAYERS);
      final IFigure gridFigure = ((LayerManager) rootEditPart).getLayer(LayerConstants.GRID_LAYER);
      final Rectangle rootFigureBounds = rootFigure.getBounds();

      final boolean toggleRequired = gridFigure.isShowing();

      final Display display = Display.getDefault();

      final Image img = new Image(display, rootFigureBounds.width, rootFigureBounds.height);
      final GC imageGC = new GC(img);
      final SWTGraphics grap = new SWTGraphics(imageGC);

      // Access UI thread from runnable to print the canvas to the image
      display.syncExec(
          new Runnable() {

            @Override
            public void run() {
              if (toggleRequired) {
                // Disable any grids temporarily
                gridFigure.setVisible(false);
              }
              // Deselect any selections
              graphicalViewer.deselectAll();
              rootFigure.paint(grap);
            }
          });

      ImageLoader imgLoader = new ImageLoader();
      imgLoader.data = new ImageData[] {img.getImageData()};

      ByteArrayOutputStream baos = new ByteArrayOutputStream(imgLoader.data.length);

      imgLoader.save(baos, SWT.IMAGE_PNG);

      imageGC.dispose();
      img.dispose();

      // Access UI thread from runnable
      display.syncExec(
          new Runnable() {

            @Override
            public void run() {
              if (toggleRequired) {
                // Re-enable any grids
                gridFigure.setVisible(true);
              }
            }
          });

      String imageFileName = null;
      if (modelFileName.endsWith(".bpmn20.xml")) {
        imageFileName = modelFileName.substring(0, modelFileName.length() - 11) + ".png";
      } else {
        imageFileName = modelFileName.substring(0, modelFileName.lastIndexOf(".")) + ".png";
      }
      File imageFile = new File(imageFileName);
      FileOutputStream outStream = new FileOutputStream(imageFile);
      baos.writeTo(outStream);

    } catch (Exception e) {
      e.printStackTrace();
    }
  }
 private RootModel getRootModel() {
   GraphicalViewer viewer = (GraphicalViewer) getWorkbenchPart().getAdapter(GraphicalViewer.class);
   RootModel root = (RootModel) viewer.getRootEditPart().getContents().getModel();
   return root;
 }
Esempio n. 28
0
  // Private constructor means you can't open an OPIShell without adding
  // it to the cache.
  private OPIShell(Display display, IPath path, MacrosInput macrosInput) throws Exception {
    this.path = path;
    this.macrosInput = macrosInput;
    icon =
        OPIBuilderPlugin.imageDescriptorFromPlugin(
                OPIBuilderPlugin.PLUGIN_ID, "icons/OPIRunner.png")
            .createImage(display);

    shell = new Shell(display);
    shell.setImage(icon);
    displayModel = new DisplayModel(path);
    displayModel.setOpiRuntime(this);
    actionRegistry = new ActionRegistry();

    viewer = new GraphicalViewerImpl();
    viewer.createControl(shell);
    viewer.setEditPartFactory(new WidgetEditPartFactory(ExecutionMode.RUN_MODE));
    viewer.setRootEditPart(
        new ScalableFreeformRootEditPart() {
          @Override
          public DragTracker getDragTracker(Request req) {
            return new DragEditPartsTracker(this);
          }

          @Override
          public boolean isSelectable() {
            return false;
          }
        });

    EditDomain editDomain =
        new EditDomain() {
          @Override
          public void loadDefaultTool() {
            setActiveTool(new RuntimePatchedSelectionTool());
          }
        };
    editDomain.addViewer(viewer);

    displayModel = createDisplayModel();
    setTitle();

    shell.setLayout(new FillLayout());
    shell.addShellListener(
        new ShellListener() {
          private boolean firstRun = true;

          public void shellIconified(ShellEvent e) {}

          public void shellDeiconified(ShellEvent e) {}

          public void shellDeactivated(ShellEvent e) {}

          public void shellClosed(ShellEvent e) {
            // Remove this shell from the cache.
            openShells.remove(OPIShell.this);
            sendUpdateCommand();
          }

          public void shellActivated(ShellEvent e) {
            if (firstRun) {
              // Resize the shell after it's open, so we can take into account different window
              // borders.
              // Do this only the first time it's activated.
              resizeToContents();
              shell.setFocus();
              firstRun = false;
            }
          }
        });
    shell.addDisposeListener(
        new DisposeListener() {

          @Override
          public void widgetDisposed(DisposeEvent e) {
            if (!icon.isDisposed()) icon.dispose();
          }
        });
    /*
     * Don't open the Shell here, as it causes SWT to think the window is on top when it really isn't.
     * Wait until the window is open, then call shell.setFocus() in the activated listener.
     *
     * Make some attempt at sizing the shell, sometimes a shell is not given focus and the shellActivated
     * listener callback doesn't resize the window. It's better to have something a little too large as the
     * default. Related to Eclipse bug 96700.
     */
    shell.setSize(
        displayModel.getSize().width + WINDOW_BORDER_X,
        displayModel.getSize().height + WINDOW_BORDER_Y);
    shell.setVisible(true);
  }
Esempio n. 29
0
 /* (non-Javadoc)
  * @see org.jboss.reddeer.core.reference.ReferencedComposite#getControl()
  */
 @Override
 public Control getControl() {
   return viewer.getControl();
 }