use of com.intellij.refactoring.extractMethod.ExtractMethodProcessor in project intellij-community by JetBrains.
the class ExtractMethodTest method performExtractMethod.
public static boolean performExtractMethod(boolean doRefactor, boolean replaceAllDuplicates, Editor editor, PsiFile file, Project project, final boolean extractChainedConstructor, PsiType returnType, boolean makeStatic, String newNameOfFirstParam, PsiClass targetClass, int... disabledParams) throws PrepareFailedException, IncorrectOperationException {
int startOffset = editor.getSelectionModel().getSelectionStart();
int endOffset = editor.getSelectionModel().getSelectionEnd();
PsiElement[] elements;
PsiExpression expr = CodeInsightUtil.findExpressionInRange(file, startOffset, endOffset);
if (expr != null) {
elements = new PsiElement[] { expr };
} else {
elements = CodeInsightUtil.findStatementsInRange(file, startOffset, endOffset);
}
if (elements.length == 0) {
final PsiExpression expression = IntroduceVariableBase.getSelectedExpression(project, file, startOffset, endOffset);
if (expression != null) {
elements = new PsiElement[] { expression };
}
}
assertTrue(elements.length > 0);
final ExtractMethodProcessor processor = new ExtractMethodProcessor(project, editor, elements, null, "Extract Method", "newMethod", null);
processor.setShowErrorDialogs(false);
processor.setChainedConstructor(extractChainedConstructor);
if (!processor.prepare()) {
return false;
}
if (doRefactor) {
processor.testTargetClass(targetClass);
processor.testPrepare(returnType, makeStatic);
processor.testNullness();
if (disabledParams != null) {
for (int param : disabledParams) {
processor.doNotPassParameter(param);
}
}
if (newNameOfFirstParam != null) {
processor.changeParamName(0, newNameOfFirstParam);
}
ExtractMethodHandler.run(project, editor, processor);
}
if (replaceAllDuplicates) {
final Boolean hasDuplicates = processor.hasDuplicates();
if (hasDuplicates == null || hasDuplicates.booleanValue()) {
final List<Match> duplicates = processor.getDuplicates();
for (final Match match : duplicates) {
if (!match.getMatchStart().isValid() || !match.getMatchEnd().isValid())
continue;
PsiDocumentManager.getInstance(project).commitAllDocuments();
ApplicationManager.getApplication().runWriteAction(() -> {
processor.processMatch(match);
});
}
}
}
return true;
}
use of com.intellij.refactoring.extractMethod.ExtractMethodProcessor in project intellij-community by JetBrains.
the class TempWithQueryHandler method invokeOnVariable.
private static void invokeOnVariable(final PsiFile file, final Project project, final PsiLocalVariable local, final Editor editor) {
if (!CommonRefactoringUtil.checkReadOnlyStatus(project, file))
return;
String localName = local.getName();
final PsiExpression initializer = local.getInitializer();
if (initializer == null) {
String message = RefactoringBundle.getCannotRefactorMessage(RefactoringBundle.message("variable.has.no.initializer", localName));
CommonRefactoringUtil.showErrorHint(project, editor, message, REFACTORING_NAME, HelpID.REPLACE_TEMP_WITH_QUERY);
return;
}
final PsiReference[] refs = ReferencesSearch.search(local, GlobalSearchScope.projectScope(project), false).toArray(PsiReference.EMPTY_ARRAY);
if (refs.length == 0) {
String message = RefactoringBundle.getCannotRefactorMessage(RefactoringBundle.message("variable.is.never.used", localName));
CommonRefactoringUtil.showErrorHint(project, editor, message, REFACTORING_NAME, HelpID.REPLACE_TEMP_WITH_QUERY);
return;
}
final HighlightManager highlightManager = HighlightManager.getInstance(project);
ArrayList<PsiReference> array = new ArrayList<>();
EditorColorsManager manager = EditorColorsManager.getInstance();
final TextAttributes attributes = manager.getGlobalScheme().getAttributes(EditorColors.SEARCH_RESULT_ATTRIBUTES);
for (PsiReference ref : refs) {
PsiElement refElement = ref.getElement();
if (PsiUtil.isAccessedForWriting((PsiExpression) refElement)) {
array.add(ref);
}
if (!array.isEmpty()) {
PsiReference[] refsForWriting = array.toArray(new PsiReference[array.size()]);
highlightManager.addOccurrenceHighlights(editor, refsForWriting, attributes, true, null);
String message = RefactoringBundle.getCannotRefactorMessage(RefactoringBundle.message("variable.is.accessed.for.writing", localName));
CommonRefactoringUtil.showErrorHint(project, editor, message, REFACTORING_NAME, HelpID.REPLACE_TEMP_WITH_QUERY);
WindowManager.getInstance().getStatusBar(project).setInfo(RefactoringBundle.message("press.escape.to.remove.the.highlighting"));
return;
}
}
final ExtractMethodProcessor processor = new ExtractMethodProcessor(project, editor, new PsiElement[] { initializer }, local.getType(), REFACTORING_NAME, localName, HelpID.REPLACE_TEMP_WITH_QUERY);
try {
if (!processor.prepare())
return;
} catch (PrepareFailedException e) {
CommonRefactoringUtil.showErrorHint(project, editor, e.getMessage(), REFACTORING_NAME, HelpID.REPLACE_TEMP_WITH_QUERY);
ExtractMethodHandler.highlightPrepareError(e, file, editor, project);
return;
}
final PsiClass targetClass = processor.getTargetClass();
if (targetClass != null && targetClass.isInterface()) {
String message = RefactoringBundle.message("cannot.replace.temp.with.query.in.interface");
CommonRefactoringUtil.showErrorHint(project, editor, message, REFACTORING_NAME, HelpID.REPLACE_TEMP_WITH_QUERY);
return;
}
if (processor.showDialog()) {
CommandProcessor.getInstance().executeCommand(project, () -> {
final Runnable action = () -> {
try {
processor.doRefactoring();
local.normalizeDeclaration();
PsiExpression initializer1 = local.getInitializer();
PsiExpression[] exprs = new PsiExpression[refs.length];
for (int idx = 0; idx < refs.length; idx++) {
PsiElement ref = refs[idx].getElement();
exprs[idx] = (PsiExpression) ref.replace(initializer1);
}
PsiDeclarationStatement declaration = (PsiDeclarationStatement) local.getParent();
declaration.delete();
highlightManager.addOccurrenceHighlights(editor, exprs, attributes, true, null);
} catch (IncorrectOperationException e) {
LOG.error(e);
}
};
PostprocessReformattingAspect.getInstance(project).postponeFormattingInside(() -> {
ApplicationManager.getApplication().runWriteAction(action);
DuplicatesImpl.processDuplicates(processor, project, editor);
});
}, REFACTORING_NAME, null);
}
WindowManager.getInstance().getStatusBar(project).setInfo(RefactoringBundle.message("press.escape.to.remove.the.highlighting"));
}
use of com.intellij.refactoring.extractMethod.ExtractMethodProcessor in project intellij-community by JetBrains.
the class SuggestedParamTypesTest method doTest.
private void doTest(String... types) throws Exception {
configureByFile(BASE_PATH + getTestName(false) + ".java");
final Editor editor = getEditor();
final PsiFile file = getFile();
final Project project = getProject();
int startOffset = editor.getSelectionModel().getSelectionStart();
int endOffset = editor.getSelectionModel().getSelectionEnd();
PsiElement[] elements;
PsiExpression expr = CodeInsightUtil.findExpressionInRange(file, startOffset, endOffset);
if (expr != null) {
elements = new PsiElement[] { expr };
} else {
elements = CodeInsightUtil.findStatementsInRange(file, startOffset, endOffset);
}
assertTrue(elements.length > 0);
final ExtractMethodProcessor processor = new ExtractMethodProcessor(project, editor, elements, null, "Extract Method", "newMethod", null);
processor.prepare();
for (final VariableData data : processor.getInputVariables().getInputVariables()) {
final PsiExpression[] occurrences = ParameterTablePanel.findVariableOccurrences(elements, data.variable);
final TypeSelectorManager manager = new TypeSelectorManagerImpl(project, data.type, occurrences, true) {
@Override
protected boolean isUsedAfter() {
return processor.isOutputVariable(data.variable);
}
};
final JComponent component = manager.getTypeSelector().getComponent();
if (types.length > 1) {
assertTrue("One type suggested", component instanceof JComboBox);
final DefaultComboBoxModel model = (DefaultComboBoxModel) ((JComboBox) component).getModel();
assertEquals(types.length, model.getSize());
for (int i = 0, typesLength = types.length; i < typesLength; i++) {
String type = types[i];
assertEquals(type, model.getElementAt(i).toString());
}
} else if (types.length == 1) {
assertTrue("Multiple types suggested", component instanceof JLabel);
assertEquals(types[0], ((JLabel) component).getText());
}
}
}
use of com.intellij.refactoring.extractMethod.ExtractMethodProcessor in project intellij-community by JetBrains.
the class SuggestedReturnTypesTest method doTest.
private void doTest(String... types) throws Exception {
configureByFile(BASE_PATH + getTestName(false) + ".java");
final Editor editor = getEditor();
final PsiFile file = getFile();
final Project project = getProject();
int startOffset = editor.getSelectionModel().getSelectionStart();
int endOffset = editor.getSelectionModel().getSelectionEnd();
PsiElement[] elements;
PsiExpression expr = CodeInsightUtil.findExpressionInRange(file, startOffset, endOffset);
if (expr != null) {
elements = new PsiElement[] { expr };
} else {
elements = CodeInsightUtil.findStatementsInRange(file, startOffset, endOffset);
}
assertTrue(elements.length > 0);
final ExtractMethodProcessor processor = new ExtractMethodProcessor(project, editor, elements, null, "Extract Method", "newMethod", null);
processor.prepare();
final PsiExpression[] occurrences = processor.findOccurrences();
final TypeSelectorManager manager = new TypeSelectorManagerImpl(project, processor.getReturnType(), occurrences, true);
final JComponent component = manager.getTypeSelector().getComponent();
if (types.length > 1) {
assertTrue("One type suggested", component instanceof JComboBox);
final DefaultComboBoxModel model = (DefaultComboBoxModel) ((JComboBox) component).getModel();
assertEquals(types.length, model.getSize());
for (int i = 0, typesLength = types.length; i < typesLength; i++) {
String type = types[i];
assertEquals(type, model.getElementAt(i).toString());
}
} else if (types.length == 1) {
assertTrue("Multiple types suggested", component instanceof JLabel);
assertEquals(types[0], ((JLabel) component).getText());
}
}
Aggregations