Search in sources :

Example 46 with JavaCodeStyleManager

use of com.intellij.psi.codeStyle.JavaCodeStyleManager in project intellij-community by JetBrains.

the class GenerateComponentExternalizationAction method actionPerformed.

public void actionPerformed(AnActionEvent e) {
    final PsiClass target = getComponentInContext(e.getDataContext());
    assert target != null;
    final PsiElementFactory factory = JavaPsiFacade.getInstance(target.getProject()).getElementFactory();
    final CodeStyleManager formatter = CodeStyleManager.getInstance(target.getManager().getProject());
    final JavaCodeStyleManager styler = JavaCodeStyleManager.getInstance(target.getProject());
    final String qualifiedName = target.getQualifiedName();
    Runnable runnable = () -> ApplicationManager.getApplication().runWriteAction(() -> {
        try {
            final PsiReferenceList implList = target.getImplementsList();
            assert implList != null;
            final PsiJavaCodeReferenceElement referenceElement = factory.createReferenceFromText(PERSISTENCE_STATE_COMPONENT + "<" + qualifiedName + ">", target);
            implList.add(styler.shortenClassReferences(referenceElement.copy()));
            PsiMethod read = factory.createMethodFromText("public void loadState(" + qualifiedName + " state) {\n" + "    com.intellij.util.xmlb.XmlSerializerUtil.copyBean(state, this);\n" + "}", target);
            read = (PsiMethod) formatter.reformat(target.add(read));
            styler.shortenClassReferences(read);
            PsiMethod write = factory.createMethodFromText("public " + qualifiedName + " getState() {\n" + "    return this;\n" + "}\n", target);
            write = (PsiMethod) formatter.reformat(target.add(write));
            styler.shortenClassReferences(write);
            PsiAnnotation annotation = target.getModifierList().addAnnotation(STATE);
            annotation = (PsiAnnotation) formatter.reformat(annotation.replace(factory.createAnnotationFromText("@" + STATE + "(name = \"" + qualifiedName + "\", " + "storages = {@" + STORAGE + "(file = \"" + StoragePathMacros.WORKSPACE_FILE + "\"\n )})", target)));
            styler.shortenClassReferences(annotation);
        } catch (IncorrectOperationException e1) {
            LOG.error(e1);
        }
    });
    CommandProcessor.getInstance().executeCommand(target.getProject(), runnable, DevKitBundle.message("command.implement.externalizable"), null);
}
Also used : JavaCodeStyleManager(com.intellij.psi.codeStyle.JavaCodeStyleManager) CodeStyleManager(com.intellij.psi.codeStyle.CodeStyleManager) JavaCodeStyleManager(com.intellij.psi.codeStyle.JavaCodeStyleManager) IncorrectOperationException(com.intellij.util.IncorrectOperationException)

Example 47 with JavaCodeStyleManager

use of com.intellij.psi.codeStyle.JavaCodeStyleManager in project intellij-community by JetBrains.

the class DataPointHolderConversionIntention method convertToMethod.

private static PsiMethod convertToMethod(final PsiField field) {
    final Project project = field.getProject();
    final PsiElementFactory elementFactory = JavaPsiFacade.getElementFactory(project);
    final JavaCodeStyleManager codeStyleManager = JavaCodeStyleManager.getInstance(project);
    final PsiExpression fieldInitializer = field.getInitializer();
    final PsiMethod method = elementFactory.createMethod(codeStyleManager.variableNameToPropertyName(field.getName(), VariableKind.STATIC_FIELD), field.getType());
    PsiCodeBlock body = method.getBody();
    assert body != null;
    final PsiStatement methodCode = elementFactory.createStatementFromText(PsiKeyword.RETURN + " " + fieldInitializer.getText() + ";", null);
    body.add(methodCode);
    return method;
}
Also used : Project(com.intellij.openapi.project.Project) JavaCodeStyleManager(com.intellij.psi.codeStyle.JavaCodeStyleManager)

Example 48 with JavaCodeStyleManager

use of com.intellij.psi.codeStyle.JavaCodeStyleManager in project intellij-community by JetBrains.

the class ReplaceForEachLoopWithIteratorForLoopIntention method processIntention.

@Override
public void processIntention(@NotNull PsiElement element) throws IncorrectOperationException {
    final PsiForeachStatement statement = (PsiForeachStatement) element.getParent();
    if (statement == null) {
        return;
    }
    final PsiExpression iteratedValue = statement.getIteratedValue();
    if (iteratedValue == null) {
        return;
    }
    final PsiType iteratedValueType = iteratedValue.getType();
    if (!(iteratedValueType instanceof PsiClassType)) {
        return;
    }
    @NonNls final StringBuilder methodCall = new StringBuilder();
    if (ParenthesesUtils.getPrecedence(iteratedValue) > ParenthesesUtils.METHOD_CALL_PRECEDENCE) {
        methodCall.append('(').append(iteratedValue.getText()).append(')');
    } else {
        methodCall.append(iteratedValue.getText());
    }
    methodCall.append(".iterator()");
    final Project project = statement.getProject();
    final PsiElementFactory factory = JavaPsiFacade.getInstance(project).getElementFactory();
    final PsiExpression iteratorCall = factory.createExpressionFromText(methodCall.toString(), iteratedValue);
    final PsiType variableType = GenericsUtil.getVariableTypeByExpressionType(iteratorCall.getType());
    if (variableType == null) {
        return;
    }
    @NonNls final StringBuilder newStatement = new StringBuilder();
    newStatement.append("for(").append(variableType.getCanonicalText()).append(' ');
    final JavaCodeStyleManager codeStyleManager = JavaCodeStyleManager.getInstance(project);
    final String iterator = codeStyleManager.suggestUniqueVariableName("iterator", statement, true);
    newStatement.append(iterator).append("=").append(iteratorCall.getText()).append(';');
    newStatement.append(iterator).append(".hasNext();) {");
    final CodeStyleSettings codeStyleSettings = CodeStyleSettingsManager.getSettings(project);
    if (codeStyleSettings.GENERATE_FINAL_LOCALS) {
        newStatement.append("final ");
    }
    final PsiParameter iterationParameter = statement.getIterationParameter();
    final PsiType parameterType = iterationParameter.getType();
    final String typeText = parameterType.getCanonicalText();
    newStatement.append(typeText).append(' ').append(iterationParameter.getName()).append(" = ").append(iterator).append(".next();");
    final PsiStatement body = statement.getBody();
    if (body == null) {
        return;
    }
    if (body instanceof PsiBlockStatement) {
        final PsiCodeBlock block = ((PsiBlockStatement) body).getCodeBlock();
        final PsiElement[] children = block.getChildren();
        for (int i = 1; i < children.length - 1; i++) {
            //skip the braces
            newStatement.append(children[i].getText());
        }
    } else {
        newStatement.append(body.getText());
    }
    newStatement.append('}');
    PsiReplacementUtil.replaceStatementAndShortenClassNames(statement, newStatement.toString());
}
Also used : NonNls(org.jetbrains.annotations.NonNls) Project(com.intellij.openapi.project.Project) CodeStyleSettings(com.intellij.psi.codeStyle.CodeStyleSettings) JavaCodeStyleManager(com.intellij.psi.codeStyle.JavaCodeStyleManager)

Example 49 with JavaCodeStyleManager

use of com.intellij.psi.codeStyle.JavaCodeStyleManager in project intellij-community by JetBrains.

the class ReplaceImplementsWithStaticImportAction method invoke.

@Override
public void invoke(@NotNull final Project project, final Editor editor, final PsiFile file) throws IncorrectOperationException {
    final int offset = editor.getCaretModel().getOffset();
    final PsiClass targetClass;
    final PsiReference psiReference = TargetElementUtil.findReference(editor);
    if (psiReference != null) {
        final PsiElement element = psiReference.getElement();
        final PsiClass psiClass = PsiTreeUtil.getParentOfType(element, PsiClass.class);
        LOG.assertTrue(psiClass != null);
        final PsiElement target = psiReference.resolve();
        LOG.assertTrue(target instanceof PsiClass);
        targetClass = (PsiClass) target;
    } else {
        final PsiElement identifier = file.findElementAt(offset);
        LOG.assertTrue(identifier instanceof PsiIdentifier);
        final PsiElement element = identifier.getParent();
        LOG.assertTrue(element instanceof PsiClass);
        targetClass = (PsiClass) element;
    }
    final Map<PsiFile, Map<PsiField, Set<PsiReference>>> refs = new HashMap<>();
    if (!ProgressManager.getInstance().runProcessWithProgressSynchronously(() -> ApplicationManager.getApplication().runReadAction(() -> {
        for (PsiField field : targetClass.getAllFields()) {
            final PsiClass containingClass = field.getContainingClass();
            for (PsiReference reference : ReferencesSearch.search(field)) {
                if (reference == null) {
                    continue;
                }
                final PsiElement refElement = reference.getElement();
                if (encodeQualifier(containingClass, reference, targetClass))
                    continue;
                final PsiFile psiFile = refElement.getContainingFile();
                if (psiFile instanceof PsiJavaFile) {
                    Map<PsiField, Set<PsiReference>> references = refs.get(psiFile);
                    if (references == null) {
                        references = new HashMap<>();
                        refs.put(psiFile, references);
                    }
                    Set<PsiReference> fieldsRefs = references.get(field);
                    if (fieldsRefs == null) {
                        fieldsRefs = new HashSet<>();
                        references.put(field, fieldsRefs);
                    }
                    fieldsRefs.add(reference);
                }
            }
        }
    }), FIND_CONSTANT_FIELD_USAGES, true, project)) {
        return;
    }
    final Set<PsiJavaCodeReferenceElement> refs2Unimplement = new HashSet<>();
    if (!ProgressManager.getInstance().runProcessWithProgressSynchronously(() -> ApplicationManager.getApplication().runReadAction(() -> {
        for (PsiClass psiClass : DirectClassInheritorsSearch.search(targetClass)) {
            PsiFile containingFile = psiClass.getContainingFile();
            if (!refs.containsKey(containingFile)) {
                refs.put(containingFile, new HashMap<>());
            }
            if (collectExtendsImplements(targetClass, psiClass.getExtendsList(), refs2Unimplement))
                continue;
            collectExtendsImplements(targetClass, psiClass.getImplementsList(), refs2Unimplement);
        }
    }), "Find References in Implement/Extends Lists...", true, project)) {
        return;
    }
    if (!FileModificationService.getInstance().preparePsiElementsForWrite(refs.keySet()))
        return;
    ApplicationManager.getApplication().runWriteAction(() -> {
        for (PsiFile psiFile : refs.keySet()) {
            final Map<PsiField, Set<PsiReference>> map = refs.get(psiFile);
            for (PsiField psiField : map.keySet()) {
                final PsiClass containingClass = psiField.getContainingClass();
                final String fieldName = psiField.getName();
                for (PsiReference reference : map.get(psiField)) {
                    bindReference(psiFile, psiField, containingClass, fieldName, reference, project);
                }
            }
        }
        for (PsiJavaCodeReferenceElement referenceElement : refs2Unimplement) {
            referenceElement.delete();
        }
    });
    final Map<PsiJavaFile, PsiImportList> redundant = new HashMap<>();
    final JavaCodeStyleManager codeStyleManager = JavaCodeStyleManager.getInstance(project);
    if (!ProgressManager.getInstance().runProcessWithProgressSynchronously(() -> ApplicationManager.getApplication().runReadAction(() -> {
        for (PsiFile psiFile : refs.keySet()) {
            if (psiFile instanceof PsiJavaFile) {
                final PsiImportList prepared = codeStyleManager.prepareOptimizeImportsResult((PsiJavaFile) psiFile);
                if (prepared != null) {
                    redundant.put((PsiJavaFile) psiFile, prepared);
                }
            }
        }
    }), "Optimize Imports...", true, project))
        return;
    ApplicationManager.getApplication().runWriteAction(() -> {
        for (PsiJavaFile file1 : redundant.keySet()) {
            final PsiImportList importList = redundant.get(file1);
            if (importList != null) {
                final PsiImportList list = file1.getImportList();
                if (list != null) {
                    list.replace(importList);
                }
            }
        }
    });
}
Also used : JavaCodeStyleManager(com.intellij.psi.codeStyle.JavaCodeStyleManager)

Example 50 with JavaCodeStyleManager

use of com.intellij.psi.codeStyle.JavaCodeStyleManager in project intellij-community by JetBrains.

the class OptionalIsPresentInspection method generateOptionalLambda.

@NotNull
static String generateOptionalLambda(PsiElementFactory factory, CommentTracker ct, PsiVariable optionalVariable, PsiElement trueValue) {
    PsiType type = optionalVariable.getType();
    JavaCodeStyleManager javaCodeStyleManager = JavaCodeStyleManager.getInstance(trueValue.getProject());
    SuggestedNameInfo info = javaCodeStyleManager.suggestVariableName(VariableKind.PARAMETER, null, null, type);
    if (info.names.length == 0) {
        info = javaCodeStyleManager.suggestVariableName(VariableKind.PARAMETER, "value", null, type);
    }
    String paramName = javaCodeStyleManager.suggestUniqueVariableName(info, trueValue, true).names[0];
    if (trueValue instanceof PsiExpressionStatement) {
        trueValue = ((PsiExpressionStatement) trueValue).getExpression();
    }
    ct.markUnchanged(trueValue);
    PsiElement copy = trueValue.copy();
    for (PsiElement getCall : PsiTreeUtil.collectElements(copy, e -> isOptionalGetCall(e, optionalVariable))) {
        PsiElement result = getCall.replace(factory.createIdentifier(paramName));
        if (copy == getCall)
            copy = result;
    }
    if (copy instanceof PsiStatement && !(copy instanceof PsiBlockStatement)) {
        return paramName + "->{" + copy.getText() + "}";
    }
    return paramName + "->" + copy.getText();
}
Also used : JavaCodeStyleManager(com.intellij.psi.codeStyle.JavaCodeStyleManager) SuggestedNameInfo(com.intellij.psi.codeStyle.SuggestedNameInfo) NotNull(org.jetbrains.annotations.NotNull)

Aggregations

JavaCodeStyleManager (com.intellij.psi.codeStyle.JavaCodeStyleManager)96 Project (com.intellij.openapi.project.Project)27 SuggestedNameInfo (com.intellij.psi.codeStyle.SuggestedNameInfo)21 VariableKind (com.intellij.psi.codeStyle.VariableKind)19 IncorrectOperationException (com.intellij.util.IncorrectOperationException)15 NotNull (org.jetbrains.annotations.NotNull)13 CodeStyleManager (com.intellij.psi.codeStyle.CodeStyleManager)12 Nullable (org.jetbrains.annotations.Nullable)12 ArrayList (java.util.ArrayList)10 NonNls (org.jetbrains.annotations.NonNls)8 StringUtil (com.intellij.openapi.util.text.StringUtil)3 UniqueNameGenerator (com.intellij.util.text.UniqueNameGenerator)3 HashSet (java.util.HashSet)3 JavaLanguage (com.intellij.lang.java.JavaLanguage)2 Logger (com.intellij.openapi.diagnostic.Logger)2 Editor (com.intellij.openapi.editor.Editor)2 Comparing (com.intellij.openapi.util.Comparing)2 com.intellij.psi (com.intellij.psi)2 CodeStyleSettings (com.intellij.psi.codeStyle.CodeStyleSettings)2 FunctionalInterfaceParameterizationUtil (com.intellij.psi.impl.source.resolve.graphInference.FunctionalInterfaceParameterizationUtil)2