From baa53a97fc513af72f3b95cd50a80f4cb99cd679 Mon Sep 17 00:00:00 2001 From: UNV Date: Mon, 8 Dec 2025 20:30:09 +0300 Subject: [PATCH] Localizing refactoring conflicts gathering (part 2). --- .../ChangeClassSignatureProcessor.java | 33 +- .../ChangeSignatureProcessor.java | 25 +- .../ConvertToInstanceMethodProcessor.java | 11 +- .../EncapsulateFieldsProcessor.java | 51 +- .../extractclass/ExtractClassProcessor.java | 28 +- .../extractclass/ExtractEnumProcessor.java | 38 +- .../InheritanceToDelegationProcessor.java | 133 +-- .../inline/InlineConstantFieldProcessor.java | 17 +- .../InlineParameterExpressionProcessor.java | 66 +- .../InlineToAnonymousClassProcessor.java | 47 +- .../InlineSuperClassRefactoringProcessor.java | 14 +- .../usageInfo/ReplaceReferenceUsageInfo.java | 59 +- .../ReplaceStaticImportUsageInfo.java | 46 +- .../ReplaceWithSubtypeUsageInfo.java | 92 +- .../InplaceIntroduceConstantPopup.java | 457 +++++----- .../IntroduceConstantDialog.java | 789 +++++++++--------- .../introduceField/IntroduceFieldDialog.java | 503 +++++------ ...troduceParameterMethodUsagesProcessor.java | 5 +- .../IntroduceParameterProcessor.java | 71 +- .../MoveClassToInnerProcessor.java | 1 - .../PackageLocalsUsageCollector.java | 118 +-- .../MoveInstanceMethodProcessor.java | 78 +- .../move/moveMembers/MoveMemberHandler.java | 58 +- .../moveMembers/MoveMembersProcessor.java | 18 +- .../RemoveMiddlemanProcessor.java | 13 +- 25 files changed, 1462 insertions(+), 1309 deletions(-) diff --git a/plugin/src/main/java/com/intellij/java/impl/refactoring/changeClassSignature/ChangeClassSignatureProcessor.java b/plugin/src/main/java/com/intellij/java/impl/refactoring/changeClassSignature/ChangeClassSignatureProcessor.java index e00ddcc1d5..5850b44776 100644 --- a/plugin/src/main/java/com/intellij/java/impl/refactoring/changeClassSignature/ChangeClassSignatureProcessor.java +++ b/plugin/src/main/java/com/intellij/java/impl/refactoring/changeClassSignature/ChangeClassSignatureProcessor.java @@ -30,6 +30,7 @@ import consulo.language.util.IncorrectOperationException; import consulo.localHistory.LocalHistory; import consulo.localHistory.LocalHistoryAction; +import consulo.localize.LocalizeValue; import consulo.logging.Logger; import consulo.project.Project; import consulo.ui.annotation.RequiredUIAccess; @@ -78,7 +79,7 @@ protected UsageViewDescriptor createUsageViewDescriptor(@Nonnull UsageInfo[] usa @Override @RequiredUIAccess protected boolean preprocessUsages(@Nonnull SimpleReference refUsages) { - MultiMap conflicts = new MultiMap<>(); + MultiMap conflicts = new MultiMap<>(); PsiTypeParameter[] parameters = myClass.getTypeParameters(); Map infos = new HashMap<>(); @@ -88,7 +89,9 @@ protected boolean preprocessUsages(@Nonnull SimpleReference refUsag if (existing != null) { conflicts.putValue( myClass, - RefactoringUIUtil.getDescription(myClass, false) + " already contains type parameter " + newName + LocalizeValue.localizeTODO( + RefactoringUIUtil.getDescription(myClass, false) + " already contains type parameter " + newName + ) ); } infos.put(newName, info); @@ -139,11 +142,11 @@ protected void performRefactoring(@Nonnull UsageInfo[] usages) { @RequiredWriteAction private void doRefactoring(UsageInfo[] usages) throws IncorrectOperationException { PsiTypeParameter[] typeParameters = myClass.getTypeParameters(); - boolean[] toRemoveParms = detectRemovedParameters(typeParameters); + boolean[] toRemoveParams = detectRemovedParameters(typeParameters); for (UsageInfo usage : usages) { LOG.assertTrue(usage.getElement() instanceof PsiJavaCodeReferenceElement); - processUsage(usage, typeParameters, toRemoveParms); + processUsage(usage, typeParameters, toRemoveParams); } Map supersMap = new HashMap<>(); myClass.accept(new JavaRecursiveElementWalkingVisitor() { @@ -152,7 +155,7 @@ public void visitTypeElement(@Nonnull PsiTypeElement typeElement) { super.visitTypeElement(typeElement); if (PsiUtil.resolveClassInType(typeElement.getType()) instanceof PsiTypeParameter typeParam) { int i = ArrayUtil.find(typeParameters, typeParam); - if (i >= 0 && i < toRemoveParms.length && toRemoveParms[i]) { + if (i >= 0 && i < toRemoveParams.length && toRemoveParams[i]) { supersMap.put(typeElement, typeParam.getSuperClass()); } } @@ -162,11 +165,11 @@ public void visitTypeElement(@Nonnull PsiTypeElement typeElement) { for (Map.Entry classEntry : supersMap.entrySet()) { classEntry.getKey().replace(elementFactory.createTypeElement(elementFactory.createType(classEntry.getValue()))); } - changeClassSignature(typeParameters, toRemoveParms); + changeClassSignature(typeParameters, toRemoveParams); } @RequiredWriteAction - private void changeClassSignature(PsiTypeParameter[] originalTypeParameters, boolean[] toRemoveParms) + private void changeClassSignature(PsiTypeParameter[] originalTypeParameters, boolean[] toRemoveParams) throws IncorrectOperationException { PsiElementFactory factory = JavaPsiFacade.getInstance(myClass.getProject()).getElementFactory(); List newTypeParameters = new ArrayList<>(); @@ -179,23 +182,23 @@ private void changeClassSignature(PsiTypeParameter[] originalTypeParameters, boo newTypeParameters.add(factory.createTypeParameterFromText(info.getNewName(), null)); } } - ChangeSignatureUtil.synchronizeList(myClass.getTypeParameterList(), newTypeParameters, TypeParameterList.INSTANCE, toRemoveParms); + ChangeSignatureUtil.synchronizeList(myClass.getTypeParameterList(), newTypeParameters, TypeParameterList.INSTANCE, toRemoveParams); } - private boolean[] detectRemovedParameters(PsiTypeParameter[] originaltypeParameters) { - boolean[] toRemoveParms = new boolean[originaltypeParameters.length]; - Arrays.fill(toRemoveParms, true); + private boolean[] detectRemovedParameters(PsiTypeParameter[] originalTypeParams) { + boolean[] toRemoveParams = new boolean[originalTypeParams.length]; + Arrays.fill(toRemoveParams, true); for (TypeParameterInfo info : myNewSignature) { int oldParameterIndex = info.getOldParameterIndex(); if (oldParameterIndex >= 0) { - toRemoveParms[oldParameterIndex] = false; + toRemoveParams[oldParameterIndex] = false; } } - return toRemoveParms; + return toRemoveParams; } @RequiredWriteAction - private void processUsage(UsageInfo usage, PsiTypeParameter[] originalTypeParameters, boolean[] toRemoveParms) + private void processUsage(UsageInfo usage, PsiTypeParameter[] originalTypeParameters, boolean[] toRemoveParams) throws IncorrectOperationException { PsiElementFactory factory = JavaPsiFacade.getInstance(myClass.getProject()).getElementFactory(); PsiJavaCodeReferenceElement referenceElement = (PsiJavaCodeReferenceElement)usage.getElement(); @@ -219,7 +222,7 @@ private void processUsage(UsageInfo usage, PsiTypeParameter[] originalTypeParame newValues.add(newValue); } } - ChangeSignatureUtil.synchronizeList(referenceParameterList, newValues, ReferenceParameterList.INSTANCE, toRemoveParms); + ChangeSignatureUtil.synchronizeList(referenceParameterList, newValues, ReferenceParameterList.INSTANCE, toRemoveParams); } private PsiSubstitutor determineUsageSubstitutor(PsiJavaCodeReferenceElement referenceElement) { diff --git a/plugin/src/main/java/com/intellij/java/impl/refactoring/changeSignature/ChangeSignatureProcessor.java b/plugin/src/main/java/com/intellij/java/impl/refactoring/changeSignature/ChangeSignatureProcessor.java index 081aab449e..8064ea9750 100644 --- a/plugin/src/main/java/com/intellij/java/impl/refactoring/changeSignature/ChangeSignatureProcessor.java +++ b/plugin/src/main/java/com/intellij/java/impl/refactoring/changeSignature/ChangeSignatureProcessor.java @@ -25,6 +25,8 @@ import com.intellij.java.language.psi.*; import com.intellij.java.language.psi.util.*; import com.intellij.java.language.util.VisibilityUtil; +import consulo.annotation.access.RequiredReadAction; +import consulo.annotation.access.RequiredWriteAction; import consulo.component.extension.ExtensionPoint; import consulo.java.impl.refactoring.changeSignature.ChangeSignatureUsageProcessorEx; import consulo.language.codeStyle.CodeStyleManager; @@ -35,6 +37,7 @@ import consulo.language.editor.refactoring.ui.ConflictsDialog; import consulo.language.psi.PsiElement; import consulo.language.util.IncorrectOperationException; +import consulo.localize.LocalizeValue; import consulo.logging.Logger; import consulo.project.Project; import consulo.ui.annotation.RequiredUIAccess; @@ -53,6 +56,7 @@ public class ChangeSignatureProcessor extends ChangeSignatureProcessorBase { private static final Logger LOG = Logger.getInstance(ChangeSignatureProcessor.class); + @RequiredReadAction public ChangeSignatureProcessor( Project project, PsiMethod method, @@ -76,6 +80,7 @@ public ChangeSignatureProcessor( ); } + @RequiredReadAction public ChangeSignatureProcessor( Project project, PsiMethod method, @@ -100,6 +105,7 @@ public ChangeSignatureProcessor( ); } + @RequiredReadAction public ChangeSignatureProcessor( Project project, PsiMethod method, @@ -128,11 +134,13 @@ public ChangeSignatureProcessor( ); } + @RequiredReadAction public ChangeSignatureProcessor(Project project, JavaChangeInfo changeInfo) { super(project, changeInfo); LOG.assertTrue(myChangeInfo.getMethod().isValid()); } + @RequiredReadAction private static JavaChangeInfo generateChangeInfo( PsiMethod method, boolean generateDelegate, @@ -173,14 +181,14 @@ protected UsageViewDescriptor createUsageViewDescriptor(@Nonnull UsageInfo[] usa @Override public JavaChangeInfoImpl getChangeInfo() { - return (JavaChangeInfoImpl)super.getChangeInfo(); + return (JavaChangeInfoImpl) super.getChangeInfo(); } @Override protected void refreshElements(PsiElement[] elements) { boolean condition = elements.length == 1 && elements[0] instanceof PsiMethod; LOG.assertTrue(condition); - getChangeInfo().updateMethod((PsiMethod)elements[0]); + getChangeInfo().updateMethod((PsiMethod) elements[0]); } @Override @@ -197,11 +205,11 @@ protected boolean preprocessUsages(@Nonnull SimpleReference refUsag return false; } - MultiMap conflictDescriptions = new MultiMap<>(); + MultiMap conflictDescriptions = new MultiMap<>(); extensionPoint.forEach(usageProcessor -> { - MultiMap conflicts = usageProcessor.findConflicts(myChangeInfo, refUsages); + MultiMap conflicts = usageProcessor.findConflicts(myChangeInfo, refUsages); for (PsiElement key : conflicts.keySet()) { - Collection collection = conflictDescriptions.get(key); + Collection collection = conflictDescriptions.get(key); if (collection.size() == 0) { collection = new HashSet<>(); } @@ -289,6 +297,7 @@ protected boolean isProcessCovariantOverriders() { ) == DialogWrapper.OK_EXIT_CODE; } + @RequiredWriteAction public static void makeEmptyBody(PsiElementFactory factory, PsiMethod delegate) throws IncorrectOperationException { PsiCodeBlock body = delegate.getBody(); if (body != null) { @@ -311,19 +320,19 @@ public static PsiCallExpression addDelegatingCallTemplate(PsiMethod delegate, St PsiElement callStatement = factory.createStatementFromText("this();", null); callStatement = CodeStyleManager.getInstance(project).reformat(callStatement); callStatement = body.add(callStatement); - callExpression = (PsiCallExpression)((PsiExpressionStatement)callStatement).getExpression(); + callExpression = (PsiCallExpression) ((PsiExpressionStatement) callStatement).getExpression(); } else if (PsiType.VOID.equals(delegate.getReturnType())) { PsiElement callStatement = factory.createStatementFromText(newName + "();", null); callStatement = CodeStyleManager.getInstance(project).reformat(callStatement); callStatement = body.add(callStatement); - callExpression = (PsiCallExpression)((PsiExpressionStatement)callStatement).getExpression(); + callExpression = (PsiCallExpression) ((PsiExpressionStatement) callStatement).getExpression(); } else { PsiElement callStatement = factory.createStatementFromText("return " + newName + "();", null); callStatement = CodeStyleManager.getInstance(project).reformat(callStatement); callStatement = body.add(callStatement); - callExpression = (PsiCallExpression)((PsiReturnStatement)callStatement).getReturnValue(); + callExpression = (PsiCallExpression) ((PsiReturnStatement) callStatement).getReturnValue(); } return callExpression; } diff --git a/plugin/src/main/java/com/intellij/java/impl/refactoring/convertToInstanceMethod/ConvertToInstanceMethodProcessor.java b/plugin/src/main/java/com/intellij/java/impl/refactoring/convertToInstanceMethod/ConvertToInstanceMethodProcessor.java index f7c49ecc44..603dc150ad 100644 --- a/plugin/src/main/java/com/intellij/java/impl/refactoring/convertToInstanceMethod/ConvertToInstanceMethodProcessor.java +++ b/plugin/src/main/java/com/intellij/java/impl/refactoring/convertToInstanceMethod/ConvertToInstanceMethodProcessor.java @@ -143,7 +143,7 @@ else if (element instanceof PsiDocTagValue) { @RequiredUIAccess protected boolean preprocessUsages(@Nonnull SimpleReference refUsages) { UsageInfo[] usagesIn = refUsages.get(); - MultiMap conflicts = new MultiMap<>(); + MultiMap conflicts = new MultiMap<>(); Set methods = Collections.singleton((PsiMember)myMethod); if (!myTargetClass.isInterface()) { RefactoringConflictsUtil.analyzeAccessibilityConflicts(methods, myTargetClass, conflicts, myNewVisibility); @@ -174,7 +174,7 @@ protected boolean preprocessUsages(@Nonnull SimpleReference refUsag RefactoringUIUtil.getDescription(ConflictsUtil.getContainer(methodCall), true), CommonRefactoringUtil.htmlEmphasize(myTargetParameter.getName()) ); - conflicts.putValue(methodCall, message.get()); + conflicts.putValue(methodCall, message); } } } @@ -350,11 +350,8 @@ private void processParameterUsage(ParameterUsageInfo usage) throws IncorrectOpe refExpr.replace(expression); } } - else { - PsiElement element = reference.getElement(); - if (element instanceof PsiDocParamRef) { - element.getParent().delete(); - } + else if (reference.getElement() instanceof PsiDocParamRef docParamRef) { + docParamRef.getParent().delete(); } } diff --git a/plugin/src/main/java/com/intellij/java/impl/refactoring/encapsulateFields/EncapsulateFieldsProcessor.java b/plugin/src/main/java/com/intellij/java/impl/refactoring/encapsulateFields/EncapsulateFieldsProcessor.java index 5ea51cb7b0..1627ea4c65 100644 --- a/plugin/src/main/java/com/intellij/java/impl/refactoring/encapsulateFields/EncapsulateFieldsProcessor.java +++ b/plugin/src/main/java/com/intellij/java/impl/refactoring/encapsulateFields/EncapsulateFieldsProcessor.java @@ -24,6 +24,7 @@ import com.intellij.java.language.psi.util.PsiFormatUtilBase; import com.intellij.java.language.psi.util.PsiUtil; import consulo.annotation.access.RequiredReadAction; +import consulo.annotation.access.RequiredWriteAction; import consulo.language.editor.refactoring.BaseRefactoringProcessor; import consulo.language.editor.refactoring.localize.RefactoringLocalize; import consulo.language.editor.refactoring.ui.RefactoringUIUtil; @@ -57,8 +58,8 @@ public class EncapsulateFieldsProcessor extends BaseRefactoringProcessor { private final EncapsulateFieldsDescriptor myDescriptor; private final FieldDescriptor[] myFieldDescriptors; - private HashMap myNameToGetter; - private HashMap myNameToSetter; + private Map myNameToGetter; + private Map myNameToSetter; public EncapsulateFieldsProcessor(Project project, @Nonnull EncapsulateFieldsDescriptor descriptor) { super(project); @@ -97,7 +98,7 @@ protected String getCommandName() { @Override @RequiredUIAccess protected boolean preprocessUsages(@Nonnull SimpleReference refUsages) { - MultiMap conflicts = new MultiMap<>(); + MultiMap conflicts = new MultiMap<>(); checkExistingMethods(conflicts, true); checkExistingMethods(conflicts, false); @@ -123,7 +124,7 @@ protected boolean preprocessUsages(@Nonnull SimpleReference refUsag for (PsiReference reference : ReferencesSearch.search(field)) { PsiElement place = reference.getElement(); LOG.assertTrue(place instanceof PsiReferenceExpression); - PsiExpression qualifierExpression = ((PsiReferenceExpression)place).getQualifierExpression(); + PsiExpression qualifierExpression = ((PsiReferenceExpression) place).getQualifierExpression(); PsiClass ancestor; if (qualifierExpression == null) { ancestor = PsiTreeUtil.getParentOfType(place, PsiClass.class, false); @@ -132,13 +133,16 @@ protected boolean preprocessUsages(@Nonnull SimpleReference refUsag ancestor = PsiUtil.resolveClassInType(qualifierExpression.getType()); } - boolean isGetter = !PsiUtil.isAccessedForWriting((PsiExpression)place); + boolean isGetter = !PsiUtil.isAccessedForWriting((PsiExpression) place); for (PsiMethod overridden : isGetter ? getters : setters) { if (InheritanceUtil.isInheritorOrSelf(myClass, ancestor, true)) { - conflicts.putValue(overridden, "There is already a " + - RefactoringUIUtil.getDescription(overridden, true) + - " which would hide generated " + - (isGetter ? "getter" : "setter") + " for " + place.getText()); + conflicts.putValue( + overridden, + LocalizeValue.localizeTODO( + "There is already a " + RefactoringUIUtil.getDescription(overridden, true) + + " which would hide generated " + (isGetter ? "getter" : "setter") + " for " + place.getText() + ) + ); break; } } @@ -149,7 +153,7 @@ protected boolean preprocessUsages(@Nonnull SimpleReference refUsag } @RequiredReadAction - private void checkExistingMethods(MultiMap conflicts, boolean isGetter) { + private void checkExistingMethods(MultiMap conflicts, boolean isGetter) { if (isGetter) { if (!myDescriptor.isToEncapsulateGet()) { return; @@ -184,7 +188,7 @@ else if (!myDescriptor.isToEncapsulateSet()) { CommonRefactoringUtil.htmlEmphasize(descr), CommonRefactoringUtil.htmlEmphasize(prototype.getName()) ); - conflicts.putValue(existing, message.get()); + conflicts.putValue(existing, message); } } else { @@ -195,7 +199,7 @@ else if (!myDescriptor.isToEncapsulateSet()) { for (PsiReference reference : ReferencesSearch.search(existing)) { PsiElement place = reference.getElement(); LOG.assertTrue(place instanceof PsiReferenceExpression); - PsiExpression qualifierExpression = ((PsiReferenceExpression)place).getQualifierExpression(); + PsiExpression qualifierExpression = ((PsiReferenceExpression) place).getQualifierExpression(); PsiClass inheritor; if (qualifierExpression == null) { inheritor = PsiTreeUtil.getParentOfType(place, PsiClass.class, false); @@ -207,10 +211,10 @@ else if (!myDescriptor.isToEncapsulateSet()) { if (InheritanceUtil.isInheritorOrSelf(inheritor, myClass, true)) { conflicts.putValue( existing, - "There is already a " + RefactoringUIUtil.getDescription( - existing, - true - ) + " which would be hidden by generated " + (isGetter ? "getter" : "setter") + LocalizeValue.localizeTODO( + "There is already a " + RefactoringUIUtil.getDescription(existing, true) + + " which would be hidden by generated " + (isGetter ? "getter" : "setter") + ) ); break; } @@ -226,7 +230,7 @@ else if (!myDescriptor.isToEncapsulateSet()) { @Override @RequiredReadAction protected UsageInfo[] findUsages() { - ArrayList array = new ArrayList<>(); + List array = new ArrayList<>(); for (FieldDescriptor fieldDescriptor : myFieldDescriptors) { for (PsiReference reference : ReferencesSearch.search(fieldDescriptor.getField())) { PsiElement element = reference.getElement(); @@ -254,13 +258,14 @@ protected void refreshElements(PsiElement[] elements) { LOG.assertTrue(element instanceof PsiField); - myFieldDescriptors[idx].refreshField((PsiField)element); + myFieldDescriptors[idx].refreshField((PsiField) element); } myClass = myFieldDescriptors[0].getField().getContainingClass(); } @Override + @RequiredWriteAction protected void performRefactoring(@Nonnull UsageInfo[] usages) { updateFieldVisibility(); generateAccessors(); @@ -277,6 +282,7 @@ private void updateFieldVisibility() { } } + @RequiredWriteAction private void generateAccessors() { // generate accessors myNameToGetter = new HashMap<>(); @@ -292,7 +298,7 @@ private void generateAccessors() { assert prototype != null; PsiMethod getter = addOrChangeAccessor(prototype, myNameToGetter); if (docComment != null) { - PsiDocComment getterJavadoc = (PsiDocComment)getter.addBefore(docComment, getter.getFirstChild()); + PsiDocComment getterJavadoc = (PsiDocComment) getter.addBefore(docComment, getter.getFirstChild()); commentPolicy.processNewJavaDoc(getterJavadoc); } } @@ -308,6 +314,7 @@ private void generateAccessors() { } } + @RequiredReadAction private void processUsagesPerFile(UsageInfo[] usages) { Map> usagesInFiles = new HashMap<>(); for (UsageInfo usage : usages) { @@ -321,7 +328,7 @@ private void processUsagesPerFile(UsageInfo[] usages) { usagesInFile = new ArrayList<>(); usagesInFiles.put(file, usagesInFile); } - usagesInFile.add(((EncapsulateFieldUsageInfo)usage)); + usagesInFile.add(((EncapsulateFieldUsageInfo) usage)); } for (List usageInfos : usagesInFiles.values()) { @@ -341,13 +348,13 @@ private void processUsagesPerFile(UsageInfo[] usages) { } } - private PsiMethod addOrChangeAccessor(PsiMethod prototype, HashMap nameToAncestor) { + private PsiMethod addOrChangeAccessor(PsiMethod prototype, Map nameToAncestor) { PsiMethod existing = myClass.findMethodBySignature(prototype, false); PsiMethod result = existing; try { if (existing == null) { PsiUtil.setModifierProperty(prototype, myDescriptor.getAccessorsVisibility(), true); - result = (PsiMethod)myClass.add(prototype); + result = (PsiMethod) myClass.add(prototype); } else { //TODO : change visibility diff --git a/plugin/src/main/java/com/intellij/java/impl/refactoring/extractclass/ExtractClassProcessor.java b/plugin/src/main/java/com/intellij/java/impl/refactoring/extractclass/ExtractClassProcessor.java index 4328ed1852..ed67cad08e 100644 --- a/plugin/src/main/java/com/intellij/java/impl/refactoring/extractclass/ExtractClassProcessor.java +++ b/plugin/src/main/java/com/intellij/java/impl/refactoring/extractclass/ExtractClassProcessor.java @@ -36,6 +36,7 @@ import com.intellij.java.language.psi.util.PropertyUtil; import com.intellij.java.language.util.VisibilityUtil; import consulo.annotation.access.RequiredReadAction; +import consulo.annotation.access.RequiredWriteAction; import consulo.application.Application; import consulo.application.Result; import consulo.java.localize.JavaRefactoringLocalize; @@ -173,7 +174,7 @@ public PsiClass getCreatedClass() { @Override @RequiredUIAccess protected boolean preprocessUsages(@Nonnull SimpleReference refUsages) { - MultiMap conflicts = new MultiMap<>(); + MultiMap conflicts = new MultiMap<>(); myExtractEnumProcessor.findEnumConstantConflicts(refUsages); if (!DestinationFolderComboBox.isAccessible( myProject, @@ -182,7 +183,7 @@ protected boolean preprocessUsages(@Nonnull SimpleReference refUsag )) { conflicts.putValue( sourceClass, - "Extracted class won't be accessible in " + RefactoringUIUtil.getDescription(sourceClass, true) + LocalizeValue.localizeTODO("Extracted class won't be accessible in " + RefactoringUIUtil.getDescription(sourceClass, true)) ); } Application.get().runWriteAction(myClass::delete); @@ -195,7 +196,7 @@ protected boolean preprocessUsages(@Nonnull SimpleReference refUsag existingClass, RefactoringLocalize.cannotPerformRefactoringWithReason( JavaRefactoringLocalize.thereAlreadyExistsAClassWithTheChosenName() - ).get() + ) ); } @@ -207,13 +208,13 @@ protected boolean preprocessUsages(@Nonnull SimpleReference refUsag fieldsNeedingGetter.addAll(visitor.getFieldsNeedingGetter()); fieldsNeedingGetter.addAll(srcVisitor.getFieldsNeedingGetter()); for (PsiField field : fieldsNeedingGetter) { - conflicts.putValue(field, LocalizeValue.localizeTODO("Field \'" + field.getName() + "\' needs getter").get()); + conflicts.putValue(field, LocalizeValue.localizeTODO("Field \'" + field.getName() + "\' needs getter")); } Set fieldsNeedingSetter = new LinkedHashSet<>(); fieldsNeedingSetter.addAll(visitor.getFieldsNeedingSetter()); fieldsNeedingSetter.addAll(srcVisitor.getFieldsNeedingSetter()); for (PsiField field : fieldsNeedingSetter) { - conflicts.putValue(field, LocalizeValue.localizeTODO("Field \'" + field.getName() + "\' needs setter").get()); + conflicts.putValue(field, LocalizeValue.localizeTODO("Field \'" + field.getName() + "\' needs setter")); } } checkConflicts(refUsages, conflicts); @@ -221,16 +222,16 @@ protected boolean preprocessUsages(@Nonnull SimpleReference refUsag } - private void calculateInitializersConflicts(MultiMap conflicts) { + private void calculateInitializersConflicts(MultiMap conflicts) { PsiClassInitializer[] initializers = sourceClass.getInitializers(); for (PsiClassInitializer initializer : initializers) { if (initializerDependsOnMoved(initializer)) { - conflicts.putValue(initializer, LocalizeValue.localizeTODO("Class initializer requires moved members").get()); + conflicts.putValue(initializer, LocalizeValue.localizeTODO("Class initializer requires moved members")); } } for (PsiMethod constructor : sourceClass.getConstructors()) { if (initializerDependsOnMoved(constructor.getBody())) { - conflicts.putValue(constructor, LocalizeValue.localizeTODO("Constructor requires moved members").get()); + conflicts.putValue(constructor, LocalizeValue.localizeTODO("Constructor requires moved members")); } } } @@ -292,7 +293,7 @@ protected UsageViewDescriptor createUsageViewDescriptor(@Nonnull UsageInfo[] usa } @Override - @RequiredReadAction + @RequiredWriteAction protected void performRefactoring(@Nonnull UsageInfo[] usageInfos) { PsiClass psiClass = buildClass(); if (psiClass == null) { @@ -538,12 +539,9 @@ private void findUsagesForInnerClass(PsiClass innerClass, List StringUtil.getQualifiedName(newPackageName, newClassName) + innerName.substring(sourceClassQualifiedName.length()); boolean hasExternalReference = false; for (PsiReference reference : calls) { - PsiElement referenceElement = reference.getElement(); - if (referenceElement instanceof PsiJavaCodeReferenceElement javaCodeReferenceElement) { - if (!isInMovedElement(referenceElement)) { - usages.add(new ReplaceClassReference(javaCodeReferenceElement, newInnerClassName)); - hasExternalReference = true; - } + if (reference.getElement() instanceof PsiJavaCodeReferenceElement javaCodeRef && !isInMovedElement(javaCodeRef)) { + usages.add(new ReplaceClassReference(javaCodeRef, newInnerClassName)); + hasExternalReference = true; } } if (hasExternalReference) { diff --git a/plugin/src/main/java/com/intellij/java/impl/refactoring/extractclass/ExtractEnumProcessor.java b/plugin/src/main/java/com/intellij/java/impl/refactoring/extractclass/ExtractEnumProcessor.java index 552faf9ed5..11339cbb13 100644 --- a/plugin/src/main/java/com/intellij/java/impl/refactoring/extractclass/ExtractEnumProcessor.java +++ b/plugin/src/main/java/com/intellij/java/impl/refactoring/extractclass/ExtractEnumProcessor.java @@ -19,11 +19,13 @@ import consulo.language.psi.scope.GlobalSearchScope; import consulo.language.psi.util.PsiTreeUtil; import consulo.language.util.IncorrectOperationException; +import consulo.localize.LocalizeValue; import consulo.project.Project; import consulo.usage.UsageInfo; import consulo.util.lang.StringUtil; import consulo.util.lang.function.Functions; import consulo.util.lang.ref.SimpleReference; +import jakarta.annotation.Nonnull; import java.util.*; @@ -57,7 +59,7 @@ public void fixUsage() throws IncorrectOperationException { }); } else if (element != null) { - resolvableConflicts.add(new ConflictUsageInfo(element, null)); + resolvableConflicts.add(new ConflictUsageInfo(element, LocalizeValue.empty())); } } if (!resolvableConflicts.isEmpty()) { @@ -106,11 +108,11 @@ public List findEnumConstantUsages(List fiel for (PsiSwitchStatement switchStatement : switchStatements) { PsiStatement errStatement = EnumConstantsUtil.isEnumSwitch(switchStatement, enumValueType, enumValues); if (errStatement != null) { - String description = null; + LocalizeValue description = LocalizeValue.empty(); if (errStatement instanceof PsiSwitchLabelStatement switchLabelStmt) { PsiExpression caseValue = switchLabelStmt.getCaseValue(); if (caseValue != null) { - description = caseValue.getText() + " can not be replaced with enum"; + description = LocalizeValue.localizeTODO(caseValue.getText() + " can not be replaced with enum"); } } result.add(new ConflictUsageInfo(errStatement, description)); @@ -122,12 +124,14 @@ public List findEnumConstantUsages(List fiel if (element != null && !element.getManager().isInProject(element)) { result.add(new ConflictUsageInfo( expression, - StringUtil.capitalize(RefactoringUIUtil.getDescription(element, false)) + " is out of project" + LocalizeValue.localizeTODO( + StringUtil.capitalize(RefactoringUIUtil.getDescription(element, false)) + " is out of project" + ) )); } } else { - result.add(new ConflictUsageInfo(expression, null)); + result.add(new ConflictUsageInfo(expression, LocalizeValue.empty())); } } } @@ -143,12 +147,12 @@ public List findEnumConstantUsages(List fiel true ); for (UsageInfo usageInfo : myTypeMigrationProcessor.findUsages()) { - PsiElement migrateElement = usageInfo.getElement(); - if (migrateElement instanceof PsiField enumConstantField) { - if (enumConstantField.isStatic() && enumConstantField.isFinal() - && enumConstantField.hasInitializer() && !myEnumConstants.contains(enumConstantField)) { - continue; - } + if (usageInfo.getElement() instanceof PsiField enumConstantField + && enumConstantField.isStatic() + && enumConstantField.isFinal() + && enumConstantField.hasInitializer() + && !myEnumConstants.contains(enumConstantField)) { + continue; } result.add(new EnumTypeMigrationUsageInfo(usageInfo)); } @@ -186,9 +190,11 @@ public UsageInfo getUsageInfo() { } private static class ConflictUsageInfo extends FixableUsageInfo { - private final String myDescription; + @Nonnull + private final LocalizeValue myDescription; - public ConflictUsageInfo(PsiElement expression, String description) { + @RequiredReadAction + public ConflictUsageInfo(PsiElement expression, @Nonnull LocalizeValue description) { super(expression); myDescription = description; } @@ -198,8 +204,10 @@ public void fixUsage() throws IncorrectOperationException { } @Override - public String getConflictMessage() { - return "Unable to migrate statement to enum constant." + (myDescription != null ? " " + myDescription : ""); + public LocalizeValue getConflictMessage() { + return LocalizeValue.localizeTODO( + "Unable to migrate statement to enum constant." + (myDescription != LocalizeValue.empty() ? " " + myDescription : "") + ); } } } \ No newline at end of file diff --git a/plugin/src/main/java/com/intellij/java/impl/refactoring/inheritanceToDelegation/InheritanceToDelegationProcessor.java b/plugin/src/main/java/com/intellij/java/impl/refactoring/inheritanceToDelegation/InheritanceToDelegationProcessor.java index 0185f426ca..95579914e9 100644 --- a/plugin/src/main/java/com/intellij/java/impl/refactoring/inheritanceToDelegation/InheritanceToDelegationProcessor.java +++ b/plugin/src/main/java/com/intellij/java/impl/refactoring/inheritanceToDelegation/InheritanceToDelegationProcessor.java @@ -69,7 +69,7 @@ public class InheritanceToDelegationProcessor extends BaseRefactoringProcessor { private final boolean myIsDelegateOtherMembers; private final Set myDelegatedInterfaces; private final Set myDelegatedMethods; - private final HashMap myDelegatedMethodsVisibility; + private final Map myDelegatedMethodsVisibility; private final Set myOverriddenMethods; private final PsiClass myBaseClass; @@ -84,7 +84,7 @@ public class InheritanceToDelegationProcessor extends BaseRefactoringProcessor { private final PsiManager myManager; private final boolean myIsInnerClassNeeded; private Set myClassInheritors; - private HashSet myAbstractDelegatedMethods; + private Set myAbstractDelegatedMethods; private final Map mySuperClassesToSubstitutors = new HashMap<>(); public InheritanceToDelegationProcessor( @@ -157,7 +157,7 @@ protected UsageViewDescriptor createUsageViewDescriptor(@Nonnull UsageInfo[] usa @Nonnull @Override protected UsageInfo[] findUsages() { - ArrayList usages = new ArrayList<>(); + List usages = new ArrayList<>(); PsiClass[] inheritors = ClassInheritorsSearch.search(myClass, true).toArray(PsiClass.EMPTY_ARRAY); myClassInheritors = new HashSet<>(); myClassInheritors.add(myClass); @@ -197,14 +197,14 @@ protected boolean preprocessUsages(@Nonnull SimpleReference refUsag addAll(oldUsages, usagesIn); ObjectUpcastedUsageInfo[] objectUpcastedUsageInfos = objectUpcastedUsages(usagesIn); if (myPrepareSuccessfulSwingThreadCallback != null) { - MultiMap conflicts = new MultiMap<>(); + MultiMap conflicts = new MultiMap<>(); if (objectUpcastedUsageInfos.length > 0) { LocalizeValue message = RefactoringLocalize.instancesOf0UpcastedTo1WereFound( RefactoringUIUtil.getDescription(myClass, true), CommonRefactoringUtil.htmlEmphasize(CommonClassNames.JAVA_LANG_OBJECT) ); - conflicts.putValue(myClass, message.get()); + conflicts.putValue(myClass, message); } analyzeConflicts(usagesIn, conflicts); @@ -231,7 +231,7 @@ protected boolean preprocessUsages(@Nonnull SimpleReference refUsag } @RequiredReadAction - private void analyzeConflicts(UsageInfo[] usage, MultiMap conflicts) { + private void analyzeConflicts(UsageInfo[] usage, MultiMap conflicts) { Map> reportedNonDelegatedUsages = new HashMap<>(); Map> reportedUpcasts = new HashMap<>(); //Set reportedObjectUpcasts = new HashSet(); @@ -266,7 +266,7 @@ private void analyzeConflicts(UsageInfo[] usage, MultiMap co RefactoringUIUtil.getDescription(nonDelegatedMember, true), classDescription ); - conflicts.putValue(container, CommonRefactoringUtil.capitalize(message.get())); + conflicts.putValue(container, message.capitalize()); reportedContainers.add(container); } } @@ -284,7 +284,7 @@ else if (usageInfo instanceof UpcastedUsageInfo upcastedUsageInfo) { classDescription, RefactoringUIUtil.getDescription(upcastedTo, false) ); - conflicts.putValue(container, CommonRefactoringUtil.capitalize(message.get())); + conflicts.putValue(container, message.capitalize()); reportedContainers.add(container); } } @@ -295,7 +295,7 @@ else if (aUsage instanceof NoLongerOverridingSubClassMethodUsageInfo info) { RefactoringUIUtil.getDescription(info.getSubClassMethod(), true), RefactoringUIUtil.getDescription(info.getOverridenMethod(), true) ); - conflicts.putValue(info.getSubClassMethod(), message.get()); + conflicts.putValue(info.getSubClassMethod(), message.capitalize()); } } } @@ -333,7 +333,7 @@ private List filterUsages(List usages) { return result; } - private void processClass(PsiClass inheritor, ArrayList usages) { + private void processClass(PsiClass inheritor, List usages) { ClassReferenceScanner scanner = new ClassReferenceSearchingScanner(inheritor); MyClassInstanceReferenceVisitor instanceVisitor = new MyClassInstanceReferenceVisitor(inheritor, usages); scanner.processReferences(new ClassInstanceScanner(inheritor, instanceVisitor)); @@ -355,14 +355,14 @@ private void processClass(PsiClass inheritor, ArrayList usages) { for (PsiMethod classMethod : methodsByName) { MethodSignature signature = classMethod.getSignature(inheritorSubstitutor); if (signature.equals(method.getSignature(PsiSubstitutor.EMPTY)) && !classMethod.isAbstract()) { - usages.add(new NoLongerOverridingSubClassMethodUsageInfo(method, baseMethod)); - break; - } + usages.add(new NoLongerOverridingSubClassMethodUsageInfo(method, baseMethod)); + break; } } } } } + } @Override @RequiredWriteAction @@ -377,7 +377,7 @@ protected void performRefactoring(UsageInfo[] usages) { ); } else { - InheritanceToDelegationUsageInfo usage = (InheritanceToDelegationUsageInfo)aUsage; + InheritanceToDelegationUsageInfo usage = (InheritanceToDelegationUsageInfo) aUsage; upcastToDelegation(usage.getElement(), usage.getDelegateFieldAccessible()); } } @@ -411,7 +411,7 @@ private void addInnerClass() throws IncorrectOperationException { innerClass.getImplementsList().add(baseClassReferenceElement); } PsiUtil.setModifierProperty(innerClass, PsiModifier.PRIVATE, true); - innerClass = (PsiClass)myClass.add(innerClass); + innerClass = (PsiClass) myClass.add(innerClass); List innerClassMethods = getInnerClassMethods(); for (InnerClassMethod innerClassMethod : innerClassMethods) { @@ -430,7 +430,7 @@ private void delegateUsageFromClass( upcastToDelegation(refExpr.getQualifierExpression(), fieldAccessibility); } else { - String name = ((PsiNamedElement)nonDelegatedMember).getName(); + String name = ((PsiNamedElement) nonDelegatedMember).getName(); String qualifier; if (isStatic(nonDelegatedMember)) { qualifier = myBaseClass.getName(); @@ -443,15 +443,14 @@ else if (!fieldAccessibility.isAccessible() && myGenerateGetter) { } PsiExpression newExpr = myFactory.createExpressionFromText(qualifier + "." + name, element); - newExpr = (PsiExpression)CodeStyleManager.getInstance(myProject).reformat(newExpr); + newExpr = (PsiExpression) CodeStyleManager.getInstance(myProject).reformat(newExpr); element.replace(newExpr); } } else if (element instanceof PsiJavaCodeReferenceElement) { - String name = ((PsiNamedElement)nonDelegatedMember).getName(); + String name = ((PsiNamedElement) nonDelegatedMember).getName(); - PsiElement parent = element.getParent(); - if (!isStatic(nonDelegatedMember) && parent instanceof PsiNewExpression newExpr) { + if (!isStatic(nonDelegatedMember) && element.getParent() instanceof PsiNewExpression newExpr) { if (newExpr.getQualifier() != null) { upcastToDelegation(newExpr.getQualifier(), fieldAccessibility); } @@ -463,7 +462,7 @@ else if (element instanceof PsiJavaCodeReferenceElement) { else { qualifier = myFieldName; } - newExpr.replace(myFactory.createExpressionFromText(qualifier + "." + newExpr.getText(), parent)); + newExpr.replace(myFactory.createExpressionFromText(qualifier + "." + newExpr.getText(), newExpr)); } } else { @@ -481,11 +480,11 @@ else if (element instanceof PsiJavaCodeReferenceElement) { private static boolean isStatic(PsiElement member) { return member instanceof PsiModifierListOwner method && method.hasModifierProperty(PsiModifier.STATIC); - } + } @RequiredWriteAction private void upcastToDelegation(PsiElement element, FieldAccessibility fieldAccessibility) throws IncorrectOperationException { - PsiExpression expression = (PsiExpression)element; + PsiExpression expression = (PsiExpression) element; PsiExpression newExpr; PsiReferenceExpression ref; @@ -505,11 +504,11 @@ private void upcastToDelegation(PsiElement element, FieldAccessibility fieldAcce } if (!fieldAccessibility.isAccessible() && myGenerateGetter) { newExpr = myFactory.createExpressionFromText(delegateQualifier + myGetterName + "()", expression); - ref = (PsiReferenceExpression)((PsiMethodCallExpression)newExpr).getMethodExpression().getQualifierExpression(); + ref = (PsiReferenceExpression) ((PsiMethodCallExpression) newExpr).getMethodExpression().getQualifierExpression(); } else { newExpr = myFactory.createExpressionFromText(delegateQualifier + myFieldName, expression); - ref = (PsiReferenceExpression)((PsiReferenceExpression)newExpr).getQualifierExpression(); + ref = (PsiReferenceExpression) ((PsiReferenceExpression) newExpr).getQualifierExpression(); } // LOG.debug("upcastToDelegation:" + element + ":newExpr = " + newExpr); // LOG.debug("upcastToDelegation:" + element + ":ref = " + ref); @@ -546,7 +545,6 @@ private PsiMethod delegateMethod( PsiMethod methodToAdd = GenerateMembersUtil.substituteGenericMethod(method, substitutor); PsiModifierList modifierList = methodToAdd.getModifierList(); - NullableNotNullManager manager = NullableNotNullManager.getInstance(myProject); modifierList.setModifierProperty(PsiModifier.ABSTRACT, false); NullableNotNullManager.getInstance(myProject).copyNullableOrNotNullAnnotation(method, methodToAdd); @@ -565,8 +563,8 @@ private PsiMethod delegateMethod( if (methodToAdd.getDocComment() != null) { methodToAdd.getDocComment().delete(); } - methodToAdd = (PsiMethod)CodeStyleManager.getInstance(myProject).reformat(methodToAdd); - methodToAdd = (PsiMethod)JavaCodeStyleManager.getInstance(myProject).shortenClassReferences(methodToAdd); + methodToAdd = (PsiMethod) CodeStyleManager.getInstance(myProject).reformat(methodToAdd); + methodToAdd = (PsiMethod) JavaCodeStyleManager.getInstance(myProject).shortenClassReferences(methodToAdd); return methodToAdd; } @@ -633,12 +631,12 @@ private void addField(UsageInfo[] usages) throws IncorrectOperationException { field.getTypeElement().replace(myFactory.createTypeElement(myBaseClassType)); if (fieldInitializerNeeded) { PsiJavaCodeReferenceElement classReferenceElement = myFactory.createReferenceElementByType(myBaseClassType); - PsiNewExpression newExpression = (PsiNewExpression)field.getInitializer(); + PsiNewExpression newExpression = (PsiNewExpression) field.getInitializer(); newExpression.getClassReference().replace(classReferenceElement); } } - field = (PsiField)CodeStyleManager.getInstance(myProject).reformat(field); + field = (PsiField) CodeStyleManager.getInstance(myProject).reformat(field); myClass.add(field); if (!fieldInitializerNeeded) { fixConstructors(); @@ -655,7 +653,7 @@ private void addField(UsageInfo[] usages) throws IncorrectOperationException { getterBuffer.append(";\n}"); PsiMethod getter = myFactory.createMethodFromText(getterBuffer.toString(), myClass); getter.getReturnTypeElement().replace(myFactory.createTypeElement(myBaseClassType)); - getter = (PsiMethod)CodeStyleManager.getInstance(myProject).reformat(getter); + getter = (PsiMethod) CodeStyleManager.getInstance(myProject).reformat(getter); myClass.add(getter); } } @@ -666,7 +664,7 @@ private String getFieldVisibility(UsageInfo[] usages) { } for (UsageInfo aUsage : usages) { - InheritanceToDelegationUsageInfo usage = (InheritanceToDelegationUsageInfo)aUsage; + InheritanceToDelegationUsageInfo usage = (InheritanceToDelegationUsageInfo) aUsage; FieldAccessibility delegateFieldAccessible = usage.getDelegateFieldAccessible(); if (delegateFieldAccessible.isAccessible() && delegateFieldAccessible.getContainingClass() != myClass) { return PsiModifier.PROTECTED; @@ -715,19 +713,19 @@ private void fixConstructors() throws IncorrectOperationException { String assignmentText = fieldQualifier + myFieldName + "= new " + defaultClassFieldType() + "()"; if (statements.length < 1 || !JavaHighlightUtil.isSuperOrThisCall(statements[0], true, true) || myBaseClass.isInterface()) { PsiExpressionStatement assignmentStatement = - (PsiExpressionStatement)myFactory.createStatementFromText( + (PsiExpressionStatement) myFactory.createStatementFromText( assignmentText, body ); if (!myIsInnerClassNeeded) { - PsiAssignmentExpression assignmentExpr = (PsiAssignmentExpression)assignmentStatement.getExpression(); - PsiNewExpression newExpression = (PsiNewExpression)assignmentExpr.getRExpression(); + PsiAssignmentExpression assignmentExpr = (PsiAssignmentExpression) assignmentStatement.getExpression(); + PsiNewExpression newExpression = (PsiNewExpression) assignmentExpr.getRExpression(); assert newExpression != null; PsiJavaCodeReferenceElement classRef = newExpression.getClassReference(); assert classRef != null; classRef.replace(baseClassReference); } - assignmentStatement = (PsiExpressionStatement)CodeStyleManager.getInstance(myProject).reformat(assignmentStatement); + assignmentStatement = (PsiExpressionStatement) CodeStyleManager.getInstance(myProject).reformat(assignmentStatement); if (statements.length > 0) { if (!JavaHighlightUtil.isSuperOrThisCall(statements[0], true, false)) { body.addBefore(assignmentStatement, statements[0]); @@ -741,16 +739,16 @@ private void fixConstructors() throws IncorrectOperationException { } } else { - PsiExpressionStatement callStatement = ((PsiExpressionStatement)statements[0]); + PsiExpressionStatement callStatement = ((PsiExpressionStatement) statements[0]); if (!JavaHighlightUtil.isSuperOrThisCall(callStatement, false, true)) { - PsiMethodCallExpression superConstructorCall = (PsiMethodCallExpression)callStatement.getExpression(); + PsiMethodCallExpression superConstructorCall = (PsiMethodCallExpression) callStatement.getExpression(); PsiAssignmentExpression assignmentExpression = - (PsiAssignmentExpression)myFactory.createExpressionFromText(assignmentText, superConstructorCall); - PsiNewExpression newExpression = (PsiNewExpression)assignmentExpression.getRExpression(); + (PsiAssignmentExpression) myFactory.createExpressionFromText(assignmentText, superConstructorCall); + PsiNewExpression newExpression = (PsiNewExpression) assignmentExpression.getRExpression(); if (!myIsInnerClassNeeded) { newExpression.getClassReference().replace(baseClassReference); } - assignmentExpression = (PsiAssignmentExpression)CodeStyleManager.getInstance(myProject).reformat(assignmentExpression); + assignmentExpression = (PsiAssignmentExpression) CodeStyleManager.getInstance(myProject).reformat(assignmentExpression); newExpression.getArgumentList().replace(superConstructorCall.getArgumentList()); superConstructorCall.replace(assignmentExpression); } @@ -774,16 +772,16 @@ private boolean isFieldInitializerNeeded() { @RequiredReadAction private List getInnerClassMethods() { - ArrayList result = new ArrayList<>(); + List result = new ArrayList<>(); - // find all neccessary constructors + // find all necessary constructors if (!myBaseClass.isInterface()) { PsiMethod[] constructors = myClass.getConstructors(); for (PsiMethod constructor : constructors) { PsiStatement[] statements = constructor.getBody().getStatements(); if (statements.length > 0 && JavaHighlightUtil.isSuperOrThisCall(statements[0], true, false)) { PsiMethodCallExpression superConstructorCall = - (PsiMethodCallExpression)((PsiExpressionStatement)statements[0]).getExpression(); + (PsiMethodCallExpression) ((PsiExpressionStatement) statements[0]).getExpression(); if (superConstructorCall.getMethodExpression().resolve() instanceof PsiMethod superConstructor && superConstructor.isConstructor()) { result.add(new InnerClassConstructor(superConstructor)); @@ -800,6 +798,7 @@ public InnerClassOverridingMethod(PsiMethod method) { } @Override + @RequiredWriteAction public void createMethod(PsiClass innerClass) throws IncorrectOperationException { OverriddenMethodClassMemberReferencesVisitor visitor = new OverriddenMethodClassMemberReferencesVisitor(); @@ -845,7 +844,7 @@ public void createMethod(PsiClass innerClass) PsiMethod outerMethod = MethodSignatureUtil.findMethodBySignature(myClass, signature, false); if (outerMethod == null) { String visibility = checkOuterClassAbstractMethod(signature); - PsiMethod newOuterMethod = (PsiMethod)myClass.add(myMethod); + PsiMethod newOuterMethod = (PsiMethod) myClass.add(myMethod); PsiUtil.setModifierProperty(newOuterMethod, visibility, true); PsiDocComment docComment = newOuterMethod.getDocComment(); if (docComment != null) { @@ -914,7 +913,7 @@ private String checkOuterClassAbstractMethod(MethodSignature methodSignature) { } private Set getOverriddenMethods() { - LinkedHashSet result = new LinkedHashSet<>(); + Set result = new LinkedHashSet<>(); PsiMethod[] methods = myClass.getMethods(); for (PsiMethod method : methods) { @@ -972,7 +971,7 @@ private Set getAllBases() { private static void addAll(Collection collection, T[] objs) { Collections.addAll(collection, objs); - } + } private boolean isDelegated(PsiMember classMember) { if (!(classMember instanceof PsiMethod method)) { @@ -1061,17 +1060,18 @@ interface PsiAction { } /** - * This visitor should be called for overriden methods before they are moved to an inner class + * This visitor should be called for overridden methods before they are moved to an inner class */ private class OverriddenMethodClassMemberReferencesVisitor extends ClassMemberReferencesVisitor { - private final ArrayList myPsiActions; + private final List myPsiActions; private final PsiThisExpression myQualifiedThis; + @RequiredWriteAction OverriddenMethodClassMemberReferencesVisitor() throws IncorrectOperationException { super(myClass); myPsiActions = new ArrayList<>(); PsiJavaCodeReferenceElement classReferenceElement = myFactory.createClassReferenceElement(myClass); - myQualifiedThis = (PsiThisExpression)myFactory.createExpressionFromText("A.this", null); + myQualifiedThis = (PsiThisExpression) myFactory.createExpressionFromText("A.this", null); myQualifiedThis.getQualifier().replace(classReferenceElement); } @@ -1087,6 +1087,7 @@ class QualifyThis implements PsiAction { } @Override + @RequiredWriteAction public void run() throws IncorrectOperationException { myThisExpression.replace(myQualifiedThis); } @@ -1102,9 +1103,9 @@ class QualifyName implements PsiAction { } @Override + @RequiredWriteAction public void run() throws IncorrectOperationException { - PsiReferenceExpression newRef = - (PsiReferenceExpression)myFactory.createExpressionFromText("a." + myReferencedName, null); + PsiReferenceExpression newRef = (PsiReferenceExpression) myFactory.createExpressionFromText("a." + myReferencedName, null); newRef.getQualifierExpression().replace(myQualifiedThis); myRef.replace(newRef); } @@ -1123,7 +1124,7 @@ public QualifyWithField(PsiReferenceExpression reference, String name) { @RequiredWriteAction public void run() throws IncorrectOperationException { PsiReferenceExpression newRef = - (PsiReferenceExpression)myFactory.createExpressionFromText(myFieldName + "." + myReferencedName, null); + (PsiReferenceExpression) myFactory.createExpressionFromText(myFieldName + "." + myReferencedName, null); myReference.replace(newRef); } } @@ -1143,20 +1144,20 @@ else if (classMemberReference.getQualifierExpression() instanceof PsiThisExpress } } else if (classMember instanceof PsiMethod method && method.getContainingClass().equals(myClass)) { - if (!myOverriddenMethods.contains(method)) { + if (!myOverriddenMethods.contains(method)) { PsiMethod baseMethod = findSuperMethodInBaseClass(method); - if (baseMethod != null) { - myPsiActions.add(new QualifyName(classMemberReference, baseMethod.getName())); - } + if (baseMethod != null) { + myPsiActions.add(new QualifyName(classMemberReference, baseMethod.getName())); + } else if (classMemberReference.getQualifierExpression() instanceof PsiThisExpression thisExpr) { myPsiActions.add(new QualifyThis(thisExpr)); - } - } - else if (!myDelegatedMethods.contains(method)) { - myPsiActions.add(new QualifyWithField(classMemberReference, method.getName())); } } + else if (!myDelegatedMethods.contains(method)) { + myPsiActions.add(new QualifyWithField(classMemberReference, method.getName())); + } } + } @Override public void visitThisExpression(@Nonnull final PsiThisExpression expression) { @@ -1214,7 +1215,7 @@ public MyClassInstanceReferenceVisitor(PsiClass aClass, List usageInf public Set getImplementedInterfaces() { PsiClass aClass = myClass; - HashSet result = new HashSet<>(); + Set result = new HashSet<>(); while (aClass != null && !myManager.areElementsEquivalent(aClass, myBaseClass)) { PsiClassType[] implementsTypes = aClass.getImplementsListTypes(); for (PsiClassType implementsType : implementsTypes) { @@ -1242,10 +1243,10 @@ public void visitQualifier(PsiReferenceExpression qualified, PsiExpression insta return; } - PsiElement resolved = qualified.resolve(); - if (resolved != null && (myBaseClassMembers.contains(resolved) || myOverriddenMethods.contains(resolved)) - && !isDelegated((PsiMember)resolved)) { - myUsageInfoStorage.add(new NonDelegatedMemberUsageInfo(instanceRef, resolved, getFieldAccessibility(instanceRef))); + if (qualified.resolve() instanceof PsiMember member + && (myBaseClassMembers.contains(member) || myOverriddenMethods.contains(member)) + && !isDelegated(member)) { + myUsageInfoStorage.add(new NonDelegatedMemberUsageInfo(instanceRef, member, getFieldAccessibility(instanceRef))); } } diff --git a/plugin/src/main/java/com/intellij/java/impl/refactoring/inline/InlineConstantFieldProcessor.java b/plugin/src/main/java/com/intellij/java/impl/refactoring/inline/InlineConstantFieldProcessor.java index 5cf8c96f95..d45d0cbe4b 100644 --- a/plugin/src/main/java/com/intellij/java/impl/refactoring/inline/InlineConstantFieldProcessor.java +++ b/plugin/src/main/java/com/intellij/java/impl/refactoring/inline/InlineConstantFieldProcessor.java @@ -173,7 +173,6 @@ protected void refreshElements(@Nonnull PsiElement[] elements) { } @Override - @RequiredUIAccess @RequiredWriteAction protected void performRefactoring(@Nonnull UsageInfo[] usages) { PsiExpression initializer = myField.getInitializer(); @@ -290,13 +289,13 @@ protected String getCommandName() { @RequiredUIAccess protected boolean preprocessUsages(@Nonnull SimpleReference refUsages) { UsageInfo[] usagesIn = refUsages.get(); - MultiMap conflicts = new MultiMap<>(); + MultiMap conflicts = new MultiMap<>(); ReferencedElementsCollector collector = new ReferencedElementsCollector(); PsiExpression initializer = myField.getInitializer(); LOG.assertTrue(initializer != null); initializer.accept(collector); - HashSet referencedWithVisibility = collector.myReferencedMembers; + Set referencedWithVisibility = collector.myReferencedMembers; PsiResolveHelper resolveHelper = JavaPsiFacade.getInstance(myField.getProject()).getResolveHelper(); for (UsageInfo info : usagesIn) { @@ -306,7 +305,7 @@ protected boolean preprocessUsages(@Nonnull SimpleReference refUsag RefactoringUIUtil.getDescription(myField, true), RefactoringUIUtil.getDescription(ConflictsUtil.getContainer(element), true) ); - conflicts.putValue(element, message.get()); + conflicts.putValue(element, message); } for (PsiMember member : referencedWithVisibility) { @@ -315,7 +314,7 @@ protected boolean preprocessUsages(@Nonnull SimpleReference refUsag RefactoringUIUtil.getDescription(member, true), RefactoringUIUtil.getDescription(ConflictsUtil.getContainer(element), true) ); - conflicts.putValue(member, message.get()); + conflicts.putValue(member, message); } } } @@ -325,11 +324,11 @@ protected boolean preprocessUsages(@Nonnull SimpleReference refUsag PsiElement element = info.getElement(); if (element instanceof PsiDocMethodOrFieldRef psiDocMethodOrFieldRef && !PsiTreeUtil.isAncestor(myField, psiDocMethodOrFieldRef, false)) { - conflicts.putValue(psiDocMethodOrFieldRef, JavaRefactoringLocalize.inlineFieldUsedInJavadoc().get()); + conflicts.putValue(psiDocMethodOrFieldRef, JavaRefactoringLocalize.inlineFieldUsedInJavadoc()); } - if (element instanceof PsiLiteralExpression - && ContainerUtil.or(element.getReferences(), JavaLangClassMemberReference.class::isInstance)) { - conflicts.putValue(element, JavaRefactoringLocalize.inlineFieldUsedInReflection().get()); + if (element instanceof PsiLiteralExpression literal + && ContainerUtil.or(literal.getReferences(), JavaLangClassMemberReference.class::isInstance)) { + conflicts.putValue(literal, JavaRefactoringLocalize.inlineFieldUsedInReflection()); } } } diff --git a/plugin/src/main/java/com/intellij/java/impl/refactoring/inline/InlineParameterExpressionProcessor.java b/plugin/src/main/java/com/intellij/java/impl/refactoring/inline/InlineParameterExpressionProcessor.java index 896b9a1ad0..0f458b301c 100644 --- a/plugin/src/main/java/com/intellij/java/impl/refactoring/inline/InlineParameterExpressionProcessor.java +++ b/plugin/src/main/java/com/intellij/java/impl/refactoring/inline/InlineParameterExpressionProcessor.java @@ -31,6 +31,7 @@ import consulo.language.psi.PsiReference; import consulo.language.psi.search.ReferencesSearch; import consulo.language.psi.util.PsiTreeUtil; +import consulo.localize.LocalizeValue; import consulo.logging.Logger; import consulo.ui.annotation.RequiredUIAccess; import consulo.usage.UsageInfo; @@ -105,15 +106,15 @@ protected UsageInfo[] findUsages() { PsiExpression paramRef = JavaPsiFacade.getInstance(myMethod.getProject()) .getElementFactory() .createExpressionFromText(param.getName(), myMethod); - localToParamRef.put((PsiVariable)element, paramRef); + localToParamRef.put((PsiVariable) element, paramRef); } } } List result = new ArrayList<>(); myInitializer.accept(new JavaRecursiveElementVisitor() { - @RequiredWriteAction @Override + @RequiredWriteAction public void visitReferenceExpression(PsiReferenceExpression expression) { super.visitReferenceExpression(expression); if (expression.resolve() instanceof PsiLocalVariable localVariable) { @@ -179,7 +180,7 @@ public void visitReferenceExpression(PsiReferenceExpression referenceExpression) @Override @RequiredUIAccess protected boolean preprocessUsages(@Nonnull SimpleReference refUsages) { - MultiMap conflicts = new MultiMap<>(); + MultiMap conflicts = new MultiMap<>(); UsageInfo[] usages = refUsages.get(); InaccessibleExpressionsDetector detector = new InaccessibleExpressionsDetector(conflicts); myInitializer.accept(detector); @@ -206,7 +207,9 @@ protected boolean preprocessUsages(@Nonnull SimpleReference refUsag if (ref.getElement() instanceof PsiExpression expression && isAccessedForWriting(expression)) { conflicts.putValue( expression, - "Parameter initializer depends on value which is not available inside method and cannot be inlined" + LocalizeValue.localizeTODO( + "Parameter initializer depends on value which is not available inside method and cannot be inlined" + ) ); break; } @@ -240,21 +243,21 @@ protected void performRefactoring(UsageInfo[] usages) { } else { LOG.assertTrue(!myCreateLocal); - paramRefsToInline.add((PsiJavaCodeReferenceElement)usage.getElement()); + paramRefsToInline.add((PsiJavaCodeReferenceElement) usage.getElement()); } } - myInitializer = (PsiExpression)RefactoringUtil.replaceElementsWithMap(myInitializer, replacements); + myInitializer = (PsiExpression) RefactoringUtil.replaceElementsWithMap(myInitializer, replacements); if (myCreateLocal) { PsiElementFactory factory = JavaPsiFacade.getInstance(myMethod.getProject()).getElementFactory(); PsiDeclarationStatement localDeclaration = factory.createVariableDeclarationStatement(myParameter.getName(), myParameter.getType(), myInitializer); - PsiLocalVariable declaredVar = (PsiLocalVariable)localDeclaration.getDeclaredElements()[0]; + PsiLocalVariable declaredVar = (PsiLocalVariable) localDeclaration.getDeclaredElements()[0]; PsiUtil.setModifierProperty(declaredVar, PsiModifier.FINAL, myParameter.hasModifierProperty(PsiModifier.FINAL)); PsiExpression localVarInitializer = InlineUtil.inlineVariable( myParameter, myInitializer, - (PsiReferenceExpression)factory.createExpressionFromText(myParameter.getName(), myMethod) + (PsiReferenceExpression) factory.createExpressionFromText(myParameter.getName(), myMethod) ); PsiExpression initializer = declaredVar.getInitializer(); LOG.assertTrue(initializer != null); @@ -333,9 +336,9 @@ public PsiVariable getVariable() { } private class InaccessibleExpressionsDetector extends JavaRecursiveElementWalkingVisitor { - private final MultiMap myConflicts; + private final MultiMap myConflicts; - public InaccessibleExpressionsDetector(MultiMap conflicts) { + public InaccessibleExpressionsDetector(MultiMap conflicts) { myConflicts = conflicts; } @@ -348,23 +351,30 @@ public void visitReferenceExpression(PsiReferenceExpression expression) { if (myMethod.isStatic()) { myConflicts.putValue( expression, - "Parameter initializer depends on " + RefactoringUIUtil.getDescription( - element, - false - ) + " which is not available inside the static method" + LocalizeValue.localizeTODO( + "Parameter initializer depends on " + + RefactoringUIUtil.getDescription(member, false) + " which is not available inside the static method" + ) ); } } if (element instanceof PsiMethod || element instanceof PsiField) { - if (!mySameClass && !((PsiModifierListOwner)element).hasModifierProperty(PsiModifier.STATIC)) { - myConflicts.putValue(expression, "Parameter initializer depends on non static member from some other class"); + PsiMember member = (PsiMember) element; + if (!mySameClass && !member.isStatic()) { + myConflicts.putValue( + expression, + LocalizeValue.localizeTODO("Parameter initializer depends on non static member from some other class") + ); } - else if (!PsiUtil.isAccessible((PsiMember)element, myMethod, null)) { - myConflicts.putValue(expression, "Parameter initializer depends on value which is not available inside method"); + else if (!PsiUtil.isAccessible(member, myMethod, null)) { + myConflicts.putValue( + expression, + LocalizeValue.localizeTODO("Parameter initializer depends on value which is not available inside method") + ); } } else if (element instanceof PsiParameter) { - myConflicts.putValue(expression, "Parameter initializer depends on callers parameter"); + myConflicts.putValue(expression, LocalizeValue.localizeTODO("Parameter initializer depends on callers parameter")); } } @@ -385,13 +395,15 @@ public void visitThisExpression(@Nonnull PsiThisExpression thisExpression) { if (!PsiTreeUtil.isAncestor(containingClass, methodContainingClass, false)) { myConflicts.putValue( thisExpression, - "Parameter initializer depends on this which is not available inside the method and cannot be inlined" + LocalizeValue.localizeTODO( + "Parameter initializer depends on this which is not available inside the method and cannot be inlined" + ) ); } else if (myMethod.isStatic()) { myConflicts.putValue( thisExpression, - "Parameter initializer depends on this which is not available inside the static method" + LocalizeValue.localizeTODO("Parameter initializer depends on this which is not available inside the static method") ); } } @@ -403,7 +415,9 @@ public void visitReferenceElement(@Nonnull PsiJavaCodeReferenceElement reference if (myMethod.isStatic() && reference.resolve() instanceof PsiClass psiClass && !psiClass.isStatic()) { myConflicts.putValue( reference, - "Parameter initializer depends on non static class which is not available inside static method" + LocalizeValue.localizeTODO( + "Parameter initializer depends on non static class which is not available inside static method" + ) ); } } @@ -414,9 +428,11 @@ public void visitNewExpression(@Nonnull PsiNewExpression expression) { super.visitNewExpression(expression); PsiJavaCodeReferenceElement reference = expression.getClassOrAnonymousClassReference(); if (reference != null && reference.resolve() instanceof PsiClass refClass) { - String classUnavailableMessage = "Parameter initializer depends on " + - RefactoringUIUtil.getDescription(refClass, true) + - " which is not available inside method and cannot be inlined"; + LocalizeValue classUnavailableMessage = LocalizeValue.localizeTODO( + "Parameter initializer depends on " + + RefactoringUIUtil.getDescription(refClass, true) + + " which is not available inside method and cannot be inlined" + ); if (!PsiUtil.isAccessible(refClass, myMethod, null)) { myConflicts.putValue(expression, classUnavailableMessage); } diff --git a/plugin/src/main/java/com/intellij/java/impl/refactoring/inline/InlineToAnonymousClassProcessor.java b/plugin/src/main/java/com/intellij/java/impl/refactoring/inline/InlineToAnonymousClassProcessor.java index 1e1f857b61..ade221ae5e 100644 --- a/plugin/src/main/java/com/intellij/java/impl/refactoring/inline/InlineToAnonymousClassProcessor.java +++ b/plugin/src/main/java/com/intellij/java/impl/refactoring/inline/InlineToAnonymousClassProcessor.java @@ -30,9 +30,9 @@ import consulo.language.psi.search.ReferencesSearch; import consulo.language.psi.util.PsiTreeUtil; import consulo.language.util.IncorrectOperationException; +import consulo.localize.LocalizeValue; import consulo.logging.Logger; import consulo.project.Project; -import consulo.project.ui.wm.WindowManager; import consulo.ui.annotation.RequiredUIAccess; import consulo.usage.UsageInfo; import consulo.usage.UsageViewDescriptor; @@ -116,7 +116,7 @@ protected UsageInfo[] findUsages() { @Override protected void refreshElements(PsiElement[] elements) { assert elements.length == 1; - myClass = (PsiClass)elements[0]; + myClass = (PsiClass) elements[0]; } @Override @@ -139,19 +139,13 @@ private static boolean isForcePreview(UsageInfo usage) { return true; } PsiElement element = usage.getElement(); - if (element != null) { - PsiFile file = element.getContainingFile(); - if (!(file instanceof PsiJavaFile)) { - return true; - } - } - return false; + return element != null && !(element.getContainingFile() instanceof PsiJavaFile); } @Override @RequiredUIAccess protected boolean preprocessUsages(@Nonnull SimpleReference refUsages) { - MultiMap conflicts = getConflicts(refUsages.get()); + MultiMap conflicts = getConflicts(refUsages.get()); if (!conflicts.isEmpty()) { return showConflicts(conflicts, refUsages.get()); } @@ -159,17 +153,15 @@ protected boolean preprocessUsages(@Nonnull SimpleReference refUsag } @RequiredReadAction - public MultiMap getConflicts(UsageInfo[] usages) { - final MultiMap result = new MultiMap<>(); + public MultiMap getConflicts(UsageInfo[] usages) { + final MultiMap result = new MultiMap<>(); ReferencedElementsCollector collector = new ReferencedElementsCollector() { @Override protected void checkAddMember(@Nonnull PsiMember member) { if (PsiTreeUtil.isAncestor(myClass, member, false)) { return; } - PsiModifierList modifierList = member.getModifierList(); - if (member.getContainingClass() == myClass.getSuperClass() && modifierList != null - && modifierList.hasModifierProperty(PsiModifier.PROTECTED)) { + if (member.getContainingClass() == myClass.getSuperClass() && member.isProtected()) { // ignore access to protected members of superclass - they'll be accessible anyway return; } @@ -197,9 +189,12 @@ public void visitParameter(@Nonnull PsiParameter parameter) { if (resolvedMember instanceof PsiMethod method && myClass.findMethodsBySignature(method, true).length > 1) { //skip inherited methods - continue; - } - result.putValue(refElement, "Class cannot be inlined because a call to its member inside body"); + continue; + } + result.putValue( + refElement, + LocalizeValue.localizeTODO("Class cannot be inlined because a call to its member inside body") + ); } } } @@ -212,7 +207,10 @@ public void visitNewExpression(@Nonnull PsiNewExpression expression) { if (PsiUtil.resolveClassInType(expression.getType()) != myClass) { return; } - result.putValue(expression, "Class cannot be inlined because a call to its constructor inside body"); + result.putValue( + expression, + LocalizeValue.localizeTODO("Class cannot be inlined because a call to its constructor inside body") + ); } @Override @@ -224,11 +222,10 @@ public void visitMethodCallExpression(@Nonnull PsiMethodCallExpression expressio if (qualifierExpression != null && PsiUtil.resolveClassInType(qualifierExpression.getType()) != myClass) { return; } - PsiElement resolved = methodExpression.resolve(); - if (resolved instanceof PsiMethod method) { - if ("getClass".equals(method.getName()) && method.getParameterList().getParametersCount() == 0) { - result.putValue(methodExpression, "Result of getClass() invocation would be changed"); - } + if (methodExpression.resolve() instanceof PsiMethod method + && "getClass".equals(method.getName()) + && method.getParameterList().getParametersCount() == 0) { + result.putValue(methodExpression, LocalizeValue.localizeTODO("Result of getClass() invocation would be changed")); } } }); @@ -309,7 +306,7 @@ private void replaceNewOrType(PsiNewExpression psiNewExpression, PsiClassType su @RequiredWriteAction private void replaceWithSuperType(PsiTypeElement typeElement, PsiClassType superType) { PsiElementFactory factory = JavaPsiFacade.getInstance(myClass.getProject()).getElementFactory(); - PsiClassType psiType = (PsiClassType)typeElement.getType(); + PsiClassType psiType = (PsiClassType) typeElement.getType(); PsiClassType.ClassResolveResult classResolveResult = psiType.resolveGenerics(); PsiType substType = classResolveResult.getSubstitutor().substitute(superType); assert classResolveResult.getElement() == myClass; diff --git a/plugin/src/main/java/com/intellij/java/impl/refactoring/inlineSuperClass/InlineSuperClassRefactoringProcessor.java b/plugin/src/main/java/com/intellij/java/impl/refactoring/inlineSuperClass/InlineSuperClassRefactoringProcessor.java index e41ae55f8e..b21fdec5f5 100644 --- a/plugin/src/main/java/com/intellij/java/impl/refactoring/inlineSuperClass/InlineSuperClassRefactoringProcessor.java +++ b/plugin/src/main/java/com/intellij/java/impl/refactoring/inlineSuperClass/InlineSuperClassRefactoringProcessor.java @@ -40,6 +40,7 @@ import consulo.language.psi.search.ReferencesSearch; import consulo.language.psi.util.PsiTreeUtil; import consulo.language.util.IncorrectOperationException; +import consulo.localize.LocalizeValue; import consulo.logging.Logger; import consulo.project.Project; import consulo.ui.annotation.RequiredUIAccess; @@ -219,7 +220,7 @@ else if (element.getParent() instanceof PsiJavaCodeReferenceElement parentCodeRe @Override @RequiredUIAccess protected boolean preprocessUsages(@Nonnull SimpleReference refUsages) { - MultiMap conflicts = new MultiMap<>(); + MultiMap conflicts = new MultiMap<>(); PushDownConflicts pushDownConflicts = new PushDownConflicts(mySuperClass, myMemberInfos); for (PsiClass targetClass : myTargetClasses) { for (MemberInfo info : myMemberInfos) { @@ -228,7 +229,7 @@ protected boolean preprocessUsages(@Nonnull SimpleReference refUsag } //todo check accessibility conflicts } - MultiMap conflictsMap = pushDownConflicts.getConflicts(); + MultiMap conflictsMap = pushDownConflicts.getConflicts(); for (PsiElement element : conflictsMap.keySet()) { conflicts.put(element, conflictsMap.get(element)); } @@ -237,7 +238,9 @@ protected boolean preprocessUsages(@Nonnull SimpleReference refUsag PsiElement element = reference.getElement(); if (element != null && element.getParent() instanceof PsiNewExpression newExpr && PsiUtil.resolveClassInType(getPlaceExpectedType(newExpr)) == mySuperClass) { - conflicts.putValue(newExpr, "Instance of target type is passed to a place where super class is expected."); + conflicts.putValue(newExpr, + LocalizeValue.localizeTODO("Instance of target type is passed to a place where super class is expected.") + ); return false; } return true; @@ -274,18 +277,17 @@ private static PsiType getPlaceExpectedType(PsiElement parent) { } @Override - @RequiredUIAccess + @RequiredWriteAction protected void performRefactoring(@Nonnull UsageInfo[] usages) { new PushDownProcessor(mySuperClass.getProject(), myMemberInfos, mySuperClass, new DocCommentPolicy(myPolicy)) { //push down conflicts are already collected @Override @RequiredUIAccess - protected boolean showConflicts(@Nonnull MultiMap conflicts, UsageInfo[] usages) { + protected boolean showConflicts(@Nonnull MultiMap conflicts, UsageInfo[] usages) { return true; } @Override - @RequiredUIAccess @RequiredWriteAction protected void performRefactoring(@Nonnull UsageInfo[] pushDownUsages) { if (myCurrentInheritor != null) { diff --git a/plugin/src/main/java/com/intellij/java/impl/refactoring/inlineSuperClass/usageInfo/ReplaceReferenceUsageInfo.java b/plugin/src/main/java/com/intellij/java/impl/refactoring/inlineSuperClass/usageInfo/ReplaceReferenceUsageInfo.java index a8f660485a..61337f15e5 100644 --- a/plugin/src/main/java/com/intellij/java/impl/refactoring/inlineSuperClass/usageInfo/ReplaceReferenceUsageInfo.java +++ b/plugin/src/main/java/com/intellij/java/impl/refactoring/inlineSuperClass/usageInfo/ReplaceReferenceUsageInfo.java @@ -25,38 +25,49 @@ import com.intellij.java.language.psi.PsiClass; import com.intellij.java.language.psi.PsiElementFactory; import com.intellij.java.language.psi.PsiReferenceExpression; +import consulo.annotation.access.RequiredReadAction; +import consulo.annotation.access.RequiredWriteAction; import consulo.language.psi.PsiElement; import consulo.language.util.IncorrectOperationException; +import consulo.localize.LocalizeValue; import consulo.logging.Logger; import consulo.util.lang.StringUtil; - -import java.util.function.Function; +import jakarta.annotation.Nonnull; public class ReplaceReferenceUsageInfo extends FixableUsageInfo { - public static final Logger LOG = Logger.getInstance(ReplaceReferenceUsageInfo.class); - private final PsiClass myTargetClass; - private final String myConflict; + public static final Logger LOG = Logger.getInstance(ReplaceReferenceUsageInfo.class); + private final PsiClass myTargetClass; + @Nonnull + private final LocalizeValue myConflict; - public ReplaceReferenceUsageInfo(PsiElement referenceExpression, PsiClass[] targetClasses) { - super(referenceExpression); - myTargetClass = targetClasses[0]; - myConflict = targetClasses.length > 1 ? referenceExpression.getText() + "can be replaced with any of " + StringUtil.join(targetClasses, new Function() { - public String apply(final PsiClass psiClass) { - return psiClass.getQualifiedName(); - } - }, ", ") : null; - } + @RequiredReadAction + public ReplaceReferenceUsageInfo(PsiElement referenceExpression, PsiClass[] targetClasses) { + super(referenceExpression); + myTargetClass = targetClasses[0]; + myConflict = targetClasses.length > 1 + ? LocalizeValue.localizeTODO( + referenceExpression.getText() + "can be replaced with any of " + + StringUtil.join(targetClasses, PsiClass::getQualifiedName, ", ") + ) + : LocalizeValue.empty(); + } - public void fixUsage() throws IncorrectOperationException { - final PsiElement referenceExpression = getElement(); - if (referenceExpression != null) { - final PsiElementFactory elementFactory = JavaPsiFacade.getInstance(getProject()).getElementFactory(); - referenceExpression.replace(referenceExpression instanceof PsiReferenceExpression ? elementFactory.createReferenceExpression(myTargetClass) : elementFactory.createClassReferenceElement(myTargetClass)); + @Override + @RequiredWriteAction + public void fixUsage() throws IncorrectOperationException { + PsiElement referenceExpression = getElement(); + if (referenceExpression != null) { + PsiElementFactory elementFactory = JavaPsiFacade.getInstance(getProject()).getElementFactory(); + referenceExpression.replace( + referenceExpression instanceof PsiReferenceExpression + ? elementFactory.createReferenceExpression(myTargetClass) + : elementFactory.createClassReferenceElement(myTargetClass) + ); + } } - } - @Override - public String getConflictMessage() { - return myConflict; - } + @Override + public LocalizeValue getConflictMessage() { + return myConflict; + } } \ No newline at end of file diff --git a/plugin/src/main/java/com/intellij/java/impl/refactoring/inlineSuperClass/usageInfo/ReplaceStaticImportUsageInfo.java b/plugin/src/main/java/com/intellij/java/impl/refactoring/inlineSuperClass/usageInfo/ReplaceStaticImportUsageInfo.java index 691bc97b7f..6ad9d87c2c 100644 --- a/plugin/src/main/java/com/intellij/java/impl/refactoring/inlineSuperClass/usageInfo/ReplaceStaticImportUsageInfo.java +++ b/plugin/src/main/java/com/intellij/java/impl/refactoring/inlineSuperClass/usageInfo/ReplaceStaticImportUsageInfo.java @@ -24,30 +24,40 @@ import com.intellij.java.language.psi.JavaPsiFacade; import com.intellij.java.language.psi.PsiClass; import com.intellij.java.language.psi.PsiImportStaticStatement; +import consulo.annotation.access.RequiredReadAction; +import consulo.annotation.access.RequiredWriteAction; import consulo.language.util.IncorrectOperationException; +import consulo.localize.LocalizeValue; import consulo.util.lang.StringUtil; public class ReplaceStaticImportUsageInfo extends FixableUsageInfo { - private final PsiImportStaticStatement myStaticImportStatement; - private final PsiClass[] myTargetClasses; + private final PsiImportStaticStatement myStaticImportStatement; + private final PsiClass[] myTargetClasses; - public ReplaceStaticImportUsageInfo(final PsiImportStaticStatement staticImportStatement, final PsiClass[] targetClass) { - super(staticImportStatement); - myStaticImportStatement = staticImportStatement; - myTargetClasses = targetClass; - } + @RequiredReadAction + public ReplaceStaticImportUsageInfo(PsiImportStaticStatement staticImportStatement, PsiClass[] targetClass) { + super(staticImportStatement); + myStaticImportStatement = staticImportStatement; + myTargetClasses = targetClass; + } - public void fixUsage() throws IncorrectOperationException { - final String memberName = myStaticImportStatement.getReferenceName(); - myStaticImportStatement.replace(JavaPsiFacade.getInstance(myStaticImportStatement.getProject()).getElementFactory().createImportStaticStatement(myTargetClasses[0], - memberName != null ? memberName : "*")); - } + @Override + @RequiredWriteAction + public void fixUsage() throws IncorrectOperationException { + String memberName = myStaticImportStatement.getReferenceName(); + myStaticImportStatement.replace(JavaPsiFacade.getInstance(myStaticImportStatement.getProject()) + .getElementFactory() + .createImportStaticStatement(myTargetClasses[0], memberName != null ? memberName : "*")); + } - @Override - public String getConflictMessage() { - if (myTargetClasses.length != 1) { - return "Static import can be replaced with any of " + StringUtil.join(myTargetClasses, psiClass -> psiClass.getQualifiedName(), ", "); + @Override + public LocalizeValue getConflictMessage() { + if (myTargetClasses.length != 1) { + return LocalizeValue.localizeTODO( + "Static import can be replaced with any of " + + StringUtil.join(myTargetClasses, psiClass -> psiClass.getQualifiedName(), ", ") + ); + } + return super.getConflictMessage(); } - return super.getConflictMessage(); - } } \ No newline at end of file diff --git a/plugin/src/main/java/com/intellij/java/impl/refactoring/inlineSuperClass/usageInfo/ReplaceWithSubtypeUsageInfo.java b/plugin/src/main/java/com/intellij/java/impl/refactoring/inlineSuperClass/usageInfo/ReplaceWithSubtypeUsageInfo.java index d1403b6875..ec3f333616 100644 --- a/plugin/src/main/java/com/intellij/java/impl/refactoring/inlineSuperClass/usageInfo/ReplaceWithSubtypeUsageInfo.java +++ b/plugin/src/main/java/com/intellij/java/impl/refactoring/inlineSuperClass/usageInfo/ReplaceWithSubtypeUsageInfo.java @@ -13,66 +13,68 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - -/* - * User: anna - * Date: 27-Aug-2008 - */ package com.intellij.java.impl.refactoring.inlineSuperClass.usageInfo; import com.intellij.java.impl.refactoring.util.FixableUsageInfo; import com.intellij.java.language.psi.*; import com.intellij.java.language.psi.util.TypeConversionUtil; +import consulo.annotation.access.RequiredReadAction; +import consulo.annotation.access.RequiredWriteAction; import consulo.language.util.IncorrectOperationException; +import consulo.localize.LocalizeValue; import consulo.logging.Logger; import consulo.util.lang.StringUtil; +import jakarta.annotation.Nonnull; -import java.util.function.Function; - +/** + * @author anna + * @since 2008-08-27 + */ public class ReplaceWithSubtypeUsageInfo extends FixableUsageInfo { - public static final Logger LOG = Logger.getInstance(ReplaceWithSubtypeUsageInfo.class); - private final PsiTypeElement myTypeElement; - private final PsiClassType myTargetClassType; - private final PsiType myOriginalType; - private String myConflict; + public static final Logger LOG = Logger.getInstance(ReplaceWithSubtypeUsageInfo.class); + private final PsiTypeElement myTypeElement; + private final PsiClassType myTargetClassType; + private final PsiType myOriginalType; + @Nonnull + private LocalizeValue myConflict; - public ReplaceWithSubtypeUsageInfo(PsiTypeElement typeElement, PsiClassType classType, final PsiClass[] targetClasses) { - super(typeElement); - myTypeElement = typeElement; - myTargetClassType = classType; - myOriginalType = myTypeElement.getType(); - if (targetClasses.length > 1) { - myConflict = typeElement.getText() + " can be replaced with any of " + StringUtil.join(targetClasses, new Function() { - public String apply(final PsiClass psiClass) { - return psiClass.getQualifiedName(); + @RequiredReadAction + public ReplaceWithSubtypeUsageInfo(PsiTypeElement typeElement, PsiClassType classType, PsiClass[] targetClasses) { + super(typeElement); + myTypeElement = typeElement; + myTargetClassType = classType; + myOriginalType = myTypeElement.getType(); + if (targetClasses.length > 1) { + myConflict = LocalizeValue.localizeTODO( + typeElement.getText() + " can be replaced with any of " + + StringUtil.join(targetClasses, psiClass -> psiClass.getQualifiedName(), ", ") + ); } - }, ", ") ; } - } - public void fixUsage() throws IncorrectOperationException { - if (myTypeElement.isValid()) { - final PsiElementFactory elementFactory = JavaPsiFacade.getInstance(myTypeElement.getProject()).getElementFactory(); - myTypeElement.replace(elementFactory.createTypeElement(myTargetClassType)); + @Override + @RequiredWriteAction + public void fixUsage() throws IncorrectOperationException { + if (myTypeElement.isValid()) { + PsiElementFactory elementFactory = JavaPsiFacade.getInstance(myTypeElement.getProject()).getElementFactory(); + myTypeElement.replace(elementFactory.createTypeElement(myTargetClassType)); + } } - } - @Override - public String getConflictMessage() { - if (!TypeConversionUtil.isAssignable(myOriginalType, myTargetClassType)) { - final String conflict = "No consistent substitution found for " + - getElement().getText() + - ". Expected \'" + - myOriginalType.getPresentableText() + - "\' but found \'" + - myTargetClassType.getPresentableText() + - "\'."; - if (myConflict == null) { - myConflict = conflict; - } else { - myConflict += "\n" + conflict; - } + @Override + @RequiredReadAction + public LocalizeValue getConflictMessage() { + if (!TypeConversionUtil.isAssignable(myOriginalType, myTargetClassType)) { + LocalizeValue conflict = LocalizeValue.localizeTODO("No consistent substitution found for " + getElement().getText() + ". " + + "Expected \'" + myOriginalType.getPresentableText() + "\' " + + "but found \'" + myTargetClassType.getPresentableText() + "\'."); + if (myConflict == LocalizeValue.empty()) { + myConflict = conflict; + } + else { + myConflict = LocalizeValue.join(myConflict, LocalizeValue.of("\n"), conflict); + } + } + return myConflict; } - return myConflict; - } } diff --git a/plugin/src/main/java/com/intellij/java/impl/refactoring/introduceField/InplaceIntroduceConstantPopup.java b/plugin/src/main/java/com/intellij/java/impl/refactoring/introduceField/InplaceIntroduceConstantPopup.java index 818aa78d02..451298b444 100644 --- a/plugin/src/main/java/com/intellij/java/impl/refactoring/introduceField/InplaceIntroduceConstantPopup.java +++ b/plugin/src/main/java/com/intellij/java/impl/refactoring/introduceField/InplaceIntroduceConstantPopup.java @@ -39,259 +39,270 @@ import java.awt.*; /** - * User: anna - * Date: 3/18/11 + * @author anna + * @since 2011-03-18 */ public class InplaceIntroduceConstantPopup extends AbstractInplaceIntroduceFieldPopup { + private final String myInitializerText; - private final String myInitializerText; + private JCheckBox myReplaceAllCb; - private JCheckBox myReplaceAllCb; + private JCheckBox myMoveToAnotherClassCb; - private JCheckBox myMoveToAnotherClassCb; + @RequiredReadAction + public InplaceIntroduceConstantPopup( + Project project, + Editor editor, + PsiClass parentClass, + PsiExpression expr, + PsiLocalVariable localVariable, + PsiExpression[] occurrences, + TypeSelectorManagerImpl typeSelectorManager, + PsiElement anchorElement, + PsiElement anchorElementIfAll, OccurrenceManager occurrenceManager + ) { + super( + project, + editor, + expr, + localVariable, + occurrences, + typeSelectorManager, + IntroduceConstantHandlerImpl.REFACTORING_NAME.get(), + parentClass, + anchorElement, + occurrenceManager, + anchorElementIfAll + ); - @RequiredReadAction - public InplaceIntroduceConstantPopup( - Project project, - Editor editor, - PsiClass parentClass, - PsiExpression expr, - PsiLocalVariable localVariable, - PsiExpression[] occurrences, - TypeSelectorManagerImpl typeSelectorManager, - PsiElement anchorElement, - PsiElement anchorElementIfAll, OccurrenceManager occurrenceManager - ) { - super( - project, - editor, - expr, - localVariable, - occurrences, - typeSelectorManager, - IntroduceConstantHandlerImpl.REFACTORING_NAME, - parentClass, - anchorElement, - occurrenceManager, - anchorElementIfAll - ); + myInitializerText = getExprText(expr, localVariable); - myInitializerText = getExprText(expr, localVariable); + GridBagConstraints gc = new GridBagConstraints( + 0, 0, 1, 1, 1, 0, GridBagConstraints.NORTHWEST, GridBagConstraints.HORIZONTAL, + JBUI.emptyInsets(), 0, 0 + ); + myWholePanel.add(getPreviewComponent(), gc); - GridBagConstraints gc = new GridBagConstraints( - 0, 0, 1, 1, 1, 0, GridBagConstraints.NORTHWEST, GridBagConstraints.HORIZONTAL, - JBUI.emptyInsets(), 0, 0 - ); - myWholePanel.add(getPreviewComponent(), gc); + gc.gridy = 1; + myWholePanel.add(createRightPanel(), gc); - gc.gridy = 1; - myWholePanel.add(createRightPanel(), gc); - - gc.gridy = 2; - myWholePanel.add(createLeftPanel(), gc); - } - - @Nullable - @RequiredReadAction - private static String getExprText(PsiExpression expr, PsiLocalVariable localVariable) { - final String exprText = expr != null ? expr.getText() : null; - if (localVariable != null) { - final PsiExpression initializer = localVariable.getInitializer(); - return initializer != null ? initializer.getText() : exprText; - } else { - return exprText; + gc.gridy = 2; + myWholePanel.add(createLeftPanel(), gc); } - } - private JPanel createRightPanel() { - final JPanel right = new JPanel(new GridBagLayout()); - final GridBagConstraints rgc = new GridBagConstraints( - 0, GridBagConstraints.RELATIVE, 1, 1, 1, 0, GridBagConstraints.NORTHWEST, GridBagConstraints.HORIZONTAL, - JBUI.emptyInsets(), 0, 0 - ); - myReplaceAllCb = new JCheckBox("Replace all occurrences"); - myReplaceAllCb.setMnemonic('a'); - myReplaceAllCb.setFocusable(false); - myReplaceAllCb.setVisible(myOccurrences.length > 1); - right.add(myReplaceAllCb, rgc); + @Nullable + @RequiredReadAction + private static String getExprText(PsiExpression expr, PsiLocalVariable localVariable) { + final String exprText = expr != null ? expr.getText() : null; + if (localVariable != null) { + final PsiExpression initializer = localVariable.getInitializer(); + return initializer != null ? initializer.getText() : exprText; + } + else { + return exprText; + } + } - return right; - } + private JPanel createRightPanel() { + final JPanel right = new JPanel(new GridBagLayout()); + final GridBagConstraints rgc = new GridBagConstraints( + 0, GridBagConstraints.RELATIVE, 1, 1, 1, 0, GridBagConstraints.NORTHWEST, GridBagConstraints.HORIZONTAL, + JBUI.emptyInsets(), 0, 0 + ); + myReplaceAllCb = new JCheckBox("Replace all occurrences"); + myReplaceAllCb.setMnemonic('a'); + myReplaceAllCb.setFocusable(false); + myReplaceAllCb.setVisible(myOccurrences.length > 1); + right.add(myReplaceAllCb, rgc); - private JPanel createLeftPanel() { - final JPanel left = new JPanel(new GridBagLayout()); - myMoveToAnotherClassCb = - new JCheckBox("Move to another class", JavaRefactoringSettings.getInstance().INTRODUCE_CONSTANT_MOVE_TO_ANOTHER_CLASS); - myMoveToAnotherClassCb.setMnemonic('m'); - myMoveToAnotherClassCb.setFocusable(false); - left.add( - myMoveToAnotherClassCb, - new GridBagConstraints( - 0, 0, 1, 1, 1, 0, GridBagConstraints.NORTHWEST, GridBagConstraints.HORIZONTAL, - JBUI.emptyInsets(), 0, 0 - ) - ); - return left; - } + return right; + } - private String getSelectedVisibility() { - if (myParentClass != null && myParentClass.isInterface()) { - return PsiModifier.PUBLIC; + private JPanel createLeftPanel() { + final JPanel left = new JPanel(new GridBagLayout()); + myMoveToAnotherClassCb = + new JCheckBox("Move to another class", JavaRefactoringSettings.getInstance().INTRODUCE_CONSTANT_MOVE_TO_ANOTHER_CLASS); + myMoveToAnotherClassCb.setMnemonic('m'); + myMoveToAnotherClassCb.setFocusable(false); + left.add( + myMoveToAnotherClassCb, + new GridBagConstraints( + 0, 0, 1, 1, 1, 0, GridBagConstraints.NORTHWEST, GridBagConstraints.HORIZONTAL, + JBUI.emptyInsets(), 0, 0 + ) + ); + return left; } - String initialVisibility = JavaRefactoringSettings.getInstance().INTRODUCE_CONSTANT_VISIBILITY; - if (initialVisibility == null) { - initialVisibility = PsiModifier.PUBLIC; + + private String getSelectedVisibility() { + if (myParentClass != null && myParentClass.isInterface()) { + return PsiModifier.PUBLIC; + } + String initialVisibility = JavaRefactoringSettings.getInstance().INTRODUCE_CONSTANT_VISIBILITY; + if (initialVisibility == null) { + initialVisibility = PsiModifier.PUBLIC; + } + return initialVisibility; } - return initialVisibility; - } - @Override - @RequiredReadAction - @RequiredUIAccess - protected PsiVariable createFieldToStartTemplateOn(final String[] names, final PsiType psiType) { - final PsiElementFactory elementFactory = JavaPsiFacade.getElementFactory(myProject); - return myProject.getApplication().runWriteAction((Computable)() -> { + @Override + @RequiredReadAction + @RequiredUIAccess + protected PsiVariable createFieldToStartTemplateOn(final String[] names, final PsiType psiType) { + final PsiElementFactory elementFactory = JavaPsiFacade.getElementFactory(myProject); + return myProject.getApplication().runWriteAction((Computable) () -> { - PsiField field = elementFactory.createFieldFromText( - psiType.getCanonicalText() + " " + (getInputName() != null ? getInputName() : names[0]) + " = " + myInitializerText + ";", - myParentClass - ); - PsiUtil.setModifierProperty(field, PsiModifier.FINAL, true); - PsiUtil.setModifierProperty(field, PsiModifier.STATIC, true); - final String visibility = getSelectedVisibility(); - if (visibility != null) { - PsiUtil.setModifierProperty(field, visibility, true); - } - final PsiElement anchorElementIfAll = getAnchorElementIfAll(); - PsiElement finalAnchorElement; - for (finalAnchorElement = anchorElementIfAll; - finalAnchorElement != null && finalAnchorElement.getParent() != myParentClass; - finalAnchorElement = finalAnchorElement.getParent()) { - } - PsiMember anchorMember = finalAnchorElement instanceof PsiMember member ? member : null; - field = BaseExpressionToFieldHandler.ConvertToFieldRunnable.appendField( - myExpr, - BaseExpressionToFieldHandler.InitializationPlace.IN_FIELD_DECLARATION, - myParentClass, - myParentClass, - field, - anchorMember - ); - myFieldRangeStart = myEditor.getDocument().createRangeMarker(field.getTextRange()); - return field; - }); - } + PsiField field = elementFactory.createFieldFromText( + psiType.getCanonicalText() + " " + (getInputName() != null ? getInputName() : names[0]) + " = " + myInitializerText + ";", + myParentClass + ); + PsiUtil.setModifierProperty(field, PsiModifier.FINAL, true); + PsiUtil.setModifierProperty(field, PsiModifier.STATIC, true); + final String visibility = getSelectedVisibility(); + if (visibility != null) { + PsiUtil.setModifierProperty(field, visibility, true); + } + final PsiElement anchorElementIfAll = getAnchorElementIfAll(); + PsiElement finalAnchorElement; + for (finalAnchorElement = anchorElementIfAll; + finalAnchorElement != null && finalAnchorElement.getParent() != myParentClass; + finalAnchorElement = finalAnchorElement.getParent()) { + } + PsiMember anchorMember = finalAnchorElement instanceof PsiMember member ? member : null; + field = BaseExpressionToFieldHandler.ConvertToFieldRunnable.appendField( + myExpr, + BaseExpressionToFieldHandler.InitializationPlace.IN_FIELD_DECLARATION, + myParentClass, + myParentClass, + field, + anchorMember + ); + myFieldRangeStart = myEditor.getDocument().createRangeMarker(field.getTextRange()); + return field; + }); + } - @Override - protected String[] suggestNames(PsiType defaultType, String propName) { - return IntroduceConstantDialog.createNameSuggestionGenerator( - propName, - myExpr != null && myExpr.isValid() ? myExpr : null, - JavaCodeStyleManager.getInstance(myProject), null, - myParentClass - ).getSuggestedNameInfo(defaultType).names; - } + @Override + protected String[] suggestNames(PsiType defaultType, String propName) { + return IntroduceConstantDialog.createNameSuggestionGenerator( + propName, + myExpr != null && myExpr.isValid() ? myExpr : null, + JavaCodeStyleManager.getInstance(myProject), null, + myParentClass + ).getSuggestedNameInfo(defaultType).names; + } - @Override - protected VariableKind getVariableKind() { - return VariableKind.STATIC_FINAL_FIELD; - } + @Override + protected VariableKind getVariableKind() { + return VariableKind.STATIC_FINAL_FIELD; + } - @Override - public boolean isReplaceAllOccurrences() { - return myReplaceAllCb.isSelected(); - } + @Override + public boolean isReplaceAllOccurrences() { + return myReplaceAllCb.isSelected(); + } - @Override - public void setReplaceAllOccurrences(boolean allOccurrences) { - myReplaceAllCb.setSelected(allOccurrences); - } + @Override + public void setReplaceAllOccurrences(boolean allOccurrences) { + myReplaceAllCb.setSelected(allOccurrences); + } - @Override - protected void saveSettings(@Nonnull PsiVariable psiVariable) { - super.saveSettings(psiVariable); - JavaRefactoringSettings.getInstance().INTRODUCE_CONSTANT_VISIBILITY = getSelectedVisibility(); - } + @Override + protected void saveSettings(@Nonnull PsiVariable psiVariable) { + super.saveSettings(psiVariable); + JavaRefactoringSettings.getInstance().INTRODUCE_CONSTANT_VISIBILITY = getSelectedVisibility(); + } - @Override - protected boolean performRefactoring() { - JavaRefactoringSettings.getInstance().INTRODUCE_CONSTANT_MOVE_TO_ANOTHER_CLASS = myMoveToAnotherClassCb.isSelected(); - if (myMoveToAnotherClassCb.isSelected()) { - myEditor.putUserData(INTRODUCE_RESTART, true); - myProject.getApplication().invokeLater(() -> { - myEditor.putUserData(ACTIVE_INTRODUCE, InplaceIntroduceConstantPopup.this); - try { - final IntroduceConstantHandlerImpl constantHandler = new IntroduceConstantHandlerImpl(); - final PsiLocalVariable localVariable = (PsiLocalVariable) getLocalVariable(); - if (localVariable != null) { - constantHandler.invokeImpl(myProject, localVariable, myEditor); - } else { - constantHandler.invokeImpl(myProject, myExpr, myEditor); - } - } finally { - myEditor.putUserData(INTRODUCE_RESTART, false); - myEditor.putUserData(ACTIVE_INTRODUCE, null); - releaseResources(); - if (myLocalMarker != null) { - myLocalMarker.dispose(); - } - if (myExprMarker != null) { - myExprMarker.dispose(); - } + @Override + protected boolean performRefactoring() { + JavaRefactoringSettings.getInstance().INTRODUCE_CONSTANT_MOVE_TO_ANOTHER_CLASS = myMoveToAnotherClassCb.isSelected(); + if (myMoveToAnotherClassCb.isSelected()) { + myEditor.putUserData(INTRODUCE_RESTART, true); + myProject.getApplication().invokeLater(() -> { + myEditor.putUserData(ACTIVE_INTRODUCE, InplaceIntroduceConstantPopup.this); + try { + final IntroduceConstantHandlerImpl constantHandler = new IntroduceConstantHandlerImpl(); + final PsiLocalVariable localVariable = (PsiLocalVariable) getLocalVariable(); + if (localVariable != null) { + constantHandler.invokeImpl(myProject, localVariable, myEditor); + } + else { + constantHandler.invokeImpl(myProject, myExpr, myEditor); + } + } + finally { + myEditor.putUserData(INTRODUCE_RESTART, false); + myEditor.putUserData(ACTIVE_INTRODUCE, null); + releaseResources(); + if (myLocalMarker != null) { + myLocalMarker.dispose(); + } + if (myExprMarker != null) { + myExprMarker.dispose(); + } + } + }); + return false; } - }); - return false; + return super.performRefactoring(); } - return super.performRefactoring(); - } - @Override - protected boolean startsOnTheSameElement(RefactoringActionHandler handler, PsiElement element) { - return super.startsOnTheSameElement(handler, element) && handler instanceof IntroduceConstantHandlerImpl; - } + @Override + protected boolean startsOnTheSameElement(RefactoringActionHandler handler, PsiElement element) { + return super.startsOnTheSameElement(handler, element) && handler instanceof IntroduceConstantHandlerImpl; + } - @Override - protected void performIntroduce() { - final BaseExpressionToFieldHandler.Settings settings = - new BaseExpressionToFieldHandler.Settings(getInputName(), - getExpr(), - getOccurrences(), - isReplaceAllOccurrences(), true, - true, - BaseExpressionToFieldHandler.InitializationPlace.IN_FIELD_DECLARATION, - getSelectedVisibility(), (PsiLocalVariable) getLocalVariable(), - getType(), - true, - myParentClass, false, false); - new WriteCommandAction(myProject, getCommandName(), getCommandName()) { - @Override - protected void run(Result result) throws Throwable { - if (getLocalVariable() != null) { - final LocalToFieldHandler.IntroduceFieldRunnable fieldRunnable = - new LocalToFieldHandler.IntroduceFieldRunnable(false, (PsiLocalVariable) getLocalVariable(), myParentClass, settings, true, - myOccurrences); - fieldRunnable.run(); - } else { - final BaseExpressionToFieldHandler.ConvertToFieldRunnable convertToFieldRunnable = - new BaseExpressionToFieldHandler.ConvertToFieldRunnable(myExpr, settings, settings.getForcedType(), - myOccurrences, myOccurrenceManager, - getAnchorElementIfAll(), getAnchorElement(), myEditor, myParentClass); - convertToFieldRunnable.run(); - } - } - }.execute(); - } + @Override + protected void performIntroduce() { + final BaseExpressionToFieldHandler.Settings settings = + new BaseExpressionToFieldHandler.Settings(getInputName(), + getExpr(), + getOccurrences(), + isReplaceAllOccurrences(), true, + true, + BaseExpressionToFieldHandler.InitializationPlace.IN_FIELD_DECLARATION, + getSelectedVisibility(), (PsiLocalVariable) getLocalVariable(), + getType(), + true, + myParentClass, false, false + ); + new WriteCommandAction(myProject, getCommandName(), getCommandName()) { + @Override + protected void run(Result result) throws Throwable { + if (getLocalVariable() != null) { + final LocalToFieldHandler.IntroduceFieldRunnable fieldRunnable = + new LocalToFieldHandler.IntroduceFieldRunnable( + false, + (PsiLocalVariable) getLocalVariable(), + myParentClass, + settings, + true, + myOccurrences + ); + fieldRunnable.run(); + } + else { + final BaseExpressionToFieldHandler.ConvertToFieldRunnable convertToFieldRunnable = + new BaseExpressionToFieldHandler.ConvertToFieldRunnable(myExpr, settings, settings.getForcedType(), + myOccurrences, myOccurrenceManager, + getAnchorElementIfAll(), getAnchorElement(), myEditor, myParentClass + ); + convertToFieldRunnable.run(); + } + } + }.execute(); + } - @Override - protected JComponent getComponent() { - myReplaceAllCb.addItemListener(e -> restartInplaceIntroduceTemplate()); + @Override + protected JComponent getComponent() { + myReplaceAllCb.addItemListener(e -> restartInplaceIntroduceTemplate()); - return myWholePanel; - } + return myWholePanel; + } - @Override - protected String getActionName() { - return "IntroduceConstant"; - } + @Override + protected String getActionName() { + return "IntroduceConstant"; + } } diff --git a/plugin/src/main/java/com/intellij/java/impl/refactoring/introduceField/IntroduceConstantDialog.java b/plugin/src/main/java/com/intellij/java/impl/refactoring/introduceField/IntroduceConstantDialog.java index 26dd40a65f..e01220cefa 100644 --- a/plugin/src/main/java/com/intellij/java/impl/refactoring/introduceField/IntroduceConstantDialog.java +++ b/plugin/src/main/java/com/intellij/java/impl/refactoring/introduceField/IntroduceConstantDialog.java @@ -43,6 +43,7 @@ import consulo.language.psi.scope.GlobalSearchScope; import consulo.language.psi.util.PsiTreeUtil; import consulo.language.util.IncorrectOperationException; +import consulo.localize.LocalizeValue; import consulo.logging.Logger; import consulo.platform.base.icon.PlatformIconGroup; import consulo.project.Project; @@ -70,426 +71,452 @@ import java.util.Set; class IntroduceConstantDialog extends DialogWrapper { - private static final Logger LOG = Logger.getInstance(IntroduceConstantDialog.class); - @NonNls private static final String RECENTS_KEY = "IntroduceConstantDialog.RECENTS_KEY"; - @NonNls protected static final String NONNLS_SELECTED_PROPERTY = "INTRODUCE_CONSTANT_NONNLS"; - - private final Project myProject; - private final PsiClass myParentClass; - private final PsiExpression myInitializerExpression; - private final PsiLocalVariable myLocalVariable; - private final boolean myInvokedOnDeclaration; - private final PsiExpression[] myOccurrences; - private final String myEnteredName; - private final int myOccurrencesCount; - private PsiClass myTargetClass; - private final TypeSelectorManager myTypeSelectorManager; - - private NameSuggestionsField myNameField; - private JCheckBox myCbReplaceAll; - - private TypeSelector myTypeSelector; - private StateRestoringCheckBox myCbDeleteVariable; - private final JavaCodeStyleManager myCodeStyleManager; - private ReferenceEditorComboWithBrowseButton myTfTargetClassName; - private BaseExpressionToFieldHandler.TargetDestination myDestinationClass; - private JPanel myTypePanel; - private JPanel myTargetClassNamePanel; - private JPanel myPanel; - private JLabel myTypeLabel; - private JPanel myNameSuggestionPanel; - private JLabel myNameSuggestionLabel; - private JLabel myTargetClassNameLabel; - private JCheckBox myCbNonNls; - private JPanel myVisibilityPanel; - private final JavaVisibilityPanel myVPanel; - private final JCheckBox myIntroduceEnumConstantCb = new JCheckBox(RefactoringLocalize.introduceConstantEnumCb().get(), true); - - IntroduceConstantDialog( - Project project, - PsiClass parentClass, - PsiExpression initializerExpression, - PsiLocalVariable localVariable, - boolean isInvokedOnDeclaration, - PsiExpression[] occurrences, - PsiClass targetClass, - TypeSelectorManager typeSelectorManager, String enteredName - ) { - super(project, true); - myProject = project; - myParentClass = parentClass; - myInitializerExpression = initializerExpression; - myLocalVariable = localVariable; - myInvokedOnDeclaration = isInvokedOnDeclaration; - myOccurrences = occurrences; - myEnteredName = enteredName; - myOccurrencesCount = occurrences.length; - myTargetClass = targetClass; - myTypeSelectorManager = typeSelectorManager; - myDestinationClass = null; - - setTitle(IntroduceConstantHandlerImpl.REFACTORING_NAME); - myCodeStyleManager = JavaCodeStyleManager.getInstance(myProject); - myVPanel = new JavaVisibilityPanel(false, true); - myVisibilityPanel.add(TargetAWT.to(myVPanel.getComponent()), BorderLayout.CENTER); - init(); - - myVPanel.setVisibility(JavaRefactoringSettings.getInstance().INTRODUCE_CONSTANT_VISIBILITY); - myIntroduceEnumConstantCb.setEnabled(isSuitableForEnumConstant()); - updateVisibilityPanel(); - updateButtons(); - } - - public String getEnteredName() { - return myNameField.getEnteredName(); - } - - private String getTargetClassName() { - return myTfTargetClassName.getText().trim(); - } - - public BaseExpressionToFieldHandler.TargetDestination getDestinationClass () { - return myDestinationClass; - } - - public boolean introduceEnumConstant() { - return myIntroduceEnumConstantCb.isEnabled() && myIntroduceEnumConstantCb.isSelected(); - } - - public String getFieldVisibility() { - return myVPanel.getVisibility(); - } - - public boolean isReplaceAllOccurrences() { - return myOccurrencesCount > 1 && myCbReplaceAll.isSelected(); - } - - public PsiType getSelectedType() { - return myTypeSelector.getSelectedType(); - } - - @Nonnull - protected Action[] createActions() { - return new Action[]{getOKAction(), getCancelAction(), getHelpAction()}; - } - - protected void doHelpAction() { - HelpManager.getInstance().invokeHelp(HelpID.INTRODUCE_CONSTANT); - } - - protected JComponent createNorthPanel() { - myTypeSelector = myTypeSelectorManager.getTypeSelector(); - myTypePanel.setLayout(new BorderLayout()); - myTypePanel.add(myTypeSelector.getComponent(), BorderLayout.CENTER); - if (myTypeSelector.getFocusableComponent() != null) { - myTypeLabel.setLabelFor(myTypeSelector.getFocusableComponent()); + private static final Logger LOG = Logger.getInstance(IntroduceConstantDialog.class); + @NonNls + private static final String RECENTS_KEY = "IntroduceConstantDialog.RECENTS_KEY"; + @NonNls + protected static final String NONNLS_SELECTED_PROPERTY = "INTRODUCE_CONSTANT_NONNLS"; + + private final Project myProject; + private final PsiClass myParentClass; + private final PsiExpression myInitializerExpression; + private final PsiLocalVariable myLocalVariable; + private final boolean myInvokedOnDeclaration; + private final PsiExpression[] myOccurrences; + private final String myEnteredName; + private final int myOccurrencesCount; + private PsiClass myTargetClass; + private final TypeSelectorManager myTypeSelectorManager; + + private NameSuggestionsField myNameField; + private JCheckBox myCbReplaceAll; + + private TypeSelector myTypeSelector; + private StateRestoringCheckBox myCbDeleteVariable; + private final JavaCodeStyleManager myCodeStyleManager; + private ReferenceEditorComboWithBrowseButton myTfTargetClassName; + private BaseExpressionToFieldHandler.TargetDestination myDestinationClass; + private JPanel myTypePanel; + private JPanel myTargetClassNamePanel; + private JPanel myPanel; + private JLabel myTypeLabel; + private JPanel myNameSuggestionPanel; + private JLabel myNameSuggestionLabel; + private JLabel myTargetClassNameLabel; + private JCheckBox myCbNonNls; + private JPanel myVisibilityPanel; + private final JavaVisibilityPanel myVPanel; + private final JCheckBox myIntroduceEnumConstantCb = new JCheckBox(RefactoringLocalize.introduceConstantEnumCb().get(), true); + + IntroduceConstantDialog( + Project project, + PsiClass parentClass, + PsiExpression initializerExpression, + PsiLocalVariable localVariable, + boolean isInvokedOnDeclaration, + PsiExpression[] occurrences, + PsiClass targetClass, + TypeSelectorManager typeSelectorManager, String enteredName + ) { + super(project, true); + myProject = project; + myParentClass = parentClass; + myInitializerExpression = initializerExpression; + myLocalVariable = localVariable; + myInvokedOnDeclaration = isInvokedOnDeclaration; + myOccurrences = occurrences; + myEnteredName = enteredName; + myOccurrencesCount = occurrences.length; + myTargetClass = targetClass; + myTypeSelectorManager = typeSelectorManager; + myDestinationClass = null; + + setTitle(IntroduceConstantHandlerImpl.REFACTORING_NAME); + myCodeStyleManager = JavaCodeStyleManager.getInstance(myProject); + myVPanel = new JavaVisibilityPanel(false, true); + myVisibilityPanel.add(TargetAWT.to(myVPanel.getComponent()), BorderLayout.CENTER); + init(); + + myVPanel.setVisibility(JavaRefactoringSettings.getInstance().INTRODUCE_CONSTANT_VISIBILITY); + myIntroduceEnumConstantCb.setEnabled(isSuitableForEnumConstant()); + updateVisibilityPanel(); + updateButtons(); } - myNameField = new NameSuggestionsField(myProject); - myNameSuggestionPanel.setLayout(new BorderLayout()); - myNameField.addDataChangedListener(this::updateButtons); - myNameSuggestionPanel.add(myNameField.getComponent(), BorderLayout.CENTER); - myNameSuggestionLabel.setLabelFor(myNameField.getFocusableComponent()); - - Set possibleClassNames = new LinkedHashSet<>(); - for (final PsiExpression occurrence : myOccurrences) { - final PsiClass parentClass = new IntroduceConstantHandlerImpl().getParentClass(occurrence); - if (parentClass != null && parentClass.getQualifiedName() != null) { - possibleClassNames.add(parentClass.getQualifiedName()); - } + public String getEnteredName() { + return myNameField.getEnteredName(); } - myTfTargetClassName = - new ReferenceEditorComboWithBrowseButton(new ChooseClassAction(), "", myProject, true, RECENTS_KEY); - myTfTargetClassName.setButtonIcon(PlatformIconGroup.nodesClass()); - myTargetClassNamePanel.setLayout(new BorderLayout()); - myTargetClassNamePanel.add(myTfTargetClassName, BorderLayout.CENTER); - myTargetClassNameLabel.setLabelFor(myTfTargetClassName); - for (String possibleClassName : possibleClassNames) { - myTfTargetClassName.prependItem(possibleClassName); + + private String getTargetClassName() { + return myTfTargetClassName.getText().trim(); } - myTfTargetClassName.getChildComponent().addDocumentListener(new DocumentAdapter() { - public void documentChanged(DocumentEvent e) { - targetClassChanged(); - enableEnumDependant(introduceEnumConstant()); - } - }); - myIntroduceEnumConstantCb.addActionListener(e -> enableEnumDependant(introduceEnumConstant())); - final JPanel enumPanel = new JPanel(new BorderLayout()); - enumPanel.add(myIntroduceEnumConstantCb, BorderLayout.EAST); - myTargetClassNamePanel.add(enumPanel, BorderLayout.SOUTH); - - final String propertyName; - if (myLocalVariable != null) { - propertyName = myCodeStyleManager.variableNameToPropertyName(myLocalVariable.getName(), VariableKind.LOCAL_VARIABLE); + + public BaseExpressionToFieldHandler.TargetDestination getDestinationClass() { + return myDestinationClass; } - else { - propertyName = null; + + public boolean introduceEnumConstant() { + return myIntroduceEnumConstantCb.isEnabled() && myIntroduceEnumConstantCb.isSelected(); } - final NameSuggestionsManager nameSuggestionsManager = - new NameSuggestionsManager(myTypeSelector, myNameField, createNameSuggestionGenerator(propertyName, myInitializerExpression, - myCodeStyleManager, myEnteredName, myParentClass)); - - nameSuggestionsManager.setLabelsFor(myTypeLabel, myNameSuggestionLabel); - ////////// - if (myOccurrencesCount > 1) { - myCbReplaceAll.addItemListener(e -> { - updateTypeSelector(); - myNameField.requestFocusInWindow(); - }); - myCbReplaceAll.setText(RefactoringLocalize.replaceAllOccurences(myOccurrencesCount).get()); + public String getFieldVisibility() { + return myVPanel.getVisibility(); } - else { - myCbReplaceAll.setVisible(false); + + public boolean isReplaceAllOccurrences() { + return myOccurrencesCount > 1 && myCbReplaceAll.isSelected(); } - if (myLocalVariable != null) { - if (myInvokedOnDeclaration) { - myCbDeleteVariable.setEnabled(false); - myCbDeleteVariable.setSelected(true); - } - else if (myCbReplaceAll != null) { - updateCbDeleteVariable(); - myCbReplaceAll.addItemListener(e -> updateCbDeleteVariable()); - } + public PsiType getSelectedType() { + return myTypeSelector.getSelectedType(); } - else { - myCbDeleteVariable.setVisible(false); + + @Nonnull + protected Action[] createActions() { + return new Action[]{getOKAction(), getCancelAction(), getHelpAction()}; } - final PsiManager psiManager = PsiManager.getInstance(myProject); - if ( - ( - myTypeSelectorManager.isSuggestedType(CommonClassNames.JAVA_LANG_STRING) - || (myLocalVariable != null && AnnotationUtil.isAnnotated(myLocalVariable, AnnotationUtil.NON_NLS, false, false)) - ) - && PsiUtil.isLanguageLevel5OrHigher(myParentClass) - && JavaPsiFacade.getInstance(psiManager.getProject()).findClass(AnnotationUtil.NON_NLS, myParentClass.getResolveScope()) != null - ) { - final PropertiesComponent component = ProjectPropertiesComponent.getInstance(myProject); - myCbNonNls.setSelected(component.isTrueValue(NONNLS_SELECTED_PROPERTY)); - myCbNonNls.addItemListener(e -> component.setValue(NONNLS_SELECTED_PROPERTY, Boolean.toString(myCbNonNls.isSelected()))); - } else { - myCbNonNls.setVisible(false); + protected void doHelpAction() { + HelpManager.getInstance().invokeHelp(HelpID.INTRODUCE_CONSTANT); } - updateTypeSelector(); + protected JComponent createNorthPanel() { + myTypeSelector = myTypeSelectorManager.getTypeSelector(); + myTypePanel.setLayout(new BorderLayout()); + myTypePanel.add(myTypeSelector.getComponent(), BorderLayout.CENTER); + if (myTypeSelector.getFocusableComponent() != null) { + myTypeLabel.setLabelFor(myTypeSelector.getFocusableComponent()); + } + + myNameField = new NameSuggestionsField(myProject); + myNameSuggestionPanel.setLayout(new BorderLayout()); + myNameField.addDataChangedListener(this::updateButtons); + myNameSuggestionPanel.add(myNameField.getComponent(), BorderLayout.CENTER); + myNameSuggestionLabel.setLabelFor(myNameField.getFocusableComponent()); + + Set possibleClassNames = new LinkedHashSet<>(); + for (final PsiExpression occurrence : myOccurrences) { + final PsiClass parentClass = new IntroduceConstantHandlerImpl().getParentClass(occurrence); + if (parentClass != null && parentClass.getQualifiedName() != null) { + possibleClassNames.add(parentClass.getQualifiedName()); + } + } + myTfTargetClassName = + new ReferenceEditorComboWithBrowseButton(new ChooseClassAction(), "", myProject, true, RECENTS_KEY); + myTfTargetClassName.setButtonIcon(PlatformIconGroup.nodesClass()); + myTargetClassNamePanel.setLayout(new BorderLayout()); + myTargetClassNamePanel.add(myTfTargetClassName, BorderLayout.CENTER); + myTargetClassNameLabel.setLabelFor(myTfTargetClassName); + for (String possibleClassName : possibleClassNames) { + myTfTargetClassName.prependItem(possibleClassName); + } + myTfTargetClassName.getChildComponent().addDocumentListener(new DocumentAdapter() { + public void documentChanged(DocumentEvent e) { + targetClassChanged(); + enableEnumDependant(introduceEnumConstant()); + } + }); + myIntroduceEnumConstantCb.addActionListener(e -> enableEnumDependant(introduceEnumConstant())); + final JPanel enumPanel = new JPanel(new BorderLayout()); + enumPanel.add(myIntroduceEnumConstantCb, BorderLayout.EAST); + myTargetClassNamePanel.add(enumPanel, BorderLayout.SOUTH); + + final String propertyName; + if (myLocalVariable != null) { + propertyName = myCodeStyleManager.variableNameToPropertyName(myLocalVariable.getName(), VariableKind.LOCAL_VARIABLE); + } + else { + propertyName = null; + } + final NameSuggestionsManager nameSuggestionsManager = + new NameSuggestionsManager(myTypeSelector, myNameField, createNameSuggestionGenerator(propertyName, myInitializerExpression, + myCodeStyleManager, myEnteredName, myParentClass + )); + + nameSuggestionsManager.setLabelsFor(myTypeLabel, myNameSuggestionLabel); + ////////// + if (myOccurrencesCount > 1) { + myCbReplaceAll.addItemListener(e -> { + updateTypeSelector(); + + myNameField.requestFocusInWindow(); + }); + myCbReplaceAll.setText(RefactoringLocalize.replaceAllOccurences(myOccurrencesCount).get()); + } + else { + myCbReplaceAll.setVisible(false); + } + + if (myLocalVariable != null) { + if (myInvokedOnDeclaration) { + myCbDeleteVariable.setEnabled(false); + myCbDeleteVariable.setSelected(true); + } + else if (myCbReplaceAll != null) { + updateCbDeleteVariable(); + myCbReplaceAll.addItemListener(e -> updateCbDeleteVariable()); + } + } + else { + myCbDeleteVariable.setVisible(false); + } - enableEnumDependant(introduceEnumConstant()); - return myPanel; - } + final PsiManager psiManager = PsiManager.getInstance(myProject); + if ( + ( + myTypeSelectorManager.isSuggestedType(CommonClassNames.JAVA_LANG_STRING) + || (myLocalVariable != null && AnnotationUtil.isAnnotated(myLocalVariable, AnnotationUtil.NON_NLS, false, false)) + ) + && PsiUtil.isLanguageLevel5OrHigher(myParentClass) + && JavaPsiFacade.getInstance(psiManager.getProject()) + .findClass(AnnotationUtil.NON_NLS, myParentClass.getResolveScope()) != null + ) { + final PropertiesComponent component = ProjectPropertiesComponent.getInstance(myProject); + myCbNonNls.setSelected(component.isTrueValue(NONNLS_SELECTED_PROPERTY)); + myCbNonNls.addItemListener(e -> component.setValue(NONNLS_SELECTED_PROPERTY, Boolean.toString(myCbNonNls.isSelected()))); + } + else { + myCbNonNls.setVisible(false); + } + + updateTypeSelector(); - public void setReplaceAllOccurrences(boolean replaceAllOccurrences) { - if (myCbReplaceAll != null) { - myCbReplaceAll.setSelected(replaceAllOccurrences); + enableEnumDependant(introduceEnumConstant()); + return myPanel; } - } - - protected static NameSuggestionsGenerator createNameSuggestionGenerator( - final String propertyName, - final PsiExpression psiExpression, - final JavaCodeStyleManager codeStyleManager, - final String enteredName, final PsiClass parentClass - ) { - return type -> { - SuggestedNameInfo nameInfo = - codeStyleManager.suggestVariableName(VariableKind.STATIC_FINAL_FIELD, propertyName, psiExpression, type); - if (psiExpression != null) { - String[] names = nameInfo.names; - for (int i = 0, namesLength = names.length; i < namesLength; i++) { - String name = names[i]; - if (parentClass.findFieldByName(name, false) != null) { - names[i] = codeStyleManager.suggestUniqueVariableName(name, psiExpression, true); - } + + public void setReplaceAllOccurrences(boolean replaceAllOccurrences) { + if (myCbReplaceAll != null) { + myCbReplaceAll.setSelected(replaceAllOccurrences); } - } - final String[] strings = AbstractJavaInplaceIntroducer.appendUnresolvedExprName( - JavaCompletionUtil.completeVariableNameForRefactoring(codeStyleManager, type, VariableKind.LOCAL_VARIABLE, nameInfo), - psiExpression - ); - return new SuggestedNameInfo.Delegate(enteredName != null ? ArrayUtil.mergeArrays(new String[]{enteredName}, strings): strings, nameInfo); - }; - } - - private void updateButtons() { - setOKActionEnabled(PsiNameHelper.getInstance(myProject).isIdentifier(getEnteredName())); - } - - private void targetClassChanged() { - final String targetClassName = getTargetClassName(); - myTargetClass = JavaPsiFacade.getInstance(myProject).findClass(targetClassName, GlobalSearchScope.projectScope(myProject)); - updateVisibilityPanel(); - myIntroduceEnumConstantCb.setEnabled(isSuitableForEnumConstant()); - } - - private boolean isSuitableForEnumConstant() { - return EnumConstantsUtil.isSuitableForEnumConstant(getSelectedType(), myTargetClass) && PsiTreeUtil - .getParentOfType(myInitializerExpression, - PsiEnumConstant.class) == null; - } - - private void enableEnumDependant(boolean enable) { - if (enable) { - myVPanel.disableAllButPublic(); - } else { - updateVisibilityPanel(); } - myCbNonNls.setEnabled(!enable); - } - protected JComponent createCenterPanel() { - return new JPanel(); - } + protected static NameSuggestionsGenerator createNameSuggestionGenerator( + final String propertyName, + final PsiExpression psiExpression, + final JavaCodeStyleManager codeStyleManager, + final String enteredName, final PsiClass parentClass + ) { + return type -> { + SuggestedNameInfo nameInfo = + codeStyleManager.suggestVariableName(VariableKind.STATIC_FINAL_FIELD, propertyName, psiExpression, type); + if (psiExpression != null) { + String[] names = nameInfo.names; + for (int i = 0, namesLength = names.length; i < namesLength; i++) { + String name = names[i]; + if (parentClass.findFieldByName(name, false) != null) { + names[i] = codeStyleManager.suggestUniqueVariableName(name, psiExpression, true); + } + } + } + final String[] strings = AbstractJavaInplaceIntroducer.appendUnresolvedExprName( + JavaCompletionUtil.completeVariableNameForRefactoring(codeStyleManager, type, VariableKind.LOCAL_VARIABLE, nameInfo), + psiExpression + ); + return new SuggestedNameInfo.Delegate( + enteredName != null ? ArrayUtil.mergeArrays(new String[]{enteredName}, strings) : strings, + nameInfo + ); + }; + } - public boolean isDeleteVariable() { - return myInvokedOnDeclaration || myCbDeleteVariable != null && myCbDeleteVariable.isSelected(); - } + private void updateButtons() { + setOKActionEnabled(PsiNameHelper.getInstance(myProject).isIdentifier(getEnteredName())); + } - public boolean isAnnotateAsNonNls() { - return myCbNonNls != null && myCbNonNls.isSelected(); - } + private void targetClassChanged() { + final String targetClassName = getTargetClassName(); + myTargetClass = JavaPsiFacade.getInstance(myProject).findClass(targetClassName, GlobalSearchScope.projectScope(myProject)); + updateVisibilityPanel(); + myIntroduceEnumConstantCb.setEnabled(isSuitableForEnumConstant()); + } - private void updateCbDeleteVariable() { - if (!myCbReplaceAll.isSelected()) { - myCbDeleteVariable.makeUnselectable(false); + private boolean isSuitableForEnumConstant() { + return EnumConstantsUtil.isSuitableForEnumConstant(getSelectedType(), myTargetClass) && PsiTreeUtil + .getParentOfType( + myInitializerExpression, + PsiEnumConstant.class + ) == null; } - else { - myCbDeleteVariable.makeSelectable(); + + private void enableEnumDependant(boolean enable) { + if (enable) { + myVPanel.disableAllButPublic(); + } + else { + updateVisibilityPanel(); + } + myCbNonNls.setEnabled(!enable); } - } - private void updateTypeSelector() { - if (myCbReplaceAll != null) { - myTypeSelectorManager.setAllOccurrences(myCbReplaceAll.isSelected()); + protected JComponent createCenterPanel() { + return new JPanel(); } - else { - myTypeSelectorManager.setAllOccurrences(false); + + public boolean isDeleteVariable() { + return myInvokedOnDeclaration || myCbDeleteVariable != null && myCbDeleteVariable.isSelected(); } - } - private void updateVisibilityPanel() { - if (myTargetClass != null && myTargetClass.isInterface()) { - myVPanel.disableAllButPublic(); + public boolean isAnnotateAsNonNls() { + return myCbNonNls != null && myCbNonNls.isSelected(); } - else { - UIUtil.setEnabled(myVisibilityPanel, true, true); - // exclude all modifiers not visible from all occurences - final Set visible = new HashSet<>(); - visible.add(PsiModifier.PRIVATE); - visible.add(PsiModifier.PROTECTED); - visible.add(PsiModifier.PACKAGE_LOCAL); - visible.add(PsiModifier.PUBLIC); - for (PsiExpression occurrence : myOccurrences) { - final PsiManager psiManager = PsiManager.getInstance(myProject); - for (Iterator iterator = visible.iterator(); iterator.hasNext();) { - String modifier = iterator.next(); - - try { - final String modifierText = PsiModifier.PACKAGE_LOCAL.equals(modifier) ? "" : modifier + " "; - final PsiField field = JavaPsiFacade.getInstance(psiManager.getProject()).getElementFactory().createFieldFromText(modifierText + "int xxx;", myTargetClass); - if (!JavaResolveUtil.isAccessible(field, myTargetClass, field.getModifierList(), occurrence, myTargetClass, null)) { - iterator.remove(); - } - } - catch (IncorrectOperationException e) { - LOG.error(e); - } + + private void updateCbDeleteVariable() { + if (!myCbReplaceAll.isSelected()) { + myCbDeleteVariable.makeUnselectable(false); } - } - if (!visible.contains(getFieldVisibility())) { - if (visible.contains(PsiModifier.PUBLIC)) myVPanel.setVisibility(PsiModifier.PUBLIC); - if (visible.contains(PsiModifier.PACKAGE_LOCAL)) myVPanel.setVisibility(PsiModifier.PACKAGE_LOCAL); - if (visible.contains(PsiModifier.PROTECTED)) myVPanel.setVisibility(PsiModifier.PROTECTED); - if (visible.contains(PsiModifier.PRIVATE)) myVPanel.setVisibility(PsiModifier.PRIVATE); - } - } - } - - @RequiredUIAccess - protected void doOKAction() { - final String targetClassName = getTargetClassName(); - PsiClass newClass = myParentClass; - - if (!"".equals (targetClassName) && !Comparing.strEqual(targetClassName, myParentClass.getQualifiedName())) { - newClass = JavaPsiFacade.getInstance(myProject).findClass(targetClassName, GlobalSearchScope.projectScope(myProject)); - if (newClass == null) { - if (Messages.showOkCancelDialog( - myProject, - RefactoringLocalize.classDoesNotExistInTheProject().get(), - IntroduceConstantHandlerImpl.REFACTORING_NAME, - UIUtil.getErrorIcon() - ) != OK_EXIT_CODE) { - return; + else { + myCbDeleteVariable.makeSelectable(); } - myDestinationClass = new BaseExpressionToFieldHandler.TargetDestination(targetClassName, myParentClass); - } else { - myDestinationClass = new BaseExpressionToFieldHandler.TargetDestination(newClass); - } } - String fieldName = getEnteredName(); - String errorString = null; - if ("".equals(fieldName)) { - errorString = RefactoringLocalize.noFieldNameSpecified().get(); - } else if (!PsiNameHelper.getInstance(myProject).isIdentifier(fieldName)) { - errorString = RefactoringMessageUtil.getIncorrectIdentifierMessage(fieldName); - } else if (newClass != null && !myParentClass.getLanguage().equals(newClass.getLanguage())) { - errorString = RefactoringLocalize.moveToDifferentLanguage(UsageViewUtil.getType(myParentClass), - myParentClass.getQualifiedName(), - newClass.getQualifiedName() - ).get(); + private void updateTypeSelector() { + if (myCbReplaceAll != null) { + myTypeSelectorManager.setAllOccurrences(myCbReplaceAll.isSelected()); + } + else { + myTypeSelectorManager.setAllOccurrences(false); + } } - if (errorString != null) { - CommonRefactoringUtil.showErrorMessage( - IntroduceFieldHandler.REFACTORING_NAME, - errorString, - HelpID.INTRODUCE_FIELD, - myProject); - return; + + private void updateVisibilityPanel() { + if (myTargetClass != null && myTargetClass.isInterface()) { + myVPanel.disableAllButPublic(); + } + else { + UIUtil.setEnabled(myVisibilityPanel, true, true); + // exclude all modifiers not visible from all occurences + final Set visible = new HashSet<>(); + visible.add(PsiModifier.PRIVATE); + visible.add(PsiModifier.PROTECTED); + visible.add(PsiModifier.PACKAGE_LOCAL); + visible.add(PsiModifier.PUBLIC); + for (PsiExpression occurrence : myOccurrences) { + final PsiManager psiManager = PsiManager.getInstance(myProject); + for (Iterator iterator = visible.iterator(); iterator.hasNext(); ) { + String modifier = iterator.next(); + + try { + final String modifierText = PsiModifier.PACKAGE_LOCAL.equals(modifier) ? "" : modifier + " "; + final PsiField field = JavaPsiFacade.getInstance(psiManager.getProject()) + .getElementFactory() + .createFieldFromText(modifierText + "int xxx;", myTargetClass); + if (!JavaResolveUtil.isAccessible(field, myTargetClass, field.getModifierList(), occurrence, myTargetClass, null)) { + iterator.remove(); + } + } + catch (IncorrectOperationException e) { + LOG.error(e); + } + } + } + if (!visible.contains(getFieldVisibility())) { + if (visible.contains(PsiModifier.PUBLIC)) { + myVPanel.setVisibility(PsiModifier.PUBLIC); + } + if (visible.contains(PsiModifier.PACKAGE_LOCAL)) { + myVPanel.setVisibility(PsiModifier.PACKAGE_LOCAL); + } + if (visible.contains(PsiModifier.PROTECTED)) { + myVPanel.setVisibility(PsiModifier.PROTECTED); + } + if (visible.contains(PsiModifier.PRIVATE)) { + myVPanel.setVisibility(PsiModifier.PRIVATE); + } + } + } } - if (newClass != null) { - PsiField oldField = newClass.findFieldByName(fieldName, true); - - if (oldField != null) { - int answer = Messages.showYesNoDialog( - myProject, - RefactoringLocalize.fieldExists(fieldName, oldField.getContainingClass().getQualifiedName()).get(), - IntroduceFieldHandler.REFACTORING_NAME, - UIUtil.getWarningIcon() - ); - if (answer != 0) { - return; + + @RequiredUIAccess + protected void doOKAction() { + final String targetClassName = getTargetClassName(); + PsiClass newClass = myParentClass; + + if (!"".equals(targetClassName) && !Comparing.strEqual(targetClassName, myParentClass.getQualifiedName())) { + newClass = JavaPsiFacade.getInstance(myProject).findClass(targetClassName, GlobalSearchScope.projectScope(myProject)); + if (newClass == null) { + if (Messages.showOkCancelDialog( + myProject, + RefactoringLocalize.classDoesNotExistInTheProject().get(), + IntroduceConstantHandlerImpl.REFACTORING_NAME.get(), + UIUtil.getErrorIcon() + ) != OK_EXIT_CODE) { + return; + } + myDestinationClass = new BaseExpressionToFieldHandler.TargetDestination(targetClassName, myParentClass); + } + else { + myDestinationClass = new BaseExpressionToFieldHandler.TargetDestination(newClass); + } + } + + String fieldName = getEnteredName(); + LocalizeValue errorString = LocalizeValue.empty(); + if ("".equals(fieldName)) { + errorString = RefactoringLocalize.noFieldNameSpecified(); } - } + else if (!PsiNameHelper.getInstance(myProject).isIdentifier(fieldName)) { + errorString = LocalizeValue.localizeTODO(RefactoringMessageUtil.getIncorrectIdentifierMessage(fieldName)); + } + else if (newClass != null && !myParentClass.getLanguage().equals(newClass.getLanguage())) { + errorString = RefactoringLocalize.moveToDifferentLanguage( + UsageViewUtil.getType(myParentClass), + myParentClass.getQualifiedName(), + newClass.getQualifiedName() + ); + } + if (errorString != LocalizeValue.empty()) { + CommonRefactoringUtil.showErrorMessage( + IntroduceFieldHandler.REFACTORING_NAME, + errorString, + HelpID.INTRODUCE_FIELD, + myProject + ); + return; + } + if (newClass != null) { + PsiField oldField = newClass.findFieldByName(fieldName, true); + + if (oldField != null) { + int answer = Messages.showYesNoDialog( + myProject, + RefactoringLocalize.fieldExists(fieldName, oldField.getContainingClass().getQualifiedName()).get(), + IntroduceFieldHandler.REFACTORING_NAME.get(), + UIUtil.getWarningIcon() + ); + if (answer != 0) { + return; + } + } + } + + JavaRefactoringSettings.getInstance().INTRODUCE_CONSTANT_VISIBILITY = getFieldVisibility(); + + RecentsManager.getInstance(myProject).registerRecentEntry(RECENTS_KEY, targetClassName); + super.doOKAction(); + } + + @RequiredUIAccess + public JComponent getPreferredFocusedComponent() { + return myNameField.getFocusableComponent(); } - JavaRefactoringSettings.getInstance().INTRODUCE_CONSTANT_VISIBILITY = getFieldVisibility(); - - RecentsManager.getInstance(myProject).registerRecentEntry(RECENTS_KEY, targetClassName); - super.doOKAction(); - } - - @RequiredUIAccess - public JComponent getPreferredFocusedComponent() { - return myNameField.getFocusableComponent(); - } - - private class ChooseClassAction implements ActionListener { - public void actionPerformed(ActionEvent e) { - TreeClassChooser chooser = TreeClassChooserFactory.getInstance(myProject).createWithInnerClassesScopeChooser( - RefactoringLocalize.chooseDestinationClass().get(), - GlobalSearchScope.projectScope(myProject), - aClass -> aClass.getParent() instanceof PsiJavaFile || aClass.hasModifierProperty(PsiModifier.STATIC), - null - ); - if (myTargetClass != null) { - chooser.selectDirectory(myTargetClass.getContainingFile().getContainingDirectory()); - } - chooser.showDialog(); - PsiClass aClass = chooser.getSelected(); - if (aClass != null) { - myTfTargetClassName.setText(aClass.getQualifiedName()); - } + private class ChooseClassAction implements ActionListener { + public void actionPerformed(ActionEvent e) { + TreeClassChooser chooser = TreeClassChooserFactory.getInstance(myProject).createWithInnerClassesScopeChooser( + RefactoringLocalize.chooseDestinationClass().get(), + GlobalSearchScope.projectScope(myProject), + aClass -> aClass.getParent() instanceof PsiJavaFile || aClass.hasModifierProperty(PsiModifier.STATIC), + null + ); + if (myTargetClass != null) { + chooser.selectDirectory(myTargetClass.getContainingFile().getContainingDirectory()); + } + chooser.showDialog(); + PsiClass aClass = chooser.getSelected(); + if (aClass != null) { + myTfTargetClassName.setText(aClass.getQualifiedName()); + } + } } - } } diff --git a/plugin/src/main/java/com/intellij/java/impl/refactoring/introduceField/IntroduceFieldDialog.java b/plugin/src/main/java/com/intellij/java/impl/refactoring/introduceField/IntroduceFieldDialog.java index bc176273cb..ca3b768ab5 100644 --- a/plugin/src/main/java/com/intellij/java/impl/refactoring/introduceField/IntroduceFieldDialog.java +++ b/plugin/src/main/java/com/intellij/java/impl/refactoring/introduceField/IntroduceFieldDialog.java @@ -34,7 +34,9 @@ import consulo.language.editor.refactoring.rename.SuggestedNameInfo; import consulo.language.editor.refactoring.ui.NameSuggestionsField; import consulo.language.editor.refactoring.util.CommonRefactoringUtil; +import consulo.localize.LocalizeValue; import consulo.project.Project; +import consulo.ui.annotation.RequiredUIAccess; import consulo.ui.ex.awt.DialogWrapper; import consulo.ui.ex.awt.JBUI; import consulo.ui.ex.awt.Messages; @@ -49,255 +51,280 @@ class IntroduceFieldDialog extends DialogWrapper { - public static BaseExpressionToFieldHandler.InitializationPlace ourLastInitializerPlace; + public static BaseExpressionToFieldHandler.InitializationPlace ourLastInitializerPlace; + + private final Project myProject; + private final PsiClass myParentClass; + private final PsiExpression myInitializerExpression; + private final String myEnteredName; + private final PsiLocalVariable myLocalVariable; + private final boolean myIsInvokedOnDeclaration; + private final boolean myWillBeDeclaredStatic; + private final TypeSelectorManager myTypeSelectorManager; + + private NameSuggestionsField myNameField; + + private final IntroduceFieldCentralPanel myCentralPanel; + + private TypeSelector myTypeSelector; + private NameSuggestionsManager myNameSuggestionsManager; + private static final String REFACTORING_NAME = RefactoringBundle.message("introduce.field.title"); + + public IntroduceFieldDialog( + Project project, + PsiClass parentClass, + PsiExpression initializerExpression, + PsiLocalVariable localVariable, + boolean isCurrentMethodConstructor, boolean isInvokedOnDeclaration, boolean willBeDeclaredStatic, + PsiExpression[] occurrences, boolean allowInitInMethod, boolean allowInitInMethodIfAll, + TypeSelectorManager typeSelectorManager, String enteredName + ) { + super(project, true); + myProject = project; + myParentClass = parentClass; + myInitializerExpression = initializerExpression; + myEnteredName = enteredName; + myCentralPanel = + new IntroduceFieldDialogPanel( + parentClass, + initializerExpression, + localVariable, + isCurrentMethodConstructor, + isInvokedOnDeclaration, + willBeDeclaredStatic, + occurrences, + allowInitInMethod, + allowInitInMethodIfAll, + typeSelectorManager + ); + myLocalVariable = localVariable; + myIsInvokedOnDeclaration = isInvokedOnDeclaration; + myWillBeDeclaredStatic = willBeDeclaredStatic; + + myTypeSelectorManager = typeSelectorManager; + + setTitle(REFACTORING_NAME); + init(); + + myCentralPanel.initializeControls(initializerExpression, ourLastInitializerPlace); + updateButtons(); + } - private final Project myProject; - private final PsiClass myParentClass; - private final PsiExpression myInitializerExpression; - private final String myEnteredName; - private final PsiLocalVariable myLocalVariable; - private final boolean myIsInvokedOnDeclaration; - private final boolean myWillBeDeclaredStatic; - private final TypeSelectorManager myTypeSelectorManager; + public void setReplaceAllOccurrences(boolean replaceAll) { + myCentralPanel.setReplaceAllOccurrences(replaceAll); + } - private NameSuggestionsField myNameField; + public String getEnteredName() { + return myNameField.getEnteredName(); + } - private final IntroduceFieldCentralPanel myCentralPanel; + public BaseExpressionToFieldHandler.InitializationPlace getInitializerPlace() { - private TypeSelector myTypeSelector; - private NameSuggestionsManager myNameSuggestionsManager; - private static final String REFACTORING_NAME = RefactoringBundle.message("introduce.field.title"); + return myCentralPanel.getInitializerPlace(); + } - public IntroduceFieldDialog(Project project, - PsiClass parentClass, - PsiExpression initializerExpression, - PsiLocalVariable localVariable, - boolean isCurrentMethodConstructor, boolean isInvokedOnDeclaration, boolean willBeDeclaredStatic, - PsiExpression[] occurrences, boolean allowInitInMethod, boolean allowInitInMethodIfAll, - TypeSelectorManager typeSelectorManager, String enteredName) { - super(project, true); - myProject = project; - myParentClass = parentClass; - myInitializerExpression = initializerExpression; - myEnteredName = enteredName; - myCentralPanel = - new IntroduceFieldDialogPanel(parentClass, initializerExpression, localVariable, isCurrentMethodConstructor, isInvokedOnDeclaration, - willBeDeclaredStatic, occurrences, allowInitInMethod, allowInitInMethodIfAll, - typeSelectorManager); - myLocalVariable = localVariable; - myIsInvokedOnDeclaration = isInvokedOnDeclaration; - myWillBeDeclaredStatic = willBeDeclaredStatic; - - myTypeSelectorManager = typeSelectorManager; - - setTitle(REFACTORING_NAME); - init(); - - myCentralPanel.initializeControls(initializerExpression, ourLastInitializerPlace); - updateButtons(); - } - - public void setReplaceAllOccurrences(boolean replaceAll) { - myCentralPanel.setReplaceAllOccurrences(replaceAll); - } - - public String getEnteredName() { - return myNameField.getEnteredName(); - } - - public BaseExpressionToFieldHandler.InitializationPlace getInitializerPlace() { - - return myCentralPanel.getInitializerPlace(); - } - - @PsiModifier.ModifierConstant - public String getFieldVisibility() { - return myCentralPanel.getFieldVisibility(); - } - - public boolean isReplaceAllOccurrences() { - return myCentralPanel.isReplaceAllOccurrences(); - - } - - public boolean isDeleteVariable() { - return myCentralPanel.isDeleteVariable(); - - } - - public boolean isDeclareFinal() { - return myCentralPanel.isDeclareFinal(); - } - - public PsiType getFieldType() { - return myTypeSelector.getSelectedType(); - } - - - @Nonnull - protected Action[] createActions() { - return new Action[]{getOKAction(), getCancelAction(), getHelpAction()}; - } - - - protected JComponent createNorthPanel() { - - JPanel panel = new JPanel(new GridBagLayout()); - GridBagConstraints gbConstraints = new GridBagConstraints(); - - gbConstraints.insets = JBUI.insets(4, 4, 4, 0); - gbConstraints.anchor = GridBagConstraints.EAST; - gbConstraints.fill = GridBagConstraints.BOTH; - - gbConstraints.gridwidth = 1; - gbConstraints.weightx = 0; - gbConstraints.weighty = 1; - gbConstraints.gridx = 0; - gbConstraints.gridy = 0; - - JLabel type = new JLabel(getTypeLabel()); - - panel.add(type, gbConstraints); - - gbConstraints.gridx++; - gbConstraints.insets = JBUI.insets(4, 0, 4, 4); - gbConstraints.weightx = 0; - myTypeSelector = myTypeSelectorManager.getTypeSelector(); - panel.add(myTypeSelector.getComponent(), gbConstraints); - - gbConstraints.insets = JBUI.insets(4, 4, 4, 0); - gbConstraints.gridwidth = 1; - gbConstraints.weightx = 0; - gbConstraints.weighty = 1; - gbConstraints.gridx = 0; - gbConstraints.gridy = 1; - JLabel namePrompt = new JLabel(RefactoringLocalize.namePrompt().get()); - panel.add(namePrompt, gbConstraints); - - gbConstraints.insets = JBUI.insets(4, 0, 4, 4); - gbConstraints.gridwidth = 1; - gbConstraints.weightx = 1; - gbConstraints.gridx = 1; - gbConstraints.gridy = 1; - myNameField = new NameSuggestionsField(myProject); - panel.add(myNameField.getComponent(), gbConstraints); - myNameField.addDataChangedListener(this::updateButtons); - namePrompt.setLabelFor(myNameField.getFocusableComponent()); - - myNameSuggestionsManager = new NameSuggestionsManager( - myTypeSelector, - myNameField, - createGenerator( - myWillBeDeclaredStatic, - myLocalVariable, - myInitializerExpression, - myIsInvokedOnDeclaration, - myEnteredName, - myParentClass, - myProject - ) - ); - myNameSuggestionsManager.setLabelsFor(type, namePrompt); - - return panel; - } - - private void updateButtons() { - setOKActionEnabled(PsiNameHelper.getInstance(myProject).isIdentifier(getEnteredName())); - } - - private String getTypeLabel() { - return myWillBeDeclaredStatic - ? RefactoringLocalize.introduceFieldStaticFieldOfType().get() - : RefactoringLocalize.introduceFieldFieldOfType().get(); - } - - protected JComponent createCenterPanel() { - return myCentralPanel.createCenterPanel(); - } - - static NameSuggestionsGenerator createGenerator( - final boolean willBeDeclaredStatic, - final PsiLocalVariable localVariable, - final PsiExpression initializerExpression, - final boolean isInvokedOnDeclaration, - @Nullable final String enteredName, - final PsiClass parentClass, - final Project project - ) { - return new NameSuggestionsGenerator() { - private final JavaCodeStyleManager myCodeStyleManager = JavaCodeStyleManager.getInstance(project); - @RequiredReadAction - public SuggestedNameInfo getSuggestedNameInfo(PsiType type) { - VariableKind variableKind = willBeDeclaredStatic ? VariableKind.STATIC_FIELD : VariableKind.FIELD; - - String propertyName = null; - if (isInvokedOnDeclaration) { - propertyName = myCodeStyleManager.variableNameToPropertyName(localVariable.getName(), VariableKind.LOCAL_VARIABLE); - } - final SuggestedNameInfo nameInfo = myCodeStyleManager.suggestVariableName(variableKind, propertyName, initializerExpression, type); - if (initializerExpression != null) { - String[] names = nameInfo.names; - for (int i = 0, namesLength = names.length; i < namesLength; i++) { - String name = names[i]; - if (parentClass.findFieldByName(name, false) != null) { - names[i] = myCodeStyleManager.suggestUniqueVariableName(name, initializerExpression, true); - } - } - } - final String[] strings = AbstractJavaInplaceIntroducer.appendUnresolvedExprName(JavaCompletionUtil.completeVariableNameForRefactoring(myCodeStyleManager, type, VariableKind.LOCAL_VARIABLE, nameInfo), initializerExpression); - return new SuggestedNameInfo.Delegate(enteredName != null ? ArrayUtil.mergeArrays(new String[]{enteredName}, strings) : strings, nameInfo); - } - }; - } - - - protected void doOKAction() { - String fieldName = getEnteredName(); - String errorString = null; - if ("".equals(fieldName)) { - errorString = RefactoringLocalize.noFieldNameSpecified().get(); - } else if (!PsiNameHelper.getInstance(myProject).isIdentifier(fieldName)) { - errorString = RefactoringMessageUtil.getIncorrectIdentifierMessage(fieldName); + @PsiModifier.ModifierConstant + public String getFieldVisibility() { + return myCentralPanel.getFieldVisibility(); + } + + public boolean isReplaceAllOccurrences() { + return myCentralPanel.isReplaceAllOccurrences(); + + } + + public boolean isDeleteVariable() { + return myCentralPanel.isDeleteVariable(); + + } + + public boolean isDeclareFinal() { + return myCentralPanel.isDeclareFinal(); + } + + public PsiType getFieldType() { + return myTypeSelector.getSelectedType(); + } + + + @Nonnull + protected Action[] createActions() { + return new Action[]{getOKAction(), getCancelAction(), getHelpAction()}; } - if (errorString != null) { - CommonRefactoringUtil.showErrorMessage( - IntroduceFieldHandler.REFACTORING_NAME, - errorString, - HelpID.INTRODUCE_FIELD, - myProject - ); - return; + + + protected JComponent createNorthPanel() { + + JPanel panel = new JPanel(new GridBagLayout()); + GridBagConstraints gbConstraints = new GridBagConstraints(); + + gbConstraints.insets = JBUI.insets(4, 4, 4, 0); + gbConstraints.anchor = GridBagConstraints.EAST; + gbConstraints.fill = GridBagConstraints.BOTH; + + gbConstraints.gridwidth = 1; + gbConstraints.weightx = 0; + gbConstraints.weighty = 1; + gbConstraints.gridx = 0; + gbConstraints.gridy = 0; + + JLabel type = new JLabel(getTypeLabel()); + + panel.add(type, gbConstraints); + + gbConstraints.gridx++; + gbConstraints.insets = JBUI.insets(4, 0, 4, 4); + gbConstraints.weightx = 0; + myTypeSelector = myTypeSelectorManager.getTypeSelector(); + panel.add(myTypeSelector.getComponent(), gbConstraints); + + gbConstraints.insets = JBUI.insets(4, 4, 4, 0); + gbConstraints.gridwidth = 1; + gbConstraints.weightx = 0; + gbConstraints.weighty = 1; + gbConstraints.gridx = 0; + gbConstraints.gridy = 1; + JLabel namePrompt = new JLabel(RefactoringLocalize.namePrompt().get()); + panel.add(namePrompt, gbConstraints); + + gbConstraints.insets = JBUI.insets(4, 0, 4, 4); + gbConstraints.gridwidth = 1; + gbConstraints.weightx = 1; + gbConstraints.gridx = 1; + gbConstraints.gridy = 1; + myNameField = new NameSuggestionsField(myProject); + panel.add(myNameField.getComponent(), gbConstraints); + myNameField.addDataChangedListener(this::updateButtons); + namePrompt.setLabelFor(myNameField.getFocusableComponent()); + + myNameSuggestionsManager = new NameSuggestionsManager( + myTypeSelector, + myNameField, + createGenerator( + myWillBeDeclaredStatic, + myLocalVariable, + myInitializerExpression, + myIsInvokedOnDeclaration, + myEnteredName, + myParentClass, + myProject + ) + ); + myNameSuggestionsManager.setLabelsFor(type, namePrompt); + + return panel; + } + + private void updateButtons() { + setOKActionEnabled(PsiNameHelper.getInstance(myProject).isIdentifier(getEnteredName())); + } + + private String getTypeLabel() { + return myWillBeDeclaredStatic + ? RefactoringLocalize.introduceFieldStaticFieldOfType().get() + : RefactoringLocalize.introduceFieldFieldOfType().get(); } - PsiField oldField = myParentClass.findFieldByName(fieldName, true); - - if (oldField != null) { - int answer = Messages.showYesNoDialog( - myProject, - RefactoringLocalize.fieldExists(fieldName, oldField.getContainingClass().getQualifiedName()).get(), - IntroduceFieldHandler.REFACTORING_NAME, - UIUtil.getWarningIcon() - ); - if (answer != 0) { - return; - } + protected JComponent createCenterPanel() { + return myCentralPanel.createCenterPanel(); } - myCentralPanel.saveFinalState(); - ourLastInitializerPlace = myCentralPanel.getInitializerPlace(); - JavaRefactoringSettings.getInstance().INTRODUCE_FIELD_VISIBILITY = getFieldVisibility(); + static NameSuggestionsGenerator createGenerator( + final boolean willBeDeclaredStatic, + final PsiLocalVariable localVariable, + final PsiExpression initializerExpression, + final boolean isInvokedOnDeclaration, + @Nullable final String enteredName, + final PsiClass parentClass, + final Project project + ) { + return new NameSuggestionsGenerator() { + private final JavaCodeStyleManager myCodeStyleManager = JavaCodeStyleManager.getInstance(project); + + @RequiredReadAction + public SuggestedNameInfo getSuggestedNameInfo(PsiType type) { + VariableKind variableKind = willBeDeclaredStatic ? VariableKind.STATIC_FIELD : VariableKind.FIELD; + + String propertyName = null; + if (isInvokedOnDeclaration) { + propertyName = myCodeStyleManager.variableNameToPropertyName(localVariable.getName(), VariableKind.LOCAL_VARIABLE); + } + final SuggestedNameInfo nameInfo = + myCodeStyleManager.suggestVariableName(variableKind, propertyName, initializerExpression, type); + if (initializerExpression != null) { + String[] names = nameInfo.names; + for (int i = 0, namesLength = names.length; i < namesLength; i++) { + String name = names[i]; + if (parentClass.findFieldByName(name, false) != null) { + names[i] = myCodeStyleManager.suggestUniqueVariableName(name, initializerExpression, true); + } + } + } + final String[] strings = + AbstractJavaInplaceIntroducer.appendUnresolvedExprName(JavaCompletionUtil.completeVariableNameForRefactoring( + myCodeStyleManager, + type, + VariableKind.LOCAL_VARIABLE, + nameInfo + ), initializerExpression); + return new SuggestedNameInfo.Delegate(enteredName != null ? ArrayUtil.mergeArrays( + new String[]{enteredName}, + strings + ) : strings, nameInfo); + } + }; + } + + + @Override + @RequiredUIAccess + protected void doOKAction() { + String fieldName = getEnteredName(); + LocalizeValue errorString = LocalizeValue.empty(); + if ("".equals(fieldName)) { + errorString = RefactoringLocalize.noFieldNameSpecified(); + } + else if (!PsiNameHelper.getInstance(myProject).isIdentifier(fieldName)) { + errorString = LocalizeValue.localizeTODO(RefactoringMessageUtil.getIncorrectIdentifierMessage(fieldName)); + } + if (errorString != null) { + CommonRefactoringUtil.showErrorMessage( + IntroduceFieldHandler.REFACTORING_NAME, + errorString, + HelpID.INTRODUCE_FIELD, + myProject + ); + return; + } + + PsiField oldField = myParentClass.findFieldByName(fieldName, true); + + if (oldField != null) { + int answer = Messages.showYesNoDialog( + myProject, + RefactoringLocalize.fieldExists(fieldName, oldField.getContainingClass().getQualifiedName()).get(), + IntroduceFieldHandler.REFACTORING_NAME.get(), + UIUtil.getWarningIcon() + ); + if (answer != 0) { + return; + } + } - myNameSuggestionsManager.nameSelected(); - myTypeSelectorManager.typeSelected(getFieldType()); - super.doOKAction(); - } + myCentralPanel.saveFinalState(); + ourLastInitializerPlace = myCentralPanel.getInitializerPlace(); + JavaRefactoringSettings.getInstance().INTRODUCE_FIELD_VISIBILITY = getFieldVisibility(); - public JComponent getPreferredFocusedComponent() { - return myNameField.getFocusableComponent(); - } + myNameSuggestionsManager.nameSelected(); + myTypeSelectorManager.typeSelected(getFieldType()); + super.doOKAction(); + } - protected void doHelpAction() { - HelpManager.getInstance().invokeHelp(HelpID.INTRODUCE_FIELD); - } + public JComponent getPreferredFocusedComponent() { + return myNameField.getFocusableComponent(); + } + + protected void doHelpAction() { + HelpManager.getInstance().invokeHelp(HelpID.INTRODUCE_FIELD); + } } diff --git a/plugin/src/main/java/com/intellij/java/impl/refactoring/introduceParameter/IntroduceParameterMethodUsagesProcessor.java b/plugin/src/main/java/com/intellij/java/impl/refactoring/introduceParameter/IntroduceParameterMethodUsagesProcessor.java index 38628aa716..7f32b9ea0c 100644 --- a/plugin/src/main/java/com/intellij/java/impl/refactoring/introduceParameter/IntroduceParameterMethodUsagesProcessor.java +++ b/plugin/src/main/java/com/intellij/java/impl/refactoring/introduceParameter/IntroduceParameterMethodUsagesProcessor.java @@ -19,13 +19,14 @@ import consulo.annotation.component.ExtensionAPI; import consulo.component.extension.ExtensionPointName; import consulo.language.psi.PsiElement; +import consulo.localize.LocalizeValue; import consulo.usage.UsageInfo; import consulo.language.util.IncorrectOperationException; import consulo.util.collection.MultiMap; /** * @author Maxim.Medvedev - * Date: Apr 17, 2009 5:16:10 PM + * @since 2009-04-17 */ @ExtensionAPI(ComponentScope.APPLICATION) public interface IntroduceParameterMethodUsagesProcessor { @@ -34,7 +35,7 @@ public interface IntroduceParameterMethodUsagesProcessor { boolean isMethodUsage(UsageInfo usage); - void findConflicts(IntroduceParameterData data, UsageInfo[] usages, MultiMap conflicts); + void findConflicts(IntroduceParameterData data, UsageInfo[] usages, MultiMap conflicts); boolean processChangeMethodUsage(IntroduceParameterData data, UsageInfo usage, UsageInfo[] usages) throws IncorrectOperationException; diff --git a/plugin/src/main/java/com/intellij/java/impl/refactoring/introduceParameter/IntroduceParameterProcessor.java b/plugin/src/main/java/com/intellij/java/impl/refactoring/introduceParameter/IntroduceParameterProcessor.java index 7f2586155e..59a2d46584 100644 --- a/plugin/src/main/java/com/intellij/java/impl/refactoring/introduceParameter/IntroduceParameterProcessor.java +++ b/plugin/src/main/java/com/intellij/java/impl/refactoring/introduceParameter/IntroduceParameterProcessor.java @@ -13,15 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - -/* - * Created by IntelliJ IDEA. - * User: dsl - * Date: 07.05.2002 - * Time: 11:17:31 - * To change template for new class use - * Code Style | Class Templates options (Tools | IDE Options). - */ package com.intellij.java.impl.refactoring.introduceParameter; import com.intellij.java.impl.refactoring.IntroduceParameterRefactoring; @@ -69,8 +60,13 @@ import java.util.ArrayList; import java.util.HashSet; +import java.util.List; import java.util.Set; +/** + * @author dsl + * @since 2002-05-07 + */ public class IntroduceParameterProcessor extends BaseRefactoringProcessor implements IntroduceParameterData { private static final Logger LOG = Logger.getInstance(IntroduceParameterProcessor.class); @@ -81,7 +77,7 @@ public class IntroduceParameterProcessor extends BaseRefactoringProcessor implem private final PsiLocalVariable myLocalVariable; private final boolean myRemoveLocalVariable; private final String myParameterName; - private final boolean myReplaceAllOccurences; + private final boolean myReplaceAllOccurrences; private int myReplaceFieldsWithGetters; private final boolean myDeclareFinal; @@ -104,7 +100,7 @@ public IntroduceParameterProcessor( PsiLocalVariable localVariable, boolean removeLocalVariable, String parameterName, - boolean replaceAllOccurences, + boolean replaceAllOccurrences, int replaceFieldsWithGetters, boolean declareFinal, boolean generateDelegate, @@ -121,7 +117,7 @@ public IntroduceParameterProcessor( myLocalVariable = localVariable; myRemoveLocalVariable = removeLocalVariable; myParameterName = parameterName; - myReplaceAllOccurences = replaceAllOccurences; + myReplaceAllOccurrences = replaceAllOccurrences; myReplaceFieldsWithGetters = replaceFieldsWithGetters; myDeclareFinal = declareFinal; myGenerateDelegate = generateDelegate; @@ -162,7 +158,7 @@ public void setReplaceFieldsWithGetters(int replaceFieldsWithGetters) { @Override @RequiredReadAction protected UsageInfo[] findUsages() { - ArrayList result = new ArrayList<>(); + List result = new ArrayList<>(); PsiMethod[] overridingMethods = OverridingMethodsSearch.search(myMethodToSearchFor, true).toArray(PsiMethod.EMPTY_ARRAY); @@ -193,7 +189,7 @@ else if (!IntroduceParameterUtil.insideMethodToBeReplaced(ref, myMethodToReplace } } - if (myReplaceAllOccurences) { + if (myReplaceAllOccurrences) { for (PsiElement expr : getOccurrences()) { result.add(new InternalUsageInfo(expr)); } @@ -247,11 +243,11 @@ public void visitReferenceElement(@Nonnull PsiJavaCodeReferenceElement reference @RequiredUIAccess protected boolean preprocessUsages(SimpleReference refUsages) { UsageInfo[] usagesIn = refUsages.get(); - MultiMap conflicts = new MultiMap<>(); + MultiMap conflicts = new MultiMap<>(); AnySameNameVariables anySameNameVariables = new AnySameNameVariables(); myMethodToReplaceIn.accept(anySameNameVariables); - Pair conflictPair = anySameNameVariables.getConflict(); + Pair conflictPair = anySameNameVariables.getConflict(); if (conflictPair != null) { conflicts.putValue(conflictPair.first, conflictPair.second); } @@ -265,16 +261,16 @@ protected boolean preprocessUsages(SimpleReference refUsages) { myParameterInitializer.accept(anySupers); if (anySupers.isResult()) { for (UsageInfo usageInfo : usagesIn) { - if (!(usageInfo.getElement() instanceof PsiMethod) && !(usageInfo instanceof InternalUsageInfo)) { - if (!PsiTreeUtil.isAncestor(myMethodToReplaceIn.getContainingClass(), usageInfo.getElement(), false)) { - conflicts.putValue( - myParameterInitializer, - RefactoringLocalize.parameterInitializerContains0ButNotAllCallsToMethodAreInItsClass( - CommonRefactoringUtil.htmlEmphasize(PsiKeyword.SUPER) - ).get() - ); - break; - } + if (!(usageInfo.getElement() instanceof PsiMethod) + && !(usageInfo instanceof InternalUsageInfo) + && !PsiTreeUtil.isAncestor(myMethodToReplaceIn.getContainingClass(), usageInfo.getElement(), false)) { + conflicts.putValue( + myParameterInitializer, + RefactoringLocalize.parameterInitializerContains0ButNotAllCallsToMethodAreInItsClass( + CommonRefactoringUtil.htmlEmphasize(PsiKeyword.SUPER) + ) + ); + break; } } } @@ -288,7 +284,7 @@ protected boolean preprocessUsages(SimpleReference refUsages) { } @RequiredReadAction - private void detectAccessibilityConflicts(UsageInfo[] usageArray, MultiMap conflicts) { + private void detectAccessibilityConflicts(UsageInfo[] usageArray, MultiMap conflicts) { if (myParameterInitializer != null) { ReferencedElementsCollector collector = new ReferencedElementsCollector(); myParameterInitializer.accept(collector); @@ -316,7 +312,7 @@ private void detectAccessibilityConflicts(UsageInfo[] usageArray, MultiMap conflict = null; + private Pair conflict = null; - public Pair getConflict() { + public Pair getConflict() { return conflict; } @@ -361,7 +357,7 @@ public void visitVariable(@Nonnull PsiVariable variable) { RefactoringUIUtil.getDescription(variable, true) ); - conflict = Pair.create(variable, CommonRefactoringUtil.capitalize(descr.get())); + conflict = Pair.create(variable, descr); } } @@ -396,12 +392,12 @@ else if (myParameterInitializer instanceof PsiArrayInitializerExpression arrayIn arrayInitializerExpr, initializerType ); - myParameterInitializer = (PsiExpression)myParameterInitializer.replace(newExprArrayInitializer); + myParameterInitializer = (PsiExpression) myParameterInitializer.replace(newExprArrayInitializer); } myInitializerWrapper = new JavaExpressionWrapper(myParameterInitializer); - // Changing external occurences (the tricky part) + // Changing external occurrences (the tricky part) IntroduceParameterUtil.processUsages(usages, this); @@ -444,7 +440,7 @@ else if (usage instanceof InternalUsageInfo) { } else { PsiExpression newExpr = factory.createExpressionFromText(myParameterName, element); - IntroduceVariableBase.replace((PsiExpression)element, newExpr, myProject); + IntroduceVariableBase.replace((PsiExpression) element, newExpr, myProject); } } } @@ -461,8 +457,9 @@ else if (usage instanceof InternalUsageInfo) { } } + @RequiredWriteAction private PsiMethod generateDelegate(PsiMethod methodToReplaceIn) throws IncorrectOperationException { - PsiMethod delegate = (PsiMethod)methodToReplaceIn.copy(); + PsiMethod delegate = (PsiMethod) methodToReplaceIn.copy(); PsiElementFactory elementFactory = JavaPsiFacade.getInstance(myManager.getProject()).getElementFactory(); ChangeSignatureProcessor.makeEmptyBody(elementFactory, delegate); PsiCallExpression callExpression = ChangeSignatureProcessor.addDelegatingCallTemplate(delegate, delegate.getName()); @@ -490,7 +487,7 @@ private PsiMethod generateDelegate(PsiMethod methodToReplaceIn) throws Incorrect } } - return (PsiMethod)methodToReplaceIn.getContainingClass().addBefore(delegate, methodToReplaceIn); + return (PsiMethod) methodToReplaceIn.getContainingClass().addBefore(delegate, methodToReplaceIn); } static PsiType getInitializerType(PsiType forcedType, PsiExpression parameterInitializer, PsiLocalVariable localVariable) { @@ -518,6 +515,7 @@ else if (localVariable == null) { return initializerType; } + @RequiredWriteAction private void processChangedMethodCall(PsiElement element) throws IncorrectOperationException { if (element.getParent() instanceof PsiMethodCallExpression methodCall) { if (myMethodToReplaceIn == myMethodToSearchFor && PsiTreeUtil.isAncestor(methodCall, myParameterInitializer, false)) { @@ -567,6 +565,7 @@ else if (first && exprs.length > 0) { } } + @RequiredWriteAction private void removeParametersFromCall(PsiExpressionList argList) { PsiExpression[] exprs = argList.getExpressions(); for (int i = myParametersToRemove.size() - 1; i >= 0; i--) { diff --git a/plugin/src/main/java/com/intellij/java/impl/refactoring/move/moveClassesOrPackages/MoveClassToInnerProcessor.java b/plugin/src/main/java/com/intellij/java/impl/refactoring/move/moveClassesOrPackages/MoveClassToInnerProcessor.java index 06b5e83fac..1da6782b45 100644 --- a/plugin/src/main/java/com/intellij/java/impl/refactoring/move/moveClassesOrPackages/MoveClassToInnerProcessor.java +++ b/plugin/src/main/java/com/intellij/java/impl/refactoring/move/moveClassesOrPackages/MoveClassToInnerProcessor.java @@ -139,7 +139,6 @@ protected void refreshElements(@Nonnull PsiElement[] elements) { } @Override - @RequiredUIAccess @RequiredWriteAction protected void performRefactoring(@Nonnull UsageInfo[] usages) { if (!prepareWritable(usages)) { diff --git a/plugin/src/main/java/com/intellij/java/impl/refactoring/move/moveClassesOrPackages/PackageLocalsUsageCollector.java b/plugin/src/main/java/com/intellij/java/impl/refactoring/move/moveClassesOrPackages/PackageLocalsUsageCollector.java index 11106e6a71..c4ec6b610c 100644 --- a/plugin/src/main/java/com/intellij/java/impl/refactoring/move/moveClassesOrPackages/PackageLocalsUsageCollector.java +++ b/plugin/src/main/java/com/intellij/java/impl/refactoring/move/moveClassesOrPackages/PackageLocalsUsageCollector.java @@ -19,79 +19,91 @@ import com.intellij.java.impl.refactoring.util.ConflictsUtil; import com.intellij.java.language.psi.*; import com.intellij.java.language.util.VisibilityUtil; +import consulo.annotation.access.RequiredReadAction; import consulo.language.editor.refactoring.localize.RefactoringLocalize; import consulo.language.editor.refactoring.ui.RefactoringUIUtil; -import consulo.language.editor.refactoring.util.CommonRefactoringUtil; import consulo.language.psi.PsiDirectory; import consulo.language.psi.PsiElement; import consulo.language.psi.PsiFile; import consulo.language.psi.util.PsiTreeUtil; import consulo.localize.LocalizeValue; import consulo.util.collection.MultiMap; +import jakarta.annotation.Nonnull; import java.util.HashMap; import java.util.HashSet; +import java.util.Map; +import java.util.Set; class PackageLocalsUsageCollector extends JavaRecursiveElementWalkingVisitor { - private final HashMap> myReported = new HashMap>(); - private final PsiElement[] myElementsToMove; - private final MultiMap myConflicts; - private final PackageWrapper myTargetPackage; + private final Map> myReported = new HashMap<>(); + private final PsiElement[] myElementsToMove; + @Nonnull + private final MultiMap myConflicts; + private final PackageWrapper myTargetPackage; - public PackageLocalsUsageCollector(final PsiElement[] elementsToMove, final PackageWrapper targetPackage, MultiMap conflicts) { - myElementsToMove = elementsToMove; - myConflicts = conflicts; - myTargetPackage = targetPackage; - } + public PackageLocalsUsageCollector( + PsiElement[] elementsToMove, + PackageWrapper targetPackage, + @Nonnull MultiMap conflicts + ) { + myElementsToMove = elementsToMove; + myConflicts = conflicts; + myTargetPackage = targetPackage; + } - @Override public void visitReferenceExpression(PsiReferenceExpression expression) { - super.visitReferenceExpression(expression); - visitReferenceElement(expression); - } + @Override + @RequiredReadAction + public void visitReferenceExpression(@Nonnull PsiReferenceExpression expression) { + super.visitReferenceExpression(expression); + visitReferenceElement(expression); + } - @Override public void visitReferenceElement(PsiJavaCodeReferenceElement reference) { - super.visitReferenceElement(reference); - PsiElement resolved = reference.resolve(); - visitResolvedReference(resolved, reference); - } + @Override + @RequiredReadAction + public void visitReferenceElement(@Nonnull PsiJavaCodeReferenceElement reference) { + super.visitReferenceElement(reference); + PsiElement resolved = reference.resolve(); + visitResolvedReference(resolved, reference); + } - private void visitResolvedReference(PsiElement resolved, PsiJavaCodeReferenceElement reference) { - if (resolved instanceof PsiModifierListOwner) { - final PsiModifierList modifierList = ((PsiModifierListOwner)resolved).getModifierList(); - if (PsiModifier.PACKAGE_LOCAL.equals(VisibilityUtil.getVisibilityModifier(modifierList))) { - PsiFile aFile = resolved.getContainingFile(); - if (aFile != null && !isInsideMoved(resolved)) { - final PsiDirectory containingDirectory = aFile.getContainingDirectory(); - if (containingDirectory != null) { - PsiJavaPackage aPackage = JavaDirectoryService.getInstance().getPackage(containingDirectory); - if (aPackage != null && !myTargetPackage.equalToPackage(aPackage)) { - HashSet reportedRefs = myReported.get(resolved); - if (reportedRefs == null) { - reportedRefs = new HashSet(); - myReported.put(resolved, reportedRefs); - } - PsiElement container = ConflictsUtil.getContainer(reference); - if (!reportedRefs.contains(container)) { - final LocalizeValue message = RefactoringLocalize.zeroUsesAPackageLocal1( - RefactoringUIUtil.getDescription(container, true), - RefactoringUIUtil.getDescription(resolved, true) - ); - myConflicts.putValue(resolved, CommonRefactoringUtil.capitalize(message.get())); - reportedRefs.add(container); - } + private void visitResolvedReference(PsiElement resolved, PsiJavaCodeReferenceElement reference) { + if (resolved instanceof PsiModifierListOwner modifierListOwner) { + PsiModifierList modifierList = modifierListOwner.getModifierList(); + if (PsiModifier.PACKAGE_LOCAL.equals(VisibilityUtil.getVisibilityModifier(modifierList))) { + PsiFile aFile = modifierListOwner.getContainingFile(); + if (aFile != null && !isInsideMoved(modifierListOwner)) { + PsiDirectory containingDirectory = aFile.getContainingDirectory(); + if (containingDirectory != null) { + PsiJavaPackage aPackage = JavaDirectoryService.getInstance().getPackage(containingDirectory); + if (aPackage != null && !myTargetPackage.equalToPackage(aPackage)) { + Set reportedRefs = myReported.get(modifierListOwner); + if (reportedRefs == null) { + reportedRefs = new HashSet<>(); + myReported.put(modifierListOwner, reportedRefs); + } + PsiElement container = ConflictsUtil.getContainer(reference); + if (!reportedRefs.contains(container)) { + LocalizeValue message = RefactoringLocalize.zeroUsesAPackageLocal1( + RefactoringUIUtil.getDescription(container, true), + RefactoringUIUtil.getDescription(modifierListOwner, true) + ); + myConflicts.putValue(modifierListOwner, message.capitalize()); + reportedRefs.add(container); + } + } + } + } } - } } - } } - } - private boolean isInsideMoved(PsiElement place) { - for (PsiElement element : myElementsToMove) { - if (element instanceof PsiClass) { - if (PsiTreeUtil.isAncestor(element, place, false)) return true; - } + private boolean isInsideMoved(PsiElement place) { + for (PsiElement element : myElementsToMove) { + if (element instanceof PsiClass && PsiTreeUtil.isAncestor(element, place, false)) { + return true; + } + } + return false; } - return false; - } } \ No newline at end of file diff --git a/plugin/src/main/java/com/intellij/java/impl/refactoring/move/moveInstanceMethod/MoveInstanceMethodProcessor.java b/plugin/src/main/java/com/intellij/java/impl/refactoring/move/moveInstanceMethod/MoveInstanceMethodProcessor.java index 50545626a1..5c6aa225a6 100644 --- a/plugin/src/main/java/com/intellij/java/impl/refactoring/move/moveInstanceMethod/MoveInstanceMethodProcessor.java +++ b/plugin/src/main/java/com/intellij/java/impl/refactoring/move/moveInstanceMethod/MoveInstanceMethodProcessor.java @@ -89,7 +89,7 @@ public MoveInstanceMethodProcessor( LOG.assertTrue(myTargetVariable.getType() instanceof PsiClassType); PsiType type = myTargetVariable.getType(); LOG.assertTrue(type instanceof PsiClassType); - myTargetClass = ((PsiClassType)type).resolve(); + myTargetClass = ((PsiClassType) type).resolve(); myNewVisibility = newVisibility; } @@ -103,7 +103,7 @@ protected UsageViewDescriptor createUsageViewDescriptor(@Nonnull UsageInfo[] usa @RequiredUIAccess protected boolean preprocessUsages(@Nonnull SimpleReference refUsages) { UsageInfo[] usages = refUsages.get(); - MultiMap conflicts = new MultiMap<>(); + MultiMap conflicts = new MultiMap<>(); Set members = new HashSet<>(); members.add(myMethod); if (myTargetVariable instanceof PsiField field) { @@ -140,12 +140,12 @@ protected boolean preprocessUsages(@Nonnull SimpleReference refUsag RefactoringUIUtil.getDescription(ConflictsUtil.getContainer(methodCallExpr), true), CommonRefactoringUtil.htmlEmphasize(parameter.getName()) ); - conflicts.putValue(instanceValue, message.get()); + conflicts.putValue(literal, message); } } } else if (methodCall instanceof PsiMethodReferenceExpression) { - conflicts.putValue(methodCall, "Method reference would be broken after move"); + conflicts.putValue(methodCall, LocalizeValue.localizeTODO("Method reference would be broken after move")); } } } @@ -170,7 +170,7 @@ protected UsageInfo[] findUsages() { for (PsiReference ref : ReferencesSearch.search(myMethod, searchScope, false)) { PsiElement element = ref.getElement(); if (element instanceof PsiReferenceExpression refExpr) { - boolean isInternal = PsiTreeUtil.isAncestor(myMethod, element, true); + boolean isInternal = PsiTreeUtil.isAncestor(myMethod, refExpr, true); usages.add(new MethodCallUsageInfo(refExpr, isInternal)); } else if (element instanceof PsiDocTagValue docTagValue) { @@ -231,9 +231,9 @@ private static void addInheritorUsages(PsiClass aClass, GlobalSearchScope search @Override protected void refreshElements(PsiElement[] elements) { LOG.assertTrue(elements.length == 3); - myMethod = (PsiMethod)elements[0]; - myTargetVariable = (PsiVariable)elements[1]; - myTargetClass = (PsiClass)elements[2]; + myMethod = (PsiMethod) elements[0]; + myTargetVariable = (PsiVariable) elements[1]; + myTargetClass = (PsiClass) elements[2]; } @Nonnull @@ -247,7 +247,7 @@ public PsiClass getTargetClass() { } @Override - @RequiredUIAccess + @RequiredWriteAction protected void performRefactoring(@Nonnull UsageInfo[] usages) { if (!CommonRefactoringUtil.checkReadOnlyStatus(myProject, myTargetClass)) { return; @@ -309,7 +309,7 @@ private void correctMethodCall(PsiMethodCallExpression expression, boolean isInt int index = myMethod.getParameterList().getParameterIndex(parameter); PsiExpression[] arguments = expression.getArgumentList().getExpressions(); if (index < arguments.length) { - newQualifier = (PsiExpression)arguments[index].copy(); + newQualifier = (PsiExpression) arguments[index].copy(); arguments[index].delete(); } } @@ -345,39 +345,31 @@ else if (myTargetVariable instanceof PsiField field) { .createExpressionFromText(thisArgumentText, null); } } - else { - if (!isInternalCall && oldQualifier != null) { - PsiType type = oldQualifier.getType(); - if (type instanceof PsiClassType classType) { - PsiClass resolved = classType.resolve(); - if (resolved != null && getParameterNameToCreate(resolved) != null) { - newArgument = - replaceRefsToTargetVariable(oldQualifier); //replace is needed in case old qualifier is e.g. the same as field as target variable - } - } + else if (!isInternalCall && oldQualifier != null && oldQualifier.getType() instanceof PsiClassType classType) { + PsiClass resolved = classType.resolve(); + if (resolved != null && getParameterNameToCreate(resolved) != null) { + //replace is needed in case old qualifier is e.g. the same as field as target variable + newArgument = replaceRefsToTargetVariable(oldQualifier); } } - if (newArgument != null) { expression.getArgumentList().add(newArgument); } - if (newQualifier != null) { - if (newQualifier instanceof PsiThisExpression thisExpr && thisExpr.getQualifier() == null) { - //Remove now redundant 'this' qualifier - if (oldQualifier != null) { - oldQualifier.delete(); - } - } - else { - PsiReferenceExpression refExpr = (PsiReferenceExpression)JavaPsiFacade.getInstance(manager.getProject()) - .getElementFactory() - .createExpressionFromText("q." + myMethod.getName(), null); - refExpr.getQualifierExpression().replace(newQualifier); - methodExpression.replace(refExpr); + if (newQualifier instanceof PsiThisExpression thisExpr && thisExpr.getQualifier() == null) { + //Remove now redundant 'this' qualifier + if (oldQualifier != null) { + oldQualifier.delete(); } } + else if (newQualifier != null) { + PsiReferenceExpression refExpr = (PsiReferenceExpression) JavaPsiFacade.getInstance(manager.getProject()) + .getElementFactory() + .createExpressionFromText("q." + myMethod.getName(), null); + refExpr.getQualifierExpression().replace(newQualifier); + methodExpression.replace(refExpr); + } } catch (IncorrectOperationException e) { LOG.error(e); @@ -423,7 +415,7 @@ private static PsiExpression createThisExpr(PsiManager manager) { @RequiredWriteAction private static PsiMethod addMethodToClass(PsiClass aClass, PsiMethod patternMethod, boolean canAddOverride) { try { - PsiMethod method = (PsiMethod)aClass.add(patternMethod); + PsiMethod method = (PsiMethod) aClass.add(patternMethod); ChangeContextUtil.decodeContextInfo(method, null, null); if (canAddOverride && OverrideImplementUtil.isInsertOverride(method, aClass)) { method.getModifierList().addAnnotation(CommonClassNames.JAVA_LANG_OVERRIDE); @@ -437,6 +429,7 @@ private static PsiMethod addMethodToClass(PsiClass aClass, PsiMethod patternMeth return null; } + @RequiredWriteAction private PsiMethod createMethodToAdd() { ChangeContextUtil.encodeContextInfo(myMethod, true); try { @@ -468,19 +461,19 @@ public void visitThisExpression(@Nonnull PsiThisExpression expression) { @RequiredWriteAction public void visitReferenceExpression(PsiReferenceExpression expression) { try { - PsiExpression qualifier = expression.getQualifierExpression(); PsiElement resolved = expression.resolve(); - if (qualifier instanceof PsiReferenceExpression qRefExpr && qRefExpr.isReferenceTo(myTargetVariable)) { + if (expression.getQualifierExpression() instanceof PsiReferenceExpression qRefExpr + && qRefExpr.isReferenceTo(myTargetVariable)) { if (resolved instanceof PsiField field) { for (PsiParameter parameter : myMethod.getParameterList().getParameters()) { if (Comparing.strEqual(parameter.getName(), field.getName())) { - qualifier.replace(factory.createExpressionFromText("this", null)); + qRefExpr.replace(factory.createExpressionFromText("this", null)); return; } } } //Target is a field, replace target.m -> m - qualifier.delete(); + qRefExpr.delete(); return; } if (myTargetVariable.equals(resolved)) { @@ -501,7 +494,7 @@ else if (myMethod.equals(resolved)) { String paramName = getParameterNameToCreate(classReferencedByThis); if (paramName != null) { PsiReferenceExpression newQualifier = - (PsiReferenceExpression)factory.createExpressionFromText(paramName, null); + (PsiReferenceExpression) factory.createExpressionFromText(paramName, null); expression.setQualifierExpression(newQualifier); return; } @@ -521,7 +514,7 @@ public void visitNewExpression(@Nonnull PsiNewExpression expression) { PsiExpression qualifier = expression.getQualifier(); if (qualifier instanceof PsiReferenceExpression qRefExpr && qRefExpr.isReferenceTo(myTargetVariable)) { //Target is a field, replace target.new A() -> new A() - qualifier.delete(); + qRefExpr.delete(); } else { PsiClass classReferencedByThis = MoveInstanceMembersUtil.getClassReferencedByThis(expression); @@ -568,7 +561,7 @@ public void visitMethodCallExpression(@Nonnull PsiMethodCallExpression expressio } private PsiMethod getPatternMethod() throws IncorrectOperationException { - PsiMethod methodCopy = (PsiMethod)myMethod.copy(); + PsiMethod methodCopy = (PsiMethod) myMethod.copy(); String name = myTargetClass.isInterface() ? PsiModifier.PUBLIC : !Comparing.strEqual(myNewVisibility, VisibilityUtil.ESCALATE_VISIBILITY) ? myNewVisibility : null; if (name != null) { @@ -576,6 +569,7 @@ private PsiMethod getPatternMethod() throws IncorrectOperationException { } if (myTargetVariable instanceof PsiParameter parameter) { int index = myMethod.getParameterList().getParameterIndex(parameter); + //noinspection RequiredXAction methodCopy.getParameterList().getParameters()[index].delete(); } diff --git a/plugin/src/main/java/com/intellij/java/impl/refactoring/move/moveMembers/MoveMemberHandler.java b/plugin/src/main/java/com/intellij/java/impl/refactoring/move/moveMembers/MoveMemberHandler.java index 73c34ce872..f929a6417d 100644 --- a/plugin/src/main/java/com/intellij/java/impl/refactoring/move/moveMembers/MoveMemberHandler.java +++ b/plugin/src/main/java/com/intellij/java/impl/refactoring/move/moveMembers/MoveMemberHandler.java @@ -28,6 +28,7 @@ import consulo.language.extension.LanguageOneToOne; import consulo.language.psi.PsiElement; import consulo.language.psi.PsiReference; +import consulo.localize.LocalizeValue; import consulo.util.collection.MultiMap; import jakarta.annotation.Nonnull; @@ -40,31 +41,50 @@ */ @ExtensionAPI(ComponentScope.APPLICATION) public interface MoveMemberHandler extends LanguageExtension { - ExtensionPointCacheKey> KEY = ExtensionPointCacheKey.create("MoveMemberHandler", LanguageOneToOne.build()); + ExtensionPointCacheKey> KEY = + ExtensionPointCacheKey.create("MoveMemberHandler", LanguageOneToOne.build()); - @Nullable - static MoveMemberHandler forLanguage(@Nonnull Language language) { - return Application.get().getExtensionPoint(MoveMemberHandler.class).getOrBuildCache(KEY).get(language); - } + @Nullable + static MoveMemberHandler forLanguage(@Nonnull Language language) { + return Application.get().getExtensionPoint(MoveMemberHandler.class).getOrBuildCache(KEY).get(language); + } - @Nullable - MoveMembersProcessor.MoveMembersUsageInfo getUsage(@Nonnull PsiMember member, @Nonnull PsiReference ref, @Nonnull Set membersToMove, - @Nonnull PsiClass targetClass); + @Nullable + MoveMembersProcessor.MoveMembersUsageInfo getUsage( + @Nonnull PsiMember member, @Nonnull PsiReference ref, @Nonnull Set membersToMove, + @Nonnull PsiClass targetClass + ); - void checkConflictsOnUsage(@Nonnull MoveMembersProcessor.MoveMembersUsageInfo usageInfo, @Nullable String newVisibility, - @Nullable PsiModifierList modifierListCopy, @Nonnull PsiClass targetClass, @Nonnull Set membersToMove, - @Nonnull MultiMap conflicts); + void checkConflictsOnUsage( + @Nonnull MoveMembersProcessor.MoveMembersUsageInfo usageInfo, + @Nullable String newVisibility, + @Nullable PsiModifierList modifierListCopy, + @Nonnull PsiClass targetClass, + @Nonnull Set membersToMove, + @Nonnull MultiMap conflicts + ); - void checkConflictsOnMember(@Nonnull PsiMember member, @Nullable String newVisibility, @Nullable PsiModifierList modifierListCopy, - @Nonnull PsiClass targetClass, @Nonnull Set membersToMove, @Nonnull MultiMap conflicts); + void checkConflictsOnMember( + @Nonnull PsiMember member, + @Nullable String newVisibility, + @Nullable PsiModifierList modifierListCopy, + @Nonnull PsiClass targetClass, + @Nonnull Set membersToMove, + @Nonnull MultiMap conflicts + ); - @Nullable - PsiElement getAnchor(@Nonnull PsiMember member, @Nonnull PsiClass targetClass, Set membersToMove); + @Nullable + PsiElement getAnchor(@Nonnull PsiMember member, @Nonnull PsiClass targetClass, Set membersToMove); - boolean changeExternalUsage(@Nonnull MoveMembersOptions options, @Nonnull MoveMembersProcessor.MoveMembersUsageInfo usage); + boolean changeExternalUsage(@Nonnull MoveMembersOptions options, @Nonnull MoveMembersProcessor.MoveMembersUsageInfo usage); - @Nonnull - PsiMember doMove(@Nonnull MoveMembersOptions options, @Nonnull PsiMember member, @Nullable PsiElement anchor, @Nonnull PsiClass targetClass); + @Nonnull + PsiMember doMove( + @Nonnull MoveMembersOptions options, + @Nonnull PsiMember member, + @Nullable PsiElement anchor, + @Nonnull PsiClass targetClass + ); - void decodeContextInfo(@Nonnull PsiElement scope); + void decodeContextInfo(@Nonnull PsiElement scope); } diff --git a/plugin/src/main/java/com/intellij/java/impl/refactoring/move/moveMembers/MoveMembersProcessor.java b/plugin/src/main/java/com/intellij/java/impl/refactoring/move/moveMembers/MoveMembersProcessor.java index 483e36618f..70cc727111 100644 --- a/plugin/src/main/java/com/intellij/java/impl/refactoring/move/moveMembers/MoveMembersProcessor.java +++ b/plugin/src/main/java/com/intellij/java/impl/refactoring/move/moveMembers/MoveMembersProcessor.java @@ -62,7 +62,7 @@ public class MoveMembersProcessor extends BaseRefactoringProcessor { private final MoveCallback myMoveCallback; private final boolean myOpenInEditor; private String myNewVisibility; // "null" means "as is" - private String myCommandName = MoveMembersImpl.REFACTORING_NAME; + private LocalizeValue myCommandName = MoveMembersImpl.REFACTORING_NAME; private MoveMembersOptions myOptions; public MoveMembersProcessor(Project project, MoveMembersOptions options) { @@ -83,7 +83,7 @@ public MoveMembersProcessor(Project project, @Nullable MoveCallback moveCallback @Nonnull @Override protected String getCommandName() { - return myCommandName; + return myCommandName.get(); } private void setOptions(MoveMembersOptions dialog) { @@ -116,7 +116,7 @@ private void setCommandName(PsiMember[] members) { first = false; } - myCommandName = commandName.toString(); + myCommandName = LocalizeValue.localizeTODO(commandName.toString()); } @Nonnull @@ -296,8 +296,8 @@ private void fixModifierList(PsiMember member, PsiMember newMember, UsageInfo[] List filtered = new ArrayList<>(); for (UsageInfo usage : usages) { - if (usage instanceof MoveMembersUsageInfo moveMembersUsageInfo && member == moveMembersUsageInfo.member) { - filtered.add(usage); + if (usage instanceof MoveMembersUsageInfo moveMembersUsage && member == moveMembersUsage.member) { + filtered.add(moveMembersUsage); } } UsageInfo[] infos = filtered.toArray(new UsageInfo[filtered.size()]); @@ -307,7 +307,7 @@ private void fixModifierList(PsiMember member, PsiMember newMember, UsageInfo[] @Override @RequiredUIAccess protected boolean preprocessUsages(@Nonnull SimpleReference refUsages) { - MultiMap conflicts = new MultiMap<>(); + MultiMap conflicts = new MultiMap<>(); UsageInfo[] usages = refUsages.get(); String newVisibility = myNewVisibility; @@ -347,7 +347,7 @@ private static void analyzeConflictsOnUsages( String newVisibility, @Nonnull PsiClass targetClass, Map modifierListCopies, - MultiMap conflicts + MultiMap conflicts ) { for (UsageInfo usage : usages) { if (!(usage instanceof MoveMembersUsageInfo usageInfo)) { @@ -374,7 +374,7 @@ private static void analyzeConflictsOnMembers( String newVisibility, PsiClass targetClass, Map modifierListCopies, - MultiMap conflicts + MultiMap conflicts ) { for (PsiMember member : membersToMove) { MoveMemberHandler handler = MoveMemberHandler.forLanguage(member.getLanguage()); @@ -396,7 +396,7 @@ private static void analyzeConflictsOnMembers( public void doRun() { if (myMembersToMove.isEmpty()) { LocalizeValue message = RefactoringLocalize.noMembersSelected(); - CommonRefactoringUtil.showErrorMessage(MoveMembersImpl.REFACTORING_NAME, message.get(), HelpID.MOVE_MEMBERS, myProject); + CommonRefactoringUtil.showErrorMessage(MoveMembersImpl.REFACTORING_NAME, message, HelpID.MOVE_MEMBERS, myProject); return; } super.doRun(); diff --git a/plugin/src/main/java/com/intellij/java/impl/refactoring/removemiddleman/RemoveMiddlemanProcessor.java b/plugin/src/main/java/com/intellij/java/impl/refactoring/removemiddleman/RemoveMiddlemanProcessor.java index 19ef41093c..e64f2183f9 100644 --- a/plugin/src/main/java/com/intellij/java/impl/refactoring/removemiddleman/RemoveMiddlemanProcessor.java +++ b/plugin/src/main/java/com/intellij/java/impl/refactoring/removemiddleman/RemoveMiddlemanProcessor.java @@ -27,12 +27,14 @@ import com.intellij.java.language.psi.PsiMethodCallExpression; import com.intellij.java.language.psi.util.PropertyUtil; import consulo.annotation.access.RequiredReadAction; +import consulo.annotation.access.RequiredWriteAction; import consulo.java.localize.JavaRefactoringLocalize; import consulo.language.psi.PsiElement; import consulo.language.psi.PsiReference; import consulo.language.psi.search.ReferencesSearch; import consulo.language.psi.util.SymbolPresentationUtil; import consulo.language.util.IncorrectOperationException; +import consulo.localize.LocalizeValue; import consulo.logging.Logger; import consulo.ui.annotation.RequiredUIAccess; import consulo.usage.UsageInfo; @@ -74,7 +76,7 @@ public void findUsages(@Nonnull List usages) { if (!memberInfo.isChecked()) { continue; } - PsiMethod method = (PsiMethod)memberInfo.getMember(); + PsiMethod method = (PsiMethod) memberInfo.getMember(); String getterName = PropertyUtil.suggestGetterName(field); int[] paramPermutation = DelegationUtils.getParameterPermutation(method); PsiMethod delegatedMethod = DelegationUtils.getDelegatedMethod(method); @@ -86,7 +88,7 @@ public void findUsages(@Nonnull List usages) { @Override @RequiredUIAccess protected boolean preprocessUsages(@Nonnull SimpleReference refUsages) { - MultiMap conflicts = new MultiMap<>(); + MultiMap conflicts = new MultiMap<>(); for (MemberInfo memberInfo : myDelegateMethodInfos) { if (memberInfo.isChecked() && memberInfo.isToAbstract() && memberInfo.getMember() instanceof PsiMethod method && method.findDeepestSuperMethods().length > 0) { @@ -94,14 +96,14 @@ protected boolean preprocessUsages(@Nonnull SimpleReference refUsag method, JavaRefactoringLocalize.removeMiddlemanDeletedHierarchyConflict( SymbolPresentationUtil.getSymbolPresentableText(method) - ).get() + ) ); } } return showConflicts(conflicts, refUsages.get()); } - @RequiredReadAction + @RequiredWriteAction private void processUsagesForMethod( boolean deleteMethodHierarchy, PsiMethod method, @@ -112,7 +114,7 @@ private void processUsagesForMethod( ) { for (PsiReference reference : ReferencesSearch.search(method)) { PsiElement referenceElement = reference.getElement(); - PsiMethodCallExpression call = (PsiMethodCallExpression)referenceElement.getParent(); + PsiMethodCallExpression call = (PsiMethodCallExpression) referenceElement.getParent(); String access; if (call.getMethodExpression().getQualifierExpression() == null) { access = field.getName(); @@ -131,6 +133,7 @@ private void processUsagesForMethod( } @Override + @RequiredWriteAction protected void performRefactoring(@Nonnull UsageInfo[] usageInfos) { if (getter != null) { try {