private static void beginCompoundChange(ITextViewer viewer) {
   if (viewer instanceof ITextViewerExtension) {
     ITextViewerExtension extension = (ITextViewerExtension) viewer;
     IRewriteTarget target = extension.getRewriteTarget();
     target.beginCompoundChange();
   }
 }
  private void doPasteWithImportsOperation() {
    ITextEditor editor = getTextEditor();
    IJavaElement inputElement = JavaUI.getEditorInputTypeRoot(editor.getEditorInput());

    Clipboard clipboard = new Clipboard(getDisplay());
    try {
      ClipboardData importsData = (ClipboardData) clipboard.getContents(fgTransferInstance);
      if (importsData != null
          && inputElement instanceof ICompilationUnit
          && !importsData.isFromSame(inputElement)) {
        // combine operation and adding of imports
        IRewriteTarget target = (IRewriteTarget) editor.getAdapter(IRewriteTarget.class);
        if (target != null) {
          target.beginCompoundChange();
        }
        try {
          fOperationTarget.doOperation(fOperationCode);
          addImports((ICompilationUnit) inputElement, importsData);
        } catch (CoreException e) {
          JavaPlugin.log(e);
        } finally {
          if (target != null) {
            target.endCompoundChange();
          }
        }
      } else {
        fOperationTarget.doOperation(fOperationCode);
      }
    } finally {
      clipboard.dispose();
    }
  }
  private static void applyProposal(
      ICompletionProposal proposal,
      ITextViewer viewer,
      char trigger,
      int stateMask,
      final int offset) {
    Assert.isTrue(proposal instanceof ICompletionProposalExtension2);

    IRewriteTarget target = null;
    IEditingSupportRegistry registry = null;
    IEditingSupport helper =
        new IEditingSupport() {

          public boolean isOriginator(DocumentEvent event, IRegion focus) {
            return focus.getOffset() <= offset && focus.getOffset() + focus.getLength() >= offset;
          }

          public boolean ownsFocusShell() {
            return false;
          }
        };

    try {
      IDocument document = viewer.getDocument();

      if (viewer instanceof ITextViewerExtension) {
        ITextViewerExtension extension = (ITextViewerExtension) viewer;
        target = extension.getRewriteTarget();
      }

      if (target != null) target.beginCompoundChange();

      if (viewer instanceof IEditingSupportRegistry) {
        registry = (IEditingSupportRegistry) viewer;
        registry.register(helper);
      }

      ((ICompletionProposalExtension2) proposal).apply(viewer, trigger, stateMask, offset);

      Point selection = proposal.getSelection(document);
      if (selection != null) {
        viewer.setSelectedRange(selection.x, selection.y);
        viewer.revealRange(selection.x, selection.y);
      }
    } finally {
      if (target != null) target.endCompoundChange();

      if (registry != null) registry.unregister(helper);
    }
  }
示例#4
0
  /**
   * 執行Quick Fix變更
   *
   * @param activeEditor
   * @param document
   * @throws CoreException
   */
  private void performChange(IEditorPart activeEditor, IDocument document, ASTRewrite rewrite)
      throws CoreException {
    Change change = null;
    IRewriteTarget rewriteTarget = null;
    try {
      change = getChange(actRoot, rewrite);
      if (change != null) {
        if (document != null) {
          LinkedModeModel.closeAllModels(document);
        }
        if (activeEditor != null) {
          rewriteTarget = (IRewriteTarget) activeEditor.getAdapter(IRewriteTarget.class);
          if (rewriteTarget != null) {
            rewriteTarget.beginCompoundChange();
          }
        }

        change.initializeValidationData(new NullProgressMonitor());
        RefactoringStatus valid = change.isValid(new NullProgressMonitor());
        if (valid.hasFatalError()) {
          IStatus status =
              new Status(
                  IStatus.ERROR,
                  JavaPlugin.getPluginId(),
                  IStatus.ERROR,
                  valid.getMessageMatchingSeverity(RefactoringStatus.FATAL),
                  null);
          throw new CoreException(status);
        } else {
          IUndoManager manager = RefactoringCore.getUndoManager();
          manager.aboutToPerformChange(change);
          Change undoChange = change.perform(new NullProgressMonitor());
          manager.changePerformed(change, true);
          if (undoChange != null) {
            undoChange.initializeValidationData(new NullProgressMonitor());
            manager.addUndo("Quick Undo", undoChange);
          }
        }
      }
    } finally {
      if (rewriteTarget != null) {
        rewriteTarget.endCompoundChange();
      }

      if (change != null) {
        change.dispose();
      }
    }
  }
  private void run(Shell shell, IType type) throws CoreException {
    final OverrideMethodDialog dialog = new OverrideMethodDialog(shell, fEditor, type, false);
    if (!dialog.hasMethodsToOverride()) {
      MessageDialog.openInformation(
          shell, getDialogTitle(), ActionMessages.OverrideMethodsAction_error_nothing_found);
      notifyResult(false);
      return;
    }
    if (dialog.open() != Window.OK) {
      notifyResult(false);
      return;
    }

    final Object[] selected = dialog.getResult();
    if (selected == null) {
      notifyResult(false);
      return;
    }

    ArrayList<IMethodBinding> methods = new ArrayList<IMethodBinding>();
    for (int i = 0; i < selected.length; i++) {
      Object elem = selected[i];
      if (elem instanceof IMethodBinding) {
        methods.add((IMethodBinding) elem);
      }
    }
    IMethodBinding[] methodToOverride = methods.toArray(new IMethodBinding[methods.size()]);

    final IEditorPart editor = JavaUI.openInEditor(type.getCompilationUnit());
    final IRewriteTarget target =
        editor != null ? (IRewriteTarget) editor.getAdapter(IRewriteTarget.class) : null;
    if (target != null) target.beginCompoundChange();
    try {
      CompilationUnit astRoot = dialog.getCompilationUnit();
      final ITypeBinding typeBinding = ASTNodes.getTypeBinding(astRoot, type);
      int insertPos = dialog.getInsertOffset();

      AddUnimplementedMethodsOperation operation =
          (AddUnimplementedMethodsOperation)
              createRunnable(
                  astRoot, typeBinding, methodToOverride, insertPos, dialog.getGenerateComment());
      IRunnableContext context = JavaPlugin.getActiveWorkbenchWindow();
      if (context == null) context = new BusyIndicatorRunnableContext();
      PlatformUI.getWorkbench()
          .getProgressService()
          .runInUI(
              context,
              new WorkbenchRunnableAdapter(operation, operation.getSchedulingRule()),
              operation.getSchedulingRule());
      final String[] created = operation.getCreatedMethods();
      if (created == null || created.length == 0)
        MessageDialog.openInformation(
            shell, getDialogTitle(), ActionMessages.OverrideMethodsAction_error_nothing_found);
    } catch (InvocationTargetException exception) {
      ExceptionHandler.handle(exception, shell, getDialogTitle(), null);
    } catch (InterruptedException exception) {
      // Do nothing. Operation has been canceled by user.
    } finally {
      if (target != null) target.endCompoundChange();
    }
    notifyResult(true);
  }
示例#6
0
  /*
   * @see ITextOperationTarget#doOperation(int)
   */
  public void doOperation(int operation) {

    if (getTextWidget() == null || (!redraws() && operation != FORMAT)) return;

    switch (operation) {
      case CONTENTASSIST_PROPOSALS:
        fContentAssistant.showPossibleCompletions();
        return;
      case CONTENTASSIST_CONTEXT_INFORMATION:
        fContentAssistant.showContextInformation();
        return;
      case QUICK_ASSIST:
        // FIXME: must find a way to post to the status line
        /* String msg= */ fQuickAssistAssistant.showPossibleQuickAssists();
        // setStatusLineErrorMessage(msg);
        return;
      case INFORMATION:
        fInformationPresenter.showInformation();
        return;
      case FORMAT:
        {
          final Point selection = rememberSelection();
          final IRewriteTarget target = getRewriteTarget();
          final IDocument document = getDocument();
          IFormattingContext context = null;
          DocumentRewriteSession rewriteSession = null;

          if (document instanceof IDocumentExtension4) {
            IDocumentExtension4 extension = (IDocumentExtension4) document;
            DocumentRewriteSessionType type =
                (selection.y == 0 && document.getLength() > 1000) || selection.y > 1000
                    ? DocumentRewriteSessionType.SEQUENTIAL
                    : DocumentRewriteSessionType.UNRESTRICTED_SMALL;
            rewriteSession = extension.startRewriteSession(type);
          } else {
            setRedraw(false);
            target.beginCompoundChange();
          }

          try {

            final String rememberedContents = document.get();

            try {

              if (fContentFormatter instanceof IContentFormatterExtension) {
                final IContentFormatterExtension extension =
                    (IContentFormatterExtension) fContentFormatter;
                context = createFormattingContext();
                if (selection.y == 0) {
                  context.setProperty(FormattingContextProperties.CONTEXT_DOCUMENT, Boolean.TRUE);
                } else {
                  context.setProperty(FormattingContextProperties.CONTEXT_DOCUMENT, Boolean.FALSE);
                  context.setProperty(
                      FormattingContextProperties.CONTEXT_REGION,
                      new Region(selection.x, selection.y));
                }
                extension.format(document, context);
              } else {
                IRegion r;
                if (selection.y == 0) {
                  IRegion coverage = getModelCoverage();
                  r = coverage == null ? new Region(0, 0) : coverage;
                } else {
                  r = new Region(selection.x, selection.y);
                }
                fContentFormatter.format(document, r);
              }

              updateSlaveDocuments(document);

            } catch (RuntimeException x) {
              // fire wall for https://bugs.eclipse.org/bugs/show_bug.cgi?id=47472
              // if something went wrong we undo the changes we just did
              // TODO to be removed after 3.0 M8
              document.set(rememberedContents);
              throw x;
            }

          } finally {

            if (document instanceof IDocumentExtension4) {
              IDocumentExtension4 extension = (IDocumentExtension4) document;
              extension.stopRewriteSession(rewriteSession);
            } else {
              target.endCompoundChange();
              setRedraw(true);
            }

            restoreSelection();
            if (context != null) context.dispose();
          }
          return;
        }
      default:
        super.doOperation(operation);
    }
  }
  /**
   * Note: This method is for internal use only. Clients should not call this method.
   *
   * @param cu The compilation unit to process
   */
  public void run(ICompilationUnit cu) {
    if (!ElementValidator.check(
        cu, getShell(), ActionMessages.OrganizeImportsAction_error_title, fEditor != null)) return;
    if (!ActionUtil.isProcessable(getShell(), cu)) return;

    IEditingSupport helper = createViewerHelper();
    try {
      CodeGenerationSettings settings =
          JavaPreferencesSettings.getCodeGenerationSettings(cu.getJavaProject());

      if (fEditor == null && EditorUtility.isOpenInEditor(cu) == null) {
        IEditorPart editor = EditorUtility.openInEditor(cu);
        if (editor instanceof JavaEditor) {
          fEditor = (JavaEditor) editor;
        }
      }

      CompilationUnit astRoot =
          JavaPlugin.getDefault().getASTProvider().getAST(cu, ASTProvider.WAIT_ACTIVE_ONLY, null);

      AJOrganizeImportsOperation op =
          new AJOrganizeImportsOperation(
              cu,
              astRoot,
              settings.importIgnoreLowercase,
              !cu.isWorkingCopy(),
              true,
              createChooseImportQuery());

      IRewriteTarget target = null;
      if (fEditor != null) {
        target = (IRewriteTarget) fEditor.getAdapter(IRewriteTarget.class);
        if (target != null) {
          target.beginCompoundChange();
        }
      }

      IProgressService progressService = PlatformUI.getWorkbench().getProgressService();
      IRunnableContext context = getSite().getWorkbenchWindow();
      if (context == null) {
        context = progressService;
      }
      try {
        registerHelper(helper);
        progressService.runInUI(
            context, new WorkbenchRunnableAdapter(op, op.getScheduleRule()), op.getScheduleRule());
        IProblem parseError = op.getParseError();
        if (parseError != null) {
          String message =
              Messages.format(
                  ActionMessages.OrganizeImportsAction_single_error_parse, parseError.getMessage());
          MessageDialog.openInformation(
              getShell(), ActionMessages.OrganizeImportsAction_error_title, message);
          if (fEditor != null && parseError.getSourceStart() != -1) {
            fEditor.selectAndReveal(
                parseError.getSourceStart(),
                parseError.getSourceEnd() - parseError.getSourceStart() + 1);
          }
        } else {
          if (fEditor != null) {
            setStatusBarMessage(getOrganizeInfo(op));
          }
        }
      } catch (InvocationTargetException e) {
        ExceptionHandler.handle(
            e,
            getShell(),
            ActionMessages.OrganizeImportsAction_error_title,
            ActionMessages.OrganizeImportsAction_error_message);
      } catch (InterruptedException e) {
      } finally {
        deregisterHelper(helper);
        if (target != null) {
          target.endCompoundChange();
        }
      }
    } catch (CoreException e) {
      ExceptionHandler.handle(
          e,
          getShell(),
          ActionMessages.OrganizeImportsAction_error_title,
          ActionMessages.OrganizeImportsAction_error_message);
    }
  }