Example #1
0
 public void run() {
   final ReadonlyStatusHandler roHandler = ReadonlyStatusHandler.getInstance(myField.getProject());
   final PsiFile psiFile = myField.getContainingFile();
   if (psiFile == null) return;
   final ReadonlyStatusHandler.OperationStatus status =
       roHandler.ensureFilesWritable(psiFile.getVirtualFile());
   if (status.hasReadonlyFiles()) return;
   ApplicationManager.getApplication()
       .runWriteAction(
           new Runnable() {
             public void run() {
               CommandProcessor.getInstance()
                   .executeCommand(
                       myField.getProject(),
                       new Runnable() {
                         public void run() {
                           try {
                             final PsiManager manager = myField.getManager();
                             myField
                                 .getTypeElement()
                                 .replace(
                                     JavaPsiFacade.getInstance(manager.getProject())
                                         .getElementFactory()
                                         .createTypeElement(myNewType));
                           } catch (final IncorrectOperationException e) {
                             ApplicationManager.getApplication()
                                 .invokeLater(
                                     new Runnable() {
                                       public void run() {
                                         Messages.showErrorDialog(
                                             myEditor,
                                             UIDesignerBundle.message(
                                                 "error.cannot.change.field.type",
                                                 myField.getName(),
                                                 e.getMessage()),
                                             CommonBundle.getErrorTitle());
                                       }
                                     });
                           }
                         }
                       },
                       getName(),
                       null);
             }
           });
 }
    public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) {
      if (!myField.isValid()) return; // weird. should not get here when field becomes invalid

      final Collection<PsiReference> refs = ReferencesSearch.search(myField).findAll();
      if (refs.isEmpty()) return;
      Set<PsiReference> refsSet = new HashSet<PsiReference>(refs);
      PsiCodeBlock anchorBlock = findAnchorBlock(refs);
      if (anchorBlock == null)
        return; // was assert, but need to fix the case when obsolete inspection highlighting is
                // left
      if (!CodeInsightUtil.preparePsiElementsForWrite(anchorBlock)) return;
      final PsiElementFactory elementFactory =
          JavaPsiFacade.getInstance(project).getElementFactory();
      final JavaCodeStyleManager styleManager = JavaCodeStyleManager.getInstance(project);
      final String propertyName =
          styleManager.variableNameToPropertyName(myField.getName(), VariableKind.FIELD);
      String localName =
          styleManager.propertyNameToVariableName(propertyName, VariableKind.LOCAL_VARIABLE);
      localName = RefactoringUtil.suggestUniqueVariableName(localName, anchorBlock, myField);
      PsiElement firstElement = getFirstElement(refs);
      boolean mayBeFinal = mayBeFinal(refsSet, firstElement);
      PsiElement newDeclaration = null;
      try {
        final PsiElement anchor = getAnchorElement(anchorBlock, firstElement);
        if (anchor instanceof PsiExpressionStatement
            && ((PsiExpressionStatement) anchor).getExpression()
                instanceof PsiAssignmentExpression) {
          final PsiAssignmentExpression expression =
              (PsiAssignmentExpression) ((PsiExpressionStatement) anchor).getExpression();
          if (expression.getOperationTokenType() == JavaTokenType.EQ
              && expression.getLExpression() instanceof PsiReferenceExpression
              && ((PsiReference) expression.getLExpression()).isReferenceTo(myField)) {
            final PsiExpression initializer = expression.getRExpression();
            final PsiDeclarationStatement decl =
                elementFactory.createVariableDeclarationStatement(
                    localName, myField.getType(), initializer);
            if (!mayBeFinal) {
              PsiUtil.setModifierProperty(
                  ((PsiModifierListOwner) decl.getDeclaredElements()[0]), PsiModifier.FINAL, false);
            }
            newDeclaration = anchor.replace(decl);
            refsSet.remove(expression.getLExpression());
            retargetReferences(elementFactory, localName, refsSet);
          } else {
            newDeclaration =
                addDeclarationWithFieldInitializerAndRetargetReferences(
                    elementFactory, localName, anchorBlock, anchor, refsSet);
          }
        } else {
          newDeclaration =
              addDeclarationWithFieldInitializerAndRetargetReferences(
                  elementFactory, localName, anchorBlock, anchor, refsSet);
        }
      } catch (IncorrectOperationException e) {
        LOG.error(e);
      }

      if (newDeclaration != null) {
        final PsiFile psiFile = myField.getContainingFile();
        final Editor editor = FileEditorManager.getInstance(project).getSelectedTextEditor();
        if (editor != null && IJSwingUtilities.hasFocus(editor.getComponent())) {
          final PsiFile file =
              PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument());
          if (file == psiFile) {
            editor.getCaretModel().moveToOffset(newDeclaration.getTextOffset());
            editor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE);
          }
        }
      }

      try {
        myField.normalizeDeclaration();
        myField.delete();
      } catch (IncorrectOperationException e) {
        LOG.error(e);
      }
    }