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;
}
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();
}
}
}
}
}
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();
}
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();
}
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);
}
});
}
Aggregations