Merge branch 'master' into upsource-master

This commit is contained in:
Dmitry Lomov
2012-05-14 11:38:01 +02:00
492 changed files with 38232 additions and 1650 deletions
+1
View File
@@ -91,6 +91,7 @@
<module fileurl="file://$PROJECT_DIR$/platform/platform-resources-en/platform-resources-en.iml" filepath="$PROJECT_DIR$/platform/platform-resources-en/platform-resources-en.iml" group="platform" />
<module fileurl="file://$PROJECT_DIR$/platform/platform-tests/platform-tests.iml" filepath="$PROJECT_DIR$/platform/platform-tests/platform-tests.iml" group="platform" />
<module fileurl="file://$PROJECT_DIR$/plugins/properties/properties.iml" filepath="$PROJECT_DIR$/plugins/properties/properties.iml" group="plugins" />
<module fileurl="file://$PROJECT_DIR$/plugins/rearranger/rearranger.iml" filepath="$PROJECT_DIR$/plugins/rearranger/rearranger.iml" />
<module fileurl="file://$PROJECT_DIR$/xml/relaxng/relaxng.iml" filepath="$PROJECT_DIR$/xml/relaxng/relaxng.iml" group="plugins" />
<module fileurl="file://$PROJECT_DIR$/resources/resources.iml" filepath="$PROJECT_DIR$/resources/resources.iml" />
<module fileurl="file://$PROJECT_DIR$/resources-en/resources-en.iml" filepath="$PROJECT_DIR$/resources-en/resources-en.iml" />
+1
View File
@@ -10602,6 +10602,7 @@ gutter/overridingMethod.png:/lib/icons.jar
gutter/implementingMethod.png:/lib/icons.jar
gutter/overridenMethod.png:/lib/icons.jar
gutter/implementedMethod.png:/lib/icons.jar
gutter/recursiveMethod.png:/lib/icons.jar
com/intellij/codeInsight/daemon/impl/analysis/HighlightVisitorImpl$1.class:/lib/idea.jar
com/intellij/codeInsight/daemon/impl/IconLineMarkerProvider.class:/lib/idea.jar
com/intellij/codeInsight/daemon/impl/IconLineMarkerProvider$1.class:/lib/idea.jar
+6
View File
@@ -226,6 +226,12 @@ public def layoutCommunityPlugins(String home) {
module("gradle")
}
}
layoutPlugin("rearranger") {
jar("rearranger.jar") {
module("rearranger")
}
}
layoutPlugin("git4idea") {
jar("git4idea-rt.jar") {
+1
View File
@@ -89,6 +89,7 @@
<orderEntry type="module" module-name="android" />
<orderEntry type="module" module-name="relaxng" />
<orderEntry type="module" module-name="gradle" />
<orderEntry type="module" module-name="rearranger" />
</component>
</module>
@@ -643,7 +643,8 @@ public class CompileServerManager implements ApplicationComponent{
cmdLine.addParameter("-classpath");
final List<File> cp = ClasspathBootstrap.getCompileServerApplicationClasspath();
final List<File> cp = ClasspathBootstrap.getBuildProcessApplicationClasspath();
cp.add(ClasspathBootstrap.getResourcePath(systemCompiler.getClass())); // tools.jar
cp.addAll(myClasspathManager.getCompileServerPluginsClasspath());
cmdLine.addParameter(classpathToString(cp));
@@ -565,14 +565,10 @@ public class BuildManager implements ApplicationComponent{
}
private Process launchBuildProcess(Project project, final int port, final UUID sessionId) throws ExecutionException {
// validate tools.jar presence
final JavaCompiler systemCompiler = ToolProvider.getSystemJavaCompiler();
if (systemCompiler == null) {
throw new ExecutionException("No system java compiler is provided by the JRE. Make sure tools.jar is present in IntelliJ IDEA classpath.");
}
// choosing sdk with which the build process should be run
Sdk projectJdk = JavaAwareProjectJdkTableImpl.getInstanceEx().getInternalJdk();
final Sdk internalJdk = JavaAwareProjectJdkTableImpl.getInstanceEx().getInternalJdk();
Sdk projectJdk = internalJdk;
final String versionString = projectJdk.getVersionString();
if (versionString != null) {
JavaSdkVersion sdkVersion = ((JavaSdk)projectJdk.getSdkType()).getVersion(versionString);
@@ -600,6 +596,23 @@ public class BuildManager implements ApplicationComponent{
}
}
// validate tools.jar presence
final File compilerPath;
if (projectJdk.equals(internalJdk)) {
final JavaCompiler systemCompiler = ToolProvider.getSystemJavaCompiler();
if (systemCompiler == null) {
throw new ExecutionException("No system java compiler is provided by the JRE. Make sure tools.jar is present in IntelliJ IDEA classpath.");
}
compilerPath = ClasspathBootstrap.getResourcePath(systemCompiler.getClass());
}
else {
final String path = ((JavaSdk)projectJdk.getSdkType()).getToolsPath(projectJdk);
if (path == null) {
throw new ExecutionException("Cannot determine path to 'tools.jar' library for " + projectJdk.getName() + " (" + projectJdk.getHomePath() + ")");
}
compilerPath = new File(path);
}
final GeneralCommandLine cmdLine = new GeneralCommandLine();
final String vmExecutablePath = ((JavaSdkType)projectJdk.getSdkType()).getVMExecutablePath(projectJdk);
cmdLine.setExePath(vmExecutablePath);
@@ -667,7 +680,8 @@ public class BuildManager implements ApplicationComponent{
cmdLine.addParameter("-classpath");
final List<File> cp = ClasspathBootstrap.getCompileServerApplicationClasspath();
final List<File> cp = ClasspathBootstrap.getBuildProcessApplicationClasspath();
cp.add(compilerPath);
cp.addAll(myClasspathManager.getCompileServerPluginsClasspath());
cmdLine.addParameter(classpathToString(cp));
@@ -820,13 +834,17 @@ public class BuildManager implements ApplicationComponent{
}
public void addChanged(Collection<String> paths) {
myDeleted.removeAll(paths);
myChanged.addAll(paths);
if (!myNeedRescan) {
myDeleted.removeAll(paths);
myChanged.addAll(paths);
}
}
public void addDeleted(Collection<String> paths) {
myChanged.removeAll(paths);
myDeleted.addAll(paths);
if (!myNeedRescan) {
myChanged.removeAll(paths);
myDeleted.addAll(paths);
}
}
public CmdlineRemoteProto.Message.ControllerMessage.FSEvent createNextEvent() {
@@ -32,6 +32,7 @@ import com.intellij.openapi.project.DumbService;
import com.intellij.openapi.project.IndexNotReadyException;
import com.intellij.openapi.util.IconLoader;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.*;
import com.intellij.psi.search.searches.AllOverridingMethodsSearch;
import com.intellij.psi.search.searches.ClassInheritorsSearch;
@@ -60,6 +61,8 @@ public class JavaLineMarkerProvider implements LineMarkerProvider, DumbAware {
private static final Icon IMPLEMENTED_INTERFACE_MARKER_RENDERER = IMPLEMENTED_METHOD_MARKER_RENDERER;
private static final Icon SUBCLASSED_CLASS_MARKER_RENDERER = OVERRIDEN_METHOD_MARKER_RENDERER;
private static final Icon RECURSIVE_METHOD_ICON = IconLoader.getIcon("/gutter/recursiveMethod.png");
protected final DaemonCodeAnalyzerSettings myDaemonSettings;
protected final EditorColorsManager myColorsManager;
@@ -164,6 +167,11 @@ public class JavaLineMarkerProvider implements LineMarkerProvider, DumbAware {
}
else if (element instanceof PsiClass && !(element instanceof PsiTypeParameter)) {
collectInheritingClasses((PsiClass)element, result);
} else if(element instanceof PsiMethodCallExpression){
final PsiMethodCallExpression methodCall = (PsiMethodCallExpression)element;
if (isRecursiveMethodCall(methodCall)){
result.add(new RecursiveMethodCallMarkerInfo(methodCall));
}
}
}
if (!methods.isEmpty()) {
@@ -171,6 +179,14 @@ public class JavaLineMarkerProvider implements LineMarkerProvider, DumbAware {
}
}
private static boolean isRecursiveMethodCall(@NotNull PsiMethodCallExpression methodCall){
PsiMethod referencedMethod = methodCall.resolveMethod();
TextRange rmRange = referencedMethod == null ? null : referencedMethod.getTextRange();
int mcOffset = methodCall.getTextRange().getStartOffset();
return rmRange != null && rmRange.contains(mcOffset);
}
private static void collectInheritingClasses(PsiClass aClass, Collection<LineMarkerInfo> result) {
if (aClass.hasModifierProperty(PsiModifier.FINAL)) {
return;
@@ -276,4 +292,36 @@ public class JavaLineMarkerProvider implements LineMarkerProvider, DumbAware {
};
}
}
private static class RecursiveMethodCallMarkerInfo extends MergeableLineMarkerInfo<PsiMethodCallExpression> {
private RecursiveMethodCallMarkerInfo(@NotNull PsiMethodCallExpression methodCall) {
super(methodCall,
methodCall.getTextRange(),
RECURSIVE_METHOD_ICON,
Pass.UPDATE_OVERRIDEN_MARKERS,
FunctionUtil.<PsiMethodCallExpression, String>constant("Recursive call"),
null,
GutterIconRenderer.Alignment.RIGHT
);
}
@Override
public boolean canMergeWith(@NotNull MergeableLineMarkerInfo<?> info) {
if (!(info instanceof RecursiveMethodCallMarkerInfo)) return false;
PsiElement otherElement = info.getElement();
PsiElement myElement = getElement();
return otherElement != null && myElement != null;
}
@Override
public Icon getCommonIcon(@NotNull List<MergeableLineMarkerInfo> infos) {
return myIcon;
}
@Override
public Function<? super PsiElement, String> getCommonTooltip(@NotNull List<MergeableLineMarkerInfo> infos) {
return FunctionUtil.<PsiElement, String>constant("Multiple recursive calls");
}
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2011 JetBrains s.r.o.
* Copyright 2000-2012 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.
@@ -51,7 +51,6 @@ import java.util.*;
*/
public class GenericsHighlightUtil {
private static final Logger LOG = Logger.getInstance("#com.intellij.codeInsight.daemon.impl.analysis.GenericsHighlightUtil");
private static final String GENERICS_ARE_NOT_SUPPORTED = JavaErrorMessages.message("generics.are.not.supported");
private static final QuickFixFactory QUICK_FIX_FACTORY = QuickFixFactory.getInstance();
private GenericsHighlightUtil() {}
@@ -102,6 +101,7 @@ public class GenericsHighlightUtil {
return null;
}
@Nullable
public static HighlightInfo checkParameterizedReferenceTypeArguments(PsiElement resolved,
final PsiJavaCodeReferenceElement referenceElement,
final PsiSubstitutor substitutor) {
@@ -110,17 +110,14 @@ public class GenericsHighlightUtil {
return checkReferenceTypeArgumentList(typeParameterListOwner, referenceElement.getParameterList(), substitutor, true);
}
@Nullable
public static HighlightInfo checkReferenceTypeArgumentList(final PsiTypeParameterListOwner typeParameterListOwner,
final PsiReferenceParameterList referenceParameterList,
final PsiSubstitutor substitutor,
boolean registerIntentions) {
if (referenceParameterList != null && !PsiUtil.isLanguageLevel5OrHigher(referenceParameterList)) {
if (referenceParameterList.getTypeParameterElements().length > 0) {
HighlightInfo info = HighlightInfo.createHighlightInfo(HighlightInfoType.ERROR, referenceParameterList, GENERICS_ARE_NOT_SUPPORTED);
QuickFixAction.registerQuickFixAction(info, new ShowModulePropertiesFix(referenceParameterList));
QuickFixAction.registerQuickFixAction(info, new IncreaseLanguageLevelFix(LanguageLevel.JDK_1_5));
return info;
}
if (referenceParameterList != null) {
HighlightInfo info = HighlightUtil.checkGenericsFeature(referenceParameterList, referenceParameterList.getTypeParameterElements().length);
if (info != null) return info;
}
PsiDiamondType.DiamondInferenceResult inferenceResult = null;
@@ -914,15 +911,13 @@ public class GenericsHighlightUtil {
return valueOfMethod.equals(methodSignature);
}
@Nullable
public static HighlightInfo checkTypeParametersList(PsiTypeParameterList parameterList) {
PsiTypeParameter[] typeParameters = parameterList.getTypeParameters();
if (typeParameters.length == 0) return null;
if (!PsiUtil.isLanguageLevel5OrHigher(parameterList)) {
HighlightInfo info = HighlightInfo.createHighlightInfo(HighlightInfoType.ERROR, parameterList, GENERICS_ARE_NOT_SUPPORTED);
QuickFixAction.registerQuickFixAction(info, new ShowModulePropertiesFix(parameterList));
QuickFixAction.registerQuickFixAction(info, new IncreaseLanguageLevelFix(LanguageLevel.JDK_1_5));
return info;
}
HighlightInfo info = HighlightUtil.checkGenericsFeature(parameterList, typeParameters.length);
if (info != null) return info;
final PsiElement parent = parameterList.getParent();
if (parent instanceof PsiClass && ((PsiClass)parent).isEnum()) {
return HighlightInfo.createHighlightInfo(HighlightInfoType.ERROR,
@@ -1208,21 +1203,18 @@ public class GenericsHighlightUtil {
return null;
}
@Nullable
public static HighlightInfo checkVarArgParameterIsLast(PsiParameter parameter) {
PsiElement declarationScope = parameter.getDeclarationScope();
if (declarationScope instanceof PsiMethod) {
PsiParameter[] params = ((PsiMethod)declarationScope).getParameterList().getParameters();
if (parameter.isVarArgs()) {
if (!PsiUtil.getLanguageLevel(parameter).hasEnumKeywordAndAutoboxing()) {
HighlightInfo info = HighlightInfo.createHighlightInfo(HighlightInfoType.ERROR, parameter, JavaErrorMessages.message("varargs.prior.15"));
QuickFixAction.registerQuickFixAction(info, new IncreaseLanguageLevelFix(LanguageLevel.JDK_1_5));
return info;
}
HighlightInfo info = HighlightUtil.checkVarargFeature(parameter);
if (info != null) return info;
if (params[params.length - 1] != parameter) {
HighlightInfo info = HighlightInfo.createHighlightInfo(HighlightInfoType.ERROR, parameter,
JavaErrorMessages.message("vararg.not.last.parameter"));
QuickFixAction.registerQuickFixAction(info, new MakeVarargParameterLastFix(parameter), null);
info = HighlightInfo.createHighlightInfo(HighlightInfoType.ERROR, parameter, JavaErrorMessages.message("vararg.not.last.parameter"));
QuickFixAction.registerQuickFixAction(info, new MakeVarargParameterLastFix(parameter));
return info;
}
}
@@ -1230,6 +1222,7 @@ public class GenericsHighlightUtil {
return null;
}
@Nullable
public static List<HighlightInfo> checkEnumConstantModifierList(PsiModifierList modifierList) {
List<HighlightInfo> list = null;
PsiElement[] children = modifierList.getChildren();
@@ -58,6 +58,7 @@ import org.intellij.lang.annotations.Language;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.PropertyKey;
import java.util.*;
@@ -593,6 +594,7 @@ public class HighlightUtil {
if (variable instanceof PsiLocalVariable ||
variable instanceof PsiParameter && ((PsiParameter)variable).getDeclarationScope() instanceof PsiCatchSection ||
variable instanceof PsiParameter && ((PsiParameter)variable).getDeclarationScope() instanceof PsiForeachStatement) {
@SuppressWarnings("unchecked")
PsiElement scope = PsiTreeUtil.getParentOfType(variable, PsiFile.class, PsiMethod.class, PsiClassInitializer.class, PsiResourceList.class);
VariablesNotProcessor proc = new VariablesNotProcessor(variable, false) {
@Override
@@ -602,7 +604,9 @@ public class HighlightUtil {
};
PsiScopesUtil.treeWalkUp(proc, identifier, scope);
if (scope instanceof PsiResourceList && proc.size() == 0) {
scope = PsiTreeUtil.getParentOfType(variable, PsiFile.class, PsiMethod.class, PsiClassInitializer.class);
@SuppressWarnings({"unchecked", "UnnecessaryLocalVariable"})
NavigatablePsiElement parent = PsiTreeUtil.getParentOfType(variable, PsiFile.class, PsiMethod.class, PsiClassInitializer.class);
scope = parent;
PsiScopesUtil.treeWalkUp(proc, identifier, scope);
}
if (proc.size() > 0) {
@@ -1403,7 +1407,7 @@ public class HighlightUtil {
}
@Nullable
static HighlightInfo checkValidArrayAccessExpression(PsiExpression arrayExpression, PsiExpression indexExpression, PsiType type) {
static HighlightInfo checkValidArrayAccessExpression(@Nullable PsiExpression arrayExpression, PsiExpression indexExpression, PsiType type) {
PsiType arrayExpressionType = arrayExpression == null ? null : arrayExpression.getType();
if (arrayExpressionType != null && !(arrayExpressionType instanceof PsiArrayType)) {
String description = JavaErrorMessages.message("array.type.expected", formatType(arrayExpressionType));
@@ -1744,9 +1748,11 @@ public class HighlightUtil {
referencedClass = PsiUtil.resolveClassInType(type);
}
else if (qualifier instanceof PsiThisExpression || qualifier == null) {
resolved = PsiTreeUtil.getParentOfType(expression, PsiMethod.class, true, PsiMember.class);
@SuppressWarnings({"unchecked", "UnnecessaryLocalVariable"})
PsiMethod parent = PsiTreeUtil.getParentOfType(expression, PsiMethod.class, true, PsiMember.class);
resolved = parent;
expression = qualifier == null ? expression : qualifier;
if (resolved instanceof PsiMethod) {
if (resolved != null) {
referencedClass = ((PsiMethod)resolved).getContainingClass();
}
}
@@ -2452,7 +2458,7 @@ public class HighlightUtil {
public static void registerChangeVariableTypeFixes(PsiVariable parameter, PsiType itemType, HighlightInfo highlightInfo) {
for (ChangeVariableTypeQuickFixProvider fixProvider : Extensions.getExtensions(ChangeVariableTypeQuickFixProvider.EP_NAME)) {
for (IntentionAction action : fixProvider.getFixes(parameter, itemType)) {
QuickFixAction.registerQuickFixAction(highlightInfo, action, null);
QuickFixAction.registerQuickFixAction(highlightInfo, action);
}
}
ChangeParameterClassFix.registerQuickFixAction(parameter, itemType, highlightInfo);
@@ -2466,4 +2472,76 @@ public class HighlightUtil {
}
return null;
}
private static enum Feature {
GENERICS(LanguageLevel.JDK_1_5, "feature.generics"),
ANNOTATIONS(LanguageLevel.JDK_1_5, "feature.annotations"),
STATIC_IMPORTS(LanguageLevel.JDK_1_5, "feature.static.imports"),
FOR_EACH(LanguageLevel.JDK_1_5, "feature.for.each"),
VARARGS(LanguageLevel.JDK_1_5, "feature.varargs"),
DIAMOND_TYPES(LanguageLevel.JDK_1_7, "feature.diamond.types"),
MULTI_CATCH(LanguageLevel.JDK_1_7, "feature.multi.catch"),
TRY_WITH_RESOURCES(LanguageLevel.JDK_1_7, "feature.try.with.resources");
private final LanguageLevel level;
private final String key;
private Feature(final LanguageLevel level, @PropertyKey(resourceBundle = JavaErrorMessages.BUNDLE) final String key) {
this.level = level;
this.key = key;
}
}
@Nullable
private static HighlightInfo checkFeature(@Nullable final PsiElement element, @NotNull final Feature feature) {
if (element != null && !PsiUtil.getLanguageLevel(element).isAtLeast(feature.level)) {
final String message = JavaErrorMessages.message("insufficient.language.level", JavaErrorMessages.message(feature.key));
final HighlightInfo info = HighlightInfo.createHighlightInfo(HighlightInfoType.ERROR, element, message);
QuickFixAction.registerQuickFixAction(info, new IncreaseLanguageLevelFix(feature.level));
QuickFixAction.registerQuickFixAction(info, new ShowModulePropertiesFix(element));
return info;
}
return null;
}
@Nullable
public static HighlightInfo checkGenericsFeature(final PsiElement parameterList, final int listSize) {
return listSize > 0 ? checkFeature(parameterList, Feature.GENERICS) : null;
}
@Nullable
public static HighlightInfo checkAnnotationFeature(final PsiElement element) {
return checkFeature(element, Feature.ANNOTATIONS);
}
@Nullable
public static HighlightInfo checkForEachFeature(final PsiForeachStatement statement) {
return checkFeature(statement, Feature.FOR_EACH);
}
@Nullable
public static HighlightInfo checkStaticImportFeature(final PsiImportStaticStatement statement) {
return checkFeature(statement, Feature.STATIC_IMPORTS);
}
@Nullable
public static HighlightInfo checkVarargFeature(final PsiParameter parameter) {
return checkFeature(parameter, Feature.VARARGS);
}
@Nullable
public static HighlightInfo checkDiamondFeature(final PsiTypeElement typeElement) {
return typeElement.getType() instanceof PsiDiamondType ? checkFeature(typeElement.getParent(), Feature.DIAMOND_TYPES) : null;
}
@Nullable
public static HighlightInfo checkMultiCatchFeature(final PsiParameter parameter) {
return parameter.getType() instanceof PsiDisjunctionType ? checkFeature(parameter, Feature.MULTI_CATCH) : null;
}
@Nullable
public static HighlightInfo checkTryWithResourcesFeature(final PsiResourceVariable resourceVariable) {
return checkFeature(resourceVariable.getParent(), Feature.TRY_WITH_RESOURCES);
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2011 JetBrains s.r.o.
* Copyright 2000-2012 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.
@@ -30,7 +30,6 @@ import com.intellij.openapi.project.IndexNotReadyException;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.TextRange;
import com.intellij.pom.java.LanguageLevel;
import com.intellij.psi.*;
import com.intellij.psi.controlFlow.ControlFlowUtil;
import com.intellij.psi.impl.source.javadoc.PsiDocMethodOrFieldRef;
@@ -170,16 +169,11 @@ public class HighlightVisitorImpl extends JavaElementVisitor implements Highligh
}
}
@Override public void visitAnnotation(PsiAnnotation annotation) {
@Override
public void visitAnnotation(PsiAnnotation annotation) {
super.visitAnnotation(annotation);
if (!PsiUtil.isLanguageLevel5OrHigher(annotation)) {
HighlightInfo info = HighlightInfo.createHighlightInfo(HighlightInfoType.ERROR, annotation, JavaErrorMessages.message("annotations.prior.15"));
QuickFixAction.registerQuickFixAction(info, new IncreaseLanguageLevelFix(LanguageLevel.JDK_1_5));
myHolder.add(info);
return;
}
myHolder.add(AnnotationsHighlightUtil.checkApplicability(annotation));
if (!myHolder.hasErrorResults()) myHolder.add(HighlightUtil.checkAnnotationFeature(annotation));
if (!myHolder.hasErrorResults()) myHolder.add(AnnotationsHighlightUtil.checkApplicability(annotation));
if (!myHolder.hasErrorResults()) myHolder.add(AnnotationsHighlightUtil.checkAnnotationType(annotation));
if (!myHolder.hasErrorResults()) myHolder.add(AnnotationsHighlightUtil.checkMissingAttributes(annotation));
if (!myHolder.hasErrorResults()) myHolder.add(AnnotationsHighlightUtil.checkTargetAnnotationDuplicates(annotation));
@@ -187,7 +181,8 @@ public class HighlightVisitorImpl extends JavaElementVisitor implements Highligh
if (!myHolder.hasErrorResults()) myHolder.add(AnnotationsHighlightUtil.checkForeignInnerClassesUsed(annotation));
}
@Override public void visitAnnotationArrayInitializer(PsiArrayInitializerMemberValue initializer) {
@Override
public void visitAnnotationArrayInitializer(PsiArrayInitializerMemberValue initializer) {
PsiMethod method = null;
PsiElement parent = initializer.getParent();
if (parent instanceof PsiNameValuePair) {
@@ -364,28 +359,24 @@ public class HighlightVisitorImpl extends JavaElementVisitor implements Highligh
}
}
@Override public void visitField(PsiField field) {
@Override
public void visitField(PsiField field) {
super.visitField(field);
if (!myHolder.hasErrorResults()) myHolder.add(HighlightControlFlowUtil.checkFinalFieldInitialized(field));
}
@Override public void visitForeachStatement(PsiForeachStatement statement) {
if (!PsiUtil.isLanguageLevel5OrHigher(statement)) {
HighlightInfo info = HighlightInfo.createHighlightInfo(HighlightInfoType.ERROR, statement.getFirstChild(), JavaErrorMessages.message("foreach.prior.15"));
QuickFixAction.registerQuickFixAction(info, new IncreaseLanguageLevelFix(LanguageLevel.JDK_1_5));
myHolder.add(info);
}
@Override
public void visitForeachStatement(final PsiForeachStatement statement) {
myHolder.add(HighlightUtil.checkForEachFeature(statement));
}
@Override public void visitImportStaticStatement(PsiImportStaticStatement statement) {
if (!PsiUtil.isLanguageLevel5OrHigher(statement)) {
HighlightInfo info = HighlightInfo.createHighlightInfo(HighlightInfoType.ERROR, statement.getFirstChild(), JavaErrorMessages.message("static.imports.prior.15"));
QuickFixAction.registerQuickFixAction(info, new IncreaseLanguageLevelFix(LanguageLevel.JDK_1_5));
myHolder.add(info);
}
@Override
public void visitImportStaticStatement(final PsiImportStaticStatement statement) {
myHolder.add(HighlightUtil.checkStaticImportFeature(statement));
}
@Override public void visitIdentifier(PsiIdentifier identifier) {
@Override
public void visitIdentifier(final PsiIdentifier identifier) {
PsiElement parent = identifier.getParent();
final EditorColorsScheme colorsScheme = myHolder.getColorsScheme();
if (parent instanceof PsiVariable) {
@@ -411,10 +402,8 @@ public class HighlightVisitorImpl extends JavaElementVisitor implements Highligh
}
else if (parent instanceof PsiClass) {
PsiClass aClass = (PsiClass)parent;
if (aClass.isAnnotationType() && !PsiUtil.isLanguageLevel5OrHigher(aClass)) {
HighlightInfo info = HighlightInfo.createHighlightInfo(HighlightInfoType.ERROR, identifier, JavaErrorMessages.message("annotations.prior.15"));
QuickFixAction.registerQuickFixAction(info, new IncreaseLanguageLevelFix(LanguageLevel.JDK_1_5));
myHolder.add(info);
if (aClass.isAnnotationType()) {
myHolder.add(HighlightUtil.checkAnnotationFeature(identifier));
}
myHolder.add(HighlightClassUtil.checkClassAlreadyImported(aClass, identifier));
@@ -742,6 +731,7 @@ public class HighlightVisitorImpl extends JavaElementVisitor implements Highligh
if (!myHolder.hasErrorResults()) myHolder.add(GenericsHighlightUtil.checkForeachLoopParameterType((PsiForeachStatement)parent));
}
else if (parent instanceof PsiCatchSection) {
if (!myHolder.hasErrorResults()) myHolder.add(HighlightUtil.checkMultiCatchFeature(parameter));
if (!myHolder.hasErrorResults()) myHolder.add(HighlightUtil.checkCatchParameterIsThrowable(parameter));
if (!myHolder.hasErrorResults()) myHolder.addAll(GenericsHighlightUtil.checkCatchParameterIsClass(parameter));
if (!myHolder.hasErrorResults()) myHolder.addAll(HighlightUtil.checkCatchTypeIsDisjoint(parameter));
@@ -987,11 +977,14 @@ public class HighlightVisitorImpl extends JavaElementVisitor implements Highligh
@Override
public void visitResourceVariable(final PsiResourceVariable resourceVariable) {
visitVariable(resourceVariable);
if (!myHolder.hasErrorResults()) myHolder.add(HighlightUtil.checkTryWithResourcesFeature(resourceVariable));
if (!myHolder.hasErrorResults()) myHolder.add(HighlightUtil.checkTryResourceIsAutoCloseable(resourceVariable));
if (!myHolder.hasErrorResults()) myHolder.add(HighlightUtil.checkUnhandledCloserExceptions(resourceVariable));
}
@Override public void visitTypeElement(PsiTypeElement type) {
@Override
public void visitTypeElement(final PsiTypeElement type) {
if (!myHolder.hasErrorResults()) myHolder.add(HighlightUtil.checkDiamondFeature(type));
if (!myHolder.hasErrorResults()) myHolder.add(HighlightUtil.checkIllegalType(type));
if (!myHolder.hasErrorResults()) myHolder.add(GenericsHighlightUtil.checkReferenceTypeUsedAsTypeArgument(type));
if (!myHolder.hasErrorResults()) myHolder.add(GenericsHighlightUtil.checkWildcardUsage(type));
@@ -137,7 +137,7 @@ public class RedundantSuppressInspection extends GlobalInspectionTool{
String idsString = SuppressManager.getInstance().getSuppressedInspectionIdsIn(owner);
if (idsString != null && idsString.length() != 0) {
List<String> ids = StringUtil.split(idsString, ",");
if (IGNORE_ALL && ids.contains(SuppressionUtil.ALL)) return;
if (IGNORE_ALL && (ids.contains(SuppressionUtil.ALL) || ids.contains(SuppressionUtil.ALL.toLowerCase()))) return;
Collection<String> suppressed = suppressedScopes.get(owner);
if (suppressed == null) {
suppressed = ids;
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2011 JetBrains s.r.o.
* Copyright 2000-2012 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.
@@ -39,6 +39,7 @@ import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.project.ProjectManager;
import com.intellij.openapi.util.Pair;
import com.intellij.pom.java.LanguageLevel;
import com.intellij.psi.*;
import com.intellij.psi.util.PsiUtil;
import com.intellij.util.ArrayUtil;
@@ -118,7 +119,7 @@ public class DataFlowInspection extends BaseLocalInspectionTool {
binary.getLOperand().replace(qualifier);
List<LocalQuickFix> fixes = new SmartList<LocalQuickFix>();
if (PsiUtil.getLanguageLevel(qualifier).hasAssertKeyword()) {
if (PsiUtil.getLanguageLevel(qualifier).isAtLeast(LanguageLevel.JDK_1_4)) {
fixes.add(new AddAssertStatementFix(binary));
}
SurroundWithIfFix ifFix = new SurroundWithIfFix(qualifier);
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2009 JetBrains s.r.o.
* Copyright 2000-2012 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.
@@ -34,9 +34,7 @@ public class JavaHighlightingLexer extends LayeredLexer {
registerSelfStoppingLayer(new StringLiteralLexer('\'', JavaTokenType.STRING_LITERAL),
new IElementType[]{JavaTokenType.CHARACTER_LITERAL}, IElementType.EMPTY_ARRAY);
LayeredLexer docLexer = new LayeredLexer(new JavaDocLexer(languageLevel.hasEnumKeywordAndAutoboxing()));
LayeredLexer docLexer = new LayeredLexer(new JavaDocLexer(languageLevel.isAtLeast(LanguageLevel.JDK_1_5)));
HtmlHighlightingLexer lexer = new HtmlHighlightingLexer();
lexer.setHasNoEmbeddments(true);
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2009 JetBrains s.r.o.
* Copyright 2000-2012 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.
@@ -53,7 +53,7 @@ public class ValueDocTagInfo implements JavadocTagInfo {
public String checkTagValue(PsiDocTagValue value) {
boolean hasReference = (value != null && value.getFirstChild() != null);
if (hasReference) {
if (!PsiUtil.getLanguageLevel(value).hasEnumKeywordAndAutoboxing()) {
if (!PsiUtil.isLanguageLevel5OrHigher(value)) {
return JavaErrorMessages.message("javadoc.value.tag.jdk15.required");
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2011 JetBrains s.r.o.
* Copyright 2000-2012 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.
@@ -82,7 +82,7 @@ public class JavaClassReferenceSet {
if (ch == LT || ch == COMMA) {
if (!allowGenericsCalculated) {
allowGenerics = !isStaticImport && PsiUtil.getLanguageLevel(element).hasEnumKeywordAndAutoboxing();
allowGenerics = !isStaticImport && PsiUtil.isLanguageLevel5OrHigher(element);
allowGenericsCalculated = true;
}
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2009 JetBrains s.r.o.
* Copyright 2000-2012 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.
@@ -30,6 +30,7 @@ import com.intellij.openapi.roots.LanguageLevelProjectExtension;
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.util.Comparing;
import com.intellij.pom.java.LanguageLevel;
import com.intellij.psi.*;
import com.intellij.psi.codeStyle.JavaCodeStyleManager;
import com.intellij.psi.codeStyle.SuggestedNameInfo;
@@ -265,7 +266,7 @@ class IntroduceConstantDialog extends DialogWrapper {
final PsiManager psiManager = PsiManager.getInstance(myProject);
if ((myTypeSelectorManager.isSuggestedType("java.lang.String") || (myLocalVariable != null && AnnotationUtil.isAnnotated(myLocalVariable, AnnotationUtil.NON_NLS, false)))&&
LanguageLevelProjectExtension.getInstance(psiManager.getProject()).getLanguageLevel().hasEnumKeywordAndAutoboxing() &&
LanguageLevelProjectExtension.getInstance(psiManager.getProject()).getLanguageLevel().isAtLeast(LanguageLevel.JDK_1_5) &&
JavaPsiFacade.getInstance(psiManager.getProject()).findClass(AnnotationUtil.NON_NLS, myParentClass.getResolveScope()) != null) {
final PropertiesComponent component = PropertiesComponent.getInstance(myProject);
myCbNonNls.setSelected(component.isTrueValue(NONNLS_SELECTED_PROPERTY));
@@ -80,20 +80,10 @@ public class JavaNameSuggestionProvider implements NameSuggestionProvider {
}
}
final String[] strings = info != null ? info.names : ArrayUtil.EMPTY_STRING_ARRAY;
ArrayList<String> list = new ArrayList<String>(Arrays.asList(strings));
final ArrayList<String> list = new ArrayList<String>(Arrays.asList(strings));
final String[] properlyCased = suggestProperlyCasedName(element);
if (!list.contains(initialName)) {
list.add(0, initialName);
}
else {
int i = list.indexOf(initialName);
list.remove(i);
list.add(0, initialName);
}
if (properlyCased != null) {
for (String properlyCasedSuggestion : properlyCased) {
list.add(1, properlyCasedSuggestion);
}
Collections.addAll(list, properlyCased);
}
if (parameterName != null && !list.contains(parameterName)) {
list.add(parameterName);
@@ -101,6 +91,14 @@ public class JavaNameSuggestionProvider implements NameSuggestionProvider {
if (superMethodName != null && !list.contains(superMethodName)) {
list.add(0, superMethodName);
}
if (!list.contains(initialName)) {
list.add(initialName);
}
else {
int i = list.indexOf(initialName);
list.remove(i);
list.add(initialName);
}
ContainerUtil.removeDuplicates(list);
result.addAll(list);
return info;
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2009 JetBrains s.r.o.
* Copyright 2000-2012 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.
@@ -39,14 +39,20 @@ public enum LanguageLevel {
myPresentableText = presentableText;
}
/** @deprecated (to remove in IDEA 13) */
@SuppressWarnings("UnusedDeclaration")
public int getIndex() {
return ordinal() + 3; // solely for backward compatibility
}
/** @deprecated (to remove in IDEA 13) */
@SuppressWarnings("UnusedDeclaration")
public boolean hasAssertKeyword() {
return isAtLeast(JDK_1_4);
}
/** @deprecated use {@linkplain com.intellij.psi.util.PsiUtil#isLanguageLevel5OrHigher(com.intellij.psi.PsiElement)} (to remove in IDEA 13) */
@SuppressWarnings("UnusedDeclaration")
public boolean hasEnumKeywordAndAutoboxing() {
return isAtLeast(JDK_1_5);
}
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2009 JetBrains s.r.o.
* Copyright 2000-2012 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.
@@ -87,6 +87,7 @@ public interface JavaTokenType extends TokenType{
IElementType TRY_KEYWORD = new IKeywordElementType("TRY_KEYWORD");
IElementType VOLATILE_KEYWORD = new IKeywordElementType("VOLATILE_KEYWORD");
IElementType THROWS_KEYWORD = new IKeywordElementType("THROWS_KEYWORD");
IElementType NONE_KEYWORD = new IKeywordElementType("NONE_KEYWORD");
IElementType LPARENTH = new IJavaElementType("LPARENTH");
IElementType RPARENTH = new IJavaElementType("RPARENTH");
@@ -139,6 +140,9 @@ public interface JavaTokenType extends TokenType{
IElementType GTGTEQ = new IJavaElementType("GTGTEQ");
IElementType GTGTGTEQ = new IJavaElementType("GTGTGTEQ");
IElementType DOUBLE_COLON = new IJavaElementType("DOUBLE_COLON");
IElementType ARROW = new IJavaElementType("ARROW");
TokenSet OPERATION_BIT_SET = TokenSet.create(
EQ, GT, LT, EXCL, TILDE, QUEST, COLON, PLUS, MINUS, ASTERISK, DIV, AND, OR, XOR,
PERC, EQEQ, LE, GE, NE, ANDAND, OROR, PLUSPLUS, MINUSMINUS, LTLT, GTGT, GTGTGT,
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2009 JetBrains s.r.o.
* Copyright 2000-2012 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.
@@ -104,7 +104,7 @@ public class PsiPrimitiveType extends PsiType {
@Nullable
public static PsiPrimitiveType getUnboxedType(PsiType type) {
if (!(type instanceof PsiClassType)) return null;
if (!((PsiClassType)type).getLanguageLevel().hasEnumKeywordAndAutoboxing()) return null;
if (!((PsiClassType)type).getLanguageLevel().isAtLeast(LanguageLevel.JDK_1_5)) return null;
final PsiClass psiClass = ((PsiClassType)type).resolve();
if (psiClass == null) return null;
return ourQNameToUnboxed.get(psiClass.getQualifiedName());
@@ -124,7 +124,7 @@ public class PsiPrimitiveType extends PsiType {
@Nullable
public PsiClassType getBoxedType(PsiElement context) {
LanguageLevel languageLevel = PsiUtil.getLanguageLevel(context);
if (!languageLevel.hasEnumKeywordAndAutoboxing()) return null;
if (!languageLevel.isAtLeast(LanguageLevel.JDK_1_5)) return null;
final String boxedQName = getBoxedTypeName();
//[ven]previous call returns null for NULL, VOID
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2011 JetBrains s.r.o.
* Copyright 2000-2012 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.
@@ -780,7 +780,7 @@ public class TypeConversionUtil {
private static final Key<CachedValue<Set<String>>> POSSIBLE_BOXED_HOLDER_TYPES = Key.create("Types that may be possibly assigned from primitive ones");
private static boolean isBoxable(final PsiClassType left, final PsiPrimitiveType right) {
if (!left.getLanguageLevel().hasEnumKeywordAndAutoboxing()) return false;
if (!left.getLanguageLevel().isAtLeast(LanguageLevel.JDK_1_5)) return false;
final PsiClass psiClass = left.resolve();
if (psiClass == null) return false;
@@ -1,9 +1,8 @@
psi.error.attempt.to.edit.class.file=Cannot modify compiled element
#language levels
jdk.1.3.language.level.description=1.3 - Plain old Java
jdk.1.4.language.level.description=1.4 - 'assert' keyword
jdk.1.5.language.level.description=5.0 - 'enum' keyword, autoboxing, etc.
jdk.1.5.language.level.description=5.0 - 'enum' keyword, autoboxing etc.
jdk.1.6.language.level.description=6.0 - @Override in interfaces
jdk.1.7.language.level.description=7.0 - Diamonds, ARM, multi-catch, etc.
jdk.1.8.language.level.description=8.0 - Type annotations
jdk.1.7.language.level.description=7.0 - Diamonds, ARM, multi-catch etc.
jdk.1.8.language.level.description=8.0 - Lambdas, type annotations etc.
@@ -671,15 +671,14 @@ public class ExpressionParser {
final PsiBuilder.Marker newExpr = (start != null ? start.precede() : builder.mark());
builder.advanceLexer();
final boolean parseDiamonds = areDiamondsSupported(builder);
myReferenceParser.parseReferenceParameterList(builder, false, parseDiamonds);
myReferenceParser.parseReferenceParameterList(builder, false, true);
final PsiBuilder.Marker refOrType;
final boolean parseAnnotations = areTypeAnnotationsSupported(builder) && builder.getTokenType() == JavaTokenType.AT;
final IElementType tokenType = builder.getTokenType();
if (tokenType == JavaTokenType.IDENTIFIER || parseAnnotations) {
refOrType = myReferenceParser.parseJavaCodeReference(builder, true, true, parseAnnotations, true, parseDiamonds);
refOrType = myReferenceParser.parseJavaCodeReference(builder, true, true, parseAnnotations, true, true);
if (refOrType == null) {
error(builder, JavaErrorMessages.message("expected.identifier"));
newExpr.done(JavaElementType.NEW_EXPRESSION);
@@ -133,17 +133,6 @@ public class JavaParserUtil {
builder.putUserDataUnprotected(LANG_LEVEL_KEY, level);
}
// todo[r.sh] join all JDK 7 check clauses into single method (IDEA 11)
public static boolean areDiamondsSupported(final PsiBuilder builder) {
return getLanguageLevel(builder).isAtLeast(LanguageLevel.JDK_1_7);
}
public static boolean areMultiCatchSupported(final PsiBuilder builder) {
return getLanguageLevel(builder).isAtLeast(LanguageLevel.JDK_1_7);
}
public static boolean areTryWithResourcesSupported(final PsiBuilder builder) {
return getLanguageLevel(builder).isAtLeast(LanguageLevel.JDK_1_7);
}
public static boolean areTypeAnnotationsSupported(final PsiBuilder builder) {
return getLanguageLevel(builder).isAtLeast(LanguageLevel.JDK_1_8);
}
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2011 JetBrains s.r.o.
* Copyright 2000-2012 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.
@@ -622,9 +622,8 @@ public class StatementParser {
final PsiBuilder.Marker statement = builder.mark();
builder.advanceLexer();
boolean hasResourceList = false;
if (areTryWithResourcesSupported(builder) && builder.getTokenType() == JavaTokenType.LPARENTH) {
hasResourceList = true;
final boolean hasResourceList = builder.getTokenType() == JavaTokenType.LPARENTH;
if (hasResourceList) {
myDeclarationParser.parseResourceList(builder);
}
@@ -667,7 +666,7 @@ public class StatementParser {
return false;
}
final PsiBuilder.Marker param = myDeclarationParser.parseParameter(builder, false, areMultiCatchSupported(builder));
final PsiBuilder.Marker param = myDeclarationParser.parseParameter(builder, false, true);
if (param == null) {
error(builder, JavaErrorMessages.message("expected.parameter"));
}
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2009 JetBrains s.r.o.
* Copyright 2000-2012 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.
@@ -23,50 +23,51 @@ import com.intellij.psi.impl.source.tree.JavaDocElementType;
import com.intellij.psi.tree.IElementType;
import com.intellij.util.text.CharArrayUtil;
import gnu.trove.THashSet;
import org.jetbrains.annotations.NotNull;
import java.io.IOException;
import java.util.Set;
public class JavaLexer extends LexerBase {
private JavaLexer(boolean isAssertKeywordEnabled, boolean isJDK15) {
myTable = getTable(isAssertKeywordEnabled, isJDK15);
myFlexLexer = new _JavaLexer(isAssertKeywordEnabled, isJDK15);
}
private static final HashTable[] TABLES = new HashTable[]{
new HashTable(LanguageLevel.JDK_1_8),
new HashTable(LanguageLevel.JDK_1_5),
new HashTable(LanguageLevel.JDK_1_4),
new HashTable(LanguageLevel.JDK_1_3)
};
public JavaLexer(LanguageLevel level) {
this(level.hasAssertKeyword(), level.hasEnumKeywordAndAutoboxing());
private static HashTable getTable(final LanguageLevel level) {
for (HashTable table : TABLES) {
if (level.isAtLeast(table.myLevel)) {
return table;
}
}
throw new IllegalArgumentException("Unsupported level: " + level);
}
private static HashTable getTable(boolean isAssertKeywordEnabled, boolean isJDK15) {
return isAssertKeywordEnabled
? isJDK15 ? ourTableWithAssertAndJDK15 : ourTableWithAssert
: isJDK15 ? ourTableWithJDK15 : ourTableWithoutAssert;
}
private static HashTable getTable(LanguageLevel level) {
return getTable(level.hasAssertKeyword(), level.hasEnumKeywordAndAutoboxing());
}
public static boolean isKeyword(String id, LanguageLevel level) {
return getTable(level).contains(id);
}
private final _JavaLexer myFlexLexer;
private final HashTable myTable;
private CharSequence myBuffer;
private char[] myBufferArray;
private int myBufferIndex;
private int myBufferEndOffset;
private int myTokenEndOffset; // positioned after the last symbol of the current token
private IElementType myTokenType;
private _JavaLexer myFlexLexer;
//Positioned after the last symbol of the current token
private int myTokenEndOffset;
public JavaLexer(@NotNull final LanguageLevel level) {
myFlexLexer = new _JavaLexer(level);
myTable = getTable(level);
}
private static final class HashTable {
private static final int NUM_ENTRIES = 999;
private static final Logger LOG = Logger.getInstance("com.intellij.Lexer.JavaLexer");
private final LanguageLevel myLevel;
private final char[][] myTable = new char[NUM_ENTRIES][];
private final IElementType[] myKeywords = new IElementType[NUM_ENTRIES];
private final Set<String> myKeywordsInSet = new THashSet<String>();
@@ -111,12 +112,16 @@ public class JavaLexer extends LexerBase {
}
@SuppressWarnings({"HardCodedStringLiteral"})
private HashTable(boolean isAssertKeywordEnabled, boolean isJDK15) {
if (isAssertKeywordEnabled) {
private HashTable(final LanguageLevel level) {
myLevel = level;
if (level.isAtLeast(LanguageLevel.JDK_1_4)) {
add("assert", JavaTokenType.ASSERT_KEYWORD);
}
if (isJDK15) {
add("enum", JavaTokenType.ENUM_KEYWORD);
if (level.isAtLeast(LanguageLevel.JDK_1_5)) {
add("enum", JavaTokenType.ENUM_KEYWORD);
if (level.isAtLeast(LanguageLevel.JDK_1_8)) {
add("none", JavaTokenType.NONE_KEYWORD);
}
}
}
add("abstract", JavaTokenType.ABSTRACT_KEYWORD);
add("default", JavaTokenType.DEFAULT_KEYWORD);
@@ -172,12 +177,6 @@ public class JavaLexer extends LexerBase {
}
}
private final HashTable myTable;
private static final HashTable ourTableWithoutAssert = new HashTable(false, false);
private static final HashTable ourTableWithAssert = new HashTable(true, false);
private static final HashTable ourTableWithAssertAndJDK15 = new HashTable(true, true);
private static final HashTable ourTableWithJDK15 = new HashTable(false, true);
@Override
public final void start(CharSequence buffer, int startOffset, int endOffset, int initialState) {
myBuffer = buffer;
@@ -1,6 +1,8 @@
/* It's an automatically generated code. Do not modify it. */
package com.intellij.lexer;
import com.intellij.psi.*;
import com.intellij.pom.java.LanguageLevel;
import com.intellij.psi.JavaTokenType;
import com.intellij.psi.impl.source.tree.JavaDocElementType;
import com.intellij.psi.tree.IElementType;
@@ -8,13 +10,15 @@ import com.intellij.psi.tree.IElementType;
%%
%{
private boolean myAssertKeywordEnabled;
private boolean myJdk15Enabled;
private boolean myAssertKeyword;
private boolean myEnumKeyword;
private boolean myNoneKeyword;
public _JavaLexer(boolean isAssertKeywordEnabled, boolean jdk15Enabled){
public _JavaLexer(LanguageLevel level) {
this((java.io.Reader)null);
myAssertKeywordEnabled = isAssertKeywordEnabled;
myJdk15Enabled = jdk15Enabled;
myAssertKeyword = level.isAtLeast(LanguageLevel.JDK_1_4);
myEnumKeyword = level.isAtLeast(LanguageLevel.JDK_1_5);
myNoneKeyword = level.isAtLeast(LanguageLevel.JDK_1_8);
}
public void goTo(int offset) {
@@ -101,7 +105,7 @@ ESCAPE_SEQUENCE=\\[^\r\n]
<YYINITIAL> "null" { return JavaTokenType.NULL_KEYWORD; }
<YYINITIAL> "abstract" { return JavaTokenType.ABSTRACT_KEYWORD; }
<YYINITIAL> "assert" { return myAssertKeywordEnabled ? JavaTokenType.ASSERT_KEYWORD : JavaTokenType.IDENTIFIER; }
<YYINITIAL> "assert" { return myAssertKeyword ? JavaTokenType.ASSERT_KEYWORD : JavaTokenType.IDENTIFIER; }
<YYINITIAL> "boolean" { return JavaTokenType.BOOLEAN_KEYWORD; }
<YYINITIAL> "break" { return JavaTokenType.BREAK_KEYWORD; }
<YYINITIAL> "byte" { return JavaTokenType.BYTE_KEYWORD; }
@@ -115,7 +119,7 @@ ESCAPE_SEQUENCE=\\[^\r\n]
<YYINITIAL> "do" { return JavaTokenType.DO_KEYWORD; }
<YYINITIAL> "double" { return JavaTokenType.DOUBLE_KEYWORD; }
<YYINITIAL> "else" { return JavaTokenType.ELSE_KEYWORD; }
<YYINITIAL> "enum" { return myJdk15Enabled ? JavaTokenType.ENUM_KEYWORD : JavaTokenType.IDENTIFIER; }
<YYINITIAL> "enum" { return myEnumKeyword ? JavaTokenType.ENUM_KEYWORD : JavaTokenType.IDENTIFIER; }
<YYINITIAL> "extends" { return JavaTokenType.EXTENDS_KEYWORD; }
<YYINITIAL> "final" { return JavaTokenType.FINAL_KEYWORD; }
<YYINITIAL> "finally" { return JavaTokenType.FINALLY_KEYWORD; }
@@ -150,6 +154,7 @@ ESCAPE_SEQUENCE=\\[^\r\n]
<YYINITIAL> "try" { return JavaTokenType.TRY_KEYWORD; }
<YYINITIAL> "volatile" { return JavaTokenType.VOLATILE_KEYWORD; }
<YYINITIAL> "throws" { return JavaTokenType.THROWS_KEYWORD; }
<YYINITIAL> "none" { return myNoneKeyword ? JavaTokenType.NONE_KEYWORD : JavaTokenType.IDENTIFIER; }
<YYINITIAL> {IDENTIFIER} { return JavaTokenType.IDENTIFIER; }
@@ -201,5 +206,7 @@ ESCAPE_SEQUENCE=\\[^\r\n]
<YYINITIAL> "%" { return JavaTokenType.PERC; }
<YYINITIAL> "@" { return JavaTokenType.AT; }
<YYINITIAL> . { return JavaTokenType.BAD_CHARACTER; }
<YYINITIAL> "::" { return JavaTokenType.DOUBLE_COLON; }
<YYINITIAL> "->" { return JavaTokenType.ARROW; }
<YYINITIAL> . { return JavaTokenType.BAD_CHARACTER; }
File diff suppressed because it is too large Load Diff
@@ -41,7 +41,6 @@ annotation.target.PACKAGE=package
generics.holder.type=Type
generics.holder.method=Method
generics.are.not.supported=Generics are not supported at this language level
generics.inferred.type.for.type.parameter.is.not.within.its.bound.extend=Inferred type ''{2}'' for type parameter ''{0}'' is not within its bound; should extend ''{1}''
generics.inferred.type.for.type.parameter.is.not.within.its.bound.implement=Inferred type ''{2}'' for type parameter ''{0}'' is not within its bound; should implement ''{1}''
generics.type.parameter.is.not.within.its.bound.extend=Type parameter ''{0}'' is not within its bound; should extend ''{1}''
@@ -83,7 +82,6 @@ generics.type.arguments.on.raw.type=Type arguments given on a raw type
generics.type.arguments.on.raw.method=Type arguments given on a raw method
classes.extends.enum=Classes cannot directly extend 'java.lang.Enum'
unchecked.overriding.incompatible.return.type=Unchecked overriding: return type requires unchecked conversion. Found ''{0}'', required ''{1}''
unchecked.overriding=Unchecked overriding
local.enum=Enum must not be local
interface.expected=Interface expected here
@@ -237,10 +235,6 @@ static.member.accessed.via.instance.reference=Static member ''{0}.{1}'' accessed
unresolved.label=Undefined label: ''{0}''
deprecated.symbol=''{0}'' is deprecated
cannot.resolve.symbol=Cannot resolve symbol ''{0}''
static.imports.prior.15=Static imports are not supported at this language level
varargs.prior.15=Variable arity methods are not supported at this language level
foreach.prior.15=Foreach loops are not supported at this language level
annotations.prior.15=Annotations are not supported at this language level
class.is.already.defined.in.single.static.import=Class ''{0}'' is already defined in a single static import
class.is.ambiguous.in.single.static.import=Class ''{0}'' is ambiguous in a single static import
field.is.already.defined.in.single.static.import=Field ''{0}'' is already defined in a single static import
@@ -264,8 +258,6 @@ private.inner.interface.is.not.used=Private inner interface ''{0}'' is never use
type.parameter.is.not.used=Type parameter ''{0}'' is never used
local.class.is.not.used=Local class ''{0}'' is never used
class.is.not.used=Class ''{0}'' is never used
uidesigned.field.is.overwritten.by.generated.code=Field ''{0}'' is overwritten by generated code
uidesigner.bound.field.type.mismatch=Types of GUI component (''{0}'') and bound field (''{1}'') do not match
hexadecimal.numbers.must.contain.at.least.one.hexadecimal.digit=Hexadecimal numbers must contain at least one hexadecimal digit
binary.numbers.must.contain.at.least.one.hexadecimal.digit=Binary numbers must contain at least one binary digit
@@ -322,7 +314,6 @@ expected.resource=Resource definition expected
expected.type.parameter=Type parameter expected
expected.comma=',' expected
expected.comma.or.rparen=',' or ')' expected
unexpected.tokens.beyond.the.end.of.expression=Unexpected token(s) beyond the end of expression
expected.colon=':' expected
expected.type=Type expected
expected.lbracket='[' expected
@@ -352,3 +343,13 @@ cannot.resolve.package=Cannot resolve package {0}
override.not.allowed.in.interfaces=@Override is not allowed when implementing interface method
wildcard.not.expected=Unexpected wildcard
bound.not.expected=Unexpected bound
feature.generics=Generics
feature.annotations=Annotations
feature.static.imports=Static imports
feature.for.each=For-each loops
feature.varargs=Variable arity methods
feature.diamond.types=Diamond types
feature.try.with.resources=Try-with-resources
feature.multi.catch=Multi-catches
insufficient.language.level={0} are not supported at this language level
@@ -0,0 +1,41 @@
/*
* Copyright 2000-2012 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.io.*;
import java.util.*;
<error descr="Static imports are not supported at this language level">import static java.lang.Math.*;</error>
@interface <error descr="Annotations are not supported at this language level">Anno</error> { }
<error descr="Annotations are not supported at this language level">@Anno</error>
class UnsupportedFeatures {
void m(<error descr="Variable arity methods are not supported at this language level">String... args</error>) throws Exception {
<error descr="For-each loops are not supported at this language level">for (String s : args) { System.out.println(s); }</error>
List<error descr="Generics are not supported at this language level"><String></error> list =
new ArrayList<error descr="Diamond types are not supported at this language level"><></error>();
for (<error descr="Incompatible types. Found: 'java.lang.Object', required: 'java.lang.String'">String s : list</error>) {}
Arrays.asList<error descr="'asList(java.lang.String...)' in 'java.util.Arrays' cannot be applied to '(java.lang.String)'">("")</error>;
<error descr="Incompatible types. Found: 'boolean', required: 'java.lang.Boolean'">Boolean b = true;</error>
<error descr="Incompatible types. Found: 'java.lang.Boolean', required: 'boolean'">boolean b1 = Boolean.TRUE;</error>
try { Reader r = new FileReader("/dev/null"); }
catch (<error descr="Multi-catches are not supported at this language level">FileNotFoundException | IOException e</error>) { e.printStackTrace(); }
try <error descr="Try-with-resources are not supported at this language level">(Reader r = new FileReader("/dev/null"))</error> { }
}
}
@@ -0,0 +1,37 @@
/*
* Copyright 2000-2012 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.util.List;
import static java.lang.Math.min;
class a {
List<String> l;
private void asList(Object... objects) {}
void foo() {
for (String s : l) {}
for (Object o : l) {}
asList("");
Boolean b = true;
boolean b1 = Boolean.TRUE;
}
enum e {}
}
@@ -1,4 +1,4 @@
// "Remove redundant arguments to match 'method(int, Integer)'" "true"
// "Remove redundant arguments to call 'method(int, Integer)'" "true"
class A {
public A() {
method(new Integer(5), 5);
@@ -1,4 +1,4 @@
// "Remove redundant arguments to match 'method(int, T)'" "true"
// "Remove redundant arguments to call 'method(int, T)'" "true"
class A {
public A() {
method(5, new Exception());
@@ -1,4 +1,4 @@
// "Remove redundant arguments to match 'method(int, String)'" "true"
// "Remove redundant arguments to call 'method(int, String)'" "true"
class A {
public A() {
method(5, "");
@@ -1,4 +1,4 @@
// "Remove redundant arguments to match 'method(int, Integer)'" "true"
// "Remove redundant arguments to call 'method(int, Integer)'" "true"
class A {
public A() {
method(new Integer(5), 5,<caret> "", new String());
@@ -1,4 +1,4 @@
// "Remove redundant arguments to match 'method(int, T)'" "true"
// "Remove redundant arguments to call 'method(int, T)'" "true"
class A {
public A() {
method(5,<caret> new Exception(), new Exception(), "", 3);
@@ -1,4 +1,4 @@
// "Remove redundant arguments to match 'method(int, String)'" "true"
// "Remove redundant arguments to call 'method(int, String)'" "true"
class A {
public A() {
method(5, "",<caret> 10);
@@ -5,6 +5,6 @@
* Time: 17:43
* To change this template use File | Settings | File Templates.
*/
@Ann({A.class})
@Ann(A.class)
public class Annotated {
}
@@ -1,24 +1,21 @@
PsiJavaFile:New15.java
PsiMethodCallExpression:new C<?>.B()
PsiReferenceExpression:new C<?>.B
PsiNewExpression:new C<?>
PsiKeyword:new('new')
PsiNewExpression:new C<?>.B()
PsiKeyword:new('new')
PsiReferenceParameterList
<empty list>
PsiWhiteSpace(' ')
PsiJavaCodeReferenceElement:C<?>.B
PsiJavaCodeReferenceElement:C<?>
PsiIdentifier:C('C')
PsiReferenceParameterList
<empty list>
PsiWhiteSpace(' ')
PsiJavaCodeReferenceElement:C<?>
PsiIdentifier:C('C')
PsiReferenceParameterList
PsiJavaToken:LT('<')
PsiTypeElement:?
PsiJavaToken:QUEST('?')
PsiJavaToken:GT('>')
PsiErrorElement:'(' or '[' expected
<empty list>
PsiJavaToken:LT('<')
PsiTypeElement:?
PsiJavaToken:QUEST('?')
PsiJavaToken:GT('>')
PsiJavaToken:DOT('.')
PsiIdentifier:B('B')
PsiReferenceParameterList
<empty list>
PsiIdentifier:B('B')
PsiExpressionList
PsiJavaToken:LPARENTH('(')
PsiJavaToken:RPARENTH(')')
-10
View File
@@ -1,10 +0,0 @@
class Anonymous {
int num1;
int num2;
Object o = new Object(){
int num = 1;
};
Anonymous() {}
void foo() {}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2011 JetBrains s.r.o.
* Copyright 2000-2012 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.
@@ -57,6 +57,10 @@ public class LightAdvHighlightingJdk7Test extends LightDaemonAnalyzerTestCase {
};
}
public void testAllJava15Features() throws Exception {
doTest(false, false);
}
public void testEnumSyntheticMethods() throws Exception {
doTest(false, false);
}
@@ -40,6 +40,7 @@ import com.intellij.openapi.extensions.Extensions;
import com.intellij.openapi.fileTypes.StdFileTypes;
import com.intellij.openapi.roots.LanguageLevelProjectExtension;
import com.intellij.openapi.vfs.VfsUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.pom.java.LanguageLevel;
import com.intellij.psi.*;
import com.intellij.psi.xml.XmlAttribute;
@@ -161,7 +162,7 @@ public class LightAdvHighlightingTest extends LightDaemonAnalyzerTestCase {
public void testQualifiedNew() throws Exception { doTest(false, false); }
public void testEnclosingInstance() throws Exception { doTest(false, false); }
public void testStaticViaInstance() throws Exception { doTest(true, false); } // static via instabnce
public void testStaticViaInstance() throws Exception { doTest(true, false); } // static via instance
public void testQualifiedThisSuper() throws Exception { doTest(true, false); } //illegal qualified this or super
public void testAmbiguousMethodCall() throws Exception { doTest(false, false); }
@@ -230,19 +231,13 @@ public class LightAdvHighlightingTest extends LightDaemonAnalyzerTestCase {
}
@Override
public void setSelected(boolean selected) {
}
public void setSelected(boolean selected) { }
@Override
public void readExternal(Element element) {
}
public void readExternal(Element element) { }
@Override
public void writeExternal(Element element) {
}
public void writeExternal(Element element) { }
};
point.registerExtension(extension);
@@ -265,9 +260,13 @@ public class LightAdvHighlightingTest extends LightDaemonAnalyzerTestCase {
ApplicationManager.getApplication().runWriteAction(new Runnable() {
@Override
public void run() {
PsiFile txt = myFile.getParent().createFile("x.txt");
PsiDirectory directory = myFile.getParent();
assertNotNull(myFile.toString(), directory);
PsiFile txt = directory.createFile("x.txt");
VirtualFile vFile = txt.getVirtualFile();
assertNotNull(txt.toString(), vFile);
try {
VfsUtil.saveText(txt.getVirtualFile(), "XXX");
VfsUtil.saveText(vFile, "XXX");
}
catch (IOException e) {
throw new RuntimeException(e);
@@ -356,11 +355,7 @@ public class LightAdvHighlightingTest extends LightDaemonAnalyzerTestCase {
doHighlighting();
}
public void testClassicRethrow() throws Exception {
doTest(false, false);
}
public void testRegexp() throws Exception {
doTest(false, false);
}
public void testClassicRethrow() throws Exception { doTest(false, false); }
public void testRegexp() throws Exception { doTest(false, false); }
public void testUnsupportedFeatures() throws Exception { doTest(false, false); }
}
@@ -134,6 +134,11 @@ public class JavaLexerTest extends LexerTestCase {
"WHITE_SPACE (' ')\nINTEGER_LITERAL ('0')\nRPARENTH (')')\n");
}
public void testJava8Tokens() {
doTest("none :: ->",
"NONE_KEYWORD ('none')\nWHITE_SPACE (' ')\nDOUBLE_COLON ('::')\nWHITE_SPACE (' ')\nARROW ('->')");
}
@Override
protected Lexer createLexer() {
return new JavaLexer(LanguageLevel.HIGHEST);
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2010 JetBrains s.r.o.
* Copyright 2000-2012 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -15,11 +15,7 @@
*/
package com.intellij.lang.java.parser;
import com.intellij.pom.java.LanguageLevel;
public class ExpressionParsingTest extends JavaParsingTestCase {
public ExpressionParsingTest() {
super("parser-full/expressionParsing");
}
@@ -75,11 +71,7 @@ public class ExpressionParsingTest extends JavaParsingTestCase {
public void testNew12() { doTest(true); }
public void testNew13() { doTest(true); }
public void testNew14() { doTest(true); }
public void testNew15() {
withLevel(LanguageLevel.JDK_1_7, new Runnable() { @Override public void run() {
doTest(true);
}});
}
public void testNew15() { doTest(true); }
public void testExprList0() { doTest(true); }
public void testExprList1() { doTest(true); }
@@ -18,10 +18,8 @@ package com.intellij.lang.java.parser.partial;
import com.intellij.lang.PsiBuilder;
import com.intellij.lang.java.parser.JavaParsers;
import com.intellij.lang.java.parser.JavaParsingTestCase;
import com.intellij.pom.java.LanguageLevel;
import org.jetbrains.annotations.NonNls;
public class ExpressionParserTest extends JavaParsingTestCase {
public ExpressionParserTest() {
super("parser-partial/expressions");
@@ -77,11 +75,7 @@ public class ExpressionParserTest extends JavaParsingTestCase {
public void testNew13() { doParserTest("new int[1][][2]"); }
public void testNew14() { doParserTest("Q.new A()"); }
public void testNew15() { doParserTest("new C<?>.B()"); }
public void testNew16() {
withLevel(LanguageLevel.JDK_1_7,
new Runnable() { @Override
public void run() { doParserTest("new C<>()"); } });
}
public void testNew16() { doParserTest("new C<>()"); }
public void testExprList0() { doParserTest("f(1,2)"); }
public void testExprList1() { doParserTest("f("); }
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2010 JetBrains s.r.o.
* Copyright 2000-2012 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.
@@ -18,8 +18,6 @@ package com.intellij.lang.java.parser.partial;
import com.intellij.lang.PsiBuilder;
import com.intellij.lang.java.parser.JavaParsers;
import com.intellij.lang.java.parser.JavaParsingTestCase;
import com.intellij.pom.java.LanguageLevel;
public class StatementParserTest extends JavaParsingTestCase {
public StatementParserTest() {
@@ -119,10 +117,10 @@ public class StatementParserTest extends JavaParsingTestCase {
public void testTryNormal0() { doParserTest("try{}catch(E e){}"); }
public void testTryNormal1() { doParserTest("try{}catch(final E e){}finally{}"); }
public void testTryNormal2() { doParserTest("try{}finally{}"); }
public void testTryNormal3() { doParserTestJDK7("try{}catch(A|B e){}"); }
public void testTryNormal4() { doParserTestJDK7("try(R r = 0){}"); }
public void testTryNormal5() { doParserTestJDK7("try(R1 r1 = 1; R2 r2 = 2){}"); }
public void testTryNormal6() { doParserTestJDK7("try(R r = 0;){}"); }
public void testTryNormal3() { doParserTest("try{}catch(A|B e){}"); }
public void testTryNormal4() { doParserTest("try(R r = 0){}"); }
public void testTryNormal5() { doParserTest("try(R1 r1 = 1; R2 r2 = 2){}"); }
public void testTryNormal6() { doParserTest("try(R r = 0;){}"); }
public void testTryIncomplete0() { doParserTest("try"); }
public void testTryIncomplete1() { doParserTest("try{}"); }
public void testTryIncomplete2() { doParserTest("try{}catch"); }
@@ -131,16 +129,16 @@ public class StatementParserTest extends JavaParsingTestCase {
public void testTryIncomplete5() { doParserTest("try{}catch(E e"); }
public void testTryIncomplete6() { doParserTest("try{}catch(E e)"); }
public void testTryIncomplete7() { doParserTest("try{}finally"); }
public void testTryIncomplete8() { doParserTestJDK7("try{}catch(A|)"); }
public void testTryIncomplete9() { doParserTestJDK7("try{}catch(A|B)"); }
public void testTryIncomplete10() { doParserTestJDK7("try({}"); }
public void testTryIncomplete11() { doParserTestJDK7("try(){}"); }
public void testTryIncomplete12() { doParserTestJDK7("try(;){}"); }
public void testTryIncomplete13() { doParserTestJDK7("try(final ){}"); }
public void testTryIncomplete14() { doParserTestJDK7("try(int){}"); }
public void testTryIncomplete15() { doParserTestJDK7("try(R r){}"); }
public void testTryIncomplete16() { doParserTestJDK7("try(R r =){}"); }
public void testTryIncomplete17() { doParserTestJDK7("try(R r = 0;;){}"); }
public void testTryIncomplete8() { doParserTest("try{}catch(A|)"); }
public void testTryIncomplete9() { doParserTest("try{}catch(A|B)"); }
public void testTryIncomplete10() { doParserTest("try({}"); }
public void testTryIncomplete11() { doParserTest("try(){}"); }
public void testTryIncomplete12() { doParserTest("try(;){}"); }
public void testTryIncomplete13() { doParserTest("try(final ){}"); }
public void testTryIncomplete14() { doParserTest("try(int){}"); }
public void testTryIncomplete15() { doParserTest("try(R r){}"); }
public void testTryIncomplete16() { doParserTest("try(R r =){}"); }
public void testTryIncomplete17() { doParserTest("try(R r = 0;;){}"); }
public void testWhileNormal() { doParserTest("while (true) foo();"); }
public void testWhileIncomplete0() { doParserTest("while"); }
@@ -151,33 +149,22 @@ public class StatementParserTest extends JavaParsingTestCase {
public void testWhileIncomplete5() { doParserTest("while() foo();"); }
private void doBlockParserTest(final String text) {
doParserTest(text, new MyTestParser1());
doParserTest(text, new MyBlockTestParser());
}
private void doParserTest(final String text) {
doParserTest(text, new MyTestParser2());
}
private void doParserTestJDK7(final String text) {
withLevel(LanguageLevel.JDK_1_7, new Runnable() {
@Override
public void run() {
doParserTest(text);
}
});
}
private static class MyTestParser2 implements TestParser {
@Override
public void parse(final PsiBuilder builder) {
JavaParsers.STATEMENT_PARSER.parseStatements(builder);
}
}
private static class MyTestParser1 implements TestParser {
private static class MyBlockTestParser implements TestParser {
@Override
public void parse(final PsiBuilder builder) {
JavaParsers.STATEMENT_PARSER.parseCodeBlockDeep(builder, true);
}
}
private void doParserTest(final String text) {
doParserTest(text, new MyStatementsTestParser());
}
private static class MyStatementsTestParser implements TestParser {
@Override
public void parse(final PsiBuilder builder) {
JavaParsers.STATEMENT_PARSER.parseStatements(builder);
}
}
}
@@ -1,8 +1,21 @@
/*
* Copyright 2000-2012 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.lang.java.parser.statementParsing;
import com.intellij.lang.java.parser.JavaParsingTestCase;
import com.intellij.pom.java.LanguageLevel;
public class TryParsingTest extends JavaParsingTestCase {
public TryParsingTest() {
@@ -12,11 +25,7 @@ public class TryParsingTest extends JavaParsingTestCase {
public void testNormal1() { doTest(true); }
public void testNormal2() { doTest(true); }
public void testNormal3() { doTest(true); }
public void testNormal4() {
withLevel(LanguageLevel.JDK_1_7, new Runnable() { @Override public void run() {
doTest(true);
}});
}
public void testNormal4() { doTest(true); }
public void testIncomplete1() { doTest(true); }
public void testIncomplete2() { doTest(true); }
@@ -26,9 +35,5 @@ public class TryParsingTest extends JavaParsingTestCase {
public void testIncomplete6() { doTest(true); }
public void testIncomplete7() { doTest(true); }
public void testIncomplete8() { doTest(true); }
public void testIncomplete9() {
withLevel(LanguageLevel.JDK_1_7, new Runnable() { @Override public void run() {
doTest(true);
}});
}
public void testIncomplete9() { doTest(true); }
}
@@ -168,11 +168,12 @@ final class BuildSession implements Runnable, CanceledStatus {
final Project project = loadProject(projectPath);
final File dataStorageRoot = Utils.getDataStorageRoot(project);
final boolean inMemoryMappingsDelta = System.getProperty(GlobalOptions.USE_MEMORY_TEMP_CACHE_OPTION) != null;
ProjectTimestamps projectTimestamps = null;
BuildDataManager dataManager = null;
try {
projectTimestamps = new ProjectTimestamps(dataStorageRoot);
dataManager = new BuildDataManager(dataStorageRoot, true);
dataManager = new BuildDataManager(dataStorageRoot, inMemoryMappingsDelta);
if (dataManager.versionDiffers()) {
forceCleanCaches = true;
msgHandler.processMessage(new CompilerMessage("build", BuildMessage.Kind.INFO, "Dependency data format has changed, project rebuild required"));
@@ -190,7 +191,7 @@ final class BuildSession implements Runnable, CanceledStatus {
forceCleanCaches = true;
FileUtil.delete(dataStorageRoot);
projectTimestamps = new ProjectTimestamps(dataStorageRoot);
dataManager = new BuildDataManager(dataStorageRoot, true);
dataManager = new BuildDataManager(dataStorageRoot, inMemoryMappingsDelta);
// second attempt succeded
msgHandler.processMessage(new CompilerMessage("build", BuildMessage.Kind.INFO, "Project rebuild forced: " + e.getMessage()));
}
@@ -58,6 +58,7 @@ public class JavaBuilder extends ModuleLevelBuilder {
private static final String JAVA_EXTENSION = ".java";
private static final String FORM_EXTENSION = ".form";
public static final boolean USE_EMBEDDED_JAVAC = System.getProperty(GlobalOptions.USE_EXTERNAL_JAVAC_OPTION) == null;
private static final Key<Integer> JAVA_COMPILER_VERSION_KEY = Key.create("_java_compiler_version_");
public static final FileFilter JAVA_SOURCES_FILTER = new FileFilter() {
public boolean accept(File file) {
@@ -599,7 +600,17 @@ public class JavaBuilder extends ModuleLevelBuilder {
final BytecodeTargetConfiguration targetConfig = context.getProject().getCompilerConfiguration().getBytecodeTarget();
String bytecodeTarget = null;
int chunkSdkVersion = -1;
for (Module module : chunk.getModules()) {
final Sdk sdk = module.getSdk();
if (sdk instanceof JavaSdk) {
final JavaSdk moduleSdk = (JavaSdk)sdk;
final int moduleSdkVersion = convertToNumber(moduleSdk.getVersion());
if (moduleSdkVersion != 0 /*could determine the version*/&& (chunkSdkVersion < 0 || chunkSdkVersion > moduleSdkVersion)) {
chunkSdkVersion = moduleSdkVersion;
}
}
final String moduleTarget = getModuleTarget(targetConfig, module);
if (moduleTarget == null) {
continue;
@@ -617,10 +628,37 @@ public class JavaBuilder extends ModuleLevelBuilder {
options.add("-target");
options.add(bytecodeTarget);
}
else {
if (chunkSdkVersion > 0 && getCompilerSdkVersion(context) > chunkSdkVersion) {
// force lower bytecode target level to match the version of sdk assigned to this chunk
options.add("-target");
options.add("1." + chunkSdkVersion);
}
}
return options;
}
private static int getCompilerSdkVersion(CompileContext context) {
final Integer cached = JAVA_COMPILER_VERSION_KEY.get(context);
if (cached != null) {
return cached;
}
int javaVersion = convertToNumber(SystemProperties.getJavaVersion());
if (!USE_EMBEDDED_JAVAC) {
// in case of external javac, run compiler from the newest jdk that is used in the project
for (JavaSdk sdk : context.getProjectDescriptor().getProjectJavaSdks()) {
final String version = sdk.getVersion();
final int ver = convertToNumber(version);
if (ver > javaVersion) {
javaVersion = ver;
}
}
}
JAVA_COMPILER_VERSION_KEY.set(context, javaVersion);
return javaVersion;
}
@Nullable
private static String getModuleTarget(BytecodeTargetConfiguration config, Module module) {
final String level = config.getModulesBytecodeTarget().get(module.getName());
@@ -86,7 +86,7 @@ public class ClasspathBootstrap {
private ClasspathBootstrap() {
}
public static List<File> getCompileServerApplicationClasspath() {
public static List<File> getBuildProcessApplicationClasspath() {
final Set<File> cp = new LinkedHashSet<File>();
cp.add(getResourcePath(Server.class));
for (String path : PathManager.getUtilClassPath()) { cp.add(new File(path)); } // util
@@ -114,14 +114,6 @@ public class ClasspathBootstrap {
catch (Throwable ignored) {
}
final JavaCompiler systemCompiler = ToolProvider.getSystemJavaCompiler();
if (systemCompiler != null) {
try {
cp.add(getResourcePath(systemCompiler.getClass())); // tools.jar
}
catch (Throwable ignored) {
}
}
return new ArrayList<File>(cp);
}
@@ -930,6 +930,7 @@ public class Mappings {
if (classes != null) {
for (ClassRepr c : classes) {
debug("Affecting usages of removed class ", c.name);
u.affectAll(c.name, affectedFiles);
}
}
@@ -1226,8 +1227,10 @@ public class Mappings {
}
final Collection<Pair<MethodRepr, ClassRepr>> overriding = u.findOverridingMethods(m, it, false);
for (final Pair<MethodRepr, ClassRepr> p : overriding) {
final int fName = myClassToSourceFile.get(p.second.name);
debug("Affecting file by overriding: ", fName);
affectedFiles.add(new File(myContext.getValue(fName)));
}
@@ -33,6 +33,10 @@ public abstract class AbstractExtensionPointBean implements PluginAware {
myPluginDescriptor = pluginDescriptor;
}
public PluginDescriptor getPluginDescriptor() {
return myPluginDescriptor;
}
@NotNull
public final <T> Class<T> findClass(final String className) throws ClassNotFoundException {
return (Class<T>)Class.forName(className, true, getLoaderForClass());
Binary file not shown.

Before

Width:  |  Height:  |  Size: 570 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 490 B

@@ -23,6 +23,7 @@ import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiFile;
import com.intellij.ui.GuiUtils;
import com.intellij.util.SmartList;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import java.lang.reflect.InvocationTargetException;
@@ -41,7 +42,7 @@ public abstract class WriteCommandAction<T> extends BaseActionRunnable<T> {
this(project, "Undefined", files);
}
protected WriteCommandAction(Project project, String commandName, PsiFile... files) {
protected WriteCommandAction(Project project, @NonNls String commandName, PsiFile... files) {
this(project, commandName, null, files);
}
@@ -64,11 +65,13 @@ public abstract class WriteCommandAction<T> extends BaseActionRunnable<T> {
return myGroupID;
}
@Override
public RunResult<T> execute() {
final RunResult<T> result = new RunResult<T>(this);
try {
Runnable runnable = new Runnable() {
@Override
public void run() {
performWriteCommandAction(result);
}
@@ -83,7 +86,7 @@ public abstract class WriteCommandAction<T> extends BaseActionRunnable<T> {
} catch (Throwable e) {
if (e instanceof InvocationTargetException) e = e.getCause();
if (e instanceof Error) throw (Error)e;
else if (e instanceof RuntimeException) throw (RuntimeException)e;
if (e instanceof RuntimeException) throw (RuntimeException)e;
throw new Error(e);
}
return result;
@@ -116,8 +119,10 @@ public abstract class WriteCommandAction<T> extends BaseActionRunnable<T> {
final RunResult[] results = {result};
CommandProcessor.getInstance().executeCommand(getProject(), new Runnable() {
@Override
public void run() {
getApplication().runWriteAction(new Runnable() {
@Override
public void run() {
results[0].run();
results[0] = null;
@@ -141,6 +146,7 @@ public abstract class WriteCommandAction<T> extends BaseActionRunnable<T> {
final RunResult[] results = {result};
CommandProcessor.getInstance().executeCommand(myProject, new Runnable() {
@Override
public void run() {
if (isGlobalUndoAction()) CommandProcessor.getInstance().markCurrentCommandAsGlobal(myProject);
results[0].run();
@@ -167,6 +173,7 @@ public abstract class WriteCommandAction<T> extends BaseActionRunnable<T> {
super(project, name, groupID, files);
}
@Override
protected void run(final Result result) throws Throwable {
run();
}
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2010 JetBrains s.r.o.
* Copyright 2000-2012 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.
@@ -263,13 +263,13 @@ public abstract class OptionTableWithPreviewPanel extends MultilanguageCodeStyle
final TableColumn levelColumn = treeTable.getColumnModel().getColumn(1);
//TODO[max]: better preffered size...
JLabel value = new JLabel(ApplicationBundle.message("option.table.sizing.text"));
final Dimension valueSize = value.getPreferredSize();
levelColumn.setPreferredWidth(valueSize.width);
levelColumn.setMaxWidth(valueSize.width);
levelColumn.setMinWidth(valueSize.width);
levelColumn.setResizable(false);
//TODO[kb]: Did I fixed it by making the last column floating?
//levelColumn.setPreferredWidth(valueSize.width);
//levelColumn.setMaxWidth(valueSize.width);
//levelColumn.setMinWidth(valueSize.width);
//levelColumn.setResizable(false);
final Dimension valueSize = new JLabel(ApplicationBundle.message("option.table.sizing.text")).getPreferredSize();
treeTable.setPreferredScrollableViewportSize(new Dimension(maxWidth + valueSize.width + 10, 20));
return treeTable;
@@ -147,11 +147,19 @@ public class GotoDeclarationAction extends BaseCodeInsightAction implements Code
return true;
}
if (elements.length > 1) {
final TextRange range = reference.getRangeInElement();
final String elementText = reference.getElement().getText();
LOG.assertTrue(range.getStartOffset() >= 0 && range.getEndOffset() <= elementText.length(), Arrays.toString(elements));
final String refText = range.substring(elementText);
String title = MessageFormat.format(titlePattern, refText);
String title;
if (reference != null) {
final TextRange range = reference.getRangeInElement();
final String elementText = reference.getElement().getText();
LOG.assertTrue(range.getStartOffset() >= 0 && range.getEndOffset() <= elementText.length(), Arrays.toString(elements));
final String refText = range.substring(elementText);
title = MessageFormat.format(titlePattern, refText);
}
else {
title = titlePattern;
}
NavigationUtil.getPsiElementPopup(elements, new DefaultPsiElementCellRenderer(), title, processor).showInBestPositionFor(editor);
return true;
}
@@ -58,7 +58,7 @@ public class SuppressionUtil {
for (@NonNls String id : ids) {
@NonNls String trim = id.trim();
if (trim.equals(inspectionToolID) || trim.equals(ALL)) return true;
if (trim.equals(inspectionToolID) || trim.equalsIgnoreCase(ALL)) return true;
}
return false;
}
@@ -255,7 +255,7 @@ public abstract class RefElementImpl extends RefEntityImpl implements RefElement
public boolean isSuppressed(final String toolId) {
if (mySuppressions != null) {
for (@NonNls String suppression : mySuppressions) {
if (suppression.equals(toolId) || suppression.equals(SuppressionUtil.ALL)){
if (suppression.equals(toolId) || suppression.equalsIgnoreCase(SuppressionUtil.ALL)){
return true;
}
}
@@ -32,7 +32,7 @@ public abstract class IndentationFoldingBuilder implements FoldingBuilder, DumbA
private void collectDescriptors(@NotNull final ASTNode node, @NotNull final List<FoldingDescriptor> descriptors) {
final ASTNode[] children = node.getChildren(myTokenSet);
if (children.length > 0) {
if (node.getTreeParent() !=null) {
if (node.getTreeParent() !=null && node.getTextLength() > 0) {
descriptors.add(new FoldingDescriptor(node, node.getTextRange()));
}
for (ASTNode child : children) {
@@ -143,7 +143,7 @@ public class DocumentCommitThread implements Runnable, Disposable {
markRemovedFromDocsToCommit(newTask);
markRemovedCurrentTask(newTask);
markRemovedFromDocsToApplyInEDT(newTask);
removeFromDocsToApplyInEDT(newTask);
documentsToCommit.addLast(newTask);
log("Queued", newTask, false, reason);
@@ -192,7 +192,7 @@ public class DocumentCommitThread implements Runnable, Disposable {
cancel("cancel all in tests");
markRemovedFromDocsToCommit(null);
documentsToCommit.clear();
markRemovedFromDocsToApplyInEDT(null);
removeFromDocsToApplyInEDT(null);
markRemovedCurrentTask(null);
}
}
@@ -208,6 +208,7 @@ public class DocumentCommitThread implements Runnable, Disposable {
private static class CommitTask {
private final Document document;
private final Project project;
// when queued it's not started
// when dequeued it's started
// when failed it's canceled
@@ -253,25 +254,16 @@ public class DocumentCommitThread implements Runnable, Disposable {
private void markRemovedCurrentTask(@Nullable CommitTask newTask) {
CommitTask task = currentTask;
if (task != null && (task.equals(newTask) || newTask == null)) {
if (task != null && (newTask == null || task.equals(newTask))) {
task.removed = true;
cancel("Sync commit intervened");
}
}
private void markRemovedFromDocsToApplyInEDT(@Nullable("null means all") CommitTask newTask) {
private void removeFromDocsToApplyInEDT(@Nullable("null means all") CommitTask newTask) {
for (int i = documentsToApplyInEDT.size() - 1; i >= 0; i--) {
CommitTask task = documentsToApplyInEDT.get(i);
if (newTask == null || task.equals(newTask)) {
log("Marked as Removed in EDT apply queue", task, false);
task.removed = true;
}
}
}
private void removeFromDocsToApplyInEDT(CommitTask newTask) {
for (int i = documentsToApplyInEDT.size() - 1; i >= 0; i--) {
CommitTask task = documentsToApplyInEDT.get(i);
if (task.equals(newTask)) {
task.removed = true;
documentsToApplyInEDT.remove(i);
log("Marked and Removed from EDT apply queue (sync commit called)", task, true);
@@ -301,7 +293,6 @@ public class DocumentCommitThread implements Runnable, Disposable {
pollQueue();
}
catch(Throwable e) {
//e.printStackTrace();
LOG.error(e);
}
}
@@ -443,7 +434,6 @@ public class DocumentCommitThread implements Runnable, Disposable {
if (cur != null) {
cur.indicator.cancel();
}
//log("Start new task", task, false, cur == null ? "" : cur.indicator + " canceled", reason);
currentTask = task;
}
}
@@ -556,7 +546,6 @@ public class DocumentCommitThread implements Runnable, Disposable {
((PsiDocumentManagerImpl)documentManager).clearTreeHardRef(document);
final TextBlock textBlock = TextBlock.get(file);
if (textBlock.isEmpty()) return null;
final long startPsiModificationTimeStamp = file.getModificationStamp();
final long startDocModificationTimeStamp = document.getModificationStamp();
final FileElement myTreeElementBeingReparsedSoItWontBeCollected = ((PsiFileImpl)file).calcTreeElement();
if (textBlock.isEmpty()) return null; // if tree was just loaded above textBlock will be cleared by contentsLoaded
@@ -593,7 +582,6 @@ public class DocumentCommitThread implements Runnable, Disposable {
public boolean process(Document document) {
ApplicationManager.getApplication().assertWriteAccessAllowed();
log("Finishing", task, synchronously, document.getModificationStamp(), startDocModificationTimeStamp);
//if (file.getModificationStamp() != startPsiModificationTimeStamp) return; // optimistic locking failed
if (document.getModificationStamp() != startDocModificationTimeStamp) {
return false; // optimistic locking failed
}
@@ -620,8 +608,6 @@ public class DocumentCommitThread implements Runnable, Disposable {
SmartPointerManagerImpl.synchronizePointers(file);
}
//System.out.println("committed "+task+"; tree length of "+myTreeElementBeingReparsedSoItWontBeCollected+" is " +myTreeElementBeingReparsedSoItWontBeCollected.getTextLength());
return true;
}
};
@@ -41,6 +41,7 @@ public class DirDiffSettings {
public boolean enableChoosers = true;
public CompareMode compareMode = CompareMode.CONTENT;
public double compareTimestampAccuracy = 0;
public CustomSourceChooser customSourceChooser;
public boolean showInFrame = true; // in dialog otherwise
@@ -103,4 +104,9 @@ public class DirDiffSettings {
@Nullable
String getName(CompareMode mode);
}
public interface CustomSourceChooser {
@Nullable
DiffElement chooseSource(@NotNull DiffElement first, @NotNull DiffElement second);
}
}
@@ -519,7 +519,7 @@ public class JBTable extends JTable implements ComponentWithEmptyText, Component
if (!isEditing()) {
return;
}
Component c = myFocusManager.getFocusOwner();
Component c = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner();
while (c != null) {
if (c instanceof JPopupMenu) {
c = ((JPopupMenu)c).getInvoker();
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2011 JetBrains s.r.o.
* Copyright 2000-2012 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.
@@ -19,7 +19,11 @@ import com.intellij.execution.ExecutionException;
import com.intellij.execution.configurations.GeneralCommandLine;
import com.intellij.execution.util.ExecutionErrorDialog;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.diff.*;
import com.intellij.openapi.diff.DiffBundle;
import com.intellij.openapi.diff.DiffRequest;
import com.intellij.openapi.diff.DiffTool;
import com.intellij.openapi.diff.DiffViewer;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.util.config.AbstractProperty;
import com.intellij.util.config.BooleanProperty;
@@ -27,9 +31,12 @@ import com.intellij.util.config.StringProperty;
import org.jetbrains.annotations.Nullable;
import java.awt.*;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
* @author Konstantin Bulenkov
*/
abstract class BaseExternalTool implements DiffTool {
private final BooleanProperty myEnableProperty;
private final StringProperty myToolProperty;
@@ -39,16 +46,9 @@ abstract class BaseExternalTool implements DiffTool {
myToolProperty = toolProperty;
}
public boolean canShow(DiffRequest request) {
AbstractProperty.AbstractPropertyContainer config = DiffManagerImpl.getInstanceEx().getProperties();
if (!myEnableProperty.value(config)) return false;
String path = getToolPath();
if (path == null || path.length() == 0) return false;
DiffContent[] contents = request.getContents();
if (contents.length != 2) return false;
if (externalize(request, 0) == null) return false;
if (externalize(request, 1) == null) return false;
return true;
public final boolean canShow(DiffRequest request) {
if (!isEnabled() || StringUtil.isEmpty(getToolPath())) return false;
return isAvailable(request);
}
@Override
@@ -56,18 +56,45 @@ abstract class BaseExternalTool implements DiffTool {
return null;
}
protected abstract ContentExternalizer externalize(DiffRequest request, int index);
public abstract boolean isAvailable(DiffRequest request);
private String getToolPath() {
return myToolProperty.get(DiffManagerImpl.getInstanceEx().getProperties());
@Nullable
protected ContentExternalizer externalize(final DiffRequest request, final int index) {
final VirtualFile file = getLocalFile(request.getContents()[index].getFile());
if (LocalFileExternalizer.canExternalizeAsFile(file)) {
return LocalFileExternalizer.tryCreate(file);
}
return new ExternalToolContentExternalizer(request, index);
}
public static AbstractProperty.AbstractPropertyContainer getProperties() {
return DiffManagerImpl.getInstanceEx().getProperties();
}
protected String getToolPath() {
return myToolProperty.get(getProperties());
}
protected boolean isEnabled() {
return myEnableProperty.value(getProperties());
}
protected List<String> getParameters(DiffRequest request) throws Exception {
final String p1 = convertToPath(request, 0);
final String p2 = convertToPath(request, 1);
final List<String> params = new ArrayList<String>();
if (p1 != null) params.add(p1);
if (p2 != null) params.add(p2);
return params;
}
public void show(DiffRequest request) {
GeneralCommandLine commandLine = new GeneralCommandLine();
commandLine.setExePath(getToolPath());
try {
commandLine.addParameter(convertToPath(request, 0));
commandLine.addParameter(convertToPath(request, 1));
commandLine.addParameters(getParameters(request));
commandLine.createProcess();
}
catch (Exception e) {
@@ -76,8 +103,10 @@ abstract class BaseExternalTool implements DiffTool {
}
}
private String convertToPath(DiffRequest request, int index) throws IOException {
return externalize(request, index).getContentFile().getAbsolutePath();
@Nullable
protected String convertToPath(DiffRequest request, int index) throws Exception {
final ContentExternalizer externalize = externalize(request, index);
return externalize == null ? null : externalize.getContentFile().getAbsolutePath();
}
@Nullable
@@ -85,27 +114,4 @@ abstract class BaseExternalTool implements DiffTool {
if (file != null && file.isInLocalFileSystem()) return file;
return null;
}
protected interface ContentExternalizer {
File getContentFile() throws IOException;
}
protected static class LocalFileExternalizer implements ContentExternalizer {
private final File myFile;
public LocalFileExternalizer(File file) {
myFile = file;
}
public File getContentFile() {
return myFile;
}
@Nullable
public static LocalFileExternalizer tryCreate(VirtualFile file) {
if (file == null || !file.isValid()) return null;
if (!file.isInLocalFileSystem()) return null;
return new LocalFileExternalizer(new File(file.getPath().replace('/', File.separatorChar)));
}
}
}
@@ -0,0 +1,26 @@
/*
* Copyright 2000-2012 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.openapi.diff.impl.external;
import java.io.File;
import java.io.IOException;
/**
* @author Konstantin Bulenkov
*/
interface ContentExternalizer {
File getContentFile() throws IOException;
}
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2011 JetBrains s.r.o.
* Copyright 2000-2012 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,10 +58,12 @@ public class DiffManagerImpl extends DiffManager implements JDOMExternalizable {
static final StringProperty FOLDERS_TOOL = new StringProperty("foldersTool", "");
static final StringProperty FILES_TOOL = new StringProperty("filesTool", "");
static final BooleanProperty ENABLE_FOLDERS = new BooleanProperty(
"enableFolders", false);
static final BooleanProperty ENABLE_FILES = new BooleanProperty(
"enableFiles", false);
static final StringProperty MERGE_TOOL = new StringProperty("mergeTool", "");
static final StringProperty MERGE_TOOL_PARAMETERS = new StringProperty("mergeToolParameters", "");
static final BooleanProperty ENABLE_FOLDERS = new BooleanProperty("enableFolders", false);
static final BooleanProperty ENABLE_FILES = new BooleanProperty("enableFiles", false);
static final BooleanProperty ENABLE_MERGE = new BooleanProperty("enableMerge", false);
private final ExternalizablePropertyContainer myProperties;
private final ArrayList<DiffTool> myAdditionTools = new ArrayList<DiffTool>();
@@ -89,7 +91,7 @@ public class DiffManagerImpl extends DiffManager implements JDOMExternalizable {
public DiffTool getDiffTool() {
DiffTool[] standardTools;
// there is inner check in multiple tool for external viewers as well
if (! ENABLE_FILES.value(myProperties) || ! ENABLE_FOLDERS.value(myProperties)) {
if (! ENABLE_FILES.value(myProperties) || ! ENABLE_FOLDERS.value(myProperties) || !ENABLE_MERGE.value(myProperties)) {
DiffTool[] embeddableTools = {
INTERNAL_DIFF,
new MergeTool(),
@@ -98,6 +100,7 @@ public class DiffManagerImpl extends DiffManager implements JDOMExternalizable {
standardTools = new DiffTool[]{
ExtCompareFolders.INSTANCE,
ExtCompareFiles.INSTANCE,
ExtMergeFiles.INSTANCE,
new MultiLevelDiffTool(Arrays.asList(embeddableTools)),
INTERNAL_DIFF,
new MergeTool(),
@@ -107,6 +110,7 @@ public class DiffManagerImpl extends DiffManager implements JDOMExternalizable {
standardTools = new DiffTool[]{
ExtCompareFolders.INSTANCE,
ExtCompareFiles.INSTANCE,
ExtMergeFiles.INSTANCE,
INTERNAL_DIFF,
new MergeTool(),
BinaryDiffTool.INSTANCE
@@ -1,9 +1,9 @@
<?xml version="1.0" encoding="UTF-8"?>
<form xmlns="http://www.intellij.com/uidesigner/form/" version="1" bind-to-class="com.intellij.openapi.diff.impl.external.DiffOptionsForm">
<grid id="6e6fb" binding="myPanel" layout-manager="GridLayoutManager" row-count="5" column-count="1" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="2">
<grid id="6e6fb" binding="myPanel" layout-manager="GridLayoutManager" row-count="6" column-count="1" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="2">
<margin top="0" left="0" bottom="0" right="0"/>
<constraints>
<xy x="7" y="76" width="563" height="151"/>
<xy x="7" y="76" width="1438" height="296"/>
</constraints>
<properties/>
<border type="none"/>
@@ -34,18 +34,6 @@
<properties/>
<border type="none"/>
<children>
<xy id="2fc3d" layout-manager="XYLayout" hgap="-1" vgap="-1">
<margin top="0" left="0" bottom="0" right="0"/>
<constraints>
<grid row="0" column="0" row-span="1" col-span="1" vsize-policy="3" hsize-policy="3" anchor="0" fill="3" indent="0" use-parent-layout="false">
<minimum-size width="16" height="-1"/>
<maximum-size width="16" height="-1"/>
</grid>
</constraints>
<properties/>
<border type="none"/>
<children/>
</xy>
<component id="89fa" class="com.intellij.openapi.ui.TextFieldWithBrowseButton" binding="myFoldersTool">
<constraints>
<grid row="0" column="1" row-span="1" col-span="1" vsize-policy="0" hsize-policy="7" anchor="8" fill="1" indent="0" use-parent-layout="false"/>
@@ -54,6 +42,14 @@
<text value=""/>
</properties>
</component>
<component id="3f6a3" class="javax.swing.JLabel">
<constraints>
<grid row="0" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="0" anchor="8" fill="0" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<text value="Path to executable:"/>
</properties>
</component>
</children>
</grid>
<grid id="10020" layout-manager="GridLayoutManager" row-count="1" column-count="2" same-size-horizontally="false" same-size-vertically="false" hgap="0" vgap="0">
@@ -64,18 +60,6 @@
<properties/>
<border type="none"/>
<children>
<xy id="11371" layout-manager="XYLayout" hgap="-1" vgap="-1">
<margin top="0" left="0" bottom="0" right="0"/>
<constraints>
<grid row="0" column="0" row-span="1" col-span="1" vsize-policy="3" hsize-policy="3" anchor="0" fill="3" indent="0" use-parent-layout="false">
<minimum-size width="16" height="-1"/>
<maximum-size width="16" height="-1"/>
</grid>
</constraints>
<properties/>
<border type="none"/>
<children/>
</xy>
<component id="553c9" class="com.intellij.openapi.ui.TextFieldWithBrowseButton" binding="myFilesTool">
<constraints>
<grid row="0" column="1" row-span="1" col-span="1" vsize-policy="0" hsize-policy="7" anchor="8" fill="1" indent="0" use-parent-layout="false"/>
@@ -84,13 +68,98 @@
<text value=""/>
</properties>
</component>
<component id="d82e9" class="javax.swing.JLabel">
<constraints>
<grid row="0" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="0" anchor="8" fill="0" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<text value="Path to executable:"/>
</properties>
</component>
</children>
</grid>
<vspacer id="dba7d">
<constraints>
<grid row="4" column="0" row-span="1" col-span="1" vsize-policy="6" hsize-policy="1" anchor="0" fill="2" indent="0" use-parent-layout="false"/>
<grid row="5" column="0" row-span="1" col-span="1" vsize-policy="6" hsize-policy="1" anchor="0" fill="2" indent="0" use-parent-layout="false"/>
</constraints>
</vspacer>
<grid id="2320a" layout-manager="GridLayoutManager" row-count="4" column-count="1" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1">
<margin top="0" left="0" bottom="0" right="0"/>
<constraints>
<grid row="4" column="0" row-span="1" col-span="1" vsize-policy="3" hsize-policy="3" anchor="0" fill="3" indent="0" use-parent-layout="false"/>
</constraints>
<properties/>
<clientProperties>
<BorderFactoryClass class="java.lang.String" value="com.intellij.ui.IdeBorderFactory"/>
</clientProperties>
<border type="none"/>
<children>
<grid id="fc396" binding="myMergePanel" layout-manager="GridLayoutManager" row-count="2" column-count="2" same-size-horizontally="false" same-size-vertically="false" hgap="0" vgap="0">
<margin top="0" left="0" bottom="0" right="0"/>
<constraints>
<grid row="1" column="0" row-span="1" col-span="1" vsize-policy="3" hsize-policy="3" anchor="0" fill="3" indent="0" use-parent-layout="false"/>
</constraints>
<properties/>
<border type="none"/>
<children>
<component id="437e3" class="com.intellij.openapi.ui.TextFieldWithBrowseButton" binding="myMergeTool">
<constraints>
<grid row="0" column="1" row-span="1" col-span="1" vsize-policy="0" hsize-policy="7" anchor="8" fill="1" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<text value=""/>
</properties>
</component>
<component id="15882" class="javax.swing.JLabel">
<constraints>
<grid row="0" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="0" anchor="8" fill="0" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<text value="Path to executable:"/>
</properties>
</component>
<component id="47dec" class="javax.swing.JLabel">
<constraints>
<grid row="1" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="0" anchor="8" fill="0" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<horizontalAlignment value="4"/>
<text value="Parameters:"/>
</properties>
</component>
<component id="1c9c8" class="javax.swing.JTextField" binding="myMergeParameters">
<constraints>
<grid row="1" column="1" row-span="1" col-span="1" vsize-policy="0" hsize-policy="6" anchor="8" fill="1" indent="0" use-parent-layout="false">
<preferred-size width="150" height="-1"/>
</grid>
</constraints>
<properties/>
</component>
</children>
</grid>
<vspacer id="4f578">
<constraints>
<grid row="3" column="0" row-span="1" col-span="1" vsize-policy="6" hsize-policy="1" anchor="0" fill="2" indent="0" use-parent-layout="false"/>
</constraints>
</vspacer>
<component id="8a36e" class="javax.swing.JCheckBox" binding="myEnableMerge">
<constraints>
<grid row="0" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="3" anchor="8" fill="0" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<text resource-bundle="messages/DiffBundle" key="diff.options.use.external.merge.tool.for.files.checkbox"/>
</properties>
</component>
<component id="64be3" class="javax.swing.JLabel" binding="myMergeParamInfo">
<constraints>
<grid row="2" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="0" anchor="8" fill="0" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<text value="&lt;html&gt;Different merge tools have different parameters. It's important to specify all necessary parameters in proper order&lt;br&gt;&#10;&lt;b&gt;%1&lt;/b&gt; - left (Local changes)&lt;br&gt;&#10;&lt;b&gt;%2&lt;/b&gt; - base (Current version without local changes)&lt;br&gt;&#10;&lt;b&gt;%3&lt;/b&gt; - right (Server content)&lt;br&gt;&#10;&lt;b&gt;%4&lt;/b&gt; - output path&lt;/html&gt;"/>
</properties>
</component>
</children>
</grid>
</children>
</grid>
</form>
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2009 JetBrains s.r.o.
* Copyright 2000-2012 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.
@@ -27,6 +27,7 @@ import com.intellij.util.config.StringProperty;
import com.intellij.util.ui.UIUtil;
import org.jetbrains.annotations.Nls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.awt.event.ActionEvent;
@@ -39,14 +40,27 @@ public class DiffOptionsForm implements SearchableConfigurable, Configurable.NoS
private JCheckBox myEnableFiles;
private TextFieldWithBrowseButton myFoldersTool;
private TextFieldWithBrowseButton myFilesTool;
private TextFieldWithBrowseButton myMergeTool;
private JCheckBox myEnableMerge;
private JTextField myMergeParameters;
private JLabel myMergeParamInfo;
private JPanel myMergePanel;
private final ToolPath[] myTools = new ToolPath[2];
private final ToolPath[] myTools = new ToolPath[3];
public DiffOptionsForm() {
myTools[0] = new ToolPath(myEnableFolders, myFoldersTool,
DiffManagerImpl.FOLDERS_TOOL, DiffManagerImpl.ENABLE_FOLDERS);
myTools[1] = new ToolPath(myEnableFiles, myFilesTool, DiffManagerImpl.FILES_TOOL,
DiffManagerImpl.ENABLE_FILES);
myEnableMerge.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
myMergeParameters.setEditable(myEnableMerge.isEnabled());
myMergeParameters.setEnabled(myEnableMerge.isEnabled());
}
});
myTools[0] = new ToolPath(myEnableFolders, myFoldersTool, null, DiffManagerImpl.FOLDERS_TOOL, DiffManagerImpl.ENABLE_FOLDERS, null);
myTools[1] = new ToolPath(myEnableFiles, myFilesTool, null, DiffManagerImpl.FILES_TOOL, DiffManagerImpl.ENABLE_FILES, null);
myTools[2] = new ToolPath(myEnableMerge, myMergeTool, myMergeParameters, DiffManagerImpl.MERGE_TOOL, DiffManagerImpl.ENABLE_MERGE, DiffManagerImpl.MERGE_TOOL_PARAMETERS);
myMergeParameters.setEditable(myEnableMerge.isEnabled());
myMergeParameters.setEnabled(myEnableMerge.isEnabled());
}
public JComponent createComponent() {
@@ -102,13 +116,17 @@ public class DiffOptionsForm implements SearchableConfigurable, Configurable.NoS
private final TextFieldWithBrowseButton myTextField;
private final StringProperty myPathProperty;
private final BooleanProperty myEnabledProperty;
@Nullable private final JTextField myParameters;
@Nullable private final StringProperty myParametersProperty;
public ToolPath(JCheckBox checkBox, TextFieldWithBrowseButton textField,
StringProperty pathProperty, BooleanProperty enabledProperty) {
public ToolPath(JCheckBox checkBox, TextFieldWithBrowseButton textField, @Nullable JTextField parameters,
StringProperty pathProperty, BooleanProperty enabledProperty, @Nullable StringProperty parametersProperty) {
myCheckBox = checkBox;
myTextField = textField;
myPathProperty = pathProperty;
myEnabledProperty = enabledProperty;
myParameters = parameters;
myParametersProperty = parametersProperty;
final ButtonModel model = myCheckBox.getModel();
model.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
@@ -126,8 +144,9 @@ public class DiffOptionsForm implements SearchableConfigurable, Configurable.NoS
public boolean isModifier() {
AbstractProperty.AbstractPropertyContainer properties = getProperties();
return !myTextField.getText().equals(myPathProperty.get(properties)) ||
isEnabled() != myEnabledProperty.value(properties);
return !myTextField.getText().equals(myPathProperty.get(properties))
|| isEnabled() != myEnabledProperty.value(properties)
|| (myParametersProperty != null && myParameters != null && !myParameters.getText().equals(myParametersProperty.get(properties)));
}
private boolean isEnabled() {
@@ -141,11 +160,17 @@ public class DiffOptionsForm implements SearchableConfigurable, Configurable.NoS
public void apply() {
myPathProperty.set(getProperties(), myTextField.getText());
myEnabledProperty.primSet(getProperties(), isEnabled());
if (myParameters != null && myParametersProperty != null) {
myParametersProperty.set(getProperties(), myParameters.getText());
}
}
public void reset() {
myTextField.setText(myPathProperty.get(getProperties()));
myCheckBox.getModel().setSelected(myEnabledProperty.value(getProperties()));
if (myParameters != null && myParametersProperty != null) {
myParameters.setText(myParametersProperty.get(getProperties()));
}
updateEnabledEffect();
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2009 JetBrains s.r.o.
* Copyright 2000-2012 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.
@@ -18,105 +18,37 @@ package com.intellij.openapi.diff.impl.external;
import com.intellij.openapi.diff.DiffContent;
import com.intellij.openapi.diff.DiffRequest;
import com.intellij.openapi.diff.impl.DiffUtil;
import com.intellij.openapi.fileTypes.FileType;
import com.intellij.openapi.fileTypes.FileTypes;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.vfs.VirtualFile;
import org.jetbrains.annotations.NonNls;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
/**
* @author Konstantin Bulenkov
*/
class ExtCompareFiles extends BaseExternalTool {
public static final BaseExternalTool INSTANCE = new ExtCompareFiles();
private ExtCompareFiles() {
super(DiffManagerImpl.ENABLE_FILES, DiffManagerImpl.FILES_TOOL);
}
public boolean canShow(DiffRequest request) {
DiffContent[] contents = request.getContents();
for (int i = 0; i < contents.length; i++) {
DiffContent content = contents[i];
VirtualFile file = getLocalFile(content.getFile());
if (file != null && file.isDirectory()) return false;
if (canExternalizeAsFile(file)) continue;
if (DiffUtil.isWritable(content)) return false;
public boolean isAvailable(DiffRequest request) {
final DiffContent[] contents = request.getContents();
for (DiffContent content : contents) {
final VirtualFile file = getLocalFile(content.getFile());
if (file != null && file.isDirectory()) {
return false;
}
if (LocalFileExternalizer.canExternalizeAsFile(file)) {
continue;
}
if (DiffUtil.isWritable(content)) {
return false;
}
}
return super.canShow(request);
}
protected BaseExternalTool.ContentExternalizer externalize(final DiffRequest request, final int index) {
VirtualFile file = getLocalFile(request.getContents()[index].getFile());
if (canExternalizeAsFile(file)) return LocalFileExternalizer.tryCreate(file);
return new MyContentExternalizer(request, index);
}
private boolean canExternalizeAsFile(VirtualFile file) {
if (file == null || file.isDirectory()) return false;
FileType fileType = file.getFileType();
if (fileType.isBinary() && fileType != FileTypes.UNKNOWN) return false;
if (contents.length != 2) return false;
if (externalize(request, 0) == null) return false;
if (externalize(request, 1) == null) return false;
return true;
}
private static class MyContentExternalizer implements BaseExternalTool.ContentExternalizer {
private final DiffRequest myRequest;
private final int myIndex;
@NonNls public static final String STD_PREFIX = "IJDiff";
public MyContentExternalizer(DiffRequest request, int index) {
myRequest = request;
myIndex = index;
}
public File getContentFile() throws IOException {
String extension = chooseExtension();
String name = chooseName();
if (name.length() <= 3) name = "___" + name;
File tempFile;
try {
tempFile = FileUtil.createTempFile(name, extension);
}
catch (IOException e) {
tempFile = FileUtil.createTempFile(STD_PREFIX, extension);
}
FileOutputStream stream = null;
try {
stream = new FileOutputStream(tempFile);
stream.write(getContent().getBytes());
} finally {
if (stream != null) stream.close();
}
return tempFile;
}
private String chooseName() {
String title = myRequest.getContentTitles()[myIndex];
char[] chars = title.toCharArray();
for (int i = 0; i < chars.length; i++) {
char aChar = chars[i];
if (!Character.isLetterOrDigit(aChar)) chars[i] = '_';
}
return new String(chars);
}
private String chooseExtension() {
DiffContent content = getContent();
VirtualFile contentFile = content.getFile();
String extension;
if (contentFile != null) {
extension = "." + contentFile.getExtension();
}
else {
FileType contentType = content.getContentType();
if (contentType == null) contentType = DiffUtil.chooseContentTypes(myRequest.getContents())[myIndex];
extension = contentType != null ? "." + contentType.getDefaultExtension() : null;
}
return extension;
}
private DiffContent getContent() {
return myRequest.getContents()[myIndex];
}
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2009 JetBrains s.r.o.
* Copyright 2000-2012 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -15,24 +15,43 @@
*/
package com.intellij.openapi.diff.impl.external;
import com.intellij.openapi.diff.DiffContent;
import com.intellij.openapi.diff.DiffRequest;
import com.intellij.openapi.vfs.VirtualFile;
import org.jetbrains.annotations.Nullable;
/**
* @author Konstantin Bulenkov
*/
class ExtCompareFolders extends BaseExternalTool {
public static final BaseExternalTool INSTANCE = new ExtCompareFolders();
private ExtCompareFolders() {
super(DiffManagerImpl.ENABLE_FOLDERS, DiffManagerImpl.FOLDERS_TOOL);
}
protected BaseExternalTool.ContentExternalizer externalize(DiffRequest request, int index) {
VirtualFile file = request.getContents()[index].getFile();
if (!isLocalDirectory(file)) return null;
@Override
public boolean isAvailable(DiffRequest request) {
final DiffContent[] contents = request.getContents();
if (contents.length != 2) return false;
if (externalize(request, 0) == null) return false;
if (externalize(request, 1) == null) return false;
return true;
}
@Nullable
protected ContentExternalizer externalize(DiffRequest request, int index) {
final VirtualFile file = request.getContents()[index].getFile();
if (!isLocalDirectory(file)) {
return null;
}
return LocalFileExternalizer.tryCreate(file);
}
private boolean isLocalDirectory(VirtualFile file) {
file = getLocalFile(file);
return file != null && file.isDirectory();
private static boolean isLocalDirectory(VirtualFile file) {
final VirtualFile local = getLocalFile(file);
return local != null && local.isDirectory();
}
}
@@ -0,0 +1,63 @@
/*
* Copyright 2000-2012 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.openapi.diff.impl.external;
import com.intellij.openapi.diff.DiffContent;
import com.intellij.openapi.diff.DiffRequest;
import com.intellij.openapi.diff.impl.mergeTool.MergeRequestImpl;
import com.intellij.openapi.util.text.StringUtil;
import java.util.ArrayList;
import java.util.List;
/**
* @author Konstantin Bulenkov
*/
public class ExtMergeFiles extends BaseExternalTool {
public static final ExtMergeFiles INSTANCE = new ExtMergeFiles();
protected ExtMergeFiles() {
super(DiffManagerImpl.ENABLE_MERGE, DiffManagerImpl.MERGE_TOOL);
}
@Override
public boolean isAvailable(DiffRequest request) {
DiffContent[] contents = request.getContents();
if (contents.length != 3) return false;
if (externalize(request, 0) == null) return false;
if (externalize(request, 1) == null) return false;
if (externalize(request, 2) == null) return false;
return true;
}
@Override
protected List<String> getParameters(DiffRequest request) throws Exception {
final List<String> params = new ArrayList<String>();
String result = ((MergeRequestImpl)request).getResultContent().getFile().getPath();
String left = externalize(request, 0).getContentFile().getPath();
String base = new ExternalToolContentExternalizer(request, 1).getContentFile().getPath();
String right = externalize(request, 2).getContentFile().getPath();
for (String param : StringUtil.split(DiffManagerImpl.MERGE_TOOL_PARAMETERS.get(getProperties()), " ")) {
if ("%1".equals(param)) params.add(left);
else if ("%2".equals(param)) params.add(base);
else if ("%3".equals(param)) params.add(right);
else if ("%4".equals(param)) params.add(result);
else params.add(param);
}
return params;
}
}
@@ -0,0 +1,94 @@
/*
* Copyright 2000-2012 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.openapi.diff.impl.external;
import com.intellij.openapi.diff.DiffContent;
import com.intellij.openapi.diff.DiffRequest;
import com.intellij.openapi.diff.MergeRequest;
import com.intellij.openapi.diff.impl.DiffUtil;
import com.intellij.openapi.fileTypes.FileType;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.vfs.VirtualFile;
import org.jetbrains.annotations.NonNls;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
/**
* @author Konstantin Bulenkov
*/
class ExternalToolContentExternalizer implements ContentExternalizer {
private final DiffRequest myRequest;
private final int myIndex;
@NonNls public static final String STD_PREFIX = "IJDiff";
public ExternalToolContentExternalizer(DiffRequest request, int index) {
myRequest = request;
myIndex = index;
}
public File getContentFile() throws IOException {
String extension = chooseExtension();
String name = chooseName();
if (name.length() <= 3) name = "___" + name;
File tempFile;
try {
tempFile = FileUtil.createTempFile(name, extension);
}
catch (IOException e) {
tempFile = FileUtil.createTempFile(STD_PREFIX, extension);
}
FileOutputStream stream = null;
try {
stream = new FileOutputStream(tempFile);
final DiffContent content = getContent();
stream.write(myRequest instanceof MergeRequest ? content.getDocument().getText().getBytes() : content.getBytes());
} finally {
if (stream != null) stream.close();
}
return tempFile;
}
private String chooseName() {
String title = myRequest.getContentTitles()[myIndex];
char[] chars = title.toCharArray();
for (int i = 0; i < chars.length; i++) {
char aChar = chars[i];
if (!Character.isLetterOrDigit(aChar)) chars[i] = '_';
}
return new String(chars);
}
private String chooseExtension() {
DiffContent content = getContent();
VirtualFile contentFile = content.getFile();
String extension;
if (contentFile != null) {
extension = "." + contentFile.getExtension();
}
else {
FileType contentType = content.getContentType();
if (contentType == null) contentType = DiffUtil.chooseContentTypes(myRequest.getContents())[myIndex];
extension = contentType != null ? "." + contentType.getDefaultExtension() : null;
}
return extension;
}
private DiffContent getContent() {
return myRequest.getContents()[myIndex];
}
}
@@ -0,0 +1,52 @@
/*
* Copyright 2000-2012 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.openapi.diff.impl.external;
import com.intellij.openapi.fileTypes.FileType;
import com.intellij.openapi.fileTypes.FileTypes;
import com.intellij.openapi.vfs.VirtualFile;
import org.jetbrains.annotations.Nullable;
import java.io.File;
/**
* @author Konstantin Bulenkov
*/
class LocalFileExternalizer implements ContentExternalizer {
private final File myFile;
public LocalFileExternalizer(File file) {
myFile = file;
}
public File getContentFile() {
return myFile;
}
@Nullable
public static LocalFileExternalizer tryCreate(VirtualFile file) {
if (file == null || !file.isValid()) return null;
if (!file.isInLocalFileSystem()) return null;
return new LocalFileExternalizer(new File(file.getPath().replace('/', File.separatorChar)));
}
static boolean canExternalizeAsFile(VirtualFile file) {
if (file == null || file.isDirectory()) return false;
FileType fileType = file.getFileType();
if (fileType.isBinary() && fileType != FileTypes.UNKNOWN) return false;
return true;
}
}
@@ -104,7 +104,7 @@ public interface MergeVersion {
}
public static void reportProjectFileChangeIfNeeded(Project project, VirtualFile file) {
if (file != null) {
if (file != null && ! file.isDirectory()) {
if (ProjectUtil.isProjectOrWorkspaceFile(file) || isProjectFile(file)) {
ProjectManagerEx.getInstanceEx().saveChangedProjectFile(file, project);
}
@@ -115,7 +115,7 @@ public interface MergeVersion {
public static Runnable prepareToReportChangedProjectFiles(final Project project, final Collection<VirtualFile> files) {
final Set<VirtualFile> vfs = new HashSet<VirtualFile>();
for (VirtualFile vf : files) {
if (vf != null) {
if (vf != null && ! vf.isDirectory()) {
if (ProjectUtil.isProjectOrWorkspaceFile(vf) || isProjectFile(vf)) {
vfs.add(vf);
}
@@ -48,6 +48,7 @@ files.are.different.dialog.title=Files Are Different
diff.options.diff.options.border=Diff Options
diff.options.use.external.tool.for.files.checkbox=Use external tool to compare files:
diff.options.use.external.tool.for.directories.checkbox=Use external tool to compare folders:
diff.options.use.external.merge.tool.for.files.checkbox=Use external merge tool:
select.external.diff.program.dialog.title=Select External Diff Program
diff.contents.are.identical.message.text=Contents are identical
diff.contents.have.differences.only.in.line.separators.message.text=Contents have differences only in line separators
@@ -540,6 +540,8 @@
<action id="DirDiffMenu.SetCopyToRight" class="com.intellij.openapi.diff.impl.dir.actions.popup.SetCopyToRight" text="Set Copy to Right" icon="/vcs/arrow_right.png"/>
<action id="DirDiffMenu.SetCopyToLeft" class="com.intellij.openapi.diff.impl.dir.actions.popup.SetCopyToLeft" text="Set Copy to Left" icon="/vcs/arrow_left.png"/>
<action id="DirDiffMenu.SetDelete" class="com.intellij.openapi.diff.impl.dir.actions.popup.SetDelete" text="Set Delete" icon="/vcs/remove.png"/>
<action id="DirDiffMenu.SetNoOperation" class="com.intellij.openapi.diff.impl.dir.actions.popup.SetNoOperation" text="Set Do Nothing"/>
<separator/>
<action id="DirDiffMenu.SetDefault" class="com.intellij.openapi.diff.impl.dir.actions.popup.SetDefault" text="Set Default"/>
</group>
@@ -3,13 +3,20 @@
*/
package com.intellij.psi.tree;
import com.intellij.lang.Language;
import com.intellij.lang.LanguageExtensionPoint;
import com.intellij.lang.ParserDefinition;
import com.intellij.lang.PsiParser;
import com.intellij.lexer.Lexer;
import com.intellij.openapi.extensions.ExtensionPointName;
import com.intellij.openapi.extensions.Extensions;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.testFramework.fixtures.LightPlatformCodeInsightFixtureTestCase;
import gnu.trove.THashMap;
import gnu.trove.TObjectIntHashMap;
import java.util.Arrays;
import java.util.Comparator;
/**
* @author gregsh
@@ -20,28 +27,74 @@ public class IElementTypeTest extends LightPlatformCodeInsightFixtureTestCase {
@SuppressWarnings("UnusedDeclaration")
public void testCount() throws Exception {
int count = IElementType.getAllocatedTypesCount();
System.out.println("Before: " + count +" types");
System.out.println("Preloaded: " + count +" element types");
LanguageExtensionPoint[] extensions = Extensions.getExtensions(new ExtensionPointName<LanguageExtensionPoint>("com.intellij.lang.parserDefinition"));
System.out.println(extensions.length +" definitions");
System.out.println("ParserDefinitions: " + extensions.length);
THashMap<Language, String> languageMap = new THashMap<Language, String>();
languageMap.put(Language.ANY, "platform");
final TObjectIntHashMap<String> map = new TObjectIntHashMap<String>();
for (LanguageExtensionPoint e : extensions) {
String key = e.getPluginDescriptor().getPluginId().getIdString();
int curCount = IElementType.getAllocatedTypesCount();
ParserDefinition definition = (ParserDefinition)e.getInstance();
IFileElementType type = definition.getFileNodeType();
Language language = type.getLanguage();
languageMap.put(language, key);
if (language.getBaseLanguage() != null && !languageMap.containsKey(language.getBaseLanguage())) {
languageMap.put(language.getBaseLanguage(), key);
}
try {
IFileElementType type = definition.getFileNodeType();
Lexer lexer = definition.createLexer(getProject());
PsiParser parser = definition.createParser(getProject());
}
catch (UnsupportedOperationException e1) {
}
// language-based calculation: per-class-loading stuff commented
//int diff = IElementType.getAllocatedTypesCount() - curCount;
//map.put(key, map.get(key) + diff);
}
System.out.println("After: " + IElementType.getAllocatedTypesCount() +" types");
// language-based calculation
count = IElementType.getAllocatedTypesCount();
for (short i = 0; i < count; i ++ ) {
IElementType type = IElementType.find(i);
Language language = type.getLanguage();
String key = null;
for (Language cur = language; cur != null && key == null; cur = cur.getBaseLanguage()) {
key = languageMap.get(cur);
}
key = StringUtil.notNullize(key, "unknown");
map.put(key, map.get(key) + 1);
//if (key.equals("unknown")) System.out.println(type +" " + language);
}
System.out.println("Total: " + IElementType.getAllocatedTypesCount() +" element types");
// Show per-plugin statistics
Object[] keys = map.keys();
Arrays.sort(keys, new Comparator<Object>() {
@Override
public int compare(Object o1, Object o2) {
return map.get((String)o2) - map.get((String)o1);
}
});
int sum = 0;
for (Object key : keys) {
int value = map.get((String)key);
if (value == 0) continue;
sum += value;
System.out.println(" " + key + ": " + value);
}
// leave some index-space for plugin developers
assertTrue(IElementType.getAllocatedTypesCount() < 10000);
assertEquals(IElementType.getAllocatedTypesCount(), sum);
// output on 11.05.2012
// Before: 3485 types
// Preloaded: 3485 types
// 95 definitions
// After: 7694 types
// Total: 7694 types
}
}
@@ -790,4 +790,25 @@ public abstract class PlatformTestCase extends UsefulTestCase implements DataPro
}
}.execute().throwException().getResultObject();
}
protected static void delete(@NotNull final VirtualFile file) {
ApplicationManager.getApplication().runWriteAction(new Runnable() {
@Override
public void run() {
try {
file.delete(null);
}
catch (IOException e) {
fail();
}
}
});
}
protected static void rename(@NotNull final VirtualFile vFile1, @NotNull final String newName) {
new WriteCommandAction.Simple(null) {
@Override
protected void run() throws Throwable {
vFile1.rename(this, newName);
}
}.execute().throwException();
}
}
@@ -436,6 +436,10 @@ public class FileUtil extends FileUtilRt {
ioException.initCause(e);
throw ioException;
}
else if (SystemInfo.isWindows && e.getMessage() != null && e.getMessage().contains("denied") &&
WinUACTemporaryFix.nativeCopy(fromFile, toFile, syncTimestamp)) {
return;
}
createParentDirs(toFile);
fos = new FileOutputStream(toFile);
}
@@ -0,0 +1,106 @@
/*
* Copyright 2000-2012 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.openapi.util.io;
import com.intellij.openapi.application.PathManager;
import java.io.*;
/**
* @author gregsh
*/
class WinUACTemporaryFix {
public static void main(String[] args) throws Exception {
String command = args[0];
if ("copy".equals(command)) {
File fromFile = new File(args[1]);
File toFile = new File(args[2]);
boolean syncTimestamp = Boolean.parseBoolean(args[3]);
boolean result = execExternalProcess(new String[]{"cmd.exe", "/C", "copy", fromFile.getPath(), toFile.getPath()});
if (result && syncTimestamp && toFile.exists()) {
long lastModified = fromFile.lastModified();
if (lastModified >= 0) {
toFile.setLastModified(lastModified);
}
}
System.exit(result ? 0 : 1);
}
}
private static boolean execExternalProcess(String[] args) throws IOException, InterruptedException {
Process process = Runtime.getRuntime().exec(args);
Thread outThread = new Thread(new StreamRedirector(process.getInputStream(), System.out));
Thread errThread = new Thread(new StreamRedirector(process.getErrorStream(), System.err));
outThread.start();
errThread.start();
try {
process.waitFor();
}
finally {
outThread.join();
errThread.join();
}
return process.exitValue() == 0;
}
static boolean nativeCopy(File fromFile, File toFile, boolean syncTimestamp) {
File launcherFile = new File(PathManager.getBinPath(), "vistalauncher.exe");
try {
// todo vistalauncher should be replaced with generic "elevate" process
// todo so the second java process will be unnecessary: plain 'elevate cmd /C copy' will work
return execExternalProcess(new String[]{launcherFile.getPath(),
//"cmd", "/C", "move", fromFile.getPath(),
//toFile.getPath()
System.getProperty("java.home") + "/bin/java",
"-classpath",
PathManager.getLibPath() + "/util.jar",
WinUACTemporaryFix.class.getName(),
"copy",
fromFile.getPath(),
toFile.getPath(),
String.valueOf(syncTimestamp),
// vistalauncher hack
"install",
toFile.getParent()
});
}
catch (Exception ex) {
return false;
}
}
static class StreamRedirector implements Runnable {
private final InputStream myIn;
private final OutputStream myOut;
private StreamRedirector(InputStream in, OutputStream out) {
myIn = in;
myOut = out;
}
public void run() {
try {
StreamUtil.copyStreamContent(myIn, myOut);
}
catch (IOException e) {
e.printStackTrace();
}
}
}
}
@@ -16,6 +16,7 @@
package com.intellij.openapi.diff.impl.dir;
import com.intellij.ide.diff.DiffElement;
import com.intellij.ide.diff.DirDiffSettings;
import com.intellij.util.text.DateFormatUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
@@ -39,7 +40,8 @@ public class DirDiffElement {
private DirDiffOperation myDefaultOperation;
private DTree myNode;
private DirDiffElement(DTree parent, @Nullable DiffElement source, @Nullable DiffElement target, DType type, String name) {
private DirDiffElement(DTree parent, @Nullable DiffElement source, @Nullable DiffElement target, DType type, String name,
@Nullable DirDiffOperation defaultOperation) {
myParent = parent.getParent();
myNode = parent;
myType = type;
@@ -48,7 +50,10 @@ public class DirDiffElement {
myTarget = target;
myTargetLength = target == null || target.isContainer() ? -1 : target.getSize();
myName = name;
if (type == DType.ERROR) {
if(defaultOperation != null){
myDefaultOperation = defaultOperation;
}
else if (type == DType.ERROR) {
myDefaultOperation = NONE;
}
else if (isSource()) {
@@ -87,28 +92,41 @@ public class DirDiffElement {
return timeStamp < 0 ? "" : DateFormatUtil.formatDateTime(timeStamp);
}
public static DirDiffElement createChange(DTree parent, @NotNull DiffElement source, @NotNull DiffElement target) {
return new DirDiffElement(parent, source, target, DType.CHANGED, source.getName());
public static DirDiffElement createChange(DTree parent,
@NotNull DiffElement source,
@NotNull DiffElement target,
@Nullable DirDiffSettings.CustomSourceChooser customSourceChooser) {
DirDiffOperation defaultOperation = null;
if (customSourceChooser != null) {
DiffElement chosenSource = customSourceChooser.chooseSource(source, target);
if (chosenSource == source) { // chosenSource might be null
defaultOperation = COPY_TO;
}
else if (chosenSource == target) {
defaultOperation = COPY_FROM;
}
}
return new DirDiffElement(parent, source, target, DType.CHANGED, source.getName(), defaultOperation);
}
public static DirDiffElement createError(DTree parent, @Nullable DiffElement source, @Nullable DiffElement target) {
return new DirDiffElement(parent, source, target, DType.ERROR, source == null ? target.getName() : source.getName());
return new DirDiffElement(parent, source, target, DType.ERROR, source == null ? target.getName() : source.getName(), null);
}
public static DirDiffElement createSourceOnly(DTree parent, @NotNull DiffElement source) {
return new DirDiffElement(parent, source, null, DType.SOURCE, null);
return new DirDiffElement(parent, source, null, DType.SOURCE, null, null);
}
public static DirDiffElement createTargetOnly(DTree parent, @NotNull DiffElement target) {
return new DirDiffElement(parent, null, target, DType.TARGET, null);
return new DirDiffElement(parent, null, target, DType.TARGET, null, null);
}
public static DirDiffElement createDirElement(DTree parent, DiffElement src, DiffElement trg, String name) {
return new DirDiffElement(parent, src, trg, DType.SEPARATOR, name);
return new DirDiffElement(parent, src, trg, DType.SEPARATOR, name, null);
}
public static DirDiffElement createEqual(DTree parent, @NotNull DiffElement source, @NotNull DiffElement target) {
return new DirDiffElement(parent, source, target, DType.EQUAL, source.getName());
return new DirDiffElement(parent, source, target, DType.EQUAL, source.getName(), null);
}
public DType getType() {
@@ -323,7 +323,7 @@ public class DirDiffTableModel extends AbstractTableModel implements DirDiffMode
elements.add(DirDiffElement.createTargetOnly(child, child.getTarget()));
break;
case CHANGED:
elements.add(DirDiffElement.createChange(child, child.getSource(), child.getTarget()));
elements.add(DirDiffElement.createChange(child, child.getSource(), child.getTarget(), mySettings.customSourceChooser));
break;
case EQUAL:
elements.add(DirDiffElement.createEqual(child, child.getSource(), child.getTarget()));
@@ -0,0 +1,56 @@
/*
* Copyright 2000-2012 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.openapi.diff.impl.dir.actions.popup;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.diff.impl.dir.DirDiffElement;
import com.intellij.openapi.diff.impl.dir.DirDiffOperation;
import com.intellij.openapi.diff.impl.dir.DirDiffTableModel;
import javax.swing.*;
/**
* @author lene
* Date: 23.04.12
*/
public class SetNoOperation extends AnAction {
@Override
public void actionPerformed(AnActionEvent e) {
final DirDiffTableModel model = SetOperationToBase.getModel(e);
final JTable table = SetOperationToBase.getTable(e);
assert model != null && table != null;
for (DirDiffElement element : model.getSelectedElements()) {
element.setOperation(DirDiffOperation.NONE);
}
table.repaint();
}
@Override
public final void update(AnActionEvent e) {
final DirDiffTableModel model = SetOperationToBase.getModel(e);
final JTable table = SetOperationToBase.getTable(e);
if (table != null && model != null) {
for (DirDiffElement element : model.getSelectedElements()) {
if (element.getOperation() != DirDiffOperation.NONE) {
e.getPresentation().setEnabled(true);
return;
}
}
}
e.getPresentation().setEnabled(false);
}
}
@@ -68,7 +68,7 @@ public abstract class SetOperationToBase extends AnAction {
protected abstract boolean isEnabledFor(DirDiffElement element);
@Nullable
private static JTable getTable(AnActionEvent e) {
static JTable getTable(AnActionEvent e) {
return e.getData(DirDiffPanel.DIR_DIFF_TABLE);
}
@@ -15,19 +15,20 @@
*/
package com.intellij.openapi.vcs.update;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.vcs.VcsBundle;
import com.intellij.openapi.vcs.changes.Change;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.vfs.newvfs.NewVirtualFile;
import com.intellij.util.concurrency.Semaphore;
import gnu.trove.THashSet;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.File;
import java.util.Collection;
import java.util.List;
public class RefreshVFsSynchronously {
@@ -35,30 +36,28 @@ public class RefreshVFsSynchronously {
}
public static void updateAllChanged(final UpdatedFiles updatedFiles) {
// approx so ok
final ProgressIndicator progressIndicator = ProgressManager.getInstance().getProgressIndicator();
if (progressIndicator != null) {
progressIndicator.setIndeterminate(false);
}
final int num = getFilesNum(updatedFiles);
FilesToRefreshCollector callback = new FilesToRefreshCollector();
UpdateFilesHelper.iterateFileGroupFilesDeletedOnServerFirst(updatedFiles, callback);
wrapIntoLock(new Runnable() {
public void run() {
UpdateFilesHelper.iterateFileGroupFilesDeletedOnServerFirst(updatedFiles, new MyRefreshCallback(num, progressIndicator));
}
});
}
private static int getFilesNum(final UpdatedFiles files) {
int result = 0;
for (FileGroup group : files.getTopLevelGroups()) {
result += group.getImmediateFilesSize();
final List<FileGroup> children = group.getChildren();
for (FileGroup child : children) {
result += child.getImmediateFilesSize();
}
for (File file : callback.getToRefreshDeletedOrReplaced()) {
refreshDeletedOrReplaced(file);
}
return result;
final Semaphore semaphore = new Semaphore();
semaphore.down();
try {
LocalFileSystem.getInstance().refreshIoFiles(callback.getToRefresh(), true, false, new Runnable() {
@Override
public void run() {
semaphore.up();
}
});
}
catch (Throwable t) {
semaphore.up();
throw new RuntimeException(t);
}
semaphore.waitFor();
}
@Nullable
@@ -191,54 +190,30 @@ public class RefreshVFsSynchronously {
boolean movedOrRenamedOrReplaced(final Change change);
}
private static void wrapIntoLock(final Runnable runnable) {
final ProgressIndicator indicator = ProgressManager.getInstance().getProgressIndicator();
if (indicator != null) {
indicator.startNonCancelableSection();
indicator.setText(VcsBundle.message("progress.text.synchronizing.files"));
indicator.setText2("");
}
final Semaphore semaphore = new Semaphore();
semaphore.down();
ApplicationManager.getApplication().invokeLater(new Runnable() {
public void run() {
try {
// common lock for all refreshes inside
runnable.run();
}
finally {
semaphore.up();
}
}
});
semaphore.waitFor();
}
private static class MyRefreshCallback implements UpdateFilesHelper.Callback {
private int myCnt;
private final double myTotal;
private final ProgressIndicator myProgressIndicator;
private MyRefreshCallback(final int total, final ProgressIndicator progressIndicator) {
myTotal = total;
myProgressIndicator = progressIndicator;
myCnt = 0;
}
private static class FilesToRefreshCollector implements UpdateFilesHelper.Callback {
private final Collection<File> myToRefresh = new THashSet<File>();
private final Collection<File> myToRefreshDeletedOrReplaced = new THashSet<File>();
@Override
public void onFile(String filePath, String groupId) {
final File file = new File(filePath);
if (FileGroup.REMOVED_FROM_REPOSITORY_ID.equals(groupId)) {
refreshDeletedOrReplaced(file);
} else {
refresh(file);
myToRefreshDeletedOrReplaced.add(file);
}
if (myProgressIndicator != null) {
++ myCnt;
myProgressIndicator.setFraction(myCnt/myTotal);
myProgressIndicator.setText2("Refreshing " + filePath);
else {
myToRefresh.add(file);
}
}
@NotNull
public Collection<File> getToRefresh() {
return myToRefresh;
}
@NotNull
public Collection<File> getToRefreshDeletedOrReplaced() {
return myToRefreshDeletedOrReplaced;
}
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2009 JetBrains s.r.o.
* Copyright 2000-2012 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.
@@ -202,7 +202,7 @@ public class JavaLanguageInjectionSupport extends AbstractLanguageInjectionSuppo
static boolean doAddLanguageAnnotation(final Project project, final PsiModifierListOwner modifierListOwner,
final String languageId) {
if (modifierListOwner.getModifierList() == null || !PsiUtil.getLanguageLevel(modifierListOwner).hasEnumKeywordAndAutoboxing()) return false;
if (modifierListOwner.getModifierList() == null || !PsiUtil.isLanguageLevel5OrHigher(modifierListOwner)) return false;
if (!OrderEntryFix.ensureAnnotationsJarInPath(ModuleUtil.findModuleForPsiElement(modifierListOwner), AnnotationUtil.LANGUAGE)) return false;
new WriteCommandAction(project, modifierListOwner.getContainingFile()) {
protected void run(final Result result) throws Throwable {
@@ -30,8 +30,5 @@ public class LanguageInjectionConfigBean extends AbstractExtensionPointBean {
return myConfigUrl;
}
public PluginDescriptor getPluginDescriptor() {
return myPluginDescriptor;
}
}
@@ -111,15 +111,19 @@ public abstract class UpdatePsiFileCopyright extends AbstractUpdateCopyright {
protected void checkComments(PsiElement last, boolean commentHere, List<PsiComment> comments) {
try {
LinkedHashSet<CommentRange> found = new LinkedHashSet<CommentRange>();
Pattern pattern = Pattern.compile(myOptions.getKeyword(), Pattern.CASE_INSENSITIVE);
Document doc = FileDocumentManager.getInstance().getDocument(getFile().getVirtualFile());
for (int i = 0; i < comments.size(); i++) {
PsiComment comment = comments.get(i);
String text = comment.getText();
Matcher match = pattern.matcher(text);
if (match.find()) {
found.add(getLineCopyrightComments(comments, doc, i, comment));
final String keyword = myOptions.getKeyword();
final LinkedHashSet<CommentRange> found = new LinkedHashSet<CommentRange>();
Document doc = null;
if (!StringUtil.isEmpty(keyword)) {
Pattern pattern = Pattern.compile(keyword, Pattern.CASE_INSENSITIVE);
doc = FileDocumentManager.getInstance().getDocument(getFile().getVirtualFile());
for (int i = 0; i < comments.size(); i++) {
PsiComment comment = comments.get(i);
String text = comment.getText();
Matcher match = pattern.matcher(text);
if (match.find()) {
found.add(getLineCopyrightComments(comments, doc, i, comment));
}
}
}
+19 -2
View File
@@ -698,7 +698,7 @@ public class GitUtil {
}
@NotNull
public static Collection<VirtualFile> getRoots(@NotNull Collection<GitRepository> repositories) {
public static Collection<VirtualFile> getRootsFromRepositories(@NotNull Collection<GitRepository> repositories) {
Collection<VirtualFile> roots = new ArrayList<VirtualFile>(repositories.size());
for (GitRepository repository : repositories) {
roots.add(repository.getRoot());
@@ -706,6 +706,22 @@ public class GitUtil {
return roots;
}
@NotNull
public static Collection<GitRepository> getRepositoriesFromRoots(@NotNull GitRepositoryManager repositoryManager,
@NotNull Collection<VirtualFile> roots) {
Collection<GitRepository> repositories = new ArrayList<GitRepository>(roots.size());
for (VirtualFile root : roots) {
GitRepository repo = repositoryManager.getRepositoryForRoot(root);
if (repo == null) {
LOG.error("Repository not found for root " + root);
}
else {
repositories.add(repo);
}
}
return repositories;
}
/**
* Returns absolute paths which have changed remotely comparing to the current branch, i.e. performs
* <code>git diff --name-only master..origin/master</code>
@@ -719,6 +735,7 @@ public class GitUtil {
diff.setNoSSH(true);
diff.setStdoutSuppressed(true);
diff.setStderrSuppressed(true);
diff.setSilent(true);
final String output = diff.run();
final Collection<String> remoteChanges = new HashSet<String>();
@@ -763,7 +780,7 @@ public class GitUtil {
return affectedChanges;
}
@Nullable
@NotNull
public static GitRepositoryManager getRepositoryManager(@NotNull Project project) {
return ServiceManager.getService(project, GitRepositoryManager.class);
}
@@ -20,8 +20,10 @@ import com.intellij.openapi.progress.Task;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vcs.VcsException;
import com.intellij.openapi.vfs.VirtualFile;
import git4idea.GitUtil;
import git4idea.GitVcs;
import git4idea.i18n.GitBundle;
import git4idea.repo.GitRepositoryManager;
import git4idea.update.GitFetcher;
import org.jetbrains.annotations.NotNull;
@@ -46,7 +48,9 @@ public class GitFetch extends GitRepositoryAction {
GitVcs.runInBackground(new Task.Backgroundable(project, "Fetching...", false) {
@Override
public void run(@NotNull ProgressIndicator indicator) {
new GitFetcher(project, indicator, true).fetchRootsAndNotify(gitRoots, null, true);
GitRepositoryManager repositoryManager = GitUtil.getRepositoryManager(project);
new GitFetcher(project, indicator, true).fetchRootsAndNotify(GitUtil.getRepositoriesFromRoots(repositoryManager, gitRoots),
null, true);
}
});
}
@@ -37,10 +37,11 @@ import git4idea.merge.GitPullDialog;
import git4idea.repo.GitRemote;
import git4idea.repo.GitRepository;
import git4idea.repo.GitRepositoryManager;
import git4idea.util.GitUIUtil;
import git4idea.update.GitFetcher;
import git4idea.util.GitUIUtil;
import org.jetbrains.annotations.NotNull;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.concurrent.atomic.AtomicReference;
@@ -73,9 +74,6 @@ public class GitPull extends GitRepositoryAction {
@Override
public void run(@NotNull ProgressIndicator indicator) {
final GitRepositoryManager repositoryManager = GitUtil.getRepositoryManager(myProject);
if (repositoryManager == null) {
return;
}
GitRepository repository = repositoryManager.getRepositoryForRoot(dialog.gitRoot());
assert repository != null : "Repository can't be null for root " + dialog.gitRoot();
@@ -89,7 +87,8 @@ public class GitPull extends GitRepositoryAction {
}
if (GitHttpAdapter.shouldUseJGit(url)) {
boolean fetchSuccessful = new GitFetcher(project, indicator, true).fetchRootsAndNotify(gitRoots, "Pull failed", false);
boolean fetchSuccessful = new GitFetcher(project, indicator, true).fetchRootsAndNotify(Collections.singleton(repository),
"Pull failed", false);
if (!fetchSuccessful) {
return;
}
@@ -20,6 +20,7 @@ import com.intellij.notification.NotificationListener;
import com.intellij.notification.NotificationType;
import com.intellij.openapi.components.ServiceManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.Messages;
@@ -172,6 +173,15 @@ abstract class GitBranchOperation {
notifySuccess(getSuccessMessage());
}
protected static void saveAllDocuments() {
UIUtil.invokeAndWaitIfNeeded(new Runnable() {
@Override
public void run() {
FileDocumentManager.getInstance().saveAllDocuments();
}
});
}
/**
* Show fatal error as a notification or as a dialog with rollback proposal.
*/
@@ -297,7 +307,8 @@ abstract class GitBranchOperation {
setMergeDescription("The following files have unresolved conflicts. You need to resolve them before " +
getOperationName() + ".").
setErrorNotificationTitle("Unresolved files remain.");
new GitConflictResolver(myProject, myGit, ServiceManager.getService(PlatformFacade.class), GitUtil.getRoots(getRepositories()), params).merge();
new GitConflictResolver(myProject, myGit, ServiceManager.getService(PlatformFacade.class), GitUtil.getRootsFromRepositories(
getRepositories()), params).merge();
}
}
});
@@ -18,7 +18,6 @@ package git4idea.branch;
import com.intellij.notification.NotificationType;
import com.intellij.openapi.components.ServiceManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.Task;
import com.intellij.openapi.project.Project;
@@ -28,7 +27,6 @@ import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vcs.VcsException;
import com.intellij.openapi.vcs.changes.Change;
import com.intellij.util.ui.UIUtil;
import git4idea.GitBranch;
import git4idea.GitExecutionException;
import git4idea.GitVcs;
@@ -471,7 +469,6 @@ public final class GitBranchOperationsProcessor {
@Override
public final void run(@NotNull ProgressIndicator indicator) {
saveAllDocuments();
execute(indicator);
if (myCallInAwtAfterExecution != null) {
SwingUtilities.invokeLater(myCallInAwtAfterExecution);
@@ -484,14 +481,6 @@ public final class GitBranchOperationsProcessor {
GitVcs.runInBackground(this);
}
private static void saveAllDocuments() {
UIUtil.invokeAndWaitIfNeeded(new Runnable() {
@Override
public void run() {
FileDocumentManager.getInstance().saveAllDocuments();
}
});
}
}
}
@@ -17,6 +17,7 @@ package git4idea.branch;
import git4idea.GitBranch;
import git4idea.repo.GitBranchTrackInfo;
import git4idea.repo.GitRemote;
import git4idea.repo.GitRepository;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
@@ -41,4 +42,27 @@ public class GitBranchUtil {
}
return null;
}
/**
* Looks through the remote branches in the given repository and tries to find the one from the given remote,
* which the given name.
* @return remote branch or null if such branch couldn't be found.
*/
@Nullable
public static GitBranch findRemoteBranchByName(@NotNull GitRepository repository, @Nullable GitRemote remote, @Nullable String name) {
if (name == null || remote == null) {
return null;
}
final String BRANCH_PREFIX = "refs/heads/";
if (name.startsWith(BRANCH_PREFIX)) {
name = name.substring(BRANCH_PREFIX.length());
}
for (GitBranch branch : repository.getBranches().getRemoteBranches()) {
if (branch.getName().equals(remote.getName() + "/" + name)) {
return branch;
}
}
return null;
}
}
@@ -65,6 +65,7 @@ class GitCheckoutOperation extends GitBranchOperation {
@Override
protected void execute() {
saveAllDocuments();
boolean fatalErrorHappened = false;
while (hasMoreRepositories() && !fatalErrorHappened) {
final GitRepository repository = next();
@@ -79,6 +79,7 @@ class GitMergeOperation extends GitBranchOperation {
@Override
protected void execute() {
LOG.info("starting");
saveAllDocuments();
boolean fatalErrorHappened = false;
int alreadyUpToDateRepositories = 0;
while (hasMoreRepositories() && !fatalErrorHappened) {
@@ -363,7 +364,7 @@ class GitMergeOperation extends GitBranchOperation {
private class MyMergeConflictResolver extends GitMergeCommittingConflictResolver {
public MyMergeConflictResolver() {
super(GitMergeOperation.this.myProject, myGit, new GitMerger(GitMergeOperation.this.myProject),
GitUtil.getRoots(GitMergeOperation.this.myConflictedRepositories.keySet()), new Params(), true);
GitUtil.getRootsFromRepositories(GitMergeOperation.this.myConflictedRepositories.keySet()), new Params(), true);
}
@Override
@@ -27,6 +27,7 @@ import com.intellij.util.Consumer;
import com.intellij.util.ui.UIUtil;
import git4idea.GitBranch;
import git4idea.GitUtil;
import git4idea.branch.GitBranchUtil;
import git4idea.history.browser.GitCommit;
import git4idea.repo.GitRemote;
import git4idea.repo.GitRepository;
@@ -211,7 +212,7 @@ public class GitPushDialog extends DialogWrapper {
String remoteName = currentBranch.getTrackedRemoteName(repository.getProject(), repository.getRoot());
String trackedBranchName = currentBranch.getTrackedBranchName(repository.getProject(), repository.getRoot());
GitRemote remote = GitUtil.findRemoteByName(repository, remoteName);
GitBranch tracked = findRemoteBranchByName(repository, remote, trackedBranchName);
GitBranch tracked = GitBranchUtil.findRemoteBranchByName(repository, remote, trackedBranchName);
if (remote == null || tracked == null) {
Pair<GitRemote,GitBranch> remoteAndBranch = GitUtil.findMatchingRemoteBranch(repository, currentBranch);
if (remoteAndBranch == null) {
@@ -226,7 +227,7 @@ public class GitPushDialog extends DialogWrapper {
if (myRefspecPanel.turnedOn()) {
String manualBranchName = myRefspecPanel.getBranchToPush();
remote = myRefspecPanel.getSelectedRemote();
GitBranch manualBranch = findRemoteBranchByName(repository, remote, manualBranchName);
GitBranch manualBranch = GitBranchUtil.findRemoteBranchByName(repository, remote, manualBranchName);
if (manualBranch == null) {
if (!manualBranchName.startsWith("refs/remotes/")) {
manualBranchName = myRefspecPanel.getSelectedRemote().getName() + "/" + manualBranchName;
@@ -242,24 +243,6 @@ public class GitPushDialog extends DialogWrapper {
return defaultSpecs;
}
@Nullable
private static GitBranch findRemoteBranchByName(@NotNull GitRepository repository, @Nullable GitRemote remote, @Nullable String name) {
if (name == null || remote == null) {
return null;
}
final String BRANCH_PREFIX = "refs/heads/";
if (name.startsWith(BRANCH_PREFIX)) {
name = name.substring(BRANCH_PREFIX.length());
}
for (GitBranch branch : repository.getBranches().getRemoteBranches()) {
if (branch.getName().equals(remote.getName() + "/" + name)) {
return branch;
}
}
return null;
}
@Override
public JComponent getPreferredFocusedComponent() {
return myListPanel.getPreferredFocusComponent();
@@ -484,7 +484,7 @@ public final class GitPusher {
Collection<GitRepository> repositoriesToUpdate = getRootsToUpdate(rejectedPushesForCurrentBranch, updateSettings.shouldUpdateAllRoots());
GitPushResult adjustedPushResult = result.remove(rejectedPushesForCurrentBranch);
adjustedPushResult.markUpdateStartIfNotMarked(repositoriesToUpdate);
boolean updateResult = update(getRootsFromRepositories(repositoriesToUpdate), updateSettings.getUpdateMethod());
boolean updateResult = update(repositoriesToUpdate, updateSettings.getUpdateMethod());
if (updateResult) {
myProgressIndicator.setText(INDICATOR_TEXT);
GitPushInfo newPushInfo = pushInfo.retain(rejectedPushesForCurrentBranch);
@@ -544,20 +544,12 @@ public final class GitPusher {
return updateAllRoots ? myRepositories : rejectedPushesForCurrentBranch.keySet();
}
@NotNull
private static Collection<VirtualFile> getRootsFromRepositories(@NotNull Collection<GitRepository> repositories) {
Collection<VirtualFile> roots = new ArrayList<VirtualFile>();
for (GitRepository repository : repositories) {
roots.add(repository.getRoot());
}
return roots;
}
private boolean update(@NotNull Collection<VirtualFile> rootsToUpdate, @NotNull UpdateMethod updateMethod) {
private boolean update(@NotNull Collection<GitRepository> rootsToUpdate, @NotNull UpdateMethod updateMethod) {
GitUpdateProcess.UpdateMethod um = updateMethod == UpdateMethod.MERGE ? GitUpdateProcess.UpdateMethod.MERGE : GitUpdateProcess.UpdateMethod.REBASE;
boolean updateResult = new GitUpdateProcess(myProject, myProgressIndicator, new HashSet<VirtualFile>(rootsToUpdate), UpdatedFiles.create()).update(um);
for (VirtualFile virtualFile : rootsToUpdate) {
virtualFile.refresh(true, true);
boolean updateResult = new GitUpdateProcess(myProject, myProgressIndicator, new HashSet<GitRepository>(rootsToUpdate),
UpdatedFiles.create()).update(um);
for (GitRepository repository : rootsToUpdate) {
repository.getRoot().refresh(true, true);
}
return updateResult;
}
@@ -50,6 +50,12 @@ public class GitBranchTrackInfo {
return myRemote;
}
/**
* Returns the name of the remote branch.<br/>
* The name is local for that remote (i.e. without the remote prefix),
* and the name is simplified (i.e. without the {@code refs/heads/} prefix).<br/>
* For example, returns {@code master}, and not {@code origin/master} or {@code refs/heads/master} or {@code refs/remotes/origin/master}.
*/
@NotNull
public String getRemoteBranch() {
return myRemoteBranch;
@@ -81,14 +81,11 @@ public class GitFetcher {
* Invokes 'git fetch'.
* @return true if fetch was successful, false in the case of error.
*/
public GitFetchResult fetch(@NotNull VirtualFile root) {
GitRepository repository = myRepositoryManager.getRepositoryForRoot(root);
assert repository != null : "Repository can't be null for " + root + "\n" + myRepositoryManager;
public GitFetchResult fetch(@NotNull GitRepository repository) {
// TODO need to have a fair compound result here
GitFetchResult fetchResult = GitFetchResult.success();
if (myFetchAll) {
fetchResult = fetchAll(root, repository, fetchResult);
fetchResult = fetchAll(repository, fetchResult);
}
else {
return fetchCurrentRemote(repository);
@@ -187,7 +184,7 @@ public class GitFetcher {
}
@NotNull
private GitFetchResult fetchAll(@NotNull VirtualFile root, @NotNull GitRepository repository, @NotNull GitFetchResult fetchResult) {
private GitFetchResult fetchAll(@NotNull GitRepository repository, @NotNull GitFetchResult fetchResult) {
for (GitRemote remote : repository.getRemotes()) {
String url = remote.getFirstUrl();
if (url == null) {
@@ -204,7 +201,7 @@ public class GitFetcher {
}
}
else {
GitFetchResult res = fetchNatively(root, remote, null);
GitFetchResult res = fetchNatively(repository.getRoot(), remote, null);
res.addPruneInfo(fetchResult.getPrunedRefs());
fetchResult = res;
if (!fetchResult.isSuccess()) {
@@ -318,13 +315,15 @@ public class GitFetcher {
* @param notifySuccess if set to {@code true} successful notification will be displayed.
* @return true if all fetches were successful, false if at least one fetch failed.
*/
public boolean fetchRootsAndNotify(@NotNull Collection<VirtualFile> roots, @Nullable String errorNotificationTitle, boolean notifySuccess) {
public boolean fetchRootsAndNotify(@NotNull Collection<GitRepository> roots,
@Nullable String errorNotificationTitle, boolean notifySuccess) {
Map<VirtualFile, String> additionalInfo = new HashMap<VirtualFile, String>();
for (VirtualFile root : roots) {
GitFetchResult result = fetch(root);
for (GitRepository repository : roots) {
LOG.info("fetching " + repository);
GitFetchResult result = fetch(repository);
String ai = result.getAdditionalInfo();
if (!StringUtil.isEmptyOrSpaces(ai)) {
additionalInfo.put(root, ai);
additionalInfo.put(repository.getRoot(), ai);
}
if (!result.isSuccess()) {
Collection<Exception> errors = new ArrayList<Exception>(getErrors());

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