diff options
author | Tor Norbye <tnorbye@google.com> | 2013-04-24 10:43:41 -0700 |
---|---|---|
committer | Tor Norbye <tnorbye@google.com> | 2013-04-24 10:43:41 -0700 |
commit | b17587c84879dd2ea42495f1fbdadbc806b9475b (patch) | |
tree | b4d9014f69cb8289627ddc75339a6b0b3fe1bc5e /plugins | |
parent | b569bc6aa78f6eacf72e8b90622d300e1a9db25f (diff) | |
download | idea-b17587c84879dd2ea42495f1fbdadbc806b9475b.tar.gz |
Snapshot e242282deb41c328afbe971fc167e47ddfb26df9 from master branch of git://git.jetbrains.org/idea/community.git
Change-Id: Ifdc1818cde7b63f6d7bf42801f18c7f1557b8d85
Diffstat (limited to 'plugins')
142 files changed, 1324 insertions, 5794 deletions
diff --git a/plugins/InspectionGadgets/src/META-INF/plugin.xml b/plugins/InspectionGadgets/src/META-INF/plugin.xml index 1b3efecf24ca..2e8c2d98e469 100644 --- a/plugins/InspectionGadgets/src/META-INF/plugin.xml +++ b/plugins/InspectionGadgets/src/META-INF/plugin.xml @@ -2297,6 +2297,10 @@ key="unnecessary.call.to.string.valueof.display.name" groupBundle="messages.InspectionsBundle" groupKey="group.names.code.style.issues" enabledByDefault="false" level="WARNING" implementationClass="com.siyeh.ig.style.UnnecessaryCallToStringValueOfInspection"/> + <localInspection language="JAVA" shortName="UnnecessaryToStringCall" bundle="com.siyeh.InspectionGadgetsBundle" + key="unnecessary.tostring.call.display.name" groupBundle="messages.InspectionsBundle" + groupKey="group.names.code.style.issues" enabledByDefault="false" level="WARNING" + implementationClass="com.siyeh.ig.style.UnnecessaryToStringCallInspection"/> <localInspection language="JAVA" suppressId="RedundantNoArgConstructor" shortName="UnnecessaryConstructor" bundle="com.siyeh.InspectionGadgetsBundle" key="unnecessary.constructor.display.name" groupBundle="messages.InspectionsBundle" groupKey="group.names.code.style.issues" enabledByDefault="false" level="WARNING" diff --git a/plugins/InspectionGadgets/src/com/siyeh/InspectionGadgetsBundle.properties b/plugins/InspectionGadgets/src/com/siyeh/InspectionGadgetsBundle.properties index df0905eac73c..8120f291f364 100644 --- a/plugins/InspectionGadgets/src/com/siyeh/InspectionGadgetsBundle.properties +++ b/plugins/InspectionGadgets/src/com/siyeh/InspectionGadgetsBundle.properties @@ -1682,7 +1682,9 @@ synchronization.on.method.parameter.problem.descriptor=Synchronization on method too.broad.catch.quickfix=Add ''catch'' clause for ''{0}'' too.broad.catch.option=&Only warn on RuntimeException, Exception, Error or Throwable unnecessary.call.to.string.valueof.display.name=Unnecessary call to 'String.valueOf()' +unnecessary.tostring.call.display.name=Unnecessary call to '.toString()' unnecessary.call.to.string.valueof.problem.descriptor=<code>#ref</code> can be simplified to ''{0}'' #loc +unnecessary.tostring.call.problem.descriptor=Unnecessary <code>#ref()</code> call #loc unnecessary.call.to.string.valueof.quickfix=Replace with ''{0}'' throwable.result.of.method.call.ignored.display.name=Throwable result of method call ignored throwable.result.of.method.call.ignored.problem.descriptor=Result of <code>#ref()</code> not thrown #loc diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/jdk/VarargParameterInspection.java b/plugins/InspectionGadgets/src/com/siyeh/ig/jdk/VarargParameterInspection.java index f011d6dd84c2..f93166cfd2b3 100644 --- a/plugins/InspectionGadgets/src/com/siyeh/ig/jdk/VarargParameterInspection.java +++ b/plugins/InspectionGadgets/src/com/siyeh/ig/jdk/VarargParameterInspection.java @@ -1,5 +1,5 @@ /* - * Copyright 2003-2011 Dave Griffith, Bas Leijdekkers + * Copyright 2003-2013 Dave Griffith, Bas Leijdekkers * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,13 +15,13 @@ */ package com.siyeh.ig.jdk; +import com.intellij.codeInsight.AnnotationUtil; import com.intellij.codeInspection.ProblemDescriptor; import com.intellij.openapi.project.Project; import com.intellij.psi.*; import com.intellij.psi.codeStyle.CodeStyleManager; import com.intellij.psi.codeStyle.JavaCodeStyleManager; import com.intellij.psi.search.searches.ReferencesSearch; -import com.intellij.util.IncorrectOperationException; import com.intellij.util.Query; import com.siyeh.InspectionGadgetsBundle; import com.siyeh.ig.BaseInspection; @@ -44,15 +44,13 @@ public class VarargParameterInspection extends BaseInspection { @Override @NotNull public String getDisplayName() { - return InspectionGadgetsBundle.message( - "variable.argument.method.display.name"); + return InspectionGadgetsBundle.message("variable.argument.method.display.name"); } @Override @NotNull public String buildErrorString(Object... infos) { - return InspectionGadgetsBundle.message( - "variable.argument.method.problem.descriptor"); + return InspectionGadgetsBundle.message("variable.argument.method.problem.descriptor"); } @Override @@ -65,27 +63,29 @@ public class VarargParameterInspection extends BaseInspection { @NotNull public String getName() { - return InspectionGadgetsBundle.message( - "variable.argument.method.quickfix"); + return InspectionGadgetsBundle.message("variable.argument.method.quickfix"); } @Override - protected void doFix(Project project, ProblemDescriptor descriptor) - throws IncorrectOperationException { + protected void doFix(Project project, ProblemDescriptor descriptor) { final PsiElement element = descriptor.getPsiElement(); final PsiMethod method = (PsiMethod)element.getParent(); final PsiParameterList parameterList = method.getParameterList(); final PsiParameter[] parameters = parameterList.getParameters(); - final PsiParameter lastParameter = - parameters[parameters.length - 1]; + final PsiParameter lastParameter = parameters[parameters.length - 1]; if (!lastParameter.isVarArgs()) { return; } - final PsiEllipsisType type = - (PsiEllipsisType)lastParameter.getType(); + final PsiEllipsisType type = (PsiEllipsisType)lastParameter.getType(); final Query<PsiReference> query = ReferencesSearch.search(method); final PsiType componentType = type.getComponentType(); - final String typeText = componentType.getCanonicalText(); + final String typeText; + if (componentType instanceof PsiClassType) { + final PsiClassType classType = (PsiClassType)componentType; + typeText = classType.rawType().getCanonicalText(); + } else { + typeText = componentType.getCanonicalText(); + } final Collection<PsiReference> references = query.findAll(); for (PsiReference reference : references) { modifyCalls(reference, typeText, parameters.length - 1); @@ -93,59 +93,48 @@ public class VarargParameterInspection extends BaseInspection { final PsiType arrayType = type.toArrayType(); final PsiManager psiManager = lastParameter.getManager(); final PsiElementFactory factory = JavaPsiFacade.getInstance(psiManager.getProject()).getElementFactory(); - final PsiTypeElement newTypeElement = - factory.createTypeElement(arrayType); - final PsiTypeElement typeElement = - lastParameter.getTypeElement(); + final PsiTypeElement newTypeElement = factory.createTypeElement(arrayType); + final PsiTypeElement typeElement = lastParameter.getTypeElement(); + if (typeElement == null) { + return; + } + final PsiAnnotation annotation = AnnotationUtil.findAnnotation(method, "java.lang.SafeVarargs"); + if (annotation != null) { + annotation.delete(); + } typeElement.replace(newTypeElement); } - public static void modifyCalls(PsiReference reference, - String arrayTypeText, - int indexOfFirstVarargArgument) - throws IncorrectOperationException { - final PsiReferenceExpression referenceExpression = - (PsiReferenceExpression)reference.getElement(); - final PsiMethodCallExpression methodCallExpression = - (PsiMethodCallExpression)referenceExpression.getParent(); - final PsiExpressionList argumentList = - methodCallExpression.getArgumentList(); + public static void modifyCalls(PsiReference reference, String arrayTypeText, int indexOfFirstVarargArgument) { + final PsiReferenceExpression referenceExpression = (PsiReferenceExpression)reference.getElement(); + final PsiMethodCallExpression methodCallExpression = (PsiMethodCallExpression)referenceExpression.getParent(); + final PsiExpressionList argumentList = methodCallExpression.getArgumentList(); final PsiExpression[] arguments = argumentList.getExpressions(); @NonNls final StringBuilder builder = new StringBuilder("new "); builder.append(arrayTypeText); builder.append("[]{"); if (arguments.length > indexOfFirstVarargArgument) { - final PsiExpression firstArgument = - arguments[indexOfFirstVarargArgument]; + final PsiExpression firstArgument = arguments[indexOfFirstVarargArgument]; final String firstArgumentText = firstArgument.getText(); builder.append(firstArgumentText); - for (int i = indexOfFirstVarargArgument + 1; - i < arguments.length; i++) { - builder.append(','); - builder.append(arguments[i].getText()); + for (int i = indexOfFirstVarargArgument + 1; i < arguments.length; i++) { + builder.append(',').append(arguments[i].getText()); } } builder.append('}'); final Project project = referenceExpression.getProject(); - final PsiElementFactory factory = - JavaPsiFacade.getElementFactory(project); - final PsiExpression arrayExpression = - factory.createExpressionFromText(builder.toString(), - referenceExpression); + final PsiElementFactory factory = JavaPsiFacade.getElementFactory(project); + final PsiExpression arrayExpression = factory.createExpressionFromText(builder.toString(), referenceExpression); if (arguments.length > indexOfFirstVarargArgument) { - final PsiExpression firstArgument = - arguments[indexOfFirstVarargArgument]; - argumentList.deleteChildRange(firstArgument, - arguments[arguments.length - 1]); + final PsiExpression firstArgument = arguments[indexOfFirstVarargArgument]; + argumentList.deleteChildRange(firstArgument, arguments[arguments.length - 1]); argumentList.add(arrayExpression); } else { argumentList.add(arrayExpression); } - final CodeStyleManager codeStyleManager = - CodeStyleManager.getInstance(project); - final JavaCodeStyleManager javaCodeStyleManager = - JavaCodeStyleManager.getInstance(project); + final CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(project); + final JavaCodeStyleManager javaCodeStyleManager = JavaCodeStyleManager.getInstance(project); javaCodeStyleManager.shortenClassReferences(argumentList); codeStyleManager.reformat(argumentList); } @@ -165,8 +154,7 @@ public class VarargParameterInspection extends BaseInspection { return; } final PsiParameter[] parameters = parameterList.getParameters(); - final PsiParameter lastParameter = - parameters[parameters.length - 1]; + final PsiParameter lastParameter = parameters[parameters.length - 1]; if (lastParameter.isVarArgs()) { registerMethodError(method); } diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/style/UnnecessaryCallToStringValueOfInspection.java b/plugins/InspectionGadgets/src/com/siyeh/ig/style/UnnecessaryCallToStringValueOfInspection.java index 4c75ce15866d..45fdfb5146b9 100644 --- a/plugins/InspectionGadgets/src/com/siyeh/ig/style/UnnecessaryCallToStringValueOfInspection.java +++ b/plugins/InspectionGadgets/src/com/siyeh/ig/style/UnnecessaryCallToStringValueOfInspection.java @@ -1,5 +1,5 @@ /* - * Copyright 2008-2012 Bas Leijdekkers + * Copyright 2008-2013 Bas Leijdekkers * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -104,32 +104,7 @@ public class UnnecessaryCallToStringValueOfInspection extends BaseInspection { if (!"valueOf".equals(referenceName)) { return; } - final PsiElement parent = expression.getParent(); - if (!(parent instanceof PsiPolyadicExpression)) { - return; - } - final PsiPolyadicExpression polyadicExpression = (PsiPolyadicExpression)parent; - final PsiType type = polyadicExpression.getType(); - if (!TypeUtils.typeEquals(CommonClassNames.JAVA_LANG_STRING, type)) { - return; - } - final PsiExpression[] operands = polyadicExpression.getOperands(); - int index = -1; - for (int i = 0, length = operands.length; i < length; i++) { - final PsiExpression operand = operands[i]; - if (expression.equals(operand)) { - index = i; - } - } - if (index > 0) { - if (!TypeUtils.typeEquals(CommonClassNames.JAVA_LANG_STRING, operands[index - 1].getType())) { - return; - } - } else if (operands.length > 1) { - if (!TypeUtils.typeEquals(CommonClassNames.JAVA_LANG_STRING, operands[index + 1].getType())) { - return; - } - } else { + if (isCallToStringValueOfNecessary(expression)) { return; } final PsiExpressionList argumentList = expression.getArgumentList(); @@ -160,5 +135,86 @@ public class UnnecessaryCallToStringValueOfInspection extends BaseInspection { } registerError(expression, calculateReplacementText(argument)); } + + private boolean isCallToStringValueOfNecessary(PsiMethodCallExpression expression) { + final PsiElement parent = ParenthesesUtils.getParentSkipParentheses(expression); + if (parent instanceof PsiPolyadicExpression) { + final PsiPolyadicExpression polyadicExpression = (PsiPolyadicExpression)parent; + final PsiType type = polyadicExpression.getType(); + if (!TypeUtils.typeEquals(CommonClassNames.JAVA_LANG_STRING, type)) { + return true; + } + final PsiExpression[] operands = polyadicExpression.getOperands(); + int index = -1; + for (int i = 0, length = operands.length; i < length; i++) { + final PsiExpression operand = operands[i]; + if (expression.equals(operand)) { + index = i; + } + } + if (index > 0) { + if (!TypeUtils.typeEquals(CommonClassNames.JAVA_LANG_STRING, operands[index - 1].getType())) { + return true; + } + } else if (operands.length > 1) { + if (!TypeUtils.typeEquals(CommonClassNames.JAVA_LANG_STRING, operands[index + 1].getType())) { + return true; + } + } else { + return true; + } + } else if (parent instanceof PsiExpressionList) { + final PsiExpressionList expressionList = (PsiExpressionList)parent; + final PsiElement grandParent = expressionList.getParent(); + if (!(grandParent instanceof PsiMethodCallExpression)) { + return true; + } + final PsiMethodCallExpression methodCallExpression = (PsiMethodCallExpression)grandParent; + final PsiReferenceExpression methodExpression1 = methodCallExpression.getMethodExpression(); + final String name = methodExpression1.getReferenceName(); + final PsiExpression[] expressions = expressionList.getExpressions(); + if ("insert".equals(name)) { + if (expressions.length < 2 || !expression.equals(ParenthesesUtils.stripParentheses(expressions[1]))) { + return true; + } + if (!isCallToMethodIn(methodCallExpression, "java.lang.StringBuilder", "java.lang.StringBuffer")) { + return true; + } + + } else if ("append".equals(name)) { + if (expressions.length < 1 || !expression.equals(ParenthesesUtils.stripParentheses(expressions[0]))) { + return true; + } + if (!isCallToMethodIn(methodCallExpression, "java.lang.StringBuilder", "java.lang.StringBuffer")) { + return true; + } + } else if ("print".equals(name) || "println".equals(name)) { + if (!isCallToMethodIn(methodCallExpression, "java.io.PrintStream", "java.io.PrintWriter")) { + return true; + } + } + } else { + return true; + } + return false; + } + + private boolean isCallToMethodIn(PsiMethodCallExpression methodCallExpression, String... classNames) { + final PsiMethod method = methodCallExpression.resolveMethod(); + if (method == null) { + return false; + } + final PsiClass containingClass = method.getContainingClass(); + if (containingClass == null) { + return false; + } + final String qualifiedName = containingClass.getQualifiedName(); + for (String className : classNames) { + if (className.equals(qualifiedName)) { + return true; + } + } + return false; + } } } diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/style/UnnecessaryToStringCallInspection.java b/plugins/InspectionGadgets/src/com/siyeh/ig/style/UnnecessaryToStringCallInspection.java new file mode 100644 index 000000000000..d7cad4ef4f13 --- /dev/null +++ b/plugins/InspectionGadgets/src/com/siyeh/ig/style/UnnecessaryToStringCallInspection.java @@ -0,0 +1,200 @@ +/* + * Copyright 2008-2013 Bas Leijdekkers + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.siyeh.ig.style; + +import com.intellij.codeInspection.ProblemDescriptor; +import com.intellij.openapi.project.Project; +import com.intellij.psi.*; +import com.intellij.util.IncorrectOperationException; +import com.siyeh.InspectionGadgetsBundle; +import com.siyeh.ig.BaseInspection; +import com.siyeh.ig.BaseInspectionVisitor; +import com.siyeh.ig.InspectionGadgetsFix; +import com.siyeh.ig.psiutils.ParenthesesUtils; +import com.siyeh.ig.psiutils.TypeUtils; +import org.jetbrains.annotations.Nls; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +public class UnnecessaryToStringCallInspection extends BaseInspection { + + @Override + @Nls + @NotNull + public String getDisplayName() { + return InspectionGadgetsBundle.message("unnecessary.tostring.call.display.name"); + } + + @Override + @NotNull + protected String buildErrorString(Object... infos) { + final String text = (String)infos[0]; + return InspectionGadgetsBundle.message("unnecessary.tostring.call.problem.descriptor", text); + } + + @Override + @Nullable + protected InspectionGadgetsFix buildFix(Object... infos) { + final String text = (String)infos[0]; + return new UnnecessaryCallToStringValueOfFix(text); + } + + public static String calculateReplacementText(PsiExpression expression) { + if (expression == null) { + return "this"; + } + return expression.getText(); + } + + private static class UnnecessaryCallToStringValueOfFix extends InspectionGadgetsFix { + + private final String replacementText; + + UnnecessaryCallToStringValueOfFix(String replacementText) { + this.replacementText = replacementText; + } + + @NotNull + public String getName() { + return InspectionGadgetsBundle.message("unnecessary.call.to.string.valueof.quickfix", replacementText); + } + + @Override + protected void doFix(Project project, ProblemDescriptor descriptor) throws IncorrectOperationException { + final PsiMethodCallExpression methodCallExpression = (PsiMethodCallExpression)descriptor.getPsiElement().getParent().getParent(); + final PsiReferenceExpression methodExpression = methodCallExpression.getMethodExpression(); + final PsiExpression qualifier = methodExpression.getQualifierExpression(); + if (qualifier == null) { + replaceExpression(methodCallExpression, "this"); + } else { + methodCallExpression.replace(qualifier); + } + } + } + + @Override + public BaseInspectionVisitor buildVisitor() { + return new UnnecessaryCallToStringValueOfVisitor(); + } + + private static class UnnecessaryCallToStringValueOfVisitor extends BaseInspectionVisitor { + + @Override + public void visitMethodCallExpression(PsiMethodCallExpression expression) { + super.visitMethodCallExpression(expression); + final PsiReferenceExpression methodExpression = expression.getMethodExpression(); + final String referenceName = methodExpression.getReferenceName(); + if (!"toString".equals(referenceName)) { + return; + } + if (isToStringCallNecessary(expression)) { + return; + } + final PsiExpressionList argumentList = expression.getArgumentList(); + final PsiExpression[] arguments = argumentList.getExpressions(); + if (arguments.length != 0) { + return; + } + final PsiExpression qualifier = methodExpression.getQualifierExpression(); + if (qualifier != null && qualifier.getType() instanceof PsiArrayType) { + // do not warn on nonsensical code + return; + } + registerMethodCallError(expression, calculateReplacementText(qualifier)); + } + + private boolean isToStringCallNecessary(PsiMethodCallExpression expression) { + final PsiElement parent = ParenthesesUtils.getParentSkipParentheses(expression); + if (parent instanceof PsiPolyadicExpression) { + final PsiPolyadicExpression polyadicExpression = (PsiPolyadicExpression)parent; + final PsiType type = polyadicExpression.getType(); + if (!TypeUtils.typeEquals(CommonClassNames.JAVA_LANG_STRING, type)) { + return true; + } + final PsiExpression[] operands = polyadicExpression.getOperands(); + int index = -1; + for (int i = 0, length = operands.length; i < length; i++) { + final PsiExpression operand = operands[i]; + if (expression.equals(operand)) { + index = i; + } + } + if (index > 0) { + if (!TypeUtils.typeEquals(CommonClassNames.JAVA_LANG_STRING, operands[index - 1].getType())) { + return true; + } + } else if (operands.length > 1) { + if (!TypeUtils.typeEquals(CommonClassNames.JAVA_LANG_STRING, operands[index + 1].getType())) { + return true; + } + } else { + return true; + } + } else if (parent instanceof PsiExpressionList) { + final PsiExpressionList expressionList = (PsiExpressionList)parent; + final PsiElement grandParent = expressionList.getParent(); + if (!(grandParent instanceof PsiMethodCallExpression)) { + return true; + } + final PsiMethodCallExpression methodCallExpression = (PsiMethodCallExpression)grandParent; + final PsiReferenceExpression methodExpression1 = methodCallExpression.getMethodExpression(); + final String name = methodExpression1.getReferenceName(); + final PsiExpression[] expressions = expressionList.getExpressions(); + if ("insert".equals(name)) { + if (expressions.length < 2 || !expression.equals(ParenthesesUtils.stripParentheses(expressions[1]))) { + return true; + } + if (!isCallToMethodIn(methodCallExpression, "java.lang.StringBuilder", "java.lang.StringBuffer")) { + return true; + } + + } else if ("append".equals(name)) { + if (expressions.length < 1 || !expression.equals(ParenthesesUtils.stripParentheses(expressions[0]))) { + return true; + } + if (!isCallToMethodIn(methodCallExpression, "java.lang.StringBuilder", "java.lang.StringBuffer")) { + return true; + } + } else if ("print".equals(name) || "println".equals(name)) { + if (!isCallToMethodIn(methodCallExpression, "java.io.PrintStream", "java.io.PrintWriter")) { + return true; + } + } + } else { + return true; + } + return false; + } + + private boolean isCallToMethodIn(PsiMethodCallExpression methodCallExpression, String... classNames) { + final PsiMethod method = methodCallExpression.resolveMethod(); + if (method == null) { + return false; + } + final PsiClass containingClass = method.getContainingClass(); + if (containingClass == null) { + return false; + } + final String qualifiedName = containingClass.getQualifiedName(); + for (String className : classNames) { + if (className.equals(qualifiedName)) { + return true; + } + } + return false; + } + } +} diff --git a/plugins/InspectionGadgets/src/inspectionDescriptions/UnnecessaryCallToStringValueOf.html b/plugins/InspectionGadgets/src/inspectionDescriptions/UnnecessaryCallToStringValueOf.html index 3d95b3ac2f14..ecbdf6ff2ff8 100644 --- a/plugins/InspectionGadgets/src/inspectionDescriptions/UnnecessaryCallToStringValueOf.html +++ b/plugins/InspectionGadgets/src/inspectionDescriptions/UnnecessaryCallToStringValueOf.html @@ -1,8 +1,8 @@ <html> <body> -Reports on any calls to <b>String.valueOf()</b> -used in string concatenations. The conversion to string is handled automatically by the compiler -without a call to <b>String.valueOf()</b>, making it unnecessary. +Reports on any calls to <b>String.valueOf()</b> used in string concatenations and as arguments to the +<b>print</b> and <b>println</b> methods of <b>java.io.PrintWriter</b> and <b>java.io.PrintStream</b>. The conversion +to string will be handled by the underlying library methods without an explicit call to <b>String.valueOf()</b>. <!-- tooltip end --> <p> <small>Powered by InspectionGadgets</small> diff --git a/plugins/InspectionGadgets/src/inspectionDescriptions/UnnecessaryToStringCall.html b/plugins/InspectionGadgets/src/inspectionDescriptions/UnnecessaryToStringCall.html new file mode 100644 index 000000000000..69cfb6134430 --- /dev/null +++ b/plugins/InspectionGadgets/src/inspectionDescriptions/UnnecessaryToStringCall.html @@ -0,0 +1,13 @@ +<html> +<body> +Reports on any calls to <b>.toString()</b> used in string concatenations and as arguments to the +<b>print</b> and <b>println</b> methods of <b>java.io.PrintWriter</b> and <b>java.io.PrintStream</b>. The conversion +to string will be handled by the underlying library methods without an explicit call to <b>.toString()</b>. +<p> +Note that without the <b>.toString()</b> the expression will have different semantics (the string "null" will be used instead of + throwing a <b>NullPointerException</b>). +<!-- tooltip end --> +<p> +<small>Powered by InspectionGadgets</small> +</body> +</html>
\ No newline at end of file diff --git a/plugins/InspectionGadgets/test/com/siyeh/igfixes/jdk/vararg_parameter/GenericType.after.java b/plugins/InspectionGadgets/test/com/siyeh/igfixes/jdk/vararg_parameter/GenericType.after.java new file mode 100644 index 000000000000..7c6d0d34ed4d --- /dev/null +++ b/plugins/InspectionGadgets/test/com/siyeh/igfixes/jdk/vararg_parameter/GenericType.after.java @@ -0,0 +1,11 @@ +package com.siyeh.igfixes.jdk.vararg_parameter; + +@SuppressWarnings("UnusedDeclaration") +public class GenericType { + final void addClasses(Class<? extends Number>[] classes) { + } + + void test() { + addClasses(new Class[]{Number.class, Byte.class}); + } +}
\ No newline at end of file diff --git a/plugins/InspectionGadgets/test/com/siyeh/igfixes/jdk/vararg_parameter/GenericType.java b/plugins/InspectionGadgets/test/com/siyeh/igfixes/jdk/vararg_parameter/GenericType.java new file mode 100644 index 000000000000..595bf0032e2b --- /dev/null +++ b/plugins/InspectionGadgets/test/com/siyeh/igfixes/jdk/vararg_parameter/GenericType.java @@ -0,0 +1,12 @@ +package com.siyeh.igfixes.jdk.vararg_parameter; + +@SuppressWarnings("UnusedDeclaration") +public class GenericType { + @java.lang.SafeVarargs + final void addCl<caret>asses(Class<? extends Number>... classes) { + } + + void test() { + addClasses(Number.class, Byte.class); + } +}
\ No newline at end of file diff --git a/plugins/InspectionGadgets/test/com/siyeh/igtest/style/unnecessary_tostring/UnnecessaryToString.java b/plugins/InspectionGadgets/test/com/siyeh/igtest/style/unnecessary_tostring/UnnecessaryToString.java new file mode 100644 index 000000000000..a77660ab714a --- /dev/null +++ b/plugins/InspectionGadgets/test/com/siyeh/igtest/style/unnecessary_tostring/UnnecessaryToString.java @@ -0,0 +1,30 @@ +package com.siyeh.igtest.style.unnecessary_tostring; + +public class UnnecessaryToString { + + String foo(Object o) { + return "star" + o.toString(); + } + + String bar() { + char[] cs = {'!'}; + return "wars" + cs.toString(); + } + + void fizzz(Object o) { + boolean c = true; + System.out.println(o.toString() + c); + } + + void polyadic(Object s) { + s = "abc" + s.toString() + "efg"; + } + + void printStream(Object o) { + System.out.print(o.toString()); + } + + void builder(StringBuilder builder, Object o) { + builder.append(o.toString()); + } +}
\ No newline at end of file diff --git a/plugins/InspectionGadgets/test/com/siyeh/igtest/style/unnecessary_tostring/expected.xml b/plugins/InspectionGadgets/test/com/siyeh/igtest/style/unnecessary_tostring/expected.xml new file mode 100644 index 000000000000..9aea4d234a81 --- /dev/null +++ b/plugins/InspectionGadgets/test/com/siyeh/igtest/style/unnecessary_tostring/expected.xml @@ -0,0 +1,32 @@ +<?xml version="1.0" encoding="UTF-8"?> +<problems> + + <problem> + <file>UnnecessaryToString.java</file> + <line>6</line> + <problem_class severity="WARNING" attribute_key="WARNING_ATTRIBUTES">Unnecessary call to '.toString()'</problem_class> + <description>Unnecessary <code>toString()</code> call #loc</description> + </problem> + + <problem> + <file>UnnecessaryToString.java</file> + <line>20</line> + <problem_class severity="WARNING" attribute_key="WARNING_ATTRIBUTES">Unnecessary call to '.toString()'</problem_class> + <description>Unnecessary <code>toString()</code> call #loc</description> + </problem> + + <problem> + <file>UnnecessaryToString.java</file> + <line>24</line> + <problem_class severity="WARNING" attribute_key="WARNING_ATTRIBUTES">Unnecessary call to '.toString()'</problem_class> + <description>Unnecessary <code>toString()</code> call #loc</description> + </problem> + + <problem> + <file>UnnecessaryToString.java</file> + <line>28</line> + <problem_class severity="WARNING" attribute_key="WARNING_ATTRIBUTES">Unnecessary call to '.toString()'</problem_class> + <description>Unnecessary <code>toString()</code> call #loc</description> + </problem> + +</problems>
\ No newline at end of file diff --git a/plugins/InspectionGadgets/test/com/siyeh/igtest/style/unnecessary_valueof/UnnecessaryCallToStringValueOf.java b/plugins/InspectionGadgets/test/com/siyeh/igtest/style/unnecessary_valueof/UnnecessaryCallToStringValueOf.java index cf3f87cfae7a..023d86fef245 100644 --- a/plugins/InspectionGadgets/test/com/siyeh/igtest/style/unnecessary_valueof/UnnecessaryCallToStringValueOf.java +++ b/plugins/InspectionGadgets/test/com/siyeh/igtest/style/unnecessary_valueof/UnnecessaryCallToStringValueOf.java @@ -21,4 +21,11 @@ public class UnnecessaryCallToStringValueOf { s = "abc" + String.valueOf('d') + "efg"; } + void printStream() { + System.out.print(String.valueOf(7)); + } + + void builder(StringBuilder builder) { + builder.append(String.valueOf(0x8)); + } }
\ No newline at end of file diff --git a/plugins/InspectionGadgets/test/com/siyeh/igtest/style/unnecessary_valueof/expected.xml b/plugins/InspectionGadgets/test/com/siyeh/igtest/style/unnecessary_valueof/expected.xml index 315e44ea81b7..c453124dc5ca 100644 --- a/plugins/InspectionGadgets/test/com/siyeh/igtest/style/unnecessary_valueof/expected.xml +++ b/plugins/InspectionGadgets/test/com/siyeh/igtest/style/unnecessary_valueof/expected.xml @@ -15,4 +15,18 @@ <description><code>String.valueOf('d')</code> can be simplified to ''d'' #loc</description> </problem> + <problem> + <file>UnnecessaryCallToStringValueOf.java</file> + <line>25</line> + <problem_class severity="WARNING" attribute_key="WARNING_ATTRIBUTES">Unnecessary call to 'String.valueOf()'</problem_class> + <description><code>String.valueOf(7)</code> can be simplified to '7' #loc</description> + </problem> + + <problem> + <file>UnnecessaryCallToStringValueOf.java</file> + <line>29</line> + <problem_class severity="WARNING" attribute_key="WARNING_ATTRIBUTES">Unnecessary call to 'String.valueOf()'</problem_class> + <description><code>String.valueOf(0x8)</code> can be simplified to '0x8' #loc</description> + </problem> + </problems>
\ No newline at end of file diff --git a/plugins/InspectionGadgets/testsrc/com/siyeh/ig/fixes/jdk/VarargParameterFixTest.java b/plugins/InspectionGadgets/testsrc/com/siyeh/ig/fixes/jdk/VarargParameterFixTest.java new file mode 100644 index 000000000000..f14e395ff243 --- /dev/null +++ b/plugins/InspectionGadgets/testsrc/com/siyeh/ig/fixes/jdk/VarargParameterFixTest.java @@ -0,0 +1,18 @@ +package com.siyeh.ig.fixes.jdk; + +import com.siyeh.InspectionGadgetsBundle; +import com.siyeh.ig.IGQuickFixesTestCase; +import com.siyeh.ig.jdk.VarargParameterInspection; + +public class VarargParameterFixTest extends IGQuickFixesTestCase { + + @Override + protected void setUp() throws Exception { + super.setUp(); + myFixture.enableInspections(new VarargParameterInspection()); + myRelativePath = "jdk/vararg_parameter"; + myDefaultHint = InspectionGadgetsBundle.message("variable.argument.method.quickfix"); + } + + public void testGenericType() { doTest(); } +}
\ No newline at end of file diff --git a/plugins/InspectionGadgets/testsrc/com/siyeh/ig/style/UnnecessaryToStringCallInspectionTest.java b/plugins/InspectionGadgets/testsrc/com/siyeh/ig/style/UnnecessaryToStringCallInspectionTest.java new file mode 100644 index 000000000000..797b4273106d --- /dev/null +++ b/plugins/InspectionGadgets/testsrc/com/siyeh/ig/style/UnnecessaryToStringCallInspectionTest.java @@ -0,0 +1,10 @@ +package com.siyeh.ig.style; + +import com.siyeh.ig.IGInspectionTestCase; + +public class UnnecessaryToStringCallInspectionTest extends IGInspectionTestCase { + + public void test() throws Exception { + doTest("com/siyeh/igtest/style/unnecessary_tostring", new UnnecessaryToStringCallInspection()); + } +}
\ No newline at end of file diff --git a/plugins/IntelliLang/java-support/org/intellij/plugins/intelliLang/inject/java/ConcatenationInjector.java b/plugins/IntelliLang/java-support/org/intellij/plugins/intelliLang/inject/java/ConcatenationInjector.java index 15c79cbaa3c5..b8dca4df4983 100644 --- a/plugins/IntelliLang/java-support/org/intellij/plugins/intelliLang/inject/java/ConcatenationInjector.java +++ b/plugins/IntelliLang/java-support/org/intellij/plugins/intelliLang/inject/java/ConcatenationInjector.java @@ -142,7 +142,7 @@ public class ConcatenationInjector implements ConcatenationAwareInjector { boolean unparsable) { InjectorUtils.registerInjection(language, list, containingFile, registrar); InjectorUtils.registerSupport(mySupport, settingsAvailable, registrar); - if (unparsable) InjectorUtils.putInjectedFileUserData(registrar, InjectedLanguageUtil.FRANKENSTEIN_INJECTION, Boolean.TRUE); + InjectorUtils.putInjectedFileUserData(registrar, InjectedLanguageUtil.FRANKENSTEIN_INJECTION, unparsable ? Boolean.TRUE : null); } @Override diff --git a/plugins/IntelliLang/java-support/resources/javaInjections.xml b/plugins/IntelliLang/java-support/resources/javaInjections.xml index 78ef7006dcae..7bbd374ae8b1 100644 --- a/plugins/IntelliLang/java-support/resources/javaInjections.xml +++ b/plugins/IntelliLang/java-support/resources/javaInjections.xml @@ -67,7 +67,7 @@ </injection> <injection language="RegExp" injector-id="java"> <display-name>Pattern.regexp (javax.validation.constraints)</display-name> - <place><![CDATA[psiParameter().ofMethod(0, psiMethod().withName("regexp").withParameters().definedInClass("javax.validation.constraints.Pattern"))]]></place> + <place><![CDATA[psiMethod().withName("regexp").withParameters().definedInClass("javax.validation.constraints.Pattern")]]></place> </injection> <injection language="HQL" injector-id="java"> <display-name>Session.createQuery (org.hibernate)</display-name> diff --git a/plugins/android/jps-plugin/src/org/jetbrains/jps/android/AndroidDexBuilder.java b/plugins/android/jps-plugin/src/org/jetbrains/jps/android/AndroidDexBuilder.java index a3f1429da95c..dd06b93a89e4 100644 --- a/plugins/android/jps-plugin/src/org/jetbrains/jps/android/AndroidDexBuilder.java +++ b/plugins/android/jps-plugin/src/org/jetbrains/jps/android/AndroidDexBuilder.java @@ -39,10 +39,7 @@ import org.jetbrains.jps.builders.BuildOutputConsumer; import org.jetbrains.jps.builders.BuildRootDescriptor; import org.jetbrains.jps.builders.DirtyFilesHolder; import org.jetbrains.jps.cmdline.ClasspathBootstrap; -import org.jetbrains.jps.incremental.CompileContext; -import org.jetbrains.jps.incremental.ExternalProcessUtil; -import org.jetbrains.jps.incremental.ProjectBuildException; -import org.jetbrains.jps.incremental.TargetBuilder; +import org.jetbrains.jps.incremental.*; import org.jetbrains.jps.incremental.messages.BuildMessage; import org.jetbrains.jps.incremental.messages.CompilerMessage; import org.jetbrains.jps.incremental.messages.ProgressMessage; @@ -77,7 +74,7 @@ public class AndroidDexBuilder extends TargetBuilder<BuildRootDescriptor, Androi try { if (!doDexBuild(buildTarget, context, holder.hasDirtyFiles())) { - throw new ProjectBuildException(); + throw new StopBuildException(); } } catch (ProjectBuildException e) { diff --git a/plugins/android/jps-plugin/src/org/jetbrains/jps/android/AndroidPackagingBuilder.java b/plugins/android/jps-plugin/src/org/jetbrains/jps/android/AndroidPackagingBuilder.java index b417740b769d..533957f0cca5 100644 --- a/plugins/android/jps-plugin/src/org/jetbrains/jps/android/AndroidPackagingBuilder.java +++ b/plugins/android/jps-plugin/src/org/jetbrains/jps/android/AndroidPackagingBuilder.java @@ -22,10 +22,7 @@ import org.jetbrains.jps.builders.BuildOutputConsumer; import org.jetbrains.jps.builders.BuildRootDescriptor; import org.jetbrains.jps.builders.DirtyFilesHolder; import org.jetbrains.jps.builders.java.JavaModuleBuildTargetType; -import org.jetbrains.jps.incremental.CompileContext; -import org.jetbrains.jps.incremental.ModuleBuildTarget; -import org.jetbrains.jps.incremental.ProjectBuildException; -import org.jetbrains.jps.incremental.TargetBuilder; +import org.jetbrains.jps.incremental.*; import org.jetbrains.jps.incremental.messages.BuildMessage; import org.jetbrains.jps.incremental.messages.CompilerMessage; import org.jetbrains.jps.incremental.messages.ProgressMessage; @@ -80,15 +77,15 @@ public class AndroidPackagingBuilder extends TargetBuilder<BuildRootDescriptor, fillStates(modules, resourcesStates, assetsStates, manifestFiles); if (!doCaching(context, modules, resourcesStates)) { - throw new ProjectBuildException(); + throw new StopBuildException(); } if (!doResourcePackaging(context, modules, resourcesStates, assetsStates, manifestFiles)) { - throw new ProjectBuildException(); + throw new StopBuildException(); } if (!doPackaging(context, modules, outputConsumer)) { - throw new ProjectBuildException(); + throw new StopBuildException(); } } catch (ProjectBuildException e) { diff --git a/plugins/ant/jps-plugin/src/org/jetbrains/jps/ant/build/AntArtifactBuildTaskProvider.java b/plugins/ant/jps-plugin/src/org/jetbrains/jps/ant/build/AntArtifactBuildTaskProvider.java index b9f712887cfc..dd5864a11631 100644 --- a/plugins/ant/jps-plugin/src/org/jetbrains/jps/ant/build/AntArtifactBuildTaskProvider.java +++ b/plugins/ant/jps-plugin/src/org/jetbrains/jps/ant/build/AntArtifactBuildTaskProvider.java @@ -35,10 +35,7 @@ import org.jetbrains.jps.ant.model.JpsAntInstallation; import org.jetbrains.jps.ant.model.artifacts.JpsAntArtifactExtension; import org.jetbrains.jps.ant.model.impl.JpsAntInstallationImpl; import org.jetbrains.jps.builders.artifacts.ArtifactBuildTaskProvider; -import org.jetbrains.jps.incremental.BuildTask; -import org.jetbrains.jps.incremental.CompileContext; -import org.jetbrains.jps.incremental.ExternalProcessUtil; -import org.jetbrains.jps.incremental.ProjectBuildException; +import org.jetbrains.jps.incremental.*; import org.jetbrains.jps.incremental.messages.BuildMessage; import org.jetbrains.jps.incremental.messages.CompilerMessage; import org.jetbrains.jps.model.JpsDummyElement; @@ -98,20 +95,20 @@ public class AntArtifactBuildTaskProvider extends ArtifactBuildTaskProvider { jdkLibrary = project.getModel().getGlobal().getLibraryCollection().findLibrary(jdkName, JpsJavaSdkType.INSTANCE); if (jdkLibrary == null) { reportError(context, "JDK '" + jdkName + "' not found"); - throw new ProjectBuildException(); + throw new StopBuildException(); } } else { JpsSdkReference<JpsDummyElement> reference = project.getSdkReferencesTable().getSdkReference(JpsJavaSdkType.INSTANCE); if (reference == null) { reportError(context, "project JDK is not specified"); - throw new ProjectBuildException(); + throw new StopBuildException(); } jdkLibrary = reference.resolve(); if (jdkLibrary == null) { reportError(context, "JDK '" + reference.getSdkName() + "' not found"); - throw new ProjectBuildException(); + throw new StopBuildException(); } } JpsSdk<?> jdk = jdkLibrary.getProperties(); @@ -120,7 +117,7 @@ public class AntArtifactBuildTaskProvider extends ArtifactBuildTaskProvider { myExtension.getFileUrl()); if (antInstallation == null) { reportError(context, "Ant installation is not configured"); - throw new ProjectBuildException(); + throw new StopBuildException(); } List<String> classpath = new ArrayList<String>(); @@ -199,7 +196,7 @@ public class AntArtifactBuildTaskProvider extends ArtifactBuildTaskProvider { handler.startNotify(); handler.waitFor(); if (hasErrors.get()) { - throw new ProjectBuildException(); + throw new StopBuildException(); } } catch (IOException e) { diff --git a/plugins/ant/src/com/intellij/lang/ant/dom/AntDomExtender.java b/plugins/ant/src/com/intellij/lang/ant/dom/AntDomExtender.java index fd5cf56d2b1d..02ab264cc894 100644 --- a/plugins/ant/src/com/intellij/lang/ant/dom/AntDomExtender.java +++ b/plugins/ant/src/com/intellij/lang/ant/dom/AntDomExtender.java @@ -29,6 +29,7 @@ import com.intellij.psi.xml.XmlTag; import com.intellij.util.xml.*; import com.intellij.util.xml.reflect.*; import org.apache.tools.ant.Task; +import org.apache.tools.ant.types.Reference; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -248,6 +249,9 @@ public class AntDomExtender extends DomExtender<AntDomElement>{ type = Boolean.class; converterClass = AntBooleanConverter.class; } + else if (isAssignableFrom(Reference.class.getName(), attributeType)) { + converterClass = AntDomRefIdConverter.class; + } } } diff --git a/plugins/cvs/cvs-core/src/com/intellij/cvsSupport2/connections/ConnectionOnProcess.java b/plugins/cvs/cvs-core/src/com/intellij/cvsSupport2/connections/ConnectionOnProcess.java index 8401df2f4c6b..bcf34e8f48a0 100644 --- a/plugins/cvs/cvs-core/src/com/intellij/cvsSupport2/connections/ConnectionOnProcess.java +++ b/plugins/cvs/cvs-core/src/com/intellij/cvsSupport2/connections/ConnectionOnProcess.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2013 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -46,7 +46,7 @@ public abstract class ConnectionOnProcess implements IConnection { private final ErrorRegistry myErrorRegistry; private boolean myContainsError = false; - + protected final StringBuffer myErrorText = new StringBuffer(); private Future<?> myStdErrFuture; private ReadProcessThread myErrThread; @@ -142,7 +142,7 @@ public abstract class ConnectionOnProcess implements IConnection { protected synchronized void execute(GeneralCommandLine commandLine) throws AuthenticationException { try { - commandLine.setEnvParams(EnvironmentUtil.getEnvironmentProperties()); + commandLine.setEnvironment(EnvironmentUtil.getEnvironmentProperties()); myProcess = commandLine.createProcess(); myErrThread = new ReadProcessThread( diff --git a/plugins/git4idea/src/git4idea/commands/GitHandler.java b/plugins/git4idea/src/git4idea/commands/GitHandler.java index 952574ca4bcb..0669a9ee164e 100644 --- a/plugins/git4idea/src/git4idea/commands/GitHandler.java +++ b/plugins/git4idea/src/git4idea/commands/GitHandler.java @@ -451,7 +451,7 @@ public abstract class GitHandler { LOG.debug(String.format("handler=%s, port=%s", myHandlerNo, port)); addAuthListener(httpAuthenticator); } - myCommandLine.setEnvParams(myEnv); + myCommandLine.setEnvironment(myEnv); // start process myProcess = startProcess(); startHandlingStreams(); diff --git a/plugins/git4idea/src/git4idea/push/GitPushLog.java b/plugins/git4idea/src/git4idea/push/GitPushLog.java index 9fc48df5fa12..8c492ed2e770 100644 --- a/plugins/git4idea/src/git4idea/push/GitPushLog.java +++ b/plugins/git4idea/src/git4idea/push/GitPushLog.java @@ -371,6 +371,7 @@ class GitPushLog extends JPanel implements TypeSafeDataProvider { GitBranch dest = branchInfo.getDestBranch(); GitPushBranchInfo.Type type = branchInfo.getType(); + final String showingRecentCommits = ", showing " + GitPusher.RECENT_COMMITS_NUMBER + " recent commits"; String text = fromBranch.getName(); SimpleTextAttributes attrs = SimpleTextAttributes.REGULAR_ATTRIBUTES; String additionalText = ""; @@ -384,11 +385,11 @@ class GitPushLog extends JPanel implements TypeSafeDataProvider { case NEW_BRANCH: text += " -> +" + dest.getName(); attrs = SimpleTextAttributes.REGULAR_BOLD_ATTRIBUTES; - additionalText = " new branch will be created."; + additionalText = " new branch will be created" + showingRecentCommits; break; case NO_TRACKED_OR_TARGET: attrs = SimpleTextAttributes.REGULAR_BOLD_ATTRIBUTES; - additionalText = " no tracked branch. Use checkbox below to push branch to manually specified."; + additionalText = " no tracked branch. Use checkbox below to push branch to manually specified" + showingRecentCommits; break; } renderer.append(text, attrs); diff --git a/plugins/git4idea/src/git4idea/push/GitPusher.java b/plugins/git4idea/src/git4idea/push/GitPusher.java index fd06e8c149d4..75f31576f6fe 100644 --- a/plugins/git4idea/src/git4idea/push/GitPusher.java +++ b/plugins/git4idea/src/git4idea/push/GitPusher.java @@ -59,6 +59,11 @@ import java.util.concurrent.atomic.AtomicInteger; */ public final class GitPusher { + /** + * if diff-log is not available (new branch is created, for example), we show a few recent commits made on the branch + */ + static final int RECENT_COMMITS_NUMBER = 5; + @Deprecated static final GitRemoteBranch NO_TARGET_BRANCH = new GitStandardRemoteBranch(GitRemote.DOT, "", GitBranch.DUMMY_HASH); @@ -182,7 +187,7 @@ public final class GitPusher { List<GitCommit> commits; GitPushBranchInfo.Type type; if (dest == NO_TARGET_BRANCH) { - commits = collectCommitsToPushForNewBranch(repository, source, dest.getRemote()); + commits = collectRecentCommitsOnBranch(repository, source); type = GitPushBranchInfo.Type.NO_TRACKED_OR_TARGET; } else if (GitUtil.repoContainsRemoteBranch(repository, dest)) { @@ -190,7 +195,7 @@ public final class GitPusher { type = GitPushBranchInfo.Type.STANDARD; } else { - commits = collectCommitsToPushForNewBranch(repository, source, dest.getRemote()); + commits = collectRecentCommitsOnBranch(repository, source); type = GitPushBranchInfo.Type.NEW_BRANCH; } commitsByBranch.put(source, new GitPushBranchInfo(source, dest, commits, type)); @@ -199,13 +204,8 @@ public final class GitPusher { return new GitCommitsByBranch(commitsByBranch); } - @NotNull - private static List<GitCommit> collectCommitsToPushForNewBranch(@NotNull GitRepository repository, @NotNull GitBranch source, - @NotNull GitRemote remote) throws VcsException { - // `git log new_branch --not --remotes=origin` - // shows all commits that are in the given branch, but not in any remote branches in the given remote - return GitHistoryUtils.history(repository.getProject(), repository.getRoot(), - source.getName(), "--not", "--remotes=" + remote.getName()); + private List<GitCommit> collectRecentCommitsOnBranch(GitRepository repository, GitBranch source) throws VcsException { + return GitHistoryUtils.history(myProject, repository.getRoot(), "--max-count=" + RECENT_COMMITS_NUMBER, source.getName()); } @NotNull @@ -239,12 +239,7 @@ public final class GitPusher { GitCommitsByRepoAndBranch commits = pushInfo.getCommits(); for (GitRepository repository : commits.getRepositories()) { - GitCommitsByBranch commitsForRepo = commits.get(repository); - GitLocalBranch sourceBranch = pushInfo.getPushSpecs().get(repository).getSource(); - if (commitsForRepo.get(sourceBranch).getType() == GitPushBranchInfo.Type.STANDARD && - commitsForRepo.getAllCommits().size() == 0) { - // don't push repositories where there is nothing to push. - // however, do push if new branch is created, even without commits + if (commits.get(repository).getAllCommits().size() == 0) { // don't push repositories where there is nothing to push. Note that when a branch is created, several recent commits are stored in the pushInfo. continue; } GitPushRepoResult repoResult = pushRepository(pushInfo, commits, repository); diff --git a/plugins/google-app-engine/google-app-engine.iml b/plugins/google-app-engine/google-app-engine.iml index 452bb1f80aed..52217861ad17 100644 --- a/plugins/google-app-engine/google-app-engine.iml +++ b/plugins/google-app-engine/google-app-engine.iml @@ -16,7 +16,6 @@ <orderEntry type="module" module-name="lang-api" /> <orderEntry type="module" module-name="openapi" /> <orderEntry type="module" module-name="debugger-openapi" /> - <orderEntry type="module" module-name="codeInsight-tests" scope="TEST" /> <orderEntry type="module" module-name="testFramework-java" scope="TEST" /> <orderEntry type="library" scope="TEST" name="JUnit4" level="project" /> <orderEntry type="module" module-name="xml" scope="TEST" /> diff --git a/plugins/google-app-engine/jps-plugin/google-app-engine-jps-plugin.iml b/plugins/google-app-engine/jps-plugin/google-app-engine-jps-plugin.iml index 01751f13d84f..e471a6a62370 100644 --- a/plugins/google-app-engine/jps-plugin/google-app-engine-jps-plugin.iml +++ b/plugins/google-app-engine/jps-plugin/google-app-engine-jps-plugin.iml @@ -12,7 +12,6 @@ <orderEntry type="module" module-name="jps-model-api" /> <orderEntry type="module" module-name="jps-model-serialization" /> <orderEntry type="module" module-name="jps-model-impl" scope="TEST" /> - <orderEntry type="module" module-name="javaee-jps-plugin" /> <orderEntry type="module" module-name="appEngine-runtime" /> </component> </module> diff --git a/plugins/google-app-engine/source/com/intellij/appengine/facet/AppEngineSupportProvider.java b/plugins/google-app-engine/source/com/intellij/appengine/facet/AppEngineSupportProvider.java index b5b1be386585..255145fd9449 100644 --- a/plugins/google-app-engine/source/com/intellij/appengine/facet/AppEngineSupportProvider.java +++ b/plugins/google-app-engine/source/com/intellij/appengine/facet/AppEngineSupportProvider.java @@ -39,6 +39,10 @@ import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VfsUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.packaging.artifacts.Artifact; +import com.intellij.packaging.artifacts.ArtifactManager; +import com.intellij.packaging.artifacts.ArtifactType; +import com.intellij.packaging.elements.ArtifactRootElement; +import com.intellij.packaging.elements.PackagingElementFactory; import com.intellij.packaging.impl.artifacts.ArtifactUtil; import com.intellij.ui.DocumentAdapter; import com.intellij.ui.HyperlinkLabel; @@ -94,28 +98,29 @@ public class AppEngineSupportProvider extends FacetBasedFrameworkSupportProvider private void addSupport(final Module module, final ModifiableRootModel rootModel, String sdkPath, @Nullable PersistenceApi persistenceApi) { super.addSupport(module, rootModel, null, null); - final VirtualFile descriptorDir = AppEngineWebIntegration.getInstance().suggestParentDirectoryForAppEngineWebXml(module, rootModel); - if (descriptorDir != null) { - createFileFromTemplate(AppEngineTemplateGroupDescriptorFactory.APP_ENGINE_WEB_XML_TEMPLATE, descriptorDir, - AppEngineUtil.APP_ENGINE_WEB_XML_NAME); - } - final AppEngineFacet appEngineFacet = AppEngineFacet.getAppEngineFacetByModule(module); LOG.assertTrue(appEngineFacet != null); final AppEngineFacetConfiguration facetConfiguration = appEngineFacet.getConfiguration(); facetConfiguration.setSdkHomePath(sdkPath); final AppEngineSdk sdk = appEngineFacet.getSdk(); - final Artifact artifact = findContainingArtifact(appEngineFacet); + final Artifact artifact = findOrCreateArtifact(appEngineFacet); + + final VirtualFile descriptorDir = AppEngineWebIntegration.getInstance().suggestParentDirectoryForAppEngineWebXml(module, rootModel); + if (descriptorDir != null) { + VirtualFile descriptor = createFileFromTemplate(AppEngineTemplateGroupDescriptorFactory.APP_ENGINE_WEB_XML_TEMPLATE, descriptorDir, + AppEngineUtil.APP_ENGINE_WEB_XML_NAME); + if (descriptor != null) { + AppEngineWebIntegration.getInstance().addDescriptor(artifact, module.getProject(), descriptor); + } + } final Project project = module.getProject(); AppEngineWebIntegration.getInstance().setupRunConfiguration(rootModel, sdk, artifact, project); final Library apiJar = addProjectLibrary(module, "AppEngine API", sdk.getLibUserDirectoryPath(), VirtualFile.EMPTY_ARRAY); rootModel.addLibraryEntry(apiJar); - if (artifact != null) { - AppEngineWebIntegration.getInstance().addLibraryToArtifact(apiJar, artifact, project); - } + AppEngineWebIntegration.getInstance().addLibraryToArtifact(apiJar, artifact, project); if (persistenceApi != null) { facetConfiguration.setRunEnhancerOnMake(true); @@ -146,21 +151,25 @@ public class AppEngineSupportProvider extends FacetBasedFrameworkSupportProvider } final Library library = addProjectLibrary(module, "AppEngine ORM", sdk.getOrmLibDirectoryPath(), sdk.getOrmLibSources()); rootModel.addLibraryEntry(library); - if (artifact != null) { - AppEngineWebIntegration.getInstance().addLibraryToArtifact(library, artifact, project); - } + AppEngineWebIntegration.getInstance().addLibraryToArtifact(library, artifact, project); } } - @Nullable - private static Artifact findContainingArtifact(AppEngineFacet appEngineFacet) { - final Collection<Artifact> artifacts = ArtifactUtil.getArtifactsContainingModuleOutput(appEngineFacet.getModule()); + @NotNull + private static Artifact findOrCreateArtifact(AppEngineFacet appEngineFacet) { + Module module = appEngineFacet.getModule(); + ArtifactType artifactType = AppEngineWebIntegration.getInstance().getAppEngineTargetArtifactType(); + final Collection<Artifact> artifacts = ArtifactUtil.getArtifactsContainingModuleOutput(module); for (Artifact artifact : artifacts) { - if (AppEngineWebIntegration.getInstance().getAppEngineTargetArtifactType().equals(artifact.getArtifactType())) { + if (artifactType.equals(artifact.getArtifactType())) { return artifact; } } - return null; + ArtifactManager artifactManager = ArtifactManager.getInstance(module.getProject()); + PackagingElementFactory elementFactory = PackagingElementFactory.getInstance(); + ArtifactRootElement<?> root = elementFactory.createArtifactRootElement(); + elementFactory.getOrCreateDirectory(root, "WEB-INF/classes").addOrFindChild(elementFactory.createModuleOutput(module)); + return artifactManager.addArtifact(module.getName(), artifactType, root); } private static Library addProjectLibrary(final Module module, final String name, final String path, final VirtualFile[] sources) { diff --git a/plugins/google-app-engine/source/com/intellij/appengine/facet/AppEngineWebIntegration.java b/plugins/google-app-engine/source/com/intellij/appengine/facet/AppEngineWebIntegration.java index 82076bf1d301..f1d8a67f6779 100644 --- a/plugins/google-app-engine/source/com/intellij/appengine/facet/AppEngineWebIntegration.java +++ b/plugins/google-app-engine/source/com/intellij/appengine/facet/AppEngineWebIntegration.java @@ -52,4 +52,7 @@ public abstract class AppEngineWebIntegration { public abstract void addLibraryToArtifact(@NotNull Library library, @NotNull Artifact artifact, @NotNull Project project); public abstract List<? extends AppEngineSdk> getSdkForConfiguredDevServers(); + + public void addDescriptor(@NotNull Artifact artifact, @NotNull Project project, @NotNull VirtualFile descriptor) { + } } diff --git a/plugins/google-app-engine/source/com/intellij/appengine/facet/impl/AppEngineCommunityWebIntegration.java b/plugins/google-app-engine/source/com/intellij/appengine/facet/impl/AppEngineCommunityWebIntegration.java index 060355357829..90ea918678ee 100644 --- a/plugins/google-app-engine/source/com/intellij/appengine/facet/impl/AppEngineCommunityWebIntegration.java +++ b/plugins/google-app-engine/source/com/intellij/appengine/facet/impl/AppEngineCommunityWebIntegration.java @@ -94,4 +94,9 @@ public class AppEngineCommunityWebIntegration extends AppEngineWebIntegration { public List<? extends AppEngineSdk> getSdkForConfiguredDevServers() { return Collections.emptyList(); } + + @Override + public void addDescriptor(@NotNull Artifact artifact, @NotNull Project project, @NotNull VirtualFile descriptor) { + ArtifactManager.getInstance(project).addElementsToDirectory(artifact, "WEB-INF", PackagingElementFactory.getInstance().createFileCopy(descriptor.getPath(), null)); + } } diff --git a/plugins/gradle/gradle.iml b/plugins/gradle/gradle.iml index daa6aa3e8091..a7b46ec7c4d6 100644 --- a/plugins/gradle/gradle.iml +++ b/plugins/gradle/gradle.iml @@ -279,7 +279,8 @@ </SOURCES> </library> </orderEntry> - <orderEntry type="module" module-name="external-system" /> + <orderEntry type="module" module-name="external-system-impl" /> + <orderEntry type="module" module-name="external-system-api" /> </component> </module> diff --git a/plugins/gradle/src/META-INF/plugin.xml b/plugins/gradle/src/META-INF/plugin.xml index 5be26a31ac3b..2000beeb443f 100644 --- a/plugins/gradle/src/META-INF/plugin.xml +++ b/plugins/gradle/src/META-INF/plugin.xml @@ -37,8 +37,6 @@ <library.presentationProvider implementation="org.jetbrains.plugins.gradle.config.GradleLibraryPresentationProvider" order="last"/> <java.elementFinder implementation="org.jetbrains.plugins.gradle.config.GradleClassFinder"/> <!--<projectOpenProcessor implementation="com.intellij.openapi.externalSystem.service.project.wizard.ExternalProjectOpenProcessor"/>--> - <colorAndFontPanelFactory implementation="org.jetbrains.plugins.gradle.config.GradleColorAndFontPanelFactory"/> - <colorAndFontDescriptorProvider implementation="org.jetbrains.plugins.gradle.config.GradleColorAndFontDescriptorsProvider"/> <externalSystemManager implementation="org.jetbrains.plugins.gradle.GradleManager"/> <postStartupActivity implementation="org.jetbrains.plugins.gradle.sync.GradleStartupActivity"/> @@ -112,7 +110,6 @@ <actions> <!-- Tool window toolbar actions --> - <action id="Gradle.LinkToProject" class="org.jetbrains.plugins.gradle.action.GradleLinkToProjectAction"/> <action id="Gradle.RefreshProject" class="org.jetbrains.plugins.gradle.action.GradleRefreshProjectAction" icon="AllIcons.Actions.Refresh"/> <action id="Gradle.OpenScript" class="org.jetbrains.plugins.gradle.action.GradleOpenScriptAction" icon="GradleIcons.GradleNavigate"/> <action id="Gradle.Help.ToolWindow" class="org.jetbrains.plugins.gradle.action.GradleToolWindowHelpAction" icon="AllIcons.Actions.Help"/> @@ -122,33 +119,6 @@ <reference id="Gradle.Help.ToolWindow"/> </group> - <!-- 'Sync project structure' tree nodes actions --> - <action id="Gradle.ImportEntity" class="org.jetbrains.plugins.gradle.action.GradleImportEntityAction" icon="GradleIcons.GradleImport"/> - <action id="Gradle.ShowConflict" class="org.jetbrains.plugins.gradle.action.GradleShowConflictDetailsAction" icon="AllIcons.Actions.Diff"/> - <action id="Gradle.RemoveEntity" class="org.jetbrains.plugins.gradle.action.GradleRemoveIdeEntityAction" icon="AllIcons.General.Remove"/> - <action id="Gradle.SyncOutdatedLibrary" class="org.jetbrains.plugins.gradle.action.GradleSyncAction" icon="GradleIcons.GradleSync"/> - <group id="Gradle.SyncTreeGroup"> - <reference id="Gradle.ImportEntity"/> - <reference id="Gradle.RemoveEntity"/> - <reference id="Gradle.ShowConflict"/> - <reference id="Gradle.SyncOutdatedLibrary"/> - </group> - - <!-- 'Sync project structure' tree filters --> - <action id="Gradle.SyncTreeFilter.None" class="org.jetbrains.plugins.gradle.action.GradleResetTreeFiltersAction"/> - <action id="Gradle.SyncTreeFilter.GradleLocal" class="org.jetbrains.plugins.gradle.action.GradleLocalSyncTreeFilterAction"/> - <action id="Gradle.SyncTreeFilter.IntellijLocal" class="org.jetbrains.plugins.gradle.action.IntellijLocalSyncTreeFilterAction"/> - <action id="Gradle.SyncTreeFilter.Conflict" class="org.jetbrains.plugins.gradle.action.GradleConflictSyncTreeFilterAction"/> - <action id="Gradle.SyncTreeFilter.Outdated" class="org.jetbrains.plugins.gradle.action.GradleOutdatedSyncTreeFilterAction"/> - <group id="Gradle.SyncTreeFilter"> - <reference id="Gradle.SyncTreeFilter.GradleLocal"/> - <reference id="Gradle.SyncTreeFilter.IntellijLocal"/> - <reference id="Gradle.SyncTreeFilter.Conflict"/> - <reference id="Gradle.SyncTreeFilter.Outdated"/> - <reference id="Gradle.SyncTreeFilter.None"/> - </group> - - <action id="Gradle.RebuildChangesTree" class="org.jetbrains.plugins.gradle.action.GradleRebuildStructureChangesTreeAction"/> <group id="Gradle.TasksGroup"> <reference ref="RunContextGroup"/> </group> diff --git a/plugins/gradle/src/org/jetbrains/plugins/gradle/GradleManager.java b/plugins/gradle/src/org/jetbrains/plugins/gradle/GradleManager.java index a920ed8858e1..f7bd4be6ff5e 100644 --- a/plugins/gradle/src/org/jetbrains/plugins/gradle/GradleManager.java +++ b/plugins/gradle/src/org/jetbrains/plugins/gradle/GradleManager.java @@ -17,17 +17,25 @@ package org.jetbrains.plugins.gradle; import com.intellij.execution.ExecutionException; import com.intellij.execution.configurations.SimpleJavaParameters; +import com.intellij.externalSystem.JavaProjectData; import com.intellij.openapi.application.PathManager; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.externalSystem.ExternalSystemManager; import com.intellij.openapi.externalSystem.build.ExternalSystemBuildManager; import com.intellij.openapi.externalSystem.model.ProjectSystemId; import com.intellij.openapi.externalSystem.service.project.ExternalSystemProjectResolver; -import com.intellij.openapi.externalSystem.util.ExternalSystemUtil; +import com.intellij.openapi.externalSystem.util.ExternalSystemApiUtil; +import com.intellij.openapi.module.EmptyModuleType; +import com.intellij.openapi.module.JavaModuleType; +import com.intellij.openapi.module.ModuleType; +import com.intellij.openapi.module.StdModuleTypes; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.NotNullLazyValue; import com.intellij.openapi.util.text.StringUtil; +import com.intellij.pom.java.LanguageLevel; import com.intellij.util.Function; +import com.intellij.util.PathUtil; +import com.intellij.util.PathsList; import com.intellij.util.containers.ContainerUtilRt; import org.gradle.tooling.ProjectConnection; import org.jetbrains.annotations.NotNull; @@ -68,7 +76,7 @@ public class GradleManager protected List<GradleProjectResolverExtension> compute() { List<GradleProjectResolverExtension> result = ContainerUtilRt.newArrayList(); Collections.addAll(result, GradleProjectResolverExtension.EP_NAME.getExtensions()); - ExternalSystemUtil.orderAwareSort(result); + ExternalSystemApiUtil.orderAwareSort(result); return result; } }; @@ -149,8 +157,10 @@ public class GradleManager @Override public void enhanceParameters(@NotNull SimpleJavaParameters parameters) throws ExecutionException { + PathsList classPath = parameters.getClassPath(); + // Gradle i18n bundle. - ExternalSystemUtil.addBundle(parameters.getClassPath(), GradleBundle.PATH_TO_BUNDLE, GradleBundle.class); + ExternalSystemApiUtil.addBundle(classPath, GradleBundle.PATH_TO_BUNDLE, GradleBundle.class); // Gradle tool jars. String toolingApiPath = PathManager.getJarPathForClass(ProjectConnection.class); @@ -170,7 +180,18 @@ public class GradleManager throw new ExecutionException("Can't find gradle libraries at " + gradleJarsDir.getAbsolutePath()); } for (String jar : gradleJars) { - parameters.getClassPath().add(new File(gradleJarsDir, jar).getAbsolutePath()); + classPath.add(new File(gradleJarsDir, jar).getAbsolutePath()); + } + + List<String> additionalEntries = ContainerUtilRt.newArrayList(); + ContainerUtilRt.addIfNotNull(additionalEntries, PathUtil.getJarPathForClass(JavaProjectData.class)); + ContainerUtilRt.addIfNotNull(additionalEntries, PathUtil.getJarPathForClass(LanguageLevel.class)); + ContainerUtilRt.addIfNotNull(additionalEntries, PathUtil.getJarPathForClass(StdModuleTypes.class)); + ContainerUtilRt.addIfNotNull(additionalEntries, PathUtil.getJarPathForClass(JavaModuleType.class)); + ContainerUtilRt.addIfNotNull(additionalEntries, PathUtil.getJarPathForClass(ModuleType.class)); + ContainerUtilRt.addIfNotNull(additionalEntries, PathUtil.getJarPathForClass(EmptyModuleType.class)); + for (String entry : additionalEntries) { + classPath.add(entry); } for (GradleProjectResolverExtension extension : RESOLVER_EXTENSIONS.getValue()) { diff --git a/plugins/gradle/src/org/jetbrains/plugins/gradle/action/AbstractGradleSyncTreeFilterAction.java b/plugins/gradle/src/org/jetbrains/plugins/gradle/action/AbstractGradleSyncTreeFilterAction.java deleted file mode 100644 index bd558c8f5c0b..000000000000 --- a/plugins/gradle/src/org/jetbrains/plugins/gradle/action/AbstractGradleSyncTreeFilterAction.java +++ /dev/null @@ -1,122 +0,0 @@ -package org.jetbrains.plugins.gradle.action; - -import com.intellij.openapi.actionSystem.AnActionEvent; -import com.intellij.openapi.actionSystem.PlatformDataKeys; -import com.intellij.openapi.actionSystem.ToggleAction; -import com.intellij.openapi.editor.colors.EditorColorsListener; -import com.intellij.openapi.editor.colors.EditorColorsManager; -import com.intellij.openapi.editor.colors.EditorColorsScheme; -import com.intellij.openapi.editor.colors.TextAttributesKey; -import com.intellij.openapi.externalSystem.ui.ExternalProjectStructureNodeFilter; -import com.intellij.openapi.options.colors.AttributesDescriptor; -import com.intellij.openapi.project.Project; -import com.intellij.openapi.util.text.StringUtil; -import com.intellij.util.ui.ColorIcon; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; -import org.jetbrains.plugins.gradle.settings.GradleSettings; -import com.intellij.openapi.externalSystem.ui.ExternalProjectStructureTreeModel; -import com.intellij.openapi.externalSystem.ui.ProjectStructureNode; -import org.jetbrains.plugins.gradle.util.GradleUtil; - -import javax.swing.*; -import java.awt.*; - -/** - * @author Denis Zhdanov - * @since 3/7/12 3:48 PM - */ -public abstract class AbstractGradleSyncTreeFilterAction extends ToggleAction { - - @NotNull private final ExternalProjectStructureNodeFilter myFilter; - @NotNull private final TextAttributesKey myAttributesKey; - - private Color myColor; - private boolean myIconChanged; - - protected AbstractGradleSyncTreeFilterAction(@NotNull AttributesDescriptor descriptor) { - myFilter = createFilter(descriptor.getKey()); - myAttributesKey = descriptor.getKey(); - getTemplatePresentation().setText(descriptor.getDisplayName()); - updateIcon(EditorColorsManager.getInstance().getGlobalScheme()); - EditorColorsManager.getInstance().addEditorColorsListener(new EditorColorsListener() { - @Override - public void globalSchemeChange(EditorColorsScheme scheme) { - updateIcon(scheme); - } - }); - } - - @Override - public boolean isSelected(AnActionEvent e) { - final ExternalProjectStructureTreeModel model = GradleUtil.getProjectStructureTreeModel(e.getDataContext()); - if (model == null) { - return false; - } - - return model.hasFilter(myFilter); - } - - @Override - public void setSelected(AnActionEvent e, boolean state) { - final ExternalProjectStructureTreeModel treeModel = GradleUtil.getProjectStructureTreeModel(e.getDataContext()); - if (treeModel == null) { - return; - } - if (state) { - treeModel.addFilter(myFilter); - } - else { - treeModel.removeFilter(myFilter); - } - } - - @Override - public void update(AnActionEvent e) { - super.update(e); - - final Project project = PlatformDataKeys.PROJECT.getData(e.getDataContext()); - if (project == null || StringUtil.isEmpty(GradleSettings.getInstance(project).getLinkedExternalProjectPath())) { - e.getPresentation().setEnabled(false); - return; - } - else { - e.getPresentation().setEnabled(true); - } - - if (myIconChanged) { - e.getPresentation().setIcon(getTemplatePresentation().getIcon()); - myIconChanged = false; - } - } - - public static ExternalProjectStructureNodeFilter createFilter(@NotNull TextAttributesKey key) { - return new MyFilter(key); - } - - private void updateIcon(@Nullable EditorColorsScheme scheme) { - if (scheme == null) { - return; - } - final Color color = scheme.getAttributes(myAttributesKey).getForegroundColor(); - if (color != null && !color.equals(myColor)) { - getTemplatePresentation().setIcon(new ColorIcon(new JLabel("").getFont().getSize(), color)); - myColor = color; - myIconChanged = true; - } - } - - private static class MyFilter implements ExternalProjectStructureNodeFilter { - - @NotNull private final TextAttributesKey myKey; - - MyFilter(@NotNull TextAttributesKey key) { - myKey = key; - } - - @Override - public boolean isVisible(@NotNull ProjectStructureNode<?> node) { - return myKey.equals(node.getDescriptor().getAttributes()); - } - } -} diff --git a/plugins/gradle/src/org/jetbrains/plugins/gradle/action/AbstractGradleSyncTreeNodeAction.java b/plugins/gradle/src/org/jetbrains/plugins/gradle/action/AbstractGradleSyncTreeNodeAction.java deleted file mode 100644 index 04746230c28b..000000000000 --- a/plugins/gradle/src/org/jetbrains/plugins/gradle/action/AbstractGradleSyncTreeNodeAction.java +++ /dev/null @@ -1,119 +0,0 @@ -package org.jetbrains.plugins.gradle.action; - -import com.intellij.openapi.actionSystem.AnAction; -import com.intellij.openapi.actionSystem.AnActionEvent; -import com.intellij.openapi.actionSystem.PlatformDataKeys; -import com.intellij.openapi.actionSystem.Presentation; -import com.intellij.openapi.components.ServiceManager; -import com.intellij.openapi.editor.colors.TextAttributesKey; -import com.intellij.openapi.externalSystem.model.ExternalSystemDataKeys; -import com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskType; -import com.intellij.openapi.externalSystem.ui.ProjectStructureNode; -import com.intellij.openapi.project.Project; -import com.intellij.ui.treeStructure.Tree; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; -import com.intellij.openapi.externalSystem.service.task.ExternalSystemTaskManager; -import org.jetbrains.plugins.gradle.util.GradleConstants; - -import java.util.Collection; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; - -/** - * Common super class for actions that are invoked on 'sync project structures' tree nodes. - * <p/> - * Not thread-safe. - * - * @author Denis Zhdanov - * @since 2/29/12 4:15 PM - */ -public abstract class AbstractGradleSyncTreeNodeAction extends AnAction { - - private static final Map<String, Helper> HELPERS = new HashMap<String, Helper>(); - static { - HELPERS.put(GradleConstants.SYNC_TREE_CONTEXT_MENU_PLACE, new ContextMenuHelper()); - } - - @SuppressWarnings("unchecked") - @Override - public void update(AnActionEvent e) { - final Project project = PlatformDataKeys.PROJECT.getData(e.getDataContext()); - final Helper helper = HELPERS.get(e.getPlace()); - if (project == null || helper == null) { - e.getPresentation().setEnabled(false); - e.getPresentation().setVisible(false); - return; - } - Collection<ProjectStructureNode<?>> nodes = helper.getTargetNodes(e); - if (nodes != null) { - filterNodes(nodes); - } - helper.updatePresentation(nodes, e.getPresentation()); - if (e.getPresentation().isEnabled()) { - final ExternalSystemTaskManager taskManager = ServiceManager.getService(ExternalSystemTaskManager.class); - if (taskManager != null && taskManager.hasTaskOfTypeInProgress(ExternalSystemTaskType.RESOLVE_PROJECT)) { - e.getPresentation().setEnabled(false); - } - } - } - - @Override - public void actionPerformed(AnActionEvent e) { - final Project project = PlatformDataKeys.PROJECT.getData(e.getDataContext()); - final Helper helper = HELPERS.get(e.getPlace()); - if (project == null || helper == null) { - return; - } - final Collection<ProjectStructureNode<?>> nodes = helper.getTargetNodes(e); - if (nodes != null) { - filterNodes(nodes); - } - if (nodes == null || nodes.isEmpty()) { - return; - } - final Tree tree = ExternalSystemDataKeys.PROJECT_TREE.getData(e.getDataContext()); - if (tree != null) { - doActionPerformed(nodes, project, tree); - } - } - - protected abstract void doActionPerformed(@NotNull Collection<ProjectStructureNode<?>> nodes, - @NotNull Project project, - @NotNull Tree tree); - - protected void filterNodes(@NotNull Collection<ProjectStructureNode<?>> nodes) { - } - - protected static void filterNodesByAttributes(@NotNull Collection<ProjectStructureNode<?>> nodes, @NotNull TextAttributesKey key) { - for (Iterator<ProjectStructureNode<?>> iterator = nodes.iterator(); iterator.hasNext(); ) { - ProjectStructureNode<?> node = iterator.next(); - if (!key.equals(node.getDescriptor().getAttributes())) { - iterator.remove(); - } - } - } - - private interface Helper { - - @Nullable - Collection<ProjectStructureNode<?>> getTargetNodes(@NotNull AnActionEvent e); - - void updatePresentation(@Nullable Collection<ProjectStructureNode<?>> nodes, @NotNull Presentation presentation); - } - - private static class ContextMenuHelper implements Helper { - @Nullable - @Override - public Collection<ProjectStructureNode<?>> getTargetNodes(@NotNull AnActionEvent e) { - return ExternalSystemDataKeys.PROJECT_TREE_SELECTED_NODE.getData(e.getDataContext()); - } - - @Override - public void updatePresentation(@Nullable Collection<ProjectStructureNode<?>> nodes, @NotNull Presentation presentation) { - presentation.setVisible(true); - presentation.setEnabled(nodes != null && !nodes.isEmpty()); - } - } -} diff --git a/plugins/gradle/src/org/jetbrains/plugins/gradle/action/GradleConflictSyncTreeFilterAction.java b/plugins/gradle/src/org/jetbrains/plugins/gradle/action/GradleConflictSyncTreeFilterAction.java deleted file mode 100644 index 49c1f906c43b..000000000000 --- a/plugins/gradle/src/org/jetbrains/plugins/gradle/action/GradleConflictSyncTreeFilterAction.java +++ /dev/null @@ -1,14 +0,0 @@ -package org.jetbrains.plugins.gradle.action; - -import org.jetbrains.plugins.gradle.config.GradleColorAndFontDescriptorsProvider; - -/** - * @author Denis Zhdanov - * @since 3/7/12 6:08 PM - */ -public class GradleConflictSyncTreeFilterAction extends AbstractGradleSyncTreeFilterAction { - - public GradleConflictSyncTreeFilterAction() { - super(GradleColorAndFontDescriptorsProvider.CONFLICT); - } -} diff --git a/plugins/gradle/src/org/jetbrains/plugins/gradle/action/GradleImportEntityAction.java b/plugins/gradle/src/org/jetbrains/plugins/gradle/action/GradleImportEntityAction.java deleted file mode 100644 index dd4c4cd3de0e..000000000000 --- a/plugins/gradle/src/org/jetbrains/plugins/gradle/action/GradleImportEntityAction.java +++ /dev/null @@ -1,41 +0,0 @@ -package org.jetbrains.plugins.gradle.action; - -import com.intellij.openapi.components.ServiceManager; -import com.intellij.openapi.externalSystem.settings.ExternalSystemTextAttributes; -import com.intellij.openapi.externalSystem.util.ExternalSystemBundle; -import com.intellij.openapi.project.Project; -import com.intellij.ui.treeStructure.Tree; -import org.jetbrains.annotations.NotNull; -import com.intellij.openapi.externalSystem.service.project.manage.GradleLocalNodeManageHelper; -import com.intellij.openapi.externalSystem.ui.ProjectStructureNode; - -import java.util.Collection; - -/** - * Imports target {@link ExternalSystemTextAttributes#EXTERNAL_SYSTEM_LOCAL_CHANGE 'gradle local'} entity to the current intellij project. - * <p/> - * Not thread-safe. - * - * @author Denis Zhdanov - * @since 2/7/12 10:32 AM - */ -public class GradleImportEntityAction extends AbstractGradleSyncTreeNodeAction { - - public GradleImportEntityAction() { - // TODO den implement -// getTemplatePresentation().setText(ExternalSystemBundle.message("gradle.action.import.entity.text")); -// getTemplatePresentation().setDescription(ExternalSystemBundle.message("gradle.action.import.entity.description")); - } - - @Override - protected void filterNodes(@NotNull Collection<ProjectStructureNode<?>> nodes) { - filterNodesByAttributes(nodes, ExternalSystemTextAttributes.EXTERNAL_SYSTEM_LOCAL_CHANGE); - } - - @Override - protected void doActionPerformed(@NotNull Collection<ProjectStructureNode<?>> nodes, @NotNull Project project, @NotNull Tree tree) { - final GradleLocalNodeManageHelper helper = ServiceManager.getService(project, GradleLocalNodeManageHelper.class); - // TODO den implement -// helper.importNodes(nodes); - } -} diff --git a/plugins/gradle/src/org/jetbrains/plugins/gradle/action/GradleLinkToProjectAction.java b/plugins/gradle/src/org/jetbrains/plugins/gradle/action/GradleLinkToProjectAction.java deleted file mode 100644 index 5ae550c1a807..000000000000 --- a/plugins/gradle/src/org/jetbrains/plugins/gradle/action/GradleLinkToProjectAction.java +++ /dev/null @@ -1,44 +0,0 @@ -package org.jetbrains.plugins.gradle.action; - -import com.intellij.openapi.actionSystem.AnAction; -import com.intellij.openapi.actionSystem.AnActionEvent; -import com.intellij.openapi.actionSystem.PlatformDataKeys; -import com.intellij.openapi.externalSystem.util.ExternalSystemBundle; -import com.intellij.openapi.fileChooser.FileChooser; -import com.intellij.openapi.project.DumbAware; -import com.intellij.openapi.project.Project; -import com.intellij.openapi.vfs.VirtualFile; -import org.jetbrains.plugins.gradle.settings.GradleSettings; -import org.jetbrains.plugins.gradle.util.GradleUtil; - -/** - * Allows to link gradle project to the current IntelliJ IDEA project. - * <p/> - * Not thread-safe. - * - * @author Denis Zhdanov - * @since 12/26/11 5:09 PM - */ -public class GradleLinkToProjectAction extends AnAction implements DumbAware { - - public GradleLinkToProjectAction() { - // TODO den implement -// getTemplatePresentation().setText(ExternalSystemBundle.message("gradle.action.link.project.text")); -// getTemplatePresentation().setDescription(ExternalSystemBundle.message("gradle.action.link.project.description")); -// getTemplatePresentation().setText(ExternalSystemBundle.message("gradle.toolwindow.linked.action.text")); - } - - @Override - public void actionPerformed(AnActionEvent e) { - final Project project = PlatformDataKeys.PROJECT.getData(e.getDataContext()); - if (project == null) { - return; - } - final VirtualFile file = FileChooser.chooseFile(GradleUtil.getGradleProjectFileChooserDescriptor(), project, null); - if (file == null) { - return; - } - // TODO den implement -// GradleSettings.applyLinkedProjectPath(file.getPath(), project); - } -} diff --git a/plugins/gradle/src/org/jetbrains/plugins/gradle/action/GradleLocalSyncTreeFilterAction.java b/plugins/gradle/src/org/jetbrains/plugins/gradle/action/GradleLocalSyncTreeFilterAction.java deleted file mode 100644 index 3ff4ff6cfdb6..000000000000 --- a/plugins/gradle/src/org/jetbrains/plugins/gradle/action/GradleLocalSyncTreeFilterAction.java +++ /dev/null @@ -1,14 +0,0 @@ -package org.jetbrains.plugins.gradle.action; - -import org.jetbrains.plugins.gradle.config.GradleColorAndFontDescriptorsProvider; - -/** - * @author Denis Zhdanov - * @since 3/7/12 3:54 PM - */ -public class GradleLocalSyncTreeFilterAction extends AbstractGradleSyncTreeFilterAction { - - public GradleLocalSyncTreeFilterAction() { - super(GradleColorAndFontDescriptorsProvider.GRADLE_LOCAL); - } -} diff --git a/plugins/gradle/src/org/jetbrains/plugins/gradle/action/GradleRebuildStructureChangesTreeAction.java b/plugins/gradle/src/org/jetbrains/plugins/gradle/action/GradleRebuildStructureChangesTreeAction.java deleted file mode 100644 index 2e6d647a0f14..000000000000 --- a/plugins/gradle/src/org/jetbrains/plugins/gradle/action/GradleRebuildStructureChangesTreeAction.java +++ /dev/null @@ -1,27 +0,0 @@ -package org.jetbrains.plugins.gradle.action; - -import com.intellij.openapi.actionSystem.AnAction; -import com.intellij.openapi.actionSystem.AnActionEvent; -import com.intellij.openapi.externalSystem.util.ExternalSystemBundle; -import com.intellij.openapi.externalSystem.ui.ExternalProjectStructureTreeModel; -import org.jetbrains.plugins.gradle.util.GradleUtil; - -/** - * @author Denis Zhdanov - * @since 3/15/12 11:23 AM - */ -public class GradleRebuildStructureChangesTreeAction extends AnAction { - - public GradleRebuildStructureChangesTreeAction() { - getTemplatePresentation().setText(ExternalSystemBundle.message("gradle.action.rebuild.sync.tree.text")); - getTemplatePresentation().setDescription(ExternalSystemBundle.message("gradle.action.rebuild.sync.tree.description")); - } - - @Override - public void actionPerformed(AnActionEvent e) { - final ExternalProjectStructureTreeModel model = GradleUtil.getProjectStructureTreeModel(e.getDataContext()); - if (model != null) { - model.rebuild(); - } - } -} diff --git a/plugins/gradle/src/org/jetbrains/plugins/gradle/action/GradleRefreshProjectAction.java b/plugins/gradle/src/org/jetbrains/plugins/gradle/action/GradleRefreshProjectAction.java index 4d297d135d25..f92ca083fd87 100644 --- a/plugins/gradle/src/org/jetbrains/plugins/gradle/action/GradleRefreshProjectAction.java +++ b/plugins/gradle/src/org/jetbrains/plugins/gradle/action/GradleRefreshProjectAction.java @@ -14,7 +14,6 @@ import org.jetbrains.annotations.NotNull; import org.jetbrains.plugins.gradle.settings.GradleSettings; import com.intellij.openapi.externalSystem.service.task.ExternalSystemTaskManager; import org.jetbrains.plugins.gradle.notification.GradleConfigNotificationManager; -import com.intellij.openapi.externalSystem.ui.ExternalProjectStructureTreeModel; import org.jetbrains.plugins.gradle.util.GradleConstants; import org.jetbrains.plugins.gradle.util.GradleUtil; @@ -40,10 +39,11 @@ public class GradleRefreshProjectAction extends AbstractGradleLinkedProjectActio protected void doUpdate(@NotNull AnActionEvent event, @NotNull Project project, @NotNull String linkedProjectPath) { String message = myErrorMessage.get(); if (message != null) { - ExternalProjectStructureTreeModel model = GradleUtil.getProjectStructureTreeModel(event.getDataContext()); - if (model != null) { - model.rebuild(); - } + // TODO den implement +// ExternalProjectStructureTreeModel model = GradleUtil.getProjectStructureTreeModel(event.getDataContext()); +// if (model != null) { +// model.rebuild(); +// } GradleConfigNotificationManager notificationManager = ServiceManager.getService(project, GradleConfigNotificationManager.class); notificationManager.processRefreshError(message); myErrorMessage.set(null); diff --git a/plugins/gradle/src/org/jetbrains/plugins/gradle/action/GradleRemoveIdeEntityAction.java b/plugins/gradle/src/org/jetbrains/plugins/gradle/action/GradleRemoveIdeEntityAction.java deleted file mode 100644 index 6ec10e3e28ad..000000000000 --- a/plugins/gradle/src/org/jetbrains/plugins/gradle/action/GradleRemoveIdeEntityAction.java +++ /dev/null @@ -1,40 +0,0 @@ -package org.jetbrains.plugins.gradle.action; - -import com.intellij.openapi.components.ServiceManager; -import com.intellij.openapi.externalSystem.settings.ExternalSystemTextAttributes; -import com.intellij.openapi.externalSystem.util.ExternalSystemBundle; -import com.intellij.openapi.project.Project; -import com.intellij.ui.treeStructure.Tree; -import org.jetbrains.annotations.NotNull; -import com.intellij.openapi.externalSystem.service.project.manage.GradleLocalNodeManageHelper; -import com.intellij.openapi.externalSystem.ui.ProjectStructureNode; - -import java.util.Collection; - -/** - * Allows to remove IDE entity (module, dependency, content root etc). Convenient to use when project structure tree is configured - * to show only IDE-local changes and we want to remove them all. - * - * @author Denis Zhdanov - * @since 11/17/12 3:01 PM - */ -public class GradleRemoveIdeEntityAction extends AbstractGradleSyncTreeNodeAction { - - public GradleRemoveIdeEntityAction() { - // TODO den implement -// getTemplatePresentation().setText(ExternalSystemBundle.message("gradle.action.remove.entity.text")); -// getTemplatePresentation().setDescription(ExternalSystemBundle.message("gradle.action.remove.entity.description")); - } - - @Override - protected void filterNodes(@NotNull Collection<ProjectStructureNode<?>> nodes) { - filterNodesByAttributes(nodes, ExternalSystemTextAttributes.IDE_LOCAL_CHANGE); - } - - @Override - protected void doActionPerformed(@NotNull Collection<ProjectStructureNode<?>> nodes, @NotNull Project project, @NotNull Tree tree) { - final GradleLocalNodeManageHelper helper = ServiceManager.getService(project, GradleLocalNodeManageHelper.class); - // TODO den implement -// helper.removeNodes(nodes); - } -} diff --git a/plugins/gradle/src/org/jetbrains/plugins/gradle/action/GradleResetTreeFiltersAction.java b/plugins/gradle/src/org/jetbrains/plugins/gradle/action/GradleResetTreeFiltersAction.java deleted file mode 100644 index c51b67407a13..000000000000 --- a/plugins/gradle/src/org/jetbrains/plugins/gradle/action/GradleResetTreeFiltersAction.java +++ /dev/null @@ -1,35 +0,0 @@ -package org.jetbrains.plugins.gradle.action; - -import com.intellij.openapi.actionSystem.AnActionEvent; -import com.intellij.openapi.actionSystem.ToggleAction; -import com.intellij.openapi.externalSystem.util.ExternalSystemBundle; -import com.intellij.openapi.externalSystem.ui.ExternalProjectStructureTreeModel; -import org.jetbrains.plugins.gradle.util.GradleUtil; -import org.jetbrains.plugins.gradle.util.TextIcon; - -/** - * @author Denis Zhdanov - * @since 11/22/12 7:27 PM - */ -public class GradleResetTreeFiltersAction extends ToggleAction { - - public GradleResetTreeFiltersAction() { - getTemplatePresentation().setText(ExternalSystemBundle.message("gradle.action.reset.tree.filters.text")); - getTemplatePresentation().setDescription(ExternalSystemBundle.message("gradle.action.reset.tree.filters.description")); - getTemplatePresentation().setIcon(new TextIcon(ExternalSystemBundle.message("gradle.action.reset.tree.filters.icon"))); - } - - @Override - public boolean isSelected(AnActionEvent e) { - final ExternalProjectStructureTreeModel model = GradleUtil.getProjectStructureTreeModel(e.getDataContext()); - return model == null || !model.hasAnyFilter(); - } - - @Override - public void setSelected(AnActionEvent e, boolean state) { - final ExternalProjectStructureTreeModel treeModel = GradleUtil.getProjectStructureTreeModel(e.getDataContext()); - if (treeModel != null) { - treeModel.removeAllFilters(); - } - } -} diff --git a/plugins/gradle/src/org/jetbrains/plugins/gradle/action/GradleShowConflictDetailsAction.java b/plugins/gradle/src/org/jetbrains/plugins/gradle/action/GradleShowConflictDetailsAction.java deleted file mode 100644 index a83ee30023e3..000000000000 --- a/plugins/gradle/src/org/jetbrains/plugins/gradle/action/GradleShowConflictDetailsAction.java +++ /dev/null @@ -1,93 +0,0 @@ -package org.jetbrains.plugins.gradle.action; - -import com.intellij.codeInsight.hint.HintManager; -import com.intellij.openapi.components.ServiceManager; -import com.intellij.openapi.externalSystem.service.project.ProjectStructureServices; -import com.intellij.openapi.externalSystem.util.ExternalSystemBundle; -import com.intellij.openapi.project.Project; -import com.intellij.openapi.ui.popup.Balloon; -import com.intellij.openapi.ui.popup.JBPopupAdapter; -import com.intellij.openapi.ui.popup.JBPopupFactory; -import com.intellij.openapi.ui.popup.LightweightWindowEvent; -import com.intellij.ui.awt.RelativePoint; -import com.intellij.ui.treeStructure.Tree; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.plugins.gradle.sync.conflict.GradleConflictControlFactory; -import com.intellij.openapi.externalSystem.ui.ProjectStructureNode; -import org.jetbrains.plugins.gradle.ui.GradleUiListener; -import org.jetbrains.plugins.gradle.util.GradleUtil; - -import javax.swing.*; -import java.awt.*; -import java.util.Collection; - -/** - * There is a possible case that particular project structure entity has conflicting setup at the gradle and intellij - * (e.g. particular library contains one set of binaries at the gradle and another one at the intellij). We want to - * show the conflict and allow to resolve it then. This action is a trigger mechanism for that. - * <p/> - * Not thread-safe. - * - * @author Denis Zhdanov - * @since 3/2/12 2:43 PM - */ -public class GradleShowConflictDetailsAction extends AbstractGradleSyncTreeNodeAction { - - public GradleShowConflictDetailsAction() { - // TODO den implement -// getTemplatePresentation().setText(ExternalSystemBundle.message("gradle.action.show.conflict.text")); -// getTemplatePresentation().setDescription(ExternalSystemBundle.message("gradle.action.show.conflict.description")); - } - - @Override - protected void filterNodes(@NotNull Collection<ProjectStructureNode<?>> nodes) { - if (nodes.size() != 1) { - // Don't provide details if more than one node is selected - nodes.clear(); - return; - } - final ProjectStructureNode<?> node = nodes.iterator().next(); - if (node.getConflictChanges().isEmpty()) { - nodes.clear(); - } - } - - @Override - protected void doActionPerformed(@NotNull Collection<ProjectStructureNode<?>> nodes, @NotNull final Project project, @NotNull Tree tree) { - assert nodes.size() == 1; - final ProjectStructureNode<?> node = nodes.iterator().next(); - final ProjectStructureServices context = ServiceManager.getService(project, ProjectStructureServices.class); - // TODO den implement - final Object entity = null; -// final Object entity = node.getDescriptor().getElement().mapToEntity(context); - if (entity == null) { - return; - } - - final HintManager hintManager = HintManager.getInstance(); - hintManager.hideAllHints(); - - final GradleConflictControlFactory factory = ServiceManager.getService(GradleConflictControlFactory.class); - JComponent control = factory.getDiffControl(entity, node.getConflictChanges()); - if (control == null) { - return; - } - final Point hintPosition = GradleUtil.getHintPosition(node, tree); - if (hintPosition == null) { - return; - } - final Balloon balloon = JBPopupFactory.getInstance().createBalloonBuilder(control).setDisposable(project) - .setFillColor(tree.getBackground()).createBalloon(); - final GradleUiListener publisher = project.getMessageBus().syncPublisher(GradleUiListener.TOPIC); - publisher.beforeConflictUiShown(); - balloon.addListener(new JBPopupAdapter() { - @Override - public void onClosed(LightweightWindowEvent event) { - if (!project.isDisposed()) { - publisher.afterConflictUiShown(); - } - } - }); - balloon.show(new RelativePoint(tree, hintPosition), Balloon.Position.below); - } -} diff --git a/plugins/gradle/src/org/jetbrains/plugins/gradle/action/GradleSyncAction.java b/plugins/gradle/src/org/jetbrains/plugins/gradle/action/GradleSyncAction.java deleted file mode 100644 index 45ca79a72e60..000000000000 --- a/plugins/gradle/src/org/jetbrains/plugins/gradle/action/GradleSyncAction.java +++ /dev/null @@ -1,77 +0,0 @@ -/* - * Copyright 2000-2013 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.jetbrains.plugins.gradle.action; - -import com.intellij.openapi.components.ServiceManager; -import com.intellij.openapi.editor.colors.TextAttributesKey; -import com.intellij.openapi.externalSystem.model.project.change.ExternalProjectStructureChange; -import com.intellij.openapi.externalSystem.service.project.manage.EntityManageHelper; -import com.intellij.openapi.externalSystem.service.project.manage.OutdatedLibraryService; -import com.intellij.openapi.externalSystem.settings.ExternalSystemTextAttributes; -import com.intellij.openapi.externalSystem.ui.ProjectStructureNode; -import com.intellij.openapi.project.Project; -import com.intellij.ui.treeStructure.Tree; -import com.intellij.util.containers.ContainerUtilRt; -import org.jetbrains.annotations.NotNull; - -import java.util.*; - -/** - * @author Denis Zhdanov - * @since 1/23/13 11:13 AM - */ -public class GradleSyncAction extends AbstractGradleSyncTreeNodeAction { - - public GradleSyncAction() { - // TODO den implement -// getTemplatePresentation().setText(ExternalSystemBundle.message("gradle.action.sync.text")); -// getTemplatePresentation().setDescription(ExternalSystemBundle.message("gradle.action.sync.description")); - } - - @Override - protected void filterNodes(@NotNull Collection<ProjectStructureNode<?>> nodes) { - for (Iterator<ProjectStructureNode<?>> iterator = nodes.iterator(); iterator.hasNext(); ) { - ProjectStructureNode<?> node = iterator.next(); - TextAttributesKey attributes = node.getDescriptor().getAttributes(); - if (!ExternalSystemTextAttributes.OUTDATED_ENTITY.equals(attributes) && node.getConflictChanges().isEmpty()) { - iterator.remove(); - } - } - } - - @Override - protected void doActionPerformed(@NotNull Collection<ProjectStructureNode<?>> nodes, @NotNull Project project, @NotNull Tree tree) { - OutdatedLibraryService manager = ServiceManager.getService(project, OutdatedLibraryService.class); - EntityManageHelper helper = ServiceManager.getService(project, EntityManageHelper.class); - - List<ProjectStructureNode<?>> outdatedLibraryNodes = ContainerUtilRt.newArrayList(); - Set<ExternalProjectStructureChange> conflictChanges = ContainerUtilRt.newHashSet(); - for (ProjectStructureNode<?> node : nodes) { - if (ExternalSystemTextAttributes.OUTDATED_ENTITY.equals(node.getDescriptor().getAttributes())) { - outdatedLibraryNodes.add(node); - } - conflictChanges.addAll(node.getConflictChanges()); - } - - // TODO den implement -// if (!outdatedLibraryNodes.isEmpty()) { -// manager.sync(nodes); -// } -// if (!conflictChanges.isEmpty()) { -// helper.eliminateChange(conflictChanges, Collections.<UserProjectChange>emptySet(), true); -// } - } -} diff --git a/plugins/gradle/src/org/jetbrains/plugins/gradle/action/IntellijLocalSyncTreeFilterAction.java b/plugins/gradle/src/org/jetbrains/plugins/gradle/action/IntellijLocalSyncTreeFilterAction.java deleted file mode 100644 index 4a95797a88c1..000000000000 --- a/plugins/gradle/src/org/jetbrains/plugins/gradle/action/IntellijLocalSyncTreeFilterAction.java +++ /dev/null @@ -1,14 +0,0 @@ -package org.jetbrains.plugins.gradle.action; - -import org.jetbrains.plugins.gradle.config.GradleColorAndFontDescriptorsProvider; - -/** - * @author Denis Zhdanov - * @since 3/7/12 3:59 PM - */ -public class IntellijLocalSyncTreeFilterAction extends AbstractGradleSyncTreeFilterAction { - - public IntellijLocalSyncTreeFilterAction() { - super(GradleColorAndFontDescriptorsProvider.INTELLIJ_LOCAL); - } -} diff --git a/plugins/gradle/src/org/jetbrains/plugins/gradle/config/GradleColorAndFontDescriptorsProvider.java b/plugins/gradle/src/org/jetbrains/plugins/gradle/config/GradleColorAndFontDescriptorsProvider.java deleted file mode 100644 index b425607e8dd0..000000000000 --- a/plugins/gradle/src/org/jetbrains/plugins/gradle/config/GradleColorAndFontDescriptorsProvider.java +++ /dev/null @@ -1,68 +0,0 @@ -package org.jetbrains.plugins.gradle.config; - -import com.intellij.openapi.externalSystem.settings.ExternalSystemTextAttributes; -import com.intellij.openapi.externalSystem.util.ExternalSystemBundle; -import com.intellij.openapi.options.colors.AttributesDescriptor; -import com.intellij.openapi.options.colors.ColorAndFontDescriptorsProvider; -import com.intellij.openapi.options.colors.ColorDescriptor; -import org.jetbrains.annotations.NotNull; - -/** - * Provides support for defining gradle-specific color settings. - * <p/> - * Not thread-safe. - * - * @author Denis Zhdanov - * @since 1/18/12 4:15 PM - */ -public class GradleColorAndFontDescriptorsProvider implements ColorAndFontDescriptorsProvider { - - public static final AttributesDescriptor CONFLICT = new AttributesDescriptor( - ExternalSystemBundle.message("gradle.sync.change.type.conflict"), - ExternalSystemTextAttributes.CHANGE_CONFLICT - ); - - public static final AttributesDescriptor GRADLE_LOCAL = new AttributesDescriptor( - ExternalSystemBundle.message("gradle.sync.change.type.gradle"), - ExternalSystemTextAttributes.EXTERNAL_SYSTEM_LOCAL_CHANGE - ); - - public static final AttributesDescriptor INTELLIJ_LOCAL = new AttributesDescriptor( - ExternalSystemBundle.message("gradle.sync.change.type.intellij"), - //GradleBundle.message("gradle.sync.change.type.intellij", ApplicationNamesInfo.getInstance().getProductName()), - ExternalSystemTextAttributes.IDE_LOCAL_CHANGE - ); - - public static final AttributesDescriptor OUTDATED_ENTITY = new AttributesDescriptor( - ExternalSystemBundle.message("gradle.sync.change.type.changed.library.version"), - //GradleBundle.message("gradle.sync.change.type.intellij", ApplicationNamesInfo.getInstance().getProductName()), - ExternalSystemTextAttributes.OUTDATED_ENTITY - ); - - public static final AttributesDescriptor NO_CHANGE = new AttributesDescriptor( - ExternalSystemBundle.message("gradle.sync.change.type.unchanged"), - ExternalSystemTextAttributes.NO_CHANGE - ); - - public static final AttributesDescriptor[] DESCRIPTORS = { - CONFLICT, GRADLE_LOCAL, INTELLIJ_LOCAL, OUTDATED_ENTITY, NO_CHANGE - }; - - @NotNull - @Override - public String getDisplayName() { - return ExternalSystemBundle.message("gradle.name"); - } - - @NotNull - @Override - public AttributesDescriptor[] getAttributeDescriptors() { - return DESCRIPTORS; - } - - @NotNull - @Override - public ColorDescriptor[] getColorDescriptors() { - return new ColorDescriptor[0]; - } -} diff --git a/plugins/gradle/src/org/jetbrains/plugins/gradle/config/GradleColorAndFontPanelFactory.java b/plugins/gradle/src/org/jetbrains/plugins/gradle/config/GradleColorAndFontPanelFactory.java deleted file mode 100644 index f53892c5aa81..000000000000 --- a/plugins/gradle/src/org/jetbrains/plugins/gradle/config/GradleColorAndFontPanelFactory.java +++ /dev/null @@ -1,35 +0,0 @@ -package org.jetbrains.plugins.gradle.config; - -import com.intellij.application.options.colors.*; -import com.intellij.openapi.externalSystem.util.ExternalSystemBundle; -import com.intellij.psi.codeStyle.DisplayPriority; -import org.jetbrains.annotations.NotNull; - -/** - * @author Denis Zhdanov - * @since 1/19/12 11:32 AM - */ -public class GradleColorAndFontPanelFactory implements ColorAndFontPanelFactoryEx { - - @NotNull - @Override - public NewColorAndFontPanel createPanel(@NotNull ColorAndFontOptions options) { - SchemesPanel schemesPanel = new SchemesPanel(options); - final ColorAndFontDescriptionPanel descriptionPanel = new ColorAndFontDescriptionPanel(); - final OptionsPanel optionsPanel = new OptionsPanelImpl(descriptionPanel, options, schemesPanel, ExternalSystemBundle - .message("gradle.name")); - GradleColorAndFontPreviewPanel previewPanel = new GradleColorAndFontPreviewPanel(options); - return new NewColorAndFontPanel(schemesPanel, optionsPanel, previewPanel, ExternalSystemBundle.message("gradle.name"), null, null); - } - - @NotNull - @Override - public String getPanelDisplayName() { - return ExternalSystemBundle.message("gradle.name"); - } - - @Override - public DisplayPriority getPriority() { - return DisplayPriority.LANGUAGE_SETTINGS; - } -} diff --git a/plugins/gradle/src/org/jetbrains/plugins/gradle/config/GradleColorAndFontPreviewPanel.java b/plugins/gradle/src/org/jetbrains/plugins/gradle/config/GradleColorAndFontPreviewPanel.java deleted file mode 100644 index d827672248ec..000000000000 --- a/plugins/gradle/src/org/jetbrains/plugins/gradle/config/GradleColorAndFontPreviewPanel.java +++ /dev/null @@ -1,329 +0,0 @@ -package org.jetbrains.plugins.gradle.config; - -import com.intellij.application.options.colors.ColorAndFontOptions; -import com.intellij.application.options.colors.ColorAndFontSettingsListener; -import com.intellij.application.options.colors.EditorSchemeAttributeDescriptor; -import com.intellij.application.options.colors.PreviewPanel; -import com.intellij.ide.projectView.PresentationData; -import com.intellij.ide.util.treeView.NodeRenderer; -import com.intellij.openapi.editor.colors.EditorColorsScheme; -import com.intellij.openapi.editor.colors.TextAttributesKey; -import com.intellij.openapi.externalSystem.model.project.ProjectEntityType; -import com.intellij.openapi.externalSystem.settings.ExternalSystemTextAttributes; -import com.intellij.openapi.externalSystem.util.ExternalSystemBundle; -import com.intellij.openapi.util.Pair; -import com.intellij.openapi.util.Ref; -import com.intellij.ui.JBColor; -import com.intellij.ui.components.JBScrollPane; -import com.intellij.ui.treeStructure.Tree; -import com.intellij.util.containers.ContainerUtil; -import com.intellij.util.containers.hash.HashMap; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; -import com.intellij.openapi.externalSystem.model.project.id.GradleSyntheticId; -import com.intellij.openapi.externalSystem.ui.ProjectStructureNodeDescriptor; - -import javax.swing.*; -import javax.swing.event.TreeSelectionEvent; -import javax.swing.event.TreeSelectionListener; -import javax.swing.tree.*; -import java.awt.*; -import java.util.List; -import java.util.Map; - -/** - * @author Denis Zhdanov - * @since 1/19/12 11:59 AM - */ -public class GradleColorAndFontPreviewPanel implements PreviewPanel { - - private final Map<TextAttributesKey, DefaultMutableTreeNode> myNodes = new HashMap<TextAttributesKey, DefaultMutableTreeNode>(); - - // TODO den switch to ContainerUtil.createLockFreeCopyOnWriteList() as soon as v.12.1 is released. - // TODO den (we need to preserve binary compatibility with v.12.0 at the moment) - private final List<ColorAndFontSettingsListener> myListeners = ContainerUtil.createEmptyCOWList(); - private final JPanel myContent = new JPanel(new GridBagLayout()); - private final JPanel myNodeRenderPanel = new JPanel(new GridBagLayout()); - private final Ref<Boolean> myAllowTreeExpansion = new Ref<Boolean>(true); - private final ArrowPanel mySelectedElementSignPanel = new ArrowPanel(); - - private final Tree myTree; - private final DefaultTreeModel myTreeModel; - - private ColorAndFontOptions myOptions; - private TreeNode mySelectedNode; - - public GradleColorAndFontPreviewPanel(@NotNull ColorAndFontOptions options) { - myOptions = options; - final Pair<Tree, DefaultTreeModel> pair = init(); - myTree = pair.first; - myTreeModel = pair.second; - } - - private Pair<Tree, DefaultTreeModel> init() { - myContent.removeAll(); - String projectName = ExternalSystemBundle.message("gradle.settings.color.text.sample.conflict.node.name"); - DefaultMutableTreeNode root = createNode( - projectName, - ProjectEntityType.PROJECT, - ExternalSystemTextAttributes.CHANGE_CONFLICT - ); - - String moduleName = ExternalSystemBundle.message("gradle.settings.color.text.sample.node.sync.name"); - DefaultMutableTreeNode module = createNode(moduleName, ProjectEntityType.MODULE, ExternalSystemTextAttributes.NO_CHANGE); - - String gradleLibraryName = ExternalSystemBundle.message("gradle.settings.color.text.sample.node.gradle.name"); - DefaultMutableTreeNode gradleLibrary = createNode( - gradleLibraryName, ProjectEntityType.LIBRARY_DEPENDENCY, ExternalSystemTextAttributes.EXTERNAL_SYSTEM_LOCAL_CHANGE - ); - - String intellijLibraryName = ExternalSystemBundle.message("gradle.settings.color.text.sample.node.intellij.name"); - DefaultMutableTreeNode intellijLibrary = createNode( - intellijLibraryName, ProjectEntityType.LIBRARY_DEPENDENCY, ExternalSystemTextAttributes.IDE_LOCAL_CHANGE - ); - - String libraryWithChangedVersionName = ExternalSystemBundle.message("gradle.settings.color.text.sample.node.outdated.name"); - DefaultMutableTreeNode libraryWithChangedVersion = createNode( - libraryWithChangedVersionName, ProjectEntityType.LIBRARY_DEPENDENCY, ExternalSystemTextAttributes.OUTDATED_ENTITY); - - module.add(gradleLibrary); - module.add(intellijLibrary); - module.add(libraryWithChangedVersion); - root.add(module); - - mySelectedNode = root; - - DefaultTreeModel treeModel = new DefaultTreeModel(root); - Tree tree = buildTree(treeModel, module); - - GridBagConstraints constraints = new GridBagConstraints(); - constraints.fill = GridBagConstraints.BOTH; - constraints.weightx = constraints.weighty = 1; - myContent.add(new JBScrollPane(tree), constraints); - return new Pair<Tree, DefaultTreeModel>(tree, treeModel); - } - - private Tree buildTree(@NotNull TreeModel model, DefaultMutableTreeNode... nodesToExpand) { - final Tree tree = new Tree(model) { - @Override - protected void setExpandedState(TreePath path, boolean state) { - if (myAllowTreeExpansion.get()) { - super.setExpandedState(path, state); - } - // Ignore the expansion change events otherwise - } - }; - - // Configure expansion - for (DefaultMutableTreeNode node : nodesToExpand) { - tree.expandPath(new TreePath(node.getPath())); - } - myAllowTreeExpansion.set(false); - - // Configure selection. - tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION); - tree.addTreeSelectionListener(new TreeSelectionListener() { - - private boolean myIgnore; - - @Override - public void valueChanged(TreeSelectionEvent e) { - if (myIgnore) { - return; - } - final TreePath path = e.getNewLeadSelectionPath(); - if (path == null) { - clearSelection(); - return; - } - final Object component = path.getLastPathComponent(); - for (Map.Entry<TextAttributesKey, DefaultMutableTreeNode> entry : myNodes.entrySet()) { - if (entry.getValue().equals(component)) { - pointTo(entry.getValue()); - for (ColorAndFontSettingsListener listener : myListeners) { - listener.selectionInPreviewChanged(entry.getKey().getExternalName()); - clearSelection(); - } - return; - } - } - clearSelection(); - } - - private void clearSelection() { - // Don't show selection at the 'preview' node. - myIgnore = true; - try { - tree.getSelectionModel().clearSelection(); - } - finally { - myIgnore = false; - } - } - }); - - // Bind rendering to the target colors scheme. - final NodeRenderer delegate = new NodeRenderer() { - @NotNull - @Override - protected EditorColorsScheme getColorsScheme() { - return myOptions.getSelectedScheme(); - } - }; - myNodeRenderPanel.setBackground(tree.getBackground()); - tree.setCellRenderer(new TreeCellRenderer() { - @Override - public Component getTreeCellRendererComponent(JTree tree, - Object value, - boolean selected, - boolean expanded, - boolean leaf, - int row, - boolean hasFocus) { - final Component component = delegate.getTreeCellRendererComponent(tree, value, selected, expanded, leaf, row, hasFocus); - if (myNodeRenderPanel.getComponentCount() <= 0) { - GridBagConstraints constraints = new GridBagConstraints(); - myNodeRenderPanel.add(component, constraints); - constraints.weightx = 1; - constraints.anchor = GridBagConstraints.CENTER; - myNodeRenderPanel.add(mySelectedElementSignPanel, constraints); - } - - mySelectedElementSignPanel.setPaint(value == mySelectedNode); - - // The same component is used for rendering all nodes, that's there is a possible situation when the renderer was used - // for narrow node component painting at first and then we want to paint a wider node. The problem is that preferred renderer - // size value calculated for the narrow node component might be cached at the renderer. That's why we explicitly drop - // that cached value (if any). - myNodeRenderPanel.setPreferredSize(null); - return myNodeRenderPanel; - } - }); - return tree; - } - - @Override - public void blinkSelectedHighlightType(Object selected) { - if (!(selected instanceof EditorSchemeAttributeDescriptor)) { - return; - } - final String type = ((EditorSchemeAttributeDescriptor)selected).getType(); - for (Map.Entry<TextAttributesKey, DefaultMutableTreeNode> entry : myNodes.entrySet()) { - if (entry.getKey().getExternalName().equals(type)) { - pointTo(entry.getValue()); - return; - } - } - } - - /** - * Instructs the panel to show given node as selected. - * - * @param node node to show as 'selected' - */ - private void pointTo(@NotNull TreeNode node) { - TreeNode oldSelectedNode = mySelectedNode; - mySelectedNode = node; - myTreeModel.nodeChanged(oldSelectedNode); - myTreeModel.nodeChanged(mySelectedNode); - } - - @Override - public void disposeUIResources() { - myListeners.clear(); - myNodes.clear(); - myContent.removeAll(); - myNodeRenderPanel.removeAll(); - } - - @Override - public Component getPanel() { - return myContent; - } - - @Override - public void updateView() { - repaintTree(); - } - - private void repaintTree() { - myTreeModel.reload(); - myAllowTreeExpansion.set(true); - try { - for (DefaultMutableTreeNode node : myNodes.values()) { - myTree.expandPath(new TreePath(node.getPath())); - } - } - finally { - myAllowTreeExpansion.set(false); - } - } - - @Override - public void addListener(@NotNull ColorAndFontSettingsListener listener) { - myListeners.add(listener); - } - - private DefaultMutableTreeNode createNode(@NotNull String text, @NotNull ProjectEntityType type, @Nullable TextAttributesKey textAttributesKey) { - final ProjectStructureNodeDescriptor<GradleSyntheticId> descriptor - = new ProjectStructureNodeDescriptor<GradleSyntheticId>(new GradleSyntheticId(text), text, type.getIcon()); - DefaultMutableTreeNode result = new DefaultMutableTreeNode(descriptor); - if (textAttributesKey != null) { - final PresentationData presentation = descriptor.getPresentation(); - presentation.setAttributesKey(textAttributesKey); - myNodes.put(textAttributesKey, result); - } - return result; - } - - /** - * Encapsulates logic of drawing 'selected element' sign. - */ - private static class ArrowPanel extends JPanel { - - private boolean myPaint; - - ArrowPanel() { - super(new BorderLayout()); - // Reserve enough horizontal space. - add(new JLabel("intelli")); - } - - public void setPaint(boolean paint) { - myPaint = paint; - } - - @Override - public void paint(Graphics g) { - if (!myPaint) { - return; - } - Graphics2D g2 = (Graphics2D)g; - g.setColor(JBColor.RED); - RenderingHints renderHints = new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); - renderHints.put(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); - g2.setRenderingHints(renderHints); - - FontMetrics fontMetrics = getFontMetrics(getFont()); - int unit = fontMetrics.charWidth('a') * 2 / 3; - int yShift = 0; - final Dimension size = getSize(); - if (size != null) { - yShift = size.height / 2 - unit; - if (size.height % 2 != 0) { - // Prefer 'draw below the center' to 'draw above the center'. - yShift++; - } - } - int q = unit / 4; - int[] x = {0, unit * 3, unit * 2, unit * 4, unit * 4, unit * 2, unit * 3, 0 }; - int[] y = {unit, 0, unit - q, unit - q, unit + q, unit + q, unit * 2, unit}; - if (yShift != 0) { - for (int i = 0; i < y.length; i++) { - y[i] += yShift; - } - } - g2.fillPolygon(x, y, x.length); - } - } -} diff --git a/plugins/gradle/src/org/jetbrains/plugins/gradle/config/GradleToolWindowPanel.java b/plugins/gradle/src/org/jetbrains/plugins/gradle/config/GradleToolWindowPanel.java index 72f689d6fcb2..91da39a93522 100644 --- a/plugins/gradle/src/org/jetbrains/plugins/gradle/config/GradleToolWindowPanel.java +++ b/plugins/gradle/src/org/jetbrains/plugins/gradle/config/GradleToolWindowPanel.java @@ -3,8 +3,6 @@ package org.jetbrains.plugins.gradle.config; import com.intellij.openapi.actionSystem.ActionGroup; import com.intellij.openapi.actionSystem.ActionManager; import com.intellij.openapi.actionSystem.ActionToolbar; -import com.intellij.openapi.components.ServiceManager; -import com.intellij.openapi.externalSystem.service.project.ProjectStructureChangesDetector; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.SimpleToolWindowPanel; import com.intellij.openapi.util.text.StringUtil; @@ -126,12 +124,6 @@ public abstract class GradleToolWindowPanel extends SimpleToolWindowPanel { for (JComponent component : getToolbarControls()) { component.setVisible(showToolbar); } - - if (!NON_LINKED_CARD_NAME.equals(cardToShow)) { - updateContent(); - // Ensure that changes detector service is loaded. - ServiceManager.getService(myProject, ProjectStructureChangesDetector.class); - } } @NotNull diff --git a/plugins/gradle/src/org/jetbrains/plugins/gradle/diff/GradleDiffUtil.java b/plugins/gradle/src/org/jetbrains/plugins/gradle/diff/GradleDiffUtil.java deleted file mode 100644 index 189d07339bf4..000000000000 --- a/plugins/gradle/src/org/jetbrains/plugins/gradle/diff/GradleDiffUtil.java +++ /dev/null @@ -1,207 +0,0 @@ -package org.jetbrains.plugins.gradle.diff; - -import com.intellij.openapi.diagnostic.Logger; -import com.intellij.openapi.externalSystem.model.project.*; -import com.intellij.openapi.externalSystem.model.project.change.*; -import com.intellij.openapi.externalSystem.model.project.id.JarId; -import com.intellij.openapi.externalSystem.service.project.change.ExternalProjectChangesCalculationContext; -import com.intellij.openapi.module.Module; -import com.intellij.openapi.project.Project; -import com.intellij.openapi.roots.LibraryOrderEntry; -import com.intellij.openapi.roots.ModuleOrderEntry; -import com.intellij.openapi.roots.OrderEntry; -import com.intellij.openapi.roots.OrderRootType; -import com.intellij.openapi.roots.libraries.Library; -import com.intellij.openapi.vfs.VirtualFile; -import org.jetbrains.annotations.NotNull; -import com.intellij.openapi.externalSystem.model.project.change.ModulePresenceChange; -import com.intellij.openapi.externalSystem.model.ProjectSystemId; -import com.intellij.openapi.externalSystem.model.project.id.LibraryId; -import com.intellij.openapi.externalSystem.util.IdeEntityVisitor; -import com.intellij.openapi.externalSystem.service.project.ModuleAwareContentRoot; -import org.jetbrains.plugins.gradle.util.GradleUtil; - -import java.util.HashMap; -import java.util.Map; - -/** - * Contains various utility methods for building changes between the gradle and intellij project structures. - * - * @author Denis Zhdanov - * @since 1/24/12 11:20 AM - */ -public class GradleDiffUtil { - - private static final Logger LOG = Logger.getInstance("#" + GradleDiffUtil.class.getName()); - - private GradleDiffUtil() { - } - - /** - * Build changes objects assuming that all entities starting from the given (i.e. given and all of its interested sub-entities) - * exist only at the gradle side. - * <p/> - * Example: particular module has been added at the gradle side. We want to mark that module, its content root(s), dependencies etc - * as gradle-local changes. - * - * @param entity target gradle-local entity - * @param context changes calculation context to use - */ - public static void buildLocalChanges(@NotNull ProjectEntityData entity, @NotNull final ExternalProjectChangesCalculationContext context) { - // TODO den implement -// entity.invite(new ExternalEntityVisitor() { -// @Override -// public void visit(@NotNull ProjectData project) { -// assert false; -// } -// -// @Override -// public void visit(@NotNull ModuleData module) { -// context.register(new ModulePresenceChange(module, null)); -// for (ContentRootData root : module.getContentRoots()) { -// root.invite(this); -// } -// for (DependencyData dependency : module.getDependencies()) { -// dependency.invite(this); -// } -// } -// -// @Override -// public void visit(@NotNull ContentRootData contentRoot) { -// context.register(new ContentRootPresenceChange(contentRoot, null)); -// } -// -// @Override -// public void visit(@NotNull LibraryData library) { -// for (LibraryPathType pathType : LibraryPathType.values()) { -// for (String path : library.getPaths(pathType)) { -// JarId jarId = new JarId(path, pathType, new LibraryId(ProjectSystemId.GRADLE, library.getName())); -// context.register(new JarPresenceChange(jarId, null)); -// } -// } -// } -// -// @Override -// public void visit(@NotNull JarData jar) { -// context.register(new JarPresenceChange(jar.getId(), null)); -// } -// -// @Override -// public void visit(@NotNull ModuleDependencyData dependency) { -// context.register(new ModuleDependencyPresenceChange(dependency, null)); -// } -// -// @Override -// public void visit(@NotNull LibraryDependencyData dependency) { -// context.register(new LibraryDependencyPresenceChange(dependency, null)); -// } -// -// @Override -// public void visit(@NotNull CompositeLibraryDependencyData dependency) { -// // We expect such composite entities for outdated libraries to appear as 'low-level' project structure changes processing -// // result. -// assert false; -// } -// }); - } - - /** - * Performs argument type-based dispatch and delegates to one of strongly typed <code>'buildLocalChanges()'</code> methods. - * - * @param entity target ide-local entity that doesn't present at the gradle side - * @param context changes calculation context to use - */ - public static void buildLocalChanges(@NotNull Object entity, @NotNull final ExternalProjectChangesCalculationContext context) { - if (entity instanceof ProjectEntityData) { - buildLocalChanges((ProjectEntityData)entity, context); - } - else { - // TODO den implement -// GradleUtil.dispatch(entity, new IdeEntityVisitor() { -// @Override -// public void visit(@NotNull Project project) { -// } -// -// @Override -// public void visit(@NotNull Module module) { -// context.register(new ModulePresenceChange(null, module)); -// for (ModuleAwareContentRoot contentRoot : context.getPlatformFacade().getContentRoots(module)) { -// visit(contentRoot); -// } -// for (OrderEntry entry : context.getPlatformFacade().getOrderEntries(module)) { -// GradleUtil.dispatch(entry, this); -// } -// } -// -// @Override -// public void visit(@NotNull ModuleAwareContentRoot contentRoot) { -// context.register(new ContentRootPresenceChange(null, contentRoot)); -// } -// -// @Override -// public void visit(@NotNull LibraryOrderEntry libraryDependency) { -// context.register(new LibraryDependencyPresenceChange(null, libraryDependency)); -// } -// -// @Override -// public void visit(@NotNull ModuleOrderEntry moduleDependency) { -// final Module module = moduleDependency.getModule(); -// if (module != null) { -// context.register(new ModuleDependencyPresenceChange(null, moduleDependency)); -// } -// } -// -// @Override -// public void visit(@NotNull Library library) { -// for (VirtualFile file : library.getFiles(OrderRootType.CLASSES)) { -// JarId jarId = new JarId(context.getPlatformFacade().getLocalFileSystemPath(file), -// LibraryPathType.BINARY, -// new LibraryId(ProjectSystemId.IDE, GradleUtil.getLibraryName(library))); -// context.register(new JarPresenceChange(null, jarId)); -// } -// } -// }); - } - } - - /** - * Utility method for comparing entity collections. For example, it may be provided with the collection of gradle modules and - * collection of ide modules. Matched entities are found and the comparison is delegated to the given <code>'calculator'</code>. - * Corresponding changes are generated for the non-matched (local) changes (e.g. particular library dependency presents - * at the ide side but not at the gradle). - * - * @param calculator comparison strategy that works with the single entities (not collection of entities) - * @param gradleEntities entities available at the gradle side - * @param ideEntities entities available at the ide side - * @param context changes calculation context - * @param <I> target ide entity type - * @param <G> target gradle entity type - */ - public static <I, G extends ProjectEntityData> void calculate( - @NotNull ExternalProjectStructureChangesCalculator<G, I> calculator, - @NotNull Iterable<? extends G> gradleEntities, - @NotNull Iterable<? extends I> ideEntities, - @NotNull ExternalProjectChangesCalculationContext context) - { - // TODO den implement -// Map<Object, I> ideEntitiesByKeys = new HashMap<Object, I>(); -// for (I entity : ideEntities) { -// Object key = calculator.getIdeKey(entity); -// final I previous = ideEntitiesByKeys.put(key, entity); -// assert previous == null : key; -// } -// for (G gradleEntity: gradleEntities) { -// I ideEntity = ideEntitiesByKeys.remove(calculator.getGradleKey(gradleEntity, context)); -// if (ideEntity == null) { -// buildLocalChanges(gradleEntity, context); -// } -// else { -// calculator.calculate(gradleEntity, ideEntity, context); -// } -// } -// -// for (I entity : ideEntitiesByKeys.values()) { -// buildLocalChanges(entity, context); -// } - } -} diff --git a/plugins/gradle/src/org/jetbrains/plugins/gradle/diff/contentroot/GradleContentRootStructureChangesCalculator.java b/plugins/gradle/src/org/jetbrains/plugins/gradle/diff/contentroot/GradleContentRootStructureChangesCalculator.java deleted file mode 100644 index a3d3bf5a386f..000000000000 --- a/plugins/gradle/src/org/jetbrains/plugins/gradle/diff/contentroot/GradleContentRootStructureChangesCalculator.java +++ /dev/null @@ -1,37 +0,0 @@ -package org.jetbrains.plugins.gradle.diff.contentroot; - -import com.intellij.openapi.externalSystem.model.project.ContentRootData; -import com.intellij.openapi.externalSystem.model.project.change.ExternalProjectStructureChangesCalculator; -import com.intellij.openapi.externalSystem.model.project.id.EntityIdMapper; -import com.intellij.openapi.externalSystem.service.project.change.ExternalProjectChangesCalculationContext; -import org.jetbrains.annotations.NotNull; -import com.intellij.openapi.externalSystem.service.project.ModuleAwareContentRoot; - -/** - * @author Denis Zhdanov - * @since 2/27/12 7:00 PM - */ -public class GradleContentRootStructureChangesCalculator - implements ExternalProjectStructureChangesCalculator<ContentRootData, ModuleAwareContentRoot> -{ - @Override - public void calculate(@NotNull ContentRootData gradleEntity, - @NotNull ModuleAwareContentRoot ideEntity, - @NotNull ExternalProjectChangesCalculationContext context) - { - } - - // TODO den implement -// @NotNull -// @Override -// public Object getIdeKey(@NotNull ModuleAwareContentRoot entity) { -// return EntityIdMapper.mapEntityToId(entity); -// } -// -// @NotNull -// @Override -// public Object getGradleKey(@NotNull ContentRootData entity, @NotNull ExternalProjectChangesCalculationContext context) { -// // TODO den consider the known changes -// return EntityIdMapper.mapEntityToId(entity); -// } -} diff --git a/plugins/gradle/src/org/jetbrains/plugins/gradle/diff/dependency/AbstractGradleDependencyStructureChangesCalculator.java b/plugins/gradle/src/org/jetbrains/plugins/gradle/diff/dependency/AbstractGradleDependencyStructureChangesCalculator.java deleted file mode 100644 index af96f396485b..000000000000 --- a/plugins/gradle/src/org/jetbrains/plugins/gradle/diff/dependency/AbstractGradleDependencyStructureChangesCalculator.java +++ /dev/null @@ -1,38 +0,0 @@ -package org.jetbrains.plugins.gradle.diff.dependency; - -import com.intellij.openapi.externalSystem.model.project.DependencyData; -import com.intellij.openapi.externalSystem.model.project.change.DependencyExportedChange; -import com.intellij.openapi.externalSystem.model.project.change.DependencyScopeChange; -import com.intellij.openapi.externalSystem.model.project.change.ExternalProjectStructureChangesCalculator; -import com.intellij.openapi.externalSystem.model.project.id.AbstractExternalDependencyId; -import com.intellij.openapi.externalSystem.model.project.id.EntityIdMapper; -import com.intellij.openapi.externalSystem.service.project.change.ExternalProjectChangesCalculationContext; -import com.intellij.openapi.roots.ExportableOrderEntry; -import org.jetbrains.annotations.NotNull; - -/** - * Manages common dependency properties like 'scope', 'exported'. - * <p/> - * Thread-safe. - * - * @author Denis Zhdanov - * @since 2/20/12 11:17 AM - */ -public abstract class AbstractGradleDependencyStructureChangesCalculator<G extends DependencyData, I extends ExportableOrderEntry> - implements ExternalProjectStructureChangesCalculator<G, I> -{ - @Override - public void calculate(@NotNull G gradleEntity, @NotNull I ideEntity, @NotNull ExternalProjectChangesCalculationContext context) { - final AbstractExternalDependencyId id = EntityIdMapper.mapEntityToId(gradleEntity); - if (gradleEntity.getScope() != ideEntity.getScope()) { - context.register(new DependencyScopeChange(id, gradleEntity.getScope(), ideEntity.getScope())); - } - if (gradleEntity.isExported() != ideEntity.isExported()) { - context.register(new DependencyExportedChange(id, gradleEntity.isExported(), ideEntity.isExported())); - } - - doCalculate(gradleEntity, ideEntity, context); - } - - protected abstract void doCalculate(@NotNull G gradleEntity, @NotNull I intellijEntity, @NotNull ExternalProjectChangesCalculationContext context); -} diff --git a/plugins/gradle/src/org/jetbrains/plugins/gradle/diff/dependency/GradleLibraryDependencyStructureChangesCalculator.java b/plugins/gradle/src/org/jetbrains/plugins/gradle/diff/dependency/GradleLibraryDependencyStructureChangesCalculator.java deleted file mode 100644 index 708b965a3451..000000000000 --- a/plugins/gradle/src/org/jetbrains/plugins/gradle/diff/dependency/GradleLibraryDependencyStructureChangesCalculator.java +++ /dev/null @@ -1,52 +0,0 @@ -package org.jetbrains.plugins.gradle.diff.dependency; - -import com.intellij.openapi.externalSystem.model.project.LibraryDependencyData; -import com.intellij.openapi.externalSystem.service.project.change.ExternalProjectChangesCalculationContext; -import com.intellij.openapi.roots.LibraryOrderEntry; -import com.intellij.openapi.roots.libraries.Library; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.plugins.gradle.diff.library.GradleLibraryStructureChangesCalculator; - -/** - * @author Denis Zhdanov - * @since 1/24/12 1:37 PM - */ -public class GradleLibraryDependencyStructureChangesCalculator - extends AbstractGradleDependencyStructureChangesCalculator<LibraryDependencyData, LibraryOrderEntry> -{ - - private final GradleLibraryStructureChangesCalculator myLibraryCalculator; - - public GradleLibraryDependencyStructureChangesCalculator(@NotNull GradleLibraryStructureChangesCalculator libraryCalculator) { - myLibraryCalculator = libraryCalculator; - } - - @Override - public void doCalculate(@NotNull LibraryDependencyData gradleEntity, - @NotNull LibraryOrderEntry intellijEntity, - @NotNull ExternalProjectChangesCalculationContext context) - { - final Library library = intellijEntity.getLibrary(); - if (library == null) { - return; - } - myLibraryCalculator.calculate(gradleEntity.getTarget(), library, context); - } - - // TODO den implement -// @NotNull -// @Override -// public Object getIdeKey(@NotNull LibraryOrderEntry entity) { -// final Library library = entity.getLibrary(); -// if (library == null) { -// return ""; -// } -// return myLibraryCalculator.getIdeKey(library); -// } -// -// @NotNull -// @Override -// public Object getGradleKey(@NotNull LibraryDependencyData entity, @NotNull ExternalProjectChangesCalculationContext context) { -// return myLibraryCalculator.getGradleKey(entity.getTarget(), context); -// } -} diff --git a/plugins/gradle/src/org/jetbrains/plugins/gradle/diff/dependency/GradleModuleDependencyStructureChangesCalculator.java b/plugins/gradle/src/org/jetbrains/plugins/gradle/diff/dependency/GradleModuleDependencyStructureChangesCalculator.java deleted file mode 100644 index 3111b9ee76a3..000000000000 --- a/plugins/gradle/src/org/jetbrains/plugins/gradle/diff/dependency/GradleModuleDependencyStructureChangesCalculator.java +++ /dev/null @@ -1,37 +0,0 @@ -package org.jetbrains.plugins.gradle.diff.dependency; - -import com.intellij.openapi.externalSystem.model.project.ModuleDependencyData; -import com.intellij.openapi.externalSystem.service.project.change.ExternalProjectChangesCalculationContext; -import com.intellij.openapi.roots.ModuleOrderEntry; -import org.jetbrains.annotations.NotNull; - -/** - * @author Denis Zhdanov - * @since 2/20/12 11:10 AM - */ -public class GradleModuleDependencyStructureChangesCalculator - extends AbstractGradleDependencyStructureChangesCalculator<ModuleDependencyData, ModuleOrderEntry> -{ - - @Override - public void doCalculate(@NotNull ModuleDependencyData gradleEntity, - @NotNull ModuleOrderEntry intellijEntity, - @NotNull ExternalProjectChangesCalculationContext context) - { - // Assuming that the modules referenced by the given dependencies are compared independently. - } - - @NotNull - public Object getIdeKey(@NotNull ModuleOrderEntry entity) { - final String intellijModuleName = entity.getModuleName(); - if (intellijModuleName == null) { - return ""; - } - return intellijModuleName; - } - - @NotNull - public Object getGradleKey(@NotNull ModuleDependencyData entity, @NotNull ExternalProjectChangesCalculationContext context) { - return entity.getTarget().getName(); - } -} diff --git a/plugins/gradle/src/org/jetbrains/plugins/gradle/diff/library/GradleLibraryStructureChangesCalculator.java b/plugins/gradle/src/org/jetbrains/plugins/gradle/diff/library/GradleLibraryStructureChangesCalculator.java deleted file mode 100644 index 4fcab4c3cd82..000000000000 --- a/plugins/gradle/src/org/jetbrains/plugins/gradle/diff/library/GradleLibraryStructureChangesCalculator.java +++ /dev/null @@ -1,87 +0,0 @@ -package org.jetbrains.plugins.gradle.diff.library; - -import com.intellij.openapi.externalSystem.model.project.LibraryData; -import com.intellij.openapi.externalSystem.model.ProjectSystemId; -import com.intellij.openapi.externalSystem.model.project.change.ExternalProjectStructureChangesCalculator; -import com.intellij.openapi.externalSystem.model.project.change.JarPresenceChange; -import com.intellij.openapi.externalSystem.model.project.id.JarId; -import com.intellij.openapi.externalSystem.service.project.change.ExternalProjectChangesCalculationContext; -import com.intellij.openapi.roots.OrderRootType; -import com.intellij.openapi.roots.libraries.Library; -import com.intellij.openapi.vfs.VirtualFile; -import org.jetbrains.annotations.NotNull; -import com.intellij.openapi.externalSystem.service.project.PlatformFacade; -import com.intellij.openapi.externalSystem.model.project.LibraryPathType; -import com.intellij.openapi.externalSystem.model.project.id.LibraryId; -import org.jetbrains.plugins.gradle.util.GradleUtil; - -import java.util.HashSet; -import java.util.Set; - -/** - * @author Denis Zhdanov - * @since 2/3/12 11:17 AM - */ -public class GradleLibraryStructureChangesCalculator implements ExternalProjectStructureChangesCalculator<LibraryData, Library> { - - private final PlatformFacade myPlatformFacade; - - public GradleLibraryStructureChangesCalculator(@NotNull PlatformFacade platformFacade) { - myPlatformFacade = platformFacade; - } - - @Override - public void calculate(@NotNull LibraryData gradleEntity, - @NotNull Library ideEntity, - @NotNull ExternalProjectChangesCalculationContext context) - { - for (LibraryPathType pathType : LibraryPathType.values()) { - doCalculate(gradleEntity, pathType, context.getLibraryPathTypeMapper().map(pathType), ideEntity, context); - } - } - - private void doCalculate(@NotNull LibraryData gradleEntity, - @NotNull LibraryPathType gradleType, - @NotNull OrderRootType ideType, - @NotNull Library ideEntity, - @NotNull ExternalProjectChangesCalculationContext context) - { - final Set<String> gradleBinaryPaths = new HashSet<String>(gradleEntity.getPaths(gradleType)); - final Set<String> ideBinaryPaths = new HashSet<String>(); - for (VirtualFile file : ideEntity.getFiles(ideType)) { - final String path = myPlatformFacade.getLocalFileSystemPath(file); - if (!gradleBinaryPaths.remove(path)) { - ideBinaryPaths.add(path); - } - } - - if (!gradleBinaryPaths.isEmpty()) { - // TODO den implement -// LibraryId libraryId = new LibraryId(ProjectSystemId.GRADLE, gradleEntity.getName()); -// for (String path : gradleBinaryPaths) { -// context.register(new JarPresenceChange(new JarId(path, gradleType, libraryId), null)); -// } - } - - if (!ideBinaryPaths.isEmpty()) { - // TODO den implement -// LibraryId libraryId = new LibraryId(ProjectSystemId.IDE, GradleUtil.getLibraryName(ideEntity)); -// for (String path : ideBinaryPaths) { -// context.register(new JarPresenceChange(null, new JarId(path, gradleType, libraryId))); -// } - } - } - - // TODO den implement -// @NotNull -// @Override -// public Object getIdeKey(@NotNull Library entity) { -// return GradleUtil.getLibraryName(entity); -// } -// -// @NotNull -// @Override -// public Object getGradleKey(@NotNull LibraryData entity, @NotNull ExternalProjectChangesCalculationContext context) { -// return entity.getName(); -// } -} diff --git a/plugins/gradle/src/org/jetbrains/plugins/gradle/diff/module/GradleModuleStructureChangesCalculator.java b/plugins/gradle/src/org/jetbrains/plugins/gradle/diff/module/GradleModuleStructureChangesCalculator.java deleted file mode 100644 index ee8fd62e4cf4..000000000000 --- a/plugins/gradle/src/org/jetbrains/plugins/gradle/diff/module/GradleModuleStructureChangesCalculator.java +++ /dev/null @@ -1,132 +0,0 @@ -/* - * Copyright 2000-2011 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.jetbrains.plugins.gradle.diff.module; - -import com.intellij.openapi.externalSystem.model.project.*; -import com.intellij.openapi.externalSystem.model.project.change.ExternalProjectStructureChangesCalculator; -import com.intellij.openapi.externalSystem.service.project.change.ExternalProjectChangesCalculationContext; -import com.intellij.openapi.module.Module; -import com.intellij.openapi.roots.LibraryOrderEntry; -import com.intellij.openapi.roots.ModuleOrderEntry; -import com.intellij.openapi.roots.OrderEntry; -import com.intellij.openapi.roots.RootPolicy; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.plugins.gradle.diff.GradleDiffUtil; -import org.jetbrains.plugins.gradle.diff.contentroot.GradleContentRootStructureChangesCalculator; -import org.jetbrains.plugins.gradle.diff.dependency.GradleLibraryDependencyStructureChangesCalculator; -import org.jetbrains.plugins.gradle.diff.dependency.GradleModuleDependencyStructureChangesCalculator; -import com.intellij.openapi.externalSystem.service.project.ModuleAwareContentRoot; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; - -/** - * Encapsulates functionality of calculating changes between Gradle and IntelliJ IDEA module hierarchies. - * <p/> - * Thread-safe. - * - * @author Denis Zhdanov - * @since 11/14/11 6:30 PM - */ -public class GradleModuleStructureChangesCalculator implements ExternalProjectStructureChangesCalculator<ModuleData, Module> { - - @NotNull private final GradleLibraryDependencyStructureChangesCalculator myLibraryDependencyCalculator; - @NotNull private final GradleModuleDependencyStructureChangesCalculator myModuleDependencyCalculator; - @NotNull private final GradleContentRootStructureChangesCalculator myContentRootCalculator; - - public GradleModuleStructureChangesCalculator(@NotNull GradleLibraryDependencyStructureChangesCalculator libraryDependencyCalculator, - @NotNull GradleModuleDependencyStructureChangesCalculator moduleDependencyCalculator, - @NotNull GradleContentRootStructureChangesCalculator calculator) - { - myLibraryDependencyCalculator = libraryDependencyCalculator; - myModuleDependencyCalculator = moduleDependencyCalculator; - myContentRootCalculator = calculator; - } - - @Override - public void calculate(@NotNull ModuleData gradleEntity, - @NotNull Module ideEntity, - @NotNull ExternalProjectChangesCalculationContext context) - { - // Content roots. - // TODO den implement -// final Collection<ContentRootData> gradleContentRoots = gradleEntity.getContentRoots(); -// final Collection<ModuleAwareContentRoot> intellijContentRoots = context.getPlatformFacade().getContentRoots(ideEntity); -// GradleDiffUtil.calculate(myContentRootCalculator, gradleContentRoots, intellijContentRoots, context); - - // Dependencies. - checkDependencies(gradleEntity, ideEntity, context); - } - - @NotNull - public Object getIdeKey(@NotNull Module entity) { - return entity.getName(); - } - - @NotNull - public Object getGradleKey(@NotNull ModuleData entity, @NotNull ExternalProjectChangesCalculationContext context) { - return entity.getName(); - } - - private void checkDependencies(@NotNull ModuleData gradleModule, - @NotNull Module intellijModule, - @NotNull ExternalProjectChangesCalculationContext context) - { - // Prepare intellij part. - final List<ModuleOrderEntry> intellijModuleDependencies = new ArrayList<ModuleOrderEntry>(); - final List<LibraryOrderEntry> intellijLibraryDependencies = new ArrayList<LibraryOrderEntry>(); - RootPolicy<Object> policy = new RootPolicy<Object>() { - @Override - public Object visitModuleOrderEntry(ModuleOrderEntry moduleOrderEntry, Object value) { - intellijModuleDependencies.add(moduleOrderEntry); - return moduleOrderEntry; - } - - @Override - public Object visitLibraryOrderEntry(LibraryOrderEntry libraryOrderEntry, Object value) { - intellijLibraryDependencies.add(libraryOrderEntry); - return libraryOrderEntry; - } - }; - for (OrderEntry orderEntry : context.getPlatformFacade().getOrderEntries(intellijModule)) { - orderEntry.accept(policy, null); - } - - // Prepare gradle part. - final List<ModuleDependencyData> gradleModuleDependencies = new ArrayList<ModuleDependencyData>(); - final List<LibraryDependencyData> gradleLibraryDependencies = new ArrayList<LibraryDependencyData>(); - // TODO den implement -// ExternalEntityVisitor visitor = new ExternalEntityVisitorAdapter() { -// @Override -// public void visit(@NotNull ModuleDependencyData dependency) { -// gradleModuleDependencies.add(dependency); -// } -// -// @Override -// public void visit(@NotNull LibraryDependencyData dependency) { -// gradleLibraryDependencies.add(dependency); -// } -// }; -// for (DependencyData dependency : gradleModule.getDependencies()) { -// dependency.invite(visitor); -// } - - // Calculate changes. - GradleDiffUtil.calculate(myLibraryDependencyCalculator, gradleLibraryDependencies, intellijLibraryDependencies, context); - GradleDiffUtil.calculate(myModuleDependencyCalculator, gradleModuleDependencies, intellijModuleDependencies, context); - } -} diff --git a/plugins/gradle/src/org/jetbrains/plugins/gradle/diff/project/GradleProjectStructureChangesCalculator.java b/plugins/gradle/src/org/jetbrains/plugins/gradle/diff/project/GradleProjectStructureChangesCalculator.java deleted file mode 100644 index 8a1e5201147d..000000000000 --- a/plugins/gradle/src/org/jetbrains/plugins/gradle/diff/project/GradleProjectStructureChangesCalculator.java +++ /dev/null @@ -1,103 +0,0 @@ -package org.jetbrains.plugins.gradle.diff.project; - -import com.intellij.openapi.externalSystem.model.project.ProjectData; -import com.intellij.openapi.externalSystem.model.project.ModuleData; -import com.intellij.openapi.externalSystem.model.project.change.ExternalProjectStructureChange; -import com.intellij.openapi.externalSystem.model.project.change.ExternalProjectStructureChangesCalculator; -import com.intellij.openapi.externalSystem.model.project.change.LanguageLevelChange; -import com.intellij.openapi.externalSystem.model.project.change.GradleProjectRenameChange; -import com.intellij.openapi.externalSystem.service.project.change.ExternalProjectChangesCalculationContext; -import com.intellij.openapi.module.Module; -import com.intellij.openapi.project.Project; -import com.intellij.openapi.roots.libraries.LibraryTable; -import com.intellij.pom.java.LanguageLevel; -import org.jetbrains.annotations.NotNull; -import com.intellij.openapi.externalSystem.service.project.PlatformFacade; -import org.jetbrains.plugins.gradle.diff.GradleDiffUtil; -import org.jetbrains.plugins.gradle.diff.library.GradleLibraryStructureChangesCalculator; -import org.jetbrains.plugins.gradle.diff.module.GradleModuleStructureChangesCalculator; - -import java.util.Arrays; -import java.util.Collection; -import java.util.Set; - -/** - * Encapsulates functionality of calculating changes between Gradle and IntelliJ IDEA project hierarchies. - * <p/> - * Thread-safe. - * - * @author Denis Zhdanov - * @since 11/3/11 3:55 PM - */ -public class GradleProjectStructureChangesCalculator implements ExternalProjectStructureChangesCalculator<ProjectData, Project> { - - @NotNull private final GradleModuleStructureChangesCalculator myModuleChangesCalculator; - @NotNull private final GradleLibraryStructureChangesCalculator myLibraryChangesCalculator; - @NotNull private final PlatformFacade myPlatformFacade; - - public GradleProjectStructureChangesCalculator(@NotNull GradleModuleStructureChangesCalculator moduleCalculator, - @NotNull GradleLibraryStructureChangesCalculator calculator, - @NotNull PlatformFacade platformFacade) - { - myModuleChangesCalculator = moduleCalculator; - myLibraryChangesCalculator = calculator; - myPlatformFacade = platformFacade; - } - - @Override - public void calculate(@NotNull ProjectData gradleEntity, - @NotNull Project ideEntity, - @NotNull ExternalProjectChangesCalculationContext context) - { - calculateProjectChanges(gradleEntity, ideEntity, context.getCurrentChanges()); - - // TODO den implement -// final Set<? extends ModuleData> gradleSubEntities = gradleEntity.getModules(); -// final Collection<Module> intellijSubEntities = myPlatformFacade.getModules(ideEntity); -// GradleDiffUtil.calculate(myModuleChangesCalculator, gradleSubEntities, intellijSubEntities, context); -// -// LibraryTable libraryTable = myPlatformFacade.getProjectLibraryTable(ideEntity); -// GradleDiffUtil.calculate(myLibraryChangesCalculator, gradleEntity.getLibraries(), Arrays.asList(libraryTable.getLibraries()), context); - } - - @NotNull - public Object getIdeKey(@NotNull Project entity) { - return entity.getName(); - } - - @NotNull - public Object getGradleKey(@NotNull ProjectData entity, @NotNull ExternalProjectChangesCalculationContext context) { - return entity.getName(); - } - - private void calculateProjectChanges(@NotNull ProjectData gradleProject, - @NotNull Project intellijProject, - @NotNull Set<ExternalProjectStructureChange> currentChanges) - { - checkName(gradleProject, intellijProject, currentChanges); - checkLanguageLevel(gradleProject, intellijProject, currentChanges); - } - - private static void checkName(@NotNull ProjectData gradleProject, - @NotNull Project intellijProject, - @NotNull Set<ExternalProjectStructureChange> currentChanges) - { - String gradleName = gradleProject.getName(); - String intellijName = intellijProject.getName(); - if (!gradleName.equals(intellijName)) { - currentChanges.add(new GradleProjectRenameChange(gradleName, intellijName)); - } - } - - private void checkLanguageLevel(@NotNull ProjectData gradleProject, - @NotNull Project intellijProject, - @NotNull Set<ExternalProjectStructureChange> currentChanges) - { - // TODO den implement -// LanguageLevel gradleLevel = gradleProject.getLanguageLevel(); -// LanguageLevel intellijLevel = myPlatformFacade.getLanguageLevel(intellijProject); -// if (gradleLevel != intellijLevel) { -// currentChanges.add(new LanguageLevelChange(gradleLevel, intellijLevel)); -// } - } -} diff --git a/plugins/gradle/src/org/jetbrains/plugins/gradle/manage/wizard/adjust/GradleAdjustImportSettingsUtil.java b/plugins/gradle/src/org/jetbrains/plugins/gradle/manage/wizard/adjust/GradleAdjustImportSettingsUtil.java deleted file mode 100644 index 9910ad2271f1..000000000000 --- a/plugins/gradle/src/org/jetbrains/plugins/gradle/manage/wizard/adjust/GradleAdjustImportSettingsUtil.java +++ /dev/null @@ -1,80 +0,0 @@ -package org.jetbrains.plugins.gradle.manage.wizard.adjust; - -import com.intellij.openapi.externalSystem.model.project.AbstractDependencyData; -import com.intellij.openapi.externalSystem.util.ExternalSystemBundle; -import com.intellij.openapi.externalSystem.util.ExternalSystemUiUtil; -import com.intellij.openapi.roots.DependencyScope; -import com.intellij.openapi.ui.MessageType; -import com.intellij.openapi.util.Pair; -import com.intellij.openapi.util.text.StringUtil; -import org.jetbrains.annotations.NotNull; -import com.intellij.openapi.externalSystem.model.project.Named; -import org.jetbrains.plugins.gradle.util.GradleUtil; - -import javax.swing.*; - -/** - * @author Denis Zhdanov - * @since 8/24/11 2:40 PM - */ -public class GradleAdjustImportSettingsUtil { - - private GradleAdjustImportSettingsUtil() { - } - - /** - * Performs generic check of the name of the given component. - * - * @param namedComponent target component - * @param componentNameUI UI control that allow to manage target component's name - * @return <code>true</code> if validation is successful; <code>false</code> otherwise - */ - public static boolean validate(@NotNull Named namedComponent, @NotNull JComponent componentNameUI) { - if (!StringUtil.isEmptyOrSpaces(namedComponent.getName())) { - return true; - } - // TODO den uncomment - //ExternalSystemUiUtil.showBalloon(componentNameUI, MessageType.ERROR, ExternalSystemBundle.message("gradle.import.text.error.undefined.name")); - return false; - } - - /** - * Allows to configure GUI controls for managing common dependency settings. - * - * @param builder target GUI builder - * @param dependency target dependency - * @return pair of two callbacks. The first one is {@link GradleProjectStructureNodeSettings#refresh() 'refresh'} callback, - * the second one is {@link GradleProjectStructureNodeSettings#validate() 'validate'} callback - */ - @NotNull - public static Pair<Runnable, Runnable> configureCommonDependencyControls(@NotNull GradleProjectSettingsBuilder builder, - @NotNull final AbstractDependencyData dependency) - { - builder.setKeyAndValueControlsOnSameRow(true); - - final JCheckBox exportedCheckBock = new JCheckBox(); - // TODO den uncomment - //builder.add("gradle.import.structure.settings.label.export", exportedCheckBock); - - final JComboBox scopeComboBox = new JComboBox(DependencyScope.values()); - // TODO den uncomment - //builder.add("gradle.import.structure.settings.label.scope", scopeComboBox); - - Runnable refreshCallback = new Runnable() { - @Override - public void run() { - exportedCheckBock.setSelected(dependency.isExported()); - scopeComboBox.setSelectedItem(dependency.getScope()); - } - }; - - Runnable validateCallback = new Runnable() { - @Override - public void run() { - dependency.setExported(exportedCheckBock.isSelected()); - dependency.setScope((DependencyScope)scopeComboBox.getSelectedItem()); - } - }; - return new Pair<Runnable, Runnable>(refreshCallback, validateCallback); - } -} diff --git a/plugins/gradle/src/org/jetbrains/plugins/gradle/manage/wizard/adjust/GradleContentRootSettings.java b/plugins/gradle/src/org/jetbrains/plugins/gradle/manage/wizard/adjust/GradleContentRootSettings.java deleted file mode 100644 index edcedf050632..000000000000 --- a/plugins/gradle/src/org/jetbrains/plugins/gradle/manage/wizard/adjust/GradleContentRootSettings.java +++ /dev/null @@ -1,69 +0,0 @@ -package org.jetbrains.plugins.gradle.manage.wizard.adjust; - -import com.intellij.ide.util.projectWizard.NamePathComponent; -import com.intellij.openapi.externalSystem.model.project.ContentRootData; -import com.intellij.openapi.externalSystem.model.project.ExternalSystemSourceType; -import com.intellij.openapi.externalSystem.util.ExternalSystemBundle; -import com.intellij.util.containers.ContainerUtilRt; -import org.jetbrains.annotations.NotNull; - -import javax.swing.*; -import java.util.Collection; -import java.util.EnumMap; -import java.util.Map; - -/** - * @author Denis Zhdanov - * @since 10/31/11 1:52 PM - */ -public class GradleContentRootSettings implements GradleProjectStructureNodeSettings { - - private static final Map<ExternalSystemSourceType, String> ROOT_TYPE_TITLES = ContainerUtilRt.newHashMap(); - - static { - // TODO den implement -// ROOT_TYPE_TITLES.put(ExternalSystemSourceType.SOURCE, -// ExternalSystemBundle.message("gradle.import.structure.settings.label.root.source")); -// ROOT_TYPE_TITLES.put(ExternalSystemSourceType.TEST, -// ExternalSystemBundle.message("gradle.import.structure.settings.label.root.test")); -// ROOT_TYPE_TITLES.put(ExternalSystemSourceType.EXCLUDED, -// ExternalSystemBundle.message("gradle.import.structure.settings.label.root.excluded")); - } - - @NotNull private final JComponent myComponent; - - public GradleContentRootSettings(@NotNull ContentRootData contentRoot) { - GradleProjectSettingsBuilder builder = new GradleProjectSettingsBuilder(); - // TODO den implement -// for (ExternalSystemSourceType sourceType : ExternalSystemSourceType.values()) { -// Collection<String> paths = contentRoot.getPaths(sourceType); -// if (paths.isEmpty()) { -// continue; -// } -// builder.add(new JLabel(ROOT_TYPE_TITLES.get(sourceType))); -// for (String path : paths) { -// NamePathComponent component = new NamePathComponent("", " ", "", "", false); -// component.setNameComponentVisible(false); -// component.setPath(path); -// component.getPathPanel().setEditable(false); -// builder.add(component, GradleProjectSettingsBuilder.InsetSize.SMALL); -// } -// } - myComponent = builder.build(); - } - - @Override - public boolean validate() { - return true; - } - - @Override - public void refresh() { - } - - @NotNull - @Override - public JComponent getComponent() { - return myComponent; - } -} diff --git a/plugins/gradle/src/org/jetbrains/plugins/gradle/manage/wizard/adjust/GradleJarSettings.java b/plugins/gradle/src/org/jetbrains/plugins/gradle/manage/wizard/adjust/GradleJarSettings.java deleted file mode 100644 index c187fecee849..000000000000 --- a/plugins/gradle/src/org/jetbrains/plugins/gradle/manage/wizard/adjust/GradleJarSettings.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * 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 org.jetbrains.plugins.gradle.manage.wizard.adjust; - -import com.intellij.ide.util.projectWizard.NamePathComponent; -import com.intellij.openapi.externalSystem.model.project.JarData; -import com.intellij.openapi.externalSystem.util.ExternalSystemBundle; -import org.jetbrains.annotations.NotNull; - -import javax.swing.*; - -/** - * @author Denis Zhdanov - * @since 12/12/12 2:16 PM - */ -public class GradleJarSettings implements GradleProjectStructureNodeSettings { - - @NotNull private final JComponent myComponent; - - public GradleJarSettings(@NotNull JarData jar) { - GradleProjectSettingsBuilder builder = new GradleProjectSettingsBuilder(); - builder.add(new JLabel(ExternalSystemBundle.message("gradle.import.structure.settings.label.jar.path"))); - NamePathComponent component = new NamePathComponent("", " ", "", "", false); - component.setNameComponentVisible(false); - component.setPath(jar.getPath()); - component.getPathPanel().setEditable(false); - builder.add(component, GradleProjectSettingsBuilder.InsetSize.SMALL); - - myComponent = builder.build(); - } - - @Override - public boolean validate() { - return true; - } - - @Override - public void refresh() { - } - - @NotNull - @Override - public JComponent getComponent() { - return myComponent; - } -} diff --git a/plugins/gradle/src/org/jetbrains/plugins/gradle/manage/wizard/adjust/GradleLibraryDependencySettings.java b/plugins/gradle/src/org/jetbrains/plugins/gradle/manage/wizard/adjust/GradleLibraryDependencySettings.java deleted file mode 100644 index 320c47798c78..000000000000 --- a/plugins/gradle/src/org/jetbrains/plugins/gradle/manage/wizard/adjust/GradleLibraryDependencySettings.java +++ /dev/null @@ -1,52 +0,0 @@ -package org.jetbrains.plugins.gradle.manage.wizard.adjust; - -import com.intellij.openapi.externalSystem.model.project.LibraryDependencyData; -import com.intellij.openapi.util.Pair; -import org.jetbrains.annotations.NotNull; - -import javax.swing.*; - -/** - * @author Denis Zhdanov - * @since 10/24/11 3:00 PM - */ -public class GradleLibraryDependencySettings implements GradleProjectStructureNodeSettings { - - private final GradleLibrarySettings myLibrarySettings; - private final Runnable myRefreshCallback; - private final Runnable myValidateCallback; - private final JComponent myComponent; - - public GradleLibraryDependencySettings(@NotNull LibraryDependencyData dependency) { - myLibrarySettings = new GradleLibrarySettings(); - - GradleProjectSettingsBuilder builder = new GradleProjectSettingsBuilder(); - builder.add(myLibrarySettings.getComponent(), GradleProjectSettingsBuilder.InsetSize.NONE); - Pair<Runnable,Runnable> pair = GradleAdjustImportSettingsUtil.configureCommonDependencyControls(builder, dependency); - myRefreshCallback = pair.first; - myValidateCallback = pair.second; - myComponent = builder.build(); - refresh(); - } - - @Override - public void refresh() { - myLibrarySettings.refresh(); - myRefreshCallback.run(); - } - - @Override - public boolean validate() { - if (!myLibrarySettings.validate()) { - return false; - } - myValidateCallback.run(); - return true; - } - - @NotNull - @Override - public JComponent getComponent() { - return myComponent; - } -} diff --git a/plugins/gradle/src/org/jetbrains/plugins/gradle/manage/wizard/adjust/GradleLibrarySettings.java b/plugins/gradle/src/org/jetbrains/plugins/gradle/manage/wizard/adjust/GradleLibrarySettings.java deleted file mode 100644 index ad00e7e97554..000000000000 --- a/plugins/gradle/src/org/jetbrains/plugins/gradle/manage/wizard/adjust/GradleLibrarySettings.java +++ /dev/null @@ -1,33 +0,0 @@ -package org.jetbrains.plugins.gradle.manage.wizard.adjust; - -import org.jetbrains.annotations.NotNull; - -import javax.swing.*; - -/** - * @author Denis Zhdanov - * @since 8/23/11 4:22 PM - */ -public class GradleLibrarySettings implements GradleProjectStructureNodeSettings { - - private final JComponent myComponent; - - public GradleLibrarySettings() { - myComponent = new JPanel(); - } - - @Override - public boolean validate() { - return true; - } - - @Override - public void refresh() { - } - - @NotNull - @Override - public JComponent getComponent() { - return myComponent; - } -} diff --git a/plugins/gradle/src/org/jetbrains/plugins/gradle/manage/wizard/adjust/GradleModuleDependencySettings.java b/plugins/gradle/src/org/jetbrains/plugins/gradle/manage/wizard/adjust/GradleModuleDependencySettings.java deleted file mode 100644 index fbd0ec8e2ae1..000000000000 --- a/plugins/gradle/src/org/jetbrains/plugins/gradle/manage/wizard/adjust/GradleModuleDependencySettings.java +++ /dev/null @@ -1,52 +0,0 @@ -package org.jetbrains.plugins.gradle.manage.wizard.adjust; - -import com.intellij.openapi.externalSystem.model.project.ModuleDependencyData; -import com.intellij.openapi.util.Pair; -import org.jetbrains.annotations.NotNull; - -import javax.swing.*; - -/** - * @author Denis Zhdanov - * @since 10/28/11 12:40 PM - */ -public class GradleModuleDependencySettings implements GradleProjectStructureNodeSettings { - - private final GradleModuleSettings myModuleSettings; - private final Runnable myRefreshCallback; - private final Runnable myValidateCallback; - private final JComponent myComponent; - - public GradleModuleDependencySettings(@NotNull ModuleDependencyData dependency) { - myModuleSettings = new GradleModuleSettings(dependency.getTarget()); - - GradleProjectSettingsBuilder builder = new GradleProjectSettingsBuilder(); - builder.add(myModuleSettings.getComponent(), GradleProjectSettingsBuilder.InsetSize.NONE); - Pair<Runnable,Runnable> pair = GradleAdjustImportSettingsUtil.configureCommonDependencyControls(builder, dependency); - myRefreshCallback = pair.first; - myValidateCallback = pair.second; - myComponent = builder.build(); - refresh(); - } - - @Override - public boolean validate() { - if (!myModuleSettings.validate()) { - return false; - } - myValidateCallback.run(); - return true; - } - - @Override - public void refresh() { - myModuleSettings.refresh(); - myRefreshCallback.run(); - } - - @NotNull - @Override - public JComponent getComponent() { - return myComponent; - } -} diff --git a/plugins/gradle/src/org/jetbrains/plugins/gradle/manage/wizard/adjust/GradleModuleSettings.java b/plugins/gradle/src/org/jetbrains/plugins/gradle/manage/wizard/adjust/GradleModuleSettings.java deleted file mode 100644 index 4406d227d7eb..000000000000 --- a/plugins/gradle/src/org/jetbrains/plugins/gradle/manage/wizard/adjust/GradleModuleSettings.java +++ /dev/null @@ -1,134 +0,0 @@ -package org.jetbrains.plugins.gradle.manage.wizard.adjust; - -import com.intellij.ide.util.BrowseFilesListener; -import com.intellij.openapi.externalSystem.model.project.ModuleData; -import com.intellij.openapi.externalSystem.model.project.ExternalSystemSourceType; -import com.intellij.openapi.externalSystem.util.ExternalSystemBundle; -import com.intellij.openapi.externalSystem.util.ExternalSystemUiUtil; -import com.intellij.openapi.project.ProjectBundle; -import com.intellij.openapi.ui.MessageType; -import com.intellij.openapi.ui.TextFieldWithBrowseButton; -import com.intellij.openapi.util.Pair; -import com.intellij.openapi.util.text.StringUtil; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.plugins.gradle.util.GradleUtil; - -import javax.swing.*; -import java.awt.event.ItemEvent; -import java.awt.event.ItemListener; - -/** - * Manages settings of {@link ModuleData gradle module} component. - * - * @author Denis Zhdanov - * @since 8/12/11 3:39 PM - */ -public class GradleModuleSettings implements GradleProjectStructureNodeSettings { - - private final JComponent myComponent; - private final ModuleData myModule; - private final JRadioButton myInheritProjectCompileOutputPathButton; - private final JRadioButton myUseModuleCompileOutputPathButton; - private final TextFieldWithBrowseButton myOutputLocationField; - private final TextFieldWithBrowseButton myTestOutputLocationField; - - public GradleModuleSettings(@NotNull ModuleData module) { - myModule = module; - GradleProjectSettingsBuilder builder = new GradleProjectSettingsBuilder(); - Pair<JRadioButton, JRadioButton> pair = setupCompileOutput(builder); - myInheritProjectCompileOutputPathButton = pair.first; - myUseModuleCompileOutputPathButton = pair.second; - Pair<TextFieldWithBrowseButton, TextFieldWithBrowseButton> locationPair = setupOutputLocation(builder); - myOutputLocationField = locationPair.first; - myTestOutputLocationField = locationPair.second; - myComponent = builder.build(); - refresh(); - } - - @NotNull - private Pair<JRadioButton, JRadioButton> setupCompileOutput(@NotNull GradleProjectSettingsBuilder builder) { - JRadioButton inheritButton = new JRadioButton(ProjectBundle.message("project.inherit.compile.output.path")); - JRadioButton moduleButton = new JRadioButton(ProjectBundle.message("project.module.compile.output.path")); - ButtonGroup group = new ButtonGroup(); - group.add(inheritButton); - group.add(moduleButton); - builder.add(inheritButton); - builder.add(moduleButton, GradleProjectSettingsBuilder.InsetSize.SMALL); - ItemListener listener = new ItemListener() { - @Override - public void itemStateChanged(ItemEvent e) { - myOutputLocationField.setEditable(myUseModuleCompileOutputPathButton.isSelected()); - myTestOutputLocationField.setEditable(myUseModuleCompileOutputPathButton.isSelected()); - } - }; - inheritButton.addItemListener(listener); - moduleButton.addItemListener(listener); - return new Pair<JRadioButton, JRadioButton>(inheritButton, moduleButton); - } - - @NotNull - private static Pair<TextFieldWithBrowseButton, TextFieldWithBrowseButton> setupOutputLocation( - @NotNull GradleProjectSettingsBuilder builder) - { - TextFieldWithBrowseButton outputField = new TextFieldWithBrowseButton(); - String title = ProjectBundle.message("module.paths.output.label"); - outputField.addBrowseFolderListener(title, "", null, BrowseFilesListener.SINGLE_DIRECTORY_DESCRIPTOR); - builder.add(new JLabel(title), outputField, GradleProjectSettingsBuilder.InsetSize.SMALL); - - TextFieldWithBrowseButton testOutputField = new TextFieldWithBrowseButton(); - title = ProjectBundle.message("module.paths.test.output.label"); - testOutputField.addBrowseFolderListener(title, "", null, BrowseFilesListener.SINGLE_DIRECTORY_DESCRIPTOR); - builder.add(new JLabel(title), testOutputField, GradleProjectSettingsBuilder.InsetSize.SMALL); - - return new Pair<TextFieldWithBrowseButton, TextFieldWithBrowseButton>(outputField, testOutputField); - } - - @Override - public boolean validate() { - if (myUseModuleCompileOutputPathButton.isSelected()) { - String outputLocation = myOutputLocationField.getText(); - if (outputLocation == null || StringUtil.isEmpty(outputLocation.trim())) { - // TODO den uncomment - } - // ExternalSystemUiUtil.showBalloon( - // myOutputLocationField, - // MessageType.ERROR, - // ExternalSystemBundle.message("gradle.import.text.error.file.module.compile.output.location") - // ); - // return false; - //} - String testOutputLocation = myTestOutputLocationField.getText(); - // TODO den uncomment - //if (testOutputLocation == null || StringUtil.isEmpty(testOutputLocation.trim())) { - // ExternalSystemUiUtil.showBalloon( - // myTestOutputLocationField, - // MessageType.ERROR, - // ExternalSystemBundle.message("gradle.import.text.error.file.module.test.output.location") - // ); - // return false; - //} - myModule.setCompileOutputPath(ExternalSystemSourceType.SOURCE, outputLocation.trim()); - myModule.setCompileOutputPath(ExternalSystemSourceType.TEST, testOutputLocation.trim()); - } - myModule.setInheritProjectCompileOutputPath(myInheritProjectCompileOutputPathButton.isSelected()); - return true; - } - - @Override - public void refresh() { - if (myModule.isInheritProjectCompileOutputPath()) { - myInheritProjectCompileOutputPathButton.setSelected(true); - } - else { - myUseModuleCompileOutputPathButton.setSelected(true); - } - myOutputLocationField.setText(myModule.getCompileOutputPath(ExternalSystemSourceType.SOURCE)); - myTestOutputLocationField.setText(myModule.getCompileOutputPath(ExternalSystemSourceType.TEST)); - } - - @NotNull - @Override - public JComponent getComponent() { - return myComponent; - } -} diff --git a/plugins/gradle/src/org/jetbrains/plugins/gradle/manage/wizard/adjust/GradleProjectSettings.java b/plugins/gradle/src/org/jetbrains/plugins/gradle/manage/wizard/adjust/GradleProjectSettings.java deleted file mode 100644 index c0ac1f441027..000000000000 --- a/plugins/gradle/src/org/jetbrains/plugins/gradle/manage/wizard/adjust/GradleProjectSettings.java +++ /dev/null @@ -1,271 +0,0 @@ -package org.jetbrains.plugins.gradle.manage.wizard.adjust; - -import com.intellij.ide.util.PropertiesComponent; -import com.intellij.openapi.externalSystem.model.project.ProjectData; -import com.intellij.openapi.externalSystem.util.ExternalSystemBundle; -import com.intellij.openapi.externalSystem.util.ExternalSystemUiUtil; -import com.intellij.openapi.projectRoots.JavaSdk; -import com.intellij.openapi.projectRoots.JavaSdkVersion; -import com.intellij.openapi.projectRoots.ProjectJdkTable; -import com.intellij.openapi.projectRoots.Sdk; -import com.intellij.openapi.ui.MessageType; -import com.intellij.openapi.ui.TextFieldWithBrowseButton; -import com.intellij.openapi.util.io.FileUtilRt; -import com.intellij.openapi.util.text.StringUtil; -import com.intellij.pom.java.LanguageLevel; -import com.intellij.ui.components.JBRadioButton; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.PropertyKey; -import org.jetbrains.plugins.gradle.util.GradleBundle; - -import javax.swing.*; -import java.awt.*; -import java.awt.event.ItemEvent; -import java.awt.event.ItemListener; -import java.io.File; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -/** - * Manages settings of {@link ProjectData gradle project} component. - * - * @author Denis Zhdanov - * @since 8/12/11 2:58 PM - */ -public class GradleProjectSettings implements GradleProjectStructureNodeSettings { - - private static final String KEEP_IML_AT_MODULE_DIR_PROPERTY_KEY = "gradle.iml.at.module.dir"; - - @NotNull private final JComponent myComponent; - @NotNull private final ProjectData myProject; - @NotNull private final JComboBox myLanguageLevelComboBox; - @NotNull private final DefaultComboBoxModel mySdkModel; - @NotNull private final TextFieldWithBrowseButton myProjectConfigLocationField; - @NotNull private final TextFieldWithBrowseButton myProjectCompileOutputLocationField; - @NotNull private final JRadioButton myImlAtModuleContentRootsButton; - @NotNull private final JRadioButton myImlAtProjectDirButton; - - public GradleProjectSettings(@NotNull ProjectData project) { - myProject = project; - GradleProjectSettingsBuilder builder = new GradleProjectSettingsBuilder(); - myLanguageLevelComboBox = setupLanguageLevelControls(builder); - setupSdkControls(mySdkModel = new DefaultComboBoxModel(), builder); - myProjectConfigLocationField = setupProjectConfigLocation(builder); - myProjectCompileOutputLocationField = setupProjectCompileOutputLocation(builder); - filterSdksByLanguageLevel(); - myImlAtModuleContentRootsButton = - new JBRadioButton(GradleBundle.message("gradle.import.structure.settings.label.iml.location.per.module")); - myImlAtProjectDirButton = new JBRadioButton( - GradleBundle.message("gradle.import.structure.settings.label.iml.location.project.dir")); - setModuleFilesLocationControl(builder); - myComponent = builder.build(); - refresh(); - } - - private JComboBox setupLanguageLevelControls(@NotNull GradleProjectSettingsBuilder builder) { - JComboBox result = new JComboBox(); - final Map<Object, LanguageLevel> levels = new HashMap<Object, LanguageLevel>(); - for (LanguageLevel level : LanguageLevel.values()) { - levels.put(level.getPresentableText(), level); - result.addItem(level.getPresentableText()); - } - result.addItemListener(new ItemListener() { - @Override - public void itemStateChanged(ItemEvent e) { - // TODO den implement -// myProject.setLanguageLevel(levels.get(e.getItem())); - filterSdksByLanguageLevel(); - } - }); - // TODO den implement -// builder.add("gradle.import.structure.settings.label.language.level", result); - return result; - } - - private void filterSdksByLanguageLevel() { - Object selectedItem = mySdkModel.getSelectedItem(); - mySdkModel.removeAllElements(); - // TODO den implement - LanguageLevel languageLevel = null; -// LanguageLevel languageLevel = myProject.getLanguageLevel(); - boolean restoreSelection = false; - List<Sdk> matchedRegisteredSdks = new ArrayList<Sdk>(); - JavaSdk javaSdk = JavaSdk.getInstance(); - List<Sdk> javaSdks = ProjectJdkTable.getInstance().getSdksOfType(javaSdk); - for (Sdk sdk : javaSdks) { - JavaSdkVersion version = javaSdk.getVersion(sdk); - if (version == null || !version.getMaxLanguageLevel().isAtLeast(languageLevel)) { - continue; - } - matchedRegisteredSdks.add(sdk); - } - - // TODO den implement -// if (matchedRegisteredSdks.isEmpty()) { -// mySdkModel.addElement(ExternalSystemBundle.message("gradle.import.structure.settings.no.sdk.for.language.level.text")); -// } - - for (Sdk sdk : matchedRegisteredSdks) { - mySdkModel.addElement(sdk.getName()); - if (sdk.getName().equals(selectedItem)) { - restoreSelection = true; - } - } - - if (restoreSelection) { - mySdkModel.setSelectedItem(selectedItem); - } - } - - private void setupSdkControls(@NotNull ComboBoxModel model, @NotNull GradleProjectSettingsBuilder builder) { - // Configure SDK combo box with all jdk versions. - final JComboBox sdkComboBox = new JComboBox(model); - sdkComboBox.addItemListener(new ItemListener() { - @Override - public void itemStateChanged(ItemEvent e) { - Object selectedItem = sdkComboBox.getSelectedItem(); - if (selectedItem == null) { - return; - } - Sdk sdk = ProjectJdkTable.getInstance().findJdk(selectedItem.toString()); - if (sdk != null) { - // TODO den implement -// myProject.setSdk(sdk); - } - } - }); - // TODO den implement -// builder.add("gradle.import.structure.settings.label.sdk", sdkComboBox); - } - - @NotNull - private TextFieldWithBrowseButton setupProjectConfigLocation(@NotNull GradleProjectSettingsBuilder builder) { - TextFieldWithBrowseButton result = new TextFieldWithBrowseButton(); - // TODO den implement -// String title = ExternalSystemBundle.message("gradle.import.structure.settings.title.project.config.location"); -// result.addBrowseFolderListener(title, "", null, BrowseFilesListener.SINGLE_DIRECTORY_DESCRIPTOR); -// result.setText(myProject.getProjectFileDirectoryPath()); -// builder.add("gradle.import.structure.settings.label.project.config.location", result); - return result; - } - - @NotNull - private TextFieldWithBrowseButton setupProjectCompileOutputLocation(@NotNull GradleProjectSettingsBuilder builder) { - TextFieldWithBrowseButton result = new TextFieldWithBrowseButton(); - // TODO den implement -// String title = ExternalSystemBundle.message("gradle.import.structure.settings.title.project.compile.output.location"); -// result.addBrowseFolderListener(title, "", null, BrowseFilesListener.SINGLE_DIRECTORY_DESCRIPTOR); -// result.setText(myProject.getCompileOutputPath()); -// builder.add("gradle.import.structure.settings.label.project.compile.output.location", result); - return result; - } - - private void setModuleFilesLocationControl(@NotNull GradleProjectSettingsBuilder builder) { - ButtonGroup group = new ButtonGroup(); - group.add(myImlAtModuleContentRootsButton); - group.add(myImlAtProjectDirButton); - JPanel panel = new JPanel(new GridLayout(2, 1)); - panel.add(myImlAtModuleContentRootsButton); - panel.add(myImlAtProjectDirButton); - myImlAtModuleContentRootsButton.addItemListener(new ItemListener() { - @Override - public void itemStateChanged(ItemEvent e) { - if (e.getStateChange() != ItemEvent.SELECTED) { - return; - } - // TODO den implement -// for (ModuleData module : myProject.getModules()) { -// Collection<ContentRootData> contentRoots = module.getContentRoots(); -// if (contentRoots.isEmpty()) { -// continue; -// } -// module.setModuleFileDirectoryPath(contentRoots.iterator().next().getRootPath()); -// } - PropertiesComponent.getInstance().setValue(KEEP_IML_AT_MODULE_DIR_PROPERTY_KEY, String.valueOf(true)); - } - }); - myImlAtProjectDirButton.addItemListener(new ItemListener() { - @Override - public void itemStateChanged(ItemEvent e) { - if (e.getStateChange() != ItemEvent.SELECTED) { - return; - } - String dirPath = myProjectConfigLocationField.getText(); - if (StringUtil.isEmpty(dirPath)) { - return; - } - boolean goodDir = FileUtilRt.createDirectory(new File(dirPath)); - if (!goodDir) { - return; - } - // TODO den implement -// for (ModuleData module : myProject.getModules()) { -// module.setModuleFileDirectoryPath(dirPath); -// } - PropertiesComponent.getInstance().setValue(KEEP_IML_AT_MODULE_DIR_PROPERTY_KEY, String.valueOf(false)); - } - }); - boolean imlAtModuleDir = PropertiesComponent.getInstance().getBoolean(KEEP_IML_AT_MODULE_DIR_PROPERTY_KEY, true); - if (imlAtModuleDir) { - myImlAtModuleContentRootsButton.setSelected(true); - } - else { - myImlAtProjectDirButton.setSelected(true); - } - // TODO den implement -// builder.add("gradle.import.structure.settings.label.iml.location", panel); - } - - @Override - public boolean validate() { - // TODO den implement -// if (!validateDirLocation(myProjectConfigLocationField, "gradle.import.text.error.project.undefined.config.location", -// "gradle.import.text.error.file.config.location")) -// { -// return false; -// } -// myProject.setProjectFileDirectoryPath(myProjectConfigLocationField.getText()); -// -// if (!validateDirLocation(myProjectCompileOutputLocationField, "gradle.import.text.error.undefined.project.compile.output.location", -// "gradle.import.text.error.file.project.compile.output.location")) -// { -// return false; -// } -// myProject.setCompileOutputPath(myProjectCompileOutputLocationField.getText()); - - return true; - } - - @Override - public void refresh() { - myProjectConfigLocationField.setText(myProject.getProjectFileDirectoryPath()); - // TODO den implement -// myProjectCompileOutputLocationField.setText(myProject.getCompileOutputPath()); -// myLanguageLevelComboBox.setSelectedItem(myProject.getLanguageLevel().getPresentableText()); - } - - private static boolean validateDirLocation( - @NotNull TextFieldWithBrowseButton dataHolder, - @NotNull @PropertyKey(resourceBundle = ExternalSystemBundle.PATH_TO_BUNDLE)String undefinedPathMessageKey, - @NotNull @PropertyKey(resourceBundle = ExternalSystemBundle.PATH_TO_BUNDLE) String filePathMessageKey) - { - String path = dataHolder.getText(); - if (path == null || path.trim().isEmpty()) { - ExternalSystemUiUtil.showBalloon(dataHolder, MessageType.ERROR, ExternalSystemBundle.message(undefinedPathMessageKey)); - return false; - } - else if (new File(path).isFile()) { - ExternalSystemUiUtil.showBalloon(dataHolder, MessageType.ERROR, ExternalSystemBundle.message(filePathMessageKey)); - return false; - } - return true; - } - - @NotNull - @Override - public JComponent getComponent() { - return myComponent; - } -} diff --git a/plugins/gradle/src/org/jetbrains/plugins/gradle/manage/wizard/adjust/GradleProjectSettingsBuilder.java b/plugins/gradle/src/org/jetbrains/plugins/gradle/manage/wizard/adjust/GradleProjectSettingsBuilder.java deleted file mode 100644 index d4711e5c76c5..000000000000 --- a/plugins/gradle/src/org/jetbrains/plugins/gradle/manage/wizard/adjust/GradleProjectSettingsBuilder.java +++ /dev/null @@ -1,130 +0,0 @@ -package org.jetbrains.plugins.gradle.manage.wizard.adjust; - -import com.intellij.openapi.externalSystem.util.ExternalSystemBundle; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.PropertyKey; - -import javax.swing.*; -import java.awt.*; - -/** - * Reliefs implementation of the {@link GradleProjectStructureNodeSettings#getComponent() GUI for managing gradle entity settings}. - * <p/> - * Basically, assumes that all settings are displayed at the two-columns view where left column holds setting name and the right one - * holds GUI control that shows current setting value and/or allows to modify it. - * <p/> - * See method-level documentation for more details. - * - * @author Denis Zhdanov - * @since 8/12/11 3:03 PM - */ -public class GradleProjectSettingsBuilder { - - public enum InsetSize { - NONE(0), SMALL(3), NORMAL(15); - - private final int myInsetValue; - - InsetSize(int insetValue) { - myInsetValue = insetValue; - } - - public int getValue() { - return myInsetValue; - } - } - - private final JPanel myResult = new JPanel(new GridBagLayout()); - private final GridBagConstraints myKeyConstraint = new GridBagConstraints(); - private final GridBagConstraints myValueConstraint = new GridBagConstraints(); - - public GradleProjectSettingsBuilder() { - myKeyConstraint.anchor = myValueConstraint.anchor = GridBagConstraints.WEST; - myKeyConstraint.gridwidth = myValueConstraint.gridwidth = GridBagConstraints.REMAINDER; - myKeyConstraint.weightx = myValueConstraint.weightx = 1; - myKeyConstraint.fill = myValueConstraint.fill = GridBagConstraints.HORIZONTAL; - myKeyConstraint.insets.top = InsetSize.NORMAL.getValue(); - myValueConstraint.insets.top = InsetSize.SMALL.getValue(); - } - - public void add(@NotNull JComponent component) { - add(component, InsetSize.NORMAL); - } - - /** - * Instructs current builder to use given component for the target property management. - * - * @param component component to use - * @param insetSize top insets to use - */ - public void add(@NotNull JComponent component, @NotNull InsetSize insetSize) { - int insetsToRestore = myValueConstraint.insets.top; - myValueConstraint.insets.top = insetSize.getValue(); - myResult.add(component, myValueConstraint); - myValueConstraint.insets.top = insetsToRestore; - } - - /** - * Instructs current builder to use given property key for the setting label name retrieval and given control for - * the settings value processing - * - * @param labelKey bundle key to use for retrieving setting's label name - * @param control GUI control for managing target setting's value - */ - public void add(@NotNull @PropertyKey(resourceBundle = ExternalSystemBundle.PATH_TO_BUNDLE) String labelKey, @NotNull JComponent control) { - myResult.add(new JLabel(ExternalSystemBundle.message(labelKey)), myKeyConstraint); - myResult.add(control, myValueConstraint); - } - - /** - * Shortcut for calling {@link #add(JComponent, JComponent, InsetSize)} with {@link InsetSize#NORMAL}. - * - * @param keyComponent control that provides information about the target property (e.g. its name or description) - * @param valueComponent control that holds available property values and (possibly) allows to choose between them - */ - public void add(@NotNull JComponent keyComponent, @NotNull JComponent valueComponent) { - add(keyComponent, valueComponent, InsetSize.NORMAL); - } - - /** - * Instructs current builder to expose target property using the given UI controls. - * - * @param keyComponent control that provides information about the target property (e.g. its name or description) - * @param valueComponent control that holds available property values and (possibly) allows to choose between them - * @param insetSize top vertical inset to use for the 'key' component - */ - public void add(@NotNull JComponent keyComponent, @NotNull JComponent valueComponent, @NotNull InsetSize insetSize) { - int insetToRestore = myKeyConstraint.insets.top; - myKeyConstraint.insets.top = insetSize.getValue(); - - myResult.add(keyComponent, myKeyConstraint); - myResult.add(valueComponent, myValueConstraint); - - myKeyConstraint.insets.top = insetToRestore; - } - - /** - * Allows to define whether 'key'/'value' components ({@link #add(String, JComponent)}, {@link #add(JComponent, JComponent)}) - * should be located on the same line. - * - * @param sameRow flag that defines whether 'key'/'value' components should be located on the same line - */ - public void setKeyAndValueControlsOnSameRow(boolean sameRow) { - myKeyConstraint.gridwidth = sameRow ? 1 : GridBagConstraints.REMAINDER; - myKeyConstraint.weightx = sameRow ? 0 : 1; - myValueConstraint.insets.top = sameRow ? InsetSize.NORMAL.getValue() : InsetSize.SMALL.getValue(); - } - - /** - * @return GUI component that shows all of the stuff registered earlier via {@link #add(String, JComponent)} - */ - @NotNull - public JComponent build() { - // We don't check that this method hasn't been called already. Add that check if necessary. - GridBagConstraints constraints = new GridBagConstraints(); - constraints.weighty = 1; - constraints.fill = GridBagConstraints.VERTICAL; - myResult.add(new JLabel(""), constraints); - return myResult; - } -} diff --git a/plugins/gradle/src/org/jetbrains/plugins/gradle/manage/wizard/adjust/GradleProjectStructureFactory.java b/plugins/gradle/src/org/jetbrains/plugins/gradle/manage/wizard/adjust/GradleProjectStructureFactory.java deleted file mode 100644 index e832caaabd5d..000000000000 --- a/plugins/gradle/src/org/jetbrains/plugins/gradle/manage/wizard/adjust/GradleProjectStructureFactory.java +++ /dev/null @@ -1,163 +0,0 @@ -package org.jetbrains.plugins.gradle.manage.wizard.adjust; - -import com.intellij.openapi.externalSystem.model.project.*; -import com.intellij.openapi.externalSystem.model.project.id.EntityIdMapper; -import com.intellij.openapi.externalSystem.model.project.id.ProjectEntityId; -import com.intellij.openapi.externalSystem.ui.ProjectStructureNode; -import com.intellij.openapi.externalSystem.util.ExternalSystemBundle; -import com.intellij.openapi.util.Ref; -import org.jetbrains.annotations.NotNull; -import com.intellij.openapi.externalSystem.ui.ProjectStructureNodeDescriptor; -import org.jetbrains.plugins.gradle.util.GradleUtil; - -import javax.swing.tree.DefaultTreeModel; -import java.beans.PropertyChangeEvent; -import java.beans.PropertyChangeListener; -import java.util.Collection; - -/** - * Allows to build various entities related to the 'project structure' view elements. - * <p/> - * Thread-safe. - * <p/> - * This class is not singleton but offers single-point-of-usage field - {@link #INSTANCE}. - * - * @author Denis Zhdanov - * @since 8/12/11 2:52 PM - */ -public class GradleProjectStructureFactory { - - /** Shared instance of the current (stateless) class. */ - public static final GradleProjectStructureFactory INSTANCE = new GradleProjectStructureFactory(); - - @SuppressWarnings({"MethodMayBeStatic", "unchecked"}) - @NotNull - public <T extends ProjectEntityData> ProjectStructureNodeDescriptor<ProjectEntityId> buildDescriptor(@NotNull T entity) { - final Ref<String> text = new Ref<String>(); - // TODO den implement -// entity.invite(new ExternalEntityVisitor() { -// @Override -// public void visit(@NotNull ProjectData project) { -// text.set(project.getName()); -// } -// -// @Override -// public void visit(@NotNull ModuleData module) { -// text.set(module.getName()); -// } -// -// @Override -// public void visit(@NotNull ContentRootData contentRoot) { -// text.set(ExternalSystemBundle.message("gradle.import.structure.tree.node.content.root")); -// } -// -// @Override -// public void visit(@NotNull LibraryData library) { -// text.set(library.getName()); -// } -// -// @Override -// public void visit(@NotNull JarData jar) { -// text.set(GradleUtil.extractNameFromPath(jar.getPath())); -// } -// -// @Override -// public void visit(@NotNull ModuleDependencyData dependency) { -// visit(dependency.getTarget()); -// } -// -// @Override -// public void visit(@NotNull LibraryDependencyData dependency) { -// visit(dependency.getTarget()); -// } -// -// @Override -// public void visit(@NotNull CompositeLibraryDependencyData dependency) { -// assert false; // We don't expect outdated library during importing project. -// } -// }); - return GradleUtil.buildDescriptor(EntityIdMapper.mapEntityToId(entity), text.get()); - } - - @SuppressWarnings("MethodMayBeStatic") - @NotNull - public GradleProjectStructureNodeSettings buildSettings(@NotNull ProjectEntityData entity, - @NotNull final DefaultTreeModel treeModel, - @NotNull final Collection<ProjectStructureNode> treeNodes) - { - final Ref<GradleProjectStructureNodeSettings> result = new Ref<GradleProjectStructureNodeSettings>(); - // TODO den implement -// entity.invite(new ExternalEntityVisitor() { -// @Override -// public void visit(@NotNull ProjectData project) { -// setupController(project, treeModel, treeNodes); -// result.set(new GradleProjectSettings(project)); -// } -// -// @Override -// public void visit(@NotNull ModuleData module) { -// setupController(module, treeModel, treeNodes); -// result.set(new GradleModuleSettings(module)); -// } -// -// @Override -// public void visit(@NotNull ContentRootData contentRoot) { -// result.set(new GradleContentRootSettings(contentRoot)); -// } -// -// @Override -// public void visit(@NotNull LibraryData library) { -// result.set(new GradleLibrarySettings()); -// } -// -// @Override -// public void visit(@NotNull JarData jar) { -// result.set(new GradleJarSettings(jar)); -// } -// -// @Override -// public void visit(@NotNull ModuleDependencyData dependency) { -// setupController(dependency, treeModel, treeNodes); -// result.set(new GradleModuleDependencySettings(dependency)); -// } -// -// @Override -// public void visit(@NotNull LibraryDependencyData dependency) { -// setupController(dependency, treeModel, treeNodes); -// result.set(new GradleLibraryDependencySettings(dependency)); -// } -// -// @Override -// public void visit(@NotNull CompositeLibraryDependencyData dependency) { -// assert false; // We don't expect outdated library during importing project. -// } -// }); - return result.get(); - } - - /** - * Configures controller that delegates entity state change to all corresponding nodes. - * - * @param entity target entity to wrap - * @param model model of the target tree - * @param treeNodes tree nodes that represent the given entity - */ - @SuppressWarnings("unchecked") - private static void setupController(@NotNull final ProjectEntityData entity, @NotNull final DefaultTreeModel model, - @NotNull final Collection<ProjectStructureNode> treeNodes) - { - - entity.addPropertyChangeListener(new PropertyChangeListener() { - @Override - public void propertyChange(PropertyChangeEvent evt) { - if (!Named.NAME_PROPERTY.equals(evt.getPropertyName())) { - return; - } - for (ProjectStructureNode node : treeNodes) { - node.getDescriptor().setName(evt.getNewValue().toString()); - model.nodeChanged(node); - } - } - }); - } -} diff --git a/plugins/gradle/src/org/jetbrains/plugins/gradle/manage/wizard/adjust/GradleProjectStructureNodeSettings.java b/plugins/gradle/src/org/jetbrains/plugins/gradle/manage/wizard/adjust/GradleProjectStructureNodeSettings.java deleted file mode 100644 index 2c5404e0aa4d..000000000000 --- a/plugins/gradle/src/org/jetbrains/plugins/gradle/manage/wizard/adjust/GradleProjectStructureNodeSettings.java +++ /dev/null @@ -1,39 +0,0 @@ -package org.jetbrains.plugins.gradle.manage.wizard.adjust; - -import org.jetbrains.annotations.NotNull; - -import javax.swing.*; - -/** - * Defines contract for the control that exposes settings of particular node of the 'project structure' view derived from gradle. - * - * @author Denis Zhdanov - * @since 8/12/11 2:50 PM - */ -public interface GradleProjectStructureNodeSettings { - - /** - * Asks current component to validate current model state, i.e. expected actions sequence is below: - * <p/> - * <pre> - * <ol> - * <li> - * Particular node settings are {@link #getComponent() exposed} to the end user; - * </li> - * <li>He or she tweaks the settings;</li> - * <li>This method is called on request to finish editing;</li> - * </ol> - * </pre> - * - * @return <code>true</code> if everything is ok; <code>false</code> otherwise - */ - boolean validate(); - - /** - * Asks current control to refresh, i.e. show values stored at the underlying model. - */ - void refresh(); - - @NotNull - JComponent getComponent(); -} diff --git a/plugins/gradle/src/org/jetbrains/plugins/gradle/service/project/GradleProjectResolver.java b/plugins/gradle/src/org/jetbrains/plugins/gradle/service/project/GradleProjectResolver.java index 209cefc332f1..25d2dcd8e2b8 100644 --- a/plugins/gradle/src/org/jetbrains/plugins/gradle/service/project/GradleProjectResolver.java +++ b/plugins/gradle/src/org/jetbrains/plugins/gradle/service/project/GradleProjectResolver.java @@ -1,12 +1,14 @@ package org.jetbrains.plugins.gradle.service.project; +import com.intellij.externalSystem.JavaProjectData; import com.intellij.openapi.externalSystem.model.DataNode; import com.intellij.openapi.externalSystem.model.ExternalSystemException; import com.intellij.openapi.externalSystem.model.ProjectKeys; import com.intellij.openapi.externalSystem.model.project.*; import com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskId; import com.intellij.openapi.externalSystem.service.project.ExternalSystemProjectResolver; -import com.intellij.openapi.externalSystem.util.ExternalSystemUtil; +import com.intellij.openapi.externalSystem.util.ExternalSystemApiUtil; +import com.intellij.openapi.module.StdModuleTypes; import com.intellij.openapi.roots.DependencyScope; import com.intellij.openapi.util.Pair; import com.intellij.openapi.util.io.FileUtil; @@ -98,14 +100,14 @@ public class GradleProjectResolver implements ExternalSystemProjectResolver<Grad // populating dependent module object. Map<String, Pair<DataNode<ModuleData>, IdeaModule>> modules = createModules(project, result); populateModules(modules.values(), result); - Collection<DataNode<LibraryData>> libraries = ExternalSystemUtil.getChildren(result, ProjectKeys.LIBRARY); + Collection<DataNode<LibraryData>> libraries = ExternalSystemApiUtil.getChildren(result, ProjectKeys.LIBRARY); myLibraryNamesMixer.mixNames(libraries); return result; } @NotNull private static DataNode<ProjectData> populateProject(@NotNull IdeaProject project, @NotNull String projectPath) { - String projectDirPath = ExternalSystemUtil.toCanonicalPath(PathUtil.getParentPath(projectPath)); + String projectDirPath = ExternalSystemApiUtil.toCanonicalPath(PathUtil.getParentPath(projectPath)); ProjectData projectData = new ProjectData(GradleConstants.SYSTEM_ID, projectDirPath); projectData.setName(project.getName()); @@ -116,7 +118,7 @@ public class GradleProjectResolver implements ExternalSystemProjectResolver<Grad javaProjectData.setLanguageLevel(project.getLanguageLevel().getLevel()); DataNode<ProjectData> result = new DataNode<ProjectData>(ProjectKeys.PROJECT, projectData, null); - result.createChild(ProjectKeys.JAVA_PROJECT, javaProjectData); + result.createChild(JavaProjectData.KEY, javaProjectData); return result; } @@ -140,7 +142,9 @@ public class GradleProjectResolver implements ExternalSystemProjectResolver<Grad throw new IllegalStateException("Module with undefined name detected: " + gradleModule); } ProjectData projectData = ideProject.getData(); - ModuleData ideModule = new ModuleData(GradleConstants.SYSTEM_ID, moduleName, projectData.getProjectFileDirectoryPath()); + ModuleData ideModule = new ModuleData( + GradleConstants.SYSTEM_ID, StdModuleTypes.JAVA.getId(), moduleName, projectData.getProjectFileDirectoryPath() + ); Pair<DataNode<ModuleData>, IdeaModule> previouslyParsedModule = result.get(moduleName); if (previouslyParsedModule != null) { throw new IllegalStateException( @@ -305,7 +309,7 @@ public class GradleProjectResolver implements ExternalSystemProjectResolver<Grad } Set<String> registeredModuleNames = ContainerUtilRt.newHashSet(); - Collection<DataNode<ModuleData>> modulesDataNode = ExternalSystemUtil.getChildren(ideProject, ProjectKeys.MODULE); + Collection<DataNode<ModuleData>> modulesDataNode = ExternalSystemApiUtil.getChildren(ideProject, ProjectKeys.MODULE); for (DataNode<ModuleData> moduleDataNode : modulesDataNode) { String name = moduleDataNode.getData().getName(); registeredModuleNames.add(name); @@ -347,7 +351,7 @@ public class GradleProjectResolver implements ExternalSystemProjectResolver<Grad } DataNode<LibraryData> libraryData = - ExternalSystemUtil.find(ideProject, ProjectKeys.LIBRARY, new BooleanFunction<DataNode<LibraryData>>() { + ExternalSystemApiUtil.find(ideProject, ProjectKeys.LIBRARY, new BooleanFunction<DataNode<LibraryData>>() { @Override public boolean fun(DataNode<LibraryData> node) { return library.equals(node.getData()); diff --git a/plugins/gradle/src/org/jetbrains/plugins/gradle/service/settings/GradleProjectImportBuilder.java b/plugins/gradle/src/org/jetbrains/plugins/gradle/service/settings/GradleProjectImportBuilder.java index 075058f2afa4..c5faad8efcb6 100644 --- a/plugins/gradle/src/org/jetbrains/plugins/gradle/service/settings/GradleProjectImportBuilder.java +++ b/plugins/gradle/src/org/jetbrains/plugins/gradle/service/settings/GradleProjectImportBuilder.java @@ -15,29 +15,29 @@ */ package org.jetbrains.plugins.gradle.service.settings; +import com.intellij.externalSystem.JavaProjectData; import com.intellij.ide.util.projectWizard.WizardContext; import com.intellij.openapi.externalSystem.model.DataNode; -import com.intellij.openapi.externalSystem.model.ProjectKeys; -import com.intellij.openapi.externalSystem.model.project.JavaProjectData; import com.intellij.openapi.externalSystem.model.project.ProjectData; -import com.intellij.openapi.externalSystem.service.project.manage.*; +import com.intellij.openapi.externalSystem.service.project.manage.ProjectDataManager; import com.intellij.openapi.externalSystem.service.project.wizard.AbstractExternalProjectImportBuilder; import com.intellij.openapi.externalSystem.settings.ExternalSystemSettingsManager; -import com.intellij.openapi.externalSystem.util.ExternalSystemUtil; +import com.intellij.openapi.externalSystem.util.ExternalSystemApiUtil; import com.intellij.openapi.project.Project; import com.intellij.openapi.project.ProjectManager; -import com.intellij.openapi.projectRoots.JavaSdkVersion; -import com.intellij.openapi.projectRoots.Sdk; +import com.intellij.openapi.projectRoots.*; import com.intellij.openapi.roots.LanguageLevelProjectExtension; import com.intellij.pom.java.LanguageLevel; import icons.GradleIcons; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; import org.jetbrains.plugins.gradle.settings.GradleSettings; import org.jetbrains.plugins.gradle.util.GradleBundle; import org.jetbrains.plugins.gradle.util.GradleConstants; import javax.swing.*; import java.io.File; +import java.util.List; /** * @author Denis Zhdanov @@ -71,7 +71,7 @@ public class GradleProjectImportBuilder extends AbstractExternalProjectImportBui @Override protected void beforeCommit(@NotNull DataNode<ProjectData> dataNode, @NotNull Project project) { - DataNode<JavaProjectData> javaProjectNode = ExternalSystemUtil.find(dataNode, ProjectKeys.JAVA_PROJECT); + DataNode<JavaProjectData> javaProjectNode = ExternalSystemApiUtil.find(dataNode, JavaProjectData.KEY); if (javaProjectNode == null) { return; } @@ -90,18 +90,36 @@ public class GradleProjectImportBuilder extends AbstractExternalProjectImportBui return; } - DataNode<JavaProjectData> javaProjectNode = ExternalSystemUtil.find(node, ProjectKeys.JAVA_PROJECT); + DataNode<JavaProjectData> javaProjectNode = ExternalSystemApiUtil.find(node, JavaProjectData.KEY); if (javaProjectNode != null) { JavaProjectData data = javaProjectNode.getData(); context.setCompilerOutputDirectory(data.getCompileOutputPath()); JavaSdkVersion version = data.getJdkVersion(); - Sdk jdk = ExternalSystemUtil.findJdk(version); + Sdk jdk = findJdk(version); if (jdk != null) { context.setProjectJdk(jdk); } } } + @Nullable + private static Sdk findJdk(@NotNull JavaSdkVersion version) { + JavaSdk javaSdk = JavaSdk.getInstance(); + List<Sdk> javaSdks = ProjectJdkTable.getInstance().getSdksOfType(javaSdk); + Sdk candidate = null; + for (Sdk sdk : javaSdks) { + JavaSdkVersion v = javaSdk.getVersion(sdk); + if (v == version) { + return sdk; + } + else if (candidate == null && v != null && version.getMaxLanguageLevel().isAtLeast(version.getMaxLanguageLevel())) { + candidate = sdk; + } + } + return candidate; + } + + @Override protected void onProjectInit(@NotNull Project project) { GradleSettings settings = (GradleSettings)getSettingsManager().getSettings(project, GradleConstants.SYSTEM_ID); @@ -123,4 +141,9 @@ public class GradleProjectImportBuilder extends AbstractExternalProjectImportBui } return file; } + + @Override + public boolean isSuitableSdkType(SdkTypeId sdk) { + return sdk == JavaSdk.getInstance(); + } } diff --git a/plugins/gradle/src/org/jetbrains/plugins/gradle/settings/GradleExecutionSettings.java b/plugins/gradle/src/org/jetbrains/plugins/gradle/settings/GradleExecutionSettings.java index 0e73d6caaddb..24f5af420fb7 100644 --- a/plugins/gradle/src/org/jetbrains/plugins/gradle/settings/GradleExecutionSettings.java +++ b/plugins/gradle/src/org/jetbrains/plugins/gradle/settings/GradleExecutionSettings.java @@ -15,7 +15,7 @@ */ package org.jetbrains.plugins.gradle.settings; -import com.intellij.openapi.externalSystem.service.remote.ExternalSystemExecutionSettings; +import com.intellij.openapi.externalSystem.model.settings.ExternalSystemExecutionSettings; import com.intellij.util.containers.ContainerUtilRt; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; diff --git a/plugins/gradle/src/org/jetbrains/plugins/gradle/sync/GradleDuplicateLibrariesPreProcessor.java b/plugins/gradle/src/org/jetbrains/plugins/gradle/sync/GradleDuplicateLibrariesPreProcessor.java deleted file mode 100644 index 8368c092c494..000000000000 --- a/plugins/gradle/src/org/jetbrains/plugins/gradle/sync/GradleDuplicateLibrariesPreProcessor.java +++ /dev/null @@ -1,87 +0,0 @@ -/* - * Copyright 2000-2013 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.jetbrains.plugins.gradle.sync; - -import com.intellij.openapi.externalSystem.model.project.*; -import com.intellij.openapi.externalSystem.service.project.change.ExternalProjectStructureChangesPreProcessor; -import com.intellij.openapi.externalSystem.service.project.manage.LibraryDataService; -import com.intellij.openapi.externalSystem.service.project.manage.LibraryDependencyDataService; -import com.intellij.openapi.project.Project; -import org.jetbrains.annotations.NotNull; - -/** - * There is a possible situation that there are module-local libraries which reference jars similar to those provided by gradle - * as project libraries (IDEA-100968). This class manages that by auto-removing module-local libraries and replacing it by - * references to project-level libraries instead. - * - * @author Denis Zhdanov - * @since 2/13/13 9:15 AM - */ -public class GradleDuplicateLibrariesPreProcessor implements ExternalProjectStructureChangesPreProcessor { - - @NotNull private final LibraryDependencyDataService myDependencyManager; - @NotNull private final LibraryDataService myLibraryManager; - - public GradleDuplicateLibrariesPreProcessor(@NotNull LibraryDependencyDataService manager, @NotNull LibraryDataService manager1) { - myDependencyManager = manager; - myLibraryManager = manager1; - } - - @NotNull - @Override - public ProjectData preProcess(@NotNull ProjectData externalProject, @NotNull final Project ideProject) { - // TODO den implement -// final ProjectStructureHelper projectStructureHelper = ServiceManager.getService(ideProject, ProjectStructureHelper.class); -// for (ModuleData gradleModule : externalProject.getModules()) { -// final Module ideModule = projectStructureHelper.findIdeModule(gradleModule); -// if (ideModule == null) { -// continue; -// } -// ExternalEntityVisitor visitor = new ExternalEntityVisitorAdapter() { -// @Override -// public void visit(@NotNull LibraryDependencyData gradleDependency) { -// LibraryDependencyId id = EntityIdMapper.mapEntityToId(gradleDependency); -// LibraryOrderEntry ideDependency = projectStructureHelper.findIdeModuleLocalLibraryDependency( -// id.getOwnerModuleName(), id.getDependencyName() -// ); -// if (ideDependency == null) { -// return; -// } -// myDependencyManager.removeDependency(ideDependency, true); -// -// ideDependency = projectStructureHelper.findIdeLibraryDependency(id); -// if (ideDependency == null) { -// myDependencyManager.importDependency(gradleDependency, ideModule, true); -// } -// -// LibraryData gradleLibrary = gradleDependency.getTarget(); -// Library ideLibrary = projectStructureHelper.findIdeLibrary(gradleLibrary); -// if (ideLibrary == null) { -// myLibraryManager.importLibrary(gradleLibrary, ideProject, true); -// } -// else { -// myLibraryManager.syncPaths(gradleLibrary, ideLibrary, ideProject, true); -// } -// } -// }; -// for (DependencyData dependency : gradleModule.getDependencies()) { -// dependency.invite(visitor); -// } -// } - - return externalProject; - } -} diff --git a/plugins/gradle/src/org/jetbrains/plugins/gradle/sync/GradleProjectStructureChangesPanel.java b/plugins/gradle/src/org/jetbrains/plugins/gradle/sync/GradleProjectStructureChangesPanel.java deleted file mode 100644 index b209bfa826b6..000000000000 --- a/plugins/gradle/src/org/jetbrains/plugins/gradle/sync/GradleProjectStructureChangesPanel.java +++ /dev/null @@ -1,319 +0,0 @@ -package org.jetbrains.plugins.gradle.sync; - -import com.intellij.ide.ui.customization.CustomizationUtil; -import com.intellij.openapi.actionSystem.PlatformDataKeys; -import com.intellij.openapi.components.ServiceManager; -import com.intellij.openapi.externalSystem.model.ExternalSystemDataKeys; -import com.intellij.openapi.externalSystem.service.project.ProjectStructureServices; -import com.intellij.openapi.externalSystem.ui.ExternalProjectStructureTreeModel; -import com.intellij.openapi.project.Project; -import com.intellij.ui.TreeSpeedSearch; -import com.intellij.ui.treeStructure.Tree; -import com.intellij.util.Alarm; -import com.intellij.util.Consumer; -import com.intellij.util.containers.ContainerUtilRt; -import com.intellij.util.messages.MessageBusConnection; -import com.intellij.util.ui.UIUtil; -import com.intellij.util.ui.tree.TreeModelAdapter; -import com.intellij.util.ui.tree.TreeUtil; -import org.jetbrains.annotations.NonNls; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; -import org.jetbrains.plugins.gradle.settings.GradleSettingsListener; -import org.jetbrains.plugins.gradle.settings.GradleLocalSettings; -import org.jetbrains.plugins.gradle.config.GradleToolWindowPanel; -import org.jetbrains.plugins.gradle.notification.GradleConfigNotificationManager; -import com.intellij.openapi.externalSystem.ui.ProjectStructureNode; -import org.jetbrains.plugins.gradle.util.GradleConstants; -import org.jetbrains.plugins.gradle.util.GradleUtil; - -import javax.swing.*; -import javax.swing.event.TreeExpansionEvent; -import javax.swing.event.TreeModelEvent; -import javax.swing.event.TreeWillExpandListener; -import javax.swing.tree.ExpandVetoException; -import javax.swing.tree.TreePath; -import java.awt.*; -import java.awt.event.MouseEvent; -import java.awt.event.MouseMotionAdapter; -import java.util.*; -import java.util.List; - -/** - * UI control for showing difference between the gradle and intellij project structure. - * - * @author Denis Zhdanov - * @since 11/3/11 3:58 PM - */ -public class GradleProjectStructureChangesPanel extends GradleToolWindowPanel { - - private static final int COLLAPSE_STATE_PROCESSING_DELAY_MILLIS = 200; - - private static final Comparator<TreePath> PATH_COMPARATOR = new Comparator<TreePath>() { - @Override - public int compare(TreePath o1, TreePath o2) { - return o2.getPathCount() - o1.getPathCount(); - } - }; - - private final Alarm myCollapseStateAlarm = new Alarm(Alarm.ThreadToUse.SWING_THREAD); - private final List<JComponent> myToolbarControls = new ArrayList<JComponent>(); - - /** Holds list of paths which 'expand/collapse' state should be restored. */ - private final Set<TreePath> myPathsToProcessCollapseState = ContainerUtilRt.newHashSet(); - - private final GradleLocalSettings mySettings; - - private Tree myTree; - private ExternalProjectStructureTreeModel myTreeModel; - private ProjectStructureServices myContext; - private Object myNodeUnderMouse; - private boolean mySuppressCollapseTracking; - - public GradleProjectStructureChangesPanel(@NotNull Project project, - @NotNull ProjectStructureServices context) - { - super(project, GradleConstants.TOOL_WINDOW_TOOLBAR_PLACE); - myContext = context; - myToolbarControls.add(new GradleProjectStructureFiltersPanel()); - mySettings = GradleLocalSettings.getInstance(project); - initContent(); - - MessageBusConnection connection = project.getMessageBus().connect(project); - // TODO den implement -// connection.subscribe(GradleSettingsListener.TOPIC, new GradleSettingsListener() { -// -// private boolean myRefresh; -// private boolean myInBulk; -// -// @Override -// public void onBulkChangeStart() { -// myInBulk = true; -// } -// -// @Override -// public void onBulkChangeEnd() { -// myInBulk = false; -// if (myRefresh) { -// myRefresh = false; -// refreshAll(); -// } -// } -// -// @Override -// public void onLinkedProjectPathChange(@Nullable String oldPath, @Nullable String newPath) { refreshAll(); } -// -// @Override -// public void onPreferLocalGradleDistributionToWrapperChange(boolean currentValue) { refreshAll(); } -// -// @Override -// public void onGradleHomeChange(@Nullable String oldPath, @Nullable String newPath) { refreshAll(); } -// -// @Override -// public void onServiceDirectoryPathChange(@Nullable String oldPath, @Nullable String newPath) { refreshAll(); } -// -// @Override -// public void onUseAutoImportChange(boolean oldValue, boolean newValue) { -// if (newValue) { -// update(); -// } -// } -// -// private void refreshAll() { -// if (myInBulk) { -// myRefresh = true; -// return; -// } -// GradleUtil.refreshProject(getProject(), new Consumer<String>() { -// @Override -// public void consume(String s) { -// GradleConfigNotificationManager notificationManager -// = ServiceManager.getService(getProject(), GradleConfigNotificationManager.class); -// notificationManager.processRefreshError(s); -// UIUtil.invokeLaterIfNeeded(new Runnable() { -// @Override -// public void run() { -// update(); -// } -// }); -// } -// }); -// update(); -// } -// }); - } - - @NotNull - public ExternalProjectStructureTreeModel getTreeModel() { - return myTreeModel; - } - - @NotNull - @Override - protected JComponent buildContent() { - JPanel result = new JPanel(new GridBagLayout()); - // TODO den implement - myTreeModel = null; -// myTreeModel = new ExternalProjectStructureTreeModel(getProject(), myContext, false); - myTree = new Tree(myTreeModel); - myTree.addTreeWillExpandListener(new TreeWillExpandListener() { - @Override - public void treeWillExpand(TreeExpansionEvent event) throws ExpandVetoException { - if (!mySuppressCollapseTracking) { - mySettings.getWorkingExpandStates().put(getPath(event.getPath()), true); - } - } - - @Override - public void treeWillCollapse(TreeExpansionEvent event) throws ExpandVetoException { - if (!mySuppressCollapseTracking) { - mySettings.getWorkingExpandStates().put(getPath(event.getPath()), false); - } - } - }); - myTreeModel.addTreeModelListener(new TreeModelAdapter() { - @Override - public void treeStructureChanged(TreeModelEvent e) { - scheduleCollapseStateAppliance(e.getTreePath()); - } - - @Override - public void treeNodesInserted(TreeModelEvent e) { - scheduleCollapseStateAppliance(e.getTreePath()); - } - }); - new TreeSpeedSearch(myTree, TreeSpeedSearch.NODE_DESCRIPTOR_TOSTRING, true); - TreeUtil.installActions(myTree); - - GridBagConstraints constraints = new GridBagConstraints(); - constraints.gridwidth = GridBagConstraints.REMAINDER; - constraints.anchor = GridBagConstraints.WEST; - constraints.fill = GridBagConstraints.BOTH; - constraints.weightx = constraints.weighty = 1; - result.add(myTree, constraints); - result.setBackground(myTree.getBackground()); - - CustomizationUtil.installPopupHandler(myTree, GradleConstants.ACTION_GROUP_SYNC_TREE, GradleConstants.SYNC_TREE_CONTEXT_MENU_PLACE); - myTree.addMouseMotionListener(new MouseMotionAdapter() { - @Override - public void mouseMoved(MouseEvent e) { - final TreePath path = myTree.getPathForLocation(e.getX(), e.getY()); - if (path == null) { - return; - } - myNodeUnderMouse = path.getLastPathComponent(); - } - }); - return result; - } - - @NotNull - @Override - protected List<JComponent> getToolbarControls() { - return myToolbarControls; - } - - @Override - protected void updateContent() { - myTreeModel.rebuild(); - } - - @Nullable - @Override - public Object getData(@NonNls String dataId) { - if (ExternalSystemDataKeys.PROJECT_TREE.is(dataId)) { - return myTree; - } - else if (ExternalSystemDataKeys.PROJECT_TREE_MODEL.is(dataId)) { - return myTreeModel; - } - else if (ExternalSystemDataKeys.PROJECT_TREE_SELECTED_NODE.is(dataId)) { - TreePath[] paths = myTree.getSelectionPaths(); - if (paths == null) { - return null; - } - List<ProjectStructureNode<?>> result = new ArrayList<ProjectStructureNode<?>>(); - for (TreePath path : paths) { - result.add((ProjectStructureNode<?>)path.getLastPathComponent()); - } - return result; - } - else if (ExternalSystemDataKeys.SYNC_TREE_NODE_UNDER_MOUSE.is(dataId)) { - return myNodeUnderMouse; - } - else if (PlatformDataKeys.HELP_ID.is(dataId)) { - return GradleConstants.HELP_TOPIC_TOOL_WINDOW; - } - else { - return super.getData(dataId); - } - } - - /** - * Schedules 'collapse/expand' state restoring for the given path. We can't do that immediately from the tree model listener - * as there is a possible case that other listeners have not been notified about the model state change, hence, attempt to define - * 'collapse/expand' state may bring us to the inconsistent state. - * - * @param path target path - */ - private void scheduleCollapseStateAppliance(@NotNull TreePath path) { - myPathsToProcessCollapseState.add(path); - myCollapseStateAlarm.cancelAllRequests(); - myCollapseStateAlarm.addRequest(new Runnable() { - @Override - public void run() { - // We assume that the paths collection is modified only from the EDT, so, ConcurrentModificationException doesn't have - // a chance. - // Another thing is that we sort the paths in order to process the longest first. That is related to the JTree specifics - // that it automatically expands parent paths on child path expansion. - List<TreePath> paths = new ArrayList<TreePath>(myPathsToProcessCollapseState); - myPathsToProcessCollapseState.clear(); - Collections.sort(paths, PATH_COMPARATOR); - for (TreePath treePath : paths) { - applyCollapseState(treePath); - } - final TreePath rootPath = new TreePath(myTreeModel.getRoot()); - if (myTree.isCollapsed(rootPath)) { - myTree.expandPath(rootPath); - } - } - }, COLLAPSE_STATE_PROCESSING_DELAY_MILLIS); - } - - /** - * Applies stored 'collapse/expand' state to the node located at the given path. - * - * @param path target path - */ - private void applyCollapseState(@NotNull TreePath path) { - final String key = getPath(path); - final Boolean expanded = mySettings.getWorkingExpandStates().get(key); - if (expanded == null) { - return; - } - boolean s = mySuppressCollapseTracking; - mySuppressCollapseTracking = true; - try { - if (expanded) { - myTree.expandPath(path); - } - else { - myTree.collapsePath(path); - } - } - finally { - mySuppressCollapseTracking = s; - } - } - - @NotNull - private static String getPath(@NotNull TreePath path) { - StringBuilder buffer = new StringBuilder(); - for (TreePath current = path; current != null; current = current.getParentPath()) { - // TODO den implement -// buffer.append(current.getLastPathComponent().toString()).append(GradleUtil.PATH_SEPARATOR); - } - buffer.setLength(buffer.length() - 1); - return buffer.toString(); - } -} diff --git a/plugins/gradle/src/org/jetbrains/plugins/gradle/sync/GradleProjectStructureFiltersPanel.java b/plugins/gradle/src/org/jetbrains/plugins/gradle/sync/GradleProjectStructureFiltersPanel.java deleted file mode 100644 index 46b61c7f1bb0..000000000000 --- a/plugins/gradle/src/org/jetbrains/plugins/gradle/sync/GradleProjectStructureFiltersPanel.java +++ /dev/null @@ -1,27 +0,0 @@ -package org.jetbrains.plugins.gradle.sync; - -import com.intellij.openapi.actionSystem.ActionGroup; -import com.intellij.openapi.actionSystem.ActionManager; -import com.intellij.openapi.actionSystem.ActionToolbar; -import com.intellij.openapi.externalSystem.util.ExternalSystemBundle; -import org.jetbrains.plugins.gradle.util.GradleConstants; - -import javax.swing.*; - -/** - * @author Denis Zhdanov - * @since 3/6/12 3:44 PM - */ -public class GradleProjectStructureFiltersPanel extends JPanel { - - - public GradleProjectStructureFiltersPanel() { - setLayout(new BoxLayout(this, BoxLayout.X_AXIS)); - add(Box.createHorizontalStrut(7)); - add(new JLabel(ExternalSystemBundle.message("gradle.import.structure.settings.label.filters"))); - final ActionManager actionManager = ActionManager.getInstance(); - final ActionGroup group = (ActionGroup)actionManager.getAction("Gradle.SyncTreeFilter"); - final ActionToolbar toolbar = actionManager.createActionToolbar(GradleConstants.SYNC_TREE_FILTER_PLACE, group, true); - add(toolbar.getComponent()); - } -} diff --git a/plugins/gradle/src/org/jetbrains/plugins/gradle/sync/conflict/GradleCommonDependencyConflictControlFactory.java b/plugins/gradle/src/org/jetbrains/plugins/gradle/sync/conflict/GradleCommonDependencyConflictControlFactory.java deleted file mode 100644 index 20b671c450f1..000000000000 --- a/plugins/gradle/src/org/jetbrains/plugins/gradle/sync/conflict/GradleCommonDependencyConflictControlFactory.java +++ /dev/null @@ -1,80 +0,0 @@ -package org.jetbrains.plugins.gradle.sync.conflict; - -import com.intellij.openapi.externalSystem.model.project.change.*; -import com.intellij.openapi.externalSystem.model.project.id.EntityIdMapper; -import com.intellij.openapi.externalSystem.model.project.id.ProjectEntityId; -import com.intellij.openapi.externalSystem.util.ExternalSystemBundle; -import com.intellij.openapi.roots.ExportableOrderEntry; -import com.intellij.openapi.util.Ref; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; -import com.intellij.openapi.externalSystem.model.project.change.DependencyExportedChange; -import org.jetbrains.plugins.gradle.ui.MatrixControlBuilder; -import org.jetbrains.plugins.gradle.util.GradleUtil; - -import javax.swing.*; -import java.util.Collection; - -/** - * Encapsulates functionality of building UI that represents common dependency settings conflicts (scope, 'exported'). - * <p/> - * Thread-safe. - * - * @author Denis Zhdanov - * @since 3/14/12 2:20 PM - */ -public class GradleCommonDependencyConflictControlFactory { - - /** - * Allows to build UI for showing common dependency settings conflicts (scope, 'exported'). - * - * @param dependency target dependency which conflict changes should be shown - * @param changes target changes to use represent - * @return UI control for showing common dependency settings conflicts if they are present at the given settings; - * <code>null</code> otherwise - */ - @SuppressWarnings("MethodMayBeStatic") - @Nullable - public JComponent getControl(@NotNull ExportableOrderEntry dependency, @NotNull Collection<ExternalProjectStructureChange> changes) { - final ProjectEntityId id = EntityIdMapper.mapEntityToId(dependency); - final Ref<DependencyScopeChange> scopeChangeRef = new Ref<DependencyScopeChange>(); - final Ref<DependencyExportedChange> exportedChangeRef = new Ref<DependencyExportedChange>(); - ExternalProjectStructureChangeVisitor visitor = new ExternalProjectStructureChangeVisitorAdapter() { - @Override - public void visit(@NotNull DependencyScopeChange change) { - if (id.equals(change.getEntityId())) { - scopeChangeRef.set(change); - } - } - - @Override - public void visit(@NotNull DependencyExportedChange change) { - if (id.equals(change.getEntityId())) { - exportedChangeRef.set(change); - } - } - }; - for (ExternalProjectStructureChange change : changes) { - if (scopeChangeRef.get() != null && exportedChangeRef.get() != null) { - break; - } - change.invite(visitor); - } - - final DependencyScopeChange scopeChange = scopeChangeRef.get(); - final DependencyExportedChange exportedChange = exportedChangeRef.get(); - if (scopeChange == null && exportedChange == null) { - return null; - } - MatrixControlBuilder builder = GradleUtil.getConflictChangeBuilder(); - if (scopeChange != null) { - builder.addRow(ExternalSystemBundle.message("gradle.sync.change.dependency.scope.text"), - scopeChange.getExternalValue(), scopeChange.getIdeValue()); - } - if (exportedChange != null) { - builder.addRow(ExternalSystemBundle.message("gradle.sync.change.dependency.exported.text"), - exportedChange.getExternalValue(), exportedChange.getIdeValue()); - } - return builder.build(); - } -} diff --git a/plugins/gradle/src/org/jetbrains/plugins/gradle/sync/conflict/GradleConflictControlFactory.java b/plugins/gradle/src/org/jetbrains/plugins/gradle/sync/conflict/GradleConflictControlFactory.java deleted file mode 100644 index 2fd5d64d2fd1..000000000000 --- a/plugins/gradle/src/org/jetbrains/plugins/gradle/sync/conflict/GradleConflictControlFactory.java +++ /dev/null @@ -1,85 +0,0 @@ -package org.jetbrains.plugins.gradle.sync.conflict; - -import com.intellij.openapi.externalSystem.model.project.change.ExternalProjectStructureChange; -import com.intellij.openapi.module.Module; -import com.intellij.openapi.project.Project; -import com.intellij.openapi.roots.LibraryOrderEntry; -import com.intellij.openapi.roots.ModuleOrderEntry; -import com.intellij.openapi.roots.libraries.Library; -import com.intellij.openapi.util.Ref; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; -import com.intellij.openapi.externalSystem.util.IdeEntityVisitor; -import com.intellij.openapi.externalSystem.service.project.ModuleAwareContentRoot; -import org.jetbrains.plugins.gradle.util.GradleUtil; - -import javax.swing.*; -import java.util.Collection; - -/** - * We want to be able to show changes for the conflicting gradle and intellij project structure entities. - * <p/> - * For example, there is a possible case that particular library has a different classpath configuration at the gradle and the intellij. - * We want to be able to show them to the user. - * <p/> - * This class allows to retrieve UI controls for such a conflicting changes. - * <p/> - * Thread-safe. - * - * @author Denis Zhdanov - * @since 3/2/12 3:03 PM - */ -public class GradleConflictControlFactory { - - @NotNull private final GradleProjectConflictControlFactory myProjectFactory; - @NotNull private final GradleCommonDependencyConflictControlFactory myCommonDependencyFactory; - - public GradleConflictControlFactory(@NotNull GradleProjectConflictControlFactory factory, - @NotNull GradleCommonDependencyConflictControlFactory commonDependencyFactory) { - myProjectFactory = factory; - myCommonDependencyFactory = commonDependencyFactory; - } - - /** - * Tries to build UI control for showing the differences between the gradle and intellij setup of the given project structure entity. - * - * @param entity target entity - * @param changes known changes for the given entity - * @return UI control for showing the differences between the gradle and intellij setup of the given project structure entity; - * <code>null</code> if there are no differences or if we don't know how to show them - */ - @Nullable - public JComponent getDiffControl(@NotNull Object entity, final @NotNull Collection<ExternalProjectStructureChange> changes) { - final Ref<JComponent> result = new Ref<JComponent>(); - // TODO den implement -// GradleUtil.dispatch(entity, new IdeEntityVisitor() { -// @Override -// public void visit(@NotNull Project project) { -// result.set(myProjectFactory.getControl(changes)); -// } -// -// @Override -// public void visit(@NotNull Module module) { -// } -// -// @Override -// public void visit(@NotNull ModuleAwareContentRoot contentRoot) { -// } -// -// @Override -// public void visit(@NotNull LibraryOrderEntry libraryDependency) { -// result.set(myCommonDependencyFactory.getControl(libraryDependency, changes)); -// } -// -// @Override -// public void visit(@NotNull ModuleOrderEntry moduleDependency) { -// result.set(myCommonDependencyFactory.getControl(moduleDependency, changes)); -// } -// -// @Override -// public void visit(@NotNull Library library) { -// } -// }); - return result.get(); - } -} diff --git a/plugins/gradle/src/org/jetbrains/plugins/gradle/sync/conflict/GradleProjectConflictControlFactory.java b/plugins/gradle/src/org/jetbrains/plugins/gradle/sync/conflict/GradleProjectConflictControlFactory.java deleted file mode 100644 index ecd6cea238f0..000000000000 --- a/plugins/gradle/src/org/jetbrains/plugins/gradle/sync/conflict/GradleProjectConflictControlFactory.java +++ /dev/null @@ -1,74 +0,0 @@ -package org.jetbrains.plugins.gradle.sync.conflict; - -import com.intellij.openapi.externalSystem.model.project.change.*; -import com.intellij.openapi.externalSystem.util.ExternalSystemBundle; -import com.intellij.openapi.util.Ref; -import com.intellij.pom.java.LanguageLevel; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; -import com.intellij.openapi.externalSystem.model.project.change.LanguageLevelChange; -import org.jetbrains.plugins.gradle.ui.MatrixControlBuilder; -import org.jetbrains.plugins.gradle.util.GradleUtil; - -import javax.swing.*; -import java.util.Collection; - -/** - * Thread-safe. - * - * @author Denis Zhdanov - * @since 3/15/12 4:26 PM - */ -public class GradleProjectConflictControlFactory { - - @SuppressWarnings("MethodMayBeStatic") - @Nullable - public JComponent getControl(Collection<ExternalProjectStructureChange> changes) { - final Ref<GradleProjectRenameChange> renameChangeRef = new Ref<GradleProjectRenameChange>(); - final Ref<LanguageLevelChange> languageLevelChangeRef = new Ref<LanguageLevelChange>(); - - ExternalProjectStructureChangeVisitor visitor = new ExternalProjectStructureChangeVisitorAdapter() { - @Override - public void visit(@NotNull GradleProjectRenameChange change) { - renameChangeRef.set(change); - } - - @Override - public void visit(@NotNull LanguageLevelChange change) { - languageLevelChangeRef.set(change); - } - }; - - for (ExternalProjectStructureChange change : changes) { - if (renameChangeRef.get() != null && languageLevelChangeRef.get() != null) { - break; - } - change.invite(visitor); - } - - final GradleProjectRenameChange renameChange = renameChangeRef.get(); - final LanguageLevelChange languageLevelChange = languageLevelChangeRef.get(); - if (renameChange == null && languageLevelChange == null) { - return null; - } - - MatrixControlBuilder builder = GradleUtil.getConflictChangeBuilder(); - if (renameChange != null) { - builder.addRow(ExternalSystemBundle.message("gradle.import.structure.settings.label.name"), - renameChange.getExternalValue(), renameChange.getIdeValue()); - } - - if (languageLevelChange != null) { - builder.addRow(ExternalSystemBundle.message("gradle.import.structure.settings.label.language.level"), - getTextToShow(languageLevelChange.getExternalValue()), getTextToShow(languageLevelChange.getIdeValue())); - } - - return builder.build(); - } - - @NotNull - private static String getTextToShow(@NotNull LanguageLevel level) { - final String s = level.toString(); - return s.substring(s.indexOf('1')).replace('_', '.'); - } -} diff --git a/plugins/gradle/src/org/jetbrains/plugins/gradle/ui/GradleToolWindowFactory.java b/plugins/gradle/src/org/jetbrains/plugins/gradle/ui/GradleToolWindowFactory.java index ccd65695194d..3a4e833ba001 100644 --- a/plugins/gradle/src/org/jetbrains/plugins/gradle/ui/GradleToolWindowFactory.java +++ b/plugins/gradle/src/org/jetbrains/plugins/gradle/ui/GradleToolWindowFactory.java @@ -15,7 +15,6 @@ import com.intellij.ui.content.ContentManager; import com.intellij.ui.content.ContentManagerAdapter; import com.intellij.ui.content.ContentManagerEvent; import com.intellij.ui.content.impl.ContentImpl; -import org.jetbrains.plugins.gradle.sync.GradleProjectStructureChangesPanel; import org.jetbrains.plugins.gradle.tasks.GradleTasksPanel; import org.jetbrains.plugins.gradle.util.GradleConstants; @@ -25,31 +24,13 @@ public class GradleToolWindowFactory implements ToolWindowFactory, DumbAware { public void createToolWindowContent(final Project project, final ToolWindow toolWindow) { final ProjectStructureServices context = ServiceManager.getService(project, ProjectStructureServices.class); - // Project structure. - final GradleProjectStructureChangesPanel projectStructurePanel = new GradleProjectStructureChangesPanel(project, context); - final String projectStructureTitle = ExternalSystemBundle.message("gradle.sync.title.tab"); - ContentImpl projectStructureContent = new ContentImpl(projectStructurePanel, projectStructureTitle, true); ContentManager contentManager = toolWindow.getContentManager(); - contentManager.addContent(projectStructureContent); - - // Task. - String tasksTitle = ExternalSystemBundle.message("gradle.task.title.tab"); + // TODO den implement + String tasksTitle = "tasks"; +// String tasksTitle = ExternalSystemBundle.message("gradle.task.title.tab"); ContentImpl tasksContent = new ContentImpl( new GradleTasksPanel(project), tasksTitle, true); contentManager.addContent(tasksContent); - project.getMessageBus().connect(project).subscribe(ProjectTopics.PROJECT_ROOTS, new ModuleRootAdapter() { - @Override - public void rootsChanged(ModuleRootEvent event) { - // The general idea is to change dependencies order at the UI if they are changed at the module settings. - projectStructurePanel.getTreeModel().onModuleRootsChange(); - } - }); - - // Restore previously selected tab. - String toSelect = PropertiesComponent.getInstance(project).getValue(GradleConstants.ACTIVE_TOOL_WINDOW_TAB_KEY, projectStructureTitle); - if (tasksTitle.equals(toSelect)) { - contentManager.setSelectedContent(tasksContent); - } contentManager.addContentManagerListener(new ContentManagerAdapter() { @Override diff --git a/plugins/gradle/src/org/jetbrains/plugins/gradle/util/GradleConstants.java b/plugins/gradle/src/org/jetbrains/plugins/gradle/util/GradleConstants.java index 010eab7af761..41affcfe96d1 100644 --- a/plugins/gradle/src/org/jetbrains/plugins/gradle/util/GradleConstants.java +++ b/plugins/gradle/src/org/jetbrains/plugins/gradle/util/GradleConstants.java @@ -1,10 +1,7 @@ package org.jetbrains.plugins.gradle.util; import com.intellij.openapi.externalSystem.model.ProjectSystemId; -import com.intellij.openapi.externalSystem.ui.ProjectStructureNodeDescriptor; -import com.intellij.openapi.externalSystem.util.ExternalSystemBundle; import org.jetbrains.annotations.NonNls; -import com.intellij.openapi.externalSystem.model.project.id.GradleSyntheticId; import org.jetbrains.annotations.NotNull; /** diff --git a/plugins/gradle/src/org/jetbrains/plugins/gradle/util/GradleUtil.java b/plugins/gradle/src/org/jetbrains/plugins/gradle/util/GradleUtil.java index 9f9133365aea..c6f048df2b31 100644 --- a/plugins/gradle/src/org/jetbrains/plugins/gradle/util/GradleUtil.java +++ b/plugins/gradle/src/org/jetbrains/plugins/gradle/util/GradleUtil.java @@ -1,29 +1,19 @@ package org.jetbrains.plugins.gradle.util; import com.intellij.ide.actions.OpenProjectFileChooserDescriptor; -import com.intellij.openapi.actionSystem.DataContext; import com.intellij.openapi.components.ServiceManager; -import com.intellij.openapi.externalSystem.model.project.id.GradleSyntheticId; -import com.intellij.openapi.externalSystem.model.project.id.ProjectEntityId; -import com.intellij.openapi.externalSystem.ui.ExternalProjectStructureTreeModel; -import com.intellij.openapi.externalSystem.ui.ProjectStructureNode; -import com.intellij.openapi.externalSystem.ui.ProjectStructureNodeDescriptor; import com.intellij.openapi.fileChooser.FileChooserDescriptor; import com.intellij.openapi.fileChooser.FileTypeDescriptor; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.NotNullLazyValue; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VirtualFile; -import com.intellij.ui.treeStructure.Tree; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.plugins.gradle.service.GradleInstallationManager; import org.jetbrains.plugins.gradle.settings.GradleSettings; import org.jetbrains.plugins.gradle.ui.MatrixControlBuilder; -import javax.swing.*; -import javax.swing.tree.TreePath; -import java.awt.*; import java.io.*; import java.util.Arrays; import java.util.Properties; @@ -156,55 +146,6 @@ public class GradleUtil { return null; } - @NotNull - public static <T extends ProjectEntityId> ProjectStructureNodeDescriptor<T> buildDescriptor(@NotNull T id, @NotNull String name) { - return new ProjectStructureNodeDescriptor<T>(id, name, id.getType().getIcon()); - } - - @NotNull - public static ProjectStructureNodeDescriptor<GradleSyntheticId> buildSyntheticDescriptor(@NotNull String text) { - return buildSyntheticDescriptor(text, null); - } - - public static ProjectStructureNodeDescriptor<GradleSyntheticId> buildSyntheticDescriptor(@NotNull String text, @Nullable Icon icon) { - return new ProjectStructureNodeDescriptor<GradleSyntheticId>(new GradleSyntheticId(text), text, icon); - } - - /** - * Tries to calculate the position to use for showing hint for the given node of the given tree. - * - * @param node target node for which a hint should be shown - * @param tree target tree that contains given node - * @return preferred hint position (in coordinates relative to the given tree) if it's possible to calculate the one; - * <code>null</code> otherwise - */ - @Nullable - public static Point getHintPosition(@NotNull ProjectStructureNode<?> node, @NotNull Tree tree) { - final Rectangle bounds = tree.getPathBounds(new TreePath(node.getPath())); - if (bounds == null) { - return null; - } - final Icon icon = ((ProjectStructureNode)node).getDescriptor().getIcon(); - int xAdjustment = 0; - if (icon != null) { - xAdjustment = icon.getIconWidth(); - } - return new Point(bounds.x + xAdjustment, bounds.y + bounds.height); - } - - /** - * Tries to find the current {@link ExternalProjectStructureTreeModel} instance. - * - * @param context target context (if defined) - * @return current {@link ExternalProjectStructureTreeModel} instance (if any has been found); <code>null</code> otherwise - */ - @Nullable - public static ExternalProjectStructureTreeModel getProjectStructureTreeModel(@Nullable DataContext context) { - // TODO den implement - return null; -// return getToolWindowElement(ExternalProjectStructureTreeModel.class, context, ExternalSystemDataKeys.PROJECT_TREE_MODEL); - } - /** * @return {@link MatrixControlBuilder} with predefined set of columns ('gradle' and 'intellij') */ diff --git a/plugins/gradle/testSources/org/jetbrains/plugins/gradle/sync/GradleOutdatedLibraryVersionTest.groovy b/plugins/gradle/testSources/org/jetbrains/plugins/gradle/sync/GradleOutdatedLibraryVersionTest.groovy deleted file mode 100644 index 55daa27c1757..000000000000 --- a/plugins/gradle/testSources/org/jetbrains/plugins/gradle/sync/GradleOutdatedLibraryVersionTest.groovy +++ /dev/null @@ -1,255 +0,0 @@ -/* - * Copyright 2000-2013 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.jetbrains.plugins.gradle.sync - -import com.intellij.openapi.externalSystem.settings.ExternalSystemTextAttributes -import org.jetbrains.plugins.gradle.testutil.AbstractGradleTest -import org.junit.Test - -/** - * @author Denis Zhdanov - * @since 1/22/13 3:04 PM - */ -class GradleOutdatedLibraryVersionTest extends AbstractGradleTest { - - // TODO den remove - @Test - void "dummy"() { - } - -// @Test -// void "changed library version change construction and representation"() { -// def gradleProject = { -// project { -// module('module1') { -// dependencies { -// library('lib-2', bin: ['jar1-2', 'jar2-2']) } } -// module('module2') { -// dependencies { -// library('lib-2', bin: ['jar1-2', 'jar2-2']) } } } } -// -// init( -// gradle: gradleProject, -// -// intellij: { -// project { -// module('module1') { -// dependencies { -// library('lib-1', bin: ['jar1-1', 'jar2-1']) } } -// module('module2') { -// dependencies { -// library('lib-1', bin: ['jar1-1', 'jar2-1']) } } } -// } -// ) -// -// checkChanges { -// libraryVersion ( -// name: 'lib', -// gradleVersion: '2', -// gradleLibraryId: findLibraryId('lib-2', true), -// ideVersion: '1', -// ideLibraryId: findLibraryId('lib-1', false) -// ) -// } -// -// checkTree { -// project { -// module1 { -// dependencies { -// 'lib (1 -> 2)' ('outdated') } } -// module2 { -// dependencies { -// 'lib (1 -> 2)' ('outdated') } } } } -// -// // Emulate 'sync library' and check how obsolete change is processed. -// setState(intellij: gradleProject) -// checkChanges { } // No changes -// checkTree { -// project { -// module1 { -// dependencies { -// 'lib-2' { -// 'jar1-2'() -// 'jar2-2'() } } } -// module2 { -// dependencies { -// 'lib-2' { -// 'jar1-2'() -// 'jar2-2'() } } } } } -// } -// -// @Test -// void "'outdated' filter processing"() { -// init( -// gradle: { -// project { -// module('module1') { -// dependencies { -// library('lib-2', bin: ['jar1-2', 'jar2-2']) -// library('same-lib') } } -// module('module2') { -// dependencies { -// library('lib-2', bin: ['jar1-2', 'jar2-2']) } } } }, -// -// intellij: { -// project { -// module('module1') { -// dependencies { -// library('lib-1', bin: ['jar1-1', 'jar2-1']) -// library('same-lib')} } -// module('module2') { -// dependencies { -// library('lib-1', bin: ['jar1-1', 'jar2-1']) } } } } -// ) -// -// applyTreeFilter(ExternalSystemTextAttributes.OUTDATED_ENTITY) -// checkTree { -// project { -// module1 { -// dependencies { -// 'lib (1 -> 2)' ('outdated') -// } } -// module2 { -// dependencies { -// 'lib (1 -> 2)' ('outdated') } } } } -// -// resetTreeFilter(ExternalSystemTextAttributes.OUTDATED_ENTITY) -// checkTree { -// project { -// module1 { -// dependencies { -// 'lib (1 -> 2)' ('outdated') -// 'same-lib'() -// } } -// module2 { -// dependencies { -// 'lib (1 -> 2)' ('outdated') } } } } -// } -// -// @Test -// void "gradle-local library after outdated library"() { -// init( -// gradle: { -// project { -// module { -// dependencies { -// library('lib1-1') } } } }, -// intellij: { -// project { -// module { -// dependencies { -// library('lib1-1') } } } } ) -// checkChanges {} -// -// setState(gradle: { -// project { -// module { -// dependencies { -// library('lib1-2')} } } } ) -// -// checkChanges { -// libraryVersion ( -// name: 'lib1', -// gradleVersion: '2', -// gradleLibraryId: findLibraryId('lib1-2', true), -// ideVersion: '1', -// ideLibraryId: findLibraryId('lib1-1', false) -// ) -// } -// checkTree { -// project { -// module { -// dependencies { -// 'lib1 (1 -> 2)' ('outdated')} } } } -// -// setState(gradle: { -// project { -// module { -// dependencies { -// library('lib1-2') -// library('lib2-1') } } } } ) -// checkChanges { -// libraryVersion ( -// name: 'lib1', -// gradleVersion: '2', -// gradleLibraryId: findLibraryId('lib1-2', true), -// ideVersion: '1', -// ideLibraryId: findLibraryId('lib1-1', false) -// ) -// presence { -// library(gradle: gradle.libraryDependencies.values().flatten().findAll { it.name == "lib2-1" }) -// } -// } -// checkTree { -// project { -// module { -// dependencies { -// 'lib2-1' ('gradle') -// 'lib1 (1 -> 2)' ('outdated') -// } } } } -// } -// -// @Test -// void "outdated library dependencies at one module and gradle-local at another"() { -// init( -// gradle: { -// project { -// module('module1') { -// dependencies { -// library('lib-2')} } -// module ('module2') { -// dependencies { -// library('lib-2')} } } }, -// intellij: { -// project { -// module('module1') { -// dependencies { -// library('lib-1')} } -// module('module2') { -// dependencies()} } } -// ) -// checkTree { -// project { -// module1 { -// dependencies { -// 'lib (1 -> 2)'('outdated') } } -// module2 { -// dependencies { -// 'lib-2'('gradle') } } } } -// } -// -// @Test -// void "new outdated library dependency on active 'outdated' filter"() { -// Closure initialProject = { -// project { -// module { -// dependencies { -// library('lib-1') } } } } -// init(gradle: initialProject, intellij: initialProject) -// applyTreeFilter(ExternalSystemTextAttributes.OUTDATED_ENTITY) -// setState(gradle: { -// project { -// module { -// dependencies { -// library('lib-2')} } } } ) -// checkTree { -// project { -// module { -// dependencies { -// 'lib (1 -> 2)'('outdated') -// } } } } -// } -} diff --git a/plugins/gradle/testSources/org/jetbrains/plugins/gradle/sync/MovedJarsPostProcessorTest.groovy b/plugins/gradle/testSources/org/jetbrains/plugins/gradle/sync/MovedJarsPostProcessorTest.groovy deleted file mode 100644 index 398dec2f792a..000000000000 --- a/plugins/gradle/testSources/org/jetbrains/plugins/gradle/sync/MovedJarsPostProcessorTest.groovy +++ /dev/null @@ -1,72 +0,0 @@ -/* - * Copyright 2000-2013 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.jetbrains.plugins.gradle.sync - -import com.intellij.openapi.roots.libraries.Library -import com.intellij.openapi.externalSystem.service.project.manage.JarDataService -import com.intellij.openapi.externalSystem.model.project.JarData -import com.intellij.openapi.externalSystem.model.project.LibraryData -import com.intellij.openapi.externalSystem.model.project.LibraryPathType -import org.jetbrains.plugins.gradle.testutil.AbstractGradleTest -import org.jetbrains.plugins.gradle.util.GradleUtil -import org.jetbrains.plugins.gradle.util.TestExternalJarManager -import org.junit.Assert -import org.junit.Test - -/** - * @author Denis Zhdanov - * @since 1/17/13 4:40 PM - */ -class MovedJarsPostProcessorTest extends AbstractGradleTest { - - @Test - void "moved jar matched"() { - // TODO den uncomment - //init( - // gradle: { - // project { - // module { - // dependencies { - // library('lib1', bin: ['repo1/jar1', 'repo1/jar2'], src: [ 'repo1/zip1', 'repo1/zip2']) }}}}, - // intellij: { - // project { - // module { - // dependencies { - // library('lib1', bin: ['repo2/jar1', 'repo2/jar2'], src: [ 'repo2/zip1', 'repo2/zip2']) }}}} - //) - // - //checkChanges { } - // - //def gradleLibrary = gradle.libraries['lib1'] as LibraryData - //def ideLibrary = intellij.libraries['lib1'] as Library - //def expectedImported = [ - // new JarData(GradleUtil.toCanonicalPath('repo1/jar1'), LibraryPathType.BINARY, null, gradleLibrary), - // new JarData(GradleUtil.toCanonicalPath('repo1/jar2'), LibraryPathType.BINARY, null, gradleLibrary), - // new JarData(GradleUtil.toCanonicalPath('repo1/zip1'), LibraryPathType.SOURCE, null, gradleLibrary), - // new JarData(GradleUtil.toCanonicalPath('repo1/zip2'), LibraryPathType.SOURCE, null, gradleLibrary), - //] - // - //def expectedRemoved = [ - // new JarData(GradleUtil.toCanonicalPath('repo2/jar1'), LibraryPathType.BINARY, ideLibrary, null), - // new JarData(GradleUtil.toCanonicalPath('repo2/jar2'), LibraryPathType.BINARY, ideLibrary, null), - // new JarData(GradleUtil.toCanonicalPath('repo2/zip1'), LibraryPathType.SOURCE, ideLibrary, null), - // new JarData(GradleUtil.toCanonicalPath('repo2/zip2'), LibraryPathType.SOURCE, ideLibrary, null), - //] - //TestExternalJarManager jarManager = container.getComponentInstance(JarDataService) - //Assert.assertEquals(expectedImported.toSet(), jarManager.importedJars.toSet()) - //Assert.assertEquals(expectedRemoved.toSet(), jarManager.removedJars.toSet()) - } -} diff --git a/plugins/gradle/testSources/org/jetbrains/plugins/gradle/sync/ProjectStructureChangesModelTest.groovy b/plugins/gradle/testSources/org/jetbrains/plugins/gradle/sync/ProjectStructureChangesModelTest.groovy deleted file mode 100644 index 8b129601b39d..000000000000 --- a/plugins/gradle/testSources/org/jetbrains/plugins/gradle/sync/ProjectStructureChangesModelTest.groovy +++ /dev/null @@ -1,925 +0,0 @@ -package org.jetbrains.plugins.gradle.sync - -import com.intellij.testFramework.SkipInHeadlessEnvironment -import com.intellij.openapi.externalSystem.model.project.change.JarPresenceChange -import com.intellij.openapi.externalSystem.model.project.change.ModulePresenceChange -import org.jetbrains.plugins.gradle.testutil.AbstractGradleTest -import org.jetbrains.plugins.gradle.testutil.AbstractProjectBuilder -import org.junit.Before -import org.junit.Test - -import static org.junit.Assert.assertEquals -import com.intellij.openapi.externalSystem.model.project.change.LibraryDependencyPresenceChange -import com.intellij.openapi.externalSystem.settings.ExternalSystemTextAttributes - -/** - * @author Denis Zhdanov - * @since 01/25/2012 - */ -@SkipInHeadlessEnvironment -public class ProjectStructureChangesModelTest extends AbstractGradleTest { - - @Before - public void setUp() { - super.setUp() - // TODO den uncomment -// clearChangePostProcessors() - } - - // TODO den remove - @Test - void "dummy"() { - } - - // TODO den uncomment -// @Test -// public void "obsolete gradle-local modules"() { -// // Configure initial projects state. -// init( -// gradle: { -// project { -// module { -// dependencies { -// library("lib1") -// library("lib2") -// library("lib3") -// } } } }, -// -// intellij: { -// project { -// module { -// dependencies { -// library("lib1") -// } } } }, -// changesSorter: { a, b -> -// b.getExternalEntity.dependencyName.compareTo(a.getExternalEntity.dependencyName) -// } -// ) -// -// // Check that the initial projects state is correctly parsed. -// checkChanges { -// presence { -// library(gradle: gradle.libraryDependencies.values().flatten().findAll { it.name == "lib2" }) -// library(gradle: gradle.libraryDependencies.values().flatten().findAll { it.name == "lib3" }) -// } } -// checkTree { -// project { -// module() { -// dependencies { -// lib2('gradle') // Gradle-local entities are on top -// lib3('gradle') // Gradle-local entities are on top -// lib1() -// } } } } -// -// // Add the same library at intellij side. Expecting to have the only change now. -// setState(intellij: { -// project { -// module { -// dependencies { -// library("lib1") -// library("lib2") -// } } } }) -// -// checkChanges { -// presence { -// library(gradle: gradle.libraryDependencies.values().flatten().findAll { it.name == "lib3" }) -// } } -// checkTree { -// project { -// module() { -// dependencies { -// lib3('gradle') // Gradle-local entities are on top -// lib1() -// lib2() -// } } } } -// -// // Remove the 'gradle local' dependency. -// setState(gradle: { -// project { -// module { -// dependencies { -// library("lib1") -// library("lib2") -// } } } }) -// -// checkChanges { } // no changes. -// assertEquals([].toSet(), changesModel.changes) -// checkTree { -// project { -// module { -// dependencies { -// lib1() -// lib2() -// } } } } -// } -// -// @Test -// public void "library dependencies on binary paths"() { -// // Let the model has two differences in a library setup initially. -// init( -// gradle: { -// project { -// module { -// dependencies { -// library("lib1") -// library("lib2", bin: ['jar1', 'jar2']) } } } }, -// intellij: { -// project { -// module { -// dependencies { -// library("lib1") -// library("lib2", bin: ['jar2', 'jar3']) } } } }) -// -// checkChanges { -// presence { -// jar(gradle: [findJarId('jar1')]) -// jar(intellij: [findJarId('jar3')]) -// } -// } -// -// checkTree { -// project { -// module { -// dependencies { -// lib1() -// lib2 { -// jar1('gradle') -// jar2() -// jar3('intellij') } } } } } -// -// // Remove one difference from the library setup and check that the corresponding node is still marked as conflicted -// setState( -// gradle: { -// project { -// module { -// dependencies { -// library("lib1") -// library("lib2", bin: ['jar2']) } } } }, -// intellij: { -// project { -// module { -// dependencies { -// library("lib1") -// library("lib2", bin: ['jar2', 'jar3']) } } } }) -// -// checkChanges { -// presence { -// jar(intellij: [findJarId('jar3')]) -// } -// } -// -// checkTree { -// project { -// module { -// dependencies { -// lib1() -// lib2 { -// jar2() -// jar3('intellij') } } } } } -// -// // Match the remaining change and check that the corresponding node is not marked as conflicted anymore. -// setState( -// gradle: { -// project { -// module { -// dependencies { -// library("lib1") -// library("lib2", bin: ['jar2', 'jar3']) -// } } } }, -// intellij: { -// project { -// module { -// dependencies { -// library("lib1") -// library("lib2", bin: ['jar2', 'jar3']) } } } }) -// checkChanges { } // No changes -// checkTree { -// project { -// module { -// dependencies { -// lib1() -// lib2 { -// jar2() -// jar3() } } } } } -// } -// -// @Test -// public void "gradle-local module which library setup differs from intellij when jar presence change goes first"() { -// init( -// gradle: { -// project { -// module('module1') { -// dependencies { -// library("lib1", bin: ['jar1', 'jar2']) }} -// module('module2') { -// dependencies { -// library("lib1", bin: ['jar1', 'jar2']) } } } }, -// intellij: { -// project { -// module('module1') { -// dependencies { -// library("lib1", bin: ['jar2', 'jar3']) } } } }, -// changesSorter: changeByClassSorter([ -// (JarPresenceChange) : 1, -// (LibraryDependencyPresenceChange) : 2, -// (ModulePresenceChange) : 3, -// ]) -// ) -// -// checkChanges { -// presence { -// jar(gradle: [findJarId('jar1')]) -// jar(intellij: [findJarId('jar3')]) -// library(gradle: gradle.libraryDependencies[gradle.modules['module2']].find { it.name == "lib1" }) -// module(gradle: gradle.modules['module2']) -// } -// } -// -// checkTree { -// project { -// module2('gradle') { -// dependencies { -// lib1('gradle') { -// jar1('gradle') -// jar2() -// jar3('intellij')} } } -// module1 { -// dependencies { -// lib1 { -// jar1('gradle') -// jar2() -// jar3('intellij') } } } } } -// } -// -// @Test -// public void "adding intellij-local jar"() { -// Closure initialProject = { -// project { -// module { -// dependencies { -// library('lib1', bin: ['jar1'])} } } } -// init(gradle: initialProject, intellij: initialProject) -// checkChanges {} // empty -// -// setState( -// intellij: { -// project { -// module { -// dependencies { -// library('lib1', bin: ['jar1', 'jar2']) -// } } } } -// ) -// -// checkChanges { -// presence { -// jar(intellij: [findJarId('jar2')]) -// } } -// checkTree { -// project { -// module { -// dependencies { -// lib1 { -// jar1() -// jar2('intellij')} } } } } -// } -// -// @Test -// public void "intellij module removal"() { -// Closure initialClosure = { -// project { -// module('module1') -// module('module2') { -// dependencies { -// library('lib1') -// library('lib2') -// } } } } -// init(gradle: initialClosure, intellij: initialClosure) -// checkChanges { } // No changes -// checkTree { -// project { -// module1() -// module2() { -// dependencies { -// lib1() -// lib2() -// } } } } -// -// setState(intellij: { -// project { -// module('module1') -// } } ) -// checkChanges { -// presence { -// module(gradle: gradle.modules['module2']) -// libraryDependency(gradle: gradle.modules['module2'].dependencies) -// } } -// checkTree { -// project { -// module2('gradle') { -// dependencies { -// lib1('gradle') -// lib2('gradle') -// } } -// module1() -// } } -// } -// -// @Test -// public void "gradle-local module is not treated as 'local' after import"() { -// init( -// gradle: { -// project { -// module('module1') -// module('module2') -// } }, -// intellij: { -// project { -// module('module1') -// } } -// ) -// checkChanges { -// presence { -// module(gradle: gradle.modules['module2']) -// } } -// checkTree { -// project { -// module2('gradle') -// module1() -// } } -// -// // Emulate import gradle module to intellij. -// setState(intellij: { -// project { -// module('module1') -// module('module2') -// } }) -// checkChanges { } // No changes -// checkTree { -// project { -// module1() -// module2() // Imported module node is not highlighted anymore. -// } } -// } -// -// @Test -// public void "mismatched module dependency import"() { -// init( -// gradle: { -// project { -// module('module1') -// module('module2') -// module('module3') { -// dependencies { -// module('module1') -// module('module2') -// } } } }, -// intellij: { -// project { -// module('module2') -// module('module4') -// module('module3') { -// dependencies { -// module('module2') -// module('module4') -// } } } } -// ) -// checkChanges { -// presence { -// module(gradle: gradle.modules['module1']) -// module(intellij: intellij.modules['module4']) -// moduleDependency(gradle: gradle.moduleDependencies[gradle.modules['module3']].find { it.target == gradle.modules['module1']}) -// moduleDependency(intellij: intellij.moduleDependencies[intellij.modules['module3']].find { it.moduleName == 'module4'}) -// } } -// checkTree { -// project { -// module1('gradle') -// module2() -// module3() { -// dependencies { -// module1('gradle') -// module2() -// module4('intellij') -// } } -// module4('intellij') -// } } -// -// Closure newProjectState = { -// project { -// module('module1') -// module('module2') -// module('module4') -// module('module3') { -// dependencies { -// module('module1') -// module('module2') -// module('module4') -// } } } } -// setState(gradle: newProjectState, intellij: newProjectState) -// checkChanges { } // No changes -// checkTree { -// project { -// module1() -// module2() -// module3 { -// dependencies { -// module1() -// module2() -// module4() -// } } -// module4() -// } } -// } -// -// @Test -// public void "mismatched module dependency removal"() { -// init( -// gradle: { -// project { -// module('module1') -// module('module2') -// module('module3') { -// dependencies { -// module('module1') -// module('module2') -// } } } }, -// intellij: { -// project { -// module('module2') -// module('module4') -// module('module3') { -// dependencies { -// module('module2') -// module('module4') -// } } } } -// ) -// checkChanges { -// presence { -// module(gradle: gradle.modules['module1']) -// module(intellij: intellij.modules['module4']) -// moduleDependency(gradle: gradle.moduleDependencies[gradle.modules['module3']].find { it.target == gradle.modules['module1']}) -// moduleDependency(intellij: intellij.moduleDependencies[intellij.modules['module3']].find { it.moduleName == 'module4'}) -// } } -// checkTree { -// project { -// module1('gradle') -// module2() -// module3() { -// dependencies { -// module1('gradle') -// module2() -// module4('intellij') -// } } -// module4('intellij') -// } } -// -// Closure newProjectState = { -// project { -// module('module2') -// module('module3') { -// dependencies { -// module('module2') -// } } } } -// setState(gradle: newProjectState, intellij: newProjectState) -// checkChanges { } // No changes -// checkTree { -// project { -// module2() -// module3 { -// dependencies { -// module2() -// } } } } -// } -// -// @Test -// public void "cycled module dependencies"() { -// init( -// gradle: { -// project { -// module('module1') { -// dependencies { -// module('module2') -// } } -// module('module2') { -// dependencies { -// module('module1') -// } } } }, -// intellij: { -// project { -// module('module2') { -// dependencies { -// module('module3') -// } } -// module('module3') { -// dependencies { -// module('module2') -// } } } } -// ) -// checkChanges { -// presence { -// module(gradle: gradle.modules['module1']) -// module(intellij: intellij.modules['module3']) -// moduleDependency(gradle: gradle.moduleDependencies.values().flatten()) -// moduleDependency(intellij: intellij.moduleDependencies.values().flatten()) -// } } -// checkTree { -// project { -// module1('gradle') { -// dependencies { -// module2('gradle') -// } } -// module2() { -// dependencies { -// module1('gradle') -// module3('intellij') -// } } -// module3('intellij') { -// dependencies { -// module2('intellij') -// } } } } -// } -// -// @Test -// public void "local content root importing"() { -// init( -// gradle: { -// project { -// module { -// contentRoot('1') -// contentRoot('2') -// } } }, -// intellij: { -// project { -// module { -// contentRoot('2') -// contentRoot('3') -// } } } -// ) -// checkChanges { -// presence { -// contentRoot(gradle: gradle.contentRoots.values().flatten().find { it.rootPath.endsWith('1') }) -// contentRoot(intellij: intellij.contentRoots.values().flatten().find { it.file.path.endsWith('3') }) -// } } -// checkTree { -// project { -// module { -// "content-root:1"('gradle') -// "content-root:2"() -// "content-root:3"('intellij') -// } } } -// -// // Import local content roots. -// Closure projectState = { -// project { -// module { -// contentRoot('1') -// contentRoot('2') -// contentRoot('3') -// } } } -// setState(intellij: projectState, gradle: projectState) -// checkChanges { } // No changes -// checkTree { -// project { -// module { -// "content-root:1"() -// "content-root:2"() -// "content-root:3"() -// } } } -// } -// -// @Test -// public void "module removal at intellij"() { -// Closure initial = { -// project { -// module { -// contentRoot('1') -// dependencies { -// library('lib1') -// } } } } -// init(gradle: initial, intellij: initial) -// checkChanges { } -// checkTree { -// project { -// module { -// "content-root"() -// dependencies { -// lib1() -// } } } } -// -// setState(intellij: { project { }}) -// def m = gradle.modules.values().flatten().first() -// checkChanges { -// presence { -// module(gradle: m) -// contentRoot(gradle: gradle.contentRoots[m]) -// libraryDependency(gradle: gradle.libraryDependencies[m]) -// } } -// checkTree { -// project { -// module('gradle') { -// "content-root"('gradle') -// dependencies { -// lib1('gradle') -// } } } } -// } -// -// @Test -// public void "content root is correctly highlighted after importing gradle local module"() { -// Closure completeProject = { -// project { -// module { -// contentRoot('1') -// } } } -// init(gradle: completeProject, intellij: { project { }}) -// def m = gradle.modules.values().flatten().first() -// checkChanges { -// presence { -// module(gradle: m) -// contentRoot(gradle: gradle.contentRoots[m]) -// } } -// checkTree { -// project { -// module('gradle') { -// "content-root"('gradle') -// } } } -// -// // Import the whole module. -// setState(gradle: completeProject, intellij: completeProject) -// checkChanges { } -// checkTree { -// project { -// module() { -// "content-root"() -// } } } -// } -// -// @Test -// public void "filter new gradle local changes"() { -// Closure initial = { -// project { -// module('module1') { -// } } } -// init(gradle: initial, intellij: initial) -// -// // Apply filter. -// applyTreeFilter(ExternalSystemTextAttributes.CHANGE_CONFLICT) -// checkTree { -// project { -// } } -// -// // Introduce gradle-local entities. -// setState(gradle: { -// project { -// module('module1') -// module('module2') { -// contentRoot('1') -// dependencies { -// library('lib1') -// module('module1') -// } } } }) -// -// // Ensure that gradle-local entities have not been picked up. -// checkTree { -// project { -// } } -// } -// -// @Test -// public void "filter new conflict changes"() { -// Closure initial = { -// project { -// module('module1') -// module('module2') { -// dependencies { -// library('lib1', bin: ['1']) -// module('module1', scope: 'compile') -// } } } } -// init(gradle: initial, intellij: initial) -// -// // Apply filter. -// applyTreeFilter(ExternalSystemTextAttributes.EXTERNAL_SYSTEM_LOCAL_CHANGE) -// checkTree { -// project { -// } } -// -// // Introduce conflict changes. -// setState(gradle: { -// project { -// module('module1') -// module('module2') { -// dependencies { -// library('lib1', bin: ['2']) -// module('module1', scope: 'test') -// } } } }) -// -// // Ensure that conflict changes have not been processed. -// checkTree { -// project { -// } } -// } -// -// @Test -// public void "filter obsolete gradle local changes"() { -// Closure completeProject = { -// project { -// module('module1') -// module('module2') { -// contentRoot('1') -// dependencies { -// module('module1') -// library('lib1') -// } } } } -// init ( -// gradle: completeProject, -// intellij: { -// project { -// } } -// ) -// -// applyTreeFilter(ExternalSystemTextAttributes.EXTERNAL_SYSTEM_LOCAL_CHANGE) -// checkTree { -// project { -// module1('gradle') -// module2('gradle') { -// "content-root"('gradle') -// dependencies { -// module1('gradle') -// lib1('gradle') -// } } } } -// -// setState(intellij: completeProject) -// checkTree { -// project { -// } } -// } -// -// @Test -// public void "filter obsolete conflict changes"() { -// Closure gradleProject = { -// project { -// module('module1') -// module('module2') { -// dependencies { -// library('lib1', bin: ['jar1']) -// module('module1', scope: 'compile') -// } } } } -// init(gradle: gradleProject, intellij: { -// project { -// module('module1') -// module('module2') { -// dependencies { -// library('lib1', bin: ['jar2']) -// module('module1', scope: 'test') -// } } } }) -// -// applyTreeFilter(ExternalSystemTextAttributes.CHANGE_CONFLICT) -// checkTree { -// project { -// module2 { -// dependencies { -// module1('conflict') -// } } } } -// -// setState(intellij: gradleProject) -// checkTree { -// project { -// } } -// } -// -// @Test -// public void "gradle-local library dependency with mixed jars state"() { -// init( -// gradle: { -// project { -// module('module1') { -// dependencies { -// library('lib1', bin: ['jar1', 'jar2']) } } -// module('module2') { -// dependencies { -// library('lib1', bin: ['jar1', 'jar2'])} } } }, -// intellij: { -// project { -// module('module1') { -// dependencies { -// library('lib1', bin: ['jar2', 'jar3']) }} -// module('module2') }} -// ) -// -// checkChanges { -// presence { -// libraryDependency(gradle: gradle.modules['module2'].dependencies) -// jar(gradle: [findJarId('jar1')]) -// jar(intellij: [findJarId('jar3')]) -// } -// } -// checkTree { -// project { -// module1 { -// dependencies { -// lib1 { -// jar1('gradle') -// jar2() -// jar3('intellij')} } } -// module2 { -// dependencies { -// lib1('gradle') { -// jar1('gradle') -// jar2() -// jar3('intellij') } } } } } -// } -// -// @Test -// public void "gradle-local library dependency for gradle-local library"() { -// init( -// gradle: { -// project { -// module { -// dependencies { -// library('lib1', bin: ['jar1', 'jar2']) } } } }, -// intellij: { -// project { -// module() } }) -// -// checkChanges { -// presence { -// libraryDependency(gradle: gradle.modules[AbstractProjectBuilder.SAME_TOKEN].dependencies) -// jar(gradle: [findJarId('jar1')]) -// jar(gradle: [findJarId('jar2')]) -// } } -// -// checkTree { -// project { -// module { -// dependencies { -// lib1('gradle') { -// jar1('gradle') -// jar2('gradle') -// } } } } } -// } -// -// @Test -// public void "intellij-local library dependency with mixed jars state"() { -// init( -// gradle: { -// project { -// module('module1') { -// dependencies { -// library('lib1', bin: ['jar1', 'jar2']) } } -// module('module2')} }, -// intellij: { -// project { -// module('module1') { -// dependencies { -// library('lib1', bin: ['jar2', 'jar3']) }} -// module('module2') { -// dependencies { -// library('lib1', bin: ['jar1', 'jar2'])}}}} -// ) -// -// checkChanges { -// presence { -// libraryDependency(intellij: intellij.libraryDependencies[intellij.modules['module2']]) -// jar(gradle: [findJarId('jar1')]) -// jar(intellij: [findJarId('jar3')]) -// } -// } -// checkTree { -// project { -// module1 { -// dependencies { -// lib1 { -// jar1('gradle') -// jar2() -// jar3('intellij')} } } -// module2 { -// dependencies { -// lib1('intellij') { -// jar1('gradle') -// jar2() -// jar3('intellij') } } } } } -// } -// -// @Test -// void "ide-local library jars are highlighted accordingly"() { -// init( -// gradle: { -// project { -// module() } }, -// intellij: { -// project { -// module { -// dependencies { -// library('lib', bin: ['jar']) } } } } -// ) -// checkChanges { -// presence { -// libraryDependency(intellij: intellij.libraryDependencies.values().flatten()) -// jar(intellij: [findJarId('jar')]) -// } } -// checkTree { -// project { -// module { -// dependencies { -// lib('intellij') { -// jar('intellij') } } } } } -// } -}
\ No newline at end of file diff --git a/plugins/gradle/testSources/org/jetbrains/plugins/gradle/testutil/AbstractGradleTest.groovy b/plugins/gradle/testSources/org/jetbrains/plugins/gradle/testutil/AbstractGradleTest.groovy deleted file mode 100644 index 7b3b1c33326a..000000000000 --- a/plugins/gradle/testSources/org/jetbrains/plugins/gradle/testutil/AbstractGradleTest.groovy +++ /dev/null @@ -1,246 +0,0 @@ -package org.jetbrains.plugins.gradle.testutil - -import com.intellij.openapi.components.ServiceManager -import com.intellij.openapi.editor.colors.TextAttributesKey -import com.intellij.openapi.externalSystem.service.project.ExternalLibraryPathTypeMapper -import com.intellij.openapi.externalSystem.service.project.ProjectStructureServices -import com.intellij.openapi.project.Project -import com.intellij.openapi.roots.OrderRootType -import com.intellij.openapi.roots.libraries.Library -import org.jetbrains.annotations.NotNull -import org.jetbrains.plugins.gradle.action.AbstractGradleSyncTreeFilterAction -import com.intellij.openapi.externalSystem.service.project.change.AutoImporter -import org.jetbrains.plugins.gradle.config.GradleColorAndFontDescriptorsProvider -import org.jetbrains.plugins.gradle.settings.GradleLocalSettings -import org.jetbrains.plugins.gradle.settings.GradleSettings -import com.intellij.openapi.externalSystem.service.project.PlatformFacade -import com.intellij.openapi.externalSystem.model.project.change.ExternalProjectStructureChangesCalculator -import org.jetbrains.plugins.gradle.diff.contentroot.GradleContentRootStructureChangesCalculator -import org.jetbrains.plugins.gradle.diff.dependency.GradleLibraryDependencyStructureChangesCalculator -import org.jetbrains.plugins.gradle.diff.dependency.GradleModuleDependencyStructureChangesCalculator -import org.jetbrains.plugins.gradle.diff.library.GradleLibraryStructureChangesCalculator -import org.jetbrains.plugins.gradle.diff.module.GradleModuleStructureChangesCalculator -import org.jetbrains.plugins.gradle.diff.project.GradleProjectStructureChangesCalculator -import com.intellij.openapi.externalSystem.service.project.manage.EntityManageHelper -import com.intellij.openapi.externalSystem.service.project.manage.JarDataService -import com.intellij.openapi.externalSystem.service.project.manage.LibraryDataService -import com.intellij.openapi.externalSystem.service.project.manage.ProjectDataServiceImpl -import com.intellij.openapi.externalSystem.model.ProjectSystemId -import com.intellij.openapi.externalSystem.model.project.LibraryData -import com.intellij.openapi.externalSystem.model.project.LibraryPathType -import com.intellij.openapi.externalSystem.model.project.id.EntityIdMapper -import com.intellij.openapi.externalSystem.model.project.id.JarId -import com.intellij.openapi.externalSystem.model.project.id.LibraryId -import org.jetbrains.plugins.gradle.sync.GradleDuplicateLibrariesPreProcessor -import com.intellij.openapi.externalSystem.service.project.change.MovedJarsPostProcessor -import com.intellij.openapi.externalSystem.service.project.change.OutdatedLibraryVersionPostProcessor -import com.intellij.openapi.externalSystem.service.project.change.ProjectStructureChangesModel -import com.intellij.openapi.externalSystem.service.project.ProjectStructureHelper -import com.intellij.openapi.externalSystem.ui.ExternalProjectStructureTreeModel -import com.intellij.openapi.externalSystem.ui.ExternalProjectStructureNodeFilter -import org.jetbrains.plugins.gradle.util.* -import org.junit.Before -import org.picocontainer.MutablePicoContainer -import org.picocontainer.defaults.DefaultPicoContainer - -import static org.junit.Assert.fail - -/** - * @author Denis Zhdanov - * @since 2/13/12 10:43 AM - */ -public abstract class AbstractGradleTest { - - ProjectStructureChangesModel changesModel - ExternalProjectStructureTreeModel treeModel - GradleProjectBuilder gradle - IntellijProjectBuilder intellij - ChangeBuilder changesBuilder - ProjectStructureChecker treeChecker - def container - private Map<TextAttributesKey, ExternalProjectStructureNodeFilter> treeFilters = [:] - - @Before - public void setUp() { - // TODO den uncomment - //gradle = new GradleProjectBuilder() - //intellij = new IntellijProjectBuilder() - //changesBuilder = new ChangeBuilder() - //treeChecker = new ProjectStructureChecker() - //container = new DefaultPicoContainer() { - // @Override - // Object getComponentInstance(Object componentKey) { - // def result = super.getComponentInstance(componentKey) - // if (result == null && componentKey instanceof String) { - // def clazz = Class.forName(componentKey) - // if (clazz != null) { - // result = super.getComponentInstance(clazz) - // } - // } - // result - // } - //} - //container.registerComponentInstance(Project, intellij.project) - //container.registerComponentInstance(PlatformFacade, intellij.platformFacade as PlatformFacade) - //container.registerComponentImplementation(ProjectStructureChangesModel) - //container.registerComponentImplementation(ExternalProjectStructureTreeModel) - //container.registerComponentImplementation(ProjectStructureHelper) - //container.registerComponentImplementation(ExternalProjectStructureChangesCalculator, GradleProjectStructureChangesCalculator) - //container.registerComponentImplementation(GradleModuleStructureChangesCalculator) - //container.registerComponentImplementation(GradleContentRootStructureChangesCalculator) - //container.registerComponentImplementation(GradleModuleDependencyStructureChangesCalculator) - //container.registerComponentImplementation(GradleLibraryDependencyStructureChangesCalculator) - //container.registerComponentImplementation(GradleLibraryStructureChangesCalculator) - //container.registerComponentImplementation(EntityIdMapper) - //container.registerComponentImplementation(ProjectStructureServices) - //container.registerComponentImplementation(ExternalLibraryPathTypeMapper, TestExternalLibraryPathTypeMapper) - //container.registerComponentImplementation(ExternalDependencyManager) - //container.registerComponentImplementation(LibraryDataService) - //container.registerComponentImplementation(JarDataService, TestExternalJarManager) - //container.registerComponentImplementation(ProjectDataServiceImpl) - //container.registerComponentImplementation(GradleDuplicateLibrariesPreProcessor) - //container.registerComponentImplementation(MovedJarsPostProcessor, TestMovedJarsPostProcessor) - //container.registerComponentImplementation(OutdatedLibraryVersionPostProcessor) - //container.registerComponentImplementation(AutoImporter) - //container.registerComponentImplementation(GradleSettings) - //container.registerComponentImplementation(GradleLocalSettings) - //container.registerComponentImplementation(EntityManageHelper) - //configureContainer(container) - // - //intellij.projectStub.getComponent = { clazz -> container.getComponentInstance(clazz) } - //intellij.projectStub.getPicoContainer = { container } - // - //changesModel = container.getComponentInstance(ProjectStructureChangesModel) as ProjectStructureChangesModel - // - //for (d in GradleColorAndFontDescriptorsProvider.DESCRIPTORS) { - // treeFilters[d.key] = AbstractGradleSyncTreeFilterAction.createFilter(d.key) - //} - // - //def settings = ServiceManager.getService(intellij.project, GradleSettings.class) - //settings.useAutoImport = false - } - - protected void clearChangePostProcessors() { - changesModel.commonPreProcessors.clear() - changesModel.commonPostProcessors.clear() - } - - protected void configureContainer(MutablePicoContainer container) { - } - - @SuppressWarnings("GroovyAssignabilityCheck") - protected def init(map = [:]) { - treeModel = container.getComponentInstance(ExternalProjectStructureTreeModel) as ExternalProjectStructureTreeModel - treeModel.processChangesAtTheSameThread = true; - setState(map, false) - treeModel.rebuild() - changesModel.update(gradle.project) - } - - protected def setState(map, update = true) { - map.intellij?.delegate = intellij - map.intellij?.call() - map.gradle?.delegate = gradle - map.gradle?.call() - treeModel.changesComparator = map.changesSorter as Comparator - if (update) { - changesModel.update(gradle.project) - } - } - - protected def checkChanges(Closure c) { - changesBuilder.changes.clear() - c.delegate = changesBuilder - def expected = c() - if (!expected) { - expected = [].toSet() - } - def actual = new HashSet(changesModel.changes) - if (expected == actual) { - return - } - actual.removeAll(expected) - expected.removeAll(changesModel.changes) - def message = "Project structure changes are mismatched." - if (expected) { - message += "\n Expected but not matched:" - expected.each { message += "\n * $it"} - } - if (actual) { - message += "\n Unexpected:" - actual.each { message += "\n * $it"} - } - fail(message) - } - - protected def checkTree(c) { - def nodeBuilder = new NodeBuilder() - c.delegate = nodeBuilder - def expected = c() - treeChecker.check(expected, treeModel.root) - } - - protected static Closure changeByClassSorter(Map<Class<?>, Integer> rules) { - { a, b -> - def weightA = rules[a.class] ?: Integer.MAX_VALUE - def weightB = rules[b.class] ?: Integer.MAX_VALUE - if (weightA == weightB) { - return a.hashCode() - b.hashCode() - } - else { - return weightA - weightB - } - } - } - - protected def applyTreeFilter(@NotNull TextAttributesKey toShow) { - treeModel.addFilter(treeFilters[toShow]) - } - - protected def resetTreeFilter(@NotNull TextAttributesKey filterKey) { - treeModel.removeFilter(treeFilters[filterKey]) - } - - @NotNull - protected JarId findJarId(@NotNull String path) { - String pathToUse = GradleUtil.toCanonicalPath(path) - for (LibraryData library in (gradle.libraries.values() as Collection<LibraryData>)) { - for (libPath in library.getPaths(LibraryPathType.BINARY)) { - if (libPath == pathToUse) { - return new JarId(pathToUse, LibraryPathType.BINARY, new LibraryId(ProjectSystemId.GRADLE, library.name)) - } - } - } - - for (Library library in (intellij.libraries.values() as Collection<Library>)) { - for (jarFile in library.getFiles(OrderRootType.CLASSES)) { - if (pathToUse == jarFile.path) { - return new JarId(pathToUse, LibraryPathType.BINARY, new LibraryId(ProjectSystemId.IDE, library.name)) - } - } - } - - String errorMessage = """ -Can't build an id object for given jar path ($path). - Available gradle libraries: - ${gradle.libraries.values().collect { LibraryData lib -> "${lib.name}: ${lib.getPaths(LibraryPathType.BINARY)}" }.join('\n ') } - Available intellij libraries: - ${intellij.libraries.values().collect { Library lib -> "${lib.name}: ${lib.getFiles(OrderRootType.CLASSES).collect{it.path}}" } - .join('\n ')} -""" - - throw new IllegalArgumentException(errorMessage) - } - - @NotNull - protected LibraryId findLibraryId(@NotNull String name, boolean gradleLibrary) { - def libraries = gradleLibrary ? gradle.libraries : intellij.libraries - def library = libraries[name] - if (library == null) { - def errorMessage = - "Can't find ${gradleLibrary ? 'gradle' : 'ide'} library with name '$name'. Available libraries: ${libraries.keySet()}" - throw new IllegalArgumentException(errorMessage) - } - new LibraryId(gradleLibrary ? ProjectSystemId.GRADLE : ProjectSystemId.IDE, name) - } -} diff --git a/plugins/gradle/testSources/org/jetbrains/plugins/gradle/testutil/ChangeBuilder.groovy b/plugins/gradle/testSources/org/jetbrains/plugins/gradle/testutil/ChangeBuilder.groovy deleted file mode 100644 index 0af1f810265c..000000000000 --- a/plugins/gradle/testSources/org/jetbrains/plugins/gradle/testutil/ChangeBuilder.groovy +++ /dev/null @@ -1,83 +0,0 @@ -package org.jetbrains.plugins.gradle.testutil - -import com.intellij.openapi.externalSystem.model.project.change.ContentRootPresenceChange -import com.intellij.openapi.externalSystem.model.project.change.LibraryDependencyPresenceChange -import com.intellij.openapi.externalSystem.model.project.change.ModuleDependencyPresenceChange -import com.intellij.openapi.externalSystem.model.project.change.OutdatedLibraryVersionChange -import com.intellij.openapi.externalSystem.model.project.change.JarPresenceChange -import com.intellij.openapi.externalSystem.model.project.change.ModulePresenceChange - -/** - * @author Denis Zhdanov - * @since 1/26/12 3:25 PM - */ -public class ChangeBuilder extends BuilderSupport { - - def changes = [] - - @Override - protected void setParent(Object parent, Object child) { - } - - @Override - protected Object createNode(Object name) { - createNode(name, [:]) - } - - @Override - protected Object createNode(Object name, Object value) { changes } - - @Override - protected Object createNode(Object name, Map attributes) { - switch (name) { - case "module": - changes.addAll attributes.gradle.collect { new ModulePresenceChange(it, null)} - changes.addAll attributes.intellij.collect { new ModulePresenceChange(null, it)} - return changes - case "moduleDependency": - changes.addAll attributes.gradle.collect { new ModuleDependencyPresenceChange(it, null) } - changes.addAll attributes.intellij.collect { new ModuleDependencyPresenceChange(null, it) } - return changes - case "library": - changes.addAll attributes.gradle.collect { new LibraryDependencyPresenceChange(it, null)} - changes.addAll attributes.intellij.collect { new LibraryDependencyPresenceChange(null, it)} - return changes - case "libraryDependency": - changes.addAll attributes.gradle.collect { new LibraryDependencyPresenceChange(it, null)} - changes.addAll attributes.intellij.collect { new LibraryDependencyPresenceChange(null, it)} - return changes - case "libraryConflict": - def library = attributes.entity - if (!library) { - throw new IllegalArgumentException("No entity is defined for the library conflict change. Known attributes: $attributes") - } - return library - case "contentRoot": - changes.addAll attributes.gradle.collect { new ContentRootPresenceChange(it, null)} - changes.addAll attributes.intellij.collect { new ContentRootPresenceChange(null, it)} - return changes - case "jar": - changes.addAll attributes.gradle.collect { new JarPresenceChange(it, null) } - changes.addAll attributes.intellij.collect { new JarPresenceChange(null, it) } - return changes - case "libraryVersion": - changes.add(new OutdatedLibraryVersionChange( - attributes.name, attributes.gradleLibraryId, attributes.gradleVersion, attributes.ideLibraryId, attributes.ideVersion - )) - } - changes - } - - @Override - protected Object createNode(Object name, Map attributes, Object value) { changes } - - @Override - protected Object postNodeCompletion(Object parent, Object node) { - parent == null ? changes.toSet() : node - } - - protected def register(change) { - changes << change - changes - } -} diff --git a/plugins/gradle/testSources/org/jetbrains/plugins/gradle/testutil/ProjectStructureChecker.groovy b/plugins/gradle/testSources/org/jetbrains/plugins/gradle/testutil/ProjectStructureChecker.groovy deleted file mode 100644 index e9d75adf4aa2..000000000000 --- a/plugins/gradle/testSources/org/jetbrains/plugins/gradle/testutil/ProjectStructureChecker.groovy +++ /dev/null @@ -1,89 +0,0 @@ -package org.jetbrains.plugins.gradle.testutil - -import com.intellij.openapi.module.Module -import com.intellij.openapi.project.Project -import org.jetbrains.annotations.NotNull -import com.intellij.openapi.externalSystem.model.project.id.ProjectEntityId -import com.intellij.openapi.externalSystem.ui.ProjectStructureNode - -import javax.swing.tree.DefaultMutableTreeNode -import com.intellij.openapi.externalSystem.settings.ExternalSystemTextAttributes -import com.intellij.openapi.externalSystem.ui.ProjectStructureNodeDescriptor -import org.junit.Assert -import static junit.framework.Assert.assertEquals -import static junit.framework.Assert.fail -import com.intellij.openapi.externalSystem.model.ProjectSystemId - -import com.intellij.openapi.externalSystem.model.project.ProjectEntityType - -/** - * @author Denis Zhdanov - * @since 1/30/12 6:04 PM - */ -class ProjectStructureChecker { - - static def BUILT_IN = [ - "project": Project, - "module" : Module - ] - - static def COLORS = [ - 'gradle' : ExternalSystemTextAttributes.EXTERNAL_SYSTEM_LOCAL_CHANGE, - 'intellij': ExternalSystemTextAttributes.IDE_LOCAL_CHANGE, - 'conflict': ExternalSystemTextAttributes.CHANGE_CONFLICT, - 'outdated': ExternalSystemTextAttributes.OUTDATED_ENTITY - ] - - def check(Node expected, DefaultMutableTreeNode actual) { - ProjectStructureNodeDescriptor descriptor = actual.userObject as ProjectStructureNodeDescriptor - checkName(expected, descriptor) - checkMarkup(expected, descriptor) - int childIndex = 0 - for (it in expected.children().findAll { it instanceof Collection }) { - check it as Node, actual.getChildAt(childIndex++) as DefaultMutableTreeNode - } - for (it in expected.children().findAll { it instanceof Node }) { - if (childIndex >= actual.childCount) { - fail "Expected node is not matched: $it" - } - check it as Node, actual.getChildAt(childIndex++) as DefaultMutableTreeNode - } - if (childIndex < actual.childCount) { - def transform = { nodePath(actual.getChildAt(it) as ProjectStructureNode<? extends ProjectEntityId>) } - fail("Unexpected nodes detected: ${(childIndex..<actual.childCount).collect(transform,).join(', ')}") - } - } - - @NotNull - private static String nodePath(@NotNull ProjectStructureNode<? extends ProjectEntityId> node) { - StringBuilder result = new StringBuilder("'${node.descriptor.name}") - for (ProjectStructureNode<? extends ProjectEntityId> n = node.parent; n != null; n = n.parent) { - result.append(" -> ${n.descriptor.name}") - } - result.append("'") - result.toString() - } - - private static void checkName(Node expected, ProjectStructureNodeDescriptor actual) { - if (AbstractProjectBuilder.SAME_TOKEN == actual.toString() || expected.name() == actual.toString()) { - return - } - def clazz = BUILT_IN[expected.name().toString()] - if (clazz == null || !clazz.isAssignableFrom(actual.element.class)) { - Assert.fail( - "Failed node name check. Expected to find name '${expected.name()}'" + (clazz ? " or user object of type ${clazz.simpleName}" : "") - + " but got: name='$actual', user object=${actual.element} " - ) - } - } - - static def checkMarkup(Node node, ProjectStructureNodeDescriptor descriptor) { - def expectedMarkup = COLORS[node.children().find {it instanceof CharSequence}.toString()]?: ExternalSystemTextAttributes.NO_CHANGE - assertEquals("node '$descriptor'", expectedMarkup, descriptor.attributes) - - if (descriptor.element.type != ProjectEntityType.SYNTHETIC) { - def expectedOwner = expectedMarkup == ExternalSystemTextAttributes.EXTERNAL_SYSTEM_LOCAL_CHANGE ? ProjectSystemId.GRADLE : ProjectSystemId.IDE - assertEquals("node '$descriptor'", expectedOwner, descriptor.element.owner) - } - } -} diff --git a/plugins/gradle/testSources/org/jetbrains/plugins/gradle/util/TestExternalJarManager.groovy b/plugins/gradle/testSources/org/jetbrains/plugins/gradle/util/TestExternalJarManager.groovy deleted file mode 100644 index d0f1dcf77076..000000000000 --- a/plugins/gradle/testSources/org/jetbrains/plugins/gradle/util/TestExternalJarManager.groovy +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright 2000-2013 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.jetbrains.plugins.gradle.util - -import com.intellij.openapi.externalSystem.service.project.ExternalLibraryPathTypeMapper -import com.intellij.openapi.externalSystem.service.project.ProjectStructureHelper -import com.intellij.openapi.project.Project -import org.jetbrains.annotations.NotNull -import com.intellij.openapi.externalSystem.service.project.PlatformFacade -import com.intellij.openapi.externalSystem.service.project.manage.JarDataService -import com.intellij.openapi.externalSystem.model.project.JarData - -/** - * @author Denis Zhdanov - * @since 1/18/13 2:16 PM - */ -class TestExternalJarManager extends JarDataService { - - def importedJars = [] - def removedJars = [] - - TestExternalJarManager(@NotNull PlatformFacade facade, - @NotNull ProjectStructureHelper helper, - @NotNull ExternalLibraryPathTypeMapper mapper) { - super(facade, helper, mapper); - } - - void importJars(@NotNull Collection<? extends JarData> jars, @NotNull Project project, boolean synchronous) { - importedJars.addAll(jars) - } - - void removeJars(@NotNull Collection<? extends JarData> jars, @NotNull Project project, boolean synchronous) { - removedJars.addAll(jars) - } -} diff --git a/plugins/gradle/testSources/org/jetbrains/plugins/gradle/util/TestMovedJarsPostProcessor.java b/plugins/gradle/testSources/org/jetbrains/plugins/gradle/util/TestMovedJarsPostProcessor.java deleted file mode 100644 index d35cadeccf2e..000000000000 --- a/plugins/gradle/testSources/org/jetbrains/plugins/gradle/util/TestMovedJarsPostProcessor.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Copyright 2000-2013 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.jetbrains.plugins.gradle.util; - -import com.intellij.openapi.externalSystem.service.project.manage.JarDataService; -import com.intellij.openapi.project.Project; -import org.jetbrains.annotations.NotNull; -import com.intellij.openapi.externalSystem.service.project.change.MovedJarsPostProcessor; - -/** - * @author Denis Zhdanov - * @since 1/18/13 2:11 PM - */ -public class TestMovedJarsPostProcessor extends MovedJarsPostProcessor { - - public TestMovedJarsPostProcessor(@NotNull JarDataService manager) { - super(manager); - } - - @Override - public void doMerge(@NotNull Runnable mergeTask, @NotNull Project project) { - mergeTask.run(); - } -} diff --git a/plugins/groovy/src/META-INF/plugin.xml b/plugins/groovy/src/META-INF/plugin.xml index 5d847e6c0d97..265266056696 100644 --- a/plugins/groovy/src/META-INF/plugin.xml +++ b/plugins/groovy/src/META-INF/plugin.xml @@ -250,6 +250,8 @@ order="first"/> <renamePsiElementProcessor implementation="org.jetbrains.plugins.groovy.refactoring.rename.RenameAliasImportedFieldProcessor" order="first"/> + <renamePsiElementProcessor implementation="org.jetbrains.plugins.groovy.refactoring.rename.RenameGroovyScriptProcessor"/> + <rename.inplace.resolveSnapshotProvider language="Groovy" implementationClass="org.jetbrains.plugins.groovy.refactoring.rename.inplace.GroovyResolveSnapshotProvider"/> @@ -981,7 +983,7 @@ implementationClass="org.jetbrains.plugins.groovy.codeInspection.untypedUnresolvedAccess.GroovyUntypedAccessInspection"/> <localInspection language="Groovy" groupPath="Groovy" shortName="GrUnresolvedAccess" displayName="Access to unresolved expression" groupName="Probable bugs" - enabledByDefault="true" level="WARNING" + enabledByDefault="true" level="WEAK WARNING" implementationClass="org.jetbrains.plugins.groovy.codeInspection.untypedUnresolvedAccess.GrUnresolvedAccessInspection"/> <localInspection language="Groovy" groupPath="Groovy" shortName="GroovySingletonAnnotation" displayName="Check '@Singleton' annotation conventions" diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/GroovyBundle.properties b/plugins/groovy/src/org/jetbrains/plugins/groovy/GroovyBundle.properties index 268058c36fcf..131fe230d341 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/GroovyBundle.properties +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/GroovyBundle.properties @@ -359,3 +359,4 @@ annotation.expected=Annotation expected annotation.type.cannot.be.inner=Annotation type cannot be inner cannot.find.operator.overload.method=Cannot resolve index access with arguments {0} named.arguments.are.not.allowed.inside.index.operations=Named arguments are not allowed inside index operations +expected.0.to.be.inline.constant=Expected ''{0}'' to be an inline constant diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/actions/generate/GroovyGenerationInfo.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/actions/generate/GroovyGenerationInfo.java index 72b88cdfaa95..90c9b9e00f1f 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/actions/generate/GroovyGenerationInfo.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/actions/generate/GroovyGenerationInfo.java @@ -20,14 +20,18 @@ import com.intellij.codeInsight.generation.PsiGenerationInfo; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.ScrollType; +import com.intellij.openapi.project.Project; import com.intellij.psi.PsiClass; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiMember; +import com.intellij.psi.codeStyle.CodeStyleManager; +import com.intellij.psi.javadoc.PsiDocComment; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.util.IncorrectOperationException; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.plugins.groovy.lang.GrReferenceAdjuster; +import org.jetbrains.plugins.groovy.lang.groovydoc.psi.api.GrDocComment; import org.jetbrains.plugins.groovy.lang.lexer.GroovyTokenTypes; import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElement; import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElementFactory; @@ -92,6 +96,19 @@ public class GroovyGenerationInfo<T extends PsiMember> extends PsiGenerationInfo } GrReferenceAdjuster.shortenReferences(member); + + adjustDocCommentIfExists(member); + } + + private static void adjustDocCommentIfExists(PsiMember member) { + final PsiElement child = member.getFirstChild(); + if (child instanceof PsiDocComment) { + final Project project = member.getProject(); + final GrDocComment groovyDoc = GroovyPsiElementFactory.getInstance(project).createDocCommentFromText(child.getText()); + child.delete(); + CodeStyleManager.getInstance(project).reformat(member); + member.getParent().addBefore(groovyDoc, member); + } } @Override diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/GroovyAnnotator.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/GroovyAnnotator.java index f324581756dc..7cb03049ed19 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/GroovyAnnotator.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/GroovyAnnotator.java @@ -36,6 +36,8 @@ import com.intellij.psi.infos.CandidateInfo; import com.intellij.psi.search.searches.SuperMethodsSearch; import com.intellij.psi.tree.IElementType; import com.intellij.psi.util.*; +import com.intellij.refactoring.introduceParameter.ExpressionConverter; +import com.intellij.util.IncorrectOperationException; import com.intellij.util.ObjectUtils; import com.intellij.util.VisibilityUtil; import com.intellij.util.containers.ContainerUtil; @@ -45,6 +47,7 @@ import gnu.trove.THashSet; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.plugins.groovy.GroovyBundle; +import org.jetbrains.plugins.groovy.GroovyFileType; import org.jetbrains.plugins.groovy.annotator.intentions.*; import org.jetbrains.plugins.groovy.codeInspection.untypedUnresolvedAccess.GrUnresolvedAccessInspection; import org.jetbrains.plugins.groovy.config.GroovyConfigUtils; @@ -57,9 +60,7 @@ import org.jetbrains.plugins.groovy.lang.psi.api.GroovyResolveResult; import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.GrListOrMap; import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.GrModifier; import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.GrModifierList; -import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.annotation.GrAnnotation; -import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.annotation.GrAnnotationArgumentList; -import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.annotation.GrAnnotationMemberValue; +import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.annotation.*; import org.jetbrains.plugins.groovy.lang.psi.api.statements.*; import org.jetbrains.plugins.groovy.lang.psi.api.statements.arguments.GrArgumentLabel; import org.jetbrains.plugins.groovy.lang.psi.api.statements.arguments.GrArgumentList; @@ -80,10 +81,7 @@ import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.path.GrI import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.path.GrMethodCallExpression; import org.jetbrains.plugins.groovy.lang.psi.api.statements.params.GrParameter; import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.*; -import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrAnnotationMethod; -import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrEnumConstant; -import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMember; -import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod; +import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.*; import org.jetbrains.plugins.groovy.lang.psi.api.toplevel.imports.GrImportStatement; import org.jetbrains.plugins.groovy.lang.psi.api.toplevel.packaging.GrPackageDefinition; import org.jetbrains.plugins.groovy.lang.psi.api.types.*; @@ -338,7 +336,7 @@ public class GroovyAnnotator extends GroovyElementVisitor { } checkTypeDefinition(myHolder, typeDefinition); - checkDuplicateMethod(typeDefinition.getMethods(), myHolder); + checkDuplicateMethod(typeDefinition, myHolder); checkImplementedMethodsOfClass(myHolder, typeDefinition); checkConstructors(myHolder, typeDefinition); @@ -1281,7 +1279,7 @@ public class GroovyAnnotator extends GroovyElementVisitor { public void visitFile(GroovyFileBase file) { final PsiClass scriptClass = file.getScriptClass(); if (scriptClass != null) { - checkDuplicateMethod(scriptClass.getMethods(), myHolder); + checkDuplicateMethod(scriptClass, myHolder); } } @@ -1347,6 +1345,49 @@ public class GroovyAnnotator extends GroovyElementVisitor { } @Override + public void visitAnnotationNameValuePair(GrAnnotationNameValuePair nameValuePair) { + final GrAnnotationMemberValue value = nameValuePair.getValue(); + + checkAnnotationAttributeValue(value, value); + } + + private boolean checkAnnotationAttributeValue(GrAnnotationMemberValue value, PsiElement toHighlight) { + if (value instanceof GrLiteral) return false; + if (value instanceof GrClosableBlock) return false; + + if (value instanceof GrReferenceExpression) { + PsiElement resolved = ((GrReferenceExpression)value).resolve(); + if (resolved instanceof PsiClass) return false; + + if (resolved instanceof GrAccessorMethod) resolved = ((GrAccessorMethod)resolved).getProperty(); + if (resolved instanceof PsiField) { + GrExpression initializer; + try { + initializer = resolved instanceof GrField + ? ((GrField)resolved).getInitializerGroovy() + : (GrExpression)ExpressionConverter.getExpression(((PsiField)resolved).getInitializer(), GroovyFileType.GROOVY_LANGUAGE, value.getProject()); + } + catch (IncorrectOperationException e) { + initializer = null; + } + + if (initializer != null) { + return checkAnnotationAttributeValue(initializer, toHighlight); + } + } + } + if (value instanceof GrAnnotationArrayInitializer) { + for (GrAnnotationMemberValue expression : ((GrAnnotationArrayInitializer)value).getInitializers()) { + if (checkAnnotationAttributeValue(expression, toHighlight)) return true; + } + return false; + } + + myHolder.createErrorAnnotation(toHighlight, GroovyBundle.message("expected.0.to.be.inline.constant", value.getText())); + return true; + } + + @Override public void visitImportStatement(GrImportStatement importStatement) { checkAnnotationList(myHolder, importStatement.getAnnotationList(), GroovyBundle.message("import.statement.cannot.have.modifiers")); } @@ -1717,8 +1758,8 @@ public class GroovyAnnotator extends GroovyElementVisitor { } } - private static void checkDuplicateMethod(PsiMethod[] methods, AnnotationHolder holder) { - MultiMap<MethodSignature, PsiMethod> map = GrClosureSignatureUtil.findMethodSignatures(methods); + private static void checkDuplicateMethod(PsiClass clazz, AnnotationHolder holder) { + MultiMap<MethodSignature, PsiMethod> map = GrClosureSignatureUtil.findRawMethodSignatures(clazz.getMethods(), clazz); processMethodDuplicates(map, holder); } diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/codeInspection/assignment/GroovyAssignabilityCheckInspection.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/codeInspection/assignment/GroovyAssignabilityCheckInspection.java index 1080800ccd1a..a86a1ea0f43b 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/codeInspection/assignment/GroovyAssignabilityCheckInspection.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/codeInspection/assignment/GroovyAssignabilityCheckInspection.java @@ -25,10 +25,12 @@ import com.intellij.openapi.editor.Editor; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Pair; import com.intellij.psi.*; +import com.intellij.psi.impl.PsiSubstitutorImpl; import com.intellij.psi.tree.IElementType; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.util.Function; import com.intellij.util.IncorrectOperationException; +import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.Nls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -64,6 +66,7 @@ import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.*; import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.literals.GrString; import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.path.GrIndexProperty; import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.path.GrMethodCallExpression; +import org.jetbrains.plugins.groovy.lang.psi.api.statements.params.GrParameter; import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.*; import org.jetbrains.plugins.groovy.lang.psi.api.types.GrCodeReferenceElement; import org.jetbrains.plugins.groovy.lang.psi.impl.GrClosureType; @@ -322,6 +325,26 @@ public class GroovyAssignabilityCheckInspection extends BaseInspection { return; } + if (variable instanceof GrParameter && ((GrParameter)variable).getDeclarationScope() instanceof GrMethod) { + final GrMethod method = (GrMethod)((GrParameter)variable).getDeclarationScope(); + final PsiTypeParameter[] parameters = method.getTypeParameters(); + + Map<PsiTypeParameter, PsiType> map = ContainerUtil.newHashMap(); + for (PsiTypeParameter parameter : parameters) { + final PsiClassType[] types = parameter.getSuperTypes(); + + if (types.length == 1) { + map.put(parameter, PsiWildcardType.createExtends(variable.getManager(), types[0])); + } + else { + map.put(parameter, PsiWildcardType.createExtends(variable.getManager(), PsiIntersectionType.createIntersection(types))); + } + } + PsiSubstitutor substitutor = PsiSubstitutorImpl.createSubstitutor(map); + checkAssignability(substitutor.substitute(varType), initializer); + return; + } + checkAssignability(varType, initializer); } diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/codeInspection/untypedUnresolvedAccess/GrUnresolvedAccessInspection.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/codeInspection/untypedUnresolvedAccess/GrUnresolvedAccessInspection.java index dcfe7a5bfd9e..3ec5540042d3 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/codeInspection/untypedUnresolvedAccess/GrUnresolvedAccessInspection.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/codeInspection/untypedUnresolvedAccess/GrUnresolvedAccessInspection.java @@ -379,7 +379,7 @@ public class GrUnresolvedAccessInspection extends GroovySuppressableInspectionTo return HighlightInfo.newHighlightInfo(HighlightInfoType.WRONG_REF).range(refNameElement).descriptionAndTooltip(message).create(); } - if (displayLevel == HighlightDisplayLevel.WARNING) { + if (displayLevel == HighlightDisplayLevel.WEAK_WARNING) { boolean isTestMode = ApplicationManager.getApplication().isUnitTestMode(); HighlightInfoType infotype = isTestMode ? HighlightInfoType.WARNING : HighlightInfoType.INFORMATION; diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/codeInspection/utils/JavaStylePropertiesUtil.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/codeInspection/utils/JavaStylePropertiesUtil.java index 759d8c9c4fde..7289e29aeb2f 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/codeInspection/utils/JavaStylePropertiesUtil.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/codeInspection/utils/JavaStylePropertiesUtil.java @@ -59,11 +59,13 @@ public class JavaStylePropertiesUtil { String name = getPropertyNameBySetterName(accessorName); GrExpression value = call.getExpressionArguments()[0]; GrReferenceExpression refExpr = (GrReferenceExpression)call.getInvokedExpression(); - String oldNameStr = refExpr.getReferenceNameElement().getText(); - String newRefExpr = StringUtil.trimEnd(refExpr.getText(), oldNameStr) + name; + final GroovyPsiElementFactory factory = GroovyPsiElementFactory.getInstance(call.getProject()); - final GrAssignmentExpression assignment = (GrAssignmentExpression)factory.createStatementFromText(newRefExpr + " = xxx", call); + final GrAssignmentExpression assignment = (GrAssignmentExpression)factory.createStatementFromText(name + " = xxx", call); + + ((GrReferenceExpression)assignment.getLValue()).setQualifier(refExpr.getQualifier()); assignment.getRValue().replaceWithExpression(value, true); + return assignment; } diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/config/GroovyFrameworkSupportProvider.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/config/GroovyFrameworkSupportProvider.java index 65fb89daca35..794897c7a5ed 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/config/GroovyFrameworkSupportProvider.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/config/GroovyFrameworkSupportProvider.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2013 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,7 +20,9 @@ import com.intellij.framework.addSupport.FrameworkSupportInModuleConfigurable; import com.intellij.framework.addSupport.FrameworkSupportInModuleProvider; import com.intellij.ide.util.frameworkSupport.FrameworkSupportModel; import com.intellij.ide.util.projectWizard.ModuleBuilder; +import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleType; +import com.intellij.openapi.roots.ui.configuration.FacetsProvider; import org.jetbrains.annotations.NotNull; import org.jetbrains.plugins.groovy.util.GroovyUtils; @@ -39,6 +41,12 @@ public class GroovyFrameworkSupportProvider extends FrameworkSupportInModuleProv return super.isEnabledForModuleBuilder(builder) && !(builder instanceof GroovyAwareModuleBuilder); } + @Override + public boolean isSupportAlreadyAdded(@NotNull Module module, @NotNull FacetsProvider facetsProvider) { + final String version = GroovyConfigUtils.getInstance().getSDKVersion(module); + return version != null; + } + @NotNull public FrameworkSupportInModuleConfigurable createConfigurable(final @NotNull FrameworkSupportModel model) { return new GroovySupportConfigurable(); diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/intentions/other/GrAliasImportIntention.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/intentions/other/GrAliasImportIntention.java index 3112af6fe3e0..4663ef6d305f 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/intentions/other/GrAliasImportIntention.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/intentions/other/GrAliasImportIntention.java @@ -139,7 +139,7 @@ public class GrAliasImportIntention extends Intention { final PsiElement aliasNameElement = templateImport.getAliasNameElement(); assert aliasNameElement != null; - templateBuilder.replaceElement(aliasNameElement, new MyLookupExpression(resolved.getName(), names, (PsiNamedElement)resolved, true, null)); + templateBuilder.replaceElement(aliasNameElement, new MyLookupExpression(resolved.getName(), names, (PsiNamedElement)resolved, resolved, true, null)); Template built = templateBuilder.buildTemplate(); final Editor newEditor = QuickfixUtil.positionCursor(project, file, templateImport); diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/signatures/GrClosureSignatureUtil.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/signatures/GrClosureSignatureUtil.java index c3a7026f105d..69b5f2aca795 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/signatures/GrClosureSignatureUtil.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/signatures/GrClosureSignatureUtil.java @@ -18,6 +18,7 @@ package org.jetbrains.plugins.groovy.lang.psi.impl.signatures; import com.intellij.openapi.util.Pair; import com.intellij.openapi.util.Trinity; import com.intellij.psi.*; +import com.intellij.psi.impl.PsiSubstitutorImpl; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.util.InheritanceUtil; import com.intellij.psi.util.MethodSignature; @@ -770,14 +771,41 @@ public class GrClosureSignatureUtil { return result; } - public static MultiMap<MethodSignature, PsiMethod> findMethodSignatures(PsiMethod[] methods) { - MultiMap<MethodSignature, PsiMethod> map = new MultiMap<MethodSignature, PsiMethod>(); + @NotNull + public static MultiMap<MethodSignature, PsiMethod> findRawMethodSignatures(@NotNull PsiMethod[] methods, @NotNull PsiClass clazz) { + Map<PsiTypeParameter, PsiType> initialMap = ContainerUtil.newHashMap(); + + for (PsiTypeParameter parameter : clazz.getTypeParameters()) { + initialMap.put(parameter, null); + } + + final PsiSubstitutor initialSubstitutor = PsiSubstitutorImpl.createSubstitutor(initialMap); + + MultiMap<MethodSignature, PsiMethod> result = new MultiMap<MethodSignature, PsiMethod>(); for (PsiMethod method : methods) { final PsiMethod actual = method instanceof GrReflectedMethod ? ((GrReflectedMethod)method).getBaseMethod() : method; - map.putValue(method.getSignature(PsiSubstitutor.EMPTY), actual); + + PsiSubstitutor substitutor = calcRawSubstitutor(initialMap, initialSubstitutor, actual); + result.putValue(method.getSignature(substitutor), actual); } - return map; + return result; + } + + @NotNull + private static PsiSubstitutor calcRawSubstitutor(@NotNull Map<PsiTypeParameter, PsiType> initialMap, + @NotNull PsiSubstitutor initialSubstitutor, + @NotNull PsiMethod actual) { + if (actual.hasTypeParameters()) { + final HashMap<PsiTypeParameter, PsiType> map1 = ContainerUtil.newHashMap(initialMap); + for (PsiTypeParameter parameter : actual.getTypeParameters()) { + map1.put(parameter, null); + } + return PsiSubstitutorImpl.createSubstitutor(map1); + } + else { + return initialSubstitutor; + } } private static MethodSignature generateSignature(String name, diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/expressions/GrReferenceExpressionImpl.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/expressions/GrReferenceExpressionImpl.java index c519f46da231..829c73474fd0 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/expressions/GrReferenceExpressionImpl.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/expressions/GrReferenceExpressionImpl.java @@ -94,11 +94,19 @@ public class GrReferenceExpressionImpl extends GrReferenceElementImpl<GrExpressi private boolean findClassOrPackageAtFirst() { final String name = getReferenceName(); - if (name == null || name.length() == 0 || hasAt()) return false; - return Character.isUpperCase(name.charAt(0)) || + if (StringUtil.isEmpty(name) || hasAt()) return false; + assert name != null; + + return Character.isUpperCase(name.charAt(0)) && !isMethodCallRef() || getParent() instanceof GrReferenceExpressionImpl && ((GrReferenceExpressionImpl)getParent()).findClassOrPackageAtFirst(); } + private boolean isMethodCallRef() { + final PsiElement parent = getParent(); + return parent instanceof GrMethodCall || + parent instanceof GrReferenceExpressionImpl && ((GrReferenceExpressionImpl)parent).isMethodCallRef(); + } + private boolean isDefinitelyKeyOfMap() { final GrExpression qualifier = ResolveUtil.getSelfOrWithQualifier(this); if (qualifier == null) return false; @@ -190,13 +198,10 @@ public class GrReferenceExpressionImpl extends GrReferenceElementImpl<GrExpressi boolean canBeClassOrPackage = ResolveUtil.canBeClassOrPackage(this); if (canBeClassOrPackage && findClassOrPackageAtFirst()) { - boolean preferVar = containsLocalVar(fieldCandidates); - if (!preferVar) { - ResolverProcessor classProcessor = new ClassResolverProcessor(name, this, kinds); - GrReferenceResolveUtil.resolveImpl(classProcessor, this); - classCandidates = classProcessor.getCandidates(); - if (classCandidates.length > 0) return classCandidates; - } + ResolverProcessor classProcessor = new ClassResolverProcessor(name, this, kinds); + GrReferenceResolveUtil.resolveImpl(classProcessor, this); + classCandidates = classProcessor.getCandidates(); + if (classCandidates.length > 0 && containsPackage(classCandidates)) return classCandidates; } //if reference expression is in class we need to return field instead of accessor method @@ -246,6 +251,13 @@ public class GrReferenceExpressionImpl extends GrReferenceElementImpl<GrExpressi return GroovyResolveResult.EMPTY_ARRAY; } + private static boolean containsPackage(@NotNull GroovyResolveResult[] candidates) { + for (GroovyResolveResult candidate : candidates) { + if (candidate.getElement() instanceof PsiPackage) return true; + } + return false; + } + private static boolean containsLocalVar(GroovyResolveResult[] fieldCandidates) { boolean preferVar = false; if (fieldCandidates.length > 0) { @@ -727,7 +739,7 @@ public class GrReferenceExpressionImpl extends GrReferenceElementImpl<GrExpressi @Nullable private static PsiType getInferredTypes(GrReferenceExpressionImpl refExpr, @Nullable PsiElement resolved) { final GrExpression qualifier = refExpr.getQualifier(); - if (qualifier == null && !(resolved instanceof PsiClass)) { + if (qualifier == null && !(resolved instanceof PsiClass || resolved instanceof PsiPackage)) { return TypeInferenceHelper.getCurrentContext().getVariableType(refExpr); } else if (qualifier != null) { diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/types/GrCodeReferenceElementImpl.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/types/GrCodeReferenceElementImpl.java index 81a9ca0f7078..159c92b24116 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/types/GrCodeReferenceElementImpl.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/types/GrCodeReferenceElementImpl.java @@ -29,6 +29,7 @@ import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.util.ArrayUtil; import com.intellij.util.Consumer; +import com.intellij.util.IncorrectOperationException; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.plugins.groovy.lang.completion.GroovyCompletionUtil; @@ -77,6 +78,16 @@ public class GrCodeReferenceElementImpl extends GrReferenceElementImpl<GrCodeRef } @Override + public PsiElement handleElementRenameSimple(String newElementName) throws IncorrectOperationException { + if (StringUtil.isJavaIdentifier(newElementName)) { + return super.handleElementRenameSimple(newElementName); + } + else { + throw new IncorrectOperationException("Cannot rename reference to '" + newElementName + "'"); + } + } + + @Override protected GrCodeReferenceElement bindWithQualifiedRef(@NotNull String qName) { final GrTypeArgumentList list = getTypeArgumentList(); final String typeArgs = (list != null) ? list.getText() : ""; @@ -95,7 +106,7 @@ public class GrCodeReferenceElementImpl extends GrReferenceElementImpl<GrCodeRef } public GrCodeReferenceElement getQualifier() { - return (GrCodeReferenceElement) findChildByType(GroovyElementTypes.REFERENCE_ELEMENT); + return (GrCodeReferenceElement)findChildByType(GroovyElementTypes.REFERENCE_ELEMENT); } @Override @@ -126,17 +137,24 @@ public class GrCodeReferenceElementImpl extends GrReferenceElementImpl<GrCodeRef PsiElement parent = getParent(); if (parent instanceof GrCodeReferenceElementImpl) { - ReferenceKind parentKind = ((GrCodeReferenceElementImpl) parent).getKind(forCompletion); - if (parentKind == CLASS) return CLASS_OR_PACKAGE; - else if (parentKind == STATIC_MEMBER_FQ) return CLASS; + ReferenceKind parentKind = ((GrCodeReferenceElementImpl)parent).getKind(forCompletion); + if (parentKind == CLASS) { + return CLASS_OR_PACKAGE; + } + else if (parentKind == STATIC_MEMBER_FQ) { + return CLASS; + } else if (parentKind == CLASS_FQ) return CLASS_OR_PACKAGE_FQ; return parentKind; - } else if (parent instanceof GrPackageDefinition) { + } + else if (parent instanceof GrPackageDefinition) { return PACKAGE_FQ; - } else if (parent instanceof GrDocReferenceElement) { + } + else if (parent instanceof GrDocReferenceElement) { return CLASS_OR_PACKAGE; - } else if (parent instanceof GrImportStatement) { - final GrImportStatement importStatement = (GrImportStatement) parent; + } + else if (parent instanceof GrImportStatement) { + final GrImportStatement importStatement = (GrImportStatement)parent; if (importStatement.isStatic()) { return importStatement.isOnDemand() ? CLASS : STATIC_MEMBER_FQ; } @@ -208,7 +226,7 @@ public class GrCodeReferenceElementImpl extends GrReferenceElementImpl<GrCodeRef if (element instanceof PsiClass) { final PsiElement resolved = resolve(); if (resolved instanceof PsiMethod) { - final PsiMethod method = (PsiMethod) resolved; + final PsiMethod method = (PsiMethod)resolved; if (method.isConstructor() && getManager().areElementsEquivalent(element, method.getContainingClass())) { return true; } @@ -257,7 +275,8 @@ public class GrCodeReferenceElementImpl extends GrReferenceElementImpl<GrCodeRef } private static void feedLookupElements(PsiNamedElement psi, boolean afterNew, Consumer<LookupElement> consumer, PrefixMatcher matcher) { - for (LookupElement element : GroovyCompletionUtil.createLookupElements(new GroovyResolveResultImpl(psi, true), afterNew, matcher, null)) { + for (LookupElement element : GroovyCompletionUtil + .createLookupElements(new GroovyResolveResultImpl(psi, true), afterNew, matcher, null)) { consumer.consume(element); } } @@ -270,7 +289,7 @@ public class GrCodeReferenceElementImpl extends GrReferenceElementImpl<GrCodeRef if (qualifier != null) { final PsiElement resolve = qualifier.resolve(); if (resolve instanceof PsiClass) { - final PsiClass clazz = (PsiClass) resolve; + final PsiClass clazz = (PsiClass)resolve; for (PsiField field : clazz.getFields()) { if (field.hasModifierProperty(PsiModifier.STATIC)) { @@ -336,7 +355,7 @@ public class GrCodeReferenceElementImpl extends GrReferenceElementImpl<GrCodeRef if (qualifier != null) { PsiElement qualifierResolved = qualifier.resolve(); if (qualifierResolved instanceof PsiPackage) { - PsiPackage aPackage = (PsiPackage) qualifierResolved; + PsiPackage aPackage = (PsiPackage)qualifierResolved; for (PsiClass aClass : aPackage.getClasses(getResolveScope())) { feedLookupElements(aClass, afterNew, consumer, matcher); } @@ -345,12 +364,14 @@ public class GrCodeReferenceElementImpl extends GrReferenceElementImpl<GrCodeRef for (PsiPackage subpackage : aPackage.getSubPackages(getResolveScope())) { feedLookupElements(subpackage, afterNew, consumer, matcher); } - } else if (qualifierResolved instanceof PsiClass) { + } + else if (qualifierResolved instanceof PsiClass) { for (PsiClass aClass : ((PsiClass)qualifierResolved).getInnerClasses()) { feedLookupElements(aClass, afterNew, consumer, matcher); } } - } else { + } + else { ResolverProcessor classProcessor = CompletionProcessor.createClassCompletionProcessor(this); processTypeParametersFromUnfinishedMethodOrField(classProcessor); @@ -427,9 +448,10 @@ public class GrCodeReferenceElementImpl extends GrReferenceElementImpl<GrCodeRef final PsiElement element = result.getElement(); if (element instanceof PsiClass) { final PsiSubstitutor substitutor = result.getSubstitutor(); - final PsiSubstitutor newSubstitutor = substitutor.putAll((PsiClass) element, args); + final PsiSubstitutor newSubstitutor = substitutor.putAll((PsiClass)element, args); PsiElement context = result.getCurrentFileResolveContext(); - GroovyResolveResultImpl newResult = new GroovyResolveResultImpl(element, context, null, newSubstitutor, result.isAccessible(), result.isStaticsOK()); + GroovyResolveResultImpl newResult = + new GroovyResolveResultImpl(element, context, null, newSubstitutor, result.isAccessible(), result.isStaticsOK()); results[i] = newResult; if (context instanceof GrImportStatement) { imported.add(newResult); @@ -484,7 +506,7 @@ public class GrCodeReferenceElementImpl extends GrReferenceElementImpl<GrCodeRef if (qualifier != null) { PsiElement qualifierResolved = qualifier.resolve(); if (qualifierResolved instanceof PsiPackage) { - for (final PsiClass aClass : ((PsiPackage) qualifierResolved).getClasses(ref.getResolveScope())) { + for (final PsiClass aClass : ((PsiPackage)qualifierResolved).getClasses(ref.getResolveScope())) { if (refName.equals(aClass.getName())) { boolean isAccessible = PsiUtil.isAccessible(ref, aClass); return new GroovyResolveResult[]{new GroovyResolveResultImpl(aClass, isAccessible)}; @@ -502,7 +524,8 @@ public class GrCodeReferenceElementImpl extends GrReferenceElementImpl<GrCodeRef qualifierResolved.processDeclarations(processor, ResolveState.initial(), null, ref); return processor.getCandidates(); } - } else { + } + else { EnumSet<ClassHint.ResolveKind> kinds = kind == CLASS ? ResolverProcessor.RESOLVE_KINDS_CLASS : ResolverProcessor.RESOLVE_KINDS_CLASS_PACKAGE; ResolverProcessor processor = new ClassResolverProcessor(refName, ref, kinds); @@ -514,8 +537,9 @@ public class GrCodeReferenceElementImpl extends GrReferenceElementImpl<GrCodeRef PsiPackage defaultPackage = JavaPsiFacade.getInstance(ref.getProject()).findPackage(""); if (defaultPackage != null) { for (final PsiPackage subpackage : defaultPackage.getSubPackages(ref.getResolveScope())) { - if (refName.equals(subpackage.getName())) + if (refName.equals(subpackage.getName())) { return new GroovyResolveResult[]{new GroovyResolveResultImpl(subpackage, true)}; + } } } } @@ -529,7 +553,7 @@ public class GrCodeReferenceElementImpl extends GrReferenceElementImpl<GrCodeRef if (qualifier != null) { final PsiElement resolved = qualifier.resolve(); if (resolved instanceof PsiClass) { - final PsiClass clazz = (PsiClass) resolved; + final PsiClass clazz = (PsiClass)resolved; PsiResolveHelper helper = JavaPsiFacade.getInstance(clazz.getProject()).getResolveHelper(); List<GroovyResolveResult> result = new ArrayList<GroovyResolveResult>(); @@ -630,7 +654,7 @@ public class GrCodeReferenceElementImpl extends GrReferenceElementImpl<GrCodeRef public GroovyResolveResult advancedResolve() { ResolveResult[] results = TypeInferenceHelper.getCurrentContext().multiResolve(this, false, RESOLVER); - return results.length == 1 ? (GroovyResolveResult) results[0] : GroovyResolveResult.EMPTY_RESULT; + return results.length == 1 ? (GroovyResolveResult)results[0] : GroovyResolveResult.EMPTY_RESULT; } @NotNull diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/resolve/noncode/MixinMemberContributor.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/resolve/noncode/MixinMemberContributor.java index 3cce1d595535..d8d24a28944e 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/resolve/noncode/MixinMemberContributor.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/resolve/noncode/MixinMemberContributor.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2012 JetBrains s.r.o. + * Copyright 2000-2013 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,6 +20,7 @@ import com.intellij.psi.*; import com.intellij.psi.impl.light.LightMethod; import com.intellij.psi.scope.DelegatingScopeProcessor; import com.intellij.psi.scope.PsiScopeProcessor; +import com.intellij.psi.util.PsiUtil; import com.intellij.util.ObjectUtils; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -45,10 +46,9 @@ public class MixinMemberContributor extends NonCodeMembersContributor { @NotNull PsiScopeProcessor processor, @NotNull final PsiElement place, @NotNull ResolveState state) { - if (!(qualifierType instanceof PsiClassType)) return; if (isInAnnotation(place)) return; - final PsiClassType.ClassResolveResult resolveResult = ((PsiClassType)qualifierType).resolveGenerics(); - final PsiClass aClass = resolveResult.getElement(); + + final PsiClass aClass = PsiUtil.resolveClassInClassTypeOnly(qualifierType); if (aClass == null) return; final PsiModifierList modifierList = aClass.getModifierList(); @@ -91,7 +91,7 @@ public class MixinMemberContributor extends NonCodeMembersContributor { private static List<PsiAnnotation> getAllMixins(PsiModifierList modifierList) { final ArrayList<PsiAnnotation> result = new ArrayList<PsiAnnotation>(); - for (PsiAnnotation annotation : modifierList.getApplicableAnnotations()) { + for (PsiAnnotation annotation : modifierList.getAnnotations()) { if (GroovyCommonClassNames.GROOVY_LANG_MIXIN.equals(annotation.getQualifiedName())) { result.add(annotation); } diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/mvc/MvcFramework.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/mvc/MvcFramework.java index 246321eff735..c9c968814d85 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/mvc/MvcFramework.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/mvc/MvcFramework.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2012 JetBrains s.r.o. + * Copyright 2000-2013 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -45,6 +45,7 @@ import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.JarFileSystem; import com.intellij.openapi.vfs.VfsUtil; +import com.intellij.openapi.vfs.VfsUtilCore; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.*; import com.intellij.psi.search.GlobalSearchScope; @@ -104,7 +105,7 @@ public abstract class MvcFramework { public List<Module> reorderModulesForMvcView(List<Module> modules) { return modules; } - + public abstract String getApplicationDirectoryName(); public void syncSdkAndLibrariesInPluginsModule(@NotNull Module module) { @@ -379,7 +380,7 @@ public abstract class MvcFramework { @NotNull public GeneralCommandLine createCommand(@NotNull Module module, @Nullable String jvmParams, - final boolean forCreation, + boolean forCreation, @NotNull MvcCommand command) throws ExecutionException { final JavaParameters params = createJavaParameters(module, forCreation, false, true, jvmParams, command); addJavaHome(params, module); @@ -388,11 +389,11 @@ public abstract class MvcFramework { final VirtualFile griffonHome = getSdkRoot(module); if (griffonHome != null) { - commandLine.setEnvParams(Collections.singletonMap(getSdkHomePropertyName(), FileUtil.toSystemDependentName(griffonHome.getPath()))); + commandLine.setEnvironment(getSdkHomePropertyName(), FileUtil.toSystemDependentName(griffonHome.getPath())); } final VirtualFile root = findAppRoot(module); - final File ioRoot = root != null ? VfsUtil.virtualToIoFile(root) : new File(module.getModuleFilePath()).getParentFile(); + final File ioRoot = root != null ? VfsUtilCore.virtualToIoFile(root) : new File(module.getModuleFilePath()).getParentFile(); commandLine.setWorkDirectory(forCreation ? ioRoot.getParentFile() : ioRoot); return commandLine; diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/GroovyRefactoringBundle.properties b/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/GroovyRefactoringBundle.properties index 8663a38115da..dd8b9cc181ad 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/GroovyRefactoringBundle.properties +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/GroovyRefactoringBundle.properties @@ -174,3 +174,4 @@ cannot.inline.0.=Cannot inline {0} ref.0.will.not.be.resolved.outside.of.current.context=Reference ''{0}'' will not be resolved outside of current context cannot.rename.property.0=Cannot rename property <bold>''{0}''</bold> which overrides method <bold>''{1}''</bold> cannot.inline.reference.0=Cannot inline reference ''{0}'' +cannot.rename.script.class.to.0=Cannot rename script class ''{0}'' to ''{1}'' diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/changeSignature/GrMethodConflictUtil.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/changeSignature/GrMethodConflictUtil.java index 761c37dd2fc3..49a5c8a39789 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/changeSignature/GrMethodConflictUtil.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/changeSignature/GrMethodConflictUtil.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2012 JetBrains s.r.o. + * Copyright 2000-2013 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -109,7 +109,7 @@ public class GrMethodConflictUtil { String newName = prototype.getName(); PsiMethod[] methods = clazz.findMethodsByName(newName, false); - MultiMap<MethodSignature, PsiMethod> signatures = GrClosureSignatureUtil.findMethodSignatures(methods); + MultiMap<MethodSignature, PsiMethod> signatures = GrClosureSignatureUtil.findRawMethodSignatures(methods, clazz); for (MethodSignature prototypeSignature : prototypeSignatures) { for (PsiMethod method : signatures.get(prototypeSignature)) { if (method != refactoredMethod) { diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/rename/RenameGroovyScriptProcessor.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/rename/RenameGroovyScriptProcessor.java new file mode 100644 index 000000000000..cf5f2717e593 --- /dev/null +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/rename/RenameGroovyScriptProcessor.java @@ -0,0 +1,60 @@ +/* + * Copyright 2000-2013 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.plugins.groovy.refactoring.rename; + +import com.intellij.openapi.util.io.FileUtil; +import com.intellij.openapi.util.text.StringUtil; +import com.intellij.psi.PsiClass; +import com.intellij.psi.PsiElement; +import com.intellij.refactoring.rename.RenamePsiFileProcessor; +import com.intellij.util.containers.MultiMap; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.plugins.groovy.lang.psi.GroovyFile; +import org.jetbrains.plugins.groovy.refactoring.GroovyRefactoringBundle; + +import java.util.Map; + +/** + * @author Max Medvedev + */ +public class RenameGroovyScriptProcessor extends RenamePsiFileProcessor { + @Override + public boolean canProcessElement(@NotNull PsiElement element) { + return element instanceof GroovyFile && ((GroovyFile)element).isScript(); + } + + @Override + public void prepareRenaming(PsiElement element, String newName, Map<PsiElement, String> allRenames) { + if (element instanceof GroovyFile) { + final PsiClass script = ((GroovyFile)element).getScriptClass(); + if (script != null && script.isValid()) { + final String scriptName = FileUtil.getNameWithoutExtension(newName); + if (StringUtil.isJavaIdentifier(scriptName)) { + allRenames.put(script, scriptName); + } + } + } + } + + @Override + public void findExistingNameConflicts(PsiElement element, String newName, MultiMap<PsiElement, String> conflicts) { + final String scriptName = FileUtil.getNameWithoutExtension(newName); + if (!StringUtil.isJavaIdentifier(scriptName)) { + final PsiClass script = ((GroovyFile)element).getScriptClass(); + conflicts.putValue(script, GroovyRefactoringBundle.message("cannot.rename.script.class.to.0", script.getName(), scriptName)); + } + } +} diff --git a/plugins/gradle/src/org/jetbrains/plugins/gradle/action/GradleOutdatedSyncTreeFilterAction.java b/plugins/groovy/test/org/jetbrains/plugins/groovy/intentions/GrCreateConstructorMatchingSuperTest.groovy index cc41ab073df9..8e450c215b8d 100644 --- a/plugins/gradle/src/org/jetbrains/plugins/gradle/action/GradleOutdatedSyncTreeFilterAction.java +++ b/plugins/groovy/test/org/jetbrains/plugins/groovy/intentions/GrCreateConstructorMatchingSuperTest.groovy @@ -13,17 +13,40 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.jetbrains.plugins.gradle.action; - -import org.jetbrains.plugins.gradle.config.GradleColorAndFontDescriptorsProvider; +package org.jetbrains.plugins.groovy.intentions /** - * @author Denis Zhdanov - * @since 1/23/13 9:47 AM + * @author Max Medvedev */ -public class GradleOutdatedSyncTreeFilterAction extends AbstractGradleSyncTreeFilterAction { +class GrCreateConstructorMatchingSuperTest extends GrIntentionTestCase { + GrCreateConstructorMatchingSuperTest() { + super('Create constructor matching super') + } + + public void testSuperWithJavaDoc() throws Exception { + myFixture.addClass('''\ +public class Base { + /** + * my doc + */ + public Base(int x) { + } +} +''') + + doTextTest('''\ +class <caret>Inheritor extends Base { +} +''', '''\ +class Inheritor extends Base { + /** + * my doc + */ + Inheritor(int x) { + super(x) + } +} +''') - public GradleOutdatedSyncTreeFilterAction() { - super(GradleColorAndFontDescriptorsProvider.OUTDATED_ENTITY); } -}
\ No newline at end of file +} diff --git a/plugins/groovy/test/org/jetbrains/plugins/groovy/lang/highlighting/GrAssignabilityTest.groovy b/plugins/groovy/test/org/jetbrains/plugins/groovy/lang/highlighting/GrAssignabilityTest.groovy index 8a8036b876f0..992c5bfccc6b 100644 --- a/plugins/groovy/test/org/jetbrains/plugins/groovy/lang/highlighting/GrAssignabilityTest.groovy +++ b/plugins/groovy/test/org/jetbrains/plugins/groovy/lang/highlighting/GrAssignabilityTest.groovy @@ -678,4 +678,19 @@ class CollectionTypeTest { } ''') } + + void testParameterInitializerWithGenericType() { + testHighlighting('''\ +class PsiElement {} +class Foo extends PsiElement implements I {} + +interface I {} + +def <T extends PsiElement> T foo1(Class<T> x = <warning descr="Cannot assign 'Class<String>' to 'Class<? extends PsiElement>'">String</warning> ) {} +def <T extends PsiElement> T foo2(Class<T> x = PsiElement ) {} +def <T> T foo3(Class<T> x = PsiElement ) {} +def <T extends PsiElement & I> T foo4(Class<T> x = <warning descr="Cannot assign 'Class<PsiElement>' to 'Class<? extends PsiElement>'">PsiElement</warning> ) {} +def <T extends PsiElement & I> T foo5(Class<T> x = Foo ) {} +''') + } } diff --git a/plugins/groovy/test/org/jetbrains/plugins/groovy/lang/highlighting/GroovyHighlightingTest.groovy b/plugins/groovy/test/org/jetbrains/plugins/groovy/lang/highlighting/GroovyHighlightingTest.groovy index 5bacfcfba89c..dcdf59c935ea 100644 --- a/plugins/groovy/test/org/jetbrains/plugins/groovy/lang/highlighting/GroovyHighlightingTest.groovy +++ b/plugins/groovy/test/org/jetbrains/plugins/groovy/lang/highlighting/GroovyHighlightingTest.groovy @@ -1196,4 +1196,70 @@ class Y{} ''') } + void testAnnotationAttribute() { + testHighlighting('''\ +@interface A { + String value() default 'a' + String[] values() default [] +} + + +@A('abc') +def x + +@A(<error descr="Expected ''abc' + 'cde'' to be an inline constant">'abc' + 'cde'</error>) +def y + +class C { + final static String CONST1 = 'ABC' + final static String CONST2 = 'ABC' + 'CDE' + final String CONST3 = 'ABC' +} + +@A(C.CONST1) +def z + +@A(<error descr="Expected ''ABC' + 'CDE'' to be an inline constant">C.CONST2</error>) +def a + +@A(C.CONST3) +def b + +@A(values=['a']) +def c + +@A(values=<error descr="Expected ''a'+'b'' to be an inline constant">['a'+'b']</error>) +def d + +@A(values=[C.CONST1]) +def e + +@A(values=<error descr="Expected ''ABC' + 'CDE'' to be an inline constant">[C.CONST1, C.CONST2]</error>) +def f +''') + } + + void testDuplicateMethodsWithGenerics() { + testHighlighting('''\ +class A<T, E> { + <error descr="Method with signature foo(Object) is already defined in the class 'A'">def foo(T t)</error> {} + <error descr="Method with signature foo(Object) is already defined in the class 'A'">def foo(E e)</error> {} +} + +class B { + <error descr="Method with signature foo(Object) is already defined in the class 'B'">def <T> void foo(T t)</error> {} + <error descr="Method with signature foo(Object) is already defined in the class 'B'">def <E> void foo(E e)</error> {} +} + +class C<T, E> { + <error descr="Method with signature foo(Object) is already defined in the class 'C'">def foo(T t, T t2 = null)</error> {} + <error descr="Method with signature foo(Object) is already defined in the class 'C'">def foo(E e)</error> {} +} + +class D<T, E> { + <error descr="Method with signature foo(Object, Object) is already defined in the class 'D'">def foo(T t, E e)</error> {} + <error descr="Method with signature foo(Object, Object) is already defined in the class 'D'">def foo(E t, T e)</error> {} + def foo(E t) {} +}''') + } }
\ No newline at end of file diff --git a/plugins/groovy/test/org/jetbrains/plugins/groovy/lang/resolve/ResolveClassTest.groovy b/plugins/groovy/test/org/jetbrains/plugins/groovy/lang/resolve/ResolveClassTest.groovy index 59c670e48ab2..52263b499758 100644 --- a/plugins/groovy/test/org/jetbrains/plugins/groovy/lang/resolve/ResolveClassTest.groovy +++ b/plugins/groovy/test/org/jetbrains/plugins/groovy/lang/resolve/ResolveClassTest.groovy @@ -13,13 +13,9 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.jetbrains.plugins.groovy.lang.resolve; +package org.jetbrains.plugins.groovy.lang.resolve - -import com.intellij.psi.JavaPsiFacade -import com.intellij.psi.PsiClass -import com.intellij.psi.PsiElement -import com.intellij.psi.PsiReference +import com.intellij.psi.* import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrAccessorMethod import org.jetbrains.plugins.groovy.util.TestUtils @@ -131,7 +127,7 @@ public class ResolveClassTest extends GroovyResolveTestCase { public void testEnumVsProperty() throws Exception { PsiReference ref = configureByFile("enumVsProperty/Test.groovy"); final PsiElement resolved = ref.resolve(); - assertInstanceOf(resolved, PsiClass.class); + assertInstanceOf(resolved, PsiField.class); } public void testTwoStaticImports() throws Exception { diff --git a/plugins/groovy/test/org/jetbrains/plugins/groovy/lang/resolve/ResolvePropertyTest.groovy b/plugins/groovy/test/org/jetbrains/plugins/groovy/lang/resolve/ResolvePropertyTest.groovy index 566b70c9601b..733b5fc42de9 100644 --- a/plugins/groovy/test/org/jetbrains/plugins/groovy/lang/resolve/ResolvePropertyTest.groovy +++ b/plugins/groovy/test/org/jetbrains/plugins/groovy/lang/resolve/ResolvePropertyTest.groovy @@ -1205,6 +1205,68 @@ print a<caret>a ''', GrBindingVariable) } + void testVarVsPackage1() { + myFixture.addClass('''package p; public class A {}''') + resolveByText('''\ + def p = [A:5] + + print <caret>p.A +''', PsiPackage) + } + + void testVarVsPackage2() { + myFixture.addClass('''package p; public class A {}''') + + resolveByText('''\ + def p = [A:5] + + print <caret>p +''', PsiVariable) + } + + void testVarVsPackage3() { + myFixture.addClass('''package p; public class A {}''') + + resolveByText('''\ + def p = [A:{2}] + + print <caret>p.A() +''', PsiVariable) + } + + void testVarVsPackage4() { + myFixture.addClass('''package p; public class A {public static int foo(){return 2;}}''') + + resolveByText('''\ + def p = [A:[foo:{-2}]] + + print <caret>p.A.foo() +''', PsiVariable) + } + + void testVarVsClass1() { + myFixture.addClass('package p; public class A {public static int foo() {return 1;}}') + + resolveByText('''\ +import p.A + +def A = [a:{-1}] + +print <caret>A +''', PsiVariable) + } + + void testVarVsClass2() { + myFixture.addClass('package p; public class A {public static int foo() {return 1;}}') + + resolveByText('''\ +import p.A + +def A = [a:{-1}] + +print <caret>A.a() +''', PsiVariable) + } } diff --git a/plugins/groovy/test/org/jetbrains/plugins/groovy/refactoring/rename/RenameTest.groovy b/plugins/groovy/test/org/jetbrains/plugins/groovy/refactoring/rename/RenameTest.groovy index e1cefdc28d0c..38d3b3984eab 100644 --- a/plugins/groovy/test/org/jetbrains/plugins/groovy/refactoring/rename/RenameTest.groovy +++ b/plugins/groovy/test/org/jetbrains/plugins/groovy/refactoring/rename/RenameTest.groovy @@ -1,5 +1,5 @@ /* - * Copyright 2000-2012 JetBrains s.r.o. + * Copyright 2000-2013 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -690,4 +690,16 @@ new Inheritor().bar(2) ''') } } + + void testRenameScriptFile() { + myFixture.with { + final PsiFile file = configureByText('Abc.groovy', '''\ +print new Abc() +''') + renameElement(file, 'Abcd.groovy') + checkResult('''\ +print new Abcd() +''') + } + } } diff --git a/plugins/hg4idea/src/org/zmlx/hg4idea/execution/HgCommandExecutor.java b/plugins/hg4idea/src/org/zmlx/hg4idea/execution/HgCommandExecutor.java index 25c3ecc097d7..fe7cd45e2cbc 100644 --- a/plugins/hg4idea/src/org/zmlx/hg4idea/execution/HgCommandExecutor.java +++ b/plugins/hg4idea/src/org/zmlx/hg4idea/execution/HgCommandExecutor.java @@ -145,6 +145,8 @@ public final class HgCommandExecutor { return null; } + logCommand(operation, arguments); + final List<String> cmdLine = new LinkedList<String>(); cmdLine.add(myVcs.getGlobalSettings().getHgExecutable()); if (repo != null) { @@ -214,13 +216,13 @@ public final class HgCommandExecutor { String warnings = warningReceiver.getWarnings(); result.setWarnings(warnings); - log(operation, arguments, result); + logResult(result); return result; } // logging to the Version Control console (without extensions and configs) @SuppressWarnings("UseOfSystemOutOrSystemErr") - private void log(@NotNull String operation, @Nullable List<String> arguments, @NotNull HgCommandResult result) { + private void logCommand(@NotNull String operation, @Nullable List<String> arguments) { if (myProject.isDisposed()) { return; } @@ -244,10 +246,15 @@ public final class HgCommandExecutor { else { LOG.debug(cmdString); } + } + + @SuppressWarnings("UseOfSystemOutOrSystemErr") + private void logResult(@NotNull HgCommandResult result) { + final boolean unitTestMode = ApplicationManager.getApplication().isUnitTestMode(); // log output if needed if (!result.getRawOutput().isEmpty()) { - if (isUnitTestMode) { + if (unitTestMode) { System.out.print(result.getRawOutput() + "\n"); } if (!myIsSilent && myShowOutput) { @@ -261,7 +268,7 @@ public final class HgCommandExecutor { // log error if (!result.getRawError().isEmpty()) { - if (isUnitTestMode) { + if (unitTestMode) { System.out.print(result.getRawError() + "\n"); } if (!myIsSilent) { diff --git a/plugins/javaFX/common-javaFX-plugin/src/org/jetbrains/plugins/javaFX/packaging/AbstractJavaFxPackager.java b/plugins/javaFX/common-javaFX-plugin/src/org/jetbrains/plugins/javaFX/packaging/AbstractJavaFxPackager.java index d4c1d9c75545..7d5f7c25007b 100644 --- a/plugins/javaFX/common-javaFX-plugin/src/org/jetbrains/plugins/javaFX/packaging/AbstractJavaFxPackager.java +++ b/plugins/javaFX/common-javaFX-plugin/src/org/jetbrains/plugins/javaFX/packaging/AbstractJavaFxPackager.java @@ -15,6 +15,7 @@ */ package org.jetbrains.plugins.javaFX.packaging; +import com.intellij.execution.CommandLineUtil; import com.intellij.openapi.application.PathManager; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.util.io.FileUtil; @@ -23,7 +24,10 @@ import com.intellij.util.Base64Converter; import com.intellij.util.PathUtilRt; import com.intellij.util.io.ZipUtil; -import java.io.*; +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.OutputStream; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.List; @@ -97,7 +101,7 @@ public abstract class AbstractJavaFxPackager { buf.append("<target name=\"build artifact\" xmlns:fx=\"javafx:com.sun.javafx.tools.ant\">"); final String artifactFileName = getArtifactRootName(); final String artifactName = FileUtil.getNameWithoutExtension(artifactFileName); - final List<JavaFxAntGenerator.SimpleTag> tags = + final List<JavaFxAntGenerator.SimpleTag> tags = JavaFxAntGenerator.createJarAndDeployTasks(this, artifactFileName, artifactName, tempUnzippedArtifactOutput.getPath()); for (JavaFxAntGenerator.SimpleTag tag : tags) { tag.generate(buf); @@ -228,16 +232,15 @@ public abstract class AbstractJavaFxPackager { registerJavaFxPackagerError(ex.getMessage()); } - protected abstract String prepareParam(String param); - private void addParameter(List<String> commandLine, String param) { + private static void addParameter(List<String> commandLine, String param) { if (!StringUtil.isEmptyOrSpaces(param)) { - commandLine.add(prepareParam(param)); + commandLine.add(param); } } private int startProcess(List<String> commands) { try { - final Process process = new ProcessBuilder(commands).start(); + final Process process = new ProcessBuilder(CommandLineUtil.toCommandLine(commands)).start(); final String message = new String(FileUtil.loadBytes(process.getErrorStream())); if (!StringUtil.isEmptyOrSpaces(message)) { registerJavaFxPackagerError(message); @@ -262,9 +265,9 @@ public abstract class AbstractJavaFxPackager { commands.add("-Dant.home=" + antHome); commands.add("-classpath"); - commands.add(antHome + "/lib/ant.jar" + File.pathSeparator + + commands.add(antHome + "/lib/ant.jar" + File.pathSeparator + antHome + "/lib/ant-launcher.jar" + File.pathSeparator + - javaHome + "/lib/ant-javafx.jar" + File.pathSeparator + + javaHome + "/lib/ant-javafx.jar" + File.pathSeparator + javaHome + "/jre/lib/jfxrt.jar"); commands.add("org.apache.tools.ant.launch.Launcher"); commands.add("-f"); diff --git a/plugins/javaFX/common-javaFX-plugin/src/org/jetbrains/plugins/javaFX/packaging/JavaFxAntGenerator.java b/plugins/javaFX/common-javaFX-plugin/src/org/jetbrains/plugins/javaFX/packaging/JavaFxAntGenerator.java index 0afee28b74e7..5c4e56572558 100644 --- a/plugins/javaFX/common-javaFX-plugin/src/org/jetbrains/plugins/javaFX/packaging/JavaFxAntGenerator.java +++ b/plugins/javaFX/common-javaFX-plugin/src/org/jetbrains/plugins/javaFX/packaging/JavaFxAntGenerator.java @@ -118,7 +118,11 @@ public class JavaFxAntGenerator { if (bundle != JavaFxPackagerConstants.NativeBundles.none) { deployTag.addAttribute(new Pair<String, String>("nativeBundles", bundle.name())); } - + + if (packager.isEnabledSigning()) { + deployTag.add(new SimpleTag("fx:permissions", new Pair<String, String>("elevated", "true"))); + } + deployTag.add(new SimpleTag("fx:application", new Pair<String, String>("refid", appId))); final List<Pair> infoPairs = new ArrayList<Pair>(); diff --git a/plugins/javaFX/javaFX-CE/testSrc/org/jetbrains/plugins/javaFX/packaging/JavaFxAntTaskTest.java b/plugins/javaFX/javaFX-CE/testSrc/org/jetbrains/plugins/javaFX/packaging/JavaFxAntTaskTest.java index ffd274d0f76f..191304c602c6 100644 --- a/plugins/javaFX/javaFX-CE/testSrc/org/jetbrains/plugins/javaFX/packaging/JavaFxAntTaskTest.java +++ b/plugins/javaFX/javaFX-CE/testSrc/org/jetbrains/plugins/javaFX/packaging/JavaFxAntTaskTest.java @@ -32,6 +32,7 @@ public class JavaFxAntTaskTest extends UsefulTestCase{ private static final String PRELOADER_CLASS = "preloaderClass"; private static final String TITLE = "title"; private static final String PRELOADER_JAR = "preloaderJar"; + private static final String SIGNED = "signed"; public void testJarDeployNoInfo() throws Exception { doTest("<fx:fileset id=\"all_but_jarDeployNoInfo\" dir=\"temp\" includes=\"*.jar\">\n" + @@ -93,6 +94,37 @@ public class JavaFxAntTaskTest extends UsefulTestCase{ "</fx:deploy>\n", Collections.singletonMap(TITLE, "My App")); } + public void testJarDeploySigned() throws Exception { + doTest("<fx:fileset id=\"all_but_jarDeploySigned\" dir=\"temp\" includes=\"*.jar\">\n" + + "<exclude name=\"jarDeploySigned.jar\">\n" + + "</exclude>\n" + + "</fx:fileset>\n" + + "<fx:fileset id=\"all_jarDeploySigned\" dir=\"temp\" includes=\"*.jar\">\n" + + "</fx:fileset>\n" + + "<fx:application id=\"jarDeploySigned_id\" name=\"jarDeploySigned\" mainClass=\"Main\">\n" + + "</fx:application>\n" + + "<fx:jar destfile=\"temp" + File.separator + "jarDeploySigned.jar\">\n" + + "<fx:application refid=\"jarDeploySigned_id\">\n" + + "</fx:application>\n" + + "<fileset dir=\"temp\" excludes=\"*.jar\">\n" + + "</fileset>\n" + + "<fx:resources>\n" + + "<fx:fileset refid=\"all_but_jarDeploySigned\">\n" + + "</fx:fileset>\n" + + "</fx:resources>\n" + + "</fx:jar>\n" + + "<fx:deploy width=\"800\" height=\"400\" updatemode=\"background\" outdir=\"temp" + File.separator + "deploy\" outfile=\"jarDeploySigned\">\n" + + "<fx:permissions elevated=\"true\">\n" + + "</fx:permissions>\n" + + "<fx:application refid=\"jarDeploySigned_id\">\n" + + "</fx:application>\n" + + "<fx:resources>\n" + + "<fx:fileset refid=\"all_jarDeploySigned\">\n" + + "</fx:fileset>\n" + + "</fx:resources>\n" + + "</fx:deploy>\n", Collections.singletonMap(SIGNED, "true")); + } + public void testJarDeployPreloader() throws Exception { final HashMap<String, String> options = new HashMap<String, String>(); options.put(PRELOADER_CLASS, "MyPreloader"); @@ -154,7 +186,11 @@ public class JavaFxAntTaskTest extends UsefulTestCase{ if (preloaderJar != null) { packager.setPreloaderJar(preloaderJar); } - + + if (options.containsKey(SIGNED)) { + packager.setSigned(true); + } + final List<JavaFxAntGenerator.SimpleTag> temp = JavaFxAntGenerator .createJarAndDeployTasks(packager, artifactFileName, artifactName, "temp"); final StringBuilder buf = new StringBuilder(); @@ -163,7 +199,7 @@ public class JavaFxAntTaskTest extends UsefulTestCase{ } assertEquals(expected .replaceAll("temp/deploy", "temp\\" + File.separator + "deploy") - .replaceAll("temp/" + artifactFileName, "temp\\" + File.separator + artifactFileName), + .replaceAll("temp/" + artifactFileName, "temp\\" + File.separator + artifactFileName), buf.toString()); } @@ -178,6 +214,7 @@ public class JavaFxAntTaskTest extends UsefulTestCase{ private String myPreloaderClass; private String myPreloaderJar; private boolean myConvertCss2Bin; + private boolean mySigned; private MockJavaFxPackager(String outputPath) { myOutputPath = outputPath; @@ -211,6 +248,10 @@ public class JavaFxAntTaskTest extends UsefulTestCase{ myPreloaderJar = preloaderJar; } + public void setSigned(boolean signed) { + mySigned = signed; + } + @Override protected String getArtifactOutputPath() { return new File(myOutputPath).getParent(); @@ -276,11 +317,6 @@ public class JavaFxAntTaskTest extends UsefulTestCase{ } @Override - protected String prepareParam(String param) { - return param; - } - - @Override public String getKeypass() { return null; } @@ -307,7 +343,7 @@ public class JavaFxAntTaskTest extends UsefulTestCase{ @Override public boolean isEnabledSigning() { - return false; + return mySigned; } @Override diff --git a/plugins/javaFX/javaFX-jps-plugin/src/org/jetbrains/plugins/javaFX/JpsJavaFxArtifactBuildTaskProvider.java b/plugins/javaFX/javaFX-jps-plugin/src/org/jetbrains/plugins/javaFX/JpsJavaFxArtifactBuildTaskProvider.java index 4e509f22e7dd..7e961f1fe821 100644 --- a/plugins/javaFX/javaFX-jps-plugin/src/org/jetbrains/plugins/javaFX/JpsJavaFxArtifactBuildTaskProvider.java +++ b/plugins/javaFX/javaFX-jps-plugin/src/org/jetbrains/plugins/javaFX/JpsJavaFxArtifactBuildTaskProvider.java @@ -1,10 +1,24 @@ +/* + * Copyright 2000-2013 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.jetbrains.plugins.javaFX; import org.jetbrains.annotations.NotNull; import org.jetbrains.jps.builders.artifacts.ArtifactBuildTaskProvider; import org.jetbrains.jps.incremental.BuildTask; import org.jetbrains.jps.incremental.CompileContext; -import org.jetbrains.jps.incremental.ExternalProcessUtil; import org.jetbrains.jps.incremental.ProjectBuildException; import org.jetbrains.jps.incremental.messages.BuildMessage; import org.jetbrains.jps.incremental.messages.CompilerMessage; @@ -145,11 +159,6 @@ public class JpsJavaFxArtifactBuildTaskProvider extends ArtifactBuildTaskProvide } @Override - protected String prepareParam(String param) { - return ExternalProcessUtil.prepareCommand(param); - } - - @Override protected String getHtmlParamFile() { return myProperties.myState.getHtmlParamFile(); } diff --git a/plugins/javaFX/src/org/jetbrains/plugins/javaFX/fxml/JavaFxFileTypeFactory.java b/plugins/javaFX/src/org/jetbrains/plugins/javaFX/fxml/JavaFxFileTypeFactory.java index 81627dbb93b0..27e0093fb04b 100644 --- a/plugins/javaFX/src/org/jetbrains/plugins/javaFX/fxml/JavaFxFileTypeFactory.java +++ b/plugins/javaFX/src/org/jetbrains/plugins/javaFX/fxml/JavaFxFileTypeFactory.java @@ -21,8 +21,11 @@ public class JavaFxFileTypeFactory extends FileTypeFactory { } public static boolean isFxml(@NotNull VirtualFile virtualFile) { - final FileType fileType = FileTypeManager.getInstance().getFileTypeByExtension(FXML_EXTENSION); - return virtualFile.getFileType() == fileType && FXML_EXTENSION.equals(virtualFile.getExtension()); + if (FXML_EXTENSION.equals(virtualFile.getExtension())) { + final FileType fileType = virtualFile.getFileType(); + if (fileType == FileTypeManager.getInstance().getFileTypeByExtension(FXML_EXTENSION) && !fileType.isBinary()) return true; + } + return false; } @Override diff --git a/plugins/javaFX/src/org/jetbrains/plugins/javaFX/packaging/JavaFxArtifactProperties.java b/plugins/javaFX/src/org/jetbrains/plugins/javaFX/packaging/JavaFxArtifactProperties.java index 499ae7786c76..9bfeac0a31f0 100644 --- a/plugins/javaFX/src/org/jetbrains/plugins/javaFX/packaging/JavaFxArtifactProperties.java +++ b/plugins/javaFX/src/org/jetbrains/plugins/javaFX/packaging/JavaFxArtifactProperties.java @@ -15,7 +15,6 @@ */ package org.jetbrains.plugins.javaFX.packaging; -import com.intellij.execution.configurations.GeneralCommandLine; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.compiler.CompileContext; import com.intellij.openapi.compiler.CompilerMessageCategory; @@ -371,15 +370,10 @@ public class JavaFxArtifactProperties extends ArtifactProperties<JavaFxArtifactP } @Override - protected String prepareParam(String param) { - return GeneralCommandLine.prepareCommand(param); - } - - @Override protected String getHtmlParamFile() { return myProperties.getHtmlParamFile(); } - + @Override protected String getParamFile() { return myProperties.getParamFile(); diff --git a/plugins/junit_rt/src/com/intellij/rt/execution/junit/ProcessBuilder.java b/plugins/junit_rt/src/com/intellij/rt/execution/junit/ProcessBuilder.java index e4bde1b145f7..0f008dafc06b 100644 --- a/plugins/junit_rt/src/com/intellij/rt/execution/junit/ProcessBuilder.java +++ b/plugins/junit_rt/src/com/intellij/rt/execution/junit/ProcessBuilder.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2011 JetBrains s.r.o. + * Copyright 2000-2013 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,6 +25,8 @@ import java.util.List; public class ProcessBuilder { public static final boolean isWindows = System.getProperty("os.name").toLowerCase().startsWith("windows"); + private static final String WIN_SHELL_SPECIALS = "&<>()@^|"; + private final List myParameters = new ArrayList(); public void add(final String parameter) { @@ -37,36 +39,55 @@ public class ProcessBuilder { } } + // please keep an implementation in sync with [util] CommandLineUtil.toCommandLine() public Process createProcess() throws IOException { if (myParameters.size() < 1) { throw new IllegalArgumentException("Executable name not specified"); } - final String[] command = new String[myParameters.size()]; - for (int i = 0; i < myParameters.size(); i++) { - command[i] = prepareCommand(myParameters.get(i).toString()); - } + String command = myParameters.get(0).toString(); + boolean winShell = isWindows && + ("cmd".equalsIgnoreCase(command) || "cmd.exe".equalsIgnoreCase(command)) && + myParameters.size() > 1 && "/c".equalsIgnoreCase(myParameters.get(0).toString()); - return Runtime.getRuntime().exec(command); - } + String[] commandLine = new String[myParameters.size()]; + commandLine[0] = command; + + for (int i = 1; i < myParameters.size(); i++) { + String parameter = myParameters.get(i).toString(); + + if (isWindows) { + int pos = parameter.indexOf('\"'); + if (pos >= 0) { + StringBuffer buffer = new StringBuffer(parameter); + do { + buffer.insert(pos, '\\'); + pos += 2; + } + while ((pos = parameter.indexOf('\"', pos)) >= 0); + parameter = buffer.toString(); + } + else if (parameter.length() == 0) { + parameter = "\"\""; + } - // please keep in sync with GeneralCommandLine.prepareCommand() - private static String prepareCommand(String parameter) { - if (isWindows) { - int pos = parameter.indexOf('\"'); - if (pos >= 0) { - final StringBuffer buffer = new StringBuffer(parameter); - do { - buffer.insert(pos, '\\'); - pos += 2; + if (winShell && containsAnyChar(parameter, WIN_SHELL_SPECIALS)) { + parameter = '"' + parameter + '"'; } - while ((pos = parameter.indexOf('\"', pos)) >= 0); - parameter = buffer.toString(); } - else if (parameter.length() == 0) { - parameter = "\"\""; + + commandLine[i] = parameter; + } + + return Runtime.getRuntime().exec(commandLine); + } + + private static boolean containsAnyChar(String value, String chars) { + for (int i = 0; i < value.length(); i++) { + if (chars.indexOf(value.charAt(i)) >= 0) { + return true; } } - return parameter; + return false; } } diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/tasks/actions/AssignShortcutAction.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/tasks/actions/AssignShortcutAction.java index 677286ea4122..1fb5d6afee79 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/tasks/actions/AssignShortcutAction.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/tasks/actions/AssignShortcutAction.java @@ -54,7 +54,11 @@ public class AssignShortcutAction extends MavenAction { if (project == null) return null; final List<String> goals = MavenDataKeys.MAVEN_GOALS.getData(context); - String goal = (goals == null || goals.size() != 1) ? null : goals.get(0); + if (goals == null || goals.size() != 1) { + return null; + } + + String goal = goals.get(0); return getShortcutsManager(context).getActionId(project.getPath(), goal); } diff --git a/plugins/maven/src/test/java/org/jetbrains/idea/maven/MavenImportingTestCase.java b/plugins/maven/src/test/java/org/jetbrains/idea/maven/MavenImportingTestCase.java index ab77fe477b3c..8a4f802a7e88 100644 --- a/plugins/maven/src/test/java/org/jetbrains/idea/maven/MavenImportingTestCase.java +++ b/plugins/maven/src/test/java/org/jetbrains/idea/maven/MavenImportingTestCase.java @@ -33,7 +33,6 @@ import com.intellij.openapi.module.ModuleManager; import com.intellij.openapi.progress.EmptyProgressIndicator; import com.intellij.openapi.projectRoots.Sdk; import com.intellij.openapi.projectRoots.impl.JavaAwareProjectJdkTableImpl; -import com.intellij.openapi.projectRoots.impl.JavaSdkImpl; import com.intellij.openapi.roots.*; import com.intellij.openapi.roots.impl.libraries.ProjectLibraryTable; import com.intellij.openapi.roots.libraries.Library; @@ -45,7 +44,6 @@ import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VfsUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.testFramework.IdeaTestUtil; -import com.intellij.util.ArrayUtil; import com.intellij.util.PathUtil; import com.intellij.util.concurrency.Semaphore; import com.intellij.util.ui.UIUtil; @@ -116,7 +114,7 @@ public abstract class MavenImportingTestCase extends MavenTestCase { expectedRoots[i] = VfsUtil.pathToUrl(expectedRoots[i]); } - assertUnorderedElementsAreEqual(actual, expectedRoots); + assertUnorderedPathsAreEqual(actual, Arrays.asList(expectedRoots)); } protected void assertSources(String moduleName, String... expectedSources) { @@ -155,7 +153,7 @@ public abstract class MavenImportingTestCase extends MavenTestCase { actual.add(folderUrl); } - assertUnorderedElementsAreEqual(actual, expected); + assertUnorderedPathsAreEqual(actual, Arrays.asList(expected)); } protected void assertModuleOutput(String moduleName, String output, String testOutput) { @@ -211,9 +209,9 @@ public abstract class MavenImportingTestCase extends MavenTestCase { private void assertModuleLibDepPath(LibraryOrderEntry lib, OrderRootType type, List<String> paths) { if (paths == null) return; - assertUnorderedElementsAreEqual(lib.getRootUrls(type), ArrayUtil.toStringArray(paths)); + assertUnorderedPathsAreEqual(Arrays.asList(lib.getRootUrls(type)), paths); // also check the library because it may contain slight different set of urls (e.g. with duplicates) - assertUnorderedElementsAreEqual(lib.getLibrary().getUrls(type), ArrayUtil.toStringArray(paths)); + assertUnorderedPathsAreEqual(Arrays.asList(lib.getLibrary().getUrls(type)), paths); } protected void assertModuleLibDepScope(String moduleName, String depName, DependencyScope scope) { diff --git a/plugins/maven/src/test/java/org/jetbrains/idea/maven/MavenTestCase.java b/plugins/maven/src/test/java/org/jetbrains/idea/maven/MavenTestCase.java index dcf900e1f087..ef8e43f78829 100644 --- a/plugins/maven/src/test/java/org/jetbrains/idea/maven/MavenTestCase.java +++ b/plugins/maven/src/test/java/org/jetbrains/idea/maven/MavenTestCase.java @@ -35,6 +35,7 @@ import com.intellij.testFramework.UsefulTestCase; import com.intellij.testFramework.fixtures.IdeaProjectTestFixture; import com.intellij.testFramework.fixtures.IdeaTestFixtureFactory; import com.intellij.util.ui.UIUtil; +import gnu.trove.THashSet; import org.intellij.lang.annotations.Language; import org.jetbrains.annotations.NonNls; import org.jetbrains.idea.maven.indices.MavenIndicesManager; @@ -497,6 +498,9 @@ public abstract class MavenTestCase extends UsefulTestCase { protected static <T> void assertUnorderedElementsAreEqual(Collection<T> actual, Collection<T> expected) { assertEquals(new HashSet<T>(expected), new HashSet<T>(actual)); } + protected static void assertUnorderedPathsAreEqual(Collection<String> actual, Collection<String> expected) { + assertEquals(new THashSet<String>(expected, FileUtil.PATH_HASHING_STRATEGY), new THashSet<String>(actual, FileUtil.PATH_HASHING_STRATEGY)); + } protected static <T> void assertUnorderedElementsAreEqual(T[] actual, T... expected) { assertUnorderedElementsAreEqual(Arrays.asList(actual), expected); diff --git a/plugins/maven/src/test/java/org/jetbrains/idea/maven/execution/MavenResolveToWorkspaceTest.java b/plugins/maven/src/test/java/org/jetbrains/idea/maven/execution/MavenResolveToWorkspaceTest.java index 3cfb1a4ca46d..4cf5b79a615b 100644 --- a/plugins/maven/src/test/java/org/jetbrains/idea/maven/execution/MavenResolveToWorkspaceTest.java +++ b/plugins/maven/src/test/java/org/jetbrains/idea/maven/execution/MavenResolveToWorkspaceTest.java @@ -35,9 +35,9 @@ import java.util.Properties; /** * @author Sergey Evdokimov */ -public class MavenResolveToWorkspaceTest extends MavenImportingTestCase { +public abstract class MavenResolveToWorkspaceTest extends MavenImportingTestCase { - public void _testIgnoredProject() throws Exception { + public void testIgnoredProject() throws Exception { createProjectPom("<groupId>test</groupId>" + "<artifactId>project</artifactId>" + "<version>1</version>" + diff --git a/plugins/maven/src/test/java/org/jetbrains/idea/maven/importing/FacetImporterTestCase.java b/plugins/maven/src/test/java/org/jetbrains/idea/maven/importing/FacetImporterTestCase.java index 0c11426e5a1f..31ae08162462 100644 --- a/plugins/maven/src/test/java/org/jetbrains/idea/maven/importing/FacetImporterTestCase.java +++ b/plugins/maven/src/test/java/org/jetbrains/idea/maven/importing/FacetImporterTestCase.java @@ -3,8 +3,7 @@ package org.jetbrains.idea.maven.importing; import com.intellij.facet.Facet; import com.intellij.facet.FacetManager; import com.intellij.facet.FacetType; -import com.intellij.openapi.vfs.VfsUtil; -import com.intellij.util.ArrayUtil; +import com.intellij.openapi.vfs.VfsUtilCore; import org.jetbrains.idea.maven.MavenImportingTestCase; import java.util.ArrayList; @@ -25,11 +24,11 @@ public abstract class FacetImporterTestCase<FACET_TYPE extends Facet, FACET_TYPE List<String> expectedRootUrls = new ArrayList<String>(); for (String r : roots) { - String url = VfsUtil.pathToUrl(getProjectPath() + "/" + r); + String url = VfsUtilCore.pathToUrl(getProjectPath() + "/" + r); expectedRootUrls.add(url); } - assertUnorderedElementsAreEqual(actualRoots, ArrayUtil.toStringArray(expectedRootUrls)); + assertUnorderedPathsAreEqual(actualRoots, expectedRootUrls); } protected FACET_TYPE getFacet(String module) { diff --git a/plugins/maven/src/test/java/org/jetbrains/idea/maven/importing/GroovyImporterTest.java b/plugins/maven/src/test/java/org/jetbrains/idea/maven/importing/GroovyImporterTest.java index be05c84b78bc..9cf632dc956d 100644 --- a/plugins/maven/src/test/java/org/jetbrains/idea/maven/importing/GroovyImporterTest.java +++ b/plugins/maven/src/test/java/org/jetbrains/idea/maven/importing/GroovyImporterTest.java @@ -8,11 +8,10 @@ import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.roots.OrderRootType; import com.intellij.openapi.roots.libraries.Library; import org.jetbrains.idea.maven.MavenImportingTestCase; -import org.jetbrains.idea.maven.importing.MavenDefaultModifiableModelsProvider; -import org.jetbrains.idea.maven.importing.MavenRootModelAdapter; import org.jetbrains.plugins.groovy.config.GroovyConfigUtils; import java.io.File; +import java.util.Arrays; public class GroovyImporterTest extends MavenImportingTestCase { @Override @@ -67,9 +66,9 @@ public class GroovyImporterTest extends MavenImportingTestCase { Library[] libraries = GroovyConfigUtils.getInstance().getSDKLibrariesByModule(getModule("project")); assertTrue("unexpected groovy libs configuration: " + libraries.length, libraries.length > 0); Library library = libraries[0]; - assertUnorderedElementsAreEqual( - library.getUrls(OrderRootType.CLASSES), - "jar://" + getRepositoryPath() + "/org/codehaus/groovy/groovy-all-minimal/1.5.6/groovy-all-minimal-1.5.6.jar!/"); + assertUnorderedPathsAreEqual( + Arrays.asList(library.getUrls(OrderRootType.CLASSES)), + Arrays.asList("jar://" + getRepositoryPath() + "/org/codehaus/groovy/groovy-all-minimal/1.5.6/groovy-all-minimal-1.5.6.jar!/")); } public void testAddingGroovySpecificSources() throws Exception { diff --git a/plugins/maven/src/test/java/org/jetbrains/idea/maven/importing/ReimportingTest.java b/plugins/maven/src/test/java/org/jetbrains/idea/maven/importing/ReimportingTest.java index 7ae1ec738bae..44d5f0dfd683 100644 --- a/plugins/maven/src/test/java/org/jetbrains/idea/maven/importing/ReimportingTest.java +++ b/plugins/maven/src/test/java/org/jetbrains/idea/maven/importing/ReimportingTest.java @@ -224,10 +224,10 @@ public class ReimportingTest extends MavenImportingTestCase { configConfirmationForYesAnswer(); // will ask about absent modules importProjectWithProfiles("profile1"); - assertModules("project", "m1"); + assertModules("project", "m1", "m2"); importProjectWithProfiles("profile2"); - assertModules("project", "m2"); + assertModules("project", "m1", "m2"); } public void testChangingDependencyTypeToTestJar() throws Exception { diff --git a/plugins/maven/src/test/java/org/jetbrains/idea/maven/project/MavenProjectsManagerTest.java b/plugins/maven/src/test/java/org/jetbrains/idea/maven/project/MavenProjectsManagerTest.java index cee2ec718491..ac9b17abe4c8 100644 --- a/plugins/maven/src/test/java/org/jetbrains/idea/maven/project/MavenProjectsManagerTest.java +++ b/plugins/maven/src/test/java/org/jetbrains/idea/maven/project/MavenProjectsManagerTest.java @@ -371,8 +371,8 @@ public class MavenProjectsManagerTest extends MavenImportingTestCase { MavenProject parentNode = roots.get(0); MavenProject childNode = myProjectsTree.getModules(roots.get(0)).get(0); - assertUnorderedElementsAreEqual(parentNode.getSources(), FileUtil.toSystemDependentName(getProjectPath() + "/value1")); - assertUnorderedElementsAreEqual(childNode.getSources(), FileUtil.toSystemDependentName(getProjectPath() + "/m/value1")); + assertUnorderedPathsAreEqual(parentNode.getSources(), Arrays.asList(FileUtil.toSystemDependentName(getProjectPath() + "/value1"))); + assertUnorderedPathsAreEqual(childNode.getSources(), Arrays.asList(FileUtil.toSystemDependentName(getProjectPath() + "/m/value1"))); updateSettingsXml("<profiles>" + " <profile>" + @@ -387,14 +387,14 @@ public class MavenProjectsManagerTest extends MavenImportingTestCase { "</profiles>"); waitForReadingCompletion(); - assertUnorderedElementsAreEqual(parentNode.getSources(), FileUtil.toSystemDependentName(getProjectPath() + "/value2")); - assertUnorderedElementsAreEqual(childNode.getSources(), FileUtil.toSystemDependentName(getProjectPath() + "/m/value2")); + assertUnorderedPathsAreEqual(parentNode.getSources(), Arrays.asList(FileUtil.toSystemDependentName(getProjectPath() + "/value2"))); + assertUnorderedPathsAreEqual(childNode.getSources(), Arrays.asList(FileUtil.toSystemDependentName(getProjectPath() + "/m/value2"))); deleteSettingsXml(); waitForReadingCompletion(); - assertUnorderedElementsAreEqual(parentNode.getSources(), FileUtil.toSystemDependentName(getProjectPath() + "/${prop}")); - assertUnorderedElementsAreEqual(childNode.getSources(), FileUtil.toSystemDependentName(getProjectPath() + "/m/${prop}")); + assertUnorderedPathsAreEqual(parentNode.getSources(), Arrays.asList(FileUtil.toSystemDependentName(getProjectPath() + "/${prop}"))); + assertUnorderedPathsAreEqual(childNode.getSources(), Arrays.asList(FileUtil.toSystemDependentName(getProjectPath() + "/m/${prop}"))); updateSettingsXml("<profiles>" + " <profile>" + @@ -409,8 +409,8 @@ public class MavenProjectsManagerTest extends MavenImportingTestCase { "</profiles>"); waitForReadingCompletion(); - assertUnorderedElementsAreEqual(parentNode.getSources(), FileUtil.toSystemDependentName(getProjectPath() + "/value2")); - assertUnorderedElementsAreEqual(childNode.getSources(), FileUtil.toSystemDependentName(getProjectPath() + "/m/value2")); + assertUnorderedPathsAreEqual(parentNode.getSources(), Arrays.asList(FileUtil.toSystemDependentName(getProjectPath() + "/value2"))); + assertUnorderedPathsAreEqual(childNode.getSources(), Arrays.asList(FileUtil.toSystemDependentName(getProjectPath() + "/m/value2"))); } public void testUpdatingProjectsWhenSettingsXmlLocationIsChanged() throws Exception { @@ -461,20 +461,20 @@ public class MavenProjectsManagerTest extends MavenImportingTestCase { MavenProject parentNode = roots.get(0); MavenProject childNode = myProjectsTree.getModules(roots.get(0)).get(0); - assertUnorderedElementsAreEqual(parentNode.getSources(), FileUtil.toSystemDependentName(getProjectPath() + "/value1")); - assertUnorderedElementsAreEqual(childNode.getSources(), FileUtil.toSystemDependentName(getProjectPath() + "/m/value1")); + assertUnorderedPathsAreEqual(parentNode.getSources(), Arrays.asList(FileUtil.toSystemDependentName(getProjectPath() + "/value1"))); + assertUnorderedPathsAreEqual(childNode.getSources(), Arrays.asList(FileUtil.toSystemDependentName(getProjectPath() + "/m/value1"))); getMavenGeneralSettings().setUserSettingsFile(""); waitForReadingCompletion(); - assertUnorderedElementsAreEqual(parentNode.getSources(), FileUtil.toSystemDependentName(getProjectPath() + "/${prop}")); - assertUnorderedElementsAreEqual(childNode.getSources(), FileUtil.toSystemDependentName(getProjectPath() + "/m/${prop}")); + assertUnorderedPathsAreEqual(parentNode.getSources(), Arrays.asList(FileUtil.toSystemDependentName(getProjectPath() + "/${prop}"))); + assertUnorderedPathsAreEqual(childNode.getSources(), Arrays.asList(FileUtil.toSystemDependentName(getProjectPath() + "/m/${prop}"))); getMavenGeneralSettings().setUserSettingsFile(new File(myDir, "settings.xml").getPath()); waitForReadingCompletion(); - assertUnorderedElementsAreEqual(parentNode.getSources(), FileUtil.toSystemDependentName(getProjectPath() + "/value1")); - assertUnorderedElementsAreEqual(childNode.getSources(), FileUtil.toSystemDependentName(getProjectPath() + "/m/value1")); + assertUnorderedPathsAreEqual(parentNode.getSources(), Arrays.asList(FileUtil.toSystemDependentName(getProjectPath() + "/value1"))); + assertUnorderedPathsAreEqual(childNode.getSources(), Arrays.asList(FileUtil.toSystemDependentName(getProjectPath() + "/m/value1"))); } public void testUpdatingProjectsOnSettingsXmlCreationAndDeletion() throws Exception { @@ -586,8 +586,8 @@ public class MavenProjectsManagerTest extends MavenImportingTestCase { MavenProject parentNode = roots.get(0); MavenProject childNode = myProjectsTree.getModules(roots.get(0)).get(0); - assertUnorderedElementsAreEqual(parentNode.getSources(), FileUtil.toSystemDependentName(getProjectPath() + "/value1")); - assertUnorderedElementsAreEqual(childNode.getSources(), FileUtil.toSystemDependentName(getProjectPath() + "/m/value1")); + assertUnorderedPathsAreEqual(parentNode.getSources(), Arrays.asList(FileUtil.toSystemDependentName(getProjectPath() + "/value1"))); + assertUnorderedPathsAreEqual(childNode.getSources(), Arrays.asList(FileUtil.toSystemDependentName(getProjectPath() + "/m/value1"))); createProfilesXmlOldStyle("<profile>" + " <id>one</id>" + @@ -600,14 +600,14 @@ public class MavenProjectsManagerTest extends MavenImportingTestCase { "</profile>"); waitForReadingCompletion(); - assertUnorderedElementsAreEqual(parentNode.getSources(), FileUtil.toSystemDependentName(getProjectPath() + "/value2")); - assertUnorderedElementsAreEqual(childNode.getSources(), FileUtil.toSystemDependentName(getProjectPath() + "/m/value2")); + assertUnorderedPathsAreEqual(parentNode.getSources(), Arrays.asList(FileUtil.toSystemDependentName(getProjectPath() + "/value2"))); + assertUnorderedPathsAreEqual(childNode.getSources(), Arrays.asList(FileUtil.toSystemDependentName(getProjectPath() + "/m/value2"))); deleteProfilesXml(); waitForReadingCompletion(); - assertUnorderedElementsAreEqual(parentNode.getSources(), FileUtil.toSystemDependentName(getProjectPath() + "/${prop}")); - assertUnorderedElementsAreEqual(childNode.getSources(), FileUtil.toSystemDependentName(getProjectPath() + "/m/${prop}")); + assertUnorderedPathsAreEqual(parentNode.getSources(), Arrays.asList(FileUtil.toSystemDependentName(getProjectPath() + "/${prop}"))); + assertUnorderedPathsAreEqual(childNode.getSources(), Arrays.asList(FileUtil.toSystemDependentName(getProjectPath() + "/m/${prop}"))); createProfilesXmlOldStyle("<profile>" + " <id>one</id>" + @@ -620,8 +620,8 @@ public class MavenProjectsManagerTest extends MavenImportingTestCase { "</profile>"); waitForReadingCompletion(); - assertUnorderedElementsAreEqual(parentNode.getSources(), FileUtil.toSystemDependentName(getProjectPath() + "/value2")); - assertUnorderedElementsAreEqual(childNode.getSources(), FileUtil.toSystemDependentName(getProjectPath() + "/m/value2")); + assertUnorderedPathsAreEqual(parentNode.getSources(), Arrays.asList(FileUtil.toSystemDependentName(getProjectPath() + "/value2"))); + assertUnorderedPathsAreEqual(childNode.getSources(), Arrays.asList(FileUtil.toSystemDependentName(getProjectPath() + "/m/value2"))); } public void testHandlingDirectoryWithPomFileDeletion() throws Exception { @@ -691,9 +691,9 @@ public class MavenProjectsManagerTest extends MavenImportingTestCase { myProjectsManager.setIgnoredFilesPatterns(Arrays.asList("*.xxx")); state = myProjectsManager.getState(); - assertUnorderedElementsAreEqual(state.originalFiles, p1.getPath(), p2.getPath()); + assertUnorderedPathsAreEqual(state.originalFiles, Arrays.asList(p1.getPath(), p2.getPath())); assertUnorderedElementsAreEqual(MavenWorkspaceSettingsComponent.getInstance(myProject).getState().enabledProfiles, "one", "two"); - assertUnorderedElementsAreEqual(state.ignoredFiles, p1.getPath()); + assertUnorderedPathsAreEqual(state.ignoredFiles, Arrays.asList(p1.getPath())); assertUnorderedElementsAreEqual(state.ignoredPathMasks, "*.xxx"); MavenProjectsManagerState newState = new MavenProjectsManagerState(); @@ -705,10 +705,10 @@ public class MavenProjectsManagerTest extends MavenImportingTestCase { myProjectsManager.loadState(newState); - assertUnorderedElementsAreEqual(myProjectsManager.getProjectsTreeForTests().getManagedFilesPaths(), - p1.getPath(), p3.getPath()); + assertUnorderedPathsAreEqual(myProjectsManager.getProjectsTreeForTests().getManagedFilesPaths(), + Arrays.asList(p1.getPath(), p3.getPath())); assertUnorderedElementsAreEqual(myProjectsManager.getExplicitProfiles(), "three"); - assertUnorderedElementsAreEqual(myProjectsManager.getIgnoredFilesPaths(), p1.getPath()); + assertUnorderedPathsAreEqual(myProjectsManager.getIgnoredFilesPaths(), Arrays.asList(p1.getPath())); assertUnorderedElementsAreEqual(myProjectsManager.getIgnoredFilesPatterns(), "*.zzz"); waitForReadingCompletion(); diff --git a/plugins/maven/src/test/java/org/jetbrains/idea/maven/project/MavenProjectsTreeReadingTest.java b/plugins/maven/src/test/java/org/jetbrains/idea/maven/project/MavenProjectsTreeReadingTest.java index 56b53e94d151..2f118ed2b79f 100644 --- a/plugins/maven/src/test/java/org/jetbrains/idea/maven/project/MavenProjectsTreeReadingTest.java +++ b/plugins/maven/src/test/java/org/jetbrains/idea/maven/project/MavenProjectsTreeReadingTest.java @@ -429,7 +429,7 @@ public class MavenProjectsTreeReadingTest extends MavenProjectsTreeTestCase { l.log = ""; } - public void testUpdatingModelWithNewProfiles() throws Exception { + public void _testUpdatingModelWithNewProfiles() throws Exception { createProjectPom("<groupId>test</groupId>" + "<artifactId>project</artifactId>" + "<version>1</version>" + @@ -466,17 +466,9 @@ public class MavenProjectsTreeReadingTest extends MavenProjectsTreeTestCase { assertEquals(1, roots.size()); assertEquals(myProjectPom, roots.get(0).getFile()); - assertEquals(1, myTree.getModules(roots.get(0)).size()); + assertEquals(2, myTree.getModules(roots.get(0)).size()); assertEquals(m1, myTree.getModules(roots.get(0)).get(0).getFile()); - - updateAll(Collections.singletonList("two"), myProjectPom); - - roots = myTree.getRootProjects(); - assertEquals(1, roots.size()); - assertEquals(myProjectPom, roots.get(0).getFile()); - - assertEquals(1, myTree.getModules(roots.get(0)).size()); - assertEquals(m2, myTree.getModules(roots.get(0)).get(0).getFile()); + assertEquals(m2, myTree.getModules(roots.get(0)).get(1).getFile()); } public void testUpdatingParticularProject() throws Exception { @@ -1602,13 +1594,13 @@ public class MavenProjectsTreeReadingTest extends MavenProjectsTreeTestCase { MavenProject parentNode = roots.get(0); MavenProject childNode = myTree.getModules(roots.get(0)).get(0); - assertUnorderedElementsAreEqual(parentNode.getSources(), FileUtil.toSystemDependentName(getProjectPath() + "/value1")); - assertUnorderedElementsAreEqual(childNode.getSources(), FileUtil.toSystemDependentName(getProjectPath() + "/m/value1")); + assertUnorderedPathsAreEqual(parentNode.getSources(), Arrays.asList(FileUtil.toSystemDependentName(getProjectPath() + "/value1"))); + assertUnorderedPathsAreEqual(childNode.getSources(), Arrays.asList(FileUtil.toSystemDependentName(getProjectPath() + "/m/value1"))); updateAll(Arrays.asList("two"), myProjectPom); - assertUnorderedElementsAreEqual(parentNode.getSources(), FileUtil.toSystemDependentName(getProjectPath() + "/value2")); - assertUnorderedElementsAreEqual(childNode.getSources(), FileUtil.toSystemDependentName(getProjectPath() + "/m/value2")); + assertUnorderedPathsAreEqual(parentNode.getSources(), Arrays.asList(FileUtil.toSystemDependentName(getProjectPath() + "/value2"))); + assertUnorderedPathsAreEqual(childNode.getSources(), Arrays.asList(FileUtil.toSystemDependentName(getProjectPath() + "/m/value2"))); } public void testUpdatingModelWhenProfilesXmlChange() throws Exception { @@ -1636,7 +1628,7 @@ public class MavenProjectsTreeReadingTest extends MavenProjectsTreeTestCase { List<MavenProject> roots = myTree.getRootProjects(); MavenProject project = roots.get(0); - assertUnorderedElementsAreEqual(project.getSources(), FileUtil.toSystemDependentName(getProjectPath() + "/value1")); + assertUnorderedPathsAreEqual(project.getSources(), Arrays.asList(FileUtil.toSystemDependentName(getProjectPath() + "/value1"))); createProfilesXmlOldStyle("<profile>" + " <id>one</id>" + @@ -1650,7 +1642,7 @@ public class MavenProjectsTreeReadingTest extends MavenProjectsTreeTestCase { updateAll(myProjectPom); - assertUnorderedElementsAreEqual(project.getSources(), FileUtil.toSystemDependentName(getProjectPath() + "/value2")); + assertUnorderedPathsAreEqual(project.getSources(), Arrays.asList(FileUtil.toSystemDependentName(getProjectPath() + "/value2"))); } public void testUpdatingModelWhenParentProfilesXmlChange() throws Exception { @@ -1691,7 +1683,7 @@ public class MavenProjectsTreeReadingTest extends MavenProjectsTreeTestCase { List<MavenProject> roots = myTree.getRootProjects(); MavenProject childProject = roots.get(1); - assertUnorderedElementsAreEqual(childProject.getSources(), FileUtil.toSystemDependentName(getProjectPath() + "/m/value1")); + assertUnorderedPathsAreEqual(childProject.getSources(), Arrays.asList(FileUtil.toSystemDependentName(getProjectPath() + "/m/value1"))); createProfilesXmlOldStyle("parent", "<profile>" + @@ -1705,7 +1697,7 @@ public class MavenProjectsTreeReadingTest extends MavenProjectsTreeTestCase { "</profile>"); update(parent); - assertUnorderedElementsAreEqual(childProject.getSources(), FileUtil.toSystemDependentName(getProjectPath() + "/m/value2")); + assertUnorderedPathsAreEqual(childProject.getSources(), Arrays.asList(FileUtil.toSystemDependentName(getProjectPath() + "/m/value2"))); } public void testUpdatingModelWhenParentProfilesXmlChangeAndItIsAModuleAlso() throws Exception { @@ -1746,7 +1738,7 @@ public class MavenProjectsTreeReadingTest extends MavenProjectsTreeTestCase { updateAll(myProjectPom); MavenProject childNode = myTree.getModules(myTree.getRootProjects().get(0)).get(0); - assertUnorderedElementsAreEqual(childNode.getSources(), FileUtil.toSystemDependentName(getProjectPath() + "/m/value1")); + assertUnorderedPathsAreEqual(childNode.getSources(), Arrays.asList(FileUtil.toSystemDependentName(getProjectPath() + "/m/value1"))); createProfilesXmlOldStyle("<profile>" + " <id>one</id>" + @@ -1759,7 +1751,7 @@ public class MavenProjectsTreeReadingTest extends MavenProjectsTreeTestCase { "</profile>"); updateAll(myProjectPom); - assertUnorderedElementsAreEqual(childNode.getSources(), FileUtil.toSystemDependentName(getProjectPath() + "/m/value2")); + assertUnorderedPathsAreEqual(childNode.getSources(), Arrays.asList(FileUtil.toSystemDependentName(getProjectPath() + "/m/value2"))); } public void testDoNotUpdateModelWhenAggregatorProfilesXmlChange() throws Exception { diff --git a/plugins/svn4idea/lib/svnkit-javahl.jar b/plugins/svn4idea/lib/svnkit-javahl.jar Binary files differindex 265fda0bb963..5dc349cf60a9 100644 --- a/plugins/svn4idea/lib/svnkit-javahl.jar +++ b/plugins/svn4idea/lib/svnkit-javahl.jar diff --git a/plugins/svn4idea/lib/svnkit-javahl16.zip b/plugins/svn4idea/lib/svnkit-javahl16.zip Binary files differindex da9b8269cbb5..563f5930e74d 100644 --- a/plugins/svn4idea/lib/svnkit-javahl16.zip +++ b/plugins/svn4idea/lib/svnkit-javahl16.zip diff --git a/plugins/svn4idea/lib/svnkit.jar b/plugins/svn4idea/lib/svnkit.jar Binary files differindex 46a3ab556976..c01f43040416 100644 --- a/plugins/svn4idea/lib/svnkit.jar +++ b/plugins/svn4idea/lib/svnkit.jar diff --git a/plugins/svn4idea/lib/svnkitsrc.zip b/plugins/svn4idea/lib/svnkitsrc.zip Binary files differindex ab1a19f594c0..81c259467896 100644 --- a/plugins/svn4idea/lib/svnkitsrc.zip +++ b/plugins/svn4idea/lib/svnkitsrc.zip diff --git a/plugins/svn4idea/src/org/jetbrains/idea/svn/SvnConfiguration.java b/plugins/svn4idea/src/org/jetbrains/idea/svn/SvnConfiguration.java index 66132f516be6..9549ce5b506f 100644 --- a/plugins/svn4idea/src/org/jetbrains/idea/svn/SvnConfiguration.java +++ b/plugins/svn4idea/src/org/jetbrains/idea/svn/SvnConfiguration.java @@ -181,10 +181,9 @@ public class SvnConfiguration implements PersistentStateComponent<Element> { String groupName = SvnAuthenticationManager.getGroupForHost(host, configFile); if (StringUtil.isEmptyOrSpaces(groupName)) { - groupName = StringUtil.replace(host, " ", "_"); + groupName = host; final Map<String,ProxyGroup> groups = configFile.getAllGroups(); - while (true) { - if (! groups.containsKey(groupName)) break; + while (StringUtil.isEmptyOrSpaces(groupName) || groups.containsKey(groupName)) { groupName += "1"; } } diff --git a/plugins/svn4idea/src/org/jetbrains/idea/svn/dialogs/LoadRecentBranchRevisions.java b/plugins/svn4idea/src/org/jetbrains/idea/svn/dialogs/LoadRecentBranchRevisions.java index 7187613a0f86..825f7e79b901 100644 --- a/plugins/svn4idea/src/org/jetbrains/idea/svn/dialogs/LoadRecentBranchRevisions.java +++ b/plugins/svn4idea/src/org/jetbrains/idea/svn/dialogs/LoadRecentBranchRevisions.java @@ -59,6 +59,10 @@ class LoadRecentBranchRevisions extends TaskDescriptor { private final Integer myTestBunchSize; LoadRecentBranchRevisions(String branchName, long first, WCInfo info, SvnVcs vcs, String url) { + this(branchName, first, info, vcs, url, -1); + } + + LoadRecentBranchRevisions(String branchName, long first, WCInfo info, SvnVcs vcs, String url, final int bunchSize) { super("Loading recent " + branchName + " revisions", Where.POOLED); myFirst = first; myWcInfo = info; @@ -69,15 +73,10 @@ class LoadRecentBranchRevisions extends TaskDescriptor { if (myTestBunchSize != null) { myBunchSize = myTestBunchSize.intValue(); } else { - myBunchSize = BUNCH_SIZE; + myBunchSize = bunchSize > 0 ? bunchSize : BUNCH_SIZE; } } - void setBunchSize(int bunchSize) { - if (myTestBunchSize != null) return; - myBunchSize = bunchSize; - } - public boolean isLastLoaded() { return myLastLoaded; } diff --git a/plugins/svn4idea/src/org/jetbrains/idea/svn/dialogs/QuickMerge.java b/plugins/svn4idea/src/org/jetbrains/idea/svn/dialogs/QuickMerge.java index 01e5a1d0342a..29e5b311bc4d 100644 --- a/plugins/svn4idea/src/org/jetbrains/idea/svn/dialogs/QuickMerge.java +++ b/plugins/svn4idea/src/org/jetbrains/idea/svn/dialogs/QuickMerge.java @@ -200,8 +200,7 @@ public class QuickMerge { @Override public void consume(Long bunchSize, final MergeDialogI dialog) { final LoadRecentBranchRevisions loader = - new LoadRecentBranchRevisions(myBranchName, dialog.getLastNumber(), myWcInfo, myVcs, mySourceUrl); - loader.setBunchSize(bunchSize.intValue()); + new LoadRecentBranchRevisions(myBranchName, dialog.getLastNumber(), myWcInfo, myVcs, mySourceUrl, bunchSize.intValue()); final TaskDescriptor updater = new TaskDescriptor("", Where.AWT) { @Override public void run(ContinuationContext context) { diff --git a/plugins/svn4idea/src/org/jetbrains/idea/svn/integrate/QuickMergeInteraction.java b/plugins/svn4idea/src/org/jetbrains/idea/svn/integrate/QuickMergeInteraction.java index def31a2c3e74..5b2e0ca97589 100644 --- a/plugins/svn4idea/src/org/jetbrains/idea/svn/integrate/QuickMergeInteraction.java +++ b/plugins/svn4idea/src/org/jetbrains/idea/svn/integrate/QuickMergeInteraction.java @@ -35,10 +35,6 @@ import java.util.List; */ public interface QuickMergeInteraction { void setTitle(@NotNull final String title); - /** - * @return {@link com.intellij.openapi.ui.Messages.CANCEL} - cancel, - * {@link com.intellij.openapi.ui.Messages.OK} - merge all, {@link com.intellij.openapi.ui.Messages.NO} - select revisions to merge - */ QuickMergeContentsVariants selectMergeVariant(); boolean shouldContinueSwitchedRootFound(); diff --git a/plugins/tasks/jira-connector/src/main/java/com/intellij/tasks/jira/JiraRepository.java b/plugins/tasks/jira-connector/src/main/java/com/intellij/tasks/jira/JiraRepository.java index 91763014b989..c48be1c99b3e 100644 --- a/plugins/tasks/jira-connector/src/main/java/com/intellij/tasks/jira/JiraRepository.java +++ b/plugins/tasks/jira-connector/src/main/java/com/intellij/tasks/jira/JiraRepository.java @@ -39,6 +39,8 @@ import java.util.List; public class JiraRepository extends BaseRepositoryImpl { private final static Logger LOG = Logger.getInstance("#com.intellij.tasks.jira.JiraRepository"); + public static final String LOGIN_FAILED_CHECK_YOUR_PERMISSIONS = "Login failed. Check your permissions."; + private boolean myJira4 = true; /** @@ -160,6 +162,9 @@ public class JiraRepository extends BaseRepositoryImpl { if (statusCode != HttpStatus.SC_OK && statusCode != HttpStatus.SC_MOVED_TEMPORARILY) { throw new IOException("Can't login: " + statusCode + " (" + HttpStatus.getStatusText(statusCode) + ")"); } + if (statusCode == HttpStatus.SC_OK && new String(postMethod.getResponseBody(2000)).contains("\"loginSucceeded\":false")) { + throw new IOException(LOGIN_FAILED_CHECK_YOUR_PERMISSIONS); + } return true; } diff --git a/plugins/tasks/tasks-tests/test/com/intellij/tasks/integration/JiraIntegrationTest.java b/plugins/tasks/tasks-tests/test/com/intellij/tasks/integration/JiraIntegrationTest.java index 98fa5568c891..a03906966b01 100644 --- a/plugins/tasks/tasks-tests/test/com/intellij/tasks/integration/JiraIntegrationTest.java +++ b/plugins/tasks/tasks-tests/test/com/intellij/tasks/integration/JiraIntegrationTest.java @@ -38,6 +38,14 @@ public class JiraIntegrationTest extends TaskManagerTestCase { assertFalse(issues[0].isClosed()); } + public void testLogin() throws Exception { + myRepository.setUsername("german"); + myRepository.setUsername("wrong password"); + Exception exception = myRepository.createCancellableConnection().call(); + assertNotNull(exception); + assertEquals(JiraRepository.LOGIN_FAILED_CHECK_YOUR_PERMISSIONS, exception.getMessage()); + } + @Override public void setUp() throws Exception { super.setUp(); diff --git a/plugins/ui-designer/src/META-INF/plugin.xml b/plugins/ui-designer/src/META-INF/plugin.xml index 1b4122c81cd0..69aa128a275b 100644 --- a/plugins/ui-designer/src/META-INF/plugin.xml +++ b/plugins/ui-designer/src/META-INF/plugin.xml @@ -206,7 +206,6 @@ <reference ref="VersionControlsGroup"/> <separator/> <reference ref="AddToFavorites"/> - <reference ref="MoveToChangeList"/> <separator/> </group> diff --git a/plugins/ui-designer/testData/formEmbedding/Ideadev14081/Main.java b/plugins/ui-designer/testData/formEmbedding/Ideadev14081/Main.java index 6ada180b3b5e..bd2b425e9553 100644 --- a/plugins/ui-designer/testData/formEmbedding/Ideadev14081/Main.java +++ b/plugins/ui-designer/testData/formEmbedding/Ideadev14081/Main.java @@ -13,6 +13,8 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +import com.intellij.ui.ScreenUtil; + import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; @@ -50,10 +52,8 @@ public class Main { for(int i = 0; i < lafs.length; i++){ viewMenu.add(new MySetLafAction(frame, lafs[i])); } - frame.pack(); - Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); - frame.setLocation((screenSize.width - frame.getWidth())/2, (screenSize.height - frame.getHeight())/2); + frame.setLocationRelativeTo(null); frame.setVisible(true); } diff --git a/plugins/xpath/xpath-lang/src/org/intellij/lang/xpath/xslt/associations/impl/AssociationsEditor.java b/plugins/xpath/xpath-lang/src/org/intellij/lang/xpath/xslt/associations/impl/AssociationsEditor.java index ed0af7f62b17..35d23b1fb649 100644 --- a/plugins/xpath/xpath-lang/src/org/intellij/lang/xpath/xslt/associations/impl/AssociationsEditor.java +++ b/plugins/xpath/xpath-lang/src/org/intellij/lang/xpath/xslt/associations/impl/AssociationsEditor.java @@ -68,7 +68,6 @@ class AssociationsEditor { myBuilder = new ProjectTreeBuilder(project, myTree, treeModel, new MyGroupByTypeComparator(), new MyProjectStructure(project)); - myTree.expandRow(0); myTree.setCellRenderer(new MyNodeRenderer(myManager)); new TreeSpeedSearch(myTree); |