diff --git a/.idea/modules.xml b/.idea/modules.xml index 7173cae34b58..315b69f7138f 100644 --- a/.idea/modules.xml +++ b/.idea/modules.xml @@ -106,6 +106,7 @@ + diff --git a/build/scripts/layouts.gant b/build/scripts/layouts.gant index fb0427ec800e..27e02a867918 100644 --- a/build/scripts/layouts.gant +++ b/build/scripts/layouts.gant @@ -299,6 +299,13 @@ public def layoutCommunityPlugins(String home) { } } + jar("artifact-resolver-m31.jar") { + module("maven-artifact-resolver-m31") + module("maven-artifact-resolver-m2") { + include(name: 'org/jetbrains/idea/maven/artifactResolver/common/*') + } + } + dir("maven3") { fileset(dir: "$home/plugins/maven/maven3-server-impl/lib") {include(name: "*.jar")} fileset(dir: "$home/plugins/maven/maven3-server-impl/lib/maven3/lib") {include(name: "*.jar")} diff --git a/build/scripts/libLicenses.gant b/build/scripts/libLicenses.gant index 01a28dfc9f72..bfe2f2957a9c 100644 --- a/build/scripts/libLicenses.gant +++ b/build/scripts/libLicenses.gant @@ -207,6 +207,7 @@ libraryLicense(name: "markdownj", libraryName: "markdownj", version: "0.4.2", li libraryLicense(name: "Maven", version: "2.2.1", license: "Apache 2.0", url: "http://maven.apache.org/", licenseUrl: "http://maven.apache.org/license.html") libraryLicense(name: "plexus-util", version: "2.0.6", license: "Apache 2.0", url: "http://maven.apache.org/", libraryNames:['plexus-utils-2.0.6.jar'], licenseUrl: "http://apache.org/licenses/LICENSE-2.0") libraryLicense(name: "aether-api", version: "1.11", libraryNames: ["aether-api-1.11.jar"], license: "Apache 2.0", url: "http://maven.apache.org/", licenseUrl: "http://maven.apache.org/license.html") +libraryLicense(name: "aether-api-0.9.0.M2.jar", version: "0.9.0.M2", libraryNames: ["aether-api-0.9.0.M2.jar"], license: "Eclipse Public License v1.0", url: "http://nexus.sonatype.org/", licenseUrl: "http://www.eclipse.org/org/documents/epl-v10.html") libraryLicense(name: "maven-2.2.1-uber", version: "2.2.1", libraryNames: ["maven-2.2.1-uber.jar"], license: "Apache 2.0", url: "http://maven.apache.org/", licenseUrl: "http://maven.apache.org/license.html") libraryLicense(name: "maven-artifact", version: "3.0.3", libraryNames: ["maven-artifact-3.0.3.jar"], license: "Apache 2.0", url: "http://maven.apache.org/", licenseUrl: "http://maven.apache.org/license.html") libraryLicense(name: "maven-core", version: "3.0.3", libraryNames: ["maven-core-3.0.3.jar"], license: "Apache 2.0", url: "http://maven.apache.org/", licenseUrl: "http://maven.apache.org/license.html") diff --git a/community-resources/src/idea/IdeaApplicationInfo.xml b/community-resources/src/idea/IdeaApplicationInfo.xml index 084236c06f0b..52e4c01765a3 100644 --- a/community-resources/src/idea/IdeaApplicationInfo.xml +++ b/community-resources/src/idea/IdeaApplicationInfo.xml @@ -3,8 +3,8 @@ - - + + diff --git a/community-resources/src/idea_community_about.png b/community-resources/src/idea_community_about.png index 3f363f2d5135..5bed0ec33a17 100644 Binary files a/community-resources/src/idea_community_about.png and b/community-resources/src/idea_community_about.png differ diff --git a/community-resources/src/idea_community_about@2x.png b/community-resources/src/idea_community_about@2x.png index 619c7c554c5f..428aaa5ed1fb 100644 Binary files a/community-resources/src/idea_community_about@2x.png and b/community-resources/src/idea_community_about@2x.png differ diff --git a/community-resources/src/idea_community_logo.png b/community-resources/src/idea_community_logo.png index f95add3eeb5c..87543ff9b401 100644 Binary files a/community-resources/src/idea_community_logo.png and b/community-resources/src/idea_community_logo.png differ diff --git a/community-resources/src/idea_community_logo@2x.png b/community-resources/src/idea_community_logo@2x.png index 50ea4eed78a7..57603bed5536 100644 Binary files a/community-resources/src/idea_community_logo@2x.png and b/community-resources/src/idea_community_logo@2x.png differ diff --git a/java/compiler/impl/src/com/intellij/compiler/server/BuildMessageDispatcher.java b/java/compiler/impl/src/com/intellij/compiler/server/BuildMessageDispatcher.java index 6e5f66766e12..a6ba4a38190a 100644 --- a/java/compiler/impl/src/com/intellij/compiler/server/BuildMessageDispatcher.java +++ b/java/compiler/impl/src/com/intellij/compiler/server/BuildMessageDispatcher.java @@ -41,7 +41,7 @@ class BuildMessageDispatcher extends SimpleChannelInboundHandler SESSION_DATA = AttributeKey.valueOf("BuildMessageDispatcher.sessionData"); - private final Map myMessageHandlers = new ConcurrentHashMap(); + private final Map myMessageHandlers = new ConcurrentHashMap(16, 0.75f, 1); private final Set myCanceledSessions = new ConcurrentHashSet(); public void registerBuildMessageHandler(UUID sessionId, diff --git a/java/execution/openapi/src/com/intellij/execution/filters/ExceptionExFilterFactory.java b/java/execution/openapi/src/com/intellij/execution/filters/ExceptionExFilterFactory.java index 88fa616d7025..433da78acb21 100644 --- a/java/execution/openapi/src/com/intellij/execution/filters/ExceptionExFilterFactory.java +++ b/java/execution/openapi/src/com/intellij/execution/filters/ExceptionExFilterFactory.java @@ -20,6 +20,7 @@ import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.editor.Document; import com.intellij.openapi.editor.markup.EffectType; import com.intellij.openapi.editor.markup.TextAttributes; +import com.intellij.openapi.fileEditor.OpenFileDescriptor; import com.intellij.openapi.util.TextRange; import com.intellij.openapi.util.Trinity; import com.intellij.psi.*; @@ -84,10 +85,16 @@ public class ExceptionExFilterFactory implements ExceptionFilterFactory { worker.execute(text, lineEndOffset); Result result = worker.getResult(); if (result == null) continue; - OpenFileHyperlinkInfo hyperlinkInfo = ExceptionWorker.getOpenFileHyperlinkInfo(result); - int offset = hyperlinkInfo == null? -1 : hyperlinkInfo.getDescriptor().getOffset(); + HyperlinkInfo hyperlinkInfo = result.hyperlinkInfo; + if (!(hyperlinkInfo instanceof FileHyperlinkInfo)) continue; + + OpenFileDescriptor descriptor = ((FileHyperlinkInfo)hyperlinkInfo).getDescriptor(); + if (descriptor == null) continue; + + int offset = descriptor.getOffset(); PsiFile psiFile = worker.getFile(); if (offset <= 0 || psiFile == null) continue; + PsiElement element = psiFile.findElementAt(offset); PsiTryStatement parent = PsiTreeUtil.getParentOfType(element, PsiTryStatement.class, true, PsiClass.class); PsiCodeBlock tryBlock = parent != null? parent.getTryBlock() : null; diff --git a/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/projectRoot/BaseLibrariesConfigurable.java b/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/projectRoot/BaseLibrariesConfigurable.java index 711b723141c9..2f38609ed93e 100644 --- a/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/projectRoot/BaseLibrariesConfigurable.java +++ b/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/projectRoot/BaseLibrariesConfigurable.java @@ -234,25 +234,25 @@ public abstract class BaseLibrariesConfigurable extends BaseStructureConfigurabl @Override protected void updateSelection(@Nullable NamedConfigurable configurable) { boolean selectionChanged = !Comparing.equal(myCurrentConfigurable, configurable); - if (myCurrentConfigurable != null && selectionChanged) { + if (myCurrentConfigurable instanceof LibraryConfigurable && selectionChanged) { ((LibraryConfigurable)myCurrentConfigurable).onUnselected(); } super.updateSelection(configurable); - if (myCurrentConfigurable != null && selectionChanged) { + if (myCurrentConfigurable instanceof LibraryConfigurable && selectionChanged) { ((LibraryConfigurable)myCurrentConfigurable).onSelected(); } } @Override public void onStructureUnselected() { - if (myCurrentConfigurable != null) { + if (myCurrentConfigurable instanceof LibraryConfigurable) { ((LibraryConfigurable)myCurrentConfigurable).onUnselected(); } } @Override public void onStructureSelected() { - if (myCurrentConfigurable != null) { + if (myCurrentConfigurable instanceof LibraryConfigurable) { ((LibraryConfigurable)myCurrentConfigurable).onSelected(); } } diff --git a/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/analysis/HighlightNamesUtil.java b/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/analysis/HighlightNamesUtil.java index e7b162fbcc4b..6f2af69a8f4c 100644 --- a/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/analysis/HighlightNamesUtil.java +++ b/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/analysis/HighlightNamesUtil.java @@ -234,15 +234,14 @@ public class HighlightNamesUtil { DependencyValidationManagerImpl validationManager = (DependencyValidationManagerImpl)DependencyValidationManager.getInstance(file.getProject()); List> scopes = validationManager.getScopeBasedHighlightingCachedScopes(); for (Pair scope : scopes) { - NamedScope namedScope = scope.getFirst(); - NamedScopesHolder scopesHolder = scope.getSecond(); - PackageSet packageSet = namedScope.getValue(); - if (packageSet != null && packageSet.contains(file, scopesHolder)) { - TextAttributesKey scopeKey = ScopeAttributesUtil.getScopeTextAttributeKey(namedScope.getName()); - TextAttributes attributes = colorsScheme.getAttributes(scopeKey); - if (attributes == null || attributes.isEmpty()) { - continue; - } + final NamedScope namedScope = scope.getFirst(); + final TextAttributesKey scopeKey = ScopeAttributesUtil.getScopeTextAttributeKey(namedScope.getName()); + final TextAttributes attributes = colorsScheme.getAttributes(scopeKey); + if (attributes == null || attributes.isEmpty()) { + continue; + } + final PackageSet packageSet = namedScope.getValue(); + if (packageSet != null && packageSet.contains(file, scope.getSecond())) { result = TextAttributes.merge(attributes, result); } } diff --git a/java/java-analysis-impl/src/com/intellij/codeInspection/localCanBeFinal/LocalCanBeFinal.java b/java/java-analysis-impl/src/com/intellij/codeInspection/localCanBeFinal/LocalCanBeFinal.java index d4cff693643a..b693e5e4ee9d 100644 --- a/java/java-analysis-impl/src/com/intellij/codeInspection/localCanBeFinal/LocalCanBeFinal.java +++ b/java/java-analysis-impl/src/com/intellij/codeInspection/localCanBeFinal/LocalCanBeFinal.java @@ -21,21 +21,19 @@ import com.intellij.codeInspection.*; import com.intellij.codeInspection.ui.MultipleCheckboxOptionsPanel; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.project.Project; +import com.intellij.openapi.util.WriteExternalException; import com.intellij.psi.*; import com.intellij.psi.controlFlow.*; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.psi.util.PsiUtil; import com.intellij.util.IncorrectOperationException; +import org.jdom.Element; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; -import javax.swing.event.ChangeEvent; -import javax.swing.event.ChangeListener; -import java.awt.*; import java.util.*; -import java.util.List; /** * @author max @@ -55,6 +53,18 @@ public class LocalCanBeFinal extends BaseJavaBatchLocalInspectionTool { myQuickFix = new AcceptSuggested(); } + @Override + public void writeSettings(@NotNull Element node) throws WriteExternalException { + node.addContent(new Element("option").setAttribute("name", "REPORT_VARIABLES").setAttribute("value", String.valueOf(REPORT_VARIABLES))); + node.addContent(new Element("option").setAttribute("name", "REPORT_PARAMETERS").setAttribute("value", String.valueOf(REPORT_PARAMETERS))); + if (!REPORT_CATCH_PARAMETERS) { + node.addContent(new Element("option").setAttribute("name", "REPORT_CATCH_PARAMETERS").setAttribute("value", "false")); + } + if (!REPORT_FOREACH_PARAMETERS) { + node.addContent(new Element("option").setAttribute("name", "REPORT_FOREACH_PARAMETERS").setAttribute("value", "false")); + } + } + @Override public ProblemDescriptor[] checkMethod(@NotNull PsiMethod method, @NotNull InspectionManager manager, boolean isOnTheFly) { List list = checkCodeBlock(method.getBody(), manager, isOnTheFly); diff --git a/java/java-impl/src/com/intellij/codeInspection/deadCode/DummyEntryPointsPresentation.java b/java/java-impl/src/com/intellij/codeInspection/deadCode/DummyEntryPointsPresentation.java index 04fe0f2125d1..20465b1fe919 100644 --- a/java/java-impl/src/com/intellij/codeInspection/deadCode/DummyEntryPointsPresentation.java +++ b/java/java-impl/src/com/intellij/codeInspection/deadCode/DummyEntryPointsPresentation.java @@ -46,6 +46,11 @@ public class DummyEntryPointsPresentation extends UnusedDeclarationPresentation return myQuickFixActions; } + @Override + protected String getSeverityDelegateName() { + return UnusedDeclarationInspection.SHORT_NAME; + } + private class MoveEntriesToSuspicious extends QuickFixAction { private MoveEntriesToSuspicious(@NotNull InspectionToolWrapper toolWrapper) { super(InspectionsBundle.message("inspection.dead.code.remove.from.entry.point.quickfix"), null, null, toolWrapper); diff --git a/java/java-impl/src/com/intellij/codeInspection/deadCode/UnusedDeclarationPresentation.java b/java/java-impl/src/com/intellij/codeInspection/deadCode/UnusedDeclarationPresentation.java index 8dd6a04d8061..276bb97e2922 100644 --- a/java/java-impl/src/com/intellij/codeInspection/deadCode/UnusedDeclarationPresentation.java +++ b/java/java-impl/src/com/intellij/codeInspection/deadCode/UnusedDeclarationPresentation.java @@ -117,7 +117,7 @@ public class UnusedDeclarationPresentation extends DefaultInspectionToolPresenta @NonNls Element problemClassElement = new Element(InspectionsBundle.message("inspection.export.results.problem.element.tag")); final RefElement refElement = (RefElement)refEntity; - final HighlightSeverity severity = getSeverity(refElement, getContext(), getToolWrapper()); + final HighlightSeverity severity = getSeverity(refElement); final String attributeKey = getTextAttributeKey(refElement.getRefManager().getProject(), severity, ProblemHighlightType.LIKE_UNUSED_SYMBOL); problemClassElement.setAttribute("severity", severity.myName); diff --git a/java/java-psi-api/src/com/intellij/psi/LambdaUtil.java b/java/java-psi-api/src/com/intellij/psi/LambdaUtil.java index 6d8f91b7e289..4851504f5b76 100644 --- a/java/java-psi-api/src/com/intellij/psi/LambdaUtil.java +++ b/java/java-psi-api/src/com/intellij/psi/LambdaUtil.java @@ -455,7 +455,12 @@ public class LambdaUtil { if (!tryToSubstitute) return cachedType; } - final PsiElement gParent = expressionList.getParent(); + PsiElement gParent = expressionList.getParent(); + + if (gParent instanceof PsiAnonymousClass) { + gParent = gParent.getParent(); + } + if (gParent instanceof PsiCall) { final PsiCall contextCall = (PsiCall)gParent; final JavaResolveResult resolveResult = contextCall.resolveMethodGenerics(); diff --git a/java/java-psi-impl/src/com/intellij/codeInsight/generation/OverrideImplementExploreUtil.java b/java/java-psi-impl/src/com/intellij/codeInsight/generation/OverrideImplementExploreUtil.java index f8991e62cbc5..c64baf294ce6 100644 --- a/java/java-psi-impl/src/com/intellij/codeInsight/generation/OverrideImplementExploreUtil.java +++ b/java/java-psi-impl/src/com/intellij/codeInsight/generation/OverrideImplementExploreUtil.java @@ -9,10 +9,7 @@ import com.intellij.openapi.util.text.StringUtil; import com.intellij.pom.java.LanguageLevel; import com.intellij.psi.*; import com.intellij.psi.infos.CandidateInfo; -import com.intellij.psi.util.MethodSignature; -import com.intellij.psi.util.MethodSignatureBackedByPsiMethod; -import com.intellij.psi.util.MethodSignatureUtil; -import com.intellij.psi.util.PsiUtil; +import com.intellij.psi.util.*; import org.jetbrains.annotations.NotNull; import java.util.*; @@ -47,12 +44,12 @@ public class OverrideImplementExploreUtil { Map finals = new LinkedHashMap(); Map concretes = new LinkedHashMap(); - LOG.assertTrue(aClass.isValid()); + PsiUtilCore.ensureValid(aClass); Collection allMethodSigs = aClass.getVisibleSignatures(); PsiResolveHelper resolveHelper = JavaPsiFacade.getInstance(aClass.getProject()).getResolveHelper(); for (HierarchicalMethodSignature signature : allMethodSigs) { PsiMethod method = signature.getMethod(); - LOG.assertTrue(method.isValid(), aClass); + PsiUtilCore.ensureValid(method); if (method.hasModifierProperty(PsiModifier.STATIC) || !resolveHelper.isAccessible(method, aClass, aClass)) continue; PsiClass hisClass = method.getContainingClass(); diff --git a/java/java-psi-impl/src/com/intellij/codeInsight/javadoc/JavaDocInfoGenerator.java b/java/java-psi-impl/src/com/intellij/codeInsight/javadoc/JavaDocInfoGenerator.java index 4a99129c3d88..6f877e968ec6 100644 --- a/java/java-psi-impl/src/com/intellij/codeInsight/javadoc/JavaDocInfoGenerator.java +++ b/java/java-psi-impl/src/com/intellij/codeInsight/javadoc/JavaDocInfoGenerator.java @@ -30,6 +30,7 @@ import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.*; import com.intellij.psi.impl.JavaConstantExpressionEvaluator; +import com.intellij.psi.impl.source.javadoc.PsiInlineDocTagImpl; import com.intellij.psi.impl.source.tree.JavaDocElementType; import com.intellij.psi.javadoc.PsiDocComment; import com.intellij.psi.javadoc.PsiDocTag; @@ -1039,7 +1040,7 @@ public class JavaDocInfoGenerator { generateLinkValue(tag, buffer, false); } else if (tagName.equals(LITERAL_TAG)) { - generateLiteralValue(tag, buffer); + generateLiteralValue(buffer, ((PsiInlineDocTagImpl)tag).getDataElementsIgnoreWhitespaces()); } else if (tagName.equals(CODE_TAG)) { generateCodeValue(tag, buffer); @@ -1073,14 +1074,12 @@ public class JavaDocInfoGenerator { @SuppressWarnings({"HardCodedStringLiteral"}) private static void generateCodeValue(PsiInlineDocTag tag, StringBuilder buffer) { buffer.append(""); - generateLiteralValue(tag, buffer); + generateLiteralValue(buffer, tag.getDataElements()); buffer.append(""); } - private static void generateLiteralValue(PsiInlineDocTag tag, StringBuilder buffer) { - PsiElement[] elements = tag.getDataElements(); - - for (PsiElement element : elements) { + private static void generateLiteralValue(StringBuilder buffer, final PsiElement[] dataElements) { + for (PsiElement element : dataElements) { appendPlainText(element.getText(), buffer); } } diff --git a/java/java-psi-impl/src/com/intellij/psi/impl/source/javadoc/PsiInlineDocTagImpl.java b/java/java-psi-impl/src/com/intellij/psi/impl/source/javadoc/PsiInlineDocTagImpl.java index 1adf3a5a700a..668453c71a70 100644 --- a/java/java-psi-impl/src/com/intellij/psi/impl/source/javadoc/PsiInlineDocTagImpl.java +++ b/java/java-psi-impl/src/com/intellij/psi/impl/source/javadoc/PsiInlineDocTagImpl.java @@ -35,10 +35,11 @@ import com.intellij.util.IncorrectOperationException; import org.jetbrains.annotations.NotNull; public class PsiInlineDocTagImpl extends CompositePsiElement implements PsiInlineDocTag, Constants { - private static final TokenSet TAG_VALUE_BIT_SET = TokenSet.create( - DOC_TAG_VALUE_ELEMENT, DOC_METHOD_OR_FIELD_REF); - private static final TokenSet VALUE_BIT_SET = TokenSet.orSet(TAG_VALUE_BIT_SET, TokenSet.create( + private static final TokenSet TAG_VALUE_BIT_SET = TokenSet.create(DOC_TAG_VALUE_ELEMENT, DOC_METHOD_OR_FIELD_REF); + private static final TokenSet VALUE_NO_WHITESPACE_BIT_SET = TokenSet.orSet(TAG_VALUE_BIT_SET, TokenSet.create( JAVA_CODE_REFERENCE, DOC_TAG_VALUE_TOKEN, DOC_COMMENT_DATA, DOC_INLINE_TAG, DOC_REFERENCE_HOLDER, DOC_COMMENT_BAD_CHARACTER)); + private static final TokenSet VALUE_BIT_SET = TokenSet.orSet(TAG_VALUE_BIT_SET, TokenSet.create( + JAVA_CODE_REFERENCE, DOC_TAG_VALUE_TOKEN, WHITE_SPACE, DOC_COMMENT_DATA, DOC_INLINE_TAG, DOC_REFERENCE_HOLDER, DOC_COMMENT_BAD_CHARACTER)); public PsiInlineDocTagImpl() { super(DOC_INLINE_TAG); @@ -63,6 +64,10 @@ public class PsiInlineDocTagImpl extends CompositePsiElement implements PsiInlin return getChildrenAsPsiElements(VALUE_BIT_SET, PsiElement.ARRAY_FACTORY); } + public PsiElement[] getDataElementsIgnoreWhitespaces() { + return getChildrenAsPsiElements(VALUE_NO_WHITESPACE_BIT_SET, PsiElement.ARRAY_FACTORY); + } + @Override public PsiDocTagValue getValueElement() { return (PsiDocTagValue)findPsiChildByType(TAG_VALUE_BIT_SET); diff --git a/java/java-psi-impl/src/com/intellij/psi/impl/source/tree/java/PsiMethodReferenceExpressionImpl.java b/java/java-psi-impl/src/com/intellij/psi/impl/source/tree/java/PsiMethodReferenceExpressionImpl.java index c6fb44b0d993..c25ba98b9d40 100644 --- a/java/java-psi-impl/src/com/intellij/psi/impl/source/tree/java/PsiMethodReferenceExpressionImpl.java +++ b/java/java-psi-impl/src/com/intellij/psi/impl/source/tree/java/PsiMethodReferenceExpressionImpl.java @@ -439,9 +439,12 @@ public class PsiMethodReferenceExpressionImpl extends PsiReferenceExpressionBase } } else { if (rightTypes.length != types.length || rightTypes[rightTypes.length - 1].getArrayDimensions() != types[types.length-1].getArrayDimensions()) { - types[types.length - 1] = ((PsiArrayType)types[types.length - 1]).getComponentType(); + boolean expandTypeArray = types.length < rightTypes.length; int min = Math.min(types.length, rightTypes.length); types = Arrays.copyOf(types, min); + if (expandTypeArray) { + types[types.length - 1] = ((PsiArrayType)types[types.length - 1]).getComponentType(); + } rightTypes = Arrays.copyOf(rightTypes, min); } } diff --git a/java/java-psi-impl/src/com/intellij/psi/scope/util/PsiScopesUtil.java b/java/java-psi-impl/src/com/intellij/psi/scope/util/PsiScopesUtil.java index 8556ee13e513..30f908426cd6 100644 --- a/java/java-psi-impl/src/com/intellij/psi/scope/util/PsiScopesUtil.java +++ b/java/java-psi-impl/src/com/intellij/psi/scope/util/PsiScopesUtil.java @@ -25,6 +25,7 @@ package com.intellij.psi.scope.util; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.progress.ProgressIndicatorProvider; +import com.intellij.openapi.util.Comparing; import com.intellij.pom.java.LanguageLevel; import com.intellij.psi.*; import com.intellij.psi.impl.source.resolve.JavaResolveUtil; @@ -318,7 +319,13 @@ public class PsiScopesUtil { if (initializer instanceof PsiNewExpression) { final PsiAnonymousClass anonymousClass = ((PsiNewExpression)initializer).getAnonymousClass(); if (anonymousClass != null && type.equals(anonymousClass.getBaseClassType())) { - type = initializer.getType(); + final PsiMethod[] refMethods = anonymousClass.findMethodsByName(methodCall.getMethodExpression().getReferenceName(), false); + if (refMethods.length > 0) { + final PsiClass baseClass = PsiUtil.resolveClassInType(type); + if (baseClass != null && !hasCovariantOverriding(baseClass, refMethods)) { + type = initializer.getType(); + } + } } } } @@ -381,6 +388,18 @@ public class PsiScopesUtil { } } + private static boolean hasCovariantOverriding(PsiClass baseClass, PsiMethod[] refMethods) { + for (PsiMethod method : refMethods) { + final PsiType methodReturnType = method.getReturnType(); + for (PsiMethod superMethod : method.findSuperMethods(baseClass)) { + if (!Comparing.equal(methodReturnType, superMethod.getReturnType())) { + return true; + } + } + } + return false; + } + private static boolean processQualifierType(@NotNull final PsiType type, final MethodsProcessor processor, PsiManager manager, diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/newLambda/ArgumentOfAnonymousClass.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/newLambda/ArgumentOfAnonymousClass.java new file mode 100644 index 000000000000..dfd4563e5a82 --- /dev/null +++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/newLambda/ArgumentOfAnonymousClass.java @@ -0,0 +1,19 @@ +interface I { + void accept(T t); +} + +class LamdbaTest { + + public void f() { + new A(t -> g(t)) {}; + } + + private void g(T t) { + } + + class A { + public A(I editor) { + } + } + +} \ No newline at end of file diff --git a/java/java-tests/testData/codeInsight/javadocIG/code.html b/java/java-tests/testData/codeInsight/javadocIG/code.html new file mode 100644 index 000000000000..e75e09176a2f --- /dev/null +++ b/java/java-tests/testData/codeInsight/javadocIG/code.html @@ -0,0 +1,10 @@ + Foo
int foo
+
+     
+      class Clazzz {
+        def f[U](u: U) {}
+   
+        val a = 1
+      }
+    
+     
\ No newline at end of file diff --git a/java/java-tests/testData/codeInsight/javadocIG/code.java b/java/java-tests/testData/codeInsight/javadocIG/code.java new file mode 100644 index 000000000000..f5cf2a77f600 --- /dev/null +++ b/java/java-tests/testData/codeInsight/javadocIG/code.java @@ -0,0 +1,14 @@ +class Foo { + /** + *
+   * {@code
+   *   class Clazzz {
+   *     def f[U](u: U) {}
+   *
+   *     val a = 1
+   *   }
+   * }
+   * 
+ */ + int foo; +} \ No newline at end of file diff --git a/java/java-tests/testData/compileServer/incremental/common/addClassHidingImportedClass.log b/java/java-tests/testData/compileServer/incremental/common/addClassHidingImportedClass.log new file mode 100644 index 000000000000..228bc41f8f7e --- /dev/null +++ b/java/java-tests/testData/compileServer/incremental/common/addClassHidingImportedClass.log @@ -0,0 +1,11 @@ +Compiling files: +src/package2/A.java +End of files +Cleaning output files: +out/production/AddClassHidingImportedClass/package2/B.class +out/production/AddClassHidingImportedClass/package3/C.class +End of files +Compiling files: +src/package2/B.java +src/package3/C.java +End of files diff --git a/java/java-tests/testData/compileServer/incremental/common/addClassHidingImportedClass/src/package1/A.java b/java/java-tests/testData/compileServer/incremental/common/addClassHidingImportedClass/src/package1/A.java new file mode 100644 index 000000000000..a61ecd9b2705 --- /dev/null +++ b/java/java-tests/testData/compileServer/incremental/common/addClassHidingImportedClass/src/package1/A.java @@ -0,0 +1,7 @@ +package package1; + +public class A { + public static class D { + public final String s = new String("package1"); + } +} diff --git a/java/java-tests/testData/compileServer/incremental/common/addClassHidingImportedClass/src/package2/A.java.new b/java/java-tests/testData/compileServer/incremental/common/addClassHidingImportedClass/src/package2/A.java.new new file mode 100644 index 000000000000..98b0feeffca2 --- /dev/null +++ b/java/java-tests/testData/compileServer/incremental/common/addClassHidingImportedClass/src/package2/A.java.new @@ -0,0 +1,7 @@ +package package2; + +public class A { + public static class D { + public final String s = new String("package2"); + } +} \ No newline at end of file diff --git a/java/java-tests/testData/compileServer/incremental/common/addClassHidingImportedClass/src/package2/B.java b/java/java-tests/testData/compileServer/incremental/common/addClassHidingImportedClass/src/package2/B.java new file mode 100644 index 000000000000..a32b694a09c8 --- /dev/null +++ b/java/java-tests/testData/compileServer/incremental/common/addClassHidingImportedClass/src/package2/B.java @@ -0,0 +1,6 @@ +package package2; +import package1.*; + +public class B extends A{ + +} diff --git a/java/java-tests/testData/compileServer/incremental/common/addClassHidingImportedClass/src/package3/C.java b/java/java-tests/testData/compileServer/incremental/common/addClassHidingImportedClass/src/package3/C.java new file mode 100644 index 000000000000..04d86d390ea6 --- /dev/null +++ b/java/java-tests/testData/compileServer/incremental/common/addClassHidingImportedClass/src/package3/C.java @@ -0,0 +1,14 @@ +package package3; + +import package2.B; + +public class C { + + public B.D p; + + public String get() { + p = new B.D(); + return p.s; + } + +} diff --git a/java/java-tests/testData/psi/resolve/method/generics/CovariantReturnTypeAnonymous.java b/java/java-tests/testData/psi/resolve/method/generics/CovariantReturnTypeAnonymous.java new file mode 100644 index 000000000000..b487a309af24 --- /dev/null +++ b/java/java-tests/testData/psi/resolve/method/generics/CovariantReturnTypeAnonymous.java @@ -0,0 +1,20 @@ +interface X { + A[] foo(); +} + +class A {} + +class B extends A {} + +class C { + final X x = new X() { + @Override + public B[] foo() { + return new B[0]; + } + }; + + B[] bar() { + return x.foo(); + } +} \ No newline at end of file diff --git a/java/java-tests/testSrc/com/intellij/codeInsight/completion/HeavyNormalCompletionTest.groovy b/java/java-tests/testSrc/com/intellij/codeInsight/completion/HeavyNormalCompletionTest.groovy index 45f79b2ce770..b9620a18b0ab 100644 --- a/java/java-tests/testSrc/com/intellij/codeInsight/completion/HeavyNormalCompletionTest.groovy +++ b/java/java-tests/testSrc/com/intellij/codeInsight/completion/HeavyNormalCompletionTest.groovy @@ -20,6 +20,7 @@ import com.intellij.openapi.vfs.LocalFileSystem import com.intellij.openapi.vfs.VirtualFile import com.intellij.psi.JavaPsiFacade import com.intellij.psi.PsiClass +import com.intellij.psi.PsiManager import com.intellij.psi.search.GlobalSearchScope import com.intellij.psi.util.PsiTreeUtil import com.intellij.testFramework.PsiTestUtil @@ -141,5 +142,12 @@ public class Test { myFixture.assertPreferredCompletionItems 0, 'getBuilder' } + public void testNoJavaStructureModificationOnSecondInvocation() { + myFixture.configureByText 'a.java', 'class Foo { Xxxxx }' + def oldCount = PsiManager.getInstance(project).modificationTracker.javaStructureModificationCount + assert !myFixture.completeBasic() + assert !myFixture.completeBasic() + assert oldCount == PsiManager.getInstance(project).modificationTracker.javaStructureModificationCount + } } diff --git a/java/java-tests/testSrc/com/intellij/codeInsight/daemon/lambda/NewLambdaHighlightingTest.java b/java/java-tests/testSrc/com/intellij/codeInsight/daemon/lambda/NewLambdaHighlightingTest.java index 34a45ee3e094..7cc843809a0e 100644 --- a/java/java-tests/testSrc/com/intellij/codeInsight/daemon/lambda/NewLambdaHighlightingTest.java +++ b/java/java-tests/testSrc/com/intellij/codeInsight/daemon/lambda/NewLambdaHighlightingTest.java @@ -82,6 +82,10 @@ public class NewLambdaHighlightingTest extends LightDaemonAnalyzerTestCase { doTest(); } + public void testArgumentOfAnonymousClass() throws Exception { + doTest(); + } + private void doTest() { doTest(false); } diff --git a/java/java-tests/testSrc/com/intellij/codeInsight/javadoc/JavaDocInfoGeneratorTest.java b/java/java-tests/testSrc/com/intellij/codeInsight/javadoc/JavaDocInfoGeneratorTest.java index ae3df006df09..80d2e4ac2fb6 100644 --- a/java/java-tests/testSrc/com/intellij/codeInsight/javadoc/JavaDocInfoGeneratorTest.java +++ b/java/java-tests/testSrc/com/intellij/codeInsight/javadoc/JavaDocInfoGeneratorTest.java @@ -72,6 +72,10 @@ public class JavaDocInfoGeneratorTest extends CodeInsightTestCase { doTestField(); } + public void testCode() throws Exception { + doTestField(); + } + public void testEnumConstantOrdinal() throws Exception { PsiClass psiClass = getTestClass(); PsiField field = psiClass.getFields() [0]; diff --git a/java/java-tests/testSrc/com/intellij/codeInspection/InspectionProfileTest.java b/java/java-tests/testSrc/com/intellij/codeInspection/InspectionProfileTest.java index ed2db874ef46..a84b0703eef8 100644 --- a/java/java-tests/testSrc/com/intellij/codeInspection/InspectionProfileTest.java +++ b/java/java-tests/testSrc/com/intellij/codeInspection/InspectionProfileTest.java @@ -313,7 +313,7 @@ public class InspectionProfileTest extends LightIdeaTestCase { assertEquals(0, countInitializedTools(profile)); profile.writeExternal(new Element("profile")); List initializedTools = getInitializedTools(profile); - if (initializedTools.size() != 1) { + if (initializedTools.size() > 0) { for (InspectionToolWrapper initializedTool : initializedTools) { System.out.println(initializedTool.getShortName()); } diff --git a/java/java-tests/testSrc/com/intellij/openapi/roots/impl/DirectoryIndexTest.java b/java/java-tests/testSrc/com/intellij/openapi/roots/impl/DirectoryIndexTest.java index 3641d9dc06f4..a721f29a8a88 100644 --- a/java/java-tests/testSrc/com/intellij/openapi/roots/impl/DirectoryIndexTest.java +++ b/java/java-tests/testSrc/com/intellij/openapi/roots/impl/DirectoryIndexTest.java @@ -186,7 +186,7 @@ public class DirectoryIndexTest extends IdeaTestCase { return instance; } - public void testDirInfos() { + public void testDirInfos() throws IOException { checkInfoNull(myRootVFile); // beware: files in directory index @@ -215,9 +215,13 @@ public class DirectoryIndexTest extends IdeaTestCase { assertEquals(myModule1Dir, checkInfoNotNull(myLibClsDir).getContentRoot()); checkInfo(myModule3Dir, myModule3, false, false, null, null); + + VirtualFile cvs = myPack1Dir.createChildDirectory(this, "CVS"); + checkInfoNull(cvs); + assertNull(ProjectRootManager.getInstance(myProject).getFileIndex().getPackageNameByDirectory(cvs)); } - public void testDirsByPackageName() { + public void testDirsByPackageName() throws IOException { checkPackage("", true, myFileLibSrc, myFileLibCls, mySrcDir1, myTestSrc1, myResDir, myTestResDir, myLibSrcDir, myLibClsDir, mySrcDir2); checkPackage("", false, myFileLibCls, mySrcDir1, myTestSrc1, myResDir, myTestResDir, myLibClsDir, mySrcDir2); diff --git a/java/java-tests/testSrc/com/intellij/psi/resolve/ResolveMethod15Test.java b/java/java-tests/testSrc/com/intellij/psi/resolve/ResolveMethod15Test.java index 36b1c4c9de63..788febf4da6e 100644 --- a/java/java-tests/testSrc/com/intellij/psi/resolve/ResolveMethod15Test.java +++ b/java/java-tests/testSrc/com/intellij/psi/resolve/ResolveMethod15Test.java @@ -7,7 +7,6 @@ import com.intellij.navigation.NavigationItem; import org.jetbrains.annotations.NonNls; import static org.junit.Assert.assertThat; import static org.hamcrest.core.IsInstanceOf.instanceOf; -import static org.junit.Assert.assertTrue; /** * @author dsl @@ -129,6 +128,16 @@ public class ResolveMethod15Test extends Resolve15TestCase { assertTrue(containingClass != null ? containingClass.getName() : null, containingClass instanceof PsiAnonymousClass); } + public void testCovariantReturnTypeAnonymous() throws Exception { + final PsiReference ref = configureByFile(); + assertThat(ref, instanceOf(PsiReferenceExpression.class)); + final PsiReferenceExpression refExpr = (PsiReferenceExpression)ref; + final PsiElement resolve = refExpr.resolve(); + assertTrue(resolve != null ? resolve.toString() : null, resolve instanceof PsiMethod); + final PsiClass containingClass = ((PsiMethod)resolve).getContainingClass(); + assertTrue(containingClass != null ? containingClass.getName() : null, !(containingClass instanceof PsiAnonymousClass)); + } + public void testFilterFixedVsVarargs1() throws Exception { final PsiReference ref = configureByFile(); assertThat(ref, instanceOf(PsiReferenceExpression.class)); diff --git a/java/openapi/src/com/intellij/execution/filters/ExceptionWorker.java b/java/openapi/src/com/intellij/execution/filters/ExceptionWorker.java index 3fcd9c959a50..ff02aadc3856 100644 --- a/java/openapi/src/com/intellij/execution/filters/ExceptionWorker.java +++ b/java/openapi/src/com/intellij/execution/filters/ExceptionWorker.java @@ -15,26 +15,29 @@ */ package com.intellij.execution.filters; -import com.intellij.openapi.application.AccessToken; -import com.intellij.openapi.application.ReadAction; import com.intellij.openapi.editor.colors.CodeInsightColors; import com.intellij.openapi.editor.colors.EditorColorsManager; import com.intellij.openapi.editor.markup.TextAttributes; -import com.intellij.openapi.fileEditor.OpenFileDescriptor; import com.intellij.openapi.project.Project; +import com.intellij.openapi.roots.ProjectFileIndex; import com.intellij.openapi.roots.ProjectRootManager; import com.intellij.openapi.util.TextRange; import com.intellij.openapi.util.Trinity; import com.intellij.openapi.vfs.VirtualFile; -import com.intellij.psi.*; +import com.intellij.psi.JavaPsiFacade; +import com.intellij.psi.PsiClass; +import com.intellij.psi.PsiFile; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.search.PsiShortNamesCache; +import com.intellij.util.ArrayUtil; import com.intellij.util.ui.UIUtil; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.awt.*; +import java.util.ArrayList; +import java.util.List; /** * User: Irina.Chernushina @@ -61,8 +64,8 @@ public class ExceptionWorker { private final Project myProject; private final GlobalSearchScope mySearchScope; private Filter.Result myResult; - private PsiClass myClass; - private PsiFile myFile; + private PsiClass[] myClasses = PsiClass.EMPTY_ARRAY; + private PsiFile[] myFiles = PsiFile.EMPTY_ARRAY; private String myMethod; private Trinity myInfo; @@ -90,16 +93,17 @@ public class ExceptionWorker { final String lineString = fileAndLine.substring(colonIndex + 1); try { final int lineNumber = Integer.parseInt(lineString); - myClass = findPositionClass(line); - myFile = myClass == null ? null : (PsiFile)myClass.getContainingFile().getNavigationElement(); - if (myFile == null) { - // try find the file with the required name - PsiFile[] files = PsiShortNamesCache.getInstance(myProject).getFilesByName(fileAndLine.substring(0, colonIndex).trim()); - if (files.length > 0) { - myFile = files[0]; - } + myClasses = findPositionClasses(line); + myFiles = new PsiFile[myClasses.length]; + for (int i = 0; i < myClasses.length; i++) { + myFiles[i] = (PsiFile)myClasses[i].getContainingFile().getNavigationElement(); } - if (myFile == null) return; + if (myFiles.length == 0) { + // try find the file with the required name + //todo[nik] it would be better to use FilenameIndex here to honor the scope by it isn't accessible in Open API + myFiles = PsiShortNamesCache.getInstance(myProject).getFilesByName(fileAndLine.substring(0, colonIndex).trim()); + } + if (myFiles.length == 0) return; /* IDEADEV-4976: Some scramblers put something like SourceFile mock instead of real class name. @@ -113,12 +117,31 @@ public class ExceptionWorker { final int highlightStartOffset = textStartOffset + lparenthIndex + 1; final int highlightEndOffset = textStartOffset + rparenthIndex; - final VirtualFile virtualFile = myFile.getVirtualFile(); - HyperlinkInfo linkInfo = new MyHyperlinkInfo(myProject, virtualFile, lineNumber); + ProjectFileIndex index = ProjectRootManager.getInstance(myProject).getFileIndex(); + List virtualFilesInLibraries = new ArrayList(); + List virtualFilesInContent = new ArrayList(); + for (PsiFile file : myFiles) { + VirtualFile virtualFile = file.getVirtualFile(); + if (index.isInContent(virtualFile)) { + virtualFilesInContent.add(virtualFile); + } + else { + virtualFilesInLibraries.add(virtualFile); + } + } - boolean inContent = ProjectRootManager.getInstance(myProject).getFileIndex().isInContent(virtualFile); - TextAttributes attributes = inContent ? HYPERLINK_ATTRIBUTES : LIBRARY_HYPERLINK_ATTRIBUTES; + List virtualFiles; + TextAttributes attributes; + if (virtualFilesInContent.isEmpty()) { + attributes = LIBRARY_HYPERLINK_ATTRIBUTES; + virtualFiles = virtualFilesInLibraries; + } + else { + attributes = HYPERLINK_ATTRIBUTES; + virtualFiles = virtualFilesInContent; + } + HyperlinkInfo linkInfo = HyperlinkInfoFactory.getInstance().createMultipleFilesHyperlinkInfo(virtualFiles, lineNumber - 1, myProject); myResult = new Filter.Result(highlightStartOffset, highlightEndOffset, linkInfo, attributes); } catch (NumberFormatException e) { @@ -126,22 +149,23 @@ public class ExceptionWorker { } } - private PsiClass findPositionClass(String line) { + private PsiClass[] findPositionClasses(String line) { String className = myInfo.first.substring(line).trim(); - PsiClass result = findClassPreferringMyScope(className); - if (result == null) { + PsiClass[] result = findClassesPreferringMyScope(className); + if (result.length == 0) { final int dollarIndex = className.indexOf('$'); if (dollarIndex >= 0) { - result = findClassPreferringMyScope(className.substring(0, dollarIndex)); + result = findClassesPreferringMyScope(className.substring(0, dollarIndex)); } } return result; } - private PsiClass findClassPreferringMyScope(String className) { + @NotNull + private PsiClass[] findClassesPreferringMyScope(String className) { JavaPsiFacade psiFacade = JavaPsiFacade.getInstance(myProject); - PsiClass result = psiFacade.findClass(className, mySearchScope); - return result != null ? result : psiFacade.findClass(className, GlobalSearchScope.allScope(myProject)); + PsiClass[] result = psiFacade.findClasses(className, mySearchScope); + return result.length != 0 ? result : psiFacade.findClasses(className, GlobalSearchScope.allScope(myProject)); } public Filter.Result getResult() { @@ -149,7 +173,7 @@ public class ExceptionWorker { } public PsiClass getPsiClass() { - return myClass; + return ArrayUtil.getFirstElement(myClasses); } public String getMethod() { @@ -157,7 +181,7 @@ public class ExceptionWorker { } public PsiFile getFile() { - return myFile; + return ArrayUtil.getFirstElement(myFiles); } public Trinity getInfo() { @@ -205,59 +229,4 @@ public class ExceptionWorker { } return pos; } - - @Nullable - static OpenFileHyperlinkInfo getOpenFileHyperlinkInfo(Filter.Result result) { - if (result.hyperlinkInfo instanceof MyHyperlinkInfo) { - MyHyperlinkInfo info = (MyHyperlinkInfo)result.hyperlinkInfo; - return new OpenFileHyperlinkInfo(info.myProject, info.myVirtualFile, info.myLineNumber); - } - return null; - } - - private static class MyHyperlinkInfo implements FileHyperlinkInfo { - private final VirtualFile myVirtualFile; - private final int myLineNumber; - private final Project myProject; - - public MyHyperlinkInfo(@NotNull Project project, @NotNull VirtualFile virtualFile, int lineNumber) { - myProject = project; - myVirtualFile = virtualFile; - myLineNumber = lineNumber; - } - - @Override - public void navigate(Project project) { - VirtualFile currentVirtualFile = null; - - AccessToken accessToken = ReadAction.start(); - - try { - if (!myVirtualFile.isValid()) return; - - PsiFile psiFile = PsiManager.getInstance(project).findFile(myVirtualFile); - if (psiFile != null) { - PsiElement navigationElement = psiFile.getNavigationElement(); // Sources may be downloaded. - if (navigationElement instanceof PsiFile) { - currentVirtualFile = ((PsiFile)navigationElement).getVirtualFile(); - } - } - - if (currentVirtualFile == null) { - currentVirtualFile = myVirtualFile; - } - } - finally { - accessToken.finish(); - } - - new OpenFileHyperlinkInfo(myProject, currentVirtualFile, myLineNumber - 1).navigate(project); - } - - @Nullable - @Override - public OpenFileDescriptor getDescriptor() { - return new OpenFileDescriptor(myProject, myVirtualFile, myLineNumber - 1, 0); - } - } } diff --git a/java/remote-servers/impl/remote-servers-java-impl.iml b/java/remote-servers/impl/remote-servers-java-impl.iml index c98f909fbfd8..b0228d7f4075 100644 --- a/java/remote-servers/impl/remote-servers-java-impl.iml +++ b/java/remote-servers/impl/remote-servers-java-impl.iml @@ -12,7 +12,7 @@ - +
diff --git a/java/remote-servers/impl/src/com/intellij/remoteServer/impl/util/ArtifactDeploymentSourceHandlerBase.java b/java/remote-servers/impl/src/com/intellij/remoteServer/impl/util/ArtifactDeploymentSourceHandlerBase.java new file mode 100644 index 000000000000..3b50c7752e3d --- /dev/null +++ b/java/remote-servers/impl/src/com/intellij/remoteServer/impl/util/ArtifactDeploymentSourceHandlerBase.java @@ -0,0 +1,69 @@ +/* + * 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 com.intellij.remoteServer.impl.util; + +import com.intellij.openapi.diagnostic.Logger; +import com.intellij.packaging.artifacts.Artifact; +import com.intellij.remoteServer.agent.util.CloudGitApplication; +import com.intellij.remoteServer.configuration.deployment.ArtifactDeploymentSource; +import com.intellij.remoteServer.configuration.deployment.DeploymentSource; +import com.intellij.remoteServer.util.DeploymentSourceHandler; +import com.intellij.remoteServer.util.ServerRuntimeException; + +import java.io.File; + +/** + * @author michael.golubev + */ +public abstract class ArtifactDeploymentSourceHandlerBase implements DeploymentSourceHandler { + + private static final Logger LOG = Logger.getInstance("#" + ArtifactDeploymentSourceHandlerBase.class.getName()); + + private Artifact myArtifact; + private File myRepositoryRootFile; + + protected File getArtifactFile() { + return new File(myArtifact.getOutputFilePath()); + } + + @Override + public File getRepositoryRootFile() { + return myRepositoryRootFile; + } + + @Override + public boolean init(DeploymentSource deploymentSource) throws ServerRuntimeException { + if (!(deploymentSource instanceof ArtifactDeploymentSource)) { + return false; + } + ArtifactDeploymentSource artifactDeploymentSource = (ArtifactDeploymentSource)deploymentSource; + Artifact artifact = artifactDeploymentSource.getArtifact(); + if (artifact == null) { + throw new ServerRuntimeException("Artifact not found " + artifactDeploymentSource.getArtifactPointer().getArtifactName()); + } + + String outputPath = artifact.getOutputPath(); + LOG.assertTrue(outputPath != null, "Artifact output path not found"); + myRepositoryRootFile = new File(outputPath, "/deploy"); + if (!myRepositoryRootFile.exists()) { + if (!myRepositoryRootFile.mkdir()) { + throw new ServerRuntimeException("Unable to create deploy folder"); + } + } + myArtifact = artifact; + return true; + } +} diff --git a/jps/jps-builders/src/org/jetbrains/jps/builders/impl/BuildRootIndexImpl.java b/jps/jps-builders/src/org/jetbrains/jps/builders/impl/BuildRootIndexImpl.java index 078e1fbe331b..0ec56d99662f 100644 --- a/jps/jps-builders/src/org/jetbrains/jps/builders/impl/BuildRootIndexImpl.java +++ b/jps/jps-builders/src/org/jetbrains/jps/builders/impl/BuildRootIndexImpl.java @@ -19,7 +19,6 @@ import com.intellij.openapi.util.Key; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.io.FileUtilRt; import com.intellij.util.SmartList; -import com.intellij.util.containers.ConcurrentHashMap; import gnu.trove.THashMap; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -37,6 +36,7 @@ import org.jetbrains.jps.service.JpsServiceManager; import java.io.File; import java.io.FileFilter; import java.util.*; +import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; /** @@ -55,7 +55,7 @@ public class BuildRootIndexImpl implements BuildRootIndex { myIgnoredFileIndex = ignoredFileIndex; myRootsByTarget = new HashMap, List>(); myRootToDescriptors = new THashMap>(FileUtil.FILE_HASHING_STRATEGY); - myFileFilters = new ConcurrentHashMap(); + myFileFilters = new ConcurrentHashMap(16, 0.75f, 1); final Iterable rootsProviders = JpsServiceManager.getInstance().getExtensions(AdditionalRootsProviderService.class); for (BuildTargetType targetType : TargetTypeRegistry.getInstance().getTargetTypes()) { for (BuildTarget target : targetIndex.getAllTargets(targetType)) { diff --git a/jps/jps-builders/src/org/jetbrains/jps/builders/java/dependencyView/ClassRepr.java b/jps/jps-builders/src/org/jetbrains/jps/builders/java/dependencyView/ClassRepr.java index fdc84abf785f..154d5daa6215 100644 --- a/jps/jps-builders/src/org/jetbrains/jps/builders/java/dependencyView/ClassRepr.java +++ b/jps/jps-builders/src/org/jetbrains/jps/builders/java/dependencyView/ClassRepr.java @@ -321,15 +321,17 @@ public class ClassRepr extends Proto { } public String getPackageName() { - return getPackageName(name); + final String strValue = myContext.getValue(name); + return strValue != null? getPackageName(strValue) : null; } - public String getPackageName(final int s) { - return getPackageName(myContext.getValue(s)); + public String getShortName() { + final String strValue = myContext.getValue(name); + return strValue != null? getShortName(strValue) : null; } @NotNull - public static String getPackageName(final String raw) { + public static String getPackageName(@NotNull final String raw) { final int index = raw.lastIndexOf('/'); if (index == -1) { @@ -339,6 +341,17 @@ public class ClassRepr extends Proto { return raw.substring(0, index); } + @NotNull + public static String getShortName(@NotNull final String fqName) { + final int index = fqName.lastIndexOf('/'); + + if (index == -1) { + return fqName; + } + + return fqName.substring(index + 1); + } + @Nullable public FieldRepr findField(final int name) { for (FieldRepr f : myFields) { diff --git a/jps/jps-builders/src/org/jetbrains/jps/builders/java/dependencyView/Mappings.java b/jps/jps-builders/src/org/jetbrains/jps/builders/java/dependencyView/Mappings.java index 29c92aa7a916..8d178ad46990 100644 --- a/jps/jps-builders/src/org/jetbrains/jps/builders/java/dependencyView/Mappings.java +++ b/jps/jps-builders/src/org/jetbrains/jps/builders/java/dependencyView/Mappings.java @@ -45,6 +45,7 @@ public class Mappings { private final static String CLASS_TO_SUBCLASSES = "classToSubclasses.tab"; private final static String CLASS_TO_CLASS = "classToClass.tab"; + private final static String SHORT_NAMES = "shortNames.tab"; private final static String SOURCE_TO_CLASS = "sourceToClass.tab"; private final static String CLASS_TO_SOURCE = "classToSource.tab"; private static final IntInlineKeyDescriptor INT_KEY_DESCRIPTOR = new IntInlineKeyDescriptor(); @@ -65,6 +66,7 @@ public class Mappings { private final TIntHashSet myChangedClasses; private final THashSet myChangedFiles; private final Set myDeletedClasses; + private final Set myAddedClasses; private final Object myLock; private final File myRootDir; @@ -83,6 +85,10 @@ public class Mappings { private IntIntMultiMaplet myClassToClassDependency; private ObjectObjectMultiMaplet mySourceFileToClasses; private IntObjectMaplet myClassToSourceFile; + /** + * [short className] -> list of FQ names + */ + private IntIntMultiMaplet myShortClassNameIndex; private IntIntTransientMultiMaplet myRemovedSuperClasses; private IntIntTransientMultiMaplet myAddedSuperClasses; @@ -96,6 +102,7 @@ public class Mappings { myChangedClasses = new TIntHashSet(DEFAULT_SET_CAPACITY, DEFAULT_SET_LOAD_FACTOR); myChangedFiles = new THashSet(FileUtil.FILE_HASHING_STRATEGY); myDeletedClasses = new HashSet(DEFAULT_SET_CAPACITY, DEFAULT_SET_LOAD_FACTOR); + myAddedClasses = new HashSet(DEFAULT_SET_CAPACITY, DEFAULT_SET_LOAD_FACTOR); myDeltaIsTransient = base.myDeltaIsTransient; myRootDir = new File(FileUtil.toSystemIndependentName(base.myRootDir.getAbsolutePath()) + File.separatorChar + "myDelta"); myContext = base.myContext; @@ -112,6 +119,7 @@ public class Mappings { myChangedClasses = null; myChangedFiles = null; myDeletedClasses = null; + myAddedClasses = null; myDeltaIsTransient = transientDelta; myRootDir = rootDir; createImplementation(); @@ -132,6 +140,7 @@ public class Mappings { if (myIsDelta && myDeltaIsTransient) { myClassToSubclasses = new IntIntTransientMultiMaplet(); myClassToClassDependency = new IntIntTransientMultiMaplet(); + myShortClassNameIndex = null; mySourceFileToClasses = new ObjectObjectTransientMultiMaplet(FileUtil.FILE_HASHING_STRATEGY, ourClassSetConstructor); myClassToSourceFile = new IntObjectTransientMaplet(); } @@ -141,6 +150,7 @@ public class Mappings { } myClassToSubclasses = new IntIntPersistentMultiMaplet(DependencyContext.getTableFile(myRootDir, CLASS_TO_SUBCLASSES), INT_KEY_DESCRIPTOR); myClassToClassDependency = new IntIntPersistentMultiMaplet(DependencyContext.getTableFile(myRootDir, CLASS_TO_CLASS), INT_KEY_DESCRIPTOR); + myShortClassNameIndex = myIsDelta? null : new IntIntPersistentMultiMaplet(DependencyContext.getTableFile(myRootDir, SHORT_NAMES), INT_KEY_DESCRIPTOR); mySourceFileToClasses = new ObjectObjectPersistentMultiMaplet( DependencyContext.getTableFile(myRootDir, SOURCE_TO_CLASS), new FileKeyDescriptor(), ClassRepr.externalizer(myContext), ourClassSetConstructor @@ -1788,36 +1798,51 @@ public class Mappings { for (final ClassRepr c : addedClasses) { debug("Class name: ", c.name); - myDelta.addChangedClass(c.name); + myDelta.addAddedClass(c); for (final int sup : c.getSupers()) { myDelta.registerAddedSuperClass(c.name, sup); } - if (!myEasyMode) { - final TIntHashSet depClasses = myClassToClassDependency.get(c.name); - - if (depClasses != null) { - depClasses.forEach(new TIntProcedure() { - @Override - public boolean execute(int depClass) { - final File fName = myClassToSourceFile.get(depClass); - if (fName != null) { - if (myFilter == null || myFilter.accept(fName)) { - debug("Adding dependent file ", fName); - myAffectedFiles.add(fName); - } - } - return true; - } - }); + if (!myEasyMode && !c.isAnonymous() && !c.isLocal()) { + final TIntHashSet toAffect = new TIntHashSet(); + toAffect.add(c.name); + final TIntHashSet classes = myShortClassNameIndex.get(myContext.get(c.getShortName())); + if (classes != null) { + // affecting dependencies on all other classes with the same short name + toAffect.addAll(classes.toArray()); } + toAffect.forEach(new TIntProcedure() { + public boolean execute(int qName) { + final TIntHashSet depClasses = myClassToClassDependency.get(qName); + if (depClasses != null) { + affectCorrespondingSourceFiles(depClasses); + } + return true; + } + }); } } debug("End of added classes processing."); } + private void affectCorrespondingSourceFiles(TIntHashSet toAffect) { + toAffect.forEach(new TIntProcedure() { + @Override + public boolean execute(int depClass) { + final File fName = myClassToSourceFile.get(depClass); + if (fName != null) { + if (myFilter == null || myFilter.accept(fName)) { + debug("Adding dependent file ", fName); + myAffectedFiles.add(fName); + } + } + return true; + } + }); + } + private void calculateAffectedFiles(final DiffState state) { debug("Checking dependent classes:"); @@ -1979,10 +2004,7 @@ public class Mappings { } } - private void cleanupRemovedClass(final Mappings delta, - @NotNull final ClassRepr cr, - final Set usages, - final IntIntMultiMaplet dependenciesTrashBin) { + private void cleanupRemovedClass(final Mappings delta, @NotNull final ClassRepr cr, final Set usages, final IntIntMultiMaplet dependenciesTrashBin) { final int className = cr.name; for (final int superSomething : cr.getSupers()) { @@ -1994,6 +2016,9 @@ public class Mappings { myClassToClassDependency.remove(className); myClassToSubclasses.remove(className); myClassToSourceFile.remove(className); + if (!cr.isLocal() && !cr.isAnonymous()) { + myShortClassNameIndex.removeFrom(myContext.get(cr.getShortName()), className); + } } public void integrate(final Mappings delta) { @@ -2025,6 +2050,11 @@ public class Mappings { for (final ClassRepr repr : delta.getDeletedClasses()) { cleanupRemovedClass(delta, repr, repr.getUsages(), dependenciesTrashBin); } + for (ClassRepr repr : delta.getAddedClasses()) { + if (!repr.isAnonymous() && !repr.isLocal()) { + myShortClassNameIndex.put(myContext.get(repr.getShortName()), repr.name); + } + } final TIntHashSet superClasses = new TIntHashSet(); final IntIntTransientMultiMaplet addedSuperClasses = delta.getAddedSuperClasses(); @@ -2090,6 +2120,16 @@ public class Mappings { myClassToSubclasses.putAll(delta.myClassToSubclasses); myClassToSourceFile.putAll(delta.myClassToSourceFile); mySourceFileToClasses.replaceAll(delta.mySourceFileToClasses); + delta.mySourceFileToClasses.forEachEntry(new TObjectObjectProcedure>() { + public boolean execute(File src, Collection classes) { + for (ClassRepr repr : classes) { + if (!repr.isAnonymous() && !repr.isLocal()) { + myShortClassNameIndex.put(myContext.get(repr.getShortName()), repr.name); + } + } + return true; + } + }); } // updating classToClass dependencies @@ -2224,6 +2264,7 @@ public class Mappings { myClassToSourceFile.close(); if (!myIsDelta) { + myShortClassNameIndex.close(); // only close if you own the context final DependencyContext context = myContext; if (context != null) { @@ -2247,6 +2288,7 @@ public class Mappings { myClassToSourceFile.flush(memoryCachesOnly); if (!myIsDelta) { + myShortClassNameIndex.flush(memoryCachesOnly); // flush if you own the context final DependencyContext context = myContext; if (context != null) { @@ -2312,6 +2354,14 @@ public class Mappings { addChangedClass(cr.name); } + private void addAddedClass(final ClassRepr cr) { + assert (myAddedClasses != null); + + myAddedClasses.add(cr); + + addChangedClass(cr.name); + } + private void addChangedClass(final int it) { assert (myChangedClasses != null && myChangedFiles != null); myChangedClasses.add(it); @@ -2328,6 +2378,11 @@ public class Mappings { return myDeletedClasses == null ? Collections.emptySet() : Collections.unmodifiableSet(myDeletedClasses); } + @NotNull + private Set getAddedClasses() { + return myAddedClasses == null ? Collections.emptySet() : Collections.unmodifiableSet(myAddedClasses); + } + private TIntHashSet getChangedClasses() { return myChangedClasses; } @@ -2390,6 +2445,7 @@ public class Mappings { myClassToClassDependency, mySourceFileToClasses, myClassToSourceFile, + myShortClassNameIndex }; final String[] info = { @@ -2397,6 +2453,7 @@ public class Mappings { "ClassToClassDependency", "SourceFileToClasses", "ClassToSourceFile", + "ShortClassNameIndex" }; for (int i = 0; i < data.length; i++) { diff --git a/jps/jps-builders/src/org/jetbrains/jps/client/ProtobufClientMessageHandler.java b/jps/jps-builders/src/org/jetbrains/jps/client/ProtobufClientMessageHandler.java index 81acebb74026..821a2ffea980 100644 --- a/jps/jps-builders/src/org/jetbrains/jps/client/ProtobufClientMessageHandler.java +++ b/jps/jps-builders/src/org/jetbrains/jps/client/ProtobufClientMessageHandler.java @@ -34,7 +34,7 @@ import java.util.concurrent.Executor; */ @ChannelHandler.Sharable final class ProtobufClientMessageHandler extends SimpleChannelInboundHandler { - private final ConcurrentHashMap> myHandlers = new ConcurrentHashMap>(); + private final ConcurrentHashMap> myHandlers = new ConcurrentHashMap>(16, 0.75f, 1); @NotNull private final UUIDGetter myUuidGetter; private final SimpleProtobufClient myClient; diff --git a/jps/jps-builders/src/org/jetbrains/jps/incremental/IncProjectBuilder.java b/jps/jps-builders/src/org/jetbrains/jps/incremental/IncProjectBuilder.java index 24cbd84aa914..8bc64536a451 100644 --- a/jps/jps-builders/src/org/jetbrains/jps/incremental/IncProjectBuilder.java +++ b/jps/jps-builders/src/org/jetbrains/jps/incremental/IncProjectBuilder.java @@ -88,6 +88,7 @@ public class IncProjectBuilder { maxThreads = Math.max(2, Integer.parseInt(System.getProperty(GlobalOptions.COMPILE_PARALLEL_MAX_THREADS_OPTION, Integer.toString(maxThreads)))); } catch (NumberFormatException ignored) { + maxThreads = Math.max(2, maxThreads); } MAX_BUILDER_THREADS = maxThreads; } @@ -632,9 +633,7 @@ public class IncProjectBuilder { } private class BuildParallelizer { - private final BoundedTaskExecutor myParallelBuildExecutor = - new BoundedTaskExecutor(SharedThreadPool.getInstance(), - Math.min(MAX_BUILDER_THREADS, Math.max(2, Runtime.getRuntime().availableProcessors()))); + private final BoundedTaskExecutor myParallelBuildExecutor = new BoundedTaskExecutor(SharedThreadPool.getInstance(), MAX_BUILDER_THREADS); private final CompileContext myContext; private final AtomicReference myException = new AtomicReference(); private final Object myQueueLock = new Object(); diff --git a/jps/jps-builders/src/org/jetbrains/jps/incremental/storage/BuildDataManager.java b/jps/jps-builders/src/org/jetbrains/jps/incremental/storage/BuildDataManager.java index 1a0ce3bdc1d6..791e2e291f73 100644 --- a/jps/jps-builders/src/org/jetbrains/jps/incremental/storage/BuildDataManager.java +++ b/jps/jps-builders/src/org/jetbrains/jps/incremental/storage/BuildDataManager.java @@ -41,7 +41,7 @@ import java.util.concurrent.ConcurrentMap; * Date: 10/7/11 */ public class BuildDataManager implements StorageOwner { - private static final int VERSION = 20; + private static final int VERSION = 21; private static final Logger LOG = Logger.getInstance("#org.jetbrains.jps.incremental.storage.BuildDataManager"); private static final String SRC_TO_FORM_STORAGE = "src-form"; private static final String MAPPINGS_STORAGE = "mappings"; diff --git a/jps/jps-builders/src/org/jetbrains/jps/incremental/storage/BuildTargetTypeState.java b/jps/jps-builders/src/org/jetbrains/jps/incremental/storage/BuildTargetTypeState.java index e9e2291a166a..d7053cbb4cd4 100644 --- a/jps/jps-builders/src/org/jetbrains/jps/incremental/storage/BuildTargetTypeState.java +++ b/jps/jps-builders/src/org/jetbrains/jps/incremental/storage/BuildTargetTypeState.java @@ -17,7 +17,6 @@ package org.jetbrains.jps.incremental.storage; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.util.io.FileUtil; -import com.intellij.util.containers.ConcurrentHashMap; import com.intellij.util.io.IOUtil; import org.jetbrains.jps.builders.BuildTarget; import org.jetbrains.jps.builders.BuildTargetLoader; @@ -26,6 +25,7 @@ import org.jetbrains.jps.builders.BuildTargetType; import java.io.*; import java.util.HashMap; import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; /** @@ -43,7 +43,7 @@ public class BuildTargetTypeState { myTargetType = targetType; myTargetsState = state; myTargetsFile = new File(state.getDataPaths().getTargetTypeDataRoot(targetType), "targets.dat"); - myConfigurations = new ConcurrentHashMap, BuildTargetConfiguration>(); + myConfigurations = new ConcurrentHashMap, BuildTargetConfiguration>(16, 0.75f, 1); myTargetIds = new HashMap, Integer>(); load(); } diff --git a/jps/jps-builders/src/org/jetbrains/jps/incremental/storage/BuildTargetsState.java b/jps/jps-builders/src/org/jetbrains/jps/incremental/storage/BuildTargetsState.java index b4294293dc86..ad0f85d6dfdf 100644 --- a/jps/jps-builders/src/org/jetbrains/jps/incremental/storage/BuildTargetsState.java +++ b/jps/jps-builders/src/org/jetbrains/jps/incremental/storage/BuildTargetsState.java @@ -17,7 +17,6 @@ package org.jetbrains.jps.incremental.storage; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.util.io.FileUtil; -import com.intellij.util.containers.ConcurrentHashMap; import org.jetbrains.annotations.NotNull; import org.jetbrains.jps.builders.BuildTarget; import org.jetbrains.jps.builders.BuildTargetType; @@ -27,6 +26,7 @@ import org.jetbrains.jps.incremental.TargetTypeRegistry; import org.jetbrains.jps.model.JpsModel; import java.io.*; +import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.atomic.AtomicInteger; @@ -37,7 +37,7 @@ public class BuildTargetsState { private static final Logger LOG = Logger.getInstance("#org.jetbrains.jps.incremental.storage.BuildTargetsState"); private final BuildDataPaths myDataPaths; private AtomicInteger myMaxTargetId = new AtomicInteger(0); - private ConcurrentMap, BuildTargetTypeState> myTypeStates = new ConcurrentHashMap, BuildTargetTypeState>(); + private ConcurrentMap, BuildTargetTypeState> myTypeStates = new ConcurrentHashMap, BuildTargetTypeState>(16, 0.75f, 1); private JpsModel myModel; private final BuildRootIndexImpl myBuildRootIndex; @@ -99,9 +99,11 @@ public class BuildTargetsState { private BuildTargetTypeState getTypeState(BuildTargetType type) { BuildTargetTypeState state = myTypeStates.get(type); if (state == null) { - state = new BuildTargetTypeState(type, this); - myTypeStates.putIfAbsent(type, state); - state = myTypeStates.get(type); + final BuildTargetTypeState newState = new BuildTargetTypeState(type, this); + state = myTypeStates.putIfAbsent(type, newState); + if (state == null) { + state = newState; + } } return state; } diff --git a/jps/jps-builders/src/org/jetbrains/jps/javac/OptimizedFileManager.java b/jps/jps-builders/src/org/jetbrains/jps/javac/OptimizedFileManager.java index c63614e17895..c848aef58a75 100644 --- a/jps/jps-builders/src/org/jetbrains/jps/javac/OptimizedFileManager.java +++ b/jps/jps-builders/src/org/jetbrains/jps/javac/OptimizedFileManager.java @@ -542,6 +542,7 @@ class OptimizedFileManager extends DefaultFileManager { myDirectoryCache.clear(); myByteBufferCache.clear(); myIsFile.clear(); + Paths.clearPathExistanceCache(); } } } diff --git a/jps/jps-builders/testSrc/org/jetbrains/ether/CommonTest.java b/jps/jps-builders/testSrc/org/jetbrains/ether/CommonTest.java index 8f97b867cdbd..7adfbea6124f 100644 --- a/jps/jps-builders/testSrc/org/jetbrains/ether/CommonTest.java +++ b/jps/jps-builders/testSrc/org/jetbrains/ether/CommonTest.java @@ -113,4 +113,9 @@ public class CommonTest extends IncrementalTestCase { public void testAddDuplicateClass() throws Exception { doTest(); } + + public void testAddClassHidingImportedClass() throws Exception { + doTest(); + } + } diff --git a/jps/lib/optimizedFileManager.jar b/jps/lib/optimizedFileManager.jar index 55b4e61617f5..9900a870a99b 100644 Binary files a/jps/lib/optimizedFileManager.jar and b/jps/lib/optimizedFileManager.jar differ diff --git a/jps/model-impl/src/org/jetbrains/jps/service/impl/JpsServiceManagerImpl.java b/jps/model-impl/src/org/jetbrains/jps/service/impl/JpsServiceManagerImpl.java index 750469071360..3a33747b85da 100644 --- a/jps/model-impl/src/org/jetbrains/jps/service/impl/JpsServiceManagerImpl.java +++ b/jps/model-impl/src/org/jetbrains/jps/service/impl/JpsServiceManagerImpl.java @@ -24,8 +24,8 @@ import java.util.concurrent.ConcurrentHashMap; * @author nik */ public class JpsServiceManagerImpl extends JpsServiceManager { - private final ConcurrentHashMap myServices = new ConcurrentHashMap(); - private final ConcurrentHashMap> myExtensions = new ConcurrentHashMap>(); + private final ConcurrentHashMap myServices = new ConcurrentHashMap(16, 0.75f, 1); + private final ConcurrentHashMap> myExtensions = new ConcurrentHashMap>(16, 0.75f, 1); @Override public T getService(Class serviceClass) { @@ -36,14 +36,16 @@ public class JpsServiceManagerImpl extends JpsServiceManager { if (!iterator.hasNext()) { throw new ServiceConfigurationError("Implementation for " + serviceClass + " not found"); } - service = iterator.next(); + final T loadedService = iterator.next(); if (iterator.hasNext()) { throw new ServiceConfigurationError( - "More than one implementation for " + serviceClass + " found: " + service.getClass() + " and " + iterator.next().getClass()); + "More than one implementation for " + serviceClass + " found: " + loadedService.getClass() + " and " + iterator.next().getClass()); } - myServices.putIfAbsent(serviceClass, service); //noinspection unchecked - service = (T)myServices.get(serviceClass); + service = (T)myServices.putIfAbsent(serviceClass, loadedService); + if (service == null) { + service = loadedService; + } } return service; } @@ -53,12 +55,14 @@ public class JpsServiceManagerImpl extends JpsServiceManager { List cached = myExtensions.get(extensionClass); if (cached == null) { final ServiceLoader loader = ServiceLoader.load(extensionClass, extensionClass.getClassLoader()); - List extensions = new ArrayList(); + final List extensions = new ArrayList(); for (T t : loader) { extensions.add(t); } - myExtensions.putIfAbsent(extensionClass, extensions); - cached = myExtensions.get(extensionClass); + cached = myExtensions.putIfAbsent(extensionClass, extensions); + if (cached == null) { + cached = extensions; + } } //noinspection unchecked return (List)cached; diff --git a/lib/pty4j-0.3.jar b/lib/pty4j-0.3.jar index 94b515636331..8ffcc9c0d67b 100644 Binary files a/lib/pty4j-0.3.jar and b/lib/pty4j-0.3.jar differ diff --git a/platform/analysis-impl/src/com/intellij/codeInspection/ex/ToolsImpl.java b/platform/analysis-impl/src/com/intellij/codeInspection/ex/ToolsImpl.java index a017575a3f27..f8d215ceee24 100644 --- a/platform/analysis-impl/src/com/intellij/codeInspection/ex/ToolsImpl.java +++ b/platform/analysis-impl/src/com/intellij/codeInspection/ex/ToolsImpl.java @@ -145,7 +145,9 @@ public class ToolsImpl implements Tools { scopeElement.setAttribute(LEVEL_ATTRIBUTE, state.getLevel().toString()); scopeElement.setAttribute(ENABLED_ATTRIBUTE, Boolean.toString(state.isEnabled())); InspectionToolWrapper toolWrapper = state.getTool(); - toolWrapper.getTool().writeSettings(scopeElement); + if (toolWrapper.isInitialized()) { + toolWrapper.getTool().writeSettings(scopeElement); + } inspectionElement.addContent(scopeElement); } } @@ -153,7 +155,9 @@ public class ToolsImpl implements Tools { inspectionElement.setAttribute(LEVEL_ATTRIBUTE, getLevel().toString()); inspectionElement.setAttribute(ENABLED_BY_DEFAULT_ATTRIBUTE, Boolean.toString(myDefaultState.isEnabled())); InspectionToolWrapper toolWrapper = myDefaultState.getTool(); - toolWrapper.getTool().writeSettings(inspectionElement); + if (toolWrapper.isInitialized()) { + toolWrapper.getTool().writeSettings(inspectionElement); + } } void readExternal(@NotNull Element toolElement, @NotNull InspectionProfile profile) throws InvalidDataException { diff --git a/platform/core-impl/src/com/intellij/psi/impl/source/text/BlockSupportImpl.java b/platform/core-impl/src/com/intellij/psi/impl/source/text/BlockSupportImpl.java index 1452ed0d53a4..695e948cce32 100644 --- a/platform/core-impl/src/com/intellij/psi/impl/source/text/BlockSupportImpl.java +++ b/platform/core-impl/src/com/intellij/psi/impl/source/text/BlockSupportImpl.java @@ -106,7 +106,9 @@ public class BlockSupportImpl extends BlockSupport { if (baseLanguage.isKindOf(reparseable.getLanguage())) { final int start = textRange.getStartOffset(); final int end = start + textRange.getLength() + lengthShift; - assertFileLength(file, newFileText, node, elementType, start, end); + if (!assertFileLength(file, newFileText, node, elementType, start, end)) { + break; + } CharSequence newTextStr = newFileText.subSequence(start, end); @@ -134,11 +136,13 @@ public class BlockSupportImpl extends BlockSupport { return makeFullParse(node, newFileText, textLength, fileImpl, indicator); } - private static void assertFileLength(PsiFile file, CharSequence newFileText, ASTNode node, IElementType elementType, int start, int end) { - if (end > newFileText.length() && ApplicationManager.getApplication().isInternal()) { + private static boolean assertFileLength(PsiFile file, CharSequence newFileText, ASTNode node, IElementType elementType, int start, int end) { + if ((end > newFileText.length() || start > end) && ApplicationManager.getApplication().isInternal()) { String newTextBefore = newFileText.subSequence(0, start).toString(); String oldTextBefore = file.getText().subSequence(0, start).toString(); String message = "IOOBE: type=" + elementType + + "; start=" + start + + "; end=" + end + "; oldText=" + node.getText() + "; newText=" + newFileText.subSequence(start, newFileText.length()) + "; length=" + node.getTextLength(); @@ -148,8 +152,10 @@ public class BlockSupportImpl extends BlockSupport { message += "; oldTextBefore=" + oldTextBefore + "; newTextBefore=" + newTextBefore; } - throw new AssertionError(message); + LOG.error(message); + return false; } + return true; } @NotNull diff --git a/platform/external-system-api/resources/i18n/ExternalSystemBundle.properties b/platform/external-system-api/resources/i18n/ExternalSystemBundle.properties index 17078c097875..a8660af76cb0 100644 --- a/platform/external-system-api/resources/i18n/ExternalSystemBundle.properties +++ b/platform/external-system-api/resources/i18n/ExternalSystemBundle.properties @@ -11,6 +11,7 @@ setting.type.location.explicit.correct={0} location is defined setting.type.location.explicit.incorrect={0} location is incorrect settings.label.select.project={0} project: settings.label.use.auto.import=Use auto-import +settings.label.create.empty.content.root.directories=Create directories for empty content roots automatically settings.title.linked.projects=Linked {0} projects settings.title.project.settings=Project-level settings settings.title.system.settings=Global {0} settings @@ -59,6 +60,8 @@ run.configuration.settings.label.project={0} project: run.configuration.settings.label.tasks=Tasks: run.configuration.settings.label.vmoptions=VM options: run.configuration.settings.caption.vmoptions=VM options: -run.text.starting.multiple.task=Executing external tasks ''{0}''...\n -run.text.starting.single.task=Executing external task ''{0}''...\n +run.text.starting.multiple.task={0}: Executing external tasks ''{1}''...\n +run.text.starting.single.task={0}: Executing external task ''{1}''...\n +run.text.ended.multiple.task={0}: External tasks execution finished ''{1}''.\n +run.text.ended.single.task={0}: External task execution finished ''{1}''.\n run.error.undefined.task=No task to execute is specified \ No newline at end of file diff --git a/platform/external-system-api/src/com/intellij/openapi/externalSystem/model/project/AbstractDependencyData.java b/platform/external-system-api/src/com/intellij/openapi/externalSystem/model/project/AbstractDependencyData.java index a765ef5a8fd0..fb82dfe4d2cc 100644 --- a/platform/external-system-api/src/com/intellij/openapi/externalSystem/model/project/AbstractDependencyData.java +++ b/platform/external-system-api/src/com/intellij/openapi/externalSystem/model/project/AbstractDependencyData.java @@ -77,6 +77,7 @@ public abstract class AbstractDependencyData that = (AbstractDependencyData)o; - return myOwnerModule.equals(that.myOwnerModule) && myTarget.equals(that.myTarget); + return myScope.equals(that.myScope) && myOwnerModule.equals(that.myOwnerModule) && myTarget.equals(that.myTarget); } @Override diff --git a/platform/external-system-api/src/com/intellij/openapi/externalSystem/settings/ExternalProjectSettings.java b/platform/external-system-api/src/com/intellij/openapi/externalSystem/settings/ExternalProjectSettings.java index c7a6ecbd5443..c3e68dea3942 100644 --- a/platform/external-system-api/src/com/intellij/openapi/externalSystem/settings/ExternalProjectSettings.java +++ b/platform/external-system-api/src/com/intellij/openapi/externalSystem/settings/ExternalProjectSettings.java @@ -28,6 +28,7 @@ public abstract class ExternalProjectSettings implements Comparable 1) { - greeting = ExternalSystemBundle.message("run.text.starting.multiple.task", StringUtil.join(mySettings.getTaskNames(), " ")); + greeting = ExternalSystemBundle.message("run.text.starting.multiple.task", startDateTime, StringUtil.join(mySettings.getTaskNames(), " ")); } else { - greeting = ExternalSystemBundle.message("run.text.starting.single.task", StringUtil.join(mySettings.getTaskNames(), " ")); + greeting = ExternalSystemBundle.message("run.text.starting.single.task", startDateTime, StringUtil.join(mySettings.getTaskNames(), " ")); } processHandler.notifyTextAvailable(greeting, ProcessOutputTypes.SYSTEM); task.execute(new ExternalSystemTaskNotificationListenerAdapter() { @@ -189,6 +191,15 @@ public class ExternalSystemRunConfiguration extends LocatableConfigurationBase { @Override public void onEnd(@NotNull ExternalSystemTaskId id) { + final String endDateTime = DateFormatUtil.formatTimeWithSeconds(System.currentTimeMillis()); + final String farewell; + if (mySettings.getTaskNames().size() > 1) { + farewell = ExternalSystemBundle.message("run.text.ended.multiple.task", endDateTime, StringUtil.join(mySettings.getTaskNames(), " ")); + } + else { + farewell = ExternalSystemBundle.message("run.text.ended.single.task", endDateTime, StringUtil.join(mySettings.getTaskNames(), " ")); + } + processHandler.notifyTextAvailable(farewell, ProcessOutputTypes.SYSTEM); processHandler.notifyProcessTerminated(0); } }); diff --git a/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/project/manage/ContentRootDataService.java b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/project/manage/ContentRootDataService.java index ad37b00fbb2b..e0c52255fb58 100644 --- a/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/project/manage/ContentRootDataService.java +++ b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/project/manage/ContentRootDataService.java @@ -4,10 +4,13 @@ import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.externalSystem.model.DataNode; import com.intellij.openapi.externalSystem.model.Key; import com.intellij.openapi.externalSystem.model.ProjectKeys; +import com.intellij.openapi.externalSystem.model.ProjectSystemId; import com.intellij.openapi.externalSystem.model.project.ContentRootData; import com.intellij.openapi.externalSystem.model.project.ExternalSystemSourceType; import com.intellij.openapi.externalSystem.model.project.ModuleData; import com.intellij.openapi.externalSystem.service.project.ProjectStructureHelper; +import com.intellij.openapi.externalSystem.settings.AbstractExternalSystemSettings; +import com.intellij.openapi.externalSystem.settings.ExternalProjectSettings; import com.intellij.openapi.externalSystem.util.DisposeAwareProjectChange; import com.intellij.openapi.externalSystem.util.ExternalSystemApiUtil; import com.intellij.openapi.externalSystem.util.ExternalSystemConstants; @@ -95,30 +98,45 @@ public class ContentRootDataService implements ProjectDataService data : datas) { final ContentRootData contentRoot = data.getData(); + final ContentEntry contentEntry = findOrCreateContentRoot(model, contentRoot.getRootPath()); contentEntry.clearExcludeFolders(); contentEntry.clearSourceFolders(); LOG.info(String.format("Importing content root '%s' for module '%s'", contentRoot.getRootPath(), module.getName())); for (String path : contentRoot.getPaths(ExternalSystemSourceType.SOURCE)) { - createSourceRootIfAbsent(contentEntry, path, module.getName(), JavaSourceRootType.SOURCE, false); + createSourceRootIfAbsent(contentEntry, path, module.getName(), JavaSourceRootType.SOURCE, false, createEmptyContentRootDirectories); } for (String path : contentRoot.getPaths(ExternalSystemSourceType.TEST)) { - createSourceRootIfAbsent(contentEntry, path, module.getName(), JavaSourceRootType.TEST_SOURCE, false); + createSourceRootIfAbsent(contentEntry, path, module.getName(), JavaSourceRootType.TEST_SOURCE, false, createEmptyContentRootDirectories); } for (String path : contentRoot.getPaths(ExternalSystemSourceType.RESOURCE)) { - createSourceRootIfAbsent(contentEntry, path, module.getName(), JavaResourceRootType.RESOURCE, false); + createSourceRootIfAbsent(contentEntry, path, module.getName(), JavaResourceRootType.RESOURCE, false, createEmptyContentRootDirectories); } for (String path : contentRoot.getPaths(ExternalSystemSourceType.TEST_RESOURCE)) { - createSourceRootIfAbsent(contentEntry, path, module.getName(), JavaResourceRootType.TEST_RESOURCE, false); + createSourceRootIfAbsent(contentEntry, path, module.getName(), JavaResourceRootType.TEST_RESOURCE, false, createEmptyContentRootDirectories); } for (String path : contentRoot.getPaths(ExternalSystemSourceType.SOURCE_GENERATED)) { - createSourceRootIfAbsent(contentEntry, path, module.getName(), JavaSourceRootType.SOURCE, true); + createSourceRootIfAbsent(contentEntry, path, module.getName(), JavaSourceRootType.SOURCE, true, createEmptyContentRootDirectories); } for (String path : contentRoot.getPaths(ExternalSystemSourceType.TEST_GENERATED)) { - createSourceRootIfAbsent(contentEntry, path, module.getName(), JavaSourceRootType.TEST_SOURCE, true); + createSourceRootIfAbsent(contentEntry, path, module.getName(), JavaSourceRootType.TEST_SOURCE, true, createEmptyContentRootDirectories); } for (String path : contentRoot.getPaths(ExternalSystemSourceType.EXCLUDED)) { createExcludedRootIfAbsent(contentEntry, path, module.getName()); @@ -154,7 +172,7 @@ public class ContentRootDataService implements ProjectDataService folders = entry.getSourceFolders(sourceRootType); for (SourceFolder folder : folders) { VirtualFile file = folder.getFile(); @@ -173,11 +191,13 @@ public class ContentRootDataService implements ProjectDataService/* library paths */, LibraryDependencyData> moduleLibrariesToImport = ContainerUtilRt.newHashMap(); - Map projectLibrariesToImport = ContainerUtilRt.newHashMap(); + Map projectLibrariesToImport = ContainerUtilRt.newHashMap(); Set toImport = ContainerUtilRt.newLinkedHashSet(); boolean hasUnresolved = false; @@ -132,7 +132,7 @@ public class LibraryDependencyDataService extends AbstractDependencyDataService< } break; case PROJECT: - projectLibrariesToImport.put(ExternalSystemApiUtil.getLibraryName(libraryData), dependencyData); + projectLibrariesToImport.put(ExternalSystemApiUtil.getLibraryName(libraryData) + dependencyData.getScope().name(), dependencyData); toImport.add(dependencyData); } } @@ -224,8 +224,8 @@ public class LibraryDependencyDataService extends AbstractDependencyDataService< else if (entry instanceof LibraryOrderEntry) { final LibraryOrderEntry libraryOrderEntry = (LibraryOrderEntry)entry; final String libraryName = libraryOrderEntry.getLibraryName(); - final LibraryDependencyData existing = projectLibrariesToImport.remove(libraryName); - if (existing != null && libraryOrderEntry.getScope() == existing.getScope()) { + final LibraryDependencyData existing = projectLibrariesToImport.remove(libraryName + libraryOrderEntry.getScope().name()); + if (existing != null) { toImport.remove(existing); } else if (!hasUnresolvedLibraries) { diff --git a/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/settings/AbstractExternalProjectSettingsControl.java b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/settings/AbstractExternalProjectSettingsControl.java index a7d09ebc58d9..c44eb9123a42 100644 --- a/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/settings/AbstractExternalProjectSettingsControl.java +++ b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/settings/AbstractExternalProjectSettingsControl.java @@ -37,6 +37,7 @@ public abstract class AbstractExternalProjectSettingsControl myPathsToProcessCollapseState = ContainerUtilRt.newHashSet(); - + @NotNull private final Map myExpandedStateHolder; private boolean mySuppressCollapseTracking; @@ -86,7 +88,7 @@ public class ExternalSystemTasksTree extends Tree implements Producer map = ContainerUtil.newHashMap(); + for (TreePath selectionPath : selectionPaths) { + Object component = selectionPath.getLastPathComponent(); + if (!(component instanceof ExternalSystemNode)) { + continue; + } + + Object element = ((ExternalSystemNode)component).getDescriptor().getElement(); + if (element instanceof ExternalTaskExecutionInfo) { + ExternalTaskExecutionInfo taskExecutionInfo = (ExternalTaskExecutionInfo)element; + ExternalSystemTaskExecutionSettings executionSettings = taskExecutionInfo.getSettings(); + String key = executionSettings.getExternalSystemIdString() + executionSettings.getExternalProjectPath() + executionSettings.getVmOptions(); + ExternalTaskExecutionInfo executionInfo = map.get(key); + if(executionInfo == null) { + ExternalSystemTaskExecutionSettings taskExecutionSettings = new ExternalSystemTaskExecutionSettings(); + taskExecutionSettings.setExternalProjectPath(executionSettings.getExternalProjectPath()); + taskExecutionSettings.setExternalSystemIdString(executionSettings.getExternalSystemIdString()); + taskExecutionSettings.setVmOptions(executionSettings.getVmOptions()); + executionInfo = new ExternalTaskExecutionInfo(taskExecutionSettings, taskExecutionInfo.getExecutorId()); + map.put(key, executionInfo); + } + executionInfo.getSettings().getTaskNames().addAll(executionSettings.getTaskNames()); + executionInfo.getSettings().getTaskDescriptions().addAll(executionSettings.getTaskDescriptions()); + } + } + + // Disable tasks execution if it comes from different projects + if(map.values().size() > 1) return null; + return map.values().iterator().next(); } } diff --git a/platform/external-system-impl/testSrc/com/intellij/openapi/externalSystem/service/project/ExternalProjectServiceTest.groovy b/platform/external-system-impl/testSrc/com/intellij/openapi/externalSystem/service/project/ExternalProjectServiceTest.groovy index b763920caf7c..cdbd81190895 100644 --- a/platform/external-system-impl/testSrc/com/intellij/openapi/externalSystem/service/project/ExternalProjectServiceTest.groovy +++ b/platform/external-system-impl/testSrc/com/intellij/openapi/externalSystem/service/project/ExternalProjectServiceTest.groovy @@ -54,7 +54,7 @@ public class ExternalProjectServiceTest extends AbstractExternalSystemTest { dependencies[name]++ } } - ExternalSystemTestUtil.assertMapsEqual(['lib1': 1, 'lib2': 1], dependencies) + ExternalSystemTestUtil.assertMapsEqual(['Test_external_system_id: lib1': 1, 'Test_external_system_id: lib2': 1], dependencies) } void 'test changes in a project layout (content roots) could be detected on Refresh'() { diff --git a/platform/lang-api/src/com/intellij/execution/filters/HyperlinkInfoFactory.java b/platform/lang-api/src/com/intellij/execution/filters/HyperlinkInfoFactory.java new file mode 100644 index 000000000000..42beb03faeff --- /dev/null +++ b/platform/lang-api/src/com/intellij/execution/filters/HyperlinkInfoFactory.java @@ -0,0 +1,37 @@ +/* + * 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 com.intellij.execution.filters; + +import com.intellij.openapi.components.ServiceManager; +import com.intellij.openapi.project.Project; +import com.intellij.openapi.vfs.VirtualFile; +import org.jetbrains.annotations.NotNull; + +import java.util.List; + +/** + * @author nik + */ +public abstract class HyperlinkInfoFactory { + @NotNull + public static HyperlinkInfoFactory getInstance() { + return ServiceManager.getService(HyperlinkInfoFactory.class); + } + + @NotNull + public abstract HyperlinkInfo createMultipleFilesHyperlinkInfo(@NotNull List files, + int line, @NotNull Project project); +} diff --git a/platform/lang-impl/src/com/intellij/application/options/codeStyle/CodeStyleSchemesUIConfiguration.java b/platform/lang-impl/src/com/intellij/application/options/codeStyle/CodeStyleSchemesUIConfiguration.java index 75784fc1e525..7780f7ae9c41 100644 --- a/platform/lang-impl/src/com/intellij/application/options/codeStyle/CodeStyleSchemesUIConfiguration.java +++ b/platform/lang-impl/src/com/intellij/application/options/codeStyle/CodeStyleSchemesUIConfiguration.java @@ -75,7 +75,10 @@ public class CodeStyleSchemesUIConfiguration implements PersistentStateComponent public static void setRecentImportFile(@NotNull VirtualFile recentFile) { CodeStyleSchemesUIConfiguration configuration = getInstance(); if (configuration != null) { - configuration.RECENT_IMPORT_FILE_LOCATION = recentFile.getUrl(); + URL url = VfsUtil.convertToURL(recentFile.getUrl()); + if (url != null) { + configuration.RECENT_IMPORT_FILE_LOCATION = url.toString(); + } } } } diff --git a/platform/lang-impl/src/com/intellij/codeInsight/completion/CodeCompletionHandlerBase.java b/platform/lang-impl/src/com/intellij/codeInsight/completion/CodeCompletionHandlerBase.java index c5c5d6fe1737..c4ff55b2972a 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/completion/CodeCompletionHandlerBase.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/completion/CodeCompletionHandlerBase.java @@ -45,8 +45,8 @@ import com.intellij.openapi.project.IndexNotReadyException; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Disposer; import com.intellij.openapi.util.Key; -import com.intellij.openapi.util.Pair; import com.intellij.openapi.util.Ref; +import com.intellij.openapi.util.Trinity; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.PsiDocumentManager; @@ -457,7 +457,7 @@ public class CodeCompletionHandlerBase { public void run() { AccessToken token = WriteAction.start(); try { - hostCopy[0] = createFileCopy(hostFile); + hostCopy[0] = createFileCopy(hostFile, initContext.getStartOffset(), initContext.getSelectionEndOffset()); } finally { token.finish(); @@ -748,7 +748,7 @@ public class CodeCompletionHandlerBase { } } - public static final Key>> FILE_COPY_KEY = Key.create("CompletionFileCopy"); + private static final Key>> FILE_COPY_KEY = Key.create("CompletionFileCopy"); private static boolean isCopyUpToDate(Document document, @NotNull PsiFile file) { if (!file.isValid()) { @@ -760,31 +760,37 @@ public class CodeCompletionHandlerBase { return current != null && current.getViewProvider().getPsi(file.getLanguage()) == file; } - private static PsiFile createFileCopy(PsiFile file) { + private static PsiFile createFileCopy(PsiFile file, long caret, long selEnd) { final VirtualFile virtualFile = file.getVirtualFile(); - if (file.isPhysical() && virtualFile != null && virtualFile.isInLocalFileSystem() - // must not cache injected file copy, since it does not reflect changes in host document - && !InjectedLanguageManager.getInstance(file.getProject()).isInjectedFragment(file)) { - final SoftReference> reference = file.getUserData(FILE_COPY_KEY); - if (reference != null) { - final Pair pair = reference.get(); - if (pair != null && pair.first.getClass().equals(file.getClass()) && isCopyUpToDate(pair.second, pair.first)) { - final PsiFile copy = pair.first; - if (copy.getViewProvider().getModificationStamp() > file.getViewProvider().getModificationStamp()) { - ((PsiModificationTrackerImpl) file.getManager().getModificationTracker()).incCounter(); - } - final Document document = pair.second; - assert document != null; - document.setText(file.getText()); - return copy; + boolean mayCacheCopy = file.isPhysical() && + // we don't want to cache code fragment copies even if they appear to be physical + virtualFile != null && virtualFile.isInLocalFileSystem(); + long combinedOffsets = caret + (selEnd << 32); + if (mayCacheCopy) { + final Trinity cached = SoftReference.dereference(file.getUserData(FILE_COPY_KEY)); + if (cached != null && cached.first.getClass().equals(file.getClass()) && isCopyUpToDate(cached.second, cached.first)) { + final PsiFile copy = cached.first; + if (copy.getViewProvider().getModificationStamp() > file.getViewProvider().getModificationStamp() && + cached.third.longValue() != combinedOffsets) { + // the copy PSI might have some caches that are not cleared on its modification because there are no events in the copy + // so, clear all the caches + // hopefully it's a rare situation that the user invokes completion in different parts of the file + // without modifying anything physical in between + ((PsiModificationTrackerImpl) file.getManager().getModificationTracker()).incCounter(); } + final Document document = cached.second; + assert document != null; + document.setText(file.getText()); + return copy; } } final PsiFile copy = (PsiFile)file.copy(); - final Document document = copy.getViewProvider().getDocument(); - assert document != null; - file.putUserData(FILE_COPY_KEY, new SoftReference>(Pair.create(copy, document))); + if (mayCacheCopy) { + final Document document = copy.getViewProvider().getDocument(); + assert document != null; + file.putUserData(FILE_COPY_KEY, new SoftReference>(Trinity.create(copy, document, combinedOffsets))); + } return copy; } diff --git a/platform/lang-impl/src/com/intellij/codeInspection/ui/DefaultInspectionToolPresentation.java b/platform/lang-impl/src/com/intellij/codeInspection/ui/DefaultInspectionToolPresentation.java index 14be260ed63d..212489bda65f 100644 --- a/platform/lang-impl/src/com/intellij/codeInspection/ui/DefaultInspectionToolPresentation.java +++ b/platform/lang-impl/src/com/intellij/codeInspection/ui/DefaultInspectionToolPresentation.java @@ -91,17 +91,16 @@ public class DefaultInspectionToolPresentation implements ProblemDescriptionsPro return FileStatus.NOT_CHANGED; } - protected static HighlightSeverity getSeverity(@NotNull RefElement element, - @NotNull GlobalInspectionContextImpl context, - @NotNull InspectionToolWrapper thisToolWrapper) { + protected HighlightSeverity getSeverity(@NotNull RefElement element) { final PsiElement psiElement = element.getPointer().getContainingFile(); if (psiElement != null) { - String shortName = thisToolWrapper.getShortName(); + final GlobalInspectionContextImpl context = getContext(); + final String shortName = getSeverityDelegateName(); final Tools tools = context.getTools().get(shortName); if (tools != null) { for (ScopeToolState state : tools.getTools()) { InspectionToolWrapper toolWrapper = state.getTool(); - if (toolWrapper == thisToolWrapper) { + if (toolWrapper == getToolWrapper()) { return context.getCurrentProfile().getErrorLevel(HighlightDisplayKey.find(shortName), psiElement).getSeverity(); } } @@ -114,6 +113,10 @@ public class DefaultInspectionToolPresentation implements ProblemDescriptionsPro return null; } + protected String getSeverityDelegateName() { + return getToolWrapper().getShortName(); + } + protected static String getTextAttributeKey(@NotNull Project project, @NotNull HighlightSeverity severity, @NotNull ProblemHighlightType highlightType) { @@ -203,7 +206,7 @@ public class DefaultInspectionToolPresentation implements ProblemDescriptionsPro } InspectionNode toolNode = myToolNode; if (toolNode == null) { - final HighlightSeverity currentSeverity = getSeverity((RefElement)refElement, context, myToolWrapper); + final HighlightSeverity currentSeverity = getSeverity((RefElement)refElement); view.addTool(myToolWrapper, HighlightDisplayLevel.find(currentSeverity), context.getUIOptions().GROUP_BY_SEVERITY); } else if (toolNode.isTooBigForOnlineRefresh()) { @@ -437,7 +440,7 @@ public class DefaultInspectionToolPresentation implements ProblemDescriptionsPro problemClassElement.addContent(myToolWrapper.getDisplayName()); if (refEntity instanceof RefElement){ final RefElement refElement = (RefElement)refEntity; - final HighlightSeverity severity = getSeverity(refElement, getContext(), getToolWrapper()); + final HighlightSeverity severity = getSeverity(refElement); ProblemHighlightType problemHighlightType = descriptor instanceof ProblemDescriptor ? ((ProblemDescriptor)descriptor).getHighlightType() : ProblemHighlightType.GENERIC_ERROR_OR_WARNING; diff --git a/platform/lang-impl/src/com/intellij/execution/filters/impl/HyperlinkInfoFactoryImpl.java b/platform/lang-impl/src/com/intellij/execution/filters/impl/HyperlinkInfoFactoryImpl.java new file mode 100644 index 000000000000..f8a800094410 --- /dev/null +++ b/platform/lang-impl/src/com/intellij/execution/filters/impl/HyperlinkInfoFactoryImpl.java @@ -0,0 +1,36 @@ +/* + * 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 com.intellij.execution.filters.impl; + +import com.intellij.execution.filters.*; +import com.intellij.openapi.project.Project; +import com.intellij.openapi.vfs.VirtualFile; +import org.jetbrains.annotations.NotNull; + +import java.util.List; + +/** + * @author nik + */ +public class HyperlinkInfoFactoryImpl extends HyperlinkInfoFactory { + + @NotNull + @Override + public HyperlinkInfo createMultipleFilesHyperlinkInfo(@NotNull List files, + int line, @NotNull Project project) { + return new MultipleFilesHyperlinkInfo(files, line, project); + } +} diff --git a/platform/lang-impl/src/com/intellij/execution/filters/impl/MultipleFilesHyperlinkInfo.java b/platform/lang-impl/src/com/intellij/execution/filters/impl/MultipleFilesHyperlinkInfo.java new file mode 100644 index 000000000000..36dc51e15be9 --- /dev/null +++ b/platform/lang-impl/src/com/intellij/execution/filters/impl/MultipleFilesHyperlinkInfo.java @@ -0,0 +1,119 @@ +/* + * 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 com.intellij.execution.filters.impl; + +import com.intellij.execution.filters.FileHyperlinkInfo; +import com.intellij.execution.filters.HyperlinkInfoBase; +import com.intellij.execution.filters.OpenFileHyperlinkInfo; +import com.intellij.ide.util.gotoByName.GotoFileCellRenderer; +import com.intellij.openapi.application.AccessToken; +import com.intellij.openapi.application.ReadAction; +import com.intellij.openapi.fileEditor.OpenFileDescriptor; +import com.intellij.openapi.project.Project; +import com.intellij.openapi.ui.popup.JBPopup; +import com.intellij.openapi.ui.popup.JBPopupFactory; +import com.intellij.openapi.vfs.VirtualFile; +import com.intellij.openapi.wm.WindowManager; +import com.intellij.psi.PsiElement; +import com.intellij.psi.PsiFile; +import com.intellij.psi.PsiManager; +import com.intellij.ui.awt.RelativePoint; +import com.intellij.ui.components.JBList; +import com.intellij.util.containers.ContainerUtil; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.ArrayList; +import java.util.List; + +/** +* @author nik +*/ +class MultipleFilesHyperlinkInfo extends HyperlinkInfoBase implements FileHyperlinkInfo { + private final List myVirtualFiles; + private final int myLineNumber; + private final Project myProject; + + public MultipleFilesHyperlinkInfo(@NotNull List virtualFiles, int lineNumber, @NotNull Project project) { + myVirtualFiles = virtualFiles; + myLineNumber = lineNumber; + myProject = project; + } + + @Override + public void navigate(@NotNull final Project project, @Nullable RelativePoint hyperlinkLocationPoint) { + List currentFiles = new ArrayList(); + + AccessToken accessToken = ReadAction.start(); + try { + for (VirtualFile file : myVirtualFiles) { + if (!file.isValid()) continue; + + PsiFile psiFile = PsiManager.getInstance(project).findFile(file); + if (psiFile != null) { + PsiElement navigationElement = psiFile.getNavigationElement(); // Sources may be downloaded. + if (navigationElement instanceof PsiFile) { + currentFiles.add((PsiFile)navigationElement); + continue; + } + currentFiles.add(psiFile); + } + } + } + finally { + accessToken.finish(); + } + + if (currentFiles.isEmpty()) return; + + if (currentFiles.size() == 1) { + new OpenFileHyperlinkInfo(myProject, currentFiles.get(0).getVirtualFile(), myLineNumber).navigate(project); + } + else { + final JBList list = new JBList(currentFiles); + int width = WindowManager.getInstance().getFrame(project).getSize().width; + list.setCellRenderer(new GotoFileCellRenderer(width)); + JBPopup popup = JBPopupFactory.getInstance().createListPopupBuilder(list) + .setTitle("Choose Target File") + .setItemChoosenCallback(new Runnable() { + @Override + public void run() { + VirtualFile file = ((PsiFile)list.getSelectedValue()).getVirtualFile(); + new OpenFileHyperlinkInfo(myProject, file, myLineNumber).navigate(project); + } + }) + .createPopup(); + if (hyperlinkLocationPoint != null) { + popup.show(hyperlinkLocationPoint); + } + else { + popup.showInFocusCenter(); + } + } + } + + @Nullable + @Override + public OpenFileDescriptor getDescriptor() { + VirtualFile file = getPreferredFile(); + return file != null ? new OpenFileDescriptor(myProject, file, myLineNumber, 0) : null; + } + + @Nullable + private VirtualFile getPreferredFile() { + return ContainerUtil.getFirstItem(myVirtualFiles); + } +} diff --git a/platform/lang-impl/src/com/intellij/execution/impl/ConsoleViewImpl.java b/platform/lang-impl/src/com/intellij/execution/impl/ConsoleViewImpl.java index 154d1e8a36f3..2d4a9c356af1 100644 --- a/platform/lang-impl/src/com/intellij/execution/impl/ConsoleViewImpl.java +++ b/platform/lang-impl/src/com/intellij/execution/impl/ConsoleViewImpl.java @@ -65,6 +65,7 @@ import com.intellij.psi.PsiDocumentManager; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.tree.IElementType; import com.intellij.ui.EditorNotificationPanel; +import com.intellij.ui.awt.RelativePoint; import com.intellij.util.Alarm; import com.intellij.util.Consumer; import com.intellij.util.EditorPopupHandler; @@ -1384,10 +1385,18 @@ public class ConsoleViewImpl extends JPanel implements ConsoleView, ObservableCo return EditorHyperlinkSupport.getNextOccurrence(myEditor, hyperlinks.getHyperlinks().keySet(), delta, new Consumer() { @Override public void consume(RangeHighlighter next) { - scrollTo(next.getStartOffset()); + int offset = next.getStartOffset(); + scrollTo(offset); final HyperlinkInfo hyperlinkInfo = hyperlinks.getHyperlinks().get(next); if (hyperlinkInfo != null) { - hyperlinkInfo.navigate(myProject); + if (hyperlinkInfo instanceof HyperlinkInfoBase) { + VisualPosition position = myEditor.offsetToVisualPosition(offset); + Point point = myEditor.visualPositionToXY(new VisualPosition(position.getLine() + 1, position.getColumn())); + ((HyperlinkInfoBase)hyperlinkInfo).navigate(myProject, new RelativePoint(myEditor.getContentComponent(), point)); + } + else { + hyperlinkInfo.navigate(myProject); + } } } }); diff --git a/platform/lang-impl/src/com/intellij/execution/runners/RerunTestsNotification.java b/platform/lang-impl/src/com/intellij/execution/runners/RerunTestsNotification.java index 04f5bdc160a9..abb2b3b01c89 100644 --- a/platform/lang-impl/src/com/intellij/execution/runners/RerunTestsNotification.java +++ b/platform/lang-impl/src/com/intellij/execution/runners/RerunTestsNotification.java @@ -53,7 +53,7 @@ public class RerunTestsNotification { return; } - GotItMessage message = GotItMessage.createMessage("Press " + shortcutText + " to rerun tests", ""); + GotItMessage message = GotItMessage.createMessage("Rerun tests with " + shortcutText, ""); message.setDisposable(executionConsole); message.setCallback(new Runnable() { @Override diff --git a/platform/lang-impl/src/com/intellij/find/actions/FindInPathAction.java b/platform/lang-impl/src/com/intellij/find/actions/FindInPathAction.java index cc332d2ad110..4ced6fb97c3e 100644 --- a/platform/lang-impl/src/com/intellij/find/actions/FindInPathAction.java +++ b/platform/lang-impl/src/com/intellij/find/actions/FindInPathAction.java @@ -31,6 +31,10 @@ import com.intellij.psi.PsiElement; public class FindInPathAction extends AnAction implements DumbAware { static final NotificationGroup NOTIFICATION_GROUP = NotificationGroup.toolWindowGroup("FindInPath", ToolWindowId.FIND, false); + { // enabled in modal content for find in path <-> replace in path modal dialog transition + setEnabledInModalContext(true); + } + @Override public void actionPerformed(AnActionEvent e) { DataContext dataContext = e.getDataContext(); diff --git a/platform/lang-impl/src/com/intellij/find/actions/ReplaceInPathAction.java b/platform/lang-impl/src/com/intellij/find/actions/ReplaceInPathAction.java index ae7a0233c86f..eef79eed9dac 100644 --- a/platform/lang-impl/src/com/intellij/find/actions/ReplaceInPathAction.java +++ b/platform/lang-impl/src/com/intellij/find/actions/ReplaceInPathAction.java @@ -22,6 +22,10 @@ import com.intellij.openapi.actionSystem.*; import com.intellij.openapi.project.Project; public class ReplaceInPathAction extends AnAction { + { // enabled in modal content for find in path <-> replace in path modal dialog transition + setEnabledInModalContext(true); + } + @Override public void actionPerformed(AnActionEvent e) { DataContext dataContext = e.getDataContext(); diff --git a/platform/lang-impl/src/com/intellij/find/impl/FindInProjectUtil.java b/platform/lang-impl/src/com/intellij/find/impl/FindInProjectUtil.java index 9721e1b00b36..45622f0532c6 100644 --- a/platform/lang-impl/src/com/intellij/find/impl/FindInProjectUtil.java +++ b/platform/lang-impl/src/com/intellij/find/impl/FindInProjectUtil.java @@ -23,7 +23,6 @@ import com.intellij.navigation.ItemPresentation; import com.intellij.openapi.actionSystem.CommonDataKeys; import com.intellij.openapi.actionSystem.DataContext; import com.intellij.openapi.actionSystem.LangDataKeys; -import com.intellij.openapi.actionSystem.PlatformDataKeys; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.ApplicationNamesInfo; import com.intellij.openapi.editor.Document; @@ -114,6 +113,13 @@ public class FindInProjectUtil { if (model.getModuleName() == null || editor == null) { model.setDirectoryName(directoryName); model.setProjectScope(directoryName == null && module == null && !model.isCustomScope() || editor != null); + + // for convenience set directory name to directory of current file, note that we doesn't change default projectScope + if (directoryName == null) { + VirtualFile virtualFile = CommonDataKeys.VIRTUAL_FILE.getData(dataContext); + if (virtualFile != null && !virtualFile.isDirectory()) virtualFile = virtualFile.getParent(); + if (virtualFile != null) model.setDirectoryName(virtualFile.getPresentableUrl()); + } } } diff --git a/platform/lang-impl/src/com/intellij/find/impl/FindManagerImpl.java b/platform/lang-impl/src/com/intellij/find/impl/FindManagerImpl.java index b35309e40b58..936e379de8c9 100644 --- a/platform/lang-impl/src/com/intellij/find/impl/FindManagerImpl.java +++ b/platform/lang-impl/src/com/intellij/find/impl/FindManagerImpl.java @@ -454,7 +454,7 @@ public class FindManagerImpl extends FindManager implements PersistentStateCompo SyntaxHighlighter highlighter = getHighlighter(file, lang); if (highlighter == null) { - LOG.error("Syntax highlighter is null:"+file); + // no syntax highlighter -> no search return NOT_FOUND_RESULT; } @@ -467,12 +467,9 @@ public class FindManagerImpl extends FindManager implements PersistentStateCompo public Set compute() { THashSet result = new THashSet(); - for(Project project: ProjectManager.getInstance().getOpenProjects()) { - FileViewProvider viewProvider = PsiManager.getInstance(project).findViewProvider(file); - if (viewProvider != null) { - result.addAll(viewProvider.getLanguages()); - break; - } + FileViewProvider viewProvider = PsiManager.getInstance(myProject).findViewProvider(file); + if (viewProvider != null) { + result.addAll(viewProvider.getLanguages()); } if (result.isEmpty()) { diff --git a/platform/lang-impl/src/com/intellij/ide/actions/SearchEverywhereAction.java b/platform/lang-impl/src/com/intellij/ide/actions/SearchEverywhereAction.java index 81b51bfb03ba..a0ef975666ad 100644 --- a/platform/lang-impl/src/com/intellij/ide/actions/SearchEverywhereAction.java +++ b/platform/lang-impl/src/com/intellij/ide/actions/SearchEverywhereAction.java @@ -29,6 +29,7 @@ import com.intellij.ide.ui.search.BooleanOptionDescription; import com.intellij.ide.ui.search.OptionDescription; import com.intellij.ide.ui.search.SearchableOptionsRegistrarImpl; import com.intellij.ide.util.DefaultPsiElementCellRenderer; +import com.intellij.ide.util.PropertiesComponent; import com.intellij.ide.util.gotoByName.*; import com.intellij.openapi.Disposable; import com.intellij.openapi.actionSystem.*; @@ -92,6 +93,7 @@ import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; +import javax.swing.border.EmptyBorder; import javax.swing.event.DocumentEvent; import java.awt.*; import java.awt.event.*; @@ -105,6 +107,7 @@ import java.util.concurrent.atomic.AtomicLong; * @author Konstantin Bulenkov */ public class SearchEverywhereAction extends AnAction implements CustomComponentAction, DumbAware{ + public static final String SE_HISTORY_KEY = "SearchEverywhereHistory"; public static final int SEARCH_FIELD_COLUMNS = 25; private static final int MAX_CLASSES = 6; private static final int MAX_FILES = 6; @@ -149,6 +152,7 @@ public class SearchEverywhereAction extends AnAction implements CustomComponentA private static AtomicLong ourLastTimePressed = new AtomicLong(0); private static AtomicBoolean showAll = new AtomicBoolean(false); private ArrayList myAlreadyAddedFiles = new ArrayList(); + private int myHistoryIndex = 0; static { IdeEventQueue.getInstance().addPostprocessor(new IdeEventQueue.EventDispatcher() { @@ -250,8 +254,8 @@ public class SearchEverywhereAction extends AnAction implements CustomComponentA @Override protected void paintComponent(Graphics g) { if (myBalloon != null && !myBalloon.isDisposed() && myActionEvent != null && myActionEvent.getInputEvent() instanceof MouseEvent) { - ((Graphics2D)g).setPaint(new GradientPaint(0,0, new JBColor(new Color(147, 162, 174), new Color(64, 80, 94)), 0, getHeight(), - new JBColor(new Color(116, 128, 143), new Color(53, 65, 87)))); + final Gradient gradient = getGradientColors(); + ((Graphics2D)g).setPaint(new GradientPaint(0, 0, gradient.getStartColor(), 0, getHeight(), gradient.getEndColor())); g.fillRect(0,0,getWidth(), getHeight()); } else { super.paintComponent(g); @@ -299,6 +303,11 @@ public class SearchEverywhereAction extends AnAction implements CustomComponentA return panel; } + private static Gradient getGradientColors() { + return new Gradient( + new JBColor(new Color(101, 147, 242), new Color(64, 80, 94)), + new JBColor(new Color(46, 111, 205), new Color(53, 65, 87))); + } public SearchEverywhereAction() { myRenderer = new MyListRenderer(); @@ -511,6 +520,15 @@ public class SearchEverywhereAction extends AnAction implements CustomComponentA if (myPopup != null && myPopup.isVisible()) { myPopup.cancel(); } + + if (value instanceof BooleanOptionDescription) { + final BooleanOptionDescription option = (BooleanOptionDescription)value; + option.setOptionState(!option.isOptionEnabled()); + myList.revalidate(); + myList.repaint(); + return; + } + AccessToken token = ApplicationManager.getApplication().acquireReadActionLock(); try { if (value instanceof PsiElement) { @@ -531,17 +549,11 @@ public class SearchEverywhereAction extends AnAction implements CustomComponentA IdeFocusManager.getInstance(project).doWhenFocusSettlesDown(new Runnable() { @Override public void run() { - if (value instanceof BooleanOptionDescription) { - final BooleanOptionDescription option = (BooleanOptionDescription)value; - option.setOptionState(!option.isOptionEnabled()); - } - else { - Component c = comp; - if (c == null) { - c = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner(); - } - GotoActionAction.openOptionOrPerformAction(value, pattern, project, c, event); + Component c = comp; + if (c == null) { + c = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner(); } + GotoActionAction.openOptionOrPerformAction(value, pattern, project, c, event); } }); return; @@ -588,6 +600,7 @@ public class SearchEverywhereAction extends AnAction implements CustomComponentA } if (e == null) return; myContextComponent = PlatformDataKeys.CONTEXT_COMPONENT.getData(e.getDataContext()); + final Project project = e.getProject(); Window wnd = myContextComponent != null ? SwingUtilities.windowForComponent(myContextComponent) : KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusedWindow(); if (wnd == null && myContextComponent instanceof Window) { @@ -601,35 +614,53 @@ public class SearchEverywhereAction extends AnAction implements CustomComponentA myPopupField = new MySearchTextField(); initSearchField(myPopupField); myPopupField.setOpaque(false); - myPopupField.getTextEditor().setColumns(SEARCH_FIELD_COLUMNS); + final JTextField editor = myPopupField.getTextEditor(); + editor.setColumns(SEARCH_FIELD_COLUMNS); final JPanel panel = new JPanel(new BorderLayout()) { @Override protected void paintComponent(Graphics g) { - ((Graphics2D)g).setPaint(new GradientPaint(0,0, new JBColor(new Color(147, 162, 174), new Color(64, 80, 94)), 0, getHeight(), - new JBColor(new Color(116, 128, 143), new Color(53, 65, 87)))); + final Gradient gradient = getGradientColors(); + ((Graphics2D)g).setPaint(new GradientPaint(0, 0, gradient.getStartColor(), 0, getHeight(), gradient.getEndColor())); g.fillRect(0, 0, getWidth(), getHeight()); } }; final JLabel title = new JLabel(" Search Everywhere: "); final JPanel topPanel = new NonOpaquePanel(new BorderLayout()); - title.setForeground(new JBColor(Gray._50, Gray._180)); + title.setForeground(new JBColor(Gray._240, Gray._200)); if (SystemInfo.isMac) { title.setFont(title.getFont().deriveFont(Font.BOLD, title.getFont().getSize() - 1f)); } else { title.setFont(title.getFont().deriveFont(Font.BOLD)); } topPanel.add(title, BorderLayout.WEST); + myNonProjectCheckBox.setForeground(new JBColor(Gray._240, Gray._200)); myNonProjectCheckBox.setText("Include non-project items (" + getShortcut() + ")"); topPanel.add(myNonProjectCheckBox, BorderLayout.EAST); panel.add(myPopupField, BorderLayout.CENTER); panel.add(topPanel, BorderLayout.NORTH); panel.setBorder(IdeBorderFactory.createEmptyBorder(3, 5, 4, 5)); - final ComponentPopupBuilder builder = JBPopupFactory.getInstance().createComponentPopupBuilder(panel, myPopupField.getTextEditor()); + final ComponentPopupBuilder builder = JBPopupFactory.getInstance().createComponentPopupBuilder(panel, editor); myBalloon = builder .setCancelOnClickOutside(true) .setModalContext(false) + .setCancelCallback(new Computable() { + @Override + public Boolean compute() { + final String last = editor.getText().trim(); + final PropertiesComponent storage = PropertiesComponent.getInstance(project); + final String historyString = storage.getValue(SE_HISTORY_KEY); + List history = StringUtil.isEmpty(historyString) ? new ArrayList() : StringUtil.split(historyString, "\n"); + history.remove(last); + history.add(last); + if (history.size() > 10) { + history = history.subList(0, 10); + } + storage.setValue(SE_HISTORY_KEY, StringUtil.join(history, "\n")); + return true; + } + }) .createPopup(); - + myBalloon.getContent().setBorder(new EmptyBorder(0,0,0,0)); final Window window = WindowManager.getInstance().suggestParentWindow(e.getProject()); Component parent = UIUtil.findUltimateParent(window); @@ -656,7 +687,7 @@ public class SearchEverywhereAction extends AnAction implements CustomComponentA myBalloon.show(showPoint); initSearchActions(myBalloon, myPopupField); IdeFocusManager focusManager = IdeFocusManager.getInstance(e.getProject()); - focusManager.requestFocus(myPopupField.getTextEditor(), true); + focusManager.requestFocus(editor, true); FeatureUsageTracker.getInstance().triggerFeatureUsed(IdeActions.ACTION_SEARCH_EVERYWHERE); } @@ -710,6 +741,28 @@ public class SearchEverywhereAction extends AnAction implements CustomComponentA } } }.registerCustomShortcutSet(CustomShortcutSet.fromString("ENTER"), editor, balloon); + new DumbAwareAction(){ + @Override + public void actionPerformed(AnActionEvent e) { + final PropertiesComponent storage = PropertiesComponent.getInstance(e.getProject()); + final String historyString = storage.getValue(SE_HISTORY_KEY); + if (historyString != null) { + final List history = StringUtil.split(historyString, "\n"); + if (history.size() > myHistoryIndex) { + final String text = history.get(myHistoryIndex); + editor.setText(text); + editor.setCaretPosition(text.length()); + editor.moveCaretPosition(0); + myHistoryIndex++; + } + } + } + + @Override + public void update(AnActionEvent e) { + e.getPresentation().setEnabled(editor.getCaretPosition() == 0); + } + }.registerCustomShortcutSet(CustomShortcutSet.fromString("LEFT"), editor, balloon); } private static class MySearchTextField extends SearchTextField implements DataProvider, Disposable { @@ -1460,6 +1513,7 @@ public class SearchEverywhereAction extends AnAction implements CustomComponentA } }) .createPopup(); + myPopup.getContent().setBorder(new EmptyBorder(0,0,0,0)); Disposer.register(myPopup, new Disposable() { @Override public void dispose() { @@ -1487,6 +1541,7 @@ public class SearchEverywhereAction extends AnAction implements CustomComponentA myRenderer.myProject = null; myCalcThread = null; myPopup = null; + myHistoryIndex = 0; showAll.set(false); myNonProjectCheckBox.setSelected(false); ActionToolbarImpl.updateAllToolbarsImmediately(); diff --git a/platform/lang-impl/src/com/intellij/ide/util/gotoByName/ChooseByNameBase.java b/platform/lang-impl/src/com/intellij/ide/util/gotoByName/ChooseByNameBase.java index fec55d085d01..06273414191f 100644 --- a/platform/lang-impl/src/com/intellij/ide/util/gotoByName/ChooseByNameBase.java +++ b/platform/lang-impl/src/com/intellij/ide/util/gotoByName/ChooseByNameBase.java @@ -82,6 +82,7 @@ import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; +import javax.swing.border.Border; import javax.swing.border.CompoundBorder; import javax.swing.border.EmptyBorder; import javax.swing.event.DocumentEvent; @@ -1247,6 +1248,18 @@ public abstract class ChooseByNameBase { }); } + @Override + public Dimension getPreferredSize() { + Dimension size = super.getPreferredSize(); + Border border = super.getBorder(); + if (border != null && UIUtil.isUnderAquaLookAndFeel()) { + Insets insets = border.getBorderInsets(this); + size.height += insets.top + insets.bottom; + size.width += insets.left + insets.right; + } + return size; + } + @Nullable private KeyStroke getShortcut(String actionCodeCompletion) { final Shortcut[] shortcuts = KeymapManager.getInstance().getActiveKeymap().getShortcuts(actionCodeCompletion); diff --git a/platform/lang-impl/src/com/intellij/lang/javascript/boilerplate/AbstractGithubTagDownloadedProjectGenerator.java b/platform/lang-impl/src/com/intellij/lang/javascript/boilerplate/AbstractGithubTagDownloadedProjectGenerator.java index 8c46ec5b1b0e..5af6db07b9d7 100644 --- a/platform/lang-impl/src/com/intellij/lang/javascript/boilerplate/AbstractGithubTagDownloadedProjectGenerator.java +++ b/platform/lang-impl/src/com/intellij/lang/javascript/boilerplate/AbstractGithubTagDownloadedProjectGenerator.java @@ -64,7 +64,7 @@ public abstract class AbstractGithubTagDownloadedProjectGenerator extends WebPro unpackToDir(project, new File(baseDir.getPath()), tag); } catch (GeneratorException e) { - showErrorMessage(e.getMessage()); + showErrorMessage(project, e.getMessage()); } ApplicationManager.getApplication().runWriteAction(new Runnable() { @Override @@ -149,10 +149,9 @@ public abstract class AbstractGithubTagDownloadedProjectGenerator extends WebPro return GithubDownloadUtil.findCacheFile(getGithubUserName(), getGithubRepositoryName(), fileName); } - private void showErrorMessage(@NotNull String message) { + private void showErrorMessage(@NotNull Project project, @NotNull String message) { String fullMessage = "Error creating " + getDisplayName() + " project. " + message; String title = "Create " + getDisplayName() + " Project"; - Project project = null; Messages.showErrorDialog(project, fullMessage, title); } diff --git a/platform/lang-impl/src/com/intellij/openapi/roots/impl/RootIndex.java b/platform/lang-impl/src/com/intellij/openapi/roots/impl/RootIndex.java index cc01c67973d4..df8b295ec9de 100644 --- a/platform/lang-impl/src/com/intellij/openapi/roots/impl/RootIndex.java +++ b/platform/lang-impl/src/com/intellij/openapi/roots/impl/RootIndex.java @@ -420,6 +420,10 @@ class RootIndex { @Nullable public String getPackageName(@NotNull final VirtualFile dir) { if (dir.isDirectory()) { + if (FileTypeManager.getInstance().isFileIgnored(dir)) { + return null; + } + for (final Map.Entry> entry : myPackagePrefixRoots.entrySet()) { if (entry.getValue().contains(dir)) { return entry.getKey(); diff --git a/platform/lang-impl/src/com/intellij/platform/templates/github/ZipUtil.java b/platform/lang-impl/src/com/intellij/platform/templates/github/ZipUtil.java index 28f86cbc6b53..73c7b4aea852 100644 --- a/platform/lang-impl/src/com/intellij/platform/templates/github/ZipUtil.java +++ b/platform/lang-impl/src/com/intellij/platform/templates/github/ZipUtil.java @@ -12,11 +12,13 @@ import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.File; -import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; +import java.io.InputStream; +import java.util.Enumeration; import java.util.concurrent.Callable; import java.util.zip.ZipEntry; +import java.util.zip.ZipFile; import java.util.zip.ZipInputStream; /** @@ -45,13 +47,7 @@ public class ZipUtil { @Override public Boolean call() throws IOException { ProgressIndicator progress = ProgressManager.getInstance().getProgressIndicator(); - ZipInputStream stream = new ZipInputStream(new FileInputStream(zipArchive)); - try { - unzip(progress, extractToDir, stream, null, null, unwrapSingleTopLevelFolder); - } - finally { - stream.close(); - } + unzip(progress, extractToDir, zipArchive, null, null, unwrapSingleTopLevelFolder); return true; } }, @@ -73,25 +69,59 @@ public class ZipUtil { } } + private static File getUnzipToDir(@Nullable ProgressIndicator progress, + @NotNull File targetDir, + boolean unwrapSingleTopLevelFolder) throws IOException { + if (progress != null) { + progress.setText("Extracting..."); + } + if (unwrapSingleTopLevelFolder) { + return FileUtil.createTempDirectory("unzip-dir-", null); + } + return targetDir; + } + + // This method will throw IOException, if a zipArchive file isn't a valid zip archive. + public static void unzip(@Nullable ProgressIndicator progress, + @NotNull File targetDir, + @NotNull File zipArchive, + @Nullable NullableFunction pathConvertor, + @Nullable ContentProcessor contentProcessor, + boolean unwrapSingleTopLevelFolder) throws IOException { + File unzipToDir = getUnzipToDir(progress, targetDir, unwrapSingleTopLevelFolder); + ZipFile zipFile = new ZipFile(zipArchive, ZipFile.OPEN_READ); + try { + Enumeration entries = zipFile.entries(); + while (entries.hasMoreElements()) { + ZipEntry entry = entries.nextElement(); + InputStream entryContentStream = zipFile.getInputStream(entry); + unzipEntryToDir(progress, entry, entryContentStream, unzipToDir, pathConvertor, contentProcessor); + entryContentStream.close(); + } + } + finally { + zipFile.close(); + } + doUnwrapSingleTopLevelFolder(unwrapSingleTopLevelFolder, unzipToDir, targetDir); + } + public static void unzip(@Nullable ProgressIndicator progress, @NotNull File targetDir, @NotNull ZipInputStream stream, @Nullable NullableFunction pathConvertor, @Nullable ContentProcessor contentProcessor, boolean unwrapSingleTopLevelFolder) throws IOException { - if (progress != null) { - progress.setText("Extracting..."); - } - File unzipToDir = targetDir; - if (unwrapSingleTopLevelFolder) { - unzipToDir = FileUtil.createTempDirectory("unzip-dir-", null); - } - + File unzipToDir = getUnzipToDir(progress, targetDir, unwrapSingleTopLevelFolder); ZipEntry entry; while ((entry = stream.getNextEntry()) != null) { - unzipEntryToDir(progress, entry, unzipToDir, stream, pathConvertor, contentProcessor); + unzipEntryToDir(progress, entry, stream, unzipToDir, pathConvertor, contentProcessor); } + doUnwrapSingleTopLevelFolder(unwrapSingleTopLevelFolder, unzipToDir, targetDir); + } + private static void doUnwrapSingleTopLevelFolder(boolean unwrapSingleTopLevelFolder, + @NotNull File unzipToDir, + @NotNull File targetDir) throws IOException { if (unwrapSingleTopLevelFolder) { File[] topLevelFiles = unzipToDir.listFiles(); File dirToMove; @@ -110,8 +140,8 @@ public class ZipUtil { private static void unzipEntryToDir(@Nullable ProgressIndicator progress, @NotNull final ZipEntry zipEntry, + @NotNull final InputStream entryContentStream, @NotNull final File extractToDir, - ZipInputStream stream, @Nullable NullableFunction pathConvertor, @Nullable ContentProcessor contentProcessor) throws IOException { String relativeExtractPath = createRelativeExtractPath(zipEntry); @@ -136,14 +166,14 @@ public class ZipUtil { if (contentProcessor == null) { FileOutputStream fileOutputStream = new FileOutputStream(child); try { - FileUtil.copy(stream, fileOutputStream); + FileUtil.copy(entryContentStream, fileOutputStream); } finally { fileOutputStream.close(); } } else { - byte[] content = contentProcessor.processContent(FileUtil.loadBytes(stream), child); + byte[] content = contentProcessor.processContent(FileUtil.loadBytes(entryContentStream), child); if (content != null) { FileOutputStream fileOutputStream = new FileOutputStream(child); try { diff --git a/platform/lang-impl/src/com/intellij/psi/stubs/StubIndexImpl.java b/platform/lang-impl/src/com/intellij/psi/stubs/StubIndexImpl.java index 06f4e2703252..5f887b115d03 100644 --- a/platform/lang-impl/src/com/intellij/psi/stubs/StubIndexImpl.java +++ b/platform/lang-impl/src/com/intellij/psi/stubs/StubIndexImpl.java @@ -315,7 +315,7 @@ public class StubIndexImpl extends StubIndex implements ApplicationComponent, Pe final MyIndex index = (MyIndex)myIndices.get(indexKey); try { - return index.processAllKeys(processor, idFilter); + return index.processAllKeys(processor, scope, idFilter); } catch (StorageException e) { forceRebuild(e); diff --git a/platform/lang-impl/src/com/intellij/util/indexing/AbstractIndex.java b/platform/lang-impl/src/com/intellij/util/indexing/AbstractIndex.java index 10adf97d59b1..50e87f85baab 100644 --- a/platform/lang-impl/src/com/intellij/util/indexing/AbstractIndex.java +++ b/platform/lang-impl/src/com/intellij/util/indexing/AbstractIndex.java @@ -16,6 +16,7 @@ package com.intellij.util.indexing; +import com.intellij.psi.search.GlobalSearchScope; import com.intellij.util.Processor; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -28,5 +29,5 @@ public interface AbstractIndex { @NotNull ValueContainer getData(Key key) throws StorageException; - boolean processAllKeys(Processor processor, @Nullable IdFilter idFilter) throws StorageException; + boolean processAllKeys(Processor processor, GlobalSearchScope scope, @Nullable IdFilter idFilter) throws StorageException; } diff --git a/platform/lang-impl/src/com/intellij/util/indexing/FileBasedIndexImpl.java b/platform/lang-impl/src/com/intellij/util/indexing/FileBasedIndexImpl.java index b0592ed6a590..f0bb5a676e72 100644 --- a/platform/lang-impl/src/com/intellij/util/indexing/FileBasedIndexImpl.java +++ b/platform/lang-impl/src/com/intellij/util/indexing/FileBasedIndexImpl.java @@ -736,7 +736,7 @@ public class FileBasedIndexImpl extends FileBasedIndex { return true; } ensureUpToDate(indexId, scope.getProject(), scope); - return index.processAllKeys(processor, idFilter); + return index.processAllKeys(processor, scope, idFilter); } catch (StorageException e) { scheduleRebuild(indexId, e); diff --git a/platform/lang-impl/src/com/intellij/util/indexing/IndexStorage.java b/platform/lang-impl/src/com/intellij/util/indexing/IndexStorage.java index 5e0296b335dd..0f8bb67f00fc 100644 --- a/platform/lang-impl/src/com/intellij/util/indexing/IndexStorage.java +++ b/platform/lang-impl/src/com/intellij/util/indexing/IndexStorage.java @@ -16,6 +16,7 @@ package com.intellij.util.indexing; +import com.intellij.psi.search.GlobalSearchScope; import com.intellij.util.Processor; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -39,7 +40,7 @@ public interface IndexStorage extends Flushable { @NotNull ValueContainer read(Key key) throws StorageException; - boolean processKeys(Processor processor, @Nullable IdFilter idFilter) throws StorageException; + boolean processKeys(Processor processor, GlobalSearchScope scope, @Nullable IdFilter idFilter) throws StorageException; Collection getKeys() throws StorageException; diff --git a/platform/lang-impl/src/com/intellij/util/indexing/MapIndexStorage.java b/platform/lang-impl/src/com/intellij/util/indexing/MapIndexStorage.java index b0eaf2dd29d6..649bd25730fb 100644 --- a/platform/lang-impl/src/com/intellij/util/indexing/MapIndexStorage.java +++ b/platform/lang-impl/src/com/intellij/util/indexing/MapIndexStorage.java @@ -18,20 +18,24 @@ package com.intellij.util.indexing; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.progress.ProgressManager; +import com.intellij.openapi.project.Project; import com.intellij.openapi.util.LowMemoryWatcher; import com.intellij.openapi.util.io.FileUtil; +import com.intellij.psi.search.GlobalSearchScope; +import com.intellij.psi.search.ProjectAndLibrariesScope; +import com.intellij.psi.search.ProjectScopeImpl; import com.intellij.util.CommonProcessors; import com.intellij.util.Processor; +import com.intellij.util.SystemProperties; import com.intellij.util.containers.SLRUCache; import com.intellij.util.io.*; +import com.intellij.util.io.DataOutputStream; import gnu.trove.TIntHashSet; +import gnu.trove.TIntProcedure; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.io.DataInput; -import java.io.DataOutput; -import java.io.File; -import java.io.IOException; +import java.io.*; import java.util.ArrayList; import java.util.Collection; import java.util.List; @@ -44,10 +48,12 @@ import java.util.concurrent.locks.ReentrantLock; */ public final class MapIndexStorage implements IndexStorage{ private static final Logger LOG = Logger.getInstance("#com.intellij.util.indexing.MapIndexStorage"); + private static final boolean ENABLE_CACHED_HASH_IDS = SystemProperties.getBooleanProperty("idea.index.no.cashed.hashids", true); private final boolean myBuildKeyHashToVirtualFileMapping; private PersistentMap> myMap; private PersistentBTreeEnumerator myKeyHashToVirtualFileMapping; private SLRUCache> myCache; + private volatile int myLastScannedId; private final File myStorageFile; private final KeyDescriptor myKeyDescriptor; private final int myCacheSize; @@ -216,29 +222,58 @@ public final class MapIndexStorage implements IndexStorage processor, final IdFilter idFilter) throws StorageException { + public boolean processKeys(final Processor processor, GlobalSearchScope scope, final IdFilter idFilter) throws StorageException { l.lock(); try { myCache.clear(); // this will ensure that all new keys are made into the map if (myBuildKeyHashToVirtualFileMapping && idFilter != null) { - final TIntHashSet hashMaskSet = new TIntHashSet(1000); + TIntHashSet hashMaskSet = null; long l = System.currentTimeMillis(); - myKeyHashToVirtualFileMapping.iterateData(new Processor() { - @Override - public boolean process(int[] key) { - if (!idFilter.containsFileId(key[1])) return true; - hashMaskSet.add(key[0]); - ProgressManager.checkCanceled(); - return true; + + File fileWithCaches = getSavedProjectFileValueIds(myLastScannedId, scope); + final boolean useCachedHashIds = ENABLE_CACHED_HASH_IDS && + (scope instanceof ProjectScopeImpl || scope instanceof ProjectAndLibrariesScope) && + fileWithCaches != null; + int id = myKeyHashToVirtualFileMapping.getLargestId(); + + if (useCachedHashIds && id == myLastScannedId) { + try { + hashMaskSet = loadHashedIds(fileWithCaches); + } catch (IOException ex) { + LOG.info(ex); } - }); + } + + if (hashMaskSet == null) { + if (useCachedHashIds && myLastScannedId != 0) { + FileUtil.asyncDelete(fileWithCaches); + } + + hashMaskSet = new TIntHashSet(1000); + final TIntHashSet finalHashMaskSet = hashMaskSet; + myKeyHashToVirtualFileMapping.iterateData(new Processor() { + @Override + public boolean process(int[] key) { + if (!idFilter.containsFileId(key[1])) return true; + finalHashMaskSet.add(key[0]); + ProgressManager.checkCanceled(); + return true; + } + }); + + if (useCachedHashIds) { + saveHashedIds(hashMaskSet, id, scope); + } + } + if (LOG.isDebugEnabled()) { LOG.debug("Scanned keyHashToVirtualFileMapping of " + myStorageFile + " for " + (System.currentTimeMillis() - l)); } + final TIntHashSet finalHashMaskSet = hashMaskSet; return myMap.processKeys(new Processor() { @Override public boolean process(Key key) { - if (!hashMaskSet.contains(myKeyDescriptor.getHashCode(key))) return true; + if (!finalHashMaskSet.contains(myKeyDescriptor.getHashCode(key))) return true; return processor.process(key); } }); @@ -263,11 +298,70 @@ public final class MapIndexStorage implements IndexStorage 0) { + hashMaskSet.add(DataInputOutputUtil.readINT(inputStream)); + --capacity; + } + inputStream.close(); + return hashMaskSet; + } + finally { + if (inputStream != null) { + try { + inputStream.close(); + } catch (IOException ex) {} + } + } + } + + private void saveHashedIds(TIntHashSet hashMaskSet, int largestId, GlobalSearchScope scope) { + File newFileWithCaches = getSavedProjectFileValueIds(largestId, scope); + assert newFileWithCaches != null; + DataOutputStream stream = null; + + try { + stream = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(newFileWithCaches))); + DataInputOutputUtil.writeINT(stream, hashMaskSet.size()); + final DataOutputStream finalStream = stream; + boolean result = hashMaskSet.forEach(new TIntProcedure() { + @Override + public boolean execute(int value) { + try { + DataInputOutputUtil.writeINT(finalStream, value); + return true; + } catch (IOException ex) { + return false; + } + } + }); + if (result) myLastScannedId = largestId; + } catch (IOException ex) {} + finally { + if (stream != null) { + try { + stream.close(); + } catch (IOException ex) {} + } + } + } + + private @Nullable File getSavedProjectFileValueIds(int id, GlobalSearchScope scope) { + Project project = scope.getProject(); + if (project == null) return null; + return new File(myStorageFile.getPath() + ".project."+project.hashCode() + "."+id + "." + scope.isSearchInLibraries()); + } + @NotNull @Override public Collection getKeys() throws StorageException { List keys = new ArrayList(); - processKeys(new CommonProcessors.CollectProcessor(keys), null); + processKeys(new CommonProcessors.CollectProcessor(keys), null, null); return keys; } diff --git a/platform/lang-impl/src/com/intellij/util/indexing/MapReduceIndex.java b/platform/lang-impl/src/com/intellij/util/indexing/MapReduceIndex.java index 008aa3fd43a0..439770324875 100644 --- a/platform/lang-impl/src/com/intellij/util/indexing/MapReduceIndex.java +++ b/platform/lang-impl/src/com/intellij/util/indexing/MapReduceIndex.java @@ -22,6 +22,7 @@ import com.intellij.openapi.util.Computable; import com.intellij.openapi.util.Factory; import com.intellij.openapi.util.Ref; import com.intellij.openapi.util.io.FileUtil; +import com.intellij.psi.search.GlobalSearchScope; import com.intellij.util.Processor; import com.intellij.util.io.PersistentHashMap; import gnu.trove.THashMap; @@ -155,11 +156,11 @@ public class MapReduceIndex implements UpdatableIndex processor, IdFilter idFilter) throws StorageException { + public boolean processAllKeys(Processor processor, GlobalSearchScope scope, IdFilter idFilter) throws StorageException { final Lock lock = getReadLock(); try { lock.lock(); - return myStorage.processKeys(processor, idFilter); + return myStorage.processKeys(processor, scope, idFilter); } finally { lock.unlock(); diff --git a/platform/lang-impl/src/com/intellij/util/indexing/MemoryIndexStorage.java b/platform/lang-impl/src/com/intellij/util/indexing/MemoryIndexStorage.java index f07fc85b85cb..2b27622810a0 100644 --- a/platform/lang-impl/src/com/intellij/util/indexing/MemoryIndexStorage.java +++ b/platform/lang-impl/src/com/intellij/util/indexing/MemoryIndexStorage.java @@ -16,6 +16,7 @@ package com.intellij.util.indexing; +import com.intellij.psi.search.GlobalSearchScope; import com.intellij.util.CommonProcessors; import com.intellij.util.Processor; import com.intellij.util.containers.ContainerUtil; @@ -101,12 +102,12 @@ public class MemoryIndexStorage implements IndexStorage @Override public Collection getKeys() throws StorageException { final Set keys = new HashSet(); - processKeys(new CommonProcessors.CollectProcessor(keys), null); + processKeys(new CommonProcessors.CollectProcessor(keys), null, null); return keys; } @Override - public boolean processKeys(final Processor processor, IdFilter idFilter) throws StorageException { + public boolean processKeys(final Processor processor, GlobalSearchScope scope, IdFilter idFilter) throws StorageException { final Set stopList = new HashSet(); Processor decoratingProcessor = new Processor() { @@ -128,7 +129,7 @@ public class MemoryIndexStorage implements IndexStorage } stopList.add(key); } - return myBackendStorage.processKeys(stopList.size() == 0 && myMap.size() == 0 ? processor : decoratingProcessor, idFilter); + return myBackendStorage.processKeys(stopList.size() == 0 && myMap.size() == 0 ? processor : decoratingProcessor, scope, idFilter); } @Override diff --git a/platform/lang-impl/testData/platform/templates/github/invalid-archive.zip b/platform/lang-impl/testData/platform/templates/github/invalid-archive.zip new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/platform/lang-impl/testSources/com/intellij/platform/templates/github/ZipUtilTest.java b/platform/lang-impl/testSources/com/intellij/platform/templates/github/ZipUtilTest.java index 95e065f4ca0c..2f85513863fb 100644 --- a/platform/lang-impl/testSources/com/intellij/platform/templates/github/ZipUtilTest.java +++ b/platform/lang-impl/testSources/com/intellij/platform/templates/github/ZipUtilTest.java @@ -3,11 +3,13 @@ package com.intellij.platform.templates.github; import com.intellij.openapi.util.io.FileUtil; import com.intellij.testFramework.PlatformTestUtil; import com.intellij.util.io.TestFileSystemBuilder; +import junit.framework.Assert; import org.jetbrains.annotations.NotNull; import org.junit.Test; import java.io.File; import java.io.FileInputStream; +import java.io.IOException; import java.util.zip.ZipInputStream; import static com.intellij.util.io.TestFileSystemBuilder.fs; @@ -51,6 +53,41 @@ public class ZipUtilTest { } } + @Test + public void testSimpleUnzipUsingFile() throws Exception { + File tempDir = FileUtil.createTempDirectory("unzip-test-", null); + File simpleZipFile = new File(getZipParentDir(), "simple.zip"); + ZipUtil.unzip(null, tempDir, simpleZipFile, null, null, true); + checkFileStructure(tempDir, + fs() + .file("a.txt") + .dir("dir").file("b.txt")); + } + + @Test + public void testSingleRootDirUnzipUsingFile() throws Exception { + File tempDir = FileUtil.createTempDirectory("unzip-test-", null); + File simpleZipFile = new File(getZipParentDir(), "single-root-dir-archive.zip"); + ZipUtil.unzip(null, tempDir, simpleZipFile, null, null, true); + checkFileStructure(tempDir, + fs() + .file("a.txt") + .dir("dir").file("b.txt")); + } + + @Test + public void testExpectedFailureOnBrokenZipArchive() throws Exception { + File tempDir = FileUtil.createTempDirectory("unzip-test-", null); + File file = new File(getZipParentDir(), "invalid-archive.zip"); + try { + ZipUtil.unzip(null, tempDir, file, null, null, true); + Assert.fail("Zip archive is broken, but it was unzipped without exceptions."); + } + catch (IOException e) { + // expected exception + } + } + private static void checkFileStructure(@NotNull File parentDir, @NotNull TestFileSystemBuilder expected) { expected.build().assertDirectoryEqual(parentDir); } diff --git a/platform/platform-api/platform-api.iml b/platform/platform-api/platform-api.iml index e40a631f0c55..f6769b444e2b 100644 --- a/platform/platform-api/platform-api.iml +++ b/platform/platform-api/platform-api.iml @@ -32,6 +32,8 @@ + +
diff --git a/platform/platform-api/src/com/intellij/execution/configurations/GeneralCommandLine.java b/platform/platform-api/src/com/intellij/execution/configurations/GeneralCommandLine.java index 3a1e9f431652..8f54a0d6de81 100644 --- a/platform/platform-api/src/com/intellij/execution/configurations/GeneralCommandLine.java +++ b/platform/platform-api/src/com/intellij/execution/configurations/GeneralCommandLine.java @@ -15,6 +15,7 @@ */ package com.intellij.execution.configurations; +import com.google.common.collect.Maps; import com.intellij.execution.CommandLineUtil; import com.intellij.execution.ExecutionException; import com.intellij.execution.Platform; @@ -26,10 +27,12 @@ import com.intellij.openapi.util.SystemInfo; import com.intellij.openapi.util.UserDataHolder; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.CharsetToolkit; +import com.intellij.util.ArrayUtil; import com.intellij.util.EnvironmentUtil; import com.intellij.util.PlatformUtils; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.text.CaseInsensitiveStringHashingStrategy; +import com.pty4j.PtyProcess; import gnu.trove.THashMap; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; @@ -62,8 +65,10 @@ public class GeneralCommandLine implements UserDataHolder { private Charset myCharset = CharsetToolkit.getDefaultSystemCharset(); private boolean myRedirectErrorStream = false; private Map myUserData = null; + private boolean myStartProcessWithPty = false; - public GeneralCommandLine() { } + public GeneralCommandLine() { + } public GeneralCommandLine(@NotNull String... command) { this(Arrays.asList(command)); @@ -107,13 +112,17 @@ public class GeneralCommandLine implements UserDataHolder { return myEnvParams; } - /** @deprecated use {@link #getEnvironment()} (to remove in IDEA 14) */ + /** + * @deprecated use {@link #getEnvironment()} (to remove in IDEA 14) + */ @SuppressWarnings("unused") public Map getEnvParams() { return getEnvironment(); } - /** @deprecated use {@link #getEnvironment()} (to remove in IDEA 14) */ + /** + * @deprecated use {@link #getEnvironment()} (to remove in IDEA 14) + */ @SuppressWarnings("unused") public void setEnvParams(@Nullable Map envParams) { myEnvParams.clear(); @@ -126,7 +135,9 @@ public class GeneralCommandLine implements UserDataHolder { myPassParentEnvironment = passParentEnvironment; } - /** @deprecated use {@link #setPassParentEnvironment(boolean)} (to remove in IDEA 14) */ + /** + * @deprecated use {@link #setPassParentEnvironment(boolean)} (to remove in IDEA 14) + */ @SuppressWarnings({"unused", "SpellCheckingInspection"}) public void setPassParentEnvs(boolean passParentEnvironment) { setPassParentEnvironment(passParentEnvironment); @@ -136,6 +147,15 @@ public class GeneralCommandLine implements UserDataHolder { return myPassParentEnvironment; } + /** + * If argument is true the process created with Pseudo-Terminal (PTY). + * This works only on Unix. On Windows the option is ignored. + */ + public GeneralCommandLine withPty(boolean startProcessWithPty) { + myStartProcessWithPty = startProcessWithPty; + return this; + } + public void addParameters(final String... parameters) { for (String parameter : parameters) { addParameter(parameter); @@ -235,11 +255,16 @@ public class GeneralCommandLine implements UserDataHolder { } try { - ProcessBuilder builder = new ProcessBuilder(commands); - setupEnvironment(builder.environment()); - builder.directory(myWorkDirectory); - builder.redirectErrorStream(myRedirectErrorStream); - return builder.start(); + if (myStartProcessWithPty && SystemInfo.isUnix) { + try { + return startProcessWithPty(commands); + } + catch (Exception e) { + LOG.error("Couldn't run process with PTY", e); + } + } + + return startProcess(commands); } catch (IOException e) { LOG.warn(e); @@ -247,6 +272,23 @@ public class GeneralCommandLine implements UserDataHolder { } } + private Process startProcessWithPty(List commands) throws IOException { + Map env = Maps.newHashMap(); + setupEnvironment(env); + if (myRedirectErrorStream) { + LOG.error("Launching process with PTY and redirected error stream is unsupported yet"); + } + return PtyProcess.exec(ArrayUtil.toStringArray(commands), env, myWorkDirectory.getPath(), true); + } + + private Process startProcess(List commands) throws IOException { + ProcessBuilder builder = new ProcessBuilder(commands); + setupEnvironment(builder.environment()); + builder.directory(myWorkDirectory); + builder.redirectErrorStream(myRedirectErrorStream); + return builder.start(); + } + private void checkWorkingDirectory() throws ExecutionException { if (myWorkDirectory == null) { return; diff --git a/platform/platform-api/src/com/intellij/execution/filters/HyperlinkInfoBase.java b/platform/platform-api/src/com/intellij/execution/filters/HyperlinkInfoBase.java new file mode 100644 index 000000000000..2529ca84d329 --- /dev/null +++ b/platform/platform-api/src/com/intellij/execution/filters/HyperlinkInfoBase.java @@ -0,0 +1,33 @@ +/* + * 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 com.intellij.execution.filters; + +import com.intellij.openapi.project.Project; +import com.intellij.ui.awt.RelativePoint; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +/** + * @author nik + */ +public abstract class HyperlinkInfoBase implements HyperlinkInfo { + public abstract void navigate(@NotNull Project project, @Nullable RelativePoint hyperlinkLocationPoint); + + @Override + public void navigate(Project project) { + navigate(project, null); + } +} diff --git a/platform/platform-api/src/com/intellij/ui/SearchTextField.java b/platform/platform-api/src/com/intellij/ui/SearchTextField.java index c6a76b830b65..1312410cb3ac 100644 --- a/platform/platform-api/src/com/intellij/ui/SearchTextField.java +++ b/platform/platform-api/src/com/intellij/ui/SearchTextField.java @@ -375,6 +375,18 @@ public class SearchTextField extends JPanel { } } + @Override + public Dimension getPreferredSize() { + Dimension size = super.getPreferredSize(); + Border border = super.getBorder(); + if (border != null && UIUtil.isUnderAquaLookAndFeel()) { + Insets insets = border.getBorderInsets(this); + size.height += insets.top + insets.bottom; + size.width += insets.left + insets.right; + } + return size; + } + protected Runnable createItemChosenCallback(final JList list) { return new Runnable() { public void run() { diff --git a/platform/platform-api/src/com/intellij/ui/components/OnOffButton.java b/platform/platform-api/src/com/intellij/ui/components/OnOffButton.java index 7ee0ab9207eb..ee0ee8a23749 100644 --- a/platform/platform-api/src/com/intellij/ui/components/OnOffButton.java +++ b/platform/platform-api/src/com/intellij/ui/components/OnOffButton.java @@ -17,7 +17,6 @@ package com.intellij.ui.components; import com.intellij.ui.Gray; import com.intellij.ui.JBColor; -import com.intellij.util.ui.GraphicsUtil; import com.intellij.util.ui.UIUtil; import javax.swing.*; @@ -67,6 +66,8 @@ public class OnOffButton extends JToggleButton { @SuppressWarnings({"MethodOverridesStaticMethodOfSuperclass", "UnusedDeclaration"}) public static ComponentUI createUI(JComponent c) { + c.setOpaque(false); + c.setAlignmentY(0.5f); return new OnOffButtonUI((OnOffButton)c); } @@ -92,31 +93,33 @@ public class OnOffButton extends JToggleButton { h--; } Graphics2D g = ((Graphics2D)gr); - GraphicsUtil.setupAAPainting(g); - g.translate(1,1); + g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); + int xOff = (myButton.getWidth() - w) / 2; + int yOff = (myButton.getHeight() - h) / 2; + g.translate(xOff, yOff); if (button.isSelected()) { - g.setColor(new JBColor(new Color(57, 113, 238), new Color(13, 41, 62))); - g.fillRoundRect(0, 0, w, h, h, h); - g.setColor(UIUtil.getBorderColor()); - g.drawRoundRect(0, 0, w, h, h, h); - g.setColor(new JBColor(Gray._220, Gray._128)); - g.fillOval(w - h + 1, 1, h - 1, h - 1); + g.setColor(new JBColor(new Color(74, 146, 73), new Color(77, 105, 76))); + g.fillRoundRect(0, 0, w, h, 5, 5); + g.setColor(new JBColor(Gray._192, Gray._80)); + g.drawRoundRect(0, 0, w, h, 5, 5); + g.setColor(new JBColor(Gray._200, Gray._100)); + g.fillRoundRect(w - h, 1, h, h-1, 3, 3); g.setColor(UIUtil.getListForeground(true)); g.drawString(button.getOnText(), h/2, h - 4); } else { g.setColor(UIUtil.getPanelBackground()); - g.fillRoundRect(0, 0, w, h, h, h); - g.setColor(UIUtil.getBorderColor()); - g.drawRoundRect(0, 0, w, h, h, h); + g.fillRoundRect(0, 0, w, h, 5, 5); + g.setColor(new JBColor(Gray._192, Gray._100)); + g.drawRoundRect(0, 0, w, h, 5, 5); g.setColor(UIUtil.getLabelDisabledForeground()); g.drawString(button.getOffText(), h + 4 , h - 4); g.setColor(UIUtil.getBorderColor()); - g.setPaint(new GradientPaint(h,0, Gray._178, 0,h, Gray._240)); - g.fillOval(0, 0, h, h); - g.setColor(UIUtil.getBorderColor()); - g.drawOval(0, 0, h, h); + g.setPaint(new GradientPaint(h, 0, new JBColor(Gray._158, Gray._100), 0, h, new JBColor(Gray._210, Gray._100))); + g.fillRoundRect(0, 0, h, h, 3, 3); +// g.setColor(UIUtil.getBorderColor()); +// g.drawOval(0, 0, h, h); } - g.translate(-1, -1); + g.translate(-xOff, -yOff); } @Override diff --git a/platform/platform-api/src/com/intellij/util/net/NetUtils.java b/platform/platform-api/src/com/intellij/util/net/NetUtils.java index 2f6270cb4038..ae18326d1836 100644 --- a/platform/platform-api/src/com/intellij/util/net/NetUtils.java +++ b/platform/platform-api/src/com/intellij/util/net/NetUtils.java @@ -129,6 +129,19 @@ public class NetUtils { } } + public static int tryToFindAvailableSocketPort(int defaultPort) { + try { + return findAvailableSocketPort(); + } + catch (IOException ignored) { + return defaultPort; + } + } + + public static int tryToFindAvailableSocketPort() { + return tryToFindAvailableSocketPort(-1); + } + public static int[] findAvailableSocketPorts(int capacity) throws IOException { final int[] ports = new int[capacity]; final ServerSocket[] sockets = new ServerSocket[capacity]; diff --git a/platform/platform-impl/src/com/intellij/diagnostic/AttachmentFactory.java b/platform/platform-impl/src/com/intellij/diagnostic/AttachmentFactory.java index 0fb4baf1979b..9e107edcc140 100644 --- a/platform/platform-impl/src/com/intellij/diagnostic/AttachmentFactory.java +++ b/platform/platform-impl/src/com/intellij/diagnostic/AttachmentFactory.java @@ -4,9 +4,11 @@ import com.intellij.openapi.diagnostic.Attachment; import com.intellij.openapi.editor.Document; import com.intellij.openapi.fileEditor.FileDocumentManager; import com.intellij.openapi.fileEditor.impl.LoadTextUtil; +import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.vfs.VirtualFile; import org.jetbrains.annotations.NotNull; +import java.io.File; import java.io.IOException; import java.text.MessageFormat; @@ -26,6 +28,20 @@ public class AttachmentFactory { file.getFileType().isBinary() ? "File is binary" : LoadTextUtil.loadText(file).toString()); } + public static Attachment createAttachment(@NotNull File file, boolean isBinary) { + byte[] bytes = getBytes(file); + return new Attachment(file.getPath(), bytes, isBinary ? "File is binary" : new String(bytes)); + } + + private static byte[] getBytes(File file) { + try { + return FileUtil.loadFileBytes(file); + } + catch (IOException e) { + return Attachment.getBytes(MessageFormat.format(ERROR_MESSAGE_PATTERN, e.getMessage())); + } + } + private static byte[] getBytes(VirtualFile file) { try { return file.contentsToByteArray(); diff --git a/platform/platform-impl/src/com/intellij/execution/impl/EditorHyperlinkSupport.java b/platform/platform-impl/src/com/intellij/execution/impl/EditorHyperlinkSupport.java index c0e0362f8642..25ca738635b3 100644 --- a/platform/platform-impl/src/com/intellij/execution/impl/EditorHyperlinkSupport.java +++ b/platform/platform-impl/src/com/intellij/execution/impl/EditorHyperlinkSupport.java @@ -18,6 +18,7 @@ package com.intellij.execution.impl; import com.intellij.execution.filters.Filter; import com.intellij.execution.filters.FilterMixin; import com.intellij.execution.filters.HyperlinkInfo; +import com.intellij.execution.filters.HyperlinkInfoBase; import com.intellij.ide.OccurenceNavigator; import com.intellij.openapi.editor.Document; import com.intellij.openapi.editor.Editor; @@ -36,6 +37,7 @@ import com.intellij.openapi.editor.markup.TextAttributes; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Key; import com.intellij.pom.NavigatableAdapter; +import com.intellij.ui.awt.RelativePoint; import com.intellij.util.BeforeAfter; import com.intellij.util.Consumer; import com.intellij.util.SmartList; @@ -87,7 +89,12 @@ public class EditorHyperlinkSupport { if (range != null) { final HyperlinkInfo info = myHighlighterToMessageInfoMap.get(range); if (info != null) { - info.navigate(project); + if (info instanceof HyperlinkInfoBase) { + ((HyperlinkInfoBase)info).navigate(project, new RelativePoint(mouseEvent)); + } + else { + info.navigate(project); + } linkFollowed(editor, getHyperlinks().keySet(), range); } } diff --git a/platform/platform-impl/src/com/intellij/ide/actions/Switcher.java b/platform/platform-impl/src/com/intellij/ide/actions/Switcher.java index 45f0da6dd5ab..57b707b54947 100644 --- a/platform/platform-impl/src/com/intellij/ide/actions/Switcher.java +++ b/platform/platform-impl/src/com/intellij/ide/actions/Switcher.java @@ -490,9 +490,9 @@ public class Switcher extends AnAction implements DumbAware { this.add(toolWindows, BorderLayout.WEST); if (filesModel.size() > 0) { files.setAlignmentY(1f); - if (files.getModel().getSize() > 30) { + if (files.getModel().getSize() > 20) { final JScrollPane pane = ScrollPaneFactory.createScrollPane(files, true); - pane.setPreferredSize(new Dimension(files.getPreferredSize().width + 10, 30 * 20)); + pane.setPreferredSize(new Dimension(files.getPreferredSize().width + 10, 20 * 20)); pane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); this.add(pane, BorderLayout.EAST); } else { @@ -556,16 +556,9 @@ public class Switcher extends AnAction implements DumbAware { }.registerCustomShortcutSet(CustomShortcutSet.fromString("ESCAPE"), this, myPopup); } - Component comp = null; - final EditorWindow result = FileEditorManagerEx.getInstanceEx(project).getActiveWindow().getResult(); - if (result != null) { - comp = result.getOwner(); - } - if (comp == null) { - comp = ideFrame.getContentPane(); - } + final Window window = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusedWindow(); myAlarm = new Alarm(Alarm.ThreadToUse.SWING_THREAD, myPopup); - myPopup.showInCenterOf(comp); + myPopup.showInCenterOf(window); } @@ -668,48 +661,67 @@ public class Switcher extends AnAction implements DumbAware { } private void closeTabOrToolWindow() { - final Object value = getSelectedList().getSelectedValue(); - if (value instanceof FileInfo) { - final FileInfo info = (FileInfo)value; - final VirtualFile virtualFile = info.first; - final FileEditorManagerImpl editorManager = ((FileEditorManagerImpl)FileEditorManager.getInstance(project)); - final JList jList = getSelectedList(); - final EditorWindow wnd = findAppropriateWindow(info); - if (wnd == null) { - editorManager.closeFile(virtualFile, false, false); - } else { - editorManager.closeFile(virtualFile, wnd, false); - } - final int selectedIndex = jList.getSelectedIndex(); - final IdeFocusManager focusManager = IdeFocusManager.getInstance(project); - myAlarm.addRequest(new Runnable() { - @Override - public void run() { - focusManager.requestFocus(SwitcherPanel.this, true); + final int[] selected = getSelectedList().getSelectedIndices(); + Arrays.sort(selected); + int selectedIndex = 0; + for (int i = selected.length - 1; i>=0; i--) { + selectedIndex = selected[i]; + Object value = getSelectedList().getModel().getElementAt(selectedIndex); + if (value instanceof FileInfo) { + final FileInfo info = (FileInfo)value; + final VirtualFile virtualFile = info.first; + final FileEditorManagerImpl editorManager = ((FileEditorManagerImpl)FileEditorManager.getInstance(project)); + final JList jList = getSelectedList(); + final EditorWindow wnd = findAppropriateWindow(info); + if (wnd == null) { + editorManager.closeFile(virtualFile, false, false); + } + else { + editorManager.closeFile(virtualFile, wnd, false); + } + + final IdeFocusManager focusManager = IdeFocusManager.getInstance(project); + myAlarm.cancelAllRequests(); + myAlarm.addRequest(new Runnable() { + @Override + public void run() { + focusManager.requestFocus(SwitcherPanel.this, true); + } + }, 300); + if (jList.getModel().getSize() == 1) { + goLeft(); + removeElementAt(jList, selectedIndex); + this.remove(jList); + this.remove(separator); + final Dimension size = toolWindows.getSize(); + myPopup.setSize(new Dimension(size.width, myPopup.getSize().height)); + } + else { + removeElementAt(jList, selectedIndex); + jList.setSize(jList.getPreferredSize()); + } + if (isPinnedMode()) { + EditorHistoryManager.getInstance(project).removeFile(virtualFile); } - }, 300); - if (jList.getModel().getSize() == 1) { - goLeft(); - removeElementAt(jList, selectedIndex); - this.remove(jList); - this.remove(separator); - final Dimension size = toolWindows.getSize(); - myPopup.setSize(new Dimension(size.width, myPopup.getSize().height)); - } else { - goForward(); - removeElementAt(jList, selectedIndex); - jList.setSize(jList.getPreferredSize()); } - pack(); - } else if (value instanceof ToolWindow) { - final ToolWindow toolWindow = (ToolWindow)value; - if (twManager instanceof ToolWindowManagerImpl) { - ToolWindowManagerImpl manager = (ToolWindowManagerImpl)twManager; - manager.hideToolWindow(ids.get(toolWindow), false, false); - } else { - toolWindow.hide(null); + else if (value instanceof ToolWindow) { + final ToolWindow toolWindow = (ToolWindow)value; + if (twManager instanceof ToolWindowManagerImpl) { + ToolWindowManagerImpl manager = (ToolWindowManagerImpl)twManager; + manager.hideToolWindow(ids.get(toolWindow), false, false); + } + else { + toolWindow.hide(null); + } } } + pack(); + myPopup.getContent().revalidate(); + myPopup.getContent().repaint(); + if (getSelectedList().getModel().getSize() > selectedIndex) { + getSelectedList().setSelectedIndex(selectedIndex); + getSelectedList().ensureIndexIsVisible(selectedIndex); + } } private static void removeElementAt(JList jList, int index) { diff --git a/platform/platform-impl/src/com/intellij/ide/ui/laf/darcula/ui/DarculaTextBorder.java b/platform/platform-impl/src/com/intellij/ide/ui/laf/darcula/ui/DarculaTextBorder.java index 1e75c100e3ee..59660a47282f 100644 --- a/platform/platform-impl/src/com/intellij/ide/ui/laf/darcula/ui/DarculaTextBorder.java +++ b/platform/platform-impl/src/com/intellij/ide/ui/laf/darcula/ui/DarculaTextBorder.java @@ -34,7 +34,7 @@ public class DarculaTextBorder implements Border, UIResource { public Insets getBorderInsets(Component c) { int vOffset = c instanceof JPasswordField ? 3 : 4; if (DarculaTextFieldUI.isSearchField(c)) { - vOffset++; + vOffset += 2; } if (DarculaTextFieldUI.isSearchFieldWithHistoryPopup(c)) { return new InsetsUIResource(vOffset, 7 + 16 + 3, vOffset, 7 + 16); diff --git a/platform/platform-impl/src/com/intellij/openapi/components/impl/stores/CompoundSaveSession.java b/platform/platform-impl/src/com/intellij/openapi/components/impl/stores/CompoundSaveSession.java index 0c20859283e1..51cc717726f3 100644 --- a/platform/platform-impl/src/com/intellij/openapi/components/impl/stores/CompoundSaveSession.java +++ b/platform/platform-impl/src/com/intellij/openapi/components/impl/stores/CompoundSaveSession.java @@ -17,33 +17,30 @@ package com.intellij.openapi.components.impl.stores; import com.intellij.openapi.components.StateStorage; import com.intellij.openapi.components.StateStorageException; +import com.intellij.util.SmartList; import com.intellij.util.io.fs.IFile; +import gnu.trove.THashMap; -import java.util.*; +import java.util.List; +import java.util.Map; /** * @author mike */ public class CompoundSaveSession { - private final Map mySaveSessions = new HashMap(); + private final Map mySaveSessions = new THashMap(); public CompoundSaveSession(final CompoundExternalizationSession compoundExternalizationSession) { - final Collection stateStorages = compoundExternalizationSession.getStateStorages(); - - for (StateStorage stateStorage : stateStorages) { + for (StateStorage stateStorage : compoundExternalizationSession.getStateStorages()) { mySaveSessions.put(stateStorage, stateStorage.startSave(compoundExternalizationSession.getExternalizationSession(stateStorage))); } } public List getAllStorageFilesToSave() throws StateStorageException { - List result = new ArrayList(); - - for (StateStorage stateStorage : mySaveSessions.keySet()) { - final StateStorage.SaveSession saveSession = mySaveSessions.get(stateStorage); - + List result = new SmartList(); + for (StateStorage.SaveSession saveSession : mySaveSessions.values()) { result.addAll(saveSession.getStorageFilesToSave()); } - return result; } @@ -56,11 +53,11 @@ public class CompoundSaveSession { public void finishSave() { RuntimeException re = null; for (StateStorage stateStorage : mySaveSessions.keySet()) { - final StateStorage.SaveSession saveSession = mySaveSessions.get(stateStorage); try { - stateStorage.finishSave(saveSession); - } catch(RuntimeException t) { - re = t; + stateStorage.finishSave(mySaveSessions.get(stateStorage)); + } + catch (RuntimeException e) { + re = e; } } @@ -74,11 +71,10 @@ public class CompoundSaveSession { } public List getAllStorageFiles() { - List result = new ArrayList(); + List result = new SmartList(); for (StateStorage.SaveSession saveSession : mySaveSessions.values()) { result.addAll(saveSession.getAllStorageFiles()); } - return result; } } diff --git a/platform/platform-impl/src/com/intellij/openapi/components/impl/stores/StateStorageManagerImpl.java b/platform/platform-impl/src/com/intellij/openapi/components/impl/stores/StateStorageManagerImpl.java index c7c4aec145d0..1b7da8fc2144 100644 --- a/platform/platform-impl/src/com/intellij/openapi/components/impl/stores/StateStorageManagerImpl.java +++ b/platform/platform-impl/src/com/intellij/openapi/components/impl/stores/StateStorageManagerImpl.java @@ -31,6 +31,7 @@ import com.intellij.util.ObjectUtils; import com.intellij.util.SmartList; import com.intellij.util.io.fs.IFile; import gnu.trove.THashMap; +import gnu.trove.THashSet; import gnu.trove.TObjectLongHashMap; import org.jdom.Document; import org.jdom.Element; @@ -468,19 +469,18 @@ public abstract class StateStorageManagerImpl implements StateStorageManager, Di @Override @Nullable public Set analyzeExternalChanges(@NotNull final Set> changedFiles) { - Set result = new HashSet(); - - nextStorage: + Set result = new THashSet(); for (Pair pair : changedFiles) { - final StateStorage stateStorage = pair.second; - final StateStorage.SaveSession saveSession = myCompoundSaveSession.getSaveSession(stateStorage); - if (saveSession == null) continue nextStorage; - final Set s = saveSession.analyzeExternalChanges(changedFiles); - - if (s == null) return null; - result.addAll(s); + final StateStorage.SaveSession saveSession = myCompoundSaveSession.getSaveSession(pair.second); + if (saveSession == null) { + continue; + } + final Set changes = saveSession.analyzeExternalChanges(changedFiles); + if (changes == null) { + return null; + } + result.addAll(changes); } - return result; } } diff --git a/platform/platform-impl/src/com/intellij/openapi/editor/ex/SoftWrapModelEx.java b/platform/platform-impl/src/com/intellij/openapi/editor/ex/SoftWrapModelEx.java index 4e8d60bc753a..48d43bcce8bd 100644 --- a/platform/platform-impl/src/com/intellij/openapi/editor/ex/SoftWrapModelEx.java +++ b/platform/platform-impl/src/com/intellij/openapi/editor/ex/SoftWrapModelEx.java @@ -16,7 +16,6 @@ package com.intellij.openapi.editor.ex; import com.intellij.openapi.editor.*; -import com.intellij.openapi.editor.impl.softwrap.SoftWrapAppliancePlaces; import com.intellij.openapi.editor.impl.softwrap.SoftWrapDrawingType; import org.jetbrains.annotations.NotNull; @@ -107,18 +106,6 @@ public interface SoftWrapModelEx extends SoftWrapModel { */ boolean addSoftWrapChangeListener(@NotNull SoftWrapChangeListener listener); - /** - * Instructs current soft wrap model about the place where corresponding editor is used. - *

- * {@link SoftWrapAppliancePlaces#MAIN_EDITOR} is used by default. - * - * @param place place where corresponding editor is used - */ - void setPlace(@NotNull SoftWrapAppliancePlaces place); - - /** Asks the model to completely recalculate soft wraps. */ - void recalculate(); - /** * IJ editor defines a notion of {@link EditorSettings#getAdditionalColumnsCount() additional columns}. They define additional * amount of space to be used during editor component's width calculation (IJ editor perform 'preventive UI component expansion' diff --git a/platform/platform-impl/src/com/intellij/openapi/editor/impl/EditorMarkupModelImpl.java b/platform/platform-impl/src/com/intellij/openapi/editor/impl/EditorMarkupModelImpl.java index 0452a661df88..fa9f2744bd1d 100644 --- a/platform/platform-impl/src/com/intellij/openapi/editor/impl/EditorMarkupModelImpl.java +++ b/platform/platform-impl/src/com/intellij/openapi/editor/impl/EditorMarkupModelImpl.java @@ -45,7 +45,6 @@ import com.intellij.openapi.ui.MessageType; import com.intellij.openapi.ui.popup.Balloon; import com.intellij.openapi.util.Disposer; import com.intellij.openapi.util.ProperTextRange; -import com.intellij.openapi.util.registry.Registry; import com.intellij.ui.*; import com.intellij.ui.awt.RelativePoint; import com.intellij.util.Alarm; @@ -1106,7 +1105,7 @@ public class EditorMarkupModelImpl extends MarkupModelImpl implements EditorMark needDelay = true; final JPanel editorFragmentPreviewPanel = new JPanel() { private static final int R = 6; - private static final int LEFT_INDENT = BalloonImpl.ARC;// + 5; + private static final int LEFT_INDENT = 0;//BalloonImpl.ARC;// + 5; @Override public Dimension getPreferredSize() { @@ -1133,13 +1132,13 @@ public class EditorMarkupModelImpl extends MarkupModelImpl implements EditorMark UISettings.setupAntialiasing(cg); int lineShift = -myEditor.getLineHeight() * myCacheStartLine; - AffineTransform translateInstance = AffineTransform.getTranslateInstance(0, lineShift); + AffineTransform translateInstance = AffineTransform.getTranslateInstance(-4, lineShift); translateInstance.preConcatenate(t); cg.setTransform(translateInstance); cg.setClip(0, -lineShift, gutterWidth, myCacheLevel2.getHeight()); gutterComponentEx.paint(cg); - translateInstance = AffineTransform.getTranslateInstance(gutterWidth, lineShift); + translateInstance = AffineTransform.getTranslateInstance(gutterWidth - 4, lineShift); translateInstance.preConcatenate(t); cg.setTransform(translateInstance); EditorComponentImpl contentComponent = myEditor.getContentComponent(); @@ -1261,7 +1260,7 @@ public class EditorMarkupModelImpl extends MarkupModelImpl implements EditorMark showEditorHint(hintManager, myPointHolder.get(), myHintHolder.get()); myDelayed = false; } - }, Registry.intValue("ide.tooltip.initialDelay")); + }, /*Registry.intValue("ide.tooltip.initialDelay")*/300); } else if (!myDelayed) { showEditorHint(hintManager, point, hintInfo); diff --git a/platform/platform-impl/src/com/intellij/openapi/editor/impl/FoldRegionsTree.java b/platform/platform-impl/src/com/intellij/openapi/editor/impl/FoldRegionsTree.java index cf3b6136e047..0acfbbcc33f8 100644 --- a/platform/platform-impl/src/com/intellij/openapi/editor/impl/FoldRegionsTree.java +++ b/platform/platform-impl/src/com/intellij/openapi/editor/impl/FoldRegionsTree.java @@ -157,8 +157,15 @@ abstract class FoldRegionsTree { boolean addRegion(FoldRegion range) { // During batchProcessing elements are inserted in ascending order, // binary search find acceptable insertion place first time - final boolean canUseCachedValue = - myCachedLastIndex != -1 && isBatchFoldingProcessing() && myRegions.get(myCachedLastIndex).getStartOffset() <= range.getStartOffset(); + final boolean canUseCachedValue; + if (myCachedLastIndex >= myRegions.size()) { + // todo this happens after removeRegion()... myCachedListIndex must die! + canUseCachedValue = false; + } + else { + canUseCachedValue = + myCachedLastIndex != -1 && isBatchFoldingProcessing() && myRegions.get(myCachedLastIndex).getStartOffset() <= range.getStartOffset(); + } int fastIndex = canUseCachedValue ? myCachedLastIndex + 1 : Collections.binarySearch(myRegions, range, RangeMarker.BY_START_OFFSET); if (fastIndex < 0) fastIndex = -fastIndex - 1; diff --git a/platform/platform-impl/src/com/intellij/openapi/editor/impl/SoftWrapModelImpl.java b/platform/platform-impl/src/com/intellij/openapi/editor/impl/SoftWrapModelImpl.java index 9971e82b61bd..57978a8c0af4 100644 --- a/platform/platform-impl/src/com/intellij/openapi/editor/impl/SoftWrapModelImpl.java +++ b/platform/platform-impl/src/com/intellij/openapi/editor/impl/SoftWrapModelImpl.java @@ -551,7 +551,6 @@ public class SoftWrapModelImpl implements SoftWrapModelEx, PrioritizedDocumentLi caretModel.moveToVisualPosition(visualCaretPosition); } - @Override public void setPlace(@NotNull SoftWrapAppliancePlaces place) { myFoldBasedApplianceStrategy.setCurrentPlace(place); } @@ -663,7 +662,6 @@ public class SoftWrapModelImpl implements SoftWrapModelEx, PrioritizedDocumentLi myDeferredFoldRegions.clear(); } - @Override public void recalculate() { myApplianceManager.reset(); myStorage.removeAll(); diff --git a/platform/platform-impl/src/com/intellij/openapi/fileTypes/ex/FileTypeChooser.java b/platform/platform-impl/src/com/intellij/openapi/fileTypes/ex/FileTypeChooser.java index 155f06a82f35..9821e9400d4e 100644 --- a/platform/platform-impl/src/com/intellij/openapi/fileTypes/ex/FileTypeChooser.java +++ b/platform/platform-impl/src/com/intellij/openapi/fileTypes/ex/FileTypeChooser.java @@ -57,7 +57,7 @@ public class FileTypeChooser extends DialogWrapper { super(true); myFileName = fileName; - myOpenInIdea.setText("Open matching files in " + ApplicationNamesInfo.getInstance().getProductName() + ":"); + myOpenInIdea.setText("Open matching files in " + ApplicationNamesInfo.getInstance().getFullProductName() + ":"); FileType[] fileTypes = FileTypeManager.getInstance().getRegisteredFileTypes(); Arrays.sort(fileTypes, new Comparator() { diff --git a/platform/platform-impl/src/com/intellij/openapi/updateSettings/impl/AbstractUpdateDialog.java b/platform/platform-impl/src/com/intellij/openapi/updateSettings/impl/AbstractUpdateDialog.java index ad2b11984806..319ad85113da 100644 --- a/platform/platform-impl/src/com/intellij/openapi/updateSettings/impl/AbstractUpdateDialog.java +++ b/platform/platform-impl/src/com/intellij/openapi/updateSettings/impl/AbstractUpdateDialog.java @@ -76,7 +76,7 @@ public abstract class AbstractUpdateDialog extends DialogWrapper { css += ""; } updateLinkPane.setBorder(IdeBorderFactory.createEmptyBorder()); - updateLinkPane.setText(IdeBundle.message("updates.configure.label", css)); + updateLinkPane.setText(IdeBundle.message("updates.configure.label", css, ShowSettingsUtil.getSettingsMenuName())); updateLinkPane.setEditable(false); LabelTextReplacingUtil.replaceText(panel); diff --git a/platform/platform-impl/src/com/intellij/openapi/updateSettings/impl/pluginsAdvertisement/PluginAdvertiserEditorNotificationProvider.java b/platform/platform-impl/src/com/intellij/openapi/updateSettings/impl/pluginsAdvertisement/PluginAdvertiserEditorNotificationProvider.java index 1fd3b6d8db12..22cb0e9e93c9 100644 --- a/platform/platform-impl/src/com/intellij/openapi/updateSettings/impl/pluginsAdvertisement/PluginAdvertiserEditorNotificationProvider.java +++ b/platform/platform-impl/src/com/intellij/openapi/updateSettings/impl/pluginsAdvertisement/PluginAdvertiserEditorNotificationProvider.java @@ -138,8 +138,7 @@ public class PluginAdvertiserEditorNotificationProvider extends EditorNotificati }); } }); - } else { - + } else if (PluginsAdvertiser.hasBundledNotInstalledPlugin(plugins)){ if (PropertiesComponent.getInstance().isTrueValue(PluginsAdvertiser.IGNORE_ULTIMATE_EDITION)) { return null; } @@ -159,6 +158,8 @@ public class PluginAdvertiserEditorNotificationProvider extends EditorNotificati myNotifications.updateAllNotifications(); } }); + } else { + return null; } panel.createActionLabel("Ignore extension", new Runnable() { @Override diff --git a/platform/platform-impl/src/com/intellij/openapi/updateSettings/impl/pluginsAdvertisement/PluginsAdvertiser.java b/platform/platform-impl/src/com/intellij/openapi/updateSettings/impl/pluginsAdvertisement/PluginsAdvertiser.java index 509de138bb06..f14580b8abd7 100644 --- a/platform/platform-impl/src/com/intellij/openapi/updateSettings/impl/pluginsAdvertisement/PluginsAdvertiser.java +++ b/platform/platform-impl/src/com/intellij/openapi/updateSettings/impl/pluginsAdvertisement/PluginsAdvertiser.java @@ -210,6 +210,15 @@ public class PluginsAdvertiser implements StartupActivity { return null; } + static boolean hasBundledNotInstalledPlugin(Collection plugins) { + for (Plugin plugin : plugins) { + if (plugin.myBundled && PluginManager.getPlugin(PluginId.getId(plugin.myPluginId)) == null) { + return true; + } + } + return false; + } + @Override public void runActivity(@NotNull final Project project) { if (!UpdateSettings.getInstance().CHECK_NEEDED) return; @@ -258,13 +267,11 @@ public class PluginsAdvertiser implements StartupActivity { if (pluginDescriptor != null) { myDisabledPlugins.put(plugin, pluginDescriptor); } - } else { - if (plugin.myBundled) { - myBundledPlugins = true; - } - } + } } + myBundledPlugins = hasBundledNotInstalledPlugin(ids.values()); + for (IdeaPluginDescriptor loadedPlugin : myAllPlugins) { final PluginId pluginId = loadedPlugin.getPluginId(); if (ids.containsKey(pluginId.getIdString()) && !disabledPlugins.contains(pluginId.getIdString())) { diff --git a/platform/platform-impl/src/com/intellij/openapi/updateSettings/impl/pluginsAdvertisement/PluginsAdvertiserDialog.java b/platform/platform-impl/src/com/intellij/openapi/updateSettings/impl/pluginsAdvertisement/PluginsAdvertiserDialog.java index c74911131a80..f663533d700d 100644 --- a/platform/platform-impl/src/com/intellij/openapi/updateSettings/impl/pluginsAdvertisement/PluginsAdvertiserDialog.java +++ b/platform/platform-impl/src/com/intellij/openapi/updateSettings/impl/pluginsAdvertisement/PluginsAdvertiserDialog.java @@ -74,14 +74,14 @@ public class PluginsAdvertiserDialog extends DialogWrapper { @Override protected void doOKAction() { - final Set pluginsToEnable = new HashSet(); + final Set pluginsToEnable = new HashSet(); final List nodes = new ArrayList(); for (PluginDownloader downloader : myUploadedPlugins) { - if (!mySkippedPlugins.contains(downloader.getPluginId())) { - final IdeaPluginDescriptor descriptor = PluginManager.getPlugin(PluginId.getId(downloader.getPluginId())); - if (descriptor != null) { - pluginsToEnable.add(descriptor); - } else { + String pluginId = downloader.getPluginId(); + if (!mySkippedPlugins.contains(pluginId)) { + pluginsToEnable.add(pluginId); + final IdeaPluginDescriptor descriptor = PluginManager.getPlugin(PluginId.getId(pluginId)); + if (descriptor == null) { final PluginNode pluginNode = PluginDownloader.createPluginNode(null, downloader); if (pluginNode != null) { nodes.add(pluginNode); @@ -95,8 +95,8 @@ public class PluginsAdvertiserDialog extends DialogWrapper { PluginManagerMain.notifyPluginsWereInstalled(null, myProject); } }; - for (IdeaPluginDescriptor pluginDescriptor : pluginsToEnable) { - PluginManagerCore.enablePlugin(pluginDescriptor.getPluginId().getIdString()); + for (String pluginId : pluginsToEnable) { + PluginManagerCore.enablePlugin(pluginId); } if (!nodes.isEmpty()) { try { diff --git a/platform/platform-impl/src/com/intellij/openapi/wm/impl/IdeMenuBar.java b/platform/platform-impl/src/com/intellij/openapi/wm/impl/IdeMenuBar.java index 9e51608a03db..e7dbaef39b78 100644 --- a/platform/platform-impl/src/com/intellij/openapi/wm/impl/IdeMenuBar.java +++ b/platform/platform-impl/src/com/intellij/openapi/wm/impl/IdeMenuBar.java @@ -161,8 +161,13 @@ public class IdeMenuBar extends JMenuBar implements IdeEventQueue.EventDispatche @Override public void menuSelectionChanged(boolean isIncluded) { - if (!getSelectionModel().isSelected()) return; - if (myState == State.COLLAPSED) { + if (!isIncluded && myState == State.TEMPORARY_EXPANDED) { + myActivated = false; + setState(State.COLLAPSING); + restartAnimator(); + return; + } + if (isIncluded && myState == State.COLLAPSED) { myActivated = true; setState(State.TEMPORARY_EXPANDED); revalidate(); diff --git a/platform/platform-impl/src/com/intellij/openapi/wm/impl/StripeButtonUI.java b/platform/platform-impl/src/com/intellij/openapi/wm/impl/StripeButtonUI.java index ecf6af18c51e..eb360e39d1ad 100644 --- a/platform/platform-impl/src/com/intellij/openapi/wm/impl/StripeButtonUI.java +++ b/platform/platform-impl/src/com/intellij/openapi/wm/impl/StripeButtonUI.java @@ -15,9 +15,7 @@ */ package com.intellij.openapi.wm.impl; -import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.wm.ToolWindowAnchor; -import com.intellij.ui.ColorUtil; import com.intellij.ui.Gray; import com.intellij.util.ui.UIUtil; @@ -27,7 +25,6 @@ import javax.swing.plaf.basic.BasicGraphicsUtils; import javax.swing.plaf.metal.MetalToggleButtonUI; import java.awt.*; import java.awt.geom.AffineTransform; -import java.awt.geom.RoundRectangle2D; /** * @author Vladimir Kondratyev @@ -52,7 +49,7 @@ public final class StripeButtonUI extends MetalToggleButtonUI{ final Dimension dim=super.getPreferredSize(button); dim.width=(int)(4+dim.width*1.1f); - dim.height+=4; + dim.height+=2; final ToolWindowAnchor anchor=button.getAnchor(); if(ToolWindowAnchor.LEFT==anchor||ToolWindowAnchor.RIGHT==anchor){ @@ -109,20 +106,16 @@ public final class StripeButtonUI extends MetalToggleButtonUI{ final ButtonModel model=button.getModel(); final Color background = button.getBackground(); - final boolean vertical = anchor == ToolWindowAnchor.LEFT || anchor == ToolWindowAnchor.RIGHT; - - if (ApplicationManager.getApplication().isInternal()) { - ourIconRect.x-=2; - ourTextRect.x-=2; + ourIconRect.x -= 2; + ourTextRect.x -= 2; + if (model.isArmed() && model.isPressed() || model.isSelected() || model.isRollover()) { if (anchor == ToolWindowAnchor.LEFT) g2.translate(-1, 0); if (anchor.isHorizontal()) g2.translate(0, -1); - paintNewDecoration(g2, button, model, vertical); + final boolean dark = UIUtil.isUnderDarcula(); + g2.setColor(dark ? Gray._15.withAlpha(model.isSelected() ? 85: 40) : Gray._85.withAlpha(model.isSelected()? 85: 40)); + g2.fillRect(0, 0, button.getWidth(), button.getHeight()); if (anchor == ToolWindowAnchor.LEFT) g2.translate(1, 0); if (anchor.isHorizontal()) g2.translate(0, 1); - } else { - if (anchor == ToolWindowAnchor.RIGHT) g2.translate(1, 0); - paintLegacyDecoration(g2, button, model, vertical); - if (anchor == ToolWindowAnchor.RIGHT) g2.translate(-1, 0); } @@ -164,7 +157,7 @@ public final class StripeButtonUI extends MetalToggleButtonUI{ /* Draw the Text */ if(model.isEnabled()){ /*** paint the text normally */ - g2.setColor(button.getForeground()); + g2.setColor(UIUtil.isUnderDarcula() && model.isSelected() ? button.getForeground().brighter() : button.getForeground()); BasicGraphicsUtils.drawString(g2,clippedText,button.getMnemonic2(),ourTextRect.x,ourTextRect.y+fm.getAscent()); } else{ /*** paint the text disabled ***/ @@ -182,50 +175,4 @@ public final class StripeButtonUI extends MetalToggleButtonUI{ g2.dispose(); } - - private static void paintNewDecoration(Graphics2D g2, AnchoredButton button, ButtonModel model, boolean vertical) { - final boolean dark = UIUtil.isUnderDarcula(); - Color toBorder = model.isRollover() ? dark ? Gray._90 : new Color(0, 0, 0, 50) : null; - double gap = 2; - double r = (((vertical? button.getWidth() : button.getHeight()) - 2 * gap) - 1)/4; - Shape shape = new RoundRectangle2D.Double(gap, gap, button.getWidth() - 2 * gap, button.getHeight() - 2 * gap, r, r); - - if (model.isArmed() && model.isPressed() || model.isSelected()) { - g2.setColor(ColorUtil.mix(dark ? Gray._85.withAlpha(85) : new Color(0, 0, 0, 30), new Color(100, 150, 230, 50), .5)); - g2.fill(shape); - g2.setColor(dark ? Gray._40 : new Color(0, 0, 0, 120)); - g2.draw(shape); - toBorder = null; - } - if (toBorder != null) { - g2.setColor(toBorder); - g2.draw(shape); - } - } - - private static void paintLegacyDecoration(Graphics2D g2, AnchoredButton button, ButtonModel model, boolean vertical) { - final boolean dark = UIUtil.isUnderDarcula(); - Color toBorder = model.isRollover() ? dark ? Gray._90 : new Color(0, 0, 0, 50) : null; - if (model.isArmed() && model.isPressed() || model.isSelected()) { - g2.setColor(dark ? Gray._85.withAlpha(85) : new Color(0, 0, 0, 30)); - g2.fillRect(3, 3, button.getWidth() - (vertical ? 6 : 5), button.getHeight() - 6); - - g2.setColor(dark ? Gray._40 : new Color(0, 0, 0, 120)); - g2.drawLine(2, 2, 3 + button.getWidth() - (vertical ? 7 : 6), 2); - g2.drawLine(2, 3, 2, 3 + button.getHeight() - 7); - - g2.setColor(dark ? Gray._65 : new Color(0, 0, 0, 40)); - g2.drawRect(3, 3, button.getWidth() - (vertical ? 7 : 6), button.getHeight() - 7); - - g2.setColor(dark ? Gray._75 : new Color(255, 255, 255, 110)); - g2.drawLine(3, button.getHeight() - 3, 3 + button.getWidth() - (vertical ? 6 : 5), button.getHeight() - 3); - g2.drawLine(3 + button.getWidth() - (vertical ? 6 : 5), 2, 3 + button.getWidth() - (vertical ? 6 : 5), - 3 + button.getHeight() - 7); - toBorder = null; - } - if (toBorder != null) { - g2.setColor(toBorder); - g2.drawRect(2, 2, button.getWidth() - (vertical ? 6 : 5), button.getHeight() - 6); - } - } } diff --git a/platform/platform-impl/src/com/intellij/openapi/wm/impl/WindowManagerImpl.java b/platform/platform-impl/src/com/intellij/openapi/wm/impl/WindowManagerImpl.java index 8a59c04b2ab4..984b6551cb82 100644 --- a/platform/platform-impl/src/com/intellij/openapi/wm/impl/WindowManagerImpl.java +++ b/platform/platform-impl/src/com/intellij/openapi/wm/impl/WindowManagerImpl.java @@ -27,13 +27,12 @@ import com.intellij.openapi.application.Application; import com.intellij.openapi.application.ApplicationInfo; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.ex.ApplicationInfoEx; -import com.intellij.openapi.components.ApplicationComponent; +import com.intellij.openapi.components.*; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.project.Project; import com.intellij.openapi.project.ProjectManager; import com.intellij.openapi.ui.popup.JBPopup; import com.intellij.openapi.util.Disposer; -import com.intellij.openapi.util.NamedJDOMExternalizable; import com.intellij.openapi.util.SystemInfo; import com.intellij.openapi.wm.IdeFrame; import com.intellij.openapi.wm.StatusBar; @@ -67,7 +66,11 @@ import java.util.Set; * @author Anton Katilin * @author Vladimir Kondratyev */ -public final class WindowManagerImpl extends WindowManagerEx implements ApplicationComponent, NamedJDOMExternalizable { +@State( + name = "WindowManager", + roamingType = RoamingType.GLOBAL, + storages = {@Storage(file = StoragePathMacros.APP_CONFIG + "/window.manager.xml")}) +public final class WindowManagerImpl extends WindowManagerEx implements ApplicationComponent, PersistentStateComponent { private static final Logger LOG = Logger.getInstance("#com.intellij.openapi.wm.impl.WindowManagerImpl"); @NonNls public static final String FULL_SCREEN = "ide.frame.full.screen"; @@ -689,12 +692,9 @@ public final class WindowManagerImpl extends WindowManagerEx implements Applicat return myCommandProcessor; } - public final String getExternalFileName() { - return "window.manager"; - } - - public final void readExternal(final Element element) { - final Element frameElement = element.getChild(FRAME_ELEMENT); + @Override + public void loadState(Element state) { + final Element frameElement = state.getChild(FRAME_ELEMENT); if (frameElement != null) { myFrameBounds = loadFrameBounds(frameElement); try { @@ -708,7 +708,7 @@ public final class WindowManagerImpl extends WindowManagerEx implements Applicat } } - final Element desktopElement = element.getChild(DesktopLayout.TAG); + final Element desktopElement = state.getChild(DesktopLayout.TAG); if (desktopElement != null) { myLayout.readExternal(desktopElement); } @@ -743,43 +743,61 @@ public final class WindowManagerImpl extends WindowManagerEx implements Applicat return bounds; } - public final void writeExternal(final Element element) { - // Save frame bounds - final Element frameElement = new Element(FRAME_ELEMENT); - element.addContent(frameElement); - final Project[] projects = ProjectManager.getInstance().getOpenProjects(); - final Project project = projects.length > 0 ? projects[0] : null; - - final IdeFrameImpl frame = getFrame(project); - if (frame != null) { - int extendedState = frame.getExtendedState(); - if (SystemInfo.isMacOSLion) { - @SuppressWarnings("deprecation") ComponentPeer peer = frame.getPeer(); - if (peer instanceof FramePeer) { - // frame.state is not updated by jdk so get it directly from peer - extendedState = ((FramePeer)peer).getState(); - } - } - boolean isMaximized = extendedState == Frame.MAXIMIZED_BOTH || - isFullScreenSupportedInCurrentOS() && frame.isInFullScreen(); - boolean usePreviousBounds = isMaximized && - myFrameBounds != null && - frame.getBounds().contains(new Point((int)myFrameBounds.getCenterX(), (int)myFrameBounds.getCenterY())); - Rectangle rectangle = usePreviousBounds ? myFrameBounds : frame.getBounds(); - frameElement.setAttribute(X_ATTR, Integer.toString(rectangle.x)); - frameElement.setAttribute(Y_ATTR, Integer.toString(rectangle.y)); - frameElement.setAttribute(WIDTH_ATTR, Integer.toString(rectangle.width)); - frameElement.setAttribute(HEIGHT_ATTR, Integer.toString(rectangle.height)); - - if (!(frame.isInFullScreen() && SystemInfo.isAppleJvm)) { - frameElement.setAttribute(EXTENDED_STATE_ATTR, Integer.toString(extendedState)); - } - - // Save default layout - final Element layoutElement = new Element(DesktopLayout.TAG); - element.addContent(layoutElement); - myLayout.writeExternal(layoutElement); + @Nullable + @Override + public Element getState() { + Element frameState = getFrameState(); + if (frameState == null) { + return null; } + + Element state = new Element("state"); + state.addContent(frameState); + + // Save default layout + Element layoutElement = new Element(DesktopLayout.TAG); + state.addContent(layoutElement); + myLayout.writeExternal(layoutElement); + return state; + } + + private Element getFrameState() { + // Save frame bounds + final Project[] projects = ProjectManager.getInstance().getOpenProjects(); + if (projects.length == 0) { + return null; + } + + Project project = projects[0]; + final IdeFrameImpl frame = getFrame(project); + if (frame == null) { + return null; + } + + final Element frameElement = new Element(FRAME_ELEMENT); + int extendedState = frame.getExtendedState(); + if (SystemInfo.isMacOSLion) { + @SuppressWarnings("deprecation") ComponentPeer peer = frame.getPeer(); + if (peer instanceof FramePeer) { + // frame.state is not updated by jdk so get it directly from peer + extendedState = ((FramePeer)peer).getState(); + } + } + boolean isMaximized = extendedState == Frame.MAXIMIZED_BOTH || + isFullScreenSupportedInCurrentOS() && frame.isInFullScreen(); + boolean usePreviousBounds = isMaximized && + myFrameBounds != null && + frame.getBounds().contains(new Point((int)myFrameBounds.getCenterX(), (int)myFrameBounds.getCenterY())); + Rectangle rectangle = usePreviousBounds ? myFrameBounds : frame.getBounds(); + frameElement.setAttribute(X_ATTR, Integer.toString(rectangle.x)); + frameElement.setAttribute(Y_ATTR, Integer.toString(rectangle.y)); + frameElement.setAttribute(WIDTH_ATTR, Integer.toString(rectangle.width)); + frameElement.setAttribute(HEIGHT_ATTR, Integer.toString(rectangle.height)); + + if (!(frame.isInFullScreen() && SystemInfo.isAppleJvm)) { + frameElement.setAttribute(EXTENDED_STATE_ATTR, Integer.toString(extendedState)); + } + return frameElement; } public final DesktopLayout getLayout() { diff --git a/platform/platform-impl/src/com/intellij/ui/FinderRecursivePanel.java b/platform/platform-impl/src/com/intellij/ui/FinderRecursivePanel.java index 37ebcc40efa1..47970514f429 100644 --- a/platform/platform-impl/src/com/intellij/ui/FinderRecursivePanel.java +++ b/platform/platform-impl/src/com/intellij/ui/FinderRecursivePanel.java @@ -427,10 +427,12 @@ public abstract class FinderRecursivePanel extends JBSplitter implements Data @Override public void run() { try { + final List listItems = getListItems(); + SwingUtilities.invokeLater(new Runnable() { @Override public void run() { - mergeListItems(myListModel, getListItems()); + mergeListItems(myListModel, listItems); if (myList.getSelectedIndex() < 0) { myList.setSelectedIndex(myListModel.getSize() > oldIndex ? oldIndex : 0); diff --git a/platform/platform-impl/src/com/intellij/util/UrlImpl.java b/platform/platform-impl/src/com/intellij/util/UrlImpl.java index 530121ce439f..ec2d7e02af60 100644 --- a/platform/platform-impl/src/com/intellij/util/UrlImpl.java +++ b/platform/platform-impl/src/com/intellij/util/UrlImpl.java @@ -22,12 +22,7 @@ import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public final class UrlImpl implements Url { - private String externalForm; - private UrlImpl withoutParameters; - - @Nullable private final String scheme; - private final String authority; private final String path; @@ -35,6 +30,9 @@ public final class UrlImpl implements Url { private final String parameters; + private String externalForm; + private UrlImpl withoutParameters; + public UrlImpl(@Nullable String path) { this(null, null, path, null); } @@ -105,6 +103,11 @@ public final class UrlImpl implements Url { return externalForm; } + // relative path - special url, encoding is not required + if (path.charAt(0) != '/' && !isInLocalFileSystem()) { + return toDecodedForm(); + } + String result = Urls.toUriWithoutParameters(this).toASCIIString(); if (parameters != null) { result += parameters; diff --git a/platform/platform-impl/src/com/intellij/util/Urls.java b/platform/platform-impl/src/com/intellij/util/Urls.java index 295f3918b458..9bbb70f1cafe 100644 --- a/platform/platform-impl/src/com/intellij/util/Urls.java +++ b/platform/platform-impl/src/com/intellij/util/Urls.java @@ -37,6 +37,11 @@ public final class Urls { // about ";" see WEB-100359 private static final Pattern URI_PATTERN = Pattern.compile("^([^:/?#]+)://([^/?#]*)([^?#;]*)(.*)"); + @NotNull + public static Url newUri(@NotNull String scheme, @NotNull String path) { + return new UrlImpl(scheme, null, path); + } + @NotNull public static Url newFromEncoded(@NotNull String url) { Url result = parse(url, true); @@ -125,7 +130,7 @@ public final class Urls { // must not be used in NodeJS public static Url newFromVirtualFile(@NotNull VirtualFile file) { if (file.isInLocalFileSystem()) { - return new UrlImpl(file.getFileSystem().getProtocol(), null, file.getPath()); + return newUri(file.getFileSystem().getProtocol(), file.getPath()); } else { return parseUrl(file.getUrl()); diff --git a/platform/platform-resources-en/src/messages/IdeBundle.properties b/platform/platform-resources-en/src/messages/IdeBundle.properties index e5852f28a28c..1bdb05e4a97f 100644 --- a/platform/platform-resources-en/src/messages/IdeBundle.properties +++ b/platform/platform-resources-en/src/messages/IdeBundle.properties @@ -889,7 +889,7 @@ unscramble.unscrambled.deadlock.tab= updates.info.dialog.title=Update Info updates.no.updates.message=

You are using the latest version of $FULLNAME$.

-updates.configure.label={0}
To configure automatic update settings, see the Updates dialog of your IDE settings +updates.configure.label={0}
To configure automatic update settings, see the Updates dialog of your IDE {1} updates.timeout.error=Connection timed out updates.download.and.install.patch.button=&Download Patch and Shutdown updates.download.and.install.patch.button.restart=Up&date and Restart diff --git a/platform/platform-resources-en/src/tips/RenameCssSelector.html b/platform/platform-resources-en/src/tips/RenameCssSelector.html index 6c377a924d47..12e4b7a9cfbb 100644 --- a/platform/platform-resources-en/src/tips/RenameCssSelector.html +++ b/platform/platform-resources-en/src/tips/RenameCssSelector.html @@ -8,7 +8,6 @@

It is possible to rename CSS selectors directly from HTML. Position the caret at the selector to be renamed and press &shortcut:RenameElement; (Refactor | Rename).

-

diff --git a/platform/platform-resources/src/META-INF/LangExtensions.xml b/platform/platform-resources/src/META-INF/LangExtensions.xml index e0082450dc10..65fd47d6baf1 100644 --- a/platform/platform-resources/src/META-INF/LangExtensions.xml +++ b/platform/platform-resources/src/META-INF/LangExtensions.xml @@ -44,6 +44,8 @@ + diff --git a/platform/remote-servers/impl/src/com/intellij/remoteServer/util/DeploymentSourceHandler.java b/platform/remote-servers/impl/src/com/intellij/remoteServer/util/DeploymentSourceHandler.java new file mode 100644 index 000000000000..0dba5d2932b5 --- /dev/null +++ b/platform/remote-servers/impl/src/com/intellij/remoteServer/util/DeploymentSourceHandler.java @@ -0,0 +1,33 @@ +/* + * 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 com.intellij.remoteServer.util; + +import com.intellij.remoteServer.agent.util.CloudGitApplication; +import com.intellij.remoteServer.configuration.deployment.DeploymentSource; + +import java.io.File; + +/** + * @author michael.golubev + */ +public interface DeploymentSourceHandler { + + boolean init(DeploymentSource deploymentSource) throws ServerRuntimeException; + + File getRepositoryRootFile(); + + CloudGitApplication deploy() throws ServerRuntimeException; +} diff --git a/platform/util/src/com/intellij/ui/Gradient.java b/platform/util/src/com/intellij/ui/Gradient.java new file mode 100644 index 000000000000..511fff947154 --- /dev/null +++ b/platform/util/src/com/intellij/ui/Gradient.java @@ -0,0 +1,39 @@ +/* + * 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 com.intellij.ui; + +import java.awt.*; + +/** + * @author Konstantin Bulenkov + */ +public class Gradient { + private final Color myStartColor; + private final Color myEndColor; + + public Gradient(Color startColor, Color endColor) { + myStartColor = startColor; + myEndColor = endColor; + } + + public Color getStartColor() { + return myStartColor; + } + + public Color getEndColor() { + return myEndColor; + } +} diff --git a/platform/util/src/com/intellij/util/ReflectionCache.java b/platform/util/src/com/intellij/util/ReflectionCache.java index 9fc96728bf7e..1a948882e4b3 100644 --- a/platform/util/src/com/intellij/util/ReflectionCache.java +++ b/platform/util/src/com/intellij/util/ReflectionCache.java @@ -15,70 +15,30 @@ */ package com.intellij.util; -import com.intellij.util.containers.ConcurrentFactoryMap; import org.jetbrains.annotations.NotNull; -import java.lang.reflect.*; +import java.lang.reflect.Method; +import java.lang.reflect.ParameterizedType; +import java.lang.reflect.Type; +import java.lang.reflect.TypeVariable; /** + * Contrary to the name, this class doesn't do any caching. So the usages may be safely dropped in favor of plain reflection calls. + * + * Consider caching higher-level things, if you see reflection in your snapshots. + * * @author peter */ @SuppressWarnings({"MismatchedQueryAndUpdateOfCollection"}) public class ReflectionCache { - private static final ConcurrentFactoryMap ourSuperClasses = new ConcurrentFactoryMap() { - @Override - protected Class create(final Class key) { - return key.getSuperclass(); - } - }; - private static final ConcurrentFactoryMap ourInterfaces = new ConcurrentFactoryMap() { - @Override - @NotNull - protected Class[] create(final Class key) { - Class[] classes = key.getInterfaces(); - return classes.length == 0 ? ArrayUtil.EMPTY_CLASS_ARRAY : classes; - } - }; - - private static final ConcurrentFactoryMap ourIsInterfaces = new ConcurrentFactoryMap() { - @Override - @NotNull - protected Boolean create(final Class key) { - return key.isInterface(); - } - }; - private static final ConcurrentFactoryMap ourTypeParameters = new ConcurrentFactoryMap() { - @Override - @NotNull - protected TypeVariable[] create(final Class key) { - return key.getTypeParameters(); - } - }; - private static final ConcurrentFactoryMap ourGenericInterfaces = new ConcurrentFactoryMap() { - @Override - @NotNull - protected Type[] create(final Class key) { - return key.getGenericInterfaces(); - } - }; - private static final ConcurrentFactoryMap ourActualTypeArguments = new ConcurrentFactoryMap() { - @Override - @NotNull - protected Type[] create(final ParameterizedType key) { - return key.getActualTypeArguments(); - } - }; - - private ReflectionCache() { - } public static Class getSuperClass(@NotNull Class aClass) { - return ourSuperClasses.get(aClass); + return aClass.getSuperclass(); } @NotNull public static Class[] getInterfaces(@NotNull Class aClass) { - return ourInterfaces.get(aClass); + return aClass.getInterfaces(); } @NotNull @@ -95,22 +55,22 @@ public class ReflectionCache { } public static boolean isInterface(@NotNull Class aClass) { - return ourIsInterfaces.get(aClass); + return aClass.isInterface(); } @NotNull public static TypeVariable>[] getTypeParameters(@NotNull Class aClass) { - return ourTypeParameters.get(aClass); + return aClass.getTypeParameters(); } @NotNull public static Type[] getGenericInterfaces(@NotNull Class aClass) { - return ourGenericInterfaces.get(aClass); + return aClass.getGenericInterfaces(); } @NotNull public static Type[] getActualTypeArguments(@NotNull ParameterizedType type) { - return ourActualTypeArguments.get(type); + return type.getActualTypeArguments(); } } diff --git a/plugins/copyright/src/com/maddyhome/idea/copyright/CopyrightManager.java b/plugins/copyright/src/com/maddyhome/idea/copyright/CopyrightManager.java index e5ee2804c871..0b36db82a451 100644 --- a/plugins/copyright/src/com/maddyhome/idea/copyright/CopyrightManager.java +++ b/plugins/copyright/src/com/maddyhome/idea/copyright/CopyrightManager.java @@ -33,6 +33,7 @@ import com.intellij.openapi.roots.ProjectRootManager; import com.intellij.openapi.startup.StartupManager; import com.intellij.openapi.util.*; import com.intellij.openapi.util.io.FileUtil; +import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.packageDependencies.DependencyValidationManager; import com.intellij.psi.PsiFile; @@ -58,11 +59,11 @@ import java.util.*; storages = {@Storage(file = StoragePathMacros.PROJECT_FILE), @Storage(file = StoragePathMacros.PROJECT_CONFIG_DIR + "/copyright/", scheme = StorageScheme.DIRECTORY_BASED, stateSplitter = CopyrightManager.CopyrightStateSplitter.class)}) -public class CopyrightManager extends AbstractProjectComponent implements JDOMExternalizable, PersistentStateComponent { +public class CopyrightManager extends AbstractProjectComponent implements PersistentStateComponent { private static final Logger LOG = Logger.getInstance("#" + CopyrightManager.class.getName()); @Nullable private CopyrightProfile myDefaultCopyright = null; - private final LinkedHashMap myModule2Copyrights = new LinkedHashMap(); + private final LinkedHashMap myModuleToCopyrights = new LinkedHashMap(); private final Map myCopyrights = new HashMap(); private final Options myOptions = new Options(); @@ -92,10 +93,10 @@ public class CopyrightManager extends AbstractProjectComponent implements JDOMEx final Document document = e.getDocument(); final VirtualFile virtualFile = fileDocumentManager.getFile(document); if (virtualFile == null) return; - if (!newFileTracker.poll(virtualFile)) return; - if (!fileTypeUtil.isSupportedFile(virtualFile)) return; final Module module = projectRootManager.getFileIndex().getModuleForFile(virtualFile); if (module == null) return; + if (!newFileTracker.poll(virtualFile)) return; + if (!fileTypeUtil.isSupportedFile(virtualFile)) return; final PsiFile file = psiManager.findFile(virtualFile); if (file == null) return; application.invokeLater(new Runnable() { @@ -140,64 +141,68 @@ public class CopyrightManager extends AbstractProjectComponent implements JDOMEx return "CopyrightManager"; } - @Override - public void readExternal(Element element) throws InvalidDataException { - clearCopyrights(); - final Element module2copyright = element.getChild(MODULE2COPYRIGHT); - if (module2copyright != null) { - for (Object o : module2copyright.getChildren(ELEMENT)) { - final Element el = (Element)o; - final String moduleName = el.getAttributeValue(MODULE); - final String copyrightName = el.getAttributeValue(COPYRIGHT); - myModule2Copyrights.put(moduleName, copyrightName); - } - } - for (Object o : element.getChildren(COPYRIGHT)) { - final CopyrightProfile copyrightProfile = new CopyrightProfile(); - copyrightProfile.readExternal((Element)o); - myCopyrights.put(copyrightProfile.getName(), copyrightProfile); - } - myDefaultCopyright = myCopyrights.get(element.getAttributeValue(DEFAULT)); - myOptions.readExternal(element); - } - - @Override - public void writeExternal(Element element) throws WriteExternalException { - for (CopyrightProfile copyright : myCopyrights.values()) { - final Element copyrightElement = new Element(COPYRIGHT); - copyright.writeExternal(copyrightElement); - element.addContent(copyrightElement); - } - final Element map = new Element(MODULE2COPYRIGHT); - for (String moduleName : myModule2Copyrights.keySet()) { - final Element setting = new Element(ELEMENT); - setting.setAttribute(MODULE, moduleName); - setting.setAttribute(COPYRIGHT, myModule2Copyrights.get(moduleName)); - map.addContent(setting); - } - element.addContent(map); - element.setAttribute(DEFAULT, myDefaultCopyright != null ? myDefaultCopyright.getName() : ""); - myOptions.writeExternal(element); - } - - @Override public Element getState() { + Element state = new Element("settings"); + try { - final Element e = new Element("settings"); - writeExternal(e); - return e; + if (!myCopyrights.isEmpty()) { + for (CopyrightProfile copyright : myCopyrights.values()) { + final Element copyrightElement = new Element(COPYRIGHT); + copyright.writeExternal(copyrightElement); + state.addContent(copyrightElement); + } + } + + if (!myModuleToCopyrights.isEmpty()) { + final Element map = new Element(MODULE2COPYRIGHT); + for (String moduleName : myModuleToCopyrights.keySet()) { + final Element setting = new Element(ELEMENT); + setting.setAttribute(MODULE, moduleName); + setting.setAttribute(COPYRIGHT, myModuleToCopyrights.get(moduleName)); + map.addContent(setting); + } + state.addContent(map); + } + + myOptions.writeExternal(state); } - catch (WriteExternalException e1) { - LOG.error(e1); + catch (WriteExternalException e) { + LOG.error(e); return null; } + + if (myDefaultCopyright != null) { + state.setAttribute(DEFAULT, myDefaultCopyright.getName()); + } + else { + // todo we still add empty attribute to avoid annoying change (idea 12 - attribute exists, idea 13 - attribute doesn't exists) + // CR-IC-3403#CFR-62470, idea <= 12 compatibility + state.setAttribute(DEFAULT, ""); + } + + return state; } @Override public void loadState(Element state) { + clearCopyrights(); + + final Element moduleToCopyright = state.getChild(MODULE2COPYRIGHT); + if (moduleToCopyright != null) { + for (Element element : moduleToCopyright.getChildren(ELEMENT)) { + myModuleToCopyrights.put(element.getAttributeValue(MODULE), element.getAttributeValue(COPYRIGHT)); + } + } + try { - readExternal(state); + for (Element element : state.getChildren(COPYRIGHT)) { + final CopyrightProfile copyrightProfile = new CopyrightProfile(); + copyrightProfile.readExternal(element); + myCopyrights.put(copyrightProfile.getName(), copyrightProfile); + } + myDefaultCopyright = myCopyrights.get(StringUtil.notNullize(state.getAttributeValue(DEFAULT))); + myOptions.readExternal(state); } catch (InvalidDataException e) { LOG.error(e); @@ -205,7 +210,7 @@ public class CopyrightManager extends AbstractProjectComponent implements JDOMEx } public Map getCopyrightsMapping() { - return myModule2Copyrights; + return myModuleToCopyrights; } public void setDefaultCopyright(@Nullable CopyrightProfile copyright) { @@ -223,8 +228,8 @@ public class CopyrightManager extends AbstractProjectComponent implements JDOMEx public void removeCopyright(CopyrightProfile copyrightProfile) { myCopyrights.values().remove(copyrightProfile); - for (Iterator it = myModule2Copyrights.keySet().iterator(); it.hasNext();) { - final String profileName = myModule2Copyrights.get(it.next()); + for (Iterator it = myModuleToCopyrights.keySet().iterator(); it.hasNext();) { + final String profileName = myModuleToCopyrights.get(it.next()); if (profileName.equals(copyrightProfile.getName())) { it.remove(); } @@ -234,15 +239,15 @@ public class CopyrightManager extends AbstractProjectComponent implements JDOMEx public void clearCopyrights() { myDefaultCopyright = null; myCopyrights.clear(); - myModule2Copyrights.clear(); + myModuleToCopyrights.clear(); } public void mapCopyright(String scopeName, String copyrightProfileName) { - myModule2Copyrights.put(scopeName, copyrightProfileName); + myModuleToCopyrights.put(scopeName, copyrightProfileName); } public void unmapCopyright(String scopeName) { - myModule2Copyrights.remove(scopeName); + myModuleToCopyrights.remove(scopeName); } public Collection getCopyrights() { @@ -250,7 +255,7 @@ public class CopyrightManager extends AbstractProjectComponent implements JDOMEx } public boolean hasAnyCopyrights() { - return myDefaultCopyright != null || !myModule2Copyrights.isEmpty(); + return myDefaultCopyright != null || !myModuleToCopyrights.isEmpty(); } @Nullable @@ -258,13 +263,13 @@ public class CopyrightManager extends AbstractProjectComponent implements JDOMEx final VirtualFile virtualFile = file.getVirtualFile(); if (virtualFile == null || myOptions.getOptions(virtualFile.getFileType().getName()).getFileTypeOverride() == LanguageOptions.NO_COPYRIGHT) return null; final DependencyValidationManager validationManager = DependencyValidationManager.getInstance(myProject); - for (String scopeName : myModule2Copyrights.keySet()) { + for (String scopeName : myModuleToCopyrights.keySet()) { final NamedScope namedScope = validationManager.getScope(scopeName); if (namedScope != null) { final PackageSet packageSet = namedScope.getValue(); if (packageSet != null) { if (packageSet.contains(file, validationManager)) { - final CopyrightProfile profile = myCopyrights.get(myModule2Copyrights.get(scopeName)); + final CopyrightProfile profile = myCopyrights.get(myModuleToCopyrights.get(scopeName)); if (profile != null) { return profile; } @@ -330,7 +335,7 @@ public class CopyrightManager extends AbstractProjectComponent implements JDOMEx target.addContent(state); } for (Object attr : element.getAttributes()) { - target.setAttribute((Attribute)((Attribute)attr).clone()); + target.setAttribute(((Attribute)attr).clone()); } } } diff --git a/plugins/copyright/src/com/maddyhome/idea/copyright/actions/RecursionDlg.form b/plugins/copyright/src/com/maddyhome/idea/copyright/actions/RecursionDlg.form deleted file mode 100644 index c5d6d7aa135a..000000000000 --- a/plugins/copyright/src/com/maddyhome/idea/copyright/actions/RecursionDlg.form +++ /dev/null @@ -1,50 +0,0 @@ - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
diff --git a/plugins/copyright/src/com/maddyhome/idea/copyright/actions/RecursionDlg.java b/plugins/copyright/src/com/maddyhome/idea/copyright/actions/RecursionDlg.java deleted file mode 100644 index 3898c90c4b89..000000000000 --- a/plugins/copyright/src/com/maddyhome/idea/copyright/actions/RecursionDlg.java +++ /dev/null @@ -1,190 +0,0 @@ -/* - * Copyright 2000-2009 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.maddyhome.idea.copyright.actions; - -import com.intellij.openapi.diagnostic.Logger; -import com.intellij.openapi.project.Project; -import com.intellij.openapi.roots.ProjectFileIndex; -import com.intellij.openapi.roots.ProjectRootManager; -import com.intellij.openapi.ui.DialogWrapper; -import com.intellij.openapi.vfs.VirtualFile; -import com.intellij.uiDesigner.core.GridConstraints; -import com.intellij.uiDesigner.core.GridLayoutManager; - -import javax.swing.*; -import java.awt.*; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; - -public class RecursionDlg extends DialogWrapper -{ - public RecursionDlg(Project project, VirtualFile file) - { - super(project, false); - - logger.debug("file=" + file); - - this.project = project; - this.file = file; - - setupControls(); - - init(); - } - - public boolean isAll() - { - return rbAll.isSelected(); - } - - public boolean includeSubdirs() - { - return cbSubdirs.isSelected(); - } - - private void setupControls() - { - setTitle("Update Copyright"); - - setOKButtonText("Run"); - - ButtonGroup group = new ButtonGroup(); - group.add(rbFile); - group.add(rbAll); - - rbFile.setMnemonic('F'); - rbAll.setMnemonic('A'); - cbSubdirs.setMnemonic('I'); - - if (file.isDirectory()) - { - rbFile.setText("File"); - rbFile.setEnabled(false); - rbAll.setText("All files in " + file.getPresentableUrl()); - rbAll.setSelected(true); - cbSubdirs.setSelected(true); - cbSubdirs.setEnabled(true); - } - else - { - VirtualFile parent = file.getParent(); - rbFile.setText("File '" + file.getPresentableUrl() + '\''); - rbFile.setSelected(true); - if (parent != null) - { - rbAll.setText("All files in " + parent.getPresentableUrl()); - cbSubdirs.setSelected(true); - cbSubdirs.setEnabled(false); - } - else - { - rbAll.setVisible(false); - cbSubdirs.setVisible(false); - } - } - - VirtualFile check = file; - if (!file.isDirectory()) - { - check = file.getParent(); - } - ProjectRootManager prm = ProjectRootManager.getInstance(project); - ProjectFileIndex pfi = prm.getFileIndex(); - - VirtualFile[] children = check != null ? check.getChildren() : VirtualFile.EMPTY_ARRAY; - boolean hasSubdirs = false; - for (int i = 0; i < children.length && !hasSubdirs; i++) - { - if (children[i].isDirectory() && !pfi.isIgnored(children[i])) - { - hasSubdirs = true; - } - } - - cbSubdirs.setVisible(hasSubdirs); - if (!hasSubdirs) - { - cbSubdirs.setEnabled(false); - mainPanel.remove(cbSubdirs); - } - - ActionListener listener = new ActionListener() - { - public void actionPerformed(ActionEvent e) - { - if (cbSubdirs.isVisible()) - { - cbSubdirs.setEnabled(rbAll.isSelected()); - } - } - }; - - rbFile.addActionListener(listener); - rbAll.addActionListener(listener); - } - - protected JComponent createCenterPanel() - { - return mainPanel; - } - - { -// GUI initializer generated by IntelliJ IDEA GUI Designer -// >>> IMPORTANT!! <<< -// DO NOT EDIT OR ADD ANY CODE HERE! - $$$setupUI$$$(); - } - - /** - * Method generated by IntelliJ IDEA GUI Designer >>> IMPORTANT!! <<< DO NOT edit this method OR call it in your - * code! - */ - private void $$$setupUI$$$() - { - mainPanel = new JPanel(); - mainPanel.setLayout(new GridLayoutManager(3, 2, new Insets(0, 0, 0, 0), -1, -1)); - rbFile = new JRadioButton(); - rbFile.setText("File"); - mainPanel.add(rbFile, new GridConstraints(0, 0, 1, 2, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, - GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, - GridConstraints.SIZEPOLICY_FIXED, null, null, null)); - rbAll = new JRadioButton(); - rbAll.setText("All"); - mainPanel.add(rbAll, new GridConstraints(1, 0, 1, 2, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, - GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, - GridConstraints.SIZEPOLICY_FIXED, null, null, null)); - cbSubdirs = new JCheckBox(); - cbSubdirs.setText("Include subdirectories"); - mainPanel.add(cbSubdirs, new GridConstraints(2, 1, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, - GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, - GridConstraints.SIZEPOLICY_FIXED, null, null, null)); - final JLabel label1 = new JLabel(); - label1.setText(" "); - mainPanel.add(label1, new GridConstraints(2, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, - GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null)); - } - - private final VirtualFile file; - private JPanel mainPanel; - private JRadioButton rbFile; - private JRadioButton rbAll; - private JCheckBox cbSubdirs; - private final Project project; - - private static final Logger logger = Logger.getInstance(RecursionDlg.class.getName()); - -} \ No newline at end of file diff --git a/plugins/copyright/src/com/maddyhome/idea/copyright/actions/UpdateCopyrightAction.java b/plugins/copyright/src/com/maddyhome/idea/copyright/actions/UpdateCopyrightAction.java index db0101803a22..a372331e0c2b 100644 --- a/plugins/copyright/src/com/maddyhome/idea/copyright/actions/UpdateCopyrightAction.java +++ b/plugins/copyright/src/com/maddyhome/idea/copyright/actions/UpdateCopyrightAction.java @@ -16,21 +16,24 @@ package com.maddyhome.idea.copyright.actions; +import com.intellij.analysis.AnalysisScope; +import com.intellij.analysis.BaseAnalysisAction; import com.intellij.openapi.actionSystem.*; import com.intellij.openapi.editor.Editor; -import com.intellij.openapi.module.Module; +import com.intellij.openapi.module.ModuleUtilCore; import com.intellij.openapi.project.Project; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.*; -import com.intellij.psi.util.PsiUtilCore; import com.maddyhome.idea.copyright.CopyrightManager; import com.maddyhome.idea.copyright.pattern.FileUtil; import com.maddyhome.idea.copyright.util.FileTypeUtil; +import org.jetbrains.annotations.NotNull; -import java.util.ArrayList; -import java.util.List; +public class UpdateCopyrightAction extends BaseAnalysisAction { + protected UpdateCopyrightAction() { + super(UpdateCopyrightProcessor.TITLE, UpdateCopyrightProcessor.TITLE); + } -public class UpdateCopyrightAction extends AnAction { public void update(AnActionEvent event) { final boolean enabled = isEnabled(event); event.getPresentation().setEnabled(enabled); @@ -94,79 +97,14 @@ public class UpdateCopyrightAction extends AnAction { return true; } - public void actionPerformed(AnActionEvent event) { - final DataContext context = event.getDataContext(); - final Project project = CommonDataKeys.PROJECT.getData(context); - assert project != null; - - final Module module = LangDataKeys.MODULE.getData(context); - PsiDocumentManager.getInstance(project).commitAllDocuments(); - - final VirtualFile[] files = CommonDataKeys.VIRTUAL_FILE_ARRAY.getData(context); - final Editor editor = CommonDataKeys.EDITOR.getData(context); - - PsiFile file = null; - PsiDirectory dir; - if (editor != null) { - file = PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument()); - if (file == null) { - return; + @Override + protected void analyze(@NotNull final Project project, @NotNull AnalysisScope scope) { + if (scope.checkScopeWritable(project)) return; + scope.accept(new PsiElementVisitor() { + @Override + public void visitFile(PsiFile file) { + new UpdateCopyrightProcessor(project, ModuleUtilCore.findModuleForPsiElement(file), file).run(); } - dir = file.getContainingDirectory(); - } - else { - if (FileUtil.areFiles(files)) { - new UpdateCopyrightProcessor(project, null, FileUtil.convertToPsiFiles(files, project)).run(); - return; - } - final Module modCtx = LangDataKeys.MODULE_CONTEXT.getData(context); - if (modCtx != null) { - new UpdateCopyrightProcessor(project, module).run(); - return; - } - - final Module[] modules = LangDataKeys.MODULE_CONTEXT_ARRAY.getData(context); - if (modules != null && modules.length > 0) { - List psiFiles = new ArrayList(); - for (Module mod : modules) { - AbstractFileProcessor.findFiles(mod, psiFiles); - } - new UpdateCopyrightProcessor(project, null, PsiUtilCore.toPsiFileArray(psiFiles)).run(); - return; - } - - final PsiElement psielement = CommonDataKeys.PSI_ELEMENT.getData(context); - if (psielement == null) { - return; - } - - if (psielement instanceof PsiDirectoryContainer) { - dir = ((PsiDirectoryContainer)psielement).getDirectories()[0]; - } - else if (psielement instanceof PsiDirectory) { - dir = (PsiDirectory)psielement; - } - else { - file = psielement.getContainingFile(); - if (file == null) { - return; - } - dir = file.getContainingDirectory(); - } - } - - final RecursionDlg recDlg = new RecursionDlg(project, file != null ? file.getVirtualFile() : dir.getVirtualFile()); - recDlg.show(); - if (!recDlg.isOK()) { - return; - } - - if (recDlg.isAll()) { - new UpdateCopyrightProcessor(project, module, dir, recDlg.includeSubdirs()).run(); - } - else { - new UpdateCopyrightProcessor(project, module, file).run(); - } + }); } - } \ No newline at end of file diff --git a/plugins/copyright/src/com/maddyhome/idea/copyright/actions/UpdateCopyrightProcessor.java b/plugins/copyright/src/com/maddyhome/idea/copyright/actions/UpdateCopyrightProcessor.java index 513b862c2413..dceefc6fd6e7 100644 --- a/plugins/copyright/src/com/maddyhome/idea/copyright/actions/UpdateCopyrightProcessor.java +++ b/plugins/copyright/src/com/maddyhome/idea/copyright/actions/UpdateCopyrightProcessor.java @@ -35,6 +35,9 @@ import com.maddyhome.idea.copyright.util.FileTypeUtil; public class UpdateCopyrightProcessor extends AbstractFileProcessor { + public static final String TITLE = "Update Copyright"; + public static final String MESSAGE = "Updating copyrights..."; + public UpdateCopyrightProcessor(Project project, Module module) { super(project, module, TITLE, MESSAGE); @@ -115,8 +118,5 @@ public class UpdateCopyrightProcessor extends AbstractFileProcessor private Project project; private Module module; - private static final String TITLE = "Update Copyright"; - private static final String MESSAGE = "Updating copyrights..."; - private static final Logger logger = Logger.getInstance(UpdateCopyrightProcessor.class.getName()); } diff --git a/plugins/copyright/src/com/maddyhome/idea/copyright/options/LanguageOptions.java b/plugins/copyright/src/com/maddyhome/idea/copyright/options/LanguageOptions.java index 501fa0bec80e..5df860efc776 100644 --- a/plugins/copyright/src/com/maddyhome/idea/copyright/options/LanguageOptions.java +++ b/plugins/copyright/src/com/maddyhome/idea/copyright/options/LanguageOptions.java @@ -16,10 +16,13 @@ package com.maddyhome.idea.copyright.options; -import com.intellij.openapi.util.*; +import com.intellij.openapi.util.DefaultJDOMExternalizer; +import com.intellij.openapi.util.DifferenceFilter; +import com.intellij.openapi.util.InvalidDataException; +import com.intellij.openapi.util.WriteExternalException; import org.jdom.Element; -public class LanguageOptions implements JDOMExternalizable, Cloneable { +public class LanguageOptions implements Cloneable { public static final int NO_COPYRIGHT = 1; public static final int USE_TEMPLATE = 2; public static final int USE_TEXT = 3; diff --git a/plugins/copyright/src/com/maddyhome/idea/copyright/options/Options.java b/plugins/copyright/src/com/maddyhome/idea/copyright/options/Options.java index 35722e924154..8ca3c763437e 100644 --- a/plugins/copyright/src/com/maddyhome/idea/copyright/options/Options.java +++ b/plugins/copyright/src/com/maddyhome/idea/copyright/options/Options.java @@ -20,7 +20,6 @@ import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.fileTypes.FileType; import com.intellij.openapi.fileTypes.StdFileTypes; import com.intellij.openapi.util.InvalidDataException; -import com.intellij.openapi.util.JDOMExternalizable; import com.intellij.openapi.util.WriteExternalException; import com.maddyhome.idea.copyright.CopyrightUpdaters; import com.maddyhome.idea.copyright.psi.UpdateCopyrightsProvider; @@ -34,196 +33,161 @@ import java.util.TreeMap; /** */ -public class Options implements JDOMExternalizable, Cloneable -{ - public LanguageOptions getOptions(String name) - { - String lang = FileTypeUtil.getInstance().getFileTypeNameByName(name); - LanguageOptions res = options.get(lang); - if (res == null) - { - // NOTE: If any change is made here you need to update ConfigTabFactory and UpdateCopyrightFactory too. - final FileType fileType = FileTypeUtil.getInstance().getFileTypeByName(name); - if (fileType != null) { - final UpdateCopyrightsProvider provider = CopyrightUpdaters.INSTANCE.forFileType(fileType); - if (provider != null) return provider.getDefaultOptions(); +public class Options implements Cloneable { + public LanguageOptions getOptions(String name) { + String lang = FileTypeUtil.getInstance().getFileTypeNameByName(name); + LanguageOptions res = options.get(lang); + if (res == null) { + // NOTE: If any change is made here you need to update ConfigTabFactory and UpdateCopyrightFactory too. + final FileType fileType = FileTypeUtil.getInstance().getFileTypeByName(name); + if (fileType != null) { + final UpdateCopyrightsProvider provider = CopyrightUpdaters.INSTANCE.forFileType(fileType); + if (provider != null) return provider.getDefaultOptions(); + } + res = new LanguageOptions(); + } + + return res; + } + + public LanguageOptions getTemplateOptions() { + return getOptions(LANG_TEMPLATE); + } + + public void setOptions(String name, LanguageOptions options) { + String lang = FileTypeUtil.getInstance().getFileTypeNameByName(name); + this.options.put(lang, options); + } + + public void setTemplateOptions(LanguageOptions options) { + setOptions(LANG_TEMPLATE, options); + } + + @Nullable + public LanguageOptions getMergedOptions(String name) { + try { + LanguageOptions lang = getOptions(name).clone(); + LanguageOptions temp = getTemplateOptions().clone(); + switch (lang.getFileTypeOverride()) { + case LanguageOptions.USE_TEMPLATE: + temp.setFileLocation(lang.getFileLocation()); + temp.setFileTypeOverride(lang.getFileTypeOverride()); + lang = temp; + break; + case LanguageOptions.USE_TEXT: + break; + } + + return lang; + } + catch (CloneNotSupportedException e) { + // This shouldn't happen + } + + return null; + } + + + public void readExternal(Element element) throws InvalidDataException { + logger.debug("readExternal()"); + List languageOptions = element.getChildren("LanguageOptions"); + if (languageOptions != null && !languageOptions.isEmpty()) { + //noinspection ForLoopReplaceableByForEach + for (int i = 0; i < languageOptions.size(); i++) { + Element languageOption = languageOptions.get(i); + // NOTE: If any change is made here you need to update ConfigTabFactory and UpdateCopyrightFactory too. + LanguageOptions opts = new LanguageOptions(); + opts.readExternal(languageOption); + setOptions(languageOption.getAttributeValue("name"), opts); + } + } + else { + Element root = null; + Element jOpts = element.getChild("JavaOptions"); + if (jOpts != null) // version 2.1.x + { + root = jOpts; + } + else // versions 0.0.1 - 2.0.x + { + Element child = element.getChild("option"); + if (child != null && child.getAttribute("name") != null) { + root = element; + } + } + if (root != null) { + String languageName = StdFileTypes.JAVA.getName(); + // NOTE: If any change is made here you need to update ConfigTabFactory and UpdateCopyrightFactory too. + LanguageOptions opts = new LanguageOptions(); + opts.setFileTypeOverride(LanguageOptions.USE_TEMPLATE); + for (Object option : root.getChildren("option")) { + String name = ((Element)option).getAttributeValue("name"); + String val = ((Element)option).getAttributeValue("value"); + if ("body".equals(name)) { + //todo opts.setNotice(val); + } + else if ("location".equals(name)) { + opts.setFileLocation(Integer.parseInt(val)); } - res = new LanguageOptions(); } - return res; + setOptions(languageName, opts); + } } - public LanguageOptions getTemplateOptions() - { - return getOptions(LANG_TEMPLATE); + logger.debug("options=" + this); + } + + public void writeExternal(Element element) throws WriteExternalException { + logger.debug("writeExternal()"); + + for (String lang : options.keySet()) { + Element elem = new Element("LanguageOptions"); + elem.setAttribute("name", lang); + element.addContent(elem); + options.get(lang).writeExternal(elem); } - public void setOptions(String name, LanguageOptions options) - { - String lang = FileTypeUtil.getInstance().getFileTypeNameByName(name); - this.options.put(lang, options); + logger.debug("options=" + this); + } + + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; } - public void setTemplateOptions(LanguageOptions options) - { - setOptions(LANG_TEMPLATE, options); + final Options options1 = (Options)o; + + return options.equals(options1.options); + } + + public int hashCode() { + int result; + result = options.hashCode(); + return result; + } + + public String toString() { + return "Options" + "{options=" + options + '}'; + } + + @Override + public Options clone() throws CloneNotSupportedException { + Options res = (Options)super.clone(); + res.options = new TreeMap(); + for (String lang : options.keySet()) { + LanguageOptions opts = options.get(lang); + res.options.put(lang, opts.clone()); } - @Nullable - public LanguageOptions getMergedOptions(String name) - { - try - { - LanguageOptions lang = getOptions(name).clone(); - LanguageOptions temp = getTemplateOptions().clone(); - switch (lang.getFileTypeOverride()){ - case LanguageOptions.USE_TEMPLATE: - temp.setFileLocation(lang.getFileLocation()); - temp.setFileTypeOverride(lang.getFileTypeOverride()); - lang = temp; - break; - case LanguageOptions.USE_TEXT: - break; - } + return res; + } - return lang; - } - catch (CloneNotSupportedException e) - { - // This shouldn't happen - } + private Map options = new TreeMap(); + private static final String LANG_TEMPLATE = "__TEMPLATE__"; - return null; - } - - - public void readExternal(Element element) throws InvalidDataException - { - logger.debug("readExternal()"); - List langs = element.getChildren("LanguageOptions"); - if (langs != null && langs.size() > 0) - { - //noinspection ForLoopReplaceableByForEach - for (int i = 0; i < langs.size(); i++) - { - Element lang = (Element)langs.get(i); - String name = lang.getAttributeValue("name"); - // NOTE: If any change is made here you need to update ConfigTabFactory and UpdateCopyrightFactory too. - LanguageOptions opts = new LanguageOptions(); - opts.readExternal(lang); - - setOptions(name, opts); - } - } - else - { - Element root = null; - Element jOpts = element.getChild("JavaOptions"); - if (jOpts != null) // version 2.1.x - { - root = jOpts; - } - else // versions 0.0.1 - 2.0.x - { - Element child = element.getChild("option"); - if (child != null && child.getAttribute("name") != null) - { - root = element; - } - } - if (root != null) - { - String lname = StdFileTypes.JAVA.getName(); - // NOTE: If any change is made here you need to update ConfigTabFactory and UpdateCopyrightFactory too. - LanguageOptions opts = new LanguageOptions(); - opts.setFileTypeOverride(LanguageOptions.USE_TEMPLATE); - List children = root.getChildren("option"); - for (Object option : children) - { - String name = ((Element)option).getAttributeValue("name"); - String val = ((Element)option).getAttributeValue("value"); - if ("body".equals(name)) - { - //todo opts.setNotice(val); - } - else if ("location".equals(name)) - { - opts.setFileLocation(Integer.parseInt(val)); - } - } - - setOptions(lname, opts); - } - } - - logger.debug("options=" + this); - } - - public void writeExternal(Element element) throws WriteExternalException - { - logger.debug("writeExternal()"); - - for (String lang : options.keySet()) - { - LanguageOptions opts = options.get(lang); - - Element elem = new Element("LanguageOptions"); - elem.setAttribute("name", lang); - element.addContent(elem); - opts.writeExternal(elem); - } - - logger.debug("options=" + this); - } - - public boolean equals(Object o) - { - if (this == o) - { - return true; - } - if (o == null || getClass() != o.getClass()) - { - return false; - } - - final Options options1 = (Options)o; - - return options.equals(options1.options); - } - - public int hashCode() - { - int result; - result = options.hashCode(); - return result; - } - - public String toString() - { - final StringBuffer sb = new StringBuffer(); - sb.append("Options"); - sb.append("{options=").append(options); - sb.append('}'); - return sb.toString(); - } - - public Options clone() throws CloneNotSupportedException - { - Options res = (Options)super.clone(); - res.options = new TreeMap(); - for (String lang : options.keySet()) - { - LanguageOptions opts = options.get(lang); - res.options.put(lang, opts.clone()); - } - - return res; - } - - private Map options = new TreeMap(); - private static final String LANG_TEMPLATE = "__TEMPLATE__"; - - private static final Logger logger = Logger.getInstance(Options.class.getName()); + private static final Logger logger = Logger.getInstance(Options.class.getName()); } \ No newline at end of file diff --git a/plugins/git4idea/remote-servers-git/src/com/intellij/remoteServer/util/CloudGitDeploymentConfiguratorBase.java b/plugins/git4idea/remote-servers-git/src/com/intellij/remoteServer/util/CloudGitDeploymentConfiguratorBase.java new file mode 100644 index 000000000000..c1fb091012cc --- /dev/null +++ b/plugins/git4idea/remote-servers-git/src/com/intellij/remoteServer/util/CloudGitDeploymentConfiguratorBase.java @@ -0,0 +1,59 @@ +package com.intellij.remoteServer.util; + +import com.intellij.openapi.module.Module; +import com.intellij.openapi.module.ModuleManager; +import com.intellij.openapi.module.ModulePointerManager; +import com.intellij.openapi.project.Project; +import com.intellij.remoteServer.ServerType; +import com.intellij.remoteServer.configuration.ServerConfiguration; +import com.intellij.remoteServer.configuration.deployment.DeploymentConfiguration; +import com.intellij.remoteServer.configuration.deployment.DeploymentConfigurator; +import com.intellij.remoteServer.configuration.deployment.DeploymentSource; +import com.intellij.remoteServer.impl.configuration.deployment.ModuleDeploymentSourceImpl; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +/** + * @author michael.golubev + */ +public abstract class CloudGitDeploymentConfiguratorBase + extends DeploymentConfigurator { + + private final Project myProject; + private ServerType myServerType; + + public CloudGitDeploymentConfiguratorBase(Project project, ServerType serverType) { + myProject = project; + myServerType = serverType; + } + + @Nullable + public static CloudGitDeploymentSourceHandlerProvider getDeploymentSourceHandlerProvider(ServerType serverType) { + for (CloudGitDeploymentSourceHandlerProvider provider : CloudGitDeploymentSourceHandlerProvider.EP_NAME.getExtensions()) { + if (provider.getServerType() == serverType) { + return provider; + } + } + return null; + } + + @NotNull + @Override + public List getAvailableDeploymentSources() { + if (myProject.isDefault()) return Collections.emptyList(); + List result = new ArrayList(); + ModulePointerManager pointerManager = ModulePointerManager.getInstance(myProject); + for (Module module : ModuleManager.getInstance(myProject).getModules()) { + result.add(new ModuleDeploymentSourceImpl(pointerManager.create(module))); + } + CloudGitDeploymentSourceHandlerProvider provider = getDeploymentSourceHandlerProvider(myServerType); + if (provider != null) { + result.addAll(provider.getDeploymentSources(myProject)); + } + return result; + } +} diff --git a/plugins/git4idea/remote-servers-git/src/com/intellij/remoteServer/util/CloudGitDeploymentRuntime.java b/plugins/git4idea/remote-servers-git/src/com/intellij/remoteServer/util/CloudGitDeploymentRuntime.java index 41bc988f23af..74bf0ea3b8e5 100644 --- a/plugins/git4idea/remote-servers-git/src/com/intellij/remoteServer/util/CloudGitDeploymentRuntime.java +++ b/plugins/git4idea/remote-servers-git/src/com/intellij/remoteServer/util/CloudGitDeploymentRuntime.java @@ -12,7 +12,9 @@ import com.intellij.openapi.util.Key; import com.intellij.openapi.util.Ref; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.vcs.VcsException; +import com.intellij.openapi.vfs.LocalFileSystem; import com.intellij.openapi.vfs.VirtualFile; +import com.intellij.remoteServer.ServerType; import com.intellij.remoteServer.agent.util.CloudGitAgent; import com.intellij.remoteServer.agent.util.CloudGitAgentDeployment; import com.intellij.remoteServer.agent.util.CloudGitApplication; @@ -38,6 +40,8 @@ import org.jetbrains.annotations.Nullable; import java.io.File; import java.io.IOException; +import java.util.ArrayList; +import java.util.List; /** * @author michael.golubev @@ -53,6 +57,7 @@ public abstract class CloudGitDeploymentRuntime serverType) throws ServerRuntimeException { myConfiguration = serverConfiguration; myTasksExecutor = taskExecutor; myLogManager = logManager; @@ -84,25 +90,31 @@ public abstract class CloudGitDeploymentRuntime handlers = new ArrayList(); + handlers.add(new ModuleDeploymentSourceHandler()); + CloudGitDeploymentSourceHandlerProvider handlerProvider + = CloudGitDeploymentConfiguratorBase.getDeploymentSourceHandlerProvider(serverType); + if (handlerProvider != null) { + handlers.addAll(handlerProvider.getHandlers(this)); + } DeploymentSource deploymentSource = task.getSource(); - if (!(deploymentSource instanceof ModuleDeploymentSource)) { - throw new ServerRuntimeException("Module deployment source is the only supported"); + for (DeploymentSourceHandler sourceHandler : handlers) { + if (sourceHandler.init(deploymentSource)) { + mySourceHandler = sourceHandler; + break; + } + } + if (mySourceHandler == null) { + throw new ServerRuntimeException("Unknown deployment source"); } - ModuleDeploymentSource moduleDeploymentSource = (ModuleDeploymentSource)deploymentSource; - Module module = moduleDeploymentSource.getModule(); - if (module == null) { - throw new ServerRuntimeException("Module not found: " + moduleDeploymentSource.getModulePointer().getModuleName()); - } - - VirtualFile contentRoot = moduleDeploymentSource.getContentRoot(); - LOG.assertTrue(contentRoot != null, "Content root is not found"); - myContentRoot = contentRoot; - - File contentRootFile = moduleDeploymentSource.getFile(); - LOG.assertTrue(contentRootFile != null, "Content root file is not found"); + File contentRootFile = mySourceHandler.getRepositoryRootFile(); myContentRootFile = contentRootFile; + VirtualFile contentRoot = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(myContentRootFile); + LOG.assertTrue(contentRoot != null, "Repository root is not found"); + myContentRoot = contentRoot; + myProject = task.getProject(); myGitRepositoryManager = GitUtil.getRepositoryManager(myProject); myGit = ServiceManager.getService(Git.class); @@ -142,59 +154,7 @@ public abstract class CloudGitDeploymentRuntime EP_NAME + = ExtensionPointName.create("Git4Idea.remoteServer.CloudGitDeploymentSourceHandlerProvider"); + + ServerType getServerType(); + + Collection getDeploymentSources(Project project); + + List getHandlers(CloudGitDeploymentRuntime deploymentRuntime); +} diff --git a/plugins/git4idea/src/META-INF/plugin.xml b/plugins/git4idea/src/META-INF/plugin.xml index 0c98e1491a7b..1d2beb25ad28 100644 --- a/plugins/git4idea/src/META-INF/plugin.xml +++ b/plugins/git4idea/src/META-INF/plugin.xml @@ -193,6 +193,8 @@ - + + diff --git a/plugins/gradle/src/META-INF/services/org.jetbrains.plugins.gradle.model.ModelBuilderService b/plugins/gradle/src/META-INF/services/org.jetbrains.plugins.gradle.model.ModelBuilderService index a07e3541f5eb..3989c7cb0610 100644 --- a/plugins/gradle/src/META-INF/services/org.jetbrains.plugins.gradle.model.ModelBuilderService +++ b/plugins/gradle/src/META-INF/services/org.jetbrains.plugins.gradle.model.ModelBuilderService @@ -13,6 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # -org.jetbrains.plugins.gradle.model.impl.WarModelBuilderImpl -org.jetbrains.plugins.gradle.model.impl.ModelDependenciesBuilderImpl -org.jetbrains.plugins.gradle.model.impl.ModuleExtendedModelBuilderImpl +org.jetbrains.plugins.gradle.model.builder.WarModelBuilderImpl +org.jetbrains.plugins.gradle.model.builder.ModelDependenciesBuilderImpl +org.jetbrains.plugins.gradle.model.builder.ModuleExtendedModelBuilderImpl diff --git a/plugins/gradle/src/org/jetbrains/plugins/gradle/integrations/maven/ImportMavenRepositoriesTask.java b/plugins/gradle/src/org/jetbrains/plugins/gradle/integrations/maven/ImportMavenRepositoriesTask.java index 13ffa5e0ed3c..54e898b96649 100644 --- a/plugins/gradle/src/org/jetbrains/plugins/gradle/integrations/maven/ImportMavenRepositoriesTask.java +++ b/plugins/gradle/src/org/jetbrains/plugins/gradle/integrations/maven/ImportMavenRepositoriesTask.java @@ -73,6 +73,8 @@ public class ImportMavenRepositoriesTask implements Runnable { @Override public void run() { + if(myProject.isDisposed()) return; + final LocalFileSystem localFileSystem = LocalFileSystem.getInstance(); final List psiFileList = ContainerUtil.newArrayList(); diff --git a/plugins/gradle/src/org/jetbrains/plugins/gradle/model/GradleDependencyScope.java b/plugins/gradle/src/org/jetbrains/plugins/gradle/model/GradleDependencyScope.java new file mode 100644 index 000000000000..65f31567a7ae --- /dev/null +++ b/plugins/gradle/src/org/jetbrains/plugins/gradle/model/GradleDependencyScope.java @@ -0,0 +1,132 @@ +/* + * 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.model; + +import org.jetbrains.annotations.Nullable; + +/** + * @author Vladislav.Soroka + * @since 11/25/13 + */ +public enum GradleDependencyScope { + // Implicit scopes + PROVIDED("provided", "provided", true, true, true, true), + OPTIONAL("optional", "compile", true, true, true, true), + + + // Java Plugin Scopes + /** + * Compile time dependencies + */ + COMPILE("compile", "compile", true, true, true, true), + /** + * Runtime dependencies + */ + RUNTIME("runtime", "runtime", false, true, false, true), + /** + * Additional dependencies for compiling tests. + */ + TEST_COMPILE("testCompile", "test", false, false, true, true), + /** + * Additional dependencies for running tests only. + */ + TEST_RUNTIME("testRuntime", "test", false, false, false, true), + + + // War Plugin Scopes + /** + * the same scope as the compile scope dependencies, except that they are not added to the WAR archive. + */ + PROVIDED_COMPILE("providedCompile", "provided", true, true, true, true), + /** + * the same scope as the runtime scope dependencies, except that they are not added to the WAR archive. + */ + PROVIDED_RUNTIME("providedRuntime", "provided", false, true, false, true), + + // Groovy Plugin Scopes + /** + * Compiles production Groovy source files. + */ + COMPILE_GROOVY("compileGroovy", "compile", true, true, true, true), + /** + * Compiles test Groovy source files. + */ + COMPILE_TEST_GROOVY("compileTestGroovy", "test", false, false, true, true), + + // Scala Plugin Scopes + /** + * Compiles production Scala source files. + */ + COMPILE_SCALA("compileScala", "compile", true, true, true, true), + /** + * Compiles test Scala source files. + */ + COMPILE_TEST_SCALA("compileTestScala", "test", false, false, true, true); + + private final String myGradleName; + private final String myIdeaMappingName; + private final boolean myForProductionCompile; + private final boolean myForProductionRuntime; + private final boolean myForTestCompile; + private final boolean myForTestRuntime; + + GradleDependencyScope(String gradleName, + String ideaMappingName, + boolean forProductionCompile, + boolean forProductionRuntime, + boolean forTestCompile, + boolean forTestRuntime) { + myGradleName = gradleName; + myIdeaMappingName = ideaMappingName; + myForProductionCompile = forProductionCompile; + myForProductionRuntime = forProductionRuntime; + myForTestCompile = forTestCompile; + myForTestRuntime = forTestRuntime; + } + + public boolean isForProductionCompile() { + return myForProductionCompile; + } + + public boolean isForProductionRuntime() { + return myForProductionRuntime; + } + + public boolean isForTestCompile() { + return myForTestCompile; + } + + public boolean isForTestRuntime() { + return myForTestRuntime; + } + + @Nullable + public static GradleDependencyScope fromName(final String scopeName) { + for (GradleDependencyScope scope : values()) { + if (scope.myGradleName.equals(scopeName)) return scope; + } + return null; + } + + public String getIdeaMappingName() { + return myIdeaMappingName; + } + + @Override + public String toString() { + return myGradleName; + } +} diff --git a/plugins/gradle/src/org/jetbrains/plugins/gradle/model/ProjectDependenciesModel.java b/plugins/gradle/src/org/jetbrains/plugins/gradle/model/ProjectDependenciesModel.java index 584d9cf37e6c..45828b4991ba 100644 --- a/plugins/gradle/src/org/jetbrains/plugins/gradle/model/ProjectDependenciesModel.java +++ b/plugins/gradle/src/org/jetbrains/plugins/gradle/model/ProjectDependenciesModel.java @@ -15,8 +15,7 @@ */ package org.jetbrains.plugins.gradle.model; -import org.jetbrains.plugins.gradle.model.impl.GradleDependency; -import org.jetbrains.plugins.gradle.model.impl.GradleDependencyImpl; +import org.gradle.tooling.model.idea.IdeaDependency; import java.io.Serializable; import java.util.List; @@ -29,5 +28,5 @@ public interface ProjectDependenciesModel extends Serializable { String getProjectName(); - List getDependencies(); + List getDependencies(); } diff --git a/plugins/gradle/src/org/jetbrains/plugins/gradle/model/builder/ModelDependenciesBuilderImpl.java b/plugins/gradle/src/org/jetbrains/plugins/gradle/model/builder/ModelDependenciesBuilderImpl.java new file mode 100644 index 000000000000..8eb1c678f370 --- /dev/null +++ b/plugins/gradle/src/org/jetbrains/plugins/gradle/model/builder/ModelDependenciesBuilderImpl.java @@ -0,0 +1,196 @@ +/* + * 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.model.builder; + +import org.gradle.api.Project; +import org.gradle.api.artifacts.Configuration; +import org.gradle.api.artifacts.ModuleVersionIdentifier; +import org.gradle.plugins.ide.idea.IdeaPlugin; +import org.gradle.plugins.ide.idea.model.IdeaModel; +import org.gradle.plugins.ide.internal.IdeDependenciesExtractor; +import org.gradle.tooling.model.idea.IdeaDependency; +import org.jetbrains.annotations.Nullable; +import org.jetbrains.plugins.gradle.model.GradleDependencyScope; +import org.jetbrains.plugins.gradle.model.ModelBuilderService; +import org.jetbrains.plugins.gradle.model.ProjectDependenciesModel; +import org.jetbrains.plugins.gradle.model.internal.*; + +import java.util.*; + +/** + * @author Vladislav.Soroka + * @since 11/5/13 + */ +public class ModelDependenciesBuilderImpl implements ModelBuilderService { + + @Override + public boolean canBuild(String modelName) { + return ProjectDependenciesModel.class.getName().equals(modelName); + } + + @Nullable + @Override + public Object buildAll(final String modelName, final Project project) { + final List dependencies = new ArrayList(); + + final Map scopesMap = new HashMap(); + final IdeDependenciesExtractor dependenciesExtractor = new IdeDependenciesExtractor(); + + boolean offline = false; + boolean downloadJavadoc = false; + boolean downloadSources = true; + + final IdeaPlugin ideaPlugin = project.getPlugins().getPlugin(IdeaPlugin.class); + if (ideaPlugin != null) { + IdeaModel ideaModel = ideaPlugin.getModel(); + if (ideaModel != null && ideaModel.getModule() == null) { + offline = ideaModel.getModule().isOffline(); + downloadJavadoc = ideaModel.getModule().isDownloadJavadoc(); + downloadSources = ideaModel.getModule().isDownloadSources(); + } + } + + for (final Configuration configuration : project.getConfigurations()) { + Collection plusConfigurations = new ArrayList(); + plusConfigurations.add(configuration); + + final List ideProjectDependencies = + dependenciesExtractor.extractProjectDependencies(plusConfigurations, new ArrayList()); + + for (IdeDependenciesExtractor.IdeProjectDependency ideProjectDependency : ideProjectDependencies) { + merge(scopesMap, ideProjectDependency); + } + + if (!offline) { + final Collection ideRepoFileDependencies = + dependenciesExtractor.extractRepoFileDependencies( + project.getConfigurations(), plusConfigurations, new ArrayList(), downloadSources, downloadJavadoc); + for (IdeDependenciesExtractor.IdeRepoFileDependency repoFileDependency : ideRepoFileDependencies) { + merge(scopesMap, repoFileDependency); + } + } + + final List ideLocalFileDependencies = + dependenciesExtractor.extractLocalFileDependencies(plusConfigurations, new ArrayList()); + for (IdeDependenciesExtractor.IdeLocalFileDependency fileDependency : ideLocalFileDependencies) { + merge(scopesMap, fileDependency); + } + } + + for (Map.Entry entry : scopesMap.entrySet()) { + DependencyVersionId versionId = entry.getKey(); + for (GradleDependencyScope scope : entry.getValue().getScopes()) { + if (versionId.getIdeDependency() instanceof IdeDependenciesExtractor.IdeRepoFileDependency) { + IdeDependenciesExtractor.IdeRepoFileDependency repoFileDependency = + (IdeDependenciesExtractor.IdeRepoFileDependency)versionId.getIdeDependency(); + IdeaSingleEntryLibraryDependencyImpl libraryDependency = new IdeaSingleEntryLibraryDependencyImpl( + new IdeaDependencyScopeImpl(scope), + versionId.getName(), + versionId.getGroup(), + versionId.getVersion() + ); + libraryDependency.setFile(repoFileDependency.getFile()); + libraryDependency.setSource(repoFileDependency.getSourceFile()); + libraryDependency.setJavadoc(repoFileDependency.getJavadocFile()); + dependencies.add(libraryDependency); + } + else if (versionId.getIdeDependency() instanceof IdeDependenciesExtractor.IdeProjectDependency) { + IdeaModuleDependencyImpl moduleDependency = new IdeaModuleDependencyImpl( + new IdeaDependencyScopeImpl(scope), + versionId.getName(), + versionId.getGroup(), + versionId.getVersion() + ); + moduleDependency.setIdeaModule(new StubIdeaModule(versionId.getName())); + dependencies.add(moduleDependency); + } + else if (versionId.getIdeDependency() instanceof IdeDependenciesExtractor.IdeLocalFileDependency) { + IdeDependenciesExtractor.IdeLocalFileDependency fileDependency = + (IdeDependenciesExtractor.IdeLocalFileDependency)versionId.getIdeDependency(); + IdeaSingleEntryLibraryDependencyImpl libraryDependency = new IdeaSingleEntryLibraryDependencyImpl( + new IdeaDependencyScopeImpl(scope), + versionId.getName(), + versionId.getGroup(), + versionId.getVersion() + ); + libraryDependency.setFile(fileDependency.getFile()); + dependencies.add(libraryDependency); + } + } + } + + return new ProjectDependenciesModelImpl(project.getPath(), dependencies); + } + + private static void merge(Map map, IdeDependenciesExtractor.IdeProjectDependency dependency) { + final String configurationName = dependency.getDeclaredConfiguration().getName(); + final GradleDependencyScope scope = GradleDependencyScope.fromName(configurationName); + if (scope == null) return; + + final Project project = dependency.getProject(); + final String version = project.hasProperty("version") ? str(project.property("version")) : ""; + final String group = project.hasProperty("group") ? str(project.property("group")) : ""; + + DependencyVersionId versionId = + new DependencyVersionId(dependency, project.getName(), group, version); + Scopes scopes = map.get(versionId); + if (scopes == null) { + map.put(versionId, new Scopes(scope)); + } + else { + scopes.add(scope); + } + } + + private static String str(Object o) { + return String.valueOf(o == null ? "" : o); + } + + private static void merge(Map map, IdeDependenciesExtractor.IdeRepoFileDependency dependency) { + final String configurationName = dependency.getDeclaredConfiguration().getName(); + final GradleDependencyScope scope = GradleDependencyScope.fromName(configurationName); + if (scope == null) return; + + ModuleVersionIdentifier dependencyId = dependency.getId(); + DependencyVersionId versionId = + new DependencyVersionId(dependency, dependencyId.getName(), dependencyId.getGroup(), dependencyId.getVersion()); + Scopes scopes = map.get(versionId); + if (scopes == null) { + map.put(versionId, new Scopes(scope)); + } + else { + scopes.add(scope); + } + } + + private static void merge(Map map, IdeDependenciesExtractor.IdeLocalFileDependency dependency) { + + final String configurationName = dependency.getDeclaredConfiguration().getName(); + final GradleDependencyScope scope = GradleDependencyScope.fromName(configurationName); + if (scope == null) return; + + String path = dependency.getFile().getPath(); + DependencyVersionId versionId = + new DependencyVersionId(dependency, path, "", ""); + Scopes scopes = map.get(versionId); + if (scopes == null) { + map.put(versionId, new Scopes(scope)); + } + else { + scopes.add(scope); + } + } +} diff --git a/plugins/gradle/src/org/jetbrains/plugins/gradle/model/impl/ModuleExtendedModelBuilderImpl.java b/plugins/gradle/src/org/jetbrains/plugins/gradle/model/builder/ModuleExtendedModelBuilderImpl.java similarity index 97% rename from plugins/gradle/src/org/jetbrains/plugins/gradle/model/impl/ModuleExtendedModelBuilderImpl.java rename to plugins/gradle/src/org/jetbrains/plugins/gradle/model/builder/ModuleExtendedModelBuilderImpl.java index 59ed7692bc71..3dc854020c6c 100644 --- a/plugins/gradle/src/org/jetbrains/plugins/gradle/model/impl/ModuleExtendedModelBuilderImpl.java +++ b/plugins/gradle/src/org/jetbrains/plugins/gradle/model/builder/ModuleExtendedModelBuilderImpl.java @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.jetbrains.plugins.gradle.model.impl; +package org.jetbrains.plugins.gradle.model.builder; import org.gradle.api.Project; import org.gradle.api.Task; @@ -29,6 +29,7 @@ import org.jetbrains.plugins.gradle.model.ModelBuilderService; import org.jetbrains.plugins.gradle.model.ModuleExtendedModel; import org.jetbrains.plugins.gradle.model.internal.IdeaContentRootImpl; import org.jetbrains.plugins.gradle.model.internal.IdeaSourceDirectoryImpl; +import org.jetbrains.plugins.gradle.model.internal.ModuleExtendedModelImpl; import java.io.File; import java.io.IOException; diff --git a/plugins/gradle/src/org/jetbrains/plugins/gradle/model/impl/WarModelBuilderImpl.java b/plugins/gradle/src/org/jetbrains/plugins/gradle/model/builder/WarModelBuilderImpl.java similarity index 97% rename from plugins/gradle/src/org/jetbrains/plugins/gradle/model/impl/WarModelBuilderImpl.java rename to plugins/gradle/src/org/jetbrains/plugins/gradle/model/builder/WarModelBuilderImpl.java index 9964d0b47cce..8a1d2a133bf8 100644 --- a/plugins/gradle/src/org/jetbrains/plugins/gradle/model/impl/WarModelBuilderImpl.java +++ b/plugins/gradle/src/org/jetbrains/plugins/gradle/model/builder/WarModelBuilderImpl.java @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.jetbrains.plugins.gradle.model.impl; +package org.jetbrains.plugins.gradle.model.builder; import org.gradle.api.Action; import org.gradle.api.Project; @@ -27,6 +27,7 @@ import org.gradle.api.tasks.bundling.War; import org.jetbrains.annotations.Nullable; import org.jetbrains.plugins.gradle.model.ModelBuilderService; import org.jetbrains.plugins.gradle.model.WarModel; +import org.jetbrains.plugins.gradle.model.internal.WarModelImpl; import java.io.File; import java.io.StringWriter; diff --git a/plugins/gradle/src/org/jetbrains/plugins/gradle/model/impl/ModelDependenciesBuilderImpl.java b/plugins/gradle/src/org/jetbrains/plugins/gradle/model/impl/ModelDependenciesBuilderImpl.java deleted file mode 100644 index 6f151bd9a2aa..000000000000 --- a/plugins/gradle/src/org/jetbrains/plugins/gradle/model/impl/ModelDependenciesBuilderImpl.java +++ /dev/null @@ -1,108 +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.model.impl; - -import org.gradle.api.Project; -import org.gradle.api.artifacts.*; -import org.jetbrains.annotations.Nullable; -import org.jetbrains.plugins.gradle.model.ModelBuilderService; -import org.jetbrains.plugins.gradle.model.ProjectDependenciesModel; - -import java.util.ArrayList; -import java.util.List; -import java.util.Set; - -/** - * @author Vladislav.Soroka - * @since 11/5/13 - */ -public class ModelDependenciesBuilderImpl implements ModelBuilderService { - - @Override - public boolean canBuild(String modelName) { - return ProjectDependenciesModel.class.getName().equals(modelName); - } - - @Nullable - @Override - public Object buildAll(String modelName, Project project) { - List dependencies = new ArrayList(); - - for (Configuration configuration : project.getConfigurations()) { - for (Dependency dependency : configuration.getDependencies()) { - if (dependency instanceof ClientModule) { - ClientModule clientModule = (ClientModule)dependency; - for (ModuleDependency moduleDependency : clientModule.getDependencies()) { - dependencies.add( - new GradleDependencyImpl( - configuration.getName(), - moduleDependency.getName(), - moduleDependency.getGroup(), - moduleDependency.getVersion() - )); - ResolvedDependency resolvedDependency = - findResolvedDependency(moduleDependency, configuration.getResolvedConfiguration().getFirstLevelModuleDependencies()); - if (resolvedDependency != null) { - addTransitiveDependencies(dependencies, configuration.getName(), resolvedDependency.getChildren()); - } - } - } - dependencies.add( - new GradleDependencyImpl( - configuration.getName(), - dependency.getName(), - dependency.getGroup(), - dependency.getVersion() - )); - } - } - return new ProjectDependenciesModelImpl(project.getPath(), dependencies); - } - - private static void addTransitiveDependencies(List dependencies, - String configurationName, - Set resolvedDependencies) { - if (resolvedDependencies == null) return; - for (ResolvedDependency resolvedDependency : resolvedDependencies) { - dependencies.add( - new GradleDependencyImpl( - configurationName, - resolvedDependency.getModuleName(), - resolvedDependency.getModuleGroup(), - resolvedDependency.getModuleVersion() - )); - addTransitiveDependencies(dependencies, configurationName, resolvedDependency.getChildren()); - } - } - - private static ResolvedDependency findResolvedDependency(ModuleDependency moduleDependency, - Set resolvedDependencies) { - for (ResolvedDependency resolvedDependency : resolvedDependencies) { - ResolvedDependency dependency = findResolvedDependency(moduleDependency, resolvedDependency.getChildren()); - if (dependency != null) return dependency; - if (isEqual(resolvedDependency.getModuleName(), moduleDependency.getName()) && - isEqual(resolvedDependency.getModuleGroup(), moduleDependency.getGroup()) && - isEqual(resolvedDependency.getModuleVersion(), moduleDependency.getVersion())) { - return resolvedDependency; - } - } - return null; - } - - private static boolean isEqual(String str1, String str2) { - return str1 != null ? str1.equals(str2) : str2 == null; - } -} diff --git a/plugins/gradle/src/org/jetbrains/plugins/gradle/model/impl/GradleDependencyImpl.java b/plugins/gradle/src/org/jetbrains/plugins/gradle/model/internal/AbstractGradleDependency.java similarity index 65% rename from plugins/gradle/src/org/jetbrains/plugins/gradle/model/impl/GradleDependencyImpl.java rename to plugins/gradle/src/org/jetbrains/plugins/gradle/model/internal/AbstractGradleDependency.java index 9a113ea01920..662806a4881d 100644 --- a/plugins/gradle/src/org/jetbrains/plugins/gradle/model/impl/GradleDependencyImpl.java +++ b/plugins/gradle/src/org/jetbrains/plugins/gradle/model/internal/AbstractGradleDependency.java @@ -13,41 +13,45 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.jetbrains.plugins.gradle.model.impl; +package org.jetbrains.plugins.gradle.model.internal; + +import org.gradle.tooling.model.idea.IdeaDependencyScope; + +import java.io.Serializable; /** * @author Vladislav.Soroka * @since 11/8/13 */ -public class GradleDependencyImpl implements GradleDependency { - private final String configurationName; +public abstract class AbstractGradleDependency implements Serializable { + private final IdeaDependencyScope myScope; private final String dependencyName; private final String dependencyGroup; private final String dependencyVersion; - public GradleDependencyImpl(String configurationName, String dependencyName, String dependencyGroup, String dependencyVersion) { - this.configurationName = configurationName; + public AbstractGradleDependency(IdeaDependencyScope myScope, String dependencyName, String dependencyGroup, String dependencyVersion) { + this.myScope = myScope; this.dependencyName = dependencyName; this.dependencyGroup = dependencyGroup; this.dependencyVersion = dependencyVersion; } - @Override - public String getConfigurationName() { - return configurationName; + public IdeaDependencyScope getScope() { + return myScope; + } + + public boolean getExported() { + return "compile".equals(myScope.getScope()) || "runtime".equals(myScope.getScope()); } - @Override public String getDependencyName() { return dependencyName; } - @Override public String getDependencyGroup() { return dependencyGroup; } - @Override public String getDependencyVersion() { return dependencyVersion; } @@ -55,20 +59,22 @@ public class GradleDependencyImpl implements GradleDependency { @Override public boolean equals(Object o) { if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; + if (!(o instanceof AbstractGradleDependency)) return false; - GradleDependencyImpl that = (GradleDependencyImpl)o; + AbstractGradleDependency that = (AbstractGradleDependency)o; if (dependencyGroup != null ? !dependencyGroup.equals(that.dependencyGroup) : that.dependencyGroup != null) return false; if (dependencyName != null ? !dependencyName.equals(that.dependencyName) : that.dependencyName != null) return false; if (dependencyVersion != null ? !dependencyVersion.equals(that.dependencyVersion) : that.dependencyVersion != null) return false; + if (myScope != null ? !myScope.equals(that.myScope) : that.myScope != null) return false; return true; } @Override public int hashCode() { - int result = dependencyName != null ? dependencyName.hashCode() : 0; + int result = myScope != null ? myScope.hashCode() : 0; + result = 31 * result + (dependencyName != null ? dependencyName.hashCode() : 0); result = 31 * result + (dependencyGroup != null ? dependencyGroup.hashCode() : 0); result = 31 * result + (dependencyVersion != null ? dependencyVersion.hashCode() : 0); return result; @@ -76,11 +82,12 @@ public class GradleDependencyImpl implements GradleDependency { @Override public String toString() { - return "GradleDependencyImpl{" + - "configurationName='" + configurationName + '\'' + + return "GradleDependency{" + + "myScope=" + myScope + ", dependencyName='" + dependencyName + '\'' + ", dependencyGroup='" + dependencyGroup + '\'' + ", dependencyVersion='" + dependencyVersion + '\'' + + ", exported=" + getExported() + '}'; } } diff --git a/plugins/gradle/src/org/jetbrains/plugins/gradle/model/internal/DependencyVersionId.java b/plugins/gradle/src/org/jetbrains/plugins/gradle/model/internal/DependencyVersionId.java new file mode 100644 index 000000000000..cc1387035864 --- /dev/null +++ b/plugins/gradle/src/org/jetbrains/plugins/gradle/model/internal/DependencyVersionId.java @@ -0,0 +1,83 @@ +/* + * 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.model.internal; + +import org.gradle.plugins.ide.internal.IdeDependenciesExtractor; + +/** +* @author Vladislav.Soroka +* @since 11/25/13 +*/ +public class DependencyVersionId { + private final IdeDependenciesExtractor.IdeDependency myIdeDependency; + private final String name; + private final String group; + private final String version; + + public DependencyVersionId(IdeDependenciesExtractor.IdeDependency dependency, String name, String group, String version) { + myIdeDependency = dependency; + this.name = name; + this.group = group; + this.version = version; + } + + public String getName() { + return name; + } + + public String getGroup() { + return group; + } + + public String getVersion() { + return version; + } + + public IdeDependenciesExtractor.IdeDependency getIdeDependency() { + return myIdeDependency; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (!(o instanceof DependencyVersionId)) return false; + + DependencyVersionId id = (DependencyVersionId)o; + + if (group != null ? !group.equals(id.group) : id.group != null) return false; + if (name != null ? !name.equals(id.name) : id.name != null) return false; + if (version != null ? !version.equals(id.version) : id.version != null) return false; + + return true; + } + + @Override + public int hashCode() { + int result = name != null ? name.hashCode() : 0; + result = 31 * result + (group != null ? group.hashCode() : 0); + result = 31 * result + (version != null ? version.hashCode() : 0); + return result; + } + + @Override + public String toString() { + return "DependencyVersionId{" + + "name='" + name + '\'' + + ", group='" + group + '\'' + + ", version='" + version + '\'' + + '}'; + } +} diff --git a/plugins/gradle/src/org/jetbrains/plugins/gradle/model/internal/IdeaDependencyScopeImpl.java b/plugins/gradle/src/org/jetbrains/plugins/gradle/model/internal/IdeaDependencyScopeImpl.java new file mode 100644 index 000000000000..aa7f5af7e656 --- /dev/null +++ b/plugins/gradle/src/org/jetbrains/plugins/gradle/model/internal/IdeaDependencyScopeImpl.java @@ -0,0 +1,61 @@ +/* + * 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.model.internal; + +import org.gradle.tooling.model.idea.IdeaDependencyScope; +import org.jetbrains.plugins.gradle.model.GradleDependencyScope; + +import java.io.Serializable; + +/** + * @author Vladislav.Soroka + * @since 11/25/13 + */ +public class IdeaDependencyScopeImpl implements IdeaDependencyScope, Serializable { + + private final GradleDependencyScope myDependencyScope; + + public IdeaDependencyScopeImpl(GradleDependencyScope scope) { + myDependencyScope = scope; + } + + @Override + public String getScope() { + return myDependencyScope.getIdeaMappingName(); + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (!(o instanceof IdeaDependencyScopeImpl)) return false; + + IdeaDependencyScopeImpl scope = (IdeaDependencyScopeImpl)o; + + if (myDependencyScope != scope.myDependencyScope) return false; + + return true; + } + + @Override + public int hashCode() { + return myDependencyScope != null ? myDependencyScope.hashCode() : 0; + } + + @Override + public String toString() { + return "IdeaDependencyScope{" + myDependencyScope + '}'; + } +} diff --git a/plugins/gradle/src/org/jetbrains/plugins/gradle/model/internal/IdeaModuleDependencyImpl.java b/plugins/gradle/src/org/jetbrains/plugins/gradle/model/internal/IdeaModuleDependencyImpl.java new file mode 100644 index 000000000000..e35d049c5030 --- /dev/null +++ b/plugins/gradle/src/org/jetbrains/plugins/gradle/model/internal/IdeaModuleDependencyImpl.java @@ -0,0 +1,46 @@ +/* + * 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.model.internal; + +import org.gradle.tooling.model.idea.IdeaDependencyScope; +import org.gradle.tooling.model.idea.IdeaModule; +import org.gradle.tooling.model.idea.IdeaModuleDependency; + +import java.io.Serializable; + +/** + * @author Vladislav.Soroka + * @since 11/25/13 + */ +public class IdeaModuleDependencyImpl extends AbstractGradleDependency + implements IdeaModuleDependency, Serializable { + private IdeaModule myIdeaModule; + + public IdeaModuleDependencyImpl(IdeaDependencyScope myScope, + String dependencyName, + String dependencyGroup, String dependencyVersion) { + super(myScope, dependencyName, dependencyGroup, dependencyVersion); + } + + @Override + public IdeaModule getDependencyModule() { + return myIdeaModule; + } + + public void setIdeaModule(IdeaModule ideaModule) { + myIdeaModule = ideaModule; + } +} diff --git a/plugins/gradle/src/org/jetbrains/plugins/gradle/model/internal/IdeaSingleEntryLibraryDependencyImpl.java b/plugins/gradle/src/org/jetbrains/plugins/gradle/model/internal/IdeaSingleEntryLibraryDependencyImpl.java new file mode 100644 index 000000000000..bb77b89036fe --- /dev/null +++ b/plugins/gradle/src/org/jetbrains/plugins/gradle/model/internal/IdeaSingleEntryLibraryDependencyImpl.java @@ -0,0 +1,73 @@ +/* + * 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.model.internal; + +import org.gradle.tooling.model.GradleModuleVersion; +import org.gradle.tooling.model.idea.IdeaDependencyScope; +import org.gradle.tooling.model.idea.IdeaSingleEntryLibraryDependency; + +import java.io.File; +import java.io.Serializable; + +/** + * @author Vladislav.Soroka + * @since 11/25/13 + */ +public class IdeaSingleEntryLibraryDependencyImpl extends AbstractGradleDependency + implements IdeaSingleEntryLibraryDependency, Serializable { + + private File myFile; + private File mySource; + private File myJavadoc; + + public IdeaSingleEntryLibraryDependencyImpl(IdeaDependencyScope myScope, + String dependencyName, + String dependencyGroup, String dependencyVersion) { + super(myScope, dependencyName, dependencyGroup, dependencyVersion); + } + + @Override + public File getFile() { + return myFile; + } + + @Override + public File getSource() { + return mySource; + } + + @Override + public File getJavadoc() { + return myJavadoc; + } + + public void setFile(File file) { + myFile = file; + } + + public void setSource(File source) { + mySource = source; + } + + public void setJavadoc(File javadoc) { + myJavadoc = javadoc; + } + + @Override + public GradleModuleVersion getGradleModuleVersion() { + return null; + } +} diff --git a/plugins/gradle/src/org/jetbrains/plugins/gradle/model/impl/ModuleExtendedModelImpl.java b/plugins/gradle/src/org/jetbrains/plugins/gradle/model/internal/ModuleExtendedModelImpl.java similarity index 97% rename from plugins/gradle/src/org/jetbrains/plugins/gradle/model/impl/ModuleExtendedModelImpl.java rename to plugins/gradle/src/org/jetbrains/plugins/gradle/model/internal/ModuleExtendedModelImpl.java index d915e6a78415..b8bce40264cc 100644 --- a/plugins/gradle/src/org/jetbrains/plugins/gradle/model/impl/ModuleExtendedModelImpl.java +++ b/plugins/gradle/src/org/jetbrains/plugins/gradle/model/internal/ModuleExtendedModelImpl.java @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.jetbrains.plugins.gradle.model.impl; +package org.jetbrains.plugins.gradle.model.internal; import org.gradle.tooling.model.DomainObjectSet; import org.gradle.tooling.model.internal.ImmutableDomainObjectSet; diff --git a/plugins/gradle/src/org/jetbrains/plugins/gradle/model/impl/ProjectDependenciesModelImpl.java b/plugins/gradle/src/org/jetbrains/plugins/gradle/model/internal/ProjectDependenciesModelImpl.java similarity index 80% rename from plugins/gradle/src/org/jetbrains/plugins/gradle/model/impl/ProjectDependenciesModelImpl.java rename to plugins/gradle/src/org/jetbrains/plugins/gradle/model/internal/ProjectDependenciesModelImpl.java index 2285b227dbd6..533c35084fa2 100644 --- a/plugins/gradle/src/org/jetbrains/plugins/gradle/model/impl/ProjectDependenciesModelImpl.java +++ b/plugins/gradle/src/org/jetbrains/plugins/gradle/model/internal/ProjectDependenciesModelImpl.java @@ -13,8 +13,9 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.jetbrains.plugins.gradle.model.impl; +package org.jetbrains.plugins.gradle.model.internal; +import org.gradle.tooling.model.idea.IdeaDependency; import org.jetbrains.plugins.gradle.model.ProjectDependenciesModel; import java.util.List; @@ -25,9 +26,9 @@ import java.util.List; */ public class ProjectDependenciesModelImpl implements ProjectDependenciesModel { private final String projectName; - private final List myDependencies; + private final List myDependencies; - public ProjectDependenciesModelImpl(String projectName, List dependencies) { + public ProjectDependenciesModelImpl(String projectName, List dependencies) { this.projectName = projectName; myDependencies = dependencies; } @@ -38,7 +39,7 @@ public class ProjectDependenciesModelImpl implements ProjectDependenciesModel { } @Override - public List getDependencies() { + public List getDependencies() { return myDependencies; } diff --git a/plugins/gradle/src/org/jetbrains/plugins/gradle/model/internal/Scopes.java b/plugins/gradle/src/org/jetbrains/plugins/gradle/model/internal/Scopes.java new file mode 100644 index 000000000000..3c08f521a549 --- /dev/null +++ b/plugins/gradle/src/org/jetbrains/plugins/gradle/model/internal/Scopes.java @@ -0,0 +1,79 @@ +/* + * 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.model.internal; + +import org.jetbrains.plugins.gradle.model.GradleDependencyScope; + +/** + * @author Vladislav.Soroka + * @since 11/25/13 + */ +public class Scopes { + private boolean myForProductionCompile; + private boolean myForProductionRuntime; + private boolean myForTestCompile; + private boolean myForTestRuntime; + private boolean myIsProvided; + + public Scopes(GradleDependencyScope scope) { + myForProductionCompile = scope.isForProductionCompile(); + myForProductionRuntime = scope.isForProductionRuntime(); + myForTestCompile = scope.isForTestCompile(); + myForTestRuntime = scope.isForTestRuntime(); + myIsProvided = scope == GradleDependencyScope.PROVIDED_COMPILE || scope == GradleDependencyScope.PROVIDED_RUNTIME; + } + + public GradleDependencyScope[] getScopes() { + if (myIsProvided) { + if (myForProductionCompile && myForProductionRuntime && myForTestCompile && myForTestRuntime) { + return new GradleDependencyScope[]{GradleDependencyScope.PROVIDED_COMPILE}; + } + else if (!myForProductionCompile && myForProductionRuntime && !myForTestCompile && myForTestRuntime) { + return new GradleDependencyScope[]{GradleDependencyScope.PROVIDED_RUNTIME}; + } + else if (!myForProductionCompile && myForProductionRuntime && myForTestCompile && myForTestRuntime) { + return new GradleDependencyScope[]{GradleDependencyScope.TEST_COMPILE, GradleDependencyScope.PROVIDED_RUNTIME}; + } + } + + if (myForProductionCompile && myForProductionRuntime && myForTestCompile && myForTestRuntime) { + return new GradleDependencyScope[]{GradleDependencyScope.COMPILE}; + } + else if (!myForProductionCompile && myForProductionRuntime && !myForTestCompile && myForTestRuntime) { + return new GradleDependencyScope[]{GradleDependencyScope.RUNTIME}; + } + else if (!myForProductionCompile && !myForProductionRuntime && myForTestCompile && myForTestRuntime) { + return new GradleDependencyScope[]{GradleDependencyScope.TEST_COMPILE}; + } + else if (!myForProductionCompile && !myForProductionRuntime && !myForTestCompile && myForTestRuntime) { + return new GradleDependencyScope[]{GradleDependencyScope.TEST_RUNTIME}; + } + else if (!myForProductionCompile && myForProductionRuntime && myForTestCompile && myForTestRuntime) { + return new GradleDependencyScope[]{GradleDependencyScope.TEST_COMPILE, GradleDependencyScope.RUNTIME}; + } + else { + return new GradleDependencyScope[]{GradleDependencyScope.COMPILE}; + } + } + + public void add(GradleDependencyScope scope) { + myForProductionCompile = myForProductionCompile || scope.isForProductionCompile(); + myForProductionRuntime = myForProductionRuntime || scope.isForProductionRuntime(); + myForTestCompile = myForTestCompile || scope.isForTestCompile(); + myForTestRuntime = myForTestRuntime || scope.isForTestRuntime(); + myIsProvided = myIsProvided || scope == GradleDependencyScope.PROVIDED_COMPILE || scope == GradleDependencyScope.PROVIDED_RUNTIME; + } +} diff --git a/plugins/gradle/src/org/jetbrains/plugins/gradle/model/internal/StubIdeaModule.java b/plugins/gradle/src/org/jetbrains/plugins/gradle/model/internal/StubIdeaModule.java new file mode 100644 index 000000000000..0e8d2bc6068d --- /dev/null +++ b/plugins/gradle/src/org/jetbrains/plugins/gradle/model/internal/StubIdeaModule.java @@ -0,0 +1,81 @@ +/* + * 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.model.internal; + +import org.gradle.tooling.model.DomainObjectSet; +import org.gradle.tooling.model.GradleProject; +import org.gradle.tooling.model.HierarchicalElement; +import org.gradle.tooling.model.idea.*; + +import java.io.Serializable; + +/** + * @author Vladislav.Soroka + * @since 11/25/13 + */ +public class StubIdeaModule implements IdeaModule, Serializable { + + private final String name; + + public StubIdeaModule(String name) { + this.name = name; + } + + @Override + public DomainObjectSet getContentRoots() { + throw new UnsupportedOperationException(); + } + + @Override + public GradleProject getGradleProject() { + throw new UnsupportedOperationException(); + } + + @Override + public IdeaProject getParent() { + throw new UnsupportedOperationException(); + } + + @Override + public DomainObjectSet getChildren() { + throw new UnsupportedOperationException(); + } + + @Override + public IdeaProject getProject() { + throw new UnsupportedOperationException(); + } + + @Override + public IdeaCompilerOutput getCompilerOutput() { + throw new UnsupportedOperationException(); + } + + @Override + public DomainObjectSet getDependencies() { + throw new UnsupportedOperationException(); + } + + @Override + public String getName() { + return name; + } + + @Override + public String getDescription() { + throw new UnsupportedOperationException(); + } +} diff --git a/plugins/gradle/src/org/jetbrains/plugins/gradle/model/impl/WarModelImpl.java b/plugins/gradle/src/org/jetbrains/plugins/gradle/model/internal/WarModelImpl.java similarity index 97% rename from plugins/gradle/src/org/jetbrains/plugins/gradle/model/impl/WarModelImpl.java rename to plugins/gradle/src/org/jetbrains/plugins/gradle/model/internal/WarModelImpl.java index 56aa6d311e5c..6ebe710322be 100644 --- a/plugins/gradle/src/org/jetbrains/plugins/gradle/model/impl/WarModelImpl.java +++ b/plugins/gradle/src/org/jetbrains/plugins/gradle/model/internal/WarModelImpl.java @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.jetbrains.plugins.gradle.model.impl; +package org.jetbrains.plugins.gradle.model.internal; import org.jetbrains.plugins.gradle.model.WarModel; diff --git a/plugins/gradle/src/org/jetbrains/plugins/gradle/service/project/BaseGradleProjectResolverExtension.java b/plugins/gradle/src/org/jetbrains/plugins/gradle/service/project/BaseGradleProjectResolverExtension.java index b1c444b9167f..6b155a23092e 100644 --- a/plugins/gradle/src/org/jetbrains/plugins/gradle/service/project/BaseGradleProjectResolverExtension.java +++ b/plugins/gradle/src/org/jetbrains/plugins/gradle/service/project/BaseGradleProjectResolverExtension.java @@ -34,7 +34,6 @@ import com.intellij.openapi.module.StdModuleTypes; import com.intellij.openapi.roots.DependencyScope; import com.intellij.openapi.util.KeyValue; import com.intellij.openapi.util.io.FileUtil; -import com.intellij.openapi.util.text.StringUtil; import com.intellij.pom.java.LanguageLevel; import com.intellij.util.BooleanFunction; import com.intellij.util.PathUtil; @@ -53,7 +52,6 @@ import org.jetbrains.annotations.Nullable; import org.jetbrains.plugins.gradle.model.ExtIdeaContentRoot; import org.jetbrains.plugins.gradle.model.ModuleExtendedModel; import org.jetbrains.plugins.gradle.model.ProjectDependenciesModel; -import org.jetbrains.plugins.gradle.model.impl.GradleDependency; import org.jetbrains.plugins.gradle.util.GradleBundle; import org.jetbrains.plugins.gradle.util.GradleConstants; import org.jetbrains.plugins.gradle.util.GradleUtil; @@ -222,10 +220,11 @@ public class BaseGradleProjectResolverExtension implements GradleProjectResolver ProjectDependenciesModel dependenciesModel = resolverCtx.getExtraProject(gradleModule, ProjectDependenciesModel.class); - DomainObjectSet dependencies = gradleModule.getDependencies(); - if (dependencies == null) { - return; - } + final List dependencies = + dependenciesModel != null ? dependenciesModel.getDependencies() : gradleModule.getDependencies().getAll(); + + if (dependencies == null) return; + for (IdeaDependency dependency : dependencies) { if (dependency == null) { continue; @@ -243,10 +242,6 @@ public class BaseGradleProjectResolverExtension implements GradleProjectResolver else if (dependency instanceof IdeaSingleEntryLibraryDependency) { LibraryDependencyData d = buildDependency(ideModule, (IdeaSingleEntryLibraryDependency)dependency, ideProject); d.setExported(dependency.getExported()); - if (dependenciesModel != null) { - DependencyScope providedScope = parseProvidedScope(d, dependenciesModel.getDependencies()); - scope = providedScope == null ? scope : providedScope; - } if (scope != null) { d.setScope(scope); } @@ -497,19 +492,4 @@ public class BaseGradleProjectResolverExtension implements GradleProjectResolver private static boolean isIdeaTask(final String taskName) { return taskName.toLowerCase().contains("idea"); } - - @Nullable - private static DependencyScope parseProvidedScope(LibraryDependencyData libraryDependencyData, List dependencies) { - for (GradleDependency dependency : dependencies) { - String s = dependency.getDependencyName() + '-' + dependency.getDependencyVersion(); - if (libraryDependencyData.getName().equals(s)) { - String configurationName = dependency.getConfigurationName(); - if (StringUtil.startsWith(configurationName, "provided")) { - return DependencyScope.PROVIDED; - } - } - } - - return null; - } } diff --git a/plugins/gradle/src/org/jetbrains/plugins/gradle/service/project/GradleExecutionHelper.java b/plugins/gradle/src/org/jetbrains/plugins/gradle/service/project/GradleExecutionHelper.java index 6edaee4b5051..3de1b906432d 100644 --- a/plugins/gradle/src/org/jetbrains/plugins/gradle/service/project/GradleExecutionHelper.java +++ b/plugins/gradle/src/org/jetbrains/plugins/gradle/service/project/GradleExecutionHelper.java @@ -23,10 +23,7 @@ import com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskNotifica import com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskNotificationListener; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.text.StringUtil; -import com.intellij.util.ArrayUtilRt; -import com.intellij.util.Function; -import com.intellij.util.PathUtil; -import com.intellij.util.SystemProperties; +import com.intellij.util.*; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.containers.ContainerUtilRt; import org.gradle.StartParameter; @@ -47,8 +44,10 @@ import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.lang.reflect.Field; +import java.util.Collection; import java.util.Collections; import java.util.List; +import java.util.Set; import java.util.concurrent.TimeUnit; /** @@ -125,7 +124,7 @@ public class GradleExecutionHelper { return; } - List jvmArgs = ContainerUtilRt.newArrayList(); + Set jvmArgs = ContainerUtilRt.newHashSet(); String vmOptions = settings.getDaemonVmOptions(); if (!StringUtil.isEmpty(vmOptions)) { @@ -142,9 +141,18 @@ public class GradleExecutionHelper { if (!jvmArgs.isEmpty()) { BuildEnvironment buildEnvironment = getBuildEnvironment(connection); - List merged = + Collection merged = buildEnvironment != null ? mergeJvmArgs(buildEnvironment.getJava().getJvmArguments(), jvmArgs) : jvmArgs; - operation.setJvmArguments(ArrayUtilRt.toStringArray(merged)); + + // filter nulls and empty strings + List filteredArgs = ContainerUtil.mapNotNull(merged, new Function() { + @Override + public String fun(String s) { + return StringUtil.isEmpty(s) ? null : s; + } + }); + + operation.setJvmArguments(ArrayUtil.toStringArray(filteredArgs)); } listener.onStart(id); @@ -259,7 +267,7 @@ public class GradleExecutionHelper { } } - private static List mergeJvmArgs(List jvmArgs1, List jvmArgs2) { + private static List mergeJvmArgs(Iterable jvmArgs1, Iterable jvmArgs2) { JvmOptions jvmOptions = new JvmOptions(null); jvmOptions.setAllJvmArgs(ContainerUtil.concat(jvmArgs1, jvmArgs2)); return jvmOptions.getAllJvmArgs(); diff --git a/plugins/gradle/src/org/jetbrains/plugins/gradle/service/project/ProjectImportAction.java b/plugins/gradle/src/org/jetbrains/plugins/gradle/service/project/ProjectImportAction.java index ac26037dfcb6..4ddf55dc847b 100644 --- a/plugins/gradle/src/org/jetbrains/plugins/gradle/service/project/ProjectImportAction.java +++ b/plugins/gradle/src/org/jetbrains/plugins/gradle/service/project/ProjectImportAction.java @@ -25,10 +25,7 @@ import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.Serializable; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; +import java.util.*; /** * @author Vladislav.Soroka @@ -104,14 +101,35 @@ public class ProjectImportAction implements BuildAction findModulesWithModel(@NotNull Class modelClazz) { + List modules = new ArrayList(); + for (Map.Entry set : projectsByPath.entrySet()) { + if (modelClazz.isInstance(set.getValue())) { + modules.add(extractModulePath(modelClazz, set.getKey())); + } + } + return modules; + } + public void addExtraProject(@NotNull Object project, @NotNull Class modelClazz, @NotNull IdeaModule module) { projectsByPath.put(extractMapKey(modelClazz, module), project); } - @NotNull private static String extractMapKey(Class modelClazz, @NotNull IdeaModule module) { - return modelClazz.getName() + "@" + module.getGradleProject().getPath(); + return modelClazz.getName() + '@' + module.getGradleProject().getPath(); + } + + @NotNull + private static String extractModulePath(Class modelClazz, String key) { + return key.replaceFirst(modelClazz.getName() + '@', ""); } @Override diff --git a/plugins/gradle/src/org/jetbrains/plugins/gradle/service/project/ProjectResolverContext.java b/plugins/gradle/src/org/jetbrains/plugins/gradle/service/project/ProjectResolverContext.java index f874946cd5c7..0f9bc3987e09 100644 --- a/plugins/gradle/src/org/jetbrains/plugins/gradle/service/project/ProjectResolverContext.java +++ b/plugins/gradle/src/org/jetbrains/plugins/gradle/service/project/ProjectResolverContext.java @@ -23,6 +23,8 @@ import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.plugins.gradle.settings.GradleExecutionSettings; +import java.util.Collection; + /** * @author Vladislav.Soroka * @since 10/15/13 @@ -93,4 +95,9 @@ public class ProjectResolverContext { public T getExtraProject(@NotNull IdeaModule module, Class modelClazz) { return myModels.getExtraProject(module, modelClazz); } + + @NotNull + public Collection findModulesWithModel(@NotNull Class modelClazz) { + return myModels.findModulesWithModel(modelClazz); + } } diff --git a/plugins/gradle/src/org/jetbrains/plugins/gradle/service/resolve/GradleResolverUtil.java b/plugins/gradle/src/org/jetbrains/plugins/gradle/service/resolve/GradleResolverUtil.java index a1376f32ea78..535565cfec89 100644 --- a/plugins/gradle/src/org/jetbrains/plugins/gradle/service/resolve/GradleResolverUtil.java +++ b/plugins/gradle/src/org/jetbrains/plugins/gradle/service/resolve/GradleResolverUtil.java @@ -15,7 +15,8 @@ */ package org.jetbrains.plugins.gradle.service.resolve; -import com.intellij.openapi.util.Key; +import com.intellij.openapi.util.Computable; +import com.intellij.openapi.util.RecursionManager; import com.intellij.psi.*; import com.intellij.psi.scope.PsiScopeProcessor; import com.intellij.psi.util.PsiTreeUtil; @@ -43,7 +44,6 @@ import java.util.Arrays; * @since 8/30/13 */ public class GradleResolverUtil { - private static final Key TYPE_RESOLVE_IN_PROGRESS_KEY = Key.create("TYPE_RESOLVE_IN_PROGRESS_KEY"); public static int getGrMethodArumentsCount(@NotNull GrArgumentList args) { int argsCount = 0; @@ -235,17 +235,13 @@ public class GradleResolverUtil { } @Nullable - public static PsiType getTypeOf(@Nullable GrExpression expression) { - PsiType psiType = null; - if (expression != null) { - Integer count = expression.getUserData(TYPE_RESOLVE_IN_PROGRESS_KEY); - if (count == null) count = 0; - if (count < 15) { - expression.putUserData(TYPE_RESOLVE_IN_PROGRESS_KEY, ++count); - psiType = expression.getNominalType(); - expression.putUserData(TYPE_RESOLVE_IN_PROGRESS_KEY, null); + public static PsiType getTypeOf(@Nullable final GrExpression expression) { + if (expression == null) return null; + return RecursionManager.doPreventingRecursion(expression, true, new Computable() { + @Override + public PsiType compute() { + return expression.getNominalType(); } - } - return psiType; + }); } } diff --git a/plugins/groovy/jps-plugin/src/org/jetbrains/jps/incremental/groovy/GroovyBuilder.java b/plugins/groovy/jps-plugin/src/org/jetbrains/jps/incremental/groovy/GroovyBuilder.java index 8030a303bfba..e8d800efb245 100644 --- a/plugins/groovy/jps-plugin/src/org/jetbrains/jps/incremental/groovy/GroovyBuilder.java +++ b/plugins/groovy/jps-plugin/src/org/jetbrains/jps/incremental/groovy/GroovyBuilder.java @@ -56,7 +56,6 @@ import org.jetbrains.jps.service.SharedThreadPool; import java.io.File; import java.io.IOException; import java.util.*; -import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.Future; /** @@ -237,7 +236,7 @@ public class GroovyBuilder extends ModuleLevelBuilder { private static void rememberStubSources(CompileContext context, Map> compiled) { Map stubToSrc = STUB_TO_SRC.get(context); if (stubToSrc == null) { - STUB_TO_SRC.set(context, stubToSrc = new ConcurrentHashMap()); + STUB_TO_SRC.set(context, stubToSrc = new HashMap()); } for (Collection items : compiled.values()) { for (GroovycOSProcessHandler.OutputItem item : items) { diff --git a/plugins/groovy/src/org/intellij/plugins/intelliLang/inject/groovy/GrConcatenationAwareInjector.java b/plugins/groovy/src/org/intellij/plugins/intelliLang/inject/groovy/GrConcatenationAwareInjector.java index 5f3a421a4a5e..45ff3fe0a3f1 100644 --- a/plugins/groovy/src/org/intellij/plugins/intelliLang/inject/groovy/GrConcatenationAwareInjector.java +++ b/plugins/groovy/src/org/intellij/plugins/intelliLang/inject/groovy/GrConcatenationAwareInjector.java @@ -48,6 +48,7 @@ import org.jetbrains.plugins.groovy.lang.psi.GroovyFileBase; import org.jetbrains.plugins.groovy.lang.psi.api.GroovyResolveResult; import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.annotation.GrAnnotationNameValuePair; import org.jetbrains.plugins.groovy.lang.psi.api.statements.arguments.GrArgumentList; +import org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrCodeBlock; import org.jetbrains.plugins.groovy.lang.psi.api.statements.branch.GrReturnStatement; import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.*; import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.literals.GrStringInjection; @@ -124,7 +125,7 @@ public class GrConcatenationAwareInjector implements ConcatenationAwareInjector void processInjections() { final PsiElement firstOperand = myOperands[0]; final PsiElement topBlock = ControlFlowUtils.findControlFlowOwner(firstOperand); - final LocalSearchScope searchScope = new LocalSearchScope(new PsiElement[]{topBlock instanceof PsiCodeBlock + final LocalSearchScope searchScope = new LocalSearchScope(new PsiElement[]{topBlock instanceof GrCodeBlock ? topBlock : firstOperand.getContainingFile()}, "", true); final THashSet visitedVars = new THashSet(); final LinkedList places = new LinkedList(); diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/dgm/DGMMemberContributor.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/dgm/DGMMemberContributor.java index a210716b7593..224c5b43878c 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/dgm/DGMMemberContributor.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/dgm/DGMMemberContributor.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. @@ -17,10 +17,14 @@ package org.jetbrains.plugins.groovy.dgm; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Pair; -import com.intellij.psi.*; +import com.intellij.psi.PsiClass; +import com.intellij.psi.PsiElement; +import com.intellij.psi.PsiType; +import com.intellij.psi.ResolveState; import com.intellij.psi.scope.PsiScopeProcessor; import com.intellij.psi.search.GlobalSearchScope; import org.jetbrains.annotations.NotNull; +import org.jetbrains.plugins.groovy.lang.psi.impl.GroovyPsiManager; import org.jetbrains.plugins.groovy.lang.resolve.NonCodeMembersContributor; import java.util.List; @@ -37,15 +41,15 @@ public class DGMMemberContributor extends NonCodeMembersContributor { ResolveState state) { Project project = place.getProject(); GlobalSearchScope resolveScope = place.getResolveScope(); - JavaPsiFacade facade = JavaPsiFacade.getInstance(project); + GroovyPsiManager groovyPsiManager = GroovyPsiManager.getInstance(project); Pair, List> extensions = GroovyExtensionProvider.getInstance(project).collectExtensions(resolveScope); List instanceCategories = extensions.getFirst(); List staticCategories = extensions.getSecond(); - if (!processCategories(qualifierType, processor, state, project, resolveScope, facade, instanceCategories, false)) return; - if (!processCategories(qualifierType, processor, state, project, resolveScope, facade, staticCategories, true)) return; + if (!processCategories(qualifierType, processor, state, project, resolveScope, groovyPsiManager, instanceCategories, false)) return; + if (!processCategories(qualifierType, processor, state, project, resolveScope, groovyPsiManager, staticCategories, true)) return; } private static boolean processCategories(PsiType qualifierType, @@ -53,11 +57,10 @@ public class DGMMemberContributor extends NonCodeMembersContributor { ResolveState state, Project project, GlobalSearchScope resolveScope, - JavaPsiFacade facade, - List instanceCategories, + GroovyPsiManager groovyPsiManager, List instanceCategories, boolean isStatic) { for (String category : instanceCategories) { - PsiClass clazz = facade.findClass(category, resolveScope); + PsiClass clazz = groovyPsiManager.findClassWithCache(category, resolveScope); if (clazz != null) { if (!GdkMethodHolder.getHolderForClass(clazz, isStatic, resolveScope).processMethods(processor, state, qualifierType, project)) { return false; diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/expressions/path/GrIndexPropertyImpl.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/expressions/path/GrIndexPropertyImpl.java index 0de1c35c811b..a50f7ae7149b 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/expressions/path/GrIndexPropertyImpl.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/expressions/path/GrIndexPropertyImpl.java @@ -420,7 +420,7 @@ public class GrIndexPropertyImpl extends GrExpressionImpl implements GrIndexProp @NotNull @Override public ResolveResult[] multiResolve(boolean incompleteCode) { - return resolveImpl(incompleteCode, null, null); + return GrIndexPropertyImpl.this.multiResolve(incompleteCode); } } } \ No newline at end of file diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/resolve/CollectClassMembersUtil.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/resolve/CollectClassMembersUtil.java index 5d7e5bc3882d..8e1382e7f399 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/resolve/CollectClassMembersUtil.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/resolve/CollectClassMembersUtil.java @@ -85,7 +85,7 @@ public class CollectClassMembersUtil { @NotNull private static ClassMembers getCachedMembers(@NotNull PsiClass aClass, boolean includeSynthetic) { - LOG.assertTrue(aClass.isValid()); + PsiUtilCore.ensureValid(aClass); Key> key = includeSynthetic ? CACHED_MEMBERS_INCLUDING_SYNTHETIC : CACHED_MEMBERS; CachedValue cachedValue = aClass.getUserData(key); if (isCyclicDependence(aClass)) { @@ -150,7 +150,7 @@ public class CollectClassMembersUtil { @NotNull Set visitedClasses, @NotNull PsiSubstitutor substitutor, boolean includeSynthetic) { - LOG.assertTrue(aClass.isValid()); + PsiUtilCore.ensureValid(aClass); if (!visitedClasses.add(aClass)) return; diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/resolve/processors/SubstitutorComputer.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/resolve/processors/SubstitutorComputer.java index d4c42aa0ca82..fcefca01fcb3 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/resolve/processors/SubstitutorComputer.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/resolve/processors/SubstitutorComputer.java @@ -83,7 +83,6 @@ public class SubstitutorComputer { } } - @Nullable protected PsiType inferContextType() { final PsiElement parent = myPlaceToInferContext.getParent(); @@ -188,7 +187,7 @@ public class SubstitutorComputer { } } final PsiResolveHelper helper = JavaPsiFacade.getInstance(method.getProject()).getResolveHelper(); - PsiSubstitutor substitutor = helper.inferTypeArguments(typeParameters, parameterTypes, argumentTypes, LanguageLevel.HIGHEST); + PsiSubstitutor substitutor = helper.inferTypeArguments(typeParameters, parameterTypes, argumentTypes, LanguageLevel.JDK_1_7); for (PsiTypeParameter typeParameter : typeParameters) { if (!substitutor.getSubstitutionMap().containsKey(typeParameter)) { substitutor = inferFromContext(typeParameter, PsiUtil.getSmartReturnType(method), substitutor, helper); @@ -215,7 +214,7 @@ public class SubstitutorComputer { PsiResolveHelper helper) { if (myPlace == null) return substitutor; - final PsiType inferred = helper.getSubstitutionForTypeParameter(typeParameter, lType, inferContextType(), false, LanguageLevel.HIGHEST); + final PsiType inferred = helper.getSubstitutionForTypeParameter(typeParameter, lType, inferContextType(), false, LanguageLevel.JDK_1_7); if (inferred != PsiType.NULL) { return substitutor.put(typeParameter, inferred); } diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/mvc/MvcModuleStructureSynchronizer.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/mvc/MvcModuleStructureSynchronizer.java index a29e9d36f34d..b2d0257a31ff 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/mvc/MvcModuleStructureSynchronizer.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/mvc/MvcModuleStructureSynchronizer.java @@ -349,7 +349,9 @@ public class MvcModuleStructureSynchronizer extends AbstractProjectComponent { SyncLibrariesInPluginsModule { @Override void doAction(Module module, MvcFramework framework) { - framework.syncSdkAndLibrariesInPluginsModule(module); + if (MvcModuleStructureUtil.isEnabledStructureUpdate()) { + framework.syncSdkAndLibrariesInPluginsModule(module); + } } }, diff --git a/plugins/hg4idea/src/org/zmlx/hg4idea/log/HgLogProvider.java b/plugins/hg4idea/src/org/zmlx/hg4idea/log/HgLogProvider.java index 7f38310a6326..3e1df88c17d9 100644 --- a/plugins/hg4idea/src/org/zmlx/hg4idea/log/HgLogProvider.java +++ b/plugins/hg4idea/src/org/zmlx/hg4idea/log/HgLogProvider.java @@ -231,8 +231,11 @@ public class HgLogProvider implements VcsLogProvider { if (userName == null) { userName = System.getenv("HGUSER"); } + if (userName == null) { + return null; + } Pair userArgs = HgUtil.parseUserNameAndEmail(userName); - return userName == null ? null : myVcsObjectsFactory.createUser(userArgs.getFirst(), userArgs.getSecond()); + return myVcsObjectsFactory.createUser(userArgs.getFirst(), userArgs.getSecond()); } private static String prepareParameter(String paramName, String value) { diff --git a/plugins/junit/src/com/intellij/execution/ConfigurationUtil.java b/plugins/junit/src/com/intellij/execution/ConfigurationUtil.java index c200d8f64459..89590887cbbb 100644 --- a/plugins/junit/src/com/intellij/execution/ConfigurationUtil.java +++ b/plugins/junit/src/com/intellij/execution/ConfigurationUtil.java @@ -24,6 +24,7 @@ import com.intellij.openapi.project.IndexNotReadyException; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Computable; import com.intellij.openapi.util.Ref; +import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.*; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.search.PsiElementProcessor; @@ -96,6 +97,7 @@ public class ConfigurationUtil { } ); if (testAnnotation != null) { + //allScope is used to find all abstract test cases which probably have inheritors in the current 'scope' AnnotatedMembersSearch.search(testAnnotation, GlobalSearchScope.allScope(manager.getProject())).forEach(new Processor() { public boolean process(final PsiMember annotated) { final PsiClass containingClass = annotated instanceof PsiClass ? (PsiClass)annotated : annotated.getContainingClass(); @@ -104,7 +106,8 @@ public class ConfigurationUtil { new Computable() { @Override public Boolean compute() { - return scope.contains(PsiUtilCore.getVirtualFile(containingClass)) && testClassFilter.isAccepted(containingClass); + final VirtualFile file = PsiUtilCore.getVirtualFile(containingClass); + return file != null && scope.contains(file) && testClassFilter.isAccepted(containingClass); } })) { found.add(containingClass); diff --git a/plugins/junit/src/com/intellij/execution/junit/AllInDirectoryConfigurationProducer.java b/plugins/junit/src/com/intellij/execution/junit/AllInDirectoryConfigurationProducer.java index 298f9d2f9bd4..35ff7804c85e 100644 --- a/plugins/junit/src/com/intellij/execution/junit/AllInDirectoryConfigurationProducer.java +++ b/plugins/junit/src/com/intellij/execution/junit/AllInDirectoryConfigurationProducer.java @@ -43,6 +43,7 @@ public class AllInDirectoryConfigurationProducer extends JUnitConfigurationProdu final VirtualFile virtualFile = ((PsiDirectory)element).getVirtualFile(); final Module module = ModuleUtilCore.findModuleForFile(virtualFile, project); if (module == null) return false; + if (!ModuleRootManager.getInstance(module).getFileIndex().isInTestSourceContent(virtualFile)) return false; int testRootCount = ModuleRootManager.getInstance(module).getSourceRoots(JavaSourceRootType.TEST_SOURCE).size(); if (testRootCount < 2) return false; if (!LocationUtil.isJarAttached(context.getLocation(), aPackage, JUnitUtil.TESTCASE_CLASS)) return false; diff --git a/plugins/junit/src/com/intellij/execution/junit/JUnitConfigurationProducer.java b/plugins/junit/src/com/intellij/execution/junit/JUnitConfigurationProducer.java index 4220c5a0e39c..d70a97f7beb9 100644 --- a/plugins/junit/src/com/intellij/execution/junit/JUnitConfigurationProducer.java +++ b/plugins/junit/src/com/intellij/execution/junit/JUnitConfigurationProducer.java @@ -56,6 +56,7 @@ public abstract class JUnitConfigurationProducer extends JavaRunConfigurationPro } else { testPackage = null; } + PsiDirectory testDir = element instanceof PsiDirectory ? (PsiDirectory)element : null; RunnerAndConfigurationSettings template = RunManager.getInstance(location.getProject()) .getConfigurationTemplate(getConfigurationFactory()); final Module predefinedModule = @@ -66,7 +67,7 @@ public abstract class JUnitConfigurationProducer extends JavaRunConfigurationPro if (vmParameters != null && !Comparing.strEqual(vmParameters, unitConfiguration.getVMParameters())) return false; final TestObject testobject = unitConfiguration.getTestObject(); if (testobject != null) { - if (testobject.isConfiguredByElement(unitConfiguration, testClass, testMethod, testPackage)) { + if (testobject.isConfiguredByElement(unitConfiguration, testClass, testMethod, testPackage, testDir)) { final Module configurationModule = unitConfiguration.getConfigurationModule().getModule(); if (Comparing.equal(location.getModule(), configurationModule)) return true; if (Comparing.equal(predefinedModule, configurationModule)) { diff --git a/plugins/junit/src/com/intellij/execution/junit/TestClass.java b/plugins/junit/src/com/intellij/execution/junit/TestClass.java index db91769f840e..d1b687d05af9 100644 --- a/plugins/junit/src/com/intellij/execution/junit/TestClass.java +++ b/plugins/junit/src/com/intellij/execution/junit/TestClass.java @@ -26,10 +26,7 @@ import com.intellij.execution.configurations.RuntimeConfigurationWarning; import com.intellij.execution.runners.ExecutionEnvironment; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Comparing; -import com.intellij.psi.PsiClass; -import com.intellij.psi.PsiElement; -import com.intellij.psi.PsiMethod; -import com.intellij.psi.PsiPackage; +import com.intellij.psi.*; import com.intellij.refactoring.listeners.RefactoringElementListener; class TestClass extends TestObject { @@ -62,7 +59,8 @@ class TestClass extends TestObject { public boolean isConfiguredByElement(final JUnitConfiguration configuration, PsiClass testClass, PsiMethod testMethod, - PsiPackage testPackage) { + PsiPackage testPackage, + PsiDirectory testDir) { if (testClass == null) { return false; diff --git a/plugins/junit/src/com/intellij/execution/junit/TestDirectory.java b/plugins/junit/src/com/intellij/execution/junit/TestDirectory.java index 77403dfe6618..b99c2f0c91ba 100644 --- a/plugins/junit/src/com/intellij/execution/junit/TestDirectory.java +++ b/plugins/junit/src/com/intellij/execution/junit/TestDirectory.java @@ -25,6 +25,7 @@ import com.intellij.execution.util.JavaParametersUtil; import com.intellij.execution.util.ProgramParametersUtil; import com.intellij.openapi.module.Module; import com.intellij.openapi.project.Project; +import com.intellij.openapi.util.Comparing; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.vfs.LocalFileSystem; import com.intellij.openapi.vfs.VirtualFile; @@ -120,14 +121,12 @@ class TestDirectory extends TestPackage { public boolean isConfiguredByElement(JUnitConfiguration configuration, PsiClass testClass, PsiMethod testMethod, - PsiPackage testPackage) { - if (JUnitConfiguration.TEST_DIRECTORY.equals(configuration.getPersistentData().TEST_OBJECT) && testPackage != null) { - final PsiDirectory[] directories = testPackage.getDirectories(configuration.getConfigurationModule().getSearchScope()); - final String dirName = configuration.getPersistentData().getDirName(); - if (dirName != null) { - for (PsiDirectory directory : directories) { - if (dirName.equals(directory.getVirtualFile().getPath())) return true; - } + PsiPackage testPackage, + PsiDirectory testDir) { + if (JUnitConfiguration.TEST_DIRECTORY.equals(configuration.getPersistentData().TEST_OBJECT) && testDir != null) { + if (Comparing.strEqual(FileUtil.toSystemIndependentName(configuration.getPersistentData().getDirName()), + testDir.getVirtualFile().getPath())) { + return true; } } return false; diff --git a/plugins/junit/src/com/intellij/execution/junit/TestMethod.java b/plugins/junit/src/com/intellij/execution/junit/TestMethod.java index 3d03c0294ddf..23d798314197 100644 --- a/plugins/junit/src/com/intellij/execution/junit/TestMethod.java +++ b/plugins/junit/src/com/intellij/execution/junit/TestMethod.java @@ -22,10 +22,7 @@ import com.intellij.execution.configurations.*; import com.intellij.execution.runners.ExecutionEnvironment; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Comparing; -import com.intellij.psi.PsiClass; -import com.intellij.psi.PsiElement; -import com.intellij.psi.PsiMethod; -import com.intellij.psi.PsiPackage; +import com.intellij.psi.*; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.refactoring.listeners.RefactoringElementAdapter; import com.intellij.refactoring.listeners.RefactoringElementListener; @@ -105,7 +102,8 @@ class TestMethod extends TestObject { public boolean isConfiguredByElement(final JUnitConfiguration configuration, PsiClass testClass, PsiMethod testMethod, - PsiPackage testPackage) { + PsiPackage testPackage, + PsiDirectory testDir) { if (testMethod == null) return false; if (testClass == null) return false; final JUnitConfiguration.Data data = configuration.getPersistentData(); diff --git a/plugins/junit/src/com/intellij/execution/junit/TestObject.java b/plugins/junit/src/com/intellij/execution/junit/TestObject.java index ac1c52395523..7b54e63f1c0d 100644 --- a/plugins/junit/src/com/intellij/execution/junit/TestObject.java +++ b/plugins/junit/src/com/intellij/execution/junit/TestObject.java @@ -62,10 +62,7 @@ import com.intellij.openapi.util.Key; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.registry.Registry; import com.intellij.openapi.vfs.CharsetToolkit; -import com.intellij.psi.PsiClass; -import com.intellij.psi.PsiElement; -import com.intellij.psi.PsiMethod; -import com.intellij.psi.PsiPackage; +import com.intellij.psi.*; import com.intellij.refactoring.listeners.RefactoringElementListener; import com.intellij.rt.execution.junit.IDEAJUnitListener; import com.intellij.rt.execution.junit.JUnitStarter; @@ -138,7 +135,8 @@ public abstract class TestObject implements JavaCommandLine { public abstract boolean isConfiguredByElement(JUnitConfiguration configuration, PsiClass testClass, PsiMethod testMethod, - PsiPackage testPackage); + PsiPackage testPackage, + PsiDirectory testDir); protected void configureModule(final JavaParameters parameters, final RunConfigurationModule configurationModule, final String mainClassName) throws CantRunException { @@ -162,7 +160,8 @@ public abstract class TestObject implements JavaCommandLine { public boolean isConfiguredByElement(final JUnitConfiguration configuration, PsiClass testClass, PsiMethod testMethod, - PsiPackage testPackage) { + PsiPackage testPackage, + PsiDirectory testDir) { return false; } diff --git a/plugins/junit/src/com/intellij/execution/junit/TestPackage.java b/plugins/junit/src/com/intellij/execution/junit/TestPackage.java index 7e6cf5c9c87b..1527e1880b73 100644 --- a/plugins/junit/src/com/intellij/execution/junit/TestPackage.java +++ b/plugins/junit/src/com/intellij/execution/junit/TestPackage.java @@ -246,7 +246,8 @@ public class TestPackage extends TestObject { public boolean isConfiguredByElement(final JUnitConfiguration configuration, PsiClass testClass, PsiMethod testMethod, - PsiPackage testPackage) { + PsiPackage testPackage, + PsiDirectory testDir) { return testPackage != null && Comparing.equal(testPackage.getQualifiedName(), configuration.getPersistentData().getPackageName()); } diff --git a/plugins/junit/src/com/intellij/execution/junit/TestsPattern.java b/plugins/junit/src/com/intellij/execution/junit/TestsPattern.java index b0cc87bd7946..c4954f09b1dc 100644 --- a/plugins/junit/src/com/intellij/execution/junit/TestsPattern.java +++ b/plugins/junit/src/com/intellij/execution/junit/TestsPattern.java @@ -34,10 +34,7 @@ import com.intellij.openapi.progress.Task; import com.intellij.openapi.progress.impl.BackgroundableProcessIndicator; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.text.StringUtil; -import com.intellij.psi.PsiClass; -import com.intellij.psi.PsiElement; -import com.intellij.psi.PsiMethod; -import com.intellij.psi.PsiPackage; +import com.intellij.psi.*; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.refactoring.listeners.RefactoringElementListener; import com.intellij.refactoring.listeners.RefactoringElementListenerComposite; @@ -194,7 +191,8 @@ public class TestsPattern extends TestPackage { public boolean isConfiguredByElement(JUnitConfiguration configuration, PsiClass testClass, PsiMethod testMethod, - PsiPackage testPackage) { + PsiPackage testPackage, + PsiDirectory testDir) { /*if (testMethod != null && Comparing.strEqual(testMethod.getName(), configuration.getPersistentData().METHOD_NAME)) { return true; }*/ diff --git a/plugins/maven/artifact-resolver-m2/src/org/jetbrains/idea/maven/artifactResolver/common/MavenModuleMap.java b/plugins/maven/artifact-resolver-m2/src/org/jetbrains/idea/maven/artifactResolver/common/MavenModuleMap.java index f9246328b8c1..bf3fff93b063 100644 --- a/plugins/maven/artifact-resolver-m2/src/org/jetbrains/idea/maven/artifactResolver/common/MavenModuleMap.java +++ b/plugins/maven/artifact-resolver-m2/src/org/jetbrains/idea/maven/artifactResolver/common/MavenModuleMap.java @@ -56,6 +56,10 @@ public class MavenModuleMap { public boolean resolveToModule(Artifact artifact) { String extension = artifact.getArtifactHandler().getExtension(); + if ("jar".equals(extension) && "test-jar".equals(artifact.getType())) { + extension = "test-jar"; + } + File file = findArtifact(artifact.getGroupId(), artifact.getArtifactId(), extension, artifact.getBaseVersion()); if(file == null) { diff --git a/plugins/maven/artifact-resolver-m3/src/org/jetbrains/idea/maven/artifactResolver/MyWorkspaceReader.java b/plugins/maven/artifact-resolver-m3/src/org/jetbrains/idea/maven/artifactResolver/MyWorkspaceReader.java index d67fcc9f0a12..612d24bb8b7d 100644 --- a/plugins/maven/artifact-resolver-m3/src/org/jetbrains/idea/maven/artifactResolver/MyWorkspaceReader.java +++ b/plugins/maven/artifact-resolver-m3/src/org/jetbrains/idea/maven/artifactResolver/MyWorkspaceReader.java @@ -52,7 +52,12 @@ public class MyWorkspaceReader implements WorkspaceReader { } public File findArtifact(Artifact artifact) { - return MavenModuleMap.getInstance().findArtifact(artifact.getGroupId(), artifact.getArtifactId(), artifact.getExtension(), + String type = artifact.getExtension(); + if ("jar".equals(type) && "tests".equals(artifact.getClassifier())) { + type = "test-jar"; + } + + return MavenModuleMap.getInstance().findArtifact(artifact.getGroupId(), artifact.getArtifactId(), type, artifact.getBaseVersion()); } diff --git a/plugins/maven/artifact-resolver-m31/lib/eclipse-aether/aether-api-0.9.0.M2.jar b/plugins/maven/artifact-resolver-m31/lib/eclipse-aether/aether-api-0.9.0.M2.jar new file mode 100644 index 000000000000..e5b122cec252 Binary files /dev/null and b/plugins/maven/artifact-resolver-m31/lib/eclipse-aether/aether-api-0.9.0.M2.jar differ diff --git a/plugins/maven/artifact-resolver-m31/maven-artifact-resolver-m31.iml b/plugins/maven/artifact-resolver-m31/maven-artifact-resolver-m31.iml new file mode 100644 index 000000000000..3d45f6bed168 --- /dev/null +++ b/plugins/maven/artifact-resolver-m31/maven-artifact-resolver-m31.iml @@ -0,0 +1,40 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/plugins/maven/artifact-resolver-m31/src/META-INF/plexus/components.xml b/plugins/maven/artifact-resolver-m31/src/META-INF/plexus/components.xml new file mode 100644 index 000000000000..d4d29b1060f7 --- /dev/null +++ b/plugins/maven/artifact-resolver-m31/src/META-INF/plexus/components.xml @@ -0,0 +1,12 @@ + + + + + org.eclipse.aether.repository.WorkspaceReader + ide + org.jetbrains.idea.maven.artifactResolver.IntelliJWorkspaceReaderM31 + + false + + + diff --git a/plugins/maven/artifact-resolver-m31/src/org/jetbrains/idea/maven/artifactResolver/IntelliJWorkspaceReaderM31.java b/plugins/maven/artifact-resolver-m31/src/org/jetbrains/idea/maven/artifactResolver/IntelliJWorkspaceReaderM31.java new file mode 100644 index 000000000000..3041e8350a20 --- /dev/null +++ b/plugins/maven/artifact-resolver-m31/src/org/jetbrains/idea/maven/artifactResolver/IntelliJWorkspaceReaderM31.java @@ -0,0 +1,67 @@ +/* + * 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.idea.maven.artifactResolver; + +import org.codehaus.plexus.component.annotations.Component; +import org.eclipse.aether.artifact.Artifact; +import org.eclipse.aether.repository.WorkspaceReader; +import org.eclipse.aether.repository.WorkspaceRepository; +import org.jetbrains.idea.maven.artifactResolver.common.MavenModuleMap; + +import java.io.File; +import java.util.Collections; +import java.util.List; + +/** + * @author Sergey Evdokimov + */ +@Component(role = WorkspaceReader.class, hint = "ide") +public class IntelliJWorkspaceReaderM31 implements WorkspaceReader { + + private final WorkspaceRepository myWorkspaceRepository; + + public IntelliJWorkspaceReaderM31() { + myWorkspaceRepository = new WorkspaceRepository("ide", getClass()); + } + + @Override + public int hashCode() { + return 311; + } + + @Override + public boolean equals(Object o) { + return o instanceof IntelliJWorkspaceReaderM31; + } + + public WorkspaceRepository getRepository() { + return myWorkspaceRepository; + } + + public File findArtifact(Artifact artifact) { + String type = artifact.getExtension(); + if ("jar".equals(type) && "tests".equals(artifact.getClassifier())) { + type = "test-jar"; + } + + return MavenModuleMap.getInstance().findArtifact(artifact.getGroupId(), artifact.getArtifactId(), type, + artifact.getBaseVersion()); + } + + public List findVersions(Artifact artifact) { + return Collections.emptyList(); + } +} diff --git a/plugins/gradle/src/org/jetbrains/plugins/gradle/model/impl/GradleDependency.java b/plugins/maven/artifact-resolver-m31/src/org/jetbrains/idea/maven/artifactResolver/MavenArtifactResolvedM31RtMarker.java similarity index 62% rename from plugins/gradle/src/org/jetbrains/plugins/gradle/model/impl/GradleDependency.java rename to plugins/maven/artifact-resolver-m31/src/org/jetbrains/idea/maven/artifactResolver/MavenArtifactResolvedM31RtMarker.java index fec7c977b988..ad15baf8aae2 100644 --- a/plugins/gradle/src/org/jetbrains/plugins/gradle/model/impl/GradleDependency.java +++ b/plugins/maven/artifact-resolver-m31/src/org/jetbrains/idea/maven/artifactResolver/MavenArtifactResolvedM31RtMarker.java @@ -13,22 +13,10 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.jetbrains.plugins.gradle.model.impl; - -import org.gradle.tooling.model.Dependency; - -import java.io.Serializable; +package org.jetbrains.idea.maven.artifactResolver; /** - * @author Vladislav.Soroka - * @since 11/8/13 + * @author Sergey Evdokimov */ -public interface GradleDependency extends Dependency, Serializable { - String getConfigurationName(); - - String getDependencyName(); - - String getDependencyGroup(); - - String getDependencyVersion(); +public class MavenArtifactResolvedM31RtMarker { } diff --git a/plugins/maven/maven.iml b/plugins/maven/maven.iml index 8c58bb720940..c15aa891282b 100644 --- a/plugins/maven/maven.iml +++ b/plugins/maven/maven.iml @@ -59,6 +59,7 @@ + diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/execution/MavenExternalParameters.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/execution/MavenExternalParameters.java index a8f4606d176c..181537bd3e56 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/execution/MavenExternalParameters.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/execution/MavenExternalParameters.java @@ -47,6 +47,7 @@ import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.idea.maven.artifactResolver.MavenArtifactResolvedM2RtMarker; +import org.jetbrains.idea.maven.artifactResolver.MavenArtifactResolvedM31RtMarker; import org.jetbrains.idea.maven.artifactResolver.MavenArtifactResolvedM3RtMarker; import org.jetbrains.idea.maven.artifactResolver.common.MavenModuleMap; import org.jetbrains.idea.maven.project.MavenGeneralSettings; @@ -126,7 +127,7 @@ public class MavenExternalParameters { if (project != null && parameters.isResolveToWorkspace()) { try { - String resolverJar = getArtifactResolverJar(MavenUtil.isMaven3(mavenHome)); + String resolverJar = getArtifactResolverJar(MavenUtil.getMavenVersion(mavenHome)); confFile = patchConfFile(confFile, resolverJar); File modulesPathsFile = dumpModulesPaths(project); @@ -196,11 +197,24 @@ public class MavenExternalParameters { finally { sc.close(); } - } - private static String getArtifactResolverJar(boolean isMaven3) throws IOException { - Class marker = isMaven3 ? MavenArtifactResolvedM3RtMarker.class : MavenArtifactResolvedM2RtMarker.class; + private static String getArtifactResolverJar(@Nullable String mavenVersion) throws IOException { + boolean isMaven3; + Class marker; + + if (mavenVersion != null && mavenVersion.compareTo("3.1.0") >= 0) { + isMaven3 = true; + marker = MavenArtifactResolvedM31RtMarker.class; + } + else if (mavenVersion != null && mavenVersion.compareTo("3.0.0") >= 0) { + isMaven3 = true; + marker = MavenArtifactResolvedM3RtMarker.class; + } + else { + isMaven3 = false; + marker = MavenArtifactResolvedM2RtMarker.class; + } File classDirOrJar = new File(PathUtil.getJarPathForClass(marker)); @@ -246,6 +260,12 @@ public class MavenExternalParameters { + ':' + mavenProject.getMavenId().getVersion(), mavenProject.getFile().getPath()); + res.setProperty(mavenProject.getMavenId().getGroupId() + + ':' + mavenProject.getMavenId().getArtifactId() + + ":test-jar" + + ':' + mavenProject.getMavenId().getVersion(), + mavenProject.getTestOutputDirectory()); + res.setProperty(mavenProject.getMavenId().getGroupId() + ':' + mavenProject.getMavenId().getArtifactId() + ':' + mavenProject.getPackaging() diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/server/MavenServerManager.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/server/MavenServerManager.java index b4c440bfd78c..cf8ccd1c6bcd 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/server/MavenServerManager.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/server/MavenServerManager.java @@ -258,6 +258,11 @@ public class MavenServerManager extends RemoteObjectWrapper impleme params.getVMParametersList().addParametersString("-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=" + mavenEmbedderDebugPort); } + String mavenEmbedderParameters = System.getProperty("idea.maven.embedder.parameters"); + if (mavenEmbedderParameters != null) { + params.getProgramParametersList().addParametersString(mavenEmbedderParameters); + } + return params; } diff --git a/plugins/terminal/src/org/jetbrains/plugins/terminal/LocalTerminalDirectRunner.java b/plugins/terminal/src/org/jetbrains/plugins/terminal/LocalTerminalDirectRunner.java index 064dad91d25e..3d0ec61e5c0a 100644 --- a/plugins/terminal/src/org/jetbrains/plugins/terminal/LocalTerminalDirectRunner.java +++ b/plugins/terminal/src/org/jetbrains/plugins/terminal/LocalTerminalDirectRunner.java @@ -33,32 +33,10 @@ public class LocalTerminalDirectRunner extends AbstractTerminalRunner envs = new HashMap(System.getenv()); envs.put("TERM", "xterm"); try { - return PtyProcess.exec(myCommand, envs, currentProjectFolder()); + return PtyProcess.exec(getCommand(), envs, currentProjectFolder()); } catch (IOException e) { throw new ExecutionException(e); @@ -116,7 +94,33 @@ public class LocalTerminalDirectRunner extends AbstractTerminalRunner - + @@ -33,17 +33,9 @@ - + - - - - - - - - @@ -55,12 +47,18 @@ - + + + + + + + diff --git a/plugins/terminal/src/org/jetbrains/plugins/terminal/TerminalSettingsPanel.java b/plugins/terminal/src/org/jetbrains/plugins/terminal/TerminalSettingsPanel.java index 0400bb311feb..ff0a771a1d60 100644 --- a/plugins/terminal/src/org/jetbrains/plugins/terminal/TerminalSettingsPanel.java +++ b/plugins/terminal/src/org/jetbrains/plugins/terminal/TerminalSettingsPanel.java @@ -15,9 +15,12 @@ */ package org.jetbrains.plugins.terminal; -import com.intellij.openapi.Disposable; +import com.intellij.openapi.fileChooser.FileChooserDescriptor; +import com.intellij.openapi.ui.TextComponentAccessor; +import com.intellij.openapi.ui.TextFieldWithBrowseButton; import com.intellij.openapi.util.Comparing; import com.intellij.ui.components.JBCheckBox; +import org.jetbrains.annotations.NotNull; import javax.swing.*; @@ -26,7 +29,7 @@ import javax.swing.*; */ public class TerminalSettingsPanel { private JPanel myWholePanel; - private JTextField myShellTextField; + private TextFieldWithBrowseButton myShellPathField; private JBCheckBox mySoundBellCheckBox; private JBCheckBox myCloseSessionCheckBox; private JBCheckBox myMouseReportCheckBox; @@ -35,14 +38,25 @@ public class TerminalSettingsPanel { private JBCheckBox myCopyOnSelectionCheckBox; private TerminalOptionsProvider myOptionsProvider; - public JComponent createPanel(TerminalOptionsProvider provider) { + public JComponent createPanel(@NotNull TerminalOptionsProvider provider) { myOptionsProvider = provider; + FileChooserDescriptor fileChooserDescriptor = new FileChooserDescriptor(true, false, false, false, false, false); + + myShellPathField.addBrowseFolderListener( + "", + "Shell Executable Path", + null, + fileChooserDescriptor, + TextComponentAccessor.TEXT_FIELD_WHOLE_TEXT, + false + ); + return myWholePanel; } public boolean isModified() { - return !Comparing.equal(myShellTextField.getText(), myOptionsProvider.getShellPath()) + return !Comparing.equal(myShellPathField.getText(), myOptionsProvider.getShellPath()) || !Comparing.equal(myTabNameTextField.getText(), myOptionsProvider.getTabName()) || (myCloseSessionCheckBox.isSelected() != myOptionsProvider.closeSessionOnLogout()) || (myMouseReportCheckBox.isSelected() != myOptionsProvider.enableMouseReporting()) @@ -53,7 +67,7 @@ public class TerminalSettingsPanel { } public void apply() { - myOptionsProvider.setShellPath(myShellTextField.getText()); + myOptionsProvider.setShellPath(myShellPathField.getText()); myOptionsProvider.setTabName(myTabNameTextField.getText()); myOptionsProvider.setCloseSessionOnLogout(myCloseSessionCheckBox.isSelected()); myOptionsProvider.setReportMouse(myMouseReportCheckBox.isSelected()); @@ -63,7 +77,7 @@ public class TerminalSettingsPanel { } public void reset() { - myShellTextField.setText(myOptionsProvider.getShellPath()); + myShellPathField.setText(myOptionsProvider.getShellPath()); myTabNameTextField.setText(myOptionsProvider.getTabName()); myCloseSessionCheckBox.setSelected(myOptionsProvider.closeSessionOnLogout()); myMouseReportCheckBox.setSelected(myOptionsProvider.enableMouseReporting()); diff --git a/plugins/testng/src/com/theoryinpractice/testng/inspection/DependsOnGroupsInspection.java b/plugins/testng/src/com/theoryinpractice/testng/inspection/DependsOnGroupsInspection.java index 35aa88ad537c..3f8699bf2959 100644 --- a/plugins/testng/src/com/theoryinpractice/testng/inspection/DependsOnGroupsInspection.java +++ b/plugins/testng/src/com/theoryinpractice/testng/inspection/DependsOnGroupsInspection.java @@ -114,7 +114,7 @@ public class DependsOnGroupsInspection extends BaseJavaLocalInspectionTool { if (dep != null) { final PsiAnnotationMemberValue value = dep.getValue(); if (value != null) { - LOGGER.info("Found " + dep.getName() + " with: " + value.getText()); + LOGGER.debug("Found " + dep.getName() + " with: " + value.getText()); String text = value.getText(); if (value instanceof PsiReferenceExpression) { final PsiElement resolve = ((PsiReferenceExpression)value).resolve(); @@ -131,7 +131,7 @@ public class DependsOnGroupsInspection extends BaseJavaLocalInspectionTool { while (matcher.find()) { String methodName = matcher.group(1); if (!groups.contains(methodName)) { - LOGGER.info("group doesn't exist:" + methodName); + LOGGER.debug("group doesn't exist:" + methodName); ProblemDescriptor descriptor = manager.createProblemDescriptor(annotation, "Group '" + methodName + "' is undefined.", new GroupNameQuickFix(methodName), ProblemHighlightType.GENERIC_ERROR_OR_WARNING, isOnTheFly); diff --git a/plugins/ui-designer-core/src/com/intellij/designer/actions/CommonEditActionsProvider.java b/plugins/ui-designer-core/src/com/intellij/designer/actions/CommonEditActionsProvider.java index 04021bd5195c..304a26c6d2bc 100644 --- a/plugins/ui-designer-core/src/com/intellij/designer/actions/CommonEditActionsProvider.java +++ b/plugins/ui-designer-core/src/com/intellij/designer/actions/CommonEditActionsProvider.java @@ -50,6 +50,8 @@ import java.util.Map; public class CommonEditActionsProvider implements DeleteProvider, CopyProvider, PasteProvider, CutProvider { private static final DataFlavor DATA_FLAVOR = FileCopyPasteUtil.createJvmDataFlavor(SerializedComponentData.class); + public static boolean isDeleting; + private final DesignerEditorPanel myDesigner; public CommonEditActionsProvider(DesignerEditorPanel designer) { @@ -141,12 +143,19 @@ public class CommonEditActionsProvider implements DeleteProvider, CopyProvider, } public static void updateSelectionBeforeDelete(EditableArea area, RadComponent component, List excludes) { - RadComponent newSelection = getNewSelection(component, excludes); - if (newSelection == null) { - area.deselectAll(); + try { + isDeleting = true; + + RadComponent newSelection = getNewSelection(component, excludes); + if (newSelection == null) { + area.deselectAll(); + } + else { + area.select(newSelection); + } } - else { - area.select(newSelection); + finally { + isDeleting = false; } } diff --git a/plugins/ui-designer-core/src/com/intellij/designer/designSurface/DesignerEditorPanel.java b/plugins/ui-designer-core/src/com/intellij/designer/designSurface/DesignerEditorPanel.java index dc12a18ce9ae..1a088da27071 100644 --- a/plugins/ui-designer-core/src/com/intellij/designer/designSurface/DesignerEditorPanel.java +++ b/plugins/ui-designer-core/src/com/intellij/designer/designSurface/DesignerEditorPanel.java @@ -17,6 +17,7 @@ package com.intellij.designer.designSurface; import com.intellij.designer.*; import com.intellij.designer.actions.AbstractComboBoxAction; +import com.intellij.designer.actions.CommonEditActionsProvider; import com.intellij.designer.actions.DesignerActionPanel; import com.intellij.designer.componentTree.TreeComponentDecorator; import com.intellij.designer.componentTree.TreeEditableArea; @@ -33,6 +34,7 @@ import com.intellij.diagnostic.LogMessageEx; import com.intellij.icons.AllIcons; import com.intellij.openapi.actionSystem.*; import com.intellij.openapi.command.CommandProcessor; +import com.intellij.openapi.diagnostic.Attachment; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleUtilCore; @@ -344,10 +346,14 @@ public abstract class DesignerEditorPanel extends JPanel implements DataProvider if (info.myShowLog) { LOG.error(LogMessageEx.createEvent(info.myDisplayMessage, info.myMessage + "\n" + ExceptionUtil.getThrowableText(info.myThrowable), - AttachmentFactory.createAttachment(myFile))); + getErrorAttachments(info))); } } + protected Attachment[] getErrorAttachments(ErrorInfo info) { + return new Attachment[]{AttachmentFactory.createAttachment(myFile)}; + } + protected abstract void configureError(final @NotNull ErrorInfo info); protected void showErrorPage(final ErrorInfo info) { @@ -574,7 +580,9 @@ public abstract class DesignerEditorPanel extends JPanel implements DataProvider } private void storeSourceSelectionState() { - mySourceSelectionState.put(getEditorText(), getSelectionState()); + if (!CommonEditActionsProvider.isDeleting) { + mySourceSelectionState.put(getEditorText(), getSelectionState()); + } } private int[][] getSelectionState() { diff --git a/plugins/ui-designer/src/com/intellij/uiDesigner/snapShooter/SnapShooterConfigurationExtension.java b/plugins/ui-designer/src/com/intellij/uiDesigner/snapShooter/SnapShooterConfigurationExtension.java index 624e321fb2b2..a4b0f848dda7 100644 --- a/plugins/ui-designer/src/com/intellij/uiDesigner/snapShooter/SnapShooterConfigurationExtension.java +++ b/plugins/ui-designer/src/com/intellij/uiDesigner/snapShooter/SnapShooterConfigurationExtension.java @@ -45,7 +45,6 @@ import com.jgoodies.forms.layout.FormLayout; import org.jdom.Element; import org.jetbrains.annotations.NotNull; -import java.io.IOException; import java.util.Set; import java.util.TreeSet; @@ -65,12 +64,7 @@ public class SnapShooterConfigurationExtension extends RunConfigurationExtension appConfiguration.putUserData(SnapShooterConfigurationSettings.SNAP_SHOOTER_KEY, settings); } if (appConfiguration.ENABLE_SWING_INSPECTOR) { - try { - settings.setLastPort(NetUtils.findAvailableSocketPort()); - } - catch(IOException ex) { - settings.setLastPort(-1); - } + settings.setLastPort(NetUtils.tryToFindAvailableSocketPort()); } if (appConfiguration.ENABLE_SWING_INSPECTOR && settings.getLastPort() != -1) { diff --git a/plugins/xpath/xpath-lang/src/org/intellij/lang/xpath/xslt/run/XsltCommandLineState.java b/plugins/xpath/xpath-lang/src/org/intellij/lang/xpath/xslt/run/XsltCommandLineState.java index c1d45c228495..e2886b345356 100644 --- a/plugins/xpath/xpath-lang/src/org/intellij/lang/xpath/xslt/run/XsltCommandLineState.java +++ b/plugins/xpath/xpath-lang/src/org/intellij/lang/xpath/xslt/run/XsltCommandLineState.java @@ -27,6 +27,7 @@ import com.intellij.execution.runners.ExecutionEnvironment; import com.intellij.ide.BrowserUtil; import com.intellij.ide.plugins.IdeaPluginDescriptor; import com.intellij.ide.plugins.PluginManager; +import com.intellij.ide.plugins.PluginManagerCore; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.ex.ApplicationManagerEx; import com.intellij.openapi.components.PathMacroManager; @@ -50,7 +51,6 @@ import org.jetbrains.annotations.NotNull; import javax.swing.*; import java.io.File; -import java.io.IOException; import java.util.List; import static org.intellij.lang.xpath.xslt.run.XsltRunConfiguration.isEmpty; @@ -86,105 +86,104 @@ public class XsltCommandLineState extends CommandLineState { } protected SimpleJavaParameters createJavaParameters() throws ExecutionException { - final Sdk jdk = myXsltRunConfiguration.getEffectiveJDK(); - if (jdk == null) { - throw CantRunException.noJdkConfigured(); + final Sdk jdk = myXsltRunConfiguration.getEffectiveJDK(); + if (jdk == null) { + throw CantRunException.noJdkConfigured(); + } + + final SimpleJavaParameters parameters = new SimpleJavaParameters(); + parameters.setJdk(jdk); + + if (myXsltRunConfiguration.getJdkChoice() == XsltRunConfiguration.JdkChoice.FROM_MODULE) { + final Module module = myXsltRunConfiguration.getEffectiveModule(); + // relaxed check for valid module: when running XSLTs that don't belong to any module, let's assume it is + // OK to run as if just a JDK has been selected (a missing JDK would already have been complained about above) + if (module != null) { + OrderEnumerator.orderEntries(module).productionOnly().recursively().classes().collectPaths(parameters.getClassPath()); } + } - final SimpleJavaParameters parameters = new SimpleJavaParameters(); - parameters.setJdk(jdk); + final ParametersList vmParameters = parameters.getVMParametersList(); + vmParameters.addParametersString(myXsltRunConfiguration.myVmArguments); + if (isEmpty(myXsltRunConfiguration.getXsltFile())) { + throw new CantRunException("No XSLT file selected"); + } + vmParameters.defineProperty("xslt.file", myXsltRunConfiguration.getXsltFile()); + if (isEmpty(myXsltRunConfiguration.getXmlInputFile())) { + throw new CantRunException("No XML input file selected"); + } + vmParameters.defineProperty("xslt.input", myXsltRunConfiguration.getXmlInputFile()); - if (myXsltRunConfiguration.getJdkChoice() == XsltRunConfiguration.JdkChoice.FROM_MODULE) { - final Module module = myXsltRunConfiguration.getEffectiveModule(); - // relaxed check for valid module: when running XSLTs that don't belong to any module, let's assume it is - // OK to run as if just a JDK has been selected (a missing JDK would already have been complained about above) - if (module != null) { - OrderEnumerator.orderEntries(module).productionOnly().recursively().classes().collectPaths(parameters.getClassPath()); - } + final XsltRunConfiguration.OutputType outputType = myXsltRunConfiguration.getOutputType(); + if (outputType == XsltRunConfiguration.OutputType.CONSOLE) { + //noinspection deprecation + myPort = NetUtils.tryToFindAvailableSocketPort(myXsltRunConfiguration.myRunnerPort); + vmParameters.defineProperty("xslt.listen-port", String.valueOf(myPort)); + } + if (myXsltRunConfiguration.isSaveToFile()) { + vmParameters.defineProperty("xslt.output", myXsltRunConfiguration.myOutputFile); + } + + for (Pair pair : myXsltRunConfiguration.getParameters()) { + final String name = pair.getFirst(); + final String value = pair.getSecond(); + if (isEmpty(name) || value == null) continue; + vmParameters.defineProperty("xslt.param." + name, value); + } + vmParameters.defineProperty("xslt.smart-error-handling", String.valueOf(myXsltRunConfiguration.mySmartErrorHandling)); + + final PluginId pluginId = PluginManagerCore.getPluginByClassName(getClass().getName()); + assert pluginId != null || System.getProperty("xslt.plugin.path") != null : "PluginId not found - development builds need to specify -Dxslt.plugin.path=../out/classes/production/xslt-rt"; + + final File pluginPath; + if (pluginId != null) { + final IdeaPluginDescriptor descriptor = PluginManager.getPlugin(pluginId); + assert descriptor != null; + pluginPath = descriptor.getPath(); + } + else { + // -Dxslt.plugin.path=C:\work\java\intellij/ultimate\out\classes\production\xslt-rt + pluginPath = new File(System.getProperty("xslt.plugin.path")); + } + + LOG.debug("Plugin Path = " + pluginPath.getAbsolutePath()); + + final char c = File.separatorChar; + File rtClasspath = new File(pluginPath, "lib" + c + "rt" + c + "xslt-rt.jar"); + // File rtClasspath = new File("C:/Demetra/plugins/xpath/lib/rt/xslt-rt.jar"); + if (!rtClasspath.exists()) { + LOG.warn("Plugin's Runtime classes not found in " + rtClasspath.getAbsolutePath()); + if (!(rtClasspath = new File(pluginPath, "classes")).exists()) { + if (ApplicationManagerEx.getApplicationEx().isInternal() && new File(pluginPath, "org").exists()) { + rtClasspath = pluginPath; + } + else { + throw new CantRunException("Runtime classes not found"); + } } + parameters.getVMParametersList().prepend("-ea"); + } + parameters.getClassPath().addTail(rtClasspath.getAbsolutePath()); - final ParametersList vmParameters = parameters.getVMParametersList(); - vmParameters.addParametersString(myXsltRunConfiguration.myVmArguments); - if (isEmpty(myXsltRunConfiguration.getXsltFile())) { - throw new CantRunException("No XSLT file selected"); - } - vmParameters.defineProperty("xslt.file", myXsltRunConfiguration.getXsltFile()); - if (isEmpty(myXsltRunConfiguration.getXmlInputFile())) { - throw new CantRunException("No XML input file selected"); - } - vmParameters.defineProperty("xslt.input", myXsltRunConfiguration.getXmlInputFile()); - - final XsltRunConfiguration.OutputType outputType = myXsltRunConfiguration.getOutputType(); - if (outputType == XsltRunConfiguration.OutputType.CONSOLE) { - try { - myPort = NetUtils.findAvailableSocketPort(); - } catch (IOException e) { - //noinspection deprecation - myPort = myXsltRunConfiguration.myRunnerPort; - } - vmParameters.defineProperty("xslt.listen-port", String.valueOf(myPort)); - } - if (myXsltRunConfiguration.isSaveToFile()) { - vmParameters.defineProperty("xslt.output", myXsltRunConfiguration.myOutputFile); - } - - for (Pair pair : myXsltRunConfiguration.getParameters()) { - final String name = pair.getFirst(); - final String value = pair.getSecond(); - if (isEmpty(name) || value == null) continue; - vmParameters.defineProperty("xslt.param." + name, value); - } - vmParameters.defineProperty("xslt.smart-error-handling", String.valueOf(myXsltRunConfiguration.mySmartErrorHandling)); - - final PluginId pluginId = PluginManager.getPluginByClassName(getClass().getName()); - assert pluginId != null || System.getProperty("xslt.plugin.path") != null : "PluginId not found - development builds need to specify -Dxslt.plugin.path=../out/classes/production/xslt-rt"; - - final File pluginPath; - if (pluginId != null) { - final IdeaPluginDescriptor descriptor = PluginManager.getPlugin(pluginId); - assert descriptor != null; - pluginPath = descriptor.getPath(); - } else { - // -Dxslt.plugin.path=C:\work\java\intellij/ultimate\out\classes\production\xslt-rt - pluginPath = new File(System.getProperty("xslt.plugin.path")); - } - - LOG.debug("Plugin Path = " + pluginPath.getAbsolutePath()); - - final char c = File.separatorChar; - File rtClasspath = new File(pluginPath, "lib" + c + "rt" + c + "xslt-rt.jar"); -// File rtClasspath = new File("C:/Demetra/plugins/xpath/lib/rt/xslt-rt.jar"); - if (!rtClasspath.exists()) { - LOG.warn("Plugin's Runtime classes not found in " + rtClasspath.getAbsolutePath()); - if (!(rtClasspath = new File(pluginPath, "classes")).exists()) { - if (ApplicationManagerEx.getApplicationEx().isInternal() && new File(pluginPath, "org").exists()) { - rtClasspath = pluginPath; - } else { - throw new CantRunException("Runtime classes not found"); - } - } - parameters.getVMParametersList().prepend("-ea"); - } - parameters.getClassPath().addTail(rtClasspath.getAbsolutePath()); - - parameters.setMainClass("org.intellij.plugins.xslt.run.rt.XSLTRunner"); + parameters.setMainClass("org.intellij.plugins.xslt.run.rt.XSLTRunner"); if (isEmpty(myXsltRunConfiguration.myWorkingDirectory)) { parameters.setWorkingDirectory(new File(myXsltRunConfiguration.getXsltFile()).getParentFile().getAbsolutePath()); - } else { + } + else { parameters.setWorkingDirectory(expandPath(myXsltRunConfiguration.myWorkingDirectory, myXsltRunConfiguration.getEffectiveModule(), myXsltRunConfiguration.getProject())); } - myExtensionData = new UserDataHolderBase(); - final List extensions = XsltRunnerExtension.getExtensions(myXsltRunConfiguration, myIsDebugger); - for (XsltRunnerExtension extension : extensions) { - extension.patchParameters(parameters, myXsltRunConfiguration, myExtensionData); - } + myExtensionData = new UserDataHolderBase(); + final List extensions = XsltRunnerExtension.getExtensions(myXsltRunConfiguration, myIsDebugger); + for (XsltRunnerExtension extension : extensions) { + extension.patchParameters(parameters, myXsltRunConfiguration, myExtensionData); + } - parameters.setUseDynamicClasspath(JdkUtil.useDynamicClasspath(myXsltRunConfiguration.getProject())); + parameters.setUseDynamicClasspath(JdkUtil.useDynamicClasspath(myXsltRunConfiguration.getProject())); - return parameters; + return parameters; } protected static String expandPath(String path, Module module, Project project) { diff --git a/plugins/xslt-debugger/src/org/intellij/plugins/xsltDebugger/XsltDebuggerExtension.java b/plugins/xslt-debugger/src/org/intellij/plugins/xsltDebugger/XsltDebuggerExtension.java index f48a5eadb601..038d5be4d7d4 100644 --- a/plugins/xslt-debugger/src/org/intellij/plugins/xsltDebugger/XsltDebuggerExtension.java +++ b/plugins/xslt-debugger/src/org/intellij/plugins/xsltDebugger/XsltDebuggerExtension.java @@ -25,6 +25,7 @@ import com.intellij.execution.process.ProcessListener; import com.intellij.icons.AllIcons; import com.intellij.ide.plugins.IdeaPluginDescriptor; import com.intellij.ide.plugins.PluginManager; +import com.intellij.ide.plugins.PluginManagerCore; import com.intellij.openapi.application.PathManager; import com.intellij.openapi.application.ex.ApplicationManagerEx; import com.intellij.openapi.diagnostic.Logger; @@ -125,7 +126,7 @@ public class XsltDebuggerExtension extends XsltRunnerExtension { final char c = File.separatorChar; - final PluginId pluginId = PluginManager.getPluginByClassName(getClass().getName()); + final PluginId pluginId = PluginManagerCore.getPluginByClassName(getClass().getName()); assert pluginId != null || System.getProperty("xslt-debugger.plugin.path") != null; final File pluginPath; diff --git a/python/helpers/pydev/pydev_monkey.py b/python/helpers/pydev/pydev_monkey.py index 07c7e2b93929..c5dd39a87870 100644 --- a/python/helpers/pydev/pydev_monkey.py +++ b/python/helpers/pydev/pydev_monkey.py @@ -37,8 +37,9 @@ def patch_args(args): host, port = pydevd.dispatch() if port is not None: - args[indC + 1] = "import sys; sys.path.append('%s'); import pydevd; pydevd.settrace(host='%s', port=%s, suspend=False); %s"%(helpers, host, port, args[indC + 1]) - return args + new_args.extend(args) + new_args[indC + 1] = "import sys; sys.path.append('%s'); import pydevd; pydevd.settrace(host='%s', port=%s, suspend=False); %s"%(helpers, host, port, args[indC + 1]) + return new_args else: new_args.append(args[0]) else: diff --git a/resources-en/src/tips/images/complete_statement.png b/resources-en/src/tips/images/complete_statement.png index f52d046573c4..d0b55f9633a1 100644 Binary files a/resources-en/src/tips/images/complete_statement.png and b/resources-en/src/tips/images/complete_statement.png differ diff --git a/resources-en/src/tips/images/complete_statement@2x.png b/resources-en/src/tips/images/complete_statement@2x.png index 257269820fad..d5f5a9c99984 100644 Binary files a/resources-en/src/tips/images/complete_statement@2x.png and b/resources-en/src/tips/images/complete_statement@2x.png differ diff --git a/resources-en/src/tips/images/complete_statement@2x_dark.png b/resources-en/src/tips/images/complete_statement@2x_dark.png index 53fc8021cdd7..f989cd06fbc3 100644 Binary files a/resources-en/src/tips/images/complete_statement@2x_dark.png and b/resources-en/src/tips/images/complete_statement@2x_dark.png differ diff --git a/resources-en/src/tips/images/complete_statement_dark.png b/resources-en/src/tips/images/complete_statement_dark.png index c782129a625f..747a012205c9 100644 Binary files a/resources-en/src/tips/images/complete_statement_dark.png and b/resources-en/src/tips/images/complete_statement_dark.png differ diff --git a/resources-en/src/tips/images/sidebyside.png b/resources-en/src/tips/images/sidebyside.png new file mode 100644 index 000000000000..1a9d16d800bd Binary files /dev/null and b/resources-en/src/tips/images/sidebyside.png differ diff --git a/resources-en/src/tips/images/sidebyside@2x.png b/resources-en/src/tips/images/sidebyside@2x.png new file mode 100644 index 000000000000..d4a6892118cf Binary files /dev/null and b/resources-en/src/tips/images/sidebyside@2x.png differ diff --git a/resources-en/src/tips/images/sidebyside@2x_dark.png b/resources-en/src/tips/images/sidebyside@2x_dark.png new file mode 100644 index 000000000000..99bdfbf3fbd9 Binary files /dev/null and b/resources-en/src/tips/images/sidebyside@2x_dark.png differ diff --git a/resources-en/src/tips/images/sidebyside_dark.png b/resources-en/src/tips/images/sidebyside_dark.png new file mode 100644 index 000000000000..7bd244a2291c Binary files /dev/null and b/resources-en/src/tips/images/sidebyside_dark.png differ diff --git a/resources-en/src/tips/tips.xml b/resources-en/src/tips/tips.xml index c4a8f818e6fe..503f38594771 100644 --- a/resources-en/src/tips/tips.xml +++ b/resources-en/src/tips/tips.xml @@ -162,6 +162,5 @@ - diff --git a/xml/dom-impl/src/com/intellij/util/xml/impl/DomInvocationHandler.java b/xml/dom-impl/src/com/intellij/util/xml/impl/DomInvocationHandler.java index d1d85ccecbdf..98666dfc780f 100644 --- a/xml/dom-impl/src/com/intellij/util/xml/impl/DomInvocationHandler.java +++ b/xml/dom-impl/src/com/intellij/util/xml/impl/DomInvocationHandler.java @@ -441,7 +441,7 @@ public abstract class DomInvocationHandler ourTypeParameters = new ConcurrentFactoryMap() { @NotNull protected Class create(final Type key) { - final Class result = ReflectionUtil.substituteGenericType(GENERIC_VALUE_TYPE_VARIABLE, key); + final Class result = substituteGenericType(GENERIC_VALUE_TYPE_VARIABLE, key); return result == null ? DUMMY : result; } }; - - private DomUtil() { - } + private static final ConcurrentFactoryMap, Class> ourVariableSubstitutions = new ConcurrentFactoryMap, Class>() { + @Nullable + protected Class create(final Pair key) { + return ReflectionUtil.substituteGenericType(key.first, key.second); + } + }; public static Class extractParameterClassFromGenericType(Type type) { return getGenericValueParameter(type); @@ -156,6 +159,10 @@ public class DomUtil { return description != null ? description.getGetterMethod(description.getValues(parent).indexOf(element)) : null; } + public static Class substituteGenericType(Type genericType, Type classType) { + return ourVariableSubstitutions.get(Pair.create(genericType, classType)); + } + @Nullable public static Class getGenericValueParameter(Type type) { final Class aClass = ourTypeParameters.get(type);