Merge remote-tracking branch 'origin/master'

This commit is contained in:
Ekaterina Tuzova
2014-11-27 12:21:16 +03:00
88 changed files with 1002 additions and 594 deletions
+21 -13
View File
@@ -557,7 +557,7 @@
<value>
<option name="EFFECT_COLOR" value="bc3f3c" />
<option name="EFFECT_TYPE" value="2" />
<option name="ERROR_STRIPE_COLOR" value="bc3f3c" />
<option name="ERROR_STRIPE_COLOR" value="9e2927" />
</value>
</option>
<option name="EXECUTIONPOINT_ATTRIBUTES">
@@ -587,7 +587,7 @@
<value>
<option name="EFFECT_COLOR" value="f49810" />
<option name="EFFECT_TYPE" value="1" />
<option name="ERROR_STRIPE_COLOR" value="f49810" />
<option name="ERROR_STRIPE_COLOR" value="B06100" />
</value>
</option>
<option name="GRADLE_CHANGE_CONFLICT">
@@ -710,7 +710,7 @@
<option name="IDENTIFIER_UNDER_CARET_ATTRIBUTES">
<value>
<option name="BACKGROUND" value="344134" />
<option name="ERROR_STRIPE_COLOR" value="5d8e48" />
<option name="ERROR_STRIPE_COLOR" value="036b13" />
<option name="EFFECT_TYPE" value="1" />
</value>
</option>
@@ -731,7 +731,7 @@
<value>
<option name="EFFECT_COLOR" value="aeae80" />
<option name="EFFECT_TYPE" value="2" />
<option name="ERROR_STRIPE_COLOR" value="aeae80" />
<option name="ERROR_STRIPE_COLOR" value="756D56" />
</value>
</option>
<option name="INJECTED_LANGUAGE_FRAGMENT">
@@ -1367,7 +1367,6 @@
<option name="SEARCH_RESULT_ATTRIBUTES">
<value>
<option name="BACKGROUND" value="155221" />
<option name="ERROR_STRIPE_COLOR" value="246e00" />
</value>
</option>
<option name="SPY-JS.FUNCTION_SCOPE">
@@ -1486,16 +1485,16 @@
</option>
<option name="TEXT_SEARCH_RESULT_ATTRIBUTES">
<value>
<option name="BACKGROUND" value="425f44" />
<option name="EFFECT_COLOR" value="56ac48" />
<option name="ERROR_STRIPE_COLOR" value="425f44" />
<option name="BACKGROUND" value="32593D" />
<option name="EFFECT_COLOR" value="3C704B" />
<option name="ERROR_STRIPE_COLOR" value="61936f" />
</value>
</option>
<option name="TODO_DEFAULT_ATTRIBUTES">
<value>
<option name="FOREGROUND" value="a8c023" />
<option name="FOREGROUND" value="0264ab" />
<option name="FONT_TYPE" value="2" />
<option name="ERROR_STRIPE_COLOR" value="a74c0" />
<option name="ERROR_STRIPE_COLOR" value="015998" />
</value>
</option>
<option name="OC.TYPEDEF">
@@ -1511,10 +1510,20 @@
</option>
<option name="TYPO">
<value>
<option name="EFFECT_COLOR" value="867f27" />
<option name="EFFECT_COLOR" value="6C7507" />
<option name="EFFECT_TYPE" value="2" />
</value>
</option>
<option name="NO_ANALYSIS">
<value>
<option name="ERROR_STRIPE_COLOR" value="777777" />
</value>
</option>
<option name="DO_NOT_SHOW">
<value>
<option name="ERROR_STRIPE_COLOR" value="266109" />
</value>
</option>
<option name="Type parameter">
<value>
<option name="FOREGROUND" value="507874" />
@@ -1580,14 +1589,13 @@
<option name="WRITE_IDENTIFIER_UNDER_CARET_ATTRIBUTES">
<value>
<option name="BACKGROUND" value="40332b" />
<option name="ERROR_STRIPE_COLOR" value="cc7832" />
<option name="ERROR_STRIPE_COLOR" value="b56277" />
<option name="EFFECT_TYPE" value="1" />
</value>
</option>
<option name="WRITE_SEARCH_RESULT_ATTRIBUTES">
<value>
<option name="BACKGROUND" value="532b2e" />
<option name="ERROR_STRIPE_COLOR" value="c55450" />
</value>
</option>
<option name="WRONG_REFERENCES_ATTRIBUTES">
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2012 JetBrains s.r.o.
* Copyright 2000-2014 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -60,6 +60,7 @@ public class CompilerEncodingServiceImpl extends CompilerEncodingService {
}, false);
}
@NotNull
private Map<Module, Set<Charset>> computeModuleCharsetMap() {
final Map<Module, Set<Charset>> map = new THashMap<Module, Set<Charset>>();
final Map<VirtualFile, Charset> mappings = EncodingProjectManager.getInstance(myProject).getAllMappings();
@@ -15,7 +15,6 @@
*/
package com.intellij.packaging.impl.run;
import com.intellij.compiler.impl.CompileScopeUtil;
import com.intellij.execution.BeforeRunTask;
import com.intellij.execution.BeforeRunTaskProvider;
import com.intellij.execution.RunManagerEx;
@@ -43,12 +42,10 @@ import com.intellij.util.containers.ContainerUtil;
import gnu.trove.THashSet;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.jps.api.CmdlineRemoteProto;
import javax.swing.*;
import java.awt.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
@@ -191,7 +188,6 @@ public class BuildArtifactsBeforeRunTaskProvider extends BeforeRunTaskProvider<B
final CompilerManager manager = CompilerManager.getInstance(myProject);
finished.down();
final CompileScope scope = ArtifactCompileScope.createArtifactsScope(myProject, artifacts);
CompileScopeUtil.setBaseScopeForExternalBuild(scope, Collections.<CmdlineRemoteProto.Message.ControllerMessage.ParametersMessage.TargetTypeBuildScope>emptyList());
ExecutionManagerImpl.EXECUTION_SESSION_ID_KEY.set(scope, ExecutionManagerImpl.EXECUTION_SESSION_ID_KEY.get(env));
manager.make(scope, CompilerFilter.ALL, callback);
}
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2009 JetBrains s.r.o.
* Copyright 2000-2014 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.
@@ -35,7 +35,6 @@ import com.intellij.execution.executors.DefaultDebugExecutor;
import com.intellij.execution.runners.ExecutionEnvironment;
import com.intellij.execution.runners.ExecutionEnvironmentBuilder;
import com.intellij.execution.runners.ProgramRunner;
import com.intellij.execution.ui.ExecutionConsole;
import com.intellij.execution.ui.RunContentDescriptor;
import com.intellij.execution.ui.RunContentManager;
import com.intellij.execution.ui.RunContentWithExecutorListener;
@@ -158,7 +157,7 @@ public class DebuggerPanelsManager implements ProjectComponent {
@Override
public void contentSelected(@Nullable RunContentDescriptor descriptor, @NotNull Executor executor) {
if (executor == DefaultDebugExecutor.getDebugExecutorInstance()) {
DebuggerSession session = descriptor == null ? null : getSession(myProject, descriptor.getExecutionConsole());
DebuggerSession session = descriptor == null ? null : getSession(myProject, descriptor);
if (session != null) {
getContextManager().setState(session.getContextManager().getContext(), session.getState(), DebuggerSession.EVENT_CONTEXT, null);
}
@@ -222,12 +221,13 @@ public class DebuggerPanelsManager implements ProjectComponent {
}
}
private static DebuggerSession getSession(Project project, ExecutionConsole console) {
XDebugSession session = XDebuggerManager.getInstance(project).getDebugSession(console);
if (session != null) {
XDebugProcess process = session.getDebugProcess();
if (process instanceof JavaDebugProcess) {
return ((JavaDebugProcess)process).getDebuggerSession();
private static DebuggerSession getSession(Project project, RunContentDescriptor descriptor) {
for (XDebugSession session : XDebuggerManager.getInstance(project).getDebugSessions()) {
if (session.getRunContentDescriptor().equals(descriptor)) {
XDebugProcess process = session.getDebugProcess();
if (process instanceof JavaDebugProcess) {
return ((JavaDebugProcess)process).getDebuggerSession();
}
}
}
return null;
@@ -23,6 +23,7 @@ import com.intellij.openapi.project.Project;
import com.intellij.pom.java.LanguageLevel;
import com.intellij.psi.*;
import com.intellij.psi.infos.CandidateInfo;
import com.intellij.psi.infos.MethodCandidateInfo;
import com.intellij.psi.scope.conflictResolvers.JavaMethodsConflictResolver;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.util.PsiUtil;
@@ -87,8 +88,7 @@ public class RedundantLambdaCodeBlockInspection extends BaseJavaBatchLocalInspec
final List<CandidateInfo> info = new ArrayList<CandidateInfo>(Arrays.asList(candidates));
final LanguageLevel level = PsiUtil.getLanguageLevel(parent);
final JavaMethodsConflictResolver conflictResolver = new JavaMethodsConflictResolver((PsiExpressionList)parent, level);
final int applicability = conflictResolver.checkApplicability(info);
conflictResolver.checkSpecifics(info, applicability, level);
conflictResolver.checkSpecifics(info, MethodCandidateInfo.ApplicabilityLevel.FIXED_ARITY, level);
if (info.size() > 1) {
return;
}
@@ -50,31 +50,24 @@ import static com.intellij.psi.formatter.java.JavaFormatterUtil.getWrapType;
public abstract class AbstractJavaBlock extends AbstractBlock implements JavaBlock, ReservedWrapsProvider {
/**
* Holds types of the elements for which <code>'align in column'</code> rule may be preserved.
*
* @see CodeStyleSettings#ALIGN_GROUP_FIELD_DECLARATIONS
*/
protected static final Set<IElementType> ALIGN_IN_COLUMNS_ELEMENT_TYPES = Collections.unmodifiableSet(new HashSet<IElementType>(
Arrays.asList(JavaElementType.FIELD)));
private static final Logger LOG = Logger.getInstance("#com.intellij.psi.formatter.java.AbstractJavaBlock");
/**
* Shared thread-safe config object to use during <code>'align in column'</code> processing.
*
* @see CodeStyleSettings#ALIGN_GROUP_FIELD_DECLARATIONS
*/
private static final AlignmentInColumnsConfig ALIGNMENT_IN_COLUMNS_CONFIG = new AlignmentInColumnsConfig(
TokenSet.create(JavaTokenType.IDENTIFIER), JavaJspElementType.WHITE_SPACE_BIT_SET, ElementType.JAVA_COMMENT_BIT_SET,
TokenSet.create(JavaTokenType.EQ), TokenSet.create(JavaElementType.FIELD));
protected static final Set<IElementType> ALIGN_IN_COLUMNS_ELEMENT_TYPES = ContainerUtil.newHashSet(JavaElementType.FIELD);
/**
* Enumerates types of variable declaration sub-elements that should be aligned in columns.
*/
private static final Set<IElementType> VAR_DECLARATION_ELEMENT_TYPES_TO_ALIGN = new HashSet<IElementType>(Arrays.asList(
JavaElementType.MODIFIER_LIST, JavaElementType.TYPE, JavaTokenType.IDENTIFIER, JavaTokenType.EQ
));
private static final AlignmentInColumnsConfig ALIGNMENT_IN_COLUMNS_CONFIG = new AlignmentInColumnsConfig(
TokenSet.create(JavaTokenType.IDENTIFIER),
JavaJspElementType.WHITE_SPACE_BIT_SET,
ElementType.JAVA_COMMENT_BIT_SET,
TokenSet.create(JavaTokenType.EQ),
TokenSet.create(JavaElementType.FIELD)
);
private static final Set<IElementType> VAR_DECLARATION_ELEMENT_TYPES_TO_ALIGN = ContainerUtil.newHashSet(
JavaElementType.MODIFIER_LIST,
JavaElementType.TYPE,
JavaTokenType.IDENTIFIER,
JavaTokenType.EQ
);
@NotNull protected final CommonCodeStyleSettings mySettings;
@NotNull protected final JavaCodeStyleSettings myJavaSettings;
@@ -50,7 +50,11 @@ public class SimpleJavaBlock extends AbstractJavaBlock {
@Override
protected List<Block> buildChildren() {
ASTNode child = myNode.getFirstChildNode();
int offset = myStartOffset != -1 ? myStartOffset : child != null ? child.getTextRange().getStartOffset():0;
int offset = myStartOffset;
if (offset == -1) {
offset = child != null ? child.getTextRange().getStartOffset() : 0;
}
final ArrayList<Block> result = new ArrayList<Block>();
Indent indent = null;
@@ -71,11 +75,9 @@ public class SimpleJavaBlock extends AbstractJavaBlock {
myReservedAlignment2 = createChildAlignment2(myReservedAlignment);
Wrap childWrap = createChildWrap();
while (child != null) {
if (!FormatterUtil.containsWhiteSpacesOnly(child) && child.getTextLength() > 0){
if (isNotEmptyNode(child)) {
final ASTNode astNode = child;
AlignmentStrategy alignmentStrategyToUse = ALIGN_IN_COLUMNS_ELEMENT_TYPES.contains(myNode.getElementType())
? myAlignmentStrategy
: AlignmentStrategy.wrap(chooseAlignment(myReservedAlignment, myReservedAlignment2, child));
AlignmentStrategy alignmentStrategyToUse = getAlignmentStrategy(child);
child = processChild(result, astNode, alignmentStrategyToUse, childWrap, indent, offset);
if (astNode != child && child != null) {
offset = child.getTextRange().getStartOffset();
@@ -86,6 +88,7 @@ public class SimpleJavaBlock extends AbstractJavaBlock {
indent = Indent.getContinuationIndent(myIndentSettings.USE_RELATIVE_INDENTS);
}
}
if (child != null) {
offset += child.getTextLength();
child = child.getTreeNext();
@@ -95,6 +98,16 @@ public class SimpleJavaBlock extends AbstractJavaBlock {
return result;
}
private AlignmentStrategy getAlignmentStrategy(ASTNode child) {
return ALIGN_IN_COLUMNS_ELEMENT_TYPES.contains(myNode.getElementType())
? myAlignmentStrategy
: AlignmentStrategy.wrap(chooseAlignment(myReservedAlignment, myReservedAlignment2, child));
}
private boolean isNotEmptyNode(@NotNull ASTNode child) {
return !FormatterUtil.containsWhiteSpacesOnly(child) && child.getTextLength() > 0;
}
@Override
@NotNull
public TextRange getTextRange() {
@@ -19,7 +19,9 @@ import com.intellij.openapi.project.Project;
import com.intellij.psi.*;
import com.intellij.psi.util.*;
import com.intellij.util.ArrayUtil;
import com.intellij.util.CommonProcessors;
import com.intellij.util.containers.ConcurrentFactoryMap;
import com.intellij.util.containers.ContainerUtil;
import gnu.trove.THashSet;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.NonNls;
@@ -191,6 +193,30 @@ public class AnnotationUtil {
return result == null ? PsiAnnotation.EMPTY_ARRAY : result.toArray(new PsiAnnotation[result.size()]);
}
public static <T extends PsiModifierListOwner> List<T> getSuperAnnotationOwners(final T element) {
return CachedValuesManager.getCachedValue(element, new CachedValueProvider<List<T>>() {
@Nullable
@Override
public Result<List<T>> compute() {
LinkedHashSet<PsiModifierListOwner> result = ContainerUtil.newLinkedHashSet();
if (element instanceof PsiMethod) {
collectSuperMethods(result, ((PsiMethod)element).getHierarchicalMethodSignature(), element,
JavaPsiFacade.getInstance(element.getProject()).getResolveHelper());
} else if (element instanceof PsiClass) {
//noinspection unchecked
InheritanceUtil.processSupers((PsiClass)element, false, new CommonProcessors.CollectProcessor<PsiClass>((Set)result));
} else if (element instanceof PsiParameter) {
collectSuperParameters(result, (PsiParameter)element);
}
List<T> list = new ArrayList<T>();
//noinspection unchecked
list.addAll((Collection<? extends T>)result);
return Result.create(list, PsiModificationTracker.MODIFICATION_COUNT);
}
});
}
@Nullable
public static PsiAnnotation findAnnotationInHierarchy(@NotNull final PsiModifierListOwner listOwner, @NotNull Set<String> annotationNames) {
PsiAnnotation directAnnotation = findAnnotation(listOwner, annotationNames);
@@ -206,20 +232,11 @@ public class AnnotationUtil {
@Nullable
@Override
protected PsiAnnotation create(Set<String> annotationNames) {
if (listOwner instanceof PsiMethod) {
PsiMethod method = (PsiMethod)listOwner;
PsiClass aClass = method.getContainingClass();
if (aClass == null) return null;
HierarchicalMethodSignature methodSignature = method.getHierarchicalMethodSignature();
return findAnnotationInHierarchy(methodSignature, annotationNames, method, null,
JavaPsiFacade.getInstance(method.getProject()).getResolveHelper());
}
if (listOwner instanceof PsiClass) {
return findAnnotationInHierarchy((PsiClass)listOwner, annotationNames, null);
}
if (listOwner instanceof PsiParameter) {
PsiParameter parameter = (PsiParameter)listOwner;
return doFindAnnotationInHierarchy(parameter, annotationNames, null);
for (PsiModifierListOwner superOwner : getSuperAnnotationOwners(listOwner)) {
PsiAnnotation annotation = findAnnotation(superOwner, annotationNames);
if (annotation != null) {
return annotation;
}
}
return null;
}
@@ -230,74 +247,36 @@ public class AnnotationUtil {
return map.get(annotationNames);
}
@Nullable
private static PsiAnnotation doFindAnnotationInHierarchy(@NotNull PsiParameter parameter,
@NotNull Set<String> annotationNames,
@Nullable Set<PsiModifierListOwner> visited) {
PsiAnnotation annotation = findAnnotation(parameter, annotationNames);
if (annotation != null) return annotation;
private static void collectSuperParameters(LinkedHashSet<PsiModifierListOwner> result, @NotNull PsiParameter parameter) {
PsiElement scope = parameter.getDeclarationScope();
if (!(scope instanceof PsiMethod)) {
return null;
return;
}
PsiMethod method = (PsiMethod)scope;
PsiClass aClass = method.getContainingClass();
PsiElement parent = parameter.getParent();
if (aClass == null || !(parent instanceof PsiParameterList)) {
return null;
if (!(parent instanceof PsiParameterList)) {
return;
}
int index = ((PsiParameterList)parent).getParameterIndex(parameter);
HierarchicalMethodSignature methodSignature = method.getHierarchicalMethodSignature();
final List<HierarchicalMethodSignature> superSignatures = methodSignature.getSuperSignatures();
PsiResolveHelper resolveHelper = PsiResolveHelper.SERVICE.getInstance(aClass.getProject());
for (final HierarchicalMethodSignature superSignature : superSignatures) {
final PsiMethod superMethod = superSignature.getMethod();
if (visited == null) visited = new THashSet<PsiModifierListOwner>();
if (!visited.add(superMethod)) continue;
if (!resolveHelper.isAccessible(superMethod, parameter, null)) continue;
for (PsiMethod superMethod : getSuperAnnotationOwners(method)) {
PsiParameter[] superParameters = superMethod.getParameterList().getParameters();
if (index < superParameters.length) {
PsiAnnotation insuper = doFindAnnotationInHierarchy(superParameters[index], annotationNames, visited);
if (insuper != null) return insuper;
result.add(superParameters[index]);
}
}
return null;
}
@Nullable
private static PsiAnnotation findAnnotationInHierarchy(@NotNull final PsiClass psiClass, @NotNull Set<String> annotationNames, @Nullable Set<PsiClass> processed) {
final PsiClass[] superClasses = psiClass.getSupers();
for (final PsiClass superClass : superClasses) {
if (processed == null) processed = new THashSet<PsiClass>();
if (!processed.add(superClass)) return null;
final PsiAnnotation annotation = findAnnotation(superClass, annotationNames);
if (annotation != null) return annotation;
final PsiAnnotation annotationInHierarchy = findAnnotationInHierarchy(superClass, annotationNames, processed);
if (annotationInHierarchy != null) return annotationInHierarchy;
}
return null;
}
@Nullable
private static PsiAnnotation findAnnotationInHierarchy(@NotNull HierarchicalMethodSignature signature,
@NotNull Set<String> annotationNames,
@NotNull PsiElement place,
@Nullable Set<PsiMethod> processed,
@NotNull PsiResolveHelper resolveHelper) {
final List<HierarchicalMethodSignature> superSignatures = signature.getSuperSignatures();
for (final HierarchicalMethodSignature superSignature : superSignatures) {
private static void collectSuperMethods(LinkedHashSet<PsiModifierListOwner> result,
@NotNull HierarchicalMethodSignature signature,
@NotNull PsiElement place,
@NotNull PsiResolveHelper resolveHelper) {
for (final HierarchicalMethodSignature superSignature : signature.getSuperSignatures()) {
final PsiMethod superMethod = superSignature.getMethod();
if (processed == null) processed = new THashSet<PsiMethod>();
if (!processed.add(superMethod)) continue;
if (!resolveHelper.isAccessible(superMethod, place, null)) continue;
PsiAnnotation direct = findAnnotation(superMethod, annotationNames);
if (direct != null) return direct;
PsiAnnotation superResult = findAnnotationInHierarchy(superSignature, annotationNames, place, processed, resolveHelper);
if (superResult != null) return superResult;
if (!result.add(superMethod)) continue;
collectSuperMethods(result, superSignature, place, resolveHelper);
}
return null;
}
public static boolean isAnnotated(@NotNull PsiModifierListOwner listOwner, @NotNull Collection<String> annotations) {
@@ -24,7 +24,7 @@ import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
/**
* Returns annotations inferred by bytecode our source code, for example contracts and nullity.
* Returns annotations inferred by bytecode or source code, for example contracts and nullity.
*
* @see com.intellij.codeInsight.NullableNotNullManager
* @see org.jetbrains.annotations.Contract
@@ -24,6 +24,7 @@ import com.intellij.openapi.util.InvalidDataException;
import com.intellij.openapi.util.JDOMExternalizableStringList;
import com.intellij.openapi.util.WriteExternalException;
import com.intellij.psi.*;
import com.intellij.psi.util.PsiUtil;
import com.intellij.psi.util.TypeConversionUtil;
import com.intellij.util.containers.ContainerUtil;
import org.jdom.Element;
@@ -167,16 +168,30 @@ public class NullableNotNullManager implements PersistentStateComponent<Element>
myDefaultNotNull = defaultNotNull;
}
private static boolean skipAnnotation(@NotNull PsiAnnotation annotation, @NotNull PsiModifierListOwner owner) {
return owner instanceof PsiMethod &&
PsiUtil.canBeOverriden((PsiMethod)owner) &&
AnnotationUtil.isInferredAnnotation(annotation) &&
AnnotationUtil.NOT_NULL.equals(annotation.getQualifiedName());
}
@Nullable
private PsiAnnotation findNullabilityAnnotation(@NotNull PsiModifierListOwner owner, boolean checkBases, boolean nullable) {
Set<String> qNames = ContainerUtil.newHashSet(nullable ? getNullables() : getNotNulls());
PsiAnnotation annotation = checkBases && (owner instanceof PsiClass || owner instanceof PsiMethod)
? AnnotationUtil.findAnnotationInHierarchy(owner, qNames)
: AnnotationUtil.findAnnotation(owner, qNames);
if (annotation != null) {
PsiAnnotation annotation = AnnotationUtil.findAnnotation(owner, qNames);
if (annotation != null && !skipAnnotation(annotation, owner)) {
return annotation;
}
if (checkBases && owner instanceof PsiMethod) {
for (PsiModifierListOwner superOwner : AnnotationUtil.getSuperAnnotationOwners(owner)) {
annotation = AnnotationUtil.findAnnotation(superOwner, qNames);
if (annotation != null && !skipAnnotation(annotation, superOwner)) {
return annotation;
}
}
}
PsiType type = getOwnerType(owner);
if (type == null || TypeConversionUtil.isPrimitiveAndNotNull(type)) return null;
@@ -302,6 +317,7 @@ public class NullableNotNullManager implements PersistentStateComponent<Element>
}
try {
//noinspection deprecation
DefaultJDOMExternalizer.writeExternal(this, component);
}
catch (WriteExternalException e) {
@@ -313,6 +329,7 @@ public class NullableNotNullManager implements PersistentStateComponent<Element>
@Override
public void loadState(Element state) {
try {
//noinspection deprecation
DefaultJDOMExternalizer.readExternal(this, state);
if (myNullables.isEmpty()) {
Collections.addAll(myNullables, DEFAULT_NULLABLES);
@@ -18,6 +18,7 @@ package com.intellij.psi;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.Computable;
import com.intellij.openapi.util.registry.Registry;
import com.intellij.pom.java.LanguageLevel;
import com.intellij.psi.infos.MethodCandidateInfo;
import com.intellij.psi.util.*;
@@ -493,6 +494,31 @@ public class LambdaUtil {
return expression;
}
// http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.12.2.1
// A lambda expression or a method reference expression is potentially compatible with a type variable
// if the type variable is a type parameter of the candidate method.
public static boolean isPotentiallyCompatibleWithTypeParameter(PsiFunctionalExpression expression,
PsiExpressionList argsList,
PsiMethod method) {
if (!Registry.is("JDK8042508.bug.fixed", false)) {
final PsiCallExpression callExpression = PsiTreeUtil.getParentOfType(argsList, PsiCallExpression.class);
if (callExpression == null || callExpression.getTypeArguments().length > 0) {
return false;
}
}
final int lambdaIdx = getLambdaIdx(argsList, expression);
if (lambdaIdx >= 0) {
final PsiParameter[] parameters = method.getParameterList().getParameters();
final PsiParameter lambdaParameter = parameters[Math.min(lambdaIdx, parameters.length - 1)];
final PsiClass paramClass = PsiUtil.resolveClassInType(lambdaParameter.getType());
if (paramClass instanceof PsiTypeParameter && ((PsiTypeParameter)paramClass).getOwner() == method) {
return true;
}
}
return false;
}
public static class TypeParamsChecker extends PsiTypeVisitor<Boolean> {
private PsiMethod myMethod;
private final PsiClass myClass;
@@ -46,6 +46,4 @@ public interface PsiLambdaExpression extends PsiFunctionalExpression {
* @return true when lambda declares parameter types explicitly
*/
boolean hasFormalParameterTypes();
boolean isAcceptable(PsiType leftType, boolean checkReturnType);
}
@@ -178,7 +178,7 @@ public class PsiMethodReferenceUtil {
PsiClassType.ClassResolveResult result = PsiUtil.resolveGenericsClassInType(type);
containingClass = result.getElement();
if (containingClass != null) {
substitutor = result.getSubstitutor();
return new QualifierResolveResult(containingClass, result.getSubstitutor(), true);
}
}
}
@@ -731,7 +731,7 @@ public class TypeConversionUtil {
final PsiType lType = lLambdaExpression.getFunctionalInterfaceType();
return Comparing.equal(rType, lType);
}
return !(left instanceof PsiArrayType) && rLambdaExpression.isAcceptable(left, false);
return !(left instanceof PsiArrayType) && rLambdaExpression.isAcceptable(left);
}
if (left instanceof PsiIntersectionType) {
@@ -18,7 +18,6 @@ package com.intellij.psi.impl.source.tree.java;
import com.intellij.icons.AllIcons;
import com.intellij.lang.ASTNode;
import com.intellij.psi.*;
import com.intellij.psi.codeStyle.JavaCodeStyleManager;
import com.intellij.psi.controlFlow.*;
import com.intellij.psi.impl.PsiImplUtil;
import com.intellij.psi.impl.source.resolve.graphInference.FunctionalInterfaceParameterizationUtil;
@@ -34,6 +33,8 @@ import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.util.HashMap;
import java.util.Map;
public class PsiLambdaExpressionImpl extends ExpressionPsiElement implements PsiLambdaExpression {
@@ -168,35 +169,35 @@ public class PsiLambdaExpressionImpl extends ExpressionPsiElement implements Psi
}
@Override
public boolean isAcceptable(PsiType left) {
return isAcceptable(left, false);
}
@Override
public boolean isAcceptable(PsiType leftType, boolean checkReturnType) {
public boolean isAcceptable(PsiType leftType) {
if (leftType instanceof PsiIntersectionType) {
for (PsiType conjunctType : ((PsiIntersectionType)leftType).getConjuncts()) {
if (isAcceptable(conjunctType, checkReturnType)) return true;
if (isAcceptable(conjunctType)) return true;
}
return false;
}
final PsiElement argsList = PsiTreeUtil.getParentOfType(this, PsiExpressionList.class);
if (MethodCandidateInfo.ourOverloadGuard.currentStack().contains(argsList)) {
if (!hasFormalParameterTypes()) {
return true;
}
final MethodCandidateInfo.CurrentCandidateProperties candidateProperties = MethodCandidateInfo.getCurrentMethod(argsList);
if (candidateProperties != null && !InferenceSession.isPertinentToApplicability(this, candidateProperties.getMethod())) {
return true;
}
}
final PsiExpressionList argsList = PsiTreeUtil.getParentOfType(this, PsiExpressionList.class);
leftType = FunctionalInterfaceParameterizationUtil.getGroundTargetType(leftType, this);
final PsiClassType.ClassResolveResult resolveResult = PsiUtil.resolveGenericsClassInType(leftType);
final PsiClass psiClass = resolveResult.getElement();
if (psiClass instanceof PsiAnonymousClass) {
return isAcceptable(((PsiAnonymousClass)psiClass).getBaseClassType(), checkReturnType);
return isAcceptable(((PsiAnonymousClass)psiClass).getBaseClassType());
}
if (MethodCandidateInfo.ourOverloadGuard.currentStack().contains(argsList)) {
final MethodCandidateInfo.CurrentCandidateProperties candidateProperties = MethodCandidateInfo.getCurrentMethod(argsList);
if (candidateProperties != null) {
final PsiMethod method = candidateProperties.getMethod();
if (!InferenceSession.isPertinentToApplicability(this, method) && hasFormalParameterTypes()) {
return true;
}
if (LambdaUtil.isPotentiallyCompatibleWithTypeParameter(this, argsList, method)) {
return true;
}
}
}
final PsiMethod interfaceMethod = LambdaUtil.getFunctionalInterfaceMethod(resolveResult);
@@ -206,56 +207,77 @@ public class PsiLambdaExpressionImpl extends ExpressionPsiElement implements Psi
final PsiSubstitutor substitutor = LambdaUtil.getSubstitutor(interfaceMethod, resolveResult);
assert leftType != null;
final PsiParameter[] lambdaParameters = getParameterList().getParameters();
final PsiType[] parameterTypes = interfaceMethod.getSignature(substitutor).getParameterTypes();
if (lambdaParameters.length != parameterTypes.length) return false;
if (!isPotentiallyCompatible(leftType)) {
return false;
}
for (int lambdaParamIdx = 0, length = lambdaParameters.length; lambdaParamIdx < length; lambdaParamIdx++) {
PsiParameter parameter = lambdaParameters[lambdaParamIdx];
final PsiTypeElement typeElement = parameter.getTypeElement();
if (typeElement != null) {
final PsiType lambdaFormalType = toArray(typeElement.getType());
final PsiType methodParameterType = toArray(parameterTypes[lambdaParamIdx]);
if (!lambdaFormalType.equals(methodParameterType)) {
return false;
if (MethodCandidateInfo.ourOverloadGuard.currentStack().contains(argsList) && !hasFormalParameterTypes()) {
return true;
}
if (hasFormalParameterTypes()) {
final PsiParameter[] lambdaParameters = getParameterList().getParameters();
final PsiType[] parameterTypes = interfaceMethod.getSignature(substitutor).getParameterTypes();
for (int lambdaParamIdx = 0, length = lambdaParameters.length; lambdaParamIdx < length; lambdaParamIdx++) {
PsiParameter parameter = lambdaParameters[lambdaParamIdx];
final PsiTypeElement typeElement = parameter.getTypeElement();
if (typeElement != null) {
final PsiType lambdaFormalType = toArray(typeElement.getType());
final PsiType methodParameterType = toArray(parameterTypes[lambdaParamIdx]);
if (!lambdaFormalType.equals(methodParameterType)) {
return false;
}
}
}
}
//A lambda expression (§15.27) is potentially compatible with a functional interface type (§9.8) if all of the following are true:
// The arity of the target type's function type is the same as the arity of the lambda expression.
// If the target type's function type has a void return, then the lambda body is either a statement expression (§14.8) or a void-compatible block (§15.27.2).
// If the target type's function type has a (non-void) return type, then the lambda body is either an expression or a value-compatible block (§15.27.2).
PsiType methodReturnType = interfaceMethod.getReturnType();
if (checkReturnType) {
final String uniqueVarName = JavaCodeStyleManager.getInstance(getProject()).suggestUniqueVariableName("l", this, true);
final String canonicalText = toArray(leftType).getCanonicalText();
final PsiStatement assignmentFromText = JavaPsiFacade.getElementFactory(getProject())
.createStatementFromText(canonicalText + " " + uniqueVarName + " = " + getText(), this);
final PsiLocalVariable localVariable = (PsiLocalVariable)((PsiDeclarationStatement)assignmentFromText).getDeclaredElements()[0];
if (methodReturnType != null) {
return LambdaHighlightingUtil.checkReturnTypeCompatible((PsiLambdaExpression)localVariable.getInitializer(),
substitutor.substitute(methodReturnType)) == null;
if (methodReturnType != null && methodReturnType != PsiType.VOID) {
Map<PsiElement, PsiType> map = LambdaUtil.ourFunctionTypes.get();
if (map == null) {
map = new HashMap<PsiElement, PsiType>();
LambdaUtil.ourFunctionTypes.set(map);
}
} else {
final PsiElement body = getBody();
if (methodReturnType == PsiType.VOID) {
if (body instanceof PsiCodeBlock) {
return isVoidCompatible();
} else {
return LambdaUtil.isExpressionStatementExpression(body);
try {
if (map.put(this, leftType) != null) {
return false;
}
} else {
if (body instanceof PsiCodeBlock) {
return isValueCompatible();
}
return body instanceof PsiExpression;
return LambdaHighlightingUtil.checkReturnTypeCompatible(this, substitutor.substitute(methodReturnType)) == null;
}
finally {
map.remove(this);
}
}
return true;
}
//A lambda expression (§15.27) is potentially compatible with a functional interface type (§9.8) if all of the following are true:
// The arity of the target type's function type is the same as the arity of the lambda expression.
// If the target type's function type has a void return, then the lambda body is either a statement expression (§14.8) or a void-compatible block (§15.27.2).
// If the target type's function type has a (non-void) return type, then the lambda body is either an expression or a value-compatible block (§15.27.2).
private boolean isPotentiallyCompatible(PsiType left) {
final PsiMethod interfaceMethod = LambdaUtil.getFunctionalInterfaceMethod(left);
if (interfaceMethod == null) return false;
if (getParameterList().getParametersCount() != interfaceMethod.getParameterList().getParametersCount()) {
return false;
}
final PsiType methodReturnType = interfaceMethod.getReturnType();
final PsiElement body = getBody();
if (methodReturnType == PsiType.VOID) {
if (body instanceof PsiCodeBlock) {
return isVoidCompatible();
} else {
return LambdaUtil.isExpressionStatementExpression(body);
}
}
else {
return body instanceof PsiCodeBlock && isValueCompatible() || body instanceof PsiExpression;
}
}
private static PsiType toArray(PsiType paramType) {
if (paramType instanceof PsiEllipsisType) {
return ((PsiEllipsisType)paramType).toArrayType();
@@ -20,6 +20,7 @@ import com.intellij.lang.ASTNode;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.TextRange;
import com.intellij.openapi.util.registry.Registry;
import com.intellij.psi.*;
import com.intellij.psi.impl.PsiImplUtil;
import com.intellij.psi.impl.source.resolve.graphInference.FunctionalInterfaceParameterizationUtil;
@@ -97,8 +98,8 @@ public class PsiMethodReferenceExpressionImpl extends PsiReferenceExpressionBase
final PsiElement element = resolveResult.getElement();
if (element instanceof PsiMethod) {
final boolean isStatic = ((PsiMethod)element).hasModifierProperty(PsiModifier.STATIC);
final int parametersCount = ((PsiMethod)element).getParameterList().getParametersCount();
if (qualifierResolveResult.isReferenceTypeQualified() && getReferenceNameElement() instanceof PsiIdentifier) {
final int parametersCount = ((PsiMethod)element).getParameterList().getParametersCount();
if (parametersCount == interfaceArity && isStatic) {
return true;
}
@@ -106,8 +107,11 @@ public class PsiMethodReferenceExpressionImpl extends PsiReferenceExpressionBase
return true;
}
if (((PsiMethod)element).isVarArgs()) return true;
} else if (!isStatic) {
return true;
}
else if (!isStatic) {
if (parametersCount == interfaceArity || ((PsiMethod)element).isVarArgs()) {
return true;
}
}
} else if (element instanceof PsiClass) {
return true;
@@ -370,12 +374,19 @@ public class PsiMethodReferenceExpressionImpl extends PsiReferenceExpressionBase
return false;
}
final PsiElement argsList = PsiTreeUtil.getParentOfType(this, PsiExpressionList.class);
final PsiExpressionList argsList = PsiTreeUtil.getParentOfType(this, PsiExpressionList.class);
final boolean isExact = isExact();
if (MethodCandidateInfo.ourOverloadGuard.currentStack().contains(argsList) && isExact) {
if (MethodCandidateInfo.ourOverloadGuard.currentStack().contains(argsList)) {
final MethodCandidateInfo.CurrentCandidateProperties candidateProperties = MethodCandidateInfo.getCurrentMethod(argsList);
if (candidateProperties != null && !InferenceSession.isPertinentToApplicability(this, candidateProperties.getMethod())) {
return true;
if (candidateProperties != null) {
final PsiMethod method = candidateProperties.getMethod();
if (isExact && !InferenceSession.isPertinentToApplicability(this, method)) {
return true;
}
if (LambdaUtil.isPotentiallyCompatibleWithTypeParameter(this, argsList, method)) {
return true;
}
}
}
@@ -33,6 +33,7 @@ import com.intellij.util.containers.HashSet;
import gnu.trove.THashMap;
import gnu.trove.THashSet;
import gnu.trove.TIntArrayList;
import gnu.trove.TObjectHashingStrategy;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
@@ -91,9 +92,6 @@ public class JavaMethodsConflictResolver implements PsiConflictResolver{
// then noone can be more specific
if (!atLeastOneMatch) return null;
checkLambdaApplicable(conflicts, myLanguageLevel);
if (conflicts.size() == 1) return conflicts.get(0);
checkSpecifics(conflicts, applicabilityLevel, myLanguageLevel);
if (conflicts.size() == 1) return conflicts.get(0);
@@ -108,63 +106,6 @@ public class JavaMethodsConflictResolver implements PsiConflictResolver{
return null;
}
private void checkLambdaApplicable(@NotNull List<CandidateInfo> conflicts, @NotNull LanguageLevel languageLevel) {
if (!languageLevel.isAtLeast(LanguageLevel.JDK_1_8)) return;
for (int i = 0; i < getActualParametersLength(); i++) {
PsiExpression expression;
if (myArgumentsList instanceof PsiExpressionList) {
expression = ((PsiExpressionList)myArgumentsList).getExpressions()[i];
}
else {
final PsiType argType = getActualParameterTypes()[i];
expression = argType instanceof PsiLambdaExpressionType ? ((PsiLambdaExpressionType)argType).getExpression() : null;
}
final PsiLambdaExpression lambdaExpression = findNestedLambdaExpression(expression);
if (lambdaExpression != null) {
checkLambdaApplicable(conflicts, i, lambdaExpression);
}
}
}
private static PsiLambdaExpression findNestedLambdaExpression(PsiExpression expression) {
if (expression instanceof PsiLambdaExpression) {
return (PsiLambdaExpression)expression;
}
else if (expression instanceof PsiParenthesizedExpression) {
return findNestedLambdaExpression(((PsiParenthesizedExpression)expression).getExpression());
}
else if (expression instanceof PsiConditionalExpression) {
PsiLambdaExpression lambdaExpression = findNestedLambdaExpression(((PsiConditionalExpression)expression).getThenExpression());
if (lambdaExpression != null) {
return lambdaExpression;
}
return findNestedLambdaExpression(((PsiConditionalExpression)expression).getElseExpression());
}
return null;
}
private static void checkLambdaApplicable(@NotNull List<CandidateInfo> conflicts, int i, @NotNull PsiLambdaExpression lambdaExpression) {
for (Iterator<CandidateInfo> iterator = conflicts.iterator(); iterator.hasNext(); ) {
ProgressManager.checkCanceled();
final CandidateInfo conflict = iterator.next();
final PsiMethod method = (PsiMethod)conflict.getElement();
final PsiParameter[] methodParameters = method.getParameterList().getParameters();
if (methodParameters.length == 0) continue;
final PsiParameter param = i < methodParameters.length ? methodParameters[i] : methodParameters[methodParameters.length - 1];
final PsiType paramType = param.getType();
// http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.12.2.1
// A lambda expression or a method reference expression is potentially compatible with a type variable if the type variable is a type parameter of the candidate method.
final PsiClass paramClass = PsiUtil.resolveClassInType(paramType);
if (paramClass instanceof PsiTypeParameter && ((PsiTypeParameter)paramClass).getOwner() == method) continue;
if (!lambdaExpression.isAcceptable(((MethodCandidateInfo)conflict).getSubstitutor(false).substitute(paramType),
InferenceSession.isPertinentToApplicability(lambdaExpression, method))) {
iterator.remove();
}
}
}
public void checkSpecifics(@NotNull List<CandidateInfo> conflicts,
@MethodCandidateInfo.ApplicabilityLevelConstant int applicabilityLevel,
@NotNull LanguageLevel languageLevel) {
@@ -20,7 +20,7 @@ public class Test<A, B extends Number> {
public static void main(String[] args) {
Inner<Number, Double> inn = new Inner<>();
inn.m8<error descr="Ambiguous method call: both 'Inner.m8(IO<? extends Number>)' and 'Inner.m8(IN<? extends Double>)' match">(p -> 1.0)</error>;
new Test<Number, Integer>().foo<error descr="Ambiguous method call: both 'Test.foo(IO<? extends Number>)' and 'Test.foo(IN<? extends Integer>)' match">(p -> 1.0)</error>;
new Test<Number, Integer>().foo<error descr="Cannot resolve method 'foo(<lambda expression>)'">(p -> 1.0)</error>;
}
}
@@ -1,7 +1,7 @@
class Demo {
public void f1() {
f2(2, <error descr="Target type of a lambda conversion must be an interface">input -> input</error>);
f2<error descr="Cannot resolve method 'f2(int, <lambda expression>)'">(2, input -> input)</error>;
}
public void f2() {
@@ -25,7 +25,7 @@ class ReturnTypeIncompatibility {
}
public static void main(String[] args) {
call<error descr="Ambiguous method call: both 'ReturnTypeIncompatibility.call(I1<Integer>)' and 'ReturnTypeIncompatibility.call(I2<P>)' match">(i-> {return i;})</error>;
call<error descr="Cannot resolve method 'call(<lambda expression>)'">(i-> {return i;})</error>;
}
}
@@ -57,7 +57,7 @@ class ReturnTypeCompatibility {
}
public static void main(String[] args) {
call<error descr="Ambiguous method call: both 'ReturnTypeCompatibility.call(I1<Number>)' and 'ReturnTypeCompatibility.call(I2<String>)' match">(i-> {return i;})</error>;
call<error descr="Cannot resolve method 'call(<lambda expression>)'">(i-> {return i;})</error>;
}
}
@@ -21,9 +21,9 @@ class Test {
}
void foo(Foo<String> as, final Foo<Character> ac) {
boolean b1 = as.forAll(s -> ac.forAll<error descr="Ambiguous method call: both 'Foo.forAll(I<Character, Boolean>)' and 'Foo.forAll(II<Character, String>)' match">(c -> false)</error>);
String s1 = as.forAll(s -> ac.forAll<error descr="Ambiguous method call: both 'Foo.forAll(I<Character, Boolean>)' and 'Foo.forAll(II<Character, String>)' match">(c -> "")</error>);
boolean b2 = as.forAll(s -> ac.forAll<error descr="Ambiguous method call: both 'Foo.forAll(I<Character, Boolean>)' and 'Foo.forAll(II<Character, String>)' match">(c -> "")</error>);
boolean b1 = as.forAll(s -> ac.forAll<error descr="Cannot resolve method 'forAll(<lambda expression>)'">(c -> false)</error>);
String s1 = as.forAll(s -> ac.forAll<error descr="Cannot resolve method 'forAll(<lambda expression>)'">(c -> "")</error>);
boolean b2 = as.forAll(s -> ac.forAll<error descr="Cannot resolve method 'forAll(<lambda expression>)'">(c -> "")</error>);
String s2 = as.forAll2(s -> ac.forAll2(<error descr="Incompatible return type boolean in lambda expression">c -> false</error>));
boolean b3 = as.forAll((I<String, Boolean>)s -> ac.forAll((I<Character, Boolean>)<error descr="Incompatible return type String in lambda expression">c -> ""</error>));
String s3 = as.forAll((II<String, String>)s -> ac.forAll((II<Character, String>)<error descr="Incompatible return type boolean in lambda expression">c -> false</error>));
@@ -0,0 +1,40 @@
import java.util.List;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.function.Function;
class Test {
private List<String> query(String request) {
System.out.println(request);
return null;
}
private List<String> <warning descr="Private method 'query(java.lang.String, java.lang.Object)' is never used">query</warning>(String request, Object context) {
System.out.println(request + context);
return null;
}
private List<String> <warning descr="Private method 'query1()' is never used">query1</warning>(){ return null;}
private List<String> <warning descr="Private method 'query1(java.lang.String)' is never used">query1</warning>(String request) {
System.out.println(request);
return null;
}
private List<String> <warning descr="Private method 'query1(java.lang.String, java.lang.Object)' is never used">query1</warning>(String request, Object context) {
System.out.println(request + context);
return null;
}
private static <Message, Reply> Set<Message> replyWith(Function<Message, List<Reply>> futureFn){
System.out.println(futureFn);
return null;
}
private static <Message, Reply> Set<Message> <warning descr="Private method 'replyWith(java.util.concurrent.Callable<java.util.List<Reply>>)' is never used">replyWith</warning>(Callable<List<Reply>> fn) {
System.out.println(fn);
return null;
}
{
Set<String> m = replyWith(this::query);
System.out.println(m);
Set<String> m1 = replyWith<error descr="Ambiguous method call: both 'Test.replyWith(Function<String, List<String>>)' and 'Test.replyWith(Callable<List<String>>)' match">(this::query1)</error>;
System.out.println(m1);
}
}
@@ -14,7 +14,7 @@ class Test {
}
void fooBar(IntStream1 instr){
Supplier<Stream<Integer>> si = () -> instr.map ((i) -> (( <error descr="Operator '%' cannot be applied to '<lambda parameter>', 'int'">i % 2</error>) == 0) ? i : <error descr="Incompatible types. Found: '<lambda parameter>', required: '<lambda parameter>'">-i</error>).boxed();
Supplier<Stream<Integer>> si = () -> instr.map ((i) -> (( <error descr="Operator '%' cannot be applied to '<lambda parameter>', 'int'">i % 2</error>) == 0) ? i : -i).boxed();
System.out.println(si);
Supplier<Stream<Integer>> si1 = () -> instr.map <error descr="Ambiguous method call: both 'IntStream1.map(IntFunction<Integer>)' and 'IntStream1.map(IntUnaryOperator)' match">(null)</error>.boxed();
System.out.println(si1);
@@ -12,6 +12,6 @@ abstract class PertinentToApplicabilityOfExplicitlyTypedLambdaTest {
abstract void foo(B b);
{
foo<error descr="Ambiguous method call: both 'PertinentToApplicabilityOfExplicitlyTypedLambdaTest.foo(A)' and 'PertinentToApplicabilityOfExplicitlyTypedLambdaTest.foo(B)' match">(x -> y -> 42)</error>;
foo<error descr="Cannot resolve method 'foo(<lambda expression>)'">(x -> y -> 42)</error>;
}
}
@@ -14,10 +14,10 @@ abstract class Test {
foo(x -> {
return x += 1;
});
foo(x -> <error descr="Incompatible types. Found: 'int', required: '<lambda parameter>'">x += 1</error>);
foo<error descr="Ambiguous method call: both 'Test.foo(A)' and 'Test.foo(B)' match">(x -> x += 1)</error>;
foo(x -> 1);
foo(x -> <error descr="Operator '!' cannot be applied to 'int'">!x</error>);
foo(x -> <error descr="Operator '++' cannot be applied to '<lambda parameter>'">++x</error>);
foo<error descr="Ambiguous method call: both 'Test.foo(A)' and 'Test.foo(B)' match">(x -> ++x)</error>;
foo(x -> o instanceof String ? 1 : 0);
}
}
@@ -26,9 +26,9 @@ class Foo {
System.out.println(s);
});
<error descr="Cannot resolve method 'foo(<lambda expression>)'">foo</error>((String p, String k) -> {
foo<error descr="Cannot resolve method 'foo(<lambda expression>)'">((String p, String k) -> {
System.out.println(p);
});
})</error>;
}
}
@@ -62,7 +62,7 @@ class WithTypeParams {
System.out.println(p);
});
<error descr="Cannot resolve method 'foo(<lambda expression>)'">foo</error>((int k) -> {System.out.println(k);});
foo<error descr="Cannot resolve method 'foo(<lambda expression>)'">((int k) -> {System.out.println(k);})</error>;
}
}
}
@@ -0,0 +1,12 @@
import org.jetbrains.annotations.Nullable;
class City {
@Nullable
private String name;
@Override
@Nullable
public String toString() {
return name;
}
}
@@ -19,6 +19,7 @@ import com.intellij.codeInsight.daemon.LightDaemonAnalyzerTestCase;
import com.intellij.codeInspection.deadCode.UnusedDeclarationInspection;
import com.intellij.openapi.projectRoots.JavaSdkVersion;
import com.intellij.openapi.projectRoots.Sdk;
import com.intellij.openapi.util.registry.Registry;
import com.intellij.testFramework.IdeaTestUtil;
import org.jetbrains.annotations.NonNls;
@@ -100,7 +101,9 @@ public class MostSpecificResolutionTest extends LightDaemonAnalyzerTestCase {
}
public void testJDK8042508() throws Exception {
doTest(false);
if (Registry.is("JDK8042508.bug.fixed", false)) {
doTest(false);
}
}
public void testIDEA125855() throws Exception {
@@ -334,6 +334,10 @@ public class NewMethodRefHighlightingTest extends LightDaemonAnalyzerTestCase {
doTest(true);
}
public void testPotentialCompatibilityWithInvalidShape() throws Exception {
doTest(true);
}
private void doTest() {
doTest(false);
}
@@ -268,6 +268,7 @@ public class DataFlowInspectionTest extends LightCodeInsightFixtureTestCase {
public void testSameComparisonTwice() { doTest(); }
public void testRootThrowableCause() { doTest(); }
public void testOverridingInferredNotNullMethod() { doTest(); }
public void testUseInferredContracts() { doTest(); }
public void testContractWithNoArgs() { doTest(); }
public void testContractInferenceBewareOverriding() { doTest(); }
@@ -44,11 +44,13 @@ object IndexTestGenerator {
const(InvisiblePsiChange),
const(PostponedFormatting),
const(Reformat),
const(LoadViewProviderDocument),
const(ForceReloadPsi),
const(AddEnum),
const(CheckStamps),
for (withImport <- arbitrary[Boolean];
viaDocument <- arbitrary[Boolean])
yield TextChange(viaDocument, withImport),
arbitrary[Boolean] map ChangeLanguageLevel,
arbitrary[Boolean] map UpdatePsiClassRef,
arbitrary[Boolean] map UpdatePsiFileRef,
arbitrary[Boolean] map UpdateASTNodeRef,
@@ -97,18 +99,26 @@ case class IndexTestSeq(actions: List[Action]) {
|""".stripMargin)
}
def printPostponedFormatting = sb.append(
"""PostprocessReformattingAspect.getInstance(getProject()).
| doPostponedFormatting()
|""".stripMargin)
for (action <- actions) {
sb.append("\n")
action match {
case Gc =>
sb.append("PlatformTestUtil.tryGcSoftlyReachableObjects()\n")
case LoadViewProviderDocument =>
sb.append("assert psiManager.findFile(vFile).viewProvider.document\n")
case PostponedFormatting =>
sb.append(
"""PostprocessReformattingAspect.getInstance(getProject()).
| doPostponedFormatting()
|""".stripMargin)
printPostponedFormatting
case ForceReloadPsi =>
printPostponedFormatting
sb.append("FileContentUtilCore.reparseFiles(vFile)\n")
case ChangeLanguageLevel(highest) =>
printPostponedFormatting
val level = if (highest) "HIGHEST" else "JDK_1_3"
sb.append(s"IdeaTestUtil.setModuleLanguageLevel(myFixture.module, LanguageLevel.$level)\n")
case CheckStamps =>
sb.append(
"""L:{
@@ -147,6 +157,12 @@ case class IndexTestSeq(actions: List[Action]) {
s"""((PsiJavaFile)psiManager.findFile(vFile)).importList.add(
| elementFactory.createImportStatementOnDemand("java.io"))
|""".stripMargin)
case AddEnum =>
printCommit
sb.append(
s"""psiManager.findFile(vFile).add(
| elementFactory.createEnum("SomeEnum"))
|""".stripMargin)
case InvisiblePsiChange =>
printCommit
sb.append(
@@ -167,14 +183,13 @@ case class IndexTestSeq(actions: List[Action]) {
case UpdateDocumentRef(load) =>
sb.append("document = " + (if (load) "FileDocumentManager.instance.getDocument(vFile)" else "null") + "\n")
case TextChange(viaDocument, withImport) =>
printPostponedFormatting
changeId += 1
docClassName = "Foo" + changeId
val newText = (if (withImport) "import zoo.Zoo; " else "") + s"class $docClassName {\\n }"
sb.append(
"""PostprocessReformattingAspect.getInstance(getProject()).
| doPostponedFormatting()
|counterBefore =
"""counterBefore =
| psiManager.modificationTracker.javaStructureModificationCount
|""".stripMargin)
@@ -214,13 +229,14 @@ case class IndexTestSeq(actions: List[Action]) {
|import com.intellij.openapi.fileEditor.FileDocumentManager
|import com.intellij.openapi.util.Ref
|import com.intellij.openapi.vfs.VfsUtil
|import com.intellij.pom.java.*
|import com.intellij.psi.*
|import com.intellij.psi.codeStyle.*
|import com.intellij.psi.impl.source.*
|import com.intellij.psi.search.GlobalSearchScope
|import com.intellij.testFramework.PlatformTestUtil
|import com.intellij.testFramework.*
|import com.intellij.testFramework.fixtures.JavaCodeInsightFixtureTestCase
|import com.intellij.util.ObjectUtils
|import com.intellij.util.*
|import com.intellij.openapi.fileEditor.impl.LoadTextUtil
|import org.jetbrains.annotations.NotNull
|class DummyTest extends JavaCodeInsightFixtureTestCase {
@@ -264,5 +280,7 @@ case object PsiChange extends Action
case object InvisiblePsiChange extends Action
case object PostponedFormatting extends Action
case object Reformat extends Action
case object LoadViewProviderDocument extends Action
case object CheckStamps extends Action
case object ForceReloadPsi extends Action
case object AddEnum extends Action
case class ChangeLanguageLevel(highest: Boolean) extends Action
@@ -17,6 +17,7 @@ package com.intellij.navigation
import com.intellij.ide.actions.GotoFileItemProvider
import com.intellij.ide.util.gotoByName.ChooseByNamePopup
import com.intellij.ide.util.gotoByName.GotoFileModel
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.util.io.FileUtil
import com.intellij.testFramework.fixtures.JavaCodeInsightFixtureTestCase
import org.jetbrains.annotations.NotNull
@@ -27,12 +28,16 @@ class ChooseByNameHddTest extends JavaCodeInsightFixtureTestCase {
public void "test go to file by full path"() {
def psiFile = myFixture.addFileToProject("foo/index.html", "foo")
def path = psiFile.virtualFile.path
def vFile = psiFile.virtualFile
def path = vFile.path
def popup = ChooseByNamePopup.createPopup(project, new GotoFileModel(project), new GotoFileItemProvider(project, null))
assert ChooseByNameTest.calcPopupElements(popup, path) == [psiFile]
assert ChooseByNameTest.calcPopupElements(popup, FileUtil.toSystemDependentName(path)) == [psiFile]
popup.close(false)
ApplicationManager.application.runReadAction {
def popup = ChooseByNamePopup.createPopup(project, new GotoFileModel(project), new GotoFileItemProvider(project, null))
assert ChooseByNameTest.calcPopupElements(popup, path) == [psiFile]
assert ChooseByNameTest.calcPopupElements(popup, FileUtil.toSystemDependentName(path)) == [psiFile]
assert ChooseByNameTest.calcPopupElements(popup, vFile.parent.path) == [psiFile.containingDirectory]
popup.close(false)
}
}
@Override
@@ -101,7 +101,7 @@ public class Mappings {
myLock = base.myLock;
myIsDelta = true;
myChangedClasses = new TIntHashSet(DEFAULT_SET_CAPACITY, DEFAULT_SET_LOAD_FACTOR);
myChangedFiles = new THashSet(FileUtil.FILE_HASHING_STRATEGY);
myChangedFiles = new THashSet<File>(FileUtil.FILE_HASHING_STRATEGY);
myDeletedClasses = new HashSet<Pair<ClassRepr, File>>(DEFAULT_SET_CAPACITY, DEFAULT_SET_LOAD_FACTOR);
myAddedClasses = new HashSet<ClassRepr>(DEFAULT_SET_CAPACITY, DEFAULT_SET_LOAD_FACTOR);
myDeltaIsTransient = base.myDeltaIsTransient;
@@ -2003,51 +2003,60 @@ public class Mappings {
debug("Begin of Differentiate:");
debug("Easy mode: ", myEasyMode);
processDisappearedClasses();
try {
processDisappearedClasses();
final List<FileClasses> newClasses = new ArrayList<FileClasses>();
myDelta.mySourceFileToClasses.forEachEntry(new TObjectObjectProcedure<File, Collection<ClassRepr>>() {
@Override
public boolean execute(File fileName, Collection<ClassRepr> classes) {
newClasses.add(new FileClasses(fileName, classes));
return true;
}
});
final List<FileClasses> newClasses = new ArrayList<FileClasses>();
myDelta.mySourceFileToClasses.forEachEntry(new TObjectObjectProcedure<File, Collection<ClassRepr>>() {
@Override
public boolean execute(File fileName, Collection<ClassRepr> classes) {
newClasses.add(new FileClasses(fileName, classes));
return true;
}
});
for (final FileClasses compiledFile : newClasses) {
final File fileName = compiledFile.myFileName;
final Set<ClassRepr> classes = compiledFile.myFileClasses;
final Set<ClassRepr> pastClasses = (Set<ClassRepr>)mySourceFileToClasses.get(fileName);
final DiffState state = new DiffState(Difference.make(pastClasses, classes));
if (!processChangedClasses(state)) {
for (final FileClasses compiledFile : newClasses) {
final File fileName = compiledFile.myFileName;
final Set<ClassRepr> classes = compiledFile.myFileClasses;
final Set<ClassRepr> pastClasses = (Set<ClassRepr>)mySourceFileToClasses.get(fileName);
final DiffState state = new DiffState(Difference.make(pastClasses, classes));
if (!processChangedClasses(state)) {
if (!myEasyMode) {
// turning non-incremental
return false;
}
}
processRemovedClases(state, fileName);
processAddedClasses(state, fileName);
if (!myEasyMode) {
// turning non-incremental
return false;
calculateAffectedFiles(state);
}
}
processRemovedClases(state, fileName);
processAddedClasses(state, fileName);
debug("End of Differentiate.");
if (!myEasyMode) {
calculateAffectedFiles(state);
if (myEasyMode) {
return false;
}
final Collection<String> removed = myDelta.myRemovedFiles;
if (removed != null) {
for (final String r : removed) {
myAffectedFiles.remove(new File(r));
}
}
return myDelayedWorks.doWork(myAffectedFiles);
}
finally {
if (myFilesToCompile != null) {
// if some class is associated with several sources,
// some of them may not have been compiled in this round, so such files should be considered unchanged
myDelta.myChangedFiles.retainAll(myFilesToCompile);
}
}
debug("End of Differentiate.");
if (myEasyMode) {
return false;
}
final Collection<String> removed = myDelta.myRemovedFiles;
if (removed != null) {
for (final String r : removed) {
myAffectedFiles.remove(new File(r));
}
}
return myDelayedWorks.doWork(myAffectedFiles);
}
}
}
@@ -18,11 +18,9 @@ package com.intellij.codeHighlighting;
import com.intellij.lang.annotation.HighlightSeverity;
import com.intellij.openapi.editor.colors.CodeInsightColors;
import com.intellij.openapi.editor.colors.EditorColorsManager;
import com.intellij.openapi.editor.colors.EditorColorsScheme;
import com.intellij.openapi.editor.colors.TextAttributesKey;
import com.intellij.openapi.editor.markup.TextAttributes;
import com.intellij.openapi.util.Comparing;
import com.intellij.ui.JBColor;
import com.intellij.util.containers.HashMap;
import com.intellij.util.ui.ColorIcon;
import org.jetbrains.annotations.NotNull;
@@ -39,10 +37,8 @@ public class HighlightDisplayLevel {
createIconByKey(CodeInsightColors.GENERIC_SERVER_ERROR_OR_WARNING));
public static final HighlightDisplayLevel ERROR = new HighlightDisplayLevel(HighlightSeverity.ERROR, createIconByKey(CodeInsightColors.ERRORS_ATTRIBUTES));
public static final HighlightDisplayLevel WARNING = new HighlightDisplayLevel(HighlightSeverity.WARNING, createIconByKey(CodeInsightColors.WARNINGS_ATTRIBUTES));
// todo: move to color schemas
public static final Color GREEN = new JBColor(new Color(113, 178, 98), new Color(30, 160, 0));
public static final Color TYPO = new JBColor(new Color(176, 209, 171), new Color(30, 160, 0));
public static final HighlightDisplayLevel DO_NOT_SHOW = new HighlightDisplayLevel(HighlightSeverity.INFORMATION, createIconByMask(GREEN));
private static final Icon DO_NOT_SHOW_KEY = createIconByKey(TextAttributesKey.createTextAttributesKey("DO_NOT_SHOW"));
public static final HighlightDisplayLevel DO_NOT_SHOW = new HighlightDisplayLevel(HighlightSeverity.INFORMATION, DO_NOT_SHOW_KEY);
/**
* use #WEAK_WARNING instead
*/
@@ -100,8 +96,8 @@ public class HighlightDisplayLevel {
return mySeverity;
}
public static void registerSeverity(@NotNull HighlightSeverity severity, final Color renderColor) {
Icon severityIcon = createIconByMask(renderColor);
public static void registerSeverity(@NotNull HighlightSeverity severity, final TextAttributesKey key) {
Icon severityIcon = createIconByKey(key);
final HighlightDisplayLevel level = ourMap.get(severity);
if (level == null) {
new HighlightDisplayLevel(severity, severityIcon);
@@ -147,19 +143,20 @@ public class HighlightDisplayLevel {
public Color getColor() {
final EditorColorsManager manager = EditorColorsManager.getInstance();
if (manager != null) {
final EditorColorsScheme globalScheme = manager.getGlobalScheme();
return globalScheme.getAttributes(myKey).getErrorStripeColor();
TextAttributes attributes = manager.getGlobalScheme().getAttributes(myKey);
Color stripe = attributes.getErrorStripeColor();
if (stripe != null) return stripe;
return attributes.getEffectColor();
}
TextAttributes defaultAttributes = myKey.getDefaultAttributes();
if (defaultAttributes == null) defaultAttributes = TextAttributes.ERASE_MARKER;
return defaultAttributes.getErrorStripeColor();
return defaultAttributes.getErrorStripeColor();
}
@Override
public void paintIcon(final Component c, final Graphics g, final int x, final int y) {
final Graphics2D g2 = (Graphics2D)g;
g2.setColor(getColor());
g2.fillRect(x, y, EMPTY_ICON_DIM, EMPTY_ICON_DIM);
g.setColor(getColor());
g.fillRect(x, y, EMPTY_ICON_DIM, EMPTY_ICON_DIM);
}
@Override
@@ -172,4 +169,17 @@ public class HighlightDisplayLevel {
return EMPTY_ICON_DIM;
}
}
public static class SemiBorderIcon extends SingleColorIcon {
public SemiBorderIcon(TextAttributesKey key) {
super(key);
}
@Override
public void paintIcon(Component component, Graphics g, int x, int y) {
g.setColor(getColor());
g.fillRect(x, y, 1, getIconHeight());
g.fillRect(x, y + getIconHeight() - 1, getIconWidth(), 1);
}
}
}
@@ -93,7 +93,7 @@ public class SeverityRegistrar implements JDOMExternalizable, Comparator<Highlig
myRendererColors.put(severity.getName(), renderColor);
}
myOrderMap = null;
HighlightDisplayLevel.registerSeverity(severity, renderColor);
HighlightDisplayLevel.registerSeverity(severity, getHighlightInfoTypeBySeverity(severity).getAttributesKey());
severitiesChanged();
}
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2009 JetBrains s.r.o.
* Copyright 2000-2014 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.
@@ -100,8 +100,9 @@ public abstract class DocumentCommitProcessor {
}
}
// public for Upsource
@Nullable("returns runnable to execute under write action in AWT to finish the commit")
Processor<Document> doCommit(@NotNull final CommitTask task,
public Processor<Document> doCommit(@NotNull final CommitTask task,
@NotNull final PsiFile file,
final boolean synchronously) {
Document document = task.document;
@@ -282,7 +282,8 @@ public abstract class PsiDocumentManagerBase extends PsiDocumentManager implemen
}
}
boolean finishCommit(@NotNull final Document document,
// public for Upsource
public boolean finishCommit(@NotNull final Document document,
@NotNull final List<Processor<Document>> finishProcessors,
final boolean synchronously,
@NotNull final Object reason) {
@@ -363,7 +364,7 @@ public abstract class PsiDocumentManagerBase extends PsiDocumentManager implemen
}
}
private void doCommit(@NotNull final Document document) {
protected void doCommit(@NotNull final Document document) {
assert !myIsCommitInProgress : "Do not call commitDocument() from inside PSI change listener";
ApplicationManager.getApplication().runWriteAction(new Runnable() {
@Override
@@ -29,6 +29,7 @@ import com.intellij.lang.annotation.HighlightSeverity;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.colors.TextAttributesKey;
import com.intellij.openapi.editor.ex.EditorMarkupModel;
import com.intellij.openapi.editor.ex.MarkupModelEx;
import com.intellij.openapi.editor.ex.RangeHighlighterEx;
@@ -47,13 +48,10 @@ import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.FileViewProvider;
import com.intellij.psi.PsiCompiledElement;
import com.intellij.psi.PsiFile;
import com.intellij.ui.ColorUtil;
import com.intellij.ui.JBColor;
import com.intellij.ui.LayeredIcon;
import com.intellij.util.ArrayUtil;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.io.storage.HeavyProcessLatch;
import com.intellij.util.ui.EmptyIcon;
import com.intellij.util.ui.UIUtil;
import com.intellij.xml.util.XmlStringUtil;
import gnu.trove.TIntArrayList;
@@ -67,7 +65,8 @@ import java.util.*;
import java.util.List;
public class TrafficLightRenderer implements ErrorStripeRenderer, Disposable {
private static final Icon NO_ANALYSIS = new SemiBorderIcon();
private static final TextAttributesKey NO_ANALYSIS = TextAttributesKey.createTextAttributesKey("NO_ANALYSIS");
private static final Icon NO_ANALYSIS_ICON = new HighlightDisplayLevel.SemiBorderIcon(NO_ANALYSIS);
private final Project myProject;
private final Document myDocument;
private final PsiFile myFile;
@@ -341,7 +340,7 @@ public class TrafficLightRenderer implements ErrorStripeRenderer, Disposable {
statusExtraLine = "(" + status.reasonWhyDisabled + ")";
passStatusesVisible = true;
progressBarsCompleted = Boolean.FALSE;
icon = NO_ANALYSIS;
icon = NO_ANALYSIS_ICON;
return result;
}
if (status.reasonWhySuspended != null) {
@@ -416,17 +415,4 @@ public class TrafficLightRenderer implements ErrorStripeRenderer, Disposable {
passes.put(pass, Pair.create(progressBar, percLabel));
}
}
public static class SemiBorderIcon extends EmptyIcon {
public SemiBorderIcon() {
super(HighlightDisplayLevel.EMPTY_ICON_DIM, HighlightDisplayLevel.EMPTY_ICON_DIM);
}
@Override
public void paintIcon(Component component, Graphics g, int x, int y) {
g.setColor(new JBColor(ColorUtil.fromHex("d3d3d3"), ColorUtil.fromHex("4a4a4b")));
g.fillRect(x, y, 1, getIconHeight());
g.fillRect(x, y + getIconHeight() - 1, getIconWidth(), 1);
}
}
}
@@ -19,17 +19,17 @@ import com.intellij.ide.util.gotoByName.ChooseByNameBase;
import com.intellij.ide.util.gotoByName.DefaultChooseByNameItemProvider;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.roots.ProjectFileIndex;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiFileSystemItem;
import com.intellij.psi.PsiManager;
import com.intellij.util.Processor;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.File;
/**
* @author peter
*/
@@ -48,11 +48,17 @@ public class GotoFileItemProvider extends DefaultChooseByNameItemProvider {
@NotNull ProgressIndicator indicator,
@NotNull Processor<Object> consumer) {
if (pattern.contains("/") || pattern.contains("\\")) {
File ioFile = new File(pattern);
VirtualFile vFile = ioFile.exists() ? LocalFileSystem.getInstance().refreshAndFindFileByIoFile(ioFile) : null;
PsiFile psiFile = vFile == null ? null : PsiManager.getInstance(myProject).findFile(vFile);
if (psiFile != null && !consumer.process(psiFile)) {
return false;
VirtualFile vFile = LocalFileSystem.getInstance().findFileByPathIfCached(FileUtil.toSystemIndependentName(pattern));
if (vFile != null) {
ProjectFileIndex index = ProjectFileIndex.SERVICE.getInstance(myProject);
if (index.isInContent(vFile) || index.isInLibraryClasses(vFile) || index.isInLibrarySource(vFile)) {
PsiFileSystemItem fileOrDir = vFile.isDirectory() ?
PsiManager.getInstance(myProject).findDirectory(vFile) :
PsiManager.getInstance(myProject).findFile(vFile);
if (fileOrDir != null && !consumer.process(fileOrDir)) {
return false;
}
}
}
}
@@ -28,6 +28,7 @@ import com.intellij.navigation.NavigationItem;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.RangeMarker;
import com.intellij.openapi.editor.colors.CodeInsightColors;
import com.intellij.openapi.editor.colors.EditorColors;
import com.intellij.openapi.editor.colors.EditorColorsManager;
import com.intellij.openapi.editor.ex.MarkupModelEx;
import com.intellij.openapi.editor.ex.RangeHighlighterEx;
@@ -358,7 +359,7 @@ public class Bookmark implements Navigatable {
}
private static boolean darkBackground() {
return ColorUtil.isDark(EditorColorsManager.getInstance().getGlobalScheme().getDefaultBackground()); // or gutter background?
return ColorUtil.isDark(EditorColorsManager.getInstance().getGlobalScheme().getColor(EditorColors.GUTTER_BACKGROUND));
}
private static class MyGutterIconRenderer extends GutterIconRenderer {
@@ -823,6 +823,11 @@ public class EditorWindowImpl extends UserDataHolderBase implements EditorWindow
myDelegate.setPlaceholder(text);
}
@Override
public void setShowPlaceholderWhenFocused(boolean show) {
myDelegate.setShowPlaceholderWhenFocused(show);
}
@Override
public boolean isStickySelection() {
return myDelegate.isStickySelection();
@@ -30,10 +30,7 @@ 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.colors.EditorColorsManager;
import com.intellij.openapi.editor.colors.EditorColorsScheme;
import com.intellij.openapi.editor.colors.TextAttributesKey;
import com.intellij.openapi.editor.markup.TextAttributes;
import com.intellij.openapi.extensions.Extensions;
import com.intellij.openapi.options.BaseSchemeProcessor;
import com.intellij.openapi.options.Scheme;
@@ -148,17 +145,12 @@ public class InspectionProfileManagerImpl extends InspectionProfileManager imple
}
public static void registerProvidedSeverities() {
final EditorColorsScheme scheme = EditorColorsManager.getInstance().getGlobalScheme();
for (SeveritiesProvider provider : Extensions.getExtensions(SeveritiesProvider.EP_NAME)) {
for (HighlightInfoType highlightInfoType : provider.getSeveritiesHighlightInfoTypes()) {
final HighlightSeverity highlightSeverity = highlightInfoType.getSeverity(null);
HighlightSeverity highlightSeverity = highlightInfoType.getSeverity(null);
SeverityRegistrar.registerStandard(highlightInfoType, highlightSeverity);
final TextAttributesKey attributesKey = highlightInfoType.getAttributesKey();
TextAttributes textAttributes = scheme.getAttributes(attributesKey);
if (textAttributes == null) {
textAttributes = attributesKey.getDefaultAttributes();
}
HighlightDisplayLevel.registerSeverity(highlightSeverity, provider.getTrafficRendererColor(textAttributes));
TextAttributesKey attributesKey = highlightInfoType.getAttributesKey();
HighlightDisplayLevel.registerSeverity(highlightSeverity, attributesKey);
}
}
}
@@ -324,7 +324,9 @@ public class SingleInspectionProfilePanel extends JPanel {
for (HighlightSeverity severity : severities) {
final TextAttributesKey attributesKey = TextAttributesKey.find(severity.getName());
final TextAttributes textAttributes = oppositeRegister.getTextAttributesBySeverity(severity);
LOG.assertTrue(textAttributes != null, severity);
if (textAttributes == null) {
continue;
}
HighlightInfoType.HighlightInfoTypeImpl info = new HighlightInfoType.HighlightInfoTypeImpl(severity, attributesKey);
registrar.registerSeverity(new SeverityRegistrar.SeverityBasedTextAttributes(textAttributes.clone(), info),
textAttributes.getErrorStripeColor());
@@ -34,6 +34,7 @@ import com.intellij.icons.AllIcons;
import com.intellij.lang.annotation.HighlightSeverity;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.colors.CodeInsightColors;
import com.intellij.openapi.editor.colors.TextAttributesKey;
import com.intellij.openapi.editor.markup.TextAttributes;
import com.intellij.openapi.fileChooser.FileChooser;
import com.intellij.openapi.fileChooser.FileChooserDescriptor;
@@ -80,20 +81,19 @@ public abstract class InspectionToolsConfigurable extends BaseConfigurable
implements ErrorsConfigurable, SearchableConfigurable, Configurable.NoScroll {
public static final String ID = "Errors";
public static final String DISPLAY_NAME = "Inspections";
private static final String HEADER_TITLE = "Profile:";
private static final Logger LOG = Logger.getInstance("#" + InspectionToolsConfigurable.class.getName());
protected final InspectionProfileManager myProfileManager;
protected final InspectionProjectProfileManager myProjectProfileManager;
private final CardLayout myLayout = new CardLayout();
private final AuxiliaryRightPanel myAuxiliaryRightPanel;
private final JPanel myProfilesHolder;
private final Map<Profile, SingleInspectionProfilePanel> myPanels =
new HashMap<Profile, SingleInspectionProfilePanel>();
private final List<String> myDeletedProfiles = new ArrayList<String>();
private final String myHeaderTitle = "Profile:";
protected ProfilesConfigurableComboBox myProfiles;
private JPanel myPanel;
private JPanel myWholePanel;
private JComponent myManageButton;
private Alarm mySelectionAlarm;
public InspectionToolsConfigurable(@NotNull final InspectionProjectProfileManager projectProfileManager,
@@ -115,7 +115,7 @@ public abstract class InspectionToolsConfigurable extends BaseConfigurable
public void customize(final JList list, final Profile value, final int index, final boolean selected, final boolean hasFocus) {
final String profileName = value.getName();
final SingleInspectionProfilePanel singleInspectionProfilePanel = myPanels.get(value);
final boolean isShared = singleInspectionProfilePanel != null ? singleInspectionProfilePanel.isProfileShared() : false;
final boolean isShared = singleInspectionProfilePanel != null && singleInspectionProfilePanel.isProfileShared();
setIcon(isShared ? AllIcons.General.ProjectSettings : AllIcons.General.Settings);
setText(profileName);
}
@@ -126,11 +126,11 @@ public abstract class InspectionToolsConfigurable extends BaseConfigurable
myAuxiliaryRightPanel.showDescription(inspectionProfile.getDescription());
}
};
myProfilesHolder = new JPanel();
myProfilesHolder.setLayout(new CardLayout());
JPanel profilesHolder = new JPanel();
profilesHolder.setLayout(new CardLayout());
myManageButton = new ManageButton(new ManageButtonBuilder() {
JComponent manageButton = new ManageButton(new ManageButtonBuilder() {
@Override
public boolean isSharedToTeamMembers() {
SingleInspectionProfilePanel panel = getSelectedPanel();
@@ -138,16 +138,29 @@ public abstract class InspectionToolsConfigurable extends BaseConfigurable
}
@Override
public void setShareToTeamMembers(boolean share) {
public void setShareToTeamMembers(boolean shared) {
final InspectionProfileImpl inspectionProfile = getSelectedObject();
final String name = inspectionProfile.getName();
for (Map.Entry<Profile, SingleInspectionProfilePanel> e : myPanels.entrySet()) {
final InspectionProfileImpl currentProfile = (InspectionProfileImpl)e.getKey();
if (currentProfile.getName().equals(name) && !currentProfile.equals(inspectionProfile)) {
final boolean curShared = e.getValue().isProfileShared();
if (curShared == shared) {
Messages.showErrorDialog((shared ? "Shared" : "Application level") + " profile with same name exists.", "Inspections Settings");
return;
}
}
}
final SingleInspectionProfilePanel panel = getSelectedPanel();
LOG.assertTrue(panel != null, "No settings panel for: " + getSelectedObject());
panel.setProfileShared(share);
panel.setProfileShared(shared);
myProfiles.repaint();
}
@Override
public void copy() {
final InspectionProfileImpl newProfile = copyToNewProfile(0, getSelectedObject(), getProject());
final InspectionProfileImpl newProfile = copyToNewProfile(getSelectedObject(), getProject());
if (newProfile != null) {
final InspectionProfileImpl modifiableModel = (InspectionProfileImpl)newProfile.getModifiableModel();
modifiableModel.setModified(true);
@@ -186,10 +199,11 @@ public abstract class InspectionToolsConfigurable extends BaseConfigurable
@Override
public boolean checkValid(@NotNull String text) {
final boolean isValid = text.equals(initialName) || !hasName(text);
final boolean isValid = text.equals(initialName) || !hasName(text, myPanels.get(inspectionProfile).isProfileShared());
if (isValid) {
myAuxiliaryRightPanel.showDescription(getSelectedObject().getDescription());
} else {
}
else {
myAuxiliaryRightPanel.showError("Name is already in use. Please change name to unique.");
}
return isValid;
@@ -219,6 +233,11 @@ public abstract class InspectionToolsConfigurable extends BaseConfigurable
myAuxiliaryRightPanel.editDescription(getSelectedObject().getDescription());
}
@Override
public boolean hasDescription() {
return !StringUtil.isEmpty(getSelectedObject().getDescription());
}
@Override
public void export() {
final FileChooserDescriptor descriptor = FileChooserDescriptorFactory.createSingleFolderDescriptor();
@@ -297,7 +316,7 @@ public abstract class InspectionToolsConfigurable extends BaseConfigurable
final TextAttributes textAttributes = CodeInsightColors.WARNINGS_ATTRIBUTES.getDefaultAttributes();
HighlightInfoType.HighlightInfoTypeImpl info =
new HighlightInfoType.HighlightInfoTypeImpl(new HighlightSeverity(level, 50),
com.intellij.openapi.editor.colors.TextAttributesKey
TextAttributesKey
.createTextAttributesKey(level));
myProfileManager.getOwnSeverityRegistrar()
.registerSeverity(new SeverityRegistrar.SeverityBasedTextAttributes(textAttributes.clone(), info),
@@ -346,13 +365,13 @@ public abstract class InspectionToolsConfigurable extends BaseConfigurable
});
toolbar.setLayout(new GridBagLayout());
toolbar.add(new JLabel(myHeaderTitle),
toolbar.add(new JLabel(HEADER_TITLE),
new GridBagConstraints(0, 0, 1, 1, 0, 0, GridBagConstraints.WEST, GridBagConstraints.VERTICAL, new Insets(10, 5, 0, 0), 0,
0));
toolbar.add(myProfiles,
new GridBagConstraints(1, 0, 1, 1, 0, 0, GridBagConstraints.WEST, GridBagConstraints.VERTICAL, new Insets(10, 5, 0, 0), 0,
0));
toolbar.add(myManageButton,
toolbar.add(manageButton,
new GridBagConstraints(2, 0, 1, 1, 0, 0, GridBagConstraints.WEST, GridBagConstraints.VERTICAL, new Insets(10, 5, 0, 0), 0,
0));
toolbar.add(myAuxiliaryRightPanel,
@@ -369,12 +388,12 @@ public abstract class InspectionToolsConfigurable extends BaseConfigurable
}
@Nullable
private InspectionProfileImpl copyToNewProfile(final int initValue, ModifiableModel selectedProfile, @NotNull Project project) {
private InspectionProfileImpl copyToNewProfile(ModifiableModel selectedProfile, @NotNull Project project) {
String profileDefaultName = selectedProfile.getName();
do {
profileDefaultName += " (copy)";
}
while (hasName(profileDefaultName));
while (hasName(profileDefaultName, myPanels.get(selectedProfile).isProfileShared()));
final ProfileManager profileManager = selectedProfile.getProfileManager();
InspectionProfileImpl inspectionProfile =
@@ -606,9 +625,9 @@ public abstract class InspectionToolsConfigurable extends BaseConfigurable
});
}
private boolean hasName(final @NotNull String name) {
for (Profile profile : myPanels.keySet()) {
if (name.equals(profile.getName())) {
private boolean hasName(final @NotNull String name, boolean shared) {
for (Map.Entry<Profile, SingleInspectionProfilePanel> e : myPanels.entrySet()) {
if (name.equals(e.getKey().getName()) && shared == e.getValue().isProfileShared()) {
return true;
}
}
@@ -54,7 +54,7 @@ public class ManageButton extends ComboBoxAction implements DumbAware {
group.add(new CopyAction());
group.add(new RenameAction());
group.add(new DeleteAction());
group.add(new EditDescriptionAction());
group.add(new EditDescriptionAction(myBuilder.hasDescription()));
group.add(new ExportAction());
group.addSeparator();
@@ -123,8 +123,8 @@ public class ManageButton extends ComboBoxAction implements DumbAware {
}
private class EditDescriptionAction extends AnAction implements DumbAware {
public EditDescriptionAction() {
super("Edit description");
public EditDescriptionAction(boolean hasDescription) {
super(hasDescription ? "Edit description" : "Add description");
}
@Override
@@ -38,6 +38,8 @@ public interface ManageButtonBuilder {
void editDescription();
boolean hasDescription();
void export();
void doImport();
@@ -37,7 +37,7 @@ import java.awt.event.MouseEvent;
* @author Vladimir Kondratyev
*/
public class ThreeComponentsSplitter extends JPanel implements Disposable {
public static final int MIN_SIZE = 48;
public static final int MIN_SIZE = 0;
private int myDividerWidth;
/**
@@ -63,8 +63,8 @@ public class ThreeComponentsSplitter extends JPanel implements Disposable {
@Nullable private JComponent myInnerComponent;
@Nullable private JComponent myLastComponent;
private int myFirstSize = 10;
private int myLastSize = 10;
private int myFirstSize = 0;
private int myLastSize = 0;
private boolean myShowDividerControls;
private int myDividerZone;
@@ -48,7 +48,6 @@ public interface EditorEx extends Editor {
@NonNls String PROP_COLUMN_MODE = "columnMode";
@NonNls String PROP_FONT_SIZE = "fontSize";
Key<TextRange> LAST_PASTED_REGION = Key.create("LAST_PASTED_REGION");
Key<Boolean> SHOW_PLACEHOLDER_WHEN_FOCUSED = Key.create("SHOW_PLACEHOLDER_WHEN_FOCUSED");
@NotNull
@Override
@@ -199,10 +198,8 @@ public interface EditorEx extends Editor {
/**
* Allows to define <code>'placeholder text'</code> for the current editor, i.e. virtual text that will be represented until
* any user data is entered and current editor is not focused.
* <p/>
* If {@link EditorEx#SHOW_PLACEHOLDER_WHEN_FOCUSED} is set to <code>'true'</code>, the placeholder is shown in focused editor as well.
* <p/>
* any user data is entered.
*
* Feel free to see the detailed feature
* definition <a href="http://dev.w3.org/html5/spec/Overview.html#the-placeholder-attribute">here</a>.
*
@@ -210,6 +207,15 @@ public interface EditorEx extends Editor {
*/
void setPlaceholder(@Nullable CharSequence text);
/**
* Controls whether <code>'placeholder text'</code> is visible when editor is focused.
*
* @param show flag indicating whether placeholder is visible when editor is focused.
*
* @see EditorEx#setPlaceholder(CharSequence)
*/
void setShowPlaceholderWhenFocused(boolean show);
/**
* Allows to answer if 'sticky selection' is active for the current editor.
* <p/>
@@ -276,6 +276,7 @@ public final class EditorImpl extends UserDataHolderBase implements EditorEx, Hi
@Nullable
private CharSequence myPlaceholderText;
private int myLastPaintedPlaceholderWidth;
private boolean myShowPlaceholderWhenFocused;
private boolean myStickySelection;
private int myStickySelectionStart;
@@ -2113,6 +2114,11 @@ public final class EditorImpl extends UserDataHolderBase implements EditorEx, Hi
myPlaceholderText = text;
}
@Override
public void setShowPlaceholderWhenFocused(boolean show) {
myShowPlaceholderWhenFocused = show;
}
Color getBackgroundColor(@NotNull final TextAttributes attributes) {
final Color attrColor = attributes.getBackgroundColor();
return Comparing.equal(attrColor, myScheme.getDefaultBackground()) ? getBackgroundColor() : attrColor;
@@ -2930,8 +2936,7 @@ public final class EditorImpl extends UserDataHolderBase implements EditorEx, Hi
return false;
}
if (KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner() == myEditorComponent &&
!Boolean.TRUE.equals(SHOW_PLACEHOLDER_WHEN_FOCUSED.get(this))) {
if (KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner() == myEditorComponent && !myShowPlaceholderWhenFocused) {
// There is a possible case that placeholder text was painted and the editor gets focus now. We want to over-paint previously
// used placeholder text then.
myLastBackgroundColor = getBackgroundColor();
@@ -22,6 +22,8 @@
*/
package com.intellij.openapi.keymap.impl.ui;
import com.intellij.openapi.util.registry.Registry;
import javax.swing.*;
import java.awt.event.KeyEvent;
@@ -62,4 +64,9 @@ public class ShortcutTextField extends JTextField {
public KeyStroke getKeyStroke() {
return myKeyStroke;
}
@Override
public void enableInputMethods(boolean enable) {
super.enableInputMethods(enable && Registry.is("ide.settings.keymap.input.method.enabled"));
}
}
@@ -113,6 +113,7 @@ public class PluginDownloader {
}
catch (IOException ex) {
myFile = null;
LOG.warn(ex);
errorMessage = ex.getMessage();
}
if (myFile == null) {
@@ -157,9 +157,9 @@ public final class UpdateChecker {
settings.setKnownChannelIds(result.getAllChannelsIds());
}
else if (result.getState() == UpdateStrategy.State.CONNECTION_ERROR) {
//noinspection ThrowableResultOfMethodCallIgnored
showErrorMessage(manualCheck,
result.getError() instanceof InterruptedIOException ? IdeBundle.message("updates.timeout.error") : IdeBundle.message("updates.error.connection.failed"));
Exception e = result.getError();
if (e != null) LOG.warn(e);
showErrorMessage(manualCheck, IdeBundle.message(e instanceof InterruptedIOException ? "updates.timeout.error" : "updates.error.connection.failed"));
return;
}
@@ -250,6 +250,7 @@ public final class UpdateChecker {
return null;
}
catch (Exception e) {
LOG.warn(e);
showErrorMessage(manualCheck, e.getMessage());
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2009 JetBrains s.r.o.
* Copyright 2000-2014 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.
@@ -68,7 +68,7 @@ public abstract class ChooseFileEncodingAction extends ComboBoxAction {
}
@Override
public void update(AnActionEvent e) {
public void update(@NotNull AnActionEvent e) {
}
@Override
@@ -89,7 +89,7 @@ public abstract class ChooseFileEncodingAction extends ComboBoxAction {
}
@Override
public void actionPerformed(final AnActionEvent e) {
public void actionPerformed(@NotNull final AnActionEvent e) {
chosen(myFile, NO_ENCODING);
}
}
@@ -99,7 +99,7 @@ public final class InternalDecorator extends JPanel implements Queryable, DataPr
myHeader = new ToolWindowHeader(toolWindow, info, new Producer<ActionGroup>() {
@Override
public ActionGroup produce() {
return createGearPopupGroup();
return /*createGearPopupGroup()*/createPopupGroup(true);
}
}) {
@Override
@@ -370,6 +370,10 @@ public final class InternalDecorator extends JPanel implements Queryable, DataPr
public final ActionGroup createPopupGroup() {
return createPopupGroup(false);
}
public final ActionGroup createPopupGroup(boolean skipHideAction) {
final DefaultActionGroup group = createGearPopupGroup();
if (!ToolWindowId.PREVIEW.equals(myInfo.getId())) {
group.add(myToggleContentUiTypeAction);
@@ -405,9 +409,10 @@ public final class InternalDecorator extends JPanel implements Queryable, DataPr
resize.add(ActionManager.getInstance().getAction("MaximizeToolWindow"));
group.add(resize);
group.addSeparator();
group.add(new HideAction());
if (!skipHideAction) {
group.addSeparator();
group.add(new HideAction());
}
return group;
}
@@ -25,13 +25,12 @@ import com.intellij.openapi.actionSystem.ex.ActionManagerEx;
import com.intellij.openapi.actionSystem.impl.*;
import com.intellij.openapi.keymap.KeymapUtil;
import com.intellij.openapi.project.DumbAware;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.SystemInfo;
import com.intellij.openapi.wm.ToolWindow;
import com.intellij.openapi.wm.ToolWindowAnchor;
import com.intellij.openapi.wm.ToolWindowManager;
import com.intellij.openapi.wm.ToolWindowType;
import com.intellij.openapi.wm.impl.content.ToolWindowContentUi;
import com.intellij.ui.DoubleClickListener;
import com.intellij.ui.InplaceButton;
import com.intellij.ui.PopupHandler;
import com.intellij.ui.UIBundle;
@@ -91,7 +90,7 @@ public abstract class ToolWindowHeader extends JPanel implements Disposable, UIS
Component c = getComponent(0);
Dimension size = c.getPreferredSize();
if (size.width < (r.width - insets.left - insets.right)) {
c.setBounds(insets.left, insets.top, r.width, r.height - insets.top - insets.bottom);
c.setBounds(insets.left, insets.top, size.width, r.height - insets.top - insets.bottom);
} else {
c.setBounds(insets.left, insets.top, r.width - insets.left - insets.right, r.height - insets.top - insets.bottom);
}
@@ -169,7 +168,7 @@ public abstract class ToolWindowHeader extends JPanel implements Disposable, UIS
addDefaultActions(eastPanel);
myButtonPanel = eastPanel;
addMouseListener(new PopupHandler() {
westPanel.addMouseListener(new PopupHandler() {
public void invokePopup(final Component comp, final int x, final int y) {
toolWindow.getContentUI().showContextMenu(comp, x, y, toolWindow.getPopupGroup(), toolWindow.getContentManager().getSelectedContent());
}
@@ -210,12 +209,14 @@ public abstract class ToolWindowHeader extends JPanel implements Disposable, UIS
}
}
};
}
void switchMaximizedState(Project project) {
if (project == null || project.isDisposed()) return;
ToolWindowManager mgr = ToolWindowManager.getInstance(project);
mgr.setMaximized(myToolWindow, !mgr.isMaximized(myToolWindow));
new DoubleClickListener(){
@Override
protected boolean onDoubleClick(MouseEvent event) {
ToolWindowManagerImpl mgr = toolWindow.getToolWindowManager();
mgr.setMaximized(myToolWindow, !mgr.isMaximized(myToolWindow));
return true;
}
}.installOn(westPanel);
}
@Override
@@ -22,28 +22,25 @@ import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.Splitter;
import com.intellij.openapi.ui.ThreeComponentsSplitter;
import com.intellij.openapi.util.Condition;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.SystemInfo;
import com.intellij.openapi.util.registry.Registry;
import com.intellij.openapi.wm.IdeGlassPaneUtil;
import com.intellij.openapi.wm.ToolWindow;
import com.intellij.openapi.wm.ToolWindowAnchor;
import com.intellij.openapi.wm.ToolWindowType;
import com.intellij.openapi.wm.impl.commands.FinalizableCommand;
import com.intellij.reference.SoftReference;
import com.intellij.ui.ScreenUtil;
import com.intellij.ui.components.JBLayeredPane;
import com.intellij.util.containers.HashMap;
import com.intellij.util.ui.FadeInFadeOut;
import com.intellij.util.ui.UIUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.ArrayList;
@@ -201,24 +198,6 @@ public final class ToolWindowsPane extends JBLayeredPane implements Disposable {
super.addNotify();
if (ScreenUtil.isStandardAddRemoveNotify(this)) {
UISettings.getInstance().addUISettingsListener(myUISettingsListener, myDisposable);
IdeGlassPaneUtil.find(this).addMousePreprocessor(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
if (SwingUtilities.isLeftMouseButton(e) && e.getClickCount() == 2 && e.getModifiersEx() == 0) {
e = SwingUtilities.convertMouseEvent(e.getComponent(), e, ToolWindowsPane.this);
Component component = SwingUtilities.getDeepestComponentAt(ToolWindowsPane.this, e.getX(), e.getY());
Component header = component == null ? null : UIUtil.findParentByCondition((JComponent)component, new Condition<Component>() {
@Override
public boolean value(Component component) {
return component instanceof ToolWindowHeader || component instanceof ActionListener;
}
});
if (header instanceof ToolWindowHeader) {
((ToolWindowHeader)header).switchMaximizedState(myFrame.getProject());
}
}
}
}, this);
}
}
@@ -891,36 +870,60 @@ public final class ToolWindowsPane extends JBLayeredPane implements Disposable {
myInfo = info;
myDirtyMode = dirtyMode;
}
public final void run() {
// Show component.
final UISettings uiSettings = UISettings.getInstance();
if (!myDirtyMode && uiSettings.ANIMATE_WINDOWS && !UISettings.isRemoteDesktopConnected()) {
myLayeredPane.add(myComponent, JLayeredPane.PALETTE_LAYER);
myLayeredPane.moveToFront(myComponent);
myLayeredPane.setBoundsInPaletteLayer(myComponent, myInfo.getAnchor(), myInfo.getWeight());
final FadeInFadeOut fadeIn = new FadeInFadeOut(myComponent, 250, true, myId2Button.get(myInfo.getId()));
add(fadeIn, FadeInFadeOut.LAYER);
fadeIn.setBounds(0, 0, getWidth(), getHeight());
myLayeredPane.remove(myComponent);
fadeIn.doAnimation(new Runnable() {
@Override
public void run() {
remove(fadeIn);
try {
// Show component.
final UISettings uiSettings = UISettings.getInstance();
if (!myDirtyMode && uiSettings.ANIMATE_WINDOWS && !UISettings.isRemoteDesktopConnected()) {
// Prepare top image. This image is scrolling over bottom image.
final Image topImage = myLayeredPane.getTopImage();
final Graphics topGraphics = topImage.getGraphics();
Rectangle bounds;
try {
myLayeredPane.add(myComponent, JLayeredPane.PALETTE_LAYER);
//myComponent.requestFocus();
repaint();
finish();
myLayeredPane.moveToFront(myComponent);
myLayeredPane.setBoundsInPaletteLayer(myComponent, myInfo.getAnchor(), myInfo.getWeight());
bounds = myComponent.getBounds();
myComponent.paint(topGraphics);
myLayeredPane.remove(myComponent);
}
});
}
else { // not animated
myLayeredPane.add(myComponent, JLayeredPane.PALETTE_LAYER);
myLayeredPane.setBoundsInPaletteLayer(myComponent, myInfo.getAnchor(), myInfo.getWeight());
finally {
topGraphics.dispose();
}
// Prepare bottom image.
final Image bottomImage = myLayeredPane.getBottomImage();
final Graphics bottomGraphics = bottomImage.getGraphics();
try {
bottomGraphics.setClip(0, 0, bounds.width, bounds.height);
bottomGraphics.translate(-bounds.x, -bounds.y);
myLayeredPane.paint(bottomGraphics);
}
finally {
bottomGraphics.dispose();
}
// Start animation.
final Surface surface = new Surface(topImage, bottomImage, 1, myInfo.getAnchor(), uiSettings.ANIMATION_SPEED);
myLayeredPane.add(surface, JLayeredPane.PALETTE_LAYER);
surface.setBounds(bounds);
myLayeredPane.validate();
myLayeredPane.repaint();
surface.runMovement();
myLayeredPane.remove(surface);
myLayeredPane.add(myComponent, JLayeredPane.PALETTE_LAYER);
}
else { // not animated
myLayeredPane.add(myComponent, JLayeredPane.PALETTE_LAYER);
myLayeredPane.setBoundsInPaletteLayer(myComponent, myInfo.getAnchor(), myInfo.getWeight());
}
if (!myDirtyMode) {
myLayeredPane.revalidate();
myLayeredPane.validate();
myLayeredPane.repaint();
}
}
finally {
finish();
}
}
@@ -1076,30 +1079,53 @@ public final class ToolWindowsPane extends JBLayeredPane implements Disposable {
myInfo = info;
myDirtyMode = dirtyMode;
}
public final void run() {
final UISettings uiSettings = UISettings.getInstance();
if (!myDirtyMode && uiSettings.ANIMATE_WINDOWS && !UISettings.isRemoteDesktopConnected()) {
// Remove component from the layered pane and start animation.
final FadeInFadeOut fadeOut = new FadeInFadeOut(myComponent, 450, false, getButtonById(myInfo.getId()));
add(fadeOut, FadeInFadeOut.LAYER);
fadeOut.setBounds(0, 0, getWidth(), getHeight());
myLayeredPane.remove(myComponent);
fadeOut.doAnimation(new Runnable() {
@Override
public void run() {
remove(fadeOut);
repaint();
finish();
try {
final UISettings uiSettings = UISettings.getInstance();
if (!myDirtyMode && uiSettings.ANIMATE_WINDOWS && !UISettings.isRemoteDesktopConnected()) {
final Rectangle bounds = myComponent.getBounds();
// Prepare top image. This image is scrolling over bottom image. It contains
// picture of component is being removed.
final Image topImage = myLayeredPane.getTopImage();
final Graphics topGraphics = topImage.getGraphics();
try {
myComponent.paint(topGraphics);
}
});
}
else { // not animated
myLayeredPane.remove(myComponent);
finally {
topGraphics.dispose();
}
// Prepare bottom image. This image contains picture of component that is located
// under the component to is being removed.
final Image bottomImage = myLayeredPane.getBottomImage();
final Graphics bottomGraphics = bottomImage.getGraphics();
try {
myLayeredPane.remove(myComponent);
bottomGraphics.clipRect(0, 0, bounds.width, bounds.height);
bottomGraphics.translate(-bounds.x, -bounds.y);
myLayeredPane.paint(bottomGraphics);
}
finally {
bottomGraphics.dispose();
}
// Remove component from the layered pane and start animation.
final Surface surface = new Surface(topImage, bottomImage, -1, myInfo.getAnchor(), uiSettings.ANIMATION_SPEED * 2);
myLayeredPane.add(surface, JLayeredPane.PALETTE_LAYER);
surface.setBounds(bounds);
myLayeredPane.validate();
myLayeredPane.repaint();
surface.runMovement();
myLayeredPane.remove(surface);
}
else { // not animated
myLayeredPane.remove(myComponent);
}
if (!myDirtyMode) {
myLayeredPane.revalidate();
myLayeredPane.validate();
myLayeredPane.repaint();
}
}
finally {
finish();
}
}
@@ -1166,18 +1192,58 @@ public final class ToolWindowsPane extends JBLayeredPane implements Disposable {
updateLayout();
}
}
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.
*/
private SoftReference<BufferedImage> myBottomImageRef;
private SoftReference<BufferedImage> myTopImageRef;
public MyLayeredPane(final JComponent splitter) {
myBottomImageRef = new SoftReference<BufferedImage>(null);
myTopImageRef = new SoftReference<BufferedImage>(null);
setOpaque(false);
add(splitter, JLayeredPane.DEFAULT_LAYER);
}
public final Image getBottomImage() {
Pair<BufferedImage, SoftReference<BufferedImage>> result = getImage(myBottomImageRef);
myBottomImageRef = result.second;
return result.first;
}
public final Image getTopImage() {
Pair<BufferedImage, SoftReference<BufferedImage>> result = getImage(myTopImageRef);
myTopImageRef = result.second;
return result.first;
}
private Pair<BufferedImage, SoftReference<BufferedImage>> getImage(SoftReference<BufferedImage> imageRef) {
LOG.assertTrue(UISettings.getInstance().ANIMATE_WINDOWS);
BufferedImage image = imageRef.get();
if (
image == null ||
image.getWidth(null) < getWidth() || image.getHeight(null) < getHeight()
) {
final int width = Math.max(Math.max(1, getWidth()), myFrame.getWidth());
final int height = Math.max(Math.max(1, getHeight()), myFrame.getHeight());
if (SystemInfo.isWindows) {
image = myFrame.getGraphicsConfiguration().createCompatibleImage(width, height);
}
else {
// Under Linux we have found that images created by createCompatibleImage(),
// createVolatileImage(), etc extremely slow for rendering. TrueColor buffered image
// is MUCH faster.
// On Mac we create a retina-compatible image
image = UIUtil.createImage(width, height, BufferedImage.TYPE_INT_RGB);
}
imageRef = new SoftReference<BufferedImage>(image);
}
return Pair.create(image, imageRef);
}
/**
* When component size becomes larger then bottom and top images should be enlarged.
*/
@@ -478,6 +478,7 @@ public class ToolWindowContentUi extends JPanel implements ContentUI, PropertyCh
tabActions[j] = new DumbAwareAction(tabs.get(index).first) {
@Override
public void actionPerformed(@NotNull AnActionEvent e) {
myManager.setSelectedContent(content);
((TabbedContent)content).selectContent(index);
}
};
@@ -88,7 +88,7 @@ public class SliderSelectorAction extends DumbAwareAction {
});
}
final JBPopup popup = JBPopupFactory.getInstance().createComponentPopupBuilder(result, slider).createPopup();
final JBPopup popup = JBPopupFactory.getInstance().createComponentPopupBuilder(result, slider).setMovable(true).createPopup();
final Runnable finalRunnable = new Runnable() {
@Override
public void run() {
@@ -105,6 +105,10 @@ public class SliderSelectorAction extends DumbAwareAction {
};
popup.setFinalRunnable(finalRunnable);
InputEvent inputEvent = e.getInputEvent();
show(e, result, popup, inputEvent);
}
protected void show(AnActionEvent e, JPanel result, JBPopup popup, InputEvent inputEvent) {
if (inputEvent instanceof MouseEvent) {
int width = result.getPreferredSize().width;
MouseEvent inputEvent1 = (MouseEvent)inputEvent;
@@ -190,6 +190,6 @@ public final class HttpRequests {
return connection;
}
throw new IOException("Too many redirects");
throw new IOException(IdeBundle.message("error.connection.failed.redirects"));
}
}
@@ -534,6 +534,7 @@ progress.waiting.for.reply.from.plugin.manager=Waiting for reply from {0}
progress.downloading.plugin=Downloading plugin ''{0}''
error.cannot.create.temp.dir=Unable to create temp directory ''{0}''
error.connection.failed.with.http.code.N=Connection failed with HTTP code {0}
error.connection.failed.redirects=Connection failed: too many redirects
progress.connecting.to.plugin.manager=Connecting to {0}
label.plugin.vendor.email=E-mail:
label.plugin.vendor.name=Name:
@@ -24,9 +24,9 @@
<option name="SELECTED_TEARLINE_COLOR" value="9C9C9C"/>
<option name="READONLY_FRAGMENT_BACKGROUND" value="cfe7ff"/>
<option name="ADDED_LINES_COLOR" value="CBE3CA"/>
<option name="MODIFIED_LINES_COLOR" value="C7D5E2"/>
<option name="DELETED_LINES_COLOR" value="9F9F9F"/>
<option name="ADDED_LINES_COLOR" value="c3d6e8"/>
<option name="MODIFIED_LINES_COLOR" value="c9dec1"/>
<option name="DELETED_LINES_COLOR" value="9f9f9f"/>
<option name="WHITESPACES_MODIFIED_LINES_COLOR" value="ffffff"/>
<option name="CONSOLE_BACKGROUND_KEY" value="ffffff" />
</colors>
@@ -599,7 +599,7 @@
<value>
<option name="FOREGROUND"/>
<option name="BACKGROUND" value="e4e4ff"/>
<option name="ERROR_STRIPE_COLOR" value="b8b8e5"/>
<option name="ERROR_STRIPE_COLOR" value="baa8ff"/>
<option name="EFFECT_COLOR"/>
</value>
</option>
@@ -608,7 +608,7 @@
<value>
<option name="FOREGROUND"/>
<option name="BACKGROUND" value="ffe4ff"/>
<option name="ERROR_STRIPE_COLOR" value="e0b4e0"/>
<option name="ERROR_STRIPE_COLOR" value="f0adf0"/>
<option name="EFFECT_COLOR"/>
</value>
</option>
@@ -654,7 +654,7 @@
<option name="NOT_TOP_FRAME_ATTRIBUTES">
<value>
<option name="BACKGROUND" value="e1ebf7"/>
<option name="BACKGROUND" value="c0d0f0"/>
</value>
</option>
@@ -810,7 +810,7 @@
<option name="TODO_ATTRIBUTES">
<value>
<option name="FOREGROUND" value="ff"/>
<option name="FOREGROUND" value="3a53cf"/>
<option name="BACKGROUND"/>
<option name="EFFECT_COLOR"/>
<option name="FONT_TYPE" value="3"/>
@@ -880,12 +880,28 @@
</option>
<option name="TODO_DEFAULT_ATTRIBUTES">
<value>
<option name="FOREGROUND" value="ff" />
<option name="FOREGROUND" value="347fcf" />
<option name="BACKGROUND" />
<option name="FONT_TYPE" value="3" />
<option name="EFFECT_COLOR" />
<option name="EFFECT_TYPE" value="0" />
<option name="ERROR_STRIPE_COLOR" value="295CFF" />
<option name="ERROR_STRIPE_COLOR" value="4c97ff" />
</value>
</option>
<option name="TYPO">
<value>
<option name="EFFECT_COLOR" value="B0D1AB" />
<option name="EFFECT_TYPE" value="2" />
</value>
</option>
<option name="NO_ANALYSIS">
<value>
<option name="ERROR_STRIPE_COLOR" value="d3d3d3" />
</value>
</option>
<option name="DO_NOT_SHOW">
<value>
<option name="ERROR_STRIPE_COLOR" value="71B262" />
</value>
</option>
<option name="BOOKMARKS_ATTRIBUTES">
@@ -15,6 +15,7 @@
*/
package com.intellij.util.io;
import com.intellij.ide.IdeBundle;
import org.jetbrains.annotations.NotNull;
import org.junit.Test;
@@ -41,31 +42,19 @@ public class HttpRequestsTest {
fail();
}
catch (IOException e) {
assertEquals("Too many redirects", e.getMessage());
assertEquals(IdeBundle.message("error.connection.failed.redirects"), e.getMessage());
}
}
@Test
public void testConnectTimeout() {
try {
HttpRequests.request("http://openjdk.java.net").connectTimeout(1).connect(myProcessor);
fail();
}
catch (SocketTimeoutException ignore) { }
catch (IOException e) {
fail(e.getMessage());
}
@Test(timeout = 5000, expected = SocketTimeoutException.class)
public void testConnectTimeout() throws IOException {
HttpRequests.request("http://openjdk.java.net").connectTimeout(1).connect(myProcessor);
fail();
}
@Test
public void testReadTimeout() {
try {
HttpRequests.request("http://openjdk.java.net").readTimeout(1).connect(myProcessor);
fail();
}
catch (SocketTimeoutException ignore) { }
catch (IOException e) {
fail(e.getMessage());
}
@Test(timeout = 5000, expected = SocketTimeoutException.class)
public void testReadTimeout() throws IOException {
HttpRequests.request("http://openjdk.java.net").readTimeout(1).connect(myProcessor);
fail();
}
}
@@ -262,6 +262,12 @@ public class PsiTestUtil {
Assert.assertEquals(reparsedTree, originalTree);
}
public static void addLibrary(final Module module, final String libPath) {
File file = new File(libPath);
String libName = file.getName();
addLibrary(module, libName, file.getParent(), libName);
}
public static void addLibrary(final Module module, final String libName, final String libPath, final String... jarArr) {
ModuleRootModificationUtil.updateModel(module, new Consumer<ModifiableRootModel>() {
@Override
@@ -242,12 +242,12 @@ public class UsageInfo2UsageAdapter implements UsageInModule,
return canNavigate();
}
@Nullable
private OpenFileDescriptor getDescriptor() {
VirtualFile file = getFile();
if(file == null) return null;
Segment range = getNavigationRange();
if (range != null && file instanceof VirtualFileWindow) {
if (range != null && file instanceof VirtualFileWindow && range.getStartOffset() >= 0) {
// have to use injectedToHost(TextRange) to calculate right offset in case of multiple shreds
range = ((VirtualFileWindow)file).getDocumentWindow().injectedToHost(TextRange.create(range));
file = ((VirtualFileWindow)file).getDelegate();
}
@@ -272,7 +272,7 @@ public class UsageInfo2UsageAdapter implements UsageInModule,
Segment range = getUsageInfo().getNavigationRange();
if (range == null) {
ProperTextRange rangeInElement = getUsageInfo().getRangeInElement();
range = rangeInElement == null ? TextRange.from(myOffset,1) : rangeInElement.shiftRight(myOffset);
range = myOffset < 0 ? new UnfairTextRange(-1,-1) : rangeInElement == null ? TextRange.from(myOffset,1) : rangeInElement.shiftRight(myOffset);
}
if (range.getEndOffset() >= document.getTextLength()) {
int line = Math.max(0, Math.min(myLineNumber, document.getLineCount() - 1));
@@ -450,6 +450,7 @@ console.too.much.text.buffer.ratio.description=Used for disabling of console pro
The ratio is used against the console cycle buffer size (idea.cycle.buffer.size/theRatio=maxTextLength).
ide.settings.appearance.font.family.only=true
ide.settings.keymap.input.method.enabled=false
ide.settings.old.style=true
ide.new.settings.view=true
ide.new.settings.view.description=New view for the Settings dialog
@@ -494,4 +495,7 @@ editor.xcode.like.scrollbar=false
editor.xcode.like.scrollbar.description=Enables auto-hideable Xcode-like editor stripes
editor.config.stop.at.project.root=true
editor.config.stop.at.project.root.description=Stops searching for .editorconfig at project root (requires project reopening)
editor.config.stop.at.project.root.description=Stops searching for .editorconfig at project root (requires project reopening)
JDK8042508.bug.fixed=false
JDK8042508.bug.fixed.description=Disable check for type variable until javac bug is fixed
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2009 JetBrains s.r.o.
* Copyright 2000-2014 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.
@@ -58,12 +58,14 @@ public class TextRange implements Segment, Serializable {
return myEndOffset - myStartOffset;
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof TextRange)) return false;
TextRange range = (TextRange)obj;
return myStartOffset == range.myStartOffset && myEndOffset == range.myEndOffset;
}
@Override
public int hashCode() {
return myStartOffset + myEndOffset;
}
@@ -80,6 +82,7 @@ public class TextRange implements Segment, Serializable {
return myStartOffset <= offset && offset <= myEndOffset;
}
@Override
public String toString() {
return "(" + myStartOffset + "," + myEndOffset + ")";
}
@@ -181,7 +181,8 @@ public final class ObjectTree<T> {
}
@TestOnly
void assertNoReferenceKeptInTree(@NotNull T disposable) {
// public for Upsource
public void assertNoReferenceKeptInTree(@NotNull T disposable) {
synchronized (treeLock) {
Collection<ObjectNode<T>> nodes = myObject2NodeMap.values();
for (ObjectNode<T> node : nodes) {
@@ -1426,8 +1426,8 @@ public class ContainerUtil extends ContainerUtilRt {
}
@Contract(pure=true)
public static <T> T getFirstItem(@Nullable final Collection<T> items, @Nullable final T def) {
return items == null || items.isEmpty() ? def : items.iterator().next();
public static <T> T getFirstItem(@Nullable final Collection<T> items, @Nullable final T defaultResult) {
return items == null || items.isEmpty() ? defaultResult : items.iterator().next();
}
/**
@@ -2890,13 +2890,29 @@ public class UIUtil {
}
}
/**
* Adds an empty border with the specified insets to the specified component.
* If the component already has a border it will be preserved.
*
* @param component the component to which border added
* @param top the inset from the top
* @param left the inset from the left
* @param bottom the inset from the bottom
* @param right the inset from the right
*/
public static void addInsets(@NotNull JComponent component, int top, int left, int bottom, int right) {
addBorder(component, BorderFactory.createEmptyBorder(top, left, bottom, right));
}
/**
* Adds an empty border with the specified insets to the specified component.
* If the component already has a border it will be preserved.
*
* @param component the component to which border added
* @param insets the top, left, bottom, and right insets
*/
public static void addInsets(@NotNull JComponent component, @NotNull Insets insets) {
if (component.getBorder() != null) {
component.setBorder(new CompoundBorder(new EmptyBorder(insets), component.getBorder()));
}
else {
component.setBorder(new EmptyBorder(insets));
}
addInsets(component, insets.top, insets.left, insets.bottom, insets.right);
}
public static Dimension addInsets(@NotNull Dimension dimension, @NotNull Insets insets) {
@@ -2947,13 +2963,20 @@ public class UIUtil {
return null;
}
/**
* Adds the specified border to the specified component.
* If the component already has a border it will be preserved.
* If component or border is not specified nothing happens.
*
* @param component the component to which border added
* @param border the border to add to the component
*/
public static void addBorder(JComponent component, Border border) {
if (component == null) return;
if (component.getBorder() != null) {
component.setBorder(new CompoundBorder(border, component.getBorder()));
}
else {
if (component != null && border != null) {
Border old = component.getBorder();
if (old != null) {
border = BorderFactory.createCompoundBorder(border, old);
}
component.setBorder(border);
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2009 JetBrains s.r.o.
* Copyright 2000-2014 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.
@@ -22,15 +22,16 @@
*/
package com.intellij.openapi.vcs.changes.committed;
import com.intellij.openapi.application.ModalityState;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.openapi.vcs.VcsBundle;
import com.intellij.openapi.vcs.versionBrowser.ChangeBrowserSettings;
import com.intellij.openapi.vcs.versionBrowser.ChangesBrowserSettingsEditor;
import com.intellij.openapi.application.ModalityState;
import com.intellij.ui.JBColor;
import com.intellij.util.Alarm;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.awt.*;
@@ -54,7 +55,7 @@ public class CommittedChangesFilterDialog extends DialogWrapper {
myPanel.setSettings(settings);
setTitle(VcsBundle.message("browse.changes.filter.title"));
init();
myErrorLabel.setForeground(Color.red);
myErrorLabel.setForeground(JBColor.RED);
validateInput();
myValidateAlarm.addRequest(myValidateRunnable, 500, ModalityState.stateForComponent(myPanel.getComponent()));
}
@@ -75,7 +75,7 @@ public class XDebuggerEditorLinePainter extends EditorLinePainter {
}
Set<XValueNodeImpl> values = map.get(Pair.create(file, lineNumber));
if (values != null && !values.isEmpty()) {
final int bpLine = getCurrentBreakPointLine(values);
final int bpLine = getCurrentBreakPointLineInFile(values, file);
ArrayList<VariableText> result = new ArrayList<VariableText>();
for (XValueNodeImpl value : values) {
SimpleColoredText text = new SimpleColoredText();
@@ -147,13 +147,13 @@ public class XDebuggerEditorLinePainter extends EditorLinePainter {
return null;
}
private static int getCurrentBreakPointLine(Set<XValueNodeImpl> values) {
private static int getCurrentBreakPointLineInFile(Set<XValueNodeImpl> values, VirtualFile file) {
try {
final XValueNodeImpl node = values.iterator().next();
final XDebugSession session = XDebugView.getSession(node.getTree());
if (session != null) {
final XSourcePosition position = session.getCurrentPosition();
if (position != null) {
if (position != null && position.getFile().equals(file)) {
return position.getLine();
}
}
@@ -0,0 +1,17 @@
package icons;
import com.intellij.openapi.util.IconLoader;
import javax.swing.*;
/**
* NOTE THIS FILE IS AUTO-GENERATED
* DO NOT EDIT IT BY HAND, run build/scripts/icons.gant instead
*/
public class EditorconfigIcons {
private static Icon load(String path) {
return IconLoader.getIcon(path, EditorconfigIcons.class);
}
public static final Icon Editorconfig = load("/org/editorconfig/icons/editorconfig.png"); // 16x16
}
@@ -27,10 +27,6 @@ public class Utils {
EditorConfigNotifier.getInstance().error(project, configValue, "\"" + configValue + "\" is not a valid value" + (!configKey.isEmpty() ? " for " + configKey : "") + " for file " + filePath);
}
public static void appliedConfigMessage(Project project, String configValue, String configKey, String filePath) {
EditorConfigNotifier.getInstance().info(project, "Applied .editorconfig settings");
}
public static String getFilePath(Project project, VirtualFile file) {
if (!file.isInLocalFileSystem()) {
return project.getBasePath() + "/" + file.getNameWithoutExtension() + "." + file.getFileType().getDefaultExtension();
@@ -0,0 +1,126 @@
package org.editorconfig.annotations;
import com.intellij.codeInsight.daemon.DaemonCodeAnalyzer;
import com.intellij.codeInsight.intention.IntentionAction;
import com.intellij.ide.util.PropertiesComponent;
import com.intellij.lang.annotation.Annotation;
import com.intellij.lang.annotation.AnnotationHolder;
import com.intellij.lang.annotation.Annotator;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.markup.GutterIconRenderer;
import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.codeStyle.CodeStyleSettings;
import com.intellij.psi.codeStyle.CodeStyleSettingsManager;
import com.intellij.util.IncorrectOperationException;
import com.intellij.util.ObjectUtils;
import icons.EditorconfigIcons;
import org.editorconfig.Utils;
import org.editorconfig.core.EditorConfig;
import org.editorconfig.plugincomponents.SettingsProviderComponent;
import org.editorconfig.settings.EditorConfigSettings;
import org.jetbrains.annotations.NotNull;
import javax.swing.*;
import java.util.List;
/**
* @author Dennis.Ushakov
*/
public class EditorConfigAnnotator implements Annotator {
private static final String EDITOR_CONFIG_ACCEPTED = "editor.config.accepted";
@Override
public void annotate(@NotNull PsiElement element, @NotNull AnnotationHolder holder) {
PsiFile file = ObjectUtils.tryCast(element, PsiFile.class);
if (file == null) {
return;
}
final Project project = file.getProject();
final CodeStyleSettings settings = CodeStyleSettingsManager.getInstance(project).getCurrentSettings();
if (!Utils.isEnabled(settings) || PropertiesComponent.getInstance(project).getBoolean(EDITOR_CONFIG_ACCEPTED, false)) return;
final List<EditorConfig.OutPair> pairs = SettingsProviderComponent.getInstance().getOutPairs(project, Utils.getFilePath(project, file.getVirtualFile()));
if (!pairs.isEmpty()) {
final Annotation annotation = holder.createInfoAnnotation(file, "EditorConfig is overriding Code Style settings for this file");
annotation.setFileLevelAnnotation(true);
annotation.setGutterIconRenderer(new MyGutterIconRenderer());
annotation.registerFix(new IntentionAction() {
@NotNull
@Override
public String getText() {
return "Disable EditorConfig support";
}
@NotNull
@Override
public String getFamilyName() {
return "EditorConfig";
}
@Override
public boolean isAvailable(@NotNull Project project, Editor editor, PsiFile file) {
return true;
}
@Override
public void invoke(@NotNull Project project, Editor editor, PsiFile file) throws IncorrectOperationException {
settings.getCustomSettings(EditorConfigSettings.class).ENABLED = false;
DaemonCodeAnalyzer.getInstance(project).restart();
}
@Override
public boolean startInWriteAction() {
return false;
}
});
annotation.registerFix(new IntentionAction() {
@NotNull
@Override
public String getText() {
return "Dismiss";
}
@NotNull
@Override
public String getFamilyName() {
return "EditorConfig";
}
@Override
public boolean isAvailable(@NotNull Project project, Editor editor, PsiFile file) {
return true;
}
@Override
public void invoke(@NotNull Project project, Editor editor, PsiFile file) throws IncorrectOperationException {
PropertiesComponent.getInstance(project).setValue(EDITOR_CONFIG_ACCEPTED, "true");
DaemonCodeAnalyzer.getInstance(project).restart();
}
@Override
public boolean startInWriteAction() {
return false;
}
});
}
}
private static class MyGutterIconRenderer extends GutterIconRenderer {
@NotNull
@Override
public Icon getIcon() {
return EditorconfigIcons.Editorconfig;
}
@Override
public boolean equals(Object obj) {
return obj instanceof MyGutterIconRenderer;
}
@Override
public int hashCode() {
return EditorconfigIcons.Editorconfig.hashCode();
}
}
}
@@ -66,7 +66,6 @@ public class EditorConfigIndentOptionsProvider extends FileIndentOptionsProvider
final String calculatedTabWidth = calculateTabWidth(tabWidth, indentSize);
if (!calculatedIndentSize.isEmpty()) {
if (applyIndentSize(indentOptions, calculatedIndentSize)) {
Utils.appliedConfigMessage(project, calculatedIndentSize, indentSizeKey, filePath);
changed = true;
} else {
Utils.invalidConfigMessage(project, calculatedIndentSize, indentSizeKey, filePath);
@@ -74,7 +73,6 @@ public class EditorConfigIndentOptionsProvider extends FileIndentOptionsProvider
}
if (!calculatedContinuationSize.isEmpty()) {
if (applyContinuationIndentSize(indentOptions, calculatedContinuationSize)) {
Utils.appliedConfigMessage(project, calculatedContinuationSize, continuationSizeKey, filePath);
changed = true;
}
else {
@@ -83,7 +81,6 @@ public class EditorConfigIndentOptionsProvider extends FileIndentOptionsProvider
}
if (!calculatedTabWidth.isEmpty()) {
if (applyTabWidth(indentOptions, calculatedTabWidth)) {
Utils.appliedConfigMessage(project, calculatedTabWidth, tabWidthKey, filePath);
changed = true;
}
else {
@@ -92,7 +89,6 @@ public class EditorConfigIndentOptionsProvider extends FileIndentOptionsProvider
}
if (!indentStyle.isEmpty()) {
if (applyIndentStyle(indentOptions, indentStyle)) {
Utils.appliedConfigMessage(project, indentStyle, indentStyleKey, filePath);
changed = true;
}
else {
@@ -84,7 +84,6 @@ public class EditorSettingsManager extends FileDocumentManagerAdapter {
}
else {
file.putUserData(userDataKey, data);
Utils.appliedConfigMessage(myProject, configValue, editorConfigKey, file.getCanonicalPath());
}
}
}
@@ -67,7 +67,6 @@ public class EncodingManager extends FileDocumentManagerAdapter {
if (newCharset != null) {
if (Comparing.equal(newCharset, file.getCharset())) return;
encodingProjectManager.setEncoding(file, newCharset);
Utils.appliedConfigMessage(myProject, charset, charsetKey, filePath);
} else {
Utils.invalidConfigMessage(myProject, charset, charsetKey, filePath);
}
@@ -84,7 +84,6 @@ public class LineEndingsManager extends FileDocumentManagerAdapter {
statusBarUpdated = true;
updateStatusBar();
}
Utils.appliedConfigMessage(myProject, lineEndings, lineEndingsKey, filePath);
}
}
catch (IllegalArgumentException e) {
Binary file not shown.

After

Width:  |  Height:  |  Size: 584 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 KiB

@@ -1,7 +1,11 @@
package org.editorconfig.plugincomponents;
import com.intellij.lang.LanguageAnnotators;
import com.intellij.openapi.components.ApplicationComponent;
import com.intellij.openapi.components.ServiceManager;
import com.intellij.openapi.fileTypes.FileType;
import com.intellij.openapi.fileTypes.FileTypeManager;
import com.intellij.openapi.fileTypes.LanguageFileType;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.module.ModuleManager;
import com.intellij.openapi.project.Project;
@@ -13,6 +17,7 @@ import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.util.CachedValueProvider;
import com.intellij.psi.util.CachedValuesManager;
import org.editorconfig.Utils;
import org.editorconfig.annotations.EditorConfigAnnotator;
import org.editorconfig.core.EditorConfig;
import org.editorconfig.core.EditorConfig.OutPair;
import org.editorconfig.core.EditorConfigException;
@@ -24,8 +29,18 @@ import java.util.*;
public class SettingsProviderComponent implements ApplicationComponent {
private EditorConfig editorConfig;
public SettingsProviderComponent() {
public SettingsProviderComponent(FileTypeManager manager) {
editorConfig = new EditorConfig();
registerAnnotator(manager);
}
public void registerAnnotator(FileTypeManager manager) {
final EditorConfigAnnotator annotator = new EditorConfigAnnotator();
for (FileType type : manager.getRegisteredFileTypes()) {
if (type instanceof LanguageFileType) {
LanguageAnnotators.INSTANCE.addExplicitExtension(((LanguageFileType)type).getLanguage(), annotator);
}
}
}
public static SettingsProviderComponent getInstance() {
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2009 JetBrains s.r.o.
* Copyright 2000-2014 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.
@@ -20,15 +20,16 @@ import com.intellij.openapi.ui.FixedSizeButton;
import com.intellij.openapi.ui.TextFieldWithBrowseButton;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.ui.JBColor;
import com.intellij.util.NullableFunction;
import com.intellij.util.ui.UIUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.idea.svn.branchConfig.SvnBranchMapperManager;
import org.jetbrains.idea.svn.SvnBundle;
import org.jetbrains.idea.svn.SvnUtil;
import org.jetbrains.idea.svn.branchConfig.SelectBranchPopup;
import org.jetbrains.idea.svn.branchConfig.SvnBranchConfigurationNew;
import org.jetbrains.idea.svn.branchConfig.SvnBranchMapperManager;
import org.jetbrains.idea.svn.dialogs.WCInfoWithBranches;
import org.jetbrains.idea.svn.integrate.IntegratedSelectedOptionsDialog;
import org.jetbrains.idea.svn.integrate.WorkingCopyInfo;
@@ -196,7 +197,7 @@ public class SvnMergeInfoRootPanelManual {
gb.gridx = 0;
gb.gridwidth = 2;
myMixedRevisions = new JTextArea("Mixed Revision Working Copy");
myMixedRevisions.setForeground(Color.red);
myMixedRevisions.setForeground(JBColor.RED);
myMixedRevisions.setBackground(myContentPanel.getBackground());
myContentPanel.add(myMixedRevisions, gb);
@@ -231,7 +232,7 @@ public class SvnMergeInfoRootPanelManual {
private void calculateBranchPathByBranch(final String url, final String localPath) {
final String local = url == null ? null : getLocal(url, localPath == null ? myBranchToLocal.get(url) : localPath);
if (local == null) {
myLocalArea.setForeground(Color.red);
myLocalArea.setForeground(JBColor.RED);
myLocalArea.setText(SvnBundle.message("tab.repository.merge.panel.root.panel.select.local"));
} else {
myLocalArea.setForeground(UIUtil.getInactiveTextColor());
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2012 JetBrains s.r.o.
* Copyright 2000-2014 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.
@@ -35,6 +35,7 @@ import com.intellij.openapi.vcs.changes.Change;
import com.intellij.openapi.vcs.changes.ChangesUtil;
import com.intellij.openapi.vcs.history.*;
import com.intellij.openapi.vcs.ui.VcsBalloonProblemNotifier;
import com.intellij.ui.JBColor;
import com.intellij.util.BeforeAfter;
import com.intellij.util.containers.Convertor;
import com.intellij.util.ui.UIUtil;
@@ -230,7 +231,7 @@ public class TreeConflictRefreshablePanel extends AbstractRefreshablePanel {
BeforeAfter<ConflictSidePresentation> ba, boolean directory) {
if (description == null) return;
JLabel descriptionLbl = new JLabel(description.toPresentableString());
descriptionLbl.setForeground(Color.red);
descriptionLbl.setForeground(JBColor.RED);
main.add(descriptionLbl, gb);
++ gb.gridy;
//buttons
@@ -20,12 +20,10 @@
*/
package com.intellij.spellchecker;
import com.intellij.codeHighlighting.HighlightDisplayLevel;
import com.intellij.codeInsight.daemon.impl.HighlightInfoType;
import com.intellij.codeInsight.daemon.impl.SeveritiesProvider;
import com.intellij.lang.annotation.HighlightSeverity;
import com.intellij.openapi.editor.colors.TextAttributesKey;
import com.intellij.openapi.editor.markup.EffectType;
import com.intellij.openapi.editor.markup.TextAttributes;
import org.jetbrains.annotations.NotNull;
@@ -34,23 +32,19 @@ import java.util.Collections;
import java.util.List;
public class SpellCheckerSeveritiesProvider extends SeveritiesProvider {
private static final TextAttributesKey TYPO_KEY = TextAttributesKey.createTextAttributesKey("TYPO");
public static final HighlightSeverity TYPO = new HighlightSeverity("TYPO", HighlightSeverity.INFORMATION.myVal + 5);
@Override
@NotNull
public List<HighlightInfoType> getSeveritiesHighlightInfoTypes() {
final TextAttributes attributes = new TextAttributes();
attributes.setEffectType(EffectType.WAVE_UNDERSCORE);
attributes.setEffectColor(HighlightDisplayLevel.TYPO);
HighlightInfoType typo = new HighlightInfoType.HighlightInfoTypeImpl(TYPO, TextAttributesKey.createTextAttributesKey("TYPO", attributes));
HighlightInfoType typo = new HighlightInfoType.HighlightInfoTypeImpl(TYPO, TYPO_KEY);
return Collections.singletonList(typo);
}
@Override
public Color getTrafficRendererColor(@NotNull TextAttributes textAttributes) {
return HighlightDisplayLevel.TYPO;
return textAttributes.getErrorStripeColor();
}
@Override
@@ -151,6 +151,7 @@ filesystem
filesystems
finalizer
finalizers
findbugs
firefox
fixme
foreach
@@ -47,7 +47,9 @@ public class NamespaceFilter implements ElementFilter {
if (psiFile instanceof XmlFile) {
// We use file references for as dtd namespace
// But we should also check PUBLIC ID for namespace
final XmlProlog prolog = ((XmlFile)psiFile).getDocument().getProlog();
XmlDocument document = ((XmlFile)psiFile).getDocument();
if (document == null) return false;
final XmlProlog prolog = document.getProlog();
if (prolog != null) {
final XmlDoctype doctype = prolog.getDoctype();
@@ -148,11 +148,10 @@ public abstract class XmlElementImpl extends CompositePsiElement implements XmlE
if (super.isEquivalentTo(another)) return true;
PsiElement element1 = this;
PsiElement element2 = another;
// TODO: seem to be only necessary for tag dirs equivalens checking.
if (element1 instanceof XmlTag && element2 instanceof XmlTag) {
if (!element1.isPhysical() && !element2.isPhysical()) return element1.getText().equals(element2.getText());
// TODO: seem to be only necessary for tag dirs equivalents checking.
if (element1 instanceof XmlTag && another instanceof XmlTag) {
if (!element1.isPhysical() && !another.isPhysical()) return element1.getText().equals(another.getText());
}
return false;