static void addExceptionsToThrowsList(
      @NotNull final Project project,
      @NotNull final PsiMethod targetMethod,
      @NotNull final Set<PsiClassType> unhandledExceptions) {
    final PsiMethod[] superMethods = getSuperMethods(targetMethod);

    boolean hasSuperMethodsWithoutExceptions =
        hasSuperMethodsWithoutExceptions(superMethods, unhandledExceptions);

    final boolean processSuperMethods;
    if (hasSuperMethodsWithoutExceptions && superMethods.length > 0) {
      int result =
          ApplicationManager.getApplication().isUnitTestMode()
              ? Messages.YES
              : Messages.showYesNoCancelDialog(
                  QuickFixBundle.message(
                      "add.exception.to.throws.inherited.method.warning.text",
                      targetMethod.getName()),
                  QuickFixBundle.message("method.is.inherited.warning.title"),
                  Messages.getQuestionIcon());

      if (result == Messages.YES) {
        processSuperMethods = true;
      } else if (result == Messages.NO) {
        processSuperMethods = false;
      } else {
        return;
      }
    } else {
      processSuperMethods = false;
    }

    ApplicationManager.getApplication()
        .runWriteAction(
            () -> {
              if (!FileModificationService.getInstance()
                  .prepareFileForWrite(targetMethod.getContainingFile())) return;
              if (processSuperMethods) {
                for (PsiMethod superMethod : superMethods) {
                  if (!FileModificationService.getInstance()
                      .prepareFileForWrite(superMethod.getContainingFile())) return;
                }
              }

              try {
                processMethod(project, targetMethod, unhandledExceptions);

                if (processSuperMethods) {
                  for (PsiMethod superMethod : superMethods) {
                    processMethod(project, superMethod, unhandledExceptions);
                  }
                }
              } catch (IncorrectOperationException e) {
                LOG.error(e);
              }
            });
  }
  public static void createProperty(
      @NotNull final Project project,
      @NotNull final PsiElement psiElement,
      @NotNull final Collection<PropertiesFile> selectedPropertiesFiles,
      @NotNull final String key,
      @NotNull final String value) {
    for (PropertiesFile selectedFile : selectedPropertiesFiles) {
      if (!FileModificationService.getInstance()
          .prepareFileForWrite(selectedFile.getContainingFile())) return;
    }
    UndoUtil.markPsiFileForUndo(psiElement.getContainingFile());

    ApplicationManager.getApplication()
        .runWriteAction(
            new Runnable() {
              public void run() {
                CommandProcessor.getInstance()
                    .executeCommand(
                        project,
                        new Runnable() {
                          public void run() {
                            try {
                              I18nUtil.createProperty(project, selectedPropertiesFiles, key, value);
                            } catch (IncorrectOperationException e) {
                              LOG.error(e);
                            }
                          }
                        },
                        CodeInsightBundle.message("quickfix.i18n.command.name"),
                        project);
              }
            });
  }
 @Override
 public void invoke(@NotNull Project project, Editor editor, PsiFile file)
     throws IncorrectOperationException {
   if (!FileModificationService.getInstance().prepareFileForWrite(file)) return;
   PsiExpression expression = getExpressionToSimplify(editor, file);
   SimplifyBooleanExpressionFix.simplifyExpression(expression);
 }
Example #4
0
 @Override
 public void invoke(@NotNull final Project project, final Editor editor, PsiFile file) {
   if (!FileModificationService.getInstance().prepareFileForWrite(file)) return;
   ApplicationManager.getApplication()
       .runWriteAction(
           () -> {
             final List<T> methodsToImport = getMembersToImport(false);
             if (methodsToImport.isEmpty()) return;
             createQuestionAction(methodsToImport, project, editor).execute();
           });
 }
 @Override
 public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) {
   if (!FileModificationService.getInstance()
       .preparePsiElementForWrite(descriptor.getPsiElement())) return;
   PsiElement castTypeElement = descriptor.getPsiElement();
   PsiTypeCastExpression cast =
       castTypeElement == null ? null : (PsiTypeCastExpression) castTypeElement.getParent();
   if (cast != null) {
     RedundantCastUtil.removeCast(cast);
   }
 }
  @Override
  public void invoke(@NotNull Project project, Editor editor, @NotNull PsiElement element)
      throws IncorrectOperationException {
    try {
      if (!FileModificationService.getInstance().preparePsiElementForWrite(element)) return;

      final PsiJavaToken token = (PsiJavaToken) element;
      final PsiPolyadicExpression expression =
          SplitConditionUtil.findCondition(element, true, false);

      final PsiLambdaExpression lambdaExpression =
          PsiTreeUtil.getParentOfType(expression, PsiLambdaExpression.class);
      LOG.assertTrue(lambdaExpression != null);
      final String lambdaParameterName =
          lambdaExpression.getParameterList().getParameters()[0].getName();

      final PsiMethodCallExpression methodCallExpression =
          PsiTreeUtil.getParentOfType(expression, PsiMethodCallExpression.class);
      LOG.assertTrue(methodCallExpression != null, expression);

      PsiExpression lOperand = getLOperands(expression, token);
      PsiExpression rOperand = getROperands(expression, token);

      final Collection<PsiComment> comments =
          PsiTreeUtil.findChildrenOfType(expression, PsiComment.class);

      final PsiMethodCallExpression chainedCall =
          (PsiMethodCallExpression)
              JavaPsiFacade.getElementFactory(project)
                  .createExpressionFromText(
                      "a.filter(" + lambdaParameterName + " -> x)", expression);
      final PsiExpression argExpression = chainedCall.getArgumentList().getExpressions()[0];
      final PsiElement rReplaced =
          ((PsiLambdaExpression) argExpression).getBody().replace(rOperand);

      final PsiExpression compoundArg = methodCallExpression.getArgumentList().getExpressions()[0];

      final int separatorOffset = token.getTextOffset();
      for (PsiComment comment : comments) {
        if (comment.getTextOffset() < separatorOffset) {
          compoundArg.getParent().add(comment);
        } else {
          rReplaced.getParent().add(comment);
        }
      }

      ((PsiLambdaExpression) compoundArg).getBody().replace(lOperand);

      chainedCall.getMethodExpression().getQualifierExpression().replace(methodCallExpression);
      methodCallExpression.replace(chainedCall);
    } catch (IncorrectOperationException e) {
      LOG.error(e);
    }
  }
 @Override
 public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) {
   final PsiTypeElement typeElement =
       PsiTreeUtil.getParentOfType(descriptor.getPsiElement(), PsiTypeElement.class);
   if (!FileModificationService.getInstance().preparePsiElementForWrite(typeElement)) return;
   final PsiMethodReferenceExpression expression =
       PsiTreeUtil.getParentOfType(typeElement, PsiMethodReferenceExpression.class);
   if (expression != null) {
     expression.replace(createMethodReference(expression, typeElement));
   }
 }
Example #8
0
 @Override
 public void invoke(@NotNull Project project, Editor editor, @NotNull PsiElement element) {
   if (prepareForWriting()
       && !FileModificationService.getInstance().preparePsiElementsForWrite(element)) {
     return;
   }
   final PsiElement matchingElement = findMatchingElement(element, editor);
   if (matchingElement == null) {
     return;
   }
   processIntention(editor, matchingElement);
 }
Example #9
0
  @Override
  public void invoke(
      @NotNull Project project,
      @NotNull PsiFile file,
      Editor editor,
      @NotNull PsiElement startElement,
      @NotNull PsiElement endElement) {
    final PsiMethod myMethod = (PsiMethod) startElement;

    if (!FileModificationService.getInstance().prepareFileForWrite(myMethod.getContainingFile()))
      return;
    final PsiType myReturnType = myReturnTypePointer.getType();
    if (myReturnType == null) return;
    if (myFixWholeHierarchy) {
      final PsiMethod superMethod = myMethod.findDeepestSuperMethod();
      final PsiType superReturnType = superMethod == null ? null : superMethod.getReturnType();
      if (superReturnType != null
          && !Comparing.equal(myReturnType, superReturnType)
          && !changeClassTypeArgument(
              myMethod,
              project,
              superReturnType,
              superMethod.getContainingClass(),
              editor,
              myReturnType)) {
        return;
      }
    }

    final List<PsiMethod> affectedMethods = changeReturnType(myMethod, myReturnType);

    PsiElementFactory factory = JavaPsiFacade.getInstance(project).getElementFactory();
    PsiReturnStatement statementToSelect = null;
    if (!PsiType.VOID.equals(myReturnType)) {
      final ReturnStatementAdder adder = new ReturnStatementAdder(factory, myReturnType);

      for (PsiMethod affectedMethod : affectedMethods) {
        PsiReturnStatement statement = adder.addReturnForMethod(file, affectedMethod);
        if (statement != null && affectedMethod == myMethod) {
          statementToSelect = statement;
        }
      }
    }

    if (statementToSelect != null) {
      Editor editorForMethod =
          getEditorForMethod(myMethod, project, editor, statementToSelect.getContainingFile());
      if (editorForMethod != null) {
        selectReturnValueInEditor(statementToSelect, editorForMethod);
      }
    }
  }
  @Override
  public void invoke(@NotNull final Project project, Editor editor, PsiFile file) {
    if (!FileModificationService.getInstance().prepareFileForWrite(file)) return;

    PsiDocumentManager.getInstance(project).commitAllDocuments();

    final List<PsiClassType> exceptions = new ArrayList<PsiClassType>();
    final PsiMethod targetMethod = collectExceptions(exceptions);
    if (targetMethod == null) return;

    Set<PsiClassType> unhandledExceptions = new THashSet<PsiClassType>(exceptions);

    addExceptionsToThrowsList(project, targetMethod, unhandledExceptions);
  }
Example #11
0
 private void invokeFix(
     final RefEntity element, final CommonProblemDescriptor descriptor, final int idx) {
   final QuickFix[] fixes = descriptor.getFixes();
   if (fixes != null && fixes.length > idx && fixes[idx] != null) {
     if (element instanceof RefElement) {
       PsiElement psiElement = ((RefElement) element).getElement();
       if (psiElement != null && psiElement.isValid()) {
         if (!FileModificationService.getInstance().preparePsiElementForWrite(psiElement)) return;
         performFix(element, descriptor, idx, fixes[idx]);
       }
     } else {
       performFix(element, descriptor, idx, fixes[idx]);
     }
   }
 }
 @Override
 public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) {
   final PsiReferenceParameterList typeArgumentList =
       (PsiReferenceParameterList) descriptor.getPsiElement();
   if (!FileModificationService.getInstance().preparePsiElementForWrite(typeArgumentList))
     return;
   try {
     final PsiMethodCallExpression expr =
         (PsiMethodCallExpression)
             JavaPsiFacade.getInstance(project)
                 .getElementFactory()
                 .createExpressionFromText("foo()", null);
     typeArgumentList.replace(expr.getTypeArgumentList());
   } catch (IncorrectOperationException e) {
     LOG.error(e);
   }
 }
Example #13
0
 @Override
 public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) {
   final PsiElement element = descriptor.getPsiElement();
   if (element != null) {
     if (!FileModificationService.getInstance().preparePsiElementForWrite(element)) return;
     final PsiLambdaExpression lambdaExpression =
         PsiTreeUtil.getParentOfType(element, PsiLambdaExpression.class);
     if (lambdaExpression != null) {
       final PsiElement body = lambdaExpression.getBody();
       if (body != null) {
         PsiExpression expression = LambdaUtil.extractSingleExpressionFromBody(body);
         if (expression != null) {
           body.replace(expression);
         }
       }
     }
   }
 }
 @Override
 public void invoke(@NotNull Project project, Editor editor, @NotNull PsiElement element)
     throws IncorrectOperationException {
   if (!FileModificationService.getInstance().preparePsiElementsForWrite(element)) return;
   final XmlAttribute attr = (XmlAttribute) element.getParent();
   final String name = attr.getName();
   final XmlAttributeDescriptor descriptor = attr.getDescriptor();
   LOG.assertTrue(descriptor != null);
   String value = attr.getValue();
   final PsiElement declaration = descriptor.getDeclaration();
   if (declaration instanceof PsiField) {
     final PsiType fieldType = ((PsiField) declaration).getType();
     final PsiType itemType =
         JavaGenericsUtil.getCollectionItemType(fieldType, declaration.getResolveScope());
     if (itemType != null) {
       final String typeNode = itemType.getPresentableText();
       JavaFxPsiUtil.insertImportWhenNeeded(
           (XmlFile) attr.getContainingFile(), typeNode, itemType.getCanonicalText());
       final String[] vals = value.split(",");
       value =
           StringUtil.join(
               vals,
               new Function<String, String>() {
                 @Override
                 public String fun(String s) {
                   return "<"
                       + typeNode
                       + " "
                       + FxmlConstants.FX_VALUE
                       + "=\""
                       + s.trim()
                       + "\"/>";
                 }
               },
               "\n");
     }
   }
   final XmlTag childTag =
       XmlElementFactory.getInstance(project)
           .createTagFromText("<" + name + ">" + value + "</" + name + ">");
   attr.getParent().add(childTag);
   attr.delete();
 }
 public void run() {
   final PsiFile psiFile = myField.getContainingFile();
   if (psiFile == null) return;
   if (!FileModificationService.getInstance().preparePsiElementForWrite(psiFile)) 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);
             }
           });
 }
 @Override
 public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) {
   if (!FileModificationService.getInstance()
       .preparePsiElementForWrite(descriptor.getPsiElement())) return;
   final PsiElement psiElement = descriptor.getPsiElement();
   if (psiElement instanceof PsiInstanceOfExpression) {
     try {
       final PsiExpression compareToNull =
           JavaPsiFacade.getInstance(psiElement.getProject())
               .getElementFactory()
               .createExpressionFromText(
                   ((PsiInstanceOfExpression) psiElement).getOperand().getText() + " != null",
                   psiElement.getParent());
       psiElement.replace(compareToNull);
     } catch (IncorrectOperationException e) {
       LOG.error(e);
     }
   }
 }
  public static void chooseColor(
      JComponent editorComponent, PsiElement element, String caption, boolean startInWriteAction) {
    final XmlAttributeValue literal =
        PsiTreeUtil.getParentOfType(element, XmlAttributeValue.class, false);
    if (literal == null) return;
    final String text = StringUtil.unquoteString(literal.getValue());

    Color oldColor;
    try {
      oldColor = Color.decode(text);
    } catch (NumberFormatException e) {
      oldColor = JBColor.GRAY;
    }
    Color color = ColorChooser.chooseColor(editorComponent, caption, oldColor, true);
    if (color == null) return;
    if (!Comparing.equal(color, oldColor)) {
      if (!FileModificationService.getInstance().preparePsiElementForWrite(element)) return;
      final String newText = "#" + ColorUtil.toHex(color);
      final PsiManager manager = literal.getManager();
      final XmlAttribute newAttribute =
          XmlElementFactory.getInstance(manager.getProject()).createXmlAttribute("name", newText);
      final Runnable replaceRunnable =
          new Runnable() {
            @Override
            public void run() {
              final XmlAttributeValue valueElement = newAttribute.getValueElement();
              assert valueElement != null;
              literal.replace(valueElement);
            }
          };
      if (startInWriteAction) {
        new WriteCommandAction(element.getProject(), caption) {
          @Override
          protected void run(@NotNull Result result) throws Throwable {
            replaceRunnable.run();
          }
        }.execute();
      } else {
        replaceRunnable.run();
      }
    }
  }
    @Override
    public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) {
      if (!FileModificationService.getInstance()
          .preparePsiElementForWrite(descriptor.getPsiElement())) return;
      final PsiModifierListOwner element =
          PsiTreeUtil.getParentOfType(descriptor.getPsiElement(), PsiModifierListOwner.class);
      if (element != null) {
        RefElement refElement = null;
        if (myManager != null) {
          refElement = myManager.getReference(element);
        }
        try {
          if (element instanceof PsiVariable) {
            ((PsiVariable) element).normalizeDeclaration();
          }

          PsiModifierList list = element.getModifierList();

          LOG.assertTrue(list != null);

          if (element instanceof PsiMethod) {
            PsiMethod psiMethod = (PsiMethod) element;
            PsiClass containingClass = psiMethod.getContainingClass();
            if (containingClass != null
                && containingClass.getParent() instanceof PsiFile
                && myHint == PsiModifier.PRIVATE
                && list.hasModifierProperty(PsiModifier.FINAL)) {
              list.setModifierProperty(PsiModifier.FINAL, false);
            }
          }

          list.setModifierProperty(myHint, true);
          if (refElement instanceof RefJavaElement) {
            RefJavaUtil.getInstance().setAccessModifier((RefJavaElement) refElement, myHint);
          }
        } catch (IncorrectOperationException e) {
          LOG.error(e);
        }
      }
    }
 @Override
 public void invoke(@NotNull Project project, Editor editor, PsiFile file) {
   if (!FileModificationService.getInstance().preparePsiElementsForWrite(myClass, myVariable))
     return;
   try {
     switch (myFixType) {
       case MAKE_FINAL:
         makeFinal();
         break;
       case MAKE_ARRAY:
         makeArray();
         break;
       case COPY_TO_FINAL:
         copyToFinal();
         break;
     }
   } catch (IncorrectOperationException e) {
     LOG.error(e);
   } finally {
     getVariablesToFix().clear();
   }
 }
  @Override
  public void invoke(@NotNull final Project project, Editor editor, final PsiFile file) {
    if (!FileModificationService.getInstance().prepareFileForWrite(file)) return;

    final PsiMethod method =
        SuperMethodWarningUtil.checkSuperMethod(
            myTargetMethod, RefactoringBundle.message("to.refactor"));
    if (method == null) return;
    myNewParametersInfo = getNewParametersInfo(myExpressions, myTargetMethod, mySubstitutor);

    final List<ParameterInfoImpl> parameterInfos =
        performChange(
            project,
            editor,
            file,
            method,
            myMinUsagesNumberToShowDialog,
            myNewParametersInfo,
            myChangeAllUsages,
            false);
    if (parameterInfos != null) {
      myNewParametersInfo = parameterInfos.toArray(new ParameterInfoImpl[parameterInfos.size()]);
    }
  }
  public void finishLookup(char completionChar, @Nullable final LookupElement item) {
    //noinspection deprecation,unchecked
    if (item == null
        || item instanceof EmptyLookupItem
        || item.getObject() instanceof DeferredUserLookupValue
            && item.as(LookupItem.CLASS_CONDITION_KEY) != null
            && !((DeferredUserLookupValue) item.getObject())
                .handleUserSelection(item.as(LookupItem.CLASS_CONDITION_KEY), myProject)) {
      doHide(false, true);
      fireItemSelected(null, completionChar);
      return;
    }

    if (myDisposed) { // DeferredUserLookupValue could close us in any way
      return;
    }

    final PsiFile file = getPsiFile();
    boolean writableOk =
        file == null || FileModificationService.getInstance().prepareFileForWrite(file);
    if (myDisposed) { // ensureFilesWritable could close us by showing a dialog
      return;
    }

    if (!writableOk) {
      doHide(false, true);
      fireItemSelected(null, completionChar);
      return;
    }

    final String prefix = itemPattern(item);
    boolean plainMatch =
        ContainerUtil.or(
            item.getAllLookupStrings(),
            new Condition<String>() {
              @Override
              public boolean value(String s) {
                return StringUtil.containsIgnoreCase(s, prefix);
              }
            });
    if (!plainMatch) {
      FeatureUsageTracker.getInstance()
          .triggerFeatureUsed(CodeCompletionFeatures.EDITING_COMPLETION_CAMEL_HUMPS);
    }

    myFinishing = true;
    ApplicationManager.getApplication()
        .runWriteAction(
            new Runnable() {
              public void run() {
                myEditor.getDocument().startGuardedBlockChecking();
                try {
                  insertLookupString(item, getPrefixLength(item));
                } finally {
                  myEditor.getDocument().stopGuardedBlockChecking();
                }
              }
            });

    if (myDisposed) { // any document listeners could close us
      return;
    }

    doHide(false, true);

    fireItemSelected(item, completionChar);
  }
 @Override
 public void invoke(@NotNull Project project, Editor editor, PsiFile file)
     throws IncorrectOperationException {
   if (!FileModificationService.getInstance().prepareFileForWrite(file)) return;
   myAnnotation.delete();
 }
  @Override
  public void invoke(@NotNull final Project project, final Editor editor, final PsiFile file)
      throws IncorrectOperationException {
    if (!FileModificationService.getInstance().prepareFileForWrite(file)) return;

    PsiMethod[] constructors = myClass.getConstructors();
    if (constructors.length == 0) {
      final AddDefaultConstructorFix defaultConstructorFix = new AddDefaultConstructorFix(myClass);
      ApplicationManager.getApplication()
          .runWriteAction(
              new Runnable() {
                @Override
                public void run() {
                  defaultConstructorFix.invoke(project, editor, file);
                }
              });
      constructors = myClass.getConstructors();
    }
    Arrays.sort(
        constructors,
        new Comparator<PsiMethod>() {
          @Override
          public int compare(PsiMethod c1, PsiMethod c2) {
            final PsiMethod cc1 = RefactoringUtil.getChainedConstructor(c1);
            final PsiMethod cc2 = RefactoringUtil.getChainedConstructor(c2);
            if (cc1 == c2) return 1;
            if (cc2 == c1) return -1;
            if (cc1 == null) {
              return cc2 == null ? 0 : compare(c1, cc2);
            } else {
              return cc2 == null ? compare(cc1, c2) : compare(cc1, cc2);
            }
          }
        });
    final ArrayList<PsiMethod> constrs =
        filterConstructorsIfFieldAlreadyAssigned(constructors, getField());
    if (constrs.size() > 1) {
      final PsiMethodMember[] members = new PsiMethodMember[constrs.size()];
      int i = 0;
      for (PsiMethod constructor : constrs) {
        members[i++] = new PsiMethodMember(constructor);
      }
      final List<PsiMethodMember> elements;
      if (ApplicationManager.getApplication().isUnitTestMode()) {
        elements = Arrays.asList(members);
      } else {
        final MemberChooser<PsiMethodMember> chooser =
            new MemberChooser<PsiMethodMember>(members, false, true, project);
        chooser.setTitle("Choose constructors to add parameter to");
        chooser.show();
        elements = chooser.getSelectedElements();
        if (elements == null) return;
      }

      for (PsiMethodMember member : elements) {
        if (!addParameterToConstructor(
            project, file, editor, member.getElement(), new PsiField[] {getField()})) break;
      }

    } else if (!constrs.isEmpty()) {
      final Collection<SmartPsiElementPointer<PsiField>> fieldsToFix = getFieldsToFix();
      try {
        final PsiMethod constructor = constrs.get(0);
        final LinkedHashSet<PsiField> fields = new LinkedHashSet<PsiField>();
        getFieldsToFix().add(myField);
        for (SmartPsiElementPointer<PsiField> elementPointer : fieldsToFix) {
          final PsiField field = elementPointer.getElement();
          if (field != null
              && isAvailable(field)
              && filterConstructorsIfFieldAlreadyAssigned(new PsiMethod[] {constructor}, field)
                  .contains(constructor)) {
            fields.add(field);
          }
        }
        if (constrs.size() == constructors.length
            && fields.size() > 1
            && !ApplicationManager.getApplication().isUnitTestMode()) {
          PsiFieldMember[] members = new PsiFieldMember[fields.size()];
          int i = 0;
          for (PsiField field : fields) {
            members[i++] = new PsiFieldMember(field);
          }
          MemberChooser<PsiElementClassMember> chooser =
              new MemberChooser<PsiElementClassMember>(members, false, true, project);
          chooser.setTitle("Choose Fields to Generate Constructor Parameters for");
          chooser.show();
          if (chooser.getExitCode() != DialogWrapper.OK_EXIT_CODE) return;
          final List<PsiElementClassMember> selectedElements = chooser.getSelectedElements();
          if (selectedElements == null) return;
          fields.clear();
          for (PsiElementClassMember member : selectedElements) {
            fields.add((PsiField) member.getElement());
          }
        }

        addParameterToConstructor(
            project,
            file,
            editor,
            constructor,
            constrs.size() == constructors.length
                ? fields.toArray(new PsiField[fields.size()])
                : new PsiField[] {getField()});
      } finally {
        fieldsToFix.clear();
      }
    }
  }
 @Override
 public void invoke(@NotNull Project project, Editor editor, PsiFile file) {
   if (!FileModificationService.getInstance().prepareFileForWrite(myVariable.getContainingFile()))
     return;
   removeVariableAndReferencingStatements(editor);
 }
  public static void invoke(
      final Project project, PsiFile file, final Editor editor, PsiElement element) {
    if (!FileModificationService.getInstance().prepareFileForWrite(file)) return;

    final PsiJavaCodeReferenceElement refExpr = (PsiJavaCodeReferenceElement) element.getParent();
    final PsiClass aClass = (PsiClass) refExpr.resolve();
    if (aClass == null) {
      return;
    }
    final PsiClass containingClass = PsiUtil.getTopLevelClass(refExpr);
    if (aClass != containingClass) {
      PsiImportList importList = ((PsiJavaFile) file).getImportList();
      if (importList == null) {
        return;
      }
      boolean alreadyImported = false;
      for (PsiImportStaticStatement statement : importList.getImportStaticStatements()) {
        if (!statement.isOnDemand()) continue;
        PsiClass staticResolve = statement.resolveTargetClass();
        if (aClass == staticResolve) {
          alreadyImported = true;
          break;
        }
      }
      if (!alreadyImported) {
        PsiImportStaticStatement importStaticStatement =
            JavaPsiFacade.getInstance(file.getProject())
                .getElementFactory()
                .createImportStaticStatement(aClass, "*");
        importList.add(importStaticStatement);
      }
    }

    List<PsiFile> roots = file.getViewProvider().getAllFiles();
    for (final PsiFile root : roots) {
      PsiElement copy = root.copy();
      final PsiManager manager = root.getManager();

      final TIntArrayList expressionToDequalifyOffsets = new TIntArrayList();
      copy.accept(
          new JavaRecursiveElementWalkingVisitor() {
            int delta;

            @Override
            public void visitReferenceElement(PsiJavaCodeReferenceElement expression) {
              if (isParameterizedReference(expression)) return;
              PsiElement qualifierExpression = expression.getQualifier();
              if (qualifierExpression instanceof PsiJavaCodeReferenceElement
                  && ((PsiJavaCodeReferenceElement) qualifierExpression).isReferenceTo(aClass)) {
                try {
                  PsiElement resolved = expression.resolve();
                  int end = expression.getTextRange().getEndOffset();
                  qualifierExpression.delete();
                  delta += end - expression.getTextRange().getEndOffset();
                  PsiElement after = expression.resolve();
                  if (manager.areElementsEquivalent(after, resolved)) {
                    expressionToDequalifyOffsets.add(
                        expression.getTextRange().getStartOffset() + delta);
                  }
                } catch (IncorrectOperationException e) {
                  LOG.error(e);
                }
              }
              super.visitElement(expression);
            }
          });

      expressionToDequalifyOffsets.forEachDescending(
          new TIntProcedure() {
            @Override
            public boolean execute(int offset) {
              PsiJavaCodeReferenceElement expression =
                  PsiTreeUtil.findElementOfClassAtOffset(
                      root, offset, PsiJavaCodeReferenceElement.class, false);
              if (expression == null) {
                return false;
              }
              PsiElement qualifierExpression = expression.getQualifier();
              if (qualifierExpression instanceof PsiJavaCodeReferenceElement
                  && ((PsiJavaCodeReferenceElement) qualifierExpression).isReferenceTo(aClass)) {
                qualifierExpression.delete();
                if (editor != null) {
                  HighlightManager.getInstance(project)
                      .addRangeHighlight(
                          editor,
                          expression.getTextRange().getStartOffset(),
                          expression.getTextRange().getEndOffset(),
                          EditorColorsManager.getInstance()
                              .getGlobalScheme()
                              .getAttributes(EditorColors.SEARCH_RESULT_ATTRIBUTES),
                          false,
                          null);
                }
              }

              return true;
            }
          });
    }
  }
    @Override
    public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) {
      final PsiForeachStatement foreachStatement =
          PsiTreeUtil.getParentOfType(descriptor.getPsiElement(), PsiForeachStatement.class);
      if (foreachStatement != null) {
        if (!FileModificationService.getInstance().preparePsiElementForWrite(foreachStatement))
          return;
        PsiStatement body = foreachStatement.getBody();
        final PsiExpression iteratedValue = foreachStatement.getIteratedValue();
        if (body != null && iteratedValue != null) {
          restoreComments(foreachStatement, body);

          final PsiParameter parameter = foreachStatement.getIterationParameter();
          final PsiIfStatement ifStmt = extractIfStatement(body);

          StringBuilder buffer = new StringBuilder(getIteratedValueText(iteratedValue));
          if (ifStmt != null) {
            final PsiStatement thenBranch = ifStmt.getThenBranch();
            LOG.assertTrue(thenBranch != null);
            buffer.append(".stream()");
            buffer.append(createFiltersChainText(body, parameter, ifStmt));
            body = thenBranch;
          }

          buffer.append(".").append(getForEachMethodName()).append("(");

          final String functionalExpressionText =
              createForEachFunctionalExpressionText(project, body, parameter);
          final PsiElementFactory elementFactory = JavaPsiFacade.getElementFactory(project);
          PsiExpressionStatement callStatement =
              (PsiExpressionStatement)
                  elementFactory.createStatementFromText(
                      buffer.toString() + functionalExpressionText + ");", foreachStatement);
          callStatement = (PsiExpressionStatement) foreachStatement.replace(callStatement);

          final PsiExpressionList argumentList =
              ((PsiCallExpression) callStatement.getExpression()).getArgumentList();
          LOG.assertTrue(argumentList != null, callStatement.getText());
          final PsiExpression[] expressions = argumentList.getExpressions();
          LOG.assertTrue(expressions.length == 1);

          if (expressions[0] instanceof PsiFunctionalExpression
              && ((PsiFunctionalExpression) expressions[0]).getFunctionalInterfaceType() == null) {
            callStatement =
                (PsiExpressionStatement)
                    callStatement.replace(
                        elementFactory.createStatementFromText(
                            buffer.toString()
                                + "("
                                + parameter.getText()
                                + ") -> "
                                + wrapInBlock(body)
                                + ");",
                            callStatement));
          }

          simplifyRedundantCast(callStatement);

          CodeStyleManager.getInstance(project)
              .reformat(
                  JavaCodeStyleManager.getInstance(project).shortenClassReferences(callStatement));
        }
      }
    }
    @Override
    public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) {
      final PsiForeachStatement foreachStatement =
          PsiTreeUtil.getParentOfType(descriptor.getPsiElement(), PsiForeachStatement.class);
      if (foreachStatement != null) {
        if (!FileModificationService.getInstance().preparePsiElementForWrite(foreachStatement))
          return;
        final PsiElementFactory elementFactory = JavaPsiFacade.getElementFactory(project);
        PsiStatement body = foreachStatement.getBody();
        final PsiExpression iteratedValue = foreachStatement.getIteratedValue();
        if (body != null && iteratedValue != null) {
          final PsiParameter parameter = foreachStatement.getIterationParameter();
          final PsiIfStatement ifStatement = extractIfStatement(body);
          final PsiMethodCallExpression methodCallExpression = extractAddCall(body, ifStatement);

          if (methodCallExpression == null) return;

          if (isAddAllCall(foreachStatement, body)) {
            restoreComments(foreachStatement, body);
            final PsiExpression qualifierExpression =
                methodCallExpression.getMethodExpression().getQualifierExpression();
            final String qualifierText =
                qualifierExpression != null ? qualifierExpression.getText() : "";
            final String callText =
                StringUtil.getQualifiedName(
                    qualifierText, "addAll(" + getIteratedValueText(iteratedValue) + ");");
            PsiElement result =
                foreachStatement.replace(
                    elementFactory.createStatementFromText(callText, foreachStatement));
            reformatWhenNeeded(project, result);
            return;
          }
          final StringBuilder builder =
              new StringBuilder(getIteratedValueText(iteratedValue) + ".stream()");

          builder.append(createFiltersChainText(body, parameter, ifStatement));
          builder.append(
              createMapperFunctionalExpressionText(
                  parameter, methodCallExpression.getArgumentList().getExpressions()[0]));

          builder.append(".collect(java.util.stream.Collectors.");
          PsiElement result = null;
          try {
            final PsiExpression qualifierExpression =
                methodCallExpression.getMethodExpression().getQualifierExpression();
            if (qualifierExpression instanceof PsiReferenceExpression) {
              final PsiElement resolve = ((PsiReferenceExpression) qualifierExpression).resolve();
              if (resolve instanceof PsiVariable) {
                if (resolve instanceof PsiLocalVariable
                    && foreachStatement.equals(
                        PsiTreeUtil.skipSiblingsForward(
                            resolve.getParent(), PsiWhiteSpace.class))) {
                  final PsiExpression initializer = ((PsiVariable) resolve).getInitializer();
                  if (initializer instanceof PsiNewExpression) {
                    final PsiExpressionList argumentList =
                        ((PsiNewExpression) initializer).getArgumentList();
                    if (argumentList != null && argumentList.getExpressions().length == 0) {
                      restoreComments(foreachStatement, body);
                      final String callText =
                          builder.toString()
                              + createInitializerReplacementText(
                                  ((PsiVariable) resolve).getType(), initializer)
                              + ")";
                      result =
                          initializer.replace(
                              elementFactory.createExpressionFromText(callText, null));
                      simplifyRedundantCast(result);
                      foreachStatement.delete();
                      return;
                    }
                  }
                }
              }
            }
            restoreComments(foreachStatement, body);
            final String qualifierText =
                qualifierExpression != null ? qualifierExpression.getText() : "";
            final String callText =
                StringUtil.getQualifiedName(
                    qualifierText, "addAll(" + builder.toString() + "toList()));");
            result =
                foreachStatement.replace(
                    elementFactory.createStatementFromText(callText, foreachStatement));
            simplifyRedundantCast(result);
          } finally {
            reformatWhenNeeded(project, result);
          }
        }
      }
    }
  public static List<ParameterInfoImpl> performChange(
      final Project project,
      final Editor editor,
      final PsiFile file,
      final PsiMethod method,
      final int minUsagesNumber,
      final ParameterInfoImpl[] newParametersInfo,
      final boolean changeAllUsages,
      final boolean allowDelegation) {
    if (!FileModificationService.getInstance().prepareFileForWrite(method.getContainingFile()))
      return null;
    final FindUsagesManager findUsagesManager =
        ((FindManagerImpl) FindManager.getInstance(project)).getFindUsagesManager();
    final FindUsagesHandler handler = findUsagesManager.getFindUsagesHandler(method, false);
    if (handler == null) return null; // on failure or cancel (e.g. cancel of super methods dialog)

    final JavaMethodFindUsagesOptions options = new JavaMethodFindUsagesOptions(project);
    options.isImplementingMethods = true;
    options.isOverridingMethods = true;
    options.isUsages = true;
    options.isSearchForTextOccurrences = false;
    final int[] usagesFound = new int[1];
    Runnable runnable =
        () -> {
          Processor<UsageInfo> processor = t -> ++usagesFound[0] < minUsagesNumber;

          handler.processElementUsages(method, processor, options);
        };
    String progressTitle = QuickFixBundle.message("searching.for.usages.progress.title");
    if (!ProgressManager.getInstance()
        .runProcessWithProgressSynchronously(runnable, progressTitle, true, project)) return null;

    if (ApplicationManager.getApplication().isUnitTestMode() || usagesFound[0] < minUsagesNumber) {
      ChangeSignatureProcessor processor =
          new ChangeSignatureProcessor(
              project,
              method,
              false,
              null,
              method.getName(),
              method.getReturnType(),
              newParametersInfo) {
            @Override
            @NotNull
            protected UsageInfo[] findUsages() {
              return changeAllUsages ? super.findUsages() : UsageInfo.EMPTY_ARRAY;
            }

            @Override
            protected void performRefactoring(@NotNull UsageInfo[] usages) {
              CommandProcessor.getInstance().setCurrentCommandName(getCommandName());
              super.performRefactoring(usages);
            }
          };
      processor.run();
      ApplicationManager.getApplication().runWriteAction(() -> UndoUtil.markPsiFileForUndo(file));
      return Arrays.asList(newParametersInfo);
    } else {
      final List<ParameterInfoImpl> parameterInfos =
          newParametersInfo != null
              ? new ArrayList<ParameterInfoImpl>(Arrays.asList(newParametersInfo))
              : new ArrayList<ParameterInfoImpl>();
      final PsiReferenceExpression refExpr =
          JavaTargetElementEvaluator.findReferenceExpression(editor);
      JavaChangeSignatureDialog dialog =
          JavaChangeSignatureDialog.createAndPreselectNew(
              project, method, parameterInfos, allowDelegation, refExpr);
      dialog.setParameterInfos(parameterInfos);
      dialog.show();
      return dialog.isOK() ? dialog.getParameters() : null;
    }
  }