protected boolean invokeImpl(
     final Project project, final PsiLocalVariable localVariable, final Editor editor) {
   final PsiElement parent = localVariable.getParent();
   if (!(parent instanceof PsiDeclarationStatement)) {
     String message =
         RefactoringBundle.getCannotRefactorMessage(
             RefactoringBundle.message("error.wrong.caret.position.local.or.expression.name"));
     CommonRefactoringUtil.showErrorHint(project, editor, message, REFACTORING_NAME, getHelpID());
     return false;
   }
   final LocalToFieldHandler localToFieldHandler =
       new LocalToFieldHandler(project, true) {
         @Override
         protected Settings showRefactoringDialog(
             PsiClass aClass,
             PsiLocalVariable local,
             PsiExpression[] occurences,
             boolean isStatic) {
           return IntroduceConstantHandler.this.showRefactoringDialog(
               project,
               editor,
               aClass,
               local.getInitializer(),
               local.getType(),
               occurences,
               local,
               null);
         }
       };
   return localToFieldHandler.convertLocalToField(localVariable, editor);
 }
  public void invoke(
      @NotNull Project project, Editor editor, PsiFile file, DataContext dataContext) {
    int offset = editor.getCaretModel().getOffset();
    editor.getScrollingModel().scrollToCaret(ScrollType.MAKE_VISIBLE);
    PsiElement element = file.findElementAt(offset);

    while (true) {
      if (element == null || element instanceof PsiFile) {
        String message =
            RefactoringBundle.getCannotRefactorMessage(
                RefactoringBundle.message(
                    "the.caret.should.be.positioned.inside.a.class.to.push.members.from"));
        CommonRefactoringUtil.showErrorHint(
            project, editor, message, REFACTORING_NAME, HelpID.MEMBERS_PUSH_DOWN);
        return;
      }

      if (element instanceof PsiClass
          || element instanceof PsiField
          || element instanceof PsiMethod) {
        if (element instanceof JspClass) {
          RefactoringMessageUtil.showNotSupportedForJspClassesError(
              project, editor, REFACTORING_NAME, HelpID.MEMBERS_PUSH_DOWN);
          return;
        }
        invoke(project, new PsiElement[] {element}, dataContext);
        return;
      }
      element = element.getParent();
    }
  }
Exemplo n.º 3
0
  private static ElementToWorkOn getElementToWorkOn(
      final Editor editor,
      final PsiFile file,
      final String refactoringName,
      final String helpId,
      final Project project,
      PsiLocalVariable localVar,
      PsiExpression expr) {
    int startOffset = 0;
    int endOffset = 0;
    if (localVar == null && expr == null) {
      startOffset = editor.getSelectionModel().getSelectionStart();
      endOffset = editor.getSelectionModel().getSelectionEnd();
      expr = CodeInsightUtil.findExpressionInRange(file, startOffset, endOffset);
      if (expr == null) {
        PsiIdentifier ident =
            CodeInsightUtil.findElementInRange(file, startOffset, endOffset, PsiIdentifier.class);
        if (ident != null) {
          localVar = PsiTreeUtil.getParentOfType(ident, PsiLocalVariable.class);
        }
      }
    }

    if (expr == null && localVar == null) {
      PsiElement[] statements = CodeInsightUtil.findStatementsInRange(file, startOffset, endOffset);
      if (statements.length == 1 && statements[0] instanceof PsiExpressionStatement) {
        expr = ((PsiExpressionStatement) statements[0]).getExpression();
      } else if (statements.length == 1 && statements[0] instanceof PsiDeclarationStatement) {
        PsiDeclarationStatement decl = (PsiDeclarationStatement) statements[0];
        PsiElement[] declaredElements = decl.getDeclaredElements();
        if (declaredElements.length == 1 && declaredElements[0] instanceof PsiLocalVariable) {
          localVar = (PsiLocalVariable) declaredElements[0];
        }
      }
    }
    if (localVar == null && expr == null) {
      expr = IntroduceVariableBase.getSelectedExpression(project, file, startOffset, endOffset);
    }

    if (localVar == null && expr == null) {
      String message =
          RefactoringBundle.getCannotRefactorMessage(
              RefactoringBundle.message("error.wrong.caret.position.local.or.expression.name"));
      CommonRefactoringUtil.showErrorHint(project, editor, message, refactoringName, helpId);
      return null;
    }
    return new ElementToWorkOn(localVar, expr);
  }
  private static void invoke(final PsiClass aClass, Editor editor) {
    final PsiTypeParameterList typeParameterList = aClass.getTypeParameterList();
    Project project = aClass.getProject();
    if (typeParameterList == null) {
      final String message =
          RefactoringBundle.getCannotRefactorMessage(
              RefactoringBundle.message("changeClassSignature.no.type.parameters"));
      CommonRefactoringUtil.showErrorHint(
          project, editor, message, REFACTORING_NAME, HelpID.CHANGE_CLASS_SIGNATURE);
      return;
    }
    if (!CommonRefactoringUtil.checkReadOnlyStatus(project, aClass)) return;

    ChangeClassSignatureDialog dialog = new ChangeClassSignatureDialog(aClass);
    dialog.show();
  }
  private void invokeOnElements(
      @NotNull final Project project,
      @NotNull final Editor editor,
      @NotNull PsiFile file,
      @NotNull PsiElement[] elements) {
    if (elements.length == 0) {
      String message =
          RefactoringBundle.getCannotRefactorMessage(
              RefactoringBundle.message(
                  "selected.block.should.represent.a.set.of.statements.or.an.expression"));
      CommonRefactoringUtil.showErrorHint(
          project,
          editor,
          message,
          ExtractMethodObjectProcessor.REFACTORING_NAME,
          HelpID.EXTRACT_METHOD_OBJECT);
      return;
    }

    final ExtractMethodObjectProcessor processor =
        new ExtractMethodObjectProcessor(project, editor, elements, "");
    final ExtractMethodObjectProcessor.MyExtractMethodProcessor extractProcessor =
        processor.getExtractProcessor();
    try {
      if (!extractProcessor.prepare()) return;
    } catch (PrepareFailedException e) {
      CommonRefactoringUtil.showErrorHint(
          project,
          editor,
          e.getMessage(),
          ExtractMethodObjectProcessor.REFACTORING_NAME,
          HelpID.EXTRACT_METHOD_OBJECT);
      ExtractMethodHandler.highlightPrepareError(e, file, editor, project);
      return;
    }

    if (!CommonRefactoringUtil.checkReadOnlyStatus(
        project, extractProcessor.getTargetClass().getContainingFile())) return;
    if (extractProcessor.showDialog()) {
      run(project, editor, processor, extractProcessor);
    }
  }
 private static void invokeOnElement(Project project, Editor editor, PsiElement element) {
   if (element instanceof PsiMethod) {
     final ChangeSignatureGestureDetector detector =
         ChangeSignatureGestureDetector.getInstance(project);
     final PsiIdentifier nameIdentifier = ((PsiMethod) element).getNameIdentifier();
     if (nameIdentifier != null && detector.isChangeSignatureAvailable(nameIdentifier)) {
       detector.changeSignature(element.getContainingFile(), false);
       return;
     }
     invoke((PsiMethod) element, project, editor);
   } else if (element instanceof PsiClass) {
     invoke((PsiClass) element, editor);
   } else {
     String message =
         RefactoringBundle.getCannotRefactorMessage(
             RefactoringBundle.message("error.wrong.caret.position.method.or.class.name"));
     CommonRefactoringUtil.showErrorHint(
         project, editor, message, REFACTORING_NAME, HelpID.CHANGE_SIGNATURE);
   }
 }
  @Override
  public void invoke(
      @NotNull final Project project, final Editor editor, PsiFile file, DataContext dataContext) {
    final int offset = editor.getCaretModel().getOffset();
    final PsiElement element = file.findElementAt(offset);
    final PsiMember member = PsiTreeUtil.getParentOfType(element, PsiMember.class);
    final String cannotRefactorMessage = getCannotRefactorMessage(member);
    if (cannotRefactorMessage != null) {
      String message = RefactoringBundle.getCannotRefactorMessage(cannotRefactorMessage);
      showErrorMessage(message, project, editor);
      return;
    }

    final AnalysisScope scope = new AnalysisScope(file);
    final Module module = ModuleUtilCore.findModuleForPsiElement(file);
    final BaseAnalysisActionDialog dlg =
        new BaseAnalysisActionDialog(
            RefactoringBundle.message(
                "replace.method.duplicates.scope.chooser.title", REFACTORING_NAME),
            RefactoringBundle.message("replace.method.duplicates.scope.chooser.message"),
            project,
            scope,
            module != null ? module.getName() : null,
            false,
            AnalysisUIOptions.getInstance(project),
            element);
    if (dlg.showAndGet()) {
      ProgressManager.getInstance()
          .run(
              new Task.Backgroundable(project, "Locate duplicates", true) {
                @Override
                public void run(@NotNull ProgressIndicator indicator) {
                  indicator.setIndeterminate(true);
                  invokeOnScope(
                      project,
                      member,
                      dlg.getScope(AnalysisUIOptions.getInstance(project), scope, project, module));
                }
              });
    }
  }
 public void invoke(
     @NotNull Project project, Editor editor, PsiFile file, DataContext dataContext) {
   editor.getScrollingModel().scrollToCaret(ScrollType.MAKE_VISIBLE);
   int offset = editor.getCaretModel().getOffset();
   PsiElement element = file.findElementAt(offset);
   while (true) {
     if (element == null || element instanceof PsiFile) {
       String message =
           RefactoringBundle.getCannotRefactorMessage(
               RefactoringBundle.message("error.wrong.caret.position.class"));
       CommonRefactoringUtil.showErrorHint(
           project, editor, message, REFACTORING_NAME, HelpID.EXTRACT_SUPERCLASS);
       return;
     }
     if (element instanceof PsiClass && !(element instanceof PsiAnonymousClass)) {
       invoke(project, new PsiElement[] {element}, dataContext);
       return;
     }
     element = element.getParent();
   }
 }
  private static boolean invoke(final PsiClass aClass, Editor editor) {
    final PsiTypeParameterList typeParameterList = aClass.getTypeParameterList();
    Project project = aClass.getProject();
    if (typeParameterList == null) {
      final String message =
          RefactoringBundle.getCannotRefactorMessage(
              RefactoringBundle.message("changeClassSignature.no.type.parameters"));
      CommonRefactoringUtil.showErrorHint(
          project, editor, message, REFACTORING_NAME, HelpID.CHANGE_CLASS_SIGNATURE);
      return false;
    }
    if (!CommonRefactoringUtil.checkReadOnlyStatus(project, aClass)) return false;

    ChangeClassSignatureDialog dialog = new ChangeClassSignatureDialog(aClass, true);
    // if (!ApplicationManager.getApplication().isUnitTestMode()){

    return dialog.showAndGet();
    // }else {
    //  dialog.showAndGetOk()
    // }
  }
Exemplo n.º 10
0
  @Nullable
  public static JetChangeSignatureDialog createDialog(
      @NotNull PsiElement element, PsiElement context, Project project, Editor editor) {
    if (!CommonRefactoringUtil.checkReadOnlyStatus(project, element)) return null;
    BindingContext bindingContext =
        AnalyzerFacadeWithCache.analyzeFileWithCache((JetFile) element.getContainingFile())
            .getBindingContext();
    DeclarationDescriptor descriptor =
        bindingContext.get(BindingContext.DECLARATION_TO_DESCRIPTOR, element);

    if (descriptor instanceof ClassDescriptor) {
      descriptor = ((ClassDescriptor) descriptor).getUnsubstitutedPrimaryConstructor();
    }
    if (descriptor instanceof FunctionDescriptorImpl) {
      for (ValueParameterDescriptor parameter :
          ((FunctionDescriptor) descriptor).getValueParameters()) {
        if (parameter.getVarargElementType() != null) {
          String message = JetRefactoringBundle.message("error.cant.refactor.vararg.functions");
          CommonRefactoringUtil.showErrorHint(
              project, editor, message, REFACTORING_NAME, HelpID.CHANGE_SIGNATURE);
          return null;
        }
      }

      return new JetChangeSignatureDialog(
          project,
          new JetFunctionPlatformDescriptorImpl((FunctionDescriptor) descriptor, element),
          context);
    } else {
      String message =
          RefactoringBundle.getCannotRefactorMessage(
              JetRefactoringBundle.message(
                  "error.wrong.caret.position.function.or.constructor.name"));
      CommonRefactoringUtil.showErrorHint(
          project, editor, message, REFACTORING_NAME, HelpID.CHANGE_SIGNATURE);
      return null;
    }
  }
  public void invoke(
      @NotNull final Project project,
      final Editor editor,
      final PsiFile file,
      DataContext dataContext) {
    myIncludingFile = file;
    if (!editor.getSelectionModel().hasSelection()) {
      String message =
          RefactoringBundle.getCannotRefactorMessage(RefactoringBundle.message("no.selection"));
      CommonRefactoringUtil.showErrorHint(project, editor, message, getRefactoringName(), HELP_ID);
      return;
    }
    final int start = editor.getSelectionModel().getSelectionStart();
    final int end = editor.getSelectionModel().getSelectionEnd();

    final Pair<T, T> children = findPairToExtract(start, end);
    if (children == null) {
      String message =
          RefactoringBundle.getCannotRefactorMessage(
              RefactoringBundle.message("selection.does.not.form.a.fragment.for.extraction"));
      CommonRefactoringUtil.showErrorHint(project, editor, message, getRefactoringName(), HELP_ID);
      return;
    }

    if (!verifyChildRange(children.getFirst(), children.getSecond())) {
      String message =
          RefactoringBundle.getCannotRefactorMessage(
              RefactoringBundle.message("cannot.extract.selected.elements.into.include.file"));
      CommonRefactoringUtil.showErrorHint(project, editor, message, getRefactoringName(), HELP_ID);
      return;
    }

    final FileType fileType = getFileType(getLanguageForExtract(children.getFirst()));
    if (!(fileType instanceof LanguageFileType)) {
      String message =
          RefactoringBundle.message(
              "the.language.for.selected.elements.has.no.associated.file.type");
      CommonRefactoringUtil.showErrorHint(project, editor, message, getRefactoringName(), HELP_ID);
      return;
    }

    if (!CommonRefactoringUtil.checkReadOnlyStatus(project, file)) return;

    ExtractIncludeDialog dialog =
        createDialog(file.getContainingDirectory(), getExtractExtension(fileType, children.first));
    dialog.show();
    if (dialog.getExitCode() == DialogWrapper.OK_EXIT_CODE) {
      final PsiDirectory targetDirectory = dialog.getTargetDirectory();
      LOG.assertTrue(targetDirectory != null);
      final String targetfileName = dialog.getTargetFileName();
      CommandProcessor.getInstance()
          .executeCommand(
              project,
              new Runnable() {
                public void run() {
                  ApplicationManager.getApplication()
                      .runWriteAction(
                          new Runnable() {
                            public void run() {
                              try {
                                final List<IncludeDuplicate<T>> duplicates =
                                    new ArrayList<IncludeDuplicate<T>>();
                                final T first = children.getFirst();
                                final T second = children.getSecond();
                                PsiEquivalenceUtil.findChildRangeDuplicates(
                                    first,
                                    second,
                                    file,
                                    new PairConsumer<PsiElement, PsiElement>() {
                                      public void consume(
                                          final PsiElement start, final PsiElement end) {
                                        duplicates.add(new IncludeDuplicate<T>((T) start, (T) end));
                                      }
                                    });
                                final String includePath =
                                    processPrimaryFragment(
                                        first, second, targetDirectory, targetfileName, file);
                                editor
                                    .getCaretModel()
                                    .moveToOffset(first.getTextRange().getStartOffset());

                                ApplicationManager.getApplication()
                                    .invokeLater(
                                        new Runnable() {
                                          public void run() {
                                            replaceDuplicates(
                                                includePath, duplicates, editor, project);
                                          }
                                        });
                              } catch (IncorrectOperationException e) {
                                CommonRefactoringUtil.showErrorMessage(
                                    getRefactoringName(), e.getMessage(), null, project);
                              }

                              editor.getSelectionModel().removeSelection();
                            }
                          });
                }
              },
              getRefactoringName(),
              null);
    }
  }
  public void invoke(
      @NotNull final Project project, @NotNull PsiElement[] elements, DataContext dataContext) {
    if (elements.length != 1) return;

    myProject = project;
    mySubclass = (PsiClass) elements[0];

    if (!CommonRefactoringUtil.checkReadOnlyStatus(project, mySubclass)) return;

    Editor editor = dataContext != null ? PlatformDataKeys.EDITOR.getData(dataContext) : null;
    if (mySubclass.isInterface()) {
      String message =
          RefactoringBundle.getCannotRefactorMessage(
              RefactoringBundle.message("superclass.cannot.be.extracted.from.an.interface"));
      CommonRefactoringUtil.showErrorHint(
          project, editor, message, REFACTORING_NAME, HelpID.EXTRACT_SUPERCLASS);
      return;
    }

    if (mySubclass.isEnum()) {
      String message =
          RefactoringBundle.getCannotRefactorMessage(
              RefactoringBundle.message("superclass.cannot.be.extracted.from.an.enum"));
      CommonRefactoringUtil.showErrorHint(
          project, editor, message, REFACTORING_NAME, HelpID.EXTRACT_SUPERCLASS);
      return;
    }

    final List<MemberInfo> memberInfos =
        MemberInfo.extractClassMembers(
            mySubclass,
            new MemberInfo.Filter<PsiMember>() {
              public boolean includeMember(PsiMember element) {
                return true;
              }
            },
            false);

    final ExtractSuperclassDialog dialog =
        new ExtractSuperclassDialog(
            project, mySubclass, memberInfos, ExtractSuperclassHandler.this);
    dialog.show();
    if (!dialog.isOK() || !dialog.isExtractSuperclass()) return;

    CommandProcessor.getInstance()
        .executeCommand(
            myProject,
            new Runnable() {
              public void run() {
                final Runnable action =
                    new Runnable() {
                      public void run() {
                        doRefactoring(project, mySubclass, dialog);
                      }
                    };
                ApplicationManager.getApplication().runWriteAction(action);
              }
            },
            REFACTORING_NAME,
            null);
  }
  protected Settings showRefactoringDialog(
      Project project,
      final Editor editor,
      PsiClass parentClass,
      PsiExpression expr,
      PsiType type,
      PsiExpression[] occurrences,
      PsiElement anchorElement,
      PsiElement anchorElementIfAll) {
    final PsiMethod containingMethod =
        PsiTreeUtil.getParentOfType(expr != null ? expr : anchorElement, PsiMethod.class);

    PsiLocalVariable localVariable = null;
    if (expr instanceof PsiReferenceExpression) {
      PsiElement ref = ((PsiReferenceExpression) expr).resolve();
      if (ref instanceof PsiLocalVariable) {
        localVariable = (PsiLocalVariable) ref;
      }
    } else if (anchorElement instanceof PsiLocalVariable) {
      localVariable = (PsiLocalVariable) anchorElement;
    }

    String enteredName = null;
    boolean replaceAllOccurrences = true;

    final AbstractInplaceIntroducer activeIntroducer =
        AbstractInplaceIntroducer.getActiveIntroducer(editor);
    if (activeIntroducer != null) {
      activeIntroducer.stopIntroduce(editor);
      expr = (PsiExpression) activeIntroducer.getExpr();
      localVariable = (PsiLocalVariable) activeIntroducer.getLocalVariable();
      occurrences = (PsiExpression[]) activeIntroducer.getOccurrences();
      enteredName = activeIntroducer.getInputName();
      replaceAllOccurrences = activeIntroducer.isReplaceAllOccurrences();
      type = ((InplaceIntroduceConstantPopup) activeIntroducer).getType();
    }

    for (PsiExpression occurrence : occurrences) {
      if (RefactoringUtil.isAssignmentLHS(occurrence)) {
        String message =
            RefactoringBundle.getCannotRefactorMessage("Selected expression is used for write");
        CommonRefactoringUtil.showErrorHint(
            project, editor, message, REFACTORING_NAME, getHelpID());
        highlightError(project, editor, occurrence);
        return null;
      }
    }

    if (localVariable == null) {
      final PsiElement errorElement = isStaticFinalInitializer(expr);
      if (errorElement != null) {
        String message =
            RefactoringBundle.getCannotRefactorMessage(
                RefactoringBundle.message("selected.expression.cannot.be.a.constant.initializer"));
        CommonRefactoringUtil.showErrorHint(
            project, editor, message, REFACTORING_NAME, getHelpID());
        highlightError(project, editor, errorElement);
        return null;
      }
    } else {
      final PsiExpression initializer = localVariable.getInitializer();
      if (initializer == null) {
        String message =
            RefactoringBundle.getCannotRefactorMessage(
                RefactoringBundle.message(
                    "variable.does.not.have.an.initializer", localVariable.getName()));
        CommonRefactoringUtil.showErrorHint(
            project, editor, message, REFACTORING_NAME, getHelpID());
        return null;
      }
      final PsiElement errorElement = isStaticFinalInitializer(initializer);
      if (errorElement != null) {
        String message =
            RefactoringBundle.getCannotRefactorMessage(
                RefactoringBundle.message(
                    "initializer.for.variable.cannot.be.a.constant.initializer",
                    localVariable.getName()));
        CommonRefactoringUtil.showErrorHint(
            project, editor, message, REFACTORING_NAME, getHelpID());
        highlightError(project, editor, errorElement);
        return null;
      }
    }

    final TypeSelectorManagerImpl typeSelectorManager =
        new TypeSelectorManagerImpl(project, type, containingMethod, expr, occurrences);
    if (editor != null
        && editor.getSettings().isVariableInplaceRenameEnabled()
        && (expr == null || expr.isPhysical())
        && activeIntroducer == null) {
      myInplaceIntroduceConstantPopup =
          new InplaceIntroduceConstantPopup(
              project,
              editor,
              parentClass,
              expr,
              localVariable,
              occurrences,
              typeSelectorManager,
              anchorElement,
              anchorElementIfAll,
              expr != null ? createOccurrenceManager(expr, parentClass) : null);
      if (myInplaceIntroduceConstantPopup.startInplaceIntroduceTemplate()) {
        return null;
      }
    }

    final IntroduceConstantDialog dialog =
        new IntroduceConstantDialog(
            project,
            parentClass,
            expr,
            localVariable,
            localVariable != null,
            occurrences,
            getParentClass(),
            typeSelectorManager,
            enteredName);
    dialog.setReplaceAllOccurrences(replaceAllOccurrences);
    if (!dialog.showAndGet()) {
      if (occurrences.length > 1) {
        WindowManager.getInstance()
            .getStatusBar(project)
            .setInfo(RefactoringBundle.message("press.escape.to.remove.the.highlighting"));
      }
      return null;
    }
    return new Settings(
        dialog.getEnteredName(),
        expr,
        occurrences,
        dialog.isReplaceAllOccurrences(),
        true,
        true,
        InitializationPlace.IN_FIELD_DECLARATION,
        dialog.getFieldVisibility(),
        localVariable,
        dialog.getSelectedType(),
        dialog.isDeleteVariable(),
        dialog.getDestinationClass(),
        dialog.isAnnotateAsNonNls(),
        dialog.introduceEnumConstant());
  }