Merge remote-tracking branch 'origin/master'

This commit is contained in:
irengrig
2015-06-12 16:05:55 +02:00
192 changed files with 2890 additions and 1726 deletions
+1 -1
View File
@@ -1,6 +1,6 @@
; Installer images
!define IMAGES_LOCATION "${BASE_DIR}\build\images\idea"
!define LICENSE_FILE "${BASE_DIR}\license\IDEA_license"
;!define LICENSE_FILE "${BASE_DIR}\license\IDEA_license"
!define PRODUCT_PROPERTIES_FILE "${BASE_DIR}\out\release\dist.all\bin\idea.properties"
!define PRODUCT_VM_OPTIONS_NAME idea*.exe.vmoptions
!define PRODUCT_VM_OPTIONS_FILE "${BASE_DIR}\out\release\dist.win\bin\${PRODUCT_VM_OPTIONS_NAME}"
+4 -1
View File
@@ -144,8 +144,11 @@ def layoutAll(Map args, String home, String out, Paths _paths = null, buildJps =
include(name: "*.*")
}
}
dir("license") {
fileset(dir: "${home}/license")
fileset(dir: "${home}/license") {
exclude(name: "placeholder.txt")
}
}
fileset(file: "${home}/LICENSE.txt")
fileset(file: "${home}/NOTICE.txt")
@@ -79,6 +79,7 @@ public class CompoundPositionManager extends PositionManagerEx implements MultiR
return defaultValue;
}
@Nullable
@Override
public SourcePosition getSourcePosition(final Location location) {
if (location == null) return null;
@@ -20,6 +20,7 @@ import com.intellij.debugger.NoDataException;
import com.intellij.debugger.PositionManager;
import com.intellij.debugger.SourcePosition;
import com.intellij.debugger.engine.evaluation.EvaluateException;
import com.intellij.debugger.impl.DebuggerUtilsEx;
import com.intellij.debugger.jdi.VirtualMachineProxyImpl;
import com.intellij.debugger.requests.ClassPrepareRequestor;
import com.intellij.execution.filters.LineNumbersMapping;
@@ -122,6 +123,7 @@ public class PositionManagerImpl implements PositionManager, MultiRequestPositio
});
}
@Nullable
public SourcePosition getSourcePosition(final Location location) throws NoDataException {
DebuggerManagerThreadImpl.assertIsManagerThread();
if(location == null) {
@@ -254,51 +256,17 @@ public class PositionManagerImpl implements PositionManager, MultiRequestPositio
PsiFile file = original.getFile();
int line = original.getLine();
if (LambdaMethodFilter.isLambdaName(myExpectedMethodName) && myLambdaOrdinal > -1) {
List<PsiLambdaExpression> lambdas = DebuggerUtilsEx.collectLambdas(original, false);
Document document = PsiDocumentManager.getInstance(file.getProject()).getDocument(file);
if (document == null || line >= document.getLineCount()) {
return original;
}
PsiElement element = original.getElementAt();
TextRange lineRange = new TextRange(document.getLineStartOffset(line), document.getLineEndOffset(line));
do {
PsiElement parent = element.getParent();
if (parent == null || (parent.getTextOffset() < lineRange.getStartOffset())) {
break;
}
element = parent;
}
while(true);
final List<PsiLambdaExpression> lambdas = new ArrayList<PsiLambdaExpression>(3);
final PsiElementVisitor lambdaCollector = new JavaRecursiveElementVisitor() {
@Override
public void visitLambdaExpression(PsiLambdaExpression expression) {
super.visitLambdaExpression(expression);
lambdas.add(expression);
}
};
element.accept(lambdaCollector);
// add initial lambda if we're inside already
NavigatablePsiElement method = PsiTreeUtil.getParentOfType(element, PsiMethod.class, PsiLambdaExpression.class);
if (method instanceof PsiLambdaExpression) {
lambdas.add((PsiLambdaExpression)method);
}
for (PsiElement sibling = getNextElement(element); sibling != null; sibling = getNextElement(sibling)) {
if (!lineRange.intersects(sibling.getTextRange())) {
break;
}
sibling.accept(lambdaCollector);
}
if (myLambdaOrdinal < lambdas.size()) {
PsiElement body = lambdas.get(myLambdaOrdinal).getBody();
if (body instanceof PsiCodeBlock) {
for (PsiStatement statement : ((PsiCodeBlock)body).getStatements()) {
if (lineRange.intersects(statement.getTextRange())) {
body = statement;
break;
}
}
PsiElement firstElem = DebuggerUtilsEx.getFirstElementOnTheLine(lambdas.get(myLambdaOrdinal), document, line);
if (firstElem != null) {
return SourcePosition.createFromElement(firstElem);
}
return SourcePosition.createFromElement(body);
}
}
else {
@@ -316,14 +284,6 @@ public class PositionManagerImpl implements PositionManager, MultiRequestPositio
});
}
private static PsiElement getNextElement(PsiElement element) {
PsiElement sibling = element.getNextSibling();
if (sibling != null) return sibling;
element = element.getParent();
if (element != null) return getNextElement(element);
return null;
}
@Nullable
@Override
public RangeHighlighter createHighlighter(Document document, Project project, TextAttributes attributes) {
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2009 JetBrains s.r.o.
* Copyright 2000-2015 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.
@@ -15,8 +15,6 @@
*/
package com.intellij.debugger.engine;
import com.intellij.debugger.engine.SuspendContextImpl;
public interface SuspendContextRunnable {
void run(SuspendContextImpl suspendContext) throws Exception;
}
@@ -58,6 +58,7 @@ import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.pom.Navigatable;
import com.intellij.psi.*;
import com.intellij.psi.codeStyle.CodeStyleSettingsManager;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.ui.classFilter.ClassFilter;
import com.intellij.ui.content.Content;
import com.intellij.unscramble.ThreadDumpPanel;
@@ -779,4 +780,85 @@ public abstract class DebuggerUtilsEx extends DebuggerUtils {
res.append(location.method().name());
return res.toString();
}
private static PsiElement getNextElement(PsiElement element) {
PsiElement sibling = element.getNextSibling();
if (sibling != null) return sibling;
element = element.getParent();
if (element != null) return getNextElement(element);
return null;
}
public static List<PsiLambdaExpression> collectLambdas(SourcePosition position, final boolean onlyOnTheLine) {
ApplicationManager.getApplication().assertReadAccessAllowed();
PsiFile file = position.getFile();
int line = position.getLine();
Document document = PsiDocumentManager.getInstance(file.getProject()).getDocument(file);
if (document == null || line >= document.getLineCount()) {
return Collections.emptyList();
}
PsiElement element = position.getElementAt();
final TextRange lineRange = new TextRange(document.getLineStartOffset(line), document.getLineEndOffset(line));
do {
PsiElement parent = element.getParent();
if (parent == null || (parent.getTextOffset() < lineRange.getStartOffset())) {
break;
}
element = parent;
}
while(true);
final List<PsiLambdaExpression> lambdas = new ArrayList<PsiLambdaExpression>(3);
final PsiElementVisitor lambdaCollector = new JavaRecursiveElementVisitor() {
@Override
public void visitLambdaExpression(PsiLambdaExpression expression) {
super.visitLambdaExpression(expression);
if (!onlyOnTheLine || lineRange.intersects(expression.getTextRange())) {
lambdas.add(expression);
}
}
};
element.accept(lambdaCollector);
// add initial lambda if we're inside already
NavigatablePsiElement method = PsiTreeUtil.getParentOfType(element, PsiMethod.class, PsiLambdaExpression.class);
if (method instanceof PsiLambdaExpression) {
lambdas.add((PsiLambdaExpression)method);
}
for (PsiElement sibling = getNextElement(element); sibling != null; sibling = getNextElement(sibling)) {
if (!lineRange.intersects(sibling.getTextRange())) {
break;
}
sibling.accept(lambdaCollector);
}
return lambdas;
}
@Nullable
public static PsiElement getFirstElementOnTheLine(PsiLambdaExpression lambda, Document document, int line) {
ApplicationManager.getApplication().assertReadAccessAllowed();
TextRange lineRange = new TextRange(document.getLineStartOffset(line), document.getLineEndOffset(line));
if (!lineRange.intersects(lambda.getTextRange())) return null;
PsiElement body = lambda.getBody();
if (body instanceof PsiCodeBlock) {
for (PsiStatement statement : ((PsiCodeBlock)body).getStatements()) {
if (lineRange.intersects(statement.getTextRange())) {
return statement;
}
}
}
return body;
}
public static boolean inTheSameMethod(@NotNull SourcePosition pos1, @NotNull SourcePosition pos2) {
ApplicationManager.getApplication().assertReadAccessAllowed();
PsiElement elem1 = pos1.getElementAt();
PsiElement elem2 = pos2.getElementAt();
if (elem1 == null) return elem2 == null;
if (elem2 != null) {
NavigatablePsiElement expectedMethod = PsiTreeUtil.getParentOfType(elem1, PsiMethod.class, PsiLambdaExpression.class);
NavigatablePsiElement currentMethod = PsiTreeUtil.getParentOfType(elem2, PsiMethod.class, PsiLambdaExpression.class);
return Comparing.equal(expectedMethod, currentMethod);
}
return false;
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2014 JetBrains s.r.o.
* Copyright 2000-2015 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.
@@ -17,26 +17,39 @@ package com.intellij.debugger.ui.breakpoints;
import com.intellij.debugger.DebuggerBundle;
import com.intellij.debugger.HelpID;
import com.intellij.icons.AllIcons;
import com.intellij.debugger.SourcePosition;
import com.intellij.debugger.impl.DebuggerUtilsEx;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.TextRange;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.*;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.util.SmartList;
import com.intellij.xdebugger.XDebuggerUtil;
import com.intellij.xdebugger.XSourcePosition;
import com.intellij.xdebugger.breakpoints.XBreakpoint;
import com.intellij.xdebugger.breakpoints.XLineBreakpoint;
import com.intellij.xdebugger.breakpoints.ui.XBreakpointGroupingRule;
import com.intellij.xdebugger.impl.XSourcePositionImpl;
import com.intellij.xdebugger.impl.breakpoints.XLineBreakpointVariant;
import com.intellij.xdebugger.impl.breakpoints.XLineBreakpointVariantsProvider;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.java.debugger.breakpoints.properties.JavaBreakpointProperties;
import org.jetbrains.java.debugger.breakpoints.properties.JavaLineBreakpointProperties;
import javax.swing.*;
import java.util.Collections;
import java.util.List;
/**
* Base class for java line-connected exceptions (line, method, field)
* @author egor
*/
public class JavaLineBreakpointType extends JavaLineBreakpointTypeBase<JavaBreakpointProperties> implements JavaBreakpointType {
public class JavaLineBreakpointType extends JavaLineBreakpointTypeBase<JavaBreakpointProperties>
implements JavaBreakpointType, XLineBreakpointVariantsProvider<JavaLineBreakpointType.JavaBreakpointVariant> {
public JavaLineBreakpointType() {
super("java-line", DebuggerBundle.message("line.breakpoints.tab.title"));
}
@@ -58,13 +71,13 @@ public class JavaLineBreakpointType extends JavaLineBreakpointTypeBase<JavaBreak
@Nullable
@Override
public JavaBreakpointProperties createProperties() {
public JavaLineBreakpointProperties createProperties() {
return new JavaLineBreakpointProperties();
}
@Nullable
@Override
public JavaBreakpointProperties createBreakpointProperties(@NotNull VirtualFile file, int line) {
public JavaLineBreakpointProperties createBreakpointProperties(@NotNull VirtualFile file, int line) {
return new JavaLineBreakpointProperties();
}
@@ -78,4 +91,104 @@ public class JavaLineBreakpointType extends JavaLineBreakpointTypeBase<JavaBreak
public int getPriority() {
return 100;
}
@NotNull
@Override
public List<JavaBreakpointVariant> computeLineBreakpointVariants(@NotNull Project project, @NotNull XSourcePosition position) {
PsiFile file = PsiManager.getInstance(project).findFile(position.getFile());
if (file == null) {
return Collections.emptyList();
}
SourcePosition pos = SourcePosition.createFromLine(file, position.getLine());
List<PsiLambdaExpression> lambdas = DebuggerUtilsEx.collectLambdas(pos, true);
if (lambdas.isEmpty()) {
return Collections.emptyList();
}
NavigatablePsiElement startMethod = PsiTreeUtil.getParentOfType(pos.getElementAt(), PsiMethod.class, PsiLambdaExpression.class);
//noinspection SuspiciousMethodCalls
if (lambdas.contains(startMethod) && lambdas.size() == 1) {
return Collections.emptyList();
}
Document document = PsiDocumentManager.getInstance(file.getProject()).getDocument(file);
if (document == null) {
return Collections.emptyList();
}
List<JavaBreakpointVariant> res = new SmartList<JavaBreakpointVariant>();
res.add(new JavaBreakpointVariant(position)); //all
if (startMethod instanceof PsiMethod) {
res.add(new ExactJavaBreakpointVariant(position, startMethod)); // base method
}
for (PsiLambdaExpression lambda : lambdas) { //lambdas
PsiElement firstElem = DebuggerUtilsEx.getFirstElementOnTheLine(lambda, document, position.getLine());
res.add(new ExactJavaBreakpointVariant(XSourcePositionImpl.createByElement(firstElem), lambda));
}
return res;
}
class JavaBreakpointVariant extends XLineBreakpointVariant {
protected final XSourcePosition mySourcePosition;
private JavaBreakpointVariant(XSourcePosition position) {
mySourcePosition = position;
}
@Override
public String getText() {
return "All";
}
@Override
public Icon getIcon() {
return null;
}
@Override
public TextRange getHighlightRange() {
return null;
}
@Override
public JavaLineBreakpointProperties createProperties() {
return createBreakpointProperties(mySourcePosition.getFile(),
mySourcePosition.getLine());
}
}
private class ExactJavaBreakpointVariant extends JavaBreakpointVariant {
private final PsiElement myElement;
public ExactJavaBreakpointVariant(XSourcePosition position, PsiElement element) {
super(position);
myElement = element;
}
@Override
public Icon getIcon() {
return myElement.getIcon(0);
}
@Override
public String getText() {
return StringUtil.shortenTextWithEllipsis(myElement.getText(), 100, 0);
}
@Override
public TextRange getHighlightRange() {
return myElement.getTextRange();
}
@Override
public JavaLineBreakpointProperties createProperties() {
JavaLineBreakpointProperties properties = super.createProperties();
properties.setOffset(mySourcePosition.getOffset());
return properties;
}
}
}
@@ -62,6 +62,7 @@ import com.sun.jdi.request.BreakpointRequest;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.java.debugger.breakpoints.properties.JavaLineBreakpointProperties;
import org.jetbrains.jps.model.java.JavaModuleSourceRootTypes;
import javax.swing.*;
@@ -198,12 +199,30 @@ public class LineBreakpoint extends BreakpointWithHighlighter {
return false;
}
protected boolean acceptLocation(DebugProcessImpl debugProcess, ReferenceType classType, Location loc) {
protected boolean acceptLocation(final DebugProcessImpl debugProcess, ReferenceType classType, final Location loc) {
Method method = loc.method();
if (DebuggerUtils.isSynthetic(method)) {
return false;
}
return !(method.isConstructor() && loc.codeIndex() == 0 && isAnonymousClass(classType));
boolean res = !(method.isConstructor() && loc.codeIndex() == 0 && isAnonymousClass(classType));
if (!res) return false;
return ApplicationManager.getApplication().runReadAction(new Computable<Boolean>() {
@Override
public Boolean compute() {
if (getProperties() instanceof JavaLineBreakpointProperties) {
Integer offset = ((JavaLineBreakpointProperties)getProperties()).getOffset();
if (offset == null) return true;
PsiFile file = getPsiFile();
if (file != null) {
SourcePosition exactPosition = SourcePosition.createFromOffset(file, offset);
SourcePosition position = debugProcess.getPositionManager().getSourcePosition(loc);
if (position == null) return false;
return DebuggerUtilsEx.inTheSameMethod(exactPosition, position);
}
}
return true;
}
});
}
private boolean isInScopeOf(DebugProcessImpl debugProcess, String className) {
@@ -17,17 +17,18 @@ package com.intellij.debugger.ui.breakpoints;
import com.intellij.debugger.SourcePosition;
import com.intellij.debugger.engine.DebugProcessImpl;
import com.intellij.debugger.impl.DebuggerUtilsEx;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.Computable;
import com.intellij.psi.*;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiManager;
import com.intellij.xdebugger.XSourcePosition;
import com.sun.jdi.Location;
import com.sun.jdi.ReferenceType;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.java.debugger.breakpoints.properties.JavaBreakpointProperties;
/**
* @author Eugene Zhuravlev
@@ -114,6 +115,11 @@ public class RunToCursorBreakpoint extends LineBreakpoint {
return true;
}
@Override
protected JavaBreakpointProperties getProperties() {
return null;
}
@Override
protected boolean isMuted(@NotNull final DebugProcessImpl debugProcess) {
return false; // always enabled
@@ -125,19 +131,9 @@ public class RunToCursorBreakpoint extends LineBreakpoint {
return ApplicationManager.getApplication().runReadAction(new Computable<Boolean>() {
@Override
public Boolean compute() {
PsiElement expectedElement = myCustomPosition.getElementAt();
if (expectedElement != null) {
SourcePosition position = debugProcess.getPositionManager().getSourcePosition(loc);
if (position != null) {
PsiElement currentElement = position.getElementAt();
if (currentElement != null) {
NavigatablePsiElement expectedMethod = PsiTreeUtil.getParentOfType(expectedElement, PsiMethod.class, PsiLambdaExpression.class);
NavigatablePsiElement currentMethod = PsiTreeUtil.getParentOfType(currentElement, PsiMethod.class, PsiLambdaExpression.class);
return Comparing.equal(expectedMethod, currentMethod);
}
}
}
return true;
SourcePosition position = debugProcess.getPositionManager().getSourcePosition(loc);
if (position == null) return false;
return DebuggerUtilsEx.inTheSameMethod(myCustomPosition, position);
}
});
}
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2014 JetBrains s.r.o.
* Copyright 2000-2015 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.
@@ -15,8 +15,20 @@
*/
package org.jetbrains.java.debugger.breakpoints.properties;
import com.intellij.util.xmlb.annotations.OptionTag;
/**
* @author egor
*/
public class JavaLineBreakpointProperties extends JavaBreakpointProperties<JavaLineBreakpointProperties> {
private Integer myOffset = null;
@OptionTag("offset")
public Integer getOffset() {
return myOffset;
}
public void setOffset(Integer offset) {
myOffset = offset;
}
}
@@ -312,7 +312,7 @@ public abstract class SourcePosition implements Navigatable{
}
@Nullable
public static SourcePosition createFromElement(PsiElement element) {
public static SourcePosition createFromElement(@NotNull PsiElement element) {
ApplicationManager.getApplication().assertReadAccessAllowed();
PsiElement navigationElement = element.getNavigationElement();
final SmartPsiElementPointer<PsiElement> pointer =
@@ -20,6 +20,7 @@ import com.intellij.codeInsight.daemon.LineMarkerProvider;
import com.intellij.execution.lineMarker.RunLineMarkerInfo;
import com.intellij.psi.PsiClass;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiIdentifier;
import com.intellij.psi.PsiMethod;
import com.intellij.psi.util.PsiMethodUtil;
import org.jetbrains.annotations.NotNull;
@@ -35,11 +36,14 @@ public class ApplicationRunLineMarkerProvider implements LineMarkerProvider {
@Nullable
@Override
public LineMarkerInfo getLineMarkerInfo(@NotNull PsiElement element) {
if (element instanceof PsiClass && PsiMethodUtil.findMainInClass((PsiClass)element) != null)
return new RunLineMarkerInfo(element, ApplicationConfigurationType.getInstance().getIcon(), null);
if (element instanceof PsiMethod && "main".equals(((PsiMethod)element).getName()) && PsiMethodUtil.isMainMethod((PsiMethod)element))
return new RunLineMarkerInfo(element, ApplicationConfigurationType.getInstance().getIcon(), null);
public LineMarkerInfo getLineMarkerInfo(@NotNull PsiElement e) {
if (e instanceof PsiIdentifier) {
PsiElement element = e.getParent();
if (element instanceof PsiClass && PsiMethodUtil.findMainInClass((PsiClass)element) != null)
return new RunLineMarkerInfo(element, ApplicationConfigurationType.getInstance().getIcon(), null);
if (element instanceof PsiMethod && "main".equals(((PsiMethod)element).getName()) && PsiMethodUtil.isMainMethod((PsiMethod)element))
return new RunLineMarkerInfo(element, ApplicationConfigurationType.getInstance().getIcon(), null);
}
return null;
}
@@ -71,7 +71,7 @@ class RefCountHolder {
private static final Key<Reference<RefCountHolder>> REF_COUNT_HOLDER_IN_FILE_KEY = Key.create("REF_COUNT_HOLDER_IN_FILE_KEY");
@NotNull
public static RefCountHolder get(@NotNull PsiFile file) {
static RefCountHolder get(@NotNull PsiFile file) {
Reference<RefCountHolder> ref = file.getUserData(REF_COUNT_HOLDER_IN_FILE_KEY);
RefCountHolder holder = com.intellij.reference.SoftReference.dereference(ref);
if (holder == null) {
@@ -171,7 +171,7 @@ class RefCountHolder {
}
}
public boolean isReferenced(@NotNull PsiElement element) {
boolean isReferenced(@NotNull PsiElement element) {
Collection<PsiReference> array;
synchronized (myLocalRefsMap) {
array = myLocalRefsMap.get(element);
@@ -272,10 +272,10 @@ class RefCountHolder {
return false;
}
public boolean analyze(@NotNull PsiFile file,
TextRange dirtyScope,
@NotNull ProgressIndicator indicator,
@NotNull Runnable analyze) {
boolean analyze(@NotNull PsiFile file,
TextRange dirtyScope,
@NotNull ProgressIndicator indicator,
@NotNull Runnable analyze) {
ProgressIndicator result;
if (myState.compareAndSet(EMPTY, indicator)) {
if (!file.getTextRange().equals(dirtyScope)) {
@@ -124,7 +124,7 @@ public class JavaCompletionContributor extends CompletionContributor {
return new AnnotationTypeFilter();
}
if (JavaCompletionData.DECLARATION_START.accepts(position) ||
if (JavaCompletionData.DECLARATION_START.getValue().accepts(position) ||
JavaCompletionData.isInsideParameterList(position) ||
psiElement().inside(psiElement(PsiJavaCodeReferenceElement.class).withParent(psiAnnotation())).accepts(position)) {
return new OrFilter(ElementClassFilter.CLASS, ElementClassFilter.PACKAGE_FILTER);
@@ -20,6 +20,8 @@ import com.intellij.codeInsight.TailType;
import com.intellij.codeInsight.TailTypes;
import com.intellij.codeInsight.completion.util.ParenthesesInsertHandler;
import com.intellij.codeInsight.lookup.*;
import com.intellij.openapi.util.AtomicNotNullLazyValue;
import com.intellij.openapi.util.NotNullLazyValue;
import com.intellij.patterns.ElementPattern;
import com.intellij.patterns.PsiJavaElementPattern;
import com.intellij.pom.java.LanguageLevel;
@@ -37,6 +39,7 @@ import com.intellij.psi.util.PsiUtil;
import com.intellij.util.Consumer;
import com.intellij.util.ProcessingContext;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import static com.intellij.patterns.PsiJavaPatterns.*;
import static com.intellij.patterns.StandardPatterns.not;
@@ -86,33 +89,39 @@ public class JavaCompletionData extends JavaAwareCompletionData {
new StartElementFilter()
);
static final ElementFilter END_OF_BLOCK = new OrFilter(
new AndFilter(
new LeftNeighbour(
new OrFilter(
static final NotNullLazyValue<ElementFilter> END_OF_BLOCK = new AtomicNotNullLazyValue<ElementFilter>() {
@NotNull
@Override
protected ElementFilter compute() {
return new OrFilter(
new AndFilter(
new LeftNeighbour(
new OrFilter(
new AndFilter (
new TextFilter(BLOCK_FINALIZERS),
new NotFilter (
new SuperParentFilter(new ClassFilter(PsiAnnotation.class))
)
new TextFilter(BLOCK_FINALIZERS),
new NotFilter (
new SuperParentFilter(new ClassFilter(PsiAnnotation.class))
)
),
new TextFilter("*/"),
new TokenTypeFilter(JspElementType.HOLDER_TEMPLATE_DATA),
new ClassFilter(OuterLanguageElement.class),
new AndFilter(
new TextFilter(")"),
new NotFilter(
new OrFilter(
new ParentElementFilter(new ClassFilter(PsiExpressionList.class)),
new ParentElementFilter(new ClassFilter(PsiParameterList.class)),
new ParentElementFilter(new ClassFilter(PsiTypeCastExpression.class))
)
new TextFilter(")"),
new NotFilter(
new OrFilter(
new ParentElementFilter(new ClassFilter(PsiExpressionList.class)),
new ParentElementFilter(new ClassFilter(PsiParameterList.class)),
new ParentElementFilter(new ClassFilter(PsiTypeCastExpression.class))
)
)
))),
new NotFilter(new TextFilter("."))
),
START_OF_CODE_FRAGMENT
);
new NotFilter(new TextFilter("."))
),
START_OF_CODE_FRAGMENT
);
}
};
static final ElementPattern<PsiElement> START_SWITCH =
psiElement().afterLeaf(psiElement().withText("{").withParents(PsiCodeBlock.class, PsiSwitchStatement.class));
@@ -132,9 +141,15 @@ public class JavaCompletionData extends JavaAwareCompletionData {
PsiKeyword.CHAR, PsiKeyword.BYTE
};
private static final ElementFilter CLASS_BODY = new OrFilter(
new AfterElementFilter(new TextFilter("{")),
new ScopeFilter(new ClassFilter(JspClassLevelDeclarationStatement.class)));
private static final NotNullLazyValue<ElementFilter> CLASS_BODY = new AtomicNotNullLazyValue<ElementFilter>() {
@NotNull
@Override
protected ElementFilter compute() {
return new OrFilter(
new AfterElementFilter(new TextFilter("{")),
new ScopeFilter(new ClassFilter(JspClassLevelDeclarationStatement.class)));
}
};
public static final ElementPattern<PsiElement> START_FOR =
psiElement().afterLeaf(psiElement().withText("(").afterLeaf("for")).withParents(PsiJavaCodeReferenceElement.class,
@@ -166,25 +181,31 @@ public class JavaCompletionData extends JavaAwareCompletionData {
defineScopeEquivalence(PsiMethod.class, JavaCodeFragment.class);
}
public static final ElementPattern<PsiElement> DECLARATION_START = psiElement().andNot(psiElement().afterLeaf("@", ".")).
andOr(
psiElement().and(new FilterPattern(CLASS_BODY)).
public static final NotNullLazyValue<ElementPattern<PsiElement>> DECLARATION_START = new NotNullLazyValue<ElementPattern<PsiElement>>() {
@NotNull
@Override
protected ElementPattern<PsiElement> compute() {
return psiElement().andNot(psiElement().afterLeaf("@", ".")).
andOr(
new FilterPattern(END_OF_BLOCK),
psiElement().afterLeaf(or(
psiElement().inside(PsiModifierList.class),
psiElement().withElementType(JavaTokenType.GT).inside(PsiTypeParameterList.class)
))),
psiElement().withParents(PsiJavaCodeReferenceElement.class, PsiTypeElement.class, PsiMember.class),
psiElement().withParents(PsiJavaCodeReferenceElement.class, PsiTypeElement.class, PsiClassLevelDeclarationStatement.class)
);
psiElement().and(new FilterPattern(CLASS_BODY.getValue())).
andOr(
new FilterPattern(END_OF_BLOCK.getValue()),
psiElement().afterLeaf(or(
psiElement().inside(PsiModifierList.class),
psiElement().withElementType(JavaTokenType.GT).inside(PsiTypeParameterList.class)
))),
psiElement().withParents(PsiJavaCodeReferenceElement.class, PsiTypeElement.class, PsiMember.class),
psiElement().withParents(PsiJavaCodeReferenceElement.class, PsiTypeElement.class, PsiClassLevelDeclarationStatement.class)
);
}
};
private void declareCompletionSpaces() {
declareFinalScope(PsiFile.class);
{
// Class body
final CompletionVariant variant = new CompletionVariant(CLASS_BODY);
final CompletionVariant variant = new CompletionVariant(CLASS_BODY.getValue());
variant.includeScopeClass(PsiClass.class, true);
registerVariant(variant);
}
@@ -219,7 +240,7 @@ public class JavaCompletionData extends JavaAwareCompletionData {
// position
{
final ElementFilter position = new AndFilter(
new NotFilter(CLASS_BODY),
new NotFilter(CLASS_BODY.getValue()),
new NotFilter(new AfterElementFilter(new ContentFilter(new TextFilter(PsiKeyword.EXTENDS)))),
new NotFilter(new AfterElementFilter(new ContentFilter(new TextFilter(PsiKeyword.IMPLEMENTS)))),
new NotFilter(new LeftNeighbour(new LeftNeighbour(new TextFilter("<", ",")))),
@@ -240,7 +261,7 @@ public class JavaCompletionData extends JavaAwareCompletionData {
// position
{
final ElementFilter position = new AndFilter(
new NotFilter(CLASS_BODY),
new NotFilter(CLASS_BODY.getValue()),
new NotFilter(new BeforeElementFilter(new ContentFilter(new TextFilter(PsiKeyword.EXTENDS)))),
new NotFilter(new AfterElementFilter(new ContentFilter(new TextFilter(PsiKeyword.IMPLEMENTS)))),
new NotFilter(new LeftNeighbour(new LeftNeighbour(new TextFilter("<", ",")))),
@@ -476,7 +497,7 @@ public class JavaCompletionData extends JavaAwareCompletionData {
result.consume(new OverrideableSpace(createKeyword(position, PsiKeyword.PACKAGE), TailType.HUMBLE_SPACE_BEFORE_WORD));
result.consume(new OverrideableSpace(createKeyword(position, PsiKeyword.IMPORT), TailType.HUMBLE_SPACE_BEFORE_WORD));
}
else if (END_OF_BLOCK.isAcceptable(position, position) && PsiTreeUtil.getParentOfType(position, PsiMember.class) == null) {
else if (END_OF_BLOCK.getValue().isAcceptable(position, position) && PsiTreeUtil.getParentOfType(position, PsiMember.class) == null) {
result.consume(new OverrideableSpace(createKeyword(position, PsiKeyword.IMPORT), TailType.HUMBLE_SPACE_BEFORE_WORD));
}
}
@@ -589,7 +610,7 @@ public class JavaCompletionData extends JavaAwareCompletionData {
return true;
}
return END_OF_BLOCK.isAcceptable(position, position);
return END_OF_BLOCK.getValue().isAcceptable(position, position);
}
static void addExpectedTypeMembers(CompletionParameters parameters, final CompletionResultSet result) {
@@ -656,7 +677,7 @@ public class JavaCompletionData extends JavaAwareCompletionData {
.accepts(position);
boolean typeFragment = position.getContainingFile() instanceof PsiTypeCodeFragment && PsiTreeUtil.prevVisibleLeaf(position) == null;
boolean declaration = DECLARATION_START.accepts(position);
boolean declaration = DECLARATION_START.getValue().accepts(position);
boolean expressionPosition = isExpressionPosition(position);
boolean inGenerics = PsiTreeUtil.getParentOfType(position, PsiReferenceParameterList.class) != null;
if (START_FOR.accepts(position) ||
@@ -723,7 +744,7 @@ public class JavaCompletionData extends JavaAwareCompletionData {
return false;
}
if (END_OF_BLOCK.isAcceptable(position, position) &&
if (END_OF_BLOCK.getValue().isAcceptable(position, position) &&
PsiTreeUtil.getParentOfType(position, PsiCodeBlock.class, true, PsiMember.class) != null) {
return true;
}
@@ -130,7 +130,7 @@ public class ModifierChooser {
PsiElement prev = FilterPositionUtil.searchNonSpaceNonCommentBack(element);
if (parent instanceof PsiJavaFile || parent instanceof PsiClass) {
if (prev == null || JavaCompletionData.END_OF_BLOCK.isAcceptable(element, prev.getParent())) {
if (prev == null || JavaCompletionData.END_OF_BLOCK.getValue().isAcceptable(element, prev.getParent())) {
return true;
}
}
@@ -39,7 +39,7 @@ public class ReplaceConstructorWithBuilderAction extends BaseRefactoringAction{
final int offset = editor.getCaretModel().getOffset();
final PsiElement elementAt = file.findElementAt(offset);
final PsiClass psiClass = ReplaceConstructorWithBuilderHandler.getParentNamedClass(elementAt);
return psiClass != null && psiClass.getConstructors().length > 0;
return psiClass != null && psiClass.getConstructors().length > 0 && !psiClass.isEnum();
}
protected boolean isEnabledOnElements(@NotNull final PsiElement[] elements) {
@@ -17,8 +17,10 @@ package com.intellij.refactoring.actions;
import com.intellij.lang.java.JavaLanguage;
import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.openapi.editor.Editor;
import com.intellij.psi.PsiClass;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiMethod;
import com.intellij.refactoring.RefactoringActionHandler;
import com.intellij.refactoring.replaceConstructorWithFactory.ReplaceConstructorWithFactoryHandler;
@@ -32,10 +34,25 @@ public class ReplaceConstructorWithFactoryAction extends BaseRefactoringAction {
return false;
}
@Override
protected boolean isEnabledOnElements(@NotNull PsiElement[] elements) {
return elements.length == 1 &&
(elements[0] instanceof PsiMethod && ((PsiMethod)elements[0]).isConstructor() || elements[0] instanceof PsiClass)
&& elements[0].getLanguage().isKindOf(JavaLanguage.INSTANCE);
return false;
}
@Override
protected boolean isAvailableOnElementInEditorAndFile(@NotNull PsiElement element,
@NotNull Editor editor,
@NotNull PsiFile file,
@NotNull DataContext context) {
return (element instanceof PsiMethod &&
((PsiMethod)element).isConstructor() &&
acceptClass(((PsiMethod)element).getContainingClass()) ||
acceptClass(element))
&& element.getLanguage().isKindOf(JavaLanguage.INSTANCE);
}
private static boolean acceptClass(PsiElement element) {
return element instanceof PsiClass && !((PsiClass)element).isEnum();
}
protected RefactoringActionHandler getHandler(@NotNull DataContext dataContext) {
@@ -136,7 +136,7 @@ public class JavaChangeSignatureHandler implements ChangeSignatureHandler {
return elementParent;
}
if (elementParent instanceof PsiClass && ((PsiClass)elementParent).getNameIdentifier()==element) {
if (((PsiClass)elementParent).isAnnotationType()) {
if (((PsiClass)elementParent).isAnnotationType() || ((PsiClass)elementParent).isEnum()) {
return null;
}
return elementParent;
@@ -22,17 +22,17 @@ import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.ScrollType;
import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiClass;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiField;
import com.intellij.psi.PsiFile;
import com.intellij.openapi.util.Condition;
import com.intellij.psi.*;
import com.intellij.refactoring.HelpID;
import com.intellij.refactoring.RefactoringActionHandler;
import com.intellij.refactoring.RefactoringBundle;
import com.intellij.refactoring.util.CommonRefactoringUtil;
import com.intellij.util.containers.ContainerUtil;
import org.jetbrains.annotations.NotNull;
import java.util.HashSet;
import java.util.List;
public class EncapsulateFieldsHandler implements RefactoringActionHandler {
private static final Logger LOG = Logger.getInstance("#com.intellij.refactoring.encapsulateFields.EncapsulateFieldsHandler");
@@ -108,8 +108,13 @@ public class EncapsulateFieldsHandler implements RefactoringActionHandler {
}
LOG.assertTrue(aClass != null);
final PsiField[] fields = aClass.getFields();
if (fields.length == 0) {
final List<PsiField> fields = ContainerUtil.filter(aClass.getFields(), new Condition<PsiField>() {
@Override
public boolean value(PsiField field) {
return !(field instanceof PsiEnumConstant);
}
});
if (fields.isEmpty()) {
CommonRefactoringUtil.showErrorHint(project, CommonDataKeys.EDITOR.getData(dataContext), "Class has no fields to encapsulate",
REFACTORING_NAME, HelpID.ENCAPSULATE_FIELDS);
return;
@@ -17,6 +17,7 @@ package com.intellij.refactoring.encapsulateFields;
import com.intellij.codeInsight.generation.GenerateMembersUtil;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.Condition;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.*;
import com.intellij.psi.tree.IElementType;
@@ -25,10 +26,13 @@ import com.intellij.psi.util.PsiUtil;
import com.intellij.refactoring.util.RefactoringUtil;
import com.intellij.util.IncorrectOperationException;
import com.intellij.util.VisibilityUtil;
import com.intellij.util.containers.ContainerUtil;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.List;
/**
* @author Max Medvedev
*/
@@ -307,7 +311,13 @@ public class JavaEncapsulateFieldHelper extends EncapsulateFieldHelper {
@NotNull
@Override
public PsiField[] getApplicableFields(@NotNull PsiClass aClass) {
return aClass.getFields();
final List<PsiField> fields = ContainerUtil.filter(aClass.getFields(), new Condition<PsiField>() {
@Override
public boolean value(PsiField field) {
return !(field instanceof PsiEnumConstant);
}
});
return fields.toArray(new PsiField[fields.size()]);
}
@Override
@@ -51,7 +51,7 @@ class ExtractInterfaceDialog extends JavaExtractSuperBaseDialog {
return element.hasModifierProperty(PsiModifier.PUBLIC)
&& !element.hasModifierProperty(PsiModifier.STATIC);
}
else if (element instanceof PsiField) {
else if (element instanceof PsiField && !(element instanceof PsiEnumConstant)) {
return element.hasModifierProperty(PsiModifier.FINAL)
&& element.hasModifierProperty(PsiModifier.STATIC)
&& element.hasModifierProperty(PsiModifier.PUBLIC);
@@ -108,7 +108,7 @@ public class MethodDuplicatesHandler implements RefactoringActionHandler {
}
} else if (member instanceof PsiField) {
final PsiField field = (PsiField)member;
if (!field.hasInitializer()) {
if (field.getInitializer() == null) {
return "Field " + member.getName() + " doesn't have initializer";
}
final PsiClass containingClass = field.getContainingClass();
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2014 JetBrains s.r.o.
* Copyright 2000-2015 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.
@@ -49,13 +49,13 @@ import java.util.Set;
/**
* @author cdr
*/
public class SliceUtil {
public static boolean processUsagesFlownDownTo(@NotNull PsiElement expression,
@NotNull Processor<SliceUsage> processor,
@NotNull SliceUsage parent,
@NotNull PsiSubstitutor parentSubstitutor,
int indexNesting,
@NotNull String syntheticField) {
class SliceUtil {
static boolean processUsagesFlownDownTo(@NotNull PsiElement expression,
@NotNull Processor<SliceUsage> processor,
@NotNull SliceUsage parent,
@NotNull PsiSubstitutor parentSubstitutor,
int indexNesting,
@NotNull String syntheticField) {
assert indexNesting >= 0 : indexNesting;
expression = simplify(expression);
PsiElement original = expression;
@@ -337,16 +337,18 @@ public class SliceUtil {
}
@NotNull
public static SliceUsage createSliceUsage(@NotNull PsiElement element,
@NotNull SliceUsage parent,
@NotNull PsiSubstitutor substitutor,
int indexNesting,
@NotNull String syntheticField) {
static SliceUsage createSliceUsage(@NotNull PsiElement element,
@NotNull SliceUsage parent,
@NotNull PsiSubstitutor substitutor,
int indexNesting,
@NotNull String syntheticField) {
return new SliceUsage(simplify(element), parent, substitutor,indexNesting, syntheticField);
}
@NotNull
public static SliceUsage createTooComplexDFAUsage(@NotNull PsiElement element, @NotNull SliceUsage parent, @NotNull PsiSubstitutor substitutor) {
private static SliceUsage createTooComplexDFAUsage(@NotNull PsiElement element,
@NotNull SliceUsage parent,
@NotNull PsiSubstitutor substitutor) {
return new SliceTooComplexDFAUsage(simplify(element), parent, substitutor);
}
@@ -336,7 +336,8 @@ public class ExceptionUtil {
final JavaResolveResult resolveResult = methodReferenceExpression.advancedResolve(false);
final PsiElement resolve = resolveResult.getElement();
if (resolve instanceof PsiMethod) {
return getUnhandledExceptions((PsiMethod)resolve, methodReferenceExpression, topElement, resolveResult.getSubstitutor());
final PsiElement referenceNameElement = methodReferenceExpression.getReferenceNameElement();
return getUnhandledExceptions((PsiMethod)resolve, referenceNameElement, topElement, resolveResult.getSubstitutor());
}
return Collections.emptyList();
}
@@ -667,12 +668,9 @@ public class ExceptionUtil {
// like in void f() throws XXX { new AA(methodThrowingXXX()) { ... }; }
return parent instanceof PsiAnonymousClass && isHandled(parent, exceptionType, topElement);
}
else if (parent instanceof PsiLambdaExpression) {
final PsiType interfaceType = ((PsiLambdaExpression)parent).getFunctionalInterfaceType();
return isDeclaredBySAMMethod(exceptionType, interfaceType);
}
else if (element instanceof PsiMethodReferenceExpression) {
final PsiType interfaceType = ((PsiMethodReferenceExpression)element).getFunctionalInterfaceType();
else if (parent instanceof PsiLambdaExpression ||
parent instanceof PsiMethodReferenceExpression && element == ((PsiMethodReferenceExpression)parent).getReferenceNameElement()) {
final PsiType interfaceType = ((PsiFunctionalExpression)parent).getFunctionalInterfaceType();
return isDeclaredBySAMMethod(exceptionType, interfaceType);
}
else if (parent instanceof PsiClassInitializer) {
@@ -272,6 +272,6 @@ public class PsiLambdaExpressionImpl extends ExpressionPsiElement implements Psi
@Nullable
@Override
public Icon getIcon(int flags) {
return AllIcons.Nodes.AnonymousClass;
return AllIcons.Nodes.Function;
}
}
@@ -0,0 +1,17 @@
class E1 extends Exception {}
class E2 extends Exception {}
class Test {
interface I {
void m() throws E1;
}
void a(I i) {}
Test b() throws E2 {return this;}
void c() throws E1 {}
void e() throws E1, E2 {}
void d() throws E2 {
a(b()::c);
a(<error descr="Unhandled exception: E2">this::e</error>);
}
}
@@ -0,0 +1,3 @@
enum <caret>E {
;
}
@@ -0,0 +1,12 @@
enum A {
B;
private int i;
public int getI() {
return i;
}
public void setI(int i) {
this.i = i;
}
}
@@ -0,0 +1,4 @@
enum A {
B;
private int i;
}
@@ -410,6 +410,10 @@ public class NewMethodRefHighlightingTest extends LightDaemonAnalyzerTestCase {
doTest();
}
public void testUnhandledExceptionsInQualifier() throws Exception {
doTest();
}
private void doTest() {
doTest(false);
}
@@ -22,13 +22,13 @@ import com.intellij.psi.PsiFile
import com.intellij.psi.PsiJavaFile
import com.intellij.psi.impl.PsiDocumentManagerBase
import com.intellij.psi.impl.source.PsiFileImpl
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.testFramework.BombedProgressIndicator
import com.intellij.testFramework.PlatformTestUtil
import com.intellij.testFramework.SkipSlowTestLocally
import com.intellij.testFramework.fixtures.JavaCodeInsightFixtureTestCase
import java.util.concurrent.CountDownLatch
/**
* @author peter
*/
@@ -128,4 +128,46 @@ class ConcurrentIndexTest extends JavaCodeInsightFixtureTestCase {
for(future in futuresToWait) future.get();
}
}
public void "test forceUpdateAffectsReadOfDataForUnsavedDocuments"() {
def N = Math.max(2, (int)(Runtime.runtime.availableProcessors()));
PsiFileImpl file = (PsiFileImpl) myFixture.addFileToProject("Foo.java", "class Foo {" + ("public void foo() {}\n") * 1000 + "}")
assert myFixture.findClass("Foo").node
for (i in 1..20) {
println "iteration $i"
WriteCommandAction.runWriteCommandAction(project) {
((PsiJavaFile) file).importList.add(JavaPsiFacade.getElementFactory(project).createImportStatementOnDemand("foo.bar$i"))
}
PlatformTestUtil.tryGcSoftlyReachableObjects()
assert !file.contentsLoaded
myFixture.addFileToProject("Foo" + i + ".java", "class Foo" + i + " {" + ("public void foo() {}\n") * 1000 + "}")
def futuresToWait = []
def sameStartCondition = new CountDownLatch(N)
for(j in 1..N/2) {
futuresToWait.add(ApplicationManager.application.executeOnPooledThread {
ApplicationManager.application.runReadAction {
sameStartCondition.countDown()
sameStartCondition.await()
assert myFixture.getJavaFacade().findClass("Foo", GlobalSearchScope.fileScope(file)).node
}
})
}
for(j in 1..N/2) {
futuresToWait.add(ApplicationManager.application.executeOnPooledThread {
ApplicationManager.application.runReadAction {
sameStartCondition.countDown()
sameStartCondition.await()
assert myFixture.findClass("Foo" + i).node
}
});
}
for(future in futuresToWait) future.get();
}
}
}
@@ -46,28 +46,22 @@ public abstract class ChangeSignatureBaseTest extends LightRefactoringTestCase {
@Nullable final String[] parameters,
@Nullable final String[] exceptions,
boolean delegate) {
GenParams genParams = parameters == null ? new SimpleParameterGen() : new GenParams() {
@Override
public ParameterInfoImpl[] genParams(PsiMethod method) throws IncorrectOperationException {
ParameterInfoImpl[] parameterInfos = new ParameterInfoImpl[parameters.length];
for (int i = 0; i < parameters.length; i++) {
PsiType type = myFactory.createTypeFromText(parameters[i], method);
parameterInfos[i] = new ParameterInfoImpl(-1, "p" + (i + 1), type);
}
return parameterInfos;
GenParams genParams = parameters == null ? new SimpleParameterGen() : method -> {
ParameterInfoImpl[] parameterInfos = new ParameterInfoImpl[parameters.length];
for (int i = 0; i < parameters.length; i++) {
PsiType type = myFactory.createTypeFromText(parameters[i], method);
parameterInfos[i] = new ParameterInfoImpl(-1, "p" + (i + 1), type);
}
return parameterInfos;
};
GenExceptions genExceptions = exceptions == null ? new SimpleExceptionsGen() : new GenExceptions() {
@Override
public ThrownExceptionInfo[] genExceptions(PsiMethod method) throws IncorrectOperationException {
ThrownExceptionInfo[] exceptionInfos = new ThrownExceptionInfo[exceptions.length];
for (int i = 0; i < exceptions.length; i++) {
PsiType type = myFactory.createTypeFromText(exceptions[i], method);
exceptionInfos[i] = new JavaThrownExceptionInfo(-1, (PsiClassType)type);
}
return exceptionInfos;
GenExceptions genExceptions = exceptions == null ? new SimpleExceptionsGen() : method -> {
ThrownExceptionInfo[] exceptionInfos = new ThrownExceptionInfo[exceptions.length];
for (int i = 0; i < exceptions.length; i++) {
PsiType type = myFactory.createTypeFromText(exceptions[i], method);
exceptionInfos[i] = new JavaThrownExceptionInfo(-1, (PsiClassType)type);
}
return exceptionInfos;
};
doTest(null, null, returnType, genParams, genExceptions, delegate);
@@ -102,34 +102,28 @@ public class ChangeSignatureGestureTest extends LightCodeInsightFixtureTestCase
}
public void testOnAnotherMethod() {
doTest(new Runnable() {
@Override
public void run() {
myFixture.type("int param");
final int nextMethodOffset = ((PsiJavaFile)myFixture.getFile()).getClasses()[0].getMethods()[1].getTextOffset();
myFixture.getEditor().getCaretModel().moveToOffset(nextMethodOffset);
}
doTest(() -> {
myFixture.type("int param");
final int nextMethodOffset = ((PsiJavaFile)myFixture.getFile()).getClasses()[0].getMethods()[1].getTextOffset();
myFixture.getEditor().getCaretModel().moveToOffset(nextMethodOffset);
}, false, ChangeSignatureDetectorAction.CHANGE_SIGNATURE);
}
public void testAddParamChangeReturnType() {
doTest(new Runnable() {
@Override
public void run() {
myFixture.type("int param");
CaretModel model = myFixture.getEditor().getCaretModel();
PsiElement element = myFixture.getElementAtCaret();
PsiMethod method = PsiTreeUtil.getParentOfType(element, PsiMethod.class, false);
assertTrue(method != null);
PsiTypeElement returnTypeElement = method.getReturnTypeElement();
assertTrue(returnTypeElement != null);
model.moveToOffset(returnTypeElement.getTextRange().getEndOffset());
int i = returnTypeElement.getTextLength();
while (i-- > 0) {
myFixture.type('\b');
}
myFixture.type("boolean");
doTest(() -> {
myFixture.type("int param");
CaretModel model = myFixture.getEditor().getCaretModel();
PsiElement element = myFixture.getElementAtCaret();
PsiMethod method = PsiTreeUtil.getParentOfType(element, PsiMethod.class, false);
assertTrue(method != null);
PsiTypeElement returnTypeElement = method.getReturnTypeElement();
assertTrue(returnTypeElement != null);
model.moveToOffset(returnTypeElement.getTextRange().getEndOffset());
int i = returnTypeElement.getTextLength();
while (i-- > 0) {
myFixture.type('\b');
}
myFixture.type("boolean");
}, true, ChangeSignatureDetectorAction.CHANGE_SIGNATURE);
}
@@ -154,12 +148,7 @@ public class ChangeSignatureGestureTest extends LightCodeInsightFixtureTestCase
}
private void doTypingTest(final String param, final String hint) {
doTest(new Runnable() {
@Override
public void run() {
myFixture.type(param);
}
}, true, hint);
doTest(() -> myFixture.type(param), true, hint);
}
public void testReturnValue() {
@@ -175,12 +164,7 @@ public class ChangeSignatureGestureTest extends LightCodeInsightFixtureTestCase
}
private void doTypingNoBorderTest(final String param) {
doTest(new Runnable() {
@Override
public void run() {
myFixture.type(param);
}
}, false, ChangeSignatureDetectorAction.CHANGE_SIGNATURE);
doTest(() -> myFixture.type(param), false, ChangeSignatureDetectorAction.CHANGE_SIGNATURE);
}
public void testDeleteParamInSuperUsed() {
@@ -188,17 +172,14 @@ public class ChangeSignatureGestureTest extends LightCodeInsightFixtureTestCase
}
private void doDeleteTest() {
doTest(new Runnable() {
@Override
public void run() {
final Editor editor = myFixture.getEditor();
final Document document = editor.getDocument();
final int selectionStart = editor.getSelectionModel().getSelectionStart();
final int selectionEnd = editor.getSelectionModel().getSelectionEnd();
CommandProcessor.getInstance().setCurrentCommandGroupId(EditorActionUtil.DELETE_COMMAND_GROUP);
document.deleteString(selectionStart, selectionEnd);
editor.getCaretModel().moveToOffset(selectionStart);
}
doTest(() -> {
final Editor editor = myFixture.getEditor();
final Document document = editor.getDocument();
final int selectionStart = editor.getSelectionModel().getSelectionStart();
final int selectionEnd = editor.getSelectionModel().getSelectionEnd();
CommandProcessor.getInstance().setCurrentCommandGroupId(EditorActionUtil.DELETE_COMMAND_GROUP);
document.deleteString(selectionStart, selectionEnd);
editor.getCaretModel().moveToOffset(selectionStart);
}, true, ChangeSignatureDetectorAction.CHANGE_SIGNATURE);
}
@@ -34,7 +34,7 @@ public class ChangeSignaturePropagationTest extends LightRefactoringTestCase {
public void testParamTypeSubst() throws Exception {
final PsiMethod method = getPrimaryMethod();
final HashSet<PsiMethod> methods = new HashSet<PsiMethod>();
final HashSet<PsiMethod> methods = new HashSet<>();
for (PsiReference reference : ReferencesSearch.search(method)) {
final PsiMethod psiMethod = PsiTreeUtil.getParentOfType(reference.getElement(), PsiMethod.class);
if (psiMethod != null) {
@@ -63,7 +63,7 @@ public class ChangeSignaturePropagationTest extends LightRefactoringTestCase {
}
private static HashSet<PsiMethod> collectNonPhysicalMethodsToPropagate(PsiMethod method) {
final HashSet<PsiMethod> methodsToPropagate = new HashSet<PsiMethod>();
final HashSet<PsiMethod> methodsToPropagate = new HashSet<>();
final PsiReference[] references =
MethodReferencesSearch.search(method, GlobalSearchScope.allScope(getProject()), true).toArray(PsiReference.EMPTY_ARRAY);
for (PsiReference reference : references) {
@@ -91,7 +91,7 @@ public class ChangeSignaturePropagationTest extends LightRefactoringTestCase {
}
private static HashSet<PsiMethod> collectDefaultConstructorsToPropagate(PsiMethod method) {
final HashSet<PsiMethod> methodsToPropagate = new HashSet<PsiMethod>();
final HashSet<PsiMethod> methodsToPropagate = new HashSet<>();
for (PsiClass inheritor : ClassInheritorsSearch.search(method.getContainingClass())) {
methodsToPropagate.add(inheritor.getConstructors()[0]);
}
@@ -105,7 +105,7 @@ public class ChangeSignaturePropagationTest extends LightRefactoringTestCase {
private void parameterPropagationTest(final PsiClassType paramType) throws Exception {
final PsiMethod method = getPrimaryMethod();
parameterPropagationTest(method, new HashSet<PsiMethod>(Arrays.asList(method.getContainingClass().getMethods())),
parameterPropagationTest(method, new HashSet<>(Arrays.asList(method.getContainingClass().getMethods())),
paramType);
}
@@ -116,7 +116,7 @@ public class ChangeSignaturePropagationTest extends LightRefactoringTestCase {
private void exceptionPropagationTest() throws Exception {
final PsiMethod method = getPrimaryMethod();
exceptionPropagationTest(method, new HashSet<PsiMethod>(Arrays.asList(method.getContainingClass().getMethods())));
exceptionPropagationTest(method, new HashSet<>(Arrays.asList(method.getContainingClass().getMethods())));
}
private void exceptionPropagationTest(final PsiMethod method, final Set<PsiMethod> methodsToPropagateExceptions) throws Exception {
@@ -51,6 +51,11 @@ public class ChangeSignatureTargetTest extends LightCodeInsightTestCase {
doTest("A1");
}
public void testDisabledForEnum() throws Exception {
configureByFile("/refactoring/changeSignatureTarget/" + getTestName(true) + ".java");
assertNull(new JavaChangeSignatureHandler().findTargetMember(getFile(), getEditor()));
}
private void doTest(String expectedMemberName) throws Exception {
String basePath = "/refactoring/changeSignatureTarget/" + getTestName(true);
@NonNls final String filePath = basePath + ".java";
@@ -54,38 +54,23 @@ public class ChangeSignatureTest extends ChangeSignatureBaseTest {
}
public void testGenericTypes() {
doTest(null, null, "T", new GenParams() {
@Override
public ParameterInfoImpl[] genParams(PsiMethod method) throws IncorrectOperationException {
return new ParameterInfoImpl[]{
new ParameterInfoImpl(-1, "x", myFactory.createTypeFromText("T", method.getParameterList()), "null"),
new ParameterInfoImpl(-1, "y", myFactory.createTypeFromText("C<T>", method.getParameterList()), "null")
};
}
doTest(null, null, "T", method -> new ParameterInfoImpl[]{
new ParameterInfoImpl(-1, "x", myFactory.createTypeFromText("T", method.getParameterList()), "null"),
new ParameterInfoImpl(-1, "y", myFactory.createTypeFromText("C<T>", method.getParameterList()), "null")
}, false);
}
public void testGenericTypesInOldParameters() {
doTest(null, null, null, new GenParams() {
@Override
public ParameterInfoImpl[] genParams(PsiMethod method) throws IncorrectOperationException {
return new ParameterInfoImpl[]{
new ParameterInfoImpl(0, "t", myFactory.createTypeFromText("T", method), null)
};
}
doTest(null, null, null, method -> new ParameterInfoImpl[]{
new ParameterInfoImpl(0, "t", myFactory.createTypeFromText("T", method), null)
}, false);
}
public void testTypeParametersInMethod() {
doTest(null, null, null, new GenParams() {
@Override
public ParameterInfoImpl[] genParams(PsiMethod method) throws IncorrectOperationException {
return new ParameterInfoImpl[]{
new ParameterInfoImpl(-1, "t", myFactory.createTypeFromText("T", method.getParameterList()), "null"),
new ParameterInfoImpl(-1, "u", myFactory.createTypeFromText("U", method.getParameterList()), "null"),
new ParameterInfoImpl(-1, "cu", myFactory.createTypeFromText("C<U>", method.getParameterList()), "null")
};
}
doTest(null, null, null, method -> new ParameterInfoImpl[]{
new ParameterInfoImpl(-1, "t", myFactory.createTypeFromText("T", method.getParameterList()), "null"),
new ParameterInfoImpl(-1, "u", myFactory.createTypeFromText("U", method.getParameterList()), "null"),
new ParameterInfoImpl(-1, "cu", myFactory.createTypeFromText("C<U>", method.getParameterList()), "null")
}, false);
}
@@ -215,35 +200,20 @@ public class ChangeSignatureTest extends ChangeSignatureBaseTest {
}
public void testUseAnyVariable() {
doTest(null, null, null, new GenParams() {
@Override
public ParameterInfoImpl[] genParams(PsiMethod method) throws IncorrectOperationException {
return new ParameterInfoImpl[]{
new ParameterInfoImpl(-1, "l", myFactory.createTypeFromText("List", method), "null", true)
};
}
doTest(null, null, null, method -> new ParameterInfoImpl[]{
new ParameterInfoImpl(-1, "l", myFactory.createTypeFromText("List", method), "null", true)
}, false);
}
public void testUseThisAsAnyVariable() {
doTest(null, null, null, new GenParams() {
@Override
public ParameterInfoImpl[] genParams(PsiMethod method) throws IncorrectOperationException {
return new ParameterInfoImpl[]{
new ParameterInfoImpl(-1, "l", myFactory.createTypeFromText("List", method), "null", true)
};
}
doTest(null, null, null, method -> new ParameterInfoImpl[]{
new ParameterInfoImpl(-1, "l", myFactory.createTypeFromText("List", method), "null", true)
}, false);
}
public void testUseAnyVariableAndDefault() {
doTest(null, null, null, new GenParams() {
@Override
public ParameterInfoImpl[] genParams(PsiMethod method) throws IncorrectOperationException {
return new ParameterInfoImpl[]{
new ParameterInfoImpl(-1, "c", myFactory.createTypeFromText("C", method), "null", true)
};
}
doTest(null, null, null, method -> new ParameterInfoImpl[]{
new ParameterInfoImpl(-1, "c", myFactory.createTypeFromText("C", method), "null", true)
}, false);
}
@@ -282,13 +252,10 @@ public class ChangeSignatureTest extends ChangeSignatureBaseTest {
public void testAlreadyHandled() {
doTest(null, null, null, new SimpleParameterGen(new ParameterInfoImpl[0]),
new GenExceptions() {
@Override
public ThrownExceptionInfo[] genExceptions(PsiMethod method) {
return new ThrownExceptionInfo[]{
new JavaThrownExceptionInfo(-1, myFactory.createTypeByFQClassName("java.lang.Exception", method.getResolveScope()))
};
}
method -> {
return new ThrownExceptionInfo[]{
new JavaThrownExceptionInfo(-1, myFactory.createTypeByFQClassName("java.lang.Exception", method.getResolveScope()))
};
},
false
);
@@ -296,13 +263,10 @@ public class ChangeSignatureTest extends ChangeSignatureBaseTest {
public void testConstructorException() {
doTest(null, null, null, new SimpleParameterGen(new ParameterInfoImpl[0]),
new GenExceptions() {
@Override
public ThrownExceptionInfo[] genExceptions(PsiMethod method) {
return new ThrownExceptionInfo[]{
new JavaThrownExceptionInfo(-1, myFactory.createTypeByFQClassName("java.io.IOException", method.getResolveScope()))
};
}
method -> {
return new ThrownExceptionInfo[]{
new JavaThrownExceptionInfo(-1, myFactory.createTypeByFQClassName("java.io.IOException", method.getResolveScope()))
};
},
false
);
@@ -310,13 +274,10 @@ public class ChangeSignatureTest extends ChangeSignatureBaseTest {
public void testAddRuntimeException() {
doTest(null, null, null, new SimpleParameterGen(new ParameterInfoImpl[0]),
new GenExceptions() {
@Override
public ThrownExceptionInfo[] genExceptions(PsiMethod method) {
return new ThrownExceptionInfo[]{
new JavaThrownExceptionInfo(-1, myFactory.createTypeByFQClassName("java.lang.RuntimeException", method.getResolveScope()))
};
}
method -> {
return new ThrownExceptionInfo[]{
new JavaThrownExceptionInfo(-1, myFactory.createTypeByFQClassName("java.lang.RuntimeException", method.getResolveScope()))
};
},
false
);
@@ -324,13 +285,10 @@ public class ChangeSignatureTest extends ChangeSignatureBaseTest {
public void testAddException() {
doTest(null, null, null, new SimpleParameterGen(new ParameterInfoImpl[0]),
new GenExceptions() {
@Override
public ThrownExceptionInfo[] genExceptions(PsiMethod method) {
return new ThrownExceptionInfo[]{
new JavaThrownExceptionInfo(-1, myFactory.createTypeByFQClassName("java.lang.Exception", method.getResolveScope()))
};
}
method -> {
return new ThrownExceptionInfo[]{
new JavaThrownExceptionInfo(-1, myFactory.createTypeByFQClassName("java.lang.Exception", method.getResolveScope()))
};
},
false
);
@@ -357,14 +315,9 @@ public class ChangeSignatureTest extends ChangeSignatureBaseTest {
}
public void testReplaceVarargWithArray() {
doTest(null, null, null, new GenParams() {
@Override
public ParameterInfoImpl[] genParams(PsiMethod method) throws IncorrectOperationException {
return new ParameterInfoImpl[]{
new ParameterInfoImpl(1, "l", myFactory.createTypeFromText("List<T>[]", method.getParameterList()), "null", false),
new ParameterInfoImpl(0, "s", myFactory.createTypeFromText("String", method.getParameterList()))
};
}
doTest(null, null, null, method -> new ParameterInfoImpl[]{
new ParameterInfoImpl(1, "l", myFactory.createTypeFromText("List<T>[]", method.getParameterList()), "null", false),
new ParameterInfoImpl(0, "s", myFactory.createTypeFromText("String", method.getParameterList()))
}, false);
}
@@ -405,7 +358,7 @@ public class ChangeSignatureTest extends ChangeSignatureBaseTest {
final PsiMethod[] callers = containingClass.findMethodsByName("caller", false);
assertTrue(callers.length > 0);
final PsiMethod caller = callers[0];
final HashSet<PsiMethod> propagateParametersMethods = new HashSet<PsiMethod>();
final HashSet<PsiMethod> propagateParametersMethods = new HashSet<>();
propagateParametersMethods.add(caller);
final PsiParameter[] parameters = method.getParameterList().getParameters();
new ChangeSignatureProcessor(getProject(), method, false, null, method.getName(),
@@ -74,16 +74,10 @@ public class CopyClassTest extends CodeInsightTestCase {
private PsiElement performAction(final String oldName, final String copyName) throws IncorrectOperationException {
final PsiClass oldClass = JavaPsiFacade.getInstance(myProject).findClass(oldName, ProjectScope.getAllScope(myProject));
return WriteCommandAction.runWriteCommandAction(null, new Computable<PsiElement>(){
@Override
public PsiElement compute() {
return CopyClassesHandler.doCopyClasses(
Collections.singletonMap(oldClass.getNavigationElement().getContainingFile(), new PsiClass[]{oldClass}), copyName,
myPsiManager.findDirectory(myRootDir),
myProject);
}
});
return WriteCommandAction.runWriteCommandAction(null, (Computable<PsiElement>)() -> CopyClassesHandler.doCopyClasses(
Collections.singletonMap(oldClass.getNavigationElement().getContainingFile(), new PsiClass[]{oldClass}), copyName,
myPsiManager.findDirectory(myRootDir),
myProject));
}
public void testPackageLocalClasses() throws Exception {
@@ -101,7 +95,7 @@ public class CopyClassTest extends CodeInsightTestCase {
PsiTestUtil.removeAllRoots(myModule, IdeaTestUtil.getMockJdk17());
VirtualFile rootDir = PsiTestUtil.createTestProjectStructure(myProject, myModule, rootBefore, myFilesToDelete);
final HashMap<PsiFile, PsiClass[]> map = new HashMap<PsiFile, PsiClass[]>();
final HashMap<PsiFile, PsiClass[]> map = new HashMap<>();
final VirtualFile sourceDir = rootDir.findChild("p1");
for (VirtualFile file : sourceDir.getChildren()) {
final PsiFile psiFile = myPsiManager.findFile(file);
@@ -36,23 +36,11 @@ public class DndMoveTest extends CodeInsightTestCase {
}
public void testPublicJavaClass() throws Exception {
doTest("d", new Computable<PsiElement>() {
@Nullable
@Override
public PsiElement compute() {
return getJavaFacade().findClass("d.MyClass");
}
}, true);
doTest("d", () -> getJavaFacade().findClass("d.MyClass"), true);
}
public void testSecondJavaClass() throws Exception {
doTest("d", new Computable<PsiElement>() {
@Nullable
@Override
public PsiElement compute() {
return getJavaFacade().findClass("d.Second");
}
}, false);
doTest("d", () -> getJavaFacade().findClass("d.Second"), false);
}
private void doTest(final String targetDirName, final Computable<PsiElement> source, final boolean expected) throws Exception {
@@ -25,16 +25,11 @@ import com.intellij.codeInsight.generation.GenerateMembersUtil;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiClass;
import com.intellij.psi.PsiField;
import com.intellij.psi.PsiModifier;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.util.PropertyUtil;
import com.intellij.refactoring.encapsulateFields.EncapsulateFieldsDescriptor;
import com.intellij.refactoring.encapsulateFields.EncapsulateFieldsProcessor;
import com.intellij.refactoring.encapsulateFields.FieldDescriptor;
import com.intellij.refactoring.encapsulateFields.FieldDescriptorImpl;
import com.intellij.refactoring.encapsulateFields.*;
import com.intellij.refactoring.util.DocCommentPolicy;
import junit.framework.Assert;
import org.jetbrains.annotations.NotNull;
@@ -77,15 +72,20 @@ public class EncapsulateFieldsTest extends MultiFileTestCase{
}
public void testMoveJavadocToGetter() throws Exception {
doTest(new PerformAction() {
@Override
public void performAction(VirtualFile rootDir, VirtualFile rootAfter) throws Exception {
final PsiClass aClass = myJavaFacade.findClass("A", GlobalSearchScope.projectScope(myProject));
assertNotNull("Tested class not found", aClass);
final PsiField field = aClass.findFieldByName("i", false);
assertNotNull(field);
doTest(aClass, field, null, true, true);
}
doTest((rootDir, rootAfter) -> {
final PsiClass aClass = myJavaFacade.findClass("A", GlobalSearchScope.projectScope(myProject));
assertNotNull("Tested class not found", aClass);
final PsiField field = aClass.findFieldByName("i", false);
assertNotNull(field);
doTest(aClass, null, true, true, field);
});
}
public void testFilterEnumConstants() throws Exception {
doTest((rootDir, rootAfter) -> {
final PsiClass aClass = myJavaFacade.findClass("A", GlobalSearchScope.projectScope(myProject));
assertNotNull("Tested class not found", aClass);
doTest(aClass, null, true, true, new JavaEncapsulateFieldHelper().getApplicableFields(aClass));
});
}
@@ -106,37 +106,38 @@ public class EncapsulateFieldsTest extends MultiFileTestCase{
}
private void doTest(final String fieldName, final String className, final String conflicts) throws Exception {
doTest(new PerformAction() {
@Override
public void performAction(final VirtualFile rootDir, final VirtualFile rootAfter) throws Exception {
PsiClass aClass = myJavaFacade.findClass(className, GlobalSearchScope.projectScope(myProject));
doTest((rootDir, rootAfter) -> {
PsiClass aClass = myJavaFacade.findClass(className, GlobalSearchScope.projectScope(myProject));
assertNotNull("Tested class not found", aClass);
assertNotNull("Tested class not found", aClass);
doTest(aClass, aClass.findFieldByName(fieldName, false), conflicts, true, true);
}
doTest(aClass, conflicts, true, true, aClass.findFieldByName(fieldName, false));
});
}
private static void doTest(final PsiClass aClass,
final PsiField field,
final String conflicts,
final boolean generateGetters,
final boolean generateSetters) {
final boolean generateSetters,
final PsiField... fields) {
try {
final Project project = aClass.getProject();
EncapsulateFieldsProcessor processor = new EncapsulateFieldsProcessor(project, new EncapsulateFieldsDescriptor() {
@Override
public FieldDescriptor[] getSelectedFields() {
return new FieldDescriptor[]{new FieldDescriptorImpl(
field,
GenerateMembersUtil.suggestGetterName(field),
GenerateMembersUtil.suggestSetterName(field),
isToEncapsulateGet() ? GenerateMembersUtil.generateGetterPrototype(field) : null,
isToEncapsulateSet() ? GenerateMembersUtil.generateSetterPrototype(field) : null
)};
final FieldDescriptor[] descriptors = new FieldDescriptor[fields.length];
for (int i = 0; i < fields.length; i++) {
descriptors[i] = new FieldDescriptorImpl(
fields[i],
GenerateMembersUtil.suggestGetterName(fields[i]),
GenerateMembersUtil.suggestSetterName(fields[i]),
isToEncapsulateGet() ? GenerateMembersUtil.generateGetterPrototype(fields[i]) : null,
isToEncapsulateSet() ? GenerateMembersUtil.generateSetterPrototype(fields[i]) : null
);
}
return descriptors;
}
@Override
@@ -67,18 +67,15 @@ public class ExtractClassTest extends MultiFileTestCase{
private void doTestMethod(final String methodName,
final String conflicts,
final String qualifiedName) throws Exception {
doTest(new PerformAction() {
@Override
public void performAction(final VirtualFile rootDir, final VirtualFile rootAfter) throws Exception {
PsiClass aClass = myJavaFacade.findClass(qualifiedName, GlobalSearchScope.projectScope(myProject));
doTest((rootDir, rootAfter) -> {
PsiClass aClass = myJavaFacade.findClass(qualifiedName, GlobalSearchScope.projectScope(myProject));
assertNotNull("Class Test not found", aClass);
assertNotNull("Class Test not found", aClass);
final ArrayList<PsiMethod> methods = new ArrayList<PsiMethod>();
methods.add(aClass.findMethodsByName(methodName, false)[0]);
doTest(aClass, methods, new ArrayList<PsiField>(), conflicts, false);
}
final ArrayList<PsiMethod> methods = new ArrayList<>();
methods.add(aClass.findMethodsByName(methodName, false)[0]);
doTest(aClass, methods, new ArrayList<>(), conflicts, false);
});
}
@@ -151,21 +148,18 @@ public class ExtractClassTest extends MultiFileTestCase{
}
private void doTestFieldAndMethod(final String methodName) throws Exception {
doTest(new PerformAction() {
@Override
public void performAction(final VirtualFile rootDir, final VirtualFile rootAfter) throws Exception {
PsiClass aClass = myJavaFacade.findClass("Test", GlobalSearchScope.projectScope(myProject));
doTest((rootDir, rootAfter) -> {
PsiClass aClass = myJavaFacade.findClass("Test", GlobalSearchScope.projectScope(myProject));
assertNotNull("Class Test not found", aClass);
assertNotNull("Class Test not found", aClass);
final ArrayList<PsiMethod> methods = new ArrayList<PsiMethod>();
methods.add(aClass.findMethodsByName(methodName, false)[0]);
final ArrayList<PsiMethod> methods = new ArrayList<>();
methods.add(aClass.findMethodsByName(methodName, false)[0]);
final ArrayList<PsiField> fields = new ArrayList<PsiField>();
fields.add(aClass.findFieldByName("myT", false));
final ArrayList<PsiField> fields = new ArrayList<>();
fields.add(aClass.findFieldByName("myT", false));
doTest(aClass, methods, fields, null, false);
}
doTest(aClass, methods, fields, null, false);
});
}
@@ -174,27 +168,24 @@ public class ExtractClassTest extends MultiFileTestCase{
}
private void doTestField(final String conflicts, final boolean generateGettersSetters) throws Exception {
doTest(new PerformAction() {
@Override
public void performAction(final VirtualFile rootDir, final VirtualFile rootAfter) throws Exception {
PsiClass aClass = myJavaFacade.findClass("Test", GlobalSearchScope.projectScope(myProject));
doTest((rootDir, rootAfter) -> {
PsiClass aClass = myJavaFacade.findClass("Test", GlobalSearchScope.projectScope(myProject));
assertNotNull("Class Test not found", aClass);
assertNotNull("Class Test not found", aClass);
final ArrayList<PsiMethod> methods = new ArrayList<PsiMethod>();
final ArrayList<PsiMethod> methods = new ArrayList<>();
final ArrayList<PsiField> fields = new ArrayList<PsiField>();
fields.add(aClass.findFieldByName("myT", false));
final ArrayList<PsiField> fields = new ArrayList<>();
fields.add(aClass.findFieldByName("myT", false));
doTest(aClass, methods, fields, conflicts, generateGettersSetters);
}
doTest(aClass, methods, fields, conflicts, generateGettersSetters);
});
}
private static void doTest(final PsiClass aClass, final ArrayList<PsiMethod> methods, final ArrayList<PsiField> fields, final String conflicts,
boolean generateGettersSetters) {
try {
ExtractClassProcessor processor = new ExtractClassProcessor(aClass, fields, methods, new ArrayList<PsiClass>(), StringUtil.getPackageName(aClass.getQualifiedName()), null,
ExtractClassProcessor processor = new ExtractClassProcessor(aClass, fields, methods, new ArrayList<>(), StringUtil.getPackageName(aClass.getQualifiedName()), null,
"Extracted", null, generateGettersSetters, Collections.<MemberInfo>emptyList());
processor.run();
LocalFileSystem.getInstance().refresh(false);
@@ -233,39 +224,33 @@ public class ExtractClassTest extends MultiFileTestCase{
}
public void testPublicFieldDelegation() throws Exception {
doTest(new PerformAction() {
@Override
public void performAction(final VirtualFile rootDir, final VirtualFile rootAfter) throws Exception {
PsiClass aClass = myJavaFacade.findClass("Test", GlobalSearchScope.projectScope(myProject));
doTest((rootDir, rootAfter) -> {
PsiClass aClass = myJavaFacade.findClass("Test", GlobalSearchScope.projectScope(myProject));
assertNotNull("Class Test not found", aClass);
assertNotNull("Class Test not found", aClass);
final ArrayList<PsiField> fields = new ArrayList<PsiField>();
fields.add(aClass.findFieldByName("myT", false));
final ArrayList<PsiField> fields = new ArrayList<>();
fields.add(aClass.findFieldByName("myT", false));
ExtractClassProcessor processor = new ExtractClassProcessor(aClass, fields, new ArrayList<PsiMethod>(), new ArrayList<PsiClass>(), "", "Extracted");
processor.run();
LocalFileSystem.getInstance().refresh(false);
FileDocumentManager.getInstance().saveAllDocuments();
}
ExtractClassProcessor processor = new ExtractClassProcessor(aClass, fields, new ArrayList<>(), new ArrayList<>(), "", "Extracted");
processor.run();
LocalFileSystem.getInstance().refresh(false);
FileDocumentManager.getInstance().saveAllDocuments();
});
}
private void doTestInnerClass() throws Exception {
doTest(new PerformAction() {
@Override
public void performAction(final VirtualFile rootDir, final VirtualFile rootAfter) throws Exception {
PsiClass aClass = myJavaFacade.findClass("Test", GlobalSearchScope.projectScope(myProject));
doTest((rootDir, rootAfter) -> {
PsiClass aClass = myJavaFacade.findClass("Test", GlobalSearchScope.projectScope(myProject));
assertNotNull("Class Test not found", aClass);
assertNotNull("Class Test not found", aClass);
final ArrayList<PsiClass> classes = new ArrayList<PsiClass>();
classes.add(aClass.findInnerClassByName("Inner", false));
ExtractClassProcessor processor = new ExtractClassProcessor(aClass, new ArrayList<PsiField>(), new ArrayList<PsiMethod>(), classes, "", "Extracted");
processor.run();
LocalFileSystem.getInstance().refresh(false);
FileDocumentManager.getInstance().saveAllDocuments();
}
final ArrayList<PsiClass> classes = new ArrayList<>();
classes.add(aClass.findInnerClassByName("Inner", false));
ExtractClassProcessor processor = new ExtractClassProcessor(aClass, new ArrayList<>(), new ArrayList<>(), classes, "", "Extracted");
processor.run();
LocalFileSystem.getInstance().refresh(false);
FileDocumentManager.getInstance().saveAllDocuments();
});
}
@@ -302,25 +287,22 @@ public class ExtractClassTest extends MultiFileTestCase{
}
public void testPublicVisibility() throws Exception {
doTest(new PerformAction() {
@Override
public void performAction(final VirtualFile rootDir, final VirtualFile rootAfter) throws Exception {
PsiClass aClass = myJavaFacade.findClass("Test", GlobalSearchScope.projectScope(myProject));
doTest((rootDir, rootAfter) -> {
PsiClass aClass = myJavaFacade.findClass("Test", GlobalSearchScope.projectScope(myProject));
assertNotNull("Class Test not found", aClass);
assertNotNull("Class Test not found", aClass);
final ArrayList<PsiMethod> methods = new ArrayList<PsiMethod>();
methods.add(aClass.findMethodsByName("foos", false)[0]);
final ArrayList<PsiMethod> methods = new ArrayList<>();
methods.add(aClass.findMethodsByName("foos", false)[0]);
final ArrayList<PsiField> fields = new ArrayList<PsiField>();
fields.add(aClass.findFieldByName("myT", false));
final ArrayList<PsiField> fields = new ArrayList<>();
fields.add(aClass.findFieldByName("myT", false));
final ExtractClassProcessor processor =
new ExtractClassProcessor(aClass, fields, methods, new ArrayList<PsiClass>(), "", null, "Extracted", PsiModifier.PUBLIC, false, Collections.<MemberInfo>emptyList());
processor.run();
LocalFileSystem.getInstance().refresh(false);
FileDocumentManager.getInstance().saveAllDocuments();
}
final ExtractClassProcessor processor =
new ExtractClassProcessor(aClass, fields, methods, new ArrayList<>(), "", null, "Extracted", PsiModifier.PUBLIC, false, Collections.<MemberInfo>emptyList());
processor.run();
LocalFileSystem.getInstance().refresh(false);
FileDocumentManager.getInstance().saveAllDocuments();
});
}
}
@@ -144,53 +144,50 @@ public class ExtractEnumTest extends MultiFileTestCase {
private void doTest(final String conflicts,
final boolean generateAccessors,
final RefactoringTestUtil.MemberDescriptor... memberDescriptors) throws Exception {
doTest(new PerformAction() {
@Override
public void performAction(VirtualFile rootDir, VirtualFile rootAfter) throws Exception {
final PsiClass aClass = myJavaFacade.findClass("Test", GlobalSearchScope.projectScope(myProject));
assertNotNull("Class Test not found", aClass);
doTest((rootDir, rootAfter) -> {
final PsiClass aClass = myJavaFacade.findClass("Test", GlobalSearchScope.projectScope(myProject));
assertNotNull("Class Test not found", aClass);
final ArrayList<PsiField> fields = new ArrayList<PsiField>();
final ArrayList<PsiMethod> methods = new ArrayList<PsiMethod>();
final List<MemberInfo> enumConstants = new ArrayList<MemberInfo>();
for (MemberInfo memberInfo : RefactoringTestUtil.findMembers(aClass, memberDescriptors)) {
final PsiMember member = memberInfo.getMember();
if (member instanceof PsiField) {
fields.add((PsiField)member);
if (member.hasModifierProperty(PsiModifier.STATIC) && member.hasModifierProperty(PsiModifier.FINAL) && ((PsiField)member).hasInitializer()) {
if (memberInfo.isToAbstract()) {
enumConstants.add(memberInfo);
memberInfo.setChecked(true);
}
final ArrayList<PsiField> fields = new ArrayList<>();
final ArrayList<PsiMethod> methods = new ArrayList<>();
final List<MemberInfo> enumConstants = new ArrayList<>();
for (MemberInfo memberInfo : RefactoringTestUtil.findMembers(aClass, memberDescriptors)) {
final PsiMember member = memberInfo.getMember();
if (member instanceof PsiField) {
fields.add((PsiField)member);
if (member.hasModifierProperty(PsiModifier.STATIC) && member.hasModifierProperty(PsiModifier.FINAL) && ((PsiField)member).hasInitializer()) {
if (memberInfo.isToAbstract()) {
enumConstants.add(memberInfo);
memberInfo.setChecked(true);
}
}
else if (member instanceof PsiMethod) {
methods.add((PsiMethod)member);
}
}
try {
final ExtractClassProcessor processor =
new ExtractClassProcessor(aClass, fields, methods, new ArrayList<PsiClass>(), "", null, "EEnum",
null, generateAccessors, enumConstants);
else if (member instanceof PsiMethod) {
methods.add((PsiMethod)member);
}
}
try {
final ExtractClassProcessor processor =
new ExtractClassProcessor(aClass, fields, methods, new ArrayList<>(), "", null, "EEnum",
null, generateAccessors, enumConstants);
processor.run();
LocalFileSystem.getInstance().refresh(false);
FileDocumentManager.getInstance().saveAllDocuments();
}
catch (BaseRefactoringProcessor.ConflictsInTestsException e) {
if (conflicts != null) {
TreeSet expectedConflictsSet = new TreeSet(Arrays.asList(conflicts.split("\n")));
TreeSet actualConflictsSet = new TreeSet(Arrays.asList(e.getMessage().split("\n")));
Assert.assertEquals(expectedConflictsSet, actualConflictsSet);
return;
}
else {
fail(e.getMessage());
}
}
processor.run();
LocalFileSystem.getInstance().refresh(false);
FileDocumentManager.getInstance().saveAllDocuments();
}
catch (BaseRefactoringProcessor.ConflictsInTestsException e) {
if (conflicts != null) {
fail("Conflicts were not detected: " + conflicts);
TreeSet expectedConflictsSet = new TreeSet(Arrays.asList(conflicts.split("\n")));
TreeSet actualConflictsSet = new TreeSet(Arrays.asList(e.getMessage().split("\n")));
Assert.assertEquals(expectedConflictsSet, actualConflictsSet);
return;
}
else {
fail(e.getMessage());
}
}
if (conflicts != null) {
fail("Conflicts were not detected: " + conflicts);
}
});
}
@@ -41,10 +41,8 @@ public class ExtractMethodObjectTest extends LightRefactoringTestCase {
extractProcessor.prepare();
extractProcessor.testPrepare();
ApplicationManager.getApplication().runWriteAction(new Runnable() {
public void run() {
ExtractMethodObjectHandler.run(getProject(), getEditor(), processor, extractProcessor);
}
ApplicationManager.getApplication().runWriteAction(() -> {
ExtractMethodObjectHandler.run(getProject(), getEditor(), processor, extractProcessor);
});
@@ -48,10 +48,8 @@ public class ExtractMethodObjectWithMultipleExitPointsTest extends LightRefactor
processor.setCreateInnerClass(createInnerClass);
ApplicationManager.getApplication().runWriteAction(new Runnable() {
public void run() {
ExtractMethodObjectHandler.run(getProject(), getEditor(), processor, extractProcessor);
}
ApplicationManager.getApplication().runWriteAction(() -> {
ExtractMethodObjectHandler.run(getProject(), getEditor(), processor, extractProcessor);
});
@@ -174,7 +174,7 @@ public class ExtractSuperClassTest extends RefactoringTestCase {
newClassName,
psiClass, members,
false,
new DocCommentPolicy<PsiComment>(DocCommentPolicy.ASIS));
new DocCommentPolicy<>(DocCommentPolicy.ASIS));
final PsiPackage targetPackage;
if (targetDirectory != null) {
targetPackage = JavaDirectoryService.getInstance().getPackage(targetDirectory);
@@ -184,18 +184,14 @@ public class ExtractSuperClassTest extends RefactoringTestCase {
}
final PsiClass superClass = psiClass.getExtendsListTypes().length > 0 ? psiClass.getSuperClass() : null;
final MultiMap<PsiElement, String> conflictsMap =
PullUpConflictsUtil.checkConflicts(members, psiClass, superClass, targetPackage, targetDirectory, new InterfaceContainmentVerifier() {
@Override
public boolean checkedInterfacesContain(PsiMethod psiMethod) {
return PullUpProcessor.checkedInterfacesContain(Arrays.asList(members), psiMethod);
}
}, false);
PullUpConflictsUtil.checkConflicts(members, psiClass, superClass, targetPackage, targetDirectory,
psiMethod -> PullUpProcessor.checkedInterfacesContain(Arrays.asList(members), psiMethod), false);
if (conflicts != null) {
if (conflictsMap.isEmpty()) {
fail("Conflicts were not detected");
}
final HashSet<String> expectedConflicts = new HashSet<String>(Arrays.asList(conflicts));
final HashSet<String> actualConflicts = new HashSet<String>(conflictsMap.values());
final HashSet<String> expectedConflicts = new HashSet<>(Arrays.asList(conflicts));
final HashSet<String> actualConflicts = new HashSet<>(conflictsMap.values());
assertEquals(expectedConflicts.size(), actualConflicts.size());
for (String actualConflict : actualConflicts) {
if (!expectedConflicts.contains(actualConflict)) {
@@ -32,7 +32,7 @@ public abstract class FixMethodJavadocTest extends FileSetTestCase {
final PsiManager manager = PsiManager.getInstance(myProject);
final PsiElementFactory factory = JavaPsiFacade.getInstance(manager.getProject()).getElementFactory();
final PsiMethod method = factory.createMethodFromText(data[0], null);
final HashSet<PsiParameter> newParameters = new HashSet<PsiParameter>();
final HashSet<PsiParameter> newParameters = new HashSet<>();
if (data.length == 2) {
final String[] strings = data[1].split("\\s+");
collectNewParameters(method, strings, newParameters);
@@ -42,7 +42,7 @@ public abstract class FixMethodJavadocTest extends FileSetTestCase {
}
private void collectNewParameters(PsiMethod method, String[] names, Set<PsiParameter> newParameters) {
Set<String> newNames = new HashSet<String>(Arrays.asList(names));
Set<String> newNames = new HashSet<>(Arrays.asList(names));
final PsiParameter[] parameters = method.getParameterList().getParameters();
for (int i = 0; i < parameters.length; i++) {
PsiParameter parameter = parameters[i];
@@ -139,30 +139,27 @@ public class InheritanceToDelegationTest extends MultiFileTestCase {
final String className, final String fieldName, final String innerClassName,
final String baseClassName, final int[] methodIndices, final String[] delegatedInterfaceNames,
final boolean delegateOtherMembers, final boolean generateGetter) {
return new PerformAction() {
@Override
public void performAction(VirtualFile rootDir, VirtualFile rootAfter) throws Exception {
PsiClass aClass = myJavaFacade.findClass(className, GlobalSearchScope.allScope(getProject()));
assertNotNull("Class " + className + " not found", aClass);
PsiClass baseClass = myJavaFacade.findClass(baseClassName, GlobalSearchScope.allScope(getProject()));
assertNotNull("Base class " + baseClassName + " not found", baseClass);
final PsiMethod[] methods = baseClass.getMethods();
final PsiMethod[] delegatedMethods = new PsiMethod[methodIndices.length];
for (int i = 0; i < methodIndices.length; i++) {
delegatedMethods[i] = methods[methodIndices[i]];
}
final PsiClass[] delegatedInterfaces = new PsiClass[delegatedInterfaceNames.length];
for (int i = 0; i < delegatedInterfaceNames.length; i++) {
String delegatedInterfaceName = delegatedInterfaceNames[i];
PsiClass anInterface = myJavaFacade.findClass(delegatedInterfaceName, GlobalSearchScope.allScope(getProject()));
assertNotNull(anInterface);
delegatedInterfaces[i] = anInterface;
}
new InheritanceToDelegationProcessor(
myProject,
aClass, baseClass, fieldName, innerClassName, delegatedInterfaces, delegatedMethods, delegateOtherMembers,
generateGetter).run();
return (rootDir, rootAfter) -> {
PsiClass aClass = myJavaFacade.findClass(className, GlobalSearchScope.allScope(getProject()));
assertNotNull("Class " + className + " not found", aClass);
PsiClass baseClass = myJavaFacade.findClass(baseClassName, GlobalSearchScope.allScope(getProject()));
assertNotNull("Base class " + baseClassName + " not found", baseClass);
final PsiMethod[] methods = baseClass.getMethods();
final PsiMethod[] delegatedMethods = new PsiMethod[methodIndices.length];
for (int i = 0; i < methodIndices.length; i++) {
delegatedMethods[i] = methods[methodIndices[i]];
}
final PsiClass[] delegatedInterfaces = new PsiClass[delegatedInterfaceNames.length];
for (int i = 0; i < delegatedInterfaceNames.length; i++) {
String delegatedInterfaceName = delegatedInterfaceNames[i];
PsiClass anInterface = myJavaFacade.findClass(delegatedInterfaceName, GlobalSearchScope.allScope(getProject()));
assertNotNull(anInterface);
delegatedInterfaces[i] = anInterface;
}
new InheritanceToDelegationProcessor(
myProject,
aClass, baseClass, fieldName, innerClassName, delegatedInterfaces, delegatedMethods, delegateOtherMembers,
generateGetter).run();
};
}
@@ -170,34 +167,31 @@ public class InheritanceToDelegationTest extends MultiFileTestCase {
final String className, final String fieldName, final String innerClassName,
final String baseClassName, final String[] methodNames, final String[] delegatedInterfaceNames,
final boolean delegateOtherMembers, final boolean generateGetter) {
return new PerformAction() {
@Override
public void performAction(VirtualFile rootDir, VirtualFile rootAfter) throws Exception {
PsiClass aClass = myJavaFacade.findClass(className, GlobalSearchScope.allScope(getProject()));
assertNotNull("Class " + className + " not found", aClass);
PsiClass baseClass = myJavaFacade.findClass(baseClassName, GlobalSearchScope.allScope(getProject()));
assertNotNull("Base class " + baseClassName + " not found", baseClass);
final PsiMethod[] delegatedMethods;
final List<PsiMethod> methodsList = new ArrayList<PsiMethod>();
for (String name : methodNames) {
final PsiMethod[] methodsByName = baseClass.findMethodsByName(name, false);
ContainerUtil.addAll(methodsList, methodsByName);
}
delegatedMethods = methodsList.toArray(new PsiMethod[methodsList.size()]);
final PsiClass[] delegatedInterfaces = new PsiClass[delegatedInterfaceNames.length];
for (int i = 0; i < delegatedInterfaceNames.length; i++) {
String delegatedInterfaceName = delegatedInterfaceNames[i];
PsiClass anInterface = myJavaFacade.findClass(delegatedInterfaceName, GlobalSearchScope.allScope(getProject()));
assertNotNull(anInterface);
delegatedInterfaces[i] = anInterface;
}
new InheritanceToDelegationProcessor(
myProject,
aClass, baseClass, fieldName, innerClassName, delegatedInterfaces, delegatedMethods, delegateOtherMembers,
generateGetter).run();
//FileDocumentManager.getInstance().saveAllDocuments();
return (rootDir, rootAfter) -> {
PsiClass aClass = myJavaFacade.findClass(className, GlobalSearchScope.allScope(getProject()));
assertNotNull("Class " + className + " not found", aClass);
PsiClass baseClass = myJavaFacade.findClass(baseClassName, GlobalSearchScope.allScope(getProject()));
assertNotNull("Base class " + baseClassName + " not found", baseClass);
final PsiMethod[] delegatedMethods;
final List<PsiMethod> methodsList = new ArrayList<>();
for (String name : methodNames) {
final PsiMethod[] methodsByName = baseClass.findMethodsByName(name, false);
ContainerUtil.addAll(methodsList, methodsByName);
}
delegatedMethods = methodsList.toArray(new PsiMethod[methodsList.size()]);
final PsiClass[] delegatedInterfaces = new PsiClass[delegatedInterfaceNames.length];
for (int i = 0; i < delegatedInterfaceNames.length; i++) {
String delegatedInterfaceName = delegatedInterfaceNames[i];
PsiClass anInterface = myJavaFacade.findClass(delegatedInterfaceName, GlobalSearchScope.allScope(getProject()));
assertNotNull(anInterface);
delegatedInterfaces[i] = anInterface;
}
new InheritanceToDelegationProcessor(
myProject,
aClass, baseClass, fieldName, innerClassName, delegatedInterfaces, delegatedMethods, delegateOtherMembers,
generateGetter).run();
//FileDocumentManager.getInstance().saveAllDocuments();
};
}
@@ -77,18 +77,15 @@ public class InlineSuperClassTest extends MultiFileTestCase {
private void doTest(boolean fail, final boolean inlineOne) {
try {
doTest(new PerformAction() {
@Override
public void performAction(final VirtualFile rootDir, final VirtualFile rootAfter) throws Exception {
GlobalSearchScope scope = GlobalSearchScope.allScope(myProject);
PsiClass aClass = myJavaFacade.findClass("Test", scope);
if (aClass == null) aClass = myJavaFacade.findClass("p.Test", scope);
assertNotNull("Class Test not found", aClass);
PsiClass superClass = myJavaFacade.findClass("Super", scope);
if (superClass == null) superClass = myJavaFacade.findClass("p1.Super", scope);
assertNotNull("Class Super not found", superClass);
new InlineSuperClassRefactoringProcessor(myProject, inlineOne ? aClass : null, superClass, DocCommentPolicy.ASIS, aClass).run();
}
doTest((rootDir, rootAfter) -> {
GlobalSearchScope scope = GlobalSearchScope.allScope(myProject);
PsiClass aClass = myJavaFacade.findClass("Test", scope);
if (aClass == null) aClass = myJavaFacade.findClass("p.Test", scope);
assertNotNull("Class Test not found", aClass);
PsiClass superClass = myJavaFacade.findClass("Super", scope);
if (superClass == null) superClass = myJavaFacade.findClass("p1.Super", scope);
assertNotNull("Class Super not found", superClass);
new InlineSuperClassRefactoringProcessor(myProject, inlineOne ? aClass : null, superClass, DocCommentPolicy.ASIS, aClass).run();
});
}
catch (BaseRefactoringProcessor.ConflictsInTestsException e) {
@@ -105,17 +102,14 @@ public class InlineSuperClassTest extends MultiFileTestCase {
}
private void doTestMultipleSubclasses() {
doTest(new PerformAction() {
@Override
public void performAction(final VirtualFile rootDir, final VirtualFile rootAfter) throws Exception {
GlobalSearchScope scope = GlobalSearchScope.allScope(myProject);
PsiClass superClass = myJavaFacade.findClass("Super", scope);
if (superClass == null) superClass = myJavaFacade.findClass("p1.Super", scope);
assertNotNull("Class Super not found", superClass);
PsiClass target1 = myJavaFacade.findClass("Test", scope);
PsiClass target2 = myJavaFacade.findClass("Test1", scope);
new InlineSuperClassRefactoringProcessor(myProject, null, superClass, DocCommentPolicy.ASIS, target1, target2).run();
}
doTest((rootDir, rootAfter) -> {
GlobalSearchScope scope = GlobalSearchScope.allScope(myProject);
PsiClass superClass = myJavaFacade.findClass("Super", scope);
if (superClass == null) superClass = myJavaFacade.findClass("p1.Super", scope);
assertNotNull("Class Super not found", superClass);
PsiClass target1 = myJavaFacade.findClass("Test", scope);
PsiClass target2 = myJavaFacade.findClass("Test1", scope);
new InlineSuperClassRefactoringProcessor(myProject, null, superClass, DocCommentPolicy.ASIS, target1, target2).run();
});
}
}
@@ -23,7 +23,6 @@ package com.intellij.refactoring;
import com.intellij.JavaTestUtil;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.*;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.refactoring.introduceparameterobject.IntroduceParameterObjectProcessor;
@@ -48,31 +47,23 @@ public class IntroduceParameterObjectTest extends MultiFileTestCase{
}
private void doTest(final boolean delegate, final boolean createInner) throws Exception {
doTest(delegate, createInner, new Function<PsiMethod, VariableData[]>() {
@Override
public VariableData[] fun(PsiMethod psiMethod) {
return generateParams(psiMethod);
}
});
doTest(delegate, createInner, IntroduceParameterObjectTest::generateParams);
}
private void doTest(final boolean delegate,
final boolean createInner,
final Function<PsiMethod, VariableData[]> function) throws Exception {
doTest(new PerformAction() {
@Override
public void performAction(final VirtualFile rootDir, final VirtualFile rootAfter) throws Exception {
PsiClass aClass = myJavaFacade.findClass("Test", GlobalSearchScope.projectScope(getProject()));
doTest((rootDir, rootAfter) -> {
PsiClass aClass = myJavaFacade.findClass("Test", GlobalSearchScope.projectScope(getProject()));
assertNotNull("Class Test not found", aClass);
assertNotNull("Class Test not found", aClass);
final PsiMethod method = aClass.findMethodsByName("foo", false)[0];
final VariableData[] datas = function.fun(method);
final PsiMethod method = aClass.findMethodsByName("foo", false)[0];
final VariableData[] datas = function.fun(method);
IntroduceParameterObjectProcessor processor = new IntroduceParameterObjectProcessor("Param", "", null, method, datas, delegate, false,
createInner, null, false);
processor.run();
}
IntroduceParameterObjectProcessor processor = new IntroduceParameterObjectProcessor("Param", "", null, method, datas, delegate, false,
createInner, null, false);
processor.run();
});
}
@@ -134,53 +125,44 @@ public class IntroduceParameterObjectTest extends MultiFileTestCase{
}
public void testSameTypeAndVarargs() throws Exception {
doTest(false, false, new Function<PsiMethod, VariableData[]>() {
@Override
public VariableData[] fun(PsiMethod method) {
final PsiParameter[] parameters = method.getParameterList().getParameters();
doTest(false, false, method -> {
final PsiParameter[] parameters = method.getParameterList().getParameters();
final VariableData[] datas = new VariableData[parameters.length - 1];
for (int i = 0; i < parameters.length - 1; i++) {
PsiParameter parameter = parameters[i];
datas[i] = new VariableData(parameter);
datas[i].name = parameter.getName();
datas[i].passAsParameter = true;
}
return datas;
final VariableData[] datas = new VariableData[parameters.length - 1];
for (int i = 0; i < parameters.length - 1; i++) {
PsiParameter parameter = parameters[i];
datas[i] = new VariableData(parameter);
datas[i].name = parameter.getName();
datas[i].passAsParameter = true;
}
return datas;
});
}
public void testCopyJavadoc1() throws Exception {
doTest(false, true, new Function<PsiMethod, VariableData[]>() {
@Override
public VariableData[] fun(PsiMethod method) {
final PsiParameter[] parameters = method.getParameterList().getParameters();
doTest(false, true, method -> {
final PsiParameter[] parameters = method.getParameterList().getParameters();
final VariableData[] datas = new VariableData[parameters.length - 1];
for (int i = 0; i < parameters.length - 1; i++) {
PsiParameter parameter = parameters[i];
datas[i] = new VariableData(parameter);
datas[i].name = parameter.getName();
datas[i].passAsParameter = true;
}
return datas;
final VariableData[] datas = new VariableData[parameters.length - 1];
for (int i = 0; i < parameters.length - 1; i++) {
PsiParameter parameter = parameters[i];
datas[i] = new VariableData(parameter);
datas[i].name = parameter.getName();
datas[i].passAsParameter = true;
}
return datas;
});
}
public void testTypeParametersWithChosenSubtype() throws Exception {
doTest(false, true, new Function<PsiMethod, VariableData[]>() {
@Override
public VariableData[] fun(PsiMethod psiMethod) {
final PsiParameter parameter = psiMethod.getParameterList().getParameters()[0];
final PsiClass collectionClass = getJavaFacade().findClass(CommonClassNames.JAVA_UTIL_COLLECTION);
final VariableData variableData =
new VariableData(parameter, JavaPsiFacade.getElementFactory(getProject()).createType(collectionClass));
variableData.name = parameter.getName();
variableData.passAsParameter = true;
return new VariableData[]{variableData};
}
doTest(false, true, psiMethod -> {
final PsiParameter parameter = psiMethod.getParameterList().getParameters()[0];
final PsiClass collectionClass = getJavaFacade().findClass(CommonClassNames.JAVA_UTIL_COLLECTION);
final VariableData variableData =
new VariableData(parameter, JavaPsiFacade.getElementFactory(getProject()).createType(collectionClass));
variableData.name = parameter.getName();
variableData.passAsParameter = true;
return new VariableData[]{variableData};
});
}
@@ -198,23 +180,20 @@ public class IntroduceParameterObjectTest extends MultiFileTestCase{
private void doTestExistingClass(final String existingClassName, final String existingClassPackage, final boolean generateAccessors,
final String newVisibility) throws Exception {
doTest(new PerformAction() {
@Override
public void performAction(final VirtualFile rootDir, final VirtualFile rootAfter) throws Exception {
PsiClass aClass = myJavaFacade.findClass("Test", GlobalSearchScope.projectScope(getProject()));
if (aClass == null) {
aClass = myJavaFacade.findClass("p2.Test", GlobalSearchScope.projectScope(getProject()));
}
assertNotNull("Class Test not found", aClass);
final PsiMethod method = aClass.findMethodsByName("foo", false)[0];
IntroduceParameterObjectProcessor processor = new IntroduceParameterObjectProcessor(existingClassName, existingClassPackage, null, method,
generateParams(method), false, true,
false, newVisibility, generateAccessors);
processor.run();
LocalFileSystem.getInstance().refresh(false);
FileDocumentManager.getInstance().saveAllDocuments();
doTest((rootDir, rootAfter) -> {
PsiClass aClass = myJavaFacade.findClass("Test", GlobalSearchScope.projectScope(getProject()));
if (aClass == null) {
aClass = myJavaFacade.findClass("p2.Test", GlobalSearchScope.projectScope(getProject()));
}
assertNotNull("Class Test not found", aClass);
final PsiMethod method = aClass.findMethodsByName("foo", false)[0];
IntroduceParameterObjectProcessor processor = new IntroduceParameterObjectProcessor(existingClassName, existingClassPackage, null, method,
generateParams(method), false, true,
false, newVisibility, generateAccessors);
processor.run();
LocalFileSystem.getInstance().refresh(false);
FileDocumentManager.getInstance().saveAllDocuments();
});
}
@@ -94,20 +94,17 @@ public class IntroduceVariableMultifileTest extends MultiFileTestCase {
}
PerformAction createAction(final String className, final IntroduceVariableBase testMe) {
return new PerformAction() {
@Override
public void performAction(VirtualFile vroot, VirtualFile rootAfter) {
final JavaPsiFacade psiManager = getJavaFacade();
final PsiClass aClass = psiManager.findClass(className, GlobalSearchScope.allScope(myProject));
assertTrue(className + " class not found", aClass != null);
final PsiFile containingFile = aClass.getContainingFile();
final VirtualFile virtualFile = containingFile.getVirtualFile();
assertTrue(virtualFile != null);
final Editor editor = createEditor(virtualFile);
setupCursorAndSelection(editor);
testMe.invoke(myProject, editor, containingFile, null);
FileDocumentManager.getInstance().saveAllDocuments();
}
return (vroot, rootAfter) -> {
final JavaPsiFacade psiManager = getJavaFacade();
final PsiClass aClass = psiManager.findClass(className, GlobalSearchScope.allScope(myProject));
assertTrue(className + " class not found", aClass != null);
final PsiFile containingFile = aClass.getContainingFile();
final VirtualFile virtualFile = containingFile.getVirtualFile();
assertTrue(virtualFile != null);
final Editor editor = createEditor(virtualFile);
setupCursorAndSelection(editor);
testMe.invoke(myProject, editor, containingFile, null);
FileDocumentManager.getInstance().saveAllDocuments();
};
}
}
@@ -51,57 +51,44 @@ public abstract class LightRefactoringParameterizedTestCase extends LightRefacto
public void runSingle() throws Throwable {
final Throwable[] throwables = new Throwable[1];
final Runnable runnable = new Runnable() {
@Override
public void run() {
final Runnable runnable = () -> {
try {
final String filePath = getBeforeFile(myFileSuffix);
configureByFile(filePath);
final File testDir = new File(getTestDataPath(), filePath).getParentFile();
final String afterName = getAfterFile(myFileSuffix);
final boolean conflictShouldBeFound = !new File(testDir, afterName).exists();
try {
final String filePath = getBeforeFile(myFileSuffix);
configureByFile(filePath);
final File testDir = new File(getTestDataPath(), filePath).getParentFile();
final String afterName = getAfterFile(myFileSuffix);
final boolean conflictShouldBeFound = !new File(testDir, afterName).exists();
try {
perform();
if (conflictShouldBeFound) {
fail("Conflict expected.");
}
perform();
if (conflictShouldBeFound) {
fail("Conflict expected.");
}
catch (BaseRefactoringProcessor.ConflictsInTestsException exception) {
if (!conflictShouldBeFound) {
fail("Conflict not expected");
} else {
final File conflicts = new File(testDir, FileUtilRt.getNameWithoutExtension(myFileSuffix) + CONFLICTS_SUFFIX);
if (!conflicts.exists()) {
fail("Conflict file " + conflicts.getPath() + " not found");
}
final VirtualFile conflictsFile = VfsUtil.findFileByIoFile(conflicts, false);
assertNotNull(conflictsFile);
assertEquals(LoadTextUtil.loadText(conflictsFile).toString(), exception.getMessage());
}
}
}
catch (BaseRefactoringProcessor.ConflictsInTestsException exception) {
if (!conflictShouldBeFound) {
checkResultByFile(getAfterFile(myFileSuffix));
fail("Conflict not expected");
} else {
final File conflicts = new File(testDir, FileUtilRt.getNameWithoutExtension(myFileSuffix) + CONFLICTS_SUFFIX);
if (!conflicts.exists()) {
fail("Conflict file " + conflicts.getPath() + " not found");
}
final VirtualFile conflictsFile = VfsUtil.findFileByIoFile(conflicts, false);
assertNotNull(conflictsFile);
assertEquals(LoadTextUtil.loadText(conflictsFile).toString(), exception.getMessage());
}
}
catch (Throwable e) {
throwables[0] = e;
if (!conflictShouldBeFound) {
checkResultByFile(getAfterFile(myFileSuffix));
}
}
catch (Throwable e) {
throwables[0] = e;
}
};
invokeTestRunnable(new Runnable() {
@Override
public void run() {
CommandProcessor.getInstance().executeCommand(getProject(), new Runnable() {
@Override
public void run() {
runnable.run();
}
}, "", null);
}
});
invokeTestRunnable(() -> CommandProcessor.getInstance().executeCommand(getProject(), runnable::run, "", null));
if (throwables[0] != null) {
throw throwables[0];
@@ -83,7 +83,7 @@ public class MakeClassStaticTest extends LightRefactoringTestCase {
PsiElement element = TargetElementUtil.findTargetElement(myEditor, TargetElementUtil.ELEMENT_NAME_ACCEPTED);
assertTrue(element instanceof PsiClass);
PsiClass aClass = (PsiClass)element;
final ArrayList<VariableData> parametersForFields = new ArrayList<VariableData>();
final ArrayList<VariableData> parametersForFields = new ArrayList<>();
final boolean addClassParameter = MakeStaticUtil.buildVariableData(aClass, parametersForFields);
new MakeClassStaticProcessor(
@@ -248,7 +248,7 @@ public class MakeMethodStaticTest extends LightRefactoringTestCase {
PsiElement element = TargetElementUtil.findTargetElement(myEditor, TargetElementUtil.ELEMENT_NAME_ACCEPTED);
assertTrue(element instanceof PsiMethod);
PsiMethod method = (PsiMethod) element;
final ArrayList<VariableData> parametersForFields = new ArrayList<VariableData>();
final ArrayList<VariableData> parametersForFields = new ArrayList<>();
final boolean addClassParameter = MakeStaticUtil.buildVariableData(method, parametersForFields);
new MakeMethodStaticProcessor(
@@ -222,11 +222,8 @@ public class MoveMembersTest extends MultiFileTestCase {
final String defaultVisibility,
final int... memberIndices)
throws Exception {
doTest(new PerformAction() {
@Override
public void performAction(VirtualFile rootDir, VirtualFile rootAfter) throws Exception {
MoveMembersTest.this.performAction(sourceClassName, targetClassName, memberIndices, defaultVisibility);
}
doTest((rootDir, rootAfter) -> {
MoveMembersTest.this.performAction(sourceClassName, targetClassName, memberIndices, defaultVisibility);
}, lowercaseFirstLetter);
}
@@ -237,14 +234,14 @@ public class MoveMembersTest extends MultiFileTestCase {
assertNotNull("Class " + targetClassName + " not found", targetClass);
PsiElement[] children = sourceClass.getChildren();
ArrayList<PsiMember> members = new ArrayList<PsiMember>();
ArrayList<PsiMember> members = new ArrayList<>();
for (PsiElement child : children) {
if (child instanceof PsiMember) {
members.add(((PsiMember) child));
}
}
LinkedHashSet<PsiMember> memberSet = new LinkedHashSet<PsiMember>();
LinkedHashSet<PsiMember> memberSet = new LinkedHashSet<>();
for (int index : memberIndices) {
PsiMember member = members.get(index);
assertTrue(member.hasModifierProperty(PsiModifier.STATIC));
@@ -52,16 +52,13 @@ public class MovePackageAsDirectoryTest extends MultiFileTestCase {
}
public void testRenamePackage() throws Exception {
final PerformAction action = new PerformAction() {
@Override
public void performAction(VirtualFile rootDir, VirtualFile rootAfter) throws Exception {
final JavaPsiFacade psiFacade = JavaPsiFacade.getInstance(myProject);
final PsiPackage sourcePackage = psiFacade.findPackage("pack1");
assertNotNull(sourcePackage);
RenamePsiPackageProcessor.createRenameMoveProcessor("pack1.pack2", sourcePackage, false, false).run();
FileDocumentManager.getInstance().saveAllDocuments();
}
final PerformAction action = (rootDir, rootAfter) -> {
final JavaPsiFacade psiFacade = JavaPsiFacade.getInstance(myProject);
final PsiPackage sourcePackage = psiFacade.findPackage("pack1");
assertNotNull(sourcePackage);
RenamePsiPackageProcessor.createRenameMoveProcessor("pack1.pack2", sourcePackage, false, false).run();
FileDocumentManager.getInstance().saveAllDocuments();
};
doTest(action);
}
@@ -105,21 +102,15 @@ public class MovePackageAsDirectoryTest extends MultiFileTestCase {
protected void preprocessSrcDir(PsiDirectory srcDirectory) {
final PsiFile empty = srcDirectory.findFile(EMPTY_TXT);
assert empty != null;
WriteCommandAction.runWriteCommandAction(null, new Runnable() {
public void run() {
empty.delete();
}
});
WriteCommandAction.runWriteCommandAction(null, empty::delete);
}
@Override
protected void postProcessTargetDir(PsiDirectory targetDirectory) {
final PsiDirectory subdirectory = targetDirectory.findSubdirectory(packageName);
assert subdirectory != null;
ApplicationManager.getApplication().runWriteAction(new Runnable() {
public void run() {
subdirectory.createFile(EMPTY_TXT);
}
ApplicationManager.getApplication().runWriteAction(() -> {
subdirectory.createFile(EMPTY_TXT);
});
}
});
@@ -133,11 +124,7 @@ public class MovePackageAsDirectoryTest extends MultiFileTestCase {
protected void preprocessSrcDir(PsiDirectory srcDirectory) {
final PsiClass empty = JavaPsiFacade.getInstance(getProject()).findClass(FOO, GlobalSearchScope.projectScope(getProject()));
assert empty != null;
ApplicationManager.getApplication().runWriteAction(new Runnable() {
public void run() {
empty.delete();
}
});
ApplicationManager.getApplication().runWriteAction(empty::delete);
}
@Override
@@ -146,10 +133,8 @@ public class MovePackageAsDirectoryTest extends MultiFileTestCase {
assert subdirectory != null;
final PsiDirectory emptyDir = subdirectory.findSubdirectory("subPack");
assert emptyDir != null;
ApplicationManager.getApplication().runWriteAction(new Runnable() {
public void run() {
emptyDir.createFile(EMPTY_TXT);
}
ApplicationManager.getApplication().runWriteAction(() -> {
emptyDir.createFile(EMPTY_TXT);
});
}
});
@@ -182,12 +167,8 @@ public class MovePackageAsDirectoryTest extends MultiFileTestCase {
@Override
public void performAction(VirtualFile rootDir, VirtualFile rootAfter) throws Exception {
final JavaPsiFacade psiFacade = JavaPsiFacade.getInstance(myProject);
final Comparator<PsiDirectory> directoryComparator = new Comparator<PsiDirectory>() {
@Override
public int compare(PsiDirectory o1, PsiDirectory o2) {
return o1.getVirtualFile().getPresentableUrl().compareTo(o2.getVirtualFile().getPresentableUrl());
}
};
final Comparator<PsiDirectory> directoryComparator =
(o1, o2) -> o1.getVirtualFile().getPresentableUrl().compareTo(o2.getVirtualFile().getPresentableUrl());
final PsiPackage sourcePackage = psiFacade.findPackage(myPackageName);
assertNotNull(sourcePackage);
@@ -51,23 +51,20 @@ public class MovePackageMultirootTest extends MultiFileTestCase {
}
private PerformAction createAction(final String[] packageNames, final String targetPackageName) {
return new PerformAction() {
@Override
public void performAction(VirtualFile rootDir, VirtualFile rootAfter) throws Exception {
final PsiManager manager = PsiManager.getInstance(myProject);
PsiPackage[] sourcePackages = new PsiPackage[packageNames.length];
for (int i = 0; i < packageNames.length; i++) {
String packageName = packageNames[i];
sourcePackages[i] = JavaPsiFacade.getInstance(manager.getProject()).findPackage(packageName);
assertNotNull(sourcePackages[i]);
}
PsiPackage targetPackage = JavaPsiFacade.getInstance(manager.getProject()).findPackage(targetPackageName);
assertNotNull(targetPackage);
new MoveClassesOrPackagesProcessor(myProject, sourcePackages,
new MultipleRootsMoveDestination(new PackageWrapper(targetPackage)),
true, true, null).run();
FileDocumentManager.getInstance().saveAllDocuments();
return (rootDir, rootAfter) -> {
final PsiManager manager = PsiManager.getInstance(myProject);
PsiPackage[] sourcePackages = new PsiPackage[packageNames.length];
for (int i = 0; i < packageNames.length; i++) {
String packageName = packageNames[i];
sourcePackages[i] = JavaPsiFacade.getInstance(manager.getProject()).findPackage(packageName);
assertNotNull(sourcePackages[i]);
}
PsiPackage targetPackage = JavaPsiFacade.getInstance(manager.getProject()).findPackage(targetPackageName);
assertNotNull(targetPackage);
new MoveClassesOrPackagesProcessor(myProject, sourcePackages,
new MultipleRootsMoveDestination(new PackageWrapper(targetPackage)),
true, true, null).run();
FileDocumentManager.getInstance().saveAllDocuments();
};
}
@@ -56,12 +56,7 @@ public class MovePackageTest extends MultiFileTestCase {
}
private void doTest(final String[] packageNames, final String newPackageName) throws Exception {
doTest(new PerformAction() {
@Override
public void performAction(VirtualFile rootDir, VirtualFile rootAfter) throws Exception {
MovePackageTest.this.performAction(packageNames, newPackageName);
}
});
doTest((rootDir, rootAfter) -> MovePackageTest.this.performAction(packageNames, newPackageName));
}
private void performAction(String[] packageNames, String newPackageName) throws Exception {
@@ -21,13 +21,11 @@
package com.intellij.refactoring;
import com.intellij.JavaTestUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.*;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.refactoring.memberPullUp.PullUpConflictsUtil;
import com.intellij.refactoring.memberPullUp.PullUpProcessor;
import com.intellij.refactoring.util.DocCommentPolicy;
import com.intellij.refactoring.util.classMembers.InterfaceContainmentVerifier;
import com.intellij.refactoring.util.classMembers.MemberInfo;
import com.intellij.util.containers.MultiMap;
import org.jetbrains.annotations.NotNull;
@@ -49,42 +47,35 @@ public class PullUpMultifileTest extends MultiFileTestCase {
}
private void doTest(final String... conflicts) throws Exception {
final MultiMap<PsiElement, String> conflictsMap = new MultiMap<PsiElement, String>();
doTest(new PerformAction() {
@Override
public void performAction(final VirtualFile rootDir, final VirtualFile rootAfter) throws Exception {
final PsiClass srcClass = myJavaFacade.findClass("a.A", GlobalSearchScope.allScope(myProject));
assertTrue("Source class not found", srcClass != null);
final MultiMap<PsiElement, String> conflictsMap = new MultiMap<>();
doTest((rootDir, rootAfter) -> {
final PsiClass srcClass = myJavaFacade.findClass("a.A", GlobalSearchScope.allScope(myProject));
assertTrue("Source class not found", srcClass != null);
final PsiClass targetClass = myJavaFacade.findClass("b.B", GlobalSearchScope.allScope(myProject));
assertTrue("Target class not found", targetClass != null);
final PsiClass targetClass = myJavaFacade.findClass("b.B", GlobalSearchScope.allScope(myProject));
assertTrue("Target class not found", targetClass != null);
final PsiMethod[] methods = srcClass.getMethods();
assertTrue("No methods found", methods.length > 0);
final MemberInfo[] membersToMove = new MemberInfo[1];
final MemberInfo memberInfo = new MemberInfo(methods[0]);
memberInfo.setChecked(true);
membersToMove[0] = memberInfo;
final PsiMethod[] methods = srcClass.getMethods();
assertTrue("No methods found", methods.length > 0);
final MemberInfo[] membersToMove = new MemberInfo[1];
final MemberInfo memberInfo = new MemberInfo(methods[0]);
memberInfo.setChecked(true);
membersToMove[0] = memberInfo;
final PsiDirectory targetDirectory = targetClass.getContainingFile().getContainingDirectory();
final PsiPackage targetPackage = targetDirectory != null ? JavaDirectoryService.getInstance().getPackage(targetDirectory) : null;
conflictsMap.putAllValues(
PullUpConflictsUtil.checkConflicts(membersToMove, srcClass, targetClass, targetPackage, targetDirectory, new InterfaceContainmentVerifier() {
@Override
public boolean checkedInterfacesContain(PsiMethod psiMethod) {
return PullUpProcessor.checkedInterfacesContain(Arrays.asList(membersToMove), psiMethod);
}
}));
final PsiDirectory targetDirectory = targetClass.getContainingFile().getContainingDirectory();
final PsiPackage targetPackage = targetDirectory != null ? JavaDirectoryService.getInstance().getPackage(targetDirectory) : null;
conflictsMap.putAllValues(
PullUpConflictsUtil.checkConflicts(membersToMove, srcClass, targetClass, targetPackage, targetDirectory,
psiMethod -> PullUpProcessor.checkedInterfacesContain(Arrays.asList(membersToMove), psiMethod)));
new PullUpProcessor(srcClass, targetClass, membersToMove, new DocCommentPolicy(DocCommentPolicy.ASIS)).run();
}
new PullUpProcessor(srcClass, targetClass, membersToMove, new DocCommentPolicy(DocCommentPolicy.ASIS)).run();
});
if (conflicts.length != 0 && conflictsMap.isEmpty()) {
fail("Conflict was not detected");
}
final HashSet<String> values = new HashSet<String>(conflictsMap.values());
final HashSet<String> expected = new HashSet<String>(Arrays.asList(conflicts));
final HashSet<String> values = new HashSet<>(conflictsMap.values());
final HashSet<String> expected = new HashSet<>(Arrays.asList(conflicts));
assertEquals(expected.size(), values.size());
for (String value : values) {
@@ -189,7 +189,7 @@ public class PullUpTest extends LightRefactoringTestCase {
private void doTest(final boolean checkMembersMovedCount,
String conflictMessage,
RefactoringTestUtil.MemberDescriptor... membersToFind) {
final MultiMap<PsiElement, String> conflictsMap = new MultiMap<PsiElement, String>();
final MultiMap<PsiElement, String> conflictsMap = new MultiMap<>();
configureByFile(BASE_PATH + getTestName(false) + ".java");
PsiElement elementAt = getFile().findElementAt(getEditor().getCaretModel().getOffset());
final PsiClass sourceClass = PsiTreeUtil.getParentOfType(elementAt, PsiClass.class);
@@ -206,24 +206,17 @@ public class PullUpTest extends LightRefactoringTestCase {
final MemberInfo[] infos = RefactoringTestUtil.findMembers(sourceClass, membersToFind);
final int[] countMoved = {0};
final MoveMemberListener listener = new MoveMemberListener() {
@Override
public void memberMoved(PsiClass aClass, PsiMember member) {
assertEquals(sourceClass, aClass);
countMoved[0]++;
}
final MoveMemberListener listener = (aClass, member) -> {
assertEquals(sourceClass, aClass);
countMoved[0]++;
};
JavaRefactoringListenerManager.getInstance(getProject()).addMoveMembersListener(listener);
final PsiDirectory targetDirectory = targetClass.getContainingFile().getContainingDirectory();
final PsiPackage targetPackage = targetDirectory != null ? JavaDirectoryService.getInstance().getPackage(targetDirectory) : null;
conflictsMap.putAllValues(
PullUpConflictsUtil
.checkConflicts(infos, sourceClass, targetClass, targetPackage, targetDirectory, new InterfaceContainmentVerifier() {
@Override
public boolean checkedInterfacesContain(PsiMethod psiMethod) {
return PullUpProcessor.checkedInterfacesContain(Arrays.asList(infos), psiMethod);
}
})
.checkConflicts(infos, sourceClass, targetClass, targetPackage, targetDirectory,
psiMethod -> PullUpProcessor.checkedInterfacesContain(Arrays.asList(infos), psiMethod))
);
final PullUpProcessor helper = new PullUpProcessor(sourceClass, targetClass, infos, new DocCommentPolicy(DocCommentPolicy.ASIS));
helper.run();
@@ -54,28 +54,25 @@ public class PushDownMultifileTest extends MultiFileTestCase {
private void doTest(final boolean fail, final String sourceClassName, final String targetClassName) throws Exception {
try {
doTest(new PerformAction() {
@Override
public void performAction(final VirtualFile rootDir, final VirtualFile rootAfter) throws Exception {
final PsiClass srcClass = myJavaFacade.findClass(sourceClassName, GlobalSearchScope.allScope(myProject));
assertTrue("Source class not found", srcClass != null);
doTest((rootDir, rootAfter) -> {
final PsiClass srcClass = myJavaFacade.findClass(sourceClassName, GlobalSearchScope.allScope(myProject));
assertTrue("Source class not found", srcClass != null);
final PsiClass targetClass = myJavaFacade.findClass(targetClassName, GlobalSearchScope.allScope(myProject));
assertTrue("Target class not found", targetClass != null);
final PsiClass targetClass = myJavaFacade.findClass(targetClassName, GlobalSearchScope.allScope(myProject));
assertTrue("Target class not found", targetClass != null);
final PsiMethod[] methods = srcClass.getMethods();
assertTrue("No methods found", methods.length > 0);
final MemberInfo[] membersToMove = new MemberInfo[1];
final MemberInfo memberInfo = new MemberInfo(methods[0]);
memberInfo.setChecked(true);
membersToMove[0] = memberInfo;
final PsiMethod[] methods = srcClass.getMethods();
assertTrue("No methods found", methods.length > 0);
final MemberInfo[] membersToMove = new MemberInfo[1];
final MemberInfo memberInfo = new MemberInfo(methods[0]);
memberInfo.setChecked(true);
membersToMove[0] = memberInfo;
new PushDownProcessor(getProject(), membersToMove, srcClass, new DocCommentPolicy(DocCommentPolicy.ASIS)).run();
new PushDownProcessor(getProject(), membersToMove, srcClass, new DocCommentPolicy(DocCommentPolicy.ASIS)).run();
//LocalFileSystem.getInstance().refresh(false);
//FileDocumentManager.getInstance().saveAllDocuments();
}
//LocalFileSystem.getInstance().refresh(false);
//FileDocumentManager.getInstance().saveAllDocuments();
});
}
catch (BaseRefactoringProcessor.ConflictsInTestsException e) {
@@ -110,28 +107,25 @@ public class PushDownMultifileTest extends MultiFileTestCase {
public void testUsagesInXml() throws Exception {
try {
doTest(new PerformAction() {
@Override
public void performAction(final VirtualFile rootDir, final VirtualFile rootAfter) throws Exception {
final PsiClass srcClass = myJavaFacade.findClass("a.A", GlobalSearchScope.allScope(myProject));
assertTrue("Source class not found", srcClass != null);
doTest((rootDir, rootAfter) -> {
final PsiClass srcClass = myJavaFacade.findClass("a.A", GlobalSearchScope.allScope(myProject));
assertTrue("Source class not found", srcClass != null);
final PsiClass targetClass = myJavaFacade.findClass("b.B", GlobalSearchScope.allScope(myProject));
assertTrue("Target class not found", targetClass != null);
final PsiClass targetClass = myJavaFacade.findClass("b.B", GlobalSearchScope.allScope(myProject));
assertTrue("Target class not found", targetClass != null);
final PsiField[] fields = srcClass.getFields();
assertTrue("No methods found", fields.length > 0);
final MemberInfo[] membersToMove = new MemberInfo[1];
final MemberInfo memberInfo = new MemberInfo(fields[0]);
memberInfo.setChecked(true);
membersToMove[0] = memberInfo;
final PsiField[] fields = srcClass.getFields();
assertTrue("No methods found", fields.length > 0);
final MemberInfo[] membersToMove = new MemberInfo[1];
final MemberInfo memberInfo = new MemberInfo(fields[0]);
memberInfo.setChecked(true);
membersToMove[0] = memberInfo;
new PushDownProcessor(getProject(), membersToMove, srcClass, new DocCommentPolicy(DocCommentPolicy.ASIS)).run();
new PushDownProcessor(getProject(), membersToMove, srcClass, new DocCommentPolicy(DocCommentPolicy.ASIS)).run();
//LocalFileSystem.getInstance().refresh(false);
//FileDocumentManager.getInstance().saveAllDocuments();
}
//LocalFileSystem.getInstance().refresh(false);
//FileDocumentManager.getInstance().saveAllDocuments();
});
}
catch (BaseRefactoringProcessor.ConflictsInTestsException e) {
@@ -78,7 +78,7 @@ public class PushDownTest extends LightRefactoringTestCase {
assert currentClass != null;
final List<MemberInfo> membersToMove = new ArrayList<MemberInfo>();
final List<MemberInfo> membersToMove = new ArrayList<>();
final PsiField fieldByName = currentClass.findFieldByName("fieldToMove", false);
if (fieldByName != null) {
@@ -109,12 +109,7 @@ public class PushDownTest extends LightRefactoringTestCase {
configureByFile(BASE_PATH + getTestName(false) + ".java");
PsiClass currentClass = JavaPsiFacade.getInstance(getProject()).findClass("Test", GlobalSearchScope.projectScope(getProject()));
MemberInfoStorage memberInfoStorage = new MemberInfoStorage(currentClass, new MemberInfo.Filter<PsiMember>() {
@Override
public boolean includeMember(PsiMember element) {
return true;
}
});
MemberInfoStorage memberInfoStorage = new MemberInfoStorage(currentClass, element -> true);
List<MemberInfo> members = memberInfoStorage.getClassMemberInfos(currentClass);
for (MemberInfo member : members) {
member.setChecked(true);
@@ -50,34 +50,31 @@ public class RemoveMiddleManTest extends MultiFileTestCase{
}
private void doTest(final String conflict) throws Exception {
doTest(new PerformAction() {
@Override
public void performAction(final VirtualFile rootDir, final VirtualFile rootAfter) throws Exception {
PsiClass aClass = myJavaFacade.findClass("Test", GlobalSearchScope.allScope(getProject()));
doTest((rootDir, rootAfter) -> {
PsiClass aClass = myJavaFacade.findClass("Test", GlobalSearchScope.allScope(getProject()));
if (aClass == null) aClass = myJavaFacade.findClass("p.Test", GlobalSearchScope.allScope(getProject()));
assertNotNull("Class Test not found", aClass);
if (aClass == null) aClass = myJavaFacade.findClass("p.Test", GlobalSearchScope.allScope(getProject()));
assertNotNull("Class Test not found", aClass);
final PsiField field = aClass.findFieldByName("myField", false);
final Set<PsiMethod> methods = DelegationUtils.getDelegatingMethodsForField(field);
List<MemberInfo> infos = new ArrayList<MemberInfo>();
for (PsiMethod method : methods) {
final MemberInfo info = new MemberInfo(method);
info.setChecked(true);
info.setToAbstract(true);
infos.add(info);
}
try {
RemoveMiddlemanProcessor processor = new RemoveMiddlemanProcessor(field, infos);
processor.run();
LocalFileSystem.getInstance().refresh(false);
FileDocumentManager.getInstance().saveAllDocuments();
if (conflict != null) fail("Conflict expected");
}
catch (BaseRefactoringProcessor.ConflictsInTestsException e) {
if (conflict == null) throw e;
assertEquals(conflict, e.getMessage());
}
final PsiField field = aClass.findFieldByName("myField", false);
final Set<PsiMethod> methods = DelegationUtils.getDelegatingMethodsForField(field);
List<MemberInfo> infos = new ArrayList<>();
for (PsiMethod method : methods) {
final MemberInfo info = new MemberInfo(method);
info.setChecked(true);
info.setToAbstract(true);
infos.add(info);
}
try {
RemoveMiddlemanProcessor processor = new RemoveMiddlemanProcessor(field, infos);
processor.run();
LocalFileSystem.getInstance().refresh(false);
FileDocumentManager.getInstance().saveAllDocuments();
if (conflict != null) fail("Conflict expected");
}
catch (BaseRefactoringProcessor.ConflictsInTestsException e) {
if (conflict == null) throw e;
assertEquals(conflict, e.getMessage());
}
});
}
@@ -75,20 +75,17 @@ public class RenameClassTest extends MultiFileTestCase {
}
private void doRenameClass(final String className, final String newName) throws Exception {
doTest(new PerformAction() {
@Override
public void performAction(VirtualFile rootDir, VirtualFile rootAfter) throws Exception {
PsiClass aClass = myJavaFacade.findClass(className, GlobalSearchScope.allScope(getProject()));
assertNotNull("Class XX not found", aClass);
doTest((rootDir, rootAfter) -> {
PsiClass aClass = myJavaFacade.findClass(className, GlobalSearchScope.allScope(getProject()));
assertNotNull("Class XX not found", aClass);
final RenameProcessor processor = new RenameProcessor(myProject, aClass, newName, true, true);
for (AutomaticRenamerFactory factory : Extensions.getExtensions(AutomaticRenamerFactory.EP_NAME)) {
processor.addRenamerFactory(factory);
}
processor.run();
PsiDocumentManager.getInstance(myProject).commitAllDocuments();
FileDocumentManager.getInstance().saveAllDocuments();
final RenameProcessor processor = new RenameProcessor(myProject, aClass, newName, true, true);
for (AutomaticRenamerFactory factory : Extensions.getExtensions(AutomaticRenamerFactory.EP_NAME)) {
processor.addRenamerFactory(factory);
}
processor.run();
PsiDocumentManager.getInstance(myProject).commitAllDocuments();
FileDocumentManager.getInstance().saveAllDocuments();
});
}
@@ -101,12 +98,7 @@ public class RenameClassTest extends MultiFileTestCase {
}
private void doTest(@NonNls final String qClassName, @NonNls final String newName) throws Exception {
doTest(new PerformAction() {
@Override
public void performAction(VirtualFile rootDir, VirtualFile rootAfter) throws Exception {
RenameClassTest.this.performAction(qClassName, newName);
}
});
doTest((rootDir, rootAfter) -> RenameClassTest.this.performAction(qClassName, newName));
}
private void performAction(String qClassName, String newName) throws Exception {
@@ -283,7 +283,7 @@ public class RenameCollisionsTest extends LightRefactoringTestCase {
PsiElement element = TargetElementUtil
.findTargetElement(myEditor, TargetElementUtil.ELEMENT_NAME_ACCEPTED | TargetElementUtil.REFERENCED_ELEMENT_ACCEPTED);
assertNotNull(element);
final UsageInfo[] usageInfos = RenameUtil.findUsages(element, "newName", true, true, new HashMap<PsiElement, String>());
final UsageInfo[] usageInfos = RenameUtil.findUsages(element, "newName", true, true, new HashMap<>());
assertSize(1, usageInfos);
for (UsageInfo usageInfo : usageInfos) {
assertTrue(usageInfo instanceof MoveRenameUsageInfo);
@@ -62,7 +62,7 @@ public class RenameLocalTest extends LightRefactoringTestCase {
PsiElement element = TargetElementUtil
.findTargetElement(myEditor, TargetElementUtil.ELEMENT_NAME_ACCEPTED | TargetElementUtil.REFERENCED_ELEMENT_ACCEPTED);
assertNotNull(element);
final HashSet<String> result = new HashSet<String>();
final HashSet<String> result = new HashSet<>();
new JavaNameSuggestionProvider().getSuggestedNames(element, getFile(), result);
assertTrue(result.toString(), result.contains("window"));
}
@@ -90,7 +90,7 @@ public class RenameMembersInplaceTest extends LightCodeInsightTestCase {
final PsiElement element = TargetElementUtil.findTargetElement(myEditor, TargetElementUtil.getInstance().getAllAccepted());
assertNotNull(element);
final Set<String> result = new LinkedHashSet<String>();
final Set<String> result = new LinkedHashSet<>();
new JavaNameSuggestionProvider().getSuggestedNames(element, getFile(), result);
CodeInsightTestUtil.doInlineRename(new MemberInplaceRenameHandler(), result.iterator().next(), getEditor(), element);
@@ -99,41 +99,35 @@ public class RenameMethodMultiTest extends MultiFileTestCase {
}
private void doTest(final String className, final String methodSignature, final String newName) throws Exception {
doTest(new PerformAction() {
@Override
public void performAction(VirtualFile rootDir, VirtualFile rootAfter) throws Exception {
final JavaPsiFacade manager = getJavaFacade();
final PsiClass aClass = manager.findClass(className, GlobalSearchScope.moduleScope(myModule));
assertNotNull(aClass);
final PsiMethod methodBySignature = aClass.findMethodBySignature(manager.getElementFactory().createMethodFromText(
methodSignature + "{}", null), false);
assertNotNull(methodBySignature);
final RenameProcessor renameProcessor = new RenameProcessor(myProject, methodBySignature, newName, false, false);
renameProcessor.run();
FileDocumentManager.getInstance().saveAllDocuments();
}
doTest((rootDir, rootAfter) -> {
final JavaPsiFacade manager = getJavaFacade();
final PsiClass aClass = manager.findClass(className, GlobalSearchScope.moduleScope(myModule));
assertNotNull(aClass);
final PsiMethod methodBySignature = aClass.findMethodBySignature(manager.getElementFactory().createMethodFromText(
methodSignature + "{}", null), false);
assertNotNull(methodBySignature);
final RenameProcessor renameProcessor = new RenameProcessor(myProject, methodBySignature, newName, false, false);
renameProcessor.run();
FileDocumentManager.getInstance().saveAllDocuments();
});
}
private void doAutomaticRenameMethod(final String className, final String methodSignature, final String newName) throws Exception {
doTest(new PerformAction() {
@Override
public void performAction(VirtualFile rootDir, VirtualFile rootAfter) throws Exception {
final JavaPsiFacade manager = getJavaFacade();
final PsiClass aClass = manager.findClass(className, GlobalSearchScope.moduleScope(myModule));
assertNotNull(aClass);
final PsiMethod methodBySignature = aClass.findMethodBySignature(manager.getElementFactory().createMethodFromText(
methodSignature + "{}", null), false);
assertNotNull(methodBySignature);
doTest((rootDir, rootAfter) -> {
final JavaPsiFacade manager = getJavaFacade();
final PsiClass aClass = manager.findClass(className, GlobalSearchScope.moduleScope(myModule));
assertNotNull(aClass);
final PsiMethod methodBySignature = aClass.findMethodBySignature(manager.getElementFactory().createMethodFromText(
methodSignature + "{}", null), false);
assertNotNull(methodBySignature);
final RenameProcessor processor = new RenameProcessor(myProject, methodBySignature, newName, false, false);
for (AutomaticRenamerFactory factory : Extensions.getExtensions(AutomaticRenamerFactory.EP_NAME)) {
processor.addRenamerFactory(factory);
}
processor.run();
PsiDocumentManager.getInstance(myProject).commitAllDocuments();
FileDocumentManager.getInstance().saveAllDocuments();
final RenameProcessor processor = new RenameProcessor(myProject, methodBySignature, newName, false, false);
for (AutomaticRenamerFactory factory : Extensions.getExtensions(AutomaticRenamerFactory.EP_NAME)) {
processor.addRenamerFactory(factory);
}
processor.run();
PsiDocumentManager.getInstance(myProject).commitAllDocuments();
FileDocumentManager.getInstance().saveAllDocuments();
});
}
@@ -62,13 +62,13 @@ public class ReplaceConstructorWithBuilderTest extends MultiFileTestCase {
}
public void testConstructorChain() throws Exception {
final HashMap<String, String> defaults = new HashMap<String, String>();
final HashMap<String, String> defaults = new HashMap<>();
defaults.put("i", "2");
doTest(true, defaults);
}
public void testConstructorChainWithoutDefaults() throws Exception {
final HashMap<String, String> defaults = new HashMap<String, String>();
final HashMap<String, String> defaults = new HashMap<>();
defaults.put("i", "2");
defaults.put("j", null);
doTest(true, defaults);
@@ -102,39 +102,36 @@ public class ReplaceConstructorWithBuilderTest extends MultiFileTestCase {
final Map<String, String> expectedDefaults,
final String conflicts,
final String packageName) throws Exception {
doTest(new PerformAction() {
@Override
public void performAction(final VirtualFile rootDir, final VirtualFile rootAfter) throws Exception {
final PsiClass aClass = myJavaFacade.findClass("Test", GlobalSearchScope.projectScope(getProject()));
assertNotNull("Class Test not found", aClass);
doTest((rootDir, rootAfter) -> {
final PsiClass aClass = myJavaFacade.findClass("Test", GlobalSearchScope.projectScope(getProject()));
assertNotNull("Class Test not found", aClass);
final LinkedHashMap<String, ParameterData> map = new LinkedHashMap<String, ParameterData>();
final PsiMethod[] constructors = aClass.getConstructors();
for (PsiMethod constructor : constructors) {
ParameterData.createFromConstructor(constructor, "set", map);
}
if (expectedDefaults != null) {
for (Map.Entry<String, String> entry : expectedDefaults.entrySet()) {
final ParameterData parameterData = map.get(entry.getKey());
assertNotNull(parameterData);
assertEquals(entry.getValue(), parameterData.getDefaultValue());
}
}
try {
new ReplaceConstructorWithBuilderProcessor(getProject(), constructors, map, "Builder", packageName, null, createNewBuilderClass).run();
if (conflicts != null) {
fail("Conflicts were not detected:" + conflicts);
}
}
catch (BaseRefactoringProcessor.ConflictsInTestsException e) {
if (conflicts == null) {
fail("Conflict detected:" + e.getMessage());
}
}
LocalFileSystem.getInstance().refresh(false);
FileDocumentManager.getInstance().saveAllDocuments();
final LinkedHashMap<String, ParameterData> map = new LinkedHashMap<>();
final PsiMethod[] constructors = aClass.getConstructors();
for (PsiMethod constructor : constructors) {
ParameterData.createFromConstructor(constructor, "set", map);
}
if (expectedDefaults != null) {
for (Map.Entry<String, String> entry : expectedDefaults.entrySet()) {
final ParameterData parameterData = map.get(entry.getKey());
assertNotNull(parameterData);
assertEquals(entry.getValue(), parameterData.getDefaultValue());
}
}
try {
new ReplaceConstructorWithBuilderProcessor(getProject(), constructors, map, "Builder", packageName, null, createNewBuilderClass).run();
if (conflicts != null) {
fail("Conflicts were not detected:" + conflicts);
}
}
catch (BaseRefactoringProcessor.ConflictsInTestsException e) {
if (conflicts == null) {
fail("Conflict detected:" + e.getMessage());
}
}
LocalFileSystem.getInstance().refresh(false);
FileDocumentManager.getInstance().saveAllDocuments();
});
}
@@ -278,11 +278,8 @@ public class SafeDeleteTest extends MultiFileTestCase {
}
private void doTest(@NonNls final String qClassName) throws Exception {
doTest(new PerformAction() {
@Override
public void performAction(VirtualFile rootDir, VirtualFile rootAfter) throws Exception {
SafeDeleteTest.this.performAction(qClassName);
}
doTest((rootDir, rootAfter) -> {
SafeDeleteTest.this.performAction(qClassName);
});
}
@@ -67,11 +67,8 @@ public class TurnRefsToSuperTest extends MultiFileTestCase {
//public void testForEach2() throws Exception { doTest("Test.MyIterableImpl", "Test.MyIterable", false); }
private void doTest(@NonNls final String className, @NonNls final String superClassName, final boolean replaceInstanceOf) throws Exception {
doTest(new PerformAction() {
@Override
public void performAction(VirtualFile rootDir, VirtualFile rootAfter) throws Exception {
TurnRefsToSuperTest.this.performAction(className, superClassName, replaceInstanceOf);
}
doTest((rootDir, rootAfter) -> {
TurnRefsToSuperTest.this.performAction(className, superClassName, replaceInstanceOf);
}, true);
}
@@ -672,12 +672,7 @@ public class TypeCookTest extends MultiFileTestCase {
}
public void start(final boolean cookObjects) throws Exception {
doTest(new PerformAction() {
@Override
public void performAction(VirtualFile rootDir, VirtualFile rootAfter) throws Exception {
TypeCookTest.this.performAction("Test", rootDir.getName(), cookObjects);
}
});
doTest((rootDir, rootAfter) -> TypeCookTest.this.performAction("Test", rootDir.getName(), cookObjects));
}
private void performAction(String className, String rootDir, final boolean cookObjects) throws Exception {
@@ -70,18 +70,15 @@ public class WrapReturnValueTest extends MultiFileTestCase {
private void doTest(final boolean existing, String exceptionMessage, final boolean createInnerClass) {
try {
doTest(new PerformAction() {
@Override
public void performAction(final VirtualFile rootDir, final VirtualFile rootAfter) {
PsiClass aClass = myJavaFacade.findClass("Test", GlobalSearchScope.projectScope(getProject()));
assertNotNull("Class Test not found", aClass);
PsiMethod method = aClass.findMethodsByName("foo", false)[0];
String wrapperClassName = "Wrapper";
PsiClass wrapperClass = myJavaFacade.findClass(wrapperClassName, GlobalSearchScope.projectScope(getProject()));
assertTrue(!existing || wrapperClass != null);
PsiField delegateField = existing ? wrapperClass.findFieldByName("myField", false) : null;
new WrapReturnValueProcessor(wrapperClassName, "", null, method, existing, createInnerClass, delegateField).run();
}
doTest((rootDir, rootAfter) -> {
PsiClass aClass = myJavaFacade.findClass("Test", GlobalSearchScope.projectScope(getProject()));
assertNotNull("Class Test not found", aClass);
PsiMethod method = aClass.findMethodsByName("foo", false)[0];
String wrapperClassName = "Wrapper";
PsiClass wrapperClass = myJavaFacade.findClass(wrapperClassName, GlobalSearchScope.projectScope(getProject()));
assertTrue(!existing || wrapperClass != null);
PsiField delegateField = existing ? wrapperClass.findFieldByName("myField", false) : null;
new WrapReturnValueProcessor(wrapperClassName, "", null, method, existing, createInnerClass, delegateField).run();
});
}
catch (BaseRefactoringProcessor.ConflictsInTestsException e) {
@@ -22,120 +22,65 @@ public class ChangeClassSignatureTest extends LightRefactoringTestCase {
}
public void testNoParams() throws Exception {
doTest(new GenParams() {
@Override
public TypeParameterInfo[] gen(PsiClass aClass) throws IncorrectOperationException {
return new TypeParameterInfo[]{
new TypeParameterInfo(aClass, "T", "java.lang.String")
};
}
doTest(aClass -> new TypeParameterInfo[]{
new TypeParameterInfo(aClass, "T", "java.lang.String")
});
}
public void testInstanceOf() throws Exception {
doTest(new GenParams() {
@Override
public TypeParameterInfo[] gen(PsiClass aClass) throws IncorrectOperationException {
return new TypeParameterInfo[]{
new TypeParameterInfo(aClass, "T", "java.lang.String")
};
}
doTest(aClass -> new TypeParameterInfo[]{
new TypeParameterInfo(aClass, "T", "java.lang.String")
});
}
public void testSubstituteParamInsideClass() throws Exception {
doTest(new GenParams() {
@Override
public TypeParameterInfo[] gen(PsiClass aClass) throws IncorrectOperationException {
return new TypeParameterInfo[0];
}
});
doTest(aClass -> new TypeParameterInfo[0]);
}
public void testRemoveAllParams() throws Exception {
doTest(new GenParams() {
@Override
public TypeParameterInfo[] gen(PsiClass aClass) {
return new TypeParameterInfo[0];
}
});
doTest(aClass -> new TypeParameterInfo[0]);
}
public void testReorderParams() throws Exception {
doTest(new GenParams() {
@Override
public TypeParameterInfo[] gen(PsiClass aClass) {
return new TypeParameterInfo[] {
new TypeParameterInfo(1),
new TypeParameterInfo(0)
};
}
doTest(aClass -> new TypeParameterInfo[] {
new TypeParameterInfo(1),
new TypeParameterInfo(0)
});
}
public void testAddParam() throws Exception {
doTest(new GenParams() {
@Override
public TypeParameterInfo[] gen(PsiClass aClass) throws IncorrectOperationException {
return new TypeParameterInfo[] {
new TypeParameterInfo(0),
new TypeParameterInfo(aClass, "E", "L<T>")
};
}
doTest(aClass -> new TypeParameterInfo[] {
new TypeParameterInfo(0),
new TypeParameterInfo(aClass, "E", "L<T>")
});
}
public void testAddParamDiamond() throws Exception {
doTest(new GenParams() {
@Override
public TypeParameterInfo[] gen(PsiClass aClass) throws IncorrectOperationException {
return new TypeParameterInfo[] {
new TypeParameterInfo(0),
new TypeParameterInfo(aClass, "I", "Integer")
};
}
doTest(aClass -> new TypeParameterInfo[] {
new TypeParameterInfo(0),
new TypeParameterInfo(aClass, "I", "Integer")
});
}
public void testAddOneFirst() throws Exception {
doTest(new GenParams() {
@Override
public TypeParameterInfo[] gen(PsiClass aClass) throws IncorrectOperationException {
return new TypeParameterInfo[]{
new TypeParameterInfo(aClass, "T", "java.lang.String")
};
}
doTest(aClass -> new TypeParameterInfo[]{
new TypeParameterInfo(aClass, "T", "java.lang.String")
}, "Zero.java", "OneString.java");
}
public void testAddManyFirst() throws Exception {
doTest(new GenParams() {
@Override
public TypeParameterInfo[] gen(PsiClass aClass) throws IncorrectOperationException {
return new TypeParameterInfo[]{
new TypeParameterInfo(aClass, "U", "SubjectFace"),
new TypeParameterInfo(aClass, "V", "java.util.Set<java.lang.Object>")
};
}
doTest(aClass -> new TypeParameterInfo[]{
new TypeParameterInfo(aClass, "U", "SubjectFace"),
new TypeParameterInfo(aClass, "V", "java.util.Set<java.lang.Object>")
}, "Zero.java", "TwoSubjectFaceSetObject.java");
}
public void testRemoveOneLast() throws Exception {
doTest(new GenParams() {
@Override
public TypeParameterInfo[] gen(PsiClass aClass) throws IncorrectOperationException {
return new TypeParameterInfo[0];
}
}, "OneString.java", "Zero.java");
doTest(aClass -> new TypeParameterInfo[0], "OneString.java", "Zero.java");
}
public void testRemoveManyLast() throws Exception {
doTest(new GenParams() {
@Override
public TypeParameterInfo[] gen(PsiClass aClass) throws IncorrectOperationException {
return new TypeParameterInfo[0];
}
}, "TwoSubjectFaceSetObject.java", "Zero.java");
doTest(aClass -> new TypeParameterInfo[0], "TwoSubjectFaceSetObject.java", "Zero.java");
}
private void doTest(GenParams gen) throws Exception {
@@ -51,14 +51,12 @@ public class InlineLibraryMethodTest extends RefactoringTestCase {
PsiClass fileClass = getJavaFacade().findClass("mycompany.File");
assertNotNull(fileClass);
final PsiFile file = fileClass.getContainingFile();
WriteCommandAction.runWriteCommandAction(null, new Runnable() {
public void run() {
try {
((VirtualFileSystemEntry)file.getVirtualFile()).setWritable(false);
}
catch (IOException e) {
throw new RuntimeException(e);
}
WriteCommandAction.runWriteCommandAction(null, () -> {
try {
((VirtualFileSystemEntry)file.getVirtualFile()).setWritable(false);
}
catch (IOException e) {
throw new RuntimeException(e);
}
});
@@ -57,12 +57,9 @@ public class MigrationTest extends MultiFileTestCase {
}
private MultiFileTestCase.PerformAction createAction(final MigrationMap migrationMap) {
return new MultiFileTestCase.PerformAction() {
@Override
public void performAction(VirtualFile rootDir, VirtualFile rootAfter) throws Exception {
new MigrationProcessor(myProject, migrationMap).run();
FileDocumentManager.getInstance().saveAllDocuments();
}
return (rootDir, rootAfter) -> {
new MigrationProcessor(myProject, migrationMap).run();
FileDocumentManager.getInstance().saveAllDocuments();
};
}
@@ -138,6 +138,7 @@ public abstract class ExecutionWithDebuggerToolsTestCase extends ExecutionTestCa
}
catch (AssertionError e) {
addException(e);
paused(suspendContext);
}
if (myScriptRunnables.isEmpty()) {
Binary file not shown.
@@ -351,6 +351,11 @@ public class FileStatusMap implements Disposable {
public <T> void putUserData(@NotNull Key<T> key, @Nullable T value) {
throw new UnsupportedOperationException();
}
@Override
public String toString() {
return "WHOLE_FILE";
}
};
// logging
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2014 JetBrains s.r.o.
* Copyright 2000-2015 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.
@@ -60,7 +60,7 @@ public @interface Flow {
* </li>
* </ul>
*/
String source() default org.intellij.lang.annotations.Flow.DEFAULT_SOURCE;
String source() default Flow.DEFAULT_SOURCE;
String DEFAULT_SOURCE = "The method argument (if parameter was annotated) or this container (if instance method was annotated)";
String THIS_SOURCE = "this";
@@ -109,7 +109,7 @@ public @interface Flow {
* </li>
* </ul>
*/
String target() default org.intellij.lang.annotations.Flow.DEFAULT_TARGET;
String target() default Flow.DEFAULT_TARGET;
String DEFAULT_TARGET = "This container (if the parameter was annotated) or the return value (if instance method was annotated)";
String RETURN_METHOD_TARGET = "The return value of this method";
String THIS_TARGET = "this";
@@ -59,7 +59,7 @@ public class BuiltInWebBrowserUrlProvider extends WebBrowserUrlProvider implemen
}
public static boolean compareAuthority(@Nullable String currentAuthority) {
if (currentAuthority == null) {
if (StringUtil.isEmpty(currentAuthority)) {
return false;
}
@@ -35,6 +35,7 @@ public abstract class ApplicationInfo {
public abstract String getCompanyURL();
public abstract String getThirdPartySoftwareURL();
public abstract String getJetbrainsTvUrl();
public abstract String getEvalLicenseUrl();
public abstract Rectangle getAboutLogoRect();
public abstract boolean hasHelp();
@@ -418,7 +418,7 @@ public class VfsUtilCore {
return prefix + ":///" + suffix;
}
}
else if (url.charAt(index + 3) == '/' && SystemInfoRt.isWindows && url.regionMatches(0, StandardFileSystems.FILE_PROTOCOL_PREFIX, 0, StandardFileSystems.FILE_PROTOCOL_PREFIX.length())) {
else if (SystemInfoRt.isWindows && (index + 3) < url.length() && url.charAt(index + 3) == '/' && url.regionMatches(0, StandardFileSystems.FILE_PROTOCOL_PREFIX, 0, StandardFileSystems.FILE_PROTOCOL_PREFIX.length())) {
// file:///C:/test/file.js -> file://C:/test/file.js
for (int i = index + 4; i < url.length(); i++) {
char c = url.charAt(i);
@@ -100,6 +100,7 @@ public class ApplicationInfoImpl extends ApplicationInfoEx implements JDOMExtern
private String myStatisticsServiceKey;
private String myThirdPartySoftwareUrl;
private String myJetbrainsTvUrl;
private String myEvalLicenseUrl = "https://www.jetbrains.com/company/useterms.html";
private Rectangle myAboutLogoRect;
@@ -172,6 +173,8 @@ public class ApplicationInfoImpl extends ApplicationInfoEx implements JDOMExtern
private static final String ELEMENT_JB_TV = "jetbrains-tv";
private static final String CUSTOMIZE_IDE_WIZARD_STEPS = "customize-ide-wizard";
private static final String STEPS_PROVIDER = "provider";
private static final String ELEMENT_EVALUATION = "evaluation";
private static final String ATTRIBUTE_EVAL_LICENSE_URL = "license-url";
private static final String DEFAULT_PLUGINS_HOST = "http://plugins.jetbrains.com";
@@ -488,6 +491,11 @@ public class ApplicationInfoImpl extends ApplicationInfoEx implements JDOMExtern
return myJetbrainsTvUrl;
}
@Override
public String getEvalLicenseUrl() {
return myEvalLicenseUrl;
}
@Override
public Rectangle getAboutLogoRect() {
return myAboutLogoRect;
@@ -764,6 +772,15 @@ public class ApplicationInfoImpl extends ApplicationInfoEx implements JDOMExtern
if (tvElement != null) {
myJetbrainsTvUrl = tvElement.getAttributeValue(ATTRIBUTE_URL);
}
Element evaluationElement = parentNode.getChild(ELEMENT_EVALUATION);
if (evaluationElement != null) {
final String url = evaluationElement.getAttributeValue(ATTRIBUTE_EVAL_LICENSE_URL);
if (url != null && !url.isEmpty()) {
myEvalLicenseUrl = url;
}
}
}
private static void setBuildNumber(String apiVersion, String buildNumber) {
@@ -64,7 +64,7 @@ public class CoreProgressManager extends ProgressManager implements Disposable {
private static volatile boolean thereIsProcessUnderCanceledIndicator;
// active (i.e. which have executeProcessUnderProgress() method running) indicators which are not inherited from StandardProgressIndicator.
// for them an extra processing thread (see myCheckCancelledFuture) has to be run to call their non-standard checkCanceled() method
// for them an extra processing thread (see myCheckCancelledFuture) has to be run to call their non-standard checkCanceled() method periodically.
private static final Collection<ProgressIndicator> nonStandardIndicators = ConcurrentHashMultiset.create();
public CoreProgressManager() {
@@ -241,8 +241,8 @@ public class SingleRootFileViewProvider extends UserDataHolderBase implements Fi
@NotNull
public FileElement[] getKnownTreeRoots() {
PsiFile psiFile = getCachedPsi(myBaseLanguage);
if (psiFile == null || !(psiFile instanceof PsiFileImpl)) return new FileElement[0];
if (((PsiFileImpl)psiFile).getTreeElement() == null) return new FileElement[0];
if (!(psiFile instanceof PsiFileImpl)) return FileElement.EMPTY_ARRAY;
if (((PsiFileImpl)psiFile).getTreeElement() == null) return FileElement.EMPTY_ARRAY;
return new FileElement[]{(FileElement)psiFile.getNode()};
}
@@ -528,9 +528,7 @@ public class SingleRootFileViewProvider extends UserDataHolderBase implements Fi
if (document == null) {
return LoadTextUtil.loadText(virtualFile);
}
else {
return getLastCommittedText(document);
}
return getLastCommittedText(document);
}
@Override
@@ -546,9 +544,7 @@ public class SingleRootFileViewProvider extends UserDataHolderBase implements Fi
if (document == null) {
return virtualFile.getModificationStamp();
}
else {
return getLastCommittedStamp(document);
}
return getLastCommittedStamp(document);
}
@NonNls
@@ -567,7 +563,7 @@ public class SingleRootFileViewProvider extends UserDataHolderBase implements Fi
private class PsiFileContent implements Content {
private final PsiFileImpl myFile;
private volatile String myContent = null;
private volatile String myContent;
private final long myModificationStamp;
@SuppressWarnings("MismatchedQueryAndUpdateOfCollection")
@@ -29,7 +29,7 @@ import com.intellij.psi.impl.PsiManagerEx;
import com.intellij.psi.impl.source.tree.MarkersHolderFileViewProvider;
import com.intellij.psi.util.PsiUtilCore;
import com.intellij.reference.SoftReference;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.ArrayUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.TestOnly;
@@ -37,10 +37,6 @@ import org.jetbrains.annotations.TestOnly;
import java.lang.ref.Reference;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.WeakReference;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
public class SmartPointerManagerImpl extends SmartPointerManager {
private static final Logger LOG = Logger.getInstance("#com.intellij.psi.impl.smartPointers.SmartPointerManagerImpl");
@@ -54,7 +50,7 @@ public class SmartPointerManagerImpl extends SmartPointerManager {
});
private final Project myProject;
private final Key<Set<PointerReference>> POINTERS_KEY;
private final Key<FilePointersList> POINTERS_KEY;
private final Key<Boolean> POINTERS_ARE_FASTENED_KEY;
public SmartPointerManagerImpl(Project project) {
@@ -68,7 +64,7 @@ public class SmartPointerManagerImpl extends SmartPointerManager {
PointerReference reference = (PointerReference)ourQueue.poll();
if (reference == null) break;
synchronized (lock) {
Set<PointerReference> pointers = reference.file.getUserData(reference.key);
FilePointersList pointers = reference.file.getUserData(reference.key);
if (pointers != null) {
pointers.remove(reference);
if (pointers.isEmpty()) {
@@ -83,13 +79,15 @@ public class SmartPointerManagerImpl extends SmartPointerManager {
ApplicationManager.getApplication().assertIsDispatchThread();
processQueue();
synchronized (lock) {
List<SmartPointerEx> pointers = getStrongPointers(file);
if (pointers.isEmpty()) return;
if (getAndFasten(file)) return;
for (SmartPointerEx pointer : pointers) {
pointer.fastenBelt(offset, cachedRangeMarkers);
FilePointersList pointers = getPointers(file);
if (pointers != null && !pointers.isEmpty()) {
for (PointerReference ref : pointers.references) {
SmartPointerEx pointer = SoftReference.dereference(ref);
if (pointer != null) {
pointer.fastenBelt(offset, cachedRangeMarkers);
}
}
}
PsiFile psiFile = ((PsiManagerEx)PsiManager.getInstance(myProject)).getFileManager().getCachedPsiFile(file);
@@ -124,13 +122,16 @@ public class SmartPointerManagerImpl extends SmartPointerManager {
ApplicationManager.getApplication().assertIsDispatchThread();
processQueue();
synchronized (lock) {
List<SmartPointerEx> pointers = getStrongPointers(file);
if (pointers.isEmpty()) return;
FilePointersList pointers = getPointers(file);
if (pointers == null || pointers.isEmpty()) return;
if (!getAndUnfasten(file)) return;
for (SmartPointerEx pointer : pointers) {
pointer.unfastenBelt(offset);
for (PointerReference ref : pointers.references) {
SmartPointerEx pointer = SoftReference.dereference(ref);
if (pointer != null) {
pointer.unfastenBelt(offset);
}
}
PsiFile psiFile = ((PsiManagerEx)PsiManager.getInstance(myProject)).getFileManager().getCachedPsiFile(file);
@@ -211,9 +212,9 @@ public class SmartPointerManagerImpl extends SmartPointerManager {
private <E extends PsiElement> void initPointer(@NotNull SmartPsiElementPointerImpl<E> pointer, @NotNull VirtualFile containingFile) {
synchronized (lock) {
Set<PointerReference> pointers = getPointers(containingFile);
FilePointersList pointers = getPointers(containingFile);
if (pointers == null) {
pointers = ContainerUtil.newTroveSet(); // we synchronise access anyway
pointers = new FilePointersList(); // we synchronise access anyway
containingFile.putUserData(POINTERS_KEY, pointers);
}
if (areBeltsFastened(containingFile)) {
@@ -244,45 +245,29 @@ public class SmartPointerManagerImpl extends SmartPointerManager {
if (containingFile == null) return false;
VirtualFile vFile = containingFile.getViewProvider().getVirtualFile();
Set<PointerReference> pointers = getPointers(vFile);
FilePointersList pointers = getPointers(vFile);
if (pointers == null) return false;
for (Iterator<PointerReference> iterator = pointers.iterator(); iterator.hasNext(); ) {
if (pointer == iterator.next().get()) {
iterator.remove();
if (pointers.isEmpty()) {
vFile.putUserData(POINTERS_KEY, null);
}
return true;
}
boolean result = pointers.remove(pointer);
if (pointers.isEmpty()) {
vFile.putUserData(POINTERS_KEY, null);
}
return result;
}
}
return false;
}
@Nullable
private Set<PointerReference> getPointers(@NotNull VirtualFile containingFile) {
private FilePointersList getPointers(@NotNull VirtualFile containingFile) {
return containingFile.getUserData(POINTERS_KEY);
}
@NotNull
private List<SmartPointerEx> getStrongPointers(@NotNull VirtualFile containingFile) {
Set<PointerReference> refs = getPointers(containingFile);
if (refs == null) return Collections.emptyList();
List<SmartPointerEx> result = ContainerUtil.newArrayList();
for (PointerReference reference : refs) {
ContainerUtil.addIfNotNull(result, reference.get());
}
return result;
}
@TestOnly
public int getPointersNumber(@NotNull PsiFile containingFile) {
synchronized (lock) {
return getStrongPointers(containingFile.getViewProvider().getVirtualFile()).size();
VirtualFile file = containingFile.getViewProvider().getVirtualFile();
FilePointersList pointers = getPointers(file);
return pointers == null ? 0 : pointers.size;
}
}
@@ -306,17 +291,66 @@ public class SmartPointerManagerImpl extends SmartPointerManager {
}
private static class PointerReference extends WeakReference<SmartPointerEx> {
private final VirtualFile file;
private final Key<Set<PointerReference>> key;
@NotNull private final VirtualFile file;
@NotNull private final Key<FilePointersList> key;
public PointerReference(SmartPointerEx<?> pointer,
VirtualFile containingFile,
ReferenceQueue<SmartPointerEx> queue,
Key<Set<PointerReference>> key) {
private PointerReference(@NotNull SmartPointerEx<?> pointer,
@NotNull VirtualFile containingFile,
@NotNull ReferenceQueue<SmartPointerEx> queue,
@NotNull Key<FilePointersList> key) {
super(pointer, queue);
file = containingFile;
this.key = key;
}
}
private static class FilePointersList {
private int nextAvailableIndex;
private int size;
private PointerReference[] references = new PointerReference[10];
private void add(@NotNull PointerReference reference) {
if (nextAvailableIndex >= references.length || nextAvailableIndex > size*2) { // overflow or too many dead refs
int newCapacity = nextAvailableIndex >= references.length ? references.length * 3/2 +1 : size * 3/2+1;
PointerReference[] newReferences = new PointerReference[newCapacity];
int o = 0;
for (PointerReference oldRef : references) {
if (SoftReference.dereference(oldRef) != null) {
newReferences[o++] = oldRef;
}
}
references = newReferences;
size = nextAvailableIndex = o;
}
references[nextAvailableIndex++] = reference;
size++;
}
private void remove(@NotNull PointerReference reference) {
int index = ArrayUtil.indexOf(references, reference);
if (index != -1) {
references[index] = null;
size--;
}
}
private boolean remove(@NotNull SmartPsiElementPointer smartPointer) {
boolean result = false;
for (int i = 0; i < references.length; i++) {
PointerReference reference = references[i];
if (reference != null && reference.get() == smartPointer) {
references[i] = null;
result = true;
break;
}
}
size--;
return result;
}
private boolean isEmpty() {
return size == 0;
}
}
}
@@ -30,6 +30,7 @@ import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
public class FileElement extends LazyParseableElement implements FileASTNode, Getter<FileElement> {
public static final FileElement[] EMPTY_ARRAY = new FileElement[0];
private volatile CharTable myCharTable = new CharTableImpl();
private volatile boolean myDetached;
@@ -52,7 +52,6 @@ import com.intellij.openapi.editor.ex.EditorMarkupModel;
import com.intellij.openapi.editor.ex.util.EmptyEditorHighlighter;
import com.intellij.openapi.editor.highlighter.EditorHighlighter;
import com.intellij.openapi.editor.highlighter.EditorHighlighterFactory;
import com.intellij.openapi.editor.impl.softwrap.SoftWrapAppliancePlaces;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.fileTypes.FileType;
import com.intellij.openapi.progress.ProgressIndicator;
@@ -165,7 +164,6 @@ public class DiffUtil {
EditorEx editor = (EditorEx)(isViewer ? factory.createViewer(document, project) : factory.createEditor(document, project));
editor.putUserData(DiffManagerImpl.EDITOR_IS_DIFF_KEY, Boolean.TRUE);
editor.setSoftWrapAppliancePlace(SoftWrapAppliancePlaces.VCS_DIFF);
editor.getSettings().setLineNumbersShown(true);
((EditorMarkupModel)editor.getMarkupModel()).setErrorStripeVisible(true);
@@ -130,7 +130,7 @@ public class InspectionResultsView extends JPanel implements Disposable, Occuren
myBrowser = new Browser(this);
mySplitter = new Splitter(false, AnalysisUIOptions.getInstance(myProject).SPLITTER_PROPORTION);
mySplitter = new OnePixelSplitter(false, AnalysisUIOptions.getInstance(myProject).SPLITTER_PROPORTION);
mySplitter.setFirstComponent(ScrollPaneFactory.createScrollPane(myTree, SideBorder.LEFT | SideBorder.RIGHT));
mySplitter.setSecondComponent(myBrowser);
@@ -13,7 +13,6 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.execution.impl;
import com.intellij.execution.BeforeRunTask;
@@ -44,8 +43,9 @@ import java.util.List;
*/
public class ConfigurationSettingsEditorWrapper extends SettingsEditor<RunnerAndConfigurationSettings>
implements BeforeRunStepsPanel.StepsBeforeRunListener {
public static DataKey<ConfigurationSettingsEditorWrapper> CONFIGURATION_EDITOR_KEY = DataKey.create("ConfigurationSettingsEditor");
public static final DataKey<ConfigurationSettingsEditorWrapper> CONFIGURATION_EDITOR_KEY = DataKey.create("ConfigurationSettingsEditor");
@NonNls private static final String EXPAND_PROPERTY_KEY = "ExpandBeforeRunStepsPanel";
private JPanel myComponentPlace;
private JPanel myWholePanel;
@@ -79,6 +79,7 @@ public class ConfigurationSettingsEditorWrapper extends SettingsEditor<RunnerAnd
super.off();
storeState();
}
private void storeState() {
PropertiesComponent.getInstance().setValue(EXPAND_PROPERTY_KEY, String.valueOf(isExpanded()));
}
@@ -153,7 +154,6 @@ public class ConfigurationSettingsEditorWrapper extends SettingsEditor<RunnerAnd
}
private class MyDataProvider implements DataProvider {
@Nullable
@Override
public Object getData(@NonNls String dataId) {
@@ -22,6 +22,7 @@ import com.intellij.execution.configurations.*;
import com.intellij.execution.runners.ExecutionEnvironment;
import com.intellij.ide.util.PropertiesComponent;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.components.*;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.extensions.Extensions;
@@ -154,6 +155,7 @@ public class RunManagerImpl extends RunManagerEx implements PersistentStateCompo
@NotNull
public RunnerAndConfigurationSettings createConfiguration(@NotNull final RunConfiguration runConfiguration,
@NotNull final ConfigurationFactory factory) {
assertDispatchThread();
RunnerAndConfigurationSettings template = getConfigurationTemplate(factory);
RunnerAndConfigurationSettingsImpl settings = new RunnerAndConfigurationSettingsImpl(this, runConfiguration, false);
settings.importRunnerAndConfigurationSettings((RunnerAndConfigurationSettingsImpl)template);
@@ -163,6 +165,12 @@ public class RunManagerImpl extends RunManagerEx implements PersistentStateCompo
return settings;
}
private void assertDispatchThread() {
if (myProject.isInitialized()) {
ApplicationManager.getApplication().assertIsDispatchThread();
}
}
@Override
public void dispose() {
myTemplateConfigurationsMap.clear();
@@ -336,6 +344,7 @@ public class RunManagerImpl extends RunManagerEx implements PersistentStateCompo
public void addConfiguration(RunnerAndConfigurationSettings settings,
boolean shared,
List<BeforeRunTask> tasks, boolean addEnabledTemplateTasksIfAbsent) {
assertDispatchThread();
String existingId = findExistingConfigurationId(settings);
String newId = settings.getUniqueID();
RunnerAndConfigurationSettings existingSettings = null;
@@ -416,6 +425,7 @@ public class RunManagerImpl extends RunManagerEx implements PersistentStateCompo
@Override
public void removeConfiguration(@Nullable RunnerAndConfigurationSettings settings) {
assertDispatchThread();
if (settings == null) return;
for (Iterator<RunnerAndConfigurationSettings> it = getSortedConfigurations().iterator(); it.hasNext(); ) {
@@ -684,8 +694,6 @@ public class RunManagerImpl extends RunManagerEx implements PersistentStateCompo
@Override
public void loadState(Element parentNode) {
clear(false);
List<Element> children = parentNode.getChildren(CONFIGURATION);
Element[] sortedElements = children.toArray(new Element[children.size()]);
// ensure templates are loaded first
@@ -810,6 +818,7 @@ public class RunManagerImpl extends RunManagerEx implements PersistentStateCompo
}
private void clear(boolean allConfigurations) {
assertDispatchThread();
List<RunnerAndConfigurationSettings> configurations;
if (allConfigurations) {
myConfigurations.clear();
@@ -1138,6 +1147,7 @@ public class RunManagerImpl extends RunManagerEx implements PersistentStateCompo
@NotNull
@Override
public <T extends BeforeRunTask> List<T> getBeforeRunTasks(RunConfiguration settings, Key<T> taskProviderID) {
assertDispatchThread();
if (settings instanceof WrappingRunConfiguration) {
return getBeforeRunTasks(((WrappingRunConfiguration)settings).getPeer(), taskProviderID);
}
@@ -1159,6 +1169,7 @@ public class RunManagerImpl extends RunManagerEx implements PersistentStateCompo
@Override
@NotNull
public List<BeforeRunTask> getBeforeRunTasks(final RunConfiguration settings) {
assertDispatchThread();
if (settings instanceof WrappingRunConfiguration) {
return getBeforeRunTasks(((WrappingRunConfiguration)settings).getPeer());
}
@@ -1214,6 +1225,7 @@ public class RunManagerImpl extends RunManagerEx implements PersistentStateCompo
@Override
public final void setBeforeRunTasks(final RunConfiguration runConfiguration, @NotNull List<BeforeRunTask> tasks, boolean addEnabledTemplateTasksIfAbsent) {
assertDispatchThread();
List<BeforeRunTask> result = new SmartList<BeforeRunTask>(tasks);
if (addEnabledTemplateTasksIfAbsent) {
List<BeforeRunTask> templates = getTemplateBeforeRunTasks(runConfiguration);
@@ -1234,6 +1246,7 @@ public class RunManagerImpl extends RunManagerEx implements PersistentStateCompo
}
public final void resetBeforeRunTasks(final RunConfiguration runConfiguration) {
assertDispatchThread();
myConfigurationToBeforeTasksMap.remove(runConfiguration);
fireBeforeRunTasksUpdated();
}
@@ -15,6 +15,7 @@
*/
package com.intellij.formatting.contextConfiguration;
import com.intellij.codeInsight.CodeInsightBundle;
import com.intellij.codeInsight.intention.IntentionAction;
import com.intellij.lang.Language;
import com.intellij.openapi.diagnostic.Logger;
@@ -28,6 +29,7 @@ import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.openapi.util.Computable;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.util.TextRange;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.PsiFile;
import com.intellij.psi.codeStyle.CodeStyleSettings;
import com.intellij.psi.codeStyle.CodeStyleSettingsCodeFragmentFilter;
@@ -50,7 +52,7 @@ public class ConfigureCodeStyleOnSelectedFragment implements IntentionAction {
@NotNull
@Override
public String getText() {
return "Configure code style";
return CodeInsightBundle.message("configure.code.style.on.fragment.dialog.title");
}
@Nls
@@ -108,7 +110,9 @@ public class ConfigureCodeStyleOnSelectedFragment implements IntentionAction {
myEditor = editor;
myDocument = editor.getDocument();
setTitle("Configure Code Style Settings: " + language.getDisplayName());
String title = CodeInsightBundle.message("configure.code.style.on.fragment.dialog.title");
setTitle(StringUtil.capitalizeWords(title, true) + ": " + language.getDisplayName());
setOKButtonText("Save");
setInitialLocationCallback(new Computable<Point>() {
@@ -96,7 +96,7 @@ public class CreateFileFromTemplateDialog extends DialogWrapper {
@Override
protected void doOKAction() {
if (myCreator.tryCreate(getEnteredName()).length == 0) {
if (myCreator != null && myCreator.tryCreate(getEnteredName()).length == 0) {
return;
}
super.doOKAction();
@@ -63,7 +63,7 @@ class EditorSettingsStatisticsCollector extends UsagesCollector {
addIfDiffers(set, es.isWhitespacesShown() && es.isTrailingWhitespacesShown(), false, "showTrailingWhitespace");
addIfDiffers(set, es.isIndentGuidesShown(), true, "noIndentGuides");
addIfDiffers(set, es.isSmoothScrolling(), true, "noAnimatedScroll");
addIfDiffers(set, es.isDndEnabled(), false, "dragNDrop");
addIfDiffers(set, es.isDndEnabled(), true, "noDragNDrop");
addIfDiffers(set, es.isWheelFontChangeEnabled(), false, "wheelZoom");
addIfDiffers(set, es.isMouseClickSelectionHonorsCamelWords(), true, "mouseNoCamel");
addIfDiffers(set, es.isVariableInplaceRenameEnabled(), true, "noInplaceRename");
@@ -68,7 +68,8 @@ public class CodeStyleSettingsCodeFragmentFilter {
try {
codeStyleSettingsManager.setTemporarySettings(clonedSettings);
SequentialModalProgressTask progressTask = new SequentialModalProgressTask(myProject, CodeInsightBundle.message("configure.code.style.on.fragment.dialog.title"));
String title = CodeInsightBundle.message("configure.code.style.on.fragment.dialog.title");
SequentialModalProgressTask progressTask = new SequentialModalProgressTask(myProject, StringUtil.capitalizeWords(title, true));
progressTask.setCancelText(CodeInsightBundle.message("configure.code.style.on.fragment.dialog.cancel"));
CompositeSequentialTask compositeTask = new CompositeSequentialTask(progressTask);
compositeTask.setProgressText(CodeInsightBundle.message("configure.code.style.on.fragment.dialog.progress.text"));
@@ -190,11 +190,9 @@ public class MemoryIndexStorage<Key, Value> implements IndexStorage<Key, Value>
@Override
@NotNull
public ValueContainer<Value> read(final Key key) throws StorageException {
if (myBufferingEnabled) {
final ValueContainer<Value> valueContainer = myMap.get(key);
if (valueContainer != null) {
return valueContainer;
}
final ValueContainer<Value> valueContainer = myMap.get(key);
if (valueContainer != null) {
return valueContainer;
}
return myBackendStorage.read(key);
@@ -96,11 +96,14 @@ public class CommonShortcuts {
return shortcutsById(IdeActions.ACTION_NEW_ELEMENT);
}
public static ShortcutSet getDuplicate() {
return shortcutsById(IdeActions.ACTION_EDITOR_DUPLICATE);
}
public static ShortcutSet getMove() {
return shortcutsById(IdeActions.ACTION_MOVE);
}
public static ShortcutSet getRename() {
return shortcutsById(IdeActions.ACTION_RENAME);
}
@@ -15,11 +15,11 @@
*/
package com.intellij.ide;
import com.intellij.icons.AllIcons;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.Separator;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ex.ApplicationInfoEx;
import com.intellij.openapi.components.PersistentStateComponent;
import com.intellij.openapi.project.DumbAwareAction;
import com.intellij.openapi.project.Project;
@@ -27,6 +27,7 @@ import com.intellij.openapi.project.ProjectManager;
import com.intellij.openapi.project.ProjectManagerListener;
import com.intellij.openapi.project.impl.ProjectImpl;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.util.IconLoader;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.Ref;
import com.intellij.openapi.util.SystemInfo;
@@ -36,10 +37,12 @@ import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.CharsetToolkit;
import com.intellij.openapi.wm.impl.SystemDock;
import com.intellij.openapi.wm.impl.welcomeScreen.WelcomeFrame;
import com.intellij.util.IconUtil;
import com.intellij.util.ImageLoader;
import com.intellij.util.SmartList;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.messages.MessageBus;
import com.intellij.util.ui.EmptyIcon;
import com.intellij.util.ui.ImageUtil;
import com.intellij.util.ui.JBUI;
import com.intellij.util.ui.UIUtil;
@@ -63,6 +66,7 @@ import java.util.List;
*/
public abstract class RecentProjectsManagerBase extends RecentProjectsManager implements ProjectManagerListener, PersistentStateComponent<RecentProjectsManagerBase.State> {
private static final Map<String, MyIcon> ourProjectIcons = new HashMap<String, MyIcon>();
private static Icon ourSmallAppIcon;
public static RecentProjectsManagerBase getInstanceEx() {
return (RecentProjectsManagerBase)RecentProjectsManager.getInstance();
@@ -215,6 +219,11 @@ public abstract class RecentProjectsManagerBase extends RecentProjectsManager im
@NotNull
public static Icon createIcon(File file) {
final BufferedImage image = loadAndScaleImage(file);
return toRetinaAwareIcon(image);
}
@NotNull
protected static Icon toRetinaAwareIcon(final BufferedImage image) {
return new Icon() {
@Override
public void paintIcon(Component c, Graphics g, int x, int y) {
@@ -245,10 +254,9 @@ public abstract class RecentProjectsManagerBase extends RecentProjectsManager im
private static BufferedImage loadAndScaleImage(File file) {
try {
Image img = ImageLoader.loadFromUrl(file.toURL());
return Scalr.resize(ImageUtil.toBufferedImage(img), Scalr.Method.ULTRA_QUALITY, UIUtil.isRetina() ? 32 : JBUI.scale(16), null);
return Scalr.resize(ImageUtil.toBufferedImage(img), Scalr.Method.ULTRA_QUALITY, UIUtil.isRetina() ? 32 : JBUI.scale(16));
}
catch (MalformedURLException e) {
e.printStackTrace();
catch (MalformedURLException e) {//
}
return null;
}
@@ -267,8 +275,32 @@ public abstract class RecentProjectsManagerBase extends RecentProjectsManager im
}
}
return getSmallApplicationIcon();
}
return AllIcons.Nodes.IdeaProject;
protected static Icon getSmallApplicationIcon() {
if (ourSmallAppIcon == null) {
try {
Icon appIcon = IconLoader.findIcon(ApplicationInfoEx.getInstanceEx().getIconUrl());
if (appIcon != null) {
if (appIcon.getIconWidth() == JBUI.scale(16) && appIcon.getIconHeight() == JBUI.scale(16)) {
ourSmallAppIcon = appIcon;
} else {
BufferedImage image = ImageUtil.toBufferedImage(IconUtil.toImage(appIcon));
image = Scalr.resize(image, Scalr.Method.ULTRA_QUALITY, UIUtil.isRetina() ? 32 : JBUI.scale(16));
ourSmallAppIcon = toRetinaAwareIcon(image);
}
}
}
catch (Exception e) {//
}
if (ourSmallAppIcon == null) {
ourSmallAppIcon = EmptyIcon.ICON_16;
}
}
return ourSmallAppIcon;
}
private Set<String> getDuplicateProjectNames(Set<String> openedPaths, Set<String> recentPaths) {
@@ -56,5 +56,11 @@ public class IntelliJLaf extends DarculaLaf {
defaults.put("Label.font", font);
defaults.put("CheckBox.font", font);
defaults.put("RadioButton.font", font);
defaults.put("ComboBox.font", font);
}
public static boolean isGraphite() {
Color c = UIManager.getColor("controlHighlight");
return c != null && c.getBlue() < 150;
}
}
@@ -437,4 +437,8 @@ public class DarculaLaf extends BasicLookAndFeel {
public boolean getSupportsWindowDecorations() {
return true;
}
public static Icon loadIcon(String path) {
return IconLoader.findIcon(path, DarculaLaf.class, true);
}
}

Some files were not shown because too many files have changed in this diff Show More