Merge remote-tracking branch 'origin/master'
authorDmitry Trofimov <dmitry.trofimov@jetbrains.com>
Fri, 2 Dec 2016 09:32:50 +0000 (12:32 +0300)
committerDmitry Trofimov <dmitry.trofimov@jetbrains.com>
Fri, 2 Dec 2016 09:32:50 +0000 (12:32 +0300)
209 files changed:
build/order.txt
java/compiler/impl/src/com/intellij/compiler/CompilerManagerImpl.java
java/compiler/impl/src/com/intellij/compiler/classFilesIndex/chainsSearch/completion/lookup/ChainCompletionNewVariableLookupElement.java
java/debugger/impl/src/com/intellij/debugger/impl/GenericDebuggerParametersRunnerConfigurable.java
java/execution/impl/src/com/intellij/execution/applet/AppletConfigurable.java
java/execution/impl/src/com/intellij/execution/application/ApplicationConfigurable.java
java/execution/impl/src/com/intellij/execution/jar/JarApplicationConfigurable.java
java/execution/impl/src/com/intellij/execution/remote/RemoteConfigurable.java
java/execution/impl/src/com/intellij/execution/scratch/JavaScratchConfigurable.java
java/idea-ui/src/com/intellij/codeInsight/daemon/impl/LibrarySourceNotificationProvider.kt
java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/ControlFlowAnalyzer.java
java/java-analysis-impl/src/com/intellij/codeInspection/miscGenerics/SuspiciousCollectionsMethodCallsInspection.java
java/java-impl/src/com/intellij/codeInsight/daemon/quickFix/CreateClassOrPackageFix.java
java/java-impl/src/com/intellij/codeInsight/generation/GenerateMembersHandlerBase.java
java/java-impl/src/com/intellij/codeInsight/hints/JavaHintUtils.kt [new file with mode: 0644]
java/java-impl/src/com/intellij/codeInsight/hints/JavaInlayParameterHintsProvider.kt
java/java-impl/src/com/intellij/codeInsight/hints/JavaParameterHintManager.java [deleted file]
java/java-impl/src/com/intellij/codeInspection/streamMigration/ReplaceWithCollectFix.java
java/java-impl/src/com/intellij/codeInspection/streamMigration/StreamApiMigrationInspection.java
java/java-impl/src/com/intellij/codeInspection/streamToLoop/TerminalOperation.java
java/java-impl/src/com/intellij/refactoring/inline/InlineLocalHandler.java
java/java-psi-api/src/com/intellij/psi/LambdaUtil.java
java/java-psi-api/src/com/intellij/psi/util/RedundantCastUtil.java
java/java-runtime/src/com/intellij/rt/execution/junit/ComparisonFailureData.java
java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/highlighting/LambdaContext.java
java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/streamApiMigration/afterCollectToMap.java [new file with mode: 0644]
java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/streamApiMigration/afterCollectToMapPut.java [new file with mode: 0644]
java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/streamApiMigration/afterCollectToMapPutIfAbsent.java [new file with mode: 0644]
java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/streamApiMigration/afterGroupingByArrayList.java [new file with mode: 0644]
java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/streamApiMigration/afterGroupingByCustomCollection.java [new file with mode: 0644]
java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/streamApiMigration/afterGroupingByDownstream.java [new file with mode: 0644]
java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/streamApiMigration/afterGroupingBySimple.java [new file with mode: 0644]
java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/streamApiMigration/beforeCollectToMap.java [new file with mode: 0644]
java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/streamApiMigration/beforeCollectToMapPut.java [new file with mode: 0644]
java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/streamApiMigration/beforeCollectToMapPutIfAbsent.java [new file with mode: 0644]
java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/streamApiMigration/beforeCollectToMapPutInvalid.java [new file with mode: 0644]
java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/streamApiMigration/beforeGroupingByArrayList.java [new file with mode: 0644]
java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/streamApiMigration/beforeGroupingByCustomCollection.java [new file with mode: 0644]
java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/streamApiMigration/beforeGroupingByDownstream.java [new file with mode: 0644]
java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/streamApiMigration/beforeGroupingBySimple.java [new file with mode: 0644]
java/java-tests/testData/inspection/suspiciousCalls/NewExpressionPassedToMapContains.java [new file with mode: 0644]
java/java-tests/testData/refactoring/inlineLocal/InlineFromTryCatchAvailable.java
java/java-tests/testData/refactoring/inlineLocal/InlineFromTryCatchAvailable.java.after
java/java-tests/testSrc/com/intellij/codeInsight/daemon/inlays/JavaParameterNameHintsTest.kt
java/java-tests/testSrc/com/intellij/codeInspection/SuspiciousCollectionMethodCallsTest.java
java/testFramework/src/com/intellij/codeInsight/CodeInsightTestCase.java
json/src/com/jetbrains/jsonSchema/impl/JsonSchemaConflictNotificationProvider.java
platform/analysis-api/src/com/intellij/lang/annotation/HighlightSeverity.java
platform/core-impl/src/com/intellij/openapi/application/impl/ApplicationInfoImpl.java
platform/diff-impl/src/com/intellij/diff/tools/util/DiffNotifications.java
platform/editor-ui-api/src/com/intellij/openapi/actionSystem/ex/AnActionListener.java
platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/RemoteExternalSystemCommunicationManager.java
platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/execution/ExternalSystemRunConfigurationEditor.java
platform/lang-api/src/com/intellij/execution/configurations/UnknownRunConfiguration.java
platform/lang-impl/src/com/intellij/application/options/DefaultSchemeActions.java [new file with mode: 0644]
platform/lang-impl/src/com/intellij/application/options/codeStyle/CodeStyleSchemeExporterUI.java [deleted file]
platform/lang-impl/src/com/intellij/application/options/codeStyle/CodeStyleSchemesActions.java [new file with mode: 0644]
platform/lang-impl/src/com/intellij/application/options/codeStyle/CodeStyleSchemesPanel.form
platform/lang-impl/src/com/intellij/application/options/codeStyle/CodeStyleSchemesPanel.java
platform/lang-impl/src/com/intellij/application/options/codeStyle/ManageCodeStyleSchemesDialog.form [deleted file]
platform/lang-impl/src/com/intellij/application/options/codeStyle/ManageCodeStyleSchemesDialog.java [deleted file]
platform/lang-impl/src/com/intellij/codeInsight/actions/MultiCaretCodeInsightAction.java
platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/EditorTracker.java
platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/StatusBarUpdater.java
platform/lang-impl/src/com/intellij/codeInsight/documentation/DocumentationManager.java
platform/lang-impl/src/com/intellij/codeInsight/editorActions/EmacsStyleIndentAction.java
platform/lang-impl/src/com/intellij/codeInsight/editorActions/EndHandler.java
platform/lang-impl/src/com/intellij/codeInsight/editorActions/FixDocCommentAction.java
platform/lang-impl/src/com/intellij/codeInsight/generation/CommentByBlockCommentHandler.java
platform/lang-impl/src/com/intellij/codeInsight/generation/CommentByLineCommentHandler.java
platform/lang-impl/src/com/intellij/codeInsight/highlighting/BraceHighlighter.java
platform/lang-impl/src/com/intellij/codeInsight/intention/impl/FileLevelIntentionComponent.java
platform/lang-impl/src/com/intellij/codeInsight/navigation/CtrlMouseHandler.java
platform/lang-impl/src/com/intellij/codeInsight/unwrap/UnwrapHandler.java
platform/lang-impl/src/com/intellij/codeInspection/actions/CodeInspectionAction.java
platform/lang-impl/src/com/intellij/diagnostic/logging/LogConfigurationPanel.java
platform/lang-impl/src/com/intellij/execution/compound/CompoundRunConfigurationSettingsEditor.java
platform/lang-impl/src/com/intellij/execution/console/LanguageConsoleImpl.java
platform/lang-impl/src/com/intellij/execution/impl/ConfigurationSettingsEditor.java
platform/lang-impl/src/com/intellij/execution/impl/ConfigurationSettingsEditorWrapper.java
platform/lang-impl/src/com/intellij/ide/GeneratedSourceFileChangeTrackerImpl.java
platform/lang-impl/src/com/intellij/ide/favoritesTreeView/actions/AddAllOpenFilesToFavorites.java
platform/lang-impl/src/com/intellij/ide/navigationToolbar/NavBarListener.java
platform/lang-impl/src/com/intellij/ide/scratch/ScratchFileServiceImpl.java
platform/lang-impl/src/com/intellij/ide/todo/CurrentFileTodosPanel.java
platform/lang-impl/src/com/intellij/ide/util/FileStructurePopup.java
platform/lang-impl/src/com/intellij/platform/templates/ManageProjectTemplatesDialog.java
platform/lang-impl/src/com/intellij/psi/impl/source/codeStyle/CodeStyleSchemeImpl.java
platform/lang-impl/src/com/intellij/psi/impl/source/codeStyle/CodeStyleSchemesImpl.java
platform/lang-impl/src/com/intellij/psi/impl/source/codeStyle/PersistableCodeStyleSchemes.java
platform/lang-impl/src/com/intellij/refactoring/BaseRefactoringProcessor.java
platform/lang-impl/src/com/intellij/ui/ManageSchemesComboAction.java [new file with mode: 0644]
platform/lang-impl/testSources/com/intellij/openapi/wm/impl/ToolWindowManagerTestCase.java
platform/platform-api/src/com/intellij/ide/GeneralSettings.java
platform/platform-api/src/com/intellij/openapi/editor/actionSystem/EditorWriteActionHandler.java
platform/platform-api/src/com/intellij/openapi/fileEditor/FileEditorManagerAdapter.java
platform/platform-api/src/com/intellij/openapi/fileEditor/FileEditorManagerListener.java
platform/platform-api/src/com/intellij/openapi/options/CompositeSettingsEditor.java
platform/platform-api/src/com/intellij/openapi/options/SettingsEditorGroup.java
platform/platform-api/src/com/intellij/openapi/options/SettingsEditorWrapper.java
platform/platform-api/src/com/intellij/openapi/ui/DialogWrapper.java
platform/platform-api/src/com/intellij/openapi/ui/TestDialog.java
platform/platform-api/src/com/intellij/ui/AutoScrollFromSourceHandler.java
platform/platform-api/src/com/intellij/ui/EditorNotificationPanel.java
platform/platform-impl/src/com/intellij/codeInsight/hint/HintManagerImpl.java
platform/platform-impl/src/com/intellij/ide/GeneralSettingsConfigurable.java
platform/platform-impl/src/com/intellij/ide/IdeEventQueue.java
platform/platform-impl/src/com/intellij/ide/highlighter/custom/impl/CustomFileTypeEditor.java
platform/platform-impl/src/com/intellij/internal/TestWriteActionUnderProgress.java [new file with mode: 0644]
platform/platform-impl/src/com/intellij/openapi/application/impl/ApplicationImpl.java
platform/platform-impl/src/com/intellij/openapi/editor/impl/CaretImpl.java
platform/platform-impl/src/com/intellij/openapi/editor/impl/EditorImpl.java
platform/platform-impl/src/com/intellij/openapi/editor/impl/SoftWrapModelImpl.java
platform/platform-impl/src/com/intellij/openapi/editor/impl/softwrap/mapping/SoftWrapApplianceManager.java
platform/platform-impl/src/com/intellij/openapi/editor/impl/view/TextLayoutCache.java
platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/EditorComposite.java
platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/EditorHistoryManager.java
platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/FileEditorManagerImpl.java
platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/IdeDocumentHistoryImpl.java
platform/platform-impl/src/com/intellij/openapi/progress/util/PotemkinProgress.java [new file with mode: 0644]
platform/platform-impl/src/com/intellij/openapi/progress/util/ProgressDialog.java
platform/platform-impl/src/com/intellij/openapi/progress/util/ProgressWindow.java
platform/platform-impl/src/com/intellij/openapi/ui/FrameWrapper.java
platform/platform-impl/src/com/intellij/openapi/ui/impl/DialogWrapperPeerImpl.java
platform/platform-impl/src/com/intellij/openapi/wm/impl/DesktopLayout.java
platform/platform-impl/src/com/intellij/openapi/wm/impl/IdeGlassPaneImpl.java
platform/platform-impl/src/com/intellij/openapi/wm/impl/ToolWindowManagerImpl.java
platform/platform-impl/src/com/intellij/openapi/wm/impl/WindowManagerImpl.java
platform/platform-impl/src/com/intellij/openapi/wm/impl/content/TabbedContentTabLabel.java
platform/platform-impl/src/com/intellij/openapi/wm/impl/status/EditorBasedWidget.java
platform/platform-impl/src/com/intellij/openapi/wm/impl/status/ToggleReadOnlyAttributePanel.java
platform/platform-impl/src/com/intellij/openapi/wm/impl/welcomeScreen/FlatWelcomeFrame.java
platform/platform-impl/src/com/intellij/ui/EditorNotificationsImpl.java
platform/platform-impl/src/com/intellij/ui/FocusTrackback.java
platform/platform-impl/src/com/intellij/ui/LightweightHint.java
platform/platform-impl/src/com/intellij/ui/content/impl/TabbedContentImpl.java
platform/platform-impl/src/com/intellij/ui/popup/AbstractPopup.java
platform/platform-impl/src/com/intellij/ui/popup/PopupComponent.java
platform/platform-impl/src/com/intellij/util/ui/SwingHelper.java
platform/platform-resources/src/META-INF/LangExtensions.xml
platform/platform-resources/src/componentSets/WindowManagement.xml
platform/platform-resources/src/idea/ApplicationInfo.xsd
platform/platform-resources/src/idea/PlatformActions.xml
platform/remote-servers/impl/src/com/intellij/remoteServer/util/CloudDeploymentNameEditor.java
platform/script-debugger/debugger-ui/src/org/jetbrains/debugger/RemoteDebugConfiguration.java
platform/smRunner/src/com/intellij/execution/testframework/sm/runner/events/TestFailedEvent.java
platform/testFramework/src/com/intellij/testFramework/LightPlatformCodeInsightTestCase.java
platform/testFramework/src/com/intellij/testFramework/fixtures/impl/CodeInsightTestFixtureImpl.java
platform/vcs-impl/src/com/intellij/openapi/vcs/annotate/AnnotationsPreloader.java
platform/vcs-impl/src/com/intellij/openapi/vcs/changes/committed/OutdatedVersionNotifier.java
platform/vcs-log/impl/src/com/intellij/vcs/log/data/VcsLogFiltererImpl.java
platform/vcs-log/impl/src/com/intellij/vcs/log/data/VisiblePackBuilder.java
platform/vcs-log/impl/src/com/intellij/vcs/log/impl/VcsLogFilterCollectionImpl.java
platform/vcs-log/impl/src/com/intellij/vcs/log/impl/VcsLogUtil.java
platform/vcs-log/impl/src/com/intellij/vcs/log/ui/filter/VcsLogClassicFilterUi.java
platform/vcs-log/impl/src/com/intellij/vcs/log/ui/frame/VcsLogGraphTable.java
platform/vcs-log/impl/src/com/intellij/vcs/log/ui/render/GraphCommitCell.java
platform/vcs-log/impl/test/com/intellij/vcs/log/VcsLogUserFilterTest.java
platform/vcs-log/impl/test/com/intellij/vcs/log/data/VisiblePackBuilderTest.kt
platform/xdebugger-impl/src/com/intellij/xdebugger/impl/XDebuggerManagerImpl.java
plugins/InspectionGadgets/src/com/siyeh/ig/junit/JUnit5ConverterInspection.java
plugins/ant/src/com/intellij/lang/ant/config/execution/AntRunConfiguration.java
plugins/coverage/src/com/intellij/execution/configurations/coverage/CoverageConfigurable.java
plugins/devkit/src/run/PluginRunConfigurationEditor.java
plugins/editorconfig/src/org/editorconfig/plugincomponents/EditorConfigNotifierProvider.java
plugins/git4idea/tests/git4idea/log/GitLogProviderTest.java
plugins/groovy/src/org/jetbrains/plugins/groovy/console/GroovyConsole.java
plugins/groovy/src/org/jetbrains/plugins/groovy/grape/GrabDependencies.java
plugins/groovy/src/org/jetbrains/plugins/groovy/shell/GroovyShellRunnerImpl.java
plugins/junit/src/com/intellij/execution/junit2/configuration/JUnitConfigurable.java
plugins/maven/src/main/java/org/jetbrains/idea/maven/execution/MavenRunnerParametersSettingEditor.java
plugins/maven/src/main/java/org/jetbrains/idea/maven/execution/MavenRunnerSettingsEditor.java
plugins/maven/src/main/java/org/jetbrains/idea/maven/server/MavenServerManager.java
plugins/properties/src/com/intellij/lang/properties/editor/ResourceBundleEditor.java
plugins/testng/src/com/theoryinpractice/testng/configuration/TestNGConfigurationEditor.java
plugins/ui-designer/src/com/intellij/uiDesigner/propertyInspector/PropertyInspectorTable.java
plugins/xpath/xpath-lang/src/org/intellij/lang/xpath/xslt/run/XsltRunSettingsEditor.java
python/educational-core/course-creator/src/com/jetbrains/edu/coursecreator/CCSubtaskEditorNotificationProvider.java
python/educational-core/student/src/com/jetbrains/edu/learning/stepic/StepicAdaptiveReactionsPanel.java
python/educational-core/student/src/com/jetbrains/edu/learning/ui/StudyTestResultsToolWindowFactory.kt
python/educational-python/course-creator-python/course-creator-python.iml
python/educational-python/course-creator-python/src/com/jetbrains/edu/coursecreator/CreateFromArchiveProjectStep.java
python/educational-python/course-creator-python/src/com/jetbrains/edu/coursecreator/run/PyCCSettingsEditor.java
python/educational-python/student-python/src/com/jetbrains/edu/learning/actions/PyStudyIntroductionCourseAction.java
python/educational-python/student-python/student-python.iml
python/ide/src/META-INF/pycharm-core.xml
python/ide/src/com/jetbrains/python/newProject/PyCharmNewProjectDialog.java
python/ipnb/src/org/jetbrains/plugins/ipnb/protocol/IpnbConnection.java
python/python-community-configure/src/com/jetbrains/python/newProject/steps/PluginSpecificProjectsStep.java [moved from python/ide/src/com/jetbrains/python/newProject/actions/PluginSpecificProjectsStep.java with 95% similarity]
python/python-community-configure/src/com/jetbrains/python/newProject/steps/ProjectSpecificSettingsStep.java [moved from python/ide/src/com/jetbrains/python/newProject/actions/ProjectSpecificSettingsStep.java with 99% similarity]
python/python-community-configure/src/com/jetbrains/python/newProject/steps/PyCharmNewProjectStep.java [moved from python/ide/src/com/jetbrains/python/newProject/actions/PyCharmNewProjectStep.java with 96% similarity]
python/python-community-configure/src/com/jetbrains/python/newProject/steps/PyRemotePathField.form [moved from python/ide/src/com/jetbrains/python/newProject/actions/PyRemotePathField.form with 95% similarity]
python/python-community-configure/src/com/jetbrains/python/newProject/steps/PyRemotePathField.java [moved from python/ide/src/com/jetbrains/python/newProject/actions/PyRemotePathField.java with 97% similarity]
python/python-community-configure/src/com/jetbrains/python/newProject/steps/PythonBaseProjectGenerator.java [moved from python/ide/src/com/jetbrains/python/newProject/PythonBaseProjectGenerator.java with 94% similarity]
python/python-community-configure/src/com/jetbrains/python/newProject/steps/PythonGenerateProjectCallback.java [moved from python/ide/src/com/jetbrains/python/newProject/actions/PythonGenerateProjectCallback.java with 99% similarity]
python/python-community-configure/src/com/jetbrains/python/newProject/steps/PythonSdkChooserCombo.java [moved from python/ide/src/com/jetbrains/python/PythonSdkChooserCombo.java with 97% similarity]
python/python-rest/src/com/jetbrains/rest/run/RestConfigurationEditor.java
python/src/com/jetbrains/python/newProject/PythonProjectGenerator.java
python/src/com/jetbrains/python/run/PythonExtendedConfigurationEditor.java
python/src/com/jetbrains/python/run/PythonRunConfigurationEditor.java
python/src/com/jetbrains/python/testing/attest/PythonAtTestRunConfigurationEditor.java
python/src/com/jetbrains/python/testing/doctest/PythonDocTestRunConfigurationEditor.java
python/src/com/jetbrains/python/testing/nosetest/PythonNoseTestRunConfigurationEditor.java
python/src/com/jetbrains/python/testing/pytest/PyTestConfigurationEditor.java
python/src/com/jetbrains/python/testing/tox/PyToxConfigurationSettings.java
python/src/com/jetbrains/python/testing/unittest/PythonUnitTestRunConfigurationEditor.java
python/testSrc/com/jetbrains/python/testing/JythonUnitTestUtil.java [deleted file]
xml/dom-openapi/src/com/intellij/util/xml/ui/PerspectiveFileEditor.java
xml/impl/src/com/intellij/xml/breadcrumbs/BreadcrumbsInitializingActivity.java

index 8e437272bce90778dcaeed859d00ee28cafbde55..2bb3f9d04790db6a3086bd6f128324482a34563d 100644 (file)
@@ -4114,7 +4114,6 @@ com/intellij/util/indexing/UnindexedFilesUpdater.class:/lib/idea.jar
 com/intellij/util/indexing/FileBasedIndexProjectHandler$1.class:/lib/idea.jar
 com/intellij/codeInsight/navigation/CtrlMouseHandler$1.class:/lib/idea.jar
 com/intellij/codeInsight/navigation/CtrlMouseHandler$2.class:/lib/idea.jar
-com/intellij/openapi/fileEditor/FileEditorManagerAdapter.class:/lib/openapi.jar
 com/intellij/codeInsight/navigation/CtrlMouseHandler$3.class:/lib/idea.jar
 com/intellij/codeInsight/navigation/CtrlMouseHandler$5.class:/lib/idea.jar
 com/intellij/codeInsight/navigation/CtrlMouseHandler$6.class:/lib/idea.jar
index 1876f91ab744874f3f32211e2e1081816f44d0f1..eb669501620bb8435209b23f3ad8c5cd37da7405 100644 (file)
@@ -30,10 +30,7 @@ import com.intellij.openapi.fileTypes.StdFileTypes;
 import com.intellij.openapi.module.Module;
 import com.intellij.openapi.module.ModuleType;
 import com.intellij.openapi.project.Project;
-import com.intellij.openapi.projectRoots.JavaSdkType;
-import com.intellij.openapi.projectRoots.JavaSdkVersion;
-import com.intellij.openapi.projectRoots.Sdk;
-import com.intellij.openapi.projectRoots.SdkTypeId;
+import com.intellij.openapi.projectRoots.*;
 import com.intellij.openapi.util.Disposer;
 import com.intellij.openapi.util.Pair;
 import com.intellij.openapi.util.io.FileUtil;
@@ -351,6 +348,18 @@ public class CompilerManagerImpl extends CompilerManager {
     final SdkTypeId type = sdk.getSdkType();
     if (type instanceof JavaSdkType) {
       javaHome = sdk.getHomePath();
+      if (javaHome != null) {
+        final JavaSdk javaSdk = JavaSdk.getInstance();
+        if (!javaSdk.isValidSdkHome(javaHome)) {
+          // this can be a java-dependent SDK, implementing JavaSdkType
+          // hack, because there is no direct way to obtain the java sdk, this sdk depends on 
+          final String binPath = ((JavaSdkType)type).getBinPath(sdk);
+          javaHome = binPath != null? new File(binPath).getParent() : null;
+          if (javaHome != null && !javaSdk.isValidSdkHome(javaHome)) {
+            javaHome = null;
+          }
+        }
+      }
     }
     if (javaHome == null) {
       throw new IOException("Was not able to determine JDK for project " + myProject.getName());
index 6e941d2dfb287bfc27901e149a7b3d05efbdf17b..c2f0fadb87422a50ef98bbc94f318485ca1e5742 100644 (file)
@@ -19,7 +19,6 @@ import com.intellij.codeInsight.completion.InsertionContext;
 import com.intellij.codeInsight.lookup.LookupElement;
 import com.intellij.codeInsight.lookup.LookupElementDecorator;
 import com.intellij.codeInsight.lookup.LookupElementPresentation;
-import com.intellij.openapi.command.WriteCommandAction;
 import com.intellij.openapi.diagnostic.Logger;
 import com.intellij.openapi.editor.RangeMarker;
 import com.intellij.openapi.project.Project;
@@ -76,13 +75,8 @@ public class ChainCompletionNewVariableLookupElement extends LookupElementDecora
     final Ref<PsiElement> insertedStatementRef = Ref.create();
     final PsiElementFactory elementFactory = JavaPsiFacade.getElementFactory(project);
     context.commitDocument();
-    new WriteCommandAction.Simple(project, file) {
-      @Override
-      protected void run() throws Throwable {
-        final PsiStatement statementFromText = elementFactory.createStatementFromText(String.format("%s %s = null;", myPsiClass.getName(), myNewVarName), null);
-        insertedStatementRef.set(codeBlock.addBefore(statementFromText, statement));
-      }
-    }.execute();
+    final PsiStatement statementFromText = elementFactory.createStatementFromText(String.format("%s %s = null;", myPsiClass.getName(), myNewVarName), null);
+    insertedStatementRef.set(codeBlock.addBefore(statementFromText, statement));
     final PsiLiteralExpression nullKeyword = findNull(insertedStatementRef.get());
     PsiDocumentManager.getInstance(context.getProject()).doPostponedOperationsAndUnblockDocument(context.getDocument());
     context.getDocument().insertString(rangeMarker.getStartOffset(), myNewVarName + ".");
index baf7072785b9b9482ae00808be88da2bebe16d9a..b027a0e629d863b31287aa4e562f39f7324d0421 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2014 JetBrains s.r.o.
+ * Copyright 2000-2016 JetBrains s.r.o.
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -98,7 +98,7 @@ public class GenericDebuggerParametersRunnerConfigurable extends SettingsEditor<
   }
 
   @Override
-  public void resetEditorFrom(GenericDebuggerRunnerSettings runnerSettings) {
+  public void resetEditorFrom(@NotNull GenericDebuggerRunnerSettings runnerSettings) {
     setIsLocal(runnerSettings.LOCAL);
     setTransport(runnerSettings.getTransport());
     setPort(StringUtil.notNullize(runnerSettings.getDebugPort()));
@@ -182,7 +182,7 @@ public class GenericDebuggerParametersRunnerConfigurable extends SettingsEditor<
   }
 
   @Override
-  public void applyEditorTo(GenericDebuggerRunnerSettings runnerSettings) throws ConfigurationException {
+  public void applyEditorTo(@NotNull GenericDebuggerRunnerSettings runnerSettings) throws ConfigurationException {
     runnerSettings.LOCAL = myIsLocal;
     checkPort();
     runnerSettings.setDebugPort(getPort());
index 6c1c8f99a0a552f80e1fdf72869f05d81aa1b159..a4f26ae79e560885eb598c3d8f5469a6ed010744 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2009 JetBrains s.r.o.
+ * Copyright 2000-2016 JetBrains s.r.o.
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -18,10 +18,10 @@ package com.intellij.execution.applet;
 import com.intellij.application.options.ModulesComboBox;
 import com.intellij.execution.ExecutionBundle;
 import com.intellij.execution.impl.CheckableRunConfigurationEditor;
-import com.intellij.execution.ui.DefaultJreSelector;
-import com.intellij.execution.ui.JrePathEditor;
 import com.intellij.execution.ui.ClassBrowser;
 import com.intellij.execution.ui.ConfigurationModuleSelector;
+import com.intellij.execution.ui.DefaultJreSelector;
+import com.intellij.execution.ui.JrePathEditor;
 import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory;
 import com.intellij.openapi.options.SettingsEditor;
 import com.intellij.openapi.project.Project;
@@ -216,14 +216,14 @@ public class AppletConfigurable extends SettingsEditor<AppletConfiguration> impl
     return s.length() == 0 ? null : s.replace(File.separatorChar, '/');
   }
 
-  public void applyEditorTo(final AppletConfiguration configuration) {
+  public void applyEditorTo(@NotNull final AppletConfiguration configuration) {
     checkEditorData(configuration);
     myTable.stopEditing();
     final List<AppletConfiguration.AppletParameter> params = cloneParameters(myParameters.getItems());
     configuration.setAppletParameters(params);
   }
 
-  public void resetEditorFrom(final AppletConfiguration configuration) {
+  public void resetEditorFrom(@NotNull final AppletConfiguration configuration) {
     getClassNameComponent().setText(configuration.MAIN_CLASS_NAME);
     String presentableHtmlName = configuration.HTML_FILE_NAME;
     if (presentableHtmlName != null && !StringUtil.startsWithIgnoreCase(presentableHtmlName, HTTP_PREFIX)) {
index 25ca23b0a5b42c882b0822adbc39c9b2d3a8584b..081a97ff6303f4379c021c032607586cb6d98b33 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2009 JetBrains s.r.o.
+ * Copyright 2000-2016 JetBrains s.r.o.
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -68,7 +68,7 @@ public class ApplicationConfigurable extends SettingsEditor<ApplicationConfigura
     myAnchor = UIUtil.mergeComponentsWithAnchor(myMainClass, myCommonProgramParameters, myJrePathEditor, myModule);
   }
 
-  public void applyEditorTo(final ApplicationConfiguration configuration) throws ConfigurationException {
+  public void applyEditorTo(@NotNull final ApplicationConfiguration configuration) throws ConfigurationException {
     myCommonProgramParameters.applyTo(configuration);
     myModuleSelector.applyTo(configuration);
     final String className = getMainClassField().getText();
@@ -81,7 +81,7 @@ public class ApplicationConfigurable extends SettingsEditor<ApplicationConfigura
     updateShowSwingInspector(configuration);
   }
 
-  public void resetEditorFrom(final ApplicationConfiguration configuration) {
+  public void resetEditorFrom(@NotNull final ApplicationConfiguration configuration) {
     myCommonProgramParameters.reset(configuration);
     myModuleSelector.reset(configuration);
     getMainClassField().setText(configuration.MAIN_CLASS_NAME != null ? configuration.MAIN_CLASS_NAME.replaceAll("\\$", "\\.") : "");
index ba37521cad1d6de71b6e0c6a7514d696c8e4a4f3..53c95533c3379340f50a6d580901d5159b5605e0 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2014 JetBrains s.r.o.
+ * Copyright 2000-2016 JetBrains s.r.o.
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -16,9 +16,9 @@
 package com.intellij.execution.jar;
 
 import com.intellij.application.options.ModulesComboBox;
+import com.intellij.execution.ui.CommonJavaParametersPanel;
 import com.intellij.execution.ui.DefaultJreSelector;
 import com.intellij.execution.ui.JrePathEditor;
-import com.intellij.execution.ui.CommonJavaParametersPanel;
 import com.intellij.openapi.fileChooser.FileChooserDescriptor;
 import com.intellij.openapi.options.ConfigurationException;
 import com.intellij.openapi.options.SettingsEditor;
@@ -52,7 +52,7 @@ public class JarApplicationConfigurable extends SettingsEditor<JarApplicationCon
     myJrePathEditor.setDefaultJreSelector(DefaultJreSelector.fromModuleDependencies(modulesComboBox, true));
   }
 
-  public void applyEditorTo(final JarApplicationConfiguration configuration) throws ConfigurationException {
+  public void applyEditorTo(@NotNull final JarApplicationConfiguration configuration) throws ConfigurationException {
     myCommonProgramParameters.applyTo(configuration);
     configuration.setAlternativeJrePath(myJrePathEditor.getJrePathOrName());
     configuration.setAlternativeJrePathEnabled(myJrePathEditor.isAlternativeJreSelected());
@@ -60,7 +60,7 @@ public class JarApplicationConfigurable extends SettingsEditor<JarApplicationCon
     configuration.setModule(myModuleComponent.getComponent().getSelectedModule());
   }
 
-  public void resetEditorFrom(final JarApplicationConfiguration configuration) {
+  public void resetEditorFrom(@NotNull final JarApplicationConfiguration configuration) {
     myCommonProgramParameters.reset(configuration);
     myJarPathComponent.getComponent().setText(FileUtil.toSystemDependentName(configuration.getJarPath()));
     myJrePathEditor.setPathOrName(configuration.getAlternativeJrePath(), configuration.isAlternativeJrePathEnabled()
index f40c81bac8ba409e4c11625907a0658ba5dae8d4..352a4ba424e471a4b2067cdd1849d3b5f4d6843d 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2009 JetBrains s.r.o.
+ * Copyright 2000-2016 JetBrains s.r.o.
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -150,7 +150,7 @@ public class RemoteConfigurable extends SettingsEditor<RemoteConfiguration> {
     myModuleSelector.applyTo(configuration);
   }
 
-  public void resetEditorFrom(final RemoteConfiguration configuration) {
+  public void resetEditorFrom(@NotNull final RemoteConfiguration configuration) {
     if (!SystemInfo.isWindows) {
       configuration.USE_SOCKET_TRANSPORT = true;
       myRbShmem.setEnabled(false);
index 9522cd1c12c80882668cb0bb0626c54f09d97808..eeaac86b4b3d0ec5e877c8f47f08d03b9e050d73 100644 (file)
@@ -42,6 +42,7 @@ import org.jetbrains.annotations.Nullable;
 
 import javax.swing.*;
 import java.awt.*;
+import java.awt.GridBagConstraints;
 import java.awt.event.ActionEvent;
 import java.awt.event.ActionListener;
 
@@ -114,7 +115,7 @@ public class JavaScratchConfigurable extends SettingsEditor<JavaScratchConfigura
   }
 
   @Override
-  public void applyEditorTo(JavaScratchConfiguration configuration) throws ConfigurationException {
+  public void applyEditorTo(@NotNull JavaScratchConfiguration configuration) throws ConfigurationException {
     myCommonProgramParameters.applyTo(configuration);
     myModuleSelector.applyTo(configuration);
     configuration.MAIN_CLASS_NAME = myMainClass.getComponent().getText().trim();
@@ -132,7 +133,7 @@ public class JavaScratchConfigurable extends SettingsEditor<JavaScratchConfigura
   }
 
   @Override
-  public void resetEditorFrom(JavaScratchConfiguration configuration) {
+  public void resetEditorFrom(@NotNull JavaScratchConfiguration configuration) {
     myCommonProgramParameters.reset(configuration);
     myModuleSelector.reset(configuration);
     myMainClass.getComponent().setText(configuration.MAIN_CLASS_NAME != null ? configuration.MAIN_CLASS_NAME.replaceAll("\\$", "\\.") : "");
index 3034e708d571c06178a8b8eb8b7d84c5b0a2c51e..23c379c4eb647b3d5d0345e39f8c314de06eee89 100644 (file)
@@ -59,8 +59,7 @@ class LibrarySourceNotificationProvider(private val project: Project, notificati
         if (offender != null) {
           val clsFile = offender.originalElement.containingFile?.virtualFile
           if (clsFile != null && !clsFile.path.matches(ANDROID_SDK_PATTERN)) {
-            val panel = EditorNotificationPanel()
-            panel.background(LightColors.RED)
+            val panel = EditorNotificationPanel(LightColors.RED)
             panel.setText(ProjectBundle.message("library.source.mismatch", offender.name))
             panel.createActionLabel(ProjectBundle.message("library.source.open.class"), {
               OpenFileDescriptor(project, clsFile, -1).navigate(true)
index c23def894c6523e265d8b910aa00d7ad27a577ea..4f0bc88b373f658d29710267dd8369f385ffa051 100644 (file)
@@ -862,17 +862,17 @@ public class ControlFlowAnalyzer extends JavaElementVisitor {
     if (condition != null) {
       condition.accept(this);
       generateBoxingUnboxingInstructionFor(condition, PsiType.BOOLEAN);
-      addInstruction(new ConditionalGotoInstruction(getEndOffset(statement), true, condition));
+    } else {
+      pushUnknown();
     }
+    addInstruction(new ConditionalGotoInstruction(getEndOffset(statement), true, condition));
 
     PsiStatement body = statement.getBody();
     if (body != null) {
       body.accept(this);
     }
 
-    if (condition != null) {
-      addInstruction(new GotoInstruction(getStartOffset(statement)));
-    }
+    addInstruction(new GotoInstruction(getStartOffset(statement)));
 
     finishElement(statement);
   }
index e31f8c45d913aa5232cc2becf006aee159f36a7c..77b988aae62eb5199c900e30d4b39cd48c50a258 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2013 JetBrains s.r.o.
+ * Copyright 2000-2016 JetBrains s.r.o.
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -96,9 +96,10 @@ public class SuspiciousCollectionsMethodCallsInspection extends BaseJavaBatchLoc
     if (args.length != 1) return null;
 
     PsiType argType = args[0].getType();
+    boolean exactType = args[0] instanceof PsiNewExpression;
     final String plainMessage = SuspiciousMethodCallUtil
-      .getSuspiciousMethodCallMessage(methodCall, args[0], argType, reportConvertibleMethodCalls, patternMethods, indices);
-    if (plainMessage != null) {
+      .getSuspiciousMethodCallMessage(methodCall, args[0], argType, exactType || reportConvertibleMethodCalls, patternMethods, indices);
+    if (plainMessage != null && !exactType) {
       final PsiType dfaType = GuessManager.getInstance(methodCall.getProject()).getControlFlowExpressionType(args[0]);
       if (dfaType != null && SuspiciousMethodCallUtil
                                .getSuspiciousMethodCallMessage(methodCall, args[0], dfaType, reportConvertibleMethodCalls, patternMethods, indices) == null) {
index 1611415f7842254a917d52c834233aa6c7e1b3fc..8689c7d9a560dbd7a157df107a317ca183fc20a1 100644 (file)
@@ -21,8 +21,7 @@ import com.intellij.codeInsight.daemon.impl.quickfix.CreateFromUsageUtils;
 import com.intellij.codeInspection.LocalQuickFixAndIntentionActionOnPsiElement;
 import com.intellij.ide.util.DirectoryChooserUtil;
 import com.intellij.openapi.application.ApplicationManager;
-import com.intellij.openapi.application.Result;
-import com.intellij.openapi.command.WriteCommandAction;
+import com.intellij.openapi.application.WriteAction;
 import com.intellij.openapi.diagnostic.Logger;
 import com.intellij.openapi.editor.Editor;
 import com.intellij.openapi.module.Module;
@@ -129,14 +128,9 @@ public class CreateClassOrPackageFix extends LocalQuickFixAndIntentionActionOnPs
                      @NotNull final PsiElement startElement,
                      @NotNull PsiElement endElement) {
     if (isAvailable(project, null, file)) {
-      new WriteCommandAction(project) {
-        @Override
-        protected void run(@NotNull Result result) throws Throwable {
-          final PsiDirectory directory = chooseDirectory(project, file);
-          if (directory == null) return;
-          ApplicationManager.getApplication().runWriteAction(() -> doCreate(directory, startElement));
-        }
-      }.execute();
+      PsiDirectory directory = chooseDirectory(project, file);
+      if (directory == null) return;
+      WriteAction.run(() -> doCreate(directory, startElement));
     }
   }
 
index d17964ae44a226d8c04be4a1395257ce88dc89c6..0d3a19fbe6ac6e953382b6527d50c8c0a7bbf057 100644 (file)
@@ -27,6 +27,8 @@ import com.intellij.lang.ContextAwareActionHandler;
 import com.intellij.openapi.actionSystem.DataContext;
 import com.intellij.openapi.application.ApplicationManager;
 import com.intellij.openapi.application.Result;
+import com.intellij.openapi.application.WriteAction;
+import com.intellij.openapi.command.CommandProcessor;
 import com.intellij.openapi.command.WriteCommandAction;
 import com.intellij.openapi.diagnostic.Logger;
 import com.intellij.openapi.editor.Document;
@@ -84,7 +86,7 @@ public abstract class GenerateMembersHandlerBase implements CodeInsightActionHan
       final ClassMember[] members = chooseOriginalMembers(aClass, project, editor);
       if (members == null) return;
 
-      WriteCommandAction.runWriteCommandAction(project, () -> {
+      CommandProcessor.getInstance().executeCommand(project, () -> {
         final int offset = editor.getCaretModel().getOffset();
         try {
           doGenerate(project, editor, aClass, members);
@@ -98,7 +100,7 @@ public abstract class GenerateMembersHandlerBase implements CodeInsightActionHan
             }
           }, project.getDisposed());
         }
-      });
+      }, null, null);
     }
     finally {
       cleanup();
@@ -121,7 +123,7 @@ public abstract class GenerateMembersHandlerBase implements CodeInsightActionHan
     final PsiElement lBrace = aClass.getLBrace();
     if (textBeforeCaret.trim().length() > 0 && StringUtil.isEmptyOrSpaces(afterCaret) &&
         (lBrace == null || lBrace.getTextOffset() < offset) && !editor.getSelectionModel().hasSelection()) {
-      EnterAction.insertNewLineAtCaret(editor);
+      WriteAction.run(() -> EnterAction.insertNewLineAtCaret(editor));
       PsiDocumentManager.getInstance(project).commitDocument(document);
       offset = editor.getCaretModel().getOffset();
       col = editor.getCaretModel().getLogicalPosition().column;
@@ -130,15 +132,9 @@ public abstract class GenerateMembersHandlerBase implements CodeInsightActionHan
 
     editor.getCaretModel().moveToLogicalPosition(new LogicalPosition(0, 0));
 
-    List<? extends GenerationInfo> newMembers;
-    try{
-      List<? extends GenerationInfo> prototypes = generateMemberPrototypes(aClass, members);
-      newMembers = GenerateMembersUtil.insertMembersAtOffset(aClass, offset, prototypes);
-    }
-    catch(IncorrectOperationException e){
-      LOG.error(e);
-      return;
-    }
+    int finalOffset = offset;
+    List<? extends GenerationInfo> newMembers = WriteAction.compute(
+      () -> GenerateMembersUtil.insertMembersAtOffset(aClass, finalOffset, generateMemberPrototypes(aClass, members)));
 
     editor.getCaretModel().moveToLogicalPosition(new LogicalPosition(line, col));
 
@@ -170,7 +166,6 @@ public abstract class GenerateMembersHandlerBase implements CodeInsightActionHan
     }
 
     if (!templates.isEmpty()){
-      PsiDocumentManager.getInstance(project).doPostponedOperationsAndUnblockDocument(document);
       runTemplates(project, editor, templates, 0);
     }
     else if (!newMembers.isEmpty()){
@@ -188,7 +183,7 @@ public abstract class GenerateMembersHandlerBase implements CodeInsightActionHan
 
     final PsiElement element = info.getPsiMember();
     final TextRange range = element.getTextRange();
-    editor.getDocument().deleteString(range.getStartOffset(), range.getEndOffset());
+    WriteAction.run(() -> editor.getDocument().deleteString(range.getStartOffset(), range.getEndOffset()));
     int offset = range.getStartOffset();
     editor.getCaretModel().moveToOffset(offset);
     editor.getScrollingModel().scrollToCaret(ScrollType.CENTER);
diff --git a/java/java-impl/src/com/intellij/codeInsight/hints/JavaHintUtils.kt b/java/java-impl/src/com/intellij/codeInsight/hints/JavaHintUtils.kt
new file mode 100644 (file)
index 0000000..7e86a8c
--- /dev/null
@@ -0,0 +1,175 @@
+/*
+ * Copyright 2000-2016 JetBrains s.r.o.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.intellij.codeInsight.hints
+
+import com.intellij.codeInsight.hints.settings.ParameterNameHintsSettings
+import com.intellij.psi.*
+import com.intellij.psi.util.TypeConversionUtil
+
+
+object JavaInlayHintsProvider {
+
+  fun createHints(callExpression: PsiCallExpression): Set<InlayInfo> {
+    val (element, substitutor) = callExpression.resolveMethodGenerics().let { it.element to it.substitutor }
+    if (element is PsiMethod && isMethodToShow(element, callExpression)) {
+      val info = getCallInfo(callExpression, element)
+      return createHintSet(info, substitutor)
+    }
+    return emptySet()
+  }
+
+  private fun createHintSet(info: CallInfo, substitutor: PsiSubstitutor): Set<InlayInfo> {
+    val args = info.regularArgs.filter { it.isAssignable(substitutor) }
+
+    val resultSet = mutableSetOf<InlayInfo>()
+    with(resultSet) {
+      getVarArgInlay(info)?.let { add(it) }
+
+      if (ParameterNameHintsSettings.getInstance().isShowForParamsWithSameType) {
+        addAll(createSameTypeInlays(args))
+      }
+
+      addAll(createUnclearInlays(args))
+    }
+
+    return resultSet
+  }
+
+  private fun isMethodToShow(method: PsiMethod, callExpression: PsiCallExpression): Boolean {
+    val params = method.parameterList.parameters
+    if (params.isEmpty()) return false
+    if (params.size == 1) {
+      if (isBuilderLike(callExpression, method) || isSetterNamed(method)) return false
+      if (!ParameterNameHintsSettings.getInstance().isShowParamNameContainedInMethodName
+          && isParamNameContainedInMethodName(params[0], method)) return false
+    }
+    return true
+  }
+
+  private fun createUnclearInlays(args: List<CallArgumentInfo>): List<InlayInfo> {
+    return args
+      .filter { isUnclearExpression(it.argument) }
+      .mapNotNull { createInlayInfo(it.argument, it.parameter) }
+  }
+
+  private fun getVarArgInlay(info: CallInfo): InlayInfo? {
+    if (info.varArg == null || info.varArgExpressions.isEmpty()) return null
+    val hasUnclearExpressions = info.varArgExpressions.find { isUnclearExpression(it) } != null
+    if (hasUnclearExpressions) {
+      return createInlayInfo(info.varArgExpressions.first(), info.varArg)
+    }
+    return null
+  }
+
+  private fun isBuilderLike(expression: PsiCallExpression, method: PsiMethod): Boolean {
+    if (expression is PsiNewExpression) return false
+
+    val returnType = TypeConversionUtil.erasure(method.returnType) ?: return false
+    val calledMethodClassFqn = method.containingClass?.qualifiedName ?: return false
+
+    return returnType.equalsToText(calledMethodClassFqn)
+  }
+
+  private fun isSetterNamed(method: PsiMethod): Boolean {
+    val methodName = method.name
+    if (methodName.startsWith("set")
+        && (methodName.length == 3 || methodName.length > 3 && methodName[3].isUpperCase())) {
+      return true
+    }
+    return false
+  }
+
+  private fun isParamNameContainedInMethodName(parameter: PsiParameter, method: PsiMethod): Boolean {
+    val parameterName = parameter.name ?: return false
+    if (parameterName.length > 1) {
+      return method.name.contains(parameterName, ignoreCase = true)
+    }
+    return false
+  }
+
+  private fun createSameTypeInlays(args: List<CallArgumentInfo>): List<InlayInfo> {
+    val all = args.map { it.parameter.typeText() }
+    val duplicated = all.toMutableList()
+
+    all.distinct().forEach {
+      duplicated.remove(it)
+    }
+
+    return args
+      .filter { duplicated.contains(it.parameter.typeText()) }
+      .mapNotNull { createInlayInfo(it.argument, it.parameter) }
+  }
+
+  private fun createInlayInfo(callArgument: PsiExpression, methodParam: PsiParameter): InlayInfo? {
+    val paramName = methodParam.name ?: return null
+    val paramToShow = (if (methodParam.type is PsiEllipsisType) "..." else "") + paramName
+    return InlayInfo(paramToShow, callArgument.textRange.startOffset)
+  }
+
+  private fun getCallInfo(callExpression: PsiCallExpression, method: PsiMethod): CallInfo {
+    val params = method.parameterList.parameters
+    val hasVarArg = params.lastOrNull()?.isVarArgs ?: false
+    val regularParamsCount = if (hasVarArg) params.size - 1 else params.size
+
+    val arguments = callExpression.argumentList?.expressions ?: emptyArray()
+
+    val regularArgInfos = params
+      .take(regularParamsCount)
+      .zip(arguments)
+      .map { CallArgumentInfo(it.first, it.second) }
+
+    val varargParam = if (hasVarArg) params.last() else null
+    val varargExpressions = arguments.drop(regularParamsCount)
+    return CallInfo(regularArgInfos, varargParam, varargExpressions)
+  }
+
+  private fun isUnclearExpression(callArgument: PsiElement): Boolean {
+    return when (callArgument) {
+      is PsiLiteralExpression -> true
+      is PsiThisExpression -> true
+      is PsiBinaryExpression -> true
+      is PsiPolyadicExpression -> true
+      is PsiPrefixExpression -> {
+        val tokenType = callArgument.operationTokenType
+        val isLiteral = callArgument.operand is PsiLiteralExpression
+        isLiteral && (JavaTokenType.MINUS == tokenType || JavaTokenType.PLUS == tokenType)
+      }
+      else -> false
+    }
+  }
+}
+
+
+private class CallInfo(val regularArgs: List<CallArgumentInfo>,
+                       val varArg: PsiParameter?,
+                       val varArgExpressions: List<PsiExpression>)
+
+
+private class CallArgumentInfo(val parameter: PsiParameter, val argument: PsiExpression)
+
+
+private fun CallArgumentInfo.isAssignable(substitutor: PsiSubstitutor): Boolean {
+  val substitutedType = substitutor.substitute(parameter.type)
+  return argument.type?.isAssignableTo(substitutedType) ?: false
+}
+
+
+private fun PsiType.isAssignableTo(parameterType: PsiType): Boolean {
+  return TypeConversionUtil.isAssignable(parameterType, this)
+}
+
+
+private fun PsiParameter.typeText() = type.canonicalText
\ No newline at end of file
index 224e3a2a27e92cf9595a82af4a066bc9e4e3c408..f4d670ddc0c8550124214d20887731330f91beb1 100644 (file)
@@ -34,7 +34,7 @@ class JavaInlayParameterHintsProvider : InlayParameterHintsProvider {
 
   override fun getParameterHints(element: PsiElement): List<InlayInfo> {
     if (element is PsiCallExpression) {
-      return JavaParameterHintManager(element).descriptors.toList()
+      return JavaInlayHintsProvider.createHints(element).toList()
     }
     return emptyList()
   }
diff --git a/java/java-impl/src/com/intellij/codeInsight/hints/JavaParameterHintManager.java b/java/java-impl/src/com/intellij/codeInsight/hints/JavaParameterHintManager.java
deleted file mode 100644 (file)
index 7e6c0e8..0000000
+++ /dev/null
@@ -1,244 +0,0 @@
-/*
- * Copyright 2000-2016 JetBrains s.r.o.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.intellij.codeInsight.hints;
-
-import com.intellij.codeInsight.hints.settings.ParameterNameHintsSettings;
-import com.intellij.openapi.util.Pair;
-import com.intellij.openapi.util.text.StringUtil;
-import com.intellij.psi.*;
-import com.intellij.psi.tree.IElementType;
-import com.intellij.psi.util.TypeConversionUtil;
-import com.intellij.util.containers.ContainerUtil;
-import one.util.streamex.StreamEx;
-import org.jetbrains.annotations.NotNull;
-import org.jetbrains.annotations.Nullable;
-
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.List;
-import java.util.Set;
-import java.util.stream.Collectors;
-
-public class JavaParameterHintManager {
-
-  @NotNull
-  private final Set<InlayInfo> myDescriptors;
-
-  public JavaParameterHintManager(@NotNull PsiCallExpression callExpression) {
-    PsiExpression[] callArguments = getArguments(callExpression);
-    JavaResolveResult resolveResult = callExpression.resolveMethodGenerics();
-    if (!(resolveResult.getElement() instanceof PsiMethod)) {
-      myDescriptors = Collections.emptySet();
-      return;
-    }
-
-    final PsiMethod method = (PsiMethod)resolveResult.getElement();
-
-    Set<InlayInfo> descriptors = Collections.emptySet();
-    if (isMethodToShowParams(callExpression, method)) {
-      PsiParameter[] parameters = method.getParameterList().getParameters();
-      descriptors = buildDescriptorsForLiteralArguments(callArguments, parameters, resolveResult);
-    }
-
-    myDescriptors = descriptors;
-  }
-
-  private static boolean isMethodToShowParams(@NotNull PsiCallExpression callExpression, @NotNull PsiMethod method) {
-    if (isSetter(method)) return false;
-
-    PsiParameter[] parameters = method.getParameterList().getParameters();
-    if (parameters.length == 1) {
-      if (isBuilder(callExpression, method)) return false;
-
-      ParameterNameHintsSettings settings = ParameterNameHintsSettings.getInstance();
-      if (!settings.isShowParamNameContainedInMethodName()
-          && isParamNameContainedInMethodName(parameters[0], method)) {
-        return false;
-      }
-    }
-
-    return true;
-  }
-
-  private static Set<String> getDuplicatedParamTypes(PsiParameter[] parameters) {
-    List<String> duplicatedTypes = Arrays
-      .stream(parameters)
-      .map((p) -> p.getType().getCanonicalText())
-      .collect(Collectors.toList());
-
-    ContainerUtil.newHashSet(duplicatedTypes).forEach((e) -> duplicatedTypes.remove(e));
-    return ContainerUtil.newHashSet(duplicatedTypes);
-  }
-
-  private static boolean isParamNameContainedInMethodName(@NotNull PsiParameter parameter, @NotNull PsiMethod method) {
-    String parameterName = parameter.getName();
-    if (parameterName != null && parameterName.length() > 1) {
-      String methodName = method.getName();
-      return StringUtil.containsIgnoreCase(methodName, parameterName);
-    }
-    return false;
-  }
-
-  private static boolean isBuilder(PsiCallExpression expression, PsiMethod method) {
-    if (expression instanceof PsiNewExpression || !hasSingleParameter(method)) {
-      return false;
-    }
-
-    PsiType returnType = TypeConversionUtil.erasure(method.getReturnType());
-    final PsiClass aClass = method.getContainingClass();
-    final String calledMethodFqn = aClass != null ? aClass.getQualifiedName() : null;
-    if (calledMethodFqn != null && returnType != null) {
-      return returnType.equalsToText(calledMethodFqn);
-    }
-
-    return false;
-  }
-
-  private static boolean hasSingleParameter(PsiMethod method) {
-    return method.getParameterList().getParametersCount() == 1;
-  }
-
-
-  private static boolean isSetter(PsiMethod method) {
-    String methodName = method.getName();
-    if (hasSingleParameter(method) && methodName.startsWith("set")
-        && (methodName.length() == 3
-            || methodName.length() > 3 && Character.isUpperCase(methodName.charAt(3)))) {
-      return true;
-    }
-    return false;
-  }
-
-  static boolean isUnclearExpression(@Nullable PsiElement callArgument) {
-    if (callArgument instanceof PsiLiteralExpression) {
-      return true;
-    }
-
-    if (callArgument instanceof PsiPrefixExpression) {
-      PsiPrefixExpression expr = (PsiPrefixExpression)callArgument;
-      IElementType tokenType = expr.getOperationTokenType();
-      return (JavaTokenType.MINUS.equals(tokenType)
-              || JavaTokenType.PLUS.equals(tokenType)) && expr.getOperand() instanceof PsiLiteralExpression;
-    }
-
-    if (callArgument instanceof PsiThisExpression
-        || callArgument instanceof PsiBinaryExpression
-        || callArgument instanceof PsiPolyadicExpression) {
-      return true;
-    }
-
-    return false;
-  }
-
-  @NotNull
-  private static PsiExpression[] getArguments(@NotNull PsiCallExpression call) {
-    PsiExpressionList callArgumentsList = call.getArgumentList();
-    return callArgumentsList == null ? PsiExpression.EMPTY_ARRAY : callArgumentsList.getExpressions();
-  }
-
-  @NotNull
-  public Set<InlayInfo> getDescriptors() {
-    return myDescriptors;
-  }
-
-  @NotNull
-  private static Set<InlayInfo> buildDescriptorsForLiteralArguments(@NotNull PsiExpression[] callArguments,
-                                                                    @NotNull PsiParameter[] parameters,
-                                                                    @NotNull JavaResolveResult resolveResult) {
-
-    final Set<InlayInfo> descriptors = ContainerUtil.newHashSet();
-    final PsiSubstitutor substitutor = resolveResult.getSubstitutor();
-
-    if (ParameterNameHintsSettings.getInstance().isShowForParamsWithSameType()) {
-      final List<InlayInfo> hintsForNonLiterals = getHintsForParamsWithSameType(callArguments, parameters, substitutor);
-      descriptors.addAll(hintsForNonLiterals);
-    }
-
-    for (int i = 0; i < Math.min(callArguments.length, parameters.length); i++) {
-      PsiExpression arg = callArguments[i];
-      PsiParameter param = parameters[i];
-
-      if (isVarargParam(param.getType(), arg.getType()) && hasUnclearExpressionStartingFrom(i, callArguments)
-          || isUnclearExpression(arg) && isAssignable(arg, param, substitutor)) {
-        descriptors.add(createInlayInfo(arg, param));
-      }
-    }
-
-    return descriptors;
-  }
-
-  private static List<InlayInfo> getHintsForParamsWithSameType(@NotNull PsiExpression[] callArguments,
-                                                               @NotNull PsiParameter[] parameters,
-                                                               @NotNull PsiSubstitutor substitutor)
-  {
-    final Set<String> duplicatedTypes = getDuplicatedParamTypes(parameters);
-
-    final int minArraySize = Math.min(callArguments.length, parameters.length);
-    List<PsiExpression> args = ContainerUtil.list(callArguments).subList(0, minArraySize);
-    List<PsiParameter> params = ContainerUtil.list(parameters).subList(0, minArraySize);
-
-    return StreamEx
-      .zip(args, params, (a, b) -> Pair.create(a, b))
-      .filter((pair) -> {
-        PsiParameter param = pair.getSecond();
-        return duplicatedTypes.contains(param.getType().getCanonicalText());
-      })
-      .filter((pair) -> isAssignable(pair.first, pair.second, substitutor))
-      .map((pair) -> createInlayInfo(pair.first, pair.second))
-      .collect(Collectors.toList());
-  }
-
-  @NotNull
-  private static InlayInfo createInlayInfo(@NotNull PsiExpression callArgument, @NotNull PsiParameter methodParam) {
-    String paramName = ((methodParam.getType() instanceof PsiEllipsisType) ? "..." : "") + methodParam.getName();
-    return new InlayInfo(paramName, callArgument.getTextRange().getStartOffset());
-  }
-
-  private static boolean isAssignable(@NotNull PsiExpression argument,
-                                      @NotNull PsiParameter parameter,
-                                      @NotNull PsiSubstitutor substitutor) {
-    PsiType argType = argument.getType();
-    PsiType paramType = parameter.getType();
-
-    if (argType != null) {
-      PsiType parameterType = substitutor.substitute(paramType);
-      return TypeConversionUtil.isAssignable(parameterType, argType);
-    }
-
-    return false;
-  }
-
-  private static boolean hasUnclearExpressionStartingFrom(int index, PsiExpression[] callArguments) {
-    for (int i = index; i < callArguments.length; i++) {
-      PsiExpression arg = callArguments[i];
-      if (isUnclearExpression(arg)) return true;
-    }
-    return false;
-  }
-
-  private static boolean isVarargParam(@Nullable PsiType paramType, @Nullable PsiType argType) {
-    if (paramType == null || argType == null) return false;
-    PsiType deepType = paramType.getDeepComponentType();
-    return paramType instanceof PsiEllipsisType && TypeConversionUtil.isAssignable(deepType, argType);
-  }
-
-  private static boolean hasUnclearExpressions(@NotNull PsiExpression[] arguments) {
-    for (PsiExpression argument : arguments) {
-      if (isUnclearExpression(argument)) return true;
-    }
-    return false;
-  }
-}
index 74c85641b70145cebb8c81d4d2365ba0999d955c..c9e37a316cac02ea7e7caa72d94b3c1358c15c93 100644 (file)
@@ -17,6 +17,7 @@ package com.intellij.codeInspection.streamMigration;
 
 import com.intellij.codeInspection.streamMigration.StreamApiMigrationInspection.InitializerUsageStatus;
 import com.intellij.codeInspection.streamMigration.StreamApiMigrationInspection.MapOp;
+import com.intellij.codeInspection.streamMigration.StreamApiMigrationInspection.TerminalBlock;
 import com.intellij.openapi.diagnostic.Logger;
 import com.intellij.openapi.project.Project;
 import com.intellij.openapi.util.text.StringUtil;
@@ -24,7 +25,10 @@ import com.intellij.psi.*;
 import com.intellij.psi.codeStyle.JavaCodeStyleManager;
 import com.intellij.psi.codeStyle.SuggestedNameInfo;
 import com.intellij.psi.codeStyle.VariableKind;
+import com.intellij.psi.util.InheritanceUtil;
 import com.intellij.psi.util.PsiTreeUtil;
+import com.intellij.psi.util.PsiUtil;
+import com.siyeh.ig.psiutils.ExpressionUtils;
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
 
@@ -60,65 +64,47 @@ class ReplaceWithCollectFix extends MigrateToStreamFix {
   PsiElement migrate(@NotNull Project project,
                      @NotNull PsiLoopStatement loopStatement,
                      @NotNull PsiStatement body,
-                     @NotNull StreamApiMigrationInspection.TerminalBlock tb) {
-    final PsiElementFactory elementFactory = JavaPsiFacade.getElementFactory(project);
-    final PsiMethodCallExpression methodCallExpression = tb.getSingleMethodCall();
-
-    if (methodCallExpression == null) return null;
+                     @NotNull TerminalBlock tb) {
+    PsiElementFactory factory = JavaPsiFacade.getElementFactory(project);
+    PsiMethodCallExpression call = tb.getSingleMethodCall();
+    if (call == null) return null;
 
     restoreComments(loopStatement, body);
     if (!tb.hasOperations() && StreamApiMigrationInspection.isAddAllCall(tb) && loopStatement instanceof PsiForeachStatement) {
-      PsiExpression iteratedValue = ((PsiForeachStatement)loopStatement).getIteratedValue();
-      if (iteratedValue == null) return null;
-      final PsiType iteratedValueType = iteratedValue.getType();
-      final PsiExpression qualifierExpression = methodCallExpression.getMethodExpression().getQualifierExpression();
-      final String qualifierText = qualifierExpression != null ? qualifierExpression.getText() : "";
-      final String collectionText =
-        iteratedValueType instanceof PsiArrayType ? "java.util.Arrays.asList(" + iteratedValue.getText() + ")" :
-        getIteratedValueText(iteratedValue);
-      final String callText = StringUtil.getQualifiedName(qualifierText, "addAll(" + collectionText + ");");
-      return loopStatement.replace(elementFactory.createStatementFromText(callText, loopStatement));
+      return handleAddAll(loopStatement, factory, call);
+    }
+    PsiExpression qualifierExpression = call.getMethodExpression().getQualifierExpression();
+    PsiLocalVariable variable = StreamApiMigrationInspection.extractCollectionVariable(qualifierExpression);
+    if(variable != null && InheritanceUtil.isInheritor(variable.getType(), CommonClassNames.JAVA_UTIL_MAP)) {
+      PsiElement result = handleToMap(loopStatement, tb, call, variable);
+      if (result != null) return result;
     }
-    PsiExpression itemToAdd = methodCallExpression.getArgumentList().getExpressions()[0];
-    PsiType addedType = getAddedElementType(methodCallExpression);
+
+    PsiExpression itemToAdd = call.getArgumentList().getExpressions()[0];
+    PsiType addedType = getAddedElementType(call);
     if (addedType == null) addedType = itemToAdd.getType();
+
+    if(variable == null && qualifierExpression instanceof PsiMethodCallExpression) {
+      PsiMethodCallExpression qualifierCall = (PsiMethodCallExpression)qualifierExpression;
+      if(StreamApiMigrationInspection.isCallOf(qualifierCall, CommonClassNames.JAVA_UTIL_MAP, "computeIfAbsent")) {
+        PsiElement result = handleComputeIfAbsent(loopStatement, tb, itemToAdd, qualifierCall);
+        if (result != null) return result;
+      }
+    }
+
     StringBuilder builder = generateStream(new MapOp(tb.getLastOperation(), itemToAdd, tb.getVariable(), addedType));
 
-    final PsiExpression qualifierExpression = methodCallExpression.getMethodExpression().getQualifierExpression();
-    final PsiLocalVariable variable = StreamApiMigrationInspection.extractCollectionVariable(qualifierExpression);
     if (variable != null) {
       InitializerUsageStatus status = StreamApiMigrationInspection.getInitializerUsageStatus(variable, loopStatement);
       if(status != InitializerUsageStatus.UNKNOWN) {
         PsiExpression initializer = variable.getInitializer();
         LOG.assertTrue(initializer != null);
-        PsiMethodCallExpression toArrayExpression =
-          StreamApiMigrationInspection.extractToArrayExpression(loopStatement, methodCallExpression);
-        if(toArrayExpression != null) {
-          PsiType type = initializer.getType();
-          if(type instanceof PsiClassType) {
-            String replacement = StreamApiMigrationInspection.COLLECTION_TO_ARRAY.get(((PsiClassType)type).rawType().getCanonicalText());
-            if(replacement != null) {
-              builder.append(".").append(replacement);
-              PsiExpression[] args = toArrayExpression.getArgumentList().getExpressions();
-              if(args.length == 0) {
-                builder.append("()");
-              } else {
-                if(args.length != 1 || !(args[0] instanceof PsiNewExpression)) return null;
-                PsiNewExpression newArray = (PsiNewExpression)args[0];
-                PsiType arrayType = newArray.getType();
-                if(arrayType == null) return null;
-                String name = arrayType.getCanonicalText();
-                builder.append('(').append(name).append("::new)");
-              }
-              PsiElement result =
-                toArrayExpression.replace(elementFactory.createExpressionFromText(builder.toString(), toArrayExpression));
-              removeLoop(loopStatement);
-              if(status != InitializerUsageStatus.AT_WANTED_PLACE) {
-                variable.delete();
-              }
-              return result;
-            }
+        PsiElement toArrayConversion = handleToArray(builder, initializer, loopStatement, call);
+        if(toArrayConversion != null) {
+          if(status != InitializerUsageStatus.AT_WANTED_PLACE) {
+            variable.delete();
           }
+          return toArrayConversion;
         }
         PsiElement nextStatement = PsiTreeUtil.skipSiblingsForward(loopStatement, PsiComment.class, PsiWhiteSpace.class);
         String comparatorText = StreamApiMigrationInspection.tryExtractSortComparatorText(nextStatement, variable);
@@ -126,29 +112,163 @@ class ReplaceWithCollectFix extends MigrateToStreamFix {
           builder.append(".sorted(").append(comparatorText).append(")");
           nextStatement.delete();
         }
-        String callText = builder.append(".collect(java.util.stream.Collectors.")
+        String callText = builder.append(".collect(" + CommonClassNames.JAVA_UTIL_STREAM_COLLECTORS + ".")
           .append(createInitializerReplacementText(qualifierExpression.getType(), initializer))
           .append(")").toString();
         return replaceInitializer(loopStatement, variable, initializer, callText, status);
       }
     }
-    final String qualifierText = qualifierExpression != null ? qualifierExpression.getText() + "." : "";
+    String qualifierText = qualifierExpression != null ? qualifierExpression.getText() + "." : "";
 
     JavaCodeStyleManager codeStyleManager = JavaCodeStyleManager.getInstance(project);
     SuggestedNameInfo suggestedNameInfo =
       codeStyleManager.suggestVariableName(VariableKind.LOCAL_VARIABLE, null, null, addedType, false);
     if (suggestedNameInfo.names.length == 0) {
-      suggestedNameInfo = codeStyleManager.suggestVariableName(VariableKind.LOCAL_VARIABLE, "item", null, itemToAdd.getType(), false);
+      suggestedNameInfo = codeStyleManager.suggestVariableName(VariableKind.LOCAL_VARIABLE, "item", null, null, false);
     }
-    String varName = codeStyleManager.suggestUniqueVariableName(suggestedNameInfo, methodCallExpression, false).names[0];
+    String varName = codeStyleManager.suggestUniqueVariableName(suggestedNameInfo, call, false).names[0];
 
     PsiExpression forEachBody =
-      elementFactory.createExpressionFromText(qualifierText + "add(" + varName + ")", qualifierExpression);
-    final String callText =
-      builder.append(".forEach(").append(varName).append("->").append(forEachBody.getText()).append(");").toString();
-    return loopStatement.replace(elementFactory.createStatementFromText(callText, loopStatement));
+      factory.createExpressionFromText(qualifierText + "add(" + varName + ")", qualifierExpression);
+    String callText = builder.append(".forEach(").append(varName).append("->").append(forEachBody.getText()).append(");").toString();
+    return loopStatement.replace(factory.createStatementFromText(callText, loopStatement));
+  }
+
+  @Nullable
+  private static PsiElement handleComputeIfAbsent(@NotNull PsiLoopStatement loopStatement, @NotNull TerminalBlock tb,
+                                                  PsiExpression itemToAdd, PsiMethodCallExpression qualifierCall) {
+    PsiLocalVariable variable;
+    variable = StreamApiMigrationInspection.extractCollectionVariable(qualifierCall.getMethodExpression().getQualifierExpression());
+    if (variable == null || !InheritanceUtil.isInheritor(variable.getType(), CommonClassNames.JAVA_UTIL_MAP)) return null;
+    InitializerUsageStatus status = StreamApiMigrationInspection.getInitializerUsageStatus(variable, loopStatement);
+    if(status == InitializerUsageStatus.UNKNOWN) return null;
+    PsiExpression[] computeArgs = qualifierCall.getArgumentList().getExpressions();
+    if(!(computeArgs[1] instanceof PsiLambdaExpression)) return null;
+    PsiExpression ctor = LambdaUtil.extractSingleExpressionFromBody(((PsiLambdaExpression)computeArgs[1]).getBody());
+    PsiType mapType = variable.getType();
+    PsiType valueType = PsiUtil.substituteTypeParameter(mapType, CommonClassNames.JAVA_UTIL_MAP, 1, false);
+    if(valueType == null) return null;
+    String downstreamCollector = CommonClassNames.JAVA_UTIL_STREAM_COLLECTORS + "." + createInitializerReplacementText(valueType, ctor);
+    if(!ExpressionUtils.isReferenceTo(itemToAdd, tb.getVariable())) {
+      downstreamCollector = CommonClassNames.JAVA_UTIL_STREAM_COLLECTORS + ".mapping(" +
+                            tb.getVariable().getName() + "->" + itemToAdd.getText() + "," + downstreamCollector + ")";
+    }
+    StringBuilder builder = generateStream(tb.getLastOperation());
+    builder.append(".collect(" + CommonClassNames.JAVA_UTIL_STREAM_COLLECTORS + ".groupingBy(")
+      .append(LambdaUtil.createLambda(tb.getVariable(), computeArgs[0]));
+    PsiExpression initializer = variable.getInitializer();
+    LOG.assertTrue(initializer != null);
+    if (!isHashMap(variable)) {
+      builder.append(",()->").append(initializer.getText()).append(",").append(downstreamCollector);
+    }
+    else if (!(CommonClassNames.JAVA_UTIL_STREAM_COLLECTORS + "." + "toList()").equals(downstreamCollector)) {
+      builder.append(",").append(downstreamCollector);
+    }
+    builder.append("))");
+    return replaceInitializer(loopStatement, variable, initializer, builder.toString(), status);
+  }
+
+  @Nullable
+  private static PsiElement handleAddAll(@NotNull PsiLoopStatement loopStatement, PsiElementFactory factory, PsiMethodCallExpression call) {
+    PsiExpression iteratedValue = ((PsiForeachStatement)loopStatement).getIteratedValue();
+    if (iteratedValue == null) return null;
+    PsiExpression qualifierExpression = call.getMethodExpression().getQualifierExpression();
+    String qualifierText = qualifierExpression != null ? qualifierExpression.getText() : "";
+    String collectionText =
+      iteratedValue.getType() instanceof PsiArrayType ? CommonClassNames.JAVA_UTIL_ARRAYS + ".asList(" + iteratedValue.getText() + ")" :
+      getIteratedValueText(iteratedValue);
+    String callText = StringUtil.getQualifiedName(qualifierText, "addAll(" + collectionText + ");");
+    return loopStatement.replace(factory.createStatementFromText(callText, loopStatement));
   }
 
+  @Nullable
+  private static PsiElement handleToMap(@NotNull PsiLoopStatement loopStatement,
+                                        @NotNull TerminalBlock tb,
+                                        PsiMethodCallExpression call,
+                                        PsiLocalVariable variable) {
+    PsiExpression[] args = call.getArgumentList().getExpressions();
+    if(args.length < 2) return null;
+    String methodName = call.getMethodExpression().getReferenceName();
+    if(methodName == null) return null;
+    InitializerUsageStatus status = StreamApiMigrationInspection.getInitializerUsageStatus(variable, loopStatement);
+    if(status == InitializerUsageStatus.UNKNOWN) return null;
+    Project project = loopStatement.getProject();
+    PsiElementFactory factory = JavaPsiFacade.getElementFactory(project);
+    PsiExpression merger;
+    JavaCodeStyleManager codeStyleManager = JavaCodeStyleManager.getInstance(project);
+    String aVar = codeStyleManager.suggestUniqueVariableName("a", call, true);
+    String bVar = codeStyleManager.suggestUniqueVariableName("b", call, true);
+    switch(methodName) {
+      case "put":
+        merger = factory.createExpressionFromText("("+aVar+","+bVar+")->"+bVar, call);
+        break;
+      case "putIfAbsent":
+        merger = factory.createExpressionFromText("("+aVar+","+bVar+")->"+aVar, call);
+        break;
+      case "merge":
+        if(args.length != 3) return null;
+        merger = args[2];
+        break;
+      default:
+        return null;
+    }
+    StringBuilder collector = new StringBuilder(CommonClassNames.JAVA_UTIL_STREAM_COLLECTORS+".toMap(");
+    collector.append(LambdaUtil.createLambda(tb.getVariable(), args[0])).append(',')
+      .append(LambdaUtil.createLambda(tb.getVariable(), args[1])).append(',')
+      .append(merger.getText());
+    PsiExpression initializer = variable.getInitializer();
+    LOG.assertTrue(initializer != null);
+    if(!isHashMap(variable)) {
+      collector.append(",()->").append(initializer.getText());
+    }
+    collector.append(")");
+    String callText = generateStream(tb.getLastOperation()).append(".collect(").append(collector).append(")").toString();
+    return replaceInitializer(loopStatement, variable, initializer, callText, status);
+  }
+
+  private static boolean isHashMap(PsiLocalVariable variable) {
+    PsiExpression initializer = variable.getInitializer();
+    LOG.assertTrue(initializer != null);
+    PsiClass initializerClass = PsiUtil.resolveClassInClassTypeOnly(initializer.getType());
+    PsiClass varClass = PsiUtil.resolveClassInClassTypeOnly(variable.getType());
+    return initializerClass != null &&
+           varClass != null &&
+           CommonClassNames.JAVA_UTIL_HASH_MAP.equals(initializerClass.getQualifiedName()) &&
+           CommonClassNames.JAVA_UTIL_MAP.equals(varClass.getQualifiedName());
+  }
+
+  @Nullable
+  private static PsiElement handleToArray(StringBuilder builder,
+                                          PsiExpression initializer,
+                                          PsiLoopStatement loopStatement,
+                                          PsiMethodCallExpression methodCallExpression) {
+    PsiMethodCallExpression toArrayExpression =
+      StreamApiMigrationInspection.extractToArrayExpression(loopStatement, methodCallExpression);
+    if (toArrayExpression == null) return null;
+    PsiType type = initializer.getType();
+    if (!(type instanceof PsiClassType)) return null;
+    String replacement = StreamApiMigrationInspection.COLLECTION_TO_ARRAY.get(((PsiClassType)type).rawType().getCanonicalText());
+    if (replacement == null) return null;
+
+    builder.append(".").append(replacement);
+    PsiExpression[] args = toArrayExpression.getArgumentList().getExpressions();
+    if(args.length == 0) {
+      builder.append("()");
+    } else {
+      if(args.length != 1 || !(args[0] instanceof PsiNewExpression)) return null;
+      PsiNewExpression newArray = (PsiNewExpression)args[0];
+      PsiType arrayType = newArray.getType();
+      if(arrayType == null) return null;
+      String name = arrayType.getCanonicalText();
+      builder.append('(').append(name).append("::new)");
+    }
+    PsiElementFactory elementFactory = JavaPsiFacade.getElementFactory(toArrayExpression.getProject());
+    PsiElement result = toArrayExpression.replace(elementFactory.createExpressionFromText(builder.toString(), toArrayExpression));
+    removeLoop(loopStatement);
+    return result;
+  }
+
+  @NotNull
   private static String createInitializerReplacementText(PsiType varType, PsiExpression initializer) {
     final PsiType initializerType = initializer.getType();
     final PsiClassType rawType = initializerType instanceof PsiClassType ? ((PsiClassType)initializerType).rawType() : null;
@@ -164,9 +284,6 @@ class ReplaceWithCollectFix extends MigrateToStreamFix {
               rawVarType.equalsToText(CommonClassNames.JAVA_UTIL_COLLECTION))) {
       return "toSet()";
     }
-    else if (rawType != null) {
-      return "toCollection(" + rawType.getClassName() + "::new)";
-    }
     else {
       return "toCollection(() -> " + initializer.getText() + ")";
     }
index 428e500778a1c398430c016dc82bc01047b36d0c..845644da04ba953e19e01f1119b8521198f94506 100644 (file)
@@ -256,68 +256,100 @@ public class StreamApiMigrationInspection extends BaseJavaBatchLocalInspectionTo
   }
 
   static boolean isAddAllCall(TerminalBlock tb) {
-    final PsiVariable variable = tb.getVariable();
-    final PsiMethodCallExpression methodCallExpression = tb.getSingleMethodCall();
-    LOG.assertTrue(methodCallExpression != null);
-    if (!ExpressionUtils.isReferenceTo(methodCallExpression.getArgumentList().getExpressions()[0], variable)) return false;
-    PsiExpression qualifierExpression = methodCallExpression.getMethodExpression().getQualifierExpression();
-    if(qualifierExpression == null || qualifierExpression instanceof PsiThisExpression) {
-      PsiMethod method = PsiTreeUtil.getParentOfType(methodCallExpression, PsiMethod.class);
+    PsiMethodCallExpression call = tb.getSingleMethodCall();
+    LOG.assertTrue(call != null);
+    if (!ExpressionUtils.isReferenceTo(call.getArgumentList().getExpressions()[0], tb.getVariable())) return false;
+    if (!"add".equals(call.getMethodExpression().getReferenceName())) return false;
+    PsiExpression qualifierExpression = call.getMethodExpression().getQualifierExpression();
+    if (qualifierExpression == null || qualifierExpression instanceof PsiThisExpression) {
+      PsiMethod method = PsiTreeUtil.getParentOfType(call, PsiMethod.class);
       return method == null || !method.getName().equals("addAll");
     }
     return true;
   }
 
-  private static boolean isCollectCall(TerminalBlock tb) {
-    final PsiMethodCallExpression methodCallExpression = tb.getSingleMethodCall();
-    if (methodCallExpression != null) {
-      final PsiReferenceExpression methodExpression = methodCallExpression.getMethodExpression();
-      final PsiExpression qualifierExpression = methodExpression.getQualifierExpression();
-      PsiClass qualifierClass = null;
-      if (qualifierExpression instanceof PsiReferenceExpression) {
-        if (ReferencesSearch.search(tb.getVariable(), new LocalSearchScope(qualifierExpression)).findFirst() != null) {
-          return false;
-        }
-        final PsiElement resolve = ((PsiReferenceExpression)qualifierExpression).resolve();
-        if (resolve instanceof PsiVariable) {
-          if (ReferencesSearch.search(resolve, new LocalSearchScope(methodCallExpression.getArgumentList())).findFirst() != null) {
-            return false;
-          }
-        }
-        qualifierClass = PsiUtil.resolveClassInType(qualifierExpression.getType());
+  @Nullable
+  private static PsiClass extractQualifierClass(TerminalBlock tb, PsiMethodCallExpression methodCallExpression) {
+    PsiExpression qualifierExpression = methodCallExpression.getMethodExpression().getQualifierExpression();
+    PsiClass qualifierClass = null;
+    if (qualifierExpression instanceof PsiReferenceExpression) {
+      if (ReferencesSearch.search(tb.getVariable(), new LocalSearchScope(qualifierExpression)).findFirst() != null) {
+        return null;
       }
-      else if (qualifierExpression == null || qualifierExpression instanceof PsiThisExpression) {
-        final PsiClass enclosingClass = PsiTreeUtil.getParentOfType(methodCallExpression, PsiClass.class);
-        if (PsiUtil.getEnclosingStaticElement(methodCallExpression, enclosingClass) == null) {
-          qualifierClass = enclosingClass;
+      final PsiElement resolve = ((PsiReferenceExpression)qualifierExpression).resolve();
+      if (resolve instanceof PsiVariable) {
+        if (ReferencesSearch.search(resolve, new LocalSearchScope(methodCallExpression.getArgumentList())).findFirst() != null) {
+          return null;
         }
       }
+      qualifierClass = PsiUtil.resolveClassInType(qualifierExpression.getType());
+    }
+    else if (qualifierExpression == null || qualifierExpression instanceof PsiThisExpression) {
+      final PsiClass enclosingClass = PsiTreeUtil.getParentOfType(methodCallExpression, PsiClass.class);
+      if (PsiUtil.getEnclosingStaticElement(methodCallExpression, enclosingClass) == null) {
+        qualifierClass = enclosingClass;
+      }
+    }
+    return qualifierClass;
+  }
 
-      if (qualifierClass != null && 
-          InheritanceUtil.isInheritor(qualifierClass, false, CommonClassNames.JAVA_UTIL_COLLECTION)) {
+  @Contract("null, _, _ -> false")
+  static boolean isCallOf(PsiMethodCallExpression call, String className, String... methodNames) {
+    if (call == null) return false;
+    PsiReferenceExpression methodExpression = call.getMethodExpression();
+    String name = methodExpression.getReferenceName();
+    if (!ArrayUtil.contains(name, methodNames)) return false;
+    PsiMethod maybeMapMethod = call.resolveMethod();
+    if (maybeMapMethod == null ||
+        maybeMapMethod.getParameterList().getParametersCount() != call.getArgumentList().getExpressions().length) {
+      return false;
+    }
+    PsiClass containingClass = maybeMapMethod.getContainingClass();
+    if (containingClass == null) return false;
+    if (className.equals(containingClass.getQualifiedName())) return true;
+    PsiMethod[] superMethods = maybeMapMethod.findDeepestSuperMethods();
+    return StreamEx.of(superMethods).map(PsiMember::getContainingClass).nonNull().map(PsiClass::getQualifiedName).has(className);
+  }
 
-        if (tb.intermediateExpressions().anyMatch(expression -> isExpressionDependsOnUpdatedCollections(expression, qualifierExpression))) {
-          return false;
-        }
+  private static boolean isCollectMapCall(PsiLoopStatement loop, TerminalBlock tb) {
+    PsiMethodCallExpression call = tb.getSingleMethodCall();
+    if (!isCallOf(call, CommonClassNames.JAVA_UTIL_MAP, "merge", "put", "putIfAbsent")) return false;
+    PsiReferenceExpression methodExpression = call.getMethodExpression();
+    PsiExpression qualifierExpression = methodExpression.getQualifierExpression();
+    return extractQualifierClass(tb, call) != null && !tb.dependsOn(qualifierExpression) && canCollect(loop, call);
+  }
 
-        final PsiElement resolve = methodExpression.resolve();
-        if (resolve instanceof PsiMethod &&
-            "add".equals(((PsiMethod)resolve).getName()) &&
-            ((PsiMethod)resolve).getParameterList().getParametersCount() == 1) {
-          final PsiExpression[] args = methodCallExpression.getArgumentList().getExpressions();
-          if (args.length == 1) {
-            if (args[0] instanceof PsiCallExpression) {
-              final PsiMethod method = ((PsiCallExpression)args[0]).resolveMethod();
-              return method != null && !method.hasTypeParameters() && !isThrowsCompatible(method);
-            }
-            return true;
-          }
-        }
+  private static boolean isCollectCall(TerminalBlock tb) {
+    PsiMethodCallExpression call = tb.getSingleMethodCall();
+    if (!isCallOf(call, CommonClassNames.JAVA_UTIL_COLLECTION, "add")) return false;
+    PsiReferenceExpression methodExpression = call.getMethodExpression();
+    PsiExpression qualifierExpression = methodExpression.getQualifierExpression();
+
+    if (tb.dependsOn(qualifierExpression)) return false;
+
+    if (extractQualifierClass(tb, call) != null) return true;
+    if (qualifierExpression instanceof PsiMethodCallExpression) {
+      PsiMethodCallExpression qualifierCall = (PsiMethodCallExpression)qualifierExpression;
+      if (isCallOf(qualifierCall, CommonClassNames.JAVA_UTIL_MAP, "computeIfAbsent")) {
+        PsiExpression[] args = qualifierCall.getArgumentList().getExpressions();
+        if (args.length != 2 || !(args[1] instanceof PsiLambdaExpression)) return false;
+        PsiLambdaExpression lambda = (PsiLambdaExpression)args[1];
+        PsiExpression body = LambdaUtil.extractSingleExpressionFromBody(lambda.getBody());
+        if (!(body instanceof PsiNewExpression)) return false;
+        PsiExpressionList ctorArgs = ((PsiNewExpression)body).getArgumentList();
+        return ctorArgs != null && ctorArgs.getExpressions().length == 0;
       }
     }
     return false;
   }
 
+  @Contract("_, null -> false")
+  static boolean canCollect(PsiLoopStatement statement, PsiMethodCallExpression call) {
+    if(call == null) return false;
+    PsiLocalVariable variable = extractCollectionVariable(call.getMethodExpression().getQualifierExpression());
+    return variable != null && getInitializerUsageStatus(variable, statement) != UNKNOWN;
+  }
+
   private static boolean isExpressionDependsOnUpdatedCollections(PsiExpression condition,
                                                                  PsiExpression qualifierExpression) {
     final PsiElement collection = qualifierExpression instanceof PsiReferenceExpression
@@ -610,9 +642,12 @@ public class StreamApiMigrationInspection extends BaseJavaBatchLocalInspectionTo
           if(addAll) {
             methodName = "addAll";
           } else {
-            PsiMethodCallExpression methodCallExpression = tb.getSingleMethodCall();
-            if(canCollect(statement, methodCallExpression)) {
-              if(extractToArrayExpression(statement, methodCallExpression) != null)
+            PsiMethodCallExpression call = tb.getSingleMethodCall();
+            if(call != null && call.getMethodExpression().getQualifierExpression() instanceof PsiMethodCallExpression) {
+              call = (PsiMethodCallExpression)call.getMethodExpression().getQualifierExpression();
+            }
+            if(canCollect(statement, call)) {
+              if(extractToArrayExpression(statement, call) != null)
                 methodName = "toArray";
               else
                 methodName = "collect";
@@ -623,6 +658,9 @@ public class StreamApiMigrationInspection extends BaseJavaBatchLocalInspectionTo
           }
           registerProblem(statement, methodName, new ReplaceWithCollectFix(methodName));
         }
+        else if (isCollectMapCall(statement, tb) && (REPLACE_TRIVIAL_FOREACH || tb.hasOperations())) {
+          registerProblem(statement, "collect", new ReplaceWithCollectFix("collect"));
+        }
         // do not replace for(T e : arr) {} with Arrays.stream(arr).forEach(e -> {}) even if flag is set
         else if (SUGGEST_FOREACH &&
                  (tb.hasOperations() || (!(source instanceof ArrayStream) && (REPLACE_TRIVIAL_FOREACH || !isTrivial(body, statement))))) {
@@ -673,13 +711,6 @@ public class StreamApiMigrationInspection extends BaseJavaBatchLocalInspectionTo
       }
     }
 
-    boolean canCollect(PsiLoopStatement statement, PsiMethodCallExpression methodCallExpression) {
-      if(methodCallExpression == null) return false;
-      PsiLocalVariable variable = extractCollectionVariable(methodCallExpression.getMethodExpression().getQualifierExpression());
-      if(variable == null) return false;
-      return getInitializerUsageStatus(variable, statement) != UNKNOWN;
-    }
-
     void handleSingleReturn(PsiLoopStatement statement, TerminalBlock tb) {
       PsiReturnStatement returnStatement = (PsiReturnStatement)tb.getSingleStatement();
       PsiExpression value = returnStatement.getReturnValue();
@@ -1512,5 +1543,9 @@ public class StreamApiMigrationInspection extends BaseJavaBatchLocalInspectionTo
     public static TerminalBlock from(StreamSource source, @NotNull PsiStatement body) {
       return new TerminalBlock(source, source.myVariable, body).extractOperations();
     }
+
+    boolean dependsOn(PsiExpression qualifier) {
+      return intermediateExpressions().anyMatch(expression -> isExpressionDependsOnUpdatedCollections(expression, qualifier));
+    }
   }
 }
index 65643adddfb2b0931a987532b635f235c7ca6519..f98e87336eff30bc8e6314cd1bfc77088f49872c 100644 (file)
@@ -243,16 +243,7 @@ abstract class TerminalOperation extends Operation {
             || collectorArgs.length == 3 && collectorName.equals("partitioningBy")) return null;
         fn = FunctionHelper.create(collectorArgs[0], 1);
         if (fn == null) return null;
-        if (!(resultType instanceof PsiClassType)) return null;
-        PsiClass aClass = ((PsiClassType)resultType).resolve();
-        if (aClass == null) return null;
-        PsiSubstitutor substitutor = ((PsiClassType)resultType).resolveGenerics().getSubstitutor();
-        PsiClass mapClass =
-          JavaPsiFacade.getInstance(aClass.getProject()).findClass(CommonClassNames.JAVA_UTIL_MAP, aClass.getResolveScope());
-        if (mapClass == null) return null;
-        PsiTypeParameter[] parameters = mapClass.getTypeParameters();
-        if (parameters.length != 2) return null;
-        PsiType resultSubType = substitutor.substitute(parameters[1]);
+        PsiType resultSubType = PsiUtil.substituteTypeParameter(resultType, CommonClassNames.JAVA_UTIL_MAP, 1, false);
         if (resultSubType == null) return null;
         CollectorOperation downstreamCollector;
         if (collectorArgs.length == 1) {
@@ -689,8 +680,7 @@ abstract class TerminalOperation extends Operation {
         if (PsiType.DOUBLE.equalsToText(elementType)) {
           return new MinMaxTerminalOperation(elementType, "java.lang.Double.compare({item},{best})" + sign + "0", null);
         }
-      } else if(InheritanceUtil.isInheritor(PsiUtil.resolveClassInClassTypeOnly(comparator.getType()), false,
-                                     CommonClassNames.JAVA_UTIL_COMPARATOR)) {
+      } else if(InheritanceUtil.isInheritor(comparator.getType(), CommonClassNames.JAVA_UTIL_COMPARATOR)) {
         return new MinMaxTerminalOperation(elementType, "{comparator}.compare({item},{best})" + sign + "0", comparator);
       }
       return null;
index 89fa74ad324109e0defb8c7c62fd60be4a55f422..b045fda2888b404b1bb748a68f51ecdd9c57e7c1 100644 (file)
@@ -21,6 +21,7 @@ import com.intellij.codeInsight.highlighting.HighlightManager;
 import com.intellij.codeInsight.intention.QuickFixFactory;
 import com.intellij.openapi.application.ApplicationManager;
 import com.intellij.openapi.application.ModalityState;
+import com.intellij.openapi.application.WriteAction;
 import com.intellij.openapi.command.CommandProcessor;
 import com.intellij.openapi.diagnostic.Logger;
 import com.intellij.openapi.editor.Editor;
@@ -46,7 +47,6 @@ import com.intellij.refactoring.listeners.RefactoringEventListener;
 import com.intellij.refactoring.util.CommonRefactoringUtil;
 import com.intellij.refactoring.util.InlineUtil;
 import com.intellij.util.ArrayUtil;
-import com.intellij.util.IncorrectOperationException;
 import com.intellij.util.Query;
 import com.intellij.util.containers.ContainerUtil;
 import org.jetbrains.annotations.NotNull;
@@ -244,24 +244,25 @@ public class InlineLocalHandler extends JavaInlineActionHandler {
         beforeData.addElements(refsToInline);
         project.getMessageBus().syncPublisher(RefactoringEventListener.REFACTORING_EVENT_TOPIC).refactoringStarted(refactoringId, beforeData);
 
-        final SmartPointerManager pointerManager = SmartPointerManager.getInstance(project);
-        for(int idx = 0; idx < refsToInline.length; idx++){
-          PsiJavaCodeReferenceElement refElement = (PsiJavaCodeReferenceElement)refsToInline[idx];
-          exprs[idx] = pointerManager.createSmartPsiElementPointer(InlineUtil.inlineVariable(local, defToInline, refElement));
-        }
-
-        if (inlineAll.get()) {
-          if (!isInliningVariableInitializer(defToInline)) {
-            defToInline.getParent().delete();
-          } else {
-            defToInline.delete();
+        WriteAction.run(() -> {
+          final SmartPointerManager pointerManager = SmartPointerManager.getInstance(project);
+          for(int idx = 0; idx < refsToInline.length; idx++){
+            PsiJavaCodeReferenceElement refElement = (PsiJavaCodeReferenceElement)refsToInline[idx];
+            exprs[idx] = pointerManager.createSmartPsiElementPointer(InlineUtil.inlineVariable(local, defToInline, refElement));
           }
 
-          if (ReferencesSearch.search(local).findFirst() == null) {
-            QuickFixFactory.getInstance().createRemoveUnusedVariableFix(local).invoke(project, editor, local.getContainingFile());
+          if (inlineAll.get()) {
+            if (!isInliningVariableInitializer(defToInline)) {
+              defToInline.getParent().delete();
+            } else {
+              defToInline.delete();
+            }
           }
-        }
+        });
 
+        if (inlineAll.get() && ReferencesSearch.search(local).findFirst() == null) {
+          QuickFixFactory.getInstance().createRemoveUnusedVariableFix(local).invoke(project, editor, local.getContainingFile());
+        }
 
         if (editor != null && !ApplicationManager.getApplication().isUnitTestMode()) {
           highlightManager.addOccurrenceHighlights(editor, ContainerUtil.convert(exprs, new PsiExpression[refsToInline.length],
@@ -269,12 +270,11 @@ public class InlineLocalHandler extends JavaInlineActionHandler {
           WindowManager.getInstance().getStatusBar(project).setInfo(RefactoringBundle.message("press.escape.to.remove.the.highlighting"));
         }
 
-        for (final SmartPsiElementPointer<PsiExpression> expr : exprs) {
-          InlineUtil.tryToInlineArrayCreationForVarargs(expr.getElement());
-        }
-      }
-      catch (IncorrectOperationException e){
-        LOG.error(e);
+        WriteAction.run(() -> {
+          for (SmartPsiElementPointer<PsiExpression> expr : exprs) {
+            InlineUtil.tryToInlineArrayCreationForVarargs(expr.getElement());
+          }
+        });
       }
       finally {
         final RefactoringEventData afterData = new RefactoringEventData();
@@ -283,7 +283,7 @@ public class InlineLocalHandler extends JavaInlineActionHandler {
       }
     };
 
-    CommandProcessor.getInstance().executeCommand(project, () -> ApplicationManager.getApplication().runWriteAction(runnable), RefactoringBundle.message("inline.command", localName), null);
+    CommandProcessor.getInstance().executeCommand(project, runnable, RefactoringBundle.message("inline.command", localName), null);
   }
 
   @Nullable
index 4bfc650cf327bb24ff3970e39bab7428a5030aba..1658481927bb45fda5228677b01a420c8334545b 100644 (file)
@@ -127,11 +127,20 @@ public class LambdaUtil {
   @Contract("null -> false")
   public static boolean isValidLambdaContext(@Nullable PsiElement context) {
     context = PsiUtil.skipParenthesizedExprUp(context);
-    return isAssignmentOrInvocationContext(context) ||
-           context instanceof PsiTypeCastExpression ||
-           context instanceof PsiConditionalExpression && isAssignmentOrInvocationContext(PsiUtil.skipParenthesizedExprUp(context.getParent()));
+    if (isAssignmentOrInvocationContext(context) || context instanceof PsiTypeCastExpression) {
+      return true;
+    }
+    if (context instanceof PsiConditionalExpression) {
+      PsiElement parentContext = PsiUtil.skipParenthesizedExprUp(context.getParent());
+      if (isAssignmentOrInvocationContext(parentContext)) return true;
+      if (parentContext instanceof PsiConditionalExpression) {
+        return isValidLambdaContext(parentContext);
+      }
+    }
+    return false;
   }
 
+  @Contract("null -> false")
   private static boolean isAssignmentOrInvocationContext(PsiElement context) {
     return isAssignmentContext(context) || isInvocationContext(context);
   }
index 01523ca39f00b1978345c9f0eab42e83110f5f37..9084db52b5bf66d64a704a4cdffe8840189c9344 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2015 JetBrains s.r.o.
+ * Copyright 2000-2016 JetBrains s.r.o.
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -506,7 +506,7 @@ public class RedundantCastUtil {
       PsiExpression operand = typeCast.getOperand();
       if (operand == null) return;
 
-      PsiElement expr = deparenthesizeExpression(operand);
+      PsiExpression expr = deparenthesizeExpression(operand);
 
       final PsiType topCastType = typeCast.getType();
       if (expr instanceof PsiTypeCastExpression) {
@@ -540,7 +540,7 @@ public class RedundantCastUtil {
             if (opposite == null || conditionalType instanceof PsiPrimitiveType &&
                                     !Comparing.equal(conditionalType, opposite.getType())) return;
           }
-        } else if (parent instanceof PsiSynchronizedStatement && (expr instanceof PsiExpression && ((PsiExpression)expr).getType() instanceof PsiPrimitiveType)) {
+        } else if (parent instanceof PsiSynchronizedStatement && expr != null && expr.getType() instanceof PsiPrimitiveType) {
           return;
         } else if (expr instanceof PsiLambdaExpression || expr instanceof PsiMethodReferenceExpression) {
           if (parent instanceof PsiParenthesizedExpression && parent.getParent() instanceof PsiReferenceExpression) {
@@ -562,8 +562,8 @@ public class RedundantCastUtil {
         int idx = ArrayUtil.find(expressions, parent);
         PsiElement grandGrandPa = grandPa.getParent();
         if (grandGrandPa instanceof PsiCall) {
-          PsiElement resolve = ((PsiCall)grandGrandPa).resolveMethod();
-          if (resolve instanceof PsiMethod) {
+          PsiMethod resolve = ((PsiCall)grandGrandPa).resolveMethod();
+          if (resolve != null) {
             PsiCall expression = (PsiCall)grandGrandPa.copy();
             PsiExpressionList argumentList = expression.getArgumentList();
             LOG.assertTrue(argumentList != null);
@@ -660,7 +660,7 @@ public class RedundantCastUtil {
           final PsiExpression opposite = PsiTreeUtil.isAncestor(thenExpression, typeCast, false) ? elseExpression : thenExpression;
           if (opposite != null &&
               !(opposite.getType() instanceof PsiPrimitiveType) &&
-              !(PsiTypesUtil.getExpectedTypeByParent((PsiExpression)parent) instanceof PsiPrimitiveType)) {
+              !(PsiTypesUtil.getExpectedTypeByParent(parent) instanceof PsiPrimitiveType)) {
             return;
           }
         }
@@ -830,7 +830,7 @@ public class RedundantCastUtil {
       }
     } else if (parent instanceof PsiConditionalExpression) {
       if (opType instanceof PsiPrimitiveType && !(((PsiConditionalExpression)parent).getType() instanceof PsiPrimitiveType)) {
-        if (PsiPrimitiveType.getUnboxedType(PsiTypesUtil.getExpectedTypeByParent((PsiExpression)parent)) != null) {
+        if (PsiPrimitiveType.getUnboxedType(PsiTypesUtil.getExpectedTypeByParent(parent)) != null) {
           return true;
         }
       }
@@ -839,7 +839,7 @@ public class RedundantCastUtil {
   }
 
   private static boolean isCastToSerializable(PsiType castType) {
-    return castType instanceof PsiClassType && InheritanceUtil.isInheritor(PsiUtil.resolveClassInType(castType), CommonClassNames.JAVA_IO_SERIALIZABLE);
+    return InheritanceUtil.isInheritor(castType, CommonClassNames.JAVA_IO_SERIALIZABLE);
   }
 
   private static boolean wrapperCastChangeSemantics(PsiExpression operand, PsiExpression otherOperand, PsiExpression toCast) {
index 874ef5e57ff7bc17156360afe059c265c65552af..56c95a65bbdc5d13159155b74f59749ffe8ed57f 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2015 JetBrains s.r.o.
+ * Copyright 2000-2016 JetBrains s.r.o.
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -87,17 +87,20 @@ public class ComparisonFailureData {
     attrs.put("details", failureIdx > -1 ? trace.substring(failureIdx + failureMessageLength) : trace);
  
     if (notification != null) {
-      attrs.put("expected", notification.getExpected());
-      attrs.put("actual", notification.getActual());
-
       final String filePath = notification.getFilePath();
       if (filePath != null) {
         attrs.put("expectedFile", filePath);
       }
+      else {
+        attrs.put("expected", notification.getExpected());
+      }
       final String actualFilePath = notification.getActualFilePath();
       if (actualFilePath != null) {
         attrs.put("actualFile", actualFilePath);
       }
+      else {
+        attrs.put("actual", notification.getActual());
+      }
       final int expectedIdx = trace.indexOf("expected:<");
       final String comparisonFailureMessage;
       if (expectedIdx > 0) {
index cff20f66966615566744867eed19dbe7ed05a16c..df6e32a2364744070977ce7a0cac5fb14ce13609 100644 (file)
@@ -27,4 +27,10 @@ class Test1 {
     II ik2 = (II)(ik1 = (b ? (s)-> true : (s)->false));
     (b ? <error descr="Lambda expression not expected here">(s) -> true</error> : ik)._("");
   }
+}
+
+class Test2 {
+  void f() {
+    final Runnable one=true ? null : true ? () -> {} : () -> {};
+  }
 }
\ No newline at end of file
diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/streamApiMigration/afterCollectToMap.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/streamApiMigration/afterCollectToMap.java
new file mode 100644 (file)
index 0000000..4cb585f
--- /dev/null
@@ -0,0 +1,17 @@
+// "Replace with collect" "true"
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Objects;
+import java.util.stream.Collectors;
+
+public class Main {
+  private Map<String, Integer> test(String... list) {
+      Map<String, Integer> map = Arrays.stream(list).filter(Objects::nonNull).collect(Collectors.toMap(s -> s, s -> 1, (a, b) -> a + b));
+      return map;
+  }
+
+  public static void main(String[] args) {
+    System.out.println(new Main().test("a", "bbb", null, "cc", "dd", "eedasfasdfs", "dd"));
+  }
+}
diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/streamApiMigration/afterCollectToMapPut.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/streamApiMigration/afterCollectToMapPut.java
new file mode 100644 (file)
index 0000000..dc0c2b3
--- /dev/null
@@ -0,0 +1,17 @@
+// "Replace with collect" "true"
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Objects;
+import java.util.stream.Collectors;
+
+public class Main {
+  private Map<String, Integer> test(String... list) {
+      HashMap<String, Integer> map = Arrays.stream(list).filter(Objects::nonNull).collect(Collectors.toMap(s -> s, s -> 1, (a, b) -> b, HashMap::new));
+      return map;
+  }
+
+  public static void main(String[] args) {
+    System.out.println(new Main().test("a", "bbb", null, "cc", "dd", "eedasfasdfs", "dd"));
+  }
+}
diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/streamApiMigration/afterCollectToMapPutIfAbsent.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/streamApiMigration/afterCollectToMapPutIfAbsent.java
new file mode 100644 (file)
index 0000000..187b323
--- /dev/null
@@ -0,0 +1,17 @@
+// "Replace with collect" "true"
+import java.util.Arrays;
+import java.util.LinkedHashMap;
+import java.util.Map;
+import java.util.Objects;
+import java.util.stream.Collectors;
+
+public class Main {
+  private Map<String, Integer> test(String... list) {
+      Map<String, Integer> map = Arrays.stream(list).filter(Objects::nonNull).collect(Collectors.toMap(s -> s, s -> 1, (a, b) -> a, LinkedHashMap::new));
+      return map;
+  }
+
+  public static void main(String[] args) {
+    System.out.println(new Main().test("a", "bbb", null, "cc", "dd", "eedasfasdfs", "dd"));
+  }
+}
diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/streamApiMigration/afterGroupingByArrayList.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/streamApiMigration/afterGroupingByArrayList.java
new file mode 100644 (file)
index 0000000..f951615
--- /dev/null
@@ -0,0 +1,14 @@
+// "Replace with collect" "true"
+import java.util.*;
+import java.util.stream.Collectors;
+
+public class Main {
+  private Map<Integer, ArrayList<String>> test(String... list) {
+      Map<Integer, ArrayList<String>> map = Arrays.stream(list).filter(Objects::nonNull).collect(Collectors.groupingBy(String::length, Collectors.toCollection(ArrayList::new)));
+      return map;
+  }
+
+  public static void main(String[] args) {
+    System.out.println(new Main().test("a", "bbb", null, "cc", "dd", "eedasfasdfs", "dd"));
+  }
+}
diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/streamApiMigration/afterGroupingByCustomCollection.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/streamApiMigration/afterGroupingByCustomCollection.java
new file mode 100644 (file)
index 0000000..c1c7628
--- /dev/null
@@ -0,0 +1,14 @@
+// "Replace with collect" "true"
+import java.util.*;
+import java.util.stream.Collectors;
+
+public class Main {
+  private Map<Integer, List<String>> test(String... list) {
+      Map<Integer, List<String>> map = Arrays.stream(list).filter(Objects::nonNull).collect(Collectors.groupingBy(String::length, Collectors.mapping(String::trim, Collectors.toCollection(LinkedList::new))));
+      return map;
+  }
+
+  public static void main(String[] args) {
+    System.out.println(new Main().test("a", "bbb", null, "cc", "dd", "eedasfasdfs", "dd"));
+  }
+}
diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/streamApiMigration/afterGroupingByDownstream.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/streamApiMigration/afterGroupingByDownstream.java
new file mode 100644 (file)
index 0000000..cdec5a6
--- /dev/null
@@ -0,0 +1,14 @@
+// "Replace with collect" "true"
+import java.util.*;
+import java.util.stream.Collectors;
+
+public class Main {
+  private Map<Integer, List<String>> test(String... list) {
+      HashMap<Integer, List<String>> map = Arrays.stream(list).filter(Objects::nonNull).collect(Collectors.groupingBy(String::length, HashMap::new, Collectors.mapping(String::trim, Collectors.toList())));
+      return map;
+  }
+
+  public static void main(String[] args) {
+    System.out.println(new Main().test("a", "bbb", null, "cc", "dd", "eedasfasdfs", "dd"));
+  }
+}
diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/streamApiMigration/afterGroupingBySimple.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/streamApiMigration/afterGroupingBySimple.java
new file mode 100644 (file)
index 0000000..01de5cd
--- /dev/null
@@ -0,0 +1,14 @@
+// "Replace with collect" "true"
+import java.util.*;
+import java.util.stream.Collectors;
+
+public class Main {
+  private Map<Integer, List<String>> test(String... list) {
+      Map<Integer, List<String>> map = Arrays.stream(list).filter(Objects::nonNull).collect(Collectors.groupingBy(String::length));
+      return map;
+  }
+
+  public static void main(String[] args) {
+    System.out.println(new Main().test("a", "bbb", null, "cc", "dd", "eedasfasdfs", "dd"));
+  }
+}
diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/streamApiMigration/beforeCollectToMap.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/streamApiMigration/beforeCollectToMap.java
new file mode 100644 (file)
index 0000000..65cf03c
--- /dev/null
@@ -0,0 +1,19 @@
+// "Replace with collect" "true"
+import java.util.HashMap;
+import java.util.Map;
+
+public class Main {
+  private Map<String, Integer> test(String... list) {
+    Map<String, Integer> map = new HashMap<>();
+    for(String s : li<caret>st) {
+      if(s != null) {
+        map.merge(s, 1, (a, b) -> a + b);
+      }
+    }
+    return map;
+  }
+
+  public static void main(String[] args) {
+    System.out.println(new Main().test("a", "bbb", null, "cc", "dd", "eedasfasdfs", "dd"));
+  }
+}
diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/streamApiMigration/beforeCollectToMapPut.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/streamApiMigration/beforeCollectToMapPut.java
new file mode 100644 (file)
index 0000000..3598633
--- /dev/null
@@ -0,0 +1,19 @@
+// "Replace with collect" "true"
+import java.util.HashMap;
+import java.util.Map;
+
+public class Main {
+  private Map<String, Integer> test(String... list) {
+    HashMap<String, Integer> map = new HashMap<>();
+    for(String s : lis<caret>t) {
+      if(s != null) {
+        map.put(s, 1);
+      }
+    }
+    return map;
+  }
+
+  public static void main(String[] args) {
+    System.out.println(new Main().test("a", "bbb", null, "cc", "dd", "eedasfasdfs", "dd"));
+  }
+}
diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/streamApiMigration/beforeCollectToMapPutIfAbsent.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/streamApiMigration/beforeCollectToMapPutIfAbsent.java
new file mode 100644 (file)
index 0000000..5ebecf2
--- /dev/null
@@ -0,0 +1,19 @@
+// "Replace with collect" "true"
+import java.util.LinkedHashMap;
+import java.util.Map;
+
+public class Main {
+  private Map<String, Integer> test(String... list) {
+    Map<String, Integer> map = new LinkedHashMap<>();
+    for(String s : l<caret>ist) {
+      if(s != null) {
+        map.putIfAbsent(s, 1);
+      }
+    }
+    return map;
+  }
+
+  public static void main(String[] args) {
+    System.out.println(new Main().test("a", "bbb", null, "cc", "dd", "eedasfasdfs", "dd"));
+  }
+}
diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/streamApiMigration/beforeCollectToMapPutInvalid.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/streamApiMigration/beforeCollectToMapPutInvalid.java
new file mode 100644 (file)
index 0000000..618d373
--- /dev/null
@@ -0,0 +1,19 @@
+// "Replace with collect" "false"
+import java.util.HashMap;
+import java.util.Map;
+
+public class Main {
+  private Map<String, Integer> test(String... list) {
+    HashMap<String, Integer> map = new HashMap<>();
+    for(String s : lis<caret>t) {
+      if(s != null) {
+        map.put(s, 1,);
+      }
+    }
+    return map;
+  }
+
+  public static void main(String[] args) {
+    System.out.println(new Main().test("a", "bbb", null, "cc", "dd", "eedasfasdfs", "dd"));
+  }
+}
diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/streamApiMigration/beforeGroupingByArrayList.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/streamApiMigration/beforeGroupingByArrayList.java
new file mode 100644 (file)
index 0000000..ef6a60f
--- /dev/null
@@ -0,0 +1,18 @@
+// "Replace with collect" "true"
+import java.util.*;
+
+public class Main {
+  private Map<Integer, ArrayList<String>> test(String... list) {
+    Map<Integer, ArrayList<String>> map = new HashMap<>();
+    for(String s : li<caret>st) {
+      if(s != null) {
+        map.computeIfAbsent(s.length(), k -> new ArrayList<>()).add(s);
+      }
+    }
+    return map;
+  }
+
+  public static void main(String[] args) {
+    System.out.println(new Main().test("a", "bbb", null, "cc", "dd", "eedasfasdfs", "dd"));
+  }
+}
diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/streamApiMigration/beforeGroupingByCustomCollection.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/streamApiMigration/beforeGroupingByCustomCollection.java
new file mode 100644 (file)
index 0000000..754794b
--- /dev/null
@@ -0,0 +1,18 @@
+// "Replace with collect" "true"
+import java.util.*;
+
+public class Main {
+  private Map<Integer, List<String>> test(String... list) {
+    Map<Integer, List<String>> map = new HashMap<>();
+    for(String s : li<caret>st) {
+      if(s != null) {
+        map.computeIfAbsent(s.length(), k -> new LinkedList<>()).add(s.trim());
+      }
+    }
+    return map;
+  }
+
+  public static void main(String[] args) {
+    System.out.println(new Main().test("a", "bbb", null, "cc", "dd", "eedasfasdfs", "dd"));
+  }
+}
diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/streamApiMigration/beforeGroupingByDownstream.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/streamApiMigration/beforeGroupingByDownstream.java
new file mode 100644 (file)
index 0000000..ac7d6cb
--- /dev/null
@@ -0,0 +1,18 @@
+// "Replace with collect" "true"
+import java.util.*;
+
+public class Main {
+  private Map<Integer, List<String>> test(String... list) {
+    HashMap<Integer, List<String>> map = new HashMap<>();
+    for(String s : li<caret>st) {
+      if(s != null) {
+        map.computeIfAbsent(s.length(), k -> new ArrayList<>()).add(s.trim());
+      }
+    }
+    return map;
+  }
+
+  public static void main(String[] args) {
+    System.out.println(new Main().test("a", "bbb", null, "cc", "dd", "eedasfasdfs", "dd"));
+  }
+}
diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/streamApiMigration/beforeGroupingBySimple.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/streamApiMigration/beforeGroupingBySimple.java
new file mode 100644 (file)
index 0000000..5294c53
--- /dev/null
@@ -0,0 +1,18 @@
+// "Replace with collect" "true"
+import java.util.*;
+
+public class Main {
+  private Map<Integer, List<String>> test(String... list) {
+    Map<Integer, List<String>> map = new HashMap<>();
+    for(String s : li<caret>st) {
+      if(s != null) {
+        map.computeIfAbsent(s.length(), k -> new ArrayList<>()).add(s);
+      }
+    }
+    return map;
+  }
+
+  public static void main(String[] args) {
+    System.out.println(new Main().test("a", "bbb", null, "cc", "dd", "eedasfasdfs", "dd"));
+  }
+}
diff --git a/java/java-tests/testData/inspection/suspiciousCalls/NewExpressionPassedToMapContains.java b/java/java-tests/testData/inspection/suspiciousCalls/NewExpressionPassedToMapContains.java
new file mode 100644 (file)
index 0000000..b0a46d2
--- /dev/null
@@ -0,0 +1,9 @@
+import java.util.*;
+
+class Foo<T extends List<Integer>> {
+
+  public void foo() {
+    Map<T, T> map = new HashMap<>();
+    map.containsKey(<warning descr="Suspicious call to 'Map.containsKey'">new HashMap<>()</warning>);
+  }
+}
\ No newline at end of file
index 41164ea97600e38d9180b1bace9f0590c251553a..a4166226fab50b1b23267c829c9ea7f712cb63e7 100644 (file)
@@ -1,15 +1,15 @@
 import java.io.*;
 
 class Test {
-  private static InputStream getInputUnchecked(InputStream inputSupplier) throws IOException {
-    InputStream in;
-    try {
-      in = null;
+    private static InputStream getInputUnchecked(InputStream inputSupplier) throws IOException {
+        InputStream in;
+        try {
+          in = null;
+        }
+        catch (IOException e) {
+            throw new IOException();
+        }
+        return i<caret>n;
     }
-    catch (IOException e) {
-      throw new IOException();
-    }
-    return i<caret>n;
-  }
 
 }
\ No newline at end of file
index 1853d8acca74d6abfce378ddce6c1b92ee576157..8f1e51ef47f820baa73d669fb4eb832e7babbc59 100644 (file)
@@ -1,13 +1,13 @@
 import java.io.*;
 
 class Test {
-  private static InputStream getInputUnchecked(InputStream inputSupplier) throws IOException {
-      try {
-      }
-    catch (IOException e) {
-      throw new IOException();
+    private static InputStream getInputUnchecked(InputStream inputSupplier) throws IOException {
+        try {
+        }
+        catch (IOException e) {
+            throw new IOException();
+        }
+        return null;
     }
-    return null;
-  }
 
 }
\ No newline at end of file
index 5e6b20fafd8a29a9d2ca46c51c0352d6fa601424..50fa1403fdfb8d52b40c9aa4bb73dd78dc04d2d1 100644 (file)
@@ -21,7 +21,7 @@ import com.intellij.openapi.editor.ex.EditorSettingsExternalizable
 import org.assertj.core.api.Assertions
 
 class JavaInlayParameterHintsTest : InlayParameterHintsTest() {
-  
+
   fun setup(text: String) = configureFile("a.java", text)
 
   fun `test insert literal arguments`() {
@@ -47,13 +47,13 @@ class Groo {
 }""")
 
     onLineStartingWith("configure(true").assertInlays(
-        "testNow->true",
-        "shouldIgnoreRoots->false",
-        "times->555",
-        "pii->3.141f",
-        """title->"Huge Title"""",
-        "terminate->'c'",
-        "file->null"
+      "testNow->true",
+      "shouldIgnoreRoots->false",
+      "times->555",
+      "pii->3.141f",
+      """title->"Huge Title"""",
+      "terminate->'c'",
+      "file->null"
     )
 
     onLineStartingWith("configure(testNow").assertNoInlays()
@@ -70,10 +70,10 @@ class Fooo {
   
 }
 """)
-    
+
     onLineStartingWith("Throw").assertNoInlays()
   }
-  
+
 
   fun `test show hint for single string literal if there is multiple string params`() {
     setup("""class Groo {
@@ -94,7 +94,7 @@ class Fooo {
     onLineStartingWith("assertEquals").assertInlays("expected->\"fooo\"")
     onLineStartingWith("show").assertInlays("message->\"Hi\"")
   }
-  
+
   fun `test no hints for generic builders`() {
     setup("""
 class Foo {
@@ -112,7 +112,7 @@ class Stream<T> {
   public Stream<T> skip(int n) {}
 }
 """)
-    
+
     onLineStartingWith("new IntStream").assertNoInlays()
     onLineStartingWith("new Stream").assertNoInlays()
   }
@@ -152,7 +152,7 @@ public class VarArgTest {
 """)
 
     onLineStartingWith("testBooleanVarargs")
-        .assertInlays("test->13", "...booleans->false")
+      .assertInlays("test->13", "...booleans->false")
   }
 
   fun `test no hint if varargs null`() {
@@ -191,7 +191,7 @@ public class VarArgTest {
 """)
 
     onLineStartingWith("testBooleanVarargs")
-        .assertInlays("test->13", "...booleans->false")
+      .assertInlays("test->13", "...booleans->false")
   }
 
   fun `test do not inline if parameter length is one or two`() {
@@ -263,7 +263,7 @@ public class CharSymbol {
 """)
 
     onLineStartingWith("count(1")
-        .assertInlays("test->100", "boo->false", """seq->"Hi!"""")
+      .assertInlays("test->100", "boo->false", """seq->"Hi!"""")
   }
 
   fun `test inline positive and negative numbers`() {
@@ -284,10 +284,10 @@ public class CharSymbol {
 """)
 
     onLineStartingWith("count(-")
-        .assertInlays("test->-")
+      .assertInlays("test->-")
 
     onLineStartingWith("count(+")
-        .assertInlays("test->+")
+      .assertInlays("test->+")
   }
 
   fun `test inline literal arguments with crazy settings`() {
@@ -305,10 +305,10 @@ public class Test {
 """)
 
     onLineStartingWith("System")
-        .assertNoInlays()
+      .assertNoInlays()
 
     onLineStartingWith("main(t")
-        .assertInlays("isActive->true", "requestFocus->false", "xoo->2")
+      .assertInlays("isActive->true", "requestFocus->false", "xoo->2")
   }
 
 
@@ -377,10 +377,10 @@ public class Test {
 """)
 
     onLineStartingWith("c.compare")
-        .assertInlays("o1->0", "o2->3")
+      .assertInlays("o1->0", "o2->3")
 
     onLineStartingWith("l.add")
-        .assertInlays("query->1", """obj->"uuu"""")
+      .assertInlays("query->1", """obj->"uuu"""")
   }
 
   fun `test inline constructor literal arguments names`() {
@@ -404,7 +404,7 @@ public class Test {
 """)
 
     onLineStartingWith("Checker r")
-        .assertInlays("isActive->true", "requestFocus->false")
+      .assertInlays("isActive->true", "requestFocus->false")
   }
 
   fun `test inline anonymous class constructor parameters`() {
@@ -425,7 +425,7 @@ public class Test {
 """)
 
     onLineStartingWith("Test t")
-        .assertInlays("counter->10", "shouldTest->false")
+      .assertInlays("counter->10", "shouldTest->false")
   }
 
   fun `test inline if one of vararg params is literal`() {
@@ -448,7 +448,7 @@ public class VarArgTest {
 """)
 
     onLineStartingWith("testBooleanVarargs")
-        .assertInlays("...booleans->isCheck")
+      .assertInlays("...booleans->isCheck")
   }
 
   fun `test if any param matches inline all`() {
@@ -466,7 +466,7 @@ public class VarArgTest {
 """)
 
     onLineStartingWith("check(")
-        .assertInlays("x->10", "paramNameLength->1000")
+      .assertInlays("x->10", "paramNameLength->1000")
   }
 
   fun `test inline common name pair if more that 2 args`() {
@@ -485,7 +485,7 @@ public class VarArgTest {
 """)
 
     onLineStartingWith("check(")
-        .assertInlays("beginIndex->10", "endIndex->1000")
+      .assertInlays("beginIndex->10", "endIndex->1000")
   }
 
   fun `test ignore String methods`() {
@@ -517,7 +517,7 @@ public class VarArgTest {
 """)
 
     onLineStartingWith("check(")
-        .assertInlays("beginIndex->10", "endIndex->1000", """x->"su"""" )
+      .assertInlays("beginIndex->10", "endIndex->1000", """x->"su"""")
   }
 
   fun `test inline this`() {
@@ -535,7 +535,7 @@ public class VarArgTest {
 """)
 
     onLineStartingWith("check(t")
-        .assertInlays("test->this", "endIndex->1000")
+      .assertInlays("test->this", "endIndex->1000")
   }
 
   fun `test inline strange methods`() {
@@ -724,7 +724,7 @@ class Key {
     onLineStartingWith("System.set").assertNoInlays()
     onLineStartingWith("new").assertNoInlays()
   }
-  
+
   fun `test poly and binary expressions`() {
     setup("""
 class Test {
@@ -745,7 +745,7 @@ class Test {
     onLineStartingWith("int").assertInlays("isShow->1")
     onLineStartingWith("yyy").assertInlays("followTheSum->200")
   }
-  
+
   fun `test incorrect pattern`() {
     ParameterNameHintsSettings.getInstance().addIgnorePattern(JavaLanguage.INSTANCE, "")
     setup("""
@@ -764,13 +764,15 @@ class Test {
 class Test {
   void main() {
     timeoutExecution(1000);
+    createSpace(true);
   }
-  void timeoutExecution(int timeout) {
-  }
+  void timeoutExecution(int timeout) {}
+  void createSpace(boolean space) {}
 }
 """)
 
     onLineStartingWith("timeoutExec").assertNoInlays()
+    onLineStartingWith("createSpace").assertNoInlays()
   }
 
   fun `test show if multiple params but name contained`() {
@@ -779,14 +781,18 @@ class Test {
 class Test {
   void main() {
     timeoutExecution(1000, "xxx");
+    createSpace(true, 10);
   }
-  void timeoutExecution(int timeout, String message) {
-  }
+  void timeoutExecution(int timeout, String message) {}
+  void createSpace(boolean space, int a) {}
 }
 """)
 
     onLineStartingWith("timeout")
       .assertInlays("timeout->1000", "message->\"xxx\"")
+
+    onLineStartingWith("createSpace")
+      .assertInlays("space->true", "a->10")
   }
 
   fun `test show same params`() {
@@ -806,4 +812,36 @@ class Test {
     onLineStartingWith("test").assertInlays("parent->c", "child->d")
   }
 
+  fun `test show triple`() {
+    ParameterNameHintsSettings.getInstance().isShowForParamsWithSameType = true
+    setup("""
+class Test {
+  void main() {
+    String c = "c";
+    test(c, c, c);
+  }
+  void test(String parent, String child, String grandParent) {
+  }
+}
+""")
+    onLineStartingWith("test").assertInlays("parent->c", "child->c", "grandParent->c")
+  }
+
+  fun `test show couple of doubles`() {
+    ParameterNameHintsSettings.getInstance().isShowForParamsWithSameType = true
+    setup("""
+class Test {
+  void main() {
+    String c = "c";
+    String d = "d";
+    int v = 10;
+    test(c, d, v, v);
+  }
+  void test(String parent, String child, int vx, int vy) {
+  }
+}
+""")
+    onLineStartingWith("test").assertInlays("parent->c", "child->d", "vx->v", "vy->v")
+  }
+
 }
\ No newline at end of file
index 8619792bb6313379d27a6ea42750e136e08c22ac..12f726f0afc87ab6b54e88acaac8c5058bc62e4d 100644 (file)
@@ -1,3 +1,18 @@
+/*
+ * Copyright 2000-2016 JetBrains s.r.o.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
 package com.intellij.codeInspection;
 
 import com.intellij.JavaTestUtil;
@@ -25,6 +40,7 @@ public class SuspiciousCollectionMethodCallsTest extends LightCodeInsightFixture
   public void testUseDfa() throws Exception { doTest(); }
   public void testWildcard() throws Exception { doTest(); }
   public void testPolyConditionalExpressionPassedToMapGetCall() throws Exception { doTest(); }
+  public void testNewExpressionPassedToMapContains() throws Exception { doTest(); }
   public void testIgnoreConvertible() throws Exception {
     myTool.REPORT_CONVERTIBLE_METHOD_CALLS = false;
     doTest();
index 8222a919c839b1b9c8645fbcdc72397f4e0f9d04..e10fbee71add88e2c81b6e145f368efcf5750a0c 100644 (file)
@@ -105,8 +105,7 @@ public abstract class CodeInsightTestCase extends PsiTestCase {
     try {
       if (myProject != null) {
         FileEditorManager editorManager = FileEditorManager.getInstance(myProject);
-        VirtualFile[] openFiles = editorManager.getOpenFiles();
-        for (VirtualFile openFile : openFiles) {
+        for (VirtualFile openFile : editorManager.getOpenFiles()) {
           editorManager.closeFile(openFile);
         }
       }
index 7263895299903201649a64bc91f842ea67b0db32..cde46b673e67649185b5b76337f58c2a7dd0db6c 100644 (file)
@@ -66,8 +66,7 @@ public class JsonSchemaConflictNotificationProvider extends EditorNotifications.
     final String message = worker.createMessage(descriptors);
     if (message == null) return null;
 
-    final EditorNotificationPanel panel = new EditorNotificationPanel();
-    panel.background(LightColors.RED);
+    final EditorNotificationPanel panel = new EditorNotificationPanel(LightColors.RED);
     panel.setText(message);
     panel.createActionLabel("Edit JSON Schema Mappings", () -> {
       ShowSettingsUtil.getInstance().editConfigurable(myProject, new JsonSchemaMappingsConfigurable(myProject));
index 925e861c189ee84fdb4af72858b4da43168034bb..9bcb6b9af295792da0ae80e5cb18efc85d871803 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2014 JetBrains s.r.o.
+ * Copyright 2000-2016 JetBrains s.r.o.
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -110,12 +110,14 @@ public class HighlightSeverity implements Comparable<HighlightSeverity> {
 
     final HighlightSeverity that = (HighlightSeverity)o;
 
+    if (myVal != that.myVal) return false;
     return myName.equals(that.myName);
   }
 
   @Override
   public int hashCode() {
-    return myName.hashCode();
+    int result = myName != null ? myName.hashCode() : 0;
+    return 31 * result + myVal;
   }
 
   @NotNull
index b31ed3e9fb93c25addcc8ad3a77cd177b0da647a..bbda5df7a026137a1d814a0ee937dd9c307ee9c3 100644 (file)
@@ -628,6 +628,9 @@ public class ApplicationInfoImpl extends ApplicationInfoEx {
     return ourShadowInstance;
   }
 
+  /**
+   * Behavior of this method must be consistent with idea/ApplicationInfo.xsd schema.
+   */
   private void loadState(Element parentNode) {
     Element versionElement = getChild(parentNode, ELEMENT_VERSION);
     if (versionElement != null) {
index 188fbce9651643ca2acf06c3fbb09b83622db658..a0e0ed9d09446995939292ef597911cfc9cd5e7a 100644 (file)
@@ -87,9 +87,8 @@ public class DiffNotifications {
 
   @NotNull
   public static JPanel createNotification(@NotNull String text, @Nullable final Color background, boolean showHideAction) {
-    final EditorNotificationPanel panel = new EditorNotificationPanel();
+    final EditorNotificationPanel panel = new EditorNotificationPanel(background);
     panel.text(text);
-    panel.background(background);
     if (showHideAction) {
       HyperlinkLabel link = panel.createActionLabel("Hide", () -> panel.setVisible(false));
       link.setToolTipText("Hide this notification");
index e195cd1932184da62a23f3c866c40049c46eee2c..c20b16df3e89b1dd6d2f3e1ddc02da50a4b83732 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2014 JetBrains s.r.o.
+ * Copyright 2000-2016 JetBrains s.r.o.
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -38,9 +38,11 @@ public interface AnActionListener {
   /**
    * Note that using <code>dataContext</code> in implementing methods is unsafe - it could have been invalidated by the performed action.
    */
-  void afterActionPerformed(AnAction action, DataContext dataContext, AnActionEvent event);
+  default void afterActionPerformed(AnAction action, DataContext dataContext, AnActionEvent event) {
+  }
 
-  void beforeEditorTyping(char c, DataContext dataContext);
+  default void beforeEditorTyping(char c, DataContext dataContext) {
+  }
 
   abstract class Adapter implements AnActionListener {
     @Override
index c485258bfcb3824eec026c3f85df8d2fd60ab086..71b719d20bd70d0677d26efdcc7aaad1456ed4f0 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2015 JetBrains s.r.o.
+ * Copyright 2000-2016 JetBrains s.r.o.
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -51,9 +51,6 @@ import com.intellij.openapi.module.JavaModuleType;
 import com.intellij.openapi.module.ModuleType;
 import com.intellij.openapi.module.StdModuleTypes;
 import com.intellij.openapi.project.ProjectBundle;
-import com.intellij.openapi.projectRoots.JavaSdkType;
-import com.intellij.openapi.projectRoots.JdkUtil;
-import com.intellij.openapi.projectRoots.Sdk;
 import com.intellij.openapi.projectRoots.SimpleJavaSdkType;
 import com.intellij.openapi.roots.DependencyScope;
 import com.intellij.openapi.util.ShutDownTracker;
@@ -198,13 +195,7 @@ public class RemoteExternalSystemCommunicationManager implements ExternalSystemC
       @NotNull
       protected OSProcessHandler startProcess() throws ExecutionException {
         SimpleJavaParameters params = createJavaParameters();
-        Sdk sdk = params.getJdk();
-        if (sdk == null) {
-          throw new ExecutionException("No sdk is defined. Params: " + params);
-        }
-
-        String executablePath = ((JavaSdkType)sdk.getSdkType()).getVMExecutablePath(sdk);
-        GeneralCommandLine commandLine = JdkUtil.setupJVMCommandLine(executablePath, params, false);
+        GeneralCommandLine commandLine = params.toCommandLine();
         OSProcessHandler processHandler = new OSProcessHandler(commandLine);
         ProcessTerminatedListener.attach(processHandler);
         return processHandler;
index 2eaabf2050ef76278d37aab104653299f634e02e..b3e3df06052a43c909f6283f123b478a612a9199 100644 (file)
@@ -1,3 +1,18 @@
+/*
+ * Copyright 2000-2016 JetBrains s.r.o.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
 package com.intellij.openapi.externalSystem.service.execution;
 
 import com.intellij.openapi.externalSystem.model.ProjectSystemId;
@@ -24,13 +39,13 @@ public class ExternalSystemRunConfigurationEditor extends SettingsEditor<Externa
   }
 
   @Override
-  protected void resetEditorFrom(ExternalSystemRunConfiguration s) {
+  protected void resetEditorFrom(@NotNull ExternalSystemRunConfiguration s) {
     myControl.setOriginalSettings(s.getSettings());
     myControl.reset();
   }
 
   @Override
-  protected void applyEditorTo(ExternalSystemRunConfiguration s) throws ConfigurationException {
+  protected void applyEditorTo(@NotNull ExternalSystemRunConfiguration s) throws ConfigurationException {
     myControl.apply(s.getSettings());
   }
 
index b1face870522bc1c67ff111f7548922f40f348d0..583e840654101c8eeabf03561a14884cc8f63b6d 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2009 JetBrains s.r.o.
+ * Copyright 2000-2016 JetBrains s.r.o.
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -174,11 +174,11 @@ public class UnknownRunConfiguration implements RunConfiguration, WithoutOwnBefo
     }
 
     @Override
-    protected void resetEditorFrom(final UnknownRunConfiguration s) {
+    protected void resetEditorFrom(@NotNull final UnknownRunConfiguration s) {
     }
 
     @Override
-    protected void applyEditorTo(final UnknownRunConfiguration s) throws ConfigurationException {
+    protected void applyEditorTo(@NotNull final UnknownRunConfiguration s) throws ConfigurationException {
     }
 
     @Override
diff --git a/platform/lang-impl/src/com/intellij/application/options/DefaultSchemeActions.java b/platform/lang-impl/src/com/intellij/application/options/DefaultSchemeActions.java
new file mode 100644 (file)
index 0000000..ea6cc8d
--- /dev/null
@@ -0,0 +1,198 @@
+/*
+ * Copyright 2000-2016 JetBrains s.r.o.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.intellij.application.options;
+
+import com.intellij.openapi.actionSystem.*;
+import com.intellij.openapi.options.Scheme;
+import com.intellij.openapi.options.SchemeExporterEP;
+import com.intellij.openapi.options.SchemeImporterEP;
+import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.List;
+
+public abstract class DefaultSchemeActions<T extends Scheme> {
+  private final Collection<String> mySchemeImportersNames;
+  private final Collection<String> mySchemeExporterNames;
+
+  protected DefaultSchemeActions() {
+    mySchemeImportersNames = getSchemeImportersNames();
+    mySchemeExporterNames = getSchemeExporterNames();
+  }
+  
+    
+  private Collection<String> getSchemeImportersNames() {
+    List<String> importersNames = new ArrayList<>();
+    for (SchemeImporterEP importerEP : SchemeImporterEP.getExtensions(getSchemeType())) {
+      importersNames.add(importerEP.name);
+    }
+    return importersNames;
+  }
+  
+  private Collection<String> getSchemeExporterNames() {
+    List<String> exporterNames = new ArrayList<>();
+    for (SchemeExporterEP exporterEP : SchemeExporterEP.getExtensions(getSchemeType())) {
+      exporterNames.add(exporterEP.name);
+    }
+    return exporterNames;
+  }
+
+  public final Collection<AnAction> getActions() {
+    List<AnAction> actions = new ArrayList<>();
+    actions.add(new CopyAction());
+    actions.add(new ResetAction());
+    actions.add(new DeleteAction());
+    actions.add(new Separator());
+    if (!mySchemeExporterNames.isEmpty()) {
+      actions.add(new ExportGroup());
+    }
+    if (!mySchemeImportersNames.isEmpty()) {
+      actions.add(new ImportGroup());
+    }
+    addAdditionalActions(actions);
+    return actions;
+  }
+  
+  protected void addAdditionalActions(@NotNull List<AnAction> defaultActions) {}
+  
+  private class ResetAction extends AnAction {
+    
+    public ResetAction() {
+      super("Reset");
+    }
+
+    @Override
+    public void actionPerformed(AnActionEvent e) {
+      doReset();
+    }
+  }
+  
+  
+  private class CopyAction extends AnAction {
+    public CopyAction() {
+      super("Copy...");
+    }
+
+    @Override
+    public void actionPerformed(AnActionEvent e) {
+      doSaveAs();
+    }
+  }
+  
+  private class DeleteAction extends AnAction {
+    public DeleteAction() {
+      super("Delete");
+    }
+
+    @Override
+    public void actionPerformed(AnActionEvent e) {
+      doDelete();
+    }
+
+    @Override
+    public void update(AnActionEvent e) {
+      Presentation p = e.getPresentation();
+      T currentScheme = getCurrentScheme(); 
+      p.setEnabled(currentScheme != null && isDeleteAvailable(currentScheme));
+    }
+  }
+
+  private class ImportGroup extends ActionGroup {
+
+    public ImportGroup() {
+      super("Import", true);
+    }
+
+    @NotNull
+    @Override
+    public AnAction[] getChildren(@Nullable AnActionEvent e) {
+      List<ImportAction> importActions = new ArrayList<>();
+      for (String importerName : mySchemeImportersNames) {
+        importActions.add(new ImportAction(importerName));
+      }
+      return importActions.toArray(new AnAction[importActions.size()]);
+    }
+  }
+  
+  private class ImportAction extends AnAction {
+
+    private String myImporterName;
+
+    public ImportAction(@NotNull String importerName) {
+      super(importerName);
+      myImporterName = importerName;
+    }
+
+    @Override
+    public void actionPerformed(AnActionEvent e) {
+      doImport(myImporterName);
+    }
+  }
+
+  private class ExportGroup extends ActionGroup {
+    public ExportGroup() {
+      super("Export As", true);
+    }
+
+    @NotNull
+    @Override
+    public AnAction[] getChildren(@Nullable AnActionEvent e) {
+      List<ExportAction> exportActions = new ArrayList<>();
+      for (String exporterName : mySchemeExporterNames) {
+        exportActions.add(new ExportAction(exporterName));
+      }
+      return exportActions.toArray(new AnAction[exportActions.size()]);
+    }
+  }
+  
+  private class ExportAction extends AnAction {
+    private String myExporterName;
+
+    public ExportAction(@NotNull String exporterName) {
+      super(exporterName);
+      myExporterName = exporterName;
+    }
+
+    @Override
+    public void actionPerformed(AnActionEvent e) {
+      T currentScheme = getCurrentScheme();
+      if (currentScheme != null) {
+        doExport(currentScheme, myExporterName);
+      }
+    }
+  }
+
+  protected abstract void doImport(@NotNull String importerName);
+
+  protected abstract void doReset();
+  
+  protected abstract void doSaveAs();
+  
+  protected abstract void doDelete();
+  
+  protected abstract boolean isDeleteAvailable(@NotNull T scheme);
+  
+  protected abstract void doExport(@NotNull T scheme, @NotNull String exporterName);
+  
+  @Nullable
+  protected abstract T getCurrentScheme();
+  
+  protected abstract Class<T> getSchemeType();
+
+}
+
diff --git a/platform/lang-impl/src/com/intellij/application/options/codeStyle/CodeStyleSchemeExporterUI.java b/platform/lang-impl/src/com/intellij/application/options/codeStyle/CodeStyleSchemeExporterUI.java
deleted file mode 100644 (file)
index cc08b6a..0000000
+++ /dev/null
@@ -1,128 +0,0 @@
-/*
- * Copyright 2000-2015 JetBrains s.r.o.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.intellij.application.options.codeStyle;
-
-import com.intellij.openapi.application.ApplicationBundle;
-import com.intellij.openapi.application.WriteAction;
-import com.intellij.openapi.fileChooser.FileChooserFactory;
-import com.intellij.openapi.fileChooser.FileSaverDescriptor;
-import com.intellij.openapi.fileChooser.FileSaverDialog;
-import com.intellij.openapi.options.SchemeExporter;
-import com.intellij.openapi.options.SchemeExporterEP;
-import com.intellij.openapi.ui.MessageType;
-import com.intellij.openapi.ui.popup.JBPopupFactory;
-import com.intellij.openapi.ui.popup.ListPopup;
-import com.intellij.openapi.ui.popup.PopupStep;
-import com.intellij.openapi.ui.popup.util.BaseListPopupStep;
-import com.intellij.openapi.vfs.VirtualFile;
-import com.intellij.openapi.vfs.VirtualFileWrapper;
-import com.intellij.psi.codeStyle.CodeStyleScheme;
-import com.intellij.util.ArrayUtil;
-import org.jetbrains.annotations.NotNull;
-
-import java.awt.*;
-import java.io.OutputStream;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.List;
-
-
-/**
- * @author Rustam Vishnyakov
- */
-class CodeStyleSchemeExporterUI {
-  @NotNull private final Component myParentComponent;
-  @NotNull private final CodeStyleScheme myScheme;
-  @NotNull private final StatusCallback myStatusCallback;
-
-  CodeStyleSchemeExporterUI(@NotNull Component parentComponent, @NotNull CodeStyleScheme scheme, @NotNull StatusCallback statusCallback) {
-    myParentComponent = parentComponent;
-    myScheme = scheme;
-    myStatusCallback = statusCallback;
-  }
-
-  void export() {
-    ListPopup popup = JBPopupFactory.getInstance().createListPopup(
-      new BaseListPopupStep<String>(ApplicationBundle.message("scheme.exporter.ui.export.as.title"), enumExporters()) {
-        @Override
-        public PopupStep onChosen(final String selectedValue, boolean finalChoice) {
-          return doFinalStep(() -> exportSchemeUsing(selectedValue));
-        }
-      });
-    popup.showInCenterOf(myParentComponent);
-  }
-
-  private static String[] enumExporters() {
-    List<String> names = new ArrayList<>();
-    Collection<SchemeExporterEP<CodeStyleScheme>> extensions = SchemeExporterEP.getExtensions(CodeStyleScheme.class);
-    for (SchemeExporterEP<CodeStyleScheme> extension : extensions) {
-      names.add(extension.name);
-    }
-    return ArrayUtil.toStringArray(names);
-  }
-
-  private void exportSchemeUsing(@NotNull String exporterName) {
-    SchemeExporter<CodeStyleScheme> exporter = SchemeExporterEP.getExporter(exporterName, CodeStyleScheme.class);
-    if (exporter != null) {
-      String ext = exporter.getExtension();
-      FileSaverDialog saver =
-        FileChooserFactory.getInstance()
-          .createSaveFileDialog(new FileSaverDescriptor(
-            ApplicationBundle.message("scheme.exporter.ui.file.chooser.title"),
-            ApplicationBundle.message("scheme.exporter.ui.file.chooser.message"),
-            ext), myParentComponent);
-      VirtualFileWrapper target = saver.save(null, getFileNameSuggestion() + "." + ext);
-      if (target != null) {
-        VirtualFile targetFile = target.getVirtualFile(true);
-        String message;
-        MessageType messageType;
-        if (targetFile != null) {
-          try {
-            WriteAction.run(() -> {
-              OutputStream outputStream = targetFile.getOutputStream(this);
-              try {
-                exporter.exportScheme(myScheme, outputStream);
-              }
-              finally {
-                outputStream.close();
-              }
-            });
-            message = ApplicationBundle
-              .message("scheme.exporter.ui.code.style.exported.message", myScheme.getName(), targetFile.getPresentableUrl());
-            messageType = MessageType.INFO;
-          }
-          catch (Exception e) {
-            message = ApplicationBundle.message("scheme.exporter.ui.export.failed", e.getMessage());
-            messageType = MessageType.ERROR;
-          }
-        }
-        else {
-          message = ApplicationBundle.message("scheme.exporter.ui.cannot.write.message");
-          messageType = MessageType.ERROR;
-        }
-        myStatusCallback.showMessage(message, messageType);
-      }
-    }
-  }
-
-  private String getFileNameSuggestion() {
-    return myScheme.getName();
-  }
-
-  interface StatusCallback {
-    void showMessage(@NotNull String message, @NotNull MessageType messageType);
-  }
-}
diff --git a/platform/lang-impl/src/com/intellij/application/options/codeStyle/CodeStyleSchemesActions.java b/platform/lang-impl/src/com/intellij/application/options/codeStyle/CodeStyleSchemesActions.java
new file mode 100644 (file)
index 0000000..02943be
--- /dev/null
@@ -0,0 +1,291 @@
+/*
+ * Copyright 2000-2016 JetBrains s.r.o.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.intellij.application.options.codeStyle;
+
+import com.intellij.application.options.DefaultSchemeActions;
+import com.intellij.application.options.SaveSchemeDialog;
+import com.intellij.application.options.SchemesToImportPopup;
+import com.intellij.openapi.actionSystem.AnAction;
+import com.intellij.openapi.actionSystem.AnActionEvent;
+import com.intellij.openapi.actionSystem.Presentation;
+import com.intellij.openapi.actionSystem.Separator;
+import com.intellij.openapi.application.ApplicationBundle;
+import com.intellij.openapi.application.WriteAction;
+import com.intellij.openapi.fileChooser.FileChooserFactory;
+import com.intellij.openapi.fileChooser.FileSaverDescriptor;
+import com.intellij.openapi.fileChooser.FileSaverDialog;
+import com.intellij.openapi.options.*;
+import com.intellij.openapi.ui.MessageType;
+import com.intellij.openapi.ui.Messages;
+import com.intellij.openapi.util.text.StringUtil;
+import com.intellij.openapi.vfs.VirtualFile;
+import com.intellij.openapi.vfs.VirtualFileWrapper;
+import com.intellij.psi.codeStyle.CodeStyleScheme;
+import com.intellij.psi.impl.source.codeStyle.CodeStyleSchemesImpl;
+import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
+
+import javax.swing.*;
+import java.io.OutputStream;
+import java.util.Collection;
+import java.util.List;
+
+abstract class CodeStyleSchemesActions extends DefaultSchemeActions<CodeStyleScheme> {
+  private final CodeStyleSchemesModel mySchemesModel;
+
+  private final static String SHARED_IMPORT_SOURCE = ApplicationBundle.message("import.scheme.shared");
+
+  CodeStyleSchemesActions(@NotNull CodeStyleSchemesModel model) {
+    mySchemesModel = model;
+  }
+
+  @Override
+  protected void addAdditionalActions(@NotNull List<AnAction> defaultActions) {
+    defaultActions.add(0, new CopyToProjectAction());
+    defaultActions.add(1, new Separator());
+  }
+
+  private class CopyToProjectAction extends AnAction {
+
+    public CopyToProjectAction() {
+      super("Copy To Project");
+    }
+
+    @Override
+    public void actionPerformed(AnActionEvent e) {
+      CodeStyleScheme currentScheme = getCurrentScheme();
+      if (currentScheme != null && !mySchemesModel.isProjectScheme(currentScheme)) {
+        copyToProject(currentScheme);
+      }
+    }
+
+    @Override
+    public void update(AnActionEvent e) {
+      Presentation p = e.getPresentation();
+      CodeStyleScheme currentScheme = getCurrentScheme();
+      p.setEnabled(currentScheme != null && !mySchemesModel.isProjectScheme(currentScheme));
+    }
+  }
+
+  @Override
+  protected void doReset() {
+    CodeStyleScheme selectedScheme = getCurrentScheme();
+    if (selectedScheme != null) {
+      if (Messages
+            .showOkCancelDialog(ApplicationBundle.message("settings.code.style.reset.to.defaults.message"),
+                                ApplicationBundle.message("settings.code.style.reset.to.defaults.title"), Messages.getQuestionIcon()) ==
+          Messages.OK) {
+        selectedScheme.resetToDefaults();
+        mySchemesModel.fireSchemeChanged(selectedScheme);
+      }
+    }
+  }
+
+  @Override
+  protected void doSaveAs() {
+    CodeStyleScheme scheme = getCurrentScheme();
+    if (mySchemesModel.isProjectScheme(scheme)) {
+      exportProjectScheme();
+    }
+    else {
+      CodeStyleScheme currentScheme = getCurrentScheme();
+      if (currentScheme != null) {
+        String selectedName = currentScheme.getName();
+        Collection<String> names = CodeStyleSchemesImpl.getSchemeManager().getAllSchemeNames();
+        SaveSchemeDialog saveDialog =
+          new SaveSchemeDialog(getParentComponent(), ApplicationBundle.message("title.save.code.style.scheme.as"), names, selectedName);
+        if (saveDialog.showAndGet()) {
+          CodeStyleScheme newScheme = mySchemesModel.createNewScheme(saveDialog.getSchemeName(), getCurrentScheme());
+          mySchemesModel.addScheme(newScheme, true);
+        }
+      }
+    }
+  }
+
+  @Override
+  protected void doDelete() {
+    mySchemesModel.removeScheme(getCurrentScheme());
+  }
+
+  @Override
+  protected boolean isDeleteAvailable(@NotNull CodeStyleScheme scheme) {
+    return !mySchemesModel.isProjectScheme(scheme) && !scheme.isDefault();
+  }
+
+  @Override
+  protected void doImport(@NotNull String importerName) {
+    CodeStyleScheme currentScheme = getCurrentScheme();
+    if (currentScheme != null) {
+      chooseAndImport(currentScheme, importerName);
+    }
+  }
+
+  private void exportProjectScheme() {
+    String name = Messages.showInputDialog("Enter new scheme name:", "Copy Project Scheme to Global List", Messages.getQuestionIcon());
+    if (name != null && !CodeStyleSchemesModel.PROJECT_SCHEME_NAME.equals(name)) {
+      CodeStyleScheme newScheme = mySchemesModel.exportProjectScheme(name);
+      int switchToGlobal = Messages
+        .showYesNoDialog("Project scheme was copied to global scheme list as '" + newScheme.getName() + "'.\n" +
+                         "Switch to this created scheme?",
+                         "Copy Project Scheme to Global List", Messages.getQuestionIcon());
+      if (switchToGlobal == Messages.YES) {
+        mySchemesModel.setUsePerProjectSettings(false);
+        mySchemesModel.selectScheme(newScheme, null);
+      }
+    }
+  }
+
+  @NotNull
+  protected abstract JComponent getParentComponent();
+
+  private void chooseAndImport(@NotNull CodeStyleScheme currentScheme, @NotNull String importerName) {
+    if (importerName.equals(SHARED_IMPORT_SOURCE)) {
+      new SchemesToImportPopup<CodeStyleScheme>(getParentComponent()) {
+        @Override
+        protected void onSchemeSelected(CodeStyleScheme scheme) {
+          if (scheme != null) {
+            mySchemesModel.addScheme(scheme, true);
+          }
+        }
+      }.show(mySchemesModel.getSchemes());
+    }
+    else {
+      final SchemeImporter<CodeStyleScheme> importer = SchemeImporterEP.getImporter(importerName, CodeStyleScheme.class);
+      if (importer == null) return;
+      try {
+        final CodeStyleScheme scheme = importExternalCodeStyle(importer, currentScheme);
+        if (scheme != null) {
+          final String additionalImportInfo = StringUtil.notNullize(importer.getAdditionalImportInfo(scheme));
+          SchemeImportUtil
+            .showStatus(getParentComponent(),
+                        ApplicationBundle.message("message.code.style.scheme.import.success", importerName, scheme.getName(),
+                                                  additionalImportInfo),
+                        MessageType.INFO);
+        }
+      }
+      catch (SchemeImportException e) {
+        if (e.isWarning()) {
+          SchemeImportUtil.showStatus(getParentComponent(), e.getMessage(), MessageType.WARNING);
+          return;
+        }
+        final String message = ApplicationBundle.message("message.code.style.scheme.import.failure", importerName, e.getMessage());
+        SchemeImportUtil.showStatus(getParentComponent(), message, MessageType.ERROR);
+      }
+    }
+  }
+
+  @Nullable
+  private CodeStyleScheme importExternalCodeStyle(final SchemeImporter<CodeStyleScheme> importer, @NotNull CodeStyleScheme currentScheme)
+    throws SchemeImportException {
+    final VirtualFile selectedFile = SchemeImportUtil
+      .selectImportSource(importer.getSourceExtensions(), getParentComponent(), CodeStyleSchemesUIConfiguration.Util.getRecentImportFile());
+    if (selectedFile != null) {
+      CodeStyleSchemesUIConfiguration.Util.setRecentImportFile(selectedFile);
+      final SchemeCreator schemeCreator = new SchemeCreator();
+      final CodeStyleScheme
+        schemeImported = importer.importScheme(mySchemesModel.getProject(), selectedFile, currentScheme, schemeCreator);
+      if (schemeImported != null) {
+        if (schemeCreator.isSchemeWasCreated()) {
+          mySchemesModel.fireSchemeListChanged();
+        }
+        else {
+          mySchemesModel.fireSchemeChanged(schemeImported);
+        }
+        return schemeImported;
+      }
+    }
+    return null;
+  }
+
+  private class SchemeCreator implements SchemeFactory<CodeStyleScheme> {
+    private boolean mySchemeWasCreated;
+
+    @Override
+    public CodeStyleScheme createNewScheme(@Nullable String targetName) {
+      mySchemeWasCreated = true;
+      if (targetName == null) targetName = ApplicationBundle.message("code.style.scheme.import.unnamed");
+      CodeStyleScheme newScheme = mySchemesModel.createNewScheme(targetName, getCurrentScheme());
+      mySchemesModel.addScheme(newScheme, true);
+      return newScheme;
+    }
+
+    public boolean isSchemeWasCreated() {
+      return mySchemeWasCreated;
+    }
+  }
+
+  @Override
+  protected Class<CodeStyleScheme> getSchemeType() {
+    return CodeStyleScheme.class;
+  }
+
+  public void copyToProject(CodeStyleScheme scheme) {
+    mySchemesModel.copyToProject(scheme);
+    int switchToProject = Messages
+      .showYesNoDialog("Scheme '" + scheme.getName() + "' was copied to be used as the project scheme.\n" +
+                       "Switch to this created scheme?",
+                       "Copy Scheme to Project", Messages.getQuestionIcon());
+    if (switchToProject == Messages.YES) {
+      mySchemesModel.setUsePerProjectSettings(true, true);
+    }
+  }
+
+  @SuppressWarnings("Duplicates")
+  @Override
+  protected void doExport(@NotNull CodeStyleScheme scheme, @NotNull String exporterName) {
+    SchemeExporter<CodeStyleScheme> exporter = SchemeExporterEP.getExporter(exporterName, CodeStyleScheme.class);
+    if (exporter != null) {
+      String ext = exporter.getExtension();
+      FileSaverDialog saver =
+        FileChooserFactory.getInstance()
+          .createSaveFileDialog(new FileSaverDescriptor(
+            ApplicationBundle.message("scheme.exporter.ui.file.chooser.title"),
+            ApplicationBundle.message("scheme.exporter.ui.file.chooser.message"),
+            ext), getParentComponent());
+      VirtualFileWrapper target = saver.save(null, scheme.getName() + "." + ext);
+      if (target != null) {
+        VirtualFile targetFile = target.getVirtualFile(true);
+        String message;
+        MessageType messageType;
+        if (targetFile != null) {
+          try {
+            WriteAction.run(() -> {
+              OutputStream outputStream = targetFile.getOutputStream(this);
+              try {
+                exporter.exportScheme(scheme, outputStream);
+              }
+              finally {
+                outputStream.close();
+              }
+            });
+            message = ApplicationBundle
+              .message("scheme.exporter.ui.code.style.exported.message", scheme.getName(), targetFile.getPresentableUrl());
+            messageType = MessageType.INFO;
+          }
+          catch (Exception e) {
+            message = ApplicationBundle.message("scheme.exporter.ui.export.failed", e.getMessage());
+            messageType = MessageType.ERROR;
+          }
+        }
+        else {
+          message = ApplicationBundle.message("scheme.exporter.ui.cannot.write.message");
+          messageType = MessageType.ERROR;
+        }
+        SchemeImportUtil.showStatus(getParentComponent(), message, messageType);
+      }
+    }
+  }
+}
\ No newline at end of file
index 20d7e48925a7fbcf874cbf2cef4556ab8da873f5..1f593c7455231225250ed3030b86bab5cae86c63 100644 (file)
@@ -1,6 +1,6 @@
 <?xml version="1.0" encoding="UTF-8"?>
 <form xmlns="http://www.intellij.com/uidesigner/form/" version="1" bind-to-class="com.intellij.application.options.codeStyle.CodeStyleSchemesPanel">
-  <grid id="27dc6" binding="myPanel" layout-manager="GridLayoutManager" row-count="2" column-count="6" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1">
+  <grid id="27dc6" binding="myPanel" layout-manager="GridLayoutManager" row-count="2" column-count="3" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1">
     <margin top="0" left="0" bottom="5" right="0"/>
     <constraints>
       <xy x="20" y="20" width="566" height="113"/>
     <children>
       <vspacer id="d9e80">
         <constraints>
-          <grid row="1" column="0" row-span="1" col-span="6" vsize-policy="6" hsize-policy="1" anchor="0" fill="2" indent="0" use-parent-layout="false"/>
+          <grid row="1" column="0" row-span="1" col-span="3" vsize-policy="6" hsize-policy="1" anchor="0" fill="2" indent="0" use-parent-layout="false"/>
         </constraints>
       </vspacer>
       <hspacer id="fd090">
         <constraints>
-          <grid row="0" column="5" row-span="1" col-span="1" vsize-policy="1" hsize-policy="6" anchor="0" fill="1" indent="0" use-parent-layout="false"/>
+          <grid row="0" column="2" row-span="1" col-span="1" vsize-policy="1" hsize-policy="6" anchor="0" fill="1" indent="0" use-parent-layout="false"/>
         </constraints>
       </hspacer>
       <component id="a1636" class="javax.swing.JLabel">
           <text resource-bundle="messages/ApplicationBundle" key="editbox.scheme.name"/>
         </properties>
       </component>
-      <component id="c234b" class="javax.swing.JComboBox" binding="myCombo">
+      <grid id="b828" layout-manager="GridLayoutManager" row-count="1" column-count="2" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1">
+        <margin top="0" left="0" bottom="0" right="0"/>
         <constraints>
-          <grid row="0" column="1" row-span="1" col-span="1" vsize-policy="0" hsize-policy="2" anchor="8" fill="1" indent="0" use-parent-layout="false">
-            <preferred-size width="100" height="-1"/>
-          </grid>
+          <grid row="0" column="1" row-span="1" col-span="1" vsize-policy="3" hsize-policy="3" anchor="0" fill="3" indent="0" use-parent-layout="false"/>
         </constraints>
         <properties/>
-      </component>
-      <component id="dc89" class="javax.swing.JButton" binding="myManageButton">
-        <constraints>
-          <grid row="0" column="3" row-span="1" col-span="1" vsize-policy="0" hsize-policy="3" anchor="0" fill="1" indent="0" use-parent-layout="false"/>
-        </constraints>
-        <properties>
-          <text value="&amp;More..."/>
-        </properties>
-      </component>
-      <component id="3cef4" class="javax.swing.JButton" binding="myResetButton">
-        <constraints>
-          <grid row="0" column="2" row-span="1" col-span="1" vsize-policy="0" hsize-policy="3" anchor="0" fill="1" indent="0" use-parent-layout="false"/>
-        </constraints>
-        <properties>
-          <text value="Reset"/>
-        </properties>
-      </component>
+        <border type="none"/>
+        <children>
+          <component id="c234b" class="javax.swing.JComboBox" binding="myCombo">
+            <constraints>
+              <grid row="0" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="2" anchor="8" fill="3" indent="0" use-parent-layout="false">
+                <preferred-size width="100" height="-1"/>
+              </grid>
+            </constraints>
+            <properties/>
+          </component>
+          <component id="98c4e" class="javax.swing.JButton" binding="myManageButton" custom-create="true">
+            <constraints>
+              <grid row="0" column="1" row-span="1" col-span="1" vsize-policy="6" hsize-policy="3" anchor="0" fill="3" indent="0" use-parent-layout="false"/>
+            </constraints>
+            <properties>
+              <text value="Manage"/>
+            </properties>
+          </component>
+        </children>
+      </grid>
     </children>
   </grid>
   <buttonGroups>
index 78a8f4e4271edb5a257e3d161b351af42cb783e1..b6a1add548d4a827998e0b4b8fc07f26c459194c 100644 (file)
 
 package com.intellij.application.options.codeStyle;
 
-import com.intellij.openapi.application.ApplicationBundle;
 import com.intellij.openapi.application.ApplicationManager;
-import com.intellij.openapi.ui.Messages;
 import com.intellij.psi.codeStyle.CodeStyleScheme;
 import com.intellij.ui.ListCellRendererWrapper;
+import com.intellij.ui.ManageSchemesComboAction;
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
 
@@ -37,8 +36,7 @@ public class CodeStyleSchemesPanel {
 
   private final CodeStyleSchemesModel myModel;
   private JPanel myPanel;
-  private JButton myManageButton;
-  private JButton myResetButton;
+  @SuppressWarnings("unused") private JButton myManageButton;
 
   private boolean myIsReset = false;
   private final Font myDefaultComboFont;
@@ -71,19 +69,6 @@ public class CodeStyleSchemesPanel {
       }
     });
     
-    myManageButton.addActionListener(new ActionListener() {
-      @Override
-      public void actionPerformed(@NotNull ActionEvent e) {
-        showManageSchemesDialog();
-      }
-    });
-
-    myResetButton.addActionListener(new ActionListener() {
-      @Override
-      public void actionPerformed(ActionEvent e) {
-        resetCurrentSchemeToDefaults();
-      }
-    });
   }
 
   private void onCombo() {
@@ -129,11 +114,8 @@ public class CodeStyleSchemesPanel {
     finally {
       myIsReset = false;
     }
-
-
   }
 
-
   public void onSelectedSchemeChanged() {
     myIsReset = true;
     try {
@@ -153,11 +135,6 @@ public class CodeStyleSchemesPanel {
     return myPanel;
   }
 
-  private void showManageSchemesDialog() {
-    ManageCodeStyleSchemesDialog manageSchemesDialog = new ManageCodeStyleSchemesDialog(myPanel, myModel);
-    manageSchemesDialog.show();
-  }
-
   public void usePerProjectSettingsOptionChanged() {
     if (myModel.isProjectScheme(myModel.getSelectedScheme())) {
       myCombo.setSelectedItem(myModel.getProjectScheme());
@@ -167,15 +144,21 @@ public class CodeStyleSchemesPanel {
     }
   }
 
-  private void resetCurrentSchemeToDefaults() {
-    CodeStyleScheme selectedScheme = getSelectedScheme();
-    if (selectedScheme != null) {
-      if (Messages
-            .showOkCancelDialog(ApplicationBundle.message("settings.code.style.reset.to.defaults.message"),
-                                ApplicationBundle.message("settings.code.style.reset.to.defaults.title"), Messages.getQuestionIcon()) == Messages.OK) {
-        selectedScheme.resetToDefaults();
-        myModel.fireSchemeChanged(selectedScheme);
+  private void createUIComponents() {
+    ManageSchemesComboAction manageSchemesComboAction = new ManageSchemesComboAction(new CodeStyleSchemesActions(myModel) {
+      @NotNull
+      @Override
+      protected JComponent getParentComponent() {
+        return myPanel;
       }
-    }
+
+      @Nullable
+      @Override
+      protected CodeStyleScheme getCurrentScheme() {
+        return getSelectedScheme();
+      }
+    });
+    myManageButton = manageSchemesComboAction.createCombo();
   }
+
 }
diff --git a/platform/lang-impl/src/com/intellij/application/options/codeStyle/ManageCodeStyleSchemesDialog.form b/platform/lang-impl/src/com/intellij/application/options/codeStyle/ManageCodeStyleSchemesDialog.form
deleted file mode 100644 (file)
index 8c11896..0000000
+++ /dev/null
@@ -1,93 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<form xmlns="http://www.intellij.com/uidesigner/form/" version="1" bind-to-class="com.intellij.application.options.codeStyle.ManageCodeStyleSchemesDialog">
-  <grid id="27dc6" binding="myContentPane" layout-manager="GridLayoutManager" row-count="1" column-count="2" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1">
-    <margin top="0" left="0" bottom="0" right="0"/>
-    <constraints>
-      <xy x="20" y="20" width="500" height="400"/>
-    </constraints>
-    <properties/>
-    <border type="none"/>
-    <children>
-      <scrollpane id="fb787" class="com.intellij.ui.components.JBScrollPane">
-        <constraints>
-          <grid row="0" column="0" row-span="1" col-span="1" vsize-policy="3" hsize-policy="3" anchor="0" fill="3" indent="0" use-parent-layout="false">
-            <preferred-size width="200" height="200"/>
-          </grid>
-        </constraints>
-        <properties/>
-        <border type="none"/>
-        <children>
-          <component id="578bf" class="com.intellij.ui.table.JBTable" binding="mySchemesTable" custom-create="true">
-            <constraints/>
-            <properties>
-              <striped value="true"/>
-            </properties>
-          </component>
-        </children>
-      </scrollpane>
-      <grid id="8885" layout-manager="GridLayoutManager" row-count="7" column-count="1" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1">
-        <margin top="0" left="0" bottom="0" right="0"/>
-        <constraints>
-          <grid row="0" column="1" row-span="1" col-span="1" vsize-policy="3" hsize-policy="3" anchor="0" fill="3" indent="0" use-parent-layout="false"/>
-        </constraints>
-        <properties/>
-        <border type="none"/>
-        <children>
-          <component id="27e35" class="javax.swing.JButton" binding="myDeleteButton">
-            <constraints>
-              <grid row="1" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="3" anchor="0" fill="1" indent="0" use-parent-layout="false"/>
-            </constraints>
-            <properties>
-              <text value="&amp;Delete"/>
-            </properties>
-          </component>
-          <vspacer id="e34fc">
-            <constraints>
-              <grid row="6" column="0" row-span="1" col-span="1" vsize-policy="6" hsize-policy="1" anchor="0" fill="2" indent="0" use-parent-layout="false"/>
-            </constraints>
-          </vspacer>
-          <component id="2095b" class="javax.swing.JButton" binding="mySaveAsButton">
-            <constraints>
-              <grid row="0" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="3" anchor="0" fill="1" indent="0" use-parent-layout="false"/>
-            </constraints>
-            <properties>
-              <text value="&amp;Save As..."/>
-            </properties>
-          </component>
-          <component id="dbfe3" class="javax.swing.JButton" binding="myCopyToProjectButton" default-binding="true">
-            <constraints>
-              <grid row="2" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="3" anchor="0" fill="1" indent="0" use-parent-layout="false"/>
-            </constraints>
-            <properties>
-              <text value="Copy to &amp;Project"/>
-            </properties>
-          </component>
-          <component id="9a9cc" class="javax.swing.JButton" binding="myCloseButton">
-            <constraints>
-              <grid row="5" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="3" anchor="0" fill="1" indent="0" use-parent-layout="false"/>
-            </constraints>
-            <properties>
-              <text value="&amp;Close"/>
-            </properties>
-          </component>
-          <component id="2e22f" class="javax.swing.JButton" binding="myExportButton" default-binding="true">
-            <constraints>
-              <grid row="3" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="3" anchor="0" fill="1" indent="0" use-parent-layout="false"/>
-            </constraints>
-            <properties>
-              <text value="E&amp;xport..."/>
-            </properties>
-          </component>
-          <component id="816ef" class="javax.swing.JButton" binding="myImportButton" default-binding="true">
-            <constraints>
-              <grid row="4" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="3" anchor="0" fill="1" indent="0" use-parent-layout="false"/>
-            </constraints>
-            <properties>
-              <text value="Import..."/>
-            </properties>
-          </component>
-        </children>
-      </grid>
-    </children>
-  </grid>
-</form>
diff --git a/platform/lang-impl/src/com/intellij/application/options/codeStyle/ManageCodeStyleSchemesDialog.java b/platform/lang-impl/src/com/intellij/application/options/codeStyle/ManageCodeStyleSchemesDialog.java
deleted file mode 100644 (file)
index 471d708..0000000
+++ /dev/null
@@ -1,406 +0,0 @@
-/*
- * Copyright 2000-2016 JetBrains s.r.o.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.intellij.application.options.codeStyle;
-
-import com.intellij.application.options.ImportSourceChooserDialog;
-import com.intellij.application.options.SaveSchemeDialog;
-import com.intellij.application.options.SchemesToImportPopup;
-import com.intellij.openapi.application.ApplicationBundle;
-import com.intellij.openapi.options.*;
-import com.intellij.openapi.ui.DialogWrapper;
-import com.intellij.openapi.ui.MessageType;
-import com.intellij.openapi.ui.Messages;
-import com.intellij.openapi.util.text.StringUtil;
-import com.intellij.openapi.vfs.VirtualFile;
-import com.intellij.psi.codeStyle.CodeStyleScheme;
-import com.intellij.psi.impl.source.codeStyle.CodeStyleSchemesImpl;
-import com.intellij.ui.table.JBTable;
-import org.jetbrains.annotations.NotNull;
-import org.jetbrains.annotations.Nullable;
-
-import javax.swing.*;
-import javax.swing.table.AbstractTableModel;
-import javax.swing.table.DefaultTableCellRenderer;
-import javax.swing.table.TableCellRenderer;
-import java.awt.*;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.List;
-
-/**
- * @author: rvishnyakov
- */
-public class ManageCodeStyleSchemesDialog extends DialogWrapper {
-  private JPanel myContentPane;
-  private JBTable mySchemesTable;
-  private JButton myDeleteButton;
-  private JButton mySaveAsButton;
-  private JButton myCopyToProjectButton;
-  private JButton myCloseButton;
-  private JButton myExportButton;
-  private JButton myImportButton;
-  private final MySchemesTableModel mySchemesTableModel;
-  private final CodeStyleSchemesModel myModel;
-  private final Component myParent;
-
-  protected ManageCodeStyleSchemesDialog(final Component parent, CodeStyleSchemesModel schemesModel) {
-    super(parent, true);
-    myParent = parent;
-    myModel = schemesModel;
-    setTitle("Code Style Schemes");
-    mySchemesTableModel = new MySchemesTableModel(schemesModel);
-    mySchemesTable.setModel(mySchemesTableModel);
-    mySchemesTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
-    mySchemesTable.getSelectionModel().addListSelectionListener(e -> updateActions());
-    setDefaultSelection();
-
-
-    myDeleteButton.addActionListener(e -> deleteSelected());
-    mySaveAsButton.addActionListener(e -> onSaveAs());
-    myCopyToProjectButton.addActionListener(e -> onCopyToProject());
-    myCloseButton.addActionListener(e -> doCancelAction());
-
-    myExportButton.setVisible(false);
-
-    if (SchemeImporterEP.getExtensions(CodeStyleScheme.class).isEmpty()) {
-      myImportButton.setVisible(false);
-    }
-    else {
-      myImportButton.setVisible(true);
-      myImportButton.addActionListener(e -> chooseAndImport());
-    }
-
-    if (SchemeExporterEP.getExtensions(CodeStyleScheme.class).isEmpty()) {
-      myExportButton.setVisible(false);
-    }
-    else {
-      myExportButton.setVisible(true);
-      myExportButton.addActionListener(e -> exportSelectedScheme());
-    }
-
-    init();
-  }
-
-  private void chooseAndImport() {
-    ImportSourceChooserDialog<CodeStyleScheme> importSourceChooserDialog =
-      new ImportSourceChooserDialog<>(myContentPane, CodeStyleScheme.class);
-    if (importSourceChooserDialog.showAndGet()) {
-      if (importSourceChooserDialog.isImportFromSharedSelected()) {
-        new SchemesToImportPopup<CodeStyleScheme>(myContentPane) {
-          @Override
-          protected void onSchemeSelected(CodeStyleScheme scheme) {
-            if (scheme != null) {
-              myModel.addScheme(scheme, true);
-            }
-          }
-        }.show(myModel.getSchemes());
-      }
-      else {
-        final String selectedImporterName = importSourceChooserDialog.getSelectedSourceName();
-        if (selectedImporterName != null) {
-          final SchemeImporter<CodeStyleScheme> importer = SchemeImporterEP.getImporter(selectedImporterName, CodeStyleScheme.class);
-          if (importer == null) return;
-          try {
-            final CodeStyleScheme scheme = importExternalCodeStyle(importer);
-            if (scheme != null) {
-              final String additionalImportInfo = StringUtil.notNullize(importer.getAdditionalImportInfo(scheme));
-              SchemeImportUtil
-                .showStatus(myImportButton,
-                         ApplicationBundle.message("message.code.style.scheme.import.success", selectedImporterName, scheme.getName(), additionalImportInfo),
-                         MessageType.INFO);
-            }
-          }
-          catch (SchemeImportException e) {
-            if (e.isWarning()) {
-              SchemeImportUtil.showStatus(myImportButton, e.getMessage(), MessageType.WARNING);
-              return;
-            }
-            final String message = ApplicationBundle.message("message.code.style.scheme.import.failure", selectedImporterName, e.getMessage());
-            SchemeImportUtil.showStatus(myImportButton, message, MessageType.ERROR);
-          }
-        }
-      }
-    }
-  }
-
-  @Nullable
-  private CodeStyleScheme importExternalCodeStyle(final SchemeImporter<CodeStyleScheme> importer) throws SchemeImportException {
-    final VirtualFile selectedFile = SchemeImportUtil
-      .selectImportSource(importer.getSourceExtensions(), myContentPane, CodeStyleSchemesUIConfiguration.Util.getRecentImportFile());
-    if (selectedFile != null) {
-      CodeStyleSchemesUIConfiguration.Util.setRecentImportFile(selectedFile);
-      final SchemeCreator schemeCreator = new SchemeCreator();
-      final CodeStyleScheme
-        schemeImported = importer.importScheme(myModel.getProject(), selectedFile, getSelectedScheme(), schemeCreator);
-      if (schemeImported != null) {
-        if (schemeCreator.isSchemeWasCreated()) myModel.fireSchemeListChanged();
-        else myModel.fireSchemeChanged(schemeImported);
-        return schemeImported;
-      }
-    }
-    return null;
-  }
-
-  private void updateActions() {
-    // there is a possibility that nothing will be selected in a table. So we just need to corresponding disable actions
-    final CodeStyleScheme selectedScheme = getSelectedInTableScheme();
-    myDeleteButton.setEnabled(selectedScheme != null && (!(selectedScheme.isDefault() || mySchemesTableModel.isProjectScheme(selectedScheme))));
-    myCopyToProjectButton.setEnabled(selectedScheme != null && !mySchemesTableModel.isProjectScheme(selectedScheme));
-  }
-
-  @Nullable
-  private CodeStyleScheme getSelectedInTableScheme() {
-    int row = mySchemesTable.getSelectedRow();
-    if (row < 0) return null;
-    return mySchemesTableModel.getSchemeAt(row);
-  }
-
-  @NotNull
-  private CodeStyleScheme getSelectedScheme() {
-    int row = mySchemesTable.getSelectedRow();
-    if (row < 0) row = mySchemesTableModel.getDefaultRow();
-    return mySchemesTableModel.getSchemeAt(row);
-  }
-
-  @NotNull
-  @Override
-  protected Action[] createActions() {
-    return new Action[]{};
-  }
-
-  private void deleteSelected() {
-    int row = mySchemesTable.getSelectedRow();
-    if (row >= 0) {
-      int rowToSelect = row + 1;
-      if (rowToSelect >= mySchemesTableModel.getRowCount()) {
-        rowToSelect = mySchemesTableModel.getDefaultRow();
-      }
-      mySchemesTable.getSelectionModel().setSelectionInterval(rowToSelect, rowToSelect);
-      mySchemesTableModel.deleteAt(row);
-    }
-  }
-
-  @Override
-  protected JComponent createCenterPanel() {
-    return myContentPane;
-  }
-
-  private void createUIComponents() {
-    mySchemesTable = new MySchemesTable();
-  }
-
-  private class SchemeCreator implements SchemeFactory<CodeStyleScheme> {
-    private boolean mySchemeWasCreated;
-
-    @Override
-    public CodeStyleScheme createNewScheme(@Nullable String targetName) {
-      mySchemeWasCreated = true;
-      if (targetName == null) targetName = ApplicationBundle.message("code.style.scheme.import.unnamed");
-      final int row = mySchemesTableModel.createNewScheme(getSelectedScheme(), targetName);
-
-      mySchemesTable.getSelectionModel().setSelectionInterval(row, row);
-      return mySchemesTableModel.getSchemeAt(row);
-    }
-
-    public boolean isSchemeWasCreated() {
-      return mySchemeWasCreated;
-    }
-  }
-
-  private class MySchemesTable extends JBTable {
-    private final TableCellRenderer myFixedItemsRenderer;
-
-    private MySchemesTable() {
-      myFixedItemsRenderer = new DefaultTableCellRenderer() {
-        @NotNull
-        @Override
-        public Component getTableCellRendererComponent(@NotNull JTable table,
-                                                       Object value,
-                                                       boolean isSelected,
-                                                       boolean hasFocus,
-                                                       int row,
-                                                       int column) {
-          Component defaultComponent = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
-          if (value instanceof CodeStyleScheme) {
-            CodeStyleScheme scheme = (CodeStyleScheme)value;
-            if (scheme.isDefault() || myModel.isProjectScheme(scheme)) {
-              defaultComponent.setFont(defaultComponent.getFont().deriveFont(Font.BOLD));
-            }
-          }
-          return defaultComponent;
-        }
-      };
-    }
-
-    @Override
-    public TableCellRenderer getCellRenderer(int row, int column) {
-      return myFixedItemsRenderer;
-    }
-  }
-
-  private static class MySchemesTableModel extends AbstractTableModel {
-    private final CodeStyleSchemesModel mySchemesModel;
-    private final List<CodeStyleScheme> mySchemes;
-
-    public MySchemesTableModel(CodeStyleSchemesModel schemesModel) {
-      mySchemesModel = schemesModel;
-      mySchemes = new ArrayList<>();
-      updateSchemes();
-    }
-
-    @NotNull
-    @Override
-    public String getColumnName(int column) {
-      assert column == 0;
-      return "Name";
-    }
-
-    @Override
-    public int getRowCount() {
-      return mySchemes.size();
-    }
-
-    @Override
-    public int getColumnCount() {
-      return 1;
-    }
-
-    @Override
-    public Object getValueAt(int rowIndex, int columnIndex) {
-      assert columnIndex == 0;
-      return mySchemes.get(rowIndex);
-    }
-
-    public CodeStyleScheme getSchemeAt(int row) {
-      return mySchemes.get(row);
-    }
-
-    public void deleteAt(int row) {
-      CodeStyleScheme scheme = mySchemes.get(row);
-      mySchemesModel.removeScheme(scheme);
-      updateSchemes();
-      fireTableRowsDeleted(row, row);
-    }
-
-    public int createNewScheme(CodeStyleScheme selectedScheme, String schemeName) {
-      CodeStyleScheme newScheme = mySchemesModel.createNewScheme(schemeName, selectedScheme);
-      mySchemesModel.addScheme(newScheme, true);
-      updateSchemes();
-      int row = 0;
-      for (CodeStyleScheme scheme : mySchemes) {
-        if (scheme == newScheme) {
-          fireTableRowsInserted(row, row);
-          break;
-        }
-        row ++;
-      }
-      return row;
-    }
-
-    public int getDefaultRow() {
-      int row = 0;
-      for (CodeStyleScheme scheme : mySchemes) {
-        if (scheme.isDefault()) return row;
-        row ++;
-      }
-      return 0;
-    }
-
-    public void copyToProject(CodeStyleScheme scheme) {
-      mySchemesModel.copyToProject(scheme);
-      int switchToProject = Messages
-        .showYesNoDialog("Scheme '" + scheme.getName() + "' was copied to be used as the project scheme.\n" +
-                         "Switch to this created scheme?",
-                         "Copy Scheme to Project", Messages.getQuestionIcon());
-      if (switchToProject == Messages.YES) {
-        mySchemesModel.setUsePerProjectSettings(true, true);
-      }
-    }
-
-    public int exportProjectScheme() {
-      String name = Messages.showInputDialog("Enter new scheme name:", "Copy Project Scheme to Global List", Messages.getQuestionIcon());
-      if (name != null && !CodeStyleSchemesModel.PROJECT_SCHEME_NAME.equals(name)) {
-        CodeStyleScheme newScheme = mySchemesModel.exportProjectScheme(name);
-        updateSchemes();
-        int switchToGlobal = Messages
-          .showYesNoDialog("Project scheme was copied to global scheme list as '" + newScheme.getName() + "'.\n" +
-                           "Switch to this created scheme?",
-                           "Copy Project Scheme to Global List", Messages.getQuestionIcon());
-        if (switchToGlobal == Messages.YES) {
-          mySchemesModel.setUsePerProjectSettings(false);
-          mySchemesModel.selectScheme(newScheme, null);
-        }
-        int row = 0;
-        for (CodeStyleScheme scheme : mySchemes) {
-          if (scheme == newScheme) {
-            fireTableRowsInserted(row, row);
-            return switchToGlobal == 0 ? row : -1;
-          }
-          row++;
-        }
-      }
-      return -1;
-    }
-
-    private void updateSchemes() {
-      mySchemes.clear();
-      mySchemes.addAll(mySchemesModel.getAllSortedSchemes());
-    }
-
-
-    public boolean isProjectScheme(CodeStyleScheme scheme) {
-      return mySchemesModel.isProjectScheme(scheme);
-    }
-  }
-
-  private void onSaveAs() {
-    if (mySchemesTableModel.isProjectScheme(getSelectedScheme())) {
-      int rowToSelect = mySchemesTableModel.exportProjectScheme();
-      if (rowToSelect > 0) {
-        mySchemesTable.getSelectionModel().setSelectionInterval(rowToSelect, rowToSelect);
-      }
-    }
-    else {
-      Collection<String> names = CodeStyleSchemesImpl.getSchemeManager().getAllSchemeNames();
-      String selectedName = getSelectedScheme().getName();
-      SaveSchemeDialog saveDialog =
-        new SaveSchemeDialog(myParent, ApplicationBundle.message("title.save.code.style.scheme.as"), names, selectedName);
-      if (saveDialog.showAndGet()) {
-        int row = mySchemesTableModel.createNewScheme(getSelectedScheme(), saveDialog.getSchemeName());
-        mySchemesTable.getSelectionModel().setSelectionInterval(row, row);
-      }
-    }
-  }
-
-  private void onCopyToProject() {
-    mySchemesTableModel.copyToProject(getSelectedScheme());
-  }
-
-  private void setDefaultSelection() {
-    CodeStyleScheme selectedScheme = myModel.getSelectedScheme();
-    for (int i = 0; i < mySchemesTableModel.getRowCount(); i ++) {
-      if (mySchemesTableModel.getSchemeAt(i).equals(selectedScheme)) {
-        mySchemesTable.getSelectionModel().setSelectionInterval(i, i);
-        return;
-      }
-    }
-  }
-
-  private void exportSelectedScheme() {
-    new CodeStyleSchemeExporterUI(myExportButton, getSelectedScheme(),
-                                  (message, messageType) -> SchemeImportUtil.showStatus(myExportButton, message, messageType)).export();
-  }
-}
index 855c79a1ffdeb1707bd231ef10a4cb29f87152eb..2648af1d52cdc2675ffc45e5254c8cd0dd6942cd 100644 (file)
@@ -15,6 +15,7 @@
  */
 package com.intellij.codeInsight.actions;
 
+import com.intellij.codeInsight.FileModificationService;
 import com.intellij.openapi.actionSystem.AnAction;
 import com.intellij.openapi.actionSystem.AnActionEvent;
 import com.intellij.openapi.actionSystem.CommonDataKeys;
@@ -55,6 +56,8 @@ public abstract class MultiCaretCodeInsightAction extends AnAction {
     if (hostEditor == null) {
       return;
     }
+    PsiFile hostFile = PsiDocumentManager.getInstance(project).getPsiFile(hostEditor.getDocument());
+    if (hostFile != null && !FileModificationService.getInstance().prepareFileForWrite(hostFile)) return;
 
     actionPerformedImpl(project, hostEditor);
   }
index cd0c881016a3444fdc3f44bd0644c10f345fd61f..2a2f7043fd9f7cfe6365346801084ee88a86d5d2 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2015 JetBrains s.r.o.
+ * Copyright 2000-2016 JetBrains s.r.o.
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -24,7 +24,6 @@ import com.intellij.openapi.editor.Editor;
 import com.intellij.openapi.editor.EditorFactory;
 import com.intellij.openapi.editor.event.EditorFactoryEvent;
 import com.intellij.openapi.editor.event.EditorFactoryListener;
-import com.intellij.openapi.fileEditor.FileEditorManagerAdapter;
 import com.intellij.openapi.fileEditor.FileEditorManagerEvent;
 import com.intellij.openapi.fileEditor.FileEditorManagerListener;
 import com.intellij.openapi.project.Project;
@@ -72,7 +71,7 @@ public class EditorTracker extends AbstractProjectComponent {
   @Override
   public void projectOpened() {
     myIdeFrame = ((WindowManagerEx)myWindowManager).getFrame(myProject);
-    myProject.getMessageBus().connect(myProject).subscribe(FileEditorManagerListener.FILE_EDITOR_MANAGER, new FileEditorManagerAdapter() {
+    myProject.getMessageBus().connect(myProject).subscribe(FileEditorManagerListener.FILE_EDITOR_MANAGER, new FileEditorManagerListener() {
       @Override
       public void selectionChanged(@NotNull FileEditorManagerEvent event) {
         if (myIdeFrame == null || myIdeFrame.getFocusOwner() == null) return;
index d1c254873a9da40323468d54f66f4f070765e95e..1cd03990caf507a93bdf91cdbceb0b3c33522be1 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2013 JetBrains s.r.o.
+ * Copyright 2000-2016 JetBrains s.r.o.
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -25,7 +25,6 @@ import com.intellij.openapi.editor.Document;
 import com.intellij.openapi.editor.Editor;
 import com.intellij.openapi.editor.ex.DocumentEx;
 import com.intellij.openapi.fileEditor.FileEditorManager;
-import com.intellij.openapi.fileEditor.FileEditorManagerAdapter;
 import com.intellij.openapi.fileEditor.FileEditorManagerEvent;
 import com.intellij.openapi.fileEditor.FileEditorManagerListener;
 import com.intellij.openapi.project.DumbAwareRunnable;
@@ -50,7 +49,7 @@ public class StatusBarUpdater implements Disposable {
   public StatusBarUpdater(Project project) {
     myProject = project;
 
-    project.getMessageBus().connect(this).subscribe(FileEditorManagerListener.FILE_EDITOR_MANAGER, new FileEditorManagerAdapter() {
+    project.getMessageBus().connect(this).subscribe(FileEditorManagerListener.FILE_EDITOR_MANAGER, new FileEditorManagerListener() {
       @Override
       public void selectionChanged(@NotNull FileEditorManagerEvent event) {
         updateLater();
index 3dc5f6e8b655fc1a4128899b49f918e6d0422d55..beeac4907c7dfa34007dc360bcd01b840269cbd9 100644 (file)
@@ -208,11 +208,6 @@ public class DocumentationManager extends DockablePopupManager<DocumentationComp
           hint.cancel();
         }
       }
-
-
-      @Override
-      public void afterActionPerformed(final AnAction action, final DataContext dataContext, AnActionEvent event) {
-      }
     };
     myActionManager.addAnActionListener(actionListener, project);
     myUpdateDocAlarm = new Alarm(Alarm.ThreadToUse.POOLED_THREAD,myProject);
index 8b277d5d0df5b595a98908dd3fbe79175213ecc7..357cd9a0ae4c5a36ca65242018d15add190bc1d7 100644 (file)
@@ -22,7 +22,7 @@ import com.intellij.codeInsight.actions.BaseCodeInsightAction;
 import com.intellij.codeInsight.editorActions.emacs.EmacsProcessingHandler;
 import com.intellij.codeInsight.editorActions.emacs.LanguageEmacsExtension;
 import com.intellij.lang.LanguageFormatting;
-import com.intellij.openapi.diagnostic.Logger;
+import com.intellij.openapi.application.WriteAction;
 import com.intellij.openapi.editor.Document;
 import com.intellij.openapi.editor.Editor;
 import com.intellij.openapi.editor.ScrollType;
@@ -33,13 +33,10 @@ import com.intellij.psi.PsiDocumentManager;
 import com.intellij.psi.PsiElement;
 import com.intellij.psi.PsiFile;
 import com.intellij.psi.codeStyle.CodeStyleManager;
-import com.intellij.util.IncorrectOperationException;
 import org.jetbrains.annotations.NotNull;
 
 public class EmacsStyleIndentAction extends BaseCodeInsightAction implements DumbAware {
 
-  private static final Logger LOG = Logger.getInstance("#com.intellij.codeInsight.generation.actions.EmacsStyleIndentAction");
-
   @NotNull
   @Override
   protected CodeInsightActionHandler getHandler() {
@@ -64,18 +61,18 @@ public class EmacsStyleIndentAction extends BaseCodeInsightAction implements Dum
         return;
       }
 
-      EmacsProcessingHandler emacsProcessingHandler = LanguageEmacsExtension.INSTANCE.forLanguage(file.getLanguage());
-      if (emacsProcessingHandler != null) {
-        EmacsProcessingHandler.Result result = emacsProcessingHandler.changeIndent(project, editor, file);
-        if (result == EmacsProcessingHandler.Result.STOP) {
-          return;
+      WriteAction.run(() -> {
+        EmacsProcessingHandler emacsProcessingHandler = LanguageEmacsExtension.INSTANCE.forLanguage(file.getLanguage());
+        if (emacsProcessingHandler != null) {
+          EmacsProcessingHandler.Result result = emacsProcessingHandler.changeIndent(project, editor, file);
+          if (result == EmacsProcessingHandler.Result.STOP) {
+            return;
+          }
         }
-      }
 
-      final Document document = editor.getDocument();
-      int startLine = document.getLineNumber(editor.getSelectionModel().getSelectionStart());
-      int endLine = document.getLineNumber(editor.getSelectionModel().getSelectionEnd());
-      try{
+        final Document document = editor.getDocument();
+        int startLine = document.getLineNumber(editor.getSelectionModel().getSelectionStart());
+        int endLine = document.getLineNumber(editor.getSelectionModel().getSelectionEnd());
         for (int line = startLine; line <= endLine; line++) {
           final int lineStart = document.getLineStartOffset(line);
           final CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(project);
@@ -86,15 +83,12 @@ public class EmacsStyleIndentAction extends BaseCodeInsightAction implements Dum
             editor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE);
           }
         }
-      }
-      catch(IncorrectOperationException e){
-        LOG.error(e);
-      }
+      });
     }
 
     @Override
     public boolean startInWriteAction() {
-      return true;
+      return false;
     }
   }
 }
index dce7674debcfa0937efbd6dc1e66343af57e1b30..1a943b9954b480295278aef8e4b9c2c23178960d 100644 (file)
@@ -21,6 +21,7 @@ import com.intellij.ide.DataManager;
 import com.intellij.openapi.actionSystem.CommonDataKeys;
 import com.intellij.openapi.actionSystem.DataContext;
 import com.intellij.openapi.application.ApplicationManager;
+import com.intellij.openapi.application.WriteAction;
 import com.intellij.openapi.editor.*;
 import com.intellij.openapi.editor.actionSystem.EditorActionHandler;
 import com.intellij.openapi.fileEditor.FileDocumentManager;
@@ -30,8 +31,6 @@ import com.intellij.psi.PsiFile;
 import com.intellij.psi.codeStyle.CodeStyleManager;
 import com.intellij.util.text.CharArrayUtil;
 
-import java.util.concurrent.atomic.AtomicBoolean;
-
 public class EndHandler extends EditorActionHandler {
   private final EditorActionHandler myOriginalHandler;
 
@@ -87,46 +86,32 @@ public class EndHandler extends EditorActionHandler {
         if (isEmptyLine) {
 
           // There is a possible case that indent string is not calculated for particular document (that is true at least for plain text
-          // documents). Hence, we check that and don't finish processing in case we have such a situation. AtomicBoolean is used
-          // here just as a boolean value holder due to requirement to declare variable used from inner class as final.
-          final AtomicBoolean stopProcessing = new AtomicBoolean(true);
+          // documents). Hence, we check that and don't finish processing in case we have such a situation.
+          boolean stopProcessing = true;
           PsiDocumentManager.getInstance(project).commitAllDocuments();
-          ApplicationManager.getApplication().runWriteAction(new Runnable() {
-            @Override
-            public void run() {
-              CodeStyleManager styleManager = CodeStyleManager.getInstance(project);
-              final String lineIndent = styleManager.getLineIndent(file, caretOffset);
-              if (lineIndent != null) {
-                int col = calcColumnNumber(lineIndent, editor.getSettings().getTabSize(project));
-                int line = caretModel.getVisualPosition().line;
-                caretModel.moveToVisualPosition(new VisualPosition(line, col));
-
-                if (caretModel.getLogicalPosition().column != col){
-                  if (!FileDocumentManager.getInstance().requestWriting(editor.getDocument(), project)) {
-                    return;
-                  }
-                  editor.getSelectionModel().removeSelection();
-                  document.replaceString(offset1 + 1, offset2, lineIndent);
-                }
-              }
-              else {
-                stopProcessing.set(false);
+          CodeStyleManager styleManager = CodeStyleManager.getInstance(project);
+          final String lineIndent = styleManager.getLineIndent(file, caretOffset);
+          if (lineIndent != null) {
+            int col = calcColumnNumber(lineIndent, editor.getSettings().getTabSize(project));
+            int line = caretModel.getVisualPosition().line;
+            caretModel.moveToVisualPosition(new VisualPosition(line, col));
+
+            if (caretModel.getLogicalPosition().column != col){
+              if (!ApplicationManager.getApplication().isWriteAccessAllowed() &&
+                  !FileDocumentManager.getInstance().requestWriting(editor.getDocument(), project)) {
+                return;
               }
-
-              editor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE);
               editor.getSelectionModel().removeSelection();
+              WriteAction.run(() -> document.replaceString(offset1 + 1, offset2, lineIndent));
             }
+          }
+          else {
+            stopProcessing = false;
+          }
 
-            private int calcColumnNumber(final String lineIndent, final int tabSize) {
-              int result = 0;
-              for (char c : lineIndent.toCharArray()) {
-                if (c == ' ') result++;
-                if (c == '\t') result += tabSize;
-              }
-              return result;
-            }
-          });
-          if (stopProcessing.get()) {
+          editor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE);
+          editor.getSelectionModel().removeSelection();
+          if (stopProcessing) {
             return;
           }
         }
@@ -137,4 +122,14 @@ public class EndHandler extends EditorActionHandler {
       myOriginalHandler.execute(editor, caret, dataContext);
     }
   }
+
+  private static int calcColumnNumber(final String lineIndent, final int tabSize) {
+    int result = 0;
+    for (char c : lineIndent.toCharArray()) {
+      if (c == ' ') result++;
+      if (c == '\t') result += tabSize;
+    }
+    return result;
+  }
+
 }
index ecafc1f01450d07663027a79ab54006eab7d5cd6..da232961e9f270726aec15944ff929644e0cd9f2 100644 (file)
@@ -77,7 +77,7 @@ public class FixDocCommentAction extends EditorAction {
 
   private static void process(@NotNull final PsiFile file, @NotNull final Editor editor, @NotNull final Project project, int offset) {
     PsiElement elementAtOffset = file.findElementAt(offset);
-    if (elementAtOffset == null) {
+    if (elementAtOffset == null || !FileModificationService.getInstance().preparePsiElementForWrite(elementAtOffset)) {
       return;
     }
     generateOrFixComment(elementAtOffset, project, editor);
@@ -152,7 +152,6 @@ public class FixDocCommentAction extends EditorAction {
                                       @NotNull CodeDocumentationAwareCommenter commenter,
                                       @NotNull Project project)
   {
-    if (!FileModificationService.getInstance().preparePsiElementForWrite(anchor)) return;
     Document document = editor.getDocument();
     int commentStartOffset = anchor.getTextRange().getStartOffset();
     int lineStartOffset = document.getLineStartOffset(document.getLineNumber(commentStartOffset));
index 0edde0b040eb92f30ae14eb56c73246e62bce873..27455d00ee6cf2e34f67f1fa8af7ca5f6b1df0ac 100644 (file)
@@ -28,7 +28,6 @@ import com.intellij.lang.LanguageCommenters;
 import com.intellij.lexer.Lexer;
 import com.intellij.openapi.editor.*;
 import com.intellij.openapi.editor.ex.util.EditorUtil;
-import com.intellij.openapi.fileEditor.FileDocumentManager;
 import com.intellij.openapi.fileTypes.FileType;
 import com.intellij.openapi.fileTypes.impl.AbstractFileType;
 import com.intellij.openapi.fileTypes.impl.CustomSyntaxTableFileType;
@@ -71,9 +70,6 @@ public class CommentByBlockCommentHandler extends MultiCaretCodeInsightActionHan
 
     myDocument = editor.getDocument();
 
-    if (!FileDocumentManager.getInstance().requestWriting(myDocument, project)) {
-      return;
-    }
     FeatureUsageTracker.getInstance().triggerFeatureUsed("codeassists.comment.block");
     final Commenter commenter = findCommenter(myFile, myEditor, caret);
     if (commenter == null) return;
index e317bd36dfa6888afdc0d1ff793e4d93ae4f64f3..3df1a5f930b9ab0cd2f6a17e443c048bd9f65800 100644 (file)
@@ -31,7 +31,6 @@ import com.intellij.openapi.actionSystem.IdeActions;
 import com.intellij.openapi.actionSystem.ex.ActionManagerEx;
 import com.intellij.openapi.editor.*;
 import com.intellij.openapi.editor.ex.util.EditorUtil;
-import com.intellij.openapi.fileEditor.FileDocumentManager;
 import com.intellij.openapi.fileTypes.FileType;
 import com.intellij.openapi.fileTypes.impl.AbstractFileType;
 import com.intellij.openapi.fileTypes.impl.CustomSyntaxTableFileType;
@@ -82,10 +81,6 @@ public class CommentByLineCommentHandler extends MultiCaretCodeInsightActionHand
     }
 
     Document document = editor.getDocument();
-    if (!FileDocumentManager.getInstance().requestWriting(document, project)) {
-      return;
-    }
-
     boolean hasSelection = caret.hasSelection();
     int startOffset = caret.getSelectionStart();
     int endOffset = caret.getSelectionEnd();
index 93b99adea60bffb626ab862444ac3f031a8b9a09..746054ae90bf7eab6efaca1622595f4a08f07ab8 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2015 JetBrains s.r.o.
+ * Copyright 2000-2016 JetBrains s.r.o.
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -26,13 +26,12 @@ import com.intellij.openapi.editor.ex.DocumentEx;
 import com.intellij.openapi.editor.ex.EditorEventMulticasterEx;
 import com.intellij.openapi.editor.ex.FocusChangeListener;
 import com.intellij.openapi.fileEditor.FileEditorManager;
-import com.intellij.openapi.fileEditor.FileEditorManagerAdapter;
 import com.intellij.openapi.fileEditor.FileEditorManagerEvent;
+import com.intellij.openapi.fileEditor.FileEditorManagerListener;
 import com.intellij.openapi.project.Project;
 import com.intellij.openapi.startup.StartupActivity;
 import com.intellij.openapi.util.TextRange;
 import com.intellij.util.Alarm;
-import com.intellij.util.Processor;
 import org.jetbrains.annotations.NotNull;
 
 public class BraceHighlighter implements StartupActivity {
@@ -112,7 +111,7 @@ public class BraceHighlighter implements StartupActivity {
 
     final FileEditorManager fileEditorManager = FileEditorManager.getInstance(project);
 
-    fileEditorManager.addFileEditorManagerListener(new FileEditorManagerAdapter() {
+    fileEditorManager.addFileEditorManagerListener(new FileEditorManagerListener() {
       @Override
       public void selectionChanged(@NotNull FileEditorManagerEvent e) {
         myAlarm.cancelAllRequests();
index 51a59ab9a22f892076bf1821b6d778da3f1720e2..9a91c50560d30fe3c24e3d7884903dc144248e97 100644 (file)
@@ -56,8 +56,8 @@ public class FileLevelIntentionComponent extends EditorNotificationPanel {
                                      @NotNull final Project project,
                                      @NotNull final PsiFile psiFile,
                                      @NotNull final Editor editor, @Nullable String tooltip) {
+    super(getColor(project, severity));
     myProject = project;
-    background(getColor(severity));
 
     final ShowIntentionsPass.IntentionsInfo info = new ShowIntentionsPass.IntentionsInfo();
 
@@ -106,12 +106,12 @@ public class FileLevelIntentionComponent extends EditorNotificationPanel {
   }
 
   @NotNull
-  private Color getColor(@NotNull HighlightSeverity severity) {
-    if (SeverityRegistrar.getSeverityRegistrar(myProject).compare(severity, HighlightSeverity.ERROR) >= 0) {
+  private static Color getColor(@NotNull Project project, @NotNull HighlightSeverity severity) {
+    if (SeverityRegistrar.getSeverityRegistrar(project).compare(severity, HighlightSeverity.ERROR) >= 0) {
       return LightColors.RED;
     }
 
-    if (SeverityRegistrar.getSeverityRegistrar(myProject).compare(severity, HighlightSeverity.WARNING) >= 0) {
+    if (SeverityRegistrar.getSeverityRegistrar(project).compare(severity, HighlightSeverity.WARNING) >= 0) {
       return LightColors.YELLOW;
     }
 
index 4c810fddb0ff3441a687ee3a88cd2b073eb37e4a..386d471d61ad5e6c5bdcc8ecc4c4a6a9f18150f8 100644 (file)
@@ -49,7 +49,6 @@ import com.intellij.openapi.editor.markup.HighlighterTargetArea;
 import com.intellij.openapi.editor.markup.RangeHighlighter;
 import com.intellij.openapi.editor.markup.TextAttributes;
 import com.intellij.openapi.fileEditor.FileEditorManager;
-import com.intellij.openapi.fileEditor.FileEditorManagerAdapter;
 import com.intellij.openapi.fileEditor.FileEditorManagerEvent;
 import com.intellij.openapi.fileEditor.FileEditorManagerListener;
 import com.intellij.openapi.keymap.Keymap;
@@ -154,7 +153,7 @@ public class CtrlMouseHandler extends AbstractProjectComponent {
     }
   };
 
-  private final FileEditorManagerListener myFileEditorManagerListener = new FileEditorManagerAdapter() {
+  private final FileEditorManagerListener myFileEditorManagerListener = new FileEditorManagerListener() {
     @Override
     public void selectionChanged(@NotNull FileEditorManagerEvent e) {
       disposeHighlighter();
index 560c7d6387282a947d55d38bade03178ce25bcd3..ccfe1e5b1251b7116bc7ee65aeebec78dc4c1d7f 100644 (file)
@@ -54,7 +54,7 @@ public class UnwrapHandler implements CodeInsightActionHandler {
 
   @Override
   public boolean startInWriteAction() {
-    return true;
+    return false;
   }
 
   @Override
@@ -64,7 +64,7 @@ public class UnwrapHandler implements CodeInsightActionHandler {
     selectOption(options, editor, file);
   }
 
-  private List<AnAction> collectOptions(Project project, Editor editor, PsiFile file) {
+  private static List<AnAction> collectOptions(Project project, Editor editor, PsiFile file) {
     List<AnAction> result = new ArrayList<>();
 
     UnwrapDescriptor d = getUnwrapDescription(file);
@@ -80,7 +80,7 @@ public class UnwrapHandler implements CodeInsightActionHandler {
     return LanguageUnwrappers.INSTANCE.forLanguage(file.getLanguage());
   }
 
-  private AnAction createUnwrapAction(Unwrapper u, PsiElement el, Editor ed, Project p) {
+  private static AnAction createUnwrapAction(Unwrapper u, PsiElement el, Editor ed, Project p) {
     return new MyUnwrapAction(p, ed, u, el);
   }
 
@@ -97,10 +97,10 @@ public class UnwrapHandler implements CodeInsightActionHandler {
     showPopup(options, editor);
   }
 
-  private void showPopup(final List<AnAction> options, Editor editor) {
+  private static void showPopup(final List<AnAction> options, Editor editor) {
     final ScopeHighlighter highlighter = new ScopeHighlighter(editor);
 
-    DefaultListModel m = new DefaultListModel();
+    DefaultListModel<String> m = new DefaultListModel<>();
     for (AnAction a : options) {
       m.addElement(((MyUnwrapAction)a).getName());
     }
@@ -192,7 +192,7 @@ public class UnwrapHandler implements CodeInsightActionHandler {
     private void saveCaretPosition(PsiFile file) {
       int offset = myEditor.getCaretModel().getOffset();
       PsiElement el = file.findElementAt(offset);
-
+      if (el == null) return;
       int innerOffset = offset - el.getTextOffset();
       el.putCopyableUserData(CARET_POS_KEY, innerOffset);
     }
index e56bfd83bda4c1abf09295cef5c647fbccae2d9f..5fdf2919b4c434377d45f907209b2c3dc0a48fad 100644 (file)
@@ -25,6 +25,8 @@ import com.intellij.codeInspection.ex.GlobalInspectionContextImpl;
 import com.intellij.codeInspection.ex.InspectionManagerEx;
 import com.intellij.codeInspection.ex.InspectionProfileImpl;
 import com.intellij.codeInspection.ex.InspectionProfileModifiableModel;
+import com.intellij.ide.util.PropertiesComponent;
+import com.intellij.openapi.diagnostic.Logger;
 import com.intellij.openapi.fileEditor.FileDocumentManager;
 import com.intellij.openapi.options.ex.SingleConfigurableEditor;
 import com.intellij.openapi.project.Project;
@@ -45,6 +47,9 @@ import java.util.ArrayList;
 import java.util.List;
 
 public class CodeInspectionAction extends BaseAnalysisAction {
+  private static final Logger LOG = Logger.getInstance(CodeInspectionAction.class);
+  private static final String LAST_SELECTED_PROFILE_PROP = "run.code.analysis.last.selected.profile";
+
   private GlobalInspectionContextImpl myGlobalInspectionContext;
   protected InspectionProfileImpl myExternalProfile;
 
@@ -127,6 +132,7 @@ public class CodeInspectionAction extends BaseAnalysisAction {
         final boolean canExecute = myExternalProfile != null && myExternalProfile.isExecutable(project);
         dialog.setOKActionEnabled(canExecute);
         if (canExecute) {
+          PropertiesComponent.getInstance(project).setValue(LAST_SELECTED_PROFILE_PROP, (myExternalProfile.isProjectLevel() ? 'p' : 'a') + myExternalProfile.getName());
           manager.setProfile(myExternalProfile.getName());
         }
       }
@@ -178,7 +184,7 @@ public class CodeInspectionAction extends BaseAnalysisAction {
                               InspectionProfileManager inspectionProfileManager,
                               InspectionProjectProfileManager inspectionProjectProfileManager,
                               InspectionManagerEx inspectionManager) {
-    InspectionProfileImpl selectedProfile = getGlobalInspectionContext(inspectionManager.getProject()).getCurrentProfile();
+    InspectionProfileImpl selectedProfile = getProfileToUse(inspectionManager.getProject(), inspectionProfileManager, inspectionProjectProfileManager);
     List<InspectionProfileImpl> profiles = new ArrayList<>();
     profiles.addAll(inspectionProfileManager.getProfiles());
     profiles.addAll(inspectionProjectProfileManager.getProfiles());
@@ -186,6 +192,26 @@ public class CodeInspectionAction extends BaseAnalysisAction {
     profilesCombo.selectProfile(selectedProfile);
   }
 
+  @NotNull
+  private InspectionProfileImpl getProfileToUse(@NotNull Project project,
+                                               @NotNull InspectionProfileManager appProfileManager,
+                                               @NotNull InspectionProjectProfileManager projectProfileManager) {
+    final String lastSelectedProfile = PropertiesComponent.getInstance(project).getValue(LAST_SELECTED_PROFILE_PROP);
+    if (lastSelectedProfile != null) {
+      final char type = lastSelectedProfile.charAt(0);
+      final String lastSelectedProfileName = lastSelectedProfile.substring(1);
+      if (type == 'a') {
+        final InspectionProfileImpl profile = appProfileManager.getProfile(lastSelectedProfileName, false);
+        if (profile != null) return profile;
+      } else {
+        LOG.assertTrue(type == 'p', "Unexpected last selected profile: \'" + lastSelectedProfile + "\'");
+        final InspectionProfileImpl profile = projectProfileManager.getProfile(lastSelectedProfileName, false);
+        if (profile != null && profile.isProjectLevel()) return profile;
+      }
+    }
+    return getGlobalInspectionContext(project).getCurrentProfile();
+  }
+
   private static class AdditionalPanel {
     public ComboboxWithBrowseButton myBrowseProfilesCombo;
     public JPanel myAdditionalPanel;
index c009736610680c4e52b90d93322400c016d2ece0..fa5e2e36045e739e5aed67ee68836e24cbfb13ff 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2014 JetBrains s.r.o.
+ * Copyright 2000-2016 JetBrains s.r.o.
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -217,7 +217,7 @@ public class LogConfigurationPanel<T extends RunConfigurationBase> extends Setti
   }
 
   @Override
-  protected void resetEditorFrom(final RunConfigurationBase configuration) {
+  protected void resetEditorFrom(@NotNull final RunConfigurationBase configuration) {
     ArrayList<LogFileOptions> list = new ArrayList<>();
     final List<LogFileOptions> logFiles = configuration.getLogFiles();
     for (LogFileOptions setting : logFiles) {
@@ -249,7 +249,7 @@ public class LogConfigurationPanel<T extends RunConfigurationBase> extends Setti
   }
 
   @Override
-  protected void applyEditorTo(final RunConfigurationBase configuration) throws ConfigurationException {
+  protected void applyEditorTo(@NotNull final RunConfigurationBase configuration) throws ConfigurationException {
     myFilesTable.stopEditing();
     configuration.removeAllLogFiles();
     configuration.removeAllPredefinedLogFiles();
index 9d9689366312ff53e0365c5c1c864c82a99ca161..8be37648aa44a30df954f317cfd229b454d0c314 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2015 JetBrains s.r.o.
+ * Copyright 2000-2016 JetBrains s.r.o.
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -33,7 +33,6 @@ import com.intellij.openapi.ui.popup.JBPopupFactory;
 import com.intellij.openapi.ui.popup.ListSeparator;
 import com.intellij.openapi.ui.popup.MultiSelectionListPopupStep;
 import com.intellij.openapi.ui.popup.PopupStep;
-import com.intellij.openapi.util.Condition;
 import com.intellij.ui.*;
 import com.intellij.ui.components.JBList;
 import com.intellij.util.containers.ContainerUtil;
@@ -92,14 +91,14 @@ public class CompoundRunConfigurationSettingsEditor extends SettingsEditor<Compo
   }
 
   @Override
-  protected void resetEditorFrom(CompoundRunConfiguration compoundRunConfiguration) {
+  protected void resetEditorFrom(@NotNull CompoundRunConfiguration compoundRunConfiguration) {
     myModel.clear();
     myModel.addAll(compoundRunConfiguration.getSetToRun());
     mySnapshot = compoundRunConfiguration;
   }
 
   @Override
-  protected void applyEditorTo(CompoundRunConfiguration s) throws ConfigurationException {
+  protected void applyEditorTo(@NotNull CompoundRunConfiguration s) throws ConfigurationException {
     Set<RunConfiguration> checked = new HashSet<>();
     for (int i = 0; i < myModel.getSize(); i++) {
       RunConfiguration configuration = myModel.get(i);
index a7c6bdbce32b5b04adb8318e80faf5049faf5884..b236e2b3f742cd8b20c8f5f6c4553a3ff1a01dbd 100644 (file)
@@ -27,8 +27,8 @@ import com.intellij.openapi.actionSystem.DataProvider;
 import com.intellij.openapi.actionSystem.EmptyAction;
 import com.intellij.openapi.actionSystem.IdeActions;
 import com.intellij.openapi.application.ApplicationManager;
-import com.intellij.openapi.application.TransactionGuard;
 import com.intellij.openapi.application.ReadAction;
+import com.intellij.openapi.application.TransactionGuard;
 import com.intellij.openapi.command.undo.UndoUtil;
 import com.intellij.openapi.editor.*;
 import com.intellij.openapi.editor.colors.EditorColorsManager;
@@ -445,7 +445,7 @@ public class LanguageConsoleImpl extends ConsoleViewImpl implements LanguageCons
   }
 
   private void installEditorFactoryListener() {
-    FileEditorManagerAdapter fileEditorListener = new FileEditorManagerAdapter() {
+    FileEditorManagerListener fileEditorListener = new FileEditorManagerListener() {
       @Override
       public void fileOpened(@NotNull FileEditorManager source, @NotNull VirtualFile file) {
         if (myConsoleEditor == null || !Comparing.equal(file, getVirtualFile())) {
index caa891634110079a126f3311a0393927aaadf845..3c74bb97f44a91bca8d66dc73214dccd2508077c 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2015 JetBrains s.r.o.
+ * Copyright 2000-2016 JetBrains s.r.o.
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -23,7 +23,6 @@ import com.intellij.execution.configurations.RunnerSettings;
 import com.intellij.execution.runners.ProgramRunner;
 import com.intellij.execution.ui.AdjustingTabSettingsEditor;
 import com.intellij.openapi.options.*;
-import com.intellij.openapi.util.Condition;
 import com.intellij.openapi.util.Disposer;
 import com.intellij.openapi.util.Pair;
 import com.intellij.ui.ColoredListCellRenderer;
@@ -304,12 +303,12 @@ public class ConfigurationSettingsEditor extends CompositeSettingsEditor<RunnerA
     }
 
     @Override
-    public void resetEditorFrom(RunnerAndConfigurationSettings configurationSettings) {
+    public void resetEditorFrom(@NotNull RunnerAndConfigurationSettings configurationSettings) {
       myConfigEditor.resetFrom(configurationSettings.getConfiguration());
     }
 
     @Override
-    public void applyEditorTo(RunnerAndConfigurationSettings configurationSettings) throws ConfigurationException {
+    public void applyEditorTo(@NotNull RunnerAndConfigurationSettings configurationSettings) throws ConfigurationException {
       myConfigEditor.applyTo(configurationSettings.getConfiguration());
     }
 
index 5d9da6121ca6f40a971987514c8d79d5262dea4b..506639b0b95f946a7d2a33c644a34d37b97c93ef 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2009 JetBrains s.r.o.
+ * Copyright 2000-2016 JetBrains s.r.o.
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -105,13 +105,13 @@ public class ConfigurationSettingsEditorWrapper extends SettingsEditor<RunnerAnd
   }
 
   @Override
-  public void resetEditorFrom(final RunnerAndConfigurationSettings settings) {
+  public void resetEditorFrom(@NotNull final RunnerAndConfigurationSettings settings) {
     myEditor.resetEditorFrom(settings);
     doReset(settings);
   }
 
   @Override
-  public void applyEditorTo(final RunnerAndConfigurationSettings settings) throws ConfigurationException {
+  public void applyEditorTo(@NotNull final RunnerAndConfigurationSettings settings) throws ConfigurationException {
     myEditor.applyEditorTo(settings);
     doApply(settings);
   }
index 8dd36c80d746cf158c5e472255a49171293cbabb..8351ed6f5bff9a9a9c324cc8bc0da4f0f636f4c2 100644 (file)
@@ -23,7 +23,10 @@ import com.intellij.openapi.editor.Document;
 import com.intellij.openapi.editor.EditorFactory;
 import com.intellij.openapi.editor.event.DocumentAdapter;
 import com.intellij.openapi.editor.event.DocumentEvent;
-import com.intellij.openapi.fileEditor.*;
+import com.intellij.openapi.fileEditor.FileDocumentManager;
+import com.intellij.openapi.fileEditor.FileDocumentManagerAdapter;
+import com.intellij.openapi.fileEditor.FileEditorManager;
+import com.intellij.openapi.fileEditor.FileEditorManagerListener;
 import com.intellij.openapi.project.Project;
 import com.intellij.openapi.roots.GeneratedSourcesFilter;
 import com.intellij.openapi.roots.ModuleRootEvent;
@@ -88,7 +91,7 @@ public class GeneratedSourceFileChangeTrackerImpl extends GeneratedSourceFileCha
         }
       }
     });
-    connection.subscribe(FileEditorManagerListener.FILE_EDITOR_MANAGER, new FileEditorManagerAdapter() {
+    connection.subscribe(FileEditorManagerListener.FILE_EDITOR_MANAGER, new FileEditorManagerListener() {
       @Override
       public void fileClosed(@NotNull FileEditorManager source, @NotNull VirtualFile file) {
         myEditedGeneratedFiles.remove(file);
index 76c0128056943d7466ab0f4d53cf6b4f3793b613..4d637744a397de937cb2528026deb913d3b4204e 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2014 JetBrains s.r.o.
+ * Copyright 2000-2016 JetBrains s.r.o.
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -59,8 +59,7 @@ public class AddAllOpenFilesToFavorites extends AnAction implements DumbAware {
     ArrayList<PsiFile> result = new ArrayList<>();
     final FileEditorManager editorManager = FileEditorManager.getInstance(project);
     final PsiManager psiManager = PsiManager.getInstance(project);
-    final VirtualFile[] openFiles = editorManager.getOpenFiles();
-    for (VirtualFile openFile : openFiles) {
+    for (VirtualFile openFile : editorManager.getOpenFiles()) {
       if (!openFile.isValid()) continue;
       final PsiFile psiFile = psiManager.findFile(openFile);
       if (psiFile != null) {
index 0a105fef0e5d94cc93b5fa67e5c16057ae33b6d7..37d5539a493dd558ad62af5c68ca52aa1351fc5f 100644 (file)
@@ -25,7 +25,6 @@ import com.intellij.openapi.actionSystem.*;
 import com.intellij.openapi.actionSystem.ex.AnActionListener;
 import com.intellij.openapi.application.ApplicationManager;
 import com.intellij.openapi.fileEditor.FileEditorManager;
-import com.intellij.openapi.fileEditor.FileEditorManagerEvent;
 import com.intellij.openapi.fileEditor.FileEditorManagerListener;
 import com.intellij.openapi.project.Project;
 import com.intellij.openapi.roots.ModuleRootEvent;
@@ -397,10 +396,4 @@ public class NavBarListener extends WolfTheProblemSolver.ProblemListener
 
   @Override
   public void childRemoved(@NotNull PsiTreeChangeEvent event) {}
-
-  @Override
-  public void fileClosed(@NotNull FileEditorManager source, @NotNull VirtualFile file) {}
-
-  @Override
-  public void selectionChanged(@NotNull FileEditorManagerEvent event) {}
 }
index cfd01a2182c91ad49b1c0eef3a70124f6caf7266..56195c1366fe823c02447ae949e90c76cdab06e7 100644 (file)
@@ -31,7 +31,6 @@ import com.intellij.openapi.components.State;
 import com.intellij.openapi.components.Storage;
 import com.intellij.openapi.fileEditor.FileDocumentManager;
 import com.intellij.openapi.fileEditor.FileEditorManager;
-import com.intellij.openapi.fileEditor.FileEditorManagerAdapter;
 import com.intellij.openapi.fileEditor.FileEditorManagerListener;
 import com.intellij.openapi.fileEditor.impl.EditorTabTitleProvider;
 import com.intellij.openapi.fileEditor.impl.FileEditorManagerImpl;
@@ -102,7 +101,7 @@ public class ScratchFileServiceImpl extends ScratchFileService implements Persis
   }
 
   private void initFileOpenedListener(MessageBus messageBus) {
-    final FileEditorManagerAdapter editorListener = new FileEditorManagerAdapter() {
+    final FileEditorManagerListener editorListener = new FileEditorManagerListener() {
       @Override
       public void fileOpened(@NotNull FileEditorManager source, @NotNull VirtualFile file) {
         if (!isEditable(file)) return;
index 95b48bf6bc3406ac7167e8baeb6606dce9d58baf..d647990dc32f1eeacd509ee93f4d101d3ef8c2a7 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2015 JetBrains s.r.o.
+ * Copyright 2000-2016 JetBrains s.r.o.
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -16,7 +16,6 @@
 package com.intellij.ide.todo;
 
 import com.intellij.openapi.fileEditor.FileEditorManager;
-import com.intellij.openapi.fileEditor.FileEditorManagerAdapter;
 import com.intellij.openapi.fileEditor.FileEditorManagerEvent;
 import com.intellij.openapi.fileEditor.FileEditorManagerListener;
 import com.intellij.openapi.project.DumbService;
@@ -37,7 +36,7 @@ abstract class CurrentFileTodosPanel extends TodoPanel {
     VirtualFile[] files = FileEditorManager.getInstance(project).getSelectedFiles();
     setFile(files.length == 0 ? null : PsiManager.getInstance(myProject).findFile(files[0]));
     // It's important to remove this listener. It prevents invocation of setFile method after the tree builder is disposed
-    project.getMessageBus().connect(this).subscribe(FileEditorManagerListener.FILE_EDITOR_MANAGER, new FileEditorManagerAdapter() {
+    project.getMessageBus().connect(this).subscribe(FileEditorManagerListener.FILE_EDITOR_MANAGER, new FileEditorManagerListener() {
       @Override
       public void selectionChanged(@NotNull FileEditorManagerEvent e) {
         VirtualFile file = e.getNewFile();
index 9b8edfbcea9e10e929913d27648ef64502af4a19..e1489ee51832517546449f06be3d38401caa073f 100644 (file)
@@ -354,7 +354,8 @@ public class FileStructurePopup implements Disposable, TreeActionsOwner {
     }
 
     IdeFocusManager.getInstance(myProject).requestFocus(myTree, true);
-    SwingUtilities.windowForComponent(myPopup.getContent()).addWindowFocusListener(new WindowFocusListener() {
+    Window window = SwingUtilities.windowForComponent(myPopup.getContent());
+    WindowFocusListener windowFocusListener = new WindowFocusListener() {
       @Override
       public void windowGainedFocus(WindowEvent e) {
       }
@@ -363,7 +364,10 @@ public class FileStructurePopup implements Disposable, TreeActionsOwner {
       public void windowLostFocus(WindowEvent e) {
         myPopup.cancel();
       }
-    });
+    };
+    window.addWindowFocusListener(windowFocusListener);
+    Disposer.register(myPopup, () -> window.removeWindowFocusListener(windowFocusListener));
+
     ApplicationManager.getApplication().executeOnPooledThread(() -> {
       ApplicationManager.getApplication().runReadAction(() -> myFilteringStructure.rebuild());
 
index deda13b4c821d5e6c2c1df90fe8631d3b41595f2..6990141bad7032c42a5248d33be3a02e15b1ffbd 100644 (file)
@@ -65,7 +65,6 @@ class ManageProjectTemplatesDialog extends DialogWrapper {
       }
     });
     myTemplatesList.setEmptyText("No user-defined project templates");
-    myTemplatesList.setPreferredSize(JBUI.size(300, 100));
     myTemplatesList.setCellRenderer(new ColoredListCellRenderer() {
       @Override
       protected void customizeCellRenderer(@NotNull JList list, Object value, int index, boolean selected, boolean hasFocus) {
@@ -81,7 +80,9 @@ class ManageProjectTemplatesDialog extends DialogWrapper {
     });
 
     myPanel = new JPanel(new BorderLayout(0, 5));
-    myPanel.add(ToolbarDecorator.createDecorator(myTemplatesList).disableUpDownActions().createPanel());
+    JPanel panel = ToolbarDecorator.createDecorator(myTemplatesList).disableUpDownActions().createPanel();
+    panel.setPreferredSize(JBUI.size(300, 200));
+    myPanel.add(panel);
 
     myDescriptionPane = new JTextPane();
     myDescriptionPane.setPreferredSize(JBUI.size(300, 50));
index 412e6bb0603bc5e0f14da165c67d437518afd55e..ae0c2aa9951f8af75a684b04aedd1d0d9113a519 100644 (file)
@@ -28,6 +28,8 @@ import org.jetbrains.annotations.Nullable;
 
 public class CodeStyleSchemeImpl extends ExternalizableSchemeAdapter implements CodeStyleScheme, SerializableScheme {
   private static final Logger LOG = Logger.getInstance(CodeStyleSchemeImpl.class);
+  
+  static final String DEFAULT_SCHEME_NAME = "Default";
 
   private SchemeDataHolder<? super CodeStyleSchemeImpl> myDataHolder;
   private String myParentSchemeName;
@@ -37,7 +39,7 @@ public class CodeStyleSchemeImpl extends ExternalizableSchemeAdapter implements
   CodeStyleSchemeImpl(@NotNull String name, String parentSchemeName, @NotNull SchemeDataHolder<? super CodeStyleSchemeImpl> dataHolder) {
     setName(name);
     myDataHolder = dataHolder;
-    myIsDefault = false;
+    myIsDefault = DEFAULT_SCHEME_NAME.equals(name);
     myParentSchemeName = parentSchemeName;
   }
 
index 124b9a3f4bf81127640346b5c1a092ca552e7cd8..9fac75081dc1d298814ebba1a7b698bf01636253 100644 (file)
@@ -29,7 +29,6 @@ import org.jetbrains.annotations.Nullable;
 import java.util.function.Function;
 
 public abstract class CodeStyleSchemesImpl extends CodeStyleSchemes {
-  protected static final String DEFAULT_SCHEME_NAME = "Default";
 
   @NonNls
   static final String CODE_STYLES_DIR_PATH = "codestyles";
@@ -119,9 +118,9 @@ public abstract class CodeStyleSchemesImpl extends CodeStyleSchemes {
 
   @Override
   public CodeStyleScheme getDefaultScheme() {
-    CodeStyleScheme defaultScheme = mySchemeManager.findSchemeByName(DEFAULT_SCHEME_NAME);
+    CodeStyleScheme defaultScheme = mySchemeManager.findSchemeByName(CodeStyleSchemeImpl.DEFAULT_SCHEME_NAME);
     if (defaultScheme == null) {
-      defaultScheme = new CodeStyleSchemeImpl(DEFAULT_SCHEME_NAME, true, null);
+      defaultScheme = new CodeStyleSchemeImpl(CodeStyleSchemeImpl.DEFAULT_SCHEME_NAME, true, null);
       addScheme(defaultScheme);
     }
     return defaultScheme;
index 6574a24cf651c94a8a0634a4a19c880f9d8d0099..978049dc954849258922b77dee04564b4764bacf 100644 (file)
@@ -39,7 +39,7 @@ import org.jetbrains.annotations.Nullable;
   additionalExportFile = CodeStyleSchemesImpl.CODE_STYLES_DIR_PATH
 )
 class PersistableCodeStyleSchemes extends CodeStyleSchemesImpl implements PersistentStateComponent<Element> {
-  public String CURRENT_SCHEME_NAME = DEFAULT_SCHEME_NAME;
+  public String CURRENT_SCHEME_NAME = CodeStyleSchemeImpl.DEFAULT_SCHEME_NAME;
 
   public PersistableCodeStyleSchemes(@NotNull SchemeManagerFactory schemeManagerFactory) {
     super(schemeManagerFactory);
@@ -54,7 +54,7 @@ class PersistableCodeStyleSchemes extends CodeStyleSchemesImpl implements Persis
       @Override
       public boolean accepts(@NotNull Accessor accessor, @NotNull Object bean) {
         if ("CURRENT_SCHEME_NAME".equals(accessor.getName())) {
-          return !DEFAULT_SCHEME_NAME.equals(accessor.read(bean));
+          return !CodeStyleSchemeImpl.DEFAULT_SCHEME_NAME.equals(accessor.read(bean));
         }
         else {
           return accessor.getValueClass().equals(String.class);
index 24a016633df99eda82d7493c687f2ba3d3007f11..7e28661d2978d44d8da57b73cd8266dd8fc3a22b 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2015 JetBrains s.r.o.
+ * Copyright 2000-2016 JetBrains s.r.o.
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -228,6 +228,7 @@ public abstract class BaseRefactoringProcessor implements Runnable {
 
   protected void previewRefactoring(@NotNull UsageInfo[] usages) {
     if (ApplicationManager.getApplication().isUnitTestMode()) {
+      ensureElementsWritable(usages, createUsageViewDescriptor(usages));
       execute(usages);
       return;
     }
diff --git a/platform/lang-impl/src/com/intellij/ui/ManageSchemesComboAction.java b/platform/lang-impl/src/com/intellij/ui/ManageSchemesComboAction.java
new file mode 100644 (file)
index 0000000..2b02d72
--- /dev/null
@@ -0,0 +1,61 @@
+/*
+ * Copyright 2000-2016 JetBrains s.r.o.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.intellij.ui;
+
+import com.intellij.icons.AllIcons;
+import com.intellij.openapi.actionSystem.AnAction;
+import com.intellij.openapi.actionSystem.AnActionEvent;
+import com.intellij.openapi.actionSystem.DefaultActionGroup;
+import com.intellij.openapi.actionSystem.Presentation;
+import com.intellij.openapi.actionSystem.ex.ComboBoxAction;
+import com.intellij.application.options.DefaultSchemeActions;
+import org.jetbrains.annotations.NotNull;
+
+import javax.swing.*;
+import java.util.Collection;
+
+public class ManageSchemesComboAction extends ComboBoxAction {
+  
+  private Collection<AnAction> myActions;
+
+  public ManageSchemesComboAction(@NotNull DefaultSchemeActions schemeActions) {
+    myActions = schemeActions.getActions();
+  }
+
+  @NotNull
+  @Override
+  protected DefaultActionGroup createPopupActionGroup(JComponent button) {
+    DefaultActionGroup group = new DefaultActionGroup();
+    for(AnAction action : myActions) {
+      group.add(action);
+    }
+    return group;
+  }
+  
+  @Override
+  public void update(AnActionEvent e) {
+    for(AnAction action : myActions) {
+      action.update(e);
+    }
+  }
+  
+  public JButton createCombo() {
+    Presentation presentation = getTemplatePresentation();
+    presentation.setIcon(AllIcons.General.GearPlain);
+    return createComboBoxButton(presentation);
+  }
+  
+}
index 085ad743040433b650def0f0a021f068acfc560f..23eebd7ae19cdd7c1b12e89966a120c5b3e289d0 100644 (file)
  */
 package com.intellij.openapi.wm.impl;
 
-import com.intellij.ide.ui.LafManager;
 import com.intellij.openapi.actionSystem.ActionManager;
 import com.intellij.openapi.components.impl.ComponentManagerImpl;
-import com.intellij.openapi.fileEditor.FileEditorManager;
 import com.intellij.openapi.wm.ToolWindowManager;
 import com.intellij.openapi.wm.ex.ToolWindowManagerEx;
 import com.intellij.openapi.wm.ex.WindowManagerEx;
@@ -36,8 +34,7 @@ public abstract class ToolWindowManagerTestCase extends LightPlatformCodeInsight
   @Override
   public void setUp() throws Exception {
     super.setUp();
-    myManager = new ToolWindowManagerImpl(getProject(), WindowManagerEx.getInstanceEx(), FileEditorManager.getInstance(getProject()), ActionManager
-      .getInstance(), LafManager.getInstance());
+    myManager = new ToolWindowManagerImpl(getProject(), WindowManagerEx.getInstanceEx(), ActionManager.getInstance());
     myOldManager = (ToolWindowManagerEx)((ComponentManagerImpl)getProject()).registerComponentInstance(ToolWindowManager.class, myManager);
     myManager.projectOpened();
   }
index 41628c0622dfb0865588613a0699c23618f980e8..67f88d9ad1e51d10f380513af613997e34a1be31 100644 (file)
@@ -15,6 +15,7 @@
  */
 package com.intellij.ide;
 
+import com.intellij.ide.ui.UINumericRange;
 import com.intellij.ide.util.PropertiesComponent;
 import com.intellij.openapi.components.PersistentStateComponent;
 import com.intellij.openapi.components.ServiceManager;
@@ -179,18 +180,18 @@ public class GeneralSettings implements PersistentStateComponent<GeneralSettings
 
   /**
    * @return timeout in seconds after which IDEA saves all files if there was no user activity.
-   * The method always return non positive (more then zero) value.
+   * The method always return positive (more then zero) value.
    */
   public int getInactiveTimeout(){
-    return myInactiveTimeout;
+    return UINumericRange.SYSTEM_SETTINGS_SAVE_FILES_AFTER_IDLE_SEC.fit(myInactiveTimeout);
   }
 
   public void setInactiveTimeout(int inactiveTimeoutSeconds) {
     int oldInactiveTimeout = myInactiveTimeout;
 
-    myInactiveTimeout = inactiveTimeoutSeconds;
+    myInactiveTimeout = UINumericRange.SYSTEM_SETTINGS_SAVE_FILES_AFTER_IDLE_SEC.fit(inactiveTimeoutSeconds);
     myPropertyChangeSupport.firePropertyChange(
-        PROP_INACTIVE_TIMEOUT, Integer.valueOf(oldInactiveTimeout), Integer.valueOf(inactiveTimeoutSeconds)
+        PROP_INACTIVE_TIMEOUT, Integer.valueOf(oldInactiveTimeout), Integer.valueOf(myInactiveTimeout)
     );
   }
 
index 61d9af0fc8e8bbe5dd955f222a0a065783960d54..fa6de37bde378f38e0050127d6a1167ca1ea5a2e 100644 (file)
@@ -37,7 +37,8 @@ public abstract class EditorWriteActionHandler extends EditorActionHandler {
 
   @Override
   public void doExecute(final Editor editor, @Nullable final Caret caret, final DataContext dataContext) {
-    if (editor.isViewer() || !EditorModificationUtil.requestWriting(editor)) return;
+    if (editor.isViewer()) return;
+    if (!ApplicationManager.getApplication().isWriteAccessAllowed() && !EditorModificationUtil.requestWriting(editor)) return;
 
     DocumentRunnable runnable = new DocumentRunnable(editor.getDocument(), editor.getProject()) {
       @Override
index 7e0f3ff441a8de66e3dada83ac7a476be4ee0738..1e4b5ef677af1e3a8974c7cd235ed73ca2fb22b9 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2014 JetBrains s.r.o.
+ * Copyright 2000-2016 JetBrains s.r.o.
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
  */
 package com.intellij.openapi.fileEditor;
 
-import com.intellij.openapi.vfs.VirtualFile;
-import org.jetbrains.annotations.NotNull;
-
-public abstract class FileEditorManagerAdapter implements FileEditorManagerListener{
-  @Override
-  public void fileOpened(@NotNull FileEditorManager source, @NotNull VirtualFile file) {}
-
-  @Override
-  public void fileClosed(@NotNull FileEditorManager source, @NotNull VirtualFile file) {}
-
-  @Override
-  public void selectionChanged(@NotNull FileEditorManagerEvent event) {}
+/**
+ * @deprecated Please use FileEditorManagerListener
+ */
+@Deprecated
+public abstract class FileEditorManagerAdapter implements FileEditorManagerListener {
 }
index 8bd5ce571358fd9ab5af7027e1d5c324a1152ea9..37913eb64f7d206b2e1b66922a1a701ef40429c0 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2014 JetBrains s.r.o.
+ * Copyright 2000-2016 JetBrains s.r.o.
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -25,11 +25,14 @@ public interface FileEditorManagerListener extends EventListener{
   Topic<FileEditorManagerListener> FILE_EDITOR_MANAGER =
     new Topic<>("file editor events", FileEditorManagerListener.class, Topic.BroadcastDirection.TO_PARENT);
 
-  void fileOpened(@NotNull FileEditorManager source, @NotNull VirtualFile file);
+  default void fileOpened(@NotNull FileEditorManager source, @NotNull VirtualFile file) {
+  }
 
-  void fileClosed(@NotNull FileEditorManager source, @NotNull VirtualFile file);
+  default void fileClosed(@NotNull FileEditorManager source, @NotNull VirtualFile file) {
+  }
 
-  void selectionChanged(@NotNull FileEditorManagerEvent event);
+  default void selectionChanged(@NotNull FileEditorManagerEvent event) {
+  }
 
   interface Before extends EventListener {
     Topic<Before> FILE_EDITOR_MANAGER =
index 4a733e83961448968bd35a659e63d0ef8af6c99c..6913105345d626202d2e39b6999863d9b1c841d4 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2009 JetBrains s.r.o.
+ * Copyright 2000-2016 JetBrains s.r.o.
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -45,7 +45,7 @@ public abstract class CompositeSettingsEditor<Settings> extends SettingsEditor<S
 
   public abstract CompositeSettingsBuilder<Settings> getBuilder();
 
-  public void resetEditorFrom(Settings settings) {
+  public void resetEditorFrom(@NotNull Settings settings) {
     for (final SettingsEditor<Settings> myEditor : myEditors) {
       try {
         myEditor.resetEditorFrom(settings);
@@ -56,7 +56,7 @@ public abstract class CompositeSettingsEditor<Settings> extends SettingsEditor<S
     }
   }
 
-  public void applyEditorTo(Settings settings) throws ConfigurationException {
+  public void applyEditorTo(@NotNull Settings settings) throws ConfigurationException {
     for (final SettingsEditor<Settings> myEditor : myEditors) {
       try {
         myEditor.applyTo(settings);
index 9db36a17396daa25b39398ea33c2646d2c386288..f66bc6881dc073405c2d80b392a408af6ffe5586 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2014 JetBrains s.r.o.
+ * Copyright 2000-2016 JetBrains s.r.o.
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -42,8 +42,8 @@ public class SettingsEditorGroup<T> extends SettingsEditor<T> {
     return myEditors;
   }
 
-  public void resetEditorFrom(T t) {}
-  public void applyEditorTo(T t) throws ConfigurationException {}
+  public void resetEditorFrom(@NotNull T t) {}
+  public void applyEditorTo(@NotNull T t) throws ConfigurationException {}
 
   @NotNull
   public JComponent createEditor() {
index 003a4408fe7e04dc611f7d6befbb4b1fb45ee1ad..d3e74639467110097cd6da5e52b941fd885134c2 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2009 JetBrains s.r.o.
+ * Copyright 2000-2016 JetBrains s.r.o.
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -42,11 +42,11 @@ public class SettingsEditorWrapper <Src, Dst> extends SettingsEditor<Src> {
     myWrapped.addSettingsEditorListener(myListener);
   }
 
-  public void resetEditorFrom(Src src) {
+  public void resetEditorFrom(@NotNull Src src) {
     myWrapped.resetFrom(mySrcToDstConvertor.convert(src));
   }
 
-  public void applyEditorTo(Src src) throws ConfigurationException {
+  public void applyEditorTo(@NotNull Src src) throws ConfigurationException {
     myWrapped.applyTo(mySrcToDstConvertor.convert(src));
   }
 
index edb4e6591cf3ee7bd3767044b0b9620289353a2f..03ee6a9b2b250f6cb4c3c2aa11204a96131147d5 100644 (file)
@@ -951,7 +951,7 @@ public abstract class DialogWrapper {
     if (rootPane == null) return;
     RepaintManager.currentManager(rootPane).removeInvalidComponent(rootPane);
     unregisterKeyboardActions(rootPane);
-    Disposer.clearOwnFields(rootPane, field -> field.getDeclaringClass() != Component.class);
+    Disposer.clearOwnFields(rootPane, field -> !field.getDeclaringClass().getName().startsWith("java.awt."));
   }
 
   private static void unregisterKeyboardActions(@Nullable JRootPane rootPane) {
@@ -971,6 +971,19 @@ public abstract class DialogWrapper {
     }
   }
 
+  public static void cleanupWindowListeners(@Nullable Window window) {
+    if (window == null) return;
+    for (WindowListener listener : window.getWindowListeners()) {
+      if (listener.getClass().getName().startsWith("com.intellij.")) {
+        LOG.warn("Stale listener: " + listener);
+      }
+      else {
+        LOG.info("Stale listener: " + listener);
+      }
+      window.removeWindowListener(listener);
+    }
+  }
+
 
   /**
    * This method is invoked by default implementation of "Cancel" action. It just closes dialog
index 821b5cd38721aa4bbde887cd16d9f7d49c7facc3..0892387137ae8d3ef186f9eb1514a478d544f47a 100644 (file)
@@ -28,6 +28,11 @@ public interface TestDialog {
       return 0;
     }
   };
+  TestDialog NO = new TestDialog() {
+    public int show(String message) {
+      return Messages.NO;
+    }
+  };
 
   int show(String message);
 }
index 6ec2efd919a0311525e44919f3bb9da82f13f5ba..8a229f9b4a18b05d50572669ae3d7914929afd5c 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2009 JetBrains s.r.o.
+ * Copyright 2000-2016 JetBrains s.r.o.
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -22,7 +22,6 @@ import com.intellij.openapi.actionSystem.AnActionEvent;
 import com.intellij.openapi.actionSystem.ToggleAction;
 import com.intellij.openapi.application.ModalityState;
 import com.intellij.openapi.fileEditor.FileEditor;
-import com.intellij.openapi.fileEditor.FileEditorManagerAdapter;
 import com.intellij.openapi.fileEditor.FileEditorManagerEvent;
 import com.intellij.openapi.fileEditor.FileEditorManagerListener;
 import com.intellij.openapi.project.DumbAware;
@@ -75,7 +74,7 @@ public abstract class AutoScrollFromSourceHandler implements Disposable {
 
   public void install() {
     final MessageBusConnection connection = myProject.getMessageBus().connect(myProject);
-    connection.subscribe(FileEditorManagerListener.FILE_EDITOR_MANAGER, new FileEditorManagerAdapter() {
+    connection.subscribe(FileEditorManagerListener.FILE_EDITOR_MANAGER, new FileEditorManagerListener() {
       @Override
       public void selectionChanged(@NotNull FileEditorManagerEvent event) {
         final FileEditor editor = event.getNewEditor();