Search in sources :

Example 86 with JavaCodeStyleManager

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

the class CopyClassesHandler method doCopyClasses.

@Nullable
public static Collection<PsiFile> doCopyClasses(final Map<PsiFile, PsiClass[]> fileToClasses, @Nullable HashMap<PsiFile, String> map, final String copyClassName, final PsiDirectory targetDirectory, final Project project) throws IncorrectOperationException {
    PsiElement newElement = null;
    final Map<PsiClass, PsiElement> oldToNewMap = new HashMap<>();
    for (final PsiClass[] psiClasses : fileToClasses.values()) {
        if (psiClasses != null) {
            for (PsiClass aClass : psiClasses) {
                if (isSynthetic(aClass)) {
                    continue;
                }
                oldToNewMap.put(aClass, null);
            }
        }
    }
    final List<PsiFile> createdFiles = new ArrayList<>(fileToClasses.size());
    int[] choice = fileToClasses.size() > 1 ? new int[] { -1 } : null;
    List<PsiFile> files = new ArrayList<>();
    for (final Map.Entry<PsiFile, PsiClass[]> entry : fileToClasses.entrySet()) {
        final PsiFile psiFile = entry.getKey();
        final PsiClass[] sources = entry.getValue();
        if (psiFile instanceof PsiClassOwner && sources != null) {
            final PsiFile createdFile = copy(psiFile, targetDirectory, copyClassName, map == null ? null : map.get(psiFile), choice);
            if (createdFile == null) {
                //do not touch unmodified classes
                for (PsiClass aClass : ((PsiClassOwner) psiFile).getClasses()) {
                    oldToNewMap.remove(aClass);
                }
                continue;
            }
            PsiClass[] classes = ((PsiClassOwner) createdFile).getClasses();
            for (final PsiClass destination : classes) {
                if (isSynthetic(destination)) {
                    continue;
                }
                PsiClass source = findByName(sources, destination.getName());
                if (source != null) {
                    final PsiClass copy = copy(source, classes.length > 1 ? null : copyClassName);
                    newElement = WriteAction.compute(() -> destination.replace(copy));
                    oldToNewMap.put(source, newElement);
                } else {
                    WriteAction.run(() -> destination.delete());
                }
            }
            createdFiles.add(createdFile);
        } else {
            files.add(psiFile);
        }
    }
    for (PsiFile file : files) {
        try {
            PsiDirectory finalTarget = targetDirectory;
            final String relativePath = map != null ? map.get(file) : null;
            if (relativePath != null && !relativePath.isEmpty()) {
                finalTarget = WriteAction.compute(() -> buildRelativeDir(targetDirectory, relativePath).findOrCreateTargetDirectory());
            }
            final PsiFile fileCopy = CopyFilesOrDirectoriesHandler.copyToDirectory(file, getNewFileName(file, copyClassName), finalTarget, choice, null);
            if (fileCopy != null) {
                createdFiles.add(fileCopy);
            }
        } catch (IOException e) {
            throw new IncorrectOperationException(e.getMessage());
        }
    }
    WriteAction.run(() -> {
        final Set<PsiElement> rebindExpressions = new HashSet<>();
        for (PsiElement element : oldToNewMap.values()) {
            if (element == null) {
                LOG.error(oldToNewMap.keySet());
                continue;
            }
            decodeRefs(element, oldToNewMap, rebindExpressions);
        }
        final JavaCodeStyleManager codeStyleManager = JavaCodeStyleManager.getInstance(project);
        for (PsiFile psiFile : createdFiles) {
            if (psiFile instanceof PsiJavaFile) {
                codeStyleManager.removeRedundantImports((PsiJavaFile) psiFile);
            }
        }
        for (PsiElement expression : rebindExpressions) {
            //new expressions/type elements, like: List<List<String>>; new Foo(new Foo()), etc
            if (expression.isValid()) {
                codeStyleManager.shortenClassReferences(expression);
            }
        }
    });
    new OptimizeImportsProcessor(project, createdFiles.toArray(new PsiFile[createdFiles.size()]), null).run();
    return createdFiles;
}
Also used : OptimizeImportsProcessor(com.intellij.codeInsight.actions.OptimizeImportsProcessor) IOException(java.io.IOException) JavaCodeStyleManager(com.intellij.psi.codeStyle.JavaCodeStyleManager) IncorrectOperationException(com.intellij.util.IncorrectOperationException) Nullable(org.jetbrains.annotations.Nullable)

Example 87 with JavaCodeStyleManager

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

the class UsedIconsListingAction method doReplacements.

private static void doReplacements(final Project project, MultiMap<String, PsiExpression> calls, List<XmlAttribute> xmlAttributes, MultiMap<String, PsiAnnotation> annotations, PsiClass iconClass) {
    final HashMap<String, String> mappings = new HashMap<>();
    int size = mappings.size();
    collectFields(iconClass, "", mappings);
    System.out.println("Found " + (mappings.size() - size) + " icons in " + iconClass.getQualifiedName());
    GlobalSearchScope useScope = (GlobalSearchScope) iconClass.getUseScope();
    for (final XmlAttribute att : xmlAttributes) {
        if (!att.isValid())
            continue;
        String value = att.getValue();
        final String replacement = mappings.get(value);
        if (replacement != null) {
            final PsiFile file = att.getContainingFile();
            if (useScope.contains(file.getVirtualFile())) {
                new WriteCommandAction<Void>(project, file) {

                    @Override
                    protected void run(@NotNull Result<Void> result) throws Throwable {
                        att.setValue(replacement);
                    }
                }.execute();
            }
        }
    }
    final JVMElementFactory factory = JVMElementFactories.getFactory(JavaLanguage.INSTANCE, project);
    for (Map.Entry<String, Collection<PsiExpression>> entry : calls.entrySet()) {
        String path = entry.getKey();
        final String replacement = mappings.get(path);
        if (replacement != null) {
            for (final PsiExpression call : entry.getValue()) {
                if (!call.isValid())
                    continue;
                final PsiFile file = call.getContainingFile();
                if (useScope.contains(file.getVirtualFile())) {
                    new WriteCommandAction(project, file) {

                        @Override
                        protected void run(@NotNull Result result) throws Throwable {
                            if (call instanceof PsiLiteralExpression) {
                                call.replace(factory.createExpressionFromText("\"" + replacement + "\"", call));
                            } else {
                                JavaCodeStyleManager styleManager = JavaCodeStyleManager.getInstance(project);
                                String packageName = replacement.startsWith("AllIcons.") ? "com.intellij.icons." : "icons.";
                                PsiElement expr = factory.createExpressionFromText(packageName + replacement, call);
                                styleManager.shortenClassReferences(call.replace(expr));
                            }
                        }
                    }.execute();
                }
            }
        }
    }
    for (Map.Entry<String, Collection<PsiAnnotation>> entry : annotations.entrySet()) {
        String path = entry.getKey();
        final String replacement = mappings.get(path);
        if (replacement != null) {
            for (final PsiAnnotation annotation : entry.getValue()) {
                if (annotation instanceof PsiCompiledElement)
                    continue;
                if (!annotation.isValid())
                    continue;
                PsiFile file = annotation.getContainingFile();
                if (useScope.contains(file.getVirtualFile())) {
                    new WriteCommandAction(project, file) {

                        @Override
                        protected void run(@NotNull Result result) throws Throwable {
                            annotation.getNode();
                            annotation.setDeclaredAttributeValue("icon", JavaPsiFacade.getInstance(annotation.getProject()).getElementFactory().createAnnotationFromText("@A(\"" + replacement + "\")", null).findDeclaredAttributeValue(null));
                        }
                    }.execute();
                }
            }
        }
    }
}
Also used : WriteCommandAction(com.intellij.openapi.command.WriteCommandAction) XmlAttribute(com.intellij.psi.xml.XmlAttribute) Result(com.intellij.openapi.application.Result) DelegatingGlobalSearchScope(com.intellij.psi.search.DelegatingGlobalSearchScope) GlobalSearchScope(com.intellij.psi.search.GlobalSearchScope) JavaCodeStyleManager(com.intellij.psi.codeStyle.JavaCodeStyleManager) MultiMap(com.intellij.util.containers.MultiMap)

Example 88 with JavaCodeStyleManager

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

the class LambdaRefactoringUtil method createLambdaWithoutFormalParameters.

private static String createLambdaWithoutFormalParameters(PsiMethodReferenceExpression referenceExpression) {
    PsiType functionalInterfaceType = referenceExpression.getFunctionalInterfaceType();
    final PsiElement resolve = referenceExpression.resolve();
    if (resolve == null) {
        return null;
    }
    final PsiClassType.ClassResolveResult functionalInterfaceResolveResult = PsiUtil.resolveGenericsClassInType(functionalInterfaceType);
    final PsiMethod interfaceMethod = LambdaUtil.getFunctionalInterfaceMethod(functionalInterfaceType);
    if (interfaceMethod == null) {
        return null;
    }
    final PsiSubstitutor psiSubstitutor = LambdaUtil.getSubstitutor(interfaceMethod, functionalInterfaceResolveResult);
    final MethodSignature signature = interfaceMethod.getSignature(psiSubstitutor);
    final boolean isReceiver;
    if (resolve instanceof PsiMethod) {
        final PsiMethod method = (PsiMethod) resolve;
        isReceiver = PsiMethodReferenceUtil.isResolvedBySecondSearch(referenceExpression, signature, method.isVarArgs(), method.hasModifierProperty(PsiModifier.STATIC), method.getParameterList().getParametersCount());
    } else {
        isReceiver = false;
    }
    final PsiParameter[] psiParameters = resolve instanceof PsiMethod ? ((PsiMethod) resolve).getParameterList().getParameters() : null;
    final PsiParameterList parameterList = interfaceMethod.getParameterList();
    final PsiParameter[] parameters = parameterList.getParameters();
    final Map<PsiParameter, String> map = new HashMap<>();
    final UniqueNameGenerator nameGenerator = new UniqueNameGenerator();
    final JavaCodeStyleManager codeStyleManager = JavaCodeStyleManager.getInstance(referenceExpression.getProject());
    Function<PsiParameter, String> paramPresentationFunction = parameter -> {
        final int parameterIndex = parameterList.getParameterIndex(parameter);
        String baseName;
        if (isReceiver && parameterIndex == 0) {
            final SuggestedNameInfo nameInfo = codeStyleManager.suggestVariableName(VariableKind.PARAMETER, null, null, psiSubstitutor.substitute(parameter.getType()));
            baseName = nameInfo.names.length > 0 ? nameInfo.names[0] : parameter.getName();
        } else {
            String initialName;
            if (psiParameters != null) {
                final int idx = parameterIndex - (isReceiver ? 1 : 0);
                initialName = psiParameters.length > 0 ? psiParameters[idx < psiParameters.length ? idx : psiParameters.length - 1].getName() : parameter.getName();
            } else {
                initialName = parameter.getName();
            }
            LOG.assertTrue(initialName != null);
            if ("_".equals(initialName)) {
                SuggestedNameInfo nameInfo = codeStyleManager.suggestVariableName(VariableKind.PARAMETER, null, null, psiSubstitutor.substitute(parameter.getType()));
                if (nameInfo.names.length > 0) {
                    initialName = nameInfo.names[0];
                }
            }
            baseName = codeStyleManager.variableNameToPropertyName(initialName, VariableKind.PARAMETER);
        }
        if (baseName != null) {
            String parameterName = nameGenerator.generateUniqueName(codeStyleManager.suggestUniqueVariableName(baseName, referenceExpression, true));
            map.put(parameter, parameterName);
            return parameterName;
        }
        return "";
    };
    StringBuilder buf = new StringBuilder();
    if (parameters.length == 1) {
        buf.append(paramPresentationFunction.fun(parameters[0]));
    } else {
        buf.append("(").append(StringUtil.join(parameters, paramPresentationFunction, ", ")).append(")");
    }
    buf.append(" -> ");
    final JavaResolveResult resolveResult = referenceExpression.advancedResolve(false);
    final PsiElement resolveElement = resolveResult.getElement();
    if (resolveElement instanceof PsiMember) {
        final PsiElementFactory elementFactory = JavaPsiFacade.getElementFactory(referenceExpression.getProject());
        buf.append("{");
        if (!PsiType.VOID.equals(interfaceMethod.getReturnType())) {
            buf.append("return ");
        }
        final PsiMethodReferenceUtil.QualifierResolveResult qualifierResolveResult = PsiMethodReferenceUtil.getQualifierResolveResult(referenceExpression);
        final PsiElement qualifier = referenceExpression.getQualifier();
        PsiClass containingClass = qualifierResolveResult.getContainingClass();
        final boolean onArrayRef = elementFactory.getArrayClass(PsiUtil.getLanguageLevel(referenceExpression)) == containingClass;
        final PsiElement referenceNameElement = referenceExpression.getReferenceNameElement();
        if (isReceiver) {
            buf.append(map.get(parameters[0])).append(".");
        } else {
            if (!(referenceNameElement instanceof PsiKeyword)) {
                if (qualifier instanceof PsiTypeElement) {
                    final PsiJavaCodeReferenceElement referenceElement = ((PsiTypeElement) qualifier).getInnermostComponentReferenceElement();
                    LOG.assertTrue(referenceElement != null);
                    if (!PsiTreeUtil.isAncestor(containingClass, referenceExpression, false)) {
                        buf.append(referenceElement.getReferenceName()).append(".");
                    }
                } else if (qualifier != null && !isQualifierUnnecessary(qualifier, containingClass)) {
                    buf.append(qualifier.getText()).append(".");
                }
            }
        }
        //new or method name
        buf.append(referenceExpression.getReferenceName());
        if (referenceNameElement instanceof PsiKeyword) {
            //class name
            buf.append(" ");
            if (onArrayRef) {
                if (qualifier instanceof PsiTypeElement) {
                    final PsiType type = ((PsiTypeElement) qualifier).getType();
                    int dim = type.getArrayDimensions();
                    buf.append(type.getDeepComponentType().getCanonicalText());
                    buf.append("[");
                    buf.append(map.get(parameters[0]));
                    buf.append("]");
                    while (--dim > 0) {
                        buf.append("[]");
                    }
                }
            } else {
                buf.append(((PsiMember) resolveElement).getName());
                final PsiSubstitutor substitutor = resolveResult.getSubstitutor();
                LOG.assertTrue(containingClass != null);
                if (containingClass.hasTypeParameters() && !PsiUtil.isRawSubstitutor(containingClass, substitutor)) {
                    buf.append("<").append(StringUtil.join(containingClass.getTypeParameters(), parameter -> {
                        final PsiType psiType = substitutor.substitute(parameter);
                        LOG.assertTrue(psiType != null);
                        return psiType.getCanonicalText();
                    }, ", ")).append(">");
                }
            }
        }
        if (!onArrayRef || isReceiver) {
            //param list
            buf.append("(");
            boolean first = true;
            for (int i = isReceiver ? 1 : 0; i < parameters.length; i++) {
                PsiParameter parameter = parameters[i];
                if (!first) {
                    buf.append(", ");
                } else {
                    first = false;
                }
                buf.append(map.get(parameter));
            }
            buf.append(")");
        }
        buf.append(";}");
    }
    return buf.toString();
}
Also used : PsiTypesUtil(com.intellij.psi.util.PsiTypesUtil) SuggestedNameInfo(com.intellij.psi.codeStyle.SuggestedNameInfo) IntroduceVariableHandler(com.intellij.refactoring.introduceVariable.IntroduceVariableHandler) ElementToWorkOn(com.intellij.refactoring.introduceField.ElementToWorkOn) HashMap(java.util.HashMap) SideEffectChecker(com.siyeh.ig.psiutils.SideEffectChecker) JavaCodeStyleManager(com.intellij.psi.codeStyle.JavaCodeStyleManager) ArrayList(java.util.ArrayList) DefaultParameterTypeInferencePolicy(com.intellij.psi.impl.source.resolve.DefaultParameterTypeInferencePolicy) PsiTreeUtil(com.intellij.psi.util.PsiTreeUtil) Map(java.util.Map) PsiUtil(com.intellij.psi.util.PsiUtil) Messages(com.intellij.openapi.ui.Messages) Logger(com.intellij.openapi.diagnostic.Logger) StringUtil(com.intellij.openapi.util.text.StringUtil) MethodCandidateInfo(com.intellij.psi.infos.MethodCandidateInfo) UniqueNameGenerator(com.intellij.util.text.UniqueNameGenerator) Editor(com.intellij.openapi.editor.Editor) Nullable(org.jetbrains.annotations.Nullable) List(java.util.List) MethodSignature(com.intellij.psi.util.MethodSignature) VariableKind(com.intellij.psi.codeStyle.VariableKind) RedundantLambdaCodeBlockInspection(com.intellij.codeInspection.RedundantLambdaCodeBlockInspection) Function(com.intellij.util.Function) ApplicationManager(com.intellij.openapi.application.ApplicationManager) FunctionalInterfaceParameterizationUtil(com.intellij.psi.impl.source.resolve.graphInference.FunctionalInterfaceParameterizationUtil) com.intellij.psi(com.intellij.psi) NotNull(org.jetbrains.annotations.NotNull) HashMap(java.util.HashMap) JavaCodeStyleManager(com.intellij.psi.codeStyle.JavaCodeStyleManager) SuggestedNameInfo(com.intellij.psi.codeStyle.SuggestedNameInfo) MethodSignature(com.intellij.psi.util.MethodSignature) UniqueNameGenerator(com.intellij.util.text.UniqueNameGenerator)

Example 89 with JavaCodeStyleManager

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

the class TypeMigrationProcessor method runHighlightingTypeMigration.

public static void runHighlightingTypeMigration(final Project project, final Editor editor, final TypeMigrationRules rules, final PsiElement[] roots, final Function<PsiElement, PsiType> migrationTypeFunction, final boolean optimizeImports) {
    final Set<PsiFile> containingFiles = ContainerUtil.map2Set(roots, element -> element.getContainingFile());
    final TypeMigrationProcessor processor = new TypeMigrationProcessor(project, roots, migrationTypeFunction, rules) {

        @Override
        public void performRefactoring(@NotNull final UsageInfo[] usages) {
            super.performRefactoring(usages);
            if (editor != null) {
                ApplicationManager.getApplication().invokeLater(() -> {
                    final List<PsiElement> result = new ArrayList<>();
                    for (UsageInfo usage : usages) {
                        final PsiElement element = usage.getElement();
                        if (element == null || !containingFiles.contains(element.getContainingFile()))
                            continue;
                        if (element instanceof PsiMethod) {
                            result.add(((PsiMethod) element).getReturnTypeElement());
                        } else if (element instanceof PsiVariable) {
                            result.add(((PsiVariable) element).getTypeElement());
                        } else {
                            result.add(element);
                        }
                    }
                    RefactoringUtil.highlightAllOccurrences(project, PsiUtilCore.toPsiElementArray(result), editor);
                });
            }
            if (optimizeImports) {
                final JavaCodeStyleManager javaCodeStyleManager = JavaCodeStyleManager.getInstance(myProject);
                final Set<PsiFile> affectedFiles = new THashSet<>();
                for (UsageInfo usage : usages) {
                    final PsiFile usageFile = usage.getFile();
                    if (usageFile != null) {
                        affectedFiles.add(usageFile);
                    }
                }
                for (PsiFile file : affectedFiles) {
                    javaCodeStyleManager.optimizeImports(file);
                    javaCodeStyleManager.shortenClassReferences(file);
                }
            }
        }
    };
    processor.run();
}
Also used : JavaCodeStyleManager(com.intellij.psi.codeStyle.JavaCodeStyleManager) ObjectUtils.assertNotNull(com.intellij.util.ObjectUtils.assertNotNull) NotNull(org.jetbrains.annotations.NotNull) UsageInfo(com.intellij.usageView.UsageInfo) TypeMigrationUsageInfo(com.intellij.refactoring.typeMigration.usageInfo.TypeMigrationUsageInfo) THashSet(gnu.trove.THashSet)

Example 90 with JavaCodeStyleManager

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

the class CreateFieldFromParameterActionBase method processParameter.

private void processParameter(@NotNull final Project project, @NotNull final PsiParameter myParameter, final boolean isInteractive) {
    final PsiType type = getSubstitutedType(myParameter);
    final JavaCodeStyleManager styleManager = JavaCodeStyleManager.getInstance(project);
    final String parameterName = myParameter.getName();
    String propertyName = styleManager.variableNameToPropertyName(parameterName, VariableKind.PARAMETER);
    String fieldNameToCalc;
    boolean isFinalToCalc;
    final PsiClass targetClass = PsiTreeUtil.getParentOfType(myParameter, PsiClass.class);
    final PsiMethod method = (PsiMethod) myParameter.getDeclarationScope();
    final boolean isMethodStatic = method.hasModifierProperty(PsiModifier.STATIC);
    VariableKind kind = isMethodStatic ? VariableKind.STATIC_FIELD : VariableKind.FIELD;
    SuggestedNameInfo suggestedNameInfo = styleManager.suggestVariableName(kind, propertyName, null, type);
    String[] names = suggestedNameInfo.names;
    if (isInteractive) {
        List<String> namesList = new ArrayList<>();
        ContainerUtil.addAll(namesList, names);
        String defaultName = styleManager.propertyNameToVariableName(propertyName, kind);
        if (namesList.contains(defaultName)) {
            Collections.swap(namesList, 0, namesList.indexOf(defaultName));
        } else {
            namesList.add(0, defaultName);
        }
        names = ArrayUtil.toStringArray(namesList);
        final CreateFieldFromParameterDialog dialog = new CreateFieldFromParameterDialog(project, names, targetClass, method.isConstructor(), type);
        if (!dialog.showAndGet()) {
            return;
        }
        fieldNameToCalc = dialog.getEnteredName();
        isFinalToCalc = dialog.isDeclareFinal();
        suggestedNameInfo.nameChosen(fieldNameToCalc);
    } else {
        isFinalToCalc = !isMethodStatic && method.isConstructor();
        fieldNameToCalc = names[0];
    }
    final boolean isFinal = isFinalToCalc;
    final String fieldName = fieldNameToCalc;
    ApplicationManager.getApplication().runWriteAction(() -> {
        try {
            performRefactoring(project, targetClass, method, myParameter, type, fieldName, isMethodStatic, isFinal);
        } catch (IncorrectOperationException e) {
            LOG.error(e);
        }
    });
}
Also used : ArrayList(java.util.ArrayList) JavaCodeStyleManager(com.intellij.psi.codeStyle.JavaCodeStyleManager) IncorrectOperationException(com.intellij.util.IncorrectOperationException) SuggestedNameInfo(com.intellij.psi.codeStyle.SuggestedNameInfo) VariableKind(com.intellij.psi.codeStyle.VariableKind)

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