/**
   * Run code inspection function, and shows the result in the workbench
   *
   * @param viewtTitle title of the view
   * @param noResultMessage if there is no result, this message will be displayed
   * @param tmpFile temp .dot file
   * @param functionName function to call
   * @param signature parameters signature
   * @param parameters function parameters
   */
  protected void runInspection(
      final String viewtTitle,
      final String secondaryID,
      final String noResultMessage,
      final File tmpFile,
      final String functionName,
      final String signature,
      final Object... parameters) {
    try {
      CodeInspectionViewsManager.hideView(CodeInspectionViewsManager.GRAPH_VIEW, secondaryID);
      final Boolean b =
          WranglerBackendManager.getRefactoringBackend()
              .callSimpleInspection(functionName, signature, parameters);
      if (b) {
        final FileInputStream fis = new FileInputStream(tmpFile);
        try {
          if (fis.available() > 0) {

            final Image img = GraphViz.load(fis, "png", new Point(0, 0));
            CodeInspectionViewsManager.showDotImage(img, viewtTitle, secondaryID, tmpFile);
          } else {
            MessageDialog.openInformation(
                GlobalParameters.getEditor().getSite().getShell(), viewtTitle, noResultMessage);
          }
        } finally {
          fis.close();
        }
      } else {
        MessageDialog.openError(
            GlobalParameters.getEditor().getSite().getShell(),
            "Internal error",
            "Internal error occured. Please report it!");
      }
    } catch (final IOException e) {
      ErlLogger.error(e);
    } catch (final CoreException e) {
      ErlLogger.error(e);
    } catch (final Exception e) {
      ErlLogger.error(e);
    }
  }
 @Override
 public RefactoringStatus checkFinalConditions(IProgressMonitor pm)
     throws CoreException, OperationCanceledException {
   IErlSelection sel = GlobalParameters.getWranglerSelection();
   IRefactoringRpcMessage message = run(sel);
   if (message.isSuccessful()) {
     changedFiles = message.getRefactoringChangeset();
     return new RefactoringStatus();
   } else {
     return RefactoringStatus.createFatalErrorStatus(message.getMessageString());
   }
 }
 @Override
 public IRefactoringRpcMessage run(IErlSelection selection) {
   IErlMemberSelection sel = (IErlMemberSelection) selection;
   return WranglerBackendManager.getRefactoringBackend()
       .call(
           "fold_expr_1_eclipse",
           "sxxxi",
           sel.getFilePath(),
           syntaxTree,
           getSelectedPos(),
           sel.getSearchPath(),
           GlobalParameters.getTabWidth());
 }
  @Override
  public IStatus handleDrop(
      final CommonDropAdapter dropAdapter,
      final DropTargetEvent dropTargetEvent,
      final Object target) {

    // get the source data
    final TransferData td = dropAdapter.getCurrentTransfer();
    final ISelection sel = (ISelection) LocalSelectionTransfer.getTransfer().nativeToJava(td);
    final TreeSelection s = (TreeSelection) sel;
    try {
      GlobalParameters.setSelection(s);
    } catch (final WranglerException e1) {
      e1.printStackTrace();
    }

    // get the target data
    String moduleName;
    IFile file;
    if (target instanceof IFile) {
      file = (IFile) target;
    } else {
      file = (IFile) ((IErlElement) target).getResource();
    }
    moduleName = file.getName();

    moduleName = moduleName.substring(0, moduleName.lastIndexOf("."));

    final MoveFunctionRefactoring refactoring = new MoveFunctionRefactoring();
    refactoring.setUserInput(moduleName);
    final RefactoringWizard wizard =
        new DefaultWranglerRefactoringWizard(
            refactoring,
            RefactoringWizard.DIALOG_BASED_USER_INTERFACE,
            new ArrayList<WranglerPage>());

    final Shell shell = PlatformUI.getWorkbench().getDisplay().getActiveShell();

    final RefactoringWizardOpenOperation op = new RefactoringWizardOpenOperation(wizard);

    try {
      op.run(shell, refactoring.getName());
    } catch (final Exception e) {
      e.printStackTrace();
    }

    System.out.print("hand");

    return Status.OK_STATUS;
  }
 @Override
 public RefactoringStatus checkInitialConditions(final IProgressMonitor pm)
     throws CoreException, OperationCanceledException {
   // FIXME: what kind of preconditions do I need?
   final IErlMemberSelection sel = (IErlMemberSelection) GlobalParameters.getWranglerSelection();
   final StateDataToRecordRpcMessage message = runFirst(sel);
   if (!message.isSuccessful()) {
     return RefactoringStatus.createFatalErrorStatus(message.getMessageString());
   } else {
     fieldCount = message.getFieldCount();
     stateFuns = message.getStateFuns();
     return new RefactoringStatus();
   }
 }
 @Override
 public IRefactoringRpcMessage runAlternative(final IErlSelection selection) {
   IErlMemberSelection sel = (IErlMemberSelection) selection;
   return WranglerBackendManager.getRefactoringBackend()
       .call(
           "new_let_1_eclipse",
           "ssxxxi",
           sel.getFilePath(),
           userInput,
           expr,
           parentExpr,
           sel.getSearchPath(),
           GlobalParameters.getTabWidth());
 }
 @Override
 public IRefactoringRpcMessage run(final IErlSelection selection) {
   IErlMemberSelection sel = (IErlMemberSelection) selection;
   return WranglerBackendManager.getRefactoringBackend()
       .call(
           "new_let_eclipse",
           "sxxsxi",
           sel.getFilePath(),
           sel.getSelectionRange().getStartPos(),
           sel.getSelectionRange().getEndPos(),
           userInput,
           sel.getSearchPath(),
           GlobalParameters.getTabWidth());
 }
  @Override
  public RefactoringStatus checkInitialConditions(IProgressMonitor pm)
      throws CoreException, OperationCanceledException {
    if (functionClause == null) {
      return RefactoringStatus.createFatalErrorStatus("No function clause was given!");
    } else {

      ExpressionPosRpcMessage m = new ExpressionPosRpcMessage();
      String path = selection.getFilePath();
      String moduleName = functionClause.getModule().getModuleName();
      String functionName = functionClause.getFunctionName();
      int arity = functionClause.getArity();

      int clauseIndex = 1;
      if (!(functionClause instanceof IErlFunction))
        // FIXME: avoid hacking!!!
        clauseIndex = Integer.valueOf(functionClause.getName().substring(1));

      m =
          (ExpressionPosRpcMessage)
              WranglerBackendManager.getRefactoringBackend()
                  .callWithParser(
                      m,
                      "fold_expr_by_name_eclipse",
                      "sssiixi",
                      path,
                      moduleName,
                      functionName,
                      arity,
                      clauseIndex,
                      selection.getSearchPath(),
                      GlobalParameters.getTabWidth());

      if (m.isSuccessful()) {
        syntaxTree = m.getSyntaxTree();
        // TODO: store positions, selectedpositions
        positions = m.getPositionDefinitions(selection.getDocument());
        selectedPositions = new ArrayList<IErlRange>();
      } else {
        return RefactoringStatus.createFatalErrorStatus(m.getMessageString());
      }
    }

    return new RefactoringStatus();
  }
  @Override
  protected Control createDialogArea(final Composite parent) {

    final Composite composite = (Composite) super.createDialogArea(parent);
    final Tree functionClausesTree;

    final Label label = new Label(composite, SWT.WRAP);
    label.setText("Please select the function clause which against should fold!");
    final GridData minToksData =
        new GridData(
            GridData.GRAB_HORIZONTAL
                | GridData.GRAB_VERTICAL
                | GridData.HORIZONTAL_ALIGN_FILL
                | GridData.VERTICAL_ALIGN_CENTER);
    minToksData.widthHint =
        convertHorizontalDLUsToPixels(IDialogConstants.MINIMUM_MESSAGE_AREA_WIDTH);
    label.setLayoutData(minToksData);
    label.setFont(parent.getFont());

    functionClausesTree = new Tree(composite, SWT.BORDER);
    final GridData treeData =
        new GridData(
            GridData.GRAB_HORIZONTAL
                | GridData.GRAB_VERTICAL
                | GridData.HORIZONTAL_ALIGN_FILL
                | GridData.VERTICAL_ALIGN_CENTER);
    treeData.widthHint = convertHorizontalDLUsToPixels(IDialogConstants.MINIMUM_MESSAGE_AREA_WIDTH);
    functionClausesTree.setLayoutData(treeData);

    try {
      final Collection<IErlModule> erlmodules =
          ErlangEngine.getInstance()
              .getModelUtilService()
              .getProject(GlobalParameters.getWranglerSelection().getErlElement())
              .getModules();

      for (final IErlModule m : erlmodules) {
        // must refresh the scanner!
        if (
        /* !m.isStructureKnown() */ true) {
          // FIXME: not permitted operation
          m.open(null);
        }

        final TreeItem moduleName = new TreeItem(functionClausesTree, 0);
        moduleName.setText(m.getModuleName());
        moduleName.setData(m);
        final List<IErlFunction> functions = filterFunctions(m.getChildren());
        for (final IErlFunction f : functions) {
          final TreeItem functionName = new TreeItem(moduleName, 0);
          functionName.setText(f.getNameWithArity());
          final List<IErlFunctionClause> clauses = filterClauses(f.getChildren());
          functionName.setData(f);
          for (final IErlFunctionClause c : clauses) {
            final TreeItem clauseName = new TreeItem(functionName, 0);
            clauseName.setText(String.valueOf(c.getName()));
            clauseName.setData(c);
          }
        }
      }

      // listen to treeitem selection
      functionClausesTree.addSelectionListener(
          new SelectionListener() {

            @Override
            public void widgetDefaultSelected(final SelectionEvent e) {}

            // if a function or a function clause is selected, then
            // highlight it
            // and store the selection
            @Override
            public void widgetSelected(final SelectionEvent e) {

              final TreeItem[] selectedItems = functionClausesTree.getSelection();

              if (selectedItems.length > 0) {
                final TreeItem treeItem = selectedItems[0];
                final Object data = treeItem.getData();
                if (data instanceof IErlFunctionClause) {
                  // enable the ok button
                  okButton.setEnabled(true);

                  // highlight
                  WranglerUtils.highlightSelection((IErlFunctionClause) data);

                  // store
                  functionClause = (IErlFunctionClause) data;
                } else {
                  okButton.setEnabled(false);
                }
              }
            }
          });
    } catch (final ErlModelException e) {
      ErlLogger.error(e);
    }

    applyDialogFont(composite);
    return composite;
  }
  @Override
  public Object execute(final ExecutionEvent event) throws ExecutionException {
    final String actionId = event.getCommand().getId();
    PlatformUI.getWorkbench()
        .getActiveWorkbenchWindow()
        .getActivePage()
        .getActiveEditor()
        .setFocus();
    try {
      GlobalParameters.setSelection(
          PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getSelection());
    } catch (final WranglerException e1) {
      MessageDialog.openError(
          PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(),
          "Error",
          e1.getMessage());
      return null;
    }
    try {
      final File tmpFile = File.createTempFile("wrangler_graph_", ".dot");
      tmpFile.deleteOnExit();

      final IErlSelection wranglerSelection = GlobalParameters.getWranglerSelection();

      if (actionId.equals("org.erlide.wrangler.refactoring.codeinspection.cyclicdependencies")) {
        final Boolean answer =
            MessageDialog.openQuestion(
                PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(),
                "Labels",
                "Label edges with function names called?");
        runInspection(
            "Cyclic module dependency",
            CYCLYC_VIEW_ID,
            "There is no cyclic dependent modules in the project!",
            tmpFile,
            "cyclic_dependent_modules",
            "ssx",
            tmpFile.getAbsolutePath(),
            wranglerSelection.getSearchPath(),
            new OtpErlangBoolean(answer));
      } else if (actionId.equals(
          "org.erlide.wrangler.refactoring.codeinspection.generatefunctioncallgraph")) {
        runInspection(
            "Function callgraph",
            FUNCTION_CALL_GRAPH_VIEW_ID,
            "There is no dependent functions in the module!",
            tmpFile,
            "gen_function_callgraph",
            "sss",
            tmpFile.getAbsolutePath(),
            wranglerSelection.getFilePath(),
            wranglerSelection.getSearchPath());

      } else if (actionId.equals(
          "org.erlide.wrangler.refactoring.codeinspection.generatemodulegraph")) {
        final Boolean answer =
            MessageDialog.openQuestion(
                PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(),
                "Labels",
                "Label edges with function names called?");
        runInspection(
            "Module dependency graph",
            MODULE_GRAPH_VIEW_ID,
            "There is no dependent modules in the project!",
            tmpFile,
            "gen_module_graph",
            "ssx",
            tmpFile.getAbsolutePath(),
            wranglerSelection.getSearchPath(),
            new OtpErlangBoolean(answer));

      } else if (actionId.equals(
          "org.erlide.wrangler.refactoring.codeinspection.improperdependecies")) {
        runInspection(
            "Improper module dependencies",
            IMPROPER_DEPENDECIES_VIEW_ID,
            "There is no improper module dependecies!",
            tmpFile,
            "improper_inter_module_calls",
            "ss",
            tmpFile.getAbsolutePath(),
            wranglerSelection.getSearchPath());
      }

    } catch (final Exception e) {
      ErlLogger.error(e);
    }
    return event;
  }