From 8e64b35f4cdb9ce4846275bbfe23fbdb08a58c17 Mon Sep 17 00:00:00 2001 From: UNV Date: Sun, 21 Dec 2025 03:48:46 +0300 Subject: [PATCH] Java inspections and refactoring processors refactoring (part 4). --- .../InplaceIntroduceParameterPopup.java | 2 +- .../IntroduceParameterHandler.java | 833 ++++++++++-------- ...troduceParameterMethodUsagesProcessor.java | 63 +- .../makeStatic/MakeClassStaticProcessor.java | 108 ++- .../makeStatic/MakeMethodStaticProcessor.java | 1 + .../memberPullUp/PullUpConflictsUtil.java | 120 ++- .../memberPullUp/PullUpDialog.java | 80 +- 7 files changed, 628 insertions(+), 579 deletions(-) diff --git a/plugin/src/main/java/com/intellij/java/impl/refactoring/introduceParameter/InplaceIntroduceParameterPopup.java b/plugin/src/main/java/com/intellij/java/impl/refactoring/introduceParameter/InplaceIntroduceParameterPopup.java index 25afc6a828..e38f4176dc 100644 --- a/plugin/src/main/java/com/intellij/java/impl/refactoring/introduceParameter/InplaceIntroduceParameterPopup.java +++ b/plugin/src/main/java/com/intellij/java/impl/refactoring/introduceParameter/InplaceIntroduceParameterPopup.java @@ -75,7 +75,7 @@ public class InplaceIntroduceParameterPopup extends AbstractJavaInplaceIntroduce final PsiExpression[] occurrences, final IntList parametersToRemove, final boolean mustBeFinal) { - super(project, editor, expr, localVar, occurrences, typeSelectorManager, IntroduceParameterHandler.REFACTORING_NAME + super(project, editor, expr, localVar, occurrences, typeSelectorManager, IntroduceParameterHandler.REFACTORING_NAME.get() ); myMethod = method; myMethodToSearchFor = methodToSearchFor; diff --git a/plugin/src/main/java/com/intellij/java/impl/refactoring/introduceParameter/IntroduceParameterHandler.java b/plugin/src/main/java/com/intellij/java/impl/refactoring/introduceParameter/IntroduceParameterHandler.java index a88f110237..57f7a0bff5 100644 --- a/plugin/src/main/java/com/intellij/java/impl/refactoring/introduceParameter/IntroduceParameterHandler.java +++ b/plugin/src/main/java/com/intellij/java/impl/refactoring/introduceParameter/IntroduceParameterHandler.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: 06.05.2002 - * Time: 13:36:30 - * 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.codeInsight.CodeInsightUtil; @@ -38,7 +29,6 @@ import com.intellij.java.language.psi.*; import com.intellij.java.language.psi.codeStyle.JavaCodeStyleManager; import com.intellij.java.language.psi.codeStyle.VariableKind; -import consulo.application.ApplicationManager; import consulo.application.ui.wm.IdeFocusManager; import consulo.codeEditor.Editor; import consulo.codeEditor.EditorColors; @@ -52,7 +42,6 @@ import consulo.colorScheme.TextAttributes; import consulo.dataContext.DataContext; import consulo.document.util.TextRange; -import consulo.language.editor.refactoring.RefactoringBundle; import consulo.language.editor.refactoring.introduce.inplace.AbstractInplaceIntroducer; import consulo.language.editor.refactoring.localize.RefactoringLocalize; import consulo.language.editor.refactoring.rename.SuggestedNameInfo; @@ -64,6 +53,7 @@ import consulo.localize.LocalizeValue; import consulo.logging.Logger; import consulo.project.Project; +import consulo.ui.annotation.RequiredUIAccess; import consulo.ui.ex.awt.JBList; import consulo.ui.ex.awt.ScrollPaneFactory; import consulo.ui.ex.popup.JBPopup; @@ -75,425 +65,504 @@ import consulo.util.collection.primitive.ints.IntList; import consulo.util.collection.primitive.ints.IntLists; import consulo.util.lang.Pair; -import org.jetbrains.annotations.NonNls; - import jakarta.annotation.Nonnull; import jakarta.annotation.Nullable; + import javax.swing.*; -import javax.swing.event.ListSelectionEvent; -import javax.swing.event.ListSelectionListener; import java.awt.*; -import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.util.ArrayList; import java.util.Collections; import java.util.List; - +/** + * @author dsl + * @since 2002-05-06 + */ public class IntroduceParameterHandler extends IntroduceHandlerBase { - private static final Logger LOG = Logger.getInstance(IntroduceParameterHandler.class); - static final String REFACTORING_NAME = RefactoringBundle.message("introduce.parameter.title"); - private JBPopup myEnclosingMethodsPopup; - private InplaceIntroduceParameterPopup myInplaceIntroduceParameterPopup; - - public void invoke(@Nonnull final Project project, final Editor editor, PsiFile file, DataContext dataContext) { - PsiDocumentManager.getInstance(project).commitAllDocuments(); - editor.getScrollingModel().scrollToCaret(ScrollType.MAKE_VISIBLE); - ElementToWorkOn.processElementToWorkOn(editor, file, REFACTORING_NAME, HelpID.INTRODUCE_PARAMETER, project, new ElementToWorkOn.ElementsProcessor() { - @Override - public boolean accept(ElementToWorkOn el) { - return true; - } - - @Override - public void pass(ElementToWorkOn elementToWorkOn) { - if (elementToWorkOn == null) return; - - PsiExpression expr = elementToWorkOn.getExpression(); - PsiLocalVariable localVar = elementToWorkOn.getLocalVariable(); - boolean isInvokedOnDeclaration = elementToWorkOn.isInvokedOnDeclaration(); - - invoke(editor, project, expr, localVar, isInvokedOnDeclaration); - } - }); - } - - protected boolean invokeImpl(Project project, PsiExpression tempExpr, Editor editor) { - return invoke(editor, project, tempExpr, null, false); - } - - protected boolean invokeImpl(Project project, PsiLocalVariable localVariable, Editor editor) { - return invoke(editor, project, null, localVariable, true); - } - - private boolean invoke(Editor editor, Project project, PsiExpression expr, - PsiLocalVariable localVar, boolean invokedOnDeclaration) { - LOG.assertTrue(!PsiDocumentManager.getInstance(project).hasUncommitedDocuments()); - PsiMethod method; - if (expr != null) { - method = Util.getContainingMethod(expr); - } else { - method = Util.getContainingMethod(localVar); + private static final Logger LOG = Logger.getInstance(IntroduceParameterHandler.class); + static final LocalizeValue REFACTORING_NAME = RefactoringLocalize.introduceParameterTitle(); + private JBPopup myEnclosingMethodsPopup; + private InplaceIntroduceParameterPopup myInplaceIntroduceParameterPopup; + + @Override + @RequiredUIAccess + public void invoke(@Nonnull final Project project, final Editor editor, PsiFile file, DataContext dataContext) { + PsiDocumentManager.getInstance(project).commitAllDocuments(); + editor.getScrollingModel().scrollToCaret(ScrollType.MAKE_VISIBLE); + ElementToWorkOn.processElementToWorkOn( + editor, + file, + REFACTORING_NAME.get(), + HelpID.INTRODUCE_PARAMETER, + project, + new ElementToWorkOn.ElementsProcessor<>() { + @Override + public boolean accept(ElementToWorkOn el) { + return true; + } + + @Override + @RequiredUIAccess + public void pass(ElementToWorkOn elementToWorkOn) { + if (elementToWorkOn == null) { + return; + } + + PsiExpression expr = elementToWorkOn.getExpression(); + PsiLocalVariable localVar = elementToWorkOn.getLocalVariable(); + boolean isInvokedOnDeclaration = elementToWorkOn.isInvokedOnDeclaration(); + + invoke(editor, project, expr, localVar, isInvokedOnDeclaration); + } + } + ); } - if (LOG.isDebugEnabled()) { - LOG.debug("expression:" + expr); + @Override + @RequiredUIAccess + protected boolean invokeImpl(@Nonnull Project project, PsiExpression tempExpr, Editor editor) { + return invoke(editor, project, tempExpr, null, false); } - if (expr == null && localVar == null) { - LocalizeValue message = - RefactoringLocalize.cannotPerformRefactoringWithReason(RefactoringLocalize.selectedBlockShouldRepresentAnExpression()); - showErrorMessage(project, message.get(), editor); - return false; + @Override + @RequiredUIAccess + protected boolean invokeImpl(@Nonnull Project project, PsiLocalVariable localVariable, Editor editor) { + return invoke(editor, project, null, localVariable, true); } - if (localVar != null) { - PsiElement parent = localVar.getParent(); - if (!(parent instanceof PsiDeclarationStatement)) { - LocalizeValue message = - RefactoringLocalize.cannotPerformRefactoringWithReason(RefactoringLocalize.errorWrongCaretPositionLocalOrExpressionName()); - showErrorMessage(project, message.get(), editor); - return false; - } - } + @RequiredUIAccess + private boolean invoke( + Editor editor, + @Nonnull Project project, + PsiExpression expr, + PsiLocalVariable localVar, + boolean invokedOnDeclaration + ) { + LOG.assertTrue(!PsiDocumentManager.getInstance(project).hasUncommitedDocuments()); + PsiMethod method; + if (expr != null) { + method = Util.getContainingMethod(expr); + } + else { + method = Util.getContainingMethod(localVar); + } - if (method == null) { - LocalizeValue message = - RefactoringLocalize.cannotPerformRefactoringWithReason(RefactoringLocalize.isNotSupportedInTheCurrentContext(REFACTORING_NAME)); - showErrorMessage(project, message.get(), editor); - return false; - } + if (LOG.isDebugEnabled()) { + LOG.debug("expression:" + expr); + } - if (!CommonRefactoringUtil.checkReadOnlyStatus(project, method)) return false; + if (expr == null && localVar == null) { + LocalizeValue message = + RefactoringLocalize.cannotPerformRefactoringWithReason(RefactoringLocalize.selectedBlockShouldRepresentAnExpression()); + showErrorMessage(project, message, editor); + return false; + } - PsiType typeByExpression = invokedOnDeclaration ? null : RefactoringUtil.getTypeByExpressionWithExpectedType(expr); - if (!invokedOnDeclaration && (typeByExpression == null || LambdaUtil.notInferredType(typeByExpression))) { - LocalizeValue message = - RefactoringLocalize.cannotPerformRefactoringWithReason(RefactoringLocalize.typeOfTheSelectedExpressionCannotBeDetermined()); - showErrorMessage(project, message.get(), editor); - return false; - } + if (localVar != null) { + PsiElement parent = localVar.getParent(); + if (!(parent instanceof PsiDeclarationStatement)) { + LocalizeValue message = RefactoringLocalize.cannotPerformRefactoringWithReason( + RefactoringLocalize.errorWrongCaretPositionLocalOrExpressionName() + ); + showErrorMessage(project, message, editor); + return false; + } + } - if (!invokedOnDeclaration && PsiType.VOID.equals(typeByExpression)) { - LocalizeValue message = RefactoringLocalize.cannotPerformRefactoringWithReason(RefactoringLocalize.selectedExpressionHasVoidType()); - showErrorMessage(project, message.get(), editor); - return false; - } + if (method == null) { + LocalizeValue message = RefactoringLocalize.cannotPerformRefactoringWithReason( + RefactoringLocalize.isNotSupportedInTheCurrentContext(REFACTORING_NAME) + ); + showErrorMessage(project, message, editor); + return false; + } - List validEnclosingMethods = getEnclosingMethods(method); - if (validEnclosingMethods.isEmpty()) { - return false; - } - Introducer introducer = new Introducer(project, expr, localVar, editor); - boolean unitTestMode = ApplicationManager.getApplication().isUnitTestMode(); - if (validEnclosingMethods.size() == 1 || unitTestMode) { - PsiMethod methodToIntroduceParameterTo = validEnclosingMethods.get(0); - if (methodToIntroduceParameterTo.findDeepestSuperMethod() == null || unitTestMode) { - introducer.introduceParameter(methodToIntroduceParameterTo, methodToIntroduceParameterTo); - return true; - } - } + if (!CommonRefactoringUtil.checkReadOnlyStatus(project, method)) { + return false; + } - chooseMethodToIntroduceParameter(editor, validEnclosingMethods, introducer); + PsiType typeByExpression = invokedOnDeclaration ? null : RefactoringUtil.getTypeByExpressionWithExpectedType(expr); + if (!invokedOnDeclaration && (typeByExpression == null || LambdaUtil.notInferredType(typeByExpression))) { + LocalizeValue message = + RefactoringLocalize.cannotPerformRefactoringWithReason(RefactoringLocalize.typeOfTheSelectedExpressionCannotBeDetermined()); + showErrorMessage(project, message, editor); + return false; + } - return true; - } + if (!invokedOnDeclaration && PsiType.VOID.equals(typeByExpression)) { + LocalizeValue message = + RefactoringLocalize.cannotPerformRefactoringWithReason(RefactoringLocalize.selectedExpressionHasVoidType()); + showErrorMessage(project, message, editor); + return false; + } - private void chooseMethodToIntroduceParameter(final Editor editor, - List validEnclosingMethods, - final Introducer introducer) { - AbstractInplaceIntroducer inplaceIntroducer = AbstractInplaceIntroducer.getActiveIntroducer(editor); - if (inplaceIntroducer instanceof InplaceIntroduceParameterPopup) { - InplaceIntroduceParameterPopup introduceParameterPopup = (InplaceIntroduceParameterPopup) inplaceIntroducer; - introducer.introduceParameter(introduceParameterPopup.getMethodToIntroduceParameter(), - introduceParameterPopup.getMethodToSearchFor()); - return; - } - JPanel panel = new JPanel(new BorderLayout()); - final JCheckBox superMethod = new JCheckBox("Refactor super method", true); - superMethod.setMnemonic('U'); - panel.add(superMethod, BorderLayout.SOUTH); - final JBList list = new JBList(validEnclosingMethods.toArray()); - list.setVisibleRowCount(5); - list.setCellRenderer(new MethodCellRenderer()); - list.getSelectionModel().setSelectionMode(ListSelectionModel.SINGLE_SELECTION); - list.setSelectedIndex(0); - final List highlighters = new ArrayList(); - final TextAttributes attributes = - EditorColorsManager.getInstance().getGlobalScheme().getAttributes(EditorColors.SEARCH_RESULT_ATTRIBUTES); - list.addListSelectionListener(new ListSelectionListener() { - public void valueChanged(ListSelectionEvent e) { - PsiMethod selectedMethod = (PsiMethod) list.getSelectedValue(); - if (selectedMethod == null) return; - dropHighlighters(highlighters); - updateView(selectedMethod, editor, attributes, highlighters, superMethod); - } - }); - updateView(validEnclosingMethods.get(0), editor, attributes, highlighters, superMethod); - JScrollPane scrollPane = ScrollPaneFactory.createScrollPane(list); - scrollPane.setBorder(null); - panel.add(scrollPane, BorderLayout.CENTER); - - List> - keyboardActions = Collections.singletonList(Pair.create(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - final PsiMethod methodToSearchIn = (PsiMethod) list.getSelectedValue(); - if (myEnclosingMethodsPopup != null && myEnclosingMethodsPopup.isVisible()) { - myEnclosingMethodsPopup.cancel(); + List validEnclosingMethods = getEnclosingMethods(method); + if (validEnclosingMethods.isEmpty()) { + return false; + } + Introducer introducer = new Introducer(project, expr, localVar, editor); + boolean unitTestMode = project.getApplication().isUnitTestMode(); + if (validEnclosingMethods.size() == 1 || unitTestMode) { + PsiMethod methodToIntroduceParameterTo = validEnclosingMethods.get(0); + if (methodToIntroduceParameterTo.findDeepestSuperMethod() == null || unitTestMode) { + introducer.introduceParameter(methodToIntroduceParameterTo, methodToIntroduceParameterTo); + return true; + } } - final PsiMethod methodToSearchFor = superMethod.isEnabled() && superMethod.isSelected() - ? methodToSearchIn.findDeepestSuperMethod() : methodToSearchIn; - Runnable runnable = new Runnable() { - public void run() { - introducer.introduceParameter(methodToSearchIn, methodToSearchFor); - } - }; - IdeFocusManager.findInstance().doWhenFocusSettlesDown(runnable); - } - }, KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0))); - myEnclosingMethodsPopup = JBPopupFactory.getInstance().createComponentPopupBuilder(panel, list) - .setTitle("Introduce parameter to method") - .setMovable(false) - .setResizable(false) - .setRequestFocus(true) - .setKeyboardActions(keyboardActions).addListener(new JBPopupAdapter() { - @Override - public void onClosed(LightweightWindowEvent event) { - dropHighlighters(highlighters); - } - }).createPopup(); - EditorPopupHelper.getInstance().showPopupInBestPositionFor(editor, myEnclosingMethodsPopup); - } - - private static void updateView(PsiMethod selectedMethod, - Editor editor, - TextAttributes attributes, - List highlighters, - JCheckBox superMethod) { - MarkupModel markupModel = editor.getMarkupModel(); - PsiIdentifier nameIdentifier = selectedMethod.getNameIdentifier(); - if (nameIdentifier != null) { - TextRange textRange = nameIdentifier.getTextRange(); - RangeHighlighter rangeHighlighter = markupModel.addRangeHighlighter( - textRange.getStartOffset(), textRange.getEndOffset(), HighlighterLayer.SELECTION - 1, - attributes, - HighlighterTargetArea.EXACT_RANGE); - highlighters.add(rangeHighlighter); - } - superMethod.setEnabled(selectedMethod.findDeepestSuperMethod() != null); - } + chooseMethodToIntroduceParameter(editor, validEnclosingMethods, introducer); - private static void dropHighlighters(List highlighters) { - for (RangeHighlighter highlighter : highlighters) { - highlighter.dispose(); + return true; } - highlighters.clear(); - } - - protected static NameSuggestionsGenerator createNameSuggestionGenerator(final PsiExpression expr, - final String propName, - final Project project, - final String enteredName) { - return new NameSuggestionsGenerator() { - public SuggestedNameInfo getSuggestedNameInfo(PsiType type) { - JavaCodeStyleManager codeStyleManager = JavaCodeStyleManager.getInstance(project); - SuggestedNameInfo info = codeStyleManager.suggestVariableName(VariableKind.PARAMETER, propName, expr != null && expr.isValid() ? expr : null, type); - if (expr != null && expr.isValid()) { - info = codeStyleManager.suggestUniqueVariableName(info, expr, true); + + @RequiredUIAccess + private void chooseMethodToIntroduceParameter( + Editor editor, + @Nonnull List validEnclosingMethods, + @Nonnull Introducer introducer + ) { + AbstractInplaceIntroducer inplaceIntroducer = AbstractInplaceIntroducer.getActiveIntroducer(editor); + if (inplaceIntroducer instanceof InplaceIntroduceParameterPopup) { + InplaceIntroduceParameterPopup introduceParameterPopup = (InplaceIntroduceParameterPopup) inplaceIntroducer; + introducer.introduceParameter( + introduceParameterPopup.getMethodToIntroduceParameter(), + introduceParameterPopup.getMethodToSearchFor() + ); + return; } - String[] strings = AbstractJavaInplaceIntroducer.appendUnresolvedExprName(JavaCompletionUtil - .completeVariableNameForRefactoring(codeStyleManager, type, VariableKind.LOCAL_VARIABLE, info), expr); - return new SuggestedNameInfo.Delegate(enteredName != null ? ArrayUtil.mergeArrays(new String[]{enteredName}, strings) : strings, info); - } - - }; - } - - private static void showErrorMessage(Project project, String message, Editor editor) { - CommonRefactoringUtil.showErrorHint(project, editor, message, REFACTORING_NAME, HelpID.INTRODUCE_PARAMETER); - } - - - public void invoke(@Nonnull Project project, @Nonnull PsiElement[] elements, DataContext dataContext) { - // Never called - /* do nothing */ - } - - public static List getEnclosingMethods(PsiMethod nearest) { - List enclosingMethods = new ArrayList(); - enclosingMethods.add(nearest); - PsiMethod method = nearest; - while (true) { - method = PsiTreeUtil.getParentOfType(method, PsiMethod.class, true); - if (method == null) break; - enclosingMethods.add(method); + JPanel panel = new JPanel(new BorderLayout()); + JCheckBox superMethod = new JCheckBox("Refactor super method", true); + superMethod.setMnemonic('U'); + panel.add(superMethod, BorderLayout.SOUTH); + JBList list = new JBList<>(validEnclosingMethods); + list.setVisibleRowCount(5); + list.setCellRenderer(new MethodCellRenderer()); + list.getSelectionModel().setSelectionMode(ListSelectionModel.SINGLE_SELECTION); + list.setSelectedIndex(0); + final List highlighters = new ArrayList<>(); + TextAttributes attributes = + EditorColorsManager.getInstance().getGlobalScheme().getAttributes(EditorColors.SEARCH_RESULT_ATTRIBUTES); + list.addListSelectionListener(e -> { + PsiMethod selectedMethod = (PsiMethod) list.getSelectedValue(); + if (selectedMethod == null) { + return; + } + dropHighlighters(highlighters); + updateView(selectedMethod, editor, attributes, highlighters, superMethod); + }); + updateView(validEnclosingMethods.get(0), editor, attributes, highlighters, superMethod); + JScrollPane scrollPane = ScrollPaneFactory.createScrollPane(list); + scrollPane.setBorder(null); + panel.add(scrollPane, BorderLayout.CENTER); + + List> + keyboardActions = Collections.singletonList(Pair.create(e -> { + PsiMethod methodToSearchIn = (PsiMethod) list.getSelectedValue(); + if (myEnclosingMethodsPopup != null && myEnclosingMethodsPopup.isVisible()) { + myEnclosingMethodsPopup.cancel(); + } + + PsiMethod methodToSearchFor = superMethod.isEnabled() && superMethod.isSelected() + ? methodToSearchIn.findDeepestSuperMethod() : methodToSearchIn; + Runnable runnable = () -> introducer.introduceParameter(methodToSearchIn, methodToSearchFor); + IdeFocusManager.findInstance().doWhenFocusSettlesDown(runnable); + }, KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0))); + myEnclosingMethodsPopup = JBPopupFactory.getInstance().createComponentPopupBuilder(panel, list) + .setTitle(LocalizeValue.localizeTODO("Introduce parameter to method")) + .setMovable(false) + .setResizable(false) + .setRequestFocus(true) + .setKeyboardActions(keyboardActions) + .addListener(new JBPopupAdapter() { + @Override + public void onClosed(LightweightWindowEvent event) { + dropHighlighters(highlighters); + } + }) + .createPopup(); + EditorPopupHelper.getInstance().showPopupInBestPositionFor(editor, myEnclosingMethodsPopup); } - if (enclosingMethods.size() > 1) { - List methodsNotImplementingLibraryInterfaces = new ArrayList(); - for (PsiMethod enclosing : enclosingMethods) { - PsiMethod[] superMethods = enclosing.findDeepestSuperMethods(); - boolean libraryInterfaceMethod = false; - for (PsiMethod superMethod : superMethods) { - libraryInterfaceMethod |= isLibraryInterfaceMethod(superMethod); - } - if (!libraryInterfaceMethod) { - methodsNotImplementingLibraryInterfaces.add(enclosing); + + private static void updateView( + PsiMethod selectedMethod, + Editor editor, + TextAttributes attributes, + List highlighters, + JCheckBox superMethod + ) { + MarkupModel markupModel = editor.getMarkupModel(); + PsiIdentifier nameIdentifier = selectedMethod.getNameIdentifier(); + if (nameIdentifier != null) { + TextRange textRange = nameIdentifier.getTextRange(); + RangeHighlighter rangeHighlighter = markupModel.addRangeHighlighter( + textRange.getStartOffset(), textRange.getEndOffset(), HighlighterLayer.SELECTION - 1, + attributes, + HighlighterTargetArea.EXACT_RANGE + ); + highlighters.add(rangeHighlighter); } - } - if (methodsNotImplementingLibraryInterfaces.size() > 0) { - return methodsNotImplementingLibraryInterfaces; - } - } - return enclosingMethods; - } - - - @Nullable - public static PsiMethod chooseEnclosingMethod(@Nonnull PsiMethod method) { - List validEnclosingMethods = getEnclosingMethods(method); - if (validEnclosingMethods.size() > 1 && !ApplicationManager.getApplication().isUnitTestMode()) { - EnclosingMethodSelectionDialog dialog = new EnclosingMethodSelectionDialog(method.getProject(), validEnclosingMethods); - dialog.show(); - if (!dialog.isOK()) return null; - method = dialog.getSelectedMethod(); - } else if (validEnclosingMethods.size() == 1) { - method = validEnclosingMethods.get(0); + superMethod.setEnabled(selectedMethod.findDeepestSuperMethod() != null); } - return method; - } - private static boolean isLibraryInterfaceMethod(PsiMethod method) { - return method.hasModifierProperty(PsiModifier.ABSTRACT) && !method.getManager().isInProject(method); - } - - private class Introducer { + private static void dropHighlighters(List highlighters) { + for (RangeHighlighter highlighter : highlighters) { + highlighter.dispose(); + } + highlighters.clear(); + } - private final Project myProject; + protected static NameSuggestionsGenerator createNameSuggestionGenerator( + PsiExpression expr, + String propName, + Project project, + String enteredName + ) { + return type -> { + JavaCodeStyleManager codeStyleManager = JavaCodeStyleManager.getInstance(project); + SuggestedNameInfo info = codeStyleManager.suggestVariableName( + VariableKind.PARAMETER, + propName, + expr != null && expr.isValid() ? expr : null, + type + ); + if (expr != null && expr.isValid()) { + info = codeStyleManager.suggestUniqueVariableName(info, expr, true); + } + String[] strings = AbstractJavaInplaceIntroducer.appendUnresolvedExprName( + JavaCompletionUtil.completeVariableNameForRefactoring(codeStyleManager, type, VariableKind.LOCAL_VARIABLE, info), + expr + ); + return new SuggestedNameInfo.Delegate( + enteredName != null ? ArrayUtil.mergeArrays(new String[]{enteredName}, strings) : strings, + info + ); + }; + } - private PsiExpression myExpr; - private PsiLocalVariable myLocalVar; - private final Editor myEditor; + @RequiredUIAccess + private static void showErrorMessage(Project project, @Nonnull LocalizeValue message, Editor editor) { + CommonRefactoringUtil.showErrorHint(project, editor, message, REFACTORING_NAME, HelpID.INTRODUCE_PARAMETER); + } - public Introducer(Project project, - PsiExpression expr, - PsiLocalVariable localVar, - Editor editor) { - myProject = project; - myExpr = expr; - myLocalVar = localVar; - myEditor = editor; + @Override + public void invoke(@Nonnull Project project, @Nonnull PsiElement[] elements, DataContext dataContext) { + // Never called + /* do nothing */ } - public void introduceParameter(PsiMethod method, PsiMethod methodToSearchFor) { - if (!CommonRefactoringUtil.checkReadOnlyStatus(myProject, methodToSearchFor)) return; - - PsiExpression[] occurences; - if (myExpr != null) { - occurences = new ExpressionOccurrenceManager(myExpr, method, null).findExpressionOccurrences(); - } else { // local variable - occurences = CodeInsightUtil.findReferenceExpressions(method, myLocalVar); - } - - String enteredName = null; - boolean replaceAllOccurrences = false; - boolean delegate = false; - PsiType initializerType = IntroduceParameterProcessor.getInitializerType(null, myExpr, myLocalVar); - - AbstractInplaceIntroducer activeIntroducer = AbstractInplaceIntroducer.getActiveIntroducer(myEditor); - if (activeIntroducer != null) { - activeIntroducer.stopIntroduce(myEditor); - myExpr = (PsiExpression) activeIntroducer.getExpr(); - myLocalVar = (PsiLocalVariable) activeIntroducer.getLocalVariable(); - occurences = (PsiExpression[]) activeIntroducer.getOccurrences(); - enteredName = activeIntroducer.getInputName(); - replaceAllOccurrences = activeIntroducer.isReplaceAllOccurrences(); - delegate = ((InplaceIntroduceParameterPopup) activeIntroducer).isGenerateDelegate(); - initializerType = ((AbstractJavaInplaceIntroducer) activeIntroducer).getType(); - } - - boolean mustBeFinal = false; - for (PsiExpression occurrence : occurences) { - if (PsiTreeUtil.getParentOfType(occurrence, PsiClass.class, PsiMethod.class) != method) { - mustBeFinal = true; - break; + public static List getEnclosingMethods(PsiMethod nearest) { + List enclosingMethods = new ArrayList<>(); + enclosingMethods.add(nearest); + PsiMethod method = nearest; + while (true) { + method = PsiTreeUtil.getParentOfType(method, PsiMethod.class, true); + if (method == null) { + break; + } + enclosingMethods.add(method); } - } - - List localVars = new ArrayList(); - List classMemberRefs = new ArrayList(); - List params = new ArrayList(); - - - if (myExpr != null) { - Util.analyzeExpression(myExpr, localVars, classMemberRefs, params); - } - - String propName = myLocalVar != null ? JavaCodeStyleManager - .getInstance(myProject).variableNameToPropertyName(myLocalVar.getName(), VariableKind.LOCAL_VARIABLE) : null; + if (enclosingMethods.size() > 1) { + List methodsNotImplementingLibraryInterfaces = new ArrayList<>(); + for (PsiMethod enclosing : enclosingMethods) { + PsiMethod[] superMethods = enclosing.findDeepestSuperMethods(); + boolean libraryInterfaceMethod = false; + for (PsiMethod superMethod : superMethods) { + libraryInterfaceMethod |= isLibraryInterfaceMethod(superMethod); + } + if (!libraryInterfaceMethod) { + methodsNotImplementingLibraryInterfaces.add(enclosing); + } + } + if (methodsNotImplementingLibraryInterfaces.size() > 0) { + return methodsNotImplementingLibraryInterfaces; + } + } + return enclosingMethods; + } - boolean isInplaceAvailableOnDataContext = myEditor != null && myEditor.getSettings().isVariableInplaceRenameEnabled(); + @Nullable + @RequiredUIAccess + public static PsiMethod chooseEnclosingMethod(@Nonnull PsiMethod method) { + List validEnclosingMethods = getEnclosingMethods(method); + if (validEnclosingMethods.size() > 1 && !method.getApplication().isUnitTestMode()) { + EnclosingMethodSelectionDialog dialog = new EnclosingMethodSelectionDialog(method.getProject(), validEnclosingMethods); + dialog.show(); + if (!dialog.isOK()) { + return null; + } + method = dialog.getSelectedMethod(); + } + else if (validEnclosingMethods.size() == 1) { + method = validEnclosingMethods.get(0); + } + return method; + } - if (myExpr != null) { - isInplaceAvailableOnDataContext &= myExpr.isPhysical(); - } + private static boolean isLibraryInterfaceMethod(PsiMethod method) { + return method.isAbstract() && !method.getManager().isInProject(method); + } - if (isInplaceAvailableOnDataContext && activeIntroducer == null) { - myInplaceIntroduceParameterPopup = - new InplaceIntroduceParameterPopup(myProject, myEditor, classMemberRefs, - createTypeSelectorManager(occurences, initializerType), - myExpr, myLocalVar, method, methodToSearchFor, occurences, - getParamsToRemove(method, occurences), - mustBeFinal); - if (myInplaceIntroduceParameterPopup.startInplaceIntroduceTemplate()) { - return; + private class Introducer { + @Nonnull + private final Project myProject; + + private PsiExpression myExpr; + private PsiLocalVariable myLocalVar; + private final Editor myEditor; + + public Introducer( + @Nonnull Project project, + PsiExpression expr, + PsiLocalVariable localVar, + Editor editor + ) { + myProject = project; + myExpr = expr; + myLocalVar = localVar; + myEditor = editor; } - } - if (ApplicationManager.getApplication().isUnitTestMode()) { - @NonNls String parameterName = "anObject"; - boolean replaceAllOccurences = true; - boolean isDeleteLocalVariable = true; - PsiExpression initializer = myLocalVar != null && myExpr == null ? myLocalVar.getInitializer() : myExpr; - new IntroduceParameterProcessor(myProject, method, methodToSearchFor, initializer, myExpr, myLocalVar, isDeleteLocalVariable, parameterName, - replaceAllOccurences, IntroduceParameterRefactoring.REPLACE_FIELDS_WITH_GETTERS_NONE, mustBeFinal, - false, null, - getParamsToRemove(method, occurences)).run(); - } else { - if (myEditor != null) { - RefactoringUtil.highlightAllOccurrences(myProject, occurences, myEditor); + + @RequiredUIAccess + public void introduceParameter(PsiMethod method, PsiMethod methodToSearchFor) { + if (!CommonRefactoringUtil.checkReadOnlyStatus(myProject, methodToSearchFor)) { + return; + } + + PsiExpression[] occurrences = myExpr != null + ? new ExpressionOccurrenceManager(myExpr, method, null).findExpressionOccurrences() + // local variable + : CodeInsightUtil.findReferenceExpressions(method, myLocalVar); + + String enteredName = null; + boolean replaceAllOccurrences = false; + boolean delegate = false; + PsiType initializerType = IntroduceParameterProcessor.getInitializerType(null, myExpr, myLocalVar); + + AbstractInplaceIntroducer activeIntroducer = AbstractInplaceIntroducer.getActiveIntroducer(myEditor); + if (activeIntroducer != null) { + activeIntroducer.stopIntroduce(myEditor); + myExpr = (PsiExpression) activeIntroducer.getExpr(); + myLocalVar = (PsiLocalVariable) activeIntroducer.getLocalVariable(); + occurrences = (PsiExpression[]) activeIntroducer.getOccurrences(); + enteredName = activeIntroducer.getInputName(); + replaceAllOccurrences = activeIntroducer.isReplaceAllOccurrences(); + delegate = ((InplaceIntroduceParameterPopup) activeIntroducer).isGenerateDelegate(); + initializerType = ((AbstractJavaInplaceIntroducer) activeIntroducer).getType(); + } + + boolean mustBeFinal = false; + for (PsiExpression occurrence : occurrences) { + if (PsiTreeUtil.getParentOfType(occurrence, PsiClass.class, PsiMethod.class) != method) { + mustBeFinal = true; + break; + } + } + + List localVars = new ArrayList<>(); + List classMemberRefs = new ArrayList<>(); + List params = new ArrayList<>(); + + if (myExpr != null) { + Util.analyzeExpression(myExpr, localVars, classMemberRefs, params); + } + + String propName = myLocalVar != null + ? JavaCodeStyleManager.getInstance(myProject).variableNameToPropertyName(myLocalVar.getName(), VariableKind.LOCAL_VARIABLE) + : null; + + boolean isInplaceAvailableOnDataContext = myEditor != null && myEditor.getSettings().isVariableInplaceRenameEnabled(); + + if (myExpr != null) { + isInplaceAvailableOnDataContext &= myExpr.isPhysical(); + } + + if (isInplaceAvailableOnDataContext && activeIntroducer == null) { + myInplaceIntroduceParameterPopup = new InplaceIntroduceParameterPopup( + myProject, + myEditor, + classMemberRefs, + createTypeSelectorManager(occurrences, initializerType), + myExpr, + myLocalVar, + method, + methodToSearchFor, + occurrences, + getParamsToRemove(method, occurrences), + mustBeFinal + ); + if (myInplaceIntroduceParameterPopup.startInplaceIntroduceTemplate()) { + return; + } + } + if (myProject.getApplication().isUnitTestMode()) { + String parameterName = "anObject"; + boolean isDeleteLocalVariable = true; + PsiExpression initializer = myLocalVar != null && myExpr == null ? myLocalVar.getInitializer() : myExpr; + new IntroduceParameterProcessor( + myProject, + method, + methodToSearchFor, + initializer, + myExpr, + myLocalVar, + isDeleteLocalVariable, + parameterName, + replaceAllOccurrences, + IntroduceParameterRefactoring.REPLACE_FIELDS_WITH_GETTERS_NONE, + mustBeFinal, + false, + null, + getParamsToRemove(method, occurrences) + ).run(); + } + else { + if (myEditor != null) { + RefactoringUtil.highlightAllOccurrences(myProject, occurrences, myEditor); + } + IntroduceParameterDialog dialog = + new IntroduceParameterDialog( + myProject, + classMemberRefs, + occurrences, + myLocalVar, + myExpr, + createNameSuggestionGenerator(myExpr, propName, myProject, enteredName), + createTypeSelectorManager(occurrences, initializerType), + methodToSearchFor, + method, + getParamsToRemove(method, occurrences), + mustBeFinal + ); + dialog.setReplaceAllOccurrences(replaceAllOccurrences); + dialog.setGenerateDelegate(delegate); + dialog.show(); + if (myEditor != null) { + myEditor.getSelectionModel().removeSelection(); + } + } } - IntroduceParameterDialog dialog = - new IntroduceParameterDialog(myProject, classMemberRefs, occurences, myLocalVar, myExpr, - createNameSuggestionGenerator(myExpr, propName, myProject, enteredName), - createTypeSelectorManager(occurences, initializerType), methodToSearchFor, method, getParamsToRemove(method, occurences), mustBeFinal); - dialog.setReplaceAllOccurrences(replaceAllOccurrences); - dialog.setGenerateDelegate(delegate); - dialog.show(); - if (myEditor != null) { - myEditor.getSelectionModel().removeSelection(); + + private TypeSelectorManagerImpl createTypeSelectorManager(PsiExpression[] occurrences, PsiType initializerType) { + return myExpr != null + ? new TypeSelectorManagerImpl(myProject, initializerType, myExpr, occurrences) + : new TypeSelectorManagerImpl(myProject, initializerType, occurrences); } - } - } - private TypeSelectorManagerImpl createTypeSelectorManager(PsiExpression[] occurences, PsiType initializerType) { - return myExpr != null ? new TypeSelectorManagerImpl(myProject, initializerType, myExpr, occurences) - : new TypeSelectorManagerImpl(myProject, initializerType, occurences); + private IntList getParamsToRemove(PsiMethod method, PsiExpression[] occurrences) { + PsiExpression expressionToRemoveParamFrom = myExpr; + if (myExpr == null) { + expressionToRemoveParamFrom = myLocalVar.getInitializer(); + } + return expressionToRemoveParamFrom == null + ? IntLists.newArrayList() + : Util.findParametersToRemove(method, expressionToRemoveParamFrom, occurrences); + } } - private IntList getParamsToRemove(PsiMethod method, PsiExpression[] occurences) { - PsiExpression expressionToRemoveParamFrom = myExpr; - if (myExpr == null) { - expressionToRemoveParamFrom = myLocalVar.getInitializer(); - } - return expressionToRemoveParamFrom == null ? IntLists.newArrayList() : Util - .findParametersToRemove(method, expressionToRemoveParamFrom, occurences); + @Override + public AbstractInplaceIntroducer getInplaceIntroducer() { + return myInplaceIntroduceParameterPopup; } - } - - @Override - public AbstractInplaceIntroducer getInplaceIntroducer() { - return myInplaceIntroduceParameterPopup; - } } diff --git a/plugin/src/main/java/com/intellij/java/impl/refactoring/introduceParameter/JavaIntroduceParameterMethodUsagesProcessor.java b/plugin/src/main/java/com/intellij/java/impl/refactoring/introduceParameter/JavaIntroduceParameterMethodUsagesProcessor.java index 2fc732b9bd..a691d56f6d 100644 --- a/plugin/src/main/java/com/intellij/java/impl/refactoring/introduceParameter/JavaIntroduceParameterMethodUsagesProcessor.java +++ b/plugin/src/main/java/com/intellij/java/impl/refactoring/introduceParameter/JavaIntroduceParameterMethodUsagesProcessor.java @@ -27,6 +27,8 @@ import com.intellij.java.language.psi.javadoc.PsiDocTag; import com.intellij.java.language.psi.util.PsiUtil; import com.intellij.java.language.util.VisibilityUtil; +import consulo.annotation.access.RequiredReadAction; +import consulo.annotation.access.RequiredWriteAction; import consulo.annotation.component.ExtensionImpl; import consulo.language.Language; import consulo.language.codeStyle.CodeStyleManager; @@ -53,15 +55,20 @@ public class JavaIntroduceParameterMethodUsagesProcessor implements IntroducePar Logger.getInstance(JavaIntroduceParameterMethodUsagesProcessor.class); private static final JavaLanguage myLanguage = Language.findInstance(JavaLanguage.class); + @RequiredReadAction private static boolean isJavaUsage(UsageInfo usage) { PsiElement e = usage.getElement(); return e != null && e.getLanguage().is(myLanguage); } + @Override + @RequiredReadAction public boolean isMethodUsage(UsageInfo usage) { return RefactoringUtil.isMethodUsage(usage.getElement()) && isJavaUsage(usage); } + @Override + @RequiredWriteAction public boolean processChangeMethodUsage( IntroduceParameterData data, UsageInfo usage, @@ -108,13 +115,9 @@ public boolean processChangeMethodUsage( PsiElement initializer = ExpressionConverter.getExpression(data.getParameterInitializer().getExpression(), JavaLanguage.INSTANCE, data.getProject()); assert initializer instanceof PsiExpression; - if (initializer instanceof PsiNewExpression) { - if (!PsiDiamondTypeUtil.canChangeContextForDiamond( - (PsiNewExpression) initializer, - ((PsiNewExpression) initializer).getType() - )) { - initializer = PsiDiamondTypeUtil.expandTopLevelDiamondsInside((PsiNewExpression) initializer); - } + if (initializer instanceof PsiNewExpression newExpression + && !PsiDiamondTypeUtil.canChangeContextForDiamond(newExpression, newExpression.getType())) { + initializer = PsiDiamondTypeUtil.expandTopLevelDiamondsInside(newExpression); } substituteTypeParametersInInitializer(initializer, callExpression, argList, methodToSearchFor); ChangeContextUtil.encodeContextInfo(initializer, true); @@ -141,20 +144,23 @@ private static void substituteTypeParametersInInitializer( PsiMethod method ) { Project project = method.getProject(); - PsiSubstitutor psiSubstitutor = JavaPsiFacade.getInstance(project).getResolveHelper() - .inferTypeArguments( - method.getTypeParameters(), - method.getParameterList().getParameters(), - argList.getExpressions(), - PsiSubstitutor.EMPTY, - callExpression, - DefaultParameterTypeInferencePolicy.INSTANCE - ); - RefactoringUtil.replaceMovedMemberTypeParameters(initializer, PsiUtil.typeParametersIterable(method), psiSubstitutor, + PsiSubstitutor psiSubstitutor = JavaPsiFacade.getInstance(project).getResolveHelper().inferTypeArguments( + method.getTypeParameters(), + method.getParameterList().getParameters(), + argList.getExpressions(), + PsiSubstitutor.EMPTY, + callExpression, + DefaultParameterTypeInferencePolicy.INSTANCE + ); + RefactoringUtil.replaceMovedMemberTypeParameters( + initializer, + PsiUtil.typeParametersIterable(method), + psiSubstitutor, JavaPsiFacade.getElementFactory(project) ); } + @RequiredWriteAction private static void removeParametersFromCall(@Nonnull PsiExpressionList argList, IntList parametersToRemove) { PsiExpression[] exprs = argList.getExpressions(); @@ -185,6 +191,7 @@ private static PsiExpression getLast(PsiExpression[] oldArgs) { } @Override + @RequiredReadAction public void findConflicts(IntroduceParameterData data, UsageInfo[] usages, MultiMap conflicts) { PsiMethod method = data.getMethodToReplaceIn(); int parametersCount = method.getParameterList().getParametersCount(); @@ -197,8 +204,8 @@ public void findConflicts(IntroduceParameterData data, UsageInfo[] usages, Multi PsiExpressionList argList = call.getArgumentList(); if (argList != null) { int actualParamLength = argList.getExpressions().length; - if ((method.isVarArgs() && actualParamLength + 1 < parametersCount) || - (!method.isVarArgs() && actualParamLength < parametersCount)) { + if ((method.isVarArgs() && actualParamLength + 1 < parametersCount) + || (!method.isVarArgs() && actualParamLength < parametersCount)) { conflicts.putValue( call, LocalizeValue.localizeTODO( @@ -223,6 +230,7 @@ public void findConflicts(IntroduceParameterData data, UsageInfo[] usages, Multi } @Override + @RequiredWriteAction public boolean processChangeMethodSignature( IntroduceParameterData data, UsageInfo usage, @@ -288,11 +296,12 @@ public static PsiParameter getAnchorParameter(PsiMethod methodToReplaceIn) { return anchorParameter; } + @Override + @RequiredWriteAction public boolean processAddDefaultConstructor(IntroduceParameterData data, UsageInfo usage, UsageInfo[] usages) { - if (!(usage.getElement() instanceof PsiClass) || !isJavaUsage(usage)) { + if (!(usage.getElement() instanceof PsiClass aClass) || !isJavaUsage(usage)) { return true; } - PsiClass aClass = (PsiClass) usage.getElement(); if (!(aClass instanceof PsiAnonymousClass)) { PsiElementFactory factory = JavaPsiFacade.getInstance(data.getProject()).getElementFactory(); PsiMethod constructor = factory.createMethodFromText(aClass.getName() + "(){}", aClass); @@ -307,15 +316,13 @@ public boolean processAddDefaultConstructor(IntroduceParameterData data, UsageIn return false; } - public boolean processAddSuperCall( - IntroduceParameterData data, - UsageInfo usage, - UsageInfo[] usages - ) throws IncorrectOperationException { - if (!(usage.getElement() instanceof PsiMethod) || !isJavaUsage(usage)) { + @Override + @RequiredWriteAction + public boolean processAddSuperCall(IntroduceParameterData data, UsageInfo usage, UsageInfo[] usages) + throws IncorrectOperationException { + if (!(usage.getElement() instanceof PsiMethod constructor) || !isJavaUsage(usage)) { return true; } - PsiMethod constructor = (PsiMethod) usage.getElement(); if (!constructor.isConstructor()) { return true; diff --git a/plugin/src/main/java/com/intellij/java/impl/refactoring/makeStatic/MakeClassStaticProcessor.java b/plugin/src/main/java/com/intellij/java/impl/refactoring/makeStatic/MakeClassStaticProcessor.java index d8b2d998e5..410b9e712a 100644 --- a/plugin/src/main/java/com/intellij/java/impl/refactoring/makeStatic/MakeClassStaticProcessor.java +++ b/plugin/src/main/java/com/intellij/java/impl/refactoring/makeStatic/MakeClassStaticProcessor.java @@ -25,6 +25,7 @@ import com.intellij.java.language.psi.javadoc.PsiDocTag; import com.intellij.java.language.psi.util.PsiUtil; import consulo.annotation.access.RequiredReadAction; +import consulo.annotation.access.RequiredWriteAction; import consulo.language.codeStyle.CodeStyleManager; import consulo.language.codeStyle.CodeStyleSettingsManager; import consulo.language.editor.refactoring.localize.RefactoringLocalize; @@ -40,7 +41,6 @@ import consulo.project.Project; import consulo.usage.UsageInfo; import consulo.util.collection.MultiMap; -import org.jetbrains.annotations.NonNls; import java.util.ArrayList; import java.util.List; @@ -50,12 +50,14 @@ */ public class MakeClassStaticProcessor extends MakeMethodOrClassStaticProcessor { private static final Logger LOG = Logger.getInstance("#com.intellij.refactoring.makeMethodStatic.MakeClassStaticProcessor"); - private List myFieldsToSplit = new ArrayList(); + private List myFieldsToSplit = new ArrayList<>(); public MakeClassStaticProcessor(Project project, PsiClass aClass, Settings settings) { super(project, aClass, settings); } + @Override + @RequiredWriteAction protected void changeSelf(PsiElementFactory factory, UsageInfo[] usages) throws IncorrectOperationException { PsiClass containingClass = myMember.getContainingClass(); @@ -102,7 +104,6 @@ protected void changeSelf(PsiElementFactory factory, UsageInfo[] usages) throws anchor = javaDocHelper.addParameterAfter(classParameterName, anchor); addAssignmentToField(classParameterName, constructor); - } if (mySettings.isMakeFieldParameters()) { @@ -119,14 +120,12 @@ protected void changeSelf(PsiElementFactory factory, UsageInfo[] usages) throws addAssignmentToField(fieldParameter.name, constructor); } for (UsageInfo usage : usages) { - if (usage instanceof InternalUsageInfo) { - PsiElement element = usage.getElement(); - PsiElement referencedElement = ((InternalUsageInfo) usage).getReferencedElement(); - if (referencedElement instanceof PsiField && mySettings.getNameForField((PsiField) referencedElement) != null) { - PsiField field = PsiTreeUtil.getParentOfType(element, PsiField.class); - if (field != null) { - MoveInstanceMembersUtil.moveInitializerToConstructor(factory, constructor, field); - } + if (usage instanceof InternalUsageInfo internalUsageInfo + && internalUsageInfo.getReferencedElement() instanceof PsiField refField + && mySettings.getNameForField(refField) != null) { + PsiField field = PsiTreeUtil.getParentOfType(internalUsageInfo.getElement(), PsiField.class); + if (field != null) { + MoveInstanceMembersUtil.moveInitializerToConstructor(factory, constructor, field); } } } @@ -136,7 +135,6 @@ protected void changeSelf(PsiElementFactory factory, UsageInfo[] usages) throws } } - setupTypeParameterList(); // Add static modifier @@ -145,8 +143,9 @@ protected void changeSelf(PsiElementFactory factory, UsageInfo[] usages) throws modifierList.setModifierProperty(PsiModifier.FINAL, false); } + @RequiredReadAction private void addAssignmentToField(String parameterName, PsiMethod constructor) { - @NonNls String fieldName = convertToFieldName(parameterName); + String fieldName = convertToFieldName(parameterName); PsiManager manager = PsiManager.getInstance(myProject); PsiElementFactory factory = JavaPsiFacade.getInstance(manager.getProject()).getElementFactory(); PsiCodeBlock body = constructor.getBody(); @@ -173,6 +172,8 @@ private String convertToFieldName(String parameterName) { return fieldName; } + @Override + @RequiredWriteAction protected void changeSelfUsage(SelfUsageInfo usageInfo) throws IncorrectOperationException { PsiElement parent = usageInfo.getElement().getParent(); LOG.assertTrue(parent instanceof PsiCallExpression); //either this() or new() @@ -200,6 +201,8 @@ protected void changeSelfUsage(SelfUsageInfo usageInfo) throws IncorrectOperatio } } + @Override + @RequiredWriteAction protected void changeInternalUsage(InternalUsageInfo usage, PsiElementFactory factory) throws IncorrectOperationException { if (!mySettings.isChangeSignature()) { return; @@ -207,26 +210,24 @@ protected void changeInternalUsage(InternalUsageInfo usage, PsiElementFactory fa PsiElement element = usage.getElement(); - if (element instanceof PsiReferenceExpression) { + if (element instanceof PsiReferenceExpression refExpr) { PsiReferenceExpression newRef = null; - if (mySettings.isMakeFieldParameters()) { - PsiElement resolved = ((PsiReferenceExpression) element).resolve(); - if (resolved instanceof PsiField) { - String name = mySettings.getNameForField((PsiField) resolved); + if (mySettings.isMakeFieldParameters() && refExpr.resolve() instanceof PsiField field) { + String name = mySettings.getNameForField(field); + if (name != null) { + name = convertToFieldName(name); if (name != null) { - name = convertToFieldName(name); - if (name != null) { - newRef = (PsiReferenceExpression) factory.createExpressionFromText(name, null); - } + newRef = (PsiReferenceExpression) factory.createExpressionFromText(name, null); } } } if (newRef == null && mySettings.isMakeClassParameter()) { - newRef = - (PsiReferenceExpression) factory.createExpressionFromText( - convertToFieldName(mySettings.getClassParameterName()) + "." + element.getText(), null); + newRef = (PsiReferenceExpression) factory.createExpressionFromText( + convertToFieldName(mySettings.getClassParameterName()) + "." + element.getText(), + null + ); } if (newRef != null) { @@ -243,8 +244,7 @@ else if (mySettings.isMakeClassParameter() && (element instanceof PsiThisExpress myFieldsToSplit.add(field); } } - else if (element instanceof PsiNewExpression && mySettings.isMakeClassParameter()) { - PsiNewExpression newExpression = ((PsiNewExpression) element); + else if (element instanceof PsiNewExpression newExpression && mySettings.isMakeClassParameter()) { LOG.assertTrue(newExpression.getQualifier() == null); String newText = convertToFieldName(mySettings.getClassParameterName()) + "." + newExpression.getText(); PsiExpression expr = factory.createExpressionFromText(newText, null); @@ -252,16 +252,16 @@ else if (element instanceof PsiNewExpression && mySettings.isMakeClassParameter( } } + @Override + @RequiredWriteAction protected void changeExternalUsage(UsageInfo usage, PsiElementFactory factory) throws IncorrectOperationException { - PsiElement element = usage.getElement(); - if (!(element instanceof PsiJavaCodeReferenceElement)) { + if (!(usage.getElement() instanceof PsiJavaCodeReferenceElement methodRef)) { return; } - PsiJavaCodeReferenceElement methodRef = (PsiJavaCodeReferenceElement) element; PsiElement parent = methodRef.getParent(); - if (parent instanceof PsiAnonymousClass) { - parent = parent.getParent(); + if (parent instanceof PsiAnonymousClass anonymousClass) { + parent = anonymousClass.getParent(); } LOG.assertTrue(parent instanceof PsiCallExpression, "call expression expected, found " + parent); @@ -269,14 +269,14 @@ protected void changeExternalUsage(UsageInfo usage, PsiElementFactory factory) t PsiExpression instanceRef; - instanceRef = - call instanceof PsiMethodCallExpression ? ((PsiMethodCallExpression) call).getMethodExpression().getQualifierExpression() : - ((PsiNewExpression) call).getQualifier(); + instanceRef = call instanceof PsiMethodCallExpression methodCall + ? methodCall.getMethodExpression().getQualifierExpression() + : ((PsiNewExpression) call).getQualifier(); PsiElement newQualifier; if (instanceRef == null || instanceRef instanceof PsiSuperExpression) { - PsiClass thisClass = RefactoringChangeUtil.getThisClass(element); - @NonNls String thisText; + PsiClass thisClass = RefactoringChangeUtil.getThisClass(methodRef); + String thisText; if (thisClass.getManager().areElementsEquivalent(thisClass, myMember.getContainingClass())) { thisText = "this"; } @@ -298,7 +298,6 @@ protected void changeExternalUsage(UsageInfo usage, PsiElementFactory factory) t } } - PsiElement anchor = null; PsiExpressionList argList = call.getArgumentList(); PsiExpression[] exprs = argList.getExpressions(); @@ -319,8 +318,7 @@ protected void changeExternalUsage(UsageInfo usage, PsiElementFactory factory) t PsiReferenceExpression fieldRef; String fieldName = fieldParameter.field.getName(); if (newQualifier != null) { - fieldRef = (PsiReferenceExpression) factory.createExpressionFromText( - "a." + fieldName, null); + fieldRef = (PsiReferenceExpression) factory.createExpressionFromText("a." + fieldName, null); fieldRef.getQualifierExpression().replace(instanceRef); } else { @@ -330,13 +328,11 @@ protected void changeExternalUsage(UsageInfo usage, PsiElementFactory factory) t if (anchor != null) { anchor = argList.addAfter(fieldRef, anchor); } + else if (exprs.length > 0) { + anchor = argList.addBefore(fieldRef, exprs[0]); + } else { - if (exprs.length > 0) { - anchor = argList.addBefore(fieldRef, exprs[0]); - } - else { - anchor = argList.add(fieldRef); - } + anchor = argList.add(fieldRef); } } } @@ -346,9 +342,10 @@ protected void changeExternalUsage(UsageInfo usage, PsiElementFactory factory) t instanceRef.replace(newQualifier); } else { - PsiAnonymousClass anonymousClass = ((PsiNewExpression) call).getAnonymousClass(); + PsiNewExpression newExpression = (PsiNewExpression) call; + PsiAnonymousClass anonymousClass = newExpression.getAnonymousClass(); if (anonymousClass != null) { - ((PsiNewExpression) call).getQualifier().delete(); + newExpression.getQualifier().delete(); PsiJavaCodeReferenceElement baseClassReference = anonymousClass.getBaseClassReference(); baseClassReference.replace(((PsiNewExpression) factory.createExpressionFromText( "new " + newQualifier.getText() + "." + baseClassReference.getText() + "()", @@ -356,13 +353,12 @@ protected void changeExternalUsage(UsageInfo usage, PsiElementFactory factory) t )).getClassReference()); } else { - PsiJavaCodeReferenceElement classReference = ((PsiNewExpression) call).getClassReference(); + PsiJavaCodeReferenceElement classReference = newExpression.getClassReference(); LOG.assertTrue(classReference != null); - PsiNewExpression newExpr = - (PsiNewExpression) factory.createExpressionFromText( - "new " + newQualifier.getText() + "." + classReference.getText() + "()", - classReference - ); + PsiNewExpression newExpr = (PsiNewExpression) factory.createExpressionFromText( + "new " + newQualifier.getText() + "." + classReference.getText() + "()", + classReference + ); PsiExpressionList callArgs = call.getArgumentList(); if (callArgs != null) { PsiExpressionList argumentList = newExpr.getArgumentList(); @@ -426,11 +422,11 @@ protected void findExternalUsages(List result) { } } + @RequiredReadAction private void findDefaultConstructorReferences(List result) { for (PsiReference ref : ReferencesSearch.search(myMember)) { PsiElement element = ref.getElement(); - if (element.getParent() instanceof PsiNewExpression) { - PsiNewExpression newExpression = (PsiNewExpression) element.getParent(); + if (element.getParent() instanceof PsiNewExpression newExpression) { PsiElement qualifier = newExpression.getQualifier(); if (qualifier instanceof PsiThisExpression) { qualifier = null; diff --git a/plugin/src/main/java/com/intellij/java/impl/refactoring/makeStatic/MakeMethodStaticProcessor.java b/plugin/src/main/java/com/intellij/java/impl/refactoring/makeStatic/MakeMethodStaticProcessor.java index cdbcb531f7..827ff59981 100644 --- a/plugin/src/main/java/com/intellij/java/impl/refactoring/makeStatic/MakeMethodStaticProcessor.java +++ b/plugin/src/main/java/com/intellij/java/impl/refactoring/makeStatic/MakeMethodStaticProcessor.java @@ -223,6 +223,7 @@ protected void changeExternalUsage(UsageInfo usage, PsiElementFactory factory) } } + if (mySettings.isMakeFieldParameters()) { List parameters = mySettings.getParameterOrderList(); diff --git a/plugin/src/main/java/com/intellij/java/impl/refactoring/memberPullUp/PullUpConflictsUtil.java b/plugin/src/main/java/com/intellij/java/impl/refactoring/memberPullUp/PullUpConflictsUtil.java index 5e2104226d..f84aa906ef 100644 --- a/plugin/src/main/java/com/intellij/java/impl/refactoring/memberPullUp/PullUpConflictsUtil.java +++ b/plugin/src/main/java/com/intellij/java/impl/refactoring/memberPullUp/PullUpConflictsUtil.java @@ -27,6 +27,7 @@ import com.intellij.java.language.psi.util.PsiUtil; import com.intellij.java.language.psi.util.TypeConversionUtil; 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; @@ -56,6 +57,7 @@ public class PullUpConflictsUtil { private PullUpConflictsUtil() { } + @RequiredReadAction public static MultiMap checkConflicts( MemberInfo[] infos, PsiClass subclass, @@ -67,6 +69,7 @@ public static MultiMap checkConflicts( return checkConflicts(infos, subclass, superClass, targetPackage, targetDirectory, interfaceContainmentVerifier, true); } + @RequiredReadAction public static MultiMap checkConflicts( MemberInfo[] infos, @Nonnull final PsiClass subclass, @@ -76,8 +79,8 @@ public static MultiMap checkConflicts( InterfaceContainmentVerifier interfaceContainmentVerifier, boolean movedMembers2Super ) { - final Set movedMembers = new HashSet(); - Set abstractMethods = new HashSet(); + final Set movedMembers = new HashSet<>(); + Set abstractMethods = new HashSet<>(); boolean isInterfaceTarget; PsiElement targetRepresentativeElement; if (superClass != null) { @@ -90,12 +93,12 @@ public static MultiMap checkConflicts( } for (MemberInfo info : infos) { PsiMember member = info.getMember(); - if (member instanceof PsiMethod) { + if (member instanceof PsiMethod method) { if (!info.isToAbstract() && !isInterfaceTarget) { - movedMembers.add(member); + movedMembers.add(method); } else { - abstractMethods.add((PsiMethod) member); + abstractMethods.add(method); } } else { @@ -103,13 +106,11 @@ public static MultiMap checkConflicts( } } final MultiMap conflicts = new MultiMap<>(); - Set abstrMethods = new HashSet(abstractMethods); + Set abstrMethods = new HashSet<>(abstractMethods); if (superClass != null) { for (PsiMethod method : subclass.getMethods()) { - if (!movedMembers.contains(method) && !method.hasModifierProperty(PsiModifier.PRIVATE)) { - if (method.findSuperMethods(superClass).length > 0) { - abstrMethods.add(method); - } + if (!movedMembers.contains(method) && !method.isPrivate() && method.findSuperMethods(superClass).length > 0) { + abstrMethods.add(method); } } } @@ -136,8 +137,8 @@ public static MultiMap checkConflicts( conflicts.putValue( superClass, LocalizeValue.localizeTODO( - RefactoringUIUtil.getDescription(superClass, true) + " won't be accessible from " + - RefactoringUIUtil.getDescription(targetPackage, true) + RefactoringUIUtil.getDescription(superClass, true) + + " won't be accessible from " + RefactoringUIUtil.getDescription(targetPackage, true) ) ); } @@ -145,7 +146,7 @@ public static MultiMap checkConflicts( } } // check if moved methods use other members in the classes between Subclass and Superclass - List checkModuleConflictsList = new ArrayList(); + List checkModuleConflictsList = new ArrayList<>(); for (PsiMember member : movedMembers) { if (member instanceof PsiMethod || member instanceof PsiClass && !(member instanceof PsiCompiledElement)) { ClassMemberReferencesVisitor visitor = movedMembers2Super @@ -153,9 +154,9 @@ public static MultiMap checkConflicts( member, movedMembers, abstractMethods, - subclass, - superClass, - superClass != null ? null : targetPackage, conflicts, + subclass, superClass, + superClass != null ? null : targetPackage, + conflicts, interfaceContainmentVerifier ) : new ConflictingUsagesOfSuperClassMembers(member, subclass, targetPackage, movedMembers, conflicts); @@ -180,14 +181,11 @@ public static MultiMap checkConflicts( if (fqName != null) { packageName = StringUtil.getPackageName(fqName); } + else if (PsiTreeUtil.getParentOfType(subclass, PsiFile.class) instanceof PsiClassOwner classOwner) { + packageName = classOwner.getPackageName(); + } else { - PsiFile psiFile = PsiTreeUtil.getParentOfType(subclass, PsiFile.class); - if (psiFile instanceof PsiClassOwner) { - packageName = ((PsiClassOwner) psiFile).getPackageName(); - } - else { - packageName = null; - } + packageName = null; } final boolean toDifferentPackage = !Comparing.strEqual(targetPackage.getQualifiedName(), packageName); for (final PsiMethod abstractMethod : abstractMethods) { @@ -196,7 +194,7 @@ public static MultiMap checkConflicts( protected void visitClassMemberReferenceElement(PsiMember classMember, PsiJavaCodeReferenceElement classMemberReference) { if (classMember != null && willBeMoved(classMember, movedMembers)) { boolean isAccessible = false; - if (classMember.hasModifierProperty(PsiModifier.PRIVATE)) { + if (classMember.isPrivate()) { isAccessible = true; } else if (classMember.hasModifierProperty(PsiModifier.PACKAGE_LOCAL) && @@ -217,7 +215,7 @@ else if (classMember.hasModifierProperty(PsiModifier.PACKAGE_LOCAL) && if (!isInterfaceTarget) { String message = "Can't make " + RefactoringUIUtil.getDescription(abstractMethod, false) + " abstract as it won't be accessible from the subclass."; - conflicts.putValue(abstractMethod, LocalizeValue.localizeTODO(CommonRefactoringUtil.capitalize(message))); + conflicts.putValue(abstractMethod, LocalizeValue.localizeTODO(message)); } } } @@ -229,41 +227,35 @@ private static void checkInterfaceTarget(MemberInfo[] infos, MultiMap conflictsList - ) { + @RequiredReadAction + private static void checkSuperclassMembers(PsiClass superClass, MemberInfo[] infos, MultiMap conflictsList) { for (MemberInfo info : infos) { PsiMember member = info.getMember(); boolean isConflict = false; - if (member instanceof PsiField) { - String name = member.getName(); - - isConflict = superClass.findFieldByName(name, false) != null; + if (member instanceof PsiField field) { + isConflict = superClass.findFieldByName(field.getName(), false) != null; } - else if (member instanceof PsiMethod) { + else if (member instanceof PsiMethod method) { PsiSubstitutor superSubstitutor = TypeConversionUtil.getSuperClassSubstitutor(superClass, member.getContainingClass(), PsiSubstitutor.EMPTY); - MethodSignature signature = ((PsiMethod) member).getSignature(superSubstitutor); + MethodSignature signature = method.getSignature(superSubstitutor); PsiMethod superClassMethod = MethodSignatureUtil.findMethodBySignature(superClass, signature, false); isConflict = superClassMethod != null; } @@ -276,27 +268,25 @@ else if (member instanceof PsiMethod) { conflictsList.putValue(superClass, message.capitalize()); } - if (member instanceof PsiMethod) { - PsiMethod method = (PsiMethod) member; + if (member instanceof PsiMethod method) { PsiModifierList modifierList = method.getModifierList(); if (!modifierList.hasModifierProperty(PsiModifier.PRIVATE)) { for (PsiClass subClass : ClassInheritorsSearch.search(superClass)) { if (method.getContainingClass() != subClass) { - MethodSignature signature = ((PsiMethod) member).getSignature(TypeConversionUtil.getSuperClassSubstitutor( - superClass, - subClass, - PsiSubstitutor.EMPTY - )); - PsiMethod wouldBeOverriden = MethodSignatureUtil.findMethodBySignature(subClass, signature, false); - if (wouldBeOverriden != null && VisibilityUtil.compare( - VisibilityUtil.getVisibilityModifier(wouldBeOverriden.getModifierList()), + MethodSignature signature = method.getSignature( + TypeConversionUtil.getSuperClassSubstitutor(superClass, subClass, PsiSubstitutor.EMPTY) + ); + PsiMethod wouldBeOverridden = MethodSignatureUtil.findMethodBySignature(subClass, signature, false); + if (wouldBeOverridden != null && VisibilityUtil.compare( + VisibilityUtil.getVisibilityModifier(wouldBeOverridden.getModifierList()), VisibilityUtil.getVisibilityModifier(modifierList) ) > 0) { conflictsList.putValue( - wouldBeOverriden, + wouldBeOverridden, LocalizeValue.localizeTODO(CommonRefactoringUtil.capitalize( - RefactoringUIUtil.getDescription(method, true) + " in super class would clash " + - "with local method from " + RefactoringUIUtil.getDescription(subClass, true) + RefactoringUIUtil.getDescription(method, true) + + " in super class would clash with local method from " + + RefactoringUIUtil.getDescription(subClass, true) )) ); } @@ -305,6 +295,7 @@ else if (member instanceof PsiMethod) { } } } + } private static boolean willBeMoved(PsiElement element, Set movedMembers) { @@ -326,8 +317,7 @@ private static class ConflictingUsagesOfSuperClassMembers extends ClassMemberRef private MultiMap myConflicts; public ConflictingUsagesOfSuperClassMembers( - PsiMember member, - PsiClass aClass, + PsiMember member, PsiClass aClass, PsiJavaPackage targetPackage, Set movedMembers, MultiMap conflicts @@ -352,7 +342,7 @@ protected void visitClassMemberReferenceElement(PsiMember classMember, PsiJavaCo LocalizeValue.localizeTODO(RefactoringUIUtil.getDescription(classMember, true) + " won't be accessible") ); } - else if (classMember.hasModifierProperty(PsiModifier.PROTECTED) && !mySubClass.isInheritor(containingClass, true)) { + else if (classMember.isProtected() && !mySubClass.isInheritor(containingClass, true)) { myConflicts.putValue( myMember, LocalizeValue.localizeTODO(RefactoringUIUtil.getDescription(classMember, true) + " won't be accessible") @@ -395,14 +385,11 @@ private static class ConflictingUsagesOfSubClassMembers extends ClassMemberRefer myInterfaceContainmentVerifier = interfaceContainmentVerifier; } - protected void visitClassMemberReferenceElement( - PsiMember classMember, - PsiJavaCodeReferenceElement classMemberReference - ) { + @Override + protected void visitClassMemberReferenceElement(PsiMember classMember, PsiJavaCodeReferenceElement classMemberReference) { if (classMember != null && RefactoringHierarchyUtil.isMemberBetween(mySuperClass, mySubclass, classMember)) { - if (classMember.hasModifierProperty(PsiModifier.STATIC) - && !willBeMoved(classMember, myMovedMembers)) { + if (classMember.isStatic() && !willBeMoved(classMember, myMovedMembers)) { boolean isAccessible; if (mySuperClass != null) { isAccessible = PsiUtil.isAccessible(classMember, mySuperClass, null); @@ -411,7 +398,7 @@ else if (myTargetPackage != null) { isAccessible = PsiUtil.isAccessibleFromPackage(classMember, myTargetPackage); } else { - isAccessible = classMember.hasModifierProperty(PsiModifier.PUBLIC); + isAccessible = classMember.isPublic(); } if (!isAccessible) { LocalizeValue message = RefactoringLocalize.zeroUses1WhichIsNotAccessibleFromTheSuperclass( @@ -436,10 +423,9 @@ else if (myTargetPackage != null) { private boolean existsInSuperClass(PsiElement classMember) { - if (!(classMember instanceof PsiMethod)) { + if (!(classMember instanceof PsiMethod method)) { return false; } - PsiMethod method = ((PsiMethod) classMember); if (myInterfaceContainmentVerifier.checkedInterfacesContain(method)) { return true; } @@ -450,6 +436,4 @@ private boolean existsInSuperClass(PsiElement classMember) { return methodBySignature != null; } } - - } diff --git a/plugin/src/main/java/com/intellij/java/impl/refactoring/memberPullUp/PullUpDialog.java b/plugin/src/main/java/com/intellij/java/impl/refactoring/memberPullUp/PullUpDialog.java index d441c7dde2..dc9808ffbf 100644 --- a/plugin/src/main/java/com/intellij/java/impl/refactoring/memberPullUp/PullUpDialog.java +++ b/plugin/src/main/java/com/intellij/java/impl/refactoring/memberPullUp/PullUpDialog.java @@ -29,6 +29,7 @@ import com.intellij.java.language.psi.util.MethodSignatureUtil; import com.intellij.java.language.psi.util.PsiUtil; import com.intellij.java.language.psi.util.TypeConversionUtil; +import consulo.annotation.access.RequiredReadAction; import consulo.application.HelpManager; import consulo.language.editor.refactoring.classMember.MemberInfoModel; import consulo.language.editor.refactoring.localize.RefactoringLocalize; @@ -41,6 +42,7 @@ import consulo.language.statistician.StatisticsManager; import consulo.project.Project; import consulo.ui.Component; +import consulo.ui.annotation.RequiredUIAccess; import consulo.ui.ex.awtUnsafe.TargetAWT; import consulo.util.lang.Comparing; import jakarta.annotation.Nonnull; @@ -48,7 +50,6 @@ import javax.swing.*; import java.awt.*; import java.awt.event.ItemEvent; -import java.awt.event.ItemListener; import java.util.List; /** @@ -59,11 +60,8 @@ public class PullUpDialog extends PullUpDialogBase PullUpProcessor.checkedInterfacesContain(myMemberInfos, psiMethod); private static final String PULL_UP_STATISTICS_KEY = "pull.up##"; @@ -84,10 +82,12 @@ public PullUpDialog( init(); } + @RequiredUIAccess public int getJavaDocPolicy() { return myJavaDocPanel.getPolicy(); } + @Override protected String getDimensionServiceKey() { return "#com.intellij.refactoring.memberPullUp.PullUpDialog"; } @@ -99,19 +99,18 @@ InterfaceContainmentVerifier getContainmentVerifier() { @Override protected void initClassCombo(JComboBox classCombo) { classCombo.setRenderer(new ClassCellRenderer(classCombo.getRenderer())); - classCombo.addItemListener(new ItemListener() { - public void itemStateChanged(ItemEvent e) { - if (e.getStateChange() == ItemEvent.SELECTED) { - if (myMemberSelectionPanel != null) { - ((MyMemberInfoModel) myMemberInfoModel).setSuperClass(getSuperClass()); - myMemberSelectionPanel.getTable().setMemberInfos(myMemberInfos); - myMemberSelectionPanel.getTable().fireExternalDataChange(); - } + classCombo.addItemListener(e -> { + if (e.getStateChange() == ItemEvent.SELECTED) { + if (myMemberSelectionPanel != null) { + ((MyMemberInfoModel) myMemberInfoModel).setSuperClass(getSuperClass()); + myMemberSelectionPanel.getTable().setMemberInfos(myMemberInfos); + myMemberSelectionPanel.getTable().fireExternalDataChange(); } } }); } + @Override protected PsiClass getPreselection() { PsiClass preselection = RefactoringHierarchyUtil.getNearestBaseClass(myClass, false); @@ -133,10 +132,14 @@ protected PsiClass getPreselection() { return preselection; } + @Override + @RequiredUIAccess protected void doHelpAction() { HelpManager.getInstance().invokeHelp(HelpID.MEMBERS_PULL_UP); } + @Override + @RequiredUIAccess protected void doAction() { if (!myCallback.checkConflicts(this)) { return; @@ -157,17 +160,17 @@ protected void doAction() { } @Override + @RequiredUIAccess protected void addCustomElementsToCentralPanel(JPanel panel) { myJavaDocPanel = new DocCommentPanel(RefactoringLocalize.javadocForAbstracts()); myJavaDocPanel.setPolicy(JavaRefactoringSettings.getInstance().PULL_UP_MEMBERS_JAVADOC); boolean hasJavadoc = false; for (MemberInfo info : myMemberInfos) { - PsiMember member = info.getMember(); if (myMemberInfoModel.isAbstractEnabled(info)) { info.setToAbstract(myMemberInfoModel.isAbstractWhenDisabled(info)); - if (!hasJavadoc && - member instanceof PsiDocCommentOwner && - ((PsiDocCommentOwner) member).getDocComment() != null) { + if (!hasJavadoc + && info.getMember() instanceof PsiDocCommentOwner docCommentOwner + && docCommentOwner.getDocComment() != null) { hasJavadoc = true; } } @@ -194,6 +197,7 @@ public MyMemberInfoModel() { } @Override + @RequiredReadAction public boolean isMemberEnabled(MemberInfo member) { PsiClass currentSuperClass = getSuperClass(); if (currentSuperClass == null) { @@ -211,54 +215,43 @@ public boolean isMemberEnabled(MemberInfo member) { } PsiElement element = member.getMember(); - if (element instanceof PsiClass && ((PsiClass) element).isInterface()) { + if (element instanceof PsiClass psiClass && psiClass.isInterface()) { return true; } - if (element instanceof PsiField) { - return ((PsiModifierListOwner) element).hasModifierProperty(PsiModifier.STATIC); + if (element instanceof PsiField field) { + return field.isStatic(); } - if (element instanceof PsiMethod) { + if (element instanceof PsiMethod method) { PsiSubstitutor superSubstitutor = TypeConversionUtil.getSuperClassSubstitutor(currentSuperClass, myClass, PsiSubstitutor.EMPTY ); - MethodSignature signature = ((PsiMethod) element).getSignature(superSubstitutor); - PsiMethod superClassMethod = MethodSignatureUtil.findMethodBySignature(currentSuperClass, - signature, false - ); + MethodSignature signature = method.getSignature(superSubstitutor); + PsiMethod superClassMethod = MethodSignatureUtil.findMethodBySignature(currentSuperClass, signature, false); if (superClassMethod != null && !PsiUtil.isLanguageLevel8OrHigher(currentSuperClass)) { return false; } - return !((PsiModifierListOwner) element).hasModifierProperty(PsiModifier.STATIC) || PsiUtil - .isLanguageLevel8OrHigher(currentSuperClass); + return !method.isStatic() || PsiUtil.isLanguageLevel8OrHigher(currentSuperClass); } return true; } @Override + @RequiredReadAction public boolean isAbstractEnabled(MemberInfo member) { PsiClass currentSuperClass = getSuperClass(); if (currentSuperClass == null || !currentSuperClass.isInterface()) { return true; } - if (PsiUtil.isLanguageLevel8OrHigher(currentSuperClass)) { - return true; - } - return false; + return PsiUtil.isLanguageLevel8OrHigher(currentSuperClass); } @Override public boolean isAbstractWhenDisabled(MemberInfo member) { PsiClass currentSuperClass = getSuperClass(); - if (currentSuperClass == null) { - return false; - } - if (currentSuperClass.isInterface()) { - PsiMember psiMember = member.getMember(); - if (psiMember instanceof PsiMethod) { - return !psiMember.hasModifierProperty(PsiModifier.STATIC); - } - } - return false; + return currentSuperClass != null + && currentSuperClass.isInterface() + && member.getMember() instanceof PsiMethod method + && !method.isStatic(); } @Override @@ -269,8 +262,7 @@ public int checkForProblems(@Nonnull MemberInfo member) { PsiClass currentSuperClass = getSuperClass(); if (currentSuperClass != null && currentSuperClass.isInterface()) { - PsiMember element = member.getMember(); - if (element.hasModifierProperty(PsiModifier.STATIC)) { + if (member.getMember().isStatic()) { return super.checkForProblems(member); } return OK;