Merge remote branch 'origin/master'

This commit is contained in:
irengrig
2011-12-14 14:17:42 +04:00
65 changed files with 529 additions and 432 deletions
@@ -15,6 +15,8 @@
*/
package com.intellij.codeInsight.daemon.impl.quickfix;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.util.Computable;
import com.intellij.psi.*;
import com.intellij.psi.controlFlow.ReturnStatementsVisitor;
import com.intellij.psi.util.PsiTypesUtil;
@@ -23,7 +25,7 @@ import org.jetbrains.annotations.Nullable;
import java.util.List;
public class ConvertReturnStatementsVisitor implements ReturnStatementsVisitor {
class ConvertReturnStatementsVisitor implements ReturnStatementsVisitor {
private final PsiElementFactory myFactory;
private final PsiMethod myMethod;
private final DeclarationSearcher mySearcher;
@@ -39,7 +41,11 @@ public class ConvertReturnStatementsVisitor implements ReturnStatementsVisitor {
@Override
public void visit(final List<PsiReturnStatement> returnStatements) throws IncorrectOperationException {
final PsiReturnStatement statement = replaceReturnStatements(returnStatements);
final PsiReturnStatement statement = ApplicationManager.getApplication().runWriteAction(new Computable<PsiReturnStatement>() {
public PsiReturnStatement compute() {
return replaceReturnStatements(returnStatements);
}
});
if (statement != null) {
myLatestReturn = statement;
}
@@ -55,10 +61,14 @@ public class ConvertReturnStatementsVisitor implements ReturnStatementsVisitor {
}
public PsiReturnStatement createReturnInLastStatement() throws IncorrectOperationException {
PsiCodeBlock body = myMethod.getBody();
final String value = generateValue(body.getRBrace());
PsiReturnStatement returnStatement = (PsiReturnStatement) myFactory.createStatementFromText("return " + value+";", myMethod);
return (PsiReturnStatement) body.addBefore(returnStatement, body.getRBrace());
return ApplicationManager.getApplication().runWriteAction(new Computable<PsiReturnStatement>() {
public PsiReturnStatement compute() {
PsiCodeBlock body = myMethod.getBody();
final String value = generateValue(body.getRBrace());
PsiReturnStatement returnStatement = (PsiReturnStatement) myFactory.createStatementFromText("return " + value+";", myMethod);
return (PsiReturnStatement) body.addBefore(returnStatement, body.getRBrace());
}
});
}
@Nullable
@@ -122,60 +122,40 @@ public class MethodReturnTypeFix extends LocalQuickFixAndIntentionActionOnPsiEle
final List<PsiMethod> affectedMethods = changeReturnType(myMethod, myReturnType);
PsiElementFactory factory = JavaPsiFacade.getInstance(project).getElementFactory();
final SourceMethodSelector returnSelector = new SourceMethodSelector(myMethod);
PsiReturnStatement statementToSelect = null;
if (!PsiType.VOID.equals(myReturnType)) {
final ReturnStatementAdder adder = new ReturnStatementAdder(factory, myReturnType, returnSelector);
final ReturnStatementAdder adder = new ReturnStatementAdder(factory, myReturnType);
for (PsiMethod affectedMethod : affectedMethods) {
adder.addReturnForMethod(file, affectedMethod);
PsiReturnStatement statement = adder.addReturnForMethod(file, affectedMethod);
if (statement != null && affectedMethod == myMethod) {
statementToSelect = statement;
}
}
}
final PsiReturnStatement latestReturn = returnSelector.getReturnStatement();
if (latestReturn != null) {
Editor editorForMethod = getEditorForMethod(myMethod, project, editor, latestReturn.getContainingFile());
if (statementToSelect != null) {
Editor editorForMethod = getEditorForMethod(myMethod, project, editor, statementToSelect.getContainingFile());
if (editorForMethod != null) {
selectReturnValueInEditor(latestReturn, editorForMethod);
selectReturnValueInEditor(statementToSelect, editorForMethod);
}
}
}
private static class SourceMethodSelector {
private final PsiMethod mySourceMethod;
private PsiReturnStatement myReturnStatement;
private SourceMethodSelector(final PsiMethod sourceMethod) {
mySourceMethod = sourceMethod;
}
public void accept(final PsiReturnStatement statement, final PsiMethod method) {
if (mySourceMethod.equals(method) && statement != null) {
myReturnStatement = statement;
}
}
public PsiReturnStatement getReturnStatement() {
return myReturnStatement;
}
}
// to clearly separate data
private static class ReturnStatementAdder {
private final PsiElementFactory factory;
private final PsiType myTargetType;
private final SourceMethodSelector mySelector;
private ReturnStatementAdder(@NotNull final PsiElementFactory factory, @NotNull final PsiType targetType,
@NotNull final SourceMethodSelector selector) {
private ReturnStatementAdder(@NotNull final PsiElementFactory factory, @NotNull final PsiType targetType) {
this.factory = factory;
myTargetType = targetType;
mySelector = selector;
}
public void addReturnForMethod(final PsiFile file, final PsiMethod method) {
public PsiReturnStatement addReturnForMethod(final PsiFile file, final PsiMethod method) {
final PsiModifierList modifiers = method.getModifierList();
if (modifiers.hasModifierProperty(PsiModifier.ABSTRACT) || method.getBody() == null) {
return;
return null;
}
try {
@@ -197,15 +177,16 @@ public class MethodReturnTypeFix extends LocalQuickFixAndIntentionActionOnPsiEle
else {
returnStatement = visitor.createReturnInLastStatement();
}
mySelector.accept(returnStatement, method);
if (method.getContainingFile() != file) {
UndoUtil.markPsiFileForUndo(file);
}
return returnStatement;
}
catch (IncorrectOperationException e) {
LOG.error(e);
}
if (method.getContainingFile() != file) {
UndoUtil.markPsiFileForUndo(file);
}
return null;
}
}
@@ -401,4 +382,9 @@ public class MethodReturnTypeFix extends LocalQuickFixAndIntentionActionOnPsiEle
}
return null;
}
@Override
public boolean startInWriteAction() {
return false;
}
}
@@ -18,7 +18,6 @@ package com.intellij.codeInsight.daemon.impl.quickfix;
import com.intellij.codeInsight.CodeInsightUtilBase;
import com.intellij.codeInsight.daemon.QuickFixBundle;
import com.intellij.codeInspection.LocalQuickFixAndIntentionActionOnPsiElement;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Comparing;
@@ -100,4 +99,9 @@ public class RemoveUnusedParameterFix extends LocalQuickFixAndIntentionActionOnP
}
return result.toArray(new ParameterInfoImpl[result.size()]);
}
@Override
public boolean startInWriteAction() {
return false;
}
}
@@ -65,28 +65,36 @@ public class ImplementAbstractMethodHandler {
final PsiElement[][] result = new PsiElement[1][];
ProgressManager.getInstance().runProcessWithProgressSynchronously(new Runnable() {
@Override
public void run() {
final PsiClass psiClass = myMethod.getContainingClass();
if (!psiClass.isValid()) return;
if (!psiClass.isEnum()) {
result[0] = getClassImplementations(psiClass);
} else {
final List<PsiElement> enumConstants = new ArrayList<PsiElement>();
for (PsiField field : psiClass.getFields()) {
if (field instanceof PsiEnumConstant) {
final PsiEnumConstantInitializer initializingClass = ((PsiEnumConstant)field).getInitializingClass();
if (initializingClass != null) {
PsiMethod method = initializingClass.findMethodBySignature(myMethod, true);
if (method == null || !method.getContainingClass().equals(initializingClass)) {
enumConstants.add(initializingClass);
ApplicationManager.getApplication().runReadAction(new Runnable() {
@Override
public void run() {
final PsiClass psiClass = myMethod.getContainingClass();
if (!psiClass.isValid()) return;
if (!psiClass.isEnum()) {
result[0] = getClassImplementations(psiClass);
}
else {
final List<PsiElement> enumConstants = new ArrayList<PsiElement>();
for (PsiField field : psiClass.getFields()) {
if (field instanceof PsiEnumConstant) {
final PsiEnumConstantInitializer initializingClass = ((PsiEnumConstant)field).getInitializingClass();
if (initializingClass != null) {
PsiMethod method = initializingClass.findMethodBySignature(myMethod, true);
if (method == null || !method.getContainingClass().equals(initializingClass)) {
enumConstants.add(initializingClass);
}
}
else {
enumConstants.add(field);
}
}
} else {
enumConstants.add(field);
}
result[0] = PsiUtilBase.toPsiElementArray(enumConstants);
}
}
result[0] = PsiUtilBase.toPsiElementArray(enumConstants);
}
});
}
}, CodeInsightBundle.message("intention.implement.abstract.method.searching.for.descendants.progress"), true, myProject);
@@ -108,6 +116,7 @@ public class ImplementAbstractMethodHandler {
myList = new JBList(result[0]);
myList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
final Runnable runnable = new Runnable(){
@Override
public void run() {
int index = myList.getSelectedIndex();
if (index < 0) return;
@@ -131,6 +140,7 @@ public class ImplementAbstractMethodHandler {
if (!((PsiElement)o).isValid()) return;
}
CommandProcessor.getInstance().executeCommand(myProject, new Runnable() {
@Override
public void run() {
final LinkedHashSet<PsiClass> classes = new LinkedHashSet<PsiClass>();
for (Object o : selection) {
@@ -143,6 +153,7 @@ public class ImplementAbstractMethodHandler {
}
if (!CodeInsightUtilBase.preparePsiElementsForWrite(classes)) return;
ApplicationManager.getApplication().runWriteAction(new Runnable() {
@Override
public void run() {
for (PsiClass psiClass : classes) {
try {
@@ -63,7 +63,11 @@ public class JavaDirectInheritorsSearcher implements QueryExecutor<PsiClass, Dir
return consumer.process(psiClass);
}
final PsiClass superClass = psiClass.getSuperClass();
if (superClass != null && CommonClassNames.JAVA_LANG_OBJECT.equals(superClass.getQualifiedName())) {
if (superClass != null && CommonClassNames.JAVA_LANG_OBJECT.equals(ApplicationManager.getApplication().runReadAction(new Computable<String>() {
public String compute() {
return superClass.getQualifiedName();
}
}))) {
return consumer.process(psiClass);
}
return true;
@@ -182,9 +186,6 @@ public class JavaDirectInheritorsSearcher implements QueryExecutor<PsiClass, Dir
}
}
if (!sameJarClassFound) {
return ContainerUtil.process(sameNamedClasses, consumer);
}
return true;
return sameJarClassFound || ContainerUtil.process(sameNamedClasses, consumer);
}
}
@@ -76,7 +76,7 @@ public class ExtractMethodHandler implements RefactoringActionHandler {
selectAndPass(project, editor, file, callback);
}
public static void selectAndPass(final Project project, final Editor editor, final PsiFile file, final Pass<PsiElement[]> callback) {
public static void selectAndPass(@NotNull final Project project, @NotNull final Editor editor, @NotNull final PsiFile file, @NotNull final Pass<PsiElement[]> callback) {
editor.getScrollingModel().scrollToCaret(ScrollType.MAKE_VISIBLE);
if (!editor.getSelectionModel().hasSelection()) {
final int offset = editor.getCaretModel().getOffset();
@@ -133,26 +133,30 @@ public class ExtractMethodHandler implements RefactoringActionHandler {
private static boolean invokeOnElements(final Project project, final Editor editor, @NotNull final ExtractMethodProcessor processor, final boolean directTypes) {
if (!CommonRefactoringUtil.checkReadOnlyStatus(project, processor.getTargetClass().getContainingFile())) return false;
if (processor.showDialog(directTypes)) {
CommandProcessor.getInstance().executeCommand(project, new Runnable() {
public void run() {
PostprocessReformattingAspect.getInstance(project).postponeFormattingInside(new Runnable() {
public void run() {
try {
processor.doRefactoring();
}
catch (IncorrectOperationException e) {
LOG.error(e);
}
DuplicatesImpl.processDuplicates(processor, project, editor);
}
});
}
}, REFACTORING_NAME, null);
run(project, editor, processor);
DuplicatesImpl.processDuplicates(processor, project, editor);
return true;
}
return false;
}
public static void run(@NotNull final Project project, final Editor editor, final ExtractMethodProcessor processor) {
CommandProcessor.getInstance().executeCommand(project, new Runnable() {
public void run() {
PostprocessReformattingAspect.getInstance(project).postponeFormattingInside(new Runnable() {
public void run() {
try {
processor.doRefactoring();
}
catch (IncorrectOperationException e) {
LOG.error(e);
}
}
});
}
}, REFACTORING_NAME, null);
}
@Nullable
private static ExtractMethodProcessor getProcessor(final PsiElement[] elements,
final Project project,
@@ -77,6 +77,7 @@ import com.intellij.util.VisibilityUtil;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.TestOnly;
import java.util.*;
@@ -495,15 +496,21 @@ public class ExtractMethodProcessor implements MatchProvider {
return showDialog(true);
}
@TestOnly
public void testRun() throws IncorrectOperationException {
testPrepare();
ExtractMethodHandler.run(myProject, myEditor, this);
}
@TestOnly
public void testPrepare() {
myInputVariables.setFoldingAvailable(myInputVariables.isFoldingSelectedByDefault());
myMethodName = myInitialMethodName;
myVariableDatum = new ParameterTablePanel.VariableData[myInputVariables.getInputVariables().size()];
for (int i = 0; i < myInputVariables.getInputVariables().size(); i++) {
myVariableDatum[i] = myInputVariables.getInputVariables().get(i);
}
doRefactoring();
}
/**
@@ -544,7 +551,13 @@ public class ExtractMethodProcessor implements MatchProvider {
final Map<PsiMethodCallExpression, PsiMethod> overloadsResolveMap = new HashMap<PsiMethodCallExpression, PsiMethod>();
final Runnable collectOverloads = new Runnable() {
public void run() {
overloadsResolveMap.putAll(ExtractMethodUtil.encodeOverloadTargets(myTargetClass, processConflictsScope, myMethodName, myCodeFragmentMember));
ApplicationManager.getApplication().runReadAction(new Runnable() {
public void run() {
Map<PsiMethodCallExpression, PsiMethod> overloads =
ExtractMethodUtil.encodeOverloadTargets(myTargetClass, processConflictsScope, myMethodName, myCodeFragmentMember);
overloadsResolveMap.putAll(overloads);
}
});
}
};
final Runnable extract = new Runnable() {
@@ -22,18 +22,17 @@ package com.intellij.refactoring.extractMethodObject;
import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.Result;
import com.intellij.openapi.command.CommandProcessor;
import com.intellij.openapi.command.WriteCommandAction;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.LogicalPosition;
import com.intellij.openapi.editor.RangeMarker;
import com.intellij.openapi.editor.ScrollType;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Pass;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.*;
import com.intellij.psi.PsiDocumentManager;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.refactoring.HelpID;
import com.intellij.refactoring.RefactoringActionHandler;
import com.intellij.refactoring.RefactoringBundle;
@@ -41,7 +40,6 @@ import com.intellij.refactoring.extractMethod.ExtractMethodHandler;
import com.intellij.refactoring.extractMethod.PrepareFailedException;
import com.intellij.refactoring.util.CommonRefactoringUtil;
import com.intellij.refactoring.util.duplicates.DuplicatesImpl;
import com.intellij.usageView.UsageInfo;
import org.jetbrains.annotations.NotNull;
public class ExtractMethodObjectHandler implements RefactoringActionHandler {
@@ -55,7 +53,7 @@ public class ExtractMethodObjectHandler implements RefactoringActionHandler {
});
}
private void invokeOnElements(final Project project, final Editor editor, PsiFile file, PsiElement[] elements) {
private void invokeOnElements(@NotNull final Project project, @NotNull final Editor editor, @NotNull PsiFile file, @NotNull PsiElement[] elements) {
if (elements.length == 0) {
String message = RefactoringBundle
.getCannotRefactorMessage(RefactoringBundle.message("selected.block.should.represent.a.set.of.statements.or.an.expression"));
@@ -75,41 +73,49 @@ public class ExtractMethodObjectHandler implements RefactoringActionHandler {
}
if (!CommonRefactoringUtil.checkReadOnlyStatus(project, extractProcessor.getTargetClass().getContainingFile())) return;
if (extractProcessor.showDialog()) {
run(project, editor, processor, extractProcessor);
}
}
public static void run(@NotNull final Project project,
@NotNull final Editor editor,
@NotNull final ExtractMethodObjectProcessor processor,
@NotNull final ExtractMethodObjectProcessor.MyExtractMethodProcessor extractProcessor) {
final int offset = editor.getCaretModel().getOffset();
final RangeMarker marker = editor.getDocument().createRangeMarker(new TextRange(offset, offset));
if (extractProcessor.showDialog()) {
CommandProcessor.getInstance().executeCommand(project, new Runnable() {
public void run() {
ApplicationManager.getApplication().runWriteAction(new Runnable() {
@Override
public void run() {
extractProcessor.doRefactoring();
}
});
processor.run();
processor.runChangeSignature();
PsiDocumentManager.getInstance(project).commitAllDocuments();
if (processor.isCreateInnerClass()) {
processor.moveUsedMethodsToInner();
DuplicatesImpl.processDuplicates(extractProcessor, project, editor);
CommandProcessor.getInstance().executeCommand(project, new Runnable() {
public void run() {
ApplicationManager.getApplication().runWriteAction(new Runnable() {
@Override
public void run() {
extractProcessor.doRefactoring();
}
ApplicationManager.getApplication().runWriteAction(new Runnable() {
@Override
public void run() {
if (processor.isCreateInnerClass()) {
processor.changeInstanceAccess(project);
}
final PsiElement method = processor.getMethod();
LOG.assertTrue(method != null);
method.delete();
}
});
});
processor.run();
processor.runChangeSignature();
PsiDocumentManager.getInstance(project).commitAllDocuments();
if (processor.isCreateInnerClass()) {
processor.moveUsedMethodsToInner();
DuplicatesImpl.processDuplicates(extractProcessor, project, editor);
}
}, ExtractMethodObjectProcessor.REFACTORING_NAME, ExtractMethodObjectProcessor.REFACTORING_NAME);
editor.getCaretModel().moveToOffset(marker.getStartOffset());
editor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE);
}
ApplicationManager.getApplication().runWriteAction(new Runnable() {
@Override
public void run() {
if (processor.isCreateInnerClass()) {
processor.changeInstanceAccess(project);
}
final PsiElement method = processor.getMethod();
LOG.assertTrue(method != null);
method.delete();
}
});
}
}, ExtractMethodObjectProcessor.REFACTORING_NAME, ExtractMethodObjectProcessor.REFACTORING_NAME);
editor.getCaretModel().moveToOffset(marker.getStartOffset());
marker.dispose();
editor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE);
}
public void invoke(@NotNull final Project project, @NotNull final PsiElement[] elements, final DataContext dataContext) {
@@ -193,7 +193,7 @@ public class ExtractMethodObjectProcessor extends BaseRefactoringProcessor {
}
}
public void moveUsedMethodsToInner() {
void moveUsedMethodsToInner() {
if (!myUsages.isEmpty()) {
if (ApplicationManager.getApplication().isUnitTestMode()) {
for (MethodToMoveUsageInfo usage : myUsages) {
@@ -370,7 +370,7 @@ public class ExtractMethodObjectProcessor extends BaseRefactoringProcessor {
new PsiImmediateClassType(myInnerClass, PsiSubstitutor.EMPTY), infos);
}
public void runChangeSignature() {
void runChangeSignature() {
if (myChangeSignatureProcessor != null) {
myChangeSignatureProcessor.run();
}
@@ -17,6 +17,7 @@ package com.intellij.refactoring.inline;
import com.intellij.codeInsight.TargetElementUtilBase;
import com.intellij.lang.StdLanguages;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.project.Project;
@@ -72,7 +73,11 @@ public class InlineToAnonymousClassHandler extends JavaInlineActionHandler {
if (!ProgressManager.getInstance().runProcessWithProgressSynchronously(new Runnable(){
@Override
public void run() {
inheritors.addAll(ClassInheritorsSearch.search(element).findAll());
ApplicationManager.getApplication().runReadAction(new Runnable() {
public void run() {
inheritors.addAll(ClassInheritorsSearch.search(element).findAll());
}
});
}
}, "Searching for class \"" + element.getQualifiedName() + "\" inheritors ...", true, element.getProject())) return false;
return inheritors.size() == 0;
@@ -30,6 +30,7 @@ import com.intellij.codeInsight.ChangeContextUtil;
import com.intellij.codeInsight.PsiEquivalenceUtil;
import com.intellij.codeInsight.intention.AddAnnotationFix;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ModalityState;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.util.Condition;
@@ -89,6 +90,7 @@ public class PullUpHelper extends BaseRefactoringProcessor{
myManager = mySourceClass.getManager();
}
@NotNull
protected UsageViewDescriptor createUsageViewDescriptor(UsageInfo[] usages) {
return new PullUpUsageViewDescriptor();
}
@@ -119,17 +121,12 @@ public class PullUpHelper extends BaseRefactoringProcessor{
}
}
}
final Runnable replaceMethodDuplicatesRunnable = new Runnable() {
ApplicationManager.getApplication().invokeLater(new Runnable() {
@Override
public void run() {
processMethodsDuplicates();
}
};
if (ApplicationManager.getApplication().isUnitTestMode()) {
replaceMethodDuplicatesRunnable.run();
} else {
ApplicationManager.getApplication().invokeLater(replaceMethodDuplicatesRunnable);
}
}, ModalityState.NON_MODAL, myProject.getDisposed());
}
private void processMethodsDuplicates() {
@@ -33,7 +33,10 @@ import com.intellij.psi.PsiManager;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.refactoring.MoveDestination;
import com.intellij.refactoring.PackageWrapper;
import com.intellij.ui.*;
import com.intellij.ui.CollectionComboBoxModel;
import com.intellij.ui.ComboboxSpeedSearch;
import com.intellij.ui.ComboboxWithBrowseButton;
import com.intellij.ui.EditorComboBox;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
@@ -46,6 +49,7 @@ import java.util.*;
* Date: 9/13/11
*/
public abstract class DestinationFolderComboBox extends ComboboxWithBrowseButton {
private static final String LEAVE_IN_SAME_SOURCE_ROOT = "Leave in same source root";
private PsiDirectory myInitialTargetDirectory;
private VirtualFile[] mySourceRoots;
@@ -81,6 +85,7 @@ public abstract class DestinationFolderComboBox extends ComboboxWithBrowseButton
new ComboboxSpeedSearch(getComboBox()) {
@Override
protected String getElementText(Object element) {
if (element == null) return LEAVE_IN_SAME_SOURCE_ROOT;
if (element instanceof DirectoryChooser.ItemWrapper) {
final VirtualFile virtualFile = ((DirectoryChooser.ItemWrapper)element).getDirectory().getVirtualFile();
final Module module = ModuleUtil.findModuleForFile(virtualFile, project);
@@ -105,7 +110,7 @@ public abstract class DestinationFolderComboBox extends ComboboxWithBrowseButton
setText(getPresentableText(itemWrapper, project));
}
else {
setText("Leave in same source root");
setText(LEAVE_IN_SAME_SOURCE_ROOT);
}
}
});
@@ -43,6 +43,7 @@ import com.intellij.refactoring.RefactoringBundle;
import com.intellij.refactoring.util.CommonRefactoringUtil;
import com.intellij.ui.ReplacePromptDialog;
import com.intellij.util.IncorrectOperationException;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
@@ -56,7 +57,7 @@ public class DuplicatesImpl {
private DuplicatesImpl() {}
public static void invoke(final Project project, Editor editor, final MatchProvider provider) {
public static void invoke(@NotNull final Project project, @NotNull Editor editor, @NotNull MatchProvider provider) {
final List<Match> duplicates = provider.getDuplicates();
int idx = 0;
final Ref<Boolean> showAll = new Ref<Boolean>();
@@ -96,7 +97,7 @@ public class DuplicatesImpl {
return confirmDuplicatePrompt;
}
private static boolean replaceMatch(final Project project, final MatchProvider provider, final Match match, final Editor editor,
private static boolean replaceMatch(final Project project, final MatchProvider provider, final Match match, @NotNull final Editor editor,
final int idx, final int size, Ref<Boolean> showAll, final String confirmDuplicatePrompt) {
final ArrayList<RangeHighlighter> highlighters = new ArrayList<RangeHighlighter>();
highlightMatch(project, editor, match, highlighters);
@@ -172,7 +173,7 @@ public class DuplicatesImpl {
attributes, true, highlighters);
}
public static void processDuplicates(final MatchProvider provider, final Project project, Editor editor) {
public static void processDuplicates(@NotNull MatchProvider provider, @NotNull Project project, @NotNull Editor editor) {
boolean hasDuplicates = provider.hasDuplicates();
if (hasDuplicates) {
final int answer = Messages.showYesNoDialog(project,
@@ -63,6 +63,7 @@ public class MethodDuplicatesHandler implements RefactoringActionHandler {
public static final String REFACTORING_NAME = RefactoringBundle.message("replace.method.code.duplicates.title");
private static final Logger LOG = Logger.getInstance("#" + MethodDuplicatesHandler.class.getName());
@Override
public void invoke(@NotNull final Project project, final Editor editor, PsiFile file, DataContext dataContext) {
final int offset = editor.getCaretModel().getOffset();
final PsiElement element = file.findElementAt(offset);
@@ -98,6 +99,7 @@ public class MethodDuplicatesHandler implements RefactoringActionHandler {
dlg.show();
if (dlg.isOK()) {
ProgressManager.getInstance().runProcessWithProgressSynchronously(new Runnable() {
@Override
public void run() {
ProgressManager.getInstance().getProgressIndicator().setIndeterminate(true);
invokeOnScope(project, method, dlg.getScope(AnalysisUIOptions.getInstance(project), scope, project, module));
@@ -144,6 +146,7 @@ public class MethodDuplicatesHandler implements RefactoringActionHandler {
replaceDuplicate(project, duplicates, methods);
if (!silent) {
final Runnable nothingFoundRunnable = new Runnable() {
@Override
public void run() {
if (duplicates.isEmpty()) {
final String message = RefactoringBundle.message("idea.has.not.found.any.code.that.can.be.replaced.with.method.call",
@@ -167,6 +170,7 @@ public class MethodDuplicatesHandler implements RefactoringActionHandler {
if (progressIndicator != null && progressIndicator.isCanceled()) return;
final Runnable replaceRunnable = new Runnable() {
@Override
public void run() {
for (final PsiMethod method : methods) {
final List<Match> matches = duplicates.get(method);
@@ -174,8 +178,10 @@ public class MethodDuplicatesHandler implements RefactoringActionHandler {
final int duplicatesNo = matches.size();
WindowManager.getInstance().getStatusBar(project).setInfo(getStatusMessage(duplicatesNo));
CommandProcessor.getInstance().executeCommand(project, new Runnable() {
@Override
public void run() {
PostprocessReformattingAspect.getInstance(project).postponeFormattingInside(new Runnable() {
@Override
public void run() {
DuplicatesImpl.invoke(project, new MethodDuplicatesMatchProvider(method, matches));
}
@@ -187,12 +193,7 @@ public class MethodDuplicatesHandler implements RefactoringActionHandler {
}
}
};
if (ApplicationManager.getApplication().isUnitTestMode()) {
replaceRunnable.run();
}
else {
ApplicationManager.getApplication().invokeLater(replaceRunnable, ModalityState.NON_MODAL);
}
ApplicationManager.getApplication().invokeLater(replaceRunnable, ModalityState.NON_MODAL);
}
finally {
a.finish();
@@ -243,6 +244,7 @@ public class MethodDuplicatesHandler implements RefactoringActionHandler {
CommonRefactoringUtil.showErrorHint(project, editor, message, REFACTORING_NAME, HelpID.METHOD_DUPLICATES);
}
@Override
public void invoke(@NotNull Project project, @NotNull PsiElement[] elements, DataContext dataContext) {
throw new UnsupportedOperationException();
}
@@ -256,6 +258,7 @@ public class MethodDuplicatesHandler implements RefactoringActionHandler {
myDuplicates = duplicates;
}
@Override
public PsiElement processMatch(Match match) throws IncorrectOperationException {
match.changeSignature(myMethod);
final PsiClass containingClass = myMethod.getContainingClass();
@@ -352,14 +355,17 @@ public class MethodDuplicatesHandler implements RefactoringActionHandler {
return false;
}
@Override
public List<Match> getDuplicates() {
return myDuplicates;
}
@Override
public boolean hasDuplicates() {
return myDuplicates.isEmpty();
}
@Override
@Nullable
public String getConfirmDuplicatePrompt(final Match match) {
final PsiElement matchStart = match.getMatchStart();
@@ -168,14 +168,12 @@ public class PsiClassImpl extends JavaStubPsiElement<PsiClassStub<?>> implements
PsiElement parent = getParent();
if (parent instanceof PsiJavaFile) {
String packageName = ((PsiJavaFile)parent).getPackageName();
if (packageName.length() > 0) {
return packageName + "." + getName();
}
else {
if (packageName.isEmpty()) {
return getName();
}
return packageName + "." + getName();
}
else if (parent instanceof PsiClass) {
if (parent instanceof PsiClass) {
String parentQName = ((PsiClass)parent).getQualifiedName();
if (parentQName == null) return null;
return parentQName + "." + getName();
@@ -1,4 +1,5 @@
package pack2;
import java.util.List;
public class Usage2 {
@@ -11,7 +11,6 @@ import com.intellij.refactoring.changeSignature.JavaThrownExceptionInfo;
import com.intellij.refactoring.changeSignature.ParameterInfoImpl;
import com.intellij.refactoring.changeSignature.ThrownExceptionInfo;
import com.intellij.refactoring.util.CanonicalTypes;
import com.intellij.testFramework.LightCodeInsightTestCase;
import com.intellij.util.containers.HashSet;
import junit.framework.Assert;
@@ -21,7 +20,7 @@ import java.util.Set;
/**
* @author ven
*/
public class ChangeSignaturePropagationTest extends LightCodeInsightTestCase {
public class ChangeSignaturePropagationTest extends LightRefactoringTestCase {
public void testParamSimple() throws Exception {
parameterPropagationTest();
}
@@ -23,7 +23,6 @@ import com.intellij.refactoring.changeSignature.JavaThrownExceptionInfo;
import com.intellij.refactoring.changeSignature.ParameterInfoImpl;
import com.intellij.refactoring.changeSignature.ThrownExceptionInfo;
import com.intellij.refactoring.util.CanonicalTypes;
import com.intellij.testFramework.LightCodeInsightTestCase;
import com.intellij.util.IncorrectOperationException;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.Nullable;
@@ -33,7 +32,7 @@ import java.util.HashSet;
/**
* @author dsl
*/
public class ChangeSignatureTest extends LightCodeInsightTestCase {
public class ChangeSignatureTest extends LightRefactoringTestCase {
public void testSimple() throws Exception {
doTest(null, null, null, new ParameterInfoImpl[0], new ThrownExceptionInfo[0], false);
}
@@ -6,15 +6,13 @@ package com.intellij.refactoring;
import com.intellij.JavaTestUtil;
import com.intellij.codeInsight.TargetElementUtilBase;
import com.intellij.openapi.command.WriteCommandAction;
import com.intellij.psi.PsiDocumentManager;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiMethod;
import com.intellij.refactoring.extractMethodObject.ExtractMethodObjectHandler;
import com.intellij.refactoring.extractMethodObject.ExtractMethodObjectProcessor;
import com.intellij.refactoring.util.duplicates.DuplicatesImpl;
import com.intellij.testFramework.LightCodeInsightTestCase;
public class ExtractMethodObjectTest extends LightCodeInsightTestCase {
public class ExtractMethodObjectTest extends LightRefactoringTestCase {
@Override
protected String getTestDataPath() {
return JavaTestUtil.getJavaTestDataPath();
@@ -31,26 +29,20 @@ public class ExtractMethodObjectTest extends LightCodeInsightTestCase {
assertTrue(element instanceof PsiMethod);
final PsiMethod method = (PsiMethod) element;
new WriteCommandAction.Simple(getProject()) {
@Override
protected void run() throws Throwable {
final ExtractMethodObjectProcessor processor =
new ExtractMethodObjectProcessor(getProject(), getEditor(), method.getBody().getStatements(), "InnerClass");
final ExtractMethodObjectProcessor.MyExtractMethodProcessor extractProcessor = processor.getExtractProcessor();
extractProcessor.setShowErrorDialogs(false);
extractProcessor.prepare();
extractProcessor.testRun();
processor.setCreateInnerClass(createInnerClass);
processor.run();
processor.runChangeSignature();
if (createInnerClass) {
processor.moveUsedMethodsToInner();
}
DuplicatesImpl.processDuplicates(extractProcessor, getProject(), getEditor());
PsiDocumentManager.getInstance(getProject()).commitAllDocuments();
processor.getMethod().delete();
final ExtractMethodObjectProcessor processor =
new ExtractMethodObjectProcessor(getProject(), getEditor(), method.getBody().getStatements(), "InnerClass");
final ExtractMethodObjectProcessor.MyExtractMethodProcessor extractProcessor = processor.getExtractProcessor();
processor.setCreateInnerClass(createInnerClass);
extractProcessor.setShowErrorDialogs(false);
extractProcessor.prepare();
extractProcessor.testPrepare();
ApplicationManager.getApplication().runWriteAction(new Runnable() {
public void run() {
ExtractMethodObjectHandler.run(getProject(), getEditor(), processor, extractProcessor);
}
}.execute().throwException();
});
checkResultByFile("/refactoring/extractMethodObject/" + testName + ".java" + ".after");
}
@@ -6,14 +6,13 @@ package com.intellij.refactoring;
import com.intellij.JavaTestUtil;
import com.intellij.codeInsight.CodeInsightUtil;
import com.intellij.openapi.command.WriteCommandAction;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiExpression;
import com.intellij.refactoring.extractMethodObject.ExtractMethodObjectHandler;
import com.intellij.refactoring.extractMethodObject.ExtractMethodObjectProcessor;
import com.intellij.refactoring.util.duplicates.DuplicatesImpl;
import com.intellij.testFramework.LightCodeInsightTestCase;
public class ExtractMethodObjectWithMultipleExitPointsTest extends LightCodeInsightTestCase {
public class ExtractMethodObjectWithMultipleExitPointsTest extends LightRefactoringTestCase {
@Override
protected String getTestDataPath() {
return JavaTestUtil.getJavaTestDataPath();
@@ -38,22 +37,21 @@ public class ExtractMethodObjectWithMultipleExitPointsTest extends LightCodeInsi
elements = CodeInsightUtil.findStatementsInRange(myFile, startOffset, endOffset);
}
new WriteCommandAction.Simple(getProject()) {
@Override
protected void run() throws Throwable {
final ExtractMethodObjectProcessor processor =
new ExtractMethodObjectProcessor(getProject(), getEditor(), elements, "Inner");
final ExtractMethodObjectProcessor.MyExtractMethodProcessor extractProcessor = processor.getExtractProcessor();
extractProcessor.setShowErrorDialogs(false);
extractProcessor.prepare();
extractProcessor.testRun();
processor.setCreateInnerClass(createInnerClass);
processor.run();
processor.runChangeSignature();
DuplicatesImpl.processDuplicates(extractProcessor, getProject(), getEditor());
processor.getMethod().delete();
final ExtractMethodObjectProcessor processor =
new ExtractMethodObjectProcessor(getProject(), getEditor(), elements, "Inner");
final ExtractMethodObjectProcessor.MyExtractMethodProcessor extractProcessor = processor.getExtractProcessor();
extractProcessor.setShowErrorDialogs(false);
extractProcessor.prepare();
extractProcessor.testPrepare();
processor.setCreateInnerClass(createInnerClass);
ApplicationManager.getApplication().runWriteAction(new Runnable() {
public void run() {
ExtractMethodObjectHandler.run(getProject(), getEditor(), processor, extractProcessor);
}
}.execute().throwException();
});
checkResultByFile("/refactoring/extractMethodObject/multipleExitPoints/" + testName + ".java" + ".after");
}
@@ -1,7 +1,6 @@
package com.intellij.refactoring;
import com.intellij.JavaTestUtil;
import com.intellij.codeInsight.CodeInsightTestCase;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.projectRoots.impl.JavaSdkImpl;
import com.intellij.openapi.roots.LanguageLevelProjectExtension;
@@ -29,7 +28,7 @@ import java.util.Arrays;
/**
* @author yole
*/
public class ExtractSuperClassTest extends CodeInsightTestCase {
public class ExtractSuperClassTest extends RefactoringTestCase {
public void testFinalFieldInitialization() throws Exception { // IDEADEV-19704
doTest("Test", "TestSubclass", new RefactoringTestUtil.MemberDescriptor("X", PsiClass.class),
new RefactoringTestUtil.MemberDescriptor("x", PsiField.class));
@@ -7,12 +7,11 @@ package com.intellij.refactoring;
import com.intellij.JavaTestUtil;
import com.intellij.analysis.AnalysisScope;
import com.intellij.codeInsight.TargetElementUtilBase;
import com.intellij.openapi.projectRoots.Sdk;
import com.intellij.openapi.projectRoots.impl.JavaSdkImpl;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiMethod;
import com.intellij.refactoring.util.duplicates.MethodDuplicatesHandler;
import com.intellij.testFramework.LightCodeInsightTestCase;
import com.intellij.util.ui.UIUtil;
public abstract class FindMethodDuplicatesBaseTest extends LightCodeInsightTestCase {
@Override
@@ -40,9 +39,11 @@ public abstract class FindMethodDuplicatesBaseTest extends LightCodeInsightTestC
}
return;
}
UIUtil.dispatchAllInvocationEvents();
if (shouldSucceed) {
checkResultByFile(filePath + ".after");
} else {
}
else {
fail("duplicates found");
}
}
@@ -5,8 +5,6 @@
package com.intellij.refactoring;
import com.intellij.JavaTestUtil;
import com.intellij.openapi.projectRoots.Sdk;
import com.intellij.openapi.projectRoots.impl.JavaSdkImpl;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiClass;
import com.intellij.psi.search.GlobalSearchScope;
@@ -105,4 +105,8 @@ public class InplaceIntroduceParameterTest extends AbstractJavaInplaceIntroduceT
return super.invokeImpl(project, localVariable, editor);
}
}
@Override
protected boolean isRunInWriteAction() {
return false;
}
}
@@ -21,7 +21,6 @@ import com.intellij.refactoring.introduceParameter.IntroduceParameterHandler;
import com.intellij.refactoring.introduceParameter.IntroduceParameterProcessor;
import com.intellij.refactoring.introduceParameter.Util;
import com.intellij.refactoring.util.occurrences.ExpressionOccurrenceManager;
import com.intellij.testFramework.LightCodeInsightTestCase;
import com.intellij.testFramework.TestDataPath;
import gnu.trove.TIntArrayList;
import org.jetbrains.annotations.NonNls;
@@ -30,7 +29,7 @@ import org.jetbrains.annotations.Nullable;
import java.util.List;
@TestDataPath("$CONTENT_ROOT/testData")
public class IntroduceParameterTest extends LightCodeInsightTestCase {
public class IntroduceParameterTest extends LightRefactoringTestCase {
@Override
protected String getTestDataPath() {
return JavaTestUtil.getJavaTestDataPath();
@@ -1,16 +1,15 @@
package com.intellij.refactoring;
import com.intellij.JavaTestUtil;
import com.intellij.codeInsight.TargetElementUtilBase;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiNamedElement;
import com.intellij.refactoring.invertBoolean.InvertBooleanProcessor;
import com.intellij.testFramework.LightCodeInsightTestCase;
import com.intellij.JavaTestUtil;
/**
* @author ven
*/
public class InvertBooleanTest extends LightCodeInsightTestCase {
public class InvertBooleanTest extends LightRefactoringTestCase {
@Override
protected String getTestDataPath() {
return JavaTestUtil.getJavaTestDataPath();
@@ -0,0 +1,25 @@
/*
* Copyright 2000-2011 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.refactoring;
import com.intellij.testFramework.LightCodeInsightTestCase;
public abstract class LightRefactoringTestCase extends LightCodeInsightTestCase{
@Override
protected boolean isRunInWriteAction() {
return false;
}
}
@@ -13,11 +13,10 @@ import com.intellij.refactoring.makeStatic.MakeClassStaticProcessor;
import com.intellij.refactoring.makeStatic.MakeStaticUtil;
import com.intellij.refactoring.makeStatic.Settings;
import com.intellij.refactoring.util.ParameterTablePanel;
import com.intellij.testFramework.LightCodeInsightTestCase;
import java.util.ArrayList;
public class MakeClassStaticTest extends LightCodeInsightTestCase {
public class MakeClassStaticTest extends LightRefactoringTestCase {
private static final String TEST_ROOT = "/refactoring/makeClassStatic/";
@Override
@@ -15,6 +15,7 @@
*/
package com.intellij.refactoring;
import com.intellij.JavaTestUtil;
import com.intellij.codeInsight.TargetElementUtilBase;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiMethod;
@@ -22,12 +23,10 @@ import com.intellij.refactoring.makeStatic.MakeMethodStaticProcessor;
import com.intellij.refactoring.makeStatic.MakeStaticUtil;
import com.intellij.refactoring.makeStatic.Settings;
import com.intellij.refactoring.util.ParameterTablePanel;
import com.intellij.testFramework.LightCodeInsightTestCase;
import com.intellij.JavaTestUtil;
import java.util.ArrayList;
public class MakeMethodStaticTest extends LightCodeInsightTestCase {
public class MakeMethodStaticTest extends LightRefactoringTestCase {
@Override
protected String getTestDataPath() {
return JavaTestUtil.getJavaTestDataPath();
@@ -21,7 +21,6 @@ package com.intellij.refactoring;
*/
import com.intellij.JavaTestUtil;
import com.intellij.codeInsight.CodeInsightTestCase;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.projectRoots.impl.JavaSdkImpl;
import com.intellij.openapi.vfs.LocalFileSystem;
@@ -35,7 +34,7 @@ import com.intellij.testFramework.PsiTestUtil;
import java.io.File;
public class MoveClassAndFileTest extends CodeInsightTestCase {
public class MoveClassAndFileTest extends RefactoringTestCase {
public void testAllClassesInFile() throws Exception {
doTest("allClassesInFile", "t", "txt2move.txt", "s.MyClass", "s.MyOneMoreClass");
@@ -1,7 +1,6 @@
package com.intellij.refactoring;
import com.intellij.JavaTestUtil;
import com.intellij.codeInsight.CodeInsightTestCase;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.projectRoots.impl.JavaSdkImpl;
import com.intellij.openapi.vfs.LocalFileSystem;
@@ -17,7 +16,7 @@ import org.jetbrains.annotations.NonNls;
import java.io.File;
public class MoveClassTest extends CodeInsightTestCase {
public class MoveClassTest extends RefactoringTestCase {
public void testContextChange() throws Exception{
doTest("contextChange1", new String[]{"pack1.Class1"}, "pack2");
doTest("contextChange2", new String[]{"pack1.Class1"}, "pack2");
@@ -1,7 +1,6 @@
package com.intellij.refactoring;
import com.intellij.JavaTestUtil;
import com.intellij.codeInsight.CodeInsightTestCase;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.projectRoots.impl.JavaSdkImpl;
import com.intellij.openapi.vfs.LocalFileSystem;
@@ -23,7 +22,7 @@ import java.io.File;
/**
* @author yole
*/
public class MoveClassToInnerTest extends CodeInsightTestCase {
public class MoveClassToInnerTest extends RefactoringTestCase {
public void testContextChange1() throws Exception {
doTest(new String[] { "pack1.Class1" }, "pack2.A");
}
@@ -1,4 +1,3 @@
/*
* Copyright 2000-2011 JetBrains s.r.o.
*
@@ -88,14 +87,22 @@ public class MovePackageAsDirectoryTest extends MultiFileTestCase {
protected void preprocessSrcDir(PsiDirectory srcDirectory) {
final PsiFile empty = srcDirectory.findFile(EMPTY_TXT);
assert empty != null;
empty.delete();
ApplicationManager.getApplication().runWriteAction(new Runnable() {
public void run() {
empty.delete();
}
});
}
@Override
protected void postProcessTargetDir(PsiDirectory targetDirectory) {
final PsiDirectory subdirectory = targetDirectory.findSubdirectory(packageName);
assert subdirectory != null;
subdirectory.createFile(EMPTY_TXT);
ApplicationManager.getApplication().runWriteAction(new Runnable() {
public void run() {
subdirectory.createFile(EMPTY_TXT);
}
});
}
});
}
@@ -12,12 +12,12 @@ import com.intellij.refactoring.listeners.MoveMemberListener;
import com.intellij.refactoring.memberPullUp.PullUpHelper;
import com.intellij.refactoring.util.DocCommentPolicy;
import com.intellij.refactoring.util.classMembers.MemberInfo;
import com.intellij.testFramework.LightCodeInsightTestCase;
import com.intellij.util.ui.UIUtil;
/**
* @author ven
*/
public class PullUpTest extends LightCodeInsightTestCase {
public class PullUpTest extends LightRefactoringTestCase {
private static final String BASE_PATH = "/refactoring/pullUp/";
@@ -124,13 +124,13 @@ public class PullUpTest extends LightCodeInsightTestCase {
PsiClass targetClass = sourceClass.getSuperClass();
if (!targetClass.isWritable()) {
final PsiClass[] interfaces = sourceClass.getInterfaces();
assertTrue(interfaces.length == 1);
assertEquals(1, interfaces.length);
assertTrue(interfaces[0].isWritable());
targetClass = interfaces[0];
}
MemberInfo[] infos = RefactoringTestUtil.findMembers(sourceClass, membersToFind);
final int[] countMoved = new int[]{0};
final int[] countMoved = {0};
final MoveMemberListener listener = new MoveMemberListener() {
@Override
public void memberMoved(PsiClass aClass, PsiMember member) {
@@ -141,6 +141,7 @@ public class PullUpTest extends LightCodeInsightTestCase {
JavaRefactoringListenerManager.getInstance(getProject()).addMoveMembersListener(listener);
final PullUpHelper helper = new PullUpHelper(sourceClass, targetClass, infos, new DocCommentPolicy(DocCommentPolicy.ASIS));
helper.run();
UIUtil.dispatchAllInvocationEvents();
JavaRefactoringListenerManager.getInstance(getProject()).removeMoveMembersListener(listener);
if (checkMemebersMovedCount) {
assertEquals(countMoved[0], membersToFind.length);
@@ -4,21 +4,20 @@
*/
package com.intellij.refactoring;
import com.intellij.JavaTestUtil;
import com.intellij.codeInsight.TargetElementUtilBase;
import com.intellij.psi.*;
import com.intellij.refactoring.memberPushDown.PushDownProcessor;
import com.intellij.refactoring.util.DocCommentPolicy;
import com.intellij.refactoring.util.classMembers.MemberInfo;
import com.intellij.refactoring.util.classMembers.MemberInfoStorage;
import com.intellij.testFramework.LightCodeInsightTestCase;
import com.intellij.JavaTestUtil;
import com.intellij.usageView.UsageInfo;
import com.intellij.util.containers.MultiMap;
import java.util.ArrayList;
import java.util.List;
public class PushDownTest extends LightCodeInsightTestCase {
public class PushDownTest extends LightRefactoringTestCase {
@Override
protected String getTestDataPath() {
return JavaTestUtil.getJavaTestDataPath();
@@ -0,0 +1,25 @@
/*
* Copyright 2000-2011 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.refactoring;
import com.intellij.codeInsight.CodeInsightTestCase;
public abstract class RefactoringTestCase extends CodeInsightTestCase {
@Override
protected boolean isRunInWriteAction() {
return false;
}
}
@@ -2,13 +2,10 @@ package com.intellij.refactoring;
import com.intellij.JavaTestUtil;
import com.intellij.codeInsight.TargetElementUtilBase;
import com.intellij.openapi.projectRoots.Sdk;
import com.intellij.openapi.projectRoots.impl.JavaSdkImpl;
import com.intellij.psi.PsiElement;
import com.intellij.refactoring.rename.RenameProcessor;
import com.intellij.refactoring.rename.RenameUtil;
import com.intellij.refactoring.util.MoveRenameUsageInfo;
import com.intellij.testFramework.LightCodeInsightTestCase;
import com.intellij.usageView.UsageInfo;
import org.junit.Assert;
@@ -17,7 +14,7 @@ import java.util.HashMap;
/**
* @author sashache
*/
public class RenameCollisionsTest extends LightCodeInsightTestCase {
public class RenameCollisionsTest extends LightRefactoringTestCase {
private static final String BASE_PATH = "/refactoring/renameCollisions/";
@Override
@@ -13,10 +13,9 @@ import com.intellij.codeInsight.TargetElementUtilBase;
import com.intellij.psi.PsiElement;
import com.intellij.refactoring.rename.RenameProcessor;
import com.intellij.refactoring.rename.RenameWrongRefHandler;
import com.intellij.testFramework.LightCodeInsightTestCase;
import org.jetbrains.annotations.NonNls;
public class RenameFieldTest extends LightCodeInsightTestCase {
public class RenameFieldTest extends LightRefactoringTestCase {
@Override
protected String getTestDataPath() {
return JavaTestUtil.getJavaTestDataPath();
@@ -13,16 +13,14 @@ import com.intellij.refactoring.rename.JavaNameSuggestionProvider;
import com.intellij.refactoring.rename.RenameProcessor;
import com.intellij.refactoring.rename.RenameWrongRefHandler;
import com.intellij.refactoring.rename.inplace.VariableInplaceRenameHandler;
import com.intellij.testFramework.LightCodeInsightTestCase;
import com.intellij.testFramework.fixtures.CodeInsightTestUtil;
import java.util.Collections;
import java.util.HashSet;
/**
* @author ven
*/
public class RenameLocalTest extends LightCodeInsightTestCase {
public class RenameLocalTest extends LightRefactoringTestCase {
private static final String BASE_PATH = "/refactoring/renameLocal/";
@Override
@@ -4,13 +4,12 @@ import com.intellij.JavaTestUtil;
import com.intellij.psi.*;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.refactoring.replaceConstructorWithFactory.ReplaceConstructorWithFactoryProcessor;
import com.intellij.testFramework.LightCodeInsightTestCase;
import org.jetbrains.annotations.NonNls;
/**
* @author dsl
*/
public class ReplaceConstructorWithFactoryTest extends LightCodeInsightTestCase {
public class ReplaceConstructorWithFactoryTest extends LightRefactoringTestCase {
@Override
protected String getTestDataPath() {
return JavaTestUtil.getJavaTestDataPath();
@@ -1,19 +1,17 @@
package com.intellij.refactoring.changeClassSignature;
import com.intellij.JavaTestUtil;
import com.intellij.codeInsight.TargetElementUtilBase;
import com.intellij.psi.PsiClass;
import com.intellij.psi.PsiElement;
import com.intellij.testFramework.LightCodeInsightTestCase;
import com.intellij.refactoring.LightRefactoringTestCase;
import com.intellij.util.IncorrectOperationException;
import com.intellij.openapi.projectRoots.Sdk;
import com.intellij.openapi.projectRoots.impl.JavaSdkImpl;
import com.intellij.JavaTestUtil;
import org.jetbrains.annotations.NonNls;
/**
* @author dsl
*/
public class ChangeClassSignatureTest extends LightCodeInsightTestCase {
public class ChangeClassSignatureTest extends LightRefactoringTestCase {
@NonNls private static final String DATA_PATH = "/refactoring/changeClassSignature/";
@Override
@@ -1,16 +1,16 @@
package com.intellij.refactoring.convertToInstanceMethod;
import com.intellij.JavaTestUtil;
import com.intellij.codeInsight.TargetElementUtilBase;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiMethod;
import com.intellij.testFramework.LightCodeInsightTestCase;
import com.intellij.JavaTestUtil;
import com.intellij.refactoring.LightRefactoringTestCase;
import com.intellij.util.VisibilityUtil;
/**
* @author dsl
*/
public class ConvertToInstanceMethodTest extends LightCodeInsightTestCase {
public class ConvertToInstanceMethodTest extends LightRefactoringTestCase {
@Override
protected String getTestDataPath() {
return JavaTestUtil.getJavaTestDataPath();
@@ -2,16 +2,14 @@ package com.intellij.refactoring.inline;
import com.intellij.JavaTestUtil;
import com.intellij.codeInsight.TargetElementUtilBase;
import com.intellij.openapi.projectRoots.Sdk;
import com.intellij.openapi.projectRoots.impl.JavaSdkImpl;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiField;
import com.intellij.psi.PsiReference;
import com.intellij.psi.PsiReferenceExpression;
import com.intellij.testFramework.LightCodeInsightTestCase;
import com.intellij.refactoring.LightRefactoringTestCase;
import org.jetbrains.annotations.NonNls;
public class InlineConstantFieldTest extends LightCodeInsightTestCase {
public class InlineConstantFieldTest extends LightRefactoringTestCase {
@Override
protected String getTestDataPath() {
return JavaTestUtil.getJavaTestDataPath();
@@ -16,18 +16,21 @@
package com.intellij.refactoring.inline;
import com.intellij.JavaTestUtil;
import com.intellij.codeInsight.CodeInsightTestCase;
import com.intellij.ide.highlighter.JavaFileType;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.vfs.newvfs.impl.VirtualFileSystemEntry;
import com.intellij.psi.*;
import com.intellij.refactoring.RefactoringTestCase;
import com.intellij.refactoring.util.InlineUtil;
import org.jetbrains.annotations.NonNls;
import java.io.IOException;
/**
* User: anna
* Date: 11/4/11
*/
public class InlineLibraryMethodTest extends CodeInsightTestCase {
public class InlineLibraryMethodTest extends RefactoringTestCase {
@Override
protected String getTestDataPath() {
return JavaTestUtil.getJavaTestDataPath();
@@ -43,9 +46,19 @@ public class InlineLibraryMethodTest extends CodeInsightTestCase {
configureByFile(fileName);
PsiClass fileClass = JavaPsiFacade.getInstance(getProject()).findClass("mycompany.File");
assertTrue(fileClass != null);
PsiFile file = fileClass.getContainingFile();
((VirtualFileSystemEntry)file.getVirtualFile()).setWritable(false);
assertNotNull(fileClass);
final PsiFile file = fileClass.getContainingFile();
ApplicationManager.getApplication().runWriteAction(new Runnable() {
public void run() {
try {
((VirtualFileSystemEntry)file.getVirtualFile()).setWritable(false);
}
catch (IOException e) {
throw new RuntimeException(e);
}
}
});
PsiElement element = null;
PsiMethod[] createTempFiles = fileClass.findMethodsByName("createTempFile", false);
for (PsiMethod createTempFile : createTempFiles) {
@@ -54,7 +67,7 @@ public class InlineLibraryMethodTest extends CodeInsightTestCase {
break;
}
}
assertTrue(element != null);
assertNotNull(element);
PsiMethod method = (PsiMethod)element;
final boolean condition = InlineMethodProcessor.checkBadReturns(method) && !InlineUtil.allUsagesAreTailCalls(method);
assertFalse("Bad returns found", condition);
@@ -16,7 +16,6 @@
package com.intellij.refactoring.inline;
import com.intellij.JavaTestUtil;
import com.intellij.codeInsight.CodeInsightTestCase;
import com.intellij.openapi.projectRoots.impl.JavaSdkImpl;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VirtualFile;
@@ -26,6 +25,7 @@ import com.intellij.psi.PsiMethod;
import com.intellij.psi.impl.source.PostprocessReformattingAspect;
import com.intellij.psi.search.ProjectScope;
import com.intellij.refactoring.MockInlineMethodOptions;
import com.intellij.refactoring.RefactoringTestCase;
import com.intellij.refactoring.util.InlineUtil;
import com.intellij.testFramework.IdeaTestUtil;
import com.intellij.testFramework.PsiTestUtil;
@@ -33,7 +33,7 @@ import com.intellij.testFramework.PsiTestUtil;
import java.io.File;
public class InlineMethodMultifileTest extends CodeInsightTestCase {
public class InlineMethodMultifileTest extends RefactoringTestCase {
private String getRoot() {
return JavaTestUtil.getJavaTestDataPath() + "/refactoring/inlineMethod/multifile/" + getTestName(true);
@@ -6,12 +6,12 @@ import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiMethod;
import com.intellij.psi.PsiReference;
import com.intellij.psi.PsiReferenceExpression;
import com.intellij.refactoring.LightRefactoringTestCase;
import com.intellij.refactoring.MockInlineMethodOptions;
import com.intellij.refactoring.util.InlineUtil;
import com.intellij.testFramework.LightCodeInsightTestCase;
import org.jetbrains.annotations.NonNls;
public class InlineMethodTest extends LightCodeInsightTestCase {
public class InlineMethodTest extends LightRefactoringTestCase {
@Override
protected String getTestDataPath() {
return JavaTestUtil.getJavaTestDataPath();
@@ -2,19 +2,17 @@ package com.intellij.refactoring.inline;
import com.intellij.JavaTestUtil;
import com.intellij.codeInsight.TargetElementUtilBase;
import com.intellij.openapi.projectRoots.Sdk;
import com.intellij.openapi.projectRoots.impl.JavaSdkImpl;
import com.intellij.psi.PsiElement;
import com.intellij.refactoring.BaseRefactoringProcessor;
import com.intellij.refactoring.LightRefactoringTestCase;
import com.intellij.refactoring.util.CommonRefactoringUtil;
import com.intellij.testFramework.LightCodeInsightTestCase;
import org.jetbrains.annotations.NonNls;
/**
* @author yole
*/
public class InlineParameterTest extends LightCodeInsightTestCase {
public class InlineParameterTest extends LightRefactoringTestCase {
@Override
protected String getTestDataPath() {
return JavaTestUtil.getJavaTestDataPath();
@@ -1,7 +1,6 @@
package com.intellij.refactoring.inline;
import com.intellij.JavaTestUtil;
import com.intellij.codeInsight.CodeInsightTestCase;
import com.intellij.openapi.projectRoots.impl.JavaSdkImpl;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VirtualFile;
@@ -9,6 +8,7 @@ import com.intellij.psi.PsiClass;
import com.intellij.psi.PsiElement;
import com.intellij.psi.impl.source.PostprocessReformattingAspect;
import com.intellij.psi.search.ProjectScope;
import com.intellij.refactoring.RefactoringTestCase;
import com.intellij.testFramework.IdeaTestUtil;
import com.intellij.testFramework.PsiTestUtil;
import com.intellij.usageView.UsageInfo;
@@ -19,7 +19,7 @@ import java.io.File;
/**
* @author yole
*/
public class InlineToAnonymousClassMultifileTest extends CodeInsightTestCase {
public class InlineToAnonymousClassMultifileTest extends RefactoringTestCase {
public void testProtectedMember() throws Exception { // IDEADEV-18738
doTest("p1.SubjectWithSuper");
}
@@ -2,13 +2,11 @@ package com.intellij.refactoring.inline;
import com.intellij.JavaTestUtil;
import com.intellij.codeInsight.TargetElementUtilBase;
import com.intellij.openapi.projectRoots.Sdk;
import com.intellij.openapi.projectRoots.impl.JavaSdkImpl;
import com.intellij.psi.PsiCall;
import com.intellij.psi.PsiClass;
import com.intellij.psi.PsiClassType;
import com.intellij.psi.PsiElement;
import com.intellij.testFramework.LightCodeInsightTestCase;
import com.intellij.refactoring.LightRefactoringTestCase;
import com.intellij.usageView.UsageInfo;
import com.intellij.util.containers.MultiMap;
import org.jetbrains.annotations.NonNls;
@@ -18,7 +16,7 @@ import java.util.Iterator;
/**
* @author yole
*/
public class InlineToAnonymousClassTest extends LightCodeInsightTestCase {
public class InlineToAnonymousClassTest extends LightRefactoringTestCase {
@Override
protected String getTestDataPath() {
return JavaTestUtil.getJavaTestDataPath();
@@ -1,19 +1,19 @@
package com.intellij.refactoring.moveMethod;
import com.intellij.JavaTestUtil;
import com.intellij.codeInsight.TargetElementUtilBase;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiMethod;
import com.intellij.psi.PsiVariable;
import com.intellij.refactoring.LightRefactoringTestCase;
import com.intellij.refactoring.move.moveInstanceMethod.MoveInstanceMethodHandler;
import com.intellij.refactoring.move.moveInstanceMethod.MoveInstanceMethodProcessor;
import com.intellij.testFramework.LightCodeInsightTestCase;
import com.intellij.JavaTestUtil;
import com.intellij.util.VisibilityUtil;
/**
* @author ven
*/
public class MoveInstanceMethodTest extends LightCodeInsightTestCase {
public class MoveInstanceMethodTest extends LightRefactoringTestCase {
public void testSimple() throws Exception { doTest(true, 0); }
@@ -57,13 +57,13 @@ public class LanguageLevelModuleExtension extends ModuleExtension<LanguageLevelM
public void setLanguageLevel(final LanguageLevel languageLevel) {
LOG.assertTrue(myWritable, "Writable model can be retrieved from writable ModifiableRootModel");
if (mySource == null && myModule.isLoaded()) { //do not reload project for non-commited modules: j2me|project imports
if (mySource != null && myModule.isLoaded()) { //do not reload project for non-commited modules: j2me|project imports
if (myLanguageLevel != languageLevel) {
final LanguageLevelProjectExtension languageLevelProjectExtension = LanguageLevelProjectExtension.getInstance(myModule.getProject());
final LanguageLevel projectLanguageLevel = languageLevelProjectExtension.getLanguageLevel();
if (!(languageLevel == null && myLanguageLevel == projectLanguageLevel ||
myLanguageLevel == null && languageLevel == projectLanguageLevel)) {
languageLevelProjectExtension.reloadProjectOnLanguageLevelChange(languageLevel, true);
languageLevelProjectExtension.reloadProjectOnLanguageLevelChange(languageLevel == null ? projectLanguageLevel : languageLevel, true);
}
}
}
@@ -412,42 +412,46 @@ public abstract class CodeInsightTestCase extends PsiTestCase {
return false;
}
protected void setupCursorAndSelection(Editor editor) {
Document document = editor.getDocument();
final String text = document.getText();
protected void setupCursorAndSelection(final Editor editor) {
ApplicationManager.getApplication().runWriteAction(new Runnable() {
public void run() {
Document document = editor.getDocument();
final String text = document.getText();
int caretIndex = text.indexOf(CARET_MARKER);
int selStartIndex = text.indexOf(SELECTION_START_MARKER);
int selEndIndex = text.indexOf(SELECTION_END_MARKER);
int caretIndex = text.indexOf(CARET_MARKER);
int selStartIndex = text.indexOf(SELECTION_START_MARKER);
int selEndIndex = text.indexOf(SELECTION_END_MARKER);
final RangeMarker caretMarker = caretIndex >= 0 ? document.createRangeMarker(caretIndex, caretIndex) : null;
final RangeMarker selStartMarker = selStartIndex >= 0 ? document.createRangeMarker(selStartIndex, selStartIndex) : null;
final RangeMarker selEndMarker = selEndIndex >= 0 ? document.createRangeMarker(selEndIndex, selEndIndex) : null;
final RangeMarker caretMarker = caretIndex >= 0 ? document.createRangeMarker(caretIndex, caretIndex) : null;
final RangeMarker selStartMarker = selStartIndex >= 0 ? document.createRangeMarker(selStartIndex, selStartIndex) : null;
final RangeMarker selEndMarker = selEndIndex >= 0 ? document.createRangeMarker(selEndIndex, selEndIndex) : null;
if (caretMarker != null) {
document.deleteString(caretMarker.getStartOffset(), caretMarker.getStartOffset() + CARET_MARKER.length());
}
if (selStartMarker != null) {
document.deleteString(selStartMarker.getStartOffset(), selStartMarker.getStartOffset() + SELECTION_START_MARKER.length());
}
if (selEndMarker != null) {
document.deleteString(selEndMarker.getStartOffset(), selEndMarker.getStartOffset() + SELECTION_END_MARKER.length());
}
if (caretMarker != null) {
document.deleteString(caretMarker.getStartOffset(), caretMarker.getStartOffset() + CARET_MARKER.length());
}
if (selStartMarker != null) {
document.deleteString(selStartMarker.getStartOffset(), selStartMarker.getStartOffset() + SELECTION_START_MARKER.length());
}
if (selEndMarker != null) {
document.deleteString(selEndMarker.getStartOffset(), selEndMarker.getStartOffset() + SELECTION_END_MARKER.length());
}
final String newText = document.getText();
final String newText = document.getText();
if (caretMarker != null) {
int caretLine = StringUtil.offsetToLineNumber(newText, caretMarker.getStartOffset());
int caretCol = caretMarker.getStartOffset() - StringUtil.lineColToOffset(newText, caretLine, 0);
LogicalPosition pos = new LogicalPosition(caretLine, caretCol);
editor.getCaretModel().moveToLogicalPosition(pos);
}
if (caretMarker != null) {
int caretLine = StringUtil.offsetToLineNumber(newText, caretMarker.getStartOffset());
int caretCol = caretMarker.getStartOffset() - StringUtil.lineColToOffset(newText, caretLine, 0);
LogicalPosition pos = new LogicalPosition(caretLine, caretCol);
editor.getCaretModel().moveToLogicalPosition(pos);
}
if (selStartMarker != null) {
editor.getSelectionModel().setSelection(selStartMarker.getStartOffset(), selEndMarker.getStartOffset());
}
if (selStartMarker != null) {
editor.getSelectionModel().setSelection(selStartMarker.getStartOffset(), selEndMarker.getStartOffset());
}
PsiDocumentManager.getInstance(myProject).commitAllDocuments();
PsiDocumentManager.getInstance(myProject).commitAllDocuments();
}
});
}
@Override
@@ -16,6 +16,7 @@
package com.intellij.refactoring;
import com.intellij.codeInsight.CodeInsightTestCase;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VirtualFile;
@@ -45,15 +46,20 @@ public abstract class MultiFileTestCase extends CodeInsightTestCase {
String path = getTestDataPath() + getTestRoot() + testName;
String pathBefore = path + "/before";
VirtualFile rootDir = PsiTestUtil.createTestProjectStructure(myProject, myModule, pathBefore, myFilesToDelete, false);
final VirtualFile rootDir = PsiTestUtil.createTestProjectStructure(myProject, myModule, pathBefore, myFilesToDelete, false);
prepareProject(rootDir);
PsiDocumentManager.getInstance(myProject).commitAllDocuments();
String pathAfter = path + "/after";
VirtualFile rootAfter = LocalFileSystem.getInstance().findFileByPath(pathAfter.replace(File.separatorChar, '/'));
final VirtualFile rootAfter = LocalFileSystem.getInstance().findFileByPath(pathAfter.replace(File.separatorChar, '/'));
performAction.performAction(rootDir, rootAfter);
myProject.getComponent(PostprocessReformattingAspect.class).doPostponedFormatting();
ApplicationManager.getApplication().runWriteAction(new Runnable() {
public void run() {
myProject.getComponent(PostprocessReformattingAspect.class).doPostponedFormatting();
}
});
FileDocumentManager.getInstance().saveAllDocuments();
if (myDoCompare) {
@@ -72,4 +78,9 @@ public abstract class MultiFileTestCase extends CodeInsightTestCase {
protected interface PerformAction {
void performAction(VirtualFile rootDir, VirtualFile rootAfter) throws Exception;
}
@Override
protected boolean isRunInWriteAction() {
return false;
}
}
@@ -154,7 +154,7 @@ public class LiveTemplateSettingsEditor extends JPanel {
panel.add(createTemplateOptionsPanel(), gb.nextLine().next().next().coverColumn(2).weighty(1));
panel.add(createShortContextPanel(allowNoContexts), gb.nextLine().next().fillCellNone().anchor(GridBagConstraints.WEST));
panel.add(createShortContextPanel(allowNoContexts), gb.nextLine().next().weighty(0).fillCellNone().anchor(GridBagConstraints.WEST));
myTemplateEditor.getDocument().addDocumentListener(
new DocumentAdapter() {
@@ -32,11 +32,15 @@ import com.intellij.openapi.project.DumbAwareAction;
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.openapi.ui.InputValidator;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.ui.Splitter;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.ui.*;
import com.intellij.util.*;
import com.intellij.util.Alarm;
import com.intellij.util.NullableFunction;
import com.intellij.util.ObjectUtils;
import com.intellij.util.PlatformIcons;
import com.intellij.util.containers.Convertor;
import com.intellij.util.ui.tree.TreeUtil;
import com.intellij.util.ui.update.UiNotifyConnector;
@@ -92,8 +96,11 @@ public class TemplateListPanel extends JPanel implements Disposable {
createTemplateEditor(MOCK_TEMPLATE, "Tab", MOCK_TEMPLATE.createOptions(), MOCK_TEMPLATE.createContext());
add(createExpandByPanel(), BorderLayout.NORTH);
add(createTable(), BorderLayout.CENTER);
add(myDetailsPanel, BorderLayout.SOUTH);
Splitter splitter = new Splitter(true, 0.9f);
splitter.setFirstComponent(createTable());
splitter.setSecondComponent(myDetailsPanel);
add(splitter, BorderLayout.CENTER);
}
public void dispose() {
@@ -23,10 +23,8 @@ import com.intellij.ide.DataManager;
import com.intellij.lang.Language;
import com.intellij.openapi.actionSystem.PlatformDataKeys;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.Result;
import com.intellij.openapi.command.CommandProcessor;
import com.intellij.openapi.command.UndoConfirmationPolicy;
import com.intellij.openapi.command.WriteCommandAction;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.extensions.Extensions;
import com.intellij.openapi.progress.ProcessCanceledException;
@@ -61,6 +59,7 @@ import com.intellij.usages.rules.PsiElementUsage;
import com.intellij.util.Processor;
import com.intellij.util.containers.HashSet;
import com.intellij.util.containers.MultiMap;
import com.intellij.util.ui.UIUtil;
import gnu.trove.THashSet;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
@@ -152,9 +151,15 @@ public abstract class BaseRefactoringProcessor {
final Ref<Boolean> dumbModeOccurred = new Ref<Boolean>();
final Runnable findUsagesRunnable = new Runnable() {
@Override
public void run() {
try {
refUsages.set(findUsages());
refUsages.set(ApplicationManager.getApplication().runReadAction(new Computable<UsageInfo[]>() {
@Override
public UsageInfo[] compute() {
return findUsages();
}
}));
}
catch (UnknownReferenceTypeException e) {
refErrorLanguage.set(e.getElementLanguage());
@@ -215,14 +220,21 @@ public abstract class BaseRefactoringProcessor {
}
protected void previewRefactoring(final UsageInfo[] usages) {
if (ApplicationManager.getApplication().isUnitTestMode()) {
execute(usages);
return;
}
final UsageViewDescriptor viewDescriptor = createUsageViewDescriptor(usages);
final PsiElement[] elements = viewDescriptor.getElements();
final PsiElement2UsageTargetAdapter[] targets = PsiElement2UsageTargetAdapter.convert(elements);
Factory<UsageSearcher> factory = new Factory<UsageSearcher>() {
@Override
public UsageSearcher create() {
return new UsageSearcher() {
@Override
public void generate(final Processor<Usage> processor) {
ApplicationManager.getApplication().runReadAction(new Runnable() {
@Override
public void run() {
for (int i = 0; i < elements.length; i++) {
elements[i] = targets[i].getElement();
@@ -232,6 +244,7 @@ public abstract class BaseRefactoringProcessor {
});
final Ref<UsageInfo[]> refUsages = new Ref<UsageInfo[]>();
ApplicationManager.getApplication().runReadAction(new Runnable() {
@Override
public void run() {
refUsages.set(findUsages());
}
@@ -272,8 +285,9 @@ public abstract class BaseRefactoringProcessor {
protected void execute(final UsageInfo[] usages) {
CommandProcessor.getInstance().executeCommand(myProject, new Runnable() {
@Override
public void run() {
Collection<UsageInfo> usageInfos = new HashSet<UsageInfo>(Arrays.asList(usages));
Collection<UsageInfo> usageInfos = new LinkedHashSet<UsageInfo>(Arrays.asList(usages));
doRefactoring(usageInfos);
if (isGlobalUndoAction()) CommandProcessor.getInstance().markCurrentCommandAsGlobal(myProject);
}
@@ -343,7 +357,11 @@ public abstract class BaseRefactoringProcessor {
if (!ProgressManager.getInstance().runProcessWithProgressSynchronously(new Runnable() {
@Override
public void run() {
convertUsagesRef.set(UsageInfo2UsageAdapter.convert(usageInfos));
ApplicationManager.getApplication().runReadAction(new Runnable() {
public void run() {
convertUsagesRef.set(UsageInfo2UsageAdapter.convert(usageInfos));
}
});
}
}, "Preprocess usages", true, myProject)) return;
@@ -356,6 +374,7 @@ public abstract class BaseRefactoringProcessor {
final UsageView usageView = viewManager.showUsages(targets, usages, presentation, factory);
final Runnable refactoringRunnable = new Runnable() {
@Override
public void run() {
Set<UsageInfo> usagesToRefactor = getUsageInfosToRefactor(usageView);
if (ensureElementsWritable(usagesToRefactor.toArray(new UsageInfo[usagesToRefactor.size()]), viewDescriptor)) {
@@ -373,7 +392,7 @@ public abstract class BaseRefactoringProcessor {
private static Set<UsageInfo> getUsageInfosToRefactor(final UsageView usageView) {
Set<Usage> excludedUsages = usageView.getExcludedUsages();
Set<UsageInfo> usageInfos = new HashSet<UsageInfo>();
Set<UsageInfo> usageInfos = new LinkedHashSet<UsageInfo>();
for (Usage usage : usageView.getUsages()) {
if (usage instanceof UsageInfo2UsageAdapter && !excludedUsages.contains(usage)) {
UsageInfo usageInfo = ((UsageInfo2UsageAdapter)usage).getUsageInfo();
@@ -401,6 +420,7 @@ public abstract class BaseRefactoringProcessor {
myTransaction = listenerManager.startTransaction();
final Map<RefactoringHelper, Object> preparedData = new HashMap<RefactoringHelper, Object>();
final Runnable prepareHelpersRunnable = new Runnable() {
@Override
public void run() {
for (RefactoringHelper helper : Extensions.getExtensions(RefactoringHelper.EP_NAME)) {
preparedData.put(helper, helper.prepareOperation(writableUsageInfos));
@@ -411,8 +431,8 @@ public abstract class BaseRefactoringProcessor {
ProgressManager.getInstance().runProcessWithProgressSynchronously(prepareHelpersRunnable, "Prepare ...", false, myProject);
ApplicationManager.getApplication().runWriteAction(new Runnable() {
@Override
public void run() {
ApplicationManager.getApplication().assertWriteAccessAllowed();
performRefactoring(writableUsageInfos);
}
});
@@ -423,6 +443,7 @@ public abstract class BaseRefactoringProcessor {
}
myTransaction.commit();
ApplicationManager.getApplication().runWriteAction(new Runnable() {
@Override
public void run() {
performPsiSpoilingRefactoring();
}
@@ -467,60 +488,27 @@ public abstract class BaseRefactoringProcessor {
}
}
/**
* Override in subclasses
*/
protected void prepareTestRun() {
}
public final void run() {
if (ApplicationManager.getApplication().isUnitTestMode()) {
testRun();
ApplicationManager.getApplication().assertIsDispatchThread();
doRun();
UIUtil.dispatchAllInvocationEvents();
UIUtil.dispatchAllInvocationEvents();
return;
}
if (ApplicationManager.getApplication().isWriteAccessAllowed()) {
ApplicationManager.getApplication().invokeLater(new Runnable() {
@Override
public void run() {
doRun();
}
}, myProject.getDisposed());
}
else {
if (ApplicationManager.getApplication().isWriteAccessAllowed()) {
ApplicationManager.getApplication().invokeLater(new Runnable() {
@Override
public void run() {
doRun();
}
}, myProject.getDisposed());
} else {
doRun();
}
doRun();
}
}
private void testRun() {
PsiDocumentManager.getInstance(myProject).commitAllDocuments();
prepareTestRun();
Ref<UsageInfo[]> refUsages = new Ref<UsageInfo[]>(findUsages());
preprocessUsages(refUsages);
final UsageInfo[] usages = refUsages.get();
UsageViewDescriptor descriptor = createUsageViewDescriptor(usages);
if (!ensureElementsWritable(usages, descriptor)) return;
new WriteCommandAction(myProject){
@Override
protected void run(Result result) throws Throwable {
RefactoringListenerManagerImpl listenerManager = (RefactoringListenerManagerImpl)RefactoringListenerManager.getInstance(myProject);
myTransaction = listenerManager.startTransaction();
Map<RefactoringHelper, Object> preparedData = new HashMap<RefactoringHelper, Object>();
for (RefactoringHelper helper : Extensions.getExtensions(RefactoringHelper.EP_NAME)) {
preparedData.put(helper, helper.prepareOperation(usages));
}
performRefactoring(usages);
for (Map.Entry<RefactoringHelper, Object> e : preparedData.entrySet()) {
//noinspection unchecked
e.getKey().performOperation(myProject, e.getValue());
}
myTransaction.commit();
performPsiSpoilingRefactoring();
}
}.execute();
}
public static class ConflictsInTestsException extends RuntimeException {
private final Collection<? extends String> messages;
@@ -577,6 +565,7 @@ public abstract class BaseRefactoringProcessor {
protected ConflictsDialog prepareConflictsDialog(MultiMap<PsiElement, String> conflicts, @Nullable final UsageInfo[] usages) {
final ConflictsDialog conflictsDialog = new ConflictsDialog(myProject, conflicts, usages == null ? null : new Runnable() {
@Override
public void run() {
execute(usages);
}
@@ -16,24 +16,21 @@
package com.intellij.refactoring.changeSignature;
import com.intellij.ide.actions.CopyReferenceAction;
import com.intellij.openapi.command.CommandProcessor;
import com.intellij.openapi.command.undo.BasicUndoableAction;
import com.intellij.openapi.command.undo.UndoManager;
import com.intellij.openapi.command.undo.UndoableAction;
import com.intellij.openapi.command.undo.UnexpectedUndoException;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiManager;
import com.intellij.refactoring.BaseRefactoringProcessor;
import com.intellij.refactoring.RefactoringBundle;
import com.intellij.refactoring.listeners.RefactoringElementAdapter;
import com.intellij.refactoring.listeners.RefactoringElementListener;
import com.intellij.refactoring.listeners.UndoRefactoringElementListener;
import com.intellij.refactoring.listeners.impl.RefactoringTransaction;
import com.intellij.refactoring.util.MoveRenameUsageInfo;
import com.intellij.usageView.UsageInfo;
import com.intellij.usageView.UsageViewUtil;
import com.intellij.util.CommonProcessors;
import com.intellij.util.IncorrectOperationException;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.containers.hash.HashMap;
@@ -113,18 +110,19 @@ public abstract class ChangeSignatureProcessorBase extends BaseRefactoringProces
}
protected void performRefactoring(UsageInfo[] usages) {
final RefactoringElementListener elementListener = getTransaction().getElementListener(myChangeInfo.getMethod());
RefactoringTransaction transaction = getTransaction();
final RefactoringElementListener elementListener = transaction == null ? null : transaction.getElementListener(myChangeInfo.getMethod());
final String fqn = CopyReferenceAction.elementToFqn(myChangeInfo.getMethod());
if (fqn != null) {
UndoableAction action = new BasicUndoableAction() {
public void undo() throws UnexpectedUndoException {
public void undo() {
if (elementListener instanceof UndoRefactoringElementListener) {
((UndoRefactoringElementListener)elementListener).undoElementMovedOrRenamed(myChangeInfo.getMethod(), fqn);
}
}
@Override
public void redo() throws UnexpectedUndoException {
public void redo() {
}
};
UndoManager.getInstance(myProject).undoableActionPerformed(action);
@@ -151,7 +149,7 @@ public abstract class ChangeSignatureProcessorBase extends BaseRefactoringProces
final PsiElement method = myChangeInfo.getMethod();
LOG.assertTrue(method.isValid());
if (myChangeInfo.isNameChanged()) {
if (elementListener != null && myChangeInfo.isNameChanged()) {
elementListener.elementRenamed(method);
}
}
@@ -59,8 +59,6 @@ import java.util.*;
public class RenameProcessor extends BaseRefactoringProcessor {
private static final Logger LOG = Logger.getInstance("#com.intellij.refactoring.rename.RenameProcessor");
@NonNls public static final String FORCE_RENAME_PROCESSOR_TO_THROW_EXCEPTION_ON_BAD_RENAMEABILITY =
"force.rename.processor.to.throw.exception.on.bad.renameability";
protected final LinkedHashMap<PsiElement, String> myAllRenames = new LinkedHashMap<PsiElement, String>();
@@ -197,7 +195,7 @@ public class RenameProcessor extends BaseRefactoringProcessor {
refUsages.set(usagesSet.toArray(new UsageInfo[usagesSet.size()]));
prepareSuccessful();
return true;
return PsiElementRenameHandler.canRename(myProject, null, myPrimaryElement);
}
protected static void assertNonCompileElement(PsiElement element) {
@@ -437,21 +435,6 @@ public class RenameProcessor extends BaseRefactoringProcessor {
return result;
}
protected void prepareTestRun() {
String s = PsiElementRenameHandler.renameabilityStatus(myProject, myPrimaryElement);
if (!StringUtil.isEmpty(s)) {
if (inTestsProduceExceptionOnBadRenameabilityStatus()) {
PsiElementRenameHandler.showErrorMessage(myProject, null, s);
}
return;
}
prepareRenaming(myPrimaryElement, myNewName, myAllRenames);
}
protected boolean inTestsProduceExceptionOnBadRenameabilityStatus() {
return System.getProperty(FORCE_RENAME_PROCESSOR_TO_THROW_EXCEPTION_ON_BAD_RENAMEABILITY) != null;
}
public Collection<String> getNewNames() {
return myAllRenames.values();
}
@@ -353,6 +353,14 @@ public class TestAll implements Test {
}
}
private static Set<String> normalizePaths(String[] array) {
Set<String> answer = new LinkedHashSet<String>(array.length);
for (String path : array) {
answer.add(path.replace('\\', '/'));
}
return answer;
}
public static String[] getClassRoots() {
String testRoots = System.getProperty("test.roots");
if (testRoots != null) {
@@ -363,8 +371,8 @@ public class TestAll implements Test {
if (roots != null) {
if (Comparing.equal(System.getProperty(TestCaseLoader.SKIP_COMMUNITY_TESTS), "true")) {
System.out.println("Skipping community tests");
Set<String> set = new LinkedHashSet<String>(Arrays.asList(roots));
set.removeAll(Arrays.asList(ExternalClasspathClassLoader.getExcludeRoots()));
Set<String> set = normalizePaths(roots);
set.removeAll(normalizePaths(ExternalClasspathClassLoader.getExcludeRoots()));
roots = set.toArray(new String[set.size()]);
}
@@ -77,4 +77,9 @@ public abstract class AbstractInplaceIntroduceTest extends LightPlatformCodeInsi
}
protected abstract AbstractInplaceIntroducer invokeRefactoring();
@Override
protected boolean isRunInWriteAction() {
return false;
}
}
@@ -69,7 +69,7 @@ public abstract class LightPlatformCodeInsightTestCase extends LightPlatformTest
@Override
protected void runTest() throws Throwable {
final Throwable[] throwable = {null};
ApplicationManager.getApplication().runWriteAction(new Runnable() {
Runnable action = new Runnable() {
@Override
public void run() {
CommandProcessor.getInstance().executeCommand(getProject(), new Runnable() {
@@ -78,13 +78,20 @@ public abstract class LightPlatformCodeInsightTestCase extends LightPlatformTest
try {
doRunTest();
} catch (Throwable t) {
}
catch (Throwable t) {
throwable[0] = t;
}
}
}, "", null);
}
});
};
if (isRunInWriteAction()) {
ApplicationManager.getApplication().runWriteAction(action);
}
else {
action.run();
}
if (throwable[0] != null) {
throw throwable[0];
@@ -95,6 +102,10 @@ public abstract class LightPlatformCodeInsightTestCase extends LightPlatformTest
LightPlatformCodeInsightTestCase.super.runTest();
}
protected boolean isRunInWriteAction() {
return true;
}
/**
* Configure test from data file. Data file is usual java, xml or whatever file that needs to be tested except it
* has &lt;caret&gt; marker where caret should be placed when file is loaded in editor and &lt;selection&gt;&lt;/selection&gt;
@@ -544,12 +544,7 @@ public class CodeInsightTestFixtureImpl extends BaseFixture implements CodeInsig
@Override
public void launchAction(@NotNull final IntentionAction action) {
new WriteCommandAction(getProject()) {
@Override
protected void run(final Result result) throws Exception {
ShowIntentionActionsHandler.chooseActionAndInvoke(getFile(), getEditor(), action, action.getText());
}
}.execute().throwException();
ShowIntentionActionsHandler.chooseActionAndInvoke(getFile(), getEditor(), action, action.getText());
}
@Override
@@ -645,14 +640,9 @@ public class CodeInsightTestFixtureImpl extends BaseFixture implements CodeInsig
final String newName,
final boolean searchInComments,
final boolean searchTextOccurrences) {
new WriteCommandAction.Simple(getProject()) {
@Override
protected void run() throws Exception {
final PsiElement substitution = RenamePsiElementProcessor.forElement(element).substituteElementToRename(element, myEditor);
if (substitution == null) return;
new RenameProcessor(getProject(), substitution, newName, searchInComments, searchTextOccurrences).run();
}
}.execute().throwException();
final PsiElement substitution = RenamePsiElementProcessor.forElement(element).substituteElementToRename(element, myEditor);
if (substitution == null) return;
new RenameProcessor(getProject(), substitution, newName, searchInComments, searchTextOccurrences).run();
}
@Override
@@ -54,9 +54,7 @@ public class XVariablesView extends XDebugViewBase {
XDebuggerTree tree = myDebuggerTreePanel.getTree();
if (event == SessionEvent.BEFORE_RESUME || event == SessionEvent.SETTINGS_CHANGED) {
if (myTreeRestorer != null) {
myTreeRestorer.dispose();
}
disposeTreeRestorer();
myFrameEqualityObject = stackFrame != null ? stackFrame.getEqualityObject() : null;
myTreeState = XDebuggerTreeState.saveState(tree);
if (event == SessionEvent.BEFORE_RESUME) {
@@ -70,6 +68,7 @@ public class XVariablesView extends XDebugViewBase {
tree.setRoot(new XStackFrameNode(tree, stackFrame), false);
Object newEqualityObject = stackFrame.getEqualityObject();
if (myFrameEqualityObject != null && newEqualityObject != null && myFrameEqualityObject.equals(newEqualityObject) && myTreeState != null) {
disposeTreeRestorer();
myTreeRestorer = myTreeState.restoreState(tree);
}
}
@@ -80,12 +79,20 @@ public class XVariablesView extends XDebugViewBase {
}
}
private void disposeTreeRestorer() {
if (myTreeRestorer != null) {
myTreeRestorer.dispose();
myTreeRestorer = null;
}
}
public JComponent getPanel() {
return myDebuggerTreePanel.getMainPanel();
}
@Override
public void dispose() {
disposeTreeRestorer();
DnDManager.getInstance().unregisterSource(myDebuggerTreePanel, myDebuggerTreePanel.getTree());
super.dispose();
}
@@ -31,6 +31,7 @@ import com.intellij.usageView.UsageInfo;
import com.intellij.util.IncorrectOperationException;
import com.intellij.util.containers.MultiMap;
import com.intellij.util.containers.hash.HashMap;
import com.intellij.util.containers.hash.LinkedHashMap;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.plugins.groovy.lang.GrReferenceAdjuster;
import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElementFactory;
@@ -84,11 +85,11 @@ public class RenameGrFieldProcessor extends RenameJavaVariableProcessor {
String newName,
final UsageInfo[] usages,
final RefactoringElementListener listener) throws IncorrectOperationException {
Map<PsiElement, String> renames = new HashMap<PsiElement, String>();
renames.put(psiElement, newName);
final GrField field = (GrField)psiElement;
String fieldName = field.getName();
Map<PsiElement, String> renames = new HashMap<PsiElement, String>();
renames.put(field, newName);
for (GrAccessorMethod getter : field.getGetters()) {
renames.put(getter, RenamePropertyUtil.getGetterNameByOldName(newName, getter.getName()));
}
@@ -97,8 +98,18 @@ public class RenameGrFieldProcessor extends RenameJavaVariableProcessor {
renames.put(setter, GroovyPropertyUtils.getSetterName(newName));
}
MultiMap<PsiNamedElement, UsageInfo> propertyUsages = new MultiMap<PsiNamedElement, UsageInfo>();
MultiMap<PsiNamedElement, UsageInfo> simpleUsages = new MultiMap<PsiNamedElement, UsageInfo>();
MultiMap<PsiNamedElement, UsageInfo> propertyUsages = new MultiMap<PsiNamedElement, UsageInfo>() {
@Override
protected Map<PsiNamedElement, Collection<UsageInfo>> createMap() {
return new LinkedHashMap<PsiNamedElement, Collection<UsageInfo>>();
}
};
MultiMap<PsiNamedElement, UsageInfo> simpleUsages = new MultiMap<PsiNamedElement, UsageInfo>() {
@Override
protected Map<PsiNamedElement, Collection<UsageInfo>> createMap() {
return new LinkedHashMap<PsiNamedElement, Collection<UsageInfo>>();
}
};
List<PsiReference> unknownUsages = new ArrayList<PsiReference>();
@@ -153,9 +164,6 @@ public class RenameGrFieldProcessor extends RenameJavaVariableProcessor {
rename(element, info, newName, true, manager);
}
}
simpleUsages.clear();
propertyUsages.clear();
renames.clear();
listener.elementRenamed(field);
}
@@ -27,7 +27,6 @@ import com.intellij.lang.documentation.DocumentationProvider;
import com.intellij.openapi.actionSystem.DataProvider;
import com.intellij.openapi.actionSystem.LangDataKeys;
import com.intellij.openapi.actionSystem.PlatformDataKeys;
import com.intellij.openapi.command.WriteCommandAction;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.markup.RangeHighlighter;
import com.intellij.openapi.util.Comparing;
@@ -43,7 +42,6 @@ import com.intellij.psi.xml.XmlTag;
import com.intellij.refactoring.rename.PsiElementRenameHandler;
import com.intellij.refactoring.rename.RenameHandler;
import com.intellij.refactoring.rename.RenameHandlerRegistry;
import com.intellij.refactoring.rename.RenameProcessor;
import com.intellij.refactoring.util.CommonRefactoringUtil;
import com.intellij.testFramework.MapDataContext;
import com.intellij.testFramework.fixtures.CodeInsightTestFixture;
@@ -288,25 +286,17 @@ public abstract class MavenDomTestCase extends MavenImportingTestCase {
RenameHandler handler = RenameHandlerRegistry.getInstance().getRenameHandler(context);
if (handler == null) return;
try {
System.getProperties().put(RenameProcessor.FORCE_RENAME_PROCESSOR_TO_THROW_EXCEPTION_ON_BAD_RENAMEABILITY, "");
invokeRename(context, handler);
}
catch (CommonRefactoringUtil.RefactoringErrorHintException e) {
if (!e.getMessage().startsWith("Cannot perform refactoring.")) {
throw e;
}
} finally {
System.getProperties().remove(RenameProcessor.FORCE_RENAME_PROCESSOR_TO_THROW_EXCEPTION_ON_BAD_RENAMEABILITY);
}
}
private void invokeRename(final MapDataContext context, final RenameHandler renameHandler) {
new WriteCommandAction.Simple(myProject) {
@Override
protected void run() throws Throwable {
renameHandler.invoke(myProject, PsiElement.EMPTY_ARRAY, context);
}
}.execute();
renameHandler.invoke(myProject, PsiElement.EMPTY_ARRAY, context);
}
private MapDataContext createDataContext(VirtualFile f) throws IOException {