diff --git a/.idea/libraries/gson.xml b/.idea/libraries/gson.xml index 67778e62935d..beaa3d762dc6 100644 --- a/.idea/libraries/gson.xml +++ b/.idea/libraries/gson.xml @@ -1,11 +1,11 @@ - + - + \ No newline at end of file diff --git a/java/compiler/impl/src/com/intellij/compiler/actions/ProcessAnnotationsAction.java b/java/compiler/impl/src/com/intellij/compiler/actions/ProcessAnnotationsAction.java index bb5970753e0c..3ed374732fc0 100644 --- a/java/compiler/impl/src/com/intellij/compiler/actions/ProcessAnnotationsAction.java +++ b/java/compiler/impl/src/com/intellij/compiler/actions/ProcessAnnotationsAction.java @@ -15,8 +15,8 @@ */ package com.intellij.compiler.actions; -import org.jetbrains.jps.model.java.compiler.AnnotationProcessingConfiguration; import com.intellij.compiler.CompilerConfiguration; +import com.intellij.compiler.CompilerWorkspaceConfiguration; import com.intellij.compiler.impl.FileSetCompileScope; import com.intellij.compiler.impl.ModuleCompileScope; import com.intellij.compiler.impl.javaCompiler.AnnotationProcessingCompiler; @@ -37,6 +37,7 @@ import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.*; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.Nullable; +import org.jetbrains.jps.model.java.compiler.AnnotationProcessingConfiguration; import java.text.MessageFormat; import java.util.ArrayList; @@ -79,7 +80,13 @@ public class ProcessAnnotationsAction extends CompileActionBase { return; } - CompilerConfiguration compilerConfiguration = CompilerConfiguration.getInstance(project); + if (CompilerWorkspaceConfiguration.getInstance(project).useOutOfProcessBuild()) { + presentation.setEnabled(false); + return; + } + + final CompilerConfiguration compilerConfiguration = CompilerConfiguration.getInstance(project); + final Module module = LangDataKeys.MODULE.getData(dataContext); final Module moduleContext = LangDataKeys.MODULE_CONTEXT.getData(dataContext); diff --git a/java/compiler/impl/src/com/intellij/compiler/impl/CompileDriver.java b/java/compiler/impl/src/com/intellij/compiler/impl/CompileDriver.java index d9f3aac34d4f..e64ff40f5181 100644 --- a/java/compiler/impl/src/com/intellij/compiler/impl/CompileDriver.java +++ b/java/compiler/impl/src/com/intellij/compiler/impl/CompileDriver.java @@ -854,17 +854,35 @@ public class CompileDriver { if (refreshOutputRoots) { // refresh on output roots is required in order for the order enumerator to see all roots via VFS final Set outputs = new HashSet(); - for (final String path : CompilerPathsEx.getOutputPaths(ModuleManager.getInstance(myProject).getModules())) { + final Module[] affectedModules = compileContext.getCompileScope().getAffectedModules(); + for (final String path : CompilerPathsEx.getOutputPaths(affectedModules)) { outputs.add(new File(path)); } + final LocalFileSystem lfs = LocalFileSystem.getInstance(); if (!outputs.isEmpty()) { final ProgressIndicator indicator = compileContext.getProgressIndicator(); indicator.setText("Synchronizing output directories..."); - LocalFileSystem.getInstance().refreshIoFiles(outputs, false, false, null); + lfs.refreshIoFiles(outputs, false, false, null); indicator.setText(""); } + if (compileContext.isAnnotationProcessorsEnabled()) { + final Set genSourceRoots = new THashSet(FileUtil.FILE_HASHING_STRATEGY); + final CompilerConfiguration config = CompilerConfiguration.getInstance(myProject); + for (Module module : affectedModules) { + if (config.getAnnotationProcessingConfiguration(module).isEnabled()) { + final String path = CompilerPaths.getAnnotationProcessorsGenerationPath(module); + if (path != null) { + genSourceRoots.add(new File(path)); + } + } + } + if (!genSourceRoots.isEmpty()) { + // refresh generates source roots asynchronously; needed for error highlighting update + lfs.refreshIoFiles(genSourceRoots, true, true, null); + } + } } - SwingUtilities.invokeLater(new Runnable() { + SwingUtilities.invokeLater(new Runnable() { public void run() { int errorCount = 0; int warningCount = 0; diff --git a/java/debugger/impl/src/com/intellij/debugger/ui/JavaDebuggerSupport.java b/java/debugger/impl/src/com/intellij/debugger/ui/JavaDebuggerSupport.java index dc6cbd46e207..17f7c7d686ba 100644 --- a/java/debugger/impl/src/com/intellij/debugger/ui/JavaDebuggerSupport.java +++ b/java/debugger/impl/src/com/intellij/debugger/ui/JavaDebuggerSupport.java @@ -21,6 +21,7 @@ import com.intellij.debugger.impl.DebuggerContextImpl; import com.intellij.debugger.settings.*; import com.intellij.debugger.ui.breakpoints.*; import com.intellij.ide.DataManager; +import com.intellij.openapi.Disposable; import com.intellij.openapi.actionSystem.AnAction; import com.intellij.openapi.actionSystem.AnActionEvent; import com.intellij.openapi.actionSystem.PlatformDataKeys; @@ -31,16 +32,17 @@ import com.intellij.openapi.editor.markup.RangeHighlighter; import com.intellij.openapi.options.Configurable; import com.intellij.openapi.project.Project; import com.intellij.openapi.project.ProjectManager; +import com.intellij.openapi.util.Disposer; import com.intellij.openapi.util.Key; import com.intellij.util.containers.ContainerUtil; import com.intellij.xdebugger.AbstractDebuggerSession; -import com.intellij.xdebugger.impl.breakpoints.ui.BreakpointItem; import com.intellij.xdebugger.breakpoints.ui.XBreakpointGroupingRule; import com.intellij.xdebugger.impl.DebuggerSupport; import com.intellij.xdebugger.impl.actions.DebuggerActionHandler; import com.intellij.xdebugger.impl.actions.DebuggerToggleActionHandler; import com.intellij.xdebugger.impl.actions.EditBreakpointActionHandler; import com.intellij.xdebugger.impl.actions.MarkObjectActionHandler; +import com.intellij.xdebugger.impl.breakpoints.ui.BreakpointItem; import com.intellij.xdebugger.impl.breakpoints.ui.BreakpointPanelProvider; import com.intellij.xdebugger.impl.evaluate.quick.common.QuickEvaluateHandler; import com.intellij.xdebugger.impl.settings.DebuggerSettingsPanelProvider; @@ -212,15 +214,21 @@ public class JavaDebuggerSupport extends DebuggerSupport { } @Override - public void addListener(final BreakpointsListener listener, Project project) { - BreakpointManager breakpointManager = DebuggerManagerEx.getInstanceEx(getCurrentProject()).getBreakpointManager(); + public void addListener(final BreakpointsListener listener, Project project, Disposable disposable) { + BreakpointManager breakpointManager = DebuggerManagerEx.getInstanceEx(project).getBreakpointManager(); final MyBreakpointManagerListener listener1 = new MyBreakpointManagerListener(listener, breakpointManager); breakpointManager.addBreakpointManagerListener(listener1); myListeners.add(listener1); + Disposer.register(disposable, new Disposable() { + @Override + public void dispose() { + removeListener(listener); + } + }); } @Override - public void removeListener(BreakpointsListener listener) { + protected void removeListener(BreakpointsListener listener) { for (MyBreakpointManagerListener managerListener : myListeners) { if (managerListener.myListener == listener) { BreakpointManager manager = managerListener.myBreakpointManager; diff --git a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/analysis/HighlightUtil.java b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/analysis/HighlightUtil.java index 7151855d7a4d..2098dd6bacaf 100644 --- a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/analysis/HighlightUtil.java +++ b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/analysis/HighlightUtil.java @@ -1357,9 +1357,9 @@ public class HighlightUtil extends HighlightUtilBase { } } - final PsiClass aClass; + PsiClass aClass; if (qualifier != null) { - final PsiElement resolved = qualifier.resolve(); + PsiElement resolved = qualifier.advancedResolve(true).getElement(); if (resolved != null && !(resolved instanceof PsiClass)) { String description = JavaErrorMessages.message("class.expected"); return HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR).range(qualifier).descriptionAndTooltip(description).create(); @@ -1393,7 +1393,7 @@ public class HighlightUtil extends HighlightUtilBase { } return null; } - + private static boolean isInsideDefaultMethod(PsiMethod method, PsiClass aClass) { while (method != null && method.getContainingClass() != aClass) { method = PsiTreeUtil.getParentOfType(method, PsiMethod.class, true); diff --git a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/CreateClassFromUsageBaseFix.java b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/CreateClassFromUsageBaseFix.java index 3d482f54b4ab..1845c960f7e9 100644 --- a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/CreateClassFromUsageBaseFix.java +++ b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/CreateClassFromUsageBaseFix.java @@ -156,7 +156,8 @@ public abstract class CreateClassFromUsageBaseFix extends BaseIntentionAction { final PsiClassType.ClassResolveResult classResolveResult = PsiUtil.resolveGenericsClassInType(expectedTypes[0].getType()); final PsiClass psiClass = classResolveResult.getElement(); if (psiClass != null && CommonClassNames.JAVA_LANG_CLASS.equals(psiClass.getQualifiedName())) { - PsiType psiType = classResolveResult.getSubstitutor().substitute(psiClass.getTypeParameters()[0]); + final PsiTypeParameter[] typeParameters = psiClass.getTypeParameters(); + PsiType psiType = typeParameters.length == 1 ? classResolveResult.getSubstitutor().substitute(typeParameters[0]) : null; if (psiType instanceof PsiWildcardType && ((PsiWildcardType)psiType).isExtends()) { psiType = ((PsiWildcardType)psiType).getExtendsBound(); } diff --git a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/CreateLocalFromUsageFix.java b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/CreateLocalFromUsageFix.java index 155c7ac89281..41ffc74a1129 100644 --- a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/CreateLocalFromUsageFix.java +++ b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/CreateLocalFromUsageFix.java @@ -155,7 +155,7 @@ public class CreateLocalFromUsageFix extends CreateVarFromUsageFix { } final PsiCodeBlock block = PsiTreeUtil.getParentOfType(parent, PsiCodeBlock.class, false); - LOG.assertTrue(block != null && block.getStatements().length > 0, block); + LOG.assertTrue(block != null && block.getStatements().length > 0, "block: " + block +"; parent: " + parent); PsiStatement[] statements = block.getStatements(); for (int i = 1; i < statements.length; i++) { if (statements[i].getTextRange().getStartOffset() > minOffset) return statements[i-1]; diff --git a/java/java-impl/src/com/intellij/codeInsight/intention/impl/AddSingleMemberStaticImportAction.java b/java/java-impl/src/com/intellij/codeInsight/intention/impl/AddSingleMemberStaticImportAction.java index 4f4d74c36cda..faa2deee62df 100644 --- a/java/java-impl/src/com/intellij/codeInsight/intention/impl/AddSingleMemberStaticImportAction.java +++ b/java/java-impl/src/com/intellij/codeInsight/intention/impl/AddSingleMemberStaticImportAction.java @@ -61,8 +61,7 @@ public class AddSingleMemberStaticImportAction extends PsiElementBaseIntentionAc if (parent instanceof PsiMethodReferenceExpression) return null; if (parent instanceof PsiJavaCodeReferenceElement && ((PsiJavaCodeReferenceElement)parent).getQualifier() != null) { PsiJavaCodeReferenceElement refExpr = (PsiJavaCodeReferenceElement)parent; - PsiReferenceParameterList parameterList = refExpr.getParameterList(); - if (parameterList != null && parameterList.getFirstChild() != null) return null; + if (checkParameterizedReference(refExpr)) return null; PsiElement resolved = refExpr.resolve(); if (resolved instanceof PsiMember && ((PsiModifierListOwner)resolved).hasModifierProperty(PsiModifier.STATIC)) { PsiClass aClass = getResolvedClass(element, (PsiMember)resolved); @@ -99,6 +98,11 @@ public class AddSingleMemberStaticImportAction extends PsiElementBaseIntentionAc return null; } + private static boolean checkParameterizedReference(PsiJavaCodeReferenceElement refExpr) { + PsiReferenceParameterList parameterList = refExpr instanceof PsiReferenceExpression ? refExpr.getParameterList() : null; + return parameterList != null && parameterList.getFirstChild() != null; + } + @Nullable private static PsiClass getResolvedClass(PsiElement element, PsiMember resolved) { PsiClass aClass = resolved.getContainingClass(); @@ -158,58 +162,61 @@ public class AddSingleMemberStaticImportAction extends PsiElementBaseIntentionAc @Override public void visitReferenceElement(PsiJavaCodeReferenceElement reference) { - if (reference.getParameterList() != null && - reference.getParameterList().getFirstChild() != null) return; + try { + if (checkParameterizedReference(reference)) return; - if (referenceName.equals(reference.getReferenceName()) && !(reference instanceof PsiMethodReferenceExpression)) { - final PsiElement qualifierExpression = reference.getQualifier(); - PsiElement referent = reference.getUserData(TEMP_REFERENT_USER_DATA); - if (!reference.isQualified()) { - if (referent instanceof PsiMember && referent != reference.resolve()) { - PsiElementFactory factory = JavaPsiFacade.getInstance(reference.getProject()).getElementFactory(); - try { - final PsiClass containingClass = ((PsiMember)referent).getContainingClass(); - if (containingClass != null) { - PsiReferenceExpression copy = (PsiReferenceExpression)factory.createExpressionFromText("A." + reference.getReferenceName(), null); - reference = (PsiReferenceExpression)reference.replace(copy); - ((PsiReferenceExpression)reference.getQualifier()).bindToElement(containingClass); + if (referenceName.equals(reference.getReferenceName()) && !(reference instanceof PsiMethodReferenceExpression)) { + final PsiElement qualifierExpression = reference.getQualifier(); + PsiElement referent = reference.getUserData(TEMP_REFERENT_USER_DATA); + if (!reference.isQualified()) { + if (referent instanceof PsiMember && referent != reference.resolve()) { + PsiElementFactory factory = JavaPsiFacade.getInstance(reference.getProject()).getElementFactory(); + try { + final PsiClass containingClass = ((PsiMember)referent).getContainingClass(); + if (containingClass != null) { + PsiReferenceExpression copy = (PsiReferenceExpression)factory.createExpressionFromText("A." + reference.getReferenceName(), null); + reference = (PsiReferenceExpression)reference.replace(copy); + ((PsiReferenceExpression)reference.getQualifier()).bindToElement(containingClass); + } + } + catch (IncorrectOperationException e) { + LOG.error (e); } } - catch (IncorrectOperationException e) { - LOG.error (e); + reference.putUserData(TEMP_REFERENT_USER_DATA, null); + } else { + if (qualifierExpression instanceof PsiJavaCodeReferenceElement) { + PsiElement aClass = ((PsiJavaCodeReferenceElement)qualifierExpression).resolve(); + if (aClass instanceof PsiVariable) { + aClass = PsiUtil.resolveClassInClassTypeOnly(((PsiVariable)aClass).getType()); + } + if (aClass instanceof PsiClass && InheritanceUtil.isInheritorOrSelf((PsiClass)aClass, resolvedClass, true)) { + boolean foundMemberByName = false; + if (referent instanceof PsiMember) { + final String memberName = ((PsiMember)referent).getName(); + final PsiClass containingClass = PsiTreeUtil.getParentOfType(reference, PsiClass.class); + if (containingClass != null) { + foundMemberByName |= containingClass.findFieldByName(memberName, true) != null; + foundMemberByName |= containingClass.findMethodsByName(memberName, true).length > 0; + } + } + if (!foundMemberByName) { + try { + qualifierExpression.delete(); + } + catch (IncorrectOperationException e) { + LOG.error(e); + } + } + } } } reference.putUserData(TEMP_REFERENT_USER_DATA, null); - } else { - if (qualifierExpression instanceof PsiJavaCodeReferenceElement) { - PsiElement aClass = ((PsiJavaCodeReferenceElement)qualifierExpression).resolve(); - if (aClass instanceof PsiVariable) { - aClass = PsiUtil.resolveClassInClassTypeOnly(((PsiVariable)aClass).getType()); - } - if (aClass instanceof PsiClass && InheritanceUtil.isInheritorOrSelf((PsiClass)aClass, resolvedClass, true)) { - boolean foundMemberByName = false; - if (referent instanceof PsiMember) { - final String memberName = ((PsiMember)referent).getName(); - final PsiClass containingClass = PsiTreeUtil.getParentOfType(reference, PsiClass.class); - if (containingClass != null) { - foundMemberByName |= containingClass.findFieldByName(memberName, true) != null; - foundMemberByName |= containingClass.findMethodsByName(memberName, true).length > 0; - } - } - if (!foundMemberByName) { - try { - qualifierExpression.delete(); - } - catch (IncorrectOperationException e) { - LOG.error(e); - } - } - } - } } - reference.putUserData(TEMP_REFERENT_USER_DATA, null); } - super.visitReferenceElement(reference); + finally { + super.visitReferenceElement(reference); + } } }); } diff --git a/java/java-impl/src/com/intellij/refactoring/safeDelete/usageInfo/SafeDeleteExtendsClassUsageInfo.java b/java/java-impl/src/com/intellij/refactoring/safeDelete/usageInfo/SafeDeleteExtendsClassUsageInfo.java index d11352fed71d..6d7f6c586875 100644 --- a/java/java-impl/src/com/intellij/refactoring/safeDelete/usageInfo/SafeDeleteExtendsClassUsageInfo.java +++ b/java/java-impl/src/com/intellij/refactoring/safeDelete/usageInfo/SafeDeleteExtendsClassUsageInfo.java @@ -18,6 +18,7 @@ package com.intellij.refactoring.safeDelete.usageInfo; import com.intellij.openapi.diagnostic.Logger; import com.intellij.psi.*; import com.intellij.psi.util.TypeConversionUtil; +import com.intellij.util.ArrayUtilRt; import com.intellij.util.IncorrectOperationException; /** @@ -50,15 +51,19 @@ public class SafeDeleteExtendsClassUsageInfo extends SafeDeleteReferenceUsageInf if (extendsList != null) { final PsiClassType[] referenceTypes = extendsList.getReferencedTypes(); final PsiReferenceList listToAddExtends = refClass.isInterface() == myExtendingClass.isInterface() ? myExtendingClass.getExtendsList() : extendingImplementsList; + final PsiClassType[] existingRefTypes = listToAddExtends.getReferencedTypes(); for (PsiClassType referenceType : referenceTypes) { + if (ArrayUtilRt.find(existingRefTypes, referenceType) > -1) continue; listToAddExtends.add(elementFactory.createReferenceElementByType((PsiClassType)mySubstitutor.substitute(referenceType))); } } final PsiReferenceList implementsList = refClass.getImplementsList(); if (implementsList != null) { - final PsiClassType[] referenceTypes = implementsList.getReferencedTypes(); + final PsiClassType[] existingRefTypes = extendingImplementsList.getReferencedTypes(); + PsiClassType[] referenceTypes = implementsList.getReferencedTypes(); for (PsiClassType referenceType : referenceTypes) { + if (ArrayUtilRt.find(existingRefTypes, referenceType) > -1) continue; extendingImplementsList.add(elementFactory.createReferenceElementByType((PsiClassType)mySubstitutor.substitute(referenceType))); } } diff --git a/java/java-psi-api/src/com/intellij/psi/util/PsiTypesUtil.java b/java/java-psi-api/src/com/intellij/psi/util/PsiTypesUtil.java index 43890225a21c..d770f131a608 100644 --- a/java/java-psi-api/src/com/intellij/psi/util/PsiTypesUtil.java +++ b/java/java-psi-api/src/com/intellij/psi/util/PsiTypesUtil.java @@ -184,4 +184,59 @@ public class PsiTypesUtil { } return null; } + + @Nullable + public static PsiType getExpectedTypeByParent(PsiExpression methodCall) { + final PsiElement parent = PsiUtil.skipParenthesizedExprUp(methodCall.getParent()); + if (parent instanceof PsiVariable) { + if (checkSameExpression(methodCall, ((PsiVariable)parent).getInitializer())) { + return ((PsiVariable)parent).getType(); + } + } + else if (parent instanceof PsiAssignmentExpression) { + if (checkSameExpression(methodCall, ((PsiAssignmentExpression)parent).getRExpression())) { + return ((PsiAssignmentExpression)parent).getLExpression().getType(); + } + } + else if (parent instanceof PsiIfStatement) { + if (checkSameExpression(methodCall, ((PsiIfStatement)parent).getCondition())) { + return PsiType.BOOLEAN.getBoxedType(parent); + } + } + else if (parent instanceof PsiWhileStatement) { + if (checkSameExpression(methodCall, ((PsiWhileStatement)parent).getCondition())) { + return PsiType.BOOLEAN.getBoxedType(parent); + } + } + else if (parent instanceof PsiForStatement) { + if (checkSameExpression(methodCall, ((PsiForStatement)parent).getCondition())) { + return PsiType.BOOLEAN.getBoxedType(parent); + } + } + else if (parent instanceof PsiDoWhileStatement) { + if (checkSameExpression(methodCall, ((PsiDoWhileStatement)parent).getCondition())) { + return PsiType.BOOLEAN.getBoxedType(parent); + } + } + else if (parent instanceof PsiTypeCastExpression) { + return ((PsiTypeCastExpression)parent).getType(); + } + else if (parent instanceof PsiReturnStatement) { + final PsiLambdaExpression lambdaExpression = PsiTreeUtil.getParentOfType(parent, PsiLambdaExpression.class); + if (lambdaExpression != null) { + return LambdaUtil.getFunctionalInterfaceReturnType(lambdaExpression.getFunctionalInterfaceType()); + } + else { + PsiMethod method = PsiTreeUtil.getParentOfType(parent, PsiMethod.class); + if (method != null) { + return method.getReturnType(); + } + } + } + return null; + } + + private static boolean checkSameExpression(PsiExpression templateExpr, final PsiExpression expression) { + return templateExpr.equals(PsiUtil.skipParenthesizedExprDown(expression)); + } } diff --git a/java/java-psi-api/src/com/intellij/psi/util/PsiUtil.java b/java/java-psi-api/src/com/intellij/psi/util/PsiUtil.java index 49fbfec70d4c..b0f7d453363a 100644 --- a/java/java-psi-api/src/com/intellij/psi/util/PsiUtil.java +++ b/java/java-psi-api/src/com/intellij/psi/util/PsiUtil.java @@ -466,7 +466,8 @@ public final class PsiUtil extends PsiUtilCore { final PsiParameter[] parms = method.getParameterList().getParameters(); if (args.length < parms.length - 1) return ApplicabilityLevel.NOT_APPLICABLE; - final boolean isRaw = isRawSubstitutor(method, substitutorForMethod); + final PsiClass containingClass = method.getContainingClass(); + final boolean isRaw = containingClass != null && isRawSubstitutor(containingClass, substitutorForMethod); if (!areFirstArgumentsApplicable(args, parms, languageLevel, substitutorForMethod, isRaw)) return ApplicabilityLevel.NOT_APPLICABLE; if (args.length == parms.length) { if (parms.length == 0) return ApplicabilityLevel.FIXED_ARITY; diff --git a/java/java-psi-impl/src/com/intellij/psi/impl/source/PsiTypeElementImpl.java b/java/java-psi-impl/src/com/intellij/psi/impl/source/PsiTypeElementImpl.java index 4c837556371a..cc46b4bd5cd0 100644 --- a/java/java-psi-impl/src/com/intellij/psi/impl/source/PsiTypeElementImpl.java +++ b/java/java-psi-impl/src/com/intellij/psi/impl/source/PsiTypeElementImpl.java @@ -16,11 +16,13 @@ package com.intellij.psi.impl.source; import com.intellij.lang.ASTNode; -import com.intellij.openapi.diagnostic.Logger; import com.intellij.psi.*; import com.intellij.psi.impl.PsiImplUtil; import com.intellij.psi.impl.source.codeStyle.CodeEditUtil; -import com.intellij.psi.impl.source.tree.*; +import com.intellij.psi.impl.source.tree.CompositePsiElement; +import com.intellij.psi.impl.source.tree.ElementType; +import com.intellij.psi.impl.source.tree.JavaElementType; +import com.intellij.psi.impl.source.tree.TreeElement; import com.intellij.psi.scope.PsiScopeProcessor; import com.intellij.psi.tree.IElementType; import com.intellij.psi.util.PsiTreeUtil; @@ -36,8 +38,6 @@ import org.jetbrains.annotations.Nullable; import java.util.List; public class PsiTypeElementImpl extends CompositePsiElement implements PsiTypeElement { - private static final Logger LOG = Logger.getInstance("#com.intellij.psi.impl.source.PsiTypeElementImpl"); - private volatile PsiType myCachedType = null; @SuppressWarnings({"UnusedDeclaration"}) @@ -120,22 +120,16 @@ public class PsiTypeElementImpl extends CompositePsiElement implements PsiTypeEl if (PsiUtil.isJavaToken(child, JavaTokenType.QUEST)) { assert type == null : this; - PsiElement next = PsiTreeUtil.skipSiblingsForward(child, PsiComment.class, PsiWhiteSpace.class); - if (next == null) { - type = PsiWildcardType.createUnbounded(getManager()); + PsiElement boundKind = PsiTreeUtil.skipSiblingsForward(child, PsiComment.class, PsiWhiteSpace.class); + PsiElement boundType = PsiTreeUtil.skipSiblingsForward(boundKind, PsiComment.class, PsiWhiteSpace.class); + if (PsiUtil.isJavaToken(boundKind, JavaTokenType.EXTENDS_KEYWORD) && boundType instanceof PsiTypeElement) { + type = PsiWildcardType.createExtends(getManager(), ((PsiTypeElement)boundType).getType()); + } + else if (PsiUtil.isJavaToken(boundKind, JavaTokenType.SUPER_KEYWORD) && boundType instanceof PsiTypeElement) { + type = PsiWildcardType.createSuper(getManager(), ((PsiTypeElement)boundType).getType()); } else { - PsiElement bound = PsiTreeUtil.skipSiblingsForward(next, PsiComment.class, PsiWhiteSpace.class); - if (PsiUtil.isJavaToken(next, JavaTokenType.EXTENDS_KEYWORD) && bound instanceof PsiTypeElement) { - type = PsiWildcardType.createExtends(getManager(), ((PsiTypeElement)bound).getType()); - } - else if (PsiUtil.isJavaToken(next, JavaTokenType.SUPER_KEYWORD) && bound instanceof PsiTypeElement) { - type = PsiWildcardType.createSuper(getManager(), ((PsiTypeElement)bound).getType()); - } - else { - LOG.error("next=" + next + " bound=" + bound + ": " + this); - type = PsiWildcardType.createUnbounded(getManager()); - } + type = PsiWildcardType.createUnbounded(getManager()); } PsiAnnotation[] array = ContainerUtil.copyAndClear(annotations, PsiAnnotation.ARRAY_FACTORY, true); type = ((PsiWildcardType)type).annotate(array); diff --git a/java/java-psi-impl/src/com/intellij/psi/impl/source/resolve/PsiResolveHelperImpl.java b/java/java-psi-impl/src/com/intellij/psi/impl/source/resolve/PsiResolveHelperImpl.java index 1cf2d419d97b..c9fbfbf60ded 100644 --- a/java/java-psi-impl/src/com/intellij/psi/impl/source/resolve/PsiResolveHelperImpl.java +++ b/java/java-psi-impl/src/com/intellij/psi/impl/source/resolve/PsiResolveHelperImpl.java @@ -34,10 +34,7 @@ import com.intellij.psi.scope.processor.MethodCandidatesProcessor; import com.intellij.psi.scope.processor.MethodResolverProcessor; import com.intellij.psi.scope.util.PsiScopesUtil; import com.intellij.psi.search.GlobalSearchScope; -import com.intellij.psi.util.InheritanceUtil; -import com.intellij.psi.util.PsiTreeUtil; -import com.intellij.psi.util.PsiUtil; -import com.intellij.psi.util.TypeConversionUtil; +import com.intellij.psi.util.*; import com.intellij.util.ArrayUtil; import com.intellij.util.IncorrectOperationException; import com.intellij.util.containers.HashMap; @@ -1015,88 +1012,50 @@ public class PsiResolveHelperImpl implements PsiResolveHelper { PsiSubstitutor substitutor, ParameterTypeInferencePolicy policy) { Pair constraint = null; - PsiType expectedType = null; + PsiType expectedType = PsiTypesUtil.getExpectedTypeByParent(methodCall); - if (parent instanceof PsiVariable) { - if (methodCall.equals(PsiUtil.skipParenthesizedExprDown(((PsiVariable)parent).getInitializer()))) { - expectedType = ((PsiVariable)parent).getType(); - } - } - else if (parent instanceof PsiAssignmentExpression) { - if (methodCall.equals(PsiUtil.skipParenthesizedExprDown(((PsiAssignmentExpression)parent).getRExpression()))) { - expectedType = ((PsiAssignmentExpression)parent).getLExpression().getType(); - } - } - else if (parent instanceof PsiIfStatement) { - if (methodCall.equals(PsiUtil.skipParenthesizedExprDown(((PsiIfStatement)parent).getCondition()))) { - expectedType = PsiType.BOOLEAN.getBoxedType(parent); - } - } - else if (parent instanceof PsiWhileStatement) { - if (methodCall.equals(PsiUtil.skipParenthesizedExprDown(((PsiWhileStatement)parent).getCondition()))) { - expectedType = PsiType.BOOLEAN.getBoxedType(parent); - } - } - else if (parent instanceof PsiForStatement) { - if (methodCall.equals(PsiUtil.skipParenthesizedExprDown(((PsiForStatement)parent).getCondition()))) { - expectedType = PsiType.BOOLEAN.getBoxedType(parent); - } - } - else if (parent instanceof PsiDoWhileStatement) { - if (methodCall.equals(PsiUtil.skipParenthesizedExprDown(((PsiDoWhileStatement)parent).getCondition()))) { - expectedType = PsiType.BOOLEAN.getBoxedType(parent); - } - } - else if (parent instanceof PsiReturnStatement) { - final PsiLambdaExpression lambdaExpression = PsiTreeUtil.getParentOfType(parent, PsiLambdaExpression.class); - if (lambdaExpression != null) { - expectedType = LambdaUtil.getFunctionalInterfaceReturnType(lambdaExpression.getFunctionalInterfaceType()); - if (expectedType == null) { + if (expectedType == null) { + if (parent instanceof PsiReturnStatement) { + final PsiLambdaExpression lambdaExpression = PsiTreeUtil.getParentOfType(parent, PsiLambdaExpression.class); + if (lambdaExpression != null) { return getFailedInferenceConstraint(typeParameter); } - } else { - PsiMethod method = PsiTreeUtil.getParentOfType(parent, PsiMethod.class); - if (method != null) { - expectedType = method.getReturnType(); - } } - } - else if (parent instanceof PsiExpressionList) { - final PsiElement pParent = parent.getParent(); - if (pParent instanceof PsiCallExpression && parent.equals(((PsiCallExpression)pParent).getArgumentList())) { - constraint = policy.inferTypeConstraintFromCallContext(methodCall, (PsiExpressionList)parent, (PsiCallExpression)pParent, typeParameter); - if (constraint == null && PsiUtil.isLanguageLevel8OrHigher(methodCall)) { - constraint = graphInferenceFromCallContext(methodCall, typeParameter, (PsiCallExpression)pParent); - if (constraint != null) { - final PsiType constraintFirst = constraint.getFirst(); - if (constraintFirst == null || constraintFirst.equalsToText(CommonClassNames.JAVA_LANG_OBJECT)) { - constraint = null; + else if (parent instanceof PsiExpressionList) { + final PsiElement pParent = parent.getParent(); + if (pParent instanceof PsiCallExpression && parent.equals(((PsiCallExpression)pParent).getArgumentList())) { + constraint = policy.inferTypeConstraintFromCallContext(methodCall, (PsiExpressionList)parent, (PsiCallExpression)pParent, typeParameter); + if (constraint == null && PsiUtil.isLanguageLevel8OrHigher(methodCall)) { + constraint = graphInferenceFromCallContext(methodCall, typeParameter, (PsiCallExpression)pParent); + if (constraint != null) { + final PsiType constraintFirst = constraint.getFirst(); + if (constraintFirst == null || constraintFirst.equalsToText(CommonClassNames.JAVA_LANG_OBJECT)) { + constraint = null; + } } } } - } - } else if (parent instanceof PsiLambdaExpression) { - expectedType = ourGraphGuard.doPreventingRecursion(methodCall, true, new Computable() { - @Override - public PsiType compute() { - return LambdaUtil.getFunctionalInterfaceReturnType(((PsiLambdaExpression)parent).getFunctionalInterfaceType()); - } - }); - if (expectedType == null) { - return null; - } - } else if (parent instanceof PsiTypeCastExpression) { - expectedType = ((PsiTypeCastExpression)parent).getType(); - } else if (parent instanceof PsiConditionalExpression) { - if (PsiUtil.isLanguageLevel8OrHigher(parent)) { - try { - final Pair pair = inferFromConditionalExpression(parent, methodCall, typeParameter, substitutor, policy); - if (pair != null) { - return pair; + } else if (parent instanceof PsiLambdaExpression) { + expectedType = ourGraphGuard.doPreventingRecursion(methodCall, true, new Computable() { + @Override + public PsiType compute() { + return LambdaUtil.getFunctionalInterfaceReturnType(((PsiLambdaExpression)parent).getFunctionalInterfaceType()); } + }); + if (expectedType == null) { + return null; } - finally { - GraphInferencePolicy.forget(parent); + } else if (parent instanceof PsiConditionalExpression) { + if (PsiUtil.isLanguageLevel8OrHigher(parent)) { + try { + final Pair pair = inferFromConditionalExpression(parent, methodCall, typeParameter, substitutor, policy); + if (pair != null) { + return pair; + } + } + finally { + GraphInferencePolicy.forget(parent); + } } } } @@ -1196,6 +1155,10 @@ public class PsiResolveHelperImpl implements PsiResolveHelper { return result; } + private static boolean checkSameExpression(PsiExpression templateExpr, final PsiExpression expression) { + return templateExpr.equals(PsiUtil.skipParenthesizedExprDown(expression)); + } + private static Pair inferExceptionConstrains(PsiTypeParameter typeParameter, PsiExpression expression, PsiMethod method, diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting/QualifiedThisSuper.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting/QualifiedThisSuper.java index cba08cdf3f99..76336cd0090a 100644 --- a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting/QualifiedThisSuper.java +++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting/QualifiedThisSuper.java @@ -15,3 +15,10 @@ class R { System.out.println(Z.super.toString()); } } + +class W { + static String some = ""; + static void m() { + synchronized (some.this) { } + } +} diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/genericsHighlighting/IDEA104992.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/genericsHighlighting/IDEA104992.java new file mode 100644 index 000000000000..3798c7058401 --- /dev/null +++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/genericsHighlighting/IDEA104992.java @@ -0,0 +1,17 @@ +import java.util.Collection; +import java.util.Set; + +class FooObject {} +class FooId {} + +interface Bar { + > T get(I key); + > Collection get(Collection keys); +} + +public class Target { + void foo(Bar bar) { + final Set> keys = null; + final Collection values = bar.get(keys); + } +} \ No newline at end of file diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/addSingleStaticImport/DisabledInsideParameterizedReference.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/addSingleStaticImport/DisabledInsideParameterizedReference.java new file mode 100644 index 000000000000..b349ea73b377 --- /dev/null +++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/addSingleStaticImport/DisabledInsideParameterizedReference.java @@ -0,0 +1,6 @@ +import foo.*; +class Class2 { + public static void main(String[] args) { + Class1.foo(); + } +} diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/addSingleStaticImport/InsideParameterizedReference.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/addSingleStaticImport/InsideParameterizedReference.java new file mode 100644 index 000000000000..85aa9ae8521e --- /dev/null +++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/addSingleStaticImport/InsideParameterizedReference.java @@ -0,0 +1,6 @@ +import foo.*; +class Class2 { + public static void main(String[] args) { + new Class1.Inner2(); + } +} diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/addSingleStaticImport/InsideParameterizedReferenceInsideParameterizedReference.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/addSingleStaticImport/InsideParameterizedReferenceInsideParameterizedReference.java new file mode 100644 index 000000000000..cf579dda8629 --- /dev/null +++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/addSingleStaticImport/InsideParameterizedReferenceInsideParameterizedReference.java @@ -0,0 +1,6 @@ +import foo.*; +class Class2 { + public static void main(String[] args) { + new Class1.Inner2ner1>(); + } +} diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/addSingleStaticImport/InsideParameterizedReferenceInsideParameterizedReference_after.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/addSingleStaticImport/InsideParameterizedReferenceInsideParameterizedReference_after.java new file mode 100644 index 000000000000..9a2ff4d54a98 --- /dev/null +++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/addSingleStaticImport/InsideParameterizedReferenceInsideParameterizedReference_after.java @@ -0,0 +1,9 @@ +import foo.*; + +import static foo.Class1.Inner1; + +class Class2 { + public static void main(String[] args) { + new Class1.Inner2(); + } +} diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/addSingleStaticImport/InsideParameterizedReference_after.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/addSingleStaticImport/InsideParameterizedReference_after.java new file mode 100644 index 000000000000..6f57f14f5fa4 --- /dev/null +++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/addSingleStaticImport/InsideParameterizedReference_after.java @@ -0,0 +1,9 @@ +import foo.*; + +import static foo.Class1.Inner2; + +class Class2 { + public static void main(String[] args) { + new Inner2(); + } +} diff --git a/java/java-tests/testData/inspection/redundantCast/generics/BoxingInConditional/expected.xml b/java/java-tests/testData/inspection/redundantCast/generics/BoxingInConditional/expected.xml new file mode 100644 index 000000000000..3bf1252e596b --- /dev/null +++ b/java/java-tests/testData/inspection/redundantCast/generics/BoxingInConditional/expected.xml @@ -0,0 +1,9 @@ + + + + Test.java + 8 + Redundant type cast + Casting <code>2</code> to <code>Integer</code> is redundant + + diff --git a/java/java-tests/testData/inspection/redundantCast/generics/BoxingInConditional/src/Test.java b/java/java-tests/testData/inspection/redundantCast/generics/BoxingInConditional/src/Test.java new file mode 100644 index 000000000000..995072a79416 --- /dev/null +++ b/java/java-tests/testData/inspection/redundantCast/generics/BoxingInConditional/src/Test.java @@ -0,0 +1,10 @@ +//This is a test for JDK_15 LanguageLevel +public class Test { + private Integer foo(String s, Integer i) { + return s == null ? i : (Integer)2; + } + + private int foo1(String s, Integer i) { + return s == null ? i : (Integer)2; + } +} \ No newline at end of file diff --git a/java/java-tests/testData/refactoring/safeDelete/UsageInExtendsList.java b/java/java-tests/testData/refactoring/safeDelete/UsageInExtendsList.java new file mode 100644 index 000000000000..04c1fba3bdf7 --- /dev/null +++ b/java/java-tests/testData/refactoring/safeDelete/UsageInExtendsList.java @@ -0,0 +1,3 @@ +nterface Foo {} +interface Bar extends Foo {} +class FooBarImpl implements Foo, Bar {} diff --git a/java/java-tests/testData/refactoring/safeDelete/UsageInExtendsList_after.java b/java/java-tests/testData/refactoring/safeDelete/UsageInExtendsList_after.java new file mode 100644 index 000000000000..c1c4f899abe5 --- /dev/null +++ b/java/java-tests/testData/refactoring/safeDelete/UsageInExtendsList_after.java @@ -0,0 +1,3 @@ +nterface Foo {} + +class FooBarImpl implements Foo {} diff --git a/java/java-tests/testSrc/com/intellij/codeInsight/daemon/GenericsHighlightingTest.java b/java/java-tests/testSrc/com/intellij/codeInsight/daemon/GenericsHighlightingTest.java index 0527f38a76e1..e6c8ec1c5083 100644 --- a/java/java-tests/testSrc/com/intellij/codeInsight/daemon/GenericsHighlightingTest.java +++ b/java/java-tests/testSrc/com/intellij/codeInsight/daemon/GenericsHighlightingTest.java @@ -207,6 +207,7 @@ public class GenericsHighlightingTest extends LightDaemonAnalyzerTestCase { public void testIDEA103760(){ doTest5(false); } public void testIDEA105846(){ doTest5(false); } public void testIDEA105695(){ doTest5(false); } + public void testIDEA104992(){ doTest5(false); } public void testWildcardsOnRawTypes() { doTest5(false); } public void testDisableWithinBoundsCheckForSuperWildcards() { diff --git a/java/java-tests/testSrc/com/intellij/codeInsight/daemon/LightAdvHighlightingJdk6Test.java b/java/java-tests/testSrc/com/intellij/codeInsight/daemon/LightAdvHighlightingJdk6Test.java index 0e400c19cb0e..c31cce339a0b 100644 --- a/java/java-tests/testSrc/com/intellij/codeInsight/daemon/LightAdvHighlightingJdk6Test.java +++ b/java/java-tests/testSrc/com/intellij/codeInsight/daemon/LightAdvHighlightingJdk6Test.java @@ -28,24 +28,19 @@ import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; /** - * This class is for "lightweight" tests only, i.e. those which can run inside default light project set up - * For "heavyweight" tests use AdvHighlightingTest + * This class is for "lightweight" tests only, i.e. those which can run inside default light project set up. + * For "heavyweight" tests use AdvHighlightingTest. */ public class LightAdvHighlightingJdk6Test extends LightDaemonAnalyzerTestCase { @NonNls static final String BASE_PATH = "/codeInsight/daemonCodeAnalyzer/advHighlighting6"; private void doTest(boolean checkWarnings, boolean checkInfos, Class... classes) { - setLanguageLevel(LanguageLevel.JDK_1_6); + setLanguageLevel(LanguageLevel.JDK_1_6); ((JavaVersionServiceImpl)JavaVersionService.getInstance()).setTestVersion(JavaSdkVersion.JDK_1_6, myTestRootDisposable); enableInspectionTools(classes); doTest(BASE_PATH + "/" + getTestName(false) + ".java", checkWarnings, checkInfos); } - private void doTest(boolean checkWarnings, boolean checkWeakWarnings, boolean checkInfos, Class... classes) { - enableInspectionTools(classes); - doTest(BASE_PATH + "/" + getTestName(false) + ".java", checkWarnings, checkWeakWarnings, checkInfos); - } - @NotNull @Override protected LocalInspectionTool[] configureLocalInspectionTools() { @@ -57,6 +52,6 @@ public class LightAdvHighlightingJdk6Test extends LightDaemonAnalyzerTestCase { }; } - public void testJavacQuirks() throws Exception { setLanguageLevel(LanguageLevel.JDK_1_6); doTest(true, false); } - public void testMethodReturnTypeSubstitutability() throws Exception { setLanguageLevel(LanguageLevel.JDK_1_6); doTest(true, false); } + public void testJavacQuirks() { setLanguageLevel(LanguageLevel.JDK_1_6); doTest(true, false); } + public void testMethodReturnTypeSubstitutability() { setLanguageLevel(LanguageLevel.JDK_1_6); doTest(true, false); } } diff --git a/java/java-tests/testSrc/com/intellij/codeInsight/daemon/LightAdvHighlightingTest.java b/java/java-tests/testSrc/com/intellij/codeInsight/daemon/LightAdvHighlightingTest.java index f68f93c16ee6..b1217ddec696 100644 --- a/java/java-tests/testSrc/com/intellij/codeInsight/daemon/LightAdvHighlightingTest.java +++ b/java/java-tests/testSrc/com/intellij/codeInsight/daemon/LightAdvHighlightingTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2012 JetBrains s.r.o. + * Copyright 2000-2013 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. @@ -241,7 +241,7 @@ public class LightAdvHighlightingTest extends LightDaemonAnalyzerTestCase { }; point.registerExtension(extension); - + try { UnusedDeclarationInspection deadCodeInspection = new UnusedDeclarationInspection(); enableInspectionTool(deadCodeInspection); diff --git a/java/java-tests/testSrc/com/intellij/codeInsight/intention/AddSingleStaticImportActionTest.java b/java/java-tests/testSrc/com/intellij/codeInsight/intention/AddSingleStaticImportActionTest.java index d7bacf264398..9ecdd1cfa79e 100644 --- a/java/java-tests/testSrc/com/intellij/codeInsight/intention/AddSingleStaticImportActionTest.java +++ b/java/java-tests/testSrc/com/intellij/codeInsight/intention/AddSingleStaticImportActionTest.java @@ -30,6 +30,45 @@ public class AddSingleStaticImportActionTest extends JavaCodeInsightFixtureTestC myFixture.checkResultByFile(getTestName(false) + "_after.java"); } + public void testInsideParameterizedReference() { + myFixture.addClass("package foo; " + + "public class Class1 {" + + " public static class Inner1 {}\n" + + " public static class Inner2 {}" + + "}"); + myFixture.configureByFile(getTestName(false) + ".java"); + + final IntentionAction intentionAction = myFixture.findSingleIntention("Add static import for 'foo.Class1.Inner2'"); + assertNotNull(intentionAction); + myFixture.launchAction(intentionAction); + myFixture.checkResultByFile(getTestName(false) + "_after.java"); + } + + public void testInsideParameterizedReferenceInsideParameterizedReference() { + myFixture.addClass("package foo; " + + "public class Class1 {" + + " public static class Inner1 {}\n" + + " public static class Inner2 {}" + + "}"); + myFixture.configureByFile(getTestName(false) + ".java"); + + final IntentionAction intentionAction = myFixture.findSingleIntention("Add static import for 'foo.Class1.Inner1'"); + assertNotNull(intentionAction); + myFixture.launchAction(intentionAction); + myFixture.checkResultByFile(getTestName(false) + "_after.java"); + } + + public void testDisabledInsideParameterizedReference() { + myFixture.addClass("package foo; " + + "public class Class1 {" + + " public static T foo(){return null;}\n" + + "}"); + myFixture.configureByFile(getTestName(false) + ".java"); + + final IntentionAction intentionAction = myFixture.getAvailableIntention("Add static import for 'foo.Class1.foo'"); + assertNull(intentionAction); + } + @Override protected String getTestDataPath() { diff --git a/java/java-tests/testSrc/com/intellij/codeInsight/psi/AnnotatedTypeTest.groovy b/java/java-tests/testSrc/com/intellij/codeInsight/psi/AnnotatedTypeTest.groovy index cbaa56d3ec94..f186f9e8f5c8 100644 --- a/java/java-tests/testSrc/com/intellij/codeInsight/psi/AnnotatedTypeTest.groovy +++ b/java/java-tests/testSrc/com/intellij/codeInsight/psi/AnnotatedTypeTest.groovy @@ -19,7 +19,7 @@ import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import com.intellij.testFramework.LightIdeaTestCase -@SuppressWarnings(["GrUnresolvedAccess"]) +@SuppressWarnings(["GrUnresolvedAccess", "GroovyAssignabilityCheck"]) class AnnotatedTypeTest extends LightIdeaTestCase { public void testTypeComposition() { @@ -55,6 +55,9 @@ class E2 extends Exception { } psi = javaFacade.elementFactory.createStatementFromText("@A java.lang.@TA(1) String s", context) assertEquals("@TA(1) String", psi.declaredElements[0].type.presentableText) + + psi = javaFacade.elementFactory.createStatementFromText("Collection s", context) + assertEquals("Collection", psi.declaredElements[0].type.presentableText) } } diff --git a/java/java-tests/testSrc/com/intellij/codeInspection/RedundantCast15Test.java b/java/java-tests/testSrc/com/intellij/codeInspection/RedundantCast15Test.java index db20eca0956a..0fe49b1a5435 100644 --- a/java/java-tests/testSrc/com/intellij/codeInspection/RedundantCast15Test.java +++ b/java/java-tests/testSrc/com/intellij/codeInspection/RedundantCast15Test.java @@ -24,6 +24,8 @@ public class RedundantCast15Test extends InspectionTestCase { public void testBoxingInRef() throws Exception { doTest(); } + public void testBoxingInConditional() throws Exception { doTest(); } + public void testInference1() throws Exception { doTest(); } public void testInference2() throws Exception { doTest(); } diff --git a/java/java-tests/testSrc/com/intellij/refactoring/SafeDeleteTest.java b/java/java-tests/testSrc/com/intellij/refactoring/SafeDeleteTest.java index 9c1cf4915312..27d78094281e 100644 --- a/java/java-tests/testSrc/com/intellij/refactoring/SafeDeleteTest.java +++ b/java/java-tests/testSrc/com/intellij/refactoring/SafeDeleteTest.java @@ -65,6 +65,10 @@ public class SafeDeleteTest extends MultiFileTestCase { doTest("IFoo"); } + public void testUsageInExtendsList() throws Exception { + doSingleFileTest(); + } + public void testParameterInHierarchy() throws Exception { myDoCompare = false; doTest("C2"); diff --git a/java/openapi/src/com/intellij/psi/util/RedundantCastUtil.java b/java/openapi/src/com/intellij/psi/util/RedundantCastUtil.java index 32021974bbe1..2852584db636 100644 --- a/java/openapi/src/com/intellij/psi/util/RedundantCastUtil.java +++ b/java/openapi/src/com/intellij/psi/util/RedundantCastUtil.java @@ -383,7 +383,9 @@ public class RedundantCastUtil { PsiElement parent = typeCast.getParent(); if (parent instanceof PsiConditionalExpression) { //branches need to be of the same type - if (!Comparing.equal(operand.getType(), ((PsiConditionalExpression)parent).getType())) { + final PsiType operandType = operand.getType(); + final PsiType conditionalType = ((PsiConditionalExpression)parent).getType(); + if (!Comparing.equal(operandType, conditionalType)) { if (!PsiUtil.isLanguageLevel5OrHigher(typeCast)) { return; } @@ -578,6 +580,12 @@ public class RedundantCastUtil { if (firstOperand != null && otherOperand != null && wrapperCastChangeSemantics(firstOperand, otherOperand, operand)) { return true; } + } else if (parent instanceof PsiConditionalExpression) { + if (opType instanceof PsiPrimitiveType && !(((PsiConditionalExpression)parent).getType() instanceof PsiPrimitiveType)) { + if (PsiPrimitiveType.getUnboxedType(PsiTypesUtil.getExpectedTypeByParent((PsiExpression)parent)) != null) { + return true; + } + } } return false; } diff --git a/lib/gson-2.2.1.jar b/lib/gson-2.2.1.jar deleted file mode 100644 index 93ac6d70b3ee..000000000000 Binary files a/lib/gson-2.2.1.jar and /dev/null differ diff --git a/lib/gson-2.2.3.jar b/lib/gson-2.2.3.jar new file mode 100644 index 000000000000..a4e18be67924 Binary files /dev/null and b/lib/gson-2.2.3.jar differ diff --git a/lib/src/gson-2.2.1-sources.jar b/lib/src/gson-2.2.1-sources.jar deleted file mode 100644 index fb9538e5e6fc..000000000000 Binary files a/lib/src/gson-2.2.1-sources.jar and /dev/null differ diff --git a/lib/src/gson-2.2.3-sources.jar b/lib/src/gson-2.2.3-sources.jar new file mode 100644 index 000000000000..c7a01482831b Binary files /dev/null and b/lib/src/gson-2.2.3-sources.jar differ diff --git a/platform/core-api/src/com/intellij/openapi/roots/FileIndexFacade.java b/platform/core-api/src/com/intellij/openapi/roots/FileIndexFacade.java index 2f3b7dad1885..0fef33392218 100644 --- a/platform/core-api/src/com/intellij/openapi/roots/FileIndexFacade.java +++ b/platform/core-api/src/com/intellij/openapi/roots/FileIndexFacade.java @@ -37,16 +37,16 @@ public abstract class FileIndexFacade { return ServiceManager.getService(project, FileIndexFacade.class); } - public abstract boolean isInContent(VirtualFile file); - public abstract boolean isInSource(VirtualFile file); - public abstract boolean isInSourceContent(VirtualFile file); - public abstract boolean isInLibraryClasses(VirtualFile file); + public abstract boolean isInContent(@NotNull VirtualFile file); + public abstract boolean isInSource(@NotNull VirtualFile file); + public abstract boolean isInSourceContent(@NotNull VirtualFile file); + public abstract boolean isInLibraryClasses(@NotNull VirtualFile file); - public abstract boolean isInLibrarySource(VirtualFile file); - public abstract boolean isExcludedFile(VirtualFile file); + public abstract boolean isInLibrarySource(@NotNull VirtualFile file); + public abstract boolean isExcludedFile(@NotNull VirtualFile file); @Nullable - public abstract Module getModuleForFile(VirtualFile file); + public abstract Module getModuleForFile(@NotNull VirtualFile file); /** * Checks if file is an ancestor of baseDir and none of the files @@ -56,7 +56,7 @@ public abstract class FileIndexFacade { * @param child the child directory or file to check for ancestry. * @return true if it's a valid ancestor, false otherwise. */ - public abstract boolean isValidAncestor(final VirtualFile baseDir, final VirtualFile child); + public abstract boolean isValidAncestor(@NotNull VirtualFile baseDir, @NotNull VirtualFile child); public boolean shouldBeFound(GlobalSearchScope scope, VirtualFile virtualFile) { return (scope.isSearchOutsideRootModel() || isInContent(virtualFile) || isInLibrarySource(virtualFile)) && !virtualFile.getFileType().isBinary(); diff --git a/platform/core-impl/src/com/intellij/mock/MockFileIndexFacade.java b/platform/core-impl/src/com/intellij/mock/MockFileIndexFacade.java index aa6014021ac9..ee0f2bb45344 100644 --- a/platform/core-impl/src/com/intellij/mock/MockFileIndexFacade.java +++ b/platform/core-impl/src/com/intellij/mock/MockFileIndexFacade.java @@ -63,7 +63,7 @@ public class MockFileIndexFacade extends FileIndexFacade { } @Override - public boolean isInLibrarySource(VirtualFile file) { + public boolean isInLibrarySource(@NotNull VirtualFile file) { return false; } @@ -73,12 +73,12 @@ public class MockFileIndexFacade extends FileIndexFacade { } @Override - public Module getModuleForFile(VirtualFile file) { + public Module getModuleForFile(@NotNull VirtualFile file) { return myModule; } @Override - public boolean isValidAncestor(VirtualFile baseDir, VirtualFile child) { + public boolean isValidAncestor(@NotNull VirtualFile baseDir, @NotNull VirtualFile child) { return VfsUtilCore.isAncestor(baseDir, child, false); } diff --git a/platform/icons/src/actions/clean@2x_dark.png b/platform/icons/src/actions/clean@2x_dark.png index db8502021308..665aaf9799e3 100644 Binary files a/platform/icons/src/actions/clean@2x_dark.png and b/platform/icons/src/actions/clean@2x_dark.png differ diff --git a/platform/icons/src/actions/clean_dark.png b/platform/icons/src/actions/clean_dark.png index c07babe21e55..8f4381520196 100644 Binary files a/platform/icons/src/actions/clean_dark.png and b/platform/icons/src/actions/clean_dark.png differ diff --git a/platform/icons/src/process/stop.png b/platform/icons/src/process/stop.png index 0452dc983893..238d9409d9ac 100644 Binary files a/platform/icons/src/process/stop.png and b/platform/icons/src/process/stop.png differ diff --git a/platform/icons/src/process/stop@2x.png b/platform/icons/src/process/stop@2x.png index 4c00e4dd29ce..b2ea40e05e1b 100644 Binary files a/platform/icons/src/process/stop@2x.png and b/platform/icons/src/process/stop@2x.png differ diff --git a/platform/icons/src/process/stop@2x_dark.png b/platform/icons/src/process/stop@2x_dark.png new file mode 100644 index 000000000000..968f27d8bc91 Binary files /dev/null and b/platform/icons/src/process/stop@2x_dark.png differ diff --git a/platform/icons/src/process/stopHovered.png b/platform/icons/src/process/stopHovered.png index f696c690a536..266f8c61d93b 100644 Binary files a/platform/icons/src/process/stopHovered.png and b/platform/icons/src/process/stopHovered.png differ diff --git a/platform/icons/src/process/stopHovered@2x.png b/platform/icons/src/process/stopHovered@2x.png new file mode 100644 index 000000000000..64d50f5f2c25 Binary files /dev/null and b/platform/icons/src/process/stopHovered@2x.png differ diff --git a/platform/icons/src/process/stopHovered@2x_dark.png b/platform/icons/src/process/stopHovered@2x_dark.png index 4420fd2caa77..7d8a8f07463f 100644 Binary files a/platform/icons/src/process/stopHovered@2x_dark.png and b/platform/icons/src/process/stopHovered@2x_dark.png differ diff --git a/platform/icons/src/process/stopHovered_dark.png b/platform/icons/src/process/stopHovered_dark.png index 357c94012596..0f8441e30483 100644 Binary files a/platform/icons/src/process/stopHovered_dark.png and b/platform/icons/src/process/stopHovered_dark.png differ diff --git a/platform/icons/src/process/stop_dark.png b/platform/icons/src/process/stop_dark.png index 8d16ba2fd5a7..73cd52212705 100644 Binary files a/platform/icons/src/process/stop_dark.png and b/platform/icons/src/process/stop_dark.png differ diff --git a/platform/icons/src/webreferences/server.png b/platform/icons/src/webreferences/server.png index c1d353bde7ed..e5bf3d23bace 100644 Binary files a/platform/icons/src/webreferences/server.png and b/platform/icons/src/webreferences/server.png differ diff --git a/platform/icons/src/webreferences/server@2x.png b/platform/icons/src/webreferences/server@2x.png new file mode 100644 index 000000000000..743c146ebfed Binary files /dev/null and b/platform/icons/src/webreferences/server@2x.png differ diff --git a/platform/lang-api/src/com/intellij/openapi/projectRoots/JdkUtil.java b/platform/lang-api/src/com/intellij/openapi/projectRoots/JdkUtil.java index fc5d141aad57..15279968ff0d 100644 --- a/platform/lang-api/src/com/intellij/openapi/projectRoots/JdkUtil.java +++ b/platform/lang-api/src/com/intellij/openapi/projectRoots/JdkUtil.java @@ -164,7 +164,9 @@ public class JdkUtil { commandLine.setExePath(exePath); final ParametersList vmParametersList = javaParameters.getVMParametersList(); - commandLine.setEnvironment(javaParameters.getEnv()); + if (javaParameters.getEnv() != null) { + commandLine.getEnvironment().putAll(javaParameters.getEnv()); + } commandLine.setPassParentEnvironment(javaParameters.isPassParentEnvs()); final Class commandLineWrapper; diff --git a/platform/lang-impl/src/com/intellij/codeInspection/ui/InspectionResultsView.java b/platform/lang-impl/src/com/intellij/codeInspection/ui/InspectionResultsView.java index 6eba9a5d5207..4aa80ee686d4 100644 --- a/platform/lang-impl/src/com/intellij/codeInspection/ui/InspectionResultsView.java +++ b/platform/lang-impl/src/com/intellij/codeInspection/ui/InspectionResultsView.java @@ -503,9 +503,6 @@ public class InspectionResultsView extends JPanel implements Disposable, Occuren for (Tools currentTools : tools.values()) { final InspectionTool defaultTool = (InspectionTool)currentTools.getDefaultState().getTool(); final HighlightDisplayKey key = HighlightDisplayKey.find(defaultTool.getShortName()); - if (profile != null && !profile.isToolEnabled(key)) { - continue; //exclude disabled inspections from view - } for (ScopeToolState state : currentTools.getTools()) { final InspectionTool tool = (InspectionTool)state.getTool(); if (myProvider.checkReportedProblems(tool)) { diff --git a/platform/lang-impl/src/com/intellij/find/impl/livePreview/LivePreview.java b/platform/lang-impl/src/com/intellij/find/impl/livePreview/LivePreview.java index 803a7d19f227..541170c0471b 100644 --- a/platform/lang-impl/src/com/intellij/find/impl/livePreview/LivePreview.java +++ b/platform/lang-impl/src/com/intellij/find/impl/livePreview/LivePreview.java @@ -291,7 +291,11 @@ public class LivePreview extends DocumentAdapter implements ReplacementView.Dele final TextRange range = o.getPrimaryRange(); TextAttributes attributes = EditorColorsManager.getInstance().getGlobalScheme().getAttributes(EditorColors.TEXT_SEARCH_RESULT_ATTRIBUTES); - + if (range.getLength() == 0) { + attributes = attributes.clone(); + attributes.setEffectType(EffectType.BOXED); + attributes.setEffectColor(attributes.getBackgroundColor()); + } if (mySearchResults.isExcluded(o)) { highlightRange(range, strikout(attributes), myHighlighters); } else { diff --git a/platform/lang-impl/src/com/intellij/find/impl/livePreview/SearchResults.java b/platform/lang-impl/src/com/intellij/find/impl/livePreview/SearchResults.java index 7d623e5036cc..6399d6c69ed6 100644 --- a/platform/lang-impl/src/com/intellij/find/impl/livePreview/SearchResults.java +++ b/platform/lang-impl/src/com/intellij/find/impl/livePreview/SearchResults.java @@ -303,13 +303,16 @@ public class SearchResults implements DocumentListener { private void findInRange(TextRange r, Editor editor, FindModel findModel, ArrayList results) { VirtualFile virtualFile = FileDocumentManager.getInstance().getFile(editor.getDocument()); + CharSequence charSequence = editor.getDocument().getCharsSequence(); + int offset = r.getStartOffset(); + int maxOffset = Math.min(r.getEndOffset(), charSequence.length()); + FindManager findManager = FindManager.getInstance(getProject()); while (true) { - FindManager findManager = FindManager.getInstance(getProject()); FindResult result; try { - CharSequence bombedCharSequence = StringUtil.newBombedCharSequence(editor.getDocument().getCharsSequence(), 3000); + CharSequence bombedCharSequence = StringUtil.newBombedCharSequence(charSequence, 3000); result = findManager.findString(bombedCharSequence, offset, findModel, virtualFile); } catch(PatternSyntaxException e) { result = null; @@ -318,8 +321,17 @@ public class SearchResults implements DocumentListener { } if (result == null || !result.isStringFound()) break; int newOffset = result.getEndOffset(); - if (offset == newOffset || result.getEndOffset() > r.getEndOffset()) break; - offset = newOffset; + if (result.getEndOffset() > maxOffset) break; + if (offset == newOffset) { + if (offset < maxOffset - 1) { + offset++; + } else { + results.add(result); + break; + } + } else { + offset = newOffset; + } results.add(result); } } @@ -494,7 +506,7 @@ public class SearchResults implements DocumentListener { private LiveOccurrence firstOccurrenceAfterOffset(int offset) { LiveOccurrence afterCaret = null; for (LiveOccurrence occurrence : getOccurrences()) { - if (occurrence.getPrimaryRange().getStartOffset() >= offset) { + if (occurrence.getPrimaryRange().getStartOffset() >= offset && occurrence.getPrimaryRange().getEndOffset() > offset) { if (afterCaret == null || occurrence.getPrimaryRange().getStartOffset() < afterCaret.getPrimaryRange().getStartOffset() ) { afterCaret = occurrence; } diff --git a/platform/lang-impl/src/com/intellij/openapi/fileEditor/impl/text/PsiAwareTextEditorProvider.java b/platform/lang-impl/src/com/intellij/openapi/fileEditor/impl/text/PsiAwareTextEditorProvider.java index a38e9d5e5536..cbadd5b0fcac 100644 --- a/platform/lang-impl/src/com/intellij/openapi/fileEditor/impl/text/PsiAwareTextEditorProvider.java +++ b/platform/lang-impl/src/com/intellij/openapi/fileEditor/impl/text/PsiAwareTextEditorProvider.java @@ -142,15 +142,16 @@ public class PsiAwareTextEditorProvider extends TextEditorProvider { } } + @NotNull @Override - protected EditorWrapper createWrapperForEditor(final Editor editor) { + protected EditorWrapper createWrapperForEditor(@NotNull final Editor editor) { return new PsiAwareEditorWrapper(editor); } private final class PsiAwareEditorWrapper extends EditorWrapper { private final TextEditorBackgroundHighlighter myBackgroundHighlighter; - private PsiAwareEditorWrapper(final Editor editor) { + private PsiAwareEditorWrapper(@NotNull Editor editor) { super(editor); final Project project = editor.getProject(); myBackgroundHighlighter = project == null diff --git a/platform/lang-impl/src/com/intellij/psi/stubs/StubIndexImpl.java b/platform/lang-impl/src/com/intellij/psi/stubs/StubIndexImpl.java index 54fadd1786f9..2bef70bb802b 100644 --- a/platform/lang-impl/src/com/intellij/psi/stubs/StubIndexImpl.java +++ b/platform/lang-impl/src/com/intellij/psi/stubs/StubIndexImpl.java @@ -20,6 +20,7 @@ package com.intellij.psi.stubs; import com.intellij.openapi.application.ApplicationManager; +import com.intellij.openapi.application.ModalityState; import com.intellij.openapi.components.*; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.editor.Document; @@ -90,12 +91,14 @@ public class StubIndexImpl extends StubIndex implements ApplicationComponent, Pe else { final Throwable e = new Throwable(); // avoid direct forceRebuild as it produces dependency cycle (IDEA-105485) - ApplicationManager.getApplication().invokeLater(new Runnable() { + ApplicationManager.getApplication().invokeLater( + new Runnable() { @Override public void run() { forceRebuild(e); } - }); + }, ModalityState.NON_MODAL + ); } } dropUnregisteredIndices(); diff --git a/platform/platform-api/src/com/intellij/execution/configurations/GeneralCommandLine.java b/platform/platform-api/src/com/intellij/execution/configurations/GeneralCommandLine.java index 410cdfb06b7e..c49c42561748 100644 --- a/platform/platform-api/src/com/intellij/execution/configurations/GeneralCommandLine.java +++ b/platform/platform-api/src/com/intellij/execution/configurations/GeneralCommandLine.java @@ -48,7 +48,7 @@ public class GeneralCommandLine implements UserDataHolder { private String myExePath = null; private File myWorkDirectory = null; - private Map myEnvParams = null; + private final Map myEnvParams = ContainerUtil.newTroveMap(); private boolean myPassParentEnvironment = true; private final ParametersList myProgramParams = new ParametersList(); private Charset myCharset = CharsetToolkit.getDefaultSystemCharset(); @@ -93,40 +93,22 @@ public class GeneralCommandLine implements UserDataHolder { @NotNull public Map getEnvironment() { - return myEnvParams != null ? Collections.unmodifiableMap(myEnvParams) : Collections.emptyMap(); + return myEnvParams; } /** @deprecated use {@link #getEnvironment()} (to remove in IDEA 14) */ @SuppressWarnings("unused") public Map getEnvParams() { - return myEnvParams; + return getEnvironment(); } - public void setEnvironment(@Nullable Map envVars) { - if (envVars != null) { - if (myEnvParams == null) myEnvParams = ContainerUtil.newHashMap(); - myEnvParams.putAll(envVars); - } - } - - public void setEnvironment(@NotNull String name, @NotNull String value) { - if (myEnvParams == null) myEnvParams = ContainerUtil.newHashMap(); - myEnvParams.put(name, value); - } - - public void removeEnvironment(@NotNull String name) { - if (myEnvParams != null) { - myEnvParams.remove(name); - if (myEnvParams.isEmpty()) { - myEnvParams = null; - } - } - } - - /** @deprecated use {@link #setEnvironment(Map)} (to remove in IDEA 14) */ + /** @deprecated use {@link #getEnvironment()} (to remove in IDEA 14) */ @SuppressWarnings("unused") - public void setEnvParams(@Nullable final Map envParams) { - myEnvParams = envParams; + public void setEnvParams(@Nullable Map envParams) { + myEnvParams.clear(); + if (envParams != null) { + myEnvParams.putAll(envParams); + } } public void setPassParentEnvironment(boolean passParentEnvironment) { @@ -271,7 +253,7 @@ public class GeneralCommandLine implements UserDataHolder { environment.clear(); } - if (myEnvParams != null && !myEnvParams.isEmpty()) { + if (!myEnvParams.isEmpty()) { if (SystemInfo.isWindows) { THashMap envVars = new THashMap(CaseInsensitiveStringHashingStrategy.INSTANCE); envVars.putAll(environment); diff --git a/platform/platform-api/src/com/intellij/openapi/diff/DocumentsSynchonizer.java b/platform/platform-api/src/com/intellij/openapi/diff/DocumentsSynchronizer.java similarity index 79% rename from platform/platform-api/src/com/intellij/openapi/diff/DocumentsSynchonizer.java rename to platform/platform-api/src/com/intellij/openapi/diff/DocumentsSynchronizer.java index 5204ddfcaeb3..b0e48b756184 100644 --- a/platform/platform-api/src/com/intellij/openapi/diff/DocumentsSynchonizer.java +++ b/platform/platform-api/src/com/intellij/openapi/diff/DocumentsSynchronizer.java @@ -15,26 +15,29 @@ */ package com.intellij.openapi.diff; +import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.command.CommandProcessor; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.editor.Document; import com.intellij.openapi.editor.event.DocumentAdapter; import com.intellij.openapi.editor.event.DocumentEvent; import com.intellij.openapi.project.Project; +import org.jetbrains.annotations.NotNull; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; -abstract class DocumentsSynchonizer { +abstract class DocumentsSynchronizer { private static final Logger LOG = Logger.getInstance("#com.intellij.openapi.diff.DocumentsSynchonizer"); private Document myOriginal = null; private Document myCopy = null; private final Project myProject; - private boolean myDuringModification = false; + private volatile boolean myDuringModification = false; private int myAssignedCount = 0; private final DocumentAdapter myOriginalListener = new DocumentAdapter() { + @Override public void documentChanged(DocumentEvent e) { if (myDuringModification) return; onOriginalChanged(e, getCopy()); @@ -42,39 +45,47 @@ abstract class DocumentsSynchonizer { }; private final DocumentAdapter myCopyListener = new DocumentAdapter() { + @Override public void documentChanged(DocumentEvent e) { if (myDuringModification) return; onCopyChanged(e, getOriginal()); } }; private final PropertyChangeListener myROListener = new PropertyChangeListener() { + @Override public void propertyChange(PropertyChangeEvent evt) { if (Document.PROP_WRITABLE.equals(evt.getPropertyName())) getCopy().setReadOnly(!getOriginal().isWritable()); } }; - protected DocumentsSynchonizer(Project project) { + protected DocumentsSynchronizer(Project project) { myProject = project; } - protected abstract void onCopyChanged(DocumentEvent event, Document original); + protected abstract void onCopyChanged(@NotNull DocumentEvent event, @NotNull Document original); - protected abstract void onOriginalChanged(DocumentEvent event, Document copy); + protected abstract void onOriginalChanged(@NotNull DocumentEvent event, @NotNull Document copy); - protected abstract void beforeListenersAttached(Document original, Document copy); + protected abstract void beforeListenersAttached(@NotNull Document original, @NotNull Document copy); protected abstract Document createOriginal(); protected abstract Document createCopy(); - protected void replaceString(final Document document, final int startOffset, final int endOffset, final String newText) { + protected void replaceString(@NotNull final Document document, final int startOffset, final int endOffset, @NotNull final String newText) { LOG.assertTrue(!myDuringModification); try { myDuringModification = true; CommandProcessor.getInstance().executeCommand(myProject, new Runnable() { + @Override public void run() { LOG.assertTrue(endOffset <= document.getTextLength()); - document.replaceString(startOffset, endOffset, newText); + ApplicationManager.getApplication().runWriteAction(new Runnable() { + @Override + public void run() { + document.replaceString(startOffset, endOffset, newText); + } + }); } }, DiffBundle.message("save.merge.result.command.name"), document); } diff --git a/platform/platform-api/src/com/intellij/openapi/diff/FragmentContent.java b/platform/platform-api/src/com/intellij/openapi/diff/FragmentContent.java index 608a40c548f6..6c40b3797efb 100644 --- a/platform/platform-api/src/com/intellij/openapi/diff/FragmentContent.java +++ b/platform/platform-api/src/com/intellij/openapi/diff/FragmentContent.java @@ -23,11 +23,11 @@ import com.intellij.openapi.editor.event.DocumentEvent; import com.intellij.openapi.fileEditor.FileDocumentManager; import com.intellij.openapi.fileEditor.OpenFileDescriptor; import com.intellij.openapi.fileTypes.FileType; -import com.intellij.openapi.fileTypes.FileTypeManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Key; import com.intellij.openapi.util.TextRange; import com.intellij.openapi.vfs.VirtualFile; +import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.IOException; @@ -39,19 +39,16 @@ public class FragmentContent extends DiffContent { private static final Logger LOG = Logger.getInstance("#com.intellij.openapi.diff.FragmentContent"); private final DiffContent myOriginal; private final FileType myType; - private final MyDocumentsSynchonizer mySynchonizer; + private final MyDocumentsSynchronizer mySynchonizer; public static final Key ORIGINAL_DOCUMENT = new Key("ORIGINAL_DOCUMENT"); - public FragmentContent(DiffContent original, TextRange range, Project project, VirtualFile file) { + public FragmentContent(@NotNull DiffContent original, @NotNull TextRange range, Project project, VirtualFile file) { this(original, range, project, file != null ? DiffContentUtil.getContentType(file) : null); } - public FragmentContent(DiffContent original, TextRange range, Project project, FileType type) { - this(original.getDocument().createRangeMarker(range.getStartOffset(), range.getEndOffset(), true), original, type, project); - } - - private FragmentContent(RangeMarker rangeMarker, DiffContent original, FileType fileType, Project project) { - mySynchonizer = new MyDocumentsSynchonizer(project, rangeMarker); + public FragmentContent(@NotNull DiffContent original, @NotNull TextRange range, Project project, FileType fileType) { + RangeMarker rangeMarker = original.getDocument().createRangeMarker(range.getStartOffset(), range.getEndOffset(), true); + mySynchonizer = new MyDocumentsSynchronizer(project, rangeMarker); myOriginal = original; myType = fileType; } @@ -65,27 +62,35 @@ public class FragmentContent extends DiffContent { } + @Override public void onAssigned(boolean isAssigned) { myOriginal.onAssigned(isAssigned); mySynchonizer.listenDocuments(isAssigned); super.onAssigned(isAssigned); } + @Override public Document getDocument() { return mySynchonizer.getCopy(); } + @Override public OpenFileDescriptor getOpenFileDescriptor(int offset) { return myOriginal.getOpenFileDescriptor(offset + mySynchonizer.getStartOffset()); } - public VirtualFile getFile() { return null; } + @Override + public VirtualFile getFile() { + return null; + } + @Override @Nullable public FileType getContentType() { return myType != null ? myType : myOriginal.getContentType(); } + @Override public byte[] getBytes() throws IOException { return getDocument().getText().getBytes(); } @@ -97,52 +102,59 @@ public class FragmentContent extends DiffContent { return new FragmentContent(new DocumentContent(project, document), TextRange.create(rangeMarker), project, type); } - private class MyDocumentsSynchonizer extends DocumentsSynchonizer { + private class MyDocumentsSynchronizer extends DocumentsSynchronizer { private final RangeMarker myRangeMarker; - public MyDocumentsSynchonizer(Project project, RangeMarker originalRange) { + public MyDocumentsSynchronizer(Project project, @NotNull RangeMarker originalRange) { super(project); myRangeMarker = originalRange; } - public int getStartOffset() { return myRangeMarker.getStartOffset(); } + public int getStartOffset() { + return myRangeMarker.getStartOffset(); + } - protected void onOriginalChanged(DocumentEvent event, Document copy) { + @Override + protected void onOriginalChanged(@NotNull DocumentEvent event, @NotNull Document copy) { if (!myRangeMarker.isValid()) { fireContentInvalid(); return; } - replaceString(copy, 0, copy.getTextLength(), - subText(event.getDocument(), myRangeMarker.getStartOffset(), getLength())); + replaceString(copy, 0, copy.getTextLength(), subText(event.getDocument(), myRangeMarker.getStartOffset(), getLength())); } - protected void beforeListenersAttached(Document original, Document copy) { + @Override + protected void beforeListenersAttached(@NotNull Document original, @NotNull Document copy) { boolean writable = copy.isWritable(); - Document copyEx = copy; - if (!writable) copyEx.setReadOnly(false); - replaceString(copy, 0, copy.getTextLength(), - subText(original, myRangeMarker.getStartOffset(), getLength())); - copyEx.setReadOnly(!writable); + if (!writable) { + copy.setReadOnly(false); + } + replaceString(copy, 0, copy.getTextLength(), subText(original, myRangeMarker.getStartOffset(), getLength())); + copy.setReadOnly(!writable); } private int getLength() { return myRangeMarker.getEndOffset() - myRangeMarker.getStartOffset(); } + @Override protected Document createOriginal() { return myRangeMarker.getDocument(); } + @Override protected Document createCopy() { final Document originalDocument = myRangeMarker.getDocument(); - String textInRange = originalDocument.getCharsSequence().subSequence(myRangeMarker.getStartOffset(), myRangeMarker.getEndOffset()).toString(); + String textInRange = + originalDocument.getCharsSequence().subSequence(myRangeMarker.getStartOffset(), myRangeMarker.getEndOffset()).toString(); final Document result = EditorFactory.getInstance().createDocument(textInRange); result.setReadOnly(!originalDocument.isWritable()); result.putUserData(ORIGINAL_DOCUMENT, originalDocument); return result; } - protected void onCopyChanged(DocumentEvent event, Document original) { + @Override + protected void onCopyChanged(@NotNull DocumentEvent event, @NotNull Document original) { final int originalOffset = event.getOffset() + myRangeMarker.getStartOffset(); LOG.assertTrue(originalOffset >= 0); if (!original.isWritable()) return; diff --git a/platform/platform-impl/src/com/intellij/idea/StartupUtil.java b/platform/platform-impl/src/com/intellij/idea/StartupUtil.java index ea5f9cc2a25d..28fb724f433a 100644 --- a/platform/platform-impl/src/com/intellij/idea/StartupUtil.java +++ b/platform/platform-impl/src/com/intellij/idea/StartupUtil.java @@ -186,7 +186,7 @@ public class StartupUtil { try { String shell = System.getenv("SHELL"); if (shell != null && new File(shell).canExecute()) { - String[] command = {shell, "-l", "-c", "/usr/bin/printenv -0"}; + String[] command = {shell, "-l", "-c", "/usr/bin/printenv"}; Process process = Runtime.getRuntime().exec(command); InputStream input = process.getInputStream(); @@ -194,7 +194,7 @@ public class StartupUtil { ByteArrayOutputStream lineBuf = new ByteArrayOutputStream(); int b; while ((b = input.read()) >= 0) { - if (b != 0) { + if (b != '\n') { lineBuf.write(b); } else { diff --git a/platform/platform-impl/src/com/intellij/internal/inspector/UiInspectorAction.java b/platform/platform-impl/src/com/intellij/internal/inspector/UiInspectorAction.java index 21b56711aeea..f94197480d06 100644 --- a/platform/platform-impl/src/com/intellij/internal/inspector/UiInspectorAction.java +++ b/platform/platform-impl/src/com/intellij/internal/inspector/UiInspectorAction.java @@ -197,9 +197,11 @@ public class UiInspectorAction extends ToggleAction implements DumbAware { } private void switchInfo(Component c) { - myInspectorTable = new InspectorTable(c); myWrapperPanel.removeAll(); - myWrapperPanel.add(myInspectorTable, BorderLayout.CENTER); + if (c != null) { + myInspectorTable = new InspectorTable(c); + myWrapperPanel.add(myInspectorTable, BorderLayout.CENTER); + } myWrapperPanel.revalidate(); myWrapperPanel.repaint(); } @@ -319,6 +321,10 @@ public class UiInspectorAction extends ToggleAction implements DumbAware { @Override public void valueChanged(TreeSelectionEvent e) { TreePath path = e.getNewLeadSelectionPath(); + if (path == null) { + onComponentChanged(null); + return; + } Object component = path.getLastPathComponent(); if (component instanceof ComponentNode) { Component c = ((ComponentNode)component).getOwnComponent(); @@ -411,12 +417,14 @@ public class UiInspectorAction extends ToggleAction implements DumbAware { } private static class InspectorTable extends JPanel { + private JLabel myTitleLabel; private InspectorTableModel myModel; private DimensionsComponent myDimensionComponent; private InspectorTable(@NotNull final Component component) { setLayout(new BorderLayout()); + myTitleLabel = new JLabel(component.getClass().getCanonicalName(), SwingConstants.CENTER); myModel = new InspectorTableModel(component); final StripeTable table = new StripeTable(myModel); @@ -433,6 +441,7 @@ public class UiInspectorAction extends ToggleAction implements DumbAware { table.setAutoResizeMode(JTable.AUTO_RESIZE_LAST_COLUMN); + add(myTitleLabel, BorderLayout.NORTH); add(new JBScrollPane(table), BorderLayout.CENTER); myDimensionComponent = new DimensionsComponent(component); add(myDimensionComponent, BorderLayout.SOUTH); diff --git a/platform/platform-impl/src/com/intellij/openapi/editor/ex/util/EditorUtil.java b/platform/platform-impl/src/com/intellij/openapi/editor/ex/util/EditorUtil.java index e59e5138cd7e..b663634d0852 100644 --- a/platform/platform-impl/src/com/intellij/openapi/editor/ex/util/EditorUtil.java +++ b/platform/platform-impl/src/com/intellij/openapi/editor/ex/util/EditorUtil.java @@ -301,7 +301,7 @@ public class EditorUtil { boolean useOptimization = true; boolean hasNonTabs = false; boolean hasTabs = false; - int scanEndOffset = Math.min(end, start + columnNumber - currentColumn[0]); + int scanEndOffset = Math.min(end, start + columnNumber - currentColumn[0] + 1); for (int i = start; i < scanEndOffset; i++) { char c = text.charAt(i); if (debugBuffer != null) { diff --git a/platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/FileEditorManagerImpl.java b/platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/FileEditorManagerImpl.java index 3b4bed5808aa..00bdcf158897 100644 --- a/platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/FileEditorManagerImpl.java +++ b/platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/FileEditorManagerImpl.java @@ -847,7 +847,7 @@ public class FileEditorManagerImpl extends FileEditorManagerEx implements Projec } // Restore selected editor - final FileEditorProvider selectedProvider = getSelectedFileEditorProvider(editorHistoryManager, file); + final FileEditorProvider selectedProvider = entry == null ? getSelectedFileEditorProvider(editorHistoryManager, file) : entry.mySelectedProvider; if (selectedProvider != null) { final FileEditor[] _editors = newSelectedComposite.getEditors(); final FileEditorProvider[] _providers = newSelectedComposite.getProviders(); diff --git a/platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/HistoryEntry.java b/platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/HistoryEntry.java index d83db06c8587..6edf3eaff1a7 100644 --- a/platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/HistoryEntry.java +++ b/platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/HistoryEntry.java @@ -25,14 +25,18 @@ import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.vfs.VirtualFileManager; import com.intellij.util.containers.HashMap; import org.jdom.Element; -import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import java.util.List; import java.util.Map; final class HistoryEntry{ - @NonNls public static final String TAG = "entry"; + static final String TAG = "entry"; + private static final String FILE_ATTR = "file"; + private static final String PROVIDER_ELEMENT = "provider"; + private static final String EDITOR_TYPE_ID_ATTR = "editor-type-id"; + private static final String SELECTED_ATTR_VALUE = "selected"; + private static final String STATE_ELEMENT = "state"; public final VirtualFile myFile; /** @@ -40,11 +44,6 @@ final class HistoryEntry{ */ public FileEditorProvider mySelectedProvider; private final HashMap myProvider2State; - @NonNls public static final String FILE_ATTR = "file"; - @NonNls public static final String PROVIDER_ATTR = "provider"; - @NonNls public static final String EDITOR_TYPE_ID_ATTR = "editor-type-id"; - @NonNls public static final String SELECTED_ATTR_VALUE = "selected"; - @NonNls public static final String STATE_ELEMENT = "state"; public HistoryEntry(@NotNull VirtualFile file, @NotNull FileEditorProvider[] providers, @NotNull FileEditorState[] states, @NotNull FileEditorProvider selectedProvider){ myFile = file; @@ -78,7 +77,7 @@ final class HistoryEntry{ FileDocumentManager.getInstance().getDocument(myFile); } - List providers = e.getChildren(PROVIDER_ATTR); + List providers = e.getChildren(PROVIDER_ELEMENT); for (final Object provider1 : providers) { Element _e = (Element)provider1; @@ -121,7 +120,7 @@ final class HistoryEntry{ for (final Map.Entry entry : myProvider2State.entrySet()) { FileEditorProvider provider = entry.getKey(); - Element providerElement = new Element(PROVIDER_ATTR); + Element providerElement = new Element(PROVIDER_ELEMENT); if (provider.equals(mySelectedProvider)) { providerElement.setAttribute(SELECTED_ATTR_VALUE, Boolean.TRUE.toString()); } diff --git a/platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/text/TextEditorProvider.java b/platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/text/TextEditorProvider.java index a2e53b8fc12d..f184961e6ffc 100644 --- a/platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/text/TextEditorProvider.java +++ b/platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/text/TextEditorProvider.java @@ -65,6 +65,7 @@ public class TextEditorProvider implements FileEditorProvider, DumbAware { return ApplicationManager.getApplication().getComponent(TextEditorProvider.class); } + @Override public boolean accept(@NotNull Project project, @NotNull VirtualFile file) { if (file.isDirectory() || !file.isValid()) { return false; @@ -77,16 +78,19 @@ public class TextEditorProvider implements FileEditorProvider, DumbAware { return !ft.isBinary() || BinaryFileTypeDecompilers.INSTANCE.forFileType(ft) != null; } + @Override @NotNull public FileEditor createEditor(@NotNull Project project, @NotNull final VirtualFile file) { LOG.assertTrue(accept(project, file)); return new TextEditorImpl(project, file, this); } + @Override public void disposeEditor(@NotNull FileEditor editor) { Disposer.dispose(editor); } + @Override @NotNull public FileEditorState readState(@NotNull Element element, @NotNull Project project, @NotNull VirtualFile file) { TextEditorState state = new TextEditorState(); @@ -104,6 +108,7 @@ public class TextEditorProvider implements FileEditorProvider, DumbAware { return state; } + @Override public void writeState(@NotNull FileEditorState _state, @NotNull Project project, @NotNull Element element) { TextEditorState state = (TextEditorState)_state; @@ -114,11 +119,13 @@ public class TextEditorProvider implements FileEditorProvider, DumbAware { element.setAttribute(VERTICAL_SCROLL_PROPORTION_ATTR, Float.toString(state.VERTICAL_SCROLL_PROPORTION)); } + @Override @NotNull public String getEditorTypeId() { return TYPE_ID; } + @Override @NotNull public FileEditorPolicy getPolicy() { return FileEditorPolicy.NONE; @@ -135,7 +142,8 @@ public class TextEditorProvider implements FileEditorProvider, DumbAware { return textEditor; } - protected EditorWrapper createWrapperForEditor(final Editor editor) { + @NotNull + protected EditorWrapper createWrapperForEditor(@NotNull Editor editor) { return new EditorWrapper(editor); } @@ -210,77 +218,95 @@ public class TextEditorProvider implements FileEditorProvider, DumbAware { protected class EditorWrapper extends UserDataHolderBase implements TextEditor { private final Editor myEditor; - public EditorWrapper(Editor editor) { + public EditorWrapper(@NotNull Editor editor) { myEditor = editor; } + @Override @NotNull public Editor getEditor() { return myEditor; } + @Override @NotNull public JComponent getComponent() { return myEditor.getComponent(); } + @Override public JComponent getPreferredFocusedComponent() { return myEditor.getContentComponent(); } + @Override @NotNull public String getName() { return "Text"; } + @Override public StructureViewBuilder getStructureViewBuilder() { VirtualFile file = FileDocumentManager.getInstance().getFile(myEditor.getDocument()); if (file == null) return null; - + final Project project = myEditor.getProject(); LOG.assertTrue(project != null); return StructureViewBuilder.PROVIDER.getStructureViewBuilder(file.getFileType(), file, project); } + @Override @NotNull public FileEditorState getState(@NotNull FileEditorStateLevel level) { return getStateImpl(null, myEditor, level); } + @Override public void setState(@NotNull FileEditorState state) { setStateImpl(null, myEditor, (TextEditorState)state); } + @Override public boolean isModified() { return false; } + @Override public boolean isValid() { return true; } + @Override public void dispose() { } + @Override public void selectNotify() { } + @Override public void deselectNotify() { } + @Override public void addPropertyChangeListener(@NotNull PropertyChangeListener listener) { } + @Override public void removePropertyChangeListener(@NotNull PropertyChangeListener listener) { } + @Override public BackgroundEditorHighlighter getBackgroundHighlighter() { return null; } + @Override public FileEditorLocation getCurrentLocation() { return null; } + @Override public boolean canNavigateTo(@NotNull final Navigatable navigatable) { return false; } + @Override public void navigateTo(@NotNull final Navigatable navigatable) { } } diff --git a/platform/platform-impl/src/com/intellij/openapi/wm/impl/ToolWindowsPane.java b/platform/platform-impl/src/com/intellij/openapi/wm/impl/ToolWindowsPane.java index 7a6a94c61c3f..11c92bf803d2 100644 --- a/platform/platform-impl/src/com/intellij/openapi/wm/impl/ToolWindowsPane.java +++ b/platform/platform-impl/src/com/intellij/openapi/wm/impl/ToolWindowsPane.java @@ -38,7 +38,6 @@ import com.intellij.util.ui.UIUtil; import javax.swing.*; import java.awt.*; -import java.awt.event.ComponentEvent; import java.awt.image.BufferedImage; import java.util.ArrayList; import java.util.Comparator; @@ -1005,7 +1004,7 @@ public final class ToolWindowsPane extends JBLayeredPane implements Disposable { } } - private final class MyLayeredPane extends JLayeredPane{ + private final class MyLayeredPane extends JBLayeredPane { /* * These images are used to perform animated showing and hiding of components. * They are the member for performance reason. @@ -1018,8 +1017,6 @@ public final class ToolWindowsPane extends JBLayeredPane implements Disposable { myTopImageRef=new SoftReference(null); setOpaque(!UIUtil.isUnderDarcula()); add(splitter,JLayeredPane.DEFAULT_LAYER); - splitter.setBounds(0,0,getWidth(),getHeight()); - enableEvents(ComponentEvent.COMPONENT_EVENT_MASK); } @Override @@ -1067,8 +1064,7 @@ public final class ToolWindowsPane extends JBLayeredPane implements Disposable { /** * When component size becomes larger then bottom and top images should be enlarged. */ - protected final void processComponentEvent(final ComponentEvent e) { - if(ComponentEvent.COMPONENT_RESIZED==e.getID()){ + public void doLayout() { final int width=getWidth(); final int height=getHeight(); if(width<0||height<0){ @@ -1102,11 +1098,6 @@ public final class ToolWindowsPane extends JBLayeredPane implements Disposable { } setBoundsInPaletteLayer(component, info.getAnchor(), weight); } - validate(); - repaint(); - }else{ - super.processComponentEvent(e); - } } public final void setBoundsInPaletteLayer(final Component component,final ToolWindowAnchor anchor,float weight){ diff --git a/platform/platform-tests/testSrc/com/intellij/execution/GeneralCommandLineTest.java b/platform/platform-tests/testSrc/com/intellij/execution/GeneralCommandLineTest.java index 8edda25b922a..7994aea2dd6c 100644 --- a/platform/platform-tests/testSrc/com/intellij/execution/GeneralCommandLineTest.java +++ b/platform/platform-tests/testSrc/com/intellij/execution/GeneralCommandLineTest.java @@ -229,7 +229,7 @@ public class GeneralCommandLineTest { } private static void checkEnvPassing(GeneralCommandLine commandLine, Map testEnv, boolean passParentEnv) throws Exception { - commandLine.setEnvironment(testEnv); + commandLine.getEnvironment().putAll(testEnv); commandLine.setPassParentEnvironment(passParentEnv); String output = execAndGetOutput(commandLine, null); diff --git a/platform/platform-tests/testSrc/com/intellij/openapi/fileEditor/FileEditorManagerTest.java b/platform/platform-tests/testSrc/com/intellij/openapi/fileEditor/FileEditorManagerTest.java index c8f4c78a9ba1..58e489d06e44 100644 --- a/platform/platform-tests/testSrc/com/intellij/openapi/fileEditor/FileEditorManagerTest.java +++ b/platform/platform-tests/testSrc/com/intellij/openapi/fileEditor/FileEditorManagerTest.java @@ -16,11 +16,14 @@ package com.intellij.openapi.fileEditor; import com.intellij.ide.ui.UISettings; +import com.intellij.mock.Mock; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.components.ExpandMacroToPathMap; import com.intellij.openapi.fileEditor.impl.EditorWithProviderComposite; import com.intellij.openapi.fileEditor.impl.FileEditorManagerImpl; +import com.intellij.openapi.project.Project; import com.intellij.openapi.util.JDOMUtil; +import com.intellij.openapi.vfs.VirtualFile; import com.intellij.testFramework.PlatformTestCase; import com.intellij.testFramework.PlatformTestUtil; import com.intellij.testFramework.fixtures.LightPlatformCodeInsightFixtureTestCase; @@ -30,8 +33,10 @@ import com.intellij.util.containers.ContainerUtil; import org.jdom.Document; import org.jdom.Element; import org.jdom.JDOMException; +import org.jetbrains.annotations.NotNull; import org.jetbrains.jps.model.serialization.PathMacroUtil; +import javax.swing.*; import java.io.File; import java.io.IOException; import java.util.Arrays; @@ -46,7 +51,6 @@ import java.util.concurrent.Future; public class FileEditorManagerTest extends LightPlatformCodeInsightFixtureTestCase { private FileEditorManagerImpl myManager; - @SuppressWarnings("JUnitTestCaseWithNonTrivialConstructors") public FileEditorManagerTest() { PlatformTestCase.initPlatformLangPrefix(); @@ -54,7 +58,7 @@ public class FileEditorManagerTest extends LightPlatformCodeInsightFixtureTestCa public void testTabOrder() throws Exception { - openFiles(); + openFiles(STRING); assertOpenFiles("1.txt", "foo.xml", "2.txt", "3.txt"); } @@ -63,7 +67,7 @@ public class FileEditorManagerTest extends LightPlatformCodeInsightFixtureTestCa int limit = UISettings.getInstance().EDITOR_TAB_LIMIT; try { UISettings.getInstance().EDITOR_TAB_LIMIT = 2; - openFiles(); + openFiles(STRING); // note that foo.xml is pinned assertOpenFiles("foo.xml", "3.txt"); } @@ -72,6 +76,65 @@ public class FileEditorManagerTest extends LightPlatformCodeInsightFixtureTestCa } } + public void testOpenRecentEditorTab() throws Exception { + PlatformTestUtil.registerExtension(FileEditorProvider.EP_FILE_EDITOR_PROVIDER, new MyFileEditorProvider(), getTestRootDisposable()); + + openFiles(" \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n"); + FileEditor[] selectedEditors = myManager.getSelectedEditors(); + assertEquals(1, selectedEditors.length); + assertEquals("mockEditor", selectedEditors[0].getName()); + } + + private static final String STRING = "\n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n"; + private void assertOpenFiles(String... fileNames) { EditorWithProviderComposite[] files = myManager.getSplitters().getEditorsComposites(); List names = ContainerUtil.map(files, new Function() { @@ -83,43 +146,8 @@ public class FileEditorManagerTest extends LightPlatformCodeInsightFixtureTestCa assertEquals(Arrays.asList(fileNames), names); } - private void openFiles() throws IOException, JDOMException, InterruptedException, ExecutionException { - Document document = JDOMUtil.loadDocument(" \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n"); + private void openFiles(String s) throws IOException, JDOMException, InterruptedException, ExecutionException { + Document document = JDOMUtil.loadDocument(s); Element rootElement = document.getRootElement(); ExpandMacroToPathMap map = new ExpandMacroToPathMap(); map.addMacroExpand(PathMacroUtil.PROJECT_DIR_MACRO_NAME, getTestDataPath()); @@ -156,4 +184,60 @@ public class FileEditorManagerTest extends LightPlatformCodeInsightFixtureTestCa protected boolean isWriteActionRequired() { return false; } + + private static class MyFileEditorProvider implements FileEditorProvider { + @NotNull + @Override + public String getEditorTypeId() { + return "mock"; + } + + @NotNull + @Override + public FileEditorState readState(@NotNull Element sourceElement, @NotNull Project project, @NotNull VirtualFile file) { + return FileEditorState.INSTANCE; + } + + @Override + public void writeState(@NotNull FileEditorState state, @NotNull Project project, @NotNull Element targetElement) { + } + + @Override + public boolean accept(@NotNull Project project, @NotNull VirtualFile file) { + return true; + } + + @NotNull + @Override + public FileEditor createEditor(@NotNull Project project, @NotNull VirtualFile file) { + return new Mock.MyFileEditor() { + @Override + public boolean isValid() { + return true; + } + + @NotNull + @Override + public JComponent getComponent() { + return new JLabel(); + } + + @NotNull + @Override + public String getName() { + return "mockEditor"; + } + }; + } + + @Override + public void disposeEditor(@NotNull FileEditor editor) { + } + + @NotNull + @Override + public FileEditorPolicy getPolicy() { + return FileEditorPolicy.PLACE_AFTER_DEFAULT_EDITOR; + } + } } diff --git a/platform/projectModel-impl/src/com/intellij/openapi/roots/impl/ProjectFileIndexFacade.java b/platform/projectModel-impl/src/com/intellij/openapi/roots/impl/ProjectFileIndexFacade.java index 53e7a381ac04..25d9b5b11170 100644 --- a/platform/projectModel-impl/src/com/intellij/openapi/roots/impl/ProjectFileIndexFacade.java +++ b/platform/projectModel-impl/src/com/intellij/openapi/roots/impl/ProjectFileIndexFacade.java @@ -70,12 +70,12 @@ public class ProjectFileIndexFacade extends FileIndexFacade { @Nullable @Override - public Module getModuleForFile(VirtualFile file) { + public Module getModuleForFile(@NotNull VirtualFile file) { return myFileIndex.getModuleForFile(file); } @Override - public boolean isValidAncestor(final VirtualFile baseDir, VirtualFile childDir) { + public boolean isValidAncestor(@NotNull final VirtualFile baseDir, @NotNull VirtualFile childDir) { if (!childDir.isDirectory()) { childDir = childDir.getParent(); } diff --git a/platform/util/src/com/intellij/util/containers/RecentStringInterner.java b/platform/util/src/com/intellij/util/containers/RecentStringInterner.java index 556c1449d594..00111c8078c4 100644 --- a/platform/util/src/com/intellij/util/containers/RecentStringInterner.java +++ b/platform/util/src/com/intellij/util/containers/RecentStringInterner.java @@ -1,7 +1,6 @@ package com.intellij.util.containers; import com.intellij.openapi.util.LowMemoryWatcher; -import com.intellij.util.containers.SLRUCache; import jsr166e.SequenceLock; import org.jetbrains.annotations.NotNull; @@ -16,7 +15,9 @@ public class RecentStringInterner { private final int myStripeMask; private final SLRUCache[] myInterns; private final Lock[] myStripeLocks; - private final LowMemoryWatcher myClearingCallback; + // LowMemoryWatcher relies on field holding it + @SuppressWarnings({"FieldCanBeLocal", "UnusedDeclaration"}) + private final LowMemoryWatcher myLowMemoryWatcher; public RecentStringInterner() { this(8192); @@ -24,6 +25,7 @@ public class RecentStringInterner { public RecentStringInterner(int capacity) { final int stripes = 16; + //noinspection unchecked myInterns = new SLRUCache[stripes]; myStripeLocks = new Lock[myInterns.length]; for(int i = 0; i < myInterns.length; ++i) { @@ -44,11 +46,11 @@ public class RecentStringInterner { assert Integer.highestOneBit(stripes) == stripes; myStripeMask = stripes - 1; - myClearingCallback = LowMemoryWatcher.register(new Runnable() { + myLowMemoryWatcher = LowMemoryWatcher.register(new Runnable() { @Override public void run() { clear(); - }; + } }); } diff --git a/platform/vcs-impl/src/com/intellij/openapi/vcs/changes/VcsChangeDetailsManager.java b/platform/vcs-impl/src/com/intellij/openapi/vcs/changes/VcsChangeDetailsManager.java index c4e920476e51..394484e360aa 100644 --- a/platform/vcs-impl/src/com/intellij/openapi/vcs/changes/VcsChangeDetailsManager.java +++ b/platform/vcs-impl/src/com/intellij/openapi/vcs/changes/VcsChangeDetailsManager.java @@ -339,6 +339,7 @@ public class VcsChangeDetailsManager { protected JPanel dataToPresentation(ValueWithVcsException value) { final PreparedFragmentedContent requestForChange; try { + if (value == null) return noDifferences(); requestForChange = value.get(); if (requestForChange == null) return noDifferences(); if (requestForChange.isEmpty()) { diff --git a/platform/vcs-impl/src/com/intellij/openapi/vcs/changes/committed/CommittedChangesCache.java b/platform/vcs-impl/src/com/intellij/openapi/vcs/changes/committed/CommittedChangesCache.java index 499a028127cb..9155a1a63fd9 100644 --- a/platform/vcs-impl/src/com/intellij/openapi/vcs/changes/committed/CommittedChangesCache.java +++ b/platform/vcs-impl/src/com/intellij/openapi/vcs/changes/committed/CommittedChangesCache.java @@ -167,13 +167,20 @@ public class CommittedChangesCache implements PersistentStateComponent continuation) { myTaskQueue.run(new Runnable() { + @Override public void run() { final Ref success = new Ref(); try { @@ -387,6 +399,7 @@ public class CommittedChangesCache implements PersistentStateComponent resultRef = new Ref(Boolean.FALSE); myCachesHolder.iterateAllCaches(new NotNullFunction() { + @Override @NotNull public Boolean fun(final ChangesCacheFile changesCacheFile) { try { @@ -525,7 +539,7 @@ public class CommittedChangesCache implements PersistentStateComponent refreshCache(final ChangesCacheFile cacheFile) throws VcsException, IOException { final List newLists = new ArrayList(); @@ -586,6 +600,7 @@ public class CommittedChangesCache implements PersistentStateComponent ref = new Ref(); final List savedChanges = ApplicationManager.getApplication().runReadAction(new Computable>() { + @Override public List compute() { try { return cacheFile.writeChanges(newChanges); // skip duplicates; @@ -655,7 +670,7 @@ public class CommittedChangesCache implements PersistentStateComponent, List> groupLocations(final List in) { return myVcsZipper.groupLocations(in); } @@ -723,6 +739,7 @@ public class CommittedChangesCache implements PersistentStateComponent> consumer, final boolean inBackground) { debug("Loading incoming changes"); final Runnable task = new Runnable() { + @Override public void run() { final List list = loadIncomingChanges(inBackground); if (consumer != null) { @@ -757,6 +774,7 @@ public class CommittedChangesCache implements PersistentStateComponent caches = myCachesHolder.getAllCaches(); @@ -799,6 +817,7 @@ public class CommittedChangesCache implements PersistentStateComponent committedChangeLists) { try { debug("Processing updated files after refresh in " + cache.getLocation()); @@ -825,6 +844,7 @@ public class CommittedChangesCache implements PersistentStateComponent files = myCachesHolder.getAllCaches(); final RefreshResultConsumer notifyConsumer = new RefreshResultConsumer() { @@ -939,11 +962,13 @@ public class CommittedChangesCache implements PersistentStateComponent changes) { totalChangesCount += changes.size(); checkDone(); } + @Override public void receivedError(VcsException ex) { myError = ex; checkDone(); @@ -998,6 +1023,7 @@ public class CommittedChangesCache implements PersistentStateComponent list; @@ -1105,6 +1131,7 @@ public class CommittedChangesCache implements PersistentStateComponent { void breakpointsChanged(); } - public abstract void addListener(BreakpointsListener listener, Project project); + public abstract void addListener(BreakpointsListener listener, Project project, Disposable disposable); - public abstract void removeListener(BreakpointsListener listener); + protected abstract void removeListener(BreakpointsListener listener); public abstract int getPriority(); diff --git a/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/breakpoints/ui/tree/BreakpointMasterDetailPopupBuilder.java b/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/breakpoints/ui/tree/BreakpointMasterDetailPopupBuilder.java index 939dc2a2595a..47516e84c979 100644 --- a/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/breakpoints/ui/tree/BreakpointMasterDetailPopupBuilder.java +++ b/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/breakpoints/ui/tree/BreakpointMasterDetailPopupBuilder.java @@ -15,6 +15,7 @@ */ package com.intellij.xdebugger.impl.breakpoints.ui.tree; +import com.intellij.openapi.Disposable; import com.intellij.openapi.actionSystem.*; import com.intellij.openapi.actionSystem.ex.CheckboxAction; import com.intellij.openapi.project.Project; @@ -23,6 +24,7 @@ import com.intellij.openapi.ui.popup.JBPopupFactory; import com.intellij.openapi.ui.popup.JBPopupListener; import com.intellij.openapi.ui.popup.LightweightWindowEvent; import com.intellij.openapi.util.Condition; +import com.intellij.openapi.util.Disposer; import com.intellij.openapi.util.SystemInfo; import com.intellij.ui.popup.util.DetailView; import com.intellij.ui.popup.util.DetailViewImpl; @@ -177,8 +179,9 @@ public class BreakpointMasterDetailPopupBuilder { } }; + final Disposable listenerDisposable = Disposer.newDisposable(); for (BreakpointPanelProvider provider : myBreakpointsPanelProviders) { - provider.addListener(listener, myProject); + provider.addListener(listener, myProject, listenerDisposable); } final MasterDetailPopupBuilder.Delegate delegate = new MasterDetailPopupBuilder.Delegate() { @@ -247,9 +250,7 @@ public class BreakpointMasterDetailPopupBuilder { @Override public void onClosed(LightweightWindowEvent event) { - for (BreakpointPanelProvider provider : myBreakpointsPanelProviders) { - provider.removeListener(listener); - } + Disposer.dispose(listenerDisposable); saveBreakpointsDialogState(); } }); diff --git a/plugins/InspectionGadgets/src/META-INF/plugin.xml b/plugins/InspectionGadgets/src/META-INF/plugin.xml index 1b3efecf24ca..2e8c2d98e469 100644 --- a/plugins/InspectionGadgets/src/META-INF/plugin.xml +++ b/plugins/InspectionGadgets/src/META-INF/plugin.xml @@ -2297,6 +2297,10 @@ key="unnecessary.call.to.string.valueof.display.name" groupBundle="messages.InspectionsBundle" groupKey="group.names.code.style.issues" enabledByDefault="false" level="WARNING" implementationClass="com.siyeh.ig.style.UnnecessaryCallToStringValueOfInspection"/> + #ref can be simplified to ''{0}'' #loc +unnecessary.tostring.call.problem.descriptor=Unnecessary #ref() call #loc unnecessary.call.to.string.valueof.quickfix=Replace with ''{0}'' throwable.result.of.method.call.ignored.display.name=Throwable result of method call ignored throwable.result.of.method.call.ignored.problem.descriptor=Result of #ref() not thrown #loc diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/jdk/VarargParameterInspection.java b/plugins/InspectionGadgets/src/com/siyeh/ig/jdk/VarargParameterInspection.java index f011d6dd84c2..f93166cfd2b3 100644 --- a/plugins/InspectionGadgets/src/com/siyeh/ig/jdk/VarargParameterInspection.java +++ b/plugins/InspectionGadgets/src/com/siyeh/ig/jdk/VarargParameterInspection.java @@ -1,5 +1,5 @@ /* - * Copyright 2003-2011 Dave Griffith, Bas Leijdekkers + * Copyright 2003-2013 Dave Griffith, Bas Leijdekkers * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,13 +15,13 @@ */ package com.siyeh.ig.jdk; +import com.intellij.codeInsight.AnnotationUtil; import com.intellij.codeInspection.ProblemDescriptor; import com.intellij.openapi.project.Project; import com.intellij.psi.*; import com.intellij.psi.codeStyle.CodeStyleManager; import com.intellij.psi.codeStyle.JavaCodeStyleManager; import com.intellij.psi.search.searches.ReferencesSearch; -import com.intellij.util.IncorrectOperationException; import com.intellij.util.Query; import com.siyeh.InspectionGadgetsBundle; import com.siyeh.ig.BaseInspection; @@ -44,15 +44,13 @@ public class VarargParameterInspection extends BaseInspection { @Override @NotNull public String getDisplayName() { - return InspectionGadgetsBundle.message( - "variable.argument.method.display.name"); + return InspectionGadgetsBundle.message("variable.argument.method.display.name"); } @Override @NotNull public String buildErrorString(Object... infos) { - return InspectionGadgetsBundle.message( - "variable.argument.method.problem.descriptor"); + return InspectionGadgetsBundle.message("variable.argument.method.problem.descriptor"); } @Override @@ -65,27 +63,29 @@ public class VarargParameterInspection extends BaseInspection { @NotNull public String getName() { - return InspectionGadgetsBundle.message( - "variable.argument.method.quickfix"); + return InspectionGadgetsBundle.message("variable.argument.method.quickfix"); } @Override - protected void doFix(Project project, ProblemDescriptor descriptor) - throws IncorrectOperationException { + protected void doFix(Project project, ProblemDescriptor descriptor) { final PsiElement element = descriptor.getPsiElement(); final PsiMethod method = (PsiMethod)element.getParent(); final PsiParameterList parameterList = method.getParameterList(); final PsiParameter[] parameters = parameterList.getParameters(); - final PsiParameter lastParameter = - parameters[parameters.length - 1]; + final PsiParameter lastParameter = parameters[parameters.length - 1]; if (!lastParameter.isVarArgs()) { return; } - final PsiEllipsisType type = - (PsiEllipsisType)lastParameter.getType(); + final PsiEllipsisType type = (PsiEllipsisType)lastParameter.getType(); final Query query = ReferencesSearch.search(method); final PsiType componentType = type.getComponentType(); - final String typeText = componentType.getCanonicalText(); + final String typeText; + if (componentType instanceof PsiClassType) { + final PsiClassType classType = (PsiClassType)componentType; + typeText = classType.rawType().getCanonicalText(); + } else { + typeText = componentType.getCanonicalText(); + } final Collection references = query.findAll(); for (PsiReference reference : references) { modifyCalls(reference, typeText, parameters.length - 1); @@ -93,59 +93,48 @@ public class VarargParameterInspection extends BaseInspection { final PsiType arrayType = type.toArrayType(); final PsiManager psiManager = lastParameter.getManager(); final PsiElementFactory factory = JavaPsiFacade.getInstance(psiManager.getProject()).getElementFactory(); - final PsiTypeElement newTypeElement = - factory.createTypeElement(arrayType); - final PsiTypeElement typeElement = - lastParameter.getTypeElement(); + final PsiTypeElement newTypeElement = factory.createTypeElement(arrayType); + final PsiTypeElement typeElement = lastParameter.getTypeElement(); + if (typeElement == null) { + return; + } + final PsiAnnotation annotation = AnnotationUtil.findAnnotation(method, "java.lang.SafeVarargs"); + if (annotation != null) { + annotation.delete(); + } typeElement.replace(newTypeElement); } - public static void modifyCalls(PsiReference reference, - String arrayTypeText, - int indexOfFirstVarargArgument) - throws IncorrectOperationException { - final PsiReferenceExpression referenceExpression = - (PsiReferenceExpression)reference.getElement(); - final PsiMethodCallExpression methodCallExpression = - (PsiMethodCallExpression)referenceExpression.getParent(); - final PsiExpressionList argumentList = - methodCallExpression.getArgumentList(); + public static void modifyCalls(PsiReference reference, String arrayTypeText, int indexOfFirstVarargArgument) { + final PsiReferenceExpression referenceExpression = (PsiReferenceExpression)reference.getElement(); + final PsiMethodCallExpression methodCallExpression = (PsiMethodCallExpression)referenceExpression.getParent(); + final PsiExpressionList argumentList = methodCallExpression.getArgumentList(); final PsiExpression[] arguments = argumentList.getExpressions(); @NonNls final StringBuilder builder = new StringBuilder("new "); builder.append(arrayTypeText); builder.append("[]{"); if (arguments.length > indexOfFirstVarargArgument) { - final PsiExpression firstArgument = - arguments[indexOfFirstVarargArgument]; + final PsiExpression firstArgument = arguments[indexOfFirstVarargArgument]; final String firstArgumentText = firstArgument.getText(); builder.append(firstArgumentText); - for (int i = indexOfFirstVarargArgument + 1; - i < arguments.length; i++) { - builder.append(','); - builder.append(arguments[i].getText()); + for (int i = indexOfFirstVarargArgument + 1; i < arguments.length; i++) { + builder.append(',').append(arguments[i].getText()); } } builder.append('}'); final Project project = referenceExpression.getProject(); - final PsiElementFactory factory = - JavaPsiFacade.getElementFactory(project); - final PsiExpression arrayExpression = - factory.createExpressionFromText(builder.toString(), - referenceExpression); + final PsiElementFactory factory = JavaPsiFacade.getElementFactory(project); + final PsiExpression arrayExpression = factory.createExpressionFromText(builder.toString(), referenceExpression); if (arguments.length > indexOfFirstVarargArgument) { - final PsiExpression firstArgument = - arguments[indexOfFirstVarargArgument]; - argumentList.deleteChildRange(firstArgument, - arguments[arguments.length - 1]); + final PsiExpression firstArgument = arguments[indexOfFirstVarargArgument]; + argumentList.deleteChildRange(firstArgument, arguments[arguments.length - 1]); argumentList.add(arrayExpression); } else { argumentList.add(arrayExpression); } - final CodeStyleManager codeStyleManager = - CodeStyleManager.getInstance(project); - final JavaCodeStyleManager javaCodeStyleManager = - JavaCodeStyleManager.getInstance(project); + final CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(project); + final JavaCodeStyleManager javaCodeStyleManager = JavaCodeStyleManager.getInstance(project); javaCodeStyleManager.shortenClassReferences(argumentList); codeStyleManager.reformat(argumentList); } @@ -165,8 +154,7 @@ public class VarargParameterInspection extends BaseInspection { return; } final PsiParameter[] parameters = parameterList.getParameters(); - final PsiParameter lastParameter = - parameters[parameters.length - 1]; + final PsiParameter lastParameter = parameters[parameters.length - 1]; if (lastParameter.isVarArgs()) { registerMethodError(method); } diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/style/UnnecessaryToStringCallInspection.java b/plugins/InspectionGadgets/src/com/siyeh/ig/style/UnnecessaryToStringCallInspection.java new file mode 100644 index 000000000000..d7cad4ef4f13 --- /dev/null +++ b/plugins/InspectionGadgets/src/com/siyeh/ig/style/UnnecessaryToStringCallInspection.java @@ -0,0 +1,200 @@ +/* + * Copyright 2008-2013 Bas Leijdekkers + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.siyeh.ig.style; + +import com.intellij.codeInspection.ProblemDescriptor; +import com.intellij.openapi.project.Project; +import com.intellij.psi.*; +import com.intellij.util.IncorrectOperationException; +import com.siyeh.InspectionGadgetsBundle; +import com.siyeh.ig.BaseInspection; +import com.siyeh.ig.BaseInspectionVisitor; +import com.siyeh.ig.InspectionGadgetsFix; +import com.siyeh.ig.psiutils.ParenthesesUtils; +import com.siyeh.ig.psiutils.TypeUtils; +import org.jetbrains.annotations.Nls; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +public class UnnecessaryToStringCallInspection extends BaseInspection { + + @Override + @Nls + @NotNull + public String getDisplayName() { + return InspectionGadgetsBundle.message("unnecessary.tostring.call.display.name"); + } + + @Override + @NotNull + protected String buildErrorString(Object... infos) { + final String text = (String)infos[0]; + return InspectionGadgetsBundle.message("unnecessary.tostring.call.problem.descriptor", text); + } + + @Override + @Nullable + protected InspectionGadgetsFix buildFix(Object... infos) { + final String text = (String)infos[0]; + return new UnnecessaryCallToStringValueOfFix(text); + } + + public static String calculateReplacementText(PsiExpression expression) { + if (expression == null) { + return "this"; + } + return expression.getText(); + } + + private static class UnnecessaryCallToStringValueOfFix extends InspectionGadgetsFix { + + private final String replacementText; + + UnnecessaryCallToStringValueOfFix(String replacementText) { + this.replacementText = replacementText; + } + + @NotNull + public String getName() { + return InspectionGadgetsBundle.message("unnecessary.call.to.string.valueof.quickfix", replacementText); + } + + @Override + protected void doFix(Project project, ProblemDescriptor descriptor) throws IncorrectOperationException { + final PsiMethodCallExpression methodCallExpression = (PsiMethodCallExpression)descriptor.getPsiElement().getParent().getParent(); + final PsiReferenceExpression methodExpression = methodCallExpression.getMethodExpression(); + final PsiExpression qualifier = methodExpression.getQualifierExpression(); + if (qualifier == null) { + replaceExpression(methodCallExpression, "this"); + } else { + methodCallExpression.replace(qualifier); + } + } + } + + @Override + public BaseInspectionVisitor buildVisitor() { + return new UnnecessaryCallToStringValueOfVisitor(); + } + + private static class UnnecessaryCallToStringValueOfVisitor extends BaseInspectionVisitor { + + @Override + public void visitMethodCallExpression(PsiMethodCallExpression expression) { + super.visitMethodCallExpression(expression); + final PsiReferenceExpression methodExpression = expression.getMethodExpression(); + final String referenceName = methodExpression.getReferenceName(); + if (!"toString".equals(referenceName)) { + return; + } + if (isToStringCallNecessary(expression)) { + return; + } + final PsiExpressionList argumentList = expression.getArgumentList(); + final PsiExpression[] arguments = argumentList.getExpressions(); + if (arguments.length != 0) { + return; + } + final PsiExpression qualifier = methodExpression.getQualifierExpression(); + if (qualifier != null && qualifier.getType() instanceof PsiArrayType) { + // do not warn on nonsensical code + return; + } + registerMethodCallError(expression, calculateReplacementText(qualifier)); + } + + private boolean isToStringCallNecessary(PsiMethodCallExpression expression) { + final PsiElement parent = ParenthesesUtils.getParentSkipParentheses(expression); + if (parent instanceof PsiPolyadicExpression) { + final PsiPolyadicExpression polyadicExpression = (PsiPolyadicExpression)parent; + final PsiType type = polyadicExpression.getType(); + if (!TypeUtils.typeEquals(CommonClassNames.JAVA_LANG_STRING, type)) { + return true; + } + final PsiExpression[] operands = polyadicExpression.getOperands(); + int index = -1; + for (int i = 0, length = operands.length; i < length; i++) { + final PsiExpression operand = operands[i]; + if (expression.equals(operand)) { + index = i; + } + } + if (index > 0) { + if (!TypeUtils.typeEquals(CommonClassNames.JAVA_LANG_STRING, operands[index - 1].getType())) { + return true; + } + } else if (operands.length > 1) { + if (!TypeUtils.typeEquals(CommonClassNames.JAVA_LANG_STRING, operands[index + 1].getType())) { + return true; + } + } else { + return true; + } + } else if (parent instanceof PsiExpressionList) { + final PsiExpressionList expressionList = (PsiExpressionList)parent; + final PsiElement grandParent = expressionList.getParent(); + if (!(grandParent instanceof PsiMethodCallExpression)) { + return true; + } + final PsiMethodCallExpression methodCallExpression = (PsiMethodCallExpression)grandParent; + final PsiReferenceExpression methodExpression1 = methodCallExpression.getMethodExpression(); + final String name = methodExpression1.getReferenceName(); + final PsiExpression[] expressions = expressionList.getExpressions(); + if ("insert".equals(name)) { + if (expressions.length < 2 || !expression.equals(ParenthesesUtils.stripParentheses(expressions[1]))) { + return true; + } + if (!isCallToMethodIn(methodCallExpression, "java.lang.StringBuilder", "java.lang.StringBuffer")) { + return true; + } + + } else if ("append".equals(name)) { + if (expressions.length < 1 || !expression.equals(ParenthesesUtils.stripParentheses(expressions[0]))) { + return true; + } + if (!isCallToMethodIn(methodCallExpression, "java.lang.StringBuilder", "java.lang.StringBuffer")) { + return true; + } + } else if ("print".equals(name) || "println".equals(name)) { + if (!isCallToMethodIn(methodCallExpression, "java.io.PrintStream", "java.io.PrintWriter")) { + return true; + } + } + } else { + return true; + } + return false; + } + + private boolean isCallToMethodIn(PsiMethodCallExpression methodCallExpression, String... classNames) { + final PsiMethod method = methodCallExpression.resolveMethod(); + if (method == null) { + return false; + } + final PsiClass containingClass = method.getContainingClass(); + if (containingClass == null) { + return false; + } + final String qualifiedName = containingClass.getQualifiedName(); + for (String className : classNames) { + if (className.equals(qualifiedName)) { + return true; + } + } + return false; + } + } +} diff --git a/plugins/InspectionGadgets/src/inspectionDescriptions/UnnecessaryCallToStringValueOf.html b/plugins/InspectionGadgets/src/inspectionDescriptions/UnnecessaryCallToStringValueOf.html index 3d95b3ac2f14..ecbdf6ff2ff8 100644 --- a/plugins/InspectionGadgets/src/inspectionDescriptions/UnnecessaryCallToStringValueOf.html +++ b/plugins/InspectionGadgets/src/inspectionDescriptions/UnnecessaryCallToStringValueOf.html @@ -1,8 +1,8 @@ -Reports on any calls to String.valueOf() -used in string concatenations. The conversion to string is handled automatically by the compiler -without a call to String.valueOf(), making it unnecessary. +Reports on any calls to String.valueOf() used in string concatenations and as arguments to the +print and println methods of java.io.PrintWriter and java.io.PrintStream. The conversion +to string will be handled by the underlying library methods without an explicit call to String.valueOf().

Powered by InspectionGadgets diff --git a/plugins/InspectionGadgets/src/inspectionDescriptions/UnnecessaryToStringCall.html b/plugins/InspectionGadgets/src/inspectionDescriptions/UnnecessaryToStringCall.html new file mode 100644 index 000000000000..69cfb6134430 --- /dev/null +++ b/plugins/InspectionGadgets/src/inspectionDescriptions/UnnecessaryToStringCall.html @@ -0,0 +1,13 @@ + + +Reports on any calls to .toString() used in string concatenations and as arguments to the +print and println methods of java.io.PrintWriter and java.io.PrintStream. The conversion +to string will be handled by the underlying library methods without an explicit call to .toString(). +

+Note that without the .toString() the expression will have different semantics (the string "null" will be used instead of + throwing a NullPointerException). + +

+Powered by InspectionGadgets + + \ No newline at end of file diff --git a/plugins/InspectionGadgets/test/com/siyeh/igfixes/jdk/vararg_parameter/GenericType.after.java b/plugins/InspectionGadgets/test/com/siyeh/igfixes/jdk/vararg_parameter/GenericType.after.java new file mode 100644 index 000000000000..7c6d0d34ed4d --- /dev/null +++ b/plugins/InspectionGadgets/test/com/siyeh/igfixes/jdk/vararg_parameter/GenericType.after.java @@ -0,0 +1,11 @@ +package com.siyeh.igfixes.jdk.vararg_parameter; + +@SuppressWarnings("UnusedDeclaration") +public class GenericType { + final void addClasses(Class[] classes) { + } + + void test() { + addClasses(new Class[]{Number.class, Byte.class}); + } +} \ No newline at end of file diff --git a/plugins/InspectionGadgets/test/com/siyeh/igfixes/jdk/vararg_parameter/GenericType.java b/plugins/InspectionGadgets/test/com/siyeh/igfixes/jdk/vararg_parameter/GenericType.java new file mode 100644 index 000000000000..595bf0032e2b --- /dev/null +++ b/plugins/InspectionGadgets/test/com/siyeh/igfixes/jdk/vararg_parameter/GenericType.java @@ -0,0 +1,12 @@ +package com.siyeh.igfixes.jdk.vararg_parameter; + +@SuppressWarnings("UnusedDeclaration") +public class GenericType { + @java.lang.SafeVarargs + final void addClasses(Class... classes) { + } + + void test() { + addClasses(Number.class, Byte.class); + } +} \ No newline at end of file diff --git a/plugins/InspectionGadgets/test/com/siyeh/igtest/style/unnecessary_tostring/UnnecessaryToString.java b/plugins/InspectionGadgets/test/com/siyeh/igtest/style/unnecessary_tostring/UnnecessaryToString.java new file mode 100644 index 000000000000..a77660ab714a --- /dev/null +++ b/plugins/InspectionGadgets/test/com/siyeh/igtest/style/unnecessary_tostring/UnnecessaryToString.java @@ -0,0 +1,30 @@ +package com.siyeh.igtest.style.unnecessary_tostring; + +public class UnnecessaryToString { + + String foo(Object o) { + return "star" + o.toString(); + } + + String bar() { + char[] cs = {'!'}; + return "wars" + cs.toString(); + } + + void fizzz(Object o) { + boolean c = true; + System.out.println(o.toString() + c); + } + + void polyadic(Object s) { + s = "abc" + s.toString() + "efg"; + } + + void printStream(Object o) { + System.out.print(o.toString()); + } + + void builder(StringBuilder builder, Object o) { + builder.append(o.toString()); + } +} \ No newline at end of file diff --git a/plugins/InspectionGadgets/test/com/siyeh/igtest/style/unnecessary_tostring/expected.xml b/plugins/InspectionGadgets/test/com/siyeh/igtest/style/unnecessary_tostring/expected.xml new file mode 100644 index 000000000000..9aea4d234a81 --- /dev/null +++ b/plugins/InspectionGadgets/test/com/siyeh/igtest/style/unnecessary_tostring/expected.xml @@ -0,0 +1,32 @@ + + + + + UnnecessaryToString.java + 6 + Unnecessary call to '.toString()' + Unnecessary <code>toString()</code> call #loc + + + + UnnecessaryToString.java + 20 + Unnecessary call to '.toString()' + Unnecessary <code>toString()</code> call #loc + + + + UnnecessaryToString.java + 24 + Unnecessary call to '.toString()' + Unnecessary <code>toString()</code> call #loc + + + + UnnecessaryToString.java + 28 + Unnecessary call to '.toString()' + Unnecessary <code>toString()</code> call #loc + + + \ No newline at end of file diff --git a/plugins/InspectionGadgets/testsrc/com/siyeh/ig/fixes/jdk/VarargParameterFixTest.java b/plugins/InspectionGadgets/testsrc/com/siyeh/ig/fixes/jdk/VarargParameterFixTest.java new file mode 100644 index 000000000000..f14e395ff243 --- /dev/null +++ b/plugins/InspectionGadgets/testsrc/com/siyeh/ig/fixes/jdk/VarargParameterFixTest.java @@ -0,0 +1,18 @@ +package com.siyeh.ig.fixes.jdk; + +import com.siyeh.InspectionGadgetsBundle; +import com.siyeh.ig.IGQuickFixesTestCase; +import com.siyeh.ig.jdk.VarargParameterInspection; + +public class VarargParameterFixTest extends IGQuickFixesTestCase { + + @Override + protected void setUp() throws Exception { + super.setUp(); + myFixture.enableInspections(new VarargParameterInspection()); + myRelativePath = "jdk/vararg_parameter"; + myDefaultHint = InspectionGadgetsBundle.message("variable.argument.method.quickfix"); + } + + public void testGenericType() { doTest(); } +} \ No newline at end of file diff --git a/plugins/InspectionGadgets/testsrc/com/siyeh/ig/style/UnnecessaryToStringCallInspectionTest.java b/plugins/InspectionGadgets/testsrc/com/siyeh/ig/style/UnnecessaryToStringCallInspectionTest.java new file mode 100644 index 000000000000..797b4273106d --- /dev/null +++ b/plugins/InspectionGadgets/testsrc/com/siyeh/ig/style/UnnecessaryToStringCallInspectionTest.java @@ -0,0 +1,10 @@ +package com.siyeh.ig.style; + +import com.siyeh.ig.IGInspectionTestCase; + +public class UnnecessaryToStringCallInspectionTest extends IGInspectionTestCase { + + public void test() throws Exception { + doTest("com/siyeh/igtest/style/unnecessary_tostring", new UnnecessaryToStringCallInspection()); + } +} \ No newline at end of file diff --git a/plugins/cvs/cvs-core/src/com/intellij/cvsSupport2/connections/ConnectionOnProcess.java b/plugins/cvs/cvs-core/src/com/intellij/cvsSupport2/connections/ConnectionOnProcess.java index bcf34e8f48a0..b866d1cd9136 100644 --- a/plugins/cvs/cvs-core/src/com/intellij/cvsSupport2/connections/ConnectionOnProcess.java +++ b/plugins/cvs/cvs-core/src/com/intellij/cvsSupport2/connections/ConnectionOnProcess.java @@ -142,7 +142,8 @@ public abstract class ConnectionOnProcess implements IConnection { protected synchronized void execute(GeneralCommandLine commandLine) throws AuthenticationException { try { - commandLine.setEnvironment(EnvironmentUtil.getEnvironmentProperties()); + commandLine.getEnvironment().clear(); + commandLine.getEnvironment().putAll(EnvironmentUtil.getEnvironmentProperties()); myProcess = commandLine.createProcess(); myErrThread = new ReadProcessThread( diff --git a/plugins/git4idea/src/git4idea/commands/GitHandler.java b/plugins/git4idea/src/git4idea/commands/GitHandler.java index 0669a9ee164e..0816bb93db0e 100644 --- a/plugins/git4idea/src/git4idea/commands/GitHandler.java +++ b/plugins/git4idea/src/git4idea/commands/GitHandler.java @@ -451,7 +451,8 @@ public abstract class GitHandler { LOG.debug(String.format("handler=%s, port=%s", myHandlerNo, port)); addAuthListener(httpAuthenticator); } - myCommandLine.setEnvironment(myEnv); + myCommandLine.getEnvironment().clear(); + myCommandLine.getEnvironment().putAll(myEnv); // start process myProcess = startProcess(); startHandlingStreams(); diff --git a/plugins/google-app-engine/google-app-engine.iml b/plugins/google-app-engine/google-app-engine.iml index 452bb1f80aed..52217861ad17 100644 --- a/plugins/google-app-engine/google-app-engine.iml +++ b/plugins/google-app-engine/google-app-engine.iml @@ -16,7 +16,6 @@ - diff --git a/plugins/google-app-engine/source/com/intellij/appengine/facet/AppEngineSupportProvider.java b/plugins/google-app-engine/source/com/intellij/appengine/facet/AppEngineSupportProvider.java index b5b1be386585..255145fd9449 100644 --- a/plugins/google-app-engine/source/com/intellij/appengine/facet/AppEngineSupportProvider.java +++ b/plugins/google-app-engine/source/com/intellij/appengine/facet/AppEngineSupportProvider.java @@ -39,6 +39,10 @@ import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VfsUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.packaging.artifacts.Artifact; +import com.intellij.packaging.artifacts.ArtifactManager; +import com.intellij.packaging.artifacts.ArtifactType; +import com.intellij.packaging.elements.ArtifactRootElement; +import com.intellij.packaging.elements.PackagingElementFactory; import com.intellij.packaging.impl.artifacts.ArtifactUtil; import com.intellij.ui.DocumentAdapter; import com.intellij.ui.HyperlinkLabel; @@ -94,28 +98,29 @@ public class AppEngineSupportProvider extends FacetBasedFrameworkSupportProvider private void addSupport(final Module module, final ModifiableRootModel rootModel, String sdkPath, @Nullable PersistenceApi persistenceApi) { super.addSupport(module, rootModel, null, null); - final VirtualFile descriptorDir = AppEngineWebIntegration.getInstance().suggestParentDirectoryForAppEngineWebXml(module, rootModel); - if (descriptorDir != null) { - createFileFromTemplate(AppEngineTemplateGroupDescriptorFactory.APP_ENGINE_WEB_XML_TEMPLATE, descriptorDir, - AppEngineUtil.APP_ENGINE_WEB_XML_NAME); - } - final AppEngineFacet appEngineFacet = AppEngineFacet.getAppEngineFacetByModule(module); LOG.assertTrue(appEngineFacet != null); final AppEngineFacetConfiguration facetConfiguration = appEngineFacet.getConfiguration(); facetConfiguration.setSdkHomePath(sdkPath); final AppEngineSdk sdk = appEngineFacet.getSdk(); - final Artifact artifact = findContainingArtifact(appEngineFacet); + final Artifact artifact = findOrCreateArtifact(appEngineFacet); + + final VirtualFile descriptorDir = AppEngineWebIntegration.getInstance().suggestParentDirectoryForAppEngineWebXml(module, rootModel); + if (descriptorDir != null) { + VirtualFile descriptor = createFileFromTemplate(AppEngineTemplateGroupDescriptorFactory.APP_ENGINE_WEB_XML_TEMPLATE, descriptorDir, + AppEngineUtil.APP_ENGINE_WEB_XML_NAME); + if (descriptor != null) { + AppEngineWebIntegration.getInstance().addDescriptor(artifact, module.getProject(), descriptor); + } + } final Project project = module.getProject(); AppEngineWebIntegration.getInstance().setupRunConfiguration(rootModel, sdk, artifact, project); final Library apiJar = addProjectLibrary(module, "AppEngine API", sdk.getLibUserDirectoryPath(), VirtualFile.EMPTY_ARRAY); rootModel.addLibraryEntry(apiJar); - if (artifact != null) { - AppEngineWebIntegration.getInstance().addLibraryToArtifact(apiJar, artifact, project); - } + AppEngineWebIntegration.getInstance().addLibraryToArtifact(apiJar, artifact, project); if (persistenceApi != null) { facetConfiguration.setRunEnhancerOnMake(true); @@ -146,21 +151,25 @@ public class AppEngineSupportProvider extends FacetBasedFrameworkSupportProvider } final Library library = addProjectLibrary(module, "AppEngine ORM", sdk.getOrmLibDirectoryPath(), sdk.getOrmLibSources()); rootModel.addLibraryEntry(library); - if (artifact != null) { - AppEngineWebIntegration.getInstance().addLibraryToArtifact(library, artifact, project); - } + AppEngineWebIntegration.getInstance().addLibraryToArtifact(library, artifact, project); } } - @Nullable - private static Artifact findContainingArtifact(AppEngineFacet appEngineFacet) { - final Collection artifacts = ArtifactUtil.getArtifactsContainingModuleOutput(appEngineFacet.getModule()); + @NotNull + private static Artifact findOrCreateArtifact(AppEngineFacet appEngineFacet) { + Module module = appEngineFacet.getModule(); + ArtifactType artifactType = AppEngineWebIntegration.getInstance().getAppEngineTargetArtifactType(); + final Collection artifacts = ArtifactUtil.getArtifactsContainingModuleOutput(module); for (Artifact artifact : artifacts) { - if (AppEngineWebIntegration.getInstance().getAppEngineTargetArtifactType().equals(artifact.getArtifactType())) { + if (artifactType.equals(artifact.getArtifactType())) { return artifact; } } - return null; + ArtifactManager artifactManager = ArtifactManager.getInstance(module.getProject()); + PackagingElementFactory elementFactory = PackagingElementFactory.getInstance(); + ArtifactRootElement root = elementFactory.createArtifactRootElement(); + elementFactory.getOrCreateDirectory(root, "WEB-INF/classes").addOrFindChild(elementFactory.createModuleOutput(module)); + return artifactManager.addArtifact(module.getName(), artifactType, root); } private static Library addProjectLibrary(final Module module, final String name, final String path, final VirtualFile[] sources) { diff --git a/plugins/google-app-engine/source/com/intellij/appengine/facet/AppEngineWebIntegration.java b/plugins/google-app-engine/source/com/intellij/appengine/facet/AppEngineWebIntegration.java index 82076bf1d301..f1d8a67f6779 100644 --- a/plugins/google-app-engine/source/com/intellij/appengine/facet/AppEngineWebIntegration.java +++ b/plugins/google-app-engine/source/com/intellij/appengine/facet/AppEngineWebIntegration.java @@ -52,4 +52,7 @@ public abstract class AppEngineWebIntegration { public abstract void addLibraryToArtifact(@NotNull Library library, @NotNull Artifact artifact, @NotNull Project project); public abstract List getSdkForConfiguredDevServers(); + + public void addDescriptor(@NotNull Artifact artifact, @NotNull Project project, @NotNull VirtualFile descriptor) { + } } diff --git a/plugins/google-app-engine/source/com/intellij/appengine/facet/impl/AppEngineCommunityWebIntegration.java b/plugins/google-app-engine/source/com/intellij/appengine/facet/impl/AppEngineCommunityWebIntegration.java index 060355357829..90ea918678ee 100644 --- a/plugins/google-app-engine/source/com/intellij/appengine/facet/impl/AppEngineCommunityWebIntegration.java +++ b/plugins/google-app-engine/source/com/intellij/appengine/facet/impl/AppEngineCommunityWebIntegration.java @@ -94,4 +94,9 @@ public class AppEngineCommunityWebIntegration extends AppEngineWebIntegration { public List getSdkForConfiguredDevServers() { return Collections.emptyList(); } + + @Override + public void addDescriptor(@NotNull Artifact artifact, @NotNull Project project, @NotNull VirtualFile descriptor) { + ArtifactManager.getInstance(project).addElementsToDirectory(artifact, "WEB-INF", PackagingElementFactory.getInstance().createFileCopy(descriptor.getPath(), null)); + } } diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/actions/generate/GroovyGenerationInfo.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/actions/generate/GroovyGenerationInfo.java index 72b88cdfaa95..90c9b9e00f1f 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/actions/generate/GroovyGenerationInfo.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/actions/generate/GroovyGenerationInfo.java @@ -20,14 +20,18 @@ import com.intellij.codeInsight.generation.PsiGenerationInfo; 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.PsiMember; +import com.intellij.psi.codeStyle.CodeStyleManager; +import com.intellij.psi.javadoc.PsiDocComment; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.util.IncorrectOperationException; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.plugins.groovy.lang.GrReferenceAdjuster; +import org.jetbrains.plugins.groovy.lang.groovydoc.psi.api.GrDocComment; import org.jetbrains.plugins.groovy.lang.lexer.GroovyTokenTypes; import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElement; import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElementFactory; @@ -92,6 +96,19 @@ public class GroovyGenerationInfo extends PsiGenerationInfo } GrReferenceAdjuster.shortenReferences(member); + + adjustDocCommentIfExists(member); + } + + private static void adjustDocCommentIfExists(PsiMember member) { + final PsiElement child = member.getFirstChild(); + if (child instanceof PsiDocComment) { + final Project project = member.getProject(); + final GrDocComment groovyDoc = GroovyPsiElementFactory.getInstance(project).createDocCommentFromText(child.getText()); + child.delete(); + CodeStyleManager.getInstance(project).reformat(member); + member.getParent().addBefore(groovyDoc, member); + } } @Override diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/expressions/GrReferenceExpressionImpl.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/expressions/GrReferenceExpressionImpl.java index 829c73474fd0..284d32d7686c 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/expressions/GrReferenceExpressionImpl.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/expressions/GrReferenceExpressionImpl.java @@ -73,7 +73,6 @@ import org.jetbrains.plugins.groovy.lang.psi.util.PsiUtil; import org.jetbrains.plugins.groovy.lang.resolve.ClosureMissingMethodContributor; import org.jetbrains.plugins.groovy.lang.resolve.ResolveUtil; import org.jetbrains.plugins.groovy.lang.resolve.processors.*; -import org.jetbrains.plugins.groovy.refactoring.GroovyRefactoringUtil; import org.jetbrains.plugins.groovy.util.ResolveProfiler; import java.util.*; @@ -95,7 +94,6 @@ public class GrReferenceExpressionImpl extends GrReferenceElementImpl 0) return classCandidates; + final boolean isLValue = PsiUtil.isLValue(this); String[] accessorNames = isLValue ? GroovyPropertyUtils.suggestSettersName(name) : GroovyPropertyUtils.suggestGettersName(name); List accessorResults = new ArrayList(); @@ -258,22 +258,6 @@ public class GrReferenceExpressionImpl extends GrReferenceElementImpl 0) { - for (GroovyResolveResult candidate : fieldCandidates) { - PsiElement element = candidate.getElement(); - LOG.assertTrue(element != null, candidate); - if (GroovyRefactoringUtil.isLocalVariable(element) && !(element instanceof GrBindingVariable)) { - preferVar = true; - break; - } - } - } - return preferVar; - } - - public GroovyResolveResult[] getCallVariants(GrExpression upToArgument) { return resolveMethodOrProperty(true, upToArgument, true); } diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/expressions/path/GrIndexPropertyImpl.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/expressions/path/GrIndexPropertyImpl.java index 219bf607c1b7..2ce54ad11c7c 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/expressions/path/GrIndexPropertyImpl.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/expressions/path/GrIndexPropertyImpl.java @@ -72,7 +72,10 @@ public class GrIndexPropertyImpl extends GrExpressionImpl implements GrIndexProp GrExpression selected = getInvokedExpression(); PsiType thisType = selected.getType(); - if (thisType == null) return null; + if (thisType == null) { + thisType = TypesUtil.getJavaLangObject(this); + } + GrArgumentList argList = getArgumentList(); @@ -153,7 +156,9 @@ public class GrIndexPropertyImpl extends GrExpressionImpl implements GrIndexProp GrExpression invoked = getInvokedExpression(); PsiType thisType = invoked.getType(); - if (thisType == null) return GroovyResolveResult.EMPTY_ARRAY; + if (thisType == null) { + thisType = TypesUtil.getJavaLangObject(this); + } GrArgumentList argList = getArgumentList(); diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/util/GrClassImplUtil.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/util/GrClassImplUtil.java index 6f0428fea243..a910b1d3b9fc 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/util/GrClassImplUtil.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/util/GrClassImplUtil.java @@ -36,6 +36,8 @@ import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.plugins.groovy.GroovyFileType; +import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.GrModifierList; +import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.annotation.GrAnnotation; import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrField; import org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock; import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.literals.GrLiteral; @@ -47,6 +49,7 @@ import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrAc import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrGdkMethod; import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod; import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrReflectedMethod; +import org.jetbrains.plugins.groovy.lang.psi.api.types.GrCodeReferenceElement; import org.jetbrains.plugins.groovy.lang.psi.impl.GroovyPsiManager; import org.jetbrains.plugins.groovy.lang.psi.impl.PsiImplUtil; import org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions.TypesUtil; @@ -278,10 +281,20 @@ public class GrClassImplUtil { @NotNull ResolveState state, @Nullable PsiElement lastParent, @NotNull PsiElement place) { + if (place instanceof GrCodeReferenceElement && lastParent instanceof GrModifierList) { + final PsiElement possibleAnnotation = PsiTreeUtil.skipParentsOfType(place, GrCodeReferenceElement.class); + if (possibleAnnotation instanceof GrAnnotation && possibleAnnotation.getParent() == lastParent) { + return true; //don't process class members while resolving annotation which annotates current class + } + } + for (final PsiTypeParameter typeParameter : grType.getTypeParameters()) { if (!ResolveUtil.processElement(processor, typeParameter, state)) return false; } + + boolean processInstanceMethods = shouldProcessInstanceMembers(grType, lastParent); + NameHint nameHint = processor.getHint(NameHint.KEY); //todo [DIANA] look more carefully String name = nameHint == null ? null : nameHint.getName(state); @@ -296,7 +309,7 @@ public class GrClassImplUtil { CandidateInfo fieldInfo = fieldsMap.get(name); if (fieldInfo != null) { final PsiField field = (PsiField)fieldInfo.getElement(); - if (!isSameDeclaration(place, field)) { //the same variable declaration + if (processInstanceMember(processInstanceMethods, field) && !isSameDeclaration(place, field)) { //the same variable declaration final PsiSubstitutor finalSubstitutor = PsiClassImplUtil.obtainFinalSubstitutor(field.getContainingClass(), fieldInfo.getSubstitutor(), grType, substitutor, factory, level); @@ -307,7 +320,7 @@ public class GrClassImplUtil { else { for (CandidateInfo info : fieldsMap.values()) { final PsiField field = (PsiField)info.getElement(); - if (!isSameDeclaration(place, field)) { //the same variable declaration + if (processInstanceMember(processInstanceMethods, field) && !isSameDeclaration(place, field)) { //the same variable declaration final PsiSubstitutor finalSubstitutor = PsiClassImplUtil.obtainFinalSubstitutor(field.getContainingClass(), info.getSubstitutor(), grType, substitutor, factory, level); @@ -324,7 +337,7 @@ public class GrClassImplUtil { for (List list : methodsMap.values()) { for (CandidateInfo info : list) { PsiMethod method = (PsiMethod)info.getElement(); - if (!isSameDeclaration(place, method) && isMethodVisible(isPlaceGroovy, method)) { + if (processInstanceMember(processInstanceMethods, method) && !isSameDeclaration(place, method) && isMethodVisible(isPlaceGroovy, method)) { final PsiSubstitutor finalSubstitutor = PsiClassImplUtil.obtainFinalSubstitutor(method.getContainingClass(), info.getSubstitutor(), grType, substitutor, factory, level); @@ -340,7 +353,7 @@ public class GrClassImplUtil { if (byName != null) { for (CandidateInfo info : byName) { PsiMethod method = (PsiMethod)info.getElement(); - if (!isSameDeclaration(place, method) && isMethodVisible(isPlaceGroovy, method)) { + if (processInstanceMember(processInstanceMethods, method) && !isSameDeclaration(place, method) && isMethodVisible(isPlaceGroovy, method)) { final PsiSubstitutor finalSubstitutor = PsiClassImplUtil.obtainFinalSubstitutor(method.getContainingClass(), info.getSubstitutor(), grType, substitutor, factory, level); @@ -373,6 +386,27 @@ public class GrClassImplUtil { return true; } + private static boolean shouldProcessInstanceMembers(@NotNull GrTypeDefinition grType, @Nullable PsiElement lastParent) { + if (lastParent != null) { + final GrModifierList modifierList = grType.getModifierList(); + if (modifierList != null && modifierList.findAnnotation(GroovyCommonClassNames.GROOVY_LANG_CATEGORY) != null) { + return false; + } + } + return true; + } + + private static boolean processInstanceMember(boolean shouldProcessInstance, @NotNull PsiMember member) { + if (shouldProcessInstance) return true; + + if (member instanceof GrReflectedMethod) { + return ((GrReflectedMethod)member).getBaseMethod().hasModifierProperty(PsiModifier.STATIC); + } + else { + return member.hasModifierProperty(PsiModifier.STATIC); + } + } + @NotNull private static List getInnerClassesForResolve(@NotNull final GrTypeDefinition grType, @Nullable final PsiElement lastParent, diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/mvc/MvcFramework.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/mvc/MvcFramework.java index c9c968814d85..05948bb888ec 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/mvc/MvcFramework.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/mvc/MvcFramework.java @@ -389,7 +389,7 @@ public abstract class MvcFramework { final VirtualFile griffonHome = getSdkRoot(module); if (griffonHome != null) { - commandLine.setEnvironment(getSdkHomePropertyName(), FileUtil.toSystemDependentName(griffonHome.getPath())); + commandLine.getEnvironment().put(getSdkHomePropertyName(), FileUtil.toSystemDependentName(griffonHome.getPath())); } final VirtualFile root = findAppRoot(module); diff --git a/plugins/groovy/test/org/jetbrains/plugins/groovy/intentions/GrCreateConstructorMatchingSuperTest.groovy b/plugins/groovy/test/org/jetbrains/plugins/groovy/intentions/GrCreateConstructorMatchingSuperTest.groovy new file mode 100644 index 000000000000..8e450c215b8d --- /dev/null +++ b/plugins/groovy/test/org/jetbrains/plugins/groovy/intentions/GrCreateConstructorMatchingSuperTest.groovy @@ -0,0 +1,52 @@ +/* + * Copyright 2000-2013 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.plugins.groovy.intentions + +/** + * @author Max Medvedev + */ +class GrCreateConstructorMatchingSuperTest extends GrIntentionTestCase { + GrCreateConstructorMatchingSuperTest() { + super('Create constructor matching super') + } + + public void testSuperWithJavaDoc() throws Exception { + myFixture.addClass('''\ +public class Base { + /** + * my doc + */ + public Base(int x) { + } +} +''') + + doTextTest('''\ +class Inheritor extends Base { +} +''', '''\ +class Inheritor extends Base { + /** + * my doc + */ + Inheritor(int x) { + super(x) + } +} +''') + + } +} diff --git a/plugins/groovy/test/org/jetbrains/plugins/groovy/lang/highlighting/GrAssignabilityTest.groovy b/plugins/groovy/test/org/jetbrains/plugins/groovy/lang/highlighting/GrAssignabilityTest.groovy index 992c5bfccc6b..d5dbb5681728 100644 --- a/plugins/groovy/test/org/jetbrains/plugins/groovy/lang/highlighting/GrAssignabilityTest.groovy +++ b/plugins/groovy/test/org/jetbrains/plugins/groovy/lang/highlighting/GrAssignabilityTest.groovy @@ -570,7 +570,7 @@ print i[1] +print a[1, 2] ''') } @@ -632,7 +632,7 @@ i[1] = 2 +a[1, 3] = 2 ''') } diff --git a/plugins/groovy/testdata/refactoring/convertGroovyToJava/codeBlock/unresolvedArrayAccess.java b/plugins/groovy/testdata/refactoring/convertGroovyToJava/codeBlock/unresolvedArrayAccess.java index bf6515e7cb67..dc65c743da98 100644 --- a/plugins/groovy/testdata/refactoring/convertGroovyToJava/codeBlock/unresolvedArrayAccess.java +++ b/plugins/groovy/testdata/refactoring/convertGroovyToJava/codeBlock/unresolvedArrayAccess.java @@ -1,2 +1,2 @@ java.lang.Object foo; -print(foo.getAt(1)); +print(org.codehaus.groovy.runtime.DefaultGroovyMethods.getAt(foo, 1)); diff --git a/plugins/javaFX/common-javaFX-plugin/src/org/jetbrains/plugins/javaFX/packaging/AbstractJavaFxPackager.java b/plugins/javaFX/common-javaFX-plugin/src/org/jetbrains/plugins/javaFX/packaging/AbstractJavaFxPackager.java index 7d5f7c25007b..e4e88132fb8f 100644 --- a/plugins/javaFX/common-javaFX-plugin/src/org/jetbrains/plugins/javaFX/packaging/AbstractJavaFxPackager.java +++ b/plugins/javaFX/common-javaFX-plugin/src/org/jetbrains/plugins/javaFX/packaging/AbstractJavaFxPackager.java @@ -20,6 +20,7 @@ import com.intellij.openapi.application.PathManager; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.text.StringUtil; +import com.intellij.util.ArrayUtilRt; import com.intellij.util.Base64Converter; import com.intellij.util.PathUtilRt; import com.intellij.util.io.ZipUtil; @@ -38,6 +39,7 @@ import java.util.List; */ public abstract class AbstractJavaFxPackager { private static final Logger LOG = Logger.getInstance("#" + AbstractJavaFxPackager.class.getName()); + private static final String JB_JFX_JKS = "jb-jfx.jks"; //artifact description protected String getArtifactRootName() { @@ -84,7 +86,7 @@ public abstract class AbstractJavaFxPackager { tempUnzippedArtifactOutput = FileUtil.createTempDirectory("artifact", "unzipped"); final File artifactOutputFile = new File(zipPath); ZipUtil.extract(artifactOutputFile, tempUnzippedArtifactOutput, null); - copyLibraries(artifactOutputFile.getName(), tempUnzippedArtifactOutput); + copyLibraries(FileUtil.getNameWithoutExtension(artifactOutputFile), tempUnzippedArtifactOutput); } catch (IOException e) { registerJavaFxPackagerError(e); @@ -128,11 +130,15 @@ public abstract class AbstractJavaFxPackager { private void copyLibraries(String zipPath, File tempUnzippedArtifactOutput) throws IOException { final File[] outFiles = new File(getArtifactOutputPath()).listFiles(); if (outFiles != null) { + final String[] generatedItems = new String[] {JB_JFX_JKS, zipPath + ".jar", zipPath + ".jnlp", zipPath + ".html"}; for (File file : outFiles) { - if (file.isFile()) { - final String fileName = file.getName(); - if (fileName.endsWith(".jar") && !zipPath.equals(fileName)) { - FileUtil.copy(file, new File(tempUnzippedArtifactOutput, fileName)); + final String fileName = file.getName(); + if (ArrayUtilRt.find(generatedItems, fileName) < 0) { + final File destination = new File(tempUnzippedArtifactOutput, fileName); + if (file.isFile()) { + FileUtil.copy(file, destination); + } else { + FileUtil.copyDir(file, destination, true); } } } @@ -320,7 +326,7 @@ public abstract class AbstractJavaFxPackager { } private String getKeystore(boolean selfSigning) { - return selfSigning ? getArtifactOutputPath() + File.separator + "jb-jfx.jks" : getKeystore(); + return selfSigning ? getArtifactOutputPath() + File.separator + JB_JFX_JKS : getKeystore(); } private String getStorepass(boolean selfSigning) { diff --git a/plugins/javaFX/common-javaFX-plugin/src/org/jetbrains/plugins/javaFX/packaging/JavaFxAntGenerator.java b/plugins/javaFX/common-javaFX-plugin/src/org/jetbrains/plugins/javaFX/packaging/JavaFxAntGenerator.java index 5c4e56572558..01ff08300845 100644 --- a/plugins/javaFX/common-javaFX-plugin/src/org/jetbrains/plugins/javaFX/packaging/JavaFxAntGenerator.java +++ b/plugins/javaFX/common-javaFX-plugin/src/org/jetbrains/plugins/javaFX/packaging/JavaFxAntGenerator.java @@ -53,13 +53,13 @@ public class JavaFxAntGenerator { topLevelTagsCollector.add(new SimpleTag("fx:fileset", new Pair("id", allButPreloader), new Pair("dir", tempDirPath), new Pair("excludes", preloaderJar), - new Pair("includes", "*.jar"))); + new Pair("includes", "**/*.jar"))); } final String allButSelf = "all_but_" + artifactName; final SimpleTag allButSelfAndPreloader = new SimpleTag("fx:fileset", new Pair("id", allButSelf), new Pair("dir", tempDirPath), - new Pair("includes", "*.jar")); + new Pair("includes", "**/*.jar")); allButSelfAndPreloader.add(new SimpleTag("exclude", new Pair("name", artifactFileName))); if (preloaderJar != null) { allButSelfAndPreloader.add(new SimpleTag("exclude", new Pair("name", preloaderJar))); @@ -69,7 +69,7 @@ public class JavaFxAntGenerator { final String all = "all_" + artifactName; final SimpleTag allIncluded = new SimpleTag("fx:fileset", new Pair("id", all), new Pair("dir", tempDirPath), - new Pair("includes", "*.jar")); + new Pair("includes", "**/*.jar")); topLevelTagsCollector.add(allIncluded); //register application @@ -100,7 +100,7 @@ public class JavaFxAntGenerator { final List fileset2Jar = new ArrayList(); fileset2Jar.add(new Pair("dir", tempDirPath)); - fileset2Jar.add(new Pair("excludes", "*.jar")); + fileset2Jar.add(new Pair("excludes", "**/*.jar")); createJarTag.add(new SimpleTag("fileset", fileset2Jar.toArray(new Pair[fileset2Jar.size()]))); createJarTag.add(createResourcesTag(preloaderFiles, false, allButPreloader, allButSelf, all)); diff --git a/plugins/javaFX/javaFX-CE/testSrc/org/jetbrains/plugins/javaFX/packaging/JavaFxAntTaskTest.java b/plugins/javaFX/javaFX-CE/testSrc/org/jetbrains/plugins/javaFX/packaging/JavaFxAntTaskTest.java index 191304c602c6..0c58204fbc17 100644 --- a/plugins/javaFX/javaFX-CE/testSrc/org/jetbrains/plugins/javaFX/packaging/JavaFxAntTaskTest.java +++ b/plugins/javaFX/javaFX-CE/testSrc/org/jetbrains/plugins/javaFX/packaging/JavaFxAntTaskTest.java @@ -35,18 +35,18 @@ public class JavaFxAntTaskTest extends UsefulTestCase{ private static final String SIGNED = "signed"; public void testJarDeployNoInfo() throws Exception { - doTest("\n" + + doTest("\n" + "\n" + "\n" + "\n" + - "\n" + + "\n" + "\n" + "\n" + "\n" + "\n" + "\n" + "\n" + - "\n" + + "\n" + "\n" + "\n" + "\n" + @@ -64,18 +64,18 @@ public class JavaFxAntTaskTest extends UsefulTestCase{ } public void testJarDeployTitle() throws Exception { - doTest("\n" + + doTest("\n" + "\n" + "\n" + "\n" + - "\n" + + "\n" + "\n" + "\n" + "\n" + "\n" + "\n" + "\n" + - "\n" + + "\n" + "\n" + "\n" + "\n" + @@ -95,18 +95,18 @@ public class JavaFxAntTaskTest extends UsefulTestCase{ } public void testJarDeploySigned() throws Exception { - doTest("\n" + + doTest("\n" + "\n" + "\n" + "\n" + - "\n" + + "\n" + "\n" + "\n" + "\n" + "\n" + "\n" + "\n" + - "\n" + + "\n" + "\n" + "\n" + "\n" + @@ -131,22 +131,22 @@ public class JavaFxAntTaskTest extends UsefulTestCase{ options.put(PRELOADER_JAR, "preloader.jar"); doTest("\n" + "\n" + - "\n" + + "\n" + "\n" + - "\n" + + "\n" + "\n" + "\n" + "\n" + "\n" + "\n" + - "\n" + + "\n" + "\n" + "\n" + "\n" + "\n" + "\n" + "\n" + - "\n" + + "\n" + "\n" + "\n" + "\n" + diff --git a/plugins/javaFX/src/org/jetbrains/plugins/javaFX/fxml/refs/JavaFxControllerFieldSearcher.java b/plugins/javaFX/src/org/jetbrains/plugins/javaFX/fxml/refs/JavaFxControllerFieldSearcher.java index 6f09d6fb4932..3e9fc9efa3c6 100644 --- a/plugins/javaFX/src/org/jetbrains/plugins/javaFX/fxml/refs/JavaFxControllerFieldSearcher.java +++ b/plugins/javaFX/src/org/jetbrains/plugins/javaFX/fxml/refs/JavaFxControllerFieldSearcher.java @@ -70,11 +70,11 @@ public class JavaFxControllerFieldSearcher implements QueryExecutor paths) { if (paths == null) return; - assertUnorderedElementsAreEqual(lib.getRootUrls(type), ArrayUtil.toStringArray(paths)); + assertUnorderedPathsAreEqual(Arrays.asList(lib.getRootUrls(type)), paths); // also check the library because it may contain slight different set of urls (e.g. with duplicates) - assertUnorderedElementsAreEqual(lib.getLibrary().getUrls(type), ArrayUtil.toStringArray(paths)); + assertUnorderedPathsAreEqual(Arrays.asList(lib.getLibrary().getUrls(type)), paths); } protected void assertModuleLibDepScope(String moduleName, String depName, DependencyScope scope) { diff --git a/plugins/maven/src/test/java/org/jetbrains/idea/maven/MavenTestCase.java b/plugins/maven/src/test/java/org/jetbrains/idea/maven/MavenTestCase.java index dcf900e1f087..ef8e43f78829 100644 --- a/plugins/maven/src/test/java/org/jetbrains/idea/maven/MavenTestCase.java +++ b/plugins/maven/src/test/java/org/jetbrains/idea/maven/MavenTestCase.java @@ -35,6 +35,7 @@ import com.intellij.testFramework.UsefulTestCase; import com.intellij.testFramework.fixtures.IdeaProjectTestFixture; import com.intellij.testFramework.fixtures.IdeaTestFixtureFactory; import com.intellij.util.ui.UIUtil; +import gnu.trove.THashSet; import org.intellij.lang.annotations.Language; import org.jetbrains.annotations.NonNls; import org.jetbrains.idea.maven.indices.MavenIndicesManager; @@ -497,6 +498,9 @@ public abstract class MavenTestCase extends UsefulTestCase { protected static void assertUnorderedElementsAreEqual(Collection actual, Collection expected) { assertEquals(new HashSet(expected), new HashSet(actual)); } + protected static void assertUnorderedPathsAreEqual(Collection actual, Collection expected) { + assertEquals(new THashSet(expected, FileUtil.PATH_HASHING_STRATEGY), new THashSet(actual, FileUtil.PATH_HASHING_STRATEGY)); + } protected static void assertUnorderedElementsAreEqual(T[] actual, T... expected) { assertUnorderedElementsAreEqual(Arrays.asList(actual), expected); diff --git a/plugins/maven/src/test/java/org/jetbrains/idea/maven/execution/MavenResolveToWorkspaceTest.java b/plugins/maven/src/test/java/org/jetbrains/idea/maven/execution/MavenResolveToWorkspaceTest.java index 3cfb1a4ca46d..4cf5b79a615b 100644 --- a/plugins/maven/src/test/java/org/jetbrains/idea/maven/execution/MavenResolveToWorkspaceTest.java +++ b/plugins/maven/src/test/java/org/jetbrains/idea/maven/execution/MavenResolveToWorkspaceTest.java @@ -35,9 +35,9 @@ import java.util.Properties; /** * @author Sergey Evdokimov */ -public class MavenResolveToWorkspaceTest extends MavenImportingTestCase { +public abstract class MavenResolveToWorkspaceTest extends MavenImportingTestCase { - public void _testIgnoredProject() throws Exception { + public void testIgnoredProject() throws Exception { createProjectPom("test" + "project" + "1" + diff --git a/plugins/maven/src/test/java/org/jetbrains/idea/maven/importing/FacetImporterTestCase.java b/plugins/maven/src/test/java/org/jetbrains/idea/maven/importing/FacetImporterTestCase.java index 0c11426e5a1f..31ae08162462 100644 --- a/plugins/maven/src/test/java/org/jetbrains/idea/maven/importing/FacetImporterTestCase.java +++ b/plugins/maven/src/test/java/org/jetbrains/idea/maven/importing/FacetImporterTestCase.java @@ -3,8 +3,7 @@ package org.jetbrains.idea.maven.importing; import com.intellij.facet.Facet; import com.intellij.facet.FacetManager; import com.intellij.facet.FacetType; -import com.intellij.openapi.vfs.VfsUtil; -import com.intellij.util.ArrayUtil; +import com.intellij.openapi.vfs.VfsUtilCore; import org.jetbrains.idea.maven.MavenImportingTestCase; import java.util.ArrayList; @@ -25,11 +24,11 @@ public abstract class FacetImporterTestCase expectedRootUrls = new ArrayList(); for (String r : roots) { - String url = VfsUtil.pathToUrl(getProjectPath() + "/" + r); + String url = VfsUtilCore.pathToUrl(getProjectPath() + "/" + r); expectedRootUrls.add(url); } - assertUnorderedElementsAreEqual(actualRoots, ArrayUtil.toStringArray(expectedRootUrls)); + assertUnorderedPathsAreEqual(actualRoots, expectedRootUrls); } protected FACET_TYPE getFacet(String module) { diff --git a/plugins/maven/src/test/java/org/jetbrains/idea/maven/importing/FoldersImportingTest.java b/plugins/maven/src/test/java/org/jetbrains/idea/maven/importing/FoldersImportingTest.java index 248c3cd67b97..fa0857650c3c 100644 --- a/plugins/maven/src/test/java/org/jetbrains/idea/maven/importing/FoldersImportingTest.java +++ b/plugins/maven/src/test/java/org/jetbrains/idea/maven/importing/FoldersImportingTest.java @@ -608,6 +608,25 @@ public class FoldersImportingTest extends MavenImportingTestCase { "target/generated-sources"); } + public void testIgnoreGeneratedSources() throws Exception { + createStdProjectFolders(); + + MavenProjectsManager.getInstance(myProject).getImportingSettings().setGeneratedSourcesFolder( + MavenImportingSettings.GeneratedSourcesFolder.IGNORE); + + createProjectSubFile("target/generated-sources/annotations/A.java", "package com; class A {}"); + createProjectSubFile("target/generated-sources/annotations/com/B.java", "package com; class B {}"); + + importProject("test" + + "project" + + "1"); + + assertSources("project", + "src/main/java", + "src/main/resources"); + } + + public void testAddingExistingGeneratedSources4() throws Exception { createStdProjectFolders(); diff --git a/plugins/maven/src/test/java/org/jetbrains/idea/maven/importing/GroovyImporterTest.java b/plugins/maven/src/test/java/org/jetbrains/idea/maven/importing/GroovyImporterTest.java index be05c84b78bc..9cf632dc956d 100644 --- a/plugins/maven/src/test/java/org/jetbrains/idea/maven/importing/GroovyImporterTest.java +++ b/plugins/maven/src/test/java/org/jetbrains/idea/maven/importing/GroovyImporterTest.java @@ -8,11 +8,10 @@ import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.roots.OrderRootType; import com.intellij.openapi.roots.libraries.Library; import org.jetbrains.idea.maven.MavenImportingTestCase; -import org.jetbrains.idea.maven.importing.MavenDefaultModifiableModelsProvider; -import org.jetbrains.idea.maven.importing.MavenRootModelAdapter; import org.jetbrains.plugins.groovy.config.GroovyConfigUtils; import java.io.File; +import java.util.Arrays; public class GroovyImporterTest extends MavenImportingTestCase { @Override @@ -67,9 +66,9 @@ public class GroovyImporterTest extends MavenImportingTestCase { Library[] libraries = GroovyConfigUtils.getInstance().getSDKLibrariesByModule(getModule("project")); assertTrue("unexpected groovy libs configuration: " + libraries.length, libraries.length > 0); Library library = libraries[0]; - assertUnorderedElementsAreEqual( - library.getUrls(OrderRootType.CLASSES), - "jar://" + getRepositoryPath() + "/org/codehaus/groovy/groovy-all-minimal/1.5.6/groovy-all-minimal-1.5.6.jar!/"); + assertUnorderedPathsAreEqual( + Arrays.asList(library.getUrls(OrderRootType.CLASSES)), + Arrays.asList("jar://" + getRepositoryPath() + "/org/codehaus/groovy/groovy-all-minimal/1.5.6/groovy-all-minimal-1.5.6.jar!/")); } public void testAddingGroovySpecificSources() throws Exception { diff --git a/plugins/maven/src/test/java/org/jetbrains/idea/maven/project/MavenProjectsManagerTest.java b/plugins/maven/src/test/java/org/jetbrains/idea/maven/project/MavenProjectsManagerTest.java index cee2ec718491..ac9b17abe4c8 100644 --- a/plugins/maven/src/test/java/org/jetbrains/idea/maven/project/MavenProjectsManagerTest.java +++ b/plugins/maven/src/test/java/org/jetbrains/idea/maven/project/MavenProjectsManagerTest.java @@ -371,8 +371,8 @@ public class MavenProjectsManagerTest extends MavenImportingTestCase { MavenProject parentNode = roots.get(0); MavenProject childNode = myProjectsTree.getModules(roots.get(0)).get(0); - assertUnorderedElementsAreEqual(parentNode.getSources(), FileUtil.toSystemDependentName(getProjectPath() + "/value1")); - assertUnorderedElementsAreEqual(childNode.getSources(), FileUtil.toSystemDependentName(getProjectPath() + "/m/value1")); + assertUnorderedPathsAreEqual(parentNode.getSources(), Arrays.asList(FileUtil.toSystemDependentName(getProjectPath() + "/value1"))); + assertUnorderedPathsAreEqual(childNode.getSources(), Arrays.asList(FileUtil.toSystemDependentName(getProjectPath() + "/m/value1"))); updateSettingsXml("" + " " + @@ -387,14 +387,14 @@ public class MavenProjectsManagerTest extends MavenImportingTestCase { ""); waitForReadingCompletion(); - assertUnorderedElementsAreEqual(parentNode.getSources(), FileUtil.toSystemDependentName(getProjectPath() + "/value2")); - assertUnorderedElementsAreEqual(childNode.getSources(), FileUtil.toSystemDependentName(getProjectPath() + "/m/value2")); + assertUnorderedPathsAreEqual(parentNode.getSources(), Arrays.asList(FileUtil.toSystemDependentName(getProjectPath() + "/value2"))); + assertUnorderedPathsAreEqual(childNode.getSources(), Arrays.asList(FileUtil.toSystemDependentName(getProjectPath() + "/m/value2"))); deleteSettingsXml(); waitForReadingCompletion(); - assertUnorderedElementsAreEqual(parentNode.getSources(), FileUtil.toSystemDependentName(getProjectPath() + "/${prop}")); - assertUnorderedElementsAreEqual(childNode.getSources(), FileUtil.toSystemDependentName(getProjectPath() + "/m/${prop}")); + assertUnorderedPathsAreEqual(parentNode.getSources(), Arrays.asList(FileUtil.toSystemDependentName(getProjectPath() + "/${prop}"))); + assertUnorderedPathsAreEqual(childNode.getSources(), Arrays.asList(FileUtil.toSystemDependentName(getProjectPath() + "/m/${prop}"))); updateSettingsXml("" + " " + @@ -409,8 +409,8 @@ public class MavenProjectsManagerTest extends MavenImportingTestCase { ""); waitForReadingCompletion(); - assertUnorderedElementsAreEqual(parentNode.getSources(), FileUtil.toSystemDependentName(getProjectPath() + "/value2")); - assertUnorderedElementsAreEqual(childNode.getSources(), FileUtil.toSystemDependentName(getProjectPath() + "/m/value2")); + assertUnorderedPathsAreEqual(parentNode.getSources(), Arrays.asList(FileUtil.toSystemDependentName(getProjectPath() + "/value2"))); + assertUnorderedPathsAreEqual(childNode.getSources(), Arrays.asList(FileUtil.toSystemDependentName(getProjectPath() + "/m/value2"))); } public void testUpdatingProjectsWhenSettingsXmlLocationIsChanged() throws Exception { @@ -461,20 +461,20 @@ public class MavenProjectsManagerTest extends MavenImportingTestCase { MavenProject parentNode = roots.get(0); MavenProject childNode = myProjectsTree.getModules(roots.get(0)).get(0); - assertUnorderedElementsAreEqual(parentNode.getSources(), FileUtil.toSystemDependentName(getProjectPath() + "/value1")); - assertUnorderedElementsAreEqual(childNode.getSources(), FileUtil.toSystemDependentName(getProjectPath() + "/m/value1")); + assertUnorderedPathsAreEqual(parentNode.getSources(), Arrays.asList(FileUtil.toSystemDependentName(getProjectPath() + "/value1"))); + assertUnorderedPathsAreEqual(childNode.getSources(), Arrays.asList(FileUtil.toSystemDependentName(getProjectPath() + "/m/value1"))); getMavenGeneralSettings().setUserSettingsFile(""); waitForReadingCompletion(); - assertUnorderedElementsAreEqual(parentNode.getSources(), FileUtil.toSystemDependentName(getProjectPath() + "/${prop}")); - assertUnorderedElementsAreEqual(childNode.getSources(), FileUtil.toSystemDependentName(getProjectPath() + "/m/${prop}")); + assertUnorderedPathsAreEqual(parentNode.getSources(), Arrays.asList(FileUtil.toSystemDependentName(getProjectPath() + "/${prop}"))); + assertUnorderedPathsAreEqual(childNode.getSources(), Arrays.asList(FileUtil.toSystemDependentName(getProjectPath() + "/m/${prop}"))); getMavenGeneralSettings().setUserSettingsFile(new File(myDir, "settings.xml").getPath()); waitForReadingCompletion(); - assertUnorderedElementsAreEqual(parentNode.getSources(), FileUtil.toSystemDependentName(getProjectPath() + "/value1")); - assertUnorderedElementsAreEqual(childNode.getSources(), FileUtil.toSystemDependentName(getProjectPath() + "/m/value1")); + assertUnorderedPathsAreEqual(parentNode.getSources(), Arrays.asList(FileUtil.toSystemDependentName(getProjectPath() + "/value1"))); + assertUnorderedPathsAreEqual(childNode.getSources(), Arrays.asList(FileUtil.toSystemDependentName(getProjectPath() + "/m/value1"))); } public void testUpdatingProjectsOnSettingsXmlCreationAndDeletion() throws Exception { @@ -586,8 +586,8 @@ public class MavenProjectsManagerTest extends MavenImportingTestCase { MavenProject parentNode = roots.get(0); MavenProject childNode = myProjectsTree.getModules(roots.get(0)).get(0); - assertUnorderedElementsAreEqual(parentNode.getSources(), FileUtil.toSystemDependentName(getProjectPath() + "/value1")); - assertUnorderedElementsAreEqual(childNode.getSources(), FileUtil.toSystemDependentName(getProjectPath() + "/m/value1")); + assertUnorderedPathsAreEqual(parentNode.getSources(), Arrays.asList(FileUtil.toSystemDependentName(getProjectPath() + "/value1"))); + assertUnorderedPathsAreEqual(childNode.getSources(), Arrays.asList(FileUtil.toSystemDependentName(getProjectPath() + "/m/value1"))); createProfilesXmlOldStyle("" + " one" + @@ -600,14 +600,14 @@ public class MavenProjectsManagerTest extends MavenImportingTestCase { ""); waitForReadingCompletion(); - assertUnorderedElementsAreEqual(parentNode.getSources(), FileUtil.toSystemDependentName(getProjectPath() + "/value2")); - assertUnorderedElementsAreEqual(childNode.getSources(), FileUtil.toSystemDependentName(getProjectPath() + "/m/value2")); + assertUnorderedPathsAreEqual(parentNode.getSources(), Arrays.asList(FileUtil.toSystemDependentName(getProjectPath() + "/value2"))); + assertUnorderedPathsAreEqual(childNode.getSources(), Arrays.asList(FileUtil.toSystemDependentName(getProjectPath() + "/m/value2"))); deleteProfilesXml(); waitForReadingCompletion(); - assertUnorderedElementsAreEqual(parentNode.getSources(), FileUtil.toSystemDependentName(getProjectPath() + "/${prop}")); - assertUnorderedElementsAreEqual(childNode.getSources(), FileUtil.toSystemDependentName(getProjectPath() + "/m/${prop}")); + assertUnorderedPathsAreEqual(parentNode.getSources(), Arrays.asList(FileUtil.toSystemDependentName(getProjectPath() + "/${prop}"))); + assertUnorderedPathsAreEqual(childNode.getSources(), Arrays.asList(FileUtil.toSystemDependentName(getProjectPath() + "/m/${prop}"))); createProfilesXmlOldStyle("" + " one" + @@ -620,8 +620,8 @@ public class MavenProjectsManagerTest extends MavenImportingTestCase { ""); waitForReadingCompletion(); - assertUnorderedElementsAreEqual(parentNode.getSources(), FileUtil.toSystemDependentName(getProjectPath() + "/value2")); - assertUnorderedElementsAreEqual(childNode.getSources(), FileUtil.toSystemDependentName(getProjectPath() + "/m/value2")); + assertUnorderedPathsAreEqual(parentNode.getSources(), Arrays.asList(FileUtil.toSystemDependentName(getProjectPath() + "/value2"))); + assertUnorderedPathsAreEqual(childNode.getSources(), Arrays.asList(FileUtil.toSystemDependentName(getProjectPath() + "/m/value2"))); } public void testHandlingDirectoryWithPomFileDeletion() throws Exception { @@ -691,9 +691,9 @@ public class MavenProjectsManagerTest extends MavenImportingTestCase { myProjectsManager.setIgnoredFilesPatterns(Arrays.asList("*.xxx")); state = myProjectsManager.getState(); - assertUnorderedElementsAreEqual(state.originalFiles, p1.getPath(), p2.getPath()); + assertUnorderedPathsAreEqual(state.originalFiles, Arrays.asList(p1.getPath(), p2.getPath())); assertUnorderedElementsAreEqual(MavenWorkspaceSettingsComponent.getInstance(myProject).getState().enabledProfiles, "one", "two"); - assertUnorderedElementsAreEqual(state.ignoredFiles, p1.getPath()); + assertUnorderedPathsAreEqual(state.ignoredFiles, Arrays.asList(p1.getPath())); assertUnorderedElementsAreEqual(state.ignoredPathMasks, "*.xxx"); MavenProjectsManagerState newState = new MavenProjectsManagerState(); @@ -705,10 +705,10 @@ public class MavenProjectsManagerTest extends MavenImportingTestCase { myProjectsManager.loadState(newState); - assertUnorderedElementsAreEqual(myProjectsManager.getProjectsTreeForTests().getManagedFilesPaths(), - p1.getPath(), p3.getPath()); + assertUnorderedPathsAreEqual(myProjectsManager.getProjectsTreeForTests().getManagedFilesPaths(), + Arrays.asList(p1.getPath(), p3.getPath())); assertUnorderedElementsAreEqual(myProjectsManager.getExplicitProfiles(), "three"); - assertUnorderedElementsAreEqual(myProjectsManager.getIgnoredFilesPaths(), p1.getPath()); + assertUnorderedPathsAreEqual(myProjectsManager.getIgnoredFilesPaths(), Arrays.asList(p1.getPath())); assertUnorderedElementsAreEqual(myProjectsManager.getIgnoredFilesPatterns(), "*.zzz"); waitForReadingCompletion(); diff --git a/plugins/maven/src/test/java/org/jetbrains/idea/maven/project/MavenProjectsTreeReadingTest.java b/plugins/maven/src/test/java/org/jetbrains/idea/maven/project/MavenProjectsTreeReadingTest.java index 0f594ce41042..2f118ed2b79f 100644 --- a/plugins/maven/src/test/java/org/jetbrains/idea/maven/project/MavenProjectsTreeReadingTest.java +++ b/plugins/maven/src/test/java/org/jetbrains/idea/maven/project/MavenProjectsTreeReadingTest.java @@ -1594,13 +1594,13 @@ public class MavenProjectsTreeReadingTest extends MavenProjectsTreeTestCase { MavenProject parentNode = roots.get(0); MavenProject childNode = myTree.getModules(roots.get(0)).get(0); - assertUnorderedElementsAreEqual(parentNode.getSources(), FileUtil.toSystemDependentName(getProjectPath() + "/value1")); - assertUnorderedElementsAreEqual(childNode.getSources(), FileUtil.toSystemDependentName(getProjectPath() + "/m/value1")); + assertUnorderedPathsAreEqual(parentNode.getSources(), Arrays.asList(FileUtil.toSystemDependentName(getProjectPath() + "/value1"))); + assertUnorderedPathsAreEqual(childNode.getSources(), Arrays.asList(FileUtil.toSystemDependentName(getProjectPath() + "/m/value1"))); updateAll(Arrays.asList("two"), myProjectPom); - assertUnorderedElementsAreEqual(parentNode.getSources(), FileUtil.toSystemDependentName(getProjectPath() + "/value2")); - assertUnorderedElementsAreEqual(childNode.getSources(), FileUtil.toSystemDependentName(getProjectPath() + "/m/value2")); + assertUnorderedPathsAreEqual(parentNode.getSources(), Arrays.asList(FileUtil.toSystemDependentName(getProjectPath() + "/value2"))); + assertUnorderedPathsAreEqual(childNode.getSources(), Arrays.asList(FileUtil.toSystemDependentName(getProjectPath() + "/m/value2"))); } public void testUpdatingModelWhenProfilesXmlChange() throws Exception { @@ -1628,7 +1628,7 @@ public class MavenProjectsTreeReadingTest extends MavenProjectsTreeTestCase { List roots = myTree.getRootProjects(); MavenProject project = roots.get(0); - assertUnorderedElementsAreEqual(project.getSources(), FileUtil.toSystemDependentName(getProjectPath() + "/value1")); + assertUnorderedPathsAreEqual(project.getSources(), Arrays.asList(FileUtil.toSystemDependentName(getProjectPath() + "/value1"))); createProfilesXmlOldStyle("" + " one" + @@ -1642,7 +1642,7 @@ public class MavenProjectsTreeReadingTest extends MavenProjectsTreeTestCase { updateAll(myProjectPom); - assertUnorderedElementsAreEqual(project.getSources(), FileUtil.toSystemDependentName(getProjectPath() + "/value2")); + assertUnorderedPathsAreEqual(project.getSources(), Arrays.asList(FileUtil.toSystemDependentName(getProjectPath() + "/value2"))); } public void testUpdatingModelWhenParentProfilesXmlChange() throws Exception { @@ -1683,7 +1683,7 @@ public class MavenProjectsTreeReadingTest extends MavenProjectsTreeTestCase { List roots = myTree.getRootProjects(); MavenProject childProject = roots.get(1); - assertUnorderedElementsAreEqual(childProject.getSources(), FileUtil.toSystemDependentName(getProjectPath() + "/m/value1")); + assertUnorderedPathsAreEqual(childProject.getSources(), Arrays.asList(FileUtil.toSystemDependentName(getProjectPath() + "/m/value1"))); createProfilesXmlOldStyle("parent", "" + @@ -1697,7 +1697,7 @@ public class MavenProjectsTreeReadingTest extends MavenProjectsTreeTestCase { ""); update(parent); - assertUnorderedElementsAreEqual(childProject.getSources(), FileUtil.toSystemDependentName(getProjectPath() + "/m/value2")); + assertUnorderedPathsAreEqual(childProject.getSources(), Arrays.asList(FileUtil.toSystemDependentName(getProjectPath() + "/m/value2"))); } public void testUpdatingModelWhenParentProfilesXmlChangeAndItIsAModuleAlso() throws Exception { @@ -1738,7 +1738,7 @@ public class MavenProjectsTreeReadingTest extends MavenProjectsTreeTestCase { updateAll(myProjectPom); MavenProject childNode = myTree.getModules(myTree.getRootProjects().get(0)).get(0); - assertUnorderedElementsAreEqual(childNode.getSources(), FileUtil.toSystemDependentName(getProjectPath() + "/m/value1")); + assertUnorderedPathsAreEqual(childNode.getSources(), Arrays.asList(FileUtil.toSystemDependentName(getProjectPath() + "/m/value1"))); createProfilesXmlOldStyle("" + " one" + @@ -1751,7 +1751,7 @@ public class MavenProjectsTreeReadingTest extends MavenProjectsTreeTestCase { ""); updateAll(myProjectPom); - assertUnorderedElementsAreEqual(childNode.getSources(), FileUtil.toSystemDependentName(getProjectPath() + "/m/value2")); + assertUnorderedPathsAreEqual(childNode.getSources(), Arrays.asList(FileUtil.toSystemDependentName(getProjectPath() + "/m/value2"))); } public void testDoNotUpdateModelWhenAggregatorProfilesXmlChange() throws Exception { diff --git a/spellchecker/src/com/intellij/spellchecker/SpellCheckerManager.java b/spellchecker/src/com/intellij/spellchecker/SpellCheckerManager.java index 7df9cfa8f6d1..b9d63d442292 100644 --- a/spellchecker/src/com/intellij/spellchecker/SpellCheckerManager.java +++ b/spellchecker/src/com/intellij/spellchecker/SpellCheckerManager.java @@ -80,7 +80,7 @@ public class SpellCheckerManager { public void updateBundledDictionaries(final List removedDictionaries) { for (BundledDictionaryProvider provider : Extensions.getExtensions(BundledDictionaryProvider.EP_NAME)) { for (String dictionary : provider.getBundledDictionaries()) { - boolean dictionaryShouldBeLoad = this.settings == null || !this.settings.getBundledDisabledDictionariesPaths().contains(dictionary); + boolean dictionaryShouldBeLoad = settings == null || !settings.getBundledDisabledDictionariesPaths().contains(dictionary); boolean dictionaryIsLoad = spellChecker.isDictionaryLoad(dictionary); if (dictionaryIsLoad && !dictionaryShouldBeLoad) { spellChecker.removeDictionary(dictionary); @@ -97,10 +97,11 @@ public class SpellCheckerManager { } } } - if (this.settings != null && this.settings.getDictionaryFoldersPaths() != null) { + if (settings != null && settings.getDictionaryFoldersPaths() != null) { final Set disabledDictionaries = settings.getDisabledDictionariesPaths(); - for (String folder : this.settings.getDictionaryFoldersPaths()) { + for (String folder : settings.getDictionaryFoldersPaths()) { SPFileUtil.processFilesRecursively(folder, new Consumer() { + @Override public void consume(final String s) { boolean dictionaryShouldBeLoad =!disabledDictionaries.contains(s); boolean dictionaryIsLoad = spellChecker.isDictionaryLoad(s); @@ -116,13 +117,13 @@ public class SpellCheckerManager { } } - - if (removedDictionaries != null && removedDictionaries.size() > 0) { + + if (removedDictionaries != null && !removedDictionaries.isEmpty()) { for (final String name : removedDictionaries) { spellChecker.removeDictionary(name); } } - + restartInspections(); } @@ -138,6 +139,7 @@ public class SpellCheckerManager { spellChecker.reset(); final StateLoader stateLoader = new StateLoader(project); stateLoader.load(new Consumer() { + @Override public void consume(String s) { //do nothing - in this loader we don't worry about word list itself - the whole dictionary will be restored } @@ -146,7 +148,7 @@ public class SpellCheckerManager { // Load bundled dictionaries from corresponding jars for (BundledDictionaryProvider provider : Extensions.getExtensions(BundledDictionaryProvider.EP_NAME)) { for (String dictionary : provider.getBundledDictionaries()) { - if (this.settings == null || !this.settings.getBundledDisabledDictionariesPaths().contains(dictionary)) { + if (settings == null || !settings.getBundledDisabledDictionariesPaths().contains(dictionary)) { final Class loaderClass = provider.getClass(); final InputStream stream = loaderClass.getResourceAsStream(dictionary); if (stream != null) { @@ -158,10 +160,11 @@ public class SpellCheckerManager { } } } - if (this.settings != null && this.settings.getDictionaryFoldersPaths() != null) { + if (settings != null && settings.getDictionaryFoldersPaths() != null) { final Set disabledDictionaries = settings.getDisabledDictionariesPaths(); - for (String folder : this.settings.getDictionaryFoldersPaths()) { + for (String folder : settings.getDictionaryFoldersPaths()) { SPFileUtil.processFilesRecursively(folder, new Consumer() { + @Override public void consume(final String s) { if (!disabledDictionaries.contains(s)) { loaders.add(new FileLoader(s, s)); @@ -225,7 +228,7 @@ public class SpellCheckerManager { protected List getRawSuggestions(@NotNull String word) { if (!spellChecker.isCorrect(word)) { List suggestions = spellChecker.getSuggestions(word, MAX_SUGGESTIONS_THRESHOLD, MAX_METRICS); - if (suggestions.size() != 0) { + if (!suggestions.isEmpty()) { boolean capitalized = Strings.isCapitalized(word); boolean upperCases = Strings.isUpperCase(word); if (capitalized) { @@ -249,6 +252,7 @@ public class SpellCheckerManager { public static void restartInspections() { ApplicationManager.getApplication().invokeLater(new Runnable() { + @Override public void run() { Project[] projects = ProjectManager.getInstance().getOpenProjects(); for (Project project : projects) { diff --git a/spellchecker/src/com/intellij/spellchecker/compress/CompressedDictionary.java b/spellchecker/src/com/intellij/spellchecker/compress/CompressedDictionary.java index 1f5f4e63647f..2e7587ff2c9f 100644 --- a/spellchecker/src/com/intellij/spellchecker/compress/CompressedDictionary.java +++ b/spellchecker/src/com/intellij/spellchecker/compress/CompressedDictionary.java @@ -28,7 +28,6 @@ import org.jetbrains.annotations.Nullable; import java.util.*; public final class CompressedDictionary implements Dictionary { - private final Alphabet alphabet; private int wordsCount; private byte[][] words; @@ -39,6 +38,7 @@ public final class CompressedDictionary implements Dictionary { private TIntObjectHashMap> rawData = new TIntObjectHashMap>(); private static final Comparator COMPARATOR = new Comparator() { + @Override public int compare(byte[] o1, byte[] o2) { return compareArrays(o1, o2); } @@ -50,7 +50,7 @@ public final class CompressedDictionary implements Dictionary { this.name = name; } - void addToDictionary(byte[] word) { + void addToDictionary(@NotNull byte[] word) { SortedSet set = rawData.get(word.length); if (set == null) { set = createSet(); @@ -82,11 +82,12 @@ public final class CompressedDictionary implements Dictionary { rawData = null; } + @NotNull private static SortedSet createSet() { return new TreeSet(COMPARATOR); - } + @NotNull public List getWords(char first, int minLength, int maxLength) { int index = alphabet.getIndex(first, false); List result = new ArrayList(); @@ -111,19 +112,20 @@ public final class CompressedDictionary implements Dictionary { return result; } + @NotNull public List getWords(char first) { return getWords(first, 0, Integer.MAX_VALUE); } + @NotNull + @Override public String getName() { return name; } + @Override @Nullable - public Boolean contains(String word) { - if (word == null) { - return false; - } + public Boolean contains(@NotNull String word) { UnitBitSet bs = encoder.encode(word, false); if (bs == Encoder.WORD_OF_ENTIRELY_UNKNOWN_LETTERS) return null; @@ -141,18 +143,22 @@ public final class CompressedDictionary implements Dictionary { } + @Override public boolean isEmpty() { return wordsCount <= 0; } - public void traverse(Consumer action) { + @Override + public void traverse(@NotNull Consumer action) { throw new UnsupportedOperationException(); } + @Override public Set getWords() { throw new UnsupportedOperationException(); } + @Override public int size() { return wordsCount; } @@ -167,11 +173,13 @@ public final class CompressedDictionary implements Dictionary { return sb.toString(); } + @NotNull public static CompressedDictionary create(@NotNull Loader loader, @NotNull final Transformation transform) { Alphabet alphabet = new Alphabet(); final Encoder encoder = new Encoder(alphabet); final CompressedDictionary dictionary = new CompressedDictionary(alphabet, encoder, loader.getName()); loader.load(new Consumer() { + @Override public void consume(String s) { String transformed = transform.transform(s); if (transformed != null) { @@ -186,16 +194,20 @@ public final class CompressedDictionary implements Dictionary { return dictionary; } - public static int compareArrays(byte[] array1, byte[] array2) { - if (array1.length != array2.length) { - return array1.length < array2.length ? -1 : 1; + public static int compareArrays(@NotNull byte[] array1, @NotNull byte[] array2) { + return compareArrays(array1, 0, array1.length, array2); + } + private static int compareArrays(@NotNull byte[] array1, int start1, int length1, @NotNull byte[] array2) { + if (length1 != array2.length) { + return length1 < array2.length ? -1 : 1; } //compare elements values - for (int i = 0; i < array1.length; i++) { - if (array1[i] < array2[i]) { + for (int i = 0; i < length1; i++) { + int d = array1[i+start1] - array2[i]; + if (d < 0) { return -1; } - else if (array1[i] > array2[i]) { + else if (d > 0) { return 1; } } @@ -203,19 +215,17 @@ public final class CompressedDictionary implements Dictionary { } - public static boolean contains(byte[] goal, byte[] data) { + public static boolean contains(@NotNull byte[] goal, @NotNull byte[] data) { return binarySearchNew(goal, 0, data.length / goal.length, data) >= 0; } - public static int binarySearchNew(byte[] goal, int fromIndex, int toIndex, byte[] data) { + public static int binarySearchNew(@NotNull byte[] goal, int fromIndex, int toIndex, @NotNull byte[] data) { int unitLength = goal.length; int low = fromIndex; int high = toIndex - 1; while (low <= high) { int mid = low + high >>> 1; - byte[] toTest = new byte[unitLength]; - System.arraycopy(data, mid * unitLength, toTest, 0, unitLength); - int check = compareArrays(toTest, goal); + int check = compareArrays(data, mid * unitLength, unitLength, goal); if (check == -1) { low = mid + 1; } @@ -228,6 +238,4 @@ public final class CompressedDictionary implements Dictionary { } return -(low + 1); // key not found. } - - } diff --git a/spellchecker/src/com/intellij/spellchecker/dictionary/AggregatedDictionary.java b/spellchecker/src/com/intellij/spellchecker/dictionary/AggregatedDictionary.java index 78ab84baa616..94f9d2fcc891 100644 --- a/spellchecker/src/com/intellij/spellchecker/dictionary/AggregatedDictionary.java +++ b/spellchecker/src/com/intellij/spellchecker/dictionary/AggregatedDictionary.java @@ -16,6 +16,7 @@ package com.intellij.spellchecker.dictionary; import com.intellij.util.Consumer; +import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -23,11 +24,12 @@ import java.util.Collection; import java.util.Set; public class AggregatedDictionary implements EditableDictionary { - - private static final String DICTIONARY_NAME = "common"; + @NonNls private static final String DICTIONARY_NAME = "common"; private final EditableDictionary cachedDictionary; private final ProjectDictionary projectDictionary; + @NotNull + @Override public String getName() { return DICTIONARY_NAME; } @@ -38,10 +40,12 @@ public class AggregatedDictionary implements EditableDictionary { this.cachedDictionary.addToDictionary(projectDictionary.getWords()); } + @Override public boolean isEmpty() { return false; } + @NonNls @Override public String toString() { return "AggregatedDictionary{" + @@ -50,25 +54,26 @@ public class AggregatedDictionary implements EditableDictionary { '}'; } + @Override @Nullable - public Boolean contains(String word) { - if (word == null) { - return false; - } + public Boolean contains(@NotNull String word) { return cachedDictionary.contains(word); } + @Override public void addToDictionary(String word) { getProjectDictionary().addToDictionary(word); getCachedDictionary().addToDictionary(word); } + @Override public void removeFromDictionary(String word) { getProjectDictionary().removeFromDictionary(word); getCachedDictionary().removeFromDictionary(word); } + @Override public void replaceAll(@Nullable Collection words) { Set oldWords = getProjectDictionary().getWords(); getProjectDictionary().replaceAll(words); @@ -81,29 +86,35 @@ public class AggregatedDictionary implements EditableDictionary { } } + @Override public void clear() { getProjectDictionary().clear(); } + @Override public void traverse(@NotNull final Consumer consumer) { cachedDictionary.traverse(consumer); } + @Override public Set getWords() { return cachedDictionary.getWords(); } + @Override public int size() { - return (cachedDictionary.size()); + return cachedDictionary.size(); } + @Override @Nullable public Set getEditableWords() { return getProjectDictionary().getEditableWords(); } + @Override public void addToDictionary(@Nullable Collection words) { getProjectDictionary().addToDictionary(words); getCachedDictionary().addToDictionary(words); diff --git a/spellchecker/src/com/intellij/spellchecker/dictionary/Dictionary.java b/spellchecker/src/com/intellij/spellchecker/dictionary/Dictionary.java index 1057bb6e2d32..b9cc69913edb 100644 --- a/spellchecker/src/com/intellij/spellchecker/dictionary/Dictionary.java +++ b/spellchecker/src/com/intellij/spellchecker/dictionary/Dictionary.java @@ -16,20 +16,21 @@ package com.intellij.spellchecker.dictionary; import com.intellij.util.Consumer; +import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.Set; public interface Dictionary { - + @NotNull String getName(); @Nullable - Boolean contains(String word); + Boolean contains(@NotNull String word); boolean isEmpty(); - void traverse(final Consumer action); + void traverse(@NotNull Consumer action); @Nullable Set getWords(); diff --git a/spellchecker/src/com/intellij/spellchecker/dictionary/EditableDictionary.java b/spellchecker/src/com/intellij/spellchecker/dictionary/EditableDictionary.java index d2abc06519bc..fdccba32ce56 100644 --- a/spellchecker/src/com/intellij/spellchecker/dictionary/EditableDictionary.java +++ b/spellchecker/src/com/intellij/spellchecker/dictionary/EditableDictionary.java @@ -21,7 +21,6 @@ import java.util.Collection; import java.util.Set; public interface EditableDictionary extends Dictionary { - void addToDictionary(@Nullable String word); void removeFromDictionary(@Nullable String word); @@ -34,6 +33,4 @@ public interface EditableDictionary extends Dictionary { @Nullable Set getEditableWords(); - - } diff --git a/spellchecker/src/com/intellij/spellchecker/dictionary/ProjectDictionary.java b/spellchecker/src/com/intellij/spellchecker/dictionary/ProjectDictionary.java index 1202c9201531..b72c8f45928a 100644 --- a/spellchecker/src/com/intellij/spellchecker/dictionary/ProjectDictionary.java +++ b/spellchecker/src/com/intellij/spellchecker/dictionary/ProjectDictionary.java @@ -17,6 +17,7 @@ package com.intellij.spellchecker.dictionary; import com.intellij.util.Consumer; import gnu.trove.THashSet; +import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -25,8 +26,7 @@ import java.util.HashSet; import java.util.Set; public class ProjectDictionary implements EditableDictionary { - - private static final String DEFAULT_CURRENT_USER_NAME = "default.user"; + @NonNls private static final String DEFAULT_CURRENT_USER_NAME = "default.user"; private static final String DEFAULT_PROJECT_DICTIONARY_NAME = "project"; private String activeName; private Set dictionaries; @@ -35,14 +35,17 @@ public class ProjectDictionary implements EditableDictionary { public ProjectDictionary() { } - public ProjectDictionary(Set dictionaries) { + public ProjectDictionary(@NotNull Set dictionaries) { this.dictionaries = dictionaries; } + @Override public boolean isEmpty() { return false; } + @NotNull + @Override public String getName() { return DEFAULT_PROJECT_DICTIONARY_NAME; } @@ -52,12 +55,13 @@ public class ProjectDictionary implements EditableDictionary { } public void setActiveName(String name) { - this.activeName = name; + activeName = name; } + @Override @Nullable - public Boolean contains(String word) { - if (word == null || dictionaries == null) { + public Boolean contains(@NotNull String word) { + if (dictionaries == null) { return false; } int errors = 0; @@ -66,8 +70,7 @@ public class ProjectDictionary implements EditableDictionary { if (contains == null) { errors++; } - else - if (contains) { + else if (contains) { return true; } } @@ -75,10 +78,12 @@ public class ProjectDictionary implements EditableDictionary { return false; } + @Override public void addToDictionary(String word) { getActiveDictionary().addToDictionary(word); } + @Override public void removeFromDictionary(String word) { getActiveDictionary().removeFromDictionary(word); } @@ -95,7 +100,7 @@ public class ProjectDictionary implements EditableDictionary { } EditableDictionary result = getDictionaryByName(activeName); if (result == null) { - result = new UserDictionary(this.activeName); + result = new UserDictionary(activeName); if (dictionaries == null) { dictionaries = new THashSet(); } @@ -120,15 +125,18 @@ public class ProjectDictionary implements EditableDictionary { } + @Override public void replaceAll(@Nullable Collection words) { getActiveDictionary().replaceAll(words); } + @Override public void clear() { getActiveDictionary().clear(); } + @Override @Nullable public Set getWords() { if (dictionaries == null) { @@ -141,6 +149,7 @@ public class ProjectDictionary implements EditableDictionary { return words; } + @Override public int size(){ int result = 0; for (Dictionary dictionary : dictionaries) { @@ -149,7 +158,8 @@ public class ProjectDictionary implements EditableDictionary { return result; } - public void traverse(final Consumer consumer) { + @Override + public void traverse(@NotNull final Consumer consumer) { if (dictionaries == null) { return; } @@ -160,12 +170,14 @@ public class ProjectDictionary implements EditableDictionary { } + @Override @Nullable public Set getEditableWords() { return getActiveDictionary().getWords(); } + @Override public void addToDictionary(@Nullable Collection words) { getActiveDictionary().addToDictionary(words); } @@ -195,6 +207,7 @@ public class ProjectDictionary implements EditableDictionary { return result; } + @NonNls @Override public String toString() { return "ProjectDictionary{" + "activeName='" + activeName + '\'' + ", dictionaries=" + dictionaries + '}'; diff --git a/spellchecker/src/com/intellij/spellchecker/dictionary/UserDictionary.java b/spellchecker/src/com/intellij/spellchecker/dictionary/UserDictionary.java index f4a1615a114a..7ee25df992cb 100644 --- a/spellchecker/src/com/intellij/spellchecker/dictionary/UserDictionary.java +++ b/spellchecker/src/com/intellij/spellchecker/dictionary/UserDictionary.java @@ -17,6 +17,7 @@ package com.intellij.spellchecker.dictionary; import com.intellij.util.Consumer; import gnu.trove.THashSet; +import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -24,46 +25,53 @@ import java.util.Collection; import java.util.Set; public class UserDictionary implements EditableDictionary { - private final String name; @NotNull - private final THashSet words = new THashSet(); + private final Set words = new THashSet(); - public UserDictionary(String name) { + public UserDictionary(@NotNull String name) { this.name = name; } + @NotNull + @Override public String getName() { return name; } + @Override @Nullable - public Boolean contains(String word) { + public Boolean contains(@NotNull String word) { boolean contains = words.contains(word); if(contains) return true; return null; } + @Override public int size() { return words.size(); } + @Override @Nullable public Set getWords() { return words; } + @Override @Nullable public Set getEditableWords() { return words; } + @Override public void clear() { words.clear(); } + @Override public void addToDictionary(String word) { if (word == null) { return; @@ -71,6 +79,7 @@ public class UserDictionary implements EditableDictionary { words.add(word); } + @Override public void removeFromDictionary(String word) { if (word == null) { return; @@ -78,11 +87,13 @@ public class UserDictionary implements EditableDictionary { words.remove(word); } + @Override public void replaceAll(@Nullable Collection words) { clear(); addToDictionary(words); } + @Override public void addToDictionary(@Nullable Collection words) { if (words == null || words.isEmpty()) { return; @@ -92,8 +103,9 @@ public class UserDictionary implements EditableDictionary { } } + @Override public boolean isEmpty() { - return words.size() == 0; + return words.isEmpty(); } @Override @@ -103,11 +115,12 @@ public class UserDictionary implements EditableDictionary { UserDictionary that = (UserDictionary)o; - return !(name != null ? !name.equals(that.name) : that.name != null); + return name.equals(that.name); } - public void traverse(final Consumer consumer) { + @Override + public void traverse(@NotNull final Consumer consumer) { for (String word : words) { consumer.consume(word); } @@ -115,9 +128,10 @@ public class UserDictionary implements EditableDictionary { @Override public int hashCode() { - return name != null ? name.hashCode() : 0; + return name.hashCode(); } + @NonNls @Override public String toString() { return "UserDictionary{" + "name='" + name + '\'' + ", words.count=" + words.size() + '}'; diff --git a/xml/impl/src/com/intellij/application/options/emmet/CssEditPrefixesListPanel.java b/xml/impl/src/com/intellij/application/options/emmet/CssEditPrefixesListPanel.java index 5cb55b2f0c43..765c00e4d051 100644 --- a/xml/impl/src/com/intellij/application/options/emmet/CssEditPrefixesListPanel.java +++ b/xml/impl/src/com/intellij/application/options/emmet/CssEditPrefixesListPanel.java @@ -28,6 +28,10 @@ import javax.swing.table.TableCellEditor; import javax.swing.table.TableCellRenderer; import java.util.ArrayList; import java.util.List; +import java.util.Set; + +import static com.google.common.collect.Lists.newArrayList; +import static com.google.common.collect.Sets.newHashSet; /** * User: zolotov @@ -66,12 +70,12 @@ public class CssEditPrefixesListPanel { myPrefixesTableView.setEnabled(value); } - public void setState(List prefixInfos) { - myPrefixesModel.setItems(prefixInfos); + public void setState(Set prefixInfos) { + myPrefixesModel.setItems(newArrayList(prefixInfos)); } - public List getState() { - return myPrefixesModel.getItems(); + public Set getState() { + return newHashSet(myPrefixesModel.getItems()); } public JPanel createMainComponent() { diff --git a/xml/impl/src/com/intellij/application/options/emmet/EmmetConfigurable.java b/xml/impl/src/com/intellij/application/options/emmet/EmmetConfigurable.java index a702df6fde61..9dbfc55456fd 100644 --- a/xml/impl/src/com/intellij/application/options/emmet/EmmetConfigurable.java +++ b/xml/impl/src/com/intellij/application/options/emmet/EmmetConfigurable.java @@ -137,7 +137,7 @@ public class EmmetConfigurable implements SearchableConfigurable, Disposable, Co public void apply() throws ConfigurationException { EmmetOptions emmetOptions = EmmetOptions.getInstance(); emmetOptions.setEmmetEnabled(myEnableEmmetJBCheckBox.isSelected()); - emmetOptions.setEnableBemFilterByDefault(myEnableBEMFilterJBCheckBox.isSelected()); + emmetOptions.setBemFilterEnabledByDefault(myEnableBEMFilterJBCheckBox.isSelected()); emmetOptions.setEmmetExpandShortcut(getSelectedEmmetExpandShortcut()); emmetOptions.setAutoInsertCssPrefixedEnabled(myAutoInsertCssVendorJBCheckBox.isSelected()); emmetOptions.setFuzzySearchEnabled(myEnabledFuzzySearchJBCheckBox.isSelected()); diff --git a/xml/impl/src/com/intellij/application/options/emmet/EmmetOptions.java b/xml/impl/src/com/intellij/application/options/emmet/EmmetOptions.java index dd005841293c..614e17a736a7 100644 --- a/xml/impl/src/com/intellij/application/options/emmet/EmmetOptions.java +++ b/xml/impl/src/com/intellij/application/options/emmet/EmmetOptions.java @@ -15,6 +15,7 @@ */ package com.intellij.application.options.emmet; +import com.google.common.collect.Sets; import com.intellij.application.options.editor.WebEditorOptions; import com.intellij.openapi.application.PathManager; import com.intellij.openapi.components.*; @@ -29,10 +30,10 @@ import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.File; -import java.util.List; +import java.util.Collection; import java.util.Map; +import java.util.Set; -import static com.google.common.collect.Lists.newLinkedList; import static com.google.common.collect.Maps.newHashMap; import static com.google.common.io.Resources.getResource; @@ -48,7 +49,7 @@ import static com.google.common.io.Resources.getResource; )} ) public class EmmetOptions implements PersistentStateComponent, ExportableComponent { - private boolean myEnableBemFilterByDefault = false; + private boolean myBemFilterEnabledByDefault = false; private boolean myEmmetEnabled = WebEditorOptions.getInstance().isZenCodingEnabled(); private int myEmmetExpandShortcut = WebEditorOptions.getInstance().getZenCodingExpandShortcut(); private boolean myFuzzySearchEnabled = true; @@ -56,7 +57,7 @@ public class EmmetOptions implements PersistentStateComponent, Exp @Nullable private Map prefixes = null; - public void setPrefixInfo(List prefixInfos) { + public void setPrefixInfo(Collection prefixInfos) { prefixes = newHashMap(); for (CssPrefixInfo state : prefixInfos) { prefixes.put(state.getPropertyName(), state.toIntegerValue()); @@ -67,8 +68,8 @@ public class EmmetOptions implements PersistentStateComponent, Exp return CssPrefixInfo.fromIntegerValue(propertyName, getPrefixes().get(propertyName)); } - public List getAllPrefixInfo() { - List result = newLinkedList(); + public Set getAllPrefixInfo() { + Set result = Sets.newHashSetWithExpectedSize(getPrefixes().size()); for (Map.Entry entry : getPrefixes().entrySet()) { result.add(CssPrefixInfo.fromIntegerValue(entry.getKey(), entry.getValue())); } @@ -76,11 +77,11 @@ public class EmmetOptions implements PersistentStateComponent, Exp } public boolean isBemFilterEnabledByDefault() { - return myEnableBemFilterByDefault; + return myBemFilterEnabledByDefault; } - public void setEnableBemFilterByDefault(boolean enableBemFilterByDefault) { - myEnableBemFilterByDefault = enableBemFilterByDefault; + public void setBemFilterEnabledByDefault(boolean enableBemFilterByDefault) { + myBemFilterEnabledByDefault = enableBemFilterByDefault; } public void setEmmetExpandShortcut(int emmetExpandShortcut) { @@ -141,7 +142,6 @@ public class EmmetOptions implements PersistentStateComponent, Exp return ServiceManager.getService(EmmetOptions.class); } - @SuppressWarnings("UnusedDeclaration") @NotNull public Map getPrefixes() { if (prefixes == null) { @@ -155,7 +155,7 @@ public class EmmetOptions implements PersistentStateComponent, Exp this.prefixes = prefixes; } - public static Map loadDefaultPrefixes() { + public Map loadDefaultPrefixes() { Map result = newHashMap(); try { Document document = JDOMUtil.loadDocument(getResource(EmmetOptions.class, "emmet_default_options.xml"));