Merge remote-tracking branch 'origin/master'
authorDmitry Trofimov <dmitry.trofimov@jetbrains.com>
Thu, 10 Nov 2016 16:35:43 +0000 (17:35 +0100)
committerDmitry Trofimov <dmitry.trofimov@jetbrains.com>
Thu, 10 Nov 2016 16:35:43 +0000 (17:35 +0100)
196 files changed:
RegExpSupport/src/org/intellij/lang/regexp/intention/CheckRegExpForm.java
java/compiler/openapi/src/com/intellij/openapi/compiler/ex/CompilerPathsEx.java
java/debugger/impl/src/com/intellij/debugger/engine/evaluation/expression/LiteralEvaluator.java
java/java-analysis-impl/src/com/intellij/codeInspection/RedundantSuppressInspectionBase.java
java/java-analysis-impl/src/com/intellij/codeInspection/deadCode/UnusedDeclarationInspectionBase.java
java/java-analysis-impl/src/com/intellij/codeInspection/java19modules/Java9NonAccessibleTypeExposedInspection.java
java/java-impl/src/com/intellij/codeInsight/ExpectedTypesProvider.java
java/java-impl/src/com/intellij/codeInsight/intention/impl/config/QuickFixFactoryImpl.java
java/java-impl/src/com/intellij/codeInspection/intermediaryVariable/ReturnSeparatedFromComputationInspection.java
java/java-impl/src/com/intellij/codeInspection/streamMigration/MigrateToStreamFix.java
java/java-impl/src/com/intellij/codeInspection/unusedReturnValue/UnusedReturnValueLocalInspection.java
java/java-impl/src/com/intellij/refactoring/changeSignature/DetectedJavaChangeInfo.java
java/java-impl/src/com/intellij/refactoring/changeSignature/JavaChangeSignatureDetector.java
java/java-impl/src/com/intellij/refactoring/changeSignature/JavaChangeSignatureHandler.java
java/java-impl/src/com/intellij/refactoring/turnRefsToSuper/TurnRefsToSuperProcessorBase.java
java/java-impl/src/com/intellij/testIntegration/createTest/CreateTestAction.java
java/java-impl/src/com/intellij/testIntegration/createTest/CreateTestDialog.java
java/java-psi-impl/src/com/intellij/codeInsight/ExceptionUtil.java
java/java-psi-impl/src/com/intellij/psi/impl/PsiDiamondTypeUtil.java
java/java-tests/testData/refactoring/changeSignatureGesture/DeleteParamInSuperUsed.java
java/java-tests/testData/refactoring/changeSignatureGesture/Modifier.java
java/java-tests/testData/refactoring/changeSignatureGesture/Modifier_after.java [new file with mode: 0644]
java/java-tests/testData/refactoring/changeSignatureGesture/NoUsages_after.java [new file with mode: 0644]
java/java-tests/testData/refactoring/changeSignatureGesture/Simple_after.java
java/java-tests/testSrc/com/intellij/codeInsight/daemon/impl/DaemonRespondToChangesTest.java
java/java-tests/testSrc/com/intellij/codeInspection/Java9NonAccessibleTypeExposedTest.kt
java/java-tests/testSrc/com/intellij/codeInspection/OfflineInspectionResultViewTest.java
java/java-tests/testSrc/com/intellij/codeInspection/ex/InspectionProfileTest.java
java/java-tests/testSrc/com/intellij/refactoring/ChangeSignatureGestureTest.java
java/mockJDK-1.8/jre/lib/rt.jar
java/typeMigration/src/com/intellij/refactoring/typeMigration/rules/guava/GuavaTypeConversionDescriptor.java
json/src/com/jetbrains/jsonSchema/impl/JsonSchemaWalker.java
platform/analysis-api/src/com/intellij/analysis/AnalysisScope.java
platform/analysis-api/src/com/intellij/codeInspection/InspectionProfile.java
platform/analysis-api/src/com/intellij/codeInspection/ModifiableModel.java
platform/analysis-impl/src/com/intellij/codeInsight/daemon/InspectionProfileConvertor.java
platform/analysis-impl/src/com/intellij/codeInspection/ex/InspectionProfile.kt
platform/analysis-impl/src/com/intellij/codeInspection/ex/InspectionProfileImpl.java
platform/analysis-impl/src/com/intellij/codeInspection/ex/InspectionProfileModifiableModel.kt [new file with mode: 0644]
platform/configuration-store-impl/src/FileBasedStorage.kt
platform/core-api/src/com/intellij/openapi/progress/ProgressManager.java
platform/core-api/src/com/intellij/openapi/vfs/VirtualFileManager.java
platform/core-impl/src/com/intellij/openapi/progress/impl/CoreProgressManager.java
platform/core-impl/src/com/intellij/openapi/vfs/impl/VirtualFileManagerImpl.java
platform/indexing-impl/src/com/intellij/psi/impl/search/PsiSearchHelperImpl.java
platform/lang-impl/src/com/intellij/codeInsight/editorActions/enter/EnterBetweenBracesHandler.java
platform/lang-impl/src/com/intellij/codeInspection/actions/CodeInspectionAction.java
platform/lang-impl/src/com/intellij/codeInspection/ex/Descriptor.java
platform/lang-impl/src/com/intellij/codeInspection/ex/DisableInspectionToolAction.java
platform/lang-impl/src/com/intellij/codeInspection/ex/GlobalInspectionContextImpl.java
platform/lang-impl/src/com/intellij/codeInspection/ui/actions/KeyAwareInspectionViewAction.java
platform/lang-impl/src/com/intellij/profile/codeInspection/ui/AdvancedSettingsAction.java
platform/lang-impl/src/com/intellij/profile/codeInspection/ui/SingleInspectionProfilePanel.java
platform/lang-impl/src/com/intellij/profile/codeInspection/ui/ToolDescriptors.java
platform/lang-impl/src/com/intellij/profile/codeInspection/ui/header/InspectionToolsConfigurable.java
platform/lang-impl/src/com/intellij/profile/codeInspection/ui/header/ProfilesChooser.java
platform/lang-impl/src/com/intellij/profile/codeInspection/ui/header/ProfilesComboBox.java
platform/lang-impl/src/com/intellij/psi/impl/source/codeStyle/SemanticEditorPosition.java
platform/lang-impl/src/com/intellij/psi/impl/source/codeStyle/lineIndent/IndentCalculator.java
platform/lang-impl/src/com/intellij/psi/impl/source/codeStyle/lineIndent/JavaLikeLangLineIndentProvider.java
platform/lang-impl/src/com/intellij/refactoring/actions/BaseRefactoringAction.java
platform/lang-impl/src/com/intellij/refactoring/changeSignature/ChangeSignatureDetectorAction.java [deleted file]
platform/lang-impl/src/com/intellij/refactoring/changeSignature/ChangeSignatureGestureDetector.java [deleted file]
platform/lang-impl/src/com/intellij/refactoring/changeSignature/DismissNewSignatureIntentionAction.java [deleted file]
platform/lang-impl/src/com/intellij/refactoring/changeSignature/MoveParameterAction.java [deleted file]
platform/lang-impl/src/com/intellij/refactoring/changeSignature/MoveParameterRightAction.java [deleted file]
platform/lang-impl/src/com/intellij/refactoring/changeSignature/inplace/ApplyChangeSignatureAction.java [new file with mode: 0644]
platform/lang-impl/src/com/intellij/refactoring/changeSignature/inplace/ChangeSignaturePassFactory.java [moved from platform/lang-impl/src/com/intellij/refactoring/changeSignature/ChangeSignaturePassFactory.java with 72% similarity]
platform/lang-impl/src/com/intellij/refactoring/changeSignature/inplace/EscapeHandler.java [new file with mode: 0644]
platform/lang-impl/src/com/intellij/refactoring/changeSignature/inplace/InplaceChangeSignature.java [new file with mode: 0644]
platform/lang-impl/src/com/intellij/refactoring/changeSignature/inplace/LanguageChangeSignatureDetector.java [moved from platform/lang-impl/src/com/intellij/refactoring/changeSignature/LanguageChangeSignatureDetector.java with 50% similarity]
platform/lang-impl/src/com/intellij/refactoring/changeSignature/inplace/LanguageChangeSignatureDetectors.java [moved from platform/lang-impl/src/com/intellij/refactoring/changeSignature/LanguageChangeSignatureDetectors.java with 75% similarity]
platform/lang-impl/src/com/intellij/refactoring/changeSignature/inplace/RenameChangeInfo.java [moved from platform/lang-impl/src/com/intellij/refactoring/changeSignature/RenameChangeInfo.java with 89% similarity]
platform/lang-impl/src/com/intellij/util/indexing/FileBasedIndexImpl.java
platform/platform-impl/src/com/intellij/ide/ClipboardSynchronizer.java
platform/platform-impl/src/com/intellij/openapi/application/ex/ClipboardUtil.java
platform/platform-impl/src/com/intellij/openapi/components/impl/stores/StorageUtil.java
platform/platform-impl/src/com/intellij/openapi/editor/impl/CaretImpl.java
platform/platform-impl/src/com/intellij/openapi/progress/impl/ProgressManagerImpl.java
platform/platform-impl/src/com/intellij/openapi/progress/util/ProgressIndicatorUtils.java
platform/platform-impl/src/com/intellij/openapi/project/impl/ProjectManagerImpl.java
platform/platform-resources/src/META-INF/LangExtensionPoints.xml
platform/platform-resources/src/META-INF/LangExtensions.xml
platform/platform-resources/src/componentSets/Lang.xml
platform/platform-tests/testSrc/com/intellij/concurrency/JobUtilTest.java
platform/platform-tests/testSrc/com/intellij/openapi/progress/impl/ProgressIndicatorTest.java
platform/script-debugger/debugger-ui/src/VariableView.kt
platform/testFramework/src/com/intellij/testFramework/PlatformTestCase.java
platform/util/resources/misc/registry.properties
platform/vcs-api/src/com/intellij/openapi/vcs/QuantitySelection.java
platform/vcs-api/src/com/intellij/openapi/vcs/SelectionManipulation.java [deleted file]
platform/vcs-api/src/com/intellij/openapi/vcs/SelectionResult.java [deleted file]
platform/vcs-api/src/com/intellij/openapi/vcs/SelectionState.java [deleted file]
platform/vcs-api/src/com/intellij/openapi/vcs/versionBrowser/ChangeBrowserSettings.java
platform/vcs-api/src/com/intellij/util/continuation/ContinuationContext.java [deleted file]
platform/vcs-api/src/com/intellij/util/continuation/TaskDescriptor.java [deleted file]
platform/vcs-api/src/com/intellij/util/continuation/Where.java [deleted file]
platform/vcs-impl/src/com/intellij/openapi/vcs/actions/BackgroundTaskGroup.java
platform/vcs-impl/src/com/intellij/openapi/vcs/changes/actions/BrowseChangesAction.java
platform/vcs-impl/src/com/intellij/util/continuation/GeneralRunner.java [deleted file]
platform/vcs-impl/src/com/intellij/util/continuation/SeparatePiecesRunner.java [deleted file]
plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/maturity/ObsoleteCollectionInspection.java
plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/psiutils/ExpectedTypeUtils.java
plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/psiutils/TypeUtils.java
plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/psiutils/WeakestTypeFinder.java
plugins/IntentionPowerPak/src/com/siyeh/ipp/trivialif/ReplaceIfWithConditionalIntention.java
plugins/groovy/groovy-psi/resources/fileTemplates/j2ee/GroovyServerPage.gsp.ft [deleted file]
plugins/groovy/groovy-psi/resources/fileTemplates/j2ee/GroovyServerPage.gsp.html [deleted file]
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/groovydoc/psi/impl/GrDocCommentImpl.java
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/expressions/GrReferenceExpressionImpl.java
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/resolve/GrReferenceResolveRunner.kt [moved from plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/expressions/GrReferenceResolveRunner.kt with 96% similarity]
plugins/groovy/jetgroovy.iml
plugins/groovy/resources/fileTemplates/internal/Gant Script.gant.ft [moved from plugins/groovy/groovy-psi/resources/fileTemplates/j2ee/GantScript.gant.ft with 100% similarity]
plugins/groovy/resources/fileTemplates/internal/Gant Script.gant.html [moved from plugins/groovy/groovy-psi/resources/fileTemplates/j2ee/GantScript.gant.html with 100% similarity]
plugins/groovy/resources/fileTemplates/internal/Groovy Annotation.groovy.ft [moved from plugins/groovy/groovy-psi/resources/fileTemplates/j2ee/GroovyAnnotation.groovy.ft with 100% similarity]
plugins/groovy/resources/fileTemplates/internal/Groovy Annotation.groovy.html [moved from plugins/groovy/groovy-psi/resources/fileTemplates/j2ee/GroovyAnnotation.groovy.html with 100% similarity]
plugins/groovy/resources/fileTemplates/internal/Groovy Class.groovy.ft [moved from plugins/groovy/groovy-psi/resources/fileTemplates/j2ee/GroovyClass.groovy.ft with 100% similarity]
plugins/groovy/resources/fileTemplates/internal/Groovy Class.groovy.html [moved from plugins/groovy/groovy-psi/resources/fileTemplates/j2ee/GroovyClass.groovy.html with 100% similarity]
plugins/groovy/resources/fileTemplates/internal/Groovy DSL Script.gdsl.ft [moved from plugins/groovy/groovy-psi/resources/fileTemplates/j2ee/GroovyDslScript.gdsl.ft with 100% similarity]
plugins/groovy/resources/fileTemplates/internal/Groovy DSL Script.gdsl.html [moved from plugins/groovy/groovy-psi/resources/fileTemplates/j2ee/GroovyDslScript.gdsl.html with 100% similarity]
plugins/groovy/resources/fileTemplates/internal/Groovy Enum.groovy.ft [moved from plugins/groovy/groovy-psi/resources/fileTemplates/j2ee/GroovyEnum.groovy.ft with 100% similarity]
plugins/groovy/resources/fileTemplates/internal/Groovy Enum.groovy.html [moved from plugins/groovy/groovy-psi/resources/fileTemplates/j2ee/GroovyEnum.groovy.html with 100% similarity]
plugins/groovy/resources/fileTemplates/internal/Groovy Interface.groovy.ft [moved from plugins/groovy/groovy-psi/resources/fileTemplates/j2ee/GroovyInterface.groovy.ft with 100% similarity]
plugins/groovy/resources/fileTemplates/internal/Groovy Interface.groovy.html [moved from plugins/groovy/groovy-psi/resources/fileTemplates/j2ee/GroovyInterface.groovy.html with 100% similarity]
plugins/groovy/resources/fileTemplates/internal/Groovy Script.groovy.ft [moved from plugins/groovy/groovy-psi/resources/fileTemplates/j2ee/GroovyScript.groovy.ft with 100% similarity]
plugins/groovy/resources/fileTemplates/internal/Groovy Script.groovy.html [moved from plugins/groovy/groovy-psi/resources/fileTemplates/j2ee/GroovyScript.groovy.html with 100% similarity]
plugins/groovy/resources/fileTemplates/internal/Groovy Trait.groovy.ft [moved from plugins/groovy/groovy-psi/resources/fileTemplates/j2ee/GroovyTrait.groovy.ft with 100% similarity]
plugins/groovy/resources/fileTemplates/internal/Groovy Trait.groovy.html [moved from plugins/groovy/groovy-psi/resources/fileTemplates/j2ee/GroovyTrait.groovy.html with 100% similarity]
plugins/groovy/src/META-INF/groovy-templates.xml [new file with mode: 0644]
plugins/groovy/src/META-INF/plugin.xml
plugins/groovy/src/org/jetbrains/plugins/groovy/actions/GroovyTemplates.java
plugins/groovy/src/org/jetbrains/plugins/groovy/actions/GroovyTemplatesFactory.java
plugins/groovy/src/org/jetbrains/plugins/groovy/gant/GantLoader.java [deleted file]
plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/move/MoveGroovyClassHandler.java
plugins/junit/src/com/intellij/execution/junit2/inspection/JUnitEntryPoint.java
plugins/properties/src/com/intellij/lang/properties/editor/inspections/incomplete/IncompletePropertyInspection.java
plugins/svn4idea/src/org/jetbrains/idea/svn/SvnUtil.java
plugins/svn4idea/src/org/jetbrains/idea/svn/SvnVcs.java
plugins/svn4idea/src/org/jetbrains/idea/svn/dialogs/BasePageEngine.java [deleted file]
plugins/svn4idea/src/org/jetbrains/idea/svn/dialogs/IntersectingLocalChangesPanel.java
plugins/svn4idea/src/org/jetbrains/idea/svn/dialogs/PageEngine.java [deleted file]
plugins/svn4idea/src/org/jetbrains/idea/svn/dialogs/PagedListWithActions.java [deleted file]
plugins/svn4idea/src/org/jetbrains/idea/svn/history/SvnChangeList.java
plugins/svn4idea/src/org/jetbrains/idea/svn/history/SvnCommittedChangesProvider.java
plugins/svn4idea/src/org/jetbrains/idea/svn/integrate/BaseMergeTask.java
plugins/svn4idea/src/org/jetbrains/idea/svn/integrate/ChangeListsMergerFactory.java
plugins/svn4idea/src/org/jetbrains/idea/svn/integrate/CheckRepositorySupportsMergeInfoTask.java [deleted file]
plugins/svn4idea/src/org/jetbrains/idea/svn/integrate/Intersection.java
plugins/svn4idea/src/org/jetbrains/idea/svn/integrate/LoadRecentBranchRevisions.java [deleted file]
plugins/svn4idea/src/org/jetbrains/idea/svn/integrate/LocalChangesPromptTask.java
plugins/svn4idea/src/org/jetbrains/idea/svn/integrate/LookForBranchOriginTask.java
plugins/svn4idea/src/org/jetbrains/idea/svn/integrate/MergeAllOrSelectedChooserTask.java [deleted file]
plugins/svn4idea/src/org/jetbrains/idea/svn/integrate/MergeAllWithBranchCopyPointTask.java [deleted file]
plugins/svn4idea/src/org/jetbrains/idea/svn/integrate/MergeCalculatorTask.java
plugins/svn4idea/src/org/jetbrains/idea/svn/integrate/MergeContext.java
plugins/svn4idea/src/org/jetbrains/idea/svn/integrate/MergeInitChecksTask.java [deleted file]
plugins/svn4idea/src/org/jetbrains/idea/svn/integrate/MergeTask.java
plugins/svn4idea/src/org/jetbrains/idea/svn/integrate/QuickMerge.java
plugins/svn4idea/src/org/jetbrains/idea/svn/integrate/QuickMergeInteraction.java
plugins/svn4idea/src/org/jetbrains/idea/svn/integrate/QuickMergeInteractionImpl.java
plugins/svn4idea/src/org/jetbrains/idea/svn/integrate/SelectMergeItemsResult.java [moved from platform/vcs-api/src/com/intellij/util/continuation/TaskData.java with 50% similarity]
plugins/svn4idea/src/org/jetbrains/idea/svn/integrate/ShelveLocalChangesTask.java [deleted file]
plugins/svn4idea/src/org/jetbrains/idea/svn/integrate/ShowRecentInDialogTask.java [deleted file]
plugins/svn4idea/src/org/jetbrains/idea/svn/integrate/ToBeMergedDialog.java
plugins/svn4idea/src/org/jetbrains/idea/svn/mergeinfo/OneShotMergeInfoHelper.java
plugins/svn4idea/testSource/org/jetbrains/idea/svn/QuickMergeTestInteraction.java
plugins/svn4idea/testSource/org/jetbrains/idea/svn/SvnQuickMergeTest.java
plugins/terminal/lib/jediterm-pty-2.2.jar
python/helpers/pydev/_pydev_bundle/pydev_monkey.py
python/src/META-INF/python-core-common.xml
python/src/com/jetbrains/python/codeInsight/intentions/PyConvertToFStringIntention.java [deleted file]
python/src/com/jetbrains/python/codeInsight/intentions/convertToFString/BaseConvertToFStringProcessor.java [new file with mode: 0644]
python/src/com/jetbrains/python/codeInsight/intentions/convertToFString/NewStyleConvertToFStringProcessor.java [new file with mode: 0644]
python/src/com/jetbrains/python/codeInsight/intentions/convertToFString/OldStyleConvertToFStringProcessor.java [new file with mode: 0644]
python/src/com/jetbrains/python/codeInsight/intentions/convertToFString/PyConvertToFStringIntention.java [new file with mode: 0644]
python/src/com/jetbrains/python/inspections/PyChainedComparisonsInspection.java
python/src/com/jetbrains/python/inspections/PyNewStyleStringFormatParser.java
python/src/com/jetbrains/python/inspections/PyPep8NamingInspection.java
python/src/com/jetbrains/python/inspections/PyShadowingBuiltinsInspection.java
python/src/com/jetbrains/python/inspections/PyStringFormatParser.java
python/src/com/jetbrains/python/inspections/quickfix/AddIgnoredIdentifierQuickFix.java
python/src/com/jetbrains/python/psi/PyStringLiteralUtil.java
python/src/com/jetbrains/python/validation/Pep8ExternalAnnotator.java
python/testData/intentions/PyConvertToFStringIntentionTest/formatMethodItemAccess_after.py
python/testData/intentions/PyConvertToFStringIntentionTest/formatMethodNestedFields.py
python/testData/intentions/PyConvertToFStringIntentionTest/formatMethodNestedFields_after.py
python/testData/intentions/PyConvertToFStringIntentionTest/formatMethodWrapExpressionsInParentheses.py [new file with mode: 0644]
python/testData/intentions/PyConvertToFStringIntentionTest/formatMethodWrapExpressionsInParentheses_after.py [new file with mode: 0644]
python/testData/intentions/PyConvertToFStringIntentionTest/percentOperatorWrapLambdaInParentheses.py [new file with mode: 0644]
python/testData/intentions/PyConvertToFStringIntentionTest/percentOperatorWrapLambdaInParentheses_after.py [new file with mode: 0644]
python/testSrc/com/jetbrains/python/PyStringFormatParserTest.java
python/testSrc/com/jetbrains/python/intentions/PyConvertToFStringIntentionTest.java
xml/tests/src/com/intellij/codeInsight/daemon/quickFix/RealFetchTest.java
xml/xml-analysis-impl/src/com/intellij/xml/util/CollapseTagIntention.java
xml/xml-psi-impl/src/com/intellij/psi/impl/source/resolve/reference/impl/providers/SchemaReferencesProvider.java
xml/xml-psi-impl/src/com/intellij/xml/impl/schema/ComplexTypeDescriptor.java

index 242dae54255b28445ad4a3abbc31e62c562a10ca..9c6b6502d02a2bcdff7598a0edd7575fe9f0016d 100644 (file)
@@ -156,7 +156,7 @@ public class CheckRegExpForm {
       myMessage.setText(correct == null ? "Pattern is too complex" : correct ? "Matches!" : "No match");
       myRootPanel.revalidate();
       Balloon balloon = JBPopupFactory.getInstance().getParentBalloonFor(myRootPanel);
-      if (balloon != null) balloon.revalidate();
+      if (balloon != null && !balloon.isDisposed()) balloon.revalidate();
     });
   }
 
index ebd276c270cbb37bac8224d94be743eba93a3156..adcf39da3d8bce9ff6ae47614bb51d20cf1330bb 100644 (file)
@@ -122,8 +122,19 @@ public class CompilerPathsEx extends CompilerPaths {
     return ArrayUtil.toStringArray(outputPaths);
   }
 
+  /**
+   * Presents .class file in form of {@link File} for files inside output directories or {@link VirtualFile} inside jars for library classes.
+   * Building virtual files for output directories is not feasible for the task and io.File won't work inside jars.
+   */
   public interface ClassFileDescriptor {
+    /**
+     * Loads content of the class file
+     */
     byte[] loadFileBytes() throws IOException;
+
+    /**
+     * Returns system independent path to the class file
+     */
     String getPath();
   }
 
@@ -145,24 +156,17 @@ public class CompilerPathsEx extends CompilerPaths {
         final VirtualFile virtualFile = PsiUtilCore.getVirtualFile(aClass);
         final ProjectFileIndex fileIndex = ProjectRootManager.getInstance(project).getFileIndex();
         if (virtualFile != null && fileIndex.isInLibraryClasses(virtualFile)) {
-          final VirtualFile rootForFile = fileIndex.getClassRootForFile(virtualFile);
-          if (rootForFile != null) {
-            final VirtualFile classFile = rootForFile.findFileByRelativePath("/" + classVMName.replace('.', '/') + ".class");
-            if (classFile != null) {
-              return new ClassFileDescriptor() {
-                @Override
-                public byte[] loadFileBytes() throws IOException {
-                  return classFile.contentsToByteArray();
-                }
-
-                @Override
-                public String getPath() {
-                  return classFile.getPath();
-                }
-              };
+          return new ClassFileDescriptor() {
+            @Override
+            public byte[] loadFileBytes() throws IOException {
+              return virtualFile.contentsToByteArray();
             }
-          }
-          return null;
+
+            @Override
+            public String getPath() {
+              return virtualFile.getPath();
+            }
+          };
         }
       }
       return null;
@@ -196,7 +200,7 @@ public class CompilerPathsEx extends CompilerPaths {
 
       @Override
       public String getPath() {
-        return classFile.getPath();
+        return FileUtil.toSystemIndependentName(classFile.getPath());
       }
     };
   }
index 2182027337945fe7d7bd19cf56e1086a35a32d3e..0754fc7c9d3461964af701d1b9b478411a118035 100644 (file)
@@ -63,10 +63,12 @@ class LiteralEvaluator implements Evaluator {
     }
     if (myValue instanceof String) {
       StringReference str = vm.mirrorOf((String)myValue);
-      // intern
-      Method internMethod = ((ClassType)str.referenceType()).concreteMethodByName("intern", "()Ljava/lang/String;");
-      if (internMethod != null) {
-        return context.getDebugProcess().invokeMethod(context, str, internMethod, Collections.emptyList());
+      // intern starting from jdk 7
+      if (vm.versionHigher("1.7")) {
+        Method internMethod = ((ClassType)str.referenceType()).concreteMethodByName("intern", "()Ljava/lang/String;");
+        if (internMethod != null) {
+          return context.getDebugProcess().invokeMethod(context, str, internMethod, Collections.emptyList());
+        }
       }
       return str;
     }
index 684e555f3c12b3c6fa50e164de03cdd8250ee4fe..cf9e5c769732e74f21827e156deb7e56aa151f1f 100644 (file)
@@ -18,10 +18,7 @@ package com.intellij.codeInspection;
 import com.intellij.analysis.AnalysisScope;
 import com.intellij.codeInsight.daemon.GroupNames;
 import com.intellij.codeInsight.daemon.impl.RemoveSuppressWarningAction;
-import com.intellij.codeInspection.ex.GlobalInspectionContextBase;
-import com.intellij.codeInspection.ex.GlobalInspectionToolWrapper;
-import com.intellij.codeInspection.ex.InspectionToolWrapper;
-import com.intellij.codeInspection.ex.LocalInspectionToolWrapper;
+import com.intellij.codeInspection.ex.*;
 import com.intellij.codeInspection.reference.*;
 import com.intellij.codeInspection.ui.SingleCheckboxOptionsPanel;
 import com.intellij.openapi.diagnostic.Logger;
@@ -303,8 +300,8 @@ public class RedundantSuppressInspectionBase extends GlobalInspectionTool {
   }
 
   protected InspectionToolWrapper[] getInspectionTools(PsiElement psiElement, @NotNull InspectionManager manager) {
-    return InspectionProjectProfileManager.getInstance(manager.getProject()).getCurrentProfile().getModifiableModel()
-      .getInspectionTools(psiElement);
+    // todo for what we create modifiable model here?
+    return new InspectionProfileModifiableModel(InspectionProjectProfileManager.getInstance(manager.getProject()).getCurrentProfile()).getInspectionTools(psiElement);
   }
 
   @Override
index d92bb6da70f2b9691705665a844bdbcbcd850b5c..3ed5933928636775affdf296be92d2132c1a4e58 100644 (file)
@@ -31,9 +31,7 @@ import com.intellij.ide.highlighter.JavaFileType;
 import com.intellij.openapi.application.ApplicationManager;
 import com.intellij.openapi.diagnostic.Logger;
 import com.intellij.openapi.extensions.ExtensionPoint;
-import com.intellij.openapi.extensions.ExtensionPointListener;
 import com.intellij.openapi.extensions.Extensions;
-import com.intellij.openapi.extensions.PluginDescriptor;
 import com.intellij.openapi.progress.ProgressManager;
 import com.intellij.openapi.project.Project;
 import com.intellij.openapi.util.InvalidDataException;
@@ -453,6 +451,7 @@ public class UnusedDeclarationInspectionBase extends GlobalInspectionTool {
     final RefFilter filter = myPhase == 1 ? new StrictUnreferencedFilter(this, globalContext) :
                              new RefUnreachableFilter(this, globalContext);
     final boolean[] requestAdded = {false};
+    LOG.assertTrue(myProcessedSuspicious != null, "phase: " + myPhase);
 
     globalContext.getRefManager().iterate(new RefJavaVisitor() {
       @Override
@@ -726,26 +725,6 @@ public class UnusedDeclarationInspectionBase extends GlobalInspectionTool {
   @Override
   public void initialize(@NotNull GlobalInspectionContext context) {
     super.initialize(context);
-    ExtensionPoint<EntryPoint> point = Extensions.getRootArea().getExtensionPoint(ToolExtensionPoints.DEAD_CODE_TOOL);
-    point.addExtensionPointListener(new ExtensionPointListener<EntryPoint>() {
-      @Override
-      public void extensionAdded(@NotNull final EntryPoint extension, @Nullable PluginDescriptor pluginDescriptor) {
-        boolean alreadyAdded = ContainerUtil.find(myExtensions, point1 -> point1.getClass().equals(extension.getClass())) != null;
-        if (!alreadyAdded) {
-          try {
-            myExtensions.add(extension.clone());
-          }
-          catch (CloneNotSupportedException e) {
-            LOG.error(e);
-          }
-        }
-      }
-
-      @Override
-      public void extensionRemoved(@NotNull final EntryPoint extension, @Nullable PluginDescriptor pluginDescriptor) {
-        ContainerUtil.retainAll(myExtensions, point12 -> !point12.getClass().equals(extension.getClass()));
-      }
-    }, getEntryPointsManager(context));
   }
 
   @TestOnly
index d89687f166e9c3922bcffa1012f41046139a2d86..ab4cdfb2ed1050f0781318c8d23e4813aaf36ada 100644 (file)
@@ -25,6 +25,7 @@ import com.intellij.openapi.roots.ProjectFileIndex;
 import com.intellij.openapi.vfs.VirtualFile;
 import com.intellij.pom.java.LanguageLevel;
 import com.intellij.psi.*;
+import com.intellij.psi.util.PsiTreeUtil;
 import com.intellij.psi.util.PsiUtil;
 import com.intellij.util.containers.ContainerUtil;
 import gnu.trove.THashSet;
@@ -65,6 +66,7 @@ public class Java9NonAccessibleTypeExposedInspection extends BaseJavaLocalInspec
   }
 
   private static class NonAccessibleTypeExposedVisitor extends JavaElementVisitor {
+    public static final String CLASS_IS_NOT_EXPORTED = "The class is not exported from the module";
     private final ProblemsHolder myHolder;
     private final ModuleFileIndex myModuleFileIndex;
     private final Set<String> myExportedPackageNames;
@@ -85,6 +87,12 @@ public class Java9NonAccessibleTypeExposedInspection extends BaseJavaLocalInspec
         for (PsiParameter parameter : method.getParameterList().getParameters()) {
           checkType(parameter.getType(), parameter.getTypeElement());
         }
+        for (PsiJavaCodeReferenceElement referenceElement : method.getThrowsList().getReferenceElements()) {
+          PsiElement resolved = referenceElement.resolve();
+          if (resolved instanceof PsiClass) {
+            checkType((PsiClass)resolved, referenceElement);
+          }
+        }
       }
     }
 
@@ -96,18 +104,46 @@ public class Java9NonAccessibleTypeExposedInspection extends BaseJavaLocalInspec
       }
     }
 
+    @Override
+    public void visitAnnotation(PsiAnnotation annotation) {
+      super.visitAnnotation(annotation);
+      PsiJavaCodeReferenceElement referenceElement = annotation.getNameReferenceElement();
+      if (referenceElement != null) {
+        PsiElement resolved = referenceElement.resolve();
+        if (resolved instanceof PsiClass) {
+          PsiClass annotationClass = (PsiClass)resolved;
+          if (isInModuleSource(annotationClass) && !isModulePublicApi(annotationClass)) {
+            PsiAnnotationOwner owner = annotation.getOwner();
+            if (isModulePublicApi(owner)) {
+              myHolder.registerProblem(referenceElement, CLASS_IS_NOT_EXPORTED);
+            }
+            if (owner instanceof PsiParameter) {
+              PsiElement parent = ((PsiParameter)owner).getParent();
+              if (parent instanceof PsiMember && isModulePublicApi((PsiMember)parent)) {
+                myHolder.registerProblem(referenceElement, CLASS_IS_NOT_EXPORTED);
+              }
+            }
+          }
+        }
+      }
+    }
+
     private void checkType(@Nullable PsiType type, @Nullable PsiTypeElement typeElement) {
       if (typeElement != null) {
         PsiClass psiClass = PsiUtil.resolveClassInType(type);
-        if (psiClass != null && isInModuleSource(psiClass) && !isModulePublicApi(psiClass)) {
-          myHolder.registerProblem(typeElement, "The class is not exported from the module");
-        }
+        checkType(psiClass, typeElement);
+      }
+    }
+
+    private void checkType(PsiClass psiClass, @NotNull PsiElement typeElement) {
+      if (psiClass != null && !(psiClass instanceof PsiTypeParameter) && isInModuleSource(psiClass) && !isModulePublicApi(psiClass)) {
+        myHolder.registerProblem(typeElement, CLASS_IS_NOT_EXPORTED);
       }
     }
 
     @Contract("null -> false")
     private boolean isModulePublicApi(@Nullable PsiMember member) {
-      if (member != null && isModulePublicApiMember(member)) {
+      if (member != null && (member.hasModifierProperty(PsiModifier.PUBLIC) || member.hasModifierProperty(PsiModifier.PROTECTED))) {
         PsiElement parent = member.getParent();
         if (parent instanceof PsiClass) {
           return isModulePublicApi((PsiClass)parent);
@@ -120,12 +156,40 @@ public class Java9NonAccessibleTypeExposedInspection extends BaseJavaLocalInspec
       return false;
     }
 
-    private static boolean isModulePublicApiMember(@NotNull PsiMember member) {
-      if (member.hasModifierProperty(PsiModifier.PUBLIC) || member.hasModifierProperty(PsiModifier.PROTECTED)) {
-        return true;
+    @Contract("null -> false")
+    private boolean isModulePublicApi(@Nullable PsiAnnotationOwner owner) {
+      if (owner instanceof PsiModifierList) {
+        PsiElement parent = ((PsiModifierList)owner).getParent();
+        if (parent instanceof PsiMember) {
+          return isModulePublicApi((PsiMember)parent);
+        }
+        if (parent instanceof PsiParameter) {
+          PsiElement declarationScope = ((PsiParameter)parent).getDeclarationScope();
+          if (declarationScope instanceof PsiMethod) {
+            return isModulePublicApi((PsiMethod)declarationScope);
+          }
+        }
       }
-      PsiClass containingClass = member.getContainingClass();
-      return containingClass != null && containingClass.isInterface();
+      else if (owner instanceof PsiTypeElement) {
+        PsiElement parent = ((PsiTypeElement)owner).getParent();
+        if (parent instanceof PsiMember) {
+          return isModulePublicApi((PsiMember)parent);
+        }
+        if (parent instanceof PsiReferenceParameterList) {
+          PsiMethod method = PsiTreeUtil.getParentOfType(parent, PsiMethod.class);
+          return isModulePublicApi(method);
+        }
+      }
+      else if (owner instanceof PsiTypeParameter) {
+        PsiElement parent = ((PsiTypeParameter)owner).getParent();
+        if (parent instanceof PsiTypeParameterList) {
+          PsiElement grandParent = parent.getParent();
+          if (grandParent instanceof PsiMember) {
+            return isModulePublicApi((PsiMember)grandParent);
+          }
+        }
+      }
+      return false;
     }
 
     private boolean isInModuleSource(@NotNull PsiClass psiClass) {
index 78ecffc5436b6718d5f245851df16189e60fd45a..b90f0b42fb067290aa5e36cb7939d859bdc76631 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2015 JetBrains s.r.o.
+ * Copyright 2000-2016 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.
@@ -33,13 +33,10 @@ import com.intellij.psi.search.GlobalSearchScope;
 import com.intellij.psi.search.PsiShortNamesCache;
 import com.intellij.psi.search.searches.DeepestSuperMethodsSearch;
 import com.intellij.psi.tree.IElementType;
-import com.intellij.psi.util.PropertyUtil;
-import com.intellij.psi.util.PsiTreeUtil;
-import com.intellij.psi.util.PsiUtil;
-import com.intellij.psi.util.TypeConversionUtil;
+import com.intellij.psi.util.*;
 import com.intellij.util.ArrayUtil;
 import com.intellij.util.NullableFunction;
-import com.intellij.util.containers.*;
+import com.intellij.util.containers.ContainerUtil;
 import com.intellij.util.containers.HashMap;
 import com.intellij.util.containers.HashSet;
 import com.intellij.util.containers.Stack;
@@ -1226,13 +1223,14 @@ public class ExpectedTypesProvider {
 
     @NotNull
     private ExpectedTypeInfo[] findClassesWithDeclaredMethod(@NotNull final PsiMethodCallExpression methodCallExpr, final boolean forCompletion) {
+      PsiUtilCore.ensureValid(methodCallExpr);
       final PsiReferenceExpression reference = methodCallExpr.getMethodExpression();
       if (reference.getQualifierExpression() instanceof PsiClassObjectAccessExpression) {
         return ExpectedTypeInfo.EMPTY_ARRAY;
       }
       final PsiManager manager = methodCallExpr.getManager();
       final JavaPsiFacade facade = JavaPsiFacade.getInstance(manager.getProject());
-      final PsiMethod[] methods = myClassProvider.findDeclaredMethods(reference.getManager(), reference.getReferenceName());
+      final PsiMethod[] methods = myClassProvider.findDeclaredMethods(manager, reference.getReferenceName());
       Set<ExpectedTypeInfo> types = new THashSet<>();
       for (PsiMethod method : methods) {
         final PsiClass aClass = method.getContainingClass();
index 58293d42b45ec5de0d8e8b081a3975df9df5adbc..0eeeba2474de3b58eb2891d495edc68691cb0bff 100644 (file)
@@ -54,7 +54,6 @@ import com.intellij.psi.tree.IElementType;
 import com.intellij.psi.util.ClassKind;
 import com.intellij.psi.util.InheritanceUtil;
 import com.intellij.psi.util.PropertyMemberType;
-import com.intellij.refactoring.changeSignature.ChangeSignatureGestureDetector;
 import com.intellij.util.DocumentUtil;
 import com.intellij.util.IncorrectOperationException;
 import org.jetbrains.annotations.NotNull;
@@ -703,14 +702,6 @@ public class QuickFixFactoryImpl extends QuickFixFactory {
   @NotNull
   @Override
   public IntentionAction createSafeDeleteFix(@NotNull PsiElement element) {
-    if (element instanceof PsiMethod) {
-      PsiMethod method = (PsiMethod)element;
-      PsiClass containingClass = method.getContainingClass();
-      if (method.getReturnType() != null || containingClass != null && Comparing.strEqual(containingClass.getName(), method.getName())) {
-        //ignore methods with deleted return types as they are always marked as unused without any reason
-        ChangeSignatureGestureDetector.getInstance(method.getProject()).dismissForElement(method);
-      }
-    }
     return new SafeDeleteFix(element);
   }
 
index d29da4b13488e4c005cdda8bc0dd0e3effe86dc3..fa7c7a6952a2eed3143e966ee20fe2c4d831394c 100644 (file)
@@ -25,6 +25,7 @@ import com.intellij.psi.controlFlow.*;
 import com.intellij.psi.util.PsiTreeUtil;
 import com.intellij.refactoring.util.RefactoringUtil;
 import com.siyeh.ig.psiutils.ExpressionUtils;
+import com.siyeh.ig.psiutils.TypeUtils;
 import gnu.trove.THashMap;
 import gnu.trove.THashSet;
 import org.jetbrains.annotations.Nls;
@@ -60,7 +61,7 @@ public class ReturnSeparatedFromComputationInspection extends BaseJavaBatchLocal
       final PsiCodeBlock returnScope = (PsiCodeBlock)returnParent;
       final PsiStatement[] statements = returnScope.getStatements();
       if (statements.length != 0 && statements[statements.length - 1] == returnStatement) {
-        final PsiType returnType = getReturnType(returnScope);
+        final PsiType returnType = TypeUtils.getMethodReturnType(returnStatement);
         if (returnType != null) {
           PsiStatement refactoredStatement = getPrevNonEmptyStatement(returnStatement, null);
           if (refactoredStatement != null) {
@@ -82,18 +83,6 @@ public class ReturnSeparatedFromComputationInspection extends BaseJavaBatchLocal
     return null;
   }
 
-  @Nullable
-  private static PsiType getReturnType(PsiCodeBlock returnScope) {
-    NavigatablePsiElement returnFrom = PsiTreeUtil.getNonStrictParentOfType(returnScope, PsiMethod.class, PsiLambdaExpression.class);
-    if (returnFrom instanceof PsiMethod) {
-      return ((PsiMethod)returnFrom).getReturnType();
-    }
-    if (returnFrom instanceof PsiLambdaExpression) {
-      return LambdaUtil.getFunctionalInterfaceReturnType((PsiLambdaExpression)returnFrom);
-    }
-    return null;
-  }
-
   @Nullable
   private static PsiCodeBlock getVariableScopeBlock(@Nullable PsiVariable variable) {
     if (variable instanceof PsiLocalVariable) {
@@ -249,8 +238,6 @@ public class ReturnSeparatedFromComputationInspection extends BaseJavaBatchLocal
       returnStatement = (PsiReturnStatement)returnStatement.copy();
       PsiElement lastReturnChild = returnStatement.getLastChild();
       Project project = returnStatement.getProject();
-      PsiParserFacade parserFacade = PsiParserFacade.SERVICE.getInstance(project);
-      PsiElementFactory elementFactory = JavaPsiFacade.getInstance(project).getElementFactory();
       for (PsiComment comment : keptComments) {
         lastReturnChild = returnStatement.addAfter(comment, lastReturnChild);
       }
index 894233d1507372a2f55612a9d4d0938a7044a1e4..74c09d016044c0ec6b0c5fe46fc2f413ac82711d 100644 (file)
@@ -110,39 +110,10 @@ abstract class MigrateToStreamFix implements LocalQuickFix {
   static void simplifyAndFormat(@NotNull Project project, PsiElement result) {
     if (result == null) return;
     LambdaCanBeMethodReferenceInspection.replaceAllLambdasWithMethodReferences(result);
-    removeRedundantTypeArguments(project, result);
+    PsiDiamondTypeUtil.removeRedundantTypeArguments(result);
     CodeStyleManager.getInstance(project).reformat(JavaCodeStyleManager.getInstance(project).shortenClassReferences(result));
   }
 
-  private static void removeRedundantTypeArguments(@NotNull Project project, PsiElement result) {
-    PsiElement[] typedCalls = PsiTreeUtil.collectElements(result, e -> {
-      if (!(e instanceof PsiMethodCallExpression)) return false;
-      PsiMethodCallExpression call = (PsiMethodCallExpression)e;
-      if (call.getTypeArguments().length == 0) return false;
-      PsiMethod method = call.resolveMethod();
-      if (method == null) return false;
-      PsiClass aClass = method.getContainingClass();
-      if (aClass == null) return false;
-      String className = aClass.getQualifiedName();
-      // We remove only those which related to Stream API calls trying to preserve ones which were originally in code
-      return className != null && className.startsWith("java.util.stream.");
-    });
-    for(PsiElement typedCall : typedCalls) {
-      PsiMethodCallExpression call = (PsiMethodCallExpression)typedCall;
-      PsiType[] arguments = call.getTypeArguments();
-      PsiMethod method = call.resolveMethod();
-      if(method != null) {
-        PsiTypeParameter[] parameters = method.getTypeParameters();
-        if(arguments.length == parameters.length &&
-           PsiDiamondTypeUtil.areTypeArgumentsRedundant(arguments, call, false, method, parameters)) {
-          PsiMethodCallExpression expr =
-            (PsiMethodCallExpression)JavaPsiFacade.getInstance(project).getElementFactory().createExpressionFromText("foo()", null);
-          call.getTypeArgumentList().replace(expr.getTypeArgumentList());
-        }
-      }
-    }
-  }
-
   static void restoreComments(PsiLoopStatement loopStatement, PsiStatement body) {
     final PsiElement parent = loopStatement.getParent();
     for (PsiElement comment : PsiTreeUtil.findChildrenOfType(body, PsiComment.class)) {
index 3f41a9007a11be820fca18d5e7aa1bbf475243cc..850e45c9db92ac537e4388e9909c662e469f436c 100644 (file)
@@ -23,6 +23,7 @@ import com.intellij.openapi.progress.EmptyProgressIndicator;
 import com.intellij.patterns.PsiJavaPatterns;
 import com.intellij.psi.*;
 import com.intellij.psi.util.PropertyUtil;
+import com.siyeh.ig.psiutils.MethodUtils;
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
 
@@ -55,7 +56,8 @@ public class UnusedReturnValueLocalInspection extends BaseJavaLocalInspectionToo
     if (method.isConstructor() ||
         PsiType.VOID.equals(method.getReturnType()) ||
         myGlobal.IGNORE_BUILDER_PATTERN && PropertyUtil.isSimplePropertySetter(method) ||
-        method.hasModifierProperty(PsiModifier.NATIVE)) return null;
+        method.hasModifierProperty(PsiModifier.NATIVE) ||
+        MethodUtils.hasSuper(method)) return null;
 
     final boolean[] atLeastOneUsageExists = new boolean[]{false};
     if (UnusedSymbolUtil.processUsages(manager.getProject(), method.getContainingFile(), method, new EmptyProgressIndicator(), null, u -> {
index 4399d8df447d192352dff14d2a1c3539c1082f6c..462de5a8c22e7d3ef700fe6b1ebee482ef3f8e6c 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2015 JetBrains s.r.o.
+ * Copyright 2000-2016 JetBrains s.r.o.
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -19,12 +19,13 @@ import com.intellij.lang.findUsages.DescriptiveNameUtil;
 import com.intellij.openapi.application.ApplicationManager;
 import com.intellij.openapi.command.CommandProcessor;
 import com.intellij.openapi.editor.Document;
+import com.intellij.openapi.project.Project;
 import com.intellij.openapi.util.Comparing;
 import com.intellij.openapi.util.TextRange;
 import com.intellij.psi.*;
-import com.intellij.psi.util.PsiTreeUtil;
 import com.intellij.refactoring.BaseRefactoringProcessor;
 import com.intellij.refactoring.RefactoringBundle;
+import com.intellij.refactoring.changeSignature.inplace.InplaceChangeSignature;
 import com.intellij.refactoring.util.CanonicalTypes;
 import com.intellij.usageView.UsageInfo;
 import com.intellij.util.IncorrectOperationException;
@@ -49,8 +50,8 @@ class DetectedJavaChangeInfo extends JavaChangeInfoImpl {
                          CanonicalTypes.Type newType,
                          @NotNull ParameterInfoImpl[] newParms,
                          ThrownExceptionInfo[] newExceptions,
-                         String newName, String oldName) {
-    super(newVisibility, method, newName, newType, newParms, newExceptions, false, new HashSet<>(), new HashSet<>(), oldName);
+                         String newName, String oldName, final boolean delegate) {
+    super(newVisibility, method, newName, newType, newParms, newExceptions, delegate, new HashSet<>(), new HashSet<>(), oldName);
     final PsiParameter[] parameters = method.getParameterList().getParameters();
     myModifiers = new String[parameters.length];
     for (int i = 0; i < parameters.length; i++) {
@@ -64,28 +65,17 @@ class DetectedJavaChangeInfo extends JavaChangeInfoImpl {
   }
 
   @Nullable
-  static DetectedJavaChangeInfo createFromMethod(PsiMethod method) {
+  static DetectedJavaChangeInfo createFromMethod(PsiMethod method, final boolean delegate) {
     final String newVisibility = VisibilityUtil.getVisibilityModifier(method.getModifierList());
     final PsiType returnType = method.getReturnType();
-    final CanonicalTypes.Type newReturnType;
-    final ParameterInfoImpl[] parameterInfos;
-    try {
-      newReturnType = returnType != null ? CanonicalTypes.createTypeWrapper(returnType) : null;
-      parameterInfos = ParameterInfoImpl.fromMethod(method);
-      for (ParameterInfoImpl parameterInfo : parameterInfos) {
-        if (!parameterInfo.getTypeWrapper().isValid()) {
-          return null;
-        }
-      }
-
-      if (PsiTreeUtil.findChildOfType(method.getParameterList(), PsiErrorElement.class) != null) {
+    final CanonicalTypes.Type newReturnType = returnType != null ? CanonicalTypes.createTypeWrapper(returnType) : null;
+    final ParameterInfoImpl[] parameterInfos = ParameterInfoImpl.fromMethod(method);
+    for (ParameterInfoImpl parameterInfo : parameterInfos) {
+      if (!parameterInfo.getTypeWrapper().isValid()) {
         return null;
       }
     }
-    catch (IncorrectOperationException e) {
-      return null;
-    }
-    final DetectedJavaChangeInfo fromMethod = new DetectedJavaChangeInfo(newVisibility, method, newReturnType, parameterInfos, null, method.getName(), method.getName());
+    final DetectedJavaChangeInfo fromMethod = new DetectedJavaChangeInfo(newVisibility, method, newReturnType, parameterInfos, null, method.getName(), method.getName(), delegate);
     final PsiMethod deepestSuperMethod = method.findDeepestSuperMethod();
     if (deepestSuperMethod != null) {
       if (!deepestSuperMethod.getManager().isInProject(deepestSuperMethod)) return null;
@@ -120,8 +110,8 @@ class DetectedJavaChangeInfo extends JavaChangeInfoImpl {
   }
 
   @Nullable
-  ChangeInfo createNextInfo(final PsiMethod method) {
-    final DetectedJavaChangeInfo fromMethod = createFromMethod(method);
+  DetectedJavaChangeInfo createNextInfo(final PsiMethod method, boolean delegate) {
+    final DetectedJavaChangeInfo fromMethod = createFromMethod(method, delegate);
     if (fromMethod == null) return null;
     if (!this.equals(fromMethod)) {
       if (!createParametersInfo(fromMethod.newParms)) return null;
@@ -144,7 +134,7 @@ class DetectedJavaChangeInfo extends JavaChangeInfoImpl {
 
       try {
         final DetectedJavaChangeInfo javaChangeInfo =
-          new DetectedJavaChangeInfo(newVisibility, method, fromMethod.newReturnType, fromMethod.newParms, getNewExceptions(), method.getName(), getOldName()) {
+          new DetectedJavaChangeInfo(fromMethod.getNewVisibility(), getMethod(), fromMethod.newReturnType, fromMethod.newParms, getNewExceptions(), method.getName(), getOldName(), delegate) {
             @Override
             protected void fillOldParams(PsiMethod method) {
               oldParameterNames = DetectedJavaChangeInfo.this.getOldParameterNames();
@@ -184,7 +174,7 @@ class DetectedJavaChangeInfo extends JavaChangeInfoImpl {
                                                                                         getNewReturnType(),
                                                                                         (ParameterInfoImpl[])getNewParameters(),
                                                                                         getNewExceptions(), getNewName(),
-                                                                                        method.getName()) {
+                                                                                        method.getName(), false) {
       @Override
       protected void fillOldParams(PsiMethod method) {
         super.fillOldParams(method);
@@ -263,14 +253,18 @@ class DetectedJavaChangeInfo extends JavaChangeInfoImpl {
   boolean perform(ChangeInfo initialChangeInfo, final String oldText, boolean silently) {
     final PsiMethod method = getSuperMethod();
 
+    Project project = initialChangeInfo.getMethod().getProject();
     final PsiMethod currentMethod = (PsiMethod)initialChangeInfo.getMethod();
+    final TextRange signatureRange = JavaChangeSignatureDetector.getSignatureRange(currentMethod);
+    final PsiDocumentManager documentManager = PsiDocumentManager.getInstance(project);
+    final Document document = documentManager.getDocument(currentMethod.getContainingFile());
     if (silently || ApplicationManager.getApplication().isUnitTestMode()) {
-      final TextRange signatureRange = JavaChangeSignatureDetector.getSignatureRange(currentMethod);
       final String currentSignature = currentMethod.getContainingFile().getText().substring(signatureRange.getStartOffset(),
                                                                                             signatureRange.getEndOffset());
-      temporallyRevertChanges(currentMethod, oldText);
+      InplaceChangeSignature.temporallyRevertChanges(JavaChangeSignatureDetector.getSignatureRange(currentMethod), document, oldText, project);
       createChangeSignatureProcessor(method).run();
-      temporallyRevertChanges(currentMethod, currentSignature, JavaChangeSignatureDetector.getSignatureRange(currentMethod));
+      InplaceChangeSignature
+        .temporallyRevertChanges(JavaChangeSignatureDetector.getSignatureRange(currentMethod), document, currentSignature, project);
       return true;
     }
     final JavaMethodDescriptor descriptor = new JavaMethodDescriptor(currentMethod) {
@@ -288,7 +282,7 @@ class DetectedJavaChangeInfo extends JavaChangeInfoImpl {
         @Override
         protected void invokeRefactoring(final BaseRefactoringProcessor processor) {
           CommandProcessor.getInstance().executeCommand(myProject, () -> {
-            temporallyRevertChanges(method, oldText);
+            InplaceChangeSignature.temporallyRevertChanges(JavaChangeSignatureDetector.getSignatureRange(currentMethod), document, oldText, project);
             doRefactor(processor);
           }, RefactoringBundle.message("changing.signature.of.0", DescriptiveNameUtil.getDescriptiveName(currentMethod)), null);
         }
@@ -299,22 +293,4 @@ class DetectedJavaChangeInfo extends JavaChangeInfoImpl {
       };
     return dialog.showAndGet();
   }
-
-  private static void temporallyRevertChanges(final PsiElement psiElement, final String oldText) {
-    temporallyRevertChanges(psiElement, oldText, psiElement.getTextRange());
-  }
-
-  private static void temporallyRevertChanges(final PsiElement psiElement,
-                                              final String oldText,
-                                              final TextRange textRange) {
-    ApplicationManager.getApplication().runWriteAction(() -> {
-      final PsiFile file = psiElement.getContainingFile();
-      final PsiDocumentManager documentManager = PsiDocumentManager.getInstance(psiElement.getProject());
-      final Document document = documentManager.getDocument(file);
-      if (document != null) {
-        document.replaceString(textRange.getStartOffset(), textRange.getEndOffset(), oldText);
-        documentManager.commitDocument(document);
-      }
-    });
-  }
 }
index 3307b304c1a89dc0a1fbc6fec388040f38ed14bd..4df9ba000ccf2930f2eed390eaa2d2dfa01897b2 100644 (file)
  */
 package com.intellij.refactoring.changeSignature;
 
-import com.intellij.lang.Language;
-import com.intellij.lang.StdLanguages;
-import com.intellij.openapi.application.Result;
-import com.intellij.openapi.command.WriteCommandAction;
 import com.intellij.openapi.diagnostic.Logger;
-import com.intellij.openapi.editor.Document;
-import com.intellij.openapi.editor.Editor;
 import com.intellij.openapi.project.Project;
 import com.intellij.openapi.util.TextRange;
 import com.intellij.psi.*;
 import com.intellij.psi.util.PsiTreeUtil;
+import com.intellij.refactoring.changeSignature.inplace.LanguageChangeSignatureDetector;
 import org.jetbrains.annotations.NotNull;
-import org.jetbrains.annotations.Nullable;
 
 /**
  * User: anna
  * Date: Sep 6, 2010
  */
-public class JavaChangeSignatureDetector implements LanguageChangeSignatureDetector {
+public class JavaChangeSignatureDetector implements LanguageChangeSignatureDetector<DetectedJavaChangeInfo> {
   private static final Logger LOG = Logger.getInstance("#" + JavaChangeSignatureDetector.class.getName());
 
+  @NotNull
   @Override
-  public ChangeInfo createInitialChangeInfo(final @NotNull PsiElement element) {
-    final PsiMethod method = PsiTreeUtil.getParentOfType(element, PsiMethod.class, false);
-    if (method != null && isInsideMethodSignature(element, method)) {
-      //do not initialize change signature on return type change
-      if (element.getTextRange().getEndOffset() <= method.getTextOffset()) return null;
-      return DetectedJavaChangeInfo.createFromMethod(method);
-    } else {
-      final PsiVariable variable = PsiTreeUtil.getParentOfType(element, PsiVariable.class);
-      if (variable != null) {
-        return new RenameChangeInfo(variable, null) {
-          @Override
-          public Language getLanguage() {
-            return StdLanguages.JAVA;
-          }
-        };
-      }
-    }
-    return null;
+  public DetectedJavaChangeInfo createInitialChangeInfo(final @NotNull PsiElement element) {
+    return DetectedJavaChangeInfo.createFromMethod(PsiTreeUtil.getParentOfType(element, PsiMethod.class), false);
   }
 
   @Override
-  public boolean performChange(final ChangeInfo changeInfo, ChangeInfo initialChangeInfo, @NotNull final String oldText, boolean silently) {
-    if (changeInfo instanceof DetectedJavaChangeInfo) {
-      return ((DetectedJavaChangeInfo)changeInfo).perform(initialChangeInfo, oldText, silently);
-    } else if (changeInfo instanceof RenameChangeInfo) {
-      ((RenameChangeInfo)changeInfo).perform();
-      return true;
-    }
-    return false;
-
+  public void performChange(final DetectedJavaChangeInfo changeInfo, @NotNull final String oldText) {
+    changeInfo.perform(changeInfo, oldText, true);
   }
 
   @Override
-  public boolean isChangeSignatureAvailableOnElement(PsiElement element, ChangeInfo currentInfo) {
-    if (currentInfo instanceof RenameChangeInfo) {
-      final PsiElement nameIdentifier = ((RenameChangeInfo)currentInfo).getNameIdentifier();
-      if (nameIdentifier != null) {
-        final TextRange nameIdentifierTextRange = nameIdentifier.getTextRange();
-        return nameIdentifierTextRange.contains(element.getTextRange()) ||
-               nameIdentifierTextRange.getEndOffset() == element.getTextOffset();
-      }
+  public boolean isChangeSignatureAvailableOnElement(PsiElement element, DetectedJavaChangeInfo currentInfo) {
+    final PsiMethod method = currentInfo.getMethod();
+    TextRange range = method.getTextRange();
+    PsiCodeBlock body = method.getBody();
+    if (body != null) {
+      range = new TextRange(range.getStartOffset(), body.getTextOffset());
     }
-    else if (currentInfo instanceof JavaChangeInfo) {
-      final PsiMethod method = (PsiMethod)currentInfo.getMethod();
-      return getSignatureRange(method).contains(element.getTextRange());
-    }
-    return false;
+    return element.getContainingFile() == method.getContainingFile() && range.contains(element.getTextRange());
   }
 
   @Override
@@ -92,56 +58,28 @@ public class JavaChangeSignatureDetector implements LanguageChangeSignatureDetec
     return PsiTreeUtil.getParentOfType(element, PsiImportList.class) != null;
   }
 
-  @Nullable
   @Override
-  public TextRange getHighlightingRange(ChangeInfo changeInfo) {
-    if (changeInfo == null) return null;
-    if (changeInfo instanceof RenameChangeInfo) {
-      PsiElement nameIdentifier = ((RenameChangeInfo)changeInfo).getNameIdentifier();
-      return nameIdentifier != null ? nameIdentifier.getTextRange() : null;
-    }
-
+  public TextRange getHighlightingRange(@NotNull DetectedJavaChangeInfo changeInfo) {
     PsiElement method = changeInfo.getMethod();
-    return method instanceof PsiMethod ? getSignatureRange((PsiMethod)method) : null;
+    return method != null ? getSignatureRange((PsiMethod)method) : null;
   }
 
-  @Nullable
   @Override
-  public String extractSignature(PsiElement element, @NotNull ChangeInfo initialChangeInfo) {
-    final PsiMethod method = PsiTreeUtil.getParentOfType(element, PsiMethod.class, false);
-    if (method != null && isInsideMethodSignature(element, method) && method == initialChangeInfo.getMethod()) {
-      final TextRange signatureRange = getSignatureRange(method);
-      return signatureRange.shiftRight(-signatureRange.getStartOffset()).substring(method.getText());
-    } else if (element instanceof PsiIdentifier && element.getParent() instanceof PsiNamedElement) {
-      return element.getText();
-    }
-    return null;
-  }
-
-  @Override
-  public ChangeInfo createNextChangeInfo(String signature, @NotNull final ChangeInfo currentInfo, String initialName) {
+  public DetectedJavaChangeInfo createNextChangeInfo(String signature, @NotNull final DetectedJavaChangeInfo currentInfo, boolean delegate) {
     final PsiElement currentInfoMethod = currentInfo.getMethod();
     if (currentInfoMethod == null) {
       return null;
     }
     final Project project = currentInfoMethod.getProject();
-    if (currentInfo instanceof RenameChangeInfo) {
-      return currentInfo;
-    }
-    
-    final PsiMethod oldMethod = (PsiMethod)currentInfo.getMethod();
+
+    final PsiMethod oldMethod = currentInfo.getMethod();
     String visibility = "";
     PsiClass containingClass = oldMethod.getContainingClass();
     if (containingClass != null && containingClass.isInterface()) {
       visibility = PsiModifier.PUBLIC + " ";
     }
     PsiMethod method = JavaPsiFacade.getElementFactory(project).createMethodFromText((visibility + signature).trim(), oldMethod);
-    return ((DetectedJavaChangeInfo)currentInfo).createNextInfo(method);
-  }
-
-  private static boolean isInsideMethodSignature(PsiElement element, @NotNull PsiMethod method) {
-    final TextRange textRange = element.getTextRange();
-    return getSignatureRange(method).contains(textRange);
+    return currentInfo.createNextInfo(method, delegate);
   }
 
   public static TextRange getSignatureRange(PsiMethod method) {
@@ -149,50 +87,4 @@ public class JavaChangeSignatureDetector implements LanguageChangeSignatureDetec
     int startOffset = method.getTextRange().getStartOffset();
     return new TextRange(startOffset, endOffset);
   }
-
-  @Override
-  public boolean isMoveParameterAvailable(PsiElement element, boolean left) {
-    if (element instanceof PsiParameter) {
-      final PsiParameter parameter = (PsiParameter)element;
-      final PsiElement declarationScope = parameter.getDeclarationScope();
-      if (declarationScope instanceof PsiMethod) {
-        final PsiMethod method = (PsiMethod)declarationScope;
-        final int parameterIndex = method.getParameterList().getParameterIndex(parameter);
-        if (left) {
-          return parameterIndex > 0;
-        } else {
-          return parameterIndex < method.getParameterList().getParametersCount() - 1;
-        }
-      }
-    }
-    return false;
-  }
-
-  @Override
-  public void moveParameter(final PsiElement element, final Editor editor, final boolean left) {
-    final PsiParameter parameter = (PsiParameter)element;
-    final PsiMethod method = (PsiMethod)parameter.getDeclarationScope();
-    final int parameterIndex = method.getParameterList().getParameterIndex(parameter);
-    new WriteCommandAction(element.getProject(), MOVE_PARAMETER){
-      @Override
-      protected void run(@NotNull Result result) throws Throwable {
-        final PsiParameterList parameterList = method.getParameterList();
-        final PsiParameter[] parameters = parameterList.getParameters();
-        final int deltaOffset = editor.getCaretModel().getOffset() - parameter.getTextRange().getStartOffset();
-        final PsiParameter frst = left ? parameters[parameterIndex - 1] : parameter;
-        final PsiParameter scnd = left ? parameter : parameters[parameterIndex + 1];
-        final int startOffset = frst.getTextRange().getStartOffset();
-        final int endOffset = scnd.getTextRange().getEndOffset();
-
-        final PsiFile file = method.getContainingFile();
-        final Document document = PsiDocumentManager.getInstance(getProject()).getDocument(file);
-        if (document != null) {
-          final String comma_whitespace_between =
-            document.getText().substring(frst.getTextRange().getEndOffset(), scnd.getTextRange().getStartOffset());
-          document.replaceString(startOffset, endOffset, scnd.getText() + comma_whitespace_between + frst.getText());
-          editor.getCaretModel().moveToOffset(document.getText().indexOf(parameter.getText(), startOffset) + deltaOffset);
-        }
-      }
-    }.execute();
-  }
 }
index fde6c80c178baf8aa63a0d88b1e21f3481516638..d5d47bb8509392e4b4dc0e4566aa4d82689c9bdf 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2013 JetBrains s.r.o.
+ * Copyright 2000-2016 JetBrains s.r.o.
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -19,22 +19,31 @@ import com.intellij.codeInsight.JavaTargetElementEvaluator;
 import com.intellij.ide.util.SuperMethodWarningUtil;
 import com.intellij.openapi.actionSystem.CommonDataKeys;
 import com.intellij.openapi.actionSystem.DataContext;
+import com.intellij.openapi.command.CommandProcessor;
+import com.intellij.openapi.diagnostic.Logger;
 import com.intellij.openapi.editor.Editor;
 import com.intellij.openapi.editor.ScrollType;
 import com.intellij.openapi.project.Project;
 import com.intellij.openapi.ui.DialogWrapper;
+import com.intellij.openapi.util.registry.Registry;
 import com.intellij.psi.*;
 import com.intellij.psi.util.PsiTreeUtil;
 import com.intellij.psi.util.PsiUtil;
 import com.intellij.refactoring.HelpID;
 import com.intellij.refactoring.RefactoringBundle;
 import com.intellij.refactoring.changeClassSignature.ChangeClassSignatureDialog;
+import com.intellij.refactoring.changeSignature.inplace.InplaceChangeSignature;
 import com.intellij.refactoring.util.CommonRefactoringUtil;
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
 
+import java.util.Arrays;
+import java.util.List;
+
 public class JavaChangeSignatureHandler implements ChangeSignatureHandler {
 
+  private static final Logger LOG = Logger.getInstance(JavaChangeSignatureHandler.class);
+
   public void invoke(@NotNull Project project, Editor editor, PsiFile file, DataContext dataContext) {
     editor.getScrollingModel().scrollToCaret(ScrollType.MAKE_VISIBLE);
     PsiElement element = findTargetMember(file, editor);
@@ -45,16 +54,7 @@ public class JavaChangeSignatureHandler implements ChangeSignatureHandler {
   }
 
   private static void invokeOnElement(Project project, @Nullable Editor editor, PsiElement element) {
-    if (element instanceof PsiMethod) {
-      /*final ChangeSignatureGestureDetector detector = ChangeSignatureGestureDetector.getInstance(project);
-      final PsiIdentifier nameIdentifier = ((PsiMethod)element).getNameIdentifier();
-      if (nameIdentifier != null && 
-          editor != null &&
-          editor.getDocument().isWritable() && 
-          detector.isChangeSignatureAvailable(element)) {
-        detector.changeSignature(element.getContainingFile(), false);
-        return;
-      }*/
+    if (element instanceof PsiMethod && ((PsiMethod)element).getNameIdentifier() != null) {
       invoke((PsiMethod) element, project, editor);
     }
     else if (element instanceof PsiClass) {
@@ -92,8 +92,54 @@ public class JavaChangeSignatureHandler implements ChangeSignatureHandler {
     final PsiClass containingClass = method.getContainingClass();
     final PsiReferenceExpression refExpr = editor != null ? JavaTargetElementEvaluator.findReferenceExpression(editor) : null;
     final boolean allowDelegation = containingClass != null && (!containingClass.isInterface() || PsiUtil.isLanguageLevel8OrHigher(containingClass));
-    final DialogWrapper dialog = new JavaChangeSignatureDialog(project, method, allowDelegation, refExpr == null ? method : refExpr);
-    dialog.show();
+    InplaceChangeSignature inplaceChangeSignature = InplaceChangeSignature.getCurrentRefactoring(editor);
+    ChangeInfo initialChange = inplaceChangeSignature != null ? inplaceChangeSignature.getStableChange() : null;
+
+    boolean isInplace = Registry.is("inplace.change.signature") && editor != null && editor.getSettings().isVariableInplaceRenameEnabled() && (initialChange == null || initialChange.getMethod() != method);
+    PsiIdentifier nameIdentifier = method.getNameIdentifier();
+    LOG.assertTrue(nameIdentifier != null);
+    if (isInplace) {
+      CommandProcessor.getInstance().executeCommand(project, () -> new InplaceChangeSignature(project, editor, nameIdentifier), REFACTORING_NAME, null);
+    }
+    else {
+      JavaMethodDescriptor methodDescriptor = new JavaMethodDescriptor(method);
+      if (initialChange != null) {
+        JavaChangeInfo currentInfo = (JavaChangeInfo)inplaceChangeSignature.getCurrentInfo();
+        if (currentInfo != null) {
+          methodDescriptor = new JavaMethodDescriptor(method) {
+            @Override
+            public String getName() {
+              return currentInfo.getNewName();
+            }
+
+            @Override
+            public List<ParameterInfoImpl> getParameters() {
+              return Arrays.asList((ParameterInfoImpl[])currentInfo.getNewParameters());
+            }
+
+            @Override
+            public String getVisibility() {
+              return currentInfo.getNewVisibility();
+            }
+
+
+            @Override
+            public int getParametersCount() {
+              return currentInfo.getNewParameters().length;
+            }
+
+            @Nullable
+            @Override
+            public String getReturnTypeText() {
+              return currentInfo.getNewReturnType().getTypeText();
+            }
+          };
+        }
+        inplaceChangeSignature.cancel();
+      }
+      final DialogWrapper dialog = new JavaChangeSignatureDialog(project, methodDescriptor, allowDelegation, refExpr == null ? method : refExpr);
+      dialog.show();
+    }
   }
 
   private static void invoke(final PsiClass aClass, Editor editor) {
index 9352ed5e62d8c30d0e876dc78ef4f468500a847d..93e268b5c9b0ca85efaae84fd5a511ce5953b17c 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2015 JetBrains s.r.o.
+ * Copyright 2000-2016 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.
@@ -41,10 +41,10 @@ import com.intellij.refactoring.util.MoveRenameUsageInfo;
 import com.intellij.refactoring.util.RefactoringUtil;
 import com.intellij.usageView.UsageInfo;
 import com.intellij.util.IncorrectOperationException;
-import com.intellij.util.Processor;
 import com.intellij.util.containers.HashMap;
 import com.intellij.util.containers.HashSet;
 import com.intellij.util.containers.Queue;
+import com.siyeh.ig.psiutils.TypeUtils;
 import org.jetbrains.annotations.NonNls;
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
@@ -532,9 +532,7 @@ public abstract class TurnRefsToSuperProcessorBase extends BaseRefactoringProces
 
     final PsiElement parent = element.getParent();
     if (parent instanceof PsiReturnStatement) {
-      final PsiElement el = PsiTreeUtil.getParentOfType(parent, PsiMethod.class, PsiLambdaExpression.class);
-      constrainingType = el instanceof PsiMethod ? ((PsiMethod)el).getReturnType() 
-                                                 : el instanceof PsiLambdaExpression ? LambdaUtil.getFunctionalInterfaceReturnType((PsiLambdaExpression)el) : null;
+      constrainingType = TypeUtils.getMethodReturnType(parent);
     }
     else if (parent instanceof PsiAssignmentExpression) {
       constrainingType = ((PsiAssignmentExpression)parent).getLExpression().getType();
index b71c6fe59fe752433dc14d34526ab76ebdf6eb1b..961ad3cde2a8944e50b3098776c85c832b5500f4 100644 (file)
@@ -109,7 +109,7 @@ public class CreateTestAction extends PsiElementBaseIntentionAction {
     PsiDirectory srcDir = element.getContainingFile().getContainingDirectory();
     PsiPackage srcPackage = JavaDirectoryService.getInstance().getPackage(srcDir);
 
-    final PropertiesComponent propertiesComponent = PropertiesComponent.getInstance();
+    final PropertiesComponent propertiesComponent = PropertiesComponent.getInstance(project);
     Module testModule = suggestModuleForTests(project, srcModule);
     final List<VirtualFile> testRootUrls = computeTestRoots(testModule);
     if (testRootUrls.isEmpty() && computeSuitableTestRootUrls(testModule).isEmpty()) {
index cea5da3a37b9ea9d0a9494b207dffaa34f279b4d..c10ad5ffaca444d7453db9640a37bf2e47b27f46 100644 (file)
@@ -493,7 +493,6 @@ public class CreateTestDialog extends DialogWrapper {
       final int result = Messages
         .showOkCancelDialog(myProject, errorMessage + ". Update existing class?", CommonBundle.getErrorTitle(), Messages.getErrorIcon());
       if (result == Messages.CANCEL) {
-        super.close(CANCEL_EXIT_CODE);
         return;
       }
     }
index 9e49fa9455b480700f0ca3990a7b9d15feabee9e..d0e7fc4ba8251d37d1a336039e150739d0212c02 100644 (file)
@@ -454,6 +454,10 @@ public class ExceptionUtil {
       return Collections.emptyList();
     }
 
+    if (properties != null) {
+      PsiUtilCore.ensureValid(method);
+    }
+
     final PsiClassType[] thrownExceptions = method.getThrowsList().getReferencedTypes();
     if (thrownExceptions.length == 0) {
       return Collections.emptyList();
index ef949414ef3915b9d6080f337bf969023d017472..1830a298868938a9173d91582e5467c09752d417 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2015 JetBrains s.r.o.
+ * Copyright 2000-2016 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.
@@ -287,4 +287,33 @@ public class PsiDiamondTypeUtil {
     }
     return true;
   }
+
+  /**
+   * Removes redundant type arguments which appear in any descendants of the supplied element.
+   *
+   * @param element element to start the replacement from
+   */
+  public static void removeRedundantTypeArguments(PsiElement element) {
+    for(PsiNewExpression newExpression : PsiTreeUtil.collectElementsOfType(element, PsiNewExpression.class)) {
+      PsiJavaCodeReferenceElement classReference = newExpression.getClassOrAnonymousClassReference();
+      if(classReference != null && canCollapseToDiamond(newExpression, newExpression, null)) {
+        replaceExplicitWithDiamond(classReference.getParameterList());
+      }
+    }
+    PsiElementFactory factory = JavaPsiFacade.getInstance(element.getProject()).getElementFactory();
+    for(PsiMethodCallExpression call : PsiTreeUtil.collectElementsOfType(element, PsiMethodCallExpression.class)) {
+      PsiType[] arguments = call.getTypeArguments();
+      PsiMethod method = call.resolveMethod();
+      if(method != null) {
+        PsiTypeParameter[] parameters = method.getTypeParameters();
+        if(arguments.length == parameters.length &&
+           areTypeArgumentsRedundant(arguments, call, false, method, parameters)) {
+          PsiMethodCallExpression expr =
+            (PsiMethodCallExpression)factory
+              .createExpressionFromText("foo()", null);
+          call.getTypeArgumentList().replace(expr.getTypeArgumentList());
+        }
+      }
+    }
+  }
 }
index 080e28e0ae2bbdf1760a483a3dd8dcdb75f3c176..4693138c92d311c8782c9518b75ec68a42836999 100644 (file)
@@ -5,7 +5,7 @@ public class Parent {
 }
 
 class Child extends Parent {
-  public void foo(float j, <selection> int i,</selection> String s ) {
+  public void foo(float j, <caret><selection> int i,</selection> String s ) {
   }
 
   void bar() {
index 0fe7f48dc2ea5d277eaf1fb6e44aa2a542a024f6..a00b2b28f4ce6575473c1d33f6d3c3ab800ad101 100644 (file)
@@ -1,4 +1,4 @@
 class Test {
-  <caret> void foo() {
+  <caret>void foo() {
   }
 }
\ No newline at end of file
diff --git a/java/java-tests/testData/refactoring/changeSignatureGesture/Modifier_after.java b/java/java-tests/testData/refactoring/changeSignatureGesture/Modifier_after.java
new file mode 100644 (file)
index 0000000..c61cf44
--- /dev/null
@@ -0,0 +1,4 @@
+class Test {
+  private void foo() {
+  }
+}
\ No newline at end of file
diff --git a/java/java-tests/testData/refactoring/changeSignatureGesture/NoUsages_after.java b/java/java-tests/testData/refactoring/changeSignatureGesture/NoUsages_after.java
new file mode 100644 (file)
index 0000000..c1d60b1
--- /dev/null
@@ -0,0 +1,4 @@
+package refactoring.changeSignatureGesture;
+class Test {
+  private void myverylonagname(int param){}
+}
\ No newline at end of file
index 5cbb7db4d3aa99e0dd77445d1007ce7487f1850f..dc985d8d7ba5a2904a1c5abb9494787d697c73f8 100644 (file)
@@ -1,6 +1,6 @@
 class Test {
-  void foo(int iparam) {
-    System.out.println(iparam);
+  void foo(int i, int param) {
+    System.out.println(i);
   }
   void bar(){foo();}
 }
\ No newline at end of file
index 81f17e2b0dcb3e6dcd056fcffeee8f911e7f3cac..492b99efaf675bb4c2345b36fd103e5a95f56ae4 100644 (file)
@@ -440,8 +440,10 @@ public class DaemonRespondToChangesTest extends DaemonAnalyzerTestCase {
             new DaemonCodeAnalyzer.DaemonListenerAdapter() {
               @Override
               public void daemonCancelEventOccurred(@NotNull String reason) {
-                stopDaemonReason.compareAndSet(null, new RuntimeException("Some bastard's restarted daemon: " + reason + "\nStorage write log: "+
-                                                                          StorageUtil.DEBUG_LOG));
+                RuntimeException e = new RuntimeException("Some bastard's restarted daemon: " + reason +
+                                                          "\nStorage write log: ----------\n" +
+                                                          StorageUtil.DEBUG_LOG +"\n--------------");
+                stopDaemonReason.compareAndSet(null, e);
               }
             });
     try {
index 86965769e8b62583d974501c51e36aad9feabf97..21d34e9e27de4cdc3cd3b205eb99eaf054fe9fea 100644 (file)
@@ -31,9 +31,9 @@ class Java9NonAccessibleTypeExposedTest : LightJava9ModulesCodeInsightFixtureTes
     super.setUp()
     myFixture.enableInspections(Java9NonAccessibleTypeExposedInspection())
     addFile("module-info.java", "module MAIN { exports apiPkg; exports otherPkg; requires M2; }", MAIN)
-    addFile("apiPkg/PublicApi.java", "package apiPkg; public class PublicApi {}", MAIN)
-    addFile("apiPkg/PackageLocal.java", "package apiPkg; class PackageLocal {}", MAIN)
-    addFile("otherPkg/PublicOther.java", "package otherPkg; public class PublicOther {}", MAIN)
+    add("apiPkg", "PublicApi", "public class PublicApi {}")
+    add("apiPkg", "PackageLocal", "class PackageLocal {}")
+    add("otherPkg", "PublicOther", "public class PublicOther {}")
   }
 
   fun testPrimitives() {
@@ -168,7 +168,7 @@ public interface Highlighted {
   }
 
   fun testNotExportedPackage() {
-    addFile("implPkg/NotExported.java", "package implPkg; public class NotExported {}", MAIN)
+    add("implPkg", "NotExported", "public class NotExported {}")
     highlight("""package apiPkg;
 import implPkg.NotExported;
 public class Highlighted {
@@ -182,11 +182,11 @@ public class Highlighted {
   }
 
   fun testDoubleNested() {
-    addFile("apiPkg/PublicOuter.java", """package apiPkg; public class PublicOuter {
+    add("apiPkg", "PublicOuter", """public class PublicOuter {
   static class PackageLocal {
     public class DoubleNested {}
   }
-}""", MAIN)
+}""")
     highlight("""package apiPkg;
 import apiPkg.PublicOuter.PackageLocal;
 public class Highlighted {
@@ -197,9 +197,102 @@ public class Highlighted {
 """)
   }
 
+  fun testThrows() {
+    add("apiPkg", "PublicException", "public class PublicException extends Exception {}")
+    add("apiPkg", "PackageLocalException", "class PackageLocalException extends Exception {}")
+    add("otherPkg", "OtherException", "public class OtherException extends Exception {}")
+    add("implPkg", "NotExportedException", "public class NotExportedException extends Exception {}")
+    highlight("""package apiPkg;
+import otherPkg.*;
+import implPkg.*;
+public class Highlighted {
+  public void throwsPublic() throws PublicException {}
+  public void throwsPackageLocal() throws <warning descr="The class is not exported from the module">PackageLocalException</warning> {}
+  public void throwsOther() throws OtherException {}
+  public void throwsNotExported() throws <warning descr="The class is not exported from the module">NotExportedException</warning> {}
+}
+""")
+  }
+
+  fun testPublicAnnotation() {
+    add("apiPkg", "MyAnnotation", "public @interface MyAnnotation {}")
+    highlight("""package apiPkg;
+@MyAnnotation
+public class Highlighted {
+  @MyAnnotation public PublicApi field;
+  @MyAnnotation public Highlighted() {}
+  public Highlighted(@MyAnnotation PublicApi s) {field=s;}
+  @MyAnnotation protected void init() {}
+  protected @MyAnnotation PublicApi peek() {return field;}
+  public void set(@MyAnnotation PublicApi s) {field=s;}
+}
+""")
+  }
+
+  fun testPackageLocalAnnotation() {
+    add("apiPkg", "MyAnnotation", "@interface MyAnnotation {}")
+    highlight("""package apiPkg;
+@<warning descr="The class is not exported from the module">MyAnnotation</warning>
+public class Highlighted {
+  @<warning descr="The class is not exported from the module">MyAnnotation</warning> public PublicApi field;
+  @<warning descr="The class is not exported from the module">MyAnnotation</warning> public Highlighted() {}
+  public Highlighted(@<warning descr="The class is not exported from the module">MyAnnotation</warning> PublicApi s) {field=s;}
+  @<warning descr="The class is not exported from the module">MyAnnotation</warning> protected void init() {}
+  protected @<warning descr="The class is not exported from the module">MyAnnotation</warning> PublicApi peek() {return field;}
+  public void set(@<warning descr="The class is not exported from the module">MyAnnotation</warning> PublicApi s) {field=s;}
+}
+""")
+  }
+
+  fun testNotExportedAnnotation() {
+    add("implPkg", "MyAnnotation", "public @interface MyAnnotation {}")
+    highlight("""package apiPkg;
+import implPkg.MyAnnotation;
+@<warning descr="The class is not exported from the module">MyAnnotation</warning>
+public class Highlighted {
+  @<warning descr="The class is not exported from the module">MyAnnotation</warning> public PublicApi field;
+  @<warning descr="The class is not exported from the module">MyAnnotation</warning> public Highlighted() {}
+  public Highlighted(@<warning descr="The class is not exported from the module">MyAnnotation</warning> PublicApi s) {field=s;}
+  @<warning descr="The class is not exported from the module">MyAnnotation</warning> protected void init() {}
+  protected @<warning descr="The class is not exported from the module">MyAnnotation</warning> PublicApi peek() {return field;}
+  public void set(@<warning descr="The class is not exported from the module">MyAnnotation</warning> PublicApi s) {field=s;}
+}
+""")
+  }
+
+  fun testTypeParameterAndUseAnnotation() {
+    highlight("""package apiPkg;
+import java.lang.annotation.*;
+import java.util.*;
+@Highlighted.PublicAnnotation
+@<warning descr="The class is not exported from the module">Highlighted.PackageLocalAnnotation</warning>
+public class Highlighted {
+  @Target({ElementType.TYPE_PARAMETER, ElementType.TYPE_USE}) public @interface PublicAnnotation {}
+  @Target({ElementType.TYPE_PARAMETER, ElementType.TYPE_USE}) @interface PackageLocalAnnotation {}
+
+  public class C1<@PublicAnnotation T> {
+    public void foo(Set<@PublicAnnotation String> s) {}
+    protected <@PublicAnnotation X> void bar(X x) {}
+    protected List<@PublicAnnotation T> baz() { return new ArrayList<@PublicAnnotation T>();}
+  }
+  public class C2<@<warning descr="The class is not exported from the module">PackageLocalAnnotation</warning> T> {
+    public void foo(Set<@<warning descr="The class is not exported from the module">PackageLocalAnnotation</warning> String> s) {}
+    protected <@<warning descr="The class is not exported from the module">PackageLocalAnnotation</warning> X> void bar(X x) {}
+    protected List<@<warning descr="The class is not exported from the module">PackageLocalAnnotation</warning> T> baz() {
+      return new ArrayList<@<warning descr="The class is not exported from the module">PackageLocalAnnotation</warning> T>();
+    }
+  }
+}
+""")
+  }
+
   private fun highlight(@Language("JAVA") @NotNull @NonNls text: String) {
     val file = addFile("apiPkg/Highlighted.java", text, MAIN)
     myFixture.configureFromExistingVirtualFile(file)
     myFixture.checkHighlighting()
   }
+
+  private fun add(packageName: String, className: String, @Language("JAVA") @NotNull @NonNls text: String) {
+    addFile("$packageName/$className.java", "package $packageName; $text", MAIN)
+  }
 }
index 321d587b025109edd6511bdcf3056e1c956d0344..ab01e4be08dd4def1117195074b10db04feccba6 100644 (file)
@@ -84,8 +84,8 @@ public class OfflineInspectionResultViewTest extends TestSourceBasedTestCase {
 
       @Override
       @NotNull
-      public InspectionProfileImpl getModifiableModel() {
-        return new InspectionProfileImpl("test") {
+      public InspectionProfileModifiableModel getModifiableModel() {
+        return new InspectionProfileModifiableModel(this) {
           @Override
           @NotNull
           public InspectionToolWrapper[] getInspectionTools(PsiElement element) {
index 32b79b0c0dff2f5c9a380d2e174630ce13155983..de9269ef60a288db1613be383268e9aef7149d9f 100644 (file)
@@ -215,8 +215,7 @@ public class InspectionProfileTest extends LightIdeaTestCase {
                                                   "</profile>");
     InspectionProfileImpl profile = createProfile(new InspectionProfileImpl("foo"));
     profile.readExternal(element);
-    InspectionProfileImpl model = profile.getModifiableModel();
-    model.commit();
+    profile.getModifiableModel().commit();
     assertThat(profile.writeScheme()).isEqualTo(element);
 
 
@@ -239,8 +238,7 @@ public class InspectionProfileTest extends LightIdeaTestCase {
                                                         "   </inspection_tool>\n" +
                                                         "</profile>");
     profile.readExternal(unusedProfile);
-    model = profile.getModifiableModel();
-    model.commit();
+    profile.getModifiableModel().commit();
     assertEquals("<profile version=\"1.0\">\n" +
                  "  <option name=\"myName\" value=\"ToConvert\" />\n" +
                  "  <inspection_tool class=\"UNUSED_SYMBOL\" enabled=\"true\" level=\"WARNING\" enabled_by_default=\"false\">\n" +
@@ -262,13 +260,13 @@ public class InspectionProfileTest extends LightIdeaTestCase {
     //make them default
     profile = createProfile(new InspectionProfileImpl("foo"));
     profile.readExternal(unusedProfile);
-    model = profile.getModifiableModel();
-    InspectionToolWrapper toolWrapper = model.getInspectionTool("unused", getProject());
-    UnusedDeclarationInspectionBase tool = (UnusedDeclarationInspectionBase)toolWrapper.getTool();
-    tool.ADD_NONJAVA_TO_ENTRIES = true;
-    UnusedSymbolLocalInspectionBase inspectionTool = tool.getSharedLocalInspectionTool();
-    inspectionTool.setParameterVisibility(PsiModifier.PUBLIC);
-    model.commit();
+    profile.modifyProfile(it -> {
+      InspectionToolWrapper toolWrapper = it.getInspectionTool("unused", getProject());
+      UnusedDeclarationInspectionBase tool = (UnusedDeclarationInspectionBase)toolWrapper.getTool();
+      tool.ADD_NONJAVA_TO_ENTRIES = true;
+      UnusedSymbolLocalInspectionBase inspectionTool = tool.getSharedLocalInspectionTool();
+      inspectionTool.setParameterVisibility(PsiModifier.PUBLIC);
+    });
     String mergedText = "<profile version=\"1.0\">\n" +
                         "  <option name=\"myName\" value=\"ToConvert\" />\n" +
                         "  <inspection_tool class=\"UNUSED_SYMBOL\" enabled=\"true\" level=\"WARNING\" enabled_by_default=\"false\">\n" +
@@ -297,8 +295,7 @@ public class InspectionProfileTest extends LightIdeaTestCase {
     Element mergedElement = JDOMUtil.loadDocument(mergedText).getRootElement();
     profile = createProfile(new InspectionProfileImpl("foo"));
     profile.readExternal(mergedElement);
-    model = profile.getModifiableModel();
-    model.commit();
+    profile.getModifiableModel().commit();
     assertThat(profile.writeScheme()).isEqualTo(mergedElement);
 
     assertThat(importedProfile.writeScheme()).isEqualTo(mergedElement);
@@ -320,13 +317,13 @@ public class InspectionProfileTest extends LightIdeaTestCase {
                                                "    <option name=\"ADD_NONJAVA_TO_ENTRIES\" value=\"false\" />\n" +
                                                "  </inspection_tool>\n" +
                                                "</profile>").getRootElement());
-    InspectionProfileImpl model = profile.getModifiableModel();
-    InspectionToolWrapper toolWrapper = model.getInspectionTool("unused", getProject());
-    UnusedDeclarationInspectionBase tool = (UnusedDeclarationInspectionBase)toolWrapper.getTool();
-    UnusedSymbolLocalInspectionBase inspectionTool = tool.getSharedLocalInspectionTool();
-    inspectionTool.setClassVisibility(PsiModifier.PUBLIC);
-    inspectionTool.CLASS = false;
-    model.commit();
+    profile.modifyProfile(it -> {
+      InspectionToolWrapper toolWrapper = it.getInspectionTool("unused", getProject());
+      UnusedDeclarationInspectionBase tool = (UnusedDeclarationInspectionBase)toolWrapper.getTool();
+      UnusedSymbolLocalInspectionBase inspectionTool = tool.getSharedLocalInspectionTool();
+      inspectionTool.setClassVisibility(PsiModifier.PUBLIC);
+      inspectionTool.CLASS = false;
+    });
     String mergedText = "<profile version=\"1.0\">\n" +
                         "  <option name=\"myName\" value=\"ToConvert\" />\n" +
                         "  <inspection_tool class=\"unused\" enabled=\"true\" level=\"WARNING\" enabled_by_default=\"true\">\n" +
@@ -506,10 +503,10 @@ public class InspectionProfileTest extends LightIdeaTestCase {
     assertTrue(profile.isToolEnabled(HighlightDisplayKey.find("foo")));
     assertTrue(profile.getToolDefaultState("foo", getProject()).isEnabled());
 
-    InspectionProfileImpl model = profile.getModifiableModel();
-    model.lockProfile(true);
-    model.initInspectionTools(getProject()); // todo commit should take care of initialization
-    model.commit();
+    profile.modifyProfile(it -> {
+      it.lockProfile(true);
+      it.initInspectionTools(getProject()); // todo commit should take care of initialization
+    });
 
     assertEquals("<profile version=\"1.0\" is_locked=\"true\">\n" +
                  "  <option name=\"myName\" value=\"Foo\" />\n" +
@@ -563,13 +560,12 @@ public class InspectionProfileTest extends LightIdeaTestCase {
   }
 
   public void testInspectionsInitialization() throws Exception {
-
     InspectionProfileImpl foo = new InspectionProfileImpl("foo");
     assertEquals(0, countInitializedTools(foo));
     foo.initInspectionTools(getProject());
     assertEquals(0, countInitializedTools(foo));
 
-    InspectionProfileImpl model = foo.getModifiableModel();
+    InspectionProfileModifiableModel model = foo.getModifiableModel();
     assertEquals(0, countInitializedTools(model));
     model.commit();
     assertEquals(0, countInitializedTools(model));
index d04f12b4684e9a65c1a7ef3d042ebd788f035be7..6433ec1cb1f689078bc376dfcb475c4067682be4 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2014 JetBrains s.r.o.
+ * Copyright 2000-2016 JetBrains s.r.o.
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -25,64 +25,62 @@ import com.intellij.openapi.editor.Document;
 import com.intellij.openapi.editor.Editor;
 import com.intellij.openapi.editor.actions.EditorActionUtil;
 import com.intellij.openapi.editor.ex.EditorEx;
-import com.intellij.psi.*;
+import com.intellij.psi.PsiDocumentManager;
+import com.intellij.psi.PsiElement;
+import com.intellij.psi.PsiMethod;
+import com.intellij.psi.PsiTypeElement;
 import com.intellij.psi.util.PsiTreeUtil;
-import com.intellij.refactoring.changeSignature.ChangeSignatureDetectorAction;
-import com.intellij.refactoring.changeSignature.ChangeSignatureGestureDetector;
+import com.intellij.refactoring.changeSignature.ChangeSignatureHandler;
+import com.intellij.refactoring.changeSignature.inplace.ApplyChangeSignatureAction;
+import com.intellij.refactoring.changeSignature.inplace.InplaceChangeSignature;
+import com.intellij.testFramework.PlatformTestCase;
 import com.intellij.testFramework.fixtures.LightCodeInsightFixtureTestCase;
 
-import java.util.List;
+import java.util.Optional;
 
 /**
  * User: anna
  * Date: Sep 9, 2010
  */
+@PlatformTestCase.WrapInCommand
 public class ChangeSignatureGestureTest extends LightCodeInsightFixtureTestCase {
 
-  private void doTest(final Runnable run, boolean shouldShow, final String hint) {
+  private void doTest(final Runnable run, boolean shouldShow) {
     myFixture.configureByFile("/refactoring/changeSignatureGesture/" + getTestName(false) + ".java");
     myFixture.enableInspections(new UnusedDeclarationInspection());
-    final ChangeSignatureGestureDetector detector = ChangeSignatureGestureDetector.getInstance(getProject());
     final EditorEx editor = (EditorEx)myFixture.getEditor();
     final Document document = editor.getDocument();
-    try {
-      PsiManager.getInstance(getProject()).addPsiTreeChangeListener(detector);
-      detector.addDocListener(document);
-      new WriteCommandAction.Simple(getProject()) {
-        @Override
-        protected void run() throws Throwable {
-          run.run();
-        }
-      }.execute().throwException();
-
-
-      myFixture.doHighlighting();
-      if (shouldShow) {
-        final IntentionAction intention = myFixture.findSingleIntention(hint);
-        myFixture.launchAction(intention);
-        myFixture.checkResultByFile("/refactoring/changeSignatureGesture/" + getTestName(false) + "_after.java");
-      }
-      else {
-        final List<IntentionAction> intentionActions = myFixture.filterAvailableIntentions(hint);
-        assertEmpty(intentionActions);
+    CommandProcessor.getInstance().executeCommand(myFixture.getProject(), () -> new InplaceChangeSignature(myFixture.getProject(), editor, myFixture.getFile().findElementAt(myFixture.getCaretOffset())),
+                                                  ChangeSignatureHandler.REFACTORING_NAME, null);
+    new WriteCommandAction.Simple(getProject()) {
+      @Override
+      protected void run() throws Throwable {
+        run.run();
       }
+    }.execute().throwException();
+
+
+    myFixture.doHighlighting();
+    Optional<IntentionAction> intentionAction =
+      myFixture.getAvailableIntentions().stream().filter(action -> action instanceof ApplyChangeSignatureAction).findFirst();
+    if (shouldShow) {
+      final IntentionAction intention = intentionAction.orElse(null);
+      assertNotNull(intention);
+      myFixture.launchAction(intention);
+      myFixture.checkResultByFile("/refactoring/changeSignatureGesture/" + getTestName(false) + "_after.java");
     }
-    finally {
-      detector.removeDocListener(document, editor.getVirtualFile());
-      PsiManager.getInstance(getProject()).removePsiTreeChangeListener(detector);
+    else {
+      assertFalse(intentionAction.isPresent());
     }
   }
 
   public void testSimple() {
-    doTypingTest("param");
+    doTypingTest(", int param");
   }
 
-  public void testSpaces() {
-    doTypingNoBorderTest("   ");
-  }
 
   public void testNoUsages() {
-    doTypingNoBorderTest("int param");
+    doTypingTest("int param");
   }
 
   public void testOccurrencesInSameFile() {
@@ -97,18 +95,6 @@ public class ChangeSignatureGestureTest extends LightCodeInsightFixtureTestCase
     doTypingTest("int param");
   }
 
-  public void testAddParameter2UnusedConstructor() {
-    doTypingNoBorderTest("int param");
-  }
-
-  public void testOnAnotherMethod() {
-    doTest(() -> {
-      myFixture.type("int param");
-      final int nextMethodOffset = ((PsiJavaFile)myFixture.getFile()).getClasses()[0].getMethods()[1].getTextOffset();
-      myFixture.getEditor().getCaretModel().moveToOffset(nextMethodOffset);
-    }, false, ChangeSignatureDetectorAction.CHANGE_SIGNATURE);
-  }
-  
   public void testAddParamChangeReturnType() {
     doTest(() -> {
       myFixture.type("int param");
@@ -125,7 +111,7 @@ public class ChangeSignatureGestureTest extends LightCodeInsightFixtureTestCase
         myFixture.type('\b');
       }
       myFixture.type("boolean");
-    }, true, ChangeSignatureDetectorAction.CHANGE_SIGNATURE);
+    }, true);
   }
 
   public void testNewParam() {
@@ -140,24 +126,12 @@ public class ChangeSignatureGestureTest extends LightCodeInsightFixtureTestCase
     doTypingTest(", int param");
   }
 
-  public void testRenameLocalVariable() {
-    doTypingTest("1", ChangeSignatureDetectorAction.NEW_NAME);
-  }
-
   private void doTypingTest(final String param) {
-    doTypingTest(param, ChangeSignatureDetectorAction.CHANGE_SIGNATURE);
-  }
-
-  private void doTypingTest(final String param, final String hint) {
-    doTest(() -> myFixture.type(param), true, hint);
-  }
-
-  public void testReturnValue() {
-    doTypingNoBorderTest("void");
+    doTest(() -> myFixture.type(param), true);
   }
 
   public void testModifier() {
-    doTypingNoBorderTest("private");
+    doTypingTest("private ");
   }
 
   public void testAddParameterFinal() {
@@ -165,7 +139,7 @@ public class ChangeSignatureGestureTest extends LightCodeInsightFixtureTestCase
   }
 
   private void doTypingNoBorderTest(final String param) {
-    doTest(() -> myFixture.type(param), false, ChangeSignatureDetectorAction.CHANGE_SIGNATURE);
+    doTest(() -> myFixture.type(param), false);
   }
 
   public void testDeleteParamInSuperUsed() {
@@ -187,7 +161,7 @@ public class ChangeSignatureGestureTest extends LightCodeInsightFixtureTestCase
       CommandProcessor.getInstance().setCurrentCommandGroupId(EditorActionUtil.DELETE_COMMAND_GROUP);
       document.deleteString(selectionStart, selectionEnd);
       editor.getCaretModel().moveToOffset(selectionStart);
-    }, true, ChangeSignatureDetectorAction.CHANGE_SIGNATURE);
+    }, true);
   }
 
   @Override
index 6885606d29649dd7080546543cbc1da1de042ab8..e4b9a828fcc343d4ec1503d666a84741305c6b6a 100644 (file)
Binary files a/java/mockJDK-1.8/jre/lib/rt.jar and b/java/mockJDK-1.8/jre/lib/rt.jar differ
index 1be36aa6d44729c5d117e3515bcab2bc1eb03caa..9c99cbf255803db047496af6b04db350df4450f3 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2015 JetBrains s.r.o.
+ * Copyright 2000-2016 JetBrains s.r.o.
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -17,12 +17,12 @@ package com.intellij.refactoring.typeMigration.rules.guava;
 
 import com.intellij.openapi.diagnostic.Logger;
 import com.intellij.psi.*;
-import com.intellij.psi.util.PsiTreeUtil;
 import com.intellij.psi.util.PsiTypesUtil;
 import com.intellij.refactoring.typeMigration.TypeConversionDescriptor;
 import com.intellij.refactoring.typeMigration.TypeEvaluator;
 import com.intellij.util.ArrayUtil;
 import com.intellij.util.IncorrectOperationException;
+import com.siyeh.ig.psiutils.TypeUtils;
 import org.jetbrains.annotations.NonNls;
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
@@ -64,15 +64,7 @@ public class GuavaTypeConversionDescriptor extends TypeConversionDescriptor {
       return isIterable(((PsiLocalVariable)parent).getType());
     }
     else if (parent instanceof PsiReturnStatement) {
-      final PsiElement methodOrLambda = PsiTreeUtil.getParentOfType(parent, PsiMethod.class, PsiLambdaExpression.class);
-      PsiType methodReturnType = null;
-      if (methodOrLambda instanceof PsiMethod) {
-        methodReturnType = ((PsiMethod)methodOrLambda).getReturnType();
-      }
-      else if (methodOrLambda instanceof PsiLambdaExpression) {
-        methodReturnType = LambdaUtil.getFunctionalInterfaceReturnType((PsiFunctionalExpression)methodOrLambda);
-      }
-      return isIterable(methodReturnType);
+      return isIterable(TypeUtils.getMethodReturnType(parent));
     }
     else if (parent instanceof PsiExpressionList) {
       final PsiExpressionList expressionList = (PsiExpressionList)parent;
index aba049f9b0d70c4e3f08c835f77d95057d0d66c0..fe099762cedd306e3be71d9dff300d595389b8a1 100644 (file)
@@ -99,7 +99,8 @@ public class JsonSchemaWalker {
           }
         }
         if (selectedSchema != null) {
-          queue.add(Pair.create(selectedSchema, pair.getSecond() + 1));
+          if ((pair.getSecond() + 1) >= position.size()) consumer.consume(isName, selectedSchema);
+          else queue.add(Pair.create(selectedSchema, pair.getSecond() + 1));
         }
       } else {
         List<JsonSchemaObject> list = new ArrayList<>();
index e7fdcd4b04ee99287a09d1c80b9a5665461eb835..5ba911e578242e8ec460937d70336ab889d6174a 100644 (file)
@@ -643,6 +643,7 @@ public class AnalysisScope {
 
   @NotNull
   public SearchScope toSearchScope() {
+    ApplicationManager.getApplication().assertReadAccessAllowed();
     switch (myType) {
       case CUSTOM:
         return myScope;
index a3de468837b7948bfa9d0a1c8ebfca9acc70460e..0cd11db2e06205f963f64f8a522c69cfc619ecc2 100644 (file)
@@ -24,7 +24,6 @@ import com.intellij.openapi.project.Project;
 import com.intellij.openapi.util.Key;
 import com.intellij.psi.PsiElement;
 import com.intellij.util.Consumer;
-import com.intellij.util.xmlb.annotations.Transient;
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
 
@@ -35,11 +34,6 @@ import java.util.List;
  * Date: Dec 7, 2004
  */
 public interface InspectionProfile extends Comparable {
-  @Transient
-  boolean isProjectLevel();
-
-  void setProjectLevel(boolean isProjectLevel);
-
   void setName(@NotNull String name);
 
   @NotNull
@@ -65,8 +59,6 @@ public interface InspectionProfile extends Comparable {
   <T extends InspectionProfileEntry>
   T getUnwrappedTool(@NotNull Key<T> shortNameKey, @NotNull PsiElement element);
 
-  void modifyProfile(@NotNull Consumer<ModifiableModel> modelConsumer);
-
   /**
    * Allows a plugin to modify the settings of the inspection tool with the specified ID programmatically, without going through
    * the settings dialog.
@@ -88,12 +80,6 @@ public interface InspectionProfile extends Comparable {
 
   void cleanup(@NotNull Project project);
 
-  /**
-   * @see #modifyProfile(com.intellij.util.Consumer)
-   */
-  @NotNull
-  ModifiableModel getModifiableModel();
-
   boolean isToolEnabled(@Nullable HighlightDisplayKey key, PsiElement element);
 
   boolean isToolEnabled(@Nullable HighlightDisplayKey key);
index a638975c2fd40ca36f21bf386cc96ad2474ca62f..fa2619335b41d7c59c1a7a2b2bc6a4d853f1533a 100644 (file)
@@ -30,9 +30,6 @@ import org.jetbrains.annotations.Nullable;
  * Date: 15-Feb-2006
  */
 public interface ModifiableModel extends InspectionProfile {
-
-  InspectionProfile getParentProfile();
-
   void enableTool(@NotNull String inspectionTool, NamedScope namedScope, Project project);
 
   void setErrorLevel(HighlightDisplayKey key, @NotNull HighlightDisplayLevel level, Project project);
@@ -46,16 +43,6 @@ public interface ModifiableModel extends InspectionProfile {
   @Override
   boolean isToolEnabled(@Nullable HighlightDisplayKey key, @Nullable PsiElement element);
 
-  boolean isChanged();
-
-  void setModified(final boolean toolsSettingsChanged);
-
-  boolean isProperSetting(@NotNull String toolId);
-
-  void resetToBase(@Nullable Project project);
-
-  void resetToEmpty(Project project);
-
   @Override
   InspectionProfileEntry getUnwrappedTool(@NotNull String shortName, @NotNull PsiElement element);
 
@@ -67,10 +54,6 @@ public interface ModifiableModel extends InspectionProfile {
    */
   void setSingleTool(@NotNull String toolShortName);
 
-  boolean isProfileLocked();
-
-  void lockProfile(boolean isLocked);
-
   void disableTool(@NotNull String toolId, @NotNull PsiElement element);
 
   void disableTool(@NotNull String inspectionTool, @Nullable Project project);
index b5500122fbfe596bc4d5aaed1516c0893542efd4..f4e496ee3428239ce25346d9e892732b38020913 100644 (file)
@@ -17,7 +17,6 @@ package com.intellij.codeInsight.daemon;
 
 import com.intellij.codeHighlighting.HighlightDisplayLevel;
 import com.intellij.codeInspection.ex.InspectionProfileImpl;
-import com.intellij.codeInspection.ex.InspectionToolWrapper;
 import com.intellij.lang.annotation.HighlightSeverity;
 import com.intellij.openapi.application.PathManager;
 import com.intellij.openapi.diagnostic.Logger;
@@ -89,9 +88,7 @@ public class InspectionProfileConvertor {
 
   public void storeEditorHighlightingProfile(@NotNull Element element, @NotNull InspectionProfileImpl editorProfile) {
     if (retrieveOldSettings(element)) {
-      InspectionProfileImpl editorProfileModel = editorProfile.getModifiableModel();
-      fillErrorLevels(editorProfileModel);
-      editorProfileModel.commit();
+      editorProfile.modifyProfile(it -> fillErrorLevels(it));
     }
   }
 
@@ -122,8 +119,8 @@ public class InspectionProfileConvertor {
   }
 
   protected void fillErrorLevels(final InspectionProfileImpl profile) {
-    InspectionToolWrapper[] toolWrappers = profile.getInspectionTools(null);
-    LOG.assertTrue(toolWrappers != null, "Profile was not correctly init");
+    //noinspection ConstantConditions
+    LOG.assertTrue(profile.getInspectionTools(null) != null, "Profile was not correctly init");
     //fill error levels
     for (final String shortName : myDisplayLevelMap.keySet()) {
       //key <-> short name
index 974cebc661c738dd8dcfd5e6a86b22e96222a096..daa91cf11a6e0fb9671ca2404d7f011967ae35d0 100644 (file)
@@ -15,7 +15,7 @@
  */
 package com.intellij.codeInspection.ex
 
-import com.intellij.codeInspection.ModifiableModel
+import com.intellij.codeInspection.InspectionProfile
 import com.intellij.configurationStore.SerializableScheme
 import com.intellij.openapi.application.ApplicationManager
 import com.intellij.openapi.components.PathMacroManager
@@ -24,13 +24,13 @@ import com.intellij.profile.codeInspection.BaseInspectionProfileManager
 import com.intellij.profile.codeInspection.ProjectInspectionProfileManager
 import com.intellij.util.xmlb.annotations.Transient
 
-abstract class NewInspectionProfile(name: String, private var profileManager: BaseInspectionProfileManager) : ProfileEx(name), ModifiableModel, SerializableScheme {
+abstract class NewInspectionProfile(name: String, private var profileManager: BaseInspectionProfileManager) : ProfileEx(name), InspectionProfile, SerializableScheme {
   private var isProjectLevel: Boolean = false
 
   @Transient
-  override fun isProjectLevel() = isProjectLevel
+  fun isProjectLevel() = isProjectLevel
 
-  override fun setProjectLevel(value: Boolean) {
+  fun setProjectLevel(value: Boolean) {
     isProjectLevel = value
   }
 
@@ -44,7 +44,6 @@ abstract class NewInspectionProfile(name: String, private var profileManager: Ba
   protected val pathMacroManager: PathMacroManager
     get() {
       val profileManager = profileManager
-      return PathMacroManager.getInstance(
-          if (profileManager is ProjectInspectionProfileManager) profileManager.project else ApplicationManager.getApplication())
+      return PathMacroManager.getInstance((profileManager as? ProjectInspectionProfileManager)?.project ?: ApplicationManager.getApplication())
     }
 }
\ No newline at end of file
index f11940a22a8b193a5f439ca316b1513d4646f617..0b2363aad4631c2683ccebd5eb2ce165a6df1a80 100644 (file)
@@ -19,7 +19,6 @@ import com.intellij.codeHighlighting.HighlightDisplayLevel;
 import com.intellij.codeInsight.daemon.HighlightDisplayKey;
 import com.intellij.codeInspection.InspectionEP;
 import com.intellij.codeInspection.InspectionProfileEntry;
-import com.intellij.codeInspection.ModifiableModel;
 import com.intellij.configurationStore.SchemeDataHolder;
 import com.intellij.lang.annotation.HighlightSeverity;
 import com.intellij.openapi.application.ApplicationManager;
@@ -35,7 +34,6 @@ import com.intellij.psi.PsiElement;
 import com.intellij.psi.search.scope.packageSet.NamedScope;
 import com.intellij.util.ArrayUtil;
 import com.intellij.util.Consumer;
-import com.intellij.util.containers.ContainerUtil;
 import com.intellij.util.graph.CachingSemiGraph;
 import com.intellij.util.graph.DFSTBuilder;
 import com.intellij.util.graph.GraphGenerator;
@@ -58,42 +56,29 @@ import java.util.*;
 public class InspectionProfileImpl extends NewInspectionProfile {
   @NonNls static final String INSPECTION_TOOL_TAG = "inspection_tool";
   @NonNls static final String CLASS_TAG = "class";
-  private static final Logger LOG = Logger.getInstance("#com.intellij.codeInspection.ex.InspectionProfileImpl");
+  protected static final Logger LOG = Logger.getInstance("#com.intellij.codeInspection.ex.InspectionProfileImpl");
   @NonNls private static final String VALID_VERSION = "1.0";
   @NonNls private static final String VERSION_TAG = "version";
   @NonNls private static final String USED_LEVELS = "used_levels";
   public static final String DEFAULT_PROFILE_NAME = "Default";
   @TestOnly
   public static boolean INIT_INSPECTIONS = false;
-  private final InspectionToolRegistrar myRegistrar;
-  @NotNull
-  private final Map<String, Element> myUninitializedSettings = new TreeMap<>();
-  protected InspectionProfileImpl mySource;
-  private Map<String, ToolsImpl> myTools = new THashMap<>();
-  private volatile Set<String> myChangedToolNames;
+  protected final InspectionToolRegistrar myRegistrar;
+  protected final Map<String, Element> myUninitializedSettings = new TreeMap<>();
+  protected Map<String, ToolsImpl> myTools = new THashMap<>();
+  protected volatile Set<String> myChangedToolNames;
   @Attribute("is_locked")
-  private boolean myLockedProfile;
-  private final InspectionProfileImpl myBaseProfile;
+  protected boolean myLockedProfile;
+  protected final InspectionProfileImpl myBaseProfile;
   private volatile String myToolShortName = null;
   private String[] myScopesOrder;
   private String myDescription;
-  private boolean myModified;
   private volatile boolean myInitialized;
 
   private final Object myLock = new Object();
 
   private SchemeDataHolder<? super InspectionProfileImpl> myDataHolder;
 
-  InspectionProfileImpl(@NotNull InspectionProfileImpl inspectionProfile) {
-    this(inspectionProfile.getName(), inspectionProfile.myRegistrar, inspectionProfile.getProfileManager(), inspectionProfile.myBaseProfile, null);
-    myUninitializedSettings.putAll(inspectionProfile.myUninitializedSettings);
-
-    setProjectLevel(inspectionProfile.isProjectLevel());
-    myLockedProfile = inspectionProfile.myLockedProfile;
-    mySource = inspectionProfile;
-    copyFrom(inspectionProfile);
-  }
-
   public InspectionProfileImpl(@NotNull String profileName,
                                @NotNull InspectionToolRegistrar registrar,
                                @NotNull BaseInspectionProfileManager profileManager) {
@@ -157,7 +142,7 @@ public class InspectionProfileImpl extends NewInspectionProfile {
   }
 
   @NotNull
-  private static InspectionToolWrapper copyToolSettings(@NotNull InspectionToolWrapper toolWrapper) {
+  protected static InspectionToolWrapper copyToolSettings(@NotNull InspectionToolWrapper toolWrapper) {
     final InspectionToolWrapper inspectionTool = toolWrapper.createCopy();
     if (toolWrapper.isInitialized()) {
       Element config = new Element("config");
@@ -172,42 +157,6 @@ public class InspectionProfileImpl extends NewInspectionProfile {
     return InspectionProfileImplHolder.DEFAULT_PROFILE;
   }
 
-  @Override
-  public void setModified(final boolean modified) {
-    myModified = modified;
-  }
-
-  @Override
-  public InspectionProfileImpl getParentProfile() {
-    return mySource;
-  }
-
-  @Override
-  @SuppressWarnings({"SimplifiableIfStatement"})
-  public boolean isChanged() {
-    if (mySource != null && mySource.myLockedProfile != myLockedProfile) return true;
-    return myModified;
-  }
-
-  @Override
-  public boolean isProperSetting(@NotNull String toolId) {
-    if (myBaseProfile != null) {
-      final Tools tools = myBaseProfile.getTools(toolId, null);
-      final Tools currentTools = myTools.get(toolId);
-      return !Comparing.equal(tools, currentTools);
-    }
-    return false;
-  }
-
-  @Override
-  public void resetToBase(@Nullable Project project) {
-    initInspectionTools(project);
-
-    copyToolsConfigurations(myBaseProfile, project);
-    myChangedToolNames = null;
-  }
-
-  @Override
   public void resetToEmpty(Project project) {
     initInspectionTools(project);
     final InspectionToolWrapper[] profileEntries = getInspectionTools(null);
@@ -408,11 +357,11 @@ public class InspectionProfileImpl extends NewInspectionProfile {
     return (T) getUnwrappedTool(shortNameKey.toString(), element);
   }
 
-  @Override
-  public void modifyProfile(@NotNull Consumer<ModifiableModel> modelConsumer) {
-    InspectionProfileImpl model = getModifiableModel();
-    modelConsumer.consume(model);
-    model.commit();
+  public void modifyProfile(@NotNull Consumer<InspectionProfileModifiableModel> modelConsumer) {
+    InspectionProfileModifiableModelKt.edit(this, it -> {
+      modelConsumer.consume(it);
+      return null;
+    });
   }
 
   @Override
@@ -464,7 +413,6 @@ public class InspectionProfileImpl extends NewInspectionProfile {
     return myToolShortName;
   }
 
-  @Override
   public void setSingleTool(@NotNull final String toolShortName) {
     myToolShortName = toolShortName;
   }
@@ -483,13 +431,11 @@ public class InspectionProfileImpl extends NewInspectionProfile {
     getProfileManager().fireProfileChanged(this);
   }
 
-  @Override
   @Transient
   public boolean isProfileLocked() {
     return myLockedProfile;
   }
 
-  @Override
   public void lockProfile(boolean isLocked) {
     myLockedProfile = isLocked;
   }
@@ -518,7 +464,6 @@ public class InspectionProfileImpl extends NewInspectionProfile {
     return result;
   }
 
-  @Override
   public void disableTool(@NotNull String toolId, @NotNull PsiElement element) {
     getTools(toolId, element.getProject()).disableTool(element);
   }
@@ -557,6 +502,11 @@ public class InspectionProfileImpl extends NewInspectionProfile {
     }
   }
 
+  @NotNull
+  protected List<InspectionToolWrapper> createTools(@Nullable Project project) {
+    return myRegistrar.createTools();
+  }
+
   private void initialize(@Nullable Project project) {
     SchemeDataHolder<? super InspectionProfileImpl> dataHolder = myDataHolder;
     if (dataHolder != null) {
@@ -575,12 +525,7 @@ public class InspectionProfileImpl extends NewInspectionProfile {
 
     final List<InspectionToolWrapper> tools;
     try {
-      if (mySource == null) {
-        tools = myRegistrar.createTools();
-      }
-      else {
-        tools = ContainerUtil.map(mySource.getDefaultStates(project), ScopeToolState::getTool);
-      }
+      tools = createTools(project);
     }
     catch (ProcessCanceledException ignored) {
       return;
@@ -606,9 +551,7 @@ public class InspectionProfileImpl extends NewInspectionProfile {
       myScopesOrder = ArrayUtil.toStringArray(builder.getSortedNodes());
     }
 
-    if (mySource != null) {
-      copyToolsConfigurations(mySource, project);
-    }
+    copyToolsConfigurations(project);
 
     myInitialized = true;
     if (dataHolder != null) {
@@ -617,6 +560,9 @@ public class InspectionProfileImpl extends NewInspectionProfile {
     }
   }
 
+  protected void copyToolsConfigurations(@Nullable Project project) {
+  }
+
   public void addTool(@Nullable Project project, @NotNull InspectionToolWrapper toolWrapper, @NotNull Map<String, List<String>> dependencies) {
     final String shortName = toolWrapper.getShortName();
     HighlightDisplayKey key = HighlightDisplayKey.find(shortName);
@@ -707,41 +653,10 @@ public class InspectionProfileImpl extends NewInspectionProfile {
     return tools.getLevel();
   }
 
-  @Override
   @NotNull
-  public InspectionProfileImpl getModifiableModel() {
-    return new InspectionProfileImpl(this);
-  }
-
-  private void copyToolsConfigurations(@NotNull InspectionProfileImpl profile, @Nullable Project project) {
-    try {
-      for (ToolsImpl toolList : profile.myTools.values()) {
-        final ToolsImpl tools = myTools.get(toolList.getShortName());
-        final ScopeToolState defaultState = toolList.getDefaultState();
-        tools.setDefaultState(copyToolSettings(defaultState.getTool()), defaultState.isEnabled(), defaultState.getLevel());
-        tools.removeAllScopes();
-        final List<ScopeToolState> nonDefaultToolStates = toolList.getNonDefaultTools();
-        if (nonDefaultToolStates != null) {
-          for (ScopeToolState state : nonDefaultToolStates) {
-            final InspectionToolWrapper toolWrapper = copyToolSettings(state.getTool());
-            final NamedScope scope = state.getScope(project);
-            if (scope != null) {
-              tools.addTool(scope, toolWrapper, state.isEnabled(), state.getLevel());
-            }
-            else {
-              tools.addTool(state.getScopeName(), toolWrapper, state.isEnabled(), state.getLevel());
-            }
-          }
-        }
-        tools.setEnabled(toolList.isEnabled());
-      }
-    }
-    catch (WriteExternalException e) {
-      LOG.error(e);
-    }
-    catch (InvalidDataException e) {
-      LOG.error(e);
-    }
+  @TestOnly
+  public InspectionProfileModifiableModel getModifiableModel() {
+    return new InspectionProfileModifiableModel(this);
   }
 
   @Override
@@ -765,7 +680,6 @@ public class InspectionProfileImpl extends NewInspectionProfile {
     }
   }
 
-  @Override
   public void enableTool(@NotNull String inspectionTool, NamedScope namedScope, Project project) {
     getTools(inspectionTool, project).enableTool(namedScope, project);
   }
@@ -782,7 +696,6 @@ public class InspectionProfileImpl extends NewInspectionProfile {
     }
   }
 
-  @Override
   public void disableTool(@NotNull String inspectionTool, @Nullable Project project) {
     ToolsImpl tools = getTools(inspectionTool, project);
     tools.setEnabled(false);
@@ -791,7 +704,6 @@ public class InspectionProfileImpl extends NewInspectionProfile {
     }
   }
 
-  @Override
   public void setErrorLevel(@NotNull HighlightDisplayKey key, @NotNull HighlightDisplayLevel level, Project project) {
     getTools(key.toString(), project).setLevel(level);
   }
@@ -819,24 +731,6 @@ public class InspectionProfileImpl extends NewInspectionProfile {
     return false;
   }
 
-  //invoke when isChanged() == true
-  public void commit() {
-    LOG.assertTrue(mySource != null);
-    mySource.commit(this);
-    getProfileManager().updateProfile(mySource);
-    mySource = null;
-  }
-
-  private void commit(@NotNull InspectionProfileImpl model) {
-    setName(model.getName());
-    setDescription(model.getDescription());
-    setProjectLevel(model.isProjectLevel());
-    myLockedProfile = model.myLockedProfile;
-    myChangedToolNames = model.myChangedToolNames;
-    myTools = model.myTools;
-    setProfileManager(model.getProfileManager());
-  }
-
   @Tag
   public String getDescription() {
     return myDescription;
@@ -1012,7 +906,7 @@ public class InspectionProfileImpl extends NewInspectionProfile {
   @Override
   @NotNull
   public String toString() {
-    return mySource == null ? getName() : getName() + " (copy)";
+    return getName();
   }
 
   @Override
diff --git a/platform/analysis-impl/src/com/intellij/codeInspection/ex/InspectionProfileModifiableModel.kt b/platform/analysis-impl/src/com/intellij/codeInspection/ex/InspectionProfileModifiableModel.kt
new file mode 100644 (file)
index 0000000..f772076
--- /dev/null
@@ -0,0 +1,123 @@
+/*
+ * Copyright 2000-2016 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.codeInspection.ex
+
+import com.intellij.codeInspection.ModifiableModel
+import com.intellij.openapi.project.Project
+import com.intellij.openapi.util.Comparing
+import com.intellij.openapi.util.InvalidDataException
+import com.intellij.openapi.util.WriteExternalException
+import com.intellij.profile.codeInspection.ProjectInspectionProfileManager
+import com.intellij.util.Consumer
+
+open class InspectionProfileModifiableModel(val source: InspectionProfileImpl) : InspectionProfileImpl(source.name, source.myRegistrar, source.profileManager, source.myBaseProfile, null), ModifiableModel {
+  private var modified = false
+
+  init {
+    myUninitializedSettings.putAll(source.myUninitializedSettings)
+    isProjectLevel = source.isProjectLevel
+    myLockedProfile = source.myLockedProfile
+    copyFrom(source)
+  }
+
+  fun isChanged() = modified || source.myLockedProfile != myLockedProfile
+
+  fun setModified(value: Boolean) {
+    modified = value
+  }
+
+  override fun copyToolsConfigurations(project: Project?) {
+    copyToolsConfigurations(source, project)
+  }
+
+  override fun createTools(project: Project?) = source.getDefaultStates(project).map { it.tool }
+
+  private fun copyToolsConfigurations(profile: InspectionProfileImpl, project: Project?) {
+    try {
+      for (toolList in profile.myTools.values) {
+        val tools = myTools[toolList.shortName]!!
+        val defaultState = toolList.defaultState
+        tools.setDefaultState(copyToolSettings(defaultState.tool), defaultState.isEnabled, defaultState.level)
+        tools.removeAllScopes()
+        val nonDefaultToolStates = toolList.nonDefaultTools
+        if (nonDefaultToolStates != null) {
+          for (state in nonDefaultToolStates) {
+            val toolWrapper = copyToolSettings(state.tool)
+            val scope = state.getScope(project)
+            if (scope == null) {
+              tools.addTool(state.scopeName, toolWrapper, state.isEnabled, state.level)
+            }
+            else {
+              tools.addTool(scope, toolWrapper, state.isEnabled, state.level)
+            }
+          }
+        }
+        tools.isEnabled = toolList.isEnabled
+      }
+    }
+    catch (e: WriteExternalException) {
+      LOG.error(e)
+    }
+    catch (e: InvalidDataException) {
+      LOG.error(e)
+    }
+  }
+
+  fun isProperSetting(toolId: String): Boolean {
+    if (myBaseProfile != null) {
+      val tools = myBaseProfile.getTools(toolId, null)
+      val currentTools = myTools[toolId]
+      return !Comparing.equal<Tools>(tools, currentTools)
+    }
+    return false
+  }
+
+  fun resetToBase(project: Project?) {
+    initInspectionTools(project)
+
+    copyToolsConfigurations(myBaseProfile, project)
+    myChangedToolNames = null
+  }
+
+  //invoke when isChanged() == true
+  fun commit() {
+    source.commit(this)
+    profileManager.updateProfile(source)
+    modified = false
+  }
+
+  private fun InspectionProfileImpl.commit(model: InspectionProfileImpl) {
+    name = model.name
+    description = model.description
+    isProjectLevel = model.isProjectLevel
+    myLockedProfile = model.myLockedProfile
+    myChangedToolNames = model.myChangedToolNames
+    myTools = model.myTools
+    profileManager = model.profileManager
+  }
+
+  override fun toString() = "$name (copy)"
+}
+
+fun modifyAndCommitProjectProfile(project: Project, action: Consumer<ModifiableModel>) {
+  ProjectInspectionProfileManager.getInstance(project).currentProfile.edit { action.consume(this) }
+}
+
+inline fun InspectionProfileImpl.edit(task: InspectionProfileModifiableModel.() -> Unit) {
+  val model = InspectionProfileModifiableModel(this)
+  model.task()
+  model.commit()
+}
index e79258927e630f8e2afe0c6f3aa645c202d8c514..53525f7addef9bbf935a9898c462d5ac64c7d9f5 100644 (file)
@@ -180,7 +180,7 @@ fun writeFile(file: Path?, requestor: Any, virtualFile: VirtualFile?, element: E
       throw IllegalStateException("Content equals, but it must be handled not on this level: ${result.name}")
     }
     else if (StorageUtil.DEBUG_LOG != null && ApplicationManager.getApplication().isUnitTestMode) {
-      StorageUtil.DEBUG_LOG = "${result.path}:\n$content\nOld Content:\n${LoadTextUtil.loadText(result)}\n---------"
+      StorageUtil.DEBUG_LOG = "${result.path}:\n$content\nOld Content:\n${LoadTextUtil.loadText(result)}"
     }
   }
 
index f9dfac0d9376c28c6db589f2c11c10ba9f4b194f..1f4aaf3c80c381ee47535245e5be304f292d8254 100644 (file)
@@ -141,9 +141,9 @@ public abstract class ProgressManager extends ProgressIndicatorProvider {
                                                               @Nullable JComponent parentComponent);
 
   /**
-   * Runs a specified <code>process</code> in a background thread and shows a progress dialog, which can be made non-modal by pressing
-   * background button. Upon successful termination of the process a <code>successRunnable</code> will be called in Swing UI thread and
-   * <code>canceledRunnable</code> will be called if terminated on behalf of the user by pressing either cancel button, while running in
+   * Runs a specified {@code process} in a background thread and shows a progress dialog, which can be made non-modal by pressing
+   * background button. Upon successful termination of the process a {@code successRunnable} will be called in Swing UI thread and
+   * {@code canceledRunnable} will be called if terminated on behalf of the user by pressing either cancel button, while running in
    * a modal state or stop button if running in background.
    *
    * @param project          the project in the context of which the operation is executed.
@@ -159,9 +159,9 @@ public abstract class ProgressManager extends ProgressIndicatorProvider {
                                                             @Nullable Runnable successRunnable,
                                                             @Nullable Runnable canceledRunnable);
   /**
-   * Runs a specified <code>process</code> in a background thread and shows a progress dialog, which can be made non-modal by pressing
-   * background button. Upon successful termination of the process a <code>successRunnable</code> will be called in Swing UI thread and
-   * <code>canceledRunnable</code> will be called if terminated on behalf of the user by pressing either cancel button, while running in
+   * Runs a specified {@code process} in a background thread and shows a progress dialog, which can be made non-modal by pressing
+   * background button. Upon successful termination of the process a {@code successRunnable} will be called in Swing UI thread and
+   * {@code canceledRunnable} will be called if terminated on behalf of the user by pressing either cancel button, while running in
    * a modal state or stop button if running in background.
    *
    * @param project          the project in the context of which the operation is executed.
@@ -180,7 +180,7 @@ public abstract class ProgressManager extends ProgressIndicatorProvider {
                                                             @NotNull PerformInBackgroundOption option);
 
   /**
-   * Runs a specified <code>task</code> in either background/foreground thread and shows a progress dialog.
+   * Runs a specified {@code task} in either background/foreground thread and shows a progress dialog.
    *
    * @param task task to run (either {@link Task.Modal} or {@link Task.Backgroundable}).
    */
@@ -226,7 +226,7 @@ public abstract class ProgressManager extends ProgressIndicatorProvider {
    * This method attempts to run provided action synchronously in a read action, so that, if possible, it wouldn't impact any pending,
    * executing or future write actions (for this to work effectively the action should invoke {@link ProgressManager#checkCanceled()} or
    * {@link ProgressIndicator#checkCanceled()} often enough).
-   * It returns <code>true</code> if action was executed successfully. It returns <code>false</code> if the action was not
+   * It returns {@code true} if action was executed successfully. It returns {@code false} if the action was not
    * executed successfully, i.e. if:
    * <ul>
    * <li>write action was in progress when the method was called</li>
@@ -240,4 +240,5 @@ public abstract class ProgressManager extends ProgressIndicatorProvider {
    */
   public abstract boolean runInReadActionWithWriteActionPriority(@NotNull final Runnable action);
 
+  public abstract boolean isInNonCancelableSection();
 }
\ No newline at end of file
index 532d9c76f1cc492b102c8a6840795dd61f6e6ec6..70b960a55e2653077971743a9eb30744040af8e6 100644 (file)
@@ -46,9 +46,9 @@ public abstract class VirtualFileManager implements ModificationTracker {
   }
 
   /**
-   * Gets the instance of <code>VirtualFileManager</code>.
+   * Gets the instance of {@code VirtualFileManager}.
    *
-   * @return <code>VirtualFileManager</code>
+   * @return {@code VirtualFileManager}
    */
   @NotNull
   public static VirtualFileManager getInstance() {
@@ -89,7 +89,7 @@ public abstract class VirtualFileManager implements ModificationTracker {
    * file systems.
    *
    * @param url the URL to find file by
-   * @return <code>{@link VirtualFile}</code> if the file was found, <code>null</code> otherwise
+   * @return <code>{@link VirtualFile}</code> if the file was found, {@code null} otherwise
    * @see VirtualFile#getUrl
    * @see VirtualFileSystem#findFileByPath
    * @see #refreshAndFindFileByUrl
@@ -107,7 +107,7 @@ public abstract class VirtualFileManager implements ModificationTracker {
    * If this method is invoked not from Swing event dispatch thread, then it must not happen inside a read action.
    *
    * @param url the URL
-   * @return <code>{@link VirtualFile}</code> if the file was found, <code>null</code> otherwise
+   * @return <code>{@link VirtualFile}</code> if the file was found, {@code null} otherwise
    * @see VirtualFileSystem#findFileByPath
    * @see VirtualFileSystem#refreshAndFindFileByPath
    */
@@ -148,7 +148,7 @@ public abstract class VirtualFileManager implements ModificationTracker {
    * Extracts protocol from the given URL. Protocol is a substring from the beginning of the URL till "://".
    *
    * @param url the URL
-   * @return protocol or <code>null</code> if there is no "://" in the URL
+   * @return protocol or {@code null} if there is no "://" in the URL
    * @see VirtualFileSystem#getProtocol
    */
   @Nullable
index aeb23cb6cc84d26d4b19e575015dc64ab02ab0fa..78006c7cee9c4848ee09c37b2d415fc791b488bb 100644 (file)
@@ -21,6 +21,7 @@ import com.intellij.openapi.Disposable;
 import com.intellij.openapi.application.ApplicationManager;
 import com.intellij.openapi.application.ModalityState;
 import com.intellij.openapi.application.ex.ApplicationEx;
+import com.intellij.openapi.diagnostic.Logger;
 import com.intellij.openapi.progress.*;
 import com.intellij.openapi.project.Project;
 import com.intellij.openapi.util.Computable;
@@ -50,6 +51,8 @@ import java.util.concurrent.atomic.AtomicInteger;
 import java.util.concurrent.atomic.AtomicReference;
 
 public class CoreProgressManager extends ProgressManager implements Disposable {
+  private static final Logger LOG = Logger.getInstance("#com.intellij.openapi.progress.impl.CoreProgressManager");
+
   static final int CHECK_CANCELED_DELAY_MILLIS = 10;
   final AtomicInteger myCurrentUnsafeProgressCount = new AtomicInteger(0);
   private final AtomicInteger myCurrentModalProgressCount = new AtomicInteger(0);
@@ -76,6 +79,11 @@ public class CoreProgressManager extends ProgressManager implements Disposable {
   // multiset here (instead of a set) is for simplifying add/remove indicators on process-with-progress start/end with possibly identical indicators.
   private static final Collection<ProgressIndicator> nonStandardIndicators = ConcurrentHashMultiset.create();
 
+  /** true if running in non-cancelable section started with
+   * {@link #startNonCancelableSection()} or {@link #executeNonCancelableSection(Runnable)} in this thread
+   */
+  private static final ThreadLocal<Boolean> isInNonCancelableSection = new ThreadLocal<Boolean>(); // do not supply initial value to conserve memory
+
   public CoreProgressManager() {
     HeavyProcessLatch.INSTANCE.addUIActivityListener(new HeavyProcessLatch.HeavyProcessListener() {
       @Override
@@ -206,7 +214,18 @@ public class CoreProgressManager extends ProgressManager implements Disposable {
 
   @Override
   public void executeNonCancelableSection(@NotNull Runnable runnable) {
-    executeProcessUnderProgress(runnable, NonCancelableIndicator.INSTANCE);
+    if (isInNonCancelableSection()) {
+      runnable.run();
+    }
+    else {
+      try {
+        isInNonCancelableSection.set(Boolean.TRUE);
+        executeProcessUnderProgress(runnable, NonCancelableIndicator.INSTANCE);
+      }
+      finally {
+        isInNonCancelableSection.remove();
+      }
+    }
   }
 
   @Override
@@ -656,19 +675,28 @@ public class CoreProgressManager extends ProgressManager implements Disposable {
   @NotNull
   @Override
   public final NonCancelableSection startNonCancelableSection() {
+    LOG.warn("Use executeNonCancelableSection() instead");
+    if (isInNonCancelableSection()) return NonCancelableSection.EMPTY;
     final ProgressIndicator myOld = getProgressIndicator();
 
     final Thread currentThread = Thread.currentThread();
-    NonCancelableIndicator nonCancelor = new NonCancelableIndicator() {
+    final NonCancelableIndicator nonCancelor = new NonCancelableIndicator() {
       @Override
       public void done() {
         setCurrentIndicator(currentThread, myOld);
+        isInNonCancelableSection.remove();
       }
     };
+    isInNonCancelableSection.set(Boolean.TRUE);
     setCurrentIndicator(currentThread, nonCancelor);
     return nonCancelor;
   }
 
+  @Override
+  public boolean isInNonCancelableSection() {
+    return isInNonCancelableSection.get() != null;
+  }
+
   @NotNull
   public static ModalityState getCurrentThreadProgressModality() {
     ProgressIndicator indicator = threadTopLevelIndicators.get(Thread.currentThread().getId());
@@ -710,15 +738,16 @@ public class CoreProgressManager extends ProgressManager implements Disposable {
       return myTask.toString();
     }
   }
-  protected static class TaskRunnable extends TaskContainer {
+
+  static class TaskRunnable extends TaskContainer {
     private final ProgressIndicator myIndicator;
     private final Runnable myContinuation;
 
-    public TaskRunnable(@NotNull Task task, @NotNull ProgressIndicator indicator) {
+    TaskRunnable(@NotNull Task task, @NotNull ProgressIndicator indicator) {
       this(task, indicator, null);
     }
 
-    public TaskRunnable(@NotNull Task task, @NotNull ProgressIndicator indicator, @Nullable Runnable continuation) {
+    TaskRunnable(@NotNull Task task, @NotNull ProgressIndicator indicator, @Nullable Runnable continuation) {
       super(task);
       myIndicator = indicator;
       myContinuation = continuation;
index 149babd50e5077791a635109c72331f332321734..054e4833cbd3d9b09e0d49a89164b07cf4341705 100644 (file)
@@ -52,7 +52,7 @@ public class VirtualFileManagerImpl extends VirtualFileManagerEx {
   private final List<VirtualFileSystem> myPhysicalFileSystems = new ArrayList<VirtualFileSystem>();
   private final EventDispatcher<VirtualFileListener> myVirtualFileListenerMulticaster = EventDispatcher.create(VirtualFileListener.class);
   private final List<VirtualFileManagerListener> myVirtualFileManagerListeners = ContainerUtil.createLockFreeCopyOnWriteList();
-  private int myRefreshCount = 0;
+  private int myRefreshCount;
 
   public VirtualFileManagerImpl(@NotNull VirtualFileSystem[] fileSystems, @NotNull MessageBus bus) {
     for (VirtualFileSystem fileSystem : fileSystems) {
index c83ff3c17986a9f87f0986a3ac31b79c6762890b..d47b790b5c5a95639666eb3fb0eecfbe9903ff74 100644 (file)
@@ -337,29 +337,42 @@ public class PsiSearchHelperImpl implements PsiSearchHelper {
                                                                     @NotNull List<VirtualFile> files,
                                                                     @NotNull final ProgressIndicator progress,
                                                                     @NotNull final Processor<VirtualFile> localProcessor) {
+    ApplicationEx app = (ApplicationEx)ApplicationManager.getApplication();
     final AtomicBoolean canceled = new AtomicBoolean(false);
 
-    boolean completed = true;
     while (true) {
       List<VirtualFile> failedList = new SmartList<>();
       final List<VirtualFile> failedFiles = Collections.synchronizedList(failedList);
       final Processor<VirtualFile> processor = vfile -> {
         try {
-          return localProcessor.process(vfile);
+          boolean result = localProcessor.process(vfile);
+          if (!result) {
+            canceled.set(true);
+          }
+          return result;
         }
         catch (ApplicationUtil.CannotRunReadActionException action) {
           failedFiles.add(vfile);
         }
         return !canceled.get();
       };
-      if (ApplicationManager.getApplication().isWriteAccessAllowed() || ((ApplicationEx)ApplicationManager.getApplication()).isWriteActionPending()) {
+      boolean completed;
+      if (app.isWriteAccessAllowed() || app.isReadAccessAllowed() && app.isWriteActionPending()) {
         // no point in processing in separate threads - they are doomed to fail to obtain read action anyway
-        completed &= ContainerUtil.process(files, processor);
+        completed = ContainerUtil.process(files, processor);
+      }
+      else if (app.isWriteActionPending()) {
+        completed = true;
+        // we don't have read action now so wait for write action to complete
+        failedFiles.addAll(files);
       }
       else {
-        completed &= JobLauncher.getInstance().invokeConcurrentlyUnderProgress(files, progress, false, true, processor);
+        // try to run parallel read actions but fail as soon as possible
+        completed = JobLauncher.getInstance().invokeConcurrentlyUnderProgress(files, progress, false, true, processor);
+      }
+      if (!completed) {
+        return false;
       }
-
       if (failedFiles.isEmpty()) {
         break;
       }
@@ -368,7 +381,7 @@ public class PsiSearchHelperImpl implements PsiSearchHelper {
       DumbService.getInstance(project).runReadActionInSmartMode(EmptyRunnable.getInstance());
       files = failedList;
     }
-    return completed;
+    return true;
   }
 
   private void processVirtualFile(@NotNull final VirtualFile vfile,
index 70e3526de12723d01138bd6332dc675c28558f36..d5b0028500860524486b3a808e1368ec4a287cd9 100644 (file)
@@ -25,10 +25,12 @@ import com.intellij.openapi.editor.Editor;
 import com.intellij.openapi.editor.actionSystem.EditorActionHandler;
 import com.intellij.openapi.project.Project;
 import com.intellij.openapi.util.Ref;
+import com.intellij.psi.PsiComment;
 import com.intellij.psi.PsiDocumentManager;
 import com.intellij.psi.PsiFile;
 import com.intellij.psi.codeStyle.CodeStyleManager;
 import com.intellij.psi.codeStyle.CodeStyleSettingsManager;
+import com.intellij.psi.util.PsiTreeUtil;
 import com.intellij.util.IncorrectOperationException;
 import com.intellij.util.text.CharArrayUtil;
 import org.jetbrains.annotations.NotNull;
@@ -65,7 +67,7 @@ public class EnterBetweenBracesHandler extends EnterHandlerDelegateAdapter {
       CodeDocumentationUtil.tryParseCommentContext(file, text, caretOffset, start);
 
     // special case: enter inside "()" or "{}"
-    String indentInsideJavadoc = commentContext.docAsterisk
+    String indentInsideJavadoc = isInComment(caretOffset, file) && commentContext.docAsterisk
                                  ? CodeDocumentationUtil.getIndentInsideJavadoc(document, caretOffset)
                                  : null;
 
@@ -86,6 +88,10 @@ public class EnterBetweenBracesHandler extends EnterHandlerDelegateAdapter {
     return indentInsideJavadoc == null ? Result.Continue : Result.DefaultForceIndent;
   }
 
+  private static boolean isInComment(int offset, PsiFile file) {
+    return PsiTreeUtil.getParentOfType(file.findElementAt(offset), PsiComment.class)!=null;
+  }
+
   private static boolean isValidOffset(int offset, CharSequence text) {
     return offset >= 0 && offset < text.length();
   }
index 0bbd6bb05d2629aed0842be97a2e26871b8f6551..e56bfd83bda4c1abf09295cef5c647fbccae2d9f 100644 (file)
@@ -24,6 +24,7 @@ import com.intellij.codeInspection.InspectionsBundle;
 import com.intellij.codeInspection.ex.GlobalInspectionContextImpl;
 import com.intellij.codeInspection.ex.InspectionManagerEx;
 import com.intellij.codeInspection.ex.InspectionProfileImpl;
+import com.intellij.codeInspection.ex.InspectionProfileModifiableModel;
 import com.intellij.openapi.fileEditor.FileDocumentManager;
 import com.intellij.openapi.options.ex.SingleConfigurableEditor;
 import com.intellij.openapi.project.Project;
@@ -99,7 +100,7 @@ public class CodeInspectionAction extends BaseAnalysisAction {
   protected JComponent getAdditionalActionSettings(@NotNull final Project project, final BaseAnalysisActionDialog dialog) {
     final AdditionalPanel panel = new AdditionalPanel();
     final InspectionManagerEx manager = (InspectionManagerEx)InspectionManager.getInstance(project);
-    final ProfilesComboBox profiles = (ProfilesComboBox)panel.myBrowseProfilesCombo.getComboBox();
+    final ProfilesComboBox<InspectionProfileImpl> profiles = (ProfilesComboBox<InspectionProfileImpl>)panel.myBrowseProfilesCombo.getComboBox();
     final InspectionProfileManager profileManager = InspectionProfileManager.getInstance();
     final ProjectInspectionProfileManager projectProfileManager = ProjectInspectionProfileManager.getInstance(project);
     reloadProfiles(profiles, profileManager, projectProfileManager, manager);
@@ -142,7 +143,7 @@ public class CodeInspectionAction extends BaseAnalysisAction {
   }
 
   protected static class ExternalProfilesComboboxAwareInspectionToolsConfigurable extends InspectionToolsConfigurable {
-    private final ProfilesComboBox myProfilesCombo;
+    private final ProfilesComboBox<InspectionProfileImpl> myProfilesCombo;
 
     public ExternalProfilesComboboxAwareInspectionToolsConfigurable(@NotNull ProjectInspectionProfileManager projectProfileManager, ProfilesComboBox profilesCombo) {
       super(projectProfileManager);
@@ -155,9 +156,9 @@ public class CodeInspectionAction extends BaseAnalysisAction {
     }
 
     @Override
-    protected void addProfile(InspectionProfileImpl model) {
+    protected void addProfile(InspectionProfileModifiableModel model) {
       super.addProfile(model);
-      myProfilesCombo.addProfile(model.getParentProfile());
+      myProfilesCombo.addProfile(model.getSource());
     }
 
     @Override
@@ -173,7 +174,7 @@ public class CodeInspectionAction extends BaseAnalysisAction {
   }
 
 
-  private void reloadProfiles(ProfilesComboBox profilesCombo,
+  private void reloadProfiles(ProfilesComboBox<InspectionProfileImpl> profilesCombo,
                               InspectionProfileManager inspectionProfileManager,
                               InspectionProjectProfileManager inspectionProjectProfileManager,
                               InspectionManagerEx inspectionManager) {
index 322a273830e5648857abf90984673bd9f47be982..119e952b843af84bc781af06d2ab84cf9ebbb966 100644 (file)
@@ -44,10 +44,10 @@ public class Descriptor {
   private final NamedScope myScope;
   private static final Logger LOG = Logger.getInstance("#com.intellij.codeInspection.ex.Descriptor");
   private final ScopeToolState myState;
-  private final InspectionProfileImpl myInspectionProfile;
+  private final InspectionProfileModifiableModel myInspectionProfile;
   private final String myScopeName;
 
-  public Descriptor(@NotNull ScopeToolState state, @NotNull InspectionProfileImpl inspectionProfile, @NotNull Project project) {
+  public Descriptor(@NotNull ScopeToolState state, @NotNull InspectionProfileModifiableModel inspectionProfile, @NotNull Project project) {
     myState = state;
     myInspectionProfile = inspectionProfile;
     InspectionToolWrapper tool = state.getTool();
@@ -120,7 +120,7 @@ public class Descriptor {
     return myToolWrapper.loadDescription();
   }
 
-  public InspectionProfileImpl getInspectionProfile() {
+  public InspectionProfileModifiableModel getInspectionProfile() {
     return myInspectionProfile;
   }
 
index fbacaf0eeceed0564f9dac07cf95d07474cddd5c..63f1be7e21ccf0009469d0cf1103145e3b979538 100644 (file)
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
-
 package com.intellij.codeInspection.ex;
 
 import com.intellij.codeHighlighting.HighlightDisplayLevel;
-import com.intellij.codeInsight.daemon.DaemonCodeAnalyzer;
 import com.intellij.codeInsight.daemon.HighlightDisplayKey;
-import com.intellij.codeInspection.*;
+import com.intellij.codeInspection.InspectionProfile;
+import com.intellij.codeInspection.InspectionsBundle;
+import com.intellij.codeInspection.IntentionAndQuickFixAction;
+import com.intellij.codeInspection.LocalInspectionTool;
 import com.intellij.icons.AllIcons;
 import com.intellij.openapi.editor.Editor;
 import com.intellij.openapi.project.Project;
 import com.intellij.openapi.util.Iconable;
 import com.intellij.profile.codeInspection.InspectionProjectProfileManager;
-import com.intellij.profile.codeInspection.ProjectInspectionProfileManager;
 import com.intellij.psi.PsiFile;
-import com.intellij.util.Consumer;
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
 
@@ -67,14 +66,7 @@ public class DisableInspectionToolAction extends IntentionAndQuickFixAction impl
 
   @Override
   public void applyFix(@NotNull Project project, final PsiFile file, @Nullable Editor editor) {
-    modifyAndCommitProjectProfile(modifiableModel -> modifiableModel.disableTool(myToolId, file), project);
-    DaemonCodeAnalyzer.getInstance(project).restart();
-  }
-
-  public static void modifyAndCommitProjectProfile(Consumer<ModifiableModel> action, Project project) {
-    InspectionProfileImpl model = ProjectInspectionProfileManager.getInstance(project).getCurrentProfile().getModifiableModel();
-    action.consume(model);
-    model.commit();
+    InspectionProfileModifiableModelKt.modifyAndCommitProjectProfile(project, it -> it.disableTool(myToolId, file));
   }
 
   @Override
index f31d607e0ebd93db1653f76a8d3b3c99def30044..ba7942d4d69524a7babe451b0e5004b71ca85d7e 100644 (file)
@@ -397,7 +397,7 @@ public class GlobalInspectionContextImpl extends GlobalInspectionContextBase imp
 
     if (runGlobalToolsOnly || localTools.isEmpty() && globalSimpleTools.isEmpty()) return;
 
-    final Set<VirtualFile> localScopeFiles = scope.toSearchScope() instanceof LocalSearchScope ? new THashSet<>() : null;
+    final Set<VirtualFile> localScopeFiles = ReadAction.compute(() -> scope.toSearchScope()) instanceof LocalSearchScope ? new THashSet<>() : null;
     for (Tools tools : globalSimpleTools) {
       GlobalInspectionToolWrapper toolWrapper = (GlobalInspectionToolWrapper)tools.getTool();
       GlobalSimpleInspectionTool tool = (GlobalSimpleInspectionTool)toolWrapper.getTool();
@@ -876,7 +876,7 @@ public class GlobalInspectionContextImpl extends GlobalInspectionContextBase imp
     final int fileCount = scope.getFileCount();
     final ProgressIndicator progressIndicator = ProgressManager.getInstance().getProgressIndicator();
 
-    final SearchScope searchScope = scope.toSearchScope();
+    final SearchScope searchScope = ReadAction.compute(() -> scope.toSearchScope());
     final TextRange range;
     if (searchScope instanceof LocalSearchScope) {
       final PsiElement[] elements = ((LocalSearchScope)searchScope).getScope();
index 7567d7da11a1efe7335da9eb9a1cc244beb4e8cf..e2727dd97c1d568ca408d6250e8faad5357da5d6 100644 (file)
 package com.intellij.codeInspection.ui.actions;
 
 import com.intellij.analysis.AnalysisScope;
-import com.intellij.codeInsight.daemon.DaemonCodeAnalyzer;
 import com.intellij.codeInsight.daemon.HighlightDisplayKey;
 import com.intellij.codeInspection.InspectionProfile;
 import com.intellij.codeInspection.InspectionsBundle;
 import com.intellij.codeInspection.actions.RunInspectionIntention;
 import com.intellij.codeInspection.ex.DisableInspectionToolAction;
-import com.intellij.codeInspection.ex.InspectionProfileImpl;
+import com.intellij.codeInspection.ex.InspectionProfileModifiableModelKt;
 import com.intellij.codeInspection.ex.InspectionToolWrapper;
 import com.intellij.codeInspection.reference.RefElement;
 import com.intellij.codeInspection.reference.RefEntity;
@@ -31,7 +30,6 @@ import com.intellij.openapi.actionSystem.AnActionEvent;
 import com.intellij.openapi.diagnostic.Logger;
 import com.intellij.openapi.module.Module;
 import com.intellij.openapi.module.ModuleUtilCore;
-import com.intellij.openapi.project.Project;
 import com.intellij.profile.codeInspection.InspectionProjectProfileManager;
 import com.intellij.psi.PsiElement;
 import com.intellij.psi.PsiFile;
@@ -87,28 +85,23 @@ public abstract class KeyAwareInspectionViewAction extends InspectionViewActionB
     @Override
     protected void actionPerformed(@NotNull InspectionResultsView view, @NotNull HighlightDisplayKey key) {
       if (view.isSingleInspectionRun()) {
-        InspectionProfileImpl model = view.getCurrentProfile().getModifiableModel();
-        model.disableTool(key.toString(), view.getProject());
-        model.commit();
+        view.getCurrentProfile().modifyProfile(it -> it.disableTool(key.toString(), view.getProject()));
         view.updateCurrentProfile();
       }
       else {
         final RefEntity[] selectedElements = view.getTree().getSelectedElements();
         final Set<PsiElement> files = new HashSet<>();
-        final Project project = view.getProject();
-        final InspectionProjectProfileManager profileManager = InspectionProjectProfileManager.getInstance(project);
         for (RefEntity selectedElement : selectedElements) {
           if (selectedElement instanceof RefElement) {
-            final PsiElement element = ((RefElement)selectedElement).getElement();
-            files.add(element);
+            files.add(((RefElement)selectedElement).getElement());
           }
         }
-        InspectionProfileImpl model = profileManager.getCurrentProfile().getModifiableModel();
-        for (PsiElement element : files) {
-          model.disableTool(key.toString(), element);
-        }
-        model.commit();
-        DaemonCodeAnalyzer.getInstance(project).restart();
+
+        InspectionProfileModifiableModelKt.modifyAndCommitProjectProfile(view.getProject(), it -> {
+          for (PsiElement element : files) {
+            it.disableTool(key.toString(), element);
+          }
+        });
       }
     }
   }
index a3a2ba51f466e2f6e54f5c1e201d290160cd43fb..ee3c7325ada9d85bcbeb147d1f12a30dd38302b1 100644 (file)
@@ -16,6 +16,7 @@
 package com.intellij.profile.codeInspection.ui;
 
 import com.intellij.codeInspection.ex.InspectionProfileImpl;
+import com.intellij.codeInspection.ex.InspectionProfileModifiableModel;
 import com.intellij.icons.AllIcons;
 import com.intellij.openapi.actionSystem.AnActionEvent;
 import com.intellij.openapi.application.ApplicationNamesInfo;
@@ -103,7 +104,7 @@ public abstract class AdvancedSettingsAction extends DumbAwareAction {
 
     @Override
     public void actionPerformed() {
-      final InspectionProfileImpl inspectionProfile = getInspectionProfile();
+      InspectionProfileModifiableModel inspectionProfile = getInspectionProfile();
       if (inspectionProfile == null) {
         return;
       }
@@ -179,7 +180,7 @@ public abstract class AdvancedSettingsAction extends DumbAwareAction {
     }
   }
 
-  protected abstract InspectionProfileImpl getInspectionProfile();
+  protected abstract InspectionProfileModifiableModel getInspectionProfile();
 
   protected abstract void postProcessModification();
 
index c43bacf115cdf887b4a812fd755bd6dfc3201257..dbd1e2b2cc2d2a265e17bf8c42dc8d6382edb055 100644 (file)
@@ -36,7 +36,6 @@ import com.intellij.openapi.application.ApplicationManager;
 import com.intellij.openapi.diagnostic.Logger;
 import com.intellij.openapi.editor.colors.TextAttributesKey;
 import com.intellij.openapi.editor.markup.TextAttributes;
-import com.intellij.openapi.options.ConfigurationException;
 import com.intellij.openapi.project.DumbAwareAction;
 import com.intellij.openapi.project.Project;
 import com.intellij.openapi.util.Comparing;
@@ -100,7 +99,7 @@ public class SingleInspectionProfilePanel extends JPanel {
     new InspectionConfigTreeNode.Group(InspectionsBundle.message("inspection.root.node.title"));
   private final Alarm myAlarm = new Alarm();
   private final ProjectInspectionProfileManager myProjectProfileManager;
-  private InspectionProfileImpl myProfile;
+  private InspectionProfileModifiableModel myProfile;
   private JEditorPane myBrowser;
   private JPanel myOptionsPanel;
   private JPanel myInspectionProfilePanel = null;
@@ -123,7 +122,7 @@ public class SingleInspectionProfilePanel extends JPanel {
   };
 
   public SingleInspectionProfilePanel(@NotNull ProjectInspectionProfileManager projectProfileManager,
-                                      @NotNull InspectionProfileImpl profile) {
+                                      @NotNull InspectionProfileModifiableModel profile) {
     super(new BorderLayout());
     myProjectProfileManager = projectProfileManager;
     myProfile = profile;
@@ -410,13 +409,18 @@ public class SingleInspectionProfilePanel extends JPanel {
   }
 
   private void initToolStates() {
-    final InspectionProfileImpl profile = myProfile;
-    if (profile == null) return;
+    InspectionProfileModifiableModel profile = myProfile;
+    if (profile == null) {
+      return;
+    }
+
     myInitialToolDescriptors.clear();
     final Project project = myProjectProfileManager.getProject();
     for (final ScopeToolState state : profile.getDefaultStates(myProjectProfileManager.getProject())) {
-      if (!accept(state.getTool())) continue;
-      final ToolDescriptors descriptors = ToolDescriptors.fromScopeToolState(state, profile, project);
+      if (!accept(state.getTool())) {
+        continue;
+      }
+      ToolDescriptors descriptors = ToolDescriptors.fromScopeToolState(state, profile, project);
       myInitialToolDescriptors.put(descriptors.getDefaultDescriptor().getKey(), descriptors);
     }
     myInitialScopesOrder = myProfile.getScopesOrder();
@@ -506,7 +510,7 @@ public class SingleInspectionProfilePanel extends JPanel {
 
     actions.add(new AdvancedSettingsAction(myProjectProfileManager.getProject(), myRoot) {
       @Override
-      protected InspectionProfileImpl getInspectionProfile() {
+      protected InspectionProfileModifiableModel getInspectionProfile() {
         return myProfile;
       }
 
@@ -605,16 +609,13 @@ public class SingleInspectionProfilePanel extends JPanel {
         }
 
         if (!myIsInRestore) {
-          InspectionProfileImpl selected = myProfile;
+          InspectionProfileModifiableModel selected = myProfile;
           if (selected != null) {
-            InspectionProfileImpl baseProfile = selected.getParentProfile();
-            if (baseProfile != null) {
-              getExpandedNodes(baseProfile).setSelectionPaths(myTreeTable.getTree().getSelectionPaths());
-            }
+            InspectionProfileImpl baseProfile = selected.getSource();
+            getExpandedNodes(baseProfile).setSelectionPaths(myTreeTable.getTree().getSelectionPaths());
             getExpandedNodes(selected).setSelectionPaths(myTreeTable.getTree().getSelectionPaths());
           }
         }
-
       }
     });
 
@@ -653,23 +654,17 @@ public class SingleInspectionProfilePanel extends JPanel {
 
       @Override
       public void treeCollapsed(TreeExpansionEvent event) {
-        InspectionProfileImpl selected = myProfile;
-        final InspectionProfileImpl parentProfile = selected.getParentProfile();
-        if (parentProfile != null) {
-          getExpandedNodes(parentProfile).saveVisibleState(myTreeTable.getTree());
-        }
+        InspectionProfileModifiableModel selected = myProfile;
+        getExpandedNodes(selected.getSource()).saveVisibleState(myTreeTable.getTree());
         getExpandedNodes(selected).saveVisibleState(myTreeTable.getTree());
       }
 
       @Override
       public void treeExpanded(TreeExpansionEvent event) {
-        InspectionProfileImpl selected = myProfile;
+        InspectionProfileModifiableModel selected = myProfile;
         if (selected != null) {
           final InspectionConfigTreeNode node = (InspectionConfigTreeNode)event.getPath().getLastPathComponent();
-          final InspectionProfileImpl parentProfile = selected.getParentProfile();
-          if (parentProfile != null) {
-            getExpandedNodes(parentProfile).expandNode(node);
-          }
+          getExpandedNodes(selected.getSource()).expandNode(node);
           getExpandedNodes(selected).expandNode(node);
         }
       }
@@ -1008,16 +1003,11 @@ public class SingleInspectionProfilePanel extends JPanel {
     myOptionsPanel.repaint();
   }
 
-  private boolean setSelectedProfileModified(boolean modified) {
-    myProfile.setModified(modified);
-    return modified;
-  }
-
-  public InspectionProfileImpl getProfile() {
+  public InspectionProfileModifiableModel getProfile() {
     return myProfile;
   }
 
-  private void setProfile(InspectionProfileImpl modifiableModel) {
+  private void setProfile(InspectionProfileModifiableModel modifiableModel) {
     if (myProfile == modifiableModel) {
       return;
     }
@@ -1096,8 +1086,8 @@ public class SingleInspectionProfilePanel extends JPanel {
     if (myTreeTable == null) return false;
     if (myModified) return true;
     if (myProfile.isChanged()) return true;
-    if (myProfile.getParentProfile().isProjectLevel() != myProfile.isProjectLevel()) return true;
-    if (!Comparing.strEqual(myProfile.getParentProfile().getName(), myProfile.getName())) return true;
+    if (myProfile.getSource().isProjectLevel() != myProfile.isProjectLevel()) return true;
+    if (!Comparing.strEqual(myProfile.getSource().getName(), myProfile.getName())) return true;
     if (!Comparing.equal(myInitialScopesOrder, myProfile.getScopesOrder())) return true;
     return descriptorsAreChanged();
   }
@@ -1109,23 +1099,23 @@ public class SingleInspectionProfilePanel extends JPanel {
     final String filter = myProfileFilter.getFilter();
     myProfileFilter.reset();
     myProfileFilter.setSelectedItem(filter);
-    myProfile.setName(myProfile.getParentProfile().getName());
-    myProfile.setProjectLevel(myProfile.getParentProfile().isProjectLevel());
+    myProfile.setName(myProfile.getSource().getName());
+    myProfile.setProjectLevel(myProfile.getSource().isProjectLevel());
   }
 
-  public void apply() throws ConfigurationException {
+  public void apply() {
     final boolean modified = isModified();
     if (!modified) {
       return;
     }
-    final InspectionProfileImpl selectedProfile = getProfile();
+    InspectionProfileModifiableModel selectedProfile = myProfile;
 
     BaseInspectionProfileManager profileManager = selectedProfile.isProjectLevel() ? myProjectProfileManager : (BaseInspectionProfileManager)InspectionProfileManager.getInstance();
-    InspectionProfileImpl parentProfile = selectedProfile.getParentProfile();
+    InspectionProfileImpl source = selectedProfile.getSource();
 
     // delete by instance, only if from another profile manager or has another name (otherwise will be replaced and we don't need to explicitly delete it)
-    if (parentProfile.getProfileManager() != profileManager || !parentProfile.getName().equals(selectedProfile.getName())) {
-      parentProfile.getProfileManager().deleteProfile(parentProfile);
+    if (source.getProfileManager() != profileManager || !source.getName().equals(selectedProfile.getName())) {
+      source.getProfileManager().deleteProfile(source);
     }
 
     if (selectedProfile.getProfileManager() != profileManager) {
@@ -1134,8 +1124,6 @@ public class SingleInspectionProfilePanel extends JPanel {
     }
 
     selectedProfile.commit();
-    myProfile = parentProfile.getModifiableModel();
-    setSelectedProfileModified(false);
     myModified = false;
     myRoot.dropCache();
     initToolStates();
index 6d33d8d93032c0d417c04355465c7cf7abfa40a4..b709a5d15d17c1d8dcc918150c191a72655c8a8a 100644 (file)
@@ -16,8 +16,7 @@
 package com.intellij.profile.codeInspection.ui;
 
 import com.intellij.codeInspection.ex.Descriptor;
-import com.intellij.codeInspection.ex.InspectionProfileImpl;
-import com.intellij.codeInspection.ex.InspectionToolWrapper;
+import com.intellij.codeInspection.ex.InspectionProfileModifiableModel;
 import com.intellij.codeInspection.ex.ScopeToolState;
 import com.intellij.openapi.project.Project;
 import org.jetbrains.annotations.NotNull;
@@ -42,11 +41,10 @@ public class ToolDescriptors {
   }
 
   public static ToolDescriptors fromScopeToolState(final ScopeToolState state,
-                                                   final InspectionProfileImpl profile,
+                                                   @NotNull InspectionProfileModifiableModel profile,
                                                    final Project project) {
-    final InspectionToolWrapper toolWrapper = state.getTool();
-    final List<ScopeToolState> nonDefaultTools = profile.getNonDefaultTools(toolWrapper.getShortName(), project);
-    final ArrayList<Descriptor> descriptors = new ArrayList<>(nonDefaultTools.size());
+    List<ScopeToolState> nonDefaultTools = profile.getNonDefaultTools(state.getTool().getShortName(), project);
+    ArrayList<Descriptor> descriptors = new ArrayList<>(nonDefaultTools.size());
     for (final ScopeToolState nonDefaultToolState : nonDefaultTools) {
       descriptors.add(new Descriptor(nonDefaultToolState, profile, project));
     }
index 0976bdb3c6b68abd4f94670724f5893672223275..df27dfca7856cbcc4eea1287ef841ce10e5dc7c6 100644 (file)
@@ -19,6 +19,7 @@ package com.intellij.profile.codeInspection.ui.header;
 import com.intellij.codeInsight.daemon.impl.HighlightInfoType;
 import com.intellij.codeInsight.daemon.impl.SeverityRegistrar;
 import com.intellij.codeInspection.ex.InspectionProfileImpl;
+import com.intellij.codeInspection.ex.InspectionProfileModifiableModel;
 import com.intellij.codeInspection.ex.InspectionToolRegistrar;
 import com.intellij.codeInspection.ex.InspectionToolWrapper;
 import com.intellij.lang.annotation.HighlightSeverity;
@@ -33,7 +34,6 @@ import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory;
 import com.intellij.openapi.fileTypes.StdFileTypes;
 import com.intellij.openapi.options.BaseConfigurable;
 import com.intellij.openapi.options.Configurable;
-import com.intellij.openapi.options.ConfigurationException;
 import com.intellij.openapi.options.SearchableConfigurable;
 import com.intellij.openapi.project.Project;
 import com.intellij.openapi.ui.Messages;
@@ -43,7 +43,6 @@ import com.intellij.openapi.util.InvalidDataException;
 import com.intellij.openapi.util.JDOMUtil;
 import com.intellij.openapi.util.io.FileUtil;
 import com.intellij.openapi.util.text.StringUtil;
-import com.intellij.openapi.vfs.VfsUtilCore;
 import com.intellij.openapi.vfs.VirtualFile;
 import com.intellij.profile.codeInspection.BaseInspectionProfileManager;
 import com.intellij.profile.codeInspection.InspectionProfileManager;
@@ -52,6 +51,7 @@ import com.intellij.profile.codeInspection.ui.ErrorsConfigurable;
 import com.intellij.profile.codeInspection.ui.SingleInspectionProfilePanel;
 import com.intellij.ui.IdeBorderFactory;
 import com.intellij.util.Alarm;
+import com.intellij.util.SmartList;
 import com.intellij.util.ui.JBUI;
 import com.intellij.util.ui.UIUtil;
 import org.jdom.Element;
@@ -83,7 +83,7 @@ public abstract class InspectionToolsConfigurable extends BaseConfigurable
   protected final BaseInspectionProfileManager myApplicationProfileManager;
   protected final ProjectInspectionProfileManager myProjectProfileManager;
   private final List<SingleInspectionProfilePanel> myPanels = new ArrayList<>();
-  private final List<InspectionProfileImpl> myDeletedProfiles = new ArrayList<>();
+  private final List<InspectionProfileModifiableModel> myDeletedProfiles = new SmartList<>();
   protected ProfilesChooser myProfiles;
   private JPanel myProfilePanelHolder;
   private AuxiliaryRightPanel myAuxiliaryRightPanel;
@@ -143,16 +143,15 @@ public abstract class InspectionToolsConfigurable extends BaseConfigurable
     inspectionProfile.copyFrom(selectedProfile);
     inspectionProfile.setName(profileDefaultName);
     inspectionProfile.initInspectionTools(project);
-    inspectionProfile.setModified(true);
     inspectionProfile.setProjectLevel(isProjectLevel);
 
-    final InspectionProfileImpl modifiableModel = inspectionProfile.getModifiableModel();
+    InspectionProfileModifiableModel modifiableModel = new InspectionProfileModifiableModel(inspectionProfile);
     modifiableModel.setModified(true);
     addProfile(modifiableModel);
     return modifiableModel;
   }
 
-  protected void addProfile(InspectionProfileImpl model) {
+  protected void addProfile(InspectionProfileModifiableModel model) {
     final SingleInspectionProfilePanel panel = createPanel(model);
     myPanels.add(panel);
     myProfiles.getProfilesComboBox().addProfile(model);
@@ -205,7 +204,7 @@ public abstract class InspectionToolsConfigurable extends BaseConfigurable
     myAuxiliaryRightPanel = new AuxiliaryRightPanel(new AuxiliaryRightPanel.DescriptionSaveListener() {
       @Override
       public void saveDescription(@NotNull String description) {
-        final InspectionProfileImpl inspectionProfile = getSelectedObject();
+        InspectionProfileModifiableModel inspectionProfile = getSelectedObject();
         if (!Comparing.strEqual(description, inspectionProfile.getDescription())) {
           inspectionProfile.setDescription(description);
           inspectionProfile.setModified(true);
@@ -304,7 +303,7 @@ public abstract class InspectionToolsConfigurable extends BaseConfigurable
 
       @Override
       public void delete() {
-        final InspectionProfileImpl selectedProfile = myProfiles.getProfilesComboBox().getSelectedProfile();
+        InspectionProfileModifiableModel selectedProfile = myProfiles.getProfilesComboBox().getSelectedProfile();
         myProfiles.getProfilesComboBox().removeProfile(selectedProfile);
         myPanels.remove(getProfilePanel(selectedProfile));
         myDeletedProfiles.add(selectedProfile);
@@ -365,8 +364,7 @@ public abstract class InspectionToolsConfigurable extends BaseConfigurable
           if (file != null) {
             final InspectionProfileImpl profile;
             try {
-              Element rootElement = JDOMUtil.load(VfsUtilCore.virtualToIoFile(file));
-              profile = importInspectionProfile(rootElement, myApplicationProfileManager, getProject(), wholePanel);
+              profile = importInspectionProfile(JDOMUtil.load(file.getInputStream()), myApplicationProfileManager, getProject(), wholePanel);
               final SingleInspectionProfilePanel existed = getProfilePanel(profile);
               if (existed != null) {
                 if (Messages.showOkCancelDialog(wholePanel, "Profile with name \'" +
@@ -378,13 +376,10 @@ public abstract class InspectionToolsConfigurable extends BaseConfigurable
                 myProfiles.getProfilesComboBox().removeProfile(existed.getProfile());
                 myPanels.remove(existed);
               }
-              InspectionProfileImpl model = profile.getModifiableModel();
+              InspectionProfileModifiableModel model = new InspectionProfileModifiableModel(profile);
               model.setModified(true);
               addProfile(model);
               selectProfile(model);
-
-              //TODO myDeletedProfiles ? really need this
-              myDeletedProfiles.remove(profile);
             }
             catch (JDOMException e) {
               LOG.error(e);
@@ -422,23 +417,22 @@ public abstract class InspectionToolsConfigurable extends BaseConfigurable
   public static InspectionProfileImpl importInspectionProfile(@NotNull Element rootElement,
                                                               @NotNull BaseInspectionProfileManager profileManager,
                                                               @NotNull Project project,
-                                                              @Nullable JPanel anchorPanel)
-    throws JDOMException, IOException, InvalidDataException {
+                                                              @Nullable JPanel anchorPanel) {
     final boolean unitTestMode = ApplicationManager.getApplication().isUnitTestMode();
     if (!unitTestMode) {
       LOG.assertTrue(anchorPanel != null);
     }
     InspectionProfileImpl profile =
       new InspectionProfileImpl("TempProfile", InspectionToolRegistrar.getInstance(), profileManager);
-    if (Comparing.strEqual(rootElement.getName(), "component")) {//import right from .idea/inspectProfiles/xxx.xml
+    if (Comparing.strEqual(rootElement.getName(), "component")) {
+      //import right from .idea/inspectProfiles/xxx.xml
       rootElement = rootElement.getChildren().get(0);
     }
     final Set<String> levels = new HashSet<>();
-    for (Object o : rootElement.getChildren("inspection_tool")) {
-      final Element inspectElement = (Element)o;
+    for (Element inspectElement : rootElement.getChildren("inspection_tool")) {
       addLevelIfNotNull(levels, inspectElement);
-      for (Object s : inspectElement.getChildren("scope")) {
-        addLevelIfNotNull(levels, ((Element)s));
+      for (Element s : inspectElement.getChildren("scope")) {
+        addLevelIfNotNull(levels, s);
       }
     }
     for (Iterator<String> iterator = levels.iterator(); iterator.hasNext(); ) {
@@ -472,7 +466,6 @@ public abstract class InspectionToolsConfigurable extends BaseConfigurable
     profile.setProjectLevel(false);
     profile.initInspectionTools(project);
     return profile;
-
   }
 
   private static void addLevelIfNotNull(Set<String> levels, Element inspectElement) {
@@ -494,18 +487,17 @@ public abstract class InspectionToolsConfigurable extends BaseConfigurable
     for (SingleInspectionProfilePanel panel : myPanels) {
       if (panel.isModified()) return true;
     }
-    if (getProfiles().size() != myPanels.size()) return true;
-    return !myDeletedProfiles.isEmpty();
+    return getProfiles().size() != myPanels.size() || !myDeletedProfiles.isEmpty();
   }
 
   @Override
-  public void apply() throws ConfigurationException {
-    SingleInspectionProfilePanel selectedPanel = getSelectedPanel();
-    for (InspectionProfileImpl profile : myDeletedProfiles) {
-      deleteProfile(profile);
+  public void apply() {
+    for (InspectionProfileModifiableModel profile : myDeletedProfiles) {
+      profile.getProfileManager().deleteProfile(profile.getSource());
     }
     myDeletedProfiles.clear();
 
+    SingleInspectionProfilePanel selectedPanel = getSelectedPanel();
     for (SingleInspectionProfilePanel panel : myPanels) {
       panel.apply();
       if (setActiveProfileAsDefaultOnApply() && panel == selectedPanel) {
@@ -516,15 +508,6 @@ public abstract class InspectionToolsConfigurable extends BaseConfigurable
 
   protected abstract void applyRootProfile(@NotNull String name, boolean isProjectLevel);
 
-  private void deleteProfile(@NotNull InspectionProfileImpl profile) {
-    if (profile.getProfileManager() == myApplicationProfileManager) {
-      myApplicationProfileManager.deleteProfile(profile.getName());
-    }
-    else {
-      myProjectProfileManager.deleteProfile(profile.getName());
-    }
-  }
-
   protected boolean acceptTool(InspectionToolWrapper entry) {
     return true;
   }
@@ -538,13 +521,11 @@ public abstract class InspectionToolsConfigurable extends BaseConfigurable
     myDeletedProfiles.clear();
     disposeUIResources();
     final Collection<InspectionProfileImpl> profiles = getProfiles();
-    final List<InspectionProfileImpl> modifiableProfiles = new ArrayList<>(profiles.size());
+    final List<InspectionProfileModifiableModel> modifiableProfiles = new ArrayList<>(profiles.size());
     for (InspectionProfileImpl profile : profiles) {
-      InspectionProfileImpl modifiableProfile = profile.getModifiableModel();
-      final InspectionProfileImpl inspectionProfile = modifiableProfile;
+      InspectionProfileModifiableModel inspectionProfile = new InspectionProfileModifiableModel(profile);
       modifiableProfiles.add(inspectionProfile);
-      final SingleInspectionProfilePanel panel = createPanel(inspectionProfile);
-      myPanels.add(panel);
+      myPanels.add(createPanel(inspectionProfile));
     }
     myProfiles.getProfilesComboBox().reset(modifiableProfiles);
     myAuxiliaryRightPanel.showDescription(getSelectedObject().getDescription());
@@ -560,7 +541,7 @@ public abstract class InspectionToolsConfigurable extends BaseConfigurable
     }
   }
 
-  private SingleInspectionProfilePanel createPanel(InspectionProfileImpl profile) {
+  private SingleInspectionProfilePanel createPanel(InspectionProfileModifiableModel profile) {
     return new SingleInspectionProfilePanel(myProjectProfileManager, profile) {
       @Override
       protected boolean accept(InspectionToolWrapper entry) {
@@ -651,7 +632,7 @@ public abstract class InspectionToolsConfigurable extends BaseConfigurable
 
   @NotNull
   @Override
-  public InspectionProfileImpl getSelectedObject() {
+  public InspectionProfileModifiableModel getSelectedObject() {
     return myProfiles.getProfilesComboBox().getSelectedProfile();
   }
 
index 4183106480529333f80db20616ba32787f76988b..4a279d600077efb9d8ca242c67865ec4acd2ede0 100644 (file)
@@ -16,6 +16,7 @@
 package com.intellij.profile.codeInspection.ui.header;
 
 import com.intellij.codeInspection.ex.InspectionProfileImpl;
+import com.intellij.codeInspection.ex.InspectionProfileModifiableModel;
 import com.intellij.openapi.application.ApplicationManager;
 import com.intellij.openapi.project.Project;
 import com.intellij.openapi.wm.IdeFocusManager;
@@ -32,7 +33,7 @@ public abstract class ProfilesChooser extends JPanel {
   private static final String COMBO_CARD = "combo.card";
   private static final String EDIT_CARD = "edit.card";
 
-  private final ProfilesComboBox myProfilesComboBox;
+  private final ProfilesComboBox<InspectionProfileModifiableModel> myProfilesComboBox;
   private final CardLayout myCardLayout;
   private final ValidatedTextField mySubmitNameComponent;
   private final SaveInputComponentValidator.Wrapper mySaveListener;
@@ -46,7 +47,7 @@ public abstract class ProfilesChooser extends JPanel {
     myCardLayout = new CardLayout();
     myComboBoxPanel.setLayout(myCardLayout);
     setBorder(IdeBorderFactory.createEmptyBorder(JBUI.insets(4, 0, 6, 0)));
-    myProfilesComboBox = new ProfilesComboBox() {
+    myProfilesComboBox = new ProfilesComboBox<InspectionProfileModifiableModel>() {
       @Override
       protected void onProfileChosen(InspectionProfileImpl inspectionProfile) {
         ProfilesChooser.this.onProfileChosen(inspectionProfile);
@@ -66,7 +67,7 @@ public abstract class ProfilesChooser extends JPanel {
     showComboBoxCard();
   }
 
-  ProfilesComboBox getProfilesComboBox() {
+  ProfilesComboBox<InspectionProfileModifiableModel> getProfilesComboBox() {
     return myProfilesComboBox;
   }
 
index 038d746e2228b3c8d1b3e021fbdb4cbc6eba8546..950b262512641319dd2234aff0f9ecd275303c1f 100644 (file)
@@ -36,17 +36,17 @@ import java.util.List;
 /**
  * @author Dmitry Batkovich
  */
-public abstract class ProfilesComboBox extends ComboBox<InspectionProfileImpl> {
+public abstract class ProfilesComboBox<T extends InspectionProfileImpl> extends ComboBox<T> {
   private static final String PROJECT_LEVEL_SEPARATOR_TEXT = "Project Level";
   private static final String GLOBAL_LEVEL_SEPARATOR_TEXT = "Global Level";
 
-  private SortedComboBoxModel<InspectionProfileImpl> myComboModel;
-  private InspectionProfileImpl myFirstGlobalProfile;
+  private SortedComboBoxModel<T> myComboModel;
+  private T myFirstGlobalProfile;
 
   public ProfilesComboBox() {
-    final Comparator<InspectionProfileImpl> comparator =
-      Comparator.comparing(InspectionProfileImpl::isProjectLevel).reversed().thenComparing(InspectionProfileImpl::getDisplayName);
-    myComboModel = new SortedComboBoxModel<>(comparator);
+    myComboModel = new SortedComboBoxModel<>(Comparator.comparing(T::isProjectLevel)
+                                               .reversed()
+                                               .thenComparing(InspectionProfileImpl::getDisplayName));
     setModel(myComboModel);
     //noinspection GtkPreferredJComboBoxRenderer
     setRenderer(new ListCellRenderer<InspectionProfileImpl>() {
@@ -117,9 +117,9 @@ public abstract class ProfilesComboBox extends ComboBox<InspectionProfileImpl> {
     setSelectedItem(inspectionProfile);
   }
 
-  public void reset(final Collection<InspectionProfileImpl> profiles) {
+  public void reset(final Collection<T> profiles) {
     myComboModel.clear();
-    for (InspectionProfileImpl profile : profiles) {
+    for (T profile : profiles) {
       myComboModel.add(profile);
     }
     findFirstGlobalProfile();
@@ -127,32 +127,32 @@ public abstract class ProfilesComboBox extends ComboBox<InspectionProfileImpl> {
     resort();
   }
 
-  void removeProfile(InspectionProfileImpl profile) {
+  void removeProfile(T profile) {
     myComboModel.remove(profile);
     if (!profile.isProjectLevel() && profile == myFirstGlobalProfile) {
       findFirstGlobalProfile();
     }
   }
 
-  public void addProfile(InspectionProfileImpl inspectionProfile) {
+  public void addProfile(T inspectionProfile) {
     myComboModel.add(inspectionProfile);
     if (!inspectionProfile.isProjectLevel()) {
       findFirstGlobalProfile();
     }
   }
 
-  InspectionProfileImpl getSelectedProfile() {
+  T getSelectedProfile() {
     return myComboModel.getSelectedItem();
   }
 
   @NotNull
-  List<InspectionProfileImpl> getProfiles() {
+  List<T> getProfiles() {
     return myComboModel.getItems();
   }
 
   private void findFirstGlobalProfile() {
     myFirstGlobalProfile = null;
-    for (InspectionProfileImpl profile : getProfiles()) {
+    for (T profile : getProfiles()) {
       if (!profile.isProjectLevel()) {
         myFirstGlobalProfile = profile;
         break;
index 23483aaf056caaf50d18f79a8c976c007d4fa355..b679bef461b6fe032860b9b7c11e1d8993aabadb 100644 (file)
@@ -147,7 +147,7 @@ public abstract class SemanticEditorPosition {
   public int getStartOffset() {
     return myIterator.getStart();
   }
-  
+
   @SuppressWarnings("unused")
   public boolean isAtAnyOf(@NotNull SyntaxElement... syntaxElements) {
     if (!myIterator.atEnd()) {
@@ -172,6 +172,13 @@ public abstract class SemanticEditorPosition {
     return -1;
   }
 
+  public boolean hasEmptyLineAfter(int offset) {
+    for (int i = offset; i < myIterator.getEnd(); i ++) {
+      if (myChars.charAt(i) == '\n') return true;
+    }
+    return false;
+  }
+
   public EditorEx getEditor() {
     return myEditor;
   }
index bc3a750762c321858f2bb549193afda670aa4290..92d6c3c35a42d1f1fb5127bb30948daae34143ae 100644 (file)
@@ -57,7 +57,13 @@ class IndentCalculator {
       return CharArrayUtil.shiftBackward(currPosition.getChars(), currPosition.getStartOffset(), " \t\n\r");
     }
   };
-  
+
+  public final static BaseLineOffsetCalculator LINE_AFTER = new BaseLineOffsetCalculator() {
+    @Override
+    public int getOffsetInBaseIndentLine(@NotNull SemanticEditorPosition currPosition) {
+      return CharArrayUtil.shiftForward(currPosition.getChars(), currPosition.getStartOffset(), " \t\n\r");
+    }
+  };
   
   @Nullable
   String getIndentString(@Nullable Language language, @NotNull SemanticEditorPosition currPosition) {
index 5999d4f812997e1202e35e34b5923b3202013d80..0daff82bbf0f0ad175660bf46cd24c1f2fbdc544 100644 (file)
@@ -85,9 +85,13 @@ public abstract class JavaLikeLangLineIndentProvider implements LineIndentProvid
     if (getPosition(editor, offset).matchesRule(
       position -> position.isAt(Whitespace) &&
                   position.isAtMultiline())) {
-      //noinspection StatementWithEmptyBody
       if (getPosition(editor, offset).before().isAt(Comma)) {
-        // TODO: Add support
+        SemanticEditorPosition position = getPosition(editor,offset);
+        if (position.hasEmptyLineAfter(offset) &&
+            !position.after().isAtAnyOf(ArrayClosingBracket, BlockOpeningBrace, BlockClosingBrace, RightParenthesis) &&
+            !position.isAtEnd()) {
+            return myFactory.createIndentCalculator(NONE, IndentCalculator.LINE_AFTER);
+        }
       }
       else if (getPosition(editor, offset + 1).isAt(BlockClosingBrace)) {
         return myFactory.createIndentCalculator(
index 7fbad12a03b0d252202ebb49d4283579905ce59c..a0928a10b475c06846ae6bc45eafbba8f7494477 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2009 JetBrains s.r.o.
+ * Copyright 2000-2016 JetBrains s.r.o.
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -104,12 +104,13 @@ public abstract class BaseRefactoringAction extends AnAction {
       return;
     }
 
-    if (!InplaceRefactoring.canStartAnotherRefactoring(editor, project, handler, elements)) {
+    InplaceRefactoring activeInplaceRenamer = InplaceRefactoring.getActiveInplaceRenamer(editor);
+    if (!InplaceRefactoring.canStartAnotherRefactoring(editor, project, handler, elements) && activeInplaceRenamer != null) {
       InplaceRefactoring.unableToStartWarning(project, editor);
       return;
     }
 
-    if (InplaceRefactoring.getActiveInplaceRenamer(editor) == null) {
+    if (activeInplaceRenamer == null) {
       final LookupEx lookup = LookupManager.getActiveLookup(editor);
       if (lookup instanceof LookupImpl) {
         Runnable command = () -> ((LookupImpl)lookup).finishLookup(Lookup.NORMAL_SELECT_CHAR);
diff --git a/platform/lang-impl/src/com/intellij/refactoring/changeSignature/ChangeSignatureDetectorAction.java b/platform/lang-impl/src/com/intellij/refactoring/changeSignature/ChangeSignatureDetectorAction.java
deleted file mode 100644 (file)
index 5fe9357..0000000
+++ /dev/null
@@ -1,74 +0,0 @@
-/*
- * Copyright 2000-2010 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.refactoring.changeSignature;
-
-import com.intellij.openapi.editor.Editor;
-import com.intellij.openapi.project.Project;
-import com.intellij.psi.PsiElement;
-import com.intellij.psi.PsiFile;
-import com.intellij.refactoring.BaseRefactoringIntentionAction;
-import com.intellij.util.IncorrectOperationException;
-import org.jetbrains.annotations.NotNull;
-
-/**
- * User: anna
- * Date: Sep 6, 2010
- */
-public class ChangeSignatureDetectorAction extends BaseRefactoringIntentionAction {
-  public static final String CHANGE_SIGNATURE = "Apply signature change";
-  public static final String NEW_NAME = "Apply new name";
-
-  private String myAcceptText;
-
-  @NotNull
-  @Override
-  public String getText() {
-    final String text = myAcceptText;
-    return text != null ? text : CHANGE_SIGNATURE;
-  }
-
-  @NotNull
-  @Override
-  public String getFamilyName() {
-    return CHANGE_SIGNATURE;
-  }
-
-  @Override
-  public boolean isAvailable(@NotNull Project project, Editor editor, @NotNull PsiElement element) {
-    myAcceptText = null;
-    final LanguageChangeSignatureDetector detector = LanguageChangeSignatureDetectors.INSTANCE.forLanguage(element.getLanguage());
-    if (detector != null) {
-      ChangeSignatureGestureDetector signatureGestureDetector = ChangeSignatureGestureDetector.getInstance(project);
-      PsiFile containingFile = element.getContainingFile();
-      ChangeInfo changeInfo = signatureGestureDetector.getChangeInfo(containingFile);
-      ChangeInfo initialChangeInfo = signatureGestureDetector.getInitialChangeInfo(containingFile);
-      if (changeInfo != null && detector.isChangeSignatureAvailableOnElement(element, initialChangeInfo)) {
-        myAcceptText = changeInfo instanceof RenameChangeInfo ? NEW_NAME : CHANGE_SIGNATURE;
-      }
-    }
-    return myAcceptText != null;
-  }
-
-  @Override
-  public void invoke(@NotNull Project project, Editor editor, @NotNull PsiElement element) throws IncorrectOperationException {
-    ChangeSignatureGestureDetector.getInstance(project).changeSignature(element.getContainingFile(), true);
-  }
-
-  @Override
-  public boolean startInWriteAction() {
-    return false;
-  }
-}
diff --git a/platform/lang-impl/src/com/intellij/refactoring/changeSignature/ChangeSignatureGestureDetector.java b/platform/lang-impl/src/com/intellij/refactoring/changeSignature/ChangeSignatureGestureDetector.java
deleted file mode 100644 (file)
index 7975f58..0000000
+++ /dev/null
@@ -1,392 +0,0 @@
-/*
- * Copyright 2000-2016 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.refactoring.changeSignature;
-
-import com.intellij.codeInsight.template.TemplateManager;
-import com.intellij.idea.ActionsBundle;
-import com.intellij.openapi.Disposable;
-import com.intellij.openapi.command.CommandProcessor;
-import com.intellij.openapi.diagnostic.Logger;
-import com.intellij.openapi.editor.Document;
-import com.intellij.openapi.editor.Editor;
-import com.intellij.openapi.editor.EditorBundle;
-import com.intellij.openapi.editor.EditorFactory;
-import com.intellij.openapi.editor.actions.EditorActionUtil;
-import com.intellij.openapi.editor.event.DocumentAdapter;
-import com.intellij.openapi.editor.event.DocumentEvent;
-import com.intellij.openapi.editor.event.EditorFactoryEvent;
-import com.intellij.openapi.editor.event.EditorFactoryListener;
-import com.intellij.openapi.editor.ex.EditorEx;
-import com.intellij.openapi.fileEditor.FileDocumentManager;
-import com.intellij.openapi.fileEditor.FileEditor;
-import com.intellij.openapi.fileEditor.FileEditorManager;
-import com.intellij.openapi.fileEditor.TextEditor;
-import com.intellij.openapi.project.DumbService;
-import com.intellij.openapi.project.Project;
-import com.intellij.openapi.util.Comparing;
-import com.intellij.openapi.util.Disposer;
-import com.intellij.openapi.util.TextRange;
-import com.intellij.openapi.vfs.VirtualFile;
-import com.intellij.psi.*;
-import com.intellij.psi.util.PsiUtilCore;
-import com.intellij.util.IncorrectOperationException;
-import com.intellij.util.containers.HashMap;
-import org.jetbrains.annotations.NonNls;
-import org.jetbrains.annotations.NotNull;
-import org.jetbrains.annotations.Nullable;
-
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Map;
-
-/**
- * User: anna
- * Date: Sep 6, 2010
- */
-public class ChangeSignatureGestureDetector extends PsiTreeChangeAdapter implements EditorFactoryListener, Disposable {
-  private final Map<VirtualFile, MyDocumentChangeAdapter> myListenerMap = new HashMap<>();
-  private static final Logger LOG = Logger.getInstance("#" + ChangeSignatureGestureDetector.class.getName());
-  private boolean myDeaf = false;
-  private final FileDocumentManager myDocumentManager;
-  private final PsiManager myPsiManager;
-  private final FileEditorManager myFileEditorManager;
-  private final Project myProject;
-  private final PsiDocumentManager myPsiDocumentManager;
-
-  public ChangeSignatureGestureDetector(final PsiDocumentManager psiDocumentManager,
-                                        final FileDocumentManager documentManager,
-                                        final PsiManager psiManager,
-                                        final FileEditorManager fileEditorManager,
-                                        final Project project) {
-    myDocumentManager = documentManager;
-    myPsiDocumentManager = psiDocumentManager;
-    myPsiManager = psiManager;
-    myFileEditorManager = fileEditorManager;
-    myProject = project;
-    myPsiManager.addPsiTreeChangeListener(this, this);
-    EditorFactory.getInstance().addEditorFactoryListener(this, this);
-    Disposer.register(this, new Disposable() {
-      @Override
-      public void dispose() {
-        LOG.assertTrue(myListenerMap.isEmpty(), myListenerMap);
-      }
-    });
-  }
-
-  public static ChangeSignatureGestureDetector getInstance(Project project){
-    return project.getComponent(ChangeSignatureGestureDetector.class);
-  }
-
-  public boolean isChangeSignatureAvailable(@NotNull PsiElement element) {
-    final MyDocumentChangeAdapter adapter = myListenerMap.get(PsiUtilCore.getVirtualFile(element));
-    if (adapter != null) {
-      final ChangeInfo currentInfo = adapter.getCurrentInfo();
-      if (currentInfo != null && element.equals(adapter.getInitialChangeInfo().getMethod())) {
-        return true;
-      }
-    }
-    return false;
-  }
-
-  public void dismissForElement(PsiElement method) {
-    final PsiFile psiFile = method.getContainingFile();
-    final ChangeInfo initialChangeInfo = getInitialChangeInfo(psiFile);
-    if (initialChangeInfo != null && initialChangeInfo.getMethod() == method) {
-      clearSignatureChange(psiFile);
-    }
-  }
-
-  public boolean containsChangeSignatureChange(@NotNull PsiFile file) {
-    return getChangeInfo(file) != null;
-  }
-
-  @Nullable
-  public ChangeInfo getChangeInfo(@NotNull PsiFile file) {
-    final MyDocumentChangeAdapter adapter = myListenerMap.get(file.getVirtualFile());
-    return adapter != null ? adapter.getCurrentInfo() : null;
-  }
-
-  @Nullable
-   public ChangeInfo getInitialChangeInfo(@NotNull PsiFile file) {
-     final MyDocumentChangeAdapter adapter = myListenerMap.get(file.getVirtualFile());
-     return adapter != null ? adapter.getInitialChangeInfo() : null;
-   }
-
-  public void changeSignature(PsiFile file, final boolean silently) {
-    try {
-      myDeaf = true;
-      final MyDocumentChangeAdapter changeBean = myListenerMap.get(file.getVirtualFile());
-      final ChangeInfo currentInfo = changeBean.getCurrentInfo();
-      if (currentInfo != null) {
-        final LanguageChangeSignatureDetector detector = LanguageChangeSignatureDetectors.INSTANCE.forLanguage(currentInfo.getLanguage());
-        if (detector.performChange(currentInfo, changeBean.getInitialChangeInfo(), changeBean.getInitialText(), silently)) {
-          changeBean.reinit();
-        }
-      }
-    }
-    finally {
-      myDeaf = false;
-    }
-  }
-
-  @Override
-  public void beforeChildRemoval(@NotNull PsiTreeChangeEvent event) {
-    final PsiElement child = event.getChild();
-    if (child instanceof PsiFile) {
-      final PsiFile psiFile = (PsiFile)child;
-      final VirtualFile virtualFile = psiFile.getVirtualFile();
-      if (virtualFile != null && myListenerMap.containsKey(virtualFile)) {
-        final Document document = myDocumentManager.getDocument(virtualFile);
-        if (document != null) {
-          removeDocListener(document, virtualFile);
-        } else {
-          myListenerMap.remove(virtualFile);
-        }
-      }
-    }
-  }
-
-  @Override
-  public void childRemoved(@NotNull PsiTreeChangeEvent event) {
-    change(event.getParent());
-  }
-
-  @Override
-  public void childReplaced(@NotNull PsiTreeChangeEvent event) {
-    change(event.getChild());
-  }
-
-  @Override
-  public void childAdded(@NotNull PsiTreeChangeEvent event) {
-    change(event.getChild());
-  }
-
-  private void change(PsiElement child) {
-    if (myDeaf) return;
-    if (child == null || !child.isValid()) return;
-    final PsiFile file = child.getContainingFile();
-    if (file != null) {
-      final MyDocumentChangeAdapter changeBean = myListenerMap.get(file.getVirtualFile());
-      if (changeBean != null && changeBean.getInitialText() != null) {
-        final Editor editor = myFileEditorManager.getSelectedTextEditor();
-        if (editor != null && TemplateManager.getInstance(myProject).getActiveTemplate(editor) != null) return;
-        final LanguageChangeSignatureDetector detector = LanguageChangeSignatureDetectors.INSTANCE.forLanguage(child.getLanguage());
-        if (detector == null) return;
-        if (detector.ignoreChanges(child)) return;
-        final String currentSignature = detector.extractSignature(child, changeBean.getInitialChangeInfo());
-        if (currentSignature == null) {
-          changeBean.reinit();
-        } else {
-          changeBean.addSignature(currentSignature);
-        }
-      }
-    }
-  }
-
-  @Override
-  public void editorCreated(@NotNull EditorFactoryEvent event) {
-    final Editor editor = event.getEditor();
-    if (editor.getProject() != myProject) return;
-    addDocListener(editor.getDocument());
-  }
-
-  public void addDocListener(Document document) {
-    if (document == null) return;
-    final VirtualFile file = myDocumentManager.getFile(document);
-    if (file != null && file.isValid() && !myListenerMap.containsKey(file)) {
-      final PsiFile psiFile = myPsiManager.findFile(file);
-      if (psiFile == null || !psiFile.isPhysical()) return;
-      final MyDocumentChangeAdapter adapter = new MyDocumentChangeAdapter();
-      document.addDocumentListener(adapter);
-      myListenerMap.put(file, adapter);
-    }
-  }
-
-  @Override
-  public void editorReleased(@NotNull EditorFactoryEvent event) {
-    final EditorEx editor = (EditorEx)event.getEditor();
-    final Document document = editor.getDocument();
-
-    VirtualFile file = myDocumentManager.getFile(document);
-    if (file == null) {
-      file = editor.getVirtualFile();
-    }
-    if (file != null && file.isValid()) {
-      for (FileEditor fileEditor : myFileEditorManager.getAllEditors(file)) {
-        if (fileEditor instanceof TextEditor && ((TextEditor)fileEditor).getEditor() != editor) {
-          return;
-        }
-      }
-    }
-    removeDocListener(document, file);
-  }
-
-  public void removeDocListener(Document document, VirtualFile file) {
-    final MyDocumentChangeAdapter adapter = myListenerMap.remove(file);
-    if (adapter != null) {
-      document.removeDocumentListener(adapter);
-    }
-  }
-
-  public void clearSignatureChange(PsiFile file) {
-    final MyDocumentChangeAdapter adapter = myListenerMap.get(file.getVirtualFile());
-    if (adapter != null) {
-      adapter.reinit();
-    }
-  }
-
-  @Nullable
-  private static ChangeInfo createCurrentChangeInfo(String signature, @NotNull ChangeInfo currentInfo, String initialName) {
-    final LanguageChangeSignatureDetector detector = LanguageChangeSignatureDetectors.INSTANCE.forLanguage(currentInfo.getLanguage());
-    return detector != null ? detector.createNextChangeInfo(signature, currentInfo, initialName) : null;
-  }
-
-  @Nullable
-  private static ChangeInfo createInitialChangeInfo(@NotNull PsiElement element) {
-    final LanguageChangeSignatureDetector detector = LanguageChangeSignatureDetectors.INSTANCE.forLanguage(element.getLanguage());
-    return detector != null ? detector.createInitialChangeInfo(element) : null;
-  }
-
-  private class MyDocumentChangeAdapter extends DocumentAdapter {
-    private final @NonNls String [] COMMANDS = {
-      EditorBundle.message("paste.command.name"), 
-      EditorBundle.message("typing.in.editor.command.name"),
-      ActionsBundle.message("action.MoveElementLeft.text"),
-      ActionsBundle.message("action.MoveElementRight.text"),
-      "Cut",
-      LanguageChangeSignatureDetector.MOVE_PARAMETER
-    };
-
-    private String myInitialText;
-    private String myInitialName;
-    private ChangeInfo myInitialChangeInfo;
-    private ChangeInfo myCurrentInfo;
-
-    private final List<String> mySignatures = new ArrayList<>();
-
-    public MyDocumentChangeAdapter() {
-    }
-
-    public String getInitialText() {
-      return myInitialText;
-    }
-
-    public ChangeInfo getCurrentInfo() {
-      if (myInitialChangeInfo == null) return null;
-      synchronized (mySignatures) {
-        if (!mySignatures.isEmpty()) {
-          if (myCurrentInfo == null) {
-            myCurrentInfo = myInitialChangeInfo;
-          }
-
-          for (String signature : mySignatures) {
-            if (myInitialText.equals(signature)) {
-              reinit();
-              break;
-            }
-            try {
-              myCurrentInfo = createCurrentChangeInfo(signature, myCurrentInfo, myInitialName);
-              if (myCurrentInfo == null) {
-                reinit();
-                break;
-              }
-            }
-            catch (IncorrectOperationException ignore) {
-            }
-          }
-          mySignatures.clear();
-        }
-      }
-      if (myCurrentInfo instanceof RenameChangeInfo) return myCurrentInfo;
-      return myInitialChangeInfo != null && myInitialChangeInfo.equals(myCurrentInfo) ? null : myCurrentInfo;
-    }
-
-    public void addSignature(String signature) {
-      synchronized (mySignatures) {
-        if (!mySignatures.contains(signature)) {
-          mySignatures.add(signature);
-        }
-      }
-    }
-
-    @Override
-    public void beforeDocumentChange(DocumentEvent e) {
-      if (myDeaf) return;
-      if (DumbService.isDumb(myProject)) return;
-      if (myInitialText == null) {
-        final Document document = e.getDocument();
-        final PsiDocumentManager documentManager = myPsiDocumentManager;
-
-        if (!documentManager.isUncommited(document)) {
-          final CommandProcessor processor = CommandProcessor.getInstance();
-          final String currentCommandName = processor.getCurrentCommandName();
-
-          if (!isPredefinedCommand(processor, currentCommandName)) return;
-
-          final PsiFile file = documentManager.getPsiFile(document);
-          if (file != null) {
-            final PsiElement element = file.findElementAt(e.getOffset());
-            if (element != null) {
-              final ChangeInfo info = createInitialChangeInfo(element);
-              if (info != null) {
-                final PsiElement method = info.getMethod();
-                final TextRange textRange = method.getTextRange();
-                if (document.getTextLength() <= textRange.getEndOffset()) return;
-                if (method instanceof PsiNameIdentifierOwner) {
-                  myInitialName = ((PsiNameIdentifierOwner)method).getName();
-                }
-                myInitialText =  document.getText(textRange);
-                myInitialChangeInfo = info;
-              }
-            }
-          }
-        }
-      }
-    }
-
-    private boolean isPredefinedCommand(CommandProcessor processor, String currentCommandName) {
-      if (Comparing.equal(EditorActionUtil.DELETE_COMMAND_GROUP, processor.getCurrentCommandGroupId())) {
-        return true;
-      }
-
-      for (String commandName : COMMANDS) {
-        if (Comparing.strEqual(commandName, currentCommandName)){
-          return true;
-        }
-      }
-      return false;
-    }
-
-    public ChangeInfo getInitialChangeInfo() {
-      return myInitialChangeInfo;
-    }
-
-    public void reinit() {
-      synchronized (mySignatures) {
-        mySignatures.clear();
-      }
-      myInitialText = null;
-      myInitialName = null;
-      myInitialChangeInfo = null;
-      myCurrentInfo = null;
-    }
-  }
-
-  @Override
-  public void dispose() {
-
-  }
-}
diff --git a/platform/lang-impl/src/com/intellij/refactoring/changeSignature/DismissNewSignatureIntentionAction.java b/platform/lang-impl/src/com/intellij/refactoring/changeSignature/DismissNewSignatureIntentionAction.java
deleted file mode 100644 (file)
index 46eb7ae..0000000
+++ /dev/null
@@ -1,56 +0,0 @@
-/*
- * Copyright 2000-2011 JetBrains s.r.o.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.intellij.refactoring.changeSignature;
-
-import com.intellij.codeInsight.intention.IntentionAction;
-import com.intellij.openapi.editor.Editor;
-import com.intellij.openapi.project.Project;
-import com.intellij.psi.PsiFile;
-import com.intellij.util.IncorrectOperationException;
-import org.jetbrains.annotations.NotNull;
-
-/**
- * User: anna
- * Date: 11/3/11
- */
-class DismissNewSignatureIntentionAction implements IntentionAction {
-  @NotNull
-  @Override
-  public String getText() {
-    return "Dismiss new signature";
-  }
-
-  @NotNull
-  @Override
-  public String getFamilyName() {
-    return getText();
-  }
-
-  @Override
-  public boolean isAvailable(@NotNull Project project, Editor editor, PsiFile file) {
-    return true;
-  }
-
-  @Override
-  public void invoke(@NotNull Project project, Editor editor, PsiFile file) throws IncorrectOperationException {
-    ChangeSignatureGestureDetector.getInstance(project).clearSignatureChange(file);
-  }
-
-  @Override
-  public boolean startInWriteAction() {
-    return false;
-  }
-}
diff --git a/platform/lang-impl/src/com/intellij/refactoring/changeSignature/MoveParameterAction.java b/platform/lang-impl/src/com/intellij/refactoring/changeSignature/MoveParameterAction.java
deleted file mode 100644 (file)
index 9af8aaa..0000000
+++ /dev/null
@@ -1,49 +0,0 @@
-package com.intellij.refactoring.changeSignature;
-
-import com.intellij.openapi.actionSystem.*;
-import com.intellij.openapi.diagnostic.Logger;
-import com.intellij.openapi.editor.Editor;
-import com.intellij.psi.PsiElement;
-
-/**
- * User: anna
- * Date: Sep 10, 2010
- */
-public abstract class MoveParameterAction extends AnAction{
-  private final boolean myLeft;
-  private static final Logger LOG = Logger.getInstance("#" + MoveParameterAction.class.getName());
-
-  public MoveParameterAction(boolean left) {
-    super();
-    myLeft = left;
-  }
-
-  @Override
-  public void actionPerformed(AnActionEvent e) {
-    final DataContext dataContext = e.getDataContext();
-    final PsiElement psiElement = CommonDataKeys.PSI_ELEMENT.getData(dataContext);
-    LOG.assertTrue(psiElement != null);
-    final Editor editor = CommonDataKeys.EDITOR.getData(dataContext);
-    LanguageChangeSignatureDetectors.INSTANCE.forLanguage(psiElement.getLanguage()).moveParameter(psiElement, editor, myLeft);
-  }
-
-
-  @Override
-  public void update(AnActionEvent e) {
-    final Presentation presentation = e.getPresentation();
-    presentation.setEnabled(false);
-    final DataContext dataContext = e.getDataContext();
-    final Editor editor = CommonDataKeys.EDITOR.getData(dataContext);
-    if (editor != null) {
-      final PsiElement psiElement = CommonDataKeys.PSI_ELEMENT.getData(dataContext);
-      if (psiElement != null) {
-        final LanguageChangeSignatureDetector detector = LanguageChangeSignatureDetectors.INSTANCE.forLanguage(psiElement.getLanguage());
-        if (detector != null) {
-          final boolean available = detector.isMoveParameterAvailable(psiElement, myLeft);
-          presentation.setEnabled(available);
-          presentation.setVisible(available);
-        }
-      }
-    }
-  }
-}
diff --git a/platform/lang-impl/src/com/intellij/refactoring/changeSignature/MoveParameterRightAction.java b/platform/lang-impl/src/com/intellij/refactoring/changeSignature/MoveParameterRightAction.java
deleted file mode 100644 (file)
index 8f2eb78..0000000
+++ /dev/null
@@ -1,26 +0,0 @@
-/*
- * Copyright 2000-2010 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.refactoring.changeSignature;
-
-/**
- * User: anna
- * Date: Sep 10, 2010
- */
-public class MoveParameterRightAction extends MoveParameterAction {
-  public MoveParameterRightAction() {
-    super(false);
-  }
-}
diff --git a/platform/lang-impl/src/com/intellij/refactoring/changeSignature/inplace/ApplyChangeSignatureAction.java b/platform/lang-impl/src/com/intellij/refactoring/changeSignature/inplace/ApplyChangeSignatureAction.java
new file mode 100644 (file)
index 0000000..1fa0b43
--- /dev/null
@@ -0,0 +1,80 @@
+/*
+ * Copyright 2000-2016 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.refactoring.changeSignature.inplace;
+
+import com.intellij.openapi.editor.Editor;
+import com.intellij.openapi.project.Project;
+import com.intellij.psi.PsiElement;
+import com.intellij.refactoring.BaseRefactoringIntentionAction;
+import com.intellij.refactoring.RefactoringBundle;
+import com.intellij.refactoring.changeSignature.ChangeInfo;
+import com.intellij.util.IncorrectOperationException;
+import org.jetbrains.annotations.NotNull;
+
+/**
+ * User: anna
+ * Date: Sep 6, 2010
+ */
+public class ApplyChangeSignatureAction extends BaseRefactoringIntentionAction {
+  public static final String CHANGE_SIGNATURE = "Apply signature change";
+  private final String myMethodName;
+
+  public ApplyChangeSignatureAction(String methodName) {
+    myMethodName = methodName;
+  }
+
+  @NotNull
+  @Override
+  public String getText() {
+    return RefactoringBundle.message("changing.signature.of.0", myMethodName);
+  }
+
+  @NotNull
+  @Override
+  public String getFamilyName() {
+    return CHANGE_SIGNATURE;
+  }
+
+  @Override
+  public boolean isAvailable(@NotNull Project project, Editor editor, @NotNull PsiElement element) {
+    final LanguageChangeSignatureDetector<ChangeInfo> detector = LanguageChangeSignatureDetectors.INSTANCE.forLanguage(element.getLanguage());
+    if (detector != null) {
+      InplaceChangeSignature changeSignature = InplaceChangeSignature.getCurrentRefactoring(editor);
+      ChangeInfo currentInfo = changeSignature != null ? changeSignature.getCurrentInfo() : null;
+      if (currentInfo != null && detector.isChangeSignatureAvailableOnElement(element, currentInfo)) {
+        return true;
+      }
+    }
+    return false;
+  }
+
+  @Override
+  public void invoke(@NotNull Project project, Editor editor, @NotNull PsiElement element) throws IncorrectOperationException {
+    InplaceChangeSignature signatureGestureDetector = InplaceChangeSignature.getCurrentRefactoring(editor);
+    final String initialSignature = signatureGestureDetector.getInitialSignature();
+    final ChangeInfo currentInfo = signatureGestureDetector.getCurrentInfo();
+    signatureGestureDetector.detach();
+
+    final LanguageChangeSignatureDetector<ChangeInfo> detector = LanguageChangeSignatureDetectors.INSTANCE.forLanguage(element.getLanguage());
+
+    detector.performChange(currentInfo, initialSignature);
+  }
+
+  @Override
+  public boolean startInWriteAction() {
+    return false;
+  }
+}
similarity index 72%
rename from platform/lang-impl/src/com/intellij/refactoring/changeSignature/ChangeSignaturePassFactory.java
rename to platform/lang-impl/src/com/intellij/refactoring/changeSignature/inplace/ChangeSignaturePassFactory.java
index 732a44452b6eec6bf8574bed322bdab8a45e2fa1..9e20a2f1902fda0548f0df38099c14fc6a91697f 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2014 JetBrains s.r.o.
+ * Copyright 2000-2016 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.
@@ -13,9 +13,8 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
-package com.intellij.refactoring.changeSignature;
+package com.intellij.refactoring.changeSignature.inplace;
 
-import com.intellij.codeHighlighting.Pass;
 import com.intellij.codeHighlighting.TextEditorHighlightingPass;
 import com.intellij.codeHighlighting.TextEditorHighlightingPassFactory;
 import com.intellij.codeHighlighting.TextEditorHighlightingPassRegistrar;
@@ -23,7 +22,7 @@ import com.intellij.codeInsight.daemon.impl.HighlightInfo;
 import com.intellij.codeInsight.daemon.impl.HighlightInfoType;
 import com.intellij.codeInsight.daemon.impl.UpdateHighlightersUtil;
 import com.intellij.codeInsight.daemon.impl.quickfix.QuickFixAction;
-import com.intellij.codeInsight.intention.IntentionAction;
+import com.intellij.lang.findUsages.DescriptiveNameUtil;
 import com.intellij.openapi.components.AbstractProjectComponent;
 import com.intellij.openapi.editor.Editor;
 import com.intellij.openapi.editor.colors.CodeInsightColors;
@@ -33,24 +32,23 @@ import com.intellij.openapi.project.Project;
 import com.intellij.openapi.util.TextRange;
 import com.intellij.psi.PsiElement;
 import com.intellij.psi.PsiFile;
+import com.intellij.refactoring.changeSignature.ChangeInfo;
 import org.jetbrains.annotations.NonNls;
 import org.jetbrains.annotations.NotNull;
-import org.jetbrains.annotations.Nullable;
 
 import java.awt.*;
-import java.util.ArrayList;
 import java.util.Collection;
 import java.util.Collections;
 
 public class ChangeSignaturePassFactory extends AbstractProjectComponent implements TextEditorHighlightingPassFactory {
   public ChangeSignaturePassFactory(Project project, TextEditorHighlightingPassRegistrar highlightingPassRegistrar) {
     super(project);
-    highlightingPassRegistrar.registerTextEditorHighlightingPass(this, new int[]{Pass.UPDATE_ALL}, null, false, -1);
+    highlightingPassRegistrar.registerTextEditorHighlightingPass(this, null, null, true, -1);
   }
 
   @Override
   public TextEditorHighlightingPass createHighlightingPass(@NotNull final PsiFile file, @NotNull final Editor editor) {
-    LanguageChangeSignatureDetector detector =
+    LanguageChangeSignatureDetector<ChangeInfo> detector =
       LanguageChangeSignatureDetectors.INSTANCE.forLanguage(file.getLanguage());
     if (detector == null) return null;
 
@@ -63,58 +61,41 @@ public class ChangeSignaturePassFactory extends AbstractProjectComponent impleme
     private final PsiFile myFile;
     private final Editor myEditor;
 
-    private TextRange myRange;
-
     public ChangeSignaturePass(Project project, PsiFile file, Editor editor) {
-      super(project, editor.getDocument(), false);
+      super(project, editor.getDocument(), true);
       myProject = project;
       myFile = file;
       myEditor = editor;
     }
 
     @Override
-    public void doCollectInformation(@NotNull ProgressIndicator progress) {
-      myRange = null;
-      final ChangeSignatureGestureDetector detector = ChangeSignatureGestureDetector.getInstance(myProject);
-      final ChangeInfo changeInfo = detector.getInitialChangeInfo(myFile);
-      if (changeInfo != null) {
+    public void doCollectInformation(@NotNull ProgressIndicator progress) {}
+
+    @Override
+    public void doApplyInformationToEditor() {
+      HighlightInfo info = null;
+      final InplaceChangeSignature currentRefactoring = InplaceChangeSignature.getCurrentRefactoring(myEditor);
+      if (currentRefactoring != null) {
+        final ChangeInfo changeInfo = currentRefactoring.getStableChange();
         final PsiElement element = changeInfo.getMethod();
         int offset = myEditor.getCaretModel().getOffset();
         if (element == null || !element.isValid()) return;
         final TextRange elementTextRange = element.getTextRange();
         if (elementTextRange == null || !elementTextRange.contains(offset)) return;
-        final TextRange range = getHighlightingRange(changeInfo);
-        if (range != null && detector.isChangeSignatureAvailable(element)) {
-          myRange = range;
-        }
-      }
-    }
-
-    @Override
-    public void doApplyInformationToEditor() {
-      HighlightInfo info = null;
-      if (myRange != null)  {
+        final LanguageChangeSignatureDetector<ChangeInfo> detector = LanguageChangeSignatureDetectors.INSTANCE.forLanguage(changeInfo.getLanguage());
+        TextRange range = detector.getHighlightingRange(changeInfo);
         TextAttributes attributes = new TextAttributes(null, null,
                                                        myEditor.getColorsScheme().getAttributes(CodeInsightColors.WEAK_WARNING_ATTRIBUTES)
                                                          .getEffectColor(),
                                                        null, Font.PLAIN);
-        HighlightInfo.Builder builder = HighlightInfo.newHighlightInfo(HighlightInfoType.INFORMATION).range(myRange);
+        HighlightInfo.Builder builder = HighlightInfo.newHighlightInfo(HighlightInfoType.INFORMATION).range(range);
         builder.textAttributes(attributes);
         builder.descriptionAndTooltip(SIGNATURE_SHOULD_BE_POSSIBLY_CHANGED);
         info = builder.createUnconditionally();
-        final ArrayList<IntentionAction> options = new ArrayList<>();
-        options.add(new DismissNewSignatureIntentionAction());
-        QuickFixAction.registerQuickFixAction(info, new ChangeSignatureDetectorAction(), options, null);
+        QuickFixAction.registerQuickFixAction(info, new ApplyChangeSignatureAction(DescriptiveNameUtil.getDescriptiveName(element)));
       }
       Collection<HighlightInfo> infos = info != null ? Collections.singletonList(info) : Collections.<HighlightInfo>emptyList();
       UpdateHighlightersUtil.setHighlightersToEditor(myProject, myDocument, 0, myFile.getTextLength(), infos, getColorsScheme(), getId());
     }
-
-    @Nullable
-    private static TextRange getHighlightingRange(ChangeInfo changeInfo) {
-      if (changeInfo == null) return null;
-      final LanguageChangeSignatureDetector detector = LanguageChangeSignatureDetectors.INSTANCE.forLanguage(changeInfo.getLanguage());
-      return detector != null ? detector.getHighlightingRange(changeInfo) : null;
-    }
   }
 }
diff --git a/platform/lang-impl/src/com/intellij/refactoring/changeSignature/inplace/EscapeHandler.java b/platform/lang-impl/src/com/intellij/refactoring/changeSignature/inplace/EscapeHandler.java
new file mode 100644 (file)
index 0000000..7b4220d
--- /dev/null
@@ -0,0 +1,50 @@
+/*
+ * Copyright 2000-2016 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.refactoring.changeSignature.inplace;
+
+import com.intellij.openapi.actionSystem.DataContext;
+import com.intellij.openapi.editor.Editor;
+import com.intellij.openapi.editor.actionSystem.EditorActionHandler;
+
+public class EscapeHandler extends EditorActionHandler {
+  private final EditorActionHandler myOriginalHandler;
+
+  public EscapeHandler(EditorActionHandler originalHandler) {
+    myOriginalHandler = originalHandler;
+  }
+
+  @Override
+  public void execute(Editor editor, DataContext dataContext) {
+    InplaceChangeSignature currentRefactoring = InplaceChangeSignature.getCurrentRefactoring(editor);
+    if (currentRefactoring != null) {
+      currentRefactoring.cancel();
+      return;
+    }
+
+    if (myOriginalHandler.isEnabled(editor, dataContext)) {
+      myOriginalHandler.execute(editor, dataContext);
+    }
+  }
+
+  @Override
+  public boolean isEnabled(Editor editor, DataContext dataContext) {
+    InplaceChangeSignature currentRefactoring = InplaceChangeSignature.getCurrentRefactoring(editor);
+    if (currentRefactoring != null) {
+      return true;
+    }
+    return myOriginalHandler.isEnabled(editor, dataContext);
+  }
+}
diff --git a/platform/lang-impl/src/com/intellij/refactoring/changeSignature/inplace/InplaceChangeSignature.java b/platform/lang-impl/src/com/intellij/refactoring/changeSignature/inplace/InplaceChangeSignature.java
new file mode 100644 (file)
index 0000000..f612d07
--- /dev/null
@@ -0,0 +1,213 @@
+/*
+ * Copyright 2000-2016 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.refactoring.changeSignature.inplace;
+
+import com.intellij.codeInsight.highlighting.HighlightManager;
+import com.intellij.openapi.command.WriteCommandAction;
+import com.intellij.openapi.command.impl.FinishMarkAction;
+import com.intellij.openapi.command.impl.StartMarkAction;
+import com.intellij.openapi.editor.Document;
+import com.intellij.openapi.editor.Editor;
+import com.intellij.openapi.editor.ScrollType;
+import com.intellij.openapi.editor.VisualPosition;
+import com.intellij.openapi.editor.colors.EditorColors;
+import com.intellij.openapi.editor.colors.EditorColorsManager;
+import com.intellij.openapi.editor.event.DocumentEvent;
+import com.intellij.openapi.editor.event.DocumentListener;
+import com.intellij.openapi.editor.markup.RangeHighlighter;
+import com.intellij.openapi.editor.markup.TextAttributes;
+import com.intellij.openapi.fileEditor.OpenFileDescriptor;
+import com.intellij.openapi.project.Project;
+import com.intellij.openapi.ui.Messages;
+import com.intellij.openapi.ui.popup.Balloon;
+import com.intellij.openapi.ui.popup.BalloonBuilder;
+import com.intellij.openapi.ui.popup.JBPopupFactory;
+import com.intellij.openapi.util.Key;
+import com.intellij.openapi.util.TextRange;
+import com.intellij.openapi.vfs.VirtualFile;
+import com.intellij.psi.PsiDocumentManager;
+import com.intellij.psi.PsiElement;
+import com.intellij.psi.PsiFile;
+import com.intellij.psi.PsiWhiteSpace;
+import com.intellij.psi.util.PsiTreeUtil;
+import com.intellij.psi.util.PsiUtilCore;
+import com.intellij.refactoring.RefactoringBundle;
+import com.intellij.refactoring.changeSignature.ChangeInfo;
+import com.intellij.refactoring.changeSignature.ChangeSignatureHandler;
+import com.intellij.ui.awt.RelativePoint;
+import com.intellij.ui.components.JBCheckBox;
+import com.intellij.util.ui.PositionTracker;
+import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
+
+import java.awt.*;
+import java.util.ArrayList;
+
+public class InplaceChangeSignature implements DocumentListener {
+  public static final Key<InplaceChangeSignature> INPLACE_CHANGE_SIGNATURE = Key.create("EditorInplaceChangeSignature");
+  private ChangeInfo myCurrentInfo;
+  private ChangeInfo myStableChange;
+  private String myInitialSignature;
+  private Editor myEditor;
+  private LanguageChangeSignatureDetector<ChangeInfo> myDetector;
+
+  private final Project myProject;
+  private final PsiDocumentManager myDocumentManager;
+  private final ArrayList<RangeHighlighter> myHighlighters = new ArrayList<>();
+  private StartMarkAction myMarkAction;
+  private Balloon myBalloon;
+  private boolean myDelegate;
+
+  public InplaceChangeSignature(Project project, Editor editor, @NotNull PsiElement element) {
+    myDocumentManager = PsiDocumentManager.getInstance(project);
+    myProject = project;
+    try {
+      myMarkAction = StartMarkAction.start(editor, project, ChangeSignatureHandler.REFACTORING_NAME);
+    }
+    catch (StartMarkAction.AlreadyStartedException e) {
+      final int exitCode = Messages.showYesNoDialog(myProject, e.getMessage(), ChangeSignatureHandler.REFACTORING_NAME, "Navigate to Started", "Cancel", Messages.getErrorIcon());
+      if (exitCode == Messages.CANCEL) return;
+      PsiElement method = myStableChange.getMethod();
+      VirtualFile virtualFile = PsiUtilCore.getVirtualFile(method);
+      new OpenFileDescriptor(project, virtualFile, method.getTextOffset()).navigate(true);
+      return;
+    }
+
+
+    myEditor = editor;
+    myDetector = LanguageChangeSignatureDetectors.INSTANCE.forLanguage(element.getLanguage());
+    myStableChange = myDetector.createInitialChangeInfo(element);
+    myInitialSignature = myDetector.extractSignature(myStableChange);
+    TextRange highlightingRange = myDetector.getHighlightingRange(myStableChange);
+
+    HighlightManager highlightManager = HighlightManager.getInstance(myProject);
+    TextAttributes attributes = EditorColorsManager.getInstance().getGlobalScheme().getAttributes(EditorColors.LIVE_TEMPLATE_ATTRIBUTES);
+    highlightManager.addRangeHighlight(editor, highlightingRange.getStartOffset(), highlightingRange.getEndOffset(), attributes, false, myHighlighters);
+    for (RangeHighlighter highlighter : myHighlighters) {
+      highlighter.setGreedyToRight(true);
+      highlighter.setGreedyToLeft(true);
+    }
+    myEditor.getDocument().addDocumentListener(this);
+    showBalloon();
+    myEditor.putUserData(INPLACE_CHANGE_SIGNATURE, this);
+  }
+
+  @Nullable
+  public static InplaceChangeSignature getCurrentRefactoring(Editor editor) {
+    return editor.getUserData(INPLACE_CHANGE_SIGNATURE);
+  }
+
+  public ChangeInfo getCurrentInfo() {
+    return myCurrentInfo;
+  }
+
+  public String getInitialSignature() {
+    return myInitialSignature;
+  }
+
+  @NotNull
+  public ChangeInfo getStableChange() {
+    return myStableChange;
+  }
+
+  public void cancel() {
+    TextRange highlightingRange = myDetector.getHighlightingRange(getStableChange());
+    Document document = myEditor.getDocument();
+    String initialSignature = myInitialSignature;
+    detach();
+    temporallyRevertChanges(highlightingRange, document, initialSignature, myProject);
+  }
+
+  @Override
+  public void beforeDocumentChange(DocumentEvent event) {}
+
+  @Override
+  public void documentChanged(DocumentEvent event) {
+    myDocumentManager.performWhenAllCommitted(() -> {
+      if (myDetector == null) {
+        return;
+      }
+      PsiFile file = myDocumentManager.getPsiFile(event.getDocument());
+      if (file == null) {
+        return;
+      }
+      PsiElement element = file.findElementAt(event.getOffset());
+      if (myDetector.ignoreChanges(element)) return;
+
+      if (element instanceof PsiWhiteSpace) {
+        PsiElement method = myStableChange.getMethod();
+        if (PsiTreeUtil.skipSiblingsForward(element, PsiWhiteSpace.class) == method) {
+          return;
+        }
+      }
+
+      if (!myDetector.isChangeSignatureAvailableOnElement(element, myStableChange)) {
+        detach();
+        return;
+      }
+
+      if (myCurrentInfo == null) {
+        myCurrentInfo = myStableChange;
+      }
+      String signature = myDetector.extractSignature(myCurrentInfo);
+      ChangeInfo changeInfo = myDetector.createNextChangeInfo(signature, myCurrentInfo, myDelegate);
+      if (changeInfo == null && myCurrentInfo != null) {
+        myStableChange = myCurrentInfo;
+      }
+      myCurrentInfo = changeInfo;
+    });
+  }
+
+  protected void showBalloon() {
+    JBCheckBox checkBox = new JBCheckBox(RefactoringBundle.message("delegation.panel.delegate.via.overloading.method"));
+    checkBox.addActionListener(e -> myDelegate = checkBox.isSelected());
+    final BalloonBuilder balloonBuilder = JBPopupFactory.getInstance().createDialogBalloonBuilder(checkBox, null).setSmallVariant(true);
+    myBalloon = balloonBuilder.createBalloon();
+    myEditor.getScrollingModel().scrollToCaret(ScrollType.MAKE_VISIBLE);
+    final JBPopupFactory popupFactory = JBPopupFactory.getInstance();
+    myBalloon.show(new PositionTracker<Balloon>(myEditor.getContentComponent()) {
+      @Override
+      public RelativePoint recalculateLocation(Balloon object) {
+        int offset = myStableChange.getMethod().getTextOffset();
+        VisualPosition visualPosition = myEditor.offsetToVisualPosition(offset);
+        Point point = myEditor.visualPositionToXY(new VisualPosition(visualPosition.line, visualPosition.column));
+        return new RelativePoint(myEditor.getContentComponent(), point);
+      }
+    }, Balloon.Position.above);
+  }
+
+  public void detach() {
+    myEditor.getDocument().removeDocumentListener(this);
+    HighlightManager highlightManager = HighlightManager.getInstance(myProject);
+    for (RangeHighlighter highlighter : myHighlighters) {
+      highlightManager.removeSegmentHighlighter(myEditor, highlighter);
+    }
+    myHighlighters.clear();
+    myBalloon.hide();
+    FinishMarkAction.finish(myProject, myEditor, myMarkAction);
+    myEditor.putUserData(INPLACE_CHANGE_SIGNATURE, null);
+  }
+
+  public static void temporallyRevertChanges(final TextRange signatureRange,
+                                             final Document document,
+                                             final String initialSignature,
+                                             Project project) {
+    WriteCommandAction.runWriteCommandAction(project, () -> {
+      document.replaceString(signatureRange.getStartOffset(), signatureRange.getEndOffset(), initialSignature);
+      PsiDocumentManager.getInstance(project).commitDocument(document);
+    });
+  }
+}
similarity index 50%
rename from platform/lang-impl/src/com/intellij/refactoring/changeSignature/LanguageChangeSignatureDetector.java
rename to platform/lang-impl/src/com/intellij/refactoring/changeSignature/inplace/LanguageChangeSignatureDetector.java
index a67846d777ff041a458e8431d014dfd81b1b9495..9ff3e3e21ed7ad699e5b53a6fc7d99eb69399afa 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2010 JetBrains s.r.o.
+ * Copyright 2000-2016 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.
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
-package com.intellij.refactoring.changeSignature;
+package com.intellij.refactoring.changeSignature.inplace;
 
-import com.intellij.openapi.editor.Editor;
 import com.intellij.openapi.util.TextRange;
 import com.intellij.psi.PsiElement;
+import com.intellij.refactoring.changeSignature.ChangeInfo;
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
 
@@ -25,20 +25,20 @@ import org.jetbrains.annotations.Nullable;
  * User: anna
  * Date: Sep 6, 2010
  */
-public interface LanguageChangeSignatureDetector {
-  String MOVE_PARAMETER = "Parameter Move";
+public interface LanguageChangeSignatureDetector<C extends ChangeInfo> {
 
-  @Nullable ChangeInfo createInitialChangeInfo(final @NotNull PsiElement element);
-  @Nullable String extractSignature(PsiElement child, @NotNull ChangeInfo initialChangeInfo);
+  @NotNull  C createInitialChangeInfo(final @NotNull PsiElement element);
   boolean ignoreChanges(PsiElement element);
-  @Nullable ChangeInfo createNextChangeInfo(String signature, @NotNull ChangeInfo currentInfo, String initialName);
+  @Nullable C createNextChangeInfo(String signature, @NotNull C currentInfo, boolean delegate);
 
-  boolean performChange(ChangeInfo changeInfo, ChangeInfo initialChangeInfo, @NotNull String oldText, boolean silently);
+  void performChange(C changeInfo, @NotNull String oldText);
 
-  boolean isChangeSignatureAvailableOnElement(PsiElement element, ChangeInfo currentInfo);
-  @Nullable TextRange getHighlightingRange(ChangeInfo changeInfo);
+  boolean isChangeSignatureAvailableOnElement(PsiElement element, C currentInfo);
 
+  TextRange getHighlightingRange(@NotNull C changeInfo);
 
-  boolean isMoveParameterAvailable(PsiElement parameter, boolean left);
-  void moveParameter(PsiElement parameter, Editor editor, boolean left);
+  default @NotNull String extractSignature(@NotNull C initialChangeInfo) {
+    final TextRange signatureRange = getHighlightingRange(initialChangeInfo);
+    return signatureRange.shiftRight(-signatureRange.getStartOffset()).substring(initialChangeInfo.getMethod().getText());
+  }
 }
similarity index 75%
rename from platform/lang-impl/src/com/intellij/refactoring/changeSignature/LanguageChangeSignatureDetectors.java
rename to platform/lang-impl/src/com/intellij/refactoring/changeSignature/inplace/LanguageChangeSignatureDetectors.java
index c0470ace88133d84f649a5d3c2d5b47fb50eec40..9a4400dd38dc88bca7dff912c61ab38043b1fb63 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2010 JetBrains s.r.o.
+ * Copyright 2000-2016 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.
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
-package com.intellij.refactoring.changeSignature;
+package com.intellij.refactoring.changeSignature.inplace;
 
 import com.intellij.lang.LanguageExtension;
+import com.intellij.refactoring.changeSignature.ChangeInfo;
 
 /**
  * User: anna
  * Date: Sep 9, 2010
  */
-class LanguageChangeSignatureDetectors extends LanguageExtension<LanguageChangeSignatureDetector> {
+public class LanguageChangeSignatureDetectors extends LanguageExtension<LanguageChangeSignatureDetector<ChangeInfo>> {
   public static final LanguageChangeSignatureDetectors INSTANCE = new LanguageChangeSignatureDetectors();
 
   LanguageChangeSignatureDetectors() {
similarity index 89%
rename from platform/lang-impl/src/com/intellij/refactoring/changeSignature/RenameChangeInfo.java
rename to platform/lang-impl/src/com/intellij/refactoring/changeSignature/inplace/RenameChangeInfo.java
index 46f06774b2bfb3faee597bd23dc3ed094bc33b30..1153bc6c571aba429e0b9699bc21a7de62b3bf7e 100644 (file)
@@ -1,20 +1,27 @@
 /*
- * Copyright 2000-2010 JetBrains s.r.o.
+ * Copyright 2000-2016 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.refactoring.changeSignature;
+package com.intellij.refactoring.changeSignature.inplace;
 
 import com.intellij.openapi.application.ApplicationManager;
-import com.intellij.psi.*;
+import com.intellij.psi.PsiElement;
+import com.intellij.psi.PsiFile;
+import com.intellij.psi.PsiNameIdentifierOwner;
 import com.intellij.psi.util.PsiTreeUtil;
+import com.intellij.refactoring.changeSignature.ChangeInfo;
+import com.intellij.refactoring.changeSignature.ParameterInfo;
 import com.intellij.refactoring.rename.RenameProcessor;
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
index e3388b013c490c67d8c33ee8e0c9fbac2c1caa87..cfb30aed6770bd7be3afc387fcf190292575128a 100644 (file)
@@ -1482,7 +1482,7 @@ public class FileBasedIndexImpl extends FileBasedIndex {
     try {
       // if file was scheduled for update due to vfs events then it is present in myFilesToUpdate
       // in this case we consider that current indexing (out of roots backed CacheUpdater) will cover its content
-      if (content.getTimeStamp() != file.getTimeStamp()) {
+      if (file.isValid() && content.getTimeStamp() != file.getTimeStamp()) {
         content = new com.intellij.ide.caches.FileContent(file);
       }
       if (!file.isValid() || isTooLarge(file)) {
index acbe474820525ce1126f919bf403c91b872ed847..1988e123a0c6c15b181df5f65ecfe05c182afa81 100644 (file)
@@ -17,6 +17,7 @@ package com.intellij.ide;
 
 import com.intellij.Patches;
 import com.intellij.openapi.application.ApplicationManager;
+import com.intellij.openapi.application.ex.ClipboardUtil;
 import com.intellij.openapi.components.ApplicationComponent;
 import com.intellij.openapi.diagnostic.Logger;
 import com.intellij.openapi.util.Pair;
@@ -24,14 +25,15 @@ import com.intellij.openapi.util.SystemInfo;
 import com.intellij.openapi.util.registry.Registry;
 import com.intellij.ui.mac.foundation.Foundation;
 import com.intellij.ui.mac.foundation.ID;
+import com.intellij.util.Consumer;
 import com.intellij.util.ReflectionUtil;
-import com.intellij.util.TimeoutUtil;
 import com.intellij.util.concurrency.FutureResult;
 import com.sun.jna.IntegerType;
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
 import sun.awt.datatransfer.DataTransferer;
 
+import javax.swing.*;
 import java.awt.*;
 import java.awt.datatransfer.*;
 import java.io.IOException;
@@ -41,6 +43,8 @@ import java.util.Collection;
 import java.util.Collections;
 import java.util.Set;
 import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.function.Supplier;
 
 /**
  * This class is used to workaround the problem with getting clipboard contents (http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4818143).
@@ -94,25 +98,57 @@ public class ClipboardSynchronizer implements ApplicationComponent {
     return "ClipboardSynchronizer";
   }
 
-  public boolean areDataFlavorsAvailable(@NotNull DataFlavor... flavors) {
-    try {
-      return myClipboardHandler.areDataFlavorsAvailable(flavors);
+  public void areDataFlavorsAvailableAsync(@NotNull Consumer<Boolean> callback, @NotNull DataFlavor... flavors) {
+    final Supplier<Boolean> availabilitySupplier =
+      () -> ClipboardUtil.handleClipboardSafely(() -> myClipboardHandler.areDataFlavorsAvailable(flavors),() -> false);
+
+    Boolean available = availabilitySupplier.get();
+    if (available) {
+      callback.consume(available);
+    } else {
+      AtomicInteger counter = new AtomicInteger();
+
+      Timer timer = new Timer(50, event -> {});
+      timer.addActionListener( event -> {
+        Boolean a = availabilitySupplier.get();
+        if (counter.incrementAndGet() > 3 || a) {
+          timer.stop();
+        }
+        callback.consume(a);
+      });
+      timer.start();
     }
-    catch (IllegalStateException e) {
-      LOG.info(e);
-      return false;
+  }
+
+  public void getContentsAsync(@NotNull Consumer<Transferable> callback) {
+    final Supplier<Transferable> transferableSupplier =
+      () -> ClipboardUtil.handleClipboardSafely(myClipboardHandler::getContents, () -> null);
+
+    Transferable transferable = transferableSupplier.get();
+    if (transferable != null) {
+      callback.consume(transferable);
+    } else {
+      AtomicInteger counter = new AtomicInteger();
+
+      Timer timer = new Timer(50, event -> {});
+      timer.addActionListener( event -> {
+        Transferable t = transferableSupplier.get();
+        if (counter.incrementAndGet() > 3) {
+          timer.stop();
+        }
+        callback.consume(t);
+      });
+      timer.start();
     }
   }
 
+  public boolean areDataFlavorsAvailable(@NotNull DataFlavor... flavors) {
+    return ClipboardUtil.handleClipboardSafely(() -> myClipboardHandler.areDataFlavorsAvailable(flavors), () -> false);
+  }
+
   @Nullable
   public Transferable getContents() {
-    try {
-      return myClipboardHandler.getContents();
-    }
-    catch (IllegalStateException e) {
-      LOG.info(e);
-      return null;
-    }
+    return ClipboardUtil.handleClipboardSafely(myClipboardHandler::getContents, () -> null);
   }
 
   public void setContent(@NotNull final Transferable content, @NotNull final ClipboardOwner owner) {
@@ -156,40 +192,15 @@ public class ClipboardSynchronizer implements ApplicationComponent {
 
 
     @Nullable
-    public Transferable getContents() throws IllegalStateException {
-      IllegalStateException last = null;
-      for (int i = 0; i < 3; i++) {
-        try {
-          Clipboard clipboard = getClipboard();
-          if (clipboard == null){
-            TimeoutUtil.sleep(50);
-            continue;
-          }
-          return clipboard.getContents(this);
-        }
-        catch (IllegalStateException e) {
-          TimeoutUtil.sleep(50);
-          last = e;
-        }
-      }
-      throw last;
+    public Transferable getContents() {
+      Clipboard clipboard = getClipboard();
+      return clipboard == null ? null: clipboard.getContents(this);
     }
 
     public void setContent(@NotNull final Transferable content, @NotNull final ClipboardOwner owner) {
-      for (int i = 0; i < 3; i++) {
-        try {
-          Clipboard clipboard = getClipboard();
-          if (clipboard == null) {
-            TimeoutUtil.sleep(50);
-            continue;
-          }
-          clipboard.setContents(content, owner);
-        }
-        catch (IllegalStateException e) {
-          TimeoutUtil.sleep(50);
-          continue;
-        }
-        break;
+      Clipboard clipboard = getClipboard();
+      if (clipboard !=null) {
+        clipboard.setContents(content, owner);
       }
     }
 
@@ -202,14 +213,7 @@ public class ClipboardSynchronizer implements ApplicationComponent {
     private Pair<String,Transferable> myFullTransferable;
 
     @Nullable
-    private Transferable doGetContents() throws IllegalStateException {
-      if (Registry.is("ide.mac.useNativeClipboard")) {
-        final Transferable safe = getContentsSafe();
-        if (safe != null) {
-          return safe;
-        }
-      }
-
+    private Transferable doGetContents() {
       return super.getContents();
     }
 
index a51e3eeeb1aa0189eb697227a5533cb7204e683d..d68f9edb89487ff5350ddde00edf58d00325b168 100644 (file)
  */
 package com.intellij.openapi.application.ex;
 
+import com.intellij.openapi.diagnostic.Logger;
 import com.intellij.openapi.ide.CopyPasteManager;
+import com.intellij.openapi.util.SystemInfo;
 import org.jetbrains.annotations.Nullable;
 
 import java.awt.datatransfer.DataFlavor;
+import java.util.function.Supplier;
 
 public class ClipboardUtil {
 
+  private static final Logger LOG = Logger.getInstance("#com.intellij.ide.Clipboard");
+
+  public static <E> E handleClipboardSafely(Supplier<E> supplier, Supplier<E> onFail) {
+    try {
+      return supplier.get();
+    }catch (IllegalStateException e) {
+      if (SystemInfo.isWindows) {
+        LOG.debug("Clipboard is busy");
+      } else {
+        LOG.warn(e);
+      }
+      return onFail.get();
+    }
+  }
+
   @Nullable
   public static String getTextInClipboard() {
     return CopyPasteManager.getInstance().getContents(DataFlavor.stringFlavor);
index 95df4253b62f1cb38fcddfe62859a0db5d155ebc..504d46ab2a5e57eceffd902ac177cbd3fa857af5 100644 (file)
  */
 package com.intellij.openapi.components.impl.stores;
 
-import com.intellij.notification.Notification;
-import com.intellij.notification.NotificationListener;
 import com.intellij.notification.NotificationType;
 import com.intellij.notification.NotificationsManager;
-import com.intellij.openapi.application.*;
+import com.intellij.openapi.application.ApplicationManager;
+import com.intellij.openapi.application.ApplicationNamesInfo;
+import com.intellij.openapi.application.PathMacros;
+import com.intellij.openapi.application.WriteAction;
 import com.intellij.openapi.components.ComponentManager;
 import com.intellij.openapi.components.ServiceKt;
 import com.intellij.openapi.components.TrackingPathMacroSubstitutor;
@@ -40,11 +41,9 @@ import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
 import org.jetbrains.annotations.TestOnly;
 
-import javax.swing.event.HyperlinkEvent;
 import java.io.IOException;
 import java.nio.file.Files;
 import java.nio.file.Path;
-import java.util.Iterator;
 import java.util.LinkedHashSet;
 import java.util.Map;
 import java.util.Set;
@@ -53,7 +52,7 @@ public class StorageUtil {
   public static final String NOTIFICATION_GROUP_ID = "Load Error";
   
   @TestOnly
-  public static String DEBUG_LOG = null;
+  public static String DEBUG_LOG;
 
   private StorageUtil() { }
 
@@ -68,12 +67,7 @@ public class StorageUtil {
                      "Some of the files describing the current project settings contain unknown path variables " +
                      "and " + productName + " cannot restore those paths.";
     new UnknownMacroNotification(NOTIFICATION_GROUP_ID, "Load error: undefined path variables", content, NotificationType.ERROR,
-                                 new NotificationListener() {
-                                   @Override
-                                   public void hyperlinkUpdate(@NotNull Notification notification, @NotNull HyperlinkEvent event) {
-                                     checkUnknownMacros(project, true, macros, substitutorToStore);
-                                   }
-                                 }, macros).notify(project);
+                                 (notification, event) -> checkUnknownMacros(project, true, macros, substitutorToStore), macros).notify(project);
   }
 
   public static void checkUnknownMacros(@NotNull Project project, boolean notify) {
@@ -101,17 +95,12 @@ public class StorageUtil {
                                          boolean showDialog,
                                          @NotNull Set<String> unknownMacros,
                                          @NotNull Map<TrackingPathMacroSubstitutor, IComponentStore> substitutorToStore) {
-    if (unknownMacros.isEmpty() || (showDialog && !ProjectMacrosUtil.checkMacros(project, new THashSet<>(unknownMacros)))) {
+    if (unknownMacros.isEmpty() || showDialog && !ProjectMacrosUtil.checkMacros(project, new THashSet<>(unknownMacros))) {
       return;
     }
 
     PathMacros pathMacros = PathMacros.getInstance();
-    for (Iterator<String> it = unknownMacros.iterator(); it.hasNext(); ) {
-      String macro = it.next();
-      if (StringUtil.isEmptyOrSpaces(pathMacros.getValue(macro)) && !pathMacros.isIgnoredMacroName(macro)) {
-        it.remove();
-      }
-    }
+    unknownMacros.removeIf(macro -> StringUtil.isEmptyOrSpaces(pathMacros.getValue(macro)) && !pathMacros.isIgnoredMacroName(macro));
 
     if (unknownMacros.isEmpty()) {
       return;
index fb201c5041372187a9591ac0c481a1ee0dd2a83a..4cb50d3f09495de1e98fda35af6904883bcbd997 100644 (file)
@@ -840,6 +840,11 @@ public class CaretImpl extends UserDataHolderBase implements Caret, Dumpable {
   public Caret clone(boolean above) {
     assertIsDispatchThread();
     int lineShift = above ? -1 : 1;
+    LogicalPosition oldPosition = getLogicalPosition();
+    int newLine = oldPosition.line + lineShift;
+    if (newLine < 0 || newLine >= myEditor.getDocument().getLineCount()) {
+      return null;
+    }
     final CaretImpl clone = cloneWithoutSelection();
     final int newSelectionStartOffset;
     final int newSelectionEndOffset;
@@ -875,12 +880,6 @@ public class CaretImpl extends UserDataHolderBase implements Caret, Dumpable {
       newSelectionStartColumn = -1;
       newSelectionEndColumn = -1;
     }
-    LogicalPosition oldPosition = getLogicalPosition();
-    int newLine = oldPosition.line + lineShift;
-    if (newLine < 0 || newLine >= myEditor.getDocument().getLineCount()) {
-      Disposer.dispose(clone);
-      return null;
-    }
     clone.moveToLogicalPosition(new LogicalPosition(newLine, myLastColumnNumber), false, null, false);
     clone.myLastColumnNumber = myLastColumnNumber;
     clone.myDesiredX = myDesiredX >= 0 ? myDesiredX : getCurrentX();
index 39f6f99809c879be56b13a9d25b5cdb277640b6b..9f66afd272150683f4b612e11416ada5f75c8bea 100644 (file)
@@ -96,13 +96,9 @@ public class ProgressManagerImpl extends CoreProgressManager implements Disposab
   @Override
   @NotNull
   public Future<?> runProcessWithProgressAsynchronously(@NotNull Task.Backgroundable task) {
-    final ProgressIndicator progressIndicator;
-    if (ApplicationManager.getApplication().isHeadlessEnvironment()) {
-      progressIndicator = new EmptyProgressIndicator();
-    }
-    else {
-      progressIndicator = new BackgroundableProcessIndicator(task);
-    }
+    ProgressIndicator progressIndicator = ApplicationManager.getApplication().isHeadlessEnvironment() ?
+                                          new EmptyProgressIndicator() :
+                                          new BackgroundableProcessIndicator(task);
     return runProcessWithProgressAsynchronously(task, progressIndicator, null);
   }
 
@@ -135,13 +131,13 @@ public class ProgressManagerImpl extends CoreProgressManager implements Disposab
           exception = e;
         }
         final long end = System.currentTimeMillis();
-        final long time = end - start;
 
         final boolean finalCanceled = processCanceled || progressIndicator.isCanceled();
         final Throwable finalException = exception;
 
         if (!finalCanceled) {
           final Task.NotificationInfo notificationInfo = task.notifyFinished();
+          final long time = end - start;
           if (notificationInfo != null && time > 5000) { // snow notification if process took more than 5 secs
             final Component window = KeyboardFocusManager.getCurrentKeyboardFocusManager().getActiveWindow();
             if (window == null || notificationInfo.isShowWhenFocused()) {
index dadd49495563feb31bb509905feba7c519caf6b4..6a8ff719fd87b53dcae513e06a702dc4b6f529cf 100644 (file)
@@ -22,9 +22,7 @@ import com.intellij.openapi.application.ApplicationManager;
 import com.intellij.openapi.application.ModalityState;
 import com.intellij.openapi.application.ex.ApplicationEx;
 import com.intellij.openapi.application.ex.ApplicationManagerEx;
-import com.intellij.openapi.progress.ProcessCanceledException;
-import com.intellij.openapi.progress.ProgressIndicator;
-import com.intellij.openapi.progress.ProgressManager;
+import com.intellij.openapi.progress.*;
 import com.intellij.openapi.util.EmptyRunnable;
 import com.intellij.openapi.util.Ref;
 import com.intellij.util.ui.EdtInvocationManager;
@@ -88,7 +86,7 @@ public class ProgressIndicatorUtils {
    * This method attempts to run provided action synchronously in a read action, so that, if possible, it wouldn't impact any pending, 
    * executing or future write actions (for this to work effectively the action should invoke {@link ProgressManager#checkCanceled()} or 
    * {@link ProgressIndicator#checkCanceled()} often enough). 
-   * It returns <code>true</code> if action was executed successfully. It returns <code>false</code> if the action was not
+   * It returns {@code true} if action was executed successfully. It returns {@code false} if the action was not
    * executed successfully, i.e. if:
    * <ul>
    * <li>write action was in progress when the method was called</li>
@@ -104,7 +102,7 @@ public class ProgressIndicatorUtils {
   }
 
   public static boolean runWithWriteActionPriority(@NotNull final Runnable action,
-                                                @NotNull final ProgressIndicator progressIndicator) {
+                                                   @NotNull final ProgressIndicator progressIndicator) {
     final ApplicationEx application = (ApplicationEx)ApplicationManager.getApplication();
 
     if (application.isWriteActionPending()) {
index f0b527d8b72ae50007eae34dff588275f786cf8e..f1b493c2c7d24054700cbd0ec3bca1a332c79730 100644 (file)
@@ -386,8 +386,7 @@ public class ProjectManagerImpl extends ProjectManagerEx implements Disposable {
   }
 
   private static boolean canCancelProjectLoading() {
-    ProgressIndicator indicator = ProgressIndicatorProvider.getGlobalProgressIndicator();
-    return !(indicator instanceof NonCancelableSection);
+    return !ProgressManager.getInstance().isInNonCancelableSection();
   }
 
   @Override
index d56b7bd50c2734778f25fed567e27d9af99148e5..9845ba01859b2477944c593a8e7d9d7cd17713d0 100644 (file)
     <extensionPoint name="stacktrace.fold" beanClass="com.intellij.execution.console.CustomizableConsoleFoldingBean"/>
     <extensionPoint name="changeSignatureDetector"
                     beanClass="com.intellij.lang.LanguageExtensionPoint">
-      <with attribute="implementationClass" implements="com.intellij.refactoring.changeSignature.LanguageChangeSignatureDetector"/>
+      <with attribute="implementationClass" implements="com.intellij.refactoring.changeSignature.inplace.LanguageChangeSignatureDetector"/>
     </extensionPoint>
 
     <extensionPoint name="preserveIndentOnPaste" beanClass="com.intellij.codeInsight.editorActions.PreserveIndentOnPasteBean"/>
index 8948df13a53ffe220b44400019f51cf8b221496c..4bf8716b0c48bb78b7ecc9583f3259ac72b29048 100644 (file)
     <smartPointerElementInfoFactory implementation="com.intellij.psi.impl.smartPointers.AnchorElementInfoFactory"/>
     <codeInsight.lineMarkerProvider language="" implementationClass="com.intellij.execution.lineMarker.RunLineMarkerProvider"/>
     <projectService serviceImplementation="com.intellij.execution.TestStateStorage"/>
+    <editorActionHandler action="EditorEscape" implementationClass="com.intellij.refactoring.changeSignature.inplace.EscapeHandler" id="changeSignatureEscape" order="before hide-search"/>
 
     <schemeExporter
       name="Code Style XML File"
index 554b39486f1d69e6cd04c5db6c15d5a9431218ab..e180b552186f118439111596326f1325ec54385a 100644 (file)
       <skipForDefaultProject/>
     </component>
     <component>
-      <implementation-class>com.intellij.refactoring.changeSignature.ChangeSignaturePassFactory</implementation-class>
+      <implementation-class>com.intellij.refactoring.changeSignature.inplace.ChangeSignaturePassFactory</implementation-class>
       <skipForDefaultProject/>
     </component>
     <component>
       <implementation-class>com.intellij.openapi.roots.impl.PushedFilePropertiesUpdaterImpl</implementation-class>
     </component>
 
-    <component>
-      <implementation-class>com.intellij.refactoring.changeSignature.ChangeSignatureGestureDetector</implementation-class>
-      <skipForDefaultProject/>
-    </component>
-
     <component>
       <interface-class>com.intellij.facet.pointers.FacetPointersManager</interface-class>
       <implementation-class>com.intellij.facet.impl.pointers.FacetPointersManagerImpl</implementation-class>
index 7e08e891433e79dc4850cdfb951db3ad11344667..b75591c4ade0235b93d971bc30da97d74ad9414d 100644 (file)
@@ -187,9 +187,9 @@ public class JobUtilTest extends PlatformTestCase {
 
   private static class MyException extends RuntimeException {}
   public void testExceptionalCompletion() throws Throwable {
-    final List<Object> objects = Collections.nCopies(100000000, null);
     COUNT.set(0);
     try {
+      final List<Object> objects = Collections.nCopies(100000000, null);
       JobLauncher.getInstance().invokeConcurrentlyUnderProgress(objects, null, true, o -> {
         if (COUNT.incrementAndGet() == 100000) {
           System.out.println("PCE");
@@ -204,8 +204,8 @@ public class JobUtilTest extends PlatformTestCase {
     }
   }
   public void testNotNormalCompletion() throws Throwable {
-    final List<Object> objects = Collections.nCopies(100000000, null);
     COUNT.set(0);
+    final List<Object> objects = Collections.nCopies(100000000, null);
     boolean success = JobLauncher.getInstance().invokeConcurrentlyUnderProgress(objects, null, true, o -> {
       if (COUNT.incrementAndGet() == 100000) {
         System.out.println("PCE");
@@ -217,8 +217,8 @@ public class JobUtilTest extends PlatformTestCase {
   }
 
   public void testJobUtilCompletesEvenIfCannotGrabReadAction() throws Throwable {
-    final List<Object> objects = Collections.nCopies(1000000, null);
     COUNT.set(0);
+    final List<Object> objects = Collections.nCopies(1000000, null);
     ApplicationManager.getApplication().runWriteAction(() -> {
       boolean success = JobLauncher.getInstance().invokeConcurrentlyUnderProgress(objects, null, true, false, o -> {
         COUNT.incrementAndGet();
index 1c1cfd78857b16162b976f79310673c54eabecec..82089f91b13f5bb56e6d7e320ae67243d0295095 100644 (file)
@@ -635,4 +635,30 @@ public class ProgressIndicatorTest extends LightPlatformTestCase {
     ApplicationManager.getApplication().invokeLater(semaphore::up);
     assertTrue("invokeAndWait would deadlock", semaphore.waitFor(1000));
   }
+
+  public void testNonCancelableSectionDetectedCorrectly() {
+    ProgressManager progressManager = ProgressManager.getInstance();
+    assertFalse(progressManager.isInNonCancelableSection());
+    progressManager.run(new Task.Modal(getProject(), "", false) {
+      @Override
+      public void run(@NotNull ProgressIndicator indicator) {
+        assertFalse(indicator instanceof NonCancelableIndicator);
+        assertFalse(progressManager.isInNonCancelableSection());
+        progressManager.executeNonCancelableSection(() -> {
+          assertTrue(progressManager.getProgressIndicator() instanceof NonCancelableIndicator);
+          assertTrue(progressManager.isInNonCancelableSection());
+
+          progressManager.executeProcessUnderProgress(() -> {
+            assertFalse(progressManager.getProgressIndicator() instanceof NonCancelableIndicator);
+            assertTrue(progressManager.isInNonCancelableSection());
+          }, new DaemonProgressIndicator());
+
+          assertTrue(progressManager.isInNonCancelableSection());
+        });
+
+        assertFalse(progressManager.isInNonCancelableSection());
+      }
+    });
+    assertFalse(progressManager.isInNonCancelableSection());
+  }
 }
index 4ff3d5d0b734e1745266d606cd57678b805cd0af..ee328614a132fee308ecead4e578abc2cb95a485 100644 (file)
+++ b/