Merge remote-tracking branch 'origin/master' appcode/144.959 clion/144.958 rubymine/144.955
authorVladimir.Orlov <Vladimir.Orlov@jetbrains.com>
Mon, 9 Nov 2015 07:34:58 +0000 (10:34 +0300)
committerVladimir.Orlov <Vladimir.Orlov@jetbrains.com>
Mon, 9 Nov 2015 07:34:58 +0000 (10:34 +0300)
224 files changed:
java/debugger/impl/src/com/intellij/debugger/engine/evaluation/TextWithImportsImpl.java
java/debugger/impl/src/com/intellij/debugger/jdi/LocalVariablesUtil.java
java/execution/impl/src/com/intellij/testIntegration/ShowRecentTests.java
java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/SimplifyBooleanExpressionFix.java
java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/ControlFlowAnalyzer.java
java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/DataFlowInspectionBase.java
java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/PurityInference.java
java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/StandardInstructionVisitor.java
java/java-analysis-impl/src/com/intellij/codeInspection/nullable/NullableStuffInspectionBase.java
java/java-analysis-impl/src/com/intellij/codeInspection/reference/RefJavaUtilImpl.java
java/java-analysis-impl/src/com/intellij/codeInspection/uncheckedWarnings/UncheckedWarningLocalInspectionBase.java
java/java-analysis-impl/src/com/intellij/refactoring/extractMethod/ParametersFolder.java
java/java-impl/src/com/intellij/codeInsight/FunctionalInterfaceSuggester.java
java/java-impl/src/com/intellij/codeInsight/JavaRegExpModifierProvider.java
java/java-impl/src/com/intellij/codeInsight/completion/JavaCompletionUtil.java
java/java-impl/src/com/intellij/codeInsight/completion/JavaKeywordCompletion.java
java/java-impl/src/com/intellij/codeInsight/completion/JavaMemberNameCompletionContributor.java
java/java-impl/src/com/intellij/codeInsight/completion/JavaMethodMergingContributor.java
java/java-impl/src/com/intellij/codeInsight/completion/JavaSmartCompletionContributor.java
java/java-impl/src/com/intellij/codeInsight/completion/SmartCastProvider.java
java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/DelegateWithDefaultParamValueIntentionAction.java
java/java-impl/src/com/intellij/codeInsight/editorActions/smartEnter/MissingReturnExpressionFixer.java
java/java-impl/src/com/intellij/codeInsight/generation/GenerateDelegateHandler.java
java/java-impl/src/com/intellij/codeInsight/generation/OverrideImplementUtil.java
java/java-impl/src/com/intellij/codeInsight/intention/impl/IntroduceVariableIntentionAction.java
java/java-impl/src/com/intellij/lang/java/JavaDocumentationProvider.java
java/java-impl/src/com/intellij/refactoring/changeSignature/JavaChangeSignatureUsageProcessor.java
java/java-impl/src/com/intellij/refactoring/extractMethod/ExtractMethodProcessor.java
java/java-impl/src/com/intellij/refactoring/extractMethodObject/ExtractLightMethodObjectHandler.java
java/java-impl/src/com/intellij/refactoring/inheritanceToDelegation/InheritanceToDelegationProcessor.java
java/java-impl/src/com/intellij/refactoring/inline/InlineMethodProcessor.java
java/java-impl/src/com/intellij/refactoring/introduceVariable/IntroduceVariableBase.java
java/java-impl/src/com/intellij/refactoring/move/moveMembers/MoveJavaMemberHandler.java
java/java-impl/src/com/intellij/refactoring/wrapreturnvalue/WrapReturnValueAction.java
java/java-impl/src/com/intellij/slicer/SliceUsageCellRenderer.java
java/java-psi-api/src/com/intellij/psi/LambdaUtil.java
java/java-psi-api/src/com/intellij/psi/PsiIntersectionType.java
java/java-psi-api/src/com/intellij/psi/PsiMethodReferenceUtil.java
java/java-psi-api/src/com/intellij/psi/util/PsiConcatenationUtil.java
java/java-psi-api/src/com/intellij/psi/util/PsiMethodUtil.java
java/java-psi-impl/src/com/intellij/psi/impl/PsiImplUtil.java
java/java-psi-impl/src/com/intellij/psi/impl/source/PsiJavaCodeReferenceElementImpl.java
java/java-psi-impl/src/com/intellij/psi/impl/source/PsiTypeElementImpl.java
java/java-psi-impl/src/com/intellij/psi/impl/source/tree/java/ReplaceExpressionUtil.java
java/java-tests/testData/codeInsight/completion/smartType/MethodThrows-out.java [new file with mode: 0644]
java/java-tests/testData/codeInsight/completion/smartType/MethodThrows.java [new file with mode: 0644]
java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/newMethodRef/IDEA147511.java [new file with mode: 0644]
java/java-tests/testData/inspection/nullableProblems/NotNullByDefaultFieldNotInitialized.java [new file with mode: 0644]
java/java-tests/testData/refactoring/changeSignature/JavadocOfDeleted.java [new file with mode: 0644]
java/java-tests/testData/refactoring/changeSignature/JavadocOfDeleted_after.java [new file with mode: 0644]
java/java-tests/testData/refactoring/inlineLocal/ArrayAccessPriority.java [new file with mode: 0644]
java/java-tests/testData/refactoring/inlineLocal/ArrayAccessPriority.java.after [new file with mode: 0644]
java/java-tests/testData/refactoring/moveMembers/stringConstantInSwitchLabelExpression/after/A.java [new file with mode: 0644]
java/java-tests/testData/refactoring/moveMembers/stringConstantInSwitchLabelExpression/after/B.java [new file with mode: 0644]
java/java-tests/testData/refactoring/moveMembers/stringConstantInSwitchLabelExpression/before/A.java [new file with mode: 0644]
java/java-tests/testData/refactoring/moveMembers/stringConstantInSwitchLabelExpression/before/B.java [new file with mode: 0644]
java/java-tests/testSrc/com/intellij/codeInsight/completion/SmartTypeCompletionTest.java
java/java-tests/testSrc/com/intellij/codeInsight/daemon/lambda/InferredTypeTest.java
java/java-tests/testSrc/com/intellij/codeInsight/daemon/lambda/NewMethodRefHighlightingTest.java
java/java-tests/testSrc/com/intellij/codeInsight/psi/AnnotatedTypeTest.groovy
java/java-tests/testSrc/com/intellij/codeInspection/NullableStuffInspectionTest.java
java/java-tests/testSrc/com/intellij/psi/codeStyle/autodetect/JavaAutoDetectIndentPerformanceTest.java
java/java-tests/testSrc/com/intellij/refactoring/ChangeSignatureTest.java
java/java-tests/testSrc/com/intellij/refactoring/MoveMembersTest.java
java/java-tests/testSrc/com/intellij/refactoring/inline/InlineLocalTest.java
java/structuralsearch-java/src/com/intellij/structuralsearch/JavaStructuralSearchProfile.java
java/structuralsearch-java/src/com/intellij/structuralsearch/impl/matcher/JavaMatchingVisitor.java
java/typeMigration/src/com/intellij/refactoring/typeMigration/intentions/ConvertFieldToThreadLocalIntention.java
java/typeMigration/src/com/intellij/refactoring/typeMigration/rules/AtomicConversionRule.java
platform/core-api/src/com/intellij/lang/CodeDocumentationAwareCommenter.java
platform/core-api/src/com/intellij/openapi/project/DumbService.java
platform/core-api/src/com/intellij/openapi/vfs/VfsUtilCore.java
platform/core-impl/src/com/intellij/openapi/editor/impl/EditorDocumentPriorities.java
platform/core-impl/src/com/intellij/util/DocumentUtil.java
platform/lang-impl/src/com/intellij/ide/macro/FileDirPathFromParentMacro.java
platform/lang-impl/src/com/intellij/packageDependencies/ui/DirectoryNode.java
platform/lang-impl/src/com/intellij/psi/impl/file/DirectoryIconProvider.java
platform/platform-impl/src/com/intellij/ide/IdeEventQueue.java
platform/platform-impl/src/com/intellij/openapi/editor/impl/EditorImpl.java
platform/platform-impl/src/com/intellij/openapi/editor/impl/FontInfo.java
platform/platform-impl/src/com/intellij/openapi/editor/impl/view/EditorSizeManager.java
platform/platform-impl/src/com/intellij/openapi/keymap/impl/ui/KeyboardShortcutDialog.java
platform/platform-impl/src/com/intellij/openapi/keymap/impl/ui/KeyboardShortcutPanel.java
platform/platform-impl/src/com/intellij/openapi/keymap/impl/ui/KeymapPanel.java
platform/platform-impl/src/com/intellij/openapi/keymap/impl/ui/MouseShortcutDialog.java
platform/platform-impl/src/com/intellij/openapi/keymap/impl/ui/MouseShortcutPanel.java
platform/platform-impl/src/com/intellij/openapi/keymap/impl/ui/ShortcutDialog.java [new file with mode: 0644]
platform/platform-impl/src/com/intellij/openapi/keymap/impl/ui/ShortcutFilteringPanel.java
platform/platform-impl/src/com/intellij/openapi/keymap/impl/ui/ShortcutPanel.java [new file with mode: 0644]
platform/platform-impl/src/com/intellij/openapi/keymap/impl/ui/ShortcutTextField.java
platform/platform-impl/src/com/intellij/openapi/project/DumbServiceImpl.java
platform/platform-impl/src/com/intellij/openapi/wm/impl/ToolWindowManagerImpl.java
platform/platform-resources-en/src/messages/KeyMapBundle.properties
platform/platform-tests/testSrc/com/intellij/openapi/editor/impl/EditorStressTest.java
platform/platform-tests/testSrc/com/intellij/openapi/editor/impl/softwrap/mapping/SoftWrapStressTest.java
platform/platform-tests/testSrc/com/intellij/openapi/vfs/VfsUtilTest.java
platform/smRunner/src/com/intellij/execution/testframework/sm/runner/ui/SMTRunnerUIActionsHandler.java
platform/smRunner/src/com/intellij/execution/testframework/sm/runner/ui/SMTestRunnerResultsForm.java
platform/structuralsearch/source/com/intellij/structuralsearch/DocumentBasedReplaceHandler.java
platform/structuralsearch/source/com/intellij/structuralsearch/MatchResult.java
platform/structuralsearch/source/com/intellij/structuralsearch/StructuralSearchProfile.java
platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/GlobalMatchingVisitor.java
platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/MatchResultImpl.java
platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/MatcherImpl.java
platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/compiler/PatternCompiler.java
platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/handlers/SubstitutionHandler.java
platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/predicates/ScriptLog.java [new file with mode: 0644]
platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/predicates/ScriptPredicate.java
platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/predicates/ScriptSupport.java
platform/structuralsearch/source/com/intellij/structuralsearch/plugin/replace/impl/ReplacementBuilder.java
platform/structuralsearch/source/com/intellij/structuralsearch/plugin/replace/impl/ReplacementContext.java
platform/structuralsearch/source/com/intellij/structuralsearch/plugin/replace/impl/Replacer.java
platform/structuralsearch/source/com/intellij/structuralsearch/plugin/ui/SearchCommand.java
platform/structuralsearch/testSource/com/intellij/structuralsearch/StructuralSearchTest.java
platform/testFramework/src/com/intellij/testFramework/LightProjectDescriptor.java
platform/testRunner/src/com/intellij/execution/testframework/actions/ScrollToTestSourceAction.java
platform/util/src/com/intellij/ui/components/JBPanel.java
platform/util/src/com/intellij/util/io/SafeFileOutputStream.java
platform/vcs-log/graph/src/com/intellij/vcs/log/graph/collapsing/DottedFilterEdgesGenerator.java
platform/vcs-log/graph/src/com/intellij/vcs/log/graph/impl/facade/BekBaseController.java
platform/vcs-log/graph/src/com/intellij/vcs/log/graph/impl/facade/bek/BekBranchCreator.java
platform/vcs-log/graph/src/com/intellij/vcs/log/graph/impl/facade/bek/BekChecker.java
platform/vcs-log/graph/test/com/intellij/vcs/log/graph/TestGraphBuilder.kt
platform/vcs-log/graph/test/com/intellij/vcs/log/graph/linearBek/BekTest.kt [new file with mode: 0644]
platform/vcs-log/graph/test/com/intellij/vcs/log/graph/linearBek/TestUtils.kt
platform/xdebugger-impl/src/com/intellij/xdebugger/impl/actions/handlers/XDebuggerEvaluateActionHandler.java
platform/xdebugger-impl/src/com/intellij/xdebugger/impl/ui/XDebuggerEditorBase.java
plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/intellij/codeInspection/booleanIsAlwaysInverted/BooleanMethodIsAlwaysInvertedInspectionBase.java
plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/numeric/UnpredictableBigDecimalConstructorCallInspection.java
plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/psiutils/ParenthesesUtils.java
plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/style/StringBufferReplaceableByStringInspection.java
plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/threading/StaticInitializerReferencesSubClassInspection.java
plugins/InspectionGadgets/src/com/siyeh/ig/junit/BeforeClassOrAfterClassIsPublicStaticVoidNoArgInspection.java
plugins/InspectionGadgets/test/com/siyeh/igtest/threading/StaticInitializerReferencesSubClass/StaticInitializer.java
plugins/IntelliLang/java-support/org/intellij/plugins/intelliLang/util/SubstitutedExpressionEvaluationHelper.java
plugins/IntentionPowerPak/src/com/siyeh/ipp/equality/ReplaceEqualityWithEqualsIntention.java
plugins/devkit/resources/META-INF/plugin.xml
plugins/devkit/resources/inspectionDescriptions/UsePrimitiveTypes.html [new file with mode: 0644]
plugins/devkit/src/dom/impl/ExtensionDomExtender.java
plugins/devkit/src/inspections/DevKitImplicitUsageProvider.java
plugins/devkit/src/inspections/internal/UsePrimitiveTypesInspection.java [new file with mode: 0644]
plugins/eclipse/src/org/jetbrains/idea/eclipse/conversion/EclipseClasspathWriter.java
plugins/git4idea/lib/trilead-ssh2-src.zip
plugins/git4idea/lib/trilead-ssh2.jar
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/annotator/GroovyAnnotator.java
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/codeInspection/noReturnMethod/MissingReturnInspection.java
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/codeInspection/type/GroovyTypeCheckVisitor.java
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/findUsages/GroovyFindUsagesProvider.java
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/findUsages/LiteralConstructorReference.java
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/controlFlow/impl/ControlFlowBuilder.java
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/controlFlow/impl/MaybeReturnInstruction.java
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/GrRangeType.java
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/GrTraitType.java
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/expressions/GrReferenceResolveRunner.java
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/expressions/TypesUtil.java
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/expressions/path/GrWithTraitTypeCalculator.java
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/expressions/types/GrSafeCastExpressionImpl.java
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/typeEnhancers/GrBooleanTypeConverter.java
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/typeEnhancers/GrCharConverter.java
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/typeEnhancers/GrNullVoidConverter.java
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/util/GroovyPropertyUtils.java
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/util/PsiUtil.java
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/resolve/ResolveUtil.java
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/resolve/processors/AccessorResolverProcessor.java
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/util/GroovyStdTypeCalculators.java
plugins/groovy/src/META-INF/plugin.xml
plugins/groovy/src/org/jetbrains/plugins/groovy/codeInsight/hint/GroovyExpressionTypeProvider.java
plugins/groovy/src/org/jetbrains/plugins/groovy/intentions/conversions/ConvertSimpleGetterToPropertyIntention.java
plugins/groovy/src/org/jetbrains/plugins/groovy/intentions/declaration/GrIntroduceLocalVariableIntention.java
plugins/groovy/src/org/jetbrains/plugins/groovy/lang/completion/CompleteReferenceExpression.java
plugins/groovy/src/org/jetbrains/plugins/groovy/lang/completion/GroovyCompletionData.java
plugins/groovy/src/org/jetbrains/plugins/groovy/lang/completion/GroovyCompletionUtil.java
plugins/groovy/src/org/jetbrains/plugins/groovy/lang/documentation/GroovyDocumentationProvider.java
plugins/groovy/src/org/jetbrains/plugins/groovy/overrideImplement/GroovyOverrideImplementUtil.java
plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/convertToJava/ClassItemGeneratorImpl.java
plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/convertToJava/ClosureGenerator.java
plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/convertToJava/CodeBlockGenerator.java
plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/convertToJava/ExpressionGenerator.java
plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/extract/ExtractUtil.java
plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/extract/method/GroovyExtractMethodDialog.java
plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/inline/GroovyMethodInliner.java
plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/introduce/GrIntroduceHandlerBase.java
plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/introduce/parameter/GrIntroduceParameterDialog.java
plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/introduce/parameter/java2groovy/GroovyIntroduceParameterMethodUsagesProcessor.java
plugins/groovy/test/org/jetbrains/plugins/groovy/LightGroovyTestCase.groovy
plugins/groovy/test/org/jetbrains/plugins/groovy/lang/resolve/GroovyTraitCoercionTest.groovy [new file with mode: 0644]
plugins/groovy/test/org/jetbrains/plugins/groovy/lang/resolve/ResolvePropertyTest.groovy
plugins/testng/src/resources/standardSchemas/testng-1.0.dtd
plugins/ui-designer/src/com/intellij/uiDesigner/wizard/Generator.java
python/helpers/rest_formatter.py
python/psi-api/src/com/jetbrains/python/codeInsight/PyCustomMember.java
python/psi-api/src/com/jetbrains/python/nameResolver/NameResolverTools.java
python/psi-api/src/com/jetbrains/python/psi/PyCallExpression.java
python/psi-api/src/com/jetbrains/python/psi/PyClass.java
python/src/com/jetbrains/python/codeInsight/PyMethodNavigationOffsetProvider.java
python/src/com/jetbrains/python/codeInsight/completion/PySuperMethodCompletionContributor.java
python/src/com/jetbrains/python/codeInsight/override/PyOverrideImplementUtil.java
python/src/com/jetbrains/python/codeInsight/userSkeletons/PyUserSkeletonsClassMembersProvider.java
python/src/com/jetbrains/python/documentation/PyDocumentationBuilder.java
python/src/com/jetbrains/python/documentation/docstrings/PyStructuredDocstringFormatter.java
python/src/com/jetbrains/python/inspections/PyAbstractClassInspection.java
python/src/com/jetbrains/python/inspections/PyOldStyleClassesInspection.java
python/src/com/jetbrains/python/inspections/quickfix/AddFieldQuickFix.java
python/src/com/jetbrains/python/inspections/unresolvedReference/PyUnresolvedReferencesInspection.java
python/src/com/jetbrains/python/projectView/PyElementNode.java
python/src/com/jetbrains/python/psi/impl/PyClassImpl.java
python/src/com/jetbrains/python/psi/impl/PyFunctionImpl.java
python/src/com/jetbrains/python/psi/search/PySuperMethodsSearchExecutor.java
python/src/com/jetbrains/python/psi/stubs/PyClassAttributesIndex.java
python/src/com/jetbrains/python/psi/types/PyTypeChecker.java
python/src/com/jetbrains/python/psi/types/PyTypeUtil.java
python/src/com/jetbrains/python/refactoring/classes/membersManager/MethodsManager.java
python/src/com/jetbrains/python/refactoring/extractmethod/PyExtractMethodUtil.java
python/src/com/jetbrains/python/testing/attest/PythonAtTestConfigurationProducer.java
python/src/com/jetbrains/python/testing/doctest/PythonDocTestUtil.java
python/src/com/jetbrains/python/testing/pytest/PyTestUtil.java
python/src/com/jetbrains/python/validation/Pep8ExternalAnnotator.java
python/testData/inspections/PyAbstractClassInspection/notImplementedOverriddenInParent.py [new file with mode: 0644]
python/testSrc/com/jetbrains/python/PyControlFlowBuilderTest.java
python/testSrc/com/jetbrains/python/PyOverrideTest.java
python/testSrc/com/jetbrains/python/PyStubsTest.java
python/testSrc/com/jetbrains/python/inspections/PyAbstractClassInspectionTest.java
python/testSrc/com/jetbrains/python/refactoring/classes/PyDependenciesComparatorTest.java
spellchecker/src/com/intellij/spellchecker/english.dic

index a73169ac02eabce59a257b9142e006af316958f8..cf0786258b34432d858d6bbff2c50c5b29f2fc85 100644 (file)
@@ -16,6 +16,7 @@
 package com.intellij.debugger.engine.evaluation;
 
 import com.intellij.debugger.ui.DebuggerEditorImpl;
+import com.intellij.lang.LanguageUtil;
 import com.intellij.openapi.fileTypes.FileType;
 import com.intellij.openapi.fileTypes.FileTypeManager;
 import com.intellij.openapi.fileTypes.StdFileTypes;
@@ -26,7 +27,6 @@ import com.intellij.psi.*;
 import com.intellij.xdebugger.XExpression;
 import com.intellij.xdebugger.evaluation.EvaluationMode;
 import com.intellij.xdebugger.impl.breakpoints.XExpressionImpl;
-import com.intellij.xdebugger.impl.ui.XDebuggerEditorBase;
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
 
@@ -136,7 +136,7 @@ public final class TextWithImportsImpl implements TextWithImports{
   public static XExpression toXExpression(@Nullable TextWithImports text) {
     if (text != null && !text.getText().isEmpty()) {
       return new XExpressionImpl(text.getText(),
-                                 XDebuggerEditorBase.getFileTypeLanguage(text.getFileType()),
+                                 LanguageUtil.getFileTypeLanguage(text.getFileType()),
                                  StringUtil.nullize(text.getImports()),
                                  getMode(text.getKind()));
     }
@@ -169,7 +169,7 @@ public final class TextWithImportsImpl implements TextWithImports{
       return new TextWithImportsImpl(getKind(expression.getMode()),
                                      expression.getExpression(),
                                      StringUtil.notNullize(expression.getCustomInfo()),
-                                     expression.getLanguage() != null ? expression.getLanguage().getAssociatedFileType() : null);
+                                     LanguageUtil.getLanguageFileType(expression.getLanguage()));
     }
   }
 }
index 4dfb02456bbc8aba31151f5c204837cc88e2bf94..50a03a53fd3d172c36c1597a3a2f8a97698d5bd0 100644 (file)
@@ -494,7 +494,7 @@ public class LocalVariablesUtil {
   }
 
   private static int getTypeSlotSize(PsiType varType) {
-    if (varType == PsiType.DOUBLE || varType == PsiType.LONG) {
+    if (PsiType.DOUBLE.equals(varType) || PsiType.LONG.equals(varType)) {
       return 2;
     }
     return 1;
index d590c25befb43f43e878d950441911d8dfbe88b3..4834b82214bb0f1be2e4141f2b861ed5a0917149 100644 (file)
@@ -24,6 +24,7 @@ import com.intellij.openapi.project.Project;
 import com.intellij.openapi.ui.popup.ListPopupStep;
 import com.intellij.ui.popup.list.ListPopupImpl;
 import com.intellij.util.PsiNavigateUtil;
+import com.intellij.util.Time;
 
 import javax.swing.*;
 import java.awt.event.ActionEvent;
@@ -35,7 +36,7 @@ public class ShowRecentTests extends AnAction {
   private static final int TEST_LIMIT = Integer.MAX_VALUE;
   
   private static Date getSinceDate() {
-    return new Date(0);
+    return new Date(System.currentTimeMillis() - Time.DAY);
   }
   
   @Override
index 612c6c6a9837398b2f572a350bc3c9de5a03ad9a..dab31757f12844c33b16ea2693ed3dbb17701197 100644 (file)
@@ -109,7 +109,7 @@ public class SimplifyBooleanExpressionFix extends LocalQuickFixOnPsiElement {
   public static void simplifyIfStatement(final PsiExpression expression) throws IncorrectOperationException {
     PsiElement parent = expression.getParent();
     if (!(parent instanceof PsiIfStatement) || ((PsiIfStatement)parent).getCondition() != expression) return;
-    if (!(expression instanceof PsiLiteralExpression) || expression.getType() != PsiType.BOOLEAN) return;
+    if (!(expression instanceof PsiLiteralExpression) || !PsiType.BOOLEAN.equals(expression.getType())) return;
     boolean condition = Boolean.parseBoolean(expression.getText());
     PsiIfStatement ifStatement = (PsiIfStatement)parent;
     if (condition) {
@@ -210,7 +210,7 @@ public class SimplifyBooleanExpressionFix extends LocalQuickFixOnPsiElement {
   }
 
   public static boolean canBeSimplified(@NotNull PsiExpression expression) {
-    if (!(expression instanceof PsiConditionalExpression) && expression.getType() != PsiType.BOOLEAN) return false;
+    if (!(expression instanceof PsiConditionalExpression) && !PsiType.BOOLEAN.equals(expression.getType())) return false;
 
     final ExpressionVisitor expressionVisitor = new ExpressionVisitor(expression.getManager(), false);
     final Ref<Boolean> canBeSimplified = new Ref<Boolean>(Boolean.FALSE);
index 209d0e91634c50e5497f8a0b44393f420aab4e1b..6880a66457103ed3009ce65e502b959c8d00c851 100644 (file)
@@ -1218,7 +1218,7 @@ public class ControlFlowAnalyzer extends JavaElementVisitor {
   }
 
   private void generateBoxingUnboxingInstructionFor(@NotNull PsiExpression expression, PsiType expectedType) {
-    if (expectedType == PsiType.VOID) return;
+    if (PsiType.VOID.equals(expectedType)) return;
 
     PsiType exprType = expression.getType();
 
index aecfbc1e3bca741f673b94884310ae95aa17c0ed..15e6d6b2e4c05a921b533b5b29345cf83ca71bd9 100644 (file)
@@ -572,7 +572,7 @@ public class DataFlowInspectionBase extends BaseJavaBatchLocalInspectionTool {
 
     PsiType returnType = method.getReturnType();
     // no warnings in void lambdas, where the expression is not returned anyway
-    if (block instanceof PsiExpression && block.getParent() instanceof PsiLambdaExpression && returnType == PsiType.VOID) return;
+    if (block instanceof PsiExpression && block.getParent() instanceof PsiLambdaExpression && PsiType.VOID.equals(returnType)) return;
     
     // no warnings for Void methods, where only null can be possibly returned
     if (returnType == null || returnType.equalsToText(CommonClassNames.JAVA_LANG_VOID)) return;
index c626a96f822215f4bc38878eb0da18ace5f50e64..38c9218254690f650be1d19d48b657eecb671506 100644 (file)
@@ -36,7 +36,7 @@ public class PurityInference {
 
   public static boolean inferPurity(@NotNull final PsiMethod method) {
     if (!InferenceFromSourceUtil.shouldInferFromSource(method) ||
-        method.getReturnType() == PsiType.VOID ||
+        PsiType.VOID.equals(method.getReturnType()) ||
         method.getBody() == null ||
         method.isConstructor() || 
         PropertyUtil.isSimpleGetter(method)) {
index a7894bf8e020143e583d5358c9199ea2c319581b..ed52d2c5e78be5eb13a898d06a1b7e5df14ab515 100644 (file)
@@ -517,18 +517,16 @@ public class StandardInstructionVisitor extends InstructionVisitor {
     PsiType varType = var.getVariableType();
     if (!(varType instanceof PsiPrimitiveType)) return null;
     
-    if (varType == PsiType.FLOAT || varType == PsiType.DOUBLE) return null;
-
-    double minValue = varType == PsiType.BYTE ? Byte.MIN_VALUE :
-                      varType == PsiType.SHORT ? Short.MIN_VALUE :
-                      varType == PsiType.INT ? Integer.MIN_VALUE :
-                      varType == PsiType.CHAR ? Character.MIN_VALUE :
-                      Long.MIN_VALUE;
-    double maxValue = varType == PsiType.BYTE ? Byte.MAX_VALUE :
-                      varType == PsiType.SHORT ? Short.MAX_VALUE :
-                      varType == PsiType.INT ? Integer.MAX_VALUE :
-                      varType == PsiType.CHAR ? Character.MAX_VALUE :
-                      Long.MAX_VALUE;
+    if (PsiType.FLOAT.equals(varType) || PsiType.DOUBLE.equals(varType)) return null;
+
+    double minValue = PsiType.BYTE.equals(varType) ? Byte.MIN_VALUE : PsiType.SHORT.equals(varType)
+                                                                 ? Short.MIN_VALUE : PsiType.INT.equals(varType)
+                                                                   ? Integer.MIN_VALUE : PsiType.CHAR.equals(varType) ? Character.MIN_VALUE :
+                                                                                         Long.MIN_VALUE;
+    double maxValue = PsiType.BYTE.equals(varType) ? Byte.MAX_VALUE : PsiType.SHORT.equals(varType)
+                                                                 ? Short.MAX_VALUE : PsiType.INT.equals(varType)
+                                                                   ? Integer.MAX_VALUE : PsiType.CHAR.equals(varType) ? Character.MAX_VALUE :
+                                                                                         Long.MAX_VALUE;
 
     return checkComparisonWithKnownRange(instruction, runner, memState, opSign, comparedWith, minValue, maxValue);
   }
index db8e62a1ea521392867a529b025b0f05480cb3a0..897eed80e468fccb66502a045e0996b07ee345e2 100644 (file)
@@ -105,12 +105,12 @@ public class NullableStuffInspectionBase extends BaseJavaBatchLocalInspectionToo
 
           checkAccessors(field, annotated, project, manager, anno, annoToRemove, holder);
 
-          if (REQUIRE_NOTNULL_FIELDS_INITIALIZED) {
-            checkNotNullFieldsInitialized(field, annotated, manager, holder);
-          }
-
           checkConstructorParameters(field, annotated, manager, anno, annoToRemove, holder);
         }
+
+        if (REQUIRE_NOTNULL_FIELDS_INITIALIZED && !annotated.isDeclaredNullable) {
+          checkNotNullFieldsInitialized(field, manager, holder);
+        }
       }
 
       @Override
@@ -259,17 +259,14 @@ public class NullableStuffInspectionBase extends BaseJavaBatchLocalInspectionToo
     LOG.assertTrue(parameter.isPhysical(), setter.getText());
   }
 
-  private static void checkNotNullFieldsInitialized(PsiField field,
-                                                    Annotated annotated,
-                                                    NullableNotNullManager manager, @NotNull ProblemsHolder holder) {
-    if (annotated.isDeclaredNotNull && !HighlightControlFlowUtil.isFieldInitializedAfterObjectConstruction(field)) {
-      final PsiAnnotation annotation = AnnotationUtil.findAnnotation(field, manager.getNotNulls());
-      if (annotation != null) {
-        holder.registerProblem(annotation.isPhysical() ? annotation : field.getNameIdentifier(),
-                               "Not-null fields must be initialized",
-                               ProblemHighlightType.GENERIC_ERROR_OR_WARNING);
-      }
-    }
+  private static void checkNotNullFieldsInitialized(PsiField field, NullableNotNullManager manager, @NotNull ProblemsHolder holder) {
+    PsiAnnotation annotation = manager.getNotNullAnnotation(field, false);
+    if (annotation == null || HighlightControlFlowUtil.isFieldInitializedAfterObjectConstruction(field)) return;
+
+    boolean byDefault = manager.isContainerAnnotation(annotation);
+    PsiJavaCodeReferenceElement name = annotation.getNameReferenceElement();
+    holder.registerProblem(annotation.isPhysical() && !byDefault ? annotation : field.getNameIdentifier(),
+                           (byDefault && name != null ? "@" + name.getReferenceName() : "Not-null") + " fields must be initialized");
   }
 
   private void checkConstructorParameters(PsiField field,
index ba105015a0f7fd66fc8d0527c0e5bc07a19bbeb2..3d78588936d41360efafda6919a8221b363c3460 100644 (file)
@@ -251,7 +251,7 @@ public class RefJavaUtilImpl extends RefJavaUtil{
 
     if (refExpression instanceof PsiMethodReferenceExpression) {
       PsiType returnType = psiMethod.getReturnType();
-      if (!psiMethod.isConstructor() && returnType != PsiType.VOID) {
+      if (!psiMethod.isConstructor() && !PsiType.VOID.equals(returnType)) {
         refMethod.setReturnValueUsed(true);
         addTypeReference(psiFrom, returnType, refFrom.getRefManager());
       }
@@ -263,7 +263,7 @@ public class RefJavaUtilImpl extends RefJavaUtil{
     );
     if (call != null) {
       PsiType returnType = psiMethod.getReturnType();
-      if (!psiMethod.isConstructor() && returnType != PsiType.VOID) {
+      if (!psiMethod.isConstructor() && !PsiType.VOID.equals(returnType)) {
         if (!(call.getParent() instanceof PsiExpressionStatement)) {
           refMethod.setReturnValueUsed(true);
         }
index efcb53682b63d45eff35a0e4dac65b35aae32999..71016e8d6795ff12ed3181b15655e692792bc7b6 100644 (file)
@@ -27,11 +27,9 @@ import com.intellij.openapi.diagnostic.Logger;
 import com.intellij.openapi.extensions.Extensions;
 import com.intellij.openapi.util.Pass;
 import com.intellij.openapi.util.WriteExternalException;
-import com.intellij.openapi.util.text.StringUtil;
 import com.intellij.pom.java.LanguageLevel;
 import com.intellij.psi.*;
 import com.intellij.psi.util.*;
-import com.intellij.xml.util.XmlUtil;
 import org.intellij.lang.annotations.Pattern;
 import org.jdom.Element;
 import org.jetbrains.annotations.NonNls;
@@ -407,7 +405,7 @@ public class UncheckedWarningLocalInspectionBase extends BaseJavaBatchLocalInspe
       if (psiElement instanceof PsiMethod) {
         final PsiMethod method = (PsiMethod)psiElement;
         final PsiType returnType = method.getReturnType();
-        if (returnType != null && returnType != PsiType.VOID) {
+        if (returnType != null && !PsiType.VOID.equals(returnType)) {
           final PsiExpression returnValue = statement.getReturnValue();
           if (returnValue != null) {
             final PsiType valueType = returnValue.getType();
index 29c0f5806a8c6478f2bc6aa533bde752f88e5a6d..50a5e91903d08a3c9228d19231450b4c4d1f2adc 100644 (file)
@@ -221,7 +221,7 @@ public class ParametersFolder {
           if (expression == null) break;
 
           final PsiType expressionType = ((PsiExpression)expression).getType();
-          if (expressionType != null && expressionType != PsiType.VOID && !(expression.getParent() instanceof PsiExpressionStatement)) {
+          if (expressionType != null && !PsiType.VOID.equals(expressionType) && !(expression.getParent() instanceof PsiExpressionStatement)) {
             if (dependsOnLocals(expression, inputVariables)) {
               break;
             }
index c9373869f9ea370c34106946db19333d6249de88..edde071f1ef4f81fb29d5a0f4825b01efa54db64 100644 (file)
@@ -123,7 +123,7 @@ public class FunctionalInterfaceSuggester {
             return null;
           }
           
-          if (returnType == PsiType.VOID && interfaceMethodReturnType != PsiType.VOID) {
+          if (PsiType.VOID.equals(returnType) && !PsiType.VOID.equals(interfaceMethodReturnType)) {
             return null;
           }
 
index 3c31a01506a0ac97e51dd5c2c2e1ed4cb58fe219..261b1998fa78d9912b8a7d973ab5b1bb19d5e7d3 100644 (file)
@@ -30,7 +30,7 @@ public class JavaRegExpModifierProvider implements RegExpModifierProvider {
   @Override
   public int getFlags(PsiElement elementInHost, PsiFile regexp) {
     final PsiExpressionList list = PsiTreeUtil.getParentOfType(elementInHost, PsiExpressionList.class);
-    if (list != null && list.getExpressions().length == 2 && list.getExpressionTypes()[1] == PsiType.INT) {
+    if (list != null && list.getExpressions().length == 2 && PsiType.INT.equals(list.getExpressionTypes()[1])) {
       final Object result = JavaConstantExpressionEvaluator.computeConstantExpression(list.getExpressions()[1], false);
       if (result instanceof Integer) {
         //noinspection MagicConstant
index dc12d45ad3fee0c3b92fe378a81346cb98bbc691..44cfd529b3355d04e9dd7f21ae97ef82fc41d64f 100644 (file)
@@ -757,7 +757,7 @@ public class JavaCompletionUtil {
     TailType toInsert = tailType;
     LookupItem<?> lookupItem = item.as(LookupItem.CLASS_CONDITION_KEY);
     if (lookupItem == null || lookupItem.getAttribute(LookupItem.TAIL_TYPE_ATTR) != TailType.UNKNOWN) {
-      if (!hasTail && item.getObject() instanceof PsiMethod && ((PsiMethod)item.getObject()).getReturnType() == PsiType.VOID) {
+      if (!hasTail && item.getObject() instanceof PsiMethod && PsiType.VOID.equals(((PsiMethod)item.getObject()).getReturnType())) {
         PsiDocumentManager.getInstance(context.getProject()).commitAllDocuments();
         if (psiElement().beforeLeaf(psiElement().withText(".")).accepts(context.getFile().findElementAt(context.getTailOffset() - 1))) {
           return false;
index 969dfdbcd6b75efcd75a35a533339ca3cfb72b14..e9d17e28612eaa60785531b9d6b89fe44568841c 100644 (file)
@@ -491,7 +491,7 @@ public class JavaKeywordCompletion {
   private static boolean mayExpectBoolean(CompletionParameters parameters) {
     for (ExpectedTypeInfo info : JavaSmartCompletionContributor.getExpectedTypes(parameters)) {
       PsiType type = info.getType();
-      if (type instanceof PsiClassType || type == PsiType.BOOLEAN) return true;
+      if (type instanceof PsiClassType || PsiType.BOOLEAN.equals(type)) return true;
     }
     return false;
   }
index 5908a230a32d82b9d5d3d5f1c1dd02061c8fea51..a763fb55b630b9741aa071586256f5b64ca4da4a 100644 (file)
@@ -325,7 +325,7 @@ public class JavaMemberNameCompletionContributor extends CompletionContributor {
       }
     }
 
-    if (!hasStartMatches(matcher, result) && PsiType.VOID != varType && includeOverlapped) {
+    if (!hasStartMatches(matcher, result) && !PsiType.VOID.equals(varType) && includeOverlapped) {
       // use suggested names as suffixes
       final String requiredSuffix = codeStyleManager.getSuffixByVariableKind(varKind);
       final String prefix = matcher.getPrefix();
index c9e8ae1f78db5993c90ba28929b43f14348a251a..98029f6bcd2a2165de80e6f199da6e85dde53897 100644 (file)
@@ -81,7 +81,7 @@ public class JavaMethodMergingContributor extends CompletionContributor {
 
   private static int getPriority(LookupElement element) {
     PsiMethod method = assertNotNull(getItemMethod(element));
-    return (method.getReturnType() == PsiType.VOID ? 0 : 1) +
+    return (PsiType.VOID.equals(method.getReturnType()) ? 0 : 1) +
            (method.getParameterList().getParametersCount() > 0 ? 2 : 0);
   }
 
index d181a34e635836f804e38851da349eb4106c70d3..85d45e784f15595d057376ae4e74b6511adf442b 100644 (file)
@@ -85,12 +85,6 @@ public class JavaSmartCompletionContributor extends CompletionContributor {
       return THROWABLES_FILTER;
     }
     
-    //throws list
-    PsiMethod method = PsiTreeUtil.getParentOfType(element, PsiMethod.class);
-    if (method != null && PsiTreeUtil.isAncestor(method.getThrowsList(), element, true)) {
-      return THROWABLES_FILTER;
-    }
-
     //new xxx.yyy
     if (psiElement().afterLeaf(psiElement().withText(".")).withSuperParent(2, psiElement(PsiNewExpression.class)).accepts(element)) {
       if (((PsiNewExpression)element.getParent().getParent()).getClassReference() == element.getParent()) {
@@ -107,6 +101,10 @@ public class JavaSmartCompletionContributor extends CompletionContributor {
     return null;
   }
 
+  private static boolean isInsideThrowsList(PsiElement element) {
+    PsiMethod method = PsiTreeUtil.getParentOfType(element, PsiMethod.class);
+    return method != null && PsiTreeUtil.isAncestor(method.getThrowsList(), element, true);
+  }
 
 
   public JavaSmartCompletionContributor() {
@@ -128,11 +126,18 @@ public class JavaSmartCompletionContributor extends CompletionContributor {
           PsiTreeUtil.findElementOfClassAtOffset(element.getContainingFile(), parameters.getOffset(), PsiJavaCodeReferenceElement.class, false);
         if (reference != null) {
           ElementFilter filter = getClassReferenceFilter(element);
+          boolean completeConstructor = filter != null;
+          if (filter == null && isInsideThrowsList(element)) {
+            filter = THROWABLES_FILTER;
+          }
           if (filter != null) {
             final List<ExpectedTypeInfo> infos = Arrays.asList(getExpectedTypes(parameters));
-            for (final LookupElement item : completeReference(element, reference, filter, true, false, parameters, result.getPrefixMatcher())) {
+            for (LookupElement item : completeReference(element, reference, filter, true, false, parameters, result.getPrefixMatcher())) {
               if (item.getObject() instanceof PsiClass) {
-                result.addElement(decorate(LookupElementDecorator.withInsertHandler(item, ConstructorInsertHandler.SMART_INSTANCE), infos));
+                if (completeConstructor) {
+                  item = LookupElementDecorator.withInsertHandler(item, ConstructorInsertHandler.SMART_INSTANCE);
+                }
+                result.addElement(decorate(item, infos));
               }
             }
           }
index 5ac5057d8113ae1e30773acd70dc72e3fa15025c..31de612c9ad34d9760dedd1a5bc8f591674d5571 100644 (file)
@@ -74,7 +74,7 @@ class SmartCastProvider extends CompletionProvider<CompletionParameters> {
         type = ((PsiWildcardType)type).getBound();
       }
 
-      if (type == null || type == PsiType.VOID) {
+      if (type == null || PsiType.VOID.equals(type)) {
         continue;
       }
 
index fdec4a6b1910c6888261fc4ff43ed0c0f95f3653..a4b4a0965b364d4c0f8289a4987d5975dd09dfad 100644 (file)
@@ -145,7 +145,7 @@ public class DelegateWithDefaultParamValueIntentionAction extends PsiElementBase
         final String methodCall;
         if (method.getReturnType() == null) {
           methodCall = "this";
-        } else if (method.getReturnType() != PsiType.VOID) {
+        } else if (!PsiType.VOID.equals(method.getReturnType())) {
           methodCall = "return " + method.getName();
         } else {
           methodCall = method.getName();
index eb68dd4979f70618b01c8641c5ba0e86bfa05329..cf236a6e35033e8ec402188e6c02d3ac9d60e50c 100644 (file)
@@ -55,7 +55,7 @@ public class MissingReturnExpressionFixer implements Fixer {
     PsiElement parent = PsiTreeUtil.getParentOfType(psiElement, PsiClassInitializer.class, PsiMethod.class);
     if (parent instanceof PsiMethod) {
       final PsiType returnType = ((PsiMethod)parent).getReturnType();
-      if (returnType != null && returnType != PsiType.VOID) {
+      if (returnType != null && !PsiType.VOID.equals(returnType)) {
         final int startOffset = retStatement.getTextRange().getStartOffset();
         if (returnValue != null) {
           editor.getDocument().insertString(startOffset + "return".length(), ";");
@@ -84,7 +84,7 @@ public class MissingReturnExpressionFixer implements Fixer {
     if (!(prev instanceof PsiJavaToken)) {
       int offset = returnStatement.getTextRange().getEndOffset();
       final PsiMethod method = PsiTreeUtil.getParentOfType(returnStatement, PsiMethod.class, true, PsiLambdaExpression.class);
-      if (method != null && method.getReturnType() == PsiType.VOID) {
+      if (method != null && PsiType.VOID.equals(method.getReturnType())) {
         offset = returnStatement.getTextRange().getStartOffset() + "return".length();
       } 
       editor.getDocument().insertString(offset, ";");
@@ -101,7 +101,7 @@ public class MissingReturnExpressionFixer implements Fixer {
     editor.getDocument().insertString(offset, ";");
     if (prevToken.getTokenType() == JavaTokenType.RETURN_KEYWORD) {
       final PsiMethod method = PsiTreeUtil.getParentOfType(returnStatement, PsiMethod.class);
-      if (method != null && method.getReturnType() != PsiType.VOID) {
+      if (method != null && !PsiType.VOID.equals(method.getReturnType())) {
         editor.getCaretModel().moveToOffset(offset);
         processor.setSkipEnter(true);
       }
index 9ec8d1a32f8472ec25f86b90ab32fad97d6f1061..ce293e217f74b107eb770ab6af943ef59d2e1ace 100644 (file)
@@ -115,7 +115,7 @@ public class GenerateDelegateHandler implements LanguageCodeInsightActionHandler
 
     PsiModifierList modifierList = null;
 
-    if (method.getReturnType() != PsiType.VOID) {
+    if (!PsiType.VOID.equals(method.getReturnType())) {
       call.append("return ");
     }
 
index 291003c3f4602539ff4ea078f9f6921a370e89b5..7756b072505511442a2ebdcff9afd1a05a07ca85 100644 (file)
@@ -337,7 +337,7 @@ public class OverrideImplementUtil extends OverrideImplementExploreUtil {
   @NotNull
   public static String callSuper(PsiMethod superMethod, PsiMethod overriding) {
     @NonNls StringBuilder buffer = new StringBuilder();
-    if (!superMethod.isConstructor() && superMethod.getReturnType() != PsiType.VOID) {
+    if (!superMethod.isConstructor() && !PsiType.VOID.equals(superMethod.getReturnType())) {
       buffer.append("return ");
     }
     buffer.append("super");
index 2324cb2b6838cd2f054d0417bdfc02e72be618f6..e45643fa52fbd9d63486191eaddb5d285080f897 100644 (file)
@@ -54,7 +54,7 @@ public class IntroduceVariableIntentionAction extends BaseRefactoringIntentionAc
 
     final PsiExpression expression = statement.getExpression();
 
-    return expression.getType() != PsiType.VOID && !(expression instanceof PsiAssignmentExpression);
+    return !PsiType.VOID.equals(expression.getType()) && !(expression instanceof PsiAssignmentExpression);
   }
 
   @Override
index 9d526d3d1aa2021642e64c95cd00aa0b28bb3c16..dbfba1464c4cb0c6ad6e48238d75204ca200cd54 100644 (file)
@@ -406,7 +406,7 @@ public class JavaDocumentationProvider extends DocumentationProviderEx implement
       if (typeParameterList != null) {
         createTypeParamsListComment(builder, project, commenter, typeParameterList);
       }
-      if (psiMethod.getReturnType() != null && psiMethod.getReturnType() != PsiType.VOID) {
+      if (psiMethod.getReturnType() != null && !PsiType.VOID.equals(psiMethod.getReturnType())) {
         builder.append(CodeDocumentationUtil.createDocCommentLine(RETURN_TAG, project, commenter));
         builder.append(LINE_SEPARATOR);
       }
index 3cf8da2f8fb10d435b69f61a6b90b13f23bcb516..0797d6797949c5f5b39f0d1fc6f93c27b82751f6 100644 (file)
@@ -41,6 +41,7 @@ import com.intellij.refactoring.util.*;
 import com.intellij.refactoring.util.usageInfo.DefaultConstructorImplicitUsageInfo;
 import com.intellij.refactoring.util.usageInfo.NoConstructorClassUsageInfo;
 import com.intellij.usageView.UsageInfo;
+import com.intellij.util.ArrayUtil;
 import com.intellij.util.IncorrectOperationException;
 import com.intellij.util.VisibilityUtil;
 import com.intellij.util.containers.ContainerUtil;
@@ -857,13 +858,13 @@ public class JavaChangeSignatureUsageProcessor implements ChangeSignatureUsagePr
       public boolean value(Pair<PsiParameter, String> pair) {
         final PsiParameter parameter = pair.first;
         final String oldParamName = pair.second;
-        final int idx = Arrays.binarySearch(oldParameterNames, oldParamName);
+        final int idx = ArrayUtil.find(oldParameterNames, oldParamName);
         return idx >= 0 && idx == method.getParameterList().getParameterIndex(parameter) && changeInfo.getNewParameters()[idx].getOldIndex() == idx;
       }
     }, new Condition<String>() {
       @Override
       public boolean value(String paramName) {
-        return Arrays.binarySearch(oldParameterNames, paramName) >= 0;
+        return ArrayUtil.find(oldParameterNames, paramName) >= 0;
       }
     });
   }
index 23b0a7bfef6990b4d86fe782e747be9e4c1ba8bb..570d4d57f5639d3dc13881fb9c4eb231dab211c5 100644 (file)
@@ -267,10 +267,10 @@ public class ExtractMethodProcessor implements MatchProvider {
     if (expressionType == null) {
       expressionType = PsiType.VOID;
     }
-    myHasExpressionOutput = expressionType != PsiType.VOID;
+    myHasExpressionOutput = !PsiType.VOID.equals(expressionType);
 
     final PsiType returnStatementType = getExpectedReturnType();
-    myHasReturnStatementOutput = myHasReturnStatement && returnStatementType != null && returnStatementType != PsiType.VOID;
+    myHasReturnStatementOutput = myHasReturnStatement && returnStatementType != null && !PsiType.VOID.equals(returnStatementType);
 
     if (myGenerateConditionalExit && myOutputVariables.length == 1) {
       if (!(myOutputVariables[0].getType() instanceof PsiPrimitiveType)) {
@@ -381,7 +381,7 @@ public class ExtractMethodProcessor implements MatchProvider {
 
   private boolean areAllExitPointsAreNotNull(PsiType returnStatementType) {
     if (insertNotNullCheckIfPossible() && myControlFlowWrapper.getOutputVariables(false).length == 0) {
-      boolean isNotNull = returnStatementType != null && returnStatementType != PsiType.VOID;
+      boolean isNotNull = returnStatementType != null && !PsiType.VOID.equals(returnStatementType);
       for (PsiStatement statement : myExitStatements) {
         if (statement instanceof PsiReturnStatement) {
           final PsiExpression returnValue = ((PsiReturnStatement)statement).getReturnValue();
@@ -432,7 +432,7 @@ public class ExtractMethodProcessor implements MatchProvider {
       return;
     }
     final PsiMethod method = (PsiMethod)myCodeFragmentMember;
-    if (!method.isConstructor() || myReturnType != PsiType.VOID) {
+    if (!method.isConstructor() || !PsiType.VOID.equals(myReturnType)) {
       return;
     }
     final PsiCodeBlock body = method.getBody();
index f7686c8ad02166540132e6d672b9a7f3a8091360..18beeac7a6585fd50759de66b2b5e653548152d9 100644 (file)
@@ -277,7 +277,7 @@ public class ExtractLightMethodObjectHandler {
   private static boolean isValidVariableType(PsiType type) {
     if (type instanceof PsiClassType ||
         type instanceof PsiArrayType ||
-        type instanceof PsiPrimitiveType && type != PsiType.VOID) {
+        type instanceof PsiPrimitiveType && !PsiType.VOID.equals(type)) {
       return true;
     }
     return false;
index c3d9cffb863892cde4a74d9b7ab650d1d552eb54..22c8fd78f9dbfc07ed34110bd7db1871e28694ca 100644 (file)
@@ -549,7 +549,7 @@ public class InheritanceToDelegationProcessor extends BaseRefactoringProcessor {
     @NonNls final StringBuffer buffer = new StringBuffer();
     buffer.append("{\n");
 
-    if (methodToAdd.getReturnType() != PsiType.VOID) {
+    if (!PsiType.VOID.equals(methodToAdd.getReturnType())) {
       buffer.append("return ");
     }
 
index ba9a4918a330b7791e40b26723c2445034707eca..b2c82e29a2bbae92e0f86f5ca214e57053115b77 100644 (file)
@@ -747,7 +747,7 @@ public class InlineMethodProcessor extends BaseRefactoringProcessor {
     PsiType returnType = callSubstitutor.substitute(myMethod.getReturnType());
     String resultName = null;
     final int applicabilityLevel = PsiUtil.getApplicabilityLevel(myMethod, callSubstitutor, argumentList);
-    if (returnType != null && returnType != PsiType.VOID && tailCallType == InlineUtil.TailCallType.None) {
+    if (returnType != null && !PsiType.VOID.equals(returnType) && tailCallType == InlineUtil.TailCallType.None) {
       resultName = myJavaCodeStyle.propertyNameToVariableName("result", VariableKind.LOCAL_VARIABLE);
       resultName = myJavaCodeStyle.suggestUniqueVariableName(resultName, block.getFirstChild(), true);
       PsiDeclarationStatement declaration = myFactory.createVariableDeclarationStatement(resultName, returnType, null);
index b46589f451d651a15f51107e693a5722f871ba4f..e401a679f87d093bffe50da448be0da372469058 100644 (file)
@@ -236,7 +236,7 @@ public abstract class IntroduceVariableBase extends IntroduceHandlerBase {
     PsiExpression expression = PsiTreeUtil.getParentOfType(elementAtCaret, PsiExpression.class);
     while (expression != null) {
       if (!expressions.contains(expression) && !(expression instanceof PsiParenthesizedExpression) && !(expression instanceof PsiSuperExpression) &&
-          (acceptVoid || expression.getType() != PsiType.VOID)) {
+          (acceptVoid || !PsiType.VOID.equals(expression.getType()))) {
         if (expression instanceof PsiMethodReferenceExpression) {
           expressions.add(expression);
         }
index 59dbd1ab271f43059871fa480e05c0d02c746ced..742f955d6dbfcbfbad534b954e9556a53302a70c 100644 (file)
@@ -179,14 +179,15 @@ public class MoveJavaMemberHandler implements MoveMemberHandler {
           changeQualifier(refExpr, usage.qualifierClass, usage.member);
         }
         else {
-          final PsiReferenceParameterList parameterList = refExpr.getParameterList();
-          if (parameterList != null && parameterList.getTypeArguments().length == 0 && !(refExpr instanceof PsiMethodReferenceExpression)){
-            refExpr.setQualifierExpression(null);
-          } else {
-            final Project project = element.getProject();
-            final PsiClass targetClass =
-              JavaPsiFacade.getInstance(project).findClass(options.getTargetClassName(), GlobalSearchScope.projectScope(project));
-            if (targetClass != null) {
+          final Project project = element.getProject();
+          final PsiClass targetClass =
+            JavaPsiFacade.getInstance(project).findClass(options.getTargetClassName(), GlobalSearchScope.projectScope(project));
+          if (targetClass != null) {
+            final PsiReferenceParameterList parameterList = refExpr.getParameterList();
+            if ((targetClass.isEnum() || PsiTreeUtil.isAncestor(targetClass, element, true)) && parameterList != null && parameterList.getTypeArguments().length == 0 && !(refExpr instanceof PsiMethodReferenceExpression)) {
+              refExpr.setQualifierExpression(null);
+            }
+            else {
               changeQualifier(refExpr, targetClass, usage.member);
             }
           }
index 026fa135fdb36a0245ed4bd85d28c1930b60fe8f..741bf6dd82aacdcbd68998a076f47c9bed79f4fc 100644 (file)
@@ -38,7 +38,7 @@ public class WrapReturnValueAction extends BaseRefactoringAction{
     final PsiMethod psiMethod = PsiTreeUtil.getParentOfType(element, PsiMethod.class, false);
     if (psiMethod != null && !(psiMethod instanceof PsiCompiledElement)) {
       final PsiType returnType = psiMethod.getReturnType();
-      return returnType != null && returnType != PsiType.VOID;
+      return returnType != null && !PsiType.VOID.equals(returnType);
     }
     return false;
   }
index 0dc68c326dacdd5dcb2eabb9d061cef5223f9e39..a0cc2fa7fea50267abd80502a8db4ff6ce291349 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2013 JetBrains s.r.o.
+ * Copyright 2000-2015 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.
@@ -21,6 +21,7 @@ import com.intellij.psi.*;
 import com.intellij.psi.util.PsiFormatUtil;
 import com.intellij.psi.util.PsiFormatUtilBase;
 import com.intellij.psi.util.PsiTreeUtil;
+import com.intellij.ui.JBColor;
 import com.intellij.ui.SimpleTextAttributes;
 import com.intellij.usages.TextChunk;
 import com.intellij.util.FontUtil;
@@ -56,7 +57,7 @@ public class SliceUsageCellRenderer extends SliceUsageCellRendererBase {
       TextChunk textChunk = text[i];
       SimpleTextAttributes attributes = textChunk.getSimpleAttributesIgnoreBackground();
       if (isForcedLeaf) {
-        attributes = attributes.derive(attributes.getStyle(), Color.LIGHT_GRAY, attributes.getBgColor(), attributes.getWaveColor());
+        attributes = attributes.derive(attributes.getStyle(), JBColor.LIGHT_GRAY, attributes.getBgColor(), attributes.getWaveColor());
       }
       boolean inUsage = (attributes.getFontStyle() & Font.BOLD) != 0;
       if (isInsideContainer && inUsage) {
@@ -66,7 +67,7 @@ public class SliceUsageCellRenderer extends SliceUsageCellRendererBase {
         //setPaintFocusBorder(true);
       }
       append(textChunk.getText(), attributes);
-      if(i == 0){
+      if (i == 0) {
         append(FontUtil.spaceAndThinSpace());
       }
     }
index d27e56a370a2a2bacd4301f4e2c53f4144c6add2..c602395895c2cb4f16ed053f919c91bd469ed431 100644 (file)
@@ -132,7 +132,7 @@ public class LambdaUtil {
 
   public static boolean isLambdaFullyInferred(PsiLambdaExpression expression, PsiType functionalInterfaceType) {
     final boolean hasParams = expression.getParameterList().getParametersCount() > 0;
-    if (hasParams || getFunctionalInterfaceReturnType(functionalInterfaceType) != PsiType.VOID) {   //todo check that void lambdas without params check
+    if (hasParams || !PsiType.VOID.equals(getFunctionalInterfaceReturnType(functionalInterfaceType))) {   //todo check that void lambdas without params check
       
       return !dependsOnTypeParams(functionalInterfaceType, functionalInterfaceType, expression);
     }
@@ -570,7 +570,7 @@ public class LambdaUtil {
   }
 
   public static String checkReturnTypeCompatible(PsiLambdaExpression lambdaExpression, PsiType functionalInterfaceReturnType) {
-    if (functionalInterfaceReturnType == PsiType.VOID) {
+    if (PsiType.VOID.equals(functionalInterfaceReturnType)) {
       final PsiElement body = lambdaExpression.getBody();
       if (body instanceof PsiCodeBlock) {
         if (!getReturnExpressions(lambdaExpression).isEmpty()) return "Unexpected return value";
index f590c38392d607c6380301adeb71b7efd396f6c5..3eec614acb26b074bc0110b8fbb119a032c59df3 100644 (file)
@@ -32,7 +32,7 @@ import java.util.*;
 public class PsiIntersectionType extends PsiType.Stub {
   private final PsiType[] myConjuncts;
 
-  private PsiIntersectionType(@NotNull PsiType[] conjuncts) {
+  protected PsiIntersectionType(@NotNull PsiType[] conjuncts) {
     super(PsiAnnotation.EMPTY_ARRAY);
     myConjuncts = conjuncts;
   }
@@ -67,7 +67,7 @@ public class PsiIntersectionType extends PsiType.Stub {
     }
   }
 
-  private static Set<PsiType> flatten(PsiType[] conjuncts, Set<PsiType> types) {
+  protected static Set<PsiType> flatten(PsiType[] conjuncts, Set<PsiType> types) {
     for (PsiType conjunct : conjuncts) {
       if (conjunct instanceof PsiIntersectionType) {
         PsiIntersectionType type = (PsiIntersectionType)conjunct;
index 6736b8581a224ca13a0ec2f3ba7f7ef12ae09849..7b73a88392596b6c32810a0447acf266e2184a08 100644 (file)
@@ -321,7 +321,7 @@ public class PsiMethodReferenceUtil {
         returnType = ((PsiMethod)resolve).getReturnType();
       }
       PsiType methodReturnType = subst.substitute(returnType);
-      if (interfaceReturnType != null && interfaceReturnType != PsiType.VOID) {
+      if (interfaceReturnType != null && !PsiType.VOID.equals(interfaceReturnType)) {
         if (methodReturnType == null) {
           methodReturnType = JavaPsiFacade.getElementFactory(expression.getProject()).createType(containingClass, subst);
         }
index 70c97495995bb9af9d5c79a197c4c4c829087d40..1704fea347fdc6b269fd68db9a8717b48ef837b1 100644 (file)
@@ -66,7 +66,7 @@ public class PsiConcatenationUtil {
             addFormatParameter(subExpression, formatString, formatParameters, printfFormat);
           }
           if (stringStarted) {
-            if (optype != null && (optype.equalsToText(JAVA_LANG_STRING) || optype == PsiType.CHAR)) {
+            if (optype != null && (optype.equalsToText(JAVA_LANG_STRING) || PsiType.CHAR.equals(optype))) {
               buildFormatString(op, formatString, formatParameters, printfFormat);
             }
             else {
index a92ed0542b2c045a34cfd3fa8798716cf5928fa1..7a4d333b15f5135f3f1f7991eccbb82593144f88 100644 (file)
  */
 package com.intellij.psi.util;
 
-import com.intellij.openapi.util.Condition;
+import com.intellij.codeInsight.runner.JavaMainMethodProvider;
 import com.intellij.openapi.extensions.Extensions;
+import com.intellij.openapi.util.Condition;
 import com.intellij.psi.*;
-import com.intellij.codeInsight.runner.JavaMainMethodProvider;
 import org.jetbrains.annotations.Nullable;
 
 /**
@@ -59,7 +59,7 @@ public class PsiMethodUtil {
 
   public static boolean isMainMethod(final PsiMethod method) {
     if (method == null || method.getContainingClass() == null) return false;
-    if (PsiType.VOID != method.getReturnType()) return false;
+    if (!PsiType.VOID.equals(method.getReturnType())) return false;
     if (!method.hasModifierProperty(PsiModifier.STATIC)) return false;
     if (!method.hasModifierProperty(PsiModifier.PUBLIC)) return false;
     final PsiParameter[] parameters = method.getParameterList().getParameters();
index e6781ce9ed505ae4a70435f8a5308a509e87fd86..4c70eeffdf63c7e9e1189a40c64c7e5401d92df3 100644 (file)
@@ -658,7 +658,16 @@ public class PsiImplUtil {
            findApplicableTarget((PsiAnnotation)element, TargetType.TYPE_USE) == TargetType.TYPE_USE;
   }
 
-  @Nullable
+  public static void collectTypeUseAnnotations(@NotNull PsiModifierList modifierList, @NotNull List<PsiAnnotation> annotations) {
+    for (PsiAnnotation annotation : modifierList.getAnnotations()) {
+      if (isTypeAnnotation(annotation)) {
+        annotations.add(annotation);
+      }
+    }
+  }
+
+  /** @deprecated use {@link #collectTypeUseAnnotations(PsiModifierList, List)} (to be removed in IDEA 16) */
+  @SuppressWarnings("unused")
   public static List<PsiAnnotation> getTypeUseAnnotations(@NotNull PsiModifierList modifierList) {
     SmartList<PsiAnnotation> result = null;
 
index 7b8c2632dd70d9c366bbf160fc15561d9845b208..29305d4d75e63cda3f3caec7a0ed437a27b48c4b 100644 (file)
@@ -592,10 +592,7 @@ public class PsiJavaCodeReferenceElementImpl extends CompositePsiElement impleme
     if (!isQualified()) {
       PsiModifierList modifierList = PsiImplUtil.findNeighbourModifierList(this);
       if (modifierList != null) {
-        List<PsiAnnotation> typeAnnotations = PsiImplUtil.getTypeUseAnnotations(modifierList);
-        if (typeAnnotations != null && !typeAnnotations.isEmpty()) {
-          annotations.addAll(typeAnnotations);
-        }
+        PsiImplUtil.collectTypeUseAnnotations(modifierList, annotations);
       }
     }
 
index fae8063dbe7ef2555508f14c5714aec16f1aacd2..8df615aa7c914d0c17bd6982cbca8c7d5517b51a 100644 (file)
@@ -37,6 +37,8 @@ import org.jetbrains.annotations.Nullable;
 import java.util.List;
 
 public class PsiTypeElementImpl extends CompositePsiElement implements PsiTypeElement {
+  private static final Class[] INTERMEDIATES = {PsiComment.class, PsiWhiteSpace.class, PsiAnnotation.class, PsiTypeParameterList.class};
+
   @SuppressWarnings({"UnusedDeclaration"})
   public PsiTypeElementImpl() {
     this(JavaElementType.TYPE);
@@ -69,7 +71,7 @@ public class PsiTypeElementImpl extends CompositePsiElement implements PsiTypeEl
   }
 
   private PsiType calculateType() {
-    final PsiType inferredType = PsiAugmentProvider.getInferredType(this);
+    PsiType inferredType = PsiAugmentProvider.getInferredType(this);
     if (inferredType != null) {
       return inferredType;
     }
@@ -153,16 +155,13 @@ public class PsiTypeElementImpl extends CompositePsiElement implements PsiTypeEl
     return type == null ? PsiType.NULL : type;
   }
 
-  private void addTypeUseAnnotations(List<PsiAnnotation> list) {
+  private void addTypeUseAnnotations(List<PsiAnnotation> annotations) {
     PsiElement parent = this;
     while (parent instanceof PsiTypeElement) {
-      PsiElement left = PsiTreeUtil.skipSiblingsBackward(parent, PsiComment.class, PsiWhiteSpace.class, PsiAnnotation.class);
+      PsiElement left = PsiTreeUtil.skipSiblingsBackward(parent, INTERMEDIATES);
 
       if (left instanceof PsiModifierList) {
-        List<PsiAnnotation> annotations = PsiImplUtil.getTypeUseAnnotations((PsiModifierList)left);
-        if (annotations != null && !annotations.isEmpty()) {
-          list.addAll(annotations);
-        }
+        PsiImplUtil.collectTypeUseAnnotations((PsiModifierList)left, annotations);
         break;
       }
 
index 6b499e1bfdd5975b8b72469a1cd31f95fcc8560d..f131c759a00886186344a1a6ccbcffae4e60704a 100644 (file)
@@ -75,7 +75,7 @@ public class ReplaceExpressionUtil {
     }
     else if (i == JavaElementType.ARRAY_ACCESS_EXPRESSION) {
       int role = ((CompositeElement)oldParent).getChildRole(oldExpr);
-      return role != ChildRole.ARRAY_DIMENSION && priority < parentPriority;
+      return role != ChildRole.ARRAY_DIMENSION && role != ChildRole.INDEX && priority < parentPriority;
     }
     else if (i == JavaElementType.ARRAY_INITIALIZER_EXPRESSION) {
       return false;
diff --git a/java/java-tests/testData/codeInsight/completion/smartType/MethodThrows-out.java b/java/java-tests/testData/codeInsight/completion/smartType/MethodThrows-out.java
new file mode 100644 (file)
index 0000000..752a63d
--- /dev/null
@@ -0,0 +1,10 @@
+class FirstException extends Exception {}
+class SecondException extends Exception {}
+
+interface I {
+  void method() throws FirstException, SecondException;
+}
+
+class C implements I {
+  void method() throws FirstException, SecondException<caret>;
+}
\ No newline at end of file
diff --git a/java/java-tests/testData/codeInsight/completion/smartType/MethodThrows.java b/java/java-tests/testData/codeInsight/completion/smartType/MethodThrows.java
new file mode 100644 (file)
index 0000000..d533295
--- /dev/null
@@ -0,0 +1,10 @@
+class FirstException extends Exception {}
+class SecondException extends Exception {}
+
+interface I {
+  void method() throws FirstException, SecondException;
+}
+
+class C implements I {
+  void method() throws FirstException, Sec<caret>;
+}
\ No newline at end of file
diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/newMethodRef/IDEA147511.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/newMethodRef/IDEA147511.java
new file mode 100644 (file)
index 0000000..a5f2025
--- /dev/null
@@ -0,0 +1,47 @@
+
+import java.util.Comparator;
+import java.util.Optional;
+import java.util.function.BinaryOperator;
+import java.util.function.Consumer;
+import java.util.stream.Stream;
+
+class Bug {
+
+  public static void main(String[] args) {
+    Stream<String> tokenStream = Stream.of("hello", "world");
+
+    Comparator<String> order = Comparator.naturalOrder();
+    Min<String> min = tokenStream.collect(
+      () -> new Min<>(order),
+      Min::accept,
+      Min::combine);
+
+    System.out.printf("Min = %s%n",
+                      min.asOptional().orElse(null));
+  }
+
+  static class Min<T> implements Consumer<T> {
+
+    private final BinaryOperator<T> minOf;
+    private T min;
+
+    public Min(Comparator<? super T> order) {
+      this.minOf = BinaryOperator.minBy(order);
+    }
+
+    @Override
+    public void accept(T t) {
+      this.min = min != null ? minOf.apply(min, t) : t;
+    }
+
+    public void combine(Min<T> other) {
+      if (other.min != null) {
+        accept(other.min);
+      }
+    }
+
+    public Optional<T> asOptional() {
+      return Optional.ofNullable(min);
+    }
+  }
+}
diff --git a/java/java-tests/testData/inspection/nullableProblems/NotNullByDefaultFieldNotInitialized.java b/java/java-tests/testData/inspection/nullableProblems/NotNullByDefaultFieldNotInitialized.java
new file mode 100644 (file)
index 0000000..0742736
--- /dev/null
@@ -0,0 +1,15 @@
+import javax.annotation.*;
+
+@NonnullByDefault
+class Test {
+  Object <warning descr="@NonnullByDefault fields must be initialized">member</warning>;
+
+  private void accessMember() {
+    member = new Object();
+  }
+}
+
+
+@Nonnull
+@javax.annotation.meta.TypeQualifierDefault(java.lang.annotation.ElementType.FIELD)
+@interface NonnullByDefault {}
\ No newline at end of file
diff --git a/java/java-tests/testData/refactoring/changeSignature/JavadocOfDeleted.java b/java/java-tests/testData/refactoring/changeSignature/JavadocOfDeleted.java
new file mode 100644 (file)
index 0000000..123c9b0
--- /dev/null
@@ -0,0 +1,30 @@
+/*
+ * Copyright 2000-2011 JetBrains s.r.o.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+class C {
+    /**
+     * This is the role -
+     * @param role another desc
+     * @param labelExpression blah-blah
+     * @return return description
+     */
+    public Integer ex<caret>ample(int role, String labelExpression) {
+        switch (role) {
+            case Constants.FOO:
+                break;
+        }
+        return 1;
+    }
+}
\ No newline at end of file
diff --git a/java/java-tests/testData/refactoring/changeSignature/JavadocOfDeleted_after.java b/java/java-tests/testData/refactoring/changeSignature/JavadocOfDeleted_after.java
new file mode 100644 (file)
index 0000000..af54692
--- /dev/null
@@ -0,0 +1,29 @@
+/*
+ * Copyright 2000-2011 JetBrains s.r.o.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+class C {
+    /**
+     * This is the role -
+     * @param role another desc
+     * @return return description
+     */
+    public Integer example(int role) {
+        switch (role) {
+            case Constants.FOO:
+                break;
+        }
+        return 1;
+    }
+}
\ No newline at end of file
diff --git a/java/java-tests/testData/refactoring/inlineLocal/ArrayAccessPriority.java b/java/java-tests/testData/refactoring/inlineLocal/ArrayAccessPriority.java
new file mode 100644 (file)
index 0000000..adea1fa
--- /dev/null
@@ -0,0 +1,6 @@
+class C {
+  void f(int[] a, int i) {
+    int i1 = i + 1;
+    int temp = a[i<caret>1];
+  }
+}
\ No newline at end of file
diff --git a/java/java-tests/testData/refactoring/inlineLocal/ArrayAccessPriority.java.after b/java/java-tests/testData/refactoring/inlineLocal/ArrayAccessPriority.java.after
new file mode 100644 (file)
index 0000000..bf9e8dc
--- /dev/null
@@ -0,0 +1,5 @@
+class C {
+  void f(int[] a, int i) {
+      int temp = a[i + 1];
+  }
+}
\ No newline at end of file
diff --git a/java/java-tests/testData/refactoring/moveMembers/stringConstantInSwitchLabelExpression/after/A.java b/java/java-tests/testData/refactoring/moveMembers/stringConstantInSwitchLabelExpression/after/A.java
new file mode 100644 (file)
index 0000000..8a58812
--- /dev/null
@@ -0,0 +1,2 @@
+public interface A {
+}
\ No newline at end of file
diff --git a/java/java-tests/testData/refactoring/moveMembers/stringConstantInSwitchLabelExpression/after/B.java b/java/java-tests/testData/refactoring/moveMembers/stringConstantInSwitchLabelExpression/after/B.java
new file mode 100644 (file)
index 0000000..cc08541
--- /dev/null
@@ -0,0 +1,13 @@
+public class B {
+
+    public static final String FOO = "FOO";
+}
+
+class U {
+  public void example(String foo) {
+    switch (foo) {
+      case B.FOO:
+        break;
+    }
+  }
+}
\ No newline at end of file
diff --git a/java/java-tests/testData/refactoring/moveMembers/stringConstantInSwitchLabelExpression/before/A.java b/java/java-tests/testData/refactoring/moveMembers/stringConstantInSwitchLabelExpression/before/A.java
new file mode 100644 (file)
index 0000000..0451878
--- /dev/null
@@ -0,0 +1,3 @@
+public interface A {
+  public static final String FOO = "FOO";
+}
\ No newline at end of file
diff --git a/java/java-tests/testData/refactoring/moveMembers/stringConstantInSwitchLabelExpression/before/B.java b/java/java-tests/testData/refactoring/moveMembers/stringConstantInSwitchLabelExpression/before/B.java
new file mode 100644 (file)
index 0000000..309cd8c
--- /dev/null
@@ -0,0 +1,12 @@
+public class B {
+  
+}
+
+class U {
+  public void example(String foo) {
+    switch (foo) {
+      case A.FOO:
+        break;
+    }
+  }
+}
\ No newline at end of file
index e45a9866d2c9c96de39d3553f831e6fe15ccb7b1..a48109935ecfb1bc8d4fdad759dceca14c164cd5 100644 (file)
@@ -428,6 +428,8 @@ public class SmartTypeCompletionTest extends LightFixtureCompletionTestCase {
 
   public void testJavadocThrows() throws Throwable { doTest(); }
 
+  public void testMethodThrows() throws Throwable { doTest(); }
+
   public void testDoNotExcludeAssignedVariable() throws Throwable { doTest(); }
 
   public void testArrayIndexTailType() throws Throwable { doTest(); }
index b6a1729c48451549a6d2340c96e0d6b8ec92d98a..d17ee3c2731eaa08f50fce455f631e8d759823f1 100644 (file)
@@ -80,6 +80,7 @@ public class InferredTypeTest extends LightCodeInsightFixtureTestCase {
     final PsiJavaFile file = (PsiJavaFile)myFixture.addFileToProject("R.java", "public interface R {@D void run();}");
     final PsiClass psiClass = file.getClasses()[0];
     final PsiMethod method = psiClass.getMethods()[0];
+    //noinspection UsePrimitiveTypes
     assertFalse(PsiType.VOID == method.getReturnType());
     myFixture.configureByText("a.java", "class A {{R r = () -> {};}} ");
     myFixture.checkHighlighting(false, false, false);
index b24d597f2c28fe608516e2abf9cf7b5f0847b3cd..26d02b495ac3824b243bc633ae9e050e3541f737 100644 (file)
@@ -446,6 +446,10 @@ public class NewMethodRefHighlightingTest extends LightDaemonAnalyzerTestCase {
     doTest();
   }
 
+  public void testIDEA147511() throws Exception {
+    doTest();
+  }
+
   private void doTest() {
     doTest(false);
   }
index 98d1661678045c5469527c7d5456244a2e556d01..bb2e2ba20a0b2b00d7feebae02f86b6ab266e52c 100644 (file)
@@ -40,8 +40,8 @@ class AnnotatedTypeTest extends LightCodeInsightFixtureTestCase {
         class I { }
       }
 
-      class E1 extends Exception { }
-      class E2 extends Exception { }""".stripIndent())
+      @SuppressWarnings("ExceptionClassNameDoesntEndWithException") class E1 extends Exception { }
+      @SuppressWarnings("ExceptionClassNameDoesntEndWithException") class E2 extends Exception { }""".stripIndent())
   }
 
   public void testPrimitiveArrayType() {
@@ -78,20 +78,32 @@ class AnnotatedTypeTest extends LightCodeInsightFixtureTestCase {
 
   public void testDisjunctionType() {
     def psi = factory.createStatementFromText("try { } catch (@A @TA(1) E1 | @TA(2) E2 e) { }", context) as PsiTryStatement
-    assertTypeText(psi.catchBlockParameters[0].type, "pkg.@pkg.TA(1) E1 | pkg.@pkg.TA(2) E2", "pkg.E1 | pkg.E2")
+    assertTypeText psi.catchBlockParameters[0].type, "pkg.@pkg.TA(1) E1 | pkg.@pkg.TA(2) E2", "pkg.E1 | pkg.E2"
   }
 
   public void testDiamondType() {
     def psi = factory.createStatementFromText("Class<@TA String> cs = new Class<>()", context) as PsiDeclarationStatement
     def var = psi.declaredElements[0] as PsiVariable
-    assertTypeText(var.initializer.type, "java.lang.Class<java.lang.@pkg.TA String>", "java.lang.Class<java.lang.String>")
+    assertTypeText var.initializer.type, "java.lang.Class<java.lang.@pkg.TA String>", "java.lang.Class<java.lang.String>"
   }
 
   public void testImmediateClassType() {
     def aClass = myFixture.javaFacade.findClass(CommonClassNames.JAVA_LANG_OBJECT)
     def annotations = factory.createParameterFromText("@TA int x", context).modifierList.annotations
     def type = new PsiImmediateClassType(aClass, PsiSubstitutor.EMPTY, LanguageLevel.JDK_1_8, annotations)
-    assertTypeText(type, "java.lang.@pkg.TA Object", CommonClassNames.JAVA_LANG_OBJECT)
+    assertTypeText type, "java.lang.@pkg.TA Object", CommonClassNames.JAVA_LANG_OBJECT
+  }
+
+  public void testFieldType() {
+    def psi = factory.createFieldFromText("@A @TA(1) String f;", context)
+    assertTypeText psi.type, "java.lang.@pkg.TA(1) String", "java.lang.String"
+    assertAnnotations psi.type, "@TA(1)"
+  }
+
+  public void testMethodReturnType() {
+    def psi = factory.createMethodFromText("@A @TA(1) String m() { return null; }", context)
+    assertTypeText psi.returnType, "java.lang.@pkg.TA(1) String", "java.lang.String"
+    assertAnnotations psi.returnType, "@TA(1)"
   }
 
   private void doTest(String text, String annotated, String canonical) {
@@ -102,4 +114,8 @@ class AnnotatedTypeTest extends LightCodeInsightFixtureTestCase {
     assert type.getCanonicalText(true) == annotated
     assert type.getCanonicalText(false) == canonical
   }
+
+  private static void assertAnnotations(PsiType type, String... annotations) {
+    assert type.annotations.collect { it.text } == annotations.toList()
+  }
 }
\ No newline at end of file
index e0c38a3913f4ad6bfc62aa20822f30e89a423e17..4a27815e27d2caeec2eba0b7926fa2266072eca5 100644 (file)
@@ -59,6 +59,11 @@ public class NullableStuffInspectionTest extends LightCodeInsightFixtureTestCase
     doTest();
   }
 
+  public void testNotNullByDefaultFieldNotInitialized() {
+    DataFlowInspectionTest.addJavaxNullabilityAnnotations(myFixture);
+    doTest();
+  }
+
   public void testNotNullAnnotationChecksInChildClassMethods() { doTest(); }
 
   public void testGetterSetterProblems() throws Exception{ doTest(); }
index eabe458396a2d920d5ff6dd9df4481f272c48810..00adb05989c34aea1fe009ecb754f2724b02bded 100644 (file)
@@ -62,7 +62,7 @@ public class JavaAutoDetectIndentPerformanceTest extends AbstractIndentAutoDetec
     AbstractIndentAutoDetectionTest.detectIndentOptions();
     
     PlatformTestUtil
-      .startPerformanceTest("Detecting indent on hot file", 30, AbstractIndentAutoDetectionTest::detectIndentOptions)
+      .startPerformanceTest("Detecting indent on hot file", 40, AbstractIndentAutoDetectionTest::detectIndentOptions)
       .cpuBound()
       .assertTiming();
   }
index 3652f87a7880a9e603d845a7bea860b80af0742c..afcb86dc945a594932f4315b562df7a98f98c974 100644 (file)
@@ -247,6 +247,12 @@ public class ChangeSignatureTest extends ChangeSignatureBaseTest {
     }, false);
   }
 
+  public void testJavadocOfDeleted() {
+    doTest(null, new ParameterInfoImpl[]{
+      new ParameterInfoImpl(0, "role", PsiType.INT),
+    }, false);
+  }
+
   public void testCovariantReturnType() {
     doTest(CommonClassNames.JAVA_LANG_RUNNABLE, new ParameterInfoImpl[0], false);
   }
index e1e66c483fc47d9d78872f043f0c818fa2bf0dfb..79435401350a2299391ecd4d3a3d5836d81500fd 100644 (file)
@@ -18,7 +18,6 @@ package com.intellij.refactoring;
 import com.intellij.JavaTestUtil;
 import com.intellij.openapi.fileEditor.FileDocumentManager;
 import com.intellij.openapi.roots.LanguageLevelProjectExtension;
-import com.intellij.openapi.vfs.VirtualFile;
 import com.intellij.pom.java.LanguageLevel;
 import com.intellij.psi.PsiClass;
 import com.intellij.psi.PsiElement;
@@ -174,7 +173,11 @@ public class MoveMembersTest extends MultiFileTestCase {
   public void testEscalateVisibility1() throws Exception {
     doTest("A", "B", true, VisibilityUtil.ESCALATE_VISIBILITY, 0);
   }
-  
+
+  public void testStringConstantInSwitchLabelExpression() throws Exception {
+    doTest("A", "B", true, VisibilityUtil.ESCALATE_VISIBILITY, 0);
+  }
+
   public void testMultipleWithDependencies() throws Exception {
     doTest("A", "B", true, VisibilityUtil.ESCALATE_VISIBILITY, 0, 1);
   }
index 6650bb7b6bed1ae9256d7f7ac879207655f0f54a..11c62b549b68cdd028bd7aa0c9dfbb46022b064f 100644 (file)
@@ -244,6 +244,10 @@ public class InlineLocalTest extends LightCodeInsightTestCase {
     doTest(true);
   }
 
+  public void testArrayAccessPriority() throws Exception {
+    doTest(true);
+  }
+
   public void testLocalVarInsideLambdaBodyWriteUsage() throws Exception {
     doTest(true, "Cannot perform refactoring.\n" +
                  "Variable 'hello' is accessed for writing");
index b2b44aebd867eab0b2b3d666adeeed398ff7c709..2e63ea33adeca2de8bf55c1bea835afd8a3415a4 100644 (file)
@@ -32,6 +32,7 @@ import com.intellij.structuralsearch.plugin.replace.impl.Replacer;
 import com.intellij.structuralsearch.plugin.ui.Configuration;
 import com.intellij.structuralsearch.plugin.ui.SearchContext;
 import com.intellij.structuralsearch.plugin.ui.UIUtil;
+import com.intellij.util.ArrayUtil;
 import com.intellij.util.IncorrectOperationException;
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
@@ -382,7 +383,7 @@ public class JavaStructuralSearchProfile extends StructuralSearchProfile {
       private void checkModifier(final String name) {
         if (!MatchOptions.INSTANCE_MODIFIER_NAME.equals(name) &&
             !PsiModifier.PACKAGE_LOCAL.equals(name) &&
-            Arrays.binarySearch(JavaMatchingVisitor.MODIFIERS, name) < 0
+            ArrayUtil.find(JavaMatchingVisitor.MODIFIERS, name) < 0
           ) {
           throw new MalformedPatternException(SSRBundle.message("invalid.modifier.type",name));
         }
@@ -530,7 +531,7 @@ public class JavaStructuralSearchProfile extends StructuralSearchProfile {
         handleMethodParameter(buf, info, matchMap);
         replacementString = buf.toString();
       }
-      else if (match.getAllSons().size() > 0 && !match.isScopeMatch()) {
+      else if (match.hasSons() && !match.isScopeMatch()) {
         // compound matches
         StringBuilder buf = new StringBuilder();
         MatchResult r = null;
@@ -550,7 +551,7 @@ public class JavaStructuralSearchProfile extends StructuralSearchProfile {
               }
             }
             else if (info.isStatementContext()) {
-              final PsiElement previousElement = previous.getMatchRef().getElement();
+              final PsiElement previousElement = previous.getMatch();
 
               if (!(previousElement instanceof PsiComment) &&
                   ( buf.charAt(buf.length() - 1) != '}' ||
@@ -720,15 +721,15 @@ public class JavaStructuralSearchProfile extends StructuralSearchProfile {
     }
   }
 
-  private static void appendParameter(final StringBuilder buf, final MatchResult _matchResult) {
-    for(Iterator<MatchResult> j = _matchResult.getAllSons().iterator();j.hasNext();) {
-      buf.append(j.next().getMatchImage()).append(' ').append(j.next().getMatchImage());
-    }
+  private static void appendParameter(final StringBuilder buf, final MatchResult matchResult) {
+    final List<MatchResult> sons = matchResult.getAllSons();
+    assert sons.size() == 1;
+    buf.append(sons.get(0).getMatchImage()).append(' ').append(matchResult.getMatchImage());
   }
 
   private static void removeExtraSemicolonForSingleVarInstanceInMultipleMatch(final ParameterInfo info, MatchResult r, StringBuilder buf) {
     if (info.isStatementContext()) {
-      final PsiElement element = r.getMatchRef().getElement();
+      final PsiElement element = r.getMatch();
 
       // remove extra ;
       if (buf.charAt(buf.length()-1)==';' &&
index 26f77d163a5155665335ee06bd4139fb0bcf014a..d545e0f25f7a8ed65117e19cb2857d97093567f2 100644 (file)
@@ -941,13 +941,12 @@ public class JavaMatchingVisitor extends JavaElementVisitor {
     myMatchingVisitor.getMatchContext().pushResult();
     final PsiIdentifier nameIdentifier = var.getNameIdentifier();
 
-    boolean isTypedVar = myMatchingVisitor.getMatchContext().getPattern().isTypedVar(nameIdentifier);
+    final boolean isTypedVar = myMatchingVisitor.getMatchContext().getPattern().isTypedVar(nameIdentifier);
     final PsiVariable var2 = (PsiVariable)myMatchingVisitor.getElement();
 
     try {
       myMatchingVisitor.setResult((myMatchingVisitor.matchText(var.getNameIdentifier(), var2.getNameIdentifier()) || isTypedVar) &&
-                                  ((var.getParent() instanceof PsiClass && ((PsiClass)var.getParent()).isInterface()) ||
-                                   myMatchingVisitor.match(var.getModifierList(), var2.getModifierList())));
+                                   myMatchingVisitor.match(var.getModifierList(), var2.getModifierList()));
       if (myMatchingVisitor.getResult()) {
         final PsiTypeElement typeElement1 = var.getTypeElement();
         if (typeElement1 != null) {
@@ -972,10 +971,6 @@ public class JavaMatchingVisitor extends JavaElementVisitor {
           ((PsiCatchSection)var2.getParent()).getCatchBlock()
         ));
       }
-
-      if (myMatchingVisitor.getResult() && isTypedVar) {
-        myMatchingVisitor.setResult(myMatchingVisitor.handleTypedElement(nameIdentifier, var2.getNameIdentifier()));
-      }
     }
     finally {
       saveOrDropResult(nameIdentifier, isTypedVar, var2.getNameIdentifier());
@@ -1692,9 +1687,7 @@ public class JavaMatchingVisitor extends JavaElementVisitor {
                                   myMatchingVisitor.matchSonsOptionally(method.getBody(), method2.getBody()));
     }
     finally {
-      final PsiIdentifier methodNameNode2 = method2.getNameIdentifier();
-
-      saveOrDropResult(methodNameNode, isTypedVar, methodNameNode2);
+      saveOrDropResult(methodNameNode, isTypedVar, method2.getNameIdentifier());
     }
   }
 }
index a0ca95579138e3ab0c78e485bf6a0bf0ef0155d4..05c4afc2548fe3d700d707a0c28ee9d4bbae2ffe 100644 (file)
@@ -61,7 +61,7 @@ public class ConvertFieldToThreadLocalIntention extends PsiElementBaseIntentionA
     if (psiField.getTypeElement() == null) return false;
     final PsiType fieldType = psiField.getType();
     final PsiClass fieldTypeClass = PsiUtil.resolveClassInType(fieldType);
-    if (fieldType instanceof PsiPrimitiveType && fieldType != PsiType.VOID || fieldType instanceof PsiArrayType) return true;
+    if (fieldType instanceof PsiPrimitiveType && !PsiType.VOID.equals(fieldType) || fieldType instanceof PsiArrayType) return true;
     return fieldTypeClass != null && !Comparing.strEqual(fieldTypeClass.getQualifiedName(), ThreadLocal.class.getName())
            && AllowedApiFilterExtension.isClassAllowed(ThreadLocal.class.getName(), element);
   }
@@ -121,7 +121,7 @@ public class ConvertFieldToThreadLocalIntention extends PsiElementBaseIntentionA
       if (initializer == null) {
         final PsiType type = psiField.getType();
         String initializerText = null;
-        if (type == PsiType.BOOLEAN) {
+        if (PsiType.BOOLEAN.equals(type)) {
           initializerText = "false";
         }
         else if (type instanceof PsiPrimitiveType) {
index a4ec46e448386ced5c775a6f776194746fa32135..a6275b650266d944a0df7c06ef7676cc94097692 100644 (file)
@@ -39,19 +39,19 @@ public class AtomicConversionRule extends TypeConversionRule {
   }
 
   private static boolean isAtomicTypeMigration(PsiType from, PsiClassType to, PsiExpression context) {
-    if (from == PsiType.INT && to.getCanonicalText().equals(AtomicInteger.class.getName())) {
+    if (PsiType.INT.equals(from) && to.getCanonicalText().equals(AtomicInteger.class.getName())) {
       return true;
     }
     if (from.equals(PsiType.INT.createArrayType()) && to.getCanonicalText().equals(AtomicIntegerArray.class.getName())) {
       return true;
     }
-    if (from == PsiType.LONG && to.getCanonicalText().equals(AtomicLong.class.getName())) {
+    if (PsiType.LONG.equals(from) && to.getCanonicalText().equals(AtomicLong.class.getName())) {
       return true;
     }
     if (from.equals(PsiType.LONG.createArrayType()) && to.getCanonicalText().equals(AtomicLongArray.class.getName())) {
       return true;
     }
-    if (from == PsiType.BOOLEAN && to.getCanonicalText().equals(AtomicBoolean.class.getName())) {
+    if (PsiType.BOOLEAN.equals(from) && to.getCanonicalText().equals(AtomicBoolean.class.getName())) {
       return true;
     }
     final PsiClassType.ClassResolveResult resolveResult = PsiUtil.resolveGenericsClassInType(to);
index fe07a4a257efb75439633b55244a90ed06c873e8..b90a9a9e919639fd7dc5a9e1ab998198765872f3 100644 (file)
@@ -39,7 +39,7 @@ public interface CodeDocumentationAwareCommenter extends Commenter {
    * Returns the type of the block comment in the language,
    * or null if the language does not support block comments.
    * It is assumed that block comment prefix is not null when block comment type is not null.
-   * @return the line block comment type.
+   * @return the block comment type.
    */
   @Nullable
   IElementType getBlockCommentTokenType();
@@ -48,7 +48,7 @@ public interface CodeDocumentationAwareCommenter extends Commenter {
    * Returns the type of the documentation comment token in the language,
    * or null if the language does not support documentation comments.
    * It is assumed that documentation comment prefix is not null when documentation comment type is not null.
-   * @return the line block comment type.
+   * @return the documentation comment type.
    */
   @Nullable
   IElementType getDocumentationCommentTokenType();
index 8062d86390b85483bd266e082396eb86fbe0a987..fcd2ec68fa294509511403d9f08b34a49825d6ba 100644 (file)
@@ -64,7 +64,9 @@ public abstract class DumbService {
   }
 
   /**
-   * Executes the runnable immediately if not in dumb mode, or on AWT Event Dispatch thread when the dumb mode ends.
+   * Executes the runnable immediately if not in dumb mode, or on AWT Event Dispatch thread after the dumb mode ends.
+   * Note that it's not guaranteed that the dumb mode won't start again during this runnable execution, it should manage that situation explicitly
+   * (e.g. by starting a read action; it's still necessary to check isDumb inside the read action).
    * @param runnable runnable to run
    */
   public abstract void runWhenSmart(@NotNull Runnable runnable);
index 539a8da7341c38750423adc65553063c02bf101a..975495669f9a2ddeeffbd2a2fe01485510ddaec5 100644 (file)
@@ -584,11 +584,18 @@ public class VfsUtilCore {
     }
 
     if (file == null) {
-      if (base == null) return StandardFileSystems.local().findFileByPath(uri);
-      if (!base.isDirectory()) base = base.getParent();
-      if (base == null) return StandardFileSystems.local().findFileByPath(uri);
-      file = VirtualFileManager.getInstance().findFileByUrl(base.getUrl() + "/" + uri);
-      if (file == null) return null;
+      if (base != null && !base.isDirectory()) {
+        base = base.getParent();
+      }
+      if (base == null) {
+        file = StandardFileSystems.local().findFileByPath(uri);
+        if (file == null) {
+          file = VirtualFileManager.getInstance().findFileByUrl(uri);
+        }
+      }
+      else {
+        file = VirtualFileManager.getInstance().findFileByUrl(base.getUrl() + "/" + uri);
+      }
     }
 
     return file;
index 157231cbbb362a86a417e28b6c73eb1851872c07..677da409294c240d82033ab3f7dd813a7333e94e 100644 (file)
@@ -35,9 +35,9 @@ public class EditorDocumentPriorities {
   public static final int FOLD_MODEL = 60;
   public static final int LOGICAL_POSITION_CACHE = 65;
   public static final int EDITOR_TEXT_LAYOUT_CACHE = 70;
-  public static final int EDITOR_TEXT_WIDTH_CACHE = 75;
   public static final int LEXER_EDITOR = 80;
   public static final int SOFT_WRAP_MODEL = 100;
+  public static final int EDITOR_TEXT_WIDTH_CACHE = 110;
   public static final int CARET_MODEL = 120;
   public static final int SELECTION_MODEL = 140;
   public static final int EDITOR_DOCUMENT_ADAPTER = 160;
index e175e367b6666a8d0b0308b7ed858d86f49a2681..e88e13e1a90fcb69bc9e413dd9b47f1e72f0c8ce 100644 (file)
@@ -96,6 +96,14 @@ public final class DocumentUtil {
     return document.getLineStartOffset(lineNumber);
   }
 
+  public static int getLineEndOffset(int offset, @NotNull Document document) {
+    if (offset < 0 || offset > document.getTextLength()) {
+      return offset;
+    }
+    int lineNumber = document.getLineNumber(offset);
+    return document.getLineEndOffset(lineNumber);
+  }
+
   @NotNull
   public static TextRange getLineTextRange(@NotNull Document document, int line) {
     return TextRange.create(document.getLineStartOffset(line), document.getLineEndOffset(line));
index eb68ae221082a13092fe19529a4205c2d5cf4e57..faee0d18ab2f1f437bbf7b6ac47c2da58ba0f26b 100644 (file)
@@ -18,9 +18,16 @@ package com.intellij.ide.macro;
 
 import com.intellij.ide.IdeBundle;
 import com.intellij.openapi.actionSystem.DataContext;
+import com.intellij.openapi.util.SystemInfo;
+import com.intellij.openapi.util.io.FileUtil;
+import com.intellij.openapi.util.text.StringUtil;
 import com.intellij.openapi.vfs.VirtualFile;
+import org.jetbrains.annotations.NotNull;
 
 public class FileDirPathFromParentMacro extends Macro {
+
+  private static final String PATH_DELIMITER = "/";
+
   @Override
   public String getName() {
     return "FileDirPathFromParent";
@@ -41,13 +48,71 @@ public class FileDirPathFromParentMacro extends Macro {
     if(args.length == 0) {
       return super.expand(dataContext, args);
     }
-    String param = args[0];
-    VirtualFile vFile = getVirtualDirOrParent(dataContext);
-    StringBuilder result = new StringBuilder();
-    while (vFile != null && !param.equalsIgnoreCase(vFile.getName())) {
-      result.insert(0, vFile.getName() + "/");
-      vFile = vFile.getParent();
+    VirtualFile dir = getVirtualDirOrParent(dataContext);
+    if (dir == null) {
+      return "";
+    }
+    String dirPath = dir.getPath();
+    String surroundedSubDir = surroundWithSlashes(FileUtil.toSystemIndependentName(args[0]));
+    String surroundedDirPath = surroundWithSlashes(dirPath);
+    if (surroundedSubDir.length() == 1) {
+      return surroundedDirPath.substring(1);
+    }
+    int ind = lastIndexOf(surroundedDirPath,
+                          surroundedSubDir,
+                          surroundedDirPath.length(),
+                          !SystemInfo.isFileSystemCaseSensitive);
+    if (ind >= 0) {
+      return surroundedDirPath.substring(ind + surroundedSubDir.length());
+    }
+    return dirPath;
+  }
+
+  private static int lastIndexOf(@NotNull CharSequence buffer, @NotNull String pattern, int maxIndex, boolean ignoreCase) {
+    int patternLength = pattern.length();
+    int end = buffer.length() - patternLength;
+    if (maxIndex > end) {
+      maxIndex = end;
+    }
+    for (int i = maxIndex; i >= 0; i--) {
+      boolean found = true;
+      for (int j = 0; j < patternLength; j++) {
+        if (ignoreCase) {
+          if (StringUtil.charsEqualIgnoreCase(pattern.charAt(j), buffer.charAt(i + j))) {
+            found = false;
+            break;
+          }
+        }
+        else {
+          if (pattern.charAt(j) != buffer.charAt(i + j)) {
+            found = false;
+            break;
+          }
+        }
+      }
+      if (found) {
+        return i;
+      }
+    }
+    return -1;
+  }
+
+  @NotNull
+  private static String surroundWithSlashes(@NotNull String path) {
+    if (path.isEmpty()) {
+      return PATH_DELIMITER;
+    }
+    boolean prepend = !path.startsWith(PATH_DELIMITER);
+    boolean append = !path.endsWith(PATH_DELIMITER);
+    if (prepend && append) {
+      return PATH_DELIMITER + path + PATH_DELIMITER;
+    }
+    if (prepend) {
+      path = PATH_DELIMITER + path;
+    }
+    if (append) {
+      path += PATH_DELIMITER;
     }
-    return result.toString();
+    return path;
   }
 }
index 0393cf8848bc23cedc36bf03acf9dc6409176550..6168269d7d98bd225b7fcf5d2e4e04602738353d 100644 (file)
@@ -22,6 +22,7 @@ import com.intellij.openapi.project.Project;
 import com.intellij.openapi.roots.ProjectFileIndex;
 import com.intellij.openapi.roots.ProjectRootManager;
 import com.intellij.openapi.util.Comparing;
+import com.intellij.openapi.vfs.JarFileSystem;
 import com.intellij.openapi.vfs.VfsUtil;
 import com.intellij.openapi.vfs.VfsUtilCore;
 import com.intellij.openapi.vfs.VirtualFile;
@@ -116,28 +117,35 @@ public class DirectoryNode extends PackageDependenciesNode {
   public void fillFiles(Set<PsiFile> set, boolean recursively) {
     super.fillFiles(set, recursively);
     int count = getChildCount();
+    Boolean isRoot = null;
     for (int i = 0; i < count; i++) {
       PackageDependenciesNode child = (PackageDependenciesNode)getChildAt(i);
       if (child instanceof FileNode || recursively) {
         child.fillFiles(set, true);
       }
       else if (child instanceof DirectoryNode) {
-        final VirtualFile directory = ((DirectoryNode)child).getDirectory();
-        if (directory != null) {
-          final ProjectFileIndex fileIndex = ProjectRootManager.getInstance(myProject).getFileIndex();
-          final VirtualFile contentRoot = fileIndex.getContentRootForFile(directory);
-          final VirtualFile sourceRoot = fileIndex.getSourceRootForFile(directory);
-          if (directory.equals(contentRoot) ||
-              contentRoot != null && contentRoot.equals(directory.getParent()) ||
-              directory.equals(sourceRoot) ||
-              sourceRoot != null && sourceRoot.equals(directory.getParent())) {
-            child.fillFiles(set, false);
-          }
+        if (isRoot == null) {
+          isRoot = isContentOrSourceRoot();
+        }
+        if (isRoot) {
+          child.fillFiles(set, false);
         }
       }
     }
   }
 
+  public boolean isContentOrSourceRoot() {
+    if (myVDirectory != null) {
+      final ProjectFileIndex fileIndex = ProjectRootManager.getInstance(myProject).getFileIndex();
+      final VirtualFile contentRoot = fileIndex.getContentRootForFile(myVDirectory);
+      final VirtualFile sourceRoot = fileIndex.getSourceRootForFile(myVDirectory);
+      if (myVDirectory.equals(contentRoot) || myVDirectory.equals(sourceRoot)) {
+        return true;
+      }
+    }
+    return false;
+  }
+
   public String toString() {
     if (myFQName != null) return myFQName;
     if (myCompactPackages && myCompactedDirNode != null) {
@@ -217,8 +225,9 @@ public class DirectoryNode extends PackageDependenciesNode {
 
   @Override
   public Icon getIcon() {
-    if (myDirectory != null) {
-      return new DirectoryIconProvider().getIcon(myDirectory, 0);
+    if (myVDirectory != null) {
+      final VirtualFile jarRoot = JarFileSystem.getInstance().getRootByEntry(myVDirectory);
+      return myVDirectory.equals(jarRoot) ? PlatformIcons.JAR_ICON : DirectoryIconProvider.getDirectoryIcon(myVDirectory, myProject);
     }
     return PlatformIcons.PACKAGE_ICON;
   }
index 03e0b4fa4c927495c5f75eb6bb5e87a7055cc79b..1fa0d02c3c5f0df31eccf18b7688a03ca3741a74 100644 (file)
@@ -43,20 +43,22 @@ public class DirectoryIconProvider extends IconProvider implements DumbAware {
   public Icon getIcon(@NotNull final PsiElement element, final int flags) {
     if (element instanceof PsiDirectory) {
       final PsiDirectory psiDirectory = (PsiDirectory)element;
-      final VirtualFile vFile = psiDirectory.getVirtualFile();
-      Project project = psiDirectory.getProject();
-      SourceFolder sourceFolder = ProjectRootsUtil.getModuleSourceRoot(vFile, project);
-      if (sourceFolder != null) {
-        return SourceRootPresentation.getSourceRootIcon(sourceFolder);
-      }
-      else {
-        Icon excludedIcon = getIconIfExcluded(project, vFile);
-        return excludedIcon != null ? excludedIcon : PlatformIcons.DIRECTORY_CLOSED_ICON;
-      }
+      return getDirectoryIcon(psiDirectory.getVirtualFile(), psiDirectory.getProject());
     }
     return null;
   }
 
+  public static Icon getDirectoryIcon(VirtualFile vFile, Project project) {
+    SourceFolder sourceFolder = ProjectRootsUtil.getModuleSourceRoot(vFile, project);
+    if (sourceFolder != null) {
+      return SourceRootPresentation.getSourceRootIcon(sourceFolder);
+    }
+    else {
+      Icon excludedIcon = getIconIfExcluded(project, vFile);
+      return excludedIcon != null ? excludedIcon : PlatformIcons.DIRECTORY_CLOSED_ICON;
+    }
+  }
+
   @Nullable
   public static Icon getIconIfExcluded(@NotNull Project project, @NotNull VirtualFile vFile) {
     if (!Registry.is("ide.hide.excluded.files")) {
index c7eb78761a366572ba2b191076aa42af106579c6..d8916bc6ce3b44018e9b7f8bbf06eda489009145 100644 (file)
@@ -483,15 +483,19 @@ public class IdeEventQueue extends EventQueue {
               modifiers |= InputEvent.ALT_MASK;
             }
 
+            int oldKeyCode = ke.getKeyCode();
+
             //noinspection MagicConstant
-            e = new KeyEvent(ke.getComponent(), ke.getID(), ke.getWhen(), modifiers,
-                             ke.getKeyCode(), ke.getKeyChar(), ke.getKeyLocation());
+            ke = new KeyEvent(ke.getComponent(), ke.getID(), ke.getWhen(), modifiers,
+                             KeyEvent.VK_UNDEFINED, ke.getKeyChar(), KeyEvent.KEY_LOCATION_UNKNOWN);
+
+            ke.setKeyCode(oldKeyCode);
           }
         }
       }
     }
 
-    return e;
+    return ke;
   }
 
   private static AWTEvent mapEvent(AWTEvent e) {
index 7b5f21a3ddf899fdcd481579337b3ac19da7eac8..556dd39d4481302e11e3f3e8fe4b88d25303216f 100644 (file)
@@ -1832,6 +1832,10 @@ public final class EditorImpl extends UserDataHolderBase implements EditorEx, Hi
   }
 
   private void bulkUpdateStarted() {
+    if (myUseNewRendering) {
+      myView.getPreferredSize(); // make sure size is calculated (in case it will be required while bulk mode is active)
+    }
+    
     saveCaretRelativePosition();
 
     myCaretModel.onBulkDocumentUpdateStarted();
index 84b06477b95377521e1e3f4cb258e510384c9dbb..6f0f44d7d348a940900118a5ae700ea6045893f2 100644 (file)
@@ -16,6 +16,7 @@
 package com.intellij.openapi.editor.impl;
 
 import com.intellij.openapi.editor.ex.util.EditorUIUtil;
+import com.intellij.openapi.editor.impl.view.FontLayoutService;
 import com.intellij.openapi.util.SystemInfo;
 import com.intellij.openapi.util.registry.Registry;
 import com.intellij.util.ui.UIUtil;
@@ -188,7 +189,7 @@ public class FontInfo {
   public int charWidth(char c) {
     final FontMetrics metrics = fontMetrics();
     if (c < 128) return charWidth[c];
-    return metrics.charWidth(c);
+    return FontLayoutService.getInstance().charWidth(metrics, c);
   }
 
   private FontMetrics fontMetrics() {
@@ -199,8 +200,8 @@ public class FontInfo {
       EditorUIUtil.setupAntialiasing(graphics);
       graphics.setFont(myFont);
       myFontMetrics = graphics.getFontMetrics();
-      for (int i = 0; i < 128; i++) {
-        charWidth[i] = myFontMetrics.charWidth(i);
+      for (char c = 0; c < 128; c++) {
+        charWidth[c] = FontLayoutService.getInstance().charWidth(myFontMetrics, c);
       }
     }
     return myFontMetrics;
index b9ce1d8684f938438226498c4b6fdd8da225d922..e41b3efc46a379f3b8b2b633a3f9a3b4de001762 100644 (file)
@@ -58,6 +58,11 @@ class EditorSizeManager implements PrioritizedDocumentListener, Disposable, Fold
   private int myMaxLineWithExtensionWidth;
   private int myWidestLineWithExtension;
   
+  private int myDocumentChangeStartOffset;
+  private int myDocumentChangeEndOffset;
+  private int myFoldingChangeStartOffset = Integer.MAX_VALUE;
+  private int myFoldingChangeEndOffset = Integer.MIN_VALUE;
+  
   private final List<TextRange> myDeferredRanges = new ArrayList<TextRange>();
   
   private final SoftWrapAwareDocumentParsingListenerAdapter mySoftWrapChangeListener = new SoftWrapAwareDocumentParsingListenerAdapter() {
@@ -88,31 +93,34 @@ class EditorSizeManager implements PrioritizedDocumentListener, Disposable, Fold
 
   @Override
   public void beforeDocumentChange(DocumentEvent event) {
+    if (myDocument.isInBulkUpdate()) return;
+    myDocumentChangeStartOffset = event.getOffset();
+    myDocumentChangeEndOffset = event.getOffset() + event.getNewLength();
   }
 
   @Override
   public void documentChanged(DocumentEvent event) {
-    invalidateRange(event.getOffset(), event.getOffset() + event.getNewLength());
+    if (myDocument.isInBulkUpdate()) return;
+    doInvalidateRange(myDocumentChangeStartOffset, myDocumentChangeEndOffset);
   }
   
-  private int foldingChangeStartOffset = Integer.MAX_VALUE;
-  private int foldingChangeEndOffset = Integer.MIN_VALUE;
-  
   @Override
   public void onFoldRegionStateChange(@NotNull FoldRegion region) {
+    if (myDocument.isInBulkUpdate()) return;
     if (region.isValid()) {
-      foldingChangeStartOffset = Math.min(foldingChangeStartOffset, region.getStartOffset());
-      foldingChangeEndOffset = Math.max(foldingChangeEndOffset, region.getEndOffset());
+      myFoldingChangeStartOffset = Math.min(myFoldingChangeStartOffset, region.getStartOffset());
+      myFoldingChangeEndOffset = Math.max(myFoldingChangeEndOffset, region.getEndOffset());
     }
   }
 
   @Override
   public void onFoldProcessingEnd() {
-    if (foldingChangeStartOffset <= foldingChangeEndOffset) {
-      invalidateRange(foldingChangeStartOffset, foldingChangeEndOffset);
+    if (myDocument.isInBulkUpdate()) return;
+    if (myFoldingChangeStartOffset <= myFoldingChangeEndOffset) {
+      doInvalidateRange(myFoldingChangeStartOffset, myFoldingChangeEndOffset);
     }
-    foldingChangeStartOffset = Integer.MAX_VALUE;
-    foldingChangeEndOffset = Integer.MIN_VALUE;
+    myFoldingChangeStartOffset = Integer.MAX_VALUE;
+    myFoldingChangeEndOffset = Integer.MIN_VALUE;
 
     for (TextRange range : myDeferredRanges) {
       onTextLayoutPerformed(range.getStartOffset(), range.getEndOffset());
@@ -121,7 +129,21 @@ class EditorSizeManager implements PrioritizedDocumentListener, Disposable, Fold
   }
 
   private void onSoftWrapRecalculationEnd(IncrementalCacheUpdateEvent event) {
-    invalidateRange(event.getStartOffset(), event.getActualEndOffset());
+    if (myDocument.isInBulkUpdate()) return;
+    boolean invalidate = true;
+    if (myEditor.getFoldingModel().isInBatchFoldingOperation()) {
+      myFoldingChangeStartOffset = Math.min(myFoldingChangeStartOffset, event.getStartOffset());
+      myFoldingChangeEndOffset = Math.max(myFoldingChangeEndOffset, event.getActualEndOffset());
+      invalidate = false;
+    }
+    if (myDocument.isInEventsHandling()) {
+      myDocumentChangeStartOffset = Math.min(myDocumentChangeStartOffset, event.getStartOffset());
+      myDocumentChangeEndOffset = Math.max(myDocumentChangeEndOffset, event.getActualEndOffset());
+      invalidate = false;
+    }
+    if (invalidate) {
+      doInvalidateRange(event.getStartOffset(), event.getActualEndOffset());
+    }
   }
 
   Dimension getPreferredSize() {
@@ -149,6 +171,7 @@ class EditorSizeManager implements PrioritizedDocumentListener, Disposable, Fold
 
   private int getPreferredWidth() {
     if (myWidthInPixels < 0) {
+      assert !myDocument.isInBulkUpdate();
       myWidthInPixels = calculatePreferredWidth();
     }
     validateMaxLineWithExtension();
@@ -193,10 +216,22 @@ class EditorSizeManager implements PrioritizedDocumentListener, Disposable, Fold
   }
 
   void reset() {
-    invalidateRange(0, myDocument.getTextLength());
+    assert !myDocument.isInBulkUpdate();
+    doInvalidateRange(0, myDocument.getTextLength());
   }
 
   void invalidateRange(int startOffset, int endOffset) {
+    if (myDocument.isInBulkUpdate()) return;
+    if (myDocument.isInEventsHandling()) {
+      myDocumentChangeStartOffset = Math.min(myDocumentChangeStartOffset, startOffset);
+      myDocumentChangeEndOffset = Math.max(myDocumentChangeEndOffset, endOffset);
+    }
+    else {
+      doInvalidateRange(startOffset, endOffset);
+    }
+  }
+  
+  private void doInvalidateRange(int startOffset, int endOffset) {
     myWidthInPixels = -1;
     int startVisualLine = myView.offsetToVisualLine(startOffset, false);
     int endVisualLine = myView.offsetToVisualLine(endOffset, true);
@@ -223,6 +258,7 @@ class EditorSizeManager implements PrioritizedDocumentListener, Disposable, Fold
   }
 
   void textLayoutPerformed(int startOffset, int endOffset) {
+    if (myDocument.isInBulkUpdate()) return;
     if (myEditor.getFoldingModel().isInBatchFoldingOperation()) {
       myDeferredRanges.add(new TextRange(startOffset, endOffset));
     }
index b08cf0fdd08733203744757e7caaf0dafe06d47d..e00bdf6f7f0c91fec5d7ad227778cf41706b42e1 100644 (file)
  */
 package com.intellij.openapi.keymap.impl.ui;
 
-
-import com.intellij.ide.DataManager;
-import com.intellij.openapi.actionSystem.CommonDataKeys;
 import com.intellij.openapi.actionSystem.KeyboardShortcut;
-import com.intellij.openapi.actionSystem.ex.QuickList;
-import com.intellij.openapi.help.HelpManager;
 import com.intellij.openapi.keymap.KeyMapBundle;
 import com.intellij.openapi.keymap.Keymap;
-import com.intellij.openapi.keymap.KeymapUtil;
-import com.intellij.openapi.project.Project;
-import com.intellij.openapi.ui.DialogWrapper;
-import com.intellij.openapi.wm.ex.IdeFocusTraversalPolicy;
-import com.intellij.ui.IdeBorderFactory;
-import com.intellij.ui.JBColor;
-import com.intellij.ui.ScrollPaneFactory;
-import com.intellij.util.ArrayUtil;
 import com.intellij.util.ui.JBUI;
-import com.intellij.util.ui.UIUtil;
-import org.jetbrains.annotations.NotNull;
-import org.jetbrains.annotations.Nullable;
-
-import javax.swing.*;
-import javax.swing.border.EmptyBorder;
-import java.awt.*;
-import java.awt.event.ActionEvent;
-import java.awt.event.ActionListener;
-import java.util.ArrayList;
-import java.util.Map;
-import java.util.Set;
-
-public class KeyboardShortcutDialog extends DialogWrapper {
-  private StrokePanel myFirstStrokePanel;
-  private StrokePanel mySecondStrokePanel;
-  private final JCheckBox myEnableSecondKeystroke;
-  private final JLabel myKeystrokePreview;
-  private final JTextArea myConflictInfoArea;
-  private Keymap myKeymap;
-  private final String myActionId;
-  private final Group myMainGroup;
-
-  public KeyboardShortcutDialog(Component component, String actionId, final QuickList[] quickLists) {
-    super(component, true);
-    setTitle(KeyMapBundle.message("keyboard.shortcut.dialog.title"));
-    myActionId = actionId;
-    final Project project = CommonDataKeys.PROJECT.getData(DataManager.getInstance().getDataContext(component));
-    myMainGroup = ActionsTreeUtil.createMainGroup(project, myKeymap, quickLists, null, false, null); //without current filter
-    myEnableSecondKeystroke = new JCheckBox();
-    UIUtil.applyStyle(UIUtil.ComponentStyle.SMALL, myEnableSecondKeystroke);
-    myEnableSecondKeystroke.setBorder(new EmptyBorder(4, 0, 0, 2));
-    myEnableSecondKeystroke.setFocusable(false);
-    myKeystrokePreview = new JLabel(" ");
-    myConflictInfoArea = new JTextArea("");
-    myConflictInfoArea.setFocusable(false);
-    init();
-  }
-
-  @NotNull
-  protected Action[] createActions(){
-    return new Action[]{getOKAction(),getCancelAction(),getHelpAction()};
-  }
-
-  protected JComponent createCenterPanel() {
-    JPanel panel = new JPanel(new GridBagLayout());
-
-    // First stroke
-
-    myFirstStrokePanel = new StrokePanel(KeyMapBundle.message("first.stroke.panel.title"));
-    panel.add(
-      myFirstStrokePanel,
-      new GridBagConstraints(0,0,2,1,1,0,GridBagConstraints.CENTER,GridBagConstraints.HORIZONTAL,new Insets(0,0,0,0),0,0)
-    );
-
-    // Second stroke panel
-
-    panel.add(
-      myEnableSecondKeystroke,
-      new GridBagConstraints(0,1,1,1,0,0,GridBagConstraints.NORTHWEST,GridBagConstraints.NONE,new Insets(0,0,0,0),0,0)
-    );
-
-    mySecondStrokePanel = new StrokePanel(KeyMapBundle.message("second.stroke.panel.title"));
-    panel.add(
-      mySecondStrokePanel,
-      new GridBagConstraints(1,1,1,1,1,0,GridBagConstraints.NORTHWEST,GridBagConstraints.HORIZONTAL,new Insets(0,0,0,0),0,0)
-    );
-
-    // Shortcut preview
-
-    JPanel previewPanel = new JPanel(new BorderLayout());
-    previewPanel.setBorder(IdeBorderFactory.createTitledBorder(KeyMapBundle.message("shortcut.preview.ide.border.factory.title"), true));
-    previewPanel.add(myKeystrokePreview);
-    panel.add(
-      previewPanel,
-      new GridBagConstraints(0,2,2,1,1,0,GridBagConstraints.CENTER,GridBagConstraints.HORIZONTAL,new Insets(0,0,0,0),0,0)
-    );
-
-    // Conflicts
-
-    JPanel conflictsPanel = new JPanel(new BorderLayout());
-    conflictsPanel.setBorder(IdeBorderFactory.createTitledBorder(KeyMapBundle.message("conflicts.ide.border.factory.title"),
-                                                                 true));
-    myConflictInfoArea.setEditable(false);
-    myConflictInfoArea.setBackground(panel.getBackground());
-    myConflictInfoArea.setLineWrap(true);
-    myConflictInfoArea.setWrapStyleWord(true);
-    final JScrollPane conflictInfoScroll = ScrollPaneFactory.createScrollPane(myConflictInfoArea);
-    conflictInfoScroll.setPreferredSize(JBUI.size(260, 60));
-    conflictInfoScroll.setBorder(null);
-    conflictsPanel.add(conflictInfoScroll);
-    panel.add(
-      conflictsPanel,
-      new GridBagConstraints(0,3,2,1,1,1,GridBagConstraints.CENTER,GridBagConstraints.BOTH,new Insets(0,0,0,0),0,0)
-    );
 
-    myEnableSecondKeystroke.addActionListener(new ActionListener() {
-      public void actionPerformed(ActionEvent e) {
-        handleSecondKey();
-        updateCurrentKeyStrokeInfo();
+import java.awt.BorderLayout;
+import java.awt.Component;
+import java.util.Collection;
+import javax.swing.JComponent;
+import javax.swing.JPanel;
 
-        /** TODO[anton]????  */
-        if (myEnableSecondKeystroke.isSelected()) {
-          mySecondStrokePanel.getShortcutTextField().requestFocus();
-        }
-        else {
-          myFirstStrokePanel.getShortcutTextField().requestFocus();
-        }
-      }
-    });
-    return panel;
-  }
-
-  public JComponent getPreferredFocusedComponent(){
-    return IdeFocusTraversalPolicy.getPreferredFocusedComponent(myFirstStrokePanel);
-  }
-
-  public void setData(Keymap keymap, KeyboardShortcut shortcut) {
-    myKeymap = keymap;
-    myEnableSecondKeystroke.setSelected(false);
-    if (shortcut != null) {
-      myFirstStrokePanel.getShortcutTextField().setKeyStroke(shortcut.getFirstKeyStroke());
-      if (shortcut.getSecondKeyStroke() != null) {
-        myEnableSecondKeystroke.setSelected(true);
-        mySecondStrokePanel.getShortcutTextField().setKeyStroke(shortcut.getSecondKeyStroke());
-      }
-    }
-    handleSecondKey();
-    updateCurrentKeyStrokeInfo();
-  }
-
-  private void updateCurrentKeyStrokeInfo() {
-    if (myConflictInfoArea == null || myKeystrokePreview == null){
-      return;
-    }
-
-    myConflictInfoArea.setText(null);
-    myKeystrokePreview.setText(" ");
-
-    if (myKeymap == null){
-      return;
-    }
-
-    KeyboardShortcut keyboardShortcut = getKeyboardShortcut();
-    if (keyboardShortcut == null){
-      return;
-    }
-
-    String strokeText = getTextByKeyStroke(keyboardShortcut.getFirstKeyStroke());
-    String suffixText = getTextByKeyStroke(keyboardShortcut.getSecondKeyStroke());
-    if(suffixText != null && suffixText.length() > 0) {
-      strokeText += ',' + suffixText;
-    }
-    myKeystrokePreview.setText(strokeText);
+/**
+ * @author Sergey.Malenkov
+ */
+final class KeyboardShortcutDialog extends ShortcutDialog<KeyboardShortcut> {
+  private final JComponent myPreferredFocusedComponent;
 
-    StringBuilder buffer = new StringBuilder();
+  KeyboardShortcutDialog(Component parent) {
+    super(parent, "keyboard.shortcut.dialog.title", new KeyboardShortcutPanel(new BorderLayout()));
 
-    Map<String, ArrayList<KeyboardShortcut>> conflicts = myKeymap.getConflicts(myActionId, keyboardShortcut);
+    KeyboardShortcutPanel panel = (KeyboardShortcutPanel)myShortcutPanel;
+    myPreferredFocusedComponent = panel.myFirstStroke;
 
-    Set<String> keys = conflicts.keySet();
-    String[] actionIds = ArrayUtil.toStringArray(keys);
-    boolean loaded = true;
-    for (String actionId : actionIds) {
-      String actionPath = myMainGroup.getActionQualifiedPath(actionId);
-      if (actionPath == null) {
-        loaded = false;
-      }
-      if (buffer.length() > 1) {
-        buffer.append('\n');
-      }
-      buffer.append('[');
-      buffer.append(actionPath != null ? actionPath : actionId);
-      buffer.append(']');
-    }
+    JPanel inner = new JPanel(new BorderLayout());
+    inner.add(BorderLayout.CENTER, panel.mySecondStroke);
+    inner.add(BorderLayout.WEST, panel.mySecondStrokeEnable);
+    panel.add(BorderLayout.NORTH, panel.myFirstStroke);
+    panel.add(BorderLayout.SOUTH, inner);
+    panel.setBorder(JBUI.Borders.empty(0, 10));
+    panel.mySecondStrokeEnable.setSelected(true);
+    panel.mySecondStrokeEnable.setText(KeyMapBundle.message("dialog.enable.second.stroke.checkbox"));
 
-    if (buffer.length() == 0) {
-      myConflictInfoArea.setForeground(UIUtil.getTextAreaForeground());
-      myConflictInfoArea.setText(KeyMapBundle.message("no.conflict.info.message"));
-    }
-    else {
-      myConflictInfoArea.setForeground(JBColor.RED);
-      if (loaded) {
-        myConflictInfoArea.setText(KeyMapBundle.message("assigned.to.info.message", buffer.toString()));
-      }
-      else {
-        myConflictInfoArea.setText("Assigned to " + buffer.toString() + " which is now not loaded but may be loaded later");
-      }
-    }
+    init();
   }
 
-  private void handleSecondKey() {
-    mySecondStrokePanel.setEnabled(myEnableSecondKeystroke.isSelected());
+  @Override
+  protected String getHelpId() {
+    return "preferences.keymap.shortcut";
   }
 
-  @Nullable
-  public KeyboardShortcut getKeyboardShortcut() {
-    KeyStroke firstStroke = myFirstStrokePanel.getKeyStroke();
-    return firstStroke == null ? null : new KeyboardShortcut(firstStroke, myEnableSecondKeystroke.isSelected() ? mySecondStrokePanel.getKeyStroke() : null);
+  @Override
+  public JComponent getPreferredFocusedComponent() {
+    return myPreferredFocusedComponent;
   }
 
-  static String getTextByKeyStroke(KeyStroke keyStroke) {
-    if(keyStroke == null) {
-      return "";
-    }
-    return KeymapUtil.getKeystrokeText(keyStroke);
+  @Override
+  KeyboardShortcut toShortcut(Object value) {
+    return value instanceof KeyboardShortcut ? (KeyboardShortcut)value : null;
   }
 
-  protected void doHelpAction() {
-    HelpManager.getInstance().invokeHelp("preferences.keymap.shortcut");
+  @Override
+  Collection<String> getConflicts(KeyboardShortcut shortcut, String actionId, Keymap keymap) {
+    return keymap.getConflicts(actionId, shortcut).keySet();
   }
 
-  private class StrokePanel extends JPanel {
-    private final ShortcutTextField myShortcutTextField;
-
-    public StrokePanel(String borderText) {
-      setLayout(new BorderLayout());
-      setBorder(IdeBorderFactory.createTitledBorder(borderText, false));
-
-      myShortcutTextField = new ShortcutTextField(){
-        protected void updateCurrentKeyStrokeInfo() {
-          KeyboardShortcutDialog.this.updateCurrentKeyStrokeInfo();
-        }
-      };
-      add(myShortcutTextField);
-    }
-
-    public ShortcutTextField getShortcutTextField() {
-      return myShortcutTextField;
-    }
-
-    public void setEnabled(boolean state) {
-      myShortcutTextField.setEnabled(state);
-      repaint();
-    }
-
-    public KeyStroke getKeyStroke() {
-      return myShortcutTextField.getKeyStroke();
-    }
+  @Override
+  String getActionPath(String actionId) {
+    String actionPath = super.getActionPath(actionId);
+    return actionPath != null ? actionPath : actionId;
   }
 }
index 163b3975ca3a1a8002ac21224a5bf3543a05304a..9826899373292fa786d97ad1bbe8b698fd3586d6 100644 (file)
@@ -16,7 +16,6 @@
 package com.intellij.openapi.keymap.impl.ui;
 
 import com.intellij.openapi.actionSystem.KeyboardShortcut;
-import com.intellij.openapi.actionSystem.Shortcut;
 
 import java.awt.LayoutManager;
 import java.awt.event.ItemEvent;
@@ -24,19 +23,16 @@ import java.awt.event.ItemListener;
 import java.beans.PropertyChangeEvent;
 import java.beans.PropertyChangeListener;
 import javax.swing.JCheckBox;
-import javax.swing.JPanel;
 import javax.swing.KeyStroke;
 
 /**
  * @author Sergey.Malenkov
  */
-final class KeyboardShortcutPanel extends JPanel {
+final class KeyboardShortcutPanel extends ShortcutPanel<KeyboardShortcut> {
   final ShortcutTextField myFirstStroke = new ShortcutTextField();
   final ShortcutTextField mySecondStroke = new ShortcutTextField();
   final JCheckBox mySecondStrokeEnable = new JCheckBox();
 
-  private KeyboardShortcut myShortcut;
-
   private final ItemListener myItemListener = new ItemListener() {
     @Override
     public void itemStateChanged(ItemEvent event) {
@@ -50,37 +46,35 @@ final class KeyboardShortcutPanel extends JPanel {
   private final PropertyChangeListener myPropertyListener = new PropertyChangeListener() {
     @Override
     public void propertyChange(PropertyChangeEvent event) {
-      setShortcut(newShortcut());
-      if (null == myFirstStroke.getKeyStroke()) {
-        myFirstStroke.requestFocus();
+      if (KeyboardShortcutPanel.this != event.getSource()) {
+        setShortcut(newShortcut());
+        if (null == myFirstStroke.getKeyStroke()) {
+          myFirstStroke.requestFocus();
+        }
+        else if (null == mySecondStroke.getKeyStroke() && mySecondStrokeEnable.isSelected()) {
+          mySecondStroke.requestFocus();
+        }
       }
-      else if (null == mySecondStroke.getKeyStroke() && mySecondStrokeEnable.isSelected()) {
-        mySecondStroke.requestFocus();
+      else if (event.getNewValue() instanceof KeyboardShortcut) {
+        KeyboardShortcut shortcut = (KeyboardShortcut)event.getNewValue();
+        myFirstStroke.setKeyStroke(shortcut.getFirstKeyStroke());
+        mySecondStroke.setKeyStroke(shortcut.getSecondKeyStroke());
+      }
+      else {
+        myFirstStroke.setKeyStroke(null);
+        mySecondStroke.setKeyStroke(null);
       }
     }
   };
 
   KeyboardShortcutPanel(LayoutManager layout) {
     super(layout);
+    addPropertyChangeListener("shortcut", myPropertyListener);
     myFirstStroke.addPropertyChangeListener("keyStroke", myPropertyListener);
     mySecondStroke.addPropertyChangeListener("keyStroke", myPropertyListener);
     mySecondStrokeEnable.addItemListener(myItemListener);
   }
 
-  KeyboardShortcut getShortcut() {
-    return myShortcut;
-  }
-
-  void setShortcut(KeyboardShortcut shortcut) {
-    Shortcut old = myShortcut;
-    if (old == null || !old.equals(shortcut)) {
-      myShortcut = shortcut;
-      myFirstStroke.setKeyStroke(shortcut == null ? null : shortcut.getFirstKeyStroke());
-      mySecondStroke.setKeyStroke(shortcut == null ? null : shortcut.getSecondKeyStroke());
-      firePropertyChange("shortcut", old, shortcut);
-    }
-  }
-
   private KeyboardShortcut newShortcut() {
     KeyStroke key = myFirstStroke.getKeyStroke();
     return key == null ? null : new KeyboardShortcut(key, !mySecondStrokeEnable.isSelected() ? null : mySecondStroke.getKeyStroke());
index eea7a96dab055e326f48adc08585d962d822e07e..113703b4c9cd6e2446e6a7edd4800a87870aa67e 100644 (file)
@@ -36,7 +36,6 @@ import com.intellij.openapi.options.Configurable;
 import com.intellij.openapi.options.ConfigurationException;
 import com.intellij.openapi.options.SearchableConfigurable;
 import com.intellij.openapi.project.DumbAwareAction;
-import com.intellij.openapi.project.Project;
 import com.intellij.openapi.ui.Messages;
 import com.intellij.openapi.ui.popup.JBPopupFactory;
 import com.intellij.openapi.ui.popup.ListPopup;
@@ -468,40 +467,30 @@ public class KeymapPanel extends JPanel implements SearchableConfigurable, Confi
   }
 
   private void addKeyboardShortcut(@NotNull String actionId, @Nullable Shortcut shortcut) {
-    Keymap keymap = createKeymapCopyIfNeeded();
-    addKeyboardShortcut(actionId, shortcut, keymap, this, myQuickLists);
+    Keymap keymapSelected = myEditor.getModel().getSelected();
+    assert keymapSelected != null;
+    addKeyboardShortcut(actionId, shortcut, keymapSelected, this, myQuickLists);
     repaintLists();
     currentKeymapChanged();
   }
 
   public static void addKeyboardShortcut(@NotNull String actionId,
                                          @Nullable Shortcut shortcut,
-                                         @NotNull Keymap keymap,
+                                         @NotNull Keymap keymapSelected,
                                          @NotNull Component parent,
                                          @NotNull QuickList[] quickLists) {
-    KeyboardShortcutDialog dialog = new KeyboardShortcutDialog(parent, actionId, quickLists);
-    dialog.setData(keymap, shortcut instanceof KeyboardShortcut ? (KeyboardShortcut)shortcut : null);
-    if (!dialog.showAndGet()) {
-      return;
-    }
-
-    KeyboardShortcut keyboardShortcut = dialog.getKeyboardShortcut();
+    KeyboardShortcutDialog dialog = new KeyboardShortcutDialog(parent);
+    KeyboardShortcut keyboardShortcut = dialog.showAndGet(shortcut, actionId, keymapSelected, quickLists);
     if (keyboardShortcut == null) {
       return;
     }
 
-    Map<String, ArrayList<KeyboardShortcut>> conflicts = keymap.getConflicts(actionId, keyboardShortcut);
-    if (!conflicts.isEmpty()) {
-      int result = Messages.showYesNoCancelDialog(
-        parent, 
-        KeyMapBundle.message("conflict.shortcut.dialog.message"),
-        KeyMapBundle.message("conflict.shortcut.dialog.title"),
-        KeyMapBundle.message("conflict.shortcut.dialog.remove.button"),
-        KeyMapBundle.message("conflict.shortcut.dialog.leave.button"),
-        KeyMapBundle.message("conflict.shortcut.dialog.cancel.button"),
-        Messages.getWarningIcon());
-
+    Keymap keymap = null;
+    if (dialog.hasConflicts()) {
+      int result = showConfirmationDialog(parent);
       if (result == Messages.YES) {
+        keymap = createKeymapCopyIfNeededAndPossible(parent, keymapSelected);
+        Map<String, ArrayList<KeyboardShortcut>> conflicts = keymap.getConflicts(actionId, keyboardShortcut);
         for (String id : conflicts.keySet()) {
           for (KeyboardShortcut s : conflicts.get(id)) {
             keymap.removeShortcut(id, s);
@@ -514,6 +503,8 @@ public class KeymapPanel extends JPanel implements SearchableConfigurable, Confi
     }
 
     // if shortcut is already registered to this action, just select it in the list
+
+    if (keymap == null) keymap = createKeymapCopyIfNeededAndPossible(parent, keymapSelected);
     Shortcut[] shortcuts = keymap.getShortcuts(actionId);
     for (Shortcut s : shortcuts) {
       if (s.equals(keyboardShortcut)) {
@@ -533,40 +524,20 @@ public class KeymapPanel extends JPanel implements SearchableConfigurable, Confi
       return;
     }
 
-    Keymap keymap = createKeymapCopyIfNeeded();
-
-    MouseShortcut mouseShortcut = shortcut instanceof MouseShortcut ? (MouseShortcut)shortcut : null;
-    Project project = CommonDataKeys.PROJECT.getData(DataManager.getInstance().getDataContext(this));
-    MouseShortcutDialog dialog = new MouseShortcutDialog(
-      this,
-      mouseShortcut,
-      keymap,
-      actionId,
-      ActionsTreeUtil.createMainGroup(project, keymap, myQuickLists, null, true, null),
-      restrictions
-    );
-    if (!dialog.showAndGet()) {
-      return;
-    }
-
-    mouseShortcut = dialog.getMouseShortcut();
+    Keymap keymapSelected = myEditor.getModel().getSelected();
 
+    MouseShortcutDialog dialog = new MouseShortcutDialog(this, restrictions.allowMouseDoubleClick);
+    MouseShortcut mouseShortcut = dialog.showAndGet(shortcut, actionId, keymapSelected, myQuickLists);
     if (mouseShortcut == null) {
       return;
     }
 
-    String[] actionIds = keymap.getActionIds(mouseShortcut);
-    if (actionIds.length > 1 || (actionIds.length == 1 && !actionId.equals(actionIds[0]))) {
-      int result = Messages.showYesNoCancelDialog(
-        this,
-        KeyMapBundle.message("conflict.shortcut.dialog.message"),
-        KeyMapBundle.message("conflict.shortcut.dialog.title"),
-        KeyMapBundle.message("conflict.shortcut.dialog.remove.button"),
-        KeyMapBundle.message("conflict.shortcut.dialog.leave.button"),
-        KeyMapBundle.message("conflict.shortcut.dialog.cancel.button"),
-        Messages.getWarningIcon());
-
+    Keymap keymap = null;
+    if (dialog.hasConflicts()) {
+      int result = showConfirmationDialog(this);
       if (result == Messages.YES) {
+        keymap = createKeymapCopyIfNeededAndPossible(this, keymapSelected);
+        String[] actionIds = keymap.getActionIds(mouseShortcut);
         for (String id : actionIds) {
           keymap.removeShortcut(id, mouseShortcut);
         }
@@ -578,6 +549,7 @@ public class KeymapPanel extends JPanel implements SearchableConfigurable, Confi
 
     // if shortcut is already registered to this action, just select it in the list
 
+    if (keymap == null) keymap = createKeymapCopyIfNeededAndPossible(this, keymapSelected);
     Shortcut[] shortcuts = keymap.getShortcuts(actionId);
     for (Shortcut shortcut1 : shortcuts) {
       if (shortcut1.equals(mouseShortcut)) {
@@ -598,6 +570,15 @@ public class KeymapPanel extends JPanel implements SearchableConfigurable, Confi
     myActionsTree.getComponent().repaint();
   }
 
+  @NotNull
+  private static Keymap createKeymapCopyIfNeededAndPossible(Component parent, Keymap keymap) {
+    if (parent instanceof KeymapPanel) {
+      KeymapPanel panel = (KeymapPanel)parent;
+      keymap = panel.createKeymapCopyIfNeeded();
+    }
+    return keymap;
+  }
+
   @NotNull
   private Keymap createKeymapCopyIfNeeded() {
     Keymap keymap = myEditor.getModel().getSelected();
@@ -931,4 +912,15 @@ public class KeymapPanel extends JPanel implements SearchableConfigurable, Confi
 
     return group;
   }
+
+  private static int showConfirmationDialog(Component parent) {
+    return Messages.showYesNoCancelDialog(
+      parent,
+      KeyMapBundle.message("conflict.shortcut.dialog.message"),
+      KeyMapBundle.message("conflict.shortcut.dialog.title"),
+      KeyMapBundle.message("conflict.shortcut.dialog.remove.button"),
+      KeyMapBundle.message("conflict.shortcut.dialog.leave.button"),
+      KeyMapBundle.message("conflict.shortcut.dialog.cancel.button"),
+      Messages.getWarningIcon());
+  }
 }
index 2de4bdf5f3eb21a0c72960102fc0f0160feaa21c..fe0e21de9a4c8f1ac06a92954eb4e0ecbd7f8c32 100644 (file)
@@ -17,275 +17,68 @@ package com.intellij.openapi.keymap.impl.ui;
 
 import com.intellij.icons.AllIcons;
 import com.intellij.openapi.actionSystem.MouseShortcut;
-import com.intellij.openapi.actionSystem.Shortcut;
 import com.intellij.openapi.keymap.KeyMapBundle;
 import com.intellij.openapi.keymap.Keymap;
 import com.intellij.openapi.keymap.KeymapUtil;
-import com.intellij.openapi.keymap.impl.ShortcutRestrictions;
-import com.intellij.openapi.ui.DialogWrapper;
-import com.intellij.ui.IdeBorderFactory;
-import com.intellij.ui.JBColor;
-import com.intellij.ui.ScrollPaneFactory;
 import com.intellij.util.ui.JBUI;
 import com.intellij.util.ui.UIUtil;
-import org.intellij.lang.annotations.JdkConstants;
-import org.jetbrains.annotations.NotNull;
 
-import javax.swing.*;
-import java.awt.*;
-import java.awt.event.*;
+import java.awt.BorderLayout;
+import java.awt.Component;
+import java.util.Arrays;
+import java.util.Collection;
+import javax.swing.BorderFactory;
+import javax.swing.JLabel;
+import javax.swing.SwingConstants;
 
 /**
  * @author Vladimir Kondratyev
+ * @author Sergey.Malenkov
  */
-class MouseShortcutDialog extends DialogWrapper{
-  private final Keymap myKeymap;
-  private final String myActionId;
-  private final Group myMainGroup;
+final class MouseShortcutDialog extends ShortcutDialog<MouseShortcut> {
+  private final JLabel myText = new JLabel("", SwingConstants.CENTER);
 
-  private final JRadioButton myRbSingleClick;
-  private final JRadioButton myRbDoubleClick;
-  private final JLabel myLblPreview;
-  private final JLabel myClickPad;
-  private final JTextArea myTarConflicts;
+  MouseShortcutDialog(Component component, boolean allowDoubleClick) {
+    super(component, "mouse.shortcut.dialog.title", new MouseShortcutPanel(allowDoubleClick));
 
-  private final MouseShortcutConsumer myShortcutConsumer;
-
-  private int myButton;
-  @JdkConstants.InputEventMask  private int myModifiers;
-
-  /**
-   * @param shortcut dialog will be initialized with this <code>shortcut</code>. It can be <code>null</code>
-   * if dialog is used to create new mouse shortcut.
-   */
-  public MouseShortcutDialog(
-    JComponent parentComponent,
-    MouseShortcut shortcut,
-    @NotNull Keymap keymap,
-    @NotNull String actiondId,
-    @NotNull Group mainGroup,
-    @NotNull ShortcutRestrictions restrictions
-  ){
-    super(parentComponent,true);
-    setTitle(KeyMapBundle.message("mouse.shortcut.dialog.title"));
-
-    myKeymap=keymap;
-    myActionId=actiondId;
-    myMainGroup=mainGroup;
-
-    myRbSingleClick=new JRadioButton(KeyMapBundle.message("mouse.shortcut.dialog.single.click.radio"));
-    myRbDoubleClick=new JRadioButton(KeyMapBundle.message("mouse.shortcut.dialog.double.click.radio"));
-    ButtonGroup buttonGroup=new ButtonGroup();
-    buttonGroup.add(myRbSingleClick);
-    buttonGroup.add(myRbDoubleClick);
-
-    myLblPreview=new JLabel(" ");
-
-    myTarConflicts=new JTextArea();
-    myTarConflicts.setFocusable(false);
-    myTarConflicts.setEditable(false);
-    myTarConflicts.setBackground(UIUtil.getPanelBackground());
-    myTarConflicts.setLineWrap(true);
-    myTarConflicts.setWrapStyleWord(true);
-
-    if(shortcut!=null){
-      if(shortcut.getClickCount()==1){
-        myRbSingleClick.setSelected(true);
-      }else{
-        myRbDoubleClick.setSelected(true);
-      }
-      myButton=shortcut.getButton();
-      myModifiers=shortcut.getModifiers();
-    }else{
-      myRbSingleClick.setSelected(true);
-      myButton=-1;
-      myModifiers=-1;
-    }
-
-    myRbDoubleClick.setEnabled(restrictions.allowMouseDoubleClick);
-
-    updatePreviewAndConflicts();
-
-    myClickPad = new JLabel(
-      KeyMapBundle.message("mouse.shortcut.label"),
-      AllIcons.General.Mouse, SwingConstants.LEADING
-    );
-    myShortcutConsumer = new MouseShortcutConsumer(shortcut) {
-      @Override
-      public void consume(MouseShortcut shortcut) {
-        myButton = shortcut.getButton();
-        myModifiers = shortcut.getModifiers();
-        updatePreviewAndConflicts();
-      }
-    };
-    myClickPad.addHierarchyListener(myShortcutConsumer);
+    myShortcutPanel.add(BorderLayout.NORTH, new JLabel(AllIcons.General.Mouse, SwingConstants.CENTER));
+    myShortcutPanel.add(BorderLayout.CENTER, myText);
+    myShortcutPanel.setBorder(BorderFactory.createCompoundBorder(
+      JBUI.Borders.customLine(MouseShortcutPanel.BORDER, 1, 0, 1, 0),
+      JBUI.Borders.empty(20)
+    ));
 
     init();
   }
 
-  /**
-   * @return created/edited shortcut. Returns <code>null</code> if shortcut is invalid.
-   */
-  public MouseShortcut getMouseShortcut(){
-    if (myButton > 3 && myButton != MouseShortcut.BUTTON_WHEEL_UP && myButton != MouseShortcut.BUTTON_WHEEL_DOWN && getClickCount() == 2) {
-      return null;
-    }
-
-    if(myButton!=-1 && myModifiers!=-1){
-      return new MouseShortcut(myButton,myModifiers,getClickCount());
-    }else{
-      return null;
-    }
-  }
-
   @Override
   protected String getHelpId() {
     return "preferences.mouse.shortcut";
   }
 
-  protected JComponent createCenterPanel(){
-    JPanel panel=new JPanel(new GridBagLayout());
-
-    // Single/Double click
-
-    JPanel clickCountPanel=new JPanel(new GridBagLayout());
-    clickCountPanel.setBorder(IdeBorderFactory.createTitledBorder(
-      KeyMapBundle.message("mouse.shortcut.dialog.click.count.border"), true));
-    panel.add(
-      clickCountPanel,
-      new GridBagConstraints(0,0,1,1,1,0,GridBagConstraints.CENTER,GridBagConstraints.HORIZONTAL,new Insets(0,0,0,0),0,0)
-    );
-    clickCountPanel.add(
-      myRbSingleClick,
-      new GridBagConstraints(0,0,1,1,1,0,GridBagConstraints.WEST,GridBagConstraints.NONE,new Insets(0,0,0,10),0,0)
-    );
-    clickCountPanel.add(
-      myRbDoubleClick,
-      new GridBagConstraints(1,0,1,1,1,0,GridBagConstraints.EAST,GridBagConstraints.NONE,new Insets(0,0,0,0),0,0)
-    );
-
-    ActionListener listener=new ActionListener(){
-      public void actionPerformed(ActionEvent e){
-        updatePreviewAndConflicts();
-      }
-    };
-    myRbSingleClick.addActionListener(listener);
-    myRbDoubleClick.addActionListener(listener);
-
-    // Click pad
-
-    panel.add(
-      myClickPad,
-      new GridBagConstraints(0,1,1,1,1,0,GridBagConstraints.CENTER,GridBagConstraints.BOTH,new Insets(0,0,4,0),0,0)
-    );
-    myClickPad.setBorder(BorderFactory.createCompoundBorder(
-      IdeBorderFactory.createTitledBorder(KeyMapBundle.message("mouse.shortcut.dialog.click.pad.border"), true),
-      JBUI.Borders.empty(20, 0, 20, 20)));
-
-    // Shortcut preview
-
-    JPanel previewPanel=new JPanel(new GridBagLayout());
-    previewPanel.setBorder(IdeBorderFactory.createTitledBorder(
-      KeyMapBundle.message("mouse.shortcut.dialog.shortcut.preview.border"), true));
-    panel.add(
-      previewPanel,
-      new GridBagConstraints(0,2,1,1,1,0,GridBagConstraints.CENTER,GridBagConstraints.BOTH,new Insets(0,0,4,0),0,0)
-    );
-    previewPanel.add(
-      myLblPreview,
-      new GridBagConstraints(0,0,1,1,1,1,GridBagConstraints.CENTER,GridBagConstraints.BOTH,new Insets(2,2,2,2),0,0)
-    );
-
-    // Conflicts panel
-
-    JPanel conflictsPanel=new JPanel(new GridBagLayout());
-    conflictsPanel.setBorder(IdeBorderFactory.createTitledBorder(
-      KeyMapBundle.message("mouse.shortcut.dialog.conflicts.border"), true));
-    panel.add(
-      conflictsPanel,
-      new GridBagConstraints(0,3,1,1,1,1,GridBagConstraints.CENTER,GridBagConstraints.BOTH,new Insets(0,0,0,0),0,0)
-    );
-    myTarConflicts.setPreferredSize(JBUI.size(260,60));
-    JScrollPane scrollPane= ScrollPaneFactory.createScrollPane(myTarConflicts);
-    scrollPane.setBorder(null);
-    conflictsPanel.add(
-      scrollPane,
-      new GridBagConstraints(0,0,1,1,1,1,GridBagConstraints.CENTER,GridBagConstraints.BOTH,new Insets(0,0,0,0),0,0)
-    );
-
-    return panel;
-  }
-
-  private int getClickCount() {
-    return myRbSingleClick.isSelected() ? 1 : 2;
+  @Override
+  MouseShortcut toShortcut(Object value) {
+    return value instanceof MouseShortcut ? (MouseShortcut)value : null;
   }
-  /**
-   * Updates all UI controls
-   */
-  private void updatePreviewAndConflicts(){
-    if(myButton==-1||myModifiers==-1){
-      return;
-    }
-
-    myTarConflicts.setText(null);
-
-    // Set text into preview area
-
-    // empty string should have same height
-    myLblPreview.setText(KeymapUtil.getMouseShortcutText(myButton,myModifiers,getClickCount()) + " ");
-
-    // Detect conflicts
-
-    final MouseShortcut mouseShortcut=new MouseShortcut(myButton,myModifiers,getClickCount());
-
-    if (myButton > 3 && getClickCount() == 2) {
-      myTarConflicts.setForeground(JBColor.RED);
-      myTarConflicts.setText(KeyMapBundle.message("mouse.shortcut.dialog.side.buttons.with.double.click", myButton));
-      return;
-    }
-
-    StringBuilder buffer = new StringBuilder();
-    String[] actionIds = myKeymap.getActionIds(mouseShortcut);
-    for (String actionId : actionIds) {
-      if (actionId.equals(myActionId)) {
-        continue;
-      }
-
-      String actionPath = myMainGroup.getActionQualifiedPath(actionId);
-      // actionPath == null for editor actions having corresponding $-actions
-      if (actionPath == null) {
-        continue;
-      }
-
-      Shortcut[] shortcuts = myKeymap.getShortcuts(actionId);
-      for (Shortcut shortcut1 : shortcuts) {
-        if (!(shortcut1 instanceof MouseShortcut)) {
-          continue;
-        }
-
-        MouseShortcut shortcut = (MouseShortcut)shortcut1;
-
-        if (shortcut.getButton() != mouseShortcut.getButton() || shortcut.getModifiers() != mouseShortcut.getModifiers()) {
-          continue;
-        }
 
-        if (buffer.length() > 1) {
-          buffer.append('\n');
-        }
-        buffer.append('[');
-        buffer.append(actionPath);
-        buffer.append(']');
-        break;
-      }
-    }
-
-    if (buffer.length() == 0) {
-      myTarConflicts.setForeground(UIUtil.getTextAreaForeground());
-      myTarConflicts.setText(KeyMapBundle.message("mouse.shortcut.dialog.no.conflicts.area"));
+  @Override
+  void setShortcut(MouseShortcut shortcut) {
+    super.setShortcut(shortcut);
+    if (shortcut == null) {
+      myText.setForeground(MouseShortcutPanel.FOREGROUND);
+      myText.setText(KeyMapBundle.message("dialog.mouse.pad.default.text"));
     }
     else {
-      myTarConflicts.setForeground(JBColor.RED);
-      myTarConflicts.setText(KeyMapBundle.message("mouse.shortcut.dialog.assigned.to.area", buffer.toString()));
+      myText.setForeground(UIUtil.getLabelForeground());
+      myText.setText(KeyMapBundle.message("dialog.mouse.pad.shortcut.text", KeymapUtil.getMouseShortcutText(
+        shortcut.getButton(),
+        shortcut.getModifiers(),
+        shortcut.getClickCount())));
     }
   }
+
+  @Override
+  Collection<String> getConflicts(MouseShortcut shortcut, String actionId, Keymap keymap) {
+    return Arrays.asList(keymap.getActionIds(shortcut));
+  }
 }
index 0e0e6eeeebd2367957ad3bee1c69937cdeb6bb9c..a407bb780f6528407724a67997cd025f8bcf8dc8 100644 (file)
@@ -22,18 +22,16 @@ import java.awt.BorderLayout;
 import java.awt.event.MouseAdapter;
 import java.awt.event.MouseEvent;
 import java.awt.event.MouseWheelEvent;
-import javax.swing.JPanel;
 
 /**
  * @author Sergey.Malenkov
  */
-final class MouseShortcutPanel extends JPanel {
+final class MouseShortcutPanel extends ShortcutPanel<MouseShortcut> {
   static final JBColor FOREGROUND = new JBColor(0x8C8C8C, 0x8C8C8C);
   static final JBColor BACKGROUND = new JBColor(0xF5F5F5, 0x4B4F52);
   static final JBColor BORDER = new JBColor(0xDEDEDE, 0x383B3D);
 
-  private MouseShortcut myShortcut;
-
+  private final int myClickCount;
   private final MouseAdapter myMouseListener = new MouseAdapter() {
     @Override
     public void mouseWheelMoved(MouseWheelEvent event) {
@@ -46,35 +44,26 @@ final class MouseShortcutPanel extends JPanel {
 
       int button = MouseShortcut.getButton(event);
       int clickCount = event instanceof MouseWheelEvent ? 1 : event.getClickCount();
-      if (0 <= button && clickCount < 3) {
+      if (0 <= button && clickCount <= myClickCount) {
         int modifiers = event.getModifiersEx();
-        if (myShortcut == null
-            || button != myShortcut.getButton()
-            || modifiers != myShortcut.getModifiers()
-            || clickCount != myShortcut.getClickCount()) {
-          setShortcut(new MouseShortcut(button, modifiers, clickCount));
-        }
+        setShortcut(new MouseShortcut(button, modifiers, clickCount));
       }
     }
   };
 
-  MouseShortcutPanel() {
+  MouseShortcutPanel(boolean allowDoubleClick) {
     super(new BorderLayout());
+    myClickCount = allowDoubleClick ? 2 : 1;
     addMouseListener(myMouseListener);
     addMouseWheelListener(myMouseListener);
     setBackground(BACKGROUND);
     setOpaque(true);
   }
 
-  MouseShortcut getShortcut() {
-    return myShortcut;
-  }
-
   void setShortcut(MouseShortcut shortcut) {
-    MouseShortcut old = myShortcut;
+    MouseShortcut old = getShortcut();
     if (old != null || shortcut != null) {
-      myShortcut = shortcut;
-      firePropertyChange("shortcut", old, shortcut);
+      super.setShortcut(shortcut);
     }
   }
 }
diff --git a/platform/platform-impl/src/com/intellij/openapi/keymap/impl/ui/ShortcutDialog.java b/platform/platform-impl/src/com/intellij/openapi/keymap/impl/ui/ShortcutDialog.java
new file mode 100644 (file)
index 0000000..b0713fe
--- /dev/null
@@ -0,0 +1,189 @@
+/*
+ * Copyright 2000-2015 JetBrains s.r.o.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.intellij.openapi.keymap.impl.ui;
+
+import com.intellij.icons.AllIcons;
+import com.intellij.ide.DataManager;
+import com.intellij.openapi.actionSystem.CommonDataKeys;
+import com.intellij.openapi.actionSystem.Shortcut;
+import com.intellij.openapi.actionSystem.ex.QuickList;
+import com.intellij.openapi.keymap.KeyMapBundle;
+import com.intellij.openapi.keymap.Keymap;
+import com.intellij.openapi.project.Project;
+import com.intellij.openapi.ui.DialogWrapper;
+import com.intellij.ui.ScrollPaneFactory;
+import com.intellij.ui.SimpleColoredComponent;
+import com.intellij.ui.SimpleTextAttributes;
+import com.intellij.ui.components.GradientViewport;
+import com.intellij.ui.components.JBPanel;
+import com.intellij.ui.components.panels.VerticalLayout;
+import com.intellij.util.ui.ButtonlessScrollBarUI;
+import com.intellij.util.ui.JBUI;
+import org.jetbrains.annotations.Nullable;
+
+import java.awt.BorderLayout;
+import java.awt.Component;
+import java.beans.PropertyChangeEvent;
+import java.beans.PropertyChangeListener;
+import java.util.Collection;
+import javax.swing.JComponent;
+import javax.swing.JLabel;
+import javax.swing.JScrollPane;
+import javax.swing.ScrollPaneConstants;
+import javax.swing.SwingConstants;
+import javax.swing.border.Border;
+
+/**
+ * @author Sergey.Malenkov
+ */
+abstract class ShortcutDialog<T extends Shortcut> extends DialogWrapper {
+  private final SimpleColoredComponent myAction = new SimpleColoredComponent();
+  private final JBPanel myConflictsContainer = new JBPanel(new VerticalLayout(0));
+  private final JBPanel myConflictsPanel = new JBPanel(new BorderLayout())
+    .withBorder(JBUI.Borders.empty(5, 10, 0, 10))
+    .withPreferredHeight(64)
+    .withMinimumHeight(64);
+
+  protected final ShortcutPanel<T> myShortcutPanel;
+  private final Project myProject;
+  private String myActionId;
+  private Keymap myKeymap;
+  private Group myGroup;
+
+  ShortcutDialog(Component parent, String title, ShortcutPanel<T> panel) {
+    super(parent, true);
+    myShortcutPanel = panel;
+    myProject = CommonDataKeys.PROJECT.getData(DataManager.getInstance().getDataContext(parent));
+    setTitle(KeyMapBundle.message(title));
+  }
+
+  String getActionPath(String actionId) {
+    return myGroup == null ? null : myGroup.getActionQualifiedPath(actionId);
+  }
+
+  boolean hasConflicts() {
+    return myConflictsPanel.isVisible();
+  }
+
+  abstract Collection<String> getConflicts(T shortcut, String actionId, Keymap keymap);
+
+  abstract T toShortcut(Object value);
+
+  void setShortcut(T shortcut) {
+    if (!equal(shortcut, myShortcutPanel.getShortcut())) {
+      myShortcutPanel.setShortcut(shortcut);
+    }
+    myConflictsContainer.removeAll();
+    if (shortcut != null) {
+      for (String id : getConflicts(shortcut, myActionId, myKeymap)) {
+        String path = id.equals(myActionId) ? null : getActionPath(id);
+        if (path != null) {
+          SimpleColoredComponent component = new SimpleColoredComponent();
+          fill(component, id, path);
+          myConflictsContainer.add(VerticalLayout.TOP, component);
+        }
+      }
+      myConflictsPanel.revalidate();
+    }
+    myConflictsPanel.setVisible(0 < myConflictsContainer.getComponentCount());
+  }
+
+  T showAndGet(Shortcut shortcut, String id, Keymap keymap, QuickList... lists) {
+    myActionId = id;
+    myKeymap = keymap;
+    myGroup = ActionsTreeUtil.createMainGroup(myProject, keymap, lists, null, false, null);
+    fill(myAction, id, getActionPath(id));
+    setShortcut(toShortcut(shortcut));
+    return showAndGet() ? myShortcutPanel.getShortcut() : null;
+  }
+
+  @Nullable
+  @Override
+  protected Border createContentPaneBorder() {
+    return JBUI.Borders.empty();
+  }
+
+  @Nullable
+  @Override
+  protected JComponent createSouthPanel() {
+    JComponent panel = super.createSouthPanel();
+    if (panel != null) {
+      panel.setBorder(JBUI.Borders.empty(8, 12));
+    }
+    return panel;
+  }
+
+  @Nullable
+  @Override
+  protected JComponent createNorthPanel() {
+    myAction.setIpad(JBUI.insets(10, 10, 5, 10));
+    myShortcutPanel.addPropertyChangeListener("shortcut", new PropertyChangeListener() {
+      @Override
+      public void propertyChange(PropertyChangeEvent event) {
+        setShortcut(toShortcut(event.getNewValue()));
+      }
+    });
+    JBPanel result = new JBPanel(new BorderLayout()).withPreferredWidth(300).withMinimumWidth(200);
+    result.add(BorderLayout.NORTH, myAction);
+    result.add(BorderLayout.SOUTH, myShortcutPanel);
+    return result;
+  }
+
+  @Override
+  protected JComponent createCenterPanel() {
+    JLabel icon = new JLabel(AllIcons.General.BalloonWarning);
+    icon.setVerticalAlignment(SwingConstants.TOP);
+
+    JLabel label = new JLabel(KeyMapBundle.message("dialog.conflicts.text"));
+    label.setBorder(JBUI.Borders.emptyLeft(2));
+
+    JScrollPane scroll = ScrollPaneFactory.createScrollPane(null, true);
+    scroll.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
+    scroll.setViewport(new GradientViewport(myConflictsContainer, JBUI.insets(5), false));
+    scroll.getVerticalScrollBar().setUI(ButtonlessScrollBarUI.createTransparent());
+    scroll.getVerticalScrollBar().setUnitIncrement(JBUI.scale(10));
+
+    JBPanel panel = new JBPanel(new BorderLayout());
+    panel.add(BorderLayout.NORTH, label);
+    panel.add(BorderLayout.CENTER, scroll);
+
+    myConflictsPanel.add(BorderLayout.WEST, icon);
+    myConflictsPanel.add(BorderLayout.CENTER, panel);
+    myConflictsContainer.setOpaque(false);
+    return myConflictsPanel;
+  }
+
+  private static boolean equal(Shortcut newShortcut, Shortcut oldShortcut) {
+    return newShortcut == null ? oldShortcut == null : newShortcut.equals(oldShortcut);
+  }
+
+  private static void fill(SimpleColoredComponent component, String id, String path) {
+    if (path == null) {
+      component.append(id, SimpleTextAttributes.REGULAR_ITALIC_ATTRIBUTES);
+    }
+    else {
+      int index = path.lastIndexOf(" | ");
+      if (index < 0) {
+        component.append(path, SimpleTextAttributes.REGULAR_ATTRIBUTES);
+      }
+      else {
+        component.append(path.substring(index + 3), SimpleTextAttributes.REGULAR_ATTRIBUTES);
+        component.append(" in ", SimpleTextAttributes.GRAYED_ATTRIBUTES);
+        component.append(path.substring(0, index), SimpleTextAttributes.GRAYED_ATTRIBUTES);
+      }
+    }
+  }
+}
index 6e3b199eade598624568f0faa84134c6a5b478a5..ccedfc13be04acae64aa9f7dc648167de45bdbc6 100644 (file)
@@ -40,7 +40,7 @@ import javax.swing.event.ChangeListener;
  */
 final class ShortcutFilteringPanel extends JPanel {
   final KeyboardShortcutPanel myKeyboardPanel = new KeyboardShortcutPanel(new VerticalLayout(JBUI.scale(2)));
-  final MouseShortcutPanel myMousePanel = new MouseShortcutPanel();
+  final MouseShortcutPanel myMousePanel = new MouseShortcutPanel(true);
 
   private Shortcut myShortcut;
   private JBPopup myPopup;
diff --git a/platform/platform-impl/src/com/intellij/openapi/keymap/impl/ui/ShortcutPanel.java b/platform/platform-impl/src/com/intellij/openapi/keymap/impl/ui/ShortcutPanel.java
new file mode 100644 (file)
index 0000000..1cad315
--- /dev/null
@@ -0,0 +1,42 @@
+/*
+ * Copyright 2000-2015 JetBrains s.r.o.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.intellij.openapi.keymap.impl.ui;
+
+import com.intellij.openapi.actionSystem.Shortcut;
+
+import java.awt.LayoutManager;
+import javax.swing.JPanel;
+
+/**
+ * @author Sergey.Malenkov
+ */
+class ShortcutPanel<T extends Shortcut> extends JPanel {
+  private T myShortcut;
+
+  ShortcutPanel(LayoutManager layout) {
+    super(layout);
+  }
+
+  T getShortcut() {
+    return myShortcut;
+  }
+
+  void setShortcut(T shortcut) {
+    T old = myShortcut;
+    myShortcut = shortcut;
+    firePropertyChange("shortcut", old, shortcut);
+  }
+}
index b35a096fd51de638ded8d8cb0e3a3b31f74d4db4..fa7f6787ac3f101102fba77fd95cef4497139422 100644 (file)
@@ -31,10 +31,10 @@ import javax.swing.text.DefaultCaret;
 import java.awt.*;
 import java.awt.event.KeyEvent;
 
-public class ShortcutTextField extends JTextField {
+public final class ShortcutTextField extends JTextField {
   private KeyStroke myKeyStroke;
 
-  public ShortcutTextField() {
+  ShortcutTextField() {
     enableEvents(AWTEvent.KEY_EVENT_MASK);
     setFocusTraversalKeysEnabled(false);
     putClientProperty("JTextField.variant", "search");
@@ -62,21 +62,17 @@ public class ShortcutTextField extends JTextField {
     }
   }
 
-  public void setKeyStroke(KeyStroke keyStroke) {
+  void setKeyStroke(KeyStroke keyStroke) {
     KeyStroke old = myKeyStroke;
     if (old != null || keyStroke != null) {
       myKeyStroke = keyStroke;
       super.setText(KeymapUtil.getKeystrokeText(keyStroke));
       setCaretPosition(0);
-      updateCurrentKeyStrokeInfo();
       firePropertyChange("keyStroke", old, keyStroke);
     }
   }
 
-  protected void updateCurrentKeyStrokeInfo() {
-  }
-
-  public KeyStroke getKeyStroke() {
+  KeyStroke getKeyStroke() {
     return myKeyStroke;
   }
 
index 788864eaabb457e317e2c93e8ada168753d81557..a1d1cc15b81e62ccd810bc8152c7b386ba1c5000 100644 (file)
@@ -151,14 +151,14 @@ public class DumbServiceImpl extends DumbService implements Disposable, Modifica
 
   @Override
   public void runWhenSmart(@NotNull Runnable runnable) {
-    if (!isDumb()) {
-      runnable.run();
-    }
-    else {
-      synchronized (myRunWhenSmartQueue) {
+    synchronized (myRunWhenSmartQueue) {
+      if (isDumb()) {
         myRunWhenSmartQueue.addLast(runnable);
+        return;
       }
     }
+
+    runnable.run();
   }
 
   private void scheduleCacheUpdate(@NotNull final DumbModeTask task, boolean forceDumbMode) {
@@ -220,7 +220,9 @@ public class DumbServiceImpl extends DumbService implements Disposable, Modifica
           application.runWriteAction(new Runnable() {
             @Override
             public void run() {
-              myDumb = true;
+              synchronized (myRunWhenSmartQueue) {
+                myDumb = true;
+              }
               myDumbStart = trace;
               myModificationCount++;
               try {
@@ -286,7 +288,9 @@ public class DumbServiceImpl extends DumbService implements Disposable, Modifica
   }
 
   private void updateFinished(boolean modal) {
-    myDumb = false;
+    synchronized (myRunWhenSmartQueue) {
+      myDumb = false;
+    }
     myDumbStart = null;
     myModificationCount++;
     if (myProject.isDisposed()) return;
index 41885d1cd8232f1d9478232099cbd7b4754be220..5f4cc4b913638a22c0745ce1c435f859f7c317da 100644 (file)
@@ -85,8 +85,6 @@ import java.beans.PropertyChangeListener;
 import java.util.*;
 import java.util.List;
 
-import static com.intellij.openapi.wm.impl.FloatingDecorator.DIVIDER_WIDTH;
-
 /**
  * @author Anton Katilin
  * @author Vladimir Kondratyev
@@ -975,7 +973,7 @@ public final class ToolWindowManagerImpl extends ToolWindowManagerEx implements
 
     deactivateToolWindowImpl(id, true, commandList);
 
-    if (hideSide && !info.isFloating()) {
+    if (hideSide && !info.isFloating() && !info.isWindowed()) {
       final List<String> ids = myLayout.getVisibleIdsOn(info.getAnchor(), this);
       for (String each : ids) {
         myActiveStack.remove(each, true);
@@ -2091,7 +2089,7 @@ public final class ToolWindowManagerImpl extends ToolWindowManagerEx implements
     private final FloatingDecorator myFloatingDecorator;
 
     /**
-     * Creates floating decorator for specified floating decorator.
+     * Creates floating decorator for specified internal decorator.
      */
     private AddFloatingDecoratorCmd(final InternalDecorator decorator, final WindowInfoImpl info) {
       super(myWindowManager.getCommandProcessor());
@@ -2163,16 +2161,13 @@ public final class ToolWindowManagerImpl extends ToolWindowManagerEx implements
     private final WindowedDecorator myWindowedDecorator;
 
     /**
-     * Creates floating decorator for specified floating decorator.
+     * Creates windowed decorator for specified internal decorator.
      */
     private AddWindowedDecoratorCmd(final InternalDecorator decorator, final WindowInfoImpl info) {
       super(myWindowManager.getCommandProcessor());
       myWindowedDecorator = new WindowedDecorator(myProject, info.copy(), decorator);
       Window window = myWindowedDecorator.getFrame();
       final Rectangle bounds = info.getFloatingBounds();
-      if (bounds != null) {
-        bounds.setBounds(bounds.x + DIVIDER_WIDTH, bounds.y + DIVIDER_WIDTH, bounds.width - 2 * DIVIDER_WIDTH, bounds.height - 2 * DIVIDER_WIDTH);
-      }
       if (bounds != null &&
           bounds.width > 0 &&
           bounds.height > 0 &&
@@ -2230,10 +2225,10 @@ public final class ToolWindowManagerImpl extends ToolWindowManagerEx implements
       myWindowedDecorator = getWindowedDecorator(info.getId());
       myId2WindowedDecorator.remove(info.getId());
 
-      JRootPane rootPane = ((RootPaneContainer)myWindowedDecorator.getFrame()).getRootPane();
-      Rectangle bounds = rootPane.getBounds();
-      Point location = rootPane.getLocationOnScreen();
-      bounds.setBounds(location.x - DIVIDER_WIDTH, location.y - DIVIDER_WIDTH, bounds.width + 2 * DIVIDER_WIDTH, bounds.height + 2 * DIVIDER_WIDTH);
+      Window frame = myWindowedDecorator.getFrame();
+      if (!frame.isShowing()) return;
+      Rectangle bounds = frame.getBounds();
+      bounds.setLocation(frame.getLocationOnScreen());
       info.setFloatingBounds(bounds);
     }
 
index 29986a28f522a3aeba4987d334618048181c21c1..010c44825ea73fae1a6bba9fda881da8fbc0369c 100644 (file)
@@ -96,6 +96,11 @@ mouse.wheel.rotate.down.shortcut.text={0}Wheel down
 configuration.all.keymaps.should.have.non.empty.names.error.message=All keymaps should have non empty names
 configuration.all.keymaps.should.have.unique.names.error.message=All keymaps should have unique names
 
+dialog.enable.second.stroke.checkbox=Second stroke:
+dialog.mouse.pad.default.text=<html><center>Enter a shortcut here: <br>single or double-click, scroll the wheel,<br> modify with Ctrl, Alt and Shift
+dialog.mouse.pad.shortcut.text=<html><center> <br>{0}<br><br>
+dialog.conflicts.text=Already assigned to:
+
 filter.clear.action.text=Clear Filtering
 filter.settings.popup.title=Find Shortcut
 filter.enable.second.stroke.checkbox=Second stroke
index 9cd6b7d0e6ddf48a8cda3ff24e581414e3d9b0b4..a51e8153217cc8f0284d219ee3228b353ff8033a 100644 (file)
  */
 package com.intellij.openapi.editor.impl;
 
-import com.intellij.openapi.editor.Document;
-import com.intellij.openapi.editor.Editor;
-import com.intellij.openapi.editor.FoldRegion;
-import com.intellij.openapi.editor.FoldingModel;
+import com.intellij.openapi.editor.*;
 import com.intellij.openapi.editor.ex.DocumentEx;
+import com.intellij.openapi.editor.ex.EditorEx;
+import com.intellij.openapi.editor.ex.SoftWrapModelEx;
+import com.intellij.util.DocumentUtil;
 
 import java.util.Arrays;
 import java.util.List;
@@ -37,7 +37,8 @@ public class EditorStressTest extends AbstractEditorTest {
                                                                          new AddFoldRegion(),
                                                                          new RemoveFoldRegion(),
                                                                          new CollapseFoldRegion(),
-                                                                         new ExpandFoldRegion());
+                                                                         new ExpandFoldRegion(),
+                                                                         new ChangeBulkModeState());
 
   private final Random myRandom = new Random() {{
     //noinspection ConstantConditions
@@ -67,6 +68,26 @@ public class EditorStressTest extends AbstractEditorTest {
   }
 
   protected void checkConsistency(Editor editor) {
+    checkSoftWrapPositions(editor);
+  }
+
+  private static void checkSoftWrapPositions(Editor editor) {
+    DocumentEx document = ((EditorEx)editor).getDocument();
+    if (document.isInBulkUpdate()) return;
+    FoldingModel foldingModel = editor.getFoldingModel();
+    List<? extends SoftWrap> softWraps = ((SoftWrapModelEx)editor.getSoftWrapModel()).getRegisteredSoftWraps();
+    int lastSoftWrapOffset = -1;
+    for (SoftWrap wrap : softWraps) {
+      int softWrapOffset = wrap.getStart();
+      assertTrue("Soft wraps are not ordered", softWrapOffset > lastSoftWrapOffset);
+      FoldRegion foldRegion = foldingModel.getCollapsedRegionAtOffset(softWrapOffset);
+      assertTrue("Soft wrap is inside fold region", foldRegion == null || foldRegion.getStartOffset() == softWrapOffset);
+      assertFalse("Soft wrap before line break", softWrapOffset == DocumentUtil.getLineEndOffset(softWrapOffset, document) &&
+                                                 foldRegion == null);
+      assertFalse("Soft wrap after line break", softWrapOffset == DocumentUtil.getLineStartOffset(softWrapOffset, document) && 
+                                                !foldingModel.isOffsetCollapsed(softWrapOffset - 1));
+      lastSoftWrapOffset = softWrapOffset;
+    }
   }
 
   interface Action {
@@ -116,7 +137,8 @@ public class EditorStressTest extends AbstractEditorTest {
   private static class AddFoldRegion implements Action {
     @Override
     public void perform(final Editor editor, Random random) {
-      Document document = editor.getDocument();
+      DocumentEx document = ((EditorEx)editor).getDocument();
+      if (document.isInBulkUpdate()) return;
       int textLength = document.getTextLength();
       if (textLength <= 0) return;
       final int startOffset = random.nextInt(textLength + 1);
@@ -132,6 +154,8 @@ public class EditorStressTest extends AbstractEditorTest {
   private static class RemoveFoldRegion implements Action {
     @Override
     public void perform(final Editor editor, Random random) {
+      DocumentEx document = ((EditorEx)editor).getDocument();
+      if (document.isInBulkUpdate()) return;
       final FoldingModel foldingModel = editor.getFoldingModel();
       FoldRegion[] foldRegions = foldingModel.getAllFoldRegions();
       if (foldRegions.length == 0) return;
@@ -143,6 +167,8 @@ public class EditorStressTest extends AbstractEditorTest {
   private static class CollapseFoldRegion implements Action {
     @Override
     public void perform(final Editor editor, Random random) {
+      DocumentEx document = ((EditorEx)editor).getDocument();
+      if (document.isInBulkUpdate()) return;
       final FoldingModel foldingModel = editor.getFoldingModel();
       FoldRegion[] foldRegions = foldingModel.getAllFoldRegions();
       if (foldRegions.length == 0) return;
@@ -154,6 +180,8 @@ public class EditorStressTest extends AbstractEditorTest {
   private static class ExpandFoldRegion implements Action {
     @Override
     public void perform(final Editor editor, Random random) {
+      DocumentEx document = ((EditorEx)editor).getDocument();
+      if (document.isInBulkUpdate()) return;
       final FoldingModel foldingModel = editor.getFoldingModel();
       FoldRegion[] foldRegions = foldingModel.getAllFoldRegions();
       if (foldRegions.length == 0) return;
@@ -161,4 +189,12 @@ public class EditorStressTest extends AbstractEditorTest {
       foldingModel.runBatchFoldingOperation(() -> region.setExpanded(true));
     }
   }
+  
+  private static class ChangeBulkModeState implements Action {
+    @Override
+    public void perform(Editor editor, Random random) {
+      DocumentEx document = ((EditorEx)editor).getDocument();
+      document.setInBulkUpdate(!document.isInBulkUpdate());
+    }
+  }
 }
\ No newline at end of file
index d72fcdfc69bbce36d8dfc843431b1fda33fd3337..692a32b3a6092f1221e0df163b3b64a9ffacc6ff 100644 (file)
@@ -16,6 +16,8 @@
 package com.intellij.openapi.editor.impl.softwrap.mapping;
 
 import com.intellij.openapi.editor.*;
+import com.intellij.openapi.editor.ex.DocumentEx;
+import com.intellij.openapi.editor.ex.EditorEx;
 import com.intellij.openapi.editor.impl.EditorStressTest;
 import com.intellij.openapi.editor.impl.SoftWrapModelImpl;
 import com.intellij.openapi.util.registry.Registry;
@@ -42,6 +44,8 @@ public class SoftWrapStressTest extends EditorStressTest {
 
   @Override
   protected void checkConsistency(Editor editor) {
+    DocumentEx document = ((EditorEx)editor).getDocument();
+    if (document.isInBulkUpdate()) return;
     Set<Integer> softWrapOffsets = checkSoftWraps(editor);
     List<CacheEntry> cache = ((SoftWrapModelImpl)editor.getSoftWrapModel()).getDataMapper().getCache();
     CacheEntry prevEntry = null;
index c90c85bd5b3dfd0b175305a89d034c1c0b865068..0a39b739c20845c230f678bd6553b062c336e614 100644 (file)
@@ -113,6 +113,25 @@ public class VfsUtilTest extends PlatformTestCase {
     assertEquals("test text", content);
   }
 
+  public void testFindRelativeFile() throws Exception {
+    final VirtualFile root = VirtualFileManager.getInstance().findFileByUrl("temp:///");
+    assertNotNull(root);
+    VirtualFile file = VfsUtilCore.findRelativeFile(root.getUrl(), null);
+    assertEquals(root, file);
+
+    File ioTestDataDir = new File(PathManagerEx.getTestDataPath());
+    VirtualFile testDataDir = LocalFileSystem.getInstance().findFileByIoFile(ioTestDataDir);
+    assertNotNull(testDataDir);
+    assertEquals(testDataDir, VfsUtilCore.findRelativeFile(VfsUtilCore.convertFromUrl(ioTestDataDir.toURI().toURL()), null));
+    assertEquals(testDataDir, VfsUtilCore.findRelativeFile(ioTestDataDir.getAbsolutePath(), null));
+
+    File ioVfsDir = new File(ioTestDataDir, "vfs");
+    VirtualFile vfsDir = LocalFileSystem.getInstance().findFileByIoFile(ioVfsDir);
+    assertNotNull(vfsDir);
+    assertEquals(vfsDir, VfsUtilCore.findRelativeFile(ioVfsDir.getAbsolutePath(), null));
+    assertEquals(vfsDir, VfsUtilCore.findRelativeFile("vfs", testDataDir));
+  }
+
   public void testRelativePath() throws Exception {
     final File root = new File(PathManagerEx.getTestDataPath());
     final File testRoot = new File(new File(root, "vfs"), "relativePath");
index 62ba4445b46ad8cf903498af119bc206001af875..9b79b8f5652b02ee3b7ad0e3d1e08eb0781b2e87 100644 (file)
  */
 package com.intellij.execution.testframework.sm.runner.ui;
 
-import com.intellij.execution.testframework.*;
-import com.intellij.execution.testframework.actions.ScrollToTestSourceAction;
-import com.intellij.execution.testframework.sm.SMRunnerUtil;
+import com.intellij.execution.testframework.AbstractTestProxy;
+import com.intellij.execution.testframework.TestConsoleProperties;
 import com.intellij.execution.testframework.sm.runner.ProxyFilters;
 import com.intellij.execution.testframework.sm.runner.SMTestProxy;
-import com.intellij.openapi.application.ModalityState;
-import com.intellij.pom.Navigatable;
-import com.intellij.util.OpenSourceUtil;
-import org.jetbrains.annotations.NotNull;
-import org.jetbrains.annotations.Nullable;
 
 import java.util.List;
 
@@ -67,20 +61,4 @@ public class SMTRunnerUIActionsHandler extends TestResultsViewer.SMEventsAdapter
       }
     }
   }
-
-  public void onSelected(@Nullable final SMTestProxy selectedTestProxy,
-                         @NotNull final TestResultsViewer viewer,
-                         @NotNull final TestFrameworkRunningModel model) {
-    //TODO: tests o "onSelected"
-    SMRunnerUtil.runInEventDispatchThread(new Runnable() {
-      public void run() {
-        if (ScrollToTestSourceAction.isScrollEnabled(model)) {
-          final Navigatable descriptor = TestsUIUtil.getOpenFileDescriptor(selectedTestProxy, model);
-          if (descriptor != null) {
-            OpenSourceUtil.navigate(false, descriptor);
-          }
-        }
-      }
-    }, ModalityState.NON_MODAL);
-  }
 }
index 4da5f6c16744ad06471129974c22dcb8b9d7c1e2..fe2f478346cadbb16a0b8d903af96f2421a50587 100644 (file)
@@ -20,6 +20,7 @@ import com.intellij.execution.TestStateStorage;
 import com.intellij.execution.configurations.RunConfiguration;
 import com.intellij.execution.configurations.RunProfile;
 import com.intellij.execution.testframework.*;
+import com.intellij.execution.testframework.actions.ScrollToTestSourceAction;
 import com.intellij.execution.testframework.export.TestResultsXmlFormatter;
 import com.intellij.execution.testframework.sm.SMRunnerUtil;
 import com.intellij.execution.testframework.sm.TestHistoryConfiguration;
@@ -47,8 +48,10 @@ import com.intellij.openapi.util.io.FileUtilRt;
 import com.intellij.openapi.util.registry.Registry;
 import com.intellij.openapi.util.text.StringUtil;
 import com.intellij.openapi.wm.IdeFocusManager;
+import com.intellij.pom.Navigatable;
 import com.intellij.ui.JBColor;
 import com.intellij.util.Alarm;
+import com.intellij.util.OpenSourceUtil;
 import com.intellij.util.PathUtil;
 import com.intellij.util.containers.ContainerUtil;
 import com.intellij.util.text.DateFormatUtil;
@@ -197,6 +200,7 @@ public class SMTestRunnerResultsForm extends TestResultsPanel
       @Override
       public void pass(AbstractTestProxy testProxy) {
         if (testProxy == null) return;
+        final AbstractTestProxy selectedProxy = testProxy;
         //drill to the first leaf
         while (!testProxy.isLeaf()) {
           final List<? extends AbstractTestProxy> children = testProxy.getChildren();
@@ -213,6 +217,14 @@ public class SMTestRunnerResultsForm extends TestResultsPanel
         //pretend the selection on the first leaf
         //so if test would be run, tracking would be restarted 
         myLastSelected = testProxy;
+
+        //ensure scroll to source on explicit selection only
+        if (ScrollToTestSourceAction.isScrollEnabled(SMTestRunnerResultsForm.this)) {
+          final Navigatable descriptor = TestsUIUtil.getOpenFileDescriptor(selectedProxy, SMTestRunnerResultsForm.this);
+          if (descriptor != null) {
+            OpenSourceUtil.navigate(false, descriptor);
+          }
+        }
       }
     });
 
index 1f319b8f15e51a26302b0b3f889be5600a273d89..ec0847d6c4f90aaf3d7b78a962faa142e4c8e3c9 100644 (file)
@@ -45,7 +45,7 @@ public class DocumentBasedReplaceHandler extends StructuralReplaceHandler {
     PsiElement element = result.getMatch();
     PsiFile file = element instanceof PsiFile ? (PsiFile)element : element.getContainingFile();
     Document document = PsiDocumentManager.getInstance(myProject).getDocument(file);
-    TextRange textRange = result.getMatchRef().getElement().getTextRange();
+    TextRange textRange = result.getMatch().getTextRange();
     assert textRange != null;
     RangeMarker rangeMarker = document.createRangeMarker(textRange);
     rangeMarker.setGreedyToLeft(true);
index c5196e67178d49725ddf05718cbb746edf517f0c..75ee67a63bfe2eba24a7607807101d9d4fca65f1 100644 (file)
@@ -10,8 +10,8 @@ import java.util.List;
  * Class describing the match result
  */
 public abstract class MatchResult {
-  @NonNls public static final String LINE_MATCH = "line";
-  @NonNls public static final String MULTI_LINE_MATCH = "context";
+  @NonNls public static final String LINE_MATCH = "__line__";
+  @NonNls public static final String MULTI_LINE_MATCH = "__multi_line__";
 
   public abstract String getMatchImage();
 
@@ -26,4 +26,5 @@ public abstract class MatchResult {
   public abstract boolean hasSons();
   public abstract boolean isScopeMatch();
   public abstract boolean isMultipleMatch();
+  public abstract boolean isTarget();
 }
index ea25cdefb89a5720f9e43d7f672bff3c4c1466d2..41a1c264832f1a597e0b25edb28479127c388e21 100644 (file)
@@ -221,7 +221,7 @@ public abstract class StructuralSearchProfile {
     if (info.getName().equals(match.getName())) {
       String replacementString = match.getMatchImage();
       boolean forceAddingNewLine = false;
-      if (match.getAllSons().size() > 0 && !match.isScopeMatch()) {
+      if (match.hasSons() && !match.isScopeMatch()) {
         // compound matches
         StringBuilder buf = new StringBuilder();
 
index 50e64b6457b9b1f5ae9cdf3b921c0e02e4d774c6..8d5309ad46b5d90bd683eafd294c8a970866e387 100644 (file)
@@ -246,17 +246,15 @@ public class GlobalMatchingVisitor extends AbstractMatchingVisitor {
     matchContext.getSink().newMatch(result);
   }
 
-  private boolean doDispatch(final MatchResultImpl result, MatchResultImpl context) {
+  private boolean doDispatch(final MatchResult result, MatchResultImpl context) {
     boolean ret = false;
 
-    for (MatchResult _r : result.getAllSons()) {
-      final MatchResultImpl r = (MatchResultImpl)_r;
-
+    for (MatchResult r : result.getAllSons()) {
       if ((r.isScopeMatch() && !r.isTarget()) || r.isMultipleMatch()) {
         ret |= doDispatch(r, context);
       }
       else if (r.isTarget()) {
-        r.setContext(context);
+        ((MatchResultImpl)r).setContext(context);
         matchContext.getSink().newMatch(r);
         ret = true;
       }
@@ -273,19 +271,15 @@ public class GlobalMatchingVisitor extends AbstractMatchingVisitor {
       result.setMatchImage(match.getText());
     }
     else {
-      MatchResultImpl sonresult;
 
       for (final PsiElement matchStatement : matchedNodes) {
-        result.getMatches().add(
-          sonresult = new MatchResultImpl(
+        result.getMatches().add(new MatchResultImpl(
             MatchResult.LINE_MATCH,
             matchStatement.getText(),
             new SmartPsiPointer(matchStatement),
             true
           )
         );
-
-        sonresult.setParent(result);
       }
 
       result.setMatchRef(
index 6278a6023382cd94f4d4d8725c773b861d709e26..58748a35b9706c475eb00535fd238a727a577022 100644 (file)
@@ -3,7 +3,6 @@ package com.intellij.structuralsearch.impl.matcher;
 import com.intellij.psi.PsiElement;
 import com.intellij.structuralsearch.MatchResult;
 import com.intellij.structuralsearch.plugin.util.SmartPsiPointer;
-import org.jetbrains.annotations.NonNls;
 
 import java.util.ArrayList;
 import java.util.Iterator;
@@ -23,7 +22,6 @@ public final class MatchResultImpl extends MatchResult {
 
   private boolean myScopeMatch;
   private boolean myMultipleMatch;
-  @NonNls private static final String NULL = "null";
   private MatchResultImpl myContext;
 
   MatchResultImpl() {
@@ -42,21 +40,21 @@ public final class MatchResultImpl extends MatchResult {
     this.end = end;
   }
 
+  @Override
   public String getMatchImage() {
-    if (matchImage==null) {
-      matchImage = NULL;
-    }
     return matchImage;
   }
 
-  public void setParent(MatchResult parent) {
-  }
-
+  @Override
   public SmartPsiPointer getMatchRef() {
     return matchRef;
   }
 
+  @Override
   public PsiElement getMatch() {
+    if (matchRef == null) {
+      return null;
+    }
     return matchRef.getElement();
   }
 
@@ -64,6 +62,7 @@ public final class MatchResultImpl extends MatchResult {
     matchRef = matchStart;
   }
 
+  @Override
   public String getName() {
     return name;
   }
@@ -77,18 +76,22 @@ public final class MatchResultImpl extends MatchResult {
     return matches;
   }
 
+  @Override
   public List<MatchResult> getAllSons() {
     return getMatches();
   }
 
+  @Override
   public boolean hasSons() {
-    return matches!=null;
+    return matches!=null && matches.size() > 0;
   }
 
+  @Override
   public boolean isScopeMatch() {
     return myScopeMatch;
   }
 
+  @Override
   public boolean isMultipleMatch() {
     return myMultipleMatch;
   }
@@ -159,6 +162,7 @@ public final class MatchResultImpl extends MatchResult {
     this.matchImage = matchImage;
   }
 
+  @Override
   public boolean isTarget() {
     return target;
   }
@@ -171,6 +175,7 @@ public final class MatchResultImpl extends MatchResult {
     return matchImage==null;
   }
 
+  @Override
   public int getStart() {
     return start;
   }
@@ -179,6 +184,7 @@ public final class MatchResultImpl extends MatchResult {
     this.start = start;
   }
 
+  @Override
   public int getEnd() {
     return end;
   }
index b0ea748c8477444b2d02944d0f0a8bf54f6f1fea..48eb7c471ae7a2875b09481d58ba70bdfb956841 100644 (file)
@@ -219,10 +219,6 @@ public class MatcherImpl {
     }
   }
 
-  Project getProject() {
-    return project;
-  }
-
   /**
    * Finds the matches of given pattern starting from given tree element.
    * @throws MalformedPatternException
index 78744bad6390301a5c189433e9ed48d6f9794161..afe40f03792ce79ec0e874c814eb8a1c2b039afc 100644 (file)
@@ -437,7 +437,7 @@ public class PatternCompiler {
         addPredicate(handler, matchPredicate);
       }
 
-      addScriptConstraint(name, constraint, handler);
+      addScriptConstraint(project, name, constraint, handler);
 
       if (!StringUtil.isEmptyOrSpaces(constraint.getContainsConstraint())) {
         predicate = new ContainsPredicate(name, constraint.getContainsConstraint());
@@ -474,7 +474,7 @@ public class PatternCompiler {
         addPredicate(handler,predicate);
       }
 
-      addScriptConstraint(Configuration.CONTEXT_VAR_NAME, constraint, handler);
+      addScriptConstraint(project, Configuration.CONTEXT_VAR_NAME, constraint, handler);
     }
 
     buf.append(text.substring(prevOffset,text.length()));
@@ -505,12 +505,12 @@ public class PatternCompiler {
     return elements;
   }
 
-  private static void addScriptConstraint(String name, MatchVariableConstraint constraint, SubstitutionHandler handler) {
+  private static void addScriptConstraint(Project project, String name, MatchVariableConstraint constraint, SubstitutionHandler handler) {
     if (constraint.getScriptCodeConstraint()!= null && constraint.getScriptCodeConstraint().length() > 2) {
       final String script = StringUtil.stripQuotesAroundValue(constraint.getScriptCodeConstraint());
       final String s = ScriptSupport.checkValidScript(script);
       if (s != null) throw new MalformedPatternException("Script constraint for " + constraint.getName() + " has problem "+s);
-      MatchPredicate predicate = new ScriptPredicate(name, script);
+      MatchPredicate predicate = new ScriptPredicate(project, name, script);
       addPredicate(handler,predicate);
     }
   }
index 2fb20927d3297f1db85c998637a093b1d2849127..1936818628dfdcfbbb3432280a31ebfa0f13050d 100644 (file)
@@ -96,7 +96,7 @@ public class SubstitutionHandler extends MatchingHandler {
 
     if (match!=null) {
       if (start==0 && end==-1 && result.getStart()==0 && result.getEnd()==-1) {
-        matchresult = matchContext.getMatcher().match(match,result.getMatchRef().getElement());
+        matchresult = matchContext.getMatcher().match(match,result.getMatch());
       } else {
         matchresult = StructuralSearchUtil.getProfileByPsiElement(match).getText(match, start, end).equals(
           result.getMatchImage()
@@ -167,7 +167,7 @@ public class SubstitutionHandler extends MatchingHandler {
   
         if (!substitution.isMultipleMatch()) {
           // adding intermediate node to contain all multiple matches
-          MatchResultImpl sonresult = new MatchResultImpl(
+          final MatchResultImpl sonresult = new MatchResultImpl(
             substitution.getName(),
             substitution.getMatchImage(),
             substitution.getMatchRef(),
@@ -176,7 +176,6 @@ public class SubstitutionHandler extends MatchingHandler {
             target
           );
 
-          sonresult.setParent(substitution);
           substitution.setMatchRef(
             new SmartPsiPointer(match == null ? null : match)
           );
@@ -193,7 +192,6 @@ public class SubstitutionHandler extends MatchingHandler {
           substitution.addSon( sonresult);
         } 
   
-        result.setParent(substitution);
         substitution.addSon( result );
       }
     }
@@ -247,7 +245,7 @@ public class SubstitutionHandler extends MatchingHandler {
 
     if (minOccurs >= 1 &&
         ( substitution == null ||
-          StructuralSearchUtil.getProfileByFileType(context.getOptions().getFileType()).getElementContextByPsi(substitution.getMatchRef().getElement()) != elementContext
+          StructuralSearchUtil.getProfileByFileType(context.getOptions().getFileType()).getElementContextByPsi(substitution.getMatch()) != elementContext
         )
        ) {
       return false;
diff --git a/platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/predicates/ScriptLog.java b/platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/predicates/ScriptLog.java
new file mode 100644 (file)
index 0000000..340b5bb
--- /dev/null
@@ -0,0 +1,60 @@
+/*
+ * Copyright 2000-2015 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.structuralsearch.impl.matcher.predicates;
+
+import com.intellij.notification.NotificationGroup;
+import com.intellij.notification.NotificationType;
+import com.intellij.openapi.project.Project;
+import com.intellij.structuralsearch.SSRBundle;
+
+/**
+ * @author Bas Leijdekkers
+ */
+public class ScriptLog {
+
+  private final NotificationGroup myEventLog;
+  private final Project myProject;
+
+  public ScriptLog(Project project) {
+    myProject = project;
+    myEventLog = NotificationGroup.logOnlyGroup(SSRBundle.message("structural.search.title"));
+  }
+
+  public void info(Object message) {
+    log(message, NotificationType.INFORMATION);
+  }
+
+  public void warn(Object message) {
+    log(message, NotificationType.WARNING);
+  }
+
+  public void error(Object message) {
+    log(message, NotificationType.ERROR);
+  }
+
+  private void log(Object message, NotificationType type) {
+    final StackTraceElement[] stackTrace = new Throwable().getStackTrace();
+    String location = "";
+    for (StackTraceElement e : stackTrace) {
+      final String methodName = e.getMethodName();
+      if ("run".equals(methodName)) {
+        location = "(" + e.getFileName() + ":" + e.getLineNumber() + ") ";
+        break;
+      }
+    }
+    myEventLog.createNotification(location + String.valueOf(message), type).notify(myProject);
+  }
+}
index 9310eb9e70a070ac74b055e80c33e2fd55069fb1..c4c09167b99aaf9bca6d68b19fa1c98a924a0bf7 100644 (file)
@@ -1,5 +1,6 @@
 package com.intellij.structuralsearch.impl.matcher.predicates;
 
+import com.intellij.openapi.project.Project;
 import com.intellij.psi.PsiElement;
 import com.intellij.structuralsearch.impl.matcher.MatchContext;
 
@@ -9,11 +10,12 @@ import com.intellij.structuralsearch.impl.matcher.MatchContext;
 public class ScriptPredicate extends AbstractStringBasedPredicate {
   private final ScriptSupport scriptSupport;
 
-  public ScriptPredicate(String name, String within) {
+  public ScriptPredicate(Project project, String name, String within) {
     super(name, within);
-    scriptSupport = new ScriptSupport(within, name);
+    scriptSupport = new ScriptSupport(project, within, name);
   }
 
+  @Override
   public boolean match(PsiElement node, PsiElement match, int start, int end, MatchContext context) {
     if (match == null) return false;
 
index 60190275a902511050e27e28b0a7a708e03304dd..f161dabd08d581d9585dc76362707208d6300be3 100644 (file)
@@ -1,11 +1,13 @@
 package com.intellij.structuralsearch.impl.matcher.predicates;
 
 import com.intellij.openapi.diagnostic.Logger;
+import com.intellij.openapi.project.Project;
 import com.intellij.psi.PsiElement;
 import com.intellij.structuralsearch.MatchResult;
 import com.intellij.structuralsearch.SSRBundle;
 import com.intellij.structuralsearch.StructuralSearchException;
 import com.intellij.structuralsearch.StructuralSearchUtil;
+import com.intellij.structuralsearch.plugin.ui.Configuration;
 import groovy.lang.Binding;
 import groovy.lang.GroovyRuntimeException;
 import groovy.lang.GroovyShell;
@@ -32,12 +34,14 @@ import java.util.Map;
  */
 public class ScriptSupport {
   private final Script script;
+  private final ScriptLog myScriptLog;
 
-  public ScriptSupport(String text, String name) {
+  public ScriptSupport(Project project, String text, String name) {
+    myScriptLog = new ScriptLog(project);
     File scriptFile = new File(text);
     GroovyShell shell = new GroovyShell();
     try {
-      script = scriptFile.exists() ? shell.parse(scriptFile):shell.parse(text, name);
+      script = scriptFile.exists() ? shell.parse(scriptFile) : shell.parse(text, name);
     } catch (Exception ex) {
       Logger.getInstance(getClass().getName()).error(ex);
       throw new RuntimeException(ex);
@@ -46,7 +50,7 @@ public class ScriptSupport {
 
   private static Map<String, Object> buildVariableMap(@NotNull MatchResult result, @NotNull Map<String, Object> out) {
     final String name = result.getName();
-    if (name != null && !result.isMultipleMatch() && !result.isScopeMatch()) {
+    if (name != null && !result.isMultipleMatch()) {
       final Object value = out.get(name);
       final PsiElement match = StructuralSearchUtil.getPresentableElement(result.getMatch());
       if (value == null) {
@@ -78,6 +82,7 @@ public class ScriptSupport {
   public String evaluate(MatchResult result, PsiElement context) {
     try {
       final HashMap<String, Object> variableMap = new HashMap<String, Object>();
+      variableMap.put("__log__", myScriptLog);
       if (result != null) {
         buildVariableMap(result, variableMap);
         if (context == null) {
@@ -87,7 +92,7 @@ public class ScriptSupport {
       final Binding binding = new Binding(variableMap);
 
       context = StructuralSearchUtil.getPresentableElement(context);
-      binding.setVariable("__context__", context);
+      binding.setVariable(Configuration.CONTEXT_VAR_NAME, context);
       script.setBinding(binding);
 
       final Object o = script.run();
index 2ec2c6ed31753ba63c8db5724d942a4a5a5a7ce6..61c21f26180e9e4deab70c1901f2bfcc44bb5561 100644 (file)
@@ -34,8 +34,10 @@ public final class ReplacementBuilder {
   private final List<ParameterInfo> parameterizations = new ArrayList<ParameterInfo>();
   private final Map<String, ScriptSupport> replacementVarsMap;
   private final ReplaceOptions options;
+  private final Project myProject;
 
   ReplacementBuilder(final Project project,final ReplaceOptions options) {
+    myProject = project;
     replacementVarsMap = new HashMap<String, ScriptSupport>();
     this.options = options;
     String _replacement = options.getReplacement();
@@ -177,7 +179,7 @@ public final class ReplacementBuilder {
 
     if (scriptSupport == null) {
       String constraint = options.getVariableDefinition(info.getName()).getScriptCodeConstraint();
-      scriptSupport = new ScriptSupport(StringUtil.stripQuotesAroundValue(constraint), info.getName());
+      scriptSupport = new ScriptSupport(myProject, StringUtil.stripQuotesAroundValue(constraint), info.getName());
       replacementVarsMap.put(info.getName(), scriptSupport);
     }
     return scriptSupport.evaluate(match, null);
index 07566796cf06c231c73621a18847d62062069766..0bb427036f553d2f5b514161eaa5ae9c0d6d8536 100644 (file)
@@ -42,7 +42,7 @@ public class ReplacementContext {
     if (variableMap != null) {
       for (String s : variableMap.keySet()) {
         final MatchResult matchResult = replacementInfo.getVariableMap().get(s);
-        PsiElement match = matchResult.getMatchRef() != null ? matchResult.getMatch() : null;
+        PsiElement match = matchResult.getMatch();
         match = StructuralSearchUtil.getParentIfIdentifier(match);
 
         if (match instanceof PsiNamedElement) {
index 6ca23da13e7b18f0bbe92ab57cb860c437b16349..c0db4e7a24f7fe9d21d31a31bef37fdf6ab52cac 100644 (file)
@@ -390,7 +390,7 @@ public class Replacer {
         final MatchResult r = i.next();
 
         if (MatchResult.LINE_MATCH.equals(r.getName())) {
-          PsiElement element = r.getMatchRef().getElement();
+          PsiElement element = r.getMatch();
 
           if (element instanceof PsiDocCommentBase) { // doc comment is not collapsed when created in block
             if (i.hasNext()) {
@@ -409,7 +409,7 @@ public class Replacer {
         }
       }
     } else {
-      l.add( manager.createSmartPsiElementPointer(result.getMatchRef().getElement()));
+      l.add(manager.createSmartPsiElementPointer(result.getMatch()));
     }
 
     ReplacementInfoImpl replacementInfo = new ReplacementInfoImpl();
index ac3c39e4b9a298f66a78b782f1c6792b899313fc..71118f1e4030c77a8c87940e5dc1563842c847d9 100644 (file)
@@ -144,10 +144,10 @@ public class SearchCommand {
         if (MatchResult.MULTI_LINE_MATCH.equals(result.getName())) {
           int start = -1;
           int end = -1;
-          PsiElement parent = result.getMatchRef().getElement().getParent();
+          PsiElement parent = result.getMatch().getParent();
 
           for (final MatchResult matchResult : ((MatchResultImpl)result).getMatches()) {
-            PsiElement el = matchResult.getMatchRef().getElement();
+            PsiElement el = matchResult.getMatch();
             final int elementStart = el.getTextRange().getStartOffset();
 
             if (start == -1 || start > elementStart) {
index 2aa293f3bba69e933bf535e70bacfd6705d2359f..afba062339735dc9dc0d78084a9c567de2095b90 100644 (file)
@@ -1174,6 +1174,36 @@ public class StructuralSearchTest extends StructuralSearchTestCase {
                                   "        Type.type.canonicalText\n"                                  + // reference to '_Type
                                   ")\n\")]"                                                            +
                                   "static final '_Type 'variable = '_init;"));
+
+    final String source2 = "class A {" +
+                           "  String s = new String();" +
+                           "  int m() {" +
+                           "    int i = 2+1;" +
+                           "    return i;" +
+                           "  }" +
+                           "}";
+    assertEquals("type of variables in script are as expected", 1,
+                 findMatchesCount(source2,
+                                  "[script(\"" +
+                                  "import com.intellij.psi.*\n" +
+                                  "a instanceof PsiClass &&" +
+                                  "b instanceof PsiTypeElement &&" +
+                                  "c instanceof PsiField &&" +
+                                  "d instanceof PsiNewExpression &&" +
+                                  "e instanceof PsiTypeElement &&" +
+                                  "f instanceof PsiMethod &&" +
+                                  "g instanceof PsiTypeElement &&" +
+                                  "h instanceof PsiLocalVariable &&" +
+                                  "i instanceof PsiPolyadicExpression &&" +
+                                  "j instanceof PsiReferenceExpression" +
+                                  "\n\")]" +
+                                  "class '_a {" +
+                                  "  '_b '_c = '_d;" +
+                                  "  '_e '_f() {" +
+                                  "    '_g '_h = '_i" +
+                                  "    return '_j;" +
+                                  "  }" +
+                                  "}"));
   }
 
   public void testCheckScriptValidation() {
index f0df8f8b9ca9b14a8e67b65ac546cd2d9f3a566c..c84fe76dcea3e0f37155a10018d1d3942dcad8e6 100644 (file)
@@ -30,6 +30,7 @@ import com.intellij.openapi.roots.ContentIterator;
 import com.intellij.openapi.roots.ModifiableRootModel;
 import com.intellij.openapi.util.Computable;
 import com.intellij.openapi.util.Disposer;
+import com.intellij.openapi.util.io.FileUtil;
 import com.intellij.openapi.vfs.VfsUtilCore;
 import com.intellij.openapi.vfs.VirtualFile;
 import com.intellij.openapi.vfs.VirtualFileManager;
@@ -41,6 +42,7 @@ import com.intellij.util.indexing.IndexableFileSet;
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
 
+import java.io.File;
 import java.io.IOException;
 
 import static com.intellij.openapi.roots.ModuleRootModificationUtil.updateModel;
@@ -70,7 +72,13 @@ public class LightProjectDescriptor {
     return ApplicationManager.getApplication().runWriteAction(new Computable<Module>() {
       @Override
       public Module compute() {
-        return ModuleManager.getInstance(project).newModule("light_idea_test_case.iml", getModuleType().getId());
+        String moduleFilePath = "light_idea_test_case.iml";
+        File imlFile = new File(moduleFilePath);
+        if (imlFile.exists()) {
+          //temporary workaround for IDEA-147530: otherwise if someone saved module with this name before the created module will get its settings
+          FileUtil.delete(imlFile);
+        }
+        return ModuleManager.getInstance(project).newModule(moduleFilePath, getModuleType().getId());
       }
     });
   }
index dd2a417a5a2f756c0ec024f3e13bf2974645e994..3254e58a98c059e796bed19dd450c342d9197918 100644 (file)
@@ -32,7 +32,7 @@ public class ScrollToTestSourceAction extends ToggleBooleanProperty.Disablable {
   protected boolean isEnabled() {
     final AbstractProperty.AbstractPropertyContainer properties = getProperties();
     final TestFrameworkRunningModel model = myModel;
-    return isEnabled(properties, model);
+    return isEnabled(model);
   }
 
   @Override
@@ -40,14 +40,13 @@ public class ScrollToTestSourceAction extends ToggleBooleanProperty.Disablable {
     return true;
   }
 
-  private static boolean isEnabled(final AbstractProperty.AbstractPropertyContainer properties, final TestFrameworkRunningModel model) {
-    if (!TestConsoleProperties.TRACK_RUNNING_TEST.value(properties)) return true;
+  private static boolean isEnabled(final TestFrameworkRunningModel model) {
     return model != null && !model.isRunning();
   }
 
   public static boolean isScrollEnabled(final TestFrameworkRunningModel model) {
     final TestConsoleProperties properties = model.getProperties();
-    return isEnabled(properties, model) && TestConsoleProperties.SCROLL_TO_SOURCE.value(properties);
+    return isEnabled(model) && TestConsoleProperties.SCROLL_TO_SOURCE.value(properties);
   }
 
   public void setModel(final TestFrameworkRunningModel model) {
index b265c961e49645a816646c67a875098f264db76e..fb0101033965764cffd075f01d737117414af46f 100644 (file)
@@ -16,6 +16,7 @@
 package com.intellij.ui.components;
 
 import com.intellij.util.ui.JBFont;
+import com.intellij.util.ui.JBUI;
 import com.intellij.util.ui.components.JBComponent;
 
 import javax.swing.*;
@@ -27,6 +28,12 @@ import java.awt.*;
  */
 @SuppressWarnings("unchecked")
 public class JBPanel<T extends JBPanel> extends JPanel implements JBComponent<T> {
+  private Integer myPreferredWidth;
+  private Integer myPreferredHeight;
+  private Integer myMaximumWidth;
+  private Integer myMaximumHeight;
+  private Integer myMinimumWidth;
+  private Integer myMinimumHeight;
 
   public JBPanel(LayoutManager layout, boolean isDoubleBuffered) {
     super(layout, isDoubleBuffered);
@@ -67,4 +74,57 @@ public class JBPanel<T extends JBPanel> extends JPanel implements JBComponent<T>
     setOpaque(true);
     return (T)this;
   }
+
+  public T withPreferredWidth(int width) {
+    myPreferredWidth = width;
+    return (T)this;
+  }
+
+  public T withPreferredHeight(int height) {
+    myPreferredHeight = height;
+    return (T)this;
+  }
+
+  public T withMaximumWidth(int width) {
+    myMaximumWidth = width;
+    return (T)this;
+  }
+
+  public T withMaximumHeight(int height) {
+    myMaximumHeight = height;
+    return (T)this;
+  }
+
+  public T withMinimumWidth(int width) {
+    myMinimumWidth = width;
+    return (T)this;
+  }
+
+  public T withMinimumHeight(int height) {
+    myMinimumHeight = height;
+    return (T)this;
+  }
+
+  @Override
+  public Dimension getPreferredSize() {
+    return getSize(super.getPreferredSize(), myPreferredWidth, myPreferredHeight, isPreferredSizeSet());
+  }
+
+  @Override
+  public Dimension getMaximumSize() {
+    return getSize(super.getMaximumSize(), myMaximumWidth, myMaximumHeight, isMaximumSizeSet());
+  }
+
+  @Override
+  public Dimension getMinimumSize() {
+    return getSize(super.getMinimumSize(), myMinimumWidth, myMinimumHeight, isMinimumSizeSet());
+  }
+
+  private static Dimension getSize(Dimension size, Integer width, Integer height, boolean isSet) {
+    if (!isSet && size != null) {
+      if (width != null) size.width = JBUI.scale(width);
+      if (height != null) size.height = JBUI.scale(height);
+    }
+    return size;
+  }
 }
index 6596b54a09823d7cacad7c5b5edab903820e8c0d..481022132e0f2a71e56f4612108ad726e7436fe4 100644 (file)
@@ -45,11 +45,11 @@ public class SafeFileOutputStream extends OutputStream {
     myTargetFile = target;
     myPreserveAttributes = preserveAttributes;
     myBackupFile = new File(myTargetFile.getParentFile(), myTargetFile.getName() + EXTENSION_BAK);
-    //noinspection IOResourceOpenedButNotSafelyClosed
     myBackupStream = new FileOutputStream(myBackupFile);
   }
 
   @Override
+  @SuppressWarnings("Duplicates")
   public void write(byte[] b) throws IOException {
     try {
       myBackupStream.write(b);
@@ -62,6 +62,7 @@ public class SafeFileOutputStream extends OutputStream {
   }
 
   @Override
+  @SuppressWarnings("Duplicates")
   public void write(int b) throws IOException {
     try {
       myBackupStream.write(b);
@@ -74,6 +75,7 @@ public class SafeFileOutputStream extends OutputStream {
   }
 
   @Override
+  @SuppressWarnings("Duplicates")
   public void write(byte[] b, int off, int len) throws IOException {
     try {
       myBackupStream.write(b, off, len);
@@ -137,4 +139,4 @@ public class SafeFileOutputStream extends OutputStream {
       throw new IOException(CommonBundle.message("safe.write.drop.temp", oldFile));
     }
   }
-}
+}
\ No newline at end of file
index cc5f42f6af70e44129b93590a995d572dee5cb53..6f31ad03fe02d58a5ace670bf3850feecf77b9e4 100644 (file)
@@ -67,9 +67,16 @@ public class DottedFilterEdgesGenerator {
   // update specified range
   private void update() {
     downWalk();
+    cleanup();
     upWalk();
   }
 
+  private void cleanup() {
+    for (int currentNodeIndex = myUpIndex; currentNodeIndex <= myDownIndex; currentNodeIndex++) {
+      myNumbers.setNumber(currentNodeIndex, Integer.MAX_VALUE);
+    }
+  }
+
   private boolean hasDottedEdges(int nodeIndex, boolean isUp) {
     for (GraphEdge edge : myModification.getEdgesToAdd().getAdjacentEdges(nodeIndex, EdgeFilter.NORMAL_ALL)) {
       if (edge.getType() == DOTTED) {
index 573d1f7dffc929145034e7f77358defd5d3ec522..0e941ce5a183882381f179d287e018ed67e6c683 100644 (file)
@@ -25,6 +25,7 @@ import com.intellij.vcs.log.graph.api.elements.GraphNodeType;
 import com.intellij.vcs.log.graph.api.permanent.PermanentGraphInfo;
 import com.intellij.vcs.log.graph.impl.facade.bek.BekChecker;
 import com.intellij.vcs.log.graph.impl.facade.bek.BekIntMap;
+import com.intellij.vcs.log.graph.impl.permanent.PermanentLinearGraphImpl;
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
 
@@ -39,9 +40,9 @@ public class BekBaseController extends CascadeController {
   public BekBaseController(@NotNull PermanentGraphInfo permanentGraphInfo, @NotNull BekIntMap bekIntMap) {
     super(null, permanentGraphInfo);
     myBekIntMap = bekIntMap;
-    myBekGraph = new BekLinearGraph();
+    myBekGraph = new BekLinearGraph(myBekIntMap, myPermanentGraphInfo.getPermanentLinearGraph());
 
-    assert BekChecker.checkLinearGraph(myBekGraph); // todo drop later
+    BekChecker.checkLinearGraph(myBekGraph);
   }
 
   @NotNull
@@ -85,16 +86,18 @@ public class BekBaseController extends CascadeController {
     return myBekGraph;
   }
 
-  private class BekLinearGraph implements LinearGraph {
-    @NotNull private final LinearGraph myPermanentGraph;
+  public static class BekLinearGraph implements LinearGraph {
+    @NotNull private final LinearGraph myLinearGraph;
+    @NotNull private final BekIntMap myBekIntMap;
 
-    private BekLinearGraph() {
-      myPermanentGraph = myPermanentGraphInfo.getPermanentLinearGraph();
+    public BekLinearGraph(@NotNull BekIntMap bekIntMap, @NotNull LinearGraph linearGraph) {
+      myLinearGraph = linearGraph;
+      myBekIntMap = bekIntMap;
     }
 
     @Override
     public int nodesCount() {
-      return myPermanentGraph.nodesCount();
+      return myLinearGraph.nodesCount();
     }
 
     @Nullable
@@ -107,7 +110,7 @@ public class BekBaseController extends CascadeController {
     @NotNull
     @Override
     public List<GraphEdge> getAdjacentEdges(int nodeIndex, @NotNull EdgeFilter filter) {
-      return map(myPermanentGraph.getAdjacentEdges(myBekIntMap.getUsualIndex(nodeIndex), filter), new Function<GraphEdge, GraphEdge>() {
+      return map(myLinearGraph.getAdjacentEdges(myBekIntMap.getUsualIndex(nodeIndex), filter), new Function<GraphEdge, GraphEdge>() {
         @Override
         public GraphEdge fun(GraphEdge edge) {
           return new GraphEdge(getNodeIndex(edge.getUpNodeIndex()), getNodeIndex(edge.getDownNodeIndex()), edge.getTargetId(),
index f8092d6b503f73b52f878e90f623af3630827565..df2d13e14c0c34f6d415537ef0182e306fa2b62f 100644 (file)
@@ -79,7 +79,7 @@ class BekBranchCreator {
             // almost ok node, except (may be) up nodes
             boolean hasUndoneUpNodes = false;
             for (int upNode : getUpNodes(myPermanentGraph, downNode)) {
-              if (!myDoneNodes.get(upNode) && myGraphLayout.getLayoutIndex(upNode) <= currentLayout) {
+              if (!myDoneNodes.get(upNode) && myGraphLayout.getLayoutIndex(upNode) <= myGraphLayout.getLayoutIndex(downNode)) {
                 hasUndoneUpNodes = true;
                 break;
               }
index b1dcc6a9bdd90cf10745c7d4268b9f35008236b7..6e6cd7e0316ab282623ce75008a36e32da929be9 100644 (file)
 package com.intellij.vcs.log.graph.impl.facade.bek;
 
 import com.intellij.openapi.diagnostic.Logger;
+import com.intellij.openapi.util.Pair;
 import com.intellij.vcs.log.graph.api.LinearGraph;
 import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
 
 import static com.intellij.vcs.log.graph.utils.LinearGraphUtils.getDownNodes;
 import static com.intellij.vcs.log.graph.utils.LinearGraphUtils.getUpNodes;
@@ -25,17 +27,29 @@ import static com.intellij.vcs.log.graph.utils.LinearGraphUtils.getUpNodes;
 public class BekChecker {
   private final static Logger LOG = Logger.getInstance("#com.intellij.vcs.log.graph.impl.facade.bek.BekChecker");
 
-  public static boolean checkLinearGraph(@NotNull LinearGraph linearGraph) {
+  public static void checkLinearGraph(@NotNull LinearGraph linearGraph) {
+    Pair<Integer, Integer> reversedEdge = findReversedEdge(linearGraph);
+    if (reversedEdge != null) {
+      LOG.error("Illegal edge: up node " + reversedEdge.first + ", downNode " + reversedEdge.second);
+    }
+  }
+
+  @Nullable
+  public static Pair<Integer, Integer> findReversedEdge(@NotNull LinearGraph linearGraph) {
     for (int i = 0; i < linearGraph.nodesCount(); i++) {
       for (int downNode : getDownNodes(linearGraph, i)) {
-        if (downNode <= i) LOG.error("Illegal node: " + i + ", with downNode: " + downNode);
+        if (downNode <= i) {
+          return Pair.create(i, downNode);
+        }
       }
 
       for (int upNode : getUpNodes(linearGraph, i)) {
-        if (upNode >= i) LOG.error("Illegal node: " + i + ", with upNode: " + upNode);
+        if (upNode >= i) {
+          return Pair.create(upNode, i);
+        }
       }
     }
-    return true;
+    return null;
   }
 
 }
index b55f3c721e57aa1404ebb85b32553338f84b650d..1e35ca5d9ff017189b3880825baaabbc5777173c 100644 (file)
@@ -59,8 +59,8 @@ public class TestGraphBuilder : BaseTestGraphBuilder {
 
   public fun done(): LinearGraph = TestLinearGraph(nodes)
 
-  public fun Int.invoke(): Unit = newNode(asSimpleNode())
-  public fun Int.invoke(vararg edge: Int): Unit = newNode(asSimpleNode(), edge.asSimpleEdges())
+  public operator fun Int.invoke(): Unit = newNode(asSimpleNode())
+  public operator fun Int.invoke(vararg edge: Int): Unit = newNode(asSimpleNode(), edge.asSimpleEdges())
   public fun Int.invoke(vararg edge: SimpleEdge): Unit = newNode(asSimpleNode(), edge.toList())
   public fun SimpleNode.invoke(): Unit = newNode(this)
   public fun SimpleNode.invoke(vararg edge: Int): Unit = newNode(this, edge.asSimpleEdges())
diff --git a/platform/vcs-log/graph/test/com/intellij/vcs/log/graph/linearBek/BekTest.kt b/platform/vcs-log/graph/test/com/intellij/vcs/log/graph/linearBek/BekTest.kt
new file mode 100644 (file)
index 0000000..5556845
--- /dev/null
@@ -0,0 +1,84 @@
+/*
+ * Copyright 2000-2015 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.vcs.log.graph.linearBek
+
+import com.intellij.vcs.log.graph.TestGraphBuilder
+import org.junit.Test
+
+class BekTest {
+  fun runTest(beforeBekBuilder: TestGraphBuilder.() -> Unit, afterBekBuilder: TestGraphBuilder.() -> Unit) {
+    assertEquals(afterBekBuilder, runBek(beforeBekBuilder))
+  }
+
+  @Test fun ea68497() = runTest({
+    0(1, 3)
+    1(4, 2)
+    2(4, 3)
+    3()
+    4()
+  }, {
+    0(1, 3)
+    1(4, 2)
+    2(4, 3)
+    3()
+    4()
+  })
+
+  @Test fun simpleMerge() = runTest({
+    0(1, 2)
+    1(3)
+    2(4)
+    3(5)
+    4(5)
+    5()
+  }, {
+    0(1, 2)
+    2(4)
+    4(5)
+    1(3)
+    3(5)
+    5()
+  })
+
+  @Test fun twoHeads() = runTest({
+    0(2)
+    1(2)
+    2()
+  }, {
+    1(2)
+    0(2)
+    2()
+  })
+
+  @Test fun simpleMergeWithTwoHeads() = runTest({
+    0(2, 3)
+    1(4)
+    2(4)
+    3(5)
+    4(6)
+    5(6)
+    6()
+  }, {
+    1(4)
+    0(2, 3)
+    3(5)
+    5(6)
+    2(4)
+    4(6)
+    6()
+  })
+}
+
index d9941724beb02d7c988e24d7c97bcea3755eb070..2ae82a4024f1f5433c74b305ae0340cd6e8f1783 100644 (file)
  */
 package com.intellij.vcs.log.graph.linearBek
 
-import com.intellij.vcs.log.graph.utils.TimestampGetter
 import com.intellij.vcs.log.graph.TestGraphBuilder
-import com.intellij.vcs.log.graph.impl.permanent.GraphLayoutBuilder
 import com.intellij.vcs.log.graph.api.LinearGraph
-import com.intellij.vcs.log.graph.graph
-import org.junit.Assert.assertEquals
 import com.intellij.vcs.log.graph.asTestGraphString
+import com.intellij.vcs.log.graph.graph
+import com.intellij.vcs.log.graph.impl.facade.BekBaseController
+import com.intellij.vcs.log.graph.impl.facade.bek.BekChecker
+import com.intellij.vcs.log.graph.impl.facade.bek.BekSorter
+import com.intellij.vcs.log.graph.impl.permanent.GraphLayoutBuilder
 import com.intellij.vcs.log.graph.impl.permanent.GraphLayoutImpl
+import com.intellij.vcs.log.graph.utils.TimestampGetter
+import org.junit.Assert.assertEquals
+import kotlin.test.assertNull
 
 public class DummyTimestampGetter(val nodesCount: Int) : TimestampGetter {
   override fun size(): Int {
@@ -35,7 +39,22 @@ public class DummyTimestampGetter(val nodesCount: Int) : TimestampGetter {
 }
 
 public fun buildLayout(graphBuilder: TestGraphBuilder.() -> Unit): GraphLayoutImpl {
-  return GraphLayoutBuilder.build(graph(graphBuilder), {nodeIndex1, nodeIndex2 -> nodeIndex1 - nodeIndex2 })
+  return GraphLayoutBuilder.build(graph(graphBuilder), { nodeIndex1, nodeIndex2 -> nodeIndex1 - nodeIndex2 })
+}
+
+fun runBek(graphBuilder: TestGraphBuilder.() -> Unit): BekBaseController.BekLinearGraph {
+  val beforeBek = graph(graphBuilder)
+  val beforeLayout = buildLayout(graphBuilder)
+
+  val bekMap = BekSorter.createBekMap(beforeBek, beforeLayout, DummyTimestampGetter(beforeBek.nodesCount()))
+  val afterBek = BekBaseController.BekLinearGraph(bekMap, beforeBek)
+
+  val edge = BekChecker.findReversedEdge(afterBek)
+  if (edge != null) {
+    assertNull(Pair(bekMap.getUsualIndex(edge.first), bekMap.getUsualIndex(edge.second)), "Found reversed edge");
+  }
+
+  return afterBek
 }
 
 public fun runLinearBek(graphBuilder: TestGraphBuilder.() -> Unit): LinearBekGraph {
@@ -49,4 +68,4 @@ public fun runLinearBek(graphBuilder: TestGraphBuilder.() -> Unit): LinearBekGra
 
 public fun assertEquals(expected: TestGraphBuilder.() -> Unit, actual: LinearGraph): Unit {
   assertEquals(graph(expected).asTestGraphString(), actual.asTestGraphString())
-}
\ No newline at end of file
+}
index 9afff78ef6e55f5f3b4d67b45b3ba398c7b17478..65f0aeadde5034a78c8b0ee561d97bfd04f36e77 100644 (file)
@@ -16,6 +16,7 @@
 package com.intellij.xdebugger.impl.actions.handlers;
 
 import com.intellij.lang.Language;
+import com.intellij.lang.LanguageUtil;
 import com.intellij.openapi.actionSystem.CommonDataKeys;
 import com.intellij.openapi.actionSystem.DataContext;
 import com.intellij.openapi.editor.Document;
@@ -36,7 +37,6 @@ import com.intellij.xdebugger.frame.XStackFrame;
 import com.intellij.xdebugger.frame.XValue;
 import com.intellij.xdebugger.impl.breakpoints.XExpressionImpl;
 import com.intellij.xdebugger.impl.evaluate.XDebuggerEvaluationDialog;
-import com.intellij.xdebugger.impl.ui.XDebuggerEditorBase;
 import com.intellij.xdebugger.impl.ui.tree.actions.XDebuggerTreeActionBase;
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
@@ -108,11 +108,11 @@ public class XDebuggerEvaluateActionHandler extends XDebuggerActionHandler {
       if (stackFrame != null) {
         XSourcePosition position = stackFrame.getSourcePosition();
         if (position != null) {
-          language = XDebuggerEditorBase.getFileTypeLanguage(position.getFile().getFileType());
+          language = LanguageUtil.getFileLanguage(position.getFile());
         }
       }
       if (language == null && file != null) {
-        language = XDebuggerEditorBase.getFileTypeLanguage(file.getFileType());
+        language = LanguageUtil.getFileTypeLanguage(file.getFileType());
       }
       expression = new XExpressionImpl(expression.getExpression(), language, expression.getCustomInfo(), expression.getMode());
     }
index 81ac51d233379bd4db93f85e94a29f420a3ad692..a0900ffccb1f2f6643ef85a33bcda00086951c11 100644 (file)
@@ -17,14 +17,13 @@ package com.intellij.xdebugger.impl.ui;
 
 import com.intellij.ide.DataManager;
 import com.intellij.lang.Language;
+import com.intellij.lang.LanguageUtil;
 import com.intellij.openapi.actionSystem.AnAction;
 import com.intellij.openapi.actionSystem.AnActionEvent;
 import com.intellij.openapi.actionSystem.DataContext;
 import com.intellij.openapi.actionSystem.DefaultActionGroup;
 import com.intellij.openapi.editor.Document;
 import com.intellij.openapi.editor.Editor;
-import com.intellij.openapi.fileTypes.FileType;
-import com.intellij.openapi.fileTypes.LanguageFileType;
 import com.intellij.openapi.project.Project;
 import com.intellij.openapi.ui.popup.JBPopupFactory;
 import com.intellij.openapi.ui.popup.ListPopup;
@@ -111,7 +110,7 @@ public abstract class XDebuggerEditorBase {
     }
 
     DataContext dataContext = DataManager.getInstance().getDataContext(getComponent());
-    return JBPopupFactory.getInstance().createActionGroupPopup("Choose language", actions, dataContext,
+    return JBPopupFactory.getInstance().createActionGroupPopup("Choose Language", actions, dataContext,
                                                                JBPopupFactory.ActionSelectionAid.SPEEDSEARCH,
                                                                false);
   }
@@ -156,10 +155,10 @@ public abstract class XDebuggerEditorBase {
     Language language = text.getLanguage();
     if (language == null) {
       if (mySourcePosition != null) {
-        language = getFileTypeLanguage(mySourcePosition.getFile().getFileType());
+        language = LanguageUtil.getFileLanguage(mySourcePosition.getFile());
       }
       if (language == null) {
-        language = getFileTypeLanguage(getEditorsProvider().getFileType());
+        language = LanguageUtil.getFileTypeLanguage(getEditorsProvider().getFileType());
       }
     }
     text = new XExpressionImpl(text.getExpression(), language, text.getCustomInfo(), getMode());
@@ -182,14 +181,6 @@ public abstract class XDebuggerEditorBase {
     doSetText(text);
   }
 
-  @Nullable
-  public static Language getFileTypeLanguage(@Nullable FileType fileType) {
-    if (fileType instanceof LanguageFileType) {
-      return ((LanguageFileType)fileType).getLanguage();
-    }
-    return null;
-  }
-
   public abstract XExpression getExpression();
 
   @Nullable
index ab9056eb86bb5a97327a16b34c1d96da770a01e2..7000ea80c1f4aaebd4dabf926811b3a1aca8db3e 100644 (file)
@@ -193,7 +193,7 @@ class BooleanMethodIsAlwaysInvertedInspectionBase extends GlobalJavaBatchInspect
       if (refElement instanceof RefMethod) {
         final PsiElement element = refElement.getElement();
         if (!(element instanceof PsiMethod)) return;
-        if (((PsiMethod)element).getReturnType() != PsiType.BOOLEAN) return;
+        if (!PsiType.BOOLEAN.equals(((PsiMethod)element).getReturnType())) return;
         refElement.putUserData(ALWAYS_INVERTED, Boolean.TRUE); //initial mark boolean methods
       }
     }
index 144c506728470ff3915dc5aaa10c83e41fc3e7fa..60c761b1e01ea897b9fa8c42b52de0c6c71592be 100644 (file)
@@ -160,7 +160,7 @@ public class UnpredictableBigDecimalConstructorCallInspection
       final PsiParameter[] parameters = parameterList.getParameters();
       final PsiParameter firstParameter = parameters[0];
       final PsiType type = firstParameter.getType();
-      if (type != PsiType.DOUBLE) {
+      if (!PsiType.DOUBLE.equals(type)) {
         return;
       }
     &nbs