Merge remote-tracking branch 'origin/master'
authorDmitry Trofimov <dmitry.trofimov@jetbrains.com>
Wed, 1 Feb 2012 15:29:17 +0000 (16:29 +0100)
committerDmitry Trofimov <dmitry.trofimov@jetbrains.com>
Wed, 1 Feb 2012 15:29:17 +0000 (16:29 +0100)
237 files changed:
RegExpSupport/RegExpSupport.iml
RegExpSupport/src/META-INF/RegExpPlugin.xml
RegExpSupport/src/org/intellij/lang/regexp/RegExpLanguageHost.java
RegExpSupport/src/org/intellij/lang/regexp/RegExpLanguageHosts.java [new file with mode: 0644]
RegExpSupport/src/org/intellij/lang/regexp/RegExpWordSelectionFilter.java
RegExpSupport/src/org/intellij/lang/regexp/validation/RegExpAnnotator.java
java/compiler/impl/src/com/intellij/compiler/CompileServerManager.java
java/compiler/impl/src/com/intellij/compiler/impl/CompilerUtil.java
java/compiler/impl/src/com/intellij/compiler/options/CompilerOptionsPanel.form
java/java-impl/java-impl.iml
java/java-impl/src/com/intellij/codeInsight/completion/JavaCompletionContributor.java
java/java-impl/src/com/intellij/codeInsight/completion/JavaCompletionData.java
java/java-impl/src/com/intellij/codeInsight/daemon/impl/GlobalUsageHelper.java [new file with mode: 0644]
java/java-impl/src/com/intellij/codeInsight/daemon/impl/PostHighlightingPass.java
java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/ChangeMethodSignatureFromUsageFix.java
java/java-impl/src/com/intellij/codeInsight/generation/GenerateDelegateHandler.java
java/java-impl/src/com/intellij/codeInsight/generation/GenerateMembersUtil.java
java/java-impl/src/com/intellij/codeInspection/canBeFinal/CanBeFinalHandler.java [new file with mode: 0644]
java/java-impl/src/com/intellij/codeInspection/canBeFinal/CanBeFinalInspection.java
java/java-impl/src/com/intellij/ide/hierarchy/call/CallHierarchyNodeDescriptor.java
java/java-impl/src/com/intellij/psi/impl/JavaRegExpHost.java [new file with mode: 0644]
java/java-impl/src/com/intellij/refactoring/actions/RenameFileAction.java [moved from platform/lang-impl/src/com/intellij/refactoring/rename/RenameFileAction.java with 82% similarity]
java/java-impl/src/com/intellij/refactoring/move/moveClassesOrPackages/MoveJavaFileHandler.java
java/java-impl/src/com/intellij/refactoring/rename/RenameJavaVariableProcessor.java
java/java-impl/src/com/intellij/refactoring/typeMigration/TypeMigrationLabeler.java
java/java-impl/src/com/intellij/refactoring/typeMigration/rules/RootTypeConversionRule.java
java/java-psi-api/src/com/intellij/psi/PsiTypeVisitor.java
java/java-psi-impl/src/com/intellij/core/CoreJavaFileManager.java
java/java-psi-impl/src/com/intellij/psi/PsiDiamondTypeImpl.java
java/java-psi-impl/src/com/intellij/psi/impl/PsiSubstitutorImpl.java
java/java-psi-impl/src/com/intellij/psi/impl/compiled/ClsClassImpl.java
java/java-psi-impl/src/com/intellij/psi/impl/source/PsiJavaCodeReferenceElementImpl.java
java/java-tests/testData/codeInsight/completion/normal/PackageInMemberType.java [new file with mode: 0644]
java/java-tests/testData/codeInsight/completion/normal/PackageInMemberType_after.java [new file with mode: 0644]
java/java-tests/testData/fileStructure/selection/Anonymous.java [new file with mode: 0644]
java/java-tests/testData/fileStructure/selection/Anonymous.tree [new file with mode: 0644]
java/java-tests/testData/fileStructure/selection/AnonymousInAnonymous.java [new file with mode: 0644]
java/java-tests/testData/fileStructure/selection/AnonymousInAnonymous.tree [new file with mode: 0644]
java/java-tests/testSrc/Anonymous.java [new file with mode: 0644]
java/java-tests/testSrc/com/intellij/codeInsight/completion/NormalCompletionTest.groovy
java/java-tests/testSrc/com/intellij/ide/fileStructure/JavaFileStructureSelectionTest.java
java/java-tests/testSrc/com/intellij/ide/fileStructure/JavaFileStructureTestCase.java
java/jdkAnnotations/java/awt/annotations.xml
jps/jps-builders/jps-builders.iml
jps/jps-builders/src/org/jetbrains/jps/incremental/CompileContext.java
jps/jps-builders/src/org/jetbrains/jps/incremental/IncProjectBuilder.java
jps/jps-builders/src/org/jetbrains/jps/incremental/ModuleLevelBuilder.java
jps/jps-builders/src/org/jetbrains/jps/incremental/groovy/GroovyBuilder.java
jps/jps-builders/src/org/jetbrains/jps/incremental/java/JavaBuilder.java
jps/jps-builders/src/org/jetbrains/jps/server/ServerMessageHandler.java
jps/jps-builders/testSrc/org/jetbrains/ether/IncrementalTestCase.java
platform/core-impl/src/com/intellij/openapi/vfs/impl/jar/CoreJarVirtualFile.java
platform/core-impl/src/com/intellij/psi/impl/PsiCachedValue.java
platform/lang-api/src/com/intellij/refactoring/util/MoveRenameUsageInfo.java
platform/lang-impl/src/com/intellij/codeInsight/completion/CodeCompletionHandlerBase.java
platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/DaemonTooltipRendererProvider.java
platform/lang-impl/src/com/intellij/codeInspection/ex/HTMLComposerImpl.java
platform/lang-impl/src/com/intellij/execution/ui/layout/actions/RestoreViewAction.java
platform/lang-impl/src/com/intellij/execution/ui/layout/impl/GridCellImpl.java
platform/lang-impl/src/com/intellij/execution/ui/layout/impl/RunnerContentUi.java
platform/lang-impl/src/com/intellij/ide/hierarchy/HierarchyBrowserBase.java
platform/lang-impl/src/com/intellij/ide/util/FileStructurePopup.java
platform/lang-impl/src/com/intellij/ide/util/gotoByName/ChooseByNameBase.java
platform/lang-impl/src/com/intellij/ide/util/gotoByName/ChooseByNamePopup.java
platform/lang-impl/src/com/intellij/openapi/roots/ui/configuration/PlatformContentEntriesConfigurable.java
platform/lang-impl/src/com/intellij/openapi/roots/ui/configuration/actions/ModuleDeleteProvider.java
platform/lang-impl/src/com/intellij/refactoring/rename/RenameUtil.java
platform/lang-impl/src/com/intellij/util/indexing/FileBasedIndex.java
platform/platform-api/src/com/intellij/ide/util/treeView/AbstractTreeUi.java
platform/platform-api/src/com/intellij/openapi/actionSystem/KeyboardModifierGestureShortcut.java [moved from platform/platform-api/src/com/intellij/openapi/actionSystem/KeyboardModifierGestureShortuct.java with 84% similarity]
platform/platform-api/src/com/intellij/openapi/keymap/KeymapUtil.java
platform/platform-api/src/com/intellij/openapi/ui/LoadingDecorator.java
platform/platform-api/src/com/intellij/openapi/ui/Messages.java
platform/platform-api/src/com/intellij/ui/tabs/impl/JBTabsImpl.java
platform/platform-api/src/com/intellij/util/ui/AnimatedIcon.java
platform/platform-api/src/com/intellij/util/ui/Animator.java
platform/platform-api/src/com/intellij/util/ui/AsyncProcessIcon.java
platform/platform-api/src/com/intellij/util/ui/ButtonlessScrollBarUI.java
platform/platform-api/src/com/intellij/util/ui/tree/TreeUtil.java
platform/platform-impl/src/com/intellij/ide/actionMacro/ActionMacroManager.java
platform/platform-impl/src/com/intellij/ide/actions/BackAction.java
platform/platform-impl/src/com/intellij/ide/actions/ForwardAction.java
platform/platform-impl/src/com/intellij/openapi/editor/impl/ScrollingModelImpl.java
platform/platform-impl/src/com/intellij/openapi/keymap/impl/KeymapImpl.java
platform/platform-impl/src/com/intellij/openapi/keymap/impl/keyGestures/KeyboardGestureProcessor.java
platform/platform-impl/src/com/intellij/openapi/options/newEditor/OptionsEditor.java
platform/platform-impl/src/com/intellij/ui/BalloonImpl.java
platform/platform-resources-en/src/messages/ProjectBundle.properties
platform/platform-resources/src/idea/LangActions.xml
platform/platform-tests/testSrc/com/intellij/ide/util/treeView/BaseTreeTestCase.java
platform/testFramework/src/com/intellij/testFramework/FileStructureTestBase.java
platform/testFramework/src/com/intellij/testFramework/TestTreeUpdater.java [new file with mode: 0644]
platform/usageView/src/com/intellij/usages/impl/UsageViewImpl.java
platform/util/src/com/intellij/openapi/util/Key.java
platform/util/src/com/intellij/ui/awt/RelativePoint.java
platform/vcs-impl/src/com/intellij/openapi/vcs/changes/actions/RollbackAction.java
plugins/InspectionGadgets/src/com/siyeh/InspectionGadgetsBundle.properties
plugins/InspectionGadgets/src/com/siyeh/ig/style/FieldMayBeFinalInspection.java
plugins/InspectionGadgets/src/com/siyeh/ig/style/StringBufferReplaceableByStringInspection.java
plugins/InspectionGadgets/test/com/siyeh/igfixes/style/replace_with_string/Precedence.after.java [new file with mode: 0644]
plugins/InspectionGadgets/test/com/siyeh/igfixes/style/replace_with_string/Precedence.java [new file with mode: 0644]
plugins/InspectionGadgets/test/com/siyeh/igtest/j2me/field_repeatedly_accessed/expected.xml
plugins/InspectionGadgets/test/com/siyeh/igtest/performance/string_buffer_replaceable_by_string/StringBufferReplaceableByString.java
plugins/InspectionGadgets/testsrc/com/siyeh/ig/fixes/style/StringBufferReplaceableWithStringFixTest.java
plugins/IntentionPowerPak/src/com/siyeh/ipp/base/Intention.java
plugins/IntentionPowerPak/src/com/siyeh/ipp/bool/DemorgansIntention.java
plugins/IntentionPowerPak/src/com/siyeh/ipp/psiutils/BoolUtils.java
plugins/IntentionPowerPak/test/com/siyeh/ipp/bool/demorgans/NeedsMoreParentheses.java [new file with mode: 0644]
plugins/IntentionPowerPak/test/com/siyeh/ipp/bool/demorgans/NeedsMoreParentheses_after.java [new file with mode: 0644]
plugins/IntentionPowerPak/test/com/siyeh/ipp/bool/demorgans/NeedsParentheses.java [new file with mode: 0644]
plugins/IntentionPowerPak/test/com/siyeh/ipp/bool/demorgans/NeedsParentheses_after.java [new file with mode: 0644]
plugins/IntentionPowerPak/test/com/siyeh/ipp/bool/demorgans/NotTooManyParentheses.java [new file with mode: 0644]
plugins/IntentionPowerPak/test/com/siyeh/ipp/bool/demorgans/NotTooManyParentheses_after.java [new file with mode: 0644]
plugins/IntentionPowerPak/testSrc/com/siyeh/ipp/IPPTestCase.java
plugins/IntentionPowerPak/testSrc/com/siyeh/ipp/bool/DemorgansIntentionTest.java [new file with mode: 0644]
plugins/android/src/META-INF/plugin.xml
plugins/android/src/org/jetbrains/android/AndroidIdIndex.java
plugins/android/src/org/jetbrains/android/AndroidResourcesLineMarkerProvider.java
plugins/android/src/org/jetbrains/android/AndroidValueResourcesIndex.java [new file with mode: 0644]
plugins/android/src/org/jetbrains/android/AndroidXmlSchemaProvider.java
plugins/android/src/org/jetbrains/android/actions/CreateXmlResourceDialog.java
plugins/android/src/org/jetbrains/android/compiler/AndroidCompileUtil.java
plugins/android/src/org/jetbrains/android/compiler/ResourceNamesValidityState.java
plugins/android/src/org/jetbrains/android/facet/AndroidFacet.java
plugins/android/src/org/jetbrains/android/facet/AndroidResourceFilesListener.java
plugins/android/src/org/jetbrains/android/resourceManagers/LocalResourceManager.java
plugins/android/src/org/jetbrains/android/resourceManagers/ResourceManager.java
plugins/android/src/org/jetbrains/android/resourceManagers/SystemResourceManager.java
plugins/android/src/org/jetbrains/android/sdk/AndroidSdkUtils.java
plugins/android/src/org/jetbrains/android/util/AndroidResourceUtil.java
plugins/android/src/org/jetbrains/android/util/ResourceEntry.java [moved from plugins/android/src/org/jetbrains/android/compiler/ResourceEntry.java with 88% similarity]
plugins/android/testData/dom/layout/layoutAttrs3.xml [new file with mode: 0644]
plugins/android/testSrc/org/jetbrains/android/AndroidTestCase.java
plugins/android/testSrc/org/jetbrains/android/dom/AndroidLayoutDomTest.java
plugins/devkit/src/actions/ToggleHighlightingMarkupAction.java
plugins/git4idea/src/META-INF/plugin.xml
plugins/git4idea/src/git4idea/GitBranch.java
plugins/git4idea/src/git4idea/actions/GitCurrentBranch.java [deleted file]
plugins/git4idea/src/git4idea/commands/Git.java
plugins/git4idea/src/git4idea/config/GitConfigUtil.java
plugins/git4idea/src/git4idea/push/GitPushDialog.java
plugins/git4idea/src/git4idea/push/GitPushSpec.java
plugins/git4idea/src/git4idea/push/GitPusher.java
plugins/git4idea/src/git4idea/repo/GitBranchTrackInfo.java
plugins/git4idea/src/git4idea/repo/GitConfig.java
plugins/git4idea/src/git4idea/ui/CurrentBranchDialog.form [deleted file]
plugins/git4idea/src/git4idea/ui/CurrentBranchDialog.java [deleted file]
plugins/gradle/resources/i18n/GradleBundle.properties
plugins/gradle/src/META-INF/plugin.xml
plugins/gradle/src/org/jetbrains/plugins/gradle/action/AbstractGradleLinkedProjectAction.java [new file with mode: 0644]
plugins/gradle/src/org/jetbrains/plugins/gradle/action/GradleLinkToProjectAction.java
plugins/gradle/src/org/jetbrains/plugins/gradle/action/GradleOpenScriptAction.java [new file with mode: 0644]
plugins/gradle/src/org/jetbrains/plugins/gradle/action/GradleRefreshProjectAction.java
plugins/gradle/src/org/jetbrains/plugins/gradle/bootstrap/GradleBootstrap.java
plugins/gradle/src/org/jetbrains/plugins/gradle/config/GradleToolWindowPanel.java
plugins/gradle/src/org/jetbrains/plugins/gradle/sync/GradleProjectStructureChangesPanel.java
plugins/gradle/src/org/jetbrains/plugins/gradle/sync/GradleProjectStructureTreeModel.java [new file with mode: 0644]
plugins/gradle/src/org/jetbrains/plugins/gradle/ui/GradleProjectStructureNodeDescriptor.java
plugins/gradle/testSources/org/jetbrains/plugins/gradle/sync/GradleProjectStructureChangesModelTest.groovy
plugins/gradle/testSources/org/jetbrains/plugins/gradle/testutil/IntellijProjectBuilder.groovy
plugins/gradle/testSources/org/jetbrains/plugins/gradle/testutil/ProjectStructureChecker.groovy [new file with mode: 0644]
plugins/groovy/resources/inspectionDescriptions/GroovyUnusedDeclaration.html [new file with mode: 0644]
plugins/groovy/src/META-INF/plugin.xml
plugins/groovy/src/org/jetbrains/plugins/groovy/GroovyBundle.properties
plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/GroovyAnnotator.java
plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/intentions/CreateMethodFromUsageFix.java
plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/intentions/QuickfixUtil.java
plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/intentions/dynamic/CollapseAllAction.java [new file with mode: 0644]
plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/intentions/dynamic/DynamicManager.java
plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/intentions/dynamic/DynamicManagerImpl.java
plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/intentions/dynamic/DynamicToolWindowWrapper.java
plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/intentions/dynamic/ExpandAllAction.java [new file with mode: 0644]
plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/intentions/dynamic/ParamInfo.java [moved from plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/intentions/dynamic/MyPair.java with 53% similarity]
plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/intentions/dynamic/RemoveDynamicAction.java [new file with mode: 0644]
plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/intentions/dynamic/elements/DClassElement.java
plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/intentions/dynamic/elements/DItemElement.java
plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/intentions/dynamic/elements/DMethodElement.java
plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/intentions/dynamic/elements/DNamedElement.java
plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/intentions/dynamic/elements/DPropertyElement.java
plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/intentions/dynamic/elements/DTypedElement.java
plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/intentions/dynamic/ui/DynamicDialog.form
plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/intentions/dynamic/ui/DynamicDialog.java
plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/intentions/dynamic/ui/DynamicElementSettings.java
plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/intentions/dynamic/ui/DynamicMethodDialog.form [deleted file]
plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/intentions/dynamic/ui/DynamicMethodDialog.java
plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/intentions/dynamic/ui/DynamicPropertyDialog.form [deleted file]
plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/intentions/dynamic/ui/DynamicPropertyDialog.java
plugins/groovy/src/org/jetbrains/plugins/groovy/codeInspection/GroovyUnusedDeclarationInspection.java [new file with mode: 0644]
plugins/groovy/src/org/jetbrains/plugins/groovy/codeInspection/local/GroovyPostHighlightingPass.java [moved from plugins/groovy/src/org/jetbrains/plugins/groovy/codeInspection/local/GroovyUnusedImportPass.java with 66% similarity]
plugins/groovy/src/org/jetbrains/plugins/groovy/codeInspection/local/GroovyUnusedImportsPassFactory.java
plugins/groovy/src/org/jetbrains/plugins/groovy/codeInspection/untypedUnresolvedAccess/GroovyUnresolvedAccessInspection.java
plugins/groovy/src/org/jetbrains/plugins/groovy/gpp/GppImplicitUsageProvider.java [new file with mode: 0644]
plugins/groovy/src/org/jetbrains/plugins/groovy/intentions/GroovyIntentionsBundle.properties
plugins/groovy/src/org/jetbrains/plugins/groovy/lang/folding/GroovyFoldingBuilder.java
plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/GrNamedElement.java
plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/GroovyPsiElementFactory.java
plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/api/statements/expressions/GrUnAmbiguousClosureContainer.java [new file with mode: 0644]
plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/api/util/GrStatementOwner.java
plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/GroovyFileBaseImpl.java
plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/blocks/GrBlockImpl.java
plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/clauses/GrCaseSectionImpl.java
plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/expressions/GrThisReferenceExpressionImpl.java
plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/util/GrStringUtil.java
plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/GroovyRefactoringBundle.properties
plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/GroovyRefactoringUtil.java
plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/extract/ExtractHandlerBase.java
plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/extract/method/GroovyExtractMethodHandler.java
plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/introduce/GrIntroduceHandlerBase.java
plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/introduce/field/GrIntroduceFieldHandler.java
plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/introduce/parameter/GrIntroduceParameterHandler.java
plugins/groovy/test/org/jetbrains/plugins/groovy/compiler/GroovyCompilerTest.groovy
plugins/groovy/test/org/jetbrains/plugins/groovy/lang/GppFunctionalTest.groovy
plugins/groovy/test/org/jetbrains/plugins/groovy/lang/GroovyHighlightingTest.groovy
plugins/groovy/test/org/jetbrains/plugins/groovy/lang/dynamic/DynamicTest.java
plugins/groovy/test/org/jetbrains/plugins/groovy/refactoring/extract/method/ExtractMethodTest.java
plugins/groovy/test/org/jetbrains/plugins/groovy/refactoring/introduce/field/GrIntroduceFieldTest.java
plugins/groovy/testdata/highlighting/BuilderMembersAreNotUnresolved.groovy [new file with mode: 0644]
plugins/groovy/testdata/highlighting/GloballyUnusedGppSymbols.groovy [new file with mode: 0644]
plugins/groovy/testdata/highlighting/GloballyUnusedSymbols.groovy [new file with mode: 0644]
plugins/groovy/testdata/refactoring/introduceField/InitializeInCurrentMethod.groovy [new file with mode: 0644]
plugins/groovy/testdata/refactoring/introduceField/InitializeInCurrentMethod_after.groovy [new file with mode: 0644]
plugins/junit/src/com/intellij/execution/junit/JUnitConfiguration.java
plugins/junit/src/com/intellij/execution/junit/TestsPattern.java
plugins/maven/src/main/java/org/jetbrains/idea/maven/importing/MavenDefaultModifiableModelsProvider.java
plugins/maven/src/main/java/org/jetbrains/idea/maven/importing/MavenModifiableModelsProvider.java
plugins/maven/src/main/java/org/jetbrains/idea/maven/importing/MavenUIModifiableModelsProvider.java
plugins/properties/src/META-INF/plugin.xml
plugins/properties/src/com/intellij/lang/properties/UnusedPropertyInspection.java
plugins/properties/src/com/intellij/lang/properties/findUsages/PropertySearcher.java [new file with mode: 0644]
plugins/properties/src/com/intellij/psi/impl/search/PropertyReferenceViaLastWordSearcher.java [deleted file]
plugins/svn4idea/src/META-INF/plugin.xml
plugins/svn4idea/src/org/jetbrains/idea/svn17/SvnConfigurable.java
plugins/svn4idea/src/org/jetbrains/idea/svn17/commandLine/SvnStatusHandler.java
plugins/testng/src/com/theoryinpractice/testng/configuration/TestNGConfiguration.java
resources/src/META-INF/IdeaPlugin.xml
resources/src/idea/JavaActions.xml
xml/impl/src/com/intellij/xml/util/XmlUtil.java

index b9b3142c9ce2c3c4c9283c02722ee9619737efd5..4597318e788506313ecc84b544bd2ab297331afe 100644 (file)
@@ -15,6 +15,9 @@
     <orderEntry type="module" module-name="xml" />
     <orderEntry type="module" module-name="testFramework" scope="TEST" />
     <orderEntry type="library" name="Jaxen" level="project" />
+    <orderEntry type="module" module-name="dom-impl" scope="RUNTIME" />
+    <orderEntry type="module" module-name="relaxng" scope="RUNTIME" />
+    <orderEntry type="module" module-name="spellchecker" scope="RUNTIME" />
   </component>
 </module>
 
index 3c37bbbac87590985df6c1c51da30b9d3c28aebf..a245a2eae7cda0e1d2267954dcb87d5e315b090a 100644 (file)
@@ -1,4 +1,7 @@
 <idea-plugin>
+  <extensionPoints>
+    <extensionPoint name="regExpLanguageHost" beanClass="com.intellij.openapi.util.ClassExtensionPoint"/>
+  </extensionPoints>
   <extensions defaultExtensionNs="com.intellij">
     <lang.documentationProvider language="RegExp" implementationClass="org.intellij.lang.regexp.RegExpDocumentationProvider"/>
     <completion.contributor language="RegExp" implementationClass="org.intellij.lang.regexp.RegExpCompletionContributor"/>
index 37dcc6c527b185f562bfa3dc32bc151a94e97da3..c283f19e87af545b50d08b6157c2344e27221cff 100644 (file)
@@ -15,6 +15,8 @@
  */
 package org.intellij.lang.regexp;
 
+import org.intellij.lang.regexp.psi.RegExpGroup;
+
 /**
  * @author yole
  */
@@ -22,7 +24,6 @@ public interface RegExpLanguageHost {
   boolean characterNeedsEscaping(char c);
   boolean supportsPerl5EmbeddedComments();
   boolean supportsPossessiveQuantifiers();
-  boolean supportsPythonNamedGroups();
   boolean supportsPythonConditionalRefs();
-  boolean supportsRubyNamedGroups();
+  boolean supportsNamedGroupSyntax(RegExpGroup group);
 }
diff --git a/RegExpSupport/src/org/intellij/lang/regexp/RegExpLanguageHosts.java b/RegExpSupport/src/org/intellij/lang/regexp/RegExpLanguageHosts.java
new file mode 100644 (file)
index 0000000..0f57f33
--- /dev/null
@@ -0,0 +1,29 @@
+/*
+ * Copyright 2000-2012 JetBrains s.r.o.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.intellij.lang.regexp;
+
+import com.intellij.openapi.util.ClassExtension;
+
+/**
+ * @author yole
+ */
+public class RegExpLanguageHosts extends ClassExtension<RegExpLanguageHost> {
+  public static RegExpLanguageHosts INSTANCE = new RegExpLanguageHosts();
+
+  private RegExpLanguageHosts() {
+    super("com.intellij.regExpLanguageHost");
+  }
+}
index 29ce387b74650f66f233604471e00017383a11a4..6ac84b85c7e13dd5b787f2a46a99a6a77417cd1f 100644 (file)
  */
 package org.intellij.lang.regexp;
 
+import com.intellij.lang.ASTNode;
 import com.intellij.openapi.util.Condition;
 import com.intellij.psi.PsiElement;
 import org.intellij.lang.regexp.psi.RegExpChar;
+import org.jetbrains.annotations.NotNull;
 
 /**
  * @author yole
  */
 public class RegExpWordSelectionFilter implements Condition<PsiElement> {
   @Override
-  public boolean value(PsiElement element) {
-    if (element.getNode().getElementType() == RegExpTT.CHARACTER || element instanceof RegExpChar) {
+  public boolean value(@NotNull PsiElement element) {
+    final ASTNode node = element.getNode();
+    if ((node != null && node.getElementType() == RegExpTT.CHARACTER) || element instanceof RegExpChar) {
       return false;
     }
     return true;
index 359849287d83ada4bd1b30effccfe5d66ad8ad8c..359a4871acf69c141687d4cc27bea8a82551e40c 100644 (file)
@@ -27,6 +27,7 @@ import com.intellij.psi.PsiElement;
 import com.intellij.psi.PsiLanguageInjectionHost;
 import com.intellij.psi.util.PsiTreeUtil;
 import org.intellij.lang.regexp.RegExpLanguageHost;
+import org.intellij.lang.regexp.RegExpLanguageHosts;
 import org.intellij.lang.regexp.RegExpTT;
 import org.intellij.lang.regexp.psi.*;
 import org.intellij.lang.regexp.psi.impl.RegExpPropertyImpl;
@@ -124,6 +125,9 @@ public final class RegExpAnnotator extends RegExpElementVisitor implements Annot
     if (host instanceof RegExpLanguageHost) {
       return (RegExpLanguageHost)host;
     }
+    if (host != null) {
+      return RegExpLanguageHosts.INSTANCE.forClass(host.getClass());
+    }
     return null;
   }
 
@@ -174,8 +178,7 @@ public final class RegExpAnnotator extends RegExpElementVisitor implements Annot
     }
     if (group.isPythonNamedGroup() || group.isRubyNamedGroup()) {
       RegExpLanguageHost host = findRegExpHost(group);
-      if (host == null || (group.isPythonNamedGroup() && !host.supportsPythonNamedGroups()) ||
-                          (group.isRubyNamedGroup() && !host.supportsRubyNamedGroups())) {
+      if (host == null || !host.supportsNamedGroupSyntax(group)) {
         myHolder.createErrorAnnotation(group, "This named group syntax is not supported");
       }
     }
@@ -183,11 +186,13 @@ public final class RegExpAnnotator extends RegExpElementVisitor implements Annot
 
   @Override
   public void visitRegExpPyNamedGroupRef(RegExpPyNamedGroupRef groupRef) {
+    /* the named group itself will be highlighted as unsupported; no need to highlight reference as well
     RegExpLanguageHost host = findRegExpHost(groupRef);
     if (host == null || !host.supportsPythonNamedGroups()) {
       myHolder.createErrorAnnotation(groupRef, "This named group reference syntax is not supported");
       return;
     }
+    */
     final RegExpGroup group = groupRef.resolve();
     if (group == null) {
       final Annotation a = myHolder.createErrorAnnotation(groupRef, "Unresolved backreference");
index 05aaeb88f46d7b5f790f63e3f2604bab71660c8a..2e5f1dff121982c7ae66d5d20ea3e35176f9c7d9 100644 (file)
@@ -128,12 +128,17 @@ public class CompileServerManager implements ApplicationComponent{
             @Override
             public void run() {
               if (!myAutoMakeInProgress.getAndSet(true)) {
-                try {
-                  runAutoMake();
-                }
-                finally {
-                  myAutoMakeInProgress.set(false);
-                }
+                ApplicationManager.getApplication().executeOnPooledThread(new Runnable() {
+                  @Override
+                  public void run() {
+                    try {
+                      runAutoMake();
+                    }
+                    finally {
+                      myAutoMakeInProgress.set(false);
+                    }
+                  }
+                });
               }
               else {
                 scheduleMake(this);
@@ -668,6 +673,9 @@ public class CompileServerManager implements ApplicationComponent{
 
     @Override
     public boolean handleBuildEvent(JpsRemoteProto.Message.Response.BuildEvent event) {
+      if (myProject.isDisposed()) {
+        return true;
+      }
       switch (event.getEventType()) {
         case BUILD_COMPLETED:
           if (event.hasCompletionStatus()) {
@@ -691,6 +699,9 @@ public class CompileServerManager implements ApplicationComponent{
 
     @Override
     public void handleCompileMessage(JpsRemoteProto.Message.Response.CompileMessage compileResponse) {
+      if (myProject.isDisposed()) {
+        return;
+      }
       final JpsRemoteProto.Message.Response.CompileMessage.Kind kind = compileResponse.getKind();
       if (kind == JpsRemoteProto.Message.Response.CompileMessage.Kind.ERROR) {
         informWolf(myProject, compileResponse);
index a7637185dc21b0652b0cd226f173c05e62fb2610..066baa7ea5381f2ee936c7c6cfd2fe38a2ae4fe1 100644 (file)
@@ -26,6 +26,7 @@ import com.intellij.openapi.compiler.CompilerBundle;
 import com.intellij.openapi.diagnostic.Logger;
 import com.intellij.openapi.module.Module;
 import com.intellij.openapi.projectRoots.Sdk;
+import com.intellij.openapi.util.text.StringUtil;
 import com.intellij.openapi.vfs.CharsetToolkit;
 import com.intellij.openapi.vfs.LocalFileSystem;
 import com.intellij.openapi.vfs.VfsUtil;
@@ -155,7 +156,7 @@ public class CompilerUtil {
 
   public static void addSourceCommandLineSwitch(final Sdk jdk, LanguageLevel chunkLanguageLevel, @NonNls final List<String> commandLine) {
     final String versionString = jdk.getVersionString();
-    if (versionString == null || "".equals(versionString)) {
+    if (StringUtil.isEmpty(versionString)) {
       throw new IllegalArgumentException(CompilerBundle.message("javac.error.unknown.jdk.version", jdk.getName()));
     }
 
index cd0fd7b13e983594b5b4ade342f3f94e7ed1272e..44d4269cb150ca0eaaafc0a3d5e30227ded66077 100644 (file)
@@ -98,7 +98,7 @@
           <grid row="6" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="3" anchor="8" fill="0" indent="2" use-parent-layout="false"/>
         </constraints>
         <properties>
-          <text value="Perform project make on save"/>
+          <text value="Make project on save"/>
         </properties>
       </component>
     </children>
index 934740800fe97b7b3eac8d120c3e27da8644a989..20ad95d8d9bba9f03b60af5f06e42389adcb0973 100644 (file)
@@ -31,6 +31,7 @@
     <orderEntry type="library" name="Guava" level="project" />
     <orderEntry type="library" scope="TEST" name="JUnit4" level="project" />
     <orderEntry type="module" module-name="java-psi-impl" exported="" />
+    <orderEntry type="module" module-name="RegExpSupport" />
   </component>
   <component name="copyright">
     <Base>
index 94135a94b346d51b6110e9bb64e21bfa533f59e0..30f5c20fbef837995390a8d1ae05c0d0afdb5dee 100644 (file)
@@ -113,7 +113,7 @@ public class JavaCompletionContributor extends CompletionContributor {
       return new AndFilter(ElementClassFilter.CLASS, new NotFilter(new AssignableFromContextFilter()));
     }
 
-    if (JavaCompletionData.DECLARATION_START.isAcceptable(position, position) ||
+    if (JavaCompletionData.DECLARATION_START.accepts(position) ||
         JavaCompletionData.INSIDE_PARAMETER_LIST.accepts(position)) {
       return new OrFilter(ElementClassFilter.CLASS, ElementClassFilter.PACKAGE_FILTER);
     }
index 86d61df0968de2e47252e8750d64c86a1716632b..5d9d2a0155a4b9738de5f8fca88c4a5f8950bd75 100644 (file)
@@ -166,16 +166,18 @@ public class JavaCompletionData extends JavaAwareCompletionData{
     defineScopeEquivalence(PsiMethod.class, JavaCodeFragment.class);
   }
 
-  public static final AndFilter DECLARATION_START = new AndFilter(
-    CLASS_BODY,
-    new OrFilter(
-      END_OF_BLOCK,
-      new LeftNeighbour(new OrFilter(
-        new SuperParentFilter(new ClassFilter(PsiModifierList.class)),
-        new AndFilter (new TokenTypeFilter(JavaTokenType.GT),
-                       new SuperParentFilter(new ClassFilter(PsiTypeParameterList.class)))))
-    ),
-    new PatternFilter(not(psiElement().afterLeaf("@", "."))));
+  public static final ElementPattern<PsiElement> DECLARATION_START = psiElement().andNot(psiElement().afterLeaf("@", ".")).
+    andOr(
+      psiElement().and(new FilterPattern(CLASS_BODY)).
+        andOr(
+          new FilterPattern(END_OF_BLOCK),
+          psiElement().afterLeaf(or(
+            psiElement().inside(PsiModifierList.class),
+            psiElement().withElementType(JavaTokenType.GT).inside(PsiTypeParameterList.class)
+          ))),
+      psiElement().withParents(PsiJavaCodeReferenceElement.class, PsiTypeElement.class, PsiMember.class),
+      psiElement().withParents(PsiJavaCodeReferenceElement.class, PsiTypeElement.class, PsiClassLevelDeclarationStatement.class)
+    );
 
   private void declareCompletionSpaces() {
     declareFinalScope(PsiFile.class);
@@ -578,9 +580,7 @@ public class JavaCompletionData extends JavaAwareCompletionData{
       .afterLeaf(psiElement().withText("(").withParent(psiElement(PsiParenthesizedExpression.class, PsiTypeCastExpression.class)))
       .accepts(position);
 
-    boolean declaration = DECLARATION_START.isAcceptable(position, position) ||
-                          psiElement().withParents(PsiJavaCodeReferenceElement.class, PsiTypeElement.class, PsiMember.class).accepts(position) ||
-                          psiElement().withParents(PsiJavaCodeReferenceElement.class, PsiTypeElement.class, PsiClassLevelDeclarationStatement.class).accepts(position);
+    boolean declaration = DECLARATION_START.accepts(position);
     if (START_FOR.accepts(position) ||
         INSIDE_PARAMETER_LIST.accepts(position) && !AFTER_DOT.accepts(position) ||
         VARIABLE_AFTER_FINAL.accepts(position) ||
diff --git a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/GlobalUsageHelper.java b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/GlobalUsageHelper.java
new file mode 100644 (file)
index 0000000..cf2b86f
--- /dev/null
@@ -0,0 +1,35 @@
+/*
+ * Copyright 2000-2012 JetBrains s.r.o.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.intellij.codeInsight.daemon.impl;
+
+import com.intellij.psi.PsiClass;
+import com.intellij.psi.PsiMember;
+import com.intellij.psi.PsiNamedElement;
+import org.jetbrains.annotations.NotNull;
+
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * @author peter
+ */
+public abstract class GlobalUsageHelper {
+  final Map<PsiClass,Boolean> unusedClassCache = new HashMap<PsiClass, Boolean>();
+
+  public abstract boolean shouldCheckUsages(@NotNull PsiMember member);
+  public abstract boolean isLocallyUsed(@NotNull PsiNamedElement member);
+  public abstract boolean isCurrentFileAlreadyChecked();
+}
index 5a429287899606d3858c578ef68662e77f6d09e8..815715a494fab317c22ae2f4327bae25112e57c3 100644 (file)
@@ -82,7 +82,6 @@ import com.intellij.psi.util.PsiUtilCore;
 import com.intellij.refactoring.changeSignature.ChangeSignatureGestureDetector;
 import com.intellij.util.Processor;
 import gnu.trove.THashSet;
-import gnu.trove.TObjectIntHashMap;
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
 import org.jetbrains.annotations.PropertyKey;
@@ -102,7 +101,7 @@ public class PostHighlightingPass extends TextEditorHighlightingPass {
   private final JavaCodeStyleManager myStyleManager;
   private int myCurrentEntryIndex;
   private boolean myHasMissortedImports;
-  private final ImplicitUsageProvider[] myImplicitUsageProviders;
+  private static final ImplicitUsageProvider[] ourImplicitUsageProviders = Extensions.getExtensions(ImplicitUsageProvider.EP_NAME);
   private UnusedDeclarationInspection myDeadCodeInspection;
   private UnusedSymbolLocalInspection myUnusedSymbolInspection;
   private HighlightDisplayKey myUnusedSymbolKey;
@@ -124,8 +123,6 @@ public class PostHighlightingPass extends TextEditorHighlightingPass {
 
     myStyleManager = JavaCodeStyleManager.getInstance(myProject);
     myCurrentEntryIndex = -1;
-
-    myImplicitUsageProviders = Extensions.getExtensions(ImplicitUsageProvider.EP_NAME);
   }
 
   @Override
@@ -254,13 +251,33 @@ public class PostHighlightingPass extends TextEditorHighlightingPass {
 
     myDeadCodeInfoType = myDeadCodeKey == null ? null : new HighlightInfoType.HighlightInfoTypeImpl(profile.getErrorLevel(myDeadCodeKey, myFile).getSeverity(), HighlightInfoType.UNUSED_SYMBOL.getAttributesKey());
 
+    GlobalUsageHelper helper = new GlobalUsageHelper() {
+      @Override
+      public boolean shouldCheckUsages(@NotNull PsiMember member) {
+        if (myInLibrary) return false;
+        if (!myDeadCodeEnabled) return false;
+        if (myDeadCodeInspection.isEntryPoint(member)) return false;
+        return true;
+      }
+
+      @Override
+      public boolean isCurrentFileAlreadyChecked() {
+        return true;
+      }
+
+      @Override
+      public boolean isLocallyUsed(@NotNull PsiNamedElement member) {
+        return myRefCountHolder.isReferenced(member);
+      }
+    };
+
     boolean errorFound = false;
     if (unusedSymbolEnabled) {
       for (PsiElement element : elements) {
         progress.checkCanceled();
         if (element instanceof PsiIdentifier) {
           PsiIdentifier identifier = (PsiIdentifier)element;
-          HighlightInfo info = processIdentifier(identifier, progress);
+          HighlightInfo info = processIdentifier(identifier, progress, helper);
           if (info != null) {
             errorFound |= info.getSeverity() == HighlightSeverity.ERROR;
             result.add(info);
@@ -287,7 +304,7 @@ public class PostHighlightingPass extends TextEditorHighlightingPass {
   }
 
   @Nullable
-  private HighlightInfo processIdentifier(PsiIdentifier identifier, ProgressIndicator progress) {
+  private HighlightInfo processIdentifier(PsiIdentifier identifier, ProgressIndicator progress, GlobalUsageHelper helper) {
     if (InspectionManagerEx.inspectionResultSuppressed(identifier, myUnusedSymbolInspection)) return null;
     PsiElement parent = identifier.getParent();
     if (PsiUtilCore.hasErrorElementChild(parent)) return null;
@@ -296,17 +313,17 @@ public class PostHighlightingPass extends TextEditorHighlightingPass {
       return processLocalVariable((PsiLocalVariable)parent, progress);
     }
     if (parent instanceof PsiField && myUnusedSymbolInspection.FIELD) {
-      return processField((PsiField)parent, identifier, progress);
+      return processField((PsiField)parent, identifier, progress, helper);
     }
     if (parent instanceof PsiParameter && myUnusedSymbolInspection.PARAMETER) {
       if (InspectionManagerEx.isSuppressed(identifier, UnusedParametersInspection.SHORT_NAME)) return null;
       return processParameter((PsiParameter)parent, progress);
     }
     if (parent instanceof PsiMethod && myUnusedSymbolInspection.METHOD) {
-      return processMethod((PsiMethod)parent, progress);
+      return processMethod((PsiMethod)parent, progress, helper);
     }
     if (parent instanceof PsiClass && myUnusedSymbolInspection.CLASS) {
-      return processClass((PsiClass)parent, progress);
+      return processClass((PsiClass)parent, progress, helper);
     }
     return null;
   }
@@ -346,9 +363,9 @@ public class PostHighlightingPass extends TextEditorHighlightingPass {
   }
 
 
-  private boolean isImplicitUsage(final PsiModifierListOwner element, ProgressIndicator progress) {
+  public static boolean isImplicitUsage(final PsiModifierListOwner element, ProgressIndicator progress) {
     if (UnusedSymbolLocalInspection.isInjected(element)) return true;
-    for (ImplicitUsageProvider provider : myImplicitUsageProviders) {
+    for (ImplicitUsageProvider provider : ourImplicitUsageProviders) {
       progress.checkCanceled();
       if (provider.isImplicitUsage(element)) {
         return true;
@@ -358,8 +375,8 @@ public class PostHighlightingPass extends TextEditorHighlightingPass {
     return false;
   }
 
-  private boolean isImplicitRead(final PsiVariable element, ProgressIndicator progress) {
-    for(ImplicitUsageProvider provider: myImplicitUsageProviders) {
+  private static boolean isImplicitRead(final PsiVariable element, ProgressIndicator progress) {
+    for(ImplicitUsageProvider provider: ourImplicitUsageProviders) {
       progress.checkCanceled();
       if (provider.isImplicitRead(element)) {
         return true;
@@ -368,8 +385,8 @@ public class PostHighlightingPass extends TextEditorHighlightingPass {
     return UnusedSymbolLocalInspection.isInjected(element);
   }
 
-  private boolean isImplicitWrite(final PsiVariable element, ProgressIndicator progress) {
-    for(ImplicitUsageProvider provider: myImplicitUsageProviders) {
+  private static boolean isImplicitWrite(final PsiVariable element, ProgressIndicator progress) {
+    for(ImplicitUsageProvider provider: ourImplicitUsageProviders) {
       progress.checkCanceled();
       if (provider.isImplicitWrite(element)) {
         return true;
@@ -378,7 +395,7 @@ public class PostHighlightingPass extends TextEditorHighlightingPass {
     return UnusedSymbolLocalInspection.isInjected(element);
   }
 
-  private static HighlightInfo createUnusedSymbolInfo(PsiElement element, String message, final HighlightInfoType highlightInfoType) {
+  public static HighlightInfo createUnusedSymbolInfo(@NotNull PsiElement element, @Nullable String message, @NotNull final HighlightInfoType highlightInfoType) {
     HighlightInfo info = HighlightInfo.createHighlightInfo(highlightInfoType, element, message);
     UnusedDeclarationFixProvider[] fixProviders = Extensions.getExtensions(UnusedDeclarationFixProvider.EP_NAME);
     for (UnusedDeclarationFixProvider provider : fixProviders) {
@@ -391,7 +408,7 @@ public class PostHighlightingPass extends TextEditorHighlightingPass {
   }
 
   @Nullable
-  private HighlightInfo processField(final PsiField field, final PsiIdentifier identifier, ProgressIndicator progress) {
+  private HighlightInfo processField(final PsiField field, final PsiIdentifier identifier, ProgressIndicator progress, GlobalUsageHelper helper) {
     if (field.hasModifierProperty(PsiModifier.PRIVATE)) {
       if (!myRefCountHolder.isReferenced(field) && !isImplicitUsage(field, progress)) {
         if (HighlightUtil.isSerializationImplicitlyUsedField(field)) {
@@ -435,12 +452,22 @@ public class PostHighlightingPass extends TextEditorHighlightingPass {
     else if (isImplicitUsage(field, progress)) {
       return null;
     }
-    else if (!myRefCountHolder.isReferenced(field) && weAreSureThereAreNoUsages(field, progress)) {
+    else if (isFieldUnused(field, progress, helper)) {
       return formatUnusedSymbolHighlightInfo("field.is.not.used", field, "fields", myDeadCodeKey, myDeadCodeInfoType);
     }
     return null;
   }
 
+  public static boolean isFieldUnused(PsiField field, ProgressIndicator progress, GlobalUsageHelper helper) {
+    if (helper.isLocallyUsed(field) || !weAreSureThereAreNoUsages(field, progress, helper)) {
+      return false;
+    }
+    if (field instanceof PsiEnumConstant && isEnumValuesMethodUsed(field, progress, helper)) {
+      return false;
+    }
+    return true;
+  }
+
   private HighlightInfo suggestionsToMakeFieldUsed(final PsiField field, final PsiIdentifier identifier, final String message) {
     HighlightInfo highlightInfo = createUnusedSymbolInfo(identifier, message, HighlightInfoType.UNUSED_SYMBOL);
     QuickFixAction.registerQuickFixAction(highlightInfo, new RemoveUnusedVariableFix(field), myUnusedSymbolKey);
@@ -508,14 +535,12 @@ public class PostHighlightingPass extends TextEditorHighlightingPass {
   }
 
   @Nullable
-  private HighlightInfo processMethod(final PsiMethod method, ProgressIndicator progress) {
-    boolean isPrivate = method.hasModifierProperty(PsiModifier.PRIVATE);
-    PsiClass containingClass = method.getContainingClass();
-    if (isMethodReferenced(method, progress, isPrivate, containingClass)) return null;
+  private HighlightInfo processMethod(final PsiMethod method, ProgressIndicator progress, GlobalUsageHelper helper) {
+    if (isMethodReferenced(method, progress, helper)) return null;
     HighlightInfoType highlightInfoType;
     HighlightDisplayKey highlightDisplayKey;
     String key;
-    if (isPrivate) {
+    if (method.hasModifierProperty(PsiModifier.PRIVATE)) {
       highlightInfoType = HighlightInfoType.UNUSED_SYMBOL;
       highlightDisplayKey = myUnusedSymbolKey;
       key = method.isConstructor() ? "private.constructor.is.not.used" : "private.method.is.not.used";
@@ -537,6 +562,7 @@ public class PostHighlightingPass extends TextEditorHighlightingPass {
         return true;
       }
     });
+    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(myProject).dismissForElement(method);
@@ -544,9 +570,13 @@ public class PostHighlightingPass extends TextEditorHighlightingPass {
     return highlightInfo;
   }
 
-  private boolean isMethodReferenced(PsiMethod method, ProgressIndicator progress, boolean aPrivate, PsiClass containingClass) {
-    if (myRefCountHolder.isReferenced(method)) return true;
+  public static boolean isMethodReferenced(PsiMethod method,
+                                            ProgressIndicator progress,
+                                            GlobalUsageHelper helper) {
+    if (helper.isLocallyUsed(method)) return true;
 
+    boolean aPrivate = method.hasModifierProperty(PsiModifier.PRIVATE);
+    PsiClass containingClass = method.getContainingClass();
     if (HighlightMethodUtil.isSerializationRelatedMethod(method, containingClass)) return true;
     if (aPrivate) {
       if (isIntentionalPrivateConstructor(method, containingClass)) {
@@ -555,12 +585,15 @@ public class PostHighlightingPass extends TextEditorHighlightingPass {
       if (isImplicitUsage(method, progress)) {
         return true;
       }
+      if (!helper.isCurrentFileAlreadyChecked()) {
+        return !weAreSureThereAreNoUsages(method, progress, helper);
+      }
     }
     else {
       //class maybe used in some weird way, e.g. from XML, therefore the only constructor is used too
       if (containingClass != null && method.isConstructor()
           && containingClass.getConstructors().length == 1
-          && isClassUnused(containingClass, progress) == USED) {
+          && isClassUsed(containingClass, progress, helper)) {
         return true;
       }
       if (isImplicitUsage(method, progress)) return true;
@@ -568,70 +601,50 @@ public class PostHighlightingPass extends TextEditorHighlightingPass {
       if (method.findSuperMethods().length != 0) {
         return true;
       }
-      if (!weAreSureThereAreNoUsages(method, progress)) {
+      if (!weAreSureThereAreNoUsages(method, progress, helper)) {
         return true;
       }
     }
     return false;
   }
 
-  private boolean weAreSureThereAreNoUsages(PsiMember member, ProgressIndicator progress) {
-    if (myInLibrary) return false;
-    if (!myDeadCodeEnabled) return false;
-    if (myDeadCodeInspection.isEntryPoint(member)) return false;
+  private static boolean weAreSureThereAreNoUsages(PsiMember member, ProgressIndicator progress, GlobalUsageHelper helper) {
+    if (!helper.shouldCheckUsages(member)) return false;
 
     String name = member.getName();
     if (name == null) return false;
     SearchScope useScope = member.getUseScope();
-    if (!(useScope instanceof GlobalSearchScope)) return false;
-    GlobalSearchScope scope = (GlobalSearchScope)useScope;
-    // some classes may have references from within XML outside dependent modules, e.g. our actions
-    if (member instanceof PsiClass) scope = GlobalSearchScope.projectScope(myProject).uniteWith(scope);
-
-    PsiSearchHelper.SearchCostResult cheapEnough = PsiSearchHelper.SERVICE.getInstance(myFile.getProject())
-        .isCheapEnoughToSearch(name, scope, myFile, progress);
-    if (cheapEnough == PsiSearchHelper.SearchCostResult.TOO_MANY_OCCURRENCES) return false;
-
-    //search usages if it cheap
-    //if count is 0 there is no usages since we've called myRefCountHolder.isReferenced() before
-    if (cheapEnough == PsiSearchHelper.SearchCostResult.ZERO_OCCURRENCES) {
-      if (member instanceof PsiEnumConstant) {
-        return !isEnumValuesMethodUsed(member, progress);
+    Project project = member.getProject();
+    if (useScope instanceof GlobalSearchScope) {
+      // some classes may have references from within XML outside dependent modules, e.g. our actions
+      if (member instanceof PsiClass) {
+        useScope = GlobalSearchScope.projectScope(project).uniteWith((GlobalSearchScope)useScope);
       }
-      if (!canBeReferencedViaWeirdNames(member)) return true;
-    }
-    FindUsagesManager findUsagesManager = ((FindManagerImpl)FindManager.getInstance(myProject)).getFindUsagesManager();
-    FindUsagesOptions findUsagesOptions;
-    if (member instanceof PsiClass) {
-      findUsagesOptions = new JavaClassFindUsagesOptions(myProject);
-    }
-    else if (member instanceof PsiMethod) {
-      findUsagesOptions = new JavaMethodFindUsagesOptions(myProject);
-    }
-    else if (member instanceof PsiField) {
-      findUsagesOptions = new JavaVariableFindUsagesOptions(myProject);
-    }
-    else {
-      LOG.error("unknown member: " + member);
-      return false;
-    }
-    findUsagesOptions.searchScope = scope;
 
-    boolean used = findUsagesManager.isUsed(member, findUsagesOptions);
+      PsiSearchHelper.SearchCostResult cheapEnough = PsiSearchHelper.SERVICE.getInstance(project).isCheapEnoughToSearch(name, (GlobalSearchScope)useScope,
+                                                                                                                        helper.isCurrentFileAlreadyChecked() ? member.getContainingFile() : null,
+                                                                                                                        progress);
+      if (cheapEnough == PsiSearchHelper.SearchCostResult.TOO_MANY_OCCURRENCES) return false;
 
-    if (!used && member instanceof PsiEnumConstant) {
-      return !isEnumValuesMethodUsed(member, progress);
+      //search usages if it cheap
+      //if count is 0 there is no usages since we've called myRefCountHolder.isReferenced() before
+      if (cheapEnough == PsiSearchHelper.SearchCostResult.ZERO_OCCURRENCES) {
+        if (!canBeReferencedViaWeirdNames(member)) return true;
+      }
     }
-    return !used;
+    FindUsagesManager findUsagesManager = ((FindManagerImpl)FindManager.getInstance(project)).getFindUsagesManager();
+    FindUsagesHandler handler = new JavaFindUsagesHandler(member, new JavaFindUsagesHandlerFactory(project));
+    FindUsagesOptions findUsagesOptions = handler.getFindUsagesOptions();
+    findUsagesOptions.searchScope = useScope;
+    return !findUsagesManager.isUsed(member, findUsagesOptions);
   }
 
-  private boolean isEnumValuesMethodUsed(PsiMember member, ProgressIndicator progress) {
+  private static boolean isEnumValuesMethodUsed(PsiMember member, ProgressIndicator progress, GlobalUsageHelper helper) {
     final PsiClassImpl containingClass = (PsiClassImpl)member.getContainingClass();
     if (containingClass == null) return true;
     final PsiMethod valuesMethod = containingClass.getValuesMethod();
     if (valuesMethod == null) return true;
-    boolean isPrivate = valuesMethod.hasModifierProperty(PsiModifier.PRIVATE);
-    return isMethodReferenced(valuesMethod, progress, isPrivate, containingClass);
+    return isMethodReferenced(valuesMethod, progress, helper);
   }
 
   private static boolean canBeReferencedViaWeirdNames(PsiMember member) {
@@ -646,9 +659,8 @@ public class PostHighlightingPass extends TextEditorHighlightingPass {
   }
 
   @Nullable
-  private HighlightInfo processClass(PsiClass aClass, ProgressIndicator progress) {
-    int usage = isClassUnused(aClass, progress);
-    if (usage == USED) return null;
+  private HighlightInfo processClass(PsiClass aClass, ProgressIndicator progress, GlobalUsageHelper helper) {
+    if (isClassUsed(aClass, progress, helper)) return null;
 
     String pattern;
     HighlightDisplayKey highlightDisplayKey;
@@ -678,27 +690,24 @@ public class PostHighlightingPass extends TextEditorHighlightingPass {
     return formatUnusedSymbolHighlightInfo(pattern, aClass, "classes", highlightDisplayKey, highlightInfoType);
   }
 
-  private static final int USED = 1;
-  private static final int UNUSED_LOCALLY = 2;
-  private static final int UNUSED_GLOBALLY = 3;
-  private final TObjectIntHashMap<PsiClass> unusedClassCache = new TObjectIntHashMap<PsiClass>();
-  private int isClassUnused(PsiClass aClass, ProgressIndicator progress) {
-    if (aClass == null) return USED;
-    int result = unusedClassCache.get(aClass);
-    if (result == 0) {
-      result = isReallyUnused(aClass, progress);
-      unusedClassCache.put(aClass, result);
+  public static boolean isClassUsed(PsiClass aClass, ProgressIndicator progress, GlobalUsageHelper helper) {
+    if (aClass == null) return true;
+    Boolean result = helper.unusedClassCache.get(aClass);
+    if (result == null) {
+      result = isReallyUsed(aClass, progress, helper);
+      helper.unusedClassCache.put(aClass, result);
     }
     return result;
   }
 
-  private int isReallyUnused(PsiClass aClass, ProgressIndicator progress) {
-    if (isImplicitUsage(aClass, progress) || myRefCountHolder.isReferenced(aClass)) return USED;
-    if (aClass.getContainingClass() != null && aClass.hasModifierProperty(PsiModifier.PRIVATE) ||
-           aClass.getParent() instanceof PsiDeclarationStatement ||
-           aClass instanceof PsiTypeParameter) return UNUSED_LOCALLY;
-    if (weAreSureThereAreNoUsages(aClass, progress)) return UNUSED_GLOBALLY;
-    return USED;
+  private static boolean isReallyUsed(PsiClass aClass, ProgressIndicator progress, GlobalUsageHelper helper) {
+    if (isImplicitUsage(aClass, progress) || helper.isLocallyUsed(aClass)) return true;
+    if (helper.isCurrentFileAlreadyChecked()) {
+      if (aClass.getContainingClass() != null && aClass.hasModifierProperty(PsiModifier.PRIVATE) ||
+             aClass.getParent() instanceof PsiDeclarationStatement ||
+             aClass instanceof PsiTypeParameter) return false;
+    }
+    return !weAreSureThereAreNoUsages(aClass, progress, helper);
   }
 
   private static HighlightInfo formatUnusedSymbolHighlightInfo(@PropertyKey(resourceBundle = JavaErrorMessages.BUNDLE) String pattern,
index ccdb81a65173a586a8f1bb295b8734e4316a6a14..029b12d3e423451b44ce104fb1f7033200cf84d3 100644 (file)
@@ -155,6 +155,7 @@ public class ChangeMethodSignatureFromUsageFix implements IntentionAction, HighP
     for (PsiExpression expression : myExpressions) {
       if (!expression.isValid()) return false;
     }
+    if (!mySubstitutor.isValid()) return false;
 
     myNewParametersInfo = getNewParametersInfo(myExpressions, myTargetMethod, mySubstitutor);
     if (myNewParametersInfo == null || formatTypesList(myNewParametersInfo, myContext) == null) return false;
index 06a1c85a69ad8d0b3d44fdd0357c4d884112e717..f7036b1646f341a024b5a0a17b60e5ed0aa7fefd 100644 (file)
@@ -374,7 +374,8 @@ public class GenerateDelegateHandler implements LanguageCodeInsightActionHandler
         for (int i = 0; i < proc.size(); i++) {
           final PsiVariable psiVariable = proc.getResult(i);
           final PsiElementFactory elementFactory = JavaPsiFacade.getElementFactory(aClass.getProject());
-          result.add(new PsiFieldMember(elementFactory.createField(psiVariable.getName(), psiVariable.getType())) {
+          final PsiType type = psiVariable.getType();
+          result.add(new PsiFieldMember(elementFactory.createField(psiVariable.getName(), type instanceof PsiEllipsisType ? ((PsiEllipsisType)type).toArrayType() : type)) {
             @Override
             protected PsiClass getContainingClass() {
               return aClass;
index 15725edd723d1770020bca27dcdf864b82ae4813..ec4b6f30f89eacbdc1a4297f845d6ee1f198ac99 100644 (file)
@@ -21,6 +21,7 @@ import com.intellij.lang.StdLanguages;
 import com.intellij.openapi.diagnostic.Logger;
 import com.intellij.openapi.editor.Editor;
 import com.intellij.openapi.editor.ScrollType;
+import com.intellij.openapi.extensions.Extensions;
 import com.intellij.openapi.project.Project;
 import com.intellij.openapi.util.Pair;
 import com.intellij.openapi.util.text.StringUtil;
@@ -40,9 +41,7 @@ import org.jetbrains.annotations.NonNls;
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
 
-import java.util.Collections;
-import java.util.List;
-import java.util.Map;
+import java.util.*;
 
 public class GenerateMembersUtil {
   private static final Logger LOG = Logger.getInstance("#com.intellij.codeInsight.generation.GenerateMembersUtil");
@@ -279,7 +278,9 @@ public class GenerateMembersUtil {
 
         PsiParameter newParameter = factory.createParameter(paramName, substituted);
         if (parameter.getLanguage() == StdLanguages.JAVA) {
-          newParameter.getModifierList().replace(parameter.getModifierList());
+          PsiModifierList modifierList = newParameter.getModifierList();
+          modifierList = (PsiModifierList)modifierList.replace(parameter.getModifierList());
+          processAnnotations(project, modifierList);
         }
         newMethod.getParameterList().add(newParameter);
       }
@@ -312,6 +313,23 @@ public class GenerateMembersUtil {
     }
   }
 
+  private static void processAnnotations(Project project, PsiModifierList modifierList) {
+    final Set<String> toRemove = new HashSet<String>();
+    for (PsiAnnotation annotation : modifierList.getAnnotations()) {
+      final String qualifiedName = annotation.getQualifiedName();
+      for (OverrideImplementsAnnotationsHandler handler : Extensions.getExtensions(OverrideImplementsAnnotationsHandler.EP_NAME)) {
+        final String[] annotations2Remove = handler.annotationsToRemove(project, qualifiedName);
+        Collections.addAll(toRemove, annotations2Remove);
+      }
+    }
+    for (String fqn : toRemove) {
+      final PsiAnnotation psiAnnotation = modifierList.findAnnotation(fqn);
+      if (psiAnnotation != null) {
+        psiAnnotation.delete();
+      }
+    }
+  }
+
   private static PsiType substituteType(final PsiSubstitutor substitutor, final PsiType type) {
     final PsiType psiType = substitutor.substitute(type);
     if (psiType != null) return psiType;
diff --git a/java/java-impl/src/com/intellij/codeInspection/canBeFinal/CanBeFinalHandler.java b/java/java-impl/src/com/intellij/codeInspection/canBeFinal/CanBeFinalHandler.java
new file mode 100644 (file)
index 0000000..f6d5acf
--- /dev/null
@@ -0,0 +1,37 @@
+/*
+ * Copyright 2000-2012 JetBrains s.r.o.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.intellij.codeInspection.canBeFinal;
+
+import com.intellij.openapi.extensions.ExtensionPointName;
+import com.intellij.openapi.extensions.Extensions;
+import com.intellij.psi.PsiMember;
+
+/**
+ * User: anna
+ * Date: 1/31/12
+ */
+public abstract class CanBeFinalHandler {
+  public static final ExtensionPointName<CanBeFinalHandler> EP_NAME = ExtensionPointName.create("com.intellij.canBeFinal");
+
+  public abstract boolean canBeFinal(PsiMember member);
+
+  public static boolean allowToBeFinal(PsiMember member) {
+    for (CanBeFinalHandler handler : Extensions.getExtensions(EP_NAME)) {
+      if (!handler.canBeFinal(member)) return false;
+    }
+    return true;
+  }
+}
index 85d04e9abe0012260886aa6b621878d17cb241c2..e1d43b13eff6e77b36926a025f40569c76a544c8 100644 (file)
@@ -139,22 +139,25 @@ public class CanBeFinalInspection extends GlobalJavaInspectionTool {
       if (refElement.isFinal()) return null;
       if (!((RefElementImpl)refElement).checkFlag(CanBeFinalAnnotator.CAN_BE_FINAL_MASK)) return null;
 
+      final PsiMember psiMember = (PsiMember)refElement.getElement();
+      if (psiMember == null || !CanBeFinalHandler.allowToBeFinal(psiMember)) return null;
+
       PsiIdentifier psiIdentifier = null;
       if (refElement instanceof RefClass) {
         RefClass refClass = (RefClass)refElement;
         if (refClass.isInterface() || refClass.isAnonymous() || refClass.isAbstract()) return null;
         if (!isReportClasses()) return null;
-        psiIdentifier = refClass.getElement().getNameIdentifier();
+        psiIdentifier = ((PsiClass)psiMember).getNameIdentifier();
       }
       else if (refElement instanceof RefMethod) {
         RefMethod refMethod = (RefMethod)refElement;
         if (refMethod.getOwnerClass().isFinal()) return null;
         if (!isReportMethods()) return null;
-        psiIdentifier = ((PsiMethod)refMethod.getElement()).getNameIdentifier();
+        psiIdentifier = ((PsiMethod)psiMember).getNameIdentifier();
       }
       else if (refElement instanceof RefField) {
         if (!isReportFields()) return null;
-        psiIdentifier = ((RefField)refElement).getElement().getNameIdentifier();
+        psiIdentifier = ((PsiField)psiMember).getNameIdentifier();
       }
 
 
index 9afe7593f0a66c7a1e10c8329a9605b6d1d4b2a9..6a65678a8d3a6256770eff630187cc86a63bda30 100644 (file)
@@ -156,8 +156,13 @@ public final class CallHierarchyNodeDescriptor extends HierarchyNodeDescriptor i
       myHighlightedText.getEnding().addText(IdeBundle.message("node.call.hierarchy.N.usages", myUsageCount), HierarchyNodeDescriptor.getUsageCountPrefixAttributes());
     }
     if (!(JspPsiUtil.isInJspFile(enclosingElement) && enclosingElement instanceof PsiFile)) {
-      final String packageName = JavaHierarchyUtil.getPackageName(enclosingElement instanceof PsiMethod ? ((PsiMethod)enclosingElement).getContainingClass() : (PsiClass)enclosingElement);
-      myHighlightedText.getEnding().addText("  (" + packageName + ")", HierarchyNodeDescriptor.getPackageNameAttributes());
+      final PsiClass containingClass = enclosingElement instanceof PsiMethod
+                                       ? ((PsiMethod)enclosingElement).getContainingClass()
+                                       : (PsiClass)enclosingElement;
+      if (containingClass != null) {
+        final String packageName = JavaHierarchyUtil.getPackageName(containingClass);
+        myHighlightedText.getEnding().addText("  (" + packageName + ")", HierarchyNodeDescriptor.getPackageNameAttributes());
+      }
     }
     myName = myHighlightedText.getText();
 
diff --git a/java/java-impl/src/com/intellij/psi/impl/JavaRegExpHost.java b/java/java-impl/src/com/intellij/psi/impl/JavaRegExpHost.java
new file mode 100644 (file)
index 0000000..a86bb91
--- /dev/null
@@ -0,0 +1,65 @@
+/*
+ * Copyright 2000-2012 JetBrains s.r.o.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.intellij.psi.impl;
+
+import com.intellij.openapi.module.Module;
+import com.intellij.openapi.module.ModuleUtil;
+import com.intellij.openapi.projectRoots.JavaSdk;
+import com.intellij.openapi.projectRoots.JavaSdkVersion;
+import com.intellij.openapi.projectRoots.Sdk;
+import com.intellij.openapi.roots.ModuleRootManager;
+import org.intellij.lang.regexp.RegExpLanguageHost;
+import org.intellij.lang.regexp.psi.RegExpGroup;
+
+/**
+ * @author yole
+ */
+public class JavaRegExpHost implements RegExpLanguageHost {
+  @Override
+  public boolean characterNeedsEscaping(char c) {
+    return c == ']' || c == '}';
+  }
+
+  @Override
+  public boolean supportsPerl5EmbeddedComments() {
+    return false;
+  }
+
+  @Override
+  public boolean supportsPossessiveQuantifiers() {
+    return false;
+  }
+
+  @Override
+  public boolean supportsPythonConditionalRefs() {
+    return false;
+  }
+
+  @Override
+  public boolean supportsNamedGroupSyntax(RegExpGroup group) {
+    if (group.isRubyNamedGroup()) {
+      final Module module = ModuleUtil.findModuleForPsiElement(group);
+      if (module != null) {
+        final Sdk sdk = ModuleRootManager.getInstance(module).getSdk();
+        if (sdk != null && sdk.getSdkType() instanceof JavaSdk) {
+          final JavaSdkVersion version = JavaSdk.getInstance().getVersion(sdk);
+          return version != null && version.isAtLeast(JavaSdkVersion.JDK_1_7);
+        }
+      }
+    }
+    return false;
+  }
+}
similarity index 82%
rename from platform/lang-impl/src/com/intellij/refactoring/rename/RenameFileAction.java
rename to java/java-impl/src/com/intellij/refactoring/actions/RenameFileAction.java
index a0aa127ec7b17f9db4a77168331a42fab287ea57..1e0008cb867df82a4c5a1c3f2c77702f4f06c4b3 100644 (file)
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
-package com.intellij.refactoring.rename;
+package com.intellij.refactoring.actions;
 
 import com.intellij.openapi.actionSystem.*;
 import com.intellij.openapi.project.DumbAware;
 import com.intellij.openapi.project.Project;
 import com.intellij.openapi.vfs.VirtualFile;
+import com.intellij.psi.PsiClassOwner;
 import com.intellij.psi.PsiFile;
+import com.intellij.refactoring.rename.PsiElementRenameHandler;
 
 /**
  * @author ven
@@ -34,13 +36,13 @@ public class RenameFileAction extends AnAction implements DumbAware {
     assert virtualFile != null;
     final Project project = e.getData(PlatformDataKeys.PROJECT);
     assert project != null;
-    new RenameDialog(project, file, file, null).show();
+    PsiElementRenameHandler.invoke(file, project, file, null);
   }
 
   public void update(AnActionEvent e) {
     PsiFile file = e.getData(LangDataKeys.PSI_FILE);
     Presentation presentation = e.getPresentation();
-    boolean enabled = file != null && e.getPlace() != ActionPlaces.EDITOR_POPUP && e.getData(PlatformDataKeys.PROJECT) != null;
+    boolean enabled = file instanceof PsiClassOwner && e.getPlace() != ActionPlaces.EDITOR_POPUP && e.getData(PlatformDataKeys.PROJECT) != null;
     presentation.setEnabled(enabled);
     presentation.setVisible(enabled);
     if (enabled) {
index 10cae69bf12d725f5c4532754274fbefcce74662..e7bf4396267e691f7566950602b096ecfad70d8c 100644 (file)
@@ -42,7 +42,8 @@ public class MoveJavaFileHandler extends MoveFileHandler {
   public boolean canProcessElement(PsiFile element) {
     return element instanceof PsiJavaFile &&
            !JspPsiUtil.isInJspFile(element) &&
-           !CollectHighlightsUtil.isOutsideSourceRoot(element);
+           !CollectHighlightsUtil.isOutsideSourceRoot(element) &&
+           !(element instanceof PsiCompiledElement);
   }
 
   @Override
index 3e67dbc119e4d06dce5bd4b802c2c803e8a22cbf..9c192e69d7a22089b106c1cd6bdd6c26622f4877 100644 (file)
@@ -191,6 +191,7 @@ public class RenameJavaVariableProcessor extends RenameJavaMemberProcessor {
         for (PsiMethod method : setter.findDeepestSuperMethods()) {
           if (method instanceof PsiCompiledElement) {
             setter = null;
+            shouldRenameSetterParameter = false;
             break;
           }
         }
index c6d7611c75affe73dcc5603c0fc264f512244252..0dcb61f2251d57f7b91ae7c82247a38bb2e32761 100644 (file)
@@ -249,9 +249,7 @@ public class TypeMigrationLabeler {
   public void migrateExpressionType(final PsiExpression expr, final PsiType migrationType, final PsiElement place, boolean alreadyProcessed, final boolean isCovariant) {
     PsiType originalType = expr.getType();
 
-    LOG.assertTrue(originalType != null);
-
-    if (originalType.equals(migrationType)) return;
+    if (originalType == null || originalType.equals(migrationType)) return;
 
     if (originalType.equals(PsiType.NULL)) {
       if (migrationType instanceof PsiPrimitiveType) {
index 37920f4583cc53757bd62c8615d32de48da58c91..c32b873207fa58a47899207edf926fa6d2b4efbe 100644 (file)
@@ -85,7 +85,7 @@ public class RootTypeConversionRule extends TypeConversionRule {
               }
 
               if (!originalType.equals(type)) {
-                labeler.migrateExpressionType(actualParams[i], methodTypeParamsSubstitutor.substitute(type), context, originalType.equals(type), true);
+                labeler.migrateExpressionType(actualParams[i], methodTypeParamsSubstitutor.substitute(type), context, false, true);
               }
             }
           }
index 045060685ce0657ff40c8f3580da543bae6b1b76..f0e9afd057f20058f7a5aaa75a81af470b8ea213 100644 (file)
@@ -52,4 +52,8 @@ public class PsiTypeVisitor<A> {
   public A visitDisjunctionType(PsiDisjunctionType disjunctionType) {
     return visitType(disjunctionType);
   }
+  
+  public A visitDiamondType(PsiDiamondType diamondType) {
+    return visitType(diamondType);
+  }
 }
index a3672df3289238d8ed879a59ccdffdd9a2b62a48..845339e66d7aaa977de900447fc0473359fd9f49 100644 (file)
@@ -15,6 +15,7 @@
  */
 package com.intellij.core;
 
+import com.intellij.openapi.diagnostic.Logger;
 import com.intellij.openapi.roots.PackageIndex;
 import com.intellij.openapi.util.io.FileUtil;
 import com.intellij.openapi.vfs.VirtualFile;
@@ -39,6 +40,8 @@ import java.util.List;
  * @author yole
  */
 public class CoreJavaFileManager extends PackageIndex implements JavaFileManager {
+  private static final Logger LOG = Logger.getInstance("#com.intellij.core.CoreJavaFileManager");
+
   private final CoreLocalFileSystem myLocalFileSystem;
   private final CoreJarFileSystem myJarFileSystem;
   private final List<File> myClasspath = new ArrayList<File>();
@@ -85,11 +88,17 @@ public class CoreJavaFileManager extends PackageIndex implements JavaFileManager
   
   @Nullable
   private VirtualFile findUnderClasspathEntry(File classpathEntry, String relativeName) {
+    VirtualFile root = findRootInClassPathEntry(classpathEntry);
+    return root != null ? root.findFileByRelativePath(relativeName) : null;
+  }
+
+  @Nullable
+  private VirtualFile findRootInClassPathEntry(File classpathEntry) {
     if (classpathEntry.isFile()) {
-       return myJarFileSystem.findFileByPath(classpathEntry.getPath() + "!/" + relativeName);
+       return myJarFileSystem.findFileByPath(classpathEntry.getPath() + "!/");
     }
     else {
-      return myLocalFileSystem.findFileByPath(new File(classpathEntry, relativeName).getPath());
+      return myLocalFileSystem.findFileByPath(classpathEntry.getPath());
     }
   }
 
@@ -115,25 +124,77 @@ public class CoreJavaFileManager extends PackageIndex implements JavaFileManager
   }
 
   @Nullable
-  private PsiClass findClassInClasspathEntry(String qName, File file) {
-    // TODO handle inner classes correctly
-    String fileName = qName.replace(".", "/") + ".java";
-    VirtualFile classFile = findUnderClasspathEntry(file, fileName);
-    if (classFile == null) {
-      fileName = qName.replace(".", "/") + ".class";
-      classFile = findUnderClasspathEntry(file, fileName);
+  private PsiClass findClassInClasspathEntry(String qName, File rootEntry) {
+    VirtualFile root = findRootInClassPathEntry(rootEntry);
+    if (root == null) return null;
+
+    return findClassInClasspathRoot(qName, root, myPsiManager);
+  }
+
+  @Nullable
+  public static PsiClass findClassInClasspathRoot(String qName, VirtualFile root, PsiManager psiManager) {
+    String pathRest = qName;
+    VirtualFile cur = root;
+
+    while (true) {
+      int dot = pathRest.indexOf('.');
+      if (dot < 0) break;
+
+      String pathComponent = pathRest.substring(0, dot);
+      VirtualFile child = cur.findChild(pathComponent);
+
+      if (child == null) break;
+      pathRest = pathRest.substring(dot + 1);
+      cur = child;
+    }
+
+    String className = pathRest.replace('.', '$');
+    int bucks = className.indexOf('$');
+
+    String rootClassName;
+    if (bucks < 0) {
+      rootClassName = className;
+    }
+    else {
+      rootClassName = className.substring(0, bucks);
+      className = className.substring(bucks + 1);
     }
 
-    if (classFile != null) {
-      PsiFile psiFile = myPsiManager.findFile(classFile);
-      if (!(psiFile instanceof PsiJavaFile)) {
-        throw new UnsupportedOperationException("no java file for " + fileName);
+    VirtualFile vFile = cur.findChild(rootClassName + ".class");
+    if (vFile == null) vFile = cur.findChild(rootClassName + ".java");
+
+    if (vFile != null) {
+      if (!vFile.isValid()) {
+        LOG.error("Invalid child of valid parent: " + vFile.getPath() + "; " + root.isValid() + " path=" + root.getPath());
+        return null;
       }
-      final PsiClass[] classes = ((PsiJavaFile)psiFile).getClasses();
-      if (classes.length == 1) {
-        return classes[0];
+
+      final PsiFile file = psiManager.findFile(vFile);
+      if (file instanceof PsiClassOwner) {
+        final PsiClass[] classes = ((PsiClassOwner)file).getClasses();
+        if (classes.length == 1) {
+          PsiClass curClass = classes[0];
+
+          if (bucks > 0) {
+            while (true) {
+              int b = className.indexOf("$");
+
+              String component = b < 0 ? className : className.substring(0, b);
+              PsiClass inner = curClass.findInnerClassByName(component, false);
+
+              if (inner == null) return null;
+              curClass = inner;
+              className = className.substring(b + 1);
+              if (b < 0) break;
+            }
+          }
+
+
+          return curClass;
+        }
       }
     }
+
     return null;
   }
 
index cff23586365fe63a35b2f4acde9c88d620ad9a8e..50341eef31aa5af91782098f50e893b1ecf66806 100644 (file)
@@ -29,7 +29,9 @@ import org.jetbrains.annotations.NonNls;
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
 
-import java.util.*;
+import java.util.Collections;
+import java.util.LinkedHashSet;
+import java.util.Set;
 
 /**
  * User: anna
@@ -73,7 +75,7 @@ public class PsiDiamondTypeImpl extends PsiDiamondType {
 
   @Override
   public <A> A accept(PsiTypeVisitor<A> visitor) {
-    return visitor.visitType(this);
+    return visitor.visitDiamondType(this);
   }
 
   @Override
index 2c67d7eff8bba2c191f60e3ad8be36895b269de7..f9535cbb36959624eb0707ff0078a1cbb255eed6 100644 (file)
@@ -212,6 +212,11 @@ public class PsiSubstitutorImpl implements PsiSubstitutor {
       });
       return disjunctionType.newDisjunctionType(substituted);
     }
+
+    @Override
+    public PsiType visitDiamondType(PsiDiamondType diamondType) {
+      return diamondType;
+    }
   }
 
   private final SubstitutionVisitor myAddingBoundsSubstitutionVisitor = new SubstitutionVisitor(SubstituteKind.ADD_BOUNDS);
index 4f9a039070024ed271b2ba214d83ff53c9f03bb4..968f34ad5bc3fdce723e23121f8400a86b0f6b89 100644 (file)
@@ -19,6 +19,7 @@ import com.intellij.navigation.ItemPresentation;
 import com.intellij.navigation.ItemPresentationProviders;
 import com.intellij.openapi.diagnostic.Logger;
 import com.intellij.openapi.ui.Queryable;
+import com.intellij.openapi.util.Key;
 import com.intellij.openapi.util.Pair;
 import com.intellij.openapi.util.Ref;
 import com.intellij.psi.*;
@@ -52,6 +53,7 @@ public class ClsClassImpl extends ClsRepositoryPsiElement<PsiClassStub<?>> imple
   private final ClassInnerStuffCache innersCache = new ClassInnerStuffCache(this);
   private final PsiIdentifier myNameIdentifier;
   private final PsiDocComment myDocComment;
+  public static final Key<PsiClass> DELEGATE_KEY = Key.create("DELEGATE");
 
   public ClsClassImpl(final PsiClassStub stub) {
     super(stub);
@@ -540,6 +542,11 @@ public class ClsClassImpl extends ClsRepositoryPsiElement<PsiClassStub<?>> imple
 
   @Nullable
   public PsiClass getSourceMirrorClass() {
+    PsiClass delegate = getUserData(DELEGATE_KEY);
+    if (delegate instanceof ClsClassImpl) {
+      return ((ClsClassImpl)delegate).getSourceMirrorClass();
+    }
+
     PsiElement parent = getParent();
     final String name = getName();
     if (parent instanceof PsiFile) {
index c6923329dd83c68fe41ddfa6dbdf5db3f2c03c65..87c91da8c5093a5aed07e4ed6496a344414f84de 100644 (file)
@@ -775,6 +775,9 @@ public class PsiJavaCodeReferenceElementImpl extends CompositePsiElement impleme
            break;
     case CLASS_NAME_KIND:
       addClassFilter(filter);
+      if (isQualified()) {
+        filter.addFilter(ElementClassFilter.PACKAGE_FILTER);
+      }
       break;
     case PACKAGE_NAME_KIND:
            filter.addFilter(ElementClassFilter.PACKAGE_FILTER);
diff --git a/java/java-tests/testData/codeInsight/completion/normal/PackageInMemberType.java b/java/java-tests/testData/codeInsight/completion/normal/PackageInMemberType.java
new file mode 100644 (file)
index 0000000..1080c46
--- /dev/null
@@ -0,0 +1,3 @@
+class Foo {
+  java.l<caret>
+}
\ No newline at end of file
diff --git a/java/java-tests/testData/codeInsight/completion/normal/PackageInMemberType_after.java b/java/java-tests/testData/codeInsight/completion/normal/PackageInMemberType_after.java
new file mode 100644 (file)
index 0000000..9db38bb
--- /dev/null
@@ -0,0 +1,3 @@
+class Foo {
+  java.lang.<caret>
+}
\ No newline at end of file
diff --git a/java/java-tests/testData/fileStructure/selection/Anonymous.java b/java/java-tests/testData/fileStructure/selection/Anonymous.java
new file mode 100644 (file)
index 0000000..7504bf0
--- /dev/null
@@ -0,0 +1,8 @@
+class Anonymous {
+  int num1;
+  int num2;
+  Object o = new Object(){<caret>};
+
+  Anonymous() {}
+  void foo() {}
+}
\ No newline at end of file
diff --git a/java/java-tests/testData/fileStructure/selection/Anonymous.tree b/java/java-tests/testData/fileStructure/selection/Anonymous.tree
new file mode 100644 (file)
index 0000000..94920b4
--- /dev/null
@@ -0,0 +1,8 @@
+-Anonymous.java
+ -Anonymous
+  Anonymous()
+  foo():void
+  num1:int
+  num2:int
+  -[o:Object = new Object() {...}]
+   $1
\ No newline at end of file
diff --git a/java/java-tests/testData/fileStructure/selection/AnonymousInAnonymous.java b/java/java-tests/testData/fileStructure/selection/AnonymousInAnonymous.java
new file mode 100644 (file)
index 0000000..5bfeff7
--- /dev/null
@@ -0,0 +1,15 @@
+class AnonymousInAnonymous {
+  int num1;
+  int num2;
+
+  AnonymousInAnonymous() {}
+  void foo() {
+    new Object() {
+       public String toString() {
+         return new Object(){
+           void method() {<caret>}
+         }.toString();
+       }
+    };
+  }
+}
\ No newline at end of file
diff --git a/java/java-tests/testData/fileStructure/selection/AnonymousInAnonymous.tree b/java/java-tests/testData/fileStructure/selection/AnonymousInAnonymous.tree
new file mode 100644 (file)
index 0000000..1f88488
--- /dev/null
@@ -0,0 +1,10 @@
+-AnonymousInAnonymous.java
+ -AnonymousInAnonymous
+  AnonymousInAnonymous()
+  -foo():void
+   -$1
+    -toString():String
+     -Anonymous
+      [method():void]
+  num1:int
+  num2:int
\ No newline at end of file
diff --git a/java/java-tests/testSrc/Anonymous.java b/java/java-tests/testSrc/Anonymous.java
new file mode 100644 (file)
index 0000000..e72d2fb
--- /dev/null
@@ -0,0 +1,10 @@
+class Anonymous {
+  int num1;
+  int num2;
+  Object o = new Object(){
+    int num = 1;
+  };
+
+  Anonymous() {}
+  void foo() {}
+}
\ No newline at end of file
index 9e74675a1ec28e54155a5e44c4d16e7287914833..e5203e7f1069c182969141bb8d5d8bc4ffeba0f3 100644 (file)
@@ -1258,16 +1258,10 @@ public class ListUtils {
     }
   }
 
-  public void testNoGenericsWhenChoosingWithParen() {
-    configure()
-    myFixture.type 'Ma('
-    checkResult()
-  }
+  public void testNoGenericsWhenChoosingWithParen() { doTest('Ma(') }
 
-  public void testNoClosingWhenChoosingWithParenBeforeIdentifier() {
-    configure()
-    myFixture.type '('
-    checkResult()
-  }
+  public void testNoClosingWhenChoosingWithParenBeforeIdentifier() { doTest '(' }
+
+  public void testPackageInMemberType() { doTest() }
 
 }
index 84e971463a84db5c830d3d75e5f9defbd19b3910..fbea9c3943bfacb5e3857187cef31c4c1549ea75 100644 (file)
@@ -24,8 +24,10 @@ public class JavaFileStructureSelectionTest extends JavaFileStructureTestCase {
     return "selection";
   }
 
-  public void testField() throws Exception {checkTree();}
-  public void testMethod() throws Exception {checkTree();}
-  public void testConstructor() throws Exception {checkTree();}
-  public void testInsideClass() throws Exception {checkTree();}
+  public void testField()                 throws Exception {checkTree();}
+  public void testMethod()                throws Exception {checkTree();}
+  public void testConstructor()           throws Exception {checkTree();}
+  public void testInsideClass()           throws Exception {checkTree();}
+  public void testAnonymous()             throws Exception {checkTree();}
+  public void testAnonymousInAnonymous()  throws Exception {checkTree();}
 }
index 0753206117daf8e84ae6df64ee1b413370a6bce9..c3559b0370f35d5cf6a3b30c353ab3772738fa45 100644 (file)
@@ -33,6 +33,9 @@ public abstract class JavaFileStructureTestCase extends FileStructureTestBase {
   public void setUp() throws Exception {
     super.setUp();
     myShowAnonymousByDefault = PropertiesComponent.getInstance().getBoolean(getAnonymousPropertyName(), false);
+    if (getTestName(false).contains("Anonymous")) {
+      setShowAnonymous(true);
+    }
   }
 
   @Override
@@ -40,6 +43,11 @@ public abstract class JavaFileStructureTestCase extends FileStructureTestBase {
     return "java";
   }
 
+  public void setShowAnonymous(boolean show) throws Exception {
+    myPopup.setTreeActionState(JavaAnonymousClassesNodeProvider.class, show);
+    update();
+  }
+
   @Override
   public void tearDown() throws Exception {
     PropertiesComponent.getInstance().setValue(getAnonymousPropertyName(), Boolean.toString(myShowAnonymousByDefault));
index 4bb636e6fc6d57d1302b2e2a220c6af11ae4e006..e8c89532afcf5de00cf53c0509ef104d568258e6 100644 (file)
       <val name="flagsFromClass" val="java.awt.event.InputEvent.class"/>
     </annotation>
   </item>
+  <item name='java.awt.Rectangle java.awt.Point getLocation()'>
+    <annotation name='org.jetbrains.annotations.NotNull'>
+    </annotation>
+  </item>
+  <item name='java.awt.Rectangle void setLocation(java.awt.Point) 0'>
+    <annotation name='org.jetbrains.annotations.NotNull'>
+    </annotation>
+  </item>
+  <item name='java.awt.Rectangle Rectangle(java.awt.Rectangle) 0'>
+    <annotation name='org.jetbrains.annotations.NotNull'>
+    </annotation>
+  </item>
+  <item name='java.awt.Rectangle Rectangle(java.awt.Point, java.awt.Dimension) 0'>
+    <annotation name='org.jetbrains.annotations.NotNull'>
+    </annotation>
+  </item>
+  <item name='java.awt.Rectangle Rectangle(java.awt.Point, java.awt.Dimension) 1'>
+    <annotation name='org.jetbrains.annotations.NotNull'>
+    </annotation>
+  </item>
+  <item name='java.awt.Rectangle Rectangle(java.awt.Point) 0'>
+    <annotation name='org.jetbrains.annotations.NotNull'>
+    </annotation>
+  </item>
+  <item name='java.awt.Rectangle Rectangle(java.awt.Dimension) 0'>
+    <annotation name='org.jetbrains.annotations.NotNull'>
+    </annotation>
+  </item>
+  <item name='java.awt.Rectangle java.awt.Rectangle getBounds()'>
+    <annotation name='org.jetbrains.annotations.NotNull'>
+    </annotation>
+  </item>
+  <item name='java.awt.Rectangle java.awt.geom.Rectangle2D getBounds2D()'>
+    <annotation name='org.jetbrains.annotations.NotNull'>
+    </annotation>
+  </item>
+  <item name='java.awt.Rectangle void setBounds(java.awt.Rectangle) 0'>
+    <annotation name='org.jetbrains.annotations.NotNull'>
+    </annotation>
+  </item>
+  <item name='java.awt.Rectangle java.awt.Dimension getSize()'>
+    <annotation name='org.jetbrains.annotations.NotNull'>
+    </annotation>
+  </item>
+  <item name='java.awt.Rectangle void setSize(java.awt.Dimension) 0'>
+    <annotation name='org.jetbrains.annotations.NotNull'>
+    </annotation>
+  </item>
+  <item name='java.awt.Rectangle boolean contains(java.awt.Point) 0'>
+    <annotation name='org.jetbrains.annotations.NotNull'>
+    </annotation>
+  </item>
+  <item name='java.awt.Rectangle boolean intersects(java.awt.Rectangle) 0'>
+    <annotation name='org.jetbrains.annotations.NotNull'>
+    </annotation>
+  </item>
+  <item name='java.awt.Rectangle java.awt.Rectangle intersection(java.awt.Rectangle) 0'>
+    <annotation name='org.jetbrains.annotations.NotNull'>
+    </annotation>
+  </item>
+  <item name='java.awt.Rectangle java.awt.Rectangle intersection(java.awt.Rectangle)'>
+    <annotation name='org.jetbrains.annotations.NotNull'>
+    </annotation>
+  </item>
+  <item name='java.awt.Rectangle java.awt.Rectangle union(java.awt.Rectangle) 0'>
+    <annotation name='org.jetbrains.annotations.NotNull'>
+    </annotation>
+  </item>
+  <item name='java.awt.Rectangle java.awt.Rectangle union(java.awt.Rectangle)'>
+    <annotation name='org.jetbrains.annotations.NotNull'>
+    </annotation>
+  </item>
+  <item name='java.awt.Rectangle void add(java.awt.Point) 0'>
+    <annotation name='org.jetbrains.annotations.NotNull'>
+    </annotation>
+  </item>
+  <item name='java.awt.Rectangle void add(java.awt.Rectangle) 0'>
+    <annotation name='org.jetbrains.annotations.NotNull'>
+    </annotation>
+  </item>
+  <item name='java.awt.Rectangle java.awt.geom.Rectangle2D createIntersection(java.awt.geom.Rectangle2D) 0'>
+    <annotation name='org.jetbrains.annotations.NotNull'>
+    </annotation>
+  </item>
+  <item name='java.awt.Rectangle java.awt.geom.Rectangle2D createIntersection(java.awt.geom.Rectangle2D)'>
+    <annotation name='org.jetbrains.annotations.NotNull'>
+    </annotation>
+  </item>
+  <item name='java.awt.Rectangle java.awt.geom.Rectangle2D createUnion(java.awt.geom.Rectangle2D) 0'>
+    <annotation name='org.jetbrains.annotations.NotNull'>
+    </annotation>
+  </item>
+  <item name='java.awt.Rectangle java.awt.geom.Rectangle2D createUnion(java.awt.geom.Rectangle2D)'>
+    <annotation name='org.jetbrains.annotations.NotNull'>
+    </annotation>
+  </item>
 </root>
index 2a02bef74b73cb370eab7d2356522f1cb1eaae17..1a750f0f184729fb30ee9eae0f70962bde9815b4 100644 (file)
@@ -4,7 +4,6 @@
     <exclude-output />
     <content url="file://$MODULE_DIR$">
       <sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
-      <sourceFolder url="file://$MODULE_DIR$/testSrc" isTestSource="true" />
     </content>
     <orderEntry type="inheritedJdk" />
     <orderEntry type="sourceFolder" forTests="false" />
index fdaa66d55eb51516ba7e021d1982336a87884ab6..562e30fdc462fc66d6519b6529b4aea000db135a 100644 (file)
@@ -88,6 +88,7 @@ public class CompileContext extends UserDataHolderBase implements MessageHandler
   }
 
   public void markDirty(final ModuleChunk chunk) throws Exception {
+    myFsState.clearContextRoundData();
     final Set<Module> modules = chunk.getModules();
     for (Module module : modules) {
       markDirtyFiles(module, myTsStorage, true, isCompilingTests()? DirtyMarkScope.TESTS : DirtyMarkScope.PRODUCTION, null);
index 792d5104830d5d0f91262371b7abdac58dfd0c51..11ef36a2f3f19e0d12b7e3e504f3413d981e8eff 100644 (file)
@@ -367,6 +367,7 @@ public class IncProjectBuilder {
       return;
     }
 
+    boolean rebuildFromScratchRequested = false;
     float stageCount = myTotalBuilderCount;
     int stagesPassed = 0;
     final int modulesInChunk = chunk.getModules().size();
@@ -398,6 +399,27 @@ public class IncProjectBuilder {
           }
           nextPassRequired = true;
         }
+        else if (buildResult == ModuleLevelBuilder.ExitCode.CHUNK_REBUILD_REQUIRED) {
+          if (!rebuildFromScratchRequested) {
+            // allow rebuild from scratch only once per chunk
+            rebuildFromScratchRequested = true;
+            try {
+              // forcibly mark all files in the chunk dirty
+              context.markDirty(chunk);
+              // reverting to the beginning
+              myModulesProcessed -= (stagesPassed * modulesInChunk) / stageCount;
+              stagesPassed = 0;
+              nextPassRequired = true;
+              break;
+            }
+            catch (Exception e) {
+              throw new ProjectBuildException(e);
+            }
+          }
+          else {
+            LOG.info("Builder " + builder.getDescription() + " requested second chunk rebuild");
+          }
+        }
 
         stagesPassed++;
         final float fraction = updateFractionBuilderFinished(modulesInChunk / (stageCount));
index 5b287cddbff4032d68d274b78e1b81f066850695..8fb35f7c1a9af4a7918c4ca5e4a781b1cb581fde 100644 (file)
@@ -24,7 +24,7 @@ public abstract class ModuleLevelBuilder extends Builder {
   private static final Key<Set<File>> ALL_COMPILED_FILES_KEY = Key.create("_all_compiled_files_");
 
   public static enum ExitCode {
-    OK, ABORT, ADDITIONAL_PASS_REQUIRED
+    OK, ABORT, ADDITIONAL_PASS_REQUIRED, CHUNK_REBUILD_REQUIRED
   }
 
   public abstract ExitCode build(CompileContext context, ModuleChunk chunk) throws ProjectBuildException;
index f0742ba9bcdbdbef490f0131fb410f03a2071472..2a156ddbb2535f9db54451087615d865dc121066 100644 (file)
@@ -2,6 +2,7 @@ package org.jetbrains.jps.incremental.groovy;
 
 
 import com.intellij.openapi.util.Comparing;
+import com.intellij.openapi.util.Key;
 import com.intellij.openapi.util.io.FileUtil;
 import com.intellij.util.ArrayUtil;
 import com.intellij.util.Consumer;
@@ -32,6 +33,7 @@ import java.util.*;
  */
 public class GroovyBuilder extends ModuleLevelBuilder {
   public static final String BUILDER_NAME = "groovy";
+  private static final Key<Boolean> CHUNK_REBUILD_ORDERED = Key.<Boolean>create("CHUNK_REBUILD_ORDERED");
   private final boolean myForStubs;
   private final String myBuilderName;
 
@@ -91,6 +93,16 @@ public class GroovyBuilder extends ModuleLevelBuilder {
           }
         });
 
+        if (myForStubs && handler.shouldRetry()) {
+          if (CHUNK_REBUILD_ORDERED.get(context) != null) {
+            CHUNK_REBUILD_ORDERED.set(context, null);
+          } else {
+            CHUNK_REBUILD_ORDERED.set(context, Boolean.TRUE);
+            exitCode = ExitCode.CHUNK_REBUILD_REQUIRED;
+            return exitCode;
+          }
+        }
+
         successfullyCompiled = handler.getSuccessfullyCompiled();
 
         for (CompilerMessage message : handler.getCompilerMessages()) {
index 91310a34b29efead2259a63f1673a52ecc65c73d..9383724a555e86c3281823a222011f07e9e47a24 100644 (file)
@@ -35,8 +35,7 @@ import org.objectweb.asm.ClassWriter;
 import org.objectweb.asm.Opcodes;
 import org.objectweb.asm.commons.EmptyVisitor;
 
-import javax.tools.Diagnostic;
-import javax.tools.JavaFileObject;
+import javax.tools.*;
 import java.io.*;
 import java.net.MalformedURLException;
 import java.net.ServerSocket;
@@ -257,7 +256,7 @@ public class JavaBuilder extends ModuleLevelBuilder {
       if (hasSourcesToCompile) {
         final Set<File> sourcePath = TEMPORARY_SOURCE_ROOTS_KEY.get(context, Collections.<File>emptySet());
 
-        final boolean compiledOk = compileJava(files, classpath, platformCp, sourcePath, outs, context, diagnosticSink, outputSink);
+        final boolean compiledOk = compileJava(chunk, files, classpath, platformCp, sourcePath, outs, context, diagnosticSink, outputSink);
 
         final Map<File, String> chunkSourcePath = ProjectPaths.getSourceRootsWithDependents(chunk, context.isCompilingTests());
         final ClassLoader compiledClassesLoader = createInstrumentationClassLoader(classpath, platformCp, chunkSourcePath, outputSink);
@@ -312,7 +311,7 @@ public class JavaBuilder extends ModuleLevelBuilder {
     return exitCode;
   }
 
-  private boolean compileJava(Collection<File> files,
+  private boolean compileJava(ModuleChunk chunk, Collection<File> files,
                               Collection<File> classpath,
                               Collection<File> platformCp,
                               Collection<File> sourcePath,
@@ -320,18 +319,20 @@ public class JavaBuilder extends ModuleLevelBuilder {
                               CompileContext context,
                               DiagnosticOutputConsumer diagnosticSink,
                               final OutputFileConsumer outputSink) throws Exception {
-    final List<String> options = getCompilationOptions(context);
+    final List<String> options = getCompilationOptions(context, chunk);
     final ClassProcessingConsumer classesConsumer = new ClassProcessingConsumer(context, outputSink);
     try {
       final boolean rc;
       if (USE_EMBEDDED_JAVAC) {
-        rc = JavacMain
-          .compile(options, files, classpath, platformCp, sourcePath, outs, diagnosticSink, classesConsumer, context.getCancelStatus());
+        rc = JavacMain.compile(
+          options, files, classpath, platformCp, sourcePath, outs, diagnosticSink, classesConsumer, context.getCancelStatus()
+        );
       }
       else {
         final JavacServerClient client = ensureJavacServerLaunched(context);
-        final RequestFuture<JavacServerResponseHandler> future =
-          client.sendCompileRequest(options, files, classpath, platformCp, sourcePath, outs, diagnosticSink, classesConsumer);
+        final RequestFuture<JavacServerResponseHandler> future = client.sendCompileRequest(
+          options, files, classpath, platformCp, sourcePath, outs, diagnosticSink, classesConsumer
+        );
         try {
           future.get();
         }
@@ -361,8 +362,9 @@ public class JavaBuilder extends ModuleLevelBuilder {
     final int port = findFreePort();
     final int heapSize = getJavacServerHeapSize(context);
 
-    final BaseOSProcessHandler processHandler =
-      JavacServerBootstrap.launchJavacServer(vmExecPath, heapSize, port, Paths.getSystemRoot(), getCompilationVMOptions(context));
+    final BaseOSProcessHandler processHandler = JavacServerBootstrap.launchJavacServer(
+      vmExecPath, heapSize, port, Paths.getSystemRoot(), getCompilationVMOptions(context)
+    );
     final JavacServerClient client = new JavacServerClient();
     try {
       client.connect(hostString, port);
@@ -445,13 +447,18 @@ public class JavaBuilder extends ModuleLevelBuilder {
     return cached;
   }
 
-  private static List<String> getCompilationOptions(CompileContext context) {
+  private static List<String> getCompilationOptions(CompileContext context, ModuleChunk chunk) {
     List<String> cached = JAVAC_OPTIONS.get(context);
     if (cached == null) {
       loadJavacOptions(context);
       cached = JAVAC_OPTIONS.get(context);
     }
     return cached;
+    //final List<String> options = new ArrayList<String>(cached);
+    //final Module module = chunk.getModules().iterator().next();
+    //final String langlevel = module.getLanguageLevel();
+    //final Sdk sdk = module.getSdk();
+    //return options;
   }
 
   private static void loadJavacOptions(CompileContext context) {
index 0b49fee14964088239a921026542ec96953be2ac..5afd8908e8f8c388797ad1a4fb1ecab6bd075756 100644 (file)
@@ -63,18 +63,7 @@ class ServerMessageHandler extends SimpleChannelHandler {
         case CANCEL_BUILD_COMMAND:
           final JpsRemoteProto.Message.Request.CancelBuildCommand cancelCommand = request.getCancelBuildCommand();
           final UUID targetSessionId = ProtoUtil.fromProtoUUID(cancelCommand.getTargetSessionId());
-          synchronized (myBuildsInProgress) {
-            for (Iterator<Pair<RunnableFuture, CompilationTask>> it = myBuildsInProgress.iterator(); it.hasNext(); ) {
-              final Pair<RunnableFuture, CompilationTask> pair = it.next();
-              final CompilationTask task = pair.second;
-              if (task.getSessionId().equals(targetSessionId)) {
-                it.remove();
-                task.cancel();
-                pair.first.cancel(true);
-                break;
-              }
-            }
-          }
+          cancelSession(targetSessionId);
           reply = ProtoUtil.toMessage(sessionId, ProtoUtil.createCommandCompletedEvent(null));
           break;
         case SETUP_COMMAND:
@@ -158,6 +147,30 @@ class ServerMessageHandler extends SimpleChannelHandler {
     }
   }
 
+  private void cancelSession(UUID targetSessionId) {
+    synchronized (myBuildsInProgress) {
+      for (Iterator<Pair<RunnableFuture, CompilationTask>> it = myBuildsInProgress.iterator(); it.hasNext(); ) {
+        final Pair<RunnableFuture, CompilationTask> pair = it.next();
+        final CompilationTask task = pair.second;
+        if (task.getSessionId().equals(targetSessionId)) {
+          it.remove();
+          task.cancel();
+          pair.first.cancel(true);
+          break;
+        }
+      }
+    }
+  }
+
+  @Override
+  public void channelDisconnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
+    final Object attachment = ctx.getAttachment();
+    if (attachment instanceof UUID) {
+      cancelSession((UUID)attachment);
+    }
+    super.channelDisconnected(ctx, e);
+  }
+
   @Nullable
   private JpsRemoteProto.Message startBuild(UUID sessionId, final ChannelHandlerContext channelContext, JpsRemoteProto.Message.Request.CompilationRequest compileRequest) {
     if (!compileRequest.hasProjectId()) {
@@ -172,6 +185,7 @@ class ServerMessageHandler extends SimpleChannelHandler {
       case MAKE:
       case FORCED_COMPILATION:
       case REBUILD: {
+        channelContext.setAttachment(sessionId);
         final BuildType buildType = convertCompileType(compileType);
         final CompilationTask task = new CompilationTask(
           sessionId, channelContext, projectId, buildType, compileRequest.getModuleNameList(), compileRequest.getFilePathList()
index 09e9a71eac0363cb9a2271bf70cf5575254b6a9f..fdd01362d71743d49aa526125dca75ee5ad608f0 100644 (file)
@@ -53,73 +53,73 @@ public abstract class IncrementalTestCase extends TestCase {
       this.root = root;
     }
 
-    String strip(final String s){
+    String strip(final String s) {
       if (s.startsWith(root)) {
         return s.substring(root.length());
       }
-      
+
       return s;
     }
-  } 
+  }
 
   static {
     Logger.setFactory(new Logger.Factory() {
+      @Override
+      public Logger getLoggerInstance(String category) {
+        final org.apache.log4j.Logger logger = org.apache.log4j.Logger.getLogger(category);
+
+        final boolean affectedLogger = category.equals("#org.jetbrains.jps.incremental.java.JavaBuilder") ||
+                                       category.equals("#org.jetbrains.jps.incremental.IncProjectBuilder");
+
+        return new Logger() {
+          @Override
+          public boolean isDebugEnabled() {
+            return affectedLogger;
+          }
+
+          @Override
+          public void debug(@NonNls String message) {
+          }
+
+          @Override
+          public void debug(@Nullable Throwable t) {
+          }
+
+          @Override
+          public void debug(@NonNls String message, @Nullable Throwable t) {
+          }
+
+          @Override
+          public void error(@NonNls String message, @Nullable Throwable t, @NonNls String... details) {
+          }
+
+          @Override
+          public void info(@NonNls String message) {
+            if (affectedLogger) {
+              logger.info(stripper.strip(message));
+            }
+          }
+
+          @Override
+          public void info(@NonNls String message, @Nullable Throwable t) {
+          }
+
+          @Override
+          public void warn(@NonNls String message, @Nullable Throwable t) {
+          }
+
           @Override
-          public Logger getLoggerInstance(String category) {
-            final org.apache.log4j.Logger logger = org.apache.log4j.Logger.getLogger(category);
-
-            final boolean affectedLogger = category.equals("#org.jetbrains.jps.incremental.java.JavaBuilder") ||
-                                           category.equals("#org.jetbrains.jps.incremental.IncProjectBuilder");
-
-            return new Logger() {
-              @Override
-              public boolean isDebugEnabled() {
-                return affectedLogger;
-              }
-
-              @Override
-              public void debug(@NonNls String message) {
-              }
-
-              @Override
-              public void debug(@Nullable Throwable t) {
-              }
-
-              @Override
-              public void debug(@NonNls String message, @Nullable Throwable t) {
-              }
-
-              @Override
-              public void error(@NonNls String message, @Nullable Throwable t, @NonNls String... details) {
-              }
-
-              @Override
-              public void info(@NonNls String message) {
-                if (affectedLogger) {
-                  logger.info(stripper.strip(message));
-                }
-              }
-
-              @Override
-              public void info(@NonNls String message, @Nullable Throwable t) {
-              }
-
-              @Override
-              public void warn(@NonNls String message, @Nullable Throwable t) {
-              }
-
-              @Override
-              public void setLevel(Level level) {
-              }
-            };
+          public void setLevel(Level level) {
           }
-        });
+        };
+      }
+    });
   }
 
   private static RootStripper stripper = new RootStripper();
-  
+
   private final String groupName;
-  private final String tempDir = System.getProperty("java.io.tmpdir");
+  private final String tempDir = FileUtil.toSystemDependentName(new File(System.getProperty("java.io.tmpdir")).getCanonicalPath());
 
   private String baseDir;
   private String workDir;
@@ -149,17 +149,19 @@ public abstract class IncrementalTestCase extends TestCase {
   @Override
   protected void tearDown() throws Exception {
     super.tearDown();
-    delete(new File(workDir));
+    //delete(new File(workDir));
   }
 
-  private String getDir(final String prefix) {
+  private String getProjectName() {
     final String name = getName();
 
     assert (name.startsWith("test"));
 
-    final String result = Character.toLowerCase(name.charAt("test".length())) + name.substring("test".length() + 1);
+    return Character.toLowerCase(name.charAt("test".length())) + name.substring("test".length() + 1);
+  }
 
-    return prefix + groupName + File.separator + result;
+  private String getDir(final String prefix) {
+    return prefix + groupName + File.separator + getProjectName();
   }
 
   private String getBaseDir() {
@@ -183,6 +185,7 @@ public abstract class IncrementalTestCase extends TestCase {
 
     if (!file.delete()) throw new IOException("could not delete file or directory " + file.getPath());
   }
+
   private static void copy(final File input, final File output) throws Exception {
     if (input.isDirectory()) {
       if (output.mkdirs()) {
@@ -256,18 +259,19 @@ public abstract class IncrementalTestCase extends TestCase {
   }
 
   public void doTest() throws Exception {
-    stripper.setRoot(getWorkDir() + File.separator);
-    
+    stripper.setRoot(FileUtil.toSystemIndependentName(getWorkDir() + File.separator));
+
     initLoggers();
 
     final String projectPath = getWorkDir() + File.separator + ".idea";
+    final String projectName = getProjectName();
     final Project project = new Project();
 
     IdeaProjectLoader.loadFromPath(project, projectPath, "");
 
     final ProjectDescriptor projectDescriptor =
-      new ProjectDescriptor(projectPath, project, new FSState(true), new ProjectTimestamps(projectPath),
-                            new BuildDataManager(projectPath, true));
+      new ProjectDescriptor(projectPath, project, new FSState(true), new ProjectTimestamps(projectName),
+                            new BuildDataManager(projectName, true));
     final IncProjectBuilder builder = new IncProjectBuilder(projectDescriptor, BuilderRegistry.getInstance(), CanceledStatus.NULL);
 
     builder.build(new AllProjectScope(project, true), false, true);
index c524c6e0992617acc22cf3e4fef4d8bd2769c74d..c2969d9edc098335303acfd3365f24c093deb63b 100644 (file)
@@ -32,11 +32,14 @@ public class CoreJarVirtualFile extends VirtualFile {
   private final CoreJarFileSystem myFileSystem;
   private final CoreJarHandler myHandler;
   private final String myPathInJar;
+  private final VirtualFile myParent;
+  private VirtualFile[] myChildren;
 
   public CoreJarVirtualFile(CoreJarFileSystem fileSystem, CoreJarHandler handler, String pathInJar) {
     myFileSystem = fileSystem;
     myHandler = handler;
     myPathInJar = pathInJar;
+    myParent = calcParent();
   }
 
   @NotNull
@@ -77,6 +80,10 @@ public class CoreJarVirtualFile extends VirtualFile {
 
   @Override
   public VirtualFile getParent() {
+    return myParent;
+  }
+
+  private VirtualFile calcParent() {
     if (myPathInJar.length() == 0) {
       return null;
     }
@@ -89,6 +96,15 @@ public class CoreJarVirtualFile extends VirtualFile {
 
   @Override
   public VirtualFile[] getChildren() {
+    VirtualFile[] answer = myChildren;
+    if (answer == null) {
+      answer = calcChildren();
+      myChildren = answer;
+    }
+    return answer;
+  }
+
+  private VirtualFile[] calcChildren() {
     List<VirtualFile> result = new ArrayList<VirtualFile>();
     final String[] children = myHandler.list(this);
     for (String child : children) {
index d2c292239e906bac239337f8f37acbff756f52d6..ab6cc4f284740d6fd2646048cf771ddc4ace1f03 100644 (file)
@@ -54,6 +54,7 @@ public abstract class PsiCachedValue<T> extends CachedValueBase<T> {
   protected boolean isDependencyOutOfDate(Object dependency, long oldTimeStamp) {
     if (dependency instanceof PsiElement &&
         myLastPsiTimeStamp == myManager.getModificationTracker().getModificationCount() &&
+        ((PsiElement)dependency).isValid() &&
         ((PsiElement)dependency).isPhysical()) {
       return false;
     }
index 3fe5bf17858caa626b11f0bd41a6e64492a97782..3413475fa4776a1f51a1f767c514cf5a7af40a0b 100644 (file)
  */
 package com.intellij.refactoring.util;
 
-import com.intellij.psi.*;
-import com.intellij.usageView.UsageInfo;
-import com.intellij.openapi.editor.RangeMarker;
 import com.intellij.openapi.editor.Document;
+import com.intellij.openapi.editor.RangeMarker;
 import com.intellij.openapi.project.Project;
 import com.intellij.openapi.util.TextRange;
+import com.intellij.psi.*;
+import com.intellij.usageView.UsageInfo;
 import org.jetbrains.annotations.Nullable;
 
 public class MoveRenameUsageInfo extends UsageInfo{
@@ -53,7 +53,12 @@ public class MoveRenameUsageInfo extends UsageInfo{
     }
     if (reference == null) reference = element.getReference();
     PsiFile containingFile = element.getContainingFile();
-    if (reference == null) reference = containingFile.findReferenceAt(element.getTextRange().getStartOffset());
+    if (reference == null) {
+      final TextRange textRange = element.getTextRange();
+      if (textRange != null) {
+        reference = containingFile.findReferenceAt(textRange.getStartOffset());
+      }
+    }
     myReference = reference;
     if (reference != null) {
       Document document = PsiDocumentManager.getInstance(project).getDocument(containingFile);
index 6ff52c50a8373ff6a6c5871b101a04a8e0d45e67..3bd5e56306ad071d202f06a5d6ad7f0f20040fab 100644 (file)
@@ -329,6 +329,7 @@ public class CodeCompletionHandlerBase implements CodeInsightActionHandler {
     final Runnable computeRunnable = new Runnable() {
       @Override
       public void run() {
+        final AtomicReference<LookupElement[]> data1 = new AtomicReference<LookupElement[]>(null);
         ProgressManager.getInstance().runProcess(new Runnable() {
           @Override
           public void run() {
@@ -342,7 +343,7 @@ public class CodeCompletionHandlerBase implements CodeInsightActionHandler {
                   indicator.duringCompletion(initContext);
                   ProgressManager.checkCanceled();
 
-                  data.set(CompletionService.getCompletionService().performCompletion(parameters, new Consumer<CompletionResult>() {
+                  data1.set(CompletionService.getCompletionService().performCompletion(parameters, new Consumer<CompletionResult>() {
                     @Override
                     public void consume(final CompletionResult result) {
                       indicator.addItem(result);
@@ -355,6 +356,7 @@ public class CodeCompletionHandlerBase implements CodeInsightActionHandler {
             }
           }
         }, indicator);
+        data.set(data1.get());
       }
     };
 
index 9494456141a3f69b77a40da0614602ef42639688..00d0e8345a606c1c08e7e4b1423ac5c50122c272 100644 (file)
@@ -150,7 +150,6 @@ public class DaemonTooltipRendererProvider implements ErrorStripTooltipRendererP
             text += UIUtil.getHtmlBody(problem).replace(DaemonBundle.message("inspection.extended.description"),
                                                         DaemonBundle.message("inspection.collapse.description")) +
                     BORDER_LINE + UIUtil.getHtmlBody(description) + BORDER_LINE;
-            break;
           }
         }
       }
index 08ad4e7b40c0b268f3675ac671e81f0b924a4805..71639a3a8339a3b3a44daec04f6c3caf843bdf84 100644 (file)
@@ -134,9 +134,11 @@ public abstract class HTMLComposerImpl extends HTMLComposer {
     refElement.accept(new RefVisitor() {
       @Override public void visitFile(RefFile file) {
         final PsiFile psiFile = file.getElement();
-        buf.append(B_OPENING);
-        buf.append(psiFile.getName());
-        buf.append(B_CLOSING);
+        if (psiFile != null) {
+          buf.append(B_OPENING);
+          buf.append(psiFile.getName());
+          buf.append(B_CLOSING);
+        }
       }
     });
   }
index 414d2d45c92730525f87c557d20fc8688e60a6c1..5387f12c699542a1c77bdb4ed6379e337080a5f5 100644 (file)
@@ -43,4 +43,8 @@ public class RestoreViewAction extends AnAction {
   public void actionPerformed(final AnActionEvent e) {
     myRestoreAction.restoreInGrid();
   }
+
+  public Content getContent() {
+    return myContent;
+  }
 }
index 8fcbbed3abb3c65604a38a6fdd8a6165ad94023a..1350d5fa04683b2e14e349eebe51281dee78418a 100644 (file)
@@ -451,8 +451,7 @@ public class GridCellImpl implements GridCell {
 
   private ActionCallback restore(Content content) {
     myMinimizedContents.remove(content);
-    add(content);
-    updateSelection(myTabs.getComponent().getRootPane() != null);
+    myContext.getContentManager().addContent(content);
     return new ActionCallback.Done();
   }
 }
index 4be237f92767fe7b5b6b946fca85636c262e39ce..e31d8a32d3cd3a0a1dd4422a9513091e724426e6 100644 (file)
@@ -430,9 +430,11 @@ public class RunnerContentUi implements ContentUI, Disposable, CellTransform.Fac
 
   @Override
   public void add(DockableContent dockable, RelativePoint dropTarget) {
+    final DockableGrid dockableGrid = (DockableGrid)dockable;
+    final RunnerContentUi prev = dockableGrid.getRunnerUi();
+
     saveUiState();
 
-    final DockableGrid dockableGrid = (DockableGrid)dockable;
     final List<Content> contents = dockableGrid.getContents();
     final boolean wasRestoring = myOriginal != null && myOriginal.isStateBeingRestored();
     setStateIsBeingRestored(true, this);
@@ -441,16 +443,18 @@ public class RunnerContentUi implements ContentUI, Disposable, CellTransform.Fac
       boolean hadGrid = !myTabs.shouldAddToGlobal(point);
 
       for (Content content : contents) {
-        dockableGrid.getRunnerUi().myManager.removeContent(content, false);
+        final View view = getStateFor(content);
+        if (view.isMinimizedInGrid()) continue;
+        prev.myManager.removeContent(content, false);
         myManager.removeContent(content, false);
-        if (hadGrid && contents.size() == 1 && !wasRestoring) {
-          getStateFor(content).assignTab(getTabFor(getSelectedGrid()));
-          getStateFor(content).setPlaceInGrid(myLayoutSettings.getDefaultGridPlace(content));
+        if (hadGrid && !wasRestoring) {
+          view.assignTab(getTabFor(getSelectedGrid()));
+          view.setPlaceInGrid(myLayoutSettings.getDefaultGridPlace(content));
         } else if (contents.size() == 1 && !wasRestoring) {
-          getStateFor(content).assignTab(null);
-          getStateFor(content).setPlaceInGrid(myLayoutSettings.getDefaultGridPlace(content));
+          view.assignTab(null);
+          view.setPlaceInGrid(myLayoutSettings.getDefaultGridPlace(content));
         }
-        getStateFor(content).setWindow(myWindow);
+        view.setWindow(myWindow);
         myManager.addContent(content);
       }
     } finally {
@@ -576,7 +580,6 @@ public class RunnerContentUi implements ContentUI, Disposable, CellTransform.Fac
 
         updateTabsUI(false);
 
-
         event.getContent().addPropertyChangeListener(RunnerContentUi.this);
         fireContentOpened(event.getContent());
       }
@@ -826,8 +829,14 @@ public class RunnerContentUi implements ContentUI, Disposable, CellTransform.Fac
       }
     }
 
+    tab.setHidden(true);
+    for (Content content : contents) {
+      if (!grid.isMinimized(content)) {
+        tab.setHidden(false);
+        break;
+      }
+    }
     if (icon == null && contents.size() == 1) {
-      tab.setHidden(grid.isMinimized(contents.get(0)));
       icon = contents.get(0).getIcon();
     }
 
@@ -1021,6 +1030,10 @@ public class RunnerContentUi implements ContentUI, Disposable, CellTransform.Fac
     for (RunnerContentUi child : children) {
       Collections.addAll(contents, child.myManager.getContents());
     }
+    for (AnAction action : myMinimizedViewActions.getChildren(null)) {
+      final Content content = ((RestoreViewAction)action).getContent();
+      contents.add(content);
+    }
     Content[] all = contents.toArray(new Content[contents.size()]);
     Arrays.sort(all, new Comparator<Content>() {
       @Override
@@ -1280,16 +1293,20 @@ public class RunnerContentUi implements ContentUI, Disposable, CellTransform.Fac
 
   public void minimize(final Content content, final CellTransform.Restore restore) {
     final Ref<AnAction> restoreAction = new Ref<AnAction>();
+    myManager.removeContent(content, false);
     restoreAction.set(new RestoreViewAction(content, new CellTransform.Restore() {
       public ActionCallback restoreInGrid() {
         myMinimizedViewActions.remove(restoreAction.get());
-        return restore.restoreInGrid().doWhenDone(new Runnable() {
-          public void run() {
-            saveUiState();
-            select(content, true);
-            updateTabsUI(false);
-          }
-        });
+        final GridImpl grid = getGridFor(content, false);
+        if (grid == null) {
+          getStateFor(content).assignTab(myLayoutSettings.getOrCreateTab(-1));
+        }
+        getStateFor(content).setMinimizedInGrid(false);
+        myManager.addContent(content);
+        saveUiState();
+        select(content, true);
+        updateTabsUI(false);
+        return new ActionCallback.Done();
       }
     }));
 
index f8f5ff80d6b6136d8a76543f31b0dbc405f8eecd..a1b16d706bc694382d6a6e54e80f87091923761f 100644 (file)
@@ -18,6 +18,7 @@ package com.intellij.ide.hierarchy;
 
 import com.intellij.ide.actions.CloseTabToolbarAction;
 import com.intellij.ide.actions.ContextHelpAction;
+import com.intellij.ide.util.treeView.AbstractTreeUi;
 import com.intellij.openapi.Disposable;
 import com.intellij.openapi.actionSystem.*;
 import com.intellij.openapi.progress.ProgressIndicator;
@@ -217,7 +218,9 @@ public abstract class HierarchyBrowserBase extends SimpleToolWindowPanel impleme
 
   private final class CloseAction extends CloseTabToolbarAction {
     public final void actionPerformed(final AnActionEvent e) {
-      final ProgressIndicator progress = getCurrentBuilder().getUi().getProgress();
+      final HierarchyTreeBuilder builder = getCurrentBuilder();
+      final AbstractTreeUi treeUi = builder != null ? builder.getUi() : null;
+      final ProgressIndicator progress = treeUi != null ? treeUi.getProgress() : null;
       if (progress != null) {
         progress.cancel();
       }
index 39dbe47a25aa718e29a96fad3c3096a5d0bdbf93..bc270a07174d90baa279602a02828ab7831105a7 100644 (file)
@@ -107,6 +107,7 @@ public class FileStructurePopup implements Disposable {
   private int myPreferredWidth;
   private final FilteringTreeStructure myFilteringStructure;
   private PsiElement myInitialPsiElement;
+  private Map<Class, JCheckBox> myCheckBoxes = new HashMap<Class, JCheckBox>();
 
   public FileStructurePopup(StructureViewModel structureViewModel,
                             @Nullable Editor editor,
@@ -128,7 +129,7 @@ public class FileStructurePopup implements Disposable {
 
     myTreeStructure = new SmartTreeStructure(project, myTreeModel){
       public void rebuildTree() {
-        if (!myPopup.isDisposed()) {
+        if (ApplicationManager.getApplication().isUnitTestMode() || !myPopup.isDisposed()) {
           super.rebuildTree();
         }
       }
@@ -503,7 +504,7 @@ public class FileStructurePopup implements Disposable {
     return null;
   }
 
-  protected JComponent createCenterPanel() {
+  public JComponent createCenterPanel() {
     List<FileStructureFilter> fileStructureFilters = new ArrayList<FileStructureFilter>();
     List<FileStructureNodeProvider> fileStructureNodeProviders = new ArrayList<FileStructureNodeProvider>();
     if (myTreeActionsOwner != null) {
@@ -704,6 +705,7 @@ public class FileStructurePopup implements Disposable {
     }
     chkFilter.setText(text);
     panel.add(chkFilter);
+    myCheckBoxes.put(action.getClass(), chkFilter);
   }
 
   private static boolean getDefaultValue(TreeAction action) {
@@ -742,6 +744,16 @@ public class FileStructurePopup implements Disposable {
     return myAbstractTreeBuilder;
   }
 
+  public void setTreeActionState(Class<? extends TreeAction> action, boolean state) {
+    final JCheckBox checkBox = myCheckBoxes.get(action);
+    if (checkBox != null) {
+      checkBox.setSelected(state);
+      for (ActionListener listener : checkBox.getActionListeners()) {
+        listener.actionPerformed(new ActionEvent(this, 1, ""));
+      }
+    }
+  }
+
   private class FileStructurePopupFilter implements ElementFilter {
     private String myLastFilter = null;
     private HashSet<Object> myVisibleParents = new HashSet<Object>();
index 2b459981aa6c9157602a19f44f554693be803838..8bb74f7f4a650fbfc1b0e79de256197dad758eb4 100644 (file)
@@ -118,7 +118,7 @@ public abstract class ChooseByNameBase {
 
   private volatile boolean myListIsUpToDate = false;
   private boolean myDisposedFlag = false;
-  private ActionCallback myPosponedOkAction;
+  private ActionCallback myPostponedOkAction;
 
   private final String[][] myNames = new String[2][];
   private CalcElementsThread myCalcElementsThread;
@@ -141,8 +141,8 @@ public abstract class ChooseByNameBase {
   private String myFindUsagesTitle;
 
   public boolean checkDisposed() {
-    if (myDisposedFlag && myPosponedOkAction != null && !myPosponedOkAction.isProcessed()) {
-      myPosponedOkAction.setRejected();
+    if (myDisposedFlag && myPostponedOkAction != null && !myPostponedOkAction.isProcessed()) {
+      myPostponedOkAction.setRejected();
     }
     
     return myDisposedFlag;
@@ -679,8 +679,8 @@ public abstract class ChooseByNameBase {
 
     final String text = myTextField.getText();
     if (ok && !myListIsUpToDate && text != null && text.trim().length() > 0) {
-      myPosponedOkAction = new ActionCallback();
-      IdeFocusManager.getInstance(myProject).typeAheadUntil(myPosponedOkAction);
+      myPostponedOkAction = new ActionCallback();
+      IdeFocusManager.getInstance(myProject).typeAheadUntil(myPostponedOkAction);
       return true;
     }
 
@@ -1067,7 +1067,7 @@ public abstract class ChooseByNameBase {
     }
 
     private void doPostponedOkIfNeeded() {
-      if (myPosponedOkAction != null) {
+      if (myPostponedOkAction != null) {
         if (getChosenElement() != null) {
           doClose(true);
         }
@@ -1077,16 +1077,16 @@ public abstract class ChooseByNameBase {
   }
 
   private void clearPosponedOkAction(boolean success) {
-    if (myPosponedOkAction != null) {
+    if (myPostponedOkAction != null) {
       if (success) {
-        myPosponedOkAction.setDone();
+        myPostponedOkAction.setDone();
       }
       else {
-        myPosponedOkAction.setRejected();
+        myPostponedOkAction.setRejected();
       }
     }
 
-    myPosponedOkAction = null;
+    myPostponedOkAction = null;
   }
 
   protected abstract void showList();
index c7c1be5bd0137c26b9f9b30d696188cf9cc79c89..662cb6ce10633d0d4ff98d737f08c503e10cfe6e 100644 (file)
@@ -48,7 +48,7 @@ public class ChooseByNamePopup extends ChooseByNameBase implements ChooseByNameP
   private boolean myMayRequestCurrentWindow;
 
   protected ChooseByNamePopup(final Project project, final ChooseByNameModel model, ChooseByNameItemProvider provider, final ChooseByNamePopup oldPopup,
-                            @Nullable final String predefinedText, boolean mayRequestOpenInCurrentWundow, int initialIndex) {
+                            @Nullable final String predefinedText, boolean mayRequestOpenInCurrentWindow, int initialIndex) {
     super(project, model, provider, oldPopup != null ? oldPopup.getEnteredText() : predefinedText, initialIndex);
     if (oldPopup == null && predefinedText != null) {
       setPreselectInitialText(true);
@@ -56,7 +56,7 @@ public class ChooseByNamePopup extends ChooseByNameBase implements ChooseByNameP
     if (oldPopup != null) { //inherit old focus owner
       myOldFocusOwner = oldPopup.myPreviouslyFocusedComponent;
     }
-    myMayRequestCurrentWindow = mayRequestOpenInCurrentWundow;
+    myMayRequestCurrentWindow = mayRequestOpenInCurrentWindow;
   }
 
   public String getEnteredText() {
@@ -113,13 +113,13 @@ public class ChooseByNamePopup extends ChooseByNameBase implements ChooseByNameP
 
     preferredScrollPaneSize.width = Math.max(myTextFieldPanel.getWidth(), preferredScrollPaneSize.width);
 
-    Rectangle prefferedBounds = new Rectangle(bounds.x, bounds.y, preferredScrollPaneSize.width, preferredScrollPaneSize.height);
-    Rectangle original = new Rectangle(prefferedBounds);
+    Rectangle preferredBounds = new Rectangle(bounds.x, bounds.y, preferredScrollPaneSize.width, preferredScrollPaneSize.height);
+    Rectangle original = new Rectangle(preferredBounds);
 
-    ScreenUtil.fitToScreen(prefferedBounds);
-    if (original.width > prefferedBounds.width) {
+    ScreenUtil.fitToScreen(preferredBounds);
+    if (original.width > preferredBounds.width) {
       int height = myListScrollPane.getHorizontalScrollBar().getPreferredSize().height;
-      prefferedBounds.height += height;
+      preferredBounds.height += height;
     }
 
     myListScrollPane.setVisible(true);
@@ -136,12 +136,18 @@ public class ChooseByNamePopup extends ChooseByNameBase implements ChooseByNameP
         }
       });
       myDropdownPopup = builder.createPopup();
-      myDropdownPopup.setLocation(prefferedBounds.getLocation());
-      myDropdownPopup.setSize(prefferedBounds.getSize());
+      myDropdownPopup.setLocation(preferredBounds.getLocation());
+      myDropdownPopup.setSize(preferredBounds.getSize());
       myDropdownPopup.show(layeredPane);
     } else {
-      myDropdownPopup.setLocation(prefferedBounds.getLocation());
-      myDropdownPopup.setSize(prefferedBounds.getSize());
+      myDropdownPopup.setLocation(preferredBounds.getLocation());
+
+      // in 'focus follows mouse' mode, to avoid focus escaping to editor, don't reduce popup size when list size is reduced
+      final Dimension currentSize = myDropdownPopup.getSize();
+      if (UISettings.getInstance().HIDE_NAVIGATION_ON_FOCUS_LOSS ||
+          preferredBounds.width > currentSize.width || preferredBounds.height > currentSize.height) {
+        myDropdownPopup.setSize(preferredBounds.getSize());
+      }
     }
   }
 
index 7251f701a0b987926c1db9a8bf30e28f5e5c75bb..1d38a7df7ac9906c1928ed920890742468cd2c2b 100644 (file)
@@ -86,7 +86,7 @@ public class PlatformContentEntriesConfigurable implements Configurable {
   }
 
   public boolean isModified() {
-    return myEditor.isModified();
+    return myEditor != null && myEditor.isModified();
   }
 
   public void apply() throws ConfigurationException {
index 9b71e4757b8f0a113ce1fa3e88dca94126c5c630..83fbc587b7399b3619fce0493c572488f3573f51 100644 (file)
@@ -34,6 +34,7 @@ import com.intellij.openapi.util.text.StringUtil;
 import com.intellij.projectImport.ProjectAttachProcessor;
 import com.intellij.util.ArrayUtil;
 import com.intellij.util.Function;
+import com.intellij.util.PlatformUtils;
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
 
@@ -51,7 +52,7 @@ public class ModuleDeleteProvider  implements DeleteProvider, TitledHandler  {
 
   private static boolean isPrimaryModule(Module[] modules) {
     if (!ProjectAttachProcessor.canAttachToProject()) {
-      return false;
+      return !PlatformUtils.isIdea();
     }
     for (Module module : modules) {
       final File moduleFile = new File(module.getModuleFilePath());
index db345b26cf9ad003d4c5801c84e0935a1d20290a..e241dad57b2dabe34d52481f0e61a4ce76ee8043 100644 (file)
@@ -311,6 +311,7 @@ public class RenameUtil {
 
     for (Document document : docsToOffsetsMap.keySet()) {
       List<UsageOffset> list = docsToOffsetsMap.get(document);
+      LOG.assertTrue(list != null, document);
       UsageOffset[] offsets = list.toArray(new UsageOffset[list.size()]);
       Arrays.sort(offsets);
 
index 10ef147a0e38bda495b9710b4b5899ede6f1865a..920ccaba4933aa8cd7f817cd1325ad6f26947a8b 100644 (file)
@@ -357,7 +357,9 @@ public class FileBasedIndex implements ApplicationComponent {
   }
 
   /**
-   * @return true if registered index requires full rebuild for some reason, e.g. is just created or corrupted @param extension
+   * @return true if registered index requires full rebuild for some reason, e.g. is just created or corrupted
+   *
+   * @param extension
    * @param isCurrentVersionCorrupted
    */
   private <K, V> boolean registerIndexer(final FileBasedIndexExtension<K, V> extension, final boolean isCurrentVersionCorrupted) throws IOException {
@@ -424,7 +426,7 @@ public class FileBasedIndex implements ApplicationComponent {
     }
   }
 
-  private static Set<String> readRegistsredIndexNames() {
+  private static Set<String> readRegisteredIndexNames() {
     final Set<String> result = new HashSet<String>();
     try {
       final DataInputStream in = new DataInputStream(new BufferedInputStream(new FileInputStream(getRegisteredIndicesFile())));
@@ -519,7 +521,7 @@ public class FileBasedIndex implements ApplicationComponent {
     // Important! Update IdToDataKeysIndex depending on the sate of "buffering" flag from the MemoryStorage.
     // If buffering is on, all changes should be done in memory (similar to the way it is done in memory storage).
     // Otherwise data in IdToDataKeysIndex will not be in sync with the 'main' data in the index on disk and index updates will be based on the
-    // wrong sets of keys for the given file. This will lead to unpretictable results in main index because it will not be
+    // wrong sets of keys for the given file. This will lead to unpredictable results in main index because it will not be
     // cleared properly before updating (removed data will still be present on disk). See IDEA-52223 for illustration of possible effects.
 
     final PersistentHashMap<Integer, Collection<K>> map = new PersistentHashMap<Integer, Collection<K>>(
@@ -653,7 +655,7 @@ public class FileBasedIndex implements ApplicationComponent {
   }
 
   /**
-   * @param project it is guaranteeed to return data which is up-to-date withing the project
+   * @param project it is guaranteed to return data which is up-to-date withing the project
    * Keys obtained from the files which do not belong to the project specified may not be up-to-date or even exist
    */
   @NotNull
@@ -664,7 +666,7 @@ public class FileBasedIndex implements ApplicationComponent {
   }
 
   /**
-   * @param project it is guaranteeed to return data which is up-to-date withing the project
+   * @param project it is guaranteed to return data which is up-to-date withing the project
    * Keys obtained from the files which do not belong to the project specified may not be up-to-date or even exist
    */
   public <K> boolean processAllKeys(final ID<K, ?> indexId, Processor<K> processor, @Nullable Project project) {
@@ -1407,7 +1409,7 @@ public class FileBasedIndex implements ApplicationComponent {
   }
 
   private void dropUnregisteredIndices() {
-    final Set<String> indicesToDrop = readRegistsredIndexNames();
+    final Set<String> indicesToDrop = readRegisteredIndexNames();
     for (ID<?, ?> key : myIndices.keySet()) {
       indicesToDrop.remove(key.toString());
     }
index 4d39ef8cec918f121012464cfdc7583822162980..2e21403db49bfe0598c71cb556c502168a309ce3 100644 (file)
@@ -380,7 +380,7 @@ public class AbstractTreeUi {
         UIUtil.invokeLaterIfNeeded(actual);
       }
     }
-    
+
     return result;
   }
 
@@ -836,14 +836,14 @@ public class AbstractTreeUi {
         if (edt) {
           final Ref<Boolean> changes = new Ref<Boolean>(false);
           queueToBackground(new Runnable() {
-            public void run() {
-              changes.set(_update(nodeDescriptor));
-            }
-          }, new Runnable() {
-            public void run() {
-              result.setDone(changes.get());
-            }
-          }, nodeDescriptor);
+                              public void run() {
+                                changes.set(_update(nodeDescriptor));
+                              }
+                            }, new Runnable() {
+                              public void run() {
+                                result.setDone(changes.get());
+                              }
+                            }, nodeDescriptor);
         }
         else {
           result.setDone(_update(nodeDescriptor));
@@ -1061,18 +1061,18 @@ public class AbstractTreeUi {
           if (descriptor != null) {
             DefaultMutableTreeNode node = (DefaultMutableTreeNode)path.getLastPathComponent();
             maybeYeild(new ActiveRunnable() {
-                @Override
-                public ActionCallback run() {
-                  ActionCallback result = new ActionCallback();
-                  update(descriptor, false).doWhenDone(new Runnable() {
-                    @Override
-                    public void run() {
-                      updateRow(row + 1, pass);
-                    }
-                  }).notify(result);
-                  return result;
-                }
-              }, pass, node);
+              @Override
+              public ActionCallback run() {
+                ActionCallback result = new ActionCallback();
+                update(descriptor, false).doWhenDone(new Runnable() {
+                  @Override
+                  public void run() {
+                    updateRow(row + 1, pass);
+                  }
+                }).notify(result);
+                return result;
+              }
+            }, pass, node);
           }
         }
       }
@@ -1755,7 +1755,7 @@ public class AbstractTreeUi {
       if (!isReleased()) {
         setCancelRequested(true);
         resetToReady();
-      } 
+      }
       throw e;
     }
   }
@@ -2121,8 +2121,8 @@ public class AbstractTreeUi {
 
 
     List<Object> children = preloadedChildren != null
-                    ? preloadedChildren.getElements()
-                    : Arrays.asList(getChildrenFor(element));
+                            ? preloadedChildren.getElements()
+                            : Arrays.asList(getChildrenFor(element));
     int index = 0;
     for (Object child : children) {
       if (!isValid(child)) continue;
@@ -2362,7 +2362,7 @@ public class AbstractTreeUi {
 
     final ActionCallback done = new ActionCallback();
 
-    final Runnable cancelUpdate = new Runnable() {
+    invokeLaterIfNeeded(new Runnable() {
       public void run() {
         if (isReleased()) {
           done.setRejected();
@@ -2371,29 +2371,21 @@ public class AbstractTreeUi {
 
         if (myResettingToReadyNow.get()) {
           _getReady().notify(done);
-        }
-        else if (isReady()) {
+        } else if (isReady()) {
           resetToReadyNow();
           done.setDone();
-        }
-        else {
+        } else {
           if (isIdle() && hasPendingWork()) {
             resetToReadyNow();
             done.setDone();
-          }
-          else {
+          } else {
             _getReady().notify(done);
           }
         }
 
         maybeReady();
       }
-    };
-    if (ApplicationManager.getApplication().isUnitTestMode() && isEdt()) {
-      cancelUpdate.run();
-    } else {
-      invokeLaterIfNeeded(cancelUpdate, false);
-    }
+    }, false);
 
     if (isEdt() || isPassthroughMode()) {
       maybeReady();
@@ -3621,7 +3613,7 @@ public class AbstractTreeUi {
   }
 
   public boolean addSubtreeToUpdate(final DefaultMutableTreeNode root, final Runnable runAfterUpdate, final boolean updateStructure) {
-  Object element = getElementFor(root);
+    Object element = getElementFor(root);
     if (element != null && getTreeStructure().isAlwaysLeaf(element)) {
       removeFromUnbuilt(root);
       removeLoading(root, true);
@@ -3688,7 +3680,7 @@ public class AbstractTreeUi {
   }
 
   public void userSelect(final Object[] elements, final Runnable onDone, final boolean addToSelection, boolean scroll) {
-    _select(elements, onDone, addToSelection, true, false, scroll, false, true, !ApplicationManager.getApplication().isUnitTestMode() && !isEdt());
+    _select(elements, onDone, addToSelection, true, false, scroll, false, true, true);
   }
 
   void _select(final Object[] elements,
similarity index 84%
rename from platform/platform-api/src/com/intellij/openapi/actionSystem/KeyboardModifierGestureShortuct.java
rename to platform/platform-api/src/com/intellij/openapi/actionSystem/KeyboardModifierGestureShortcut.java
index 03a78793101f40971118c4b8fd22cdc1138fa510..9f607cee4c30866175309bc297a54a8bd1063997 100644 (file)
@@ -17,7 +17,7 @@ package com.intellij.openapi.actionSystem;
 
 import javax.swing.*;
 
-public class KeyboardModifierGestureShortuct extends Shortcut {
+public class KeyboardModifierGestureShortcut extends Shortcut {
 
   private final KeyStroke myStroke;
   private final KeyboardGestureAction.ModifierType myType;
@@ -33,7 +33,7 @@ public class KeyboardModifierGestureShortuct extends Shortcut {
     throw new IllegalArgumentException(type.toString());
   }
 
-  protected KeyboardModifierGestureShortuct(final KeyStroke stroke, KeyboardGestureAction.ModifierType type) {
+  protected KeyboardModifierGestureShortcut(final KeyStroke stroke, KeyboardGestureAction.ModifierType type) {
     myStroke = stroke;
     myType = type;
   }
@@ -51,9 +51,9 @@ public class KeyboardModifierGestureShortuct extends Shortcut {
   }
 
   public boolean startsWith(final Shortcut sc) {
-    if (!(sc instanceof KeyboardModifierGestureShortuct)) return false;
+    if (!(sc instanceof KeyboardModifierGestureShortcut)) return false;
 
-    final KeyboardModifierGestureShortuct other = (KeyboardModifierGestureShortuct)sc;
+    final KeyboardModifierGestureShortcut other = (KeyboardModifierGestureShortcut)sc;
     if (myType.equals(other.myType)) {
       if (myStroke.getModifiers() != other.myStroke.getModifiers()) return false;
       return other.myStroke.getKeyCode() != -1 || other.myStroke.getKeyCode() == myStroke.getKeyCode();
@@ -67,7 +67,7 @@ public class KeyboardModifierGestureShortuct extends Shortcut {
     if (this == o) return true;
     if (o == null || getClass() != o.getClass()) return false;
 
-    final KeyboardModifierGestureShortuct that = (KeyboardModifierGestureShortuct)o;
+    final KeyboardModifierGestureShortcut that = (KeyboardModifierGestureShortcut)o;
 
     if (myStroke != null ? !myStroke.equals(that.myStroke) : that.myStroke != null) return false;
     if (myType != that.myType) return false;
@@ -83,13 +83,13 @@ public class KeyboardModifierGestureShortuct extends Shortcut {
     return result;
   }
 
-  public static class DblClick extends KeyboardModifierGestureShortuct {
+  public static class DblClick extends KeyboardModifierGestureShortcut {
     public DblClick(final KeyStroke stroke) {
       super(stroke, KeyboardGestureAction.ModifierType.dblClick);
     }
   }
 
-  public static class Hold extends KeyboardModifierGestureShortuct {
+  public static class Hold extends KeyboardModifierGestureShortcut {
     public Hold(final KeyStroke stroke) {
       super(stroke, KeyboardGestureAction.ModifierType.hold);
     }
index b64f0c369cbb558ca24fa08860f8b5bf5d5ec331..f835adb1faae17982c7b4d732d9214e16ee6e96d 100644 (file)
@@ -84,6 +84,11 @@ public class KeymapUtil {
       MouseShortcut mouseShortcut = (MouseShortcut)shortcut;
       s = getMouseShortcutText(mouseShortcut.getButton(), mouseShortcut.getModifiers(), mouseShortcut.getClickCount());
     }
+    else if (shortcut instanceof KeyboardModifierGestureShortcut) {
+      final KeyboardModifierGestureShortcut gestureShortcut = (KeyboardModifierGestureShortcut)shortcut;
+      s = gestureShortcut.getType() == KeyboardGestureAction.ModifierType.dblClick ? "Press, release and hold " : "Hold ";
+      s += getKeystrokeText(gestureShortcut.getStroke());
+    }
     else {
       throw new IllegalArgumentException("unknown shortcut class: " + shortcut.getClass().getCanonicalName());
     }
index 22ae559d18edc28461f99ca47948b20cb9aaac72..ad8ba71f2c43b96f5644d5f3518a13da728c6d89 100644 (file)
@@ -51,8 +51,8 @@ public class LoadingDecorator {
 
 
     myFadeOutAnimator = new Animator("Loading", 10, 500, false) {
-      public void paintNow(final float frame, final float totalFrames, final float cycle) {
-        myLoadingLayer.setAlpha(1f - frame / totalFrames);
+      public void paintNow(final int frame, final int totalFrames, final int cycle) {
+        myLoadingLayer.setAlpha(1f - ((float)frame) / ((float)totalFrames));
       }
 
       @Override
index 5f91404727ea2cd744e22eef6d7f972ac2f5d513..575cd184e352c5f61208eac98c9b1f0dd0bd269f 100644 (file)
@@ -386,7 +386,7 @@ public class Messages {
 
 
   public static int showTwoStepConfirmationDialog(String message, String title, String checkboxText, Icon icon) {
-    return showCheckboxMessageDialog(message, title, new String[]{OK_BUTTON, CANCEL_BUTTON}, checkboxText, true, -1, -1, icon, null);
+    return showCheckboxMessageDialog(message, title, new String[]{OK_BUTTON}, checkboxText, true, -1, -1, icon, null);
   }
 
   public static void showErrorDialog(Project project, @Nls String message, @Nls String title) {
index bd5de74ad0bd66c0bb2798209aaa949b3d91a869..71783fc6918ff0e8fc6fc116b08a6d31736a97e9 100644 (file)
@@ -233,7 +233,7 @@ public class JBTabsImpl extends JComponent
     });
 
     myAnimator = new Animator("JBTabs Attractions", 2, 500, true) {
-      public void paintNow(final float frame, final float totalFrames, final float cycle) {
+      public void paintNow(final int frame, final int totalFrames, final int cycle) {
         repaintAttractions();
       }
     };
index 30ba39ec503326d07307f1ca6ad30c63e2014fda..84e2502da2393b8bd43d47a9791ff47309d16802 100644 (file)
 package com.intellij.util.ui;
 
 import com.intellij.openapi.Disposable;
+import com.intellij.openapi.util.Disposer;
 
 import javax.swing.*;
 import java.awt.*;
 
-public abstract class AnimatedIcon extends JComponent implements Disposable {
-
-  private Icon[] myIcons;
-  private Dimension myPrefSize = new Dimension();
+/**
+ * @author Kirill Kalishev
+ * @author Konstantin Bulenkov
+ */
+public class AnimatedIcon extends JComponent implements Disposable {
+  private final Icon[] myIcons;
+  private final Dimension myPrefSize = new Dimension();
 
+  //no need to make it volatile, all r/w operations are from EDT
   private int myCurrentIconIndex;
 
-  private Icon myPassiveIcon;
+  private final Icon myPassiveIcon;
+  private final Icon myEmptyPassiveIcon;
 
-  private Icon myEmptyPassiveIcon;
   private boolean myPaintPassive = true;
-
   private boolean myRunning = true;
 
-  protected Animator myAnimator;
+  protected final Animator myAnimator;
 
   private final String myName;
 
-  private boolean myLastPaintWasRunning;
-  private boolean myPaintingBgNow;
+  //private boolean myPaintingBgNow;
 
-  protected AnimatedIcon(final String name) {
+  public AnimatedIcon(final String name, Icon[] icons, Icon passiveIcon, int cycleLength) {
     myName = name;
-  }
-
-  protected final void init(Icon[] icons, Icon passiveIcon, int cycleLength) {
-    myIcons = icons;
+    myIcons = icons.length == 0 ? new Icon[]{passiveIcon} : icons;
     myPassiveIcon = passiveIcon;
 
-    myPrefSize = new Dimension();
     for (Icon each : icons) {
       myPrefSize.width = Math.max(each.getIconWidth(), myPrefSize.width);
       myPrefSize.height = Math.max(each.getIconHeight(), myPrefSize.height);
@@ -62,16 +61,9 @@ public abstract class AnimatedIcon extends JComponent implements Disposable {
     UIUtil.removeQuaquaVisualMarginsIn(this);
 
     myAnimator = new Animator(myName, icons.length, cycleLength, true) {
-      public void paintNow(final float frame, final float totalFrames, final float cycle) {
-        if (frame < 0) {
-          myCurrentIconIndex = 0;
-        }
-        else if (frame >= myIcons.length) {
-          myCurrentIconIndex = myIcons.length-1;
-        }
-        else {
-          myCurrentIconIndex = (int)frame;
-        }
+      public void paintNow(final int frame, final int totalFrames, final int cycle) {
+        final int len = myIcons.length;
+        myCurrentIconIndex = frame < 0 ? 0 : frame >= len ? len - 1 : frame;
         paintImmediately(0, 0, getWidth(), getHeight());
       }
     };
@@ -126,7 +118,7 @@ public abstract class AnimatedIcon extends JComponent implements Disposable {
   }
 
   public void dispose() {
-    myAnimator.dispose();
+    Disposer.dispose(myAnimator);
   }
 
   public Dimension getPreferredSize() {
@@ -143,7 +135,7 @@ public abstract class AnimatedIcon extends JComponent implements Disposable {
   }
 
   protected void paintComponent(Graphics g) {
-    if (myPaintingBgNow) return;
+    //if (myPaintingBgNow) return;
 
     if (isOpaque()) {
       final Container parent = getParent();
@@ -170,7 +162,7 @@ public abstract class AnimatedIcon extends JComponent implements Disposable {
 
     paintIcon(g, icon, x, y);
 
-    myLastPaintWasRunning = myAnimator.isRunning();
+    //boolean lastPaintWasRunning = myAnimator.isRunning();
   }
 
   protected void paintIcon(Graphics g, Icon icon, int x, int y) {
index 6e84478341aa94d071cce44af69e1ad12885c2e8..b57ddfc929a621aa3582cbbffd1a38fbf7afb7ba 100644 (file)
@@ -157,7 +157,7 @@ public abstract class Animator implements Disposable {
     }
   }
 
-  public abstract void paintNow(float frame, final float totalFrames, final float cycle);
+  public abstract void paintNow(int frame, int totalFrames, int cycle);
 
   public void dispose() {
     myDisposed = true;
index 3b3881b00b429a5fe5474730a29944ff2d2737ea..6e8a74b756c51e120c0d14c8ab3201c0b411b494 100644 (file)
@@ -36,10 +36,7 @@ public class AsyncProcessIcon extends AnimatedIcon {
   }
 
   private AsyncProcessIcon(@NonNls String name, Icon[] icons, Icon passive) {
-    super(name);
-
-    init(icons, passive, CYCLE_LENGTH);
-
+    super(name, icons, passive, CYCLE_LENGTH);
     setUseMask(false);
   }
 
index 749087defb2e283caf4f7d583db8a1dcbf033e2c..9abc1de863f095fe682101066737d23c7b472619 100644 (file)
@@ -56,7 +56,7 @@ public class ButtonlessScrollBarUI extends BasicScrollBarUI {
     final int framesCount = 10 + delayFrames;
     myAnimator = new Animator("Adjustment fadeout", framesCount, framesCount * 50, false) {
       @Override
-      public void paintNow(float frame, float totalFrames, float cycle) {
+      public void paintNow(int frame, int totalFrames, int cycle) {
         myAnimationColorShift = 40;
         if (frame > delayFrames) {
           myAnimationColorShift *= 1 - (frame - delayFrames) / (totalFrames - delayFrames);
index 0df420a41ed8ae476767f5a287429a5971e80c6a..8cc2d97de28b0845556e28b5ccbd817dfbf56b46 100644 (file)
@@ -30,7 +30,6 @@ import com.intellij.util.Range;
 import com.intellij.util.ui.UIUtil;
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
-import org.omg.PortableInterceptor.SYSTEM_EXCEPTION;
 
 import javax.swing.*;
 import javax.swing.plaf.basic.BasicTreeUI;
@@ -43,7 +42,7 @@ import java.util.List;
 
 public final class TreeUtil {
   private static final Logger LOG = Logger.getInstance("#com.intellij.util.ui.tree.TreeUtil");
-  private static final String TREE_UTIL_SCROLL_TIME_STAMP = "TreeUtil.scrollTimeStamp";
+  @NotNull private static final String TREE_UTIL_SCROLL_TIME_STAMP = "TreeUtil.scrollTimeStamp";
 
   private TreeUtil() {}
 
@@ -59,6 +58,7 @@ public final class TreeUtil {
     collectExpandedPathsImpl(tree, paths, new TreePath(root));
   }
 
+  @NotNull
   public static List<TreePath> collectExpandedPaths(@NotNull final JTree tree){
     final ArrayList<TreePath> result = new ArrayList<TreePath>();
     final Object root = tree.getModel().getRoot();
@@ -68,7 +68,7 @@ public final class TreeUtil {
   }
 
   @NotNull
-  public static <T> List<T> collectSelectedObjectsOfType(JTree tree, Class<T> clazz) {
+  public static <T> List<T> collectSelectedObjectsOfType(@NotNull JTree tree, @NotNull Class<T> clazz) {
     final TreePath[] selections = tree.getSelectionPaths();
     if (selections != null) {
       final ArrayList<T> result = new ArrayList<T>();
@@ -86,7 +86,8 @@ public final class TreeUtil {
 
   }
 
-  public static List<TreePath> collectExpandedPaths(final JTree tree, TreePath path){
+  @NotNull
+  public static List<TreePath> collectExpandedPaths(@NotNull final JTree tree, @NotNull TreePath path){
     final ArrayList<TreePath> result = new ArrayList<TreePath>();
     if (!tree.isExpanded(path)) return result;
     final Object lastPathComponent = path.getLastPathComponent();
@@ -117,7 +118,7 @@ public final class TreeUtil {
     return result;
   }
 
-  private static boolean collectExpandedPathsImpl(final JTree tree, final Collection<TreePath> paths, final TreePath path){
+  private static boolean collectExpandedPathsImpl(@NotNull final JTree tree, @NotNull final Collection<TreePath> paths, @NotNull final TreePath path){
     final TreeModel model = tree.getModel();
     final Object lastPathComponent = path.getLastPathComponent();
     if(model.isLeaf(lastPathComponent)){
@@ -150,7 +151,8 @@ public final class TreeUtil {
     }
   }
 
-  public static TreePath getPath(final TreeNode aRootNode, final TreeNode aNode) {
+  @NotNull
+  public static TreePath getPath(final TreeNode aRootNode, @NotNull final TreeNode aNode) {
     final List<TreeNode> pathStack = new ArrayList<TreeNode>();
     addEach(aRootNode, aNode, pathStack);
 
@@ -172,20 +174,21 @@ public final class TreeUtil {
     return false;
   }
 
-  private static boolean isAncestor(final TreePath ancestor, final TreePath path) {
+  private static boolean isAncestor(@NotNull final TreePath ancestor, @NotNull final TreePath path) {
     if (path.getPathCount() < ancestor.getPathCount()) return false;
     for (int i = 0; i < ancestor.getPathCount(); i++)
       if (!path.getPathComponent(i).equals(ancestor.getPathComponent(i))) return false;
     return true;
   }
 
-  private static boolean isDescendants(final TreePath path, final TreePath[] paths) {
+  private static boolean isDescendants(@NotNull final TreePath path, @NotNull final TreePath[] paths) {
     for (final TreePath ancestor : paths) {
       if (isAncestor(ancestor, path)) return true;
     }
     return false;
   }
 
+  @NotNull
   public static TreePath getPathFromRoot(TreeNode node) {
     final ArrayList<TreeNode> path = new ArrayList<TreeNode>();
     do {
@@ -197,7 +200,7 @@ public final class TreeUtil {
   }
 
   @Nullable
-  public static TreeNode findNodeWithObject(final Object object, final TreeModel model, final Object parent) {
+  public static TreeNode findNodeWithObject(final Object object, @NotNull final TreeModel model, final Object parent) {
     for (int i = 0; i < model.getChildCount(parent); i++) {
       final DefaultMutableTreeNode childNode = (DefaultMutableTreeNode) model.getChild(parent, i);
       if (childNode.getUserObject().equals(object)) return childNode;
@@ -220,7 +223,7 @@ public final class TreeUtil {
   }
 
   @Nullable
-  public static DefaultMutableTreeNode findNodeWithObject(final DefaultMutableTreeNode aRoot, final Object aObject) {
+  public static DefaultMutableTreeNode findNodeWithObject(@NotNull final DefaultMutableTreeNode aRoot, final Object aObject) {
     if (Comparing.equal(aRoot.getUserObject(), aObject)) {
       return aRoot;
     } else {
@@ -234,7 +237,8 @@ public final class TreeUtil {
     }
   }
 
-  public static TreePath findCommonPath(final TreePath[] treePaths) {
+  @NotNull
+  public static TreePath findCommonPath(@NotNull final TreePath[] treePaths) {
     LOG.assertTrue(areComponentsEqual(treePaths, 0));
     TreePath result = new TreePath(treePaths[0].getPathComponent(0));
     int pathIndex = 1;
@@ -245,16 +249,24 @@ public final class TreeUtil {
     return result;
   }
 
-  public static ActionCallback selectFirstNode(final JTree tree) {
+  @NotNull
+  public static ActionCallback selectFirstNode(@NotNull JTree tree) {
+    TreePath selectionPath = getFirstNodePath(tree);
+    return selectPath(tree, selectionPath);
+  }
+
+  @NotNull
+  public static TreePath getFirstNodePath(@NotNull JTree tree) {
     final TreeModel model = tree.getModel();
     final Object root = model.getRoot();
     TreePath selectionPath = new TreePath(root);
-    if (!tree.isRootVisible() && model.getChildCount(root) > 0)
+    if (!tree.isRootVisible() && model.getChildCount(root) > 0) {
       selectionPath = selectionPath.pathByAddingChild(model.getChild(root, 0));
-    return selectPath(tree, selectionPath);
+    }
+    return selectionPath;
   }
 
-  private static void addEach(final TreeNode aRootNode, final TreeNode aNode, final List<TreeNode> aPathStack) {
+  private static void addEach(final TreeNode aRootNode, @NotNull final TreeNode aNode, @NotNull final List<TreeNode> aPathStack) {
     aPathStack.add(aNode);
 
     if (aNode != aRootNode) {
@@ -262,7 +274,8 @@ public final class TreeUtil {
     }
   }
 
-  private static IndexTreePathState removeLastPathComponent(final DefaultTreeModel model, final TreePath pathToBeRemoved) {
+  @NotNull
+  private static IndexTreePathState removeLastPathComponent(@NotNull final DefaultTreeModel model, @NotNull final TreePath pathToBeRemoved) {
     final IndexTreePathState selectionState = new IndexTreePathState(pathToBeRemoved);
     if (((MutableTreeNode) pathToBeRemoved.getLastPathComponent()).getParent() == null) return selectionState;
     model.removeNodeFromParent((MutableTreeNode) pathToBeRemoved.getLastPathComponent());
@@ -270,7 +283,7 @@ public final class TreeUtil {
   }
 
 
-  private static boolean areComponentsEqual(final TreePath[] paths, final int componentIndex) {
+  private static boolean areComponentsEqual(@NotNull final TreePath[] paths, final int componentIndex) {
     if (paths[0].getPathCount() <= componentIndex) return false;
     final Object pathComponent = paths[0].getPathComponent(componentIndex);
     for (final TreePath treePath : paths) {
@@ -280,7 +293,8 @@ public final class TreeUtil {
     return true;
   }
 
-  private static TreePath[] removeDuplicates(final TreePath[] paths) {
+  @NotNull
+  private static TreePath[] removeDuplicates(@NotNull final TreePath[] paths) {
     final ArrayList<TreePath> result = new ArrayList<TreePath>();
     for (final TreePath path : paths) {
       if (!result.contains(path)) result.add(path);
@@ -288,7 +302,8 @@ public final class TreeUtil {
     return result.toArray(new TreePath[result.size()]);
   }
 
-  public static TreePath[] selectMaximals(final TreePath[] paths) {
+  @NotNull
+  public static TreePath[] selectMaximals(@Nullable final TreePath[] paths) {
     if (paths == null) return new TreePath[0];
     final TreePath[] noDuplicates = removeDuplicates(paths);
     final ArrayList<TreePath> result = new ArrayList<TreePath>();
@@ -300,11 +315,11 @@ public final class TreeUtil {
     return result.toArray(new TreePath[result.size()]);
   }
 
-  public static void sort(final DefaultTreeModel model, final Comparator comparator) {
+  public static void sort(@NotNull final DefaultTreeModel model, final Comparator comparator) {
     sort((DefaultMutableTreeNode) model.getRoot(), comparator);
   }
 
-  public static void sort(final DefaultMutableTreeNode node, final Comparator comparator) {
+  public static void sort(@NotNull final DefaultMutableTreeNode node, final Comparator comparator) {
     final List<TreeNode> children = childrenToArray(node);
     Collections.sort(children, comparator);
     node.removeAllChildren();
@@ -314,14 +329,14 @@ public final class TreeUtil {
     }
   }
 
-  public static void addChildrenTo(final MutableTreeNode node, final List<TreeNode> children) {
+  public static void addChildrenTo(@NotNull final MutableTreeNode node, @NotNull final List<TreeNode> children) {
     for (final Object aChildren : children) {
       final MutableTreeNode child = (MutableTreeNode)aChildren;
       node.insert(child, node.getChildCount());
     }
   }
 
-  public static boolean traverse(final TreeNode node, final Traverse traverse) {
+  public static boolean traverse(@NotNull final TreeNode node, @NotNull final Traverse traverse) {
     final int childCount = node.getChildCount();
     for (int i = 0; i < childCount; i++){
       if (!traverse(node.getChildAt(i), traverse)) return false;
@@ -329,7 +344,7 @@ public final class TreeUtil {
     return traverse.accept(node);
   }
 
-  public static boolean traverseDepth(final TreeNode node, final Traverse traverse) {
+  public static boolean traverseDepth(@NotNull final TreeNode node, @NotNull final Traverse traverse) {
     if (!traverse.accept(node)) return false;
     final int childCount = node.getChildCount();
     for (int i = 0; i < childCount; i++)
@@ -337,11 +352,13 @@ public final class TreeUtil {
     return true;
   }
 
-  public static ActionCallback selectPath(final JTree tree, final TreePath path) {
+  @NotNull
+  public static ActionCallback selectPath(@NotNull final JTree tree, final TreePath path) {
     return selectPath(tree, path, true);
   }
 
-  public static ActionCallback selectPath(final JTree tree, final TreePath path, boolean center) {
+  @NotNull
+  public static ActionCallback selectPath(@NotNull final JTree tree, final TreePath path, boolean center) {
     tree.makeVisible(path);
     if (center) {
       return showRowCentred(tree, tree.getRowForPath(path));
@@ -351,7 +368,8 @@ public final class TreeUtil {
     }
   }
 
-  public static ActionCallback moveDown(final JTree tree) {
+  @NotNull
+  public static ActionCallback moveDown(@NotNull final JTree tree) {
     final int size = tree.getRowCount();
     int row = tree.getLeadSelectionRow();
     if (row < size - 1) {
@@ -362,7 +380,8 @@ public final class TreeUtil {
     }
   }
 
-  public static ActionCallback moveUp(final JTree tree) {
+  @NotNull
+  public static ActionCallback moveUp(@NotNull final JTree tree) {
     int row = tree.getLeadSelectionRow();
     if (row > 0) {
       row--;
@@ -372,7 +391,8 @@ public final class TreeUtil {
     }
   }
 
-  public static ActionCallback movePageUp(final JTree tree) {
+  @NotNull
+  public static ActionCallback movePageUp(@NotNull final JTree tree) {
     final int visible = getVisibleRowCount(tree);
     if (visible <= 0){
       return moveHome(tree);
@@ -384,7 +404,8 @@ public final class TreeUtil {
     return showAndSelect(tree, top, bottom, row, getSelectedRow(tree));
   }
 
-  public static ActionCallback movePageDown(final JTree tree) {
+  @NotNull
+  public static ActionCallback movePageDown(@NotNull final JTree tree) {
     final int visible = getVisibleRowCount(tree);
     if (visible <= 0){
       return moveEnd(tree);
@@ -397,23 +418,28 @@ public final class TreeUtil {
     return showAndSelect(tree, top, bottom, index, getSelectedRow(tree));
   }
 
-  private static ActionCallback moveHome(final JTree tree) {
+  @NotNull
+  private static ActionCallback moveHome(@NotNull final JTree tree) {
     return showRowCentred(tree, 0);
   }
 
-  private static ActionCallback moveEnd(final JTree tree) {
+  @NotNull
+  private static ActionCallback moveEnd(@NotNull final JTree tree) {
     return showRowCentred(tree, tree.getRowCount() - 1);
   }
 
-  private static ActionCallback showRowCentred(final JTree tree, final int row) {
+  @NotNull
+  private static ActionCallback showRowCentred(@NotNull final JTree tree, final int row) {
     return showRowCentered(tree, row, true);
   }
 
-  public static ActionCallback showRowCentered(final JTree tree, final int row, final boolean centerHorizontally) {
+  @NotNull
+  public static ActionCallback showRowCentered(@NotNull final JTree tree, final int row, final boolean centerHorizontally) {
     return showRowCentered(tree, row, centerHorizontally, true);
   }
 
-  public static ActionCallback showRowCentered(final JTree tree, final int row, final boolean centerHorizontally, boolean scroll) {
+  @NotNull
+  public static ActionCallback showRowCentered(@NotNull final JTree tree, final int row, final boolean centerHorizontally, boolean scroll) {
     final int visible = getVisibleRowCount(tree);
 
     final int top = visible > 0 ? row - (visible - 1)/ 2 : row;
@@ -421,19 +447,23 @@ public final class TreeUtil {
     return showAndSelect(tree, top, bottom, row, -1, false, scroll, false);
   }
 
-  public static ActionCallback showAndSelect(final JTree tree, int top, int bottom, final int row, final int previous) {
+  @NotNull
+  public static ActionCallback showAndSelect(@NotNull final JTree tree, int top, int bottom, final int row, final int previous) {
     return showAndSelect(tree, top, bottom, row, previous, false);
   }
 
-  public static ActionCallback showAndSelect(final JTree tree, int top, int bottom, final int row, final int previous, boolean addToSelection) {
+  @NotNull
+  public static ActionCallback showAndSelect(@NotNull final JTree tree, int top, int bottom, final int row, final int previous, boolean addToSelection) {
     return showAndSelect(tree, top, bottom, row, previous, addToSelection, true, false);
   }
 
-  public static ActionCallback showAndSelect(final JTree tree, int top, int bottom, final int row, final int previous, final boolean addToSelection, final boolean scroll) {
+  @NotNull
+  public static ActionCallback showAndSelect(@NotNull final JTree tree, int top, int bottom, final int row, final int previous, final boolean addToSelection, final boolean scroll) {
     return showAndSelect(tree, top, bottom, row, previous, addToSelection, scroll, false);
   }
 
-  public static ActionCallback showAndSelect(final JTree tree, int top, int bottom, final int row, final int previous, final boolean addToSelection, final boolean scroll, final boolean resetSelection) {
+  @NotNull
+  public static ActionCallback showAndSelect(@NotNull final JTree tree, int top, int bottom, final int row, final int previous, final boolean addToSelection, final boolean scroll, final boolean resetSelection) {
     final TreePath path = tree.getPathForRow(row);
 
     if (path == null) return new ActionCallback.Done();
@@ -588,11 +618,11 @@ public final class TreeUtil {
 
 
   // this method returns FIRST selected row but not LEAD
-  private static int getSelectedRow(final JTree tree) {
+  private static int getSelectedRow(@NotNull final JTree tree) {
     return tree.getRowForPath(tree.getSelectionPath());
   }
 
-  private static int getFirstVisibleRow(final JTree tree) {
+  private static int getFirstVisibleRow(@NotNull final JTree tree) {
     final Rectangle visible = tree.getVisibleRect();
     int row = -1;
     for (int i=0; i < tree.getRowCount(); i++) {
@@ -605,7 +635,7 @@ public final class TreeUtil {
     return row;
   }
 
-  private static int getVisibleRowCount(final JTree tree) {
+  private static int getVisibleRowCount(@NotNull final JTree tree) {
     final Rectangle visible = tree.getVisibleRect();
 
     if (visible == null) return 0;
@@ -622,7 +652,7 @@ public final class TreeUtil {
   }
 
   @SuppressWarnings({"HardCodedStringLiteral"})
-  public static void installActions(final JTree tree) {
+  public static void installActions(@NotNull final JTree tree) {
     tree.getActionMap().put("scrollUpChangeSelection", new AbstractAction() {
       public void actionPerformed(final ActionEvent e) {
         movePageUp(tree);
@@ -655,14 +685,14 @@ public final class TreeUtil {
     UIUtil.maybeInstall(inputMap, "selectFirst", KeyStroke.getKeyStroke(KeyEvent.VK_HOME, 0));
   }
 
-  private static void copyAction(final JTree tree, String original, String copyTo) {
+  private static void copyAction(@NotNull final JTree tree, String original, String copyTo) {
     final Action action = tree.getActionMap().get(original);
     if (action != null) {
       tree.getActionMap().put(copyTo, action);
     }
   }
 
-  public static void collapseAll(final JTree tree, final int keepSelectionLevel) {
+  public static void collapseAll(@NotNull final JTree tree, final int keepSelectionLevel) {
     final TreePath leadSelectionPath = tree.getLeadSelectionPath();
     // Collapse all
     int row = tree.getRowCount() - 1;
@@ -681,11 +711,11 @@ public final class TreeUtil {
     }
   }
 
-  public static void selectNode(final JTree tree, final TreeNode node) {
+  public static void selectNode(@NotNull final JTree tree, final TreeNode node) {
     selectPath(tree, getPathFromRoot(node));
   }
 
-  public static void moveSelectedRow(final JTree tree, final int direction){
+  public static void moveSelectedRow(@NotNull final JTree tree, final int direction){
     final TreePath selectionPath = tree.getSelectionPath();
     final DefaultMutableTreeNode treeNode = (DefaultMutableTreeNode)selectionPath.getLastPathComponent();
     final DefaultMutableTreeNode parent = (DefaultMutableTreeNode)treeNode.getParent();
@@ -696,7 +726,8 @@ public final class TreeUtil {
     selectNode(tree, treeNode);
   }
 
-  public static ArrayList<TreeNode> childrenToArray(final TreeNode node) {
+  @NotNull
+  public static ArrayList<TreeNode> childrenToArray(@NotNull final TreeNode node) {
     final ArrayList<TreeNode> result = new ArrayList<TreeNode>();
     for(int i = 0; i < node.getChildCount(); i++){
       result.add(node.getChildAt(i));
@@ -704,7 +735,7 @@ public final class TreeUtil {
     return result;
   }
 
-  public static void expandRootChildIfOnlyOne(final JTree tree) {
+  public static void expandRootChildIfOnlyOne(@Nullable final JTree tree) {
     if (tree == null) return;
     final Runnable runnable = new Runnable() {
       public void run() {
@@ -719,7 +750,7 @@ public final class TreeUtil {
     UIUtil.invokeLaterIfNeeded(runnable);
   }
 
-  public static void expandAll(final JTree tree) {
+  public static void expandAll(@NotNull final JTree tree) {
     tree.expandPath(new TreePath(tree.getModel().getRoot()));
     int oldRowCount = 0;
     do {
@@ -738,11 +769,11 @@ public final class TreeUtil {
    * @param tree to expand nodes of
    * @param levels depths of the expantion
    */
-  public static void expand(JTree tree, int levels) {
+  public static void expand(@NotNull JTree tree, int levels) {
     expand(tree, new TreePath(tree.getModel().getRoot()), levels);
   }
 
-  private static void expand(JTree tree, TreePath path, int levels) {
+  private static void expand(@NotNull JTree tree, @NotNull TreePath path, int levels) {
     if (levels == 0) return;
     tree.expandPath(path);
     TreeNode node = (TreeNode)path.getLastPathComponent();
@@ -752,11 +783,13 @@ public final class TreeUtil {
     }
   }
 
-  public static ActionCallback selectInTree(DefaultMutableTreeNode node, boolean requestFocus, JTree tree) {
+  @NotNull
+  public static ActionCallback selectInTree(DefaultMutableTreeNode node, boolean requestFocus, @NotNull JTree tree) {
     return selectInTree(node, requestFocus, tree, true);
   }
 
-  public static ActionCallback selectInTree(DefaultMutableTreeNode node, boolean requestFocus, JTree tree, boolean center) {
+  @NotNull
+  public static ActionCallback selectInTree(@Nullable DefaultMutableTreeNode node, boolean requestFocus, @NotNull JTree tree, boolean center) {
     if (node == null) return new ActionCallback.Done();
 
     final TreePath treePath = new TreePath(node.getPath());
@@ -767,7 +800,8 @@ public final class TreeUtil {
     return selectPath(tree, treePath, center);
   }
 
-  public static ActionCallback selectInTree(Project project, DefaultMutableTreeNode node, boolean requestFocus, JTree tree, boolean center) {
+  @NotNull
+  public static ActionCallback selectInTree(Project project, @Nullable DefaultMutableTreeNode node, boolean requestFocus, @NotNull JTree tree, boolean center) {
     if (node == null) return new ActionCallback.Done();
 
     final TreePath treePath = new TreePath(node.getPath());
@@ -781,7 +815,8 @@ public final class TreeUtil {
     return selectPath(tree, treePath, center);
   }
 
-  public static List<TreePath> collectSelectedPaths(final JTree tree, final TreePath treePath) {
+  @NotNull
+  public static List<TreePath> collectSelectedPaths(@NotNull final JTree tree, @NotNull final TreePath treePath) {
     final ArrayList<TreePath> result = new ArrayList<TreePath>();
     final TreePath[] selections = tree.getSelectionPaths();
     if (selections != null) {
@@ -794,7 +829,7 @@ public final class TreeUtil {
     return result;
   }
 
-  public static void unselect(JTree tree, final DefaultMutableTreeNode node) {
+  public static void unselect(@NotNull JTree tree, @NotNull final DefaultMutableTreeNode node) {
     final TreePath rootPath = new TreePath(node.getPath());
     final TreePath[] selectionPaths = tree.getSelectionPaths();
     if (selectionPaths != null) {
@@ -807,7 +842,7 @@ public final class TreeUtil {
   }
 
   @Nullable
-  public static Range<Integer> getExpandControlRange(final JTree aTree, final TreePath path) {
+  public static Range<Integer> getExpandControlRange(@NotNull final JTree aTree, @Nullable final TreePath path) {
     TreeModel treeModel = aTree.getModel();
 
     final BasicTreeUI basicTreeUI = (BasicTreeUI)aTree.getUI();
@@ -843,7 +878,7 @@ public final class TreeUtil {
     return box;
   }
 
-  public static int getDepthOffset(JTree aTree) {
+  public static int getDepthOffset(@NotNull JTree aTree) {
     if (aTree.isRootVisible()) {
       if (aTree.getShowsRootHandles()) {
         return 1;
@@ -860,7 +895,8 @@ public final class TreeUtil {
     }
   }
 
-  public static RelativePoint getPointForSelection(JTree aTree) {
+  @NotNull
+  public static RelativePoint getPointForSelection(@NotNull JTree aTree) {
     final int[] rows = aTree.getSelectionRows();
     if (rows == null || rows.length == 0) {
       return RelativePoint.getCenterOf(aTree);
@@ -868,26 +904,29 @@ public final class TreeUtil {
     return getPointForRow(aTree, rows[rows.length - 1]);
   }
 
-  public static RelativePoint getPointForRow(JTree aTree, int aRow) {
+  @NotNull
+  public static RelativePoint getPointForRow(@NotNull JTree aTree, int aRow) {
     return getPointForPath(aTree, aTree.getPathForRow(aRow));
   }
 
-  public static RelativePoint getPointForPath(JTree aTree, TreePath path) {
+  @NotNull
+  public static RelativePoint getPointForPath(@NotNull JTree aTree, TreePath path) {
     final Rectangle rowBounds = aTree.getPathBounds(path);
     rowBounds.x += 20;
     return getPointForBounds(aTree, rowBounds);
   }
 
-  public static RelativePoint getPointForBounds(JComponent aComponent, final Rectangle aBounds) {
+  @NotNull
+  public static RelativePoint getPointForBounds(JComponent aComponent, @NotNull final Rectangle aBounds) {
     return new RelativePoint(aComponent, new Point(aBounds.x, (int)aBounds.getMaxY()));
   }
 
-  public static boolean isOverSelection(final JTree tree, final Point point) {
+  public static boolean isOverSelection(@NotNull final JTree tree, @NotNull final Point point) {
     TreePath path = tree.getPathForLocation(point.x, point.y);
     return path != null && tree.getSelectionModel().isPathSelected(path);
   }
 
-  public static void dropSelectionButUnderPoint(JTree tree, Point treePoint) {
+  public static void dropSelectionButUnderPoint(@NotNull JTree tree, @NotNull Point treePoint) {
     final TreePath toRetain = tree.getPathForLocation(treePoint.x, treePoint.y);
     if (toRetain == null) return;
 
@@ -903,7 +942,7 @@ public final class TreeUtil {
     boolean accept(Object node);
   }
 
-  public static void ensureSelection(JTree tree) {
+  public static void ensureSelection(@NotNull JTree tree) {
     final TreePath[] paths = tree.getSelectionPaths();
 
     if (paths != null) {
index 66d153f1639847409e7664c2993cb35ce55869d7..190f202cd05b33223828a2ad40b7d69ad51ff30f 100644 (file)
@@ -36,8 +36,10 @@ import com.intellij.openapi.ui.popup.JBPopupFactory;
 import com.intellij.openapi.ui.popup.LightweightWindowEvent;
 import com.intellij.openapi.util.*;
 import com.intellij.openapi.util.registry.Registry;
-import com.intellij.openapi.util.text.StringUtil;
-import com.intellij.openapi.wm.*;
+import com.intellij.openapi.wm.CustomStatusBarWidget;
+import com.intellij.openapi.wm.IdeFrame;
+import com.intellij.openapi.wm.StatusBar;
+import com.intellij.openapi.wm.WindowManager;
 import com.intellij.ui.awt.RelativePoint;
 import com.intellij.ui.components.panels.NonOpaquePanel;
 import com.intellij.util.Consumer;
@@ -50,9 +52,10 @@ import org.jetbrains.annotations.NonNls;
 import org.jetbrains.annotations.NotNull;
 
 import javax.swing.*;
-import javax.swing.border.LineBorder;
 import java.awt.*;
-import java.awt.event.*;
+import java.awt.event.InputEvent;
+import java.awt.event.KeyEvent;
+import java.awt.event.MouseEvent;
 import java.io.File;
 import java.util.*;
 import java.util.List;
@@ -176,16 +179,13 @@ public class ActionMacroManager implements ExportableApplicationComponent, Named
 
   private class Widget implements CustomStatusBarWidget, Consumer<MouseEvent> {
 
-    private AnimatedIcon myIcon = new AnimatedIcon("Macro recording") {
-      {
-        init(new Icon[] {
-          IconLoader.getIcon("/ide/macro/recording_1.png"),
-          IconLoader.getIcon("/ide/macro/recording_2.png"),
-          IconLoader.getIcon("/ide/macro/recording_3.png"),
-          IconLoader.getIcon("/ide/macro/recording_4.png")},
-             IconLoader.getIcon("/ide/macro/recording_1.png"), 1000);
-      }
-    };
+    private AnimatedIcon myIcon = new AnimatedIcon("Macro recording",
+                                                   new Icon[]{
+                                                     IconLoader.getIcon("/ide/macro/recording_1.png"),
+                                                     IconLoader.getIcon("/ide/macro/recording_2.png"),
+                                                     IconLoader.getIcon("/ide/macro/recording_3.png"),
+                                                     IconLoader.getIcon("/ide/macro/recording_4.png")},
+                                                   IconLoader.getIcon("/ide/macro/recording_1.png"), 1000);
     private StatusBar myStatusBar;
     private final WidgetPresentation myPresentation;
 
index 71fbd5c59a8026dd8d15e0a93fa2f92e9b906041..f249b52bb532b48b190e2f73b38a90317b7688b9 100644 (file)
@@ -34,7 +34,7 @@ public class BackAction extends AnAction implements DumbAware {
   public void update(AnActionEvent event){
     Presentation presentation = event.getPresentation();
     Project project = PlatformDataKeys.PROJECT.getData(event.getDataContext());
-    if (project == null) {
+    if (project == null || project.isDisposed()) {
       presentation.setEnabled(false);
       return;
     }
index 6bdd6407e1062ed31bbd15a768500f9f96855f03..17dedb17e0d6b05dc9be089ae6f8a1cdf38e6e5a 100644 (file)
@@ -34,7 +34,7 @@ public class ForwardAction extends AnAction implements DumbAware {
   public void update(AnActionEvent event){
     Presentation presentation = event.getPresentation();
     Project project = PlatformDataKeys.PROJECT.getData(event.getDataContext());
-    if (project == null) {
+    if (project == null || project.isDisposed()) {
       presentation.setEnabled(false);
       return;
     }
index 5fffa314c8085c00a435a9f457c0e6418a7c01ab..6c2ae03f25758bdd9d701f0d412db620a6ce8d8e 100644 (file)
@@ -448,7 +448,7 @@ public class ScrollingModelImpl implements ScrollingModelEx {
 
       myAnimator = new Animator("Animated scroller", myStepCount, SCROLL_DURATION, false, true) {
         @Override
-        public void paintNow(float frame, float totalFrames, float cycle) {
+        public void paintNow(int frame, int totalFrames, int cycle) {
           double time = (frame + 1) / (double)totalFrames;
           double fraction = timeToFraction(time);
 
index da276bf67f19bdce30901ba05dea790d9446aaa0..3441358e9575250caa91f412b5f542498e6cfda7 100644 (file)
@@ -87,7 +87,7 @@ public class KeymapImpl implements Keymap, ExternalizableScheme {
    * Don't use this field directly! Use it only through <code>getKeystroke2ListOfIds</code>.
    */
   private Map<KeyStroke, List<String>> myKeystroke2ListOfIds = null;
-  private Map<KeyboardModifierGestureShortuct, List<String>> myGesture2ListOfIds = null;
+  private Map<KeyboardModifierGestureShortcut, List<String>> myGesture2ListOfIds = null;
   // TODO[vova,anton] it should be final member
 
   /**
@@ -276,10 +276,10 @@ public class KeymapImpl implements Keymap, ExternalizableScheme {
     return myKeystroke2ListOfIds;
   }
 
-  private Map<KeyboardModifierGestureShortuct, List<String>> getGesture2ListOfIds() {
+  private Map<KeyboardModifierGestureShortcut, List<String>> getGesture2ListOfIds() {
     if (myGesture2ListOfIds == null) {
-      myGesture2ListOfIds = new THashMap<KeyboardModifierGestureShortuct, List<String>>();
-      fillShortcut2ListOfIds(myGesture2ListOfIds, KeyboardModifierGestureShortuct.class);
+      myGesture2ListOfIds = new THashMap<KeyboardModifierGestureShortcut, List<String>>();
+      fillShortcut2ListOfIds(myGesture2ListOfIds, KeyboardModifierGestureShortcut.class);
     }
     return myGesture2ListOfIds;
   }
@@ -364,23 +364,23 @@ public class KeymapImpl implements Keymap, ExternalizableScheme {
     return myParent.getActionIds(firstKeyStroke);
   }
 
-  protected String[] getParentActionIds(KeyboardModifierGestureShortuct gesture) {
+  protected String[] getParentActionIds(KeyboardModifierGestureShortcut gesture) {
     return myParent.getActionIds(gesture);
   }
 
-  private String[] getActionIds(KeyboardModifierGestureShortuct shortuct) {
+  private String[] getActionIds(KeyboardModifierGestureShortcut shortcut) {
     // first, get keystrokes from own map
-    final Map<KeyboardModifierGestureShortuct, List<String>> map = getGesture2ListOfIds();
+    final Map<KeyboardModifierGestureShortcut, List<String>> map = getGesture2ListOfIds();
     List<String> list = new ArrayList<String>();
 
-    for (Map.Entry<KeyboardModifierGestureShortuct, List<String>> entry : map.entrySet()) {
-      if (shortuct.startsWith(entry.getKey())) {
+    for (Map.Entry<KeyboardModifierGestureShortcut, List<String>> entry : map.entrySet()) {
+      if (shortcut.startsWith(entry.getKey())) {
         list.addAll(entry.getValue());
       }
     }
 
     if (myParent != null) {
-      String[] ids = getParentActionIds(shortuct);
+      String[] ids = getParentActionIds(shortcut);
       if (ids.length > 0) {
         for (String id : ids) {
           // add actions from parent keymap only if they are absent in this keymap
@@ -449,8 +449,8 @@ public class KeymapImpl implements Keymap, ExternalizableScheme {
     else if (shortcut instanceof MouseShortcut) {
       return getActionIds((MouseShortcut)shortcut);
     }
-    else if (shortcut instanceof KeyboardModifierGestureShortuct) {
-      return getActionIds((KeyboardModifierGestureShortuct)shortcut);
+    else if (shortcut instanceof KeyboardModifierGestureShortcut) {
+      return getActionIds((KeyboardModifierGestureShortcut)shortcut);
     }
     else {
       return ArrayUtil.EMPTY_STRING_ARRAY;
@@ -618,7 +618,7 @@ public class KeymapImpl implements Keymap, ExternalizableScheme {
               throw new InvalidDataException("Wrong modifier=" + modifierText + " action id=" + id + " keymap=" + myName);
             }
 
-            Shortcut shortcut = KeyboardModifierGestureShortuct.newInstance(modifier, stroke);
+            Shortcut shortcut = KeyboardModifierGestureShortcut.newInstance(modifier, stroke);
             final ArrayList<Shortcut> shortcuts = id2shortcuts.get(id);
             shortcuts.add(shortcut);
           }
@@ -693,8 +693,8 @@ public class KeymapImpl implements Keymap, ExternalizableScheme {
           element.setAttribute(KEYSTROKE_ATTRIBUTE, getMouseShortcutString(mouseShortcut));
           actionElement.addContent(element);
         }
-        else if (shortcut instanceof KeyboardModifierGestureShortuct) {
-          final KeyboardModifierGestureShortuct gesture = (KeyboardModifierGestureShortuct)shortcut;
+        else if (shortcut instanceof KeyboardModifierGestureShortcut) {
+          final KeyboardModifierGestureShortcut gesture = (KeyboardModifierGestureShortcut)shortcut;
           final Element element = new Element(KEYBOARD_GESTURE_SHORTCUT);
           element.setAttribute(KEYBOARD_GESTURE_SHORTCUT, getKeyShortcutString(gesture.getStroke()));
           element.setAttribute(KEYBOARD_GESTURE_MODIFIER, gesture.getType().name());
index c6d1d32066ee21382aed9c9c085994e7094e4372..9dd19e1ac0872efcdec69e4f2613274c19cb389c 100644 (file)
@@ -94,7 +94,7 @@ public class KeyboardGestureProcessor {
   }
 
   private Shortcut getCurrentShortcut() {
-    return KeyboardModifierGestureShortuct.newInstance(myContext.modifierType, myContext.actionShortcut);
+    return KeyboardModifierGestureShortcut.newInstance(myContext.modifierType, myContext.actionShortcut);
   }
 
   void setState(KeyGestureState state) {
index dd89f8039d3fd7104448131bf25275c0dd8777d2..4e6a613cb0552d104944e2e6aa998f0d0f6df70f 100644 (file)
@@ -1016,7 +1016,7 @@ public class OptionsEditor extends JPanel implements DataProvider, Place.Navigat
   public void eventDispatched(final AWTEvent event) {
     if (event.getID() == MouseEvent.MOUSE_PRESSED || event.getID() == MouseEvent.MOUSE_RELEASED || event.getID() == MouseEvent.MOUSE_DRAGGED) {
       final MouseEvent me = (MouseEvent)event;
-      if (SwingUtilities.isDescendingFrom(me.getComponent(), myContentWrapper) || isPopupOverEditor(me.getComponent())) {
+      if (SwingUtilities.isDescendingFrom(me.getComponent(), SwingUtilities.getWindowAncestor(myContentWrapper)) || isPopupOverEditor(me.getComponent())) {
         queueModificationCheck();
         myFilter.clearTemporary();
       }
index b081eb3a17a07460b84a54179eaeb28eb1ee5571..ad236d27ec24dbeb26ad2db2930659b2f1fa0427 100644 (file)
@@ -571,9 +571,9 @@ public class BalloonImpl implements Balloon, IdeTooltip.Ui {
       Disposer.dispose(myAnimator);
     }
     myAnimator = new Animator("Balloon", 8, myAnimationEnabled ? myAnimationCycle : 0, false, forward) {
-      public void paintNow(final float frame, final float totalFrames, final float cycle) {
+      public void paintNow(final int frame, final int totalFrames, final int cycle) {
         if (myComp == null || myComp.getParent() == null) return;
-        myComp.setAlpha(frame / totalFrames);
+        myComp.setAlpha(((float)frame) / ((float)totalFrames));
       }
 
       @Override
index 466de59f09d3037c0efd84098efe3daee064e25b..b2d1f23ddfe82840947e620d17cce9c2bc2bd096 100644 (file)
@@ -223,7 +223,7 @@ module.unknown.type.single.error=Cannot determine module type (\"{1}\") for the
 module.unknown.type.multiple.error=Cannot determine module type for the following modules:\n{0}\nAll mentioned modules will be treated as Unknown modules.
 module.unknown.type.title=Unknown Module Type
 module.web.title=Web Module
-module.web.description=Provides facilities for developing web applications.
+module.web.description=Creates an empty module that enables developing web applications using HTML/HTML5, PHP, JavaScript, and style sheets.
 module.remove.from.project.confirmation=Would you like to remove module ''{0}'' from the project?
 element.kind.name.module=module
 module.file.does.not.exist.error=File {0} does not exist
index 8390774e613397f820fe356013909cd99454acc0..55c7d4b531c0a1d1ca3f3c1e6442aeaa953e6892 100644 (file)
               class = "com.intellij.refactoring.actions.RefactoringQuickListPopupAction"
               text = "Refactor This..." description="Context aware popup with list of refactoring actions"/>
       <action id="RenameElement" class="com.intellij.refactoring.actions.RenameElementAction"/>
-      <action id="RenameFile" class="com.intellij.refactoring.rename.RenameFileAction"/>
       <action id="ChangeSignature" class="com.intellij.refactoring.actions.ChangeSignatureAction"/>
       <separator/>
       <action id="Move" class="com.intellij.refactoring.actions.MoveAction"/>
       <separator/>
       <reference ref="AddToFavorites"/>
       <reference ref="AddAllToFavorites"/>
-      <separator/>
-      <reference ref="RenameFile"/>
-      <separator/>
       <reference ref="MoveToChangeList"/>
       <separator/>
       <reference ref="RunContextPopupGroup"/>
 
     <group id="RunnerLayoutActions">
       <group id="Runner.Layout" icon="/debugger/restoreLayout.png" popup="true">
-        <action id="Runner.RestoreLayout" class="com.intellij.execution.ui.layout.actions.RestoreLayoutAction"
-                icon="/debugger/restoreLayout.png"/>
+        <action id="Runner.RestoreLayout" class="com.intellij.execution.ui.layout.actions.RestoreLayoutAction"/>
         <action id="Runner.ToggleToolbarLayout" class="com.intellij.execution.ui.layout.actions.ToggleToolbarLayoutAction"/>
       </group>
 
index 2a232a72536183b534b78c49a882ca7f720d1312..445b99e6bbdfd5b7d71ab7d0d3016f68bf287a52 100644 (file)
@@ -53,13 +53,13 @@ abstract class BaseTreeTestCase<StructureElement> extends FlyIdeaTestCase {
 
   void doAndWaitForBuilder(final Runnable runnable, final Condition condition) throws Exception {
     final Ref<Boolean> started = new Ref<Boolean>();
-    //invokeLaterIfNeeded(new Runnable() {
-    //  @Override
-    //  public void run() {
+    invokeLaterIfNeeded(new Runnable() {
+      @Override
+      public void run() {
         started.set(true);
         runnable.run();
-    //  }
-    //});
+      }
+    });
 
     waitBuilderToCome(new Condition() {
       @Override
index 645d6ae0192eed63f7a558e3f86cd748daea31ee..99c205834e9489db560920056cf08b2fc73b47e9 100644 (file)
@@ -36,7 +36,7 @@ import java.io.File;
  * @author Konstantin Bulenkov
  */
 public abstract class FileStructureTestBase extends CodeInsightFixtureTestCase {
-  FileStructurePopup myPopup;
+  protected FileStructurePopup myPopup;
 
   @Before
   public void setUp() throws Exception {
@@ -46,6 +46,9 @@ public abstract class FileStructureTestBase extends CodeInsightFixtureTestCase {
                                               myFixture.getProject(),
                                               null,
                                               TextEditorProvider.getInstance().getTextEditor(myFixture.getEditor()));
+    assert myPopup != null;
+    myPopup.createCenterPanel();
+    getBuilder().getUi().getUpdater().setPassThroughMode(true);
     update();
   }
 
@@ -71,15 +74,17 @@ public abstract class FileStructureTestBase extends CodeInsightFixtureTestCase {
   }
 
 
-  private void update() throws InterruptedException {
+  public void update() throws InterruptedException {
     myPopup.getTreeBuilder().refilter().doWhenProcessed(new Runnable() {
       @Override
       public void run() {
+
         getStructure().rebuild();
         updateTree();
+        getBuilder().updateFromRoot();
         TreeUtil.expandAll(getTree());
         final FilteringTreeStructure.FilteringNode node = myPopup.selectPsiElement(myPopup.getCurrentElement(getFile()));
-        getTree().getSelectionModel().setSelectionPath(getTree().getPath(node));
+        getBuilder().getUi().select(node, null);
       }
     });
   }
diff --git a/platform/testFramework/src/com/intellij/testFramework/TestTreeUpdater.java b/platform/testFramework/src/com/intellij/testFramework/TestTreeUpdater.java
new file mode 100644 (file)
index 0000000..3dfec72
--- /dev/null
@@ -0,0 +1,28 @@
+/*
+ * Copyright 2000-2012 JetBrains s.r.o.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.intellij.testFramework;
+
+import com.intellij.ide.util.treeView.AbstractTreeBuilder;
+import com.intellij.ide.util.treeView.AbstractTreeUpdater;
+
+/**
+ * @author Konstantin Bulenkov
+ */
+public class TestTreeUpdater extends AbstractTreeUpdater {
+  public TestTreeUpdater(AbstractTreeBuilder treeBuilder) {
+    super(treeBuilder);
+  }
+}
index 0d5c22494c6b9aaa5729aec9f2522e2d5f244f06..950d93c1ff4b022ca82b2f2393cfe32ad921857c 100644 (file)
@@ -31,10 +31,7 @@ import com.intellij.openapi.project.Project;
 import com.intellij.openapi.ui.Messages;
 import com.intellij.openapi.ui.SimpleToolWindowPanel;
 import com.intellij.openapi.ui.Splitter;
-import com.intellij.openapi.util.Condition;
-import com.intellij.openapi.util.Disposer;
-import com.intellij.openapi.util.Factory;
-import com.intellij.openapi.util.IconLoader;
+import com.intellij.openapi.util.*;
 import com.intellij.openapi.vfs.ReadonlyStatusHandler;
 import com.intellij.openapi.vfs.VfsUtil;
 import com.intellij.openapi.vfs.VirtualFile;
@@ -688,10 +685,7 @@ public class UsageViewImpl implements UsageView, UsageModelTracker.UsageModelTra
 
   private void reset() {
     ApplicationManager.getApplication().assertIsDispatchThread();
-
     myUsageNodes.clear();
-    myIsFirstVisibleUsageFound = false;
-
     myModel.reset();
     if (!myPresentation.isDetachedMode()) {
       SwingUtilities.invokeLater(new Runnable() {
@@ -718,8 +712,6 @@ public class UsageViewImpl implements UsageView, UsageModelTracker.UsageModelTra
     });
   }
 
-  private volatile boolean myIsFirstVisibleUsageFound = false;
-
   @Override
   public void appendUsage(@NotNull Usage usage) {
     doAppendUsage(usage);
@@ -734,10 +726,6 @@ public class UsageViewImpl implements UsageView, UsageModelTracker.UsageModelTra
     }
     UsageNode node = myBuilder.appendUsage(usage);
     myUsageNodes.put(usage, node == null ? NULL_NODE : node);
-    if (!myIsFirstVisibleUsageFound && node != null) { //first visible usage found;
-      myIsFirstVisibleUsageFound = true;
-      showNode(node);
-    }
     return node;
   }
 
@@ -874,9 +862,14 @@ public class UsageViewImpl implements UsageView, UsageModelTracker.UsageModelTra
         public void run() {
           if (isDisposed) return;
           final UsageNode firstUsageNode = myModel.getFirstUsageNode();
-          if (firstUsageNode != null) {
-            showNode(firstUsageNode);
+          if (firstUsageNode == null) return;
+
+          Node node = getSelectedNode();
+          if (node != null && !Comparing.equal(new TreePath(node.getPath()), TreeUtil.getFirstNodePath(myTree))) {
+            // user has selected node already
+            return;
           }
+          showNode(firstUsageNode);
         }
       });
     }
index 967fa81553e640b6b1c2921e9a841f6f53f114f9..d33c3f6fcf0b3730fb4b9986fa28cf9a93c51ab6 100644 (file)
@@ -82,7 +82,7 @@ public class Key<T> {
     return get(holder) != null;
   }
 
-  public void set(@Nullable UserDataHolder holder, T value) {
+  public void set(@Nullable UserDataHolder holder, @Nullable T value) {
     if (holder != null) {
       holder.putUserData(this, value);
     }
index dcc24baad4b5fb9f843e994f01085beedabe510c..dad11a355004900b9ee965d597e96625d6d4e8e5 100644 (file)
@@ -15,6 +15,9 @@
  */
 package com.intellij.ui.awt;
 
+import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
+
 import javax.swing.*;
 import java.awt.*;
 import java.awt.event.MouseEvent;
@@ -27,20 +30,20 @@ public class RelativePoint {
   private Component myOriginalComponent;
   private Point myOriginalPoint;
 
-  public RelativePoint(MouseEvent event) {
+  public RelativePoint(@NotNull MouseEvent event) {
     init(event.getComponent(), event.getPoint());
 
     myOriginalComponent = event.getComponent();
     myOriginalPoint = event.getPoint();
   }
 
-  public RelativePoint(Component aComponent, Point aPointOnComponent) {
+  public RelativePoint(@NotNull Component aComponent, Point aPointOnComponent) {
     init(aComponent, aPointOnComponent);
   }
 
-  public RelativePoint(Point screenPoint) {
+  public RelativePoint(@NotNull Point screenPoint) {
     Point p = new Point(screenPoint.x, screenPoint.y);
-    Window[] windows = Frame.getWindows();
+    Window[] windows = Window.getWindows();
     Window targetWindow = null;
     for (Window each : windows) {
       if (each.isActive()) {
@@ -57,7 +60,7 @@ public class RelativePoint {
     init(targetWindow, p);
   }
 
-  private void init(Component aComponent, Point aPointOnComponent) {
+  private void init(@NotNull Component aComponent, Point aPointOnComponent) {
     if (aComponent.isShowing()) {
       myComponent = SwingUtilities.getRootPane(aComponent);
       myPointOnComponent = SwingUtilities.convertPoint(aComponent, aPointOnComponent, myComponent);
@@ -79,63 +82,73 @@ public class RelativePoint {
     return myPointOnComponent;
   }
 
-  public Point getPoint(Component aTargetComponent) {
+  public Point getPoint(@Nullable Component aTargetComponent) {
 //todo: remove that after implementation of DND to html design time controls
     if (aTargetComponent == null || aTargetComponent.getParent() == null || SwingUtilities.getWindowAncestor(aTargetComponent) == null) return new Point();
 
     return SwingUtilities.convertPoint(getComponent(), getPoint(), aTargetComponent);
   }
 
-  public RelativePoint getPointOn(Component aTargetComponent) {
+  @NotNull
+  public RelativePoint getPointOn(@NotNull Component aTargetComponent) {
     final Point point = getPoint(aTargetComponent);
     return new RelativePoint(aTargetComponent, point);
   }
 
+  @NotNull
   public Point getScreenPoint() {
     final Point point = (Point) getPoint().clone();
     SwingUtilities.convertPointToScreen(point, getComponent());
     return point;
   }
 
+  @NotNull
   public MouseEvent toMouseEvent() {
     return new MouseEvent(myComponent, 0, 0, 0, myPointOnComponent.x, myPointOnComponent.y, 1, false); 
   }
 
+  @NotNull
   public String toString() {
     //noinspection HardCodedStringLiteral
     return getPoint() + " on " + getComponent().toString();
   }
 
-  public static RelativePoint getCenterOf(JComponent component) {
+  @NotNull
+  public static RelativePoint getCenterOf(@NotNull JComponent component) {
     final Rectangle visibleRect = component.getVisibleRect();
     final Point point = new Point(visibleRect.x + visibleRect.width/2, visibleRect.y + visibleRect.height/2);
     return new RelativePoint(component, point);
   }
 
-  public static RelativePoint getSouthEastOf(JComponent component) {
+  @NotNull
+  public static RelativePoint getSouthEastOf(@NotNull JComponent component) {
     final Rectangle visibleRect = component.getVisibleRect();
     final Point point = new Point(visibleRect.x + visibleRect.width, visibleRect.y + visibleRect.height);
     return new RelativePoint(component, point);
   }
 
-  public static RelativePoint getSouthWestOf(JComponent component) {
+  @NotNull
+  public static RelativePoint getSouthWestOf(@NotNull JComponent component) {
     final Rectangle visibleRect = component.getVisibleRect();
     final Point point = new Point(visibleRect.x, visibleRect.y + visibleRect.height);
     return new RelativePoint(component, point);
   }
 
-  public static RelativePoint getNorthWestOf(JComponent component) {
+  @NotNull
+  public static RelativePoint getNorthWestOf(@NotNull JComponent component) {
     final Rectangle visibleRect = component.getVisibleRect();
     final Point point = new Point(visibleRect.x, visibleRect.y);
     return new RelativePoint(component, point);
   }
 
-  public static RelativePoint getNorthEastOf(JComponent component) {
+  @NotNull
+  public static RelativePoint getNorthEastOf(@NotNull JComponent component) {
     final Rectangle visibleRect = component.getVisibleRect();
     final Point point = new Point(visibleRect.x + visibleRect.width, visibleRect.y);
     return new RelativePoint(component, point);
   }
 
+  @NotNull
   public static RelativePoint fromScreen(Point screenPoint) {
     Frame root = JOptionPane.getRootFrame();
     SwingUtilities.convertPointFromScreen(screenPoint, root);
index 02b5bf548012751ae96a73262e81f5bbd5b22fe9..2e402f5e8cca28226b95bc3f1b2aa0fa28b92f02 100644 (file)
@@ -100,17 +100,20 @@ public class RollbackAction extends AnAction implements DumbAware {
     FileDocumentManager.getInstance().saveAllDocuments();
 
     List<FilePath> missingFiles = e.getData(ChangesListView.MISSING_FILES_DATA_KEY);
+    boolean hasChanges = false;
     if (missingFiles != null && !missingFiles.isEmpty()) {
+      hasChanges = true;
       new RollbackDeletionAction().actionPerformed(e);
     }
 
     List<VirtualFile> modifiedWithoutEditing = getModifiedWithoutEditing(e);
     if (modifiedWithoutEditing != null && !modifiedWithoutEditing.isEmpty()) {
+      hasChanges = true;
       rollbackModifiedWithoutEditing(project, modifiedWithoutEditing);
     }
 
     Change[] changes = getChanges(project, e);
-    if (changes != null) {
+    if (changes != null && (changes.length > 0 || !hasChanges)) {
       RollbackChangesDialog.rollbackChanges(project, Arrays.asList(changes));
     }
   }
index 4639e93c509bb499c234bfe8f678efdfed2f1b42..71e71761ba30a4498b054eea07a9e4749e542dc2 100644 (file)
@@ -460,7 +460,7 @@ large.array.allocation.no.outofmemoryerror.problem.descriptor=Large array alloca
 large.array.allocation.no.outofmemoryerror.maximum.number.of.elements.option=Maximum number of elements:
 connection.opened.not.safely.closed.display.name=Connection opened but not safely closed
 field.repeatedly.accessed.in.method.display.name=Field repeatedly accessed in method
-field.repeatedly.accessed.in.method.problem.descriptor=Field ''{0}'' accessed repeatedly in method <code>#ref(0</code> #loc
+field.repeatedly.accessed.in.method.problem.descriptor=Field ''{0}'' accessed repeatedly in method <code>#ref()</code> #loc
 field.repeatedly.accessed.in.method.ignore.option=Ignore final fields
 interface.one.inheritor.display.name=Interface which has only one direct inheritor
 interface.one.inheritor.problem.descriptor=Interface <code>#ref</code> has only one direct inheritor #loc
@@ -1043,7 +1043,7 @@ map.replaceable.by.enum.map.problem.descriptor=<code>#ref</code> replaceable wit
 set.replaceable.by.enum.set.problem.descriptor=<code>#ref</code> replaceable with EnumSet #loc
 inner.class.may.be.static.problem.descriptor=Inner class <code>#ref</code> may be 'static' #loc
 string.buffer.must.have.initial.capacity.problem.descriptor=<code>#ref</code> without initial capacity #loc
-string.buffer.replaceable.by.string.builder.problem.descriptor=<code>StringBuffer #ref</code> may be declared as ''StringBuilder'' #loc
+string.buffer.replaceable.by.string.builder.problem.descriptor=<code>StringBuffer #ref</code> may be declared as 'StringBuilder' #loc
 string.buffer.replaceable.by.string.problem.descriptor=<code>{0} #ref</code> can be replaced with ''String'' #loc
 new.string.buffer.replaceable.by.string.problem.descriptor=<code>#ref</code> can be replaced with 'String' #loc
 string.replaceable.by.string.buffer.problem.descriptor=Non-constant <code>String #ref</code> should probably be declared as ''StringBuilder'' #loc
index c3fec9f74ba6e3424dc4f4a261b24ee325488859..02554ab35332619c94aea33743ee79c750c957de 100644 (file)
@@ -15,6 +15,7 @@
  */
 package com.siyeh.ig.style;
 
+import com.intellij.codeInspection.canBeFinal.CanBeFinalHandler;
 import com.intellij.psi.PsiField;
 import com.intellij.psi.PsiModifier;
 import com.siyeh.InspectionGadgetsBundle;
@@ -65,6 +66,7 @@ public class FieldMayBeFinalInspection extends BaseInspection {
           !field.hasModifierProperty(PsiModifier.PRIVATE)) {
         return;
       }
+      if (!CanBeFinalHandler.allowToBeFinal(field)) return;
       if (!FinalUtils.canBeFinal(field)) {
         return;
       }
index a7e13174cc6f99b9923132eed6861d5d07e00fac..018ee3cd79bd0bbd8897e01c492600287ef4eb6f 100644 (file)
@@ -24,9 +24,11 @@ import com.siyeh.InspectionGadgetsBundle;
 import com.siyeh.ig.BaseInspection;
 import com.siyeh.ig.BaseInspectionVisitor;
 import com.siyeh.ig.InspectionGadgetsFix;
+import com.siyeh.ig.psiutils.ParenthesesUtils;
 import com.siyeh.ig.psiutils.TypeUtils;
 import com.siyeh.ig.psiutils.VariableAccessUtils;
 import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
 
 public class StringBufferReplaceableByStringInspection extends BaseInspection {
 
@@ -81,7 +83,9 @@ public class StringBufferReplaceableByStringInspection extends BaseInspection {
           final PsiNewExpression newExpression = (PsiNewExpression)parent;
           final PsiExpression stringBuilderExpression = getCompleteExpression(newExpression);
           final StringBuilder stringExpression = buildStringExpression(stringBuilderExpression, new StringBuilder());
-          replaceExpression(stringBuilderExpression, stringExpression.toString());
+          if (stringExpression != null && stringBuilderExpression != null) {
+            replaceExpression(stringBuilderExpression, stringExpression.toString());
+          }
           return;
         }
         return;
@@ -106,10 +110,14 @@ public class StringBufferReplaceableByStringInspection extends BaseInspection {
       originalTypeElement.replace(typeElement);
     }
 
+    @Nullable
     private static StringBuilder buildStringExpression(PsiExpression initializer, StringBuilder result) {
       if (initializer instanceof PsiNewExpression) {
         final PsiNewExpression newExpression = (PsiNewExpression)initializer;
         final PsiExpressionList argumentList = newExpression.getArgumentList();
+        if (argumentList ==  null) {
+          return null;
+        }
         final PsiExpression[] arguments = argumentList.getExpressions();
         if (arguments.length == 1) {
           final PsiExpression argument = arguments[0];
@@ -141,7 +149,13 @@ public class StringBufferReplaceableByStringInspection extends BaseInspection {
           }
           final PsiExpression argument = arguments[0];
           if (result.length() != 0) {
-            result.append('+').append(argument.getText());
+            result.append('+');
+            if (ParenthesesUtils.getPrecedence(argument) > ParenthesesUtils.ADDITIVE_PRECEDENCE) {
+              result.append('(').append(argument.getText()).append(')');
+            }
+            else {
+              result.append(argument.getText());
+            }
           }
           else {
             final PsiType type = argument.getType();
@@ -149,7 +163,12 @@ public class StringBufferReplaceableByStringInspection extends BaseInspection {
               result.append("String.valueOf(").append(argument.getText()).append(")");
             }
             else {
-              result.append(argument.getText());
+              if (ParenthesesUtils.getPrecedence(argument) > ParenthesesUtils.ADDITIVE_PRECEDENCE) {
+                result.append('(').append(argument.getText()).append(')');
+              }
+              else {
+                result.append(argument.getText());
+              }
             }
           }
         }
@@ -228,8 +247,18 @@ public class StringBufferReplaceableByStringInspection extends BaseInspection {
       if (expression == null) {
         return false;
       }
-      else if (expression instanceof PsiNewExpression) {
-        return true;
+      else if (
+      expression instanceof PsiNewExpression) {
+        if (!(expression.getParent() instanceof PsiVariable)) {
+          return true;
+        }
+        final PsiNewExpression newExpression = (PsiNewExpression)expression;
+        final PsiExpressionList argumentList = newExpression.getArgumentList();
+        if (argumentList == null) {
+          return false;
+        }
+        final PsiExpression[] arguments = argumentList.getExpressions();
+        return arguments.length == 1;
       }
       else if (expression instanceof PsiMethodCallExpression) {
         final PsiMethodCallExpression methodCallExpression = (PsiMethodCallExpression)expression;
@@ -250,6 +279,7 @@ public class StringBufferReplaceableByStringInspection extends BaseInspection {
     }
   }
 
+  @Nullable
   private static PsiExpression getCompleteExpression(PsiNewExpression expression) {
     PsiElement completeExpression = expression;
     boolean found = false;
@@ -259,17 +289,25 @@ public class StringBufferReplaceableByStringInspection extends BaseInspection {
         break;
       }
       final PsiReferenceExpression referenceExpression = (PsiReferenceExpression)parent;
+      final PsiElement grandParent = parent.getParent();
+      if (!(grandParent instanceof PsiMethodCallExpression)) {
+        break;
+      }
       final String name = referenceExpression.getReferenceName();
-      if (!"append".equals(name)) {
+      if ("append".equals(name)) {
+        final PsiMethodCallExpression methodCallExpression = (PsiMethodCallExpression)grandParent;
+        final PsiExpressionList argumentList = methodCallExpression.getArgumentList();
+        final PsiExpression[] arguments = argumentList.getExpressions();
+        if (arguments.length != 1) {
+          return null;
+        }
+      }
+      else {
         if (!"toString".equals(name)) {
           return null;
         }
         found = true;
       }
-      final PsiElement grandParent = parent.getParent();
-      if (!(grandParent instanceof PsiMethodCallExpression)) {
-        break;
-      }
       completeExpression = grandParent;
       if (found) {
         return (PsiExpression)completeExpression;
diff --git a/plugins/InspectionGadgets/test/com/siyeh/igfixes/style/replace_with_string/Precedence.after.java b/plugins/InspectionGadgets/test/com/siyeh/igfixes/style/replace_with_string/Precedence.after.java
new file mode 100644 (file)
index 0000000..5b82285
--- /dev/null
@@ -0,0 +1,9 @@
+package com.siyeh.igfixes.style.replace_with_string;
+
+import java.awt.*;
+
+class Precedence {
+  public static String toRgbColor( final Color color) {
+    return "rgba(" + color.getRed() + ',' + color.getGreen() + ',' + color.getBlue() + ',' + (color.getAlpha() == 0 ? '0' : String.format("0.%2d", (int) (color.getAlpha() / 255.0 * 100))) + ')' + 9 * 9;
+  }
+}
\ No newline at end of file
diff --git a/plugins/InspectionGadgets/test/com/siyeh/igfixes/style/replace_with_string/Precedence.java b/plugins/InspectionGadgets/test/com/siyeh/igfixes/style/replace_with_string/Precedence.java
new file mode 100644 (file)
index 0000000..bc35808
--- /dev/null
@@ -0,0 +1,12 @@
+package com.siyeh.igfixes.style.replace_with_string;
+
+import java.awt.*;
+
+class Precedence {
+  public static String toRgbColor( final Color color) {
+    return new StringB<caret>uilder("rgba(").append(color.getRed()).append(',')
+      .append(color.getGreen()).append(',').append(color.getBlue())
+      .append(',').append(color.getAlpha() == 0 ? '0' : String.format("0.%2d", (int) (color.getAlpha() / 255.0 * 100)))
+      .append(')').append(9*9).toString();
+  }
+}
\ No newline at end of file
index c933cf4f6c9679a006be078c77805dfee880a302..5c5d28b6202ebbff2b41eee023f6bab8a8198f47 100644 (file)
@@ -5,6 +5,6 @@
     <file>FieldRepeatedlyAccessed.java</file>
     <line>7</line>
     <problem_class severity="WARNING" attribute_key="WARNING_ATTRIBUTES">Field repeatedly accessed in method</problem_class>
-    <description>Field 's' accessed repeatedly in method &lt;code&gt;foo(0&lt;/code&gt; #loc</description>
+    <description>Field 's' accessed repeatedly in method &lt;code&gt;foo()&lt;/code&gt; #loc</description>
   </problem>
 </problems>
\ No newline at end of file
index 6c13850a12126f3585403e0254633f2df0544aca..35d89c2387a0218134ca0cd3dff9f70f26005f59 100644 (file)
@@ -11,7 +11,7 @@ public class StringBufferReplaceableByString {
 
   public void foo1()
   {
-    final StringBuffer buffer = new StringBuffer();
+    final StringBuffer buffer = new StringBuffer().append('a');
     System.out.println(buffer.toString());
   }
 
@@ -24,4 +24,9 @@ public class StringBufferReplaceableByString {
   public void bar(int i) {
     System.out.println(new StringBuilder("asdf").append(i).toString());
   }
+
+  public void exceptions(String pcdata, int i) {
+    StringBuilder b = new StringBuilder();
+    String s = new StringBuilder().append(pcdata, 0, i).toString();
+  }
 }
index 0d03db24fa176bd5fc053e27641407aae8645653..1db03b736071a603ebe3fbd52719130609e5d01d 100644 (file)
@@ -33,4 +33,5 @@ public class StringBufferReplaceableWithStringFixTest extends IGQuickFixesTestCa
   public void testStringBuilderAppend() { doTest("StringBuilderAppend", InspectionGadgetsBundle.message("string.builder.replaceable.by.string.quickfix")); }
   public void testStringBufferVariable() { doTest(); }
   public void testStartsWithPrimitive() { doTest(); }
+  public void testPrecedence() { doTest("Precedence", InspectionGadgetsBundle.message("string.builder.replaceable.by.string.quickfix")); }
 }
index a4d69d8cb90b9758d0cd191339f8a7eea48ccf06..c056fe0dcb5f5c0ff7139e349d96185b0236b4db 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright 2003-2011 Dave Griffith, Bas Leijdekkers
+ * Copyright 2003-2012 Dave Griffith, Bas Leijdekkers
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -24,7 +24,7 @@ import com.intellij.openapi.vfs.VirtualFile;
 import com.intellij.psi.*;
 import com.intellij.psi.codeStyle.CodeStyleManager;
 import com.intellij.psi.codeStyle.JavaCodeStyleManager;
-import com.intellij.psi.util.PsiUtil;
+import com.intellij.psi.util.PsiUtilCore;
 import com.intellij.util.IncorrectOperationException;
 import com.siyeh.IntentionPowerPackBundle;
 import com.siyeh.ipp.psiutils.BoolUtils;
@@ -46,8 +46,7 @@ public abstract class Intention extends PsiElementBaseIntentionAction {
   }
 
   @Override
-  public void invoke(Project project, Editor editor, PsiElement element)
-    throws IncorrectOperationException {
+  public void invoke(Project project, Editor editor, PsiElement element) throws IncorrectOperationException {
     if (!isWritable(project, element)) {
       return;
     }
@@ -58,33 +57,25 @@ public abstract class Intention extends PsiElementBaseIntentionAction {
     processIntention(matchingElement);
   }
 
-  protected abstract void processIntention(@NotNull PsiElement element)
-    throws IncorrectOperationException;
+  protected abstract void processIntention(@NotNull PsiElement element) throws IncorrectOperationException;
 
   @NotNull
   protected abstract PsiElementPredicate getElementPredicate();
 
-  protected static void replaceExpression(@NotNull String newExpression,
-                                          @NotNull PsiExpression expression)
+  protected static void replaceExpression(@NotNull String newExpression, @NotNull PsiExpression expression)
     throws IncorrectOperationException {
     final Project project = expression.getProject();
-    final PsiElementFactory factory =
-      JavaPsiFacade.getElementFactory(project);
-    final PsiExpression newCall =
-      factory.createExpressionFromText(newExpression, expression);
+    final PsiElementFactory factory = JavaPsiFacade.getElementFactory(project);
+    final PsiExpression newCall = factory.createExpressionFromText(newExpression, expression);
     final PsiElement insertedElement = expression.replace(newCall);
-    final CodeStyleManager codeStyleManager =
-      CodeStyleManager.getInstance(project);
+    final CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(project);
     codeStyleManager.reformat(insertedElement);
   }
 
-  protected static void replaceExpressionWithNegatedExpression(
-    @NotNull PsiExpression newExpression,
-    @NotNull PsiExpression expression)
+  protected static void replaceExpressionWithNegatedExpression(@NotNull PsiExpression newExpression, @NotNull PsiExpression expression)
     throws IncorrectOperationException {
     final Project project = expression.getProject();
-    final PsiElementFactory factory =
-      JavaPsiFacade.getElementFactory(project);
+    final PsiElementFactory factory = JavaPsiFacade.getElementFactory(project);
     PsiExpression expressionToReplace = expression;
     final String newExpressionText = newExpression.getText();
     final String expString;
@@ -93,36 +84,29 @@ public abstract class Intention extends PsiElementBaseIntentionAction {
       expString = newExpressionText;
     }
     else if (ComparisonUtils.isComparison(newExpression)) {
-      final PsiBinaryExpression binaryExpression =
-        (PsiBinaryExpression)newExpression;
-      final String negatedComparison =
-        ComparisonUtils.getNegatedComparison(binaryExpression.getOperationTokenType());
+      final PsiBinaryExpression binaryExpression = (PsiBinaryExpression)newExpression;
+      final String negatedComparison = ComparisonUtils.getNegatedComparison(binaryExpression.getOperationTokenType());
       final PsiExpression lhs = binaryExpression.getLOperand();
       final PsiExpression rhs = binaryExpression.getROperand();
       assert rhs != null;
       expString = lhs.getText() + negatedComparison + rhs.getText();
     }
     else {
-      if (ParenthesesUtils.getPrecedence(newExpression) >
-          ParenthesesUtils.PREFIX_PRECEDENCE) {
+      if (ParenthesesUtils.getPrecedence(newExpression) > ParenthesesUtils.PREFIX_PRECEDENCE) {
         expString = "!(" + newExpressionText + ')';
       }
       else {
         expString = '!' + newExpressionText;
       }
     }
-    final PsiExpression newCall =
-      factory.createExpressionFromText(expString, expression);
+    final PsiExpression newCall = factory.createExpressionFromText(expString, expression);
     assert expressionToReplace != null;
     final PsiElement insertedElement = expressionToReplace.replace(newCall);
-    final CodeStyleManager codeStyleManager =
-      CodeStyleManager.getInstance(project);
+    final CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(project);
     codeStyleManager.reformat(insertedElement);
   }
 
-  protected static void replaceExpressionWithNegatedExpressionString(
-    @NotNull String newExpression,
-    @NotNull PsiExpression expression)
+  protected static void replaceExpressionWithNegatedExpressionString(@NotNull String newExpression, @NotNull PsiExpression expression)
     throws IncorrectOperationException {
     final Project project = expression.getProject();
     final JavaPsiFacade psiFacade = JavaPsiFacade.getInstance(project);
@@ -130,52 +114,44 @@ public abstract class Intention extends PsiElementBaseIntentionAction {
     PsiExpression expressionToReplace = expression;
     final String expString;
     if (BoolUtils.isNegated(expression)) {
-      expressionToReplace = BoolUtils.findNegation(expression);
+      expressionToReplace = BoolUtils.findNegation(expressionToReplace);
       expString = newExpression;
     }
     else {
+      PsiElement parent = expressionToReplace.getParent();
+      while (parent instanceof PsiParenthesizedExpression) {
+        expressionToReplace = (PsiExpression)parent;
+        parent = parent.getParent();
+      }
       expString = "!(" + newExpression + ')';
     }
-    final PsiExpression newCall =
-      factory.createExpressionFromText(expString, expression);
+    final PsiExpression newCall = factory.createExpressionFromText(expString, expression);
     assert expressionToReplace != null;
     final PsiElement insertedElement = expressionToReplace.replace(newCall);
-    final CodeStyleManager codeStyleManager =
-      CodeStyleManager.getInstance(project);
+    final CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(project);
     codeStyleManager.reformat(insertedElement);
   }
 
-  protected static void replaceStatement(
-    @NonNls @NotNull String newStatementText,
-    @NonNls @NotNull PsiStatement statement)
+  protected static void replaceStatement(@NonNls @NotNull String newStatementText, @NonNls @NotNull PsiStatement statement)
     throws IncorrectOperationException {
     final Project project = statement.getProject();
-    final PsiElementFactory factory =
-      JavaPsiFacade.getElementFactory(project);
-    final PsiStatement newStatement =
-      factory.createStatementFromText(newStatementText, statement);
+    final PsiElementFactory factory = JavaPsiFacade.getElementFactory(project);
+    final PsiStatement newStatement = factory.createStatementFromText(newStatementText, statement);
     final PsiElement insertedElement = statement.replace(newStatement);
-    final CodeStyleManager codeStyleManager =
-      CodeStyleManager.getInstance(project);
+    final CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(project);
     codeStyleManager.reformat(insertedElement);
   }
 
-  protected static void replaceStatementAndShorten(
-    @NonNls @NotNull String newStatementText,
-    @NonNls @NotNull PsiStatement statement)
+  protected static void replaceStatementAndShorten(@NonNls @NotNull String newStatementText, @NonNls @NotNull PsiStatement statement)
     throws IncorrectOperationException {
     final Project project = statement.getProject();
     final JavaPsiFacade psiFacade = JavaPsiFacade.getInstance(project);
     final PsiElementFactory factory = psiFacade.getElementFactory();
-    final PsiStatement newStatement =
-      factory.createStatementFromText(newStatementText, statement);
+    final PsiStatement newStatement = factory.createStatementFromText(newStatementText, statement);
     final PsiElement insertedElement = statement.replace(newStatement);
-    final JavaCodeStyleManager javaCodeStyleManager =
-      JavaCodeStyleManager.getInstance(project);
-    final PsiElement shortenedElement =
-      javaCodeStyleManager.shortenClassReferences(insertedElement);
-    final CodeStyleManager codeStyleManager =
-      CodeStyleManager.getInstance(project);
+    final JavaCodeStyleManager javaCodeStyleManager = JavaCodeStyleManager.getInstance(project);
+    final PsiElement shortenedElement = javaCodeStyleManager.shortenClassReferences(insertedElement);
+    final CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(project);
     codeStyleManager.reformat(shortenedElement);
   }
 
@@ -202,8 +178,7 @@ public abstract class Intention extends PsiElementBaseIntentionAction {
   }
 
   @Override
-  public boolean isAvailable(@NotNull Project project, Editor editor,
-                             @NotNull PsiElement element) {
+  public boolean isAvailable(@NotNull Project project, Editor editor, @NotNull PsiElement element) {
     return findMatchingElement(element, editor) != null;
   }
 
@@ -213,14 +188,12 @@ public abstract class Intention extends PsiElementBaseIntentionAction {
   }
 
   private static boolean isWritable(Project project, PsiElement element) {
-    final VirtualFile virtualFile = PsiUtil.getVirtualFile(element);
+    final VirtualFile virtualFile = PsiUtilCore.getVirtualFile(element);
     if (virtualFile == null) {
       return true;
     }
-    final ReadonlyStatusHandler readonlyStatusHandler =
-      ReadonlyStatusHandler.getInstance(project);
-    final ReadonlyStatusHandler.OperationStatus operationStatus =
-      readonlyStatusHandler.ensureFilesWritable(virtualFile);
+    final ReadonlyStatusHandler readonlyStatusHandler = ReadonlyStatusHandler.getInstance(project);
+    final ReadonlyStatusHandler.OperationStatus operationStatus = readonlyStatusHandler.ensureFilesWritable(virtualFile);
     return !operationStatus.hasReadonlyFiles();
   }
 
index b3ef7f4863b654b53d809e260fc8af34035c89fa..ce7cb8dd7cd7ebecc70b077898678f02faa0d91f 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright 2003-2006 Dave Griffith, Bas Leijdekkers
+ * Copyright 2003-2012 Dave Griffith, Bas Leijdekkers
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -29,8 +29,7 @@ import org.jetbrains.annotations.NotNull;
 public class DemorgansIntention extends MutablyNamedIntention {
 
   protected String getTextForElement(PsiElement element) {
-    final PsiPolyadicExpression binaryExpression =
-      (PsiPolyadicExpression)element;
+    final PsiPolyadicExpression binaryExpression = (PsiPolyadicExpression)element;
     final IElementType tokenType = binaryExpression.getOperationTokenType();
     if (tokenType.equals(JavaTokenType.ANDAND)) {
       return IntentionPowerPackBundle.message("demorgans.intention.name1");
@@ -45,84 +44,55 @@ public class DemorgansIntention extends MutablyNamedIntention {
     return new ConjunctionPredicate();
   }
 
-  public void processIntention(@NotNull PsiElement element)
-    throws IncorrectOperationException {
-    PsiPolyadicExpression exp =
-      (PsiPolyadicExpression)element;
-    final IElementType tokenType = exp.getOperationTokenType();
-    PsiElement parent = exp.getParent();
-    while (isConjunctionExpression(parent, tokenType)) {
-      exp = (PsiPolyadicExpression)parent;
-      assert exp != null;
-      parent = exp.getParent();
-    }
-    final String newExpression =
-      convertConjunctionExpression(exp, tokenType);
-    replaceExpressionWithNegatedExpressionString(newExpression,
-                                                 exp);
+  public void processIntention(@NotNull PsiElement element) throws IncorrectOperationException {
+    final PsiPolyadicExpression polyadicExpression = (PsiPolyadicExpression)element;
+    final String newExpression = convertConjunctionExpression(polyadicExpression);
+    replaceExpressionWithNegatedExpressionString(newExpression, polyadicExpression);
   }
 
-  private static String convertConjunctionExpression(PsiPolyadicExpression exp,
-                                                     IElementType tokenType) {
+  private static String convertConjunctionExpression(PsiPolyadicExpression polyadicExpression) {
+    final IElementType tokenType = polyadicExpression.getOperationTokenType();
     final String flippedConjunction;
-    if (tokenType.equals(JavaTokenType.ANDAND)) {
-      flippedConjunction = "||";
-    }
-    else {
-      flippedConjunction = "&&";
-    }
-    String result = null;
-    for (PsiExpression expression : exp.getOperands()) {
-      String lhsText = convertLeafExpression(expression);
-      result = result == null ? lhsText : result + flippedConjunction + lhsText;
+    final boolean tokenTypeAndAnd = tokenType.equals(JavaTokenType.ANDAND);
+    flippedConjunction = tokenTypeAndAnd ? "||" : "&&";
+    final StringBuilder result = new StringBuilder();
+    for (PsiExpression operand : polyadicExpression.getOperands()) {
+      if (result.length() != 0) {
+        result.append(flippedConjunction);
+      }
+      result.append(convertLeafExpression(operand, tokenTypeAndAnd));
     }
-    return result;
+    return result.toString();
   }
 
-  private static String convertLeafExpression(PsiExpression condition) {
-    if (BoolUtils.isNegation(condition)) {
-      final PsiExpression negated = BoolUtils.getNegated(condition);
-      if (negated == null) {
+  private static String convertLeafExpression(PsiExpression expression, boolean tokenTypeAndAnd) {
+    if (BoolUtils.isNegation(expression)) {
+      final PsiExpression negatedExpression = BoolUtils.getNegated(expression);
+      if (negatedExpression == null) {
         return "";
       }
-      if (ParenthesesUtils.getPrecedence(negated) >
-          ParenthesesUtils.OR_PRECEDENCE) {
-        return '(' + negated.getText() + ')';
-      }
-      final PsiElement conditionParent = condition.getParent();
-      if (conditionParent instanceof PsiExpression &&
-          ParenthesesUtils.getPrecedence(negated) > ParenthesesUtils.AND_PRECEDENCE &&